@vkontakte/videoplayer-core 2.0.129-dev.505377de.0 → 2.0.129-dev.6ff96833.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 +22 -22
- package/es2015.esm.js +22 -22
- package/es2018.cjs.js +26 -26
- package/es2018.esm.js +26 -26
- package/esnext.cjs.js +27 -27
- package/esnext.esm.js +25 -25
- package/evergreen.esm.js +24 -24
- package/package.json +2 -2
- package/types/providers/DashProvider/baseDashProvider.d.ts +1 -1
- package/types/providers/DashProvider/lib/buffer.d.ts +1 -1
- package/types/providers/DashProvider/lib/player.d.ts +3 -0
- package/types/providers/utils/HTMLVideoElement/observable.d.ts +1 -0
- package/types/providers/utils/StallsManager.d.ts +2 -1
- package/types/utils/tuningConfig.d.ts +6 -0
package/es2015.esm.js
CHANGED
|
@@ -1,52 +1,52 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @vkontakte/videoplayer-core v2.0.129-dev.
|
|
3
|
-
* Mon,
|
|
2
|
+
* @vkontakte/videoplayer-core v2.0.129-dev.6ff96833.0
|
|
3
|
+
* Mon, 24 Mar 2025 04:44:38 GMT
|
|
4
4
|
* https://st.mycdn.me/static/vkontakte-videoplayer/2-0-129/doc/
|
|
5
5
|
*/
|
|
6
|
-
var eI=Object.create;var ro=Object.defineProperty,tI=Object.defineProperties,rI=Object.getOwnPropertyDescriptor,iI=Object.getOwnPropertyDescriptors,aI=Object.getOwnPropertyNames,cs=Object.getOwnPropertySymbols,sI=Object.getPrototypeOf,io=Object.prototype.hasOwnProperty,pd=Object.prototype.propertyIsEnumerable;var nI=(a,e)=>(e=Symbol[a])?e:Symbol.for("Symbol."+a);var it=Math.pow,dd=(a,e,t)=>e in a?ro(a,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):a[e]=t,P=(a,e)=>{for(var t in e||(e={}))io.call(e,t)&&dd(a,t,e[t]);if(cs)for(var t of cs(e))pd.call(e,t)&&dd(a,t,e[t]);return a},$=(a,e)=>tI(a,iI(e));var hd=(a,e)=>{var t={};for(var r in a)io.call(a,r)&&e.indexOf(r)<0&&(t[r]=a[r]);if(a!=null&&cs)for(var r of cs(a))e.indexOf(r)<0&&pd.call(a,r)&&(t[r]=a[r]);return t};var f=(a,e)=>()=>(e||a((e={exports:{}}).exports,e),e.exports);var oI=(a,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of aI(e))!io.call(a,i)&&i!==t&&ro(a,i,{get:()=>e[i],enumerable:!(r=rI(e,i))||r.enumerable});return a};var _=(a,e,t)=>(t=a!=null?eI(sI(a)):{},oI(e||!a||!a.__esModule?ro(t,"default",{value:a,enumerable:!0}):t,a));var x=(a,e,t)=>new Promise((r,i)=>{var s=u=>{try{o(t.next(u))}catch(l){i(l)}},n=u=>{try{o(t.throw(u))}catch(l){i(l)}},o=u=>u.done?r(u.value):Promise.resolve(u.value).then(s,n);o((t=t.apply(a,e)).next())}),ds=function(a,e){this[0]=a,this[1]=e},oe=(a,e,t)=>{var r=(n,o,u,l)=>{try{var c=t[n](o),d=(o=c.value)instanceof ds,p=c.done;Promise.resolve(d?o[0]:o).then(h=>d?r(n==="return"?n:"next",o[1]?{done:h.done,value:h.value}:h,u,l):u({value:h,done:p})).catch(h=>r("throw",h,u,l))}catch(h){l(h)}},i=n=>s[n]=o=>new Promise((u,l)=>r(n,o,u,l)),s={};return t=t.apply(a,e),s[nI("asyncIterator")]=()=>s,i("next"),i("throw"),i("return"),s};var ne=f((no,fd)=>{"use strict";var bi=function(a){return a&&a.Math===Math&&a};fd.exports=bi(typeof globalThis=="object"&&globalThis)||bi(typeof window=="object"&&window)||bi(typeof self=="object"&&self)||bi(typeof global=="object"&&global)||bi(typeof no=="object"&&no)||function(){return this}()||Function("return this")()});var me=f((D0,bd)=>{"use strict";bd.exports=function(a){try{return!!a()}catch(e){return!0}}});var gi=f((V0,gd)=>{"use strict";var uI=me();gd.exports=!uI(function(){var a=function(){}.bind();return typeof a!="function"||a.hasOwnProperty("prototype")})});var oo=f((_0,Td)=>{"use strict";var lI=gi(),yd=Function.prototype,vd=yd.apply,Sd=yd.call;Td.exports=typeof Reflect=="object"&&Reflect.apply||(lI?Sd.bind(vd):function(){return Sd.apply(vd,arguments)})});var le=f((O0,xd)=>{"use strict";var Id=gi(),Ed=Function.prototype,uo=Ed.call,cI=Id&&Ed.bind.bind(uo,uo);xd.exports=Id?cI:function(a){return function(){return uo.apply(a,arguments)}}});var tr=f((B0,wd)=>{"use strict";var Pd=le(),dI=Pd({}.toString),pI=Pd("".slice);wd.exports=function(a){return pI(dI(a),8,-1)}});var lo=f((N0,Ad)=>{"use strict";var hI=tr(),mI=le();Ad.exports=function(a){if(hI(a)==="Function")return mI(a)}});var ae=f((F0,kd)=>{"use strict";var co=typeof document=="object"&&document.all;kd.exports=typeof co=="undefined"&&co!==void 0?function(a){return typeof a=="function"||a===co}:function(a){return typeof a=="function"}});var Ce=f((q0,Rd)=>{"use strict";var fI=me();Rd.exports=!fI(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var De=f((U0,Ld)=>{"use strict";var bI=gi(),ms=Function.prototype.call;Ld.exports=bI?ms.bind(ms):function(){return ms.apply(ms,arguments)}});var po=f(Cd=>{"use strict";var $d={}.propertyIsEnumerable,Md=Object.getOwnPropertyDescriptor,gI=Md&&!$d.call({1:2},1);Cd.f=gI?function(e){var t=Md(this,e);return!!t&&t.enumerable}:$d});var vi=f((j0,Dd)=>{"use strict";Dd.exports=function(a,e){return{enumerable:!(a&1),configurable:!(a&2),writable:!(a&4),value:e}}});var _d=f((Q0,Vd)=>{"use strict";var vI=le(),SI=me(),yI=tr(),ho=Object,TI=vI("".split);Vd.exports=SI(function(){return!ho("z").propertyIsEnumerable(0)})?function(a){return yI(a)==="String"?TI(a,""):ho(a)}:ho});var Rr=f((G0,Od)=>{"use strict";Od.exports=function(a){return a==null}});var $t=f((W0,Bd)=>{"use strict";var II=Rr(),EI=TypeError;Bd.exports=function(a){if(II(a))throw new EI("Can't call method on "+a);return a}});var rr=f((Y0,Nd)=>{"use strict";var xI=_d(),PI=$t();Nd.exports=function(a){return xI(PI(a))}});var Ve=f((z0,Fd)=>{"use strict";var wI=ae();Fd.exports=function(a){return typeof a=="object"?a!==null:wI(a)}});var Lr=f((K0,qd)=>{"use strict";qd.exports={}});var ht=f((X0,Hd)=>{"use strict";var mo=Lr(),fo=ne(),AI=ae(),Ud=function(a){return AI(a)?a:void 0};Hd.exports=function(a,e){return arguments.length<2?Ud(mo[a])||Ud(fo[a]):mo[a]&&mo[a][e]||fo[a]&&fo[a][e]}});var Si=f((J0,jd)=>{"use strict";var kI=le();jd.exports=kI({}.isPrototypeOf)});var ir=f((Z0,Wd)=>{"use strict";var RI=ne(),Qd=RI.navigator,Gd=Qd&&Qd.userAgent;Wd.exports=Gd?String(Gd):""});var go=f((eV,Zd)=>{"use strict";var Jd=ne(),bo=ir(),Yd=Jd.process,zd=Jd.Deno,Kd=Yd&&Yd.versions||zd&&zd.version,Xd=Kd&&Kd.v8,Ye,fs;Xd&&(Ye=Xd.split("."),fs=Ye[0]>0&&Ye[0]<4?1:+(Ye[0]+Ye[1]));!fs&&bo&&(Ye=bo.match(/Edge\/(\d+)/),(!Ye||Ye[1]>=74)&&(Ye=bo.match(/Chrome\/(\d+)/),Ye&&(fs=+Ye[1])));Zd.exports=fs});var vo=f((tV,tp)=>{"use strict";var ep=go(),LI=me(),$I=ne(),MI=$I.String;tp.exports=!!Object.getOwnPropertySymbols&&!LI(function(){var a=Symbol("symbol detection");return!MI(a)||!(Object(a)instanceof Symbol)||!Symbol.sham&&ep&&ep<41})});var So=f((rV,rp)=>{"use strict";var CI=vo();rp.exports=CI&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var yo=f((iV,ip)=>{"use strict";var DI=ht(),VI=ae(),_I=Si(),OI=So(),BI=Object;ip.exports=OI?function(a){return typeof a=="symbol"}:function(a){var e=DI("Symbol");return VI(e)&&_I(e.prototype,BI(a))}});var yi=f((aV,ap)=>{"use strict";var NI=String;ap.exports=function(a){try{return NI(a)}catch(e){return"Object"}}});var at=f((sV,sp)=>{"use strict";var FI=ae(),qI=yi(),UI=TypeError;sp.exports=function(a){if(FI(a))return a;throw new UI(qI(a)+" is not a function")}});var Ti=f((nV,np)=>{"use strict";var HI=at(),jI=Rr();np.exports=function(a,e){var t=a[e];return jI(t)?void 0:HI(t)}});var up=f((oV,op)=>{"use strict";var To=De(),Io=ae(),Eo=Ve(),QI=TypeError;op.exports=function(a,e){var t,r;if(e==="string"&&Io(t=a.toString)&&!Eo(r=To(t,a))||Io(t=a.valueOf)&&!Eo(r=To(t,a))||e!=="string"&&Io(t=a.toString)&&!Eo(r=To(t,a)))return r;throw new QI("Can't convert object to primitive value")}});var ze=f((uV,lp)=>{"use strict";lp.exports=!0});var pp=f((lV,dp)=>{"use strict";var cp=ne(),GI=Object.defineProperty;dp.exports=function(a,e){try{GI(cp,a,{value:e,configurable:!0,writable:!0})}catch(t){cp[a]=e}return e}});var Ii=f((cV,fp)=>{"use strict";var WI=ze(),YI=ne(),zI=pp(),hp="__core-js_shared__",mp=fp.exports=YI[hp]||zI(hp,{});(mp.versions||(mp.versions=[])).push({version:"3.38.0",mode:WI?"pure":"global",copyright:"\xA9 2014-2024 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.38.0/LICENSE",source:"https://github.com/zloirock/core-js"})});var xo=f((dV,gp)=>{"use strict";var bp=Ii();gp.exports=function(a,e){return bp[a]||(bp[a]=e||{})}});var $r=f((pV,vp)=>{"use strict";var KI=$t(),XI=Object;vp.exports=function(a){return XI(KI(a))}});var Ke=f((hV,Sp)=>{"use strict";var JI=le(),ZI=$r(),eE=JI({}.hasOwnProperty);Sp.exports=Object.hasOwn||function(e,t){return eE(ZI(e),t)}});var Po=f((mV,yp)=>{"use strict";var tE=le(),rE=0,iE=Math.random(),aE=tE(1 .toString);yp.exports=function(a){return"Symbol("+(a===void 0?"":a)+")_"+aE(++rE+iE,36)}});var fe=f((fV,Ip)=>{"use strict";var sE=ne(),nE=xo(),Tp=Ke(),oE=Po(),uE=vo(),lE=So(),Mr=sE.Symbol,wo=nE("wks"),cE=lE?Mr.for||Mr:Mr&&Mr.withoutSetter||oE;Ip.exports=function(a){return Tp(wo,a)||(wo[a]=uE&&Tp(Mr,a)?Mr[a]:cE("Symbol."+a)),wo[a]}});var wp=f((bV,Pp)=>{"use strict";var dE=De(),Ep=Ve(),xp=yo(),pE=Ti(),hE=up(),mE=fe(),fE=TypeError,bE=mE("toPrimitive");Pp.exports=function(a,e){if(!Ep(a)||xp(a))return a;var t=pE(a,bE),r;if(t){if(e===void 0&&(e="default"),r=dE(t,a,e),!Ep(r)||xp(r))return r;throw new fE("Can't convert object to primitive value")}return e===void 0&&(e="number"),hE(a,e)}});var Ao=f((gV,Ap)=>{"use strict";var gE=wp(),vE=yo();Ap.exports=function(a){var e=gE(a,"string");return vE(e)?e:e+""}});var bs=f((vV,Rp)=>{"use strict";var SE=ne(),kp=Ve(),ko=SE.document,yE=kp(ko)&&kp(ko.createElement);Rp.exports=function(a){return yE?ko.createElement(a):{}}});var Ro=f((SV,Lp)=>{"use strict";var TE=Ce(),IE=me(),EE=bs();Lp.exports=!TE&&!IE(function(){return Object.defineProperty(EE("div"),"a",{get:function(){return 7}}).a!==7})});var Cp=f(Mp=>{"use strict";var xE=Ce(),PE=De(),wE=po(),AE=vi(),kE=rr(),RE=Ao(),LE=Ke(),$E=Ro(),$p=Object.getOwnPropertyDescriptor;Mp.f=xE?$p:function(e,t){if(e=kE(e),t=RE(t),$E)try{return $p(e,t)}catch(r){}if(LE(e,t))return AE(!PE(wE.f,e,t),e[t])}});var Lo=f((TV,Dp)=>{"use strict";var ME=me(),CE=ae(),DE=/#|\.prototype\./,Ei=function(a,e){var t=_E[VE(a)];return t===BE?!0:t===OE?!1:CE(e)?ME(e):!!e},VE=Ei.normalize=function(a){return String(a).replace(DE,".").toLowerCase()},_E=Ei.data={},OE=Ei.NATIVE="N",BE=Ei.POLYFILL="P";Dp.exports=Ei});var Cr=f((IV,_p)=>{"use strict";var Vp=lo(),NE=at(),FE=gi(),qE=Vp(Vp.bind);_p.exports=function(a,e){return NE(a),e===void 0?a:FE?qE(a,e):function(){return a.apply(e,arguments)}}});var $o=f((EV,Op)=>{"use strict";var UE=Ce(),HE=me();Op.exports=UE&&HE(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var st=f((xV,Bp)=>{"use strict";var jE=Ve(),QE=String,GE=TypeError;Bp.exports=function(a){if(jE(a))return a;throw new GE(QE(a)+" is not an object")}});var ar=f(Fp=>{"use strict";var WE=Ce(),YE=Ro(),zE=$o(),gs=st(),Np=Ao(),KE=TypeError,Mo=Object.defineProperty,XE=Object.getOwnPropertyDescriptor,Co="enumerable",Do="configurable",Vo="writable";Fp.f=WE?zE?function(e,t,r){if(gs(e),t=Np(t),gs(r),typeof e=="function"&&t==="prototype"&&"value"in r&&Vo in r&&!r[Vo]){var i=XE(e,t);i&&i[Vo]&&(e[t]=r.value,r={configurable:Do in r?r[Do]:i[Do],enumerable:Co in r?r[Co]:i[Co],writable:!1})}return Mo(e,t,r)}:Mo:function(e,t,r){if(gs(e),t=Np(t),gs(r),YE)try{return Mo(e,t,r)}catch(i){}if("get"in r||"set"in r)throw new KE("Accessors not supported");return"value"in r&&(e[t]=r.value),e}});var Dr=f((wV,qp)=>{"use strict";var JE=Ce(),ZE=ar(),ex=vi();qp.exports=JE?function(a,e,t){return ZE.f(a,e,ex(1,t))}:function(a,e,t){return a[e]=t,a}});var ue=f((AV,Hp)=>{"use strict";var xi=ne(),tx=oo(),rx=lo(),ix=ae(),ax=Cp().f,sx=Lo(),Vr=Lr(),nx=Cr(),_r=Dr(),Up=Ke();Ii();var ox=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 tx(a,this,arguments)};return e.prototype=a.prototype,e};Hp.exports=function(a,e){var t=a.target,r=a.global,i=a.stat,s=a.proto,n=r?xi:i?xi[t]:xi[t]&&xi[t].prototype,o=r?Vr:Vr[t]||_r(Vr,t,{})[t],u=o.prototype,l,c,d,p,h,m,b,g,v;for(p in e)l=sx(r?p:t+(i?".":"#")+p,a.forced),c=!l&&n&&Up(n,p),m=o[p],c&&(a.dontCallGetSet?(v=ax(n,p),b=v&&v.value):b=n[p]),h=c&&b?b:e[p],!(!l&&!s&&typeof m==typeof h)&&(a.bind&&c?g=nx(h,xi):a.wrap&&c?g=ox(h):s&&ix(h)?g=rx(h):g=h,(a.sham||h&&h.sham||m&&m.sham)&&_r(g,"sham",!0),_r(o,p,g),s&&(d=t+"Prototype",Up(Vr,d)||_r(Vr,d,{}),_r(Vr[d],p,h),a.real&&u&&(l||!u[p])&&_r(u,p,h)))}});var Qp=f((kV,jp)=>{"use strict";var ux=Math.ceil,lx=Math.floor;jp.exports=Math.trunc||function(e){var t=+e;return(t>0?lx:ux)(t)}});var Pi=f((RV,Gp)=>{"use strict";var cx=Qp();Gp.exports=function(a){var e=+a;return e!==e||e===0?0:cx(e)}});var Yp=f((LV,Wp)=>{"use strict";var dx=Pi(),px=Math.max,hx=Math.min;Wp.exports=function(a,e){var t=dx(a);return t<0?px(t+e,0):hx(t,e)}});var _o=f(($V,zp)=>{"use strict";var mx=Pi(),fx=Math.min;zp.exports=function(a){var e=mx(a);return e>0?fx(e,9007199254740991):0}});var Or=f((MV,Kp)=>{"use strict";var bx=_o();Kp.exports=function(a){return bx(a.length)}});var Oo=f((CV,Jp)=>{"use strict";var gx=rr(),vx=Yp(),Sx=Or(),Xp=function(a){return function(e,t,r){var i=gx(e),s=Sx(i);if(s===0)return!a&&-1;var n=vx(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}};Jp.exports={includes:Xp(!0),indexOf:Xp(!1)}});var wi=f((DV,Zp)=>{"use strict";Zp.exports=function(){}});var eh=f(()=>{"use strict";var yx=ue(),Tx=Oo().includes,Ix=me(),Ex=wi(),xx=Ix(function(){return!Array(1).includes()});yx({target:"Array",proto:!0,forced:xx},{includes:function(e){return Tx(this,e,arguments.length>1?arguments[1]:void 0)}});Ex("includes")});var Mt=f((OV,th)=>{"use strict";var Px=ht();th.exports=Px});var ih=f((BV,rh)=>{"use strict";eh();var wx=Mt();rh.exports=wx("Array","includes")});var sh=f((NV,ah)=>{"use strict";var Ax=ih();ah.exports=Ax});var Fe=f((FV,nh)=>{"use strict";var kx=sh();nh.exports=kx});var ys=f((JV,mh)=>{"use strict";var _x=xo(),Ox=Po(),hh=_x("keys");mh.exports=function(a){return hh[a]||(hh[a]=Ox(a))}});var bh=f((ZV,fh)=>{"use strict";var Bx=me();fh.exports=!Bx(function(){function a(){}return a.prototype.constructor=null,Object.getPrototypeOf(new a)!==a.prototype})});var Ts=f((e_,vh)=>{"use strict";var Nx=Ke(),Fx=ae(),qx=$r(),Ux=ys(),Hx=bh(),gh=Ux("IE_PROTO"),Fo=Object,jx=Fo.prototype;vh.exports=Hx?Fo.getPrototypeOf:function(a){var e=qx(a);if(Nx(e,gh))return e[gh];var t=e.constructor;return Fx(t)&&e instanceof t?t.prototype:e instanceof Fo?jx:null}});var Is=f((t_,Sh)=>{"use strict";Sh.exports={}});var Ih=f((r_,Th)=>{"use strict";var Qx=le(),qo=Ke(),Gx=rr(),Wx=Oo().indexOf,Yx=Is(),yh=Qx([].push);Th.exports=function(a,e){var t=Gx(a),r=0,i=[],s;for(s in t)!qo(Yx,s)&&qo(t,s)&&yh(i,s);for(;e.length>r;)qo(t,s=e[r++])&&(~Wx(i,s)||yh(i,s));return i}});var Uo=f((i_,Eh)=>{"use strict";Eh.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var Ho=f((a_,xh)=>{"use strict";var zx=Ih(),Kx=Uo();xh.exports=Object.keys||function(e){return zx(e,Kx)}});var jo=f((s_,Rh)=>{"use strict";var wh=Ce(),Xx=me(),Ah=le(),Jx=Ts(),Zx=Ho(),eP=rr(),tP=po().f,kh=Ah(tP),rP=Ah([].push),iP=wh&&Xx(function(){var a=Object.create(null);return a[2]=2,!kh(a,2)}),Ph=function(a){return function(e){for(var t=eP(e),r=Zx(t),i=iP&&Jx(t)===null,s=r.length,n=0,o=[],u;s>n;)u=r[n++],(!wh||(i?u in t:kh(t,u)))&&rP(o,a?[u,t[u]]:t[u]);return o}};Rh.exports={entries:Ph(!0),values:Ph(!1)}});var Lh=f(()=>{"use strict";var aP=ue(),sP=jo().entries;aP({target:"Object",stat:!0},{entries:function(e){return sP(e)}})});var Mh=f((u_,$h)=>{"use strict";Lh();var nP=Lr();$h.exports=nP.Object.entries});var Dh=f((l_,Ch)=>{"use strict";var oP=Mh();Ch.exports=oP});var Br=f((c_,Vh)=>{"use strict";var uP=Dh();Vh.exports=uP});var sr=f((d_,_h)=>{"use strict";_h.exports={}});var Nh=f((p_,Bh)=>{"use strict";var lP=ne(),cP=ae(),Oh=lP.WeakMap;Bh.exports=cP(Oh)&&/native code/.test(String(Oh))});var Yo=f((h_,Uh)=>{"use strict";var dP=Nh(),qh=ne(),pP=Ve(),hP=Dr(),Qo=Ke(),Go=Ii(),mP=ys(),fP=Is(),Fh="Object already initialized",Wo=qh.TypeError,bP=qh.WeakMap,Es,Ai,xs,gP=function(a){return xs(a)?Ai(a):Es(a,{})},vP=function(a){return function(e){var t;if(!pP(e)||(t=Ai(e)).type!==a)throw new Wo("Incompatible receiver, "+a+" required");return t}};dP||Go.state?(Xe=Go.state||(Go.state=new bP),Xe.get=Xe.get,Xe.has=Xe.has,Xe.set=Xe.set,Es=function(a,e){if(Xe.has(a))throw new Wo(Fh);return e.facade=a,Xe.set(a,e),e},Ai=function(a){return Xe.get(a)||{}},xs=function(a){return Xe.has(a)}):(nr=mP("state"),fP[nr]=!0,Es=function(a,e){if(Qo(a,nr))throw new Wo(Fh);return e.facade=a,hP(a,nr,e),e},Ai=function(a){return Qo(a,nr)?a[nr]:{}},xs=function(a){return Qo(a,nr)});var Xe,nr;Uh.exports={set:Es,get:Ai,has:xs,enforce:gP,getterFor:vP}});var Xo=f((m_,jh)=>{"use strict";var zo=Ce(),SP=Ke(),Hh=Function.prototype,yP=zo&&Object.getOwnPropertyDescriptor,Ko=SP(Hh,"name"),TP=Ko&&function(){}.name==="something",IP=Ko&&(!zo||zo&&yP(Hh,"name").configurable);jh.exports={EXISTS:Ko,PROPER:TP,CONFIGURABLE:IP}});var Gh=f(Qh=>{"use strict";var EP=Ce(),xP=$o(),PP=ar(),wP=st(),AP=rr(),kP=Ho();Qh.f=EP&&!xP?Object.defineProperties:function(e,t){wP(e);for(var r=AP(t),i=kP(t),s=i.length,n=0,o;s>n;)PP.f(e,o=i[n++],r[o]);return e}});var Jo=f((b_,Wh)=>{"use strict";var RP=ht();Wh.exports=RP("document","documentElement")});var ru=f((g_,em)=>{"use strict";var LP=st(),$P=Gh(),Yh=Uo(),MP=Is(),CP=Jo(),DP=bs(),VP=ys(),zh=">",Kh="<",eu="prototype",tu="script",Jh=VP("IE_PROTO"),Zo=function(){},Zh=function(a){return Kh+tu+zh+a+Kh+"/"+tu+zh},Xh=function(a){a.write(Zh("")),a.close();var e=a.parentWindow.Object;return a=null,e},_P=function(){var a=DP("iframe"),e="java"+tu+":",t;return a.style.display="none",CP.appendChild(a),a.src=String(e),t=a.contentWindow.document,t.open(),t.write(Zh("document.F=Object")),t.close(),t.F},Ps,ws=function(){try{Ps=new ActiveXObject("htmlfile")}catch(e){}ws=typeof document!="undefined"?document.domain&&Ps?Xh(Ps):_P():Xh(Ps);for(var a=Yh.length;a--;)delete ws[eu][Yh[a]];return ws()};MP[Jh]=!0;em.exports=Object.create||function(e,t){var r;return e!==null?(Zo[eu]=LP(e),r=new Zo,Zo[eu]=null,r[Jh]=e):r=ws(),t===void 0?r:$P.f(r,t)}});var Nr=f((v_,tm)=>{"use strict";var OP=Dr();tm.exports=function(a,e,t,r){return r&&r.enumerable?a[e]=t:OP(a,e,t),a}});var nu=f((S_,am)=>{"use strict";var BP=me(),NP=ae(),FP=Ve(),qP=ru(),rm=Ts(),UP=Nr(),HP=fe(),jP=ze(),su=HP("iterator"),im=!1,mt,iu,au;[].keys&&(au=[].keys(),"next"in au?(iu=rm(rm(au)),iu!==Object.prototype&&(mt=iu)):im=!0);var QP=!FP(mt)||BP(function(){var a={};return mt[su].call(a)!==a});QP?mt={}:jP&&(mt=qP(mt));NP(mt[su])||UP(mt,su,function(){return this});am.exports={IteratorPrototype:mt,BUGGY_SAFARI_ITERATORS:im}});var As=f((y_,nm)=>{"use strict";var GP=fe(),WP=GP("toStringTag"),sm={};sm[WP]="z";nm.exports=String(sm)==="[object z]"});var ki=f((T_,om)=>{"use strict";var YP=As(),zP=ae(),ks=tr(),KP=fe(),XP=KP("toStringTag"),JP=Object,ZP=ks(function(){return arguments}())==="Arguments",ew=function(a,e){try{return a[e]}catch(t){}};om.exports=YP?ks:function(a){var e,t,r;return a===void 0?"Undefined":a===null?"Null":typeof(t=ew(e=JP(a),XP))=="string"?t:ZP?ks(e):(r=ks(e))==="Object"&&zP(e.callee)?"Arguments":r}});var lm=f((I_,um)=>{"use strict";var tw=As(),rw=ki();um.exports=tw?{}.toString:function(){return"[object "+rw(this)+"]"}});var Ri=f((E_,dm)=>{"use strict";var iw=As(),aw=ar().f,sw=Dr(),nw=Ke(),ow=lm(),uw=fe(),cm=uw("toStringTag");dm.exports=function(a,e,t,r){var i=t?a:a&&a.prototype;i&&(nw(i,cm)||aw(i,cm,{configurable:!0,value:e}),r&&!iw&&sw(i,"toString",ow))}});var hm=f((x_,pm)=>{"use strict";var lw=nu().IteratorPrototype,cw=ru(),dw=vi(),pw=Ri(),hw=sr(),mw=function(){return this};pm.exports=function(a,e,t,r){var i=e+" Iterator";return a.prototype=cw(lw,{next:dw(+!r,t)}),pw(a,i,!1,!0),hw[i]=mw,a}});var fm=f((P_,mm)=>{"use strict";var fw=le(),bw=at();mm.exports=function(a,e,t){try{return fw(bw(Object.getOwnPropertyDescriptor(a,e)[t]))}catch(r){}}});var gm=f((w_,bm)=>{"use strict";var gw=Ve();bm.exports=function(a){return gw(a)||a===null}});var Sm=f((A_,vm)=>{"use strict";var vw=gm(),Sw=String,yw=TypeError;vm.exports=function(a){if(vw(a))return a;throw new yw("Can't set "+Sw(a)+" as a prototype")}});var ou=f((k_,ym)=>{"use strict";var Tw=fm(),Iw=Ve(),Ew=$t(),xw=Sm();ym.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var a=!1,e={},t;try{t=Tw(Object.prototype,"__proto__","set"),t(e,[]),a=e instanceof Array}catch(r){}return function(i,s){return Ew(i),xw(s),Iw(i)&&(a?t(i,s):i.__proto__=s),i}}():void 0)});var $m=f((R_,Lm)=>{"use strict";var Pw=ue(),ww=De(),Rs=ze(),km=Xo(),Aw=ae(),kw=hm(),Tm=Ts(),Im=ou(),Rw=Ri(),Lw=Dr(),uu=Nr(),$w=fe(),Em=sr(),Rm=nu(),Mw=km.PROPER,Cw=km.CONFIGURABLE,xm=Rm.IteratorPrototype,Ls=Rm.BUGGY_SAFARI_ITERATORS,Li=$w("iterator"),Pm="keys",$i="values",wm="entries",Am=function(){return this};Lm.exports=function(a,e,t,r,i,s,n){kw(t,e,r);var o=function(v){if(v===i&&p)return p;if(!Ls&&v&&v in c)return c[v];switch(v){case Pm:return function(){return new t(this,v)};case $i:return function(){return new t(this,v)};case wm:return function(){return new t(this,v)}}return function(){return new t(this)}},u=e+" Iterator",l=!1,c=a.prototype,d=c[Li]||c["@@iterator"]||i&&c[i],p=!Ls&&d||o(i),h=e==="Array"&&c.entries||d,m,b,g;if(h&&(m=Tm(h.call(new a)),m!==Object.prototype&&m.next&&(!Rs&&Tm(m)!==xm&&(Im?Im(m,xm):Aw(m[Li])||uu(m,Li,Am)),Rw(m,u,!0,!0),Rs&&(Em[u]=Am))),Mw&&i===$i&&d&&d.name!==$i&&(!Rs&&Cw?Lw(c,"name",$i):(l=!0,p=function(){return ww(d,this)})),i)if(b={values:o($i),keys:s?p:o(Pm),entries:o(wm)},n)for(g in b)(Ls||l||!(g in c))&&uu(c,g,b[g]);else Pw({target:e,proto:!0,forced:Ls||l},b);return(!Rs||n)&&c[Li]!==p&&uu(c,Li,p,{name:i}),Em[e]=p,b}});var Cm=f((L_,Mm)=>{"use strict";Mm.exports=function(a,e){return{value:a,done:e}}});var cu=f(($_,Bm)=>{"use strict";var Dw=rr(),lu=wi(),Dm=sr(),_m=Yo(),Vw=ar().f,_w=$m(),$s=Cm(),Ow=ze(),Bw=Ce(),Om="Array Iterator",Nw=_m.set,Fw=_m.getterFor(Om);Bm.exports=_w(Array,"Array",function(a,e){Nw(this,{type:Om,target:Dw(a),index:0,kind:e})},function(){var a=Fw(this),e=a.target,t=a.index++;if(!e||t>=e.length)return a.target=void 0,$s(void 0,!0);switch(a.kind){case"keys":return $s(t,!1);case"values":return $s(e[t],!1)}return $s([t,e[t]],!1)},"values");var Vm=Dm.Arguments=Dm.Array;lu("keys");lu("values");lu("entries");if(!Ow&&Bw&&Vm.name!=="values")try{Vw(Vm,"name",{value:"values"})}catch(a){}});var Fm=f((M_,Nm)=>{"use strict";var qw=fe(),Uw=sr(),Hw=qw("iterator"),jw=Array.prototype;Nm.exports=function(a){return a!==void 0&&(Uw.Array===a||jw[Hw]===a)}});var du=f((C_,Um)=>{"use strict";var Qw=ki(),qm=Ti(),Gw=Rr(),Ww=sr(),Yw=fe(),zw=Yw("iterator");Um.exports=function(a){if(!Gw(a))return qm(a,zw)||qm(a,"@@iterator")||Ww[Qw(a)]}});var jm=f((D_,Hm)=>{"use strict";var Kw=De(),Xw=at(),Jw=st(),Zw=yi(),eA=du(),tA=TypeError;Hm.exports=function(a,e){var t=arguments.length<2?eA(a):e;if(Xw(t))return Jw(Kw(t,a));throw new tA(Zw(a)+" is not iterable")}});var Wm=f((V_,Gm)=>{"use strict";var rA=De(),Qm=st(),iA=Ti();Gm.exports=function(a,e,t){var r,i;Qm(a);try{if(r=iA(a,"return"),!r){if(e==="throw")throw t;return t}r=rA(r,a)}catch(s){i=!0,r=s}if(e==="throw")throw t;if(i)throw r;return Qm(r),t}});var Cs=f((__,Xm)=>{"use strict";var aA=Cr(),sA=De(),nA=st(),oA=yi(),uA=Fm(),lA=Or(),Ym=Si(),cA=jm(),dA=du(),zm=Wm(),pA=TypeError,Ms=function(a,e){this.stopped=a,this.result=e},Km=Ms.prototype;Xm.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=aA(e,r),l,c,d,p,h,m,b,g=function(S){return l&&zm(l,"normal",S),new Ms(!0,S)},v=function(S){return i?(nA(S),o?u(S[0],S[1],g):u(S[0],S[1])):o?u(S,g):u(S)};if(s)l=a.iterator;else if(n)l=a;else{if(c=dA(a),!c)throw new pA(oA(a)+" is not iterable");if(uA(c)){for(d=0,p=lA(a);p>d;d++)if(h=v(a[d]),h&&Ym(Km,h))return h;return new Ms(!1)}l=cA(a,c)}for(m=s?a.next:l.next;!(b=sA(m,l)).done;){try{h=v(b.value)}catch(S){zm(l,"throw",S)}if(typeof h=="object"&&h&&Ym(Km,h))return h}return new Ms(!1)}});var Zm=f((O_,Jm)=>{"use strict";var hA=Ce(),mA=ar(),fA=vi();Jm.exports=function(a,e,t){hA?mA.f(a,e,fA(0,t)):a[e]=t}});var ef=f(()=>{"use strict";var bA=ue(),gA=Cs(),vA=Zm();bA({target:"Object",stat:!0},{fromEntries:function(e){var t={};return gA(e,function(r,i){vA(t,r,i)},{AS_ENTRIES:!0}),t}})});var rf=f((F_,tf)=>{"use strict";cu();ef();var SA=Lr();tf.exports=SA.Object.fromEntries});var sf=f((q_,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 of=f(()=>{"use strict";cu();var yA=sf(),TA=ne(),IA=Ri(),nf=sr();for(Ds in yA)IA(TA[Ds],Ds),nf[Ds]=nf.Array;var Ds});var lf=f((j_,uf)=>{"use strict";var EA=rf();of();uf.exports=EA});var pu=f((Q_,cf)=>{"use strict";var xA=lf();cf.exports=xA});var df=f(()=>{"use strict"});var hu=f((Y_,pf)=>{"use strict";var Mi=ne(),PA=ir(),wA=tr(),Vs=function(a){return PA.slice(0,a.length)===a};pf.exports=function(){return Vs("Bun/")?"BUN":Vs("Cloudflare-Workers")?"CLOUDFLARE":Vs("Deno/")?"DENO":Vs("Node.js/")?"NODE":Mi.Bun&&typeof Bun.version=="string"?"BUN":Mi.Deno&&typeof Deno.version=="object"?"DENO":wA(Mi.process)==="process"?"NODE":Mi.window&&Mi.document?"BROWSER":"REST"}()});var _s=f((z_,hf)=>{"use strict";var AA=hu();hf.exports=AA==="NODE"});var ff=f((K_,mf)=>{"use strict";var kA=ar();mf.exports=function(a,e,t){return kA.f(a,e,t)}});var vf=f((X_,gf)=>{"use strict";var RA=ht(),LA=ff(),$A=fe(),MA=Ce(),bf=$A("species");gf.exports=function(a){var e=RA(a);MA&&e&&!e[bf]&&LA(e,bf,{configurable:!0,get:function(){return this}})}});var yf=f((J_,Sf)=>{"use strict";var CA=Si(),DA=TypeError;Sf.exports=function(a,e){if(CA(e,a))return a;throw new DA("Incorrect invocation")}});var fu=f((Z_,Tf)=>{"use strict";var VA=le(),_A=ae(),mu=Ii(),OA=VA(Function.toString);_A(mu.inspectSource)||(mu.inspectSource=function(a){return OA(a)});Tf.exports=mu.inspectSource});var gu=f((eO,wf)=>{"use strict";var BA=le(),NA=me(),If=ae(),FA=ki(),qA=ht(),UA=fu(),Ef=function(){},xf=qA("Reflect","construct"),bu=/^\s*(?:class|function)\b/,HA=BA(bu.exec),jA=!bu.test(Ef),Ci=function(e){if(!If(e))return!1;try{return xf(Ef,[],e),!0}catch(t){return!1}},Pf=function(e){if(!If(e))return!1;switch(FA(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return jA||!!HA(bu,UA(e))}catch(t){return!0}};Pf.sham=!0;wf.exports=!xf||NA(function(){var a;return Ci(Ci.call)||!Ci(Object)||!Ci(function(){a=!0})||a})?Pf:Ci});var kf=f((tO,Af)=>{"use strict";var QA=gu(),GA=yi(),WA=TypeError;Af.exports=function(a){if(QA(a))return a;throw new WA(GA(a)+" is not a constructor")}});var vu=f((rO,Lf)=>{"use strict";var Rf=st(),YA=kf(),zA=Rr(),KA=fe(),XA=KA("species");Lf.exports=function(a,e){var t=Rf(a).constructor,r;return t===void 0||zA(r=Rf(t)[XA])?e:YA(r)}});var Mf=f((iO,$f)=>{"use strict";var JA=le();$f.exports=JA([].slice)});var Df=f((aO,Cf)=>{"use strict";var ZA=TypeError;Cf.exports=function(a,e){if(a<e)throw new ZA("Not enough arguments");return a}});var Su=f((sO,Vf)=>{"use strict";var ek=ir();Vf.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(ek)});var ku=f((nO,jf)=>{"use strict";var _e=ne(),tk=oo(),rk=Cr(),_f=ae(),ik=Ke(),Hf=me(),Of=Jo(),ak=Mf(),Bf=bs(),sk=Df(),nk=Su(),ok=_s(),Pu=_e.setImmediate,wu=_e.clearImmediate,uk=_e.process,yu=_e.Dispatch,lk=_e.Function,Nf=_e.MessageChannel,ck=_e.String,Tu=0,Di={},Ff="onreadystatechange",Vi,or,Iu,Eu;Hf(function(){Vi=_e.location});var Au=function(a){if(ik(Di,a)){var e=Di[a];delete Di[a],e()}},xu=function(a){return function(){Au(a)}},qf=function(a){Au(a.data)},Uf=function(a){_e.postMessage(ck(a),Vi.protocol+"//"+Vi.host)};(!Pu||!wu)&&(Pu=function(e){sk(arguments.length,1);var t=_f(e)?e:lk(e),r=ak(arguments,1);return Di[++Tu]=function(){tk(t,void 0,r)},or(Tu),Tu},wu=function(e){delete Di[e]},ok?or=function(a){uk.nextTick(xu(a))}:yu&&yu.now?or=function(a){yu.now(xu(a))}:Nf&&!nk?(Iu=new Nf,Eu=Iu.port2,Iu.port1.onmessage=qf,or=rk(Eu.postMessage,Eu)):_e.addEventListener&&_f(_e.postMessage)&&!_e.importScripts&&Vi&&Vi.protocol!=="file:"&&!Hf(Uf)?(or=Uf,_e.addEventListener("message",qf,!1)):Ff in Bf("script")?or=function(a){Of.appendChild(Bf("script"))[Ff]=function(){Of.removeChild(this),Au(a)}}:or=function(a){setTimeout(xu(a),0)});jf.exports={set:Pu,clear:wu}});var Wf=f((oO,Gf)=>{"use strict";var Qf=ne(),dk=Ce(),pk=Object.getOwnPropertyDescriptor;Gf.exports=function(a){if(!dk)return Qf[a];var e=pk(Qf,a);return e&&e.value}});var Ru=f((uO,zf)=>{"use strict";var Yf=function(){this.head=null,this.tail=null};Yf.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}}};zf.exports=Yf});var Xf=f((lO,Kf)=>{"use strict";var hk=ir();Kf.exports=/ipad|iphone|ipod/i.test(hk)&&typeof Pebble!="undefined"});var Zf=f((cO,Jf)=>{"use strict";var mk=ir();Jf.exports=/web0s(?!.*chrome)/i.test(mk)});var nb=f((dO,sb)=>{"use strict";var qr=ne(),fk=Wf(),eb=Cr(),Lu=ku().set,bk=Ru(),gk=Su(),vk=Xf(),Sk=Zf(),$u=_s(),tb=qr.MutationObserver||qr.WebKitMutationObserver,rb=qr.document,ib=qr.process,Os=qr.Promise,Du=fk("queueMicrotask"),Fr,Mu,Cu,Bs,ab;Du||(_i=new bk,Oi=function(){var a,e;for($u&&(a=ib.domain)&&a.exit();e=_i.get();)try{e()}catch(t){throw _i.head&&Fr(),t}a&&a.enter()},!gk&&!$u&&!Sk&&tb&&rb?(Mu=!0,Cu=rb.createTextNode(""),new tb(Oi).observe(Cu,{characterData:!0}),Fr=function(){Cu.data=Mu=!Mu}):!vk&&Os&&Os.resolve?(Bs=Os.resolve(void 0),Bs.constructor=Os,ab=eb(Bs.then,Bs),Fr=function(){ab(Oi)}):$u?Fr=function(){ib.nextTick(Oi)}:(Lu=eb(Lu,qr),Fr=function(){Lu(Oi)}),Du=function(a){_i.head||Fr(),_i.add(a)});var _i,Oi;sb.exports=Du});var ub=f((pO,ob)=>{"use strict";ob.exports=function(a,e){try{arguments.length===1?console.error(a):console.error(a,e)}catch(t){}}});var Ns=f((hO,lb)=>{"use strict";lb.exports=function(a){try{return{error:!1,value:a()}}catch(e){return{error:!0,value:e}}}});var ur=f((mO,cb)=>{"use strict";var yk=ne();cb.exports=yk.Promise});var Ur=f((fO,mb)=>{"use strict";var Tk=ne(),Bi=ur(),Ik=ae(),Ek=Lo(),xk=fu(),Pk=fe(),db=hu(),wk=ze(),Vu=go(),pb=Bi&&Bi.prototype,Ak=Pk("species"),_u=!1,hb=Ik(Tk.PromiseRejectionEvent),kk=Ek("Promise",function(){var a=xk(Bi),e=a!==String(Bi);if(!e&&Vu===66||wk&&!(pb.catch&&pb.finally))return!0;if(!Vu||Vu<51||!/native code/.test(a)){var t=new Bi(function(s){s(1)}),r=function(s){s(function(){},function(){})},i=t.constructor={};if(i[Ak]=r,_u=t.then(function(){})instanceof r,!_u)return!0}return!e&&(db==="BROWSER"||db==="DENO")&&!hb});mb.exports={CONSTRUCTOR:kk,REJECTION_EVENT:hb,SUBCLASSING:_u}});var Hr=f((bO,bb)=>{"use strict";var fb=at(),Rk=TypeError,Lk=function(a){var e,t;this.promise=new a(function(r,i){if(e!==void 0||t!==void 0)throw new Rk("Bad Promise constructor");e=r,t=i}),this.resolve=fb(e),this.reject=fb(t)};bb.exports.f=function(a){return new Lk(a)}});var Vb=f(()=>{"use strict";var $k=ue(),Mk=ze(),Hs=_s(),Ct=ne(),Wr=De(),gb=Nr(),vb=ou(),Ck=Ri(),Dk=vf(),Vk=at(),Us=ae(),_k=Ve(),Ok=yf(),Bk=vu(),Eb=ku().set,qu=nb(),Nk=ub(),Fk=Ns(),qk=Ru(),xb=Yo(),js=ur(),Uu=Ur(),Pb=Hr(),Qs="Promise",wb=Uu.CONSTRUCTOR,Uk=Uu.REJECTION_EVENT,Hk=Uu.SUBCLASSING,Ou=xb.getterFor(Qs),jk=xb.set,jr=js&&js.prototype,lr=js,Fs=jr,Ab=Ct.TypeError,Bu=Ct.document,Hu=Ct.process,Nu=Pb.f,Qk=Nu,Gk=!!(Bu&&Bu.createEvent&&Ct.dispatchEvent),kb="unhandledrejection",Wk="rejectionhandled",Sb=0,Rb=1,Yk=2,ju=1,Lb=2,qs,yb,zk,Tb,$b=function(a){var e;return _k(a)&&Us(e=a.then)?e:!1},Mb=function(a,e){var t=e.value,r=e.state===Rb,i=r?a.ok:a.fail,s=a.resolve,n=a.reject,o=a.domain,u,l,c;try{i?(r||(e.rejection===Lb&&Xk(e),e.rejection=ju),i===!0?u=t:(o&&o.enter(),u=i(t),o&&(o.exit(),c=!0)),u===a.promise?n(new Ab("Promise-chain cycle")):(l=$b(u))?Wr(l,u,s,n):s(u)):n(t)}catch(d){o&&!c&&o.exit(),n(d)}},Cb=function(a,e){a.notified||(a.notified=!0,qu(function(){for(var t=a.reactions,r;r=t.get();)Mb(r,a);a.notified=!1,e&&!a.rejection&&Kk(a)}))},Db=function(a,e,t){var r,i;Gk?(r=Bu.createEvent("Event"),r.promise=e,r.reason=t,r.initEvent(a,!1,!0),Ct.dispatchEvent(r)):r={promise:e,reason:t},!Uk&&(i=Ct["on"+a])?i(r):a===kb&&Nk("Unhandled promise rejection",t)},Kk=function(a){Wr(Eb,Ct,function(){var e=a.facade,t=a.value,r=Ib(a),i;if(r&&(i=Fk(function(){Hs?Hu.emit("unhandledRejection",t,e):Db(kb,e,t)}),a.rejection=Hs||Ib(a)?Lb:ju,i.error))throw i.value})},Ib=function(a){return a.rejection!==ju&&!a.parent},Xk=function(a){Wr(Eb,Ct,function(){var e=a.facade;Hs?Hu.emit("rejectionHandled",e):Db(Wk,e,a.value)})},Qr=function(a,e,t){return function(r){a(e,r,t)}},Gr=function(a,e,t){a.done||(a.done=!0,t&&(a=t),a.value=e,a.state=Yk,Cb(a,!0))},Fu=function(a,e,t){if(!a.done){a.done=!0,t&&(a=t);try{if(a.facade===e)throw new Ab("Promise can't be resolved itself");var r=$b(e);r?qu(function(){var i={done:!1};try{Wr(r,e,Qr(Fu,i,a),Qr(Gr,i,a))}catch(s){Gr(i,s,a)}}):(a.value=e,a.state=Rb,Cb(a,!1))}catch(i){Gr({done:!1},i,a)}}};if(wb&&(lr=function(e){Ok(this,Fs),Vk(e),Wr(qs,this);var t=Ou(this);try{e(Qr(Fu,t),Qr(Gr,t))}catch(r){Gr(t,r)}},Fs=lr.prototype,qs=function(e){jk(this,{type:Qs,done:!1,notified:!1,parent:!1,reactions:new qk,rejection:!1,state:Sb,value:void 0})},qs.prototype=gb(Fs,"then",function(e,t){var r=Ou(this),i=Nu(Bk(this,lr));return r.parent=!0,i.ok=Us(e)?e:!0,i.fail=Us(t)&&t,i.domain=Hs?Hu.domain:void 0,r.state===Sb?r.reactions.add(i):qu(function(){Mb(i,r)}),i.promise}),yb=function(){var a=new qs,e=Ou(a);this.promise=a,this.resolve=Qr(Fu,e),this.reject=Qr(Gr,e)},Pb.f=Nu=function(a){return a===lr||a===zk?new yb(a):Qk(a)},!Mk&&Us(js)&&jr!==Object.prototype)){Tb=jr.then,Hk||gb(jr,"then",function(e,t){var r=this;return new lr(function(i,s){Wr(Tb,r,i,s)}).then(e,t)},{unsafe:!0});try{delete jr.constructor}catch(a){}vb&&vb(jr,Fs)}$k({global:!0,constructor:!0,wrap:!0,forced:wb},{Promise:lr});Ck(lr,Qs,!1,!0);Dk(Qs)});var Fb=f((SO,Nb)=>{"use strict";var Jk=fe(),Ob=Jk("iterator"),Bb=!1;try{_b=0,Qu={next:function(){return{done:!!_b++}},return:function(){Bb=!0}},Qu[Ob]=function(){return this},Array.from(Qu,function(){throw 2})}catch(a){}var _b,Qu;Nb.exports=function(a,e){try{if(!e&&!Bb)return!1}catch(i){return!1}var t=!1;try{var r={};r[Ob]=function(){return{next:function(){return{done:t=!0}}}},a(r)}catch(i){}return t}});var Gu=f((yO,qb)=>{"use strict";var Zk=ur(),eR=Fb(),tR=Ur().CONSTRUCTOR;qb.exports=tR||!eR(function(a){Zk.all(a).then(void 0,function(){})})});var Ub=f(()=>{"use strict";var rR=ue(),iR=De(),aR=at(),sR=Hr(),nR=Ns(),oR=Cs(),uR=Gu();rR({target:"Promise",stat:!0,forced:uR},{all:function(e){var t=this,r=sR.f(t),i=r.resolve,s=r.reject,n=nR(function(){var o=aR(t.resolve),u=[],l=0,c=1;oR(e,function(d){var p=l++,h=!1;c++,iR(o,t,d).then(function(m){h||(h=!0,u[p]=m,--c||i(u))},s)}),--c||i(u)});return n.error&&s(n.value),r.promise}})});var jb=f(()=>{"use strict";var lR=ue(),cR=ze(),dR=Ur().CONSTRUCTOR,Yu=ur(),pR=ht(),hR=ae(),mR=Nr(),Hb=Yu&&Yu.prototype;lR({target:"Promise",proto:!0,forced:dR,real:!0},{catch:function(a){return this.then(void 0,a)}});!cR&&hR(Yu)&&(Wu=pR("Promise").prototype.catch,Hb.catch!==Wu&&mR(Hb,"catch",Wu,{unsafe:!0}));var Wu});var Qb=f(()=>{"use strict";var fR=ue(),bR=De(),gR=at(),vR=Hr(),SR=Ns(),yR=Cs(),TR=Gu();fR({target:"Promise",stat:!0,forced:TR},{race:function(e){var t=this,r=vR.f(t),i=r.reject,s=SR(function(){var n=gR(t.resolve);yR(e,function(o){bR(n,t,o).then(r.resolve,i)})});return s.error&&i(s.value),r.promise}})});var Gb=f(()=>{"use strict";var IR=ue(),ER=Hr(),xR=Ur().CONSTRUCTOR;IR({target:"Promise",stat:!0,forced:xR},{reject:function(e){var t=ER.f(this),r=t.reject;return r(e),t.promise}})});var zu=f((RO,Wb)=>{"use strict";var PR=st(),wR=Ve(),AR=Hr();Wb.exports=function(a,e){if(PR(a),wR(e)&&e.constructor===a)return e;var t=AR.f(a),r=t.resolve;return r(e),t.promise}});var Kb=f(()=>{"use strict";var kR=ue(),RR=ht(),Yb=ze(),LR=ur(),zb=Ur().CONSTRUCTOR,$R=zu(),MR=RR("Promise"),CR=Yb&&!zb;kR({target:"Promise",stat:!0,forced:Yb||zb},{resolve:function(e){return $R(CR&&this===MR?LR:this,e)}})});var Xb=f(()=>{"use strict";Vb();Ub();jb();Qb();Gb();Kb()});var tg=f(()=>{"use strict";var DR=ue(),VR=ze(),Gs=ur(),_R=me(),Zb=ht(),eg=ae(),OR=vu(),Jb=zu(),BR=Nr(),Xu=Gs&&Gs.prototype,NR=!!Gs&&_R(function(){Xu.finally.call({then:function(){}},function(){})});DR({target:"Promise",proto:!0,real:!0,forced:NR},{finally:function(a){var e=OR(this,Zb("Promise")),t=eg(a);return this.then(t?function(r){return Jb(e,a()).then(function(){return r})}:a,t?function(r){return Jb(e,a()).then(function(){throw r})}:a)}});!VR&&eg(Gs)&&(Ku=Zb("Promise").prototype.finally,Xu.finally!==Ku&&BR(Xu,"finally",Ku,{unsafe:!0}));var Ku});var ig=f((_O,rg)=>{"use strict";df();Xb();tg();var FR=Mt();rg.exports=FR("Promise","finally")});var sg=f((OO,ag)=>{"use strict";var qR=ig();ag.exports=qR});var Ws=f((BO,ng)=>{"use strict";var UR=sg();ng.exports=UR});var Sg=f(()=>{"use strict";var rL=ue(),iL=jo().values;rL({target:"Object",stat:!0},{values:function(e){return iL(e)}})});var Tg=f((IB,yg)=>{"use strict";Sg();var aL=Lr();yg.exports=aL.Object.values});var Eg=f((EB,Ig)=>{"use strict";var sL=Tg();Ig.exports=sL});var zr=f((xB,xg)=>{"use strict";var nL=Eg();xg.exports=nL});var jg=f(()=>{"use strict";var kL=ue(),RL=$r(),LL=Or(),$L=Pi(),ML=wi();kL({target:"Array",proto:!0},{at:function(e){var t=RL(this),r=LL(t),i=$L(e),s=i>=0?i:r+i;return s<0||s>=r?void 0:t[s]}});ML("at")});var Gg=f((VN,Qg)=>{"use strict";jg();var CL=Mt();Qg.exports=CL("Array","at")});var Yg=f((_N,Wg)=>{"use strict";var DL=Gg();Wg.exports=DL});var Bt=f((ON,zg)=>{"use strict";var VL=Yg();zg.exports=VL});var Tl=f((Pq,Lv)=>{"use strict";var v$=tr();Lv.exports=Array.isArray||function(e){return v$(e)==="Array"}});var Mv=f((wq,$v)=>{"use strict";var S$=TypeError,y$=9007199254740991;$v.exports=function(a){if(a>y$)throw S$("Maximum allowed index exceeded");return a}});var Vv=f((Aq,Dv)=>{"use strict";var T$=Tl(),I$=Or(),E$=Mv(),x$=Cr(),Cv=function(a,e,t,r,i,s,n,o){for(var u=i,l=0,c=n?x$(n,o):!1,d,p;l<r;)l in t&&(d=c?c(t[l],l,e):t[l],s>0&&T$(d)?(p=I$(d),u=Cv(a,e,d,p,u,s-1)-1):(E$(u+1),a[u]=d),u++),l++;return u};Dv.exports=Cv});var Nv=f((kq,Bv)=>{"use strict";var _v=Tl(),P$=gu(),w$=Ve(),A$=fe(),k$=A$("species"),Ov=Array;Bv.exports=function(a){var e;return _v(a)&&(e=a.constructor,P$(e)&&(e===Ov||_v(e.prototype))?e=void 0:w$(e)&&(e=e[k$],e===null&&(e=void 0))),e===void 0?Ov:e}});var qv=f((Rq,Fv)=>{"use strict";var R$=Nv();Fv.exports=function(a,e){return new(R$(a))(e===0?0:e)}});var Uv=f(()=>{"use strict";var L$=ue(),$$=Vv(),M$=at(),C$=$r(),D$=Or(),V$=qv();L$({target:"Array",proto:!0},{flatMap:function(e){var t=C$(this),r=D$(t),i;return M$(e),i=V$(t,0),i.length=$$(i,t,t,r,0,1,e,arguments.length>1?arguments[1]:void 0),i}})});var Hv=f(()=>{"use strict";var _$=wi();_$("flatMap")});var Qv=f((Dq,jv)=>{"use strict";Uv();Hv();var O$=Mt();jv.exports=O$("Array","flatMap")});var Wv=f((Vq,Gv)=>{"use strict";var B$=Qv();Gv.exports=B$});var Il=f((_q,Yv)=>{"use strict";var N$=Wv();Yv.exports=N$});var ea=f((Oq,zv)=>{"use strict";var F$=ki(),q$=String;zv.exports=function(a){if(F$(a)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return q$(a)}});var El=f((Bq,Kv)=>{"use strict";Kv.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 Zv=f((Nq,Jv)=>{"use strict";var U$=le(),H$=$t(),j$=ea(),Pl=El(),Xv=U$("".replace),Q$=RegExp("^["+Pl+"]+"),G$=RegExp("(^|[^"+Pl+"])["+Pl+"]+$"),xl=function(a){return function(e){var t=j$(H$(e));return a&1&&(t=Xv(t,Q$,"")),a&2&&(t=Xv(t,G$,"$1")),t}};Jv.exports={start:xl(1),end:xl(2),trim:xl(3)}});var iS=f((Fq,rS)=>{"use strict";var W$=Xo().PROPER,Y$=me(),eS=El(),tS="\u200B\x85\u180E";rS.exports=function(a){return Y$(function(){return!!eS[a]()||tS[a]()!==tS||W$&&eS[a].name!==a})}});var wl=f((qq,aS)=>{"use strict";var z$=Zv().start,K$=iS();aS.exports=K$("trimStart")?function(){return z$(this)}:"".trimStart});var nS=f(()=>{"use strict";var X$=ue(),sS=wl();X$({target:"String",proto:!0,name:"trimStart",forced:"".trimLeft!==sS},{trimLeft:sS})});var uS=f(()=>{"use strict";nS();var J$=ue(),oS=wl();J$({target:"String",proto:!0,name:"trimStart",forced:"".trimStart!==oS},{trimStart:oS})});var cS=f((Gq,lS)=>{"use strict";uS();var Z$=Mt();lS.exports=Z$("String","trimLeft")});var pS=f((Wq,dS)=>{"use strict";var eM=cS();dS.exports=eM});var mS=f((Yq,hS)=>{"use strict";var tM=pS();hS.exports=tM});var LS=f(()=>{"use strict"});var $S=f(()=>{"use strict"});var CS=f(($H,MS)=>{"use strict";var xM=Ve(),PM=tr(),wM=fe(),AM=wM("match");MS.exports=function(a){var e;return xM(a)&&((e=a[AM])!==void 0?!!e:PM(a)==="RegExp")}});var VS=f((MH,DS)=>{"use strict";var kM=st();DS.exports=function(){var a=kM(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 BS=f((CH,OS)=>{"use strict";var RM=De(),LM=Ke(),$M=Si(),MM=VS(),_S=RegExp.prototype;OS.exports=function(a){var e=a.flags;return e===void 0&&!("flags"in _S)&&!LM(a,"flags")&&$M(_S,a)?RM(MM,a):e}});var FS=f((DH,NS)=>{"use strict";var Dl=le(),CM=$r(),DM=Math.floor,Ml=Dl("".charAt),VM=Dl("".replace),Cl=Dl("".slice),_M=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,OM=/\$([$&'`]|\d{1,2})/g;NS.exports=function(a,e,t,r,i,s){var n=t+a.length,o=r.length,u=OM;return i!==void 0&&(i=CM(i),u=_M),VM(s,u,function(l,c){var d;switch(Ml(c,0)){case"$":return"$";case"&":return a;case"`":return Cl(e,0,t);case"'":return Cl(e,n);case"<":d=i[Cl(c,1,-1)];break;default:var p=+c;if(p===0)return l;if(p>o){var h=DM(p/10);return h===0?l:h<=o?r[h-1]===void 0?Ml(c,1):r[h-1]+Ml(c,1):l}d=r[p-1]}return d===void 0?"":d})}});var HS=f(()=>{"use strict";var BM=ue(),NM=De(),_l=le(),qS=$t(),FM=ae(),qM=Rr(),UM=CS(),ei=ea(),HM=Ti(),jM=BS(),QM=FS(),GM=fe(),WM=ze(),YM=GM("replace"),zM=TypeError,Vl=_l("".indexOf),KM=_l("".replace),US=_l("".slice),XM=Math.max;BM({target:"String",proto:!0},{replaceAll:function(e,t){var r=qS(this),i,s,n,o,u,l,c,d,p,h,m=0,b="";if(!qM(e)){if(i=UM(e),i&&(s=ei(qS(jM(e))),!~Vl(s,"g")))throw new zM("`.replaceAll` does not allow non-global regexes");if(n=HM(e,YM),n)return NM(n,e,r,t);if(WM&&i)return KM(ei(r),e,t)}for(o=ei(r),u=ei(e),l=FM(t),l||(t=ei(t)),c=u.length,d=XM(1,c),p=Vl(o,u);p!==-1;)h=l?ei(t(u,p,o)):QM(u,o,p,[],void 0,t),b+=US(o,m,p)+h,m=p+c,p=p+d>o.length?-1:Vl(o,u,p+d);return m<o.length&&(b+=US(o,m)),b}})});var QS=f((OH,jS)=>{"use strict";LS();$S();HS();var JM=Mt();jS.exports=JM("String","replaceAll")});var WS=f((BH,GS)=>{"use strict";var ZM=QS();GS.exports=ZM});var zS=f((NH,YS)=>{"use strict";var eC=WS();YS.exports=eC});var XS=f((FH,KS)=>{"use strict";var tC=Pi(),rC=ea(),iC=$t(),aC=RangeError;KS.exports=function(e){var t=rC(iC(this)),r="",i=tC(e);if(i<0||i===1/0)throw new aC("Wrong number of repetitions");for(;i>0;(i>>>=1)&&(t+=t))i&1&&(r+=t);return r}});var ry=f((qH,ty)=>{"use strict";var ey=le(),sC=_o(),JS=ea(),nC=XS(),oC=$t(),uC=ey(nC),lC=ey("".slice),cC=Math.ceil,ZS=function(a){return function(e,t,r){var i=JS(oC(e)),s=sC(t),n=i.length,o=r===void 0?" ":JS(r),u,l;return s<=n||o===""?i:(u=s-n,l=uC(o,cC(u/o.length)),l.length>u&&(l=lC(l,0,u)),a?i+l:l+i)}};ty.exports={start:ZS(!1),end:ZS(!0)}});var ay=f((UH,iy)=>{"use strict";var dC=ir();iy.exports=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(dC)});var sy=f(()=>{"use strict";var pC=ue(),hC=ry().start,mC=ay();pC({target:"String",proto:!0,forced:mC},{padStart:function(e){return hC(this,e,arguments.length>1?arguments[1]:void 0)}})});var oy=f((QH,ny)=>{"use strict";sy();var fC=Mt();ny.exports=fC("String","padStart")});var ly=f((GH,uy)=>{"use strict";var bC=oy();uy.exports=bC});var dy=f((WH,cy)=>{"use strict";var gC=ly();cy.exports=gC});var md="2.0.129-dev.505377de.0";var Me=(i=>(i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused",i))(Me||{}),pt=(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))(pt||{});var ps=(i=>(i.NOT_AVAILABLE="NOT_AVAILABLE",i.AVAILABLE="AVAILABLE",i.CONNECTING="CONNECTING",i.CONNECTED="CONNECTED",i))(ps||{}),ao=(r=>(r.HTTP1="http1",r.HTTP2="http2",r.QUIC="quic",r))(ao||{});var so=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(so||{}),hs=(r=>(r.TRAFFIC_SAVING="traffic_saving",r.HIGH_QUALITY="high_quality",r.UNKNOWN="unknown",r))(hs||{});var GT=_(Fe(),1);import{assertNever as ph,assertNonNullable as Rx,isNonNullable as vs,ValueSubject as Bo,Subject as Lx,Subscription as $x,merge as Mx,observableFrom as Cx,fromEvent as uh,map as lh,tap as ch,filterChanged as Dx,isNullable as No,ErrorCategory as dh}from"@vkontakte/videoplayer-shared/es2015";var oh=a=>new Promise((e,t)=>{let r=document.createElement("script");r.setAttribute("src",a),r.onload=()=>e(),r.onerror=i=>t(i),document.body.appendChild(r)});var Ss=class{constructor(e){this.connection$=new Bo(void 0);this.castState$=new Bo("NOT_AVAILABLE");this.errorEvent$=new Lx;this.realCastState$=new Bo("NOT_AVAILABLE");this.subscription=new $x;this.isDestroyed=!1;var s;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastInitializer");let t="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${t}`}),e.isDisabled||!t)return;let r=vs((s=window.chrome)==null?void 0:s.cast),i=!!window.__onGCastApiAvailable;r?this.initializeCastApi():(window.__onGCastApiAvailable=n=>{delete window.__onGCastApiAvailable,n&&!this.isDestroyed&&this.initializeCastApi()},i||oh("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:dh.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(){vs(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();No(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();No(t)||e!==t.remotePlayer.isMuted&&t.remotePlayerController.muteOrUnmute()}destroy(){this.isDestroyed=!0,this.subscription.unsubscribe()}initListeners(){let e=new cast.framework.RemotePlayer,t=new cast.framework.RemotePlayerController(e),r=cast.framework.CastContext.getInstance();this.subscription.add(uh(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 ph(i.sessionState)}})).add(Mx(uh(r,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(ch(i=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(i)}`})}),lh(i=>i.castState)),Cx([r.getCastState()])).pipe(Dx(),lh(Vx),ch(i=>{this.log({message:`realCastState$: ${i}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(i=>{var o,u;let s=i==="CONNECTED",n=vs(this.connection$.getValue());if(s&&!n){let l=r.getCurrentSession();Rx(l);let c=l.getCastDevice(),d=(u=(o=l.getMediaSession())==null?void 0:o.media)==null?void 0:u.contentId;(No(d)||d===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:l,castDevice:c}))}else!s&&n&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(i==="CONNECTED"?vs(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:dh.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:s})}}},Vx=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 ph(a)}};var Sc=_(Fe(),1),kT=_(Br(),1),RT=_(pu(),1);var bg=_(Ws(),1);import{assertNever as og}from"@vkontakte/videoplayer-shared/es2015";var be=(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:og(t)}return a},Ys=(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:og(e)}};var A=(a,e,t=!1)=>{let r=a.getTransition();(t||!r||r.to===e)&&a.setState(e)};import{isNonNullable as HR,Subject as zs,merge as ug}from"@vkontakte/videoplayer-shared/es2015";var O=class{constructor(e){this.transitionStarted$=new zs;this.transitionEnded$=new zs;this.transitionUpdated$=new zs;this.forceChanged$=new zs;this.stateChangeStarted$=ug(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=ug(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||HR(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 jR}from"@vkontakte/videoplayer-shared/es2015";var lg=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 jR(a)}};import{assertNever as Yr,assertNonNullable as cr,debounce as cg,ErrorCategory as dg,fromEvent as dr,isNonNullable as pg,map as hg,merge as mg,observableFrom as QR,Subject as GR,Subscription as Ju,timeout as WR,getHighestQuality as YR}from"@vkontakte/videoplayer-shared/es2015";var zR=5,KR=5,XR=500,fg=7e3,Ni=class{constructor(e){this.subscription=new Ju;this.loadMediaTimeoutSubscription=new Ju;this.videoState=new O("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:Yr(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:Yr(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:Yr(e)}break}default:Yr(r)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(lg(e.format)),this.params.output.isAudioAvailable$.next(!0),this.handleRemoteVolumeChange({volume:this.params.connection.remotePlayer.volumeLevel,muted:this.params.connection.remotePlayer.isMuted});let t=this.params.connection.session.getMediaSession();t&&this.restoreSession(t),this.subscribe()}destroy(){this.log({message:"[destroy]"}),this.subscription.unsubscribe()}subscribe(){this.subscription.add(this.loadMediaTimeoutSubscription);let e=new Ju;this.subscription.add(e),this.subscription.add(mg(this.videoState.stateChangeStarted$.pipe(hg(i=>`stateChangeStarted$ ${JSON.stringify(i)}`)),this.videoState.stateChangeEnded$.pipe(hg(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(cg(XR)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add(dr(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)>zR)&&i.next(o),s=o})),e.add(dr(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(dr(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),i=>{this.logRemoteEvent(i),i.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(dr(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),i=>{this.logRemoteEvent(i),i.value?this.handleRemotePause():this.handleRemotePlay()}),t(dr(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<KR&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),A(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:Yr(n)}}),t(dr(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),i=>{this.logRemoteEvent(i),this.handleRemoteVolumeChange({volume:i.value})}),t(dr(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),i=>{this.logRemoteEvent(i),this.handleRemoteVolumeChange({muted:i.value})});let r=mg(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,QR(["init"])).pipe(cg(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"),A(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),A(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"),A(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"),A(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"&&A(this.params.desiredState.playbackState,"ready")}handleRemoteStop(){this.videoState.getState()!=="stopped"&&this.videoState.setState("stopped")}handleRemoteVolumeChange(e){var i,s;let t=this.params.output.volume$.getValue(),r={volume:(i=e.volume)!=null?i:t.volume,muted:(s=e.muted)!=null?s:t.muted};(r.volume!==t.volume||r.muted!==r.muted)&&this.params.output.volume$.next(r)}seek(e){this.params.output.willSeekEvent$.next();let{remotePlayer:t,remotePlayerController:r}=this.params.connection;t.currentTime=e,r.seek()}stop(){let{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){var l;let t=this.params.source,r,i,s;switch(e){case"MPEG":{let c=t[e];cr(c);let d=YR(Object.keys(c));cr(d);let p=c[d];cr(p),r=p,i="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let c=t[e];cr(c),r=c.url,i="application/x-mpegurl",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":{let c=t[e];cr(c),r=c.url,i="application/dash+xml",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let c=t[e];cr(c),r=c.url,i="application/dash+xml",s=chrome.cast.media.StreamType.LIVE;break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let c=t[e];cr(c),r=be(c.url),i="application/x-mpegurl",s=chrome.cast.media.StreamType.LIVE;break}case"DASH_LIVE":case"WEB_RTC_LIVE":{let c="Unsupported format for Chromecast",d=new Error(c);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:dg.VIDEO_PIPELINE,message:c,thrown:d}),d}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return Yr(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 pg(o)&&(n.metadata.title=o),pg(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(WR(fg).subscribe(()=>s(`timeout(${fg})`)))});(0,bg.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:dg.VIDEO_PIPELINE,message:s,thrown:i})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var Sl=_(Fe(),1);import{clearVideoElement as vg}from"@vkontakte/videoplayer-shared/es2015";import{clearVideoElement as JR}from"@vkontakte/videoplayer-shared/es2015";var gg=a=>{try{a.pause(),a.playbackRate=0,JR(a),a.remove()}catch(e){console.error(e)}};import{fromEvent as ZR,Subscription as eL}from"@vkontakte/videoplayer-shared/es2015";var Zu=class{constructor(){this.attribute="data-pool-reused"}get(e){return e.hasAttribute(this.attribute)}set(e,t){e.toggleAttribute(this.attribute,t)}delete(e){e.removeAttribute(this.attribute)}},el=window.WeakMap?new WeakMap:new Zu,tl=window.WeakMap?new WeakMap:new Map,tL=(a,e=20)=>{let t=0;return ZR(a,"ratechange").subscribe(r=>{t++,t>=e&&(a.currentTime=a.currentTime,t=0)})},Pe=(a,{audioVideoSyncRate:e,disableYandexPiP:t})=>{let r=a.querySelector("video"),i=!!r;r?vg(r):(r=document.createElement("video"),a.appendChild(r)),el.set(r,i);let s=new eL;return s.add(tL(r,e)),tl.set(r,s),r.setAttribute("crossorigin","anonymous"),r.setAttribute("playsinline","playsinline"),t&&r.setAttribute("x-yandex-pip","false"),r.controls=!1,r.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),r},we=a=>{let e=tl.get(a);e==null||e.unsubscribe(),tl.delete(a);let t=el.get(a);el.delete(a),t?vg(a):gg(a)};var il=_(zr(),1);import{assertNonNullable as Fi,isNonNullable as ot,isNullable as lL,fromEvent as Kr,merge as Pg,observableFrom as wg,filterChanged as Ag,map as qi,Subject as kg,Subscription as cL,ValueSubject as dL,ErrorCategory as pL}from"@vkontakte/videoplayer-shared/es2015";import{isNonNullable as rl,isNullable as oL,Subscription as uL}from"@vkontakte/videoplayer-shared/es2015";var Ks=(a,e,t,{equal:r=(n,o)=>n===o,changed$:i,onError:s}={})=>{let n=a.getState(),o=e(),u=oL(i),l=new uL;return i&&l.add(i.subscribe(c=>{let d=a.getState();r(c,d)&&a.setState(c)},s)),r(o,n)||(t(n),u&&a.setState(n)),l.add(a.stateChangeStarted$.subscribe(c=>{t(c.to),u&&a.setState(c.to)},s)),l},nt=(a,e,t)=>Ks(e,()=>a.loop,r=>{rl(r)&&(a.loop=r)},{onError:t}),Ae=(a,e,t,r)=>Ks(e,()=>({muted:a.muted,volume:a.volume}),i=>{rl(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}),qe=(a,e,t,r)=>Ks(e,()=>a.playbackRate,i=>{rl(i)&&(a.playbackRate=i)},{changed$:t,onError:r}),Dt=Ks;var hL=a=>["__",a.language,a.label].join("|"),mL=(a,e)=>{if(a.id===e)return!0;let[t,r,i]=e.split("|");return a.language===r&&a.label===i},al=class a{constructor(e){this.available$=new kg;this.current$=new dL(void 0);this.error$=new kg;this.subscription=new cL;this.externalTracks=new Map;this.internalTracks=new Map;this.baseURL=e}connect(e,t,r){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();let i=s=>{this.error$.next({id:"TextTracksManager",category:pL.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(Dt(t.internalTextTracks,()=>(0,il.default)(this.internalTracks),s=>{ot(s)&&this.setInternal(s)},{equal:(s,n)=>ot(s)&&ot(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(qi(s=>s.filter(({type:n})=>n==="internal"))),onError:i})),this.subscription.add(Dt(t.externalTextTracks,()=>(0,il.default)(this.externalTracks),s=>{ot(s)&&this.setExternal(s)},{equal:(s,n)=>ot(s)&&ot(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(qi(s=>s.filter(({type:n})=>n==="external"))),onError:i})),this.subscription.add(Dt(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(Dt(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.activeCues)}))}subscribe(){Fi(this.video);let{textTracks:e}=this.video;this.subscription.add(Kr(e,"addtrack").subscribe(()=>{let r=this.current$.getValue();r&&this.select(r)})),this.subscription.add(Pg(Kr(e,"addtrack"),Kr(e,"removetrack"),wg(["init"])).pipe(qi(()=>this.htmlTextTracksAsArray().map(r=>this.htmlTextTrackToITextTrack(r))),Ag((r,i)=>r.length===i.length&&r.every(({id:s},n)=>s===i[n].id))).subscribe(this.available$)),this.subscription.add(Pg(Kr(e,"change"),wg(["init"])).pipe(qi(()=>this.htmlTextTracksAsArray().find(({mode:r})=>r==="showing")),qi(r=>r&&this.htmlTextTrackToITextTrack(r).id),Ag()).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(Kr(e,"addtrack").subscribe(r=>{var s,n;(s=r.track)==null||s.addEventListener("cuechange",t);let i=o=>{var l,c,d,p,h;let u=(c=(l=o.target)==null?void 0:l.cues)!=null?c:null;u&&u.length&&(this.applyCueSettings((p=(d=o.target)==null?void 0:d.cues)!=null?p:null),(h=o.target)==null||h.removeEventListener("cuechange",i))};(n=r.track)==null||n.addEventListener("cuechange",i)})),this.subscription.add(Kr(e,"removetrack").subscribe(r=>{var i;(i=r.track)==null||i.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;let t=this.cueSettings.getState();for(let r of Array.from(e)){let i=r;ot(t.align)&&(i.align=t.align),ot(t.position)&&(i.position=t.position),ot(t.size)&&(i.size=t.size),ot(t.line)&&(i.line=t.line)}}htmlTextTracksAsArray(e=!1){Fi(this.video);let t=[...this.video.textTracks];return e?t:t.filter(a.isHealthyTrack)}htmlTextTrackToITextTrack(e){var o,u,l,c,d;let{language:t,label:r}=e,i=e.id?e.id:hL(e),s=this.externalTracks.has(i),n=(l=s?(o=this.externalTracks.get(i))==null?void 0:o.isAuto:(u=this.internalTracks.get(i))==null?void 0:u.isAuto)!=null?l:i.includes("auto");return s?{id:i,type:"external",isAuto:n,language:t,label:r,url:(c=this.externalTracks.get(i))==null?void 0:c.url}:{id:i,type:"internal",isAuto:n,language:t,label:r,url:(d=this.internalTracks.get(i))==null?void 0:d.url}}static isHealthyTrack(e){return!(e.kind==="metadata"||e.groupId||e.id===""&&e.label===""&&e.language==="")}setExternal(e){this.internalTracks.size>0&&Array.from(this.internalTracks).forEach(([,t])=>this.detach(t)),e.filter(({id:t})=>!this.externalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.externalTracks).filter(([t])=>!e.find(r=>r.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){let t=[...this.externalTracks];e.filter(({id:r,language:i,isAuto:s})=>!this.internalTracks.has(r)&&!t.some(([,n])=>n.language===i&&n.isAuto===s)).forEach(r=>this.attach(r)),Array.from(this.internalTracks).filter(([r])=>!e.find(i=>i.id===r)).forEach(([,r])=>this.detach(r))}select(e){Fi(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(lL(e)||!mL(t,e))&&(t.mode="disabled")}destroy(){if(this.subscription.unsubscribe(),this.video)for(let e of Array.from(this.video.getElementsByTagName("track"))){let t=e.getAttribute("id");t&&this.externalTracks.has(t)&&this.video.removeChild(e)}this.externalTracks.clear()}attach(e){Fi(this.video);let t=document.createElement("track");this.baseURL?t.setAttribute("src",new URL(e.url,this.baseURL).toString()):t.setAttribute("src",e.url),t.setAttribute("id",e.id),e.label&&t.setAttribute("label",e.label),e.language&&t.setAttribute("srclang",e.language),e.type==="external"?this.externalTracks.set(e.id,e):e.type==="internal"&&this.internalTracks.set(e.id,e),this.video.appendChild(t)}detach(e){Fi(this.video);let t=Array.prototype.find.call(this.video.getElementsByTagName("track"),r=>r.getAttribute("id")===e.id);t&&this.video.removeChild(t),e.type==="external"?this.externalTracks.delete(e.id):e.type==="internal"&&this.internalTracks.delete(e.id)}},Ue=al;var pr=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 Rg=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},sl=a=>{let e=Rg(a);return!!(e&&e.fullscreenElement&&e.fullscreenElement===a)},Lg=a=>{let e=Rg(a);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===a)};import{fromEvent as He,map as Vt,merge as Ng,filterChanged as EL,isNonNullable as Fg,Subject as xL,filter as qg,mapTo as Ug,combine as PL,once as wL,ErrorCategory as AL,ValueSubject as Hg}from"@vkontakte/videoplayer-shared/es2015";var fL=3,$g=(a,e,t=fL)=>{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 Xs=class{get current(){return this._current}get isYandex(){return this.current==="Yandex"}get isSafari(){return this.current==="Safari"}get isSamsungBrowser(){return this.current==="SamsungBrowser"}get safariVersion(){return this._safariVersion}detect(){let{userAgent:e}=navigator;try{let t=/yabrowser/i.test(e)?"Yandex":void 0,r=/samsungbrowser/i.test(e)?"SamsungBrowser":void 0,i=/chrome|crios/i.test(e)?"Chrome":void 0,s=/chromium/i.test(e)?"Chromium":void 0,n=/firefox|fxios/i.test(e)?"Firefox":void 0,o=/webkit|safari|khtml/i.test(e)?"Safari":void 0,u=/opr\//i.test(e)?"Opera":void 0,l=/edg/i.test(e)?"Edge":void 0;this._current=t||r||n||u||l||i||s||o||"Rest"}catch(t){console.error(t)}this.isSafari&&this.detectSafariVersion()}detectSafariVersion(){try{let{userAgent:e}=window.navigator,t=e.match(/Version\/(\d+)/);if(!t)return;let r=t[1],i=parseInt(r,10);if(isNaN(i))return;this._safariVersion=i}catch(e){console.error(e)}}};var Mg=_(Fe(),1);var Ui=()=>{var a,e;return/Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test((a=navigator.appVersion)!=null?a:navigator.userAgent)||((e=navigator==null?void 0:navigator.userAgentData)==null?void 0:e.mobile)};var Js=class{constructor(e){this._highEntropyValues={};this._displayChecker=e}get current(){return this._current}get isIOS(){let e=["iPhone","iPad","iPod"];return this._highEntropyValues.platform==="iOS"||(0,Mg.default)(e,this.current)}get isMac(){return this._highEntropyValues.platform==="macOS"||this.current==="Mac"}get isApple(){return this.isIOS||this.isMac}get isIphoneOrOldIpad(){if(!this.isApple||!this._displayChecker.isTouch)return!1;let e=this.current==="iPad"||this._displayChecker.width>700,t=this._iosVersion;return!e||e&&!!t&&t<16}get isAndroid(){return this._highEntropyValues.platform==="Android"||this.current==="Android"}get isMobile(){return this._highEntropyValues.mobile||this._isMobile}get iOSVersion(){return this._iosVersion}detect(){let{userAgent:e}=navigator;try{this._isMobile=Ui()}catch(t){console.error(t)}this.detectDevice(e),this.detectHighEntropyValues(),this.isIOS&&this.detectIOSVersion()}detectHighEntropyValues(){return x(this,null,function*(){let{userAgentData:e}=navigator;if(e){let t=yield e.getHighEntropyValues(["architecture","bitness","brands","mobile","platform","formFactor","model","platformVersion","wow64"]);this._highEntropyValues=t}})}detectDevice(e){try{let t=/android/i.test(e)?"Android":void 0,r=/iphone/i.test(e)?"iPhone":void 0,i=/ipad/i.test(e)?"iPad":void 0,s=/ipod/i.test(e)?"iPod":void 0,n=/mac/i.test(e)?"Mac":void 0,o=/webOS|BlackBerry|IEMobile|Opera Mini/i.test(e)?"RestMobile":void 0;this._current=t||r||i||s||o||n||"Desktop"}catch(t){console.error(t)}}detectIOSVersion(){try{if(this._highEntropyValues.platformVersion){let s=this._highEntropyValues.platformVersion.split(".").slice(0,2).join("."),n=parseFloat(s);this._iosVersion=n;return}let{userAgent:e}=window.navigator,t=e.match(/OS (\d+(_\d+)?)/i);if(!t)return;let r=t[1].replace(/_/g,".");if(!r)return;let i=parseFloat(r);if(isNaN(i))return;this._iosVersion=i}catch(e){console.error(e)}}};var Zs=class{get isTouch(){return typeof this._maxTouchPoints=="number"?this._maxTouchPoints>1:"ontouchstart"in window}get maxTouchPoints(){return this._maxTouchPoints}get height(){return this._height}get width(){return this._width}get screenHeight(){return this._screenHeight}get screenWidth(){return this._screenWidth}get pixelRatio(){return this._pixelRatio}get isHDR(){return this._isHdr}get colorDepth(){return this._colorDepth}detect(){var t;let{maxTouchPoints:e}=navigator;try{this._maxTouchPoints=e!=null?e:0,this._isHdr=!!((t=matchMedia("(dynamic-range: high)"))!=null&&t.matches),this._colorDepth=screen.colorDepth}catch(r){console.error(r)}try{this._pixelRatio=window.devicePixelRatio||1,this._height=screen.height,this._width=screen.width,this._height=screen.height,this._screenHeight=this._height*this._pixelRatio,this._screenWidth=this._width*this._pixelRatio}catch(r){console.error(r)}}};var Je=()=>window.ManagedMediaSource||window.MediaSource,en=()=>{var a,e;return!!(window.ManagedMediaSource&&((e=(a=window.ManagedSourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},Cg=()=>{var a,e;return!!(window.MediaSource&&((e=(a=window.SourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},Dg=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;var bL=document.createElement("video"),gL='video/mp4; codecs="avc1.42000a,mp4a.40.2"',vL='video/mp4; codecs="hev1.1.6.L93.B0"',Vg='video/webm; codecs="vp09.00.10.08"',_g='video/webm; codecs="av01.0.00M.08"',SL='audio/mp4; codecs="mp4a.40.2"',yL='audio/webm; codecs="opus"',Og,TL=()=>x(void 0,null,function*(){if(!window.navigator.mediaCapabilities)return;let a={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=yield Promise.all([window.navigator.mediaCapabilities.decodingInfo($(P({},a),{video:$(P({},a.video),{contentType:_g})})),window.navigator.mediaCapabilities.decodingInfo($(P({},a),{video:$(P({},a.video),{contentType:Vg})}))]);Og={DASH_WEBM_AV1:e,DASH_WEBM:t}});TL().catch(a=>{console.log(bL),console.error(a)});var tn=class{constructor(e,t){this._deviceChecker=e,this._browserChecker=t}get protocols(){return this._protocols}get containers(){return this._containers}get codecs(){return this._codecs}get webmDecodingInfo(){return Og}get supportedCodecs(){return Object.keys(this._codecs).filter(e=>this._codecs[e])}get nativeHlsSupported(){return this._nativeHlsSupported}detect(){var e,t,r,i,s,n,o,u,l,c,d,p,h,m,b,g,v,S,y,I;this._video=document.createElement("video");try{this._protocols={mms:en(),mse:Cg(),hls:!!((t=(e=this._video).canPlayType)!=null&&t.call(e,"application/x-mpegurl")||(i=(r=this._video).canPlayType)!=null&&i.call(r,"vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},this._containers={mp4:!!((n=(s=this._video).canPlayType)!=null&&n.call(s,"video/mp4")),webm:!!((u=(o=this._video).canPlayType)!=null&&u.call(o,"video/webm")),cmaf:!0};let E=!!((c=(l=Je())==null?void 0:l.isTypeSupported)!=null&&c.call(l,gL)),R=!!((p=(d=Je())==null?void 0:d.isTypeSupported)!=null&&p.call(d,vL)),M=!!((m=(h=Je())==null?void 0:h.isTypeSupported)!=null&&m.call(h,SL));this._codecs={h264:E,h265:R,vp9:!!((g=(b=Je())==null?void 0:b.isTypeSupported)!=null&&g.call(b,Vg)),av1:!!((S=(v=Je())==null?void 0:v.isTypeSupported)!=null&&S.call(v,_g)),aac:M,opus:!!((I=(y=Je())==null?void 0:y.isTypeSupported)!=null&&I.call(y,yL)),mpeg:(E||R)&&M},this._nativeHlsSupported=this._protocols.hls&&this._containers.mp4}catch(E){console.error(E)}this.destroyVideoElement()}destroyVideoElement(){var t;if(!this._video)return;if(this._video.pause(),this._video.currentTime=0,this._video.removeAttribute("src"),this._video.src="",this._video.load(),this._video.remove){this._video.remove(),this._video=null;return}this._video.parentNode&&this._video.parentNode.removeChild(this._video);let e=this._video.cloneNode(!1);(t=this._video.parentNode)==null||t.replaceChild(e,this._video),this._video=null}};var Bg="audio/mpeg",rn=class{supportMp3(){return this._codecs.mp3&&this._containers.mpeg}detect(){var e,t,r,i;this._audio=document.createElement("audio");try{this._containers={mpeg:!!((t=(e=this._audio).canPlayType)!=null&&t.call(e,Bg))},this._codecs={mp3:!!((i=(r=Je())==null?void 0:r.isTypeSupported)!=null&&i.call(r,Bg))}}catch(s){console.error(s)}this.destroyAudioElement()}destroyAudioElement(){var t;if(!this._audio)return;if(this._audio.pause(),this._audio.currentTime=0,this._audio.removeAttribute("src"),this._audio.src="",this._audio.load(),this._audio.remove){this._audio.remove(),this._audio=null;return}this._audio.parentNode&&this._audio.parentNode.removeChild(this._audio);let e=this._audio.cloneNode(!1);(t=this._audio.parentNode)==null||t.replaceChild(e,this._audio),this._audio=null}};import{ValueSubject as IL}from"@vkontakte/videoplayer-shared/es2015";var nl=class{constructor(){this.isInited$=new IL(!1);this._displayChecker=new Zs,this._deviceChecker=new Js(this._displayChecker),this._browserChecker=new Xs,this._videoChecker=new tn(this._deviceChecker,this._browserChecker),this._audioChecker=new rn,this.detect()}get display(){return this._displayChecker}get device(){return this._deviceChecker}get browser(){return this._browserChecker}get video(){return this._videoChecker}get audio(){return this._audioChecker}detect(){return x(this,null,function*(){this._displayChecker.detect(),this._deviceChecker.detect(),this._browserChecker.detect(),this._videoChecker.detect(),this._audioChecker.detect(),this.isInited$.next(!0)})}},N=new nl;var ke=a=>{let e=y=>He(a,y).pipe(Ug(void 0)),r=Ng(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(y=>He(a,y))).pipe(Vt(y=>y.type==="ended"?a.readyState<2:a.readyState<3),EL()),i=Ng(He(a,"progress"),He(a,"timeupdate")).pipe(Vt(()=>$g(a.buffered,a.currentTime))),s=N.browser.isSafari?PL({play:e("play").pipe(wL()),playing:e("playing")}).pipe(Ug(void 0)):e("playing"),n=He(a,"volumechange").pipe(Vt(()=>({muted:a.muted,volume:a.volume}))),o=He(a,"ratechange").pipe(Vt(()=>a.playbackRate)),u=He(a,"error").pipe(qg(()=>!!(a.error||a.played.length)),Vt(()=>{var I;let y=a.error;return{id:y?`MediaError#${y.code}`:"HtmlVideoError",category:AL.VIDEO_PIPELINE,message:y?y.message:"Error event from HTML video element",thrown:(I=a.error)!=null?I:void 0}})),l=He(a,"timeupdate").pipe(Vt(()=>a.currentTime)),c=new xL,d=.3,p;l.subscribe(y=>{a.loop&&Fg(p)&&Fg(y)&&p>=a.duration-d&&y<=d&&c.next(p),p=y});let h=e("pause").pipe(qg(()=>!a.error&&p!==a.duration)),m=He(a,"enterpictureinpicture"),b=He(a,"leavepictureinpicture"),g=new Hg(Lg(a));m.subscribe(()=>g.next(!0)),b.subscribe(()=>g.next(!1));let v=new Hg(sl(a));return He(a,"fullscreenchange").pipe(Vt(()=>sl(a))).subscribe(v),{playing$:s,pause$:h,canplay$:e("canplay"),ended$:e("ended"),looped$:c,error$:u,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:l,durationChange$:He(a,"durationchange").pipe(Vt(()=>a.duration)),isBuffering$:r,currentBuffer$:i,volumeState$:n,playbackRateState$:o,inPiP$:g,inFullscreen$:v,enterPip$:m,leavePip$:b}};import{VideoQuality as _t}from"@vkontakte/videoplayer-shared/es2015";var Ot=a=>{switch(a){case"mobile":return _t.Q_144P;case"lowest":return _t.Q_240P;case"low":return _t.Q_360P;case"sd":case"medium":return _t.Q_480P;case"hd":case"high":return _t.Q_720P;case"fullhd":case"full":return _t.Q_1080P;case"quadhd":case"quad":return _t.Q_1440P;case"ultrahd":case"ultra":return _t.Q_2160P}};var Nt=_(Bt(),1),sv=_(Fe(),1),nn=_(Br(),1);import{isNonNullable as Oe,isNullable as tv,now as nv,isHigher as rv,isHigherOrEqual as cl,isInvariantQuality as iv,isLowerOrEqual as dl,videoSizeToQuality as BL,assertNotEmptyArray as ov,assertNonNullable as NL}from"@vkontakte/videoplayer-shared/es2015";var ol=!1,bt={},Kg=a=>{ol=a},Xg=()=>{bt={}},Jg=a=>{a(bt)},Hi=(a,e)=>{var t;ol&&(bt.meta=(t=bt.meta)!=null?t:{},bt.meta[a]=e)},Ie=class{constructor(e){this.name=e}next(e){var r,i;if(!ol)return;bt.series=(r=bt.series)!=null?r:{};let t=(i=bt.series[this.name])!=null?i:[];t.push([Date.now(),e]),bt.series[this.name]=t}};import{isHigher as _L,isHigherOrEqual as HN,isLower as Zg,isLowerOrEqual as jN,isNonNullable as an,isNullable as OL,videoHeightToQuality as sn}from"@vkontakte/videoplayer-shared/es2015";function ul({limits:a,highQualityLimit:e,trafficSavingLimit:t}){return!a.max&&a.min===e?"high_quality":!a.min&&a.max===t?"traffic_saving":"unknown"}function ll({limits:a,highQualityLimit:e,trafficSavingLimit:t}){return!!a&&ul({limits:a,highQualityLimit:e,trafficSavingLimit:t})==="high_quality"}function ji({limits:a,highestAvailableQuality:e,lowestAvailableQuality:t}){return OL(a)||an(a.min)&&an(a.max)&&Zg(a.max,a.min)||an(a.min)&&e&&_L(a.min,e)||an(a.max)&&t&&Zg(a.max,t)}function ev({limits:a,highestAvailableHeight:e,lowestAvailableHeight:t}){return ji({limits:{max:a!=null&&a.max?sn(a.max):void 0,min:a!=null&&a.min?sn(a.min):void 0},highestAvailableQuality:e?sn(e):void 0,lowestAvailableQuality:t?sn(t):void 0})}var FL=new Ie("best_bitrate"),uv=(a,e,t)=>(e-t)*Math.pow(2,-10*a)+t;var pl=a=>(e,t)=>a*(Number(e.bitrate)-Number(t.bitrate)),Qi=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=nv()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},lv='Assertion "ABR Tracks is empty array" failed',on=(a,e,t,r)=>{var u;let i=[...e].sort(pl(1)),s=[...t].sort(pl(1)),n=s.filter(l=>Oe(l.bitrate)&&Oe(a.bitrate)?a.bitrate/l.bitrate>r:!0),o=(u=(0,Nt.default)(s,Math.round(s.length*i.indexOf(a)/(i.length+1))))!=null?u:(0,Nt.default)(s,-1);return o&&(0,sv.default)(n,o)?o:n.length?(0,Nt.default)(n,-1):(0,Nt.default)(s,0)},av=a=>"quality"in a,cv=(a,e,t,r)=>{var n;let i=Oe((n=r==null?void 0:r.last)==null?void 0:n.bitrate)&&Oe(t==null?void 0:t.bitrate)&&r.last.bitrate<t.bitrate?a.trackCooldownIncreaseQuality:a.trackCooldownDecreaseQuality,s=t&&r&&r.history[t.id]&&nv()-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=av(o)?"video":"audio",l=av(o)?o.quality:o.bitrate;return e({message:`
|
|
6
|
+
var eI=Object.create;var ao=Object.defineProperty,tI=Object.defineProperties,rI=Object.getOwnPropertyDescriptor,iI=Object.getOwnPropertyDescriptors,aI=Object.getOwnPropertyNames,hs=Object.getOwnPropertySymbols,sI=Object.getPrototypeOf,so=Object.prototype.hasOwnProperty,bd=Object.prototype.propertyIsEnumerable;var nI=(a,e)=>(e=Symbol[a])?e:Symbol.for("Symbol."+a);var at=Math.pow,fd=(a,e,t)=>e in a?ao(a,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):a[e]=t,P=(a,e)=>{for(var t in e||(e={}))so.call(e,t)&&fd(a,t,e[t]);if(hs)for(var t of hs(e))bd.call(e,t)&&fd(a,t,e[t]);return a},M=(a,e)=>tI(a,iI(e));var gd=(a,e)=>{var t={};for(var r in a)so.call(a,r)&&e.indexOf(r)<0&&(t[r]=a[r]);if(a!=null&&hs)for(var r of hs(a))e.indexOf(r)<0&&bd.call(a,r)&&(t[r]=a[r]);return t};var f=(a,e)=>()=>(e||a((e={exports:{}}).exports,e),e.exports);var oI=(a,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of aI(e))!so.call(a,i)&&i!==t&&ao(a,i,{get:()=>e[i],enumerable:!(r=rI(e,i))||r.enumerable});return a};var B=(a,e,t)=>(t=a!=null?eI(sI(a)):{},oI(e||!a||!a.__esModule?ao(t,"default",{value:a,enumerable:!0}):t,a));var E=(a,e,t)=>new Promise((r,i)=>{var s=u=>{try{o(t.next(u))}catch(l){i(l)}},n=u=>{try{o(t.throw(u))}catch(l){i(l)}},o=u=>u.done?r(u.value):Promise.resolve(u.value).then(s,n);o((t=t.apply(a,e)).next())}),ms=function(a,e){this[0]=a,this[1]=e},ue=(a,e,t)=>{var r=(n,o,u,l)=>{try{var c=t[n](o),d=(o=c.value)instanceof ms,p=c.done;Promise.resolve(d?o[0]:o).then(h=>d?r(n==="return"?n:"next",o[1]?{done:h.done,value:h.value}:h,u,l):u({value:h,done:p})).catch(h=>r("throw",h,u,l))}catch(h){l(h)}},i=n=>s[n]=o=>new Promise((u,l)=>r(n,o,u,l)),s={};return t=t.apply(a,e),s[nI("asyncIterator")]=()=>s,i("next"),i("throw"),i("return"),s};var ne=f((uo,Sd)=>{"use strict";var gi=function(a){return a&&a.Math===Math&&a};Sd.exports=gi(typeof globalThis=="object"&&globalThis)||gi(typeof window=="object"&&window)||gi(typeof self=="object"&&self)||gi(typeof global=="object"&&global)||gi(typeof uo=="object"&&uo)||function(){return this}()||Function("return this")()});var me=f((O0,yd)=>{"use strict";yd.exports=function(a){try{return!!a()}catch(e){return!0}}});var vi=f((_0,Td)=>{"use strict";var uI=me();Td.exports=!uI(function(){var a=function(){}.bind();return typeof a!="function"||a.hasOwnProperty("prototype")})});var lo=f((B0,Pd)=>{"use strict";var lI=vi(),xd=Function.prototype,Id=xd.apply,Ed=xd.call;Pd.exports=typeof Reflect=="object"&&Reflect.apply||(lI?Ed.bind(Id):function(){return Ed.apply(Id,arguments)})});var ce=f((N0,kd)=>{"use strict";var wd=vi(),Ad=Function.prototype,co=Ad.call,cI=wd&&Ad.bind.bind(co,co);kd.exports=wd?cI:function(a){return function(){return co.apply(a,arguments)}}});var tr=f((F0,Rd)=>{"use strict";var $d=ce(),dI=$d({}.toString),pI=$d("".slice);Rd.exports=function(a){return pI(dI(a),8,-1)}});var po=f((q0,Ld)=>{"use strict";var hI=tr(),mI=ce();Ld.exports=function(a){if(hI(a)==="Function")return mI(a)}});var ae=f((U0,Md)=>{"use strict";var ho=typeof document=="object"&&document.all;Md.exports=typeof ho=="undefined"&&ho!==void 0?function(a){return typeof a=="function"||a===ho}:function(a){return typeof a=="function"}});var Ce=f((H0,Dd)=>{"use strict";var fI=me();Dd.exports=!fI(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var Ve=f((j0,Cd)=>{"use strict";var bI=vi(),gs=Function.prototype.call;Cd.exports=bI?gs.bind(gs):function(){return gs.apply(gs,arguments)}});var mo=f(_d=>{"use strict";var Vd={}.propertyIsEnumerable,Od=Object.getOwnPropertyDescriptor,gI=Od&&!Vd.call({1:2},1);_d.f=gI?function(e){var t=Od(this,e);return!!t&&t.enumerable}:Vd});var Si=f((G0,Bd)=>{"use strict";Bd.exports=function(a,e){return{enumerable:!(a&1),configurable:!(a&2),writable:!(a&4),value:e}}});var Fd=f((W0,Nd)=>{"use strict";var vI=ce(),SI=me(),yI=tr(),fo=Object,TI=vI("".split);Nd.exports=SI(function(){return!fo("z").propertyIsEnumerable(0)})?function(a){return yI(a)==="String"?TI(a,""):fo(a)}:fo});var $r=f((Y0,qd)=>{"use strict";qd.exports=function(a){return a==null}});var Lt=f((z0,Ud)=>{"use strict";var II=$r(),EI=TypeError;Ud.exports=function(a){if(II(a))throw new EI("Can't call method on "+a);return a}});var rr=f((K0,Hd)=>{"use strict";var xI=Fd(),PI=Lt();Hd.exports=function(a){return xI(PI(a))}});var Oe=f((X0,jd)=>{"use strict";var wI=ae();jd.exports=function(a){return typeof a=="object"?a!==null:wI(a)}});var Rr=f((J0,Qd)=>{"use strict";Qd.exports={}});var ht=f((Z0,Wd)=>{"use strict";var bo=Rr(),go=ne(),AI=ae(),Gd=function(a){return AI(a)?a:void 0};Wd.exports=function(a,e){return arguments.length<2?Gd(bo[a])||Gd(go[a]):bo[a]&&bo[a][e]||go[a]&&go[a][e]}});var yi=f((eV,Yd)=>{"use strict";var kI=ce();Yd.exports=kI({}.isPrototypeOf)});var ir=f((tV,Xd)=>{"use strict";var $I=ne(),zd=$I.navigator,Kd=zd&&zd.userAgent;Xd.exports=Kd?String(Kd):""});var So=f((rV,ip)=>{"use strict";var rp=ne(),vo=ir(),Jd=rp.process,Zd=rp.Deno,ep=Jd&&Jd.versions||Zd&&Zd.version,tp=ep&&ep.v8,ze,vs;tp&&(ze=tp.split("."),vs=ze[0]>0&&ze[0]<4?1:+(ze[0]+ze[1]));!vs&&vo&&(ze=vo.match(/Edge\/(\d+)/),(!ze||ze[1]>=74)&&(ze=vo.match(/Chrome\/(\d+)/),ze&&(vs=+ze[1])));ip.exports=vs});var yo=f((iV,sp)=>{"use strict";var ap=So(),RI=me(),LI=ne(),MI=LI.String;sp.exports=!!Object.getOwnPropertySymbols&&!RI(function(){var a=Symbol("symbol detection");return!MI(a)||!(Object(a)instanceof Symbol)||!Symbol.sham&&ap&&ap<41})});var To=f((aV,np)=>{"use strict";var DI=yo();np.exports=DI&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var Io=f((sV,op)=>{"use strict";var CI=ht(),VI=ae(),OI=yi(),_I=To(),BI=Object;op.exports=_I?function(a){return typeof a=="symbol"}:function(a){var e=CI("Symbol");return VI(e)&&OI(e.prototype,BI(a))}});var Ti=f((nV,up)=>{"use strict";var NI=String;up.exports=function(a){try{return NI(a)}catch(e){return"Object"}}});var st=f((oV,lp)=>{"use strict";var FI=ae(),qI=Ti(),UI=TypeError;lp.exports=function(a){if(FI(a))return a;throw new UI(qI(a)+" is not a function")}});var Ii=f((uV,cp)=>{"use strict";var HI=st(),jI=$r();cp.exports=function(a,e){var t=a[e];return jI(t)?void 0:HI(t)}});var pp=f((lV,dp)=>{"use strict";var Eo=Ve(),xo=ae(),Po=Oe(),QI=TypeError;dp.exports=function(a,e){var t,r;if(e==="string"&&xo(t=a.toString)&&!Po(r=Eo(t,a))||xo(t=a.valueOf)&&!Po(r=Eo(t,a))||e!=="string"&&xo(t=a.toString)&&!Po(r=Eo(t,a)))return r;throw new QI("Can't convert object to primitive value")}});var Ke=f((cV,hp)=>{"use strict";hp.exports=!0});var bp=f((dV,fp)=>{"use strict";var mp=ne(),GI=Object.defineProperty;fp.exports=function(a,e){try{GI(mp,a,{value:e,configurable:!0,writable:!0})}catch(t){mp[a]=e}return e}});var Ei=f((pV,Sp)=>{"use strict";var WI=Ke(),YI=ne(),zI=bp(),gp="__core-js_shared__",vp=Sp.exports=YI[gp]||zI(gp,{});(vp.versions||(vp.versions=[])).push({version:"3.38.0",mode:WI?"pure":"global",copyright:"\xA9 2014-2024 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.38.0/LICENSE",source:"https://github.com/zloirock/core-js"})});var wo=f((hV,Tp)=>{"use strict";var yp=Ei();Tp.exports=function(a,e){return yp[a]||(yp[a]=e||{})}});var Lr=f((mV,Ip)=>{"use strict";var KI=Lt(),XI=Object;Ip.exports=function(a){return XI(KI(a))}});var Xe=f((fV,Ep)=>{"use strict";var JI=ce(),ZI=Lr(),eE=JI({}.hasOwnProperty);Ep.exports=Object.hasOwn||function(e,t){return eE(ZI(e),t)}});var Ao=f((bV,xp)=>{"use strict";var tE=ce(),rE=0,iE=Math.random(),aE=tE(1 .toString);xp.exports=function(a){return"Symbol("+(a===void 0?"":a)+")_"+aE(++rE+iE,36)}});var fe=f((gV,wp)=>{"use strict";var sE=ne(),nE=wo(),Pp=Xe(),oE=Ao(),uE=yo(),lE=To(),Mr=sE.Symbol,ko=nE("wks"),cE=lE?Mr.for||Mr:Mr&&Mr.withoutSetter||oE;wp.exports=function(a){return Pp(ko,a)||(ko[a]=uE&&Pp(Mr,a)?Mr[a]:cE("Symbol."+a)),ko[a]}});var Rp=f((vV,$p)=>{"use strict";var dE=Ve(),Ap=Oe(),kp=Io(),pE=Ii(),hE=pp(),mE=fe(),fE=TypeError,bE=mE("toPrimitive");$p.exports=function(a,e){if(!Ap(a)||kp(a))return a;var t=pE(a,bE),r;if(t){if(e===void 0&&(e="default"),r=dE(t,a,e),!Ap(r)||kp(r))return r;throw new fE("Can't convert object to primitive value")}return e===void 0&&(e="number"),hE(a,e)}});var $o=f((SV,Lp)=>{"use strict";var gE=Rp(),vE=Io();Lp.exports=function(a){var e=gE(a,"string");return vE(e)?e:e+""}});var Ss=f((yV,Dp)=>{"use strict";var SE=ne(),Mp=Oe(),Ro=SE.document,yE=Mp(Ro)&&Mp(Ro.createElement);Dp.exports=function(a){return yE?Ro.createElement(a):{}}});var Lo=f((TV,Cp)=>{"use strict";var TE=Ce(),IE=me(),EE=Ss();Cp.exports=!TE&&!IE(function(){return Object.defineProperty(EE("div"),"a",{get:function(){return 7}}).a!==7})});var _p=f(Op=>{"use strict";var xE=Ce(),PE=Ve(),wE=mo(),AE=Si(),kE=rr(),$E=$o(),RE=Xe(),LE=Lo(),Vp=Object.getOwnPropertyDescriptor;Op.f=xE?Vp:function(e,t){if(e=kE(e),t=$E(t),LE)try{return Vp(e,t)}catch(r){}if(RE(e,t))return AE(!PE(wE.f,e,t),e[t])}});var Mo=f((EV,Bp)=>{"use strict";var ME=me(),DE=ae(),CE=/#|\.prototype\./,xi=function(a,e){var t=OE[VE(a)];return t===BE?!0:t===_E?!1:DE(e)?ME(e):!!e},VE=xi.normalize=function(a){return String(a).replace(CE,".").toLowerCase()},OE=xi.data={},_E=xi.NATIVE="N",BE=xi.POLYFILL="P";Bp.exports=xi});var Dr=f((xV,Fp)=>{"use strict";var Np=po(),NE=st(),FE=vi(),qE=Np(Np.bind);Fp.exports=function(a,e){return NE(a),e===void 0?a:FE?qE(a,e):function(){return a.apply(e,arguments)}}});var Do=f((PV,qp)=>{"use strict";var UE=Ce(),HE=me();qp.exports=UE&&HE(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var nt=f((wV,Up)=>{"use strict";var jE=Oe(),QE=String,GE=TypeError;Up.exports=function(a){if(jE(a))return a;throw new GE(QE(a)+" is not an object")}});var ar=f(jp=>{"use strict";var WE=Ce(),YE=Lo(),zE=Do(),ys=nt(),Hp=$o(),KE=TypeError,Co=Object.defineProperty,XE=Object.getOwnPropertyDescriptor,Vo="enumerable",Oo="configurable",_o="writable";jp.f=WE?zE?function(e,t,r){if(ys(e),t=Hp(t),ys(r),typeof e=="function"&&t==="prototype"&&"value"in r&&_o in r&&!r[_o]){var i=XE(e,t);i&&i[_o]&&(e[t]=r.value,r={configurable:Oo in r?r[Oo]:i[Oo],enumerable:Vo in r?r[Vo]:i[Vo],writable:!1})}return Co(e,t,r)}:Co:function(e,t,r){if(ys(e),t=Hp(t),ys(r),YE)try{return Co(e,t,r)}catch(i){}if("get"in r||"set"in r)throw new KE("Accessors not supported");return"value"in r&&(e[t]=r.value),e}});var Cr=f((kV,Qp)=>{"use strict";var JE=Ce(),ZE=ar(),ex=Si();Qp.exports=JE?function(a,e,t){return ZE.f(a,e,ex(1,t))}:function(a,e,t){return a[e]=t,a}});var le=f(($V,Wp)=>{"use strict";var Pi=ne(),tx=lo(),rx=po(),ix=ae(),ax=_p().f,sx=Mo(),Vr=Rr(),nx=Dr(),Or=Cr(),Gp=Xe();Ei();var ox=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 tx(a,this,arguments)};return e.prototype=a.prototype,e};Wp.exports=function(a,e){var t=a.target,r=a.global,i=a.stat,s=a.proto,n=r?Pi:i?Pi[t]:Pi[t]&&Pi[t].prototype,o=r?Vr:Vr[t]||Or(Vr,t,{})[t],u=o.prototype,l,c,d,p,h,m,b,g,v;for(p in e)l=sx(r?p:t+(i?".":"#")+p,a.forced),c=!l&&n&&Gp(n,p),m=o[p],c&&(a.dontCallGetSet?(v=ax(n,p),b=v&&v.value):b=n[p]),h=c&&b?b:e[p],!(!l&&!s&&typeof m==typeof h)&&(a.bind&&c?g=nx(h,Pi):a.wrap&&c?g=ox(h):s&&ix(h)?g=rx(h):g=h,(a.sham||h&&h.sham||m&&m.sham)&&Or(g,"sham",!0),Or(o,p,g),s&&(d=t+"Prototype",Gp(Vr,d)||Or(Vr,d,{}),Or(Vr[d],p,h),a.real&&u&&(l||!u[p])&&Or(u,p,h)))}});var zp=f((RV,Yp)=>{"use strict";var ux=Math.ceil,lx=Math.floor;Yp.exports=Math.trunc||function(e){var t=+e;return(t>0?lx:ux)(t)}});var wi=f((LV,Kp)=>{"use strict";var cx=zp();Kp.exports=function(a){var e=+a;return e!==e||e===0?0:cx(e)}});var Jp=f((MV,Xp)=>{"use strict";var dx=wi(),px=Math.max,hx=Math.min;Xp.exports=function(a,e){var t=dx(a);return t<0?px(t+e,0):hx(t,e)}});var Bo=f((DV,Zp)=>{"use strict";var mx=wi(),fx=Math.min;Zp.exports=function(a){var e=mx(a);return e>0?fx(e,9007199254740991):0}});var _r=f((CV,eh)=>{"use strict";var bx=Bo();eh.exports=function(a){return bx(a.length)}});var No=f((VV,rh)=>{"use strict";var gx=rr(),vx=Jp(),Sx=_r(),th=function(a){return function(e,t,r){var i=gx(e),s=Sx(i);if(s===0)return!a&&-1;var n=vx(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}};rh.exports={includes:th(!0),indexOf:th(!1)}});var Ai=f((OV,ih)=>{"use strict";ih.exports=function(){}});var ah=f(()=>{"use strict";var yx=le(),Tx=No().includes,Ix=me(),Ex=Ai(),xx=Ix(function(){return!Array(1).includes()});yx({target:"Array",proto:!0,forced:xx},{includes:function(e){return Tx(this,e,arguments.length>1?arguments[1]:void 0)}});Ex("includes")});var Mt=f((NV,sh)=>{"use strict";var Px=ht();sh.exports=Px});var oh=f((FV,nh)=>{"use strict";ah();var wx=Mt();nh.exports=wx("Array","includes")});var lh=f((qV,uh)=>{"use strict";var Ax=oh();uh.exports=Ax});var Fe=f((UV,ch)=>{"use strict";var kx=lh();ch.exports=kx});var Es=f((eO,vh)=>{"use strict";var Ox=wo(),_x=Ao(),gh=Ox("keys");vh.exports=function(a){return gh[a]||(gh[a]=_x(a))}});var yh=f((tO,Sh)=>{"use strict";var Bx=me();Sh.exports=!Bx(function(){function a(){}return a.prototype.constructor=null,Object.getPrototypeOf(new a)!==a.prototype})});var xs=f((rO,Ih)=>{"use strict";var Nx=Xe(),Fx=ae(),qx=Lr(),Ux=Es(),Hx=yh(),Th=Ux("IE_PROTO"),Uo=Object,jx=Uo.prototype;Ih.exports=Hx?Uo.getPrototypeOf:function(a){var e=qx(a);if(Nx(e,Th))return e[Th];var t=e.constructor;return Fx(t)&&e instanceof t?t.prototype:e instanceof Uo?jx:null}});var Ps=f((iO,Eh)=>{"use strict";Eh.exports={}});var wh=f((aO,Ph)=>{"use strict";var Qx=ce(),Ho=Xe(),Gx=rr(),Wx=No().indexOf,Yx=Ps(),xh=Qx([].push);Ph.exports=function(a,e){var t=Gx(a),r=0,i=[],s;for(s in t)!Ho(Yx,s)&&Ho(t,s)&&xh(i,s);for(;e.length>r;)Ho(t,s=e[r++])&&(~Wx(i,s)||xh(i,s));return i}});var jo=f((sO,Ah)=>{"use strict";Ah.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var Qo=f((nO,kh)=>{"use strict";var zx=wh(),Kx=jo();kh.exports=Object.keys||function(e){return zx(e,Kx)}});var Go=f((oO,Dh)=>{"use strict";var Rh=Ce(),Xx=me(),Lh=ce(),Jx=xs(),Zx=Qo(),eP=rr(),tP=mo().f,Mh=Lh(tP),rP=Lh([].push),iP=Rh&&Xx(function(){var a=Object.create(null);return a[2]=2,!Mh(a,2)}),$h=function(a){return function(e){for(var t=eP(e),r=Zx(t),i=iP&&Jx(t)===null,s=r.length,n=0,o=[],u;s>n;)u=r[n++],(!Rh||(i?u in t:Mh(t,u)))&&rP(o,a?[u,t[u]]:t[u]);return o}};Dh.exports={entries:$h(!0),values:$h(!1)}});var Ch=f(()=>{"use strict";var aP=le(),sP=Go().entries;aP({target:"Object",stat:!0},{entries:function(e){return sP(e)}})});var Oh=f((cO,Vh)=>{"use strict";Ch();var nP=Rr();Vh.exports=nP.Object.entries});var Bh=f((dO,_h)=>{"use strict";var oP=Oh();_h.exports=oP});var Br=f((pO,Nh)=>{"use strict";var uP=Bh();Nh.exports=uP});var sr=f((hO,Fh)=>{"use strict";Fh.exports={}});var Hh=f((mO,Uh)=>{"use strict";var lP=ne(),cP=ae(),qh=lP.WeakMap;Uh.exports=cP(qh)&&/native code/.test(String(qh))});var Ko=f((fO,Gh)=>{"use strict";var dP=Hh(),Qh=ne(),pP=Oe(),hP=Cr(),Wo=Xe(),Yo=Ei(),mP=Es(),fP=Ps(),jh="Object already initialized",zo=Qh.TypeError,bP=Qh.WeakMap,ws,ki,As,gP=function(a){return As(a)?ki(a):ws(a,{})},vP=function(a){return function(e){var t;if(!pP(e)||(t=ki(e)).type!==a)throw new zo("Incompatible receiver, "+a+" required");return t}};dP||Yo.state?(Je=Yo.state||(Yo.state=new bP),Je.get=Je.get,Je.has=Je.has,Je.set=Je.set,ws=function(a,e){if(Je.has(a))throw new zo(jh);return e.facade=a,Je.set(a,e),e},ki=function(a){return Je.get(a)||{}},As=function(a){return Je.has(a)}):(nr=mP("state"),fP[nr]=!0,ws=function(a,e){if(Wo(a,nr))throw new zo(jh);return e.facade=a,hP(a,nr,e),e},ki=function(a){return Wo(a,nr)?a[nr]:{}},As=function(a){return Wo(a,nr)});var Je,nr;Gh.exports={set:ws,get:ki,has:As,enforce:gP,getterFor:vP}});var Zo=f((bO,Yh)=>{"use strict";var Xo=Ce(),SP=Xe(),Wh=Function.prototype,yP=Xo&&Object.getOwnPropertyDescriptor,Jo=SP(Wh,"name"),TP=Jo&&function(){}.name==="something",IP=Jo&&(!Xo||Xo&&yP(Wh,"name").configurable);Yh.exports={EXISTS:Jo,PROPER:TP,CONFIGURABLE:IP}});var Kh=f(zh=>{"use strict";var EP=Ce(),xP=Do(),PP=ar(),wP=nt(),AP=rr(),kP=Qo();zh.f=EP&&!xP?Object.defineProperties:function(e,t){wP(e);for(var r=AP(t),i=kP(t),s=i.length,n=0,o;s>n;)PP.f(e,o=i[n++],r[o]);return e}});var eu=f((vO,Xh)=>{"use strict";var $P=ht();Xh.exports=$P("document","documentElement")});var au=f((SO,am)=>{"use strict";var RP=nt(),LP=Kh(),Jh=jo(),MP=Ps(),DP=eu(),CP=Ss(),VP=Es(),Zh=">",em="<",ru="prototype",iu="script",rm=VP("IE_PROTO"),tu=function(){},im=function(a){return em+iu+Zh+a+em+"/"+iu+Zh},tm=function(a){a.write(im("")),a.close();var e=a.parentWindow.Object;return a=null,e},OP=function(){var a=CP("iframe"),e="java"+iu+":",t;return a.style.display="none",DP.appendChild(a),a.src=String(e),t=a.contentWindow.document,t.open(),t.write(im("document.F=Object")),t.close(),t.F},ks,$s=function(){try{ks=new ActiveXObject("htmlfile")}catch(e){}$s=typeof document!="undefined"?document.domain&&ks?tm(ks):OP():tm(ks);for(var a=Jh.length;a--;)delete $s[ru][Jh[a]];return $s()};MP[rm]=!0;am.exports=Object.create||function(e,t){var r;return e!==null?(tu[ru]=RP(e),r=new tu,tu[ru]=null,r[rm]=e):r=$s(),t===void 0?r:LP.f(r,t)}});var Nr=f((yO,sm)=>{"use strict";var _P=Cr();sm.exports=function(a,e,t,r){return r&&r.enumerable?a[e]=t:_P(a,e,t),a}});var uu=f((TO,um)=>{"use strict";var BP=me(),NP=ae(),FP=Oe(),qP=au(),nm=xs(),UP=Nr(),HP=fe(),jP=Ke(),ou=HP("iterator"),om=!1,mt,su,nu;[].keys&&(nu=[].keys(),"next"in nu?(su=nm(nm(nu)),su!==Object.prototype&&(mt=su)):om=!0);var QP=!FP(mt)||BP(function(){var a={};return mt[ou].call(a)!==a});QP?mt={}:jP&&(mt=qP(mt));NP(mt[ou])||UP(mt,ou,function(){return this});um.exports={IteratorPrototype:mt,BUGGY_SAFARI_ITERATORS:om}});var Rs=f((IO,cm)=>{"use strict";var GP=fe(),WP=GP("toStringTag"),lm={};lm[WP]="z";cm.exports=String(lm)==="[object z]"});var $i=f((EO,dm)=>{"use strict";var YP=Rs(),zP=ae(),Ls=tr(),KP=fe(),XP=KP("toStringTag"),JP=Object,ZP=Ls(function(){return arguments}())==="Arguments",ew=function(a,e){try{return a[e]}catch(t){}};dm.exports=YP?Ls:function(a){var e,t,r;return a===void 0?"Undefined":a===null?"Null":typeof(t=ew(e=JP(a),XP))=="string"?t:ZP?Ls(e):(r=Ls(e))==="Object"&&zP(e.callee)?"Arguments":r}});var hm=f((xO,pm)=>{"use strict";var tw=Rs(),rw=$i();pm.exports=tw?{}.toString:function(){return"[object "+rw(this)+"]"}});var Ri=f((PO,fm)=>{"use strict";var iw=Rs(),aw=ar().f,sw=Cr(),nw=Xe(),ow=hm(),uw=fe(),mm=uw("toStringTag");fm.exports=function(a,e,t,r){var i=t?a:a&&a.prototype;i&&(nw(i,mm)||aw(i,mm,{configurable:!0,value:e}),r&&!iw&&sw(i,"toString",ow))}});var gm=f((wO,bm)=>{"use strict";var lw=uu().IteratorPrototype,cw=au(),dw=Si(),pw=Ri(),hw=sr(),mw=function(){return this};bm.exports=function(a,e,t,r){var i=e+" Iterator";return a.prototype=cw(lw,{next:dw(+!r,t)}),pw(a,i,!1,!0),hw[i]=mw,a}});var Sm=f((AO,vm)=>{"use strict";var fw=ce(),bw=st();vm.exports=function(a,e,t){try{return fw(bw(Object.getOwnPropertyDescriptor(a,e)[t]))}catch(r){}}});var Tm=f((kO,ym)=>{"use strict";var gw=Oe();ym.exports=function(a){return gw(a)||a===null}});var Em=f(($O,Im)=>{"use strict";var vw=Tm(),Sw=String,yw=TypeError;Im.exports=function(a){if(vw(a))return a;throw new yw("Can't set "+Sw(a)+" as a prototype")}});var lu=f((RO,xm)=>{"use strict";var Tw=Sm(),Iw=Oe(),Ew=Lt(),xw=Em();xm.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var a=!1,e={},t;try{t=Tw(Object.prototype,"__proto__","set"),t(e,[]),a=e instanceof Array}catch(r){}return function(i,s){return Ew(i),xw(s),Iw(i)&&(a?t(i,s):i.__proto__=s),i}}():void 0)});var Vm=f((LO,Cm)=>{"use strict";var Pw=le(),ww=Ve(),Ms=Ke(),Mm=Zo(),Aw=ae(),kw=gm(),Pm=xs(),wm=lu(),$w=Ri(),Rw=Cr(),cu=Nr(),Lw=fe(),Am=sr(),Dm=uu(),Mw=Mm.PROPER,Dw=Mm.CONFIGURABLE,km=Dm.IteratorPrototype,Ds=Dm.BUGGY_SAFARI_ITERATORS,Li=Lw("iterator"),$m="keys",Mi="values",Rm="entries",Lm=function(){return this};Cm.exports=function(a,e,t,r,i,s,n){kw(t,e,r);var o=function(v){if(v===i&&p)return p;if(!Ds&&v&&v in c)return c[v];switch(v){case $m:return function(){return new t(this,v)};case Mi:return function(){return new t(this,v)};case Rm:return function(){return new t(this,v)}}return function(){return new t(this)}},u=e+" Iterator",l=!1,c=a.prototype,d=c[Li]||c["@@iterator"]||i&&c[i],p=!Ds&&d||o(i),h=e==="Array"&&c.entries||d,m,b,g;if(h&&(m=Pm(h.call(new a)),m!==Object.prototype&&m.next&&(!Ms&&Pm(m)!==km&&(wm?wm(m,km):Aw(m[Li])||cu(m,Li,Lm)),$w(m,u,!0,!0),Ms&&(Am[u]=Lm))),Mw&&i===Mi&&d&&d.name!==Mi&&(!Ms&&Dw?Rw(c,"name",Mi):(l=!0,p=function(){return ww(d,this)})),i)if(b={values:o(Mi),keys:s?p:o($m),entries:o(Rm)},n)for(g in b)(Ds||l||!(g in c))&&cu(c,g,b[g]);else Pw({target:e,proto:!0,forced:Ds||l},b);return(!Ms||n)&&c[Li]!==p&&cu(c,Li,p,{name:i}),Am[e]=p,b}});var _m=f((MO,Om)=>{"use strict";Om.exports=function(a,e){return{value:a,done:e}}});var pu=f((DO,Um)=>{"use strict";var Cw=rr(),du=Ai(),Bm=sr(),Fm=Ko(),Vw=ar().f,Ow=Vm(),Cs=_m(),_w=Ke(),Bw=Ce(),qm="Array Iterator",Nw=Fm.set,Fw=Fm.getterFor(qm);Um.exports=Ow(Array,"Array",function(a,e){Nw(this,{type:qm,target:Cw(a),index:0,kind:e})},function(){var a=Fw(this),e=a.target,t=a.index++;if(!e||t>=e.length)return a.target=void 0,Cs(void 0,!0);switch(a.kind){case"keys":return Cs(t,!1);case"values":return Cs(e[t],!1)}return Cs([t,e[t]],!1)},"values");var Nm=Bm.Arguments=Bm.Array;du("keys");du("values");du("entries");if(!_w&&Bw&&Nm.name!=="values")try{Vw(Nm,"name",{value:"values"})}catch(a){}});var jm=f((CO,Hm)=>{"use strict";var qw=fe(),Uw=sr(),Hw=qw("iterator"),jw=Array.prototype;Hm.exports=function(a){return a!==void 0&&(Uw.Array===a||jw[Hw]===a)}});var hu=f((VO,Gm)=>{"use strict";var Qw=$i(),Qm=Ii(),Gw=$r(),Ww=sr(),Yw=fe(),zw=Yw("iterator");Gm.exports=function(a){if(!Gw(a))return Qm(a,zw)||Qm(a,"@@iterator")||Ww[Qw(a)]}});var Ym=f((OO,Wm)=>{"use strict";var Kw=Ve(),Xw=st(),Jw=nt(),Zw=Ti(),eA=hu(),tA=TypeError;Wm.exports=function(a,e){var t=arguments.length<2?eA(a):e;if(Xw(t))return Jw(Kw(t,a));throw new tA(Zw(a)+" is not iterable")}});var Xm=f((_O,Km)=>{"use strict";var rA=Ve(),zm=nt(),iA=Ii();Km.exports=function(a,e,t){var r,i;zm(a);try{if(r=iA(a,"return"),!r){if(e==="throw")throw t;return t}r=rA(r,a)}catch(s){i=!0,r=s}if(e==="throw")throw t;if(i)throw r;return zm(r),t}});var Os=f((BO,tf)=>{"use strict";var aA=Dr(),sA=Ve(),nA=nt(),oA=Ti(),uA=jm(),lA=_r(),Jm=yi(),cA=Ym(),dA=hu(),Zm=Xm(),pA=TypeError,Vs=function(a,e){this.stopped=a,this.result=e},ef=Vs.prototype;tf.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=aA(e,r),l,c,d,p,h,m,b,g=function(S){return l&&Zm(l,"normal",S),new Vs(!0,S)},v=function(S){return i?(nA(S),o?u(S[0],S[1],g):u(S[0],S[1])):o?u(S,g):u(S)};if(s)l=a.iterator;else if(n)l=a;else{if(c=dA(a),!c)throw new pA(oA(a)+" is not iterable");if(uA(c)){for(d=0,p=lA(a);p>d;d++)if(h=v(a[d]),h&&Jm(ef,h))return h;return new Vs(!1)}l=cA(a,c)}for(m=s?a.next:l.next;!(b=sA(m,l)).done;){try{h=v(b.value)}catch(S){Zm(l,"throw",S)}if(typeof h=="object"&&h&&Jm(ef,h))return h}return new Vs(!1)}});var af=f((NO,rf)=>{"use strict";var hA=Ce(),mA=ar(),fA=Si();rf.exports=function(a,e,t){hA?mA.f(a,e,fA(0,t)):a[e]=t}});var sf=f(()=>{"use strict";var bA=le(),gA=Os(),vA=af();bA({target:"Object",stat:!0},{fromEntries:function(e){var t={};return gA(e,function(r,i){vA(t,r,i)},{AS_ENTRIES:!0}),t}})});var of=f((UO,nf)=>{"use strict";pu();sf();var SA=Rr();nf.exports=SA.Object.fromEntries});var lf=f((HO,uf)=>{"use strict";uf.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 df=f(()=>{"use strict";pu();var yA=lf(),TA=ne(),IA=Ri(),cf=sr();for(_s in yA)IA(TA[_s],_s),cf[_s]=cf.Array;var _s});var hf=f((GO,pf)=>{"use strict";var EA=of();df();pf.exports=EA});var mu=f((WO,mf)=>{"use strict";var xA=hf();mf.exports=xA});var ff=f(()=>{"use strict"});var fu=f((KO,bf)=>{"use strict";var Di=ne(),PA=ir(),wA=tr(),Bs=function(a){return PA.slice(0,a.length)===a};bf.exports=function(){return Bs("Bun/")?"BUN":Bs("Cloudflare-Workers")?"CLOUDFLARE":Bs("Deno/")?"DENO":Bs("Node.js/")?"NODE":Di.Bun&&typeof Bun.version=="string"?"BUN":Di.Deno&&typeof Deno.version=="object"?"DENO":wA(Di.process)==="process"?"NODE":Di.window&&Di.document?"BROWSER":"REST"}()});var Ns=f((XO,gf)=>{"use strict";var AA=fu();gf.exports=AA==="NODE"});var Sf=f((JO,vf)=>{"use strict";var kA=ar();vf.exports=function(a,e,t){return kA.f(a,e,t)}});var If=f((ZO,Tf)=>{"use strict";var $A=ht(),RA=Sf(),LA=fe(),MA=Ce(),yf=LA("species");Tf.exports=function(a){var e=$A(a);MA&&e&&!e[yf]&&RA(e,yf,{configurable:!0,get:function(){return this}})}});var xf=f((e_,Ef)=>{"use strict";var DA=yi(),CA=TypeError;Ef.exports=function(a,e){if(DA(e,a))return a;throw new CA("Incorrect invocation")}});var gu=f((t_,Pf)=>{"use strict";var VA=ce(),OA=ae(),bu=Ei(),_A=VA(Function.toString);OA(bu.inspectSource)||(bu.inspectSource=function(a){return _A(a)});Pf.exports=bu.inspectSource});var Su=f((r_,Rf)=>{"use strict";var BA=ce(),NA=me(),wf=ae(),FA=$i(),qA=ht(),UA=gu(),Af=function(){},kf=qA("Reflect","construct"),vu=/^\s*(?:class|function)\b/,HA=BA(vu.exec),jA=!vu.test(Af),Ci=function(e){if(!wf(e))return!1;try{return kf(Af,[],e),!0}catch(t){return!1}},$f=function(e){if(!wf(e))return!1;switch(FA(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return jA||!!HA(vu,UA(e))}catch(t){return!0}};$f.sham=!0;Rf.exports=!kf||NA(function(){var a;return Ci(Ci.call)||!Ci(Object)||!Ci(function(){a=!0})||a})?$f:Ci});var Mf=f((i_,Lf)=>{"use strict";var QA=Su(),GA=Ti(),WA=TypeError;Lf.exports=function(a){if(QA(a))return a;throw new WA(GA(a)+" is not a constructor")}});var yu=f((a_,Cf)=>{"use strict";var Df=nt(),YA=Mf(),zA=$r(),KA=fe(),XA=KA("species");Cf.exports=function(a,e){var t=Df(a).constructor,r;return t===void 0||zA(r=Df(t)[XA])?e:YA(r)}});var Of=f((s_,Vf)=>{"use strict";var JA=ce();Vf.exports=JA([].slice)});var Bf=f((n_,_f)=>{"use strict";var ZA=TypeError;_f.exports=function(a,e){if(a<e)throw new ZA("Not enough arguments");return a}});var Tu=f((o_,Nf)=>{"use strict";var ek=ir();Nf.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(ek)});var Ru=f((u_,Yf)=>{"use strict";var _e=ne(),tk=lo(),rk=Dr(),Ff=ae(),ik=Xe(),Wf=me(),qf=eu(),ak=Of(),Uf=Ss(),sk=Bf(),nk=Tu(),ok=Ns(),Au=_e.setImmediate,ku=_e.clearImmediate,uk=_e.process,Iu=_e.Dispatch,lk=_e.Function,Hf=_e.MessageChannel,ck=_e.String,Eu=0,Vi={},jf="onreadystatechange",Oi,or,xu,Pu;Wf(function(){Oi=_e.location});var $u=function(a){if(ik(Vi,a)){var e=Vi[a];delete Vi[a],e()}},wu=function(a){return function(){$u(a)}},Qf=function(a){$u(a.data)},Gf=function(a){_e.postMessage(ck(a),Oi.protocol+"//"+Oi.host)};(!Au||!ku)&&(Au=function(e){sk(arguments.length,1);var t=Ff(e)?e:lk(e),r=ak(arguments,1);return Vi[++Eu]=function(){tk(t,void 0,r)},or(Eu),Eu},ku=function(e){delete Vi[e]},ok?or=function(a){uk.nextTick(wu(a))}:Iu&&Iu.now?or=function(a){Iu.now(wu(a))}:Hf&&!nk?(xu=new Hf,Pu=xu.port2,xu.port1.onmessage=Qf,or=rk(Pu.postMessage,Pu)):_e.addEventListener&&Ff(_e.postMessage)&&!_e.importScripts&&Oi&&Oi.protocol!=="file:"&&!Wf(Gf)?(or=Gf,_e.addEventListener("message",Qf,!1)):jf in Uf("script")?or=function(a){qf.appendChild(Uf("script"))[jf]=function(){qf.removeChild(this),$u(a)}}:or=function(a){setTimeout(wu(a),0)});Yf.exports={set:Au,clear:ku}});var Xf=f((l_,Kf)=>{"use strict";var zf=ne(),dk=Ce(),pk=Object.getOwnPropertyDescriptor;Kf.exports=function(a){if(!dk)return zf[a];var e=pk(zf,a);return e&&e.value}});var Lu=f((c_,Zf)=>{"use strict";var Jf=function(){this.head=null,this.tail=null};Jf.prototype={add:function(a){var e={item:a,next:null},t=this.tail;t?t.next=e:this.head=e,this.tail=e},get:function(){var a=this.head;if(a){var e=this.head=a.next;return e===null&&(this.tail=null),a.item}}};Zf.exports=Jf});var tb=f((d_,eb)=>{"use strict";var hk=ir();eb.exports=/ipad|iphone|ipod/i.test(hk)&&typeof Pebble!="undefined"});var ib=f((p_,rb)=>{"use strict";var mk=ir();rb.exports=/web0s(?!.*chrome)/i.test(mk)});var cb=f((h_,lb)=>{"use strict";var qr=ne(),fk=Xf(),ab=Dr(),Mu=Ru().set,bk=Lu(),gk=Tu(),vk=tb(),Sk=ib(),Du=Ns(),sb=qr.MutationObserver||qr.WebKitMutationObserver,nb=qr.document,ob=qr.process,Fs=qr.Promise,Ou=fk("queueMicrotask"),Fr,Cu,Vu,qs,ub;Ou||(_i=new bk,Bi=function(){var a,e;for(Du&&(a=ob.domain)&&a.exit();e=_i.get();)try{e()}catch(t){throw _i.head&&Fr(),t}a&&a.enter()},!gk&&!Du&&!Sk&&sb&&nb?(Cu=!0,Vu=nb.createTextNode(""),new sb(Bi).observe(Vu,{characterData:!0}),Fr=function(){Vu.data=Cu=!Cu}):!vk&&Fs&&Fs.resolve?(qs=Fs.resolve(void 0),qs.constructor=Fs,ub=ab(qs.then,qs),Fr=function(){ub(Bi)}):Du?Fr=function(){ob.nextTick(Bi)}:(Mu=ab(Mu,qr),Fr=function(){Mu(Bi)}),Ou=function(a){_i.head||Fr(),_i.add(a)});var _i,Bi;lb.exports=Ou});var pb=f((m_,db)=>{"use strict";db.exports=function(a,e){try{arguments.length===1?console.error(a):console.error(a,e)}catch(t){}}});var Us=f((f_,hb)=>{"use strict";hb.exports=function(a){try{return{error:!1,value:a()}}catch(e){return{error:!0,value:e}}}});var ur=f((b_,mb)=>{"use strict";var yk=ne();mb.exports=yk.Promise});var Ur=f((g_,vb)=>{"use strict";var Tk=ne(),Ni=ur(),Ik=ae(),Ek=Mo(),xk=gu(),Pk=fe(),fb=fu(),wk=Ke(),_u=So(),bb=Ni&&Ni.prototype,Ak=Pk("species"),Bu=!1,gb=Ik(Tk.PromiseRejectionEvent),kk=Ek("Promise",function(){var a=xk(Ni),e=a!==String(Ni);if(!e&&_u===66||wk&&!(bb.catch&&bb.finally))return!0;if(!_u||_u<51||!/native code/.test(a)){var t=new Ni(function(s){s(1)}),r=function(s){s(function(){},function(){})},i=t.constructor={};if(i[Ak]=r,Bu=t.then(function(){})instanceof r,!Bu)return!0}return!e&&(fb==="BROWSER"||fb==="DENO")&&!gb});vb.exports={CONSTRUCTOR:kk,REJECTION_EVENT:gb,SUBCLASSING:Bu}});var Hr=f((v_,yb)=>{"use strict";var Sb=st(),$k=TypeError,Rk=function(a){var e,t;this.promise=new a(function(r,i){if(e!==void 0||t!==void 0)throw new $k("Bad Promise constructor");e=r,t=i}),this.resolve=Sb(e),this.reject=Sb(t)};yb.exports.f=function(a){return new Rk(a)}});var Nb=f(()=>{"use strict";var Lk=le(),Mk=Ke(),Gs=Ns(),Dt=ne(),Wr=Ve(),Tb=Nr(),Ib=lu(),Dk=Ri(),Ck=If(),Vk=st(),Qs=ae(),Ok=Oe(),_k=xf(),Bk=yu(),Ab=Ru().set,Hu=cb(),Nk=pb(),Fk=Us(),qk=Lu(),kb=Ko(),Ws=ur(),ju=Ur(),$b=Hr(),Ys="Promise",Rb=ju.CONSTRUCTOR,Uk=ju.REJECTION_EVENT,Hk=ju.SUBCLASSING,Nu=kb.getterFor(Ys),jk=kb.set,jr=Ws&&Ws.prototype,lr=Ws,Hs=jr,Lb=Dt.TypeError,Fu=Dt.document,Qu=Dt.process,qu=$b.f,Qk=qu,Gk=!!(Fu&&Fu.createEvent&&Dt.dispatchEvent),Mb="unhandledrejection",Wk="rejectionhandled",Eb=0,Db=1,Yk=2,Gu=1,Cb=2,js,xb,zk,Pb,Vb=function(a){var e;return Ok(a)&&Qs(e=a.then)?e:!1},Ob=function(a,e){var t=e.value,r=e.state===Db,i=r?a.ok:a.fail,s=a.resolve,n=a.reject,o=a.domain,u,l,c;try{i?(r||(e.rejection===Cb&&Xk(e),e.rejection=Gu),i===!0?u=t:(o&&o.enter(),u=i(t),o&&(o.exit(),c=!0)),u===a.promise?n(new Lb("Promise-chain cycle")):(l=Vb(u))?Wr(l,u,s,n):s(u)):n(t)}catch(d){o&&!c&&o.exit(),n(d)}},_b=function(a,e){a.notified||(a.notified=!0,Hu(function(){for(var t=a.reactions,r;r=t.get();)Ob(r,a);a.notified=!1,e&&!a.rejection&&Kk(a)}))},Bb=function(a,e,t){var r,i;Gk?(r=Fu.createEvent("Event"),r.promise=e,r.reason=t,r.initEvent(a,!1,!0),Dt.dispatchEvent(r)):r={promise:e,reason:t},!Uk&&(i=Dt["on"+a])?i(r):a===Mb&&Nk("Unhandled promise rejection",t)},Kk=function(a){Wr(Ab,Dt,function(){var e=a.facade,t=a.value,r=wb(a),i;if(r&&(i=Fk(function(){Gs?Qu.emit("unhandledRejection",t,e):Bb(Mb,e,t)}),a.rejection=Gs||wb(a)?Cb:Gu,i.error))throw i.value})},wb=function(a){return a.rejection!==Gu&&!a.parent},Xk=function(a){Wr(Ab,Dt,function(){var e=a.facade;Gs?Qu.emit("rejectionHandled",e):Bb(Wk,e,a.value)})},Qr=function(a,e,t){return function(r){a(e,r,t)}},Gr=function(a,e,t){a.done||(a.done=!0,t&&(a=t),a.value=e,a.state=Yk,_b(a,!0))},Uu=function(a,e,t){if(!a.done){a.done=!0,t&&(a=t);try{if(a.facade===e)throw new Lb("Promise can't be resolved itself");var r=Vb(e);r?Hu(function(){var i={done:!1};try{Wr(r,e,Qr(Uu,i,a),Qr(Gr,i,a))}catch(s){Gr(i,s,a)}}):(a.value=e,a.state=Db,_b(a,!1))}catch(i){Gr({done:!1},i,a)}}};if(Rb&&(lr=function(e){_k(this,Hs),Vk(e),Wr(js,this);var t=Nu(this);try{e(Qr(Uu,t),Qr(Gr,t))}catch(r){Gr(t,r)}},Hs=lr.prototype,js=function(e){jk(this,{type:Ys,done:!1,notified:!1,parent:!1,reactions:new qk,rejection:!1,state:Eb,value:void 0})},js.prototype=Tb(Hs,"then",function(e,t){var r=Nu(this),i=qu(Bk(this,lr));return r.parent=!0,i.ok=Qs(e)?e:!0,i.fail=Qs(t)&&t,i.domain=Gs?Qu.domain:void 0,r.state===Eb?r.reactions.add(i):Hu(function(){Ob(i,r)}),i.promise}),xb=function(){var a=new js,e=Nu(a);this.promise=a,this.resolve=Qr(Uu,e),this.reject=Qr(Gr,e)},$b.f=qu=function(a){return a===lr||a===zk?new xb(a):Qk(a)},!Mk&&Qs(Ws)&&jr!==Object.prototype)){Pb=jr.then,Hk||Tb(jr,"then",function(e,t){var r=this;return new lr(function(i,s){Wr(Pb,r,i,s)}).then(e,t)},{unsafe:!0});try{delete jr.constructor}catch(a){}Ib&&Ib(jr,Hs)}Lk({global:!0,constructor:!0,wrap:!0,forced:Rb},{Promise:lr});Dk(lr,Ys,!1,!0);Ck(Ys)});var jb=f((T_,Hb)=>{"use strict";var Jk=fe(),qb=Jk("iterator"),Ub=!1;try{Fb=0,Wu={next:function(){return{done:!!Fb++}},return:function(){Ub=!0}},Wu[qb]=function(){return this},Array.from(Wu,function(){throw 2})}catch(a){}var Fb,Wu;Hb.exports=function(a,e){try{if(!e&&!Ub)return!1}catch(i){return!1}var t=!1;try{var r={};r[qb]=function(){return{next:function(){return{done:t=!0}}}},a(r)}catch(i){}return t}});var Yu=f((I_,Qb)=>{"use strict";var Zk=ur(),e$=jb(),t$=Ur().CONSTRUCTOR;Qb.exports=t$||!e$(function(a){Zk.all(a).then(void 0,function(){})})});var Gb=f(()=>{"use strict";var r$=le(),i$=Ve(),a$=st(),s$=Hr(),n$=Us(),o$=Os(),u$=Yu();r$({target:"Promise",stat:!0,forced:u$},{all:function(e){var t=this,r=s$.f(t),i=r.resolve,s=r.reject,n=n$(function(){var o=a$(t.resolve),u=[],l=0,c=1;o$(e,function(d){var p=l++,h=!1;c++,i$(o,t,d).then(function(m){h||(h=!0,u[p]=m,--c||i(u))},s)}),--c||i(u)});return n.error&&s(n.value),r.promise}})});var Yb=f(()=>{"use strict";var l$=le(),c$=Ke(),d$=Ur().CONSTRUCTOR,Ku=ur(),p$=ht(),h$=ae(),m$=Nr(),Wb=Ku&&Ku.prototype;l$({target:"Promise",proto:!0,forced:d$,real:!0},{catch:function(a){return this.then(void 0,a)}});!c$&&h$(Ku)&&(zu=p$("Promise").prototype.catch,Wb.catch!==zu&&m$(Wb,"catch",zu,{unsafe:!0}));var zu});var zb=f(()=>{"use strict";var f$=le(),b$=Ve(),g$=st(),v$=Hr(),S$=Us(),y$=Os(),T$=Yu();f$({target:"Promise",stat:!0,forced:T$},{race:function(e){var t=this,r=v$.f(t),i=r.reject,s=S$(function(){var n=g$(t.resolve);y$(e,function(o){b$(n,t,o).then(r.resolve,i)})});return s.error&&i(s.value),r.promise}})});var Kb=f(()=>{"use strict";var I$=le(),E$=Hr(),x$=Ur().CONSTRUCTOR;I$({target:"Promise",stat:!0,forced:x$},{reject:function(e){var t=E$.f(this),r=t.reject;return r(e),t.promise}})});var Xu=f((L_,Xb)=>{"use strict";var P$=nt(),w$=Oe(),A$=Hr();Xb.exports=function(a,e){if(P$(a),w$(e)&&e.constructor===a)return e;var t=A$.f(a),r=t.resolve;return r(e),t.promise}});var eg=f(()=>{"use strict";var k$=le(),$$=ht(),Jb=Ke(),R$=ur(),Zb=Ur().CONSTRUCTOR,L$=Xu(),M$=$$("Promise"),D$=Jb&&!Zb;k$({target:"Promise",stat:!0,forced:Jb||Zb},{resolve:function(e){return L$(D$&&this===M$?R$:this,e)}})});var tg=f(()=>{"use strict";Nb();Gb();Yb();zb();Kb();eg()});var sg=f(()=>{"use strict";var C$=le(),V$=Ke(),zs=ur(),O$=me(),ig=ht(),ag=ae(),_$=yu(),rg=Xu(),B$=Nr(),Zu=zs&&zs.prototype,N$=!!zs&&O$(function(){Zu.finally.call({then:function(){}},function(){})});C$({target:"Promise",proto:!0,real:!0,forced:N$},{finally:function(a){var e=_$(this,ig("Promise")),t=ag(a);return this.then(t?function(r){return rg(e,a()).then(function(){return r})}:a,t?function(r){return rg(e,a()).then(function(){throw r})}:a)}});!V$&&ag(zs)&&(Ju=ig("Promise").prototype.finally,Zu.finally!==Ju&&B$(Zu,"finally",Ju,{unsafe:!0}));var Ju});var og=f((B_,ng)=>{"use strict";ff();tg();sg();var F$=Mt();ng.exports=F$("Promise","finally")});var lg=f((N_,ug)=>{"use strict";var q$=og();ug.exports=q$});var Ks=f((F_,cg)=>{"use strict";var U$=lg();cg.exports=U$});var Eg=f(()=>{"use strict";var rR=le(),iR=Go().values;rR({target:"Object",stat:!0},{values:function(e){return iR(e)}})});var Pg=f((xB,xg)=>{"use strict";Eg();var aR=Rr();xg.exports=aR.Object.values});var Ag=f((PB,wg)=>{"use strict";var sR=Pg();wg.exports=sR});var zr=f((wB,kg)=>{"use strict";var nR=Ag();kg.exports=nR});var Qg=f(()=>{"use strict";var $R=le(),RR=Lr(),LR=_r(),MR=wi(),DR=Ai();$R({target:"Array",proto:!0},{at:function(e){var t=RR(this),r=LR(t),i=MR(e),s=i>=0?i:r+i;return s<0||s>=r?void 0:t[s]}});DR("at")});var Wg=f((BN,Gg)=>{"use strict";Qg();var CR=Mt();Gg.exports=CR("Array","at")});var zg=f((NN,Yg)=>{"use strict";var VR=Wg();Yg.exports=VR});var Bt=f((FN,Kg)=>{"use strict";var OR=zg();Kg.exports=OR});var Pl=f((kq,Lv)=>{"use strict";var SL=tr();Lv.exports=Array.isArray||function(e){return SL(e)==="Array"}});var Dv=f(($q,Mv)=>{"use strict";var yL=TypeError,TL=9007199254740991;Mv.exports=function(a){if(a>TL)throw yL("Maximum allowed index exceeded");return a}});var Ov=f((Rq,Vv)=>{"use strict";var IL=Pl(),EL=_r(),xL=Dv(),PL=Dr(),Cv=function(a,e,t,r,i,s,n,o){for(var u=i,l=0,c=n?PL(n,o):!1,d,p;l<r;)l in t&&(d=c?c(t[l],l,e):t[l],s>0&&IL(d)?(p=EL(d),u=Cv(a,e,d,p,u,s-1)-1):(xL(u+1),a[u]=d),u++),l++;return u};Vv.exports=Cv});var Fv=f((Lq,Nv)=>{"use strict";var _v=Pl(),wL=Su(),AL=Oe(),kL=fe(),$L=kL("species"),Bv=Array;Nv.exports=function(a){var e;return _v(a)&&(e=a.constructor,wL(e)&&(e===Bv||_v(e.prototype))?e=void 0:AL(e)&&(e=e[$L],e===null&&(e=void 0))),e===void 0?Bv:e}});var Uv=f((Mq,qv)=>{"use strict";var RL=Fv();qv.exports=function(a,e){return new(RL(a))(e===0?0:e)}});var Hv=f(()=>{"use strict";var LL=le(),ML=Ov(),DL=st(),CL=Lr(),VL=_r(),OL=Uv();LL({target:"Array",proto:!0},{flatMap:function(e){var t=CL(this),r=VL(t),i;return DL(e),i=OL(t,0),i.length=ML(i,t,t,r,0,1,e,arguments.length>1?arguments[1]:void 0),i}})});var jv=f(()=>{"use strict";var _L=Ai();_L("flatMap")});var Gv=f((_q,Qv)=>{"use strict";Hv();jv();var BL=Mt();Qv.exports=BL("Array","flatMap")});var Yv=f((Bq,Wv)=>{"use strict";var NL=Gv();Wv.exports=NL});var wl=f((Nq,zv)=>{"use strict";var FL=Yv();zv.exports=FL});var ra=f((Fq,Kv)=>{"use strict";var qL=$i(),UL=String;Kv.exports=function(a){if(qL(a)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return UL(a)}});var Al=f((qq,Xv)=>{"use strict";Xv.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 eS=f((Uq,Zv)=>{"use strict";var HL=ce(),jL=Lt(),QL=ra(),$l=Al(),Jv=HL("".replace),GL=RegExp("^["+$l+"]+"),WL=RegExp("(^|[^"+$l+"])["+$l+"]+$"),kl=function(a){return function(e){var t=QL(jL(e));return a&1&&(t=Jv(t,GL,"")),a&2&&(t=Jv(t,WL,"$1")),t}};Zv.exports={start:kl(1),end:kl(2),trim:kl(3)}});var aS=f((Hq,iS)=>{"use strict";var YL=Zo().PROPER,zL=me(),tS=Al(),rS="\u200B\x85\u180E";iS.exports=function(a){return zL(function(){return!!tS[a]()||rS[a]()!==rS||YL&&tS[a].name!==a})}});var Rl=f((jq,sS)=>{"use strict";var KL=eS().start,XL=aS();sS.exports=XL("trimStart")?function(){return KL(this)}:"".trimStart});var oS=f(()=>{"use strict";var JL=le(),nS=Rl();JL({target:"String",proto:!0,name:"trimStart",forced:"".trimLeft!==nS},{trimLeft:nS})});var lS=f(()=>{"use strict";oS();var ZL=le(),uS=Rl();ZL({target:"String",proto:!0,name:"trimStart",forced:"".trimStart!==uS},{trimStart:uS})});var dS=f((zq,cS)=>{"use strict";lS();var eM=Mt();cS.exports=eM("String","trimLeft")});var hS=f((Kq,pS)=>{"use strict";var tM=dS();pS.exports=tM});var fS=f((Xq,mS)=>{"use strict";var rM=hS();mS.exports=rM});var LS=f(()=>{"use strict"});var MS=f(()=>{"use strict"});var CS=f((CH,DS)=>{"use strict";var PM=Oe(),wM=tr(),AM=fe(),kM=AM("match");DS.exports=function(a){var e;return PM(a)&&((e=a[kM])!==void 0?!!e:wM(a)==="RegExp")}});var OS=f((VH,VS)=>{"use strict";var $M=nt();VS.exports=function(){var a=$M(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 NS=f((OH,BS)=>{"use strict";var RM=Ve(),LM=Xe(),MM=yi(),DM=OS(),_S=RegExp.prototype;BS.exports=function(a){var e=a.flags;return e===void 0&&!("flags"in _S)&&!LM(a,"flags")&&MM(_S,a)?RM(DM,a):e}});var qS=f((_H,FS)=>{"use strict";var Bl=ce(),CM=Lr(),VM=Math.floor,Ol=Bl("".charAt),OM=Bl("".replace),_l=Bl("".slice),_M=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,BM=/\$([$&'`]|\d{1,2})/g;FS.exports=function(a,e,t,r,i,s){var n=t+a.length,o=r.length,u=BM;return i!==void 0&&(i=CM(i),u=_M),OM(s,u,function(l,c){var d;switch(Ol(c,0)){case"$":return"$";case"&":return a;case"`":return _l(e,0,t);case"'":return _l(e,n);case"<":d=i[_l(c,1,-1)];break;default:var p=+c;if(p===0)return l;if(p>o){var h=VM(p/10);return h===0?l:h<=o?r[h-1]===void 0?Ol(c,1):r[h-1]+Ol(c,1):l}d=r[p-1]}return d===void 0?"":d})}});var jS=f(()=>{"use strict";var NM=le(),FM=Ve(),Fl=ce(),US=Lt(),qM=ae(),UM=$r(),HM=CS(),ti=ra(),jM=Ii(),QM=NS(),GM=qS(),WM=fe(),YM=Ke(),zM=WM("replace"),KM=TypeError,Nl=Fl("".indexOf),XM=Fl("".replace),HS=Fl("".slice),JM=Math.max;NM({target:"String",proto:!0},{replaceAll:function(e,t){var r=US(this),i,s,n,o,u,l,c,d,p,h,m=0,b="";if(!UM(e)){if(i=HM(e),i&&(s=ti(US(QM(e))),!~Nl(s,"g")))throw new KM("`.replaceAll` does not allow non-global regexes");if(n=jM(e,zM),n)return FM(n,e,r,t);if(YM&&i)return XM(ti(r),e,t)}for(o=ti(r),u=ti(e),l=qM(t),l||(t=ti(t)),c=u.length,d=JM(1,c),p=Nl(o,u);p!==-1;)h=l?ti(t(u,p,o)):GM(u,o,p,[],void 0,t),b+=HS(o,m,p)+h,m=p+c,p=p+d>o.length?-1:Nl(o,u,p+d);return m<o.length&&(b+=HS(o,m)),b}})});var GS=f((FH,QS)=>{"use strict";LS();MS();jS();var ZM=Mt();QS.exports=ZM("String","replaceAll")});var YS=f((qH,WS)=>{"use strict";var eD=GS();WS.exports=eD});var KS=f((UH,zS)=>{"use strict";var tD=YS();zS.exports=tD});var JS=f((HH,XS)=>{"use strict";var rD=wi(),iD=ra(),aD=Lt(),sD=RangeError;XS.exports=function(e){var t=iD(aD(this)),r="",i=rD(e);if(i<0||i===1/0)throw new sD("Wrong number of repetitions");for(;i>0;(i>>>=1)&&(t+=t))i&1&&(r+=t);return r}});var iy=f((jH,ry)=>{"use strict";var ty=ce(),nD=Bo(),ZS=ra(),oD=JS(),uD=Lt(),lD=ty(oD),cD=ty("".slice),dD=Math.ceil,ey=function(a){return function(e,t,r){var i=ZS(uD(e)),s=nD(t),n=i.length,o=r===void 0?" ":ZS(r),u,l;return s<=n||o===""?i:(u=s-n,l=lD(o,dD(u/o.length)),l.length>u&&(l=cD(l,0,u)),a?i+l:l+i)}};ry.exports={start:ey(!1),end:ey(!0)}});var sy=f((QH,ay)=>{"use strict";var pD=ir();ay.exports=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(pD)});var ny=f(()=>{"use strict";var hD=le(),mD=iy().start,fD=sy();hD({target:"String",proto:!0,forced:fD},{padStart:function(e){return mD(this,e,arguments.length>1?arguments[1]:void 0)}})});var uy=f((YH,oy)=>{"use strict";ny();var bD=Mt();oy.exports=bD("String","padStart")});var cy=f((zH,ly)=>{"use strict";var gD=uy();ly.exports=gD});var py=f((KH,dy)=>{"use strict";var vD=cy();dy.exports=vD});var vd="2.0.129-dev.6ff96833.0";var De=(i=>(i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused",i))(De||{}),pt=(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))(pt||{});var fs=(i=>(i.NOT_AVAILABLE="NOT_AVAILABLE",i.AVAILABLE="AVAILABLE",i.CONNECTING="CONNECTING",i.CONNECTED="CONNECTED",i))(fs||{}),no=(r=>(r.HTTP1="http1",r.HTTP2="http2",r.QUIC="quic",r))(no||{});var oo=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(oo||{}),bs=(r=>(r.TRAFFIC_SAVING="traffic_saving",r.HIGH_QUALITY="high_quality",r.UNKNOWN="unknown",r))(bs||{});var GT=B(Fe(),1);import{assertNever as bh,assertNonNullable as $x,isNonNullable as Ts,ValueSubject as Fo,Subject as Rx,Subscription as Lx,merge as Mx,observableFrom as Dx,fromEvent as ph,map as hh,tap as mh,filterChanged as Cx,isNullable as qo,ErrorCategory as fh}from"@vkontakte/videoplayer-shared/es2015";var dh=a=>new Promise((e,t)=>{let r=document.createElement("script");r.setAttribute("src",a),r.onload=()=>e(),r.onerror=i=>t(i),document.body.appendChild(r)});var Is=class{constructor(e){this.connection$=new Fo(void 0);this.castState$=new Fo("NOT_AVAILABLE");this.errorEvent$=new Rx;this.realCastState$=new Fo("NOT_AVAILABLE");this.subscription=new Lx;this.isDestroyed=!1;var s;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastInitializer");let t="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${t}`}),e.isDisabled||!t)return;let r=Ts((s=window.chrome)==null?void 0:s.cast),i=!!window.__onGCastApiAvailable;r?this.initializeCastApi():(window.__onGCastApiAvailable=n=>{delete window.__onGCastApiAvailable,n&&!this.isDestroyed&&this.initializeCastApi()},i||dh("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:fh.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(){Ts(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();qo(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();qo(t)||e!==t.remotePlayer.isMuted&&t.remotePlayerController.muteOrUnmute()}destroy(){this.isDestroyed=!0,this.subscription.unsubscribe()}initListeners(){let e=new cast.framework.RemotePlayer,t=new cast.framework.RemotePlayerController(e),r=cast.framework.CastContext.getInstance();this.subscription.add(ph(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 bh(i.sessionState)}})).add(Mx(ph(r,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(mh(i=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(i)}`})}),hh(i=>i.castState)),Dx([r.getCastState()])).pipe(Cx(),hh(Vx),mh(i=>{this.log({message:`realCastState$: ${i}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(i=>{var o,u;let s=i==="CONNECTED",n=Ts(this.connection$.getValue());if(s&&!n){let l=r.getCurrentSession();$x(l);let c=l.getCastDevice(),d=(u=(o=l.getMediaSession())==null?void 0:o.media)==null?void 0:u.contentId;(qo(d)||d===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:l,castDevice:c}))}else!s&&n&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(i==="CONNECTED"?Ts(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:fh.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:s})}}},Vx=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 bh(a)}};var Ec=B(Fe(),1),kT=B(Br(),1),$T=B(mu(),1);var yg=B(Ks(),1);import{assertNever as dg}from"@vkontakte/videoplayer-shared/es2015";var be=(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:dg(t)}return a},Xs=(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:dg(e)}};var A=(a,e,t=!1)=>{let r=a.getTransition();(t||!r||r.to===e)&&a.setState(e)};import{isNonNullable as H$,Subject as Js,merge as pg}from"@vkontakte/videoplayer-shared/es2015";var N=class{constructor(e){this.transitionStarted$=new Js;this.transitionEnded$=new Js;this.transitionUpdated$=new Js;this.forceChanged$=new Js;this.stateChangeStarted$=pg(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=pg(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||H$(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 j$}from"@vkontakte/videoplayer-shared/es2015";var hg=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 j$(a)}};import{assertNever as Yr,assertNonNullable as cr,debounce as mg,ErrorCategory as fg,fromEvent as dr,isNonNullable as bg,map as gg,merge as vg,observableFrom as Q$,Subject as G$,Subscription as el,timeout as W$,getHighestQuality as Y$}from"@vkontakte/videoplayer-shared/es2015";var z$=5,K$=5,X$=500,Sg=7e3,Fi=class{constructor(e){this.subscription=new el;this.loadMediaTimeoutSubscription=new el;this.videoState=new N("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:Yr(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:Yr(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:Yr(e)}break}default:Yr(r)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(hg(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 el;this.subscription.add(e),this.subscription.add(vg(this.videoState.stateChangeStarted$.pipe(gg(i=>`stateChangeStarted$ ${JSON.stringify(i)}`)),this.videoState.stateChangeEnded$.pipe(gg(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 G$;e.add(i.pipe(mg(X$)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add(dr(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)>z$)&&i.next(o),s=o})),e.add(dr(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(dr(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),i=>{this.logRemoteEvent(i),i.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(dr(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),i=>{this.logRemoteEvent(i),i.value?this.handleRemotePause():this.handleRemotePlay()}),t(dr(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<K$&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),A(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:Yr(n)}}),t(dr(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),i=>{this.logRemoteEvent(i),this.handleRemoteVolumeChange({volume:i.value})}),t(dr(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),i=>{this.logRemoteEvent(i),this.handleRemoteVolumeChange({muted:i.value})});let r=vg(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Q$(["init"])).pipe(mg(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"),A(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),A(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"),A(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"),A(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"&&A(this.params.desiredState.playbackState,"ready")}handleRemoteStop(){this.videoState.getState()!=="stopped"&&this.videoState.setState("stopped")}handleRemoteVolumeChange(e){var i,s;let t=this.params.output.volume$.getValue(),r={volume:(i=e.volume)!=null?i:t.volume,muted:(s=e.muted)!=null?s:t.muted};(r.volume!==t.volume||r.muted!==r.muted)&&this.params.output.volume$.next(r)}seek(e){this.params.output.willSeekEvent$.next();let{remotePlayer:t,remotePlayerController:r}=this.params.connection;t.currentTime=e,r.seek()}stop(){let{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){var l;let t=this.params.source,r,i,s;switch(e){case"MPEG":{let c=t[e];cr(c);let d=Y$(Object.keys(c));cr(d);let p=c[d];cr(p),r=p,i="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let c=t[e];cr(c),r=c.url,i="application/x-mpegurl",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":{let c=t[e];cr(c),r=c.url,i="application/dash+xml",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let c=t[e];cr(c),r=c.url,i="application/dash+xml",s=chrome.cast.media.StreamType.LIVE;break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let c=t[e];cr(c),r=be(c.url),i="application/x-mpegurl",s=chrome.cast.media.StreamType.LIVE;break}case"DASH_LIVE":case"WEB_RTC_LIVE":{let c="Unsupported format for Chromecast",d=new Error(c);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:fg.VIDEO_PIPELINE,message:c,thrown:d}),d}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return Yr(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 bg(o)&&(n.metadata.title=o),bg(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(W$(Sg).subscribe(()=>s(`timeout(${Sg})`)))});(0,yg.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:fg.VIDEO_PIPELINE,message:s,thrown:i})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var El=B(Fe(),1);import{clearVideoElement as Ig}from"@vkontakte/videoplayer-shared/es2015";import{clearVideoElement as J$}from"@vkontakte/videoplayer-shared/es2015";var Tg=a=>{try{a.pause(),a.playbackRate=0,J$(a),a.remove()}catch(e){console.error(e)}};import{fromEvent as Z$,Subscription as eR}from"@vkontakte/videoplayer-shared/es2015";var tl=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)}},rl=window.WeakMap?new WeakMap:new tl,il=window.WeakMap?new WeakMap:new Map,tR=(a,e=20)=>{let t=0;return Z$(a,"ratechange").subscribe(r=>{t++,t>=e&&(a.currentTime=a.currentTime,t=0)})},we=(a,{audioVideoSyncRate:e,disableYandexPiP:t})=>{let r=a.querySelector("video"),i=!!r;r?Ig(r):(r=document.createElement("video"),a.appendChild(r)),rl.set(r,i);let s=new eR;return s.add(tR(r,e)),il.set(r,s),r.setAttribute("crossorigin","anonymous"),r.setAttribute("playsinline","playsinline"),t&&r.setAttribute("x-yandex-pip","false"),r.controls=!1,r.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),r},Ae=a=>{let e=il.get(a);e==null||e.unsubscribe(),il.delete(a);let t=rl.get(a);rl.delete(a),t?Ig(a):Tg(a)};var sl=B(zr(),1);import{assertNonNullable as qi,isNonNullable as ut,isNullable as lR,fromEvent as Kr,merge as $g,observableFrom as Rg,filterChanged as Lg,map as Ui,Subject as Mg,Subscription as cR,ValueSubject as dR,ErrorCategory as pR}from"@vkontakte/videoplayer-shared/es2015";import{isNonNullable as al,isNullable as oR,Subscription as uR}from"@vkontakte/videoplayer-shared/es2015";var Zs=(a,e,t,{equal:r=(n,o)=>n===o,changed$:i,onError:s}={})=>{let n=a.getState(),o=e(),u=oR(i),l=new uR;return i&&l.add(i.subscribe(c=>{let d=a.getState();r(c,d)&&a.setState(c)},s)),r(o,n)||(t(n),u&&a.setState(n)),l.add(a.stateChangeStarted$.subscribe(c=>{t(c.to),u&&a.setState(c.to)},s)),l},ot=(a,e,t)=>Zs(e,()=>a.loop,r=>{al(r)&&(a.loop=r)},{onError:t}),ke=(a,e,t,r)=>Zs(e,()=>({muted:a.muted,volume:a.volume}),i=>{al(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}),qe=(a,e,t,r)=>Zs(e,()=>a.playbackRate,i=>{al(i)&&(a.playbackRate=i)},{changed$:t,onError:r}),Ct=Zs;var hR=a=>["__",a.language,a.label].join("|"),mR=(a,e)=>{if(a.id===e)return!0;let[t,r,i]=e.split("|");return a.language===r&&a.label===i},nl=class a{constructor(e){this.available$=new Mg;this.current$=new dR(void 0);this.error$=new Mg;this.subscription=new cR;this.externalTracks=new Map;this.internalTracks=new Map;this.baseURL=e}connect(e,t,r){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();let i=s=>{this.error$.next({id:"TextTracksManager",category:pR.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(Ct(t.internalTextTracks,()=>(0,sl.default)(this.internalTracks),s=>{ut(s)&&this.setInternal(s)},{equal:(s,n)=>ut(s)&&ut(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(Ui(s=>s.filter(({type:n})=>n==="internal"))),onError:i})),this.subscription.add(Ct(t.externalTextTracks,()=>(0,sl.default)(this.externalTracks),s=>{ut(s)&&this.setExternal(s)},{equal:(s,n)=>ut(s)&&ut(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(Ui(s=>s.filter(({type:n})=>n==="external"))),onError:i})),this.subscription.add(Ct(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(Ct(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.activeCues)}))}subscribe(){qi(this.video);let{textTracks:e}=this.video;this.subscription.add(Kr(e,"addtrack").subscribe(()=>{let r=this.current$.getValue();r&&this.select(r)})),this.subscription.add($g(Kr(e,"addtrack"),Kr(e,"removetrack"),Rg(["init"])).pipe(Ui(()=>this.htmlTextTracksAsArray().map(r=>this.htmlTextTrackToITextTrack(r))),Lg((r,i)=>r.length===i.length&&r.every(({id:s},n)=>s===i[n].id))).subscribe(this.available$)),this.subscription.add($g(Kr(e,"change"),Rg(["init"])).pipe(Ui(()=>this.htmlTextTracksAsArray().find(({mode:r})=>r==="showing")),Ui(r=>r&&this.htmlTextTrackToITextTrack(r).id),Lg()).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(Kr(e,"addtrack").subscribe(r=>{var s,n;(s=r.track)==null||s.addEventListener("cuechange",t);let i=o=>{var l,c,d,p,h;let u=(c=(l=o.target)==null?void 0:l.cues)!=null?c:null;u&&u.length&&(this.applyCueSettings((p=(d=o.target)==null?void 0:d.cues)!=null?p:null),(h=o.target)==null||h.removeEventListener("cuechange",i))};(n=r.track)==null||n.addEventListener("cuechange",i)})),this.subscription.add(Kr(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;ut(t.align)&&(i.align=t.align),ut(t.position)&&(i.position=t.position),ut(t.size)&&(i.size=t.size),ut(t.line)&&(i.line=t.line)}}htmlTextTracksAsArray(e=!1){qi(this.video);let t=[...this.video.textTracks];return e?t:t.filter(a.isHealthyTrack)}htmlTextTrackToITextTrack(e){var o,u,l,c,d;let{language:t,label:r}=e,i=e.id?e.id:hR(e),s=this.externalTracks.has(i),n=(l=s?(o=this.externalTracks.get(i))==null?void 0:o.isAuto:(u=this.internalTracks.get(i))==null?void 0:u.isAuto)!=null?l:i.includes("auto");return s?{id:i,type:"external",isAuto:n,language:t,label:r,url:(c=this.externalTracks.get(i))==null?void 0:c.url}:{id:i,type:"internal",isAuto:n,language:t,label:r,url:(d=this.internalTracks.get(i))==null?void 0:d.url}}static isHealthyTrack(e){return!(e.kind==="metadata"||e.groupId||e.id===""&&e.label===""&&e.language==="")}setExternal(e){this.internalTracks.size>0&&Array.from(this.internalTracks).forEach(([,t])=>this.detach(t)),e.filter(({id:t})=>!this.externalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.externalTracks).filter(([t])=>!e.find(r=>r.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){let t=[...this.externalTracks];e.filter(({id:r,language:i,isAuto:s})=>!this.internalTracks.has(r)&&!t.some(([,n])=>n.language===i&&n.isAuto===s)).forEach(r=>this.attach(r)),Array.from(this.internalTracks).filter(([r])=>!e.find(i=>i.id===r)).forEach(([,r])=>this.detach(r))}select(e){qi(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(lR(e)||!mR(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){qi(this.video);let t=document.createElement("track");this.baseURL?t.setAttribute("src",new URL(e.url,this.baseURL).toString()):t.setAttribute("src",e.url),t.setAttribute("id",e.id),e.label&&t.setAttribute("label",e.label),e.language&&t.setAttribute("srclang",e.language),e.type==="external"?this.externalTracks.set(e.id,e):e.type==="internal"&&this.internalTracks.set(e.id,e),this.video.appendChild(t)}detach(e){qi(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)}},Ue=nl;var pr=class{constructor(){this.pausedTime=0;this.streamOffset=0;this.pauseTimestamp=0}getTotalPausedTime(){return this.pausedTime+this.getCurrentPausedTime()}getCurrentPausedTime(){return this.pauseTimestamp>0?Date.now()-this.pauseTimestamp:0}getStreamOffset(){return this.streamOffset}getTotalOffset(){return this.getTotalPausedTime()+this.streamOffset}pause(){this.pauseTimestamp===0&&(this.pauseTimestamp=Date.now())}resume(){this.pauseTimestamp>0&&(this.pausedTime+=this.getCurrentPausedTime(),this.pauseTimestamp=0)}resetTo(e,t=!1){this.streamOffset=e,this.pauseTimestamp=0,this.pausedTime=0,t&&this.pause()}};var Dg=a=>{let e=a;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e==null?void 0:e.parentNode;return e!=null?e:void 0},ol=a=>{let e=Dg(a);return!!(e&&e.fullscreenElement&&e.fullscreenElement===a)},Cg=a=>{let e=Dg(a);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===a)};import{fromEvent as $e,map as Vt,merge as ll,filterChanged as ER,isNonNullable as Hg,Subject as xR,filter as ji,mapTo as cl,combine as PR,once as wR,throttle as AR,ErrorCategory as kR,ValueSubject as jg}from"@vkontakte/videoplayer-shared/es2015";var fR=3,Vg=(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 en=class{get current(){return this._current}get isYandex(){return this.current==="Yandex"}get isSafari(){return this.current==="Safari"}get isSamsungBrowser(){return this.current==="SamsungBrowser"}get safariVersion(){return this._safariVersion}detect(){let{userAgent:e}=navigator;try{let t=/yabrowser/i.test(e)?"Yandex":void 0,r=/samsungbrowser/i.test(e)?"SamsungBrowser":void 0,i=/chrome|crios/i.test(e)?"Chrome":void 0,s=/chromium/i.test(e)?"Chromium":void 0,n=/firefox|fxios/i.test(e)?"Firefox":void 0,o=/webkit|safari|khtml/i.test(e)?"Safari":void 0,u=/opr\//i.test(e)?"Opera":void 0,l=/edg/i.test(e)?"Edge":void 0;this._current=t||r||n||u||l||i||s||o||"Rest"}catch(t){console.error(t)}this.isSafari&&this.detectSafariVersion()}detectSafariVersion(){try{let{userAgent:e}=window.navigator,t=e.match(/Version\/(\d+)/);if(!t)return;let r=t[1],i=parseInt(r,10);if(isNaN(i))return;this._safariVersion=i}catch(e){console.error(e)}}};var Og=B(Fe(),1);var Hi=()=>{var a,e;return/Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test((a=navigator.appVersion)!=null?a:navigator.userAgent)||((e=navigator==null?void 0:navigator.userAgentData)==null?void 0:e.mobile)};var tn=class{constructor(e){this._highEntropyValues={};this._displayChecker=e}get current(){return this._current}get isIOS(){let e=["iPhone","iPad","iPod"];return this._highEntropyValues.platform==="iOS"||(0,Og.default)(e,this.current)}get isMac(){return this._highEntropyValues.platform==="macOS"||this.current==="Mac"}get isApple(){return this.isIOS||this.isMac}get isIphoneOrOldIpad(){if(!this.isApple||!this._displayChecker.isTouch)return!1;let e=this.current==="iPad"||this._displayChecker.width>700,t=this._iosVersion;return!e||e&&!!t&&t<16}get isAndroid(){return this._highEntropyValues.platform==="Android"||this.current==="Android"}get isMobile(){return this._highEntropyValues.mobile||this._isMobile}get iOSVersion(){return this._iosVersion}detect(){let{userAgent:e}=navigator;try{this._isMobile=Hi()}catch(t){console.error(t)}this.detectDevice(e),this.detectHighEntropyValues(),this.isIOS&&this.detectIOSVersion()}detectHighEntropyValues(){return E(this,null,function*(){let{userAgentData:e}=navigator;if(e){let t=yield e.getHighEntropyValues(["architecture","bitness","brands","mobile","platform","formFactor","model","platformVersion","wow64"]);this._highEntropyValues=t}})}detectDevice(e){try{let t=/android/i.test(e)?"Android":void 0,r=/iphone/i.test(e)?"iPhone":void 0,i=/ipad/i.test(e)?"iPad":void 0,s=/ipod/i.test(e)?"iPod":void 0,n=/mac/i.test(e)?"Mac":void 0,o=/webOS|BlackBerry|IEMobile|Opera Mini/i.test(e)?"RestMobile":void 0;this._current=t||r||i||s||o||n||"Desktop"}catch(t){console.error(t)}}detectIOSVersion(){try{if(this._highEntropyValues.platformVersion){let s=this._highEntropyValues.platformVersion.split(".").slice(0,2).join("."),n=parseFloat(s);this._iosVersion=n;return}let{userAgent:e}=window.navigator,t=e.match(/OS (\d+(_\d+)?)/i);if(!t)return;let r=t[1].replace(/_/g,".");if(!r)return;let i=parseFloat(r);if(isNaN(i))return;this._iosVersion=i}catch(e){console.error(e)}}};var rn=class{get isTouch(){return typeof this._maxTouchPoints=="number"?this._maxTouchPoints>1:"ontouchstart"in window}get maxTouchPoints(){return this._maxTouchPoints}get height(){return this._height}get width(){return this._width}get screenHeight(){return this._screenHeight}get screenWidth(){return this._screenWidth}get pixelRatio(){return this._pixelRatio}get isHDR(){return this._isHdr}get colorDepth(){return this._colorDepth}detect(){var t;let{maxTouchPoints:e}=navigator;try{this._maxTouchPoints=e!=null?e:0,this._isHdr=!!((t=matchMedia("(dynamic-range: high)"))!=null&&t.matches),this._colorDepth=screen.colorDepth}catch(r){console.error(r)}try{this._pixelRatio=window.devicePixelRatio||1,this._height=screen.height,this._width=screen.width,this._height=screen.height,this._screenHeight=this._height*this._pixelRatio,this._screenWidth=this._width*this._pixelRatio}catch(r){console.error(r)}}};var Ze=()=>window.ManagedMediaSource||window.MediaSource,an=()=>{var a,e;return!!(window.ManagedMediaSource&&((e=(a=window.ManagedSourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},_g=()=>{var a,e;return!!(window.MediaSource&&((e=(a=window.SourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},Bg=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;var bR=document.createElement("video"),gR='video/mp4; codecs="avc1.42000a,mp4a.40.2"',vR='video/mp4; codecs="hev1.1.6.L93.B0"',Ng='video/webm; codecs="vp09.00.10.08"',Fg='video/webm; codecs="av01.0.00M.08"',SR='audio/mp4; codecs="mp4a.40.2"',yR='audio/webm; codecs="opus"',qg,TR=()=>E(void 0,null,function*(){if(!window.navigator.mediaCapabilities)return;let a={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=yield Promise.all([window.navigator.mediaCapabilities.decodingInfo(M(P({},a),{video:M(P({},a.video),{contentType:Fg})})),window.navigator.mediaCapabilities.decodingInfo(M(P({},a),{video:M(P({},a.video),{contentType:Ng})}))]);qg={DASH_WEBM_AV1:e,DASH_WEBM:t}});TR().catch(a=>{console.log(bR),console.error(a)});var sn=class{constructor(e,t){this._deviceChecker=e,this._browserChecker=t}get protocols(){return this._protocols}get containers(){return this._containers}get codecs(){return this._codecs}get webmDecodingInfo(){return qg}get supportedCodecs(){return Object.keys(this._codecs).filter(e=>this._codecs[e])}get nativeHlsSupported(){return this._nativeHlsSupported}detect(){var e,t,r,i,s,n,o,u,l,c,d,p,h,m,b,g,v,S,T,I;this._video=document.createElement("video");try{this._protocols={mms:an(),mse:_g(),hls:!!((t=(e=this._video).canPlayType)!=null&&t.call(e,"application/x-mpegurl")||(i=(r=this._video).canPlayType)!=null&&i.call(r,"vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},this._containers={mp4:!!((n=(s=this._video).canPlayType)!=null&&n.call(s,"video/mp4")),webm:!!((u=(o=this._video).canPlayType)!=null&&u.call(o,"video/webm")),cmaf:!0};let y=!!((c=(l=Ze())==null?void 0:l.isTypeSupported)!=null&&c.call(l,gR)),$=!!((p=(d=Ze())==null?void 0:d.isTypeSupported)!=null&&p.call(d,vR)),C=!!((m=(h=Ze())==null?void 0:h.isTypeSupported)!=null&&m.call(h,SR));this._codecs={h264:y,h265:$,vp9:!!((g=(b=Ze())==null?void 0:b.isTypeSupported)!=null&&g.call(b,Ng)),av1:!!((S=(v=Ze())==null?void 0:v.isTypeSupported)!=null&&S.call(v,Fg)),aac:C,opus:!!((I=(T=Ze())==null?void 0:T.isTypeSupported)!=null&&I.call(T,yR)),mpeg:(y||$)&&C},this._nativeHlsSupported=this._protocols.hls&&this._containers.mp4}catch(y){console.error(y)}this.destroyVideoElement()}destroyVideoElement(){var t;if(!this._video)return;if(this._video.pause(),this._video.currentTime=0,this._video.removeAttribute("src"),this._video.src="",this._video.load(),this._video.remove){this._video.remove(),this._video=null;return}this._video.parentNode&&this._video.parentNode.removeChild(this._video);let e=this._video.cloneNode(!1);(t=this._video.parentNode)==null||t.replaceChild(e,this._video),this._video=null}};var Ug="audio/mpeg",nn=class{supportMp3(){return this._codecs.mp3&&this._containers.mpeg}detect(){var e,t,r,i;this._audio=document.createElement("audio");try{this._containers={mpeg:!!((t=(e=this._audio).canPlayType)!=null&&t.call(e,Ug))},this._codecs={mp3:!!((i=(r=Ze())==null?void 0:r.isTypeSupported)!=null&&i.call(r,Ug))}}catch(s){console.error(s)}this.destroyAudioElement()}destroyAudioElement(){var t;if(!this._audio)return;if(this._audio.pause(),this._audio.currentTime=0,this._audio.removeAttribute("src"),this._audio.src="",this._audio.load(),this._audio.remove){this._audio.remove(),this._audio=null;return}this._audio.parentNode&&this._audio.parentNode.removeChild(this._audio);let e=this._audio.cloneNode(!1);(t=this._audio.parentNode)==null||t.replaceChild(e,this._audio),this._audio=null}};import{ValueSubject as IR}from"@vkontakte/videoplayer-shared/es2015";var ul=class{constructor(){this.isInited$=new IR(!1);this._displayChecker=new rn,this._deviceChecker=new tn(this._displayChecker),this._browserChecker=new en,this._videoChecker=new sn(this._deviceChecker,this._browserChecker),this._audioChecker=new nn,this.detect()}get display(){return this._displayChecker}get device(){return this._deviceChecker}get browser(){return this._browserChecker}get video(){return this._videoChecker}get audio(){return this._audioChecker}detect(){return E(this,null,function*(){this._displayChecker.detect(),this._deviceChecker.detect(),this._browserChecker.detect(),this._videoChecker.detect(),this._audioChecker.detect(),this.isInited$.next(!0)})}},H=new ul;var Re=a=>{let e=L=>$e(a,L).pipe(cl(void 0)),r=ll(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(L=>$e(a,L))).pipe(Vt(L=>L.type==="ended"?a.readyState<2:a.readyState<3),ER()),i=ll($e(a,"progress"),$e(a,"timeupdate")).pipe(Vt(()=>Vg(a.buffered,a.currentTime))),s=H.browser.isSafari?PR({play:e("play").pipe(wR()),playing:e("playing")}).pipe(cl(void 0)):e("playing"),n=$e(a,"volumechange").pipe(Vt(()=>({muted:a.muted,volume:a.volume}))),o=$e(a,"ratechange").pipe(Vt(()=>a.playbackRate)),u=$e(a,"error").pipe(ji(()=>!!(a.error||a.played.length)),Vt(()=>{var O;let L=a.error;return{id:L?`MediaError#${L.code}`:"HtmlVideoError",category:kR.VIDEO_PIPELINE,message:L?L.message:"Error event from HTML video element",thrown:(O=a.error)!=null?O:void 0}})),l=$e(a,"timeupdate").pipe(Vt(()=>a.currentTime)),c=new xR,d=.3,p;l.subscribe(L=>{a.loop&&Hg(p)&&Hg(L)&&p>=a.duration-d&&L<=d&&c.next(p),p=L});let h=e("pause").pipe(ji(()=>!a.error&&p!==a.duration)),m=$e(a,"enterpictureinpicture"),b=$e(a,"leavepictureinpicture"),g=new jg(Cg(a));m.subscribe(()=>g.next(!0)),b.subscribe(()=>g.next(!1));let v=new jg(ol(a));$e(a,"fullscreenchange").pipe(Vt(()=>ol(a))).subscribe(v);let T=.1,I=1e3,y=$e(a,"timeupdate").pipe(ji(L=>a.duration-a.currentTime<T)),$=ll(y.pipe(ji(L=>!a.loop)),$e(a,"ended")).pipe(AR(I),cl(void 0)),C=y.pipe(ji(L=>a.loop));return{playing$:s,pause$:h,canplay$:e("canplay"),ended$:$,looped$:c,loopExpected$:C,error$:u,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:l,durationChange$:$e(a,"durationchange").pipe(Vt(()=>a.duration)),isBuffering$:r,currentBuffer$:i,volumeState$:n,playbackRateState$:o,inPiP$:g,inFullscreen$:v,enterPip$:m,leavePip$:b}};import{VideoQuality as Ot}from"@vkontakte/videoplayer-shared/es2015";var _t=a=>{switch(a){case"mobile":return Ot.Q_144P;case"lowest":return Ot.Q_240P;case"low":return Ot.Q_360P;case"sd":case"medium":return Ot.Q_480P;case"hd":case"high":return Ot.Q_720P;case"fullhd":case"full":return Ot.Q_1080P;case"quadhd":case"quad":return Ot.Q_1440P;case"ultrahd":case"ultra":return Ot.Q_2160P}};var Nt=B(Bt(),1),nv=B(Fe(),1),ln=B(Br(),1);import{isNonNullable as Ee,isNullable as rv,now as ov,isHigher as iv,isHigherOrEqual as ml,isInvariantQuality as av,isLowerOrEqual as fl,videoSizeToQuality as NR,assertNotEmptyArray as uv,assertNonNullable as FR}from"@vkontakte/videoplayer-shared/es2015";var dl=!1,bt={},Xg=a=>{dl=a},Jg=()=>{bt={}},Zg=a=>{a(bt)},Qi=(a,e)=>{var t;dl&&(bt.meta=(t=bt.meta)!=null?t:{},bt.meta[a]=e)},Ie=class{constructor(e){this.name=e}next(e){var r,i;if(!dl)return;bt.series=(r=bt.series)!=null?r:{};let t=(i=bt.series[this.name])!=null?i:[];t.push([Date.now(),e]),bt.series[this.name]=t}};import{isHigher as _R,isHigherOrEqual as GN,isLower as ev,isLowerOrEqual as WN,isNonNullable as on,isNullable as BR,videoHeightToQuality as un}from"@vkontakte/videoplayer-shared/es2015";function pl({limits:a,highQualityLimit:e,trafficSavingLimit:t}){return!a.max&&a.min===e?"high_quality":!a.min&&a.max===t?"traffic_saving":"unknown"}function hl({limits:a,highQualityLimit:e,trafficSavingLimit:t}){return!!a&&pl({limits:a,highQualityLimit:e,trafficSavingLimit:t})==="high_quality"}function Gi({limits:a,highestAvailableQuality:e,lowestAvailableQuality:t}){return BR(a)||on(a.min)&&on(a.max)&&ev(a.max,a.min)||on(a.min)&&e&&_R(a.min,e)||on(a.max)&&t&&ev(a.max,t)}function tv({limits:a,highestAvailableHeight:e,lowestAvailableHeight:t}){return Gi({limits:{max:a!=null&&a.max?un(a.max):void 0,min:a!=null&&a.min?un(a.min):void 0},highestAvailableQuality:e?un(e):void 0,lowestAvailableQuality:t?un(t):void 0})}var qR=new Ie("best_bitrate"),lv=(a,e,t)=>(e-t)*Math.pow(2,-10*a)+t;var bl=a=>(e,t)=>a*(Number(e.bitrate)-Number(t.bitrate)),Wi=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=ov()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},cv='Assertion "ABR Tracks is empty array" failed',cn=(a,e,t,r)=>{var u;let i=[...e].sort(bl(1)),s=[...t].sort(bl(1)),n=s.filter(l=>Ee(l.bitrate)&&Ee(a.bitrate)?a.bitrate/l.bitrate>r:!0),o=(u=(0,Nt.default)(s,Math.round(s.length*i.indexOf(a)/(i.length+1))))!=null?u:(0,Nt.default)(s,-1);return o&&(0,nv.default)(n,o)?o:n.length?(0,Nt.default)(n,-1):(0,Nt.default)(s,0)},sv=a=>"quality"in a,dv=(a,e,t,r)=>{var n;let i=Ee((n=r==null?void 0:r.last)==null?void 0:n.bitrate)&&Ee(t==null?void 0:t.bitrate)&&r.last.bitrate<t.bitrate?a.trackCooldownIncreaseQuality:a.trackCooldownDecreaseQuality,s=t&&r&&r.history[t.id]&&ov()-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=sv(o)?"video":"audio",l=sv(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},UR=(a,e)=>Math.log(e)/Math.log(a),HR=({tuning:a,container:e,limits:t})=>{let r=a.containerSizeFactor;if(a.usePixelRatio&&H.display.pixelRatio){let i=H.display.pixelRatio;if(a.pixelRatioMultiplier)r*=a.pixelRatioMultiplier*(i-1)+1;else{let s=a.pixelRatioLogBase,[n=0,o=0,u=0]=a.pixelRatioLogCoefficients,l=UR(s,n*i+o)+u;Number.isFinite(l)&&(r*=l)}}return hl({highQualityLimit:a.highQualityLimit,trafficSavingLimit:a.trafficSavingLimit,limits:t})&&(r*=2),{containerSizeLimit:a.limitByContainer&&e&&e.width>0&&e.height>0?{width:e.width*r,height:e.height*r}:void 0,containerSizeFactor:r}},Ft=(a,{container:e,estimatedThroughput:t,tuning:r,limits:i,reserve:s=0,forwardBufferHealth:n,playbackRate:o,current:u,history:l,visible:c,droppedVideoMaxQualityLimit:d,stallsVideoMaxQualityLimit:p,stallsPredictedThroughput:h,abrLogger:m})=>{var z,q,Z,k,D;uv(a,cv);let{containerSizeFactor:b,containerSizeLimit:g}=HR({container:e,tuning:r,limits:i}),v=r.considerPlaybackRate&&Ee(o)?o:1,S=a.filter(x=>!av(x.quality)).sort((x,U)=>iv(x.quality,U.quality)?-1:1),T=(z=(0,Nt.default)(S,-1))==null?void 0:z.quality,I=(q=(0,Nt.default)(S,0))==null?void 0:q.quality,y=Gi({limits:i,lowestAvailableQuality:T,highestAvailableQuality:I}),$=v*lv(n!=null?n:.5,r.bitrateFactorAtEmptyBuffer,r.bitrateFactorAtFullBuffer),C={},O=S.filter(x=>{let U=!0;if(g)if(x.size)U=x.size.width<=g.width&&x.size.height<=g.height;else{let Qe=g&&NR(g);U=Qe?fl(x.quality,Qe):!0}if(!U)return C[x.quality]="FitsContainer",!1;let _=h||t,je=Ee(_)&&isFinite(_)&&Ee(x.bitrate)?_-s>=x.bitrate*$:!0,Et=hl({highQualityLimit:r.highQualityLimit,trafficSavingLimit:r.trafficSavingLimit,limits:i})&&(i==null?void 0:i.min)===x.quality;if(!je&&!Et)return C[x.quality]="FitsThroughput",!1;if(r.lazyQualitySwitch&&Ee(r.minBufferToSwitchUp)&&u&&!av(u.quality)&&(n!=null?n:0)<r.minBufferToSwitchUp&&iv(x.quality,u.quality))return C[x.quality]="Buffer",!1;if(!!d&&ml(x.quality,d)&&!Et)return C[x.quality]="DroppedFramesLimit",!1;if(!!p&&ml(x.quality,p)&&!Et)return C[x.quality]="StallsLimit",!1;let ye=y||(rv(i==null?void 0:i.max)||fl(x.quality,i.max))&&(rv(i==null?void 0:i.min)||ml(x.quality,i.min)),Pe=Ee(c)&&!c?fl(x.quality,r.backgroundVideoQualityLimit):!0;return!ye||!Pe?(C[x.quality]="FitsQualityLimits",!1):!0})[0];O&&O.bitrate&&qR.next(O.bitrate);let Q=(Z=O!=null?O:(0,Nt.default)(S,-1))!=null?Z:a[0],G=l==null?void 0:l.last,R=dv(r,m,Q,l);return Ee(l)&&R.quality!==(G==null?void 0:G.quality)&&m({message:`
|
|
10
10
|
[VIDEO TRACKS ABR]
|
|
11
11
|
[available video tracks]
|
|
12
|
-
${a.map(
|
|
12
|
+
${a.map(x=>{var U,_;return`{ id: ${x.id}, quality: ${x.quality}, bitrate: ${x.bitrate}, size: ${(U=x.size)==null?void 0:U.width}:${(_=x.size)==null?void 0:_.height} }`}).join(`
|
|
13
13
|
`)}
|
|
14
14
|
|
|
15
15
|
[tuning]
|
|
16
|
-
${(0,
|
|
16
|
+
${(0,ln.default)(r!=null?r:{}).map(([x,U])=>`${x}: ${U}`).join(`
|
|
17
17
|
`)}
|
|
18
18
|
|
|
19
19
|
[limit params]
|
|
20
20
|
containerSizeFactor: ${b},
|
|
21
|
-
containerSizeLimit: ${(
|
|
21
|
+
containerSizeLimit: ${(k=g==null?void 0:g.width)!=null?k:0} x ${(D=g==null?void 0:g.height)!=null?D:0},
|
|
22
22
|
estimatedThroughput: ${t},
|
|
23
23
|
stallsPredictedThroughput: ${h},
|
|
24
24
|
reserve: ${s},
|
|
25
25
|
playbackRate: ${o},
|
|
26
26
|
playbackRateFactor: ${v},
|
|
27
27
|
forwardBufferHealth: ${n},
|
|
28
|
-
bitrateFactor: ${
|
|
28
|
+
bitrateFactor: ${$},
|
|
29
29
|
minBufferToSwitchUp: ${r.minBufferToSwitchUp},
|
|
30
30
|
droppedVideoMaxQualityLimit: ${d},
|
|
31
31
|
stallsVideoMaxQualityLimit: ${p},
|
|
32
|
-
limitsAreInvalid: ${
|
|
32
|
+
limitsAreInvalid: ${y},
|
|
33
33
|
maxQualityLimit: ${i==null?void 0:i.max},
|
|
34
34
|
minQualityLimit: ${i==null?void 0:i.min},
|
|
35
35
|
|
|
36
36
|
[limited video tracks]
|
|
37
|
-
${(0,
|
|
37
|
+
${(0,ln.default)(C).map(([x,U])=>`${x}: ${U}`).join(`
|
|
38
38
|
`)||"All tracks are available"}
|
|
39
39
|
|
|
40
|
-
[best video track] ${
|
|
41
|
-
[selected video track] ${
|
|
42
|
-
`}),
|
|
40
|
+
[best video track] ${O==null?void 0:O.quality}
|
|
41
|
+
[selected video track] ${R==null?void 0:R.quality}
|
|
42
|
+
`}),R},pv=(a,e,t,{estimatedThroughput:r,tuning:i,playbackRate:s,forwardBufferHealth:n,history:o,abrLogger:u,stallsPredictedThroughput:l})=>{uv(t,cv);let c=i.considerPlaybackRate&&Ee(s)?s:1,d=[...t].sort(bl(-1)),p=a.bitrate;FR(p);let h=c*lv(n!=null?n:.5,i.bitrateAudioFactorAtEmptyBuffer,i.bitrateAudioFactorAtFullBuffer),m,b=cn(a,e,t,i.minVideoAudioRatio),g=l||r;Ee(g)&&isFinite(g)&&(m=d.find(T=>Ee(T.bitrate)&&Ee(b==null?void 0:b.bitrate)?g-p>=T.bitrate*h&&T.bitrate>=b.bitrate:!1)),m||(m=b);let v=o==null?void 0:o.last,S=m&&dv(i,u,m,o);return Ee(o)&&(S==null?void 0:S.bitrate)!==(v==null?void 0:v.bitrate)&&u({message:`
|
|
43
43
|
[AUDIO TRACKS ABR]
|
|
44
44
|
[available audio tracks]
|
|
45
|
-
${t.map(
|
|
45
|
+
${t.map(T=>`{ id: ${T.id}, bitrate: ${T.bitrate} }`).join(`
|
|
46
46
|
`)}
|
|
47
47
|
|
|
48
48
|
[tuning]
|
|
49
|
-
${(0,
|
|
49
|
+
${(0,ln.default)(i!=null?i:{}).map(([T,I])=>`${T}: ${I}`).join(`
|
|
50
50
|
`)}
|
|
51
51
|
|
|
52
52
|
[limit params]
|
|
@@ -59,15 +59,15 @@ var eI=Object.create;var ro=Object.defineProperty,tI=Object.defineProperties,rI=
|
|
|
59
59
|
bitrateFactor: ${h},
|
|
60
60
|
minBufferToSwitchUp: ${i.minBufferToSwitchUp},
|
|
61
61
|
|
|
62
|
-
[selected audio track] ${
|
|
63
|
-
`}),m&&cv(i,u,m,o)};var ce=a=>new URL(a).hostname;import{assertNever as Iv,assertNonNullable as Ev,combine as l$,debounce as c$,ErrorCategory as xv,filter as Pv,filterChanged as d$,isNonNullable as gl,map as pn,merge as wv,observableFrom as p$,once as h$,Subscription as m$,ValueSubject as vl,videoQualityToHeight as Av,videoSizeToQuality as f$}from"@vkontakte/videoplayer-shared/es2015";var vv=_(Bt(),1);var hv=_(Fe(),1);var pv=a=>{if(a instanceof DOMException&&(0,hv.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"))},Re=(a,e)=>x(void 0,null,function*(){let t=a.muted;try{yield a.play()}catch(r){if(!pv(r))return!1;if(e&&e(),t)return console.warn(r),!1;a.muted=!0;try{yield a.play()}catch(i){return pv(i)&&(a.muted=!1,console.warn(i)),!1}}return!0});import{isNonNullable as ln,isNullable as QL,assertNonNullable as Yi}from"@vkontakte/videoplayer-shared/es2015";var fv=_(zr(),1);import{isNonNullable as mv,assertNonNullable as un,now as HL}from"@vkontakte/videoplayer-shared/es2015";function de(){return HL()}function hl(a){return de()-a}function ml(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 bv(a,e,t){let r=(...i)=>{t.apply(null,i),a.removeEventListener(e,r)};a.addEventListener(e,r)}function Xr(a,e,t,r){let i=window.XMLHttpRequest,s,n,o,u=!1,l=0,c,d,p=!1,h="arraybuffer",m=7e3,b=2e3,g=()=>{if(u)return;un(c);let L=hl(c),W;if(L<b){W=b-L,setTimeout(g,W);return}b*=2,b>m&&(b=m),n&&n.abort(),n=new i,R()},v=L=>(s=L,Q),S=L=>(d=L,Q),y=()=>(h="json",Q),I=()=>{if(!u){if(--l>=0){g(),r&&r();return}u=!0,d&&d(),t&&t()}},E=L=>(p=L,Q),R=()=>{c=de(),n=new i,n.open("get",a);let L=0,W,q=0,J=()=>(un(c),Math.max(c,Math.max(W||0,q||0)));if(s&&n.addEventListener("progress",k=>{let T=de();s.updateChunk&&k.loaded>L&&(s.updateChunk(J(),k.loaded-L),L=k.loaded,W=T)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>I())),n.addEventListener("load",()=>{if(u)return;un(n);let k=n.status;if(k>=200&&k<300){let{response:T,responseType:V}=n,Y=T==null?void 0:T.byteLength;if(typeof Y=="number"&&s){let U=Y-L;U&&s.updateChunk&&s.updateChunk(J(),U)}V==="json"&&(!T||!(0,fv.default)(T).length)?I():(d&&d(),e(T))}else I()}),n.addEventListener("error",()=>{I()}),p){let k=()=>{un(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(q=de(),n.removeEventListener("readystatechange",k))};n.addEventListener("readystatechange",k)}return n.responseType=h,n.send(),Q},Q={withBitrateReporting:v,withParallel:E,withJSONResponse:y,withRetryCount:L=>(l=L,Q),withRetryInterval:(L,W)=>(mv(L)&&(b=L),mv(W)&&(m=W),Q),withTimeout:L=>(o=L,Q),withFinally:S,send:R,abort:()=>{n&&(n.abort(),n=void 0),u=!0,d&&d()}};return Q}var Gi=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 gv=_(zr(),1);var Wi=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=de(),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=de()-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=Xr(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=de()}_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=de();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,gv.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 GL}from"@vkontakte/videoplayer-shared/es2015";var cn=1e4,fl=3;var WL=6e4,YL=10,zL=1,KL=500,zi=class{constructor(e){this.paused=!1;this.autoQuality=!0;this.autoQualityLimits=void 0;this.buffering=!0;this.destroyed=!1;this.videoPlayStarted=!1;this.lowLatency=!1;this.bitrate=0;this.manifest=[];this.sourceBuffer=0;this.bufferStates=[];this.sourceJitter=-1;this.params=e,this.soundProhibitedEvent$=new GL,this.chunkRateEstimator=new Gi(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=ml(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setAutoQualityLimits(e){this.autoQualityLimits=e}switchByName(e){let t;for(let r=0;r<this.manifest.length;++r)if(t=this.manifest[r],t.name===e){this._switchToQuality(t);return}}catchUp(){this.rep&&this.rep.stop(),this.currentManifestEntry&&(this.paused=!1,this._initPlayerWith(this.currentManifestEntry),this._notifyBuffering(!0))}stop(){this.params.videoElement.pause(),this.rep&&(this.rep.stop(),this.rep=null)}pause(){this.paused=!0,this.params.videoElement.pause(),this.videoPlayStarted=!1,this._notifyBuffering(!1)}play(){this.paused=!1;let e=this.lowLatency&&this._getBufferSizeSec()>this.sourceJitter+5;this.rep&&!e?(this.bufferStates=[],this.videoPlayStarted=!1,this.shouldPlay()?this._playVideoElement():this._notifyBuffering(!0)):this.catchUp()}startPlay(e,t){this.autoQuality=t,this._initPlayerWith(e)}destroy(){this.destroyed=!0,this.rep&&(this.rep.stop(),this.rep=null),this.manifestRequest&&this.manifestRequest.abort(),this.manifestRefetchTimer&&(clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=void 0)}reinit(e){this.manifestUrl=e,this.urlResolver=ml(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*(N.display.pixelRatio||1)*t.offsetHeight||520;for(let o=0;o<this.manifest.length;++o){s=this.manifest[o];let{max:u,min:l}=this.autoQualityLimits||{};!ev({limits:this.autoQualityLimits,highestAvailableHeight:this.manifest[0].video.height,lowestAvailableHeight:(0,vv.default)(this.manifest,-1).video.height})&&(u&&s.video.height>u||l&&s.video.height<l)||(s.bitrate<e&&n>Math.min(s.video.height,s.video.width)?(!i||s.bitrate>i.bitrate)&&(i=s):(!r||r.bitrate>s.bitrate)&&(r=s))}return i||r}shouldPlay(){if(this.paused)return!1;let t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||ln(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=()=>{bv(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 Wi(fl,cn,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){let{logger:t,videoElement:r,playerCallback:i}=this.params,s=!1,n=null,o=null,u=null,l=null,c=!1,d=()=>{let I=s&&(!c||c===this.rep);return I||t("Not running!"),I},p=(I,E,R)=>{u&&u.abort(),u=Xr(this.urlResolver.resolve(I,!1),E,R,()=>this._retryCallback()).withTimeout(cn).withBitrateReporting(this.bitrateSwitcher).withRetryCount(fl).withFinally(()=>{u=null}).send()},h=(I,E,R)=>{Yi(this.filesFetcher),o==null||o.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(I,!1),E,R,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},m=I=>{let E=r.playbackRate;r.playbackRate!==I&&(t(`Playback rate switch: ${E}=>${I}`),r.playbackRate=I)},b=I=>{this.lowLatency=I,t(`lowLatency changed to ${I}`),g()},g=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)m(1);else{let I=this._getBufferSizeSec();if(this.bufferStates.length<5){m(1);return}let R=de()-1e4,M=0;for(let C=0;C<this.bufferStates.length;C++){let j=this.bufferStates[C];I=Math.min(I,j.buf),j.ts<R&&M++}this.bufferStates.splice(0,M),t(`update playback rate; minBuffer=${I} drop=${M} jitter=${this.sourceJitter}`);let re=I-zL;this.sourceJitter>=0?re-=this.sourceJitter/2:this.sourceJitter-=1,re>3?m(1.15):re>1?m(1.1):re>.3?m(1.05):m(1)}},v=I=>{let E,R=()=>E&&E.start?E.start.length:0,M=k=>E.start[k]/1e3,re=k=>E.dur[k]/1e3,C=k=>E.fragIndex+k,j=(k,T)=>({chunkIdx:C(k),startTS:M(k),dur:re(k),discontinuity:T}),Q=()=>{let k=0;if(E&&E.dur){let T=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,V=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,Y=T;this.sourceJitter>1&&(Y+=this.sourceJitter-1);let U=E.dur.length-1;for(;U>=0&&(Y-=E.dur[U],!(Y<=0));--U);k=Math.min(U,E.dur.length-1-V),k=Math.max(k,0)}return j(k,!0)},L=k=>{let T=R();if(!(T<=0)){if(ln(k)){for(let V=0;V<T;V++)if(M(V)>k)return j(V)}return Q()}},W=k=>{let T=R(),V=k?k.chunkIdx+1:0,Y=V-E.fragIndex;if(!(T<=0)){if(!k||Y<0||Y-T>YL)return t(`Resync: offset=${Y} bChunks=${T} chunk=`+JSON.stringify(k)),Q();if(!(Y>=T))return j(V-E.fragIndex,!1)}},q=(k,T,V)=>{l&&l.abort(),l=Xr(this.urlResolver.resolve(k,!0,this.lowLatency),T,V,()=>this._retryCallback()).withTimeout(cn).withRetryCount(fl).withFinally(()=>{l=null}).withJSONResponse().send()};return{seek:(k,T)=>{q(I,V=>{if(!d())return;E=V;let Y=!!E.lowLatency;Y!==this.lowLatency&&b(Y);let U=0;for(let $e=0;$e<E.dur.length;++$e)U+=E.dur[$e];U>0&&(Yi(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(U/E.dur.length)),i({name:"index",zeroTime:E.zeroTime,shiftDuration:E.shiftDuration}),this.sourceJitter=E.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,E.jitter/1e3)):1,k(L(T))},()=>this._handleNetworkError())},nextChunk:W}},S=()=>{s=!1,o&&o.abort(),u&&u.abort(),l&&l.abort(),Yi(this.filesFetcher),this.filesFetcher.abortAll()};return c={start:I=>{let{videoElement:E,logger:R}=this.params,M=v(e.jidxUrl),re,C,j,Q,L=0,W,q,J,k=()=>{W&&(clearTimeout(W),W=void 0);let z=Math.max(KL,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),he=L+z,Se=de(),ye=Math.min(1e4,he-Se);L=Se;let Et=()=>{l||d()&&M.seek(()=>{d()&&(L=de(),T(),k())})};ye>0?W=window.setTimeout(()=>{this.paused?k():Et()},ye):Et()},T=()=>{let z;for(;z=M.nextChunk(Q);)Q=z,ui(z);let he=M.nextChunk(j);if(he){if(j&&he.discontinuity){R("Detected discontinuity; restarting playback"),this.paused?k():(S(),this._initPlayerWith(e));return}$e(he)}else k()},V=(z,he)=>{if(!d()||!this.sourceBuffer)return;let Se,ye,Et,Tr=xt=>{window.setTimeout(()=>{d()&&V(z,he)},xt)};if(this.sourceBuffer.updating)R("Source buffer is updating; delaying appendBuffer"),Tr(100);else{let xt=de(),Yt=E.currentTime;!this.paused&&E.buffered.length>1&&q===Yt&&xt-J>500&&(R("Stall suspected; trying to fix"),this._fixupStall()),q!==Yt&&(q=Yt,J=xt);let Ir=this._getBufferSizeSec();if(Ir>30)R(`Buffered ${Ir} seconds; delaying appendBuffer`),Tr(2e3);else try{this.sourceBuffer.appendBuffer(z),this.videoPlayStarted?(this.bufferStates.push({ts:xt,buf:Ir}),g(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),he&&he()}catch(li){if(li.name==="QuotaExceededError")R("QuotaExceededError; delaying appendBuffer"),Et=this.sourceBuffer.buffered.length,Et!==0&&(Se=this.sourceBuffer.buffered.start(0),ye=Yt,ye-Se>4&&this.sourceBuffer.remove(Se,ye-3)),Tr(1e3);else throw li}}},Y=()=>{C&&re&&(R([`Appending chunk, sz=${C.byteLength}:`,JSON.stringify(j)]),V(C,function(){C=null,T()}))},U=z=>e.fragUrlTemplate.replace("%%id%%",z.chunkIdx),$e=z=>{d()&&h(U(z),(he,Se)=>{if(d()){if(Se/=1e3,C=he,j=z,n=z.startTS,Se){let ye=Math.min(10,z.dur/Se);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*ye:ye}Y()}},()=>this._handleNetworkError())},ui=z=>{d()&&(Yi(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(U(z),!1)))},yr=z=>{d()&&(e.cachedHeader=z,V(z,()=>{re=!0,Y()}))};s=!0,M.seek(z=>{if(d()){if(L=de(),!z){k();return}Q=z,!QL(I)||z.startTS>I?$e(z):(j=z,T())}},I),e.cachedHeader?yr(e.cachedHeader):p(e.headerUrl,yr,()=>this._handleNetworkError())},stop:S,getTimestampSec:()=>n},c}_switchToQuality(e){let{logger:t,playerCallback:r}=this.params,i;e.bitrate!==this.bitrate&&(this.rep&&(i=this.rep.getTimestampSec(),ln(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,Yi(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(i),r({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return ln(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,r=d=>{if(!this.autoQuality)return;let p,h,m;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&d<this.bitrate&&(h=this._getBufferSizeSec(),m=d/this.bitrate,h>10&&m>.8||h>15&&m>.5||h>20&&m>.3)){e(`Not switching: buffer=${Math.floor(h)}; bitrate=${this.bitrate}; newRate=${Math.floor(d)}`);return}p=this._selectQuality(d),p?this._switchToQuality(p):e(`Could not find quality by bitrate ${d}`)},s={updateChunk:(p,h)=>{let m=de();if(this.chunkRateEstimator.addInterval(p,m,h)){let g=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:h,duration:m-p,speed:g}),!0}},get:()=>{let p=this.chunkRateEstimator.getBitRate();return p?p*.85:0}},n=-1/0,o,u=!0,l=()=>{let d=s.get();if(d&&o&&this.autoQuality){if(u&&d>o&&hl(n)<3e4)return;r(d)}u=this.autoQuality};return{updateChunk:(d,p)=>{let h=s.updateChunk(d,p);return h&&l(),h},notifySwitch:d=>{let p=de();d<o&&(n=p),o=d}}}_fetchManifest(e,t,r){this.manifestRequest=Xr(this.urlResolver.resolve(e,!0),t,r,()=>this._retryCallback()).withJSONResponse().withTimeout(cn).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;Re(e,()=>{this.soundProhibitedEvent$.next()}).then(t=>{t||(this.params.liveOffset.pause(),this.params.videoState.setState("paused"))})}_handleManifestUpdate(e){let{logger:t,playerCallback:r,videoElement:i}=this.params,s=n=>{let o=[];return n!=null&&n.length?(n.forEach((u,l)=>{var c,d;u.video&&i.canPlayType(u.codecs).replace(/no/,"")&&((d=(c=window.MediaSource)==null?void 0:c.isTypeSupported)!=null&&d.call(c,u.codecs))&&(u.index=l,o.push(u))}),o.sort(function(u,l){return u.video&&l.video?l.video.height-u.video.height:l.bitrate-u.bitrate}),o):(r({name:"error",type:"empty_manifest"}),[])};this.manifest=s(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),r({name:"manifest",manifest:this.manifest})}_refetchManifest(e){this.destroyed||(this.manifestRefetchTimer&&clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=window.setTimeout(()=>{this._fetchManifest(e,t=>{this.destroyed||(this._handleManifestUpdate(t),this._refetchManifest(e))},()=>this._refetchManifest(e))},WL))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};var Tv=_(Br(),1);import{debounce as XL,filter as Sv,fromEvent as JL,interval as ZL,isHigher as e$,isInvariantQuality as t$,isLower as r$,merge as i$,Subject as yv,Subscription as a$}from"@vkontakte/videoplayer-shared/es2015";var bl=class{constructor(){this.onDroopedVideoFramesLimit$=new yv;this.subscription=new a$;this.playing=!1;this.tracks=[];this.forceChecker$=new yv;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&&!t$(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&&e$(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(JL(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=ZL(this.droppedFramesChecker.checkTime).pipe(Sv(()=>this.playing),Sv(()=>{let i=!!this.isForceCheckCounter;return i&&(this.isForceCheckCounter-=1),!i})),t=this.forceChecker$.pipe(XL(this.droppedFramesChecker.checkTime)),r=i$(e,t);this.subscription.add(r.subscribe(this.checkDroppedFrames))}onChangeQuality(e){this.currentQuality=e;let{totalVideoFrames:t,droppedVideoFrames:r}=this.video.getVideoPlaybackQuality();this.savePrevFrameCounts(t,r),this.isForceCheckCounter=this.droppedFramesChecker.tickCountAfterQualityChange,this.forceChecker$.next()}onDroopedVideoFramesLimitTrigger(){this.isAuto.getState()&&(this.log({message:`[onDroopedVideoFramesLimit]. maxQualityLimit: ${this.maxQualityLimit}`}),this.onDroopedVideoFramesLimit$.next())}getMaxQualityLimit(e){var r,i;let t=(i=(r=(0,Tv.default)(this.limitCounts).filter(([,s])=>s>=this.droppedFramesChecker.countLimit).sort(([s],[n])=>r$(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}},dn=bl;import{map as s$,Observable as n$}from"@vkontakte/videoplayer-shared/es2015";import{fromEvent as o$}from"@vkontakte/videoplayer-shared/es2015";var Ki=()=>{var a;return!!((a=window.documentPictureInPicture)!=null&&a.window)||!!document.pictureInPictureElement};var u$=(a,e)=>new n$(t=>{if(!window.IntersectionObserver)return;let r={root:null},i=new IntersectionObserver((n,o)=>{n.forEach(u=>t.next(u.isIntersecting||Ki()))},P(P({},r),e));i.observe(a);let s=o$(document,"visibilitychange").pipe(s$(n=>!document.hidden||Ki())).subscribe(n=>t.next(n));return()=>{i.unobserve(a),s.unsubscribe}}),je=u$;var b$=["paused","playing","ready"],g$=["paused","playing","ready"],Xi=class{constructor(e){this.subscription=new m$;this.videoState=new O("stopped");this.representations$=new vl([]);this.droppedFramesManager=new dn;this.maxSeekBackTime$=new vl(1/0);this.zeroTime$=new vl(void 0);this.liveOffset=new pr;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:xv.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{let n=e.manifest,o=[];for(let u of n){let l=(t=u.name)!=null?t:u.index.toString(10),c=(r=Ot(u.name))!=null?r:f$(u.video),d=u.bitrate/1e3,p=P({},u.video);if(!c)continue;let h={id:l,quality:c,bitrate:d,size:p};o.push({track:h,representation:u})}this.representations$.next(o),this.params.output.availableVideoTracks$.next(o.map(({track:u})=>u)),((i=this.videoState.getTransition())==null?void 0:i.to)==="manifest_ready"&&this.videoState.setState("manifest_ready");break}case"qualitySwitch":{let n=e.quality,o=(s=this.representations$.getValue().find(({representation:u})=>u===n))==null?void 0:s.track;this.params.output.hostname$.next(new URL(n.headerUrl,this.params.source.url).hostname),gl(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,Sl.default)(g$,e)&&(n||o)){this.prepare();return}if((i==null?void 0:i.to)!=="paused"&&s.state==="requested"&&(0,Sl.default)(b$,e)){this.seek(s.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(be(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(be(this.params.source.url,u))}return;default:return Iv(e)}};this.textTracksManager=new Ue(e.source.url),this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=i=>{e.output.error$.next({id:"DashLiveProvider",category:xv.WTF,message:"DashLiveProvider internal logic error",thrown:i})};wv(this.videoState.stateChangeStarted$.pipe(pn(i=>({transition:i,type:"start"}))),this.videoState.stateChangeEnded$.pipe(pn(i=>({transition:i,type:"end"})))).subscribe(({transition:i,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(i)}`})}),this.video=Pe(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(ce(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=ke(this.video);this.subscription.add(this.representations$.pipe(pn(i=>i.map(({track:s})=>s)),Pv(i=>!!i.length),h$()).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(d$(),pn(i=>-i/1e3)).subscribe(this.params.output.duration$)).add(l$({zeroTime:this.zeroTime$.pipe(Pv(gl)),position:r.timeUpdate$}).subscribe(({zeroTime:i,position:s})=>this.params.output.liveTime$.next(i+s*1e3),t)).add(nt(this.video,this.params.desiredState.isLooped,t)).add(Ae(this.video,this.params.desiredState.volume,r.volumeState$,t)).add(r.volumeState$.subscribe(this.params.output.volume$,t)).add(qe(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(je(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:i,min:s}})=>{this.dash.setAutoQualityLimits({max:i&&Av(i),min:s&&Av(s)}),this.params.output.autoVideoTrackLimits$.next({max:i,min:s})})).add(this.videoState.stateChangeEnded$.subscribe(i=>{var s;switch(i.to){case"stopped":this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState("stopped");break;case"manifest_ready":case"ready":((s=this.params.desiredState.playbackState.getTransition())==null?void 0:s.to)==="ready"&&this.params.desiredState.playbackState.setState("ready");break;case"paused":this.params.desiredState.playbackState.setState("paused");break;case"playing":this.params.desiredState.playbackState.setState("playing");break;default:return Iv(i.to)}},t)).add(wv(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,p$(["init"])).pipe(c$(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),we(this.video)}createLiveDashPlayer(){let e=new zi({videoElement:this.video,videoState:this.videoState,liveOffset:this.liveOffset,config:{maxParallelRequests:this.params.config.maxParallelRequests,minBuffer:this.params.tuning.live.minBuffer,minBufferSegments:this.params.tuning.live.minBufferSegments,lowLatencyMinBuffer:this.params.tuning.live.lowLatencyMinBuffer,lowLatencyMinBufferSegments:this.params.tuning.live.lowLatencyMinBufferSegments,isLiveCatchUpMode:this.params.tuning.live.isLiveCatchUpMode,manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},playerCallback:this._dashCb,logger:t=>{this.params.dependencies.logger.log({message:String(t),component:"LiveDashPlayer"})}});return e.pause(),e}prepare(){var l,c,d,p,h,m;let e=this.representations$.getValue(),t=(c=(l=this.params.desiredState.videoTrack.getTransition())==null?void 0:l.to)!=null?c:this.params.desiredState.videoTrack.getState(),r=(p=(d=this.params.desiredState.autoVideoTrackSwitching.getTransition())==null?void 0:d.to)!=null?p:this.params.desiredState.autoVideoTrackSwitching.getState(),i=!r&&gl(t)?t:Ft(e.map(({track:b})=>b),{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),s=i==null?void 0:i.id,n=this.params.desiredState.videoTrack.getTransition(),o=(h=this.params.desiredState.videoTrack.getState())==null?void 0:h.id,u=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(i&&(n||s!==o)&&this.setVideoTrack(i),u&&this.setAutoQuality(r),n||u||s!==o){let b=(m=e.find(({track:g})=>g.id===s))==null?void 0:m.representation;Ev(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;Ev(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(be(this.params.source.url,n)),i&&this.dash.pause(),this.liveOffset.resetTo(n,i)}};var kv=Xi;var Jy=_(Fe(),1);var ut=(a,e)=>{let t=0;for(let r=0;r<a.length;r++){let i=a.start(r)*1e3,s=a.end(r)*1e3;i<=e&&e<=s&&(t=s)}return Math.max(t-e,0)};import{assertNever as XC,assertNonNullable as JC,debounce as ZC,ErrorCategory as Yy,filter as zy,filterChanged as Ba,fromEvent as eD,isNonNullable as Ky,map as nc,merge as Dn,observableFrom as oc,once as Xy,Subscription as tD}from"@vkontakte/videoplayer-shared/es2015";var hn=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 hn{constructor(){super(),this.listeners||hn.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)}},Ji=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&&(Ji.prototype[Symbol.toStringTag]="AbortController",Jr.prototype[Symbol.toStringTag]="AbortSignal");function mn(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 yl(a){typeof a=="function"&&(a={fetch:a});let{fetch:e,Request:t=e.Request,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:i=!1}=a;if(!mn({fetch:e,Request:t,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:i}))return{fetch:e,Request:s};let s=t;(s&&!s.prototype.hasOwnProperty("signal")||i)&&(s=function(l,c){let d;c&&c.signal&&(d=c.signal,delete c.signal);let p=new t(l,c);return d&&Object.defineProperty(p,"signal",{writable:!1,enumerable:!1,configurable:!0,value:d}),p},s.prototype=t.prototype);let n=e;return{fetch:(u,l)=>{let c=s&&s.prototype.isPrototypeOf(u)?u.signal:l?l.signal:void 0;if(c){let d;try{d=new DOMException("Aborted","AbortError")}catch(h){d=new Error("Aborted"),d.name="AbortError"}if(c.aborted)return Promise.reject(d);let p=new Promise((h,m)=>{c.addEventListener("abort",()=>m(d),{once:!0})});return l&&l.signal&&delete l.signal,Promise.race([p,n(u,l)])}return n(u,l)},Request:s}}var Zi=mn({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),Rv=Zi?yl({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,lt=Zi?Rv.fetch:window.fetch,Iq=Zi?Rv.Request:window.Request,ge=Zi?Ji:window.AbortController,Eq=Zi?Jr:window.AbortSignal;var rc=_(Il(),1);var fS=_(mS(),1);import{ErrorCategory as ta}from"@vkontakte/videoplayer-shared/es2015";var bS=a=>{if(!a)return{id:"EmptyResponse",category:ta.PARSER,message:"Empty response"};if(a.length<=2&&a.match(/^\d+$/))return{id:`UVError#${a}`,category:ta.NETWORK,message:`UV Error ${a}`};let e=(0,fS.default)(a).substring(0,100).toLowerCase();if(e.startsWith("<!doctype")||e.startsWith("<html>")||e.startsWith("<body>")||e.startsWith("<head>"))return{id:"UnexpectedHTML",category:ta.NETWORK,message:"Received unexpected HTML, possibly a ISP block"};if(e.startsWith("<?xml"))return new DOMParser().parseFromString(a,"text/xml").querySelector("parsererror")?{id:"InvalidXML",category:ta.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:ta.PARSER,message:"Response is valid XML, but parser failed"}};var qt=(a,e,t=0)=>{for(let r=0;r<a.length;r++)if(a.start(r)*1e3-t<=e&&a.end(r)*1e3+t>e)return!0;return!1};import{abortable as Zl,assertNonNullable as ai,combine as si,ErrorCategory as ct,filter as wn,filterChanged as An,flattenObject as _a,fromEvent as yt,getTraceSubscriptionMethod as DC,interval as ec,isNonNullable as Fy,isNullable as qy,map as Oa,merge as vr,now as tc,Subject as kn,Subscription as Uy,tap as VC,throttle as _C,ValueSubject as ie}from"@vkontakte/videoplayer-shared/es2015";var bn=_(Fe(),1),ri=_(Bt(),1),gn=_(Il(),1);var rM=(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)},iM=a=>window.clearTimeout(a),gS=a=>typeof a=="function"&&(a==null?void 0:a.toString().endsWith("{ [native code] }")),vS=!gS(window.requestIdleCallback)||!gS(window.cancelIdleCallback),Al=vS?rM:window.requestIdleCallback,ra=vS?iM:window.cancelIdleCallback;var Ay=_(Ws(),1);import{assertNever as aM,ErrorCategory as SS,Subject as yS}from"@vkontakte/videoplayer-shared/es2015";var sM=18,TS=!1;try{TS=N.browser.isSafari&&!!N.browser.safariVersion&&N.browser.safariVersion<=sM}catch(a){console.error(a)}var kl=class{constructor(e){this.bufferFull$=new yS;this.error$=new yS;this.queue=[];this.currentTask=null;this.destroyed=!1;this.abortRequested=!1;this.completeTask=()=>{var e;try{if(this.currentTask){let t=(e=this.currentTask.signal)==null?void 0:e.aborted;this.currentTask.callback(!t),this.currentTask=null}this.queue.length&&this.pull()}catch(t){this.error$.next({id:"BufferTaskQueueUnknown",category:SS.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:t})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}append(e,t){return x(this,null,function*(){return t&&t.aborted?!1:new Promise(r=>{let i={operation:"append",data:e,signal:t,callback:r};this.queue.push(i),this.pull()})})}remove(e,t,r){return x(this,null,function*(){return r&&r.aborted?!1:new Promise(i=>{let s={operation:"remove",from:e,to:t,signal:r,callback:i};this.queue.unshift(s),this.pull()})})}abort(e){return x(this,null,function*(){return new Promise(t=>{let r,i=s=>{this.abortRequested=!1,t(s)};TS&&e?r={operation:"safariAbort",init:e,callback:i}:r={operation:"abort",callback:i};for(let{callback:s}of this.queue)s(!1);this.abortRequested=!0,r&&(this.queue=[r]),this.pull()})})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){var i;if((this.buffer.updating||this.currentTask||this.destroyed)&&!this.abortRequested)return;let e=this.queue.shift();if(!e)return;if((i=e.signal)!=null&&i.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(s){s instanceof DOMException&&s.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):s instanceof DOMException&&s.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:SS.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:aM(t)}}},IS=kl;var Rl=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 Ht,assertNonNullable as Le,ErrorCategory as St,fromEvent as Gl,getExponentialDelay as Wl,isNonNullable as ti,isNullable as ve,now as fn,once as TC,Subject as IC,Subscription as EC,ValueSubject as fr}from"@vkontakte/videoplayer-shared/es2015";var H=class{constructor(e,t){this.cursor=0;this.source=e,this.boxParser=t,this.children=[];let r=this.readUint32();this.type=this.readString(4),this.size32=r<=e.buffer.byteLength-e.byteOffset?r:NaN;let i=this.size32?this.size32-8:void 0,s=e.byteOffset+this.cursor;this.size64=0,this.usertype=0,this.content=new DataView(e.buffer,s,i)}get id(){return this.type}get size(){return this.size32}scanForBoxes(e){return this.boxParser.parse(e)}readString(e,t="ascii"){let i=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,i}readUint8(){let e=this.source.getUint8(this.cursor);return this.cursor+=1,e}readUint16(){let e=this.source.getUint16(this.cursor);return this.cursor+=2,e}readUint32(){let e=this.source.getUint32(this.cursor);return this.cursor+=4,e}readUint64(){let e=this.source.getBigInt64(this.cursor);return this.cursor+=8,e}};var Zr=class extends H{};var ia=class extends H{constructor(t,r){super(t,r);this.ondemandPrefix="ondemandlivejson";this.ondemandDataReceivedKey="t-in";this.ondemandDataPreparedKey="t-out";let i=this.content.byteOffset,s=i+this.content.byteLength,n=new TextDecoder("ascii").decode(this.content.buffer.slice(i,s)).split(this.ondemandPrefix)[1],o=JSON.parse(n);this.serverDataReceivedTimestamp=o[this.ondemandDataReceivedKey],this.serverDataPreparedTime=o[this.ondemandDataPreparedKey]}};var aa=class extends H{constructor(e,t){super(e,t),this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let r=this.size-this.cursor;for(;r;){let i=this.readString(4);this.compatibleBrands.push(i),r-=4}}};var sa=class extends H{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var te=class extends H{constructor(e,t){super(e,t);let r=this.readUint32();this.version=r>>>24,this.flags=r&16777215}};var na=class extends te{constructor(e,t){super(e,t),this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.timescale=this.readUint32(),this.duration=this.readUint32(),this.rate=this.readUint32(),this.volume=this.readUint16()}};var oa=class extends H{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ua=class extends H{constructor(e,t){super(e,t),this.data=this.content}};var hr=class extends te{get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e,t){super(e,t),this.segments=[],this.referenceId=this.readUint32(),this.timescale=this.readUint32(),this.earliestPresentationTime32=this.readUint32(),this.firstOffset32=this.readUint32(),this.earliestPresentationTime64=0,this.firstOffset64=0,this.referenceCount=this.readUint32()&65535;for(let r=0;r<this.referenceCount;r++){let i=this.readUint32(),s=i>>>31,n=i<<1>>>1,o=this.readUint32();i=this.readUint32();let u=i>>>28,l=i<<3>>>3;this.segments.push({referenceType:s,referencedSize:n,subsegmentDuration:o,SAPType:u,SAPDeltaTime:l})}}};var la=class extends H{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ca=class extends H{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var da=class extends te{constructor(e,t){switch(super(e,t),this.readUint8()){case 0:this.stereoMode=0;break;case 1:this.stereoMode=1;break;case 2:this.stereoMode=2;break;case 3:this.stereoMode=3;break;case 4:this.stereoMode=4;break}this.cursor+=1}};var pa=class extends te{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var ha=class extends te{constructor(e,t){super(e,t),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}};var ma=class extends H{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var fa=class extends te{constructor(e,t){super(e,t),this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.trackId=this.readUint32(),this.cursor+=4,this.duration=this.readUint32(),this.cursor+=8,this.layer=this.readUint16(),this.alternateGroup=this.readUint16(),this.cursor+=2,this.cursor+=2,this.matrix=[[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()]],this.width=this.readUint32(),this.height=this.readUint32()}};var ba=class extends H{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ga=class extends H{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var va=class extends te{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var Sa=class extends H{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ya=class extends te{constructor(e,t){super(e,t),this.trackId=this.readUint32(),this.flags&1&&(this.baseDataOffset=this.readUint64()),this.flags&2&&(this.sampleDescriptionIndex=this.readUint32()),this.flags&8&&(this.defaultSampleDuration=this.readUint32()),this.flags&16&&(this.defaultSampleSize=this.readUint32()),this.flags&32&&(this.defaultSampleFlags=this.readUint32())}};var Ta=class extends te{constructor(t,r){super(t,r);this.baseMediaDecodeTime32=0;this.baseMediaDecodeTime64=BigInt(0);this.version===1?this.baseMediaDecodeTime64=this.readUint64():this.baseMediaDecodeTime32=this.readUint32()}get baseMediaDecodeTime(){return this.version===1?this.baseMediaDecodeTime64:this.baseMediaDecodeTime32}};var Ia=class extends te{constructor(t,r){super(t,r);this.sampleDuration=[];this.sampleSize=[];this.sampleFlags=[];this.sampleCompositionTimeOffset=[];this.optionalFields=0;this.sampleCount=this.readUint32(),this.flags&1&&(this.dataOffset=this.readUint32()),this.flags&4&&(this.firstSampleFlags=this.readUint32());for(let i=0;i<this.sampleCount;i++)this.flags&256&&this.sampleDuration.push(this.readUint32()),this.flags&512&&this.sampleSize.push(this.readUint32()),this.flags&1024&&this.sampleFlags.push(this.readUint32()),this.flags&2048&&this.sampleCompositionTimeOffset.push(this.readUint32())}};var Ea=class extends H{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var xa=class extends te{constructor(e,t){super(e,t),this.entryCount=this.readUint32(),this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+8,this.content.byteLength-8))}};var Pa=class extends H{constructor(e,t){super(e,t),this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+78,this.content.byteLength-78))}};var oM={ftyp:aa,moov:sa,mvhd:na,moof:oa,mdat:ua,sidx:hr,trak:la,mdia:ma,mfhd:va,tkhd:fa,traf:Sa,tfhd:ya,tfdt:Ta,trun:Ia,minf:ba,sv3d:ca,st3d:da,prhd:pa,proj:ga,equi:ha,uuid:ia,stbl:Ea,stsd:xa,avc1:Pa,unknown:Zr},gt=class a{constructor(e={}){this.options=P({offset:0},e)}parse(e){let t=[],r=this.options.offset;for(;r<e.byteLength;)try{let s=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+r+4,4)),n=this.createBox(s,new DataView(e.buffer,e.byteOffset+r));if(!n.size)break;t.push(n),r+=n.size}catch(i){break}return t}createBox(e,t){let r=oM[e];return r?new r(t,new a):new Zr(t,new a)}};var Ut=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{var r,i,s;(s=(r=this.index)[i=t.type])!=null||(r[i]=[]),this.index[t.type].push(t),t.children.length>0&&this.indexBoxLevel(t.children)})}find(e){return this.index[e]&&this.index[e][0]?this.index[e][0]:null}findAll(e){return this.index[e]||[]}};var lM=new TextDecoder("ascii"),cM=a=>lM.decode(new DataView(a.buffer,a.byteOffset+4,4))==="ftyp",dM=a=>{let e=new hr(a,new gt),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})},pM=(a,e)=>{let r=new gt().parse(a),i=new Ut(r),s=i.findAll("moof"),n=e?i.findAll("uuid"):i.findAll("mdat");if(!(n.length&&s.length))return null;let o=s[0],u=n[n.length-1],l=o.source.byteOffset,d=u.source.byteOffset-o.source.byteOffset+u.size;return new DataView(a.buffer,l,d)},hM=a=>{let t=new gt().parse(a),r=new Ut(t),i={},s=r.findAll("uuid");return s.length?s[s.length-1]:i},mM=a=>{var i;let t=new gt().parse(a);return(i=new Ut(t).find("sidx"))==null?void 0:i.timescale},fM=(a,e)=>{let r=new gt().parse(a),s=new Ut(r).findAll("traf"),n=s[s.length-1].children.find(d=>d.type==="tfhd"),o=s[s.length-1].children.find(d=>d.type==="tfdt"),u=s[s.length-1].children.find(d=>d.type==="trun"),l=0;return u.sampleDuration.length?l=u.sampleDuration.reduce((d,p)=>d+p,0):l=n.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+l)/e*1e3},bM=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 gt().parse(a),i=new Ut(r);if(i.find("sv3d")){e.is3dVideo=!0;let n=i.find("st3d");n&&(e.stereoMode=n.stereoMode);let o=i.find("prhd");o&&(e.projectionData.pose.yaw=o.poseYawDegrees,e.projectionData.pose.pitch=o.posePitchDegrees,e.projectionData.pose.roll=o.poseRollDegrees);let u=i.find("equi");u&&(e.projectionData.bounds.top=u.projectionBoundsTop,e.projectionData.bounds.right=u.projectionBoundsRight,e.projectionData.bounds.bottom=u.projectionBoundsBottom,e.projectionData.bounds.left=u.projectionBoundsLeft)}return e},ES={validateData:cM,parseInit:bM,getIndexRange:()=>{},parseSegments:dM,parseFeedableSegmentChunk:pM,getChunkEndTime:fM,getServerLatencyTimestamps:hM,getTimescaleFromIndex:mM};var Aa=_(Fe(),1);import{assertNonNullable as $l,isNonNullable as AS,isNullable as vM}from"@vkontakte/videoplayer-shared/es2015";import{assertNever as gM}from"@vkontakte/videoplayer-shared/es2015";var xS={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"}},PS=a=>{let e=a.getUint8(0),t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);let r=wa(a,t),i=r in xS,s=i?xS[r].type:"binary",n=a.getUint8(t),o=0;n&128?o=1:n&64?o=2:n&32?o=3:n&16?o=4:n&8?o=5:n&4?o=6:n&2?o=7:n&1&&(o=8);let u=new DataView(a.buffer,a.byteOffset+t+1,o-1),l=n&255>>o,c=wa(u),d=l*it(2,(o-1)*8)+c,p=t+o,h;return p+d>a.byteLength?h=new DataView(a.buffer,a.byteOffset+p):h=new DataView(a.buffer,a.byteOffset+p,d),{tag:i?r:"0x"+r.toString(16).toUpperCase(),type:s,tagHeaderSize:p,tagSize:p+d,value:h,valueSize:d}},wa=(a,e=a.byteLength)=>{switch(e){case 1:return a.getUint8(0);case 2:return a.getUint16(0);case 3:return a.getUint8(0)*it(2,16)+a.getUint16(1);case 4:return a.getUint32(0);case 5:return a.getUint8(0)*it(2,32)+a.getUint32(1);case 6:return a.getUint16(0)*it(2,32)+a.getUint32(2);case 7:{let t=a.getUint8(0)*281474976710656+a.getUint16(1)*4294967296+a.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},Ze=(a,e)=>{switch(e){case"int":return a.getInt8(0);case"uint":return wa(a);case"float":return a.byteLength===4?a.getFloat32(0):a.getFloat64(0);case"string":return new TextDecoder("ascii").decode(a);case"utf8":return new TextDecoder("utf-8").decode(a);case"date":return new Date(Date.UTC(2001,0)+a.getInt8(0)).getTime();case"master":return a;case"binary":return a;default:gM(e)}},mr=(a,e)=>{let t=0;for(;t<a.byteLength;){let r=new DataView(a.buffer,a.byteOffset+t),i=PS(r);if(!e(i))return;i.type==="master"&&mr(i.value,e),t=i.value.byteOffset-a.byteOffset+i.valueSize}},wS=a=>{if(a.getUint32(0)!==440786851)return!1;let e,t,r,i=PS(a);return mr(i.value,({tag:s,type:n,value:o})=>(s===17143?e=Ze(o,n):s===17026?t=Ze(o,n):s===17029&&(r=Ze(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(r===void 0||r<=2)};var kS=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],SM=[231,22612,22743,167,171,163,160,175],yM=a=>{let e,t,r,i,s=!1,n=!1,o=!1,u,l,c=!1,d=0;return mr(a,({tag:p,type:h,value:m,valueSize:b})=>{if(p===21419){let g=Ze(m,h);l=wa(g)}else p!==21420&&(l=void 0);return p===408125543?(e=m.byteOffset,t=m.byteOffset+b):p===357149030?s=!0:p===290298740?n=!0:p===2807729?r=Ze(m,h):p===17545?i=Ze(m,h):p===21420&&l===475249515?u=Ze(m,h):p===374648427?mr(m,({tag:g,type:v,value:S})=>g===30321?(c=Ze(S,v)===1,!1):!0):s&&n&&(0,Aa.default)(kS,p)&&(o=!0),!o}),$l(e,"Failed to parse webm Segment start"),$l(t,"Failed to parse webm Segment end"),$l(i,"Failed to parse webm Segment duration"),r=r!=null?r:1e6,{segmentStart:Math.round(e/1e9*r*1e3),segmentEnd:Math.round(t/1e9*r*1e3),timeScale:r,segmentDuration:Math.round(i/1e9*r*1e3),cuesSeekPosition:u,is3dVideo:c,stereoMode:d,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},TM=a=>{if(vM(a.cuesSeekPosition))return;let e=a.segmentStart+a.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},IM=(a,e)=>{let t=!1,r=!1,i=o=>AS(o.time)&&AS(o.position),s=[],n;return mr(a,({tag:o,type:u,value:l})=>{switch(o){case 475249515:t=!0;break;case 187:n&&i(n)&&s.push(n),n={};break;case 179:n&&(n.time=Ze(l,u));break;case 183:break;case 241:n&&(n.position=Ze(l,u));break;default:t&&(0,Aa.default)(kS,o)&&(r=!0)}return!(t&&r)}),n&&i(n)&&s.push(n),s.map((o,u)=>{let{time:l,position:c}=o,d=s[u+1];return{status:"none",time:{from:l,to:d?d.time:e.segmentDuration},byte:{from:e.segmentStart+c,to:d?e.segmentStart+d.position-1:e.segmentEnd-1}}})},EM=a=>{let e=0,t=!1;try{mr(a,r=>r.tag===524531317?r.tagSize<=a.byteLength?(e=r.tagSize,!1):(e+=r.tagHeaderSize,!0):(0,Aa.default)(SM,r.tag)?(e+r.tagSize<=a.byteLength&&(e+=r.tagSize,t||(t=(0,Aa.default)([163,160,175],r.tag))),!0):!1)}catch(r){}return e>0&&e<=a.byteLength&&t?new DataView(a.buffer,a.byteOffset,e):null},RS={validateData:wS,parseInit:yM,getIndexRange:TM,parseSegments:IM,parseFeedableSegmentChunk:EM};var ka=a=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(a);if(e){let[,t,r]=e;if(t==="audio"||t==="video")switch(r){case"webm":return RS;case"mp4":return ES}}throw new ReferenceError(`Unsupported mime type ${a}`)};var Hl=_(zS(),1),Ty=_(Br(),1),Iy=_(dy(),1),Ey=_(Bt(),1),jl=_(zr(),1);var py=_(Fe(),1),Ol=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,py.default)(["6E","7A","F4"],o)}}return!1};import{isNonNullable as yC,isNullable as Sy}from"@vkontakte/videoplayer-shared/es2015";var hy=a=>{if(a.includes("/")){let e=a.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(a)};var my=a=>{var e;try{let t=vC(),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 vC(){let a="(?<extlang>(?:[a-z]{3}(?:-[a-z]{3}){0,2}))",e="x(?:-[a-z0-9]{1,8})+",c=`^(?:(?<langtag>${`
|
|
62
|
+
[selected audio track] ${S==null?void 0:S.id}
|
|
63
|
+
`}),S};var de=a=>new URL(a).hostname;import{assertNever as Ev,assertNonNullable as xv,combine as cL,debounce as dL,ErrorCategory as Pv,filter as wv,filterChanged as pL,isNonNullable as Tl,map as fn,merge as Av,observableFrom as hL,once as mL,Subscription as fL,ValueSubject as Il,videoQualityToHeight as kv,videoSizeToQuality as bL}from"@vkontakte/videoplayer-shared/es2015";var Sv=B(Bt(),1);var mv=B(Fe(),1);var hv=a=>{if(a instanceof DOMException&&(0,mv.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"))},Le=(a,e)=>E(void 0,null,function*(){let t=a.muted;try{yield a.play()}catch(r){if(!hv(r))return!1;if(e&&e(),t)return console.warn(r),!1;a.muted=!0;try{yield a.play()}catch(i){return hv(i)&&(a.muted=!1,console.warn(i)),!1}}return!0});import{isNonNullable as pn,isNullable as GR,assertNonNullable as Ki}from"@vkontakte/videoplayer-shared/es2015";var bv=B(zr(),1);import{isNonNullable as fv,assertNonNullable as dn,now as jR}from"@vkontakte/videoplayer-shared/es2015";function pe(){return jR()}function gl(a){return pe()-a}function vl(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 gv(a,e,t){let r=(...i)=>{t.apply(null,i),a.removeEventListener(e,r)};a.addEventListener(e,r)}function Xr(a,e,t,r){let i=window.XMLHttpRequest,s,n,o,u=!1,l=0,c,d,p=!1,h="arraybuffer",m=7e3,b=2e3,g=()=>{if(u)return;dn(c);let R=gl(c),z;if(R<b){z=b-R,setTimeout(g,z);return}b*=2,b>m&&(b=m),n&&n.abort(),n=new i,$()},v=R=>(s=R,G),S=R=>(d=R,G),T=()=>(h="json",G),I=()=>{if(!u){if(--l>=0){g(),r&&r();return}u=!0,d&&d(),t&&t()}},y=R=>(p=R,G),$=()=>{c=pe(),n=new i,n.open("get",a);let R=0,z,q=0,Z=()=>(dn(c),Math.max(c,Math.max(z||0,q||0)));if(s&&n.addEventListener("progress",k=>{let D=pe();s.updateChunk&&k.loaded>R&&(s.updateChunk(Z(),k.loaded-R),R=k.loaded,z=D)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>I())),n.addEventListener("load",()=>{if(u)return;dn(n);let k=n.status;if(k>=200&&k<300){let{response:D,responseType:x}=n,U=D==null?void 0:D.byteLength;if(typeof U=="number"&&s){let _=U-R;_&&s.updateChunk&&s.updateChunk(Z(),_)}x==="json"&&(!D||!(0,bv.default)(D).length)?I():(d&&d(),e(D))}else I()}),n.addEventListener("error",()=>{I()}),p){let k=()=>{dn(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(q=pe(),n.removeEventListener("readystatechange",k))};n.addEventListener("readystatechange",k)}return n.responseType=h,n.send(),G},G={withBitrateReporting:v,withParallel:y,withJSONResponse:T,withRetryCount:R=>(l=R,G),withRetryInterval:(R,z)=>(fv(R)&&(b=R),fv(z)&&(m=z),G),withTimeout:R=>(o=R,G),withFinally:S,send:$,abort:()=>{n&&(n.abort(),n=void 0),u=!0,d&&d()}};return G}var Yi=class{constructor(e){this.intervals=[];this.currentRate=0;this.logger=e}_updateRate(e){let t=.2;this.currentRate&&(e<this.currentRate*.1?t=.8:e<this.currentRate*.5?t=.5:e<this.currentRate*.7&&(t=.3)),e=Math.max(1,Math.min(e,100*1024*1024)),this.currentRate=this.currentRate?this.currentRate*(1-t)+e*t:e}_createInterval(e,t,r){return{start:e,end:t,bytes:r}}_doMergeIntervals(e,t){e.start=Math.min(t.start,e.start),e.end=Math.max(t.end,e.end),e.bytes+=t.bytes}_mergeIntervals(e,t){return e.start<=t.end&&t.start<=e.end?(this._doMergeIntervals(e,t),!0):!1}_flushIntervals(){if(!this.intervals.length)return!1;let e=this.intervals[0].start,t=this.intervals[this.intervals.length-1].end-500;if(t-e>2e3){let r=0,i=0;for(;this.intervals.length>0;){let s=this.intervals[0];if(s.end<=t)r+=s.end-s.start,i+=s.bytes,this.intervals.splice(0,1);else{if(s.start>=t)break;{let n=t-s.start,o=s.end-s.start;r+=n;let u=s.bytes*n/o;i+=u,s.start=t,s.bytes-=u}}}if(i>0&&r>0){let s=i*8/(r/1e3);return this._updateRate(s),this.logger(`rate updated, new=${Math.round(s/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(i)}/${Math.round(r)} interval=${Math.round(t-e)}`),!0}}return!1}_joinIntervals(){let e;do{e=!1;for(let t=0;t<this.intervals.length-1;++t)this._mergeIntervals(this.intervals[t],this.intervals[t+1])&&(this.intervals.splice(t+1,1),e=!0)}while(e)}addInterval(e,t,r){return this.intervals.push(this._createInterval(e,t,r)),this._joinIntervals(),this.intervals.length>100&&(this.logger(`too many intervals (${this.intervals.length}); will merge`,{type:"warn"}),this._doMergeIntervals(this.intervals[1],this.intervals[0]),this.intervals.splice(0,1)),this._flushIntervals()}getBitRate(){return this.currentRate}};var vv=B(zr(),1);var zi=class{constructor(e,t,r,i,s){this.pendingQueue=[];this.activeRequests={};this.completeRequests={};this.averageSegmentDuration=2e3;this.lastPrefetchStart=0;this.throttleTimeout=null;this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=r,this.MAX_PARALLEL_REQUESTS=i,this.logger=s}limitCompleteCount(){let e;for(;(e=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){let t=e[Math.floor(Math.random()*e.length)];this.logger(`Dropping completed request for url ${t}`,{type:"warn"}),delete this.completeRequests[t]}}_sendRequest(e,t){let r=pe(),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=pe()-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=Xr(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=pe()}_getParallelRequestCount(){return Math.min(this.MAX_PARALLEL_REQUESTS,this.averageSegmentDuration<3e3?3:2)}_getPrefetchDelay(){return Math.max(100,Math.min(5e3,this.averageSegmentDuration/3))}_canSendPending(){let e=this._getParallelRequestCount(),t=pe();if(Object.keys(this.activeRequests).length>=e)return!1;let 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,vv.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 WR}from"@vkontakte/videoplayer-shared/es2015";var hn=1e4,Sl=3;var YR=6e4,zR=10,KR=1,XR=500,Xi=class{constructor(e){this.paused=!1;this.autoQuality=!0;this.autoQualityLimits=void 0;this.buffering=!0;this.destroyed=!1;this.videoPlayStarted=!1;this.lowLatency=!1;this.bitrate=0;this.manifest=[];this.sourceBuffer=0;this.bufferStates=[];this.sourceJitter=-1;this.params=e,this.soundProhibitedEvent$=new WR,this.chunkRateEstimator=new Yi(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=vl(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setAutoQualityLimits(e){this.autoQualityLimits=e}switchByName(e){let t;for(let r=0;r<this.manifest.length;++r)if(t=this.manifest[r],t.name===e){this._switchToQuality(t);return}}catchUp(){this.rep&&this.rep.stop(),this.currentManifestEntry&&(this.paused=!1,this._initPlayerWith(this.currentManifestEntry),this._notifyBuffering(!0))}stop(){this.params.videoElement.pause(),this.rep&&(this.rep.stop(),this.rep=null)}pause(){this.paused=!0,this.params.videoElement.pause(),this.videoPlayStarted=!1,this._notifyBuffering(!1)}play(){this.paused=!1;let e=this.lowLatency&&this._getBufferSizeSec()>this.sourceJitter+5;this.rep&&!e?(this.bufferStates=[],this.videoPlayStarted=!1,this.shouldPlay()?this._playVideoElement():this._notifyBuffering(!0)):this.catchUp()}startPlay(e,t){this.autoQuality=t,this._initPlayerWith(e)}destroy(){this.destroyed=!0,this.rep&&(this.rep.stop(),this.rep=null),this.manifestRequest&&this.manifestRequest.abort(),this.manifestRefetchTimer&&(clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=void 0)}reinit(e){this.manifestUrl=e,this.urlResolver=vl(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*(H.display.pixelRatio||1)*t.offsetHeight||520;for(let o=0;o<this.manifest.length;++o){s=this.manifest[o];let{max:u,min:l}=this.autoQualityLimits||{};!tv({limits:this.autoQualityLimits,highestAvailableHeight:this.manifest[0].video.height,lowestAvailableHeight:(0,Sv.default)(this.manifest,-1).video.height})&&(u&&s.video.height>u||l&&s.video.height<l)||(s.bitrate<e&&n>Math.min(s.video.height,s.video.width)?(!i||s.bitrate>i.bitrate)&&(i=s):(!r||r.bitrate>s.bitrate)&&(r=s))}return i||r}shouldPlay(){if(this.paused)return!1;let t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||pn(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=()=>{gv(i,"progress",()=>{i.buffered.length?(i.currentTime=i.buffered.start(0),s({name:"playing"})):n()})};n()}_initPlayerWith(e){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new zi(Sl,hn,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){let{logger:t,videoElement:r,playerCallback:i}=this.params,s=!1,n=null,o=null,u=null,l=null,c=!1,d=()=>{let I=s&&(!c||c===this.rep);return I||t("Not running!"),I},p=(I,y,$)=>{u&&u.abort(),u=Xr(this.urlResolver.resolve(I,!1),y,$,()=>this._retryCallback()).withTimeout(hn).withBitrateReporting(this.bitrateSwitcher).withRetryCount(Sl).withFinally(()=>{u=null}).send()},h=(I,y,$)=>{Ki(this.filesFetcher),o==null||o.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(I,!1),y,$,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},m=I=>{let y=r.playbackRate;r.playbackRate!==I&&(t(`Playback rate switch: ${y}=>${I}`),r.playbackRate=I)},b=I=>{this.lowLatency=I,t(`lowLatency changed to ${I}`),g()},g=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)m(1);else{let I=this._getBufferSizeSec();if(this.bufferStates.length<5){m(1);return}let $=pe()-1e4,C=0;for(let O=0;O<this.bufferStates.length;O++){let Q=this.bufferStates[O];I=Math.min(I,Q.buf),Q.ts<$&&C++}this.bufferStates.splice(0,C),t(`update playback rate; minBuffer=${I} drop=${C} jitter=${this.sourceJitter}`);let L=I-KR;this.sourceJitter>=0?L-=this.sourceJitter/2:this.sourceJitter-=1,L>3?m(1.15):L>1?m(1.1):L>.3?m(1.05):m(1)}},v=I=>{let y,$=()=>y&&y.start?y.start.length:0,C=k=>y.start[k]/1e3,L=k=>y.dur[k]/1e3,O=k=>y.fragIndex+k,Q=(k,D)=>({chunkIdx:O(k),startTS:C(k),dur:L(k),discontinuity:D}),G=()=>{let k=0;if(y&&y.dur){let D=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,x=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,U=D;this.sourceJitter>1&&(U+=this.sourceJitter-1);let _=y.dur.length-1;for(;_>=0&&(U-=y.dur[_],!(U<=0));--_);k=Math.min(_,y.dur.length-1-x),k=Math.max(k,0)}return Q(k,!0)},R=k=>{let D=$();if(!(D<=0)){if(pn(k)){for(let x=0;x<D;x++)if(C(x)>k)return Q(x)}return G()}},z=k=>{let D=$(),x=k?k.chunkIdx+1:0,U=x-y.fragIndex;if(!(D<=0)){if(!k||U<0||U-D>zR)return t(`Resync: offset=${U} bChunks=${D} chunk=`+JSON.stringify(k)),G();if(!(U>=D))return Q(x-y.fragIndex,!1)}},q=(k,D,x)=>{l&&l.abort(),l=Xr(this.urlResolver.resolve(k,!0,this.lowLatency),D,x,()=>this._retryCallback()).withTimeout(hn).withRetryCount(Sl).withFinally(()=>{l=null}).withJSONResponse().send()};return{seek:(k,D)=>{q(I,x=>{if(!d())return;y=x;let U=!!y.lowLatency;U!==this.lowLatency&&b(U);let _=0;for(let je=0;je<y.dur.length;++je)_+=y.dur[je];_>0&&(Ki(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(_/y.dur.length)),i({name:"index",zeroTime:y.zeroTime,shiftDuration:y.shiftDuration}),this.sourceJitter=y.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,y.jitter/1e3)):1,k(R(D))},()=>this._handleNetworkError())},nextChunk:z}},S=()=>{s=!1,o&&o.abort(),u&&u.abort(),l&&l.abort(),Ki(this.filesFetcher),this.filesFetcher.abortAll()};return c={start:I=>{let{videoElement:y,logger:$}=this.params,C=v(e.jidxUrl),L,O,Q,G,R=0,z,q,Z,k=()=>{z&&(clearTimeout(z),z=void 0);let K=Math.max(XR,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),Se=R+K,ye=pe(),Pe=Math.min(1e4,Se-ye);R=ye;let Qe=()=>{l||d()&&C.seek(()=>{d()&&(R=pe(),D(),k())})};Pe>0?z=window.setTimeout(()=>{this.paused?k():Qe()},Pe):Qe()},D=()=>{let K;for(;K=C.nextChunk(G);)G=K,Et(K);let Se=C.nextChunk(Q);if(Se){if(Q&&Se.discontinuity){$("Detected discontinuity; restarting playback"),this.paused?k():(S(),this._initPlayerWith(e));return}je(Se)}else k()},x=(K,Se)=>{if(!d()||!this.sourceBuffer)return;let ye,Pe,Qe,Tr=xt=>{window.setTimeout(()=>{d()&&x(K,Se)},xt)};if(this.sourceBuffer.updating)$("Source buffer is updating; delaying appendBuffer"),Tr(100);else{let xt=pe(),Yt=y.currentTime;!this.paused&&y.buffered.length>1&&q===Yt&&xt-Z>500&&($("Stall suspected; trying to fix"),this._fixupStall()),q!==Yt&&(q=Yt,Z=xt);let Ir=this._getBufferSizeSec();if(Ir>30)$(`Buffered ${Ir} seconds; delaying appendBuffer`),Tr(2e3);else try{this.sourceBuffer.appendBuffer(K),this.videoPlayStarted?(this.bufferStates.push({ts:xt,buf:Ir}),g(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),Se&&Se()}catch(ci){if(ci.name==="QuotaExceededError")$("QuotaExceededError; delaying appendBuffer"),Qe=this.sourceBuffer.buffered.length,Qe!==0&&(ye=this.sourceBuffer.buffered.start(0),Pe=Yt,Pe-ye>4&&this.sourceBuffer.remove(ye,Pe-3)),Tr(1e3);else throw ci}}},U=()=>{O&&L&&($([`Appending chunk, sz=${O.byteLength}:`,JSON.stringify(Q)]),x(O,function(){O=null,D()}))},_=K=>e.fragUrlTemplate.replace("%%id%%",K.chunkIdx),je=K=>{d()&&h(_(K),(Se,ye)=>{if(d()){if(ye/=1e3,O=Se,Q=K,n=K.startTS,ye){let Pe=Math.min(10,K.dur/ye);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*Pe:Pe}U()}},()=>this._handleNetworkError())},Et=K=>{d()&&(Ki(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(_(K),!1)))},yr=K=>{d()&&(e.cachedHeader=K,x(K,()=>{L=!0,U()}))};s=!0,C.seek(K=>{if(d()){if(R=pe(),!K){k();return}G=K,!GR(I)||K.startTS>I?je(K):(Q=K,D())}},I),e.cachedHeader?yr(e.cachedHeader):p(e.headerUrl,yr,()=>this._handleNetworkError())},stop:S,getTimestampSec:()=>n},c}_switchToQuality(e){let{logger:t,playerCallback:r}=this.params,i;e.bitrate!==this.bitrate&&(this.rep&&(i=this.rep.getTimestampSec(),pn(i)&&(i+=.1),this.rep.stop()),this.currentManifestEntry=e,this.rep=this._representation(e),t(`switch to quality: codecs=${e.codecs}; headerUrl=${e.headerUrl}; bitrate=${e.bitrate}`),this.bitrate=e.bitrate,Ki(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(i),r({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return pn(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,r=d=>{if(!this.autoQuality)return;let p,h,m;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&d<this.bitrate&&(h=this._getBufferSizeSec(),m=d/this.bitrate,h>10&&m>.8||h>15&&m>.5||h>20&&m>.3)){e(`Not switching: buffer=${Math.floor(h)}; bitrate=${this.bitrate}; newRate=${Math.floor(d)}`);return}p=this._selectQuality(d),p?this._switchToQuality(p):e(`Could not find quality by bitrate ${d}`)},s={updateChunk:(p,h)=>{let m=pe();if(this.chunkRateEstimator.addInterval(p,m,h)){let g=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:h,duration:m-p,speed:g}),!0}},get:()=>{let p=this.chunkRateEstimator.getBitRate();return p?p*.85:0}},n=-1/0,o,u=!0,l=()=>{let d=s.get();if(d&&o&&this.autoQuality){if(u&&d>o&&gl(n)<3e4)return;r(d)}u=this.autoQuality};return{updateChunk:(d,p)=>{let h=s.updateChunk(d,p);return h&&l(),h},notifySwitch:d=>{let p=pe();d<o&&(n=p),o=d}}}_fetchManifest(e,t,r){this.manifestRequest=Xr(this.urlResolver.resolve(e,!0),t,r,()=>this._retryCallback()).withJSONResponse().withTimeout(hn).withRetryCount(this.params.config.manifestRetryMaxCount).withRetryInterval(this.params.config.manifestRetryInterval,this.params.config.manifestRetryMaxInterval).send().withFinally(()=>{this.manifestRequest=void 0})}_playVideoElement(){let{videoElement:e}=this.params;Le(e,()=>{this.soundProhibitedEvent$.next()}).then(t=>{t||(this.params.liveOffset.pause(),this.params.videoState.setState("paused"))})}_handleManifestUpdate(e){let{logger:t,playerCallback:r,videoElement:i}=this.params,s=n=>{let o=[];return n!=null&&n.length?(n.forEach((u,l)=>{var c,d;u.video&&i.canPlayType(u.codecs).replace(/no/,"")&&((d=(c=window.MediaSource)==null?void 0:c.isTypeSupported)!=null&&d.call(c,u.codecs))&&(u.index=l,o.push(u))}),o.sort(function(u,l){return u.video&&l.video?l.video.height-u.video.height:l.bitrate-u.bitrate}),o):(r({name:"error",type:"empty_manifest"}),[])};this.manifest=s(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),r({name:"manifest",manifest:this.manifest})}_refetchManifest(e){this.destroyed||(this.manifestRefetchTimer&&clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=window.setTimeout(()=>{this._fetchManifest(e,t=>{this.destroyed||(this._handleManifestUpdate(t),this._refetchManifest(e))},()=>this._refetchManifest(e))},YR))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};var Iv=B(Br(),1);import{debounce as JR,filter as yv,fromEvent as ZR,interval as eL,isHigher as tL,isInvariantQuality as rL,isLower as iL,merge as aL,Subject as Tv,Subscription as sL}from"@vkontakte/videoplayer-shared/es2015";var yl=class{constructor(){this.onDroopedVideoFramesLimit$=new Tv;this.subscription=new sL;this.playing=!1;this.tracks=[];this.forceChecker$=new Tv;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&&!rL(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&&tL(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(ZR(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=eL(this.droppedFramesChecker.checkTime).pipe(yv(()=>this.playing),yv(()=>{let i=!!this.isForceCheckCounter;return i&&(this.isForceCheckCounter-=1),!i})),t=this.forceChecker$.pipe(JR(this.droppedFramesChecker.checkTime)),r=aL(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,Iv.default)(this.limitCounts).filter(([,s])=>s>=this.droppedFramesChecker.countLimit).sort(([s],[n])=>iL(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}},mn=yl;import{map as nL,Observable as oL}from"@vkontakte/videoplayer-shared/es2015";import{fromEvent as uL}from"@vkontakte/videoplayer-shared/es2015";var Ji=()=>{var a;return!!((a=window.documentPictureInPicture)!=null&&a.window)||!!document.pictureInPictureElement};var lL=(a,e)=>new oL(t=>{if(!window.IntersectionObserver)return;let r={root:null},i=new IntersectionObserver((n,o)=>{n.forEach(u=>t.next(u.isIntersecting||Ji()))},P(P({},r),e));i.observe(a);let s=uL(document,"visibilitychange").pipe(nL(n=>!document.hidden||Ji())).subscribe(n=>t.next(n));return()=>{i.unobserve(a),s.unsubscribe}}),He=lL;var gL=["paused","playing","ready"],vL=["paused","playing","ready"],Zi=class{constructor(e){this.subscription=new fL;this.videoState=new N("stopped");this.representations$=new Il([]);this.droppedFramesManager=new mn;this.maxSeekBackTime$=new Il(1/0);this.zeroTime$=new Il(void 0);this.liveOffset=new pr;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:Pv.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{let n=e.manifest,o=[];for(let u of n){let l=(t=u.name)!=null?t:u.index.toString(10),c=(r=_t(u.name))!=null?r:bL(u.video),d=u.bitrate/1e3,p=P({},u.video);if(!c)continue;let h={id:l,quality:c,bitrate:d,size:p};o.push({track:h,representation:u})}this.representations$.next(o),this.params.output.availableVideoTracks$.next(o.map(({track:u})=>u)),((i=this.videoState.getTransition())==null?void 0:i.to)==="manifest_ready"&&this.videoState.setState("manifest_ready");break}case"qualitySwitch":{let n=e.quality,o=(s=this.representations$.getValue().find(({representation:u})=>u===n))==null?void 0:s.track;this.params.output.hostname$.next(new URL(n.headerUrl,this.params.source.url).hostname),Tl(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,El.default)(vL,e)&&(n||o)){this.prepare();return}if((i==null?void 0:i.to)!=="paused"&&s.state==="requested"&&(0,El.default)(gL,e)){this.seek(s.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(be(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(be(this.params.source.url,u))}return;default:return Ev(e)}};this.textTracksManager=new Ue(e.source.url),this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=i=>{e.output.error$.next({id:"DashLiveProvider",category:Pv.WTF,message:"DashLiveProvider internal logic error",thrown:i})};Av(this.videoState.stateChangeStarted$.pipe(fn(i=>({transition:i,type:"start"}))),this.videoState.stateChangeEnded$.pipe(fn(i=>({transition:i,type:"end"})))).subscribe(({transition:i,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(i)}`})}),this.video=we(e.container,e.tuning),this.params.output.element$.next(this.video),this.dash=this.createLiveDashPlayer(),this.subscription.add(this.dash.soundProhibitedEvent$.subscribe(this.params.output.soundProhibitedEvent$)),this.params.output.duration$.next(1/0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(de(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);let r=Re(this.video);this.subscription.add(this.representations$.pipe(fn(i=>i.map(({track:s})=>s)),wv(i=>!!i.length),mL()).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(pL(),fn(i=>-i/1e3)).subscribe(this.params.output.duration$)).add(cL({zeroTime:this.zeroTime$.pipe(wv(Tl)),position:r.timeUpdate$}).subscribe(({zeroTime:i,position:s})=>this.params.output.liveTime$.next(i+s*1e3),t)).add(ot(this.video,this.params.desiredState.isLooped,t)).add(ke(this.video,this.params.desiredState.volume,r.volumeState$,t)).add(r.volumeState$.subscribe(this.params.output.volume$,t)).add(qe(this.video,this.params.desiredState.playbackRate,r.playbackRateState$,t)).add(r.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(r.loadedMetadata$.subscribe(this.params.output.loadedMetadataEvent$)).add(r.playing$.subscribe(this.params.output.firstFrameEvent$)).add(r.canplay$.subscribe(this.params.output.canplay$)).add(r.inPiP$.subscribe(this.params.output.inPiP$)).add(r.inFullscreen$.subscribe(this.params.output.inFullscreen$)).add(He(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:i,min:s}})=>{this.dash.setAutoQualityLimits({max:i&&kv(i),min:s&&kv(s)}),this.params.output.autoVideoTrackLimits$.next({max:i,min:s})})).add(this.videoState.stateChangeEnded$.subscribe(i=>{var s;switch(i.to){case"stopped":this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState("stopped");break;case"manifest_ready":case"ready":((s=this.params.desiredState.playbackState.getTransition())==null?void 0:s.to)==="ready"&&this.params.desiredState.playbackState.setState("ready");break;case"paused":this.params.desiredState.playbackState.setState("paused");break;case"playing":this.params.desiredState.playbackState.setState("playing");break;default:return Ev(i.to)}},t)).add(Av(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,hL(["init"])).pipe(dL(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),Ae(this.video)}createLiveDashPlayer(){let e=new Xi({videoElement:this.video,videoState:this.videoState,liveOffset:this.liveOffset,config:{maxParallelRequests:this.params.config.maxParallelRequests,minBuffer:this.params.tuning.live.minBuffer,minBufferSegments:this.params.tuning.live.minBufferSegments,lowLatencyMinBuffer:this.params.tuning.live.lowLatencyMinBuffer,lowLatencyMinBufferSegments:this.params.tuning.live.lowLatencyMinBufferSegments,isLiveCatchUpMode:this.params.tuning.live.isLiveCatchUpMode,manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},playerCallback:this._dashCb,logger:t=>{this.params.dependencies.logger.log({message:String(t),component:"LiveDashPlayer"})}});return e.pause(),e}prepare(){var l,c,d,p,h,m;let e=this.representations$.getValue(),t=(c=(l=this.params.desiredState.videoTrack.getTransition())==null?void 0:l.to)!=null?c:this.params.desiredState.videoTrack.getState(),r=(p=(d=this.params.desiredState.autoVideoTrackSwitching.getTransition())==null?void 0:d.to)!=null?p:this.params.desiredState.autoVideoTrackSwitching.getState(),i=!r&&Tl(t)?t:Ft(e.map(({track:b})=>b),{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),s=i==null?void 0:i.id,n=this.params.desiredState.videoTrack.getTransition(),o=(h=this.params.desiredState.videoTrack.getState())==null?void 0:h.id,u=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(i&&(n||s!==o)&&this.setVideoTrack(i),u&&this.setAutoQuality(r),n||u||s!==o){let b=(m=e.find(({track:g})=>g.id===s))==null?void 0:m.representation;xv(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;xv(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(be(this.params.source.url,n)),i&&this.dash.pause(),this.liveOffset.resetTo(n,i)}};var $v=Zi;var Jy=B(Fe(),1);var Jr=(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 ZD,assertNonNullable as eC,debounce as tC,ErrorCategory as Yy,filter as zy,filterChanged as qa,fromEvent as rC,isNonNullable as Ky,map as cc,merge as On,observableFrom as dc,once as Xy,Subscription as iC}from"@vkontakte/videoplayer-shared/es2015";var bn=class{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,r){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:r})}removeEventListener(e,t){if(!(e in this.listeners))return;let r=this.listeners[e];for(let i=0,s=r.length;i<s;i++)if(r[i].callback===t){r.splice(i,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;let r=this.listeners[e.type].slice();for(let i=0,s=r.length;i<s;i++){let n=r[i];try{n.callback.call(this,e)}catch(o){Promise.resolve().then(()=>{throw o})}n.options&&n.options.once&&this.removeEventListener(e.type,n.callback)}return!e.defaultPrevented}},Zr=class extends bn{constructor(){super(),this.listeners||bn.call(this),Object.defineProperty(this,"aborted",{value:!1,writable:!0,configurable:!0}),Object.defineProperty(this,"onabort",{value:null,writable:!0,configurable:!0}),Object.defineProperty(this,"reason",{value:void 0,writable:!0,configurable:!0})}toString(){return"[object AbortSignal]"}dispatchEvent(e){e.type==="abort"&&(this.aborted=!0,typeof this.onabort=="function"&&this.onabort.call(this,e)),super.dispatchEvent(e)}},ea=class{constructor(){Object.defineProperty(this,"signal",{value:new Zr,writable:!0,configurable:!0})}abort(e){let t;try{t=new Event("abort")}catch(i){typeof document!="undefined"?document.createEvent?(t=document.createEvent("Event"),t.initEvent("abort",!1,!1)):(t=document.createEventObject(),t.type="abort"):t={type:"abort",bubbles:!1,cancelable:!1}}let r=e;if(r===void 0)if(typeof document=="undefined")r=new Error("This operation was aborted"),r.name="AbortError";else try{r=new DOMException("signal is aborted without reason")}catch(i){r=new Error("This operation was aborted"),r.name="AbortError"}this.signal.reason=r,this.signal.dispatchEvent(t)}toString(){return"[object AbortController]"}};typeof Symbol!="undefined"&&Symbol.toStringTag&&(ea.prototype[Symbol.toStringTag]="AbortController",Zr.prototype[Symbol.toStringTag]="AbortSignal");function gn(a){return a.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof a.Request=="function"&&!a.Request.prototype.hasOwnProperty("signal")||!a.AbortController}function xl(a){typeof a=="function"&&(a={fetch:a});let{fetch:e,Request:t=e.Request,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:i=!1}=a;if(!gn({fetch:e,Request:t,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:i}))return{fetch:e,Request:s};let s=t;(s&&!s.prototype.hasOwnProperty("signal")||i)&&(s=function(l,c){let d;c&&c.signal&&(d=c.signal,delete c.signal);let p=new t(l,c);return d&&Object.defineProperty(p,"signal",{writable:!1,enumerable:!1,configurable:!0,value:d}),p},s.prototype=t.prototype);let n=e;return{fetch:(u,l)=>{let c=s&&s.prototype.isPrototypeOf(u)?u.signal:l?l.signal:void 0;if(c){let d;try{d=new DOMException("Aborted","AbortError")}catch(h){d=new Error("Aborted"),d.name="AbortError"}if(c.aborted)return Promise.reject(d);let p=new Promise((h,m)=>{c.addEventListener("abort",()=>m(d),{once:!0})});return l&&l.signal&&delete l.signal,Promise.race([p,n(u,l)])}return n(u,l)},Request:s}}var ta=gn({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),Rv=ta?xl({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,lt=ta?Rv.fetch:window.fetch,Pq=ta?Rv.Request:window.Request,ge=ta?ea:window.AbortController,wq=ta?Zr:window.AbortSignal;var nc=B(wl(),1);var bS=B(fS(),1);import{ErrorCategory as ia}from"@vkontakte/videoplayer-shared/es2015";var gS=a=>{if(!a)return{id:"EmptyResponse",category:ia.PARSER,message:"Empty response"};if(a.length<=2&&a.match(/^\d+$/))return{id:`UVError#${a}`,category:ia.NETWORK,message:`UV Error ${a}`};let e=(0,bS.default)(a).substring(0,100).toLowerCase();if(e.startsWith("<!doctype")||e.startsWith("<html>")||e.startsWith("<body>")||e.startsWith("<head>"))return{id:"UnexpectedHTML",category:ia.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:ia.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:ia.PARSER,message:"Response is valid XML, but parser failed"}};var qt=(a,e,t=0)=>{for(let r=0;r<a.length;r++)if(a.start(r)*1e3-t<=e&&a.end(r)*1e3+t>e)return!0;return!1};import{abortable as ic,assertNonNullable as si,combine as ni,ErrorCategory as ct,filter as $n,filterChanged as Ba,flattenObject as Na,fromEvent as yt,getTraceSubscriptionMethod as VD,interval as ac,isNonNullable as Fa,isNullable as qy,map as oi,merge as vr,now as sc,Subject as Rn,Subscription as Uy,tap as OD,throttle as _D,ValueSubject as ie}from"@vkontakte/videoplayer-shared/es2015";var Sn=B(Fe(),1),ii=B(Bt(),1),yn=B(wl(),1);var iM=(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)},aM=a=>window.clearTimeout(a),vS=a=>typeof a=="function"&&(a==null?void 0:a.toString().endsWith("{ [native code] }")),SS=!vS(window.requestIdleCallback)||!vS(window.cancelIdleCallback),Ll=SS?iM:window.requestIdleCallback,aa=SS?aM:window.cancelIdleCallback;var ky=B(Ks(),1);import{assertNever as sM,ErrorCategory as yS,Subject as TS}from"@vkontakte/videoplayer-shared/es2015";var nM=18,IS=!1;try{IS=H.browser.isSafari&&!!H.browser.safariVersion&&H.browser.safariVersion<=nM}catch(a){console.error(a)}var Ml=class{constructor(e){this.bufferFull$=new TS;this.error$=new TS;this.queue=[];this.currentTask=null;this.destroyed=!1;this.abortRequested=!1;this.completeTask=()=>{var e;try{if(this.currentTask){let t=(e=this.currentTask.signal)==null?void 0:e.aborted;this.currentTask.callback(!t),this.currentTask=null}this.queue.length&&this.pull()}catch(t){this.error$.next({id:"BufferTaskQueueUnknown",category:yS.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:t})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}append(e,t){return E(this,null,function*(){return t&&t.aborted?!1:new Promise(r=>{let i={operation:"append",data:e,signal:t,callback:r};this.queue.push(i),this.pull()})})}remove(e,t,r){return E(this,null,function*(){return r&&r.aborted?!1:new Promise(i=>{let s={operation:"remove",from:e,to:t,signal:r,callback:i};this.queue.unshift(s),this.pull()})})}abort(e){return E(this,null,function*(){return new Promise(t=>{let r,i=s=>{this.abortRequested=!1,t(s)};IS&&e?r={operation:"safariAbort",init:e,callback:i}:r={operation:"abort",callback:i};for(let{callback:s}of this.queue)s(!1);this.abortRequested=!0,r&&(this.queue=[r]),this.pull()})})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){var i;if((this.buffer.updating||this.currentTask||this.destroyed)&&!this.abortRequested)return;let e=this.queue.shift();if(!e)return;if((i=e.signal)!=null&&i.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(s){s instanceof DOMException&&s.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):s instanceof DOMException&&s.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:yS.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:sM(t)}}},ES=Ml;var Dl=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 Ht,assertNonNullable as Me,ErrorCategory as St,fromEvent as Kl,getExponentialDelay as Xl,isNonNullable as ri,isNullable as ve,now as vn,once as ID,Subject as ED,Subscription as xD,ValueSubject as fr}from"@vkontakte/videoplayer-shared/es2015";var W=class{constructor(e,t){this.cursor=0;this.source=e,this.boxParser=t,this.children=[];let r=this.readUint32();this.type=this.readString(4),this.size32=r<=e.buffer.byteLength-e.byteOffset?r:NaN;let i=this.size32?this.size32-8:void 0,s=e.byteOffset+this.cursor;this.size64=0,this.usertype=0,this.content=new DataView(e.buffer,s,i)}get id(){return this.type}get size(){return this.size32}scanForBoxes(e){return this.boxParser.parse(e)}readString(e,t="ascii"){let i=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,i}readUint8(){let e=this.source.getUint8(this.cursor);return this.cursor+=1,e}readUint16(){let e=this.source.getUint16(this.cursor);return this.cursor+=2,e}readUint32(){let e=this.source.getUint32(this.cursor);return this.cursor+=4,e}readUint64(){let e=this.source.getBigInt64(this.cursor);return this.cursor+=8,e}};var ei=class extends W{};var sa=class extends W{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 na=class extends W{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 oa=class extends W{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var re=class extends W{constructor(e,t){super(e,t);let r=this.readUint32();this.version=r>>>24,this.flags=r&16777215}};var ua=class extends re{constructor(e,t){super(e,t),this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.timescale=this.readUint32(),this.duration=this.readUint32(),this.rate=this.readUint32(),this.volume=this.readUint16()}};var la=class extends W{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ca=class extends W{constructor(e,t){super(e,t),this.data=this.content}};var hr=class extends re{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 da=class extends W{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var pa=class extends W{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ha=class extends re{constructor(e,t){switch(super(e,t),this.readUint8()){case 0:this.stereoMode=0;break;case 1:this.stereoMode=1;break;case 2:this.stereoMode=2;break;case 3:this.stereoMode=3;break;case 4:this.stereoMode=4;break}this.cursor+=1}};var ma=class extends re{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var fa=class extends re{constructor(e,t){super(e,t),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}};var ba=class extends W{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ga=class extends re{constructor(e,t){super(e,t),this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.trackId=this.readUint32(),this.cursor+=4,this.duration=this.readUint32(),this.cursor+=8,this.layer=this.readUint16(),this.alternateGroup=this.readUint16(),this.cursor+=2,this.cursor+=2,this.matrix=[[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()]],this.width=this.readUint32(),this.height=this.readUint32()}};var va=class extends W{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Sa=class extends W{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ya=class extends re{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var Ta=class extends W{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ia=class extends re{constructor(e,t){super(e,t),this.trackId=this.readUint32(),this.flags&1&&(this.baseDataOffset=this.readUint64()),this.flags&2&&(this.sampleDescriptionIndex=this.readUint32()),this.flags&8&&(this.defaultSampleDuration=this.readUint32()),this.flags&16&&(this.defaultSampleSize=this.readUint32()),this.flags&32&&(this.defaultSampleFlags=this.readUint32())}};var Ea=class extends re{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 xa=class extends re{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 Pa=class extends W{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var wa=class extends re{constructor(e,t){super(e,t),this.entryCount=this.readUint32(),this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+8,this.content.byteLength-8))}};var Aa=class extends W{constructor(e,t){super(e,t),this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+78,this.content.byteLength-78))}};var uM={ftyp:na,moov:oa,mvhd:ua,moof:la,mdat:ca,sidx:hr,trak:da,mdia:ba,mfhd:ya,tkhd:ga,traf:Ta,tfhd:Ia,tfdt:Ea,trun:xa,minf:va,sv3d:pa,st3d:ha,prhd:ma,proj:Sa,equi:fa,uuid:sa,stbl:Pa,stsd:wa,avc1:Aa,unknown:ei},gt=class a{constructor(e={}){this.options=P({offset:0},e)}parse(e){let t=[],r=this.options.offset;for(;r<e.byteLength;)try{let s=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+r+4,4)),n=this.createBox(s,new DataView(e.buffer,e.byteOffset+r));if(!n.size)break;t.push(n),r+=n.size}catch(i){break}return t}createBox(e,t){let r=uM[e];return r?new r(t,new a):new ei(t,new a)}};var Ut=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{var r,i,s;(s=(r=this.index)[i=t.type])!=null||(r[i]=[]),this.index[t.type].push(t),t.children.length>0&&this.indexBoxLevel(t.children)})}find(e){return this.index[e]&&this.index[e][0]?this.index[e][0]:null}findAll(e){return this.index[e]||[]}};var cM=new TextDecoder("ascii"),dM=a=>cM.decode(new DataView(a.buffer,a.byteOffset+4,4))==="ftyp",pM=a=>{let e=new hr(a,new gt),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})},hM=(a,e)=>{let r=new gt().parse(a),i=new Ut(r),s=i.findAll("moof"),n=e?i.findAll("uuid"):i.findAll("mdat");if(!(n.length&&s.length))return null;let o=s[0],u=n[n.length-1],l=o.source.byteOffset,d=u.source.byteOffset-o.source.byteOffset+u.size;return new DataView(a.buffer,l,d)},mM=a=>{let t=new gt().parse(a),r=new Ut(t),i={},s=r.findAll("uuid");return s.length?s[s.length-1]:i},fM=a=>{var i;let t=new gt().parse(a);return(i=new Ut(t).find("sidx"))==null?void 0:i.timescale},bM=(a,e)=>{let r=new gt().parse(a),s=new Ut(r).findAll("traf"),n=s[s.length-1].children.find(d=>d.type==="tfhd"),o=s[s.length-1].children.find(d=>d.type==="tfdt"),u=s[s.length-1].children.find(d=>d.type==="trun"),l=0;return u.sampleDuration.length?l=u.sampleDuration.reduce((d,p)=>d+p,0):l=n.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+l)/e*1e3},gM=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 gt().parse(a),i=new Ut(r);if(i.find("sv3d")){e.is3dVideo=!0;let n=i.find("st3d");n&&(e.stereoMode=n.stereoMode);let o=i.find("prhd");o&&(e.projectionData.pose.yaw=o.poseYawDegrees,e.projectionData.pose.pitch=o.posePitchDegrees,e.projectionData.pose.roll=o.poseRollDegrees);let u=i.find("equi");u&&(e.projectionData.bounds.top=u.projectionBoundsTop,e.projectionData.bounds.right=u.projectionBoundsRight,e.projectionData.bounds.bottom=u.projectionBoundsBottom,e.projectionData.bounds.left=u.projectionBoundsLeft)}return e},xS={validateData:dM,parseInit:gM,getIndexRange:()=>{},parseSegments:pM,parseFeedableSegmentChunk:hM,getChunkEndTime:bM,getServerLatencyTimestamps:mM,getTimescaleFromIndex:fM};var $a=B(Fe(),1);import{assertNonNullable as Vl,isNonNullable as kS,isNullable as SM}from"@vkontakte/videoplayer-shared/es2015";import{assertNever as vM}from"@vkontakte/videoplayer-shared/es2015";var PS={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"}},wS=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=ka(a,t),i=r in PS,s=i?PS[r].type:"binary",n=a.getUint8(t),o=0;n&128?o=1:n&64?o=2:n&32?o=3:n&16?o=4:n&8?o=5:n&4?o=6:n&2?o=7:n&1&&(o=8);let u=new DataView(a.buffer,a.byteOffset+t+1,o-1),l=n&255>>o,c=ka(u),d=l*at(2,(o-1)*8)+c,p=t+o,h;return p+d>a.byteLength?h=new DataView(a.buffer,a.byteOffset+p):h=new DataView(a.buffer,a.byteOffset+p,d),{tag:i?r:"0x"+r.toString(16).toUpperCase(),type:s,tagHeaderSize:p,tagSize:p+d,value:h,valueSize:d}},ka=(a,e=a.byteLength)=>{switch(e){case 1:return a.getUint8(0);case 2:return a.getUint16(0);case 3:return a.getUint8(0)*at(2,16)+a.getUint16(1);case 4:return a.getUint32(0);case 5:return a.getUint8(0)*at(2,32)+a.getUint32(1);case 6:return a.getUint16(0)*at(2,32)+a.getUint32(2);case 7:{let t=a.getUint8(0)*281474976710656+a.getUint16(1)*4294967296+a.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},et=(a,e)=>{switch(e){case"int":return a.getInt8(0);case"uint":return ka(a);case"float":return a.byteLength===4?a.getFloat32(0):a.getFloat64(0);case"string":return new TextDecoder("ascii").decode(a);case"utf8":return new TextDecoder("utf-8").decode(a);case"date":return new Date(Date.UTC(2001,0)+a.getInt8(0)).getTime();case"master":return a;case"binary":return a;default:vM(e)}},mr=(a,e)=>{let t=0;for(;t<a.byteLength;){let r=new DataView(a.buffer,a.byteOffset+t),i=wS(r);if(!e(i))return;i.type==="master"&&mr(i.value,e),t=i.value.byteOffset-a.byteOffset+i.valueSize}},AS=a=>{if(a.getUint32(0)!==440786851)return!1;let e,t,r,i=wS(a);return mr(i.value,({tag:s,type:n,value:o})=>(s===17143?e=et(o,n):s===17026?t=et(o,n):s===17029&&(r=et(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(r===void 0||r<=2)};var $S=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],yM=[231,22612,22743,167,171,163,160,175],TM=a=>{let e,t,r,i,s=!1,n=!1,o=!1,u,l,c=!1,d=0;return mr(a,({tag:p,type:h,value:m,valueSize:b})=>{if(p===21419){let g=et(m,h);l=ka(g)}else p!==21420&&(l=void 0);return p===408125543?(e=m.byteOffset,t=m.byteOffset+b):p===357149030?s=!0:p===290298740?n=!0:p===2807729?r=et(m,h):p===17545?i=et(m,h):p===21420&&l===475249515?u=et(m,h):p===374648427?mr(m,({tag:g,type:v,value:S})=>g===30321?(c=et(S,v)===1,!1):!0):s&&n&&(0,$a.default)($S,p)&&(o=!0),!o}),Vl(e,"Failed to parse webm Segment start"),Vl(t,"Failed to parse webm Segment end"),Vl(i,"Failed to parse webm Segment duration"),r=r!=null?r:1e6,{segmentStart:Math.round(e/1e9*r*1e3),segmentEnd:Math.round(t/1e9*r*1e3),timeScale:r,segmentDuration:Math.round(i/1e9*r*1e3),cuesSeekPosition:u,is3dVideo:c,stereoMode:d,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},IM=a=>{if(SM(a.cuesSeekPosition))return;let e=a.segmentStart+a.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},EM=(a,e)=>{let t=!1,r=!1,i=o=>kS(o.time)&&kS(o.position),s=[],n;return mr(a,({tag:o,type:u,value:l})=>{switch(o){case 475249515:t=!0;break;case 187:n&&i(n)&&s.push(n),n={};break;case 179:n&&(n.time=et(l,u));break;case 183:break;case 241:n&&(n.position=et(l,u));break;default:t&&(0,$a.default)($S,o)&&(r=!0)}return!(t&&r)}),n&&i(n)&&s.push(n),s.map((o,u)=>{let{time:l,position:c}=o,d=s[u+1];return{status:"none",time:{from:l,to:d?d.time:e.segmentDuration},byte:{from:e.segmentStart+c,to:d?e.segmentStart+d.position-1:e.segmentEnd-1}}})},xM=a=>{let e=0,t=!1;try{mr(a,r=>r.tag===524531317?r.tagSize<=a.byteLength?(e=r.tagSize,!1):(e+=r.tagHeaderSize,!0):(0,$a.default)(yM,r.tag)?(e+r.tagSize<=a.byteLength&&(e+=r.tagSize,t||(t=(0,$a.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},RS={validateData:AS,parseInit:TM,getIndexRange:IM,parseSegments:EM,parseFeedableSegmentChunk:xM};var Ra=a=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(a);if(e){let[,t,r]=e;if(t==="audio"||t==="video")switch(r){case"webm":return RS;case"mp4":return xS}}throw new ReferenceError(`Unsupported mime type ${a}`)};var Wl=B(KS(),1),Iy=B(Br(),1),Ey=B(py(),1),xy=B(Bt(),1),Yl=B(zr(),1);var hy=B(Fe(),1),ql=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,hy.default)(["6E","7A","F4"],o)}}return!1};import{isNonNullable as TD,isNullable as yy}from"@vkontakte/videoplayer-shared/es2015";var my=a=>{if(a.includes("/")){let e=a.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(a)};var fy=a=>{var e;try{let t=SD(),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 SD(){let a="(?<extlang>(?:[a-z]{3}(?:-[a-z]{3}){0,2}))",e="x(?:-[a-z0-9]{1,8})+",c=`^(?:(?<langtag>${`
|
|
64
64
|
(?<language>${`(?:[a-z]{2,3}(?:-${a})?|[a-z]{4}|[a-z]{5,8})`})
|
|
65
65
|
(-(?<script>[a-z]{4}))?
|
|
66
66
|
(-(?<region>(?:[a-z]{2}|[0-9]{3})))?
|
|
67
67
|
(?<variants>(?:-(?:[a-z0-9]{5,8}|[0-9][a-z0-9]{3}))*)
|
|
68
68
|
(?<extensions>(?:-[0-9a-wy-z](?:-[a-z0-9]{2,8})+)*)
|
|
69
69
|
(?:-(?<privateuse>(?:${e})))?
|
|
70
|
-
`})|(?<privateuse2>${e}))$`.replace(/[\s\t\n]/g,"");return new RegExp(c,"i")}var Nl=_(Bt(),1);import{videoSizeToQuality as SC}from"@vkontakte/videoplayer-shared/es2015";var fy=({id:a,width:e,height:t,bitrate:r,fps:i,quality:s,streamId:n})=>{var u;let o=(u=s?Ot(s):void 0)!=null?u:SC({width:e,height:t});return o&&{id:a,quality:o,bitrate:r,size:{width:e,height:t},fps:i,streamId:n}},by=({id:a,bitrate:e})=>({id:a,bitrate:e}),gy=({language:a,label:e},{id:t,url:r,isAuto:i})=>({id:t,url:r,isAuto:i,type:"internal",language:a,label:e}),vy=({language:a,label:e,id:t,url:r,isAuto:i})=>({id:t,url:r,isAuto:i,type:"internal",language:a,label:e}),Fl=({id:a,language:e,label:t,codecs:r,isDefault:i})=>({id:a,language:e,label:t,codec:(0,Nl.default)(r.split("."),0),isDefault:i}),ql=({id:a,language:e,label:t,hdr:r,codecs:i})=>({id:a,language:e,hdr:r,label:t,codec:(0,Nl.default)(i.split("."),0)}),Ul=a=>"url"in a,Ee=a=>a.type==="template",Ra=a=>a instanceof DOMException&&(a.name==="AbortError"||a.code===20);var yy=a=>{if(!(a!=null&&a.startsWith("P")))return;let e=(n,o)=>{let u=n?parseFloat(n.replace(",",".")):NaN;return(isNaN(u)?0:u)*o},r=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(a),i=(r==null?void 0:r[1])==="-"?-1:1,s={days:e(r==null?void 0:r[5],i),hours:e(r==null?void 0:r[6],i),minutes:e(r==null?void 0:r[7],i),seconds:e(r==null?void 0:r[8],i)};return s.days*24*60*60*1e3+s.hours*60*60*1e3+s.minutes*60*1e3+s.seconds*1e3},vt=(a,e)=>{let t=a;t=(0,Hl.default)(t,"$$","$");let r={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[i,s]of(0,Ty.default)(r)){let n=new RegExp(`\\$${i}(?:%0(\\d+)d)?\\$`,"g");t=(0,Hl.default)(t,n,(o,u)=>Sy(s)?o:Sy(u)?s:(0,Iy.default)(s,parseInt(u,10),"0"))}return t},xy=(a,e)=>{var C,j,Q,L,W,q,J,k,T,V,Y,U,$e,ui,yr,z,he,Se,ye,Et,Tr,xt,Yt,Ir,li,Ac,kc,Rc,Lc,$c,Mc,Cc,Dc,Vc,_c,Oc,Bc,Nc,Fc,qc,Uc,Hc,jc,Qc,Gc,Wc,Yc,zc,Kc,Xc,Jc,Zc,ed,td,rd,id,ad,sd,nd,od,ud;let r=new DOMParser().parseFromString(a,"application/xml"),i={video:[],audio:[],text:[]},s=r.children[0],n=Array.from(s.querySelectorAll("MPD > BaseURL").values()).map(Qe=>{var ee,zt;return(zt=(ee=Qe.textContent)==null?void 0:ee.trim())!=null?zt:""}),o=(C=(0,Ey.default)(n,0))!=null?C:"",u=s.getAttribute("type")==="dynamic",l=s.getAttribute("availabilityStartTime"),c=s.getAttribute("publishTime"),d=s.getElementsByTagName("vk:Attrs")[0],p=d==null?void 0:d.getElementsByTagName("vk:XLatestSegmentPublishTime")[0].textContent,h=d==null?void 0:d.getElementsByTagName("vk:XStreamIsLive")[0].textContent,m=d==null?void 0:d.getElementsByTagName("vk:XStreamIsUnpublished")[0].textContent,b=d==null?void 0:d.getElementsByTagName("vk:XPlaybackDuration")[0].textContent,g;u&&(g={availabilityStartTime:l?new Date(l).getTime():0,publishTime:c?new Date(c).getTime():0,latestSegmentPublishTime:p?new Date(p).getTime():0,streamIsAlive:h==="yes",streamIsUnpublished:m==="yes"});let v,S=s.getAttribute("mediaPresentationDuration"),y=[...s.getElementsByTagName("Period")],I=y.reduce((Qe,ee)=>$(P({},Qe),{[ee.id]:ee.children}),{}),E=y.reduce((Qe,ee)=>$(P({},Qe),{[ee.id]:ee.getAttribute("duration")}),{});S?v=yy(S):(0,jl.default)(E).filter(Qe=>Qe).length&&!u?v=(0,jl.default)(E).reduce((Qe,ee)=>{var zt;return Qe+((zt=yy(ee))!=null?zt:0)},0):b&&(v=parseInt(b,10));let R=0,M=(Q=(j=s.getAttribute("profiles"))==null?void 0:j.split(","))!=null?Q:[];for(let Qe of y.map(ee=>ee.id))for(let ee of I[Qe]){let zt=(L=ee.getAttribute("id"))!=null?L:"id"+(R++).toString(10),ci=(W=ee.getAttribute("mimeType"))!=null?W:"",Xn=(q=ee.getAttribute("codecs"))!=null?q:"",Jn=(J=ee.getAttribute("contentType"))!=null?J:ci==null?void 0:ci.split("/")[0],WT=(T=(k=ee.getAttribute("profiles"))==null?void 0:k.split(","))!=null?T:[],ld=(Y=my((V=ee.getAttribute("lang"))!=null?V:""))!=null?Y:{},Xa=(ui=($e=(U=ee.querySelector("Label"))==null?void 0:U.textContent)==null?void 0:$e.trim())!=null?ui:void 0,YT=ee.querySelectorAll("Representation"),zT=ee.querySelector("SegmentTemplate"),KT=(z=(yr=ee.querySelector("Role"))==null?void 0:yr.getAttribute("value"))!=null?z:void 0,Er=Jn,se={id:zt,language:ld.language,isDefault:KT==="main",label:Xa,codecs:Xn,hdr:Er==="video"&&Ol(Xn),mime:ci,representations:[]};for(let Z of YT){let Pt=(he=Z.getAttribute("lang"))!=null?he:void 0,di=(ye=(Se=Xa!=null?Xa:ee.getAttribute("label"))!=null?Se:Z.getAttribute("label"))!=null?ye:void 0,Ja=(xt=(Tr=(Et=Z.querySelector("BaseURL"))==null?void 0:Et.textContent)==null?void 0:Tr.trim())!=null?xt:"",Kt=new URL(Ja||o,e).toString(),wt=(Yt=Z.getAttribute("mimeType"))!=null?Yt:ci,Za=(li=(Ir=Z.getAttribute("codecs"))!=null?Ir:Xn)!=null?li:"",es;if(Jn==="text"){let At=Z.getAttribute("id")||"",ts=((Ac=ld.privateuse)==null?void 0:Ac.includes("x-auto"))||At.includes("_auto"),Xt=Z.querySelector("SegmentTemplate");if(Xt){let pi={representationId:(kc=Z.getAttribute("id"))!=null?kc:void 0,bandwidth:(Rc=Z.getAttribute("bandwidth"))!=null?Rc:void 0},rs=parseInt((Lc=Z.getAttribute("bandwidth"))!=null?Lc:"",10)/1e3,is=(Mc=parseInt(($c=Xt.getAttribute("startNumber"))!=null?$c:"",10))!=null?Mc:1,xr=parseInt((Cc=Xt.getAttribute("timescale"))!=null?Cc:"",10),Zn=(Dc=Xt.querySelectorAll("SegmentTimeline S"))!=null?Dc:[],Pr=Xt.getAttribute("media");if(!Pr)continue;let as=[],ss=0,ns="",wr=0,hi=is,Te=0;for(let Ge of Zn){let Jt=parseInt((Vc=Ge.getAttribute("d"))!=null?Vc:"",10),Ne=parseInt((_c=Ge.getAttribute("r"))!=null?_c:"",10)||0,kt=parseInt((Oc=Ge.getAttribute("t"))!=null?Oc:"",10);Te=Number.isFinite(kt)?kt:Te;let Zt=Jt/xr*1e3,Rt=Te/xr*1e3;for(let tt=0;tt<Ne+1;tt++){let Lt=vt(Pr,$(P({},pi),{segmentNumber:hi.toString(10),segmentTime:(Te+tt*Jt).toString(10)})),Ar=(Rt!=null?Rt:0)+tt*Zt,fi=Ar+Zt;hi++,as.push({time:{from:Ar,to:fi},url:Lt})}Te+=(Ne+1)*Jt,ss+=(Ne+1)*Zt}wr=Te/xr*1e3,ns=vt(Pr,$(P({},pi),{segmentNumber:hi.toString(10),segmentTime:Te.toString(10)}));let mi={time:{from:wr,to:1/0},url:ns},dt={type:"template",baseUrl:Kt,segmentTemplateUrl:Pr,initUrl:"",totalSegmentsDurationMs:ss,segments:as,nextSegmentBeyondManifest:mi,timescale:xr};es={id:At,kind:"text",segmentReference:dt,profiles:[],duration:v,bitrate:rs,mime:"",codecs:"",width:0,height:0,isAuto:ts}}else es={id:At,isAuto:ts,kind:"text",url:Kt}}else{let At=(Nc=(Bc=Z.getAttribute("contentType"))!=null?Bc:wt==null?void 0:wt.split("/")[0])!=null?Nc:Jn,ts=(qc=(Fc=ee.getAttribute("profiles"))==null?void 0:Fc.split(","))!=null?qc:[],Xt=parseInt((Uc=Z.getAttribute("width"))!=null?Uc:"",10),pi=parseInt((Hc=Z.getAttribute("height"))!=null?Hc:"",10),rs=parseInt((jc=Z.getAttribute("bandwidth"))!=null?jc:"",10)/1e3,is=(Qc=Z.getAttribute("frameRate"))!=null?Qc:"",xr=(Gc=Z.getAttribute("quality"))!=null?Gc:void 0,Zn=is?hy(is):void 0,Pr=(Wc=Z.getAttribute("id"))!=null?Wc:"id"+(R++).toString(10),as=At==="video"?`${pi}p`:At==="audio"?`${rs}Kbps`:Za,ss=`${Pr}@${as}`,ns=[...M,...WT,...ts],wr,hi=Z.querySelector("SegmentBase"),Te=(Yc=Z.querySelector("SegmentTemplate"))!=null?Yc:zT;if(hi){let dt=(Kc=(zc=Z.querySelector("SegmentBase Initialization"))==null?void 0:zc.getAttribute("range"))!=null?Kc:"",[Ge,Jt]=dt.split("-").map(Lt=>parseInt(Lt,10)),Ne={from:Ge,to:Jt},kt=(Xc=Z.querySelector("SegmentBase"))==null?void 0:Xc.getAttribute("indexRange"),[Zt,Rt]=kt?kt.split("-").map(Lt=>parseInt(Lt,10)):[],tt=kt?{from:Zt,to:Rt}:void 0;wr={type:"byteRange",url:Kt,initRange:Ne,indexRange:tt}}else if(Te){let dt={representationId:(Jc=Z.getAttribute("id"))!=null?Jc:void 0,bandwidth:(Zc=Z.getAttribute("bandwidth"))!=null?Zc:void 0},Ge=parseInt((ed=Te.getAttribute("timescale"))!=null?ed:"",10),Jt=(td=Te.getAttribute("initialization"))!=null?td:"",Ne=Te.getAttribute("media"),kt=(id=parseInt((rd=Te.getAttribute("startNumber"))!=null?rd:"",10))!=null?id:1,Zt=vt(Jt,dt);if(!Ne)throw new ReferenceError("No media attribute in SegmentTemplate");let Rt=(ad=Te.querySelectorAll("SegmentTimeline S"))!=null?ad:[],tt=[],Lt=0,Ar="",fi=0;if(Rt.length){let os=kt,We=0;for(let kr of Rt){let rt=parseInt((sd=kr.getAttribute("d"))!=null?sd:"",10),er=parseInt((nd=kr.getAttribute("r"))!=null?nd:"",10)||0,us=parseInt((od=kr.getAttribute("t"))!=null?od:"",10);We=Number.isFinite(us)?us:We;let eo=rt/Ge*1e3,to=We/Ge*1e3;for(let ls=0;ls<er+1;ls++){let JT=vt(Ne,$(P({},dt),{segmentNumber:os.toString(10),segmentTime:(We+ls*rt).toString(10)})),cd=(to!=null?to:0)+ls*eo,ZT=cd+eo;os++,tt.push({time:{from:cd,to:ZT},url:JT})}We+=(er+1)*rt,Lt+=(er+1)*eo}fi=We/Ge*1e3,Ar=vt(Ne,$(P({},dt),{segmentNumber:os.toString(10),segmentTime:We.toString(10)}))}else if(yC(v)){let We=parseInt((ud=Te.getAttribute("duration"))!=null?ud:"",10)/Ge*1e3,kr=Math.ceil(v/We),rt=0;for(let er=1;er<kr;er++){let us=vt(Ne,$(P({},dt),{segmentNumber:er.toString(10),segmentTime:rt.toString(10)}));tt.push({time:{from:rt,to:rt+We},url:us}),rt+=We}fi=rt,Ar=vt(Ne,$(P({},dt),{segmentNumber:kr.toString(10),segmentTime:rt.toString(10)}))}let XT={time:{from:fi,to:1/0},url:Ar};wr={type:"template",baseUrl:Kt,segmentTemplateUrl:Ne,initUrl:Zt,totalSegmentsDurationMs:Lt,segments:tt,nextSegmentBeyondManifest:XT,timescale:Ge}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!At||!wt)continue;let mi={video:"video",audio:"audio",text:"text"}[At];if(!mi)continue;Er||(Er=mi),es={id:ss,kind:mi,segmentReference:wr,profiles:ns,duration:v,bitrate:rs,mime:wt,codecs:Za,width:Xt,height:pi,fps:Zn,quality:xr}}se.language||(se.language=Pt),se.label||(se.label=di),se.mime||(se.mime=wt),se.codecs||(se.codecs=Za),se.hdr||(se.hdr=Er==="video"&&Ol(Za)),se.representations.push(es)}if(Er){let Z=i[Er].find(Pt=>Pt.id===se.id);if(Z&&se.representations.every(Pt=>Ee(Pt.segmentReference)))for(let Pt of Z.representations){let di=se.representations.find(wt=>wt.id===Pt.id),Ja=di==null?void 0:di.segmentReference,Kt=Pt.segmentReference;Kt.segments.push(...Ja.segments),Kt.nextSegmentBeyondManifest=Ja.nextSegmentBeyondManifest}else i[Er].push(se)}}return{duration:v,streams:i,baseUrls:n,live:g}};var wy=_(Fe(),1);import{isNonNullable as Py}from"@vkontakte/videoplayer-shared/es2015";var xe=(a,e)=>Py(a)&&Py(e)&&a.readyState==="open"&&(0,wy.default)([...a.activeSourceBuffers],e);var La=class{constructor(e,t,r,{fetcher:i,tuning:s,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new fr(0);this.currentLowLatencySegmentLength$=new fr(0);this.currentSegmentLength$=new fr(0);this.onLastSegment$=new fr(!1);this.fullyBuffered$=new fr(!1);this.playingRepresentation$=new fr(void 0);this.playingRepresentationInit$=new fr(void 0);this.error$=new IC;this.gaps=[];this.subscription=new EC;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new ge;this.switchAbortController=new ge;this.destroyAbortController=new ge;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=Ht(this.destroyAbortController.signal,function(e){return oe(this,null,function*(){let t=this.representations.get(e);Le(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new IS(this.sourceBuffer),this.subscription.add(Gl(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let o,u=this.mediaSource.readyState;u!=="open"&&(o={id:`SegmentEjection_source_${u}`,category:St.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o!=null||(o={id:"SegmentEjection",category:St.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),this.error$.next(o)})),this.subscription.add(Gl(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:St.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o||!xe(this.mediaSource,this.sourceBuffer))return;let u=Math.min(this.bufferLimit,Rl(this.sourceBuffer.buffered)*.8);this.bufferLimit=u;let l=ut(this.sourceBuffer.buffered,o),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(o,n*2,l<c).catch(d=>{this.handleAsyncError(d,"pruneBuffer")})})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(n=>this.error$.next(n))),yield this.loadInit(t,"high",!0);let r=this.initData.get(t.id),i=this.segments.get(t.id),s=this.parsedInitData.get(t.id);Le(r,"No init buffer for starting representation"),Le(i,"No segments for starting representation"),r instanceof ArrayBuffer&&(this.searchGaps(i,t),yield this.sourceBufferTaskQueue.append(r,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(s))})}.bind(this));this.switchTo=Ht(this.destroyAbortController.signal,function(e,t=!1){return oe(this,null,function*(){if(e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let r=this.representations.get(e);Le(r,`No such representation ${e}`);let i=this.segments.get(e),s=this.initData.get(e);if(ve(s)||ve(i)?yield this.loadInit(r,"high",!1):s instanceof Promise&&(yield s),i=this.segments.get(e),Le(i,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!xe(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer();else{let n=this.getCurrentPosition();ti(n)&&!this.isLive&&(this.bufferLimit=1/0,yield new ds(this.pruneBuffer(n,1/0,!0))),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}this.maintain()}})}.bind(this));this.switchToOld=Ht(this.destroyAbortController.signal,function(e,t=!1){return oe(this,null,function*(){if(e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let r=this.representations.get(e);Le(r,`No such representation ${e}`);let i=this.segments.get(e),s=this.initData.get(e);if(ve(s)||ve(i)?yield this.loadInit(r,"high",!1):s instanceof Promise&&(yield s),i=this.segments.get(e),Le(i,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!xe(this.mediaSource,this.sourceBuffer)))if(yield this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer(),this.maintain();else{let n=this.getCurrentPosition();ti(n)&&(this.isLive||(this.bufferLimit=1/0,yield new ds(this.pruneBuffer(n,1/0,!0))),this.maintain(n)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}})}.bind(this));this.seekLive=Ht(this.destroyAbortController.signal,function(e){return oe(this,null,function*(){var u,l;let t=(u=(0,gn.default)(e,c=>c.representations))!=null?u:[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let c of this.representations.keys()){let d=t.find(m=>m.id===c);d&&this.representations.set(c,d);let p=this.representations.get(c);if(!p||!Ee(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);Le(i);let s=this.segments.get(r);Le(s,"No segments for starting representation");let n=this.initData.get(r);if(Le(n,"No init buffer for starting representation"),!(n instanceof ArrayBuffer))return;let o=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,yield this.abort(),o&&(yield this.sourceBufferTaskQueue.remove(o.from*1e3,o.to*1e3,this.destroyAbortController.signal)),this.searchGaps(s,i),yield this.sourceBufferTaskQueue.append(n,this.destroyAbortController.signal),this.isSeekingLive=!1})}.bind(this));var c;this.fetcher=i,this.tuning=s,this.compatibilityMode=u,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=o,this.isLive=!!(l!=null&&l.live),this.baseUrls=(c=l==null?void 0:l.baseUrls)!=null?c:[],this.initData=new Map(r.map(d=>[d.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(r.map(d=>[d.id,d])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}switchToWithPreviousAbort(e,t=!1){e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new ge,Ht(this.switchAbortController.signal,function(r,i=!1){return oe(this,null,function*(){this.switchingToRepresentationId=r;let s=this.representations.get(r);Le(s,`No such representation ${r}`);let n=this.segments.get(r),o=this.initData.get(r);if(ve(o)||ve(n)?yield this.loadInit(s,"high",!1):o instanceof Promise&&(yield o),n=this.segments.get(r),Le(n,"No segments for starting representation"),o=this.initData.get(r),!(!(o instanceof ArrayBuffer)||!this.sourceBuffer||!xe(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(o,this.downloadAbortController.signal),i)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=r,yield this.dropBuffer();else{let u=this.getCurrentPosition();ti(u)&&!this.isLive&&(this.bufferLimit=this.forwardBufferTarget,yield this.pruneBuffer(u,1/0,!0)),this.downloadingRepresentationId=r,this.switchingToRepresentationId=void 0}this.maintain()}})}.bind(this))(e,t))}warmUpMediaSource(){!ve(this.sourceBuffer)&&!this.sourceBuffer.updating&&(this.sourceBuffer.mode="segments")}abort(){return x(this,null,function*(){for(let e of this.activeSegments)this.abortSegment(e.segment);return this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new ge,this.abortBuffer()})}maintain(e=this.getCurrentPosition()){if(ve(e)||ve(this.downloadingRepresentationId)||ve(this.playingRepresentationId)||ve(this.sourceBuffer)||!xe(this.mediaSource,this.sourceBuffer)||ti(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),r=this.segments.get(this.downloadingRepresentationId);if(Le(t,`No such representation ${this.downloadingRepresentationId}`),!r)return;let i=r.find(l=>e>=l.time.from&&e<l.time.to);ti(i)&&isFinite(i.time.from)&&isFinite(i.time.to)&&this.currentSegmentLength$.next((i==null?void 0:i.time.to)-i.time.from);let s=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){let c=ut(this.sourceBuffer.buffered,e),d=i?i.time.to+100:-1/0;i&&i.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&c>=i.time.to-e+100&&(s=d)}if(isFinite(this.bufferLimit)&&Rl(this.sourceBuffer.buffered)>=this.bufferLimit){let l=ut(this.sourceBuffer.buffered,e),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,l<c).catch(d=>{this.handleAsyncError(d,"pruneBuffer")});return}let o=[];if(!this.activeSegments.size&&(o=this.selectForwardBufferSegments(r,t.segmentReference.type,s),o.length)){let l="auto";if(this.tuning.dash.useFetchPriorityHints&&i)if((0,bn.default)(o,i))l="high";else{let c=(0,ri.default)(o,0);c&&c.time.from-i.time.to>=this.forwardBufferTarget/2&&(l="low")}this.loadSegments(o,t,l).catch(c=>{this.handleAsyncError(c,"loadSegments")})}(!this.preloadOnly&&!this.allInitsLoaded&&i&&i.status==="fed"&&!o.length&&ut(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let u=(0,ri.default)(r,-1);u&&u.status==="fed"&&(this.fullyBuffered$.next(!0),this.isLive||this.onLastSegment$.next(i===u))}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}searchGaps(e,t){this.gaps=[];let r=0,i=this.isLive?this.liveInitialAdditionalOffset:0;for(let s of e)Math.trunc(s.time.from-r)>0&&this.gaps.push({representation:t.id,from:r,to:s.time.from+i}),r=s.time.to;ti(t.duration)&&t.duration-r>0&&!this.isLive&&this.gaps.push({representation:t.id,from:r,to:t.duration})}getActualLiveStartingSegments(e){let t=e.segments,r=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,i=[],s=0,n=t.length-1;do i.unshift(t[n]),s+=t[n].time.to-t[n].time.from,n--;while(s<r&&n>=0);return this.liveInitialAdditionalOffset=s-r,this.isActiveLowLatency()?[i[0]]:i}getLiveSegmentsToLoadState(e){let t=(0,gn.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,gn.default)(e==null?void 0:e.streams[this.kind],o=>o.representations))!=null?r:[];if(![...this.segments.values()].every(o=>!o.length))for(let o of t){if(!o||!Ee(o.segmentReference))return;let u=o.segmentReference.segments.map(h=>$(P({},h),{status:"none",size:void 0})),l=100,c=(i=this.segments.get(o.id))!=null?i:[],d=(n=(s=(0,ri.default)(c,-1))==null?void 0:s.time.to)!=null?n:0,p=u==null?void 0:u.findIndex(h=>d>=h.time.from+l&&d<=h.time.to+l);if(p===-1){this.liveUpdateSegmentIndex=0;let h=this.getActualLiveStartingSegments(o.segmentReference);this.segments.set(o.id,h)}else{let h=u.slice(p+1);this.segments.set(o.id,[...c,...h])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;Le(e);let t=this.segments.get(e);if(t!=null&&t.length){let r=t[t.length-1];this.updateLowLatencyLiveIfNeeded(r)}}updateLowLatencyLiveIfNeeded(e){var r;let t=0;for(let i of this.representations.values()){let s=i.segmentReference;if(!Ee(s))return;let n=(r=this.segments.get(i.id))!=null?r:[],o=n.find(l=>Math.floor(l.time.from)===Math.floor(e.time.from));if(o&&!isFinite(o.time.to)&&(o.time.to=e.time.to,t=o.time.to-o.time.from),!!!n.find(l=>Math.floor(l.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let l=Math.round(e.time.to*s.timescale/1e3).toString(10),c=vt(s.segmentTemplateUrl,{segmentTime:l});n.push({status:"none",time:{from:e.time.to,to:1/0},url:c})}}this.currentLowLatencySegmentLength$.next(t)}findSegmentStartTime(e){var s,n,o;let t=(n=(s=this.switchingToRepresentationId)!=null?s:this.downloadingRepresentationId)!=null?n:this.playingRepresentationId;if(!t)return;let r=this.segments.get(t);if(!r)return;let i=r.find(u=>u.time.from<=e&&u.time.to>=e);return(o=i==null?void 0:i.time.from)!=null?o:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){var e;if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),(e=this.sourceBufferTaskQueue)==null||e.destroy(),this.gapDetectionIdleCallback&&ra&&ra(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&ra&&ra(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer)try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(t){if(!(t instanceof DOMException&&t.name==="NotFoundError"))throw t}this.sourceBuffer=null,this.downloadAbortController.abort(),this.switchAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,r){return this.isLive?this.selectForwardBufferSegmentsLive(e,r):this.selectForwardBufferSegmentsRecord(e,t,r)}selectForwardBufferSegmentsLive(e,t){let r=e.findIndex(i=>t>=i.time.from&&t<i.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=r),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,r){let i=e.findIndex(({status:d,time:{from:p,to:h}},m)=>{let b=p<=r&&h>=r,g=p>r||b||m===0&&r===0,v=Math.min(this.forwardBufferTarget,this.bufferLimit),S=this.preloadOnly&&p<=r+v||h<=r+v;return(d==="none"||d==="partially_ejected"&&g&&S&&this.sourceBuffer&&xe(this.mediaSource,this.sourceBuffer)&&!(qt(this.sourceBuffer.buffered,p)&&qt(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,c=this.preloadOnly?this.forwardBufferTarget:0;for(let d=i;d<s.length&&(n<=l||o<=c);d++){let p=s[d];if(n+=p.byte.to+1-p.byte.from,o+=p.time.to+1-p.time.from,p.status==="none"||p.status==="partially_ejected")u.push(p);else break}return u}loadSegments(e,t,r="auto"){return x(this,null,function*(){Ee(t.segmentReference)?yield this.loadTemplateSegment(e[0],t,r):yield this.loadByteRangeSegments(e,t,r)})}loadTemplateSegment(e,t,r="auto"){return x(this,null,function*(){e.status="downloading";let i={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(i);let{range:s,url:n,signal:o,onProgress:u,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(yield Ht(o,function(){return oe(this,null,function*(){let c=Wl(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(d=>setTimeout(d,c))})}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let c=yield this.fetcher.fetch(n,{range:s,signal:o,onProgress:u,priority:r,isLowLatency:this.isActiveLowLatency()});if(this.lastDataObtainedTimestampMs=fn(),!c)return;let d=new DataView(c),p=ka(t.mime);if(!isFinite(i.segment.time.to)){let b=t.segmentReference.timescale;i.segment.time.to=p.getChunkEndTime(d,b)}u&&i.feedingBytes&&l?yield Promise.all(l):yield this.sourceBufferTaskQueue.append(d,o);let{serverDataReceivedTimestamp:h,serverDataPreparedTime:m}=p.getServerLatencyTimestamps(d);h&&m&&this.currentLiveSegmentServerLatency$.next(m-h),i.segment.status="downloaded",this.onSegmentFullyAppended(i,t.id),this.failedDownloads=0}catch(c){this.abortActiveSegments([e]),Ra(c)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}})}updateRepresentationsBaseUrlIfNeeded(){if(!this.tuning.dash.enableBaseUrlSupport||!this.baseUrls.length||this.failedDownloads<=this.tuning.dash.maxSegmentRetryCount)return;this.baseUrlsIndex=(this.baseUrlsIndex+1)%this.baseUrls.length;let e=this.baseUrls[this.baseUrlsIndex];for(let t of this.representations.values())Ee(t.segmentReference)?t.segmentReference.baseUrl=e:t.segmentReference.url=e}loadByteRangeSegments(e,t,r="auto"){return x(this,null,function*(){if(!e.length)return;for(let u of e)u.status="downloading",this.activeSegments.add({segment:u,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:i,url:s,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(yield Ht(n,function(){return oe(this,null,function*(){let u=Wl(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),Gl(window,"online").pipe(TC()).subscribe(()=>{l(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{yield this.fetcher.fetch(s,{range:i,onProgress:o,signal:n,priority:r}),this.lastDataObtainedTimestampMs=fn(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),Ra(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}})}prepareByteRangeFetchSegmentParams(e,t){if(Ee(t.segmentReference))throw new Error("Representation is not byte range type");let r=t.segmentReference.url,i={from:(0,ri.default)(e,0).byte.from,to:(0,ri.default)(e,-1).byte.to},{signal:s}=this.downloadAbortController;return{url:r,range:i,signal:s,onProgress:(o,u)=>x(this,null,function*(){if(!s.aborted)try{this.lastDataObtainedTimestampMs=fn(),yield 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:St.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}})}}prepareTemplateFetchSegmentParams(e,t){if(!Ee(t.segmentReference))throw new Error("Representation is not template type");let r=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&r.searchParams.set("low-latency","yes");let i=r.toString(),{signal:s}=this.downloadAbortController,n=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(l,c)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=fn();let d=this.onSomeTemplateDataLoaded({dataView:l,loaded:c,signal:s,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(d)}catch(d){this.error$.next({id:"SegmentFeeding",category:St.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:d})}}:void 0;return{url:i,signal:s,onProgress:u,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)(0,bn.default)(e,t.segment)&&this.abortSegment(t.segment)}onSomeTemplateDataLoaded(n){return x(this,arguments,function*({dataView:e,representationId:t,loaded:r,onSegmentAppendFailed:i,signal:s}){if(!this.activeSegments.size)return;let o=this.representations.get(t);if(o)for(let u of this.activeSegments){let{segment:l}=u;if(u.representationId===t){if(s.aborted){i();continue}if(u.loadedBytes=r,u.loadedBytes>u.feedingBytes){let c=new DataView(e.buffer,e.byteOffset+u.feedingBytes,u.loadedBytes-u.feedingBytes),d=ka(o.mime).parseFeedableSegmentChunk(c,this.isLive);d!=null&&d.byteLength&&(l.status="partially_fed",u.feedingBytes+=d.byteLength,yield this.sourceBufferTaskQueue.append(d),u.fedBytes+=d.byteLength)}}}})}onSomeByteRangesDataLoaded(o){return x(this,arguments,function*({dataView:e,representationId:t,globalFrom:r,loaded:i,signal:s,onSegmentAppendFailed:n}){if(!this.activeSegments.size)return;let u=this.representations.get(t);if(u)for(let l of this.activeSegments){let{segment:c}=l;if(l.representationId!==t)continue;if(s.aborted){yield n();continue}let d=c.byte.from-r,p=c.byte.to-r,h=p-d+1,m=d<i,b=p<=i;if(!m)continue;let g=ka(u.mime);if(c.status==="downloading"&&b){c.status="downloaded";let v=new DataView(e.buffer,e.byteOffset+d,h);(yield this.sourceBufferTaskQueue.append(v,s))&&!s.aborted?this.onSegmentFullyAppended(l,t):yield n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(c.status==="downloading"||c.status==="partially_fed")&&(l.loadedBytes=Math.min(h,i-d),l.loadedBytes>l.feedingBytes)){let v=new DataView(e.buffer,e.byteOffset+d+l.feedingBytes,l.loadedBytes-l.feedingBytes),S=l.loadedBytes===h?v:g.parseFeedableSegmentChunk(v);S!=null&&S.byteLength&&(c.status="partially_fed",l.feedingBytes+=S.byteLength,(yield this.sourceBufferTaskQueue.append(S,s))&&!s.aborted?(l.fedBytes+=S.byteLength,l.fedBytes===h&&this.onSegmentFullyAppended(l,t)):yield n())}}})}onSegmentFullyAppended(e,t){var r;if(!(ve(this.sourceBuffer)||!xe(this.mediaSource,this.sourceBuffer))){!this.isLive&&N.browser.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(qt(this.sourceBuffer.buffered,e.segment.time.from,100)&&qt(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:St.VIDEO_PIPELINE,message:"Browser stuck on empty result of adding segment to source buffer"})),this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status="fed",Ul(e.segment)&&(e.segment.size=e.fedBytes);for(let i of this.representations.values())if(i.id!==t)for(let s of(r=this.segments.get(i.id))!=null?r:[])s.status==="fed"&&Math.round(s.time.from)===Math.round(e.segment.time.from)&&Math.round(s.time.to)===Math.round(e.segment.time.to)&&(s.status="none");this.updateLowLatencyLiveIfNeeded(e.segment),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment])}}abortSegment(e){e.status==="partially_fed"?e.status="partially_ejected":e.status!=="partially_ejected"&&(e.status="none");for(let t of this.activeSegments.values())if(t.segment===e){this.activeSegments.delete(t);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(let[i,s]of this.initData.entries()){let n=s instanceof Promise;t||(t=n),s===null&&(e=i)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let r=this.representations.get(e);r&&(this.initLoadIdleCallback=Al(()=>(0,Ay.default)(this.loadInit(r,"low",!1),()=>this.initLoadIdleCallback=null)))}loadInit(e,t="auto",r=!1){return x(this,null,function*(){let i=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!r&&this.failedDownloads>0?Ht(this.destroyAbortController.signal,function(){return oe(this,null,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,ka(e.mime),i)).then(o=>x(this,null,function*(){if(!o)return;let{init:u,dataView:l,segments:c}=o,d=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,d);let p=c;this.isLive&&Ee(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:St.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n})}dropBuffer(){return x(this,null,function*(){for(let e of this.segments.values())for(let t of e)t.status="none";yield this.pruneBuffer(0,1/0,!0)})}pruneBuffer(e,t,r=!1){return x(this,null,function*(){if(!this.sourceBuffer||!xe(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||ve(e))return!1;let i=[],s=0,n=u=>{u.sort((c,d)=>c.from-d.from);let l=[u[0]];for(let c=1;c<u.length;c++){let{from:d,to:p}=u[c],h=l[l.length-1];h.to>=d?h.to=Math.max(h.to,p):l.push(u[c])}return l},o=u=>{var c;if(s>=t)return i;i.push(P({},u.time)),i=n(i);let l=Ul(u)?(c=u.size)!=null?c:0:u.byte.to-u.byte.from;s+=l};for(let u of this.segments.values())for(let l of u){let c=l.time.to<=e-this.tuning.dash.bufferPruningSafeZone,d=l.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(c||d)&&l.status==="fed"&&o(l)}for(let u=0;u<this.sourceBuffer.buffered.length;u++){let l=this.sourceBuffer.buffered.start(u)*1e3,c=this.sourceBuffer.buffered.end(u)*1e3,d=0;for(let p of this.segments.values())for(let h of p)(0,bn.default)(["none","partially_ejected"],h.status)&&Math.round(h.time.from)<=Math.round(l)&&Math.round(h.time.to)>=Math.round(c)&&d++;if(d===this.segments.size){let p={time:{from:l,to:c},url:"",status:"none"};o(p)}}if(i.length&&r){let u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let l of this.segments.values())for(let c of l)c.time.from>=e+u&&c.status==="fed"&&o(c)}return i.length?(yield Promise.all(i.map(l=>this.sourceBufferTaskQueue.remove(l.from,l.to)))).reduce((l,c)=>l||c,!1):!1})}abortBuffer(){return x(this,null,function*(){if(!this.sourceBuffer||!xe(this.mediaSource,this.sourceBuffer))return!1;let e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;return this.sourceBufferTaskQueue.abort(t)})}getDebugBufferState(){if(!(!this.sourceBuffer||!xe(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}getForwardBufferDuration(){let e=this.getCurrentPosition();return!this.sourceBuffer||!xe(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||ve(e)?0:ut(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!(!this.sourceBuffer||!xe(this.mediaSource,this.sourceBuffer))){if(this.tuning.useRefactoredSearchGap)for(let r=0;r<this.sourceBuffer.buffered.length;r++)this.gaps=this.gaps.filter(i=>this.sourceBuffer&&(Math.round(i.from)<Math.round(this.sourceBuffer.buffered.start(r)*1e3)||Math.round(i.to)>Math.round(this.sourceBuffer.buffered.end(r)*1e3)));for(let r of t){let i={representation:e,from:r.time.from,to:r.time.to};for(let s=0;s<this.sourceBuffer.buffered.length;s++){let n=this.sourceBuffer.buffered.start(s)*1e3,o=this.sourceBuffer.buffered.end(s)*1e3;if(!(o<=r.time.from||n>=r.time.to)){if(n<=r.time.from&&o>=r.time.to){i=void 0;break}o>r.time.from&&o<r.time.to&&(i.from=o),n<r.time.to&&n>r.time.from&&(i.to=n)}}i&&i.to-i.from>1&&!this.gaps.some(s=>i&&s.from===i.from&&s.to===i.to)&&this.gaps.push(i)}}}detectGapsWhenIdle(e,t){if(!(this.gapDetectionIdleCallback||!this.sourceBuffer||!xe(this.mediaSource,this.sourceBuffer))){if(!this.tuning.useRefactoredSearchGap)for(let r=0;r<this.sourceBuffer.buffered.length;r++)this.gaps=this.gaps.filter(i=>this.sourceBuffer&&(Math.round(i.from)<Math.round(this.sourceBuffer.buffered.start(r)*1e3)||Math.round(i.to)>Math.round(this.sourceBuffer.buffered.end(r)*1e3)));this.gapDetectionIdleCallback=Al(()=>{try{this.detectGaps(e,t)}catch(r){this.error$.next({id:"GapDetection",category:St.WTF,message:"detectGaps threw",thrown:r})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if(ve(this.sourceBuffer)||!xe(this.mediaSource,this.sourceBuffer)||ve(this.playingRepresentationId))return;let e=[];for(let r=0;r<this.sourceBuffer.buffered.length;r++){let i=Math.floor(this.sourceBuffer.buffered.start(r)*1e3),s=Math.ceil(this.sourceBuffer.buffered.end(r)*1e3);e.push({from:i,to:s})}let t=100;for(let r of this.segments.values())for(let i of r){let{status:s}=i;if(s!=="fed"&&s!=="partially_ejected")continue;let n=Math.floor(i.time.from),o=Math.ceil(i.time.to),u=e.some(c=>c.from-t<=n&&c.to+t>=o),l=e.filter(c=>n>=c.from&&n<c.to-t||o>c.from+t&&o<=c.to);u||(l.length===1?i.status="partially_ejected":this.gaps.some(c=>c.from===i.time.from||c.to===i.time.to)?i.status="partially_ejected":i.status="none")}}handleAsyncError(e,t){this.error$.next({id:t,category:St.VIDEO_PIPELINE,thrown:e,message:"Something went wrong"})}};var $a=a=>{let e=new URL(a);return e.searchParams.set("quic","1"),e.toString()};var ky=a=>{var s;let e=a.get("X-Delivery-Type"),t=a.get("X-Reused"),r=e===null?"http1":e!=null?e:void 0,i=t===null?void 0:(s={1:!0,0:!1}[t])!=null?s:void 0;return{type:r,reused:i}};import{abortable as Ma,assertNever as Ly,fromEvent as $y,merge as xC,now as Ca,Subscription as PC,Subject as My,ValueSubject as Yl,flattenObject as ii,ErrorCategory as Da}from"@vkontakte/videoplayer-shared/es2015";var Ry=a=>{let e=new URL(a);return e.searchParams.set("enable-subtitles","yes"),e.toString()};var Sn=class{constructor({throughputEstimator:e,requestQuic:t,tracer:r,compatibilityMode:i=!1,useEnableSubtitlesParam:s=!1}){this.lastConnectionType$=new Yl(void 0);this.lastConnectionReused$=new Yl(void 0);this.lastRequestFirstBytes$=new Yl(void 0);this.recoverableError$=new My;this.error$=new My;this.abortAllController=new ge;this.subscription=new PC;this.fetchManifest=Ma(this.abortAllController.signal,function(e){return oe(this,null,function*(){let t=this.tracer.createComponentTracer("FetchManifest"),r=e;this.requestQuic&&(r=$a(r)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(r=Ry(r));let i=yield this.doFetch(r,{signal:this.abortAllController.signal}).catch(vn);return i?(t.log("success",ii({url:r,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(i.headers),i.text()):(t.error("error",ii({url:r,message:"No data in request manifest"})),t.end(),null)})}.bind(this));this.fetch=Ma(this.abortAllController.signal,function(l){return oe(this,arguments,function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:r,onProgress:i,priority:s="auto",signal:n,measureThroughput:o=!0,isLowLatency:u=!1}={}){var L,W;let c=e,d=new Headers,p=this.tracer.createComponentTracer("Fetch");if(r)switch(t){case 0:{d.append("Range",`bytes=${r.from}-${r.to}`);break}case 1:{let q=new URL(c,location.href);q.searchParams.append("bytes",`${r.from}-${r.to}`),c=q.toString();break}default:Ly(t)}this.requestQuic&&(c=$a(c));let h=this.abortAllController.signal,m;if(n){let q=new ge;if(m=xC($y(this.abortAllController.signal,"abort"),$y(n,"abort")).subscribe(()=>{try{q.abort()}catch(J){vn(J)}}),this.abortAllController.signal.aborted||n.aborted)try{q.abort()}catch(J){vn(J)}h=q.signal}let b=Ca();p.log("startRequest",ii({url:c,priority:s,rangeMethod:t,range:r,isLowLatency:u,requestStartedAt:b}));let g=yield this.doFetch(c,{priority:s,headers:d,signal:h}),v=Ca();if(!g)return p.error("error",{message:"No response in request"}),p.end(),m==null||m.unsubscribe(),null;if((L=this.throughputEstimator)==null||L.addRawRtt(v-b),!g.ok||!g.body){m==null||m.unsubscribe();let q=`Fetch error ${g.status}: ${g.statusText}`;return p.error("error",{message:q}),p.end(),Promise.reject(new Error(`Fetch error ${g.status}: ${g.statusText}`))}if(this.onHeadersReceived(g.headers),!i&&!o){m==null||m.unsubscribe();let q=Ca(),J={requestStartedAt:b,requestEndedAt:q,duration:q-b};return p.log("endRequest",ii(J)),p.end(),g.arrayBuffer()}let[S,y]=g.body.tee(),I=S.getReader();o&&((W=this.throughputEstimator)==null||W.trackStream(y,u));let E=0,R=new Uint8Array(0),M=!1,re=q=>{m==null||m.unsubscribe(),M=!0,vn(q)},C=Ma(h,function(k){return oe(this,arguments,function*({done:q,value:J}){if(E===0&&this.lastRequestFirstBytes$.next(Ca()-b),h.aborted){m==null||m.unsubscribe();return}if(!q&&J){let T=new Uint8Array(R.length+J.length);T.set(R),T.set(J,R.length),R=T,E+=J.byteLength,i==null||i(new DataView(R.buffer),E),yield I==null?void 0:I.read().then(C,re)}})}.bind(this));yield I==null?void 0:I.read().then(C,re),m==null||m.unsubscribe();let j=Ca(),Q={failed:M,requestStartedAt:b,requestEndedAt:j,duration:j-b};return M?(p.error("endRequest",ii(Q)),p.end(),null):(p.log("endRequest",ii(Q)),p.end(),R.buffer)})}.bind(this));this.fetchByteRangeRepresentation=Ma(this.abortAllController.signal,function(e,t,r){return oe(this,null,function*(){var v;if(e.type!=="byteRange")return null;let{from:i,to:s}=e.initRange,n=i,o=s,u=!1,l,c;e.indexRange&&(l=e.indexRange.from,c=e.indexRange.to,u=s+1===l,u&&(n=Math.min(l,i),o=Math.max(c,s))),n=Math.min(n,0);let d=yield this.fetch(e.url,{range:{from:n,to:o},priority:r,measureThroughput:!1});if(!d)return null;let p=new DataView(d,i-n,s-n+1);if(!t.validateData(p))throw new Error("Invalid media file");let h=t.parseInit(p),m=(v=e.indexRange)!=null?v:t.getIndexRange(h);if(!m)throw new ReferenceError("No way to load representation index");let b;if(u)b=new DataView(d,m.from-n,m.to-m.from+1);else{let S=yield this.fetch(e.url,{range:m,priority:r,measureThroughput:!1});if(!S)return null;b=new DataView(S)}let g=t.parseSegments(b,h,m);return{init:h,dataView:new DataView(d),segments:g}})}.bind(this));this.fetchTemplateRepresentation=Ma(this.abortAllController.signal,function(e,t){return oe(this,null,function*(){if(e.type!=="template")return null;let r=new URL(e.initUrl,e.baseUrl).toString(),i=yield this.fetch(r,{priority:t,measureThroughput:!1});return i?{init:null,segments:e.segments.map(n=>$(P({},n),{status:"none",size:void 0})),dataView:new DataView(i)}:null})}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=i,this.tracer=r.createComponentTracer("Fetcher"),this.useEnableSubtitlesParam=s}onHeadersReceived(e){let{type:t,reused:r}=ky(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(r)}fetchRepresentation(e,t,r="auto"){return x(this,null,function*(){var s,n;let{type:i}=e;switch(i){case"byteRange":return(s=yield this.fetchByteRangeRepresentation(e,t,r))!=null?s:null;case"template":return(n=yield this.fetchTemplateRepresentation(e,r))!=null?n:null;default:Ly(i)}})}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}doFetch(e,t){return x(this,null,function*(){let r=yield lt(e,t);if(r.ok)return r;let i=yield r.text(),s=parseInt(i);if(!isNaN(s))switch(s){case 1:this.recoverableError$.next({id:"VideoDataLinkExpiredError",message:"Video data links have expired",category:Da.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:Da.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:Da.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:Da.FATAL});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${s})`,category:Da.FATAL})}})}},vn=a=>{if(!Ra(a))throw a};var br=(a,e,t)=>t*e+(1-t)*a,zl=(a,e)=>a.reduce((t,r)=>t+r,0)/e,Cy=(a,e,t,r)=>{let i=0,s=t,n=zl(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 wC,ValueSubject as Dy}from"@vkontakte/videoplayer-shared/es2015";var jt=class{constructor(e){this.prevReported=void 0;this.pastMeasures=[];this.takenMeasures=0;this.measuresCursor=0;var r;this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new Dy(e.initial),this.debounced$=new Dy(e.initial);let t=(r=e.label)!=null?r:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new Ie(`raw_${t}`),this.smoothedSeries$=new Ie(`smoothed_${t}`),this.reportedSeries$=new Ie(`reported_${t}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,r=0;for(let o=0;o<this.pastMeasures.length;o++)this.pastMeasures[o]!==void 0&&(t+=it(this.pastMeasures[o]-this.smoothed,2),r++);this.takenMeasures=r,t/=r;let i=Math.sqrt(t),s=this.smoothed+this.params.deviationFactor*i,n=this.smoothed-this.params.deviationFactor*i;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(e),this.updateSmoothedValue(e),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),!(this.smoothed>s||this.smoothed<n)&&(wC(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 yn=class extends jt{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=br(this.slow,e,this.params.emaAlphaSlow),this.fast=br(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var Tn=class extends jt{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=zl(this.pastMeasures,this.takenMeasures);this.emaSmoothed=br(this.emaSmoothed,e,this.params.emaAlpha);let r=Cy(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=r?this.emaSmoothed:t}};var In=class extends jt{constructor(t){super(t);this.furtherValues=[];this.currentTopExtremumValue=0;this.extremumInterval=t.extremumInterval}next(t){this.currentTopExtremumValue<=t?(this.currentTopExtremumValue=t,this.furtherValues=[]):this.furtherValues.length===this.extremumInterval?(super.next(this.currentTopExtremumValue),this.currentTopExtremumValue=t,this.furtherValues=[]):this.furtherValues.push(t)}updateSmoothedValue(t){this.smoothed=this.smoothed?br(this.smoothed,t,this.params.emaAlpha):t}};var gr=class{static getSmoothedValue(e,t,r){return r.type==="TwoEma"?new yn({initial:e,emaAlphaSlow:r.emaAlphaSlow,emaAlphaFast:r.emaAlphaFast,changeThreshold:r.changeThreshold,fastDirection:t,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"}):new Tn({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 In(P({initial:e,label:"liveEdgeDelay"},t))}};var Kl=(a,e)=>{a&&a.playbackRate!==e&&(a.playbackRate=e)};import{isNullable as AC,ValueSubject as kC}from"@vkontakte/videoplayer-shared/es2015";var Va=class a{constructor(e,t){this.currentRepresentation$=new kC(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(!AC(e))for(let r of this.representations)for(let i of r){let s=i.segmentReference,n=s.segments.length,o=s.segments[0].time.from,u=s.segments[n-1].time.to;if(e<o||e>u)continue;let l=s.segments.find(c=>c.time.from<=e&&c.time.to>=e);!l||((t=this.currentSegment)==null?void 0:t.time.from)===l.time.from&&this.currentSegment.time.to===l.time.to||(this.currentSegment=l,this.currentRepresentation$.next($(P({},i),{label:"Live Text",language:"ru",isAuto:!0,url:new URL(l.url,s.baseUrl).toString()})))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e!=null?e:[]){let r=a.filterRepresentations(t.representations);if(r){this.representations[this.representationsCursor]=r,this.representationsCursor=(this.representationsCursor+1)%this.maxRepresentations;break}}}static isSupported(e){return!!(e!=null&&e.some(t=>a.filterRepresentations(t.representations)))}static filterRepresentations(e){return e==null?void 0:e.filter(t=>t.kind==="text"&&"segmentReference"in t&&Ee(t.segmentReference))}};var xn=_(Bt(),1);import{assertNever as Pn}from"@vkontakte/videoplayer-shared/es2015";var Vy=(a,{useHlsJs:e,useManagedMediaSource:t,useOldMSEDetection:r})=>{let{containers:i,protocols:s,codecs:n,nativeHlsSupported:o}=N.video,u=(n.h264||n.h265)&&n.aac,l=s.mse&&(!r||!!window.MediaStreamTrack)||s.mms&&t;return a.filter(c=>{switch(c){case"DASH_SEP":return l&&i.mp4&&u;case"DASH_WEBM":return l&&i.webm&&n.vp9&&n.opus;case"DASH_WEBM_AV1":return l&&i.webm&&n.av1&&n.opus;case"DASH_STREAMS":return l&&(i.mp4&&u||i.webm&&(n.vp9||n.av1)&&(n.opus||n.aac));case"DASH_LIVE":return l&&i.mp4&&u;case"DASH_LIVE_CMAF":return l&&i.mp4&&u&&i.cmaf;case"DASH_ONDEMAND":return l&&i.mp4&&u;case"HLS":case"HLS_ONDEMAND":return o||e&&l&&i.mp4&&u;case"HLS_LIVE":case"HLS_LIVE_CMAF":return o;case"MPEG":return i.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return s.webrtc&&s.ws&&n.h264&&(i.mp4||i.webm);default:return Pn(c)}})},En=a=>{let{webmDecodingInfo:e}=N.video,t="DASH_WEBM",r="DASH_WEBM_AV1";switch(a){case"vp9":return[t,r];case"av1":return[r,t];case"none":return[];case"smooth":return e?e[r].smooth?[r,t]:e[t].smooth?[t,r]:[r,t]:[t,r];case"power_efficient":return e?e[r].powerEfficient?[r,t]:e[t].powerEfficient?[t,r]:[r,t]:[t,r];default:Pn(a)}return[t,r]},_y=({webmCodec:a,androidPreferredFormat:e,preferMultiStream:t})=>{let r=[...t?["DASH_STREAMS"]:[],...En(a),"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]],i=[...t?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]];if(N.device.isAndroid)switch(e){case"mpeg":return["MPEG",...r,"HLS","HLS_ONDEMAND"];case"hls":return["HLS","HLS_ONDEMAND",...r,"MPEG"];case"dash":return[...r,"HLS","HLS_ONDEMAND","MPEG"];case"dash_any_mpeg":return[...i,"MPEG",...En(a),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...En(a),"MPEG",...i,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...En(a),...i,"HLS","HLS_ONDEMAND"];default:Pn(e)}return N.video.nativeHlsSupported?[...r,"HLS","HLS_ONDEMAND","MPEG"]:[...r,"HLS","HLS_ONDEMAND","MPEG"]},Oy=({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=N.device.isMac&&N.browser.isSafari;if(N.device.isAndroid)switch(a){case"dash":case"dash_any_mpeg":case"dash_any_webm":case"dash_sep":{o=s;break}case"hls":case"mpeg":{o=n;break}default:Pn(a)}else N.video.nativeHlsSupported&&!u?o=n:u?o=e?["DASH_LIVE_CMAF","HLS_LIVE_CMAF","HLS_LIVE","DASH_LIVE"]:["HLS_LIVE","DASH_LIVE","DASH_LIVE_CMAF","HLS_LIVE_CMAF"]:o=s;return t?["WEB_RTC_LIVE",...o]:[...o,"WEB_RTC_LIVE"]},Xl=a=>a?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],By=a=>{if(a.size===0)return;if(a.size===1){let t=a.values().next();return(0,xn.default)(t.value.split("."),0)}for(let t of a){let r=(0,xn.default)(t.split("."),0);if(r==="opus"||r==="vp09"||r==="av01")return r}let e=a.values().next();return(0,xn.default)(e.value.split("."),0)};var OC=["timeupdate","progress","play","seeked","stalled","waiting"],BC=["timeupdate","progress","loadeddata","playing","seeked"];var Rn=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 O("none");this.currentVideoRepresentation$=new ie(void 0);this.currentVideoRepresentationInit$=new ie(void 0);this.currentAudioRepresentation$=new ie(void 0);this.currentVideoSegmentLength$=new ie(0);this.currentAudioSegmentLength$=new ie(0);this.error$=new kn;this.lastConnectionType$=new ie(void 0);this.lastConnectionReused$=new ie(void 0);this.lastRequestFirstBytes$=new ie(void 0);this.currentLiveTextRepresentation$=new ie(null);this.isLive$=new ie(!1);this.isActiveLive$=new ie(!1);this.isLowLatency$=new ie(!1);this.liveDuration$=new ie(0);this.liveSeekableDuration$=new ie(0);this.liveAvailabilityStartTime$=new ie(0);this.liveStreamStatus$=new ie(void 0);this.bufferLength$=new ie(0);this.liveLatency$=new ie(void 0);this.liveLoadBufferLength$=new ie(0);this.livePositionFromPlayer$=new ie(0);this.currentStallDuration$=new ie(0);this.videoLastDataObtainedTimestamp$=new ie(0);this.fetcherRecoverableError$=new kn;this.fetcherError$=new kn;this.liveStreamEndTimestamp=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.forceEnded$=new kn;this.gapWatchdogActive=!1;this.destroyController=new ge;this.initManifest=Zl(this.destroyController.signal,function(e,t,r){return oe(this,null,function*(){var i;this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=be(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:ct.PARSER,message:"No playable video representations"})})}.bind(this));this.updateManifest=Zl(this.destroyController.signal,function(){return oe(this,null,function*(){var n,o;this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(u=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:ct.NETWORK,message:"Failed to load manifest",thrown:u})});if(!e)return null;let t=null;try{t=xy(e!=null?e:"",this.manifestUrlString)}catch(u){let l=(n=bS(e))!=null?n:{id:"ManifestParsing",category:ct.PARSER,message:"Failed to parse MPD manifest",thrown:u};this.error$.next(l)}if(!t)return null;let r=(u,l,c)=>{var d,p,h,m;return!!((p=(d=this.element)==null?void 0:d.canPlayType)!=null&&p.call(d,l)&&((m=(h=Je())==null?void 0:h.isTypeSupported)!=null&&m.call(h,`${l}; codecs="${c}"`))||u==="text")};if(t.live){this.isLive$.next(!!t.live);let{availabilityStartTime:u,latestSegmentPublishTime:l,streamIsUnpublished:c,streamIsAlive:d}=t.live,p=((o=t.duration)!=null?o:0)/1e3;this.liveSeekableDuration$.next(-1*p),this.liveDuration$.next((l-u)/1e3),this.liveAvailabilityStartTime$.next(t.live.availabilityStartTime);let h="active";d||(h=c?"unpublished":"unexpectedly_down"),this.liveStreamStatus$.next(h)}let i={text:t.streams.text,video:[],audio:[]};for(let u of["video","audio"]){let c=t.streams[u].filter(({mime:h,codecs:m})=>r(u,h,m)),d=new Set(c.map(({codecs:h})=>h)),p=By(d);if(p&&(i[u]=c.filter(({codecs:h})=>h.startsWith(p))),u==="video"){let h=this.tuning.preferHDR,m=i.video.some(g=>g.hdr),b=i.video.some(g=>!g.hdr);N.display.isHDR&&h&&m?i.video=i.video.filter(g=>g.hdr):b&&(i.video=i.video.filter(g=>!g.hdr))}}let s=$(P({},t),{streams:i});return this.tracer.log("updateManifestEnd",_a(s)),s})}.bind(this));this.initRepresentations=Zl(this.destroyController.signal,function(e,t,r){return oe(this,null,function*(){var d;this.tracer.log("initRepresentationsStart",_a({initialVideo:e,initialAudio:t,sourceHls:r})),ai(this.manifest),ai(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let i=p=>{this.representationSubscription.add(yt(p,"error").pipe(wn(h=>{var m;return!!((m=this.element)!=null&&m.played.length)})).subscribe(h=>{this.error$.next({id:"VideoSource",category:ct.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:h})}))};this.source=this.tuning.useManagedMediaSource?Dg():new MediaSource;let s=document.createElement("source");if(i(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),this.tuning.useManagedMediaSource&&en())if(r){let p=document.createElement("source");i(p),p.type="application/x-mpegurl",p.src=r.url,this.element.appendChild(p)}else this.element.disableRemotePlayback=!0;this.isActiveLive$.next(this.isLive$.getValue());let n={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),manifest:this.manifest},o=this.manifest.streams.video.reduce((p,h)=>[...p,...h.representations],[]);if(this.videoBufferManager=new La("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],Fy(t)){let p=this.manifest.streams.audio.reduce((h,m)=>[...h,...m.representations],[]);this.audioBufferManager=new La("audio",this.source,p,n),this.bufferManagers.push(this.audioBufferManager)}Va.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new Va(this.manifest.streams.text,n)),this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$));let u=()=>{var p;(p=this.stallWatchdogSubscription)==null||p.unsubscribe(),this.currentStallDuration$.next(0)};if(this.representationSubscription.add(vr(...BC.map(p=>yt(this.element,p))).pipe(Oa(p=>this.element?ut(this.element.buffered,this.element.currentTime*1e3):0),An(),VC(p=>{p>this.tuning.dash.bufferEmptinessTolerance&&u()})).subscribe(this.bufferLength$)),this.representationSubscription.add(vr(yt(this.element,"ended"),this.forceEnded$).subscribe(()=>{u()})),this.isLive$.getValue()){this.subscription.add(this.liveDuration$.pipe(An()).subscribe(h=>this.liveStreamEndTimestamp=tc())),this.subscription.add(yt(this.element,"pause").subscribe(()=>{this.livePauseWatchdogSubscription=ec(1e3).subscribe(h=>{let m=Ys(this.manifestUrlString,2);this.manifestUrlString=be(this.manifestUrlString,m+1e3,2),this.liveStreamStatus$.getValue()==="active"&&this.updateManifest()})})).add(yt(this.element,"play").subscribe(h=>{var m;return(m=this.livePauseWatchdogSubscription)==null?void 0:m.unsubscribe()})),this.representationSubscription.add(si({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(Oa(({isActiveLive:h,isLowLatency:m})=>h&&m),An()).subscribe(h=>{this.isManualDecreasePlaybackInLive()||Kl(this.element,1)})),this.representationSubscription.add(si({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(wn(({bufferLength:h,isActiveLive:m,isLowLatency:b})=>m&&b&&!!h)).subscribe(({bufferLength:h})=>this.liveBuffer.next(h))),this.representationSubscription.add(this.videoBufferManager.currentLowLatencySegmentLength$.subscribe(h=>{if(!this.isActiveLive$.getValue()&&!this.isLowLatency$.getValue()&&!h)return;let m=this.liveSeekableDuration$.getValue()-h/1e3;this.liveSeekableDuration$.next(Math.max(m,-1*this.tuning.dashCmafLive.maxLiveDuration)),this.liveDuration$.next(this.liveDuration$.getValue()+h/1e3)})),this.representationSubscription.add(si({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe(wn(({isLive:h})=>h),An((h,m)=>m.bufferLength<h.bufferLength),Oa(({rtt:h,bufferLength:m,segmentServerLatency:b})=>{let g=Ys(this.manifestUrlString,2);return(h/2+m+b+g)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add(si({liveBuffer:this.liveBuffer.smoothed$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).subscribe(({liveBuffer:h,isActiveLive:m,isLowLatency:b})=>{if(!b||!m)return;let g=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,v=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,S=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,y=h-g;if(this.isManualDecreasePlaybackInLive())return;let I=1;Math.abs(y)>v&&(I=1+Math.sign(y)*S),Kl(this.element,I)})),this.representationSubscription.add(this.bufferLength$.subscribe(h=>{var b,g;let m=0;if(h){let v=((g=(b=this.element)==null?void 0:b.currentTime)!=null?g:0)*1e3;m=Math.min(...this.bufferManagers.map(y=>{var I,E;return(E=(I=y.getLiveSegmentsToLoadState(this.manifest))==null?void 0:I.to)!=null?E:v}))-v}this.liveLoadBufferLength$.getValue()!==m&&this.liveLoadBufferLength$.next(m)}));let p=0;this.representationSubscription.add(si({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(_C(1e3)).subscribe(b=>x(this,[b],function*({liveLoadBufferLength:h,bufferLength:m}){if(!this.element||this.isUpdatingLive)return;let g=this.element.playbackRate,v=Ys(this.manifestUrlString,2),S=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,y=Math.min(S,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*g),I=this.tuning.dashCmafLive.normalizedActualBufferOffset*g,E=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*g,R=isFinite(h)?h:m,M=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),re=S<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next(re);let C="none";if(M?C="active_low_latency":this.isLowLatency$.getValue()&&re?(this.bufferManagers.forEach(j=>j.proceedLowLatencyLive()),C="active_low_latency"):v!==0&&R<y?C="live_forward_buffering":R<y+E&&(C="live_with_target_offset"),isFinite(h)&&(p=h>p?h:p),C==="live_forward_buffering"||C==="live_with_target_offset"){let j=p-(y+I),Q=this.normolizeLiveOffset(Math.trunc(v+j/g)),L=Math.abs(Q-v),W=0;!h||L<=this.tuning.dashCmafLive.offsetCalculationError?W=v:Q>0&&L>this.tuning.dashCmafLive.offsetCalculationError&&(W=Q),this.manifestUrlString=be(this.manifestUrlString,W,2)}(C==="live_with_target_offset"||C==="live_forward_buffering")&&(p=0,yield this.updateLive())}),h=>{this.error$.next({id:"updateLive",category:ct.VIDEO_PIPELINE,thrown:h,message:"Failed to update live with subscription"})}))}let l=vr(...this.bufferManagers.map(p=>p.fullyBuffered$)).pipe(Oa(()=>this.bufferManagers.every(p=>p.fullyBuffered$.getValue()))),c=vr(...this.bufferManagers.map(p=>p.onLastSegment$)).pipe(Oa(()=>this.bufferManagers.some(p=>p.onLastSegment$.getValue())));if(this.representationSubscription.add(vr(this.forceEnded$,si({allBuffersFull:l,someBufferEnded:c}).pipe(wn(({allBuffersFull:p,someBufferEnded:h})=>p&&h))).subscribe(()=>{var p;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(h=>!h.updating))try{(p=this.source)==null||p.endOfStream(),this.bufferManagers.forEach(h=>h.warmUpMediaSource())}catch(h){this.error$.next({id:"EndOfStream",category:ct.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:h})}})),this.representationSubscription.add(vr(...this.bufferManagers.map(p=>p.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.representationSubscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&(this.representationSubscription.add(this.audioBufferManager.playingRepresentation$.subscribe(this.currentAudioRepresentation$)),this.representationSubscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$))),this.liveTextManager&&this.representationSubscription.add(this.liveTextManager.currentRepresentation$.subscribe(this.currentLiveTextRepresentation$)),this.source.readyState!=="open"&&(yield new Promise(p=>{var h;return(h=this.source)==null?void 0:h.addEventListener("sourceopen",p)})),!this.isLive$.getValue()){let p=[(d=this.manifest.duration)!=null?d:0,...(0,rc.default)((0,rc.default)([...this.manifest.streams.audio,...this.manifest.streams.video],h=>h.representations),h=>{let m=[];return h.duration&&m.push(h.duration),Ee(h.segmentReference)&&h.segmentReference.totalSegmentsDurationMs&&m.push(h.segmentReference.totalSegmentsDurationMs),m})];this.source.duration=Math.max(...p)/1e3}this.audioBufferManager&&Fy(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=ec(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),s=>{this.error$.next({id:"GapWatchdog",category:ct.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 Sn({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer,useEnableSubtitlesParam:e.tuning.useEnableSubtitlesParam}),this.subscription.add(this.fetcher.recoverableError$.subscribe(this.fetcherRecoverableError$)),this.subscription.add(this.fetcher.error$.subscribe(this.fetcherError$)),this.liveBuffer=gr.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,P({},e.tuning.dashCmafLive.lowLatency.bufferEstimator)),this.initTracerSubscription()}seekLive(e){return x(this,null,function*(){var i,s,n;ai(this.element);let t=this.liveStreamStatus$.getValue()!=="active"?tc()-this.liveStreamEndTimestamp:0,r=this.normolizeLiveOffset(e+t);this.isActiveLive$.next(r===0),this.manifestUrlString=be(this.manifestUrlString,r,2),this.manifest=yield this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,yield(i=this.videoBufferManager)==null?void 0:i.seekLive(this.manifest.streams.video),yield(s=this.audioBufferManager)==null?void 0:s.seekLive(this.manifest.streams.audio),(n=this.liveTextManager)==null||n.seekLive(this.manifest.streams.text))})}initBuffer(){ai(this.element),this.state$.setState("running"),this.subscription.add(vr(...OC.map(e=>yt(this.element,e)),yt(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:ct.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(yt(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(yt(this.element,"waiting").subscribe(()=>{var t;this.element&&this.element.readyState===2&&!this.element.seeking&&qt(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{var h,m,b,g,v,S,y,I,E,R;if(!this.element)return;let r=this.currentStallDuration$.getValue();r+=50,this.currentStallDuration$.next(r);let i={timeInWaiting:r},s=tc(),n=100,o=(m=(h=this.videoBufferManager)==null?void 0:h.lastDataObtainedTimestamp)!=null?m:0;this.videoLastDataObtainedTimestamp$.next(o);let u=(g=(b=this.audioBufferManager)==null?void 0:b.lastDataObtainedTimestamp)!=null?g:0,l=(S=(v=this.videoBufferManager)==null?void 0:v.getForwardBufferDuration())!=null?S:0,c=(I=(y=this.audioBufferManager)==null?void 0:y.getForwardBufferDuration())!=null?I:0,d=l<n&&s-o>this.tuning.dash.crashOnStallTWithoutDataTimeout,p=this.audioBufferManager&&c<n&&s-u>this.tuning.dash.crashOnStallTWithoutDataTimeout;if((d||p)&&r>this.tuning.dash.crashOnStallTWithoutDataTimeout||r>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${r} ms`);if(this.isLive$.getValue()&&r%2e3===0){let M=this.normolizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);this.seekLive(M).catch(re=>{this.error$.next({id:"stallIntervalCallback",category:ct.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:re})}),i.liveLastOffset=M}else{let M=this.element.currentTime*1e3;(E=this.videoBufferManager)==null||E.maintain(M),(R=this.audioBufferManager)==null||R.maintain(M),i.position=M}this.tracer.log("stallIntervalCallback",_a(i))};(t=this.stallWatchdogSubscription)==null||t.unsubscribe(),this.stallWatchdogSubscription=ec(50).subscribe(e,r=>{this.error$.next({id:"StallWatchdogCallback",category:ct.NETWORK,message:"Can't restore DASH after stall.",thrown:r})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}switchRepresentation(e,t,r=!1){return x(this,null,function*(){let i={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return this.tuning.useNewSwitchTo?this.currentStallDuration$.getValue()>0?i==null?void 0:i.switchToWithPreviousAbort(t,r):i==null?void 0:i.switchTo(t,r):i==null?void 0:i.switchToOld(t,r)})}seek(e,t){return x(this,null,function*(){var i,s,n,o,u;ai(this.element),ai(this.videoBufferManager);let r;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?r=e:r=Math.max((i=this.videoBufferManager.findSegmentStartTime(e))!=null?i:e,(n=(s=this.audioBufferManager)==null?void 0:s.findSegmentStartTime(e))!=null?n:e),qt(this.element.buffered,r)||(yield Promise.all([this.videoBufferManager.abort(),(o=this.audioBufferManager)==null?void 0:o.abort()])),!(qy(this.element)||qy(this.videoBufferManager))&&(this.videoBufferManager.maintain(r),(u=this.audioBufferManager)==null||u.maintain(r),this.element.currentTime=r/1e3,this.tracer.log("seek",_a({requestedPosition:e,forcePrecise:t,position:r})))})}stop(){var e,t,r;this.tracer.log("stop"),(e=this.element)==null||e.querySelectorAll("source").forEach(i=>{URL.revokeObjectURL(i.src),i.remove()}),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),(t=this.videoBufferManager)==null||t.destroy(),this.videoBufferManager=null,(r=this.audioBufferManager)==null||r.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getStreams(){var e;return(e=this.manifest)==null?void 0:e.streams}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){var e;this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),((e=this.source)==null?void 0:e.readyState)==="open"&&Array.from(this.source.sourceBuffers).every(t=>!t.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}initTracerSubscription(){let e=DC(this.tracer.error.bind(this.tracer));this.error$.subscribe(e("error"))}isManualDecreasePlaybackInLive(){return!this.element||!this.isLive$.getValue()?!1:1-this.element.playbackRate>this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}updateLive(){return x(this,null,function*(){var e,t;this.isUpdatingLive=!0,this.manifest=yield this.updateManifest(),this.manifest&&((e=this.bufferManagers)==null||e.forEach(r=>r.updateLive(this.manifest)),(t=this.liveTextManager)==null||t.updateLive(this.manifest)),this.isUpdatingLive=!1})}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.getDebugBufferState();if(!e)return;let t=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),r={isJumpGapAfterSeekLive:this.isJumpGapAfterSeekLive,isActiveLowLatency:t,initialCurrentTime:this.element.currentTime};this.isJumpGapAfterSeekLive&&!t&&this.element.currentTime>e.to&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let i=this.element.currentTime*1e3,s=[],n=this.element.readyState===1?this.tuning.endGapTolerance:0;for(let o of this.bufferManagers)for(let u of o.gaps)o.playingRepresentation$.getValue()===u.representation&&u.from-n<=i&&u.to+n>i&&(this.element.duration*1e3-u.to<this.tuning.endGapTolerance?s.push(1/0):s.push(u.to));if(s.length){let o=Math.max(...s)+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,o===1/0?this.forceEnded$.next():(this.element.currentTime=o/1e3,r=$(P({},r),{gapEnds:s,jumpTo:o,resultCurrentTime:this.element.currentTime}),this.tracer.log("jumpGap",_a(r)))}}};var Ln=class{constructor(e,t){this.fov=e,this.orientation=t}};var $n=class{constructor(e,t){this.rotating=!1;this.fading=!1;this.lastTickTS=0;this.lastCameraTurnTS=0;this.fadeStartSpeed=null;this.fadeTime=0;this.camera=e,this.options=t,this.rotationSpeed={x:0,y:0,z:0},this.fadeCorrection=1/it(this.options.speedFadeTime/1e3,2)}turnCamera(e=0,t=0,r=0){this.pointCameraTo(this.camera.orientation.x+e,this.camera.orientation.y+t,this.camera.orientation.z+r)}pointCameraTo(e=0,t=0,r=0){t=this.limitCameraRotationY(t);let i=e-this.camera.orientation.x,s=t-this.camera.orientation.y,n=r-this.camera.orientation.z;this.camera.orientation.x=e,this.camera.orientation.y=t,this.camera.orientation.z=r,this.lastCameraTurn={x:i,y:s,z:n},this.lastCameraTurnTS=Date.now()}setRotationSpeed(e,t,r){this.rotationSpeed.x=e!=null?e:this.rotationSpeed.x,this.rotationSpeed.y=t!=null?t:this.rotationSpeed.y,this.rotationSpeed.z=r!=null?r:this.rotationSpeed.z}startRotation(){this.rotating=!0}stopRotation(e=!1){e?(this.setRotationSpeed(0,0,0),this.fadeStartSpeed=null):this.startFading(this.rotationSpeed.x,this.rotationSpeed.y,this.rotationSpeed.z),this.rotating=!1}onCameraRelease(){if(this.lastCameraTurn&&this.lastCameraTurnTS){let e=Date.now()-this.lastCameraTurnTS;if(e<this.options.speedFadeThreshold){let t=(1-e/this.options.speedFadeThreshold)*this.options.rotationSpeedCorrection;this.startFading(this.lastCameraTurn.x*t,this.lastCameraTurn.y*t,this.lastCameraTurn.z*t)}}}startFading(e,t,r){this.setRotationSpeed(e,t,r),this.fadeStartSpeed=P({},this.rotationSpeed),this.fading=!0}stopFading(){this.fadeStartSpeed=null,this.fading=!0,this.fadeTime=0}limitCameraRotationY(e){return Math.max(-this.options.maxYawAngle,Math.min(e,this.options.maxYawAngle))}tick(e){if(!this.lastTickTS){this.lastTickTS=e,this.lastCameraTurnTS=Date.now();return}let t=e-this.lastTickTS,r=t/1e3;if(this.rotating)this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*r,this.rotationSpeed.y*this.options.rotationSpeedCorrection*r,this.rotationSpeed.z*this.options.rotationSpeedCorrection*r);else if(this.fading&&this.fadeStartSpeed){let i=-this.fadeCorrection*it(this.fadeTime/1e3,2)+1;this.setRotationSpeed(this.fadeStartSpeed.x*i,this.fadeStartSpeed.y*i,this.fadeStartSpeed.z*i),i>0?this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*r,this.rotationSpeed.y*this.options.rotationSpeedCorrection*r,this.rotationSpeed.z*this.options.rotationSpeedCorrection*r):(this.stopRotation(!0),this.stopFading()),this.fadeTime=Math.min(this.fadeTime+t,this.options.speedFadeTime)}this.lastTickTS=e}};var Hy=`attribute vec2 a_vertex;
|
|
70
|
+
`})|(?<privateuse2>${e}))$`.replace(/[\s\t\n]/g,"");return new RegExp(c,"i")}var Hl=B(Bt(),1);import{videoSizeToQuality as yD}from"@vkontakte/videoplayer-shared/es2015";var by=({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:yD({width:e,height:t});return o&&{id:a,quality:o,bitrate:r,size:{width:e,height:t},fps:i,streamId:n}},gy=({id:a,bitrate:e})=>({id:a,bitrate:e}),vy=({language:a,label:e},{id:t,url:r,isAuto:i})=>({id:t,url:r,isAuto:i,type:"internal",language:a,label:e}),Sy=({language:a,label:e,id:t,url:r,isAuto:i})=>({id:t,url:r,isAuto:i,type:"internal",language:a,label:e}),jl=({id:a,language:e,label:t,codecs:r,isDefault:i})=>({id:a,language:e,label:t,codec:(0,Hl.default)(r.split("."),0),isDefault:i}),Ql=({id:a,language:e,label:t,hdr:r,codecs:i})=>({id:a,language:e,hdr:r,label:t,codec:(0,Hl.default)(i.split("."),0)}),Gl=a=>"url"in a,xe=a=>a.type==="template",La=a=>a instanceof DOMException&&(a.name==="AbortError"||a.code===20);var Ty=a=>{if(!(a!=null&&a.startsWith("P")))return;let e=(n,o)=>{let u=n?parseFloat(n.replace(",",".")):NaN;return(isNaN(u)?0:u)*o},r=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(a),i=(r==null?void 0:r[1])==="-"?-1:1,s={days:e(r==null?void 0:r[5],i),hours:e(r==null?void 0:r[6],i),minutes:e(r==null?void 0:r[7],i),seconds:e(r==null?void 0:r[8],i)};return s.days*24*60*60*1e3+s.hours*60*60*1e3+s.minutes*60*1e3+s.seconds*1e3},vt=(a,e)=>{let t=a;t=(0,Wl.default)(t,"$$","$");let r={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[i,s]of(0,Iy.default)(r)){let n=new RegExp(`\\$${i}(?:%0(\\d+)d)?\\$`,"g");t=(0,Wl.default)(t,n,(o,u)=>yy(s)?o:yy(u)?s:(0,Ey.default)(s,parseInt(u,10),"0"))}return t},Py=(a,e)=>{var O,Q,G,R,z,q,Z,k,D,x,U,_,je,Et,yr,K,Se,ye,Pe,Qe,Tr,xt,Yt,Ir,ci,Lc,Mc,Dc,Cc,Vc,Oc,_c,Bc,Nc,Fc,qc,Uc,Hc,jc,Qc,Gc,Wc,Yc,zc,Kc,Xc,Jc,Zc,ed,td,rd,id,ad,sd,nd,od,ud,ld,cd,dd,pd;let r=new DOMParser().parseFromString(a,"application/xml"),i={video:[],audio:[],text:[]},s=r.children[0],n=Array.from(s.querySelectorAll("MPD > BaseURL").values()).map(Ge=>{var te,zt;return(zt=(te=Ge.textContent)==null?void 0:te.trim())!=null?zt:""}),o=(O=(0,xy.default)(n,0))!=null?O:"",u=s.getAttribute("type")==="dynamic",l=s.getAttribute("availabilityStartTime"),c=s.getAttribute("publishTime"),d=s.getElementsByTagName("vk:Attrs")[0],p=d==null?void 0:d.getElementsByTagName("vk:XLatestSegmentPublishTime")[0].textContent,h=d==null?void 0:d.getElementsByTagName("vk:XStreamIsLive")[0].textContent,m=d==null?void 0:d.getElementsByTagName("vk:XStreamIsUnpublished")[0].textContent,b=d==null?void 0:d.getElementsByTagName("vk:XPlaybackDuration")[0].textContent,g;u&&(g={availabilityStartTime:l?new Date(l).getTime():0,publishTime:c?new Date(c).getTime():0,latestSegmentPublishTime:p?new Date(p).getTime():0,streamIsAlive:h==="yes",streamIsUnpublished:m==="yes"});let v,S=s.getAttribute("mediaPresentationDuration"),T=[...s.getElementsByTagName("Period")],I=T.reduce((Ge,te)=>M(P({},Ge),{[te.id]:te.children}),{}),y=T.reduce((Ge,te)=>M(P({},Ge),{[te.id]:te.getAttribute("duration")}),{});S?v=Ty(S):(0,Yl.default)(y).filter(Ge=>Ge).length&&!u?v=(0,Yl.default)(y).reduce((Ge,te)=>{var zt;return Ge+((zt=Ty(te))!=null?zt:0)},0):b&&(v=parseInt(b,10));let $=0,C=(G=(Q=s.getAttribute("profiles"))==null?void 0:Q.split(","))!=null?G:[];for(let Ge of T.map(te=>te.id))for(let te of I[Ge]){let zt=(R=te.getAttribute("id"))!=null?R:"id"+($++).toString(10),di=(z=te.getAttribute("mimeType"))!=null?z:"",Zn=(q=te.getAttribute("codecs"))!=null?q:"",eo=(Z=te.getAttribute("contentType"))!=null?Z:di==null?void 0:di.split("/")[0],WT=(D=(k=te.getAttribute("profiles"))==null?void 0:k.split(","))!=null?D:[],hd=(U=fy((x=te.getAttribute("lang"))!=null?x:""))!=null?U:{},es=(Et=(je=(_=te.querySelector("Label"))==null?void 0:_.textContent)==null?void 0:je.trim())!=null?Et:void 0,YT=te.querySelectorAll("Representation"),zT=te.querySelector("SegmentTemplate"),KT=(K=(yr=te.querySelector("Role"))==null?void 0:yr.getAttribute("value"))!=null?K:void 0,Er=eo,se={id:zt,language:hd.language,isDefault:KT==="main",label:es,codecs:Zn,hdr:Er==="video"&&ql(Zn),mime:di,representations:[]};for(let ee of YT){let Pt=(Se=ee.getAttribute("lang"))!=null?Se:void 0,pi=(Pe=(ye=es!=null?es:te.getAttribute("label"))!=null?ye:ee.getAttribute("label"))!=null?Pe:void 0,ts=(xt=(Tr=(Qe=ee.querySelector("BaseURL"))==null?void 0:Qe.textContent)==null?void 0:Tr.trim())!=null?xt:"",Kt=new URL(ts||o,e).toString(),wt=(Yt=ee.getAttribute("mimeType"))!=null?Yt:di,rs=(ci=(Ir=ee.getAttribute("codecs"))!=null?Ir:Zn)!=null?ci:"",is;if(eo==="text"){let At=ee.getAttribute("id")||"",as=((Lc=hd.privateuse)==null?void 0:Lc.includes("x-auto"))||At.includes("_auto"),Xt=ee.querySelector("SegmentTemplate");if(Xt){let hi={representationId:(Mc=ee.getAttribute("id"))!=null?Mc:void 0,bandwidth:(Dc=ee.getAttribute("bandwidth"))!=null?Dc:void 0},ss=parseInt((Cc=ee.getAttribute("bandwidth"))!=null?Cc:"",10)/1e3,ns=(Oc=parseInt((Vc=Xt.getAttribute("startNumber"))!=null?Vc:"",10))!=null?Oc:1,xr=parseInt((_c=Xt.getAttribute("timescale"))!=null?_c:"",10),to=(Bc=Xt.querySelectorAll("SegmentTimeline S"))!=null?Bc:[],Pr=Xt.getAttribute("media");if(!Pr)continue;let os=[],us=0,ls="",wr=0,mi=ns,Te=0;for(let We of to){let Jt=parseInt((Nc=We.getAttribute("d"))!=null?Nc:"",10),Ne=parseInt((Fc=We.getAttribute("r"))!=null?Fc:"",10)||0,kt=parseInt((qc=We.getAttribute("t"))!=null?qc:"",10);Te=Number.isFinite(kt)?kt:Te;let Zt=Jt/xr*1e3,$t=Te/xr*1e3;for(let rt=0;rt<Ne+1;rt++){let Rt=vt(Pr,M(P({},hi),{segmentNumber:mi.toString(10),segmentTime:(Te+rt*Jt).toString(10)})),Ar=($t!=null?$t:0)+rt*Zt,bi=Ar+Zt;mi++,os.push({time:{from:Ar,to:bi},url:Rt})}Te+=(Ne+1)*Jt,us+=(Ne+1)*Zt}wr=Te/xr*1e3,ls=vt(Pr,M(P({},hi),{segmentNumber:mi.toString(10),segmentTime:Te.toString(10)}));let fi={time:{from:wr,to:1/0},url:ls},dt={type:"template",baseUrl:Kt,segmentTemplateUrl:Pr,initUrl:"",totalSegmentsDurationMs:us,segments:os,nextSegmentBeyondManifest:fi,timescale:xr};is={id:At,kind:"text",segmentReference:dt,profiles:[],duration:v,bitrate:ss,mime:"",codecs:"",width:0,height:0,isAuto:as}}else is={id:At,isAuto:as,kind:"text",url:Kt}}else{let At=(Hc=(Uc=ee.getAttribute("contentType"))!=null?Uc:wt==null?void 0:wt.split("/")[0])!=null?Hc:eo,as=(Qc=(jc=te.getAttribute("profiles"))==null?void 0:jc.split(","))!=null?Qc:[],Xt=parseInt((Gc=ee.getAttribute("width"))!=null?Gc:"",10),hi=parseInt((Wc=ee.getAttribute("height"))!=null?Wc:"",10),ss=parseInt((Yc=ee.getAttribute("bandwidth"))!=null?Yc:"",10)/1e3,ns=(zc=ee.getAttribute("frameRate"))!=null?zc:"",xr=(Kc=ee.getAttribute("quality"))!=null?Kc:void 0,to=ns?my(ns):void 0,Pr=(Xc=ee.getAttribute("id"))!=null?Xc:"id"+($++).toString(10),os=At==="video"?`${hi}p`:At==="audio"?`${ss}Kbps`:rs,us=`${Pr}@${os}`,ls=[...C,...WT,...as],wr,mi=ee.querySelector("SegmentBase"),Te=(Jc=ee.querySelector("SegmentTemplate"))!=null?Jc:zT;if(mi){let dt=(ed=(Zc=ee.querySelector("SegmentBase Initialization"))==null?void 0:Zc.getAttribute("range"))!=null?ed:"",[We,Jt]=dt.split("-").map(Rt=>parseInt(Rt,10)),Ne={from:We,to:Jt},kt=(td=ee.querySelector("SegmentBase"))==null?void 0:td.getAttribute("indexRange"),[Zt,$t]=kt?kt.split("-").map(Rt=>parseInt(Rt,10)):[],rt=kt?{from:Zt,to:$t}:void 0;wr={type:"byteRange",url:Kt,initRange:Ne,indexRange:rt}}else if(Te){let dt={representationId:(rd=ee.getAttribute("id"))!=null?rd:void 0,bandwidth:(id=ee.getAttribute("bandwidth"))!=null?id:void 0},We=parseInt((ad=Te.getAttribute("timescale"))!=null?ad:"",10),Jt=(sd=Te.getAttribute("initialization"))!=null?sd:"",Ne=Te.getAttribute("media"),kt=(od=parseInt((nd=Te.getAttribute("startNumber"))!=null?nd:"",10))!=null?od:1,Zt=vt(Jt,dt);if(!Ne)throw new ReferenceError("No media attribute in SegmentTemplate");let $t=(ud=Te.querySelectorAll("SegmentTimeline S"))!=null?ud:[],rt=[],Rt=0,Ar="",bi=0;if($t.length){let cs=kt,Ye=0;for(let kr of $t){let it=parseInt((ld=kr.getAttribute("d"))!=null?ld:"",10),er=parseInt((cd=kr.getAttribute("r"))!=null?cd:"",10)||0,ds=parseInt((dd=kr.getAttribute("t"))!=null?dd:"",10);Ye=Number.isFinite(ds)?ds:Ye;let ro=it/We*1e3,io=Ye/We*1e3;for(let ps=0;ps<er+1;ps++){let JT=vt(Ne,M(P({},dt),{segmentNumber:cs.toString(10),segmentTime:(Ye+ps*it).toString(10)})),md=(io!=null?io:0)+ps*ro,ZT=md+ro;cs++,rt.push({time:{from:md,to:ZT},url:JT})}Ye+=(er+1)*it,Rt+=(er+1)*ro}bi=Ye/We*1e3,Ar=vt(Ne,M(P({},dt),{segmentNumber:cs.toString(10),segmentTime:Ye.toString(10)}))}else if(TD(v)){let Ye=parseInt((pd=Te.getAttribute("duration"))!=null?pd:"",10)/We*1e3,kr=Math.ceil(v/Ye),it=0;for(let er=1;er<kr;er++){let ds=vt(Ne,M(P({},dt),{segmentNumber:er.toString(10),segmentTime:it.toString(10)}));rt.push({time:{from:it,to:it+Ye},url:ds}),it+=Ye}bi=it,Ar=vt(Ne,M(P({},dt),{segmentNumber:kr.toString(10),segmentTime:it.toString(10)}))}let XT={time:{from:bi,to:1/0},url:Ar};wr={type:"template",baseUrl:Kt,segmentTemplateUrl:Ne,initUrl:Zt,totalSegmentsDurationMs:Rt,segments:rt,nextSegmentBeyondManifest:XT,timescale:We}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!At||!wt)continue;let fi={video:"video",audio:"audio",text:"text"}[At];if(!fi)continue;Er||(Er=fi),is={id:us,kind:fi,segmentReference:wr,profiles:ls,duration:v,bitrate:ss,mime:wt,codecs:rs,width:Xt,height:hi,fps:to,quality:xr}}se.language||(se.language=Pt),se.label||(se.label=pi),se.mime||(se.mime=wt),se.codecs||(se.codecs=rs),se.hdr||(se.hdr=Er==="video"&&ql(rs)),se.representations.push(is)}if(Er){let ee=i[Er].find(Pt=>Pt.id===se.id);if(ee&&se.representations.every(Pt=>xe(Pt.segmentReference)))for(let Pt of ee.representations){let pi=se.representations.find(wt=>wt.id===Pt.id),ts=pi==null?void 0:pi.segmentReference,Kt=Pt.segmentReference;Kt.segments.push(...ts.segments),Kt.nextSegmentBeyondManifest=ts.nextSegmentBeyondManifest}else i[Er].push(se)}}return{duration:v,streams:i,baseUrls:n,live:g}};var Ay=B(Fe(),1);import{isNonNullable as wy}from"@vkontakte/videoplayer-shared/es2015";var oe=(a,e)=>wy(a)&&wy(e)&&a.readyState==="open"&&(0,Ay.default)([...a.activeSourceBuffers],e);var Ma=class{constructor(e,t,r,{fetcher:i,tuning:s,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new fr(0);this.currentLowLatencySegmentLength$=new fr(0);this.currentSegmentLength$=new fr(0);this.onLastSegment$=new fr(!1);this.fullyBuffered$=new fr(!1);this.playingRepresentation$=new fr(void 0);this.playingRepresentationInit$=new fr(void 0);this.error$=new ED;this.gaps=[];this.subscription=new xD;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new ge;this.switchAbortController=new ge;this.destroyAbortController=new ge;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=Ht(this.destroyAbortController.signal,function(e){return ue(this,null,function*(){let t=this.representations.get(e);Me(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new ES(this.sourceBuffer),this.subscription.add(Kl(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let o,u=this.mediaSource.readyState;u!=="open"&&(o={id:`SegmentEjection_source_${u}`,category:St.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o!=null||(o={id:"SegmentEjection",category:St.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),this.error$.next(o)})),this.subscription.add(Kl(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:St.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o||!oe(this.mediaSource,this.sourceBuffer))return;let u=Math.min(this.bufferLimit,Dl(this.sourceBuffer.buffered)*.8);this.bufferLimit=u;let l=this.getForwardBufferDuration(o),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(o,n*2,l<c).catch(d=>{this.handleAsyncError(d,"pruneBuffer")})})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(n=>this.error$.next(n))),yield this.loadInit(t,"high",!0);let r=this.initData.get(t.id),i=this.segments.get(t.id),s=this.parsedInitData.get(t.id);Me(r,"No init buffer for starting representation"),Me(i,"No segments for starting representation"),r instanceof ArrayBuffer&&(this.searchGaps(i,t),yield this.sourceBufferTaskQueue.append(r,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(s))})}.bind(this));this.switchTo=Ht(this.destroyAbortController.signal,function(e,t=!1){return ue(this,null,function*(){if(!oe(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let r=this.representations.get(e);Me(r,`No such representation ${e}`);let i=this.segments.get(e),s=this.initData.get(e);if(ve(s)||ve(i)?yield this.loadInit(r,"high",!1):s instanceof Promise&&(yield s),i=this.segments.get(e),Me(i,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!oe(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer();else{let n=this.getCurrentPosition();ri(n)&&!this.isLive&&(this.bufferLimit=1/0,yield new ms(this.pruneBuffer(n,1/0,!0))),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}this.maintain()}})}.bind(this));this.switchToOld=Ht(this.destroyAbortController.signal,function(e,t=!1){return ue(this,null,function*(){if(!oe(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let r=this.representations.get(e);Me(r,`No such representation ${e}`);let i=this.segments.get(e),s=this.initData.get(e);if(ve(s)||ve(i)?yield this.loadInit(r,"high",!1):s instanceof Promise&&(yield s),i=this.segments.get(e),Me(i,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!oe(this.mediaSource,this.sourceBuffer)))if(yield this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer(),this.maintain();else{let n=this.getCurrentPosition();ri(n)&&(this.isLive||(this.bufferLimit=1/0,yield new ms(this.pruneBuffer(n,1/0,!0))),this.maintain(n)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}})}.bind(this));this.seekLive=Ht(this.destroyAbortController.signal,function(e){return ue(this,null,function*(){var u,l;let t=(u=(0,yn.default)(e,c=>c.representations))!=null?u:[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let c of this.representations.keys()){let d=t.find(m=>m.id===c);d&&this.representations.set(c,d);let p=this.representations.get(c);if(!p||!xe(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);Me(i);let s=this.segments.get(r);Me(s,"No segments for starting representation");let n=this.initData.get(r);if(Me(n,"No init buffer for starting representation"),!(n instanceof ArrayBuffer))return;let o=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,yield this.abort(),o&&(yield this.sourceBufferTaskQueue.remove(o.from*1e3,o.to*1e3,this.destroyAbortController.signal)),this.searchGaps(s,i),yield this.sourceBufferTaskQueue.append(n,this.destroyAbortController.signal),this.isSeekingLive=!1})}.bind(this));var c;this.fetcher=i,this.tuning=s,this.compatibilityMode=u,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=o,this.isLive=!!(l!=null&&l.live),this.baseUrls=(c=l==null?void 0:l.baseUrls)!=null?c:[],this.initData=new Map(r.map(d=>[d.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(r.map(d=>[d.id,d])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}switchToWithPreviousAbort(e,t=!1){!oe(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new ge,Ht(this.switchAbortController.signal,function(r,i=!1){return ue(this,null,function*(){this.switchingToRepresentationId=r;let s=this.representations.get(r);Me(s,`No such representation ${r}`);let n=this.segments.get(r),o=this.initData.get(r);if(ve(o)||ve(n)?yield this.loadInit(s,"high",!1):o instanceof Promise&&(yield o),n=this.segments.get(r),Me(n,"No segments for starting representation"),o=this.initData.get(r),!(!(o instanceof ArrayBuffer)||!this.sourceBuffer||!oe(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(o,this.downloadAbortController.signal),i)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=r,yield this.dropBuffer();else{let u=this.getCurrentPosition();ri(u)&&!this.isLive&&(this.bufferLimit=this.forwardBufferTarget,yield this.pruneBuffer(u,1/0,!0)),this.downloadingRepresentationId=r,this.switchingToRepresentationId=void 0}this.maintain()}})}.bind(this))(e,t))}warmUpMediaSource(){!ve(this.sourceBuffer)&&!this.sourceBuffer.updating&&(this.sourceBuffer.mode="segments")}abort(){return E(this,null,function*(){for(let e of this.activeSegments)this.abortSegment(e.segment);return this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new ge,this.abortBuffer()})}maintain(e=this.getCurrentPosition()){if(ve(e)||ve(this.downloadingRepresentationId)||ve(this.playingRepresentationId)||ve(this.sourceBuffer)||!oe(this.mediaSource,this.sourceBuffer)||ri(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),r=this.segments.get(this.downloadingRepresentationId);if(Me(t,`No such representation ${this.downloadingRepresentationId}`),!r)return;let i=r.find(c=>e>=c.time.from&&e<c.time.to);ri(i)&&isFinite(i.time.from)&&isFinite(i.time.to)&&this.currentSegmentLength$.next((i==null?void 0:i.time.to)-i.time.from);let s=e,n=100;if(this.playingRepresentationId!==this.downloadingRepresentationId){let c=this.getForwardBufferDuration(e),d=i?i.time.to+n:-1/0;i&&i.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&c>=i.time.to-e+n&&(s=d)}if(isFinite(this.bufferLimit)&&Dl(this.sourceBuffer.buffered)>=this.bufferLimit){let c=this.getForwardBufferDuration(e),d=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,c<d).catch(p=>{this.handleAsyncError(p,"pruneBuffer")});return}let u=[];if(!this.activeSegments.size&&(u=this.selectForwardBufferSegments(r,t.segmentReference.type,s),u.length)){let c="auto";if(this.tuning.dash.useFetchPriorityHints&&i)if((0,Sn.default)(u,i))c="high";else{let d=(0,ii.default)(u,0);d&&d.time.from-i.time.to>=this.forwardBufferTarget/2&&(c="low")}this.loadSegments(u,t,c).catch(d=>{this.handleAsyncError(d,"loadSegments")})}(!this.preloadOnly&&!this.allInitsLoaded&&i&&i.status==="fed"&&!u.length&&this.getForwardBufferDuration(e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let l=(0,ii.default)(r,-1);!this.isLive&&l&&(this.fullyBuffered$.next(l.time.to-e-this.getForwardBufferDuration(e)<n),this.onLastSegment$.next(e-l.time.from>0))}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}searchGaps(e,t){this.gaps=[];let 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;ri(t.duration)&&t.duration-r>0&&!this.isLive&&this.gaps.push({representation:t.id,from:r,to:t.duration})}getActualLiveStartingSegments(e){let t=e.segments,r=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,i=[],s=0,n=t.length-1;do i.unshift(t[n]),s+=t[n].time.to-t[n].time.from,n--;while(s<r&&n>=0);return this.liveInitialAdditionalOffset=s-r,this.isActiveLowLatency()?[i[0]]:i}getLiveSegmentsToLoadState(e){let t=(0,yn.default)(e==null?void 0:e.streams[this.kind],i=>i.representations).find(i=>i.id===this.downloadingRepresentationId);if(!t)return;let r=this.segments.get(t.id);if(r!=null&&r.length)return{from:r[0].time.from,to:r[r.length-1].time.to}}updateLive(e){var r,i,s,n;let t=(r=(0,yn.default)(e==null?void 0:e.streams[this.kind],o=>o.representations))!=null?r:[];if(![...this.segments.values()].every(o=>!o.length))for(let o of t){if(!o||!xe(o.segmentReference))return;let u=o.segmentReference.segments.map(h=>M(P({},h),{status:"none",size:void 0})),l=100,c=(i=this.segments.get(o.id))!=null?i:[],d=(n=(s=(0,ii.default)(c,-1))==null?void 0:s.time.to)!=null?n:0,p=u==null?void 0:u.findIndex(h=>d>=h.time.from+l&&d<=h.time.to+l);if(p===-1){this.liveUpdateSegmentIndex=0;let h=this.getActualLiveStartingSegments(o.segmentReference);this.segments.set(o.id,h)}else{let h=u.slice(p+1);this.segments.set(o.id,[...c,...h])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;Me(e);let t=this.segments.get(e);if(t!=null&&t.length){let r=t[t.length-1];this.updateLowLatencyLiveIfNeeded(r)}}updateLowLatencyLiveIfNeeded(e){var r;let t=0;for(let i of this.representations.values()){let s=i.segmentReference;if(!xe(s))return;let n=(r=this.segments.get(i.id))!=null?r:[],o=n.find(l=>Math.floor(l.time.from)===Math.floor(e.time.from));if(o&&!isFinite(o.time.to)&&(o.time.to=e.time.to,t=o.time.to-o.time.from),!!!n.find(l=>Math.floor(l.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let l=Math.round(e.time.to*s.timescale/1e3).toString(10),c=vt(s.segmentTemplateUrl,{segmentTime:l});n.push({status:"none",time:{from:e.time.to,to:1/0},url:c})}}this.currentLowLatencySegmentLength$.next(t)}findSegmentStartTime(e){var s,n,o;let t=(n=(s=this.switchingToRepresentationId)!=null?s:this.downloadingRepresentationId)!=null?n:this.playingRepresentationId;if(!t)return;let r=this.segments.get(t);if(!r)return;let i=r.find(u=>u.time.from<=e&&u.time.to>=e);return(o=i==null?void 0:i.time.from)!=null?o:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){var e;if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),(e=this.sourceBufferTaskQueue)==null||e.destroy(),this.gapDetectionIdleCallback&&aa&&aa(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&aa&&aa(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer)try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(t){if(!(t instanceof DOMException&&t.name==="NotFoundError"))throw t}this.sourceBuffer=null,this.downloadAbortController.abort(),this.switchAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,r){return this.isLive?this.selectForwardBufferSegmentsLive(e,r):this.selectForwardBufferSegmentsRecord(e,t,r)}selectForwardBufferSegmentsLive(e,t){let r=e.findIndex(i=>t>=i.time.from&&t<i.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=r),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,r){let i=e.findIndex(({status:d,time:{from:p,to:h}},m)=>{let b=p<=r&&h>=r,g=p>r||b||m===0&&r===0,v=Math.min(this.forwardBufferTarget,this.bufferLimit),S=this.preloadOnly&&p<=r+v||h<=r+v;return(d==="none"||d==="partially_ejected"&&g&&S&&this.sourceBuffer&&oe(this.mediaSource,this.sourceBuffer)&&!(qt(this.sourceBuffer.buffered,p)&&qt(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,c=this.preloadOnly?this.forwardBufferTarget:0;for(let d=i;d<s.length&&(n<=l||o<=c);d++){let p=s[d];if(n+=p.byte.to+1-p.byte.from,o+=p.time.to+1-p.time.from,p.status==="none"||p.status==="partially_ejected")u.push(p);else break}return u}loadSegments(e,t,r="auto"){return E(this,null,function*(){xe(t.segmentReference)?yield this.loadTemplateSegment(e[0],t,r):yield this.loadByteRangeSegments(e,t,r)})}loadTemplateSegment(e,t,r="auto"){return E(this,null,function*(){e.status="downloading";let i={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(i);let{range:s,url:n,signal:o,onProgress:u,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(yield Ht(o,function(){return ue(this,null,function*(){let c=Xl(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(d=>setTimeout(d,c))})}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let c=yield this.fetcher.fetch(n,{range:s,signal:o,onProgress:u,priority:r,isLowLatency:this.isActiveLowLatency()});if(this.lastDataObtainedTimestampMs=vn(),!c)return;let d=new DataView(c),p=Ra(t.mime);if(!isFinite(i.segment.time.to)){let b=t.segmentReference.timescale;i.segment.time.to=p.getChunkEndTime(d,b)}u&&i.feedingBytes&&l?yield Promise.all(l):yield this.sourceBufferTaskQueue.append(d,o);let{serverDataReceivedTimestamp:h,serverDataPreparedTime:m}=p.getServerLatencyTimestamps(d);h&&m&&this.currentLiveSegmentServerLatency$.next(m-h),i.segment.status="downloaded",this.onSegmentFullyAppended(i,t.id),this.failedDownloads=0}catch(c){this.abortActiveSegments([e]),La(c)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}})}updateRepresentationsBaseUrlIfNeeded(){if(!this.tuning.dash.enableBaseUrlSupport||!this.baseUrls.length||this.failedDownloads<=this.tuning.dash.maxSegmentRetryCount)return;this.baseUrlsIndex=(this.baseUrlsIndex+1)%this.baseUrls.length;let e=this.baseUrls[this.baseUrlsIndex];for(let t of this.representations.values())xe(t.segmentReference)?t.segmentReference.baseUrl=e:t.segmentReference.url=e}loadByteRangeSegments(e,t,r="auto"){return E(this,null,function*(){if(!e.length)return;for(let u of e)u.status="downloading",this.activeSegments.add({segment:u,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:i,url:s,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(yield Ht(n,function(){return ue(this,null,function*(){let u=Xl(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),Kl(window,"online").pipe(ID()).subscribe(()=>{l(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{yield this.fetcher.fetch(s,{range:i,onProgress:o,signal:n,priority:r}),this.lastDataObtainedTimestampMs=vn(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),La(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}})}prepareByteRangeFetchSegmentParams(e,t){if(xe(t.segmentReference))throw new Error("Representation is not byte range type");let r=t.segmentReference.url,i={from:(0,ii.default)(e,0).byte.from,to:(0,ii.default)(e,-1).byte.to},{signal:s}=this.downloadAbortController;return{url:r,range:i,signal:s,onProgress:(o,u)=>E(this,null,function*(){if(!s.aborted)try{this.lastDataObtainedTimestampMs=vn(),yield this.onSomeByteRangesDataLoaded({dataView:o,loaded:u,signal:s,onSegmentAppendFailed:()=>this.abort(),globalFrom:i?i.from:0,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:St.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}})}}prepareTemplateFetchSegmentParams(e,t){if(!xe(t.segmentReference))throw new Error("Representation is not template type");let r=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&r.searchParams.set("low-latency","yes");let i=r.toString(),{signal:s}=this.downloadAbortController,n=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(l,c)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=vn();let d=this.onSomeTemplateDataLoaded({dataView:l,loaded:c,signal:s,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(d)}catch(d){this.error$.next({id:"SegmentFeeding",category:St.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:d})}}:void 0;return{url:i,signal:s,onProgress:u,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)(0,Sn.default)(e,t.segment)&&this.abortSegment(t.segment)}onSomeTemplateDataLoaded(n){return E(this,arguments,function*({dataView:e,representationId:t,loaded:r,onSegmentAppendFailed:i,signal:s}){if(!this.activeSegments.size||!oe(this.mediaSource,this.sourceBuffer))return;let o=this.representations.get(t);if(o)for(let u of this.activeSegments){let{segment:l}=u;if(u.representationId===t){if(s.aborted){i();continue}if(u.loadedBytes=r,u.loadedBytes>u.feedingBytes){let c=new DataView(e.buffer,e.byteOffset+u.feedingBytes,u.loadedBytes-u.feedingBytes),d=Ra(o.mime).parseFeedableSegmentChunk(c,this.isLive);d!=null&&d.byteLength&&(l.status="partially_fed",u.feedingBytes+=d.byteLength,yield this.sourceBufferTaskQueue.append(d),u.fedBytes+=d.byteLength)}}}})}onSomeByteRangesDataLoaded(o){return E(this,arguments,function*({dataView:e,representationId:t,globalFrom:r,loaded:i,signal:s,onSegmentAppendFailed:n}){if(!this.activeSegments.size||!oe(this.mediaSource,this.sourceBuffer))return;let u=this.representations.get(t);if(u)for(let l of this.activeSegments){let{segment:c}=l;if(l.representationId!==t)continue;if(s.aborted){yield n();continue}let d=c.byte.from-r,p=c.byte.to-r,h=p-d+1,m=d<i,b=p<=i;if(!m)continue;let g=Ra(u.mime);if(c.status==="downloading"&&b){c.status="downloaded";let v=new DataView(e.buffer,e.byteOffset+d,h);(yield this.sourceBufferTaskQueue.append(v,s))&&!s.aborted?this.onSegmentFullyAppended(l,t):yield n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(c.status==="downloading"||c.status==="partially_fed")&&(l.loadedBytes=Math.min(h,i-d),l.loadedBytes>l.feedingBytes)){let v=new DataView(e.buffer,e.byteOffset+d+l.feedingBytes,l.loadedBytes-l.feedingBytes),S=l.loadedBytes===h?v:g.parseFeedableSegmentChunk(v);S!=null&&S.byteLength&&(c.status="partially_fed",l.feedingBytes+=S.byteLength,(yield this.sourceBufferTaskQueue.append(S,s))&&!s.aborted?(l.fedBytes+=S.byteLength,l.fedBytes===h&&this.onSegmentFullyAppended(l,t)):yield n())}}})}onSegmentFullyAppended(e,t){var r;if(!(ve(this.sourceBuffer)||!oe(this.mediaSource,this.sourceBuffer))){!this.isLive&&H.browser.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(qt(this.sourceBuffer.buffered,e.segment.time.from,100)&&qt(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:St.VIDEO_PIPELINE,message:"Browser stuck on empty result of adding segment to source buffer"})),this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status="fed",Gl(e.segment)&&(e.segment.size=e.fedBytes);for(let i of this.representations.values())if(i.id!==t)for(let s of(r=this.segments.get(i.id))!=null?r:[])s.status==="fed"&&Math.round(s.time.from)===Math.round(e.segment.time.from)&&Math.round(s.time.to)===Math.round(e.segment.time.to)&&(s.status="none");this.updateLowLatencyLiveIfNeeded(e.segment),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment])}}abortSegment(e){e.status==="partially_fed"?e.status="partially_ejected":e.status!=="partially_ejected"&&(e.status="none");for(let t of this.activeSegments.values())if(t.segment===e){this.activeSegments.delete(t);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(let[i,s]of this.initData.entries()){let n=s instanceof Promise;t||(t=n),s===null&&(e=i)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let r=this.representations.get(e);r&&(this.initLoadIdleCallback=Ll(()=>(0,ky.default)(this.loadInit(r,"low",!1),()=>this.initLoadIdleCallback=null)))}loadInit(e,t="auto",r=!1){return E(this,null,function*(){let i=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!r&&this.failedDownloads>0?Ht(this.destroyAbortController.signal,function(){return ue(this,null,function*(){let o=Xl(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))})}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,Ra(e.mime),i)).then(o=>E(this,null,function*(){if(!o)return;let{init:u,dataView:l,segments:c}=o,d=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,d);let p=c;this.isLive&&xe(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:St.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n})}dropBuffer(){return E(this,null,function*(){for(let e of this.segments.values())for(let t of e)t.status="none";yield this.pruneBuffer(0,1/0,!0)})}pruneBuffer(e,t,r=!1){return E(this,null,function*(){if(!this.sourceBuffer||!oe(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||ve(e))return!1;let i=[],s=0,n=u=>{u.sort((c,d)=>c.from-d.from);let l=[u[0]];for(let c=1;c<u.length;c++){let{from:d,to:p}=u[c],h=l[l.length-1];h.to>=d?h.to=Math.max(h.to,p):l.push(u[c])}return l},o=u=>{var c;if(s>=t)return i;i.push(P({},u.time)),i=n(i);let l=Gl(u)?(c=u.size)!=null?c:0:u.byte.to-u.byte.from;s+=l};for(let u of this.segments.values())for(let l of u){let c=l.time.to<=e-this.tuning.dash.bufferPruningSafeZone,d=l.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(c||d)&&l.status==="fed"&&o(l)}for(let u=0;u<this.sourceBuffer.buffered.length;u++){let l=this.sourceBuffer.buffered.start(u)*1e3,c=this.sourceBuffer.buffered.end(u)*1e3,d=0;for(let p of this.segments.values())for(let h of p)(0,Sn.default)(["none","partially_ejected"],h.status)&&Math.round(h.time.from)<=Math.round(l)&&Math.round(h.time.to)>=Math.round(c)&&d++;if(d===this.segments.size){let p={time:{from:l,to:c},url:"",status:"none"};o(p)}}if(i.length&&r){let u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let l of this.segments.values())for(let c of l)c.time.from>=e+u&&c.status==="fed"&&o(c)}return i.length?(yield Promise.all(i.map(l=>this.sourceBufferTaskQueue.remove(l.from,l.to)))).reduce((l,c)=>l||c,!1):!1})}abortBuffer(){return E(this,null,function*(){if(!this.sourceBuffer||!oe(this.mediaSource,this.sourceBuffer))return!1;let e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;return this.sourceBufferTaskQueue.abort(t)})}getDebugBufferState(){if(!(!this.sourceBuffer||!oe(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}getForwardBufferDuration(e=this.getCurrentPosition()){return!this.sourceBuffer||!oe(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||ve(e)?0:Jr(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!(!this.sourceBuffer||!oe(this.mediaSource,this.sourceBuffer))){if(this.tuning.useRefactoredSearchGap)for(let r=0;r<this.sourceBuffer.buffered.length;r++)this.gaps=this.gaps.filter(i=>this.sourceBuffer&&(Math.round(i.from)<Math.round(this.sourceBuffer.buffered.start(r)*1e3)||Math.round(i.to)>Math.round(this.sourceBuffer.buffered.end(r)*1e3)));for(let r of t){let i={representation:e,from:r.time.from,to:r.time.to};for(let s=0;s<this.sourceBuffer.buffered.length;s++){let n=this.sourceBuffer.buffered.start(s)*1e3,o=this.sourceBuffer.buffered.end(s)*1e3;if(!(o<=r.time.from||n>=r.time.to)){if(n<=r.time.from&&o>=r.time.to){i=void 0;break}o>r.time.from&&o<r.time.to&&(i.from=o),n<r.time.to&&n>r.time.from&&(i.to=n)}}i&&i.to-i.from>1&&!this.gaps.some(s=>i&&s.from===i.from&&s.to===i.to)&&this.gaps.push(i)}}}detectGapsWhenIdle(e,t){if(!(this.gapDetectionIdleCallback||!this.sourceBuffer||!oe(this.mediaSource,this.sourceBuffer))){if(!this.tuning.useRefactoredSearchGap)for(let r=0;r<this.sourceBuffer.buffered.length;r++)this.gaps=this.gaps.filter(i=>this.sourceBuffer&&(Math.round(i.from)<Math.round(this.sourceBuffer.buffered.start(r)*1e3)||Math.round(i.to)>Math.round(this.sourceBuffer.buffered.end(r)*1e3)));this.gapDetectionIdleCallback=Ll(()=>{try{this.detectGaps(e,t)}catch(r){this.error$.next({id:"GapDetection",category:St.WTF,message:"detectGaps threw",thrown:r})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if(ve(this.sourceBuffer)||!oe(this.mediaSource,this.sourceBuffer)||ve(this.playingRepresentationId))return;let e=[];for(let r=0;r<this.sourceBuffer.buffered.length;r++){let i=Math.floor(this.sourceBuffer.buffered.start(r)*1e3),s=Math.ceil(this.sourceBuffer.buffered.end(r)*1e3);e.push({from:i,to:s})}let t=100;for(let r of this.segments.values())for(let i of r){let{status:s}=i;if(s!=="fed"&&s!=="partially_ejected")continue;let n=Math.floor(i.time.from),o=Math.ceil(i.time.to),u=e.some(c=>c.from-t<=n&&c.to+t>=o),l=e.filter(c=>n>=c.from&&n<c.to-t||o>c.from+t&&o<=c.to);u||(l.length===1?i.status="partially_ejected":this.gaps.some(c=>c.from===i.time.from||c.to===i.time.to)?i.status="partially_ejected":i.status="none")}}handleAsyncError(e,t){this.error$.next({id:t,category:St.VIDEO_PIPELINE,thrown:e,message:"Something went wrong"})}};var Da=a=>{let e=new URL(a);return e.searchParams.set("quic","1"),e.toString()};var $y=a=>{var s;let e=a.get("X-Delivery-Type"),t=a.get("X-Reused"),r=e===null?"http1":e!=null?e:void 0,i=t===null?void 0:(s={1:!0,0:!1}[t])!=null?s:void 0;return{type:r,reused:i}};import{abortable as Ca,assertNever as Ly,fromEvent as My,merge as PD,now as Va,Subscription as wD,Subject as Dy,ValueSubject as Jl,flattenObject as ai,ErrorCategory as Oa}from"@vkontakte/videoplayer-shared/es2015";var Ry=a=>{let e=new URL(a);return e.searchParams.set("enable-subtitles","yes"),e.toString()};var In=class{constructor({throughputEstimator:e,requestQuic:t,tracer:r,compatibilityMode:i=!1,useEnableSubtitlesParam:s=!1}){this.lastConnectionType$=new Jl(void 0);this.lastConnectionReused$=new Jl(void 0);this.lastRequestFirstBytes$=new Jl(void 0);this.recoverableError$=new Dy;this.error$=new Dy;this.abortAllController=new ge;this.subscription=new wD;this.fetchManifest=Ca(this.abortAllController.signal,function(e){return ue(this,null,function*(){let t=this.tracer.createComponentTracer("FetchManifest"),r=e;this.requestQuic&&(r=Da(r)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(r=Ry(r));let i=yield this.doFetch(r,{signal:this.abortAllController.signal}).catch(Tn);return i?(t.log("success",ai({url:r,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(i.headers),i.text()):(t.error("error",ai({url:r,message:"No data in request manifest"})),t.end(),null)})}.bind(this));this.fetch=Ca(this.abortAllController.signal,function(l){return ue(this,arguments,function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:r,onProgress:i,priority:s="auto",signal:n,measureThroughput:o=!0,isLowLatency:u=!1}={}){var R,z;let c=e,d=new Headers,p=this.tracer.createComponentTracer("Fetch");if(r)switch(t){case 0:{d.append("Range",`bytes=${r.from}-${r.to}`);break}case 1:{let q=new URL(c,location.href);q.searchParams.append("bytes",`${r.from}-${r.to}`),c=q.toString();break}default:Ly(t)}this.requestQuic&&(c=Da(c));let h=this.abortAllController.signal,m;if(n){let q=new ge;if(m=PD(My(this.abortAllController.signal,"abort"),My(n,"abort")).subscribe(()=>{try{q.abort()}catch(Z){Tn(Z)}}),this.abortAllController.signal.aborted||n.aborted)try{q.abort()}catch(Z){Tn(Z)}h=q.signal}let b=Va();p.log("startRequest",ai({url:c,priority:s,rangeMethod:t,range:r,isLowLatency:u,requestStartedAt:b}));let g=yield this.doFetch(c,{priority:s,headers:d,signal:h}),v=Va();if(!g)return p.error("error",{message:"No response in request"}),p.end(),m==null||m.unsubscribe(),null;if((R=this.throughputEstimator)==null||R.addRawRtt(v-b),!g.ok||!g.body){m==null||m.unsubscribe();let q=`Fetch error ${g.status}: ${g.statusText}`;return p.error("error",{message:q}),p.end(),Promise.reject(new Error(`Fetch error ${g.status}: ${g.statusText}`))}if(this.onHeadersReceived(g.headers),!i&&!o){m==null||m.unsubscribe();let q=Va(),Z={requestStartedAt:b,requestEndedAt:q,duration:q-b};return p.log("endRequest",ai(Z)),p.end(),g.arrayBuffer()}let[S,T]=g.body.tee(),I=S.getReader();o&&((z=this.throughputEstimator)==null||z.trackStream(T,u));let y=0,$=new Uint8Array(0),C=!1,L=q=>{m==null||m.unsubscribe(),C=!0,Tn(q)},O=Ca(h,function(k){return ue(this,arguments,function*({done:q,value:Z}){if(y===0&&this.lastRequestFirstBytes$.next(Va()-b),h.aborted){m==null||m.unsubscribe();return}if(!q&&Z){let D=new Uint8Array($.length+Z.length);D.set($),D.set(Z,$.length),$=D,y+=Z.byteLength,i==null||i(new DataView($.buffer),y),yield I==null?void 0:I.read().then(O,L)}})}.bind(this));yield I==null?void 0:I.read().then(O,L),m==null||m.unsubscribe();let Q=Va(),G={failed:C,requestStartedAt:b,requestEndedAt:Q,duration:Q-b};return C?(p.error("endRequest",ai(G)),p.end(),null):(p.log("endRequest",ai(G)),p.end(),$.buffer)})}.bind(this));this.fetchByteRangeRepresentation=Ca(this.abortAllController.signal,function(e,t,r){return ue(this,null,function*(){var v;if(e.type!=="byteRange")return null;let{from:i,to:s}=e.initRange,n=i,o=s,u=!1,l,c;e.indexRange&&(l=e.indexRange.from,c=e.indexRange.to,u=s+1===l,u&&(n=Math.min(l,i),o=Math.max(c,s))),n=Math.min(n,0);let d=yield this.fetch(e.url,{range:{from:n,to:o},priority:r,measureThroughput:!1});if(!d)return null;let p=new DataView(d,i-n,s-n+1);if(!t.validateData(p))throw new Error("Invalid media file");let h=t.parseInit(p),m=(v=e.indexRange)!=null?v:t.getIndexRange(h);if(!m)throw new ReferenceError("No way to load representation index");let b;if(u)b=new DataView(d,m.from-n,m.to-m.from+1);else{let S=yield this.fetch(e.url,{range:m,priority:r,measureThroughput:!1});if(!S)return null;b=new DataView(S)}let g=t.parseSegments(b,h,m);return{init:h,dataView:new DataView(d),segments:g}})}.bind(this));this.fetchTemplateRepresentation=Ca(this.abortAllController.signal,function(e,t){return ue(this,null,function*(){if(e.type!=="template")return null;let r=new URL(e.initUrl,e.baseUrl).toString(),i=yield this.fetch(r,{priority:t,measureThroughput:!1});return i?{init:null,segments:e.segments.map(n=>M(P({},n),{status:"none",size:void 0})),dataView:new DataView(i)}:null})}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=i,this.tracer=r.createComponentTracer("Fetcher"),this.useEnableSubtitlesParam=s}onHeadersReceived(e){let{type:t,reused:r}=$y(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(r)}fetchRepresentation(e,t,r="auto"){return E(this,null,function*(){var s,n;let{type:i}=e;switch(i){case"byteRange":return(s=yield this.fetchByteRangeRepresentation(e,t,r))!=null?s:null;case"template":return(n=yield this.fetchTemplateRepresentation(e,r))!=null?n:null;default:Ly(i)}})}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}doFetch(e,t){return E(this,null,function*(){let r=yield lt(e,t);if(r.ok)return r;let i=yield r.text(),s=parseInt(i);if(!isNaN(s))switch(s){case 1:this.recoverableError$.next({id:"VideoDataLinkExpiredError",message:"Video data links have expired",category:Oa.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:Oa.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:Oa.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:Oa.FATAL});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${s})`,category:Oa.FATAL})}})}},Tn=a=>{if(!La(a))throw a};var br=(a,e,t)=>t*e+(1-t)*a,Zl=(a,e)=>a.reduce((t,r)=>t+r,0)/e,Cy=(a,e,t,r)=>{let i=0,s=t,n=Zl(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 AD,ValueSubject as Vy}from"@vkontakte/videoplayer-shared/es2015";var jt=class{constructor(e){this.prevReported=void 0;this.pastMeasures=[];this.takenMeasures=0;this.measuresCursor=0;var r;this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new Vy(e.initial),this.debounced$=new Vy(e.initial);let t=(r=e.label)!=null?r:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new Ie(`raw_${t}`),this.smoothedSeries$=new Ie(`smoothed_${t}`),this.reportedSeries$=new Ie(`reported_${t}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,r=0;for(let o=0;o<this.pastMeasures.length;o++)this.pastMeasures[o]!==void 0&&(t+=at(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)&&(AD(this.prevReported)||Math.abs(this.smoothed-this.prevReported)/this.prevReported>=this.params.changeThreshold)&&(this.prevReported=this.smoothed,this.debounced$.next(this.smoothed),this.reportedSeries$.next(this.smoothed))}};var En=class extends jt{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=br(this.slow,e,this.params.emaAlphaSlow),this.fast=br(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var xn=class extends jt{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=Zl(this.pastMeasures,this.takenMeasures);this.emaSmoothed=br(this.emaSmoothed,e,this.params.emaAlpha);let r=Cy(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=r?this.emaSmoothed:t}};var Pn=class extends jt{constructor(t){super(t);this.furtherValues=[];this.currentTopExtremumValue=0;this.extremumInterval=t.extremumInterval}next(t){this.currentTopExtremumValue<=t?(this.currentTopExtremumValue=t,this.furtherValues=[]):this.furtherValues.length===this.extremumInterval?(super.next(this.currentTopExtremumValue),this.currentTopExtremumValue=t,this.furtherValues=[]):this.furtherValues.push(t)}updateSmoothedValue(t){this.smoothed=this.smoothed?br(this.smoothed,t,this.params.emaAlpha):t}};var gr=class{static getSmoothedValue(e,t,r){return r.type==="TwoEma"?new En({initial:e,emaAlphaSlow:r.emaAlphaSlow,emaAlphaFast:r.emaAlphaFast,changeThreshold:r.changeThreshold,fastDirection:t,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"}):new xn({initial:e,emaAlpha:r.emaAlpha,basisTrendChangeCount:r.basisTrendChangeCount,changeThreshold:r.changeThreshold,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"})}static getLiveBufferSmoothedValue(e,t){return new Pn(P({initial:e,label:"liveEdgeDelay"},t))}};var ec=(a,e)=>{a&&a.playbackRate!==e&&(a.playbackRate=e)};import{isNullable as kD,ValueSubject as $D}from"@vkontakte/videoplayer-shared/es2015";var _a=class a{constructor(e,t){this.currentRepresentation$=new $D(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(!kD(e))for(let r of this.representations)for(let i of r){let s=i.segmentReference,n=s.segments.length,o=s.segments[0].time.from,u=s.segments[n-1].time.to;if(e<o||e>u)continue;let l=s.segments.find(c=>c.time.from<=e&&c.time.to>=e);!l||((t=this.currentSegment)==null?void 0:t.time.from)===l.time.from&&this.currentSegment.time.to===l.time.to||(this.currentSegment=l,this.currentRepresentation$.next(M(P({},i),{label:"Live Text",language:"ru",isAuto:!0,url:new URL(l.url,s.baseUrl).toString()})))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e!=null?e:[]){let r=a.filterRepresentations(t.representations);if(r){this.representations[this.representationsCursor]=r,this.representationsCursor=(this.representationsCursor+1)%this.maxRepresentations;break}}}static isSupported(e){return!!(e!=null&&e.some(t=>a.filterRepresentations(t.representations)))}static filterRepresentations(e){return e==null?void 0:e.filter(t=>t.kind==="text"&&"segmentReference"in t&&xe(t.segmentReference))}};var An=B(Bt(),1);import{assertNever as kn}from"@vkontakte/videoplayer-shared/es2015";var Oy=(a,{useHlsJs:e,useManagedMediaSource:t,useOldMSEDetection:r})=>{let{containers:i,protocols:s,codecs:n,nativeHlsSupported:o}=H.video,u=(n.h264||n.h265)&&n.aac,l=s.mse&&(!r||!!window.MediaStreamTrack)||s.mms&&t;return a.filter(c=>{switch(c){case"DASH_SEP":return l&&i.mp4&&u;case"DASH_WEBM":return l&&i.webm&&n.vp9&&n.opus;case"DASH_WEBM_AV1":return l&&i.webm&&n.av1&&n.opus;case"DASH_STREAMS":return l&&(i.mp4&&u||i.webm&&(n.vp9||n.av1)&&(n.opus||n.aac));case"DASH_LIVE":return l&&i.mp4&&u;case"DASH_LIVE_CMAF":return l&&i.mp4&&u&&i.cmaf;case"DASH_ONDEMAND":return l&&i.mp4&&u;case"HLS":case"HLS_ONDEMAND":return o||e&&l&&i.mp4&&u;case"HLS_LIVE":case"HLS_LIVE_CMAF":return o;case"MPEG":return i.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return s.webrtc&&s.ws&&n.h264&&(i.mp4||i.webm);default:return kn(c)}})},wn=a=>{let{webmDecodingInfo:e}=H.video,t="DASH_WEBM",r="DASH_WEBM_AV1";switch(a){case"vp9":return[t,r];case"av1":return[r,t];case"none":return[];case"smooth":return e?e[r].smooth?[r,t]:e[t].smooth?[t,r]:[r,t]:[t,r];case"power_efficient":return e?e[r].powerEfficient?[r,t]:e[t].powerEfficient?[t,r]:[r,t]:[t,r];default:kn(a)}return[t,r]},_y=({webmCodec:a,androidPreferredFormat:e,preferMultiStream:t})=>{let r=[...t?["DASH_STREAMS"]:[],...wn(a),"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]],i=[...t?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]];if(H.device.isAndroid)switch(e){case"mpeg":return["MPEG",...r,"HLS","HLS_ONDEMAND"];case"hls":return["HLS","HLS_ONDEMAND",...r,"MPEG"];case"dash":return[...r,"HLS","HLS_ONDEMAND","MPEG"];case"dash_any_mpeg":return[...i,"MPEG",...wn(a),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...wn(a),"MPEG",...i,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...wn(a),...i,"HLS","HLS_ONDEMAND"];default:kn(e)}return H.video.nativeHlsSupported?[...r,"HLS","HLS_ONDEMAND","MPEG"]:[...r,"HLS","HLS_ONDEMAND","MPEG"]},By=({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=H.device.isMac&&H.browser.isSafari;if(H.device.isAndroid)switch(a){case"dash":case"dash_any_mpeg":case"dash_any_webm":case"dash_sep":{o=s;break}case"hls":case"mpeg":{o=n;break}default:kn(a)}else H.video.nativeHlsSupported&&!u?o=n:u?o=e?["DASH_LIVE_CMAF","HLS_LIVE_CMAF","HLS_LIVE","DASH_LIVE"]:["HLS_LIVE","DASH_LIVE","DASH_LIVE_CMAF","HLS_LIVE_CMAF"]:o=s;return t?["WEB_RTC_LIVE",...o]:[...o,"WEB_RTC_LIVE"]},tc=a=>a?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],Ny=a=>{if(a.size===0)return;if(a.size===1){let t=a.values().next();return(0,An.default)(t.value.split("."),0)}for(let t of a){let r=(0,An.default)(t.split("."),0);if(r==="opus"||r==="vp09"||r==="av01")return r}let e=a.values().next();return(0,An.default)(e.value.split("."),0)};var BD=["timeupdate","progress","play","seeked","stalled","waiting"],ND=["timeupdate","progress","loadeddata","playing","seeked"];var Ln=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 N("none");this.currentVideoRepresentation$=new ie(void 0);this.currentVideoRepresentationInit$=new ie(void 0);this.currentAudioRepresentation$=new ie(void 0);this.currentVideoSegmentLength$=new ie(0);this.currentAudioSegmentLength$=new ie(0);this.error$=new Rn;this.lastConnectionType$=new ie(void 0);this.lastConnectionReused$=new ie(void 0);this.lastRequestFirstBytes$=new ie(void 0);this.currentLiveTextRepresentation$=new ie(null);this.isLive$=new ie(!1);this.isActiveLive$=new ie(!1);this.isLowLatency$=new ie(!1);this.liveDuration$=new ie(0);this.liveSeekableDuration$=new ie(0);this.liveAvailabilityStartTime$=new ie(0);this.liveStreamStatus$=new ie(void 0);this.bufferLength$=new ie(0);this.liveLatency$=new ie(void 0);this.liveLoadBufferLength$=new ie(0);this.livePositionFromPlayer$=new ie(0);this.currentStallDuration$=new ie(0);this.videoLastDataObtainedTimestamp$=new ie(0);this.fetcherRecoverableError$=new Rn;this.fetcherError$=new Rn;this.liveStreamEndTimestamp=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.forceEnded$=new Rn;this.gapWatchdogActive=!1;this.destroyController=new ge;this.initManifest=ic(this.destroyController.signal,function(e,t,r){return ue(this,null,function*(){var i;this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=be(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:ct.PARSER,message:"No playable video representations"})})}.bind(this));this.updateManifest=ic(this.destroyController.signal,function(){return ue(this,null,function*(){var n,o;this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(u=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:ct.NETWORK,message:"Failed to load manifest",thrown:u})});if(!e)return null;let t=null;try{t=Py(e!=null?e:"",this.manifestUrlString)}catch(u){let l=(n=gS(e))!=null?n:{id:"ManifestParsing",category:ct.PARSER,message:"Failed to parse MPD manifest",thrown:u};this.error$.next(l)}if(!t)return null;let r=(u,l,c)=>{var d,p,h,m;return!!((p=(d=this.element)==null?void 0:d.canPlayType)!=null&&p.call(d,l)&&((m=(h=Ze())==null?void 0:h.isTypeSupported)!=null&&m.call(h,`${l}; codecs="${c}"`))||u==="text")};if(t.live){this.isLive$.next(!!t.live);let{availabilityStartTime:u,latestSegmentPublishTime:l,streamIsUnpublished:c,streamIsAlive:d}=t.live,p=((o=t.duration)!=null?o:0)/1e3;this.liveSeekableDuration$.next(-1*p),this.liveDuration$.next((l-u)/1e3),this.liveAvailabilityStartTime$.next(t.live.availabilityStartTime);let h="active";d||(h=c?"unpublished":"unexpectedly_down"),this.liveStreamStatus$.next(h)}let i={text:t.streams.text,video:[],audio:[]};for(let u of["video","audio"]){let c=t.streams[u].filter(({mime:h,codecs:m})=>r(u,h,m)),d=new Set(c.map(({codecs:h})=>h)),p=Ny(d);if(p&&(i[u]=c.filter(({codecs:h})=>h.startsWith(p))),u==="video"){let h=this.tuning.preferHDR,m=i.video.some(g=>g.hdr),b=i.video.some(g=>!g.hdr);H.display.isHDR&&h&&m?i.video=i.video.filter(g=>g.hdr):b&&(i.video=i.video.filter(g=>!g.hdr))}}let s=M(P({},t),{streams:i});return this.tracer.log("updateManifestEnd",Na(s)),s})}.bind(this));this.initRepresentations=ic(this.destroyController.signal,function(e,t,r){return ue(this,null,function*(){var p;this.tracer.log("initRepresentationsStart",Na({initialVideo:e,initialAudio:t,sourceHls:r})),si(this.manifest),si(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let i=h=>{this.representationSubscription.add(yt(h,"error").pipe($n(m=>{var b;return!!((b=this.element)!=null&&b.played.length)})).subscribe(m=>{this.error$.next({id:"VideoSource",category:ct.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:m})}))};this.source=this.tuning.useManagedMediaSource?Bg():new MediaSource;let s=document.createElement("source");if(i(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),this.tuning.useManagedMediaSource&&an())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.isActiveLive$.next(this.isLive$.getValue());let n={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),manifest:this.manifest},o=this.manifest.streams.video.reduce((h,m)=>[...h,...m.representations],[]);if(this.videoBufferManager=new Ma("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],Fa(t)){let h=this.manifest.streams.audio.reduce((m,b)=>[...m,...b.representations],[]);this.audioBufferManager=new Ma("audio",this.source,h,n),this.bufferManagers.push(this.audioBufferManager)}_a.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new _a(this.manifest.streams.text,n)),this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$));let u=()=>{var h;(h=this.stallWatchdogSubscription)==null||h.unsubscribe(),this.currentStallDuration$.next(0)};if(this.representationSubscription.add(vr(...ND.map(h=>yt(this.element,h))).pipe(oi(h=>this.element?Jr(this.element.buffered,this.element.currentTime*1e3):0),Ba(),OD(h=>{h>this.tuning.dash.bufferEmptinessTolerance&&u()})).subscribe(this.bufferLength$)),this.representationSubscription.add(vr(yt(this.element,"ended"),this.forceEnded$).subscribe(()=>{u()})),this.isLive$.getValue()){this.subscription.add(this.liveDuration$.pipe(Ba()).subscribe(m=>this.liveStreamEndTimestamp=sc())),this.subscription.add(yt(this.element,"pause").subscribe(()=>{this.livePauseWatchdogSubscription=ac(1e3).subscribe(m=>{let b=Xs(this.manifestUrlString,2);this.manifestUrlString=be(this.manifestUrlString,b+1e3,2),this.liveStreamStatus$.getValue()==="active"&&this.updateManifest()})})).add(yt(this.element,"play").subscribe(m=>{var b;return(b=this.livePauseWatchdogSubscription)==null?void 0:b.unsubscribe()})),this.representationSubscription.add(ni({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(oi(({isActiveLive:m,isLowLatency:b})=>m&&b),Ba()).subscribe(m=>{this.isManualDecreasePlaybackInLive()||ec(this.element,1)})),this.representationSubscription.add(ni({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe($n(({bufferLength:m,isActiveLive:b,isLowLatency:g})=>b&&g&&!!m)).subscribe(({bufferLength:m})=>this.liveBuffer.next(m))),this.representationSubscription.add(this.videoBufferManager.currentLowLatencySegmentLength$.subscribe(m=>{if(!this.isActiveLive$.getValue()&&!this.isLowLatency$.getValue()&&!m)return;let b=this.liveSeekableDuration$.getValue()-m/1e3;this.liveSeekableDuration$.next(Math.max(b,-1*this.tuning.dashCmafLive.maxLiveDuration)),this.liveDuration$.next(this.liveDuration$.getValue()+m/1e3)})),this.representationSubscription.add(ni({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe($n(({isLive:m})=>m),Ba((m,b)=>b.bufferLength<m.bufferLength),oi(({rtt:m,bufferLength:b,segmentServerLatency:g})=>{let v=Xs(this.manifestUrlString,2);return(m/2+b+g+v)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add(ni({liveBuffer:this.liveBuffer.smoothed$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).subscribe(({liveBuffer:m,isActiveLive:b,isLowLatency:g})=>{if(!g||!b)return;let v=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,S=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,T=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,I=m-v;if(this.isManualDecreasePlaybackInLive())return;let y=1;Math.abs(I)>S&&(y=1+Math.sign(I)*T),ec(this.element,y)})),this.representationSubscription.add(this.bufferLength$.subscribe(m=>{var g,v;let b=0;if(m){let S=((v=(g=this.element)==null?void 0:g.currentTime)!=null?v:0)*1e3;b=Math.min(...this.bufferManagers.map(I=>{var y,$;return($=(y=I.getLiveSegmentsToLoadState(this.manifest))==null?void 0:y.to)!=null?$:S}))-S}this.liveLoadBufferLength$.getValue()!==b&&this.liveLoadBufferLength$.next(b)}));let h=0;this.representationSubscription.add(ni({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(_D(1e3)).subscribe(g=>E(this,[g],function*({liveLoadBufferLength:m,bufferLength:b}){if(!this.element||this.isUpdatingLive)return;let v=this.element.playbackRate,S=Xs(this.manifestUrlString,2),T=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,I=Math.min(T,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*v),y=this.tuning.dashCmafLive.normalizedActualBufferOffset*v,$=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*v,C=isFinite(m)?m:b,L=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),O=T<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next(O);let Q="none";if(L?Q="active_low_latency":this.isLowLatency$.getValue()&&O?(this.bufferManagers.forEach(G=>G.proceedLowLatencyLive()),Q="active_low_latency"):S!==0&&C<I?Q="live_forward_buffering":C<I+$&&(Q="live_with_target_offset"),isFinite(m)&&(h=m>h?m:h),Q==="live_forward_buffering"||Q==="live_with_target_offset"){let G=h-(I+y),R=this.normolizeLiveOffset(Math.trunc(S+G/v)),z=Math.abs(R-S),q=0;!m||z<=this.tuning.dashCmafLive.offsetCalculationError?q=S:R>0&&z>this.tuning.dashCmafLive.offsetCalculationError&&(q=R),this.manifestUrlString=be(this.manifestUrlString,q,2)}(Q==="live_with_target_offset"||Q==="live_forward_buffering")&&(h=0,yield this.updateLive())}),m=>{this.error$.next({id:"updateLive",category:ct.VIDEO_PIPELINE,thrown:m,message:"Failed to update live with subscription"})}))}let l=vr(...this.bufferManagers.map(h=>h.fullyBuffered$)).pipe(oi(()=>this.bufferManagers.every(h=>h.fullyBuffered$.getValue()))),c=vr(...this.bufferManagers.map(h=>h.onLastSegment$)).pipe(oi(()=>this.bufferManagers.some(h=>h.onLastSegment$.getValue()))),d=ni({allBuffersFull:l,someBufferEnded:c}).pipe(Ba(),oi(({allBuffersFull:h,someBufferEnded:m})=>h&&m),$n(h=>h));if(this.representationSubscription.add(vr(this.forceEnded$,d).subscribe(()=>{var h;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(m=>!m.updating))try{(h=this.source)==null||h.endOfStream()}catch(m){this.error$.next({id:"EndOfStream",category:ct.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:m})}})),this.representationSubscription.add(vr(...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"){let h=this.tuning.dash.sourceOpenTimeout>=0;yield new Promise((m,b)=>{var g;h&&(this.timeoutSourceOpenId=setTimeout(()=>{var v;if(((v=this.source)==null?void 0:v.readyState)==="open"){m();return}this.tuning.dash.rejectOnSourceOpenTimeout?b(new Error("Timeout reject when wait sourceopen event")):m()},this.tuning.dash.sourceOpenTimeout)),(g=this.source)==null||g.addEventListener("sourceopen",()=>{this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),m()},{once:!0})})}if(!this.isLive$.getValue()){let h=[(p=this.manifest.duration)!=null?p:0,...(0,nc.default)((0,nc.default)([...this.manifest.streams.audio,...this.manifest.streams.video],m=>m.representations),m=>{let b=[];return m.duration&&b.push(m.duration),xe(m.segmentReference)&&m.segmentReference.totalSegmentsDurationMs&&b.push(m.segmentReference.totalSegmentsDurationMs),b})];this.source.duration=Math.max(...h)/1e3}this.audioBufferManager&&Fa(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState("representations_ready"),this.tracer.log("initRepresentationsEnd")})}.bind(this));this.tick=()=>{var t,r,i,s;if(!this.element||!this.videoBufferManager||((t=this.source)==null?void 0:t.readyState)!=="open")return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),(r=this.audioBufferManager)==null||r.maintain(e),(i=this.liveTextManager)==null||i.maintain(e),(this.videoBufferManager.gaps.length||(s=this.audioBufferManager)!=null&&s.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=ac(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),n=>{this.error$.next({id:"GapWatchdog",category:ct.WTF,message:"Error handling gaps",thrown:n})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name),this.fetcher=new In({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer,useEnableSubtitlesParam:e.tuning.useEnableSubtitlesParam}),this.subscription.add(this.fetcher.recoverableError$.subscribe(this.fetcherRecoverableError$)),this.subscription.add(this.fetcher.error$.subscribe(this.fetcherError$)),this.liveBuffer=gr.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,P({},e.tuning.dashCmafLive.lowLatency.bufferEstimator)),this.initTracerSubscription()}seekLive(e){return E(this,null,function*(){var i,s,n;si(this.element);let t=this.liveStreamStatus$.getValue()!=="active"?sc()-this.liveStreamEndTimestamp:0,r=this.normolizeLiveOffset(e+t);this.isActiveLive$.next(r===0),this.manifestUrlString=be(this.manifestUrlString,r,2),this.manifest=yield this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,yield(i=this.videoBufferManager)==null?void 0:i.seekLive(this.manifest.streams.video),yield(s=this.audioBufferManager)==null?void 0:s.seekLive(this.manifest.streams.audio),(n=this.liveTextManager)==null||n.seekLive(this.manifest.streams.text))})}initBuffer(){si(this.element),this.state$.setState("running"),this.subscription.add(vr(...BD.map(e=>yt(this.element,e)),yt(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:ct.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(yt(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(yt(this.element,"waiting").subscribe(()=>{var t;this.element&&this.element.readyState===2&&!this.element.seeking&&qt(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{var h,m,b,g,v,S,T,I,y,$,C;if(!this.element||((h=this.source)==null?void 0:h.readyState)!=="open")return;let r=this.currentStallDuration$.getValue();r+=50,this.currentStallDuration$.next(r);let i={timeInWaiting:r},s=sc(),n=100,o=(b=(m=this.videoBufferManager)==null?void 0:m.lastDataObtainedTimestamp)!=null?b:0;this.videoLastDataObtainedTimestamp$.next(o);let u=(v=(g=this.audioBufferManager)==null?void 0:g.lastDataObtainedTimestamp)!=null?v:0,l=(T=(S=this.videoBufferManager)==null?void 0:S.getForwardBufferDuration())!=null?T:0,c=(y=(I=this.audioBufferManager)==null?void 0:I.getForwardBufferDuration())!=null?y:0,d=l<n&&s-o>this.tuning.dash.crashOnStallTWithoutDataTimeout,p=this.audioBufferManager&&c<n&&s-u>this.tuning.dash.crashOnStallTWithoutDataTimeout;if((d||p)&&r>this.tuning.dash.crashOnStallTWithoutDataTimeout||r>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${r} ms`);if(this.isLive$.getValue()&&r%2e3===0){let L=this.normolizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);this.seekLive(L).catch(O=>{this.error$.next({id:"stallIntervalCallback",category:ct.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:O})}),i.liveLastOffset=L}else{let L=this.element.currentTime*1e3;($=this.videoBufferManager)==null||$.maintain(L),(C=this.audioBufferManager)==null||C.maintain(L),i.position=L}this.tracer.log("stallIntervalCallback",Na(i))};(t=this.stallWatchdogSubscription)==null||t.unsubscribe(),this.stallWatchdogSubscription=ac(50).subscribe(e,r=>{this.error$.next({id:"StallWatchdogCallback",category:ct.NETWORK,message:"Can't restore DASH after stall.",thrown:r})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}switchRepresentation(e,t,r=!1){return E(this,null,function*(){let i={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return this.tuning.useNewSwitchTo?this.currentStallDuration$.getValue()>0?i==null?void 0:i.switchToWithPreviousAbort(t,r):i==null?void 0:i.switchTo(t,r):i==null?void 0:i.switchToOld(t,r)})}seek(e,t){return E(this,null,function*(){var i,s,n,o,u;si(this.element),si(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),this.warmUpMediaSourceIfNeeded(r),qt(this.element.buffered,r)||(yield Promise.all([this.videoBufferManager.abort(),(o=this.audioBufferManager)==null?void 0:o.abort()])),!(qy(this.element)||qy(this.videoBufferManager))&&(this.videoBufferManager.maintain(r),(u=this.audioBufferManager)==null||u.maintain(r),this.element.currentTime=r/1e3,this.tracer.log("seek",Na({requestedPosition:e,forcePrecise:t,position:r})))})}warmUpMediaSourceIfNeeded(e=(t=>(t=this.element)==null?void 0:t.currentTime)()){var r;Fa(this.element)&&Fa(this.source)&&Fa(e)&&((r=this.source)==null?void 0:r.readyState)==="ended"&&this.element.duration*1e3-e>this.tuning.dash.seekBiasInTheEnd&&this.bufferManagers.forEach(i=>i.warmUpMediaSource())}get isStreamEnded(){var e;return((e=this.source)==null?void 0:e.readyState)==="ended"}stop(){var e,t,r;this.tracer.log("stop"),(e=this.element)==null||e.querySelectorAll("source").forEach(i=>{URL.revokeObjectURL(i.src),i.remove()}),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),(t=this.videoBufferManager)==null||t.destroy(),this.videoBufferManager=null,(r=this.audioBufferManager)==null||r.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getStreams(){var e;return(e=this.manifest)==null?void 0:e.streams}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){var e;this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),((e=this.source)==null?void 0:e.readyState)==="open"&&Array.from(this.source.sourceBuffers).every(t=>!t.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}initTracerSubscription(){let e=VD(this.tracer.error.bind(this.tracer));this.error$.subscribe(e("error"))}isManualDecreasePlaybackInLive(){return!this.element||!this.isLive$.getValue()?!1:1-this.element.playbackRate>this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}updateLive(){return E(this,null,function*(){var e,t;this.isUpdatingLive=!0,this.manifest=yield this.updateManifest(),this.manifest&&((e=this.bufferManagers)==null||e.forEach(r=>r.updateLive(this.manifest)),(t=this.liveTextManager)==null||t.updateLive(this.manifest)),this.isUpdatingLive=!1})}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.getDebugBufferState();if(!e)return;let t=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),r={isJumpGapAfterSeekLive:this.isJumpGapAfterSeekLive,isActiveLowLatency:t,initialCurrentTime:this.element.currentTime};this.isJumpGapAfterSeekLive&&!t&&this.element.currentTime>e.to&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let i=this.element.currentTime*1e3,s=[],n=this.element.readyState===1?this.tuning.endGapTolerance:0;for(let o of this.bufferManagers)for(let u of o.gaps)o.playingRepresentation$.getValue()===u.representation&&u.from-n<=i&&u.to+n>i&&(this.element.duration*1e3-u.to<this.tuning.endGapTolerance?s.push(1/0):s.push(u.to));if(s.length){let o=Math.max(...s)+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,o===1/0?this.forceEnded$.next():(this.element.currentTime=o/1e3,r=M(P({},r),{gapEnds:s,jumpTo:o,resultCurrentTime:this.element.currentTime}),this.tracer.log("jumpGap",Na(r)))}}};var Mn=class{constructor(e,t){this.fov=e,this.orientation=t}};var Dn=class{constructor(e,t){this.rotating=!1;this.fading=!1;this.lastTickTS=0;this.lastCameraTurnTS=0;this.fadeStartSpeed=null;this.fadeTime=0;this.camera=e,this.options=t,this.rotationSpeed={x:0,y:0,z:0},this.fadeCorrection=1/at(this.options.speedFadeTime/1e3,2)}turnCamera(e=0,t=0,r=0){this.pointCameraTo(this.camera.orientation.x+e,this.camera.orientation.y+t,this.camera.orientation.z+r)}pointCameraTo(e=0,t=0,r=0){t=this.limitCameraRotationY(t);let i=e-this.camera.orientation.x,s=t-this.camera.orientation.y,n=r-this.camera.orientation.z;this.camera.orientation.x=e,this.camera.orientation.y=t,this.camera.orientation.z=r,this.lastCameraTurn={x:i,y:s,z:n},this.lastCameraTurnTS=Date.now()}setRotationSpeed(e,t,r){this.rotationSpeed.x=e!=null?e:this.rotationSpeed.x,this.rotationSpeed.y=t!=null?t:this.rotationSpeed.y,this.rotationSpeed.z=r!=null?r:this.rotationSpeed.z}startRotation(){this.rotating=!0}stopRotation(e=!1){e?(this.setRotationSpeed(0,0,0),this.fadeStartSpeed=null):this.startFading(this.rotationSpeed.x,this.rotationSpeed.y,this.rotationSpeed.z),this.rotating=!1}onCameraRelease(){if(this.lastCameraTurn&&this.lastCameraTurnTS){let e=Date.now()-this.lastCameraTurnTS;if(e<this.options.speedFadeThreshold){let t=(1-e/this.options.speedFadeThreshold)*this.options.rotationSpeedCorrection;this.startFading(this.lastCameraTurn.x*t,this.lastCameraTurn.y*t,this.lastCameraTurn.z*t)}}}startFading(e,t,r){this.setRotationSpeed(e,t,r),this.fadeStartSpeed=P({},this.rotationSpeed),this.fading=!0}stopFading(){this.fadeStartSpeed=null,this.fading=!0,this.fadeTime=0}limitCameraRotationY(e){return Math.max(-this.options.maxYawAngle,Math.min(e,this.options.maxYawAngle))}tick(e){if(!this.lastTickTS){this.lastTickTS=e,this.lastCameraTurnTS=Date.now();return}let t=e-this.lastTickTS,r=t/1e3;if(this.rotating)this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*r,this.rotationSpeed.y*this.options.rotationSpeedCorrection*r,this.rotationSpeed.z*this.options.rotationSpeedCorrection*r);else if(this.fading&&this.fadeStartSpeed){let i=-this.fadeCorrection*at(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 Hy=`attribute vec2 a_vertex;
|
|
71
71
|
attribute vec2 a_texel;
|
|
72
72
|
|
|
73
73
|
varying vec2 v_texel;
|
|
@@ -121,6 +121,6 @@ void main(void) {
|
|
|
121
121
|
// sample using new coordinates
|
|
122
122
|
gl_FragColor = texture2D(u_texture, tc);
|
|
123
123
|
}
|
|
124
|
-
`;var Mn=class{constructor(e,t,r){this.videoInitialized=!1;this.active=!1;this.container=e,this.sourceVideoElement=t,this.params=r,this.canvas=this.createCanvas();let i=this.canvas.getContext("webgl");if(!i)throw new Error("Could not initialize WebGL context");this.gl=i,this.container.appendChild(this.canvas),this.camera=new Ln(this.params.fov,this.params.orientation),this.cameraRotationManager=new $n(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(Hy,this.gl.VERTEX_SHADER),r=this.createShader(jy,this.gl.FRAGMENT_SHADER);if(this.gl.attachShader(e,t),this.gl.attachShader(e,r),this.gl.linkProgram(e),!this.gl.getProgramParameter(e,this.gl.LINK_STATUS))throw this.destroy(),new Error("Could not link shader program.");return e}createTexture(){let e=this.gl.createTexture();if(!e)throw this.destroy(),new Error("Could not create texture");return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.bindTexture(this.gl.TEXTURE_2D,null),e}updateTexture(){this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,!0),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.sourceVideoElement),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}createVertexBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create vertex buffer");let t=1,r=1,i=this.frameHeight/(this.frameWidth/this.viewportWidth);return i>this.viewportHeight?t=this.viewportHeight/i:r=i/this.viewportHeight,this.gl.bindBuffer(this.gl.ARRAY_BUFFER,e),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-t,-r,t,-r,t,r,-t,r]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),e}createTextureMappingBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create texture mapping buffer");return e}calculateTexturePosition(){let e=.5-this.camera.orientation.x/360,t=.5-this.camera.orientation.y/180,r=this.camera.fov.x/360/2,i=this.camera.fov.y/180/2,s=e-r,n=t-i,o=e+r,u=t-i,l=e+r,c=t+i,d=e-r,p=t+i;return[s,n,o,u,l,c,d,p]}updateTextureMappingBuffer(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([...this.calculateTexturePosition()]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}updateFrameSize(){this.frameWidth=this.sourceVideoElement.videoWidth,this.frameHeight=this.sourceVideoElement.videoHeight}createCanvas(){let e=document.createElement("canvas");return e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e}};import{isNullable as qC,now as Qy,Subscription as UC,filter as HC,combine as Gy,ValueSubject as ic,isNonNullable as jC}from"@vkontakte/videoplayer-shared/es2015";var ac=class{constructor(){this.isSeeked$=new ic(!1);this.isBuffering$=new ic(!1);this.currentStallsCount=0;this.maxQualityLimit=void 0;this.lastUniqueVideoTrackSelectedTimestamp=0;this.predictedThroughputWithoutData=0;this.subscription=new UC;this.severeStallOccurred$=new ic(!1)}connect(e){this.currentStallDuration$=e.currentStallDuration$,this.videoLastDataObtainedTimestamp$=e.videoLastDataObtainedTimestamp$,this.throughput$=e.throughput$,this.rtt$=e.rtt$,this.qualityLimitsOnStall=e.qualityLimitsOnStall,this.subscription.add(e.isSeeked$.subscribe(this.isSeeked$)),this.subscription.add(e.isBuffering$.subscribe(this.isBuffering$)),this.subscription.add(Gy({isBuffering:this.isBuffering$,isSeeked:this.isSeeked$}).pipe(HC(({isBuffering:t,isSeeked:r})=>t&&!r)).subscribe(()=>{this.currentStallsCount++})),this.subscription.add(Gy({currentStallDuration:this.currentStallDuration$}).subscribe(({currentStallDuration:t})=>{if(qC(this.lastUniqueVideoTrackSelected))return;let{stallDurationNoDataBeforeQualityDecrease:r,stallCountBeforeQualityDecrease:i,resetQualityRestrictionTimeout:s}=this.qualityLimitsOnStall,n=this.rtt$.getValue(),o=this.throughput$.getValue(),u=this.videoLastDataObtainedTimestamp$.getValue(),l=Qy(),c=i&&this.currentStallsCount>=i,d=r&&l-this.lastUniqueVideoTrackSelectedTimestamp>=r+n&&l-u>=r+n&&t>=r;(c||d)&&(this.severeStallOccurred$.next(!0),window.clearTimeout(this.qualityRestrictionTimer),this.maxQualityLimit=this.lastUniqueVideoTrackSelected.quality,jC(this.lastUniqueVideoTrackSelected.bitrate)&&o>this.lastUniqueVideoTrackSelected.bitrate&&(this.predictedThroughputWithoutData=this.lastUniqueVideoTrackSelected.bitrate)),t||(this.severeStallOccurred$.next(!1),window.clearTimeout(this.qualityRestrictionTimer),this.qualityRestrictionTimer=window.setTimeout(()=>{this.maxQualityLimit=void 0,this.predictedThroughputWithoutData=0},s))}))}get videoMaxQualityLimit(){return this.maxQualityLimit}get predictedThroughput(){return this.predictedThroughputWithoutData}set lastVideoTrackSelected(e){var t;((t=this.lastUniqueVideoTrackSelected)==null?void 0:t.id)!==e.id&&(this.lastUniqueVideoTrackSelected=e,this.lastUniqueVideoTrackSelectedTimestamp=Qy(),this.currentStallsCount=0)}destroy(){window.clearTimeout(this.qualityRestrictionTimer),this.subscription.unsubscribe()}},Wy=ac;import{combine as QC,map as GC,observeElementSize as WC,Subscription as YC,ValueSubject as sc,noop as zC}from"@vkontakte/videoplayer-shared/es2015";var Cn=class{constructor(){this.subscription=new YC;this.pipSize$=new sc(void 0);this.videoSize$=new sc(void 0);this.elementSize$=new sc(void 0);this.pictureInPictureWindowRemoveEventListener=zC}connect({observableVideo:e,video:t}){let r=i=>{let s=i.target;this.pipSize$.next({width:s.width,height:s.height})};this.subscription.add(WC(t).subscribe(this.videoSize$)).add(e.enterPip$.subscribe(({pictureInPictureWindow:i})=>{this.pipSize$.next({width:i.width,height:i.height}),i.addEventListener("resize",r),this.pictureInPictureWindowRemoveEventListener=()=>{i.removeEventListener("resize",r)}})).add(e.leavePip$.subscribe(()=>{this.pictureInPictureWindowRemoveEventListener()})).add(QC({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe(GC(({videoSize:i,inPip:s,pipSize:n})=>s?n:i)).subscribe(this.elementSize$))}getValue(){return this.elementSize$.getValue()}subscribe(e,t){return this.elementSize$.subscribe(e,t)}getObservable(){return this.elementSize$}destroy(){this.pictureInPictureWindowRemoveEventListener(),this.subscription.unsubscribe()}};var Sr=class{constructor(e){this.subscription=new tD;this.videoState=new O("stopped");this.droppedFramesManager=new dn;this.stallsManager=new Wy;this.elementSizeManager=new Cn;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new Qi;this.audioTrackSwitchHistory=new Qi;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),i=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(i.state==="requested"&&(r==null?void 0:r.to)!=="paused"&&e!=="stopped"&&t!=="stopped"&&this.seek(i.position,i.forcePrecise),t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.player.stop(),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),A(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"),A(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="ready"&&A(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(r==null?void 0:r.to)==="playing"&&A(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&A(this.params.desiredState.playbackState,"paused");return;default:return XC(e)}}};this.init3DScene=e=>{var r,i,s;if(this.scene3D)return;this.scene3D=new Mn(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:((r=e.projectionData)==null?void 0:r.pose.yaw)||0,y:((i=e.projectionData)==null?void 0:i.pose.pitch)||0,z:((s=e.projectionData)==null?void 0:s.pose.roll)||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});let t=this.elementSizeManager.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};this.textTracksManager=new Ue(e.source.url),this.params=e,this.video=Pe(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(ce(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 Rn({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=ke(this.video),i=this.constructor.name,s=o=>{e.error$.next({id:i,category:Yy.WTF,message:`${i} internal logic error`,thrown:o})};return{output:e,desiredState:t,observableVideo:r,genericErrorListener:s,connect:(o,u)=>this.subscription.add(o.subscribe(u,s))}}subscribe(){let{output:e,desiredState:t,observableVideo:r,genericErrorListener:i,connect:s}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe(zy(l=>!!l.length),Xy()).subscribe(l=>{this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:r.playing$,pause$:r.pause$,tracks:l})}));let n=this.params.desiredState.seekState.stateChangeEnded$.pipe(nc(l=>l.to.state!=="none"),Ba());this.stallsManager.connect({isSeeked$:n,currentStallDuration$:this.player.currentStallDuration$.pipe(Ba()),videoLastDataObtainedTimestamp$:this.player.videoLastDataObtainedTimestamp$,throughput$:this.params.dependencies.throughputEstimator.throughput$,rtt$:this.params.dependencies.throughputEstimator.rtt$,qualityLimitsOnStall:this.params.tuning.dash.qualityLimitsOnStall,isBuffering$:r.isBuffering$}),s(r.ended$,e.endedEvent$),s(r.looped$,e.loopedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentBuffer$),s(r.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),s(r.loadedMetadata$,e.loadedMetadataEvent$),s(this.player.error$,e.error$),s(this.player.fetcherRecoverableError$,e.fetcherRecoverableError$),s(this.player.fetcherError$,e.fetcherError$),s(this.player.lastConnectionType$,e.httpConnectionType$),s(this.player.lastConnectionReused$,e.httpConnectionReused$),s(this.player.isLive$,e.isLive$),s(this.player.lastRequestFirstBytes$.pipe(zy(Ky),Xy()),e.firstBytesEvent$),s(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),s(this.videoState.stateChangeEnded$.pipe(nc(l=>l.to)),this.params.output.playbackState$),this.subscription.add(r.seeked$.subscribe(e.seekedEvent$,i)),this.subscription.add(nt(this.video,t.isLooped,i)),this.subscription.add(Ae(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(qe(this.video,t.playbackRate,r.playbackRateState$,i)),this.elementSizeManager.connect({video:this.video,observableVideo:r}),s(je(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),A(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),A(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:l})=>{if(l==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let c=this.player.getStreams();if(JC(c,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let p=[];for(let h of c.audio){p.push(Fl(h));let m=[];for(let b of h.representations){let g=by(b);m.push(g),this.audioTracksMap.set(g,{stream:h,representation:b})}this.audioStreamsMap.set(h,m)}this.params.output.availableAudioStreams$.next(p)}let d=[];for(let p of c.video){d.push(ql(p));let h=[];for(let m of p.representations){let b=fy($(P({},m),{streamId:p.id}));b&&(h.push(b),this.videoTracksMap.set(b,{stream:p,representation:m}))}this.videoStreamsMap.set(p,h)}this.params.output.availableVideoStreams$.next(d);for(let p of c.text)for(let h of p.representations){let m=gy(p,h);this.textTracksMap.set(m,{stream:p,representation:h})}this.params.output.availableVideoTracks$.next(Array.from(this.videoTracksMap.keys())),this.params.output.availableAudioTracks$.next(Array.from(this.audioTracksMap.keys())),this.params.output.isAudioAvailable$.next(!!this.audioTracksMap.size),this.audioTracksMap.size&&this.textTracksMap.size&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else l==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},i)),this.subscription.add(Dn(this.player.currentStallDuration$,this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,t.videoStream.stateChangeStarted$,t.audioStream.stateChangeStarted$,this.elementSizeManager.getObservable(),this.params.output.elementVisible$,this.droppedFramesManager.onDroopedVideoFramesLimit$,eD(this.video,"progress")).subscribe(()=>x(this,null,function*(){let l=this.player.state$.getState(),c=this.player.state$.getTransition();if(!(0,Jy.default)(["manifest_ready","running"],l)||c)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let d=this.selectVideoAudioRepresentations();if(!d)return;let[p,h]=d,m=[...this.videoTracksMap.keys()].find(g=>{var v;return((v=this.videoTracksMap.get(g))==null?void 0:v.representation.id)===p.id});Ky(m)&&(this.stallsManager.lastVideoTrackSelected=m);let b=this.params.desiredState.autoVideoTrackLimits.getTransition();if(b&&this.params.output.autoVideoTrackLimits$.next(b.to),l==="manifest_ready")yield this.player.initRepresentations(p.id,h==null?void 0:h.id,this.params.sourceHls);else if(yield this.player.switchRepresentation("video",p.id),h){let g=!!t.audioStream.getTransition();yield this.player.switchRepresentation("audio",h.id,g)}}),i)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:l})=>{this.scene3D&&l&&this.scene3D.pointCameraTo(l.x,l.y)})),this.subscription.add(this.elementSizeManager.subscribe(l=>{this.scene3D&&l&&this.scene3D.setViewportSize(l.width,l.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(Ba()).subscribe(l=>{let c=[...this.videoTracksMap.entries()].find(([,{representation:m}])=>m.id===l);if(!c){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[d,{stream:p}]=c,h=this.params.desiredState.videoStream.getTransition();h&&h.to&&h.to.id===p.id&&this.params.desiredState.videoStream.setState(h.to),e.currentVideoTrack$.next(d),e.currentVideoStream$.next(ql(p))},i)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(Ba()).subscribe(l=>{let c=[...this.audioTracksMap.entries()].find(([,{representation:m}])=>m.id===l);if(!c){e.currentAudioStream$.next(void 0);return}let[d,{stream:p}]=c,h=this.params.desiredState.audioStream.getTransition();h&&h.to&&h.to.id===p.id&&this.params.desiredState.audioStream.setState(h.to),e.currentAudioStream$.next(Fl(p))},i)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(l=>{var c,d;if(l!=null&&l.is3dVideo&&((c=this.params.tuning.spherical)!=null&&c.enabled))try{this.init3DScene(l),e.is3DVideo$.next(!0)}catch(p){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${p}`})}else this.destroy3DScene(),(d=this.params.tuning.spherical)!=null&&d.enabled&&e.is3DVideo$.next(!1)},i)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,i)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,i)),this.textTracksManager.connect(this.video,t,e);let o=t.playbackState.stateChangeStarted$.pipe(nc(({to:l})=>l==="ready"),Ba());this.subscription.add(Dn(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,oc(["init"])).subscribe(()=>{let l=t.autoVideoTrackSwitching.getState(),d=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:l?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(d)})),this.subscription.add(Dn(o,this.player.state$.stateChangeEnded$,oc(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let u=Dn(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,oc(["init"])).pipe(ZC(0));this.subscription.add(u.subscribe(this.syncPlayback,i))}selectVideoAudioRepresentations(){var M,re,C,j,Q,L,W,q,J,k,T,V,Y;let{desiredState:e,output:t}=this.params,r=e.autoVideoTrackSwitching.getState(),i=(M=e.videoTrack.getState())==null?void 0:M.id,n=[...this.videoTracksMap.keys()].find(({id:U})=>U===i),o=t.currentVideoTrack$.getValue(),u=((j=(C=e.videoStream.getState())!=null?C:n&&((re=this.videoTracksMap.get(n))==null?void 0:re.stream))!=null?j:this.videoStreamsMap.size===1)?this.videoStreamsMap.keys().next().value:void 0;if(!u)return;let l=[...this.videoStreamsMap.keys()].find(({id:U})=>U===u.id),c=l&&this.videoStreamsMap.get(l);if(!c)return;let d=ut(this.video.buffered,this.video.currentTime*1e3),p;this.player.isActiveLive$.getValue()?p=this.player.isLowLatency$.getValue()?this.params.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.params.tuning.dashCmafLive.normalizedLiveMinBufferSize:this.player.isLive$.getValue()?p=this.params.tuning.dashCmafLive.normalizedTargetMinBufferSize:p=r?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;let h=(this.video.duration*1e3||1/0)-this.video.currentTime*1e3,m=Math.min(d/Math.min(p,h||1/0),1),b=(Q=e.audioStream.getState())!=null?Q:this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0,g=(L=[...this.audioStreamsMap.keys()].find(({id:U})=>U===(b==null?void 0:b.id)))!=null?L:this.audioStreamsMap.keys().next().value,v=0;if(g){if(n&&!r){let U=on(n,c,(W=this.audioStreamsMap.get(g))!=null?W:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);v=Math.max(v,(q=U==null?void 0:U.bitrate)!=null?q:-1/0)}if(o){let U=on(o,c,(J=this.audioStreamsMap.get(g))!=null?J:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);v=Math.max(v,(k=U==null?void 0:U.bitrate)!=null?k:-1/0)}}let S=Ft(c,{container:this.elementSizeManager.getValue(),estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:v,forwardBufferHealth:m,current:o,visible:this.params.output.elementVisible$.getValue(),history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,stallsVideoMaxQualityLimit:this.stallsManager.videoMaxQualityLimit,stallsPredictedThroughput:this.stallsManager.predictedThroughput,abrLogger:this.params.dependencies.abrLogger}),y=r?S!=null?S:n:n!=null?n:S,I=g&&dv(y,c,(T=this.audioStreamsMap.get(g))!=null?T:[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:m,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),E=(V=this.videoTracksMap.get(y))==null?void 0:V.representation,R=I&&((Y=this.audioTracksMap.get(I))==null?void 0:Y.representation);if(E&&R)return[E,R];if(E&&!R&&this.audioTracksMap.size===0)return[E,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){Re(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),A(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Yy.DOM,thrown:e}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.stallsManager.destroy(),this.elementSizeManager.destroy(),this.destroy3DScene(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),this.params.output.currentVideoStream$.next(void 0),we(this.video),this.tracer.end()}};var Na=class extends Sr{subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:r}=this.getProviderSubscriptionInfo();r(t.timeUpdate$,e.position$),r(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}};import{combine as Vn,merge as Zy,filter as rD,filterChanged as iD,isNullable as uc,map as eT,ValueSubject as lc}from"@vkontakte/videoplayer-shared/es2015";var Fa=class extends Sr{constructor(e){super(e),this.textTracksManager.destroy()}subscribe(){super.subscribe();let e=-1,{output:t,observableVideo:r,desiredState:i,connect:s}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),s(r.timeUpdate$,t.liveBufferTime$),s(this.player.liveSeekableDuration$,t.duration$),s(this.player.liveLatency$,t.liveLatency$);let n=new lc(1);s(r.playbackRateState$,n),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(i.isLowLatency.stateChangeEnded$.pipe(eT(o=>o.to)).subscribe(this.player.isLowLatency$)).add(Vn({liveBufferTime:t.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(eT(({liveBufferTime:o,liveAvailabilityStartTime:u})=>o&&u?o+u:void 0)).subscribe(t.liveTime$)).add(Vn({position:t.position$,liveStreamStatus:this.player.liveStreamStatus$}).subscribe(({position:o,liveStreamStatus:u})=>t.isLiveEnded$.next(u!=="active"&&o===0))).add(Vn({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:Zy(r.playbackRateState$,new lc(1))}).pipe(rD(({liveStreamStatus:o,liveDuration:u})=>o==="active"&&!!u)).subscribe(({liveDuration:o,playbackRate:u})=>{let l=t.liveBufferTime$.getValue(),c=t.position$.getValue(),{playbackCatchupSpeedup:d}=this.params.tuning.dashCmafLive.lowLatency;c||u<1-d||this.video.paused||uc(l)||(e=o-l)})).add(Vn({time:t.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:Zy(r.playbackRateState$,new lc(1))}).pipe(iD((o,u)=>this.player.liveStreamStatus$.getValue()==="active"?o.liveDuration===u.liveDuration:o.time===u.time)).subscribe(({time:o,liveDuration:u,playbackRate:l})=>{let c=t.position$.getValue(),{playbackCatchupSpeedup:d}=this.params.tuning.dashCmafLive.lowLatency;if(!c&&!this.video.paused&&l>=1-d||uc(o)||uc(u))return;let p=-1*(u-o-e);t.position$.next(Math.min(p,0))})).add(this.player.currentLiveTextRepresentation$.subscribe(o=>{if(o){let u=vy(o);this.params.output.availableTextTracks$.next([u])}}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,r=Math.trunc(t/1e3<=Math.abs(this.params.output.duration$.getValue())?t:0);this.player.seekLive(r).then(()=>{this.params.output.position$.next(e/1e3)})}};var rT=_(Ws(),1);import{assertNever as qa,assertNonNullable as tT,debounce as aD,ErrorCategory as _n,filter as sD,isNonNullable as nD,isNullable as oD,map as On,merge as uD,Observable as lD,observableFrom as cD,Subscription as dD,videoSizeToQuality as pD}from"@vkontakte/videoplayer-shared/es2015";var et={};var ni=(a,e)=>new lD(t=>{let r=(i,s)=>t.next(s);return a.on(e,r),()=>a.off(e,r)}),Ua=class{constructor(e){this.subscription=new dD;this.videoState=new O("initializing");this.trackLevels=new Map;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),i=this.params.desiredState.seekState.getState();if(e!=="initializing")switch((r==null?void 0:r.to)!=="paused"&&i.state==="requested"&&this.seek(i.position),t){case"stopped":switch(e){case"stopped":break;case"ready":case"playing":case"paused":this.stop();break;default:qa(e)}break;case"ready":switch(e){case"stopped":this.prepare();break;case"ready":case"playing":case"paused":break;default:qa(e)}break;case"playing":switch(e){case"playing":break;case"stopped":this.prepare();break;case"ready":case"paused":this.playIfAllowed();break;default:qa(e)}break;case"paused":switch(e){case"paused":break;case"stopped":this.prepare();break;case"ready":this.videoState.setState("paused"),A(this.params.desiredState.playbackState,"paused");break;case"playing":this.pause();break;default:qa(e)}break;default:qa(t)}};this.textTracksManager=new Ue(e.source.url),this.video=Pe(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(ce(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),we(this.video)}loadHlsJs(){let e=!1,t=i=>{e||this.params.output.error$.next({id:i==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:_n.NETWORK,message:"Failed to load Hls.js",thrown:i}),e=!0},r=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);(0,rT.default)(import("hls.js").then(i=>{e||(et.Hls=i.default,et.Events=i.default.Events,this.init())},t),()=>{window.clearTimeout(r),e=!0})}init(){tT(et.Hls,"hls.js not loaded"),this.hls=new et.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState("stopped")}subscribe(){tT(et.Events,"hls.js not loaded");let{desiredState:e,output:t}=this.params,r=l=>{t.error$.next({id:"HlsJsProvider",category:_n.WTF,message:"HlsJsProvider internal logic error",thrown:l})},i=ke(this.video),s=(l,c)=>this.subscription.add(l.subscribe(c,r));s(i.timeUpdate$,t.position$),s(i.durationChange$,t.duration$),s(i.ended$,t.endedEvent$),s(i.looped$,t.loopedEvent$),s(i.error$,t.error$),s(i.isBuffering$,t.isBuffering$),s(i.currentBuffer$,t.currentBuffer$),s(i.loadStart$,t.firstBytesEvent$),s(i.loadedMetadata$,t.loadedMetadataEvent$),s(i.playing$,t.firstFrameEvent$),s(i.canplay$,t.canplay$),s(i.seeked$,t.seekedEvent$),s(i.inPiP$,t.inPiP$),s(i.inFullscreen$,t.inFullscreen$),this.subscription.add(nt(this.video,e.isLooped,r)),this.subscription.add(Ae(this.video,e.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(qe(this.video,e.playbackRate,i.playbackRateState$,r)),s(je(this.video),t.elementVisible$),s(this.videoState.stateChangeEnded$.pipe(On(l=>l.to)),this.params.output.playbackState$),this.subscription.add(ni(this.hls,et.Events.ERROR).subscribe(l=>{var c;l.fatal&&t.error$.next({id:["HlsJsFatal",l.type,l.details].join("_"),category:_n.WTF,message:`HlsJs fatal ${l.type} ${l.details}, ${(c=l.err)==null?void 0:c.message} ${l.reason}`,thrown:l.error})})),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),A(e.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),A(e.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{var l;((l=this.videoState.getTransition())==null?void 0:l.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),s(ni(this.hls,et.Events.MANIFEST_PARSED).pipe(On(({levels:l})=>l.reduce((c,d)=>{var S,y;let p=d.name||d.height.toString(10),{width:h,height:m}=d,b=(y=Ot((S=d.attrs.QUALITY)!=null?S:""))!=null?y:pD({width:h,height:m});if(!b)return c;let g=d.attrs["FRAME-RATE"]?parseFloat(d.attrs["FRAME-RATE"]):void 0,v={id:p.toString(),quality:b,bitrate:d.bitrate/1e3,size:{width:h,height:m},fps:g};return this.trackLevels.set(p,{track:v,level:d}),c.push(v),c},[]))),t.availableVideoTracks$),s(ni(this.hls,et.Events.MANIFEST_PARSED),l=>{if(l.subtitleTracks.length>0){let c=[];for(let d of l.subtitleTracks){let p=d.name,h=d.attrs.URI||"",m=d.lang;c.push({id:p,url:h,language:m,type:"internal"})}e.internalTextTracks.startTransitionTo(c)}}),s(ni(this.hls,et.Events.LEVEL_LOADING).pipe(On(({url:l})=>ce(l))),t.hostname$),s(ni(this.hls,et.Events.FRAG_CHANGED),l=>{var p,h,m,b;let{video:c,audio:d}=l.frag.elementaryStreams;t.currentVideoSegmentLength$.next((((p=c==null?void 0:c.endPTS)!=null?p:0)-((h=c==null?void 0:c.startPTS)!=null?h:0))*1e3),t.currentAudioSegmentLength$.next((((m=d==null?void 0:d.endPTS)!=null?m:0)-((b=d==null?void 0:d.startPTS)!=null?b:0))*1e3)}),this.subscription.add(Dt(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,l=>{this.hls.nextLevel=l?-1:this.hls.currentLevel,this.hls.loadLevel=l?-1:this.hls.loadLevel},{onError:r}));let n=l=>{var c;return(c=Array.from(this.trackLevels.values()).find(({level:d})=>d===l))==null?void 0:c.track},o=ni(this.hls,et.Events.LEVEL_SWITCHED).pipe(On(({level:l})=>n(this.hls.levels[l])));o.pipe(sD(nD)).subscribe(t.currentVideoTrack$,r),this.subscription.add(Dt(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel]),l=>{var m;if(oD(l))return;let c=(m=this.trackLevels.get(l.id))==null?void 0:m.level;if(!c)return;let d=this.hls.levels.indexOf(c),p=this.hls.currentLevel,h=this.hls.levels[p];!h||c.bitrate>h.bitrate?this.hls.nextLevel=d:(this.hls.loadLevel=d,this.hls.loadLevel=d)},{changed$:o,onError:r})),s(i.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);let u=uD(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,cD(["init"])).pipe(aD(0));this.subscription.add(u.subscribe(this.syncPlayback,r))}prepare(){this.videoState.startTransitionTo("ready"),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}playIfAllowed(){return x(this,null,function*(){this.videoState.startTransitionTo("playing"),(yield Re(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:_n.DOM,thrown:t})))||(this.videoState.setState("paused"),A(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"),A(this.params.desiredState.playbackState,"stopped",!0)}};var iT="X-Playback-Duration",cc=a=>x(void 0,null,function*(){var i;let e=yield lt(a),t=yield e.text(),r=(i=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t))==null?void 0:i[1];return r?parseInt(r,10):e.headers.has(iT)?parseInt(e.headers.get(iT),10):void 0});import{assertNever as ED,combine as xD,debounce as PD,ErrorCategory as Fn,filter as wD,filterChanged as AD,isNonNullable as nT,isNullable as qn,map as oT,merge as kD,observableFrom as RD,Subscription as LD,ValueSubject as hc,VideoQuality as $D}from"@vkontakte/videoplayer-shared/es2015";var pc=_(pu(),1);import{videoSizeToQuality as hD,getExponentialDelay as mD}from"@vkontakte/videoplayer-shared/es2015";var fD=a=>{let e=null;if(a.QUALITY&&(e=Ot(a.QUALITY)),!e&&a.RESOLUTION){let[t,r]=a.RESOLUTION.split("x").map(i=>parseInt(i,10));e=hD({width:t,height:r})}return e!=null?e:null},bD=(a,e)=>{var s,n;let t=a.split(`
|
|
125
|
-
`),r=[],i=[];for(let o=0;o<t.length;o++){let u=t[o],l=u.match(/^#EXT-X-STREAM-INF:(.+)/),c=u.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!l&&!c)){if(l){let d=(0,
|
|
126
|
-
`),s=0;for(let n=0;n<i.length;++n){let o=i[n];switch(!0){case o.startsWith("#EXTINF:"):{let u=i[++n],l=new URL(u,t).toString(),c=Number(this.extractPlaylistRowValue("#EXTINF:",o))*1e3;if(r.segments.push({time:{from:s,to:s+c},url:l}),s=s+c,!r.segmentStartTime){let d=new Date(r.vkStartTime).valueOf(),p=new Date(r.programDateTime).valueOf();r.segmentStartTime=p-d}break}case o.startsWith("#EXT-X-TARGETDURATION:"):r.targetDuration=Number(this.extractPlaylistRowValue("#EXT-X-TARGETDURATION:",o));break;case o.startsWith("#EXT-X-MEDIA-SEQUENCE:"):r.mediaSequence=Number(this.extractPlaylistRowValue("#EXT-X-MEDIA-SEQUENCE:",o));break;case o.startsWith("#EXT-X-VK-PLAYBACK-DURATION:"):r.vkPlaybackDuration=Number(this.extractPlaylistRowValue("#EXT-X-VK-PLAYBACK-DURATION:",o));break;case o.startsWith("#EXT-X-PROGRAM-DATE-TIME:"):{let u=this.extractPlaylistRowValue("#EXT-X-PROGRAM-DATE-TIME:",o);r.programDateTime=u;let l=new Date(u);l.setMilliseconds(0),s=l.valueOf();break}case o.startsWith("#EXT-X-VK-START-TIME:"):r.vkStartTime=this.extractPlaylistRowValue("#EXT-X-VK-START-TIME:",o);break}}return r}extractPlaylistRowValue(e,t){switch(e){case"#EXTINF:":return t.substring(e.length,t.length-1);default:return t.substring(e.length)}}processLiveTime(e){if(vD(e)&&this.currentTextTrackData){let{segments:t}=this.currentTextTrackData.playlist,{from:r}=t[0].time,{to:i}=t[t.length-1].time;if(e<r||e>i)return;i-e<this.params.downloadThreshold&&this.fetchNextManifestData();for(let n of t)if(n.time.from<=e&&n.time.to>=e){this.availableTextTracks$.next([$(P({},this.currentTextTrackData.textTrack),{url:n.url,isAuto:!0})]);break}}}fetchNextManifestData(){return x(this,null,function*(){try{if(this.abortControllers.nextManifest)return;this.abortControllers.nextManifest=new ge;let{textTracks:e}=yield this.fetchManifestData(),t=yield this.parseTextTracks(e,this.params.sourceUrl);this.currentTextTrackData&&t&&(this.currentTextTrackData.playlist.segments=t.playlist.segments)}catch(e){this.error("fetchNextManifestData",e)}finally{this.abortControllers.nextManifest=null}})}fetchManifestData(){return x(this,null,function*(){var t;let e=(t=this.prepareUrl)!=null?t:this.params.sourceUrl;return yield this.params.fetchManifestData(e,{signal:this.abortControllers.destroy.signal})})}error(e,t){this.error$.next({id:"[LiveTextManager][HLS_LIVE_CMAF]",category:ID.WTF,thrown:t,message:e})}};var Ha=class{constructor(e){this.subscription=new LD;this.videoState=new O("stopped");this.textTracksManager=null;this.liveTextManager=null;this.manifests$=new hc([]);this.liveOffset=new pr;this.manifestStartTime$=new hc(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"),A(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||n||o){let c=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(c),this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if((i==null?void 0:i.to)!=="paused"&&l.state==="requested"){this.videoState.startTransitionTo("ready"),this.seek(l.position&&l.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(t){case"ready":r==="ready"?A(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),A(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"&&A(this.params.desiredState.playbackState,"playing");return;case"paused":if(r==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let c=this.liveOffset.getTotalOffset();c>=this.maxSeekBackTime$.getValue()&&(c=0,this.liveOffset.resetTo(c)),this.liveOffset.resume(),this.params.output.position$.next(-c/1e3),this.prepare()}else(i==null?void 0:i.to)==="paused"&&(A(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return ED(t)}};var r;this.params=e,this.video=Pe(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:$D.INVARIANT,url:this.params.source.url};let t=(i,s)=>Bn(i,this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},s);this.params.tuning.useHlsLiveNewTextManager?this.liveTextManager=new Nn(this.params.output.liveTime$,this.video,t,this.params.source.url,this.params.tuning.hlsLiveNewTextManagerDownloadThreshold):this.textTracksManager=new Ue(e.source.url),t(this.generateLiveUrl()).then(({qualityManifests:i,textTracks:s})=>{var n;i.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:Fn.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),(n=this.liveTextManager)==null||n.processTextTracks(s,this.params.source.url),this.manifests$.next([this.masterManifest,...i])}).catch(i=>{this.params.output.error$.next({id:"ExtractHlsQualities",category:Fn.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:i})}),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(ce(this.params.source.url)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.maxSeekBackTime$=new hc((r=e.source.maxSeekBackTime)!=null?r:1/0),this.subscribe()}selectManifest(){var u,l,c,d;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,r=e.getState(),i=t.getTransition(),s=(d=(c=(u=i==null?void 0:i.to)==null?void 0:u.id)!=null?c:(l=t.getState())==null?void 0:l.id)!=null?d:"master",n=this.manifests$.getValue();if(!n.length)return;let o=r?"master":s;return r&&!i&&t.startTransitionTo(this.masterManifest),n.find(p=>p.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"HlsLiveProvider",category:Fn.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},i=ke(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(Ae(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(qe(this.video,t.playbackRate,i.playbackRateState$,r)),s(je(this.video),e.elementVisible$),this.liveTextManager?(s(this.liveTextManager.getCurrentTime$,this.params.output.getCurrentTime$),s(this.liveTextManager.error$,this.params.output.error$)):this.textTracksManager&&this.textTracksManager.connect(this.video,t,e),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),A(t.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),A(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())==null?void 0:o.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.liveTextManager&&this.subscription.add(this.liveTextManager.availableTextTracks$.subscribe(o=>{o&&this.params.output.availableTextTracks$.next(o)})),this.subscription.add(this.maxSeekBackTime$.pipe(AD(),oT(o=>-o/1e3)).subscribe(this.params.output.duration$,r)),this.subscription.add(i.loadedMetadata$.subscribe(()=>{let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&nT(l.to)){let d=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let p=this.manifests$.getValue().find(h=>h.id===d);p&&(this.params.output.currentVideoTrack$.next(p),this.params.output.hostname$.next(ce(p.url)))}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o&&o.state==="requested"&&this.seek(o.position)},r)),this.subscription.add(i.loadedData$.subscribe(()=>{var u,l,c;let o=(c=(l=(u=this.video)==null?void 0:u.getStartDate)==null?void 0:l.call(u))==null?void 0:c.getTime();this.manifestStartTime$.next(o||void 0)},r)),this.subscription.add(xD({startTime:this.manifestStartTime$.pipe(wD(nT)),currentTime:i.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),r)),this.subscription.add(this.manifests$.pipe(oT(o=>o.map(({id:u,quality:l,size:c,bandwidth:d,fps:p})=>({id:u,quality:l,size:c,fps:p,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,r));let n=kD(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,RD(["init"])).pipe(PD(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){var e,t;this.subscription.unsubscribe(),(e=this.textTracksManager)==null||e.destroy(),(t=this.liveTextManager)==null||t.destroy(),this.params.output.element$.next(void 0),we(this.video)}prepare(){var o,u,l;let e=this.selectManifest();if(qn(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),r=this.params.desiredState.autoVideoTrackLimits.getState(),i=new URL(e.url);if((t||r)&&e.id===this.masterManifest.id){let{max:c,min:d}=(u=(o=t==null?void 0:t.to)!=null?o:r)!=null?u:{};for(let[p,h]of[[c,"mq"],[d,"lq"]]){let m=String(parseFloat(p||""));h&&p&&i.searchParams.set(h,m)}}let s=this.params.format==="HLS_LIVE_CMAF"?2:0,n=be(i.toString(),this.liveOffset.getTotalOffset(),s);(l=this.liveTextManager)==null||l.prepare(n),this.video.setAttribute("src",n),this.video.load(),cc(n).then(c=>{var d;if(!qn(c))this.maxSeekBackTime$.next(c);else{let p=(d=this.params.source.maxSeekBackTime)!=null?d:this.maxSeekBackTime$.getValue();(qn(p)||!isFinite(p))&<(n).then(h=>h.text()).then(h=>{var b;let m=(b=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(h))==null?void 0:b[1];if(m){let g=new URL(m,n).toString();cc(g).then(v=>{qn(v)||this.maxSeekBackTime$.next(v)})}}).catch(()=>{})}})}playIfAllowed(){Re(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),A(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Fn.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,r=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(r),this.params.output.position$.next(-r/1e3),this.params.output.seekedEvent$.next()}generateLiveUrl(){let e=be(this.params.source.url);if(this.params.tuning.useHlsLiveNewTextManager){let t=new URL(e);t.searchParams.set("enable-subtitles","yes"),e=t.toString()}return e}};import{assertNever as MD,debounce as CD,ErrorCategory as mc,fromEvent as fc,isNonNullable as DD,isNullable as VD,map as uT,merge as lT,observableFrom as cT,Subscription as _D,ValueSubject as OD,VideoQuality as BD}from"@vkontakte/videoplayer-shared/es2015";var ja=class{constructor(e){this.subscription=new _D;this.videoState=new O("stopped");this.manifests$=new OD([]);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"),A(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||n||o){let c=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(c);let{currentTime:d}=this.video;this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:d*1e3,forcePrecise:!0});return}switch((i==null?void 0:i.to)!=="paused"&&l.state==="requested"&&this.seek(l.position),t){case"ready":r==="ready"?A(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),A(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"&&A(this.params.desiredState.playbackState,"playing");return;case"paused":r==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&A(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return MD(t)}};this.textTracksManager=new Ue(e.source.url),this.params=e,this.video=Pe(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:BD.INVARIANT,url:this.params.source.url},this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(ce(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),Bn(be(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:mc.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){var u,l,c,d;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,r=e.getState(),i=t.getTransition(),s=(d=(c=(u=i==null?void 0:i.to)==null?void 0:u.id)!=null?c:(l=t.getState())==null?void 0:l.id)!=null?d:"master",n=this.manifests$.getValue();if(!n.length)return;let o=r?"master":s;return r&&(!i||!i.from)&&t.startTransitionTo(this.masterManifest),n.find(p=>p.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"HlsProvider",category:mc.WTF,message:"HlsProvider internal logic error",thrown:o})},i=ke(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(uT(o=>o.to)),this.params.output.playbackState$),this.subscription.add(nt(this.video,t.isLooped,r)),this.subscription.add(Ae(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(qe(this.video,t.playbackRate,i.playbackRateState$,r)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),A(t.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),A(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())==null?void 0:o.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},r).add(i.loadedMetadata$.subscribe(()=>{var h;let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&DD(l.to)){let m=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let b=this.manifests$.getValue().find(g=>g.id===m);b&&(this.params.output.currentVideoTrack$.next(b),this.params.output.hostname$.next(ce(b.url)))}let d=this.params.desiredState.playbackRate.getState(),p=(h=this.params.output.element$.getValue())==null?void 0:h.playbackRate;if(d!==p){let m=this.params.output.element$.getValue();m&&(this.params.desiredState.playbackRate.setState(d),m.playbackRate=d)}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o.state==="requested"&&this.seek(o.position)},r))),this.subscription.add(this.manifests$.pipe(uT(o=>o.map(({id:u,quality:l,size:c,bandwidth:d,fps:p})=>({id:u,quality:l,size:c,fps:p,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,r)),!N.device.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add(lT(fc(o,"addtrack"),fc(o,"removetrack"),fc(o,"change"),cT(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},r))}let n=lT(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,cT(["init"])).pipe(CD(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),we(this.video)}prepare(){var s,n;let e=this.selectManifest();if(VD(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),r=this.params.desiredState.autoVideoTrackLimits.getState(),i=new URL(e.url);if((t||r)&&e.id===this.masterManifest.id){let{max:o,min:u}=(n=(s=t==null?void 0:t.to)!=null?s:r)!=null?n:{};for(let[l,c]of[[o,"mq"],[u,"lq"]]){let d=String(parseFloat(l||""));c&&l&&i.searchParams.set(c,d)}}this.video.setAttribute("src",i.toString()),this.video.load()}playIfAllowed(){Re(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),A(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:mc.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};var hT=_(Br(),1),bc=_(zr(),1),mT=_(Bt(),1);import{assertNever as ND,assertNonNullable as dT,debounce as FD,ErrorCategory as pT,isHigherOrEqual as qD,isLowerOrEqual as UD,isNonNullable as HD,merge as jD,observableFrom as QD,Subscription as GD,map as WD}from"@vkontakte/videoplayer-shared/es2015";var Qa=class{constructor(e){this.subscription=new GD;this.videoState=new O("stopped");this.trackUrls={};this.textTracksManager=new Ue;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),A(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let s=this.params.desiredState.autoVideoTrackLimits.getTransition(),n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.seekState.getState();if(s&&e!=="ready"&&!n){this.handleQualityLimitTransition(s.to);return}if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(n){let{currentTime:u}=this.video;this.prepare(),o.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:u*1e3,forcePrecise:!0});return}switch((r==null?void 0:r.to)!=="paused"&&o.state==="requested"&&this.seek(o.position),e){case"ready":t==="ready"?A(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),A(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"&&A(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&A(this.params.desiredState.playbackState,"paused");return;default:return ND(e)}};this.params=e,this.video=Pe(e.container,e.tuning),this.params.output.element$.next(this.video),(0,hT.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,bc.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:pT.WTF,message:"MpegProvider internal logic error",thrown:o})},i=ke(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(WD(o=>o.to)),this.params.output.playbackState$),this.subscription.add(nt(this.video,t.isLooped,r)),this.subscription.add(Ae(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(qe(this.video,t.playbackRate,i.playbackRateState$,r)),s(je(this.video),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),A(t.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),A(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&&HD(o.to)){this.params.desiredState.videoTrack.setState(o.to),this.params.output.currentVideoTrack$.next(this.trackUrls[o.to.id].track);let c=this.params.desiredState.playbackRate.getState(),d=(l=this.params.output.element$.getValue())==null?void 0:l.playbackRate;if(c!==d){let p=this.params.output.element$.getValue();p&&(this.params.desiredState.playbackRate.setState(c),p.playbackRate=c)}}this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.textTracksManager.connect(this.video,t,e);let n=jD(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,QD(["init"])).pipe(FD(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),we(this.video)}prepare(){var r;let e=(r=this.params.desiredState.videoTrack.getState())==null?void 0:r.id;dT(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];dT(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=$a(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(ce(t))}playIfAllowed(){Re(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),A(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:pT.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){var l,c;this.params.output.autoVideoTrackLimits$.next(e);let t=d=>{this.params.output.currentVideoTrack$.next(d),this.params.desiredState.videoTrack.startTransitionTo(d)},r=d=>{let p=Ft(n,{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:0,limits:d,abrLogger:this.params.dependencies.abrLogger});t(p)},i=(l=this.params.output.currentVideoTrack$.getValue())==null?void 0:l.quality,s=!!(e.max||e.min),n=(0,bc.default)(this.trackUrls).map(d=>d.track);if(!i||!s||ji({limits:e,lowestAvailableQuality:(c=(0,mT.default)(n,-1))==null?void 0:c.quality,highestAvailableQuality:n[0].quality})){r();return}let o=e.max?UD(i,e.max):!0,u=e.min?qD(i,e.min):!0;o&&u||r(e)}};import{assertNever as bT,debounce as XD,merge as gT,observableFrom as JD,Subscription as ZD,map as vT,ValueSubject as e0,ErrorCategory as vc,VideoQuality as t0}from"@vkontakte/videoplayer-shared/es2015";import{ErrorCategory as YD}from"@vkontakte/videoplayer-shared/es2015";var fT=["stun:videostun.mycdn.me:80"],zD=1e3,KD=3,gc=()=>null,Un=class{constructor(e,t){this.ws=null;this.peerConnection=null;this.serverUrl="";this.streamKey="";this.stream=null;this.signalingType="JOIN";this.retryCount=0;this.externalStartCallback=gc;this.externalStopCallback=gc;this.externalErrorCallback=gc;this.options=this.normalizeOptions(t);let r=e.split("/");this.serverUrl=r.slice(0,r.length-1).join("/"),this.streamKey=r[r.length-1]}onStart(e){try{this.externalStartCallback=e}catch(t){this.handleSystemError(t)}}onStop(e){try{this.externalStopCallback=e}catch(t){this.handleSystemError(t)}}onError(e){try{this.externalErrorCallback=e}catch(t){this.handleSystemError(t)}}connect(){this.connectWS()}disconnect(){try{this.externalStopCallback(),this.closeConnections()}catch(e){this.handleSystemError(e)}}connectWS(){this.ws||(this.ws=new WebSocket(this.serverUrl),this.ws.onopen=this.onSocketOpen.bind(this),this.ws.onmessage=this.onSocketMessage.bind(this),this.ws.onclose=this.onSocketClose.bind(this),this.ws.onerror=this.onSocketError.bind(this))}onSocketOpen(){this.handleLogin()}onSocketClose(e){try{if(!this.ws)return;this.ws=null,e.code>1e3?(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():this.scheduleRetry()):this.externalStopCallback()}catch(t){this.handleRTCError(t)}}onSocketError(e){try{this.externalErrorCallback(new Error(e.toString()))}catch(t){this.handleRTCError(t)}}onSocketMessage(e){try{let t=this.parseMessage(e.data);switch(t.type){case"JOIN":case"CALL_JOIN":this.handleJoinMessage(t);break;case"UPDATE":this.handleUpdateMessage(t);break;case"STATUS":this.handleStatusMessage(t);break}}catch(t){this.handleRTCError(t)}}handleJoinMessage(e){switch(e.inviteType){case"ANSWER":this.handleAnswer(e.sdp);break;case"CANDIDATE":this.handleCandidate(e.candidate);break}}handleStatusMessage(e){switch(e.status){case"UNPUBLISHED":this.handleUnpublished();break}}handleUpdateMessage(e){return x(this,null,function*(){try{let t=yield this.createOffer();this.peerConnection&&(yield this.peerConnection.setLocalDescription(t)),this.handleAnswer(e.sdp)}catch(t){this.handleRTCError(t)}})}handleLogin(){return x(this,null,function*(){try{let e={iceServers:[{urls:fT}]};this.peerConnection=new RTCPeerConnection(e),this.peerConnection.ontrack=this.onPeerConnectionStream.bind(this),this.peerConnection.onicecandidate=this.onPeerConnectionIceCandidate.bind(this),this.peerConnection.oniceconnectionstatechange=this.onPeerConnectionIceConnectionStateChange.bind(this);let t=yield this.createOffer();yield this.peerConnection.setLocalDescription(t),this.send({type:this.signalingType,inviteType:"OFFER",streamKey:this.streamKey,sdp:t.sdp,callSupport:!1})}catch(e){this.handleRTCError(e)}})}handleAnswer(e){return x(this,null,function*(){try{this.peerConnection&&(yield this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e})))}catch(t){this.handleRTCError(t)}})}handleCandidate(e){return x(this,null,function*(){if(e)try{this.peerConnection&&(yield this.peerConnection.addIceCandidate(e))}catch(t){this.handleRTCError(t)}})}handleUnpublished(){try{this.closeConnections(),this.externalStopCallback()}catch(e){this.handleRTCError(e)}}handleSystemError(e){this.options.errorChanel&&this.options.errorChanel.next({id:"webrtc-provider-error",category:YD.WTF,message:e.message})}onPeerConnectionStream(e){return x(this,null,function*(){let t=e.streams[0];this.stream&&this.stream.id===t.id||(this.stream=t,this.externalStartCallback(this.stream))})}onPeerConnectionIceCandidate(e){e.candidate&&this.send({type:this.signalingType,inviteType:"CANDIDATE",candidate:e.candidate})}onPeerConnectionIceConnectionStateChange(){if(this.peerConnection){let e=this.peerConnection.iceConnectionState;["failed","closed"].indexOf(e)>-1&&(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():(this.closeConnections(),this.scheduleRetry()))}}createOffer(){return x(this,null,function*(){let e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");let t=yield this.peerConnection.createOffer(e),r=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(r))throw new Error("No h264 codec support error");return t})}handleRTCError(e){try{this.externalErrorCallback(e||new Error("RTC connection error"))}catch(t){this.handleSystemError(t)}}handleNetworkError(){try{this.externalErrorCallback(new Error("Network error"))}catch(e){this.handleSystemError(e)}}send(e){this.ws&&this.ws.send(JSON.stringify(e))}parseMessage(e){try{return JSON.parse(e)}catch(t){throw new Error("Can not parse socket message")}}closeConnections(){let e=this.ws;e&&(this.ws=null,e.close(1e3)),this.removePeerConnection()}removePeerConnection(){let e=this.peerConnection;e&&(this.peerConnection=null,e.close(),e.ontrack=null,e.onicecandidate=null,e.oniceconnectionstatechange=null,e=null)}scheduleRetry(){this.retryTimeout=setTimeout(this.connectWS.bind(this),zD)}normalizeOptions(e={}){let t={stunServerList:fT,maxRetryNumber:KD,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var Ga=class{constructor(e){this.videoState=new O("stopped");this.maxSeekBackTime$=new e0(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"),A(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"),A(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"&&A(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&A(this.params.desiredState.playbackState,"paused");return;default:return bT(e)}};this.subscription=new ZD,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=Pe(e.container,e.tuning),this.liveStreamClient=new Un(this.params.source.url,{maxRetryNumber:this.params.tuning.webrtc.connectionRetryMaxNumber,errorChanel:this.params.output.error$}),this.liveStreamClient.onStart(this.onLiveStreamStart.bind(this)),this.liveStreamClient.onStop(this.onLiveStreamStop.bind(this)),this.liveStreamClient.onError(this.onLiveStreamError.bind(this)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.subscribe()}destroy(){this.subscription.unsubscribe(),this.liveStreamClient.disconnect(),this.params.output.element$.next(void 0),we(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,r=n=>{e.error$.next({id:"WebRTCLiveProvider",category:vc.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};gT(this.videoState.stateChangeStarted$.pipe(vT(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe(vT(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})});let i=ke(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(je(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(Ae(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 bT(n.to)}},r)).add(gT(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,JD(["init"])).pipe(XD(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(ce(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:t0.INVARIANT}),this.video.srcObject=e,A(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:vc.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){Re(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),A(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:vc.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var Wa=class{constructor(e){this.iterator=e[Symbol.iterator](),this.next()}next(){this.current=this.iterator.next()}getValue(){if(this.current.done)throw new Error("Iterable is completed");return this.current.value}isCompleted(){return!!this.current.done}};import{assertNever as za,assertNonNullable as Qt,ErrorCategory as Hn,filter as xT,isNonNullable as PT,isNullable as u0,map as l0,merge as c0,once as d0,Subject as pe,Subscription as wT,ValueSubject as B,flattenObject as AT}from"@vkontakte/videoplayer-shared/es2015";import{Observable as r0,map as ST,Subscription as i0,Subject as a0}from"@vkontakte/videoplayer-shared/es2015";var yT=a=>new r0(e=>{let t=new i0,r=a.desiredPlaybackState$.stateChangeStarted$.pipe(ST(({from:l,to:c})=>`${l}-${c}`)),i=a.desiredPlaybackState$.stateChangeEnded$,s=a.providerChanged$.pipe(ST(({type:l})=>l!==void 0)),n=new a0,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 s0,Subscription as n0,combine as o0,filter as IT,once as ET}from"@vkontakte/videoplayer-shared/es2015";function TT(){return new(window.AudioContext||window.webkitAudioContext)}var Ya=class Ya{constructor(e,t,r,i){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=r;this.volumeMultiplier=i;this.destroyController=new ge;this.subscriptions=new n0;this.audioContext=null;this.gainNode=null;this.mediaElementSource=null;this.subscriptions.add(this.provider$.pipe(IT(s=>!!s.type),ET()).subscribe(({type:s})=>this.subscribe(s)))}subscribe(e){N.browser.isSafari&&e!=="MPEG"||this.subscriptions.add(o0({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe(IT(({playbackState:t,video:r,volume:{muted:i,volume:s}})=>t==="playing"&&!!r&&!i&&!!s),ET()).subscribe(({video:t})=>{this.initAudioContextOnce(t).then(r=>{r||this.destroy()}).catch(r=>{this.handleError(r),this.destroy()})}))}static isSupported(){return"AudioContext"in window&&"GainNode"in window&&"MediaElementAudioSourceNode"in window}initAudioContextOnce(e){return x(this,null,function*(){let{volumeMultiplier:t}=this,r=TT();this.audioContext=r;let i=r.createGain();if(this.gainNode=i,i.gain.value=t,i.connect(r.destination),r.state==="suspended"&&(yield r.resume(),this.destroyController.signal.aborted))return!1;let s=r.createMediaElementSource(e);return this.mediaElementSource=s,s.connect(i),!0})}cleanup(){this.mediaElementSource&&(this.mediaElementSource.disconnect(),this.mediaElementSource=null),this.gainNode&&(this.gainNode.disconnect(),this.gainNode=null),this.audioContext&&(this.audioContext.state!=="closed"&&this.audioContext.close(),this.audioContext=null)}destroy(){this.destroyController.abort(),this.subscriptions.unsubscribe(),this.cleanup()}handleError(e){var t;this.volumeMultiplierError$.next({id:Ya.errorId,category:s0.VIDEO_PIPELINE,message:(t=e==null?void 0:e.message)!=null?t:`${Ya.errorId} exception`,thrown:e})}};Ya.errorId="VolumeMultiplierManager";var oi=Ya;var p0={chunkDuration:5e3,maxParallelRequests:5},Ka=class{constructor(e){this.current$=new B({type:void 0});this.providerError$=new pe;this.noAvailableProvidersError$=new pe;this.volumeMultiplierError$=new pe;this.providerOutput={position$:new B(0),duration$:new B(1/0),volume$:new B({muted:!1,volume:1}),availableVideoStreams$:new B([]),currentVideoStream$:new B(void 0),availableVideoTracks$:new B([]),currentVideoTrack$:new B(void 0),availableAudioStreams$:new B([]),currentAudioStream$:new B(void 0),availableAudioTracks$:new B([]),currentVideoSegmentLength$:new B(0),currentAudioSegmentLength$:new B(0),isAudioAvailable$:new B(!0),autoVideoTrackLimitingAvailable$:new B(!1),autoVideoTrackLimits$:new B(void 0),currentBuffer$:new B(void 0),isBuffering$:new B(!0),error$:new pe,fetcherError$:new pe,fetcherRecoverableError$:new pe,warning$:new pe,willSeekEvent$:new pe,soundProhibitedEvent$:new pe,seekedEvent$:new pe,loopedEvent$:new pe,endedEvent$:new pe,firstBytesEvent$:new pe,loadedMetadataEvent$:new pe,firstFrameEvent$:new pe,canplay$:new pe,isLive$:new B(void 0),isLiveEnded$:new B(null),isLowLatency$:new B(!1),canChangePlaybackSpeed$:new B(!0),liveTime$:new B(void 0),liveBufferTime$:new B(void 0),liveLatency$:new B(void 0),severeStallOccurred$:new pe,availableTextTracks$:new B([]),currentTextTrack$:new B(void 0),hostname$:new B(void 0),httpConnectionType$:new B(void 0),httpConnectionReused$:new B(void 0),inPiP$:new B(!1),inFullscreen$:new B(!1),element$:new B(void 0),elementVisible$:new B(!0),availableSources$:new B(void 0),is3DVideo$:new B(!1),playbackState$:new B(""),getCurrentTime$:new B(null)};this.subscription=new wT;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=Vy([...Oy(this.params.tuning),..._y(this.params.tuning)],this.params.tuning).filter(l=>PT(e.sources[l])),{forceFormat:r,formatsToAvoid:i}=this.params.tuning,s=[];r?s=[r]:i.length?s=[...t.filter(l=>!(0,Sc.default)(i,l)),...t.filter(l=>(0,Sc.default)(i,l))]:s=t,this.log({message:`Selected formats: ${s.join(" > ")}`}),this.tracer.log("Selected formats",AT(s)),this.screenFormatsIterator=new Wa(s);let n=[...Xl(!0),...Xl(!1)];this.chromecastFormatsIterator=new Wa(n.filter(l=>PT(e.sources[l]))),this.providerOutput.availableSources$.next(e.sources);let{volumeMultiplier:o=1,tuning:{useVolumeMultiplier:u}}=this.params;u&&o!==1&&oi.isSupported()&&(this.volumeMultiplierManager=new oi(this.providerOutput,this.current$,this.volumeMultiplierError$,o))}init(){this.subscription.add(this.initProviderErrorHandling()),this.subscription.add(this.params.dependencies.chromecastInitializer.connection$.subscribe(()=>{this.reinitProvider()}))}destroy(){var e;this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe(),(e=this.volumeMultiplierManager)==null||e.destroy(),this.volumeMultiplierManager=null,this.tracer.end()}initProvider(){let e=this.chooseDestination(),t=this.chooseFormat(e);if(u0(t)){this.handleNoFormatsError(e);return}let r;try{r=this.createProvider(e,t)}catch(i){this.providerError$.next({id:"ProviderNotConstructed",category:Hn.WTF,message:"Failed to create provider",thrown:i})}r?this.current$.next({type:t,provider:r,destination:e}):this.current$.next({type:void 0})}reinitProvider(){this.tracer.log("reinitProvider"),this.destroyProvider(),this.initProvider()}switchToNextProvider(e){this.tracer.log("switchToNextProvider",{destination:e}),this.destroyProvider(),this.failoverIndex=void 0,this.skipFormat(e),this.initProvider()}destroyProvider(){let e=this.current$.getValue().provider;if(!e)return;this.log({message:"destroyProvider"}),this.tracer.log("destroyProvider");let t=this.providerOutput.position$.getValue()*1e3,r=this.params.desiredState.seekState.getState(),i=r.state!=="none";if(this.params.desiredState.seekState.setState({state:"requested",position:i?r.position:t,forcePrecise:i?r.forcePrecise:!1}),e.scene3D){let n=e.scene3D.getCameraRotation();this.params.desiredState.cameraOrientation.setState({x:n.x,y:n.y})}e.destroy();let s=this.providerOutput.isBuffering$;s.getValue()||s.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),this.tracer.log("createProvider",{destination:e,format:t}),e){case"SCREEN":return this.createScreenProvider(t);case"CHROMECAST":return this.createChromecastProvider(t);default:return za(e)}}createScreenProvider(e){let{sources:t,container:r,desiredState:i}=this.params,s=this.providerOutput,n={container:r,source:null,desiredState:i,output:s,dependencies:this.params.dependencies,tuning:this.params.tuning};switch(e){case"DASH_SEP":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_ONDEMAND":case"DASH_STREAMS":{let o=this.applyFailoverHost(t[e]),u=this.applyFailoverHost(t.HLS_ONDEMAND||t.HLS);return Qt(o),new Na($(P({},n),{source:o,sourceHls:u}))}case"DASH_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return Qt(o),new Fa($(P({},n),{source:o}))}case"HLS":case"HLS_ONDEMAND":{let o=this.applyFailoverHost(t[e]);return Qt(o),N.video.nativeHlsSupported||!this.params.tuning.useHlsJs?new ja($(P({},n),{source:o})):new Ua($(P({},n),{source:o}))}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return Qt(o),new Ha($(P({},n),{source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e}))}case"MPEG":{let o=this.applyFailoverHost(t[e]);return Qt(o),new Qa($(P({},n),{source:o}))}case"DASH_LIVE":{let o=this.applyFailoverHost(t[e]);return Qt(o),new kv($(P({},n),{source:o,config:$(P({},p0),{maxPausedTime:this.params.tuning.live.maxPausedTime})}))}case"WEB_RTC_LIVE":{let o=this.applyFailoverHost(t[e]);return Qt(o),new Ga({container:r,source:o,desiredState:i,output:s,dependencies:this.params.dependencies,tuning:this.params.tuning})}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return za(e)}}createChromecastProvider(e){let{sources:t,container:r,desiredState:i,meta:s}=this.params,n=this.providerOutput,o=this.params.dependencies.chromecastInitializer.connection$.getValue();return Qt(o),new Ni({connection:o,meta:s,container:r,source:t,format:e,desiredState:i,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?"CHROMECAST":"SCREEN"}chooseFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case"CHROMECAST":return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return za(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return za(e)}}handleNoFormatsError(e){switch(e){case"SCREEN":this.noAvailableProvidersError$.next(this.params.tuning.forceFormat),this.current$.next({type:void 0});return;case"CHROMECAST":this.params.dependencies.chromecastInitializer.disconnect();return;default:return za(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;let t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;let r=i=>{let s=new URL(i);return s.host=t,s.toString()};if(e===void 0)return e;if("type"in e){if(e.type==="raw")return e;if(e.type==="url")return $(P({},e),{url:r(e.url)})}return(0,RT.default)((0,kT.default)(e).map(([i,s])=>[i,r(s)]))}initProviderErrorHandling(){let e=new wT,t=!1,r=0;return e.add(c0(this.providerOutput.error$.pipe(xT(i=>!this.params.tuning.ignoreAudioRendererError||!i.message||!/AUDIO_RENDERER_ERROR/ig.test(i.message))),yT({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(l0(i=>({id:`ProviderHangup:${i}`,category:Hn.WTF,message:`A ${i} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.providerOutput.fetcherError$.subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;let i=this.params.desiredState.playbackState.transitionEnded$.pipe(xT(({to:s})=>s==="playing"),d0()).subscribe(()=>t=!0);e.add(i)})),e.add(this.providerError$.subscribe(i=>{let s=this.current$.getValue().destination,n={error:i,currentDestination:s};if(s==="CHROMECAST")this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider("SCREEN"),()=>this.params.dependencies.chromecastInitializer.disconnect());else{let o=i.category===Hn.NETWORK,u=i.category===Hn.FATAL,l=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),c=r<this.params.tuning.providerErrorLimit&&!u,d=l&&!u&&(o&&t||!c);n=$(P({},n),{isNetworkError:o,isFatalError:u,haveFailoverHost:l,tryFailover:d,canReinitProvider:c}),c?(r++,this.reinitProvider()):d?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):this.switchToNextProvider(s!=null?s:"SCREEN")}this.tracer.error("providerError",AT(n))})),e}};import{fromEvent as jn,once as h0,combine as m0,Subscription as LT,ValueSubject as yc,map as f0,filter as b0,isNonNullable as Qn,now as Be,safeStorage as Tc}from"@vkontakte/videoplayer-shared/es2015";var g0=5e3,$T="one_video_throughput",MT="one_video_rtt",Tt=window.navigator.connection,CT=()=>{let a=Tt==null?void 0:Tt.downlink;if(Qn(a)&&a!==10)return a*1e3},DT=()=>{let a=Tt==null?void 0:Tt.rtt;if(Qn(a)&&a!==3e3)return a},VT=(a,e,t)=>{let r=t*8,i=r/a;return r/(i+e)},Ic=class a{constructor(e){this.subscription=new LT;this.concurrentDownloads=new Set;var i,s;this.tuningConfig=e;let t=a.load($T)||(e.useBrowserEstimation?CT():void 0)||g0,r=(s=(i=a.load(MT))!=null?i:e.useBrowserEstimation?DT():void 0)!=null?s:0;if(this.throughput$=new yc(t),this.rtt$=new yc(r),this.rttAdjustedThroughput$=new yc(VT(t,r,e.rttPenaltyRequestSize)),this.throughput=gr.getSmoothedValue(t,-1,e),this.rtt=gr.getSmoothedValue(r,1,e),e.useBrowserEstimation){let n=()=>{let u=CT();u&&this.throughput.next(u);let l=DT();Qn(l)&&this.rtt.next(l)};Tt&&"onchange"in Tt&&this.subscription.add(jn(Tt,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{Tc.set($T,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{Tc.set(MT,n.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(m0({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(f0(({throughput:n,rtt:o})=>VT(n,o,e.rttPenaltyRequestSize)),b0(n=>{let o=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(n-o)/o>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,r=Be(),i=new LT;switch(this.subscription.add(i),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:i.add(jn(e,"progress").pipe(h0()).subscribe(s=>{t=s.loaded,r=Be()}));break;case 1:case 0:i.add(jn(e,"loadstart").subscribe(()=>{t=0,r=Be()}));break}i.add(jn(e,"loadend").subscribe(s=>{if(e.status===200){let n=s.loaded,o=Be(),u=n-t,l=o-r;this.addRawSpeed(u,l,1)}this.concurrentDownloads.delete(e),i.unsubscribe()}))}trackStream(e,t=!1){let r=e.getReader();if(!r){e.cancel("Could not get reader");return}let i=0,s=Be(),n=0,o=Be(),u=c=>{this.concurrentDownloads.delete(e),r.releaseLock(),e.cancel(`Throughput Estimator error: ${c}`).catch(()=>{})},l=p=>x(this,[p],function*({done:c,value:d}){if(c)!t&&this.addRawSpeed(i,Be()-s,1),this.concurrentDownloads.delete(e);else if(d){if(t){let h=Be();if(h-o>this.tuningConfig.lowLatency.continuesByteSequenceInterval||h-s>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let b=o-s;b&&this.addRawSpeed(n,b,1,t),n=d.byteLength,s=Be()}else n+=d.byteLength;o=Be()}else i+=d.byteLength,n+=d.byteLength,n>=this.tuningConfig.streamMinSampleSize&&Be()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,Be()-o,this.concurrentDownloads.size),n=0,o=Be());yield r==null?void 0:r.read().then(l,u)}});this.concurrentDownloads.add(e),r==null||r.read().then(l,u)}addRawSpeed(e,t,r=1,i=!1){if(a.sanityCheck(e,t,i)){let s=e*8/t;this.throughput.next(s*r)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,r=!1){let i=e*8/t;return!(!i||!isFinite(i)||i>1e6||i<30||r&&e<1e4||!r&&e<10*1024||!r&&t<=20)}static load(e){var r;let t=Tc.get(e);if(Qn(t))return(r=parseInt(t,10))!=null?r:void 0}},_T=Ic;import{fillWithDefault as v0,VideoQuality as Gn}from"@vkontakte/videoplayer-shared/es2015";var OT={configName:["core"],throughputEstimator:{type:"EmaAndMa",emaAlphaSlow:.2,emaAlphaFast:.7,emaAlpha:.45,basisTrendChangeCount:10,changeThreshold:.05,useBrowserEstimation:!0,rttPenaltyRequestSize:1*1024*1024,streamMinSampleSize:10*1024,streamMinSampleTime:300,deviationDepth:20,deviationFactor:.5,lowLatency:{continuesByteSequenceInterval:50,maxLastEvaluationTimeout:300}},autoTrackSelection:{bitrateFactorAtEmptyBuffer:2.8,bitrateAudioFactorAtEmptyBuffer:10,bitrateFactorAtFullBuffer:2,bitrateAudioFactorAtFullBuffer:7,minVideoAudioRatio:5,minAvailableThroughputAudioRatio:5,usePixelRatio:!0,pixelRatioMultiplier:void 0,pixelRatioLogBase:3,pixelRatioLogCoefficients:[1,0,1],limitByContainer:!0,containerSizeFactor:1.3,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldownIncreaseQuality:15e3,trackCooldownDecreaseQuality:3e3,backgroundVideoQualityLimit:Gn.Q_4320P,activeVideoAreaThreshold:.1,highQualityLimit:Gn.Q_720P,trafficSavingLimit:Gn.Q_480P},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:Gn.Q_480P},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,maxSegmentDurationLeftToSelectNextSegment:3e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:3e3,crashOnStallTimeout:25e3,crashOnStallTWithoutDataTimeout:5e3,enableSubSegmentBufferFeeding:!0,bufferEmptinessTolerance:100,useFetchPriorityHints:!0,qualityLimitsOnStall:{stallDurationNoDataBeforeQualityDecrease:500,stallCountBeforeQualityDecrease:3,resetQualityRestrictionTimeout:1e4},enableBaseUrlSupport:!0,maxSegmentRetryCount:5},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,maxLiveDuration:7200,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:250,playbackCatchupSpeedup:.05,isActiveOnDefault:!1,bufferEstimator:{emaAlpha:.45,changeThreshold:.05,deviationDepth:20,deviationFactor:.5,extremumInterval:5}}},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1,lowLatencyActiveLiveDelay:3e3,activeLiveDelay:5e3,maxPausedTime:5e3},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,forceFormat:void 0,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:"07A4434E",useWebmBigRequest:!1,webmCodec:"vp9",androidPreferredFormat:"dash",preferCMAF:!1,preferWebRTC:!1,preferMultiStream:!1,preferHDR:!1,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useHlsJs:!1,useNativeHLSTextTracks:!1,useManagedMediaSource:!0,useNewSwitchTo:!1,useSafariEndlessRequestBugfix:!0,useRefactoredSearchGap:!1,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,manifestRetryInterval:300,manifestRetryMaxInterval:1e4,manifestRetryMaxCount:10,audioVideoSyncRate:20,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50},useVolumeMultiplier:!1,ignoreAudioRendererError:!1,useEnableSubtitlesParam:!1,useOldMSEDetection:!1,useHlsLiveNewTextManager:!1,exposeInternalsToGlobal:!1,hlsLiveNewTextManagerDownloadThreshold:4e3,disableYandexPiP:!1,asyncResolveClientChecker:!1},BT=a=>{var e;return $(P({},v0(a,OT)),{configName:[...(e=a.configName)!=null?e:[],...OT.configName]})};import{assertNonNullable as Wn,combine as It,ErrorCategory as Yn,filter as D,filterChanged as K,fromEvent as xc,isNonNullable as P0,isNullable as w0,Logger as A0,map as G,mapTo as UT,merge as Gt,now as zn,once as F,Subject as X,Subscription as HT,tap as Pc,ValueSubject as w,isHigher as k0,isInvariantQuality as jT,flattenObject as Wt,throttle as wc,getTraceSubscriptionMethod as QT,Tracer as R0,InternalsExposure as L0}from"@vkontakte/videoplayer-shared/es2015";import{merge as S0,map as y0,filter as NT,isNonNullable as T0}from"@vkontakte/videoplayer-shared/es2015";var Ec=({seekState:a,position$:e})=>S0(a.stateChangeEnded$.pipe(y0(({to:t})=>{var r;return t.state==="none"?void 0:((r=t.position)!=null?r:NaN)/1e3}),NT(T0)),e.pipe(NT(()=>a.getState().state==="none")));import{assertNonNullable as I0}from"@vkontakte/videoplayer-shared/es2015";var FT=a=>{let e=typeof a.container=="string"?document.getElementById(a.container):a.container;return I0(e,`Wrong container or containerId {${a.container}}`),e};import{filter as E0,once as x0}from"@vkontakte/videoplayer-shared/es2015";var qT=(a,e,t,r)=>{a!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&(t==null?void 0:t.getValue().length)===0?t.pipe(E0(i=>i.length>0),x0()).subscribe(i=>{i.find(r)&&e.startTransitionTo(a)}):(a===void 0||t!=null&&t.getValue().find(r))&&e.startTransitionTo(a)};var Kn=class{constructor(e={configName:[]},t=R0.createRootTracer(!1)){this.subscription=new HT;this.logger=new A0;this.abrLogger=this.logger.createComponentLog("ABR");this.internalsExposure=null;this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new w(!1);this.hasLiveOffsetByPausedTimer=0;this.playerInited=new w(!1);this.wasSetStartedQuality=!1;this.desiredState={playbackState:new O("stopped"),seekState:new O({state:"none"}),volume:new O({volume:1,muted:!1}),videoTrack:new O(void 0),videoStream:new O(void 0),audioStream:new O(void 0),autoVideoTrackSwitching:new O(!0),autoVideoTrackLimits:new O({}),isLooped:new O(!1),isLowLatency:new O(!1),playbackRate:new O(1),externalTextTracks:new O([]),internalTextTracks:new O([]),currentTextTrack:new O(void 0),textTrackCuesSettings:new O({}),cameraOrientation:new O({x:0,y:0})};this.info={playbackState$:new w(void 0),position$:new w(0),duration$:new w(1/0),muted$:new w(!1),volume$:new w(1),availableVideoStreams$:new w([]),currentVideoStream$:new w(void 0),availableQualities$:new w([]),availableQualitiesFps$:new w({}),currentQuality$:new w(void 0),isAutoQualityEnabled$:new w(!0),autoQualityLimitingAvailable$:new w(!1),autoQualityLimits$:new w({}),predefinedQualityLimitType$:new w("unknown"),availableAudioStreams$:new w([]),currentAudioStream$:new w(void 0),availableAudioTracks$:new w([]),isAudioAvailable$:new w(!0),currentPlaybackRate$:new w(1),currentBuffer$:new w({start:0,end:0}),isBuffering$:new w(!0),isStalled$:new w(!1),isEnded$:new w(!1),isLooped$:new w(!1),isLive$:new w(void 0),isLiveEnded$:new w(null),canChangePlaybackSpeed$:new w(void 0),atLiveEdge$:new w(void 0),atLiveDurationEdge$:new w(void 0),liveTime$:new w(void 0),liveBufferTime$:new w(void 0),liveLatency$:new w(void 0),currentFormat$:new w(void 0),availableTextTracks$:new w([]),currentTextTrack$:new w(void 0),throughputEstimation$:new w(void 0),rttEstimation$:new w(void 0),videoBitrate$:new w(void 0),hostname$:new w(void 0),httpConnectionType$:new w(void 0),httpConnectionReused$:new w(void 0),surface$:new w("none"),chromecastState$:new w("NOT_AVAILABLE"),chromecastDeviceName$:new w(void 0),intrinsicVideoSize$:new w(void 0),availableSources$:new w(void 0),is3DVideo$:new w(!1),currentVideoSegmentLength$:new w(0),currentAudioSegmentLength$:new w(0)};this.events={inited$:new X,ready$:new X,started$:new X,playing$:new X,paused$:new X,stopped$:new X,willStart$:new X,willResume$:new X,willPause$:new X,willStop$:new X,willDestruct$:new X,watchCoverageRecord$:new X,watchCoverageLive$:new X,managedError$:new X,fatalError$:new X,fetcherRecoverableError$:new X,ended$:new X,looped$:new X,seeked$:new X,willSeek$:new X,autoplaySoundProhibited$:new X,firstBytes$:new X,loadedMetadata$:new X,firstFrame$:new X,canplay$:new X,log$:new X,fetcherError$:new X,severeStallOccured$:new X};this.experimental={element$:new w(void 0),tuningConfigName$:new w([]),enableDebugTelemetry$:new w(!1),dumpTelemetry:Jg,getCurrentTime$:new w(null)};if(this.initLogs(),this.tuning=BT(e),this.tracer=t,this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new Ss({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new _T(this.tuning.throughputEstimator),e.exposeInternalsToGlobal&&(this.internalsExposure=new L0("CORE"),this.internalsExposure.expose({player:this})),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(r,i,s)=>{let n=Reflect.get(r,i,s);return typeof n!="function"?n:(...o)=>{try{return n.apply(r,o)}catch(u){let l=o.map(p=>JSON.stringify(p,(h,m)=>{let b=typeof m;return(0,GT.default)(["number","string","boolean"],b)?m:m===null?null:`<${b}>`})),c=`Player.${String(i)}`,d=`Exception calling ${c} (${l.join(", ")})`;throw this.events.fatalError$.next({id:c,category:Yn.WTF,message:d,thrown:u}),u}}}})}initVideo(e){var i;this.config=e,(i=this.internalsExposure)==null||i.expose({config:e,logger:this.logger,tuning:this.tuning});let t=()=>{var u,l,c;let o=e,{container:s}=o,n=hd(o,["container"]);this.tracer.log("initVideo",Wt(n)),this.domContainer=FT(e),this.chromecastInitializer.contentId=(u=e.meta)==null?void 0:u.videoId,this.providerContainer=new Ka({sources:e.sources,meta:(l=e.meta)!=null?l:{},failoverHosts:(c=e.failoverHosts)!=null?c:[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,tracer:this.tracer,logger:this.logger,abrLogger:this.abrLogger},tuning:this.tuning,volumeMultiplier:e.volumeMultiplier}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.initTracerSubscription(),this.providerContainer.init(),this.setLiveLowLatency(this.tuning.dashCmafLive.lowLatency.isActiveOnDefault),this.setMuted(this.tuning.isAudioDisabled),this.initDebugTelemetry(),this.initWakeLock(),this.playerInited.next(!0)},r=()=>{this.tuning.asyncResolveClientChecker?N.isInited$.pipe(D(s=>!!s),F()).subscribe(()=>{console.log("Core SDK async start"),t()}):t()};return this.isNotActiveTabCase()?(this.tracer.log("request play from hidden tab"),xc(document,"visibilitychange").pipe(F()).subscribe(r)):r(),this}destroy(){var e,t;this.tracer.log("destroy"),window.clearTimeout(this.hasLiveOffsetByPausedTimer),this.events.willDestruct$.next(),this.stop(),(e=this.providerContainer)==null||e.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe(),this.tracer.end(),(t=this.internalsExposure)==null||t.destroy()}prepare(){return this.playerInited.pipe(D(e=>!!e),F()).subscribe(()=>{let e=this.desiredState.playbackState;this.tracer.log("prepare",{currentPlayBackState:e.getState()}),e.getState()==="stopped"&&e.startTransitionTo("ready")}),this}play(){return this.playerInited.pipe(D(e=>!!e),F()).subscribe(()=>{let e=this.desiredState.playbackState;this.tracer.log("play",{currentPlayBackState:e.getState()}),e.getState()!=="playing"&&e.startTransitionTo("playing")}),this}pause(){return this.playerInited.pipe(D(e=>!!e),F()).subscribe(()=>{let e=this.desiredState.playbackState;this.tracer.log("pause",{currentPlayBackState:e.getState()}),e.getState()!=="paused"&&e.startTransitionTo("paused")}),this}stop(){return this.playerInited.pipe(D(e=>!!e),F()).subscribe(()=>{let e=this.desiredState.playbackState;this.tracer.log("stop",{currentPlayBackState:e.getState()}),e.getState()!=="stopped"&&e.startTransitionTo("stopped")}),this}seekTime(e,t=!0){return this.playerInited.pipe(D(r=>!!r),F()).subscribe(()=>{let r=this.info.duration$.getValue(),i=this.info.isLive$.getValue(),s=e;e>=r&&!i&&(s=r-.2),this.tracer.log("seekTime",{duration:r,isLive:i,time:e,calculatedTime:s,forcePrecise:t}),Number.isFinite(s)&&(this.events.willSeek$.next({from:this.getExactTime(),to:s}),this.desiredState.seekState.setState({state:"requested",position:s*1e3,forcePrecise:t}))}),this}seekPercent(e){return this.playerInited.pipe(D(t=>!!t),F()).subscribe(()=>{let t=this.info.duration$.getValue();this.tracer.log("seekPercent",{percent:e,duration:t}),isFinite(t)&&this.seekTime(Math.abs(t)*e,!1)}),this}setVolume(e,t){return this.playerInited.pipe(D(r=>!!r),F()).subscribe(()=>{let r=this.desiredState.volume,i=this.info.muted$.getValue(),s=t!=null?t:this.tuning.isAudioDisabled||i;this.tracer.log("setVolume",{volume:e,isAudioDisabled:this.tuning.isAudioDisabled,chromecastState:this.chromecastInitializer.castState$.getValue(),muted:s}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setVolume(e):r.startTransitionTo({volume:e,muted:s})}),this}setMuted(e){return this.playerInited.pipe(D(t=>!!t),F()).subscribe(()=>{let t=this.tuning.isAudioDisabled||e,r=this.info.volume$.getValue();this.tracer.log("setMuted",{isMuted:e,nextMuted:t,volume:r,isAudioDisabled:this.tuning.isAudioDisabled,chromecastState:this.chromecastInitializer.castState$.getValue()}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setMuted(t):this.desiredState.volume.startTransitionTo({volume:r,muted:t})}),this}setVideoStream(e){return this.playerInited.pipe(D(t=>!!t),F()).subscribe(()=>{this.desiredState.videoStream.startTransitionTo(e)}),this}setAudioStream(e){return this.playerInited.pipe(D(t=>!!t),F()).subscribe(()=>{this.desiredState.audioStream.startTransitionTo(e)}),this}setQuality(e){return this.playerInited.pipe(D(t=>!!t),F()).subscribe(()=>{Wn(this.providerContainer);let t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();this.tracer.log("setQuality",{isDelayed:t.length===0,quality:e}),this.desiredState.videoTrack.getState()===void 0&&this.desiredState.videoTrack.getPrevState()===void 0&&t.length===0?this.wasSetStartedQuality?this.providerContainer.providerOutput.availableVideoTracks$.pipe(D(r=>r.length>0),F()).subscribe(r=>{this.setVideoTrackIdByQuality(r,e)}):this.explicitInitialQuality=e:t.length>0&&this.setVideoTrackIdByQuality(t,e)}),this}setAutoQuality(e){return this.playerInited.pipe(D(t=>!!t),F()).subscribe(()=>{this.tracer.log("setAutoQuality",{enable:e}),this.desiredState.autoVideoTrackSwitching.startTransitionTo(e)}),this}setAutoQualityLimits(e){return this.playerInited.pipe(D(t=>!!t),F()).subscribe(()=>{this.tracer.log("setAutoQualityLimits",Wt(e)),this.desiredState.autoVideoTrackLimits.startTransitionTo(e)}),this}setPredefinedQualityLimits(e){return this.playerInited.pipe(D(t=>!!t),F()).subscribe(()=>{if(this.info.predefinedQualityLimitType$.getValue()===e)return this;let{highQualityLimit:t,trafficSavingLimit:r}=this.tuning.autoTrackSelection,i;switch(e){case"high_quality":i={min:t,max:void 0};break;case"traffic_saving":i={max:r,min:void 0};break;default:i={max:void 0,min:void 0}}this.setAutoQualityLimits(i)}),this}setPlaybackRate(e){return this.playerInited.pipe(D(t=>!!t),F()).subscribe(()=>{var r;Wn(this.providerContainer);let t=(r=this.providerContainer)==null?void 0:r.providerOutput.element$.getValue();this.tracer.log("setPlaybackRate",{playbackRate:e,isVideoElementAvailable:!!t}),t&&(this.desiredState.playbackRate.setState(e),t.playbackRate=e)}),this}setExternalTextTracks(e){return this.playerInited.pipe(D(t=>!!t),F()).subscribe(()=>{e.length&&this.tracer.log("setExternalTextTracks",Wt(e)),this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>P({type:"external"},t)))}),this}selectTextTrack(e){return this.playerInited.pipe(D(t=>!!t),F()).subscribe(()=>{var t;qT(e,this.desiredState.currentTextTrack,(t=this.providerContainer)==null?void 0:t.providerOutput.availableTextTracks$,r=>r.id===e),this.tracer.log("selectTextTrack",{textTrackId:e})}),this}setTextTrackCueSettings(e){return this.playerInited.pipe(D(t=>!!t),F()).subscribe(()=>{this.tracer.log("setTextTrackCueSettings",P({},e)),this.desiredState.textTrackCuesSettings.startTransitionTo(e)}),this}setLiveLowLatency(e){let t=this.info.isLive$.getValue(),r=this.desiredState.isLowLatency.getState();return!t||r===e?this:(this.tracer.log("live switch to low latency "+e),this.desiredState.isLowLatency.setState(e),this.seekTime(0))}setLooped(e){return this.playerInited.pipe(D(t=>!!t),F()).subscribe(()=>{this.tracer.log("setLooped",{isLooped:e}),this.desiredState.isLooped.startTransitionTo(e)}),this}toggleChromecast(){this.tracer.log("toggleChromecast"),this.chromecastInitializer.toggleConnection()}startCameraManualRotation(e,t){return this.playerInited.pipe(D(r=>!!r),F()).subscribe(()=>{let r=this.getScene3D();this.tracer.log("startCameraManualRotation",{isScene3DAvailable:!!r,mx:e,my:t}),r&&r.startCameraManualRotation(e,t)}),this}stopCameraManualRotation(e=!1){return this.playerInited.pipe(D(t=>!!t),F()).subscribe(()=>{let t=this.getScene3D();this.tracer.log("stopCameraManualRotation",{isScene3DAvailable:!!t,immediate:e}),t&&t.stopCameraManualRotation(e)}),this}moveCameraFocusPX(e,t){return this.playerInited.pipe(D(r=>!!r),F()).subscribe(()=>{let r=this.getScene3D();if(this.tracer.log("moveCameraFocusPX",{isScene3DAvailable:!!r,dxpx:e,dypx:t}),r){let i=r.getCameraRotation(),s=r.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:i.x+s.x,y:i.y+s.y})}}),this}holdCamera(){return this.playerInited.pipe(D(e=>e),F()).subscribe(()=>{let e=this.getScene3D();e&&e.holdCamera()}),this}releaseCamera(){return this.playerInited.pipe(D(e=>!!e),F()).subscribe(()=>{let e=this.getScene3D();e&&e.releaseCamera()}),this}getExactTime(){if(!this.providerContainer)return 0;let e=this.providerContainer.providerOutput.element$.getValue();if(w0(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),r=t.state==="none"?void 0:t.position;return P0(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(Gt(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(G(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(G(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(G(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(G(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(G(e=>e.to)).subscribe(e=>{this.info.autoQualityLimits$.next(e);let{highQualityLimit:t,trafficSavingLimit:r}=this.tuning.autoTrackSelection;this.info.predefinedQualityLimitType$.next(ul({limits:e,highQualityLimit:t,trafficSavingLimit:r}))})),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(D(({from:e})=>e==="stopped"),F()).subscribe(()=>{this.initedAt=zn(),this.events.inited$.next()})).add(this.desiredState.playbackState.stateChangeEnded$.subscribe(e=>{switch(e.to){case"ready":this.events.ready$.next();break;case"playing":this.isPlaybackStarted||this.events.started$.next(),this.isPlaybackStarted=!0,this.events.playing$.next();break;case"paused":this.events.paused$.next();break;case"stopped":this.events.stopped$.next()}})).add(this.desiredState.playbackState.stateChangeStarted$.subscribe(e=>{switch(e.to){case"paused":this.events.willPause$.next();break;case"playing":this.isPlaybackStarted?this.events.willResume$.next():this.events.willStart$.next();break;case"stopped":this.events.willStop$.next();break;default:}}))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();this.tracer.log("willSeekEvent",Wt(n)),n.state==="requested"?this.desiredState.seekState.setState($(P({},n),{state:"applying"})):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:Yn.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.soundProhibitedEvent$.pipe(F()).subscribe(this.events.autoplaySoundProhibited$)).add(e.providerOutput.severeStallOccurred$.subscribe(this.events.severeStallOccured$)).add(e.providerOutput.seekedEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();this.tracer.log("seekedEvent",Wt(n)),n.state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe(G(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(G(n=>n.destination),K()).subscribe(()=>this.isPlaybackStarted=!1)).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add(It({availableVideoTracks:e.providerOutput.availableVideoTracks$,currentVideoStream:e.providerOutput.currentVideoStream$}).pipe(G(({availableVideoTracks:n,currentVideoStream:o})=>n.filter(u=>o?o.id===u.streamId:!0).map(({quality:u})=>u).sort((u,l)=>jT(u)?1:jT(l)?-1:k0(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(K()).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(K((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.pipe(K((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe(K()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(K()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(K()).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(G(n=>n?{start:n.from,end:n.to}:{start:0,end:0})).subscribe(this.info.currentBuffer$)).add(e.providerOutput.duration$.subscribe(this.info.duration$)).add(e.providerOutput.isBuffering$.subscribe(this.info.isBuffering$)).add(e.providerOutput.isLive$.subscribe(this.info.isLive$)).add(e.providerOutput.isLiveEnded$.pipe(Pc(n=>n&&this.stop())).subscribe(this.info.isLiveEnded$)).add(e.providerOutput.canChangePlaybackSpeed$.subscribe(this.info.canChangePlaybackSpeed$)).add(e.providerOutput.liveTime$.subscribe(this.info.liveTime$)).add(e.providerOutput.liveBufferTime$.subscribe(this.info.liveBufferTime$)).add(e.providerOutput.liveLatency$.subscribe(this.info.liveLatency$)).add(It({hasLiveOffsetByPaused:Gt(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(G(n=>n.to),K(),G(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(It({atLiveEdge:It({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:Ec({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(G(({isLive:n,position:o,isLowLatency:u})=>{let l=this.getActiveLiveDelay(u);return n&&Math.abs(o)<l/1e3}),K(),Pc(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(G(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add(It({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(G(({isLive:n,position:o,duration:u})=>n&&(Math.abs(u)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),K(),Pc(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(G(n=>n.muted),K()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(G(n=>n.volume),K()).subscribe(this.info.volume$)).add(Ec({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(Gt(e.providerOutput.endedEvent$.pipe(UT(!0)),e.providerOutput.seekedEvent$.pipe(UT(!1))).pipe(K()).subscribe(this.info.isEnded$)).add(e.providerOutput.endedEvent$.subscribe(this.events.ended$)).add(e.providerOutput.loopedEvent$.subscribe(this.events.looped$)).add(e.providerError$.subscribe(this.events.managedError$)).add(e.providerOutput.fetcherRecoverableError$.subscribe(this.events.fetcherRecoverableError$)).add(e.providerOutput.fetcherError$.subscribe(this.events.fatalError$)).add(e.volumeMultiplierError$.subscribe(this.events.managedError$)).add(e.noAvailableProvidersError$.pipe(G(n=>({id:n?`No${n}`:"NoProviders",category:Yn.VIDEO_PIPELINE,message:n?`${n} was forced but failed or not available`:"No suitable providers or all providers failed"}))).subscribe(this.events.fatalError$)).add(e.providerOutput.element$.subscribe(this.experimental.element$)).add(e.providerOutput.getCurrentTime$.subscribe(this.experimental.getCurrentTime$)).add(e.providerOutput.firstBytesEvent$.pipe(F(),G(n=>n!=null?n:zn()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe(F(),G(()=>zn()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(F(),G(()=>zn()-this.initedAt)).subscribe(this.events.canplay$)).add(this.throughputEstimator.throughput$.subscribe(this.info.throughputEstimation$)).add(this.throughputEstimator.rtt$.subscribe(this.info.rttEstimation$)).add(e.providerOutput.availableSources$.subscribe(this.info.availableSources$));let t=new w(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let r=new w(!0);this.subscription.add(e.current$.subscribe(()=>r.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(D(({to:n})=>n==="playing"),F()).subscribe(()=>r.next(!1)));let i=0,s=Gt(e.providerOutput.isBuffering$,t,r).pipe(G(()=>{let n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||r.getValue();return n&&!o}),K());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(Gt(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(Gt(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,e.providerOutput.elementVisible$,this.chromecastInitializer.castState$).subscribe(()=>{let n=e.providerOutput.inPiP$.getValue(),o=e.providerOutput.inFullscreen$.getValue(),u=e.providerOutput.element$.getValue(),l=e.providerOutput.elementVisible$.getValue(),c=this.chromecastInitializer.castState$.getValue(),d;c==="CONNECTED"?d="second_screen":u?l?n?d="pip":o?d="fullscreen":d="inline":d="invisible":d="none",this.info.surface$.getValue()!==d&&this.info.surface$.next(d)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(G(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 HT;this.subscription.add(t),this.subscription.add(e.current$.pipe(K((r,i)=>r.provider===i.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(D(r=>r.length>0),F()).subscribe(r=>{this.setStartingVideoTrack(r)}))}))}setStartingVideoTrack(e){var i;let t;this.wasSetStartedQuality=!0;let r=(i=this.explicitInitialQuality)!=null?i:this.info.currentQuality$.getValue();r&&(t=e.find(({quality:s})=>s===r),t||this.setAutoQuality(!0)),t||(t=Ft(e,{container:this.domContainer.getBoundingClientRect(),estimatedThroughput:this.throughputEstimator.throughput$.getValue(),tuning:this.tuning.autoTrackSelection,limits:this.desiredState.autoVideoTrackLimits.getState(),playbackRate:this.info.currentPlaybackRate$.getValue(),forwardBufferHealth:0,abrLogger:this.abrLogger})),this.desiredState.videoTrack.startTransitionTo(t),this.info.currentQuality$.next(t.quality),this.info.videoBitrate$.next(t.bitrate)}initLogs(){this.subscription.add(Gt(this.desiredState.videoTrack.stateChangeStarted$.pipe(G(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(G(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(G(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(G(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(G(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(G(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(G(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(G(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(G(e=>({component:"desiredState",message:`[${e.entity} change] ${e.type}: ${JSON.stringify(e.transition)}`}))).subscribe(this.logger.log)),this.subscription.add(this.logger.log$.subscribe(this.events.log$))}initDebugTelemetry(){var t;let e=(t=this.providerContainer)==null?void 0:t.providerOutput;Wn(this.providerContainer),Wn(e),Xg(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(r=>Kg(r)),this.providerContainer.current$.subscribe(({type:r})=>Hi("provider",r)),e.duration$.subscribe(r=>Hi("duration",r)),e.availableVideoTracks$.pipe(D(r=>!!r.length),F()).subscribe(r=>Hi("tracks",r)),this.events.fatalError$.subscribe(new Ie("fatalError")),this.events.managedError$.subscribe(new Ie("managedError")),e.position$.subscribe(new Ie("position")),e.currentVideoTrack$.pipe(G(r=>r==null?void 0:r.quality)).subscribe(new Ie("quality")),this.info.currentBuffer$.subscribe(new Ie("buffer")),e.isBuffering$.subscribe(new Ie("isBuffering"))].forEach(r=>this.subscription.add(r)),Hi("codecs",N.video.supportedCodecs)}initTracerSubscription(){let e=QT(this.tracer.log.bind(this.tracer)),t=QT(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(K()).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(It({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe(D(({currentQuality:r,videoBitrate:i})=>!!r&&!!i),K((r,i)=>r.currentQuality===i.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe(D(r=>r>0),K()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe(D(r=>r>0),K()).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(It({currentBuffer:this.info.currentBuffer$.pipe(D(r=>r.end>0),K((r,i)=>r.end===i.end&&r.start===i.start)),position:this.info.position$.pipe(K())}).pipe(wc(1e3)).subscribe(e("currentBufferAndPosition"))).add(this.info.duration$.pipe(K()).subscribe(e("duration"))).add(this.info.isBuffering$.subscribe(e("isBuffering"))).add(this.info.isLive$.pipe(K()).subscribe(e("isLive"))).add(this.info.canChangePlaybackSpeed$.pipe(K()).subscribe(e("canChangePlaybackSpeed"))).add(It({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe(D(({liveTime:r,liveBufferTime:i})=>!!r&&!!i),wc(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe(K(),D(r=>r===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe(K(),D(r=>r===!0)).subscribe(e("atLiveDurationEdge"))).add(this.info.muted$.pipe(K()).subscribe(e("muted"))).add(this.info.volume$.pipe(K()).subscribe(e("volume"))).add(this.info.isEnded$.pipe(K(),D(r=>r===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add(It({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe(D(({throughputEstimation:r,rtt:i})=>!!r&&!!i),wc(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe(K(),D(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=()=>x(this,null,function*(){t(),e=yield window.navigator.wakeLock.request("screen").catch(i=>{i instanceof DOMException&&i.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:Yn.DOM,message:String(i)})})});this.subscription.add(Gt(xc(document,"visibilitychange"),xc(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",Wt({quality:t,availableTracks:Wt(e),track:Wt(r),isAutoQuality:!r})),r?this.desiredState.videoTrack.startTransitionTo(r):this.setAutoQuality(!0)}getActiveLiveDelay(e=!1){return e?this.tuning.live.lowLatencyActiveLiveDelay:this.tuning.live.activeLiveDelay}isNotActiveTabCase(){return document.hidden&&this.tuning.autoplayOnlyInActiveTab&&!Ki()}};import{Subscription as Y5,Observable as z5,Subject as K5,ValueSubject as X5,VideoQuality as J5}from"@vkontakte/videoplayer-shared/es2015";var Z5=`@vkontakte/videoplayer-core@${md}`;export{ps as ChromecastState,ao as HttpConnectionType,z5 as Observable,Me as PlaybackState,Kn as Player,hs as PredefinedQualityLimits,Z5 as SDK_VERSION,K5 as Subject,Y5 as Subscription,so as Surface,md as VERSION,X5 as ValueSubject,pt as VideoFormat,J5 as VideoQuality,N as clientChecker,Ui as isMobile};
|
|
124
|
+
`;var Cn=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 Mn(this.params.fov,this.params.orientation),this.cameraRotationManager=new Dn(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(Hy,this.gl.VERTEX_SHADER),r=this.createShader(jy,this.gl.FRAGMENT_SHADER);if(this.gl.attachShader(e,t),this.gl.attachShader(e,r),this.gl.linkProgram(e),!this.gl.getProgramParameter(e,this.gl.LINK_STATUS))throw this.destroy(),new Error("Could not link shader program.");return e}createTexture(){let e=this.gl.createTexture();if(!e)throw this.destroy(),new Error("Could not create texture");return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.bindTexture(this.gl.TEXTURE_2D,null),e}updateTexture(){this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,!0),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.sourceVideoElement),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}createVertexBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create vertex buffer");let t=1,r=1,i=this.frameHeight/(this.frameWidth/this.viewportWidth);return i>this.viewportHeight?t=this.viewportHeight/i:r=i/this.viewportHeight,this.gl.bindBuffer(this.gl.ARRAY_BUFFER,e),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-t,-r,t,-r,t,r,-t,r]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),e}createTextureMappingBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create texture mapping buffer");return e}calculateTexturePosition(){let e=.5-this.camera.orientation.x/360,t=.5-this.camera.orientation.y/180,r=this.camera.fov.x/360/2,i=this.camera.fov.y/180/2,s=e-r,n=t-i,o=e+r,u=t-i,l=e+r,c=t+i,d=e-r,p=t+i;return[s,n,o,u,l,c,d,p]}updateTextureMappingBuffer(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([...this.calculateTexturePosition()]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}updateFrameSize(){this.frameWidth=this.sourceVideoElement.videoWidth,this.frameHeight=this.sourceVideoElement.videoHeight}createCanvas(){let e=document.createElement("canvas");return e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e}};import{isNullable as UD,now as Qy,Subscription as HD,filter as jD,combine as Gy,ValueSubject as oc,isNonNullable as QD,debounce as GD}from"@vkontakte/videoplayer-shared/es2015";var uc=class{constructor(){this.isSeeked$=new oc(!1);this.isBuffering$=new oc(!1);this.currentStallsCount=0;this.maxQualityLimit=void 0;this.lastUniqueVideoTrackSelectedTimestamp=0;this.predictedThroughputWithoutData=0;this.subscription=new HD;this.severeStallOccurred$=new oc(!1)}connect(e){this.currentStallDuration$=e.currentStallDuration$,this.videoLastDataObtainedTimestamp$=e.videoLastDataObtainedTimestamp$,this.throughput$=e.throughput$,this.rtt$=e.rtt$,this.qualityLimitsOnStall=e.qualityLimitsOnStall,this.subscription.add(e.isSeeked$.subscribe(this.isSeeked$)),this.subscription.add(e.isBuffering$.subscribe(this.isBuffering$)),this.subscription.add(e.looped$.subscribe(t=>this.currentStallsCount=0)),this.subscription.add(Gy({isBuffering:this.isBuffering$.pipe(GD(this.qualityLimitsOnStall.stallDurationToBeCount)),isSeeked:this.isSeeked$}).pipe(jD(({isBuffering:t,isSeeked:r})=>t&&!r)).subscribe(t=>{this.currentStallsCount++})),this.subscription.add(Gy({currentStallDuration:this.currentStallDuration$}).subscribe(({currentStallDuration:t})=>{let{stallDurationNoDataBeforeQualityDecrease:r,stallCountBeforeQualityDecrease:i,resetQualityRestrictionTimeout:s,ignoreStallsOnSeek:n}=this.qualityLimitsOnStall;if(UD(this.lastUniqueVideoTrackSelected)||n&&this.isSeeked$.getValue())return;let o=this.rtt$.getValue(),u=this.throughput$.getValue(),l=this.videoLastDataObtainedTimestamp$.getValue(),c=Qy(),d=i&&this.currentStallsCount>=i,p=r&&c-this.lastUniqueVideoTrackSelectedTimestamp>=r+o&&c-l>=r+o&&t>=r;(d||p)&&(this.severeStallOccurred$.next(!0),window.clearTimeout(this.qualityRestrictionTimer),this.maxQualityLimit=this.lastUniqueVideoTrackSelected.quality,QD(this.lastUniqueVideoTrackSelected.bitrate)&&u>this.lastUniqueVideoTrackSelected.bitrate&&(this.predictedThroughputWithoutData=this.lastUniqueVideoTrackSelected.bitrate)),t||(this.severeStallOccurred$.next(!1),window.clearTimeout(this.qualityRestrictionTimer),this.qualityRestrictionTimer=window.setTimeout(()=>{this.maxQualityLimit=void 0,this.predictedThroughputWithoutData=0},s))}))}get videoMaxQualityLimit(){return this.maxQualityLimit}get predictedThroughput(){return this.predictedThroughputWithoutData}set lastVideoTrackSelected(e){var t;((t=this.lastUniqueVideoTrackSelected)==null?void 0:t.id)!==e.id&&(this.lastUniqueVideoTrackSelected=e,this.lastUniqueVideoTrackSelectedTimestamp=Qy(),this.currentStallsCount=0)}destroy(){window.clearTimeout(this.qualityRestrictionTimer),this.subscription.unsubscribe()}},Wy=uc;import{combine as WD,map as YD,observeElementSize as zD,Subscription as KD,ValueSubject as lc,noop as XD}from"@vkontakte/videoplayer-shared/es2015";var Vn=class{constructor(){this.subscription=new KD;this.pipSize$=new lc(void 0);this.videoSize$=new lc(void 0);this.elementSize$=new lc(void 0);this.pictureInPictureWindowRemoveEventListener=XD}connect({observableVideo:e,video:t}){let r=i=>{let s=i.target;this.pipSize$.next({width:s.width,height:s.height})};this.subscription.add(zD(t).subscribe(this.videoSize$)).add(e.enterPip$.subscribe(({pictureInPictureWindow:i})=>{this.pipSize$.next({width:i.width,height:i.height}),i.addEventListener("resize",r),this.pictureInPictureWindowRemoveEventListener=()=>{i.removeEventListener("resize",r)}})).add(e.leavePip$.subscribe(()=>{this.pictureInPictureWindowRemoveEventListener()})).add(WD({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe(YD(({videoSize:i,inPip:s,pipSize:n})=>s?n:i)).subscribe(this.elementSize$))}getValue(){return this.elementSize$.getValue()}subscribe(e,t){return this.elementSize$.subscribe(e,t)}getObservable(){return this.elementSize$}destroy(){this.pictureInPictureWindowRemoveEventListener(),this.subscription.unsubscribe()}};var Sr=class{constructor(e){this.subscription=new iC;this.videoState=new N("stopped");this.droppedFramesManager=new mn;this.stallsManager=new Wy;this.elementSizeManager=new Vn;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new Wi;this.audioTrackSwitchHistory=new Wi;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),i=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(i.state==="requested"&&(r==null?void 0:r.to)!=="paused"&&e!=="stopped"&&t!=="stopped"&&this.seek(i.position,i.forcePrecise),t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.player.stop(),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),A(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"),A(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="ready"&&A(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):t==="playing"&&this.video.paused?this.playIfAllowed():(r==null?void 0:r.to)==="playing"&&A(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&A(this.params.desiredState.playbackState,"paused");return;default:return ZD(e)}}};this.init3DScene=e=>{var r,i,s;if(this.scene3D)return;this.scene3D=new Cn(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:((r=e.projectionData)==null?void 0:r.pose.yaw)||0,y:((i=e.projectionData)==null?void 0:i.pose.pitch)||0,z:((s=e.projectionData)==null?void 0:s.pose.roll)||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});let t=this.elementSizeManager.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};this.textTracksManager=new Ue(e.source.url),this.params=e,this.video=we(e.container,e.tuning),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(de(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.player=new Ln({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode,tracer:this.tracer}),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params,r=Re(this.video),i=this.constructor.name,s=o=>{e.error$.next({id:i,category:Yy.WTF,message:`${i} internal logic error`,thrown:o})};return{output:e,desiredState:t,observableVideo:r,genericErrorListener:s,connect:(o,u)=>this.subscription.add(o.subscribe(u,s))}}subscribe(){let{output:e,desiredState:t,observableVideo:r,genericErrorListener:i,connect:s}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe(zy(l=>!!l.length),Xy()).subscribe(l=>{this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:r.playing$,pause$:r.pause$,tracks:l})}));let n=this.params.desiredState.seekState.stateChangeEnded$.pipe(cc(l=>l.to.state!=="none"),qa());this.stallsManager.connect({isSeeked$:n,currentStallDuration$:this.player.currentStallDuration$.pipe(qa()),videoLastDataObtainedTimestamp$:this.player.videoLastDataObtainedTimestamp$,throughput$:this.params.dependencies.throughputEstimator.throughput$,rtt$:this.params.dependencies.throughputEstimator.rtt$,qualityLimitsOnStall:this.params.tuning.dash.qualityLimitsOnStall,isBuffering$:r.isBuffering$,looped$:r.looped$}),s(r.ended$,e.endedEvent$),s(r.looped$,e.loopedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentBuffer$),s(r.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),s(r.loadedMetadata$,e.loadedMetadataEvent$),s(this.player.error$,e.error$),s(this.player.fetcherRecoverableError$,e.fetcherRecoverableError$),s(this.player.fetcherError$,e.fetcherError$),s(this.player.lastConnectionType$,e.httpConnectionType$),s(this.player.lastConnectionReused$,e.httpConnectionReused$),s(this.player.isLive$,e.isLive$),s(this.player.lastRequestFirstBytes$.pipe(zy(Ky),Xy()),e.firstBytesEvent$),s(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),s(this.videoState.stateChangeEnded$.pipe(cc(l=>l.to)),this.params.output.playbackState$),this.subscription.add(r.loopExpected$.subscribe(l=>{t.seekState.setState({state:"requested",position:0,forcePrecise:!1})})),this.subscription.add(r.looped$.subscribe(()=>this.player.warmUpMediaSourceIfNeeded(),i)),this.subscription.add(r.seeked$.subscribe(e.seekedEvent$,i)),this.subscription.add(ot(this.video,t.isLooped,i)),this.subscription.add(ke(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(qe(this.video,t.playbackRate,r.playbackRateState$,i)),this.elementSizeManager.connect({video:this.video,observableVideo:r}),s(He(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),A(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),A(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:l})=>{if(l==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let c=this.player.getStreams();if(eC(c,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let p=[];for(let h of c.audio){p.push(jl(h));let m=[];for(let b of h.representations){let g=gy(b);m.push(g),this.audioTracksMap.set(g,{stream:h,representation:b})}this.audioStreamsMap.set(h,m)}this.params.output.availableAudioStreams$.next(p)}let d=[];for(let p of c.video){d.push(Ql(p));let h=[];for(let m of p.representations){let b=by(M(P({},m),{streamId:p.id}));b&&(h.push(b),this.videoTracksMap.set(b,{stream:p,representation:m}))}this.videoStreamsMap.set(p,h)}this.params.output.availableVideoStreams$.next(d);for(let p of c.text)for(let h of p.representations){let m=vy(p,h);this.textTracksMap.set(m,{stream:p,representation:h})}this.params.output.availableVideoTracks$.next(Array.from(this.videoTracksMap.keys())),this.params.output.availableAudioTracks$.next(Array.from(this.audioTracksMap.keys())),this.params.output.isAudioAvailable$.next(!!this.audioTracksMap.size),this.audioTracksMap.size&&this.textTracksMap.size&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else l==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},i)),this.subscription.add(On(this.player.currentStallDuration$,this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,t.videoStream.stateChangeStarted$,t.audioStream.stateChangeStarted$,this.elementSizeManager.getObservable(),this.params.output.elementVisible$,this.droppedFramesManager.onDroopedVideoFramesLimit$,rC(this.video,"progress")).subscribe(()=>E(this,null,function*(){let l=this.player.state$.getState(),c=this.player.state$.getTransition();if(!(0,Jy.default)(["manifest_ready","running"],l)||c)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let d=this.selectVideoAudioRepresentations();if(!d)return;let[p,h]=d,m=[...this.videoTracksMap.keys()].find(g=>{var v;return((v=this.videoTracksMap.get(g))==null?void 0:v.representation.id)===p.id});Ky(m)&&(this.stallsManager.lastVideoTrackSelected=m);let b=this.params.desiredState.autoVideoTrackLimits.getTransition();if(b&&this.params.output.autoVideoTrackLimits$.next(b.to),l==="manifest_ready")yield this.player.initRepresentations(p.id,h==null?void 0:h.id,this.params.sourceHls);else if(yield this.player.switchRepresentation("video",p.id),h){let g=!!t.audioStream.getTransition();yield this.player.switchRepresentation("audio",h.id,g)}}),i)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:l})=>{this.scene3D&&l&&this.scene3D.pointCameraTo(l.x,l.y)})),this.subscription.add(this.elementSizeManager.subscribe(l=>{this.scene3D&&l&&this.scene3D.setViewportSize(l.width,l.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(qa()).subscribe(l=>{let c=[...this.videoTracksMap.entries()].find(([,{representation:m}])=>m.id===l);if(!c){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[d,{stream:p}]=c,h=this.params.desiredState.videoStream.getTransition();h&&h.to&&h.to.id===p.id&&this.params.desiredState.videoStream.setState(h.to),e.currentVideoTrack$.next(d),e.currentVideoStream$.next(Ql(p))},i)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(qa()).subscribe(l=>{let c=[...this.audioTracksMap.entries()].find(([,{representation:m}])=>m.id===l);if(!c){e.currentAudioStream$.next(void 0);return}let[d,{stream:p}]=c,h=this.params.desiredState.audioStream.getTransition();h&&h.to&&h.to.id===p.id&&this.params.desiredState.audioStream.setState(h.to),e.currentAudioStream$.next(jl(p))},i)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(l=>{var c,d;if(l!=null&&l.is3dVideo&&((c=this.params.tuning.spherical)!=null&&c.enabled))try{this.init3DScene(l),e.is3DVideo$.next(!0)}catch(p){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${p}`})}else this.destroy3DScene(),(d=this.params.tuning.spherical)!=null&&d.enabled&&e.is3DVideo$.next(!1)},i)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,i)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,i)),this.textTracksManager.connect(this.video,t,e);let o=t.playbackState.stateChangeStarted$.pipe(cc(({to:l})=>l==="ready"),qa());this.subscription.add(On(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,dc(["init"])).subscribe(()=>{let l=t.autoVideoTrackSwitching.getState(),d=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:l?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(d)})),this.subscription.add(On(o,this.player.state$.stateChangeEnded$,dc(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let u=On(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,dc(["init"])).pipe(tC(0));this.subscription.add(u.subscribe(this.syncPlayback,i))}selectVideoAudioRepresentations(){var C,L,O,Q,G,R,z,q,Z,k,D,x,U;if(this.player.isStreamEnded)return;let{desiredState:e,output:t}=this.params,r=e.autoVideoTrackSwitching.getState(),i=(C=e.videoTrack.getState())==null?void 0:C.id,n=[...this.videoTracksMap.keys()].find(({id:_})=>_===i),o=t.currentVideoTrack$.getValue(),u=((Q=(O=e.videoStream.getState())!=null?O:n&&((L=this.videoTracksMap.get(n))==null?void 0:L.stream))!=null?Q:this.videoStreamsMap.size===1)?this.videoStreamsMap.keys().next().value:void 0;if(!u)return;let l=[...this.videoStreamsMap.keys()].find(({id:_})=>_===u.id),c=l&&this.videoStreamsMap.get(l);if(!c)return;let d=Jr(this.video.buffered,this.video.currentTime*1e3),p;this.player.isActiveLive$.getValue()?p=this.player.isLowLatency$.getValue()?this.params.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.params.tuning.dashCmafLive.normalizedLiveMinBufferSize:this.player.isLive$.getValue()?p=this.params.tuning.dashCmafLive.normalizedTargetMinBufferSize:p=r?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;let h=(this.video.duration*1e3||1/0)-this.video.currentTime*1e3,m=Math.min(d/Math.min(p,h||1/0),1),b=(G=e.audioStream.getState())!=null?G:this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0,g=(R=[...this.audioStreamsMap.keys()].find(({id:_})=>_===(b==null?void 0:b.id)))!=null?R:this.audioStreamsMap.keys().next().value,v=0;if(g){if(n&&!r){let _=cn(n,c,(z=this.audioStreamsMap.get(g))!=null?z:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);v=Math.max(v,(q=_==null?void 0:_.bitrate)!=null?q:-1/0)}if(o){let _=cn(o,c,(Z=this.audioStreamsMap.get(g))!=null?Z:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);v=Math.max(v,(k=_==null?void 0:_.bitrate)!=null?k:-1/0)}}let S=Ft(c,{container:this.elementSizeManager.getValue(),estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:v,forwardBufferHealth:m,current:o,visible:this.params.output.elementVisible$.getValue(),history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,stallsVideoMaxQualityLimit:this.stallsManager.videoMaxQualityLimit,stallsPredictedThroughput:this.stallsManager.predictedThroughput,abrLogger:this.params.dependencies.abrLogger}),T=r?S!=null?S:n:n!=null?n:S,I=g&&pv(T,c,(D=this.audioStreamsMap.get(g))!=null?D:[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:m,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),y=(x=this.videoTracksMap.get(T))==null?void 0:x.representation,$=I&&((U=this.audioTracksMap.get(I))==null?void 0:U.representation);if(y&&$)return[y,$];if(y&&!$&&this.audioTracksMap.size===0)return[y,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){Le(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),A(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Yy.DOM,thrown:e}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.stallsManager.destroy(),this.elementSizeManager.destroy(),this.destroy3DScene(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),this.params.output.currentVideoStream$.next(void 0),Ae(this.video),this.tracer.end()}};var Ua=class extends Sr{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 _n,merge as Zy,filter as aC,filterChanged as sC,isNullable as pc,map as eT,ValueSubject as hc}from"@vkontakte/videoplayer-shared/es2015";var Ha=class extends Sr{constructor(e){super(e),this.textTracksManager.destroy()}subscribe(){super.subscribe();let e=-1,{output:t,observableVideo:r,desiredState:i,connect:s}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),s(r.timeUpdate$,t.liveBufferTime$),s(this.player.liveSeekableDuration$,t.duration$),s(this.player.liveLatency$,t.liveLatency$);let n=new hc(1);s(r.playbackRateState$,n),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(i.isLowLatency.stateChangeEnded$.pipe(eT(o=>o.to)).subscribe(this.player.isLowLatency$)).add(_n({liveBufferTime:t.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(eT(({liveBufferTime:o,liveAvailabilityStartTime:u})=>o&&u?o+u:void 0)).subscribe(t.liveTime$)).add(_n({position:t.position$,liveStreamStatus:this.player.liveStreamStatus$}).subscribe(({position:o,liveStreamStatus:u})=>t.isLiveEnded$.next(u!=="active"&&o===0))).add(_n({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:Zy(r.playbackRateState$,new hc(1))}).pipe(aC(({liveStreamStatus:o,liveDuration:u})=>o==="active"&&!!u)).subscribe(({liveDuration:o,playbackRate:u})=>{let l=t.liveBufferTime$.getValue(),c=t.position$.getValue(),{playbackCatchupSpeedup:d}=this.params.tuning.dashCmafLive.lowLatency;c||u<1-d||this.video.paused||pc(l)||(e=o-l)})).add(_n({time:t.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:Zy(r.playbackRateState$,new hc(1))}).pipe(sC((o,u)=>this.player.liveStreamStatus$.getValue()==="active"?o.liveDuration===u.liveDuration:o.time===u.time)).subscribe(({time:o,liveDuration:u,playbackRate:l})=>{let c=t.position$.getValue(),{playbackCatchupSpeedup:d}=this.params.tuning.dashCmafLive.lowLatency;if(!c&&!this.video.paused&&l>=1-d||pc(o)||pc(u))return;let p=-1*(u-o-e);t.position$.next(Math.min(p,0))})).add(this.player.currentLiveTextRepresentation$.subscribe(o=>{if(o){let u=Sy(o);this.params.output.availableTextTracks$.next([u])}}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,r=Math.trunc(t/1e3<=Math.abs(this.params.output.duration$.getValue())?t:0);this.player.seekLive(r).then(()=>{this.params.output.position$.next(e/1e3)})}};var rT=B(Ks(),1);import{assertNever as ja,assertNonNullable as tT,debounce as nC,ErrorCategory as Bn,filter as oC,isNonNullable as uC,isNullable as lC,map as Nn,merge as cC,Observable as dC,observableFrom as pC,Subscription as hC,videoSizeToQuality as mC}from"@vkontakte/videoplayer-shared/es2015";var tt={};var ui=(a,e)=>new dC(t=>{let r=(i,s)=>t.next(s);return a.on(e,r),()=>a.off(e,r)}),Qa=class{constructor(e){this.subscription=new hC;this.videoState=new N("initializing");this.trackLevels=new Map;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),i=this.params.desiredState.seekState.getState();if(e!=="initializing")switch((r==null?void 0:r.to)!=="paused"&&i.state==="requested"&&this.seek(i.position),t){case"stopped":switch(e){case"stopped":break;case"ready":case"playing":case"paused":this.stop();break;default:ja(e)}break;case"ready":switch(e){case"stopped":this.prepare();break;case"ready":case"playing":case"paused":break;default:ja(e)}break;case"playing":switch(e){case"playing":break;case"stopped":this.prepare();break;case"ready":case"paused":this.playIfAllowed();break;default:ja(e)}break;case"paused":switch(e){case"paused":break;case"stopped":this.prepare();break;case"ready":this.videoState.setState("paused"),A(this.params.desiredState.playbackState,"paused");break;case"playing":this.pause();break;default:ja(e)}break;default:ja(t)}};this.textTracksManager=new Ue(e.source.url),this.video=we(e.container,e.tuning),this.params=e,this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(de(this.params.source.url)),this.loadHlsJs()}destroy(){var e,t;this.subscription.unsubscribe(),this.trackLevels.clear(),this.textTracksManager.destroy(),(e=this.hls)==null||e.detachMedia(),(t=this.hls)==null||t.destroy(),this.params.output.element$.next(void 0),Ae(this.video)}loadHlsJs(){let e=!1,t=i=>{e||this.params.output.error$.next({id:i==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:Bn.NETWORK,message:"Failed to load Hls.js",thrown:i}),e=!0},r=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);(0,rT.default)(import("hls.js").then(i=>{e||(tt.Hls=i.default,tt.Events=i.default.Events,this.init())},t),()=>{window.clearTimeout(r),e=!0})}init(){tT(tt.Hls,"hls.js not loaded"),this.hls=new tt.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState("stopped")}subscribe(){tT(tt.Events,"hls.js not loaded");let{desiredState:e,output:t}=this.params,r=l=>{t.error$.next({id:"HlsJsProvider",category:Bn.WTF,message:"HlsJsProvider internal logic error",thrown:l})},i=Re(this.video),s=(l,c)=>this.subscription.add(l.subscribe(c,r));s(i.timeUpdate$,t.position$),s(i.durationChange$,t.duration$),s(i.ended$,t.endedEvent$),s(i.looped$,t.loopedEvent$),s(i.error$,t.error$),s(i.isBuffering$,t.isBuffering$),s(i.currentBuffer$,t.currentBuffer$),s(i.loadStart$,t.firstBytesEvent$),s(i.loadedMetadata$,t.loadedMetadataEvent$),s(i.playing$,t.firstFrameEvent$),s(i.canplay$,t.canplay$),s(i.seeked$,t.seekedEvent$),s(i.inPiP$,t.inPiP$),s(i.inFullscreen$,t.inFullscreen$),this.subscription.add(ot(this.video,e.isLooped,r)),this.subscription.add(ke(this.video,e.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(qe(this.video,e.playbackRate,i.playbackRateState$,r)),s(He(this.video),t.elementVisible$),s(this.videoState.stateChangeEnded$.pipe(Nn(l=>l.to)),this.params.output.playbackState$),this.subscription.add(ui(this.hls,tt.Events.ERROR).subscribe(l=>{var c;l.fatal&&t.error$.next({id:["HlsJsFatal",l.type,l.details].join("_"),category:Bn.WTF,message:`HlsJs fatal ${l.type} ${l.details}, ${(c=l.err)==null?void 0:c.message} ${l.reason}`,thrown:l.error})})),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),A(e.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),A(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(ui(this.hls,tt.Events.MANIFEST_PARSED).pipe(Nn(({levels:l})=>l.reduce((c,d)=>{var S,T;let p=d.name||d.height.toString(10),{width:h,height:m}=d,b=(T=_t((S=d.attrs.QUALITY)!=null?S:""))!=null?T:mC({width:h,height:m});if(!b)return c;let g=d.attrs["FRAME-RATE"]?parseFloat(d.attrs["FRAME-RATE"]):void 0,v={id:p.toString(),quality:b,bitrate:d.bitrate/1e3,size:{width:h,height:m},fps:g};return this.trackLevels.set(p,{track:v,level:d}),c.push(v),c},[]))),t.availableVideoTracks$),s(ui(this.hls,tt.Events.MANIFEST_PARSED),l=>{if(l.subtitleTracks.length>0){let c=[];for(let d of l.subtitleTracks){let p=d.name,h=d.attrs.URI||"",m=d.lang;c.push({id:p,url:h,language:m,type:"internal"})}e.internalTextTracks.startTransitionTo(c)}}),s(ui(this.hls,tt.Events.LEVEL_LOADING).pipe(Nn(({url:l})=>de(l))),t.hostname$),s(ui(this.hls,tt.Events.FRAG_CHANGED),l=>{var p,h,m,b;let{video:c,audio:d}=l.frag.elementaryStreams;t.currentVideoSegmentLength$.next((((p=c==null?void 0:c.endPTS)!=null?p:0)-((h=c==null?void 0:c.startPTS)!=null?h:0))*1e3),t.currentAudioSegmentLength$.next((((m=d==null?void 0:d.endPTS)!=null?m:0)-((b=d==null?void 0:d.startPTS)!=null?b:0))*1e3)}),this.subscription.add(Ct(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,l=>{this.hls.nextLevel=l?-1:this.hls.currentLevel,this.hls.loadLevel=l?-1:this.hls.loadLevel},{onError:r}));let n=l=>{var c;return(c=Array.from(this.trackLevels.values()).find(({level:d})=>d===l))==null?void 0:c.track},o=ui(this.hls,tt.Events.LEVEL_SWITCHED).pipe(Nn(({level:l})=>n(this.hls.levels[l])));o.pipe(oC(uC)).subscribe(t.currentVideoTrack$,r),this.subscription.add(Ct(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel]),l=>{var m;if(lC(l))return;let c=(m=this.trackLevels.get(l.id))==null?void 0:m.level;if(!c)return;let d=this.hls.levels.indexOf(c),p=this.hls.currentLevel,h=this.hls.levels[p];!h||c.bitrate>h.bitrate?this.hls.nextLevel=d:(this.hls.loadLevel=d,this.hls.loadLevel=d)},{changed$:o,onError:r})),s(i.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);let u=cC(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,pC(["init"])).pipe(nC(0));this.subscription.add(u.subscribe(this.syncPlayback,r))}prepare(){this.videoState.startTransitionTo("ready"),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}playIfAllowed(){return E(this,null,function*(){this.videoState.startTransitionTo("playing"),(yield Le(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Bn.DOM,thrown:t})))||(this.videoState.setState("paused"),A(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"),A(this.params.desiredState.playbackState,"stopped",!0)}};var iT="X-Playback-Duration",mc=a=>E(void 0,null,function*(){var i;let e=yield lt(a),t=yield e.text(),r=(i=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t))==null?void 0:i[1];return r?parseInt(r,10):e.headers.has(iT)?parseInt(e.headers.get(iT),10):void 0});import{assertNever as PC,combine as wC,debounce as AC,ErrorCategory as Un,filter as kC,filterChanged as $C,isNonNullable as nT,isNullable as Hn,map as oT,merge as RC,observableFrom as LC,Subscription as MC,ValueSubject as gc,VideoQuality as DC}from"@vkontakte/videoplayer-shared/es2015";var bc=B(mu(),1);import{videoSizeToQuality as fC,getExponentialDelay as bC}from"@vkontakte/videoplayer-shared/es2015";var gC=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=fC({width:t,height:r})}return e!=null?e:null},vC=(a,e)=>{var s,n;let t=a.split(`
|
|
125
|
+
`),r=[],i=[];for(let o=0;o<t.length;o++){let u=t[o],l=u.match(/^#EXT-X-STREAM-INF:(.+)/),c=u.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!l&&!c)){if(l){let d=(0,bc.default)(l[1].split(",").map(S=>S.split("="))),p=(s=d.QUALITY)!=null?s:`stream-${d.BANDWIDTH}`,h=gC(d),m;d.BANDWIDTH&&(m=parseInt(d.BANDWIDTH,10)/1e3||void 0),!m&&d["AVERAGE-BANDWIDTH"]&&(m=parseInt(d["AVERAGE-BANDWIDTH"],10)/1e3||void 0);let b=d["FRAME-RATE"]?parseFloat(d["FRAME-RATE"]):void 0,g;if(d.RESOLUTION){let[S,T]=d.RESOLUTION.split("x").map(I=>parseInt(I,10));S&&T&&(g={width:S,height:T})}let v=new URL(t[++o],e).toString();h&&r.push({id:p,quality:h,url:v,bandwidth:m,size:g,fps:b})}if(c){let d=(0,bc.default)(c[1].split(",").map(b=>{let g=b.indexOf("=");return[b.substring(0,g),b.substring(g+1)]}).map(([b,g])=>[b,g.replace(/^"|"$/g,"")])),p=(n=d.URI)==null?void 0:n.replace(/playlist$/,"subtitles.vtt"),h=d.LANGUAGE,m=d.NAME;p&&h&&i.push({type:"internal",id:h,label:m,language:h,url:p,isAuto:!1})}}}if(!r.length)throw new Error("Empty manifest");return{qualityManifests:r,textTracks:i}},SC=a=>new Promise(e=>{setTimeout(()=>{e()},a)}),fc=0,aT=(i,...s)=>E(void 0,[i,...s],function*(a,e=a,t,r){let o=yield(yield lt(a,r)).text();fc+=1;try{let{qualityManifests:u,textTracks:l}=vC(o,e);return{qualityManifests:u,textTracks:l}}catch(u){if(fc<=t.manifestRetryMaxCount)return yield SC(bC(fc-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),aT(a,e,t)}return{qualityManifests:[],textTracks:[]}}),Fn=aT;import{isNonNullable as yC,Subscription as TC,throttle as IC,ValueSubject as sT,Subject as EC,ErrorCategory as xC}from"@vkontakte/videoplayer-shared/es2015";var qn=class{constructor(e,t,r,i,s){this.subscription=new TC;this.abortControllers={destroy:new ge,nextManifest:null};this.prepareUrl=void 0;this.currentTextTrackData=null;this.availableTextTracks$=new sT(null);this.getCurrentTime$=new sT(null);this.error$=new EC;this.params={fetchManifestData:r,sourceUrl:i,downloadThreshold:s},this.subscription.add(e.pipe(IC(1e3)).subscribe(n=>{this.processLiveTime(n)})),this.getCurrentTime$.next(()=>this.currentTextTrackData?this.currentTextTrackData.playlist.segmentStartTime/1e3+t.currentTime:0)}destroy(){this.subscription.unsubscribe(),this.abortControllers.destroy.abort()}prepare(e){return E(this,null,function*(){try{let t=new URL(e);t.searchParams.set("enable-subtitles","yes"),this.prepareUrl=t.toString();let{textTracks:r}=yield this.fetchManifestData();yield this.processTextTracks(r,this.params.sourceUrl)}catch(t){this.error("prepare",t)}})}processTextTracks(e,t){return E(this,null,function*(){try{let r=yield this.parseTextTracks(e,t);r&&(this.currentTextTrackData=r)}catch(r){this.error("processTextTracks",r)}})}parseTextTracks(e,t){return E(this,null,function*(){for(let r of e){let i=new URL(r.url,t).toString(),n=yield(yield lt(i,{signal:this.abortControllers.destroy.signal})).text(),o=this.parsePlaylist(n,i);return{textTrack:r,playlist:o}}})}parsePlaylist(e,t){let r={mediaSequence:0,programDateTime:"",segments:[],targetDuration:0,vkPlaybackDuration:0,segmentStartTime:0,vkStartTime:""},i=e.split(`
|
|
126
|
+
`),s=0;for(let n=0;n<i.length;++n){let o=i[n];switch(!0){case o.startsWith("#EXTINF:"):{let u=i[++n],l=new URL(u,t).toString(),c=Number(this.extractPlaylistRowValue("#EXTINF:",o))*1e3;if(r.segments.push({time:{from:s,to:s+c},url:l}),s=s+c,!r.segmentStartTime){let d=new Date(r.vkStartTime).valueOf(),p=new Date(r.programDateTime).valueOf();r.segmentStartTime=p-d}break}case o.startsWith("#EXT-X-TARGETDURATION:"):r.targetDuration=Number(this.extractPlaylistRowValue("#EXT-X-TARGETDURATION:",o));break;case o.startsWith("#EXT-X-MEDIA-SEQUENCE:"):r.mediaSequence=Number(this.extractPlaylistRowValue("#EXT-X-MEDIA-SEQUENCE:",o));break;case o.startsWith("#EXT-X-VK-PLAYBACK-DURATION:"):r.vkPlaybackDuration=Number(this.extractPlaylistRowValue("#EXT-X-VK-PLAYBACK-DURATION:",o));break;case o.startsWith("#EXT-X-PROGRAM-DATE-TIME:"):{let u=this.extractPlaylistRowValue("#EXT-X-PROGRAM-DATE-TIME:",o);r.programDateTime=u;let l=new Date(u);l.setMilliseconds(0),s=l.valueOf();break}case o.startsWith("#EXT-X-VK-START-TIME:"):r.vkStartTime=this.extractPlaylistRowValue("#EXT-X-VK-START-TIME:",o);break}}return r}extractPlaylistRowValue(e,t){switch(e){case"#EXTINF:":return t.substring(e.length,t.length-1);default:return t.substring(e.length)}}processLiveTime(e){if(yC(e)&&this.currentTextTrackData){let{segments:t}=this.currentTextTrackData.playlist,{from:r}=t[0].time,{to:i}=t[t.length-1].time;if(e<r||e>i)return;i-e<this.params.downloadThreshold&&this.fetchNextManifestData();for(let n of t)if(n.time.from<=e&&n.time.to>=e){this.availableTextTracks$.next([M(P({},this.currentTextTrackData.textTrack),{url:n.url,isAuto:!0})]);break}}}fetchNextManifestData(){return E(this,null,function*(){try{if(this.abortControllers.nextManifest)return;this.abortControllers.nextManifest=new ge;let{textTracks:e}=yield this.fetchManifestData(),t=yield this.parseTextTracks(e,this.params.sourceUrl);this.currentTextTrackData&&t&&(this.currentTextTrackData.playlist.segments=t.playlist.segments)}catch(e){this.error("fetchNextManifestData",e)}finally{this.abortControllers.nextManifest=null}})}fetchManifestData(){return E(this,null,function*(){var t;let e=(t=this.prepareUrl)!=null?t:this.params.sourceUrl;return yield this.params.fetchManifestData(e,{signal:this.abortControllers.destroy.signal})})}error(e,t){this.error$.next({id:"[LiveTextManager][HLS_LIVE_CMAF]",category:xC.WTF,thrown:t,message:e})}};var Ga=class{constructor(e){this.subscription=new MC;this.videoState=new N("stopped");this.textTracksManager=null;this.liveTextManager=null;this.manifests$=new gc([]);this.liveOffset=new pr;this.manifestStartTime$=new gc(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"),A(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||n||o){let c=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(c),this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if((i==null?void 0:i.to)!=="paused"&&l.state==="requested"){this.videoState.startTransitionTo("ready"),this.seek(l.position&&l.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(t){case"ready":r==="ready"?A(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),A(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"&&A(this.params.desiredState.playbackState,"playing");return;case"paused":if(r==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let c=this.liveOffset.getTotalOffset();c>=this.maxSeekBackTime$.getValue()&&(c=0,this.liveOffset.resetTo(c)),this.liveOffset.resume(),this.params.output.position$.next(-c/1e3),this.prepare()}else(i==null?void 0:i.to)==="paused"&&(A(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return PC(t)}};var r;this.params=e,this.video=we(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:DC.INVARIANT,url:this.params.source.url};let t=(i,s)=>Fn(i,this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},s);this.params.tuning.useHlsLiveNewTextManager?this.liveTextManager=new qn(this.params.output.liveTime$,this.video,t,this.params.source.url,this.params.tuning.hlsLiveNewTextManagerDownloadThreshold):this.textTracksManager=new Ue(e.source.url),t(this.generateLiveUrl()).then(({qualityManifests:i,textTracks:s})=>{var n;i.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:Un.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),(n=this.liveTextManager)==null||n.processTextTracks(s,this.params.source.url),this.manifests$.next([this.masterManifest,...i])}).catch(i=>{this.params.output.error$.next({id:"ExtractHlsQualities",category:Un.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:i})}),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(de(this.params.source.url)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.maxSeekBackTime$=new gc((r=e.source.maxSeekBackTime)!=null?r:1/0),this.subscribe()}selectManifest(){var u,l,c,d;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,r=e.getState(),i=t.getTransition(),s=(d=(c=(u=i==null?void 0:i.to)==null?void 0:u.id)!=null?c:(l=t.getState())==null?void 0:l.id)!=null?d:"master",n=this.manifests$.getValue();if(!n.length)return;let o=r?"master":s;return r&&!i&&t.startTransitionTo(this.masterManifest),n.find(p=>p.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"HlsLiveProvider",category:Un.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},i=Re(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(ke(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(qe(this.video,t.playbackRate,i.playbackRateState$,r)),s(He(this.video),e.elementVisible$),this.liveTextManager?(s(this.liveTextManager.getCurrentTime$,this.params.output.getCurrentTime$),s(this.liveTextManager.error$,this.params.output.error$)):this.textTracksManager&&this.textTracksManager.connect(this.video,t,e),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),A(t.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),A(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())==null?void 0:o.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.liveTextManager&&this.subscription.add(this.liveTextManager.availableTextTracks$.subscribe(o=>{o&&this.params.output.availableTextTracks$.next(o)})),this.subscription.add(this.maxSeekBackTime$.pipe($C(),oT(o=>-o/1e3)).subscribe(this.params.output.duration$,r)),this.subscription.add(i.loadedMetadata$.subscribe(()=>{let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&nT(l.to)){let d=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let p=this.manifests$.getValue().find(h=>h.id===d);p&&(this.params.output.currentVideoTrack$.next(p),this.params.output.hostname$.next(de(p.url)))}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o&&o.state==="requested"&&this.seek(o.position)},r)),this.subscription.add(i.loadedData$.subscribe(()=>{var u,l,c;let o=(c=(l=(u=this.video)==null?void 0:u.getStartDate)==null?void 0:l.call(u))==null?void 0:c.getTime();this.manifestStartTime$.next(o||void 0)},r)),this.subscription.add(wC({startTime:this.manifestStartTime$.pipe(kC(nT)),currentTime:i.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),r)),this.subscription.add(this.manifests$.pipe(oT(o=>o.map(({id:u,quality:l,size:c,bandwidth:d,fps:p})=>({id:u,quality:l,size:c,fps:p,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,r));let n=RC(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,LC(["init"])).pipe(AC(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){var e,t;this.subscription.unsubscribe(),(e=this.textTracksManager)==null||e.destroy(),(t=this.liveTextManager)==null||t.destroy(),this.params.output.element$.next(void 0),Ae(this.video)}prepare(){var o,u,l;let e=this.selectManifest();if(Hn(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),r=this.params.desiredState.autoVideoTrackLimits.getState(),i=new URL(e.url);if((t||r)&&e.id===this.masterManifest.id){let{max:c,min:d}=(u=(o=t==null?void 0:t.to)!=null?o:r)!=null?u:{};for(let[p,h]of[[c,"mq"],[d,"lq"]]){let m=String(parseFloat(p||""));h&&p&&i.searchParams.set(h,m)}}let s=this.params.format==="HLS_LIVE_CMAF"?2:0,n=be(i.toString(),this.liveOffset.getTotalOffset(),s);(l=this.liveTextManager)==null||l.prepare(n),this.video.setAttribute("src",n),this.video.load(),mc(n).then(c=>{var d;if(!Hn(c))this.maxSeekBackTime$.next(c);else{let p=(d=this.params.source.maxSeekBackTime)!=null?d:this.maxSeekBackTime$.getValue();(Hn(p)||!isFinite(p))&<(n).then(h=>h.text()).then(h=>{var b;let m=(b=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(h))==null?void 0:b[1];if(m){let g=new URL(m,n).toString();mc(g).then(v=>{Hn(v)||this.maxSeekBackTime$.next(v)})}}).catch(()=>{})}})}playIfAllowed(){Le(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),A(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Un.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,r=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(r),this.params.output.position$.next(-r/1e3),this.params.output.seekedEvent$.next()}generateLiveUrl(){let e=be(this.params.source.url);if(this.params.tuning.useHlsLiveNewTextManager){let t=new URL(e);t.searchParams.set("enable-subtitles","yes"),e=t.toString()}return e}};import{assertNever as CC,debounce as VC,ErrorCategory as vc,fromEvent as Sc,isNonNullable as OC,isNullable as _C,map as uT,merge as lT,observableFrom as cT,Subscription as BC,ValueSubject as NC,VideoQuality as FC}from"@vkontakte/videoplayer-shared/es2015";var Wa=class{constructor(e){this.subscription=new BC;this.videoState=new N("stopped");this.manifests$=new NC([]);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"),A(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||n||o){let c=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(c);let{currentTime:d}=this.video;this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:d*1e3,forcePrecise:!0});return}switch((i==null?void 0:i.to)!=="paused"&&l.state==="requested"&&this.seek(l.position),t){case"ready":r==="ready"?A(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),A(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"&&A(this.params.desiredState.playbackState,"playing");return;case"paused":r==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&A(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return CC(t)}};this.textTracksManager=new Ue(e.source.url),this.params=e,this.video=we(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:FC.INVARIANT,url:this.params.source.url},this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(de(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),Fn(be(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:vc.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){var u,l,c,d;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,r=e.getState(),i=t.getTransition(),s=(d=(c=(u=i==null?void 0:i.to)==null?void 0:u.id)!=null?c:(l=t.getState())==null?void 0:l.id)!=null?d:"master",n=this.manifests$.getValue();if(!n.length)return;let o=r?"master":s;return r&&(!i||!i.from)&&t.startTransitionTo(this.masterManifest),n.find(p=>p.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"HlsProvider",category:vc.WTF,message:"HlsProvider internal logic error",thrown:o})},i=Re(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(uT(o=>o.to)),this.params.output.playbackState$),this.subscription.add(ot(this.video,t.isLooped,r)),this.subscription.add(ke(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(qe(this.video,t.playbackRate,i.playbackRateState$,r)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),A(t.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),A(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())==null?void 0:o.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},r).add(i.loadedMetadata$.subscribe(()=>{var h;let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&OC(l.to)){let m=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let b=this.manifests$.getValue().find(g=>g.id===m);b&&(this.params.output.currentVideoTrack$.next(b),this.params.output.hostname$.next(de(b.url)))}let d=this.params.desiredState.playbackRate.getState(),p=(h=this.params.output.element$.getValue())==null?void 0:h.playbackRate;if(d!==p){let m=this.params.output.element$.getValue();m&&(this.params.desiredState.playbackRate.setState(d),m.playbackRate=d)}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o.state==="requested"&&this.seek(o.position)},r))),this.subscription.add(this.manifests$.pipe(uT(o=>o.map(({id:u,quality:l,size:c,bandwidth:d,fps:p})=>({id:u,quality:l,size:c,fps:p,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,r)),!H.device.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add(lT(Sc(o,"addtrack"),Sc(o,"removetrack"),Sc(o,"change"),cT(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},r))}let n=lT(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,cT(["init"])).pipe(VC(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),Ae(this.video)}prepare(){var s,n;let e=this.selectManifest();if(_C(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),r=this.params.desiredState.autoVideoTrackLimits.getState(),i=new URL(e.url);if((t||r)&&e.id===this.masterManifest.id){let{max:o,min:u}=(n=(s=t==null?void 0:t.to)!=null?s:r)!=null?n:{};for(let[l,c]of[[o,"mq"],[u,"lq"]]){let d=String(parseFloat(l||""));c&&l&&i.searchParams.set(c,d)}}this.video.setAttribute("src",i.toString()),this.video.load()}playIfAllowed(){Le(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),A(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:vc.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};var hT=B(Br(),1),yc=B(zr(),1),mT=B(Bt(),1);import{assertNever as qC,assertNonNullable as dT,debounce as UC,ErrorCategory as pT,isHigherOrEqual as HC,isLowerOrEqual as jC,isNonNullable as QC,merge as GC,observableFrom as WC,Subscription as YC,map as zC}from"@vkontakte/videoplayer-shared/es2015";var Ya=class{constructor(e){this.subscription=new YC;this.videoState=new N("stopped");this.trackUrls={};this.textTracksManager=new Ue;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),A(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let s=this.params.desiredState.autoVideoTrackLimits.getTransition(),n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.seekState.getState();if(s&&e!=="ready"&&!n){this.handleQualityLimitTransition(s.to);return}if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(n){let{currentTime:u}=this.video;this.prepare(),o.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:u*1e3,forcePrecise:!0});return}switch((r==null?void 0:r.to)!=="paused"&&o.state==="requested"&&this.seek(o.position),e){case"ready":t==="ready"?A(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),A(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"&&A(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&A(this.params.desiredState.playbackState,"paused");return;default:return qC(e)}};this.params=e,this.video=we(e.container,e.tuning),this.params.output.element$.next(this.video),(0,hT.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,yc.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:pT.WTF,message:"MpegProvider internal logic error",thrown:o})},i=Re(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(zC(o=>o.to)),this.params.output.playbackState$),this.subscription.add(ot(this.video,t.isLooped,r)),this.subscription.add(ke(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(qe(this.video,t.playbackRate,i.playbackRateState$,r)),s(He(this.video),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),A(t.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),A(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&&QC(o.to)){this.params.desiredState.videoTrack.setState(o.to),this.params.output.currentVideoTrack$.next(this.trackUrls[o.to.id].track);let c=this.params.desiredState.playbackRate.getState(),d=(l=this.params.output.element$.getValue())==null?void 0:l.playbackRate;if(c!==d){let p=this.params.output.element$.getValue();p&&(this.params.desiredState.playbackRate.setState(c),p.playbackRate=c)}}this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.textTracksManager.connect(this.video,t,e);let n=GC(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,WC(["init"])).pipe(UC(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),Ae(this.video)}prepare(){var r;let e=(r=this.params.desiredState.videoTrack.getState())==null?void 0:r.id;dT(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];dT(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=Da(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(de(t))}playIfAllowed(){Le(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),A(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:pT.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){var l,c;this.params.output.autoVideoTrackLimits$.next(e);let t=d=>{this.params.output.currentVideoTrack$.next(d),this.params.desiredState.videoTrack.startTransitionTo(d)},r=d=>{let p=Ft(n,{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:0,limits:d,abrLogger:this.params.dependencies.abrLogger});t(p)},i=(l=this.params.output.currentVideoTrack$.getValue())==null?void 0:l.quality,s=!!(e.max||e.min),n=(0,yc.default)(this.trackUrls).map(d=>d.track);if(!i||!s||Gi({limits:e,lowestAvailableQuality:(c=(0,mT.default)(n,-1))==null?void 0:c.quality,highestAvailableQuality:n[0].quality})){r();return}let o=e.max?jC(i,e.max):!0,u=e.min?HC(i,e.min):!0;o&&u||r(e)}};import{assertNever as bT,debounce as ZC,merge as gT,observableFrom as e0,Subscription as t0,map as vT,ValueSubject as r0,ErrorCategory as Ic,VideoQuality as i0}from"@vkontakte/videoplayer-shared/es2015";import{ErrorCategory as KC}from"@vkontakte/videoplayer-shared/es2015";var fT=["stun:videostun.mycdn.me:80"],XC=1e3,JC=3,Tc=()=>null,jn=class{constructor(e,t){this.ws=null;this.peerConnection=null;this.serverUrl="";this.streamKey="";this.stream=null;this.signalingType="JOIN";this.retryCount=0;this.externalStartCallback=Tc;this.externalStopCallback=Tc;this.externalErrorCallback=Tc;this.options=this.normalizeOptions(t);let r=e.split("/");this.serverUrl=r.slice(0,r.length-1).join("/"),this.streamKey=r[r.length-1]}onStart(e){try{this.externalStartCallback=e}catch(t){this.handleSystemError(t)}}onStop(e){try{this.externalStopCallback=e}catch(t){this.handleSystemError(t)}}onError(e){try{this.externalErrorCallback=e}catch(t){this.handleSystemError(t)}}connect(){this.connectWS()}disconnect(){try{this.externalStopCallback(),this.closeConnections()}catch(e){this.handleSystemError(e)}}connectWS(){this.ws||(this.ws=new WebSocket(this.serverUrl),this.ws.onopen=this.onSocketOpen.bind(this),this.ws.onmessage=this.onSocketMessage.bind(this),this.ws.onclose=this.onSocketClose.bind(this),this.ws.onerror=this.onSocketError.bind(this))}onSocketOpen(){this.handleLogin()}onSocketClose(e){try{if(!this.ws)return;this.ws=null,e.code>1e3?(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():this.scheduleRetry()):this.externalStopCallback()}catch(t){this.handleRTCError(t)}}onSocketError(e){try{this.externalErrorCallback(new Error(e.toString()))}catch(t){this.handleRTCError(t)}}onSocketMessage(e){try{let t=this.parseMessage(e.data);switch(t.type){case"JOIN":case"CALL_JOIN":this.handleJoinMessage(t);break;case"UPDATE":this.handleUpdateMessage(t);break;case"STATUS":this.handleStatusMessage(t);break}}catch(t){this.handleRTCError(t)}}handleJoinMessage(e){switch(e.inviteType){case"ANSWER":this.handleAnswer(e.sdp);break;case"CANDIDATE":this.handleCandidate(e.candidate);break}}handleStatusMessage(e){switch(e.status){case"UNPUBLISHED":this.handleUnpublished();break}}handleUpdateMessage(e){return E(this,null,function*(){try{let t=yield this.createOffer();this.peerConnection&&(yield this.peerConnection.setLocalDescription(t)),this.handleAnswer(e.sdp)}catch(t){this.handleRTCError(t)}})}handleLogin(){return E(this,null,function*(){try{let e={iceServers:[{urls:fT}]};this.peerConnection=new RTCPeerConnection(e),this.peerConnection.ontrack=this.onPeerConnectionStream.bind(this),this.peerConnection.onicecandidate=this.onPeerConnectionIceCandidate.bind(this),this.peerConnection.oniceconnectionstatechange=this.onPeerConnectionIceConnectionStateChange.bind(this);let t=yield this.createOffer();yield this.peerConnection.setLocalDescription(t),this.send({type:this.signalingType,inviteType:"OFFER",streamKey:this.streamKey,sdp:t.sdp,callSupport:!1})}catch(e){this.handleRTCError(e)}})}handleAnswer(e){return E(this,null,function*(){try{this.peerConnection&&(yield this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e})))}catch(t){this.handleRTCError(t)}})}handleCandidate(e){return E(this,null,function*(){if(e)try{this.peerConnection&&(yield this.peerConnection.addIceCandidate(e))}catch(t){this.handleRTCError(t)}})}handleUnpublished(){try{this.closeConnections(),this.externalStopCallback()}catch(e){this.handleRTCError(e)}}handleSystemError(e){this.options.errorChanel&&this.options.errorChanel.next({id:"webrtc-provider-error",category:KC.WTF,message:e.message})}onPeerConnectionStream(e){return E(this,null,function*(){let t=e.streams[0];this.stream&&this.stream.id===t.id||(this.stream=t,this.externalStartCallback(this.stream))})}onPeerConnectionIceCandidate(e){e.candidate&&this.send({type:this.signalingType,inviteType:"CANDIDATE",candidate:e.candidate})}onPeerConnectionIceConnectionStateChange(){if(this.peerConnection){let e=this.peerConnection.iceConnectionState;["failed","closed"].indexOf(e)>-1&&(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():(this.closeConnections(),this.scheduleRetry()))}}createOffer(){return E(this,null,function*(){let e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");let t=yield this.peerConnection.createOffer(e),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),XC)}normalizeOptions(e={}){let t={stunServerList:fT,maxRetryNumber:JC,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var za=class{constructor(e){this.videoState=new N("stopped");this.maxSeekBackTime$=new r0(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"),A(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"),A(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"&&A(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&A(this.params.desiredState.playbackState,"paused");return;default:return bT(e)}};this.subscription=new t0,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=we(e.container,e.tuning),this.liveStreamClient=new jn(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),Ae(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,r=n=>{e.error$.next({id:"WebRTCLiveProvider",category:Ic.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};gT(this.videoState.stateChangeStarted$.pipe(vT(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe(vT(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})});let i=Re(this.video),s=(n,o)=>this.subscription.add(n.subscribe(o,r));s(i.timeUpdate$,e.liveTime$),s(i.ended$,e.endedEvent$),s(i.looped$,e.loopedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(He(this.video),this.params.output.elementVisible$),this.subscription.add(i.durationChange$.subscribe(n=>{e.duration$.next(n===1/0?0:n)})).add(i.canplay$.subscribe(()=>{var n;((n=this.videoState.getTransition())==null?void 0:n.to)==="ready"&&this.videoState.setState("ready")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused")},r)).add(i.playing$.subscribe(()=>{this.videoState.setState("playing")},r)).add(i.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(ke(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 bT(n.to)}},r)).add(gT(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,e0(["init"])).pipe(ZC(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(de(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.currentVideoTrack$.next({id:"webrtc",quality:i0.INVARIANT}),this.video.srcObject=e,A(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:Ic.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){Le(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),A(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Ic.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var Ka=class{constructor(e){this.iterator=e[Symbol.iterator](),this.next()}next(){this.current=this.iterator.next()}getValue(){if(this.current.done)throw new Error("Iterable is completed");return this.current.value}isCompleted(){return!!this.current.done}};import{assertNever as Ja,assertNonNullable as Qt,ErrorCategory as Qn,filter as xT,isNonNullable as PT,isNullable as c0,map as d0,merge as p0,once as h0,Subject as he,Subscription as wT,ValueSubject as F,flattenObject as AT}from"@vkontakte/videoplayer-shared/es2015";import{Observable as a0,map as ST,Subscription as s0,Subject as n0}from"@vkontakte/videoplayer-shared/es2015";var yT=a=>new a0(e=>{let t=new s0,r=a.desiredPlaybackState$.stateChangeStarted$.pipe(ST(({from:l,to:c})=>`${l}-${c}`)),i=a.desiredPlaybackState$.stateChangeEnded$,s=a.providerChanged$.pipe(ST(({type:l})=>l!==void 0)),n=new n0,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 o0,Subscription as u0,combine as l0,filter as IT,once as ET}from"@vkontakte/videoplayer-shared/es2015";function TT(){return new(window.AudioContext||window.webkitAudioContext)}var Xa=class Xa{constructor(e,t,r,i){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=r;this.volumeMultiplier=i;this.destroyController=new ge;this.subscriptions=new u0;this.audioContext=null;this.gainNode=null;this.mediaElementSource=null;this.subscriptions.add(this.provider$.pipe(IT(s=>!!s.type),ET()).subscribe(({type:s})=>this.subscribe(s)))}subscribe(e){H.browser.isSafari&&e!=="MPEG"||this.subscriptions.add(l0({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe(IT(({playbackState:t,video:r,volume:{muted:i,volume:s}})=>t==="playing"&&!!r&&!i&&!!s),ET()).subscribe(({video:t})=>{this.initAudioContextOnce(t).then(r=>{r||this.destroy()}).catch(r=>{this.handleError(r),this.destroy()})}))}static isSupported(){return"AudioContext"in window&&"GainNode"in window&&"MediaElementAudioSourceNode"in window}initAudioContextOnce(e){return E(this,null,function*(){let{volumeMultiplier:t}=this,r=TT();this.audioContext=r;let i=r.createGain();if(this.gainNode=i,i.gain.value=t,i.connect(r.destination),r.state==="suspended"&&(yield r.resume(),this.destroyController.signal.aborted))return!1;let s=r.createMediaElementSource(e);return this.mediaElementSource=s,s.connect(i),!0})}cleanup(){this.mediaElementSource&&(this.mediaElementSource.disconnect(),this.mediaElementSource=null),this.gainNode&&(this.gainNode.disconnect(),this.gainNode=null),this.audioContext&&(this.audioContext.state!=="closed"&&this.audioContext.close(),this.audioContext=null)}destroy(){this.destroyController.abort(),this.subscriptions.unsubscribe(),this.cleanup()}handleError(e){var t;this.volumeMultiplierError$.next({id:Xa.errorId,category:o0.VIDEO_PIPELINE,message:(t=e==null?void 0:e.message)!=null?t:`${Xa.errorId} exception`,thrown:e})}};Xa.errorId="VolumeMultiplierManager";var li=Xa;var m0={chunkDuration:5e3,maxParallelRequests:5},Za=class{constructor(e){this.current$=new F({type:void 0});this.providerError$=new he;this.noAvailableProvidersError$=new he;this.volumeMultiplierError$=new he;this.providerOutput={position$:new F(0),duration$:new F(1/0),volume$:new F({muted:!1,volume:1}),availableVideoStreams$:new F([]),currentVideoStream$:new F(void 0),availableVideoTracks$:new F([]),currentVideoTrack$:new F(void 0),availableAudioStreams$:new F([]),currentAudioStream$:new F(void 0),availableAudioTracks$:new F([]),currentVideoSegmentLength$:new F(0),currentAudioSegmentLength$:new F(0),isAudioAvailable$:new F(!0),autoVideoTrackLimitingAvailable$:new F(!1),autoVideoTrackLimits$:new F(void 0),currentBuffer$:new F(void 0),isBuffering$:new F(!0),error$:new he,fetcherError$:new he,fetcherRecoverableError$:new he,warning$:new he,willSeekEvent$:new he,soundProhibitedEvent$:new he,seekedEvent$:new he,loopedEvent$:new he,endedEvent$:new he,firstBytesEvent$:new he,loadedMetadataEvent$:new he,firstFrameEvent$:new he,canplay$:new he,isLive$:new F(void 0),isLiveEnded$:new F(null),isLowLatency$:new F(!1),canChangePlaybackSpeed$:new F(!0),liveTime$:new F(void 0),liveBufferTime$:new F(void 0),liveLatency$:new F(void 0),severeStallOccurred$:new he,availableTextTracks$:new F([]),currentTextTrack$:new F(void 0),hostname$:new F(void 0),httpConnectionType$:new F(void 0),httpConnectionReused$:new F(void 0),inPiP$:new F(!1),inFullscreen$:new F(!1),element$:new F(void 0),elementVisible$:new F(!0),availableSources$:new F(void 0),is3DVideo$:new F(!1),playbackState$:new F(""),getCurrentTime$:new F(null)};this.subscription=new wT;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=Oy([...By(this.params.tuning),..._y(this.params.tuning)],this.params.tuning).filter(l=>PT(e.sources[l])),{forceFormat:r,formatsToAvoid:i}=this.params.tuning,s=[];r?s=[r]:i.length?s=[...t.filter(l=>!(0,Ec.default)(i,l)),...t.filter(l=>(0,Ec.default)(i,l))]:s=t,this.log({message:`Selected formats: ${s.join(" > ")}`}),this.tracer.log("Selected formats",AT(s)),this.screenFormatsIterator=new Ka(s);let n=[...tc(!0),...tc(!1)];this.chromecastFormatsIterator=new Ka(n.filter(l=>PT(e.sources[l]))),this.providerOutput.availableSources$.next(e.sources);let{volumeMultiplier:o=1,tuning:{useVolumeMultiplier:u}}=this.params;u&&o!==1&&li.isSupported()&&(this.volumeMultiplierManager=new li(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(c0(t)){this.handleNoFormatsError(e);return}let r;try{r=this.createProvider(e,t)}catch(i){this.providerError$.next({id:"ProviderNotConstructed",category:Qn.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 Ja(e)}}createScreenProvider(e){let{sources:t,container:r,desiredState:i}=this.params,s=this.providerOutput,n={container:r,source:null,desiredState:i,output:s,dependencies:this.params.dependencies,tuning:this.params.tuning};switch(e){case"DASH_SEP":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_ONDEMAND":case"DASH_STREAMS":{let o=this.applyFailoverHost(t[e]),u=this.applyFailoverHost(t.HLS_ONDEMAND||t.HLS);return Qt(o),new Ua(M(P({},n),{source:o,sourceHls:u}))}case"DASH_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return Qt(o),new Ha(M(P({},n),{source:o}))}case"HLS":case"HLS_ONDEMAND":{let o=this.applyFailoverHost(t[e]);return Qt(o),H.video.nativeHlsSupported||!this.params.tuning.useHlsJs?new Wa(M(P({},n),{source:o})):new Qa(M(P({},n),{source:o}))}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return Qt(o),new Ga(M(P({},n),{source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e}))}case"MPEG":{let o=this.applyFailoverHost(t[e]);return Qt(o),new Ya(M(P({},n),{source:o}))}case"DASH_LIVE":{let o=this.applyFailoverHost(t[e]);return Qt(o),new $v(M(P({},n),{source:o,config:M(P({},m0),{maxPausedTime:this.params.tuning.live.maxPausedTime})}))}case"WEB_RTC_LIVE":{let o=this.applyFailoverHost(t[e]);return Qt(o),new za({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 Ja(e)}}createChromecastProvider(e){let{sources:t,container:r,desiredState:i,meta:s}=this.params,n=this.providerOutput,o=this.params.dependencies.chromecastInitializer.connection$.getValue();return Qt(o),new Fi({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 Ja(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return Ja(e)}}handleNoFormatsError(e){switch(e){case"SCREEN":this.noAvailableProvidersError$.next(this.params.tuning.forceFormat),this.current$.next({type:void 0});return;case"CHROMECAST":this.params.dependencies.chromecastInitializer.disconnect();return;default:return Ja(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;let t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;let r=i=>{let s=new URL(i);return s.host=t,s.toString()};if(e===void 0)return e;if("type"in e){if(e.type==="raw")return e;if(e.type==="url")return M(P({},e),{url:r(e.url)})}return(0,$T.default)((0,kT.default)(e).map(([i,s])=>[i,r(s)]))}initProviderErrorHandling(){let e=new wT,t=!1,r=0;return e.add(p0(this.providerOutput.error$.pipe(xT(i=>!this.params.tuning.ignoreAudioRendererError||!i.message||!/AUDIO_RENDERER_ERROR/ig.test(i.message))),yT({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(d0(i=>({id:`ProviderHangup:${i}`,category:Qn.WTF,message:`A ${i} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.providerOutput.fetcherError$.subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;let i=this.params.desiredState.playbackState.transitionEnded$.pipe(xT(({to:s})=>s==="playing"),h0()).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===Qn.NETWORK,u=i.category===Qn.FATAL,l=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),c=r<this.params.tuning.providerErrorLimit&&!u,d=l&&!u&&(o&&t||!c);n=M(P({},n),{isNetworkError:o,isFatalError:u,haveFailoverHost:l,tryFailover:d,canReinitProvider:c}),c?(r++,this.reinitProvider()):d?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):this.switchToNextProvider(s!=null?s:"SCREEN")}this.tracer.error("providerError",AT(n))})),e}};import{fromEvent as Gn,once as f0,combine as b0,Subscription as RT,ValueSubject as xc,map as g0,filter as v0,isNonNullable as Wn,now as Be,safeStorage as Pc}from"@vkontakte/videoplayer-shared/es2015";var S0=5e3,LT="one_video_throughput",MT="one_video_rtt",Tt=window.navigator.connection,DT=()=>{let a=Tt==null?void 0:Tt.downlink;if(Wn(a)&&a!==10)return a*1e3},CT=()=>{let a=Tt==null?void 0:Tt.rtt;if(Wn(a)&&a!==3e3)return a},VT=(a,e,t)=>{let r=t*8,i=r/a;return r/(i+e)},wc=class a{constructor(e){this.subscription=new RT;this.concurrentDownloads=new Set;var i,s;this.tuningConfig=e;let t=a.load(LT)||(e.useBrowserEstimation?DT():void 0)||S0,r=(s=(i=a.load(MT))!=null?i:e.useBrowserEstimation?CT():void 0)!=null?s:0;if(this.throughput$=new xc(t),this.rtt$=new xc(r),this.rttAdjustedThroughput$=new xc(VT(t,r,e.rttPenaltyRequestSize)),this.throughput=gr.getSmoothedValue(t,-1,e),this.rtt=gr.getSmoothedValue(r,1,e),e.useBrowserEstimation){let n=()=>{let u=DT();u&&this.throughput.next(u);let l=CT();Wn(l)&&this.rtt.next(l)};Tt&&"onchange"in Tt&&this.subscription.add(Gn(Tt,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{Pc.set(LT,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{Pc.set(MT,n.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(b0({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(g0(({throughput:n,rtt:o})=>VT(n,o,e.rttPenaltyRequestSize)),v0(n=>{let o=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(n-o)/o>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,r=Be(),i=new RT;switch(this.subscription.add(i),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:i.add(Gn(e,"progress").pipe(f0()).subscribe(s=>{t=s.loaded,r=Be()}));break;case 1:case 0:i.add(Gn(e,"loadstart").subscribe(()=>{t=0,r=Be()}));break}i.add(Gn(e,"loadend").subscribe(s=>{if(e.status===200){let n=s.loaded,o=Be(),u=n-t,l=o-r;this.addRawSpeed(u,l,1)}this.concurrentDownloads.delete(e),i.unsubscribe()}))}trackStream(e,t=!1){let r=e.getReader();if(!r){e.cancel("Could not get reader");return}let i=0,s=Be(),n=0,o=Be(),u=c=>{this.concurrentDownloads.delete(e),r.releaseLock(),e.cancel(`Throughput Estimator error: ${c}`).catch(()=>{})},l=p=>E(this,[p],function*({done:c,value:d}){if(c)!t&&this.addRawSpeed(i,Be()-s,1),this.concurrentDownloads.delete(e);else if(d){if(t){let h=Be();if(h-o>this.tuningConfig.lowLatency.continuesByteSequenceInterval||h-s>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let b=o-s;b&&this.addRawSpeed(n,b,1,t),n=d.byteLength,s=Be()}else n+=d.byteLength;o=Be()}else i+=d.byteLength,n+=d.byteLength,n>=this.tuningConfig.streamMinSampleSize&&Be()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,Be()-o,this.concurrentDownloads.size),n=0,o=Be());yield r==null?void 0:r.read().then(l,u)}});this.concurrentDownloads.add(e),r==null||r.read().then(l,u)}addRawSpeed(e,t,r=1,i=!1){if(a.sanityCheck(e,t,i)){let s=e*8/t;this.throughput.next(s*r)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,r=!1){let i=e*8/t;return!(!i||!isFinite(i)||i>1e6||i<30||r&&e<1e4||!r&&e<10*1024||!r&&t<=20)}static load(e){var r;let t=Pc.get(e);if(Wn(t))return(r=parseInt(t,10))!=null?r:void 0}},OT=wc;import{fillWithDefault as y0,VideoQuality as Yn}from"@vkontakte/videoplayer-shared/es2015";var _T={configName:["core"],throughputEstimator:{type:"EmaAndMa",emaAlphaSlow:.2,emaAlphaFast:.7,emaAlpha:.45,basisTrendChangeCount:10,changeThreshold:.05,useBrowserEstimation:!0,rttPenaltyRequestSize:1*1024*1024,streamMinSampleSize:10*1024,streamMinSampleTime:300,deviationDepth:20,deviationFactor:.5,lowLatency:{continuesByteSequenceInterval:50,maxLastEvaluationTimeout:300}},autoTrackSelection:{bitrateFactorAtEmptyBuffer:2.8,bitrateAudioFactorAtEmptyBuffer:10,bitrateFactorAtFullBuffer:2,bitrateAudioFactorAtFullBuffer:7,minVideoAudioRatio:5,minAvailableThroughputAudioRatio:5,usePixelRatio:!0,pixelRatioMultiplier:void 0,pixelRatioLogBase:3,pixelRatioLogCoefficients:[1,0,1],limitByContainer:!0,containerSizeFactor:1.3,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldownIncreaseQuality:15e3,trackCooldownDecreaseQuality:3e3,backgroundVideoQualityLimit:Yn.Q_4320P,activeVideoAreaThreshold:.1,highQualityLimit:Yn.Q_720P,trafficSavingLimit:Yn.Q_480P},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:Yn.Q_480P},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,seekBiasInTheEnd:2e3,maxSegmentDurationLeftToSelectNextSegment:3e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:3e3,crashOnStallTimeout:25e3,crashOnStallTWithoutDataTimeout:5e3,enableSubSegmentBufferFeeding:!0,bufferEmptinessTolerance:100,useFetchPriorityHints:!0,qualityLimitsOnStall:{stallDurationNoDataBeforeQualityDecrease:500,stallDurationToBeCount:100,stallCountBeforeQualityDecrease:3,resetQualityRestrictionTimeout:1e4,ignoreStallsOnSeek:!1},enableBaseUrlSupport:!0,maxSegmentRetryCount:5,sourceOpenTimeout:1e3,rejectOnSourceOpenTimeout:!1},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,maxLiveDuration:7200,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:250,playbackCatchupSpeedup:.05,isActiveOnDefault:!1,bufferEstimator:{emaAlpha:.45,changeThreshold:.05,deviationDepth:20,deviationFactor:.5,extremumInterval:5}}},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1,lowLatencyActiveLiveDelay:3e3,activeLiveDelay:5e3,maxPausedTime:5e3},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,forceFormat:void 0,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:"07A4434E",useWebmBigRequest:!1,webmCodec:"vp9",androidPreferredFormat:"dash",preferCMAF:!1,preferWebRTC:!1,preferMultiStream:!1,preferHDR:!1,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,seekNearDurationBias:1,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useHlsJs:!1,useNativeHLSTextTracks:!1,useManagedMediaSource:!0,useNewSwitchTo:!1,useSafariEndlessRequestBugfix:!0,useRefactoredSearchGap:!1,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,manifestRetryInterval:300,manifestRetryMaxInterval:1e4,manifestRetryMaxCount:10,audioVideoSyncRate:20,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50},useVolumeMultiplier:!1,ignoreAudioRendererError:!1,useEnableSubtitlesParam:!1,useOldMSEDetection:!1,useHlsLiveNewTextManager:!1,exposeInternalsToGlobal:!1,hlsLiveNewTextManagerDownloadThreshold:4e3,disableYandexPiP:!1,asyncResolveClientChecker:!1},BT=a=>{var e;return M(P({},y0(a,_T)),{configName:[...(e=a.configName)!=null?e:[],..._T.configName]})};import{assertNonNullable as zn,combine as It,ErrorCategory as Kn,filter as V,filterChanged as X,fromEvent as kc,isNonNullable as A0,isNullable as k0,Logger as $0,map as Y,mapTo as UT,merge as Gt,now as Xn,once as j,Subject as J,Subscription as HT,tap as $c,ValueSubject as w,isHigher as R0,isInvariantQuality as jT,flattenObject as Wt,throttle as Rc,getTraceSubscriptionMethod as QT,Tracer as L0,InternalsExposure as M0}from"@vkontakte/videoplayer-shared/es2015";import{merge as T0,map as I0,filter as NT,isNonNullable as E0}from"@vkontakte/videoplayer-shared/es2015";var Ac=({seekState:a,position$:e})=>T0(a.stateChangeEnded$.pipe(I0(({to:t})=>{var r;return t.state==="none"?void 0:((r=t.position)!=null?r:NaN)/1e3}),NT(E0)),e.pipe(NT(()=>a.getState().state==="none")));import{assertNonNullable as x0}from"@vkontakte/videoplayer-shared/es2015";var FT=a=>{let e=typeof a.container=="string"?document.getElementById(a.container):a.container;return x0(e,`Wrong container or containerId {${a.container}}`),e};import{filter as P0,once as w0}from"@vkontakte/videoplayer-shared/es2015";var qT=(a,e,t,r)=>{a!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&(t==null?void 0:t.getValue().length)===0?t.pipe(P0(i=>i.length>0),w0()).subscribe(i=>{i.find(r)&&e.startTransitionTo(a)}):(a===void 0||t!=null&&t.getValue().find(r))&&e.startTransitionTo(a)};var Jn=class{constructor(e={configName:[]},t=L0.createRootTracer(!1)){this.subscription=new HT;this.logger=new $0;this.abrLogger=this.logger.createComponentLog("ABR");this.internalsExposure=null;this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new w(!1);this.hasLiveOffsetByPausedTimer=0;this.playerInited=new w(!1);this.wasSetStartedQuality=!1;this.desiredState={playbackState:new N("stopped"),seekState:new N({state:"none"}),volume:new N({volume:1,muted:!1}),videoTrack:new N(void 0),videoStream:new N(void 0),audioStream:new N(void 0),autoVideoTrackSwitching:new N(!0),autoVideoTrackLimits:new N({}),isLooped:new N(!1),isLowLatency:new N(!1),playbackRate:new N(1),externalTextTracks:new N([]),internalTextTracks:new N([]),currentTextTrack:new N(void 0),textTrackCuesSettings:new N({}),cameraOrientation:new N({x:0,y:0})};this.info={playbackState$:new w(void 0),position$:new w(0),duration$:new w(1/0),muted$:new w(!1),volume$:new w(1),availableVideoStreams$:new w([]),currentVideoStream$:new w(void 0),availableQualities$:new w([]),availableQualitiesFps$:new w({}),currentQuality$:new w(void 0),isAutoQualityEnabled$:new w(!0),autoQualityLimitingAvailable$:new w(!1),autoQualityLimits$:new w({}),predefinedQualityLimitType$:new w("unknown"),availableAudioStreams$:new w([]),currentAudioStream$:new w(void 0),availableAudioTracks$:new w([]),isAudioAvailable$:new w(!0),currentPlaybackRate$:new w(1),currentBuffer$:new w({start:0,end:0}),isBuffering$:new w(!0),isStalled$:new w(!1),isEnded$:new w(!1),isLooped$:new w(!1),isLive$:new w(void 0),isLiveEnded$:new w(null),canChangePlaybackSpeed$:new w(void 0),atLiveEdge$:new w(void 0),atLiveDurationEdge$:new w(void 0),liveTime$:new w(void 0),liveBufferTime$:new w(void 0),liveLatency$:new w(void 0),currentFormat$:new w(void 0),availableTextTracks$:new w([]),currentTextTrack$:new w(void 0),throughputEstimation$:new w(void 0),rttEstimation$:new w(void 0),videoBitrate$:new w(void 0),hostname$:new w(void 0),httpConnectionType$:new w(void 0),httpConnectionReused$:new w(void 0),surface$:new w("none"),chromecastState$:new w("NOT_AVAILABLE"),chromecastDeviceName$:new w(void 0),intrinsicVideoSize$:new w(void 0),availableSources$:new w(void 0),is3DVideo$:new w(!1),currentVideoSegmentLength$:new w(0),currentAudioSegmentLength$:new w(0)};this.events={inited$:new J,ready$:new J,started$:new J,playing$:new J,paused$:new J,stopped$:new J,willStart$:new J,willResume$:new J,willPause$:new J,willStop$:new J,willDestruct$:new J,watchCoverageRecord$:new J,watchCoverageLive$:new J,managedError$:new J,fatalError$:new J,fetcherRecoverableError$:new J,ended$:new J,looped$:new J,seeked$:new J,willSeek$:new J,autoplaySoundProhibited$:new J,firstBytes$:new J,loadedMetadata$:new J,firstFrame$:new J,canplay$:new J,log$:new J,fetcherError$:new J,severeStallOccured$:new J};this.experimental={element$:new w(void 0),tuningConfigName$:new w([]),enableDebugTelemetry$:new w(!1),dumpTelemetry:Zg,getCurrentTime$:new w(null)};if(this.initLogs(),this.tuning=BT(e),this.tracer=t,this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new Is({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new OT(this.tuning.throughputEstimator),e.exposeInternalsToGlobal&&(this.internalsExposure=new M0("CORE"),this.internalsExposure.expose({player:this})),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(r,i,s)=>{let n=Reflect.get(r,i,s);return typeof n!="function"?n:(...o)=>{try{return n.apply(r,o)}catch(u){let l=o.map(p=>JSON.stringify(p,(h,m)=>{let b=typeof m;return(0,GT.default)(["number","string","boolean"],b)?m:m===null?null:`<${b}>`})),c=`Player.${String(i)}`,d=`Exception calling ${c} (${l.join(", ")})`;throw this.events.fatalError$.next({id:c,category:Kn.WTF,message:d,thrown:u}),u}}}})}initVideo(e){var i;this.config=e,(i=this.internalsExposure)==null||i.expose({config:e,logger:this.logger,tuning:this.tuning});let t=()=>{var u,l,c;let o=e,{container:s}=o,n=gd(o,["container"]);this.tracer.log("initVideo",Wt(n)),this.domContainer=FT(e),this.chromecastInitializer.contentId=(u=e.meta)==null?void 0:u.videoId,this.providerContainer=new Za({sources:e.sources,meta:(l=e.meta)!=null?l:{},failoverHosts:(c=e.failoverHosts)!=null?c:[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,tracer:this.tracer,logger:this.logger,abrLogger:this.abrLogger},tuning:this.tuning,volumeMultiplier:e.volumeMultiplier}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.initTracerSubscription(),this.providerContainer.init(),this.setLiveLowLatency(this.tuning.dashCmafLive.lowLatency.isActiveOnDefault),this.setMuted(this.tuning.isAudioDisabled),this.initDebugTelemetry(),this.initWakeLock(),this.playerInited.next(!0)},r=()=>{this.tuning.asyncResolveClientChecker?H.isInited$.pipe(V(s=>!!s),j()).subscribe(()=>{console.log("Core SDK async start"),t()}):t()};return this.isNotActiveTabCase()?(this.tracer.log("request play from hidden tab"),kc(document,"visibilitychange").pipe(j()).subscribe(r)):r(),this}destroy(){var e,t;this.tracer.log("destroy"),window.clearTimeout(this.hasLiveOffsetByPausedTimer),this.events.willDestruct$.next(),this.stop(),(e=this.providerContainer)==null||e.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe(),this.tracer.end(),(t=this.internalsExposure)==null||t.destroy()}prepare(){return this.playerInited.pipe(V(e=>!!e),j()).subscribe(()=>{let e=this.desiredState.playbackState;this.tracer.log("prepare",{currentPlayBackState:e.getState()}),e.getState()==="stopped"&&e.startTransitionTo("ready")}),this}play(){return this.playerInited.pipe(V(e=>!!e),j()).subscribe(()=>{let e=this.desiredState.playbackState;this.tracer.log("play",{currentPlayBackState:e.getState()}),e.getState()!=="playing"&&e.startTransitionTo("playing")}),this}pause(){return this.playerInited.pipe(V(e=>!!e),j()).subscribe(()=>{let e=this.desiredState.playbackState;this.tracer.log("pause",{currentPlayBackState:e.getState()}),e.getState()!=="paused"&&e.startTransitionTo("paused")}),this}stop(){return this.playerInited.pipe(V(e=>!!e),j()).subscribe(()=>{let e=this.desiredState.playbackState;this.tracer.log("stop",{currentPlayBackState:e.getState()}),e.getState()!=="stopped"&&e.startTransitionTo("stopped")}),this}seekTime(e,t=!0){return this.playerInited.pipe(V(r=>!!r),j()).subscribe(()=>{let r=this.info.duration$.getValue(),i=this.info.isLive$.getValue(),s=e;e>=r&&!i&&(s=r-this.tuning.seekNearDurationBias),this.tracer.log("seekTime",{duration:r,isLive:i,time:e,calculatedTime:s,forcePrecise:t}),Number.isFinite(s)&&(this.events.willSeek$.next({from:this.getExactTime(),to:s}),this.desiredState.seekState.setState({state:"requested",position:s*1e3,forcePrecise:t}))}),this}seekPercent(e){return this.playerInited.pipe(V(t=>!!t),j()).subscribe(()=>{let t=this.info.duration$.getValue();this.tracer.log("seekPercent",{percent:e,duration:t}),isFinite(t)&&this.seekTime(Math.abs(t)*e,!1)}),this}setVolume(e,t){return this.playerInited.pipe(V(r=>!!r),j()).subscribe(()=>{let r=this.desiredState.volume,i=this.info.muted$.getValue(),s=t!=null?t:this.tuning.isAudioDisabled||i;this.tracer.log("setVolume",{volume:e,isAudioDisabled:this.tuning.isAudioDisabled,chromecastState:this.chromecastInitializer.castState$.getValue(),muted:s}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setVolume(e):r.startTransitionTo({volume:e,muted:s})}),this}setMuted(e){return this.playerInited.pipe(V(t=>!!t),j()).subscribe(()=>{let t=this.tuning.isAudioDisabled||e,r=this.info.volume$.getValue();this.tracer.log("setMuted",{isMuted:e,nextMuted:t,volume:r,isAudioDisabled:this.tuning.isAudioDisabled,chromecastState:this.chromecastInitializer.castState$.getValue()}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setMuted(t):this.desiredState.volume.startTransitionTo({volume:r,muted:t})}),this}setVideoStream(e){return this.playerInited.pipe(V(t=>!!t),j()).subscribe(()=>{this.desiredState.videoStream.startTransitionTo(e)}),this}setAudioStream(e){return this.playerInited.pipe(V(t=>!!t),j()).subscribe(()=>{this.desiredState.audioStream.startTransitionTo(e)}),this}setQuality(e){return this.playerInited.pipe(V(t=>!!t),j()).subscribe(()=>{zn(this.providerContainer);let t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();this.tracer.log("setQuality",{isDelayed:t.length===0,quality:e}),this.desiredState.videoTrack.getState()===void 0&&this.desiredState.videoTrack.getPrevState()===void 0&&t.length===0?this.wasSetStartedQuality?this.providerContainer.providerOutput.availableVideoTracks$.pipe(V(r=>r.length>0),j()).subscribe(r=>{this.setVideoTrackIdByQuality(r,e)}):this.explicitInitialQuality=e:t.length>0&&this.setVideoTrackIdByQuality(t,e)}),this}setAutoQuality(e){return this.playerInited.pipe(V(t=>!!t),j()).subscribe(()=>{this.tracer.log("setAutoQuality",{enable:e}),this.desiredState.autoVideoTrackSwitching.startTransitionTo(e)}),this}setAutoQualityLimits(e){return this.playerInited.pipe(V(t=>!!t),j()).subscribe(()=>{this.tracer.log("setAutoQualityLimits",Wt(e)),this.desiredState.autoVideoTrackLimits.startTransitionTo(e)}),this}setPredefinedQualityLimits(e){return this.playerInited.pipe(V(t=>!!t),j()).subscribe(()=>{let{highQualityLimit:t,trafficSavingLimit:r}=this.tuning.autoTrackSelection,i;switch(e){case"high_quality":i={min:t,max:void 0};break;case"traffic_saving":i={max:r,min:void 0};break;default:i={max:void 0,min:void 0}}this.setAutoQualityLimits(i)}),this}setPlaybackRate(e){return this.playerInited.pipe(V(t=>!!t),j()).subscribe(()=>{var r;zn(this.providerContainer);let t=(r=this.providerContainer)==null?void 0:r.providerOutput.element$.getValue();this.tracer.log("setPlaybackRate",{playbackRate:e,isVideoElementAvailable:!!t}),t&&(this.desiredState.playbackRate.setState(e),t.playbackRate=e)}),this}setExternalTextTracks(e){return this.playerInited.pipe(V(t=>!!t),j()).subscribe(()=>{e.length&&this.tracer.log("setExternalTextTracks",Wt(e)),this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>P({type:"external"},t)))}),this}selectTextTrack(e){return this.playerInited.pipe(V(t=>!!t),j()).subscribe(()=>{var t;qT(e,this.desiredState.currentTextTrack,(t=this.providerContainer)==null?void 0:t.providerOutput.availableTextTracks$,r=>r.id===e),this.tracer.log("selectTextTrack",{textTrackId:e})}),this}setTextTrackCueSettings(e){return this.playerInited.pipe(V(t=>!!t),j()).subscribe(()=>{this.tracer.log("setTextTrackCueSettings",P({},e)),this.desiredState.textTrackCuesSettings.startTransitionTo(e)}),this}setLiveLowLatency(e){let t=this.info.isLive$.getValue(),r=this.desiredState.isLowLatency.getState();return!t||r===e?this:(this.tracer.log("live switch to low latency "+e),this.desiredState.isLowLatency.setState(e),this.seekTime(0))}setLooped(e){return this.playerInited.pipe(V(t=>!!t),j()).subscribe(()=>{this.tracer.log("setLooped",{isLooped:e}),this.desiredState.isLooped.startTransitionTo(e)}),this}toggleChromecast(){this.tracer.log("toggleChromecast"),this.chromecastInitializer.toggleConnection()}startCameraManualRotation(e,t){return this.playerInited.pipe(V(r=>!!r),j()).subscribe(()=>{let r=this.getScene3D();this.tracer.log("startCameraManualRotation",{isScene3DAvailable:!!r,mx:e,my:t}),r&&r.startCameraManualRotation(e,t)}),this}stopCameraManualRotation(e=!1){return this.playerInited.pipe(V(t=>!!t),j()).subscribe(()=>{let t=this.getScene3D();this.tracer.log("stopCameraManualRotation",{isScene3DAvailable:!!t,immediate:e}),t&&t.stopCameraManualRotation(e)}),this}moveCameraFocusPX(e,t){return this.playerInited.pipe(V(r=>!!r),j()).subscribe(()=>{let r=this.getScene3D();if(this.tracer.log("moveCameraFocusPX",{isScene3DAvailable:!!r,dxpx:e,dypx:t}),r){let i=r.getCameraRotation(),s=r.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:i.x+s.x,y:i.y+s.y})}}),this}holdCamera(){return this.playerInited.pipe(V(e=>e),j()).subscribe(()=>{let e=this.getScene3D();e&&e.holdCamera()}),this}releaseCamera(){return this.playerInited.pipe(V(e=>!!e),j()).subscribe(()=>{let e=this.getScene3D();e&&e.releaseCamera()}),this}getExactTime(){if(!this.providerContainer)return 0;let e=this.providerContainer.providerOutput.element$.getValue();if(k0(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),r=t.state==="none"?void 0:t.position;return A0(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(Gt(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(Y(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(Y(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(Y(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(Y(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(Y(e=>e.to)).subscribe(e=>{this.info.autoQualityLimits$.next(e);let{highQualityLimit:t,trafficSavingLimit:r}=this.tuning.autoTrackSelection;this.info.predefinedQualityLimitType$.next(pl({limits:e,highQualityLimit:t,trafficSavingLimit:r}))})),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(V(({from:e})=>e==="stopped"),j()).subscribe(()=>{this.initedAt=Xn(),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",Wt(n)),n.state==="requested"?this.desiredState.seekState.setState(M(P({},n),{state:"applying"})):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:Kn.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.soundProhibitedEvent$.pipe(j()).subscribe(this.events.autoplaySoundProhibited$)).add(e.providerOutput.severeStallOccurred$.subscribe(this.events.severeStallOccured$)).add(e.providerOutput.seekedEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();this.tracer.log("seekedEvent",Wt(n)),n.state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe(Y(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(Y(n=>n.destination),X()).subscribe(()=>this.isPlaybackStarted=!1)).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add(It({availableVideoTracks:e.providerOutput.availableVideoTracks$,currentVideoStream:e.providerOutput.currentVideoStream$}).pipe(Y(({availableVideoTracks:n,currentVideoStream:o})=>n.filter(u=>o?o.id===u.streamId:!0).map(({quality:u})=>u).sort((u,l)=>jT(u)?1:jT(l)?-1:R0(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(X()).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(X((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.pipe(X((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe(X()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(X()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(X()).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(Y(n=>n?{start:n.from,end:n.to}:{start:0,end:0})).subscribe(this.info.currentBuffer$)).add(e.providerOutput.duration$.subscribe(this.info.duration$)).add(e.providerOutput.isBuffering$.subscribe(this.info.isBuffering$)).add(e.providerOutput.isLive$.subscribe(this.info.isLive$)).add(e.providerOutput.isLiveEnded$.pipe($c(n=>n&&this.stop())).subscribe(this.info.isLiveEnded$)).add(e.providerOutput.canChangePlaybackSpeed$.subscribe(this.info.canChangePlaybackSpeed$)).add(e.providerOutput.liveTime$.subscribe(this.info.liveTime$)).add(e.providerOutput.liveBufferTime$.subscribe(this.info.liveBufferTime$)).add(e.providerOutput.liveLatency$.subscribe(this.info.liveLatency$)).add(It({hasLiveOffsetByPaused:Gt(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(Y(n=>n.to),X(),Y(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(It({atLiveEdge:It({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:Ac({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(Y(({isLive:n,position:o,isLowLatency:u})=>{let l=this.getActiveLiveDelay(u);return n&&Math.abs(o)<l/1e3}),X(),$c(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(Y(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add(It({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(Y(({isLive:n,position:o,duration:u})=>n&&(Math.abs(u)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),X(),$c(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(Y(n=>n.muted),X()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(Y(n=>n.volume),X()).subscribe(this.info.volume$)).add(Ac({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(Gt(e.providerOutput.endedEvent$.pipe(UT(!0)),e.providerOutput.seekedEvent$.pipe(UT(!1))).pipe(X()).subscribe(this.info.isEnded$)).add(e.providerOutput.endedEvent$.subscribe(this.events.ended$)).add(e.providerOutput.loopedEvent$.subscribe(this.events.looped$)).add(e.providerError$.subscribe(this.events.managedError$)).add(e.providerOutput.fetcherRecoverableError$.subscribe(this.events.fetcherRecoverableError$)).add(e.providerOutput.fetcherError$.subscribe(this.events.fatalError$)).add(e.volumeMultiplierError$.subscribe(this.events.managedError$)).add(e.noAvailableProvidersError$.pipe(Y(n=>({id:n?`No${n}`:"NoProviders",category:Kn.VIDEO_PIPELINE,message:n?`${n} was forced but failed or not available`:"No suitable providers or all providers failed"}))).subscribe(this.events.fatalError$)).add(e.providerOutput.element$.subscribe(this.experimental.element$)).add(e.providerOutput.getCurrentTime$.subscribe(this.experimental.getCurrentTime$)).add(e.providerOutput.firstBytesEvent$.pipe(j(),Y(n=>n!=null?n:Xn()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe(j(),Y(()=>Xn()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(j(),Y(()=>Xn()-this.initedAt)).subscribe(this.events.canplay$)).add(this.throughputEstimator.throughput$.subscribe(this.info.throughputEstimation$)).add(this.throughputEstimator.rtt$.subscribe(this.info.rttEstimation$)).add(e.providerOutput.availableSources$.subscribe(this.info.availableSources$));let t=new w(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let r=new w(!0);this.subscription.add(e.current$.subscribe(()=>r.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(V(({to:n})=>n==="playing"),j()).subscribe(()=>r.next(!1)));let i=0,s=Gt(e.providerOutput.isBuffering$,t,r).pipe(Y(()=>{let n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||r.getValue();return n&&!o}),X());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(Gt(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(Gt(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,e.providerOutput.elementVisible$,this.chromecastInitializer.castState$).subscribe(()=>{let n=e.providerOutput.inPiP$.getValue(),o=e.providerOutput.inFullscreen$.getValue(),u=e.providerOutput.element$.getValue(),l=e.providerOutput.elementVisible$.getValue(),c=this.chromecastInitializer.castState$.getValue(),d;c==="CONNECTED"?d="second_screen":u?l?n?d="pip":o?d="fullscreen":d="inline":d="invisible":d="none",this.info.surface$.getValue()!==d&&this.info.surface$.next(d)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(Y(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 HT;this.subscription.add(t),this.subscription.add(e.current$.pipe(X((r,i)=>r.provider===i.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(V(r=>r.length>0),j()).subscribe(r=>{this.setStartingVideoTrack(r)}))}))}setStartingVideoTrack(e){var i;let t;this.wasSetStartedQuality=!0;let r=(i=this.explicitInitialQuality)!=null?i:this.info.currentQuality$.getValue();r&&(t=e.find(({quality:s})=>s===r),t||this.setAutoQuality(!0)),t||(t=Ft(e,{container:this.domContainer.getBoundingClientRect(),estimatedThroughput:this.throughputEstimator.throughput$.getValue(),tuning:this.tuning.autoTrackSelection,limits:this.desiredState.autoVideoTrackLimits.getState(),playbackRate:this.info.currentPlaybackRate$.getValue(),forwardBufferHealth:0,abrLogger:this.abrLogger})),this.desiredState.videoTrack.startTransitionTo(t),this.info.currentQuality$.next(t.quality),this.info.videoBitrate$.next(t.bitrate)}initLogs(){this.subscription.add(Gt(this.desiredState.videoTrack.stateChangeStarted$.pipe(Y(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(Y(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(Y(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(Y(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(Y(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(Y(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(Y(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(Y(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(Y(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;zn(this.providerContainer),zn(e),Jg(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(r=>Xg(r)),this.providerContainer.current$.subscribe(({type:r})=>Qi("provider",r)),e.duration$.subscribe(r=>Qi("duration",r)),e.availableVideoTracks$.pipe(V(r=>!!r.length),j()).subscribe(r=>Qi("tracks",r)),this.events.fatalError$.subscribe(new Ie("fatalError")),this.events.managedError$.subscribe(new Ie("managedError")),e.position$.subscribe(new Ie("position")),e.currentVideoTrack$.pipe(Y(r=>r==null?void 0:r.quality)).subscribe(new Ie("quality")),this.info.currentBuffer$.subscribe(new Ie("buffer")),e.isBuffering$.subscribe(new Ie("isBuffering"))].forEach(r=>this.subscription.add(r)),Qi("codecs",H.video.supportedCodecs)}initTracerSubscription(){let e=QT(this.tracer.log.bind(this.tracer)),t=QT(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(X()).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(It({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe(V(({currentQuality:r,videoBitrate:i})=>!!r&&!!i),X((r,i)=>r.currentQuality===i.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe(V(r=>r>0),X()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe(V(r=>r>0),X()).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(It({currentBuffer:this.info.currentBuffer$.pipe(V(r=>r.end>0),X((r,i)=>r.end===i.end&&r.start===i.start)),position:this.info.position$.pipe(X())}).pipe(Rc(1e3)).subscribe(e("currentBufferAndPosition"))).add(this.info.duration$.pipe(X()).subscribe(e("duration"))).add(this.info.isBuffering$.subscribe(e("isBuffering"))).add(this.info.isLive$.pipe(X()).subscribe(e("isLive"))).add(this.info.canChangePlaybackSpeed$.pipe(X()).subscribe(e("canChangePlaybackSpeed"))).add(It({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe(V(({liveTime:r,liveBufferTime:i})=>!!r&&!!i),Rc(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe(X(),V(r=>r===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe(X(),V(r=>r===!0)).subscribe(e("atLiveDurationEdge"))).add(this.info.muted$.pipe(X()).subscribe(e("muted"))).add(this.info.volume$.pipe(X()).subscribe(e("volume"))).add(this.info.isEnded$.pipe(X(),V(r=>r===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add(It({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe(V(({throughputEstimation:r,rtt:i})=>!!r&&!!i),Rc(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe(X(),V(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=()=>E(this,null,function*(){t(),e=yield window.navigator.wakeLock.request("screen").catch(i=>{i instanceof DOMException&&i.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:Kn.DOM,message:String(i)})})});this.subscription.add(Gt(kc(document,"visibilitychange"),kc(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",Wt({quality:t,availableTracks:Wt(e),track:Wt(r),isAutoQuality:!r})),r?this.desiredState.videoTrack.startTransitionTo(r):this.setAutoQuality(!0)}getActiveLiveDelay(e=!1){return e?this.tuning.live.lowLatencyActiveLiveDelay:this.tuning.live.activeLiveDelay}isNotActiveTabCase(){return document.hidden&&this.tuning.autoplayOnlyInActiveTab&&!Ji()}};import{Subscription as J5,Observable as Z5,Subject as e8,ValueSubject as t8,VideoQuality as r8}from"@vkontakte/videoplayer-shared/es2015";var i8=`@vkontakte/videoplayer-core@${vd}`;export{fs as ChromecastState,no as HttpConnectionType,Z5 as Observable,De as PlaybackState,Jn as Player,bs as PredefinedQualityLimits,i8 as SDK_VERSION,e8 as Subject,J5 as Subscription,oo as Surface,vd as VERSION,t8 as ValueSubject,pt as VideoFormat,r8 as VideoQuality,H as clientChecker,Hi as isMobile};
|