@vkontakte/videoplayer-core 2.0.130 → 2.0.131-dev.ba1a65a9.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.esm.js CHANGED
@@ -1,19 +1,19 @@
1
1
  /**
2
- * @vkontakte/videoplayer-core v2.0.130
3
- * Thu, 10 Apr 2025 15:50:39 GMT
4
- * https://st.mycdn.me/static/vkontakte-videoplayer/2-0-130/doc/
2
+ * @vkontakte/videoplayer-core v2.0.131-dev.ba1a65a9.0
3
+ * Mon, 14 Apr 2025 14:27:25 GMT
4
+ * https://st.mycdn.me/static/vkontakte-videoplayer/2-0-131/doc/
5
5
  */
6
- var iI=Object.create;var ro=Object.defineProperty,rI=Object.defineProperties,aI=Object.getOwnPropertyDescriptor,sI=Object.getOwnPropertyDescriptors,nI=Object.getOwnPropertyNames,hs=Object.getOwnPropertySymbols,oI=Object.getPrototypeOf,ao=Object.prototype.hasOwnProperty,gd=Object.prototype.propertyIsEnumerable;var uI=(a,e)=>(e=Symbol[a])?e:Symbol.for("Symbol."+a);var at=Math.pow,bd=(a,e,t)=>e in a?ro(a,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):a[e]=t,w=(a,e)=>{for(var t in e||(e={}))ao.call(e,t)&&bd(a,t,e[t]);if(hs)for(var t of hs(e))gd.call(e,t)&&bd(a,t,e[t]);return a},D=(a,e)=>rI(a,sI(e));var vd=(a,e)=>{var t={};for(var i in a)ao.call(a,i)&&e.indexOf(i)<0&&(t[i]=a[i]);if(a!=null&&hs)for(var i of hs(a))e.indexOf(i)<0&&gd.call(a,i)&&(t[i]=a[i]);return t};var f=(a,e)=>()=>(e||a((e={exports:{}}).exports,e),e.exports);var lI=(a,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of nI(e))!ao.call(a,r)&&r!==t&&ro(a,r,{get:()=>e[r],enumerable:!(i=aI(e,r))||i.enumerable});return a};var O=(a,e,t)=>(t=a!=null?iI(oI(a)):{},lI(e||!a||!a.__esModule?ro(t,"default",{value:a,enumerable:!0}):t,a));var E=(a,e,t)=>new Promise((i,r)=>{var s=u=>{try{o(t.next(u))}catch(l){r(l)}},n=u=>{try{o(t.throw(u))}catch(l){r(l)}},o=u=>u.done?i(u.value):Promise.resolve(u.value).then(s,n);o((t=t.apply(a,e)).next())}),ms=function(a,e){this[0]=a,this[1]=e},ue=(a,e,t)=>{var i=(n,o,u,l)=>{try{var c=t[n](o),d=(o=c.value)instanceof ms,h=c.done;Promise.resolve(d?o[0]:o).then(p=>d?i(n==="return"?n:"next",o[1]?{done:p.done,value:p.value}:p,u,l):u({value:p,done:h})).catch(p=>i("throw",p,u,l))}catch(p){l(p)}},r=n=>s[n]=o=>new Promise((u,l)=>i(n,o,u,l)),s={};return t=t.apply(a,e),s[uI("asyncIterator")]=()=>s,r("next"),r("throw"),r("return"),s};var ne=f((oo,yd)=>{"use strict";var gr=function(a){return a&&a.Math===Math&&a};yd.exports=gr(typeof globalThis=="object"&&globalThis)||gr(typeof window=="object"&&window)||gr(typeof self=="object"&&self)||gr(typeof global=="object"&&global)||gr(typeof oo=="object"&&oo)||function(){return this}()||Function("return this")()});var fe=f((B0,Td)=>{"use strict";Td.exports=function(a){try{return!!a()}catch(e){return!0}}});var vr=f((N0,Id)=>{"use strict";var cI=fe();Id.exports=!cI(function(){var a=function(){}.bind();return typeof a!="function"||a.hasOwnProperty("prototype")})});var uo=f((F0,wd)=>{"use strict";var dI=vr(),Pd=Function.prototype,Ed=Pd.apply,xd=Pd.call;wd.exports=typeof Reflect=="object"&&Reflect.apply||(dI?xd.bind(Ed):function(){return xd.apply(Ed,arguments)})});var ce=f((q0,Rd)=>{"use strict";var kd=vr(),Ad=Function.prototype,lo=Ad.call,pI=kd&&Ad.bind.bind(lo,lo);Rd.exports=kd?pI:function(a){return function(){return lo.apply(a,arguments)}}});var ii=f((U0,Ld)=>{"use strict";var $d=ce(),hI=$d({}.toString),mI=$d("".slice);Ld.exports=function(a){return mI(hI(a),8,-1)}});var co=f((H0,Md)=>{"use strict";var fI=ii(),bI=ce();Md.exports=function(a){if(fI(a)==="Function")return bI(a)}});var ae=f((j0,Dd)=>{"use strict";var po=typeof document=="object"&&document.all;Dd.exports=typeof po=="undefined"&&po!==void 0?function(a){return typeof a=="function"||a===po}:function(a){return typeof a=="function"}});var Ve=f((Q0,Cd)=>{"use strict";var gI=fe();Cd.exports=!gI(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var Oe=f((G0,Vd)=>{"use strict";var vI=vr(),gs=Function.prototype.call;Vd.exports=vI?gs.bind(gs):function(){return gs.apply(gs,arguments)}});var ho=f(Bd=>{"use strict";var Od={}.propertyIsEnumerable,_d=Object.getOwnPropertyDescriptor,SI=_d&&!Od.call({1:2},1);Bd.f=SI?function(e){var t=_d(this,e);return!!t&&t.enumerable}:Od});var Sr=f((Y0,Nd)=>{"use strict";Nd.exports=function(a,e){return{enumerable:!(a&1),configurable:!(a&2),writable:!(a&4),value:e}}});var qd=f((z0,Fd)=>{"use strict";var yI=ce(),TI=fe(),II=ii(),mo=Object,EI=yI("".split);Fd.exports=TI(function(){return!mo("z").propertyIsEnumerable(0)})?function(a){return II(a)==="String"?EI(a,""):mo(a)}:mo});var Ri=f((K0,Ud)=>{"use strict";Ud.exports=function(a){return a==null}});var Mt=f((X0,Hd)=>{"use strict";var xI=Ri(),PI=TypeError;Hd.exports=function(a){if(xI(a))throw new PI("Can't call method on "+a);return a}});var ri=f((J0,jd)=>{"use strict";var wI=qd(),kI=Mt();jd.exports=function(a){return wI(kI(a))}});var _e=f((Z0,Qd)=>{"use strict";var AI=ae();Qd.exports=function(a){return typeof a=="object"?a!==null:AI(a)}});var $i=f((eV,Gd)=>{"use strict";Gd.exports={}});var ft=f((tV,Yd)=>{"use strict";var fo=$i(),bo=ne(),RI=ae(),Wd=function(a){return RI(a)?a:void 0};Yd.exports=function(a,e){return arguments.length<2?Wd(fo[a])||Wd(bo[a]):fo[a]&&fo[a][e]||bo[a]&&bo[a][e]}});var yr=f((iV,zd)=>{"use strict";var $I=ce();zd.exports=$I({}.isPrototypeOf)});var ai=f((rV,Jd)=>{"use strict";var LI=ne(),Kd=LI.navigator,Xd=Kd&&Kd.userAgent;Jd.exports=Xd?String(Xd):""});var vo=f((aV,ap)=>{"use strict";var rp=ne(),go=ai(),Zd=rp.process,ep=rp.Deno,tp=Zd&&Zd.versions||ep&&ep.version,ip=tp&&tp.v8,Ye,vs;ip&&(Ye=ip.split("."),vs=Ye[0]>0&&Ye[0]<4?1:+(Ye[0]+Ye[1]));!vs&&go&&(Ye=go.match(/Edge\/(\d+)/),(!Ye||Ye[1]>=74)&&(Ye=go.match(/Chrome\/(\d+)/),Ye&&(vs=+Ye[1])));ap.exports=vs});var So=f((sV,np)=>{"use strict";var sp=vo(),MI=fe(),DI=ne(),CI=DI.String;np.exports=!!Object.getOwnPropertySymbols&&!MI(function(){var a=Symbol("symbol detection");return!CI(a)||!(Object(a)instanceof Symbol)||!Symbol.sham&&sp&&sp<41})});var yo=f((nV,op)=>{"use strict";var VI=So();op.exports=VI&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var To=f((oV,up)=>{"use strict";var OI=ft(),_I=ae(),BI=yr(),NI=yo(),FI=Object;up.exports=NI?function(a){return typeof a=="symbol"}:function(a){var e=OI("Symbol");return _I(e)&&BI(e.prototype,FI(a))}});var Tr=f((uV,lp)=>{"use strict";var qI=String;lp.exports=function(a){try{return qI(a)}catch(e){return"Object"}}});var st=f((lV,cp)=>{"use strict";var UI=ae(),HI=Tr(),jI=TypeError;cp.exports=function(a){if(UI(a))return a;throw new jI(HI(a)+" is not a function")}});var Ir=f((cV,dp)=>{"use strict";var QI=st(),GI=Ri();dp.exports=function(a,e){var t=a[e];return GI(t)?void 0:QI(t)}});var hp=f((dV,pp)=>{"use strict";var Io=Oe(),Eo=ae(),xo=_e(),WI=TypeError;pp.exports=function(a,e){var t,i;if(e==="string"&&Eo(t=a.toString)&&!xo(i=Io(t,a))||Eo(t=a.valueOf)&&!xo(i=Io(t,a))||e!=="string"&&Eo(t=a.toString)&&!xo(i=Io(t,a)))return i;throw new WI("Can't convert object to primitive value")}});var ze=f((pV,mp)=>{"use strict";mp.exports=!0});var gp=f((hV,bp)=>{"use strict";var fp=ne(),YI=Object.defineProperty;bp.exports=function(a,e){try{YI(fp,a,{value:e,configurable:!0,writable:!0})}catch(t){fp[a]=e}return e}});var Er=f((mV,yp)=>{"use strict";var zI=ze(),KI=ne(),XI=gp(),vp="__core-js_shared__",Sp=yp.exports=KI[vp]||XI(vp,{});(Sp.versions||(Sp.versions=[])).push({version:"3.38.0",mode:zI?"pure":"global",copyright:"\xA9 2014-2024 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.38.0/LICENSE",source:"https://github.com/zloirock/core-js"})});var Po=f((fV,Ip)=>{"use strict";var Tp=Er();Ip.exports=function(a,e){return Tp[a]||(Tp[a]=e||{})}});var Li=f((bV,Ep)=>{"use strict";var JI=Mt(),ZI=Object;Ep.exports=function(a){return ZI(JI(a))}});var Ke=f((gV,xp)=>{"use strict";var eE=ce(),tE=Li(),iE=eE({}.hasOwnProperty);xp.exports=Object.hasOwn||function(e,t){return iE(tE(e),t)}});var wo=f((vV,Pp)=>{"use strict";var rE=ce(),aE=0,sE=Math.random(),nE=rE(1 .toString);Pp.exports=function(a){return"Symbol("+(a===void 0?"":a)+")_"+nE(++aE+sE,36)}});var be=f((SV,kp)=>{"use strict";var oE=ne(),uE=Po(),wp=Ke(),lE=wo(),cE=So(),dE=yo(),Mi=oE.Symbol,ko=uE("wks"),pE=dE?Mi.for||Mi:Mi&&Mi.withoutSetter||lE;kp.exports=function(a){return wp(ko,a)||(ko[a]=cE&&wp(Mi,a)?Mi[a]:pE("Symbol."+a)),ko[a]}});var Lp=f((yV,$p)=>{"use strict";var hE=Oe(),Ap=_e(),Rp=To(),mE=Ir(),fE=hp(),bE=be(),gE=TypeError,vE=bE("toPrimitive");$p.exports=function(a,e){if(!Ap(a)||Rp(a))return a;var t=mE(a,vE),i;if(t){if(e===void 0&&(e="default"),i=hE(t,a,e),!Ap(i)||Rp(i))return i;throw new gE("Can't convert object to primitive value")}return e===void 0&&(e="number"),fE(a,e)}});var Ao=f((TV,Mp)=>{"use strict";var SE=Lp(),yE=To();Mp.exports=function(a){var e=SE(a,"string");return yE(e)?e:e+""}});var Ss=f((IV,Cp)=>{"use strict";var TE=ne(),Dp=_e(),Ro=TE.document,IE=Dp(Ro)&&Dp(Ro.createElement);Cp.exports=function(a){return IE?Ro.createElement(a):{}}});var $o=f((EV,Vp)=>{"use strict";var EE=Ve(),xE=fe(),PE=Ss();Vp.exports=!EE&&!xE(function(){return Object.defineProperty(PE("div"),"a",{get:function(){return 7}}).a!==7})});var Bp=f(_p=>{"use strict";var wE=Ve(),kE=Oe(),AE=ho(),RE=Sr(),$E=ri(),LE=Ao(),ME=Ke(),DE=$o(),Op=Object.getOwnPropertyDescriptor;_p.f=wE?Op:function(e,t){if(e=$E(e),t=LE(t),DE)try{return Op(e,t)}catch(i){}if(ME(e,t))return RE(!kE(AE.f,e,t),e[t])}});var Lo=f((PV,Np)=>{"use strict";var CE=fe(),VE=ae(),OE=/#|\.prototype\./,xr=function(a,e){var t=BE[_E(a)];return t===FE?!0:t===NE?!1:VE(e)?CE(e):!!e},_E=xr.normalize=function(a){return String(a).replace(OE,".").toLowerCase()},BE=xr.data={},NE=xr.NATIVE="N",FE=xr.POLYFILL="P";Np.exports=xr});var Di=f((wV,qp)=>{"use strict";var Fp=co(),qE=st(),UE=vr(),HE=Fp(Fp.bind);qp.exports=function(a,e){return qE(a),e===void 0?a:UE?HE(a,e):function(){return a.apply(e,arguments)}}});var Mo=f((kV,Up)=>{"use strict";var jE=Ve(),QE=fe();Up.exports=jE&&QE(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var nt=f((AV,Hp)=>{"use strict";var GE=_e(),WE=String,YE=TypeError;Hp.exports=function(a){if(GE(a))return a;throw new YE(WE(a)+" is not an object")}});var si=f(Qp=>{"use strict";var zE=Ve(),KE=$o(),XE=Mo(),ys=nt(),jp=Ao(),JE=TypeError,Do=Object.defineProperty,ZE=Object.getOwnPropertyDescriptor,Co="enumerable",Vo="configurable",Oo="writable";Qp.f=zE?XE?function(e,t,i){if(ys(e),t=jp(t),ys(i),typeof e=="function"&&t==="prototype"&&"value"in i&&Oo in i&&!i[Oo]){var r=ZE(e,t);r&&r[Oo]&&(e[t]=i.value,i={configurable:Vo in i?i[Vo]:r[Vo],enumerable:Co in i?i[Co]:r[Co],writable:!1})}return Do(e,t,i)}:Do:function(e,t,i){if(ys(e),t=jp(t),ys(i),KE)try{return Do(e,t,i)}catch(r){}if("get"in i||"set"in i)throw new JE("Accessors not supported");return"value"in i&&(e[t]=i.value),e}});var Ci=f(($V,Gp)=>{"use strict";var ex=Ve(),tx=si(),ix=Sr();Gp.exports=ex?function(a,e,t){return tx.f(a,e,ix(1,t))}:function(a,e,t){return a[e]=t,a}});var le=f((LV,Yp)=>{"use strict";var Pr=ne(),rx=uo(),ax=co(),sx=ae(),nx=Bp().f,ox=Lo(),Vi=$i(),ux=Di(),Oi=Ci(),Wp=Ke();Er();var lx=function(a){var e=function(t,i,r){if(this instanceof e){switch(arguments.length){case 0:return new a;case 1:return new a(t);case 2:return new a(t,i)}return new a(t,i,r)}return rx(a,this,arguments)};return e.prototype=a.prototype,e};Yp.exports=function(a,e){var t=a.target,i=a.global,r=a.stat,s=a.proto,n=i?Pr:r?Pr[t]:Pr[t]&&Pr[t].prototype,o=i?Vi:Vi[t]||Oi(Vi,t,{})[t],u=o.prototype,l,c,d,h,p,m,b,g,v;for(h in e)l=ox(i?h:t+(r?".":"#")+h,a.forced),c=!l&&n&&Wp(n,h),m=o[h],c&&(a.dontCallGetSet?(v=nx(n,h),b=v&&v.value):b=n[h]),p=c&&b?b:e[h],!(!l&&!s&&typeof m==typeof p)&&(a.bind&&c?g=ux(p,Pr):a.wrap&&c?g=lx(p):s&&sx(p)?g=ax(p):g=p,(a.sham||p&&p.sham||m&&m.sham)&&Oi(g,"sham",!0),Oi(o,h,g),s&&(d=t+"Prototype",Wp(Vi,d)||Oi(Vi,d,{}),Oi(Vi[d],h,p),a.real&&u&&(l||!u[h])&&Oi(u,h,p)))}});var Kp=f((MV,zp)=>{"use strict";var cx=Math.ceil,dx=Math.floor;zp.exports=Math.trunc||function(e){var t=+e;return(t>0?dx:cx)(t)}});var wr=f((DV,Xp)=>{"use strict";var px=Kp();Xp.exports=function(a){var e=+a;return e!==e||e===0?0:px(e)}});var Zp=f((CV,Jp)=>{"use strict";var hx=wr(),mx=Math.max,fx=Math.min;Jp.exports=function(a,e){var t=hx(a);return t<0?mx(t+e,0):fx(t,e)}});var _o=f((VV,eh)=>{"use strict";var bx=wr(),gx=Math.min;eh.exports=function(a){var e=bx(a);return e>0?gx(e,9007199254740991):0}});var _i=f((OV,th)=>{"use strict";var vx=_o();th.exports=function(a){return vx(a.length)}});var Bo=f((_V,rh)=>{"use strict";var Sx=ri(),yx=Zp(),Tx=_i(),ih=function(a){return function(e,t,i){var r=Sx(e),s=Tx(r);if(s===0)return!a&&-1;var n=yx(i,s),o;if(a&&t!==t){for(;s>n;)if(o=r[n++],o!==o)return!0}else for(;s>n;n++)if((a||n in r)&&r[n]===t)return a||n||0;return!a&&-1}};rh.exports={includes:ih(!0),indexOf:ih(!1)}});var kr=f((BV,ah)=>{"use strict";ah.exports=function(){}});var sh=f(()=>{"use strict";var Ix=le(),Ex=Bo().includes,xx=fe(),Px=kr(),wx=xx(function(){return!Array(1).includes()});Ix({target:"Array",proto:!0,forced:wx},{includes:function(e){return Ex(this,e,arguments.length>1?arguments[1]:void 0)}});Px("includes")});var Dt=f((qV,nh)=>{"use strict";var kx=ft();nh.exports=kx});var uh=f((UV,oh)=>{"use strict";sh();var Ax=Dt();oh.exports=Ax("Array","includes")});var ch=f((HV,lh)=>{"use strict";var Rx=uh();lh.exports=Rx});var qe=f((jV,dh)=>{"use strict";var $x=ch();dh.exports=$x});var Es=f((iO,Sh)=>{"use strict";var Bx=Po(),Nx=wo(),vh=Bx("keys");Sh.exports=function(a){return vh[a]||(vh[a]=Nx(a))}});var Th=f((rO,yh)=>{"use strict";var Fx=fe();yh.exports=!Fx(function(){function a(){}return a.prototype.constructor=null,Object.getPrototypeOf(new a)!==a.prototype})});var xs=f((aO,Eh)=>{"use strict";var qx=Ke(),Ux=ae(),Hx=Li(),jx=Es(),Qx=Th(),Ih=jx("IE_PROTO"),qo=Object,Gx=qo.prototype;Eh.exports=Qx?qo.getPrototypeOf:function(a){var e=Hx(a);if(qx(e,Ih))return e[Ih];var t=e.constructor;return Ux(t)&&e instanceof t?t.prototype:e instanceof qo?Gx:null}});var Ps=f((sO,xh)=>{"use strict";xh.exports={}});var kh=f((nO,wh)=>{"use strict";var Wx=ce(),Uo=Ke(),Yx=ri(),zx=Bo().indexOf,Kx=Ps(),Ph=Wx([].push);wh.exports=function(a,e){var t=Yx(a),i=0,r=[],s;for(s in t)!Uo(Kx,s)&&Uo(t,s)&&Ph(r,s);for(;e.length>i;)Uo(t,s=e[i++])&&(~zx(r,s)||Ph(r,s));return r}});var Ho=f((oO,Ah)=>{"use strict";Ah.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var jo=f((uO,Rh)=>{"use strict";var Xx=kh(),Jx=Ho();Rh.exports=Object.keys||function(e){return Xx(e,Jx)}});var Qo=f((lO,Ch)=>{"use strict";var Lh=Ve(),Zx=fe(),Mh=ce(),eP=xs(),tP=jo(),iP=ri(),rP=ho().f,Dh=Mh(rP),aP=Mh([].push),sP=Lh&&Zx(function(){var a=Object.create(null);return a[2]=2,!Dh(a,2)}),$h=function(a){return function(e){for(var t=iP(e),i=tP(t),r=sP&&eP(t)===null,s=i.length,n=0,o=[],u;s>n;)u=i[n++],(!Lh||(r?u in t:Dh(t,u)))&&aP(o,a?[u,t[u]]:t[u]);return o}};Ch.exports={entries:$h(!0),values:$h(!1)}});var Vh=f(()=>{"use strict";var nP=le(),oP=Qo().entries;nP({target:"Object",stat:!0},{entries:function(e){return oP(e)}})});var _h=f((pO,Oh)=>{"use strict";Vh();var uP=$i();Oh.exports=uP.Object.entries});var Nh=f((hO,Bh)=>{"use strict";var lP=_h();Bh.exports=lP});var Bi=f((mO,Fh)=>{"use strict";var cP=Nh();Fh.exports=cP});var ni=f((fO,qh)=>{"use strict";qh.exports={}});var jh=f((bO,Hh)=>{"use strict";var dP=ne(),pP=ae(),Uh=dP.WeakMap;Hh.exports=pP(Uh)&&/native code/.test(String(Uh))});var zo=f((gO,Wh)=>{"use strict";var hP=jh(),Gh=ne(),mP=_e(),fP=Ci(),Go=Ke(),Wo=Er(),bP=Es(),gP=Ps(),Qh="Object already initialized",Yo=Gh.TypeError,vP=Gh.WeakMap,ws,Ar,ks,SP=function(a){return ks(a)?Ar(a):ws(a,{})},yP=function(a){return function(e){var t;if(!mP(e)||(t=Ar(e)).type!==a)throw new Yo("Incompatible receiver, "+a+" required");return t}};hP||Wo.state?(Xe=Wo.state||(Wo.state=new vP),Xe.get=Xe.get,Xe.has=Xe.has,Xe.set=Xe.set,ws=function(a,e){if(Xe.has(a))throw new Yo(Qh);return e.facade=a,Xe.set(a,e),e},Ar=function(a){return Xe.get(a)||{}},ks=function(a){return Xe.has(a)}):(oi=bP("state"),gP[oi]=!0,ws=function(a,e){if(Go(a,oi))throw new Yo(Qh);return e.facade=a,fP(a,oi,e),e},Ar=function(a){return Go(a,oi)?a[oi]:{}},ks=function(a){return Go(a,oi)});var Xe,oi;Wh.exports={set:ws,get:Ar,has:ks,enforce:SP,getterFor:yP}});var Jo=f((vO,zh)=>{"use strict";var Ko=Ve(),TP=Ke(),Yh=Function.prototype,IP=Ko&&Object.getOwnPropertyDescriptor,Xo=TP(Yh,"name"),EP=Xo&&function(){}.name==="something",xP=Xo&&(!Ko||Ko&&IP(Yh,"name").configurable);zh.exports={EXISTS:Xo,PROPER:EP,CONFIGURABLE:xP}});var Xh=f(Kh=>{"use strict";var PP=Ve(),wP=Mo(),kP=si(),AP=nt(),RP=ri(),$P=jo();Kh.f=PP&&!wP?Object.defineProperties:function(e,t){AP(e);for(var i=RP(t),r=$P(t),s=r.length,n=0,o;s>n;)kP.f(e,o=r[n++],i[o]);return e}});var Zo=f((yO,Jh)=>{"use strict";var LP=ft();Jh.exports=LP("document","documentElement")});var ru=f((TO,sm)=>{"use strict";var MP=nt(),DP=Xh(),Zh=Ho(),CP=Ps(),VP=Zo(),OP=Ss(),_P=Es(),em=">",tm="<",tu="prototype",iu="script",rm=_P("IE_PROTO"),eu=function(){},am=function(a){return tm+iu+em+a+tm+"/"+iu+em},im=function(a){a.write(am("")),a.close();var e=a.parentWindow.Object;return a=null,e},BP=function(){var a=OP("iframe"),e="java"+iu+":",t;return a.style.display="none",VP.appendChild(a),a.src=String(e),t=a.contentWindow.document,t.open(),t.write(am("document.F=Object")),t.close(),t.F},As,Rs=function(){try{As=new ActiveXObject("htmlfile")}catch(e){}Rs=typeof document!="undefined"?document.domain&&As?im(As):BP():im(As);for(var a=Zh.length;a--;)delete Rs[tu][Zh[a]];return Rs()};CP[rm]=!0;sm.exports=Object.create||function(e,t){var i;return e!==null?(eu[tu]=MP(e),i=new eu,eu[tu]=null,i[rm]=e):i=Rs(),t===void 0?i:DP.f(i,t)}});var Ni=f((IO,nm)=>{"use strict";var NP=Ci();nm.exports=function(a,e,t,i){return i&&i.enumerable?a[e]=t:NP(a,e,t),a}});var ou=f((EO,lm)=>{"use strict";var FP=fe(),qP=ae(),UP=_e(),HP=ru(),om=xs(),jP=Ni(),QP=be(),GP=ze(),nu=QP("iterator"),um=!1,bt,au,su;[].keys&&(su=[].keys(),"next"in su?(au=om(om(su)),au!==Object.prototype&&(bt=au)):um=!0);var WP=!UP(bt)||FP(function(){var a={};return bt[nu].call(a)!==a});WP?bt={}:GP&&(bt=HP(bt));qP(bt[nu])||jP(bt,nu,function(){return this});lm.exports={IteratorPrototype:bt,BUGGY_SAFARI_ITERATORS:um}});var $s=f((xO,dm)=>{"use strict";var YP=be(),zP=YP("toStringTag"),cm={};cm[zP]="z";dm.exports=String(cm)==="[object z]"});var Rr=f((PO,pm)=>{"use strict";var KP=$s(),XP=ae(),Ls=ii(),JP=be(),ZP=JP("toStringTag"),ew=Object,tw=Ls(function(){return arguments}())==="Arguments",iw=function(a,e){try{return a[e]}catch(t){}};pm.exports=KP?Ls:function(a){var e,t,i;return a===void 0?"Undefined":a===null?"Null":typeof(t=iw(e=ew(a),ZP))=="string"?t:tw?Ls(e):(i=Ls(e))==="Object"&&XP(e.callee)?"Arguments":i}});var mm=f((wO,hm)=>{"use strict";var rw=$s(),aw=Rr();hm.exports=rw?{}.toString:function(){return"[object "+aw(this)+"]"}});var $r=f((kO,bm)=>{"use strict";var sw=$s(),nw=si().f,ow=Ci(),uw=Ke(),lw=mm(),cw=be(),fm=cw("toStringTag");bm.exports=function(a,e,t,i){var r=t?a:a&&a.prototype;r&&(uw(r,fm)||nw(r,fm,{configurable:!0,value:e}),i&&!sw&&ow(r,"toString",lw))}});var vm=f((AO,gm)=>{"use strict";var dw=ou().IteratorPrototype,pw=ru(),hw=Sr(),mw=$r(),fw=ni(),bw=function(){return this};gm.exports=function(a,e,t,i){var r=e+" Iterator";return a.prototype=pw(dw,{next:hw(+!i,t)}),mw(a,r,!1,!0),fw[r]=bw,a}});var ym=f((RO,Sm)=>{"use strict";var gw=ce(),vw=st();Sm.exports=function(a,e,t){try{return gw(vw(Object.getOwnPropertyDescriptor(a,e)[t]))}catch(i){}}});var Im=f(($O,Tm)=>{"use strict";var Sw=_e();Tm.exports=function(a){return Sw(a)||a===null}});var xm=f((LO,Em)=>{"use strict";var yw=Im(),Tw=String,Iw=TypeError;Em.exports=function(a){if(yw(a))return a;throw new Iw("Can't set "+Tw(a)+" as a prototype")}});var uu=f((MO,Pm)=>{"use strict";var Ew=ym(),xw=_e(),Pw=Mt(),ww=xm();Pm.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var a=!1,e={},t;try{t=Ew(Object.prototype,"__proto__","set"),t(e,[]),a=e instanceof Array}catch(i){}return function(r,s){return Pw(r),ww(s),xw(r)&&(a?t(r,s):r.__proto__=s),r}}():void 0)});var Om=f((DO,Vm)=>{"use strict";var kw=le(),Aw=Oe(),Ms=ze(),Dm=Jo(),Rw=ae(),$w=vm(),wm=xs(),km=uu(),Lw=$r(),Mw=Ci(),lu=Ni(),Dw=be(),Am=ni(),Cm=ou(),Cw=Dm.PROPER,Vw=Dm.CONFIGURABLE,Rm=Cm.IteratorPrototype,Ds=Cm.BUGGY_SAFARI_ITERATORS,Lr=Dw("iterator"),$m="keys",Mr="values",Lm="entries",Mm=function(){return this};Vm.exports=function(a,e,t,i,r,s,n){$w(t,e,i);var o=function(v){if(v===r&&h)return h;if(!Ds&&v&&v in c)return c[v];switch(v){case $m:return function(){return new t(this,v)};case Mr:return function(){return new t(this,v)};case Lm:return function(){return new t(this,v)}}return function(){return new t(this)}},u=e+" Iterator",l=!1,c=a.prototype,d=c[Lr]||c["@@iterator"]||r&&c[r],h=!Ds&&d||o(r),p=e==="Array"&&c.entries||d,m,b,g;if(p&&(m=wm(p.call(new a)),m!==Object.prototype&&m.next&&(!Ms&&wm(m)!==Rm&&(km?km(m,Rm):Rw(m[Lr])||lu(m,Lr,Mm)),Lw(m,u,!0,!0),Ms&&(Am[u]=Mm))),Cw&&r===Mr&&d&&d.name!==Mr&&(!Ms&&Vw?Mw(c,"name",Mr):(l=!0,h=function(){return Aw(d,this)})),r)if(b={values:o(Mr),keys:s?h:o($m),entries:o(Lm)},n)for(g in b)(Ds||l||!(g in c))&&lu(c,g,b[g]);else kw({target:e,proto:!0,forced:Ds||l},b);return(!Ms||n)&&c[Lr]!==h&&lu(c,Lr,h,{name:r}),Am[e]=h,b}});var Bm=f((CO,_m)=>{"use strict";_m.exports=function(a,e){return{value:a,done:e}}});var du=f((VO,Hm)=>{"use strict";var Ow=ri(),cu=kr(),Nm=ni(),qm=zo(),_w=si().f,Bw=Om(),Cs=Bm(),Nw=ze(),Fw=Ve(),Um="Array Iterator",qw=qm.set,Uw=qm.getterFor(Um);Hm.exports=Bw(Array,"Array",function(a,e){qw(this,{type:Um,target:Ow(a),index:0,kind:e})},function(){var a=Uw(this),e=a.target,t=a.index++;if(!e||t>=e.length)return a.target=void 0,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 Fm=Nm.Arguments=Nm.Array;cu("keys");cu("values");cu("entries");if(!Nw&&Fw&&Fm.name!=="values")try{_w(Fm,"name",{value:"values"})}catch(a){}});var Qm=f((OO,jm)=>{"use strict";var Hw=be(),jw=ni(),Qw=Hw("iterator"),Gw=Array.prototype;jm.exports=function(a){return a!==void 0&&(jw.Array===a||Gw[Qw]===a)}});var pu=f((_O,Wm)=>{"use strict";var Ww=Rr(),Gm=Ir(),Yw=Ri(),zw=ni(),Kw=be(),Xw=Kw("iterator");Wm.exports=function(a){if(!Yw(a))return Gm(a,Xw)||Gm(a,"@@iterator")||zw[Ww(a)]}});var zm=f((BO,Ym)=>{"use strict";var Jw=Oe(),Zw=st(),ek=nt(),tk=Tr(),ik=pu(),rk=TypeError;Ym.exports=function(a,e){var t=arguments.length<2?ik(a):e;if(Zw(t))return ek(Jw(t,a));throw new rk(tk(a)+" is not iterable")}});var Jm=f((NO,Xm)=>{"use strict";var ak=Oe(),Km=nt(),sk=Ir();Xm.exports=function(a,e,t){var i,r;Km(a);try{if(i=sk(a,"return"),!i){if(e==="throw")throw t;return t}i=ak(i,a)}catch(s){r=!0,i=s}if(e==="throw")throw t;if(r)throw i;return Km(i),t}});var Os=f((FO,rf)=>{"use strict";var nk=Di(),ok=Oe(),uk=nt(),lk=Tr(),ck=Qm(),dk=_i(),Zm=yr(),pk=zm(),hk=pu(),ef=Jm(),mk=TypeError,Vs=function(a,e){this.stopped=a,this.result=e},tf=Vs.prototype;rf.exports=function(a,e,t){var i=t&&t.that,r=!!(t&&t.AS_ENTRIES),s=!!(t&&t.IS_RECORD),n=!!(t&&t.IS_ITERATOR),o=!!(t&&t.INTERRUPTED),u=nk(e,i),l,c,d,h,p,m,b,g=function(S){return l&&ef(l,"normal",S),new Vs(!0,S)},v=function(S){return r?(uk(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=hk(a),!c)throw new mk(lk(a)+" is not iterable");if(ck(c)){for(d=0,h=dk(a);h>d;d++)if(p=v(a[d]),p&&Zm(tf,p))return p;return new Vs(!1)}l=pk(a,c)}for(m=s?a.next:l.next;!(b=ok(m,l)).done;){try{p=v(b.value)}catch(S){ef(l,"throw",S)}if(typeof p=="object"&&p&&Zm(tf,p))return p}return new Vs(!1)}});var sf=f((qO,af)=>{"use strict";var fk=Ve(),bk=si(),gk=Sr();af.exports=function(a,e,t){fk?bk.f(a,e,gk(0,t)):a[e]=t}});var nf=f(()=>{"use strict";var vk=le(),Sk=Os(),yk=sf();vk({target:"Object",stat:!0},{fromEntries:function(e){var t={};return Sk(e,function(i,r){yk(t,i,r)},{AS_ENTRIES:!0}),t}})});var uf=f((jO,of)=>{"use strict";du();nf();var Tk=$i();of.exports=Tk.Object.fromEntries});var cf=f((QO,lf)=>{"use strict";lf.exports={CSSRuleList:0,CSSStyleDeclaration:0,CSSValueList:0,ClientRectList:0,DOMRectList:0,DOMStringList:0,DOMTokenList:1,DataTransferItemList:0,FileList:0,HTMLAllCollection:0,HTMLCollection:0,HTMLFormElement:0,HTMLSelectElement:0,MediaList:0,MimeTypeArray:0,NamedNodeMap:0,NodeList:1,PaintRequestList:0,Plugin:0,PluginArray:0,SVGLengthList:0,SVGNumberList:0,SVGPathSegList:0,SVGPointList:0,SVGStringList:0,SVGTransformList:0,SourceBufferList:0,StyleSheetList:0,TextTrackCueList:0,TextTrackList:0,TouchList:0}});var pf=f(()=>{"use strict";du();var Ik=cf(),Ek=ne(),xk=$r(),df=ni();for(_s in Ik)xk(Ek[_s],_s),df[_s]=df.Array;var _s});var mf=f((YO,hf)=>{"use strict";var Pk=uf();pf();hf.exports=Pk});var hu=f((zO,ff)=>{"use strict";var wk=mf();ff.exports=wk});var bf=f(()=>{"use strict"});var mu=f((JO,gf)=>{"use strict";var Dr=ne(),kk=ai(),Ak=ii(),Bs=function(a){return kk.slice(0,a.length)===a};gf.exports=function(){return Bs("Bun/")?"BUN":Bs("Cloudflare-Workers")?"CLOUDFLARE":Bs("Deno/")?"DENO":Bs("Node.js/")?"NODE":Dr.Bun&&typeof Bun.version=="string"?"BUN":Dr.Deno&&typeof Deno.version=="object"?"DENO":Ak(Dr.process)==="process"?"NODE":Dr.window&&Dr.document?"BROWSER":"REST"}()});var Ns=f((ZO,vf)=>{"use strict";var Rk=mu();vf.exports=Rk==="NODE"});var yf=f((e_,Sf)=>{"use strict";var $k=si();Sf.exports=function(a,e,t){return $k.f(a,e,t)}});var Ef=f((t_,If)=>{"use strict";var Lk=ft(),Mk=yf(),Dk=be(),Ck=Ve(),Tf=Dk("species");If.exports=function(a){var e=Lk(a);Ck&&e&&!e[Tf]&&Mk(e,Tf,{configurable:!0,get:function(){return this}})}});var Pf=f((i_,xf)=>{"use strict";var Vk=yr(),Ok=TypeError;xf.exports=function(a,e){if(Vk(e,a))return a;throw new Ok("Incorrect invocation")}});var bu=f((r_,wf)=>{"use strict";var _k=ce(),Bk=ae(),fu=Er(),Nk=_k(Function.toString);Bk(fu.inspectSource)||(fu.inspectSource=function(a){return Nk(a)});wf.exports=fu.inspectSource});var vu=f((a_,Lf)=>{"use strict";var Fk=ce(),qk=fe(),kf=ae(),Uk=Rr(),Hk=ft(),jk=bu(),Af=function(){},Rf=Hk("Reflect","construct"),gu=/^\s*(?:class|function)\b/,Qk=Fk(gu.exec),Gk=!gu.test(Af),Cr=function(e){if(!kf(e))return!1;try{return Rf(Af,[],e),!0}catch(t){return!1}},$f=function(e){if(!kf(e))return!1;switch(Uk(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return Gk||!!Qk(gu,jk(e))}catch(t){return!0}};$f.sham=!0;Lf.exports=!Rf||qk(function(){var a;return Cr(Cr.call)||!Cr(Object)||!Cr(function(){a=!0})||a})?$f:Cr});var Df=f((s_,Mf)=>{"use strict";var Wk=vu(),Yk=Tr(),zk=TypeError;Mf.exports=function(a){if(Wk(a))return a;throw new zk(Yk(a)+" is not a constructor")}});var Su=f((n_,Vf)=>{"use strict";var Cf=nt(),Kk=Df(),Xk=Ri(),Jk=be(),Zk=Jk("species");Vf.exports=function(a,e){var t=Cf(a).constructor,i;return t===void 0||Xk(i=Cf(t)[Zk])?e:Kk(i)}});var _f=f((o_,Of)=>{"use strict";var eA=ce();Of.exports=eA([].slice)});var Nf=f((u_,Bf)=>{"use strict";var tA=TypeError;Bf.exports=function(a,e){if(a<e)throw new tA("Not enough arguments");return a}});var yu=f((l_,Ff)=>{"use strict";var iA=ai();Ff.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(iA)});var Ru=f((c_,zf)=>{"use strict";var Be=ne(),rA=uo(),aA=Di(),qf=ae(),sA=Ke(),Yf=fe(),Uf=Zo(),nA=_f(),Hf=Ss(),oA=Nf(),uA=yu(),lA=Ns(),wu=Be.setImmediate,ku=Be.clearImmediate,cA=Be.process,Tu=Be.Dispatch,dA=Be.Function,jf=Be.MessageChannel,pA=Be.String,Iu=0,Vr={},Qf="onreadystatechange",Or,ui,Eu,xu;Yf(function(){Or=Be.location});var Au=function(a){if(sA(Vr,a)){var e=Vr[a];delete Vr[a],e()}},Pu=function(a){return function(){Au(a)}},Gf=function(a){Au(a.data)},Wf=function(a){Be.postMessage(pA(a),Or.protocol+"//"+Or.host)};(!wu||!ku)&&(wu=function(e){oA(arguments.length,1);var t=qf(e)?e:dA(e),i=nA(arguments,1);return Vr[++Iu]=function(){rA(t,void 0,i)},ui(Iu),Iu},ku=function(e){delete Vr[e]},lA?ui=function(a){cA.nextTick(Pu(a))}:Tu&&Tu.now?ui=function(a){Tu.now(Pu(a))}:jf&&!uA?(Eu=new jf,xu=Eu.port2,Eu.port1.onmessage=Gf,ui=aA(xu.postMessage,xu)):Be.addEventListener&&qf(Be.postMessage)&&!Be.importScripts&&Or&&Or.protocol!=="file:"&&!Yf(Wf)?(ui=Wf,Be.addEventListener("message",Gf,!1)):Qf in Hf("script")?ui=function(a){Uf.appendChild(Hf("script"))[Qf]=function(){Uf.removeChild(this),Au(a)}}:ui=function(a){setTimeout(Pu(a),0)});zf.exports={set:wu,clear:ku}});var Jf=f((d_,Xf)=>{"use strict";var Kf=ne(),hA=Ve(),mA=Object.getOwnPropertyDescriptor;Xf.exports=function(a){if(!hA)return Kf[a];var e=mA(Kf,a);return e&&e.value}});var $u=f((p_,eb)=>{"use strict";var Zf=function(){this.head=null,this.tail=null};Zf.prototype={add:function(a){var e={item:a,next:null},t=this.tail;t?t.next=e:this.head=e,this.tail=e},get:function(){var a=this.head;if(a){var e=this.head=a.next;return e===null&&(this.tail=null),a.item}}};eb.exports=Zf});var ib=f((h_,tb)=>{"use strict";var fA=ai();tb.exports=/ipad|iphone|ipod/i.test(fA)&&typeof Pebble!="undefined"});var ab=f((m_,rb)=>{"use strict";var bA=ai();rb.exports=/web0s(?!.*chrome)/i.test(bA)});var db=f((f_,cb)=>{"use strict";var qi=ne(),gA=Jf(),sb=Di(),Lu=Ru().set,vA=$u(),SA=yu(),yA=ib(),TA=ab(),Mu=Ns(),nb=qi.MutationObserver||qi.WebKitMutationObserver,ob=qi.document,ub=qi.process,Fs=qi.Promise,Vu=gA("queueMicrotask"),Fi,Du,Cu,qs,lb;Vu||(_r=new vA,Br=function(){var a,e;for(Mu&&(a=ub.domain)&&a.exit();e=_r.get();)try{e()}catch(t){throw _r.head&&Fi(),t}a&&a.enter()},!SA&&!Mu&&!TA&&nb&&ob?(Du=!0,Cu=ob.createTextNode(""),new nb(Br).observe(Cu,{characterData:!0}),Fi=function(){Cu.data=Du=!Du}):!yA&&Fs&&Fs.resolve?(qs=Fs.resolve(void 0),qs.constructor=Fs,lb=sb(qs.then,qs),Fi=function(){lb(Br)}):Mu?Fi=function(){ub.nextTick(Br)}:(Lu=sb(Lu,qi),Fi=function(){Lu(Br)}),Vu=function(a){_r.head||Fi(),_r.add(a)});var _r,Br;cb.exports=Vu});var hb=f((b_,pb)=>{"use strict";pb.exports=function(a,e){try{arguments.length===1?console.error(a):console.error(a,e)}catch(t){}}});var Us=f((g_,mb)=>{"use strict";mb.exports=function(a){try{return{error:!1,value:a()}}catch(e){return{error:!0,value:e}}}});var li=f((v_,fb)=>{"use strict";var IA=ne();fb.exports=IA.Promise});var Ui=f((S_,Sb)=>{"use strict";var EA=ne(),Nr=li(),xA=ae(),PA=Lo(),wA=bu(),kA=be(),bb=mu(),AA=ze(),Ou=vo(),gb=Nr&&Nr.prototype,RA=kA("species"),_u=!1,vb=xA(EA.PromiseRejectionEvent),$A=PA("Promise",function(){var a=wA(Nr),e=a!==String(Nr);if(!e&&Ou===66||AA&&!(gb.catch&&gb.finally))return!0;if(!Ou||Ou<51||!/native code/.test(a)){var t=new Nr(function(s){s(1)}),i=function(s){s(function(){},function(){})},r=t.constructor={};if(r[RA]=i,_u=t.then(function(){})instanceof i,!_u)return!0}return!e&&(bb==="BROWSER"||bb==="DENO")&&!vb});Sb.exports={CONSTRUCTOR:$A,REJECTION_EVENT:vb,SUBCLASSING:_u}});var Hi=f((y_,Tb)=>{"use strict";var yb=st(),LA=TypeError,MA=function(a){var e,t;this.promise=new a(function(i,r){if(e!==void 0||t!==void 0)throw new LA("Bad Promise constructor");e=i,t=r}),this.resolve=yb(e),this.reject=yb(t)};Tb.exports.f=function(a){return new MA(a)}});var Fb=f(()=>{"use strict";var DA=le(),CA=ze(),Gs=Ns(),Ct=ne(),Wi=Oe(),Ib=Ni(),Eb=uu(),VA=$r(),OA=Ef(),_A=st(),Qs=ae(),BA=_e(),NA=Pf(),FA=Su(),Ab=Ru().set,Uu=db(),qA=hb(),UA=Us(),HA=$u(),Rb=zo(),Ws=li(),Hu=Ui(),$b=Hi(),Ys="Promise",Lb=Hu.CONSTRUCTOR,jA=Hu.REJECTION_EVENT,QA=Hu.SUBCLASSING,Bu=Rb.getterFor(Ys),GA=Rb.set,ji=Ws&&Ws.prototype,ci=Ws,Hs=ji,Mb=Ct.TypeError,Nu=Ct.document,ju=Ct.process,Fu=$b.f,WA=Fu,YA=!!(Nu&&Nu.createEvent&&Ct.dispatchEvent),Db="unhandledrejection",zA="rejectionhandled",xb=0,Cb=1,KA=2,Qu=1,Vb=2,js,Pb,XA,wb,Ob=function(a){var e;return BA(a)&&Qs(e=a.then)?e:!1},_b=function(a,e){var t=e.value,i=e.state===Cb,r=i?a.ok:a.fail,s=a.resolve,n=a.reject,o=a.domain,u,l,c;try{r?(i||(e.rejection===Vb&&ZA(e),e.rejection=Qu),r===!0?u=t:(o&&o.enter(),u=r(t),o&&(o.exit(),c=!0)),u===a.promise?n(new Mb("Promise-chain cycle")):(l=Ob(u))?Wi(l,u,s,n):s(u)):n(t)}catch(d){o&&!c&&o.exit(),n(d)}},Bb=function(a,e){a.notified||(a.notified=!0,Uu(function(){for(var t=a.reactions,i;i=t.get();)_b(i,a);a.notified=!1,e&&!a.rejection&&JA(a)}))},Nb=function(a,e,t){var i,r;YA?(i=Nu.createEvent("Event"),i.promise=e,i.reason=t,i.initEvent(a,!1,!0),Ct.dispatchEvent(i)):i={promise:e,reason:t},!jA&&(r=Ct["on"+a])?r(i):a===Db&&qA("Unhandled promise rejection",t)},JA=function(a){Wi(Ab,Ct,function(){var e=a.facade,t=a.value,i=kb(a),r;if(i&&(r=UA(function(){Gs?ju.emit("unhandledRejection",t,e):Nb(Db,e,t)}),a.rejection=Gs||kb(a)?Vb:Qu,r.error))throw r.value})},kb=function(a){return a.rejection!==Qu&&!a.parent},ZA=function(a){Wi(Ab,Ct,function(){var e=a.facade;Gs?ju.emit("rejectionHandled",e):Nb(zA,e,a.value)})},Qi=function(a,e,t){return function(i){a(e,i,t)}},Gi=function(a,e,t){a.done||(a.done=!0,t&&(a=t),a.value=e,a.state=KA,Bb(a,!0))},qu=function(a,e,t){if(!a.done){a.done=!0,t&&(a=t);try{if(a.facade===e)throw new Mb("Promise can't be resolved itself");var i=Ob(e);i?Uu(function(){var r={done:!1};try{Wi(i,e,Qi(qu,r,a),Qi(Gi,r,a))}catch(s){Gi(r,s,a)}}):(a.value=e,a.state=Cb,Bb(a,!1))}catch(r){Gi({done:!1},r,a)}}};if(Lb&&(ci=function(e){NA(this,Hs),_A(e),Wi(js,this);var t=Bu(this);try{e(Qi(qu,t),Qi(Gi,t))}catch(i){Gi(t,i)}},Hs=ci.prototype,js=function(e){GA(this,{type:Ys,done:!1,notified:!1,parent:!1,reactions:new HA,rejection:!1,state:xb,value:void 0})},js.prototype=Ib(Hs,"then",function(e,t){var i=Bu(this),r=Fu(FA(this,ci));return i.parent=!0,r.ok=Qs(e)?e:!0,r.fail=Qs(t)&&t,r.domain=Gs?ju.domain:void 0,i.state===xb?i.reactions.add(r):Uu(function(){_b(r,i)}),r.promise}),Pb=function(){var a=new js,e=Bu(a);this.promise=a,this.resolve=Qi(qu,e),this.reject=Qi(Gi,e)},$b.f=Fu=function(a){return a===ci||a===XA?new Pb(a):WA(a)},!CA&&Qs(Ws)&&ji!==Object.prototype)){wb=ji.then,QA||Ib(ji,"then",function(e,t){var i=this;return new ci(function(r,s){Wi(wb,i,r,s)}).then(e,t)},{unsafe:!0});try{delete ji.constructor}catch(a){}Eb&&Eb(ji,Hs)}DA({global:!0,constructor:!0,wrap:!0,forced:Lb},{Promise:ci});VA(ci,Ys,!1,!0);OA(Ys)});var Qb=f((E_,jb)=>{"use strict";var eR=be(),Ub=eR("iterator"),Hb=!1;try{qb=0,Gu={next:function(){return{done:!!qb++}},return:function(){Hb=!0}},Gu[Ub]=function(){return this},Array.from(Gu,function(){throw 2})}catch(a){}var qb,Gu;jb.exports=function(a,e){try{if(!e&&!Hb)return!1}catch(r){return!1}var t=!1;try{var i={};i[Ub]=function(){return{next:function(){return{done:t=!0}}}},a(i)}catch(r){}return t}});var Wu=f((x_,Gb)=>{"use strict";var tR=li(),iR=Qb(),rR=Ui().CONSTRUCTOR;Gb.exports=rR||!iR(function(a){tR.all(a).then(void 0,function(){})})});var Wb=f(()=>{"use strict";var aR=le(),sR=Oe(),nR=st(),oR=Hi(),uR=Us(),lR=Os(),cR=Wu();aR({target:"Promise",stat:!0,forced:cR},{all:function(e){var t=this,i=oR.f(t),r=i.resolve,s=i.reject,n=uR(function(){var o=nR(t.resolve),u=[],l=0,c=1;lR(e,function(d){var h=l++,p=!1;c++,sR(o,t,d).then(function(m){p||(p=!0,u[h]=m,--c||r(u))},s)}),--c||r(u)});return n.error&&s(n.value),i.promise}})});var zb=f(()=>{"use strict";var dR=le(),pR=ze(),hR=Ui().CONSTRUCTOR,zu=li(),mR=ft(),fR=ae(),bR=Ni(),Yb=zu&&zu.prototype;dR({target:"Promise",proto:!0,forced:hR,real:!0},{catch:function(a){return this.then(void 0,a)}});!pR&&fR(zu)&&(Yu=mR("Promise").prototype.catch,Yb.catch!==Yu&&bR(Yb,"catch",Yu,{unsafe:!0}));var Yu});var Kb=f(()=>{"use strict";var gR=le(),vR=Oe(),SR=st(),yR=Hi(),TR=Us(),IR=Os(),ER=Wu();gR({target:"Promise",stat:!0,forced:ER},{race:function(e){var t=this,i=yR.f(t),r=i.reject,s=TR(function(){var n=SR(t.resolve);IR(e,function(o){vR(n,t,o).then(i.resolve,r)})});return s.error&&r(s.value),i.promise}})});var Xb=f(()=>{"use strict";var xR=le(),PR=Hi(),wR=Ui().CONSTRUCTOR;xR({target:"Promise",stat:!0,forced:wR},{reject:function(e){var t=PR.f(this),i=t.reject;return i(e),t.promise}})});var Ku=f((D_,Jb)=>{"use strict";var kR=nt(),AR=_e(),RR=Hi();Jb.exports=function(a,e){if(kR(a),AR(e)&&e.constructor===a)return e;var t=RR.f(a),i=t.resolve;return i(e),t.promise}});var tg=f(()=>{"use strict";var $R=le(),LR=ft(),Zb=ze(),MR=li(),eg=Ui().CONSTRUCTOR,DR=Ku(),CR=LR("Promise"),VR=Zb&&!eg;$R({target:"Promise",stat:!0,forced:Zb||eg},{resolve:function(e){return DR(VR&&this===CR?MR:this,e)}})});var ig=f(()=>{"use strict";Fb();Wb();zb();Kb();Xb();tg()});var ng=f(()=>{"use strict";var OR=le(),_R=ze(),zs=li(),BR=fe(),ag=ft(),sg=ae(),NR=Su(),rg=Ku(),FR=Ni(),Ju=zs&&zs.prototype,qR=!!zs&&BR(function(){Ju.finally.call({then:function(){}},function(){})});OR({target:"Promise",proto:!0,real:!0,forced:qR},{finally:function(a){var e=NR(this,ag("Promise")),t=sg(a);return this.then(t?function(i){return rg(e,a()).then(function(){return i})}:a,t?function(i){return rg(e,a()).then(function(){throw i})}:a)}});!_R&&sg(zs)&&(Xu=ag("Promise").prototype.finally,Ju.finally!==Xu&&FR(Ju,"finally",Xu,{unsafe:!0}));var Xu});var ug=f((F_,og)=>{"use strict";bf();ig();ng();var UR=Dt();og.exports=UR("Promise","finally")});var cg=f((q_,lg)=>{"use strict";var HR=ug();lg.exports=HR});var Ks=f((U_,dg)=>{"use strict";var jR=cg();dg.exports=jR});var xg=f(()=>{"use strict";var a$=le(),s$=Qo().values;a$({target:"Object",stat:!0},{values:function(e){return s$(e)}})});var wg=f((wB,Pg)=>{"use strict";xg();var n$=$i();Pg.exports=n$.Object.values});var Ag=f((kB,kg)=>{"use strict";var o$=wg();kg.exports=o$});var zi=f((AB,Rg)=>{"use strict";var u$=Ag();Rg.exports=u$});var Gg=f(()=>{"use strict";var M$=le(),D$=Li(),C$=_i(),V$=wr(),O$=kr();M$({target:"Array",proto:!0},{at:function(e){var t=D$(this),i=C$(t),r=V$(e),s=r>=0?r:i+r;return s<0||s>=i?void 0:t[s]}});O$("at")});var Yg=f((FN,Wg)=>{"use strict";Gg();var _$=Dt();Wg.exports=_$("Array","at")});var Kg=f((qN,zg)=>{"use strict";var B$=Yg();zg.exports=B$});var Nt=f((UN,Xg)=>{"use strict";var N$=Kg();Xg.exports=N$});var xl=f(($q,Mv)=>{"use strict";var IL=ii();Mv.exports=Array.isArray||function(e){return IL(e)==="Array"}});var Cv=f((Lq,Dv)=>{"use strict";var EL=TypeError,xL=9007199254740991;Dv.exports=function(a){if(a>xL)throw EL("Maximum allowed index exceeded");return a}});var _v=f((Mq,Ov)=>{"use strict";var PL=xl(),wL=_i(),kL=Cv(),AL=Di(),Vv=function(a,e,t,i,r,s,n,o){for(var u=r,l=0,c=n?AL(n,o):!1,d,h;l<i;)l in t&&(d=c?c(t[l],l,e):t[l],s>0&&PL(d)?(h=wL(d),u=Vv(a,e,d,h,u,s-1)-1):(kL(u+1),a[u]=d),u++),l++;return u};Ov.exports=Vv});var qv=f((Dq,Fv)=>{"use strict";var Bv=xl(),RL=vu(),$L=_e(),LL=be(),ML=LL("species"),Nv=Array;Fv.exports=function(a){var e;return Bv(a)&&(e=a.constructor,RL(e)&&(e===Nv||Bv(e.prototype))?e=void 0:$L(e)&&(e=e[ML],e===null&&(e=void 0))),e===void 0?Nv:e}});var Hv=f((Cq,Uv)=>{"use strict";var DL=qv();Uv.exports=function(a,e){return new(DL(a))(e===0?0:e)}});var jv=f(()=>{"use strict";var CL=le(),VL=_v(),OL=st(),_L=Li(),BL=_i(),NL=Hv();CL({target:"Array",proto:!0},{flatMap:function(e){var t=_L(this),i=BL(t),r;return OL(e),r=NL(t,0),r.length=VL(r,t,t,i,0,1,e,arguments.length>1?arguments[1]:void 0),r}})});var Qv=f(()=>{"use strict";var FL=kr();FL("flatMap")});var Wv=f((Nq,Gv)=>{"use strict";jv();Qv();var qL=Dt();Gv.exports=qL("Array","flatMap")});var zv=f((Fq,Yv)=>{"use strict";var UL=Wv();Yv.exports=UL});var Pl=f((qq,Kv)=>{"use strict";var HL=zv();Kv.exports=HL});var ia=f((Uq,Xv)=>{"use strict";var jL=Rr(),QL=String;Xv.exports=function(a){if(jL(a)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return QL(a)}});var wl=f((Hq,Jv)=>{"use strict";Jv.exports=`
7
- \v\f\r \xA0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028\u2029\uFEFF`});var tS=f((jq,eS)=>{"use strict";var GL=ce(),WL=Mt(),YL=ia(),Al=wl(),Zv=GL("".replace),zL=RegExp("^["+Al+"]+"),KL=RegExp("(^|[^"+Al+"])["+Al+"]+$"),kl=function(a){return function(e){var t=YL(WL(e));return a&1&&(t=Zv(t,zL,"")),a&2&&(t=Zv(t,KL,"$1")),t}};eS.exports={start:kl(1),end:kl(2),trim:kl(3)}});var sS=f((Qq,aS)=>{"use strict";var XL=Jo().PROPER,JL=fe(),iS=wl(),rS="\u200B\x85\u180E";aS.exports=function(a){return JL(function(){return!!iS[a]()||rS[a]()!==rS||XL&&iS[a].name!==a})}});var Rl=f((Gq,nS)=>{"use strict";var ZL=tS().start,eM=sS();nS.exports=eM("trimStart")?function(){return ZL(this)}:"".trimStart});var uS=f(()=>{"use strict";var tM=le(),oS=Rl();tM({target:"String",proto:!0,name:"trimStart",forced:"".trimLeft!==oS},{trimLeft:oS})});var cS=f(()=>{"use strict";uS();var iM=le(),lS=Rl();iM({target:"String",proto:!0,name:"trimStart",forced:"".trimStart!==lS},{trimStart:lS})});var pS=f((Xq,dS)=>{"use strict";cS();var rM=Dt();dS.exports=rM("String","trimLeft")});var mS=f((Jq,hS)=>{"use strict";var aM=pS();hS.exports=aM});var bS=f((Zq,fS)=>{"use strict";var sM=mS();fS.exports=sM});var MS=f(()=>{"use strict"});var DS=f(()=>{"use strict"});var VS=f((OH,CS)=>{"use strict";var AM=_e(),RM=ii(),$M=be(),LM=$M("match");CS.exports=function(a){var e;return AM(a)&&((e=a[LM])!==void 0?!!e:RM(a)==="RegExp")}});var _S=f((_H,OS)=>{"use strict";var MM=nt();OS.exports=function(){var a=MM(this),e="";return a.hasIndices&&(e+="d"),a.global&&(e+="g"),a.ignoreCase&&(e+="i"),a.multiline&&(e+="m"),a.dotAll&&(e+="s"),a.unicode&&(e+="u"),a.unicodeSets&&(e+="v"),a.sticky&&(e+="y"),e}});var FS=f((BH,NS)=>{"use strict";var DM=Oe(),CM=Ke(),VM=yr(),OM=_S(),BS=RegExp.prototype;NS.exports=function(a){var e=a.flags;return e===void 0&&!("flags"in BS)&&!CM(a,"flags")&&VM(BS,a)?DM(OM,a):e}});var US=f((NH,qS)=>{"use strict";var _l=ce(),_M=Li(),BM=Math.floor,Vl=_l("".charAt),NM=_l("".replace),Ol=_l("".slice),FM=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,qM=/\$([$&'`]|\d{1,2})/g;qS.exports=function(a,e,t,i,r,s){var n=t+a.length,o=i.length,u=qM;return r!==void 0&&(r=_M(r),u=FM),NM(s,u,function(l,c){var d;switch(Vl(c,0)){case"$":return"$";case"&":return a;case"`":return Ol(e,0,t);case"'":return Ol(e,n);case"<":d=r[Ol(c,1,-1)];break;default:var h=+c;if(h===0)return l;if(h>o){var p=BM(h/10);return p===0?l:p<=o?i[p-1]===void 0?Vl(c,1):i[p-1]+Vl(c,1):l}d=i[h-1]}return d===void 0?"":d})}});var QS=f(()=>{"use strict";var UM=le(),HM=Oe(),Nl=ce(),HS=Mt(),jM=ae(),QM=Ri(),GM=VS(),tr=ia(),WM=Ir(),YM=FS(),zM=US(),KM=be(),XM=ze(),JM=KM("replace"),ZM=TypeError,Bl=Nl("".indexOf),eD=Nl("".replace),jS=Nl("".slice),tD=Math.max;UM({target:"String",proto:!0},{replaceAll:function(e,t){var i=HS(this),r,s,n,o,u,l,c,d,h,p,m=0,b="";if(!QM(e)){if(r=GM(e),r&&(s=tr(HS(YM(e))),!~Bl(s,"g")))throw new ZM("`.replaceAll` does not allow non-global regexes");if(n=WM(e,JM),n)return HM(n,e,i,t);if(XM&&r)return eD(tr(i),e,t)}for(o=tr(i),u=tr(e),l=jM(t),l||(t=tr(t)),c=u.length,d=tD(1,c),h=Bl(o,u);h!==-1;)p=l?tr(t(u,h,o)):zM(u,o,h,[],void 0,t),b+=jS(o,m,h)+p,m=h+c,h=h+d>o.length?-1:Bl(o,u,h+d);return m<o.length&&(b+=jS(o,m)),b}})});var WS=f((UH,GS)=>{"use strict";MS();DS();QS();var iD=Dt();GS.exports=iD("String","replaceAll")});var zS=f((HH,YS)=>{"use strict";var rD=WS();YS.exports=rD});var XS=f((jH,KS)=>{"use strict";var aD=zS();KS.exports=aD});var ZS=f((QH,JS)=>{"use strict";var sD=wr(),nD=ia(),oD=Mt(),uD=RangeError;JS.exports=function(e){var t=nD(oD(this)),i="",r=sD(e);if(r<0||r===1/0)throw new uD("Wrong number of repetitions");for(;r>0;(r>>>=1)&&(t+=t))r&1&&(i+=t);return i}});var ay=f((GH,ry)=>{"use strict";var iy=ce(),lD=_o(),ey=ia(),cD=ZS(),dD=Mt(),pD=iy(cD),hD=iy("".slice),mD=Math.ceil,ty=function(a){return function(e,t,i){var r=ey(dD(e)),s=lD(t),n=r.length,o=i===void 0?" ":ey(i),u,l;return s<=n||o===""?r:(u=s-n,l=pD(o,mD(u/o.length)),l.length>u&&(l=hD(l,0,u)),a?r+l:l+r)}};ry.exports={start:ty(!1),end:ty(!0)}});var ny=f((WH,sy)=>{"use strict";var fD=ai();sy.exports=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(fD)});var oy=f(()=>{"use strict";var bD=le(),gD=ay().start,vD=ny();bD({target:"String",proto:!0,forced:vD},{padStart:function(e){return gD(this,e,arguments.length>1?arguments[1]:void 0)}})});var ly=f((KH,uy)=>{"use strict";oy();var SD=Dt();uy.exports=SD("String","padStart")});var dy=f((XH,cy)=>{"use strict";var yD=ly();cy.exports=yD});var hy=f((JH,py)=>{"use strict";var TD=dy();py.exports=TD});var Sd="2.0.130";var Ce=(r=>(r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused",r))(Ce||{}),mt=(y=>(y.MPEG="MPEG",y.DASH="DASH",y.DASH_SEP="DASH_SEP",y.DASH_SEP_VK="DASH_SEP",y.DASH_WEBM="DASH_WEBM",y.DASH_WEBM_AV1="DASH_WEBM_AV1",y.DASH_STREAMS="DASH_STREAMS",y.DASH_WEBM_VK="DASH_WEBM",y.DASH_ONDEMAND="DASH_ONDEMAND",y.DASH_ONDEMAND_VK="DASH_ONDEMAND",y.DASH_LIVE="DASH_LIVE",y.DASH_LIVE_CMAF="DASH_LIVE_CMAF",y.DASH_LIVE_WEBM="DASH_LIVE_WEBM",y.HLS="HLS",y.HLS_ONDEMAND="HLS_ONDEMAND",y.HLS_JS="HLS",y.HLS_LIVE="HLS_LIVE",y.HLS_LIVE_CMAF="HLS_LIVE_CMAF",y.WEB_RTC_LIVE="WEB_RTC_LIVE",y))(mt||{});var fs=(r=>(r.NOT_AVAILABLE="NOT_AVAILABLE",r.AVAILABLE="AVAILABLE",r.CONNECTING="CONNECTING",r.CONNECTED="CONNECTED",r))(fs||{}),so=(i=>(i.HTTP1="http1",i.HTTP2="http2",i.QUIC="quic",i))(so||{});var no=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(no||{}),bs=(i=>(i.TRAFFIC_SAVING="traffic_saving",i.HIGH_QUALITY="high_quality",i.UNKNOWN="unknown",i))(bs||{});var YT=O(qe(),1);import{assertNever as gh,assertNonNullable as Lx,isNonNullable as Ts,ValueSubject as No,Subject as Mx,Subscription as Dx,merge as Cx,observableFrom as Vx,fromEvent as hh,map as mh,tap as fh,filterChanged as Ox,isNullable as Fo,ErrorCategory as bh}from"@vkontakte/videoplayer-shared/es2015";var ph=a=>new Promise((e,t)=>{let i=document.createElement("script");i.setAttribute("src",a),i.onload=()=>e(),i.onerror=r=>t(r),document.body.appendChild(i)});var Is=class{constructor(e){this.connection$=new No(void 0);this.castState$=new No("NOT_AVAILABLE");this.errorEvent$=new Mx;this.realCastState$=new No("NOT_AVAILABLE");this.subscription=new Dx;this.isDestroyed=!1;var s;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastInitializer");let t="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${t}`}),e.isDisabled||!t)return;let i=Ts((s=window.chrome)==null?void 0:s.cast),r=!!window.__onGCastApiAvailable;i?this.initializeCastApi():(window.__onGCastApiAvailable=n=>{delete window.__onGCastApiAvailable,n&&!this.isDestroyed&&this.initializeCastApi()},r||ph("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:bh.NETWORK,message:"Script loading failed!"})))}connect(){var e;(e=cast.framework.CastContext.getInstance())==null||e.requestSession()}disconnect(){var e,t;(t=(e=cast.framework.CastContext.getInstance())==null?void 0:e.getCurrentSession())==null||t.endSession(!0)}stopMedia(){return new Promise((e,t)=>{var i,r,s;(s=(r=(i=cast.framework.CastContext.getInstance())==null?void 0:i.getCurrentSession())==null?void 0:r.getMediaSession())==null||s.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){Ts(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();Fo(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();Fo(t)||e!==t.remotePlayer.isMuted&&t.remotePlayerController.muteOrUnmute()}destroy(){this.isDestroyed=!0,this.subscription.unsubscribe()}initListeners(){let e=new cast.framework.RemotePlayer,t=new cast.framework.RemotePlayerController(e),i=cast.framework.CastContext.getInstance();this.subscription.add(hh(i,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(r=>{var s,n,o;switch(r.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=(o=(n=(s=i.getCurrentSession())==null?void 0:s.getMediaSession())==null?void 0:n.media)==null?void 0:o.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return gh(r.sessionState)}})).add(Cx(hh(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(fh(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),mh(r=>r.castState)),Vx([i.getCastState()])).pipe(Ox(),mh(_x),fh(r=>{this.log({message:`realCastState$: ${r}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{var o,u;let s=r==="CONNECTED",n=Ts(this.connection$.getValue());if(s&&!n){let l=i.getCurrentSession();Lx(l);let c=l.getCastDevice(),d=(u=(o=l.getMediaSession())==null?void 0:o.media)==null?void 0:u.contentId;(Fo(d)||d===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:l,castDevice:c}))}else!s&&n&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(r==="CONNECTED"?Ts(this.connection$.getValue())?"CONNECTED":"AVAILABLE":r)}))}initializeCastApi(){var r;let e,t,i;try{e=cast.framework.CastContext.getInstance(),t=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,i=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch(s){return}try{e.setOptions({receiverApplicationId:(r=this.params.receiverApplicationId)!=null?r:t,autoJoinPolicy:i}),this.initListeners()}catch(s){this.errorEvent$.next({id:"ChromecastInitializer",category:bh.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:s})}}},_x=a=>{switch(a){case cast.framework.CastState.NO_DEVICES_AVAILABLE:return"NOT_AVAILABLE";case cast.framework.CastState.NOT_CONNECTED:return"AVAILABLE";case cast.framework.CastState.CONNECTING:return"CONNECTING";case cast.framework.CastState.CONNECTED:return"CONNECTED";default:return gh(a)}};var xc=O(qe(),1),RT=O(Bi(),1),$T=O(hu(),1);var Tg=O(Ks(),1);import{assertNever as pg}from"@vkontakte/videoplayer-shared/es2015";var ge=(a,e=0,t=0)=>{switch(t){case 0:return a.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case 1:{if(e===0)return a;let i=new URL(a);return i.searchParams.append("playback_shift",e.toFixed(0)),i.toString()}case 2:{let i=new URL(a);return!i.searchParams.get("offset_p")&&e===0?a:(i.searchParams.set("offset_p",e.toFixed(0)),i.toString())}default:pg(t)}return a},Xs=(a,e)=>{var t;switch(e){case 0:return NaN;case 1:{let i=new URL(a);return Number(i.searchParams.get("playback_shift"))}case 2:{let i=new URL(a);return Number((t=i.searchParams.get("offset_p"))!=null?t:0)}default:pg(e)}};var A=(a,e,t=!1)=>{let i=a.getTransition();(t||!i||i.to===e)&&a.setState(e)};import{isNonNullable as QR,Subject as Js,merge as hg}from"@vkontakte/videoplayer-shared/es2015";var _=class{constructor(e){this.transitionStarted$=new Js;this.transitionEnded$=new Js;this.transitionUpdated$=new Js;this.forceChanged$=new Js;this.stateChangeStarted$=hg(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=hg(this.transitionEnded$,this.forceChanged$);this.state=e,this.prevState=void 0}setState(e){let t=this.transition,i=this.state;this.transition=void 0,this.prevState=i,this.state=e,t?t.to===e?this.transitionEnded$.next(t):this.forceChanged$.next({from:t.from,to:e,canceledTransition:t}):this.forceChanged$.next({from:i,to:e,canceledTransition:t})}startTransitionTo(e){let t=this.transition,i=this.state;i===e||QR(t)&&t.to===e||(this.prevState=i,this.state=e,t?(this.transition={from:t.from,to:e,canceledTransition:t},this.transitionUpdated$.next(this.transition)):(this.transition={from:i,to:e},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}getPrevState(){return this.prevState}};import{assertNever as GR}from"@vkontakte/videoplayer-shared/es2015";var mg=a=>{switch(a){case"MPEG":case"DASH":case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":case"HLS":case"HLS_ONDEMAND":return!1;case"DASH_LIVE":case"DASH_LIVE_CMAF":case"HLS_LIVE":case"HLS_LIVE_CMAF":case"DASH_LIVE_WEBM":case"WEB_RTC_LIVE":return!0;default:return GR(a)}};import{assertNever as Yi,assertNonNullable as di,debounce as fg,ErrorCategory as bg,fromEvent as pi,isNonNullable as gg,map as vg,merge as Sg,observableFrom as WR,Subject as YR,Subscription as Zu,timeout as zR,getHighestQuality as KR}from"@vkontakte/videoplayer-shared/es2015";var XR=5,JR=5,ZR=500,yg=7e3,Fr=class{constructor(e){this.subscription=new Zu;this.loadMediaTimeoutSubscription=new Zu;this.videoState=new _("stopped");this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(s)};`}),i==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.stop());return}if(!t){if((r==null?void 0:r.to)!=="paused"&&s.state==="requested"&&e!=="stopped"){this.seek(s.position/1e3);return}switch(i){case"ready":{switch(e){case"playing":case"paused":case"ready":break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:Yi(e)}break}case"playing":{switch(e){case"playing":break;case"paused":this.videoState.startTransitionTo("playing"),this.params.connection.remotePlayerController.playOrPause();break;case"ready":this.videoState.startTransitionTo("playing"),this.params.connection.remotePlayerController.playOrPause();break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:Yi(e)}break}case"paused":{switch(e){case"playing":this.videoState.startTransitionTo("paused"),this.params.connection.remotePlayerController.playOrPause();break;case"paused":break;case"ready":this.videoState.startTransitionTo("paused"),this.videoState.setState("paused");break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:Yi(e)}break}default:Yi(i)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(mg(e.format)),this.params.output.isAudioAvailable$.next(!0),this.handleRemoteVolumeChange({volume:this.params.connection.remotePlayer.volumeLevel,muted:this.params.connection.remotePlayer.isMuted});let t=this.params.connection.session.getMediaSession();t&&this.restoreSession(t),this.subscribe()}destroy(){this.log({message:"[destroy]"}),this.subscription.unsubscribe()}subscribe(){this.subscription.add(this.loadMediaTimeoutSubscription);let e=new Zu;this.subscription.add(e),this.subscription.add(Sg(this.videoState.stateChangeStarted$.pipe(vg(r=>`stateChangeStarted$ ${JSON.stringify(r)}`)),this.videoState.stateChangeEnded$.pipe(vg(r=>`stateChangeEnded$ ${JSON.stringify(r)}`))).subscribe(r=>this.log({message:`[videoState] ${r}`})));let t=(r,s)=>this.subscription.add(r.subscribe(s));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{let r=new YR;e.add(r.pipe(fg(ZR)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add(pi(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe(n=>{this.logRemoteEvent(n);let o=n.value;this.params.output.position$.next(o),(this.params.desiredState.seekState.getState().state==="applying"||Math.abs(o-s)>XR)&&r.next(o),s=o})),e.add(pi(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(pi(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(pi(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemotePause():this.handleRemotePlay()}),t(pi(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),r=>{this.logRemoteEvent(r);let{remotePlayer:s}=this.params.connection,n=r.value,o=this.params.output.isBuffering$.getValue(),u=n===chrome.cast.media.PlayerState.BUFFERING;switch(o!==u&&this.params.output.isBuffering$.next(u),n){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&s.duration-s.currentTime<JR&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),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:Yi(n)}}),t(pi(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t(pi(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({muted:r.value})});let i=Sg(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,WR(["init"])).pipe(fg(0));t(i,this.syncPlayback)}restoreSession(e){this.log({message:"restoreSession"});let{remotePlayer:t}=this.params.connection;if(e.playerState!==chrome.cast.media.PlayerState.IDLE){t.isPaused?(this.videoState.setState("paused"),A(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),A(this.params.desiredState.playbackState,"playing"));let i=this.params.output.isLive$.getValue();this.params.output.duration$.next(i?0:t.duration),this.params.output.position$.next(i?0:t.currentTime),this.params.desiredState.seekState.setState({state:"none"})}}prepare(){let e=this.params.format;this.log({message:`[prepare] format: ${e}`});let t=this.createMediaInfo(e),i=this.createLoadRequest(t);this.loadMedia(i)}handleRemotePause(){let e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)==="paused"||e==="playing")&&(this.videoState.setState("paused"),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 r,s;let t=this.params.output.volume$.getValue(),i={volume:(r=e.volume)!=null?r:t.volume,muted:(s=e.muted)!=null?s:t.muted};(i.volume!==t.volume||i.muted!==i.muted)&&this.params.output.volume$.next(i)}seek(e){this.params.output.willSeekEvent$.next();let{remotePlayer:t,remotePlayerController:i}=this.params.connection;t.currentTime=e,i.seek()}stop(){let{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){var l;let t=this.params.source,i,r,s;switch(e){case"MPEG":{let c=t[e];di(c);let d=KR(Object.keys(c));di(d);let h=c[d];di(h),i=h,r="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let c=t[e];di(c),i=c.url,r="application/x-mpegurl",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":{let c=t[e];di(c),i=c.url,r="application/dash+xml",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let c=t[e];di(c),i=c.url,r="application/dash+xml",s=chrome.cast.media.StreamType.LIVE;break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let c=t[e];di(c),i=ge(c.url),r="application/x-mpegurl",s=chrome.cast.media.StreamType.LIVE;break}case"DASH_LIVE":case"WEB_RTC_LIVE":{let c="Unsupported format for Chromecast",d=new Error(c);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:bg.VIDEO_PIPELINE,message:c,thrown:d}),d}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return Yi(e)}let n=new chrome.cast.media.MediaInfo((l=this.params.meta.videoId)!=null?l:i,r);n.contentUrl=i,n.streamType=s,n.metadata=new chrome.cast.media.GenericMediaMetadata;let{title:o,subtitle:u}=this.params.meta;return gg(o)&&(n.metadata.title=o),gg(u)&&(n.metadata.subtitle=u),n}createLoadRequest(e){let t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;let i=this.params.desiredState.seekState.getState();return i.state==="applying"||i.state==="requested"?t.currentTime=this.params.output.isLive$.getValue()?0:i.position/1e3:t.currentTime=0,t}loadMedia(e){let t=this.params.connection.session.loadMedia(e),i=new Promise((r,s)=>{this.loadMediaTimeoutSubscription.add(zR(yg).subscribe(()=>s(`timeout(${yg})`)))});(0,Tg.default)(Promise.race([t,i]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},r=>{let s=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${r}`;this.log({message:s}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:bg.VIDEO_PIPELINE,message:s,thrown:r})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var Il=O(qe(),1);import{clearVideoElement as Eg}from"@vkontakte/videoplayer-shared/es2015";import{clearVideoElement as e$}from"@vkontakte/videoplayer-shared/es2015";var Ig=a=>{try{a.pause(),a.playbackRate=0,e$(a),a.remove()}catch(e){console.error(e)}};import{fromEvent as t$,Subscription as i$}from"@vkontakte/videoplayer-shared/es2015";var el=class{constructor(){this.attribute="data-pool-reused"}get(e){return e.hasAttribute(this.attribute)}set(e,t){e.toggleAttribute(this.attribute,t)}delete(e){e.removeAttribute(this.attribute)}},tl=window.WeakMap?new WeakMap:new el,il=window.WeakMap?new WeakMap:new Map,r$=(a,e=20)=>{let t=0;return t$(a,"ratechange").subscribe(i=>{t++,t>=e&&(a.currentTime=a.currentTime,t=0)})},ke=(a,{audioVideoSyncRate:e,disableYandexPiP:t})=>{let i=a.querySelector("video"),r=!!i;i?Eg(i):(i=document.createElement("video"),a.appendChild(i)),tl.set(i,r);let s=new i$;return s.add(r$(i,e)),il.set(i,s),i.setAttribute("crossorigin","anonymous"),i.setAttribute("playsinline","playsinline"),t&&i.setAttribute("x-yandex-pip","false"),i.controls=!1,i.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),i},Ae=a=>{let e=il.get(a);e==null||e.unsubscribe(),il.delete(a);let t=tl.get(a);tl.delete(a),t?Eg(a):Ig(a)};var al=O(zi(),1);import{assertNonNullable as qr,isNonNullable as ut,isNullable as d$,fromEvent as Ki,merge as $g,observableFrom as Lg,filterChanged as Mg,map as Ur,Subject as Dg,Subscription as p$,ValueSubject as h$,ErrorCategory as m$}from"@vkontakte/videoplayer-shared/es2015";import{isNonNullable as rl,isNullable as l$,Subscription as c$}from"@vkontakte/videoplayer-shared/es2015";var Zs=(a,e,t,{equal:i=(n,o)=>n===o,changed$:r,onError:s}={})=>{let n=a.getState(),o=e(),u=l$(r),l=new c$;return r&&l.add(r.subscribe(c=>{let d=a.getState();i(c,d)&&a.setState(c)},s)),i(o,n)||(t(n),u&&a.setState(n)),l.add(a.stateChangeStarted$.subscribe(c=>{t(c.to),u&&a.setState(c.to)},s)),l},ot=(a,e,t)=>Zs(e,()=>a.loop,i=>{rl(i)&&(a.loop=i)},{onError:t}),Re=(a,e,t,i)=>Zs(e,()=>({muted:a.muted,volume:a.volume}),r=>{rl(r)&&(a.muted=r.muted,a.volume=r.volume)},{equal:(r,s)=>r===s||(r==null?void 0:r.muted)===(s==null?void 0:s.muted)&&(r==null?void 0:r.volume)===(s==null?void 0:s.volume),changed$:t,onError:i}),Ue=(a,e,t,i)=>Zs(e,()=>a.playbackRate,r=>{rl(r)&&(a.playbackRate=r)},{changed$:t,onError:i}),Vt=Zs;var f$=a=>["__",a.language,a.label].join("|"),b$=(a,e)=>{if(a.id===e)return!0;let[t,i,r]=e.split("|");return a.language===i&&a.label===r},sl=class a{constructor(e){this.available$=new Dg;this.current$=new h$(void 0);this.error$=new Dg;this.subscription=new p$;this.externalTracks=new Map;this.internalTracks=new Map;this.baseURL=e}connect(e,t,i){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();let r=s=>{this.error$.next({id:"TextTracksManager",category:m$.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:s})};this.subscription.add(this.available$.subscribe(i.availableTextTracks$)),this.subscription.add(this.current$.subscribe(i.currentTextTrack$)),this.subscription.add(this.error$.subscribe(i.error$)),this.subscription.add(Vt(t.internalTextTracks,()=>(0,al.default)(this.internalTracks),s=>{ut(s)&&this.setInternal(s)},{equal:(s,n)=>ut(s)&&ut(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(Ur(s=>s.filter(({type:n})=>n==="internal"))),onError:r})),this.subscription.add(Vt(t.externalTextTracks,()=>(0,al.default)(this.externalTracks),s=>{ut(s)&&this.setExternal(s)},{equal:(s,n)=>ut(s)&&ut(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(Ur(s=>s.filter(({type:n})=>n==="external"))),onError:r})),this.subscription.add(Vt(t.currentTextTrack,()=>{if(this.video)return;let s=this.htmlTextTracksAsArray().find(({mode:n})=>n==="showing");return s&&this.htmlTextTrackToITextTrack(s).id},s=>this.select(s),{changed$:this.current$,onError:r})),this.subscription.add(Vt(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.activeCues)}))}subscribe(){qr(this.video);let{textTracks:e}=this.video;this.subscription.add(Ki(e,"addtrack").subscribe(()=>{let i=this.current$.getValue();i&&this.select(i)})),this.subscription.add($g(Ki(e,"addtrack"),Ki(e,"removetrack"),Lg(["init"])).pipe(Ur(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),Mg((i,r)=>i.length===r.length&&i.every(({id:s},n)=>s===r[n].id))).subscribe(this.available$)),this.subscription.add($g(Ki(e,"change"),Lg(["init"])).pipe(Ur(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),Ur(i=>i&&this.htmlTextTrackToITextTrack(i).id),Mg()).subscribe(this.current$));let t=i=>{var r,s;return this.applyCueSettings((s=(r=i.target)==null?void 0:r.activeCues)!=null?s:null)};this.subscription.add(Ki(e,"addtrack").subscribe(i=>{var s,n;(s=i.track)==null||s.addEventListener("cuechange",t);let r=o=>{var l,c,d,h,p;let u=(c=(l=o.target)==null?void 0:l.cues)!=null?c:null;u&&u.length&&(this.applyCueSettings((h=(d=o.target)==null?void 0:d.cues)!=null?h:null),(p=o.target)==null||p.removeEventListener("cuechange",r))};(n=i.track)==null||n.addEventListener("cuechange",r)})),this.subscription.add(Ki(e,"removetrack").subscribe(i=>{var r;(r=i.track)==null||r.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;let t=this.cueSettings.getState();for(let i of Array.from(e)){let r=i;ut(t.align)&&(r.align=t.align),ut(t.position)&&(r.position=t.position),ut(t.size)&&(r.size=t.size),ut(t.line)&&(r.line=t.line)}}htmlTextTracksAsArray(e=!1){qr(this.video);let t=[...this.video.textTracks];return e?t:t.filter(a.isHealthyTrack)}htmlTextTrackToITextTrack(e){var o,u,l,c,d;let{language:t,label:i}=e,r=e.id?e.id:f$(e),s=this.externalTracks.has(r),n=(l=s?(o=this.externalTracks.get(r))==null?void 0:o.isAuto:(u=this.internalTracks.get(r))==null?void 0:u.isAuto)!=null?l:r.includes("auto");return s?{id:r,type:"external",isAuto:n,language:t,label:i,url:(c=this.externalTracks.get(r))==null?void 0:c.url}:{id:r,type:"internal",isAuto:n,language:t,label:i,url:(d=this.internalTracks.get(r))==null?void 0:d.url}}static isHealthyTrack(e){return!(e.kind==="metadata"||e.groupId||e.id===""&&e.label===""&&e.language==="")}setExternal(e){this.internalTracks.size>0&&Array.from(this.internalTracks).forEach(([,t])=>this.detach(t)),e.filter(({id:t})=>!this.externalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.externalTracks).filter(([t])=>!e.find(i=>i.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){let t=[...this.externalTracks];e.filter(({id:i,language:r,isAuto:s})=>!this.internalTracks.has(i)&&!t.some(([,n])=>n.language===r&&n.isAuto===s)).forEach(i=>this.attach(i)),Array.from(this.internalTracks).filter(([i])=>!e.find(r=>r.id===i)).forEach(([,i])=>this.detach(i))}select(e){qr(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(d$(e)||!b$(t,e))&&(t.mode="disabled")}destroy(){if(this.subscription.unsubscribe(),this.video)for(let e of Array.from(this.video.getElementsByTagName("track"))){let t=e.getAttribute("id");t&&this.externalTracks.has(t)&&this.video.removeChild(e)}this.externalTracks.clear()}attach(e){qr(this.video);let t=document.createElement("track");this.baseURL?t.setAttribute("src",new URL(e.url,this.baseURL).toString()):t.setAttribute("src",e.url),t.setAttribute("id",e.id),e.label&&t.setAttribute("label",e.label),e.language&&t.setAttribute("srclang",e.language),e.type==="external"?this.externalTracks.set(e.id,e):e.type==="internal"&&this.internalTracks.set(e.id,e),this.video.appendChild(t)}detach(e){qr(this.video);let t=Array.prototype.find.call(this.video.getElementsByTagName("track"),i=>i.getAttribute("id")===e.id);t&&this.video.removeChild(t),e.type==="external"?this.externalTracks.delete(e.id):e.type==="internal"&&this.internalTracks.delete(e.id)}},He=sl;var hi=class{constructor(){this.pausedTime=0;this.streamOffset=0;this.pauseTimestamp=0}getTotalPausedTime(){return this.pausedTime+this.getCurrentPausedTime()}getCurrentPausedTime(){return this.pauseTimestamp>0?Date.now()-this.pauseTimestamp:0}getStreamOffset(){return this.streamOffset}getTotalOffset(){return this.getTotalPausedTime()+this.streamOffset}pause(){this.pauseTimestamp===0&&(this.pauseTimestamp=Date.now())}resume(){this.pauseTimestamp>0&&(this.pausedTime+=this.getCurrentPausedTime(),this.pauseTimestamp=0)}resetTo(e,t=!1){this.streamOffset=e,this.pauseTimestamp=0,this.pausedTime=0,t&&this.pause()}};var Cg=a=>{let e=a;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e==null?void 0:e.parentNode;return e!=null?e:void 0},nl=a=>{let e=Cg(a);return!!(e&&e.fullscreenElement&&e.fullscreenElement===a)},Vg=a=>{let e=Cg(a);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===a)};import{fromEvent as $e,map as Ot,merge as ul,filterChanged as P$,isNonNullable as jg,Subject as w$,filter as jr,mapTo as ll,combine as k$,once as A$,throttle as R$,ErrorCategory as $$,ValueSubject as Qg,Subscription as L$}from"@vkontakte/videoplayer-shared/es2015";var g$=3,Og=(a,e,t=g$)=>{let i=0,r=0;for(let s=0;s<a.length;s++){let n=a.start(s),o=a.end(s);if(n<=e&&e<=o){if(i=n,r=o,!t)return{from:i,to:r};for(let u=s-1;u>=0;u--)a.end(u)+t>=i&&(i=a.start(u));for(let u=s+1;u<a.length;u++)a.start(u)-t<=r&&(r=a.end(u))}}return{from:i,to:r}};var en=class{get current(){return this._current}get isYandex(){return this.current==="Yandex"}get isSafari(){return this.current==="Safari"}get isSamsungBrowser(){return this.current==="SamsungBrowser"}get safariVersion(){return this._safariVersion}detect(){let{userAgent:e}=navigator;try{let t=/yabrowser/i.test(e)?"Yandex":void 0,i=/samsungbrowser/i.test(e)?"SamsungBrowser":void 0,r=/chrome|crios/i.test(e)?"Chrome":void 0,s=/chromium/i.test(e)?"Chromium":void 0,n=/firefox|fxios/i.test(e)?"Firefox":void 0,o=/webkit|safari|khtml/i.test(e)?"Safari":void 0,u=/opr\//i.test(e)?"Opera":void 0,l=/edg/i.test(e)?"Edge":void 0;this._current=t||i||n||u||l||r||s||o||"Rest"}catch(t){console.error(t)}this.isSafari&&this.detectSafariVersion()}detectSafariVersion(){try{let{userAgent:e}=window.navigator,t=e.match(/Version\/(\d+)/);if(!t)return;let i=t[1],r=parseInt(i,10);if(isNaN(r))return;this._safariVersion=r}catch(e){console.error(e)}}};var _g=O(qe(),1);var Hr=()=>{var a,e;return/Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test((a=navigator.appVersion)!=null?a:navigator.userAgent)||((e=navigator==null?void 0:navigator.userAgentData)==null?void 0:e.mobile)};var tn=class{constructor(e){this._highEntropyValues={};this._displayChecker=e}get current(){return this._current}get isIOS(){let e=["iPhone","iPad","iPod"];return this._highEntropyValues.platform==="iOS"||(0,_g.default)(e,this.current)}get isMac(){return this._highEntropyValues.platform==="macOS"||this.current==="Mac"}get isApple(){return this.isIOS||this.isMac}get isIphoneOrOldIpad(){if(!this.isApple||!this._displayChecker.isTouch)return!1;let e=this.current==="iPad"||this._displayChecker.width>700,t=this._iosVersion;return!e||e&&!!t&&t<16}get isAndroid(){return this._highEntropyValues.platform==="Android"||this.current==="Android"}get isMobile(){return this._highEntropyValues.mobile||this._isMobile}get iOSVersion(){return this._iosVersion}detect(){let{userAgent:e}=navigator;try{this._isMobile=Hr()}catch(t){console.error(t)}this.detectDevice(e),this.detectHighEntropyValues(),this.isIOS&&this.detectIOSVersion()}detectHighEntropyValues(){return E(this,null,function*(){let{userAgentData:e}=navigator;if(e){let t=yield e.getHighEntropyValues(["architecture","bitness","brands","mobile","platform","formFactor","model","platformVersion","wow64"]);this._highEntropyValues=t}})}detectDevice(e){try{let t=/android/i.test(e)?"Android":void 0,i=/iphone/i.test(e)?"iPhone":void 0,r=/ipad/i.test(e)?"iPad":void 0,s=/ipod/i.test(e)?"iPod":void 0,n=/mac/i.test(e)?"Mac":void 0,o=/webOS|BlackBerry|IEMobile|Opera Mini/i.test(e)?"RestMobile":void 0;this._current=t||i||r||s||o||n||"Desktop"}catch(t){console.error(t)}}detectIOSVersion(){try{if(this._highEntropyValues.platformVersion){let s=this._highEntropyValues.platformVersion.split(".").slice(0,2).join("."),n=parseFloat(s);this._iosVersion=n;return}let{userAgent:e}=window.navigator,t=e.match(/OS (\d+(_\d+)?)/i);if(!t)return;let i=t[1].replace(/_/g,".");if(!i)return;let r=parseFloat(i);if(isNaN(r))return;this._iosVersion=r}catch(e){console.error(e)}}};var rn=class{get isTouch(){return typeof this._maxTouchPoints=="number"?this._maxTouchPoints>1:"ontouchstart"in window}get maxTouchPoints(){return this._maxTouchPoints}get height(){return this._height}get width(){return this._width}get screenHeight(){return this._screenHeight}get screenWidth(){return this._screenWidth}get pixelRatio(){return this._pixelRatio}get isHDR(){return this._isHdr}get colorDepth(){return this._colorDepth}detect(){var t;let{maxTouchPoints:e}=navigator;try{this._maxTouchPoints=e!=null?e:0,this._isHdr=!!((t=matchMedia("(dynamic-range: high)"))!=null&&t.matches),this._colorDepth=screen.colorDepth}catch(i){console.error(i)}try{this._pixelRatio=window.devicePixelRatio||1,this._height=screen.height,this._width=screen.width,this._height=screen.height,this._screenHeight=this._height*this._pixelRatio,this._screenWidth=this._width*this._pixelRatio}catch(i){console.error(i)}}};var Je=()=>window.ManagedMediaSource||window.MediaSource,an=()=>{var a,e;return!!(window.ManagedMediaSource&&((e=(a=window.ManagedSourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},Bg=()=>{var a,e;return!!(window.MediaSource&&((e=(a=window.SourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},Ng=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;var v$=document.createElement("video"),S$='video/mp4; codecs="avc1.42000a,mp4a.40.2"',y$='video/mp4; codecs="hev1.1.6.L93.B0"',Fg='video/webm; codecs="vp09.00.10.08"',qg='video/webm; codecs="av01.0.00M.08"',T$='audio/mp4; codecs="mp4a.40.2"',I$='audio/webm; codecs="opus"',Ug,E$=()=>E(void 0,null,function*(){if(!window.navigator.mediaCapabilities)return;let a={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=yield Promise.all([window.navigator.mediaCapabilities.decodingInfo(D(w({},a),{video:D(w({},a.video),{contentType:qg})})),window.navigator.mediaCapabilities.decodingInfo(D(w({},a),{video:D(w({},a.video),{contentType:Fg})}))]);Ug={DASH_WEBM_AV1:e,DASH_WEBM:t}});E$().catch(a=>{console.log(v$),console.error(a)});var sn=class{constructor(e,t){this._deviceChecker=e,this._browserChecker=t}get protocols(){return this._protocols}get containers(){return this._containers}get codecs(){return this._codecs}get webmDecodingInfo(){return Ug}get supportedCodecs(){return Object.keys(this._codecs).filter(e=>this._codecs[e])}get nativeHlsSupported(){return this._nativeHlsSupported}detect(){var e,t,i,r,s,n,o,u,l,c,d,h,p,m,b,g,v,S,y,I;this._video=document.createElement("video");try{this._protocols={mms:an(),mse:Bg(),hls:!!((t=(e=this._video).canPlayType)!=null&&t.call(e,"application/x-mpegurl")||(r=(i=this._video).canPlayType)!=null&&r.call(i,"vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},this._containers={mp4:!!((n=(s=this._video).canPlayType)!=null&&n.call(s,"video/mp4")),webm:!!((u=(o=this._video).canPlayType)!=null&&u.call(o,"video/webm")),cmaf:!0};let T=!!((c=(l=Je())==null?void 0:l.isTypeSupported)!=null&&c.call(l,S$)),$=!!((h=(d=Je())==null?void 0:d.isTypeSupported)!=null&&h.call(d,y$)),F=!!((m=(p=Je())==null?void 0:p.isTypeSupported)!=null&&m.call(p,T$));this._codecs={h264:T,h265:$,vp9:!!((g=(b=Je())==null?void 0:b.isTypeSupported)!=null&&g.call(b,Fg)),av1:!!((S=(v=Je())==null?void 0:v.isTypeSupported)!=null&&S.call(v,qg)),aac:F,opus:!!((I=(y=Je())==null?void 0:y.isTypeSupported)!=null&&I.call(y,I$)),mpeg:(T||$)&&F},this._nativeHlsSupported=this._protocols.hls&&this._containers.mp4}catch(T){console.error(T)}this.destroyVideoElement()}destroyVideoElement(){var t;if(!this._video)return;if(this._video.pause(),this._video.currentTime=0,this._video.removeAttribute("src"),this._video.src="",this._video.load(),this._video.remove){this._video.remove(),this._video=null;return}this._video.parentNode&&this._video.parentNode.removeChild(this._video);let e=this._video.cloneNode(!1);(t=this._video.parentNode)==null||t.replaceChild(e,this._video),this._video=null}};var Hg="audio/mpeg",nn=class{supportMp3(){return this._codecs.mp3&&this._containers.mpeg}detect(){var e,t,i,r;this._audio=document.createElement("audio");try{this._containers={mpeg:!!((t=(e=this._audio).canPlayType)!=null&&t.call(e,Hg))},this._codecs={mp3:!!((r=(i=Je())==null?void 0:i.isTypeSupported)!=null&&r.call(i,Hg))}}catch(s){console.error(s)}this.destroyAudioElement()}destroyAudioElement(){var t;if(!this._audio)return;if(this._audio.pause(),this._audio.currentTime=0,this._audio.removeAttribute("src"),this._audio.src="",this._audio.load(),this._audio.remove){this._audio.remove(),this._audio=null;return}this._audio.parentNode&&this._audio.parentNode.removeChild(this._audio);let e=this._audio.cloneNode(!1);(t=this._audio.parentNode)==null||t.replaceChild(e,this._audio),this._audio=null}};import{ValueSubject as x$}from"@vkontakte/videoplayer-shared/es2015";var ol=class{constructor(){this.isInited$=new x$(!1);this._displayChecker=new rn,this._deviceChecker=new tn(this._displayChecker),this._browserChecker=new en,this._videoChecker=new sn(this._deviceChecker,this._browserChecker),this._audioChecker=new nn,this.detect()}get display(){return this._displayChecker}get device(){return this._deviceChecker}get browser(){return this._browserChecker}get video(){return this._videoChecker}get audio(){return this._audioChecker}detect(){return E(this,null,function*(){this._displayChecker.detect(),this._deviceChecker.detect(),this._browserChecker.detect(),this._videoChecker.detect(),this._audioChecker.detect(),this.isInited$.next(!0)})}},U=new ol;var Le=a=>{let e=x=>$e(a,x).pipe(ll(void 0)),t=new L$,i=()=>t.unsubscribe(),s=ul(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(x=>$e(a,x))).pipe(Ot(x=>x.type==="ended"?a.readyState<2:a.readyState<3),P$()),n=ul($e(a,"progress"),$e(a,"timeupdate")).pipe(Ot(()=>Og(a.buffered,a.currentTime))),o=U.browser.isSafari?k$({play:e("play").pipe(A$()),playing:e("playing")}).pipe(ll(void 0)):e("playing"),u=$e(a,"volumechange").pipe(Ot(()=>({muted:a.muted,volume:a.volume}))),l=$e(a,"ratechange").pipe(Ot(()=>a.playbackRate)),c=$e(a,"error").pipe(jr(()=>!!(a.error||a.played.length)),Ot(()=>{var j;let x=a.error;return{id:x?`MediaError#${x.code}`:"HtmlVideoError",category:$$.VIDEO_PIPELINE,message:x?x.message:"Error event from HTML video element",thrown:(j=a.error)!=null?j:void 0}})),d=$e(a,"timeupdate").pipe(Ot(()=>a.currentTime)),h=new w$,p=.3,m;t.add(d.subscribe(x=>{a.loop&&jg(m)&&jg(x)&&m>=a.duration-p&&x<=p&&h.next(m),m=x}));let b=e("pause").pipe(jr(()=>!a.error&&m!==a.duration)),g=$e(a,"enterpictureinpicture"),v=$e(a,"leavepictureinpicture"),S=new Qg(Vg(a));t.add(g.subscribe(()=>S.next(!0))),t.add(v.subscribe(()=>S.next(!1)));let y=new Qg(nl(a)),I=$e(a,"fullscreenchange");t.add(I.pipe(Ot(()=>nl(a))).subscribe(y));let T=.1,$=1e3,F=$e(a,"timeupdate").pipe(jr(x=>a.duration-a.currentTime<T)),q=ul(F.pipe(jr(x=>!a.loop)),$e(a,"ended")).pipe(R$($),ll(void 0)),K=F.pipe(jr(x=>a.loop));return{playing$:o,pause$:b,canplay$:e("canplay"),ended$:q,looped$:h,loopExpected$:K,error$:c,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:d,durationChange$:$e(a,"durationchange").pipe(Ot(()=>a.duration)),isBuffering$:s,currentBuffer$:n,volumeState$:u,playbackRateState$:l,inPiP$:S,inFullscreen$:y,enterPip$:g,leavePip$:v,destroy:i}};import{VideoQuality as _t}from"@vkontakte/videoplayer-shared/es2015";var Bt=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 Ft=O(Nt(),1),ov=O(qe(),1),ln=O(Bi(),1);import{isNonNullable as Ee,isNullable as rv,now as uv,isHigher as av,isHigherOrEqual as hl,isInvariantQuality as sv,isLowerOrEqual as ml,videoSizeToQuality as U$,assertNotEmptyArray as lv,assertNonNullable as H$}from"@vkontakte/videoplayer-shared/es2015";var cl=!1,vt={},Jg=a=>{cl=a},Zg=()=>{vt={}},ev=a=>{a(vt)},Qr=(a,e)=>{var t;cl&&(vt.meta=(t=vt.meta)!=null?t:{},vt.meta[a]=e)},Ie=class{constructor(e){this.name=e}next(e){var i,r;if(!cl)return;vt.series=(i=vt.series)!=null?i:{};let t=(r=vt.series[this.name])!=null?r:[];t.push([Date.now(),e]),vt.series[this.name]=t}};import{isHigher as F$,isHigherOrEqual as YN,isLower as tv,isLowerOrEqual as zN,isNonNullable as on,isNullable as q$,videoHeightToQuality as un}from"@vkontakte/videoplayer-shared/es2015";function dl({limits:a,highQualityLimit:e,trafficSavingLimit:t}){return!a.max&&a.min===e?"high_quality":!a.min&&a.max===t?"traffic_saving":"unknown"}function pl({limits:a,highQualityLimit:e,trafficSavingLimit:t}){return!!a&&dl({limits:a,highQualityLimit:e,trafficSavingLimit:t})==="high_quality"}function Gr({limits:a,highestAvailableQuality:e,lowestAvailableQuality:t}){return q$(a)||on(a.min)&&on(a.max)&&tv(a.max,a.min)||on(a.min)&&e&&F$(a.min,e)||on(a.max)&&t&&tv(a.max,t)}function iv({limits:a,highestAvailableHeight:e,lowestAvailableHeight:t}){return Gr({limits:{max:a!=null&&a.max?un(a.max):void 0,min:a!=null&&a.min?un(a.min):void 0},highestAvailableQuality:e?un(e):void 0,lowestAvailableQuality:t?un(t):void 0})}var j$=new Ie("best_bitrate"),cv=(a,e,t)=>(e-t)*Math.pow(2,-10*a)+t;var fl=a=>(e,t)=>a*(Number(e.bitrate)-Number(t.bitrate)),Wr=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=uv()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},dv='Assertion "ABR Tracks is empty array" failed',cn=(a,e,t,i)=>{var u;let r=[...e].sort(fl(1)),s=[...t].sort(fl(1)),n=s.filter(l=>Ee(l.bitrate)&&Ee(a.bitrate)?a.bitrate/l.bitrate>i:!0),o=(u=(0,Ft.default)(s,Math.round(s.length*r.indexOf(a)/(r.length+1))))!=null?u:(0,Ft.default)(s,-1);return o&&(0,ov.default)(n,o)?o:n.length?(0,Ft.default)(n,-1):(0,Ft.default)(s,0)},nv=a=>"quality"in a,pv=(a,e,t,i)=>{var n;let r=Ee((n=i==null?void 0:i.last)==null?void 0:n.bitrate)&&Ee(t==null?void 0:t.bitrate)&&i.last.bitrate<t.bitrate?a.trackCooldownIncreaseQuality:a.trackCooldownDecreaseQuality,s=t&&i&&i.history[t.id]&&uv()-i.history[t.id]<=r&&(!i.last||t.id!==i.last.id);if(t!=null&&t.id&&i&&!s&&i.recordSelection(t),s&&(i!=null&&i.last)){let o=i.last;i==null||i.recordSwitch(o);let u=nv(o)?"video":"audio",l=nv(o)?o.quality:o.bitrate;return e({message:`
6
+ var sI=Object.create;var fs=Object.defineProperty,nI=Object.defineProperties,Sd=Object.getOwnPropertyDescriptor,oI=Object.getOwnPropertyDescriptors,uI=Object.getOwnPropertyNames,ms=Object.getOwnPropertySymbols,lI=Object.getPrototypeOf,so=Object.prototype.hasOwnProperty,yd=Object.prototype.propertyIsEnumerable;var cI=(a,e)=>(e=Symbol[a])?e:Symbol.for("Symbol."+a);var at=Math.pow,vd=(a,e,t)=>e in a?fs(a,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):a[e]=t,w=(a,e)=>{for(var t in e||(e={}))so.call(e,t)&&vd(a,t,e[t]);if(ms)for(var t of ms(e))yd.call(e,t)&&vd(a,t,e[t]);return a},D=(a,e)=>nI(a,oI(e));var Td=(a,e)=>{var t={};for(var i in a)so.call(a,i)&&e.indexOf(i)<0&&(t[i]=a[i]);if(a!=null&&ms)for(var i of ms(a))e.indexOf(i)<0&&yd.call(a,i)&&(t[i]=a[i]);return t};var f=(a,e)=>()=>(e||a((e={exports:{}}).exports,e),e.exports);var dI=(a,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of uI(e))!so.call(a,r)&&r!==t&&fs(a,r,{get:()=>e[r],enumerable:!(i=Sd(e,r))||i.enumerable});return a};var O=(a,e,t)=>(t=a!=null?sI(lI(a)):{},dI(e||!a||!a.__esModule?fs(t,"default",{value:a,enumerable:!0}):t,a));var no=(a,e,t,i)=>{for(var r=i>1?void 0:i?Sd(e,t):e,s=a.length-1,n;s>=0;s--)(n=a[s])&&(r=(i?n(e,t,r):n(r))||r);return i&&r&&fs(e,t,r),r};var E=(a,e,t)=>new Promise((i,r)=>{var s=u=>{try{o(t.next(u))}catch(l){r(l)}},n=u=>{try{o(t.throw(u))}catch(l){r(l)}},o=u=>u.done?i(u.value):Promise.resolve(u.value).then(s,n);o((t=t.apply(a,e)).next())}),bs=function(a,e){this[0]=a,this[1]=e},ue=(a,e,t)=>{var i=(n,o,u,l)=>{try{var c=t[n](o),d=(o=c.value)instanceof bs,h=c.done;Promise.resolve(d?o[0]:o).then(p=>d?i(n==="return"?n:"next",o[1]?{done:p.done,value:p.value}:p,u,l):u({value:p,done:h})).catch(p=>i("throw",p,u,l))}catch(p){l(p)}},r=n=>s[n]=o=>new Promise((u,l)=>i(n,o,u,l)),s={};return t=t.apply(a,e),s[cI("asyncIterator")]=()=>s,r("next"),r("throw"),r("return"),s};var ne=f((lo,Ed)=>{"use strict";var vr=function(a){return a&&a.Math===Math&&a};Ed.exports=vr(typeof globalThis=="object"&&globalThis)||vr(typeof window=="object"&&window)||vr(typeof self=="object"&&self)||vr(typeof global=="object"&&global)||vr(typeof lo=="object"&&lo)||function(){return this}()||Function("return this")()});var fe=f((F0,xd)=>{"use strict";xd.exports=function(a){try{return!!a()}catch(e){return!0}}});var Sr=f((q0,Pd)=>{"use strict";var pI=fe();Pd.exports=!pI(function(){var a=function(){}.bind();return typeof a!="function"||a.hasOwnProperty("prototype")})});var co=f((U0,Rd)=>{"use strict";var hI=Sr(),kd=Function.prototype,wd=kd.apply,Ad=kd.call;Rd.exports=typeof Reflect=="object"&&Reflect.apply||(hI?Ad.bind(wd):function(){return Ad.apply(wd,arguments)})});var ce=f((H0,Md)=>{"use strict";var $d=Sr(),Ld=Function.prototype,po=Ld.call,mI=$d&&Ld.bind.bind(po,po);Md.exports=$d?mI:function(a){return function(){return po.apply(a,arguments)}}});var ii=f((j0,Cd)=>{"use strict";var Dd=ce(),fI=Dd({}.toString),bI=Dd("".slice);Cd.exports=function(a){return bI(fI(a),8,-1)}});var ho=f((Q0,Vd)=>{"use strict";var gI=ii(),vI=ce();Vd.exports=function(a){if(gI(a)==="Function")return vI(a)}});var ae=f((G0,Od)=>{"use strict";var mo=typeof document=="object"&&document.all;Od.exports=typeof mo=="undefined"&&mo!==void 0?function(a){return typeof a=="function"||a===mo}:function(a){return typeof a=="function"}});var Ve=f((W0,Bd)=>{"use strict";var SI=fe();Bd.exports=!SI(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var Oe=f((Y0,_d)=>{"use strict";var yI=Sr(),Ss=Function.prototype.call;_d.exports=yI?Ss.bind(Ss):function(){return Ss.apply(Ss,arguments)}});var fo=f(qd=>{"use strict";var Nd={}.propertyIsEnumerable,Fd=Object.getOwnPropertyDescriptor,TI=Fd&&!Nd.call({1:2},1);qd.f=TI?function(e){var t=Fd(this,e);return!!t&&t.enumerable}:Nd});var yr=f((K0,Ud)=>{"use strict";Ud.exports=function(a,e){return{enumerable:!(a&1),configurable:!(a&2),writable:!(a&4),value:e}}});var jd=f((X0,Hd)=>{"use strict";var II=ce(),EI=fe(),xI=ii(),bo=Object,PI=II("".split);Hd.exports=EI(function(){return!bo("z").propertyIsEnumerable(0)})?function(a){return xI(a)==="String"?PI(a,""):bo(a)}:bo});var Ri=f((J0,Qd)=>{"use strict";Qd.exports=function(a){return a==null}});var Mt=f((Z0,Gd)=>{"use strict";var wI=Ri(),AI=TypeError;Gd.exports=function(a){if(wI(a))throw new AI("Can't call method on "+a);return a}});var ri=f((eV,Wd)=>{"use strict";var kI=jd(),RI=Mt();Wd.exports=function(a){return kI(RI(a))}});var Be=f((tV,Yd)=>{"use strict";var $I=ae();Yd.exports=function(a){return typeof a=="object"?a!==null:$I(a)}});var $i=f((iV,zd)=>{"use strict";zd.exports={}});var bt=f((rV,Xd)=>{"use strict";var go=$i(),vo=ne(),LI=ae(),Kd=function(a){return LI(a)?a:void 0};Xd.exports=function(a,e){return arguments.length<2?Kd(go[a])||Kd(vo[a]):go[a]&&go[a][e]||vo[a]&&vo[a][e]}});var Tr=f((aV,Jd)=>{"use strict";var MI=ce();Jd.exports=MI({}.isPrototypeOf)});var ai=f((sV,tp)=>{"use strict";var DI=ne(),Zd=DI.navigator,ep=Zd&&Zd.userAgent;tp.exports=ep?String(ep):""});var yo=f((nV,op)=>{"use strict";var np=ne(),So=ai(),ip=np.process,rp=np.Deno,ap=ip&&ip.versions||rp&&rp.version,sp=ap&&ap.v8,Ye,ys;sp&&(Ye=sp.split("."),ys=Ye[0]>0&&Ye[0]<4?1:+(Ye[0]+Ye[1]));!ys&&So&&(Ye=So.match(/Edge\/(\d+)/),(!Ye||Ye[1]>=74)&&(Ye=So.match(/Chrome\/(\d+)/),Ye&&(ys=+Ye[1])));op.exports=ys});var To=f((oV,lp)=>{"use strict";var up=yo(),CI=fe(),VI=ne(),OI=VI.String;lp.exports=!!Object.getOwnPropertySymbols&&!CI(function(){var a=Symbol("symbol detection");return!OI(a)||!(Object(a)instanceof Symbol)||!Symbol.sham&&up&&up<41})});var Io=f((uV,cp)=>{"use strict";var BI=To();cp.exports=BI&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var Eo=f((lV,dp)=>{"use strict";var _I=bt(),NI=ae(),FI=Tr(),qI=Io(),UI=Object;dp.exports=qI?function(a){return typeof a=="symbol"}:function(a){var e=_I("Symbol");return NI(e)&&FI(e.prototype,UI(a))}});var Ir=f((cV,pp)=>{"use strict";var HI=String;pp.exports=function(a){try{return HI(a)}catch(e){return"Object"}}});var st=f((dV,hp)=>{"use strict";var jI=ae(),QI=Ir(),GI=TypeError;hp.exports=function(a){if(jI(a))return a;throw new GI(QI(a)+" is not a function")}});var Er=f((pV,mp)=>{"use strict";var WI=st(),YI=Ri();mp.exports=function(a,e){var t=a[e];return YI(t)?void 0:WI(t)}});var bp=f((hV,fp)=>{"use strict";var xo=Oe(),Po=ae(),wo=Be(),zI=TypeError;fp.exports=function(a,e){var t,i;if(e==="string"&&Po(t=a.toString)&&!wo(i=xo(t,a))||Po(t=a.valueOf)&&!wo(i=xo(t,a))||e!=="string"&&Po(t=a.toString)&&!wo(i=xo(t,a)))return i;throw new zI("Can't convert object to primitive value")}});var ze=f((mV,gp)=>{"use strict";gp.exports=!0});var yp=f((fV,Sp)=>{"use strict";var vp=ne(),KI=Object.defineProperty;Sp.exports=function(a,e){try{KI(vp,a,{value:e,configurable:!0,writable:!0})}catch(t){vp[a]=e}return e}});var xr=f((bV,Ep)=>{"use strict";var XI=ze(),JI=ne(),ZI=yp(),Tp="__core-js_shared__",Ip=Ep.exports=JI[Tp]||ZI(Tp,{});(Ip.versions||(Ip.versions=[])).push({version:"3.38.0",mode:XI?"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 Ao=f((gV,Pp)=>{"use strict";var xp=xr();Pp.exports=function(a,e){return xp[a]||(xp[a]=e||{})}});var Li=f((vV,wp)=>{"use strict";var eE=Mt(),tE=Object;wp.exports=function(a){return tE(eE(a))}});var Ke=f((SV,Ap)=>{"use strict";var iE=ce(),rE=Li(),aE=iE({}.hasOwnProperty);Ap.exports=Object.hasOwn||function(e,t){return aE(rE(e),t)}});var ko=f((yV,kp)=>{"use strict";var sE=ce(),nE=0,oE=Math.random(),uE=sE(1 .toString);kp.exports=function(a){return"Symbol("+(a===void 0?"":a)+")_"+uE(++nE+oE,36)}});var be=f((TV,$p)=>{"use strict";var lE=ne(),cE=Ao(),Rp=Ke(),dE=ko(),pE=To(),hE=Io(),Mi=lE.Symbol,Ro=cE("wks"),mE=hE?Mi.for||Mi:Mi&&Mi.withoutSetter||dE;$p.exports=function(a){return Rp(Ro,a)||(Ro[a]=pE&&Rp(Mi,a)?Mi[a]:mE("Symbol."+a)),Ro[a]}});var Cp=f((IV,Dp)=>{"use strict";var fE=Oe(),Lp=Be(),Mp=Eo(),bE=Er(),gE=bp(),vE=be(),SE=TypeError,yE=vE("toPrimitive");Dp.exports=function(a,e){if(!Lp(a)||Mp(a))return a;var t=bE(a,yE),i;if(t){if(e===void 0&&(e="default"),i=fE(t,a,e),!Lp(i)||Mp(i))return i;throw new SE("Can't convert object to primitive value")}return e===void 0&&(e="number"),gE(a,e)}});var $o=f((EV,Vp)=>{"use strict";var TE=Cp(),IE=Eo();Vp.exports=function(a){var e=TE(a,"string");return IE(e)?e:e+""}});var Ts=f((xV,Bp)=>{"use strict";var EE=ne(),Op=Be(),Lo=EE.document,xE=Op(Lo)&&Op(Lo.createElement);Bp.exports=function(a){return xE?Lo.createElement(a):{}}});var Mo=f((PV,_p)=>{"use strict";var PE=Ve(),wE=fe(),AE=Ts();_p.exports=!PE&&!wE(function(){return Object.defineProperty(AE("div"),"a",{get:function(){return 7}}).a!==7})});var qp=f(Fp=>{"use strict";var kE=Ve(),RE=Oe(),$E=fo(),LE=yr(),ME=ri(),DE=$o(),CE=Ke(),VE=Mo(),Np=Object.getOwnPropertyDescriptor;Fp.f=kE?Np:function(e,t){if(e=ME(e),t=DE(t),VE)try{return Np(e,t)}catch(i){}if(CE(e,t))return LE(!RE($E.f,e,t),e[t])}});var Do=f((AV,Up)=>{"use strict";var OE=fe(),BE=ae(),_E=/#|\.prototype\./,Pr=function(a,e){var t=FE[NE(a)];return t===UE?!0:t===qE?!1:BE(e)?OE(e):!!e},NE=Pr.normalize=function(a){return String(a).replace(_E,".").toLowerCase()},FE=Pr.data={},qE=Pr.NATIVE="N",UE=Pr.POLYFILL="P";Up.exports=Pr});var Di=f((kV,jp)=>{"use strict";var Hp=ho(),HE=st(),jE=Sr(),QE=Hp(Hp.bind);jp.exports=function(a,e){return HE(a),e===void 0?a:jE?QE(a,e):function(){return a.apply(e,arguments)}}});var Co=f((RV,Qp)=>{"use strict";var GE=Ve(),WE=fe();Qp.exports=GE&&WE(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var nt=f(($V,Gp)=>{"use strict";var YE=Be(),zE=String,KE=TypeError;Gp.exports=function(a){if(YE(a))return a;throw new KE(zE(a)+" is not an object")}});var si=f(Yp=>{"use strict";var XE=Ve(),JE=Mo(),ZE=Co(),Is=nt(),Wp=$o(),ex=TypeError,Vo=Object.defineProperty,tx=Object.getOwnPropertyDescriptor,Oo="enumerable",Bo="configurable",_o="writable";Yp.f=XE?ZE?function(e,t,i){if(Is(e),t=Wp(t),Is(i),typeof e=="function"&&t==="prototype"&&"value"in i&&_o in i&&!i[_o]){var r=tx(e,t);r&&r[_o]&&(e[t]=i.value,i={configurable:Bo in i?i[Bo]:r[Bo],enumerable:Oo in i?i[Oo]:r[Oo],writable:!1})}return Vo(e,t,i)}:Vo:function(e,t,i){if(Is(e),t=Wp(t),Is(i),JE)try{return Vo(e,t,i)}catch(r){}if("get"in i||"set"in i)throw new ex("Accessors not supported");return"value"in i&&(e[t]=i.value),e}});var Ci=f((MV,zp)=>{"use strict";var ix=Ve(),rx=si(),ax=yr();zp.exports=ix?function(a,e,t){return rx.f(a,e,ax(1,t))}:function(a,e,t){return a[e]=t,a}});var le=f((DV,Xp)=>{"use strict";var wr=ne(),sx=co(),nx=ho(),ox=ae(),ux=qp().f,lx=Do(),Vi=$i(),cx=Di(),Oi=Ci(),Kp=Ke();xr();var dx=function(a){var e=function(t,i,r){if(this instanceof e){switch(arguments.length){case 0:return new a;case 1:return new a(t);case 2:return new a(t,i)}return new a(t,i,r)}return sx(a,this,arguments)};return e.prototype=a.prototype,e};Xp.exports=function(a,e){var t=a.target,i=a.global,r=a.stat,s=a.proto,n=i?wr:r?wr[t]:wr[t]&&wr[t].prototype,o=i?Vi:Vi[t]||Oi(Vi,t,{})[t],u=o.prototype,l,c,d,h,p,m,b,g,v;for(h in e)l=lx(i?h:t+(r?".":"#")+h,a.forced),c=!l&&n&&Kp(n,h),m=o[h],c&&(a.dontCallGetSet?(v=ux(n,h),b=v&&v.value):b=n[h]),p=c&&b?b:e[h],!(!l&&!s&&typeof m==typeof p)&&(a.bind&&c?g=cx(p,wr):a.wrap&&c?g=dx(p):s&&ox(p)?g=nx(p):g=p,(a.sham||p&&p.sham||m&&m.sham)&&Oi(g,"sham",!0),Oi(o,h,g),s&&(d=t+"Prototype",Kp(Vi,d)||Oi(Vi,d,{}),Oi(Vi[d],h,p),a.real&&u&&(l||!u[h])&&Oi(u,h,p)))}});var Zp=f((CV,Jp)=>{"use strict";var px=Math.ceil,hx=Math.floor;Jp.exports=Math.trunc||function(e){var t=+e;return(t>0?hx:px)(t)}});var Ar=f((VV,eh)=>{"use strict";var mx=Zp();eh.exports=function(a){var e=+a;return e!==e||e===0?0:mx(e)}});var ih=f((OV,th)=>{"use strict";var fx=Ar(),bx=Math.max,gx=Math.min;th.exports=function(a,e){var t=fx(a);return t<0?bx(t+e,0):gx(t,e)}});var No=f((BV,rh)=>{"use strict";var vx=Ar(),Sx=Math.min;rh.exports=function(a){var e=vx(a);return e>0?Sx(e,9007199254740991):0}});var Bi=f((_V,ah)=>{"use strict";var yx=No();ah.exports=function(a){return yx(a.length)}});var Fo=f((NV,nh)=>{"use strict";var Tx=ri(),Ix=ih(),Ex=Bi(),sh=function(a){return function(e,t,i){var r=Tx(e),s=Ex(r);if(s===0)return!a&&-1;var n=Ix(i,s),o;if(a&&t!==t){for(;s>n;)if(o=r[n++],o!==o)return!0}else for(;s>n;n++)if((a||n in r)&&r[n]===t)return a||n||0;return!a&&-1}};nh.exports={includes:sh(!0),indexOf:sh(!1)}});var kr=f((FV,oh)=>{"use strict";oh.exports=function(){}});var uh=f(()=>{"use strict";var xx=le(),Px=Fo().includes,wx=fe(),Ax=kr(),kx=wx(function(){return!Array(1).includes()});xx({target:"Array",proto:!0,forced:kx},{includes:function(e){return Px(this,e,arguments.length>1?arguments[1]:void 0)}});Ax("includes")});var Dt=f((HV,lh)=>{"use strict";var Rx=bt();lh.exports=Rx});var dh=f((jV,ch)=>{"use strict";uh();var $x=Dt();ch.exports=$x("Array","includes")});var hh=f((QV,ph)=>{"use strict";var Lx=dh();ph.exports=Lx});var qe=f((GV,mh)=>{"use strict";var Mx=hh();mh.exports=Mx});var Ps=f((aO,Ih)=>{"use strict";var Fx=Ao(),qx=ko(),Th=Fx("keys");Ih.exports=function(a){return Th[a]||(Th[a]=qx(a))}});var xh=f((sO,Eh)=>{"use strict";var Ux=fe();Eh.exports=!Ux(function(){function a(){}return a.prototype.constructor=null,Object.getPrototypeOf(new a)!==a.prototype})});var ws=f((nO,wh)=>{"use strict";var Hx=Ke(),jx=ae(),Qx=Li(),Gx=Ps(),Wx=xh(),Ph=Gx("IE_PROTO"),Ho=Object,Yx=Ho.prototype;wh.exports=Wx?Ho.getPrototypeOf:function(a){var e=Qx(a);if(Hx(e,Ph))return e[Ph];var t=e.constructor;return jx(t)&&e instanceof t?t.prototype:e instanceof Ho?Yx:null}});var As=f((oO,Ah)=>{"use strict";Ah.exports={}});var $h=f((uO,Rh)=>{"use strict";var zx=ce(),jo=Ke(),Kx=ri(),Xx=Fo().indexOf,Jx=As(),kh=zx([].push);Rh.exports=function(a,e){var t=Kx(a),i=0,r=[],s;for(s in t)!jo(Jx,s)&&jo(t,s)&&kh(r,s);for(;e.length>i;)jo(t,s=e[i++])&&(~Xx(r,s)||kh(r,s));return r}});var Qo=f((lO,Lh)=>{"use strict";Lh.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var Go=f((cO,Mh)=>{"use strict";var Zx=$h(),eP=Qo();Mh.exports=Object.keys||function(e){return Zx(e,eP)}});var Wo=f((dO,Bh)=>{"use strict";var Ch=Ve(),tP=fe(),Vh=ce(),iP=ws(),rP=Go(),aP=ri(),sP=fo().f,Oh=Vh(sP),nP=Vh([].push),oP=Ch&&tP(function(){var a=Object.create(null);return a[2]=2,!Oh(a,2)}),Dh=function(a){return function(e){for(var t=aP(e),i=rP(t),r=oP&&iP(t)===null,s=i.length,n=0,o=[],u;s>n;)u=i[n++],(!Ch||(r?u in t:Oh(t,u)))&&nP(o,a?[u,t[u]]:t[u]);return o}};Bh.exports={entries:Dh(!0),values:Dh(!1)}});var _h=f(()=>{"use strict";var uP=le(),lP=Wo().entries;uP({target:"Object",stat:!0},{entries:function(e){return lP(e)}})});var Fh=f((mO,Nh)=>{"use strict";_h();var cP=$i();Nh.exports=cP.Object.entries});var Uh=f((fO,qh)=>{"use strict";var dP=Fh();qh.exports=dP});var _i=f((bO,Hh)=>{"use strict";var pP=Uh();Hh.exports=pP});var ni=f((gO,jh)=>{"use strict";jh.exports={}});var Wh=f((vO,Gh)=>{"use strict";var hP=ne(),mP=ae(),Qh=hP.WeakMap;Gh.exports=mP(Qh)&&/native code/.test(String(Qh))});var Xo=f((SO,Kh)=>{"use strict";var fP=Wh(),zh=ne(),bP=Be(),gP=Ci(),Yo=Ke(),zo=xr(),vP=Ps(),SP=As(),Yh="Object already initialized",Ko=zh.TypeError,yP=zh.WeakMap,ks,Rr,Rs,TP=function(a){return Rs(a)?Rr(a):ks(a,{})},IP=function(a){return function(e){var t;if(!bP(e)||(t=Rr(e)).type!==a)throw new Ko("Incompatible receiver, "+a+" required");return t}};fP||zo.state?(Xe=zo.state||(zo.state=new yP),Xe.get=Xe.get,Xe.has=Xe.has,Xe.set=Xe.set,ks=function(a,e){if(Xe.has(a))throw new Ko(Yh);return e.facade=a,Xe.set(a,e),e},Rr=function(a){return Xe.get(a)||{}},Rs=function(a){return Xe.has(a)}):(oi=vP("state"),SP[oi]=!0,ks=function(a,e){if(Yo(a,oi))throw new Ko(Yh);return e.facade=a,gP(a,oi,e),e},Rr=function(a){return Yo(a,oi)?a[oi]:{}},Rs=function(a){return Yo(a,oi)});var Xe,oi;Kh.exports={set:ks,get:Rr,has:Rs,enforce:TP,getterFor:IP}});var eu=f((yO,Jh)=>{"use strict";var Jo=Ve(),EP=Ke(),Xh=Function.prototype,xP=Jo&&Object.getOwnPropertyDescriptor,Zo=EP(Xh,"name"),PP=Zo&&function(){}.name==="something",wP=Zo&&(!Jo||Jo&&xP(Xh,"name").configurable);Jh.exports={EXISTS:Zo,PROPER:PP,CONFIGURABLE:wP}});var em=f(Zh=>{"use strict";var AP=Ve(),kP=Co(),RP=si(),$P=nt(),LP=ri(),MP=Go();Zh.f=AP&&!kP?Object.defineProperties:function(e,t){$P(e);for(var i=LP(t),r=MP(t),s=r.length,n=0,o;s>n;)RP.f(e,o=r[n++],i[o]);return e}});var tu=f((IO,tm)=>{"use strict";var DP=bt();tm.exports=DP("document","documentElement")});var su=f((EO,um)=>{"use strict";var CP=nt(),VP=em(),im=Qo(),OP=As(),BP=tu(),_P=Ts(),NP=Ps(),rm=">",am="<",ru="prototype",au="script",nm=NP("IE_PROTO"),iu=function(){},om=function(a){return am+au+rm+a+am+"/"+au+rm},sm=function(a){a.write(om("")),a.close();var e=a.parentWindow.Object;return a=null,e},FP=function(){var a=_P("iframe"),e="java"+au+":",t;return a.style.display="none",BP.appendChild(a),a.src=String(e),t=a.contentWindow.document,t.open(),t.write(om("document.F=Object")),t.close(),t.F},$s,Ls=function(){try{$s=new ActiveXObject("htmlfile")}catch(e){}Ls=typeof document!="undefined"?document.domain&&$s?sm($s):FP():sm($s);for(var a=im.length;a--;)delete Ls[ru][im[a]];return Ls()};OP[nm]=!0;um.exports=Object.create||function(e,t){var i;return e!==null?(iu[ru]=CP(e),i=new iu,iu[ru]=null,i[nm]=e):i=Ls(),t===void 0?i:VP.f(i,t)}});var Ni=f((xO,lm)=>{"use strict";var qP=Ci();lm.exports=function(a,e,t,i){return i&&i.enumerable?a[e]=t:qP(a,e,t),a}});var lu=f((PO,pm)=>{"use strict";var UP=fe(),HP=ae(),jP=Be(),QP=su(),cm=ws(),GP=Ni(),WP=be(),YP=ze(),uu=WP("iterator"),dm=!1,gt,nu,ou;[].keys&&(ou=[].keys(),"next"in ou?(nu=cm(cm(ou)),nu!==Object.prototype&&(gt=nu)):dm=!0);var zP=!jP(gt)||UP(function(){var a={};return gt[uu].call(a)!==a});zP?gt={}:YP&&(gt=QP(gt));HP(gt[uu])||GP(gt,uu,function(){return this});pm.exports={IteratorPrototype:gt,BUGGY_SAFARI_ITERATORS:dm}});var Ms=f((wO,mm)=>{"use strict";var KP=be(),XP=KP("toStringTag"),hm={};hm[XP]="z";mm.exports=String(hm)==="[object z]"});var $r=f((AO,fm)=>{"use strict";var JP=Ms(),ZP=ae(),Ds=ii(),ew=be(),tw=ew("toStringTag"),iw=Object,rw=Ds(function(){return arguments}())==="Arguments",aw=function(a,e){try{return a[e]}catch(t){}};fm.exports=JP?Ds:function(a){var e,t,i;return a===void 0?"Undefined":a===null?"Null":typeof(t=aw(e=iw(a),tw))=="string"?t:rw?Ds(e):(i=Ds(e))==="Object"&&ZP(e.callee)?"Arguments":i}});var gm=f((kO,bm)=>{"use strict";var sw=Ms(),nw=$r();bm.exports=sw?{}.toString:function(){return"[object "+nw(this)+"]"}});var Lr=f((RO,Sm)=>{"use strict";var ow=Ms(),uw=si().f,lw=Ci(),cw=Ke(),dw=gm(),pw=be(),vm=pw("toStringTag");Sm.exports=function(a,e,t,i){var r=t?a:a&&a.prototype;r&&(cw(r,vm)||uw(r,vm,{configurable:!0,value:e}),i&&!ow&&lw(r,"toString",dw))}});var Tm=f(($O,ym)=>{"use strict";var hw=lu().IteratorPrototype,mw=su(),fw=yr(),bw=Lr(),gw=ni(),vw=function(){return this};ym.exports=function(a,e,t,i){var r=e+" Iterator";return a.prototype=mw(hw,{next:fw(+!i,t)}),bw(a,r,!1,!0),gw[r]=vw,a}});var Em=f((LO,Im)=>{"use strict";var Sw=ce(),yw=st();Im.exports=function(a,e,t){try{return Sw(yw(Object.getOwnPropertyDescriptor(a,e)[t]))}catch(i){}}});var Pm=f((MO,xm)=>{"use strict";var Tw=Be();xm.exports=function(a){return Tw(a)||a===null}});var Am=f((DO,wm)=>{"use strict";var Iw=Pm(),Ew=String,xw=TypeError;wm.exports=function(a){if(Iw(a))return a;throw new xw("Can't set "+Ew(a)+" as a prototype")}});var cu=f((CO,km)=>{"use strict";var Pw=Em(),ww=Be(),Aw=Mt(),kw=Am();km.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var a=!1,e={},t;try{t=Pw(Object.prototype,"__proto__","set"),t(e,[]),a=e instanceof Array}catch(i){}return function(r,s){return Aw(r),kw(s),ww(r)&&(a?t(r,s):r.__proto__=s),r}}():void 0)});var Nm=f((VO,_m)=>{"use strict";var Rw=le(),$w=Oe(),Cs=ze(),Om=eu(),Lw=ae(),Mw=Tm(),Rm=ws(),$m=cu(),Dw=Lr(),Cw=Ci(),du=Ni(),Vw=be(),Lm=ni(),Bm=lu(),Ow=Om.PROPER,Bw=Om.CONFIGURABLE,Mm=Bm.IteratorPrototype,Vs=Bm.BUGGY_SAFARI_ITERATORS,Mr=Vw("iterator"),Dm="keys",Dr="values",Cm="entries",Vm=function(){return this};_m.exports=function(a,e,t,i,r,s,n){Mw(t,e,i);var o=function(v){if(v===r&&h)return h;if(!Vs&&v&&v in c)return c[v];switch(v){case Dm:return function(){return new t(this,v)};case Dr:return function(){return new t(this,v)};case Cm:return function(){return new t(this,v)}}return function(){return new t(this)}},u=e+" Iterator",l=!1,c=a.prototype,d=c[Mr]||c["@@iterator"]||r&&c[r],h=!Vs&&d||o(r),p=e==="Array"&&c.entries||d,m,b,g;if(p&&(m=Rm(p.call(new a)),m!==Object.prototype&&m.next&&(!Cs&&Rm(m)!==Mm&&($m?$m(m,Mm):Lw(m[Mr])||du(m,Mr,Vm)),Dw(m,u,!0,!0),Cs&&(Lm[u]=Vm))),Ow&&r===Dr&&d&&d.name!==Dr&&(!Cs&&Bw?Cw(c,"name",Dr):(l=!0,h=function(){return $w(d,this)})),r)if(b={values:o(Dr),keys:s?h:o(Dm),entries:o(Cm)},n)for(g in b)(Vs||l||!(g in c))&&du(c,g,b[g]);else Rw({target:e,proto:!0,forced:Vs||l},b);return(!Cs||n)&&c[Mr]!==h&&du(c,Mr,h,{name:r}),Lm[e]=h,b}});var qm=f((OO,Fm)=>{"use strict";Fm.exports=function(a,e){return{value:a,done:e}}});var hu=f((BO,Gm)=>{"use strict";var _w=ri(),pu=kr(),Um=ni(),jm=Xo(),Nw=si().f,Fw=Nm(),Os=qm(),qw=ze(),Uw=Ve(),Qm="Array Iterator",Hw=jm.set,jw=jm.getterFor(Qm);Gm.exports=Fw(Array,"Array",function(a,e){Hw(this,{type:Qm,target:_w(a),index:0,kind:e})},function(){var a=jw(this),e=a.target,t=a.index++;if(!e||t>=e.length)return a.target=void 0,Os(void 0,!0);switch(a.kind){case"keys":return Os(t,!1);case"values":return Os(e[t],!1)}return Os([t,e[t]],!1)},"values");var Hm=Um.Arguments=Um.Array;pu("keys");pu("values");pu("entries");if(!qw&&Uw&&Hm.name!=="values")try{Nw(Hm,"name",{value:"values"})}catch(a){}});var Ym=f((_O,Wm)=>{"use strict";var Qw=be(),Gw=ni(),Ww=Qw("iterator"),Yw=Array.prototype;Wm.exports=function(a){return a!==void 0&&(Gw.Array===a||Yw[Ww]===a)}});var mu=f((NO,Km)=>{"use strict";var zw=$r(),zm=Er(),Kw=Ri(),Xw=ni(),Jw=be(),Zw=Jw("iterator");Km.exports=function(a){if(!Kw(a))return zm(a,Zw)||zm(a,"@@iterator")||Xw[zw(a)]}});var Jm=f((FO,Xm)=>{"use strict";var eA=Oe(),tA=st(),iA=nt(),rA=Ir(),aA=mu(),sA=TypeError;Xm.exports=function(a,e){var t=arguments.length<2?aA(a):e;if(tA(t))return iA(eA(t,a));throw new sA(rA(a)+" is not iterable")}});var tf=f((qO,ef)=>{"use strict";var nA=Oe(),Zm=nt(),oA=Er();ef.exports=function(a,e,t){var i,r;Zm(a);try{if(i=oA(a,"return"),!i){if(e==="throw")throw t;return t}i=nA(i,a)}catch(s){r=!0,i=s}if(e==="throw")throw t;if(r)throw i;return Zm(i),t}});var _s=f((UO,nf)=>{"use strict";var uA=Di(),lA=Oe(),cA=nt(),dA=Ir(),pA=Ym(),hA=Bi(),rf=Tr(),mA=Jm(),fA=mu(),af=tf(),bA=TypeError,Bs=function(a,e){this.stopped=a,this.result=e},sf=Bs.prototype;nf.exports=function(a,e,t){var i=t&&t.that,r=!!(t&&t.AS_ENTRIES),s=!!(t&&t.IS_RECORD),n=!!(t&&t.IS_ITERATOR),o=!!(t&&t.INTERRUPTED),u=uA(e,i),l,c,d,h,p,m,b,g=function(S){return l&&af(l,"normal",S),new Bs(!0,S)},v=function(S){return r?(cA(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=fA(a),!c)throw new bA(dA(a)+" is not iterable");if(pA(c)){for(d=0,h=hA(a);h>d;d++)if(p=v(a[d]),p&&rf(sf,p))return p;return new Bs(!1)}l=mA(a,c)}for(m=s?a.next:l.next;!(b=lA(m,l)).done;){try{p=v(b.value)}catch(S){af(l,"throw",S)}if(typeof p=="object"&&p&&rf(sf,p))return p}return new Bs(!1)}});var uf=f((HO,of)=>{"use strict";var gA=Ve(),vA=si(),SA=yr();of.exports=function(a,e,t){gA?vA.f(a,e,SA(0,t)):a[e]=t}});var lf=f(()=>{"use strict";var yA=le(),TA=_s(),IA=uf();yA({target:"Object",stat:!0},{fromEntries:function(e){var t={};return TA(e,function(i,r){IA(t,i,r)},{AS_ENTRIES:!0}),t}})});var df=f((GO,cf)=>{"use strict";hu();lf();var EA=$i();cf.exports=EA.Object.fromEntries});var hf=f((WO,pf)=>{"use strict";pf.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 ff=f(()=>{"use strict";hu();var xA=hf(),PA=ne(),wA=Lr(),mf=ni();for(Ns in xA)wA(PA[Ns],Ns),mf[Ns]=mf.Array;var Ns});var gf=f((KO,bf)=>{"use strict";var AA=df();ff();bf.exports=AA});var fu=f((XO,vf)=>{"use strict";var kA=gf();vf.exports=kA});var Sf=f(()=>{"use strict"});var bu=f((eB,yf)=>{"use strict";var Cr=ne(),RA=ai(),$A=ii(),Fs=function(a){return RA.slice(0,a.length)===a};yf.exports=function(){return Fs("Bun/")?"BUN":Fs("Cloudflare-Workers")?"CLOUDFLARE":Fs("Deno/")?"DENO":Fs("Node.js/")?"NODE":Cr.Bun&&typeof Bun.version=="string"?"BUN":Cr.Deno&&typeof Deno.version=="object"?"DENO":$A(Cr.process)==="process"?"NODE":Cr.window&&Cr.document?"BROWSER":"REST"}()});var qs=f((tB,Tf)=>{"use strict";var LA=bu();Tf.exports=LA==="NODE"});var Ef=f((iB,If)=>{"use strict";var MA=si();If.exports=function(a,e,t){return MA.f(a,e,t)}});var wf=f((rB,Pf)=>{"use strict";var DA=bt(),CA=Ef(),VA=be(),OA=Ve(),xf=VA("species");Pf.exports=function(a){var e=DA(a);OA&&e&&!e[xf]&&CA(e,xf,{configurable:!0,get:function(){return this}})}});var kf=f((aB,Af)=>{"use strict";var BA=Tr(),_A=TypeError;Af.exports=function(a,e){if(BA(e,a))return a;throw new _A("Incorrect invocation")}});var vu=f((sB,Rf)=>{"use strict";var NA=ce(),FA=ae(),gu=xr(),qA=NA(Function.toString);FA(gu.inspectSource)||(gu.inspectSource=function(a){return qA(a)});Rf.exports=gu.inspectSource});var yu=f((nB,Cf)=>{"use strict";var UA=ce(),HA=fe(),$f=ae(),jA=$r(),QA=bt(),GA=vu(),Lf=function(){},Mf=QA("Reflect","construct"),Su=/^\s*(?:class|function)\b/,WA=UA(Su.exec),YA=!Su.test(Lf),Vr=function(e){if(!$f(e))return!1;try{return Mf(Lf,[],e),!0}catch(t){return!1}},Df=function(e){if(!$f(e))return!1;switch(jA(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return YA||!!WA(Su,GA(e))}catch(t){return!0}};Df.sham=!0;Cf.exports=!Mf||HA(function(){var a;return Vr(Vr.call)||!Vr(Object)||!Vr(function(){a=!0})||a})?Df:Vr});var Of=f((oB,Vf)=>{"use strict";var zA=yu(),KA=Ir(),XA=TypeError;Vf.exports=function(a){if(zA(a))return a;throw new XA(KA(a)+" is not a constructor")}});var Tu=f((uB,_f)=>{"use strict";var Bf=nt(),JA=Of(),ZA=Ri(),ek=be(),tk=ek("species");_f.exports=function(a,e){var t=Bf(a).constructor,i;return t===void 0||ZA(i=Bf(t)[tk])?e:JA(i)}});var Ff=f((lB,Nf)=>{"use strict";var ik=ce();Nf.exports=ik([].slice)});var Uf=f((cB,qf)=>{"use strict";var rk=TypeError;qf.exports=function(a,e){if(a<e)throw new rk("Not enough arguments");return a}});var Iu=f((dB,Hf)=>{"use strict";var ak=ai();Hf.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(ak)});var Lu=f((pB,Jf)=>{"use strict";var _e=ne(),sk=co(),nk=Di(),jf=ae(),ok=Ke(),Xf=fe(),Qf=tu(),uk=Ff(),Gf=Ts(),lk=Uf(),ck=Iu(),dk=qs(),ku=_e.setImmediate,Ru=_e.clearImmediate,pk=_e.process,Eu=_e.Dispatch,hk=_e.Function,Wf=_e.MessageChannel,mk=_e.String,xu=0,Or={},Yf="onreadystatechange",Br,ui,Pu,wu;Xf(function(){Br=_e.location});var $u=function(a){if(ok(Or,a)){var e=Or[a];delete Or[a],e()}},Au=function(a){return function(){$u(a)}},zf=function(a){$u(a.data)},Kf=function(a){_e.postMessage(mk(a),Br.protocol+"//"+Br.host)};(!ku||!Ru)&&(ku=function(e){lk(arguments.length,1);var t=jf(e)?e:hk(e),i=uk(arguments,1);return Or[++xu]=function(){sk(t,void 0,i)},ui(xu),xu},Ru=function(e){delete Or[e]},dk?ui=function(a){pk.nextTick(Au(a))}:Eu&&Eu.now?ui=function(a){Eu.now(Au(a))}:Wf&&!ck?(Pu=new Wf,wu=Pu.port2,Pu.port1.onmessage=zf,ui=nk(wu.postMessage,wu)):_e.addEventListener&&jf(_e.postMessage)&&!_e.importScripts&&Br&&Br.protocol!=="file:"&&!Xf(Kf)?(ui=Kf,_e.addEventListener("message",zf,!1)):Yf in Gf("script")?ui=function(a){Qf.appendChild(Gf("script"))[Yf]=function(){Qf.removeChild(this),$u(a)}}:ui=function(a){setTimeout(Au(a),0)});Jf.exports={set:ku,clear:Ru}});var tb=f((hB,eb)=>{"use strict";var Zf=ne(),fk=Ve(),bk=Object.getOwnPropertyDescriptor;eb.exports=function(a){if(!fk)return Zf[a];var e=bk(Zf,a);return e&&e.value}});var Mu=f((mB,rb)=>{"use strict";var ib=function(){this.head=null,this.tail=null};ib.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}}};rb.exports=ib});var sb=f((fB,ab)=>{"use strict";var gk=ai();ab.exports=/ipad|iphone|ipod/i.test(gk)&&typeof Pebble!="undefined"});var ob=f((bB,nb)=>{"use strict";var vk=ai();nb.exports=/web0s(?!.*chrome)/i.test(vk)});var mb=f((gB,hb)=>{"use strict";var qi=ne(),Sk=tb(),ub=Di(),Du=Lu().set,yk=Mu(),Tk=Iu(),Ik=sb(),Ek=ob(),Cu=qs(),lb=qi.MutationObserver||qi.WebKitMutationObserver,cb=qi.document,db=qi.process,Us=qi.Promise,Bu=Sk("queueMicrotask"),Fi,Vu,Ou,Hs,pb;Bu||(_r=new yk,Nr=function(){var a,e;for(Cu&&(a=db.domain)&&a.exit();e=_r.get();)try{e()}catch(t){throw _r.head&&Fi(),t}a&&a.enter()},!Tk&&!Cu&&!Ek&&lb&&cb?(Vu=!0,Ou=cb.createTextNode(""),new lb(Nr).observe(Ou,{characterData:!0}),Fi=function(){Ou.data=Vu=!Vu}):!Ik&&Us&&Us.resolve?(Hs=Us.resolve(void 0),Hs.constructor=Us,pb=ub(Hs.then,Hs),Fi=function(){pb(Nr)}):Cu?Fi=function(){db.nextTick(Nr)}:(Du=ub(Du,qi),Fi=function(){Du(Nr)}),Bu=function(a){_r.head||Fi(),_r.add(a)});var _r,Nr;hb.exports=Bu});var bb=f((vB,fb)=>{"use strict";fb.exports=function(a,e){try{arguments.length===1?console.error(a):console.error(a,e)}catch(t){}}});var js=f((SB,gb)=>{"use strict";gb.exports=function(a){try{return{error:!1,value:a()}}catch(e){return{error:!0,value:e}}}});var li=f((yB,vb)=>{"use strict";var xk=ne();vb.exports=xk.Promise});var Ui=f((TB,Ib)=>{"use strict";var Pk=ne(),Fr=li(),wk=ae(),Ak=Do(),kk=vu(),Rk=be(),Sb=bu(),$k=ze(),_u=yo(),yb=Fr&&Fr.prototype,Lk=Rk("species"),Nu=!1,Tb=wk(Pk.PromiseRejectionEvent),Mk=Ak("Promise",function(){var a=kk(Fr),e=a!==String(Fr);if(!e&&_u===66||$k&&!(yb.catch&&yb.finally))return!0;if(!_u||_u<51||!/native code/.test(a)){var t=new Fr(function(s){s(1)}),i=function(s){s(function(){},function(){})},r=t.constructor={};if(r[Lk]=i,Nu=t.then(function(){})instanceof i,!Nu)return!0}return!e&&(Sb==="BROWSER"||Sb==="DENO")&&!Tb});Ib.exports={CONSTRUCTOR:Mk,REJECTION_EVENT:Tb,SUBCLASSING:Nu}});var Hi=f((IB,xb)=>{"use strict";var Eb=st(),Dk=TypeError,Ck=function(a){var e,t;this.promise=new a(function(i,r){if(e!==void 0||t!==void 0)throw new Dk("Bad Promise constructor");e=i,t=r}),this.resolve=Eb(e),this.reject=Eb(t)};xb.exports.f=function(a){return new Ck(a)}});var Hb=f(()=>{"use strict";var Vk=le(),Ok=ze(),Ys=qs(),Ct=ne(),Wi=Oe(),Pb=Ni(),wb=cu(),Bk=Lr(),_k=wf(),Nk=st(),Ws=ae(),Fk=Be(),qk=kf(),Uk=Tu(),Lb=Lu().set,ju=mb(),Hk=bb(),jk=js(),Qk=Mu(),Mb=Xo(),zs=li(),Qu=Ui(),Db=Hi(),Ks="Promise",Cb=Qu.CONSTRUCTOR,Gk=Qu.REJECTION_EVENT,Wk=Qu.SUBCLASSING,Fu=Mb.getterFor(Ks),Yk=Mb.set,ji=zs&&zs.prototype,ci=zs,Qs=ji,Vb=Ct.TypeError,qu=Ct.document,Gu=Ct.process,Uu=Db.f,zk=Uu,Kk=!!(qu&&qu.createEvent&&Ct.dispatchEvent),Ob="unhandledrejection",Xk="rejectionhandled",Ab=0,Bb=1,Jk=2,Wu=1,_b=2,Gs,kb,Zk,Rb,Nb=function(a){var e;return Fk(a)&&Ws(e=a.then)?e:!1},Fb=function(a,e){var t=e.value,i=e.state===Bb,r=i?a.ok:a.fail,s=a.resolve,n=a.reject,o=a.domain,u,l,c;try{r?(i||(e.rejection===_b&&tR(e),e.rejection=Wu),r===!0?u=t:(o&&o.enter(),u=r(t),o&&(o.exit(),c=!0)),u===a.promise?n(new Vb("Promise-chain cycle")):(l=Nb(u))?Wi(l,u,s,n):s(u)):n(t)}catch(d){o&&!c&&o.exit(),n(d)}},qb=function(a,e){a.notified||(a.notified=!0,ju(function(){for(var t=a.reactions,i;i=t.get();)Fb(i,a);a.notified=!1,e&&!a.rejection&&eR(a)}))},Ub=function(a,e,t){var i,r;Kk?(i=qu.createEvent("Event"),i.promise=e,i.reason=t,i.initEvent(a,!1,!0),Ct.dispatchEvent(i)):i={promise:e,reason:t},!Gk&&(r=Ct["on"+a])?r(i):a===Ob&&Hk("Unhandled promise rejection",t)},eR=function(a){Wi(Lb,Ct,function(){var e=a.facade,t=a.value,i=$b(a),r;if(i&&(r=jk(function(){Ys?Gu.emit("unhandledRejection",t,e):Ub(Ob,e,t)}),a.rejection=Ys||$b(a)?_b:Wu,r.error))throw r.value})},$b=function(a){return a.rejection!==Wu&&!a.parent},tR=function(a){Wi(Lb,Ct,function(){var e=a.facade;Ys?Gu.emit("rejectionHandled",e):Ub(Xk,e,a.value)})},Qi=function(a,e,t){return function(i){a(e,i,t)}},Gi=function(a,e,t){a.done||(a.done=!0,t&&(a=t),a.value=e,a.state=Jk,qb(a,!0))},Hu=function(a,e,t){if(!a.done){a.done=!0,t&&(a=t);try{if(a.facade===e)throw new Vb("Promise can't be resolved itself");var i=Nb(e);i?ju(function(){var r={done:!1};try{Wi(i,e,Qi(Hu,r,a),Qi(Gi,r,a))}catch(s){Gi(r,s,a)}}):(a.value=e,a.state=Bb,qb(a,!1))}catch(r){Gi({done:!1},r,a)}}};if(Cb&&(ci=function(e){qk(this,Qs),Nk(e),Wi(Gs,this);var t=Fu(this);try{e(Qi(Hu,t),Qi(Gi,t))}catch(i){Gi(t,i)}},Qs=ci.prototype,Gs=function(e){Yk(this,{type:Ks,done:!1,notified:!1,parent:!1,reactions:new Qk,rejection:!1,state:Ab,value:void 0})},Gs.prototype=Pb(Qs,"then",function(e,t){var i=Fu(this),r=Uu(Uk(this,ci));return i.parent=!0,r.ok=Ws(e)?e:!0,r.fail=Ws(t)&&t,r.domain=Ys?Gu.domain:void 0,i.state===Ab?i.reactions.add(r):ju(function(){Fb(r,i)}),r.promise}),kb=function(){var a=new Gs,e=Fu(a);this.promise=a,this.resolve=Qi(Hu,e),this.reject=Qi(Gi,e)},Db.f=Uu=function(a){return a===ci||a===Zk?new kb(a):zk(a)},!Ok&&Ws(zs)&&ji!==Object.prototype)){Rb=ji.then,Wk||Pb(ji,"then",function(e,t){var i=this;return new ci(function(r,s){Wi(Rb,i,r,s)}).then(e,t)},{unsafe:!0});try{delete ji.constructor}catch(a){}wb&&wb(ji,Qs)}Vk({global:!0,constructor:!0,wrap:!0,forced:Cb},{Promise:ci});Bk(ci,Ks,!1,!0);_k(Ks)});var Yb=f((PB,Wb)=>{"use strict";var iR=be(),Qb=iR("iterator"),Gb=!1;try{jb=0,Yu={next:function(){return{done:!!jb++}},return:function(){Gb=!0}},Yu[Qb]=function(){return this},Array.from(Yu,function(){throw 2})}catch(a){}var jb,Yu;Wb.exports=function(a,e){try{if(!e&&!Gb)return!1}catch(r){return!1}var t=!1;try{var i={};i[Qb]=function(){return{next:function(){return{done:t=!0}}}},a(i)}catch(r){}return t}});var zu=f((wB,zb)=>{"use strict";var rR=li(),aR=Yb(),sR=Ui().CONSTRUCTOR;zb.exports=sR||!aR(function(a){rR.all(a).then(void 0,function(){})})});var Kb=f(()=>{"use strict";var nR=le(),oR=Oe(),uR=st(),lR=Hi(),cR=js(),dR=_s(),pR=zu();nR({target:"Promise",stat:!0,forced:pR},{all:function(e){var t=this,i=lR.f(t),r=i.resolve,s=i.reject,n=cR(function(){var o=uR(t.resolve),u=[],l=0,c=1;dR(e,function(d){var h=l++,p=!1;c++,oR(o,t,d).then(function(m){p||(p=!0,u[h]=m,--c||r(u))},s)}),--c||r(u)});return n.error&&s(n.value),i.promise}})});var Jb=f(()=>{"use strict";var hR=le(),mR=ze(),fR=Ui().CONSTRUCTOR,Xu=li(),bR=bt(),gR=ae(),vR=Ni(),Xb=Xu&&Xu.prototype;hR({target:"Promise",proto:!0,forced:fR,real:!0},{catch:function(a){return this.then(void 0,a)}});!mR&&gR(Xu)&&(Ku=bR("Promise").prototype.catch,Xb.catch!==Ku&&vR(Xb,"catch",Ku,{unsafe:!0}));var Ku});var Zb=f(()=>{"use strict";var SR=le(),yR=Oe(),TR=st(),IR=Hi(),ER=js(),xR=_s(),PR=zu();SR({target:"Promise",stat:!0,forced:PR},{race:function(e){var t=this,i=IR.f(t),r=i.reject,s=ER(function(){var n=TR(t.resolve);xR(e,function(o){yR(n,t,o).then(i.resolve,r)})});return s.error&&r(s.value),i.promise}})});var eg=f(()=>{"use strict";var wR=le(),AR=Hi(),kR=Ui().CONSTRUCTOR;wR({target:"Promise",stat:!0,forced:kR},{reject:function(e){var t=AR.f(this),i=t.reject;return i(e),t.promise}})});var Ju=f((VB,tg)=>{"use strict";var RR=nt(),$R=Be(),LR=Hi();tg.exports=function(a,e){if(RR(a),$R(e)&&e.constructor===a)return e;var t=LR.f(a),i=t.resolve;return i(e),t.promise}});var ag=f(()=>{"use strict";var MR=le(),DR=bt(),ig=ze(),CR=li(),rg=Ui().CONSTRUCTOR,VR=Ju(),OR=DR("Promise"),BR=ig&&!rg;MR({target:"Promise",stat:!0,forced:ig||rg},{resolve:function(e){return VR(BR&&this===OR?CR:this,e)}})});var sg=f(()=>{"use strict";Hb();Kb();Jb();Zb();eg();ag()});var lg=f(()=>{"use strict";var _R=le(),NR=ze(),Xs=li(),FR=fe(),og=bt(),ug=ae(),qR=Tu(),ng=Ju(),UR=Ni(),el=Xs&&Xs.prototype,HR=!!Xs&&FR(function(){el.finally.call({then:function(){}},function(){})});_R({target:"Promise",proto:!0,real:!0,forced:HR},{finally:function(a){var e=qR(this,og("Promise")),t=ug(a);return this.then(t?function(i){return ng(e,a()).then(function(){return i})}:a,t?function(i){return ng(e,a()).then(function(){throw i})}:a)}});!NR&&ug(Xs)&&(Zu=og("Promise").prototype.finally,el.finally!==Zu&&UR(el,"finally",Zu,{unsafe:!0}));var Zu});var dg=f((UB,cg)=>{"use strict";Sf();sg();lg();var jR=Dt();cg.exports=jR("Promise","finally")});var hg=f((HB,pg)=>{"use strict";var QR=dg();pg.exports=QR});var Js=f((jB,mg)=>{"use strict";var GR=hg();mg.exports=GR});var Ag=f(()=>{"use strict";var n$=le(),o$=Wo().values;n$({target:"Object",stat:!0},{values:function(e){return o$(e)}})});var Rg=f((k_,kg)=>{"use strict";Ag();var u$=$i();kg.exports=u$.Object.values});var Lg=f((R_,$g)=>{"use strict";var l$=Rg();$g.exports=l$});var zi=f(($_,Mg)=>{"use strict";var c$=Lg();Mg.exports=c$});var zg=f(()=>{"use strict";var C$=le(),V$=Li(),O$=Bi(),B$=Ar(),_$=kr();C$({target:"Array",proto:!0},{at:function(e){var t=V$(this),i=O$(t),r=B$(e),s=r>=0?r:i+r;return s<0||s>=i?void 0:t[s]}});_$("at")});var Xg=f((UN,Kg)=>{"use strict";zg();var N$=Dt();Kg.exports=N$("Array","at")});var Zg=f((HN,Jg)=>{"use strict";var F$=Xg();Jg.exports=F$});var Nt=f((jN,ev)=>{"use strict";var q$=Zg();ev.exports=q$});var wl=f((Mq,Vv)=>{"use strict";var xL=ii();Vv.exports=Array.isArray||function(e){return xL(e)==="Array"}});var Bv=f((Dq,Ov)=>{"use strict";var PL=TypeError,wL=9007199254740991;Ov.exports=function(a){if(a>wL)throw PL("Maximum allowed index exceeded");return a}});var Fv=f((Cq,Nv)=>{"use strict";var AL=wl(),kL=Bi(),RL=Bv(),$L=Di(),_v=function(a,e,t,i,r,s,n,o){for(var u=r,l=0,c=n?$L(n,o):!1,d,h;l<i;)l in t&&(d=c?c(t[l],l,e):t[l],s>0&&AL(d)?(h=kL(d),u=_v(a,e,d,h,u,s-1)-1):(RL(u+1),a[u]=d),u++),l++;return u};Nv.exports=_v});var jv=f((Vq,Hv)=>{"use strict";var qv=wl(),LL=yu(),ML=Be(),DL=be(),CL=DL("species"),Uv=Array;Hv.exports=function(a){var e;return qv(a)&&(e=a.constructor,LL(e)&&(e===Uv||qv(e.prototype))?e=void 0:ML(e)&&(e=e[CL],e===null&&(e=void 0))),e===void 0?Uv:e}});var Gv=f((Oq,Qv)=>{"use strict";var VL=jv();Qv.exports=function(a,e){return new(VL(a))(e===0?0:e)}});var Wv=f(()=>{"use strict";var OL=le(),BL=Fv(),_L=st(),NL=Li(),FL=Bi(),qL=Gv();OL({target:"Array",proto:!0},{flatMap:function(e){var t=NL(this),i=FL(t),r;return _L(e),r=qL(t,0),r.length=BL(r,t,t,i,0,1,e,arguments.length>1?arguments[1]:void 0),r}})});var Yv=f(()=>{"use strict";var UL=kr();UL("flatMap")});var Kv=f((qq,zv)=>{"use strict";Wv();Yv();var HL=Dt();zv.exports=HL("Array","flatMap")});var Jv=f((Uq,Xv)=>{"use strict";var jL=Kv();Xv.exports=jL});var Al=f((Hq,Zv)=>{"use strict";var QL=Jv();Zv.exports=QL});var ra=f((jq,eS)=>{"use strict";var GL=$r(),WL=String;eS.exports=function(a){if(GL(a)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return WL(a)}});var kl=f((Qq,tS)=>{"use strict";tS.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 aS=f((Gq,rS)=>{"use strict";var YL=ce(),zL=Mt(),KL=ra(),$l=kl(),iS=YL("".replace),XL=RegExp("^["+$l+"]+"),JL=RegExp("(^|[^"+$l+"])["+$l+"]+$"),Rl=function(a){return function(e){var t=KL(zL(e));return a&1&&(t=iS(t,XL,"")),a&2&&(t=iS(t,JL,"$1")),t}};rS.exports={start:Rl(1),end:Rl(2),trim:Rl(3)}});var uS=f((Wq,oS)=>{"use strict";var ZL=eu().PROPER,eM=fe(),sS=kl(),nS="\u200B\x85\u180E";oS.exports=function(a){return eM(function(){return!!sS[a]()||nS[a]()!==nS||ZL&&sS[a].name!==a})}});var Ll=f((Yq,lS)=>{"use strict";var tM=aS().start,iM=uS();lS.exports=iM("trimStart")?function(){return tM(this)}:"".trimStart});var dS=f(()=>{"use strict";var rM=le(),cS=Ll();rM({target:"String",proto:!0,name:"trimStart",forced:"".trimLeft!==cS},{trimLeft:cS})});var hS=f(()=>{"use strict";dS();var aM=le(),pS=Ll();aM({target:"String",proto:!0,name:"trimStart",forced:"".trimStart!==pS},{trimStart:pS})});var fS=f((Zq,mS)=>{"use strict";hS();var sM=Dt();mS.exports=sM("String","trimLeft")});var gS=f((eU,bS)=>{"use strict";var nM=fS();bS.exports=nM});var SS=f((tU,vS)=>{"use strict";var oM=gS();vS.exports=oM});var VS=f(()=>{"use strict"});var OS=f(()=>{"use strict"});var _S=f((_H,BS)=>{"use strict";var $M=Be(),LM=ii(),MM=be(),DM=MM("match");BS.exports=function(a){var e;return $M(a)&&((e=a[DM])!==void 0?!!e:LM(a)==="RegExp")}});var FS=f((NH,NS)=>{"use strict";var CM=nt();NS.exports=function(){var a=CM(this),e="";return a.hasIndices&&(e+="d"),a.global&&(e+="g"),a.ignoreCase&&(e+="i"),a.multiline&&(e+="m"),a.dotAll&&(e+="s"),a.unicode&&(e+="u"),a.unicodeSets&&(e+="v"),a.sticky&&(e+="y"),e}});var HS=f((FH,US)=>{"use strict";var VM=Oe(),OM=Ke(),BM=Tr(),_M=FS(),qS=RegExp.prototype;US.exports=function(a){var e=a.flags;return e===void 0&&!("flags"in qS)&&!OM(a,"flags")&&BM(qS,a)?VM(_M,a):e}});var QS=f((qH,jS)=>{"use strict";var Nl=ce(),NM=Li(),FM=Math.floor,Bl=Nl("".charAt),qM=Nl("".replace),_l=Nl("".slice),UM=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,HM=/\$([$&'`]|\d{1,2})/g;jS.exports=function(a,e,t,i,r,s){var n=t+a.length,o=i.length,u=HM;return r!==void 0&&(r=NM(r),u=UM),qM(s,u,function(l,c){var d;switch(Bl(c,0)){case"$":return"$";case"&":return a;case"`":return _l(e,0,t);case"'":return _l(e,n);case"<":d=r[_l(c,1,-1)];break;default:var h=+c;if(h===0)return l;if(h>o){var p=FM(h/10);return p===0?l:p<=o?i[p-1]===void 0?Bl(c,1):i[p-1]+Bl(c,1):l}d=i[h-1]}return d===void 0?"":d})}});var YS=f(()=>{"use strict";var jM=le(),QM=Oe(),ql=ce(),GS=Mt(),GM=ae(),WM=Ri(),YM=_S(),tr=ra(),zM=Er(),KM=HS(),XM=QS(),JM=be(),ZM=ze(),eD=JM("replace"),tD=TypeError,Fl=ql("".indexOf),iD=ql("".replace),WS=ql("".slice),rD=Math.max;jM({target:"String",proto:!0},{replaceAll:function(e,t){var i=GS(this),r,s,n,o,u,l,c,d,h,p,m=0,b="";if(!WM(e)){if(r=YM(e),r&&(s=tr(GS(KM(e))),!~Fl(s,"g")))throw new tD("`.replaceAll` does not allow non-global regexes");if(n=zM(e,eD),n)return QM(n,e,i,t);if(ZM&&r)return iD(tr(i),e,t)}for(o=tr(i),u=tr(e),l=GM(t),l||(t=tr(t)),c=u.length,d=rD(1,c),h=Fl(o,u);h!==-1;)p=l?tr(t(u,h,o)):XM(u,o,h,[],void 0,t),b+=WS(o,m,h)+p,m=h+c,h=h+d>o.length?-1:Fl(o,u,h+d);return m<o.length&&(b+=WS(o,m)),b}})});var KS=f((jH,zS)=>{"use strict";VS();OS();YS();var aD=Dt();zS.exports=aD("String","replaceAll")});var JS=f((QH,XS)=>{"use strict";var sD=KS();XS.exports=sD});var ey=f((GH,ZS)=>{"use strict";var nD=JS();ZS.exports=nD});var iy=f((WH,ty)=>{"use strict";var oD=Ar(),uD=ra(),lD=Mt(),cD=RangeError;ty.exports=function(e){var t=uD(lD(this)),i="",r=oD(e);if(r<0||r===1/0)throw new cD("Wrong number of repetitions");for(;r>0;(r>>>=1)&&(t+=t))r&1&&(i+=t);return i}});var oy=f((YH,ny)=>{"use strict";var sy=ce(),dD=No(),ry=ra(),pD=iy(),hD=Mt(),mD=sy(pD),fD=sy("".slice),bD=Math.ceil,ay=function(a){return function(e,t,i){var r=ry(hD(e)),s=dD(t),n=r.length,o=i===void 0?" ":ry(i),u,l;return s<=n||o===""?r:(u=s-n,l=mD(o,bD(u/o.length)),l.length>u&&(l=fD(l,0,u)),a?r+l:l+r)}};ny.exports={start:ay(!1),end:ay(!0)}});var ly=f((zH,uy)=>{"use strict";var gD=ai();uy.exports=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(gD)});var cy=f(()=>{"use strict";var vD=le(),SD=oy().start,yD=ly();vD({target:"String",proto:!0,forced:yD},{padStart:function(e){return SD(this,e,arguments.length>1?arguments[1]:void 0)}})});var py=f((JH,dy)=>{"use strict";cy();var TD=Dt();dy.exports=TD("String","padStart")});var my=f((ZH,hy)=>{"use strict";var ID=py();hy.exports=ID});var by=f((ej,fy)=>{"use strict";var ED=my();fy.exports=ED});var Id="2.0.131-dev.ba1a65a9.0";var Ce=(r=>(r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused",r))(Ce||{}),ft=(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))(ft||{});var gs=(r=>(r.NOT_AVAILABLE="NOT_AVAILABLE",r.AVAILABLE="AVAILABLE",r.CONNECTING="CONNECTING",r.CONNECTED="CONNECTED",r))(gs||{}),oo=(i=>(i.HTTP1="http1",i.HTTP2="http2",i.QUIC="quic",i))(oo||{});var uo=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(uo||{}),vs=(i=>(i.TRAFFIC_SAVING="traffic_saving",i.HIGH_QUALITY="high_quality",i.UNKNOWN="unknown",i))(vs||{});var XT=O(qe(),1);import{assertNever as yh,assertNonNullable as Dx,isNonNullable as Es,ValueSubject as qo,Subject as Cx,Subscription as Vx,merge as Ox,observableFrom as Bx,fromEvent as bh,map as gh,tap as vh,filterChanged as _x,isNullable as Uo,ErrorCategory as Sh}from"@vkontakte/videoplayer-shared/es2015";var fh=a=>new Promise((e,t)=>{let i=document.createElement("script");i.setAttribute("src",a),i.onload=()=>e(),i.onerror=r=>t(r),document.body.appendChild(i)});var xs=class{constructor(e){this.connection$=new qo(void 0);this.castState$=new qo("NOT_AVAILABLE");this.errorEvent$=new Cx;this.realCastState$=new qo("NOT_AVAILABLE");this.subscription=new Vx;this.isDestroyed=!1;var s;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastInitializer");let t="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${t}`}),e.isDisabled||!t)return;let i=Es((s=window.chrome)==null?void 0:s.cast),r=!!window.__onGCastApiAvailable;i?this.initializeCastApi():(window.__onGCastApiAvailable=n=>{delete window.__onGCastApiAvailable,n&&!this.isDestroyed&&this.initializeCastApi()},r||fh("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:Sh.NETWORK,message:"Script loading failed!"})))}connect(){var e;(e=cast.framework.CastContext.getInstance())==null||e.requestSession()}disconnect(){var e,t;(t=(e=cast.framework.CastContext.getInstance())==null?void 0:e.getCurrentSession())==null||t.endSession(!0)}stopMedia(){return new Promise((e,t)=>{var i,r,s;(s=(r=(i=cast.framework.CastContext.getInstance())==null?void 0:i.getCurrentSession())==null?void 0:r.getMediaSession())==null||s.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){Es(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();Uo(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();Uo(t)||e!==t.remotePlayer.isMuted&&t.remotePlayerController.muteOrUnmute()}destroy(){this.isDestroyed=!0,this.subscription.unsubscribe()}initListeners(){let e=new cast.framework.RemotePlayer,t=new cast.framework.RemotePlayerController(e),i=cast.framework.CastContext.getInstance();this.subscription.add(bh(i,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(r=>{var s,n,o;switch(r.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=(o=(n=(s=i.getCurrentSession())==null?void 0:s.getMediaSession())==null?void 0:n.media)==null?void 0:o.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return yh(r.sessionState)}})).add(Ox(bh(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(vh(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),gh(r=>r.castState)),Bx([i.getCastState()])).pipe(_x(),gh(Nx),vh(r=>{this.log({message:`realCastState$: ${r}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{var o,u;let s=r==="CONNECTED",n=Es(this.connection$.getValue());if(s&&!n){let l=i.getCurrentSession();Dx(l);let c=l.getCastDevice(),d=(u=(o=l.getMediaSession())==null?void 0:o.media)==null?void 0:u.contentId;(Uo(d)||d===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:l,castDevice:c}))}else!s&&n&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(r==="CONNECTED"?Es(this.connection$.getValue())?"CONNECTED":"AVAILABLE":r)}))}initializeCastApi(){var r;let e,t,i;try{e=cast.framework.CastContext.getInstance(),t=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,i=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch(s){return}try{e.setOptions({receiverApplicationId:(r=this.params.receiverApplicationId)!=null?r:t,autoJoinPolicy:i}),this.initListeners()}catch(s){this.errorEvent$.next({id:"ChromecastInitializer",category:Sh.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:s})}}},Nx=a=>{switch(a){case cast.framework.CastState.NO_DEVICES_AVAILABLE:return"NOT_AVAILABLE";case cast.framework.CastState.NOT_CONNECTED:return"AVAILABLE";case cast.framework.CastState.CONNECTING:return"CONNECTING";case cast.framework.CastState.CONNECTED:return"CONNECTED";default:return yh(a)}};var wc=O(qe(),1),MT=O(_i(),1),DT=O(fu(),1);var xg=O(Js(),1);import{assertNever as fg}from"@vkontakte/videoplayer-shared/es2015";var ge=(a,e=0,t=0)=>{switch(t){case 0:return a.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case 1:{if(e===0)return a;let i=new URL(a);return i.searchParams.append("playback_shift",e.toFixed(0)),i.toString()}case 2:{let i=new URL(a);return!i.searchParams.get("offset_p")&&e===0?a:(i.searchParams.set("offset_p",e.toFixed(0)),i.toString())}default:fg(t)}return a},Zs=(a,e)=>{var t;switch(e){case 0:return NaN;case 1:{let i=new URL(a);return Number(i.searchParams.get("playback_shift"))}case 2:{let i=new URL(a);return Number((t=i.searchParams.get("offset_p"))!=null?t:0)}default:fg(e)}};var k=(a,e,t=!1)=>{let i=a.getTransition();(t||!i||i.to===e)&&a.setState(e)};import{isNonNullable as WR,Subject as en,merge as bg}from"@vkontakte/videoplayer-shared/es2015";var B=class{constructor(e){this.transitionStarted$=new en;this.transitionEnded$=new en;this.transitionUpdated$=new en;this.forceChanged$=new en;this.stateChangeStarted$=bg(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=bg(this.transitionEnded$,this.forceChanged$);this.state=e,this.prevState=void 0}setState(e){let t=this.transition,i=this.state;this.transition=void 0,this.prevState=i,this.state=e,t?t.to===e?this.transitionEnded$.next(t):this.forceChanged$.next({from:t.from,to:e,canceledTransition:t}):this.forceChanged$.next({from:i,to:e,canceledTransition:t})}startTransitionTo(e){let t=this.transition,i=this.state;i===e||WR(t)&&t.to===e||(this.prevState=i,this.state=e,t?(this.transition={from:t.from,to:e,canceledTransition:t},this.transitionUpdated$.next(this.transition)):(this.transition={from:i,to:e},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}getPrevState(){return this.prevState}};import{assertNever as YR}from"@vkontakte/videoplayer-shared/es2015";var gg=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 YR(a)}};import{assertNever as Yi,assertNonNullable as di,debounce as vg,ErrorCategory as Sg,fromEvent as pi,isNonNullable as yg,map as Tg,merge as Ig,observableFrom as zR,Subject as KR,Subscription as tl,timeout as XR,getHighestQuality as JR}from"@vkontakte/videoplayer-shared/es2015";var ZR=5,e$=5,t$=500,Eg=7e3,qr=class{constructor(e){this.subscription=new tl;this.loadMediaTimeoutSubscription=new tl;this.videoState=new B("stopped");this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(s)};`}),i==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.stop());return}if(!t){if((r==null?void 0:r.to)!=="paused"&&s.state==="requested"&&e!=="stopped"){this.seek(s.position/1e3);return}switch(i){case"ready":{switch(e){case"playing":case"paused":case"ready":break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:Yi(e)}break}case"playing":{switch(e){case"playing":break;case"paused":this.videoState.startTransitionTo("playing"),this.params.connection.remotePlayerController.playOrPause();break;case"ready":this.videoState.startTransitionTo("playing"),this.params.connection.remotePlayerController.playOrPause();break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:Yi(e)}break}case"paused":{switch(e){case"playing":this.videoState.startTransitionTo("paused"),this.params.connection.remotePlayerController.playOrPause();break;case"paused":break;case"ready":this.videoState.startTransitionTo("paused"),this.videoState.setState("paused");break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:Yi(e)}break}default:Yi(i)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(gg(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 tl;this.subscription.add(e),this.subscription.add(Ig(this.videoState.stateChangeStarted$.pipe(Tg(r=>`stateChangeStarted$ ${JSON.stringify(r)}`)),this.videoState.stateChangeEnded$.pipe(Tg(r=>`stateChangeEnded$ ${JSON.stringify(r)}`))).subscribe(r=>this.log({message:`[videoState] ${r}`})));let t=(r,s)=>this.subscription.add(r.subscribe(s));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{let r=new KR;e.add(r.pipe(vg(t$)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add(pi(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe(n=>{this.logRemoteEvent(n);let o=n.value;this.params.output.position$.next(o),(this.params.desiredState.seekState.getState().state==="applying"||Math.abs(o-s)>ZR)&&r.next(o),s=o})),e.add(pi(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(pi(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(pi(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemotePause():this.handleRemotePlay()}),t(pi(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),r=>{this.logRemoteEvent(r);let{remotePlayer:s}=this.params.connection,n=r.value,o=this.params.output.isBuffering$.getValue(),u=n===chrome.cast.media.PlayerState.BUFFERING;switch(o!==u&&this.params.output.isBuffering$.next(u),n){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&s.duration-s.currentTime<e$&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),k(this.params.desiredState.playbackState,"stopped");break;case chrome.cast.media.PlayerState.PAUSED:{this.handleRemotePause();break}case chrome.cast.media.PlayerState.PLAYING:this.handleRemotePlay();break;case chrome.cast.media.PlayerState.BUFFERING:break;default:Yi(n)}}),t(pi(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t(pi(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({muted:r.value})});let i=Ig(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,zR(["init"])).pipe(vg(0));t(i,this.syncPlayback)}restoreSession(e){this.log({message:"restoreSession"});let{remotePlayer:t}=this.params.connection;if(e.playerState!==chrome.cast.media.PlayerState.IDLE){t.isPaused?(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),k(this.params.desiredState.playbackState,"playing"));let i=this.params.output.isLive$.getValue();this.params.output.duration$.next(i?0:t.duration),this.params.output.position$.next(i?0:t.currentTime),this.params.desiredState.seekState.setState({state:"none"})}}prepare(){let e=this.params.format;this.log({message:`[prepare] format: ${e}`});let t=this.createMediaInfo(e),i=this.createLoadRequest(t);this.loadMedia(i)}handleRemotePause(){let e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)==="paused"||e==="playing")&&(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused"))}handleRemotePlay(){let e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)==="playing"||e==="paused")&&(this.videoState.setState("playing"),k(this.params.desiredState.playbackState,"playing"))}handleRemoteReady(){var t;let e=this.videoState.getTransition();(e==null?void 0:e.to)==="ready"&&this.videoState.setState("ready"),((t=this.params.desiredState.playbackState.getTransition())==null?void 0:t.to)==="ready"&&k(this.params.desiredState.playbackState,"ready")}handleRemoteStop(){this.videoState.getState()!=="stopped"&&this.videoState.setState("stopped")}handleRemoteVolumeChange(e){var r,s;let t=this.params.output.volume$.getValue(),i={volume:(r=e.volume)!=null?r:t.volume,muted:(s=e.muted)!=null?s:t.muted};(i.volume!==t.volume||i.muted!==i.muted)&&this.params.output.volume$.next(i)}seek(e){this.params.output.willSeekEvent$.next();let{remotePlayer:t,remotePlayerController:i}=this.params.connection;t.currentTime=e,i.seek()}stop(){let{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){var l;let t=this.params.source,i,r,s;switch(e){case"MPEG":{let c=t[e];di(c);let d=JR(Object.keys(c));di(d);let h=c[d];di(h),i=h,r="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let c=t[e];di(c),i=c.url,r="application/x-mpegurl",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":{let c=t[e];di(c),i=c.url,r="application/dash+xml",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let c=t[e];di(c),i=c.url,r="application/dash+xml",s=chrome.cast.media.StreamType.LIVE;break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let c=t[e];di(c),i=ge(c.url),r="application/x-mpegurl",s=chrome.cast.media.StreamType.LIVE;break}case"DASH_LIVE":case"WEB_RTC_LIVE":{let c="Unsupported format for Chromecast",d=new Error(c);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:Sg.VIDEO_PIPELINE,message:c,thrown:d}),d}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return Yi(e)}let n=new chrome.cast.media.MediaInfo((l=this.params.meta.videoId)!=null?l:i,r);n.contentUrl=i,n.streamType=s,n.metadata=new chrome.cast.media.GenericMediaMetadata;let{title:o,subtitle:u}=this.params.meta;return yg(o)&&(n.metadata.title=o),yg(u)&&(n.metadata.subtitle=u),n}createLoadRequest(e){let t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;let i=this.params.desiredState.seekState.getState();return i.state==="applying"||i.state==="requested"?t.currentTime=this.params.output.isLive$.getValue()?0:i.position/1e3:t.currentTime=0,t}loadMedia(e){let t=this.params.connection.session.loadMedia(e),i=new Promise((r,s)=>{this.loadMediaTimeoutSubscription.add(XR(Eg).subscribe(()=>s(`timeout(${Eg})`)))});(0,xg.default)(Promise.race([t,i]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},r=>{let s=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${r}`;this.log({message:s}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:Sg.VIDEO_PIPELINE,message:s,thrown:r})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var xl=O(qe(),1);import{clearVideoElement as wg}from"@vkontakte/videoplayer-shared/es2015";import{clearVideoElement as i$}from"@vkontakte/videoplayer-shared/es2015";var Pg=a=>{try{a.pause(),a.playbackRate=0,i$(a),a.remove()}catch(e){console.error(e)}};import{fromEvent as r$,Subscription as a$}from"@vkontakte/videoplayer-shared/es2015";var il=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 il,al=window.WeakMap?new WeakMap:new Map,s$=(a,e=20)=>{let t=0;return r$(a,"ratechange").subscribe(i=>{t++,t>=e&&(a.currentTime=a.currentTime,t=0)})},Ae=(a,{audioVideoSyncRate:e,disableYandexPiP:t})=>{let i=a.querySelector("video"),r=!!i;i?wg(i):(i=document.createElement("video"),a.appendChild(i)),rl.set(i,r);let s=new a$;return s.add(s$(i,e)),al.set(i,s),i.setAttribute("crossorigin","anonymous"),i.setAttribute("playsinline","playsinline"),t&&i.setAttribute("x-yandex-pip","false"),i.controls=!1,i.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),i},ke=a=>{let e=al.get(a);e==null||e.unsubscribe(),al.delete(a);let t=rl.get(a);rl.delete(a),t?wg(a):Pg(a)};var nl=O(zi(),1);import{assertNonNullable as Ur,isNonNullable as ut,isNullable as h$,fromEvent as Ki,merge as Dg,observableFrom as Cg,filterChanged as Vg,map as Hr,Subject as Og,Subscription as m$,ValueSubject as f$,ErrorCategory as b$}from"@vkontakte/videoplayer-shared/es2015";import{isNonNullable as sl,isNullable as d$,Subscription as p$}from"@vkontakte/videoplayer-shared/es2015";var tn=(a,e,t,{equal:i=(n,o)=>n===o,changed$:r,onError:s}={})=>{let n=a.getState(),o=e(),u=d$(r),l=new p$;return r&&l.add(r.subscribe(c=>{let d=a.getState();i(c,d)&&a.setState(c)},s)),i(o,n)||(t(n),u&&a.setState(n)),l.add(a.stateChangeStarted$.subscribe(c=>{t(c.to),u&&a.setState(c.to)},s)),l},ot=(a,e,t)=>tn(e,()=>a.loop,i=>{sl(i)&&(a.loop=i)},{onError:t}),Re=(a,e,t,i)=>tn(e,()=>({muted:a.muted,volume:a.volume}),r=>{sl(r)&&(a.muted=r.muted,a.volume=r.volume)},{equal:(r,s)=>r===s||(r==null?void 0:r.muted)===(s==null?void 0:s.muted)&&(r==null?void 0:r.volume)===(s==null?void 0:s.volume),changed$:t,onError:i}),Ue=(a,e,t,i)=>tn(e,()=>a.playbackRate,r=>{sl(r)&&(a.playbackRate=r)},{changed$:t,onError:i}),Vt=tn;var g$=a=>["__",a.language,a.label].join("|"),v$=(a,e)=>{if(a.id===e)return!0;let[t,i,r]=e.split("|");return a.language===i&&a.label===r},ol=class a{constructor(e){this.available$=new Og;this.current$=new f$(void 0);this.error$=new Og;this.subscription=new m$;this.externalTracks=new Map;this.internalTracks=new Map;this.baseURL=e}connect(e,t,i){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();let r=s=>{this.error$.next({id:"TextTracksManager",category:b$.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:s})};this.subscription.add(this.available$.subscribe(i.availableTextTracks$)),this.subscription.add(this.current$.subscribe(i.currentTextTrack$)),this.subscription.add(this.error$.subscribe(i.error$)),this.subscription.add(Vt(t.internalTextTracks,()=>(0,nl.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(Hr(s=>s.filter(({type:n})=>n==="internal"))),onError:r})),this.subscription.add(Vt(t.externalTextTracks,()=>(0,nl.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(Hr(s=>s.filter(({type:n})=>n==="external"))),onError:r})),this.subscription.add(Vt(t.currentTextTrack,()=>{if(this.video)return;let s=this.htmlTextTracksAsArray().find(({mode:n})=>n==="showing");return s&&this.htmlTextTrackToITextTrack(s).id},s=>this.select(s),{changed$:this.current$,onError:r})),this.subscription.add(Vt(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.activeCues)}))}subscribe(){Ur(this.video);let{textTracks:e}=this.video;this.subscription.add(Ki(e,"addtrack").subscribe(()=>{let i=this.current$.getValue();i&&this.select(i)})),this.subscription.add(Dg(Ki(e,"addtrack"),Ki(e,"removetrack"),Cg(["init"])).pipe(Hr(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),Vg((i,r)=>i.length===r.length&&i.every(({id:s},n)=>s===r[n].id))).subscribe(this.available$)),this.subscription.add(Dg(Ki(e,"change"),Cg(["init"])).pipe(Hr(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),Hr(i=>i&&this.htmlTextTrackToITextTrack(i).id),Vg()).subscribe(this.current$));let t=i=>{var r,s;return this.applyCueSettings((s=(r=i.target)==null?void 0:r.activeCues)!=null?s:null)};this.subscription.add(Ki(e,"addtrack").subscribe(i=>{var s,n;(s=i.track)==null||s.addEventListener("cuechange",t);let r=o=>{var l,c,d,h,p;let u=(c=(l=o.target)==null?void 0:l.cues)!=null?c:null;u&&u.length&&(this.applyCueSettings((h=(d=o.target)==null?void 0:d.cues)!=null?h:null),(p=o.target)==null||p.removeEventListener("cuechange",r))};(n=i.track)==null||n.addEventListener("cuechange",r)})),this.subscription.add(Ki(e,"removetrack").subscribe(i=>{var r;(r=i.track)==null||r.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;let t=this.cueSettings.getState();for(let i of Array.from(e)){let r=i;ut(t.align)&&(r.align=t.align),ut(t.position)&&(r.position=t.position),ut(t.size)&&(r.size=t.size),ut(t.line)&&(r.line=t.line)}}htmlTextTracksAsArray(e=!1){Ur(this.video);let t=[...this.video.textTracks];return e?t:t.filter(a.isHealthyTrack)}htmlTextTrackToITextTrack(e){var o,u,l,c,d;let{language:t,label:i}=e,r=e.id?e.id:g$(e),s=this.externalTracks.has(r),n=(l=s?(o=this.externalTracks.get(r))==null?void 0:o.isAuto:(u=this.internalTracks.get(r))==null?void 0:u.isAuto)!=null?l:r.includes("auto");return s?{id:r,type:"external",isAuto:n,language:t,label:i,url:(c=this.externalTracks.get(r))==null?void 0:c.url}:{id:r,type:"internal",isAuto:n,language:t,label:i,url:(d=this.internalTracks.get(r))==null?void 0:d.url}}static isHealthyTrack(e){return!(e.kind==="metadata"||e.groupId||e.id===""&&e.label===""&&e.language==="")}setExternal(e){this.internalTracks.size>0&&Array.from(this.internalTracks).forEach(([,t])=>this.detach(t)),e.filter(({id:t})=>!this.externalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.externalTracks).filter(([t])=>!e.find(i=>i.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){let t=[...this.externalTracks];e.filter(({id:i,language:r,isAuto:s})=>!this.internalTracks.has(i)&&!t.some(([,n])=>n.language===r&&n.isAuto===s)).forEach(i=>this.attach(i)),Array.from(this.internalTracks).filter(([i])=>!e.find(r=>r.id===i)).forEach(([,i])=>this.detach(i))}select(e){Ur(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(h$(e)||!v$(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){Ur(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){Ur(this.video);let t=Array.prototype.find.call(this.video.getElementsByTagName("track"),i=>i.getAttribute("id")===e.id);t&&this.video.removeChild(t),e.type==="external"?this.externalTracks.delete(e.id):e.type==="internal"&&this.internalTracks.delete(e.id)}},He=ol;var hi=class{constructor(){this.pausedTime=0;this.streamOffset=0;this.pauseTimestamp=0}getTotalPausedTime(){return this.pausedTime+this.getCurrentPausedTime()}getCurrentPausedTime(){return this.pauseTimestamp>0?Date.now()-this.pauseTimestamp:0}getStreamOffset(){return this.streamOffset}getTotalOffset(){return this.getTotalPausedTime()+this.streamOffset}pause(){this.pauseTimestamp===0&&(this.pauseTimestamp=Date.now())}resume(){this.pauseTimestamp>0&&(this.pausedTime+=this.getCurrentPausedTime(),this.pauseTimestamp=0)}resetTo(e,t=!1){this.streamOffset=e,this.pauseTimestamp=0,this.pausedTime=0,t&&this.pause()}};var Bg=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},ul=a=>{let e=Bg(a);return!!(e&&e.fullscreenElement&&e.fullscreenElement===a)},_g=a=>{let e=Bg(a);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===a)};import{fromEvent as $e,map as Ot,merge as cl,filterChanged as A$,isNonNullable as Wg,Subject as k$,filter as Qr,mapTo as dl,combine as R$,once as $$,throttle as L$,ErrorCategory as M$,ValueSubject as Yg,Subscription as D$}from"@vkontakte/videoplayer-shared/es2015";var S$=3,Ng=(a,e,t=S$)=>{let i=0,r=0;for(let s=0;s<a.length;s++){let n=a.start(s),o=a.end(s);if(n<=e&&e<=o){if(i=n,r=o,!t)return{from:i,to:r};for(let u=s-1;u>=0;u--)a.end(u)+t>=i&&(i=a.start(u));for(let u=s+1;u<a.length;u++)a.start(u)-t<=r&&(r=a.end(u))}}return{from:i,to:r}};var rn=class{get current(){return this._current}get isYandex(){return this.current==="Yandex"}get isSafari(){return this.current==="Safari"}get isSamsungBrowser(){return this.current==="SamsungBrowser"}get safariVersion(){return this._safariVersion}detect(){let{userAgent:e}=navigator;try{let t=/yabrowser/i.test(e)?"Yandex":void 0,i=/samsungbrowser/i.test(e)?"SamsungBrowser":void 0,r=/chrome|crios/i.test(e)?"Chrome":void 0,s=/chromium/i.test(e)?"Chromium":void 0,n=/firefox|fxios/i.test(e)?"Firefox":void 0,o=/webkit|safari|khtml/i.test(e)?"Safari":void 0,u=/opr\//i.test(e)?"Opera":void 0,l=/edg/i.test(e)?"Edge":void 0;this._current=t||i||n||u||l||r||s||o||"Rest"}catch(t){console.error(t)}this.isSafari&&this.detectSafariVersion()}detectSafariVersion(){try{let{userAgent:e}=window.navigator,t=e.match(/Version\/(\d+)/);if(!t)return;let i=t[1],r=parseInt(i,10);if(isNaN(r))return;this._safariVersion=r}catch(e){console.error(e)}}};var Fg=O(qe(),1);var jr=()=>{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 an=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,Fg.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=jr()}catch(t){console.error(t)}this.detectDevice(e),this.detectHighEntropyValues(),this.isIOS&&this.detectIOSVersion()}detectHighEntropyValues(){return E(this,null,function*(){let{userAgentData:e}=navigator;if(e){let t=yield e.getHighEntropyValues(["architecture","bitness","brands","mobile","platform","formFactor","model","platformVersion","wow64"]);this._highEntropyValues=t}})}detectDevice(e){try{let t=/android/i.test(e)?"Android":void 0,i=/iphone/i.test(e)?"iPhone":void 0,r=/ipad/i.test(e)?"iPad":void 0,s=/ipod/i.test(e)?"iPod":void 0,n=/mac/i.test(e)?"Mac":void 0,o=/webOS|BlackBerry|IEMobile|Opera Mini/i.test(e)?"RestMobile":void 0;this._current=t||i||r||s||o||n||"Desktop"}catch(t){console.error(t)}}detectIOSVersion(){try{if(this._highEntropyValues.platformVersion){let s=this._highEntropyValues.platformVersion.split(".").slice(0,2).join("."),n=parseFloat(s);this._iosVersion=n;return}let{userAgent:e}=window.navigator,t=e.match(/OS (\d+(_\d+)?)/i);if(!t)return;let i=t[1].replace(/_/g,".");if(!i)return;let r=parseFloat(i);if(isNaN(r))return;this._iosVersion=r}catch(e){console.error(e)}}};var sn=class{get isTouch(){return typeof this._maxTouchPoints=="number"?this._maxTouchPoints>1:"ontouchstart"in window}get maxTouchPoints(){return this._maxTouchPoints}get height(){return this._height}get width(){return this._width}get screenHeight(){return this._screenHeight}get screenWidth(){return this._screenWidth}get pixelRatio(){return this._pixelRatio}get isHDR(){return this._isHdr}get colorDepth(){return this._colorDepth}detect(){var t;let{maxTouchPoints:e}=navigator;try{this._maxTouchPoints=e!=null?e:0,this._isHdr=!!((t=matchMedia("(dynamic-range: high)"))!=null&&t.matches),this._colorDepth=screen.colorDepth}catch(i){console.error(i)}try{this._pixelRatio=window.devicePixelRatio||1,this._height=screen.height,this._width=screen.width,this._height=screen.height,this._screenHeight=this._height*this._pixelRatio,this._screenWidth=this._width*this._pixelRatio}catch(i){console.error(i)}}};var Je=()=>window.ManagedMediaSource||window.MediaSource,nn=()=>{var a,e;return!!(window.ManagedMediaSource&&((e=(a=window.ManagedSourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},qg=()=>{var a,e;return!!(window.MediaSource&&((e=(a=window.SourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},Ug=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;var y$=document.createElement("video"),T$='video/mp4; codecs="avc1.42000a,mp4a.40.2"',I$='video/mp4; codecs="hev1.1.6.L93.B0"',Hg='video/webm; codecs="vp09.00.10.08"',jg='video/webm; codecs="av01.0.00M.08"',E$='audio/mp4; codecs="mp4a.40.2"',x$='audio/webm; codecs="opus"',Qg,P$=()=>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(D(w({},a),{video:D(w({},a.video),{contentType:jg})})),window.navigator.mediaCapabilities.decodingInfo(D(w({},a),{video:D(w({},a.video),{contentType:Hg})}))]);Qg={DASH_WEBM_AV1:e,DASH_WEBM:t}});P$().catch(a=>{console.log(y$),console.error(a)});var on=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,i,r,s,n,o,u,l,c,d,h,p,m,b,g,v,S,y,I;this._video=document.createElement("video");try{this._protocols={mms:nn(),mse:qg(),hls:!!((t=(e=this._video).canPlayType)!=null&&t.call(e,"application/x-mpegurl")||(r=(i=this._video).canPlayType)!=null&&r.call(i,"vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},this._containers={mp4:!!((n=(s=this._video).canPlayType)!=null&&n.call(s,"video/mp4")),webm:!!((u=(o=this._video).canPlayType)!=null&&u.call(o,"video/webm")),cmaf:!0};let T=!!((c=(l=Je())==null?void 0:l.isTypeSupported)!=null&&c.call(l,T$)),$=!!((h=(d=Je())==null?void 0:d.isTypeSupported)!=null&&h.call(d,I$)),F=!!((m=(p=Je())==null?void 0:p.isTypeSupported)!=null&&m.call(p,E$));this._codecs={h264:T,h265:$,vp9:!!((g=(b=Je())==null?void 0:b.isTypeSupported)!=null&&g.call(b,Hg)),av1:!!((S=(v=Je())==null?void 0:v.isTypeSupported)!=null&&S.call(v,jg)),aac:F,opus:!!((I=(y=Je())==null?void 0:y.isTypeSupported)!=null&&I.call(y,x$)),mpeg:(T||$)&&F},this._nativeHlsSupported=this._protocols.hls&&this._containers.mp4}catch(T){console.error(T)}this.destroyVideoElement()}destroyVideoElement(){var t;if(!this._video)return;if(this._video.pause(),this._video.currentTime=0,this._video.removeAttribute("src"),this._video.src="",this._video.load(),this._video.remove){this._video.remove(),this._video=null;return}this._video.parentNode&&this._video.parentNode.removeChild(this._video);let e=this._video.cloneNode(!1);(t=this._video.parentNode)==null||t.replaceChild(e,this._video),this._video=null}};var Gg="audio/mpeg",un=class{supportMp3(){return this._codecs.mp3&&this._containers.mpeg}detect(){var e,t,i,r;this._audio=document.createElement("audio");try{this._containers={mpeg:!!((t=(e=this._audio).canPlayType)!=null&&t.call(e,Gg))},this._codecs={mp3:!!((r=(i=Je())==null?void 0:i.isTypeSupported)!=null&&r.call(i,Gg))}}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 w$}from"@vkontakte/videoplayer-shared/es2015";var ll=class{constructor(){this.isInited$=new w$(!1);this._displayChecker=new sn,this._deviceChecker=new an(this._displayChecker),this._browserChecker=new rn,this._videoChecker=new on(this._deviceChecker,this._browserChecker),this._audioChecker=new un,this.detect()}get display(){return this._displayChecker}get device(){return this._deviceChecker}get browser(){return this._browserChecker}get video(){return this._videoChecker}get audio(){return this._audioChecker}detect(){return E(this,null,function*(){this._displayChecker.detect(),this._deviceChecker.detect(),this._browserChecker.detect(),this._videoChecker.detect(),this._audioChecker.detect(),this.isInited$.next(!0)})}},U=new ll;var Le=a=>{let e=x=>$e(a,x).pipe(dl(void 0)),t=new D$,i=()=>t.unsubscribe(),s=cl(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(x=>$e(a,x))).pipe(Ot(x=>x.type==="ended"?a.readyState<2:a.readyState<3),A$()),n=cl($e(a,"progress"),$e(a,"timeupdate")).pipe(Ot(()=>Ng(a.buffered,a.currentTime))),o=U.browser.isSafari?R$({play:e("play").pipe($$()),playing:e("playing")}).pipe(dl(void 0)):e("playing"),u=$e(a,"volumechange").pipe(Ot(()=>({muted:a.muted,volume:a.volume}))),l=$e(a,"ratechange").pipe(Ot(()=>a.playbackRate)),c=$e(a,"error").pipe(Qr(()=>!!(a.error||a.played.length)),Ot(()=>{var H;let x=a.error;return{id:x?`MediaError#${x.code}`:"HtmlVideoError",category:M$.VIDEO_PIPELINE,message:x?x.message:"Error event from HTML video element",thrown:(H=a.error)!=null?H:void 0}})),d=$e(a,"timeupdate").pipe(Ot(()=>a.currentTime)),h=new k$,p=.3,m;t.add(d.subscribe(x=>{a.loop&&Wg(m)&&Wg(x)&&m>=a.duration-p&&x<=p&&h.next(m),m=x}));let b=e("pause").pipe(Qr(()=>!a.error&&m!==a.duration)),g=$e(a,"enterpictureinpicture"),v=$e(a,"leavepictureinpicture"),S=new Yg(_g(a));t.add(g.subscribe(()=>S.next(!0))),t.add(v.subscribe(()=>S.next(!1)));let y=new Yg(ul(a)),I=$e(a,"fullscreenchange");t.add(I.pipe(Ot(()=>ul(a))).subscribe(y));let T=.1,$=1e3,F=$e(a,"timeupdate").pipe(Qr(x=>a.duration-a.currentTime<T)),q=cl(F.pipe(Qr(x=>!a.loop)),$e(a,"ended")).pipe(L$($),dl(void 0)),K=F.pipe(Qr(x=>a.loop));return{playing$:o,pause$:b,canplay$:e("canplay"),ended$:q,looped$:h,loopExpected$:K,error$:c,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:d,durationChange$:$e(a,"durationchange").pipe(Ot(()=>a.duration)),isBuffering$:s,currentBuffer$:n,volumeState$:u,playbackRateState$:l,inPiP$:S,inFullscreen$:y,enterPip$:g,leavePip$:v,destroy:i}};import{VideoQuality as Bt}from"@vkontakte/videoplayer-shared/es2015";var _t=a=>{switch(a){case"mobile":return Bt.Q_144P;case"lowest":return Bt.Q_240P;case"low":return Bt.Q_360P;case"sd":case"medium":return Bt.Q_480P;case"hd":case"high":return Bt.Q_720P;case"fullhd":case"full":return Bt.Q_1080P;case"quadhd":case"quad":return Bt.Q_1440P;case"ultrahd":case"ultra":return Bt.Q_2160P}};var Ft=O(Nt(),1),cv=O(qe(),1),dn=O(_i(),1);import{isNonNullable as Ee,isNullable as nv,now as dv,isHigher as ov,isHigherOrEqual as fl,isInvariantQuality as uv,isLowerOrEqual as bl,videoSizeToQuality as j$,assertNotEmptyArray as pv,assertNonNullable as Q$}from"@vkontakte/videoplayer-shared/es2015";var pl=!1,St={},tv=a=>{pl=a},iv=()=>{St={}},rv=a=>{a(St)},Gr=(a,e)=>{var t;pl&&(St.meta=(t=St.meta)!=null?t:{},St.meta[a]=e)},Ie=class{constructor(e){this.name=e}next(e){var i,r;if(!pl)return;St.series=(i=St.series)!=null?i:{};let t=(r=St.series[this.name])!=null?r:[];t.push([Date.now(),e]),St.series[this.name]=t}};import{isHigher as U$,isHigherOrEqual as KN,isLower as av,isLowerOrEqual as XN,isNonNullable as ln,isNullable as H$,videoHeightToQuality as cn}from"@vkontakte/videoplayer-shared/es2015";function hl({limits:a,highQualityLimit:e,trafficSavingLimit:t}){return!a.max&&a.min===e?"high_quality":!a.min&&a.max===t?"traffic_saving":"unknown"}function ml({limits:a,highQualityLimit:e,trafficSavingLimit:t}){return!!a&&hl({limits:a,highQualityLimit:e,trafficSavingLimit:t})==="high_quality"}function Wr({limits:a,highestAvailableQuality:e,lowestAvailableQuality:t}){return H$(a)||ln(a.min)&&ln(a.max)&&av(a.max,a.min)||ln(a.min)&&e&&U$(a.min,e)||ln(a.max)&&t&&av(a.max,t)}function sv({limits:a,highestAvailableHeight:e,lowestAvailableHeight:t}){return Wr({limits:{max:a!=null&&a.max?cn(a.max):void 0,min:a!=null&&a.min?cn(a.min):void 0},highestAvailableQuality:e?cn(e):void 0,lowestAvailableQuality:t?cn(t):void 0})}var G$=new Ie("best_bitrate"),hv=(a,e,t)=>(e-t)*Math.pow(2,-10*a)+t;var gl=a=>(e,t)=>a*(Number(e.bitrate)-Number(t.bitrate)),Yr=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=dv()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},mv='Assertion "ABR Tracks is empty array" failed',pn=(a,e,t,i)=>{var u;let r=[...e].sort(gl(1)),s=[...t].sort(gl(1)),n=s.filter(l=>Ee(l.bitrate)&&Ee(a.bitrate)?a.bitrate/l.bitrate>i:!0),o=(u=(0,Ft.default)(s,Math.round(s.length*r.indexOf(a)/(r.length+1))))!=null?u:(0,Ft.default)(s,-1);return o&&(0,cv.default)(n,o)?o:n.length?(0,Ft.default)(n,-1):(0,Ft.default)(s,0)},lv=a=>"quality"in a,fv=(a,e,t,i)=>{var n;let r=Ee((n=i==null?void 0:i.last)==null?void 0:n.bitrate)&&Ee(t==null?void 0:t.bitrate)&&i.last.bitrate<t.bitrate?a.trackCooldownIncreaseQuality:a.trackCooldownDecreaseQuality,s=t&&i&&i.history[t.id]&&dv()-i.history[t.id]<=r&&(!i.last||t.id!==i.last.id);if(t!=null&&t.id&&i&&!s&&i.recordSelection(t),s&&(i!=null&&i.last)){let o=i.last;i==null||i.recordSwitch(o);let u=lv(o)?"video":"audio",l=lv(o)?o.quality:o.bitrate;return e({message:`
8
8
  [last ${u} selected] ${l}
9
- `}),o}return i==null||i.recordSwitch(t),t},Q$=(a,e)=>Math.log(e)/Math.log(a),G$=({tuning:a,container:e,limits:t,panelSize:i})=>{let r=a.containerSizeFactor;if(i)return{containerSizeLimit:i,containerSizeFactor:r};if(a.usePixelRatio&&U.display.pixelRatio){let s=U.display.pixelRatio;if(a.pixelRatioMultiplier)r*=a.pixelRatioMultiplier*(s-1)+1;else{let n=a.pixelRatioLogBase,[o=0,u=0,l=0]=a.pixelRatioLogCoefficients,c=Q$(n,o*s+u)+l;Number.isFinite(c)&&(r*=c)}}return pl({highQualityLimit:a.highQualityLimit,trafficSavingLimit:a.trafficSavingLimit,limits:t})&&(r*=2),{containerSizeLimit:a.limitByContainer&&e&&e.width>0&&e.height>0?{width:e.width*r,height:e.height*r}:void 0,containerSizeFactor:r}},qt=(a,{container:e,estimatedThroughput:t,tuning:i,limits:r,reserve:s=0,forwardBufferHealth:n,playbackRate:o,current:u,history:l,visible:c,droppedVideoMaxQualityLimit:d,stallsVideoMaxQualityLimit:h,stallsPredictedThroughput:p,abrLogger:m,panelSize:b})=>{var N,Z,R,C,X;lv(a,dv);let{containerSizeFactor:g,containerSizeLimit:v}=G$({container:e,tuning:i,limits:r,panelSize:b}),S=i.considerPlaybackRate&&Ee(o)?o:1,y=a.filter(P=>!sv(P.quality)).sort((P,M)=>av(P.quality,M.quality)?-1:1),I=(N=(0,Ft.default)(y,-1))==null?void 0:N.quality,T=(Z=(0,Ft.default)(y,0))==null?void 0:Z.quality,$=Gr({limits:r,lowestAvailableQuality:I,highestAvailableQuality:T}),F=S*cv(n!=null?n:.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),q={},x=y.filter(P=>{let M=!0;if(v)if(P.size)M=P.size.width<=v.width&&P.size.height<=v.height;else{let pt=v&&U$(v);M=pt?ml(P.quality,pt):!0}if(!M)return q[P.quality]="FitsContainer",!1;let me=p||t,Ti=Ee(me)&&isFinite(me)&&Ee(P.bitrate)?me-s>=P.bitrate*F:!0,dt=pl({highQualityLimit:i.highQualityLimit,trafficSavingLimit:i.trafficSavingLimit,limits:r})&&(r==null?void 0:r.min)===P.quality;if(!Ti&&!dt)return q[P.quality]="FitsThroughput",!1;if(i.lazyQualitySwitch&&Ee(i.minBufferToSwitchUp)&&u&&!sv(u.quality)&&(n!=null?n:0)<i.minBufferToSwitchUp&&av(P.quality,u.quality))return q[P.quality]="Buffer",!1;if(!!d&&hl(P.quality,d)&&!dt)return q[P.quality]="DroppedFramesLimit",!1;if(!!h&&hl(P.quality,h)&&!dt)return q[P.quality]="StallsLimit",!1;let we=$||(rv(r==null?void 0:r.max)||ml(P.quality,r.max))&&(rv(r==null?void 0:r.min)||hl(P.quality,r.min)),tt=Ee(c)&&!c?ml(P.quality,i.backgroundVideoQualityLimit):!0;return!we||!tt?(q[P.quality]="FitsQualityLimits",!1):!0})[0];x&&x.bitrate&&j$.next(x.bitrate);let j=(R=x!=null?x:(0,Ft.default)(y,-1))!=null?R:a[0],L=l==null?void 0:l.last,Q=pv(i,m,j,l);return Ee(l)&&Q.quality!==(L==null?void 0:L.quality)&&m({message:`
9
+ `}),o}return i==null||i.recordSwitch(t),t},W$=(a,e)=>Math.log(e)/Math.log(a),Y$=({tuning:a,container:e,limits:t,panelSize:i})=>{let r=a.containerSizeFactor;if(i)return{containerSizeLimit:i,containerSizeFactor:r};if(a.usePixelRatio&&U.display.pixelRatio){let s=U.display.pixelRatio;if(a.pixelRatioMultiplier)r*=a.pixelRatioMultiplier*(s-1)+1;else{let n=a.pixelRatioLogBase,[o=0,u=0,l=0]=a.pixelRatioLogCoefficients,c=W$(n,o*s+u)+l;Number.isFinite(c)&&(r*=c)}}return ml({highQualityLimit:a.highQualityLimit,trafficSavingLimit:a.trafficSavingLimit,limits:t})&&(r*=2),{containerSizeLimit:a.limitByContainer&&e&&e.width>0&&e.height>0?{width:e.width*r,height:e.height*r}:void 0,containerSizeFactor:r}},qt=(a,{container:e,estimatedThroughput:t,tuning:i,limits:r,reserve:s=0,forwardBufferHealth:n,playbackRate:o,current:u,history:l,visible:c,droppedVideoMaxQualityLimit:d,stallsVideoMaxQualityLimit:h,stallsPredictedThroughput:p,abrLogger:m,panelSize:b})=>{var N,Z,R,C,X;pv(a,mv);let{containerSizeFactor:g,containerSizeLimit:v}=Y$({container:e,tuning:i,limits:r,panelSize:b}),S=i.considerPlaybackRate&&Ee(o)?o:1,y=a.filter(P=>!uv(P.quality)).sort((P,M)=>ov(P.quality,M.quality)?-1:1),I=(N=(0,Ft.default)(y,-1))==null?void 0:N.quality,T=(Z=(0,Ft.default)(y,0))==null?void 0:Z.quality,$=Wr({limits:r,lowestAvailableQuality:I,highestAvailableQuality:T}),F=S*hv(n!=null?n:.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),q={},x=y.filter(P=>{let M=!0;if(v)if(P.size)M=P.size.width<=v.width&&P.size.height<=v.height;else{let ht=v&&j$(v);M=ht?bl(P.quality,ht):!0}if(!M)return q[P.quality]="FitsContainer",!1;let me=p||t,Ti=Ee(me)&&isFinite(me)&&Ee(P.bitrate)?me-s>=P.bitrate*F:!0,pt=ml({highQualityLimit:i.highQualityLimit,trafficSavingLimit:i.trafficSavingLimit,limits:r})&&(r==null?void 0:r.min)===P.quality;if(!Ti&&!pt)return q[P.quality]="FitsThroughput",!1;if(i.lazyQualitySwitch&&Ee(i.minBufferToSwitchUp)&&u&&!uv(u.quality)&&(n!=null?n:0)<i.minBufferToSwitchUp&&ov(P.quality,u.quality))return q[P.quality]="Buffer",!1;if(!!d&&fl(P.quality,d)&&!pt)return q[P.quality]="DroppedFramesLimit",!1;if(!!h&&fl(P.quality,h)&&!pt)return q[P.quality]="StallsLimit",!1;let we=$||(nv(r==null?void 0:r.max)||bl(P.quality,r.max))&&(nv(r==null?void 0:r.min)||fl(P.quality,r.min)),tt=Ee(c)&&!c?bl(P.quality,i.backgroundVideoQualityLimit):!0;return!we||!tt?(q[P.quality]="FitsQualityLimits",!1):!0})[0];x&&x.bitrate&&G$.next(x.bitrate);let H=(R=x!=null?x:(0,Ft.default)(y,-1))!=null?R:a[0],L=l==null?void 0:l.last,Q=fv(i,m,H,l);return Ee(l)&&Q.quality!==(L==null?void 0:L.quality)&&m({message:`
10
10
  [VIDEO TRACKS ABR]
11
11
  [available video tracks]
12
12
  ${a.map(P=>{var M,me;return`{ id: ${P.id}, quality: ${P.quality}, bitrate: ${P.bitrate}, size: ${(M=P.size)==null?void 0:M.width}:${(me=P.size)==null?void 0:me.height} }`}).join(`
13
13
  `)}
14
14
 
15
15
  [tuning]
16
- ${(0,ln.default)(i!=null?i:{}).map(([P,M])=>`${P}: ${M}`).join(`
16
+ ${(0,dn.default)(i!=null?i:{}).map(([P,M])=>`${P}: ${M}`).join(`
17
17
  `)}
18
18
 
19
19
  [limit params]
@@ -34,19 +34,19 @@ var iI=Object.create;var ro=Object.defineProperty,rI=Object.defineProperties,aI=
34
34
  minQualityLimit: ${r==null?void 0:r.min},
35
35
 
36
36
  [limited video tracks]
37
- ${(0,ln.default)(q).map(([P,M])=>`${P}: ${M}`).join(`
37
+ ${(0,dn.default)(q).map(([P,M])=>`${P}: ${M}`).join(`
38
38
  `)||"All tracks are available"}
39
39
 
40
40
  [best video track] ${x==null?void 0:x.quality}
41
41
  [selected video track] ${Q==null?void 0:Q.quality}
42
- `}),Q},hv=(a,e,t,{estimatedThroughput:i,tuning:r,playbackRate:s,forwardBufferHealth:n,history:o,abrLogger:u,stallsPredictedThroughput:l})=>{lv(t,dv);let c=r.considerPlaybackRate&&Ee(s)?s:1,d=[...t].sort(fl(-1)),h=a.bitrate;H$(h);let p=c*cv(n!=null?n:.5,r.bitrateAudioFactorAtEmptyBuffer,r.bitrateAudioFactorAtFullBuffer),m,b=cn(a,e,t,r.minVideoAudioRatio),g=l||i;Ee(g)&&isFinite(g)&&(m=d.find(y=>Ee(y.bitrate)&&Ee(b==null?void 0:b.bitrate)?g-h>=y.bitrate*p&&y.bitrate>=b.bitrate:!1)),m||(m=b);let v=o==null?void 0:o.last,S=m&&pv(r,u,m,o);return Ee(o)&&(S==null?void 0:S.bitrate)!==(v==null?void 0:v.bitrate)&&u({message:`
42
+ `}),Q},bv=(a,e,t,{estimatedThroughput:i,tuning:r,playbackRate:s,forwardBufferHealth:n,history:o,abrLogger:u,stallsPredictedThroughput:l})=>{pv(t,mv);let c=r.considerPlaybackRate&&Ee(s)?s:1,d=[...t].sort(gl(-1)),h=a.bitrate;Q$(h);let p=c*hv(n!=null?n:.5,r.bitrateAudioFactorAtEmptyBuffer,r.bitrateAudioFactorAtFullBuffer),m,b=pn(a,e,t,r.minVideoAudioRatio),g=l||i;Ee(g)&&isFinite(g)&&(m=d.find(y=>Ee(y.bitrate)&&Ee(b==null?void 0:b.bitrate)?g-h>=y.bitrate*p&&y.bitrate>=b.bitrate:!1)),m||(m=b);let v=o==null?void 0:o.last,S=m&&fv(r,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
45
  ${t.map(y=>`{ id: ${y.id}, bitrate: ${y.bitrate} }`).join(`
46
46
  `)}
47
47
 
48
48
  [tuning]
49
- ${(0,ln.default)(r!=null?r:{}).map(([y,I])=>`${y}: ${I}`).join(`
49
+ ${(0,dn.default)(r!=null?r:{}).map(([y,I])=>`${y}: ${I}`).join(`
50
50
  `)}
51
51
 
52
52
  [limit params]
@@ -60,14 +60,14 @@ var iI=Object.create;var ro=Object.defineProperty,rI=Object.defineProperties,aI=
60
60
  minBufferToSwitchUp: ${r.minBufferToSwitchUp},
61
61
 
62
62
  [selected audio track] ${S==null?void 0:S.id}
63
- `}),S};var de=a=>new URL(a).hostname;import{assertNever as xv,assertNonNullable as Pv,combine as hL,debounce as mL,ErrorCategory as wv,filter as kv,filterChanged as fL,isNonNullable as yl,map as fn,merge as Av,observableFrom as bL,once as gL,Subscription as vL,ValueSubject as Tl,videoQualityToHeight as Rv,videoSizeToQuality as SL}from"@vkontakte/videoplayer-shared/es2015";var yv=O(Nt(),1);var fv=O(qe(),1);var mv=a=>{if(a instanceof DOMException&&(0,fv.default)(["Failed to load because no supported source was found.","The element has no supported sources."],a.message))throw a;return!(a instanceof DOMException&&(a.code===20||a.name==="AbortError"))},Me=(a,e)=>E(void 0,null,function*(){let t=a.muted;try{yield a.play()}catch(i){if(!mv(i))return!1;if(e&&e(),t)return console.warn(i),!1;a.muted=!0;try{yield a.play()}catch(r){return mv(r)&&(a.muted=!1,console.warn(r)),!1}}return!0});import{isNonNullable as pn,isNullable as z$,assertNonNullable as Kr}from"@vkontakte/videoplayer-shared/es2015";var gv=O(zi(),1);import{isNonNullable as bv,assertNonNullable as dn,now as W$}from"@vkontakte/videoplayer-shared/es2015";function pe(){return W$()}function bl(a){return pe()-a}function gl(a){let e=a.split("/"),t=e.slice(0,e.length-1).join("/"),i=/^([a-z]+:)?\/\//i,r=n=>i.test(n);return{resolve:(n,o,u=!1)=>{r(n)||(n.startsWith("/")||(n="/"+n),n=t+n);let l=n.indexOf("?")>-1?"&":"?";return u&&(n+=l+"lowLat=1",l="&"),o&&(n+=l+"_rnd="+Math.floor(999999999*Math.random())),n}}}function vv(a,e,t){let i=(...r)=>{t.apply(null,r),a.removeEventListener(e,i)};a.addEventListener(e,i)}function Xi(a,e,t,i){let r=window.XMLHttpRequest,s,n,o,u=!1,l=0,c,d,h=!1,p="arraybuffer",m=7e3,b=2e3,g=()=>{if(u)return;dn(c);let L=bl(c),Q;if(L<b){Q=b-L,setTimeout(g,Q);return}b*=2,b>m&&(b=m),n&&n.abort(),n=new r,$()},v=L=>(s=L,j),S=L=>(d=L,j),y=()=>(p="json",j),I=()=>{if(!u){if(--l>=0){g(),i&&i();return}u=!0,d&&d(),t&&t()}},T=L=>(h=L,j),$=()=>{c=pe(),n=new r,n.open("get",a);let L=0,Q,N=0,Z=()=>(dn(c),Math.max(c,Math.max(Q||0,N||0)));if(s&&n.addEventListener("progress",R=>{let C=pe();s.updateChunk&&R.loaded>L&&(s.updateChunk(Z(),R.loaded-L),L=R.loaded,Q=C)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>I())),n.addEventListener("load",()=>{if(u)return;dn(n);let R=n.status;if(R>=200&&R<300){let{response:C,responseType:X}=n,P=C==null?void 0:C.byteLength;if(typeof P=="number"&&s){let M=P-L;M&&s.updateChunk&&s.updateChunk(Z(),M)}X==="json"&&(!C||!(0,gv.default)(C).length)?I():(d&&d(),e(C))}else I()}),n.addEventListener("error",()=>{I()}),h){let R=()=>{dn(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(N=pe(),n.removeEventListener("readystatechange",R))};n.addEventListener("readystatechange",R)}return n.responseType=p,n.send(),j},j={withBitrateReporting:v,withParallel:T,withJSONResponse:y,withRetryCount:L=>(l=L,j),withRetryInterval:(L,Q)=>(bv(L)&&(b=L),bv(Q)&&(m=Q),j),withTimeout:L=>(o=L,j),withFinally:S,send:$,abort:()=>{n&&(n.abort(),n=void 0),u=!0,d&&d()}};return j}var Yr=class{constructor(e){this.intervals=[];this.currentRate=0;this.logger=e}_updateRate(e){let t=.2;this.currentRate&&(e<this.currentRate*.1?t=.8:e<this.currentRate*.5?t=.5:e<this.currentRate*.7&&(t=.3)),e=Math.max(1,Math.min(e,100*1024*1024)),this.currentRate=this.currentRate?this.currentRate*(1-t)+e*t:e}_createInterval(e,t,i){return{start:e,end:t,bytes:i}}_doMergeIntervals(e,t){e.start=Math.min(t.start,e.start),e.end=Math.max(t.end,e.end),e.bytes+=t.bytes}_mergeIntervals(e,t){return e.start<=t.end&&t.start<=e.end?(this._doMergeIntervals(e,t),!0):!1}_flushIntervals(){if(!this.intervals.length)return!1;let e=this.intervals[0].start,t=this.intervals[this.intervals.length-1].end-500;if(t-e>2e3){let i=0,r=0;for(;this.intervals.length>0;){let s=this.intervals[0];if(s.end<=t)i+=s.end-s.start,r+=s.bytes,this.intervals.splice(0,1);else{if(s.start>=t)break;{let n=t-s.start,o=s.end-s.start;i+=n;let u=s.bytes*n/o;r+=u,s.start=t,s.bytes-=u}}}if(r>0&&i>0){let s=r*8/(i/1e3);return this._updateRate(s),this.logger(`rate updated, new=${Math.round(s/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(r)}/${Math.round(i)} interval=${Math.round(t-e)}`),!0}}return!1}_joinIntervals(){let e;do{e=!1;for(let t=0;t<this.intervals.length-1;++t)this._mergeIntervals(this.intervals[t],this.intervals[t+1])&&(this.intervals.splice(t+1,1),e=!0)}while(e)}addInterval(e,t,i){return this.intervals.push(this._createInterval(e,t,i)),this._joinIntervals(),this.intervals.length>100&&(this.logger(`too many intervals (${this.intervals.length}); will merge`,{type:"warn"}),this._doMergeIntervals(this.intervals[1],this.intervals[0]),this.intervals.splice(0,1)),this._flushIntervals()}getBitRate(){return this.currentRate}};var Sv=O(zi(),1);var zr=class{constructor(e,t,i,r,s){this.pendingQueue=[];this.activeRequests={};this.completeRequests={};this.averageSegmentDuration=2e3;this.lastPrefetchStart=0;this.throttleTimeout=null;this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=i,this.MAX_PARALLEL_REQUESTS=r,this.logger=s}limitCompleteCount(){let e;for(;(e=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){let t=e[Math.floor(Math.random()*e.length)];this.logger(`Dropping completed request for url ${t}`,{type:"warn"}),delete this.completeRequests[t]}}_sendRequest(e,t){let i=pe(),r=u=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=u,e._errorCB?e._errorCB(u):(this.limitCompleteCount(),this.completeRequests[t]=e)},s=u=>{e._complete=1,e._responseData=u,e._downloadTime=pe()-i,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(u,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},n=()=>{e._finallyCB&&e._finallyCB()},o=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=Xi(t,s,()=>r("error"),o),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally(n),this.activeRequests[t]=e,e._request.send(),this.lastPrefetchStart=pe()}_getParallelRequestCount(){return Math.min(this.MAX_PARALLEL_REQUESTS,this.averageSegmentDuration<3e3?3:2)}_getPrefetchDelay(){return Math.max(100,Math.min(5e3,this.averageSegmentDuration/3))}_canSendPending(){let e=this._getParallelRequestCount(),t=pe();if(Object.keys(this.activeRequests).length>=e)return!1;let i=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),i>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),i),!1):!0}_sendPending(){for(;this._canSendPending();){let e=this.pendingQueue.pop();if(e){if(this.activeRequests[e]||this.completeRequests[e])continue;this.logger(`Submitting pending request url=${e}`),this._sendRequest({},e)}else return}}_removeFromActive(e){delete this.completeRequests[e],delete this.activeRequests[e]}abortAll(){(0,Sv.default)(this.activeRequests).forEach(e=>{e&&e._request&&e._request.abort()}),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,i,r){let s={};return s.send=()=>{let n=this.activeRequests[e]||this.completeRequests[e];if(n)n._cb=t,n._errorCB=i,n._retryCB=r,n._finallyCB=s._finallyCB,n._error||n._complete?(this._removeFromActive(e),setTimeout(()=>{n._complete?(this.logger(`Requested url already prefetched, url=${e}`),t(n._responseData,n._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${e}`),i(n._errorMsg)),s._finallyCB&&s._finallyCB()},0)):this.logger(`Attached to active request, url=${e}`);else{let o=this.pendingQueue.indexOf(e);o!==-1&&this.pendingQueue.splice(o,1),this.logger(`Request not prefetched, starting new request, url=${e}${o===-1?"":"; removed pending"}`),this._sendRequest(s,e)}},s._cb=t,s._errorCB=i,s._retryCB=r,s.abort=function(){s.request&&s.request.abort()},s.withFinally=n=>(s._finallyCB=n,s),s}prefetch(e){this.activeRequests[e]||this.completeRequests[e]?this.logger(`Request already active for url=${e}`):(this.logger(`Added to pending queue; url=${e}`),this.pendingQueue.unshift(e),this._sendPending())}optimizeForSegDuration(e){this.averageSegmentDuration=e}};import{Subject as K$}from"@vkontakte/videoplayer-shared/es2015";var hn=1e4,vl=3;var X$=6e4,J$=10,Z$=1,eL=500,Xr=class{constructor(e){this.paused=!1;this.autoQuality=!0;this.autoQualityLimits=void 0;this.buffering=!0;this.destroyed=!1;this.videoPlayStarted=!1;this.lowLatency=!1;this.bitrate=0;this.manifest=[];this.sourceBuffer=0;this.bufferStates=[];this.sourceJitter=-1;this.params=e,this.soundProhibitedEvent$=new K$,this.chunkRateEstimator=new Yr(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=gl(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setAutoQualityLimits(e){this.autoQualityLimits=e}switchByName(e){let t;for(let i=0;i<this.manifest.length;++i)if(t=this.manifest[i],t.name===e){this._switchToQuality(t);return}}catchUp(){this.rep&&this.rep.stop(),this.currentManifestEntry&&(this.paused=!1,this._initPlayerWith(this.currentManifestEntry),this._notifyBuffering(!0))}stop(){this.params.videoElement.pause(),this.rep&&(this.rep.stop(),this.rep=null)}pause(){this.paused=!0,this.params.videoElement.pause(),this.videoPlayStarted=!1,this._notifyBuffering(!1)}play(){this.paused=!1;let e=this.lowLatency&&this._getBufferSizeSec()>this.sourceJitter+5;this.rep&&!e?(this.bufferStates=[],this.videoPlayStarted=!1,this.shouldPlay()?this._playVideoElement():this._notifyBuffering(!0)):this.catchUp()}startPlay(e,t){this.autoQuality=t,this._initPlayerWith(e)}destroy(){this.destroyed=!0,this.rep&&(this.rep.stop(),this.rep=null),this.manifestRequest&&this.manifestRequest.abort(),this.manifestRefetchTimer&&(clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=void 0)}reinit(e){this.manifestUrl=e,this.urlResolver=gl(e),this.catchUp()}_handleNetworkError(){this.params.logger("Fatal network error"),this.params.playerCallback({name:"error",type:"network"})}_retryCallback(){this.params.playerCallback({name:"retry"})}_getBufferSizeSec(){let e=this.params.videoElement,t=0,i=e.buffered.length;return i!==0&&(t=e.buffered.end(i-1)-Math.max(e.currentTime,e.buffered.start(0))),t}_notifyBuffering(e){this.destroyed||(this.params.logger(`buffering: ${e}`),this.params.playerCallback({name:"buffering",isBuffering:e}),this.buffering=e)}_initVideo(){let{videoElement:e,logger:t}=this.params;e.addEventListener("error",()=>{var r;!!e.error&&!this.destroyed&&(t(`Video element error: ${(r=e.error)==null?void 0:r.code}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{let i=this._getBufferSizeSec();!this.paused&&i<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(i+.1)*1e3)):this.buffering&&this.videoPlayStarted&&this._notifyBuffering(!1)}),e.addEventListener("playing",()=>{t("playing")}),e.addEventListener("stalled",()=>this._fixupStall()),e.addEventListener("waiting",()=>this._fixupStall())}_fixupStall(){let{logger:e,videoElement:t}=this.params,i=t.buffered.length,r;i!==0&&(r=t.buffered.start(i-1),t.currentTime<r&&(e("Fixup stall"),t.currentTime=r))}_selectQuality(e){let{videoElement:t}=this.params,i,r,s,n=t&&1.62*(U.display.pixelRatio||1)*t.offsetHeight||520;for(let o=0;o<this.manifest.length;++o){s=this.manifest[o];let{max:u,min:l}=this.autoQualityLimits||{};!iv({limits:this.autoQualityLimits,highestAvailableHeight:this.manifest[0].video.height,lowestAvailableHeight:(0,yv.default)(this.manifest,-1).video.height})&&(u&&s.video.height>u||l&&s.video.height<l)||(s.bitrate<e&&n>Math.min(s.video.height,s.video.width)?(!r||s.bitrate>r.bitrate)&&(r=s):(!i||i.bitrate>s.bitrate)&&(i=s))}return r||i}shouldPlay(){if(this.paused)return!1;let t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||pn(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){let{logger:i,videoElement:r,playerCallback:s}=this.params;this.mediaSource=new window.MediaSource,i("setting video src"),r.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.videoPlayStarted=!1,r.addEventListener("canplay",()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});let n=()=>{vv(r,"progress",()=>{r.buffered.length?(r.currentTime=r.buffered.start(0),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 zr(vl,hn,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){let{logger:t,videoElement:i,playerCallback:r}=this.params,s=!1,n=null,o=null,u=null,l=null,c=!1,d=()=>{let I=s&&(!c||c===this.rep);return I||t("Not running!"),I},h=(I,T,$)=>{u&&u.abort(),u=Xi(this.urlResolver.resolve(I,!1),T,$,()=>this._retryCallback()).withTimeout(hn).withBitrateReporting(this.bitrateSwitcher).withRetryCount(vl).withFinally(()=>{u=null}).send()},p=(I,T,$)=>{Kr(this.filesFetcher),o==null||o.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(I,!1),T,$,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},m=I=>{let T=i.playbackRate;i.playbackRate!==I&&(t(`Playback rate switch: ${T}=>${I}`),i.playbackRate=I)},b=I=>{this.lowLatency=I,t(`lowLatency changed to ${I}`),g()},g=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)m(1);else{let I=this._getBufferSizeSec();if(this.bufferStates.length<5){m(1);return}let $=pe()-1e4,F=0;for(let K=0;K<this.bufferStates.length;K++){let x=this.bufferStates[K];I=Math.min(I,x.buf),x.ts<$&&F++}this.bufferStates.splice(0,F),t(`update playback rate; minBuffer=${I} drop=${F} jitter=${this.sourceJitter}`);let q=I-Z$;this.sourceJitter>=0?q-=this.sourceJitter/2:this.sourceJitter-=1,q>3?m(1.15):q>1?m(1.1):q>.3?m(1.05):m(1)}},v=I=>{let T,$=()=>T&&T.start?T.start.length:0,F=R=>T.start[R]/1e3,q=R=>T.dur[R]/1e3,K=R=>T.fragIndex+R,x=(R,C)=>({chunkIdx:K(R),startTS:F(R),dur:q(R),discontinuity:C}),j=()=>{let R=0;if(T&&T.dur){let C=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,X=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,P=C;this.sourceJitter>1&&(P+=this.sourceJitter-1);let M=T.dur.length-1;for(;M>=0&&(P-=T.dur[M],!(P<=0));--M);R=Math.min(M,T.dur.length-1-X),R=Math.max(R,0)}return x(R,!0)},L=R=>{let C=$();if(!(C<=0)){if(pn(R)){for(let X=0;X<C;X++)if(F(X)>R)return x(X)}return j()}},Q=R=>{let C=$(),X=R?R.chunkIdx+1:0,P=X-T.fragIndex;if(!(C<=0)){if(!R||P<0||P-C>J$)return t(`Resync: offset=${P} bChunks=${C} chunk=`+JSON.stringify(R)),j();if(!(P>=C))return x(X-T.fragIndex,!1)}},N=(R,C,X)=>{l&&l.abort(),l=Xi(this.urlResolver.resolve(R,!0,this.lowLatency),C,X,()=>this._retryCallback()).withTimeout(hn).withRetryCount(vl).withFinally(()=>{l=null}).withJSONResponse().send()};return{seek:(R,C)=>{N(I,X=>{if(!d())return;T=X;let P=!!T.lowLatency;P!==this.lowLatency&&b(P);let M=0;for(let me=0;me<T.dur.length;++me)M+=T.dur[me];M>0&&(Kr(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(M/T.dur.length)),r({name:"index",zeroTime:T.zeroTime,shiftDuration:T.shiftDuration}),this.sourceJitter=T.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,T.jitter/1e3)):1,R(L(C))},()=>this._handleNetworkError())},nextChunk:Q}},S=()=>{s=!1,o&&o.abort(),u&&u.abort(),l&&l.abort(),Kr(this.filesFetcher),this.filesFetcher.abortAll()};return c={start:I=>{let{videoElement:T,logger:$}=this.params,F=v(e.jidxUrl),q,K,x,j,L=0,Q,N,Z,R=()=>{Q&&(clearTimeout(Q),Q=void 0);let Y=Math.max(eL,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),ye=L+Y,Pe=pe(),we=Math.min(1e4,ye-Pe);L=Pe;let tt=()=>{l||d()&&F.seek(()=>{d()&&(L=pe(),C(),R())})};we>0?Q=window.setTimeout(()=>{this.paused?R():tt()},we):tt()},C=()=>{let Y;for(;Y=F.nextChunk(j);)j=Y,Ti(Y);let ye=F.nextChunk(x);if(ye){if(x&&ye.discontinuity){$("Detected discontinuity; restarting playback"),this.paused?R():(S(),this._initPlayerWith(e));return}me(ye)}else R()},X=(Y,ye)=>{if(!d()||!this.sourceBuffer)return;let Pe,we,tt,pt=Pt=>{window.setTimeout(()=>{d()&&X(Y,ye)},Pt)};if(this.sourceBuffer.updating)$("Source buffer is updating; delaying appendBuffer"),pt(100);else{let Pt=pe(),zt=T.currentTime;!this.paused&&T.buffered.length>1&&N===zt&&Pt-Z>500&&($("Stall suspected; trying to fix"),this._fixupStall()),N!==zt&&(N=zt,Z=Pt);let Ii=this._getBufferSizeSec();if(Ii>30)$(`Buffered ${Ii} seconds; delaying appendBuffer`),pt(2e3);else try{this.sourceBuffer.appendBuffer(Y),this.videoPlayStarted?(this.bufferStates.push({ts:Pt,buf:Ii}),g(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),ye&&ye()}catch(cr){if(cr.name==="QuotaExceededError")$("QuotaExceededError; delaying appendBuffer"),tt=this.sourceBuffer.buffered.length,tt!==0&&(Pe=this.sourceBuffer.buffered.start(0),we=zt,we-Pe>4&&this.sourceBuffer.remove(Pe,we-3)),pt(1e3);else throw cr}}},P=()=>{K&&q&&($([`Appending chunk, sz=${K.byteLength}:`,JSON.stringify(x)]),X(K,function(){K=null,C()}))},M=Y=>e.fragUrlTemplate.replace("%%id%%",Y.chunkIdx),me=Y=>{d()&&p(M(Y),(ye,Pe)=>{if(d()){if(Pe/=1e3,K=ye,x=Y,n=Y.startTS,Pe){let we=Math.min(10,Y.dur/Pe);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*we:we}P()}},()=>this._handleNetworkError())},Ti=Y=>{d()&&(Kr(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(M(Y),!1)))},dt=Y=>{d()&&(e.cachedHeader=Y,X(Y,()=>{q=!0,P()}))};s=!0,F.seek(Y=>{if(d()){if(L=pe(),!Y){R();return}j=Y,!z$(I)||Y.startTS>I?me(Y):(x=Y,C())}},I),e.cachedHeader?dt(e.cachedHeader):h(e.headerUrl,dt,()=>this._handleNetworkError())},stop:S,getTimestampSec:()=>n},c}_switchToQuality(e){let{logger:t,playerCallback:i}=this.params,r;e.bitrate!==this.bitrate&&(this.rep&&(r=this.rep.getTimestampSec(),pn(r)&&(r+=.1),this.rep.stop()),this.currentManifestEntry=e,this.rep=this._representation(e),t(`switch to quality: codecs=${e.codecs}; headerUrl=${e.headerUrl}; bitrate=${e.bitrate}`),this.bitrate=e.bitrate,Kr(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(r),i({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return pn(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,i=d=>{if(!this.autoQuality)return;let h,p,m;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&d<this.bitrate&&(p=this._getBufferSizeSec(),m=d/this.bitrate,p>10&&m>.8||p>15&&m>.5||p>20&&m>.3)){e(`Not switching: buffer=${Math.floor(p)}; bitrate=${this.bitrate}; newRate=${Math.floor(d)}`);return}h=this._selectQuality(d),h?this._switchToQuality(h):e(`Could not find quality by bitrate ${d}`)},s={updateChunk:(h,p)=>{let m=pe();if(this.chunkRateEstimator.addInterval(h,m,p)){let g=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:p,duration:m-h,speed:g}),!0}},get:()=>{let h=this.chunkRateEstimator.getBitRate();return h?h*.85:0}},n=-1/0,o,u=!0,l=()=>{let d=s.get();if(d&&o&&this.autoQuality){if(u&&d>o&&bl(n)<3e4)return;i(d)}u=this.autoQuality};return{updateChunk:(d,h)=>{let p=s.updateChunk(d,h);return p&&l(),p},notifySwitch:d=>{let h=pe();d<o&&(n=h),o=d}}}_fetchManifest(e,t,i){this.manifestRequest=Xi(this.urlResolver.resolve(e,!0),t,i,()=>this._retryCallback()).withJSONResponse().withTimeout(hn).withRetryCount(this.params.config.manifestRetryMaxCount).withRetryInterval(this.params.config.manifestRetryInterval,this.params.config.manifestRetryMaxInterval).send().withFinally(()=>{this.manifestRequest=void 0})}_playVideoElement(){let{videoElement:e}=this.params;Me(e,()=>{this.soundProhibitedEvent$.next()}).then(t=>{t||(this.params.liveOffset.pause(),this.params.videoState.setState("paused"))})}_handleManifestUpdate(e){let{logger:t,playerCallback:i,videoElement:r}=this.params,s=n=>{let o=[];return n!=null&&n.length?(n.forEach((u,l)=>{var c,d;u.video&&r.canPlayType(u.codecs).replace(/no/,"")&&((d=(c=window.MediaSource)==null?void 0:c.isTypeSupported)!=null&&d.call(c,u.codecs))&&(u.index=l,o.push(u))}),o.sort(function(u,l){return u.video&&l.video?l.video.height-u.video.height:l.bitrate-u.bitrate}),o):(i({name:"error",type:"empty_manifest"}),[])};this.manifest=s(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),i({name:"manifest",manifest:this.manifest})}_refetchManifest(e){this.destroyed||(this.manifestRefetchTimer&&clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=window.setTimeout(()=>{this._fetchManifest(e,t=>{this.destroyed||(this._handleManifestUpdate(t),this._refetchManifest(e))},()=>this._refetchManifest(e))},X$))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};var Ev=O(Bi(),1);import{debounce as tL,filter as Tv,fromEvent as iL,interval as rL,isHigher as aL,isInvariantQuality as sL,isLower as nL,merge as oL,Subject as Iv,Subscription as uL}from"@vkontakte/videoplayer-shared/es2015";var Sl=class{constructor(){this.onDroopedVideoFramesLimit$=new Iv;this.subscription=new uL;this.playing=!1;this.tracks=[];this.forceChecker$=new Iv;this.isForceCheckCounter=0;this.prevTotalVideoFrames=0;this.prevDroppedVideoFrames=0;this.limitCounts={};this.handleChangeVideoQuality=()=>{let e=this.tracks.find(({size:t})=>(t==null?void 0:t.height)===this.video.videoHeight&&(t==null?void 0:t.width)===this.video.videoWidth);e&&!sL(e.quality)&&this.onChangeQuality(e.quality)};this.checkDroppedFrames=()=>{var n;let{totalVideoFrames:e,droppedVideoFrames:t}=this.video.getVideoPlaybackQuality(),i=e-this.prevTotalVideoFrames,r=t-this.prevDroppedVideoFrames,s=1-(i-r)/i;!isNaN(s)&&s>0&&this.log({message:`[dropped]. current dropped percent: ${s}, limit: ${this.droppedFramesChecker.percentLimit}`}),!isNaN(s)&&s>=this.droppedFramesChecker.percentLimit&&aL(this.currentQuality,this.droppedFramesChecker.minQualityBanLimit)&&(this.limitCounts[this.currentQuality]=((n=this.limitCounts[this.currentQuality])!=null?n:0)+1,this.maxQualityLimit=this.getMaxQualityLimit(this.currentQuality),this.currentTimer&&window.clearTimeout(this.currentTimer),this.currentTimer=window.setTimeout(()=>this.maxQualityLimit=this.getMaxQualityLimit(),this.droppedFramesChecker.qualityUpWaitingTime),this.onDroopedVideoFramesLimitTrigger()),this.savePrevFrameCounts(e,t)}}connect(e){this.log=e.logger.createComponentLog("DroppedFramesManager"),this.video=e.video,this.isAuto=e.isAuto,this.tracks=e.tracks,this.droppedFramesChecker=e.droppedFramesChecker,this.subscription.add(e.playing$.subscribe(()=>this.playing=!0)),this.subscription.add(e.pause$.subscribe(()=>this.playing=!1)),this.isEnabled&&this.subscribe()}destroy(){this.currentTimer&&window.clearTimeout(this.currentTimer),this.subscription.unsubscribe()}get droppedVideoMaxQualityLimit(){return this.maxQualityLimit}subscribe(){this.subscription.add(iL(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=rL(this.droppedFramesChecker.checkTime).pipe(Tv(()=>this.playing),Tv(()=>{let r=!!this.isForceCheckCounter;return r&&(this.isForceCheckCounter-=1),!r})),t=this.forceChecker$.pipe(tL(this.droppedFramesChecker.checkTime)),i=oL(e,t);this.subscription.add(i.subscribe(this.checkDroppedFrames))}onChangeQuality(e){this.currentQuality=e;let{totalVideoFrames:t,droppedVideoFrames:i}=this.video.getVideoPlaybackQuality();this.savePrevFrameCounts(t,i),this.isForceCheckCounter=this.droppedFramesChecker.tickCountAfterQualityChange,this.forceChecker$.next()}onDroopedVideoFramesLimitTrigger(){this.isAuto.getState()&&(this.log({message:`[onDroopedVideoFramesLimit]. maxQualityLimit: ${this.maxQualityLimit}`}),this.onDroopedVideoFramesLimit$.next())}getMaxQualityLimit(e){var i,r;let t=(r=(i=(0,Ev.default)(this.limitCounts).filter(([,s])=>s>=this.droppedFramesChecker.countLimit).sort(([s],[n])=>nL(s,n)?-1:1))==null?void 0:i[0])==null?void 0:r[0];return e!=null?e:t}get isEnabled(){return this.droppedFramesChecker.enabled&&this.isDroppedFramesCheckerSupport}get isDroppedFramesCheckerSupport(){return!!this.video&&typeof this.video.getVideoPlaybackQuality=="function"}savePrevFrameCounts(e,t){this.prevTotalVideoFrames=e,this.prevDroppedVideoFrames=t}},mn=Sl;import{map as lL,Observable as cL}from"@vkontakte/videoplayer-shared/es2015";import{fromEvent as dL}from"@vkontakte/videoplayer-shared/es2015";var Jr=()=>{var a;return!!((a=window.documentPictureInPicture)!=null&&a.window)||!!document.pictureInPictureElement};var pL=(a,e)=>new cL(t=>{if(!window.IntersectionObserver)return;let i={root:null},r=new IntersectionObserver((n,o)=>{n.forEach(u=>t.next(u.isIntersecting||Jr()))},w(w({},i),e));r.observe(a);let s=dL(document,"visibilitychange").pipe(lL(n=>!document.hidden||Jr())).subscribe(n=>t.next(n));return()=>{r.unobserve(a),s.unsubscribe()}}),je=pL;var yL=["paused","playing","ready"],TL=["paused","playing","ready"],Zr=class{constructor(e){this.subscription=new vL;this.videoState=new _("stopped");this.representations$=new Tl([]);this.droppedFramesManager=new mn;this.maxSeekBackTime$=new Tl(1/0);this.zeroTime$=new Tl(void 0);this.liveOffset=new hi;this._dashCb=e=>{var t,i,r,s;switch(e.name){case"buffering":{let n=e.isBuffering;this.params.output.isBuffering$.next(n);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${e.type}`,category:wv.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{let n=e.manifest,o=[];for(let u of n){let l=(t=u.name)!=null?t:u.index.toString(10),c=(i=Bt(u.name))!=null?i:SL(u.video),d=u.bitrate/1e3,h=w({},u.video);if(!c)continue;let p={id:l,quality:c,bitrate:d,size:h};o.push({track:p,representation:u})}this.representations$.next(o),this.params.output.availableVideoTracks$.next(o.map(({track:u})=>u)),((r=this.videoState.getTransition())==null?void 0:r.to)==="manifest_ready"&&this.videoState.setState("manifest_ready");break}case"qualitySwitch":{let n=e.quality,o=(s=this.representations$.getValue().find(({representation:u})=>u===n))==null?void 0:s.track;this.params.output.hostname$.next(new URL(n.headerUrl,this.params.source.url).hostname),yl(o)&&this.params.output.currentVideoTrack$.next(o);break}case"bandwidth":{let{size:n,duration:o}=e;this.params.dependencies.throughputEstimator.addRawSpeed(n,o);break}case"index":{this.maxSeekBackTime$.next(e.shiftDuration||0),this.zeroTime$.next(e.zeroTime);break}}};this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; seekState: ${JSON.stringify(s)};`}),i==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState("stopped"));return}if(t)return;let n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.autoVideoTrackSwitching.getTransition();if((0,Il.default)(TL,e)&&(n||o)){this.prepare();return}if((r==null?void 0:r.to)!=="paused"&&s.state==="requested"&&(0,Il.default)(yL,e)){this.seek(s.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(ge(this.params.source.url));return;case"manifest_ready":this.videoState.startTransitionTo("ready"),this.prepare();break;case"ready":if(i==="paused")this.videoState.setState("paused");else if(i==="playing"){this.videoState.startTransitionTo("playing");let u=r==null?void 0:r.from;u&&u==="ready"&&this.dash.catchUp(),this.dash.play()}return;case"playing":i==="paused"&&(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.dash.pause());return;case"paused":if(i==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.dash.play(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let u=this.liveOffset.getTotalOffset();u>=this.maxSeekBackTime$.getValue()&&(u=0,this.liveOffset.resetTo(u)),this.liveOffset.resume(),this.params.output.position$.next(-u/1e3),this.dash.reinit(ge(this.params.source.url,u))}return;default:return xv(e)}};this.textTracksManager=new He(e.source.url),this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=r=>{e.output.error$.next({id:"DashLiveProvider",category:wv.WTF,message:"DashLiveProvider internal logic error",thrown:r})};this.subscription.add(Av(this.videoState.stateChangeStarted$.pipe(fn(r=>({transition:r,type:"start"}))),this.videoState.stateChangeEnded$.pipe(fn(r=>({transition:r,type:"end"})))).subscribe(({transition:r,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(r)}`})})),this.video=ke(e.container,e.tuning),this.params.output.element$.next(this.video),this.dash=this.createLiveDashPlayer(),this.subscription.add(this.dash.soundProhibitedEvent$.subscribe(this.params.output.soundProhibitedEvent$)),this.params.output.duration$.next(1/0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(de(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);let i=Le(this.video);this.subscription.add(()=>i.destroy()),this.subscription.add(this.representations$.pipe(fn(r=>r.map(({track:s})=>s)),kv(r=>!!r.length),gL()).subscribe(r=>this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks:r}))),this.subscription.add(i.canplay$.subscribe(()=>{var r;((r=this.videoState.getTransition())==null?void 0:r.to)==="ready"&&this.videoState.setState("ready")},t)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused")},t)).add(i.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.videoState.setState("playing")},t)).add(i.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(fL(),fn(r=>-r/1e3)).subscribe(this.params.output.duration$)).add(hL({zeroTime:this.zeroTime$.pipe(kv(yl)),position:i.timeUpdate$}).subscribe(({zeroTime:r,position:s})=>this.params.output.liveTime$.next(r+s*1e3),t)).add(ot(this.video,this.params.desiredState.isLooped,t)).add(Re(this.video,this.params.desiredState.volume,i.volumeState$,t)).add(i.volumeState$.subscribe(this.params.output.volume$,t)).add(Ue(this.video,this.params.desiredState.playbackRate,i.playbackRateState$,t)).add(i.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(i.loadedMetadata$.subscribe(this.params.output.loadedMetadataEvent$)).add(i.playing$.subscribe(this.params.output.firstFrameEvent$)).add(i.canplay$.subscribe(this.params.output.canplay$)).add(i.inPiP$.subscribe(this.params.output.inPiP$)).add(i.inFullscreen$.subscribe(this.params.output.inFullscreen$)).add(je(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:r,min:s}})=>{this.dash.setAutoQualityLimits({max:r&&Rv(r),min:s&&Rv(s)}),this.params.output.autoVideoTrackLimits$.next({max:r,min:s})})).add(this.videoState.stateChangeEnded$.subscribe(r=>{var s;switch(r.to){case"stopped":this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState("stopped");break;case"manifest_ready":case"ready":((s=this.params.desiredState.playbackState.getTransition())==null?void 0:s.to)==="ready"&&this.params.desiredState.playbackState.setState("ready");break;case"paused":this.params.desiredState.playbackState.setState("paused");break;case"playing":this.params.desiredState.playbackState.setState("playing");break;default:return xv(r.to)}},t)).add(Av(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,bL(["init"])).pipe(mL(0)).subscribe(this.syncPlayback,t))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.droppedFramesManager.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),Ae(this.video)}createLiveDashPlayer(){let e=new Xr({videoElement:this.video,videoState:this.videoState,liveOffset:this.liveOffset,config:{maxParallelRequests:this.params.config.maxParallelRequests,minBuffer:this.params.tuning.live.minBuffer,minBufferSegments:this.params.tuning.live.minBufferSegments,lowLatencyMinBuffer:this.params.tuning.live.lowLatencyMinBuffer,lowLatencyMinBufferSegments:this.params.tuning.live.lowLatencyMinBufferSegments,isLiveCatchUpMode:this.params.tuning.live.isLiveCatchUpMode,manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},playerCallback:this._dashCb,logger:t=>{this.params.dependencies.logger.log({message:String(t),component:"LiveDashPlayer"})}});return e.pause(),e}prepare(){var l,c,d,h,p,m;let e=this.representations$.getValue(),t=(c=(l=this.params.desiredState.videoTrack.getTransition())==null?void 0:l.to)!=null?c:this.params.desiredState.videoTrack.getState(),i=(h=(d=this.params.desiredState.autoVideoTrackSwitching.getTransition())==null?void 0:d.to)!=null?h:this.params.desiredState.autoVideoTrackSwitching.getState(),r=!i&&yl(t)?t:qt(e.map(({track:b})=>b),{container:this.video.getBoundingClientRect(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),s=r==null?void 0:r.id,n=this.params.desiredState.videoTrack.getTransition(),o=(p=this.params.desiredState.videoTrack.getState())==null?void 0:p.id,u=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(r&&(n||s!==o)&&this.setVideoTrack(r),u&&this.setAutoQuality(i),n||u||s!==o){let b=(m=e.find(({track:g})=>g.id===s))==null?void 0:m.representation;Pv(b,"Representations missing"),this.dash.startPlay(b,i)}}setVideoTrack(e){var i;let t=(i=this.representations$.getValue().find(({track:r})=>r.id===e.id))==null?void 0:i.representation;Pv(t,`No such representation ${e.id}`),this.dash.switchByName(t.name),this.params.desiredState.videoTrack.setState(e)}setAutoQuality(e){this.dash.setAutoQualityEnabled(e),this.params.desiredState.autoVideoTrackSwitching.setState(e)}seek(e){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),i=this.videoState.getState(),r=t==="paused"&&i==="paused",s=-e,n=s<=this.maxSeekBackTime$.getValue()?s:0;this.params.output.position$.next(e/1e3),this.dash.reinit(ge(this.params.source.url,n)),r&&this.dash.pause(),this.liveOffset.resetTo(n,r)}};var $v=Zr;var Jy=O(qe(),1);var Ji=(a,e)=>{let t=0;for(let i=0;i<a.length;i++){let r=a.start(i)*1e3,s=a.end(i)*1e3;r<=e&&e<=s&&(t=s)}return Math.max(t-e,0)};import{assertNever as iC,assertNonNullable as rC,debounce as aC,ErrorCategory as zy,filter as lc,filterChanged as qa,fromEvent as sC,isNonNullable as Ky,map as cc,merge as On,observableFrom as dc,once as Xy,Subscription as nC}from"@vkontakte/videoplayer-shared/es2015";var bn=class{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,i){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:i})}removeEventListener(e,t){if(!(e in this.listeners))return;let i=this.listeners[e];for(let r=0,s=i.length;r<s;r++)if(i[r].callback===t){i.splice(r,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;let i=this.listeners[e.type].slice();for(let r=0,s=i.length;r<s;r++){let n=i[r];try{n.callback.call(this,e)}catch(o){Promise.resolve().then(()=>{throw o})}n.options&&n.options.once&&this.removeEventListener(e.type,n.callback)}return!e.defaultPrevented}},Zi=class extends bn{constructor(){super(),this.listeners||bn.call(this),Object.defineProperty(this,"aborted",{value:!1,writable:!0,configurable:!0}),Object.defineProperty(this,"onabort",{value:null,writable:!0,configurable:!0}),Object.defineProperty(this,"reason",{value:void 0,writable:!0,configurable:!0})}toString(){return"[object AbortSignal]"}dispatchEvent(e){e.type==="abort"&&(this.aborted=!0,typeof this.onabort=="function"&&this.onabort.call(this,e)),super.dispatchEvent(e)}},ea=class{constructor(){Object.defineProperty(this,"signal",{value:new Zi,writable:!0,configurable:!0})}abort(e){let t;try{t=new Event("abort")}catch(r){typeof document!="undefined"?document.createEvent?(t=document.createEvent("Event"),t.initEvent("abort",!1,!1)):(t=document.createEventObject(),t.type="abort"):t={type:"abort",bubbles:!1,cancelable:!1}}let i=e;if(i===void 0)if(typeof document=="undefined")i=new Error("This operation was aborted"),i.name="AbortError";else try{i=new DOMException("signal is aborted without reason")}catch(r){i=new Error("This operation was aborted"),i.name="AbortError"}this.signal.reason=i,this.signal.dispatchEvent(t)}toString(){return"[object AbortController]"}};typeof Symbol!="undefined"&&Symbol.toStringTag&&(ea.prototype[Symbol.toStringTag]="AbortController",Zi.prototype[Symbol.toStringTag]="AbortSignal");function gn(a){return a.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof a.Request=="function"&&!a.Request.prototype.hasOwnProperty("signal")||!a.AbortController}function El(a){typeof a=="function"&&(a={fetch:a});let{fetch:e,Request:t=e.Request,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r=!1}=a;if(!gn({fetch:e,Request:t,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r}))return{fetch:e,Request:s};let s=t;(s&&!s.prototype.hasOwnProperty("signal")||r)&&(s=function(l,c){let d;c&&c.signal&&(d=c.signal,delete c.signal);let h=new t(l,c);return d&&Object.defineProperty(h,"signal",{writable:!1,enumerable:!1,configurable:!0,value:d}),h},s.prototype=t.prototype);let n=e;return{fetch:(u,l)=>{let c=s&&s.prototype.isPrototypeOf(u)?u.signal:l?l.signal:void 0;if(c){let d;try{d=new DOMException("Aborted","AbortError")}catch(p){d=new Error("Aborted"),d.name="AbortError"}if(c.aborted)return Promise.reject(d);let h=new Promise((p,m)=>{c.addEventListener("abort",()=>m(d),{once:!0})});return l&&l.signal&&delete l.signal,Promise.race([h,n(u,l)])}return n(u,l)},Request:s}}var ta=gn({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),Lv=ta?El({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,lt=ta?Lv.fetch:window.fetch,kq=ta?Lv.Request:window.Request,ve=ta?ea:window.AbortController,Aq=ta?Zi:window.AbortSignal;var sc=O(Pl(),1);var gS=O(bS(),1);import{ErrorCategory as ra}from"@vkontakte/videoplayer-shared/es2015";var vS=a=>{if(!a)return{id:"EmptyResponse",category:ra.PARSER,message:"Empty response"};if(a.length<=2&&a.match(/^\d+$/))return{id:`UVError#${a}`,category:ra.NETWORK,message:`UV Error ${a}`};let e=(0,gS.default)(a).substring(0,100).toLowerCase();if(e.startsWith("<!doctype")||e.startsWith("<html>")||e.startsWith("<body>")||e.startsWith("<head>"))return{id:"UnexpectedHTML",category:ra.NETWORK,message:"Received unexpected HTML, possibly a ISP block"};if(e.startsWith("<?xml"))return new DOMParser().parseFromString(a,"text/xml").querySelector("parsererror")?{id:"InvalidXML",category:ra.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:ra.PARSER,message:"Response is valid XML, but parser failed"}};var Ut=(a,e,t=0)=>{for(let i=0;i<a.length;i++)if(a.start(i)*1e3-t<=e&&a.end(i)*1e3+t>e)return!0;return!1};import{abortable as ic,assertNonNullable as sr,combine as nr,ErrorCategory as ct,filter as Rn,filterChanged as Ba,flattenObject as Na,fromEvent as It,getTraceSubscriptionMethod as BD,interval as rc,isNonNullable as Fa,isNullable as Uy,map as or,merge as Si,now as ac,Subject as $n,Subscription as Hy,tap as ND,throttle as FD,ValueSubject as re}from"@vkontakte/videoplayer-shared/es2015";var Sn=O(qe(),1),rr=O(Nt(),1),yn=O(Pl(),1);var nM=(a,e={})=>{let i=e.timeout||1,r=performance.now();return window.setTimeout(()=>{a({get didTimeout(){return e.timeout?!1:performance.now()-r-1>i},timeRemaining(){return Math.max(0,1+(performance.now()-r))}})},1)},oM=a=>window.clearTimeout(a),SS=a=>typeof a=="function"&&(a==null?void 0:a.toString().endsWith("{ [native code] }")),yS=!SS(window.requestIdleCallback)||!SS(window.cancelIdleCallback),$l=yS?nM:window.requestIdleCallback,aa=yS?oM:window.cancelIdleCallback;var Ry=O(Ks(),1);import{assertNever as uM,ErrorCategory as TS,Subject as IS}from"@vkontakte/videoplayer-shared/es2015";var lM=18,ES=!1;try{ES=U.browser.isSafari&&!!U.browser.safariVersion&&U.browser.safariVersion<=lM}catch(a){console.error(a)}var Ll=class{constructor(e){this.bufferFull$=new IS;this.error$=new IS;this.queue=[];this.currentTask=null;this.destroyed=!1;this.abortRequested=!1;this.completeTask=()=>{var e;try{if(this.currentTask){let t=(e=this.currentTask.signal)==null?void 0:e.aborted;this.currentTask.callback(!t),this.currentTask=null}this.queue.length&&this.pull()}catch(t){this.error$.next({id:"BufferTaskQueueUnknown",category:TS.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:t})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}append(e,t){return E(this,null,function*(){return t&&t.aborted?!1:new Promise(i=>{let r={operation:"append",data:e,signal:t,callback:i};this.queue.push(r),this.pull()})})}remove(e,t,i){return E(this,null,function*(){return i&&i.aborted?!1:new Promise(r=>{let s={operation:"remove",from:e,to:t,signal:i,callback:r};this.queue.unshift(s),this.pull()})})}abort(e){return E(this,null,function*(){return new Promise(t=>{let i,r=s=>{this.abortRequested=!1,t(s)};ES&&e?i={operation:"safariAbort",init:e,callback:r}:i={operation:"abort",callback:r};for(let{callback:s}of this.queue)s(!1);this.abortRequested=!0,i&&(this.queue=[i]),this.pull()})})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){var r;if((this.buffer.updating||this.currentTask||this.destroyed)&&!this.abortRequested)return;let e=this.queue.shift();if(!e)return;if((r=e.signal)!=null&&r.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(s){s instanceof DOMException&&s.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):s instanceof DOMException&&s.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:TS.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:s}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){let{operation:t}=e;switch(t){case"append":this.buffer.appendBuffer(e.data);break;case"remove":this.buffer.remove(e.from/1e3,e.to/1e3);break;case"abort":this.buffer.abort();break;case"safariAbort":{this.buffer.abort(),this.buffer.appendBuffer(e.init);break}default:uM(t)}}},xS=Ll;var Ml=a=>{let e=0;for(let t=0;t<a.length;t++)e+=a.end(t)-a.start(t);return e*1e3};import{abortable as jt,assertNonNullable as De,ErrorCategory as Tt,fromEvent as zl,getExponentialDelay as Kl,isNonNullable as ir,isNullable as Se,now as vn,once as PD,Subject as wD,Subscription as kD,ValueSubject as bi}from"@vkontakte/videoplayer-shared/es2015";var G=class{constructor(e,t){this.cursor=0;this.source=e,this.boxParser=t,this.children=[];let i=this.readUint32();this.type=this.readString(4),this.size32=i<=e.buffer.byteLength-e.byteOffset?i:NaN;let r=this.size32?this.size32-8:void 0,s=e.byteOffset+this.cursor;this.size64=0,this.usertype=0,this.content=new DataView(e.buffer,s,r)}get id(){return this.type}get size(){return this.size32}scanForBoxes(e){return this.boxParser.parse(e)}readString(e,t="ascii"){let r=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,r}readUint8(){let e=this.source.getUint8(this.cursor);return this.cursor+=1,e}readUint16(){let e=this.source.getUint16(this.cursor);return this.cursor+=2,e}readUint32(){let e=this.source.getUint32(this.cursor);return this.cursor+=4,e}readUint64(){let e=this.source.getBigInt64(this.cursor);return this.cursor+=8,e}};var er=class extends G{};var sa=class extends G{constructor(t,i){super(t,i);this.ondemandPrefix="ondemandlivejson";this.ondemandDataReceivedKey="t-in";this.ondemandDataPreparedKey="t-out";let r=this.content.byteOffset,s=r+this.content.byteLength,n=new TextDecoder("ascii").decode(this.content.buffer.slice(r,s)).split(this.ondemandPrefix)[1],o=JSON.parse(n);this.serverDataReceivedTimestamp=o[this.ondemandDataReceivedKey],this.serverDataPreparedTime=o[this.ondemandDataPreparedKey]}};var na=class extends G{constructor(e,t){super(e,t),this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let i=this.size-this.cursor;for(;i;){let r=this.readString(4);this.compatibleBrands.push(r),i-=4}}};var oa=class extends G{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ie=class extends G{constructor(e,t){super(e,t);let i=this.readUint32();this.version=i>>>24,this.flags=i&16777215}};var ua=class extends ie{constructor(e,t){super(e,t),this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.timescale=this.readUint32(),this.duration=this.readUint32(),this.rate=this.readUint32(),this.volume=this.readUint16()}};var la=class extends G{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ca=class extends G{constructor(e,t){super(e,t),this.data=this.content}};var mi=class extends ie{get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e,t){super(e,t),this.segments=[],this.referenceId=this.readUint32(),this.timescale=this.readUint32(),this.earliestPresentationTime32=this.readUint32(),this.firstOffset32=this.readUint32(),this.earliestPresentationTime64=0,this.firstOffset64=0,this.referenceCount=this.readUint32()&65535;for(let i=0;i<this.referenceCount;i++){let r=this.readUint32(),s=r>>>31,n=r<<1>>>1,o=this.readUint32();r=this.readUint32();let u=r>>>28,l=r<<3>>>3;this.segments.push({referenceType:s,referencedSize:n,subsegmentDuration:o,SAPType:u,SAPDeltaTime:l})}}};var da=class extends G{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var pa=class extends G{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ha=class extends ie{constructor(e,t){switch(super(e,t),this.readUint8()){case 0:this.stereoMode=0;break;case 1:this.stereoMode=1;break;case 2:this.stereoMode=2;break;case 3:this.stereoMode=3;break;case 4:this.stereoMode=4;break}this.cursor+=1}};var ma=class extends ie{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var fa=class extends ie{constructor(e,t){super(e,t),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}};var ba=class extends G{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ga=class extends ie{constructor(e,t){super(e,t),this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.trackId=this.readUint32(),this.cursor+=4,this.duration=this.readUint32(),this.cursor+=8,this.layer=this.readUint16(),this.alternateGroup=this.readUint16(),this.cursor+=2,this.cursor+=2,this.matrix=[[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()]],this.width=this.readUint32(),this.height=this.readUint32()}};var va=class extends G{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Sa=class extends G{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ya=class extends ie{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var Ta=class extends G{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ia=class extends ie{constructor(e,t){super(e,t),this.trackId=this.readUint32(),this.flags&1&&(this.baseDataOffset=this.readUint64()),this.flags&2&&(this.sampleDescriptionIndex=this.readUint32()),this.flags&8&&(this.defaultSampleDuration=this.readUint32()),this.flags&16&&(this.defaultSampleSize=this.readUint32()),this.flags&32&&(this.defaultSampleFlags=this.readUint32())}};var Ea=class extends ie{constructor(t,i){super(t,i);this.baseMediaDecodeTime32=0;this.baseMediaDecodeTime64=BigInt(0);this.version===1?this.baseMediaDecodeTime64=this.readUint64():this.baseMediaDecodeTime32=this.readUint32()}get baseMediaDecodeTime(){return this.version===1?this.baseMediaDecodeTime64:this.baseMediaDecodeTime32}};var xa=class extends ie{constructor(t,i){super(t,i);this.sampleDuration=[];this.sampleSize=[];this.sampleFlags=[];this.sampleCompositionTimeOffset=[];this.optionalFields=0;this.sampleCount=this.readUint32(),this.flags&1&&(this.dataOffset=this.readUint32()),this.flags&4&&(this.firstSampleFlags=this.readUint32());for(let r=0;r<this.sampleCount;r++)this.flags&256&&this.sampleDuration.push(this.readUint32()),this.flags&512&&this.sampleSize.push(this.readUint32()),this.flags&1024&&this.sampleFlags.push(this.readUint32()),this.flags&2048&&this.sampleCompositionTimeOffset.push(this.readUint32())}};var Pa=class extends G{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var wa=class extends ie{constructor(e,t){super(e,t),this.entryCount=this.readUint32(),this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+8,this.content.byteLength-8))}};var ka=class extends G{constructor(e,t){super(e,t),this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+78,this.content.byteLength-78))}};var dM={ftyp:na,moov:oa,mvhd:ua,moof:la,mdat:ca,sidx:mi,trak:da,mdia:ba,mfhd:ya,tkhd:ga,traf:Ta,tfhd:Ia,tfdt:Ea,trun:xa,minf:va,sv3d:pa,st3d:ha,prhd:ma,proj:Sa,equi:fa,uuid:sa,stbl:Pa,stsd:wa,avc1:ka,unknown:er},St=class a{constructor(e={}){this.options=w({offset:0},e)}parse(e){let t=[],i=this.options.offset;for(;i<e.byteLength;)try{let s=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+i+4,4)),n=this.createBox(s,new DataView(e.buffer,e.byteOffset+i));if(!n.size)break;t.push(n),i+=n.size}catch(r){break}return t}createBox(e,t){let i=dM[e];return i?new i(t,new a):new er(t,new a)}};var Ht=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{var i,r,s;(s=(i=this.index)[r=t.type])!=null||(i[r]=[]),this.index[t.type].push(t),t.children.length>0&&this.indexBoxLevel(t.children)})}find(e){return this.index[e]&&this.index[e][0]?this.index[e][0]:null}findAll(e){return this.index[e]||[]}};var hM=new TextDecoder("ascii"),mM=a=>hM.decode(new DataView(a.buffer,a.byteOffset+4,4))==="ftyp",fM=a=>{let e=new mi(a,new St),t=e.earliestPresentationTime/e.timescale*1e3,i=a.byteOffset+a.byteLength+e.firstOffset;return e.segments.map(s=>{if(s.referenceType!==0)throw new Error("Unsupported multilevel sidx");let n=s.subsegmentDuration/e.timescale*1e3,o={status:"none",time:{from:t,to:t+n},byte:{from:i,to:i+s.referencedSize-1}};return t+=n,i+=s.referencedSize,o})},bM=(a,e)=>{let i=new St().parse(a),r=new Ht(i),s=r.findAll("moof"),n=e?r.findAll("uuid"):r.findAll("mdat");if(!(n.length&&s.length))return null;let o=s[0],u=n[n.length-1],l=o.source.byteOffset,d=u.source.byteOffset-o.source.byteOffset+u.size;return new DataView(a.buffer,l,d)},gM=a=>{let t=new St().parse(a),i=new Ht(t),r={},s=i.findAll("uuid");return s.length?s[s.length-1]:r},vM=a=>{var r;let t=new St().parse(a);return(r=new Ht(t).find("sidx"))==null?void 0:r.timescale},SM=(a,e)=>{let i=new St().parse(a),s=new Ht(i).findAll("traf"),n=s[s.length-1].children.find(d=>d.type==="tfhd"),o=s[s.length-1].children.find(d=>d.type==="tfdt"),u=s[s.length-1].children.find(d=>d.type==="trun"),l=0;return u.sampleDuration.length?l=u.sampleDuration.reduce((d,h)=>d+h,0):l=n.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+l)/e*1e3},yM=a=>{let e={is3dVideo:!1,stereoMode:0,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}},i=new St().parse(a),r=new Ht(i);if(r.find("sv3d")){e.is3dVideo=!0;let n=r.find("st3d");n&&(e.stereoMode=n.stereoMode);let o=r.find("prhd");o&&(e.projectionData.pose.yaw=o.poseYawDegrees,e.projectionData.pose.pitch=o.posePitchDegrees,e.projectionData.pose.roll=o.poseRollDegrees);let u=r.find("equi");u&&(e.projectionData.bounds.top=u.projectionBoundsTop,e.projectionData.bounds.right=u.projectionBoundsRight,e.projectionData.bounds.bottom=u.projectionBoundsBottom,e.projectionData.bounds.left=u.projectionBoundsLeft)}return e},PS={validateData:mM,parseInit:yM,getIndexRange:()=>{},parseSegments:fM,parseFeedableSegmentChunk:bM,getChunkEndTime:SM,getServerLatencyTimestamps:gM,getTimescaleFromIndex:vM};var Ra=O(qe(),1);import{assertNonNullable as Cl,isNonNullable as RS,isNullable as IM}from"@vkontakte/videoplayer-shared/es2015";import{assertNever as TM}from"@vkontakte/videoplayer-shared/es2015";var wS={440786851:{type:"master"},17030:{type:"uint"},17143:{type:"uint"},17138:{type:"uint"},17139:{type:"uint"},17026:{type:"string"},17031:{type:"uint"},17029:{type:"uint"},236:{type:"binary"},408125543:{type:"master"},290298740:{type:"master"},19899:{type:"master"},21419:{type:"binary"},21420:{type:"uint"},357149030:{type:"master"},2807729:{type:"uint"},17545:{type:"float"},374648427:{type:"master"},174:{type:"master"},224:{type:"master"},30320:{type:"master"},30321:{type:"uint"},30322:{type:"master"},272869232:{type:"master"},524531317:{type:"master"},231:{type:"uint"},22612:{type:"master"},22743:{type:"uint"},167:{type:"uint"},171:{type:"uint"},163:{type:"binary"},160:{type:"master"},175:{type:"binary"},423732329:{type:"master"},307544935:{type:"master"},475249515:{type:"master"},187:{type:"master"},179:{type:"uint"},183:{type:"master"},247:{type:"uint"},241:{type:"uint"},240:{type:"uint"},178:{type:"uint"},21368:{type:"uint"},234:{type:"uint"},219:{type:"master"},150:{type:"uint"}},kS=a=>{let e=a.getUint8(0),t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);let i=Aa(a,t),r=i in wS,s=r?wS[i].type:"binary",n=a.getUint8(t),o=0;n&128?o=1:n&64?o=2:n&32?o=3:n&16?o=4:n&8?o=5:n&4?o=6:n&2?o=7:n&1&&(o=8);let u=new DataView(a.buffer,a.byteOffset+t+1,o-1),l=n&255>>o,c=Aa(u),d=l*at(2,(o-1)*8)+c,h=t+o,p;return h+d>a.byteLength?p=new DataView(a.buffer,a.byteOffset+h):p=new DataView(a.buffer,a.byteOffset+h,d),{tag:r?i:"0x"+i.toString(16).toUpperCase(),type:s,tagHeaderSize:h,tagSize:h+d,value:p,valueSize:d}},Aa=(a,e=a.byteLength)=>{switch(e){case 1:return a.getUint8(0);case 2:return a.getUint16(0);case 3:return a.getUint8(0)*at(2,16)+a.getUint16(1);case 4:return a.getUint32(0);case 5:return a.getUint8(0)*at(2,32)+a.getUint32(1);case 6:return a.getUint16(0)*at(2,32)+a.getUint32(2);case 7:{let t=a.getUint8(0)*281474976710656+a.getUint16(1)*4294967296+a.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},Ze=(a,e)=>{switch(e){case"int":return a.getInt8(0);case"uint":return Aa(a);case"float":return a.byteLength===4?a.getFloat32(0):a.getFloat64(0);case"string":return new TextDecoder("ascii").decode(a);case"utf8":return new TextDecoder("utf-8").decode(a);case"date":return new Date(Date.UTC(2001,0)+a.getInt8(0)).getTime();case"master":return a;case"binary":return a;default:TM(e)}},fi=(a,e)=>{let t=0;for(;t<a.byteLength;){let i=new DataView(a.buffer,a.byteOffset+t),r=kS(i);if(!e(r))return;r.type==="master"&&fi(r.value,e),t=r.value.byteOffset-a.byteOffset+r.valueSize}},AS=a=>{if(a.getUint32(0)!==440786851)return!1;let e,t,i,r=kS(a);return fi(r.value,({tag:s,type:n,value:o})=>(s===17143?e=Ze(o,n):s===17026?t=Ze(o,n):s===17029&&(i=Ze(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)};var $S=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],EM=[231,22612,22743,167,171,163,160,175],xM=a=>{let e,t,i,r,s=!1,n=!1,o=!1,u,l,c=!1,d=0;return fi(a,({tag:h,type:p,value:m,valueSize:b})=>{if(h===21419){let g=Ze(m,p);l=Aa(g)}else h!==21420&&(l=void 0);return h===408125543?(e=m.byteOffset,t=m.byteOffset+b):h===357149030?s=!0:h===290298740?n=!0:h===2807729?i=Ze(m,p):h===17545?r=Ze(m,p):h===21420&&l===475249515?u=Ze(m,p):h===374648427?fi(m,({tag:g,type:v,value:S})=>g===30321?(c=Ze(S,v)===1,!1):!0):s&&n&&(0,Ra.default)($S,h)&&(o=!0),!o}),Cl(e,"Failed to parse webm Segment start"),Cl(t,"Failed to parse webm Segment end"),Cl(r,"Failed to parse webm Segment duration"),i=i!=null?i:1e6,{segmentStart:Math.round(e/1e9*i*1e3),segmentEnd:Math.round(t/1e9*i*1e3),timeScale:i,segmentDuration:Math.round(r/1e9*i*1e3),cuesSeekPosition:u,is3dVideo:c,stereoMode:d,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},PM=a=>{if(IM(a.cuesSeekPosition))return;let e=a.segmentStart+a.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},wM=(a,e)=>{let t=!1,i=!1,r=o=>RS(o.time)&&RS(o.position),s=[],n;return fi(a,({tag:o,type:u,value:l})=>{switch(o){case 475249515:t=!0;break;case 187:n&&r(n)&&s.push(n),n={};break;case 179:n&&(n.time=Ze(l,u));break;case 183:break;case 241:n&&(n.position=Ze(l,u));break;default:t&&(0,Ra.default)($S,o)&&(i=!0)}return!(t&&i)}),n&&r(n)&&s.push(n),s.map((o,u)=>{let{time:l,position:c}=o,d=s[u+1];return{status:"none",time:{from:l,to:d?d.time:e.segmentDuration},byte:{from:e.segmentStart+c,to:d?e.segmentStart+d.position-1:e.segmentEnd-1}}})},kM=a=>{let e=0,t=!1;try{fi(a,i=>i.tag===524531317?i.tagSize<=a.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):(0,Ra.default)(EM,i.tag)?(e+i.tagSize<=a.byteLength&&(e+=i.tagSize,t||(t=(0,Ra.default)([163,160,175],i.tag))),!0):!1)}catch(i){}return e>0&&e<=a.byteLength&&t?new DataView(a.buffer,a.byteOffset,e):null},LS={validateData:AS,parseInit:xM,getIndexRange:PM,parseSegments:wM,parseFeedableSegmentChunk:kM};var $a=a=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(a);if(e){let[,t,i]=e;if(t==="audio"||t==="video")switch(i){case"webm":return LS;case"mp4":return PS}}throw new ReferenceError(`Unsupported mime type ${a}`)};var Gl=O(XS(),1),Ey=O(Bi(),1),xy=O(hy(),1),Py=O(Nt(),1),Wl=O(zi(),1);var my=O(qe(),1),Fl=a=>{let e=a.split("."),[t,...i]=e;if(!t)return!1;switch(t){case"av01":{let[r,s,n]=i;return!!(n&&parseInt(n,10)>8)}case"vp09":{let[r,s,n]=i;return!!(r&&parseInt(r,10)>=2&&n&&parseInt(n,10)>8)}case"avc1":{let r=i[0];if(!r||r.length!==6)return!1;let[s,n]=r.toUpperCase(),o=s+n;return(0,my.default)(["6E","7A","F4"],o)}}return!1};import{isNonNullable as xD,isNullable as Ty}from"@vkontakte/videoplayer-shared/es2015";var fy=a=>{if(a.includes("/")){let e=a.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(a)};var by=a=>{var e;try{let t=ID(),i=a.match(t),{groups:r}=i!=null?i:{};if(r){let s={};if(r.extensions){let u=r.extensions.toLowerCase().match(/(?:[0-9a-wy-z](?:-[a-z0-9]{2,8})+)/g);Array.from(u||[]).forEach(l=>{s[l[0]]=l.slice(2)})}let n=(e=r.variants)==null?void 0:e.split(/-/).filter(u=>u!==""),o={extlang:r.extlang,langtag:r.langtag,language:r.language,privateuse:r.privateuse||r.privateuse2,region:r.region,script:r.script,extensions:s,variants:n};return Object.keys(o).forEach(u=>{let l=o[u];(typeof l=="undefined"||l==="")&&delete o[u]}),o}return null}catch(t){return null}};function ID(){let a="(?<extlang>(?:[a-z]{3}(?:-[a-z]{3}){0,2}))",e="x(?:-[a-z0-9]{1,8})+",c=`^(?:(?<langtag>${`
63
+ `}),S};var de=a=>new URL(a).hostname;import{assertNever as Av,assertNonNullable as kv,combine as fL,debounce as bL,ErrorCategory as Rv,filter as $v,filterChanged as gL,isNonNullable as Il,map as gn,merge as Lv,observableFrom as vL,once as SL,Subscription as yL,ValueSubject as El,videoQualityToHeight as Mv,videoSizeToQuality as TL}from"@vkontakte/videoplayer-shared/es2015";var Ev=O(Nt(),1);var vv=O(qe(),1);var gv=a=>{if(a instanceof DOMException&&(0,vv.default)(["Failed to load because no supported source was found.","The element has no supported sources."],a.message))throw a;return!(a instanceof DOMException&&(a.code===20||a.name==="AbortError"))},Me=(a,e)=>E(void 0,null,function*(){let t=a.muted;try{yield a.play()}catch(i){if(!gv(i))return!1;if(e&&e(),t)return console.warn(i),!1;a.muted=!0;try{yield a.play()}catch(r){return gv(r)&&(a.muted=!1,console.warn(r)),!1}}return!0});import{isNonNullable as mn,isNullable as X$,assertNonNullable as Xr}from"@vkontakte/videoplayer-shared/es2015";var yv=O(zi(),1);import{isNonNullable as Sv,assertNonNullable as hn,now as z$}from"@vkontakte/videoplayer-shared/es2015";function pe(){return z$()}function vl(a){return pe()-a}function Sl(a){let e=a.split("/"),t=e.slice(0,e.length-1).join("/"),i=/^([a-z]+:)?\/\//i,r=n=>i.test(n);return{resolve:(n,o,u=!1)=>{r(n)||(n.startsWith("/")||(n="/"+n),n=t+n);let l=n.indexOf("?")>-1?"&":"?";return u&&(n+=l+"lowLat=1",l="&"),o&&(n+=l+"_rnd="+Math.floor(999999999*Math.random())),n}}}function Tv(a,e,t){let i=(...r)=>{t.apply(null,r),a.removeEventListener(e,i)};a.addEventListener(e,i)}function Xi(a,e,t,i){let r=window.XMLHttpRequest,s,n,o,u=!1,l=0,c,d,h=!1,p="arraybuffer",m=7e3,b=2e3,g=()=>{if(u)return;hn(c);let L=vl(c),Q;if(L<b){Q=b-L,setTimeout(g,Q);return}b*=2,b>m&&(b=m),n&&n.abort(),n=new r,$()},v=L=>(s=L,H),S=L=>(d=L,H),y=()=>(p="json",H),I=()=>{if(!u){if(--l>=0){g(),i&&i();return}u=!0,d&&d(),t&&t()}},T=L=>(h=L,H),$=()=>{c=pe(),n=new r,n.open("get",a);let L=0,Q,N=0,Z=()=>(hn(c),Math.max(c,Math.max(Q||0,N||0)));if(s&&n.addEventListener("progress",R=>{let C=pe();s.updateChunk&&R.loaded>L&&(s.updateChunk(Z(),R.loaded-L),L=R.loaded,Q=C)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>I())),n.addEventListener("load",()=>{if(u)return;hn(n);let R=n.status;if(R>=200&&R<300){let{response:C,responseType:X}=n,P=C==null?void 0:C.byteLength;if(typeof P=="number"&&s){let M=P-L;M&&s.updateChunk&&s.updateChunk(Z(),M)}X==="json"&&(!C||!(0,yv.default)(C).length)?I():(d&&d(),e(C))}else I()}),n.addEventListener("error",()=>{I()}),h){let R=()=>{hn(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(N=pe(),n.removeEventListener("readystatechange",R))};n.addEventListener("readystatechange",R)}return n.responseType=p,n.send(),H},H={withBitrateReporting:v,withParallel:T,withJSONResponse:y,withRetryCount:L=>(l=L,H),withRetryInterval:(L,Q)=>(Sv(L)&&(b=L),Sv(Q)&&(m=Q),H),withTimeout:L=>(o=L,H),withFinally:S,send:$,abort:()=>{n&&(n.abort(),n=void 0),u=!0,d&&d()}};return H}var zr=class{constructor(e){this.intervals=[];this.currentRate=0;this.logger=e}_updateRate(e){let t=.2;this.currentRate&&(e<this.currentRate*.1?t=.8:e<this.currentRate*.5?t=.5:e<this.currentRate*.7&&(t=.3)),e=Math.max(1,Math.min(e,100*1024*1024)),this.currentRate=this.currentRate?this.currentRate*(1-t)+e*t:e}_createInterval(e,t,i){return{start:e,end:t,bytes:i}}_doMergeIntervals(e,t){e.start=Math.min(t.start,e.start),e.end=Math.max(t.end,e.end),e.bytes+=t.bytes}_mergeIntervals(e,t){return e.start<=t.end&&t.start<=e.end?(this._doMergeIntervals(e,t),!0):!1}_flushIntervals(){if(!this.intervals.length)return!1;let e=this.intervals[0].start,t=this.intervals[this.intervals.length-1].end-500;if(t-e>2e3){let i=0,r=0;for(;this.intervals.length>0;){let s=this.intervals[0];if(s.end<=t)i+=s.end-s.start,r+=s.bytes,this.intervals.splice(0,1);else{if(s.start>=t)break;{let n=t-s.start,o=s.end-s.start;i+=n;let u=s.bytes*n/o;r+=u,s.start=t,s.bytes-=u}}}if(r>0&&i>0){let s=r*8/(i/1e3);return this._updateRate(s),this.logger(`rate updated, new=${Math.round(s/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(r)}/${Math.round(i)} interval=${Math.round(t-e)}`),!0}}return!1}_joinIntervals(){let e;do{e=!1;for(let t=0;t<this.intervals.length-1;++t)this._mergeIntervals(this.intervals[t],this.intervals[t+1])&&(this.intervals.splice(t+1,1),e=!0)}while(e)}addInterval(e,t,i){return this.intervals.push(this._createInterval(e,t,i)),this._joinIntervals(),this.intervals.length>100&&(this.logger(`too many intervals (${this.intervals.length}); will merge`,{type:"warn"}),this._doMergeIntervals(this.intervals[1],this.intervals[0]),this.intervals.splice(0,1)),this._flushIntervals()}getBitRate(){return this.currentRate}};var Iv=O(zi(),1);var Kr=class{constructor(e,t,i,r,s){this.pendingQueue=[];this.activeRequests={};this.completeRequests={};this.averageSegmentDuration=2e3;this.lastPrefetchStart=0;this.throttleTimeout=null;this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=i,this.MAX_PARALLEL_REQUESTS=r,this.logger=s}limitCompleteCount(){let e;for(;(e=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){let t=e[Math.floor(Math.random()*e.length)];this.logger(`Dropping completed request for url ${t}`,{type:"warn"}),delete this.completeRequests[t]}}_sendRequest(e,t){let i=pe(),r=u=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=u,e._errorCB?e._errorCB(u):(this.limitCompleteCount(),this.completeRequests[t]=e)},s=u=>{e._complete=1,e._responseData=u,e._downloadTime=pe()-i,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(u,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},n=()=>{e._finallyCB&&e._finallyCB()},o=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=Xi(t,s,()=>r("error"),o),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally(n),this.activeRequests[t]=e,e._request.send(),this.lastPrefetchStart=pe()}_getParallelRequestCount(){return Math.min(this.MAX_PARALLEL_REQUESTS,this.averageSegmentDuration<3e3?3:2)}_getPrefetchDelay(){return Math.max(100,Math.min(5e3,this.averageSegmentDuration/3))}_canSendPending(){let e=this._getParallelRequestCount(),t=pe();if(Object.keys(this.activeRequests).length>=e)return!1;let i=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),i>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),i),!1):!0}_sendPending(){for(;this._canSendPending();){let e=this.pendingQueue.pop();if(e){if(this.activeRequests[e]||this.completeRequests[e])continue;this.logger(`Submitting pending request url=${e}`),this._sendRequest({},e)}else return}}_removeFromActive(e){delete this.completeRequests[e],delete this.activeRequests[e]}abortAll(){(0,Iv.default)(this.activeRequests).forEach(e=>{e&&e._request&&e._request.abort()}),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,i,r){let s={};return s.send=()=>{let n=this.activeRequests[e]||this.completeRequests[e];if(n)n._cb=t,n._errorCB=i,n._retryCB=r,n._finallyCB=s._finallyCB,n._error||n._complete?(this._removeFromActive(e),setTimeout(()=>{n._complete?(this.logger(`Requested url already prefetched, url=${e}`),t(n._responseData,n._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${e}`),i(n._errorMsg)),s._finallyCB&&s._finallyCB()},0)):this.logger(`Attached to active request, url=${e}`);else{let o=this.pendingQueue.indexOf(e);o!==-1&&this.pendingQueue.splice(o,1),this.logger(`Request not prefetched, starting new request, url=${e}${o===-1?"":"; removed pending"}`),this._sendRequest(s,e)}},s._cb=t,s._errorCB=i,s._retryCB=r,s.abort=function(){s.request&&s.request.abort()},s.withFinally=n=>(s._finallyCB=n,s),s}prefetch(e){this.activeRequests[e]||this.completeRequests[e]?this.logger(`Request already active for url=${e}`):(this.logger(`Added to pending queue; url=${e}`),this.pendingQueue.unshift(e),this._sendPending())}optimizeForSegDuration(e){this.averageSegmentDuration=e}};import{Subject as J$}from"@vkontakte/videoplayer-shared/es2015";var fn=1e4,yl=3;var Z$=6e4,eL=10,tL=1,iL=500,Jr=class{constructor(e){this.paused=!1;this.autoQuality=!0;this.autoQualityLimits=void 0;this.buffering=!0;this.destroyed=!1;this.videoPlayStarted=!1;this.lowLatency=!1;this.bitrate=0;this.manifest=[];this.sourceBuffer=0;this.bufferStates=[];this.sourceJitter=-1;this.waitingForFirstBufferAfterSrcChange=!1;this.params=e,this.soundProhibitedEvent$=new J$,this.chunkRateEstimator=new zr(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=Sl(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setAutoQualityLimits(e){this.autoQualityLimits=e}switchByName(e){let t;for(let i=0;i<this.manifest.length;++i)if(t=this.manifest[i],t.name===e){this._switchToQuality(t);return}}catchUp(){this.rep&&this.rep.stop(),this.currentManifestEntry&&(this.paused=!1,this._initPlayerWith(this.currentManifestEntry),this._notifyBuffering(!0))}stop(){this.params.videoElement.pause(),this.rep&&(this.rep.stop(),this.rep=null)}pause(){this.paused=!0,this.params.videoElement.pause(),this.videoPlayStarted=!1,this._notifyBuffering(!1)}play(){this.paused=!1;let e=this.lowLatency&&this._getBufferSizeSec()>this.sourceJitter+5;this.rep&&!e?(this.bufferStates=[],this.videoPlayStarted=!1,this.shouldPlay()?this._playVideoElement():this._notifyBuffering(!0)):this.catchUp()}startPlay(e,t){this.autoQuality=t,this._initPlayerWith(e)}destroy(){this.destroyed=!0,this.rep&&(this.rep.stop(),this.rep=null),this.manifestRequest&&this.manifestRequest.abort(),this.manifestRefetchTimer&&(clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=void 0)}reinit(e){this.manifestUrl=e,this.urlResolver=Sl(e),this.catchUp()}_handleNetworkError(){this.params.logger("Fatal network error"),this.params.playerCallback({name:"error",type:"network"})}_retryCallback(){this.params.playerCallback({name:"retry"})}_getBufferSizeSec(){let e=this.params.videoElement,t=0,i=e.buffered.length;return i!==0&&(t=e.buffered.end(i-1)-Math.max(e.currentTime,e.buffered.start(0))),t}_notifyBuffering(e){this.destroyed||(this.params.logger(`buffering: ${e}`),this.params.playerCallback({name:"buffering",isBuffering:e}),this.buffering=e)}_initVideo(){let{videoElement:e,logger:t}=this.params;e.addEventListener("error",()=>{var r;!!e.error&&!this.destroyed&&(t(`Video element error: ${(r=e.error)==null?void 0:r.code}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{let i=this._getBufferSizeSec();!this.paused&&i<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(i+.1)*1e3)):this.buffering&&this.videoPlayStarted&&this._notifyBuffering(!1)}),e.addEventListener("playing",()=>{t("playing")}),e.addEventListener("stalled",()=>this._fixupStall()),e.addEventListener("waiting",()=>this._fixupStall())}_fixupStall(){let{logger:e,videoElement:t}=this.params,i=t.buffered.length,r;i!==0&&!this.waitingForFirstBufferAfterSrcChange&&(r=t.buffered.start(i-1),t.currentTime<r&&(e("Fixup stall"),t.currentTime=r))}_selectQuality(e){let{videoElement:t}=this.params,i,r,s,n=t&&1.62*(U.display.pixelRatio||1)*t.offsetHeight||520;for(let o=0;o<this.manifest.length;++o){s=this.manifest[o];let{max:u,min:l}=this.autoQualityLimits||{};!sv({limits:this.autoQualityLimits,highestAvailableHeight:this.manifest[0].video.height,lowestAvailableHeight:(0,Ev.default)(this.manifest,-1).video.height})&&(u&&s.video.height>u||l&&s.video.height<l)||(s.bitrate<e&&n>Math.min(s.video.height,s.video.width)?(!r||s.bitrate>r.bitrate)&&(r=s):(!i||i.bitrate>s.bitrate)&&(i=s))}return r||i}shouldPlay(){if(this.paused)return!1;let t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||mn(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){let{logger:i,videoElement:r,playerCallback:s}=this.params;this.mediaSource=new window.MediaSource,i("setting video src"),r.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.videoPlayStarted=!1,r.addEventListener("canplay",()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});let n=()=>{Tv(r,"progress",()=>{r.buffered.length?(r.currentTime=r.buffered.start(0),this.waitingForFirstBufferAfterSrcChange=!1,s({name:"playing"})):n()})};this.waitingForFirstBufferAfterSrcChange=!0,n()}_initPlayerWith(e){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new Kr(yl,fn,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){let{logger:t,videoElement:i,playerCallback:r}=this.params,s=!1,n=null,o=null,u=null,l=null,c=!1,d=()=>{let I=s&&(!c||c===this.rep);return I||t("Not running!"),I},h=(I,T,$)=>{u&&u.abort(),u=Xi(this.urlResolver.resolve(I,!1),T,$,()=>this._retryCallback()).withTimeout(fn).withBitrateReporting(this.bitrateSwitcher).withRetryCount(yl).withFinally(()=>{u=null}).send()},p=(I,T,$)=>{Xr(this.filesFetcher),o==null||o.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(I,!1),T,$,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},m=I=>{let T=i.playbackRate;i.playbackRate!==I&&(t(`Playback rate switch: ${T}=>${I}`),i.playbackRate=I)},b=I=>{this.lowLatency=I,t(`lowLatency changed to ${I}`),g()},g=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)m(1);else{let I=this._getBufferSizeSec();if(this.bufferStates.length<5){m(1);return}let $=pe()-1e4,F=0;for(let K=0;K<this.bufferStates.length;K++){let x=this.bufferStates[K];I=Math.min(I,x.buf),x.ts<$&&F++}this.bufferStates.splice(0,F),t(`update playback rate; minBuffer=${I} drop=${F} jitter=${this.sourceJitter}`);let q=I-tL;this.sourceJitter>=0?q-=this.sourceJitter/2:this.sourceJitter-=1,q>3?m(1.15):q>1?m(1.1):q>.3?m(1.05):m(1)}},v=I=>{let T,$=()=>T&&T.start?T.start.length:0,F=R=>T.start[R]/1e3,q=R=>T.dur[R]/1e3,K=R=>T.fragIndex+R,x=(R,C)=>({chunkIdx:K(R),startTS:F(R),dur:q(R),discontinuity:C}),H=()=>{let R=0;if(T&&T.dur){let C=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,X=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,P=C;this.sourceJitter>1&&(P+=this.sourceJitter-1);let M=T.dur.length-1;for(;M>=0&&(P-=T.dur[M],!(P<=0));--M);R=Math.min(M,T.dur.length-1-X),R=Math.max(R,0)}return x(R,!0)},L=R=>{let C=$();if(!(C<=0)){if(mn(R)){for(let X=0;X<C;X++)if(F(X)>R)return x(X)}return H()}},Q=R=>{let C=$(),X=R?R.chunkIdx+1:0,P=X-T.fragIndex;if(!(C<=0)){if(!R||P<0||P-C>eL)return t(`Resync: offset=${P} bChunks=${C} chunk=`+JSON.stringify(R)),H();if(!(P>=C))return x(X-T.fragIndex,!1)}},N=(R,C,X)=>{l&&l.abort(),l=Xi(this.urlResolver.resolve(R,!0,this.lowLatency),C,X,()=>this._retryCallback()).withTimeout(fn).withRetryCount(yl).withFinally(()=>{l=null}).withJSONResponse().send()};return{seek:(R,C)=>{N(I,X=>{if(!d())return;T=X;let P=!!T.lowLatency;P!==this.lowLatency&&b(P);let M=0;for(let me=0;me<T.dur.length;++me)M+=T.dur[me];M>0&&(Xr(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(M/T.dur.length)),r({name:"index",zeroTime:T.zeroTime,shiftDuration:T.shiftDuration}),this.sourceJitter=T.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,T.jitter/1e3)):1,R(L(C))},()=>this._handleNetworkError())},nextChunk:Q}},S=()=>{s=!1,o&&o.abort(),u&&u.abort(),l&&l.abort(),Xr(this.filesFetcher),this.filesFetcher.abortAll()};return c={start:I=>{let{videoElement:T,logger:$}=this.params,F=v(e.jidxUrl),q,K,x,H,L=0,Q,N,Z,R=()=>{Q&&(clearTimeout(Q),Q=void 0);let Y=Math.max(iL,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),ye=L+Y,Pe=pe(),we=Math.min(1e4,ye-Pe);L=Pe;let tt=()=>{l||d()&&F.seek(()=>{d()&&(L=pe(),C(),R())})};we>0?Q=window.setTimeout(()=>{this.paused?R():tt()},we):tt()},C=()=>{let Y;for(;Y=F.nextChunk(H);)H=Y,Ti(Y);let ye=F.nextChunk(x);if(ye){if(x&&ye.discontinuity){$("Detected discontinuity; restarting playback"),this.paused?R():(S(),this._initPlayerWith(e));return}me(ye)}else R()},X=(Y,ye)=>{if(!d()||!this.sourceBuffer)return;let Pe,we,tt,ht=Pt=>{window.setTimeout(()=>{d()&&X(Y,ye)},Pt)};if(this.sourceBuffer.updating)$("Source buffer is updating; delaying appendBuffer"),ht(100);else{let Pt=pe(),zt=T.currentTime;!this.paused&&T.buffered.length>1&&N===zt&&Pt-Z>500&&($("Stall suspected; trying to fix"),this._fixupStall()),N!==zt&&(N=zt,Z=Pt);let Ii=this._getBufferSizeSec();if(Ii>30)$(`Buffered ${Ii} seconds; delaying appendBuffer`),ht(2e3);else try{this.sourceBuffer.appendBuffer(Y),this.videoPlayStarted?(this.bufferStates.push({ts:Pt,buf:Ii}),g(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),ye&&ye()}catch(dr){if(dr.name==="QuotaExceededError")$("QuotaExceededError; delaying appendBuffer"),tt=this.sourceBuffer.buffered.length,tt!==0&&(Pe=this.sourceBuffer.buffered.start(0),we=zt,we-Pe>4&&this.sourceBuffer.remove(Pe,we-3)),ht(1e3);else throw dr}}},P=()=>{K&&q&&($([`Appending chunk, sz=${K.byteLength}:`,JSON.stringify(x)]),X(K,function(){K=null,C()}))},M=Y=>e.fragUrlTemplate.replace("%%id%%",Y.chunkIdx),me=Y=>{d()&&p(M(Y),(ye,Pe)=>{if(d()){if(Pe/=1e3,K=ye,x=Y,n=Y.startTS,Pe){let we=Math.min(10,Y.dur/Pe);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*we:we}P()}},()=>this._handleNetworkError())},Ti=Y=>{d()&&(Xr(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(M(Y),!1)))},pt=Y=>{d()&&(e.cachedHeader=Y,X(Y,()=>{q=!0,P()}))};s=!0,F.seek(Y=>{if(d()){if(L=pe(),!Y){R();return}H=Y,!X$(I)||Y.startTS>I?me(Y):(x=Y,C())}},I),e.cachedHeader?pt(e.cachedHeader):h(e.headerUrl,pt,()=>this._handleNetworkError())},stop:S,getTimestampSec:()=>n},c}_switchToQuality(e){let{logger:t,playerCallback:i}=this.params,r;e.bitrate!==this.bitrate&&(this.rep&&(r=this.rep.getTimestampSec(),mn(r)&&(r+=.1),this.rep.stop()),this.currentManifestEntry=e,this.rep=this._representation(e),t(`switch to quality: codecs=${e.codecs}; headerUrl=${e.headerUrl}; bitrate=${e.bitrate}`),this.bitrate=e.bitrate,Xr(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(r),i({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return mn(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,i=d=>{if(!this.autoQuality)return;let h,p,m;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&d<this.bitrate&&(p=this._getBufferSizeSec(),m=d/this.bitrate,p>10&&m>.8||p>15&&m>.5||p>20&&m>.3)){e(`Not switching: buffer=${Math.floor(p)}; bitrate=${this.bitrate}; newRate=${Math.floor(d)}`);return}h=this._selectQuality(d),h?this._switchToQuality(h):e(`Could not find quality by bitrate ${d}`)},s={updateChunk:(h,p)=>{let m=pe();if(this.chunkRateEstimator.addInterval(h,m,p)){let g=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:p,duration:m-h,speed:g}),!0}},get:()=>{let h=this.chunkRateEstimator.getBitRate();return h?h*.85:0}},n=-1/0,o,u=!0,l=()=>{let d=s.get();if(d&&o&&this.autoQuality){if(u&&d>o&&vl(n)<3e4)return;i(d)}u=this.autoQuality};return{updateChunk:(d,h)=>{let p=s.updateChunk(d,h);return p&&l(),p},notifySwitch:d=>{let h=pe();d<o&&(n=h),o=d}}}_fetchManifest(e,t,i){this.manifestRequest=Xi(this.urlResolver.resolve(e,!0),t,i,()=>this._retryCallback()).withJSONResponse().withTimeout(fn).withRetryCount(this.params.config.manifestRetryMaxCount).withRetryInterval(this.params.config.manifestRetryInterval,this.params.config.manifestRetryMaxInterval).send().withFinally(()=>{this.manifestRequest=void 0})}_playVideoElement(){let{videoElement:e}=this.params;Me(e,()=>{this.soundProhibitedEvent$.next()}).then(t=>{t||(this.params.liveOffset.pause(),this.params.videoState.setState("paused"))})}_handleManifestUpdate(e){let{logger:t,playerCallback:i,videoElement:r}=this.params,s=n=>{let o=[];return n!=null&&n.length?(n.forEach((u,l)=>{var c,d;u.video&&r.canPlayType(u.codecs).replace(/no/,"")&&((d=(c=window.MediaSource)==null?void 0:c.isTypeSupported)!=null&&d.call(c,u.codecs))&&(u.index=l,o.push(u))}),o.sort(function(u,l){return u.video&&l.video?l.video.height-u.video.height:l.bitrate-u.bitrate}),o):(i({name:"error",type:"empty_manifest"}),[])};this.manifest=s(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),i({name:"manifest",manifest:this.manifest})}_refetchManifest(e){this.destroyed||(this.manifestRefetchTimer&&clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=window.setTimeout(()=>{this._fetchManifest(e,t=>{this.destroyed||(this._handleManifestUpdate(t),this._refetchManifest(e))},()=>this._refetchManifest(e))},Z$))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};var wv=O(_i(),1);import{debounce as rL,filter as xv,fromEvent as aL,interval as sL,isHigher as nL,isInvariantQuality as oL,isLower as uL,merge as lL,Subject as Pv,Subscription as cL}from"@vkontakte/videoplayer-shared/es2015";var Tl=class{constructor(){this.onDroopedVideoFramesLimit$=new Pv;this.subscription=new cL;this.playing=!1;this.tracks=[];this.forceChecker$=new Pv;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&&!oL(e.quality)&&this.onChangeQuality(e.quality)};this.checkDroppedFrames=()=>{var n;let{totalVideoFrames:e,droppedVideoFrames:t}=this.video.getVideoPlaybackQuality(),i=e-this.prevTotalVideoFrames,r=t-this.prevDroppedVideoFrames,s=1-(i-r)/i;!isNaN(s)&&s>0&&this.log({message:`[dropped]. current dropped percent: ${s}, limit: ${this.droppedFramesChecker.percentLimit}`}),!isNaN(s)&&s>=this.droppedFramesChecker.percentLimit&&nL(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(aL(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=sL(this.droppedFramesChecker.checkTime).pipe(xv(()=>this.playing),xv(()=>{let r=!!this.isForceCheckCounter;return r&&(this.isForceCheckCounter-=1),!r})),t=this.forceChecker$.pipe(rL(this.droppedFramesChecker.checkTime)),i=lL(e,t);this.subscription.add(i.subscribe(this.checkDroppedFrames))}onChangeQuality(e){this.currentQuality=e;let{totalVideoFrames:t,droppedVideoFrames:i}=this.video.getVideoPlaybackQuality();this.savePrevFrameCounts(t,i),this.isForceCheckCounter=this.droppedFramesChecker.tickCountAfterQualityChange,this.forceChecker$.next()}onDroopedVideoFramesLimitTrigger(){this.isAuto.getState()&&(this.log({message:`[onDroopedVideoFramesLimit]. maxQualityLimit: ${this.maxQualityLimit}`}),this.onDroopedVideoFramesLimit$.next())}getMaxQualityLimit(e){var i,r;let t=(r=(i=(0,wv.default)(this.limitCounts).filter(([,s])=>s>=this.droppedFramesChecker.countLimit).sort(([s],[n])=>uL(s,n)?-1:1))==null?void 0:i[0])==null?void 0:r[0];return e!=null?e:t}get isEnabled(){return this.droppedFramesChecker.enabled&&this.isDroppedFramesCheckerSupport}get isDroppedFramesCheckerSupport(){return!!this.video&&typeof this.video.getVideoPlaybackQuality=="function"}savePrevFrameCounts(e,t){this.prevTotalVideoFrames=e,this.prevDroppedVideoFrames=t}},bn=Tl;import{map as dL,Observable as pL}from"@vkontakte/videoplayer-shared/es2015";import{fromEvent as hL}from"@vkontakte/videoplayer-shared/es2015";var Zr=()=>{var a;return!!((a=window.documentPictureInPicture)!=null&&a.window)||!!document.pictureInPictureElement};var mL=(a,e)=>new pL(t=>{if(!window.IntersectionObserver)return;let i={root:null},r=new IntersectionObserver((n,o)=>{n.forEach(u=>t.next(u.isIntersecting||Zr()))},w(w({},i),e));r.observe(a);let s=hL(document,"visibilitychange").pipe(dL(n=>!document.hidden||Zr())).subscribe(n=>t.next(n));return()=>{r.unobserve(a),s.unsubscribe()}}),je=mL;var IL=["paused","playing","ready"],EL=["paused","playing","ready"],ea=class{constructor(e){this.subscription=new yL;this.videoState=new B("stopped");this.representations$=new El([]);this.droppedFramesManager=new bn;this.maxSeekBackTime$=new El(1/0);this.zeroTime$=new El(void 0);this.liveOffset=new hi;this._dashCb=e=>{var t,i,r,s;switch(e.name){case"buffering":{let n=e.isBuffering;this.params.output.isBuffering$.next(n);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${e.type}`,category:Rv.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{let n=e.manifest,o=[];for(let u of n){let l=(t=u.name)!=null?t:u.index.toString(10),c=(i=_t(u.name))!=null?i:TL(u.video),d=u.bitrate/1e3,h=w({},u.video);if(!c)continue;let p={id:l,quality:c,bitrate:d,size:h};o.push({track:p,representation:u})}this.representations$.next(o),this.params.output.availableVideoTracks$.next(o.map(({track:u})=>u)),((r=this.videoState.getTransition())==null?void 0:r.to)==="manifest_ready"&&this.videoState.setState("manifest_ready");break}case"qualitySwitch":{let n=e.quality,o=(s=this.representations$.getValue().find(({representation:u})=>u===n))==null?void 0:s.track;this.params.output.hostname$.next(new URL(n.headerUrl,this.params.source.url).hostname),Il(o)&&this.params.output.currentVideoTrack$.next(o);break}case"bandwidth":{let{size:n,duration:o}=e;this.params.dependencies.throughputEstimator.addRawSpeed(n,o);break}case"index":{this.maxSeekBackTime$.next(e.shiftDuration||0),this.zeroTime$.next(e.zeroTime);break}}};this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; seekState: ${JSON.stringify(s)};`}),i==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState("stopped"));return}if(t)return;let n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.autoVideoTrackSwitching.getTransition();if((0,xl.default)(EL,e)&&(n||o)){this.prepare();return}if((r==null?void 0:r.to)!=="paused"&&s.state==="requested"&&(0,xl.default)(IL,e)){this.seek(s.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(ge(this.params.source.url));return;case"manifest_ready":this.videoState.startTransitionTo("ready"),this.prepare();break;case"ready":if(i==="paused")this.videoState.setState("paused");else if(i==="playing"){this.videoState.startTransitionTo("playing");let u=r==null?void 0:r.from;u&&u==="ready"&&this.dash.catchUp(),this.dash.play()}return;case"playing":i==="paused"&&(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.dash.pause());return;case"paused":if(i==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.dash.play(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let u=this.liveOffset.getTotalOffset();u>=this.maxSeekBackTime$.getValue()&&(u=0,this.liveOffset.resetTo(u)),this.liveOffset.resume(),this.params.output.position$.next(-u/1e3),this.dash.reinit(ge(this.params.source.url,u))}return;default:return Av(e)}};this.textTracksManager=new He(e.source.url),this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=r=>{e.output.error$.next({id:"DashLiveProvider",category:Rv.WTF,message:"DashLiveProvider internal logic error",thrown:r})};this.subscription.add(Lv(this.videoState.stateChangeStarted$.pipe(gn(r=>({transition:r,type:"start"}))),this.videoState.stateChangeEnded$.pipe(gn(r=>({transition:r,type:"end"})))).subscribe(({transition:r,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(r)}`})})),this.video=Ae(e.container,e.tuning),this.params.output.element$.next(this.video),this.dash=this.createLiveDashPlayer(),this.subscription.add(this.dash.soundProhibitedEvent$.subscribe(this.params.output.soundProhibitedEvent$)),this.params.output.duration$.next(1/0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(de(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);let i=Le(this.video);this.subscription.add(()=>i.destroy()),this.subscription.add(this.representations$.pipe(gn(r=>r.map(({track:s})=>s)),$v(r=>!!r.length),SL()).subscribe(r=>this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks:r}))),this.subscription.add(i.canplay$.subscribe(()=>{var r;((r=this.videoState.getTransition())==null?void 0:r.to)==="ready"&&this.videoState.setState("ready")},t)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused")},t)).add(i.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.videoState.setState("playing")},t)).add(i.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(gL(),gn(r=>-r/1e3)).subscribe(this.params.output.duration$)).add(fL({zeroTime:this.zeroTime$.pipe($v(Il)),position:i.timeUpdate$}).subscribe(({zeroTime:r,position:s})=>this.params.output.liveTime$.next(r+s*1e3),t)).add(ot(this.video,this.params.desiredState.isLooped,t)).add(Re(this.video,this.params.desiredState.volume,i.volumeState$,t)).add(i.volumeState$.subscribe(this.params.output.volume$,t)).add(Ue(this.video,this.params.desiredState.playbackRate,i.playbackRateState$,t)).add(i.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(i.loadedMetadata$.subscribe(this.params.output.loadedMetadataEvent$)).add(i.playing$.subscribe(this.params.output.firstFrameEvent$)).add(i.canplay$.subscribe(this.params.output.canplay$)).add(i.inPiP$.subscribe(this.params.output.inPiP$)).add(i.inFullscreen$.subscribe(this.params.output.inFullscreen$)).add(je(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:r,min:s}})=>{this.dash.setAutoQualityLimits({max:r&&Mv(r),min:s&&Mv(s)}),this.params.output.autoVideoTrackLimits$.next({max:r,min:s})})).add(this.videoState.stateChangeEnded$.subscribe(r=>{var s;switch(r.to){case"stopped":this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState("stopped");break;case"manifest_ready":case"ready":((s=this.params.desiredState.playbackState.getTransition())==null?void 0:s.to)==="ready"&&this.params.desiredState.playbackState.setState("ready");break;case"paused":this.params.desiredState.playbackState.setState("paused");break;case"playing":this.params.desiredState.playbackState.setState("playing");break;default:return Av(r.to)}},t)).add(Lv(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,vL(["init"])).pipe(bL(0)).subscribe(this.syncPlayback,t))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.droppedFramesManager.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),ke(this.video)}createLiveDashPlayer(){let e=new Jr({videoElement:this.video,videoState:this.videoState,liveOffset:this.liveOffset,config:{maxParallelRequests:this.params.config.maxParallelRequests,minBuffer:this.params.tuning.live.minBuffer,minBufferSegments:this.params.tuning.live.minBufferSegments,lowLatencyMinBuffer:this.params.tuning.live.lowLatencyMinBuffer,lowLatencyMinBufferSegments:this.params.tuning.live.lowLatencyMinBufferSegments,isLiveCatchUpMode:this.params.tuning.live.isLiveCatchUpMode,manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},playerCallback:this._dashCb,logger:t=>{this.params.dependencies.logger.log({message:String(t),component:"LiveDashPlayer"})}});return e.pause(),e}prepare(){var l,c,d,h,p,m;let e=this.representations$.getValue(),t=(c=(l=this.params.desiredState.videoTrack.getTransition())==null?void 0:l.to)!=null?c:this.params.desiredState.videoTrack.getState(),i=(h=(d=this.params.desiredState.autoVideoTrackSwitching.getTransition())==null?void 0:d.to)!=null?h:this.params.desiredState.autoVideoTrackSwitching.getState(),r=!i&&Il(t)?t:qt(e.map(({track:b})=>b),{container:this.video.getBoundingClientRect(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),s=r==null?void 0:r.id,n=this.params.desiredState.videoTrack.getTransition(),o=(p=this.params.desiredState.videoTrack.getState())==null?void 0:p.id,u=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(r&&(n||s!==o)&&this.setVideoTrack(r),u&&this.setAutoQuality(i),n||u||s!==o){let b=(m=e.find(({track:g})=>g.id===s))==null?void 0:m.representation;kv(b,"Representations missing"),this.dash.startPlay(b,i)}}setVideoTrack(e){var i;let t=(i=this.representations$.getValue().find(({track:r})=>r.id===e.id))==null?void 0:i.representation;kv(t,`No such representation ${e.id}`),this.dash.switchByName(t.name),this.params.desiredState.videoTrack.setState(e)}setAutoQuality(e){this.dash.setAutoQualityEnabled(e),this.params.desiredState.autoVideoTrackSwitching.setState(e)}seek(e){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),i=this.videoState.getState(),r=t==="paused"&&i==="paused",s=-e,n=s<=this.maxSeekBackTime$.getValue()?s:0;this.params.output.position$.next(e/1e3),this.dash.reinit(ge(this.params.source.url,n)),r&&this.dash.pause(),this.liveOffset.resetTo(n,r)}};var Dv=ea;var tT=O(qe(),1);var Ji=(a,e)=>{let t=0;for(let i=0;i<a.length;i++){let r=a.start(i)*1e3,s=a.end(i)*1e3;r<=e&&e<=s&&(t=s)}return Math.max(t-e,0)};import{assertNever as aC,assertNonNullable as sC,debounce as nC,ErrorCategory as Jy,filter as dc,filterChanged as Ua,fromEvent as oC,isNonNullable as Zy,map as pc,merge as _n,observableFrom as hc,once as eT,Subscription as uC}from"@vkontakte/videoplayer-shared/es2015";var vn=class{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,i){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:i})}removeEventListener(e,t){if(!(e in this.listeners))return;let i=this.listeners[e];for(let r=0,s=i.length;r<s;r++)if(i[r].callback===t){i.splice(r,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;let i=this.listeners[e.type].slice();for(let r=0,s=i.length;r<s;r++){let n=i[r];try{n.callback.call(this,e)}catch(o){Promise.resolve().then(()=>{throw o})}n.options&&n.options.once&&this.removeEventListener(e.type,n.callback)}return!e.defaultPrevented}},Zi=class extends vn{constructor(){super(),this.listeners||vn.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)}},ta=class{constructor(){Object.defineProperty(this,"signal",{value:new Zi,writable:!0,configurable:!0})}abort(e){let t;try{t=new Event("abort")}catch(r){typeof document!="undefined"?document.createEvent?(t=document.createEvent("Event"),t.initEvent("abort",!1,!1)):(t=document.createEventObject(),t.type="abort"):t={type:"abort",bubbles:!1,cancelable:!1}}let i=e;if(i===void 0)if(typeof document=="undefined")i=new Error("This operation was aborted"),i.name="AbortError";else try{i=new DOMException("signal is aborted without reason")}catch(r){i=new Error("This operation was aborted"),i.name="AbortError"}this.signal.reason=i,this.signal.dispatchEvent(t)}toString(){return"[object AbortController]"}};typeof Symbol!="undefined"&&Symbol.toStringTag&&(ta.prototype[Symbol.toStringTag]="AbortController",Zi.prototype[Symbol.toStringTag]="AbortSignal");function Sn(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 Pl(a){typeof a=="function"&&(a={fetch:a});let{fetch:e,Request:t=e.Request,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r=!1}=a;if(!Sn({fetch:e,Request:t,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r}))return{fetch:e,Request:s};let s=t;(s&&!s.prototype.hasOwnProperty("signal")||r)&&(s=function(l,c){let d;c&&c.signal&&(d=c.signal,delete c.signal);let h=new t(l,c);return d&&Object.defineProperty(h,"signal",{writable:!1,enumerable:!1,configurable:!0,value:d}),h},s.prototype=t.prototype);let n=e;return{fetch:(u,l)=>{let c=s&&s.prototype.isPrototypeOf(u)?u.signal:l?l.signal:void 0;if(c){let d;try{d=new DOMException("Aborted","AbortError")}catch(p){d=new Error("Aborted"),d.name="AbortError"}if(c.aborted)return Promise.reject(d);let h=new Promise((p,m)=>{c.addEventListener("abort",()=>m(d),{once:!0})});return l&&l.signal&&delete l.signal,Promise.race([h,n(u,l)])}return n(u,l)},Request:s}}var ia=Sn({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),Cv=ia?Pl({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,lt=ia?Cv.fetch:window.fetch,Rq=ia?Cv.Request:window.Request,ve=ia?ta:window.AbortController,$q=ia?Zi:window.AbortSignal;var oc=O(Al(),1);var yS=O(SS(),1);import{ErrorCategory as aa}from"@vkontakte/videoplayer-shared/es2015";var TS=a=>{if(!a)return{id:"EmptyResponse",category:aa.PARSER,message:"Empty response"};if(a.length<=2&&a.match(/^\d+$/))return{id:`UVError#${a}`,category:aa.NETWORK,message:`UV Error ${a}`};let e=(0,yS.default)(a).substring(0,100).toLowerCase();if(e.startsWith("<!doctype")||e.startsWith("<html>")||e.startsWith("<body>")||e.startsWith("<head>"))return{id:"UnexpectedHTML",category:aa.NETWORK,message:"Received unexpected HTML, possibly a ISP block"};if(e.startsWith("<?xml"))return new DOMParser().parseFromString(a,"text/xml").querySelector("parsererror")?{id:"InvalidXML",category:aa.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:aa.PARSER,message:"Response is valid XML, but parser failed"}};var Ut=(a,e,t=0)=>{for(let i=0;i<a.length;i++)if(a.start(i)*1e3-t<=e&&a.end(i)*1e3+t>e)return!0;return!1};import{abortable as ac,assertNonNullable as sr,combine as nr,ErrorCategory as ct,filter as Ln,filterChanged as Na,flattenObject as Fa,fromEvent as Et,getTraceSubscriptionMethod as FD,interval as sc,isNonNullable as qa,isNullable as Qy,map as or,merge as Si,now as nc,Subject as Mn,Subscription as Gy,tap as qD,throttle as UD,ValueSubject as re}from"@vkontakte/videoplayer-shared/es2015";var Tn=O(qe(),1),rr=O(Nt(),1),In=O(Al(),1);var uM=(a,e={})=>{let i=e.timeout||1,r=performance.now();return window.setTimeout(()=>{a({get didTimeout(){return e.timeout?!1:performance.now()-r-1>i},timeRemaining(){return Math.max(0,1+(performance.now()-r))}})},1)},lM=a=>window.clearTimeout(a),IS=a=>typeof a=="function"&&(a==null?void 0:a.toString().endsWith("{ [native code] }")),ES=!IS(window.requestIdleCallback)||!IS(window.cancelIdleCallback),Ml=ES?uM:window.requestIdleCallback,sa=ES?lM:window.cancelIdleCallback;var My=O(Js(),1);import{assertNever as cM,ErrorCategory as xS,Subject as PS}from"@vkontakte/videoplayer-shared/es2015";var dM=18,wS=!1;try{wS=U.browser.isSafari&&!!U.browser.safariVersion&&U.browser.safariVersion<=dM}catch(a){console.error(a)}var Dl=class{constructor(e){this.bufferFull$=new PS;this.error$=new PS;this.queue=[];this.currentTask=null;this.destroyed=!1;this.abortRequested=!1;this.completeTask=()=>{var e;try{if(this.currentTask){let t=(e=this.currentTask.signal)==null?void 0:e.aborted;this.currentTask.callback(!t),this.currentTask=null}this.queue.length&&this.pull()}catch(t){this.error$.next({id:"BufferTaskQueueUnknown",category:xS.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:t})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}append(e,t){return E(this,null,function*(){return t&&t.aborted?!1:new Promise(i=>{let r={operation:"append",data:e,signal:t,callback:i};this.queue.push(r),this.pull()})})}remove(e,t,i){return E(this,null,function*(){return i&&i.aborted?!1:new Promise(r=>{let s={operation:"remove",from:e,to:t,signal:i,callback:r};this.queue.unshift(s),this.pull()})})}abort(e){return E(this,null,function*(){return new Promise(t=>{let i,r=s=>{this.abortRequested=!1,t(s)};wS&&e?i={operation:"safariAbort",init:e,callback:r}:i={operation:"abort",callback:r};for(let{callback:s}of this.queue)s(!1);this.abortRequested=!0,i&&(this.queue=[i]),this.pull()})})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){var r;if((this.buffer.updating||this.currentTask||this.destroyed)&&!this.abortRequested)return;let e=this.queue.shift();if(!e)return;if((r=e.signal)!=null&&r.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(s){s instanceof DOMException&&s.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):s instanceof DOMException&&s.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:xS.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:cM(t)}}},AS=Dl;var Cl=a=>{let e=0;for(let t=0;t<a.length;t++)e+=a.end(t)-a.start(t);return e*1e3};import{abortable as jt,assertNonNullable as De,ErrorCategory as It,fromEvent as Xl,getExponentialDelay as Jl,isNonNullable as ir,isNullable as Se,now as yn,once as AD,Subject as kD,Subscription as RD,ValueSubject as bi}from"@vkontakte/videoplayer-shared/es2015";var G=class{constructor(e,t){this.cursor=0;this.source=e,this.boxParser=t,this.children=[];let i=this.readUint32();this.type=this.readString(4),this.size32=i<=e.buffer.byteLength-e.byteOffset?i:NaN;let r=this.size32?this.size32-8:void 0,s=e.byteOffset+this.cursor;this.size64=0,this.usertype=0,this.content=new DataView(e.buffer,s,r)}get id(){return this.type}get size(){return this.size32}scanForBoxes(e){return this.boxParser.parse(e)}readString(e,t="ascii"){let r=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,r}readUint8(){let e=this.source.getUint8(this.cursor);return this.cursor+=1,e}readUint16(){let e=this.source.getUint16(this.cursor);return this.cursor+=2,e}readUint32(){let e=this.source.getUint32(this.cursor);return this.cursor+=4,e}readUint64(){let e=this.source.getBigInt64(this.cursor);return this.cursor+=8,e}};var er=class extends G{};var na=class extends G{constructor(t,i){super(t,i);this.ondemandPrefix="ondemandlivejson";this.ondemandDataReceivedKey="t-in";this.ondemandDataPreparedKey="t-out";let r=this.content.byteOffset,s=r+this.content.byteLength,n=new TextDecoder("ascii").decode(this.content.buffer.slice(r,s)).split(this.ondemandPrefix)[1],o=JSON.parse(n);this.serverDataReceivedTimestamp=o[this.ondemandDataReceivedKey],this.serverDataPreparedTime=o[this.ondemandDataPreparedKey]}};var oa=class extends G{constructor(e,t){super(e,t),this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let i=this.size-this.cursor;for(;i;){let r=this.readString(4);this.compatibleBrands.push(r),i-=4}}};var ua=class extends G{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ie=class extends G{constructor(e,t){super(e,t);let i=this.readUint32();this.version=i>>>24,this.flags=i&16777215}};var la=class extends ie{constructor(e,t){super(e,t),this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.timescale=this.readUint32(),this.duration=this.readUint32(),this.rate=this.readUint32(),this.volume=this.readUint16()}};var ca=class extends G{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var da=class extends G{constructor(e,t){super(e,t),this.data=this.content}};var mi=class extends ie{get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e,t){super(e,t),this.segments=[],this.referenceId=this.readUint32(),this.timescale=this.readUint32(),this.earliestPresentationTime32=this.readUint32(),this.firstOffset32=this.readUint32(),this.earliestPresentationTime64=0,this.firstOffset64=0,this.referenceCount=this.readUint32()&65535;for(let i=0;i<this.referenceCount;i++){let r=this.readUint32(),s=r>>>31,n=r<<1>>>1,o=this.readUint32();r=this.readUint32();let u=r>>>28,l=r<<3>>>3;this.segments.push({referenceType:s,referencedSize:n,subsegmentDuration:o,SAPType:u,SAPDeltaTime:l})}}};var pa=class extends G{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ha=class extends G{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ma=class extends ie{constructor(e,t){switch(super(e,t),this.readUint8()){case 0:this.stereoMode=0;break;case 1:this.stereoMode=1;break;case 2:this.stereoMode=2;break;case 3:this.stereoMode=3;break;case 4:this.stereoMode=4;break}this.cursor+=1}};var fa=class extends ie{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var ba=class extends ie{constructor(e,t){super(e,t),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}};var ga=class extends G{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var va=class extends ie{constructor(e,t){super(e,t),this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.trackId=this.readUint32(),this.cursor+=4,this.duration=this.readUint32(),this.cursor+=8,this.layer=this.readUint16(),this.alternateGroup=this.readUint16(),this.cursor+=2,this.cursor+=2,this.matrix=[[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()]],this.width=this.readUint32(),this.height=this.readUint32()}};var Sa=class extends G{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ya=class extends G{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ta=class extends ie{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var Ia=class extends G{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ea=class extends ie{constructor(e,t){super(e,t),this.trackId=this.readUint32(),this.flags&1&&(this.baseDataOffset=this.readUint64()),this.flags&2&&(this.sampleDescriptionIndex=this.readUint32()),this.flags&8&&(this.defaultSampleDuration=this.readUint32()),this.flags&16&&(this.defaultSampleSize=this.readUint32()),this.flags&32&&(this.defaultSampleFlags=this.readUint32())}};var xa=class extends ie{constructor(t,i){super(t,i);this.baseMediaDecodeTime32=0;this.baseMediaDecodeTime64=BigInt(0);this.version===1?this.baseMediaDecodeTime64=this.readUint64():this.baseMediaDecodeTime32=this.readUint32()}get baseMediaDecodeTime(){return this.version===1?this.baseMediaDecodeTime64:this.baseMediaDecodeTime32}};var Pa=class extends ie{constructor(t,i){super(t,i);this.sampleDuration=[];this.sampleSize=[];this.sampleFlags=[];this.sampleCompositionTimeOffset=[];this.optionalFields=0;this.sampleCount=this.readUint32(),this.flags&1&&(this.dataOffset=this.readUint32()),this.flags&4&&(this.firstSampleFlags=this.readUint32());for(let r=0;r<this.sampleCount;r++)this.flags&256&&this.sampleDuration.push(this.readUint32()),this.flags&512&&this.sampleSize.push(this.readUint32()),this.flags&1024&&this.sampleFlags.push(this.readUint32()),this.flags&2048&&this.sampleCompositionTimeOffset.push(this.readUint32())}};var wa=class extends G{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Aa=class extends ie{constructor(e,t){super(e,t),this.entryCount=this.readUint32(),this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+8,this.content.byteLength-8))}};var ka=class extends G{constructor(e,t){super(e,t),this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+78,this.content.byteLength-78))}};var hM={ftyp:oa,moov:ua,mvhd:la,moof:ca,mdat:da,sidx:mi,trak:pa,mdia:ga,mfhd:Ta,tkhd:va,traf:Ia,tfhd:Ea,tfdt:xa,trun:Pa,minf:Sa,sv3d:ha,st3d:ma,prhd:fa,proj:ya,equi:ba,uuid:na,stbl:wa,stsd:Aa,avc1:ka,unknown:er},yt=class a{constructor(e={}){this.options=w({offset:0},e)}parse(e){let t=[],i=this.options.offset;for(;i<e.byteLength;)try{let s=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+i+4,4)),n=this.createBox(s,new DataView(e.buffer,e.byteOffset+i));if(!n.size)break;t.push(n),i+=n.size}catch(r){break}return t}createBox(e,t){let i=hM[e];return i?new i(t,new a):new er(t,new a)}};var Ht=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{var i,r,s;(s=(i=this.index)[r=t.type])!=null||(i[r]=[]),this.index[t.type].push(t),t.children.length>0&&this.indexBoxLevel(t.children)})}find(e){return this.index[e]&&this.index[e][0]?this.index[e][0]:null}findAll(e){return this.index[e]||[]}};var fM=new TextDecoder("ascii"),bM=a=>fM.decode(new DataView(a.buffer,a.byteOffset+4,4))==="ftyp",gM=a=>{let e=new mi(a,new yt),t=e.earliestPresentationTime/e.timescale*1e3,i=a.byteOffset+a.byteLength+e.firstOffset;return e.segments.map(s=>{if(s.referenceType!==0)throw new Error("Unsupported multilevel sidx");let n=s.subsegmentDuration/e.timescale*1e3,o={status:"none",time:{from:t,to:t+n},byte:{from:i,to:i+s.referencedSize-1}};return t+=n,i+=s.referencedSize,o})},vM=(a,e)=>{let i=new yt().parse(a),r=new Ht(i),s=r.findAll("moof"),n=e?r.findAll("uuid"):r.findAll("mdat");if(!(n.length&&s.length))return null;let o=s[0],u=n[n.length-1],l=o.source.byteOffset,d=u.source.byteOffset-o.source.byteOffset+u.size;return new DataView(a.buffer,l,d)},SM=a=>{let t=new yt().parse(a),i=new Ht(t),r={},s=i.findAll("uuid");return s.length?s[s.length-1]:r},yM=a=>{var r;let t=new yt().parse(a);return(r=new Ht(t).find("sidx"))==null?void 0:r.timescale},TM=(a,e)=>{let i=new yt().parse(a),s=new Ht(i).findAll("traf"),n=s[s.length-1].children.find(d=>d.type==="tfhd"),o=s[s.length-1].children.find(d=>d.type==="tfdt"),u=s[s.length-1].children.find(d=>d.type==="trun"),l=0;return u.sampleDuration.length?l=u.sampleDuration.reduce((d,h)=>d+h,0):l=n.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+l)/e*1e3},IM=a=>{let e={is3dVideo:!1,stereoMode:0,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}},i=new yt().parse(a),r=new Ht(i);if(r.find("sv3d")){e.is3dVideo=!0;let n=r.find("st3d");n&&(e.stereoMode=n.stereoMode);let o=r.find("prhd");o&&(e.projectionData.pose.yaw=o.poseYawDegrees,e.projectionData.pose.pitch=o.posePitchDegrees,e.projectionData.pose.roll=o.poseRollDegrees);let u=r.find("equi");u&&(e.projectionData.bounds.top=u.projectionBoundsTop,e.projectionData.bounds.right=u.projectionBoundsRight,e.projectionData.bounds.bottom=u.projectionBoundsBottom,e.projectionData.bounds.left=u.projectionBoundsLeft)}return e},kS={validateData:bM,parseInit:IM,getIndexRange:()=>{},parseSegments:gM,parseFeedableSegmentChunk:vM,getChunkEndTime:TM,getServerLatencyTimestamps:SM,getTimescaleFromIndex:yM};var $a=O(qe(),1);import{assertNonNullable as Ol,isNonNullable as MS,isNullable as xM}from"@vkontakte/videoplayer-shared/es2015";import{assertNever as EM}from"@vkontakte/videoplayer-shared/es2015";var RS={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"}},$S=a=>{let e=a.getUint8(0),t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);let i=Ra(a,t),r=i in RS,s=r?RS[i].type:"binary",n=a.getUint8(t),o=0;n&128?o=1:n&64?o=2:n&32?o=3:n&16?o=4:n&8?o=5:n&4?o=6:n&2?o=7:n&1&&(o=8);let u=new DataView(a.buffer,a.byteOffset+t+1,o-1),l=n&255>>o,c=Ra(u),d=l*at(2,(o-1)*8)+c,h=t+o,p;return h+d>a.byteLength?p=new DataView(a.buffer,a.byteOffset+h):p=new DataView(a.buffer,a.byteOffset+h,d),{tag:r?i:"0x"+i.toString(16).toUpperCase(),type:s,tagHeaderSize:h,tagSize:h+d,value:p,valueSize:d}},Ra=(a,e=a.byteLength)=>{switch(e){case 1:return a.getUint8(0);case 2:return a.getUint16(0);case 3:return a.getUint8(0)*at(2,16)+a.getUint16(1);case 4:return a.getUint32(0);case 5:return a.getUint8(0)*at(2,32)+a.getUint32(1);case 6:return a.getUint16(0)*at(2,32)+a.getUint32(2);case 7:{let t=a.getUint8(0)*281474976710656+a.getUint16(1)*4294967296+a.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},Ze=(a,e)=>{switch(e){case"int":return a.getInt8(0);case"uint":return Ra(a);case"float":return a.byteLength===4?a.getFloat32(0):a.getFloat64(0);case"string":return new TextDecoder("ascii").decode(a);case"utf8":return new TextDecoder("utf-8").decode(a);case"date":return new Date(Date.UTC(2001,0)+a.getInt8(0)).getTime();case"master":return a;case"binary":return a;default:EM(e)}},fi=(a,e)=>{let t=0;for(;t<a.byteLength;){let i=new DataView(a.buffer,a.byteOffset+t),r=$S(i);if(!e(r))return;r.type==="master"&&fi(r.value,e),t=r.value.byteOffset-a.byteOffset+r.valueSize}},LS=a=>{if(a.getUint32(0)!==440786851)return!1;let e,t,i,r=$S(a);return fi(r.value,({tag:s,type:n,value:o})=>(s===17143?e=Ze(o,n):s===17026?t=Ze(o,n):s===17029&&(i=Ze(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)};var DS=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],PM=[231,22612,22743,167,171,163,160,175],wM=a=>{let e,t,i,r,s=!1,n=!1,o=!1,u,l,c=!1,d=0;return fi(a,({tag:h,type:p,value:m,valueSize:b})=>{if(h===21419){let g=Ze(m,p);l=Ra(g)}else h!==21420&&(l=void 0);return h===408125543?(e=m.byteOffset,t=m.byteOffset+b):h===357149030?s=!0:h===290298740?n=!0:h===2807729?i=Ze(m,p):h===17545?r=Ze(m,p):h===21420&&l===475249515?u=Ze(m,p):h===374648427?fi(m,({tag:g,type:v,value:S})=>g===30321?(c=Ze(S,v)===1,!1):!0):s&&n&&(0,$a.default)(DS,h)&&(o=!0),!o}),Ol(e,"Failed to parse webm Segment start"),Ol(t,"Failed to parse webm Segment end"),Ol(r,"Failed to parse webm Segment duration"),i=i!=null?i:1e6,{segmentStart:Math.round(e/1e9*i*1e3),segmentEnd:Math.round(t/1e9*i*1e3),timeScale:i,segmentDuration:Math.round(r/1e9*i*1e3),cuesSeekPosition:u,is3dVideo:c,stereoMode:d,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},AM=a=>{if(xM(a.cuesSeekPosition))return;let e=a.segmentStart+a.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},kM=(a,e)=>{let t=!1,i=!1,r=o=>MS(o.time)&&MS(o.position),s=[],n;return fi(a,({tag:o,type:u,value:l})=>{switch(o){case 475249515:t=!0;break;case 187:n&&r(n)&&s.push(n),n={};break;case 179:n&&(n.time=Ze(l,u));break;case 183:break;case 241:n&&(n.position=Ze(l,u));break;default:t&&(0,$a.default)(DS,o)&&(i=!0)}return!(t&&i)}),n&&r(n)&&s.push(n),s.map((o,u)=>{let{time:l,position:c}=o,d=s[u+1];return{status:"none",time:{from:l,to:d?d.time:e.segmentDuration},byte:{from:e.segmentStart+c,to:d?e.segmentStart+d.position-1:e.segmentEnd-1}}})},RM=a=>{let e=0,t=!1;try{fi(a,i=>i.tag===524531317?i.tagSize<=a.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):(0,$a.default)(PM,i.tag)?(e+i.tagSize<=a.byteLength&&(e+=i.tagSize,t||(t=(0,$a.default)([163,160,175],i.tag))),!0):!1)}catch(i){}return e>0&&e<=a.byteLength&&t?new DataView(a.buffer,a.byteOffset,e):null},CS={validateData:LS,parseInit:wM,getIndexRange:AM,parseSegments:kM,parseFeedableSegmentChunk:RM};var La=a=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(a);if(e){let[,t,i]=e;if(t==="audio"||t==="video")switch(i){case"webm":return CS;case"mp4":return kS}}throw new ReferenceError(`Unsupported mime type ${a}`)};var Yl=O(ey(),1),wy=O(_i(),1),Ay=O(by(),1),ky=O(Nt(),1),zl=O(zi(),1);var gy=O(qe(),1),Ul=a=>{let e=a.split("."),[t,...i]=e;if(!t)return!1;switch(t){case"av01":{let[r,s,n]=i;return!!(n&&parseInt(n,10)>8)}case"vp09":{let[r,s,n]=i;return!!(r&&parseInt(r,10)>=2&&n&&parseInt(n,10)>8)}case"avc1":{let r=i[0];if(!r||r.length!==6)return!1;let[s,n]=r.toUpperCase(),o=s+n;return(0,gy.default)(["6E","7A","F4"],o)}}return!1};import{isNonNullable as wD,isNullable as xy}from"@vkontakte/videoplayer-shared/es2015";var vy=a=>{if(a.includes("/")){let e=a.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(a)};var Sy=a=>{var e;try{let t=xD(),i=a.match(t),{groups:r}=i!=null?i:{};if(r){let s={};if(r.extensions){let u=r.extensions.toLowerCase().match(/(?:[0-9a-wy-z](?:-[a-z0-9]{2,8})+)/g);Array.from(u||[]).forEach(l=>{s[l[0]]=l.slice(2)})}let n=(e=r.variants)==null?void 0:e.split(/-/).filter(u=>u!==""),o={extlang:r.extlang,langtag:r.langtag,language:r.language,privateuse:r.privateuse||r.privateuse2,region:r.region,script:r.script,extensions:s,variants:n};return Object.keys(o).forEach(u=>{let l=o[u];(typeof l=="undefined"||l==="")&&delete o[u]}),o}return null}catch(t){return null}};function xD(){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 Ul=O(Nt(),1);import{videoSizeToQuality as ED}from"@vkontakte/videoplayer-shared/es2015";var gy=({id:a,width:e,height:t,bitrate:i,fps:r,quality:s,streamId:n})=>{var u;let o=(u=s?Bt(s):void 0)!=null?u:ED({width:e,height:t});return o&&{id:a,quality:o,bitrate:i,size:{width:e,height:t},fps:r,streamId:n}},vy=({id:a,bitrate:e})=>({id:a,bitrate:e}),Sy=({language:a,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:a,label:e}),yy=({language:a,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:a,label:e}),Hl=({id:a,language:e,label:t,codecs:i,isDefault:r})=>({id:a,language:e,label:t,codec:(0,Ul.default)(i.split("."),0),isDefault:r}),jl=({id:a,language:e,label:t,hdr:i,codecs:r})=>({id:a,language:e,hdr:i,label:t,codec:(0,Ul.default)(r.split("."),0)}),Ql=a=>"url"in a,xe=a=>a.type==="template",La=a=>a instanceof DOMException&&(a.name==="AbortError"||a.code===20);var Iy=a=>{if(!(a!=null&&a.startsWith("P")))return;let e=(n,o)=>{let u=n?parseFloat(n.replace(",",".")):NaN;return(isNaN(u)?0:u)*o},i=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(a),r=(i==null?void 0:i[1])==="-"?-1:1,s={days:e(i==null?void 0:i[5],r),hours:e(i==null?void 0:i[6],r),minutes:e(i==null?void 0:i[7],r),seconds:e(i==null?void 0:i[8],r)};return s.days*24*60*60*1e3+s.hours*60*60*1e3+s.minutes*60*1e3+s.seconds*1e3},yt=(a,e)=>{let t=a;t=(0,Gl.default)(t,"$$","$");let i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[r,s]of(0,Ey.default)(i)){let n=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=(0,Gl.default)(t,n,(o,u)=>Ty(s)?o:Ty(u)?s:(0,xy.default)(s,parseInt(u,10),"0"))}return t},wy=(a,e)=>{var K,x,j,L,Q,N,Z,R,C,X,P,M,me,Ti,dt,Y,ye,Pe,we,tt,pt,Pt,zt,Ii,cr,Mc,Dc,Cc,Vc,Oc,_c,Bc,Nc,Fc,qc,Uc,Hc,jc,Qc,Gc,Wc,Yc,zc,Kc,Xc,Jc,Zc,ed,td,id,rd,ad,sd,nd,od,ud,ld,cd,dd,pd,hd;let i=new DOMParser().parseFromString(a,"application/xml"),r={video:[],audio:[],text:[]},s=i.children[0],n=Array.from(s.querySelectorAll("MPD > BaseURL").values()).map(Qe=>{var te,Kt;return(Kt=(te=Qe.textContent)==null?void 0:te.trim())!=null?Kt:""}),o=(K=(0,Py.default)(n,0))!=null?K:"",u=s.getAttribute("type")==="dynamic",l=s.getAttribute("availabilityStartTime"),c=s.getAttribute("publishTime"),d=s.getElementsByTagName("vk:Attrs")[0],h=d==null?void 0:d.getElementsByTagName("vk:XLatestSegmentPublishTime")[0].textContent,p=d==null?void 0:d.getElementsByTagName("vk:XStreamIsLive")[0].textContent,m=d==null?void 0:d.getElementsByTagName("vk:XStreamIsUnpublished")[0].textContent,b=d==null?void 0:d.getElementsByTagName("vk:XPlaybackDuration")[0].textContent,g;u&&(g={availabilityStartTime:l?new Date(l).getTime():0,publishTime:c?new Date(c).getTime():0,latestSegmentPublishTime:h?new Date(h).getTime():0,streamIsAlive:p==="yes",streamIsUnpublished:m==="yes"});let v,S=s.getAttribute("mediaPresentationDuration"),y=[...s.getElementsByTagName("Period")],I=y.reduce((Qe,te)=>D(w({},Qe),{[te.id]:te.children}),{}),T=y.reduce((Qe,te)=>D(w({},Qe),{[te.id]:te.getAttribute("duration")}),{});S?v=Iy(S):(0,Wl.default)(T).filter(Qe=>Qe).length&&!u?v=(0,Wl.default)(T).reduce((Qe,te)=>{var Kt;return Qe+((Kt=Iy(te))!=null?Kt:0)},0):b&&(v=parseInt(b,10));let $=0,F=(j=(x=s.getAttribute("profiles"))==null?void 0:x.split(","))!=null?j:[];for(let Qe of y.map(te=>te.id))for(let te of I[Qe]){let Kt=(L=te.getAttribute("id"))!=null?L:"id"+($++).toString(10),dr=(Q=te.getAttribute("mimeType"))!=null?Q:"",Jn=(N=te.getAttribute("codecs"))!=null?N:"",Zn=(Z=te.getAttribute("contentType"))!=null?Z:dr==null?void 0:dr.split("/")[0],zT=(C=(R=te.getAttribute("profiles"))==null?void 0:R.split(","))!=null?C:[],md=(P=by((X=te.getAttribute("lang"))!=null?X:""))!=null?P:{},es=(Ti=(me=(M=te.querySelector("Label"))==null?void 0:M.textContent)==null?void 0:me.trim())!=null?Ti:void 0,KT=te.querySelectorAll("Representation"),XT=te.querySelector("SegmentTemplate"),JT=(Y=(dt=te.querySelector("Role"))==null?void 0:dt.getAttribute("value"))!=null?Y:void 0,Ei=Zn,se={id:Kt,language:md.language,isDefault:JT==="main",label:es,codecs:Jn,hdr:Ei==="video"&&Fl(Jn),mime:dr,representations:[]};for(let ee of KT){let wt=(ye=ee.getAttribute("lang"))!=null?ye:void 0,pr=(we=(Pe=es!=null?es:te.getAttribute("label"))!=null?Pe:ee.getAttribute("label"))!=null?we:void 0,ts=(Pt=(pt=(tt=ee.querySelector("BaseURL"))==null?void 0:tt.textContent)==null?void 0:pt.trim())!=null?Pt:"",Xt=new URL(ts||o,e).toString(),kt=(zt=ee.getAttribute("mimeType"))!=null?zt:dr,is=(cr=(Ii=ee.getAttribute("codecs"))!=null?Ii:Jn)!=null?cr:"",rs;if(Zn==="text"){let At=ee.getAttribute("id")||"",as=((Mc=md.privateuse)==null?void 0:Mc.includes("x-auto"))||At.includes("_auto"),Jt=ee.querySelector("SegmentTemplate");if(Jt){let hr={representationId:(Dc=ee.getAttribute("id"))!=null?Dc:void 0,bandwidth:(Cc=ee.getAttribute("bandwidth"))!=null?Cc:void 0},ss=parseInt((Vc=ee.getAttribute("bandwidth"))!=null?Vc:"",10)/1e3,ns=(_c=parseInt((Oc=Jt.getAttribute("startNumber"))!=null?Oc:"",10))!=null?_c:1,xi=parseInt((Bc=Jt.getAttribute("timescale"))!=null?Bc:"",10),eo=(Nc=Jt.querySelectorAll("SegmentTimeline S"))!=null?Nc:[],Pi=Jt.getAttribute("media");if(!Pi)continue;let os=[],us=0,ls="",wi=0,mr=ns,Te=0;for(let Ge of eo){let Zt=parseInt((Fc=Ge.getAttribute("d"))!=null?Fc:"",10),Fe=parseInt((qc=Ge.getAttribute("r"))!=null?qc:"",10)||0,Rt=parseInt((Uc=Ge.getAttribute("t"))!=null?Uc:"",10);Te=Number.isFinite(Rt)?Rt:Te;let ei=Zt/xi*1e3,$t=Te/xi*1e3;for(let it=0;it<Fe+1;it++){let Lt=yt(Pi,D(w({},hr),{segmentNumber:mr.toString(10),segmentTime:(Te+it*Zt).toString(10)})),ki=($t!=null?$t:0)+it*ei,br=ki+ei;mr++,os.push({time:{from:ki,to:br},url:Lt})}Te+=(Fe+1)*Zt,us+=(Fe+1)*ei}wi=Te/xi*1e3,ls=yt(Pi,D(w({},hr),{segmentNumber:mr.toString(10),segmentTime:Te.toString(10)}));let fr={time:{from:wi,to:1/0},url:ls},ht={type:"template",baseUrl:Xt,segmentTemplateUrl:Pi,initUrl:"",totalSegmentsDurationMs:us,segments:os,nextSegmentBeyondManifest:fr,timescale:xi};rs={id:At,kind:"text",segmentReference:ht,profiles:[],duration:v,bitrate:ss,mime:"",codecs:"",width:0,height:0,isAuto:as}}else rs={id:At,isAuto:as,kind:"text",url:Xt}}else{let At=(jc=(Hc=ee.getAttribute("contentType"))!=null?Hc:kt==null?void 0:kt.split("/")[0])!=null?jc:Zn,as=(Gc=(Qc=te.getAttribute("profiles"))==null?void 0:Qc.split(","))!=null?Gc:[],Jt=parseInt((Wc=ee.getAttribute("width"))!=null?Wc:"",10),hr=parseInt((Yc=ee.getAttribute("height"))!=null?Yc:"",10),ss=parseInt((zc=ee.getAttribute("bandwidth"))!=null?zc:"",10)/1e3,ns=(Kc=ee.getAttribute("frameRate"))!=null?Kc:"",xi=(Xc=ee.getAttribute("quality"))!=null?Xc:void 0,eo=ns?fy(ns):void 0,Pi=(Jc=ee.getAttribute("id"))!=null?Jc:"id"+($++).toString(10),os=At==="video"?`${hr}p`:At==="audio"?`${ss}Kbps`:is,us=`${Pi}@${os}`,ls=[...F,...zT,...as],wi,mr=ee.querySelector("SegmentBase"),Te=(Zc=ee.querySelector("SegmentTemplate"))!=null?Zc:XT;if(mr){let ht=(td=(ed=ee.querySelector("SegmentBase Initialization"))==null?void 0:ed.getAttribute("range"))!=null?td:"",[Ge,Zt]=ht.split("-").map(Lt=>parseInt(Lt,10)),Fe={from:Ge,to:Zt},Rt=(id=ee.querySelector("SegmentBase"))==null?void 0:id.getAttribute("indexRange"),[ei,$t]=Rt?Rt.split("-").map(Lt=>parseInt(Lt,10)):[],it=Rt?{from:ei,to:$t}:void 0;wi={type:"byteRange",url:Xt,initRange:Fe,indexRange:it}}else if(Te){let ht={representationId:(rd=ee.getAttribute("id"))!=null?rd:void 0,bandwidth:(ad=ee.getAttribute("bandwidth"))!=null?ad:void 0},Ge=parseInt((sd=Te.getAttribute("timescale"))!=null?sd:"",10),Zt=(nd=Te.getAttribute("initialization"))!=null?nd:"",Fe=Te.getAttribute("media"),Rt=(ud=parseInt((od=Te.getAttribute("startNumber"))!=null?od:"",10))!=null?ud:1,ei=yt(Zt,ht);if(!Fe)throw new ReferenceError("No media attribute in SegmentTemplate");let $t=(ld=Te.querySelectorAll("SegmentTimeline S"))!=null?ld:[],it=[],Lt=0,ki="",br=0;if($t.length){let cs=Rt,We=0;for(let Ai of $t){let rt=parseInt((cd=Ai.getAttribute("d"))!=null?cd:"",10),ti=parseInt((dd=Ai.getAttribute("r"))!=null?dd:"",10)||0,ds=parseInt((pd=Ai.getAttribute("t"))!=null?pd:"",10);We=Number.isFinite(ds)?ds:We;let to=rt/Ge*1e3,io=We/Ge*1e3;for(let ps=0;ps<ti+1;ps++){let eI=yt(Fe,D(w({},ht),{segmentNumber:cs.toString(10),segmentTime:(We+ps*rt).toString(10)})),fd=(io!=null?io:0)+ps*to,tI=fd+to;cs++,it.push({time:{from:fd,to:tI},url:eI})}We+=(ti+1)*rt,Lt+=(ti+1)*to}br=We/Ge*1e3,ki=yt(Fe,D(w({},ht),{segmentNumber:cs.toString(10),segmentTime:We.toString(10)}))}else if(xD(v)){let We=parseInt((hd=Te.getAttribute("duration"))!=null?hd:"",10)/Ge*1e3,Ai=Math.ceil(v/We),rt=0;for(let ti=1;ti<Ai;ti++){let ds=yt(Fe,D(w({},ht),{segmentNumber:ti.toString(10),segmentTime:rt.toString(10)}));it.push({time:{from:rt,to:rt+We},url:ds}),rt+=We}br=rt,ki=yt(Fe,D(w({},ht),{segmentNumber:Ai.toString(10),segmentTime:rt.toString(10)}))}let ZT={time:{from:br,to:1/0},url:ki};wi={type:"template",baseUrl:Xt,segmentTemplateUrl:Fe,initUrl:ei,totalSegmentsDurationMs:Lt,segments:it,nextSegmentBeyondManifest:ZT,timescale:Ge}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!At||!kt)continue;let fr={video:"video",audio:"audio",text:"text"}[At];if(!fr)continue;Ei||(Ei=fr),rs={id:us,kind:fr,segmentReference:wi,profiles:ls,duration:v,bitrate:ss,mime:kt,codecs:is,width:Jt,height:hr,fps:eo,quality:xi}}se.language||(se.language=wt),se.label||(se.label=pr),se.mime||(se.mime=kt),se.codecs||(se.codecs=is),se.hdr||(se.hdr=Ei==="video"&&Fl(is)),se.representations.push(rs)}if(Ei){let ee=r[Ei].find(wt=>wt.id===se.id);if(ee&&se.representations.every(wt=>xe(wt.segmentReference)))for(let wt of ee.representations){let pr=se.representations.find(kt=>kt.id===wt.id),ts=pr==null?void 0:pr.segmentReference,Xt=wt.segmentReference;Xt.segments.push(...ts.segments),Xt.nextSegmentBeyondManifest=ts.nextSegmentBeyondManifest}else r[Ei].push(se)}}return{duration:v,streams:r,baseUrls:n,live:g}};var Ay=O(qe(),1);import{isNonNullable as ky}from"@vkontakte/videoplayer-shared/es2015";var oe=(a,e)=>ky(a)&&ky(e)&&a.readyState==="open"&&(0,Ay.default)([...a.activeSourceBuffers],e);var Ma=class{constructor(e,t,i,{fetcher:r,tuning:s,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new bi(0);this.currentLowLatencySegmentLength$=new bi(0);this.currentSegmentLength$=new bi(0);this.onLastSegment$=new bi(!1);this.fullyBuffered$=new bi(!1);this.playingRepresentation$=new bi(void 0);this.playingRepresentationInit$=new bi(void 0);this.error$=new wD;this.gaps=[];this.subscription=new kD;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new ve;this.switchAbortController=new ve;this.destroyAbortController=new ve;this.bufferLimit=1/0;this.failedDownloads=0;this.baseUrls=[];this.baseUrlsIndex=0;this.isLive=!1;this.liveUpdateSegmentIndex=0;this.liveInitialAdditionalOffset=0;this.isSeekingLive=!1;this.index=0;this.lastDataObtainedTimestampMs=0;this.loadByteRangeSegmentsTimeoutId=0;this.startWith=jt(this.destroyAbortController.signal,function(e){return ue(this,null,function*(){let t=this.representations.get(e);De(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new xS(this.sourceBuffer),this.subscription.add(zl(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let o,u=this.mediaSource.readyState;u!=="open"&&(o={id:`SegmentEjection_source_${u}`,category:Tt.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o!=null||(o={id:"SegmentEjection",category:Tt.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),this.error$.next(o)})),this.subscription.add(zl(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:Tt.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o||!oe(this.mediaSource,this.sourceBuffer))return;let u=Math.min(this.bufferLimit,Ml(this.sourceBuffer.buffered)*.8);this.bufferLimit=u;let l=this.getForwardBufferDuration(o),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(o,n*2,l<c).catch(d=>{this.handleAsyncError(d,"pruneBuffer")})})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(n=>this.error$.next(n))),yield this.loadInit(t,"high",!0);let i=this.initData.get(t.id),r=this.segments.get(t.id),s=this.parsedInitData.get(t.id);De(i,"No init buffer for starting representation"),De(r,"No segments for starting representation"),i instanceof ArrayBuffer&&(this.searchGaps(r,t),yield this.sourceBufferTaskQueue.append(i,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(s))})}.bind(this));this.switchTo=jt(this.destroyAbortController.signal,function(e,t=!1){return ue(this,null,function*(){if(!oe(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);De(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if(Se(s)||Se(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),De(r,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!oe(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer();else{let n=this.getCurrentPosition();ir(n)&&!this.isLive&&(this.bufferLimit=1/0,yield new ms(this.pruneBuffer(n,1/0,!0))),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}this.maintain()}})}.bind(this));this.switchToOld=jt(this.destroyAbortController.signal,function(e,t=!1){return ue(this,null,function*(){if(!oe(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);De(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if(Se(s)||Se(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),De(r,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!oe(this.mediaSource,this.sourceBuffer)))if(yield this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer(),this.maintain();else{let n=this.getCurrentPosition();ir(n)&&(this.isLive||(this.bufferLimit=1/0,yield new ms(this.pruneBuffer(n,1/0,!0))),this.maintain(n)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}})}.bind(this));this.seekLive=jt(this.destroyAbortController.signal,function(e){return ue(this,null,function*(){var u,l;let t=(u=(0,yn.default)(e,c=>c.representations))!=null?u:[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let c of this.representations.keys()){let d=t.find(m=>m.id===c);d&&this.representations.set(c,d);let h=this.representations.get(c);if(!h||!xe(h.segmentReference))return;let p=this.getActualLiveStartingSegments(h.segmentReference);this.segments.set(h.id,p)}let i=(l=this.switchingToRepresentationId)!=null?l:this.downloadingRepresentationId,r=this.representations.get(i);De(r);let s=this.segments.get(i);De(s,"No segments for starting representation");let n=this.initData.get(i);if(De(n,"No init buffer for starting representation"),!(n instanceof ArrayBuffer))return;let o=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,yield this.abort(),o&&(yield this.sourceBufferTaskQueue.remove(o.from*1e3,o.to*1e3,this.destroyAbortController.signal)),this.searchGaps(s,r),yield this.sourceBufferTaskQueue.append(n,this.destroyAbortController.signal),this.isSeekingLive=!1})}.bind(this));var c;this.fetcher=r,this.tuning=s,this.compatibilityMode=u,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=o,this.isLive=!!(l!=null&&l.live),this.baseUrls=(c=l==null?void 0:l.baseUrls)!=null?c:[],this.initData=new Map(i.map(d=>[d.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(i.map(d=>[d.id,d])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}switchToWithPreviousAbort(e,t=!1){!oe(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new ve,jt(this.switchAbortController.signal,function(i,r=!1){return ue(this,null,function*(){this.switchingToRepresentationId=i;let s=this.representations.get(i);De(s,`No such representation ${i}`);let n=this.segments.get(i),o=this.initData.get(i);if(Se(o)||Se(n)?yield this.loadInit(s,"high",!1):o instanceof Promise&&(yield o),n=this.segments.get(i),De(n,"No segments for starting representation"),o=this.initData.get(i),!(!(o instanceof ArrayBuffer)||!this.sourceBuffer||!oe(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(o,this.downloadAbortController.signal),r)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=i,yield this.dropBuffer();else{let u=this.getCurrentPosition();ir(u)&&!this.isLive&&(this.bufferLimit=this.forwardBufferTarget,yield this.pruneBuffer(u,1/0,!0)),this.downloadingRepresentationId=i,this.switchingToRepresentationId=void 0}this.maintain()}})}.bind(this))(e,t))}warmUpMediaSource(){!Se(this.sourceBuffer)&&!this.sourceBuffer.updating&&(this.sourceBuffer.mode="segments")}abort(){return E(this,null,function*(){for(let e of this.activeSegments)this.abortSegment(e.segment);return this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new ve,this.abortBuffer()})}maintain(e=this.getCurrentPosition()){if(Se(e)||Se(this.downloadingRepresentationId)||Se(this.playingRepresentationId)||Se(this.sourceBuffer)||!oe(this.mediaSource,this.sourceBuffer)||ir(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if(De(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;let r=i.find(c=>e>=c.time.from&&e<c.time.to);ir(r)&&isFinite(r.time.from)&&isFinite(r.time.to)&&this.currentSegmentLength$.next((r==null?void 0:r.time.to)-r.time.from);let s=e,n=100;if(this.playingRepresentationId!==this.downloadingRepresentationId){let c=this.getForwardBufferDuration(e),d=r?r.time.to+n:-1/0;r&&r.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&c>=r.time.to-e+n&&(s=d)}if(isFinite(this.bufferLimit)&&Ml(this.sourceBuffer.buffered)>=this.bufferLimit){let c=this.getForwardBufferDuration(e),d=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,c<d).catch(h=>{this.handleAsyncError(h,"pruneBuffer")});return}let u=[];if(!this.activeSegments.size&&(u=this.selectForwardBufferSegments(i,t.segmentReference.type,s),u.length)){let c="auto";if(this.tuning.dash.useFetchPriorityHints&&r)if((0,Sn.default)(u,r))c="high";else{let d=(0,rr.default)(u,0);d&&d.time.from-r.time.to>=this.forwardBufferTarget/2&&(c="low")}this.loadSegments(u,t,c).catch(d=>{this.handleAsyncError(d,"loadSegments")})}(!this.preloadOnly&&!this.allInitsLoaded&&r&&r.status==="fed"&&!u.length&&this.getForwardBufferDuration(e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let l=(0,rr.default)(i,-1);!this.isLive&&l&&(this.fullyBuffered$.next(l.time.to-e-this.getForwardBufferDuration(e)<n),this.onLastSegment$.next(e-l.time.from>0))}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}searchGaps(e,t){this.gaps=[];let i=0,r=this.isLive?this.liveInitialAdditionalOffset:0;for(let s of e)Math.trunc(s.time.from-i)>0&&this.gaps.push({representation:t.id,from:i,to:s.time.from+r}),i=s.time.to;ir(t.duration)&&t.duration-i>0&&!this.isLive&&this.gaps.push({representation:t.id,from:i,to:t.duration})}getActualLiveStartingSegments(e){let t=e.segments,i=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,r=[],s=0,n=t.length-1;do r.unshift(t[n]),s+=t[n].time.to-t[n].time.from,n--;while(s<i&&n>=0);return this.liveInitialAdditionalOffset=s-i,this.isActiveLowLatency()?[r[0]]:r}getLiveSegmentsToLoadState(e){let t=(0,yn.default)(e==null?void 0:e.streams[this.kind],r=>r.representations).find(r=>r.id===this.downloadingRepresentationId);if(!t)return;let i=this.segments.get(t.id);if(i!=null&&i.length)return{from:i[0].time.from,to:i[i.length-1].time.to}}updateLive(e){var i,r,s,n;let t=(i=(0,yn.default)(e==null?void 0:e.streams[this.kind],o=>o.representations))!=null?i:[];if(![...this.segments.values()].every(o=>!o.length))for(let o of t){if(!o||!xe(o.segmentReference))return;let u=o.segmentReference.segments.map(p=>D(w({},p),{status:"none",size:void 0})),l=100,c=(r=this.segments.get(o.id))!=null?r:[],d=(n=(s=(0,rr.default)(c,-1))==null?void 0:s.time.to)!=null?n:0,h=u==null?void 0:u.findIndex(p=>d>=p.time.from+l&&d<=p.time.to+l);if(h===-1){this.liveUpdateSegmentIndex=0;let p=this.getActualLiveStartingSegments(o.segmentReference);this.segments.set(o.id,p)}else{let p=u.slice(h+1);this.segments.set(o.id,[...c,...p])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;De(e);let t=this.segments.get(e);if(t!=null&&t.length){let i=t[t.length-1];this.updateLowLatencyLiveIfNeeded(i)}}updateLowLatencyLiveIfNeeded(e){var i;let t=0;for(let r of this.representations.values()){let s=r.segmentReference;if(!xe(s))return;let n=(i=this.segments.get(r.id))!=null?i:[],o=n.find(l=>Math.floor(l.time.from)===Math.floor(e.time.from));if(o&&!isFinite(o.time.to)&&(o.time.to=e.time.to,t=o.time.to-o.time.from),!!!n.find(l=>Math.floor(l.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let l=Math.round(e.time.to*s.timescale/1e3).toString(10),c=yt(s.segmentTemplateUrl,{segmentTime:l});n.push({status:"none",time:{from:e.time.to,to:1/0},url:c})}}this.currentLowLatencySegmentLength$.next(t)}findSegmentStartTime(e){var s,n,o;let t=(n=(s=this.switchingToRepresentationId)!=null?s:this.downloadingRepresentationId)!=null?n:this.playingRepresentationId;if(!t)return;let i=this.segments.get(t);if(!i)return;let r=i.find(u=>u.time.from<=e&&u.time.to>=e);return(o=r==null?void 0:r.time.from)!=null?o:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){var e;if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),(e=this.sourceBufferTaskQueue)==null||e.destroy(),this.gapDetectionIdleCallback&&aa&&aa(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&aa&&aa(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer)try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(t){if(!(t instanceof DOMException&&t.name==="NotFoundError"))throw t}this.sourceBuffer=null,this.downloadAbortController.abort(),this.switchAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,i){return this.isLive?this.selectForwardBufferSegmentsLive(e,i):this.selectForwardBufferSegmentsRecord(e,t,i)}selectForwardBufferSegmentsLive(e,t){let i=e.findIndex(r=>t>=r.time.from&&t<r.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=i),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,i){let r=e.findIndex(({status:d,time:{from:h,to:p}},m)=>{let b=h<=i&&p>=i,g=h>i||b||m===0&&i===0,v=Math.min(this.forwardBufferTarget,this.bufferLimit),S=this.preloadOnly&&h<=i+v||p<=i+v;return(d==="none"||d==="partially_ejected"&&g&&S&&this.sourceBuffer&&oe(this.mediaSource,this.sourceBuffer)&&!(Ut(this.sourceBuffer.buffered,h)&&Ut(this.sourceBuffer.buffered,p)))&&g&&S});if(r===-1)return[];if(t!=="byteRange")return e.slice(r,r+1);let s=e,n=0,o=0,u=[],l=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,c=this.preloadOnly?this.forwardBufferTarget:0;for(let d=r;d<s.length&&(n<=l||o<=c);d++){let h=s[d];if(n+=h.byte.to+1-h.byte.from,o+=h.time.to+1-h.time.from,h.status==="none"||h.status==="partially_ejected")u.push(h);else break}return u}loadSegments(e,t,i="auto"){return E(this,null,function*(){xe(t.segmentReference)?yield this.loadTemplateSegment(e[0],t,i):yield this.loadByteRangeSegments(e,t,i)})}loadTemplateSegment(e,t,i="auto"){return E(this,null,function*(){e.status="downloading";let r={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(r);let{range:s,url:n,signal:o,onProgress:u,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(yield jt(o,function(){return ue(this,null,function*(){let c=Kl(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(d=>setTimeout(d,c))})}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let c=yield this.fetcher.fetch(n,{range:s,signal:o,onProgress:u,priority:i,isLowLatency:this.isActiveLowLatency()});if(this.lastDataObtainedTimestampMs=vn(),!c)return;let d=new DataView(c),h=$a(t.mime);if(!isFinite(r.segment.time.to)){let b=t.segmentReference.timescale;r.segment.time.to=h.getChunkEndTime(d,b)}u&&r.feedingBytes&&l?yield Promise.all(l):yield this.sourceBufferTaskQueue.append(d,o);let{serverDataReceivedTimestamp:p,serverDataPreparedTime:m}=h.getServerLatencyTimestamps(d);p&&m&&this.currentLiveSegmentServerLatency$.next(m-p),r.segment.status="downloaded",this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(c){this.abortActiveSegments([e]),La(c)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}})}updateRepresentationsBaseUrlIfNeeded(){if(!this.tuning.dash.enableBaseUrlSupport||!this.baseUrls.length||this.failedDownloads<=this.tuning.dash.maxSegmentRetryCount)return;this.baseUrlsIndex=(this.baseUrlsIndex+1)%this.baseUrls.length;let e=this.baseUrls[this.baseUrlsIndex];for(let t of this.representations.values())xe(t.segmentReference)?t.segmentReference.baseUrl=e:t.segmentReference.url=e}loadByteRangeSegments(e,t,i="auto"){return E(this,null,function*(){if(!e.length)return;for(let u of e)u.status="downloading",this.activeSegments.add({segment:u,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:r,url:s,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(yield jt(n,function(){return ue(this,null,function*(){let u=Kl(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),zl(window,"online").pipe(PD()).subscribe(()=>{l(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{yield this.fetcher.fetch(s,{range:r,onProgress:o,signal:n,priority:i}),this.lastDataObtainedTimestampMs=vn(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),La(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}})}prepareByteRangeFetchSegmentParams(e,t){if(xe(t.segmentReference))throw new Error("Representation is not byte range type");let i=t.segmentReference.url,r={from:(0,rr.default)(e,0).byte.from,to:(0,rr.default)(e,-1).byte.to},{signal:s}=this.downloadAbortController;return{url:i,range:r,signal:s,onProgress:(o,u)=>E(this,null,function*(){if(!s.aborted)try{this.lastDataObtainedTimestampMs=vn(),yield this.onSomeByteRangesDataLoaded({dataView:o,loaded:u,signal:s,onSegmentAppendFailed:()=>this.abort(),globalFrom:r?r.from:0,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:Tt.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}})}}prepareTemplateFetchSegmentParams(e,t){if(!xe(t.segmentReference))throw new Error("Representation is not template type");let i=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&i.searchParams.set("low-latency","yes");let r=i.toString(),{signal:s}=this.downloadAbortController,n=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(l,c)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=vn();let d=this.onSomeTemplateDataLoaded({dataView:l,loaded:c,signal:s,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(d)}catch(d){this.error$.next({id:"SegmentFeeding",category:Tt.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:d})}}:void 0;return{url:r,signal:s,onProgress:u,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)(0,Sn.default)(e,t.segment)&&this.abortSegment(t.segment)}onSomeTemplateDataLoaded(n){return E(this,arguments,function*({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:r,signal:s}){if(!this.activeSegments.size||!oe(this.mediaSource,this.sourceBuffer))return;let o=this.representations.get(t);if(o)for(let u of this.activeSegments){let{segment:l}=u;if(u.representationId===t){if(s.aborted){r();continue}if(u.loadedBytes=i,u.loadedBytes>u.feedingBytes){let c=new DataView(e.buffer,e.byteOffset+u.feedingBytes,u.loadedBytes-u.feedingBytes),d=$a(o.mime).parseFeedableSegmentChunk(c,this.isLive);d!=null&&d.byteLength&&(l.status="partially_fed",u.feedingBytes+=d.byteLength,yield this.sourceBufferTaskQueue.append(d),u.fedBytes+=d.byteLength)}}}})}onSomeByteRangesDataLoaded(o){return E(this,arguments,function*({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:s,onSegmentAppendFailed:n}){if(!this.activeSegments.size||!oe(this.mediaSource,this.sourceBuffer))return;let u=this.representations.get(t);if(u)for(let l of this.activeSegments){let{segment:c}=l;if(l.representationId!==t)continue;if(s.aborted){yield n();continue}let d=c.byte.from-i,h=c.byte.to-i,p=h-d+1,m=d<r,b=h<=r;if(!m)continue;let g=$a(u.mime);if(c.status==="downloading"&&b){c.status="downloaded";let v=new DataView(e.buffer,e.byteOffset+d,p);(yield this.sourceBufferTaskQueue.append(v,s))&&!s.aborted?this.onSegmentFullyAppended(l,t):yield n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(c.status==="downloading"||c.status==="partially_fed")&&(l.loadedBytes=Math.min(p,r-d),l.loadedBytes>l.feedingBytes)){let v=new DataView(e.buffer,e.byteOffset+d+l.feedingBytes,l.loadedBytes-l.feedingBytes),S=l.loadedBytes===p?v:g.parseFeedableSegmentChunk(v);S!=null&&S.byteLength&&(c.status="partially_fed",l.feedingBytes+=S.byteLength,(yield this.sourceBufferTaskQueue.append(S,s))&&!s.aborted?(l.fedBytes+=S.byteLength,l.fedBytes===p&&this.onSegmentFullyAppended(l,t)):yield n())}}})}onSegmentFullyAppended(e,t){var i;if(!(Se(this.sourceBuffer)||!oe(this.mediaSource,this.sourceBuffer))){!this.isLive&&U.browser.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(Ut(this.sourceBuffer.buffered,e.segment.time.from,100)&&Ut(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:Tt.VIDEO_PIPELINE,message:"Browser stuck on empty result of adding segment to source buffer"})),this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status="fed",Ql(e.segment)&&(e.segment.size=e.fedBytes);for(let r of this.representations.values())if(r.id!==t)for(let s of(i=this.segments.get(r.id))!=null?i:[])s.status==="fed"&&Math.round(s.time.from)===Math.round(e.segment.time.from)&&Math.round(s.time.to)===Math.round(e.segment.time.to)&&(s.status="none");this.updateLowLatencyLiveIfNeeded(e.segment),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment])}}abortSegment(e){e.status==="partially_fed"?e.status="partially_ejected":e.status!=="partially_ejected"&&(e.status="none");for(let t of this.activeSegments.values())if(t.segment===e){this.activeSegments.delete(t);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(let[r,s]of this.initData.entries()){let n=s instanceof Promise;t||(t=n),s===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let i=this.representations.get(e);i&&(this.initLoadIdleCallback=$l(()=>(0,Ry.default)(this.loadInit(i,"low",!1),()=>this.initLoadIdleCallback=null)))}loadInit(e,t="auto",i=!1){return E(this,null,function*(){let r=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!i&&this.failedDownloads>0?jt(this.destroyAbortController.signal,function(){return ue(this,null,function*(){let o=Kl(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))})}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,$a(e.mime),r)).then(o=>E(this,null,function*(){if(!o)return;let{init:u,dataView:l,segments:c}=o,d=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,d);let h=c;this.isLive&&xe(e.segmentReference)&&(h=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,h),u&&this.parsedInitData.set(e.id,u)})).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:Tt.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n})}dropBuffer(){return E(this,null,function*(){for(let e of this.segments.values())for(let t of e)t.status="none";yield this.pruneBuffer(0,1/0,!0)})}pruneBuffer(e,t,i=!1){return E(this,null,function*(){if(!this.sourceBuffer||!oe(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||Se(e))return!1;let r=[],s=0,n=u=>{u.sort((c,d)=>c.from-d.from);let l=[u[0]];for(let c=1;c<u.length;c++){let{from:d,to:h}=u[c],p=l[l.length-1];p.to>=d?p.to=Math.max(p.to,h):l.push(u[c])}return l},o=u=>{var c;if(s>=t)return r;r.push(w({},u.time)),r=n(r);let l=Ql(u)?(c=u.size)!=null?c:0:u.byte.to-u.byte.from;s+=l};for(let u of this.segments.values())for(let l of u){let c=l.time.to<=e-this.tuning.dash.bufferPruningSafeZone,d=l.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(c||d)&&l.status==="fed"&&o(l)}for(let u=0;u<this.sourceBuffer.buffered.length;u++){let l=this.sourceBuffer.buffered.start(u)*1e3,c=this.sourceBuffer.buffered.end(u)*1e3,d=0;for(let h of this.segments.values())for(let p of h)(0,Sn.default)(["none","partially_ejected"],p.status)&&Math.round(p.time.from)<=Math.round(l)&&Math.round(p.time.to)>=Math.round(c)&&d++;if(d===this.segments.size){let h={time:{from:l,to:c},url:"",status:"none"};o(h)}}if(r.length&&i){let u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let l of this.segments.values())for(let c of l)c.time.from>=e+u&&c.status==="fed"&&o(c)}return r.length?(yield Promise.all(r.map(l=>this.sourceBufferTaskQueue.remove(l.from,l.to)))).reduce((l,c)=>l||c,!1):!1})}abortBuffer(){return E(this,null,function*(){if(!this.sourceBuffer||!oe(this.mediaSource,this.sourceBuffer))return!1;let e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;return this.sourceBufferTaskQueue.abort(t)})}getDebugBufferState(){if(!(!this.sourceBuffer||!oe(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}getForwardBufferDuration(e=this.getCurrentPosition()){return!this.sourceBuffer||!oe(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||Se(e)?0:Ji(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!(!this.sourceBuffer||!oe(this.mediaSource,this.sourceBuffer))){if(this.tuning.useRefactoredSearchGap)for(let i=0;i<this.sourceBuffer.buffered.length;i++)this.gaps=this.gaps.filter(r=>this.sourceBuffer&&(Math.round(r.from)<Math.round(this.sourceBuffer.buffered.start(i)*1e3)||Math.round(r.to)>Math.round(this.sourceBuffer.buffered.end(i)*1e3)));for(let i of t){let r={representation:e,from:i.time.from,to:i.time.to};for(let s=0;s<this.sourceBuffer.buffered.length;s++){let n=this.sourceBuffer.buffered.start(s)*1e3,o=this.sourceBuffer.buffered.end(s)*1e3;if(!(o<=i.time.from||n>=i.time.to)){if(n<=i.time.from&&o>=i.time.to){r=void 0;break}o>i.time.from&&o<i.time.to&&(r.from=o),n<i.time.to&&n>i.time.from&&(r.to=n)}}r&&r.to-r.from>1&&!this.gaps.some(s=>r&&s.from===r.from&&s.to===r.to)&&this.gaps.push(r)}}}detectGapsWhenIdle(e,t){if(!(this.gapDetectionIdleCallback||!this.sourceBuffer||!oe(this.mediaSource,this.sourceBuffer))){if(!this.tuning.useRefactoredSearchGap)for(let i=0;i<this.sourceBuffer.buffered.length;i++)this.gaps=this.gaps.filter(r=>this.sourceBuffer&&(Math.round(r.from)<Math.round(this.sourceBuffer.buffered.start(i)*1e3)||Math.round(r.to)>Math.round(this.sourceBuffer.buffered.end(i)*1e3)));this.gapDetectionIdleCallback=$l(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:Tt.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if(Se(this.sourceBuffer)||!oe(this.mediaSource,this.sourceBuffer)||Se(this.playingRepresentationId))return;let e=[];for(let i=0;i<this.sourceBuffer.buffered.length;i++){let r=Math.floor(this.sourceBuffer.buffered.start(i)*1e3),s=Math.ceil(this.sourceBuffer.buffered.end(i)*1e3);e.push({from:r,to:s})}let t=100;for(let i of this.segments.values())for(let r of i){let{status:s}=r;if(s!=="fed"&&s!=="partially_ejected")continue;let n=Math.floor(r.time.from),o=Math.ceil(r.time.to),u=e.some(c=>c.from-t<=n&&c.to+t>=o),l=e.filter(c=>n>=c.from&&n<c.to-t||o>c.from+t&&o<=c.to);u||(l.length===1?r.status="partially_ejected":this.gaps.some(c=>c.from===r.time.from||c.to===r.time.to)?r.status="partially_ejected":r.status="none")}}handleAsyncError(e,t){this.error$.next({id:t,category:Tt.VIDEO_PIPELINE,thrown:e,message:"Something went wrong"})}};var 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"),i=e===null?"http1":e!=null?e:void 0,r=t===null?void 0:(s={1:!0,0:!1}[t])!=null?s:void 0;return{type:i,reused:r}};import{abortable as Ca,assertNever as My,fromEvent as Dy,merge as AD,now as Va,Subscription as RD,Subject as Cy,ValueSubject as Xl,flattenObject as ar,ErrorCategory as Oa}from"@vkontakte/videoplayer-shared/es2015";var Ly=a=>{let e=new URL(a);return e.searchParams.set("enable-subtitles","yes"),e.toString()};var In=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:s=!1}){this.lastConnectionType$=new Xl(void 0);this.lastConnectionReused$=new Xl(void 0);this.lastRequestFirstBytes$=new Xl(void 0);this.recoverableError$=new Cy;this.error$=new Cy;this.abortAllController=new ve;this.subscription=new RD;this.fetchManifest=Ca(this.abortAllController.signal,function(e){return ue(this,null,function*(){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=Da(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=Ly(i));let r=yield this.doFetch(i,{signal:this.abortAllController.signal}).catch(Tn);return r?(t.log("success",ar({url:i,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(r.headers),r.text()):(t.error("error",ar({url:i,message:"No data in request manifest"})),t.end(),null)})}.bind(this));this.fetch=Ca(this.abortAllController.signal,function(l){return ue(this,arguments,function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:i,onProgress:r,priority:s="auto",signal:n,measureThroughput:o=!0,isLowLatency:u=!1}={}){var L,Q;let c=e,d=new Headers,h=this.tracer.createComponentTracer("Fetch");if(i)switch(t){case 0:{d.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let N=new URL(c,location.href);N.searchParams.append("bytes",`${i.from}-${i.to}`),c=N.toString();break}default:My(t)}this.requestQuic&&(c=Da(c));let p=this.abortAllController.signal,m;if(n){let N=new ve;if(m=AD(Dy(this.abortAllController.signal,"abort"),Dy(n,"abort")).subscribe(()=>{try{N.abort()}catch(Z){Tn(Z)}}),this.subscription.add(m),this.abortAllController.signal.aborted||n.aborted)try{N.abort()}catch(Z){Tn(Z)}p=N.signal}let b=Va();h.log("startRequest",ar({url:c,priority:s,rangeMethod:t,range:i,isLowLatency:u,requestStartedAt:b}));let g=yield this.doFetch(c,{priority:s,headers:d,signal:p}),v=Va();if(!g)return h.error("error",{message:"No response in request"}),h.end(),m==null||m.unsubscribe(),null;if((L=this.throughputEstimator)==null||L.addRawRtt(v-b),!g.ok||!g.body){m==null||m.unsubscribe();let N=`Fetch error ${g.status}: ${g.statusText}`;return h.error("error",{message:N}),h.end(),Promise.reject(new Error(`Fetch error ${g.status}: ${g.statusText}`))}if(this.onHeadersReceived(g.headers),!r&&!o){m==null||m.unsubscribe();let N=Va(),Z={requestStartedAt:b,requestEndedAt:N,duration:N-b};return h.log("endRequest",ar(Z)),h.end(),g.arrayBuffer()}let[S,y]=g.body.tee(),I=S.getReader();o&&((Q=this.throughputEstimator)==null||Q.trackStream(y,u));let T=0,$=new Uint8Array(0),F=!1,q=N=>{m==null||m.unsubscribe(),F=!0,Tn(N)},K=Ca(p,function(R){return ue(this,arguments,function*({done:N,value:Z}){if(T===0&&this.lastRequestFirstBytes$.next(Va()-b),p.aborted){m==null||m.unsubscribe();return}if(!N&&Z){let C=new Uint8Array($.length+Z.length);C.set($),C.set(Z,$.length),$=C,T+=Z.byteLength,r==null||r(new DataView($.buffer),T),yield I==null?void 0:I.read().then(K,q)}})}.bind(this));yield I==null?void 0:I.read().then(K,q),m==null||m.unsubscribe();let x=Va(),j={failed:F,requestStartedAt:b,requestEndedAt:x,duration:x-b};return F?(h.error("endRequest",ar(j)),h.end(),null):(h.log("endRequest",ar(j)),h.end(),$.buffer)})}.bind(this));this.fetchByteRangeRepresentation=Ca(this.abortAllController.signal,function(e,t,i){return ue(this,null,function*(){var v;if(e.type!=="byteRange")return null;let{from:r,to:s}=e.initRange,n=r,o=s,u=!1,l,c;e.indexRange&&(l=e.indexRange.from,c=e.indexRange.to,u=s+1===l,u&&(n=Math.min(l,r),o=Math.max(c,s))),n=Math.min(n,0);let d=yield this.fetch(e.url,{range:{from:n,to:o},priority:i,measureThroughput:!1});if(!d)return null;let h=new DataView(d,r-n,s-n+1);if(!t.validateData(h))throw new Error("Invalid media file");let p=t.parseInit(h),m=(v=e.indexRange)!=null?v:t.getIndexRange(p);if(!m)throw new ReferenceError("No way to load representation index");let b;if(u)b=new DataView(d,m.from-n,m.to-m.from+1);else{let S=yield this.fetch(e.url,{range:m,priority:i,measureThroughput:!1});if(!S)return null;b=new DataView(S)}let g=t.parseSegments(b,p,m);return{init:p,dataView:new DataView(d),segments:g}})}.bind(this));this.fetchTemplateRepresentation=Ca(this.abortAllController.signal,function(e,t){return ue(this,null,function*(){if(e.type!=="template")return null;let i=new URL(e.initUrl,e.baseUrl).toString(),r=yield this.fetch(i,{priority:t,measureThroughput:!1});return r?{init:null,segments:e.segments.map(n=>D(w({},n),{status:"none",size:void 0})),dataView:new DataView(r)}:null})}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=r,this.tracer=i.createComponentTracer("Fetcher"),this.useEnableSubtitlesParam=s}onHeadersReceived(e){let{type:t,reused:i}=$y(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}fetchRepresentation(e,t,i="auto"){return E(this,null,function*(){var s,n;let{type:r}=e;switch(r){case"byteRange":return(s=yield this.fetchByteRangeRepresentation(e,t,i))!=null?s:null;case"template":return(n=yield this.fetchTemplateRepresentation(e,i))!=null?n:null;default:My(r)}})}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}doFetch(e,t){return E(this,null,function*(){let i=yield lt(e,t);if(i.ok)return i;let r=yield i.text(),s=parseInt(r);if(!isNaN(s))switch(s){case 1:this.recoverableError$.next({id:"VideoDataLinkExpiredError",message:"Video data links have expired",category:Oa.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:Oa.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:Oa.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:Oa.FATAL});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${s})`,category:Oa.FATAL})}})}},Tn=a=>{if(!La(a))throw a};var gi=(a,e,t)=>t*e+(1-t)*a,Jl=(a,e)=>a.reduce((t,i)=>t+i,0)/e,Vy=(a,e,t,i)=>{let r=0,s=t,n=Jl(a,e),o=e<i?e:i;for(let u=0;u<o;u++)a[s]>n?r++:r--,s=(a.length+s-1)%a.length;return Math.abs(r)===o};import{isNullable as $D,ValueSubject as Oy}from"@vkontakte/videoplayer-shared/es2015";var Qt=class{constructor(e){this.prevReported=void 0;this.pastMeasures=[];this.takenMeasures=0;this.measuresCursor=0;var i;this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new Oy(e.initial),this.debounced$=new Oy(e.initial);let t=(i=e.label)!=null?i:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new Ie(`raw_${t}`),this.smoothedSeries$=new Ie(`smoothed_${t}`),this.reportedSeries$=new Ie(`reported_${t}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,i=0;for(let o=0;o<this.pastMeasures.length;o++)this.pastMeasures[o]!==void 0&&(t+=at(this.pastMeasures[o]-this.smoothed,2),i++);this.takenMeasures=i,t/=i;let r=Math.sqrt(t),s=this.smoothed+this.params.deviationFactor*r,n=this.smoothed-this.params.deviationFactor*r;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(e),this.updateSmoothedValue(e),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),!(this.smoothed>s||this.smoothed<n)&&($D(this.prevReported)||Math.abs(this.smoothed-this.prevReported)/this.prevReported>=this.params.changeThreshold)&&(this.prevReported=this.smoothed,this.debounced$.next(this.smoothed),this.reportedSeries$.next(this.smoothed))}};var En=class extends Qt{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=gi(this.slow,e,this.params.emaAlphaSlow),this.fast=gi(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var xn=class extends Qt{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=Jl(this.pastMeasures,this.takenMeasures);this.emaSmoothed=gi(this.emaSmoothed,e,this.params.emaAlpha);let i=Vy(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=i?this.emaSmoothed:t}};var Pn=class extends Qt{constructor(t){super(t);this.furtherValues=[];this.currentTopExtremumValue=0;this.extremumInterval=t.extremumInterval}next(t){this.currentTopExtremumValue<=t?(this.currentTopExtremumValue=t,this.furtherValues=[]):this.furtherValues.length===this.extremumInterval?(super.next(this.currentTopExtremumValue),this.currentTopExtremumValue=t,this.furtherValues=[]):this.furtherValues.push(t)}updateSmoothedValue(t){this.smoothed=this.smoothed?gi(this.smoothed,t,this.params.emaAlpha):t}};var vi=class{static getSmoothedValue(e,t,i){return i.type==="TwoEma"?new En({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new xn({initial:e,emaAlpha:i.emaAlpha,basisTrendChangeCount:i.basisTrendChangeCount,changeThreshold:i.changeThreshold,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"})}static getLiveBufferSmoothedValue(e,t){return new Pn(w({initial:e,label:"liveEdgeDelay"},t))}};var Zl=(a,e)=>{a&&a.playbackRate!==e&&(a.playbackRate=e)};import{isNullable as LD,ValueSubject as MD}from"@vkontakte/videoplayer-shared/es2015";var _a=class a{constructor(e,t){this.currentRepresentation$=new MD(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(!LD(e))for(let i of this.representations)for(let r of i){let s=r.segmentReference,n=s.segments.length,o=s.segments[0].time.from,u=s.segments[n-1].time.to;if(e<o||e>u)continue;let l=s.segments.find(c=>c.time.from<=e&&c.time.to>=e);!l||((t=this.currentSegment)==null?void 0:t.time.from)===l.time.from&&this.currentSegment.time.to===l.time.to||(this.currentSegment=l,this.currentRepresentation$.next(D(w({},r),{label:"Live Text",language:"ru",isAuto:!0,url:new URL(l.url,s.baseUrl).toString()})))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e!=null?e:[]){let i=a.filterRepresentations(t.representations);if(i){this.representations[this.representationsCursor]=i,this.representationsCursor=(this.representationsCursor+1)%this.maxRepresentations;break}}}static isSupported(e){return!!(e!=null&&e.some(t=>a.filterRepresentations(t.representations)))}static filterRepresentations(e){return e==null?void 0:e.filter(t=>t.kind==="text"&&"segmentReference"in t&&xe(t.segmentReference))}};var kn=O(Nt(),1);import{assertNever as An}from"@vkontakte/videoplayer-shared/es2015";var _y=(a,{useHlsJs:e,useManagedMediaSource:t,useOldMSEDetection:i})=>{let{containers:r,protocols:s,codecs:n,nativeHlsSupported:o}=U.video,u=(n.h264||n.h265)&&n.aac,l=s.mse&&(!i||!!window.MediaStreamTrack)||s.mms&&t;return a.filter(c=>{switch(c){case"DASH_SEP":return l&&r.mp4&&u;case"DASH_WEBM":return l&&r.webm&&n.vp9&&n.opus;case"DASH_WEBM_AV1":return l&&r.webm&&n.av1&&n.opus;case"DASH_STREAMS":return l&&(r.mp4&&u||r.webm&&(n.vp9||n.av1)&&(n.opus||n.aac));case"DASH_LIVE":return l&&r.mp4&&u;case"DASH_LIVE_CMAF":return l&&r.mp4&&u&&r.cmaf;case"DASH_ONDEMAND":return l&&r.mp4&&u;case"HLS":case"HLS_ONDEMAND":return o||e&&l&&r.mp4&&u;case"HLS_LIVE":case"HLS_LIVE_CMAF":return o;case"MPEG":return r.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return s.webrtc&&s.ws&&n.h264&&(r.mp4||r.webm);default:return An(c)}})},wn=a=>{let{webmDecodingInfo:e}=U.video,t="DASH_WEBM",i="DASH_WEBM_AV1";switch(a){case"vp9":return[t,i];case"av1":return[i,t];case"none":return[];case"smooth":return e?e[i].smooth?[i,t]:e[t].smooth?[t,i]:[i,t]:[t,i];case"power_efficient":return e?e[i].powerEfficient?[i,t]:e[t].powerEfficient?[t,i]:[i,t]:[t,i];default:An(a)}return[t,i]},By=({webmCodec:a,androidPreferredFormat:e,preferMultiStream:t})=>{let i=[...t?["DASH_STREAMS"]:[],...wn(a),"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]],r=[...t?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]];if(U.device.isAndroid)switch(e){case"mpeg":return["MPEG",...i,"HLS","HLS_ONDEMAND"];case"hls":return["HLS","HLS_ONDEMAND",...i,"MPEG"];case"dash":return[...i,"HLS","HLS_ONDEMAND","MPEG"];case"dash_any_mpeg":return[...r,"MPEG",...wn(a),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...wn(a),"MPEG",...r,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...wn(a),...r,"HLS","HLS_ONDEMAND"];default:An(e)}return U.video.nativeHlsSupported?[...i,"HLS","HLS_ONDEMAND","MPEG"]:[...i,"HLS","HLS_ONDEMAND","MPEG"]},Ny=({androidPreferredFormat:a,preferCMAF:e,preferWebRTC:t})=>{let i=e?["DASH_LIVE_CMAF","DASH_LIVE"]:["DASH_LIVE","DASH_LIVE_CMAF"],r=e?["HLS_LIVE_CMAF","HLS_LIVE"]:["HLS_LIVE","HLS_LIVE_CMAF"],s=[...i,...r],n=[...r,...i],o,u=U.device.isMac&&U.browser.isSafari;if(U.device.isAndroid)switch(a){case"dash":case"dash_any_mpeg":case"dash_any_webm":case"dash_sep":{o=s;break}case"hls":case"mpeg":{o=n;break}default:An(a)}else U.video.nativeHlsSupported&&!u?o=n:u?o=e?["DASH_LIVE_CMAF","HLS_LIVE_CMAF","HLS_LIVE","DASH_LIVE"]:["HLS_LIVE","DASH_LIVE","DASH_LIVE_CMAF","HLS_LIVE_CMAF"]:o=s;return t?["WEB_RTC_LIVE",...o]:[...o,"WEB_RTC_LIVE"]},ec=a=>a?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],Fy=a=>{if(a.size===0)return;if(a.size===1){let t=a.values().next();return(0,kn.default)(t.value.split("."),0)}for(let t of a){let i=(0,kn.default)(t.split("."),0);if(i==="opus"||i==="vp09"||i==="av01")return i}let e=a.values().next();return(0,kn.default)(e.value.split("."),0)};var qD=["timeupdate","progress","play","seeked","stalled","waiting"],UD=["timeupdate","progress","loadeddata","playing","seeked"];var Ln=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new Hy;this.representationSubscription=new Hy;this.state$=new _("none");this.currentVideoRepresentation$=new re(void 0);this.currentVideoRepresentationInit$=new re(void 0);this.currentAudioRepresentation$=new re(void 0);this.currentVideoSegmentLength$=new re(0);this.currentAudioSegmentLength$=new re(0);this.error$=new $n;this.lastConnectionType$=new re(void 0);this.lastConnectionReused$=new re(void 0);this.lastRequestFirstBytes$=new re(void 0);this.currentLiveTextRepresentation$=new re(null);this.isLive$=new re(!1);this.isActiveLive$=new re(!1);this.isLowLatency$=new re(!1);this.liveDuration$=new re(0);this.liveSeekableDuration$=new re(0);this.liveAvailabilityStartTime$=new re(0);this.liveStreamStatus$=new re(void 0);this.bufferLength$=new re(0);this.liveLatency$=new re(void 0);this.liveLoadBufferLength$=new re(0);this.livePositionFromPlayer$=new re(0);this.currentStallDuration$=new re(0);this.videoLastDataObtainedTimestamp$=new re(0);this.fetcherRecoverableError$=new $n;this.fetcherError$=new $n;this.liveStreamEndTimestamp=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.forceEnded$=new $n;this.gapWatchdogActive=!1;this.destroyController=new ve;this.initManifest=ic(this.destroyController.signal,function(e,t,i){return ue(this,null,function*(){var r;this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=ge(t,i,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),(r=this.manifest)!=null&&r.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:ct.PARSER,message:"No playable video representations"})})}.bind(this));this.updateManifest=ic(this.destroyController.signal,function(){return ue(this,null,function*(){var n,o;this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(u=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:ct.NETWORK,message:"Failed to load manifest",thrown:u})});if(!e)return null;let t=null;try{t=wy(e!=null?e:"",this.manifestUrlString)}catch(u){let l=(n=vS(e))!=null?n:{id:"ManifestParsing",category:ct.PARSER,message:"Failed to parse MPD manifest",thrown:u};this.error$.next(l)}if(!t)return null;let i=(u,l,c)=>{var d,h,p,m;return!!((h=(d=this.element)==null?void 0:d.canPlayType)!=null&&h.call(d,l)&&((m=(p=Je())==null?void 0:p.isTypeSupported)!=null&&m.call(p,`${l}; codecs="${c}"`))||u==="text")};if(t.live){this.isLive$.next(!!t.live);let{availabilityStartTime:u,latestSegmentPublishTime:l,streamIsUnpublished:c,streamIsAlive:d}=t.live,h=((o=t.duration)!=null?o:0)/1e3;this.liveSeekableDuration$.next(-1*h),this.liveDuration$.next((l-u)/1e3),this.liveAvailabilityStartTime$.next(t.live.availabilityStartTime);let p="active";d||(p=c?"unpublished":"unexpectedly_down"),this.liveStreamStatus$.next(p)}let r={text:t.streams.text,video:[],audio:[]};for(let u of["video","audio"]){let c=t.streams[u].filter(({mime:p,codecs:m})=>i(u,p,m)),d=new Set(c.map(({codecs:p})=>p)),h=Fy(d);if(h&&(r[u]=c.filter(({codecs:p})=>p.startsWith(h))),u==="video"){let p=this.tuning.preferHDR,m=r.video.some(g=>g.hdr),b=r.video.some(g=>!g.hdr);U.display.isHDR&&p&&m?r.video=r.video.filter(g=>g.hdr):b&&(r.video=r.video.filter(g=>!g.hdr))}}let s=D(w({},t),{streams:r});return this.tracer.log("updateManifestEnd",Na(s)),s})}.bind(this));this.initRepresentations=ic(this.destroyController.signal,function(e,t,i){return ue(this,null,function*(){var h;this.tracer.log("initRepresentationsStart",Na({initialVideo:e,initialAudio:t,sourceHls:i})),sr(this.manifest),sr(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let r=p=>{this.representationSubscription.add(It(p,"error").pipe(Rn(m=>{var b;return!!((b=this.element)!=null&&b.played.length)})).subscribe(m=>{this.error$.next({id:"VideoSource",category:ct.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:m})}))};this.source=this.tuning.useManagedMediaSource?Ng():new MediaSource;let s=document.createElement("source");if(r(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),this.tuning.useManagedMediaSource&&an())if(i){let p=document.createElement("source");r(p),p.type="application/x-mpegurl",p.src=i.url,this.element.appendChild(p)}else this.element.disableRemotePlayback=!0;this.isActiveLive$.next(this.isLive$.getValue());let n={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),manifest:this.manifest},o=this.manifest.streams.video.reduce((p,m)=>[...p,...m.representations],[]);if(this.videoBufferManager=new Ma("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],Fa(t)){let p=this.manifest.streams.audio.reduce((m,b)=>[...m,...b.representations],[]);this.audioBufferManager=new Ma("audio",this.source,p,n),this.bufferManagers.push(this.audioBufferManager)}_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 p;(p=this.stallWatchdogSubscription)==null||p.unsubscribe(),this.currentStallDuration$.next(0)};if(this.representationSubscription.add(Si(...UD.map(p=>It(this.element,p))).pipe(or(p=>this.element?Ji(this.element.buffered,this.element.currentTime*1e3):0),Ba(),ND(p=>{p>this.tuning.dash.bufferEmptinessTolerance&&u()})).subscribe(this.bufferLength$)),this.representationSubscription.add(Si(It(this.element,"ended"),this.forceEnded$).subscribe(()=>{u()})),this.isLive$.getValue()){this.subscription.add(this.liveDuration$.pipe(Ba()).subscribe(m=>this.liveStreamEndTimestamp=ac())),this.subscription.add(It(this.element,"pause").subscribe(()=>{this.livePauseWatchdogSubscription=rc(1e3).subscribe(m=>{let b=Xs(this.manifestUrlString,2);this.manifestUrlString=ge(this.manifestUrlString,b+1e3,2),this.liveStreamStatus$.getValue()==="active"&&this.updateManifest()}),this.subscription.add(this.livePauseWatchdogSubscription)})).add(It(this.element,"play").subscribe(m=>{var b;return(b=this.livePauseWatchdogSubscription)==null?void 0:b.unsubscribe()})),this.representationSubscription.add(nr({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(or(({isActiveLive:m,isLowLatency:b})=>m&&b),Ba()).subscribe(m=>{this.isManualDecreasePlaybackInLive()||Zl(this.element,1)})),this.representationSubscription.add(nr({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(Rn(({bufferLength:m,isActiveLive:b,isLowLatency:g})=>b&&g&&!!m)).subscribe(({bufferLength:m})=>this.liveBuffer.next(m))),this.representationSubscription.add(this.videoBufferManager.currentLowLatencySegmentLength$.subscribe(m=>{if(!this.isActiveLive$.getValue()&&!this.isLowLatency$.getValue()&&!m)return;let b=this.liveSeekableDuration$.getValue()-m/1e3;this.liveSeekableDuration$.next(Math.max(b,-1*this.tuning.dashCmafLive.maxLiveDuration)),this.liveDuration$.next(this.liveDuration$.getValue()+m/1e3)})),this.representationSubscription.add(nr({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe(Rn(({isLive:m})=>m),Ba((m,b)=>b.bufferLength<m.bufferLength),or(({rtt:m,bufferLength:b,segmentServerLatency:g})=>{let v=Xs(this.manifestUrlString,2);return(m/2+b+g+v)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add(nr({liveBuffer:this.liveBuffer.smoothed$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).subscribe(({liveBuffer:m,isActiveLive:b,isLowLatency:g})=>{if(!g||!b)return;let v=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,S=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,y=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,I=m-v;if(this.isManualDecreasePlaybackInLive())return;let T=1;Math.abs(I)>S&&(T=1+Math.sign(I)*y),Zl(this.element,T)})),this.representationSubscription.add(this.bufferLength$.subscribe(m=>{var g,v;let b=0;if(m){let S=((v=(g=this.element)==null?void 0:g.currentTime)!=null?v:0)*1e3;b=Math.min(...this.bufferManagers.map(I=>{var T,$;return($=(T=I.getLiveSegmentsToLoadState(this.manifest))==null?void 0:T.to)!=null?$:S}))-S}this.liveLoadBufferLength$.getValue()!==b&&this.liveLoadBufferLength$.next(b)}));let p=0;this.representationSubscription.add(nr({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(FD(1e3)).subscribe(g=>E(this,[g],function*({liveLoadBufferLength:m,bufferLength:b}){if(!this.element||this.isUpdatingLive)return;let v=this.element.playbackRate,S=Xs(this.manifestUrlString,2),y=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,I=Math.min(y,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*v),T=this.tuning.dashCmafLive.normalizedActualBufferOffset*v,$=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*v,F=isFinite(m)?m:b,q=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),K=y<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next(K);let x="none";if(q?x="active_low_latency":this.isLowLatency$.getValue()&&K?(this.bufferManagers.forEach(j=>j.proceedLowLatencyLive()),x="active_low_latency"):S!==0&&F<I?x="live_forward_buffering":F<I+$&&(x="live_with_target_offset"),isFinite(m)&&(p=m>p?m:p),x==="live_forward_buffering"||x==="live_with_target_offset"){let j=p-(I+T),L=this.normolizeLiveOffset(Math.trunc(S+j/v)),Q=Math.abs(L-S),N=0;!m||Q<=this.tuning.dashCmafLive.offsetCalculationError?N=S:L>0&&Q>this.tuning.dashCmafLive.offsetCalculationError&&(N=L),this.manifestUrlString=ge(this.manifestUrlString,N,2)}(x==="live_with_target_offset"||x==="live_forward_buffering")&&(p=0,yield this.updateLive())}),m=>{this.error$.next({id:"updateLive",category:ct.VIDEO_PIPELINE,thrown:m,message:"Failed to update live with subscription"})}))}let l=Si(...this.bufferManagers.map(p=>p.fullyBuffered$)).pipe(or(()=>this.bufferManagers.every(p=>p.fullyBuffered$.getValue()))),c=Si(...this.bufferManagers.map(p=>p.onLastSegment$)).pipe(or(()=>this.bufferManagers.some(p=>p.onLastSegment$.getValue()))),d=nr({allBuffersFull:l,someBufferEnded:c}).pipe(Ba(),or(({allBuffersFull:p,someBufferEnded:m})=>p&&m),Rn(p=>p));if(this.representationSubscription.add(Si(this.forceEnded$,d).subscribe(()=>{var p;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(m=>!m.updating))try{(p=this.source)==null||p.endOfStream()}catch(m){this.error$.next({id:"EndOfStream",category:ct.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:m})}})),this.representationSubscription.add(Si(...this.bufferManagers.map(p=>p.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.representationSubscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&(this.representationSubscription.add(this.audioBufferManager.playingRepresentation$.subscribe(this.currentAudioRepresentation$)),this.representationSubscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$))),this.liveTextManager&&this.representationSubscription.add(this.liveTextManager.currentRepresentation$.subscribe(this.currentLiveTextRepresentation$)),this.source.readyState!=="open"){let p=this.tuning.dash.sourceOpenTimeout>=0;yield new Promise((m,b)=>{var g;p&&(this.timeoutSourceOpenId=setTimeout(()=>{var v;if(((v=this.source)==null?void 0:v.readyState)==="open"){m();return}this.tuning.dash.rejectOnSourceOpenTimeout?b(new Error("Timeout reject when wait sourceopen event")):m()},this.tuning.dash.sourceOpenTimeout)),(g=this.source)==null||g.addEventListener("sourceopen",()=>{this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),m()},{once:!0})})}if(!this.isLive$.getValue()){let p=[(h=this.manifest.duration)!=null?h:0,...(0,sc.default)((0,sc.default)([...this.manifest.streams.audio,...this.manifest.streams.video],m=>m.representations),m=>{let b=[];return m.duration&&b.push(m.duration),xe(m.segmentReference)&&m.segmentReference.totalSegmentsDurationMs&&b.push(m.segmentReference.totalSegmentsDurationMs),b})];this.source.duration=Math.max(...p)/1e3}this.audioBufferManager&&Fa(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState("representations_ready"),this.tracer.log("initRepresentationsEnd")})}.bind(this));this.tick=()=>{var t,i,r,s;if(!this.element||!this.videoBufferManager||((t=this.source)==null?void 0:t.readyState)!=="open")return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),(i=this.audioBufferManager)==null||i.maintain(e),(r=this.liveTextManager)==null||r.maintain(e),(this.videoBufferManager.gaps.length||(s=this.audioBufferManager)!=null&&s.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=rc(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),n=>{this.error$.next({id:"GapWatchdog",category:ct.WTF,message:"Error handling gaps",thrown:n})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name),this.fetcher=new In({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer,useEnableSubtitlesParam:e.tuning.useEnableSubtitlesParam}),this.subscription.add(this.fetcher.recoverableError$.subscribe(this.fetcherRecoverableError$)),this.subscription.add(this.fetcher.error$.subscribe(this.fetcherError$)),this.liveBuffer=vi.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,w({},e.tuning.dashCmafLive.lowLatency.bufferEstimator)),this.initTracerSubscription()}seekLive(e){return E(this,null,function*(){var r,s,n;sr(this.element);let t=this.liveStreamStatus$.getValue()!=="active"?ac()-this.liveStreamEndTimestamp:0,i=this.normolizeLiveOffset(e+t);this.isActiveLive$.next(i===0),this.manifestUrlString=ge(this.manifestUrlString,i,2),this.manifest=yield this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,yield(r=this.videoBufferManager)==null?void 0:r.seekLive(this.manifest.streams.video),yield(s=this.audioBufferManager)==null?void 0:s.seekLive(this.manifest.streams.audio),(n=this.liveTextManager)==null||n.seekLive(this.manifest.streams.text))})}initBuffer(){sr(this.element),this.state$.setState("running"),this.subscription.add(Si(...qD.map(e=>It(this.element,e)),It(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:ct.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(It(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(It(this.element,"waiting").subscribe(()=>{var t;this.element&&this.element.readyState===2&&!this.element.seeking&&Ut(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{var p,m,b,g,v,S,y,I,T,$,F;if(!this.element||((p=this.source)==null?void 0:p.readyState)!=="open")return;let i=this.currentStallDuration$.getValue();i+=50,this.currentStallDuration$.next(i);let r={timeInWaiting:i},s=ac(),n=100,o=(b=(m=this.videoBufferManager)==null?void 0:m.lastDataObtainedTimestamp)!=null?b:0;this.videoLastDataObtainedTimestamp$.next(o);let u=(v=(g=this.audioBufferManager)==null?void 0:g.lastDataObtainedTimestamp)!=null?v:0,l=(y=(S=this.videoBufferManager)==null?void 0:S.getForwardBufferDuration())!=null?y:0,c=(T=(I=this.audioBufferManager)==null?void 0:I.getForwardBufferDuration())!=null?T:0,d=l<n&&s-o>this.tuning.dash.crashOnStallTWithoutDataTimeout,h=this.audioBufferManager&&c<n&&s-u>this.tuning.dash.crashOnStallTWithoutDataTimeout;if((d||h)&&i>this.tuning.dash.crashOnStallTWithoutDataTimeout||i>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${i} ms`);if(this.isLive$.getValue()&&i%2e3===0){let q=this.normolizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);this.seekLive(q).catch(K=>{this.error$.next({id:"stallIntervalCallback",category:ct.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:K})}),r.liveLastOffset=q}else{let q=this.element.currentTime*1e3;($=this.videoBufferManager)==null||$.maintain(q),(F=this.audioBufferManager)==null||F.maintain(q),r.position=q}this.tracer.log("stallIntervalCallback",Na(r))};(t=this.stallWatchdogSubscription)==null||t.unsubscribe(),this.stallWatchdogSubscription=rc(50).subscribe(e,i=>{this.error$.next({id:"StallWatchdogCallback",category:ct.NETWORK,message:"Can't restore DASH after stall.",thrown:i})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}switchRepresentation(e,t,i=!1){return E(this,null,function*(){let r={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return this.tuning.useNewSwitchTo?this.currentStallDuration$.getValue()>0?r==null?void 0:r.switchToWithPreviousAbort(t,i):r==null?void 0:r.switchTo(t,i):r==null?void 0:r.switchToOld(t,i)})}seek(e,t){return E(this,null,function*(){var r,s,n,o,u;sr(this.element),sr(this.videoBufferManager);let i;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?i=e:i=Math.max((r=this.videoBufferManager.findSegmentStartTime(e))!=null?r:e,(n=(s=this.audioBufferManager)==null?void 0:s.findSegmentStartTime(e))!=null?n:e),this.warmUpMediaSourceIfNeeded(i),Ut(this.element.buffered,i)||(yield Promise.all([this.videoBufferManager.abort(),(o=this.audioBufferManager)==null?void 0:o.abort()])),!(Uy(this.element)||Uy(this.videoBufferManager))&&(this.videoBufferManager.maintain(i),(u=this.audioBufferManager)==null||u.maintain(i),this.element.currentTime=i/1e3,this.tracer.log("seek",Na({requestedPosition:e,forcePrecise:t,position:i})))})}warmUpMediaSourceIfNeeded(e=(t=>(t=this.element)==null?void 0:t.currentTime)()){var i;Fa(this.element)&&Fa(this.source)&&Fa(e)&&((i=this.source)==null?void 0:i.readyState)==="ended"&&this.element.duration*1e3-e>this.tuning.dash.seekBiasInTheEnd&&this.bufferManagers.forEach(r=>r.warmUpMediaSource())}get isStreamEnded(){var e;return((e=this.source)==null?void 0:e.readyState)==="ended"}stop(){var e,t,i;this.tracer.log("stop"),(e=this.element)==null||e.querySelectorAll("source").forEach(r=>{URL.revokeObjectURL(r.src),r.remove()}),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),(t=this.videoBufferManager)==null||t.destroy(),this.videoBufferManager=null,(i=this.audioBufferManager)==null||i.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getStreams(){var e;return(e=this.manifest)==null?void 0:e.streams}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){var e;this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),((e=this.source)==null?void 0:e.readyState)==="open"&&Array.from(this.source.sourceBuffers).every(t=>!t.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}initTracerSubscription(){let e=BD(this.tracer.error.bind(this.tracer));this.subscription.add(this.error$.subscribe(e("error")))}isManualDecreasePlaybackInLive(){return!this.element||!this.isLive$.getValue()?!1:1-this.element.playbackRate>this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}updateLive(){return E(this,null,function*(){var e,t;this.isUpdatingLive=!0,this.manifest=yield this.updateManifest(),this.manifest&&((e=this.bufferManagers)==null||e.forEach(i=>i.updateLive(this.manifest)),(t=this.liveTextManager)==null||t.updateLive(this.manifest)),this.isUpdatingLive=!1})}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.getDebugBufferState();if(!e)return;let t=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),i={isJumpGapAfterSeekLive:this.isJumpGapAfterSeekLive,isActiveLowLatency:t,initialCurrentTime:this.element.currentTime};this.isJumpGapAfterSeekLive&&!t&&this.element.currentTime>e.to&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let r=this.element.currentTime*1e3,s=[],n=this.element.readyState===1?this.tuning.endGapTolerance:0;for(let o of this.bufferManagers)for(let u of o.gaps)o.playingRepresentation$.getValue()===u.representation&&u.from-n<=r&&u.to+n>r&&(this.element.duration*1e3-u.to<this.tuning.endGapTolerance?s.push(1/0):s.push(u.to));if(s.length){let o=Math.max(...s)+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,o===1/0?this.forceEnded$.next():(this.element.currentTime=o/1e3,i=D(w({},i),{gapEnds:s,jumpTo:o,resultCurrentTime:this.element.currentTime}),this.tracer.log("jumpGap",Na(i)))}}};var Mn=class{constructor(e,t){this.fov=e,this.orientation=t}};var 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,i=0){this.pointCameraTo(this.camera.orientation.x+e,this.camera.orientation.y+t,this.camera.orientation.z+i)}pointCameraTo(e=0,t=0,i=0){t=this.limitCameraRotationY(t);let r=e-this.camera.orientation.x,s=t-this.camera.orientation.y,n=i-this.camera.orientation.z;this.camera.orientation.x=e,this.camera.orientation.y=t,this.camera.orientation.z=i,this.lastCameraTurn={x:r,y:s,z:n},this.lastCameraTurnTS=Date.now()}setRotationSpeed(e,t,i){this.rotationSpeed.x=e!=null?e:this.rotationSpeed.x,this.rotationSpeed.y=t!=null?t:this.rotationSpeed.y,this.rotationSpeed.z=i!=null?i:this.rotationSpeed.z}startRotation(){this.rotating=!0}stopRotation(e=!1){e?(this.setRotationSpeed(0,0,0),this.fadeStartSpeed=null):this.startFading(this.rotationSpeed.x,this.rotationSpeed.y,this.rotationSpeed.z),this.rotating=!1}onCameraRelease(){if(this.lastCameraTurn&&this.lastCameraTurnTS){let e=Date.now()-this.lastCameraTurnTS;if(e<this.options.speedFadeThreshold){let t=(1-e/this.options.speedFadeThreshold)*this.options.rotationSpeedCorrection;this.startFading(this.lastCameraTurn.x*t,this.lastCameraTurn.y*t,this.lastCameraTurn.z*t)}}}startFading(e,t,i){this.setRotationSpeed(e,t,i),this.fadeStartSpeed=w({},this.rotationSpeed),this.fading=!0}stopFading(){this.fadeStartSpeed=null,this.fading=!0,this.fadeTime=0}limitCameraRotationY(e){return Math.max(-this.options.maxYawAngle,Math.min(e,this.options.maxYawAngle))}tick(e){if(!this.lastTickTS){this.lastTickTS=e,this.lastCameraTurnTS=Date.now();return}let t=e-this.lastTickTS,i=t/1e3;if(this.rotating)this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*i,this.rotationSpeed.y*this.options.rotationSpeedCorrection*i,this.rotationSpeed.z*this.options.rotationSpeedCorrection*i);else if(this.fading&&this.fadeStartSpeed){let r=-this.fadeCorrection*at(this.fadeTime/1e3,2)+1;this.setRotationSpeed(this.fadeStartSpeed.x*r,this.fadeStartSpeed.y*r,this.fadeStartSpeed.z*r),r>0?this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*i,this.rotationSpeed.y*this.options.rotationSpeedCorrection*i,this.rotationSpeed.z*this.options.rotationSpeedCorrection*i):(this.stopRotation(!0),this.stopFading()),this.fadeTime=Math.min(this.fadeTime+t,this.options.speedFadeTime)}this.lastTickTS=e}};var jy=`attribute vec2 a_vertex;
70
+ `})|(?<privateuse2>${e}))$`.replace(/[\s\t\n]/g,"");return new RegExp(c,"i")}var jl=O(Nt(),1);import{videoSizeToQuality as PD}from"@vkontakte/videoplayer-shared/es2015";var yy=({id:a,width:e,height:t,bitrate:i,fps:r,quality:s,streamId:n})=>{var u;let o=(u=s?_t(s):void 0)!=null?u:PD({width:e,height:t});return o&&{id:a,quality:o,bitrate:i,size:{width:e,height:t},fps:r,streamId:n}},Ty=({id:a,bitrate:e})=>({id:a,bitrate:e}),Iy=({language:a,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:a,label:e}),Ey=({language:a,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:a,label:e}),Ql=({id:a,language:e,label:t,codecs:i,isDefault:r})=>({id:a,language:e,label:t,codec:(0,jl.default)(i.split("."),0),isDefault:r}),Gl=({id:a,language:e,label:t,hdr:i,codecs:r})=>({id:a,language:e,hdr:i,label:t,codec:(0,jl.default)(r.split("."),0)}),Wl=a=>"url"in a,xe=a=>a.type==="template",Ma=a=>a instanceof DOMException&&(a.name==="AbortError"||a.code===20);var Py=a=>{if(!(a!=null&&a.startsWith("P")))return;let e=(n,o)=>{let u=n?parseFloat(n.replace(",",".")):NaN;return(isNaN(u)?0:u)*o},i=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(a),r=(i==null?void 0:i[1])==="-"?-1:1,s={days:e(i==null?void 0:i[5],r),hours:e(i==null?void 0:i[6],r),minutes:e(i==null?void 0:i[7],r),seconds:e(i==null?void 0:i[8],r)};return s.days*24*60*60*1e3+s.hours*60*60*1e3+s.minutes*60*1e3+s.seconds*1e3},Tt=(a,e)=>{let t=a;t=(0,Yl.default)(t,"$$","$");let i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[r,s]of(0,wy.default)(i)){let n=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=(0,Yl.default)(t,n,(o,u)=>xy(s)?o:xy(u)?s:(0,Ay.default)(s,parseInt(u,10),"0"))}return t},Ry=(a,e)=>{var K,x,H,L,Q,N,Z,R,C,X,P,M,me,Ti,pt,Y,ye,Pe,we,tt,ht,Pt,zt,Ii,dr,Cc,Vc,Oc,Bc,_c,Nc,Fc,qc,Uc,Hc,jc,Qc,Gc,Wc,Yc,zc,Kc,Xc,Jc,Zc,ed,td,id,rd,ad,sd,nd,od,ud,ld,cd,dd,pd,hd,md,fd;let i=new DOMParser().parseFromString(a,"application/xml"),r={video:[],audio:[],text:[]},s=i.children[0],n=Array.from(s.querySelectorAll("MPD > BaseURL").values()).map(Qe=>{var te,Kt;return(Kt=(te=Qe.textContent)==null?void 0:te.trim())!=null?Kt:""}),o=(K=(0,ky.default)(n,0))!=null?K:"",u=s.getAttribute("type")==="dynamic",l=s.getAttribute("availabilityStartTime"),c=s.getAttribute("publishTime"),d=s.getElementsByTagName("vk:Attrs")[0],h=d==null?void 0:d.getElementsByTagName("vk:XLatestSegmentPublishTime")[0].textContent,p=d==null?void 0:d.getElementsByTagName("vk:XStreamIsLive")[0].textContent,m=d==null?void 0:d.getElementsByTagName("vk:XStreamIsUnpublished")[0].textContent,b=d==null?void 0:d.getElementsByTagName("vk:XPlaybackDuration")[0].textContent,g;u&&(g={availabilityStartTime:l?new Date(l).getTime():0,publishTime:c?new Date(c).getTime():0,latestSegmentPublishTime:h?new Date(h).getTime():0,streamIsAlive:p==="yes",streamIsUnpublished:m==="yes"});let v,S=s.getAttribute("mediaPresentationDuration"),y=[...s.getElementsByTagName("Period")],I=y.reduce((Qe,te)=>D(w({},Qe),{[te.id]:te.children}),{}),T=y.reduce((Qe,te)=>D(w({},Qe),{[te.id]:te.getAttribute("duration")}),{});S?v=Py(S):(0,zl.default)(T).filter(Qe=>Qe).length&&!u?v=(0,zl.default)(T).reduce((Qe,te)=>{var Kt;return Qe+((Kt=Py(te))!=null?Kt:0)},0):b&&(v=parseInt(b,10));let $=0,F=(H=(x=s.getAttribute("profiles"))==null?void 0:x.split(","))!=null?H:[];for(let Qe of y.map(te=>te.id))for(let te of I[Qe]){let Kt=(L=te.getAttribute("id"))!=null?L:"id"+($++).toString(10),pr=(Q=te.getAttribute("mimeType"))!=null?Q:"",eo=(N=te.getAttribute("codecs"))!=null?N:"",to=(Z=te.getAttribute("contentType"))!=null?Z:pr==null?void 0:pr.split("/")[0],JT=(C=(R=te.getAttribute("profiles"))==null?void 0:R.split(","))!=null?C:[],bd=(P=Sy((X=te.getAttribute("lang"))!=null?X:""))!=null?P:{},ts=(Ti=(me=(M=te.querySelector("Label"))==null?void 0:M.textContent)==null?void 0:me.trim())!=null?Ti:void 0,ZT=te.querySelectorAll("Representation"),eI=te.querySelector("SegmentTemplate"),tI=(Y=(pt=te.querySelector("Role"))==null?void 0:pt.getAttribute("value"))!=null?Y:void 0,Ei=to,se={id:Kt,language:bd.language,isDefault:tI==="main",label:ts,codecs:eo,hdr:Ei==="video"&&Ul(eo),mime:pr,representations:[]};for(let ee of ZT){let wt=(ye=ee.getAttribute("lang"))!=null?ye:void 0,hr=(we=(Pe=ts!=null?ts:te.getAttribute("label"))!=null?Pe:ee.getAttribute("label"))!=null?we:void 0,is=(Pt=(ht=(tt=ee.querySelector("BaseURL"))==null?void 0:tt.textContent)==null?void 0:ht.trim())!=null?Pt:"",Xt=new URL(is||o,e).toString(),At=(zt=ee.getAttribute("mimeType"))!=null?zt:pr,rs=(dr=(Ii=ee.getAttribute("codecs"))!=null?Ii:eo)!=null?dr:"",as;if(to==="text"){let kt=ee.getAttribute("id")||"",ss=((Cc=bd.privateuse)==null?void 0:Cc.includes("x-auto"))||kt.includes("_auto"),Jt=ee.querySelector("SegmentTemplate");if(Jt){let mr={representationId:(Vc=ee.getAttribute("id"))!=null?Vc:void 0,bandwidth:(Oc=ee.getAttribute("bandwidth"))!=null?Oc:void 0},ns=parseInt((Bc=ee.getAttribute("bandwidth"))!=null?Bc:"",10)/1e3,os=(Nc=parseInt((_c=Jt.getAttribute("startNumber"))!=null?_c:"",10))!=null?Nc:1,xi=parseInt((Fc=Jt.getAttribute("timescale"))!=null?Fc:"",10),io=(qc=Jt.querySelectorAll("SegmentTimeline S"))!=null?qc:[],Pi=Jt.getAttribute("media");if(!Pi)continue;let us=[],ls=0,cs="",wi=0,fr=os,Te=0;for(let Ge of io){let Zt=parseInt((Uc=Ge.getAttribute("d"))!=null?Uc:"",10),Fe=parseInt((Hc=Ge.getAttribute("r"))!=null?Hc:"",10)||0,Rt=parseInt((jc=Ge.getAttribute("t"))!=null?jc:"",10);Te=Number.isFinite(Rt)?Rt:Te;let ei=Zt/xi*1e3,$t=Te/xi*1e3;for(let it=0;it<Fe+1;it++){let Lt=Tt(Pi,D(w({},mr),{segmentNumber:fr.toString(10),segmentTime:(Te+it*Zt).toString(10)})),Ai=($t!=null?$t:0)+it*ei,gr=Ai+ei;fr++,us.push({time:{from:Ai,to:gr},url:Lt})}Te+=(Fe+1)*Zt,ls+=(Fe+1)*ei}wi=Te/xi*1e3,cs=Tt(Pi,D(w({},mr),{segmentNumber:fr.toString(10),segmentTime:Te.toString(10)}));let br={time:{from:wi,to:1/0},url:cs},mt={type:"template",baseUrl:Xt,segmentTemplateUrl:Pi,initUrl:"",totalSegmentsDurationMs:ls,segments:us,nextSegmentBeyondManifest:br,timescale:xi};as={id:kt,kind:"text",segmentReference:mt,profiles:[],duration:v,bitrate:ns,mime:"",codecs:"",width:0,height:0,isAuto:ss}}else as={id:kt,isAuto:ss,kind:"text",url:Xt}}else{let kt=(Gc=(Qc=ee.getAttribute("contentType"))!=null?Qc:At==null?void 0:At.split("/")[0])!=null?Gc:to,ss=(Yc=(Wc=te.getAttribute("profiles"))==null?void 0:Wc.split(","))!=null?Yc:[],Jt=parseInt((zc=ee.getAttribute("width"))!=null?zc:"",10),mr=parseInt((Kc=ee.getAttribute("height"))!=null?Kc:"",10),ns=parseInt((Xc=ee.getAttribute("bandwidth"))!=null?Xc:"",10)/1e3,os=(Jc=ee.getAttribute("frameRate"))!=null?Jc:"",xi=(Zc=ee.getAttribute("quality"))!=null?Zc:void 0,io=os?vy(os):void 0,Pi=(ed=ee.getAttribute("id"))!=null?ed:"id"+($++).toString(10),us=kt==="video"?`${mr}p`:kt==="audio"?`${ns}Kbps`:rs,ls=`${Pi}@${us}`,cs=[...F,...JT,...ss],wi,fr=ee.querySelector("SegmentBase"),Te=(td=ee.querySelector("SegmentTemplate"))!=null?td:eI;if(fr){let mt=(rd=(id=ee.querySelector("SegmentBase Initialization"))==null?void 0:id.getAttribute("range"))!=null?rd:"",[Ge,Zt]=mt.split("-").map(Lt=>parseInt(Lt,10)),Fe={from:Ge,to:Zt},Rt=(ad=ee.querySelector("SegmentBase"))==null?void 0:ad.getAttribute("indexRange"),[ei,$t]=Rt?Rt.split("-").map(Lt=>parseInt(Lt,10)):[],it=Rt?{from:ei,to:$t}:void 0;wi={type:"byteRange",url:Xt,initRange:Fe,indexRange:it}}else if(Te){let mt={representationId:(sd=ee.getAttribute("id"))!=null?sd:void 0,bandwidth:(nd=ee.getAttribute("bandwidth"))!=null?nd:void 0},Ge=parseInt((od=Te.getAttribute("timescale"))!=null?od:"",10),Zt=(ud=Te.getAttribute("initialization"))!=null?ud:"",Fe=Te.getAttribute("media"),Rt=(cd=parseInt((ld=Te.getAttribute("startNumber"))!=null?ld:"",10))!=null?cd:1,ei=Tt(Zt,mt);if(!Fe)throw new ReferenceError("No media attribute in SegmentTemplate");let $t=(dd=Te.querySelectorAll("SegmentTimeline S"))!=null?dd:[],it=[],Lt=0,Ai="",gr=0;if($t.length){let ds=Rt,We=0;for(let ki of $t){let rt=parseInt((pd=ki.getAttribute("d"))!=null?pd:"",10),ti=parseInt((hd=ki.getAttribute("r"))!=null?hd:"",10)||0,ps=parseInt((md=ki.getAttribute("t"))!=null?md:"",10);We=Number.isFinite(ps)?ps:We;let ro=rt/Ge*1e3,ao=We/Ge*1e3;for(let hs=0;hs<ti+1;hs++){let rI=Tt(Fe,D(w({},mt),{segmentNumber:ds.toString(10),segmentTime:(We+hs*rt).toString(10)})),gd=(ao!=null?ao:0)+hs*ro,aI=gd+ro;ds++,it.push({time:{from:gd,to:aI},url:rI})}We+=(ti+1)*rt,Lt+=(ti+1)*ro}gr=We/Ge*1e3,Ai=Tt(Fe,D(w({},mt),{segmentNumber:ds.toString(10),segmentTime:We.toString(10)}))}else if(wD(v)){let We=parseInt((fd=Te.getAttribute("duration"))!=null?fd:"",10)/Ge*1e3,ki=Math.ceil(v/We),rt=0;for(let ti=1;ti<ki;ti++){let ps=Tt(Fe,D(w({},mt),{segmentNumber:ti.toString(10),segmentTime:rt.toString(10)}));it.push({time:{from:rt,to:rt+We},url:ps}),rt+=We}gr=rt,Ai=Tt(Fe,D(w({},mt),{segmentNumber:ki.toString(10),segmentTime:rt.toString(10)}))}let iI={time:{from:gr,to:1/0},url:Ai};wi={type:"template",baseUrl:Xt,segmentTemplateUrl:Fe,initUrl:ei,totalSegmentsDurationMs:Lt,segments:it,nextSegmentBeyondManifest:iI,timescale:Ge}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!kt||!At)continue;let br={video:"video",audio:"audio",text:"text"}[kt];if(!br)continue;Ei||(Ei=br),as={id:ls,kind:br,segmentReference:wi,profiles:cs,duration:v,bitrate:ns,mime:At,codecs:rs,width:Jt,height:mr,fps:io,quality:xi}}se.language||(se.language=wt),se.label||(se.label=hr),se.mime||(se.mime=At),se.codecs||(se.codecs=rs),se.hdr||(se.hdr=Ei==="video"&&Ul(rs)),se.representations.push(as)}if(Ei){let ee=r[Ei].find(wt=>wt.id===se.id);if(ee&&se.representations.every(wt=>xe(wt.segmentReference)))for(let wt of ee.representations){let hr=se.representations.find(At=>At.id===wt.id),is=hr==null?void 0:hr.segmentReference,Xt=wt.segmentReference;Xt.segments.push(...is.segments),Xt.nextSegmentBeyondManifest=is.nextSegmentBeyondManifest}else r[Ei].push(se)}}return{duration:v,streams:r,baseUrls:n,live:g}};var Ly=O(qe(),1);import{isNonNullable as $y}from"@vkontakte/videoplayer-shared/es2015";var oe=(a,e)=>$y(a)&&$y(e)&&a.readyState==="open"&&(0,Ly.default)([...a.activeSourceBuffers],e);var Da=class{constructor(e,t,i,{fetcher:r,tuning:s,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new bi(0);this.currentLowLatencySegmentLength$=new bi(0);this.currentSegmentLength$=new bi(0);this.onLastSegment$=new bi(!1);this.fullyBuffered$=new bi(!1);this.playingRepresentation$=new bi(void 0);this.playingRepresentationInit$=new bi(void 0);this.error$=new kD;this.gaps=[];this.subscription=new RD;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new ve;this.switchAbortController=new ve;this.destroyAbortController=new ve;this.bufferLimit=1/0;this.failedDownloads=0;this.baseUrls=[];this.baseUrlsIndex=0;this.isLive=!1;this.liveUpdateSegmentIndex=0;this.liveInitialAdditionalOffset=0;this.isSeekingLive=!1;this.index=0;this.lastDataObtainedTimestampMs=0;this.loadByteRangeSegmentsTimeoutId=0;this.startWith=jt(this.destroyAbortController.signal,function(e){return ue(this,null,function*(){let t=this.representations.get(e);De(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new AS(this.sourceBuffer),this.subscription.add(Xl(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let o,u=this.mediaSource.readyState;u!=="open"&&(o={id:`SegmentEjection_source_${u}`,category:It.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o!=null||(o={id:"SegmentEjection",category:It.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),this.error$.next(o)})),this.subscription.add(Xl(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:It.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,Cl(this.sourceBuffer.buffered)*.8);this.bufferLimit=u;let l=this.getForwardBufferDuration(o),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(o,n*2,l<c).catch(d=>{this.handleAsyncError(d,"pruneBuffer")})})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(n=>this.error$.next(n))),yield this.loadInit(t,"high",!0);let i=this.initData.get(t.id),r=this.segments.get(t.id),s=this.parsedInitData.get(t.id);De(i,"No init buffer for starting representation"),De(r,"No segments for starting representation"),i instanceof ArrayBuffer&&(this.searchGaps(r,t),yield this.sourceBufferTaskQueue.append(i,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(s))})}.bind(this));this.switchTo=jt(this.destroyAbortController.signal,function(e,t=!1){return ue(this,null,function*(){if(!oe(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);De(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if(Se(s)||Se(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),De(r,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!oe(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer();else{let n=this.getCurrentPosition();ir(n)&&!this.isLive&&(this.bufferLimit=1/0,yield new bs(this.pruneBuffer(n,1/0,!0))),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}this.maintain()}})}.bind(this));this.switchToOld=jt(this.destroyAbortController.signal,function(e,t=!1){return ue(this,null,function*(){if(!oe(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);De(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if(Se(s)||Se(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),De(r,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!oe(this.mediaSource,this.sourceBuffer)))if(yield this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer(),this.maintain();else{let n=this.getCurrentPosition();ir(n)&&(this.isLive||(this.bufferLimit=1/0,yield new bs(this.pruneBuffer(n,1/0,!0))),this.maintain(n)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}})}.bind(this));this.seekLive=jt(this.destroyAbortController.signal,function(e){return ue(this,null,function*(){var u,l;let t=(u=(0,In.default)(e,c=>c.representations))!=null?u:[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let c of this.representations.keys()){let d=t.find(m=>m.id===c);d&&this.representations.set(c,d);let h=this.representations.get(c);if(!h||!xe(h.segmentReference))return;let p=this.getActualLiveStartingSegments(h.segmentReference);this.segments.set(h.id,p)}let i=(l=this.switchingToRepresentationId)!=null?l:this.downloadingRepresentationId,r=this.representations.get(i);De(r);let s=this.segments.get(i);De(s,"No segments for starting representation");let n=this.initData.get(i);if(De(n,"No init buffer for starting representation"),!(n instanceof ArrayBuffer))return;let o=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,yield this.abort(),o&&(yield this.sourceBufferTaskQueue.remove(o.from*1e3,o.to*1e3,this.destroyAbortController.signal)),this.searchGaps(s,r),yield this.sourceBufferTaskQueue.append(n,this.destroyAbortController.signal),this.isSeekingLive=!1})}.bind(this));var c;this.fetcher=r,this.tuning=s,this.compatibilityMode=u,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=o,this.isLive=!!(l!=null&&l.live),this.baseUrls=(c=l==null?void 0:l.baseUrls)!=null?c:[],this.initData=new Map(i.map(d=>[d.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(i.map(d=>[d.id,d])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}switchToWithPreviousAbort(e,t=!1){!oe(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new ve,jt(this.switchAbortController.signal,function(i,r=!1){return ue(this,null,function*(){this.switchingToRepresentationId=i;let s=this.representations.get(i);De(s,`No such representation ${i}`);let n=this.segments.get(i),o=this.initData.get(i);if(Se(o)||Se(n)?yield this.loadInit(s,"high",!1):o instanceof Promise&&(yield o),n=this.segments.get(i),De(n,"No segments for starting representation"),o=this.initData.get(i),!(!(o instanceof ArrayBuffer)||!this.sourceBuffer||!oe(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(o,this.downloadAbortController.signal),r)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=i,yield this.dropBuffer();else{let u=this.getCurrentPosition();ir(u)&&!this.isLive&&(this.bufferLimit=this.forwardBufferTarget,yield this.pruneBuffer(u,1/0,!0)),this.downloadingRepresentationId=i,this.switchingToRepresentationId=void 0}this.maintain()}})}.bind(this))(e,t))}warmUpMediaSource(){!Se(this.sourceBuffer)&&!this.sourceBuffer.updating&&(this.sourceBuffer.mode="segments")}abort(){return E(this,null,function*(){for(let e of this.activeSegments)this.abortSegment(e.segment);return this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new ve,this.abortBuffer()})}maintain(e=this.getCurrentPosition()){if(Se(e)||Se(this.downloadingRepresentationId)||Se(this.playingRepresentationId)||Se(this.sourceBuffer)||!oe(this.mediaSource,this.sourceBuffer)||ir(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if(De(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;let r=i.find(c=>e>=c.time.from&&e<c.time.to);ir(r)&&isFinite(r.time.from)&&isFinite(r.time.to)&&this.currentSegmentLength$.next((r==null?void 0:r.time.to)-r.time.from);let s=e,n=100;if(this.playingRepresentationId!==this.downloadingRepresentationId){let c=this.getForwardBufferDuration(e),d=r?r.time.to+n:-1/0;r&&r.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&c>=r.time.to-e+n&&(s=d)}if(isFinite(this.bufferLimit)&&Cl(this.sourceBuffer.buffered)>=this.bufferLimit){let c=this.getForwardBufferDuration(e),d=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,c<d).catch(h=>{this.handleAsyncError(h,"pruneBuffer")});return}let u=[];if(!this.activeSegments.size&&(u=this.selectForwardBufferSegments(i,t.segmentReference.type,s),u.length)){let c="auto";if(this.tuning.dash.useFetchPriorityHints&&r)if((0,Tn.default)(u,r))c="high";else{let d=(0,rr.default)(u,0);d&&d.time.from-r.time.to>=this.forwardBufferTarget/2&&(c="low")}this.loadSegments(u,t,c).catch(d=>{this.handleAsyncError(d,"loadSegments")})}(!this.preloadOnly&&!this.allInitsLoaded&&r&&r.status==="fed"&&!u.length&&this.getForwardBufferDuration(e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let l=(0,rr.default)(i,-1);!this.isLive&&l&&(this.fullyBuffered$.next(l.time.to-e-this.getForwardBufferDuration(e)<n),this.onLastSegment$.next(e-l.time.from>0))}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}searchGaps(e,t){this.gaps=[];let i=0,r=this.isLive?this.liveInitialAdditionalOffset:0;for(let s of e)Math.trunc(s.time.from-i)>0&&this.gaps.push({representation:t.id,from:i,to:s.time.from+r}),i=s.time.to;ir(t.duration)&&t.duration-i>0&&!this.isLive&&this.gaps.push({representation:t.id,from:i,to:t.duration})}getActualLiveStartingSegments(e){let t=e.segments,i=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,r=[],s=0,n=t.length-1;do r.unshift(t[n]),s+=t[n].time.to-t[n].time.from,n--;while(s<i&&n>=0);return this.liveInitialAdditionalOffset=s-i,this.isActiveLowLatency()?[r[0]]:r}getLiveSegmentsToLoadState(e){let t=(0,In.default)(e==null?void 0:e.streams[this.kind],r=>r.representations).find(r=>r.id===this.downloadingRepresentationId);if(!t)return;let i=this.segments.get(t.id);if(i!=null&&i.length)return{from:i[0].time.from,to:i[i.length-1].time.to}}updateLive(e){var i,r,s,n;let t=(i=(0,In.default)(e==null?void 0:e.streams[this.kind],o=>o.representations))!=null?i:[];if(![...this.segments.values()].every(o=>!o.length))for(let o of t){if(!o||!xe(o.segmentReference))return;let u=o.segmentReference.segments.map(p=>D(w({},p),{status:"none",size:void 0})),l=100,c=(r=this.segments.get(o.id))!=null?r:[],d=(n=(s=(0,rr.default)(c,-1))==null?void 0:s.time.to)!=null?n:0,h=u==null?void 0:u.findIndex(p=>d>=p.time.from+l&&d<=p.time.to+l);if(h===-1){this.liveUpdateSegmentIndex=0;let p=this.getActualLiveStartingSegments(o.segmentReference);this.segments.set(o.id,p)}else{let p=u.slice(h+1);this.segments.set(o.id,[...c,...p])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;De(e);let t=this.segments.get(e);if(t!=null&&t.length){let i=t[t.length-1];this.updateLowLatencyLiveIfNeeded(i)}}updateLowLatencyLiveIfNeeded(e){var i;let t=0;for(let r of this.representations.values()){let s=r.segmentReference;if(!xe(s))return;let n=(i=this.segments.get(r.id))!=null?i:[],o=n.find(l=>Math.floor(l.time.from)===Math.floor(e.time.from));if(o&&!isFinite(o.time.to)&&(o.time.to=e.time.to,t=o.time.to-o.time.from),!!!n.find(l=>Math.floor(l.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let l=Math.round(e.time.to*s.timescale/1e3).toString(10),c=Tt(s.segmentTemplateUrl,{segmentTime:l});n.push({status:"none",time:{from:e.time.to,to:1/0},url:c})}}this.currentLowLatencySegmentLength$.next(t)}findSegmentStartTime(e){var s,n,o;let t=(n=(s=this.switchingToRepresentationId)!=null?s:this.downloadingRepresentationId)!=null?n:this.playingRepresentationId;if(!t)return;let i=this.segments.get(t);if(!i)return;let r=i.find(u=>u.time.from<=e&&u.time.to>=e);return(o=r==null?void 0:r.time.from)!=null?o:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){var e;if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),(e=this.sourceBufferTaskQueue)==null||e.destroy(),this.gapDetectionIdleCallback&&sa&&sa(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&sa&&sa(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer)try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(t){if(!(t instanceof DOMException&&t.name==="NotFoundError"))throw t}this.sourceBuffer=null,this.downloadAbortController.abort(),this.switchAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,i){return this.isLive?this.selectForwardBufferSegmentsLive(e,i):this.selectForwardBufferSegmentsRecord(e,t,i)}selectForwardBufferSegmentsLive(e,t){let i=e.findIndex(r=>t>=r.time.from&&t<r.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=i),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,i){let r=e.findIndex(({status:d,time:{from:h,to:p}},m)=>{let b=h<=i&&p>=i,g=h>i||b||m===0&&i===0,v=Math.min(this.forwardBufferTarget,this.bufferLimit),S=this.preloadOnly&&h<=i+v||p<=i+v;return(d==="none"||d==="partially_ejected"&&g&&S&&this.sourceBuffer&&oe(this.mediaSource,this.sourceBuffer)&&!(Ut(this.sourceBuffer.buffered,h)&&Ut(this.sourceBuffer.buffered,p)))&&g&&S});if(r===-1)return[];if(t!=="byteRange")return e.slice(r,r+1);let s=e,n=0,o=0,u=[],l=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,c=this.preloadOnly?this.forwardBufferTarget:0;for(let d=r;d<s.length&&(n<=l||o<=c);d++){let h=s[d];if(n+=h.byte.to+1-h.byte.from,o+=h.time.to+1-h.time.from,h.status==="none"||h.status==="partially_ejected")u.push(h);else break}return u}loadSegments(e,t,i="auto"){return E(this,null,function*(){xe(t.segmentReference)?yield this.loadTemplateSegment(e[0],t,i):yield this.loadByteRangeSegments(e,t,i)})}loadTemplateSegment(e,t,i="auto"){return E(this,null,function*(){e.status="downloading";let r={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(r);let{range:s,url:n,signal:o,onProgress:u,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(yield jt(o,function(){return ue(this,null,function*(){let c=Jl(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(d=>setTimeout(d,c))})}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let c=yield this.fetcher.fetch(n,{range:s,signal:o,onProgress:u,priority:i,isLowLatency:this.isActiveLowLatency()});if(this.lastDataObtainedTimestampMs=yn(),!c)return;let d=new DataView(c),h=La(t.mime);if(!isFinite(r.segment.time.to)){let b=t.segmentReference.timescale;r.segment.time.to=h.getChunkEndTime(d,b)}u&&r.feedingBytes&&l?yield Promise.all(l):yield this.sourceBufferTaskQueue.append(d,o);let{serverDataReceivedTimestamp:p,serverDataPreparedTime:m}=h.getServerLatencyTimestamps(d);p&&m&&this.currentLiveSegmentServerLatency$.next(m-p),r.segment.status="downloaded",this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(c){this.abortActiveSegments([e]),Ma(c)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}})}updateRepresentationsBaseUrlIfNeeded(){if(!this.tuning.dash.enableBaseUrlSupport||!this.baseUrls.length||this.failedDownloads<=this.tuning.dash.maxSegmentRetryCount)return;this.baseUrlsIndex=(this.baseUrlsIndex+1)%this.baseUrls.length;let e=this.baseUrls[this.baseUrlsIndex];for(let t of this.representations.values())xe(t.segmentReference)?t.segmentReference.baseUrl=e:t.segmentReference.url=e}loadByteRangeSegments(e,t,i="auto"){return E(this,null,function*(){if(!e.length)return;for(let u of e)u.status="downloading",this.activeSegments.add({segment:u,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:r,url:s,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(yield jt(n,function(){return ue(this,null,function*(){let u=Jl(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),Xl(window,"online").pipe(AD()).subscribe(()=>{l(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{yield this.fetcher.fetch(s,{range:r,onProgress:o,signal:n,priority:i}),this.lastDataObtainedTimestampMs=yn(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),Ma(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}})}prepareByteRangeFetchSegmentParams(e,t){if(xe(t.segmentReference))throw new Error("Representation is not byte range type");let i=t.segmentReference.url,r={from:(0,rr.default)(e,0).byte.from,to:(0,rr.default)(e,-1).byte.to},{signal:s}=this.downloadAbortController;return{url:i,range:r,signal:s,onProgress:(o,u)=>E(this,null,function*(){if(!s.aborted)try{this.lastDataObtainedTimestampMs=yn(),yield this.onSomeByteRangesDataLoaded({dataView:o,loaded:u,signal:s,onSegmentAppendFailed:()=>this.abort(),globalFrom:r?r.from:0,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:It.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}})}}prepareTemplateFetchSegmentParams(e,t){if(!xe(t.segmentReference))throw new Error("Representation is not template type");let i=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&i.searchParams.set("low-latency","yes");let r=i.toString(),{signal:s}=this.downloadAbortController,n=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(l,c)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=yn();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:It.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:d})}}:void 0;return{url:r,signal:s,onProgress:u,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)(0,Tn.default)(e,t.segment)&&this.abortSegment(t.segment)}onSomeTemplateDataLoaded(n){return E(this,arguments,function*({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:r,signal:s}){if(!this.activeSegments.size||!oe(this.mediaSource,this.sourceBuffer))return;let o=this.representations.get(t);if(o)for(let u of this.activeSegments){let{segment:l}=u;if(u.representationId===t){if(s.aborted){r();continue}if(u.loadedBytes=i,u.loadedBytes>u.feedingBytes){let c=new DataView(e.buffer,e.byteOffset+u.feedingBytes,u.loadedBytes-u.feedingBytes),d=La(o.mime).parseFeedableSegmentChunk(c,this.isLive);d!=null&&d.byteLength&&(l.status="partially_fed",u.feedingBytes+=d.byteLength,yield this.sourceBufferTaskQueue.append(d),u.fedBytes+=d.byteLength)}}}})}onSomeByteRangesDataLoaded(o){return E(this,arguments,function*({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:s,onSegmentAppendFailed:n}){if(!this.activeSegments.size||!oe(this.mediaSource,this.sourceBuffer))return;let u=this.representations.get(t);if(u)for(let l of this.activeSegments){let{segment:c}=l;if(l.representationId!==t)continue;if(s.aborted){yield n();continue}let d=c.byte.from-i,h=c.byte.to-i,p=h-d+1,m=d<r,b=h<=r;if(!m)continue;let g=La(u.mime);if(c.status==="downloading"&&b){c.status="downloaded";let v=new DataView(e.buffer,e.byteOffset+d,p);(yield this.sourceBufferTaskQueue.append(v,s))&&!s.aborted?this.onSegmentFullyAppended(l,t):yield n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(c.status==="downloading"||c.status==="partially_fed")&&(l.loadedBytes=Math.min(p,r-d),l.loadedBytes>l.feedingBytes)){let v=new DataView(e.buffer,e.byteOffset+d+l.feedingBytes,l.loadedBytes-l.feedingBytes),S=l.loadedBytes===p?v:g.parseFeedableSegmentChunk(v);S!=null&&S.byteLength&&(c.status="partially_fed",l.feedingBytes+=S.byteLength,(yield this.sourceBufferTaskQueue.append(S,s))&&!s.aborted?(l.fedBytes+=S.byteLength,l.fedBytes===p&&this.onSegmentFullyAppended(l,t)):yield n())}}})}onSegmentFullyAppended(e,t){var i;if(!(Se(this.sourceBuffer)||!oe(this.mediaSource,this.sourceBuffer))){!this.isLive&&U.browser.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(Ut(this.sourceBuffer.buffered,e.segment.time.from,100)&&Ut(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:It.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",Wl(e.segment)&&(e.segment.size=e.fedBytes);for(let r of this.representations.values())if(r.id!==t)for(let s of(i=this.segments.get(r.id))!=null?i:[])s.status==="fed"&&Math.round(s.time.from)===Math.round(e.segment.time.from)&&Math.round(s.time.to)===Math.round(e.segment.time.to)&&(s.status="none");this.updateLowLatencyLiveIfNeeded(e.segment),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment])}}abortSegment(e){e.status==="partially_fed"?e.status="partially_ejected":e.status!=="partially_ejected"&&(e.status="none");for(let t of this.activeSegments.values())if(t.segment===e){this.activeSegments.delete(t);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(let[r,s]of this.initData.entries()){let n=s instanceof Promise;t||(t=n),s===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let i=this.representations.get(e);i&&(this.initLoadIdleCallback=Ml(()=>(0,My.default)(this.loadInit(i,"low",!1),()=>this.initLoadIdleCallback=null)))}loadInit(e,t="auto",i=!1){return E(this,null,function*(){let r=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!i&&this.failedDownloads>0?jt(this.destroyAbortController.signal,function(){return ue(this,null,function*(){let o=Jl(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))})}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,La(e.mime),r)).then(o=>E(this,null,function*(){if(!o)return;let{init:u,dataView:l,segments:c}=o,d=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,d);let h=c;this.isLive&&xe(e.segmentReference)&&(h=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,h),u&&this.parsedInitData.set(e.id,u)})).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:It.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n})}dropBuffer(){return E(this,null,function*(){for(let e of this.segments.values())for(let t of e)t.status="none";yield this.pruneBuffer(0,1/0,!0)})}pruneBuffer(e,t,i=!1){return E(this,null,function*(){if(!this.sourceBuffer||!oe(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||Se(e))return!1;let r=[],s=0,n=u=>{u.sort((c,d)=>c.from-d.from);let l=[u[0]];for(let c=1;c<u.length;c++){let{from:d,to:h}=u[c],p=l[l.length-1];p.to>=d?p.to=Math.max(p.to,h):l.push(u[c])}return l},o=u=>{var c;if(s>=t)return r;r.push(w({},u.time)),r=n(r);let l=Wl(u)?(c=u.size)!=null?c:0:u.byte.to-u.byte.from;s+=l};for(let u of this.segments.values())for(let l of u){let c=l.time.to<=e-this.tuning.dash.bufferPruningSafeZone,d=l.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(c||d)&&l.status==="fed"&&o(l)}for(let u=0;u<this.sourceBuffer.buffered.length;u++){let l=this.sourceBuffer.buffered.start(u)*1e3,c=this.sourceBuffer.buffered.end(u)*1e3,d=0;for(let h of this.segments.values())for(let p of h)(0,Tn.default)(["none","partially_ejected"],p.status)&&Math.round(p.time.from)<=Math.round(l)&&Math.round(p.time.to)>=Math.round(c)&&d++;if(d===this.segments.size){let h={time:{from:l,to:c},url:"",status:"none"};o(h)}}if(r.length&&i){let u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let l of this.segments.values())for(let c of l)c.time.from>=e+u&&c.status==="fed"&&o(c)}return r.length?(yield Promise.all(r.map(l=>this.sourceBufferTaskQueue.remove(l.from,l.to)))).reduce((l,c)=>l||c,!1):!1})}abortBuffer(){return E(this,null,function*(){if(!this.sourceBuffer||!oe(this.mediaSource,this.sourceBuffer))return!1;let e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;return this.sourceBufferTaskQueue.abort(t)})}getDebugBufferState(){if(!(!this.sourceBuffer||!oe(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}getForwardBufferDuration(e=this.getCurrentPosition()){return!this.sourceBuffer||!oe(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||Se(e)?0:Ji(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!(!this.sourceBuffer||!oe(this.mediaSource,this.sourceBuffer))){if(this.tuning.useRefactoredSearchGap)for(let i=0;i<this.sourceBuffer.buffered.length;i++)this.gaps=this.gaps.filter(r=>this.sourceBuffer&&(Math.round(r.from)<Math.round(this.sourceBuffer.buffered.start(i)*1e3)||Math.round(r.to)>Math.round(this.sourceBuffer.buffered.end(i)*1e3)));for(let i of t){let r={representation:e,from:i.time.from,to:i.time.to};for(let s=0;s<this.sourceBuffer.buffered.length;s++){let n=this.sourceBuffer.buffered.start(s)*1e3,o=this.sourceBuffer.buffered.end(s)*1e3;if(!(o<=i.time.from||n>=i.time.to)){if(n<=i.time.from&&o>=i.time.to){r=void 0;break}o>i.time.from&&o<i.time.to&&(r.from=o),n<i.time.to&&n>i.time.from&&(r.to=n)}}r&&r.to-r.from>1&&!this.gaps.some(s=>r&&s.from===r.from&&s.to===r.to)&&this.gaps.push(r)}}}detectGapsWhenIdle(e,t){if(!(this.gapDetectionIdleCallback||!this.sourceBuffer||!oe(this.mediaSource,this.sourceBuffer))){if(!this.tuning.useRefactoredSearchGap)for(let i=0;i<this.sourceBuffer.buffered.length;i++)this.gaps=this.gaps.filter(r=>this.sourceBuffer&&(Math.round(r.from)<Math.round(this.sourceBuffer.buffered.start(i)*1e3)||Math.round(r.to)>Math.round(this.sourceBuffer.buffered.end(i)*1e3)));this.gapDetectionIdleCallback=Ml(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:It.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if(Se(this.sourceBuffer)||!oe(this.mediaSource,this.sourceBuffer)||Se(this.playingRepresentationId))return;let e=[];for(let i=0;i<this.sourceBuffer.buffered.length;i++){let r=Math.floor(this.sourceBuffer.buffered.start(i)*1e3),s=Math.ceil(this.sourceBuffer.buffered.end(i)*1e3);e.push({from:r,to:s})}let t=100;for(let i of this.segments.values())for(let r of i){let{status:s}=r;if(s!=="fed"&&s!=="partially_ejected")continue;let n=Math.floor(r.time.from),o=Math.ceil(r.time.to),u=e.some(c=>c.from-t<=n&&c.to+t>=o),l=e.filter(c=>n>=c.from&&n<c.to-t||o>c.from+t&&o<=c.to);u||(l.length===1?r.status="partially_ejected":this.gaps.some(c=>c.from===r.time.from||c.to===r.time.to)?r.status="partially_ejected":r.status="none")}}handleAsyncError(e,t){this.error$.next({id:t,category:It.VIDEO_PIPELINE,thrown:e,message:"Something went wrong"})}};var Ca=a=>{let e=new URL(a);return e.searchParams.set("quic","1"),e.toString()};var Dy=a=>{var s;let e=a.get("X-Delivery-Type"),t=a.get("X-Reused"),i=e===null?"http1":e!=null?e:void 0,r=t===null?void 0:(s={1:!0,0:!1}[t])!=null?s:void 0;return{type:i,reused:r}};import{abortable as Va,assertNever as Vy,fromEvent as Oy,merge as $D,now as Oa,Subscription as LD,Subject as By,ValueSubject as Zl,flattenObject as ar,ErrorCategory as Ba}from"@vkontakte/videoplayer-shared/es2015";var Cy=a=>{let e=new URL(a);return e.searchParams.set("enable-subtitles","yes"),e.toString()};var xn=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:s=!1}){this.lastConnectionType$=new Zl(void 0);this.lastConnectionReused$=new Zl(void 0);this.lastRequestFirstBytes$=new Zl(void 0);this.recoverableError$=new By;this.error$=new By;this.abortAllController=new ve;this.subscription=new LD;this.fetchManifest=Va(this.abortAllController.signal,function(e){return ue(this,null,function*(){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=Ca(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=Cy(i));let r=yield this.doFetch(i,{signal:this.abortAllController.signal}).catch(En);return r?(t.log("success",ar({url:i,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(r.headers),r.text()):(t.error("error",ar({url:i,message:"No data in request manifest"})),t.end(),null)})}.bind(this));this.fetch=Va(this.abortAllController.signal,function(l){return ue(this,arguments,function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:i,onProgress:r,priority:s="auto",signal:n,measureThroughput:o=!0,isLowLatency:u=!1}={}){var L,Q;let c=e,d=new Headers,h=this.tracer.createComponentTracer("Fetch");if(i)switch(t){case 0:{d.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let N=new URL(c,location.href);N.searchParams.append("bytes",`${i.from}-${i.to}`),c=N.toString();break}default:Vy(t)}this.requestQuic&&(c=Ca(c));let p=this.abortAllController.signal,m;if(n){let N=new ve;if(m=$D(Oy(this.abortAllController.signal,"abort"),Oy(n,"abort")).subscribe(()=>{try{N.abort()}catch(Z){En(Z)}}),this.subscription.add(m),this.abortAllController.signal.aborted||n.aborted)try{N.abort()}catch(Z){En(Z)}p=N.signal}let b=Oa();h.log("startRequest",ar({url:c,priority:s,rangeMethod:t,range:i,isLowLatency:u,requestStartedAt:b}));let g=yield this.doFetch(c,{priority:s,headers:d,signal:p}),v=Oa();if(!g)return h.error("error",{message:"No response in request"}),h.end(),m==null||m.unsubscribe(),null;if((L=this.throughputEstimator)==null||L.addRawRtt(v-b),!g.ok||!g.body){m==null||m.unsubscribe();let N=`Fetch error ${g.status}: ${g.statusText}`;return h.error("error",{message:N}),h.end(),Promise.reject(new Error(`Fetch error ${g.status}: ${g.statusText}`))}if(this.onHeadersReceived(g.headers),!r&&!o){m==null||m.unsubscribe();let N=Oa(),Z={requestStartedAt:b,requestEndedAt:N,duration:N-b};return h.log("endRequest",ar(Z)),h.end(),g.arrayBuffer()}let[S,y]=g.body.tee(),I=S.getReader();o&&((Q=this.throughputEstimator)==null||Q.trackStream(y,u));let T=0,$=new Uint8Array(0),F=!1,q=N=>{m==null||m.unsubscribe(),F=!0,En(N)},K=Va(p,function(R){return ue(this,arguments,function*({done:N,value:Z}){if(T===0&&this.lastRequestFirstBytes$.next(Oa()-b),p.aborted){m==null||m.unsubscribe();return}if(!N&&Z){let C=new Uint8Array($.length+Z.length);C.set($),C.set(Z,$.length),$=C,T+=Z.byteLength,r==null||r(new DataView($.buffer),T),yield I==null?void 0:I.read().then(K,q)}})}.bind(this));yield I==null?void 0:I.read().then(K,q),m==null||m.unsubscribe();let x=Oa(),H={failed:F,requestStartedAt:b,requestEndedAt:x,duration:x-b};return F?(h.error("endRequest",ar(H)),h.end(),null):(h.log("endRequest",ar(H)),h.end(),$.buffer)})}.bind(this));this.fetchByteRangeRepresentation=Va(this.abortAllController.signal,function(e,t,i){return ue(this,null,function*(){var v;if(e.type!=="byteRange")return null;let{from:r,to:s}=e.initRange,n=r,o=s,u=!1,l,c;e.indexRange&&(l=e.indexRange.from,c=e.indexRange.to,u=s+1===l,u&&(n=Math.min(l,r),o=Math.max(c,s))),n=Math.min(n,0);let d=yield this.fetch(e.url,{range:{from:n,to:o},priority:i,measureThroughput:!1});if(!d)return null;let h=new DataView(d,r-n,s-n+1);if(!t.validateData(h))throw new Error("Invalid media file");let p=t.parseInit(h),m=(v=e.indexRange)!=null?v:t.getIndexRange(p);if(!m)throw new ReferenceError("No way to load representation index");let b;if(u)b=new DataView(d,m.from-n,m.to-m.from+1);else{let S=yield this.fetch(e.url,{range:m,priority:i,measureThroughput:!1});if(!S)return null;b=new DataView(S)}let g=t.parseSegments(b,p,m);return{init:p,dataView:new DataView(d),segments:g}})}.bind(this));this.fetchTemplateRepresentation=Va(this.abortAllController.signal,function(e,t){return ue(this,null,function*(){if(e.type!=="template")return null;let i=new URL(e.initUrl,e.baseUrl).toString(),r=yield this.fetch(i,{priority:t,measureThroughput:!1});return r?{init:null,segments:e.segments.map(n=>D(w({},n),{status:"none",size:void 0})),dataView:new DataView(r)}:null})}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=r,this.tracer=i.createComponentTracer("Fetcher"),this.useEnableSubtitlesParam=s}onHeadersReceived(e){let{type:t,reused:i}=Dy(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}fetchRepresentation(e,t,i="auto"){return E(this,null,function*(){var s,n;let{type:r}=e;switch(r){case"byteRange":return(s=yield this.fetchByteRangeRepresentation(e,t,i))!=null?s:null;case"template":return(n=yield this.fetchTemplateRepresentation(e,i))!=null?n:null;default:Vy(r)}})}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}doFetch(e,t){return E(this,null,function*(){let i=yield lt(e,t);if(i.ok)return i;let r=yield i.text(),s=parseInt(r);if(!isNaN(s))switch(s){case 1:this.recoverableError$.next({id:"VideoDataLinkExpiredError",message:"Video data links have expired",category:Ba.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:Ba.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:Ba.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:Ba.FATAL});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${s})`,category:Ba.FATAL})}})}},En=a=>{if(!Ma(a))throw a};var gi=(a,e,t)=>t*e+(1-t)*a,ec=(a,e)=>a.reduce((t,i)=>t+i,0)/e,_y=(a,e,t,i)=>{let r=0,s=t,n=ec(a,e),o=e<i?e:i;for(let u=0;u<o;u++)a[s]>n?r++:r--,s=(a.length+s-1)%a.length;return Math.abs(r)===o};import{isNullable as MD,ValueSubject as Ny}from"@vkontakte/videoplayer-shared/es2015";var Qt=class{constructor(e){this.prevReported=void 0;this.pastMeasures=[];this.takenMeasures=0;this.measuresCursor=0;var i;this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new Ny(e.initial),this.debounced$=new Ny(e.initial);let t=(i=e.label)!=null?i:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new Ie(`raw_${t}`),this.smoothedSeries$=new Ie(`smoothed_${t}`),this.reportedSeries$=new Ie(`reported_${t}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,i=0;for(let o=0;o<this.pastMeasures.length;o++)this.pastMeasures[o]!==void 0&&(t+=at(this.pastMeasures[o]-this.smoothed,2),i++);this.takenMeasures=i,t/=i;let r=Math.sqrt(t),s=this.smoothed+this.params.deviationFactor*r,n=this.smoothed-this.params.deviationFactor*r;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(e),this.updateSmoothedValue(e),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),!(this.smoothed>s||this.smoothed<n)&&(MD(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 Pn=class extends Qt{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=gi(this.slow,e,this.params.emaAlphaSlow),this.fast=gi(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var wn=class extends Qt{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=ec(this.pastMeasures,this.takenMeasures);this.emaSmoothed=gi(this.emaSmoothed,e,this.params.emaAlpha);let i=_y(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=i?this.emaSmoothed:t}};var An=class extends Qt{constructor(t){super(t);this.furtherValues=[];this.currentTopExtremumValue=0;this.extremumInterval=t.extremumInterval}next(t){this.currentTopExtremumValue<=t?(this.currentTopExtremumValue=t,this.furtherValues=[]):this.furtherValues.length===this.extremumInterval?(super.next(this.currentTopExtremumValue),this.currentTopExtremumValue=t,this.furtherValues=[]):this.furtherValues.push(t)}updateSmoothedValue(t){this.smoothed=this.smoothed?gi(this.smoothed,t,this.params.emaAlpha):t}};var vi=class{static getSmoothedValue(e,t,i){return i.type==="TwoEma"?new Pn({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new wn({initial:e,emaAlpha:i.emaAlpha,basisTrendChangeCount:i.basisTrendChangeCount,changeThreshold:i.changeThreshold,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"})}static getLiveBufferSmoothedValue(e,t){return new An(w({initial:e,label:"liveEdgeDelay"},t))}};var tc=(a,e)=>{a&&a.playbackRate!==e&&(a.playbackRate=e)};import{isNullable as DD,ValueSubject as CD}from"@vkontakte/videoplayer-shared/es2015";var _a=class a{constructor(e,t){this.currentRepresentation$=new CD(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(!DD(e))for(let i of this.representations)for(let r of i){let s=r.segmentReference,n=s.segments.length,o=s.segments[0].time.from,u=s.segments[n-1].time.to;if(e<o||e>u)continue;let l=s.segments.find(c=>c.time.from<=e&&c.time.to>=e);!l||((t=this.currentSegment)==null?void 0:t.time.from)===l.time.from&&this.currentSegment.time.to===l.time.to||(this.currentSegment=l,this.currentRepresentation$.next(D(w({},r),{label:"Live Text",language:"ru",isAuto:!0,url:new URL(l.url,s.baseUrl).toString()})))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e!=null?e:[]){let i=a.filterRepresentations(t.representations);if(i){this.representations[this.representationsCursor]=i,this.representationsCursor=(this.representationsCursor+1)%this.maxRepresentations;break}}}static isSupported(e){return!!(e!=null&&e.some(t=>a.filterRepresentations(t.representations)))}static filterRepresentations(e){return e==null?void 0:e.filter(t=>t.kind==="text"&&"segmentReference"in t&&xe(t.segmentReference))}};var Rn=O(Nt(),1);import{assertNever as $n}from"@vkontakte/videoplayer-shared/es2015";var Fy=(a,{useHlsJs:e,useManagedMediaSource:t,useOldMSEDetection:i})=>{let{containers:r,protocols:s,codecs:n,nativeHlsSupported:o}=U.video,u=(n.h264||n.h265)&&n.aac,l=s.mse&&(!i||!!window.MediaStreamTrack)||s.mms&&t;return a.filter(c=>{switch(c){case"DASH_SEP":return l&&r.mp4&&u;case"DASH_WEBM":return l&&r.webm&&n.vp9&&n.opus;case"DASH_WEBM_AV1":return l&&r.webm&&n.av1&&n.opus;case"DASH_STREAMS":return l&&(r.mp4&&u||r.webm&&(n.vp9||n.av1)&&(n.opus||n.aac));case"DASH_LIVE":return l&&r.mp4&&u;case"DASH_LIVE_CMAF":return l&&r.mp4&&u&&r.cmaf;case"DASH_ONDEMAND":return l&&r.mp4&&u;case"HLS":case"HLS_ONDEMAND":return o||e&&l&&r.mp4&&u;case"HLS_LIVE":case"HLS_LIVE_CMAF":return o;case"MPEG":return r.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return s.webrtc&&s.ws&&n.h264&&(r.mp4||r.webm);default:return $n(c)}})},kn=a=>{let{webmDecodingInfo:e}=U.video,t="DASH_WEBM",i="DASH_WEBM_AV1";switch(a){case"vp9":return[t,i];case"av1":return[i,t];case"none":return[];case"smooth":return e?e[i].smooth?[i,t]:e[t].smooth?[t,i]:[i,t]:[t,i];case"power_efficient":return e?e[i].powerEfficient?[i,t]:e[t].powerEfficient?[t,i]:[i,t]:[t,i];default:$n(a)}return[t,i]},qy=({webmCodec:a,androidPreferredFormat:e,preferMultiStream:t})=>{let i=[...t?["DASH_STREAMS"]:[],...kn(a),"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]],r=[...t?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]];if(U.device.isAndroid)switch(e){case"mpeg":return["MPEG",...i,"HLS","HLS_ONDEMAND"];case"hls":return["HLS","HLS_ONDEMAND",...i,"MPEG"];case"dash":return[...i,"HLS","HLS_ONDEMAND","MPEG"];case"dash_any_mpeg":return[...r,"MPEG",...kn(a),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...kn(a),"MPEG",...r,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...kn(a),...r,"HLS","HLS_ONDEMAND"];default:$n(e)}return U.video.nativeHlsSupported?[...i,"HLS","HLS_ONDEMAND","MPEG"]:[...i,"HLS","HLS_ONDEMAND","MPEG"]},Uy=({androidPreferredFormat:a,preferCMAF:e,preferWebRTC:t})=>{let i=e?["DASH_LIVE_CMAF","DASH_LIVE"]:["DASH_LIVE","DASH_LIVE_CMAF"],r=e?["HLS_LIVE_CMAF","HLS_LIVE"]:["HLS_LIVE","HLS_LIVE_CMAF"],s=[...i,...r],n=[...r,...i],o,u=U.device.isMac&&U.browser.isSafari;if(U.device.isAndroid)switch(a){case"dash":case"dash_any_mpeg":case"dash_any_webm":case"dash_sep":{o=s;break}case"hls":case"mpeg":{o=n;break}default:$n(a)}else U.video.nativeHlsSupported&&!u?o=n:u?o=e?["DASH_LIVE_CMAF","HLS_LIVE_CMAF","HLS_LIVE","DASH_LIVE"]:["HLS_LIVE","DASH_LIVE","DASH_LIVE_CMAF","HLS_LIVE_CMAF"]:o=s;return t?["WEB_RTC_LIVE",...o]:[...o,"WEB_RTC_LIVE"]},ic=a=>a?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],Hy=a=>{if(a.size===0)return;if(a.size===1){let t=a.values().next();return(0,Rn.default)(t.value.split("."),0)}for(let t of a){let i=(0,Rn.default)(t.split("."),0);if(i==="opus"||i==="vp09"||i==="av01")return i}let e=a.values().next();return(0,Rn.default)(e.value.split("."),0)};var HD=["timeupdate","progress","play","seeked","stalled","waiting"],jD=["timeupdate","progress","loadeddata","playing","seeked"];var Dn=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new Gy;this.representationSubscription=new Gy;this.state$=new B("none");this.currentVideoRepresentation$=new re(void 0);this.currentVideoRepresentationInit$=new re(void 0);this.currentAudioRepresentation$=new re(void 0);this.currentVideoSegmentLength$=new re(0);this.currentAudioSegmentLength$=new re(0);this.error$=new Mn;this.lastConnectionType$=new re(void 0);this.lastConnectionReused$=new re(void 0);this.lastRequestFirstBytes$=new re(void 0);this.currentLiveTextRepresentation$=new re(null);this.isLive$=new re(!1);this.isActiveLive$=new re(!1);this.isLowLatency$=new re(!1);this.liveDuration$=new re(0);this.liveSeekableDuration$=new re(0);this.liveAvailabilityStartTime$=new re(0);this.liveStreamStatus$=new re(void 0);this.bufferLength$=new re(0);this.liveLatency$=new re(void 0);this.liveLoadBufferLength$=new re(0);this.livePositionFromPlayer$=new re(0);this.currentStallDuration$=new re(0);this.videoLastDataObtainedTimestamp$=new re(0);this.fetcherRecoverableError$=new Mn;this.fetcherError$=new Mn;this.liveStreamEndTimestamp=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.forceEnded$=new Mn;this.gapWatchdogActive=!1;this.destroyController=new ve;this.initManifest=ac(this.destroyController.signal,function(e,t,i){return ue(this,null,function*(){var r;this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=ge(t,i,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),(r=this.manifest)!=null&&r.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:ct.PARSER,message:"No playable video representations"})})}.bind(this));this.updateManifest=ac(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=Ry(e!=null?e:"",this.manifestUrlString)}catch(u){let l=(n=TS(e))!=null?n:{id:"ManifestParsing",category:ct.PARSER,message:"Failed to parse MPD manifest",thrown:u};this.error$.next(l)}if(!t)return null;let i=(u,l,c)=>{var d,h,p,m;return!!((h=(d=this.element)==null?void 0:d.canPlayType)!=null&&h.call(d,l)&&((m=(p=Je())==null?void 0:p.isTypeSupported)!=null&&m.call(p,`${l}; codecs="${c}"`))||u==="text")};if(t.live){this.isLive$.next(!!t.live);let{availabilityStartTime:u,latestSegmentPublishTime:l,streamIsUnpublished:c,streamIsAlive:d}=t.live,h=((o=t.duration)!=null?o:0)/1e3;this.liveSeekableDuration$.next(-1*h),this.liveDuration$.next((l-u)/1e3),this.liveAvailabilityStartTime$.next(t.live.availabilityStartTime);let p="active";d||(p=c?"unpublished":"unexpectedly_down"),this.liveStreamStatus$.next(p)}let r={text:t.streams.text,video:[],audio:[]};for(let u of["video","audio"]){let c=t.streams[u].filter(({mime:p,codecs:m})=>i(u,p,m)),d=new Set(c.map(({codecs:p})=>p)),h=Hy(d);if(h&&(r[u]=c.filter(({codecs:p})=>p.startsWith(h))),u==="video"){let p=this.tuning.preferHDR,m=r.video.some(g=>g.hdr),b=r.video.some(g=>!g.hdr);U.display.isHDR&&p&&m?r.video=r.video.filter(g=>g.hdr):b&&(r.video=r.video.filter(g=>!g.hdr))}}let s=D(w({},t),{streams:r});return this.tracer.log("updateManifestEnd",Fa(s)),s})}.bind(this));this.initRepresentations=ac(this.destroyController.signal,function(e,t,i){return ue(this,null,function*(){var h;this.tracer.log("initRepresentationsStart",Fa({initialVideo:e,initialAudio:t,sourceHls:i})),sr(this.manifest),sr(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let r=p=>{this.representationSubscription.add(Et(p,"error").pipe(Ln(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?Ug():new MediaSource;let s=document.createElement("source");if(r(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),this.tuning.useManagedMediaSource&&nn())if(i){let p=document.createElement("source");r(p),p.type="application/x-mpegurl",p.src=i.url,this.element.appendChild(p)}else this.element.disableRemotePlayback=!0;this.isActiveLive$.next(this.isLive$.getValue());let n={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),manifest:this.manifest},o=this.manifest.streams.video.reduce((p,m)=>[...p,...m.representations],[]);if(this.videoBufferManager=new Da("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],qa(t)){let p=this.manifest.streams.audio.reduce((m,b)=>[...m,...b.representations],[]);this.audioBufferManager=new Da("audio",this.source,p,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 p;(p=this.stallWatchdogSubscription)==null||p.unsubscribe(),this.currentStallDuration$.next(0)};if(this.representationSubscription.add(Si(...jD.map(p=>Et(this.element,p))).pipe(or(p=>this.element?Ji(this.element.buffered,this.element.currentTime*1e3):0),Na(),qD(p=>{p>this.tuning.dash.bufferEmptinessTolerance&&u()})).subscribe(this.bufferLength$)),this.representationSubscription.add(Si(Et(this.element,"ended"),this.forceEnded$).subscribe(()=>{u()})),this.isLive$.getValue()){this.subscription.add(this.liveDuration$.pipe(Na()).subscribe(m=>this.liveStreamEndTimestamp=nc())),this.subscription.add(Et(this.element,"pause").subscribe(()=>{this.livePauseWatchdogSubscription=sc(1e3).subscribe(m=>{let b=Zs(this.manifestUrlString,2);this.manifestUrlString=ge(this.manifestUrlString,b+1e3,2),this.liveStreamStatus$.getValue()==="active"&&this.updateManifest()}),this.subscription.add(this.livePauseWatchdogSubscription)})).add(Et(this.element,"play").subscribe(m=>{var b;return(b=this.livePauseWatchdogSubscription)==null?void 0:b.unsubscribe()})),this.representationSubscription.add(nr({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(or(({isActiveLive:m,isLowLatency:b})=>m&&b),Na()).subscribe(m=>{this.isManualDecreasePlaybackInLive()||tc(this.element,1)})),this.representationSubscription.add(nr({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(Ln(({bufferLength:m,isActiveLive:b,isLowLatency:g})=>b&&g&&!!m)).subscribe(({bufferLength:m})=>this.liveBuffer.next(m))),this.representationSubscription.add(this.videoBufferManager.currentLowLatencySegmentLength$.subscribe(m=>{if(!this.isActiveLive$.getValue()&&!this.isLowLatency$.getValue()&&!m)return;let b=this.liveSeekableDuration$.getValue()-m/1e3;this.liveSeekableDuration$.next(Math.max(b,-1*this.tuning.dashCmafLive.maxLiveDuration)),this.liveDuration$.next(this.liveDuration$.getValue()+m/1e3)})),this.representationSubscription.add(nr({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe(Ln(({isLive:m})=>m),Na((m,b)=>b.bufferLength<m.bufferLength),or(({rtt:m,bufferLength:b,segmentServerLatency:g})=>{let v=Zs(this.manifestUrlString,2);return(m/2+b+g+v)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add(nr({liveBuffer:this.liveBuffer.smoothed$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).subscribe(({liveBuffer:m,isActiveLive:b,isLowLatency:g})=>{if(!g||!b)return;let v=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,S=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,y=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,I=m-v;if(this.isManualDecreasePlaybackInLive())return;let T=1;Math.abs(I)>S&&(T=1+Math.sign(I)*y),tc(this.element,T)})),this.representationSubscription.add(this.bufferLength$.subscribe(m=>{var g,v;let b=0;if(m){let S=((v=(g=this.element)==null?void 0:g.currentTime)!=null?v:0)*1e3;b=Math.min(...this.bufferManagers.map(I=>{var T,$;return($=(T=I.getLiveSegmentsToLoadState(this.manifest))==null?void 0:T.to)!=null?$:S}))-S}this.liveLoadBufferLength$.getValue()!==b&&this.liveLoadBufferLength$.next(b)}));let p=0;this.representationSubscription.add(nr({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(UD(1e3)).subscribe(g=>E(this,[g],function*({liveLoadBufferLength:m,bufferLength:b}){if(!this.element||this.isUpdatingLive)return;let v=this.element.playbackRate,S=Zs(this.manifestUrlString,2),y=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,I=Math.min(y,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*v),T=this.tuning.dashCmafLive.normalizedActualBufferOffset*v,$=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*v,F=isFinite(m)?m:b,q=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),K=y<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next(K);let x="none";if(q?x="active_low_latency":this.isLowLatency$.getValue()&&K?(this.bufferManagers.forEach(H=>H.proceedLowLatencyLive()),x="active_low_latency"):S!==0&&F<I?x="live_forward_buffering":F<I+$&&(x="live_with_target_offset"),isFinite(m)&&(p=m>p?m:p),x==="live_forward_buffering"||x==="live_with_target_offset"){let H=p-(I+T),L=this.normolizeLiveOffset(Math.trunc(S+H/v)),Q=Math.abs(L-S),N=0;!m||Q<=this.tuning.dashCmafLive.offsetCalculationError?N=S:L>0&&Q>this.tuning.dashCmafLive.offsetCalculationError&&(N=L),this.manifestUrlString=ge(this.manifestUrlString,N,2)}(x==="live_with_target_offset"||x==="live_forward_buffering")&&(p=0,yield this.updateLive())}),m=>{this.error$.next({id:"updateLive",category:ct.VIDEO_PIPELINE,thrown:m,message:"Failed to update live with subscription"})}))}let l=Si(...this.bufferManagers.map(p=>p.fullyBuffered$)).pipe(or(()=>this.bufferManagers.every(p=>p.fullyBuffered$.getValue()))),c=Si(...this.bufferManagers.map(p=>p.onLastSegment$)).pipe(or(()=>this.bufferManagers.some(p=>p.onLastSegment$.getValue()))),d=nr({allBuffersFull:l,someBufferEnded:c}).pipe(Na(),or(({allBuffersFull:p,someBufferEnded:m})=>p&&m),Ln(p=>p));if(this.representationSubscription.add(Si(this.forceEnded$,d).subscribe(()=>{var p;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(m=>!m.updating))try{(p=this.source)==null||p.endOfStream()}catch(m){this.error$.next({id:"EndOfStream",category:ct.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:m})}})),this.representationSubscription.add(Si(...this.bufferManagers.map(p=>p.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.representationSubscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&(this.representationSubscription.add(this.audioBufferManager.playingRepresentation$.subscribe(this.currentAudioRepresentation$)),this.representationSubscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$))),this.liveTextManager&&this.representationSubscription.add(this.liveTextManager.currentRepresentation$.subscribe(this.currentLiveTextRepresentation$)),this.source.readyState!=="open"){let p=this.tuning.dash.sourceOpenTimeout>=0;yield new Promise((m,b)=>{var g;p&&(this.timeoutSourceOpenId=setTimeout(()=>{var v;if(((v=this.source)==null?void 0:v.readyState)==="open"){m();return}this.tuning.dash.rejectOnSourceOpenTimeout?b(new Error("Timeout reject when wait sourceopen event")):m()},this.tuning.dash.sourceOpenTimeout)),(g=this.source)==null||g.addEventListener("sourceopen",()=>{this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),m()},{once:!0})})}if(!this.isLive$.getValue()){let p=[(h=this.manifest.duration)!=null?h:0,...(0,oc.default)((0,oc.default)([...this.manifest.streams.audio,...this.manifest.streams.video],m=>m.representations),m=>{let b=[];return m.duration&&b.push(m.duration),xe(m.segmentReference)&&m.segmentReference.totalSegmentsDurationMs&&b.push(m.segmentReference.totalSegmentsDurationMs),b})];this.source.duration=Math.max(...p)/1e3}this.audioBufferManager&&qa(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState("representations_ready"),this.tracer.log("initRepresentationsEnd")})}.bind(this));this.tick=()=>{var t,i,r,s;if(!this.element||!this.videoBufferManager||((t=this.source)==null?void 0:t.readyState)!=="open")return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),(i=this.audioBufferManager)==null||i.maintain(e),(r=this.liveTextManager)==null||r.maintain(e),(this.videoBufferManager.gaps.length||(s=this.audioBufferManager)!=null&&s.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=sc(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 xn({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer,useEnableSubtitlesParam:e.tuning.useEnableSubtitlesParam}),this.subscription.add(this.fetcher.recoverableError$.subscribe(this.fetcherRecoverableError$)),this.subscription.add(this.fetcher.error$.subscribe(this.fetcherError$)),this.liveBuffer=vi.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,w({},e.tuning.dashCmafLive.lowLatency.bufferEstimator)),this.initTracerSubscription()}seekLive(e){return E(this,null,function*(){var r,s,n;sr(this.element);let t=this.liveStreamStatus$.getValue()!=="active"?nc()-this.liveStreamEndTimestamp:0,i=this.normolizeLiveOffset(e+t);this.isActiveLive$.next(i===0),this.manifestUrlString=ge(this.manifestUrlString,i,2),this.manifest=yield this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,yield(r=this.videoBufferManager)==null?void 0:r.seekLive(this.manifest.streams.video),yield(s=this.audioBufferManager)==null?void 0:s.seekLive(this.manifest.streams.audio),(n=this.liveTextManager)==null||n.seekLive(this.manifest.streams.text))})}initBuffer(){sr(this.element),this.state$.setState("running"),this.subscription.add(Si(...HD.map(e=>Et(this.element,e)),Et(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:ct.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(Et(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(Et(this.element,"waiting").subscribe(()=>{var t;this.element&&this.element.readyState===2&&!this.element.seeking&&Ut(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{var p,m,b,g,v,S,y,I,T,$,F;if(!this.element||((p=this.source)==null?void 0:p.readyState)!=="open")return;let i=this.currentStallDuration$.getValue();i+=50,this.currentStallDuration$.next(i);let r={timeInWaiting:i},s=nc(),n=100,o=(b=(m=this.videoBufferManager)==null?void 0:m.lastDataObtainedTimestamp)!=null?b:0;this.videoLastDataObtainedTimestamp$.next(o);let u=(v=(g=this.audioBufferManager)==null?void 0:g.lastDataObtainedTimestamp)!=null?v:0,l=(y=(S=this.videoBufferManager)==null?void 0:S.getForwardBufferDuration())!=null?y:0,c=(T=(I=this.audioBufferManager)==null?void 0:I.getForwardBufferDuration())!=null?T:0,d=l<n&&s-o>this.tuning.dash.crashOnStallTWithoutDataTimeout,h=this.audioBufferManager&&c<n&&s-u>this.tuning.dash.crashOnStallTWithoutDataTimeout;if((d||h)&&i>this.tuning.dash.crashOnStallTWithoutDataTimeout||i>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${i} ms`);if(this.isLive$.getValue()&&i%2e3===0){let q=this.normolizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);this.seekLive(q).catch(K=>{this.error$.next({id:"stallIntervalCallback",category:ct.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:K})}),r.liveLastOffset=q}else{let q=this.element.currentTime*1e3;($=this.videoBufferManager)==null||$.maintain(q),(F=this.audioBufferManager)==null||F.maintain(q),r.position=q}this.tracer.log("stallIntervalCallback",Fa(r))};(t=this.stallWatchdogSubscription)==null||t.unsubscribe(),this.stallWatchdogSubscription=sc(50).subscribe(e,i=>{this.error$.next({id:"StallWatchdogCallback",category:ct.NETWORK,message:"Can't restore DASH after stall.",thrown:i})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}switchRepresentation(e,t,i=!1){return E(this,null,function*(){let r={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return this.tuning.useNewSwitchTo?this.currentStallDuration$.getValue()>0?r==null?void 0:r.switchToWithPreviousAbort(t,i):r==null?void 0:r.switchTo(t,i):r==null?void 0:r.switchToOld(t,i)})}seek(e,t){return E(this,null,function*(){var r,s,n,o,u;sr(this.element),sr(this.videoBufferManager);let i;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?i=e:i=Math.max((r=this.videoBufferManager.findSegmentStartTime(e))!=null?r:e,(n=(s=this.audioBufferManager)==null?void 0:s.findSegmentStartTime(e))!=null?n:e),this.warmUpMediaSourceIfNeeded(i),Ut(this.element.buffered,i)||(yield Promise.all([this.videoBufferManager.abort(),(o=this.audioBufferManager)==null?void 0:o.abort()])),!(Qy(this.element)||Qy(this.videoBufferManager))&&(this.videoBufferManager.maintain(i),(u=this.audioBufferManager)==null||u.maintain(i),this.element.currentTime=i/1e3,this.tracer.log("seek",Fa({requestedPosition:e,forcePrecise:t,position:i})))})}warmUpMediaSourceIfNeeded(e=(t=>(t=this.element)==null?void 0:t.currentTime)()){var i;qa(this.element)&&qa(this.source)&&qa(e)&&((i=this.source)==null?void 0:i.readyState)==="ended"&&this.element.duration*1e3-e>this.tuning.dash.seekBiasInTheEnd&&this.bufferManagers.forEach(r=>r.warmUpMediaSource())}get isStreamEnded(){var e;return((e=this.source)==null?void 0:e.readyState)==="ended"}stop(){var e,t,i;this.tracer.log("stop"),(e=this.element)==null||e.querySelectorAll("source").forEach(r=>{URL.revokeObjectURL(r.src),r.remove()}),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),(t=this.videoBufferManager)==null||t.destroy(),this.videoBufferManager=null,(i=this.audioBufferManager)==null||i.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getStreams(){var e;return(e=this.manifest)==null?void 0:e.streams}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){var e;this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),((e=this.source)==null?void 0:e.readyState)==="open"&&Array.from(this.source.sourceBuffers).every(t=>!t.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}initTracerSubscription(){let e=FD(this.tracer.error.bind(this.tracer));this.subscription.add(this.error$.subscribe(e("error")))}isManualDecreasePlaybackInLive(){return!this.element||!this.isLive$.getValue()?!1:1-this.element.playbackRate>this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}updateLive(){return E(this,null,function*(){var e,t;this.isUpdatingLive=!0,this.manifest=yield this.updateManifest(),this.manifest&&((e=this.bufferManagers)==null||e.forEach(i=>i.updateLive(this.manifest)),(t=this.liveTextManager)==null||t.updateLive(this.manifest)),this.isUpdatingLive=!1})}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.getDebugBufferState();if(!e)return;let t=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),i={isJumpGapAfterSeekLive:this.isJumpGapAfterSeekLive,isActiveLowLatency:t,initialCurrentTime:this.element.currentTime};this.isJumpGapAfterSeekLive&&!t&&this.element.currentTime>e.to&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let r=this.element.currentTime*1e3,s=[],n=this.element.readyState===1?this.tuning.endGapTolerance:0;for(let o of this.bufferManagers)for(let u of o.gaps)o.playingRepresentation$.getValue()===u.representation&&u.from-n<=r&&u.to+n>r&&(this.element.duration*1e3-u.to<this.tuning.endGapTolerance?s.push(1/0):s.push(u.to));if(s.length){let o=Math.max(...s)+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,o===1/0?this.forceEnded$.next():(this.element.currentTime=o/1e3,i=D(w({},i),{gapEnds:s,jumpTo:o,resultCurrentTime:this.element.currentTime}),this.tracer.log("jumpGap",Fa(i)))}}};var Cn=class{constructor(e,t){this.fov=e,this.orientation=t}};var Vn=class{constructor(e,t){this.rotating=!1;this.fading=!1;this.lastTickTS=0;this.lastCameraTurnTS=0;this.fadeStartSpeed=null;this.fadeTime=0;this.camera=e,this.options=t,this.rotationSpeed={x:0,y:0,z:0},this.fadeCorrection=1/at(this.options.speedFadeTime/1e3,2)}turnCamera(e=0,t=0,i=0){this.pointCameraTo(this.camera.orientation.x+e,this.camera.orientation.y+t,this.camera.orientation.z+i)}pointCameraTo(e=0,t=0,i=0){t=this.limitCameraRotationY(t);let r=e-this.camera.orientation.x,s=t-this.camera.orientation.y,n=i-this.camera.orientation.z;this.camera.orientation.x=e,this.camera.orientation.y=t,this.camera.orientation.z=i,this.lastCameraTurn={x:r,y:s,z:n},this.lastCameraTurnTS=Date.now()}setRotationSpeed(e,t,i){this.rotationSpeed.x=e!=null?e:this.rotationSpeed.x,this.rotationSpeed.y=t!=null?t:this.rotationSpeed.y,this.rotationSpeed.z=i!=null?i:this.rotationSpeed.z}startRotation(){this.rotating=!0}stopRotation(e=!1){e?(this.setRotationSpeed(0,0,0),this.fadeStartSpeed=null):this.startFading(this.rotationSpeed.x,this.rotationSpeed.y,this.rotationSpeed.z),this.rotating=!1}onCameraRelease(){if(this.lastCameraTurn&&this.lastCameraTurnTS){let e=Date.now()-this.lastCameraTurnTS;if(e<this.options.speedFadeThreshold){let t=(1-e/this.options.speedFadeThreshold)*this.options.rotationSpeedCorrection;this.startFading(this.lastCameraTurn.x*t,this.lastCameraTurn.y*t,this.lastCameraTurn.z*t)}}}startFading(e,t,i){this.setRotationSpeed(e,t,i),this.fadeStartSpeed=w({},this.rotationSpeed),this.fading=!0}stopFading(){this.fadeStartSpeed=null,this.fading=!0,this.fadeTime=0}limitCameraRotationY(e){return Math.max(-this.options.maxYawAngle,Math.min(e,this.options.maxYawAngle))}tick(e){if(!this.lastTickTS){this.lastTickTS=e,this.lastCameraTurnTS=Date.now();return}let t=e-this.lastTickTS,i=t/1e3;if(this.rotating)this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*i,this.rotationSpeed.y*this.options.rotationSpeedCorrection*i,this.rotationSpeed.z*this.options.rotationSpeedCorrection*i);else if(this.fading&&this.fadeStartSpeed){let r=-this.fadeCorrection*at(this.fadeTime/1e3,2)+1;this.setRotationSpeed(this.fadeStartSpeed.x*r,this.fadeStartSpeed.y*r,this.fadeStartSpeed.z*r),r>0?this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*i,this.rotationSpeed.y*this.options.rotationSpeedCorrection*i,this.rotationSpeed.z*this.options.rotationSpeedCorrection*i):(this.stopRotation(!0),this.stopFading()),this.fadeTime=Math.min(this.fadeTime+t,this.options.speedFadeTime)}this.lastTickTS=e}};var Wy=`attribute vec2 a_vertex;
71
71
  attribute vec2 a_texel;
72
72
 
73
73
  varying vec2 v_texel;
@@ -78,7 +78,7 @@ void main(void) {
78
78
  // save texel vector to pass to fragment shader
79
79
  v_texel = a_texel;
80
80
  }
81
- `;var Qy=`#ifdef GL_ES
81
+ `;var Yy=`#ifdef GL_ES
82
82
  precision highp float;
83
83
  precision highp int;
84
84
  #else
@@ -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 Cn=class{constructor(e,t,i){this.videoInitialized=!1;this.active=!1;this.container=e,this.sourceVideoElement=t,this.params=i,this.canvas=this.createCanvas();let r=this.canvas.getContext("webgl");if(!r)throw new Error("Could not initialize WebGL context");this.gl=r,this.container.appendChild(this.canvas),this.camera=new Mn(this.params.fov,this.params.orientation),this.cameraRotationManager=new 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"),i=this.gl.getAttribLocation(this.program,"a_texel"),r=this.gl.getUniformLocation(this.program,"u_texture"),s=this.gl.getUniformLocation(this.program,"u_focus");this.gl.enableVertexAttribArray(t),this.gl.enableVertexAttribArray(i),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.vertexBuffer),this.gl.vertexAttribPointer(t,2,this.gl.FLOAT,!1,0,0),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.vertexAttribPointer(i,2,this.gl.FLOAT,!1,0,0),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.uniform1i(r,0),this.gl.uniform2f(s,-this.camera.orientation.x,-this.camera.orientation.y),this.gl.drawArrays(this.gl.TRIANGLE_FAN,0,4),this.gl.bindTexture(this.gl.TEXTURE_2D,null),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),this.gl.disableVertexAttribArray(t),this.gl.disableVertexAttribArray(i),this.active&&requestAnimationFrame(this.renderFn)}createShader(e,t){let i=this.gl.createShader(t);if(!i)throw this.destroy(),new Error(`Could not create shader (${t})`);if(this.gl.shaderSource(i,e),this.gl.compileShader(i),!this.gl.getShaderParameter(i,this.gl.COMPILE_STATUS))throw this.destroy(),new Error("An error occurred while compiling the shader: "+this.gl.getShaderInfoLog(i));return i}createProgram(){let e=this.gl.createProgram();if(!e)throw this.destroy(),new Error("Could not create shader program");let t=this.createShader(jy,this.gl.VERTEX_SHADER),i=this.createShader(Qy,this.gl.FRAGMENT_SHADER);if(this.gl.attachShader(e,t),this.gl.attachShader(e,i),this.gl.linkProgram(e),!this.gl.getProgramParameter(e,this.gl.LINK_STATUS))throw this.destroy(),new Error("Could not link shader program.");return e}createTexture(){let e=this.gl.createTexture();if(!e)throw this.destroy(),new Error("Could not create texture");return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.bindTexture(this.gl.TEXTURE_2D,null),e}updateTexture(){this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,!0),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.sourceVideoElement),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}createVertexBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create vertex buffer");let t=1,i=1,r=this.frameHeight/(this.frameWidth/this.viewportWidth);return r>this.viewportHeight?t=this.viewportHeight/r:i=r/this.viewportHeight,this.gl.bindBuffer(this.gl.ARRAY_BUFFER,e),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-t,-i,t,-i,t,i,-t,i]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),e}createTextureMappingBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create texture mapping buffer");return e}calculateTexturePosition(){let e=.5-this.camera.orientation.x/360,t=.5-this.camera.orientation.y/180,i=this.camera.fov.x/360/2,r=this.camera.fov.y/180/2,s=e-i,n=t-r,o=e+i,u=t-r,l=e+i,c=t+r,d=e-i,h=t+r;return[s,n,o,u,l,c,d,h]}updateTextureMappingBuffer(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([...this.calculateTexturePosition()]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}updateFrameSize(){this.frameWidth=this.sourceVideoElement.videoWidth,this.frameHeight=this.sourceVideoElement.videoHeight}createCanvas(){let e=document.createElement("canvas");return e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e}};import{isNullable as QD,now as Gy,Subscription as GD,filter as WD,combine as Wy,debounce as YD,ValueSubject as nc,isNonNullable as zD}from"@vkontakte/videoplayer-shared/es2015";var oc=class{constructor(){this.isSeeked$=new nc(!1);this.isBuffering$=new nc(!1);this.currentStallsCount=0;this.maxQualityLimit=void 0;this.lastUniqueVideoTrackSelectedTimestamp=0;this.predictedThroughputWithoutData=0;this.subscription=new GD;this.severeStallOccurred$=new nc(!1)}connect(e){this.currentStallDuration$=e.currentStallDuration$,this.videoLastDataObtainedTimestamp$=e.videoLastDataObtainedTimestamp$,this.throughput$=e.throughput$,this.rtt$=e.rtt$,this.qualityLimitsOnStall=e.qualityLimitsOnStall,this.subscription.add(e.isSeeked$.subscribe(this.isSeeked$)),this.subscription.add(e.isBuffering$.subscribe(this.isBuffering$)),this.subscription.add(e.looped$.subscribe(t=>this.currentStallsCount=0)),this.subscription.add(Wy({isBuffering:this.isBuffering$,isSeeked:this.isSeeked$}).pipe(YD(this.qualityLimitsOnStall.stallDurationToBeCount),WD(({isBuffering:t,isSeeked:i})=>t&&!i)).subscribe(t=>{this.currentStallsCount++})),this.subscription.add(Wy({currentStallDuration:this.currentStallDuration$}).subscribe(({currentStallDuration:t})=>{let{stallDurationNoDataBeforeQualityDecrease:i,stallCountBeforeQualityDecrease:r,resetQualityRestrictionTimeout:s,ignoreStallsOnSeek:n}=this.qualityLimitsOnStall;if(QD(this.lastUniqueVideoTrackSelected)||n&&this.isSeeked$.getValue())return;let o=this.rtt$.getValue(),u=this.throughput$.getValue(),l=this.videoLastDataObtainedTimestamp$.getValue(),c=Gy(),d=r&&this.currentStallsCount>=r,h=i&&c-this.lastUniqueVideoTrackSelectedTimestamp>=i+o&&c-l>=i+o&&t>=i;(d||h)&&(this.severeStallOccurred$.next(!0),window.clearTimeout(this.qualityRestrictionTimer),this.maxQualityLimit=this.lastUniqueVideoTrackSelected.quality,zD(this.lastUniqueVideoTrackSelected.bitrate)&&u>this.lastUniqueVideoTrackSelected.bitrate&&(this.predictedThroughputWithoutData=this.lastUniqueVideoTrackSelected.bitrate)),t||(this.severeStallOccurred$.next(!1),window.clearTimeout(this.qualityRestrictionTimer),this.qualityRestrictionTimer=window.setTimeout(()=>{this.maxQualityLimit=void 0,this.predictedThroughputWithoutData=0},s))}))}get videoMaxQualityLimit(){return this.maxQualityLimit}get predictedThroughput(){return this.predictedThroughputWithoutData}set lastVideoTrackSelected(e){var t;((t=this.lastUniqueVideoTrackSelected)==null?void 0:t.id)!==e.id&&(this.lastUniqueVideoTrackSelected=e,this.lastUniqueVideoTrackSelectedTimestamp=Gy(),this.currentStallsCount=0)}destroy(){window.clearTimeout(this.qualityRestrictionTimer),this.subscription.unsubscribe()}},Yy=oc;import{combine as KD,map as XD,observeElementSize as JD,Subscription as ZD,ValueSubject as uc,noop as eC}from"@vkontakte/videoplayer-shared/es2015";var Vn=class{constructor(){this.subscription=new ZD;this.pipSize$=new uc(void 0);this.videoSize$=new uc(void 0);this.elementSize$=new uc(void 0);this.pictureInPictureWindowRemoveEventListener=eC}connect({observableVideo:e,video:t}){let i=r=>{let s=r.target;this.pipSize$.next({width:s.width,height:s.height})};this.subscription.add(JD(t).subscribe(this.videoSize$)).add(e.enterPip$.subscribe(({pictureInPictureWindow:r})=>{this.pipSize$.next({width:r.width,height:r.height}),r.addEventListener("resize",i),this.pictureInPictureWindowRemoveEventListener=()=>{r.removeEventListener("resize",i)}})).add(e.leavePip$.subscribe(()=>{this.pictureInPictureWindowRemoveEventListener()})).add(KD({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe(XD(({videoSize:r,inPip:s,pipSize:n})=>s?n:r)).subscribe(this.elementSize$))}getValue(){return this.elementSize$.getValue()}subscribe(e,t){return this.elementSize$.subscribe(e,t)}getObservable(){return this.elementSize$}destroy(){this.pictureInPictureWindowRemoveEventListener(),this.subscription.unsubscribe()}};var yi=class{constructor(e){this.subscription=new nC;this.videoState=new _("stopped");this.droppedFramesManager=new mn;this.stallsManager=new Yy;this.elementSizeManager=new Vn;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new Wr;this.audioTrackSwitchHistory=new Wr;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(r.state==="requested"&&(i==null?void 0:i.to)!=="paused"&&e!=="stopped"&&t!=="stopped"&&this.seek(r.position,r.forcePrecise),t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.player.stop(),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),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()):(i==null?void 0:i.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():(i==null?void 0:i.to)==="playing"&&A(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&A(this.params.desiredState.playbackState,"paused");return;default:return iC(e)}}};this.init3DScene=e=>{var i,r,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:((i=e.projectionData)==null?void 0:i.pose.yaw)||0,y:((r=e.projectionData)==null?void 0:r.pose.pitch)||0,z:((s=e.projectionData)==null?void 0:s.pose.roll)||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});let t=this.elementSizeManager.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};this.textTracksManager=new He(e.source.url),this.params=e,this.video=ke(e.container,e.tuning),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(de(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.player=new Ln({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode,tracer:this.tracer}),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params,i=Le(this.video);this.subscription.add(()=>i.destroy());let r=this.constructor.name,s=o=>{e.error$.next({id:r,category:zy.WTF,message:`${r} internal logic error`,thrown:o})};return{output:e,desiredState:t,observableVideo:i,genericErrorListener:s,connect:(o,u)=>this.subscription.add(o.subscribe(u,s))}}subscribe(){let{output:e,desiredState:t,observableVideo:i,genericErrorListener:r,connect:s}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe(lc(l=>!!l.length),Xy()).subscribe(l=>{this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks:l})}));let n=this.params.desiredState.seekState.stateChangeEnded$.pipe(cc(l=>l.to.state!=="none"),qa());this.stallsManager.connect({isSeeked$:n,currentStallDuration$:this.player.currentStallDuration$.pipe(qa()),videoLastDataObtainedTimestamp$:this.player.videoLastDataObtainedTimestamp$,throughput$:this.params.dependencies.throughputEstimator.throughput$,rtt$:this.params.dependencies.throughputEstimator.rtt$,qualityLimitsOnStall:this.params.tuning.dash.qualityLimitsOnStall,isBuffering$:i.isBuffering$,looped$:i.looped$}),s(i.ended$,e.endedEvent$),s(i.looped$,e.loopedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(i.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),s(i.loadedMetadata$,e.loadedMetadataEvent$),s(this.player.error$,e.error$),s(this.player.fetcherRecoverableError$,e.fetcherRecoverableError$),s(this.player.fetcherError$,e.fetcherError$),s(this.player.lastConnectionType$,e.httpConnectionType$),s(this.player.lastConnectionReused$,e.httpConnectionReused$),s(this.player.isLive$,e.isLive$),s(this.player.lastRequestFirstBytes$.pipe(lc(Ky),Xy()),e.firstBytesEvent$),s(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),s(this.videoState.stateChangeEnded$.pipe(cc(l=>l.to)),this.params.output.playbackState$),this.subscription.add(i.loopExpected$.subscribe(l=>{t.seekState.setState({state:"requested",position:0,forcePrecise:!1})})),this.subscription.add(i.looped$.subscribe(()=>this.player.warmUpMediaSourceIfNeeded(),r)),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(ot(this.video,t.isLooped,r)),this.subscription.add(Re(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Ue(this.video,t.playbackRate,i.playbackRateState$,r)),this.elementSizeManager.connect({video:this.video,observableVideo:i}),s(je(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),A(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),A(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:l})=>{if(l==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let c=this.player.getStreams();if(rC(c,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let h=[];for(let p of c.audio){h.push(Hl(p));let m=[];for(let b of p.representations){let g=vy(b);m.push(g),this.audioTracksMap.set(g,{stream:p,representation:b})}this.audioStreamsMap.set(p,m)}this.params.output.availableAudioStreams$.next(h)}let d=[];for(let h of c.video){d.push(jl(h));let p=[];for(let m of h.representations){let b=gy(D(w({},m),{streamId:h.id}));b&&(p.push(b),this.videoTracksMap.set(b,{stream:h,representation:m}))}this.videoStreamsMap.set(h,p)}this.params.output.availableVideoStreams$.next(d);for(let h of c.text)for(let p of h.representations){let m=Sy(h,p);this.textTracksMap.set(m,{stream:h,representation:p})}this.params.output.availableVideoTracks$.next(Array.from(this.videoTracksMap.keys())),this.params.output.availableAudioTracks$.next(Array.from(this.audioTracksMap.keys())),this.params.output.isAudioAvailable$.next(!!this.audioTracksMap.size),this.audioTracksMap.size&&this.textTracksMap.size&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else l==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},r)),this.subscription.add(On(this.player.currentStallDuration$,this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,this.elementSizeManager.getObservable(),this.params.output.elementVisible$,this.droppedFramesManager.onDroopedVideoFramesLimit$,sC(this.video,"progress")).pipe(lc(()=>this.videoTracksMap.size>0)).subscribe(()=>E(this,null,function*(){let l=this.player.state$.getState(),c=this.player.state$.getTransition();if(!(0,Jy.default)(["manifest_ready","running"],l)||c)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let d=this.selectVideoAudioRepresentations();if(!d)return;let[h,p]=d,m=[...this.videoTracksMap.keys()].find(g=>{var v;return((v=this.videoTracksMap.get(g))==null?void 0:v.representation.id)===h.id});Ky(m)&&(this.stallsManager.lastVideoTrackSelected=m);let b=this.params.desiredState.autoVideoTrackLimits.getTransition();if(b&&this.params.output.autoVideoTrackLimits$.next(b.to),l==="manifest_ready")yield this.player.initRepresentations(h.id,p==null?void 0:p.id,this.params.sourceHls);else if(yield this.player.switchRepresentation("video",h.id),p){let g=!!t.audioStream.getTransition();yield this.player.switchRepresentation("audio",p.id,g)}}),r)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:l})=>{this.scene3D&&l&&this.scene3D.pointCameraTo(l.x,l.y)})),this.subscription.add(this.elementSizeManager.subscribe(l=>{this.scene3D&&l&&this.scene3D.setViewportSize(l.width,l.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(qa()).subscribe(l=>{let c=[...this.videoTracksMap.entries()].find(([,{representation:m}])=>m.id===l);if(!c){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[d,{stream:h}]=c,p=this.params.desiredState.videoStream.getTransition();p&&p.to&&p.to.id===h.id&&this.params.desiredState.videoStream.setState(p.to),e.currentVideoTrack$.next(d),e.currentVideoStream$.next(jl(h))},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(qa()).subscribe(l=>{let c=[...this.audioTracksMap.entries()].find(([,{representation:m}])=>m.id===l);if(!c){e.currentAudioStream$.next(void 0);return}let[d,{stream:h}]=c,p=this.params.desiredState.audioStream.getTransition();p&&p.to&&p.to.id===h.id&&this.params.desiredState.audioStream.setState(p.to),e.currentAudioStream$.next(Hl(h))},r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(l=>{var c,d;if(l!=null&&l.is3dVideo&&((c=this.params.tuning.spherical)!=null&&c.enabled))try{this.init3DScene(l),e.is3DVideo$.next(!0)}catch(h){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${h}`})}else this.destroy3DScene(),(d=this.params.tuning.spherical)!=null&&d.enabled&&e.is3DVideo$.next(!1)},r)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,r)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,r)),this.textTracksManager.connect(this.video,t,e);let o=t.playbackState.stateChangeStarted$.pipe(cc(({to:l})=>l==="ready"),qa());this.subscription.add(On(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,dc(["init"])).subscribe(()=>{let l=t.autoVideoTrackSwitching.getState(),d=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:l?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(d)})),this.subscription.add(On(o,this.player.state$.stateChangeEnded$,dc(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let u=On(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,dc(["init"])).pipe(aC(0));this.subscription.add(u.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){var F,q,K,x,j,L,Q,N,Z,R,C,X,P;if(this.player.isStreamEnded)return;let{desiredState:e,output:t}=this.params,i=e.autoVideoTrackSwitching.getState(),r=(F=e.videoTrack.getState())==null?void 0:F.id,n=[...this.videoTracksMap.keys()].find(({id:M})=>M===r),o=t.currentVideoTrack$.getValue(),u=((x=(K=e.videoStream.getState())!=null?K:n&&((q=this.videoTracksMap.get(n))==null?void 0:q.stream))!=null?x:this.videoStreamsMap.size===1)?this.videoStreamsMap.keys().next().value:void 0;if(!u)return;let l=[...this.videoStreamsMap.keys()].find(({id:M})=>M===u.id),c=l&&this.videoStreamsMap.get(l);if(!c)return;let d=Ji(this.video.buffered,this.video.currentTime*1e3),h;this.player.isActiveLive$.getValue()?h=this.player.isLowLatency$.getValue()?this.params.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.params.tuning.dashCmafLive.normalizedLiveMinBufferSize:this.player.isLive$.getValue()?h=this.params.tuning.dashCmafLive.normalizedTargetMinBufferSize:h=i?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;let p=(this.video.duration*1e3||1/0)-this.video.currentTime*1e3,m=Math.min(d/Math.min(h,p||1/0),1),b=(j=e.audioStream.getState())!=null?j:this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0,g=(L=[...this.audioStreamsMap.keys()].find(({id:M})=>M===(b==null?void 0:b.id)))!=null?L:this.audioStreamsMap.keys().next().value,v=0;if(g){if(n&&!i){let M=cn(n,c,(Q=this.audioStreamsMap.get(g))!=null?Q:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);v=Math.max(v,(N=M==null?void 0:M.bitrate)!=null?N:-1/0)}if(o){let M=cn(o,c,(Z=this.audioStreamsMap.get(g))!=null?Z:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);v=Math.max(v,(R=M==null?void 0:M.bitrate)!=null?R:-1/0)}}let S=qt(c,{container:this.elementSizeManager.getValue(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:v,forwardBufferHealth:m,current:o,visible:this.params.output.elementVisible$.getValue(),history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,stallsVideoMaxQualityLimit:this.stallsManager.videoMaxQualityLimit,stallsPredictedThroughput:this.stallsManager.predictedThroughput,abrLogger:this.params.dependencies.abrLogger}),y=i?S!=null?S:n:n!=null?n:S,I=g&&hv(y,c,(C=this.audioStreamsMap.get(g))!=null?C:[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:m,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),T=(X=this.videoTracksMap.get(y))==null?void 0:X.representation,$=I&&((P=this.audioTracksMap.get(I))==null?void 0:P.representation);if(T&&$)return[T,$];if(T&&!$&&this.audioTracksMap.size===0)return[T,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){Me(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),A(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:zy.DOM,thrown:e}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.stallsManager.destroy(),this.elementSizeManager.destroy(),this.destroy3DScene(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),this.params.output.currentVideoStream$.next(void 0),Ae(this.video),this.tracer.end()}};var Ua=class extends yi{subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();i(t.timeUpdate$,e.position$),i(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}};import{combine as pc,merge as Zy,filter as eT,filterChanged as oC,isNullable as hc,map as tT,ValueSubject as mc,isNonNullable as uC}from"@vkontakte/videoplayer-shared/es2015";var Ha=class extends yi{constructor(e){super(e),this.textTracksManager.destroy()}subscribe(){super.subscribe();let e=-1,{output:t,observableVideo:i,desiredState:r,connect:s}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),s(i.timeUpdate$,t.liveBufferTime$),s(this.player.liveSeekableDuration$,t.duration$),s(this.player.liveLatency$,t.liveLatency$);let n=new mc(1);s(i.playbackRateState$,n),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(r.isLowLatency.stateChangeEnded$.pipe(tT(o=>o.to)).subscribe(this.player.isLowLatency$)).add(pc({liveBufferTime:t.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(tT(({liveBufferTime:o,liveAvailabilityStartTime:u})=>o&&u?o+u:void 0)).subscribe(t.liveTime$)).add(this.player.liveStreamStatus$.pipe(eT(o=>uC(o))).subscribe(o=>t.isLiveEnded$.next(o!=="active"&&t.position$.getValue()===0))).add(pc({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:Zy(i.playbackRateState$,new mc(1))}).pipe(eT(({liveStreamStatus:o,liveDuration:u})=>o==="active"&&!!u)).subscribe(({liveDuration:o,playbackRate:u})=>{let l=t.liveBufferTime$.getValue(),c=t.position$.getValue(),{playbackCatchupSpeedup:d}=this.params.tuning.dashCmafLive.lowLatency;c||u<1-d||this.video.paused||hc(l)||(e=o-l)})).add(pc({time:t.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:Zy(i.playbackRateState$,new mc(1))}).pipe(oC((o,u)=>this.player.liveStreamStatus$.getValue()==="active"?o.liveDuration===u.liveDuration:o.time===u.time)).subscribe(({time:o,liveDuration:u,playbackRate:l})=>{let c=t.position$.getValue(),{playbackCatchupSpeedup:d}=this.params.tuning.dashCmafLive.lowLatency;if(!c&&!this.video.paused&&l>=1-d||hc(o)||hc(u))return;let h=-1*(u-o-e);t.position$.next(Math.min(h,0))})).add(this.player.currentLiveTextRepresentation$.subscribe(o=>{if(o){let u=yy(o);this.params.output.availableTextTracks$.next([u])}}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,i=Math.trunc(t/1e3<=Math.abs(this.params.output.duration$.getValue())?t:0);this.player.seekLive(i).then(()=>{this.params.output.position$.next(e/1e3)})}};var rT=O(Ks(),1);import{assertNever as ja,assertNonNullable as iT,debounce as lC,ErrorCategory as _n,filter as cC,isNonNullable as dC,isNullable as pC,map as Bn,merge as hC,Observable as mC,observableFrom as fC,Subscription as bC,videoSizeToQuality as gC}from"@vkontakte/videoplayer-shared/es2015";var et={};var ur=(a,e)=>new mC(t=>{let i=(r,s)=>t.next(s);return a.on(e,i),()=>a.off(e,i)}),Qa=class{constructor(e){this.subscription=new bC;this.videoState=new _("initializing");this.trackLevels=new Map;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(e!=="initializing")switch((i==null?void 0:i.to)!=="paused"&&r.state==="requested"&&this.seek(r.position),t){case"stopped":switch(e){case"stopped":break;case"ready":case"playing":case"paused":this.stop();break;default:ja(e)}break;case"ready":switch(e){case"stopped":this.prepare();break;case"ready":case"playing":case"paused":break;default:ja(e)}break;case"playing":switch(e){case"playing":break;case"stopped":this.prepare();break;case"ready":case"paused":this.playIfAllowed();break;default:ja(e)}break;case"paused":switch(e){case"paused":break;case"stopped":this.prepare();break;case"ready":this.videoState.setState("paused"),A(this.params.desiredState.playbackState,"paused");break;case"playing":this.pause();break;default:ja(e)}break;default:ja(t)}};this.textTracksManager=new He(e.source.url),this.video=ke(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=r=>{e||this.params.output.error$.next({id:r==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:_n.NETWORK,message:"Failed to load Hls.js",thrown:r}),e=!0},i=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);(0,rT.default)(import("hls.js").then(r=>{e||(et.Hls=r.default,et.Events=r.default.Events,this.init())},t),()=>{window.clearTimeout(i),e=!0})}init(){iT(et.Hls,"hls.js not loaded"),this.hls=new et.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState("stopped")}subscribe(){iT(et.Events,"hls.js not loaded");let{desiredState:e,output:t}=this.params,i=l=>{t.error$.next({id:"HlsJsProvider",category:_n.WTF,message:"HlsJsProvider internal logic error",thrown:l})},r=Le(this.video);this.subscription.add(()=>r.destroy());let s=(l,c)=>this.subscription.add(l.subscribe(c,i));s(r.timeUpdate$,t.position$),s(r.durationChange$,t.duration$),s(r.ended$,t.endedEvent$),s(r.looped$,t.loopedEvent$),s(r.error$,t.error$),s(r.isBuffering$,t.isBuffering$),s(r.currentBuffer$,t.currentBuffer$),s(r.loadStart$,t.firstBytesEvent$),s(r.loadedMetadata$,t.loadedMetadataEvent$),s(r.playing$,t.firstFrameEvent$),s(r.canplay$,t.canplay$),s(r.seeked$,t.seekedEvent$),s(r.inPiP$,t.inPiP$),s(r.inFullscreen$,t.inFullscreen$),this.subscription.add(ot(this.video,e.isLooped,i)),this.subscription.add(Re(this.video,e.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(Ue(this.video,e.playbackRate,r.playbackRateState$,i)),s(je(this.video),t.elementVisible$),s(this.videoState.stateChangeEnded$.pipe(Bn(l=>l.to)),this.params.output.playbackState$),this.subscription.add(ur(this.hls,et.Events.ERROR).subscribe(l=>{var c;l.fatal&&t.error$.next({id:["HlsJsFatal",l.type,l.details].join("_"),category:_n.WTF,message:`HlsJs fatal ${l.type} ${l.details}, ${(c=l.err)==null?void 0:c.message} ${l.reason}`,thrown:l.error})})),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),A(e.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),A(e.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{var l;((l=this.videoState.getTransition())==null?void 0:l.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),s(ur(this.hls,et.Events.MANIFEST_PARSED).pipe(Bn(({levels:l})=>l.reduce((c,d)=>{var S,y;let h=d.name||d.height.toString(10),{width:p,height:m}=d,b=(y=Bt((S=d.attrs.QUALITY)!=null?S:""))!=null?y:gC({width:p,height:m});if(!b)return c;let g=d.attrs["FRAME-RATE"]?parseFloat(d.attrs["FRAME-RATE"]):void 0,v={id:h.toString(),quality:b,bitrate:d.bitrate/1e3,size:{width:p,height:m},fps:g};return this.trackLevels.set(h,{track:v,level:d}),c.push(v),c},[]))),t.availableVideoTracks$),s(ur(this.hls,et.Events.MANIFEST_PARSED),l=>{if(l.subtitleTracks.length>0){let c=[];for(let d of l.subtitleTracks){let h=d.name,p=d.attrs.URI||"",m=d.lang;c.push({id:h,url:p,language:m,type:"internal"})}e.internalTextTracks.startTransitionTo(c)}}),s(ur(this.hls,et.Events.LEVEL_LOADING).pipe(Bn(({url:l})=>de(l))),t.hostname$),s(ur(this.hls,et.Events.FRAG_CHANGED),l=>{var h,p,m,b;let{video:c,audio:d}=l.frag.elementaryStreams;t.currentVideoSegmentLength$.next((((h=c==null?void 0:c.endPTS)!=null?h:0)-((p=c==null?void 0:c.startPTS)!=null?p:0))*1e3),t.currentAudioSegmentLength$.next((((m=d==null?void 0:d.endPTS)!=null?m:0)-((b=d==null?void 0:d.startPTS)!=null?b:0))*1e3)}),this.subscription.add(Vt(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,l=>{this.hls.nextLevel=l?-1:this.hls.currentLevel,this.hls.loadLevel=l?-1:this.hls.loadLevel},{onError:i}));let n=l=>{var c;return(c=Array.from(this.trackLevels.values()).find(({level:d})=>d===l))==null?void 0:c.track},o=ur(this.hls,et.Events.LEVEL_SWITCHED).pipe(Bn(({level:l})=>n(this.hls.levels[l])));o.pipe(cC(dC)).subscribe(t.currentVideoTrack$,i),this.subscription.add(Vt(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel]),l=>{var m;if(pC(l))return;let c=(m=this.trackLevels.get(l.id))==null?void 0:m.level;if(!c)return;let d=this.hls.levels.indexOf(c),h=this.hls.currentLevel,p=this.hls.levels[h];!p||c.bitrate>p.bitrate?this.hls.nextLevel=d:(this.hls.loadLevel=d,this.hls.loadLevel=d)},{changed$:o,onError:i})),s(r.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);let u=hC(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,fC(["init"])).pipe(lC(0));this.subscription.add(u.subscribe(this.syncPlayback,i))}prepare(){this.videoState.startTransitionTo("ready"),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}playIfAllowed(){return E(this,null,function*(){this.videoState.startTransitionTo("playing"),(yield Me(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:_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 aT="X-Playback-Duration",fc=a=>E(void 0,null,function*(){var r;let e=yield lt(a),t=yield e.text(),i=(r=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t))==null?void 0:r[1];return i?parseInt(i,10):e.headers.has(aT)?parseInt(e.headers.get(aT),10):void 0});import{assertNever as AC,combine as RC,debounce as $C,ErrorCategory as qn,filter as LC,filterChanged as MC,isNonNullable as oT,isNullable as Un,map as uT,merge as DC,observableFrom as CC,Subscription as VC,ValueSubject as vc,VideoQuality as OC}from"@vkontakte/videoplayer-shared/es2015";var gc=O(hu(),1);import{videoSizeToQuality as vC,getExponentialDelay as SC}from"@vkontakte/videoplayer-shared/es2015";var yC=a=>{let e=null;if(a.QUALITY&&(e=Bt(a.QUALITY)),!e&&a.RESOLUTION){let[t,i]=a.RESOLUTION.split("x").map(r=>parseInt(r,10));e=vC({width:t,height:i})}return e!=null?e:null},TC=(a,e)=>{var s,n;let t=a.split(`
125
- `),i=[],r=[];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,gc.default)(l[1].split(",").map(S=>S.split("="))),h=(s=d.QUALITY)!=null?s:`stream-${d.BANDWIDTH}`,p=yC(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,y]=d.RESOLUTION.split("x").map(I=>parseInt(I,10));S&&y&&(g={width:S,height:y})}let v=new URL(t[++o],e).toString();p&&i.push({id:h,quality:p,url:v,bandwidth:m,size:g,fps:b})}if(c){let d=(0,gc.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,"")])),h=(n=d.URI)==null?void 0:n.replace(/playlist$/,"subtitles.vtt"),p=d.LANGUAGE,m=d.NAME;h&&p&&r.push({type:"internal",id:p,label:m,language:p,url:h,isAuto:!1})}}}if(!i.length)throw new Error("Empty manifest");return{qualityManifests:i,textTracks:r}},IC=a=>new Promise(e=>{setTimeout(()=>{e()},a)}),bc=0,sT=(r,...s)=>E(void 0,[r,...s],function*(a,e=a,t,i){let o=yield(yield lt(a,i)).text();bc+=1;try{let{qualityManifests:u,textTracks:l}=TC(o,e);return{qualityManifests:u,textTracks:l}}catch(u){if(bc<=t.manifestRetryMaxCount)return yield IC(SC(bc-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),sT(a,e,t)}return{qualityManifests:[],textTracks:[]}}),Nn=sT;import{isNonNullable as EC,Subscription as xC,throttle as PC,ValueSubject as nT,Subject as wC,ErrorCategory as kC}from"@vkontakte/videoplayer-shared/es2015";var Fn=class{constructor(e,t,i,r,s){this.subscription=new xC;this.abortControllers={destroy:new ve,nextManifest:null};this.prepareUrl=void 0;this.currentTextTrackData=null;this.availableTextTracks$=new nT(null);this.getCurrentTime$=new nT(null);this.error$=new wC;this.params={fetchManifestData:i,sourceUrl:r,downloadThreshold:s},this.subscription.add(e.pipe(PC(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:i}=yield this.fetchManifestData();yield this.processTextTracks(i,this.params.sourceUrl)}catch(t){this.error("prepare",t)}})}processTextTracks(e,t){return E(this,null,function*(){try{let i=yield this.parseTextTracks(e,t);i&&(this.currentTextTrackData=i)}catch(i){this.error("processTextTracks",i)}})}parseTextTracks(e,t){return E(this,null,function*(){for(let i of e){let r=new URL(i.url,t).toString(),n=yield(yield lt(r,{signal:this.abortControllers.destroy.signal})).text(),o=this.parsePlaylist(n,r);return{textTrack:i,playlist:o}}})}parsePlaylist(e,t){let i={mediaSequence:0,programDateTime:"",segments:[],targetDuration:0,vkPlaybackDuration:0,segmentStartTime:0,vkStartTime:""},r=e.split(`
126
- `),s=0;for(let n=0;n<r.length;++n){let o=r[n];switch(!0){case o.startsWith("#EXTINF:"):{let u=r[++n],l=new URL(u,t).toString(),c=Number(this.extractPlaylistRowValue("#EXTINF:",o))*1e3;if(i.segments.push({time:{from:s,to:s+c},url:l}),s=s+c,!i.segmentStartTime){let d=new Date(i.vkStartTime).valueOf(),h=new Date(i.programDateTime).valueOf();i.segmentStartTime=h-d}break}case o.startsWith("#EXT-X-TARGETDURATION:"):i.targetDuration=Number(this.extractPlaylistRowValue("#EXT-X-TARGETDURATION:",o));break;case o.startsWith("#EXT-X-MEDIA-SEQUENCE:"):i.mediaSequence=Number(this.extractPlaylistRowValue("#EXT-X-MEDIA-SEQUENCE:",o));break;case o.startsWith("#EXT-X-VK-PLAYBACK-DURATION:"):i.vkPlaybackDuration=Number(this.extractPlaylistRowValue("#EXT-X-VK-PLAYBACK-DURATION:",o));break;case o.startsWith("#EXT-X-PROGRAM-DATE-TIME:"):{let u=this.extractPlaylistRowValue("#EXT-X-PROGRAM-DATE-TIME:",o);i.programDateTime=u;let l=new Date(u);l.setMilliseconds(0),s=l.valueOf();break}case o.startsWith("#EXT-X-VK-START-TIME:"):i.vkStartTime=this.extractPlaylistRowValue("#EXT-X-VK-START-TIME:",o);break}}return i}extractPlaylistRowValue(e,t){switch(e){case"#EXTINF:":return t.substring(e.length,t.length-1);default:return t.substring(e.length)}}processLiveTime(e){if(EC(e)&&this.currentTextTrackData){let{segments:t}=this.currentTextTrackData.playlist,{from:i}=t[0].time,{to:r}=t[t.length-1].time;if(e<i||e>r)return;r-e<this.params.downloadThreshold&&this.fetchNextManifestData();for(let n of t)if(n.time.from<=e&&n.time.to>=e){this.availableTextTracks$.next([D(w({},this.currentTextTrackData.textTrack),{url:n.url,isAuto:!0})]);break}}}fetchNextManifestData(){return E(this,null,function*(){try{if(this.abortControllers.nextManifest)return;this.abortControllers.nextManifest=new ve;let{textTracks:e}=yield this.fetchManifestData(),t=yield this.parseTextTracks(e,this.params.sourceUrl);this.currentTextTrackData&&t&&(this.currentTextTrackData.playlist.segments=t.playlist.segments)}catch(e){this.error("fetchNextManifestData",e)}finally{this.abortControllers.nextManifest=null}})}fetchManifestData(){return E(this,null,function*(){var t;let e=(t=this.prepareUrl)!=null?t:this.params.sourceUrl;return yield this.params.fetchManifestData(e,{signal:this.abortControllers.destroy.signal})})}error(e,t){this.error$.next({id:"[LiveTextManager][HLS_LIVE_CMAF]",category:kC.WTF,thrown:t,message:e})}};var Ga=class{constructor(e){this.subscription=new VC;this.videoState=new _("stopped");this.textTracksManager=null;this.liveTextManager=null;this.manifests$=new vc([]);this.liveOffset=new hi;this.manifestStartTime$=new vc(void 0);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),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((r==null?void 0:r.to)!=="paused"&&l.state==="requested"){this.videoState.startTransitionTo("ready"),this.seek(l.position&&l.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(t){case"ready":i==="ready"?A(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),A(this.params.desiredState.playbackState,"paused")):i==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":i==="paused"?(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(r==null?void 0:r.to)==="playing"&&A(this.params.desiredState.playbackState,"playing");return;case"paused":if(i==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let c=this.liveOffset.getTotalOffset();c>=this.maxSeekBackTime$.getValue()&&(c=0,this.liveOffset.resetTo(c)),this.liveOffset.resume(),this.params.output.position$.next(-c/1e3),this.prepare()}else(r==null?void 0:r.to)==="paused"&&(A(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return AC(t)}};var i;this.params=e,this.video=ke(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:OC.INVARIANT,url:this.params.source.url};let t=(r,s)=>Nn(r,this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},s);this.params.tuning.useHlsLiveNewTextManager?this.liveTextManager=new Fn(this.params.output.liveTime$,this.video,t,this.params.source.url,this.params.tuning.hlsLiveNewTextManagerDownloadThreshold):this.textTracksManager=new He(e.source.url),t(this.generateLiveUrl()).then(({qualityManifests:r,textTracks:s})=>{var n;r.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:qn.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),(n=this.liveTextManager)==null||n.processTextTracks(s,this.params.source.url),this.manifests$.next([this.masterManifest,...r])}).catch(r=>{this.params.output.error$.next({id:"ExtractHlsQualities",category:qn.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:r})}),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(de(this.params.source.url)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.maxSeekBackTime$=new vc((i=e.source.maxSeekBackTime)!=null?i:1/0),this.subscribe()}selectManifest(){var u,l,c,d;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),r=t.getTransition(),s=(d=(c=(u=r==null?void 0:r.to)==null?void 0:u.id)!=null?c:(l=t.getState())==null?void 0:l.id)!=null?d:"master",n=this.manifests$.getValue();if(!n.length)return;let o=i?"master":s;return i&&!r&&t.startTransitionTo(this.masterManifest),n.find(h=>h.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsLiveProvider",category:qn.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},r=Le(this.video);this.subscription.add(()=>r.destroy());let s=(o,u)=>this.subscription.add(o.subscribe(u,i));s(r.ended$,e.endedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentBuffer$),s(r.loadedMetadata$,e.firstBytesEvent$),s(r.loadedMetadata$,e.loadedMetadataEvent$),s(r.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(Re(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Ue(this.video,t.playbackRate,r.playbackRateState$,i)),s(je(this.video),e.elementVisible$),this.liveTextManager?(s(this.liveTextManager.getCurrentTime$,this.params.output.getCurrentTime$),s(this.liveTextManager.error$,this.params.output.error$)):this.textTracksManager&&this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),A(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),A(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())==null?void 0:o.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.liveTextManager&&this.subscription.add(this.liveTextManager.availableTextTracks$.subscribe(o=>{o&&this.params.output.availableTextTracks$.next(o)})),this.subscription.add(this.maxSeekBackTime$.pipe(MC(),uT(o=>-o/1e3)).subscribe(this.params.output.duration$,i)),this.subscription.add(r.loadedMetadata$.subscribe(()=>{let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&oT(l.to)){let d=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let h=this.manifests$.getValue().find(p=>p.id===d);h&&(this.params.output.currentVideoTrack$.next(h),this.params.output.hostname$.next(de(h.url)))}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o&&o.state==="requested"&&this.seek(o.position)},i)),this.subscription.add(r.loadedData$.subscribe(()=>{var u,l,c;let o=(c=(l=(u=this.video)==null?void 0:u.getStartDate)==null?void 0:l.call(u))==null?void 0:c.getTime();this.manifestStartTime$.next(o||void 0)},i)),this.subscription.add(RC({startTime:this.manifestStartTime$.pipe(LC(oT)),currentTime:r.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),i)),this.subscription.add(this.manifests$.pipe(uT(o=>o.map(({id:u,quality:l,size:c,bandwidth:d,fps:h})=>({id:u,quality:l,size:c,fps:h,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,i));let n=DC(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,CC(["init"])).pipe($C(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){var e,t;this.subscription.unsubscribe(),(e=this.textTracksManager)==null||e.destroy(),(t=this.liveTextManager)==null||t.destroy(),this.params.output.element$.next(void 0),Ae(this.video)}prepare(){var o,u,l;let e=this.selectManifest();if(Un(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),r=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){let{max:c,min:d}=(u=(o=t==null?void 0:t.to)!=null?o:i)!=null?u:{};for(let[h,p]of[[c,"mq"],[d,"lq"]]){let m=String(parseFloat(h||""));p&&h&&r.searchParams.set(p,m)}}let s=this.params.format==="HLS_LIVE_CMAF"?2:0,n=ge(r.toString(),this.liveOffset.getTotalOffset(),s);(l=this.liveTextManager)==null||l.prepare(n),this.video.setAttribute("src",n),this.video.load(),fc(n).then(c=>{var d;if(!Un(c))this.maxSeekBackTime$.next(c);else{let h=(d=this.params.source.maxSeekBackTime)!=null?d:this.maxSeekBackTime$.getValue();(Un(h)||!isFinite(h))&&lt(n).then(p=>p.text()).then(p=>{var b;let m=(b=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(p))==null?void 0:b[1];if(m){let g=new URL(m,n).toString();fc(g).then(v=>{Un(v)||this.maxSeekBackTime$.next(v)})}}).catch(()=>{})}})}playIfAllowed(){Me(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),A(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:qn.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,i=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(i),this.params.output.position$.next(-i/1e3),this.params.output.seekedEvent$.next()}generateLiveUrl(){let e=ge(this.params.source.url);if(this.params.tuning.useHlsLiveNewTextManager){let t=new URL(e);t.searchParams.set("enable-subtitles","yes"),e=t.toString()}return e}};import{assertNever as _C,debounce as BC,ErrorCategory as Sc,fromEvent as yc,isNonNullable as NC,isNullable as FC,map as lT,merge as cT,observableFrom as dT,Subscription as qC,ValueSubject as UC,VideoQuality as HC}from"@vkontakte/videoplayer-shared/es2015";var Wa=class{constructor(e){this.subscription=new qC;this.videoState=new _("stopped");this.manifests$=new UC([]);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),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((r==null?void 0:r.to)!=="paused"&&l.state==="requested"&&this.seek(l.position),t){case"ready":i==="ready"?A(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),A(this.params.desiredState.playbackState,"paused")):i==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":i==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(r==null?void 0:r.to)==="playing"&&A(this.params.desiredState.playbackState,"playing");return;case"paused":i==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&A(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return _C(t)}};this.textTracksManager=new He(e.source.url),this.params=e,this.video=ke(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:HC.INVARIANT,url:this.params.source.url},this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(de(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),Nn(ge(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:t,textTracks:i})=>{this.manifests$.next([this.masterManifest,...t]),this.params.tuning.useNativeHLSTextTracks||this.params.desiredState.internalTextTracks.startTransitionTo(i)},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:Sc.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){var u,l,c,d;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),r=t.getTransition(),s=(d=(c=(u=r==null?void 0:r.to)==null?void 0:u.id)!=null?c:(l=t.getState())==null?void 0:l.id)!=null?d:"master",n=this.manifests$.getValue();if(!n.length)return;let o=i?"master":s;return i&&(!r||!r.from)&&t.startTransitionTo(this.masterManifest),n.find(h=>h.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsProvider",category:Sc.WTF,message:"HlsProvider internal logic error",thrown:o})},r=Le(this.video);this.subscription.add(()=>r.destroy());let s=(o,u)=>this.subscription.add(o.subscribe(u));if(s(r.timeUpdate$,e.position$),s(r.durationChange$,e.duration$),s(r.ended$,e.endedEvent$),s(r.looped$,e.loopedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentBuffer$),s(r.loadedMetadata$,e.firstBytesEvent$),s(r.loadedMetadata$,e.loadedMetadataEvent$),s(r.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.seeked$,e.seekedEvent$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe(lT(o=>o.to)),this.params.output.playbackState$),this.subscription.add(ot(this.video,t.isLooped,i)),this.subscription.add(Re(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Ue(this.video,t.playbackRate,r.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),A(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),A(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())==null?void 0:o.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i).add(r.loadedMetadata$.subscribe(()=>{var p;let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&NC(l.to)){let m=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let b=this.manifests$.getValue().find(g=>g.id===m);b&&(this.params.output.currentVideoTrack$.next(b),this.params.output.hostname$.next(de(b.url)))}let d=this.params.desiredState.playbackRate.getState(),h=(p=this.params.output.element$.getValue())==null?void 0:p.playbackRate;if(d!==h){let m=this.params.output.element$.getValue();m&&(this.params.desiredState.playbackRate.setState(d),m.playbackRate=d)}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o.state==="requested"&&this.seek(o.position)},i))),this.subscription.add(this.manifests$.pipe(lT(o=>o.map(({id:u,quality:l,size:c,bandwidth:d,fps:h})=>({id:u,quality:l,size:c,fps:h,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,i)),!U.device.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add(cT(yc(o,"addtrack"),yc(o,"removetrack"),yc(o,"change"),dT(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},i))}let n=cT(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,dT(["init"])).pipe(BC(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}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(FC(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),r=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){let{max:o,min:u}=(n=(s=t==null?void 0:t.to)!=null?s:i)!=null?n:{};for(let[l,c]of[[o,"mq"],[u,"lq"]]){let d=String(parseFloat(l||""));c&&l&&r.searchParams.set(c,d)}}this.video.setAttribute("src",r.toString()),this.video.load()}playIfAllowed(){Me(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),A(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Sc.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};var mT=O(Bi(),1),Tc=O(zi(),1),fT=O(Nt(),1);import{assertNever as jC,assertNonNullable as pT,debounce as QC,ErrorCategory as hT,isHigherOrEqual as GC,isLowerOrEqual as WC,isNonNullable as YC,merge as zC,observableFrom as KC,Subscription as XC,map as JC}from"@vkontakte/videoplayer-shared/es2015";var Ya=class{constructor(e){this.subscription=new XC;this.videoState=new _("stopped");this.trackUrls={};this.textTracksManager=new He;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),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((i==null?void 0:i.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()):(i==null?void 0:i.to)==="playing"&&A(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&A(this.params.desiredState.playbackState,"paused");return;default:return jC(e)}};this.params=e,this.video=ke(e.container,e.tuning),this.params.output.element$.next(this.video),(0,mT.default)(this.params.source).reverse().forEach(([t,i],r)=>{let s=r.toString(10);this.trackUrls[s]={track:{quality:t,id:s},url:i}}),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next((0,Tc.default)(this.trackUrls).map(({track:t})=>t)),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.desiredState.autoVideoTrackSwitching.setState(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.subscribe()}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"MpegProvider",category:hT.WTF,message:"MpegProvider internal logic error",thrown:o})},r=Le(this.video);this.subscription.add(()=>r.destroy());let s=(o,u)=>this.subscription.add(o.subscribe(u,i));s(r.timeUpdate$,e.position$),s(r.durationChange$,e.duration$),s(r.ended$,e.endedEvent$),s(r.looped$,e.loopedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentBuffer$),s(r.loadedMetadata$,e.firstBytesEvent$),s(r.loadedMetadata$,e.loadedMetadataEvent$),s(r.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.seeked$,e.seekedEvent$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe(JC(o=>o.to)),this.params.output.playbackState$),this.subscription.add(ot(this.video,t.isLooped,i)),this.subscription.add(Re(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Ue(this.video,t.playbackRate,r.playbackRateState$,i)),s(je(this.video),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),A(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),A(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{var u,l;((u=this.videoState.getTransition())==null?void 0:u.to)==="ready"&&this.videoState.setState("ready");let o=this.params.desiredState.videoTrack.getTransition();if(o&&YC(o.to)){this.params.desiredState.videoTrack.setState(o.to),this.params.output.currentVideoTrack$.next(this.trackUrls[o.to.id].track);let c=this.params.desiredState.playbackRate.getState(),d=(l=this.params.output.element$.getValue())==null?void 0:l.playbackRate;if(c!==d){let h=this.params.output.element$.getValue();h&&(this.params.desiredState.playbackRate.setState(c),h.playbackRate=c)}}this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.textTracksManager.connect(this.video,t,e);let n=zC(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,KC(["init"])).pipe(QC(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.params.output.element$.next(void 0),Ae(this.video)}prepare(){var i;let e=(i=this.params.desiredState.videoTrack.getState())==null?void 0:i.id;pT(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];pT(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=Da(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(de(t))}playIfAllowed(){Me(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),A(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:hT.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){var l,c;this.params.output.autoVideoTrackLimits$.next(e);let t=d=>{this.params.output.currentVideoTrack$.next(d),this.params.desiredState.videoTrack.startTransitionTo(d)},i=d=>{let h=qt(n,{container:this.video.getBoundingClientRect(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:0,limits:d,abrLogger:this.params.dependencies.abrLogger});t(h)},r=(l=this.params.output.currentVideoTrack$.getValue())==null?void 0:l.quality,s=!!(e.max||e.min),n=(0,Tc.default)(this.trackUrls).map(d=>d.track);if(!r||!s||Gr({limits:e,lowestAvailableQuality:(c=(0,fT.default)(n,-1))==null?void 0:c.quality,highestAvailableQuality:n[0].quality})){i();return}let o=e.max?WC(r,e.max):!0,u=e.min?GC(r,e.min):!0;o&&u||i(e)}};import{assertNever as gT,debounce as i0,merge as vT,observableFrom as r0,Subscription as a0,map as ST,ValueSubject as s0,ErrorCategory as Ec,VideoQuality as n0}from"@vkontakte/videoplayer-shared/es2015";import{ErrorCategory as ZC}from"@vkontakte/videoplayer-shared/es2015";var bT=["stun:videostun.mycdn.me:80"],e0=1e3,t0=3,Ic=()=>null,Hn=class{constructor(e,t){this.ws=null;this.peerConnection=null;this.serverUrl="";this.streamKey="";this.stream=null;this.signalingType="JOIN";this.retryCount=0;this.externalStartCallback=Ic;this.externalStopCallback=Ic;this.externalErrorCallback=Ic;this.options=this.normalizeOptions(t);let i=e.split("/");this.serverUrl=i.slice(0,i.length-1).join("/"),this.streamKey=i[i.length-1]}onStart(e){try{this.externalStartCallback=e}catch(t){this.handleSystemError(t)}}onStop(e){try{this.externalStopCallback=e}catch(t){this.handleSystemError(t)}}onError(e){try{this.externalErrorCallback=e}catch(t){this.handleSystemError(t)}}connect(){this.connectWS()}disconnect(){try{this.externalStopCallback(),this.closeConnections()}catch(e){this.handleSystemError(e)}}connectWS(){this.ws||(this.ws=new WebSocket(this.serverUrl),this.ws.onopen=this.onSocketOpen.bind(this),this.ws.onmessage=this.onSocketMessage.bind(this),this.ws.onclose=this.onSocketClose.bind(this),this.ws.onerror=this.onSocketError.bind(this))}onSocketOpen(){this.handleLogin()}onSocketClose(e){try{if(!this.ws)return;this.ws=null,e.code>1e3?(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():this.scheduleRetry()):this.externalStopCallback()}catch(t){this.handleRTCError(t)}}onSocketError(e){try{this.externalErrorCallback(new Error(e.toString()))}catch(t){this.handleRTCError(t)}}onSocketMessage(e){try{let t=this.parseMessage(e.data);switch(t.type){case"JOIN":case"CALL_JOIN":this.handleJoinMessage(t);break;case"UPDATE":this.handleUpdateMessage(t);break;case"STATUS":this.handleStatusMessage(t);break}}catch(t){this.handleRTCError(t)}}handleJoinMessage(e){switch(e.inviteType){case"ANSWER":this.handleAnswer(e.sdp);break;case"CANDIDATE":this.handleCandidate(e.candidate);break}}handleStatusMessage(e){switch(e.status){case"UNPUBLISHED":this.handleUnpublished();break}}handleUpdateMessage(e){return E(this,null,function*(){try{let t=yield this.createOffer();this.peerConnection&&(yield this.peerConnection.setLocalDescription(t)),this.handleAnswer(e.sdp)}catch(t){this.handleRTCError(t)}})}handleLogin(){return E(this,null,function*(){try{let e={iceServers:[{urls:bT}]};this.peerConnection=new RTCPeerConnection(e),this.peerConnection.ontrack=this.onPeerConnectionStream.bind(this),this.peerConnection.onicecandidate=this.onPeerConnectionIceCandidate.bind(this),this.peerConnection.oniceconnectionstatechange=this.onPeerConnectionIceConnectionStateChange.bind(this);let t=yield this.createOffer();yield this.peerConnection.setLocalDescription(t),this.send({type:this.signalingType,inviteType:"OFFER",streamKey:this.streamKey,sdp:t.sdp,callSupport:!1})}catch(e){this.handleRTCError(e)}})}handleAnswer(e){return E(this,null,function*(){try{this.peerConnection&&(yield this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e})))}catch(t){this.handleRTCError(t)}})}handleCandidate(e){return E(this,null,function*(){if(e)try{this.peerConnection&&(yield this.peerConnection.addIceCandidate(e))}catch(t){this.handleRTCError(t)}})}handleUnpublished(){try{this.closeConnections(),this.externalStopCallback()}catch(e){this.handleRTCError(e)}}handleSystemError(e){this.options.errorChanel&&this.options.errorChanel.next({id:"webrtc-provider-error",category:ZC.WTF,message:e.message})}onPeerConnectionStream(e){return E(this,null,function*(){let t=e.streams[0];this.stream&&this.stream.id===t.id||(this.stream=t,this.externalStartCallback(this.stream))})}onPeerConnectionIceCandidate(e){e.candidate&&this.send({type:this.signalingType,inviteType:"CANDIDATE",candidate:e.candidate})}onPeerConnectionIceConnectionStateChange(){if(this.peerConnection){let e=this.peerConnection.iceConnectionState;["failed","closed"].indexOf(e)>-1&&(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():(this.closeConnections(),this.scheduleRetry()))}}createOffer(){return E(this,null,function*(){let e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");let t=yield this.peerConnection.createOffer(e),i=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(i))throw new Error("No h264 codec support error");return t})}handleRTCError(e){try{this.externalErrorCallback(e||new Error("RTC connection error"))}catch(t){this.handleSystemError(t)}}handleNetworkError(){try{this.externalErrorCallback(new Error("Network error"))}catch(e){this.handleSystemError(e)}}send(e){this.ws&&this.ws.send(JSON.stringify(e))}parseMessage(e){try{return JSON.parse(e)}catch(t){throw new Error("Can not parse socket message")}}closeConnections(){let e=this.ws;e&&(this.ws=null,e.close(1e3)),this.removePeerConnection()}removePeerConnection(){let e=this.peerConnection;e&&(this.peerConnection=null,e.close(),e.ontrack=null,e.onicecandidate=null,e.oniceconnectionstatechange=null,e=null)}scheduleRetry(){this.retryTimeout=setTimeout(this.connectWS.bind(this),e0)}normalizeOptions(e={}){let t={stunServerList:bT,maxRetryNumber:t0,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var za=class{constructor(e){this.videoState=new _("stopped");this.maxSeekBackTime$=new s0(0);this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.pause(),this.video.srcObject=null,this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),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()):(i==null?void 0:i.to)==="playing"&&A(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&A(this.params.desiredState.playbackState,"paused");return;default:return gT(e)}};this.subscription=new a0,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=ke(e.container,e.tuning),this.liveStreamClient=new Hn(this.params.source.url,{maxRetryNumber:this.params.tuning.webrtc.connectionRetryMaxNumber,errorChanel:this.params.output.error$}),this.liveStreamClient.onStart(this.onLiveStreamStart.bind(this)),this.liveStreamClient.onStop(this.onLiveStreamStop.bind(this)),this.liveStreamClient.onError(this.onLiveStreamError.bind(this)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.subscribe()}destroy(){this.subscription.unsubscribe(),this.liveStreamClient.disconnect(),this.params.output.element$.next(void 0),Ae(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,i=n=>{e.error$.next({id:"WebRTCLiveProvider",category:Ec.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};this.subscription.add(vT(this.videoState.stateChangeStarted$.pipe(ST(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe(ST(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})}));let r=Le(this.video);this.subscription.add(()=>r.destroy());let s=(n,o)=>this.subscription.add(n.subscribe(o,i));s(r.timeUpdate$,e.liveTime$),s(r.ended$,e.endedEvent$),s(r.looped$,e.loopedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentBuffer$),s(je(this.video),this.params.output.elementVisible$),this.subscription.add(r.durationChange$.subscribe(n=>{e.duration$.next(n===1/0?0:n)})).add(r.canplay$.subscribe(()=>{var n;((n=this.videoState.getTransition())==null?void 0:n.to)==="ready"&&this.videoState.setState("ready")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused")},i)).add(r.playing$.subscribe(()=>{this.videoState.setState("playing")},i)).add(r.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(Re(this.video,t.volume,r.volumeState$,i)).add(r.volumeState$.subscribe(e.volume$,i)).add(this.videoState.stateChangeEnded$.subscribe(n=>{switch(n.to){case"stopped":e.position$.next(0),e.duration$.next(0),t.playbackState.setState("stopped");break;case"ready":break;case"paused":t.playbackState.setState("paused");break;case"playing":t.playbackState.setState("playing");break;default:return gT(n.to)}},i)).add(vT(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,r0(["init"])).pipe(i0(0)).subscribe(this.syncPlayback.bind(this),i)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),i))}onLiveStreamStart(e){this.params.output.element$.next(this.video),this.params.output.duration$.next(0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(de(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.currentVideoTrack$.next({id:"webrtc",quality:n0.INVARIANT}),this.video.srcObject=e,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:Ec.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){Me(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:Ec.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var Ka=class{constructor(e){this.iterator=e[Symbol.iterator](),this.next()}next(){this.current=this.iterator.next()}getValue(){if(this.current.done)throw new Error("Iterable is completed");return this.current.value}isCompleted(){return!!this.current.done}};import{assertNever as Ja,assertNonNullable as Gt,ErrorCategory as jn,filter as PT,isNonNullable as wT,isNullable as h0,map as m0,merge as f0,once as b0,Subject as he,Subscription as kT,ValueSubject as B,flattenObject as AT}from"@vkontakte/videoplayer-shared/es2015";import{Observable as o0,map as yT,Subscription as u0,Subject as l0}from"@vkontakte/videoplayer-shared/es2015";var TT=a=>new o0(e=>{let t=new u0,i=a.desiredPlaybackState$.stateChangeStarted$.pipe(yT(({from:l,to:c})=>`${l}-${c}`)),r=a.desiredPlaybackState$.stateChangeEnded$,s=a.providerChanged$.pipe(yT(({type:l})=>l!==void 0)),n=new l0,o=0,u="unknown";return t.add(i.subscribe(l=>{o&&window.clearTimeout(o),u=l,o=window.setTimeout(()=>n.next(l),a.maxTransitionInterval)})),t.add(r.subscribe(()=>{window.clearTimeout(o),u="unknown",o=0})),t.add(s.subscribe(l=>{o&&(window.clearTimeout(o),o=0,l&&(o=window.setTimeout(()=>n.next(u),a.maxTransitionInterval)))})),t.add(n.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});import{ErrorCategory as c0,Subscription as d0,combine as p0,filter as ET,once as xT}from"@vkontakte/videoplayer-shared/es2015";function IT(){return new(window.AudioContext||window.webkitAudioContext)}var Xa=class Xa{constructor(e,t,i,r){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=i;this.volumeMultiplier=r;this.destroyController=new ve;this.subscriptions=new d0;this.audioContext=null;this.gainNode=null;this.mediaElementSource=null;this.subscriptions.add(this.provider$.pipe(ET(s=>!!s.type),xT()).subscribe(({type:s})=>this.subscribe(s)))}subscribe(e){U.browser.isSafari&&e!=="MPEG"||this.subscriptions.add(p0({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe(ET(({playbackState:t,video:i,volume:{muted:r,volume:s}})=>t==="playing"&&!!i&&!r&&!!s),xT()).subscribe(({video:t})=>{this.initAudioContextOnce(t).then(i=>{i||this.destroy()}).catch(i=>{this.handleError(i),this.destroy()})}))}static isSupported(){return"AudioContext"in window&&"GainNode"in window&&"MediaElementAudioSourceNode"in window}initAudioContextOnce(e){return E(this,null,function*(){let{volumeMultiplier:t}=this,i=IT();this.audioContext=i;let r=i.createGain();if(this.gainNode=r,r.gain.value=t,r.connect(i.destination),i.state==="suspended"&&(yield i.resume(),this.destroyController.signal.aborted))return!1;let s=i.createMediaElementSource(e);return this.mediaElementSource=s,s.connect(r),!0})}cleanup(){this.mediaElementSource&&(this.mediaElementSource.disconnect(),this.mediaElementSource=null),this.gainNode&&(this.gainNode.disconnect(),this.gainNode=null),this.audioContext&&(this.audioContext.state!=="closed"&&this.audioContext.close(),this.audioContext=null)}destroy(){this.destroyController.abort(),this.subscriptions.unsubscribe(),this.cleanup()}handleError(e){var t;this.volumeMultiplierError$.next({id:Xa.errorId,category:c0.VIDEO_PIPELINE,message:(t=e==null?void 0:e.message)!=null?t:`${Xa.errorId} exception`,thrown:e})}};Xa.errorId="VolumeMultiplierManager";var lr=Xa;var g0={chunkDuration:5e3,maxParallelRequests:5},Za=class{constructor(e){this.current$=new B({type:void 0});this.providerError$=new he;this.noAvailableProvidersError$=new he;this.volumeMultiplierError$=new he;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 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 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 he,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 kT;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=_y([...Ny(this.params.tuning),...By(this.params.tuning)],this.params.tuning).filter(l=>wT(e.sources[l])),{forceFormat:i,formatsToAvoid:r}=this.params.tuning,s=[];i?s=[i]:r.length?s=[...t.filter(l=>!(0,xc.default)(r,l)),...t.filter(l=>(0,xc.default)(r,l))]:s=t,this.log({message:`Selected formats: ${s.join(" > ")}`}),this.tracer.log("Selected formats",AT(s)),this.screenFormatsIterator=new Ka(s);let n=[...ec(!0),...ec(!1)];this.chromecastFormatsIterator=new Ka(n.filter(l=>wT(e.sources[l]))),this.providerOutput.availableSources$.next(e.sources);let{volumeMultiplier:o=1,tuning:{useVolumeMultiplier:u}}=this.params;u&&o!==1&&lr.isSupported()&&(this.volumeMultiplierManager=new lr(this.providerOutput,this.current$,this.volumeMultiplierError$,o))}init(){this.subscription.add(this.initProviderErrorHandling()),this.subscription.add(this.params.dependencies.chromecastInitializer.connection$.subscribe(()=>{this.reinitProvider()}))}destroy(){var e;this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe(),(e=this.volumeMultiplierManager)==null||e.destroy(),this.volumeMultiplierManager=null,this.tracer.end()}initProvider(){let e=this.chooseDestination(),t=this.chooseFormat(e);if(h0(t)){this.handleNoFormatsError(e);return}let i;try{i=this.createProvider(e,t)}catch(r){this.providerError$.next({id:"ProviderNotConstructed",category:jn.WTF,message:"Failed to create provider",thrown:r})}i?this.current$.next({type:t,provider:i,destination:e}):this.current$.next({type:void 0})}reinitProvider(){this.tracer.log("reinitProvider"),this.destroyProvider(),this.initProvider()}switchToNextProvider(e){this.tracer.log("switchToNextProvider",{destination:e}),this.destroyProvider(),this.failoverIndex=void 0,this.skipFormat(e),this.initProvider()}destroyProvider(){let e=this.current$.getValue().provider;if(!e)return;this.log({message:"destroyProvider"}),this.tracer.log("destroyProvider");let t=this.providerOutput.position$.getValue()*1e3,i=this.params.desiredState.seekState.getState(),r=i.state!=="none";if(this.params.desiredState.seekState.setState({state:"requested",position:r?i.position:t,forcePrecise:r?i.forcePrecise:!1}),e.scene3D){let n=e.scene3D.getCameraRotation();this.params.desiredState.cameraOrientation.setState({x:n.x,y:n.y})}e.destroy();let s=this.providerOutput.isBuffering$;s.getValue()||s.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),this.tracer.log("createProvider",{destination:e,format:t}),e){case"SCREEN":return this.createScreenProvider(t);case"CHROMECAST":return this.createChromecastProvider(t);default:return Ja(e)}}createScreenProvider(e){let{sources:t,container:i,desiredState:r,panelSize:s}=this.params,n=this.providerOutput,o={container:i,source:null,desiredState:r,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning,panelSize:s};switch(e){case"DASH_SEP":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_ONDEMAND":case"DASH_STREAMS":{let u=this.applyFailoverHost(t[e]),l=this.applyFailoverHost(t.HLS_ONDEMAND||t.HLS);return Gt(u),new Ua(D(w({},o),{source:u,sourceHls:l}))}case"DASH_LIVE_CMAF":{let u=this.applyFailoverHost(t[e]);return Gt(u),new Ha(D(w({},o),{source:u}))}case"HLS":case"HLS_ONDEMAND":{let u=this.applyFailoverHost(t[e]);return Gt(u),U.video.nativeHlsSupported||!this.params.tuning.useHlsJs?new Wa(D(w({},o),{source:u})):new Qa(D(w({},o),{source:u}))}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let u=this.applyFailoverHost(t[e]);return Gt(u),new Ga(D(w({},o),{source:u,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e}))}case"MPEG":{let u=this.applyFailoverHost(t[e]);return Gt(u),new Ya(D(w({},o),{source:u}))}case"DASH_LIVE":{let u=this.applyFailoverHost(t[e]);return Gt(u),new $v(D(w({},o),{source:u,config:D(w({},g0),{maxPausedTime:this.params.tuning.live.maxPausedTime})}))}case"WEB_RTC_LIVE":{let u=this.applyFailoverHost(t[e]);return Gt(u),new za({container:i,source:u,desiredState:r,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return Ja(e)}}createChromecastProvider(e){let{sources:t,container:i,desiredState:r,meta:s}=this.params,n=this.providerOutput,o=this.params.dependencies.chromecastInitializer.connection$.getValue();return Gt(o),new Fr({connection:o,meta:s,container:i,source:t,format:e,desiredState:r,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?"CHROMECAST":"SCREEN"}chooseFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case"CHROMECAST":return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return Ja(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return Ja(e)}}handleNoFormatsError(e){switch(e){case"SCREEN":this.noAvailableProvidersError$.next(this.params.tuning.forceFormat),this.current$.next({type:void 0});return;case"CHROMECAST":this.params.dependencies.chromecastInitializer.disconnect();return;default:return Ja(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;let t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;let i=r=>{let s=new URL(r);return s.host=t,s.toString()};if(e===void 0)return e;if("type"in e){if(e.type==="raw")return e;if(e.type==="url")return D(w({},e),{url:i(e.url)})}return(0,$T.default)((0,RT.default)(e).map(([r,s])=>[r,i(s)]))}initProviderErrorHandling(){let e=new kT,t=!1,i=0;return e.add(f0(this.providerOutput.error$.pipe(PT(r=>!this.params.tuning.ignoreAudioRendererError||!r.message||!/AUDIO_RENDERER_ERROR/ig.test(r.message))),TT({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(m0(r=>({id:`ProviderHangup:${r}`,category:jn.WTF,message:`A ${r} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.providerOutput.fetcherError$.subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;let r=this.params.desiredState.playbackState.transitionEnded$.pipe(PT(({to:s})=>s==="playing"),b0()).subscribe(()=>t=!0);e.add(r)})),e.add(this.providerError$.subscribe(r=>{let s=this.current$.getValue().destination,n={error:r,currentDestination:s};if(s==="CHROMECAST")this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider("SCREEN"),()=>this.params.dependencies.chromecastInitializer.disconnect());else{let o=r.category===jn.NETWORK,u=r.category===jn.FATAL,l=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),c=i<this.params.tuning.providerErrorLimit&&!u,d=l&&!u&&(o&&t||!c);n=D(w({},n),{isNetworkError:o,isFatalError:u,haveFailoverHost:l,tryFailover:d,canReinitProvider:c}),c?(i++,this.reinitProvider()):d?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):(i=0,this.switchToNextProvider(s!=null?s:"SCREEN"))}this.tracer.error("providerError",AT(n))})),e}};import{fromEvent as Qn,once as v0,combine as S0,Subscription as LT,ValueSubject as Pc,map as y0,filter as T0,isNonNullable as Gn,now as Ne,safeStorage as wc}from"@vkontakte/videoplayer-shared/es2015";var I0=5e3,MT="one_video_throughput",DT="one_video_rtt",Et=window.navigator.connection,CT=()=>{let a=Et==null?void 0:Et.downlink;if(Gn(a)&&a!==10)return a*1e3},VT=()=>{let a=Et==null?void 0:Et.rtt;if(Gn(a)&&a!==3e3)return a},OT=(a,e,t)=>{let i=t*8,r=i/a;return i/(r+e)},kc=class a{constructor(e){this.subscription=new LT;this.concurrentDownloads=new Set;var r,s;this.tuningConfig=e;let t=a.load(MT)||(e.useBrowserEstimation?CT():void 0)||I0,i=(s=(r=a.load(DT))!=null?r:e.useBrowserEstimation?VT():void 0)!=null?s:0;if(this.throughput$=new Pc(t),this.rtt$=new Pc(i),this.rttAdjustedThroughput$=new Pc(OT(t,i,e.rttPenaltyRequestSize)),this.throughput=vi.getSmoothedValue(t,-1,e),this.rtt=vi.getSmoothedValue(i,1,e),e.useBrowserEstimation){let n=()=>{let u=CT();u&&this.throughput.next(u);let l=VT();Gn(l)&&this.rtt.next(l)};Et&&"onchange"in Et&&this.subscription.add(Qn(Et,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{wc.set(MT,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{wc.set(DT,n.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(S0({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(y0(({throughput:n,rtt:o})=>OT(n,o,e.rttPenaltyRequestSize)),T0(n=>{let o=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(n-o)/o>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,i=Ne(),r=new LT;switch(this.subscription.add(r),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:r.add(Qn(e,"progress").pipe(v0()).subscribe(s=>{t=s.loaded,i=Ne()}));break;case 1:case 0:r.add(Qn(e,"loadstart").subscribe(()=>{t=0,i=Ne()}));break}r.add(Qn(e,"loadend").subscribe(s=>{if(e.status===200){let n=s.loaded,o=Ne(),u=n-t,l=o-i;this.addRawSpeed(u,l,1)}this.concurrentDownloads.delete(e),r.unsubscribe()}))}trackStream(e,t=!1){let i=e.getReader();if(!i){e.cancel("Could not get reader");return}let r=0,s=Ne(),n=0,o=Ne(),u=c=>{this.concurrentDownloads.delete(e),i.releaseLock(),e.cancel(`Throughput Estimator error: ${c}`).catch(()=>{})},l=h=>E(this,[h],function*({done:c,value:d}){if(c)!t&&this.addRawSpeed(r,Ne()-s,1),this.concurrentDownloads.delete(e);else if(d){if(t){let p=Ne();if(p-o>this.tuningConfig.lowLatency.continuesByteSequenceInterval||p-s>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let b=o-s;b&&this.addRawSpeed(n,b,1,t),n=d.byteLength,s=Ne()}else n+=d.byteLength;o=Ne()}else r+=d.byteLength,n+=d.byteLength,n>=this.tuningConfig.streamMinSampleSize&&Ne()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,Ne()-o,this.concurrentDownloads.size),n=0,o=Ne());yield i==null?void 0:i.read().then(l,u)}});this.concurrentDownloads.add(e),i==null||i.read().then(l,u)}addRawSpeed(e,t,i=1,r=!1){if(a.sanityCheck(e,t,r)){let s=e*8/t;this.throughput.next(s*i)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,i=!1){let r=e*8/t;return!(!r||!isFinite(r)||r>1e6||r<30||i&&e<1e4||!i&&e<10*1024||!i&&t<=20)}static load(e){var i;let t=wc.get(e);if(Gn(t))return(i=parseInt(t,10))!=null?i:void 0}},_T=kc;import{fillWithDefault as E0,VideoQuality as Wn}from"@vkontakte/videoplayer-shared/es2015";var BT={configName:["core"],throughputEstimator:{type:"EmaAndMa",emaAlphaSlow:.2,emaAlphaFast:.7,emaAlpha:.45,basisTrendChangeCount:10,changeThreshold:.05,useBrowserEstimation:!0,rttPenaltyRequestSize:1*1024*1024,streamMinSampleSize:10*1024,streamMinSampleTime:300,deviationDepth:20,deviationFactor:.5,lowLatency:{continuesByteSequenceInterval:50,maxLastEvaluationTimeout:300}},autoTrackSelection:{bitrateFactorAtEmptyBuffer:2.8,bitrateAudioFactorAtEmptyBuffer:10,bitrateFactorAtFullBuffer:2,bitrateAudioFactorAtFullBuffer:7,minVideoAudioRatio:5,minAvailableThroughputAudioRatio:5,usePixelRatio:!0,pixelRatioMultiplier:void 0,pixelRatioLogBase:3,pixelRatioLogCoefficients:[1,0,1],limitByContainer:!0,containerSizeFactor:1.3,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldownIncreaseQuality:15e3,trackCooldownDecreaseQuality:3e3,backgroundVideoQualityLimit:Wn.Q_4320P,activeVideoAreaThreshold:.1,highQualityLimit:Wn.Q_720P,trafficSavingLimit:Wn.Q_480P},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:Wn.Q_480P},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,seekBiasInTheEnd:2e3,maxSegmentDurationLeftToSelectNextSegment:3e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:3e3,crashOnStallTimeout:25e3,crashOnStallTWithoutDataTimeout:5e3,enableSubSegmentBufferFeeding:!0,bufferEmptinessTolerance:100,useFetchPriorityHints:!0,qualityLimitsOnStall:{stallDurationNoDataBeforeQualityDecrease:500,stallDurationToBeCount:100,stallCountBeforeQualityDecrease:3,resetQualityRestrictionTimeout:1e4,ignoreStallsOnSeek:!1},enableBaseUrlSupport:!0,maxSegmentRetryCount:5,sourceOpenTimeout:1e3,rejectOnSourceOpenTimeout:!1},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,maxLiveDuration:7200,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:250,playbackCatchupSpeedup:.05,isActiveOnDefault:!1,bufferEstimator:{emaAlpha:.45,changeThreshold:.05,deviationDepth:20,deviationFactor:.5,extremumInterval:5}}},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1,lowLatencyActiveLiveDelay:3e3,activeLiveDelay:5e3,maxPausedTime:5e3},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,forceFormat:void 0,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:"07A4434E",useWebmBigRequest:!1,webmCodec:"vp9",androidPreferredFormat:"dash",preferCMAF:!1,preferWebRTC:!1,preferMultiStream:!1,preferHDR:!1,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,seekNearDurationBias:1,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useHlsJs:!1,useNativeHLSTextTracks:!1,useManagedMediaSource:!0,useNewSwitchTo:!1,useSafariEndlessRequestBugfix:!0,useRefactoredSearchGap:!1,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,manifestRetryInterval:300,manifestRetryMaxInterval:1e4,manifestRetryMaxCount:10,audioVideoSyncRate:20,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50},useVolumeMultiplier:!1,ignoreAudioRendererError:!1,useEnableSubtitlesParam:!1,useOldMSEDetection:!1,useHlsLiveNewTextManager:!1,exposeInternalsToGlobal:!1,hlsLiveNewTextManagerDownloadThreshold:4e3,disableYandexPiP:!1,asyncResolveClientChecker:!1,autostartOnlyIfVisible:!1},NT=a=>{var e;return D(w({},E0(a,BT)),{configName:[...(e=a.configName)!=null?e:[],...BT.configName]})};import{assertNonNullable as Yn,combine as xt,ErrorCategory as zn,filter as V,filterChanged as z,fromEvent as Rc,isNonNullable as HT,isNullable as $0,Logger as L0,map as W,mapTo as jT,merge as Wt,now as Kn,once as H,Subject as J,Subscription as QT,tap as $c,ValueSubject as k,isHigher as M0,isInvariantQuality as GT,flattenObject as Yt,throttle as Lc,getTraceSubscriptionMethod as WT,Tracer as D0,InternalsExposure as C0}from"@vkontakte/videoplayer-shared/es2015";import{merge as x0,map as P0,filter as FT,isNonNullable as w0}from"@vkontakte/videoplayer-shared/es2015";var Ac=({seekState:a,position$:e})=>x0(a.stateChangeEnded$.pipe(P0(({to:t})=>{var i;return t.state==="none"?void 0:((i=t.position)!=null?i:NaN)/1e3}),FT(w0)),e.pipe(FT(()=>a.getState().state==="none")));import{assertNonNullable as k0}from"@vkontakte/videoplayer-shared/es2015";var qT=a=>{let e=typeof a.container=="string"?document.getElementById(a.container):a.container;return k0(e,`Wrong container or containerId {${a.container}}`),e};import{filter as A0,once as R0}from"@vkontakte/videoplayer-shared/es2015";var UT=(a,e,t,i)=>{a!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&(t==null?void 0:t.getValue().length)===0?t.pipe(A0(r=>r.length>0),R0()).subscribe(r=>{r.find(i)&&e.startTransitionTo(a)}):(a===void 0||t!=null&&t.getValue().find(i))&&e.startTransitionTo(a)};var Xn=class{constructor(e={configName:[]},t=D0.createRootTracer(!1)){this.subscription=new QT;this.logger=new L0;this.abrLogger=this.logger.createComponentLog("ABR");this.internalsExposure=null;this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new k(!1);this.hasLiveOffsetByPausedTimer=0;this.playerInitRequest=0;this.playerInited=new k(!1);this.wasSetStartedQuality=!1;this.desiredState={playbackState:new _("stopped"),seekState:new _({state:"none"}),volume:new _({volume:1,muted:!1}),videoTrack:new _(void 0),videoStream:new _(void 0),audioStream:new _(void 0),autoVideoTrackSwitching:new _(!0),autoVideoTrackLimits:new _({}),isLooped:new _(!1),isLowLatency:new _(!1),playbackRate:new _(1),externalTextTracks:new _([]),internalTextTracks:new _([]),currentTextTrack:new _(void 0),textTrackCuesSettings:new _({}),cameraOrientation:new _({x:0,y:0})};this.info={playbackState$:new k(void 0),position$:new k(0),duration$:new k(1/0),muted$:new k(!1),volume$:new k(1),availableVideoStreams$:new k([]),currentVideoStream$:new k(void 0),availableQualities$:new k([]),availableQualitiesFps$:new k({}),currentQuality$:new k(void 0),isAutoQualityEnabled$:new k(!0),autoQualityLimitingAvailable$:new k(!1),autoQualityLimits$:new k({}),predefinedQualityLimitType$:new k("unknown"),availableAudioStreams$:new k([]),currentAudioStream$:new k(void 0),availableAudioTracks$:new k([]),isAudioAvailable$:new k(!0),currentPlaybackRate$:new k(1),currentBuffer$:new k({start:0,end:0}),isBuffering$:new k(!0),isStalled$:new k(!1),isEnded$:new k(!1),isLooped$:new k(!1),isLive$:new k(void 0),isLiveEnded$:new k(null),canChangePlaybackSpeed$:new k(void 0),atLiveEdge$:new k(void 0),atLiveDurationEdge$:new k(void 0),liveTime$:new k(void 0),liveBufferTime$:new k(void 0),liveLatency$:new k(void 0),currentFormat$:new k(void 0),availableTextTracks$:new k([]),currentTextTrack$:new k(void 0),throughputEstimation$:new k(void 0),rttEstimation$:new k(void 0),videoBitrate$:new k(void 0),hostname$:new k(void 0),httpConnectionType$:new k(void 0),httpConnectionReused$:new k(void 0),surface$:new k("none"),chromecastState$:new k("NOT_AVAILABLE"),chromecastDeviceName$:new k(void 0),intrinsicVideoSize$:new k(void 0),availableSources$:new k(void 0),is3DVideo$:new k(!1),currentVideoSegmentLength$:new k(0),currentAudioSegmentLength$:new k(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 k(void 0),tuningConfigName$:new k([]),enableDebugTelemetry$:new k(!1),dumpTelemetry:ev,getCurrentTime$:new k(null)};if(this.initLogs(),this.tuning=NT(e),this.tracer=t,this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new Is({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new _T(this.tuning.throughputEstimator),e.exposeInternalsToGlobal&&(this.internalsExposure=new C0("CORE"),this.internalsExposure.expose({player:this})),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(i,r,s)=>{let n=Reflect.get(i,r,s);return typeof n!="function"?n:(...o)=>{try{return n.apply(i,o)}catch(u){let l=o.map(h=>JSON.stringify(h,(p,m)=>{let b=typeof m;return(0,YT.default)(["number","string","boolean"],b)?m:m===null?null:`<${b}>`})),c=`Player.${String(r)}`,d=`Exception calling ${c} (${l.join(", ")})`;throw this.events.fatalError$.next({id:c,category:zn.WTF,message:d,thrown:u}),u}}}})}initVideo(e){var s;this.config=e,(s=this.internalsExposure)==null||s.expose({config:e,logger:this.logger,tuning:this.tuning});let t=()=>{var l,c,d;let u=e,{container:n}=u,o=vd(u,["container"]);this.tracer.log("initVideo",Yt(o)),this.domContainer=qT(e),this.chromecastInitializer.contentId=(l=e.meta)==null?void 0:l.videoId,this.providerContainer=new Za({sources:e.sources,meta:(c=e.meta)!=null?c:{},failoverHosts:(d=e.failoverHosts)!=null?d:[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,tracer:this.tracer,logger:this.logger,abrLogger:this.abrLogger},tuning:this.tuning,volumeMultiplier:e.volumeMultiplier,panelSize:e.panelSize}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.initTracerSubscription(),this.providerContainer.init(),this.setLiveLowLatency(this.tuning.dashCmafLive.lowLatency.isActiveOnDefault),this.setMuted(this.tuning.isAudioDisabled),this.initDebugTelemetry(),this.initWakeLock(),this.playerInited.next(!0)},i=()=>{this.tuning.autostartOnlyIfVisible&&window.requestAnimationFrame?this.playerInitRequest=window.requestAnimationFrame(()=>t()):t()},r=()=>{this.tuning.asyncResolveClientChecker?U.isInited$.pipe(V(n=>!!n),H()).subscribe(()=>{console.log("Core SDK async start"),i()}):i()};return this.isNotActiveTabCase()?(this.tracer.log("request play from hidden tab"),Rc(document,"visibilitychange").pipe(H()).subscribe(r)):r(),this}destroy(){var e,t;this.tracer.log("destroy"),window.clearTimeout(this.hasLiveOffsetByPausedTimer),this.playerInitRequest&&window.cancelAnimationFrame(this.playerInitRequest),this.events.willDestruct$.next(),this.stop(),(e=this.providerContainer)==null||e.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe(),this.tracer.end(),(t=this.internalsExposure)==null||t.destroy()}prepare(){return this.subscription.add(this.playerInited.pipe(V(e=>!!e),H()).subscribe(()=>{let e=this.desiredState.playbackState;this.tracer.log("prepare",{currentPlayBackState:e.getState()}),e.getState()==="stopped"&&e.startTransitionTo("ready")})),this}play(){return this.subscription.add(this.playerInited.pipe(V(e=>!!e),H()).subscribe(()=>{let e=this.desiredState.playbackState;this.tracer.log("play",{currentPlayBackState:e.getState()}),e.getState()!=="playing"&&e.startTransitionTo("playing")})),this}pause(){return this.subscription.add(this.playerInited.pipe(V(e=>!!e),H()).subscribe(()=>{let e=this.desiredState.playbackState;this.tracer.log("pause",{currentPlayBackState:e.getState()}),e.getState()!=="paused"&&e.startTransitionTo("paused")})),this}stop(){return this.subscription.add(this.playerInited.pipe(V(e=>!!e),H()).subscribe(()=>{let e=this.desiredState.playbackState;this.tracer.log("stop",{currentPlayBackState:e.getState()}),e.getState()!=="stopped"&&e.startTransitionTo("stopped")})),this}seekTime(e,t=!0){return this.subscription.add(this.playerInited.pipe(V(i=>!!i),H()).subscribe(()=>{let i=this.info.duration$.getValue(),r=this.info.isLive$.getValue(),s=e;e>=i&&!r&&(s=i-this.tuning.seekNearDurationBias),this.tracer.log("seekTime",{duration:i,isLive:r,time:e,calculatedTime:s,forcePrecise:t}),Number.isFinite(s)&&(this.events.willSeek$.next({from:this.getExactTime(),to:s}),this.desiredState.seekState.setState({state:"requested",position:s*1e3,forcePrecise:t}))})),this}seekPercent(e){return this.subscription.add(this.playerInited.pipe(V(t=>!!t),H()).subscribe(()=>{let t=this.info.duration$.getValue();this.tracer.log("seekPercent",{percent:e,duration:t}),isFinite(t)&&this.seekTime(Math.abs(t)*e,!1)})),this}setVolume(e,t){return this.subscription.add(this.playerInited.pipe(V(i=>!!i),H()).subscribe(()=>{var o;let i=this.desiredState.volume,r=i.getTransition(),s=(o=r==null?void 0:r.to.muted)!=null?o:this.info.muted$.getValue(),n=t!=null?t:this.tuning.isAudioDisabled||s;this.tracer.log("setVolume",{volume:e,isAudioDisabled:this.tuning.isAudioDisabled,chromecastState:this.chromecastInitializer.castState$.getValue(),muted:n}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setVolume(e):i.startTransitionTo({volume:e,muted:n})})),this}setMuted(e){return this.subscription.add(this.playerInited.pipe(V(t=>!!t),H()).subscribe(()=>{var n;let t=this.desiredState.volume,i=this.tuning.isAudioDisabled||e,r=t.getTransition(),s=(n=r==null?void 0:r.to.volume)!=null?n:this.info.volume$.getValue();this.tracer.log("setMuted",{isMuted:e,nextMuted:i,volume:s,isAudioDisabled:this.tuning.isAudioDisabled,chromecastState:this.chromecastInitializer.castState$.getValue()}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setMuted(i):t.startTransitionTo({volume:s,muted:i})})),this}setVideoStream(e){return this.subscription.add(this.playerInited.pipe(V(t=>!!t),H()).subscribe(()=>{this.desiredState.videoStream.startTransitionTo(e)})),this}setAudioStream(e){return this.subscription.add(this.playerInited.pipe(V(t=>!!t),H()).subscribe(()=>{this.desiredState.audioStream.startTransitionTo(e)})),this}setQuality(e){return this.subscription.add(this.playerInited.pipe(V(t=>!!t),H()).subscribe(()=>{Yn(this.providerContainer);let t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();this.tracer.log("setQuality",{isDelayed:t.length===0,quality:e}),this.desiredState.videoTrack.getState()===void 0&&this.desiredState.videoTrack.getPrevState()===void 0&&t.length===0?this.wasSetStartedQuality?this.providerContainer.providerOutput.availableVideoTracks$.pipe(V(i=>i.length>0),H()).subscribe(i=>{this.setVideoTrackIdByQuality(i,e)}):this.explicitInitialQuality=e:t.length>0&&this.setVideoTrackIdByQuality(t,e)})),this}setAutoQuality(e){return this.subscription.add(this.playerInited.pipe(V(t=>!!t),H()).subscribe(()=>{this.tracer.log("setAutoQuality",{enable:e}),this.desiredState.autoVideoTrackSwitching.startTransitionTo(e)})),this}setAutoQualityLimits(e){return this.subscription.add(this.playerInited.pipe(V(t=>!!t),H()).subscribe(()=>{this.tracer.log("setAutoQualityLimits",Yt(e)),this.desiredState.autoVideoTrackLimits.startTransitionTo(e)})),this}setPredefinedQualityLimits(e){return this.subscription.add(this.playerInited.pipe(V(t=>!!t),H()).subscribe(()=>{let{highQualityLimit:t,trafficSavingLimit:i}=this.tuning.autoTrackSelection,r;switch(e){case"high_quality":r={min:t,max:void 0};break;case"traffic_saving":r={max:i,min:void 0};break;default:r={max:void 0,min:void 0}}this.setAutoQualityLimits(r)})),this}setPlaybackRate(e){return this.subscription.add(this.playerInited.pipe(V(t=>!!t),H()).subscribe(()=>{var i;Yn(this.providerContainer);let t=(i=this.providerContainer)==null?void 0:i.providerOutput.element$.getValue();this.tracer.log("setPlaybackRate",{playbackRate:e,isVideoElementAvailable:!!t}),t&&(this.desiredState.playbackRate.setState(e),t.playbackRate=e)})),this}setExternalTextTracks(e){return this.subscription.add(this.playerInited.pipe(V(t=>!!t),H()).subscribe(()=>{e.length&&this.tracer.log("setExternalTextTracks",Yt(e)),this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>w({type:"external"},t)))})),this}selectTextTrack(e){return this.subscription.add(this.playerInited.pipe(V(t=>!!t),H()).subscribe(()=>{var t;UT(e,this.desiredState.currentTextTrack,(t=this.providerContainer)==null?void 0:t.providerOutput.availableTextTracks$,i=>i.id===e),this.tracer.log("selectTextTrack",{textTrackId:e})})),this}setTextTrackCueSettings(e){return this.subscription.add(this.playerInited.pipe(V(t=>!!t),H()).subscribe(()=>{this.tracer.log("setTextTrackCueSettings",w({},e)),this.desiredState.textTrackCuesSettings.startTransitionTo(e)})),this}setLiveLowLatency(e){let t=this.info.isLive$.getValue(),i=this.desiredState.isLowLatency.getState();return!t||i===e?this:(this.tracer.log("live switch to low latency "+e),this.desiredState.isLowLatency.setState(e),this.seekTime(0))}setLooped(e){return this.subscription.add(this.playerInited.pipe(V(t=>!!t),H()).subscribe(()=>{this.tracer.log("setLooped",{isLooped:e}),this.desiredState.isLooped.startTransitionTo(e)})),this}toggleChromecast(){this.tracer.log("toggleChromecast"),this.chromecastInitializer.toggleConnection()}startCameraManualRotation(e,t){return this.subscription.add(this.playerInited.pipe(V(i=>!!i),H()).subscribe(()=>{let i=this.getScene3D();this.tracer.log("startCameraManualRotation",{isScene3DAvailable:!!i,mx:e,my:t}),i&&i.startCameraManualRotation(e,t)})),this}stopCameraManualRotation(e=!1){return this.subscription.add(this.playerInited.pipe(V(t=>!!t),H()).subscribe(()=>{let t=this.getScene3D();this.tracer.log("stopCameraManualRotation",{isScene3DAvailable:!!t,immediate:e}),t&&t.stopCameraManualRotation(e)})),this}moveCameraFocusPX(e,t){return this.subscription.add(this.playerInited.pipe(V(i=>!!i),H()).subscribe(()=>{let i=this.getScene3D();if(this.tracer.log("moveCameraFocusPX",{isScene3DAvailable:!!i,dxpx:e,dypx:t}),i){let r=i.getCameraRotation(),s=i.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:r.x+s.x,y:r.y+s.y})}})),this}holdCamera(){return this.subscription.add(this.playerInited.pipe(V(e=>e),H()).subscribe(()=>{let e=this.getScene3D();e&&e.holdCamera()})),this}releaseCamera(){return this.subscription.add(this.playerInited.pipe(V(e=>!!e),H()).subscribe(()=>{let e=this.getScene3D();e&&e.releaseCamera()})),this}getExactTime(){if(!this.providerContainer)return 0;let e=this.providerContainer.providerOutput.element$.getValue();if($0(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),i=t.state==="none"?void 0:t.position;return HT(i)?i/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}getScene3D(){var t,i;let e=(t=this.providerContainer)==null?void 0:t.current$.getValue();if((i=e==null?void 0:e.provider)!=null&&i.scene3D)return e.provider.scene3D}setIntrinsicVideoSize(...e){let t={width:e.reduce((i,{width:r})=>i||r||0,0),height:e.reduce((i,{height:r})=>i||r||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add(Wt(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(W(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(W(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(W(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(W(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(W(e=>e.to)).subscribe(e=>{this.info.autoQualityLimits$.next(e);let{highQualityLimit:t,trafficSavingLimit:i}=this.tuning.autoTrackSelection;this.info.predefinedQualityLimitType$.next(dl({limits:e,highQualityLimit:t,trafficSavingLimit:i}))})),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(V(({from:e})=>e==="stopped"),H()).subscribe(()=>{this.initedAt=Kn(),this.events.inited$.next()})).add(this.desiredState.playbackState.stateChangeEnded$.subscribe(e=>{switch(e.to){case"ready":this.events.ready$.next();break;case"playing":this.isPlaybackStarted||this.events.started$.next(),this.isPlaybackStarted=!0,this.events.playing$.next();break;case"paused":this.events.paused$.next();break;case"stopped":this.events.stopped$.next()}})).add(this.desiredState.playbackState.stateChangeStarted$.subscribe(e=>{switch(e.to){case"paused":this.events.willPause$.next();break;case"playing":this.isPlaybackStarted?this.events.willResume$.next():this.events.willStart$.next();break;case"stopped":this.events.willStop$.next();break;default:}}))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();this.tracer.log("willSeekEvent",Yt(n)),n.state==="requested"?this.desiredState.seekState.setState(D(w({},n),{state:"applying"})):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:zn.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.soundProhibitedEvent$.pipe(H()).subscribe(this.events.autoplaySoundProhibited$)).add(e.providerOutput.severeStallOccurred$.subscribe(this.events.severeStallOccured$)).add(e.providerOutput.seekedEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();this.tracer.log("seekedEvent",Yt(n)),n.state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe(W(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(W(n=>n.destination),z()).subscribe(()=>this.isPlaybackStarted=!1)).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add(xt({availableVideoTracks:e.providerOutput.availableVideoTracks$,currentVideoStream:e.providerOutput.currentVideoStream$}).pipe(W(({availableVideoTracks:n,currentVideoStream:o})=>n.filter(u=>o?o.id===u.streamId:!0).map(({quality:u})=>u).sort((u,l)=>GT(u)?1:GT(l)?-1:M0(l,u)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(n=>{let o={};for(let u of n)u.fps&&(o[u.quality]=u.fps);this.info.availableQualitiesFps$.next(o)})).add(e.providerOutput.availableAudioStreams$.subscribe(this.info.availableAudioStreams$)).add(e.providerOutput.currentVideoStream$.subscribe(this.info.currentVideoStream$)).add(e.providerOutput.currentAudioStream$.subscribe(this.info.currentAudioStream$)).add(e.providerOutput.availableAudioTracks$.subscribe(this.info.availableAudioTracks$)).add(e.providerOutput.isAudioAvailable$.pipe(z()).subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.pipe(V(n=>HT(n))).subscribe(n=>{this.info.currentQuality$.next(n==null?void 0:n.quality),this.info.videoBitrate$.next(n==null?void 0:n.bitrate)})).add(e.providerOutput.currentVideoSegmentLength$.pipe(z((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.pipe(z((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe(z()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(z()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(z()).subscribe(this.info.httpConnectionReused$)).add(e.providerOutput.currentTextTrack$.subscribe(this.info.currentTextTrack$)).add(e.providerOutput.availableTextTracks$.subscribe(this.info.availableTextTracks$)).add(e.providerOutput.autoVideoTrackLimitingAvailable$.subscribe(this.info.autoQualityLimitingAvailable$)).add(e.providerOutput.autoVideoTrackLimits$.subscribe(n=>{this.desiredState.autoVideoTrackLimits.setState(n!=null?n:{})})).add(e.providerOutput.currentBuffer$.pipe(W(n=>n?{start:n.from,end:n.to}:{start:0,end:0})).subscribe(this.info.currentBuffer$)).add(e.providerOutput.duration$.subscribe(this.info.duration$)).add(e.providerOutput.isBuffering$.subscribe(this.info.isBuffering$)).add(e.providerOutput.isLive$.subscribe(this.info.isLive$)).add(e.providerOutput.isLiveEnded$.pipe($c(n=>n&&this.stop())).subscribe(this.info.isLiveEnded$)).add(e.providerOutput.canChangePlaybackSpeed$.subscribe(this.info.canChangePlaybackSpeed$)).add(e.providerOutput.liveTime$.subscribe(this.info.liveTime$)).add(e.providerOutput.liveBufferTime$.subscribe(this.info.liveBufferTime$)).add(e.providerOutput.liveLatency$.subscribe(this.info.liveLatency$)).add(xt({hasLiveOffsetByPaused:Wt(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(W(n=>n.to),z(),W(n=>n==="paused")),isLowLatency:e.providerOutput.isLowLatency$}).subscribe(({hasLiveOffsetByPaused:n,isLowLatency:o})=>{if(window.clearTimeout(this.hasLiveOffsetByPausedTimer),n){this.hasLiveOffsetByPausedTimer=window.setTimeout(()=>{this.hasLiveOffsetByPaused.next(!0)},this.getActiveLiveDelay(o));return}this.hasLiveOffsetByPaused.next(!1)})).add(xt({atLiveEdge:xt({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:Ac({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(W(({isLive:n,position:o,isLowLatency:u})=>{let l=this.getActiveLiveDelay(u);return n&&Math.abs(o)<l/1e3}),z(),$c(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(W(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add(xt({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(W(({isLive:n,position:o,duration:u})=>n&&(Math.abs(u)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),z(),$c(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(W(n=>n.muted),z()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(W(n=>n.volume),z()).subscribe(this.info.volume$)).add(Ac({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(Wt(e.providerOutput.endedEvent$.pipe(jT(!0)),e.providerOutput.seekedEvent$.pipe(jT(!1))).pipe(z()).subscribe(this.info.isEnded$)).add(e.providerOutput.endedEvent$.subscribe(this.events.ended$)).add(e.providerOutput.loopedEvent$.subscribe(this.events.looped$)).add(e.providerError$.subscribe(this.events.managedError$)).add(e.providerOutput.fetcherRecoverableError$.subscribe(this.events.fetcherRecoverableError$)).add(e.providerOutput.fetcherError$.subscribe(this.events.fatalError$)).add(e.volumeMultiplierError$.subscribe(this.events.managedError$)).add(e.noAvailableProvidersError$.pipe(W(n=>({id:n?`No${n}`:"NoProviders",category:zn.VIDEO_PIPELINE,message:n?`${n} was forced but failed or not available`:"No suitable providers or all providers failed"}))).subscribe(this.events.fatalError$)).add(e.providerOutput.element$.subscribe(this.experimental.element$)).add(e.providerOutput.getCurrentTime$.subscribe(this.experimental.getCurrentTime$)).add(e.providerOutput.firstBytesEvent$.pipe(H(),W(n=>n!=null?n:Kn()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe(H(),W(()=>Kn()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(H(),W(()=>Kn()-this.initedAt)).subscribe(this.events.canplay$)).add(this.throughputEstimator.throughput$.subscribe(this.info.throughputEstimation$)).add(this.throughputEstimator.rtt$.subscribe(this.info.rttEstimation$)).add(e.providerOutput.availableSources$.subscribe(this.info.availableSources$));let t=new k(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let i=new k(!0);this.subscription.add(e.current$.subscribe(()=>i.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(V(({to:n})=>n==="playing"),H()).subscribe(()=>i.next(!1)));let r=0,s=Wt(e.providerOutput.isBuffering$,t,i).pipe(W(()=>{let n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||i.getValue();return n&&!o}),z());this.subscription.add(s.subscribe(n=>{n?r=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(r),this.info.isStalled$.next(!1))})),this.subscription.add(Wt(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{let n=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:n==null?void 0:n.videoWidth,height:n==null?void 0:n.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{var u,l;let o=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:(u=n==null?void 0:n.size)==null?void 0:u.width,height:(l=n==null?void 0:n.size)==null?void 0:l.height},{width:o==null?void 0:o.videoWidth,height:o==null?void 0:o.videoHeight})})).add(e.providerOutput.is3DVideo$.subscribe(this.info.is3DVideo$)),this.subscription.add(Wt(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,e.providerOutput.elementVisible$,this.chromecastInitializer.castState$).subscribe(()=>{let n=e.providerOutput.inPiP$.getValue(),o=e.providerOutput.inFullscreen$.getValue(),u=e.providerOutput.element$.getValue(),l=e.providerOutput.elementVisible$.getValue(),c=this.chromecastInitializer.castState$.getValue(),d;c==="CONNECTED"?d="second_screen":u?l?n?d="pip":o?d="fullscreen":d="inline":d="invisible":d="none",this.info.surface$.getValue()!==d&&this.info.surface$.next(d)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(W(e=>e==null?void 0:e.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){let t=new QT;this.subscription.add(t),this.subscription.add(e.current$.pipe(z((i,r)=>i.provider===r.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(V(i=>i.length>0),H()).subscribe(i=>{this.setStartingVideoTrack(i)}))}))}setStartingVideoTrack(e){var r;let t;this.wasSetStartedQuality=!0;let i=(r=this.explicitInitialQuality)!=null?r:this.info.currentQuality$.getValue();i&&(t=e.find(({quality:s})=>s===i),t||this.setAutoQuality(!0)),t||(t=qt(e,{container:this.domContainer.getBoundingClientRect(),panelSize:this.config.panelSize,estimatedThroughput:this.throughputEstimator.throughput$.getValue(),tuning:this.tuning.autoTrackSelection,limits:this.desiredState.autoVideoTrackLimits.getState(),playbackRate:this.info.currentPlaybackRate$.getValue(),forwardBufferHealth:0,abrLogger:this.abrLogger})),this.desiredState.videoTrack.startTransitionTo(t),this.info.currentQuality$.next(t.quality),this.info.videoBitrate$.next(t.bitrate)}initLogs(){this.subscription.add(Wt(this.desiredState.videoTrack.stateChangeStarted$.pipe(W(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(W(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(W(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(W(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(W(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(W(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(W(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(W(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(W(e=>({component:"desiredState",message:`[${e.entity} change] ${e.type}: ${JSON.stringify(e.transition)}`}))).subscribe(this.logger.log)),this.subscription.add(this.logger.log$.subscribe(this.events.log$))}initDebugTelemetry(){var t;let e=(t=this.providerContainer)==null?void 0:t.providerOutput;Yn(this.providerContainer),Yn(e),Zg(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(i=>Jg(i)),this.providerContainer.current$.subscribe(({type:i})=>Qr("provider",i)),e.duration$.subscribe(i=>Qr("duration",i)),e.availableVideoTracks$.pipe(V(i=>!!i.length),H()).subscribe(i=>Qr("tracks",i)),this.events.fatalError$.subscribe(new Ie("fatalError")),this.events.managedError$.subscribe(new Ie("managedError")),e.position$.subscribe(new Ie("position")),e.currentVideoTrack$.pipe(W(i=>i==null?void 0:i.quality)).subscribe(new Ie("quality")),this.info.currentBuffer$.subscribe(new Ie("buffer")),e.isBuffering$.subscribe(new Ie("isBuffering"))].forEach(i=>this.subscription.add(i)),Qr("codecs",U.video.supportedCodecs)}initTracerSubscription(){let e=WT(this.tracer.log.bind(this.tracer)),t=WT(this.tracer.error.bind(this.tracer));this.subscription.add(this.info.playbackState$.subscribe(e("playbackState"))).add(this.info.isLooped$.subscribe(e("isLooped"))).add(this.info.currentPlaybackRate$.pipe(z()).subscribe(e("currentPlaybackRate"))).add(this.info.isAutoQualityEnabled$.subscribe(e("isAutoQualityEnabled"))).add(this.info.autoQualityLimits$.subscribe(e("autoQualityLimits"))).add(this.info.currentFormat$.subscribe(e("currentFormat"))).add(this.info.availableQualities$.subscribe(e("availableQualities"))).add(this.info.availableQualitiesFps$.subscribe(e("availableQualitiesFps"))).add(this.info.availableAudioTracks$.subscribe(e("availableAudioTracks"))).add(this.info.isAudioAvailable$.subscribe(e("isAudioAvailable"))).add(xt({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe(V(({currentQuality:i,videoBitrate:r})=>!!i&&!!r),z((i,r)=>i.currentQuality===r.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe(V(i=>i>0),z()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe(V(i=>i>0),z()).subscribe(e("currentAudioSegmentLength"))).add(this.info.hostname$.subscribe(e("hostname"))).add(this.info.currentTextTrack$.subscribe(e("currentTextTrack"))).add(this.info.availableTextTracks$.subscribe(e("availableTextTracks"))).add(this.info.autoQualityLimitingAvailable$.subscribe(e("autoQualityLimitingAvailable"))).add(xt({currentBuffer:this.info.currentBuffer$.pipe(V(i=>i.end>0),z((i,r)=>i.end===r.end&&i.start===r.start)),position:this.info.position$.pipe(z())}).pipe(Lc(1e3)).subscribe(e("currentBufferAndPosition"))).add(this.info.duration$.pipe(z()).subscribe(e("duration"))).add(this.info.isBuffering$.subscribe(e("isBuffering"))).add(this.info.isLive$.pipe(z()).subscribe(e("isLive"))).add(this.info.canChangePlaybackSpeed$.pipe(z()).subscribe(e("canChangePlaybackSpeed"))).add(xt({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe(V(({liveTime:i,liveBufferTime:r})=>!!i&&!!r),Lc(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe(z(),V(i=>i===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe(z(),V(i=>i===!0)).subscribe(e("atLiveDurationEdge"))).add(this.info.muted$.pipe(z()).subscribe(e("muted"))).add(this.info.volume$.pipe(z()).subscribe(e("volume"))).add(this.info.isEnded$.pipe(z(),V(i=>i===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add(xt({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe(V(({throughputEstimation:i,rtt:r})=>!!i&&!!r),Lc(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe(z(),V(i=>i===!0)).subscribe(e("is3DVideo"))).add(this.info.surface$.subscribe(e("surface"))).add(this.events.ended$.subscribe(e("ended"))).add(this.events.looped$.subscribe(e("looped"))).add(this.events.managedError$.subscribe(t("managedError"))).add(this.events.fatalError$.subscribe(t("fatalError"))).add(this.events.firstBytes$.subscribe(e("firstBytes"))).add(this.events.firstFrame$.subscribe(e("firstFrame"))).add(this.events.canplay$.subscribe(e("canplay")))}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e,t=()=>{e==null||e.release(),e=void 0},i=()=>E(this,null,function*(){t(),e=yield window.navigator.wakeLock.request("screen").catch(r=>{r instanceof DOMException&&r.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:zn.DOM,message:String(r)})})});this.subscription.add(Wt(Rc(document,"visibilitychange"),Rc(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{let r=document.visibilityState==="visible",s=this.desiredState.playbackState.getState()==="playing",n=!!e&&!(e!=null&&e.released);r&&s?n||i():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){let i=e.find(r=>r.quality===t);this.tracer.log("setVideoTrackIdByQuality",Yt({quality:t,availableTracks:Yt(e),track:Yt(i),isAutoQuality:!i})),i?this.desiredState.videoTrack.startTransitionTo(i):this.setAutoQuality(!0)}getActiveLiveDelay(e=!1){return e?this.tuning.live.lowLatencyActiveLiveDelay:this.tuning.live.activeLiveDelay}isNotActiveTabCase(){return document.hidden&&this.tuning.autoplayOnlyInActiveTab&&!Jr()}};import{Subscription as t8,Observable as i8,Subject as r8,ValueSubject as a8,VideoQuality as s8}from"@vkontakte/videoplayer-shared/es2015";var n8=`@vkontakte/videoplayer-core@${Sd}`;export{fs as ChromecastState,so as HttpConnectionType,i8 as Observable,Ce as PlaybackState,Xn as Player,bs as PredefinedQualityLimits,n8 as SDK_VERSION,r8 as Subject,t8 as Subscription,no as Surface,Sd as VERSION,a8 as ValueSubject,mt as VideoFormat,s8 as VideoQuality,U as clientChecker,Hr as isMobile};
124
+ `;var On=class{constructor(e,t,i){this.videoInitialized=!1;this.active=!1;this.container=e,this.sourceVideoElement=t,this.params=i,this.canvas=this.createCanvas();let r=this.canvas.getContext("webgl");if(!r)throw new Error("Could not initialize WebGL context");this.gl=r,this.container.appendChild(this.canvas),this.camera=new Cn(this.params.fov,this.params.orientation),this.cameraRotationManager=new Vn(this.camera,{rotationSpeed:this.params.rotationSpeed,maxYawAngle:this.params.maxYawAngle,rotationSpeedCorrection:this.params.rotationSpeedCorrection,degreeToPixelCorrection:this.params.degreeToPixelCorrection,speedFadeTime:this.params.speedFadeTime,speedFadeThreshold:this.params.speedFadeThreshold}),this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.textureMappingBuffer=this.createTextureMappingBuffer(),this.updateTextureMappingBuffer(),this.program=this.createProgram(),this.videoTexture=this.createTexture(),this.gl.useProgram(this.program),this.videoElementDataLoadedFn=this.onDataLoadedHandler.bind(this),this.renderFn=this.render.bind(this)}play(){this.active||(this.videoInitialized?this.doPlay():this.sourceVideoElement.readyState>=2?(this.videoInitialized=!0,this.doPlay()):this.sourceVideoElement.addEventListener("loadeddata",this.videoElementDataLoadedFn))}stop(){this.active=!1}startCameraManualRotation(e,t){this.cameraRotationManager.setRotationSpeed(e*this.params.rotationSpeed,t*this.params.rotationSpeed,0),this.cameraRotationManager.startRotation()}stopCameraManualRotation(e=!1){this.cameraRotationManager.stopRotation(e)}turnCamera(e,t){this.cameraRotationManager.turnCamera(e,t)}pointCameraTo(e,t){this.cameraRotationManager.pointCameraTo(e,t)}pixelToDegree(e){return{x:this.params.degreeToPixelCorrection*this.params.fov.x*-e.x/this.viewportWidth,y:this.params.degreeToPixelCorrection*this.params.fov.y*e.y/this.viewportHeight}}getCameraRotation(){return this.camera.orientation}holdCamera(){this.cameraRotationManager.stopRotation(!0)}releaseCamera(){this.cameraRotationManager.onCameraRelease()}destroy(){this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),this.stop(),this.canvas.remove()}setViewportSize(e,t){this.viewportWidth=e,this.viewportHeight=t,this.canvas.width=this.viewportWidth,this.canvas.height=this.viewportHeight,this.gl.viewport(0,0,this.canvas.width,this.canvas.height)}onDataLoadedHandler(){this.videoInitialized=!0,this.doPlay()}doPlay(){this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.active=!0,this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),requestAnimationFrame(this.renderFn)}render(e){this.cameraRotationManager.tick(e),this.updateTexture(),this.updateTextureMappingBuffer();let t=this.gl.getAttribLocation(this.program,"a_vertex"),i=this.gl.getAttribLocation(this.program,"a_texel"),r=this.gl.getUniformLocation(this.program,"u_texture"),s=this.gl.getUniformLocation(this.program,"u_focus");this.gl.enableVertexAttribArray(t),this.gl.enableVertexAttribArray(i),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.vertexBuffer),this.gl.vertexAttribPointer(t,2,this.gl.FLOAT,!1,0,0),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.vertexAttribPointer(i,2,this.gl.FLOAT,!1,0,0),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.uniform1i(r,0),this.gl.uniform2f(s,-this.camera.orientation.x,-this.camera.orientation.y),this.gl.drawArrays(this.gl.TRIANGLE_FAN,0,4),this.gl.bindTexture(this.gl.TEXTURE_2D,null),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),this.gl.disableVertexAttribArray(t),this.gl.disableVertexAttribArray(i),this.active&&requestAnimationFrame(this.renderFn)}createShader(e,t){let i=this.gl.createShader(t);if(!i)throw this.destroy(),new Error(`Could not create shader (${t})`);if(this.gl.shaderSource(i,e),this.gl.compileShader(i),!this.gl.getShaderParameter(i,this.gl.COMPILE_STATUS))throw this.destroy(),new Error("An error occurred while compiling the shader: "+this.gl.getShaderInfoLog(i));return i}createProgram(){let e=this.gl.createProgram();if(!e)throw this.destroy(),new Error("Could not create shader program");let t=this.createShader(Wy,this.gl.VERTEX_SHADER),i=this.createShader(Yy,this.gl.FRAGMENT_SHADER);if(this.gl.attachShader(e,t),this.gl.attachShader(e,i),this.gl.linkProgram(e),!this.gl.getProgramParameter(e,this.gl.LINK_STATUS))throw this.destroy(),new Error("Could not link shader program.");return e}createTexture(){let e=this.gl.createTexture();if(!e)throw this.destroy(),new Error("Could not create texture");return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.bindTexture(this.gl.TEXTURE_2D,null),e}updateTexture(){this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,!0),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.sourceVideoElement),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}createVertexBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create vertex buffer");let t=1,i=1,r=this.frameHeight/(this.frameWidth/this.viewportWidth);return r>this.viewportHeight?t=this.viewportHeight/r:i=r/this.viewportHeight,this.gl.bindBuffer(this.gl.ARRAY_BUFFER,e),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-t,-i,t,-i,t,i,-t,i]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),e}createTextureMappingBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create texture mapping buffer");return e}calculateTexturePosition(){let e=.5-this.camera.orientation.x/360,t=.5-this.camera.orientation.y/180,i=this.camera.fov.x/360/2,r=this.camera.fov.y/180/2,s=e-i,n=t-r,o=e+i,u=t-r,l=e+i,c=t+r,d=e-i,h=t+r;return[s,n,o,u,l,c,d,h]}updateTextureMappingBuffer(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([...this.calculateTexturePosition()]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}updateFrameSize(){this.frameWidth=this.sourceVideoElement.videoWidth,this.frameHeight=this.sourceVideoElement.videoHeight}createCanvas(){let e=document.createElement("canvas");return e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e}};import{isNullable as WD,now as zy,Subscription as YD,filter as zD,combine as Ky,debounce as KD,ValueSubject as uc,isNonNullable as XD}from"@vkontakte/videoplayer-shared/es2015";var lc=class{constructor(){this.isSeeked$=new uc(!1);this.isBuffering$=new uc(!1);this.currentStallsCount=0;this.maxQualityLimit=void 0;this.lastUniqueVideoTrackSelectedTimestamp=0;this.predictedThroughputWithoutData=0;this.subscription=new YD;this.severeStallOccurred$=new uc(!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(Ky({isBuffering:this.isBuffering$,isSeeked:this.isSeeked$}).pipe(KD(this.qualityLimitsOnStall.stallDurationToBeCount),zD(({isBuffering:t,isSeeked:i})=>t&&!i)).subscribe(t=>{this.currentStallsCount++})),this.subscription.add(Ky({currentStallDuration:this.currentStallDuration$}).subscribe(({currentStallDuration:t})=>{let{stallDurationNoDataBeforeQualityDecrease:i,stallCountBeforeQualityDecrease:r,resetQualityRestrictionTimeout:s,ignoreStallsOnSeek:n}=this.qualityLimitsOnStall;if(WD(this.lastUniqueVideoTrackSelected)||n&&this.isSeeked$.getValue())return;let o=this.rtt$.getValue(),u=this.throughput$.getValue(),l=this.videoLastDataObtainedTimestamp$.getValue(),c=zy(),d=r&&this.currentStallsCount>=r,h=i&&c-this.lastUniqueVideoTrackSelectedTimestamp>=i+o&&c-l>=i+o&&t>=i;(d||h)&&(this.severeStallOccurred$.next(!0),window.clearTimeout(this.qualityRestrictionTimer),this.maxQualityLimit=this.lastUniqueVideoTrackSelected.quality,XD(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=zy(),this.currentStallsCount=0)}destroy(){window.clearTimeout(this.qualityRestrictionTimer),this.subscription.unsubscribe()}},Xy=lc;import{combine as JD,map as ZD,observeElementSize as eC,Subscription as tC,ValueSubject as cc,noop as iC}from"@vkontakte/videoplayer-shared/es2015";var Bn=class{constructor(){this.subscription=new tC;this.pipSize$=new cc(void 0);this.videoSize$=new cc(void 0);this.elementSize$=new cc(void 0);this.pictureInPictureWindowRemoveEventListener=iC}connect({observableVideo:e,video:t}){let i=r=>{let s=r.target;this.pipSize$.next({width:s.width,height:s.height})};this.subscription.add(eC(t).subscribe(this.videoSize$)).add(e.enterPip$.subscribe(({pictureInPictureWindow:r})=>{this.pipSize$.next({width:r.width,height:r.height}),r.addEventListener("resize",i),this.pictureInPictureWindowRemoveEventListener=()=>{r.removeEventListener("resize",i)}})).add(e.leavePip$.subscribe(()=>{this.pictureInPictureWindowRemoveEventListener()})).add(JD({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe(ZD(({videoSize:r,inPip:s,pipSize:n})=>s?n:r)).subscribe(this.elementSize$))}getValue(){return this.elementSize$.getValue()}subscribe(e,t){return this.elementSize$.subscribe(e,t)}getObservable(){return this.elementSize$}destroy(){this.pictureInPictureWindowRemoveEventListener(),this.subscription.unsubscribe()}};var yi=class{constructor(e){this.subscription=new uC;this.videoState=new B("stopped");this.droppedFramesManager=new bn;this.stallsManager=new Xy;this.elementSizeManager=new Bn;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new Yr;this.audioTrackSwitchHistory=new Yr;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(r.state==="requested"&&(i==null?void 0:i.to)!=="paused"&&e!=="stopped"&&t!=="stopped"&&this.seek(r.position,r.forcePrecise),t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.player.stop(),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),k(this.params.desiredState.playbackState,"stopped",!0));return}switch(e){case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();return;case"ready":t==="paused"?(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="ready"&&k(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):t==="playing"&&this.video.paused?this.playIfAllowed():(i==null?void 0:i.to)==="playing"&&k(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&k(this.params.desiredState.playbackState,"paused");return;default:return aC(e)}}};this.init3DScene=e=>{var i,r,s;if(this.scene3D)return;this.scene3D=new On(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:((i=e.projectionData)==null?void 0:i.pose.yaw)||0,y:((r=e.projectionData)==null?void 0:r.pose.pitch)||0,z:((s=e.projectionData)==null?void 0:s.pose.roll)||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});let t=this.elementSizeManager.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};this.textTracksManager=new He(e.source.url),this.params=e,this.video=Ae(e.container,e.tuning),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(de(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.player=new Dn({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode,tracer:this.tracer}),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params,i=Le(this.video);this.subscription.add(()=>i.destroy());let r=this.constructor.name,s=o=>{e.error$.next({id:r,category:Jy.WTF,message:`${r} internal logic error`,thrown:o})};return{output:e,desiredState:t,observableVideo:i,genericErrorListener:s,connect:(o,u)=>this.subscription.add(o.subscribe(u,s))}}subscribe(){let{output:e,desiredState:t,observableVideo:i,genericErrorListener:r,connect:s}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe(dc(l=>!!l.length),eT()).subscribe(l=>{this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks:l})}));let n=this.params.desiredState.seekState.stateChangeEnded$.pipe(pc(l=>l.to.state!=="none"),Ua());this.stallsManager.connect({isSeeked$:n,currentStallDuration$:this.player.currentStallDuration$.pipe(Ua()),videoLastDataObtainedTimestamp$:this.player.videoLastDataObtainedTimestamp$,throughput$:this.params.dependencies.throughputEstimator.throughput$,rtt$:this.params.dependencies.throughputEstimator.rtt$,qualityLimitsOnStall:this.params.tuning.dash.qualityLimitsOnStall,isBuffering$:i.isBuffering$,looped$:i.looped$}),s(i.ended$,e.endedEvent$),s(i.looped$,e.loopedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(i.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),s(i.loadedMetadata$,e.loadedMetadataEvent$),s(this.player.error$,e.error$),s(this.player.fetcherRecoverableError$,e.fetcherRecoverableError$),s(this.player.fetcherError$,e.fetcherError$),s(this.player.lastConnectionType$,e.httpConnectionType$),s(this.player.lastConnectionReused$,e.httpConnectionReused$),s(this.player.isLive$,e.isLive$),s(this.player.lastRequestFirstBytes$.pipe(dc(Zy),eT()),e.firstBytesEvent$),s(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),s(this.videoState.stateChangeEnded$.pipe(pc(l=>l.to)),this.params.output.playbackState$),this.subscription.add(i.loopExpected$.subscribe(l=>{t.seekState.setState({state:"requested",position:0,forcePrecise:!1})})),this.subscription.add(i.looped$.subscribe(()=>this.player.warmUpMediaSourceIfNeeded(),r)),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(ot(this.video,t.isLooped,r)),this.subscription.add(Re(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Ue(this.video,t.playbackRate,i.playbackRateState$,r)),this.elementSizeManager.connect({video:this.video,observableVideo:i}),s(je(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),k(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),k(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:l})=>{if(l==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let c=this.player.getStreams();if(sC(c,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let h=[];for(let p of c.audio){h.push(Ql(p));let m=[];for(let b of p.representations){let g=Ty(b);m.push(g),this.audioTracksMap.set(g,{stream:p,representation:b})}this.audioStreamsMap.set(p,m)}this.params.output.availableAudioStreams$.next(h)}let d=[];for(let h of c.video){d.push(Gl(h));let p=[];for(let m of h.representations){let b=yy(D(w({},m),{streamId:h.id}));b&&(p.push(b),this.videoTracksMap.set(b,{stream:h,representation:m}))}this.videoStreamsMap.set(h,p)}this.params.output.availableVideoStreams$.next(d);for(let h of c.text)for(let p of h.representations){let m=Iy(h,p);this.textTracksMap.set(m,{stream:h,representation:p})}this.params.output.availableVideoTracks$.next(Array.from(this.videoTracksMap.keys())),this.params.output.availableAudioTracks$.next(Array.from(this.audioTracksMap.keys())),this.params.output.isAudioAvailable$.next(!!this.audioTracksMap.size),this.audioTracksMap.size&&this.textTracksMap.size&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else l==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},r)),this.subscription.add(_n(this.player.currentStallDuration$,this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,this.elementSizeManager.getObservable(),this.params.output.elementVisible$,this.droppedFramesManager.onDroopedVideoFramesLimit$,oC(this.video,"progress")).pipe(dc(()=>this.videoTracksMap.size>0)).subscribe(()=>E(this,null,function*(){let l=this.player.state$.getState(),c=this.player.state$.getTransition();if(!(0,tT.default)(["manifest_ready","running"],l)||c)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let d=this.selectVideoAudioRepresentations();if(!d)return;let[h,p]=d,m=[...this.videoTracksMap.keys()].find(g=>{var v;return((v=this.videoTracksMap.get(g))==null?void 0:v.representation.id)===h.id});Zy(m)&&(this.stallsManager.lastVideoTrackSelected=m);let b=this.params.desiredState.autoVideoTrackLimits.getTransition();if(b&&this.params.output.autoVideoTrackLimits$.next(b.to),l==="manifest_ready")yield this.player.initRepresentations(h.id,p==null?void 0:p.id,this.params.sourceHls);else if(yield this.player.switchRepresentation("video",h.id),p){let g=!!t.audioStream.getTransition();yield this.player.switchRepresentation("audio",p.id,g)}}),r)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:l})=>{this.scene3D&&l&&this.scene3D.pointCameraTo(l.x,l.y)})),this.subscription.add(this.elementSizeManager.subscribe(l=>{this.scene3D&&l&&this.scene3D.setViewportSize(l.width,l.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(Ua()).subscribe(l=>{let c=[...this.videoTracksMap.entries()].find(([,{representation:m}])=>m.id===l);if(!c){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[d,{stream:h}]=c,p=this.params.desiredState.videoStream.getTransition();p&&p.to&&p.to.id===h.id&&this.params.desiredState.videoStream.setState(p.to),e.currentVideoTrack$.next(d),e.currentVideoStream$.next(Gl(h))},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(Ua()).subscribe(l=>{let c=[...this.audioTracksMap.entries()].find(([,{representation:m}])=>m.id===l);if(!c){e.currentAudioStream$.next(void 0);return}let[d,{stream:h}]=c,p=this.params.desiredState.audioStream.getTransition();p&&p.to&&p.to.id===h.id&&this.params.desiredState.audioStream.setState(p.to),e.currentAudioStream$.next(Ql(h))},r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(l=>{var c,d;if(l!=null&&l.is3dVideo&&((c=this.params.tuning.spherical)!=null&&c.enabled))try{this.init3DScene(l),e.is3DVideo$.next(!0)}catch(h){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${h}`})}else this.destroy3DScene(),(d=this.params.tuning.spherical)!=null&&d.enabled&&e.is3DVideo$.next(!1)},r)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,r)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,r)),this.textTracksManager.connect(this.video,t,e);let o=t.playbackState.stateChangeStarted$.pipe(pc(({to:l})=>l==="ready"),Ua());this.subscription.add(_n(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,hc(["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(_n(o,this.player.state$.stateChangeEnded$,hc(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let u=_n(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,hc(["init"])).pipe(nC(0));this.subscription.add(u.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){var F,q,K,x,H,L,Q,N,Z,R,C,X,P;if(this.player.isStreamEnded)return;let{desiredState:e,output:t}=this.params,i=e.autoVideoTrackSwitching.getState(),r=(F=e.videoTrack.getState())==null?void 0:F.id,n=[...this.videoTracksMap.keys()].find(({id:M})=>M===r),o=t.currentVideoTrack$.getValue(),u=((x=(K=e.videoStream.getState())!=null?K:n&&((q=this.videoTracksMap.get(n))==null?void 0:q.stream))!=null?x:this.videoStreamsMap.size===1)?this.videoStreamsMap.keys().next().value:void 0;if(!u)return;let l=[...this.videoStreamsMap.keys()].find(({id:M})=>M===u.id),c=l&&this.videoStreamsMap.get(l);if(!c)return;let d=Ji(this.video.buffered,this.video.currentTime*1e3),h;this.player.isActiveLive$.getValue()?h=this.player.isLowLatency$.getValue()?this.params.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.params.tuning.dashCmafLive.normalizedLiveMinBufferSize:this.player.isLive$.getValue()?h=this.params.tuning.dashCmafLive.normalizedTargetMinBufferSize:h=i?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;let p=(this.video.duration*1e3||1/0)-this.video.currentTime*1e3,m=Math.min(d/Math.min(h,p||1/0),1),b=(H=e.audioStream.getState())!=null?H:this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0,g=(L=[...this.audioStreamsMap.keys()].find(({id:M})=>M===(b==null?void 0:b.id)))!=null?L:this.audioStreamsMap.keys().next().value,v=0;if(g){if(n&&!i){let M=pn(n,c,(Q=this.audioStreamsMap.get(g))!=null?Q:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);v=Math.max(v,(N=M==null?void 0:M.bitrate)!=null?N:-1/0)}if(o){let M=pn(o,c,(Z=this.audioStreamsMap.get(g))!=null?Z:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);v=Math.max(v,(R=M==null?void 0:M.bitrate)!=null?R:-1/0)}}let S=qt(c,{container:this.elementSizeManager.getValue(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:v,forwardBufferHealth:m,current:o,visible:this.params.output.elementVisible$.getValue(),history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,stallsVideoMaxQualityLimit:this.stallsManager.videoMaxQualityLimit,stallsPredictedThroughput:this.stallsManager.predictedThroughput,abrLogger:this.params.dependencies.abrLogger}),y=i?S!=null?S:n:n!=null?n:S,I=g&&bv(y,c,(C=this.audioStreamsMap.get(g))!=null?C:[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:m,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),T=(X=this.videoTracksMap.get(y))==null?void 0:X.representation,$=I&&((P=this.audioTracksMap.get(I))==null?void 0:P.representation);if(T&&$)return[T,$];if(T&&!$&&this.audioTracksMap.size===0)return[T,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){Me(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Jy.DOM,thrown:e}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.stallsManager.destroy(),this.elementSizeManager.destroy(),this.destroy3DScene(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),this.params.output.currentVideoStream$.next(void 0),ke(this.video),this.tracer.end()}};var Ha=class extends yi{subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();i(t.timeUpdate$,e.position$),i(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}};import{combine as mc,merge as iT,filter as rT,filterChanged as lC,isNullable as fc,map as aT,ValueSubject as bc,isNonNullable as cC}from"@vkontakte/videoplayer-shared/es2015";var ja=class extends yi{constructor(e){super(e),this.textTracksManager.destroy()}subscribe(){super.subscribe();let e=-1,{output:t,observableVideo:i,desiredState:r,connect:s}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),s(i.timeUpdate$,t.liveBufferTime$),s(this.player.liveSeekableDuration$,t.duration$),s(this.player.liveLatency$,t.liveLatency$);let n=new bc(1);s(i.playbackRateState$,n),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(r.isLowLatency.stateChangeEnded$.pipe(aT(o=>o.to)).subscribe(this.player.isLowLatency$)).add(mc({liveBufferTime:t.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(aT(({liveBufferTime:o,liveAvailabilityStartTime:u})=>o&&u?o+u:void 0)).subscribe(t.liveTime$)).add(this.player.liveStreamStatus$.pipe(rT(o=>cC(o))).subscribe(o=>t.isLiveEnded$.next(o!=="active"&&t.position$.getValue()===0))).add(mc({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:iT(i.playbackRateState$,new bc(1))}).pipe(rT(({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||fc(l)||(e=o-l)})).add(mc({time:t.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:iT(i.playbackRateState$,new bc(1))}).pipe(lC((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||fc(o)||fc(u))return;let h=-1*(u-o-e);t.position$.next(Math.min(h,0))})).add(this.player.currentLiveTextRepresentation$.subscribe(o=>{if(o){let u=Ey(o);this.params.output.availableTextTracks$.next([u])}}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,i=Math.trunc(t/1e3<=Math.abs(this.params.output.duration$.getValue())?t:0);this.player.seekLive(i).then(()=>{this.params.output.position$.next(e/1e3)})}};var nT=O(Js(),1);import{assertNever as Qa,assertNonNullable as sT,debounce as dC,ErrorCategory as Nn,filter as pC,isNonNullable as hC,isNullable as mC,map as Fn,merge as fC,Observable as bC,observableFrom as gC,Subscription as vC,videoSizeToQuality as SC}from"@vkontakte/videoplayer-shared/es2015";var et={};var ur=(a,e)=>new bC(t=>{let i=(r,s)=>t.next(s);return a.on(e,i),()=>a.off(e,i)}),Ga=class{constructor(e){this.subscription=new vC;this.videoState=new B("initializing");this.trackLevels=new Map;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(e!=="initializing")switch((i==null?void 0:i.to)!=="paused"&&r.state==="requested"&&this.seek(r.position),t){case"stopped":switch(e){case"stopped":break;case"ready":case"playing":case"paused":this.stop();break;default: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"),k(this.params.desiredState.playbackState,"paused");break;case"playing":this.pause();break;default:Qa(e)}break;default:Qa(t)}};this.textTracksManager=new He(e.source.url),this.video=Ae(e.container,e.tuning),this.params=e,this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(de(this.params.source.url)),this.loadHlsJs()}destroy(){var e,t;this.subscription.unsubscribe(),this.trackLevels.clear(),this.textTracksManager.destroy(),(e=this.hls)==null||e.detachMedia(),(t=this.hls)==null||t.destroy(),this.params.output.element$.next(void 0),ke(this.video)}loadHlsJs(){let e=!1,t=r=>{e||this.params.output.error$.next({id:r==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:Nn.NETWORK,message:"Failed to load Hls.js",thrown:r}),e=!0},i=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);(0,nT.default)(import("hls.js").then(r=>{e||(et.Hls=r.default,et.Events=r.default.Events,this.init())},t),()=>{window.clearTimeout(i),e=!0})}init(){sT(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(){sT(et.Events,"hls.js not loaded");let{desiredState:e,output:t}=this.params,i=l=>{t.error$.next({id:"HlsJsProvider",category:Nn.WTF,message:"HlsJsProvider internal logic error",thrown:l})},r=Le(this.video);this.subscription.add(()=>r.destroy());let s=(l,c)=>this.subscription.add(l.subscribe(c,i));s(r.timeUpdate$,t.position$),s(r.durationChange$,t.duration$),s(r.ended$,t.endedEvent$),s(r.looped$,t.loopedEvent$),s(r.error$,t.error$),s(r.isBuffering$,t.isBuffering$),s(r.currentBuffer$,t.currentBuffer$),s(r.loadStart$,t.firstBytesEvent$),s(r.loadedMetadata$,t.loadedMetadataEvent$),s(r.playing$,t.firstFrameEvent$),s(r.canplay$,t.canplay$),s(r.seeked$,t.seekedEvent$),s(r.inPiP$,t.inPiP$),s(r.inFullscreen$,t.inFullscreen$),this.subscription.add(ot(this.video,e.isLooped,i)),this.subscription.add(Re(this.video,e.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(Ue(this.video,e.playbackRate,r.playbackRateState$,i)),s(je(this.video),t.elementVisible$),s(this.videoState.stateChangeEnded$.pipe(Fn(l=>l.to)),this.params.output.playbackState$),this.subscription.add(ur(this.hls,et.Events.ERROR).subscribe(l=>{var c;l.fatal&&t.error$.next({id:["HlsJsFatal",l.type,l.details].join("_"),category:Nn.WTF,message:`HlsJs fatal ${l.type} ${l.details}, ${(c=l.err)==null?void 0:c.message} ${l.reason}`,thrown:l.error})})),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),k(e.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),k(e.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{var l;((l=this.videoState.getTransition())==null?void 0:l.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),s(ur(this.hls,et.Events.MANIFEST_PARSED).pipe(Fn(({levels:l})=>l.reduce((c,d)=>{var S,y;let h=d.name||d.height.toString(10),{width:p,height:m}=d,b=(y=_t((S=d.attrs.QUALITY)!=null?S:""))!=null?y:SC({width:p,height:m});if(!b)return c;let g=d.attrs["FRAME-RATE"]?parseFloat(d.attrs["FRAME-RATE"]):void 0,v={id:h.toString(),quality:b,bitrate:d.bitrate/1e3,size:{width:p,height:m},fps:g};return this.trackLevels.set(h,{track:v,level:d}),c.push(v),c},[]))),t.availableVideoTracks$),s(ur(this.hls,et.Events.MANIFEST_PARSED),l=>{if(l.subtitleTracks.length>0){let c=[];for(let d of l.subtitleTracks){let h=d.name,p=d.attrs.URI||"",m=d.lang;c.push({id:h,url:p,language:m,type:"internal"})}e.internalTextTracks.startTransitionTo(c)}}),s(ur(this.hls,et.Events.LEVEL_LOADING).pipe(Fn(({url:l})=>de(l))),t.hostname$),s(ur(this.hls,et.Events.FRAG_CHANGED),l=>{var h,p,m,b;let{video:c,audio:d}=l.frag.elementaryStreams;t.currentVideoSegmentLength$.next((((h=c==null?void 0:c.endPTS)!=null?h:0)-((p=c==null?void 0:c.startPTS)!=null?p:0))*1e3),t.currentAudioSegmentLength$.next((((m=d==null?void 0:d.endPTS)!=null?m:0)-((b=d==null?void 0:d.startPTS)!=null?b:0))*1e3)}),this.subscription.add(Vt(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,l=>{this.hls.nextLevel=l?-1:this.hls.currentLevel,this.hls.loadLevel=l?-1:this.hls.loadLevel},{onError:i}));let n=l=>{var c;return(c=Array.from(this.trackLevels.values()).find(({level:d})=>d===l))==null?void 0:c.track},o=ur(this.hls,et.Events.LEVEL_SWITCHED).pipe(Fn(({level:l})=>n(this.hls.levels[l])));o.pipe(pC(hC)).subscribe(t.currentVideoTrack$,i),this.subscription.add(Vt(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel]),l=>{var m;if(mC(l))return;let c=(m=this.trackLevels.get(l.id))==null?void 0:m.level;if(!c)return;let d=this.hls.levels.indexOf(c),h=this.hls.currentLevel,p=this.hls.levels[h];!p||c.bitrate>p.bitrate?this.hls.nextLevel=d:(this.hls.loadLevel=d,this.hls.loadLevel=d)},{changed$:o,onError:i})),s(r.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);let u=fC(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,gC(["init"])).pipe(dC(0));this.subscription.add(u.subscribe(this.syncPlayback,i))}prepare(){this.videoState.startTransitionTo("ready"),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}playIfAllowed(){return E(this,null,function*(){this.videoState.startTransitionTo("playing"),(yield Me(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Nn.DOM,thrown:t})))||(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused",!0))})}pause(){this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}stop(){this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.hls.stopLoad(),this.hls.detachMedia(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState("stopped"),k(this.params.desiredState.playbackState,"stopped",!0)}};var oT="X-Playback-Duration",gc=a=>E(void 0,null,function*(){var r;let e=yield lt(a),t=yield e.text(),i=(r=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t))==null?void 0:r[1];return i?parseInt(i,10):e.headers.has(oT)?parseInt(e.headers.get(oT),10):void 0});import{assertNever as $C,combine as LC,debounce as MC,ErrorCategory as Hn,filter as DC,filterChanged as CC,isNonNullable as cT,isNullable as jn,map as dT,merge as VC,observableFrom as OC,Subscription as BC,ValueSubject as yc,VideoQuality as _C}from"@vkontakte/videoplayer-shared/es2015";var Sc=O(fu(),1);import{videoSizeToQuality as yC,getExponentialDelay as TC}from"@vkontakte/videoplayer-shared/es2015";var IC=a=>{let e=null;if(a.QUALITY&&(e=_t(a.QUALITY)),!e&&a.RESOLUTION){let[t,i]=a.RESOLUTION.split("x").map(r=>parseInt(r,10));e=yC({width:t,height:i})}return e!=null?e:null},EC=(a,e)=>{var s,n;let t=a.split(`
125
+ `),i=[],r=[];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,Sc.default)(l[1].split(",").map(S=>S.split("="))),h=(s=d.QUALITY)!=null?s:`stream-${d.BANDWIDTH}`,p=IC(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,y]=d.RESOLUTION.split("x").map(I=>parseInt(I,10));S&&y&&(g={width:S,height:y})}let v=new URL(t[++o],e).toString();p&&i.push({id:h,quality:p,url:v,bandwidth:m,size:g,fps:b})}if(c){let d=(0,Sc.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,"")])),h=(n=d.URI)==null?void 0:n.replace(/playlist$/,"subtitles.vtt"),p=d.LANGUAGE,m=d.NAME;h&&p&&r.push({type:"internal",id:p,label:m,language:p,url:h,isAuto:!1})}}}if(!i.length)throw new Error("Empty manifest");return{qualityManifests:i,textTracks:r}},xC=a=>new Promise(e=>{setTimeout(()=>{e()},a)}),vc=0,uT=(r,...s)=>E(void 0,[r,...s],function*(a,e=a,t,i){let o=yield(yield lt(a,i)).text();vc+=1;try{let{qualityManifests:u,textTracks:l}=EC(o,e);return{qualityManifests:u,textTracks:l}}catch(u){if(vc<=t.manifestRetryMaxCount)return yield xC(TC(vc-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),uT(a,e,t)}return{qualityManifests:[],textTracks:[]}}),qn=uT;import{isNonNullable as PC,Subscription as wC,throttle as AC,ValueSubject as lT,Subject as kC,ErrorCategory as RC}from"@vkontakte/videoplayer-shared/es2015";var Un=class{constructor(e,t,i,r,s){this.subscription=new wC;this.abortControllers={destroy:new ve,nextManifest:null};this.prepareUrl=void 0;this.currentTextTrackData=null;this.availableTextTracks$=new lT(null);this.getCurrentTime$=new lT(null);this.error$=new kC;this.params={fetchManifestData:i,sourceUrl:r,downloadThreshold:s},this.subscription.add(e.pipe(AC(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:i}=yield this.fetchManifestData();yield this.processTextTracks(i,this.params.sourceUrl)}catch(t){this.error("prepare",t)}})}processTextTracks(e,t){return E(this,null,function*(){try{let i=yield this.parseTextTracks(e,t);i&&(this.currentTextTrackData=i)}catch(i){this.error("processTextTracks",i)}})}parseTextTracks(e,t){return E(this,null,function*(){for(let i of e){let r=new URL(i.url,t).toString(),n=yield(yield lt(r,{signal:this.abortControllers.destroy.signal})).text(),o=this.parsePlaylist(n,r);return{textTrack:i,playlist:o}}})}parsePlaylist(e,t){let i={mediaSequence:0,programDateTime:"",segments:[],targetDuration:0,vkPlaybackDuration:0,segmentStartTime:0,vkStartTime:""},r=e.split(`
126
+ `),s=0;for(let n=0;n<r.length;++n){let o=r[n];switch(!0){case o.startsWith("#EXTINF:"):{let u=r[++n],l=new URL(u,t).toString(),c=Number(this.extractPlaylistRowValue("#EXTINF:",o))*1e3;if(i.segments.push({time:{from:s,to:s+c},url:l}),s=s+c,!i.segmentStartTime){let d=new Date(i.vkStartTime).valueOf(),h=new Date(i.programDateTime).valueOf();i.segmentStartTime=h-d}break}case o.startsWith("#EXT-X-TARGETDURATION:"):i.targetDuration=Number(this.extractPlaylistRowValue("#EXT-X-TARGETDURATION:",o));break;case o.startsWith("#EXT-X-MEDIA-SEQUENCE:"):i.mediaSequence=Number(this.extractPlaylistRowValue("#EXT-X-MEDIA-SEQUENCE:",o));break;case o.startsWith("#EXT-X-VK-PLAYBACK-DURATION:"):i.vkPlaybackDuration=Number(this.extractPlaylistRowValue("#EXT-X-VK-PLAYBACK-DURATION:",o));break;case o.startsWith("#EXT-X-PROGRAM-DATE-TIME:"):{let u=this.extractPlaylistRowValue("#EXT-X-PROGRAM-DATE-TIME:",o);i.programDateTime=u;let l=new Date(u);l.setMilliseconds(0),s=l.valueOf();break}case o.startsWith("#EXT-X-VK-START-TIME:"):i.vkStartTime=this.extractPlaylistRowValue("#EXT-X-VK-START-TIME:",o);break}}return i}extractPlaylistRowValue(e,t){switch(e){case"#EXTINF:":return t.substring(e.length,t.length-1);default:return t.substring(e.length)}}processLiveTime(e){if(PC(e)&&this.currentTextTrackData){let{segments:t}=this.currentTextTrackData.playlist,{from:i}=t[0].time,{to:r}=t[t.length-1].time;if(e<i||e>r)return;r-e<this.params.downloadThreshold&&this.fetchNextManifestData();for(let n of t)if(n.time.from<=e&&n.time.to>=e){this.availableTextTracks$.next([D(w({},this.currentTextTrackData.textTrack),{url:n.url,isAuto:!0})]);break}}}fetchNextManifestData(){return E(this,null,function*(){try{if(this.abortControllers.nextManifest)return;this.abortControllers.nextManifest=new ve;let{textTracks:e}=yield this.fetchManifestData(),t=yield this.parseTextTracks(e,this.params.sourceUrl);this.currentTextTrackData&&t&&(this.currentTextTrackData.playlist.segments=t.playlist.segments)}catch(e){this.error("fetchNextManifestData",e)}finally{this.abortControllers.nextManifest=null}})}fetchManifestData(){return E(this,null,function*(){var t;let e=(t=this.prepareUrl)!=null?t:this.params.sourceUrl;return yield this.params.fetchManifestData(e,{signal:this.abortControllers.destroy.signal})})}error(e,t){this.error$.next({id:"[LiveTextManager][HLS_LIVE_CMAF]",category:RC.WTF,thrown:t,message:e})}};var Wa=class{constructor(e){this.subscription=new BC;this.videoState=new B("stopped");this.textTracksManager=null;this.liveTextManager=null;this.manifests$=new yc([]);this.liveOffset=new hi;this.manifestStartTime$=new yc(void 0);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),k(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||n||o){let c=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(c),this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if((r==null?void 0:r.to)!=="paused"&&l.state==="requested"){this.videoState.startTransitionTo("ready"),this.seek(l.position&&l.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(t){case"ready":i==="ready"?k(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),k(this.params.desiredState.playbackState,"paused")):i==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":i==="paused"?(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(r==null?void 0:r.to)==="playing"&&k(this.params.desiredState.playbackState,"playing");return;case"paused":if(i==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let c=this.liveOffset.getTotalOffset();c>=this.maxSeekBackTime$.getValue()&&(c=0,this.liveOffset.resetTo(c)),this.liveOffset.resume(),this.params.output.position$.next(-c/1e3),this.prepare()}else(r==null?void 0:r.to)==="paused"&&(k(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return $C(t)}};var i;this.params=e,this.video=Ae(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:_C.INVARIANT,url:this.params.source.url};let t=(r,s)=>qn(r,this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},s);this.params.tuning.useHlsLiveNewTextManager?this.liveTextManager=new Un(this.params.output.liveTime$,this.video,t,this.params.source.url,this.params.tuning.hlsLiveNewTextManagerDownloadThreshold):this.textTracksManager=new He(e.source.url),t(this.generateLiveUrl()).then(({qualityManifests:r,textTracks:s})=>{var n;r.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:Hn.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),(n=this.liveTextManager)==null||n.processTextTracks(s,this.params.source.url),this.manifests$.next([this.masterManifest,...r])}).catch(r=>{this.params.output.error$.next({id:"ExtractHlsQualities",category:Hn.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:r})}),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(de(this.params.source.url)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.maxSeekBackTime$=new yc((i=e.source.maxSeekBackTime)!=null?i:1/0),this.subscribe()}selectManifest(){var u,l,c,d;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),r=t.getTransition(),s=(d=(c=(u=r==null?void 0:r.to)==null?void 0:u.id)!=null?c:(l=t.getState())==null?void 0:l.id)!=null?d:"master",n=this.manifests$.getValue();if(!n.length)return;let o=i?"master":s;return i&&!r&&t.startTransitionTo(this.masterManifest),n.find(h=>h.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsLiveProvider",category:Hn.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},r=Le(this.video);this.subscription.add(()=>r.destroy());let s=(o,u)=>this.subscription.add(o.subscribe(u,i));s(r.ended$,e.endedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentBuffer$),s(r.loadedMetadata$,e.firstBytesEvent$),s(r.loadedMetadata$,e.loadedMetadataEvent$),s(r.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(Re(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Ue(this.video,t.playbackRate,r.playbackRateState$,i)),s(je(this.video),e.elementVisible$),this.liveTextManager?(s(this.liveTextManager.getCurrentTime$,this.params.output.getCurrentTime$),s(this.liveTextManager.error$,this.params.output.error$)):this.textTracksManager&&this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),k(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),k(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())==null?void 0:o.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.liveTextManager&&this.subscription.add(this.liveTextManager.availableTextTracks$.subscribe(o=>{o&&this.params.output.availableTextTracks$.next(o)})),this.subscription.add(this.maxSeekBackTime$.pipe(CC(),dT(o=>-o/1e3)).subscribe(this.params.output.duration$,i)),this.subscription.add(r.loadedMetadata$.subscribe(()=>{let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&cT(l.to)){let d=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let h=this.manifests$.getValue().find(p=>p.id===d);h&&(this.params.output.currentVideoTrack$.next(h),this.params.output.hostname$.next(de(h.url)))}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o&&o.state==="requested"&&this.seek(o.position)},i)),this.subscription.add(r.loadedData$.subscribe(()=>{var u,l,c;let o=(c=(l=(u=this.video)==null?void 0:u.getStartDate)==null?void 0:l.call(u))==null?void 0:c.getTime();this.manifestStartTime$.next(o||void 0)},i)),this.subscription.add(LC({startTime:this.manifestStartTime$.pipe(DC(cT)),currentTime:r.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),i)),this.subscription.add(this.manifests$.pipe(dT(o=>o.map(({id:u,quality:l,size:c,bandwidth:d,fps:h})=>({id:u,quality:l,size:c,fps:h,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,i));let n=VC(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,OC(["init"])).pipe(MC(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){var e,t;this.subscription.unsubscribe(),(e=this.textTracksManager)==null||e.destroy(),(t=this.liveTextManager)==null||t.destroy(),this.params.output.element$.next(void 0),ke(this.video)}prepare(){var o,u,l;let e=this.selectManifest();if(jn(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),r=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){let{max:c,min:d}=(u=(o=t==null?void 0:t.to)!=null?o:i)!=null?u:{};for(let[h,p]of[[c,"mq"],[d,"lq"]]){let m=String(parseFloat(h||""));p&&h&&r.searchParams.set(p,m)}}let s=this.params.format==="HLS_LIVE_CMAF"?2:0,n=ge(r.toString(),this.liveOffset.getTotalOffset(),s);(l=this.liveTextManager)==null||l.prepare(n),this.video.setAttribute("src",n),this.video.load(),gc(n).then(c=>{var d;if(!jn(c))this.maxSeekBackTime$.next(c);else{let h=(d=this.params.source.maxSeekBackTime)!=null?d:this.maxSeekBackTime$.getValue();(jn(h)||!isFinite(h))&&lt(n).then(p=>p.text()).then(p=>{var b;let m=(b=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(p))==null?void 0:b[1];if(m){let g=new URL(m,n).toString();gc(g).then(v=>{jn(v)||this.maxSeekBackTime$.next(v)})}}).catch(()=>{})}})}playIfAllowed(){Me(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),k(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Hn.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,i=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(i),this.params.output.position$.next(-i/1e3),this.params.output.seekedEvent$.next()}generateLiveUrl(){let e=ge(this.params.source.url);if(this.params.tuning.useHlsLiveNewTextManager){let t=new URL(e);t.searchParams.set("enable-subtitles","yes"),e=t.toString()}return e}};import{assertNever as NC,debounce as FC,ErrorCategory as Tc,fromEvent as Ic,isNonNullable as qC,isNullable as UC,map as pT,merge as hT,observableFrom as mT,Subscription as HC,ValueSubject as jC,VideoQuality as QC}from"@vkontakte/videoplayer-shared/es2015";var Ya=class{constructor(e){this.subscription=new HC;this.videoState=new B("stopped");this.manifests$=new jC([]);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),k(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||n||o){let c=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(c);let{currentTime:d}=this.video;this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:d*1e3,forcePrecise:!0});return}switch((r==null?void 0:r.to)!=="paused"&&l.state==="requested"&&this.seek(l.position),t){case"ready":i==="ready"?k(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused")):i==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":i==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(r==null?void 0:r.to)==="playing"&&k(this.params.desiredState.playbackState,"playing");return;case"paused":i==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&k(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return NC(t)}};this.textTracksManager=new He(e.source.url),this.params=e,this.video=Ae(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:QC.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),qn(ge(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:t,textTracks:i})=>{this.manifests$.next([this.masterManifest,...t]),this.params.tuning.useNativeHLSTextTracks||this.params.desiredState.internalTextTracks.startTransitionTo(i)},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:Tc.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){var u,l,c,d;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),r=t.getTransition(),s=(d=(c=(u=r==null?void 0:r.to)==null?void 0:u.id)!=null?c:(l=t.getState())==null?void 0:l.id)!=null?d:"master",n=this.manifests$.getValue();if(!n.length)return;let o=i?"master":s;return i&&(!r||!r.from)&&t.startTransitionTo(this.masterManifest),n.find(h=>h.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsProvider",category:Tc.WTF,message:"HlsProvider internal logic error",thrown:o})},r=Le(this.video);this.subscription.add(()=>r.destroy());let s=(o,u)=>this.subscription.add(o.subscribe(u));if(s(r.timeUpdate$,e.position$),s(r.durationChange$,e.duration$),s(r.ended$,e.endedEvent$),s(r.looped$,e.loopedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentBuffer$),s(r.loadedMetadata$,e.firstBytesEvent$),s(r.loadedMetadata$,e.loadedMetadataEvent$),s(r.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.seeked$,e.seekedEvent$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe(pT(o=>o.to)),this.params.output.playbackState$),this.subscription.add(ot(this.video,t.isLooped,i)),this.subscription.add(Re(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Ue(this.video,t.playbackRate,r.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),k(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),k(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())==null?void 0:o.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i).add(r.loadedMetadata$.subscribe(()=>{var p;let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&qC(l.to)){let m=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let b=this.manifests$.getValue().find(g=>g.id===m);b&&(this.params.output.currentVideoTrack$.next(b),this.params.output.hostname$.next(de(b.url)))}let d=this.params.desiredState.playbackRate.getState(),h=(p=this.params.output.element$.getValue())==null?void 0:p.playbackRate;if(d!==h){let m=this.params.output.element$.getValue();m&&(this.params.desiredState.playbackRate.setState(d),m.playbackRate=d)}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o.state==="requested"&&this.seek(o.position)},i))),this.subscription.add(this.manifests$.pipe(pT(o=>o.map(({id:u,quality:l,size:c,bandwidth:d,fps:h})=>({id:u,quality:l,size:c,fps:h,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,i)),!U.device.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add(hT(Ic(o,"addtrack"),Ic(o,"removetrack"),Ic(o,"change"),mT(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},i))}let n=hT(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,mT(["init"])).pipe(FC(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),ke(this.video)}prepare(){var s,n;let e=this.selectManifest();if(UC(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),r=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){let{max:o,min:u}=(n=(s=t==null?void 0:t.to)!=null?s:i)!=null?n:{};for(let[l,c]of[[o,"mq"],[u,"lq"]]){let d=String(parseFloat(l||""));c&&l&&r.searchParams.set(c,d)}}this.video.setAttribute("src",r.toString()),this.video.load()}playIfAllowed(){Me(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Tc.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};var gT=O(_i(),1),Ec=O(zi(),1),vT=O(Nt(),1);import{assertNever as GC,assertNonNullable as fT,debounce as WC,ErrorCategory as bT,isHigherOrEqual as YC,isLowerOrEqual as zC,isNonNullable as KC,merge as XC,observableFrom as JC,Subscription as ZC,map as e0}from"@vkontakte/videoplayer-shared/es2015";var za=class{constructor(e){this.subscription=new ZC;this.videoState=new B("stopped");this.trackUrls={};this.textTracksManager=new He;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),k(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let s=this.params.desiredState.autoVideoTrackLimits.getTransition(),n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.seekState.getState();if(s&&e!=="ready"&&!n){this.handleQualityLimitTransition(s.to);return}if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(n){let{currentTime:u}=this.video;this.prepare(),o.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:u*1e3,forcePrecise:!0});return}switch((i==null?void 0:i.to)!=="paused"&&o.state==="requested"&&this.seek(o.position),e){case"ready":t==="ready"?k(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(i==null?void 0:i.to)==="playing"&&k(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&k(this.params.desiredState.playbackState,"paused");return;default:return GC(e)}};this.params=e,this.video=Ae(e.container,e.tuning),this.params.output.element$.next(this.video),(0,gT.default)(this.params.source).reverse().forEach(([t,i],r)=>{let s=r.toString(10);this.trackUrls[s]={track:{quality:t,id:s},url:i}}),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next((0,Ec.default)(this.trackUrls).map(({track:t})=>t)),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.desiredState.autoVideoTrackSwitching.setState(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.subscribe()}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"MpegProvider",category:bT.WTF,message:"MpegProvider internal logic error",thrown:o})},r=Le(this.video);this.subscription.add(()=>r.destroy());let s=(o,u)=>this.subscription.add(o.subscribe(u,i));s(r.timeUpdate$,e.position$),s(r.durationChange$,e.duration$),s(r.ended$,e.endedEvent$),s(r.looped$,e.loopedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentBuffer$),s(r.loadedMetadata$,e.firstBytesEvent$),s(r.loadedMetadata$,e.loadedMetadataEvent$),s(r.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.seeked$,e.seekedEvent$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe(e0(o=>o.to)),this.params.output.playbackState$),this.subscription.add(ot(this.video,t.isLooped,i)),this.subscription.add(Re(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Ue(this.video,t.playbackRate,r.playbackRateState$,i)),s(je(this.video),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),k(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),k(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{var u,l;((u=this.videoState.getTransition())==null?void 0:u.to)==="ready"&&this.videoState.setState("ready");let o=this.params.desiredState.videoTrack.getTransition();if(o&&KC(o.to)){this.params.desiredState.videoTrack.setState(o.to),this.params.output.currentVideoTrack$.next(this.trackUrls[o.to.id].track);let c=this.params.desiredState.playbackRate.getState(),d=(l=this.params.output.element$.getValue())==null?void 0:l.playbackRate;if(c!==d){let h=this.params.output.element$.getValue();h&&(this.params.desiredState.playbackRate.setState(c),h.playbackRate=c)}}this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.textTracksManager.connect(this.video,t,e);let n=XC(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,JC(["init"])).pipe(WC(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.params.output.element$.next(void 0),ke(this.video)}prepare(){var i;let e=(i=this.params.desiredState.videoTrack.getState())==null?void 0:i.id;fT(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];fT(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=Ca(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(de(t))}playIfAllowed(){Me(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:bT.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){var l,c;this.params.output.autoVideoTrackLimits$.next(e);let t=d=>{this.params.output.currentVideoTrack$.next(d),this.params.desiredState.videoTrack.startTransitionTo(d)},i=d=>{let h=qt(n,{container:this.video.getBoundingClientRect(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:0,limits:d,abrLogger:this.params.dependencies.abrLogger});t(h)},r=(l=this.params.output.currentVideoTrack$.getValue())==null?void 0:l.quality,s=!!(e.max||e.min),n=(0,Ec.default)(this.trackUrls).map(d=>d.track);if(!r||!s||Wr({limits:e,lowestAvailableQuality:(c=(0,vT.default)(n,-1))==null?void 0:c.quality,highestAvailableQuality:n[0].quality})){i();return}let o=e.max?zC(r,e.max):!0,u=e.min?YC(r,e.min):!0;o&&u||i(e)}};import{assertNever as yT,debounce as a0,merge as TT,observableFrom as s0,Subscription as n0,map as IT,ValueSubject as o0,ErrorCategory as Pc,VideoQuality as u0}from"@vkontakte/videoplayer-shared/es2015";import{ErrorCategory as t0}from"@vkontakte/videoplayer-shared/es2015";var ST=["stun:videostun.mycdn.me:80"],i0=1e3,r0=3,xc=()=>null,Qn=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=xc;this.externalStopCallback=xc;this.externalErrorCallback=xc;this.options=this.normalizeOptions(t);let i=e.split("/");this.serverUrl=i.slice(0,i.length-1).join("/"),this.streamKey=i[i.length-1]}onStart(e){try{this.externalStartCallback=e}catch(t){this.handleSystemError(t)}}onStop(e){try{this.externalStopCallback=e}catch(t){this.handleSystemError(t)}}onError(e){try{this.externalErrorCallback=e}catch(t){this.handleSystemError(t)}}connect(){this.connectWS()}disconnect(){try{this.externalStopCallback(),this.closeConnections()}catch(e){this.handleSystemError(e)}}connectWS(){this.ws||(this.ws=new WebSocket(this.serverUrl),this.ws.onopen=this.onSocketOpen.bind(this),this.ws.onmessage=this.onSocketMessage.bind(this),this.ws.onclose=this.onSocketClose.bind(this),this.ws.onerror=this.onSocketError.bind(this))}onSocketOpen(){this.handleLogin()}onSocketClose(e){try{if(!this.ws)return;this.ws=null,e.code>1e3?(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():this.scheduleRetry()):this.externalStopCallback()}catch(t){this.handleRTCError(t)}}onSocketError(e){try{this.externalErrorCallback(new Error(e.toString()))}catch(t){this.handleRTCError(t)}}onSocketMessage(e){try{let t=this.parseMessage(e.data);switch(t.type){case"JOIN":case"CALL_JOIN":this.handleJoinMessage(t);break;case"UPDATE":this.handleUpdateMessage(t);break;case"STATUS":this.handleStatusMessage(t);break}}catch(t){this.handleRTCError(t)}}handleJoinMessage(e){switch(e.inviteType){case"ANSWER":this.handleAnswer(e.sdp);break;case"CANDIDATE":this.handleCandidate(e.candidate);break}}handleStatusMessage(e){switch(e.status){case"UNPUBLISHED":this.handleUnpublished();break}}handleUpdateMessage(e){return E(this,null,function*(){try{let t=yield this.createOffer();this.peerConnection&&(yield this.peerConnection.setLocalDescription(t)),this.handleAnswer(e.sdp)}catch(t){this.handleRTCError(t)}})}handleLogin(){return E(this,null,function*(){try{let e={iceServers:[{urls:ST}]};this.peerConnection=new RTCPeerConnection(e),this.peerConnection.ontrack=this.onPeerConnectionStream.bind(this),this.peerConnection.onicecandidate=this.onPeerConnectionIceCandidate.bind(this),this.peerConnection.oniceconnectionstatechange=this.onPeerConnectionIceConnectionStateChange.bind(this);let t=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:t0.WTF,message:e.message})}onPeerConnectionStream(e){return E(this,null,function*(){let t=e.streams[0];this.stream&&this.stream.id===t.id||(this.stream=t,this.externalStartCallback(this.stream))})}onPeerConnectionIceCandidate(e){e.candidate&&this.send({type:this.signalingType,inviteType:"CANDIDATE",candidate:e.candidate})}onPeerConnectionIceConnectionStateChange(){if(this.peerConnection){let e=this.peerConnection.iceConnectionState;["failed","closed"].indexOf(e)>-1&&(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():(this.closeConnections(),this.scheduleRetry()))}}createOffer(){return E(this,null,function*(){let e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");let t=yield this.peerConnection.createOffer(e),i=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(i))throw new Error("No h264 codec support error");return t})}handleRTCError(e){try{this.externalErrorCallback(e||new Error("RTC connection error"))}catch(t){this.handleSystemError(t)}}handleNetworkError(){try{this.externalErrorCallback(new Error("Network error"))}catch(e){this.handleSystemError(e)}}send(e){this.ws&&this.ws.send(JSON.stringify(e))}parseMessage(e){try{return JSON.parse(e)}catch(t){throw new Error("Can not parse socket message")}}closeConnections(){let e=this.ws;e&&(this.ws=null,e.close(1e3)),this.removePeerConnection()}removePeerConnection(){let e=this.peerConnection;e&&(this.peerConnection=null,e.close(),e.ontrack=null,e.onicecandidate=null,e.oniceconnectionstatechange=null,e=null)}scheduleRetry(){this.retryTimeout=setTimeout(this.connectWS.bind(this),i0)}normalizeOptions(e={}){let t={stunServerList:ST,maxRetryNumber:r0,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var Ka=class{constructor(e){this.videoState=new B("stopped");this.maxSeekBackTime$=new o0(0);this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.pause(),this.video.srcObject=null,this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),k(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let s=this.params.desiredState.videoTrack.getTransition();if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s){this.prepare();return}switch(e){case"ready":t==="paused"?(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(i==null?void 0:i.to)==="playing"&&k(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&k(this.params.desiredState.playbackState,"paused");return;default:return yT(e)}};this.subscription=new n0,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=Ae(e.container,e.tuning),this.liveStreamClient=new Qn(this.params.source.url,{maxRetryNumber:this.params.tuning.webrtc.connectionRetryMaxNumber,errorChanel:this.params.output.error$}),this.liveStreamClient.onStart(this.onLiveStreamStart.bind(this)),this.liveStreamClient.onStop(this.onLiveStreamStop.bind(this)),this.liveStreamClient.onError(this.onLiveStreamError.bind(this)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.subscribe()}destroy(){this.subscription.unsubscribe(),this.liveStreamClient.disconnect(),this.params.output.element$.next(void 0),ke(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,i=n=>{e.error$.next({id:"WebRTCLiveProvider",category:Pc.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};this.subscription.add(TT(this.videoState.stateChangeStarted$.pipe(IT(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe(IT(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})}));let r=Le(this.video);this.subscription.add(()=>r.destroy());let s=(n,o)=>this.subscription.add(n.subscribe(o,i));s(r.timeUpdate$,e.liveTime$),s(r.ended$,e.endedEvent$),s(r.looped$,e.loopedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentBuffer$),s(je(this.video),this.params.output.elementVisible$),this.subscription.add(r.durationChange$.subscribe(n=>{e.duration$.next(n===1/0?0:n)})).add(r.canplay$.subscribe(()=>{var n;((n=this.videoState.getTransition())==null?void 0:n.to)==="ready"&&this.videoState.setState("ready")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused")},i)).add(r.playing$.subscribe(()=>{this.videoState.setState("playing")},i)).add(r.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(Re(this.video,t.volume,r.volumeState$,i)).add(r.volumeState$.subscribe(e.volume$,i)).add(this.videoState.stateChangeEnded$.subscribe(n=>{switch(n.to){case"stopped":e.position$.next(0),e.duration$.next(0),t.playbackState.setState("stopped");break;case"ready":break;case"paused":t.playbackState.setState("paused");break;case"playing":t.playbackState.setState("playing");break;default:return yT(n.to)}},i)).add(TT(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,s0(["init"])).pipe(a0(0)).subscribe(this.syncPlayback.bind(this),i)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),i))}onLiveStreamStart(e){this.params.output.element$.next(this.video),this.params.output.duration$.next(0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(de(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.currentVideoTrack$.next({id:"webrtc",quality:u0.INVARIANT}),this.video.srcObject=e,k(this.params.desiredState.playbackState,"playing")}onLiveStreamStop(){this.videoState.startTransitionTo("stopped"),this.syncPlayback(),this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.params.output.endedEvent$.next()}onLiveStreamError(e){this.onLiveStreamStop(),this.params.output.error$.next({id:"WebRTC stream runtime error",category:Pc.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){Me(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Pc.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var Xa=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 Gt,ErrorCategory as Gn,filter as kT,isNonNullable as RT,isNullable as f0,map as b0,merge as g0,once as v0,Subject as he,Subscription as $T,ValueSubject as _,flattenObject as LT}from"@vkontakte/videoplayer-shared/es2015";import{Observable as l0,map as ET,Subscription as c0,Subject as d0}from"@vkontakte/videoplayer-shared/es2015";var xT=a=>new l0(e=>{let t=new c0,i=a.desiredPlaybackState$.stateChangeStarted$.pipe(ET(({from:l,to:c})=>`${l}-${c}`)),r=a.desiredPlaybackState$.stateChangeEnded$,s=a.providerChanged$.pipe(ET(({type:l})=>l!==void 0)),n=new d0,o=0,u="unknown";return t.add(i.subscribe(l=>{o&&window.clearTimeout(o),u=l,o=window.setTimeout(()=>n.next(l),a.maxTransitionInterval)})),t.add(r.subscribe(()=>{window.clearTimeout(o),u="unknown",o=0})),t.add(s.subscribe(l=>{o&&(window.clearTimeout(o),o=0,l&&(o=window.setTimeout(()=>n.next(u),a.maxTransitionInterval)))})),t.add(n.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});import{ErrorCategory as p0,Subscription as h0,combine as m0,filter as wT,once as AT}from"@vkontakte/videoplayer-shared/es2015";function PT(){return new(window.AudioContext||window.webkitAudioContext)}var Ja=class Ja{constructor(e,t,i,r){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=i;this.volumeMultiplier=r;this.destroyController=new ve;this.subscriptions=new h0;this.audioContext=null;this.gainNode=null;this.mediaElementSource=null;this.subscriptions.add(this.provider$.pipe(wT(s=>!!s.type),AT()).subscribe(({type:s})=>this.subscribe(s)))}subscribe(e){U.browser.isSafari&&e!=="MPEG"||this.subscriptions.add(m0({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe(wT(({playbackState:t,video:i,volume:{muted:r,volume:s}})=>t==="playing"&&!!i&&!r&&!!s),AT()).subscribe(({video:t})=>{this.initAudioContextOnce(t).then(i=>{i||this.destroy()}).catch(i=>{this.handleError(i),this.destroy()})}))}static isSupported(){return"AudioContext"in window&&"GainNode"in window&&"MediaElementAudioSourceNode"in window}initAudioContextOnce(e){return E(this,null,function*(){let{volumeMultiplier:t}=this,i=PT();this.audioContext=i;let r=i.createGain();if(this.gainNode=r,r.gain.value=t,r.connect(i.destination),i.state==="suspended"&&(yield i.resume(),this.destroyController.signal.aborted))return!1;let s=i.createMediaElementSource(e);return this.mediaElementSource=s,s.connect(r),!0})}cleanup(){this.mediaElementSource&&(this.mediaElementSource.disconnect(),this.mediaElementSource=null),this.gainNode&&(this.gainNode.disconnect(),this.gainNode=null),this.audioContext&&(this.audioContext.state!=="closed"&&this.audioContext.close(),this.audioContext=null)}destroy(){this.destroyController.abort(),this.subscriptions.unsubscribe(),this.cleanup()}handleError(e){var t;this.volumeMultiplierError$.next({id:Ja.errorId,category:p0.VIDEO_PIPELINE,message:(t=e==null?void 0:e.message)!=null?t:`${Ja.errorId} exception`,thrown:e})}};Ja.errorId="VolumeMultiplierManager";var lr=Ja;var S0={chunkDuration:5e3,maxParallelRequests:5},es=class{constructor(e){this.current$=new _({type:void 0});this.providerError$=new he;this.noAvailableProvidersError$=new he;this.volumeMultiplierError$=new he;this.providerOutput={position$:new _(0),duration$:new _(1/0),volume$:new _({muted:!1,volume:1}),availableVideoStreams$:new _([]),currentVideoStream$:new _(void 0),availableVideoTracks$:new _([]),currentVideoTrack$:new _(void 0),availableAudioStreams$:new _([]),currentAudioStream$:new _(void 0),availableAudioTracks$:new _([]),currentVideoSegmentLength$:new _(0),currentAudioSegmentLength$:new _(0),isAudioAvailable$:new _(!0),autoVideoTrackLimitingAvailable$:new _(!1),autoVideoTrackLimits$:new _(void 0),currentBuffer$:new _(void 0),isBuffering$:new _(!0),error$:new he,fetcherError$:new he,fetcherRecoverableError$:new he,warning$:new he,willSeekEvent$:new he,soundProhibitedEvent$:new he,seekedEvent$:new he,loopedEvent$:new he,endedEvent$:new he,firstBytesEvent$:new he,loadedMetadataEvent$:new he,firstFrameEvent$:new he,canplay$:new he,isLive$:new _(void 0),isLiveEnded$:new _(null),isLowLatency$:new _(!1),canChangePlaybackSpeed$:new _(!0),liveTime$:new _(void 0),liveBufferTime$:new _(void 0),liveLatency$:new _(void 0),severeStallOccurred$:new he,availableTextTracks$:new _([]),currentTextTrack$:new _(void 0),hostname$:new _(void 0),httpConnectionType$:new _(void 0),httpConnectionReused$:new _(void 0),inPiP$:new _(!1),inFullscreen$:new _(!1),element$:new _(void 0),elementVisible$:new _(!0),availableSources$:new _(void 0),is3DVideo$:new _(!1),playbackState$:new _(""),getCurrentTime$:new _(null)};this.subscription=new $T;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=Fy([...Uy(this.params.tuning),...qy(this.params.tuning)],this.params.tuning).filter(l=>RT(e.sources[l])),{forceFormat:i,formatsToAvoid:r}=this.params.tuning,s=[];i?s=[i]:r.length?s=[...t.filter(l=>!(0,wc.default)(r,l)),...t.filter(l=>(0,wc.default)(r,l))]:s=t,this.log({message:`Selected formats: ${s.join(" > ")}`}),this.tracer.log("Selected formats",LT(s)),this.screenFormatsIterator=new Xa(s);let n=[...ic(!0),...ic(!1)];this.chromecastFormatsIterator=new Xa(n.filter(l=>RT(e.sources[l]))),this.providerOutput.availableSources$.next(e.sources);let{volumeMultiplier:o=1,tuning:{useVolumeMultiplier:u}}=this.params;u&&o!==1&&lr.isSupported()&&(this.volumeMultiplierManager=new lr(this.providerOutput,this.current$,this.volumeMultiplierError$,o))}init(){this.subscription.add(this.initProviderErrorHandling()),this.subscription.add(this.params.dependencies.chromecastInitializer.connection$.subscribe(()=>{this.reinitProvider()}))}destroy(){var e;this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe(),(e=this.volumeMultiplierManager)==null||e.destroy(),this.volumeMultiplierManager=null,this.tracer.end()}initProvider(){let e=this.chooseDestination(),t=this.chooseFormat(e);if(f0(t)){this.handleNoFormatsError(e);return}let i;try{i=this.createProvider(e,t)}catch(r){this.providerError$.next({id:"ProviderNotConstructed",category:Gn.WTF,message:"Failed to create provider",thrown:r})}i?this.current$.next({type:t,provider:i,destination:e}):this.current$.next({type:void 0})}reinitProvider(){this.tracer.log("reinitProvider"),this.destroyProvider(),this.initProvider()}switchToNextProvider(e){this.tracer.log("switchToNextProvider",{destination:e}),this.destroyProvider(),this.failoverIndex=void 0,this.skipFormat(e),this.initProvider()}destroyProvider(){let e=this.current$.getValue().provider;if(!e)return;this.log({message:"destroyProvider"}),this.tracer.log("destroyProvider");let t=this.providerOutput.position$.getValue()*1e3,i=this.params.desiredState.seekState.getState(),r=i.state!=="none";if(this.params.desiredState.seekState.setState({state:"requested",position:r?i.position:t,forcePrecise:r?i.forcePrecise:!1}),e.scene3D){let n=e.scene3D.getCameraRotation();this.params.desiredState.cameraOrientation.setState({x:n.x,y:n.y})}e.destroy();let s=this.providerOutput.isBuffering$;s.getValue()||s.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),this.tracer.log("createProvider",{destination:e,format:t}),e){case"SCREEN":return this.createScreenProvider(t);case"CHROMECAST":return this.createChromecastProvider(t);default:return Za(e)}}createScreenProvider(e){let{sources:t,container:i,desiredState:r,panelSize:s}=this.params,n=this.providerOutput,o={container:i,source:null,desiredState:r,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning,panelSize:s};switch(e){case"DASH_SEP":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_ONDEMAND":case"DASH_STREAMS":{let u=this.applyFailoverHost(t[e]),l=this.applyFailoverHost(t.HLS_ONDEMAND||t.HLS);return Gt(u),new Ha(D(w({},o),{source:u,sourceHls:l}))}case"DASH_LIVE_CMAF":{let u=this.applyFailoverHost(t[e]);return Gt(u),new ja(D(w({},o),{source:u}))}case"HLS":case"HLS_ONDEMAND":{let u=this.applyFailoverHost(t[e]);return Gt(u),U.video.nativeHlsSupported||!this.params.tuning.useHlsJs?new Ya(D(w({},o),{source:u})):new Ga(D(w({},o),{source:u}))}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let u=this.applyFailoverHost(t[e]);return Gt(u),new Wa(D(w({},o),{source:u,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e}))}case"MPEG":{let u=this.applyFailoverHost(t[e]);return Gt(u),new za(D(w({},o),{source:u}))}case"DASH_LIVE":{let u=this.applyFailoverHost(t[e]);return Gt(u),new Dv(D(w({},o),{source:u,config:D(w({},S0),{maxPausedTime:this.params.tuning.live.maxPausedTime})}))}case"WEB_RTC_LIVE":{let u=this.applyFailoverHost(t[e]);return Gt(u),new Ka({container:i,source:u,desiredState:r,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return Za(e)}}createChromecastProvider(e){let{sources:t,container:i,desiredState:r,meta:s}=this.params,n=this.providerOutput,o=this.params.dependencies.chromecastInitializer.connection$.getValue();return Gt(o),new qr({connection:o,meta:s,container:i,source:t,format:e,desiredState:r,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?"CHROMECAST":"SCREEN"}chooseFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case"CHROMECAST":return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return 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 i=r=>{let s=new URL(r);return s.host=t,s.toString()};if(e===void 0)return e;if("type"in e){if(e.type==="raw")return e;if(e.type==="url")return D(w({},e),{url:i(e.url)})}return(0,DT.default)((0,MT.default)(e).map(([r,s])=>[r,i(s)]))}initProviderErrorHandling(){let e=new $T,t=!1,i=0;return e.add(g0(this.providerOutput.error$.pipe(kT(r=>!this.params.tuning.ignoreAudioRendererError||!r.message||!/AUDIO_RENDERER_ERROR/ig.test(r.message))),xT({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(b0(r=>({id:`ProviderHangup:${r}`,category:Gn.WTF,message:`A ${r} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.providerOutput.fetcherError$.subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;let r=this.params.desiredState.playbackState.transitionEnded$.pipe(kT(({to:s})=>s==="playing"),v0()).subscribe(()=>t=!0);e.add(r)})),e.add(this.providerError$.subscribe(r=>{let s=this.current$.getValue().destination,n={error:r,currentDestination:s};if(s==="CHROMECAST")this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider("SCREEN"),()=>this.params.dependencies.chromecastInitializer.disconnect());else{let o=r.category===Gn.NETWORK,u=r.category===Gn.FATAL,l=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),c=i<this.params.tuning.providerErrorLimit&&!u,d=l&&!u&&(o&&t||!c);n=D(w({},n),{isNetworkError:o,isFatalError:u,haveFailoverHost:l,tryFailover:d,canReinitProvider:c}),c?(i++,this.reinitProvider()):d?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):(i=0,this.switchToNextProvider(s!=null?s:"SCREEN"))}this.tracer.error("providerError",LT(n))})),e}};import{fromEvent as Wn,once as y0,combine as T0,Subscription as CT,ValueSubject as Ac,map as I0,filter as E0,isNonNullable as Yn,now as Ne,safeStorage as kc}from"@vkontakte/videoplayer-shared/es2015";var x0=5e3,VT="one_video_throughput",OT="one_video_rtt",xt=window.navigator.connection,BT=()=>{let a=xt==null?void 0:xt.downlink;if(Yn(a)&&a!==10)return a*1e3},_T=()=>{let a=xt==null?void 0:xt.rtt;if(Yn(a)&&a!==3e3)return a},NT=(a,e,t)=>{let i=t*8,r=i/a;return i/(r+e)},Rc=class a{constructor(e){this.subscription=new CT;this.concurrentDownloads=new Set;var r,s;this.tuningConfig=e;let t=a.load(VT)||(e.useBrowserEstimation?BT():void 0)||x0,i=(s=(r=a.load(OT))!=null?r:e.useBrowserEstimation?_T():void 0)!=null?s:0;if(this.throughput$=new Ac(t),this.rtt$=new Ac(i),this.rttAdjustedThroughput$=new Ac(NT(t,i,e.rttPenaltyRequestSize)),this.throughput=vi.getSmoothedValue(t,-1,e),this.rtt=vi.getSmoothedValue(i,1,e),e.useBrowserEstimation){let n=()=>{let u=BT();u&&this.throughput.next(u);let l=_T();Yn(l)&&this.rtt.next(l)};xt&&"onchange"in xt&&this.subscription.add(Wn(xt,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{kc.set(VT,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{kc.set(OT,n.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(T0({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(I0(({throughput:n,rtt:o})=>NT(n,o,e.rttPenaltyRequestSize)),E0(n=>{let o=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(n-o)/o>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,i=Ne(),r=new CT;switch(this.subscription.add(r),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:r.add(Wn(e,"progress").pipe(y0()).subscribe(s=>{t=s.loaded,i=Ne()}));break;case 1:case 0:r.add(Wn(e,"loadstart").subscribe(()=>{t=0,i=Ne()}));break}r.add(Wn(e,"loadend").subscribe(s=>{if(e.status===200){let n=s.loaded,o=Ne(),u=n-t,l=o-i;this.addRawSpeed(u,l,1)}this.concurrentDownloads.delete(e),r.unsubscribe()}))}trackStream(e,t=!1){let i=e.getReader();if(!i){e.cancel("Could not get reader");return}let r=0,s=Ne(),n=0,o=Ne(),u=c=>{this.concurrentDownloads.delete(e),i.releaseLock(),e.cancel(`Throughput Estimator error: ${c}`).catch(()=>{})},l=h=>E(this,[h],function*({done:c,value:d}){if(c)!t&&this.addRawSpeed(r,Ne()-s,1),this.concurrentDownloads.delete(e);else if(d){if(t){let p=Ne();if(p-o>this.tuningConfig.lowLatency.continuesByteSequenceInterval||p-s>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let b=o-s;b&&this.addRawSpeed(n,b,1,t),n=d.byteLength,s=Ne()}else n+=d.byteLength;o=Ne()}else r+=d.byteLength,n+=d.byteLength,n>=this.tuningConfig.streamMinSampleSize&&Ne()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,Ne()-o,this.concurrentDownloads.size),n=0,o=Ne());yield i==null?void 0:i.read().then(l,u)}});this.concurrentDownloads.add(e),i==null||i.read().then(l,u)}addRawSpeed(e,t,i=1,r=!1){if(a.sanityCheck(e,t,r)){let s=e*8/t;this.throughput.next(s*i)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,i=!1){let r=e*8/t;return!(!r||!isFinite(r)||r>1e6||r<30||i&&e<1e4||!i&&e<10*1024||!i&&t<=20)}static load(e){var i;let t=kc.get(e);if(Yn(t))return(i=parseInt(t,10))!=null?i:void 0}},FT=Rc;import{fillWithDefault as P0,VideoQuality as zn}from"@vkontakte/videoplayer-shared/es2015";var qT={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:zn.Q_4320P,activeVideoAreaThreshold:.1,highQualityLimit:zn.Q_720P,trafficSavingLimit:zn.Q_480P},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:zn.Q_480P},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,seekBiasInTheEnd:2e3,maxSegmentDurationLeftToSelectNextSegment:3e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:3e3,crashOnStallTimeout:25e3,crashOnStallTWithoutDataTimeout:5e3,enableSubSegmentBufferFeeding:!0,bufferEmptinessTolerance:100,useFetchPriorityHints:!0,qualityLimitsOnStall:{stallDurationNoDataBeforeQualityDecrease:500,stallDurationToBeCount:100,stallCountBeforeQualityDecrease:3,resetQualityRestrictionTimeout:1e4,ignoreStallsOnSeek:!1},enableBaseUrlSupport:!0,maxSegmentRetryCount:5,sourceOpenTimeout:1e3,rejectOnSourceOpenTimeout:!1},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,maxLiveDuration:7200,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:250,playbackCatchupSpeedup:.05,isActiveOnDefault:!1,bufferEstimator:{emaAlpha:.45,changeThreshold:.05,deviationDepth:20,deviationFactor:.5,extremumInterval:5}}},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1,lowLatencyActiveLiveDelay:3e3,activeLiveDelay:5e3,maxPausedTime:5e3},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,forceFormat:void 0,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:"07A4434E",useWebmBigRequest:!1,webmCodec:"vp9",androidPreferredFormat:"dash",preferCMAF:!1,preferWebRTC:!1,preferMultiStream:!1,preferHDR:!1,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,seekNearDurationBias:1,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useHlsJs:!1,useNativeHLSTextTracks:!1,useManagedMediaSource:!0,useNewSwitchTo:!1,useSafariEndlessRequestBugfix:!0,useRefactoredSearchGap:!1,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,manifestRetryInterval:300,manifestRetryMaxInterval:1e4,manifestRetryMaxCount:10,audioVideoSyncRate:20,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50},useVolumeMultiplier:!1,ignoreAudioRendererError:!1,useEnableSubtitlesParam:!1,useOldMSEDetection:!1,useHlsLiveNewTextManager:!1,exposeInternalsToGlobal:!1,hlsLiveNewTextManagerDownloadThreshold:4e3,disableYandexPiP:!1,asyncResolveClientChecker:!1,autostartOnlyIfVisible:!1},UT=a=>{var e;return D(w({},P0(a,qT)),{configName:[...(e=a.configName)!=null?e:[],...qT.configName]})};import{assertNonNullable as Kn,combine as dt,ErrorCategory as Xn,filter as V,filterChanged as z,fromEvent as Lc,isNonNullable as GT,isNullable as M0,Logger as D0,map as W,mapTo as WT,merge as Wt,now as Jn,once as j,Subject as J,Subscription as YT,tap as Mc,ValueSubject as A,isHigher as C0,isInvariantQuality as zT,flattenObject as Yt,throttle as Dc,getTraceSubscriptionMethod as KT,Tracer as V0,InternalsExposure as O0}from"@vkontakte/videoplayer-shared/es2015";import{merge as w0,map as A0,filter as HT,isNonNullable as k0}from"@vkontakte/videoplayer-shared/es2015";var $c=({seekState:a,position$:e})=>w0(a.stateChangeEnded$.pipe(A0(({to:t})=>{var i;return t.state==="none"?void 0:((i=t.position)!=null?i:NaN)/1e3}),HT(k0)),e.pipe(HT(()=>a.getState().state==="none")));import{assertNonNullable as R0}from"@vkontakte/videoplayer-shared/es2015";var jT=a=>{let e=typeof a.container=="string"?document.getElementById(a.container):a.container;return R0(e,`Wrong container or containerId {${a.container}}`),e};import{filter as $0,once as L0}from"@vkontakte/videoplayer-shared/es2015";var QT=(a,e,t,i)=>{a!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&(t==null?void 0:t.getValue().length)===0?t.pipe($0(r=>r.length>0),L0()).subscribe(r=>{r.find(i)&&e.startTransitionTo(a)}):(a===void 0||t!=null&&t.getValue().find(i))&&e.startTransitionTo(a)};var cr=class cr{constructor(e={configName:[]},t=V0.createRootTracer(!1)){this.subscription=new YT;this.logger=new D0;this.abrLogger=this.logger.createComponentLog("ABR");this.internalsExposure=null;this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new A(!1);this.hasLiveOffsetByPausedTimer=0;this.playerInitRequest=0;this.playerInited=new A(!1);this.wasSetStartedQuality=!1;this.desiredState={playbackState:new B("stopped"),seekState:new B({state:"none"}),volume:new B({volume:1,muted:!1}),videoTrack:new B(void 0),videoStream:new B(void 0),audioStream:new B(void 0),autoVideoTrackSwitching:new B(!0),autoVideoTrackLimits:new B({}),isLooped:new B(!1),isLowLatency:new B(!1),playbackRate:new B(1),externalTextTracks:new B([]),internalTextTracks:new B([]),currentTextTrack:new B(void 0),textTrackCuesSettings:new B({}),cameraOrientation:new B({x:0,y:0})};this.info={playbackState$:new A(void 0),position$:new A(0),duration$:new A(1/0),muted$:new A(!1),volume$:new A(1),availableVideoStreams$:new A([]),currentVideoStream$:new A(void 0),availableQualities$:new A([]),availableQualitiesFps$:new A({}),currentQuality$:new A(void 0),isAutoQualityEnabled$:new A(!0),autoQualityLimitingAvailable$:new A(!1),autoQualityLimits$:new A({}),predefinedQualityLimitType$:new A("unknown"),availableAudioStreams$:new A([]),currentAudioStream$:new A(void 0),availableAudioTracks$:new A([]),isAudioAvailable$:new A(!0),currentPlaybackRate$:new A(1),currentBuffer$:new A({start:0,end:0}),isBuffering$:new A(!0),isStalled$:new A(!1),isEnded$:new A(!1),isLooped$:new A(!1),isLive$:new A(void 0),isLiveEnded$:new A(null),canChangePlaybackSpeed$:new A(void 0),atLiveEdge$:new A(void 0),atLiveDurationEdge$:new A(void 0),liveTime$:new A(void 0),liveBufferTime$:new A(void 0),liveLatency$:new A(void 0),currentFormat$:new A(void 0),availableTextTracks$:new A([]),currentTextTrack$:new A(void 0),throughputEstimation$:new A(void 0),rttEstimation$:new A(void 0),videoBitrate$:new A(void 0),hostname$:new A(void 0),httpConnectionType$:new A(void 0),httpConnectionReused$:new A(void 0),surface$:new A("none"),chromecastState$:new A("NOT_AVAILABLE"),chromecastDeviceName$:new A(void 0),intrinsicVideoSize$:new A(void 0),availableSources$:new A(void 0),is3DVideo$:new A(!1),currentVideoSegmentLength$:new A(0),currentAudioSegmentLength$:new A(0)};this.events={inited$:new J,ready$:new J,started$:new J,playing$:new J,paused$:new J,stopped$:new J,willStart$:new J,willResume$:new J,willPause$:new J,willStop$:new J,willDestruct$:new J,watchCoverageRecord$:new J,watchCoverageLive$:new J,managedError$:new J,fatalError$:new J,fetcherRecoverableError$:new J,ended$:new J,looped$:new J,seeked$:new J,willSeek$:new J,autoplaySoundProhibited$:new J,firstBytes$:new J,loadedMetadata$:new J,firstFrame$:new J,canplay$:new J,log$:new J,fetcherError$:new J,severeStallOccured$:new J};this.experimental={element$:new A(void 0),tuningConfigName$:new A([]),enableDebugTelemetry$:new A(!1),dumpTelemetry:rv,getCurrentTime$:new A(null)};if(this.initLogs(),this.tuning=UT(e),this.tracer=t,this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new xs({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new FT(this.tuning.throughputEstimator),e.exposeInternalsToGlobal&&(this.internalsExposure=new O0("CORE"),this.internalsExposure.expose({player:this})),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(i,r,s)=>{let n=Reflect.get(i,r,s);return typeof n!="function"?n:(...o)=>{try{return n.apply(i,o)}catch(u){let l=o.map(h=>JSON.stringify(h,(p,m)=>{let b=typeof m;return(0,XT.default)(["number","string","boolean"],b)?m:m===null?null:`<${b}>`})),c=`Player.${String(r)}`,d=`Exception calling ${c} (${l.join(", ")})`;throw this.events.fatalError$.next({id:c,category:Xn.WTF,message:d,thrown:u}),u}}}})}static withFiniteDuration(e,t,i){let r=i.value;return i.value=function(...s){return this.subscription.add(dt({inited:this.playerInited.pipe(V(n=>!!n)),duration:this.info.duration$.pipe(V(n=>Number.isFinite(n)))}).pipe(j()).subscribe(()=>{r.apply(this,s)})),this},i}initVideo(e){var s;this.config=e,(s=this.internalsExposure)==null||s.expose({config:e,logger:this.logger,tuning:this.tuning});let t=()=>{var l,c,d;let u=e,{container:n}=u,o=Td(u,["container"]);this.tracer.log("initVideo",Yt(o)),this.domContainer=jT(e),this.chromecastInitializer.contentId=(l=e.meta)==null?void 0:l.videoId,this.providerContainer=new es({sources:e.sources,meta:(c=e.meta)!=null?c:{},failoverHosts:(d=e.failoverHosts)!=null?d:[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,tracer:this.tracer,logger:this.logger,abrLogger:this.abrLogger},tuning:this.tuning,volumeMultiplier:e.volumeMultiplier,panelSize:e.panelSize}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.initTracerSubscription(),this.providerContainer.init(),this.setLiveLowLatency(this.tuning.dashCmafLive.lowLatency.isActiveOnDefault),this.setMuted(this.tuning.isAudioDisabled),this.initDebugTelemetry(),this.initWakeLock(),this.playerInited.next(!0)},i=()=>{this.tuning.autostartOnlyIfVisible&&window.requestAnimationFrame?this.playerInitRequest=window.requestAnimationFrame(()=>t()):t()},r=()=>{this.tuning.asyncResolveClientChecker?U.isInited$.pipe(V(n=>!!n),j()).subscribe(()=>{console.log("Core SDK async start"),i()}):i()};return this.isNotActiveTabCase()?(this.tracer.log("request play from hidden tab"),Lc(document,"visibilitychange").pipe(j()).subscribe(r)):r(),this}destroy(){var e,t;this.tracer.log("destroy"),window.clearTimeout(this.hasLiveOffsetByPausedTimer),this.playerInitRequest&&window.cancelAnimationFrame(this.playerInitRequest),this.events.willDestruct$.next(),this.stop(),(e=this.providerContainer)==null||e.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe(),this.tracer.end(),(t=this.internalsExposure)==null||t.destroy()}prepare(){return this.subscription.add(this.playerInited.pipe(V(e=>!!e),j()).subscribe(()=>{let e=this.desiredState.playbackState;this.tracer.log("prepare",{currentPlayBackState:e.getState()}),e.getState()==="stopped"&&e.startTransitionTo("ready")})),this}play(){return this.subscription.add(this.playerInited.pipe(V(e=>!!e),j()).subscribe(()=>{let e=this.desiredState.playbackState;this.tracer.log("play",{currentPlayBackState:e.getState()}),e.getState()!=="playing"&&e.startTransitionTo("playing")})),this}pause(){return this.subscription.add(this.playerInited.pipe(V(e=>!!e),j()).subscribe(()=>{let e=this.desiredState.playbackState;this.tracer.log("pause",{currentPlayBackState:e.getState()}),e.getState()!=="paused"&&e.startTransitionTo("paused")})),this}stop(){return this.subscription.add(this.playerInited.pipe(V(e=>!!e),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){let i=this.info.duration$.getValue();if(!i||!Number.isFinite(e))return this;let r=e;return i<0?(e>0&&(r=-e),r<i&&(r=i)):e>i?r=i-this.tuning.seekNearDurationBias:e<0&&(r=Math.max(0,i+e)),this.tracer.log("seekTime",{duration:i,isLive:this.info.isLive$.getValue(),time:e,calculatedTime:r,forcePrecise:t}),this.events.willSeek$.next({from:this.getExactTime(),to:r}),this.desiredState.seekState.setState({state:"requested",position:r*1e3,forcePrecise:t}),this}seekPercent(e){let t=this.info.duration$.getValue();return this.tracer.log("seekPercent",{percent:e,duration:t}),this.seekTime(Math.abs(t)*e,!1),this}setVolume(e,t){return this.subscription.add(this.playerInited.pipe(V(i=>!!i),j()).subscribe(()=>{var o;let i=this.desiredState.volume,r=i.getTransition(),s=(o=r==null?void 0:r.to.muted)!=null?o:this.info.muted$.getValue(),n=t!=null?t:this.tuning.isAudioDisabled||s;this.tracer.log("setVolume",{volume:e,isAudioDisabled:this.tuning.isAudioDisabled,chromecastState:this.chromecastInitializer.castState$.getValue(),muted:n}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setVolume(e):i.startTransitionTo({volume:e,muted:n})})),this}setMuted(e){return this.subscription.add(this.playerInited.pipe(V(t=>!!t),j()).subscribe(()=>{var n;let t=this.desiredState.volume,i=this.tuning.isAudioDisabled||e,r=t.getTransition(),s=(n=r==null?void 0:r.to.volume)!=null?n:this.info.volume$.getValue();this.tracer.log("setMuted",{isMuted:e,nextMuted:i,volume:s,isAudioDisabled:this.tuning.isAudioDisabled,chromecastState:this.chromecastInitializer.castState$.getValue()}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setMuted(i):t.startTransitionTo({volume:s,muted:i})})),this}setVideoStream(e){return this.subscription.add(this.playerInited.pipe(V(t=>!!t),j()).subscribe(()=>{this.desiredState.videoStream.startTransitionTo(e)})),this}setAudioStream(e){return this.subscription.add(this.playerInited.pipe(V(t=>!!t),j()).subscribe(()=>{this.desiredState.audioStream.startTransitionTo(e)})),this}setQuality(e){return this.subscription.add(this.playerInited.pipe(V(t=>!!t),j()).subscribe(()=>{Kn(this.providerContainer);let t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();this.tracer.log("setQuality",{isDelayed:t.length===0,quality:e}),this.desiredState.videoTrack.getState()===void 0&&this.desiredState.videoTrack.getPrevState()===void 0&&t.length===0?this.wasSetStartedQuality?this.providerContainer.providerOutput.availableVideoTracks$.pipe(V(i=>i.length>0),j()).subscribe(i=>{this.setVideoTrackIdByQuality(i,e)}):this.explicitInitialQuality=e:t.length>0&&this.setVideoTrackIdByQuality(t,e)})),this}setAutoQuality(e){return this.subscription.add(this.playerInited.pipe(V(t=>!!t),j()).subscribe(()=>{this.tracer.log("setAutoQuality",{enable:e}),this.desiredState.autoVideoTrackSwitching.startTransitionTo(e)})),this}setAutoQualityLimits(e){return this.subscription.add(this.playerInited.pipe(V(t=>!!t),j()).subscribe(()=>{this.tracer.log("setAutoQualityLimits",Yt(e)),this.desiredState.autoVideoTrackLimits.startTransitionTo(e)})),this}setPredefinedQualityLimits(e){return this.subscription.add(this.playerInited.pipe(V(t=>!!t),j()).subscribe(()=>{if(this.info.predefinedQualityLimitType$.getValue()===e)return this;let{highQualityLimit:t,trafficSavingLimit:i}=this.tuning.autoTrackSelection,r;switch(e){case"high_quality":r={min:t,max:void 0};break;case"traffic_saving":r={max:i,min:void 0};break;default:r={max:void 0,min:void 0}}this.setAutoQualityLimits(r)})),this}setPlaybackRate(e){return this.subscription.add(this.playerInited.pipe(V(t=>!!t),j()).subscribe(()=>{var i;Kn(this.providerContainer);let t=(i=this.providerContainer)==null?void 0:i.providerOutput.element$.getValue();this.tracer.log("setPlaybackRate",{playbackRate:e,isVideoElementAvailable:!!t}),t&&(this.desiredState.playbackRate.setState(e),t.playbackRate=e)})),this}setExternalTextTracks(e){return this.subscription.add(this.playerInited.pipe(V(t=>!!t),j()).subscribe(()=>{e.length&&this.tracer.log("setExternalTextTracks",Yt(e)),this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>w({type:"external"},t)))})),this}selectTextTrack(e){return this.subscription.add(this.playerInited.pipe(V(t=>!!t),j()).subscribe(()=>{var t;QT(e,this.desiredState.currentTextTrack,(t=this.providerContainer)==null?void 0:t.providerOutput.availableTextTracks$,i=>i.id===e),this.tracer.log("selectTextTrack",{textTrackId:e})})),this}setTextTrackCueSettings(e){return this.subscription.add(this.playerInited.pipe(V(t=>!!t),j()).subscribe(()=>{this.tracer.log("setTextTrackCueSettings",w({},e)),this.desiredState.textTrackCuesSettings.startTransitionTo(e)})),this}setLiveLowLatency(e){let t=this.info.isLive$.getValue(),i=this.desiredState.isLowLatency.getState();return!t||i===e?this:(this.tracer.log("live switch to low latency "+e),this.desiredState.isLowLatency.setState(e),this.seekTime(0))}setLooped(e){return this.subscription.add(this.playerInited.pipe(V(t=>!!t),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.subscription.add(this.playerInited.pipe(V(i=>!!i),j()).subscribe(()=>{let i=this.getScene3D();this.tracer.log("startCameraManualRotation",{isScene3DAvailable:!!i,mx:e,my:t}),i&&i.startCameraManualRotation(e,t)})),this}stopCameraManualRotation(e=!1){return this.subscription.add(this.playerInited.pipe(V(t=>!!t),j()).subscribe(()=>{let t=this.getScene3D();this.tracer.log("stopCameraManualRotation",{isScene3DAvailable:!!t,immediate:e}),t&&t.stopCameraManualRotation(e)})),this}moveCameraFocusPX(e,t){return this.subscription.add(this.playerInited.pipe(V(i=>!!i),j()).subscribe(()=>{let i=this.getScene3D();if(this.tracer.log("moveCameraFocusPX",{isScene3DAvailable:!!i,dxpx:e,dypx:t}),i){let r=i.getCameraRotation(),s=i.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:r.x+s.x,y:r.y+s.y})}})),this}holdCamera(){return this.subscription.add(this.playerInited.pipe(V(e=>e),j()).subscribe(()=>{let e=this.getScene3D();e&&e.holdCamera()})),this}releaseCamera(){return this.subscription.add(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(M0(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),i=t.state==="none"?void 0:t.position;return GT(i)?i/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}getScene3D(){var t,i;let e=(t=this.providerContainer)==null?void 0:t.current$.getValue();if((i=e==null?void 0:e.provider)!=null&&i.scene3D)return e.provider.scene3D}setIntrinsicVideoSize(...e){let t={width:e.reduce((i,{width:r})=>i||r||0,0),height:e.reduce((i,{height:r})=>i||r||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add(Wt(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(W(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(W(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(W(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(W(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(W(e=>e.to)).subscribe(e=>{this.info.autoQualityLimits$.next(e);let{highQualityLimit:t,trafficSavingLimit:i}=this.tuning.autoTrackSelection;this.info.predefinedQualityLimitType$.next(hl({limits:e,highQualityLimit:t,trafficSavingLimit:i}))})),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(V(({from:e})=>e==="stopped"),j()).subscribe(()=>{this.initedAt=Jn(),this.events.inited$.next()})).add(this.desiredState.playbackState.stateChangeEnded$.subscribe(e=>{switch(e.to){case"ready":this.events.ready$.next();break;case"playing":this.isPlaybackStarted||this.events.started$.next(),this.isPlaybackStarted=!0,this.events.playing$.next();break;case"paused":this.events.paused$.next();break;case"stopped":this.events.stopped$.next()}})).add(this.desiredState.playbackState.stateChangeStarted$.subscribe(e=>{switch(e.to){case"paused":this.events.willPause$.next();break;case"playing":this.isPlaybackStarted?this.events.willResume$.next():this.events.willStart$.next();break;case"stopped":this.events.willStop$.next();break;default:}}))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();this.tracer.log("willSeekEvent",Yt(n)),n.state==="requested"?this.desiredState.seekState.setState(D(w({},n),{state:"applying"})):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:Xn.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",Yt(n)),n.state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe(W(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(W(n=>n.destination),z()).subscribe(()=>this.isPlaybackStarted=!1)).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add(dt({availableVideoTracks:e.providerOutput.availableVideoTracks$,currentVideoStream:e.providerOutput.currentVideoStream$}).pipe(W(({availableVideoTracks:n,currentVideoStream:o})=>n.filter(u=>o?o.id===u.streamId:!0).map(({quality:u})=>u).sort((u,l)=>zT(u)?1:zT(l)?-1:C0(l,u)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(n=>{let o={};for(let u of n)u.fps&&(o[u.quality]=u.fps);this.info.availableQualitiesFps$.next(o)})).add(e.providerOutput.availableAudioStreams$.subscribe(this.info.availableAudioStreams$)).add(e.providerOutput.currentVideoStream$.subscribe(this.info.currentVideoStream$)).add(e.providerOutput.currentAudioStream$.subscribe(this.info.currentAudioStream$)).add(e.providerOutput.availableAudioTracks$.subscribe(this.info.availableAudioTracks$)).add(e.providerOutput.isAudioAvailable$.pipe(z()).subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.pipe(V(n=>GT(n))).subscribe(n=>{this.info.currentQuality$.next(n==null?void 0:n.quality),this.info.videoBitrate$.next(n==null?void 0:n.bitrate)})).add(e.providerOutput.currentVideoSegmentLength$.pipe(z((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.pipe(z((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe(z()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(z()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(z()).subscribe(this.info.httpConnectionReused$)).add(e.providerOutput.currentTextTrack$.subscribe(this.info.currentTextTrack$)).add(e.providerOutput.availableTextTracks$.subscribe(this.info.availableTextTracks$)).add(e.providerOutput.autoVideoTrackLimitingAvailable$.subscribe(this.info.autoQualityLimitingAvailable$)).add(e.providerOutput.autoVideoTrackLimits$.subscribe(n=>{this.desiredState.autoVideoTrackLimits.setState(n!=null?n:{})})).add(e.providerOutput.currentBuffer$.pipe(W(n=>n?{start:n.from,end:n.to}:{start:0,end:0})).subscribe(this.info.currentBuffer$)).add(e.providerOutput.duration$.subscribe(this.info.duration$)).add(e.providerOutput.isBuffering$.subscribe(this.info.isBuffering$)).add(e.providerOutput.isLive$.subscribe(this.info.isLive$)).add(e.providerOutput.isLiveEnded$.pipe(Mc(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(dt({hasLiveOffsetByPaused:Wt(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(W(n=>n.to),z(),W(n=>n==="paused")),isLowLatency:e.providerOutput.isLowLatency$}).subscribe(({hasLiveOffsetByPaused:n,isLowLatency:o})=>{if(window.clearTimeout(this.hasLiveOffsetByPausedTimer),n){this.hasLiveOffsetByPausedTimer=window.setTimeout(()=>{this.hasLiveOffsetByPaused.next(!0)},this.getActiveLiveDelay(o));return}this.hasLiveOffsetByPaused.next(!1)})).add(dt({atLiveEdge:dt({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:$c({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(W(({isLive:n,position:o,isLowLatency:u})=>{let l=this.getActiveLiveDelay(u);return n&&Math.abs(o)<l/1e3}),z(),Mc(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(W(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add(dt({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(W(({isLive:n,position:o,duration:u})=>n&&(Math.abs(u)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),z(),Mc(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(W(n=>n.muted),z()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(W(n=>n.volume),z()).subscribe(this.info.volume$)).add($c({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(Wt(e.providerOutput.endedEvent$.pipe(WT(!0)),e.providerOutput.seekedEvent$.pipe(WT(!1))).pipe(z()).subscribe(this.info.isEnded$)).add(e.providerOutput.endedEvent$.subscribe(this.events.ended$)).add(e.providerOutput.loopedEvent$.subscribe(this.events.looped$)).add(e.providerError$.subscribe(this.events.managedError$)).add(e.providerOutput.fetcherRecoverableError$.subscribe(this.events.fetcherRecoverableError$)).add(e.providerOutput.fetcherError$.subscribe(this.events.fatalError$)).add(e.volumeMultiplierError$.subscribe(this.events.managedError$)).add(e.noAvailableProvidersError$.pipe(W(n=>({id:n?`No${n}`:"NoProviders",category:Xn.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(),W(n=>n!=null?n:Jn()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe(j(),W(()=>Jn()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(j(),W(()=>Jn()-this.initedAt)).subscribe(this.events.canplay$)).add(this.throughputEstimator.throughput$.subscribe(this.info.throughputEstimation$)).add(this.throughputEstimator.rtt$.subscribe(this.info.rttEstimation$)).add(e.providerOutput.availableSources$.subscribe(this.info.availableSources$));let t=new A(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let i=new A(!0);this.subscription.add(e.current$.subscribe(()=>i.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(V(({to:n})=>n==="playing"),j()).subscribe(()=>i.next(!1)));let r=0,s=Wt(e.providerOutput.isBuffering$,t,i).pipe(W(()=>{let n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||i.getValue();return n&&!o}),z());this.subscription.add(s.subscribe(n=>{n?r=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(r),this.info.isStalled$.next(!1))})),this.subscription.add(Wt(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{let n=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:n==null?void 0:n.videoWidth,height:n==null?void 0:n.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{var u,l;let o=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:(u=n==null?void 0:n.size)==null?void 0:u.width,height:(l=n==null?void 0:n.size)==null?void 0:l.height},{width:o==null?void 0:o.videoWidth,height:o==null?void 0:o.videoHeight})})).add(e.providerOutput.is3DVideo$.subscribe(this.info.is3DVideo$)),this.subscription.add(Wt(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,e.providerOutput.elementVisible$,this.chromecastInitializer.castState$).subscribe(()=>{let n=e.providerOutput.inPiP$.getValue(),o=e.providerOutput.inFullscreen$.getValue(),u=e.providerOutput.element$.getValue(),l=e.providerOutput.elementVisible$.getValue(),c=this.chromecastInitializer.castState$.getValue(),d;c==="CONNECTED"?d="second_screen":u?l?n?d="pip":o?d="fullscreen":d="inline":d="invisible":d="none",this.info.surface$.getValue()!==d&&this.info.surface$.next(d)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(W(e=>e==null?void 0:e.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){let t=new YT;this.subscription.add(t),this.subscription.add(e.current$.pipe(z((i,r)=>i.provider===r.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(V(i=>i.length>0),j()).subscribe(i=>{this.setStartingVideoTrack(i)}))}))}setStartingVideoTrack(e){var r;let t;this.wasSetStartedQuality=!0;let i=(r=this.explicitInitialQuality)!=null?r:this.info.currentQuality$.getValue();i&&(t=e.find(({quality:s})=>s===i),t||this.setAutoQuality(!0)),t||(t=qt(e,{container:this.domContainer.getBoundingClientRect(),panelSize:this.config.panelSize,estimatedThroughput:this.throughputEstimator.throughput$.getValue(),tuning:this.tuning.autoTrackSelection,limits:this.desiredState.autoVideoTrackLimits.getState(),playbackRate:this.info.currentPlaybackRate$.getValue(),forwardBufferHealth:0,abrLogger:this.abrLogger})),this.desiredState.videoTrack.startTransitionTo(t),this.info.currentQuality$.next(t.quality),this.info.videoBitrate$.next(t.bitrate)}initLogs(){this.subscription.add(Wt(this.desiredState.videoTrack.stateChangeStarted$.pipe(W(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(W(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(W(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(W(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(W(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(W(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(W(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(W(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(W(e=>({component:"desiredState",message:`[${e.entity} change] ${e.type}: ${JSON.stringify(e.transition)}`}))).subscribe(this.logger.log)),this.subscription.add(this.logger.log$.subscribe(this.events.log$))}initDebugTelemetry(){var t;let e=(t=this.providerContainer)==null?void 0:t.providerOutput;Kn(this.providerContainer),Kn(e),iv(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(i=>tv(i)),this.providerContainer.current$.subscribe(({type:i})=>Gr("provider",i)),e.duration$.subscribe(i=>Gr("duration",i)),e.availableVideoTracks$.pipe(V(i=>!!i.length),j()).subscribe(i=>Gr("tracks",i)),this.events.fatalError$.subscribe(new Ie("fatalError")),this.events.managedError$.subscribe(new Ie("managedError")),e.position$.subscribe(new Ie("position")),e.currentVideoTrack$.pipe(W(i=>i==null?void 0:i.quality)).subscribe(new Ie("quality")),this.info.currentBuffer$.subscribe(new Ie("buffer")),e.isBuffering$.subscribe(new Ie("isBuffering"))].forEach(i=>this.subscription.add(i)),Gr("codecs",U.video.supportedCodecs)}initTracerSubscription(){let e=KT(this.tracer.log.bind(this.tracer)),t=KT(this.tracer.error.bind(this.tracer));this.subscription.add(this.info.playbackState$.subscribe(e("playbackState"))).add(this.info.isLooped$.subscribe(e("isLooped"))).add(this.info.currentPlaybackRate$.pipe(z()).subscribe(e("currentPlaybackRate"))).add(this.info.isAutoQualityEnabled$.subscribe(e("isAutoQualityEnabled"))).add(this.info.autoQualityLimits$.subscribe(e("autoQualityLimits"))).add(this.info.currentFormat$.subscribe(e("currentFormat"))).add(this.info.availableQualities$.subscribe(e("availableQualities"))).add(this.info.availableQualitiesFps$.subscribe(e("availableQualitiesFps"))).add(this.info.availableAudioTracks$.subscribe(e("availableAudioTracks"))).add(this.info.isAudioAvailable$.subscribe(e("isAudioAvailable"))).add(dt({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe(V(({currentQuality:i,videoBitrate:r})=>!!i&&!!r),z((i,r)=>i.currentQuality===r.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe(V(i=>i>0),z()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe(V(i=>i>0),z()).subscribe(e("currentAudioSegmentLength"))).add(this.info.hostname$.subscribe(e("hostname"))).add(this.info.currentTextTrack$.subscribe(e("currentTextTrack"))).add(this.info.availableTextTracks$.subscribe(e("availableTextTracks"))).add(this.info.autoQualityLimitingAvailable$.subscribe(e("autoQualityLimitingAvailable"))).add(dt({currentBuffer:this.info.currentBuffer$.pipe(V(i=>i.end>0),z((i,r)=>i.end===r.end&&i.start===r.start)),position:this.info.position$.pipe(z())}).pipe(Dc(1e3)).subscribe(e("currentBufferAndPosition"))).add(this.info.duration$.pipe(z()).subscribe(e("duration"))).add(this.info.isBuffering$.subscribe(e("isBuffering"))).add(this.info.isLive$.pipe(z()).subscribe(e("isLive"))).add(this.info.canChangePlaybackSpeed$.pipe(z()).subscribe(e("canChangePlaybackSpeed"))).add(dt({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe(V(({liveTime:i,liveBufferTime:r})=>!!i&&!!r),Dc(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe(z(),V(i=>i===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe(z(),V(i=>i===!0)).subscribe(e("atLiveDurationEdge"))).add(this.info.muted$.pipe(z()).subscribe(e("muted"))).add(this.info.volume$.pipe(z()).subscribe(e("volume"))).add(this.info.isEnded$.pipe(z(),V(i=>i===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add(dt({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe(V(({throughputEstimation:i,rtt:r})=>!!i&&!!r),Dc(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe(z(),V(i=>i===!0)).subscribe(e("is3DVideo"))).add(this.info.surface$.subscribe(e("surface"))).add(this.events.ended$.subscribe(e("ended"))).add(this.events.looped$.subscribe(e("looped"))).add(this.events.managedError$.subscribe(t("managedError"))).add(this.events.fatalError$.subscribe(t("fatalError"))).add(this.events.firstBytes$.subscribe(e("firstBytes"))).add(this.events.firstFrame$.subscribe(e("firstFrame"))).add(this.events.canplay$.subscribe(e("canplay")))}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e,t=()=>{e==null||e.release(),e=void 0},i=()=>E(this,null,function*(){t(),e=yield window.navigator.wakeLock.request("screen").catch(r=>{r instanceof DOMException&&r.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:Xn.DOM,message:String(r)})})});this.subscription.add(Wt(Lc(document,"visibilitychange"),Lc(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{let r=document.visibilityState==="visible",s=this.desiredState.playbackState.getState()==="playing",n=!!e&&!(e!=null&&e.released);r&&s?n||i():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){let i=e.find(r=>r.quality===t);this.tracer.log("setVideoTrackIdByQuality",Yt({quality:t,availableTracks:Yt(e),track:Yt(i),isAutoQuality:!i})),i?this.desiredState.videoTrack.startTransitionTo(i):this.setAutoQuality(!0)}getActiveLiveDelay(e=!1){return e?this.tuning.live.lowLatencyActiveLiveDelay:this.tuning.live.activeLiveDelay}isNotActiveTabCase(){return document.hidden&&this.tuning.autoplayOnlyInActiveTab&&!Zr()}};no([cr.withFiniteDuration],cr.prototype,"seekTime",1),no([cr.withFiniteDuration],cr.prototype,"seekPercent",1);var Zn=cr;import{Subscription as r8,Observable as a8,Subject as s8,ValueSubject as n8,VideoQuality as o8}from"@vkontakte/videoplayer-shared/es2015";var u8=`@vkontakte/videoplayer-core@${Id}`;export{gs as ChromecastState,oo as HttpConnectionType,a8 as Observable,Ce as PlaybackState,Zn as Player,vs as PredefinedQualityLimits,u8 as SDK_VERSION,s8 as Subject,r8 as Subscription,uo as Surface,Id as VERSION,n8 as ValueSubject,ft as VideoFormat,o8 as VideoQuality,U as clientChecker,jr as isMobile};