@vkontakte/videoplayer-core 2.0.135-dev.de6f0c74.0 → 2.0.135-dev.ee4a31cc.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/es2015.cjs.js +20 -20
- package/es2015.esm.js +24 -24
- package/es2018.cjs.js +25 -25
- package/es2018.esm.js +18 -18
- package/es2024.cjs.js +26 -26
- package/es2024.esm.js +23 -23
- package/esnext.cjs.js +26 -26
- package/esnext.esm.js +23 -23
- package/evergreen.esm.js +17 -17
- package/package.json +2 -2
- package/types/providers/DashProvider/baseDashProvider.d.ts +2 -0
- package/types/providers/DashProviderNew/baseDashProvider.d.ts +2 -0
package/esnext.cjs.js
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @vkontakte/videoplayer-core v2.0.135-dev.
|
|
3
|
-
* Tue,
|
|
2
|
+
* @vkontakte/videoplayer-core v2.0.135-dev.ee4a31cc.0
|
|
3
|
+
* Tue, 01 Jul 2025 11:59:49 GMT
|
|
4
4
|
* https://st.mycdn.me/static/vkontakte-videoplayer/2-0-135/doc/
|
|
5
5
|
*/
|
|
6
|
-
"use strict";var my=Object.create;var Ga=Object.defineProperty;var by=Object.getOwnPropertyDescriptor;var gy=Object.getOwnPropertyNames;var Sy=Object.getPrototypeOf,vy=Object.prototype.hasOwnProperty;var b=(s,e)=>()=>(e||s((e={exports:{}}).exports,e),e.exports),yy=(s,e)=>{for(var t in e)Ga(s,t,{get:e[t],enumerable:!0})},Uc=(s,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of gy(e))!vy.call(s,r)&&r!==t&&Ga(s,r,{get:()=>e[r],enumerable:!(i=by(e,r))||i.enumerable});return s};var j=(s,e,t)=>(t=s!=null?my(Sy(s)):{},Uc(e||!s||!s.__esModule?Ga(t,"default",{value:s,enumerable:!0}):t,s)),Ty=s=>Uc(Ga({},"__esModule",{value:!0}),s);var De=b((Fo,qc)=>{"use strict";var jr=function(s){return s&&s.Math===Math&&s};qc.exports=jr(typeof globalThis=="object"&&globalThis)||jr(typeof window=="object"&&window)||jr(typeof self=="object"&&self)||jr(typeof global=="object"&&global)||jr(typeof Fo=="object"&&Fo)||function(){return this}()||Function("return this")()});var Qe=b((IL,Hc)=>{"use strict";Hc.exports=function(s){try{return!!s()}catch{return!0}}});var zr=b((xL,jc)=>{"use strict";var Iy=Qe();jc.exports=!Iy(function(){var s=function(){}.bind();return typeof s!="function"||s.hasOwnProperty("prototype")})});var No=b((EL,Wc)=>{"use strict";var xy=zr(),Gc=Function.prototype,zc=Gc.apply,Qc=Gc.call;Wc.exports=typeof Reflect=="object"&&Reflect.apply||(xy?Qc.bind(zc):function(){return Qc.apply(zc,arguments)})});var He=b((wL,Xc)=>{"use strict";var Yc=zr(),Kc=Function.prototype,Uo=Kc.call,Ey=Yc&&Kc.bind.bind(Uo,Uo);Xc.exports=Yc?Ey:function(s){return function(){return Uo.apply(s,arguments)}}});var Oi=b((PL,Zc)=>{"use strict";var Jc=He(),wy=Jc({}.toString),Py=Jc("".slice);Zc.exports=function(s){return Py(wy(s),8,-1)}});var qo=b((AL,ed)=>{"use strict";var Ay=Oi(),ky=He();ed.exports=function(s){if(Ay(s)==="Function")return ky(s)}});var Me=b((kL,td)=>{"use strict";var Ho=typeof document=="object"&&document.all;td.exports=typeof Ho>"u"&&Ho!==void 0?function(s){return typeof s=="function"||s===Ho}:function(s){return typeof s=="function"}});var yt=b((RL,id)=>{"use strict";var Ry=Qe();id.exports=!Ry(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var Tt=b((ML,rd)=>{"use strict";var My=zr(),Ka=Function.prototype.call;rd.exports=My?Ka.bind(Ka):function(){return Ka.apply(Ka,arguments)}});var jo=b(nd=>{"use strict";var sd={}.propertyIsEnumerable,ad=Object.getOwnPropertyDescriptor,Ly=ad&&!sd.call({1:2},1);nd.f=Ly?function(e){var t=ad(this,e);return!!t&&t.enumerable}:sd});var Qr=b((BL,od)=>{"use strict";od.exports=function(s,e){return{enumerable:!(s&1),configurable:!(s&2),writable:!(s&4),value:e}}});var ld=b(($L,ud)=>{"use strict";var By=He(),$y=Qe(),Dy=Oi(),zo=Object,Cy=By("".split);ud.exports=$y(function(){return!zo("z").propertyIsEnumerable(0)})?function(s){return Dy(s)==="String"?Cy(s,""):zo(s)}:zo});var sr=b((DL,cd)=>{"use strict";cd.exports=function(s){return s==null}});var Ii=b((CL,dd)=>{"use strict";var Vy=sr(),Oy=TypeError;dd.exports=function(s){if(Vy(s))throw new Oy("Can't call method on "+s);return s}});var _i=b((VL,pd)=>{"use strict";var _y=ld(),Fy=Ii();pd.exports=function(s){return _y(Fy(s))}});var It=b((OL,hd)=>{"use strict";var Ny=Me();hd.exports=function(s){return typeof s=="object"?s!==null:Ny(s)}});var ar=b((_L,fd)=>{"use strict";fd.exports={}});var oi=b((FL,bd)=>{"use strict";var Qo=ar(),Go=De(),Uy=Me(),md=function(s){return Uy(s)?s:void 0};bd.exports=function(s,e){return arguments.length<2?md(Qo[s])||md(Go[s]):Qo[s]&&Qo[s][e]||Go[s]&&Go[s][e]}});var Gr=b((NL,gd)=>{"use strict";var qy=He();gd.exports=qy({}.isPrototypeOf)});var Fi=b((UL,yd)=>{"use strict";var Hy=De(),Sd=Hy.navigator,vd=Sd&&Sd.userAgent;yd.exports=vd?String(vd):""});var Yo=b((qL,Pd)=>{"use strict";var wd=De(),Wo=Fi(),Td=wd.process,Id=wd.Deno,xd=Td&&Td.versions||Id&&Id.version,Ed=xd&&xd.v8,Ot,Xa;Ed&&(Ot=Ed.split("."),Xa=Ot[0]>0&&Ot[0]<4?1:+(Ot[0]+Ot[1]));!Xa&&Wo&&(Ot=Wo.match(/Edge\/(\d+)/),(!Ot||Ot[1]>=74)&&(Ot=Wo.match(/Chrome\/(\d+)/),Ot&&(Xa=+Ot[1])));Pd.exports=Xa});var Ko=b((HL,kd)=>{"use strict";var Ad=Yo(),jy=Qe(),zy=De(),Qy=zy.String;kd.exports=!!Object.getOwnPropertySymbols&&!jy(function(){var s=Symbol("symbol detection");return!Qy(s)||!(Object(s)instanceof Symbol)||!Symbol.sham&&Ad&&Ad<41})});var Xo=b((jL,Rd)=>{"use strict";var Gy=Ko();Rd.exports=Gy&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var Jo=b((zL,Md)=>{"use strict";var Wy=oi(),Yy=Me(),Ky=Gr(),Xy=Xo(),Jy=Object;Md.exports=Xy?function(s){return typeof s=="symbol"}:function(s){var e=Wy("Symbol");return Yy(e)&&Ky(e.prototype,Jy(s))}});var Wr=b((QL,Ld)=>{"use strict";var Zy=String;Ld.exports=function(s){try{return Zy(s)}catch{return"Object"}}});var zt=b((GL,Bd)=>{"use strict";var eT=Me(),tT=Wr(),iT=TypeError;Bd.exports=function(s){if(eT(s))return s;throw new iT(tT(s)+" is not a function")}});var Yr=b((WL,$d)=>{"use strict";var rT=zt(),sT=sr();$d.exports=function(s,e){var t=s[e];return sT(t)?void 0:rT(t)}});var Cd=b((YL,Dd)=>{"use strict";var Zo=Tt(),eu=Me(),tu=It(),aT=TypeError;Dd.exports=function(s,e){var t,i;if(e==="string"&&eu(t=s.toString)&&!tu(i=Zo(t,s))||eu(t=s.valueOf)&&!tu(i=Zo(t,s))||e!=="string"&&eu(t=s.toString)&&!tu(i=Zo(t,s)))return i;throw new aT("Can't convert object to primitive value")}});var _t=b((KL,Vd)=>{"use strict";Vd.exports=!0});var Fd=b((XL,_d)=>{"use strict";var Od=De(),nT=Object.defineProperty;_d.exports=function(s,e){try{nT(Od,s,{value:e,configurable:!0,writable:!0})}catch{Od[s]=e}return e}});var Kr=b((JL,qd)=>{"use strict";var oT=_t(),uT=De(),lT=Fd(),Nd="__core-js_shared__",Ud=qd.exports=uT[Nd]||lT(Nd,{});(Ud.versions||(Ud.versions=[])).push({version:"3.38.0",mode:oT?"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 iu=b((ZL,jd)=>{"use strict";var Hd=Kr();jd.exports=function(s,e){return Hd[s]||(Hd[s]=e||{})}});var nr=b((eB,zd)=>{"use strict";var cT=Ii(),dT=Object;zd.exports=function(s){return dT(cT(s))}});var Ft=b((tB,Qd)=>{"use strict";var pT=He(),hT=nr(),fT=pT({}.hasOwnProperty);Qd.exports=Object.hasOwn||function(e,t){return fT(hT(e),t)}});var ru=b((iB,Gd)=>{"use strict";var mT=He(),bT=0,gT=Math.random(),ST=mT(1 .toString);Gd.exports=function(s){return"Symbol("+(s===void 0?"":s)+")_"+ST(++bT+gT,36)}});var Ge=b((rB,Yd)=>{"use strict";var vT=De(),yT=iu(),Wd=Ft(),TT=ru(),IT=Ko(),xT=Xo(),or=vT.Symbol,su=yT("wks"),ET=xT?or.for||or:or&&or.withoutSetter||TT;Yd.exports=function(s){return Wd(su,s)||(su[s]=IT&&Wd(or,s)?or[s]:ET("Symbol."+s)),su[s]}});var Zd=b((sB,Jd)=>{"use strict";var wT=Tt(),Kd=It(),Xd=Jo(),PT=Yr(),AT=Cd(),kT=Ge(),RT=TypeError,MT=kT("toPrimitive");Jd.exports=function(s,e){if(!Kd(s)||Xd(s))return s;var t=PT(s,MT),i;if(t){if(e===void 0&&(e="default"),i=wT(t,s,e),!Kd(i)||Xd(i))return i;throw new RT("Can't convert object to primitive value")}return e===void 0&&(e="number"),AT(s,e)}});var au=b((aB,ep)=>{"use strict";var LT=Zd(),BT=Jo();ep.exports=function(s){var e=LT(s,"string");return BT(e)?e:e+""}});var Ja=b((nB,ip)=>{"use strict";var $T=De(),tp=It(),nu=$T.document,DT=tp(nu)&&tp(nu.createElement);ip.exports=function(s){return DT?nu.createElement(s):{}}});var ou=b((oB,rp)=>{"use strict";var CT=yt(),VT=Qe(),OT=Ja();rp.exports=!CT&&!VT(function(){return Object.defineProperty(OT("div"),"a",{get:function(){return 7}}).a!==7})});var np=b(ap=>{"use strict";var _T=yt(),FT=Tt(),NT=jo(),UT=Qr(),qT=_i(),HT=au(),jT=Ft(),zT=ou(),sp=Object.getOwnPropertyDescriptor;ap.f=_T?sp:function(e,t){if(e=qT(e),t=HT(t),zT)try{return sp(e,t)}catch{}if(jT(e,t))return UT(!FT(NT.f,e,t),e[t])}});var uu=b((lB,op)=>{"use strict";var QT=Qe(),GT=Me(),WT=/#|\.prototype\./,Xr=function(s,e){var t=KT[YT(s)];return t===JT?!0:t===XT?!1:GT(e)?QT(e):!!e},YT=Xr.normalize=function(s){return String(s).replace(WT,".").toLowerCase()},KT=Xr.data={},XT=Xr.NATIVE="N",JT=Xr.POLYFILL="P";op.exports=Xr});var ur=b((cB,lp)=>{"use strict";var up=qo(),ZT=zt(),eI=zr(),tI=up(up.bind);lp.exports=function(s,e){return ZT(s),e===void 0?s:eI?tI(s,e):function(){return s.apply(e,arguments)}}});var lu=b((dB,cp)=>{"use strict";var iI=yt(),rI=Qe();cp.exports=iI&&rI(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var Qt=b((pB,dp)=>{"use strict";var sI=It(),aI=String,nI=TypeError;dp.exports=function(s){if(sI(s))return s;throw new nI(aI(s)+" is not an object")}});var Ni=b(hp=>{"use strict";var oI=yt(),uI=ou(),lI=lu(),Za=Qt(),pp=au(),cI=TypeError,cu=Object.defineProperty,dI=Object.getOwnPropertyDescriptor,du="enumerable",pu="configurable",hu="writable";hp.f=oI?lI?function(e,t,i){if(Za(e),t=pp(t),Za(i),typeof e=="function"&&t==="prototype"&&"value"in i&&hu in i&&!i[hu]){var r=dI(e,t);r&&r[hu]&&(e[t]=i.value,i={configurable:pu in i?i[pu]:r[pu],enumerable:du in i?i[du]:r[du],writable:!1})}return cu(e,t,i)}:cu:function(e,t,i){if(Za(e),t=pp(t),Za(i),uI)try{return cu(e,t,i)}catch{}if("get"in i||"set"in i)throw new cI("Accessors not supported");return"value"in i&&(e[t]=i.value),e}});var lr=b((fB,fp)=>{"use strict";var pI=yt(),hI=Ni(),fI=Qr();fp.exports=pI?function(s,e,t){return hI.f(s,e,fI(1,t))}:function(s,e,t){return s[e]=t,s}});var Oe=b((mB,bp)=>{"use strict";var Jr=De(),mI=No(),bI=qo(),gI=Me(),SI=np().f,vI=uu(),cr=ar(),yI=ur(),dr=lr(),mp=Ft();Kr();var TI=function(s){var e=function(t,i,r){if(this instanceof e){switch(arguments.length){case 0:return new s;case 1:return new s(t);case 2:return new s(t,i)}return new s(t,i,r)}return mI(s,this,arguments)};return e.prototype=s.prototype,e};bp.exports=function(s,e){var t=s.target,i=s.global,r=s.stat,a=s.proto,n=i?Jr:r?Jr[t]:Jr[t]&&Jr[t].prototype,o=i?cr:cr[t]||dr(cr,t,{})[t],u=o.prototype,l,p,c,d,h,m,g,v,T;for(d in e)l=vI(i?d:t+(r?".":"#")+d,s.forced),p=!l&&n&&mp(n,d),m=o[d],p&&(s.dontCallGetSet?(T=SI(n,d),g=T&&T.value):g=n[d]),h=p&&g?g:e[d],!(!l&&!a&&typeof m==typeof h)&&(s.bind&&p?v=yI(h,Jr):s.wrap&&p?v=TI(h):a&&gI(h)?v=bI(h):v=h,(s.sham||h&&h.sham||m&&m.sham)&&dr(v,"sham",!0),dr(o,d,v),a&&(c=t+"Prototype",mp(cr,c)||dr(cr,c,{}),dr(cr[c],d,h),s.real&&u&&(l||!u[d])&&dr(u,d,h)))}});var Sp=b((bB,gp)=>{"use strict";var II=Math.ceil,xI=Math.floor;gp.exports=Math.trunc||function(e){var t=+e;return(t>0?xI:II)(t)}});var Zr=b((gB,vp)=>{"use strict";var EI=Sp();vp.exports=function(s){var e=+s;return e!==e||e===0?0:EI(e)}});var Tp=b((SB,yp)=>{"use strict";var wI=Zr(),PI=Math.max,AI=Math.min;yp.exports=function(s,e){var t=wI(s);return t<0?PI(t+e,0):AI(t,e)}});var fu=b((vB,Ip)=>{"use strict";var kI=Zr(),RI=Math.min;Ip.exports=function(s){var e=kI(s);return e>0?RI(e,9007199254740991):0}});var pr=b((yB,xp)=>{"use strict";var MI=fu();xp.exports=function(s){return MI(s.length)}});var mu=b((TB,wp)=>{"use strict";var LI=_i(),BI=Tp(),$I=pr(),Ep=function(s){return function(e,t,i){var r=LI(e),a=$I(r);if(a===0)return!s&&-1;var n=BI(i,a),o;if(s&&t!==t){for(;a>n;)if(o=r[n++],o!==o)return!0}else for(;a>n;n++)if((s||n in r)&&r[n]===t)return s||n||0;return!s&&-1}};wp.exports={includes:Ep(!0),indexOf:Ep(!1)}});var es=b((IB,Pp)=>{"use strict";Pp.exports=function(){}});var Ap=b(()=>{"use strict";var DI=Oe(),CI=mu().includes,VI=Qe(),OI=es(),_I=VI(function(){return!Array(1).includes()});DI({target:"Array",proto:!0,forced:_I},{includes:function(e){return CI(this,e,arguments.length>1?arguments[1]:void 0)}});OI("includes")});var xi=b((wB,kp)=>{"use strict";var FI=oi();kp.exports=FI});var Mp=b((PB,Rp)=>{"use strict";Ap();var NI=xi();Rp.exports=NI("Array","includes")});var Bp=b((AB,Lp)=>{"use strict";var UI=Mp();Lp.exports=UI});var xt=b((kB,$p)=>{"use strict";var qI=Bp();$p.exports=qI});var tn=b((FB,Vp)=>{"use strict";var jI=iu(),zI=ru(),Cp=jI("keys");Vp.exports=function(s){return Cp[s]||(Cp[s]=zI(s))}});var _p=b((NB,Op)=>{"use strict";var QI=Qe();Op.exports=!QI(function(){function s(){}return s.prototype.constructor=null,Object.getPrototypeOf(new s)!==s.prototype})});var rn=b((UB,Np)=>{"use strict";var GI=Ft(),WI=Me(),YI=nr(),KI=tn(),XI=_p(),Fp=KI("IE_PROTO"),bu=Object,JI=bu.prototype;Np.exports=XI?bu.getPrototypeOf:function(s){var e=YI(s);if(GI(e,Fp))return e[Fp];var t=e.constructor;return WI(t)&&e instanceof t?t.prototype:e instanceof bu?JI:null}});var sn=b((qB,Up)=>{"use strict";Up.exports={}});var jp=b((HB,Hp)=>{"use strict";var ZI=He(),gu=Ft(),ex=_i(),tx=mu().indexOf,ix=sn(),qp=ZI([].push);Hp.exports=function(s,e){var t=ex(s),i=0,r=[],a;for(a in t)!gu(ix,a)&&gu(t,a)&&qp(r,a);for(;e.length>i;)gu(t,a=e[i++])&&(~tx(r,a)||qp(r,a));return r}});var Su=b((jB,zp)=>{"use strict";zp.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var vu=b((zB,Qp)=>{"use strict";var rx=jp(),sx=Su();Qp.exports=Object.keys||function(e){return rx(e,sx)}});var yu=b((QB,Xp)=>{"use strict";var Wp=yt(),ax=Qe(),Yp=He(),nx=rn(),ox=vu(),ux=_i(),lx=jo().f,Kp=Yp(lx),cx=Yp([].push),dx=Wp&&ax(function(){var s=Object.create(null);return s[2]=2,!Kp(s,2)}),Gp=function(s){return function(e){for(var t=ux(e),i=ox(t),r=dx&&nx(t)===null,a=i.length,n=0,o=[],u;a>n;)u=i[n++],(!Wp||(r?u in t:Kp(t,u)))&&cx(o,s?[u,t[u]]:t[u]);return o}};Xp.exports={entries:Gp(!0),values:Gp(!1)}});var Jp=b(()=>{"use strict";var px=Oe(),hx=yu().entries;px({target:"Object",stat:!0},{entries:function(e){return hx(e)}})});var eh=b((YB,Zp)=>{"use strict";Jp();var fx=ar();Zp.exports=fx.Object.entries});var ih=b((KB,th)=>{"use strict";var mx=eh();th.exports=mx});var Ui=b((XB,rh)=>{"use strict";var bx=ih();rh.exports=bx});var qi=b((JB,sh)=>{"use strict";sh.exports={}});var oh=b((ZB,nh)=>{"use strict";var gx=De(),Sx=Me(),ah=gx.WeakMap;nh.exports=Sx(ah)&&/native code/.test(String(ah))});var Eu=b((e$,ch)=>{"use strict";var vx=oh(),lh=De(),yx=It(),Tx=lr(),Tu=Ft(),Iu=Kr(),Ix=tn(),xx=sn(),uh="Object already initialized",xu=lh.TypeError,Ex=lh.WeakMap,an,ts,nn,wx=function(s){return nn(s)?ts(s):an(s,{})},Px=function(s){return function(e){var t;if(!yx(e)||(t=ts(e)).type!==s)throw new xu("Incompatible receiver, "+s+" required");return t}};vx||Iu.state?(Nt=Iu.state||(Iu.state=new Ex),Nt.get=Nt.get,Nt.has=Nt.has,Nt.set=Nt.set,an=function(s,e){if(Nt.has(s))throw new xu(uh);return e.facade=s,Nt.set(s,e),e},ts=function(s){return Nt.get(s)||{}},nn=function(s){return Nt.has(s)}):(Hi=Ix("state"),xx[Hi]=!0,an=function(s,e){if(Tu(s,Hi))throw new xu(uh);return e.facade=s,Tx(s,Hi,e),e},ts=function(s){return Tu(s,Hi)?s[Hi]:{}},nn=function(s){return Tu(s,Hi)});var Nt,Hi;ch.exports={set:an,get:ts,has:nn,enforce:wx,getterFor:Px}});var Au=b((t$,ph)=>{"use strict";var wu=yt(),Ax=Ft(),dh=Function.prototype,kx=wu&&Object.getOwnPropertyDescriptor,Pu=Ax(dh,"name"),Rx=Pu&&function(){}.name==="something",Mx=Pu&&(!wu||wu&&kx(dh,"name").configurable);ph.exports={EXISTS:Pu,PROPER:Rx,CONFIGURABLE:Mx}});var fh=b(hh=>{"use strict";var Lx=yt(),Bx=lu(),$x=Ni(),Dx=Qt(),Cx=_i(),Vx=vu();hh.f=Lx&&!Bx?Object.defineProperties:function(e,t){Dx(e);for(var i=Cx(t),r=Vx(t),a=r.length,n=0,o;a>n;)$x.f(e,o=r[n++],i[o]);return e}});var ku=b((r$,mh)=>{"use strict";var Ox=oi();mh.exports=Ox("document","documentElement")});var Bu=b((s$,Ih)=>{"use strict";var _x=Qt(),Fx=fh(),bh=Su(),Nx=sn(),Ux=ku(),qx=Ja(),Hx=tn(),gh=">",Sh="<",Mu="prototype",Lu="script",yh=Hx("IE_PROTO"),Ru=function(){},Th=function(s){return Sh+Lu+gh+s+Sh+"/"+Lu+gh},vh=function(s){s.write(Th("")),s.close();var e=s.parentWindow.Object;return s=null,e},jx=function(){var s=qx("iframe"),e="java"+Lu+":",t;return s.style.display="none",Ux.appendChild(s),s.src=String(e),t=s.contentWindow.document,t.open(),t.write(Th("document.F=Object")),t.close(),t.F},on,un=function(){try{on=new ActiveXObject("htmlfile")}catch{}un=typeof document<"u"?document.domain&&on?vh(on):jx():vh(on);for(var s=bh.length;s--;)delete un[Mu][bh[s]];return un()};Nx[yh]=!0;Ih.exports=Object.create||function(e,t){var i;return e!==null?(Ru[Mu]=_x(e),i=new Ru,Ru[Mu]=null,i[yh]=e):i=un(),t===void 0?i:Fx.f(i,t)}});var hr=b((a$,xh)=>{"use strict";var zx=lr();xh.exports=function(s,e,t,i){return i&&i.enumerable?s[e]=t:zx(s,e,t),s}});var Vu=b((n$,Ph)=>{"use strict";var Qx=Qe(),Gx=Me(),Wx=It(),Yx=Bu(),Eh=rn(),Kx=hr(),Xx=Ge(),Jx=_t(),Cu=Xx("iterator"),wh=!1,ui,$u,Du;[].keys&&(Du=[].keys(),"next"in Du?($u=Eh(Eh(Du)),$u!==Object.prototype&&(ui=$u)):wh=!0);var Zx=!Wx(ui)||Qx(function(){var s={};return ui[Cu].call(s)!==s});Zx?ui={}:Jx&&(ui=Yx(ui));Gx(ui[Cu])||Kx(ui,Cu,function(){return this});Ph.exports={IteratorPrototype:ui,BUGGY_SAFARI_ITERATORS:wh}});var ln=b((o$,kh)=>{"use strict";var eE=Ge(),tE=eE("toStringTag"),Ah={};Ah[tE]="z";kh.exports=String(Ah)==="[object z]"});var is=b((u$,Rh)=>{"use strict";var iE=ln(),rE=Me(),cn=Oi(),sE=Ge(),aE=sE("toStringTag"),nE=Object,oE=cn(function(){return arguments}())==="Arguments",uE=function(s,e){try{return s[e]}catch{}};Rh.exports=iE?cn:function(s){var e,t,i;return s===void 0?"Undefined":s===null?"Null":typeof(t=uE(e=nE(s),aE))=="string"?t:oE?cn(e):(i=cn(e))==="Object"&&rE(e.callee)?"Arguments":i}});var Lh=b((l$,Mh)=>{"use strict";var lE=ln(),cE=is();Mh.exports=lE?{}.toString:function(){return"[object "+cE(this)+"]"}});var rs=b((c$,$h)=>{"use strict";var dE=ln(),pE=Ni().f,hE=lr(),fE=Ft(),mE=Lh(),bE=Ge(),Bh=bE("toStringTag");$h.exports=function(s,e,t,i){var r=t?s:s&&s.prototype;r&&(fE(r,Bh)||pE(r,Bh,{configurable:!0,value:e}),i&&!dE&&hE(r,"toString",mE))}});var Ch=b((d$,Dh)=>{"use strict";var gE=Vu().IteratorPrototype,SE=Bu(),vE=Qr(),yE=rs(),TE=qi(),IE=function(){return this};Dh.exports=function(s,e,t,i){var r=e+" Iterator";return s.prototype=SE(gE,{next:vE(+!i,t)}),yE(s,r,!1,!0),TE[r]=IE,s}});var Oh=b((p$,Vh)=>{"use strict";var xE=He(),EE=zt();Vh.exports=function(s,e,t){try{return xE(EE(Object.getOwnPropertyDescriptor(s,e)[t]))}catch{}}});var Fh=b((h$,_h)=>{"use strict";var wE=It();_h.exports=function(s){return wE(s)||s===null}});var Uh=b((f$,Nh)=>{"use strict";var PE=Fh(),AE=String,kE=TypeError;Nh.exports=function(s){if(PE(s))return s;throw new kE("Can't set "+AE(s)+" as a prototype")}});var Ou=b((m$,qh)=>{"use strict";var RE=Oh(),ME=It(),LE=Ii(),BE=Uh();qh.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var s=!1,e={},t;try{t=RE(Object.prototype,"__proto__","set"),t(e,[]),s=e instanceof Array}catch{}return function(r,a){return LE(r),BE(a),ME(r)&&(s?t(r,a):r.__proto__=a),r}}():void 0)});var Zh=b((b$,Jh)=>{"use strict";var $E=Oe(),DE=Tt(),dn=_t(),Kh=Au(),CE=Me(),VE=Ch(),Hh=rn(),jh=Ou(),OE=rs(),_E=lr(),_u=hr(),FE=Ge(),zh=qi(),Xh=Vu(),NE=Kh.PROPER,UE=Kh.CONFIGURABLE,Qh=Xh.IteratorPrototype,pn=Xh.BUGGY_SAFARI_ITERATORS,ss=FE("iterator"),Gh="keys",as="values",Wh="entries",Yh=function(){return this};Jh.exports=function(s,e,t,i,r,a,n){VE(t,e,i);var o=function(T){if(T===r&&d)return d;if(!pn&&T&&T in p)return p[T];switch(T){case Gh:return function(){return new t(this,T)};case as:return function(){return new t(this,T)};case Wh:return function(){return new t(this,T)}}return function(){return new t(this)}},u=e+" Iterator",l=!1,p=s.prototype,c=p[ss]||p["@@iterator"]||r&&p[r],d=!pn&&c||o(r),h=e==="Array"&&p.entries||c,m,g,v;if(h&&(m=Hh(h.call(new s)),m!==Object.prototype&&m.next&&(!dn&&Hh(m)!==Qh&&(jh?jh(m,Qh):CE(m[ss])||_u(m,ss,Yh)),OE(m,u,!0,!0),dn&&(zh[u]=Yh))),NE&&r===as&&c&&c.name!==as&&(!dn&&UE?_E(p,"name",as):(l=!0,d=function(){return DE(c,this)})),r)if(g={values:o(as),keys:a?d:o(Gh),entries:o(Wh)},n)for(v in g)(pn||l||!(v in p))&&_u(p,v,g[v]);else $E({target:e,proto:!0,forced:pn||l},g);return(!dn||n)&&p[ss]!==d&&_u(p,ss,d,{name:r}),zh[e]=d,g}});var tf=b((g$,ef)=>{"use strict";ef.exports=function(s,e){return{value:s,done:e}}});var Nu=b((S$,of)=>{"use strict";var qE=_i(),Fu=es(),rf=qi(),af=Eu(),HE=Ni().f,jE=Zh(),hn=tf(),zE=_t(),QE=yt(),nf="Array Iterator",GE=af.set,WE=af.getterFor(nf);of.exports=jE(Array,"Array",function(s,e){GE(this,{type:nf,target:qE(s),index:0,kind:e})},function(){var s=WE(this),e=s.target,t=s.index++;if(!e||t>=e.length)return s.target=void 0,hn(void 0,!0);switch(s.kind){case"keys":return hn(t,!1);case"values":return hn(e[t],!1)}return hn([t,e[t]],!1)},"values");var sf=rf.Arguments=rf.Array;Fu("keys");Fu("values");Fu("entries");if(!zE&&QE&&sf.name!=="values")try{HE(sf,"name",{value:"values"})}catch{}});var lf=b((v$,uf)=>{"use strict";var YE=Ge(),KE=qi(),XE=YE("iterator"),JE=Array.prototype;uf.exports=function(s){return s!==void 0&&(KE.Array===s||JE[XE]===s)}});var Uu=b((y$,df)=>{"use strict";var ZE=is(),cf=Yr(),ew=sr(),tw=qi(),iw=Ge(),rw=iw("iterator");df.exports=function(s){if(!ew(s))return cf(s,rw)||cf(s,"@@iterator")||tw[ZE(s)]}});var hf=b((T$,pf)=>{"use strict";var sw=Tt(),aw=zt(),nw=Qt(),ow=Wr(),uw=Uu(),lw=TypeError;pf.exports=function(s,e){var t=arguments.length<2?uw(s):e;if(aw(t))return nw(sw(t,s));throw new lw(ow(s)+" is not iterable")}});var bf=b((I$,mf)=>{"use strict";var cw=Tt(),ff=Qt(),dw=Yr();mf.exports=function(s,e,t){var i,r;ff(s);try{if(i=dw(s,"return"),!i){if(e==="throw")throw t;return t}i=cw(i,s)}catch(a){r=!0,i=a}if(e==="throw")throw t;if(r)throw i;return ff(i),t}});var mn=b((x$,yf)=>{"use strict";var pw=ur(),hw=Tt(),fw=Qt(),mw=Wr(),bw=lf(),gw=pr(),gf=Gr(),Sw=hf(),vw=Uu(),Sf=bf(),yw=TypeError,fn=function(s,e){this.stopped=s,this.result=e},vf=fn.prototype;yf.exports=function(s,e,t){var i=t&&t.that,r=!!(t&&t.AS_ENTRIES),a=!!(t&&t.IS_RECORD),n=!!(t&&t.IS_ITERATOR),o=!!(t&&t.INTERRUPTED),u=pw(e,i),l,p,c,d,h,m,g,v=function(P){return l&&Sf(l,"normal",P),new fn(!0,P)},T=function(P){return r?(fw(P),o?u(P[0],P[1],v):u(P[0],P[1])):o?u(P,v):u(P)};if(a)l=s.iterator;else if(n)l=s;else{if(p=vw(s),!p)throw new yw(mw(s)+" is not iterable");if(bw(p)){for(c=0,d=gw(s);d>c;c++)if(h=T(s[c]),h&&gf(vf,h))return h;return new fn(!1)}l=Sw(s,p)}for(m=a?s.next:l.next;!(g=hw(m,l)).done;){try{h=T(g.value)}catch(P){Sf(l,"throw",P)}if(typeof h=="object"&&h&&gf(vf,h))return h}return new fn(!1)}});var If=b((E$,Tf)=>{"use strict";var Tw=yt(),Iw=Ni(),xw=Qr();Tf.exports=function(s,e,t){Tw?Iw.f(s,e,xw(0,t)):s[e]=t}});var xf=b(()=>{"use strict";var Ew=Oe(),ww=mn(),Pw=If();Ew({target:"Object",stat:!0},{fromEntries:function(e){var t={};return ww(e,function(i,r){Pw(t,i,r)},{AS_ENTRIES:!0}),t}})});var wf=b((A$,Ef)=>{"use strict";Nu();xf();var Aw=ar();Ef.exports=Aw.Object.fromEntries});var Af=b((k$,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 Rf=b(()=>{"use strict";Nu();var kw=Af(),Rw=De(),Mw=rs(),kf=qi();for(bn in kw)Mw(Rw[bn],bn),kf[bn]=kf.Array;var bn});var Lf=b((L$,Mf)=>{"use strict";var Lw=wf();Rf();Mf.exports=Lw});var qu=b((B$,Bf)=>{"use strict";var Bw=Lf();Bf.exports=Bw});var $f=b(()=>{"use strict"});var Hu=b((C$,Df)=>{"use strict";var ns=De(),$w=Fi(),Dw=Oi(),gn=function(s){return $w.slice(0,s.length)===s};Df.exports=function(){return gn("Bun/")?"BUN":gn("Cloudflare-Workers")?"CLOUDFLARE":gn("Deno/")?"DENO":gn("Node.js/")?"NODE":ns.Bun&&typeof Bun.version=="string"?"BUN":ns.Deno&&typeof Deno.version=="object"?"DENO":Dw(ns.process)==="process"?"NODE":ns.window&&ns.document?"BROWSER":"REST"}()});var Sn=b((V$,Cf)=>{"use strict";var Cw=Hu();Cf.exports=Cw==="NODE"});var Of=b((O$,Vf)=>{"use strict";var Vw=Ni();Vf.exports=function(s,e,t){return Vw.f(s,e,t)}});var Nf=b((_$,Ff)=>{"use strict";var Ow=oi(),_w=Of(),Fw=Ge(),Nw=yt(),_f=Fw("species");Ff.exports=function(s){var e=Ow(s);Nw&&e&&!e[_f]&&_w(e,_f,{configurable:!0,get:function(){return this}})}});var qf=b((F$,Uf)=>{"use strict";var Uw=Gr(),qw=TypeError;Uf.exports=function(s,e){if(Uw(e,s))return s;throw new qw("Incorrect invocation")}});var zu=b((N$,Hf)=>{"use strict";var Hw=He(),jw=Me(),ju=Kr(),zw=Hw(Function.toString);jw(ju.inspectSource)||(ju.inspectSource=function(s){return zw(s)});Hf.exports=ju.inspectSource});var Gu=b((U$,Wf)=>{"use strict";var Qw=He(),Gw=Qe(),jf=Me(),Ww=is(),Yw=oi(),Kw=zu(),zf=function(){},Qf=Yw("Reflect","construct"),Qu=/^\s*(?:class|function)\b/,Xw=Qw(Qu.exec),Jw=!Qu.test(zf),os=function(e){if(!jf(e))return!1;try{return Qf(zf,[],e),!0}catch{return!1}},Gf=function(e){if(!jf(e))return!1;switch(Ww(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return Jw||!!Xw(Qu,Kw(e))}catch{return!0}};Gf.sham=!0;Wf.exports=!Qf||Gw(function(){var s;return os(os.call)||!os(Object)||!os(function(){s=!0})||s})?Gf:os});var Kf=b((q$,Yf)=>{"use strict";var Zw=Gu(),eP=Wr(),tP=TypeError;Yf.exports=function(s){if(Zw(s))return s;throw new tP(eP(s)+" is not a constructor")}});var Wu=b((H$,Jf)=>{"use strict";var Xf=Qt(),iP=Kf(),rP=sr(),sP=Ge(),aP=sP("species");Jf.exports=function(s,e){var t=Xf(s).constructor,i;return t===void 0||rP(i=Xf(t)[aP])?e:iP(i)}});var em=b((j$,Zf)=>{"use strict";var nP=He();Zf.exports=nP([].slice)});var im=b((z$,tm)=>{"use strict";var oP=TypeError;tm.exports=function(s,e){if(s<e)throw new oP("Not enough arguments");return s}});var Yu=b((Q$,rm)=>{"use strict";var uP=Fi();rm.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(uP)});var sl=b((G$,pm)=>{"use strict";var Et=De(),lP=No(),cP=ur(),sm=Me(),dP=Ft(),dm=Qe(),am=ku(),pP=em(),nm=Ja(),hP=im(),fP=Yu(),mP=Sn(),tl=Et.setImmediate,il=Et.clearImmediate,bP=Et.process,Ku=Et.Dispatch,gP=Et.Function,om=Et.MessageChannel,SP=Et.String,Xu=0,us={},um="onreadystatechange",ls,ji,Ju,Zu;dm(function(){ls=Et.location});var rl=function(s){if(dP(us,s)){var e=us[s];delete us[s],e()}},el=function(s){return function(){rl(s)}},lm=function(s){rl(s.data)},cm=function(s){Et.postMessage(SP(s),ls.protocol+"//"+ls.host)};(!tl||!il)&&(tl=function(e){hP(arguments.length,1);var t=sm(e)?e:gP(e),i=pP(arguments,1);return us[++Xu]=function(){lP(t,void 0,i)},ji(Xu),Xu},il=function(e){delete us[e]},mP?ji=function(s){bP.nextTick(el(s))}:Ku&&Ku.now?ji=function(s){Ku.now(el(s))}:om&&!fP?(Ju=new om,Zu=Ju.port2,Ju.port1.onmessage=lm,ji=cP(Zu.postMessage,Zu)):Et.addEventListener&&sm(Et.postMessage)&&!Et.importScripts&&ls&&ls.protocol!=="file:"&&!dm(cm)?(ji=cm,Et.addEventListener("message",lm,!1)):um in nm("script")?ji=function(s){am.appendChild(nm("script"))[um]=function(){am.removeChild(this),rl(s)}}:ji=function(s){setTimeout(el(s),0)});pm.exports={set:tl,clear:il}});var mm=b((W$,fm)=>{"use strict";var hm=De(),vP=yt(),yP=Object.getOwnPropertyDescriptor;fm.exports=function(s){if(!vP)return hm[s];var e=yP(hm,s);return e&&e.value}});var al=b((Y$,gm)=>{"use strict";var bm=function(){this.head=null,this.tail=null};bm.prototype={add:function(s){var e={item:s,next:null},t=this.tail;t?t.next=e:this.head=e,this.tail=e},get:function(){var s=this.head;if(s){var e=this.head=s.next;return e===null&&(this.tail=null),s.item}}};gm.exports=bm});var vm=b((K$,Sm)=>{"use strict";var TP=Fi();Sm.exports=/ipad|iphone|ipod/i.test(TP)&&typeof Pebble<"u"});var Tm=b((X$,ym)=>{"use strict";var IP=Fi();ym.exports=/web0s(?!.*chrome)/i.test(IP)});var km=b((J$,Am)=>{"use strict";var mr=De(),xP=mm(),Im=ur(),nl=sl().set,EP=al(),wP=Yu(),PP=vm(),AP=Tm(),ol=Sn(),xm=mr.MutationObserver||mr.WebKitMutationObserver,Em=mr.document,wm=mr.process,vn=mr.Promise,cl=xP("queueMicrotask"),fr,ul,ll,yn,Pm;cl||(cs=new EP,ds=function(){var s,e;for(ol&&(s=wm.domain)&&s.exit();e=cs.get();)try{e()}catch(t){throw cs.head&&fr(),t}s&&s.enter()},!wP&&!ol&&!AP&&xm&&Em?(ul=!0,ll=Em.createTextNode(""),new xm(ds).observe(ll,{characterData:!0}),fr=function(){ll.data=ul=!ul}):!PP&&vn&&vn.resolve?(yn=vn.resolve(void 0),yn.constructor=vn,Pm=Im(yn.then,yn),fr=function(){Pm(ds)}):ol?fr=function(){wm.nextTick(ds)}:(nl=Im(nl,mr),fr=function(){nl(ds)}),cl=function(s){cs.head||fr(),cs.add(s)});var cs,ds;Am.exports=cl});var Mm=b((Z$,Rm)=>{"use strict";Rm.exports=function(s,e){try{arguments.length===1?console.error(s):console.error(s,e)}catch{}}});var Tn=b((eD,Lm)=>{"use strict";Lm.exports=function(s){try{return{error:!1,value:s()}}catch(e){return{error:!0,value:e}}}});var zi=b((tD,Bm)=>{"use strict";var kP=De();Bm.exports=kP.Promise});var br=b((iD,Vm)=>{"use strict";var RP=De(),ps=zi(),MP=Me(),LP=uu(),BP=zu(),$P=Ge(),$m=Hu(),DP=_t(),dl=Yo(),Dm=ps&&ps.prototype,CP=$P("species"),pl=!1,Cm=MP(RP.PromiseRejectionEvent),VP=LP("Promise",function(){var s=BP(ps),e=s!==String(ps);if(!e&&dl===66||DP&&!(Dm.catch&&Dm.finally))return!0;if(!dl||dl<51||!/native code/.test(s)){var t=new ps(function(a){a(1)}),i=function(a){a(function(){},function(){})},r=t.constructor={};if(r[CP]=i,pl=t.then(function(){})instanceof i,!pl)return!0}return!e&&($m==="BROWSER"||$m==="DENO")&&!Cm});Vm.exports={CONSTRUCTOR:VP,REJECTION_EVENT:Cm,SUBCLASSING:pl}});var gr=b((rD,_m)=>{"use strict";var Om=zt(),OP=TypeError,_P=function(s){var e,t;this.promise=new s(function(i,r){if(e!==void 0||t!==void 0)throw new OP("Bad Promise constructor");e=i,t=r}),this.resolve=Om(e),this.reject=Om(t)};_m.exports.f=function(s){return new _P(s)}});var rb=b(()=>{"use strict";var FP=Oe(),NP=_t(),wn=Sn(),Ei=De(),Tr=Tt(),Fm=hr(),Nm=Ou(),UP=rs(),qP=Nf(),HP=zt(),En=Me(),jP=It(),zP=qf(),QP=Wu(),zm=sl().set,gl=km(),GP=Mm(),WP=Tn(),YP=al(),Qm=Eu(),Pn=zi(),Sl=br(),Gm=gr(),An="Promise",Wm=Sl.CONSTRUCTOR,KP=Sl.REJECTION_EVENT,XP=Sl.SUBCLASSING,hl=Qm.getterFor(An),JP=Qm.set,Sr=Pn&&Pn.prototype,Qi=Pn,In=Sr,Ym=Ei.TypeError,fl=Ei.document,vl=Ei.process,ml=Gm.f,ZP=ml,eA=!!(fl&&fl.createEvent&&Ei.dispatchEvent),Km="unhandledrejection",tA="rejectionhandled",Um=0,Xm=1,iA=2,yl=1,Jm=2,xn,qm,rA,Hm,Zm=function(s){var e;return jP(s)&&En(e=s.then)?e:!1},eb=function(s,e){var t=e.value,i=e.state===Xm,r=i?s.ok:s.fail,a=s.resolve,n=s.reject,o=s.domain,u,l,p;try{r?(i||(e.rejection===Jm&&aA(e),e.rejection=yl),r===!0?u=t:(o&&o.enter(),u=r(t),o&&(o.exit(),p=!0)),u===s.promise?n(new Ym("Promise-chain cycle")):(l=Zm(u))?Tr(l,u,a,n):a(u)):n(t)}catch(c){o&&!p&&o.exit(),n(c)}},tb=function(s,e){s.notified||(s.notified=!0,gl(function(){for(var t=s.reactions,i;i=t.get();)eb(i,s);s.notified=!1,e&&!s.rejection&&sA(s)}))},ib=function(s,e,t){var i,r;eA?(i=fl.createEvent("Event"),i.promise=e,i.reason=t,i.initEvent(s,!1,!0),Ei.dispatchEvent(i)):i={promise:e,reason:t},!KP&&(r=Ei["on"+s])?r(i):s===Km&&GP("Unhandled promise rejection",t)},sA=function(s){Tr(zm,Ei,function(){var e=s.facade,t=s.value,i=jm(s),r;if(i&&(r=WP(function(){wn?vl.emit("unhandledRejection",t,e):ib(Km,e,t)}),s.rejection=wn||jm(s)?Jm:yl,r.error))throw r.value})},jm=function(s){return s.rejection!==yl&&!s.parent},aA=function(s){Tr(zm,Ei,function(){var e=s.facade;wn?vl.emit("rejectionHandled",e):ib(tA,e,s.value)})},vr=function(s,e,t){return function(i){s(e,i,t)}},yr=function(s,e,t){s.done||(s.done=!0,t&&(s=t),s.value=e,s.state=iA,tb(s,!0))},bl=function(s,e,t){if(!s.done){s.done=!0,t&&(s=t);try{if(s.facade===e)throw new Ym("Promise can't be resolved itself");var i=Zm(e);i?gl(function(){var r={done:!1};try{Tr(i,e,vr(bl,r,s),vr(yr,r,s))}catch(a){yr(r,a,s)}}):(s.value=e,s.state=Xm,tb(s,!1))}catch(r){yr({done:!1},r,s)}}};if(Wm&&(Qi=function(e){zP(this,In),HP(e),Tr(xn,this);var t=hl(this);try{e(vr(bl,t),vr(yr,t))}catch(i){yr(t,i)}},In=Qi.prototype,xn=function(e){JP(this,{type:An,done:!1,notified:!1,parent:!1,reactions:new YP,rejection:!1,state:Um,value:void 0})},xn.prototype=Fm(In,"then",function(e,t){var i=hl(this),r=ml(QP(this,Qi));return i.parent=!0,r.ok=En(e)?e:!0,r.fail=En(t)&&t,r.domain=wn?vl.domain:void 0,i.state===Um?i.reactions.add(r):gl(function(){eb(r,i)}),r.promise}),qm=function(){var s=new xn,e=hl(s);this.promise=s,this.resolve=vr(bl,e),this.reject=vr(yr,e)},Gm.f=ml=function(s){return s===Qi||s===rA?new qm(s):ZP(s)},!NP&&En(Pn)&&Sr!==Object.prototype)){Hm=Sr.then,XP||Fm(Sr,"then",function(e,t){var i=this;return new Qi(function(r,a){Tr(Hm,i,r,a)}).then(e,t)},{unsafe:!0});try{delete Sr.constructor}catch{}Nm&&Nm(Sr,In)}FP({global:!0,constructor:!0,wrap:!0,forced:Wm},{Promise:Qi});UP(Qi,An,!1,!0);qP(An)});var ub=b((nD,ob)=>{"use strict";var nA=Ge(),ab=nA("iterator"),nb=!1;try{sb=0,Tl={next:function(){return{done:!!sb++}},return:function(){nb=!0}},Tl[ab]=function(){return this},Array.from(Tl,function(){throw 2})}catch{}var sb,Tl;ob.exports=function(s,e){try{if(!e&&!nb)return!1}catch{return!1}var t=!1;try{var i={};i[ab]=function(){return{next:function(){return{done:t=!0}}}},s(i)}catch{}return t}});var Il=b((oD,lb)=>{"use strict";var oA=zi(),uA=ub(),lA=br().CONSTRUCTOR;lb.exports=lA||!uA(function(s){oA.all(s).then(void 0,function(){})})});var cb=b(()=>{"use strict";var cA=Oe(),dA=Tt(),pA=zt(),hA=gr(),fA=Tn(),mA=mn(),bA=Il();cA({target:"Promise",stat:!0,forced:bA},{all:function(e){var t=this,i=hA.f(t),r=i.resolve,a=i.reject,n=fA(function(){var o=pA(t.resolve),u=[],l=0,p=1;mA(e,function(c){var d=l++,h=!1;p++,dA(o,t,c).then(function(m){h||(h=!0,u[d]=m,--p||r(u))},a)}),--p||r(u)});return n.error&&a(n.value),i.promise}})});var pb=b(()=>{"use strict";var gA=Oe(),SA=_t(),vA=br().CONSTRUCTOR,El=zi(),yA=oi(),TA=Me(),IA=hr(),db=El&&El.prototype;gA({target:"Promise",proto:!0,forced:vA,real:!0},{catch:function(s){return this.then(void 0,s)}});!SA&&TA(El)&&(xl=yA("Promise").prototype.catch,db.catch!==xl&&IA(db,"catch",xl,{unsafe:!0}));var xl});var hb=b(()=>{"use strict";var xA=Oe(),EA=Tt(),wA=zt(),PA=gr(),AA=Tn(),kA=mn(),RA=Il();xA({target:"Promise",stat:!0,forced:RA},{race:function(e){var t=this,i=PA.f(t),r=i.reject,a=AA(function(){var n=wA(t.resolve);kA(e,function(o){EA(n,t,o).then(i.resolve,r)})});return a.error&&r(a.value),i.promise}})});var fb=b(()=>{"use strict";var MA=Oe(),LA=gr(),BA=br().CONSTRUCTOR;MA({target:"Promise",stat:!0,forced:BA},{reject:function(e){var t=LA.f(this),i=t.reject;return i(e),t.promise}})});var wl=b((bD,mb)=>{"use strict";var $A=Qt(),DA=It(),CA=gr();mb.exports=function(s,e){if($A(s),DA(e)&&e.constructor===s)return e;var t=CA.f(s),i=t.resolve;return i(e),t.promise}});var Sb=b(()=>{"use strict";var VA=Oe(),OA=oi(),bb=_t(),_A=zi(),gb=br().CONSTRUCTOR,FA=wl(),NA=OA("Promise"),UA=bb&&!gb;VA({target:"Promise",stat:!0,forced:bb||gb},{resolve:function(e){return FA(UA&&this===NA?_A:this,e)}})});var vb=b(()=>{"use strict";rb();cb();pb();hb();fb();Sb()});var xb=b(()=>{"use strict";var qA=Oe(),HA=_t(),kn=zi(),jA=Qe(),Tb=oi(),Ib=Me(),zA=Wu(),yb=wl(),QA=hr(),Al=kn&&kn.prototype,GA=!!kn&&jA(function(){Al.finally.call({then:function(){}},function(){})});qA({target:"Promise",proto:!0,real:!0,forced:GA},{finally:function(s){var e=zA(this,Tb("Promise")),t=Ib(s);return this.then(t?function(i){return yb(e,s()).then(function(){return i})}:s,t?function(i){return yb(e,s()).then(function(){throw i})}:s)}});!HA&&Ib(kn)&&(Pl=Tb("Promise").prototype.finally,Al.finally!==Pl&&QA(Al,"finally",Pl,{unsafe:!0}));var Pl});var wb=b((xD,Eb)=>{"use strict";$f();vb();xb();var WA=xi();Eb.exports=WA("Promise","finally")});var Ab=b((ED,Pb)=>{"use strict";var YA=wb();Pb.exports=YA});var Rn=b((wD,kb)=>{"use strict";var KA=Ab();kb.exports=KA});var Cb=b(()=>{"use strict";var tk=Oe(),ik=yu().values;tk({target:"Object",stat:!0},{values:function(e){return ik(e)}})});var Ob=b((i0,Vb)=>{"use strict";Cb();var rk=ar();Vb.exports=rk.Object.values});var Fb=b((r0,_b)=>{"use strict";var sk=Ob();_b.exports=sk});var Gi=b((s0,Nb)=>{"use strict";var ak=Fb();Nb.exports=ak});var Xb=b(()=>{"use strict";var mk=Oe(),bk=nr(),gk=pr(),Sk=Zr(),vk=es();mk({target:"Array",proto:!0},{at:function(e){var t=bk(this),i=gk(t),r=Sk(e),a=r>=0?r:i+r;return a<0||a>=i?void 0:t[a]}});vk("at")});var Zb=b((uC,Jb)=>{"use strict";Xb();var yk=xi();Jb.exports=yk("Array","at")});var tg=b((lC,eg)=>{"use strict";var Tk=Zb();eg.exports=Tk});var Ut=b((cC,ig)=>{"use strict";var Ik=tg();ig.exports=Ik});var Ql=b((FV,Eg)=>{"use strict";var $k=Oi();Eg.exports=Array.isArray||function(e){return $k(e)==="Array"}});var Pg=b((NV,wg)=>{"use strict";var Dk=TypeError,Ck=9007199254740991;wg.exports=function(s){if(s>Ck)throw Dk("Maximum allowed index exceeded");return s}});var Rg=b((UV,kg)=>{"use strict";var Vk=Ql(),Ok=pr(),_k=Pg(),Fk=ur(),Ag=function(s,e,t,i,r,a,n,o){for(var u=r,l=0,p=n?Fk(n,o):!1,c,d;l<i;)l in t&&(c=p?p(t[l],l,e):t[l],a>0&&Vk(c)?(d=Ok(c),u=Ag(s,e,c,d,u,a-1)-1):(_k(u+1),s[u]=c),u++),l++;return u};kg.exports=Ag});var $g=b((qV,Bg)=>{"use strict";var Mg=Ql(),Nk=Gu(),Uk=It(),qk=Ge(),Hk=qk("species"),Lg=Array;Bg.exports=function(s){var e;return Mg(s)&&(e=s.constructor,Nk(e)&&(e===Lg||Mg(e.prototype))?e=void 0:Uk(e)&&(e=e[Hk],e===null&&(e=void 0))),e===void 0?Lg:e}});var Cg=b((HV,Dg)=>{"use strict";var jk=$g();Dg.exports=function(s,e){return new(jk(s))(e===0?0:e)}});var Vg=b(()=>{"use strict";var zk=Oe(),Qk=Rg(),Gk=zt(),Wk=nr(),Yk=pr(),Kk=Cg();zk({target:"Array",proto:!0},{flatMap:function(e){var t=Wk(this),i=Yk(t),r;return Gk(e),r=Kk(t,0),r.length=Qk(r,t,t,i,0,1,e,arguments.length>1?arguments[1]:void 0),r}})});var Og=b(()=>{"use strict";var Xk=es();Xk("flatMap")});var Fg=b((WV,_g)=>{"use strict";Vg();Og();var Jk=xi();_g.exports=Jk("Array","flatMap")});var Ug=b((YV,Ng)=>{"use strict";var Zk=Fg();Ng.exports=Zk});var ws=b((KV,qg)=>{"use strict";var eR=Ug();qg.exports=eR});var Ps=b((XV,Hg)=>{"use strict";var tR=is(),iR=String;Hg.exports=function(s){if(tR(s)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return iR(s)}});var Gl=b((JV,jg)=>{"use strict";jg.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 Gg=b((ZV,Qg)=>{"use strict";var rR=He(),sR=Ii(),aR=Ps(),Yl=Gl(),zg=rR("".replace),nR=RegExp("^["+Yl+"]+"),oR=RegExp("(^|[^"+Yl+"])["+Yl+"]+$"),Wl=function(s){return function(e){var t=aR(sR(e));return s&1&&(t=zg(t,nR,"")),s&2&&(t=zg(t,oR,"$1")),t}};Qg.exports={start:Wl(1),end:Wl(2),trim:Wl(3)}});var Xg=b((eO,Kg)=>{"use strict";var uR=Au().PROPER,lR=Qe(),Wg=Gl(),Yg="\u200B\x85\u180E";Kg.exports=function(s){return lR(function(){return!!Wg[s]()||Yg[s]()!==Yg||uR&&Wg[s].name!==s})}});var Kl=b((tO,Jg)=>{"use strict";var cR=Gg().start,dR=Xg();Jg.exports=dR("trimStart")?function(){return cR(this)}:"".trimStart});var eS=b(()=>{"use strict";var pR=Oe(),Zg=Kl();pR({target:"String",proto:!0,name:"trimStart",forced:"".trimLeft!==Zg},{trimLeft:Zg})});var iS=b(()=>{"use strict";eS();var hR=Oe(),tS=Kl();hR({target:"String",proto:!0,name:"trimStart",forced:"".trimStart!==tS},{trimStart:tS})});var sS=b((nO,rS)=>{"use strict";iS();var fR=xi();rS.exports=fR("String","trimLeft")});var nS=b((oO,aS)=>{"use strict";var mR=sS();aS.exports=mR});var uS=b((uO,oS)=>{"use strict";var bR=nS();oS.exports=bR});var TS=b(()=>{"use strict"});var IS=b(()=>{"use strict"});var ES=b((_F,xS)=>{"use strict";var VR=It(),OR=Oi(),_R=Ge(),FR=_R("match");xS.exports=function(s){var e;return VR(s)&&((e=s[FR])!==void 0?!!e:OR(s)==="RegExp")}});var PS=b((FF,wS)=>{"use strict";var NR=Qt();wS.exports=function(){var s=NR(this),e="";return s.hasIndices&&(e+="d"),s.global&&(e+="g"),s.ignoreCase&&(e+="i"),s.multiline&&(e+="m"),s.dotAll&&(e+="s"),s.unicode&&(e+="u"),s.unicodeSets&&(e+="v"),s.sticky&&(e+="y"),e}});var RS=b((NF,kS)=>{"use strict";var UR=Tt(),qR=Ft(),HR=Gr(),jR=PS(),AS=RegExp.prototype;kS.exports=function(s){var e=s.flags;return e===void 0&&!("flags"in AS)&&!qR(s,"flags")&&HR(AS,s)?UR(jR,s):e}});var LS=b((UF,MS)=>{"use strict";var tc=He(),zR=nr(),QR=Math.floor,Zl=tc("".charAt),GR=tc("".replace),ec=tc("".slice),WR=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,YR=/\$([$&'`]|\d{1,2})/g;MS.exports=function(s,e,t,i,r,a){var n=t+s.length,o=i.length,u=YR;return r!==void 0&&(r=zR(r),u=WR),GR(a,u,function(l,p){var c;switch(Zl(p,0)){case"$":return"$";case"&":return s;case"`":return ec(e,0,t);case"'":return ec(e,n);case"<":c=r[ec(p,1,-1)];break;default:var d=+p;if(d===0)return l;if(d>o){var h=QR(d/10);return h===0?l:h<=o?i[h-1]===void 0?Zl(p,1):i[h-1]+Zl(p,1):l}c=i[d-1]}return c===void 0?"":c})}});var DS=b(()=>{"use strict";var KR=Oe(),XR=Tt(),rc=He(),BS=Ii(),JR=Me(),ZR=sr(),eM=ES(),$r=Ps(),tM=Yr(),iM=RS(),rM=LS(),sM=Ge(),aM=_t(),nM=sM("replace"),oM=TypeError,ic=rc("".indexOf),uM=rc("".replace),$S=rc("".slice),lM=Math.max;KR({target:"String",proto:!0},{replaceAll:function(e,t){var i=BS(this),r,a,n,o,u,l,p,c,d,h,m=0,g="";if(!ZR(e)){if(r=eM(e),r&&(a=$r(BS(iM(e))),!~ic(a,"g")))throw new oM("`.replaceAll` does not allow non-global regexes");if(n=tM(e,nM),n)return XR(n,e,i,t);if(aM&&r)return uM($r(i),e,t)}for(o=$r(i),u=$r(e),l=JR(t),l||(t=$r(t)),p=u.length,c=lM(1,p),d=ic(o,u);d!==-1;)h=l?$r(t(u,d,o)):rM(u,o,d,[],void 0,t),g+=$S(o,m,d)+h,m=d+p,d=d+c>o.length?-1:ic(o,u,d+c);return m<o.length&&(g+=$S(o,m)),g}})});var VS=b((jF,CS)=>{"use strict";TS();IS();DS();var cM=xi();CS.exports=cM("String","replaceAll")});var _S=b((zF,OS)=>{"use strict";var dM=VS();OS.exports=dM});var sc=b((QF,FS)=>{"use strict";var pM=_S();FS.exports=pM});var US=b((GF,NS)=>{"use strict";var hM=Zr(),fM=Ps(),mM=Ii(),bM=RangeError;NS.exports=function(e){var t=fM(mM(this)),i="",r=hM(e);if(r<0||r===1/0)throw new bM("Wrong number of repetitions");for(;r>0;(r>>>=1)&&(t+=t))r&1&&(i+=t);return i}});var QS=b((WF,zS)=>{"use strict";var jS=He(),gM=fu(),qS=Ps(),SM=US(),vM=Ii(),yM=jS(SM),TM=jS("".slice),IM=Math.ceil,HS=function(s){return function(e,t,i){var r=qS(vM(e)),a=gM(t),n=r.length,o=i===void 0?" ":qS(i),u,l;return a<=n||o===""?r:(u=a-n,l=yM(o,IM(u/o.length)),l.length>u&&(l=TM(l,0,u)),s?r+l:l+r)}};zS.exports={start:HS(!1),end:HS(!0)}});var WS=b((YF,GS)=>{"use strict";var xM=Fi();GS.exports=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(xM)});var YS=b(()=>{"use strict";var EM=Oe(),wM=QS().start,PM=WS();EM({target:"String",proto:!0,forced:PM},{padStart:function(e){return wM(this,e,arguments.length>1?arguments[1]:void 0)}})});var XS=b((JF,KS)=>{"use strict";YS();var AM=xi();KS.exports=AM("String","padStart")});var ZS=b((ZF,JS)=>{"use strict";var kM=XS();JS.exports=kM});var ac=b((eN,ev)=>{"use strict";var RM=ZS();ev.exports=RM});var SL={};yy(SL,{ChromecastState:()=>qr,HttpConnectionType:()=>Wa,Observable:()=>Jt.Observable,PlaybackState:()=>et,Player:()=>Qa,PredefinedQualityLimits:()=>Hr,SDK_VERSION:()=>gL,Subject:()=>Jt.Subject,Subscription:()=>Jt.Subscription,Surface:()=>Ya,VERSION:()=>_o,ValueSubject:()=>Jt.ValueSubject,VideoFormat:()=>jt,VideoQuality:()=>Jt.VideoQuality,clientChecker:()=>W,isMobile:()=>Ir});module.exports=Ty(SL);var _o="2.0.135-dev.de6f0c74.0";var et=(r=>(r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused",r))(et||{}),jt=(x=>(x.MPEG="MPEG",x.DASH="DASH",x.DASH_SEP="DASH_SEP",x.DASH_SEP_VK="DASH_SEP",x.DASH_WEBM="DASH_WEBM",x.DASH_WEBM_AV1="DASH_WEBM_AV1",x.DASH_STREAMS="DASH_STREAMS",x.DASH_WEBM_VK="DASH_WEBM",x.DASH_ONDEMAND="DASH_ONDEMAND",x.DASH_ONDEMAND_VK="DASH_ONDEMAND",x.DASH_LIVE="DASH_LIVE",x.DASH_LIVE_CMAF="DASH_LIVE_CMAF",x.DASH_LIVE_WEBM="DASH_LIVE_WEBM",x.HLS="HLS",x.HLS_ONDEMAND="HLS_ONDEMAND",x.HLS_JS="HLS",x.HLS_LIVE="HLS_LIVE",x.HLS_LIVE_CMAF="HLS_LIVE_CMAF",x.WEB_RTC_LIVE="WEB_RTC_LIVE",x))(jt||{});var qr=(r=>(r.NOT_AVAILABLE="NOT_AVAILABLE",r.AVAILABLE="AVAILABLE",r.CONNECTING="CONNECTING",r.CONNECTED="CONNECTED",r))(qr||{}),Wa=(i=>(i.HTTP1="http1",i.HTTP2="http2",i.QUIC="quic",i))(Wa||{});var Ya=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(Ya||{}),Hr=(i=>(i.TRAFFIC_SAVING="traffic_saving",i.HIGH_QUALITY="high_quality",i.UNKNOWN="unknown",i))(Hr||{});var fy=j(xt(),1);var te=require("@vkontakte/videoplayer-shared");var Dp=s=>new Promise((e,t)=>{let i=document.createElement("script");i.setAttribute("src",s),i.onload=()=>e(),i.onerror=r=>t(r),document.body.appendChild(i)});var en=class{constructor(e){this.connection$=new te.ValueSubject(void 0);this.castState$=new te.ValueSubject("NOT_AVAILABLE");this.errorEvent$=new te.Subject;this.realCastState$=new te.ValueSubject("NOT_AVAILABLE");this.subscription=new te.Subscription;this.isDestroyed=!1;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=(0,te.isNonNullable)(window.chrome?.cast),r=!!window.__onGCastApiAvailable;i?this.initializeCastApi():(window.__onGCastApiAvailable=a=>{delete window.__onGCastApiAvailable,a&&!this.isDestroyed&&this.initializeCastApi()},r||Dp("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:te.ErrorCategory.NETWORK,message:"Script loading failed!"})))}connect(){cast.framework.CastContext.getInstance()?.requestSession()}disconnect(){cast.framework.CastContext.getInstance()?.getCurrentSession()?.endSession(!0)}stopMedia(){return new Promise((e,t)=>{cast.framework.CastContext.getInstance()?.getCurrentSession()?.getMediaSession()?.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){(0,te.isNonNullable)(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();(0,te.isNullable)(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();(0,te.isNullable)(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((0,te.fromEvent)(i,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(r=>{switch(r.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=i.getCurrentSession()?.getMediaSession()?.media?.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(0,te.assertNever)(r.sessionState)}})).add((0,te.merge)((0,te.fromEvent)(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe((0,te.tap)(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),(0,te.map)(r=>r.castState)),(0,te.observableFrom)([i.getCastState()])).pipe((0,te.filterChanged)(),(0,te.map)(HI),(0,te.tap)(r=>{this.log({message:`realCastState$: ${r}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{let a=r==="CONNECTED",n=(0,te.isNonNullable)(this.connection$.getValue());if(a&&!n){let o=i.getCurrentSession();(0,te.assertNonNullable)(o);let u=o.getCastDevice(),l=o.getMediaSession()?.media?.contentId;((0,te.isNullable)(l)||l===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:o,castDevice:u}))}else!a&&n&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(r==="CONNECTED"?(0,te.isNonNullable)(this.connection$.getValue())?"CONNECTED":"AVAILABLE":r)}))}initializeCastApi(){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{return}try{e.setOptions({receiverApplicationId:this.params.receiverApplicationId??t,autoJoinPolicy:i}),this.initListeners()}catch(r){this.errorEvent$.next({id:"ChromecastInitializer",category:te.ErrorCategory.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:r})}}},HI=s=>{switch(s){case cast.framework.CastState.NO_DEVICES_AVAILABLE:return"NOT_AVAILABLE";case cast.framework.CastState.NOT_CONNECTED:return"AVAILABLE";case cast.framework.CastState.CONNECTING:return"CONNECTING";case cast.framework.CastState.CONNECTED:return"CONNECTED";default:return(0,te.assertNever)(s)}};var _c=j(xt(),1),ty=j(Ui(),1),iy=j(qu(),1);var Bb=j(Rn(),1);var kl=require("@vkontakte/videoplayer-shared");var Le=(s,e=0,t=0)=>{switch(t){case 0:return s.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case 1:{if(e===0)return s;let i=new URL(s);return i.searchParams.append("playback_shift",e.toFixed(0)),i.toString()}case 2:{let i=new URL(s);return!i.searchParams.get("offset_p")&&e===0?s:(i.searchParams.set("offset_p",e.toFixed(0)),i.toString())}default:(0,kl.assertNever)(t)}return s},wi=(s,e)=>{switch(e){case 0:return NaN;case 1:{let t=new URL(s);return Number(t.searchParams.get("playback_shift"))}case 2:{let t=new URL(s);return Number(t.searchParams.get("offset_p")??0)}default:(0,kl.assertNever)(e)}};var _=(s,e,t=!1)=>{let i=s.getTransition();(t||!i||i.to===e)&&s.setState(e)};var Gt=require("@vkontakte/videoplayer-shared"),ie=class{constructor(e){this.transitionStarted$=new Gt.Subject;this.transitionEnded$=new Gt.Subject;this.transitionUpdated$=new Gt.Subject;this.forceChanged$=new Gt.Subject;this.stateChangeStarted$=(0,Gt.merge)(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=(0,Gt.merge)(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||(0,Gt.isNonNullable)(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}};var Rb=require("@vkontakte/videoplayer-shared"),Mb=s=>{switch(s){case"MPEG":case"DASH":case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":case"HLS":case"HLS_ONDEMAND":return!1;case"DASH_LIVE":case"DASH_LIVE_CMAF":case"HLS_LIVE":case"HLS_LIVE_CMAF":case"DASH_LIVE_WEBM":case"WEB_RTC_LIVE":return!0;default:return(0,Rb.assertNever)(s)}};var q=require("@vkontakte/videoplayer-shared");var XA=5,JA=5,ZA=500,Lb=7e3,hs=class{constructor(e){this.subscription=new q.Subscription;this.loadMediaTimeoutSubscription=new q.Subscription;this.videoState=new ie("stopped");this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(a)};`}),i==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.stop());return}if(!t){if(r?.to!=="paused"&&a.state==="requested"&&e!=="stopped"){this.seek(a.position/1e3);return}switch(i){case"ready":{switch(e){case"playing":case"paused":case"ready":break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:(0,q.assertNever)(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:(0,q.assertNever)(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:(0,q.assertNever)(e)}break}default:(0,q.assertNever)(i)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(Mb(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 q.Subscription;this.subscription.add(e),this.subscription.add((0,q.merge)(this.videoState.stateChangeStarted$.pipe((0,q.map)(r=>`stateChangeStarted$ ${JSON.stringify(r)}`)),this.videoState.stateChangeEnded$.pipe((0,q.map)(r=>`stateChangeEnded$ ${JSON.stringify(r)}`))).subscribe(r=>this.log({message:`[videoState] ${r}`})));let t=(r,a)=>this.subscription.add(r.subscribe(a));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{let r=new q.Subject;e.add(r.pipe((0,q.debounce)(ZA)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let a=NaN;e.add((0,q.fromEvent)(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-a)>XA)&&r.next(o),a=o})),e.add((0,q.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t((0,q.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t((0,q.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemotePause():this.handleRemotePlay()}),t((0,q.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),r=>{this.logRemoteEvent(r);let{remotePlayer:a}=this.params.connection,n=r.value,o=this.params.output.isBuffering$.getValue(),u=n===chrome.cast.media.PlayerState.BUFFERING;switch(o!==u&&this.params.output.isBuffering$.next(u),n){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&a.duration-a.currentTime<JA&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),_(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:(0,q.assertNever)(n)}}),t((0,q.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t((0,q.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({muted:r.value})});let i=(0,q.merge)(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,q.observableFrom)(["init"])).pipe((0,q.debounce)(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"),_(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),_(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();(this.videoState.getTransition()?.to==="paused"||e==="playing")&&(this.videoState.setState("paused"),_(this.params.desiredState.playbackState,"paused"))}handleRemotePlay(){let e=this.videoState.getState();(this.videoState.getTransition()?.to==="playing"||e==="paused")&&(this.videoState.setState("playing"),_(this.params.desiredState.playbackState,"playing"))}handleRemoteReady(){this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.params.desiredState.playbackState.getTransition()?.to==="ready"&&_(this.params.desiredState.playbackState,"ready")}handleRemoteStop(){this.videoState.getState()!=="stopped"&&this.videoState.setState("stopped")}handleRemoteVolumeChange(e){let t=this.params.output.volume$.getValue(),i={volume:e.volume??t.volume,muted:e.muted??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){let t=this.params.source,i,r,a;switch(e){case"MPEG":{let l=t[e];(0,q.assertNonNullable)(l);let p=(0,q.getHighestQuality)(Object.keys(l));(0,q.assertNonNullable)(p);let c=l[p];(0,q.assertNonNullable)(c),i=c,r="video/mp4",a=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let l=t[e];(0,q.assertNonNullable)(l),i=l.url,r="application/x-mpegurl",a=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":{let l=t[e];(0,q.assertNonNullable)(l),i=l.url,r="application/dash+xml",a=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let l=t[e];(0,q.assertNonNullable)(l),i=l.url,r="application/dash+xml",a=chrome.cast.media.StreamType.LIVE;break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let l=t[e];(0,q.assertNonNullable)(l),i=Le(l.url),r="application/x-mpegurl",a=chrome.cast.media.StreamType.LIVE;break}case"DASH_LIVE":case"WEB_RTC_LIVE":{let l="Unsupported format for Chromecast",p=new Error(l);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:q.ErrorCategory.VIDEO_PIPELINE,message:l,thrown:p}),p}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return(0,q.assertNever)(e)}let n=new chrome.cast.media.MediaInfo(this.params.meta.videoId??i,r);n.contentUrl=i,n.streamType=a,n.metadata=new chrome.cast.media.GenericMediaMetadata;let{title:o,subtitle:u}=this.params.meta;return(0,q.isNonNullable)(o)&&(n.metadata.title=o),(0,q.isNonNullable)(u)&&(n.metadata.subtitle=u),n}createLoadRequest(e){let t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;let i=this.params.desiredState.seekState.getState();return i.state==="applying"||i.state==="requested"?t.currentTime=this.params.output.isLive$.getValue()?0:i.position/1e3:t.currentTime=0,t}loadMedia(e){let t=this.params.connection.session.loadMedia(e),i=new Promise((r,a)=>{this.loadMediaTimeoutSubscription.add((0,q.timeout)(Lb).subscribe(()=>a(`timeout(${Lb})`)))});(0,Bb.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 a=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${r}`;this.log({message:a}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:q.ErrorCategory.VIDEO_PIPELINE,message:a,thrown:r})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var jl=j(xt(),1);var Bl=require("@vkontakte/videoplayer-shared");var $b=require("@vkontakte/videoplayer-shared"),Db=s=>{try{s.pause(),s.playbackRate=0,(0,$b.clearVideoElement)(s),s.remove()}catch(e){console.error(e)}};var Mn=require("@vkontakte/videoplayer-shared"),Rl=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)}},Ml=window.WeakMap?new WeakMap:new Rl,Ll=window.WeakMap?new WeakMap:new Map,ek=(s,e=20)=>{let t=0;return(0,Mn.fromEvent)(s,"ratechange").subscribe(i=>{t++,t>=e&&(s.currentTime=s.currentTime,t=0)})},at=(s,{audioVideoSyncRate:e,disableYandexPiP:t})=>{let i=s.querySelector("video"),r=!!i;i?(0,Bl.clearVideoElement)(i):(i=document.createElement("video"),s.appendChild(i)),Ml.set(i,r);let a=new Mn.Subscription;return a.add(ek(i,e)),Ll.set(i,a),i.setAttribute("crossorigin","anonymous"),i.setAttribute("playsinline","playsinline"),t&&i.setAttribute("x-yandex-pip","false"),i.controls=!1,i.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),i},nt=s=>{Ll.get(s)?.unsubscribe(),Ll.delete(s);let t=Ml.get(s);Ml.delete(s),t?(0,Bl.clearVideoElement)(s):Db(s)};var $l=j(Gi(),1),H=require("@vkontakte/videoplayer-shared");var Pi=require("@vkontakte/videoplayer-shared"),Ln=(s,e,t,{equal:i=(n,o)=>n===o,changed$:r,onError:a}={})=>{let n=s.getState(),o=e(),u=(0,Pi.isNullable)(r),l=new Pi.Subscription;return r&&l.add(r.subscribe(p=>{let c=s.getState();i(p,c)&&s.setState(p)},a)),i(o,n)||(t(n),u&&s.setState(n)),l.add(s.stateChangeStarted$.subscribe(p=>{t(p.to),u&&s.setState(p.to)},a)),l},Wt=(s,e,t)=>Ln(e,()=>s.loop,i=>{(0,Pi.isNonNullable)(i)&&(s.loop=i)},{onError:t}),ot=(s,e,t,i)=>Ln(e,()=>({muted:s.muted,volume:s.volume}),r=>{(0,Pi.isNonNullable)(r)&&(s.muted=r.muted,s.volume=r.volume)},{equal:(r,a)=>r===a||r?.muted===a?.muted&&r?.volume===a?.volume,changed$:t,onError:i}),kt=(s,e,t,i)=>Ln(e,()=>s.playbackRate,r=>{(0,Pi.isNonNullable)(r)&&(s.playbackRate=r)},{changed$:t,onError:i}),fs=Ln;var nk=s=>["__",s.language,s.label].join("|"),ok=(s,e)=>{if(s.id===e)return!0;let[t,i,r]=e.split("|");return s.language===i&&s.label===r},Dl=class s{constructor(e){this.available$=new H.Subject;this.current$=new H.ValueSubject(void 0);this.error$=new H.Subject;this.subscription=new H.Subscription;this.externalTracks=new Map;this.internalTracks=new Map;this.baseURL=e}connect(e,t,i){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();let r=a=>{this.error$.next({id:"TextTracksManager",category:H.ErrorCategory.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:a})};this.subscription.add(this.available$.subscribe(i.availableTextTracks$)),this.subscription.add(this.current$.subscribe(i.currentTextTrack$)),this.subscription.add(this.error$.subscribe(i.error$)),this.subscription.add(fs(t.internalTextTracks,()=>(0,$l.default)(this.internalTracks),a=>{(0,H.isNonNullable)(a)&&this.setInternal(a)},{equal:(a,n)=>(0,H.isNonNullable)(a)&&(0,H.isNonNullable)(n)&&a.length===n.length&&a.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe((0,H.map)(a=>a.filter(({type:n})=>n==="internal"))),onError:r})),this.subscription.add(fs(t.externalTextTracks,()=>(0,$l.default)(this.externalTracks),a=>{(0,H.isNonNullable)(a)&&this.setExternal(a)},{equal:(a,n)=>(0,H.isNonNullable)(a)&&(0,H.isNonNullable)(n)&&a.length===n.length&&a.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe((0,H.map)(a=>a.filter(({type:n})=>n==="external"))),onError:r})),this.subscription.add(fs(t.currentTextTrack,()=>{if(this.video)return;let a=this.htmlTextTracksAsArray().find(({mode:n})=>n==="showing");return a&&this.htmlTextTrackToITextTrack(a).id},a=>this.select(a),{changed$:this.current$,onError:r})),this.subscription.add(fs(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let a of this.htmlTextTracksAsArray())this.applyCueSettings(a.cues),this.applyCueSettings(a.activeCues)}))}subscribe(){(0,H.assertNonNullable)(this.video);let{textTracks:e}=this.video;this.subscription.add((0,H.fromEvent)(e,"addtrack").subscribe(()=>{let i=this.current$.getValue();i&&this.select(i)})),this.subscription.add((0,H.merge)((0,H.fromEvent)(e,"addtrack"),(0,H.fromEvent)(e,"removetrack"),(0,H.observableFrom)(["init"])).pipe((0,H.map)(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),(0,H.filterChanged)((i,r)=>i.length===r.length&&i.every(({id:a},n)=>a===r[n].id))).subscribe(this.available$)),this.subscription.add((0,H.merge)((0,H.fromEvent)(e,"change"),(0,H.observableFrom)(["init"])).pipe((0,H.map)(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),(0,H.map)(i=>i&&this.htmlTextTrackToITextTrack(i).id),(0,H.filterChanged)()).subscribe(this.current$));let t=i=>this.applyCueSettings(i.target?.activeCues??null);this.subscription.add((0,H.fromEvent)(e,"addtrack").subscribe(i=>{i.track?.addEventListener("cuechange",t);let r=a=>{let n=a.target?.cues??null;n&&n.length&&(this.applyCueSettings(a.target?.cues??null),a.target?.removeEventListener("cuechange",r))};i.track?.addEventListener("cuechange",r)})),this.subscription.add((0,H.fromEvent)(e,"removetrack").subscribe(i=>{i.track?.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;(0,H.isNonNullable)(t.align)&&(r.align=t.align),(0,H.isNonNullable)(t.position)&&(r.position=t.position),(0,H.isNonNullable)(t.size)&&(r.size=t.size),(0,H.isNonNullable)(t.line)&&(r.line=t.line)}}htmlTextTracksAsArray(e=!1){(0,H.assertNonNullable)(this.video);let t=[...this.video.textTracks];return e?t:t.filter(s.isHealthyTrack)}htmlTextTrackToITextTrack(e){let{language:t,label:i}=e,r=e.id?e.id:nk(e),a=this.externalTracks.has(r),n=(a?this.externalTracks.get(r)?.isAuto:this.internalTracks.get(r)?.isAuto)??r.includes("auto");return a?{id:r,type:"external",isAuto:n,language:t,label:i,url:this.externalTracks.get(r)?.url}:{id:r,type:"internal",isAuto:n,language:t,label:i,url:this.internalTracks.get(r)?.url}}static isHealthyTrack(e){return!(e.kind==="metadata"||e.groupId||e.id===""&&e.label===""&&e.language==="")}setExternal(e){this.internalTracks.size>0&&Array.from(this.internalTracks).forEach(([,t])=>this.detach(t)),e.filter(({id:t})=>!this.externalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.externalTracks).filter(([t])=>!e.find(i=>i.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){let t=[...this.externalTracks];e.filter(({id:i,language:r,isAuto:a})=>!this.internalTracks.has(i)&&!t.some(([,n])=>n.language===r&&n.isAuto===a)).forEach(i=>this.attach(i)),Array.from(this.internalTracks).filter(([i])=>!e.find(r=>r.id===i)).forEach(([,i])=>this.detach(i))}select(e){(0,H.assertNonNullable)(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))((0,H.isNullable)(e)||!ok(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){(0,H.assertNonNullable)(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){(0,H.assertNonNullable)(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)}},Rt=Dl;var Wi=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 Ub=s=>{let e=s;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e?.parentNode;return e??void 0},Cl=s=>{let e=Ub(s);return!!(e&&e.fullscreenElement&&e.fullscreenElement===s)},qb=s=>{let e=Ub(s);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===s)};var O=require("@vkontakte/videoplayer-shared");var uk=3,Hb=(s,e,t=uk)=>{let i=0,r=0;for(let a=0;a<s.length;a++){let n=s.start(a),o=s.end(a);if(n<=e&&e<=o){if(i=n,r=o,!t)return{from:i,to:r};for(let u=a-1;u>=0;u--)s.end(u)+t>=i&&(i=s.start(u));for(let u=a+1;u<s.length;u++)s.start(u)-t<=r&&(r=s.end(u))}}return{from:i,to:r}};var Bn=class{constructor(){this._isMiuiBrowser=!1}get current(){return this._current}get isChrome(){return this.current==="Chrome"}get isFirefox(){return this.current==="Firefox"}get isSafari(){return this.current==="Safari"}get isOpera(){return this.current==="Opera"}get isEdge(){return this.current==="Edge"}get isYandex(){return this.current==="Yandex"}get isSamsungBrowser(){return this.current==="SamsungBrowser"}get currentVersion(){return this._current_version}get chromeVersion(){return this._chromeVersion}get firefoxVersion(){return this._firefoxVersion}get safariVersion(){return this._safariVersion}get operaVersion(){return this._operaVersion}get edgeVersion(){return this._edgeVersion}get yandexVersion(){return this._yandexVersion}get isMiuiBrowser(){return this._isMiuiBrowser}detect(){let{userAgent:e}=navigator;try{let t=/yabrowser/i.test(e)?"Yandex":void 0,i=/samsungbrowser/i.test(e)?"SamsungBrowser":void 0,r=/chrome|crios/i.test(e)?"Chrome":void 0,a=/chromium/i.test(e)?"Chromium":void 0,n=/firefox|fxios/i.test(e)?"Firefox":void 0,o=/webkit|safari|khtml/i.test(e)?"Safari":void 0,u=/opr\//i.test(e)?"Opera":void 0,l=/edg/i.test(e)?"Edge":void 0;this._isMiuiBrowser=/(XiaoMi)|(MiuiBrowser)/i.test(e),this._current=t||i||n||u||l||r||a||o||"Rest"}catch(t){console.error(t)}this.isChrome&&this.detectChromeVersion(),this.isFirefox&&this.detectFirefoxVersion(),this.isSafari&&this.detectSafariVersion(),this.isOpera&&this.detectOperaVersion(),this.isEdge&&this.detectEdgeVersion(),this.isYandex&&this.detectYandexVersion()}detectVersion(e){try{let{userAgent:t}=window.navigator,i=t.match(e);if(!i)return;let r=i[1],a=parseInt(r,10);if(!isNaN(a))return this._current_version=a,a}catch(t){console.error(t)}}detectChromeVersion(){this._chromeVersion=this.detectVersion(/Chrome\/(\d+\.\d+)/)}detectFirefoxVersion(){this._firefoxVersion=this.detectVersion(/Firefox\/(\d+\.\d+)/)}detectSafariVersion(){this._safariVersion=this.detectVersion(/Version\/(\d+)/)}detectOperaVersion(){this._operaVersion=this.detectVersion(/OPR\/(\d+\.\d+)/)}detectEdgeVersion(){this._edgeVersion=this.detectVersion(/Edg\/(\d+\.\d+)/)}detectYandexVersion(){this._yandexVersion=this.detectVersion(/YaBrowser\/(\d+\.\d+\.\d+)/)}};var jb=j(xt(),1);var Ir=()=>/Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test(navigator.appVersion??navigator.userAgent)||navigator?.userAgentData?.mobile;var $n=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,jb.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=Ir()}catch(t){console.error(t)}this.detectDevice(e),this.detectHighEntropyValues(),this.isIOS&&this.detectIOSVersion()}async detectHighEntropyValues(){let{userAgentData:e}=navigator;if(e?.getHighEntropyValues){let t=await e.getHighEntropyValues(["architecture","bitness","brands","mobile","platform","formFactor","model","platformVersion","wow64"]);this._highEntropyValues=t}}detectDevice(e){try{let t=/android/i.test(e)?"Android":void 0,i=/iphone/i.test(e)?"iPhone":void 0,r=/ipad/i.test(e)?"iPad":void 0,a=/ipod/i.test(e)?"iPod":void 0,n=/mac/i.test(e)?"Mac":void 0,o=/webOS|BlackBerry|IEMobile|Opera Mini/i.test(e)?"RestMobile":void 0;this._current=t||i||r||a||o||n||"Desktop"}catch(t){console.error(t)}}detectIOSVersion(){try{if(this._highEntropyValues.platformVersion){let a=this._highEntropyValues.platformVersion.split(".").slice(0,2).join("."),n=parseFloat(a);this._iosVersion=n;return}let{userAgent:e}=window.navigator,t=e.match(/OS (\d+(_\d+)?)/i);if(!t)return;let i=t[1].replace(/_/g,".");if(!i)return;let r=parseFloat(i);if(isNaN(r))return;this._iosVersion=r}catch(e){console.error(e)}}};var Dn=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(){let{maxTouchPoints:e}=navigator;try{this._maxTouchPoints=e??0,this._isHdr=!!matchMedia("(dynamic-range: high)")?.matches,this._colorDepth=screen.colorDepth}catch(t){console.error(t)}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(t){console.error(t)}}};var wt=()=>window.ManagedMediaSource||window.MediaSource,xr=()=>!!(window.ManagedMediaSource&&window.ManagedSourceBuffer?.prototype?.appendBuffer),zb=()=>!!(window.MediaSource&&window.SourceBuffer?.prototype?.appendBuffer),Cn=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;var lk=document.createElement("video"),ck='video/mp4; codecs="avc1.42000a,mp4a.40.2"',dk='video/mp4; codecs="hev1.1.6.L93.B0"',Qb='video/webm; codecs="vp09.00.10.08"',Gb='video/webm; codecs="av01.0.00M.08"',pk='audio/mp4; codecs="mp4a.40.2"',hk='audio/webm; codecs="opus"',Wb,fk=async()=>{if(!window.navigator.mediaCapabilities)return;let s={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=await Promise.all([window.navigator.mediaCapabilities.decodingInfo({...s,video:{...s.video,contentType:Gb}}),window.navigator.mediaCapabilities.decodingInfo({...s,video:{...s.video,contentType:Qb}})]);Wb={DASH_WEBM_AV1:e,DASH_WEBM:t}};fk().catch(s=>{console.log(lk),console.error(s)});var Vn=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 Wb}get supportedCodecs(){return Object.keys(this._codecs).filter(e=>this._codecs[e])}get nativeHlsSupported(){return this._nativeHlsSupported}detect(){this._video=document.createElement("video");try{this._protocols={mms:xr(),mse:zb(),hls:!!(this._video.canPlayType?.("application/x-mpegurl")||this._video.canPlayType?.("vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},this._containers={mp4:!!this._video.canPlayType?.("video/mp4"),webm:!!this._video.canPlayType?.("video/webm"),cmaf:!0};let e=!!wt()?.isTypeSupported?.(ck),t=!!wt()?.isTypeSupported?.(dk),i=!!wt()?.isTypeSupported?.(pk);this._codecs={h264:e,h265:t,vp9:!!wt()?.isTypeSupported?.(Qb),av1:!!wt()?.isTypeSupported?.(Gb),aac:i,opus:!!wt()?.isTypeSupported?.(hk),mpeg:(e||t)&&i},this._nativeHlsSupported=this._protocols.hls&&this._containers.mp4}catch(e){console.error(e)}try{this.destroyVideoElement()}catch(e){console.error("Error destroying video element:",e)}}destroyVideoElement(){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);this._video.parentNode?.replaceChild(e,this._video),this._video=null}};var Yb="audio/mpeg",On=class{supportMp3(){return this._codecs.mp3&&this._containers.mpeg}detect(){this._audio=document.createElement("audio");try{this._containers={mpeg:!!this._audio.canPlayType?.(Yb)},this._codecs={mp3:!!wt()?.isTypeSupported?.(Yb)}}catch(e){console.error(e)}try{this.destroyAudioElement()}catch(e){console.error("Error destroying audio element:",e)}}destroyAudioElement(){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);this._audio.parentNode?.replaceChild(e,this._audio),this._audio=null}};var Kb=require("@vkontakte/videoplayer-shared"),Vl=class{constructor(){this.isInited$=new Kb.ValueSubject(!1);this._displayChecker=new Dn,this._deviceChecker=new $n(this._displayChecker),this._browserChecker=new Bn,this._videoChecker=new Vn(this._deviceChecker,this._browserChecker),this._audioChecker=new On,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}async detect(){this._displayChecker.detect(),this._deviceChecker.detect(),this._browserChecker.detect(),this._videoChecker.detect(),this._audioChecker.detect(),this.isInited$.next(!0)}},W=new Vl;var ut=s=>{let e=I=>(0,O.fromEvent)(s,I).pipe((0,O.mapTo)(void 0)),t=new O.Subscription,i=()=>t.unsubscribe(),r=(0,O.merge)((0,O.fromEvent)(s,"progress"),(0,O.fromEvent)(s,"timeupdate")).pipe((0,O.map)(()=>Hb(s.buffered,s.currentTime))),a=W.browser.isSafari?(0,O.combine)({play:e("play").pipe((0,O.once)()),playing:e("playing")}).pipe((0,O.mapTo)(void 0)):e("playing"),n=(0,O.fromEvent)(s,"volumechange").pipe((0,O.map)(()=>({muted:s.muted,volume:s.volume}))),o=(0,O.fromEvent)(s,"ratechange").pipe((0,O.map)(()=>s.playbackRate)),u=(0,O.fromEvent)(s,"error").pipe((0,O.filter)(()=>!!(s.error||s.played.length)),(0,O.map)(()=>{let I=s.error;return{id:I?`MediaError#${I.code}`:"HtmlVideoError",category:O.ErrorCategory.VIDEO_PIPELINE,message:I?I.message:"Error event from HTML video element",thrown:s.error??void 0}})),l=(0,O.fromEvent)(s,"timeupdate").pipe((0,O.map)(()=>s.currentTime)),p=["waiting","seeking","seeked","timeupdate"],c=new O.Subject,d=.3,h;t.add((0,O.merge)(...p.map(I=>(0,O.fromEvent)(s,I))).subscribe(I=>{let U=s.currentTime;s.loop&&(0,O.isNonNullable)(h)&&(0,O.isNonNullable)(U)&&h>=s.duration-d&&U<=d&&c.next(h),h=U}));let m=e("pause").pipe((0,O.filter)(()=>!s.error&&h!==s.duration)),g=(0,O.fromEvent)(s,"enterpictureinpicture"),v=(0,O.fromEvent)(s,"leavepictureinpicture"),T=new O.ValueSubject(qb(s));t.add(g.subscribe(()=>T.next(!0))),t.add(v.subscribe(()=>T.next(!1)));let P=new O.ValueSubject(Cl(s)),x=(0,O.fromEvent)(s,"fullscreenchange");t.add(x.pipe((0,O.map)(()=>Cl(s))).subscribe(P));let L=.1,B=1e3,F=(0,O.fromEvent)(s,"timeupdate").pipe((0,O.map)(I=>s.duration-s.currentTime<L),(0,O.filterChanged)()),G=(0,O.merge)(F.pipe((0,O.filter)(I=>!s.loop&&I)),(0,O.fromEvent)(s,"ended")).pipe((0,O.throttle)(B),(0,O.mapTo)(void 0)),D=(0,O.merge)(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(I=>(0,O.fromEvent)(s,I)),F.pipe((0,O.map)(I=>({type:I?"ended":"unknown"})))).pipe((0,O.map)(I=>W.browser.isFirefox&&I.type==="ended"?s.readyState<2:s.readyState<3),(0,O.filterChanged)());return{playing$:a,pause$:m,canplay$:e("canplay"),ended$:G,looped$:c,error$:u,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:l,durationChange$:(0,O.fromEvent)(s,"durationchange").pipe((0,O.map)(()=>s.duration)),isBuffering$:D,currentBuffer$:r,volumeState$:n,playbackRateState$:o,inPiP$:T,inFullscreen$:P,enterPip$:g,leavePip$:v,destroy:i}};var ci=require("@vkontakte/videoplayer-shared"),Ai=s=>{switch(s){case"mobile":return ci.VideoQuality.Q_144P;case"lowest":return ci.VideoQuality.Q_240P;case"low":return ci.VideoQuality.Q_360P;case"sd":case"medium":return ci.VideoQuality.Q_480P;case"hd":case"high":return ci.VideoQuality.Q_720P;case"fullhd":case"full":return ci.VideoQuality.Q_1080P;case"quadhd":case"quad":return ci.VideoQuality.Q_1440P;case"ultrahd":case"ultra":return ci.VideoQuality.Q_2160P}};var it=j(Ut(),1),Fl=j(xt(),1),Yi=j(Ui(),1),M=require("@vkontakte/videoplayer-shared");var Ol=!1,di={},rg=s=>{Ol=s},sg=()=>{di={}},ag=s=>{s(di)},ms=(s,e)=>{Ol&&(di.meta=di.meta??{},di.meta[s]=e)},tt=class{constructor(e){this.name=e}next(e){if(!Ol)return;di.series=di.series??{};let t=di.series[this.name]??[];t.push([Date.now(),e]),di.series[this.name]=t}};var _e=require("@vkontakte/videoplayer-shared");function _l(s,e,t){return!s.max&&s.min===e?"high_quality":!s.min&&s.max===t?"traffic_saving":"unknown"}function _n(s,e,t){return!!s&&_l(s,e,t)==="high_quality"}function Er(s,e,t){return(0,_e.isNullable)(s)||(0,_e.isNonNullable)(s.min)&&(0,_e.isNonNullable)(s.max)&&(0,_e.isLower)(s.max,s.min)||(0,_e.isNonNullable)(s.min)&&e&&(0,_e.isHigher)(s.min,e)||(0,_e.isNonNullable)(s.max)&&t&&(0,_e.isLower)(s.max,t)}function ng({limits:s,highestAvailableHeight:e,lowestAvailableHeight:t}){return Er({max:s?.max?(0,_e.videoHeightToQuality)(s.max):void 0,min:s?.min?(0,_e.videoHeightToQuality)(s.min):void 0},e?(0,_e.videoHeightToQuality)(e):void 0,t?(0,_e.videoHeightToQuality)(t):void 0)}var dg=new tt("best_bitrate"),Nn=(s,e,t)=>(e-t)*Math.pow(2,-10*s)+t;var wr=s=>(e,t)=>s*(Number(e.bitrate)-Number(t.bitrate)),ki=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=(0,M.now)()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},Un='Assertion "ABR Tracks is empty array" failed',Fn=new WeakMap,og=new WeakMap,ug=new WeakMap,bs=(s,e,t,i)=>{let r=[...e].sort(wr(1)),a=[...t].sort(wr(1)),n=a.filter(u=>(0,M.isNonNullable)(u.bitrate)&&(0,M.isNonNullable)(s.bitrate)?s.bitrate/u.bitrate>i:!0),o=(0,it.default)(a,Math.round(a.length*r.indexOf(s)/(r.length+1)))??(0,it.default)(a,-1);return o&&(0,Fl.default)(n,o)?o:n.length?(0,it.default)(n,-1):(0,it.default)(a,0)},gs=(s,e,t,i)=>{let r=Fn.get(e);r||(r=[...e].sort(wr(1)),Fn.set(e,r));let a=Fn.get(t);a||(a=[...t].sort(wr(1)),Fn.set(t,a));let n=ug.get(s);n||(n=a.filter(u=>(0,M.isNonNullable)(u.bitrate)&&(0,M.isNonNullable)(s.bitrate)?s.bitrate/u.bitrate>i:!0),ug.set(s,n));let o=(0,it.default)(a,Math.round(a.length*r.indexOf(s)/(r.length+1)))??(0,it.default)(a,-1);return o&&(0,Fl.default)(n,o)?o:n.length?(0,it.default)(n,-1):(0,it.default)(a,0)},lg=s=>"quality"in s,qn=(s,e,t,i)=>{let r=(0,M.isNonNullable)(i?.last?.bitrate)&&(0,M.isNonNullable)(t?.bitrate)&&i.last.bitrate<t.bitrate?s.trackCooldownIncreaseQuality:s.trackCooldownDecreaseQuality,a=t&&i&&i.history[t.id]&&(0,M.now)()-i.history[t.id]<=r&&(!i.last||t.id!==i.last.id);if(t?.id&&i&&!a&&i.recordSelection(t),a&&i?.last){let n=i.last;i?.recordSwitch(n);let o=lg(n)?"video":"audio",u=lg(n)?n.quality:n.bitrate;return e({message:`
|
|
6
|
+
"use strict";var my=Object.create;var Ga=Object.defineProperty;var by=Object.getOwnPropertyDescriptor;var gy=Object.getOwnPropertyNames;var Sy=Object.getPrototypeOf,vy=Object.prototype.hasOwnProperty;var b=(s,e)=>()=>(e||s((e={exports:{}}).exports,e),e.exports),yy=(s,e)=>{for(var t in e)Ga(s,t,{get:e[t],enumerable:!0})},Uc=(s,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of gy(e))!vy.call(s,r)&&r!==t&&Ga(s,r,{get:()=>e[r],enumerable:!(i=by(e,r))||i.enumerable});return s};var H=(s,e,t)=>(t=s!=null?my(Sy(s)):{},Uc(e||!s||!s.__esModule?Ga(t,"default",{value:s,enumerable:!0}):t,s)),Ty=s=>Uc(Ga({},"__esModule",{value:!0}),s);var De=b((Fo,qc)=>{"use strict";var Hr=function(s){return s&&s.Math===Math&&s};qc.exports=Hr(typeof globalThis=="object"&&globalThis)||Hr(typeof window=="object"&&window)||Hr(typeof self=="object"&&self)||Hr(typeof global=="object"&&global)||Hr(typeof Fo=="object"&&Fo)||function(){return this}()||Function("return this")()});var Qe=b((IL,jc)=>{"use strict";jc.exports=function(s){try{return!!s()}catch{return!0}}});var zr=b((xL,Hc)=>{"use strict";var Iy=Qe();Hc.exports=!Iy(function(){var s=function(){}.bind();return typeof s!="function"||s.hasOwnProperty("prototype")})});var No=b((EL,Wc)=>{"use strict";var xy=zr(),Gc=Function.prototype,zc=Gc.apply,Qc=Gc.call;Wc.exports=typeof Reflect=="object"&&Reflect.apply||(xy?Qc.bind(zc):function(){return Qc.apply(zc,arguments)})});var je=b((wL,Xc)=>{"use strict";var Yc=zr(),Kc=Function.prototype,Uo=Kc.call,Ey=Yc&&Kc.bind.bind(Uo,Uo);Xc.exports=Yc?Ey:function(s){return function(){return Uo.apply(s,arguments)}}});var Oi=b((AL,Zc)=>{"use strict";var Jc=je(),wy=Jc({}.toString),Ay=Jc("".slice);Zc.exports=function(s){return Ay(wy(s),8,-1)}});var qo=b((PL,ed)=>{"use strict";var Py=Oi(),ky=je();ed.exports=function(s){if(Py(s)==="Function")return ky(s)}});var Me=b((kL,td)=>{"use strict";var jo=typeof document=="object"&&document.all;td.exports=typeof jo>"u"&&jo!==void 0?function(s){return typeof s=="function"||s===jo}:function(s){return typeof s=="function"}});var yt=b((RL,id)=>{"use strict";var Ry=Qe();id.exports=!Ry(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var Tt=b((ML,rd)=>{"use strict";var My=zr(),Ka=Function.prototype.call;rd.exports=My?Ka.bind(Ka):function(){return Ka.apply(Ka,arguments)}});var Ho=b(nd=>{"use strict";var sd={}.propertyIsEnumerable,ad=Object.getOwnPropertyDescriptor,Ly=ad&&!sd.call({1:2},1);nd.f=Ly?function(e){var t=ad(this,e);return!!t&&t.enumerable}:sd});var Qr=b((BL,od)=>{"use strict";od.exports=function(s,e){return{enumerable:!(s&1),configurable:!(s&2),writable:!(s&4),value:e}}});var ld=b(($L,ud)=>{"use strict";var By=je(),$y=Qe(),Dy=Oi(),zo=Object,Cy=By("".split);ud.exports=$y(function(){return!zo("z").propertyIsEnumerable(0)})?function(s){return Dy(s)==="String"?Cy(s,""):zo(s)}:zo});var sr=b((DL,cd)=>{"use strict";cd.exports=function(s){return s==null}});var Ii=b((CL,dd)=>{"use strict";var Vy=sr(),Oy=TypeError;dd.exports=function(s){if(Vy(s))throw new Oy("Can't call method on "+s);return s}});var _i=b((VL,pd)=>{"use strict";var _y=ld(),Fy=Ii();pd.exports=function(s){return _y(Fy(s))}});var It=b((OL,hd)=>{"use strict";var Ny=Me();hd.exports=function(s){return typeof s=="object"?s!==null:Ny(s)}});var ar=b((_L,fd)=>{"use strict";fd.exports={}});var oi=b((FL,bd)=>{"use strict";var Qo=ar(),Go=De(),Uy=Me(),md=function(s){return Uy(s)?s:void 0};bd.exports=function(s,e){return arguments.length<2?md(Qo[s])||md(Go[s]):Qo[s]&&Qo[s][e]||Go[s]&&Go[s][e]}});var Gr=b((NL,gd)=>{"use strict";var qy=je();gd.exports=qy({}.isPrototypeOf)});var Fi=b((UL,yd)=>{"use strict";var jy=De(),Sd=jy.navigator,vd=Sd&&Sd.userAgent;yd.exports=vd?String(vd):""});var Yo=b((qL,Ad)=>{"use strict";var wd=De(),Wo=Fi(),Td=wd.process,Id=wd.Deno,xd=Td&&Td.versions||Id&&Id.version,Ed=xd&&xd.v8,Ot,Xa;Ed&&(Ot=Ed.split("."),Xa=Ot[0]>0&&Ot[0]<4?1:+(Ot[0]+Ot[1]));!Xa&&Wo&&(Ot=Wo.match(/Edge\/(\d+)/),(!Ot||Ot[1]>=74)&&(Ot=Wo.match(/Chrome\/(\d+)/),Ot&&(Xa=+Ot[1])));Ad.exports=Xa});var Ko=b((jL,kd)=>{"use strict";var Pd=Yo(),Hy=Qe(),zy=De(),Qy=zy.String;kd.exports=!!Object.getOwnPropertySymbols&&!Hy(function(){var s=Symbol("symbol detection");return!Qy(s)||!(Object(s)instanceof Symbol)||!Symbol.sham&&Pd&&Pd<41})});var Xo=b((HL,Rd)=>{"use strict";var Gy=Ko();Rd.exports=Gy&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var Jo=b((zL,Md)=>{"use strict";var Wy=oi(),Yy=Me(),Ky=Gr(),Xy=Xo(),Jy=Object;Md.exports=Xy?function(s){return typeof s=="symbol"}:function(s){var e=Wy("Symbol");return Yy(e)&&Ky(e.prototype,Jy(s))}});var Wr=b((QL,Ld)=>{"use strict";var Zy=String;Ld.exports=function(s){try{return Zy(s)}catch{return"Object"}}});var zt=b((GL,Bd)=>{"use strict";var eT=Me(),tT=Wr(),iT=TypeError;Bd.exports=function(s){if(eT(s))return s;throw new iT(tT(s)+" is not a function")}});var Yr=b((WL,$d)=>{"use strict";var rT=zt(),sT=sr();$d.exports=function(s,e){var t=s[e];return sT(t)?void 0:rT(t)}});var Cd=b((YL,Dd)=>{"use strict";var Zo=Tt(),eu=Me(),tu=It(),aT=TypeError;Dd.exports=function(s,e){var t,i;if(e==="string"&&eu(t=s.toString)&&!tu(i=Zo(t,s))||eu(t=s.valueOf)&&!tu(i=Zo(t,s))||e!=="string"&&eu(t=s.toString)&&!tu(i=Zo(t,s)))return i;throw new aT("Can't convert object to primitive value")}});var _t=b((KL,Vd)=>{"use strict";Vd.exports=!0});var Fd=b((XL,_d)=>{"use strict";var Od=De(),nT=Object.defineProperty;_d.exports=function(s,e){try{nT(Od,s,{value:e,configurable:!0,writable:!0})}catch{Od[s]=e}return e}});var Kr=b((JL,qd)=>{"use strict";var oT=_t(),uT=De(),lT=Fd(),Nd="__core-js_shared__",Ud=qd.exports=uT[Nd]||lT(Nd,{});(Ud.versions||(Ud.versions=[])).push({version:"3.38.0",mode:oT?"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 iu=b((ZL,Hd)=>{"use strict";var jd=Kr();Hd.exports=function(s,e){return jd[s]||(jd[s]=e||{})}});var nr=b((eB,zd)=>{"use strict";var cT=Ii(),dT=Object;zd.exports=function(s){return dT(cT(s))}});var Ft=b((tB,Qd)=>{"use strict";var pT=je(),hT=nr(),fT=pT({}.hasOwnProperty);Qd.exports=Object.hasOwn||function(e,t){return fT(hT(e),t)}});var ru=b((iB,Gd)=>{"use strict";var mT=je(),bT=0,gT=Math.random(),ST=mT(1 .toString);Gd.exports=function(s){return"Symbol("+(s===void 0?"":s)+")_"+ST(++bT+gT,36)}});var Ge=b((rB,Yd)=>{"use strict";var vT=De(),yT=iu(),Wd=Ft(),TT=ru(),IT=Ko(),xT=Xo(),or=vT.Symbol,su=yT("wks"),ET=xT?or.for||or:or&&or.withoutSetter||TT;Yd.exports=function(s){return Wd(su,s)||(su[s]=IT&&Wd(or,s)?or[s]:ET("Symbol."+s)),su[s]}});var Zd=b((sB,Jd)=>{"use strict";var wT=Tt(),Kd=It(),Xd=Jo(),AT=Yr(),PT=Cd(),kT=Ge(),RT=TypeError,MT=kT("toPrimitive");Jd.exports=function(s,e){if(!Kd(s)||Xd(s))return s;var t=AT(s,MT),i;if(t){if(e===void 0&&(e="default"),i=wT(t,s,e),!Kd(i)||Xd(i))return i;throw new RT("Can't convert object to primitive value")}return e===void 0&&(e="number"),PT(s,e)}});var au=b((aB,ep)=>{"use strict";var LT=Zd(),BT=Jo();ep.exports=function(s){var e=LT(s,"string");return BT(e)?e:e+""}});var Ja=b((nB,ip)=>{"use strict";var $T=De(),tp=It(),nu=$T.document,DT=tp(nu)&&tp(nu.createElement);ip.exports=function(s){return DT?nu.createElement(s):{}}});var ou=b((oB,rp)=>{"use strict";var CT=yt(),VT=Qe(),OT=Ja();rp.exports=!CT&&!VT(function(){return Object.defineProperty(OT("div"),"a",{get:function(){return 7}}).a!==7})});var np=b(ap=>{"use strict";var _T=yt(),FT=Tt(),NT=Ho(),UT=Qr(),qT=_i(),jT=au(),HT=Ft(),zT=ou(),sp=Object.getOwnPropertyDescriptor;ap.f=_T?sp:function(e,t){if(e=qT(e),t=jT(t),zT)try{return sp(e,t)}catch{}if(HT(e,t))return UT(!FT(NT.f,e,t),e[t])}});var uu=b((lB,op)=>{"use strict";var QT=Qe(),GT=Me(),WT=/#|\.prototype\./,Xr=function(s,e){var t=KT[YT(s)];return t===JT?!0:t===XT?!1:GT(e)?QT(e):!!e},YT=Xr.normalize=function(s){return String(s).replace(WT,".").toLowerCase()},KT=Xr.data={},XT=Xr.NATIVE="N",JT=Xr.POLYFILL="P";op.exports=Xr});var ur=b((cB,lp)=>{"use strict";var up=qo(),ZT=zt(),eI=zr(),tI=up(up.bind);lp.exports=function(s,e){return ZT(s),e===void 0?s:eI?tI(s,e):function(){return s.apply(e,arguments)}}});var lu=b((dB,cp)=>{"use strict";var iI=yt(),rI=Qe();cp.exports=iI&&rI(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var Qt=b((pB,dp)=>{"use strict";var sI=It(),aI=String,nI=TypeError;dp.exports=function(s){if(sI(s))return s;throw new nI(aI(s)+" is not an object")}});var Ni=b(hp=>{"use strict";var oI=yt(),uI=ou(),lI=lu(),Za=Qt(),pp=au(),cI=TypeError,cu=Object.defineProperty,dI=Object.getOwnPropertyDescriptor,du="enumerable",pu="configurable",hu="writable";hp.f=oI?lI?function(e,t,i){if(Za(e),t=pp(t),Za(i),typeof e=="function"&&t==="prototype"&&"value"in i&&hu in i&&!i[hu]){var r=dI(e,t);r&&r[hu]&&(e[t]=i.value,i={configurable:pu in i?i[pu]:r[pu],enumerable:du in i?i[du]:r[du],writable:!1})}return cu(e,t,i)}:cu:function(e,t,i){if(Za(e),t=pp(t),Za(i),uI)try{return cu(e,t,i)}catch{}if("get"in i||"set"in i)throw new cI("Accessors not supported");return"value"in i&&(e[t]=i.value),e}});var lr=b((fB,fp)=>{"use strict";var pI=yt(),hI=Ni(),fI=Qr();fp.exports=pI?function(s,e,t){return hI.f(s,e,fI(1,t))}:function(s,e,t){return s[e]=t,s}});var Oe=b((mB,bp)=>{"use strict";var Jr=De(),mI=No(),bI=qo(),gI=Me(),SI=np().f,vI=uu(),cr=ar(),yI=ur(),dr=lr(),mp=Ft();Kr();var TI=function(s){var e=function(t,i,r){if(this instanceof e){switch(arguments.length){case 0:return new s;case 1:return new s(t);case 2:return new s(t,i)}return new s(t,i,r)}return mI(s,this,arguments)};return e.prototype=s.prototype,e};bp.exports=function(s,e){var t=s.target,i=s.global,r=s.stat,a=s.proto,n=i?Jr:r?Jr[t]:Jr[t]&&Jr[t].prototype,o=i?cr:cr[t]||dr(cr,t,{})[t],u=o.prototype,l,d,c,p,h,m,g,v,T;for(p in e)l=vI(i?p:t+(r?".":"#")+p,s.forced),d=!l&&n&&mp(n,p),m=o[p],d&&(s.dontCallGetSet?(T=SI(n,p),g=T&&T.value):g=n[p]),h=d&&g?g:e[p],!(!l&&!a&&typeof m==typeof h)&&(s.bind&&d?v=yI(h,Jr):s.wrap&&d?v=TI(h):a&&gI(h)?v=bI(h):v=h,(s.sham||h&&h.sham||m&&m.sham)&&dr(v,"sham",!0),dr(o,p,v),a&&(c=t+"Prototype",mp(cr,c)||dr(cr,c,{}),dr(cr[c],p,h),s.real&&u&&(l||!u[p])&&dr(u,p,h)))}});var Sp=b((bB,gp)=>{"use strict";var II=Math.ceil,xI=Math.floor;gp.exports=Math.trunc||function(e){var t=+e;return(t>0?xI:II)(t)}});var Zr=b((gB,vp)=>{"use strict";var EI=Sp();vp.exports=function(s){var e=+s;return e!==e||e===0?0:EI(e)}});var Tp=b((SB,yp)=>{"use strict";var wI=Zr(),AI=Math.max,PI=Math.min;yp.exports=function(s,e){var t=wI(s);return t<0?AI(t+e,0):PI(t,e)}});var fu=b((vB,Ip)=>{"use strict";var kI=Zr(),RI=Math.min;Ip.exports=function(s){var e=kI(s);return e>0?RI(e,9007199254740991):0}});var pr=b((yB,xp)=>{"use strict";var MI=fu();xp.exports=function(s){return MI(s.length)}});var mu=b((TB,wp)=>{"use strict";var LI=_i(),BI=Tp(),$I=pr(),Ep=function(s){return function(e,t,i){var r=LI(e),a=$I(r);if(a===0)return!s&&-1;var n=BI(i,a),o;if(s&&t!==t){for(;a>n;)if(o=r[n++],o!==o)return!0}else for(;a>n;n++)if((s||n in r)&&r[n]===t)return s||n||0;return!s&&-1}};wp.exports={includes:Ep(!0),indexOf:Ep(!1)}});var es=b((IB,Ap)=>{"use strict";Ap.exports=function(){}});var Pp=b(()=>{"use strict";var DI=Oe(),CI=mu().includes,VI=Qe(),OI=es(),_I=VI(function(){return!Array(1).includes()});DI({target:"Array",proto:!0,forced:_I},{includes:function(e){return CI(this,e,arguments.length>1?arguments[1]:void 0)}});OI("includes")});var xi=b((wB,kp)=>{"use strict";var FI=oi();kp.exports=FI});var Mp=b((AB,Rp)=>{"use strict";Pp();var NI=xi();Rp.exports=NI("Array","includes")});var Bp=b((PB,Lp)=>{"use strict";var UI=Mp();Lp.exports=UI});var xt=b((kB,$p)=>{"use strict";var qI=Bp();$p.exports=qI});var tn=b((FB,Vp)=>{"use strict";var HI=iu(),zI=ru(),Cp=HI("keys");Vp.exports=function(s){return Cp[s]||(Cp[s]=zI(s))}});var _p=b((NB,Op)=>{"use strict";var QI=Qe();Op.exports=!QI(function(){function s(){}return s.prototype.constructor=null,Object.getPrototypeOf(new s)!==s.prototype})});var rn=b((UB,Np)=>{"use strict";var GI=Ft(),WI=Me(),YI=nr(),KI=tn(),XI=_p(),Fp=KI("IE_PROTO"),bu=Object,JI=bu.prototype;Np.exports=XI?bu.getPrototypeOf:function(s){var e=YI(s);if(GI(e,Fp))return e[Fp];var t=e.constructor;return WI(t)&&e instanceof t?t.prototype:e instanceof bu?JI:null}});var sn=b((qB,Up)=>{"use strict";Up.exports={}});var Hp=b((jB,jp)=>{"use strict";var ZI=je(),gu=Ft(),ex=_i(),tx=mu().indexOf,ix=sn(),qp=ZI([].push);jp.exports=function(s,e){var t=ex(s),i=0,r=[],a;for(a in t)!gu(ix,a)&&gu(t,a)&&qp(r,a);for(;e.length>i;)gu(t,a=e[i++])&&(~tx(r,a)||qp(r,a));return r}});var Su=b((HB,zp)=>{"use strict";zp.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var vu=b((zB,Qp)=>{"use strict";var rx=Hp(),sx=Su();Qp.exports=Object.keys||function(e){return rx(e,sx)}});var yu=b((QB,Xp)=>{"use strict";var Wp=yt(),ax=Qe(),Yp=je(),nx=rn(),ox=vu(),ux=_i(),lx=Ho().f,Kp=Yp(lx),cx=Yp([].push),dx=Wp&&ax(function(){var s=Object.create(null);return s[2]=2,!Kp(s,2)}),Gp=function(s){return function(e){for(var t=ux(e),i=ox(t),r=dx&&nx(t)===null,a=i.length,n=0,o=[],u;a>n;)u=i[n++],(!Wp||(r?u in t:Kp(t,u)))&&cx(o,s?[u,t[u]]:t[u]);return o}};Xp.exports={entries:Gp(!0),values:Gp(!1)}});var Jp=b(()=>{"use strict";var px=Oe(),hx=yu().entries;px({target:"Object",stat:!0},{entries:function(e){return hx(e)}})});var eh=b((YB,Zp)=>{"use strict";Jp();var fx=ar();Zp.exports=fx.Object.entries});var ih=b((KB,th)=>{"use strict";var mx=eh();th.exports=mx});var Ui=b((XB,rh)=>{"use strict";var bx=ih();rh.exports=bx});var qi=b((JB,sh)=>{"use strict";sh.exports={}});var oh=b((ZB,nh)=>{"use strict";var gx=De(),Sx=Me(),ah=gx.WeakMap;nh.exports=Sx(ah)&&/native code/.test(String(ah))});var Eu=b((e$,ch)=>{"use strict";var vx=oh(),lh=De(),yx=It(),Tx=lr(),Tu=Ft(),Iu=Kr(),Ix=tn(),xx=sn(),uh="Object already initialized",xu=lh.TypeError,Ex=lh.WeakMap,an,ts,nn,wx=function(s){return nn(s)?ts(s):an(s,{})},Ax=function(s){return function(e){var t;if(!yx(e)||(t=ts(e)).type!==s)throw new xu("Incompatible receiver, "+s+" required");return t}};vx||Iu.state?(Nt=Iu.state||(Iu.state=new Ex),Nt.get=Nt.get,Nt.has=Nt.has,Nt.set=Nt.set,an=function(s,e){if(Nt.has(s))throw new xu(uh);return e.facade=s,Nt.set(s,e),e},ts=function(s){return Nt.get(s)||{}},nn=function(s){return Nt.has(s)}):(ji=Ix("state"),xx[ji]=!0,an=function(s,e){if(Tu(s,ji))throw new xu(uh);return e.facade=s,Tx(s,ji,e),e},ts=function(s){return Tu(s,ji)?s[ji]:{}},nn=function(s){return Tu(s,ji)});var Nt,ji;ch.exports={set:an,get:ts,has:nn,enforce:wx,getterFor:Ax}});var Pu=b((t$,ph)=>{"use strict";var wu=yt(),Px=Ft(),dh=Function.prototype,kx=wu&&Object.getOwnPropertyDescriptor,Au=Px(dh,"name"),Rx=Au&&function(){}.name==="something",Mx=Au&&(!wu||wu&&kx(dh,"name").configurable);ph.exports={EXISTS:Au,PROPER:Rx,CONFIGURABLE:Mx}});var fh=b(hh=>{"use strict";var Lx=yt(),Bx=lu(),$x=Ni(),Dx=Qt(),Cx=_i(),Vx=vu();hh.f=Lx&&!Bx?Object.defineProperties:function(e,t){Dx(e);for(var i=Cx(t),r=Vx(t),a=r.length,n=0,o;a>n;)$x.f(e,o=r[n++],i[o]);return e}});var ku=b((r$,mh)=>{"use strict";var Ox=oi();mh.exports=Ox("document","documentElement")});var Bu=b((s$,Ih)=>{"use strict";var _x=Qt(),Fx=fh(),bh=Su(),Nx=sn(),Ux=ku(),qx=Ja(),jx=tn(),gh=">",Sh="<",Mu="prototype",Lu="script",yh=jx("IE_PROTO"),Ru=function(){},Th=function(s){return Sh+Lu+gh+s+Sh+"/"+Lu+gh},vh=function(s){s.write(Th("")),s.close();var e=s.parentWindow.Object;return s=null,e},Hx=function(){var s=qx("iframe"),e="java"+Lu+":",t;return s.style.display="none",Ux.appendChild(s),s.src=String(e),t=s.contentWindow.document,t.open(),t.write(Th("document.F=Object")),t.close(),t.F},on,un=function(){try{on=new ActiveXObject("htmlfile")}catch{}un=typeof document<"u"?document.domain&&on?vh(on):Hx():vh(on);for(var s=bh.length;s--;)delete un[Mu][bh[s]];return un()};Nx[yh]=!0;Ih.exports=Object.create||function(e,t){var i;return e!==null?(Ru[Mu]=_x(e),i=new Ru,Ru[Mu]=null,i[yh]=e):i=un(),t===void 0?i:Fx.f(i,t)}});var hr=b((a$,xh)=>{"use strict";var zx=lr();xh.exports=function(s,e,t,i){return i&&i.enumerable?s[e]=t:zx(s,e,t),s}});var Vu=b((n$,Ah)=>{"use strict";var Qx=Qe(),Gx=Me(),Wx=It(),Yx=Bu(),Eh=rn(),Kx=hr(),Xx=Ge(),Jx=_t(),Cu=Xx("iterator"),wh=!1,ui,$u,Du;[].keys&&(Du=[].keys(),"next"in Du?($u=Eh(Eh(Du)),$u!==Object.prototype&&(ui=$u)):wh=!0);var Zx=!Wx(ui)||Qx(function(){var s={};return ui[Cu].call(s)!==s});Zx?ui={}:Jx&&(ui=Yx(ui));Gx(ui[Cu])||Kx(ui,Cu,function(){return this});Ah.exports={IteratorPrototype:ui,BUGGY_SAFARI_ITERATORS:wh}});var ln=b((o$,kh)=>{"use strict";var eE=Ge(),tE=eE("toStringTag"),Ph={};Ph[tE]="z";kh.exports=String(Ph)==="[object z]"});var is=b((u$,Rh)=>{"use strict";var iE=ln(),rE=Me(),cn=Oi(),sE=Ge(),aE=sE("toStringTag"),nE=Object,oE=cn(function(){return arguments}())==="Arguments",uE=function(s,e){try{return s[e]}catch{}};Rh.exports=iE?cn:function(s){var e,t,i;return s===void 0?"Undefined":s===null?"Null":typeof(t=uE(e=nE(s),aE))=="string"?t:oE?cn(e):(i=cn(e))==="Object"&&rE(e.callee)?"Arguments":i}});var Lh=b((l$,Mh)=>{"use strict";var lE=ln(),cE=is();Mh.exports=lE?{}.toString:function(){return"[object "+cE(this)+"]"}});var rs=b((c$,$h)=>{"use strict";var dE=ln(),pE=Ni().f,hE=lr(),fE=Ft(),mE=Lh(),bE=Ge(),Bh=bE("toStringTag");$h.exports=function(s,e,t,i){var r=t?s:s&&s.prototype;r&&(fE(r,Bh)||pE(r,Bh,{configurable:!0,value:e}),i&&!dE&&hE(r,"toString",mE))}});var Ch=b((d$,Dh)=>{"use strict";var gE=Vu().IteratorPrototype,SE=Bu(),vE=Qr(),yE=rs(),TE=qi(),IE=function(){return this};Dh.exports=function(s,e,t,i){var r=e+" Iterator";return s.prototype=SE(gE,{next:vE(+!i,t)}),yE(s,r,!1,!0),TE[r]=IE,s}});var Oh=b((p$,Vh)=>{"use strict";var xE=je(),EE=zt();Vh.exports=function(s,e,t){try{return xE(EE(Object.getOwnPropertyDescriptor(s,e)[t]))}catch{}}});var Fh=b((h$,_h)=>{"use strict";var wE=It();_h.exports=function(s){return wE(s)||s===null}});var Uh=b((f$,Nh)=>{"use strict";var AE=Fh(),PE=String,kE=TypeError;Nh.exports=function(s){if(AE(s))return s;throw new kE("Can't set "+PE(s)+" as a prototype")}});var Ou=b((m$,qh)=>{"use strict";var RE=Oh(),ME=It(),LE=Ii(),BE=Uh();qh.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var s=!1,e={},t;try{t=RE(Object.prototype,"__proto__","set"),t(e,[]),s=e instanceof Array}catch{}return function(r,a){return LE(r),BE(a),ME(r)&&(s?t(r,a):r.__proto__=a),r}}():void 0)});var Zh=b((b$,Jh)=>{"use strict";var $E=Oe(),DE=Tt(),dn=_t(),Kh=Pu(),CE=Me(),VE=Ch(),jh=rn(),Hh=Ou(),OE=rs(),_E=lr(),_u=hr(),FE=Ge(),zh=qi(),Xh=Vu(),NE=Kh.PROPER,UE=Kh.CONFIGURABLE,Qh=Xh.IteratorPrototype,pn=Xh.BUGGY_SAFARI_ITERATORS,ss=FE("iterator"),Gh="keys",as="values",Wh="entries",Yh=function(){return this};Jh.exports=function(s,e,t,i,r,a,n){VE(t,e,i);var o=function(T){if(T===r&&p)return p;if(!pn&&T&&T in d)return d[T];switch(T){case Gh:return function(){return new t(this,T)};case as:return function(){return new t(this,T)};case Wh:return function(){return new t(this,T)}}return function(){return new t(this)}},u=e+" Iterator",l=!1,d=s.prototype,c=d[ss]||d["@@iterator"]||r&&d[r],p=!pn&&c||o(r),h=e==="Array"&&d.entries||c,m,g,v;if(h&&(m=jh(h.call(new s)),m!==Object.prototype&&m.next&&(!dn&&jh(m)!==Qh&&(Hh?Hh(m,Qh):CE(m[ss])||_u(m,ss,Yh)),OE(m,u,!0,!0),dn&&(zh[u]=Yh))),NE&&r===as&&c&&c.name!==as&&(!dn&&UE?_E(d,"name",as):(l=!0,p=function(){return DE(c,this)})),r)if(g={values:o(as),keys:a?p:o(Gh),entries:o(Wh)},n)for(v in g)(pn||l||!(v in d))&&_u(d,v,g[v]);else $E({target:e,proto:!0,forced:pn||l},g);return(!dn||n)&&d[ss]!==p&&_u(d,ss,p,{name:r}),zh[e]=p,g}});var tf=b((g$,ef)=>{"use strict";ef.exports=function(s,e){return{value:s,done:e}}});var Nu=b((S$,of)=>{"use strict";var qE=_i(),Fu=es(),rf=qi(),af=Eu(),jE=Ni().f,HE=Zh(),hn=tf(),zE=_t(),QE=yt(),nf="Array Iterator",GE=af.set,WE=af.getterFor(nf);of.exports=HE(Array,"Array",function(s,e){GE(this,{type:nf,target:qE(s),index:0,kind:e})},function(){var s=WE(this),e=s.target,t=s.index++;if(!e||t>=e.length)return s.target=void 0,hn(void 0,!0);switch(s.kind){case"keys":return hn(t,!1);case"values":return hn(e[t],!1)}return hn([t,e[t]],!1)},"values");var sf=rf.Arguments=rf.Array;Fu("keys");Fu("values");Fu("entries");if(!zE&&QE&&sf.name!=="values")try{jE(sf,"name",{value:"values"})}catch{}});var lf=b((v$,uf)=>{"use strict";var YE=Ge(),KE=qi(),XE=YE("iterator"),JE=Array.prototype;uf.exports=function(s){return s!==void 0&&(KE.Array===s||JE[XE]===s)}});var Uu=b((y$,df)=>{"use strict";var ZE=is(),cf=Yr(),ew=sr(),tw=qi(),iw=Ge(),rw=iw("iterator");df.exports=function(s){if(!ew(s))return cf(s,rw)||cf(s,"@@iterator")||tw[ZE(s)]}});var hf=b((T$,pf)=>{"use strict";var sw=Tt(),aw=zt(),nw=Qt(),ow=Wr(),uw=Uu(),lw=TypeError;pf.exports=function(s,e){var t=arguments.length<2?uw(s):e;if(aw(t))return nw(sw(t,s));throw new lw(ow(s)+" is not iterable")}});var bf=b((I$,mf)=>{"use strict";var cw=Tt(),ff=Qt(),dw=Yr();mf.exports=function(s,e,t){var i,r;ff(s);try{if(i=dw(s,"return"),!i){if(e==="throw")throw t;return t}i=cw(i,s)}catch(a){r=!0,i=a}if(e==="throw")throw t;if(r)throw i;return ff(i),t}});var mn=b((x$,yf)=>{"use strict";var pw=ur(),hw=Tt(),fw=Qt(),mw=Wr(),bw=lf(),gw=pr(),gf=Gr(),Sw=hf(),vw=Uu(),Sf=bf(),yw=TypeError,fn=function(s,e){this.stopped=s,this.result=e},vf=fn.prototype;yf.exports=function(s,e,t){var i=t&&t.that,r=!!(t&&t.AS_ENTRIES),a=!!(t&&t.IS_RECORD),n=!!(t&&t.IS_ITERATOR),o=!!(t&&t.INTERRUPTED),u=pw(e,i),l,d,c,p,h,m,g,v=function(w){return l&&Sf(l,"normal",w),new fn(!0,w)},T=function(w){return r?(fw(w),o?u(w[0],w[1],v):u(w[0],w[1])):o?u(w,v):u(w)};if(a)l=s.iterator;else if(n)l=s;else{if(d=vw(s),!d)throw new yw(mw(s)+" is not iterable");if(bw(d)){for(c=0,p=gw(s);p>c;c++)if(h=T(s[c]),h&&gf(vf,h))return h;return new fn(!1)}l=Sw(s,d)}for(m=a?s.next:l.next;!(g=hw(m,l)).done;){try{h=T(g.value)}catch(w){Sf(l,"throw",w)}if(typeof h=="object"&&h&&gf(vf,h))return h}return new fn(!1)}});var If=b((E$,Tf)=>{"use strict";var Tw=yt(),Iw=Ni(),xw=Qr();Tf.exports=function(s,e,t){Tw?Iw.f(s,e,xw(0,t)):s[e]=t}});var xf=b(()=>{"use strict";var Ew=Oe(),ww=mn(),Aw=If();Ew({target:"Object",stat:!0},{fromEntries:function(e){var t={};return ww(e,function(i,r){Aw(t,i,r)},{AS_ENTRIES:!0}),t}})});var wf=b((P$,Ef)=>{"use strict";Nu();xf();var Pw=ar();Ef.exports=Pw.Object.fromEntries});var Pf=b((k$,Af)=>{"use strict";Af.exports={CSSRuleList:0,CSSStyleDeclaration:0,CSSValueList:0,ClientRectList:0,DOMRectList:0,DOMStringList:0,DOMTokenList:1,DataTransferItemList:0,FileList:0,HTMLAllCollection:0,HTMLCollection:0,HTMLFormElement:0,HTMLSelectElement:0,MediaList:0,MimeTypeArray:0,NamedNodeMap:0,NodeList:1,PaintRequestList:0,Plugin:0,PluginArray:0,SVGLengthList:0,SVGNumberList:0,SVGPathSegList:0,SVGPointList:0,SVGStringList:0,SVGTransformList:0,SourceBufferList:0,StyleSheetList:0,TextTrackCueList:0,TextTrackList:0,TouchList:0}});var Rf=b(()=>{"use strict";Nu();var kw=Pf(),Rw=De(),Mw=rs(),kf=qi();for(bn in kw)Mw(Rw[bn],bn),kf[bn]=kf.Array;var bn});var Lf=b((L$,Mf)=>{"use strict";var Lw=wf();Rf();Mf.exports=Lw});var qu=b((B$,Bf)=>{"use strict";var Bw=Lf();Bf.exports=Bw});var $f=b(()=>{"use strict"});var ju=b((C$,Df)=>{"use strict";var ns=De(),$w=Fi(),Dw=Oi(),gn=function(s){return $w.slice(0,s.length)===s};Df.exports=function(){return gn("Bun/")?"BUN":gn("Cloudflare-Workers")?"CLOUDFLARE":gn("Deno/")?"DENO":gn("Node.js/")?"NODE":ns.Bun&&typeof Bun.version=="string"?"BUN":ns.Deno&&typeof Deno.version=="object"?"DENO":Dw(ns.process)==="process"?"NODE":ns.window&&ns.document?"BROWSER":"REST"}()});var Sn=b((V$,Cf)=>{"use strict";var Cw=ju();Cf.exports=Cw==="NODE"});var Of=b((O$,Vf)=>{"use strict";var Vw=Ni();Vf.exports=function(s,e,t){return Vw.f(s,e,t)}});var Nf=b((_$,Ff)=>{"use strict";var Ow=oi(),_w=Of(),Fw=Ge(),Nw=yt(),_f=Fw("species");Ff.exports=function(s){var e=Ow(s);Nw&&e&&!e[_f]&&_w(e,_f,{configurable:!0,get:function(){return this}})}});var qf=b((F$,Uf)=>{"use strict";var Uw=Gr(),qw=TypeError;Uf.exports=function(s,e){if(Uw(e,s))return s;throw new qw("Incorrect invocation")}});var zu=b((N$,jf)=>{"use strict";var jw=je(),Hw=Me(),Hu=Kr(),zw=jw(Function.toString);Hw(Hu.inspectSource)||(Hu.inspectSource=function(s){return zw(s)});jf.exports=Hu.inspectSource});var Gu=b((U$,Wf)=>{"use strict";var Qw=je(),Gw=Qe(),Hf=Me(),Ww=is(),Yw=oi(),Kw=zu(),zf=function(){},Qf=Yw("Reflect","construct"),Qu=/^\s*(?:class|function)\b/,Xw=Qw(Qu.exec),Jw=!Qu.test(zf),os=function(e){if(!Hf(e))return!1;try{return Qf(zf,[],e),!0}catch{return!1}},Gf=function(e){if(!Hf(e))return!1;switch(Ww(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return Jw||!!Xw(Qu,Kw(e))}catch{return!0}};Gf.sham=!0;Wf.exports=!Qf||Gw(function(){var s;return os(os.call)||!os(Object)||!os(function(){s=!0})||s})?Gf:os});var Kf=b((q$,Yf)=>{"use strict";var Zw=Gu(),eA=Wr(),tA=TypeError;Yf.exports=function(s){if(Zw(s))return s;throw new tA(eA(s)+" is not a constructor")}});var Wu=b((j$,Jf)=>{"use strict";var Xf=Qt(),iA=Kf(),rA=sr(),sA=Ge(),aA=sA("species");Jf.exports=function(s,e){var t=Xf(s).constructor,i;return t===void 0||rA(i=Xf(t)[aA])?e:iA(i)}});var em=b((H$,Zf)=>{"use strict";var nA=je();Zf.exports=nA([].slice)});var im=b((z$,tm)=>{"use strict";var oA=TypeError;tm.exports=function(s,e){if(s<e)throw new oA("Not enough arguments");return s}});var Yu=b((Q$,rm)=>{"use strict";var uA=Fi();rm.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(uA)});var sl=b((G$,pm)=>{"use strict";var Et=De(),lA=No(),cA=ur(),sm=Me(),dA=Ft(),dm=Qe(),am=ku(),pA=em(),nm=Ja(),hA=im(),fA=Yu(),mA=Sn(),tl=Et.setImmediate,il=Et.clearImmediate,bA=Et.process,Ku=Et.Dispatch,gA=Et.Function,om=Et.MessageChannel,SA=Et.String,Xu=0,us={},um="onreadystatechange",ls,Hi,Ju,Zu;dm(function(){ls=Et.location});var rl=function(s){if(dA(us,s)){var e=us[s];delete us[s],e()}},el=function(s){return function(){rl(s)}},lm=function(s){rl(s.data)},cm=function(s){Et.postMessage(SA(s),ls.protocol+"//"+ls.host)};(!tl||!il)&&(tl=function(e){hA(arguments.length,1);var t=sm(e)?e:gA(e),i=pA(arguments,1);return us[++Xu]=function(){lA(t,void 0,i)},Hi(Xu),Xu},il=function(e){delete us[e]},mA?Hi=function(s){bA.nextTick(el(s))}:Ku&&Ku.now?Hi=function(s){Ku.now(el(s))}:om&&!fA?(Ju=new om,Zu=Ju.port2,Ju.port1.onmessage=lm,Hi=cA(Zu.postMessage,Zu)):Et.addEventListener&&sm(Et.postMessage)&&!Et.importScripts&&ls&&ls.protocol!=="file:"&&!dm(cm)?(Hi=cm,Et.addEventListener("message",lm,!1)):um in nm("script")?Hi=function(s){am.appendChild(nm("script"))[um]=function(){am.removeChild(this),rl(s)}}:Hi=function(s){setTimeout(el(s),0)});pm.exports={set:tl,clear:il}});var mm=b((W$,fm)=>{"use strict";var hm=De(),vA=yt(),yA=Object.getOwnPropertyDescriptor;fm.exports=function(s){if(!vA)return hm[s];var e=yA(hm,s);return e&&e.value}});var al=b((Y$,gm)=>{"use strict";var bm=function(){this.head=null,this.tail=null};bm.prototype={add:function(s){var e={item:s,next:null},t=this.tail;t?t.next=e:this.head=e,this.tail=e},get:function(){var s=this.head;if(s){var e=this.head=s.next;return e===null&&(this.tail=null),s.item}}};gm.exports=bm});var vm=b((K$,Sm)=>{"use strict";var TA=Fi();Sm.exports=/ipad|iphone|ipod/i.test(TA)&&typeof Pebble<"u"});var Tm=b((X$,ym)=>{"use strict";var IA=Fi();ym.exports=/web0s(?!.*chrome)/i.test(IA)});var km=b((J$,Pm)=>{"use strict";var mr=De(),xA=mm(),Im=ur(),nl=sl().set,EA=al(),wA=Yu(),AA=vm(),PA=Tm(),ol=Sn(),xm=mr.MutationObserver||mr.WebKitMutationObserver,Em=mr.document,wm=mr.process,vn=mr.Promise,cl=xA("queueMicrotask"),fr,ul,ll,yn,Am;cl||(cs=new EA,ds=function(){var s,e;for(ol&&(s=wm.domain)&&s.exit();e=cs.get();)try{e()}catch(t){throw cs.head&&fr(),t}s&&s.enter()},!wA&&!ol&&!PA&&xm&&Em?(ul=!0,ll=Em.createTextNode(""),new xm(ds).observe(ll,{characterData:!0}),fr=function(){ll.data=ul=!ul}):!AA&&vn&&vn.resolve?(yn=vn.resolve(void 0),yn.constructor=vn,Am=Im(yn.then,yn),fr=function(){Am(ds)}):ol?fr=function(){wm.nextTick(ds)}:(nl=Im(nl,mr),fr=function(){nl(ds)}),cl=function(s){cs.head||fr(),cs.add(s)});var cs,ds;Pm.exports=cl});var Mm=b((Z$,Rm)=>{"use strict";Rm.exports=function(s,e){try{arguments.length===1?console.error(s):console.error(s,e)}catch{}}});var Tn=b((eD,Lm)=>{"use strict";Lm.exports=function(s){try{return{error:!1,value:s()}}catch(e){return{error:!0,value:e}}}});var zi=b((tD,Bm)=>{"use strict";var kA=De();Bm.exports=kA.Promise});var br=b((iD,Vm)=>{"use strict";var RA=De(),ps=zi(),MA=Me(),LA=uu(),BA=zu(),$A=Ge(),$m=ju(),DA=_t(),dl=Yo(),Dm=ps&&ps.prototype,CA=$A("species"),pl=!1,Cm=MA(RA.PromiseRejectionEvent),VA=LA("Promise",function(){var s=BA(ps),e=s!==String(ps);if(!e&&dl===66||DA&&!(Dm.catch&&Dm.finally))return!0;if(!dl||dl<51||!/native code/.test(s)){var t=new ps(function(a){a(1)}),i=function(a){a(function(){},function(){})},r=t.constructor={};if(r[CA]=i,pl=t.then(function(){})instanceof i,!pl)return!0}return!e&&($m==="BROWSER"||$m==="DENO")&&!Cm});Vm.exports={CONSTRUCTOR:VA,REJECTION_EVENT:Cm,SUBCLASSING:pl}});var gr=b((rD,_m)=>{"use strict";var Om=zt(),OA=TypeError,_A=function(s){var e,t;this.promise=new s(function(i,r){if(e!==void 0||t!==void 0)throw new OA("Bad Promise constructor");e=i,t=r}),this.resolve=Om(e),this.reject=Om(t)};_m.exports.f=function(s){return new _A(s)}});var rb=b(()=>{"use strict";var FA=Oe(),NA=_t(),wn=Sn(),Ei=De(),Tr=Tt(),Fm=hr(),Nm=Ou(),UA=rs(),qA=Nf(),jA=zt(),En=Me(),HA=It(),zA=qf(),QA=Wu(),zm=sl().set,gl=km(),GA=Mm(),WA=Tn(),YA=al(),Qm=Eu(),An=zi(),Sl=br(),Gm=gr(),Pn="Promise",Wm=Sl.CONSTRUCTOR,KA=Sl.REJECTION_EVENT,XA=Sl.SUBCLASSING,hl=Qm.getterFor(Pn),JA=Qm.set,Sr=An&&An.prototype,Qi=An,In=Sr,Ym=Ei.TypeError,fl=Ei.document,vl=Ei.process,ml=Gm.f,ZA=ml,eP=!!(fl&&fl.createEvent&&Ei.dispatchEvent),Km="unhandledrejection",tP="rejectionhandled",Um=0,Xm=1,iP=2,yl=1,Jm=2,xn,qm,rP,jm,Zm=function(s){var e;return HA(s)&&En(e=s.then)?e:!1},eb=function(s,e){var t=e.value,i=e.state===Xm,r=i?s.ok:s.fail,a=s.resolve,n=s.reject,o=s.domain,u,l,d;try{r?(i||(e.rejection===Jm&&aP(e),e.rejection=yl),r===!0?u=t:(o&&o.enter(),u=r(t),o&&(o.exit(),d=!0)),u===s.promise?n(new Ym("Promise-chain cycle")):(l=Zm(u))?Tr(l,u,a,n):a(u)):n(t)}catch(c){o&&!d&&o.exit(),n(c)}},tb=function(s,e){s.notified||(s.notified=!0,gl(function(){for(var t=s.reactions,i;i=t.get();)eb(i,s);s.notified=!1,e&&!s.rejection&&sP(s)}))},ib=function(s,e,t){var i,r;eP?(i=fl.createEvent("Event"),i.promise=e,i.reason=t,i.initEvent(s,!1,!0),Ei.dispatchEvent(i)):i={promise:e,reason:t},!KA&&(r=Ei["on"+s])?r(i):s===Km&&GA("Unhandled promise rejection",t)},sP=function(s){Tr(zm,Ei,function(){var e=s.facade,t=s.value,i=Hm(s),r;if(i&&(r=WA(function(){wn?vl.emit("unhandledRejection",t,e):ib(Km,e,t)}),s.rejection=wn||Hm(s)?Jm:yl,r.error))throw r.value})},Hm=function(s){return s.rejection!==yl&&!s.parent},aP=function(s){Tr(zm,Ei,function(){var e=s.facade;wn?vl.emit("rejectionHandled",e):ib(tP,e,s.value)})},vr=function(s,e,t){return function(i){s(e,i,t)}},yr=function(s,e,t){s.done||(s.done=!0,t&&(s=t),s.value=e,s.state=iP,tb(s,!0))},bl=function(s,e,t){if(!s.done){s.done=!0,t&&(s=t);try{if(s.facade===e)throw new Ym("Promise can't be resolved itself");var i=Zm(e);i?gl(function(){var r={done:!1};try{Tr(i,e,vr(bl,r,s),vr(yr,r,s))}catch(a){yr(r,a,s)}}):(s.value=e,s.state=Xm,tb(s,!1))}catch(r){yr({done:!1},r,s)}}};if(Wm&&(Qi=function(e){zA(this,In),jA(e),Tr(xn,this);var t=hl(this);try{e(vr(bl,t),vr(yr,t))}catch(i){yr(t,i)}},In=Qi.prototype,xn=function(e){JA(this,{type:Pn,done:!1,notified:!1,parent:!1,reactions:new YA,rejection:!1,state:Um,value:void 0})},xn.prototype=Fm(In,"then",function(e,t){var i=hl(this),r=ml(QA(this,Qi));return i.parent=!0,r.ok=En(e)?e:!0,r.fail=En(t)&&t,r.domain=wn?vl.domain:void 0,i.state===Um?i.reactions.add(r):gl(function(){eb(r,i)}),r.promise}),qm=function(){var s=new xn,e=hl(s);this.promise=s,this.resolve=vr(bl,e),this.reject=vr(yr,e)},Gm.f=ml=function(s){return s===Qi||s===rP?new qm(s):ZA(s)},!NA&&En(An)&&Sr!==Object.prototype)){jm=Sr.then,XA||Fm(Sr,"then",function(e,t){var i=this;return new Qi(function(r,a){Tr(jm,i,r,a)}).then(e,t)},{unsafe:!0});try{delete Sr.constructor}catch{}Nm&&Nm(Sr,In)}FA({global:!0,constructor:!0,wrap:!0,forced:Wm},{Promise:Qi});UA(Qi,Pn,!1,!0);qA(Pn)});var ub=b((nD,ob)=>{"use strict";var nP=Ge(),ab=nP("iterator"),nb=!1;try{sb=0,Tl={next:function(){return{done:!!sb++}},return:function(){nb=!0}},Tl[ab]=function(){return this},Array.from(Tl,function(){throw 2})}catch{}var sb,Tl;ob.exports=function(s,e){try{if(!e&&!nb)return!1}catch{return!1}var t=!1;try{var i={};i[ab]=function(){return{next:function(){return{done:t=!0}}}},s(i)}catch{}return t}});var Il=b((oD,lb)=>{"use strict";var oP=zi(),uP=ub(),lP=br().CONSTRUCTOR;lb.exports=lP||!uP(function(s){oP.all(s).then(void 0,function(){})})});var cb=b(()=>{"use strict";var cP=Oe(),dP=Tt(),pP=zt(),hP=gr(),fP=Tn(),mP=mn(),bP=Il();cP({target:"Promise",stat:!0,forced:bP},{all:function(e){var t=this,i=hP.f(t),r=i.resolve,a=i.reject,n=fP(function(){var o=pP(t.resolve),u=[],l=0,d=1;mP(e,function(c){var p=l++,h=!1;d++,dP(o,t,c).then(function(m){h||(h=!0,u[p]=m,--d||r(u))},a)}),--d||r(u)});return n.error&&a(n.value),i.promise}})});var pb=b(()=>{"use strict";var gP=Oe(),SP=_t(),vP=br().CONSTRUCTOR,El=zi(),yP=oi(),TP=Me(),IP=hr(),db=El&&El.prototype;gP({target:"Promise",proto:!0,forced:vP,real:!0},{catch:function(s){return this.then(void 0,s)}});!SP&&TP(El)&&(xl=yP("Promise").prototype.catch,db.catch!==xl&&IP(db,"catch",xl,{unsafe:!0}));var xl});var hb=b(()=>{"use strict";var xP=Oe(),EP=Tt(),wP=zt(),AP=gr(),PP=Tn(),kP=mn(),RP=Il();xP({target:"Promise",stat:!0,forced:RP},{race:function(e){var t=this,i=AP.f(t),r=i.reject,a=PP(function(){var n=wP(t.resolve);kP(e,function(o){EP(n,t,o).then(i.resolve,r)})});return a.error&&r(a.value),i.promise}})});var fb=b(()=>{"use strict";var MP=Oe(),LP=gr(),BP=br().CONSTRUCTOR;MP({target:"Promise",stat:!0,forced:BP},{reject:function(e){var t=LP.f(this),i=t.reject;return i(e),t.promise}})});var wl=b((bD,mb)=>{"use strict";var $P=Qt(),DP=It(),CP=gr();mb.exports=function(s,e){if($P(s),DP(e)&&e.constructor===s)return e;var t=CP.f(s),i=t.resolve;return i(e),t.promise}});var Sb=b(()=>{"use strict";var VP=Oe(),OP=oi(),bb=_t(),_P=zi(),gb=br().CONSTRUCTOR,FP=wl(),NP=OP("Promise"),UP=bb&&!gb;VP({target:"Promise",stat:!0,forced:bb||gb},{resolve:function(e){return FP(UP&&this===NP?_P:this,e)}})});var vb=b(()=>{"use strict";rb();cb();pb();hb();fb();Sb()});var xb=b(()=>{"use strict";var qP=Oe(),jP=_t(),kn=zi(),HP=Qe(),Tb=oi(),Ib=Me(),zP=Wu(),yb=wl(),QP=hr(),Pl=kn&&kn.prototype,GP=!!kn&&HP(function(){Pl.finally.call({then:function(){}},function(){})});qP({target:"Promise",proto:!0,real:!0,forced:GP},{finally:function(s){var e=zP(this,Tb("Promise")),t=Ib(s);return this.then(t?function(i){return yb(e,s()).then(function(){return i})}:s,t?function(i){return yb(e,s()).then(function(){throw i})}:s)}});!jP&&Ib(kn)&&(Al=Tb("Promise").prototype.finally,Pl.finally!==Al&&QP(Pl,"finally",Al,{unsafe:!0}));var Al});var wb=b((xD,Eb)=>{"use strict";$f();vb();xb();var WP=xi();Eb.exports=WP("Promise","finally")});var Pb=b((ED,Ab)=>{"use strict";var YP=wb();Ab.exports=YP});var Rn=b((wD,kb)=>{"use strict";var KP=Pb();kb.exports=KP});var Cb=b(()=>{"use strict";var tk=Oe(),ik=yu().values;tk({target:"Object",stat:!0},{values:function(e){return ik(e)}})});var Ob=b((i0,Vb)=>{"use strict";Cb();var rk=ar();Vb.exports=rk.Object.values});var Fb=b((r0,_b)=>{"use strict";var sk=Ob();_b.exports=sk});var Gi=b((s0,Nb)=>{"use strict";var ak=Fb();Nb.exports=ak});var Xb=b(()=>{"use strict";var mk=Oe(),bk=nr(),gk=pr(),Sk=Zr(),vk=es();mk({target:"Array",proto:!0},{at:function(e){var t=bk(this),i=gk(t),r=Sk(e),a=r>=0?r:i+r;return a<0||a>=i?void 0:t[a]}});vk("at")});var Zb=b((uC,Jb)=>{"use strict";Xb();var yk=xi();Jb.exports=yk("Array","at")});var tg=b((lC,eg)=>{"use strict";var Tk=Zb();eg.exports=Tk});var Ut=b((cC,ig)=>{"use strict";var Ik=tg();ig.exports=Ik});var Ql=b((FV,Eg)=>{"use strict";var $k=Oi();Eg.exports=Array.isArray||function(e){return $k(e)==="Array"}});var Ag=b((NV,wg)=>{"use strict";var Dk=TypeError,Ck=9007199254740991;wg.exports=function(s){if(s>Ck)throw Dk("Maximum allowed index exceeded");return s}});var Rg=b((UV,kg)=>{"use strict";var Vk=Ql(),Ok=pr(),_k=Ag(),Fk=ur(),Pg=function(s,e,t,i,r,a,n,o){for(var u=r,l=0,d=n?Fk(n,o):!1,c,p;l<i;)l in t&&(c=d?d(t[l],l,e):t[l],a>0&&Vk(c)?(p=Ok(c),u=Pg(s,e,c,p,u,a-1)-1):(_k(u+1),s[u]=c),u++),l++;return u};kg.exports=Pg});var $g=b((qV,Bg)=>{"use strict";var Mg=Ql(),Nk=Gu(),Uk=It(),qk=Ge(),jk=qk("species"),Lg=Array;Bg.exports=function(s){var e;return Mg(s)&&(e=s.constructor,Nk(e)&&(e===Lg||Mg(e.prototype))?e=void 0:Uk(e)&&(e=e[jk],e===null&&(e=void 0))),e===void 0?Lg:e}});var Cg=b((jV,Dg)=>{"use strict";var Hk=$g();Dg.exports=function(s,e){return new(Hk(s))(e===0?0:e)}});var Vg=b(()=>{"use strict";var zk=Oe(),Qk=Rg(),Gk=zt(),Wk=nr(),Yk=pr(),Kk=Cg();zk({target:"Array",proto:!0},{flatMap:function(e){var t=Wk(this),i=Yk(t),r;return Gk(e),r=Kk(t,0),r.length=Qk(r,t,t,i,0,1,e,arguments.length>1?arguments[1]:void 0),r}})});var Og=b(()=>{"use strict";var Xk=es();Xk("flatMap")});var Fg=b((WV,_g)=>{"use strict";Vg();Og();var Jk=xi();_g.exports=Jk("Array","flatMap")});var Ug=b((YV,Ng)=>{"use strict";var Zk=Fg();Ng.exports=Zk});var ws=b((KV,qg)=>{"use strict";var eR=Ug();qg.exports=eR});var As=b((XV,jg)=>{"use strict";var tR=is(),iR=String;jg.exports=function(s){if(tR(s)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return iR(s)}});var Gl=b((JV,Hg)=>{"use strict";Hg.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 Gg=b((ZV,Qg)=>{"use strict";var rR=je(),sR=Ii(),aR=As(),Yl=Gl(),zg=rR("".replace),nR=RegExp("^["+Yl+"]+"),oR=RegExp("(^|[^"+Yl+"])["+Yl+"]+$"),Wl=function(s){return function(e){var t=aR(sR(e));return s&1&&(t=zg(t,nR,"")),s&2&&(t=zg(t,oR,"$1")),t}};Qg.exports={start:Wl(1),end:Wl(2),trim:Wl(3)}});var Xg=b((eO,Kg)=>{"use strict";var uR=Pu().PROPER,lR=Qe(),Wg=Gl(),Yg="\u200B\x85\u180E";Kg.exports=function(s){return lR(function(){return!!Wg[s]()||Yg[s]()!==Yg||uR&&Wg[s].name!==s})}});var Kl=b((tO,Jg)=>{"use strict";var cR=Gg().start,dR=Xg();Jg.exports=dR("trimStart")?function(){return cR(this)}:"".trimStart});var eS=b(()=>{"use strict";var pR=Oe(),Zg=Kl();pR({target:"String",proto:!0,name:"trimStart",forced:"".trimLeft!==Zg},{trimLeft:Zg})});var iS=b(()=>{"use strict";eS();var hR=Oe(),tS=Kl();hR({target:"String",proto:!0,name:"trimStart",forced:"".trimStart!==tS},{trimStart:tS})});var sS=b((nO,rS)=>{"use strict";iS();var fR=xi();rS.exports=fR("String","trimLeft")});var nS=b((oO,aS)=>{"use strict";var mR=sS();aS.exports=mR});var uS=b((uO,oS)=>{"use strict";var bR=nS();oS.exports=bR});var TS=b(()=>{"use strict"});var IS=b(()=>{"use strict"});var ES=b((_F,xS)=>{"use strict";var VR=It(),OR=Oi(),_R=Ge(),FR=_R("match");xS.exports=function(s){var e;return VR(s)&&((e=s[FR])!==void 0?!!e:OR(s)==="RegExp")}});var AS=b((FF,wS)=>{"use strict";var NR=Qt();wS.exports=function(){var s=NR(this),e="";return s.hasIndices&&(e+="d"),s.global&&(e+="g"),s.ignoreCase&&(e+="i"),s.multiline&&(e+="m"),s.dotAll&&(e+="s"),s.unicode&&(e+="u"),s.unicodeSets&&(e+="v"),s.sticky&&(e+="y"),e}});var RS=b((NF,kS)=>{"use strict";var UR=Tt(),qR=Ft(),jR=Gr(),HR=AS(),PS=RegExp.prototype;kS.exports=function(s){var e=s.flags;return e===void 0&&!("flags"in PS)&&!qR(s,"flags")&&jR(PS,s)?UR(HR,s):e}});var LS=b((UF,MS)=>{"use strict";var tc=je(),zR=nr(),QR=Math.floor,Zl=tc("".charAt),GR=tc("".replace),ec=tc("".slice),WR=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,YR=/\$([$&'`]|\d{1,2})/g;MS.exports=function(s,e,t,i,r,a){var n=t+s.length,o=i.length,u=YR;return r!==void 0&&(r=zR(r),u=WR),GR(a,u,function(l,d){var c;switch(Zl(d,0)){case"$":return"$";case"&":return s;case"`":return ec(e,0,t);case"'":return ec(e,n);case"<":c=r[ec(d,1,-1)];break;default:var p=+d;if(p===0)return l;if(p>o){var h=QR(p/10);return h===0?l:h<=o?i[h-1]===void 0?Zl(d,1):i[h-1]+Zl(d,1):l}c=i[p-1]}return c===void 0?"":c})}});var DS=b(()=>{"use strict";var KR=Oe(),XR=Tt(),rc=je(),BS=Ii(),JR=Me(),ZR=sr(),eM=ES(),$r=As(),tM=Yr(),iM=RS(),rM=LS(),sM=Ge(),aM=_t(),nM=sM("replace"),oM=TypeError,ic=rc("".indexOf),uM=rc("".replace),$S=rc("".slice),lM=Math.max;KR({target:"String",proto:!0},{replaceAll:function(e,t){var i=BS(this),r,a,n,o,u,l,d,c,p,h,m=0,g="";if(!ZR(e)){if(r=eM(e),r&&(a=$r(BS(iM(e))),!~ic(a,"g")))throw new oM("`.replaceAll` does not allow non-global regexes");if(n=tM(e,nM),n)return XR(n,e,i,t);if(aM&&r)return uM($r(i),e,t)}for(o=$r(i),u=$r(e),l=JR(t),l||(t=$r(t)),d=u.length,c=lM(1,d),p=ic(o,u);p!==-1;)h=l?$r(t(u,p,o)):rM(u,o,p,[],void 0,t),g+=$S(o,m,p)+h,m=p+d,p=p+c>o.length?-1:ic(o,u,p+c);return m<o.length&&(g+=$S(o,m)),g}})});var VS=b((HF,CS)=>{"use strict";TS();IS();DS();var cM=xi();CS.exports=cM("String","replaceAll")});var _S=b((zF,OS)=>{"use strict";var dM=VS();OS.exports=dM});var sc=b((QF,FS)=>{"use strict";var pM=_S();FS.exports=pM});var US=b((GF,NS)=>{"use strict";var hM=Zr(),fM=As(),mM=Ii(),bM=RangeError;NS.exports=function(e){var t=fM(mM(this)),i="",r=hM(e);if(r<0||r===1/0)throw new bM("Wrong number of repetitions");for(;r>0;(r>>>=1)&&(t+=t))r&1&&(i+=t);return i}});var QS=b((WF,zS)=>{"use strict";var HS=je(),gM=fu(),qS=As(),SM=US(),vM=Ii(),yM=HS(SM),TM=HS("".slice),IM=Math.ceil,jS=function(s){return function(e,t,i){var r=qS(vM(e)),a=gM(t),n=r.length,o=i===void 0?" ":qS(i),u,l;return a<=n||o===""?r:(u=a-n,l=yM(o,IM(u/o.length)),l.length>u&&(l=TM(l,0,u)),s?r+l:l+r)}};zS.exports={start:jS(!1),end:jS(!0)}});var WS=b((YF,GS)=>{"use strict";var xM=Fi();GS.exports=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(xM)});var YS=b(()=>{"use strict";var EM=Oe(),wM=QS().start,AM=WS();EM({target:"String",proto:!0,forced:AM},{padStart:function(e){return wM(this,e,arguments.length>1?arguments[1]:void 0)}})});var XS=b((JF,KS)=>{"use strict";YS();var PM=xi();KS.exports=PM("String","padStart")});var ZS=b((ZF,JS)=>{"use strict";var kM=XS();JS.exports=kM});var ac=b((eN,ev)=>{"use strict";var RM=ZS();ev.exports=RM});var SL={};yy(SL,{ChromecastState:()=>qr,HttpConnectionType:()=>Wa,Observable:()=>Jt.Observable,PlaybackState:()=>et,Player:()=>Qa,PredefinedQualityLimits:()=>jr,SDK_VERSION:()=>gL,Subject:()=>Jt.Subject,Subscription:()=>Jt.Subscription,Surface:()=>Ya,VERSION:()=>_o,ValueSubject:()=>Jt.ValueSubject,VideoFormat:()=>Ht,VideoQuality:()=>Jt.VideoQuality,clientChecker:()=>W,isMobile:()=>Ir});module.exports=Ty(SL);var _o="2.0.135-dev.ee4a31cc.0";var et=(r=>(r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused",r))(et||{}),Ht=(x=>(x.MPEG="MPEG",x.DASH="DASH",x.DASH_SEP="DASH_SEP",x.DASH_SEP_VK="DASH_SEP",x.DASH_WEBM="DASH_WEBM",x.DASH_WEBM_AV1="DASH_WEBM_AV1",x.DASH_STREAMS="DASH_STREAMS",x.DASH_WEBM_VK="DASH_WEBM",x.DASH_ONDEMAND="DASH_ONDEMAND",x.DASH_ONDEMAND_VK="DASH_ONDEMAND",x.DASH_LIVE="DASH_LIVE",x.DASH_LIVE_CMAF="DASH_LIVE_CMAF",x.DASH_LIVE_WEBM="DASH_LIVE_WEBM",x.HLS="HLS",x.HLS_ONDEMAND="HLS_ONDEMAND",x.HLS_JS="HLS",x.HLS_LIVE="HLS_LIVE",x.HLS_LIVE_CMAF="HLS_LIVE_CMAF",x.WEB_RTC_LIVE="WEB_RTC_LIVE",x))(Ht||{});var qr=(r=>(r.NOT_AVAILABLE="NOT_AVAILABLE",r.AVAILABLE="AVAILABLE",r.CONNECTING="CONNECTING",r.CONNECTED="CONNECTED",r))(qr||{}),Wa=(i=>(i.HTTP1="http1",i.HTTP2="http2",i.QUIC="quic",i))(Wa||{});var Ya=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(Ya||{}),jr=(i=>(i.TRAFFIC_SAVING="traffic_saving",i.HIGH_QUALITY="high_quality",i.UNKNOWN="unknown",i))(jr||{});var fy=H(xt(),1);var te=require("@vkontakte/videoplayer-shared");var Dp=s=>new Promise((e,t)=>{let i=document.createElement("script");i.setAttribute("src",s),i.onload=()=>e(),i.onerror=r=>t(r),document.body.appendChild(i)});var en=class{constructor(e){this.connection$=new te.ValueSubject(void 0);this.castState$=new te.ValueSubject("NOT_AVAILABLE");this.errorEvent$=new te.Subject;this.realCastState$=new te.ValueSubject("NOT_AVAILABLE");this.subscription=new te.Subscription;this.isDestroyed=!1;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=(0,te.isNonNullable)(window.chrome?.cast),r=!!window.__onGCastApiAvailable;i?this.initializeCastApi():(window.__onGCastApiAvailable=a=>{delete window.__onGCastApiAvailable,a&&!this.isDestroyed&&this.initializeCastApi()},r||Dp("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:te.ErrorCategory.NETWORK,message:"Script loading failed!"})))}connect(){cast.framework.CastContext.getInstance()?.requestSession()}disconnect(){cast.framework.CastContext.getInstance()?.getCurrentSession()?.endSession(!0)}stopMedia(){return new Promise((e,t)=>{cast.framework.CastContext.getInstance()?.getCurrentSession()?.getMediaSession()?.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){(0,te.isNonNullable)(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();(0,te.isNullable)(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();(0,te.isNullable)(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((0,te.fromEvent)(i,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(r=>{switch(r.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=i.getCurrentSession()?.getMediaSession()?.media?.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(0,te.assertNever)(r.sessionState)}})).add((0,te.merge)((0,te.fromEvent)(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe((0,te.tap)(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),(0,te.map)(r=>r.castState)),(0,te.observableFrom)([i.getCastState()])).pipe((0,te.filterChanged)(),(0,te.map)(jI),(0,te.tap)(r=>{this.log({message:`realCastState$: ${r}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{let a=r==="CONNECTED",n=(0,te.isNonNullable)(this.connection$.getValue());if(a&&!n){let o=i.getCurrentSession();(0,te.assertNonNullable)(o);let u=o.getCastDevice(),l=o.getMediaSession()?.media?.contentId;((0,te.isNullable)(l)||l===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:o,castDevice:u}))}else!a&&n&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(r==="CONNECTED"?(0,te.isNonNullable)(this.connection$.getValue())?"CONNECTED":"AVAILABLE":r)}))}initializeCastApi(){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{return}try{e.setOptions({receiverApplicationId:this.params.receiverApplicationId??t,autoJoinPolicy:i}),this.initListeners()}catch(r){this.errorEvent$.next({id:"ChromecastInitializer",category:te.ErrorCategory.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:r})}}},jI=s=>{switch(s){case cast.framework.CastState.NO_DEVICES_AVAILABLE:return"NOT_AVAILABLE";case cast.framework.CastState.NOT_CONNECTED:return"AVAILABLE";case cast.framework.CastState.CONNECTING:return"CONNECTING";case cast.framework.CastState.CONNECTED:return"CONNECTED";default:return(0,te.assertNever)(s)}};var _c=H(xt(),1),ty=H(Ui(),1),iy=H(qu(),1);var Bb=H(Rn(),1);var kl=require("@vkontakte/videoplayer-shared");var Le=(s,e=0,t=0)=>{switch(t){case 0:return s.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case 1:{if(e===0)return s;let i=new URL(s);return i.searchParams.append("playback_shift",e.toFixed(0)),i.toString()}case 2:{let i=new URL(s);return!i.searchParams.get("offset_p")&&e===0?s:(i.searchParams.set("offset_p",e.toFixed(0)),i.toString())}default:(0,kl.assertNever)(t)}return s},wi=(s,e)=>{switch(e){case 0:return NaN;case 1:{let t=new URL(s);return Number(t.searchParams.get("playback_shift"))}case 2:{let t=new URL(s);return Number(t.searchParams.get("offset_p")??0)}default:(0,kl.assertNever)(e)}};var _=(s,e,t=!1)=>{let i=s.getTransition();(t||!i||i.to===e)&&s.setState(e)};var Gt=require("@vkontakte/videoplayer-shared"),ie=class{constructor(e){this.transitionStarted$=new Gt.Subject;this.transitionEnded$=new Gt.Subject;this.transitionUpdated$=new Gt.Subject;this.forceChanged$=new Gt.Subject;this.stateChangeStarted$=(0,Gt.merge)(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=(0,Gt.merge)(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||(0,Gt.isNonNullable)(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}};var Rb=require("@vkontakte/videoplayer-shared"),Mb=s=>{switch(s){case"MPEG":case"DASH":case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":case"HLS":case"HLS_ONDEMAND":return!1;case"DASH_LIVE":case"DASH_LIVE_CMAF":case"HLS_LIVE":case"HLS_LIVE_CMAF":case"DASH_LIVE_WEBM":case"WEB_RTC_LIVE":return!0;default:return(0,Rb.assertNever)(s)}};var q=require("@vkontakte/videoplayer-shared");var XP=5,JP=5,ZP=500,Lb=7e3,hs=class{constructor(e){this.subscription=new q.Subscription;this.loadMediaTimeoutSubscription=new q.Subscription;this.videoState=new ie("stopped");this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(a)};`}),i==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.stop());return}if(!t){if(r?.to!=="paused"&&a.state==="requested"&&e!=="stopped"){this.seek(a.position/1e3);return}switch(i){case"ready":{switch(e){case"playing":case"paused":case"ready":break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:(0,q.assertNever)(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:(0,q.assertNever)(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:(0,q.assertNever)(e)}break}default:(0,q.assertNever)(i)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(Mb(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 q.Subscription;this.subscription.add(e),this.subscription.add((0,q.merge)(this.videoState.stateChangeStarted$.pipe((0,q.map)(r=>`stateChangeStarted$ ${JSON.stringify(r)}`)),this.videoState.stateChangeEnded$.pipe((0,q.map)(r=>`stateChangeEnded$ ${JSON.stringify(r)}`))).subscribe(r=>this.log({message:`[videoState] ${r}`})));let t=(r,a)=>this.subscription.add(r.subscribe(a));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{let r=new q.Subject;e.add(r.pipe((0,q.debounce)(ZP)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let a=NaN;e.add((0,q.fromEvent)(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-a)>XP)&&r.next(o),a=o})),e.add((0,q.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t((0,q.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t((0,q.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemotePause():this.handleRemotePlay()}),t((0,q.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),r=>{this.logRemoteEvent(r);let{remotePlayer:a}=this.params.connection,n=r.value,o=this.params.output.isBuffering$.getValue(),u=n===chrome.cast.media.PlayerState.BUFFERING;switch(o!==u&&this.params.output.isBuffering$.next(u),n){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&a.duration-a.currentTime<JP&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),_(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:(0,q.assertNever)(n)}}),t((0,q.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t((0,q.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({muted:r.value})});let i=(0,q.merge)(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,q.observableFrom)(["init"])).pipe((0,q.debounce)(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"),_(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),_(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();(this.videoState.getTransition()?.to==="paused"||e==="playing")&&(this.videoState.setState("paused"),_(this.params.desiredState.playbackState,"paused"))}handleRemotePlay(){let e=this.videoState.getState();(this.videoState.getTransition()?.to==="playing"||e==="paused")&&(this.videoState.setState("playing"),_(this.params.desiredState.playbackState,"playing"))}handleRemoteReady(){this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.params.desiredState.playbackState.getTransition()?.to==="ready"&&_(this.params.desiredState.playbackState,"ready")}handleRemoteStop(){this.videoState.getState()!=="stopped"&&this.videoState.setState("stopped")}handleRemoteVolumeChange(e){let t=this.params.output.volume$.getValue(),i={volume:e.volume??t.volume,muted:e.muted??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){let t=this.params.source,i,r,a;switch(e){case"MPEG":{let l=t[e];(0,q.assertNonNullable)(l);let d=(0,q.getHighestQuality)(Object.keys(l));(0,q.assertNonNullable)(d);let c=l[d];(0,q.assertNonNullable)(c),i=c,r="video/mp4",a=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let l=t[e];(0,q.assertNonNullable)(l),i=l.url,r="application/x-mpegurl",a=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":{let l=t[e];(0,q.assertNonNullable)(l),i=l.url,r="application/dash+xml",a=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let l=t[e];(0,q.assertNonNullable)(l),i=l.url,r="application/dash+xml",a=chrome.cast.media.StreamType.LIVE;break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let l=t[e];(0,q.assertNonNullable)(l),i=Le(l.url),r="application/x-mpegurl",a=chrome.cast.media.StreamType.LIVE;break}case"DASH_LIVE":case"WEB_RTC_LIVE":{let l="Unsupported format for Chromecast",d=new Error(l);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:q.ErrorCategory.VIDEO_PIPELINE,message:l,thrown:d}),d}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return(0,q.assertNever)(e)}let n=new chrome.cast.media.MediaInfo(this.params.meta.videoId??i,r);n.contentUrl=i,n.streamType=a,n.metadata=new chrome.cast.media.GenericMediaMetadata;let{title:o,subtitle:u}=this.params.meta;return(0,q.isNonNullable)(o)&&(n.metadata.title=o),(0,q.isNonNullable)(u)&&(n.metadata.subtitle=u),n}createLoadRequest(e){let t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;let i=this.params.desiredState.seekState.getState();return i.state==="applying"||i.state==="requested"?t.currentTime=this.params.output.isLive$.getValue()?0:i.position/1e3:t.currentTime=0,t}loadMedia(e){let t=this.params.connection.session.loadMedia(e),i=new Promise((r,a)=>{this.loadMediaTimeoutSubscription.add((0,q.timeout)(Lb).subscribe(()=>a(`timeout(${Lb})`)))});(0,Bb.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 a=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${r}`;this.log({message:a}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:q.ErrorCategory.VIDEO_PIPELINE,message:a,thrown:r})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var Hl=H(xt(),1);var Bl=require("@vkontakte/videoplayer-shared");var $b=require("@vkontakte/videoplayer-shared"),Db=s=>{try{s.pause(),s.playbackRate=0,(0,$b.clearVideoElement)(s),s.remove()}catch(e){console.error(e)}};var Mn=require("@vkontakte/videoplayer-shared"),Rl=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)}},Ml=window.WeakMap?new WeakMap:new Rl,Ll=window.WeakMap?new WeakMap:new Map,ek=(s,e=20)=>{let t=0;return(0,Mn.fromEvent)(s,"ratechange").subscribe(i=>{t++,t>=e&&(s.currentTime=s.currentTime,t=0)})},at=(s,{audioVideoSyncRate:e,disableYandexPiP:t})=>{let i=s.querySelector("video"),r=!!i;i?(0,Bl.clearVideoElement)(i):(i=document.createElement("video"),s.appendChild(i)),Ml.set(i,r);let a=new Mn.Subscription;return a.add(ek(i,e)),Ll.set(i,a),i.setAttribute("crossorigin","anonymous"),i.setAttribute("playsinline","playsinline"),t&&i.setAttribute("x-yandex-pip","false"),i.controls=!1,i.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),i},nt=s=>{Ll.get(s)?.unsubscribe(),Ll.delete(s);let t=Ml.get(s);Ml.delete(s),t?(0,Bl.clearVideoElement)(s):Db(s)};var $l=H(Gi(),1),j=require("@vkontakte/videoplayer-shared");var Ai=require("@vkontakte/videoplayer-shared"),Ln=(s,e,t,{equal:i=(n,o)=>n===o,changed$:r,onError:a}={})=>{let n=s.getState(),o=e(),u=(0,Ai.isNullable)(r),l=new Ai.Subscription;return r&&l.add(r.subscribe(d=>{let c=s.getState();i(d,c)&&s.setState(d)},a)),i(o,n)||(t(n),u&&s.setState(n)),l.add(s.stateChangeStarted$.subscribe(d=>{t(d.to),u&&s.setState(d.to)},a)),l},Wt=(s,e,t)=>Ln(e,()=>s.loop,i=>{(0,Ai.isNonNullable)(i)&&(s.loop=i)},{onError:t}),ot=(s,e,t,i)=>Ln(e,()=>({muted:s.muted,volume:s.volume}),r=>{(0,Ai.isNonNullable)(r)&&(s.muted=r.muted,s.volume=r.volume)},{equal:(r,a)=>r===a||r?.muted===a?.muted&&r?.volume===a?.volume,changed$:t,onError:i}),kt=(s,e,t,i)=>Ln(e,()=>s.playbackRate,r=>{(0,Ai.isNonNullable)(r)&&(s.playbackRate=r)},{changed$:t,onError:i}),fs=Ln;var nk=s=>["__",s.language,s.label].join("|"),ok=(s,e)=>{if(s.id===e)return!0;let[t,i,r]=e.split("|");return s.language===i&&s.label===r},Dl=class s{constructor(e){this.available$=new j.Subject;this.current$=new j.ValueSubject(void 0);this.error$=new j.Subject;this.subscription=new j.Subscription;this.externalTracks=new Map;this.internalTracks=new Map;this.baseURL=e}connect(e,t,i){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();let r=a=>{this.error$.next({id:"TextTracksManager",category:j.ErrorCategory.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:a})};this.subscription.add(this.available$.subscribe(i.availableTextTracks$)),this.subscription.add(this.current$.subscribe(i.currentTextTrack$)),this.subscription.add(this.error$.subscribe(i.error$)),this.subscription.add(fs(t.internalTextTracks,()=>(0,$l.default)(this.internalTracks),a=>{(0,j.isNonNullable)(a)&&this.setInternal(a)},{equal:(a,n)=>(0,j.isNonNullable)(a)&&(0,j.isNonNullable)(n)&&a.length===n.length&&a.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe((0,j.map)(a=>a.filter(({type:n})=>n==="internal"))),onError:r})),this.subscription.add(fs(t.externalTextTracks,()=>(0,$l.default)(this.externalTracks),a=>{(0,j.isNonNullable)(a)&&this.setExternal(a)},{equal:(a,n)=>(0,j.isNonNullable)(a)&&(0,j.isNonNullable)(n)&&a.length===n.length&&a.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe((0,j.map)(a=>a.filter(({type:n})=>n==="external"))),onError:r})),this.subscription.add(fs(t.currentTextTrack,()=>{if(this.video)return;let a=this.htmlTextTracksAsArray().find(({mode:n})=>n==="showing");return a&&this.htmlTextTrackToITextTrack(a).id},a=>this.select(a),{changed$:this.current$,onError:r})),this.subscription.add(fs(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let a of this.htmlTextTracksAsArray())this.applyCueSettings(a.cues),this.applyCueSettings(a.activeCues)}))}subscribe(){(0,j.assertNonNullable)(this.video);let{textTracks:e}=this.video;this.subscription.add((0,j.fromEvent)(e,"addtrack").subscribe(()=>{let i=this.current$.getValue();i&&this.select(i)})),this.subscription.add((0,j.merge)((0,j.fromEvent)(e,"addtrack"),(0,j.fromEvent)(e,"removetrack"),(0,j.observableFrom)(["init"])).pipe((0,j.map)(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),(0,j.filterChanged)((i,r)=>i.length===r.length&&i.every(({id:a},n)=>a===r[n].id))).subscribe(this.available$)),this.subscription.add((0,j.merge)((0,j.fromEvent)(e,"change"),(0,j.observableFrom)(["init"])).pipe((0,j.map)(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),(0,j.map)(i=>i&&this.htmlTextTrackToITextTrack(i).id),(0,j.filterChanged)()).subscribe(this.current$));let t=i=>this.applyCueSettings(i.target?.activeCues??null);this.subscription.add((0,j.fromEvent)(e,"addtrack").subscribe(i=>{i.track?.addEventListener("cuechange",t);let r=a=>{let n=a.target?.cues??null;n&&n.length&&(this.applyCueSettings(a.target?.cues??null),a.target?.removeEventListener("cuechange",r))};i.track?.addEventListener("cuechange",r)})),this.subscription.add((0,j.fromEvent)(e,"removetrack").subscribe(i=>{i.track?.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;(0,j.isNonNullable)(t.align)&&(r.align=t.align),(0,j.isNonNullable)(t.position)&&(r.position=t.position),(0,j.isNonNullable)(t.size)&&(r.size=t.size),(0,j.isNonNullable)(t.line)&&(r.line=t.line)}}htmlTextTracksAsArray(e=!1){(0,j.assertNonNullable)(this.video);let t=[...this.video.textTracks];return e?t:t.filter(s.isHealthyTrack)}htmlTextTrackToITextTrack(e){let{language:t,label:i}=e,r=e.id?e.id:nk(e),a=this.externalTracks.has(r),n=(a?this.externalTracks.get(r)?.isAuto:this.internalTracks.get(r)?.isAuto)??r.includes("auto");return a?{id:r,type:"external",isAuto:n,language:t,label:i,url:this.externalTracks.get(r)?.url}:{id:r,type:"internal",isAuto:n,language:t,label:i,url:this.internalTracks.get(r)?.url}}static isHealthyTrack(e){return!(e.kind==="metadata"||e.groupId||e.id===""&&e.label===""&&e.language==="")}setExternal(e){this.internalTracks.size>0&&Array.from(this.internalTracks).forEach(([,t])=>this.detach(t)),e.filter(({id:t})=>!this.externalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.externalTracks).filter(([t])=>!e.find(i=>i.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){let t=[...this.externalTracks];e.filter(({id:i,language:r,isAuto:a})=>!this.internalTracks.has(i)&&!t.some(([,n])=>n.language===r&&n.isAuto===a)).forEach(i=>this.attach(i)),Array.from(this.internalTracks).filter(([i])=>!e.find(r=>r.id===i)).forEach(([,i])=>this.detach(i))}select(e){(0,j.assertNonNullable)(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))((0,j.isNullable)(e)||!ok(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){(0,j.assertNonNullable)(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){(0,j.assertNonNullable)(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)}},Rt=Dl;var Wi=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 Ub=s=>{let e=s;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e?.parentNode;return e??void 0},Cl=s=>{let e=Ub(s);return!!(e&&e.fullscreenElement&&e.fullscreenElement===s)},qb=s=>{let e=Ub(s);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===s)};var O=require("@vkontakte/videoplayer-shared");var uk=3,jb=(s,e,t=uk)=>{let i=0,r=0;for(let a=0;a<s.length;a++){let n=s.start(a),o=s.end(a);if(n<=e&&e<=o){if(i=n,r=o,!t)return{from:i,to:r};for(let u=a-1;u>=0;u--)s.end(u)+t>=i&&(i=s.start(u));for(let u=a+1;u<s.length;u++)s.start(u)-t<=r&&(r=s.end(u))}}return{from:i,to:r}};var Bn=class{constructor(){this._isMiuiBrowser=!1}get current(){return this._current}get isChrome(){return this.current==="Chrome"}get isFirefox(){return this.current==="Firefox"}get isSafari(){return this.current==="Safari"}get isOpera(){return this.current==="Opera"}get isEdge(){return this.current==="Edge"}get isYandex(){return this.current==="Yandex"}get isSamsungBrowser(){return this.current==="SamsungBrowser"}get currentVersion(){return this._current_version}get chromeVersion(){return this._chromeVersion}get firefoxVersion(){return this._firefoxVersion}get safariVersion(){return this._safariVersion}get operaVersion(){return this._operaVersion}get edgeVersion(){return this._edgeVersion}get yandexVersion(){return this._yandexVersion}get isMiuiBrowser(){return this._isMiuiBrowser}detect(){let{userAgent:e}=navigator;try{let t=/yabrowser/i.test(e)?"Yandex":void 0,i=/samsungbrowser/i.test(e)?"SamsungBrowser":void 0,r=/chrome|crios/i.test(e)?"Chrome":void 0,a=/chromium/i.test(e)?"Chromium":void 0,n=/firefox|fxios/i.test(e)?"Firefox":void 0,o=/webkit|safari|khtml/i.test(e)?"Safari":void 0,u=/opr\//i.test(e)?"Opera":void 0,l=/edg/i.test(e)?"Edge":void 0;this._isMiuiBrowser=/(XiaoMi)|(MiuiBrowser)/i.test(e),this._current=t||i||n||u||l||r||a||o||"Rest"}catch(t){console.error(t)}this.isChrome&&this.detectChromeVersion(),this.isFirefox&&this.detectFirefoxVersion(),this.isSafari&&this.detectSafariVersion(),this.isOpera&&this.detectOperaVersion(),this.isEdge&&this.detectEdgeVersion(),this.isYandex&&this.detectYandexVersion()}detectVersion(e){try{let{userAgent:t}=window.navigator,i=t.match(e);if(!i)return;let r=i[1],a=parseInt(r,10);if(!isNaN(a))return this._current_version=a,a}catch(t){console.error(t)}}detectChromeVersion(){this._chromeVersion=this.detectVersion(/Chrome\/(\d+\.\d+)/)}detectFirefoxVersion(){this._firefoxVersion=this.detectVersion(/Firefox\/(\d+\.\d+)/)}detectSafariVersion(){this._safariVersion=this.detectVersion(/Version\/(\d+)/)}detectOperaVersion(){this._operaVersion=this.detectVersion(/OPR\/(\d+\.\d+)/)}detectEdgeVersion(){this._edgeVersion=this.detectVersion(/Edg\/(\d+\.\d+)/)}detectYandexVersion(){this._yandexVersion=this.detectVersion(/YaBrowser\/(\d+\.\d+\.\d+)/)}};var Hb=H(xt(),1);var Ir=()=>/Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test(navigator.appVersion??navigator.userAgent)||navigator?.userAgentData?.mobile;var $n=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,Hb.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=Ir()}catch(t){console.error(t)}this.detectDevice(e),this.detectHighEntropyValues(),this.isIOS&&this.detectIOSVersion()}async detectHighEntropyValues(){let{userAgentData:e}=navigator;if(e?.getHighEntropyValues){let t=await e.getHighEntropyValues(["architecture","bitness","brands","mobile","platform","formFactor","model","platformVersion","wow64"]);this._highEntropyValues=t}}detectDevice(e){try{let t=/android/i.test(e)?"Android":void 0,i=/iphone/i.test(e)?"iPhone":void 0,r=/ipad/i.test(e)?"iPad":void 0,a=/ipod/i.test(e)?"iPod":void 0,n=/mac/i.test(e)?"Mac":void 0,o=/webOS|BlackBerry|IEMobile|Opera Mini/i.test(e)?"RestMobile":void 0;this._current=t||i||r||a||o||n||"Desktop"}catch(t){console.error(t)}}detectIOSVersion(){try{if(this._highEntropyValues.platformVersion){let a=this._highEntropyValues.platformVersion.split(".").slice(0,2).join("."),n=parseFloat(a);this._iosVersion=n;return}let{userAgent:e}=window.navigator,t=e.match(/OS (\d+(_\d+)?)/i);if(!t)return;let i=t[1].replace(/_/g,".");if(!i)return;let r=parseFloat(i);if(isNaN(r))return;this._iosVersion=r}catch(e){console.error(e)}}};var Dn=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(){let{maxTouchPoints:e}=navigator;try{this._maxTouchPoints=e??0,this._isHdr=!!matchMedia("(dynamic-range: high)")?.matches,this._colorDepth=screen.colorDepth}catch(t){console.error(t)}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(t){console.error(t)}}};var wt=()=>window.ManagedMediaSource||window.MediaSource,xr=()=>!!(window.ManagedMediaSource&&window.ManagedSourceBuffer?.prototype?.appendBuffer),zb=()=>!!(window.MediaSource&&window.SourceBuffer?.prototype?.appendBuffer),Cn=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;var lk=document.createElement("video"),ck='video/mp4; codecs="avc1.42000a,mp4a.40.2"',dk='video/mp4; codecs="hev1.1.6.L93.B0"',Qb='video/webm; codecs="vp09.00.10.08"',Gb='video/webm; codecs="av01.0.00M.08"',pk='audio/mp4; codecs="mp4a.40.2"',hk='audio/webm; codecs="opus"',Wb,fk=async()=>{if(!window.navigator.mediaCapabilities)return;let s={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=await Promise.all([window.navigator.mediaCapabilities.decodingInfo({...s,video:{...s.video,contentType:Gb}}),window.navigator.mediaCapabilities.decodingInfo({...s,video:{...s.video,contentType:Qb}})]);Wb={DASH_WEBM_AV1:e,DASH_WEBM:t}};fk().catch(s=>{console.log(lk),console.error(s)});var Vn=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 Wb}get supportedCodecs(){return Object.keys(this._codecs).filter(e=>this._codecs[e])}get nativeHlsSupported(){return this._nativeHlsSupported}detect(){this._video=document.createElement("video");try{this._protocols={mms:xr(),mse:zb(),hls:!!(this._video.canPlayType?.("application/x-mpegurl")||this._video.canPlayType?.("vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},this._containers={mp4:!!this._video.canPlayType?.("video/mp4"),webm:!!this._video.canPlayType?.("video/webm"),cmaf:!0};let e=!!wt()?.isTypeSupported?.(ck),t=!!wt()?.isTypeSupported?.(dk),i=!!wt()?.isTypeSupported?.(pk);this._codecs={h264:e,h265:t,vp9:!!wt()?.isTypeSupported?.(Qb),av1:!!wt()?.isTypeSupported?.(Gb),aac:i,opus:!!wt()?.isTypeSupported?.(hk),mpeg:(e||t)&&i},this._nativeHlsSupported=this._protocols.hls&&this._containers.mp4}catch(e){console.error(e)}try{this.destroyVideoElement()}catch(e){console.error("Error destroying video element:",e)}}destroyVideoElement(){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);this._video.parentNode?.replaceChild(e,this._video),this._video=null}};var Yb="audio/mpeg",On=class{supportMp3(){return this._codecs.mp3&&this._containers.mpeg}detect(){this._audio=document.createElement("audio");try{this._containers={mpeg:!!this._audio.canPlayType?.(Yb)},this._codecs={mp3:!!wt()?.isTypeSupported?.(Yb)}}catch(e){console.error(e)}try{this.destroyAudioElement()}catch(e){console.error("Error destroying audio element:",e)}}destroyAudioElement(){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);this._audio.parentNode?.replaceChild(e,this._audio),this._audio=null}};var Kb=require("@vkontakte/videoplayer-shared"),Vl=class{constructor(){this.isInited$=new Kb.ValueSubject(!1);this._displayChecker=new Dn,this._deviceChecker=new $n(this._displayChecker),this._browserChecker=new Bn,this._videoChecker=new Vn(this._deviceChecker,this._browserChecker),this._audioChecker=new On,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}async detect(){this._displayChecker.detect(),this._deviceChecker.detect(),this._browserChecker.detect(),this._videoChecker.detect(),this._audioChecker.detect(),this.isInited$.next(!0)}},W=new Vl;var ut=s=>{let e=I=>(0,O.fromEvent)(s,I).pipe((0,O.mapTo)(void 0)),t=new O.Subscription,i=()=>t.unsubscribe(),r=(0,O.merge)((0,O.fromEvent)(s,"progress"),(0,O.fromEvent)(s,"timeupdate")).pipe((0,O.map)(()=>jb(s.buffered,s.currentTime))),a=W.browser.isSafari?(0,O.combine)({play:e("play").pipe((0,O.once)()),playing:e("playing")}).pipe((0,O.mapTo)(void 0)):e("playing"),n=(0,O.fromEvent)(s,"volumechange").pipe((0,O.map)(()=>({muted:s.muted,volume:s.volume}))),o=(0,O.fromEvent)(s,"ratechange").pipe((0,O.map)(()=>s.playbackRate)),u=(0,O.fromEvent)(s,"error").pipe((0,O.filter)(()=>!!(s.error||s.played.length)),(0,O.map)(()=>{let I=s.error;return{id:I?`MediaError#${I.code}`:"HtmlVideoError",category:O.ErrorCategory.VIDEO_PIPELINE,message:I?I.message:"Error event from HTML video element",thrown:s.error??void 0}})),l=(0,O.fromEvent)(s,"timeupdate").pipe((0,O.map)(()=>s.currentTime)),d=["waiting","seeking","seeked","timeupdate"],c=new O.Subject,p=.3,h;t.add((0,O.merge)(...d.map(I=>(0,O.fromEvent)(s,I))).subscribe(I=>{let U=s.currentTime;s.loop&&(0,O.isNonNullable)(h)&&(0,O.isNonNullable)(U)&&h>=s.duration-p&&U<=p&&c.next(h),h=U}));let m=e("pause").pipe((0,O.filter)(()=>!s.error&&h!==s.duration)),g=(0,O.fromEvent)(s,"enterpictureinpicture"),v=(0,O.fromEvent)(s,"leavepictureinpicture"),T=new O.ValueSubject(qb(s));t.add(g.subscribe(()=>T.next(!0))),t.add(v.subscribe(()=>T.next(!1)));let w=new O.ValueSubject(Cl(s)),x=(0,O.fromEvent)(s,"fullscreenchange");t.add(x.pipe((0,O.map)(()=>Cl(s))).subscribe(w));let M=.1,B=1e3,F=(0,O.fromEvent)(s,"timeupdate").pipe((0,O.map)(I=>s.duration-s.currentTime<M),(0,O.filterChanged)()),G=(0,O.merge)(F.pipe((0,O.filter)(I=>!s.loop&&I)),(0,O.fromEvent)(s,"ended")).pipe((0,O.throttle)(B),(0,O.mapTo)(void 0)),D=(0,O.merge)(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(I=>(0,O.fromEvent)(s,I)),F.pipe((0,O.map)(I=>({type:I?"ended":"unknown"})))).pipe((0,O.map)(I=>W.browser.isFirefox&&I.type==="ended"?s.readyState<2:s.readyState<3),(0,O.filterChanged)());return{playing$:a,pause$:m,canplay$:e("canplay"),ended$:G,looped$:c,error$:u,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:l,durationChange$:(0,O.fromEvent)(s,"durationchange").pipe((0,O.map)(()=>s.duration)),isBuffering$:D,currentBuffer$:r,volumeState$:n,playbackRateState$:o,inPiP$:T,inFullscreen$:w,enterPip$:g,leavePip$:v,destroy:i}};var ci=require("@vkontakte/videoplayer-shared"),Pi=s=>{switch(s){case"mobile":return ci.VideoQuality.Q_144P;case"lowest":return ci.VideoQuality.Q_240P;case"low":return ci.VideoQuality.Q_360P;case"sd":case"medium":return ci.VideoQuality.Q_480P;case"hd":case"high":return ci.VideoQuality.Q_720P;case"fullhd":case"full":return ci.VideoQuality.Q_1080P;case"quadhd":case"quad":return ci.VideoQuality.Q_1440P;case"ultrahd":case"ultra":return ci.VideoQuality.Q_2160P}};var it=H(Ut(),1),Fl=H(xt(),1),Yi=H(Ui(),1),L=require("@vkontakte/videoplayer-shared");var Ol=!1,di={},rg=s=>{Ol=s},sg=()=>{di={}},ag=s=>{s(di)},ms=(s,e)=>{Ol&&(di.meta=di.meta??{},di.meta[s]=e)},tt=class{constructor(e){this.name=e}next(e){if(!Ol)return;di.series=di.series??{};let t=di.series[this.name]??[];t.push([Date.now(),e]),di.series[this.name]=t}};var _e=require("@vkontakte/videoplayer-shared");function _l(s,e,t){return!s.max&&s.min===e?"high_quality":!s.min&&s.max===t?"traffic_saving":"unknown"}function _n(s,e,t){return!!s&&_l(s,e,t)==="high_quality"}function Er(s,e,t){return(0,_e.isNullable)(s)||(0,_e.isNonNullable)(s.min)&&(0,_e.isNonNullable)(s.max)&&(0,_e.isLower)(s.max,s.min)||(0,_e.isNonNullable)(s.min)&&e&&(0,_e.isHigher)(s.min,e)||(0,_e.isNonNullable)(s.max)&&t&&(0,_e.isLower)(s.max,t)}function ng({limits:s,highestAvailableHeight:e,lowestAvailableHeight:t}){return Er({max:s?.max?(0,_e.videoHeightToQuality)(s.max):void 0,min:s?.min?(0,_e.videoHeightToQuality)(s.min):void 0},e?(0,_e.videoHeightToQuality)(e):void 0,t?(0,_e.videoHeightToQuality)(t):void 0)}var dg=new tt("best_bitrate"),Nn=(s,e,t)=>(e-t)*Math.pow(2,-10*s)+t;var wr=s=>(e,t)=>s*(Number(e.bitrate)-Number(t.bitrate)),ki=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=(0,L.now)()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},Un='Assertion "ABR Tracks is empty array" failed',Fn=new WeakMap,og=new WeakMap,ug=new WeakMap,bs=(s,e,t,i)=>{let r=[...e].sort(wr(1)),a=[...t].sort(wr(1)),n=a.filter(u=>(0,L.isNonNullable)(u.bitrate)&&(0,L.isNonNullable)(s.bitrate)?s.bitrate/u.bitrate>i:!0),o=(0,it.default)(a,Math.round(a.length*r.indexOf(s)/(r.length+1)))??(0,it.default)(a,-1);return o&&(0,Fl.default)(n,o)?o:n.length?(0,it.default)(n,-1):(0,it.default)(a,0)},gs=(s,e,t,i)=>{let r=Fn.get(e);r||(r=[...e].sort(wr(1)),Fn.set(e,r));let a=Fn.get(t);a||(a=[...t].sort(wr(1)),Fn.set(t,a));let n=ug.get(s);n||(n=a.filter(u=>(0,L.isNonNullable)(u.bitrate)&&(0,L.isNonNullable)(s.bitrate)?s.bitrate/u.bitrate>i:!0),ug.set(s,n));let o=(0,it.default)(a,Math.round(a.length*r.indexOf(s)/(r.length+1)))??(0,it.default)(a,-1);return o&&(0,Fl.default)(n,o)?o:n.length?(0,it.default)(n,-1):(0,it.default)(a,0)},lg=s=>"quality"in s,qn=(s,e,t,i)=>{let r=(0,L.isNonNullable)(i?.last?.bitrate)&&(0,L.isNonNullable)(t?.bitrate)&&i.last.bitrate<t.bitrate?s.trackCooldownIncreaseQuality:s.trackCooldownDecreaseQuality,a=t&&i&&i.history[t.id]&&(0,L.now)()-i.history[t.id]<=r&&(!i.last||t.id!==i.last.id);if(t?.id&&i&&!a&&i.recordSelection(t),a&&i?.last){let n=i.last;i?.recordSwitch(n);let o=lg(n)?"video":"audio",u=lg(n)?n.quality:n.bitrate;return e({message:`
|
|
8
8
|
[last ${o} selected] ${u}
|
|
9
|
-
`}),n}return i?.recordSwitch(t),t},xk=(s,e)=>Math.log(e)/Math.log(s),pg=({tuning:s,container:e,limits:t,panelSize:i})=>{let r=s.containerSizeFactor;if(i)return{containerSizeLimit:i,containerSizeFactor:r};if(s.usePixelRatio&&W.display.pixelRatio){let a=W.display.pixelRatio;if(s.pixelRatioMultiplier)r*=s.pixelRatioMultiplier*(a-1)+1;else{let n=s.pixelRatioLogBase,[o=0,u=0,l=0]=s.pixelRatioLogCoefficients,
|
|
9
|
+
`}),n}return i?.recordSwitch(t),t},xk=(s,e)=>Math.log(e)/Math.log(s),pg=({tuning:s,container:e,limits:t,panelSize:i})=>{let r=s.containerSizeFactor;if(i)return{containerSizeLimit:i,containerSizeFactor:r};if(s.usePixelRatio&&W.display.pixelRatio){let a=W.display.pixelRatio;if(s.pixelRatioMultiplier)r*=s.pixelRatioMultiplier*(a-1)+1;else{let n=s.pixelRatioLogBase,[o=0,u=0,l=0]=s.pixelRatioLogCoefficients,d=xk(n,o*a+u)+l;Number.isFinite(d)&&(r*=d)}}return _n(t,s.highQualityLimit,s.trafficSavingLimit)&&(r*=2),{containerSizeLimit:s.limitByContainer&&e&&e.width>0&&e.height>0?{width:e.width*r,height:e.height*r}:void 0,containerSizeFactor:r}},cg=new WeakMap,Yt=(s,{container:e,estimatedThroughput:t,tuning:i,limits:r,reserve:a=0,forwardBufferHealth:n,playbackRate:o,current:u,history:l,visible:d,droppedVideoMaxQualityLimit:c,stallsVideoMaxQualityLimit:p,stallsPredictedThroughput:h,abrLogger:m,panelSize:g})=>{(0,L.assertNotEmptyArray)(s,Un);let{containerSizeFactor:v,containerSizeLimit:T}=pg({container:e,tuning:i,limits:r,panelSize:g}),w=i.considerPlaybackRate&&(0,L.isNonNullable)(o)?o:1,x=cg.get(s);x||(x=s.filter(R=>!(0,L.isInvariantQuality)(R.quality)).sort((R,C)=>(0,L.isHigher)(R.quality,C.quality)?-1:1),cg.set(s,x));let M=(0,it.default)(x,-1)?.quality,B=(0,it.default)(x,0)?.quality,F=Er(r,B,M),G=w*Nn(n??.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),$={},D=null;for(let R of x){let C=!0;if(T)if(R.size)C=R.size.width<=T.width&&R.size.height<=T.height;else{let V=T&&(0,L.videoSizeToQuality)(T);C=V?(0,L.isLowerOrEqual)(R.quality,V):!0}if(!C){$[R.quality]="FitsContainer";continue}let be=h||t,N=(0,L.isNonNullable)(be)&&isFinite(be)&&(0,L.isNonNullable)(R.bitrate)?be-a>=R.bitrate*G:!0,re=_n(r,i.highQualityLimit,i.trafficSavingLimit)&&r?.min===R.quality;if(!N&&!re){$[R.quality]="FitsThroughput";continue}if(i.lazyQualitySwitch&&(0,L.isNonNullable)(i.minBufferToSwitchUp)&&u&&!(0,L.isInvariantQuality)(u.quality)&&(n??0)<i.minBufferToSwitchUp&&(0,L.isHigher)(R.quality,u.quality)){$[R.quality]="Buffer";continue}if(!!c&&(0,L.isHigherOrEqual)(R.quality,c)&&!re){$[R.quality]="DroppedFramesLimit";continue}if(!!p&&(0,L.isHigherOrEqual)(R.quality,p)&&!re){$[R.quality]="StallsLimit";continue}let Ie=F||((0,L.isNullable)(r?.max)||(0,L.isLowerOrEqual)(R.quality,r.max))&&((0,L.isNullable)(r?.min)||(0,L.isHigherOrEqual)(R.quality,r.min)),ce=(0,L.isNonNullable)(d)&&!d?(0,L.isLowerOrEqual)(R.quality,i.backgroundVideoQualityLimit):!0;if(!Ie||!ce){$[R.quality]="FitsQualityLimits";continue}D||(D=R)}D&&D.bitrate&&dg.next(D.bitrate);let I=D??(0,it.default)(x,-1)??s[0],U=l?.last,k=qn(i,m,I,l);return(0,L.isNonNullable)(l)&&k.quality!==U?.quality&&m({message:`
|
|
10
10
|
[VIDEO TRACKS ABR]
|
|
11
11
|
[available video tracks]
|
|
12
12
|
${s.map(R=>`{ id: ${R.id}, quality: ${R.quality}, bitrate: ${R.bitrate}, size: ${R.size?.width}:${R.size?.height} }`).join(`
|
|
@@ -23,12 +23,12 @@
|
|
|
23
23
|
stallsPredictedThroughput: ${h},
|
|
24
24
|
reserve: ${a},
|
|
25
25
|
playbackRate: ${o},
|
|
26
|
-
playbackRateFactor: ${
|
|
26
|
+
playbackRateFactor: ${w},
|
|
27
27
|
forwardBufferHealth: ${n},
|
|
28
28
|
bitrateFactor: ${G},
|
|
29
29
|
minBufferToSwitchUp: ${i.minBufferToSwitchUp},
|
|
30
30
|
droppedVideoMaxQualityLimit: ${c},
|
|
31
|
-
stallsVideoMaxQualityLimit: ${
|
|
31
|
+
stallsVideoMaxQualityLimit: ${p},
|
|
32
32
|
limitsAreInvalid: ${F},
|
|
33
33
|
maxQualityLimit: ${r?.max},
|
|
34
34
|
minQualityLimit: ${r?.min},
|
|
@@ -39,7 +39,7 @@
|
|
|
39
39
|
|
|
40
40
|
[best video track] ${D?.quality}
|
|
41
41
|
[selected video track] ${k?.quality}
|
|
42
|
-
`}),k},
|
|
42
|
+
`}),k},jn=(s,{container:e,estimatedThroughput:t,tuning:i,limits:r,reserve:a=0,forwardBufferHealth:n,playbackRate:o,current:u,history:l,visible:d,droppedVideoMaxQualityLimit:c,stallsVideoMaxQualityLimit:p,stallsPredictedThroughput:h,abrLogger:m,panelSize:g})=>{(0,L.assertNotEmptyArray)(s,Un);let{containerSizeFactor:v,containerSizeLimit:T}=pg({container:e,tuning:i,limits:r,panelSize:g}),w=i.considerPlaybackRate&&(0,L.isNonNullable)(o)?o:1,x=s.filter(C=>!(0,L.isInvariantQuality)(C.quality)).sort((C,be)=>(0,L.isHigher)(C.quality,be.quality)?-1:1),M=(0,it.default)(x,-1)?.quality,B=(0,it.default)(x,0)?.quality,F=Er(r,B,M),G=w*Nn(n??.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),$={},I=x.filter(C=>{let be=!0;if(T)if(C.size)be=C.size.width<=T.width&&C.size.height<=T.height;else{let z=T&&(0,L.videoSizeToQuality)(T);be=z?(0,L.isLowerOrEqual)(C.quality,z):!0}if(!be)return $[C.quality]="FitsContainer",!1;let N=h||t,re=(0,L.isNonNullable)(N)&&isFinite(N)&&(0,L.isNonNullable)(C.bitrate)?N-a>=C.bitrate*G:!0,le=_n(r,i.highQualityLimit,i.trafficSavingLimit)&&r?.min===C.quality;if(!re&&!le)return $[C.quality]="FitsThroughput",!1;if(i.lazyQualitySwitch&&(0,L.isNonNullable)(i.minBufferToSwitchUp)&&u&&!(0,L.isInvariantQuality)(u.quality)&&(n??0)<i.minBufferToSwitchUp&&(0,L.isHigher)(C.quality,u.quality))return $[C.quality]="Buffer",!1;if(!!c&&(0,L.isHigherOrEqual)(C.quality,c)&&!le)return $[C.quality]="DroppedFramesLimit",!1;if(!!p&&(0,L.isHigherOrEqual)(C.quality,p)&&!le)return $[C.quality]="StallsLimit",!1;let ce=F||((0,L.isNullable)(r?.max)||(0,L.isLowerOrEqual)(C.quality,r.max))&&((0,L.isNullable)(r?.min)||(0,L.isHigherOrEqual)(C.quality,r.min)),V=(0,L.isNonNullable)(d)&&!d?(0,L.isLowerOrEqual)(C.quality,i.backgroundVideoQualityLimit):!0;return!ce||!V?($[C.quality]="FitsQualityLimits",!1):!0})[0];I&&I.bitrate&&dg.next(I.bitrate);let U=I??(0,it.default)(x,-1)??s[0],k=l?.last,R=qn(i,m,U,l);return(0,L.isNonNullable)(l)&&R.quality!==k?.quality&&m({message:`
|
|
43
43
|
[VIDEO TRACKS ABR]
|
|
44
44
|
[available video tracks]
|
|
45
45
|
${s.map(C=>`{ id: ${C.id}, quality: ${C.quality}, bitrate: ${C.bitrate}, size: ${C.size?.width}:${C.size?.height} }`).join(`
|
|
@@ -56,12 +56,12 @@
|
|
|
56
56
|
stallsPredictedThroughput: ${h},
|
|
57
57
|
reserve: ${a},
|
|
58
58
|
playbackRate: ${o},
|
|
59
|
-
playbackRateFactor: ${
|
|
59
|
+
playbackRateFactor: ${w},
|
|
60
60
|
forwardBufferHealth: ${n},
|
|
61
61
|
bitrateFactor: ${G},
|
|
62
62
|
minBufferToSwitchUp: ${i.minBufferToSwitchUp},
|
|
63
63
|
droppedVideoMaxQualityLimit: ${c},
|
|
64
|
-
stallsVideoMaxQualityLimit: ${
|
|
64
|
+
stallsVideoMaxQualityLimit: ${p},
|
|
65
65
|
limitsAreInvalid: ${F},
|
|
66
66
|
maxQualityLimit: ${r?.max},
|
|
67
67
|
minQualityLimit: ${r?.min},
|
|
@@ -72,56 +72,56 @@
|
|
|
72
72
|
|
|
73
73
|
[best video track] ${I?.quality}
|
|
74
74
|
[selected video track] ${R?.quality}
|
|
75
|
-
`}),R},
|
|
75
|
+
`}),R},Hn=(s,e,t,{estimatedThroughput:i,tuning:r,playbackRate:a,forwardBufferHealth:n,history:o,abrLogger:u,stallsPredictedThroughput:l})=>{(0,L.assertNotEmptyArray)(t,Un);let d=r.considerPlaybackRate&&(0,L.isNonNullable)(a)?a:1,c=[...t].sort(wr(-1)),p=s.bitrate;(0,L.assertNonNullable)(p);let h=d*Nn(n??.5,r.bitrateAudioFactorAtEmptyBuffer,r.bitrateAudioFactorAtFullBuffer),m,g=bs(s,e,t,r.minVideoAudioRatio),v=l||i;(0,L.isNonNullable)(v)&&isFinite(v)&&(m=c.find(x=>(0,L.isNonNullable)(x.bitrate)&&(0,L.isNonNullable)(g?.bitrate)?v-p>=x.bitrate*h&&x.bitrate>=g.bitrate:!1)),m||(m=g);let T=o?.last,w=m&&qn(r,u,m,o);return(0,L.isNonNullable)(o)&&w?.bitrate!==T?.bitrate&&u({message:`
|
|
76
76
|
[AUDIO TRACKS ABR]
|
|
77
77
|
[available audio tracks]
|
|
78
78
|
${t.map(x=>`{ id: ${x.id}, bitrate: ${x.bitrate} }`).join(`
|
|
79
79
|
`)}
|
|
80
80
|
|
|
81
81
|
[tuning]
|
|
82
|
-
${(0,Yi.default)(r??{}).map(([x,
|
|
82
|
+
${(0,Yi.default)(r??{}).map(([x,M])=>`${x}: ${M}`).join(`
|
|
83
83
|
`)}
|
|
84
84
|
|
|
85
85
|
[limit params]
|
|
86
86
|
estimatedThroughput: ${i},
|
|
87
87
|
stallsPredictedThroughput: ${l},
|
|
88
|
-
reserve: ${
|
|
88
|
+
reserve: ${p},
|
|
89
89
|
playbackRate: ${a},
|
|
90
|
-
playbackRateFactor: ${
|
|
90
|
+
playbackRateFactor: ${d},
|
|
91
91
|
forwardBufferHealth: ${n},
|
|
92
92
|
bitrateFactor: ${h},
|
|
93
93
|
minBufferToSwitchUp: ${r.minBufferToSwitchUp},
|
|
94
94
|
|
|
95
|
-
[selected audio track] ${
|
|
96
|
-
`}),
|
|
95
|
+
[selected audio track] ${w?.id}
|
|
96
|
+
`}),w},zn=(s,e,t,{estimatedThroughput:i,tuning:r,playbackRate:a,forwardBufferHealth:n,history:o,abrLogger:u,stallsPredictedThroughput:l})=>{(0,L.assertNotEmptyArray)(t,Un);let d=r.considerPlaybackRate&&(0,L.isNonNullable)(a)?a:1,c=og.get(t);c||(c=[...t].sort(wr(-1)),og.set(t,c));let p=s.bitrate;(0,L.assertNonNullable)(p);let h=d*Nn(n??.5,r.bitrateAudioFactorAtEmptyBuffer,r.bitrateAudioFactorAtFullBuffer),m,g=gs(s,e,t,r.minVideoAudioRatio),v=l||i;(0,L.isNonNullable)(v)&&isFinite(v)&&(m=c.find(x=>(0,L.isNonNullable)(x.bitrate)&&(0,L.isNonNullable)(g?.bitrate)?v-p>=x.bitrate*h&&x.bitrate>=g.bitrate:!1)),m||(m=g);let T=o?.last,w=m&&qn(r,u,m,o);return(0,L.isNonNullable)(o)&&w?.bitrate!==T?.bitrate&&u({message:`
|
|
97
97
|
[AUDIO TRACKS ABR]
|
|
98
98
|
[available audio tracks]
|
|
99
99
|
${t.map(x=>`{ id: ${x.id}, bitrate: ${x.bitrate} }`).join(`
|
|
100
100
|
`)}
|
|
101
101
|
|
|
102
102
|
[tuning]
|
|
103
|
-
${(0,Yi.default)(r??{}).map(([x,
|
|
103
|
+
${(0,Yi.default)(r??{}).map(([x,M])=>`${x}: ${M}`).join(`
|
|
104
104
|
`)}
|
|
105
105
|
|
|
106
106
|
[limit params]
|
|
107
107
|
estimatedThroughput: ${i},
|
|
108
108
|
stallsPredictedThroughput: ${l},
|
|
109
|
-
reserve: ${
|
|
109
|
+
reserve: ${p},
|
|
110
110
|
playbackRate: ${a},
|
|
111
|
-
playbackRateFactor: ${
|
|
111
|
+
playbackRateFactor: ${d},
|
|
112
112
|
forwardBufferHealth: ${n},
|
|
113
113
|
bitrateFactor: ${h},
|
|
114
114
|
minBufferToSwitchUp: ${r.minBufferToSwitchUp},
|
|
115
115
|
|
|
116
|
-
[selected audio track] ${
|
|
117
|
-
`}),P};var We=s=>new URL(s).hostname;var Q=require("@vkontakte/videoplayer-shared");var Sg=j(Ut(),1);var fg=j(xt(),1),hg=s=>{if(s instanceof DOMException&&(0,fg.default)(["Failed to load because no supported source was found.","The element has no supported sources."],s.message))throw s;return!(s instanceof DOMException&&(s.code===20||s.name==="AbortError"))},lt=async(s,e)=>{let t=s.muted;try{await s.play()}catch(i){if(!hg(i))return!1;if(e&&e(),t)return console.warn(i),!1;s.muted=!0;try{await s.play()}catch(r){return hg(r)&&(s.muted=!1,console.warn(r)),!1}}return!0};var Pt=require("@vkontakte/videoplayer-shared");var mg=j(Gi(),1),Kt=require("@vkontakte/videoplayer-shared");function je(){return(0,Kt.now)()}function Nl(s){return je()-s}function Ul(s){let e=s.split("/"),t=e.slice(0,e.length-1).join("/"),i=/^([a-z]+:)?\/\//i,r=n=>i.test(n);return{resolve:(n,o,u=!1)=>{r(n)||(n.startsWith("/")||(n="/"+n),n=t+n);let l=n.indexOf("?")>-1?"&":"?";return u&&(n+=l+"lowLat=1",l="&"),o&&(n+=l+"_rnd="+Math.floor(999999999*Math.random())),n}}}function bg(s,e,t){let i=(...r)=>{t.apply(null,r),s.removeEventListener(e,i)};s.addEventListener(e,i)}function Pr(s,e,t,i){let r=window.XMLHttpRequest,a,n,o,u=!1,l=0,p,c,d=!1,h="arraybuffer",m=7e3,g=2e3,v=()=>{if(u)return;(0,Kt.assertNonNullable)(p);let k=Nl(p),R;if(k<g){R=g-k,setTimeout(v,R);return}g*=2,g>m&&(g=m),n&&n.abort(),n=new r,F()},T=k=>(a=k,U),P=k=>(c=k,U),x=()=>(h="json",U),L=()=>{if(!u){if(--l>=0){v(),i&&i();return}u=!0,c&&c(),t&&t()}},B=k=>(d=k,U),F=()=>{p=je(),n=new r,n.open("get",s);let k=0,R,C=0,be=()=>((0,Kt.assertNonNullable)(p),Math.max(p,Math.max(R||0,C||0)));if(a&&n.addEventListener("progress",N=>{let re=je();a.updateChunk&&N.loaded>k&&(a.updateChunk(be(),N.loaded-k),k=N.loaded,R=re)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>L())),n.addEventListener("load",()=>{if(u)return;(0,Kt.assertNonNullable)(n);let N=n.status;if(N>=200&&N<300){let{response:re,responseType:le}=n,Te=re?.byteLength;if(typeof Te=="number"&&a){let Be=Te-k;Be&&a.updateChunk&&a.updateChunk(be(),Be)}le==="json"&&(!re||!(0,mg.default)(re).length)?L():(c&&c(),e(re))}else L()}),n.addEventListener("error",()=>{L()}),d){let N=()=>{(0,Kt.assertNonNullable)(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(C=je(),n.removeEventListener("readystatechange",N))};n.addEventListener("readystatechange",N)}return n.responseType=h,n.send(),U},U={withBitrateReporting:T,withParallel:B,withJSONResponse:x,withRetryCount:k=>(l=k,U),withRetryInterval:(k,R)=>((0,Kt.isNonNullable)(k)&&(g=k),(0,Kt.isNonNullable)(R)&&(m=R),U),withTimeout:k=>(o=k,U),withFinally:P,send:F,abort:()=>{n&&(n.abort(),n=void 0),u=!0,c&&c()}};return U}var Ss=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 a=this.intervals[0];if(a.end<=t)i+=a.end-a.start,r+=a.bytes,this.intervals.splice(0,1);else{if(a.start>=t)break;{let n=t-a.start,o=a.end-a.start;i+=n;let u=a.bytes*n/o;r+=u,a.start=t,a.bytes-=u}}}if(r>0&&i>0){let a=r*8/(i/1e3);return this._updateRate(a),this.logger(`rate updated, new=${Math.round(a/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 gg=j(Gi(),1);var vs=class{constructor(e,t,i,r,a){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=a}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=je(),r=u=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=u,e._errorCB?e._errorCB(u):(this.limitCompleteCount(),this.completeRequests[t]=e)},a=u=>{e._complete=1,e._responseData=u,e._downloadTime=je()-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=Pr(t,a,()=>r("error"),o),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally(n),this.activeRequests[t]=e,e._request.send(),this.lastPrefetchStart=je()}_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=je();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,gg.default)(this.activeRequests).forEach(e=>{e&&e._request&&e._request.abort()}),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,i,r){let a={};return a.send=()=>{let n=this.activeRequests[e]||this.completeRequests[e];if(n)n._cb=t,n._errorCB=i,n._retryCB=r,n._finallyCB=a._finallyCB,n._error||n._complete?(this._removeFromActive(e),setTimeout(()=>{n._complete?(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)),a._finallyCB&&a._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(a,e)}},a._cb=t,a._errorCB=i,a._retryCB=r,a.abort=function(){a.request&&a.request.abort()},a.withFinally=n=>(a._finallyCB=n,a),a}prefetch(e){this.activeRequests[e]||this.completeRequests[e]?this.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}};var vg=require("@vkontakte/videoplayer-shared");var Qn=1e4,ql=3;var wk=6e4,Pk=10,Ak=1,kk=500,ys=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 vg.Subject,this.chunkRateEstimator=new Ss(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=Ul(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(){if(this.rep&&this.rep.stop(),this.currentManifestEntry){let e=this.params.playbackState.getState();this.paused=e==="paused",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=Ul(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",()=>{!!e.error&&!this.destroyed&&(t(`Video element error: ${e.error?.code}, details: ${e.error?.message}`),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,a,n=t&&1.62*(W.display.pixelRatio||1)*t.offsetHeight||520;for(let o=0;o<this.manifest.length;++o){a=this.manifest[o];let{max:u,min:l}=this.autoQualityLimits||{};!ng({limits:this.autoQualityLimits,highestAvailableHeight:this.manifest[0].video.height,lowestAvailableHeight:(0,Sg.default)(this.manifest,-1).video.height})&&(u&&a.video.height>u||l&&a.video.height<l)||(a.bitrate<e&&n>Math.min(a.video.height,a.video.width)?(!r||a.bitrate>r.bitrate)&&(r=a):(!i||i.bitrate>a.bitrate)&&(i=a))}return r||i}shouldPlay(){if(this.paused)return!1;let t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||(0,Pt.isNonNullable)(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){let{logger:i,videoElement:r,playerCallback:a}=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=()=>{bg(r,"progress",()=>{r.buffered.length?(r.currentTime=r.buffered.start(0),this.waitingForFirstBufferAfterSrcChange=!1,a({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 vs(ql,Qn,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,a=!1,n=null,o=null,u=null,l=null,p=!1,c=()=>{let L=a&&(!p||p===this.rep);return L||t("Not running!"),L},d=(L,B,F)=>{u&&u.abort(),u=Pr(this.urlResolver.resolve(L,!1),B,F,()=>this._retryCallback()).withTimeout(Qn).withBitrateReporting(this.bitrateSwitcher).withRetryCount(ql).withFinally(()=>{u=null}).send()},h=(L,B,F)=>{(0,Pt.assertNonNullable)(this.filesFetcher),o?.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(L,!1),B,F,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},m=L=>{let B=i.playbackRate;i.playbackRate!==L&&(t(`Playback rate switch: ${B}=>${L}`),i.playbackRate=L)},g=L=>{this.lowLatency=L,t(`lowLatency changed to ${L}`),v()},v=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)m(1);else{let L=this._getBufferSizeSec();if(this.bufferStates.length<5){m(1);return}let F=je()-1e4,G=0;for(let D=0;D<this.bufferStates.length;D++){let I=this.bufferStates[D];L=Math.min(L,I.buf),I.ts<F&&G++}this.bufferStates.splice(0,G),t(`update playback rate; minBuffer=${L} drop=${G} jitter=${this.sourceJitter}`);let $=L-Ak;this.sourceJitter>=0?$-=this.sourceJitter/2:this.sourceJitter-=1,$>3?m(1.15):$>1?m(1.1):$>.3?m(1.05):m(1)}},T=L=>{let B,F=()=>B&&B.start?B.start.length:0,G=N=>B.start[N]/1e3,$=N=>B.dur[N]/1e3,D=N=>B.fragIndex+N,I=(N,re)=>({chunkIdx:D(N),startTS:G(N),dur:$(N),discontinuity:re}),U=()=>{let N=0;if(B&&B.dur){let re=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,le=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,Te=re;this.sourceJitter>1&&(Te+=this.sourceJitter-1);let Be=B.dur.length-1;for(;Be>=0&&(Te-=B.dur[Be],!(Te<=0));--Be);N=Math.min(Be,B.dur.length-1-le),N=Math.max(N,0)}return I(N,!0)},k=N=>{let re=F();if(!(re<=0)){if((0,Pt.isNonNullable)(N)){for(let le=0;le<re;le++)if(G(le)>N)return I(le)}return U()}},R=N=>{let re=F(),le=N?N.chunkIdx+1:0,Te=le-B.fragIndex;if(!(re<=0)){if(!N||Te<0||Te-re>Pk)return t(`Resync: offset=${Te} bChunks=${re} chunk=`+JSON.stringify(N)),U();if(!(Te>=re))return I(le-B.fragIndex,!1)}},C=(N,re,le)=>{l&&l.abort(),l=Pr(this.urlResolver.resolve(N,!0,this.lowLatency),re,le,()=>this._retryCallback()).withTimeout(Qn).withRetryCount(ql).withFinally(()=>{l=null}).withJSONResponse().send()};return{seek:(N,re)=>{C(L,le=>{if(!c())return;B=le;let Te=!!B.lowLatency;Te!==this.lowLatency&&g(Te);let Be=0;for(let Ie=0;Ie<B.dur.length;++Ie)Be+=B.dur[Ie];Be>0&&((0,Pt.assertNonNullable)(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(Be/B.dur.length)),r({name:"index",zeroTime:B.zeroTime,shiftDuration:B.shiftDuration}),this.sourceJitter=B.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,B.jitter/1e3)):1,N(k(re))},()=>this._handleNetworkError())},nextChunk:R}},P=()=>{a=!1,o&&o.abort(),u&&u.abort(),l&&l.abort(),(0,Pt.assertNonNullable)(this.filesFetcher),this.filesFetcher.abortAll()};return p={start:L=>{let{videoElement:B,logger:F}=this.params,G=T(e.jidxUrl),$,D,I,U,k=0,R,C,be,N=()=>{R&&(clearTimeout(R),R=void 0);let z=Math.max(kk,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),Ne=k+z,$e=je(),pe=Math.min(1e4,Ne-$e);k=$e;let Ce=()=>{l||c()&&G.seek(()=>{c()&&(k=je(),re(),N())})};pe>0?R=window.setTimeout(()=>{this.paused?N():Ce()},pe):Ce()},re=()=>{let z;for(;z=G.nextChunk(U);)U=z,ce(z);let Ne=G.nextChunk(I);if(Ne){if(I&&Ne.discontinuity){F("Detected discontinuity; restarting playback"),this.paused?N():(P(),this._initPlayerWith(e));return}Ie(Ne)}else N()},le=(z,Ne)=>{if(!c()||!this.sourceBuffer)return;let $e,pe,Ce,pt=Ke=>{window.setTimeout(()=>{c()&&le(z,Ne)},Ke)};if(this.sourceBuffer.updating)F("Source buffer is updating; delaying appendBuffer"),pt(100);else{let Ke=je(),Pe=B.currentTime;!this.paused&&B.buffered.length>1&&C===Pe&&Ke-be>500&&(F("Stall suspected; trying to fix"),this._fixupStall()),C!==Pe&&(C=Pe,be=Ke);let ht=this._getBufferSizeSec();if(ht>30)F(`Buffered ${ht} seconds; delaying appendBuffer`),pt(2e3);else try{this.sourceBuffer.appendBuffer(z),this.videoPlayStarted?(this.bufferStates.push({ts:Ke,buf:ht}),v(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),Ne&&Ne()}catch(Fe){if(Fe.name==="QuotaExceededError")F("QuotaExceededError; delaying appendBuffer"),Ce=this.sourceBuffer.buffered.length,Ce!==0&&($e=this.sourceBuffer.buffered.start(0),pe=Pe,pe-$e>4&&this.sourceBuffer.remove($e,pe-3)),pt(1e3);else throw Fe}}},Te=()=>{D&&$&&(F([`Appending chunk, sz=${D.byteLength}:`,JSON.stringify(I)]),le(D,function(){D=null,re()}))},Be=z=>e.fragUrlTemplate.replace("%%id%%",z.chunkIdx),Ie=z=>{c()&&h(Be(z),(Ne,$e)=>{if(c()){if($e/=1e3,D=Ne,I=z,n=z.startTS,$e){let pe=Math.min(10,z.dur/$e);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*pe:pe}Te()}},()=>this._handleNetworkError())},ce=z=>{c()&&((0,Pt.assertNonNullable)(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(Be(z),!1)))},V=z=>{c()&&(e.cachedHeader=z,le(z,()=>{$=!0,Te()}))};a=!0,G.seek(z=>{if(c()){if(k=je(),!z){N();return}U=z,!(0,Pt.isNullable)(L)||z.startTS>L?Ie(z):(I=z,re())}},L),e.cachedHeader?V(e.cachedHeader):d(e.headerUrl,V,()=>this._handleNetworkError())},stop:P,getTimestampSec:()=>n},p}_switchToQuality(e){let{logger:t,playerCallback:i}=this.params,r;e.bitrate!==this.bitrate&&(this.rep&&(r=this.rep.getTimestampSec(),(0,Pt.isNonNullable)(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,(0,Pt.assertNonNullable)(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(r),i({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return(0,Pt.isNonNullable)(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,i=c=>{if(!this.autoQuality)return;let d,h,m;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&c<this.bitrate&&(h=this._getBufferSizeSec(),m=c/this.bitrate,h>10&&m>.8||h>15&&m>.5||h>20&&m>.3)){e(`Not switching: buffer=${Math.floor(h)}; bitrate=${this.bitrate}; newRate=${Math.floor(c)}`);return}d=this._selectQuality(c),d?this._switchToQuality(d):e(`Could not find quality by bitrate ${c}`)},a={updateChunk:(d,h)=>{let m=je();if(this.chunkRateEstimator.addInterval(d,m,h)){let v=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:h,duration:m-d,speed:v}),!0}},get:()=>{let d=this.chunkRateEstimator.getBitRate();return d?d*.85:0}},n=-1/0,o,u=!0,l=()=>{let c=a.get();if(c&&o&&this.autoQuality){if(u&&c>o&&Nl(n)<3e4)return;i(c)}u=this.autoQuality};return{updateChunk:(c,d)=>{let h=a.updateChunk(c,d);return h&&l(),h},notifySwitch:c=>{let d=je();c<o&&(n=d),o=c}}}_fetchManifest(e,t,i){this.manifestRequest=Pr(this.urlResolver.resolve(e,!0),t,i,()=>this._retryCallback()).withJSONResponse().withTimeout(Qn).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;lt(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,a=n=>{let o=[];return n?.length?(n.forEach((u,l)=>{u.video&&r.canPlayType(u.codecs).replace(/no/,"")&&window.MediaSource?.isTypeSupported?.(u.codecs)&&(u.index=l,o.push(u))}),o.sort(function(u,l){return u.video&&l.video?l.video.height-u.video.height:l.bitrate-u.bitrate}),o):(i({name:"error",type:"empty_manifest"}),[])};this.manifest=a(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))},wk))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};var yg=j(Ui(),1),Ae=require("@vkontakte/videoplayer-shared"),Hl=class{constructor(){this.onDroopedVideoFramesLimit$=new Ae.Subject;this.subscription=new Ae.Subscription;this.playing=!1;this.tracks=[];this.forceChecker$=new Ae.Subject;this.isForceCheckCounter=0;this.prevTotalVideoFrames=0;this.prevDroppedVideoFrames=0;this.limitCounts={};this.handleChangeVideoQuality=()=>{let e=this.tracks.find(({size:t})=>t?.height===this.video.videoHeight&&t?.width===this.video.videoWidth);e&&!(0,Ae.isInvariantQuality)(e.quality)&&this.onChangeQuality(e.quality)};this.checkDroppedFrames=()=>{let{totalVideoFrames:e,droppedVideoFrames:t}=this.video.getVideoPlaybackQuality(),i=e-this.prevTotalVideoFrames,r=t-this.prevDroppedVideoFrames,a=1-(i-r)/i;!isNaN(a)&&a>0&&this.log({message:`[dropped]. current dropped percent: ${a}, limit: ${this.droppedFramesChecker.percentLimit}`}),!isNaN(a)&&a>=this.droppedFramesChecker.percentLimit&&(0,Ae.isHigher)(this.currentQuality,this.droppedFramesChecker.minQualityBanLimit)&&(this.limitCounts[this.currentQuality]=(this.limitCounts[this.currentQuality]??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((0,Ae.fromEvent)(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=(0,Ae.interval)(this.droppedFramesChecker.checkTime).pipe((0,Ae.filter)(()=>this.playing),(0,Ae.filter)(()=>{let r=!!this.isForceCheckCounter;return r&&(this.isForceCheckCounter-=1),!r})),t=this.forceChecker$.pipe((0,Ae.debounce)(this.droppedFramesChecker.checkTime)),i=(0,Ae.merge)(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){let t=(0,yg.default)(this.limitCounts).filter(([,i])=>i>=this.droppedFramesChecker.countLimit).sort(([i],[r])=>(0,Ae.isLower)(i,r)?-1:1)?.[0]?.[0];return 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}},Ar=Hl;var Gn=require("@vkontakte/videoplayer-shared"),Tg=require("@vkontakte/videoplayer-shared");var Ts=()=>!!window.documentPictureInPicture?.window||!!document.pictureInPictureElement;var Rk=(s,e)=>new Gn.Observable(t=>{if(!window.IntersectionObserver)return;let i={root:null},r=new IntersectionObserver((n,o)=>{n.forEach(u=>t.next(u.isIntersecting||Ts()))},{...i,...e});r.observe(s);let a=(0,Tg.fromEvent)(document,"visibilitychange").pipe((0,Gn.map)(n=>!document.hidden||Ts())).subscribe(n=>t.next(n));return()=>{r.unobserve(s),a.unsubscribe()}}),Mt=Rk;var Mk=["paused","playing","ready"],Lk=["paused","playing","ready"],Is=class{constructor(e){this.subscription=new Q.Subscription;this.videoState=new ie("stopped");this.representations$=new Q.ValueSubject([]);this.droppedFramesManager=new Ar;this.maxSeekBackTime$=new Q.ValueSubject(1/0);this.zeroTime$=new Q.ValueSubject(void 0);this.liveOffset=new Wi;this._dashCb=e=>{switch(e.name){case"buffering":{let t=e.isBuffering;this.params.output.isBuffering$.next(t);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${e.type}`,category:Q.ErrorCategory.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{let t=e.manifest,i=[];for(let r of t){let a=r.name??r.index.toString(10),n=Ai(r.name)??(0,Q.videoSizeToQuality)(r.video),o=r.bitrate/1e3,u={...r.video};if(!n)continue;let l={id:a,quality:n,bitrate:o,size:u};i.push({track:l,representation:r})}this.representations$.next(i),this.params.output.availableVideoTracks$.next(i.map(({track:r})=>r)),this.videoState.getTransition()?.to==="manifest_ready"&&this.videoState.setState("manifest_ready");break}case"qualitySwitch":{let t=e.quality,i=this.representations$.getValue().find(({representation:r})=>r===t)?.track;this.params.output.hostname$.next(new URL(t.headerUrl,this.params.source.url).hostname),(0,Q.isNonNullable)(i)&&this.params.output.currentVideoTrack$.next(i);break}case"bandwidth":{let{size:t,duration:i}=e;this.params.dependencies.throughputEstimator.addRawSpeed(t,i);break}case"index":{this.maxSeekBackTime$.next(e.shiftDuration||0),this.zeroTime$.next(e.zeroTime);break}}};this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; seekState: ${JSON.stringify(a)};`}),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,jl.default)(Lk,e)&&(n||o)){this.prepare();return}if(r?.to!=="paused"&&a.state==="requested"&&(0,jl.default)(Mk,e)){this.seek(a.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(Le(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?.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(Le(this.params.source.url,u))}return;default:return(0,Q.assertNever)(e)}};this.textTracksManager=new Rt(e.source.url),this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=r=>{e.output.error$.next({id:"DashLiveProvider",category:Q.ErrorCategory.WTF,message:"DashLiveProvider internal logic error",thrown:r})};this.subscription.add((0,Q.merge)(this.videoState.stateChangeStarted$.pipe((0,Q.map)(r=>({transition:r,type:"start"}))),this.videoState.stateChangeEnded$.pipe((0,Q.map)(r=>({transition:r,type:"end"})))).subscribe(({transition:r,type:a})=>{this.log({message:`[videoState change] ${a}: ${JSON.stringify(r)}`})})),this.video=at(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(We(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=ut(this.video);this.subscription.add(()=>i.destroy()),this.subscription.add(this.representations$.pipe((0,Q.map)(r=>r.map(({track:a})=>a)),(0,Q.filter)(r=>!!r.length),(0,Q.once)()).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(()=>{this.videoState.getTransition()?.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((0,Q.filterChanged)(),(0,Q.map)(r=>-r/1e3)).subscribe(this.params.output.duration$)).add((0,Q.combine)({zeroTime:this.zeroTime$.pipe((0,Q.filter)(Q.isNonNullable)),position:i.timeUpdate$}).subscribe(({zeroTime:r,position:a})=>this.params.output.liveTime$.next(r+a*1e3),t)).add(Wt(this.video,this.params.desiredState.isLooped,t)).add(ot(this.video,this.params.desiredState.volume,i.volumeState$,t)).add(i.volumeState$.subscribe(this.params.output.volume$,t)).add(kt(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(Mt(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:r,min:a}})=>{this.dash.setAutoQualityLimits({max:r&&(0,Q.videoQualityToHeight)(r),min:a&&(0,Q.videoQualityToHeight)(a)}),this.params.output.autoVideoTrackLimits$.next({max:r,min:a})})).add(this.videoState.stateChangeEnded$.subscribe(r=>{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":this.params.desiredState.playbackState.getTransition()?.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(0,Q.assertNever)(r.to)}},t)).add((0,Q.merge)(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,(0,Q.observableFrom)(["init"])).pipe((0,Q.debounce)(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),nt(this.video)}createLiveDashPlayer(){let e=new ys({videoElement:this.video,videoState:this.videoState,playbackState:this.params.desiredState.playbackState,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(){let e=this.representations$.getValue(),t=this.params.desiredState.videoTrack.getTransition()?.to??this.params.desiredState.videoTrack.getState(),i=this.params.desiredState.autoVideoTrackSwitching.getTransition()?.to??this.params.desiredState.autoVideoTrackSwitching.getState(),r=!i&&(0,Q.isNonNullable)(t)?t:Yt(e.map(({track:l})=>l),{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}),a=r?.id,n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.videoTrack.getState()?.id,u=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(r&&(n||a!==o)&&this.setVideoTrack(r),u&&this.setAutoQuality(i),n||u||a!==o){let l=e.find(({track:p})=>p.id===a)?.representation;(0,Q.assertNonNullable)(l,"Representations missing"),this.dash.startPlay(l,i)}}setVideoTrack(e){let t=this.representations$.getValue().find(({track:i})=>i.id===e.id)?.representation;(0,Q.assertNonNullable)(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",a=-e,n=a<=this.maxSeekBackTime$.getValue()?a:0;this.params.output.position$.next(e/1e3),this.dash.reinit(Le(this.params.source.url,n)),r&&this.dash.pause(),this.liveOffset.resetTo(n,r)}};var Ig=Is;var xv=j(xt(),1);var ze=(s,e)=>{let t=0;for(let i=0;i<s.length;i++){let r=s.start(i)*1e3,a=s.end(i)*1e3;r<=e&&e<=a&&(t=a)}return Math.max(t-e,0)};var Z=require("@vkontakte/videoplayer-shared");var Wn=class{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,i){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:i})}removeEventListener(e,t){if(!(e in this.listeners))return;let i=this.listeners[e];for(let r=0,a=i.length;r<a;r++)if(i[r].callback===t){i.splice(r,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;let i=this.listeners[e.type].slice();for(let r=0,a=i.length;r<a;r++){let n=i[r];try{n.callback.call(this,e)}catch(o){Promise.resolve().then(()=>{throw o})}n.options&&n.options.once&&this.removeEventListener(e.type,n.callback)}return!e.defaultPrevented}},kr=class extends Wn{constructor(){super(),this.listeners||Wn.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)}},xs=class{constructor(){Object.defineProperty(this,"signal",{value:new kr,writable:!0,configurable:!0})}abort(e){let t;try{t=new Event("abort")}catch{typeof document<"u"?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>"u")i=new Error("This operation was aborted"),i.name="AbortError";else try{i=new DOMException("signal is aborted without reason")}catch{i=new Error("This operation was aborted"),i.name="AbortError"}this.signal.reason=i,this.signal.dispatchEvent(t)}toString(){return"[object AbortController]"}};typeof Symbol<"u"&&Symbol.toStringTag&&(xs.prototype[Symbol.toStringTag]="AbortController",kr.prototype[Symbol.toStringTag]="AbortSignal");function Yn(s){return s.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof s.Request=="function"&&!s.Request.prototype.hasOwnProperty("signal")||!s.AbortController}function zl(s){typeof s=="function"&&(s={fetch:s});let{fetch:e,Request:t=e.Request,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r=!1}=s;if(!Yn({fetch:e,Request:t,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r}))return{fetch:e,Request:a};let a=t;(a&&!a.prototype.hasOwnProperty("signal")||r)&&(a=function(l,p){let c;p&&p.signal&&(c=p.signal,delete p.signal);let d=new t(l,p);return c&&Object.defineProperty(d,"signal",{writable:!1,enumerable:!1,configurable:!0,value:c}),d},a.prototype=t.prototype);let n=e;return{fetch:(u,l)=>{let p=a&&a.prototype.isPrototypeOf(u)?u.signal:l?l.signal:void 0;if(p){let c;try{c=new DOMException("Aborted","AbortError")}catch{c=new Error("Aborted"),c.name="AbortError"}if(p.aborted)return Promise.reject(c);let d=new Promise((h,m)=>{p.addEventListener("abort",()=>m(c),{once:!0})});return l&&l.signal&&delete l.signal,Promise.race([d,n(u,l)])}return n(u,l)},Request:a}}var Bk=()=>"fetch"in window,Es=Bk()&&Yn({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),xg=Es?zl({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,Lt=Es?xg.fetch:window.fetch,VV=Es?xg.Request:window.Request,de=Es?xs:window.AbortController,OV=Es?kr:window.AbortSignal;var Sc=j(ws(),1);var lS=j(uS(),1),Rr=require("@vkontakte/videoplayer-shared"),Kn=s=>{if(!s)return{id:"EmptyResponse",category:Rr.ErrorCategory.PARSER,message:"Empty response"};if(s.length<=2&&s.match(/^\d+$/))return{id:`UVError#${s}`,category:Rr.ErrorCategory.NETWORK,message:`UV Error ${s}`};let e=(0,lS.default)(s).substring(0,100).toLowerCase();if(e.startsWith("<!doctype")||e.startsWith("<html>")||e.startsWith("<body>")||e.startsWith("<head>"))return{id:"UnexpectedHTML",category:Rr.ErrorCategory.NETWORK,message:"Received unexpected HTML, possibly a ISP block"};if(e.startsWith("<?xml"))return new DOMParser().parseFromString(s,"text/xml").querySelector("parsererror")?{id:"InvalidXML",category:Rr.ErrorCategory.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:Rr.ErrorCategory.PARSER,message:"Response is valid XML, but parser failed"}};var Ye=(s,e,t=0)=>{for(let i=0;i<s.length;i++)if(s.start(i)*1e3-t<=e&&s.end(i)*1e3+t>e)return!0;return!1};var y=require("@vkontakte/videoplayer-shared");var Jn=j(xt(),1),Cr=j(Ut(),1),Zn=j(ws(),1);var gR=(s,e={})=>{let i=e.timeout||1,r=performance.now();return window.setTimeout(()=>{s({get didTimeout(){return e.timeout?!1:performance.now()-r-1>i},timeRemaining(){return Math.max(0,1+(performance.now()-r))}})},1)},SR=s=>window.clearTimeout(s),cS=s=>typeof s=="function"&&s?.toString().endsWith("{ [native code] }"),dS=!cS(window.requestIdleCallback)||!cS(window.cancelIdleCallback),Mr=dS?gR:window.requestIdleCallback,Xt=dS?SR:window.cancelIdleCallback;var hv=j(Rn(),1);var Ri=require("@vkontakte/videoplayer-shared");var vR=18,pS=!1;try{pS=W.browser.isSafari&&!!W.browser.safariVersion&&W.browser.safariVersion<=vR}catch(s){console.error(s)}var Xl=class{constructor(e){this.bufferFull$=new Ri.Subject;this.error$=new Ri.Subject;this.queue=[];this.currentTask=null;this.destroyed=!1;this.abortRequested=!1;this.completeTask=()=>{try{if(this.currentTask){let e=this.currentTask.signal?.aborted;this.currentTask.callback(!e),this.currentTask=null}this.queue.length&&this.pull()}catch(e){this.error$.next({id:"BufferTaskQueueUnknown",category:Ri.ErrorCategory.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:e})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(i=>{let r={operation:"append",data:e,signal:t,callback:i};this.queue.push(r),this.pull()})}async remove(e,t,i){return i&&i.aborted?!1:new Promise(r=>{let a={operation:"remove",from:e,to:t,signal:i,callback:r};this.queue.unshift(a),this.pull()})}async abort(e){return new Promise(t=>{let i,r=a=>{this.abortRequested=!1,t(a)};pS&&e?i={operation:"safariAbort",init:e,callback:r}:i={operation:"abort",callback:r};for(let{callback:a}of this.queue)a(!1);this.abortRequested=!0,i&&(this.queue=[i]),this.pull()})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){if((this.buffer.updating||this.currentTask||this.destroyed)&&!this.abortRequested)return;let e=this.queue.shift();if(!e)return;if(e.signal?.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(r){r instanceof DOMException&&r.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):r instanceof DOMException&&r.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:Ri.ErrorCategory.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:r}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){let{operation:t}=e;switch(t){case"append":this.buffer.appendBuffer(e.data);break;case"remove":this.buffer.remove(e.from/1e3,e.to/1e3);break;case"abort":this.buffer.abort();break;case"safariAbort":{this.buffer.abort(),this.buffer.appendBuffer(e.init);break}default:(0,Ri.assertNever)(t)}}},hS=Xl;var Lr=s=>{let e=0;for(let t=0;t<s.length;t++)e+=s.end(t)-s.start(t);return e*1e3};var w=require("@vkontakte/videoplayer-shared");var ae=class{constructor(e,t){this.cursor=0;this.source=e,this.boxParser=t,this.children=[];let i=this.readUint32();this.type=this.readString(4),this.size32=i<=e.buffer.byteLength-e.byteOffset?i:NaN;let r=this.size32?this.size32-8:void 0,a=e.byteOffset+this.cursor;this.size64=0,this.usertype=0,this.content=new DataView(e.buffer,a,r)}get id(){return this.type}get size(){return this.size32}scanForBoxes(e){return this.boxParser.parse(e)}readString(e,t="ascii"){let r=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,r}readUint8(){let e=this.source.getUint8(this.cursor);return this.cursor+=1,e}readUint16(){let e=this.source.getUint16(this.cursor);return this.cursor+=2,e}readUint32(){let e=this.source.getUint32(this.cursor);return this.cursor+=4,e}readUint64(){let e=this.source.getBigInt64(this.cursor);return this.cursor+=8,e}};var Br=class extends ae{};var As=class extends ae{constructor(t,i){super(t,i);this.ondemandPrefix="ondemandlivejson";this.ondemandDataReceivedKey="t-in";this.ondemandDataPreparedKey="t-out";let r=this.content.byteOffset,a=r+this.content.byteLength,n=new TextDecoder("ascii").decode(this.content.buffer.slice(r,a)).split(this.ondemandPrefix)[1],o=JSON.parse(n);this.serverDataReceivedTimestamp=o[this.ondemandDataReceivedKey],this.serverDataPreparedTime=o[this.ondemandDataPreparedKey]}};var ks=class extends ae{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 Rs=class extends ae{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ge=class extends ae{constructor(e,t){super(e,t);let i=this.readUint32();this.version=i>>>24,this.flags=i&16777215}};var Ms=class extends ge{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 Ls=class extends ae{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Bs=class extends ae{constructor(e,t){super(e,t),this.data=this.content}};var Ki=class extends ge{get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e,t){super(e,t),this.segments=[],this.referenceId=this.readUint32(),this.timescale=this.readUint32(),this.earliestPresentationTime32=this.readUint32(),this.firstOffset32=this.readUint32(),this.earliestPresentationTime64=0,this.firstOffset64=0,this.referenceCount=this.readUint32()&65535;for(let i=0;i<this.referenceCount;i++){let r=this.readUint32(),a=r>>>31,n=r<<1>>>1,o=this.readUint32();r=this.readUint32();let u=r>>>28,l=r<<3>>>3;this.segments.push({referenceType:a,referencedSize:n,subsegmentDuration:o,SAPType:u,SAPDeltaTime:l})}}};var $s=class extends ae{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ds=class extends ae{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Cs=class extends ge{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 Vs=class extends ge{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var Os=class extends ge{constructor(e,t){super(e,t),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}};var _s=class extends ae{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Fs=class extends ge{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 Ns=class extends ae{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Us=class extends ae{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var qs=class extends ge{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var Hs=class extends ae{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var js=class extends ge{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 zs=class extends ge{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 Qs=class extends ge{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 Gs=class extends ae{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ws=class extends ge{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 Ys=class extends ae{constructor(e,t){super(e,t),this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+78,this.content.byteLength-78))}};var TR={ftyp:ks,moov:Rs,mvhd:Ms,moof:Ls,mdat:Bs,sidx:Ki,trak:$s,mdia:_s,mfhd:qs,tkhd:Fs,traf:Hs,tfhd:js,tfdt:zs,trun:Qs,minf:Ns,sv3d:Ds,st3d:Cs,prhd:Vs,proj:Us,equi:Os,uuid:As,stbl:Gs,stsd:Ws,avc1:Ys,unknown:Br},pi=class s{constructor(e={}){this.options={offset:0,...e}}parse(e){let t=[],i=this.options.offset;for(;i<e.byteLength;)try{let a=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+i+4,4)),n=this.createBox(a,new DataView(e.buffer,e.byteOffset+i));if(!n.size)break;t.push(n),i+=n.size}catch{break}return t}createBox(e,t){let i=TR[e];return i?new i(t,new s):new Br(t,new s)}};var Mi=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{this.index[t.type]??=[],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 xR=new TextDecoder("ascii"),ER=s=>xR.decode(new DataView(s.buffer,s.byteOffset+4,4))==="ftyp",wR=s=>{let e=new Ki(s,new pi),t=e.earliestPresentationTime/e.timescale*1e3,i=s.byteOffset+s.byteLength+e.firstOffset;return e.segments.map(a=>{if(a.referenceType!==0)throw new Error("Unsupported multilevel sidx");let n=a.subsegmentDuration/e.timescale*1e3,o={status:"none",time:{from:t,to:t+n},byte:{from:i,to:i+a.referencedSize-1}};return t+=n,i+=a.referencedSize,o})},PR=(s,e)=>{let i=new pi().parse(s),r=new Mi(i),a=r.findAll("moof"),n=e?r.findAll("uuid"):r.findAll("mdat");if(!(n.length&&a.length))return null;let o=a[0],u=n[n.length-1],l=o.source.byteOffset,c=u.source.byteOffset-o.source.byteOffset+u.size;return new DataView(s.buffer,l,c)},AR=s=>{let t=new pi().parse(s),i=new Mi(t),r={},a=i.findAll("uuid");return a.length?a[a.length-1]:r},kR=s=>{let t=new pi().parse(s);return new Mi(t).find("sidx")?.timescale},RR=(s,e)=>{let i=new pi().parse(s),a=new Mi(i).findAll("traf"),n=a[a.length-1].children.find(c=>c.type==="tfhd"),o=a[a.length-1].children.find(c=>c.type==="tfdt"),u=a[a.length-1].children.find(c=>c.type==="trun"),l=0;return u.sampleDuration.length?l=u.sampleDuration.reduce((c,d)=>c+d,0):l=n.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+l)/e*1e3},MR=s=>{let e={is3dVideo:!1,stereoMode:0,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}},i=new pi().parse(s),r=new Mi(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},fS={validateData:ER,parseInit:MR,getIndexRange:()=>{},parseSegments:wR,parseFeedableSegmentChunk:PR,getChunkEndTime:RR,getServerLatencyTimestamps:AR,getTimescaleFromIndex:kR};var Xs=j(xt(),1),hi=require("@vkontakte/videoplayer-shared");var bS=require("@vkontakte/videoplayer-shared");var mS={440786851:{type:"master"},17030:{type:"uint"},17143:{type:"uint"},17138:{type:"uint"},17139:{type:"uint"},17026:{type:"string"},17031:{type:"uint"},17029:{type:"uint"},236:{type:"binary"},408125543:{type:"master"},290298740:{type:"master"},19899:{type:"master"},21419:{type:"binary"},21420:{type:"uint"},357149030:{type:"master"},2807729:{type:"uint"},17545:{type:"float"},374648427:{type:"master"},174:{type:"master"},224:{type:"master"},30320:{type:"master"},30321:{type:"uint"},30322:{type:"master"},272869232:{type:"master"},524531317:{type:"master"},231:{type:"uint"},22612:{type:"master"},22743:{type:"uint"},167:{type:"uint"},171:{type:"uint"},163:{type:"binary"},160:{type:"master"},175:{type:"binary"},423732329:{type:"master"},307544935:{type:"master"},475249515:{type:"master"},187:{type:"master"},179:{type:"uint"},183:{type:"master"},247:{type:"uint"},241:{type:"uint"},240:{type:"uint"},178:{type:"uint"},21368:{type:"uint"},234:{type:"uint"},219:{type:"master"},150:{type:"uint"}},gS=s=>{let e=s.getUint8(0),t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);let i=Ks(s,t),r=i in mS,a=r?mS[i].type:"binary",n=s.getUint8(t),o=0;n&128?o=1:n&64?o=2:n&32?o=3:n&16?o=4:n&8?o=5:n&4?o=6:n&2?o=7:n&1&&(o=8);let u=new DataView(s.buffer,s.byteOffset+t+1,o-1),l=n&255>>o,p=Ks(u),c=l*2**((o-1)*8)+p,d=t+o,h;return d+c>s.byteLength?h=new DataView(s.buffer,s.byteOffset+d):h=new DataView(s.buffer,s.byteOffset+d,c),{tag:r?i:"0x"+i.toString(16).toUpperCase(),type:a,tagHeaderSize:d,tagSize:d+c,value:h,valueSize:c}},Ks=(s,e=s.byteLength)=>{switch(e){case 1:return s.getUint8(0);case 2:return s.getUint16(0);case 3:return s.getUint8(0)*2**16+s.getUint16(1);case 4:return s.getUint32(0);case 5:return s.getUint8(0)*2**32+s.getUint32(1);case 6:return s.getUint16(0)*2**32+s.getUint32(2);case 7:{let t=s.getUint8(0)*281474976710656+s.getUint16(1)*4294967296+s.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},qt=(s,e)=>{switch(e){case"int":return s.getInt8(0);case"uint":return Ks(s);case"float":return s.byteLength===4?s.getFloat32(0):s.getFloat64(0);case"string":return new TextDecoder("ascii").decode(s);case"utf8":return new TextDecoder("utf-8").decode(s);case"date":return new Date(Date.UTC(2001,0)+s.getInt8(0)).getTime();case"master":return s;case"binary":return s;default:(0,bS.assertNever)(e)}},Xi=(s,e)=>{let t=0;for(;t<s.byteLength;){let i=new DataView(s.buffer,s.byteOffset+t),r=gS(i);if(!e(r))return;r.type==="master"&&Xi(r.value,e),t=r.value.byteOffset-s.byteOffset+r.valueSize}},SS=s=>{if(s.getUint32(0)!==440786851)return!1;let e,t,i,r=gS(s);return Xi(r.value,({tag:a,type:n,value:o})=>(a===17143?e=qt(o,n):a===17026?t=qt(o,n):a===17029&&(i=qt(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)};var vS=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],LR=[231,22612,22743,167,171,163,160,175],BR=s=>{let e,t,i,r,a=!1,n=!1,o=!1,u,l,p=!1,c=0;return Xi(s,({tag:d,type:h,value:m,valueSize:g})=>{if(d===21419){let v=qt(m,h);l=Ks(v)}else d!==21420&&(l=void 0);return d===408125543?(e=m.byteOffset,t=m.byteOffset+g):d===357149030?a=!0:d===290298740?n=!0:d===2807729?i=qt(m,h):d===17545?r=qt(m,h):d===21420&&l===475249515?u=qt(m,h):d===374648427?Xi(m,({tag:v,type:T,value:P})=>v===30321?(p=qt(P,T)===1,!1):!0):a&&n&&(0,Xs.default)(vS,d)&&(o=!0),!o}),(0,hi.assertNonNullable)(e,"Failed to parse webm Segment start"),(0,hi.assertNonNullable)(t,"Failed to parse webm Segment end"),(0,hi.assertNonNullable)(r,"Failed to parse webm Segment duration"),i=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:p,stereoMode:c,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},$R=s=>{if((0,hi.isNullable)(s.cuesSeekPosition))return;let e=s.segmentStart+s.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},DR=(s,e)=>{let t=!1,i=!1,r=o=>(0,hi.isNonNullable)(o.time)&&(0,hi.isNonNullable)(o.position),a=[],n;return Xi(s,({tag:o,type:u,value:l})=>{switch(o){case 475249515:t=!0;break;case 187:n&&r(n)&&a.push(n),n={};break;case 179:n&&(n.time=qt(l,u));break;case 183:break;case 241:n&&(n.position=qt(l,u));break;default:t&&(0,Xs.default)(vS,o)&&(i=!0)}return!(t&&i)}),n&&r(n)&&a.push(n),a.map((o,u)=>{let{time:l,position:p}=o,c=a[u+1];return{status:"none",time:{from:l,to:c?c.time:e.segmentDuration},byte:{from:e.segmentStart+p,to:c?e.segmentStart+c.position-1:e.segmentEnd-1}}})},CR=s=>{let e=0,t=!1;try{Xi(s,i=>i.tag===524531317?i.tagSize<=s.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):(0,Xs.default)(LR,i.tag)?(e+i.tagSize<=s.byteLength&&(e+=i.tagSize,t||=(0,Xs.default)([163,160,175],i.tag)),!0):!1)}catch{}return e>0&&e<=s.byteLength&&t?new DataView(s.buffer,s.byteOffset,e):null},yS={validateData:SS,parseInit:BR,getIndexRange:$R,parseSegments:DR,parseFeedableSegmentChunk:CR};var Js=s=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(s);if(e){let[,t,i]=e;if(t==="audio"||t==="video")switch(i){case"webm":return yS;case"mp4":return fS}}throw new ReferenceError(`Unsupported mime type ${s}`)};var dc=j(sc(),1),lv=j(Ui(),1),cv=j(ac(),1),dv=j(Ut(),1),pc=j(Gi(),1);var tv=j(xt(),1),Dr=s=>{let e=s.split("."),[t,...i]=e;if(!t)return!1;switch(t){case"av01":{let[r,a,n]=i;return!!(n&&parseInt(n,10)>8)}case"vp09":{let[r,a,n]=i;return!!(r&&parseInt(r,10)>=2&&n&&parseInt(n,10)>8)}case"avc1":{let r=i[0];if(!r||r.length!==6)return!1;let[a,n]=r.toUpperCase(),o=a+n;return(0,tv.default)(["6E","7A","F4"],o)}}return!1};var ea=require("@vkontakte/videoplayer-shared");var Xn=s=>{if(s.includes("/")){let e=s.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(s)};var iv=s=>{try{let e=MM(),t=s.match(e),{groups:i}=t??{};if(i){let r={};if(i.extensions){let o=i.extensions.toLowerCase().match(/(?:[0-9a-wy-z](?:-[a-z0-9]{2,8})+)/g);Array.from(o||[]).forEach(u=>{r[u[0]]=u.slice(2)})}let a=i.variants?.split(/-/).filter(o=>o!==""),n={extlang:i.extlang,langtag:i.langtag,language:i.language,privateuse:i.privateuse||i.privateuse2,region:i.region,script:i.script,extensions:r,variants:a};return Object.keys(n).forEach(o=>{let u=n[o];(typeof u>"u"||u==="")&&delete n[o]}),n}return null}catch{return null}};function MM(){let s="(?<extlang>(?:[a-z]{3}(?:-[a-z]{3}){0,2}))",e="x(?:-[a-z0-9]{1,8})+",p=`^(?:(?<langtag>${`
|
|
116
|
+
[selected audio track] ${w?.id}
|
|
117
|
+
`}),w};var We=s=>new URL(s).hostname;var Q=require("@vkontakte/videoplayer-shared");var Sg=H(Ut(),1);var fg=H(xt(),1),hg=s=>{if(s instanceof DOMException&&(0,fg.default)(["Failed to load because no supported source was found.","The element has no supported sources."],s.message))throw s;return!(s instanceof DOMException&&(s.code===20||s.name==="AbortError"))},lt=async(s,e)=>{let t=s.muted;try{await s.play()}catch(i){if(!hg(i))return!1;if(e&&e(),t)return console.warn(i),!1;s.muted=!0;try{await s.play()}catch(r){return hg(r)&&(s.muted=!1,console.warn(r)),!1}}return!0};var At=require("@vkontakte/videoplayer-shared");var mg=H(Gi(),1),Kt=require("@vkontakte/videoplayer-shared");function He(){return(0,Kt.now)()}function Nl(s){return He()-s}function Ul(s){let e=s.split("/"),t=e.slice(0,e.length-1).join("/"),i=/^([a-z]+:)?\/\//i,r=n=>i.test(n);return{resolve:(n,o,u=!1)=>{r(n)||(n.startsWith("/")||(n="/"+n),n=t+n);let l=n.indexOf("?")>-1?"&":"?";return u&&(n+=l+"lowLat=1",l="&"),o&&(n+=l+"_rnd="+Math.floor(999999999*Math.random())),n}}}function bg(s,e,t){let i=(...r)=>{t.apply(null,r),s.removeEventListener(e,i)};s.addEventListener(e,i)}function Ar(s,e,t,i){let r=window.XMLHttpRequest,a,n,o,u=!1,l=0,d,c,p=!1,h="arraybuffer",m=7e3,g=2e3,v=()=>{if(u)return;(0,Kt.assertNonNullable)(d);let k=Nl(d),R;if(k<g){R=g-k,setTimeout(v,R);return}g*=2,g>m&&(g=m),n&&n.abort(),n=new r,F()},T=k=>(a=k,U),w=k=>(c=k,U),x=()=>(h="json",U),M=()=>{if(!u){if(--l>=0){v(),i&&i();return}u=!0,c&&c(),t&&t()}},B=k=>(p=k,U),F=()=>{d=He(),n=new r,n.open("get",s);let k=0,R,C=0,be=()=>((0,Kt.assertNonNullable)(d),Math.max(d,Math.max(R||0,C||0)));if(a&&n.addEventListener("progress",N=>{let re=He();a.updateChunk&&N.loaded>k&&(a.updateChunk(be(),N.loaded-k),k=N.loaded,R=re)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>M())),n.addEventListener("load",()=>{if(u)return;(0,Kt.assertNonNullable)(n);let N=n.status;if(N>=200&&N<300){let{response:re,responseType:le}=n,Te=re?.byteLength;if(typeof Te=="number"&&a){let Be=Te-k;Be&&a.updateChunk&&a.updateChunk(be(),Be)}le==="json"&&(!re||!(0,mg.default)(re).length)?M():(c&&c(),e(re))}else M()}),n.addEventListener("error",()=>{M()}),p){let N=()=>{(0,Kt.assertNonNullable)(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(C=He(),n.removeEventListener("readystatechange",N))};n.addEventListener("readystatechange",N)}return n.responseType=h,n.send(),U},U={withBitrateReporting:T,withParallel:B,withJSONResponse:x,withRetryCount:k=>(l=k,U),withRetryInterval:(k,R)=>((0,Kt.isNonNullable)(k)&&(g=k),(0,Kt.isNonNullable)(R)&&(m=R),U),withTimeout:k=>(o=k,U),withFinally:w,send:F,abort:()=>{n&&(n.abort(),n=void 0),u=!0,c&&c()}};return U}var Ss=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 a=this.intervals[0];if(a.end<=t)i+=a.end-a.start,r+=a.bytes,this.intervals.splice(0,1);else{if(a.start>=t)break;{let n=t-a.start,o=a.end-a.start;i+=n;let u=a.bytes*n/o;r+=u,a.start=t,a.bytes-=u}}}if(r>0&&i>0){let a=r*8/(i/1e3);return this._updateRate(a),this.logger(`rate updated, new=${Math.round(a/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 gg=H(Gi(),1);var vs=class{constructor(e,t,i,r,a){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=a}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=He(),r=u=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=u,e._errorCB?e._errorCB(u):(this.limitCompleteCount(),this.completeRequests[t]=e)},a=u=>{e._complete=1,e._responseData=u,e._downloadTime=He()-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=Ar(t,a,()=>r("error"),o),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally(n),this.activeRequests[t]=e,e._request.send(),this.lastPrefetchStart=He()}_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=He();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,gg.default)(this.activeRequests).forEach(e=>{e&&e._request&&e._request.abort()}),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,i,r){let a={};return a.send=()=>{let n=this.activeRequests[e]||this.completeRequests[e];if(n)n._cb=t,n._errorCB=i,n._retryCB=r,n._finallyCB=a._finallyCB,n._error||n._complete?(this._removeFromActive(e),setTimeout(()=>{n._complete?(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)),a._finallyCB&&a._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(a,e)}},a._cb=t,a._errorCB=i,a._retryCB=r,a.abort=function(){a.request&&a.request.abort()},a.withFinally=n=>(a._finallyCB=n,a),a}prefetch(e){this.activeRequests[e]||this.completeRequests[e]?this.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}};var vg=require("@vkontakte/videoplayer-shared");var Qn=1e4,ql=3;var wk=6e4,Ak=10,Pk=1,kk=500,ys=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 vg.Subject,this.chunkRateEstimator=new Ss(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=Ul(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(){if(this.rep&&this.rep.stop(),this.currentManifestEntry){let e=this.params.playbackState.getState();this.paused=e==="paused",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=Ul(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",()=>{!!e.error&&!this.destroyed&&(t(`Video element error: ${e.error?.code}, details: ${e.error?.message}`),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,a,n=t&&1.62*(W.display.pixelRatio||1)*t.offsetHeight||520;for(let o=0;o<this.manifest.length;++o){a=this.manifest[o];let{max:u,min:l}=this.autoQualityLimits||{};!ng({limits:this.autoQualityLimits,highestAvailableHeight:this.manifest[0].video.height,lowestAvailableHeight:(0,Sg.default)(this.manifest,-1).video.height})&&(u&&a.video.height>u||l&&a.video.height<l)||(a.bitrate<e&&n>Math.min(a.video.height,a.video.width)?(!r||a.bitrate>r.bitrate)&&(r=a):(!i||i.bitrate>a.bitrate)&&(i=a))}return r||i}shouldPlay(){if(this.paused)return!1;let t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||(0,At.isNonNullable)(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){let{logger:i,videoElement:r,playerCallback:a}=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=()=>{bg(r,"progress",()=>{r.buffered.length?(r.currentTime=r.buffered.start(0),this.waitingForFirstBufferAfterSrcChange=!1,a({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 vs(ql,Qn,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,a=!1,n=null,o=null,u=null,l=null,d=!1,c=()=>{let M=a&&(!d||d===this.rep);return M||t("Not running!"),M},p=(M,B,F)=>{u&&u.abort(),u=Ar(this.urlResolver.resolve(M,!1),B,F,()=>this._retryCallback()).withTimeout(Qn).withBitrateReporting(this.bitrateSwitcher).withRetryCount(ql).withFinally(()=>{u=null}).send()},h=(M,B,F)=>{(0,At.assertNonNullable)(this.filesFetcher),o?.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(M,!1),B,F,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},m=M=>{let B=i.playbackRate;i.playbackRate!==M&&(t(`Playback rate switch: ${B}=>${M}`),i.playbackRate=M)},g=M=>{this.lowLatency=M,t(`lowLatency changed to ${M}`),v()},v=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)m(1);else{let M=this._getBufferSizeSec();if(this.bufferStates.length<5){m(1);return}let F=He()-1e4,G=0;for(let D=0;D<this.bufferStates.length;D++){let I=this.bufferStates[D];M=Math.min(M,I.buf),I.ts<F&&G++}this.bufferStates.splice(0,G),t(`update playback rate; minBuffer=${M} drop=${G} jitter=${this.sourceJitter}`);let $=M-Pk;this.sourceJitter>=0?$-=this.sourceJitter/2:this.sourceJitter-=1,$>3?m(1.15):$>1?m(1.1):$>.3?m(1.05):m(1)}},T=M=>{let B,F=()=>B&&B.start?B.start.length:0,G=N=>B.start[N]/1e3,$=N=>B.dur[N]/1e3,D=N=>B.fragIndex+N,I=(N,re)=>({chunkIdx:D(N),startTS:G(N),dur:$(N),discontinuity:re}),U=()=>{let N=0;if(B&&B.dur){let re=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,le=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,Te=re;this.sourceJitter>1&&(Te+=this.sourceJitter-1);let Be=B.dur.length-1;for(;Be>=0&&(Te-=B.dur[Be],!(Te<=0));--Be);N=Math.min(Be,B.dur.length-1-le),N=Math.max(N,0)}return I(N,!0)},k=N=>{let re=F();if(!(re<=0)){if((0,At.isNonNullable)(N)){for(let le=0;le<re;le++)if(G(le)>N)return I(le)}return U()}},R=N=>{let re=F(),le=N?N.chunkIdx+1:0,Te=le-B.fragIndex;if(!(re<=0)){if(!N||Te<0||Te-re>Ak)return t(`Resync: offset=${Te} bChunks=${re} chunk=`+JSON.stringify(N)),U();if(!(Te>=re))return I(le-B.fragIndex,!1)}},C=(N,re,le)=>{l&&l.abort(),l=Ar(this.urlResolver.resolve(N,!0,this.lowLatency),re,le,()=>this._retryCallback()).withTimeout(Qn).withRetryCount(ql).withFinally(()=>{l=null}).withJSONResponse().send()};return{seek:(N,re)=>{C(M,le=>{if(!c())return;B=le;let Te=!!B.lowLatency;Te!==this.lowLatency&&g(Te);let Be=0;for(let Ie=0;Ie<B.dur.length;++Ie)Be+=B.dur[Ie];Be>0&&((0,At.assertNonNullable)(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(Be/B.dur.length)),r({name:"index",zeroTime:B.zeroTime,shiftDuration:B.shiftDuration}),this.sourceJitter=B.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,B.jitter/1e3)):1,N(k(re))},()=>this._handleNetworkError())},nextChunk:R}},w=()=>{a=!1,o&&o.abort(),u&&u.abort(),l&&l.abort(),(0,At.assertNonNullable)(this.filesFetcher),this.filesFetcher.abortAll()};return d={start:M=>{let{videoElement:B,logger:F}=this.params,G=T(e.jidxUrl),$,D,I,U,k=0,R,C,be,N=()=>{R&&(clearTimeout(R),R=void 0);let z=Math.max(kk,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),Ne=k+z,$e=He(),pe=Math.min(1e4,Ne-$e);k=$e;let Ce=()=>{l||c()&&G.seek(()=>{c()&&(k=He(),re(),N())})};pe>0?R=window.setTimeout(()=>{this.paused?N():Ce()},pe):Ce()},re=()=>{let z;for(;z=G.nextChunk(U);)U=z,ce(z);let Ne=G.nextChunk(I);if(Ne){if(I&&Ne.discontinuity){F("Detected discontinuity; restarting playback"),this.paused?N():(w(),this._initPlayerWith(e));return}Ie(Ne)}else N()},le=(z,Ne)=>{if(!c()||!this.sourceBuffer)return;let $e,pe,Ce,pt=Ke=>{window.setTimeout(()=>{c()&&le(z,Ne)},Ke)};if(this.sourceBuffer.updating)F("Source buffer is updating; delaying appendBuffer"),pt(100);else{let Ke=He(),Ae=B.currentTime;!this.paused&&B.buffered.length>1&&C===Ae&&Ke-be>500&&(F("Stall suspected; trying to fix"),this._fixupStall()),C!==Ae&&(C=Ae,be=Ke);let ht=this._getBufferSizeSec();if(ht>30)F(`Buffered ${ht} seconds; delaying appendBuffer`),pt(2e3);else try{this.sourceBuffer.appendBuffer(z),this.videoPlayStarted?(this.bufferStates.push({ts:Ke,buf:ht}),v(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),Ne&&Ne()}catch(Fe){if(Fe.name==="QuotaExceededError")F("QuotaExceededError; delaying appendBuffer"),Ce=this.sourceBuffer.buffered.length,Ce!==0&&($e=this.sourceBuffer.buffered.start(0),pe=Ae,pe-$e>4&&this.sourceBuffer.remove($e,pe-3)),pt(1e3);else throw Fe}}},Te=()=>{D&&$&&(F([`Appending chunk, sz=${D.byteLength}:`,JSON.stringify(I)]),le(D,function(){D=null,re()}))},Be=z=>e.fragUrlTemplate.replace("%%id%%",z.chunkIdx),Ie=z=>{c()&&h(Be(z),(Ne,$e)=>{if(c()){if($e/=1e3,D=Ne,I=z,n=z.startTS,$e){let pe=Math.min(10,z.dur/$e);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*pe:pe}Te()}},()=>this._handleNetworkError())},ce=z=>{c()&&((0,At.assertNonNullable)(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(Be(z),!1)))},V=z=>{c()&&(e.cachedHeader=z,le(z,()=>{$=!0,Te()}))};a=!0,G.seek(z=>{if(c()){if(k=He(),!z){N();return}U=z,!(0,At.isNullable)(M)||z.startTS>M?Ie(z):(I=z,re())}},M),e.cachedHeader?V(e.cachedHeader):p(e.headerUrl,V,()=>this._handleNetworkError())},stop:w,getTimestampSec:()=>n},d}_switchToQuality(e){let{logger:t,playerCallback:i}=this.params,r;e.bitrate!==this.bitrate&&(this.rep&&(r=this.rep.getTimestampSec(),(0,At.isNonNullable)(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,(0,At.assertNonNullable)(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(r),i({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return(0,At.isNonNullable)(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,i=c=>{if(!this.autoQuality)return;let p,h,m;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&c<this.bitrate&&(h=this._getBufferSizeSec(),m=c/this.bitrate,h>10&&m>.8||h>15&&m>.5||h>20&&m>.3)){e(`Not switching: buffer=${Math.floor(h)}; bitrate=${this.bitrate}; newRate=${Math.floor(c)}`);return}p=this._selectQuality(c),p?this._switchToQuality(p):e(`Could not find quality by bitrate ${c}`)},a={updateChunk:(p,h)=>{let m=He();if(this.chunkRateEstimator.addInterval(p,m,h)){let v=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:h,duration:m-p,speed:v}),!0}},get:()=>{let p=this.chunkRateEstimator.getBitRate();return p?p*.85:0}},n=-1/0,o,u=!0,l=()=>{let c=a.get();if(c&&o&&this.autoQuality){if(u&&c>o&&Nl(n)<3e4)return;i(c)}u=this.autoQuality};return{updateChunk:(c,p)=>{let h=a.updateChunk(c,p);return h&&l(),h},notifySwitch:c=>{let p=He();c<o&&(n=p),o=c}}}_fetchManifest(e,t,i){this.manifestRequest=Ar(this.urlResolver.resolve(e,!0),t,i,()=>this._retryCallback()).withJSONResponse().withTimeout(Qn).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;lt(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,a=n=>{let o=[];return n?.length?(n.forEach((u,l)=>{u.video&&r.canPlayType(u.codecs).replace(/no/,"")&&window.MediaSource?.isTypeSupported?.(u.codecs)&&(u.index=l,o.push(u))}),o.sort(function(u,l){return u.video&&l.video?l.video.height-u.video.height:l.bitrate-u.bitrate}),o):(i({name:"error",type:"empty_manifest"}),[])};this.manifest=a(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))},wk))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};var yg=H(Ui(),1),Pe=require("@vkontakte/videoplayer-shared"),jl=class{constructor(){this.onDroopedVideoFramesLimit$=new Pe.Subject;this.subscription=new Pe.Subscription;this.playing=!1;this.tracks=[];this.forceChecker$=new Pe.Subject;this.isForceCheckCounter=0;this.prevTotalVideoFrames=0;this.prevDroppedVideoFrames=0;this.limitCounts={};this.handleChangeVideoQuality=()=>{let e=this.tracks.find(({size:t})=>t?.height===this.video.videoHeight&&t?.width===this.video.videoWidth);e&&!(0,Pe.isInvariantQuality)(e.quality)&&this.onChangeQuality(e.quality)};this.checkDroppedFrames=()=>{let{totalVideoFrames:e,droppedVideoFrames:t}=this.video.getVideoPlaybackQuality(),i=e-this.prevTotalVideoFrames,r=t-this.prevDroppedVideoFrames,a=1-(i-r)/i;!isNaN(a)&&a>0&&this.log({message:`[dropped]. current dropped percent: ${a}, limit: ${this.droppedFramesChecker.percentLimit}`}),!isNaN(a)&&a>=this.droppedFramesChecker.percentLimit&&(0,Pe.isHigher)(this.currentQuality,this.droppedFramesChecker.minQualityBanLimit)&&(this.limitCounts[this.currentQuality]=(this.limitCounts[this.currentQuality]??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((0,Pe.fromEvent)(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=(0,Pe.interval)(this.droppedFramesChecker.checkTime).pipe((0,Pe.filter)(()=>this.playing),(0,Pe.filter)(()=>{let r=!!this.isForceCheckCounter;return r&&(this.isForceCheckCounter-=1),!r})),t=this.forceChecker$.pipe((0,Pe.debounce)(this.droppedFramesChecker.checkTime)),i=(0,Pe.merge)(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){let t=(0,yg.default)(this.limitCounts).filter(([,i])=>i>=this.droppedFramesChecker.countLimit).sort(([i],[r])=>(0,Pe.isLower)(i,r)?-1:1)?.[0]?.[0];return 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}},Pr=jl;var Gn=require("@vkontakte/videoplayer-shared"),Tg=require("@vkontakte/videoplayer-shared");var Ts=()=>!!window.documentPictureInPicture?.window||!!document.pictureInPictureElement;var Rk=(s,e)=>new Gn.Observable(t=>{if(!window.IntersectionObserver)return;let i={root:null},r=new IntersectionObserver((n,o)=>{n.forEach(u=>t.next(u.isIntersecting||Ts()))},{...i,...e});r.observe(s);let a=(0,Tg.fromEvent)(document,"visibilitychange").pipe((0,Gn.map)(n=>!document.hidden||Ts())).subscribe(n=>t.next(n));return()=>{r.unobserve(s),a.unsubscribe()}}),Mt=Rk;var Mk=["paused","playing","ready"],Lk=["paused","playing","ready"],Is=class{constructor(e){this.subscription=new Q.Subscription;this.videoState=new ie("stopped");this.representations$=new Q.ValueSubject([]);this.droppedFramesManager=new Pr;this.maxSeekBackTime$=new Q.ValueSubject(1/0);this.zeroTime$=new Q.ValueSubject(void 0);this.liveOffset=new Wi;this._dashCb=e=>{switch(e.name){case"buffering":{let t=e.isBuffering;this.params.output.isBuffering$.next(t);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${e.type}`,category:Q.ErrorCategory.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{let t=e.manifest,i=[];for(let r of t){let a=r.name??r.index.toString(10),n=Pi(r.name)??(0,Q.videoSizeToQuality)(r.video),o=r.bitrate/1e3,u={...r.video};if(!n)continue;let l={id:a,quality:n,bitrate:o,size:u};i.push({track:l,representation:r})}this.representations$.next(i),this.params.output.availableVideoTracks$.next(i.map(({track:r})=>r)),this.videoState.getTransition()?.to==="manifest_ready"&&this.videoState.setState("manifest_ready");break}case"qualitySwitch":{let t=e.quality,i=this.representations$.getValue().find(({representation:r})=>r===t)?.track;this.params.output.hostname$.next(new URL(t.headerUrl,this.params.source.url).hostname),(0,Q.isNonNullable)(i)&&this.params.output.currentVideoTrack$.next(i);break}case"bandwidth":{let{size:t,duration:i}=e;this.params.dependencies.throughputEstimator.addRawSpeed(t,i);break}case"index":{this.maxSeekBackTime$.next(e.shiftDuration||0),this.zeroTime$.next(e.zeroTime);break}}};this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; seekState: ${JSON.stringify(a)};`}),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,Hl.default)(Lk,e)&&(n||o)){this.prepare();return}if(r?.to!=="paused"&&a.state==="requested"&&(0,Hl.default)(Mk,e)){this.seek(a.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(Le(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?.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(Le(this.params.source.url,u))}return;default:return(0,Q.assertNever)(e)}};this.textTracksManager=new Rt(e.source.url),this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=r=>{e.output.error$.next({id:"DashLiveProvider",category:Q.ErrorCategory.WTF,message:"DashLiveProvider internal logic error",thrown:r})};this.subscription.add((0,Q.merge)(this.videoState.stateChangeStarted$.pipe((0,Q.map)(r=>({transition:r,type:"start"}))),this.videoState.stateChangeEnded$.pipe((0,Q.map)(r=>({transition:r,type:"end"})))).subscribe(({transition:r,type:a})=>{this.log({message:`[videoState change] ${a}: ${JSON.stringify(r)}`})})),this.video=at(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(We(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=ut(this.video);this.subscription.add(()=>i.destroy()),this.subscription.add(this.representations$.pipe((0,Q.map)(r=>r.map(({track:a})=>a)),(0,Q.filter)(r=>!!r.length),(0,Q.once)()).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(()=>{this.videoState.getTransition()?.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((0,Q.filterChanged)(),(0,Q.map)(r=>-r/1e3)).subscribe(this.params.output.duration$)).add((0,Q.combine)({zeroTime:this.zeroTime$.pipe((0,Q.filter)(Q.isNonNullable)),position:i.timeUpdate$}).subscribe(({zeroTime:r,position:a})=>this.params.output.liveTime$.next(r+a*1e3),t)).add(Wt(this.video,this.params.desiredState.isLooped,t)).add(ot(this.video,this.params.desiredState.volume,i.volumeState$,t)).add(i.volumeState$.subscribe(this.params.output.volume$,t)).add(kt(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(Mt(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:r,min:a}})=>{this.dash.setAutoQualityLimits({max:r&&(0,Q.videoQualityToHeight)(r),min:a&&(0,Q.videoQualityToHeight)(a)}),this.params.output.autoVideoTrackLimits$.next({max:r,min:a})})).add(this.videoState.stateChangeEnded$.subscribe(r=>{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":this.params.desiredState.playbackState.getTransition()?.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(0,Q.assertNever)(r.to)}},t)).add((0,Q.merge)(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,(0,Q.observableFrom)(["init"])).pipe((0,Q.debounce)(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),nt(this.video)}createLiveDashPlayer(){let e=new ys({videoElement:this.video,videoState:this.videoState,playbackState:this.params.desiredState.playbackState,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(){let e=this.representations$.getValue(),t=this.params.desiredState.videoTrack.getTransition()?.to??this.params.desiredState.videoTrack.getState(),i=this.params.desiredState.autoVideoTrackSwitching.getTransition()?.to??this.params.desiredState.autoVideoTrackSwitching.getState(),r=!i&&(0,Q.isNonNullable)(t)?t:Yt(e.map(({track:l})=>l),{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}),a=r?.id,n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.videoTrack.getState()?.id,u=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(r&&(n||a!==o)&&this.setVideoTrack(r),u&&this.setAutoQuality(i),n||u||a!==o){let l=e.find(({track:d})=>d.id===a)?.representation;(0,Q.assertNonNullable)(l,"Representations missing"),this.dash.startPlay(l,i)}}setVideoTrack(e){let t=this.representations$.getValue().find(({track:i})=>i.id===e.id)?.representation;(0,Q.assertNonNullable)(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",a=-e,n=a<=this.maxSeekBackTime$.getValue()?a:0;this.params.output.position$.next(e/1e3),this.dash.reinit(Le(this.params.source.url,n)),r&&this.dash.pause(),this.liveOffset.resetTo(n,r)}};var Ig=Is;var xv=H(xt(),1);var ze=(s,e)=>{let t=0;for(let i=0;i<s.length;i++){let r=s.start(i)*1e3,a=s.end(i)*1e3;r<=e&&e<=a&&(t=a)}return Math.max(t-e,0)};var K=require("@vkontakte/videoplayer-shared");var Wn=class{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,i){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:i})}removeEventListener(e,t){if(!(e in this.listeners))return;let i=this.listeners[e];for(let r=0,a=i.length;r<a;r++)if(i[r].callback===t){i.splice(r,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;let i=this.listeners[e.type].slice();for(let r=0,a=i.length;r<a;r++){let n=i[r];try{n.callback.call(this,e)}catch(o){Promise.resolve().then(()=>{throw o})}n.options&&n.options.once&&this.removeEventListener(e.type,n.callback)}return!e.defaultPrevented}},kr=class extends Wn{constructor(){super(),this.listeners||Wn.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)}},xs=class{constructor(){Object.defineProperty(this,"signal",{value:new kr,writable:!0,configurable:!0})}abort(e){let t;try{t=new Event("abort")}catch{typeof document<"u"?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>"u")i=new Error("This operation was aborted"),i.name="AbortError";else try{i=new DOMException("signal is aborted without reason")}catch{i=new Error("This operation was aborted"),i.name="AbortError"}this.signal.reason=i,this.signal.dispatchEvent(t)}toString(){return"[object AbortController]"}};typeof Symbol<"u"&&Symbol.toStringTag&&(xs.prototype[Symbol.toStringTag]="AbortController",kr.prototype[Symbol.toStringTag]="AbortSignal");function Yn(s){return s.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof s.Request=="function"&&!s.Request.prototype.hasOwnProperty("signal")||!s.AbortController}function zl(s){typeof s=="function"&&(s={fetch:s});let{fetch:e,Request:t=e.Request,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r=!1}=s;if(!Yn({fetch:e,Request:t,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r}))return{fetch:e,Request:a};let a=t;(a&&!a.prototype.hasOwnProperty("signal")||r)&&(a=function(l,d){let c;d&&d.signal&&(c=d.signal,delete d.signal);let p=new t(l,d);return c&&Object.defineProperty(p,"signal",{writable:!1,enumerable:!1,configurable:!0,value:c}),p},a.prototype=t.prototype);let n=e;return{fetch:(u,l)=>{let d=a&&a.prototype.isPrototypeOf(u)?u.signal:l?l.signal:void 0;if(d){let c;try{c=new DOMException("Aborted","AbortError")}catch{c=new Error("Aborted"),c.name="AbortError"}if(d.aborted)return Promise.reject(c);let p=new Promise((h,m)=>{d.addEventListener("abort",()=>m(c),{once:!0})});return l&&l.signal&&delete l.signal,Promise.race([p,n(u,l)])}return n(u,l)},Request:a}}var Bk=()=>"fetch"in window,Es=Bk()&&Yn({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),xg=Es?zl({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,Lt=Es?xg.fetch:window.fetch,VV=Es?xg.Request:window.Request,de=Es?xs:window.AbortController,OV=Es?kr:window.AbortSignal;var Sc=H(ws(),1);var lS=H(uS(),1),Rr=require("@vkontakte/videoplayer-shared"),Kn=s=>{if(!s)return{id:"EmptyResponse",category:Rr.ErrorCategory.PARSER,message:"Empty response"};if(s.length<=2&&s.match(/^\d+$/))return{id:`UVError#${s}`,category:Rr.ErrorCategory.NETWORK,message:`UV Error ${s}`};let e=(0,lS.default)(s).substring(0,100).toLowerCase();if(e.startsWith("<!doctype")||e.startsWith("<html>")||e.startsWith("<body>")||e.startsWith("<head>"))return{id:"UnexpectedHTML",category:Rr.ErrorCategory.NETWORK,message:"Received unexpected HTML, possibly a ISP block"};if(e.startsWith("<?xml"))return new DOMParser().parseFromString(s,"text/xml").querySelector("parsererror")?{id:"InvalidXML",category:Rr.ErrorCategory.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:Rr.ErrorCategory.PARSER,message:"Response is valid XML, but parser failed"}};var Ye=(s,e,t=0)=>{for(let i=0;i<s.length;i++)if(s.start(i)*1e3-t<=e&&s.end(i)*1e3+t>e)return!0;return!1};var y=require("@vkontakte/videoplayer-shared");var Jn=H(xt(),1),Cr=H(Ut(),1),Zn=H(ws(),1);var gR=(s,e={})=>{let i=e.timeout||1,r=performance.now();return window.setTimeout(()=>{s({get didTimeout(){return e.timeout?!1:performance.now()-r-1>i},timeRemaining(){return Math.max(0,1+(performance.now()-r))}})},1)},SR=s=>window.clearTimeout(s),cS=s=>typeof s=="function"&&s?.toString().endsWith("{ [native code] }"),dS=!cS(window.requestIdleCallback)||!cS(window.cancelIdleCallback),Mr=dS?gR:window.requestIdleCallback,Xt=dS?SR:window.cancelIdleCallback;var hv=H(Rn(),1);var Ri=require("@vkontakte/videoplayer-shared");var vR=18,pS=!1;try{pS=W.browser.isSafari&&!!W.browser.safariVersion&&W.browser.safariVersion<=vR}catch(s){console.error(s)}var Xl=class{constructor(e){this.bufferFull$=new Ri.Subject;this.error$=new Ri.Subject;this.queue=[];this.currentTask=null;this.destroyed=!1;this.abortRequested=!1;this.completeTask=()=>{try{if(this.currentTask){let e=this.currentTask.signal?.aborted;this.currentTask.callback(!e),this.currentTask=null}this.queue.length&&this.pull()}catch(e){this.error$.next({id:"BufferTaskQueueUnknown",category:Ri.ErrorCategory.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:e})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(i=>{let r={operation:"append",data:e,signal:t,callback:i};this.queue.push(r),this.pull()})}async remove(e,t,i){return i&&i.aborted?!1:new Promise(r=>{let a={operation:"remove",from:e,to:t,signal:i,callback:r};this.queue.unshift(a),this.pull()})}async abort(e){return new Promise(t=>{let i,r=a=>{this.abortRequested=!1,t(a)};pS&&e?i={operation:"safariAbort",init:e,callback:r}:i={operation:"abort",callback:r};for(let{callback:a}of this.queue)a(!1);this.abortRequested=!0,i&&(this.queue=[i]),this.pull()})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){if((this.buffer.updating||this.currentTask||this.destroyed)&&!this.abortRequested)return;let e=this.queue.shift();if(!e)return;if(e.signal?.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(r){r instanceof DOMException&&r.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):r instanceof DOMException&&r.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:Ri.ErrorCategory.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:r}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){let{operation:t}=e;switch(t){case"append":this.buffer.appendBuffer(e.data);break;case"remove":this.buffer.remove(e.from/1e3,e.to/1e3);break;case"abort":this.buffer.abort();break;case"safariAbort":{this.buffer.abort(),this.buffer.appendBuffer(e.init);break}default:(0,Ri.assertNever)(t)}}},hS=Xl;var Lr=s=>{let e=0;for(let t=0;t<s.length;t++)e+=s.end(t)-s.start(t);return e*1e3};var A=require("@vkontakte/videoplayer-shared");var ae=class{constructor(e,t){this.cursor=0;this.source=e,this.boxParser=t,this.children=[];let i=this.readUint32();this.type=this.readString(4),this.size32=i<=e.buffer.byteLength-e.byteOffset?i:NaN;let r=this.size32?this.size32-8:void 0,a=e.byteOffset+this.cursor;this.size64=0,this.usertype=0,this.content=new DataView(e.buffer,a,r)}get id(){return this.type}get size(){return this.size32}scanForBoxes(e){return this.boxParser.parse(e)}readString(e,t="ascii"){let r=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,r}readUint8(){let e=this.source.getUint8(this.cursor);return this.cursor+=1,e}readUint16(){let e=this.source.getUint16(this.cursor);return this.cursor+=2,e}readUint32(){let e=this.source.getUint32(this.cursor);return this.cursor+=4,e}readUint64(){let e=this.source.getBigInt64(this.cursor);return this.cursor+=8,e}};var Br=class extends ae{};var Ps=class extends ae{constructor(t,i){super(t,i);this.ondemandPrefix="ondemandlivejson";this.ondemandDataReceivedKey="t-in";this.ondemandDataPreparedKey="t-out";let r=this.content.byteOffset,a=r+this.content.byteLength,n=new TextDecoder("ascii").decode(this.content.buffer.slice(r,a)).split(this.ondemandPrefix)[1],o=JSON.parse(n);this.serverDataReceivedTimestamp=o[this.ondemandDataReceivedKey],this.serverDataPreparedTime=o[this.ondemandDataPreparedKey]}};var ks=class extends ae{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 Rs=class extends ae{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ge=class extends ae{constructor(e,t){super(e,t);let i=this.readUint32();this.version=i>>>24,this.flags=i&16777215}};var Ms=class extends ge{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 Ls=class extends ae{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Bs=class extends ae{constructor(e,t){super(e,t),this.data=this.content}};var Ki=class extends ge{get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e,t){super(e,t),this.segments=[],this.referenceId=this.readUint32(),this.timescale=this.readUint32(),this.earliestPresentationTime32=this.readUint32(),this.firstOffset32=this.readUint32(),this.earliestPresentationTime64=0,this.firstOffset64=0,this.referenceCount=this.readUint32()&65535;for(let i=0;i<this.referenceCount;i++){let r=this.readUint32(),a=r>>>31,n=r<<1>>>1,o=this.readUint32();r=this.readUint32();let u=r>>>28,l=r<<3>>>3;this.segments.push({referenceType:a,referencedSize:n,subsegmentDuration:o,SAPType:u,SAPDeltaTime:l})}}};var $s=class extends ae{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ds=class extends ae{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Cs=class extends ge{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 Vs=class extends ge{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var Os=class extends ge{constructor(e,t){super(e,t),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}};var _s=class extends ae{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Fs=class extends ge{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 Ns=class extends ae{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Us=class extends ae{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var qs=class extends ge{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var js=class extends ae{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Hs=class extends ge{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 zs=class extends ge{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 Qs=class extends ge{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 Gs=class extends ae{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ws=class extends ge{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 Ys=class extends ae{constructor(e,t){super(e,t),this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+78,this.content.byteLength-78))}};var TR={ftyp:ks,moov:Rs,mvhd:Ms,moof:Ls,mdat:Bs,sidx:Ki,trak:$s,mdia:_s,mfhd:qs,tkhd:Fs,traf:js,tfhd:Hs,tfdt:zs,trun:Qs,minf:Ns,sv3d:Ds,st3d:Cs,prhd:Vs,proj:Us,equi:Os,uuid:Ps,stbl:Gs,stsd:Ws,avc1:Ys,unknown:Br},pi=class s{constructor(e={}){this.options={offset:0,...e}}parse(e){let t=[],i=this.options.offset;for(;i<e.byteLength;)try{let a=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+i+4,4)),n=this.createBox(a,new DataView(e.buffer,e.byteOffset+i));if(!n.size)break;t.push(n),i+=n.size}catch{break}return t}createBox(e,t){let i=TR[e];return i?new i(t,new s):new Br(t,new s)}};var Mi=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{this.index[t.type]??=[],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 xR=new TextDecoder("ascii"),ER=s=>xR.decode(new DataView(s.buffer,s.byteOffset+4,4))==="ftyp",wR=s=>{let e=new Ki(s,new pi),t=e.earliestPresentationTime/e.timescale*1e3,i=s.byteOffset+s.byteLength+e.firstOffset;return e.segments.map(a=>{if(a.referenceType!==0)throw new Error("Unsupported multilevel sidx");let n=a.subsegmentDuration/e.timescale*1e3,o={status:"none",time:{from:t,to:t+n},byte:{from:i,to:i+a.referencedSize-1}};return t+=n,i+=a.referencedSize,o})},AR=(s,e)=>{let i=new pi().parse(s),r=new Mi(i),a=r.findAll("moof"),n=e?r.findAll("uuid"):r.findAll("mdat");if(!(n.length&&a.length))return null;let o=a[0],u=n[n.length-1],l=o.source.byteOffset,c=u.source.byteOffset-o.source.byteOffset+u.size;return new DataView(s.buffer,l,c)},PR=s=>{let t=new pi().parse(s),i=new Mi(t),r={},a=i.findAll("uuid");return a.length?a[a.length-1]:r},kR=s=>{let t=new pi().parse(s);return new Mi(t).find("sidx")?.timescale},RR=(s,e)=>{let i=new pi().parse(s),a=new Mi(i).findAll("traf"),n=a[a.length-1].children.find(c=>c.type==="tfhd"),o=a[a.length-1].children.find(c=>c.type==="tfdt"),u=a[a.length-1].children.find(c=>c.type==="trun"),l=0;return u.sampleDuration.length?l=u.sampleDuration.reduce((c,p)=>c+p,0):l=n.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+l)/e*1e3},MR=s=>{let e={is3dVideo:!1,stereoMode:0,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}},i=new pi().parse(s),r=new Mi(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},fS={validateData:ER,parseInit:MR,getIndexRange:()=>{},parseSegments:wR,parseFeedableSegmentChunk:AR,getChunkEndTime:RR,getServerLatencyTimestamps:PR,getTimescaleFromIndex:kR};var Xs=H(xt(),1),hi=require("@vkontakte/videoplayer-shared");var bS=require("@vkontakte/videoplayer-shared");var mS={440786851:{type:"master"},17030:{type:"uint"},17143:{type:"uint"},17138:{type:"uint"},17139:{type:"uint"},17026:{type:"string"},17031:{type:"uint"},17029:{type:"uint"},236:{type:"binary"},408125543:{type:"master"},290298740:{type:"master"},19899:{type:"master"},21419:{type:"binary"},21420:{type:"uint"},357149030:{type:"master"},2807729:{type:"uint"},17545:{type:"float"},374648427:{type:"master"},174:{type:"master"},224:{type:"master"},30320:{type:"master"},30321:{type:"uint"},30322:{type:"master"},272869232:{type:"master"},524531317:{type:"master"},231:{type:"uint"},22612:{type:"master"},22743:{type:"uint"},167:{type:"uint"},171:{type:"uint"},163:{type:"binary"},160:{type:"master"},175:{type:"binary"},423732329:{type:"master"},307544935:{type:"master"},475249515:{type:"master"},187:{type:"master"},179:{type:"uint"},183:{type:"master"},247:{type:"uint"},241:{type:"uint"},240:{type:"uint"},178:{type:"uint"},21368:{type:"uint"},234:{type:"uint"},219:{type:"master"},150:{type:"uint"}},gS=s=>{let e=s.getUint8(0),t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);let i=Ks(s,t),r=i in mS,a=r?mS[i].type:"binary",n=s.getUint8(t),o=0;n&128?o=1:n&64?o=2:n&32?o=3:n&16?o=4:n&8?o=5:n&4?o=6:n&2?o=7:n&1&&(o=8);let u=new DataView(s.buffer,s.byteOffset+t+1,o-1),l=n&255>>o,d=Ks(u),c=l*2**((o-1)*8)+d,p=t+o,h;return p+c>s.byteLength?h=new DataView(s.buffer,s.byteOffset+p):h=new DataView(s.buffer,s.byteOffset+p,c),{tag:r?i:"0x"+i.toString(16).toUpperCase(),type:a,tagHeaderSize:p,tagSize:p+c,value:h,valueSize:c}},Ks=(s,e=s.byteLength)=>{switch(e){case 1:return s.getUint8(0);case 2:return s.getUint16(0);case 3:return s.getUint8(0)*2**16+s.getUint16(1);case 4:return s.getUint32(0);case 5:return s.getUint8(0)*2**32+s.getUint32(1);case 6:return s.getUint16(0)*2**32+s.getUint32(2);case 7:{let t=s.getUint8(0)*281474976710656+s.getUint16(1)*4294967296+s.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},qt=(s,e)=>{switch(e){case"int":return s.getInt8(0);case"uint":return Ks(s);case"float":return s.byteLength===4?s.getFloat32(0):s.getFloat64(0);case"string":return new TextDecoder("ascii").decode(s);case"utf8":return new TextDecoder("utf-8").decode(s);case"date":return new Date(Date.UTC(2001,0)+s.getInt8(0)).getTime();case"master":return s;case"binary":return s;default:(0,bS.assertNever)(e)}},Xi=(s,e)=>{let t=0;for(;t<s.byteLength;){let i=new DataView(s.buffer,s.byteOffset+t),r=gS(i);if(!e(r))return;r.type==="master"&&Xi(r.value,e),t=r.value.byteOffset-s.byteOffset+r.valueSize}},SS=s=>{if(s.getUint32(0)!==440786851)return!1;let e,t,i,r=gS(s);return Xi(r.value,({tag:a,type:n,value:o})=>(a===17143?e=qt(o,n):a===17026?t=qt(o,n):a===17029&&(i=qt(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)};var vS=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],LR=[231,22612,22743,167,171,163,160,175],BR=s=>{let e,t,i,r,a=!1,n=!1,o=!1,u,l,d=!1,c=0;return Xi(s,({tag:p,type:h,value:m,valueSize:g})=>{if(p===21419){let v=qt(m,h);l=Ks(v)}else p!==21420&&(l=void 0);return p===408125543?(e=m.byteOffset,t=m.byteOffset+g):p===357149030?a=!0:p===290298740?n=!0:p===2807729?i=qt(m,h):p===17545?r=qt(m,h):p===21420&&l===475249515?u=qt(m,h):p===374648427?Xi(m,({tag:v,type:T,value:w})=>v===30321?(d=qt(w,T)===1,!1):!0):a&&n&&(0,Xs.default)(vS,p)&&(o=!0),!o}),(0,hi.assertNonNullable)(e,"Failed to parse webm Segment start"),(0,hi.assertNonNullable)(t,"Failed to parse webm Segment end"),(0,hi.assertNonNullable)(r,"Failed to parse webm Segment duration"),i=i??1e6,{segmentStart:Math.round(e/1e9*i*1e3),segmentEnd:Math.round(t/1e9*i*1e3),timeScale:i,segmentDuration:Math.round(r/1e9*i*1e3),cuesSeekPosition:u,is3dVideo:d,stereoMode:c,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},$R=s=>{if((0,hi.isNullable)(s.cuesSeekPosition))return;let e=s.segmentStart+s.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},DR=(s,e)=>{let t=!1,i=!1,r=o=>(0,hi.isNonNullable)(o.time)&&(0,hi.isNonNullable)(o.position),a=[],n;return Xi(s,({tag:o,type:u,value:l})=>{switch(o){case 475249515:t=!0;break;case 187:n&&r(n)&&a.push(n),n={};break;case 179:n&&(n.time=qt(l,u));break;case 183:break;case 241:n&&(n.position=qt(l,u));break;default:t&&(0,Xs.default)(vS,o)&&(i=!0)}return!(t&&i)}),n&&r(n)&&a.push(n),a.map((o,u)=>{let{time:l,position:d}=o,c=a[u+1];return{status:"none",time:{from:l,to:c?c.time:e.segmentDuration},byte:{from:e.segmentStart+d,to:c?e.segmentStart+c.position-1:e.segmentEnd-1}}})},CR=s=>{let e=0,t=!1;try{Xi(s,i=>i.tag===524531317?i.tagSize<=s.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):(0,Xs.default)(LR,i.tag)?(e+i.tagSize<=s.byteLength&&(e+=i.tagSize,t||=(0,Xs.default)([163,160,175],i.tag)),!0):!1)}catch{}return e>0&&e<=s.byteLength&&t?new DataView(s.buffer,s.byteOffset,e):null},yS={validateData:SS,parseInit:BR,getIndexRange:$R,parseSegments:DR,parseFeedableSegmentChunk:CR};var Js=s=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(s);if(e){let[,t,i]=e;if(t==="audio"||t==="video")switch(i){case"webm":return yS;case"mp4":return fS}}throw new ReferenceError(`Unsupported mime type ${s}`)};var dc=H(sc(),1),lv=H(Ui(),1),cv=H(ac(),1),dv=H(Ut(),1),pc=H(Gi(),1);var tv=H(xt(),1),Dr=s=>{let e=s.split("."),[t,...i]=e;if(!t)return!1;switch(t){case"av01":{let[r,a,n]=i;return!!(n&&parseInt(n,10)>8)}case"vp09":{let[r,a,n]=i;return!!(r&&parseInt(r,10)>=2&&n&&parseInt(n,10)>8)}case"avc1":{let r=i[0];if(!r||r.length!==6)return!1;let[a,n]=r.toUpperCase(),o=a+n;return(0,tv.default)(["6E","7A","F4"],o)}}return!1};var ea=require("@vkontakte/videoplayer-shared");var Xn=s=>{if(s.includes("/")){let e=s.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(s)};var iv=s=>{try{let e=MM(),t=s.match(e),{groups:i}=t??{};if(i){let r={};if(i.extensions){let o=i.extensions.toLowerCase().match(/(?:[0-9a-wy-z](?:-[a-z0-9]{2,8})+)/g);Array.from(o||[]).forEach(u=>{r[u[0]]=u.slice(2)})}let a=i.variants?.split(/-/).filter(o=>o!==""),n={extlang:i.extlang,langtag:i.langtag,language:i.language,privateuse:i.privateuse||i.privateuse2,region:i.region,script:i.script,extensions:r,variants:a};return Object.keys(n).forEach(o=>{let u=n[o];(typeof u>"u"||u==="")&&delete n[o]}),n}return null}catch{return null}};function MM(){let s="(?<extlang>(?:[a-z]{3}(?:-[a-z]{3}){0,2}))",e="x(?:-[a-z0-9]{1,8})+",d=`^(?:(?<langtag>${`
|
|
118
118
|
(?<language>${`(?:[a-z]{2,3}(?:-${s})?|[a-z]{4}|[a-z]{5,8})`})
|
|
119
119
|
(-(?<script>[a-z]{4}))?
|
|
120
120
|
(-(?<region>(?:[a-z]{2}|[0-9]{3})))?
|
|
121
121
|
(?<variants>(?:-(?:[a-z0-9]{5,8}|[0-9][a-z0-9]{3}))*)
|
|
122
122
|
(?<extensions>(?:-[0-9a-wy-z](?:-[a-z0-9]{2,8})+)*)
|
|
123
123
|
(?:-(?<privateuse>(?:${e})))?
|
|
124
|
-
`})|(?<privateuse2>${e}))$`.replace(/[\s\t\n]/g,"");return new RegExp(p,"i")}var oc=j(Ut(),1);var rv=require("@vkontakte/videoplayer-shared"),sv=({id:s,width:e,height:t,bitrate:i,fps:r,quality:a,streamId:n})=>{let o=(a?Ai(a):void 0)??(0,rv.videoSizeToQuality)({width:e,height:t});return o&&{id:s,quality:o,bitrate:i,size:{width:e,height:t},fps:r,streamId:n}},av=({id:s,bitrate:e})=>({id:s,bitrate:e}),nv=({language:s,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:s,label:e}),ov=({language:s,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:s,label:e}),uc=({id:s,language:e,label:t,codecs:i,isDefault:r})=>({id:s,language:e,label:t,codec:(0,oc.default)(i.split("."),0),isDefault:r}),lc=({id:s,language:e,label:t,hdr:i,codecs:r})=>({id:s,language:e,hdr:i,label:t,codec:(0,oc.default)(r.split("."),0)}),cc=s=>"url"in s,rt=s=>s.type==="template",Zs=s=>s instanceof DOMException&&(s.name==="AbortError"||s.code===20);var uv=s=>{if(!s?.startsWith("P"))return;let e=(n,o)=>{let u=n?parseFloat(n.replace(",",".")):NaN;return(isNaN(u)?0:u)*o},i=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(s),r=i?.[1]==="-"?-1:1,a={days:e(i?.[5],r),hours:e(i?.[6],r),minutes:e(i?.[7],r),seconds:e(i?.[8],r)};return a.days*24*60*60*1e3+a.hours*60*60*1e3+a.minutes*60*1e3+a.seconds*1e3},fi=(s,e)=>{let t=s;t=(0,dc.default)(t,"$$","$");let i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[r,a]of(0,lv.default)(i)){let n=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=(0,dc.default)(t,n,(o,u)=>(0,ea.isNullable)(a)?o:(0,ea.isNullable)(u)?a:(0,cv.default)(a,parseInt(u,10),"0"))}return t},pv=(s,e)=>{let i=new DOMParser().parseFromString(s,"application/xml"),r={video:[],audio:[],text:[]},a=i.children[0],n=Array.from(a.querySelectorAll("MPD > BaseURL").values()).map(D=>D.textContent?.trim()??""),o=(0,dv.default)(n,0)??"",u=a.getAttribute("type")==="dynamic",l=a.getAttribute("availabilityStartTime"),p=a.getAttribute("publishTime"),c=a.getElementsByTagName("vk:Attrs")[0],d=c?.getElementsByTagName("vk:XLatestSegmentPublishTime")[0].textContent,h=c?.getElementsByTagName("vk:XStreamIsLive")[0].textContent,m=c?.getElementsByTagName("vk:XStreamIsUnpublished")[0].textContent,g=c?.getElementsByTagName("vk:XPlaybackDuration")[0].textContent,v;u&&(v={availabilityStartTime:l?new Date(l).getTime():0,publishTime:p?new Date(p).getTime():0,latestSegmentPublishTime:d?new Date(d).getTime():0,streamIsAlive:h==="yes",streamIsUnpublished:m==="yes"});let T,P=a.getAttribute("mediaPresentationDuration"),x=[...a.getElementsByTagName("Period")],L=x.reduce((D,I)=>({...D,[I.id]:I.children}),{}),B=x.reduce((D,I)=>({...D,[I.id]:I.getAttribute("duration")}),{});P?T=uv(P):(0,pc.default)(B).filter(D=>D).length&&!u?T=(0,pc.default)(B).reduce((D,I)=>D+(uv(I)??0),0):g&&(T=parseInt(g,10));let F=0,G=a.getAttribute("profiles")?.split(",")??[];for(let D of x.map(I=>I.id))for(let I of L[D]){let U=I.getAttribute("id")??"id"+(F++).toString(10),k=I.getAttribute("mimeType")??"",R=I.getAttribute("codecs")??"",C=I.getAttribute("contentType")??k?.split("/")[0],be=I.getAttribute("profiles")?.split(",")??[],N=iv(I.getAttribute("lang")??"")??{},re=I.querySelector("Label")?.textContent?.trim()??void 0,le=I.querySelectorAll("Representation"),Te=I.querySelector("SegmentTemplate"),Be=I.querySelector("Role")?.getAttribute("value")??void 0,Ie=C,ce={id:U,language:N.language,isDefault:Be==="main",label:re,codecs:R,hdr:Ie==="video"&&Dr(R),mime:k,representations:[]};for(let V of le){let z=V.getAttribute("lang")??void 0,Ne=re??I.getAttribute("label")??V.getAttribute("label")??void 0,$e=V.querySelector("BaseURL")?.textContent?.trim()??"",pe=new URL($e||o,e).toString(),Ce=V.getAttribute("mimeType")??k,pt=V.getAttribute("codecs")??R??"",Ke;if(C==="text"){let Pe=V.getAttribute("id")||"",ht=N.privateuse?.includes("x-auto")||Pe.includes("_auto"),Fe=V.querySelector("SegmentTemplate");if(Fe){let $t={representationId:V.getAttribute("id")??void 0,bandwidth:V.getAttribute("bandwidth")??void 0},Zt=parseInt(V.getAttribute("bandwidth")??"",10)/1e3,ei=parseInt(Fe.getAttribute("startNumber")??"",10)??1,ft=parseInt(Fe.getAttribute("timescale")??"",10),Ci=Fe.querySelectorAll("SegmentTimeline S")??[],mt=Fe.getAttribute("media");if(!mt)continue;let ti=[],ii=0,ri="",bt=0,Dt=ei,oe=0;for(let xe of Ci){let Xe=parseInt(xe.getAttribute("d")??"",10),he=parseInt(xe.getAttribute("r")??"",10)||0,Ue=parseInt(xe.getAttribute("t")??"",10);oe=Number.isFinite(Ue)?Ue:oe;let Je=Xe/ft*1e3,gt=oe/ft*1e3;for(let ke=0;ke<he+1;ke++){let qe=fi(mt,{...$t,segmentNumber:Dt.toString(10),segmentTime:(oe+ke*Xe).toString(10)}),St=(gt??0)+ke*Je,Vt=St+Je;Dt++,ti.push({time:{from:St,to:Vt},url:qe})}oe+=(he+1)*Xe,ii+=(he+1)*Je}bt=oe/ft*1e3,ri=fi(mt,{...$t,segmentNumber:Dt.toString(10),segmentTime:oe.toString(10)});let Ct={time:{from:bt,to:1/0},url:ri},Ve={type:"template",baseUrl:pe,segmentTemplateUrl:mt,initUrl:"",totalSegmentsDurationMs:ii,segments:ti,nextSegmentBeyondManifest:Ct,timescale:ft};Ke={id:Pe,kind:"text",segmentReference:Ve,profiles:[],duration:T,bitrate:Zt,mime:"",codecs:"",width:0,height:0,isAuto:ht}}else Ke={id:Pe,isAuto:ht,kind:"text",url:pe}}else{let Pe=V.getAttribute("contentType")??Ce?.split("/")[0]??C,ht=I.getAttribute("profiles")?.split(",")??[],Fe=parseInt(V.getAttribute("width")??"",10),$t=parseInt(V.getAttribute("height")??"",10),Zt=parseInt(V.getAttribute("bandwidth")??"",10)/1e3,ei=V.getAttribute("frameRate")??"",ft=V.getAttribute("quality")??void 0,Ci=ei?Xn(ei):void 0,mt=V.getAttribute("id")??"id"+(F++).toString(10),ti=Pe==="video"?`${$t}p`:Pe==="audio"?`${Zt}Kbps`:pt,ii=`${mt}@${ti}`,ri=[...G,...be,...ht],bt,Dt=V.querySelector("SegmentBase"),oe=V.querySelector("SegmentTemplate")??Te;if(Dt){let Ve=V.querySelector("SegmentBase Initialization")?.getAttribute("range")??"",[xe,Xe]=Ve.split("-").map(qe=>parseInt(qe,10)),he={from:xe,to:Xe},Ue=V.querySelector("SegmentBase")?.getAttribute("indexRange"),[Je,gt]=Ue?Ue.split("-").map(qe=>parseInt(qe,10)):[],ke=Ue?{from:Je,to:gt}:void 0;bt={type:"byteRange",url:pe,initRange:he,indexRange:ke}}else if(oe){let Ve={representationId:V.getAttribute("id")??void 0,bandwidth:V.getAttribute("bandwidth")??void 0},xe=parseInt(oe.getAttribute("timescale")??"",10),Xe=oe.getAttribute("initialization")??"",he=oe.getAttribute("media"),Ue=parseInt(oe.getAttribute("startNumber")??"",10)??1,Je=fi(Xe,Ve);if(!he)throw new ReferenceError("No media attribute in SegmentTemplate");let gt=oe.querySelectorAll("SegmentTimeline S")??[],ke=[],qe=0,St="",Vt=0;if(gt.length){let si=Ue,Ee=0;for(let vt of gt){let Re=parseInt(vt.getAttribute("d")??"",10),Ze=parseInt(vt.getAttribute("r")??"",10)||0,ai=parseInt(vt.getAttribute("t")??"",10);Ee=Number.isFinite(ai)?ai:Ee;let Vi=Re/xe*1e3,Co=Ee/xe*1e3;for(let ni=0;ni<Ze+1;ni++){let Vo=fi(he,{...Ve,segmentNumber:si.toString(10),segmentTime:(Ee+ni*Re).toString(10)}),Ur=(Co??0)+ni*Vi,Oo=Ur+Vi;si++,ke.push({time:{from:Ur,to:Oo},url:Vo})}Ee+=(Ze+1)*Re,qe+=(Ze+1)*Vi}Vt=Ee/xe*1e3,St=fi(he,{...Ve,segmentNumber:si.toString(10),segmentTime:Ee.toString(10)})}else if((0,ea.isNonNullable)(T)){let Ee=parseInt(oe.getAttribute("duration")??"",10)/xe*1e3,vt=Math.ceil(T/Ee),Re=0;for(let Ze=1;Ze<vt;Ze++){let ai=fi(he,{...Ve,segmentNumber:Ze.toString(10),segmentTime:Re.toString(10)});ke.push({time:{from:Re,to:Re+Ee},url:ai}),Re+=Ee}Vt=Re,St=fi(he,{...Ve,segmentNumber:vt.toString(10),segmentTime:Re.toString(10)})}let Do={time:{from:Vt,to:1/0},url:St};bt={type:"template",baseUrl:pe,segmentTemplateUrl:he,initUrl:Je,totalSegmentsDurationMs:qe,segments:ke,nextSegmentBeyondManifest:Do,timescale:xe}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!Pe||!Ce)continue;let Ct={video:"video",audio:"audio",text:"text"}[Pe];if(!Ct)continue;Ie||=Ct,Ke={id:ii,kind:Ct,segmentReference:bt,profiles:ri,duration:T,bitrate:Zt,mime:Ce,codecs:pt,width:Fe,height:$t,fps:Ci,quality:ft}}ce.language||=z,ce.label||=Ne,ce.mime||=Ce,ce.codecs||=pt,ce.hdr||=Ie==="video"&&Dr(pt),ce.representations.push(Ke)}if(Ie){let V=r[Ie].find(z=>z.id===ce.id);if(V&&ce.representations.every(z=>rt(z.segmentReference)))for(let z of V.representations){let $e=ce.representations.find(Ce=>Ce.id===z.id)?.segmentReference,pe=z.segmentReference;pe.segments.push(...$e.segments),pe.nextSegmentBeyondManifest=$e.nextSegmentBeyondManifest}else r[Ie].push(ce)}}return{duration:T,streams:r,baseUrls:n,live:v}};var fc=require("@vkontakte/videoplayer-shared"),Y=(s,e)=>(0,fc.isNonNullable)(s)&&(0,fc.isNonNullable)(e)&&s.readyState==="open"&&LM(s,e);function LM(s,e){for(let t=0;t<s.activeSourceBuffers.length;++t)if(s.activeSourceBuffers[t]===e)return!0;return!1}var ta=class{constructor(e,t,i,{fetcher:r,tuning:a,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new w.ValueSubject(0);this.currentLowLatencySegmentLength$=new w.ValueSubject(0);this.currentSegmentLength$=new w.ValueSubject(0);this.onLastSegment$=new w.ValueSubject(!1);this.fullyBuffered$=new w.ValueSubject(!1);this.playingRepresentation$=new w.ValueSubject(void 0);this.playingRepresentationInit$=new w.ValueSubject(void 0);this.error$=new w.Subject;this.gaps=[];this.subscription=new w.Subscription;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new de;this.switchAbortController=new de;this.destroyAbortController=new de;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=(0,w.abortable)(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);(0,w.assertNonNullable)(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new hS(this.sourceBuffer),this.subscription.add((0,w.fromEvent)(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let o,u=this.mediaSource.readyState;u!=="open"&&(o={id:`SegmentEjection_source_${u}`,category:w.ErrorCategory.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o??={id:"SegmentEjection",category:w.ErrorCategory.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n},this.error$.next(o)})),this.subscription.add((0,w.fromEvent)(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:w.ErrorCategory.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o||!Y(this.mediaSource,this.sourceBuffer))return;let u=Math.min(this.bufferLimit,Lr(this.sourceBuffer.buffered)*.8);this.bufferLimit=u;let l=this.getForwardBufferDuration(o),p=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(o,n*2,l<p).catch(c=>{this.handleAsyncError(c,"pruneBuffer")})})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(n=>this.error$.next(n))),yield this.loadInit(t,"high",!0);let i=this.initData.get(t.id),r=this.segments.get(t.id),a=this.parsedInitData.get(t.id);(0,w.assertNonNullable)(i,"No init buffer for starting representation"),(0,w.assertNonNullable)(r,"No segments for starting representation"),i instanceof ArrayBuffer&&(this.searchGaps(r,t),yield this.sourceBufferTaskQueue.append(i,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(a))}.bind(this));this.switchTo=(0,w.abortable)(this.destroyAbortController.signal,async function*(e,t=!1){if(!Y(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);(0,w.assertNonNullable)(i,`No such representation ${e}`);let r=this.segments.get(e),a=this.initData.get(e);if((0,w.isNullable)(a)||(0,w.isNullable)(r)?yield this.loadInit(i,"high",!1):a instanceof Promise&&(yield a),r=this.segments.get(e),(0,w.assertNonNullable)(r,"No segments for starting representation"),a=this.initData.get(e),!(!a||!(a instanceof ArrayBuffer)||!this.sourceBuffer||!Y(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(a,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer();else{let n=this.getCurrentPosition();(0,w.isNonNullable)(n)&&!this.isLive&&(this.bufferLimit=1/0,await this.pruneBuffer(n,1/0,!0)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}this.maintain()}}.bind(this));this.switchToOld=(0,w.abortable)(this.destroyAbortController.signal,async function*(e,t=!1){if(!Y(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);(0,w.assertNonNullable)(i,`No such representation ${e}`);let r=this.segments.get(e),a=this.initData.get(e);if((0,w.isNullable)(a)||(0,w.isNullable)(r)?yield this.loadInit(i,"high",!1):a instanceof Promise&&(yield a),r=this.segments.get(e),(0,w.assertNonNullable)(r,"No segments for starting representation"),a=this.initData.get(e),!(!a||!(a instanceof ArrayBuffer)||!this.sourceBuffer||!Y(this.mediaSource,this.sourceBuffer)))if(yield this.abort(),yield this.sourceBufferTaskQueue.append(a,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer(),this.maintain();else{let n=this.getCurrentPosition();(0,w.isNonNullable)(n)&&(this.isLive||(this.bufferLimit=1/0,await this.pruneBuffer(n,1/0,!0)),this.maintain(n)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}}.bind(this));this.seekLive=(0,w.abortable)(this.destroyAbortController.signal,async function*(e){let t=(0,Zn.default)(e,u=>u.representations)??[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let u of this.representations.keys()){let l=t.find(d=>d.id===u);l&&this.representations.set(u,l);let p=this.representations.get(u);if(!p||!rt(p.segmentReference))return;let c=this.getActualLiveStartingSegments(p.segmentReference);this.segments.set(p.id,c)}let i=this.switchingToRepresentationId??this.downloadingRepresentationId,r=this.representations.get(i);(0,w.assertNonNullable)(r);let a=this.segments.get(i);(0,w.assertNonNullable)(a,"No segments for starting representation");let n=this.initData.get(i);if((0,w.assertNonNullable)(n,"No init buffer for starting representation"),!(n instanceof ArrayBuffer))return;let o=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,yield this.abort(),o&&(yield this.sourceBufferTaskQueue.remove(o.from*1e3,o.to*1e3,this.destroyAbortController.signal)),this.searchGaps(a,r),yield this.sourceBufferTaskQueue.append(n,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this));this.fetcher=r,this.tuning=a,this.compatibilityMode=u,this.forwardBufferTarget=a.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=o,this.isLive=!!l?.live,this.baseUrls=l?.baseUrls??[],this.initData=new Map(i.map(p=>[p.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(i.map(p=>[p.id,p])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}switchToWithPreviousAbort(e,t=!1){!Y(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new de,(0,w.abortable)(this.switchAbortController.signal,async function*(i,r=!1){this.switchingToRepresentationId=i;let a=this.representations.get(i);(0,w.assertNonNullable)(a,`No such representation ${i}`);let n=this.segments.get(i),o=this.initData.get(i);if((0,w.isNullable)(o)||(0,w.isNullable)(n)?yield this.loadInit(a,"high",!1):o instanceof Promise&&(yield o),n=this.segments.get(i),(0,w.assertNonNullable)(n,"No segments for starting representation"),o=this.initData.get(i),!(!(o instanceof ArrayBuffer)||!this.sourceBuffer||!Y(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();(0,w.isNonNullable)(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(){!(0,w.isNullable)(this.sourceBuffer)&&!this.sourceBuffer.updating&&(this.sourceBuffer.mode="segments")}async abort(){for(let e of this.activeSegments)this.abortSegment(e.segment);return this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new de,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if((0,w.isNullable)(e)||(0,w.isNullable)(this.downloadingRepresentationId)||(0,w.isNullable)(this.playingRepresentationId)||(0,w.isNullable)(this.sourceBuffer)||!Y(this.mediaSource,this.sourceBuffer)||(0,w.isNonNullable)(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if((0,w.assertNonNullable)(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;let r=i.find(p=>e>=p.time.from&&e<p.time.to);(0,w.isNonNullable)(r)&&isFinite(r.time.from)&&isFinite(r.time.to)&&this.currentSegmentLength$.next(r?.time.to-r.time.from);let a=e,n=100;if(this.playingRepresentationId!==this.downloadingRepresentationId){let p=this.getForwardBufferDuration(e),c=r?r.time.to+n:-1/0;r&&r.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&p>=r.time.to-e+n&&(a=c)}if(isFinite(this.bufferLimit)&&Lr(this.sourceBuffer.buffered)>=this.bufferLimit){let p=this.getForwardBufferDuration(e),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,p<c).catch(d=>{this.handleAsyncError(d,"pruneBuffer")});return}let u=[];if(!this.activeSegments.size&&(u=this.selectForwardBufferSegments(i,t.segmentReference.type,a),u.length)){let p="auto";if(this.tuning.dash.useFetchPriorityHints&&r)if((0,Jn.default)(u,r))p="high";else{let c=(0,Cr.default)(u,0);c&&c.time.from-r.time.to>=this.forwardBufferTarget/2&&(p="low")}this.loadSegments(u,t,p).catch(c=>{this.handleAsyncError(c,"loadSegments")})}(!this.preloadOnly&&!this.allInitsLoaded&&r&&r.status==="fed"&&!u.length&&this.getForwardBufferDuration(e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let l=(0,Cr.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 a of e)Math.trunc(a.time.from-i)>0&&this.gaps.push({representation:t.id,from:i,to:a.time.from+r}),i=a.time.to;(0,w.isNonNullable)(t.duration)&&t.duration-i>0&&!this.isLive&&this.gaps.push({representation:t.id,from:i,to:t.duration})}getActualLiveStartingSegments(e){let t=e.segments,i=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,r=[],a=0,n=t.length-1;do r.unshift(t[n]),a+=t[n].time.to-t[n].time.from,n--;while(a<i&&n>=0);return this.liveInitialAdditionalOffset=a-i,this.isActiveLowLatency()?[r[0]]:r}getLiveSegmentsToLoadState(e){let t=(0,Zn.default)(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?.length)return{from:i[0].time.from,to:i[i.length-1].time.to}}updateLive(e){let t=(0,Zn.default)(e?.streams[this.kind],i=>i.representations)??[];if(![...this.segments.values()].every(i=>!i.length))for(let i of t){if(!i||!rt(i.segmentReference))return;let r=i.segmentReference.segments.map(l=>({...l,status:"none",size:void 0})),a=100,n=this.segments.get(i.id)??[],o=(0,Cr.default)(n,-1)?.time.to??0,u=r?.findIndex(l=>o>=l.time.from+a&&o<=l.time.to+a);if(u===-1){this.liveUpdateSegmentIndex=0;let l=this.getActualLiveStartingSegments(i.segmentReference);this.segments.set(i.id,l)}else{let l=r.slice(u+1);this.segments.set(i.id,[...n,...l])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;(0,w.assertNonNullable)(e);let t=this.segments.get(e);if(t?.length){let i=t[t.length-1];this.updateLowLatencyLiveIfNeeded(i)}}updateLowLatencyLiveIfNeeded(e){let t=0;for(let i of this.representations.values()){let r=i.segmentReference;if(!rt(r))return;let a=this.segments.get(i.id)??[],n=a.find(u=>Math.floor(u.time.from)===Math.floor(e.time.from));if(n&&!isFinite(n.time.to)&&(n.time.to=e.time.to,t=n.time.to-n.time.from),!!!a.find(u=>Math.floor(u.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let u=Math.round(e.time.to*r.timescale/1e3).toString(10),l=fi(r.segmentTemplateUrl,{segmentTime:u});a.push({status:"none",time:{from:e.time.to,to:1/0},url:l})}}this.currentLowLatencySegmentLength$.next(t)}findSegmentStartTime(e){let t=this.switchingToRepresentationId??this.downloadingRepresentationId??this.playingRepresentationId;if(!t)return;let i=this.segments.get(t);return i?i.find(a=>a.time.from<=e&&a.time.to>=e)?.time.from??void 0:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),this.sourceBufferTaskQueue?.destroy(),this.gapDetectionIdleCallback&&Xt&&Xt(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&Xt&&Xt(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer)try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(e){if(!(e instanceof DOMException&&e.name==="NotFoundError"))throw e}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:c,time:{from:d,to:h}},m)=>{let g=d<=i&&h>=i,v=d>i||g||m===0&&i===0,T=Math.min(this.forwardBufferTarget,this.bufferLimit),P=this.preloadOnly&&d<=i+T||h<=i+T;return(c==="none"||c==="partially_ejected"&&v&&P&&this.sourceBuffer&&Y(this.mediaSource,this.sourceBuffer)&&!(Ye(this.sourceBuffer.buffered,d)&&Ye(this.sourceBuffer.buffered,h)))&&v&&P});if(r===-1)return[];if(t!=="byteRange")return e.slice(r,r+1);let a=e,n=0,o=0,u=[],l=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,p=this.preloadOnly?this.forwardBufferTarget:0;for(let c=r;c<a.length&&(n<=l||o<=p);c++){let d=a[c];if(n+=d.byte.to+1-d.byte.from,o+=d.time.to+1-d.time.from,d.status==="none"||d.status==="partially_ejected")u.push(d);else break}return u}async loadSegments(e,t,i="auto"){rt(t.segmentReference)?await this.loadTemplateSegment(e[0],t,i):await this.loadByteRangeSegments(e,t,i)}async loadTemplateSegment(e,t,i="auto"){e.status="downloading";let r={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(r);let{range:a,url:n,signal:o,onProgress:u,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(await(0,w.abortable)(o,async function*(){let p=(0,w.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>setTimeout(c,p))}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let p=await this.fetcher.fetch(n,{range:a,signal:o,onProgress:u,priority:i,isLowLatency:this.isActiveLowLatency()});if(this.lastDataObtainedTimestampMs=(0,w.now)(),!p)return;let c=new DataView(p),d=Js(t.mime);if(!isFinite(r.segment.time.to)){let g=t.segmentReference.timescale;r.segment.time.to=d.getChunkEndTime(c,g)}u&&r.feedingBytes&&l?await Promise.all(l):await this.sourceBufferTaskQueue.append(c,o);let{serverDataReceivedTimestamp:h,serverDataPreparedTime:m}=d.getServerLatencyTimestamps(c);h&&m&&this.currentLiveSegmentServerLatency$.next(m-h),r.segment.status="downloaded",this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(p){this.abortActiveSegments([e]),Zs(p)||(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())rt(t.segmentReference)?t.segmentReference.baseUrl=e:t.segmentReference.url=e}async loadByteRangeSegments(e,t,i="auto"){if(!e.length)return;for(let u of e)u.status="downloading",this.activeSegments.add({segment:u,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:r,url:a,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(await(0,w.abortable)(n,async function*(){let u=(0,w.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),(0,w.fromEvent)(window,"online").pipe((0,w.once)()).subscribe(()=>{l(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(a,{range:r,onProgress:o,signal:n,priority:i}),this.lastDataObtainedTimestampMs=(0,w.now)(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),Zs(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}prepareByteRangeFetchSegmentParams(e,t){if(rt(t.segmentReference))throw new Error("Representation is not byte range type");let i=t.segmentReference.url,r={from:(0,Cr.default)(e,0).byte.from,to:(0,Cr.default)(e,-1).byte.to},{signal:a}=this.downloadAbortController;return{url:i,range:r,signal:a,onProgress:async(o,u)=>{if(!a.aborted)try{this.lastDataObtainedTimestampMs=(0,w.now)(),await this.onSomeByteRangesDataLoaded({dataView:o,loaded:u,signal:a,onSegmentAppendFailed:()=>this.abort(),globalFrom:r?r.from:0,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:w.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!rt(t.segmentReference))throw new Error("Representation is not template type");let i=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&i.searchParams.set("low-latency","yes");let r=i.toString(),{signal:a}=this.downloadAbortController,n=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(l,p)=>{if(!a.aborted)try{this.lastDataObtainedTimestampMs=(0,w.now)();let c=this.onSomeTemplateDataLoaded({dataView:l,loaded:p,signal:a,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(c)}catch(c){this.error$.next({id:"SegmentFeeding",category:w.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:c})}}:void 0;return{url:r,signal:a,onProgress:u,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)(0,Jn.default)(e,t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:r,signal:a}){if(!this.activeSegments.size||!Y(this.mediaSource,this.sourceBuffer))return;let n=this.representations.get(t);if(n)for(let o of this.activeSegments){let{segment:u}=o;if(o.representationId===t){if(a.aborted){r();continue}if(o.loadedBytes=i,o.loadedBytes>o.feedingBytes){let l=new DataView(e.buffer,e.byteOffset+o.feedingBytes,o.loadedBytes-o.feedingBytes),p=Js(n.mime).parseFeedableSegmentChunk(l,this.isLive);p?.byteLength&&(u.status="partially_fed",o.feedingBytes+=p.byteLength,await this.sourceBufferTaskQueue.append(p),o.fedBytes+=p.byteLength)}}}}async onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:a,onSegmentAppendFailed:n}){if(!this.activeSegments.size||!Y(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)continue;if(a.aborted){await n();continue}let p=l.byte.from-i,c=l.byte.to-i,d=c-p+1,h=p<r,m=c<=r;if(!h)continue;let g=Js(o.mime);if(l.status==="downloading"&&m){l.status="downloaded";let v=new DataView(e.buffer,e.byteOffset+p,d);await this.sourceBufferTaskQueue.append(v,a)&&!a.aborted?this.onSegmentFullyAppended(u,t):await n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(l.status==="downloading"||l.status==="partially_fed")&&(u.loadedBytes=Math.min(d,r-p),u.loadedBytes>u.feedingBytes)){let v=new DataView(e.buffer,e.byteOffset+p+u.feedingBytes,u.loadedBytes-u.feedingBytes),T=u.loadedBytes===d?v:g.parseFeedableSegmentChunk(v);T?.byteLength&&(l.status="partially_fed",u.feedingBytes+=T.byteLength,await this.sourceBufferTaskQueue.append(T,a)&&!a.aborted?(u.fedBytes+=T.byteLength,u.fedBytes===d&&this.onSegmentFullyAppended(u,t)):await n())}}}onSegmentFullyAppended(e,t){if(!((0,w.isNullable)(this.sourceBuffer)||!Y(this.mediaSource,this.sourceBuffer))){!this.isLive&&W.browser.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(Ye(this.sourceBuffer.buffered,e.segment.time.from,100)&&Ye(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:w.ErrorCategory.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",cc(e.segment)&&(e.segment.size=e.fedBytes);for(let i of this.representations.values())if(i.id!==t)for(let r of this.segments.get(i.id)??[])r.status==="fed"&&Math.round(r.time.from)===Math.round(e.segment.time.from)&&Math.round(r.time.to)===Math.round(e.segment.time.to)&&(r.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,a]of this.initData.entries()){let n=a instanceof Promise;t||=n,a===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let i=this.representations.get(e);i&&(this.initLoadIdleCallback=Mr(()=>(0,hv.default)(this.loadInit(i,"low",!1),()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",i=!1){let r=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!i&&this.failedDownloads>0?(0,w.abortable)(this.destroyAbortController.signal,async function*(){let o=(0,w.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,Js(e.mime),r)).then(async o=>{if(!o)return;let{init:u,dataView:l,segments:p}=o,c=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,c);let d=p;this.isLive&&rt(e.segmentReference)&&(d=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,d),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:w.ErrorCategory.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n}async dropBuffer(){for(let e of this.segments.values())for(let t of e)t.status="none";await this.pruneBuffer(0,1/0,!0)}async pruneBuffer(e,t,i=!1){if(!this.sourceBuffer||!Y(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||(0,w.isNullable)(e))return!1;let r=[],a=0,n=u=>{u.sort((p,c)=>p.from-c.from);let l=[u[0]];for(let p=1;p<u.length;p++){let{from:c,to:d}=u[p],h=l[l.length-1];h.to>=c?h.to=Math.max(h.to,d):l.push(u[p])}return l},o=u=>{if(a>=t)return r;r.push({...u.time}),r=n(r);let l=cc(u)?u.size??0:u.byte.to-u.byte.from;a+=l};for(let u of this.segments.values())for(let l of u){let p=l.time.to<=e-this.tuning.dash.bufferPruningSafeZone,c=l.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(p||c)&&l.status==="fed"&&o(l)}for(let u=0;u<this.sourceBuffer.buffered.length;u++){let l=this.sourceBuffer.buffered.start(u)*1e3,p=this.sourceBuffer.buffered.end(u)*1e3,c=0;for(let d of this.segments.values())for(let h of d)(0,Jn.default)(["none","partially_ejected"],h.status)&&Math.round(h.time.from)<=Math.round(l)&&Math.round(h.time.to)>=Math.round(p)&&c++;if(c===this.segments.size){let d={time:{from:l,to:p},url:"",status:"none"};o(d)}}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 p of l)p.time.from>=e+u&&p.status==="fed"&&o(p)}return r.length?(await Promise.all(r.map(l=>this.sourceBufferTaskQueue.remove(l.from,l.to)))).reduce((l,p)=>l||p,!1):!1}async abortBuffer(){if(!this.sourceBuffer||!Y(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||!Y(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||!Y(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||(0,w.isNullable)(e)?0:ze(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!(!this.sourceBuffer||!Y(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 a=0;a<this.sourceBuffer.buffered.length;a++){let n=this.sourceBuffer.buffered.start(a)*1e3,o=this.sourceBuffer.buffered.end(a)*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(a=>r&&a.from===r.from&&a.to===r.to)&&this.gaps.push(r)}}}detectGapsWhenIdle(e,t){if(!(this.gapDetectionIdleCallback||!this.sourceBuffer||!Y(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=Mr(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:w.ErrorCategory.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if((0,w.isNullable)(this.sourceBuffer)||!Y(this.mediaSource,this.sourceBuffer)||(0,w.isNullable)(this.playingRepresentationId))return;let e=[];for(let i=0;i<this.sourceBuffer.buffered.length;i++){let r=Math.floor(this.sourceBuffer.buffered.start(i)*1e3),a=Math.ceil(this.sourceBuffer.buffered.end(i)*1e3);e.push({from:r,to:a})}let t=100;for(let i of this.segments.values())for(let r of i){let{status:a}=r;if(a!=="fed"&&a!=="partially_ejected")continue;let n=Math.floor(r.time.from),o=Math.ceil(r.time.to),u=e.some(p=>p.from-t<=n&&p.to+t>=o),l=e.filter(p=>n>=p.from&&n<p.to-t||o>p.from+t&&o<=p.to);u||(l.length===1?r.status="partially_ejected":this.gaps.some(p=>p.from===r.time.from||p.to===r.time.to)?r.status="partially_ejected":r.status="none")}}handleAsyncError(e,t){this.error$.next({id:t,category:w.ErrorCategory.VIDEO_PIPELINE,thrown:e,message:"Something went wrong"})}};var Li=s=>{let e=new URL(s);return e.searchParams.set("quic","1"),e.toString()};var eo=s=>{let e=s.get("X-Delivery-Type"),t=s.get("X-Reused"),i=e===null?"http1":e??void 0,r=t===null?void 0:{1:!0,0:!1}[t]??void 0;return{type:i,reused:r}};var X=require("@vkontakte/videoplayer-shared");var to=s=>{let e=new URL(s);return e.searchParams.set("enable-subtitles","yes"),e.toString()};var ro=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:a=!1}){this.lastConnectionType$=new X.ValueSubject(void 0);this.lastConnectionReused$=new X.ValueSubject(void 0);this.lastRequestFirstBytes$=new X.ValueSubject(void 0);this.recoverableError$=new X.Subject;this.error$=new X.Subject;this.abortAllController=new de;this.subscription=new X.Subscription;this.fetchManifest=(0,X.abortable)(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=Li(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=to(i));let r=yield this.doFetch(i,{signal:this.abortAllController.signal}).catch(io);return r?(t.log("success",(0,X.flattenObject)({url:i,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(r.headers),r.text()):(t.error("error",(0,X.flattenObject)({url:i,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=(0,X.abortable)(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:i,onProgress:r,priority:a="auto",signal:n,measureThroughput:o=!0,isLowLatency:u=!1}={}){let l=e,p=new Headers,c=this.tracer.createComponentTracer("Fetch");if(i)switch(t){case 0:{p.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let U=new URL(l,location.href);U.searchParams.append("bytes",`${i.from}-${i.to}`),l=U.toString();break}default:(0,X.assertNever)(t)}this.requestQuic&&(l=Li(l));let d=this.abortAllController.signal,h;if(n){let U=new de;if(h=(0,X.merge)((0,X.fromEvent)(this.abortAllController.signal,"abort"),(0,X.fromEvent)(n,"abort")).subscribe(()=>{try{U.abort()}catch(k){io(k)}}),this.subscription.add(h),this.abortAllController.signal.aborted||n.aborted)try{U.abort()}catch(k){io(k)}d=U.signal}let m=(0,X.now)();c.log("startRequest",(0,X.flattenObject)({url:l,priority:a,rangeMethod:t,range:i,isLowLatency:u,requestStartedAt:m}));let g=yield this.doFetch(l,{priority:a,headers:p,signal:d}),v=(0,X.now)();if(!g)return c.error("error",{message:"No response in request"}),c.end(),h?.unsubscribe(),null;if(this.throughputEstimator?.addRawRtt(v-m),!g.ok||!g.body){h?.unsubscribe();let U=`Fetch error ${g.status}: ${g.statusText}`;return c.error("error",{message:U}),c.end(),Promise.reject(new Error(`Fetch error ${g.status}: ${g.statusText}`))}if(this.onHeadersReceived(g.headers),!r&&!o){h?.unsubscribe();let U=(0,X.now)(),k={requestStartedAt:m,requestEndedAt:U,duration:U-m};return c.log("endRequest",(0,X.flattenObject)(k)),c.end(),g.arrayBuffer()}let[T,P]=g.body.tee(),x=T.getReader();o&&this.throughputEstimator?.trackStream(P,u);let L=0,B=new Uint8Array(0),F=!1,G=U=>{h?.unsubscribe(),F=!0,io(U)},$=(0,X.abortable)(d,async function*({done:U,value:k}){if(L===0&&this.lastRequestFirstBytes$.next((0,X.now)()-m),d.aborted){h?.unsubscribe();return}if(!U&&k){let R=new Uint8Array(B.length+k.length);R.set(B),R.set(k,B.length),B=R,L+=k.byteLength,r?.(new DataView(B.buffer),L),yield x?.read().then($,G)}}.bind(this));yield x?.read().then($,G),h?.unsubscribe();let D=(0,X.now)(),I={failed:F,requestStartedAt:m,requestEndedAt:D,duration:D-m};return F?(c.error("endRequest",(0,X.flattenObject)(I)),c.end(),null):(c.log("endRequest",(0,X.flattenObject)(I)),c.end(),B.buffer)}.bind(this));this.fetchByteRangeRepresentation=(0,X.abortable)(this.abortAllController.signal,async function*(e,t,i){if(e.type!=="byteRange")return null;let{from:r,to:a}=e.initRange,n=r,o=a,u=!1,l,p;e.indexRange&&(l=e.indexRange.from,p=e.indexRange.to,u=a+1===l,u&&(n=Math.min(l,r),o=Math.max(p,a))),n=Math.min(n,0);let c=yield this.fetch(e.url,{range:{from:n,to:o},priority:i,measureThroughput:!1});if(!c)return null;let d=new DataView(c,r-n,a-n+1);if(!t.validateData(d))throw new Error("Invalid media file");let h=t.parseInit(d),m=e.indexRange??t.getIndexRange(h);if(!m)throw new ReferenceError("No way to load representation index");let g;if(u)g=new DataView(c,m.from-n,m.to-m.from+1);else{let T=yield this.fetch(e.url,{range:m,priority:i,measureThroughput:!1});if(!T)return null;g=new DataView(T)}let v=t.parseSegments(g,h,m);return{init:h,dataView:new DataView(c),segments:v}}.bind(this));this.fetchTemplateRepresentation=(0,X.abortable)(this.abortAllController.signal,async function*(e,t){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=>({...n,status:"none",size:void 0})),dataView:new DataView(r)}:null}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=r,this.tracer=i.createComponentTracer("Fetcher"),this.useEnableSubtitlesParam=a}onHeadersReceived(e){let{type:t,reused:i}=eo(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}async fetchRepresentation(e,t,i="auto"){let{type:r}=e;switch(r){case"byteRange":return await this.fetchByteRangeRepresentation(e,t,i)??null;case"template":return await this.fetchTemplateRepresentation(e,i)??null;default:(0,X.assertNever)(r)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}async doFetch(e,t){let i=await Lt(e,t);if(i.ok)return i;let r=await i.text(),a=parseInt(r);if(!isNaN(a))switch(a){case 1:this.recoverableError$.next({id:"VideoDataLinkExpiredError",message:"Video data links have expired",category:X.ErrorCategory.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:X.ErrorCategory.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:X.ErrorCategory.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:X.ErrorCategory.FATAL});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${a})`,category:X.ErrorCategory.FATAL})}}},io=s=>{if(!Zs(s))throw s};var mi=(s,e,t)=>t*e+(1-t)*s,mc=(s,e)=>s.reduce((t,i)=>t+i,0)/e,fv=(s,e,t,i)=>{let r=0,a=t,n=mc(s,e),o=e<i?e:i;for(let u=0;u<o;u++)s[a]>n?r++:r--,a=(s.length+a-1)%s.length;return Math.abs(r)===o};var ia=require("@vkontakte/videoplayer-shared"),Bi=class{constructor(e){this.prevReported=void 0;this.pastMeasures=[];this.takenMeasures=0;this.measuresCursor=0;this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new ia.ValueSubject(e.initial),this.debounced$=new ia.ValueSubject(e.initial);let t=e.label??"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new tt(`raw_${t}`),this.smoothedSeries$=new tt(`smoothed_${t}`),this.reportedSeries$=new tt(`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+=(this.pastMeasures[o]-this.smoothed)**2,i++);this.takenMeasures=i,t/=i;let r=Math.sqrt(t),a=this.smoothed+this.params.deviationFactor*r,n=this.smoothed-this.params.deviationFactor*r;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(e),this.updateSmoothedValue(e),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),!(this.smoothed>a||this.smoothed<n)&&((0,ia.isNullable)(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 so=class extends Bi{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=mi(this.slow,e,this.params.emaAlphaSlow),this.fast=mi(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var ao=class extends Bi{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=mc(this.pastMeasures,this.takenMeasures);this.emaSmoothed=mi(this.emaSmoothed,e,this.params.emaAlpha);let i=fv(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=i?this.emaSmoothed:t}};var no=class extends Bi{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?mi(this.smoothed,t,this.params.emaAlpha):t}};var bi=class{static getSmoothedValue(e,t,i){return i.type==="TwoEma"?new so({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new ao({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 no({initial:e,label:"liveEdgeDelay",...t})}};var Vr=(s,e)=>{s&&s.playbackRate!==e&&(s.playbackRate=e)};var oo=require("@vkontakte/videoplayer-shared");var ra=class s{constructor(e,t){this.currentRepresentation$=new oo.ValueSubject(null);this.maxRepresentations=4;this.representationsCursor=0;this.representations=[];this.currentSegment=null;this.getCurrentPosition=t.getCurrentPosition,this.processStreams(e)}updateLive(e){this.processStreams(e?.streams.text)}seekLive(e){this.processStreams(e)}maintain(e=this.getCurrentPosition()){if(!(0,oo.isNullable)(e))for(let t of this.representations)for(let i of t){let r=i.segmentReference,a=r.segments.length,n=r.segments[0].time.from,o=r.segments[a-1].time.to;if(e<n||e>o)continue;let u=r.segments.find(l=>l.time.from<=e&&l.time.to>=e);!u||this.currentSegment?.time.from===u.time.from&&this.currentSegment.time.to===u.time.to||(this.currentSegment=u,this.currentRepresentation$.next({...i,label:"Live Text",language:"ru",isAuto:!0,url:new URL(u.url,r.baseUrl).toString()}))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e??[]){let i=s.filterRepresentations(t.representations);if(i){this.representations[this.representationsCursor]=i,this.representationsCursor=(this.representationsCursor+1)%this.maxRepresentations;break}}}static isSupported(e){return!!e?.some(t=>s.filterRepresentations(t.representations))}static filterRepresentations(e){return e?.filter(t=>t.kind==="text"&&"segmentReference"in t&&rt(t.segmentReference))}};var lo=j(Ut(),1);var sa=require("@vkontakte/videoplayer-shared");var mv=(s,{useManagedMediaSource:e,useOldMSEDetection:t})=>{let{containers:i,protocols:r,codecs:a,nativeHlsSupported:n}=W.video,o=(a.h264||a.h265)&&a.aac,u=r.mse&&(!t||!!window.MediaStreamTrack)||r.mms&&e;return s.filter(l=>{switch(l){case"DASH_SEP":return u&&i.mp4&&o;case"DASH_WEBM":return u&&i.webm&&a.vp9&&a.opus;case"DASH_WEBM_AV1":return u&&i.webm&&a.av1&&a.opus;case"DASH_STREAMS":return u&&(i.mp4&&o||i.webm&&(a.vp9||a.av1)&&(a.opus||a.aac));case"DASH_LIVE":return u&&i.mp4&&o;case"DASH_LIVE_CMAF":return u&&i.mp4&&o&&i.cmaf;case"DASH_ONDEMAND":return u&&i.mp4&&o;case"HLS":case"HLS_ONDEMAND":case"HLS_LIVE":case"HLS_LIVE_CMAF":return n;case"MPEG":return i.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return r.webrtc&&r.ws&&a.h264&&(i.mp4||i.webm);default:return(0,sa.assertNever)(l)}})},uo=s=>{let{webmDecodingInfo:e}=W.video,t="DASH_WEBM",i="DASH_WEBM_AV1";switch(s){case"vp9":return[t,i];case"av1":return[i,t];case"none":return[];case"smooth":return e?e[i].smooth?[i,t]:e[t].smooth?[t,i]:[i,t]:[t,i];case"power_efficient":return e?e[i].powerEfficient?[i,t]:e[t].powerEfficient?[t,i]:[i,t]:[t,i];default:(0,sa.assertNever)(s)}return[t,i]},bv=({webmCodec:s,androidPreferredFormat:e,preferMultiStream:t})=>{let i=[...t?["DASH_STREAMS"]:[],...uo(s),"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]],r=[...t?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]];if(W.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",...uo(s),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...uo(s),"MPEG",...r,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...uo(s),...r,"HLS","HLS_ONDEMAND"];default:(0,sa.assertNever)(e)}return W.video.nativeHlsSupported?[...i,"HLS","HLS_ONDEMAND","MPEG"]:[...i,"HLS","HLS_ONDEMAND","MPEG"]},gv=({androidPreferredFormat:s,preferCMAF:e,preferWebRTC:t})=>{let i=e?["DASH_LIVE_CMAF","DASH_LIVE"]:["DASH_LIVE","DASH_LIVE_CMAF"],r=e?["HLS_LIVE_CMAF","HLS_LIVE"]:["HLS_LIVE","HLS_LIVE_CMAF"],a=[...i,...r],n=[...r,...i],o,u=W.device.isMac&&W.browser.isSafari;if(W.device.isAndroid)switch(s){case"dash":case"dash_any_mpeg":case"dash_any_webm":case"dash_sep":{o=a;break}case"hls":case"mpeg":{o=n;break}default:(0,sa.assertNever)(s)}else W.video.nativeHlsSupported&&!u?o=n:u?o=e?["DASH_LIVE_CMAF","HLS_LIVE_CMAF","HLS_LIVE","DASH_LIVE"]:["HLS_LIVE","DASH_LIVE","DASH_LIVE_CMAF","HLS_LIVE_CMAF"]:o=a;return t?["WEB_RTC_LIVE",...o]:[...o,"WEB_RTC_LIVE"]},bc=s=>s?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],co=s=>{if(s.size===0)return;if(s.size===1){let t=s.values().next();return(0,lo.default)(t.value.split("."),0)}for(let t of s){let i=(0,lo.default)(t.split("."),0);if(i==="opus"||i==="vp09"||i==="av01")return i}let e=s.values().next();return(0,lo.default)(e.value.split("."),0)};var VM=["timeupdate","progress","play","seeked","stalled","waiting"],OM=["timeupdate","progress","loadeddata","playing","seeked"];var po=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new y.Subscription;this.representationSubscription=new y.Subscription;this.state$=new ie("none");this.currentVideoRepresentation$=new y.ValueSubject(void 0);this.currentVideoRepresentationInit$=new y.ValueSubject(void 0);this.currentAudioRepresentation$=new y.ValueSubject(void 0);this.currentVideoSegmentLength$=new y.ValueSubject(0);this.currentAudioSegmentLength$=new y.ValueSubject(0);this.error$=new y.Subject;this.lastConnectionType$=new y.ValueSubject(void 0);this.lastConnectionReused$=new y.ValueSubject(void 0);this.lastRequestFirstBytes$=new y.ValueSubject(void 0);this.currentLiveTextRepresentation$=new y.ValueSubject(null);this.isLive$=new y.ValueSubject(!1);this.isActiveLive$=new y.ValueSubject(!1);this.isLowLatency$=new y.ValueSubject(!1);this.liveDuration$=new y.ValueSubject(0);this.liveSeekableDuration$=new y.ValueSubject(0);this.liveAvailabilityStartTime$=new y.ValueSubject(0);this.liveStreamStatus$=new y.ValueSubject(void 0);this.bufferLength$=new y.ValueSubject(0);this.liveLatency$=new y.ValueSubject(void 0);this.liveLoadBufferLength$=new y.ValueSubject(0);this.livePositionFromPlayer$=new y.ValueSubject(0);this.currentStallDuration$=new y.ValueSubject(0);this.videoLastDataObtainedTimestamp$=new y.ValueSubject(0);this.fetcherRecoverableError$=new y.Subject;this.fetcherError$=new y.Subject;this.liveStreamEndTimestamp=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.forceEnded$=new y.Subject;this.gapWatchdogActive=!1;this.destroyController=new de;this.initManifest=(0,y.abortable)(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=Le(t,i,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),this.manifest?.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:y.ErrorCategory.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=(0,y.abortable)(this.destroyController.signal,async function*(){this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(n=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:y.ErrorCategory.NETWORK,message:"Failed to load manifest",thrown:n})});if(!e)return null;let t=null;try{t=pv(e??"",this.manifestUrlString)}catch(n){let o=Kn(e)??{id:"ManifestParsing",category:y.ErrorCategory.PARSER,message:"Failed to parse MPD manifest",thrown:n};this.error$.next(o)}if(!t)return null;let i=(n,o,u)=>!!(this.element?.canPlayType?.(o)&&wt()?.isTypeSupported?.(`${o}; codecs="${u}"`)||n==="text");if(t.live){this.isLive$.next(!!t.live);let{availabilityStartTime:n,latestSegmentPublishTime:o,streamIsUnpublished:u,streamIsAlive:l}=t.live,p=(t.duration??0)/1e3;this.liveSeekableDuration$.next(-1*p),this.liveDuration$.next((o-n)/1e3),this.liveAvailabilityStartTime$.next(t.live.availabilityStartTime);let c="active";l||(c=u?"unpublished":"unexpectedly_down"),this.liveStreamStatus$.next(c)}let r={text:t.streams.text,video:[],audio:[]};for(let n of["video","audio"]){let u=t.streams[n].filter(({mime:c,codecs:d})=>i(n,c,d)),l=new Set(u.map(({codecs:c})=>c)),p=co(l);if(p&&(r[n]=u.filter(({codecs:c})=>c.startsWith(p))),n==="video"){let c=this.tuning.preferHDR,d=r.video.some(m=>m.hdr),h=r.video.some(m=>!m.hdr);W.display.isHDR&&c&&d?r.video=r.video.filter(m=>m.hdr):h&&(r.video=r.video.filter(m=>!m.hdr))}}let a={...t,streams:r};return this.tracer.log("updateManifestEnd",(0,y.flattenObject)(a)),a}.bind(this));this.initRepresentations=(0,y.abortable)(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initRepresentationsStart",(0,y.flattenObject)({initialVideo:e,initialAudio:t,sourceHls:i})),(0,y.assertNonNullable)(this.manifest),(0,y.assertNonNullable)(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let r=d=>{this.representationSubscription.add((0,y.fromEvent)(d,"error").pipe((0,y.filter)(h=>!!this.element?.played.length)).subscribe(h=>{this.error$.next({id:"VideoSource",category:y.ErrorCategory.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:h})}))};this.source=this.tuning.useManagedMediaSource?Cn():new MediaSource;let a=document.createElement("source");if(r(a),a.src=URL.createObjectURL(this.source),this.element.appendChild(a),this.tuning.useManagedMediaSource&&xr())if(i){let d=document.createElement("source");r(d),d.type="application/x-mpegurl",d.src=i.url,this.element.appendChild(d)}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((d,h)=>[...d,...h.representations],[]);if(this.videoBufferManager=new ta("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],(0,y.isNonNullable)(t)){let d=this.manifest.streams.audio.reduce((h,m)=>[...h,...m.representations],[]);this.audioBufferManager=new ta("audio",this.source,d,n),this.bufferManagers.push(this.audioBufferManager)}ra.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new ra(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=()=>{this.stallWatchdogSubscription?.unsubscribe(),this.currentStallDuration$.next(0)};if(this.representationSubscription.add((0,y.merge)(...OM.map(d=>(0,y.fromEvent)(this.element,d))).pipe((0,y.map)(d=>this.element?ze(this.element.buffered,this.element.currentTime*1e3):0),(0,y.filterChanged)(),(0,y.tap)(d=>{d>this.tuning.dash.bufferEmptinessTolerance&&u()})).subscribe(this.bufferLength$)),this.representationSubscription.add((0,y.merge)((0,y.fromEvent)(this.element,"ended"),this.forceEnded$).subscribe(()=>{u()})),this.isLive$.getValue()){this.subscription.add(this.liveDuration$.pipe((0,y.filterChanged)()).subscribe(h=>this.liveStreamEndTimestamp=(0,y.now)())),this.subscription.add((0,y.fromEvent)(this.element,"pause").subscribe(()=>{this.livePauseWatchdogSubscription=(0,y.interval)(1e3).subscribe(h=>{let m=wi(this.manifestUrlString,2);this.manifestUrlString=Le(this.manifestUrlString,m+1e3,2),this.liveStreamStatus$.getValue()==="active"&&this.updateManifest()}),this.subscription.add(this.livePauseWatchdogSubscription)})).add((0,y.fromEvent)(this.element,"play").subscribe(h=>this.livePauseWatchdogSubscription?.unsubscribe())),this.representationSubscription.add((0,y.combine)({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe((0,y.map)(({isActiveLive:h,isLowLatency:m})=>h&&m),(0,y.filterChanged)()).subscribe(h=>{this.isManualDecreasePlaybackInLive()||Vr(this.element,1)})),this.representationSubscription.add((0,y.combine)({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe((0,y.filter)(({bufferLength:h,isActiveLive:m,isLowLatency:g})=>m&&g&&!!h)).subscribe(({bufferLength:h})=>this.liveBuffer.next(h))),this.representationSubscription.add(this.videoBufferManager.currentLowLatencySegmentLength$.subscribe(h=>{if(!this.isActiveLive$.getValue()&&!this.isLowLatency$.getValue()&&!h)return;let m=this.liveSeekableDuration$.getValue()-h/1e3;this.liveSeekableDuration$.next(Math.max(m,-1*this.tuning.dashCmafLive.maxLiveDuration)),this.liveDuration$.next(this.liveDuration$.getValue()+h/1e3)})),this.representationSubscription.add((0,y.combine)({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe((0,y.filter)(({isLive:h})=>h),(0,y.filterChanged)((h,m)=>m.bufferLength<h.bufferLength),(0,y.map)(({rtt:h,bufferLength:m,segmentServerLatency:g})=>{let v=wi(this.manifestUrlString,2);return(h/2+m+g+v)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add((0,y.combine)({liveBuffer:this.liveBuffer.smoothed$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).subscribe(({liveBuffer:h,isActiveLive:m,isLowLatency:g})=>{if(!g||!m)return;let v=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,T=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,P=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,x=h-v;if(this.isManualDecreasePlaybackInLive())return;let L=1;Math.abs(x)>T&&(L=1+Math.sign(x)*P),Vr(this.element,L)})),this.representationSubscription.add(this.bufferLength$.subscribe(h=>{let m=0;if(h){let g=(this.element?.currentTime??0)*1e3;m=Math.min(...this.bufferManagers.map(T=>T.getLiveSegmentsToLoadState(this.manifest)?.to??g))-g}this.liveLoadBufferLength$.getValue()!==m&&this.liveLoadBufferLength$.next(m)}));let d=0;this.representationSubscription.add((0,y.combine)({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe((0,y.throttle)(1e3)).subscribe(async({liveLoadBufferLength:h,bufferLength:m})=>{if(!this.element||this.isUpdatingLive)return;let g=this.element.playbackRate,v=wi(this.manifestUrlString,2),T=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,P=Math.min(T,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*g),x=this.tuning.dashCmafLive.normalizedActualBufferOffset*g,L=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*g,B=isFinite(h)?h:m,F=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),G=T<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next(G);let $="none";if(F?$="active_low_latency":this.isLowLatency$.getValue()&&G?(this.bufferManagers.forEach(D=>D.proceedLowLatencyLive()),$="active_low_latency"):v!==0&&B<P?$="live_forward_buffering":B<P+L&&($="live_with_target_offset"),isFinite(h)&&(d=h>d?h:d),$==="live_forward_buffering"||$==="live_with_target_offset"){let D=d-(P+x),I=this.normolizeLiveOffset(Math.trunc(v+D/g)),U=Math.abs(I-v),k=0;!h||U<=this.tuning.dashCmafLive.offsetCalculationError?k=v:I>0&&U>this.tuning.dashCmafLive.offsetCalculationError&&(k=I),this.manifestUrlString=Le(this.manifestUrlString,k,2)}($==="live_with_target_offset"||$==="live_forward_buffering")&&(d=0,await this.updateLive())},h=>{this.error$.next({id:"updateLive",category:y.ErrorCategory.VIDEO_PIPELINE,thrown:h,message:"Failed to update live with subscription"})}))}let l=(0,y.merge)(...this.bufferManagers.map(d=>d.fullyBuffered$)).pipe((0,y.map)(()=>this.bufferManagers.every(d=>d.fullyBuffered$.getValue()))),p=(0,y.merge)(...this.bufferManagers.map(d=>d.onLastSegment$)).pipe((0,y.map)(()=>this.bufferManagers.some(d=>d.onLastSegment$.getValue()))),c=(0,y.combine)({allBuffersFull:l,someBufferEnded:p}).pipe((0,y.filterChanged)(),(0,y.map)(({allBuffersFull:d,someBufferEnded:h})=>d&&h),(0,y.filter)(d=>d));if(this.representationSubscription.add((0,y.merge)(this.forceEnded$,c).subscribe(()=>{if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(d=>!d.updating))try{this.source?.endOfStream()}catch(d){this.error$.next({id:"EndOfStream",category:y.ErrorCategory.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:d})}})),this.representationSubscription.add((0,y.merge)(...this.bufferManagers.map(d=>d.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 d=this.tuning.dash.sourceOpenTimeout>=0;yield new Promise(h=>{d&&(this.timeoutSourceOpenId=setTimeout(()=>{if(this.source?.readyState==="open"){h();return}this.error$.next({id:"OpenOfStream",category:y.ErrorCategory.VIDEO_PIPELINE,message:"Failed to open MediaSource",thrown:new Error("Timeout reject when wait sourceopen event"),traceAsLog:!0})},this.tuning.dash.sourceOpenTimeout)),this.source?.addEventListener("sourceopen",()=>{this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),h()},{once:!0})})}if(!this.isLive$.getValue()){let d=[this.manifest.duration??0,...(0,Sc.default)((0,Sc.default)([...this.manifest.streams.audio,...this.manifest.streams.video],h=>h.representations),h=>{let m=[];return h.duration&&m.push(h.duration),rt(h.segmentReference)&&h.segmentReference.totalSegmentsDurationMs&&m.push(h.segmentReference.totalSegmentsDurationMs),m})];this.source.duration=Math.max(...d)/1e3}this.audioBufferManager&&(0,y.isNonNullable)(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=()=>{if(!this.element||!this.videoBufferManager||this.source?.readyState!=="open")return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),this.audioBufferManager?.maintain(e),this.liveTextManager?.maintain(e),(this.videoBufferManager.gaps.length||this.audioBufferManager?.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=(0,y.interval)(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),t=>{this.error$.next({id:"GapWatchdog",category:y.ErrorCategory.WTF,message:"Error handling gaps",thrown:t})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name),this.fetcher=new ro({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=bi.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.bufferEstimator}),this.initTracerSubscription()}async seekLive(e){(0,y.assertNonNullable)(this.element);let t=this.liveStreamStatus$.getValue()!=="active"?(0,y.now)()-this.liveStreamEndTimestamp:0,i=this.normolizeLiveOffset(e+t);this.isActiveLive$.next(i===0),this.manifestUrlString=Le(this.manifestUrlString,i,2),this.manifest=await this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,await this.videoBufferManager?.seekLive(this.manifest.streams.video),await this.audioBufferManager?.seekLive(this.manifest.streams.audio),this.liveTextManager?.seekLive(this.manifest.streams.text))}initBuffer(){(0,y.assertNonNullable)(this.element),this.state$.setState("running"),this.subscription.add((0,y.merge)(...VM.map(e=>(0,y.fromEvent)(this.element,e)),(0,y.fromEvent)(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:y.ErrorCategory.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add((0,y.fromEvent)(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add((0,y.fromEvent)(this.element,"waiting").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&Ye(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{if(!this.element||this.source?.readyState!=="open")return;let t=this.currentStallDuration$.getValue();t+=50,this.currentStallDuration$.next(t);let i={timeInWaiting:t},r=(0,y.now)(),a=100,n=this.videoBufferManager?.lastDataObtainedTimestamp??0;this.videoLastDataObtainedTimestamp$.next(n);let o=this.audioBufferManager?.lastDataObtainedTimestamp??0,u=this.videoBufferManager?.getForwardBufferDuration()??0,l=this.audioBufferManager?.getForwardBufferDuration()??0,p=u<a&&r-n>this.tuning.dash.crashOnStallTWithoutDataTimeout,c=this.audioBufferManager&&l<a&&r-o>this.tuning.dash.crashOnStallTWithoutDataTimeout;if((p||c)&&t>this.tuning.dash.crashOnStallTWithoutDataTimeout||t>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${t} ms`);if(this.isLive$.getValue()&&t%2e3===0){let d=this.normolizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);this.seekLive(d).catch(h=>{this.error$.next({id:"stallIntervalCallback",category:y.ErrorCategory.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:h})}),i.liveLastOffset=d}else{let d=this.element.currentTime*1e3;this.videoBufferManager?.maintain(d),this.audioBufferManager?.maintain(d),i.position=d}this.tracer.log("stallIntervalCallback",(0,y.flattenObject)(i))};this.stallWatchdogSubscription?.unsubscribe(),this.stallWatchdogSubscription=(0,y.interval)(50).subscribe(e,t=>{this.error$.next({id:"StallWatchdogCallback",category:y.ErrorCategory.NETWORK,message:"Can't restore DASH after stall.",thrown:t})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t,i=!1){let r={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return this.tuning.useNewSwitchTo?this.currentStallDuration$.getValue()>0?r?.switchToWithPreviousAbort(t,i):r?.switchTo(t,i):r?.switchToOld(t,i)}async seek(e,t){(0,y.assertNonNullable)(this.element),(0,y.assertNonNullable)(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(this.videoBufferManager.findSegmentStartTime(e)??e,this.audioBufferManager?.findSegmentStartTime(e)??e),this.warmUpMediaSourceIfNeeded(i),Ye(this.element.buffered,i)||await Promise.all([this.videoBufferManager.abort(),this.audioBufferManager?.abort()]),!((0,y.isNullable)(this.element)||(0,y.isNullable)(this.videoBufferManager))&&(this.videoBufferManager.maintain(i),this.audioBufferManager?.maintain(i),this.element.currentTime=i/1e3,this.tracer.log("seek",(0,y.flattenObject)({requestedPosition:e,forcePrecise:t,position:i})))}warmUpMediaSourceIfNeeded(e=this.element?.currentTime){(0,y.isNonNullable)(this.element)&&(0,y.isNonNullable)(this.source)&&(0,y.isNonNullable)(e)&&this.source?.readyState==="ended"&&this.element.duration*1e3-e>this.tuning.dash.seekBiasInTheEnd&&this.bufferManagers.forEach(t=>t.warmUpMediaSource())}get isStreamEnded(){return this.source?.readyState==="ended"}stop(){this.tracer.log("stop"),this.element?.querySelectorAll("source").forEach(e=>{URL.revokeObjectURL(e.src),e.remove()}),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),this.videoBufferManager?.destroy(),this.videoBufferManager=null,this.audioBufferManager?.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getStreams(){return this.manifest?.streams}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),this.source?.readyState==="open"&&Array.from(this.source.sourceBuffers).every(e=>!e.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}initTracerSubscription(){let e=(0,y.getTraceSubscriptionMethod)(this.tracer.error.bind(this.tracer));this.subscription.add(this.error$.subscribe(e("error")))}isManualDecreasePlaybackInLive(){if(!this.element||!this.isLive$.getValue())return!1;let e=1-this.element.playbackRate;return Number(e.toFixed(2))>Number(this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup.toFixed(2))}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}async updateLive(){this.isUpdatingLive=!0,this.manifest=await this.updateManifest(),this.manifest&&(this.bufferManagers?.forEach(e=>e.updateLive(this.manifest)),this.liveTextManager?.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,a=[],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?a.push(1/0):a.push(u.to));if(a.length){let o=Math.max(...a)+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,o===1/0?this.forceEnded$.next():(this.element.currentTime=o/1e3,i={...i,gapEnds:a,jumpTo:o,resultCurrentTime:this.element.currentTime},this.tracer.log("jumpGap",(0,y.flattenObject)(i)))}}};var ho=class{constructor(e,t){this.fov=e,this.orientation=t}};var fo=class{constructor(e,t){this.rotating=!1;this.fading=!1;this.lastTickTS=0;this.lastCameraTurnTS=0;this.fadeStartSpeed=null;this.fadeTime=0;this.camera=e,this.options=t,this.rotationSpeed={x:0,y:0,z:0},this.fadeCorrection=1/(this.options.speedFadeTime/1e3)**2}turnCamera(e=0,t=0,i=0){this.pointCameraTo(this.camera.orientation.x+e,this.camera.orientation.y+t,this.camera.orientation.z+i)}pointCameraTo(e=0,t=0,i=0){t=this.limitCameraRotationY(t);let r=e-this.camera.orientation.x,a=t-this.camera.orientation.y,n=i-this.camera.orientation.z;this.camera.orientation.x=e,this.camera.orientation.y=t,this.camera.orientation.z=i,this.lastCameraTurn={x:r,y:a,z:n},this.lastCameraTurnTS=Date.now()}setRotationSpeed(e,t,i){this.rotationSpeed.x=e??this.rotationSpeed.x,this.rotationSpeed.y=t??this.rotationSpeed.y,this.rotationSpeed.z=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={...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*(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 yv=`attribute vec2 a_vertex;
|
|
124
|
+
`})|(?<privateuse2>${e}))$`.replace(/[\s\t\n]/g,"");return new RegExp(d,"i")}var oc=H(Ut(),1);var rv=require("@vkontakte/videoplayer-shared"),sv=({id:s,width:e,height:t,bitrate:i,fps:r,quality:a,streamId:n})=>{let o=(a?Pi(a):void 0)??(0,rv.videoSizeToQuality)({width:e,height:t});return o&&{id:s,quality:o,bitrate:i,size:{width:e,height:t},fps:r,streamId:n}},av=({id:s,bitrate:e})=>({id:s,bitrate:e}),nv=({language:s,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:s,label:e}),ov=({language:s,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:s,label:e}),uc=({id:s,language:e,label:t,codecs:i,isDefault:r})=>({id:s,language:e,label:t,codec:(0,oc.default)(i.split("."),0),isDefault:r}),lc=({id:s,language:e,label:t,hdr:i,codecs:r})=>({id:s,language:e,hdr:i,label:t,codec:(0,oc.default)(r.split("."),0)}),cc=s=>"url"in s,rt=s=>s.type==="template",Zs=s=>s instanceof DOMException&&(s.name==="AbortError"||s.code===20);var uv=s=>{if(!s?.startsWith("P"))return;let e=(n,o)=>{let u=n?parseFloat(n.replace(",",".")):NaN;return(isNaN(u)?0:u)*o},i=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(s),r=i?.[1]==="-"?-1:1,a={days:e(i?.[5],r),hours:e(i?.[6],r),minutes:e(i?.[7],r),seconds:e(i?.[8],r)};return a.days*24*60*60*1e3+a.hours*60*60*1e3+a.minutes*60*1e3+a.seconds*1e3},fi=(s,e)=>{let t=s;t=(0,dc.default)(t,"$$","$");let i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[r,a]of(0,lv.default)(i)){let n=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=(0,dc.default)(t,n,(o,u)=>(0,ea.isNullable)(a)?o:(0,ea.isNullable)(u)?a:(0,cv.default)(a,parseInt(u,10),"0"))}return t},pv=(s,e)=>{let i=new DOMParser().parseFromString(s,"application/xml"),r={video:[],audio:[],text:[]},a=i.children[0],n=Array.from(a.querySelectorAll("MPD > BaseURL").values()).map(D=>D.textContent?.trim()??""),o=(0,dv.default)(n,0)??"",u=a.getAttribute("type")==="dynamic",l=a.getAttribute("availabilityStartTime"),d=a.getAttribute("publishTime"),c=a.getElementsByTagName("vk:Attrs")[0],p=c?.getElementsByTagName("vk:XLatestSegmentPublishTime")[0].textContent,h=c?.getElementsByTagName("vk:XStreamIsLive")[0].textContent,m=c?.getElementsByTagName("vk:XStreamIsUnpublished")[0].textContent,g=c?.getElementsByTagName("vk:XPlaybackDuration")[0].textContent,v;u&&(v={availabilityStartTime:l?new Date(l).getTime():0,publishTime:d?new Date(d).getTime():0,latestSegmentPublishTime:p?new Date(p).getTime():0,streamIsAlive:h==="yes",streamIsUnpublished:m==="yes"});let T,w=a.getAttribute("mediaPresentationDuration"),x=[...a.getElementsByTagName("Period")],M=x.reduce((D,I)=>({...D,[I.id]:I.children}),{}),B=x.reduce((D,I)=>({...D,[I.id]:I.getAttribute("duration")}),{});w?T=uv(w):(0,pc.default)(B).filter(D=>D).length&&!u?T=(0,pc.default)(B).reduce((D,I)=>D+(uv(I)??0),0):g&&(T=parseInt(g,10));let F=0,G=a.getAttribute("profiles")?.split(",")??[];for(let D of x.map(I=>I.id))for(let I of M[D]){let U=I.getAttribute("id")??"id"+(F++).toString(10),k=I.getAttribute("mimeType")??"",R=I.getAttribute("codecs")??"",C=I.getAttribute("contentType")??k?.split("/")[0],be=I.getAttribute("profiles")?.split(",")??[],N=iv(I.getAttribute("lang")??"")??{},re=I.querySelector("Label")?.textContent?.trim()??void 0,le=I.querySelectorAll("Representation"),Te=I.querySelector("SegmentTemplate"),Be=I.querySelector("Role")?.getAttribute("value")??void 0,Ie=C,ce={id:U,language:N.language,isDefault:Be==="main",label:re,codecs:R,hdr:Ie==="video"&&Dr(R),mime:k,representations:[]};for(let V of le){let z=V.getAttribute("lang")??void 0,Ne=re??I.getAttribute("label")??V.getAttribute("label")??void 0,$e=V.querySelector("BaseURL")?.textContent?.trim()??"",pe=new URL($e||o,e).toString(),Ce=V.getAttribute("mimeType")??k,pt=V.getAttribute("codecs")??R??"",Ke;if(C==="text"){let Ae=V.getAttribute("id")||"",ht=N.privateuse?.includes("x-auto")||Ae.includes("_auto"),Fe=V.querySelector("SegmentTemplate");if(Fe){let $t={representationId:V.getAttribute("id")??void 0,bandwidth:V.getAttribute("bandwidth")??void 0},Zt=parseInt(V.getAttribute("bandwidth")??"",10)/1e3,ei=parseInt(Fe.getAttribute("startNumber")??"",10)??1,ft=parseInt(Fe.getAttribute("timescale")??"",10),Ci=Fe.querySelectorAll("SegmentTimeline S")??[],mt=Fe.getAttribute("media");if(!mt)continue;let ti=[],ii=0,ri="",bt=0,Dt=ei,oe=0;for(let xe of Ci){let Xe=parseInt(xe.getAttribute("d")??"",10),he=parseInt(xe.getAttribute("r")??"",10)||0,Ue=parseInt(xe.getAttribute("t")??"",10);oe=Number.isFinite(Ue)?Ue:oe;let Je=Xe/ft*1e3,gt=oe/ft*1e3;for(let ke=0;ke<he+1;ke++){let qe=fi(mt,{...$t,segmentNumber:Dt.toString(10),segmentTime:(oe+ke*Xe).toString(10)}),St=(gt??0)+ke*Je,Vt=St+Je;Dt++,ti.push({time:{from:St,to:Vt},url:qe})}oe+=(he+1)*Xe,ii+=(he+1)*Je}bt=oe/ft*1e3,ri=fi(mt,{...$t,segmentNumber:Dt.toString(10),segmentTime:oe.toString(10)});let Ct={time:{from:bt,to:1/0},url:ri},Ve={type:"template",baseUrl:pe,segmentTemplateUrl:mt,initUrl:"",totalSegmentsDurationMs:ii,segments:ti,nextSegmentBeyondManifest:Ct,timescale:ft};Ke={id:Ae,kind:"text",segmentReference:Ve,profiles:[],duration:T,bitrate:Zt,mime:"",codecs:"",width:0,height:0,isAuto:ht}}else Ke={id:Ae,isAuto:ht,kind:"text",url:pe}}else{let Ae=V.getAttribute("contentType")??Ce?.split("/")[0]??C,ht=I.getAttribute("profiles")?.split(",")??[],Fe=parseInt(V.getAttribute("width")??"",10),$t=parseInt(V.getAttribute("height")??"",10),Zt=parseInt(V.getAttribute("bandwidth")??"",10)/1e3,ei=V.getAttribute("frameRate")??"",ft=V.getAttribute("quality")??void 0,Ci=ei?Xn(ei):void 0,mt=V.getAttribute("id")??"id"+(F++).toString(10),ti=Ae==="video"?`${$t}p`:Ae==="audio"?`${Zt}Kbps`:pt,ii=`${mt}@${ti}`,ri=[...G,...be,...ht],bt,Dt=V.querySelector("SegmentBase"),oe=V.querySelector("SegmentTemplate")??Te;if(Dt){let Ve=V.querySelector("SegmentBase Initialization")?.getAttribute("range")??"",[xe,Xe]=Ve.split("-").map(qe=>parseInt(qe,10)),he={from:xe,to:Xe},Ue=V.querySelector("SegmentBase")?.getAttribute("indexRange"),[Je,gt]=Ue?Ue.split("-").map(qe=>parseInt(qe,10)):[],ke=Ue?{from:Je,to:gt}:void 0;bt={type:"byteRange",url:pe,initRange:he,indexRange:ke}}else if(oe){let Ve={representationId:V.getAttribute("id")??void 0,bandwidth:V.getAttribute("bandwidth")??void 0},xe=parseInt(oe.getAttribute("timescale")??"",10),Xe=oe.getAttribute("initialization")??"",he=oe.getAttribute("media"),Ue=parseInt(oe.getAttribute("startNumber")??"",10)??1,Je=fi(Xe,Ve);if(!he)throw new ReferenceError("No media attribute in SegmentTemplate");let gt=oe.querySelectorAll("SegmentTimeline S")??[],ke=[],qe=0,St="",Vt=0;if(gt.length){let si=Ue,Ee=0;for(let vt of gt){let Re=parseInt(vt.getAttribute("d")??"",10),Ze=parseInt(vt.getAttribute("r")??"",10)||0,ai=parseInt(vt.getAttribute("t")??"",10);Ee=Number.isFinite(ai)?ai:Ee;let Vi=Re/xe*1e3,Co=Ee/xe*1e3;for(let ni=0;ni<Ze+1;ni++){let Vo=fi(he,{...Ve,segmentNumber:si.toString(10),segmentTime:(Ee+ni*Re).toString(10)}),Ur=(Co??0)+ni*Vi,Oo=Ur+Vi;si++,ke.push({time:{from:Ur,to:Oo},url:Vo})}Ee+=(Ze+1)*Re,qe+=(Ze+1)*Vi}Vt=Ee/xe*1e3,St=fi(he,{...Ve,segmentNumber:si.toString(10),segmentTime:Ee.toString(10)})}else if((0,ea.isNonNullable)(T)){let Ee=parseInt(oe.getAttribute("duration")??"",10)/xe*1e3,vt=Math.ceil(T/Ee),Re=0;for(let Ze=1;Ze<vt;Ze++){let ai=fi(he,{...Ve,segmentNumber:Ze.toString(10),segmentTime:Re.toString(10)});ke.push({time:{from:Re,to:Re+Ee},url:ai}),Re+=Ee}Vt=Re,St=fi(he,{...Ve,segmentNumber:vt.toString(10),segmentTime:Re.toString(10)})}let Do={time:{from:Vt,to:1/0},url:St};bt={type:"template",baseUrl:pe,segmentTemplateUrl:he,initUrl:Je,totalSegmentsDurationMs:qe,segments:ke,nextSegmentBeyondManifest:Do,timescale:xe}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!Ae||!Ce)continue;let Ct={video:"video",audio:"audio",text:"text"}[Ae];if(!Ct)continue;Ie||=Ct,Ke={id:ii,kind:Ct,segmentReference:bt,profiles:ri,duration:T,bitrate:Zt,mime:Ce,codecs:pt,width:Fe,height:$t,fps:Ci,quality:ft}}ce.language||=z,ce.label||=Ne,ce.mime||=Ce,ce.codecs||=pt,ce.hdr||=Ie==="video"&&Dr(pt),ce.representations.push(Ke)}if(Ie){let V=r[Ie].find(z=>z.id===ce.id);if(V&&ce.representations.every(z=>rt(z.segmentReference)))for(let z of V.representations){let $e=ce.representations.find(Ce=>Ce.id===z.id)?.segmentReference,pe=z.segmentReference;pe.segments.push(...$e.segments),pe.nextSegmentBeyondManifest=$e.nextSegmentBeyondManifest}else r[Ie].push(ce)}}return{duration:T,streams:r,baseUrls:n,live:v}};var fc=require("@vkontakte/videoplayer-shared"),Y=(s,e)=>(0,fc.isNonNullable)(s)&&(0,fc.isNonNullable)(e)&&s.readyState==="open"&&LM(s,e);function LM(s,e){for(let t=0;t<s.activeSourceBuffers.length;++t)if(s.activeSourceBuffers[t]===e)return!0;return!1}var ta=class{constructor(e,t,i,{fetcher:r,tuning:a,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new A.ValueSubject(0);this.currentLowLatencySegmentLength$=new A.ValueSubject(0);this.currentSegmentLength$=new A.ValueSubject(0);this.onLastSegment$=new A.ValueSubject(!1);this.fullyBuffered$=new A.ValueSubject(!1);this.playingRepresentation$=new A.ValueSubject(void 0);this.playingRepresentationInit$=new A.ValueSubject(void 0);this.error$=new A.Subject;this.gaps=[];this.subscription=new A.Subscription;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new de;this.switchAbortController=new de;this.destroyAbortController=new de;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=(0,A.abortable)(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);(0,A.assertNonNullable)(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new hS(this.sourceBuffer),this.subscription.add((0,A.fromEvent)(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let o,u=this.mediaSource.readyState;u!=="open"&&(o={id:`SegmentEjection_source_${u}`,category:A.ErrorCategory.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o??={id:"SegmentEjection",category:A.ErrorCategory.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n},this.error$.next(o)})),this.subscription.add((0,A.fromEvent)(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:A.ErrorCategory.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o||!Y(this.mediaSource,this.sourceBuffer))return;let u=Math.min(this.bufferLimit,Lr(this.sourceBuffer.buffered)*.8);this.bufferLimit=u;let l=this.getForwardBufferDuration(o),d=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(o,n*2,l<d).catch(c=>{this.handleAsyncError(c,"pruneBuffer")})})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(n=>this.error$.next(n))),yield this.loadInit(t,"high",!0);let i=this.initData.get(t.id),r=this.segments.get(t.id),a=this.parsedInitData.get(t.id);(0,A.assertNonNullable)(i,"No init buffer for starting representation"),(0,A.assertNonNullable)(r,"No segments for starting representation"),i instanceof ArrayBuffer&&(this.searchGaps(r,t),yield this.sourceBufferTaskQueue.append(i,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(a))}.bind(this));this.switchTo=(0,A.abortable)(this.destroyAbortController.signal,async function*(e,t=!1){if(!Y(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);(0,A.assertNonNullable)(i,`No such representation ${e}`);let r=this.segments.get(e),a=this.initData.get(e);if((0,A.isNullable)(a)||(0,A.isNullable)(r)?yield this.loadInit(i,"high",!1):a instanceof Promise&&(yield a),r=this.segments.get(e),(0,A.assertNonNullable)(r,"No segments for starting representation"),a=this.initData.get(e),!(!a||!(a instanceof ArrayBuffer)||!this.sourceBuffer||!Y(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(a,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer();else{let n=this.getCurrentPosition();(0,A.isNonNullable)(n)&&!this.isLive&&(this.bufferLimit=1/0,await this.pruneBuffer(n,1/0,!0)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}this.maintain()}}.bind(this));this.switchToOld=(0,A.abortable)(this.destroyAbortController.signal,async function*(e,t=!1){if(!Y(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);(0,A.assertNonNullable)(i,`No such representation ${e}`);let r=this.segments.get(e),a=this.initData.get(e);if((0,A.isNullable)(a)||(0,A.isNullable)(r)?yield this.loadInit(i,"high",!1):a instanceof Promise&&(yield a),r=this.segments.get(e),(0,A.assertNonNullable)(r,"No segments for starting representation"),a=this.initData.get(e),!(!a||!(a instanceof ArrayBuffer)||!this.sourceBuffer||!Y(this.mediaSource,this.sourceBuffer)))if(yield this.abort(),yield this.sourceBufferTaskQueue.append(a,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer(),this.maintain();else{let n=this.getCurrentPosition();(0,A.isNonNullable)(n)&&(this.isLive||(this.bufferLimit=1/0,await this.pruneBuffer(n,1/0,!0)),this.maintain(n)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}}.bind(this));this.seekLive=(0,A.abortable)(this.destroyAbortController.signal,async function*(e){let t=(0,Zn.default)(e,u=>u.representations)??[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let u of this.representations.keys()){let l=t.find(p=>p.id===u);l&&this.representations.set(u,l);let d=this.representations.get(u);if(!d||!rt(d.segmentReference))return;let c=this.getActualLiveStartingSegments(d.segmentReference);this.segments.set(d.id,c)}let i=this.switchingToRepresentationId??this.downloadingRepresentationId,r=this.representations.get(i);(0,A.assertNonNullable)(r);let a=this.segments.get(i);(0,A.assertNonNullable)(a,"No segments for starting representation");let n=this.initData.get(i);if((0,A.assertNonNullable)(n,"No init buffer for starting representation"),!(n instanceof ArrayBuffer))return;let o=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,yield this.abort(),o&&(yield this.sourceBufferTaskQueue.remove(o.from*1e3,o.to*1e3,this.destroyAbortController.signal)),this.searchGaps(a,r),yield this.sourceBufferTaskQueue.append(n,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this));this.fetcher=r,this.tuning=a,this.compatibilityMode=u,this.forwardBufferTarget=a.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=o,this.isLive=!!l?.live,this.baseUrls=l?.baseUrls??[],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){!Y(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new de,(0,A.abortable)(this.switchAbortController.signal,async function*(i,r=!1){this.switchingToRepresentationId=i;let a=this.representations.get(i);(0,A.assertNonNullable)(a,`No such representation ${i}`);let n=this.segments.get(i),o=this.initData.get(i);if((0,A.isNullable)(o)||(0,A.isNullable)(n)?yield this.loadInit(a,"high",!1):o instanceof Promise&&(yield o),n=this.segments.get(i),(0,A.assertNonNullable)(n,"No segments for starting representation"),o=this.initData.get(i),!(!(o instanceof ArrayBuffer)||!this.sourceBuffer||!Y(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();(0,A.isNonNullable)(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(){!(0,A.isNullable)(this.sourceBuffer)&&!this.sourceBuffer.updating&&(this.sourceBuffer.mode="segments")}async abort(){for(let e of this.activeSegments)this.abortSegment(e.segment);return this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new de,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if((0,A.isNullable)(e)||(0,A.isNullable)(this.downloadingRepresentationId)||(0,A.isNullable)(this.playingRepresentationId)||(0,A.isNullable)(this.sourceBuffer)||!Y(this.mediaSource,this.sourceBuffer)||(0,A.isNonNullable)(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if((0,A.assertNonNullable)(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;let r=i.find(d=>e>=d.time.from&&e<d.time.to);(0,A.isNonNullable)(r)&&isFinite(r.time.from)&&isFinite(r.time.to)&&this.currentSegmentLength$.next(r?.time.to-r.time.from);let a=e,n=100;if(this.playingRepresentationId!==this.downloadingRepresentationId){let d=this.getForwardBufferDuration(e),c=r?r.time.to+n:-1/0;r&&r.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&d>=r.time.to-e+n&&(a=c)}if(isFinite(this.bufferLimit)&&Lr(this.sourceBuffer.buffered)>=this.bufferLimit){let d=this.getForwardBufferDuration(e),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,d<c).catch(p=>{this.handleAsyncError(p,"pruneBuffer")});return}let u=[];if(!this.activeSegments.size&&(u=this.selectForwardBufferSegments(i,t.segmentReference.type,a),u.length)){let d="auto";if(this.tuning.dash.useFetchPriorityHints&&r)if((0,Jn.default)(u,r))d="high";else{let c=(0,Cr.default)(u,0);c&&c.time.from-r.time.to>=this.forwardBufferTarget/2&&(d="low")}this.loadSegments(u,t,d).catch(c=>{this.handleAsyncError(c,"loadSegments")})}(!this.preloadOnly&&!this.allInitsLoaded&&r&&r.status==="fed"&&!u.length&&this.getForwardBufferDuration(e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let l=(0,Cr.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 a of e)Math.trunc(a.time.from-i)>0&&this.gaps.push({representation:t.id,from:i,to:a.time.from+r}),i=a.time.to;(0,A.isNonNullable)(t.duration)&&t.duration-i>0&&!this.isLive&&this.gaps.push({representation:t.id,from:i,to:t.duration})}getActualLiveStartingSegments(e){let t=e.segments,i=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,r=[],a=0,n=t.length-1;do r.unshift(t[n]),a+=t[n].time.to-t[n].time.from,n--;while(a<i&&n>=0);return this.liveInitialAdditionalOffset=a-i,this.isActiveLowLatency()?[r[0]]:r}getLiveSegmentsToLoadState(e){let t=(0,Zn.default)(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?.length)return{from:i[0].time.from,to:i[i.length-1].time.to}}updateLive(e){let t=(0,Zn.default)(e?.streams[this.kind],i=>i.representations)??[];if(![...this.segments.values()].every(i=>!i.length))for(let i of t){if(!i||!rt(i.segmentReference))return;let r=i.segmentReference.segments.map(l=>({...l,status:"none",size:void 0})),a=100,n=this.segments.get(i.id)??[],o=(0,Cr.default)(n,-1)?.time.to??0,u=r?.findIndex(l=>o>=l.time.from+a&&o<=l.time.to+a);if(u===-1){this.liveUpdateSegmentIndex=0;let l=this.getActualLiveStartingSegments(i.segmentReference);this.segments.set(i.id,l)}else{let l=r.slice(u+1);this.segments.set(i.id,[...n,...l])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;(0,A.assertNonNullable)(e);let t=this.segments.get(e);if(t?.length){let i=t[t.length-1];this.updateLowLatencyLiveIfNeeded(i)}}updateLowLatencyLiveIfNeeded(e){let t=0;for(let i of this.representations.values()){let r=i.segmentReference;if(!rt(r))return;let a=this.segments.get(i.id)??[],n=a.find(u=>Math.floor(u.time.from)===Math.floor(e.time.from));if(n&&!isFinite(n.time.to)&&(n.time.to=e.time.to,t=n.time.to-n.time.from),!!!a.find(u=>Math.floor(u.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let u=Math.round(e.time.to*r.timescale/1e3).toString(10),l=fi(r.segmentTemplateUrl,{segmentTime:u});a.push({status:"none",time:{from:e.time.to,to:1/0},url:l})}}this.currentLowLatencySegmentLength$.next(t)}findSegmentStartTime(e){let t=this.switchingToRepresentationId??this.downloadingRepresentationId??this.playingRepresentationId;if(!t)return;let i=this.segments.get(t);return i?i.find(a=>a.time.from<=e&&a.time.to>=e)?.time.from??void 0:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),this.sourceBufferTaskQueue?.destroy(),this.gapDetectionIdleCallback&&Xt&&Xt(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&Xt&&Xt(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer)try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(e){if(!(e instanceof DOMException&&e.name==="NotFoundError"))throw e}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=this.getForwardBufferDuration(i),a=e.findIndex(({status:p,time:{from:h,to:m}},g)=>{let v=h<=i&&m>=i,T=h>i||v||g===0&&i===0,w=Math.min(this.forwardBufferTarget,this.bufferLimit),x=this.preloadOnly&&h<=i+w||r<w&&m-h>=w||m<=i+w;return(p==="none"||p==="partially_ejected"&&T&&x&&this.sourceBuffer&&Y(this.mediaSource,this.sourceBuffer)&&!(Ye(this.sourceBuffer.buffered,h)&&Ye(this.sourceBuffer.buffered,m)))&&T&&x});if(a===-1)return[];if(t!=="byteRange")return e.slice(a,a+1);let n=e,o=0,u=0,l=[],d=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,c=this.preloadOnly?this.forwardBufferTarget:0;for(let p=a;p<n.length&&(o<=d||u<=c);p++){let h=n[p];if(o+=h.byte.to+1-h.byte.from,u+=h.time.to+1-h.time.from,h.status==="none"||h.status==="partially_ejected")l.push(h);else break}return l}async loadSegments(e,t,i="auto"){rt(t.segmentReference)?await this.loadTemplateSegment(e[0],t,i):await this.loadByteRangeSegments(e,t,i)}async loadTemplateSegment(e,t,i="auto"){e.status="downloading";let r={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(r);let{range:a,url:n,signal:o,onProgress:u,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(await(0,A.abortable)(o,async function*(){let d=(0,A.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>setTimeout(c,d))}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let d=await this.fetcher.fetch(n,{range:a,signal:o,onProgress:u,priority:i,isLowLatency:this.isActiveLowLatency()});if(this.lastDataObtainedTimestampMs=(0,A.now)(),!d)return;let c=new DataView(d),p=Js(t.mime);if(!isFinite(r.segment.time.to)){let g=t.segmentReference.timescale;r.segment.time.to=p.getChunkEndTime(c,g)}u&&r.feedingBytes&&l?await Promise.all(l):await this.sourceBufferTaskQueue.append(c,o);let{serverDataReceivedTimestamp:h,serverDataPreparedTime:m}=p.getServerLatencyTimestamps(c);h&&m&&this.currentLiveSegmentServerLatency$.next(m-h),r.segment.status="downloaded",this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(d){this.abortActiveSegments([e]),Zs(d)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}updateRepresentationsBaseUrlIfNeeded(){if(!this.tuning.dash.enableBaseUrlSupport||!this.baseUrls.length||this.failedDownloads<=this.tuning.dash.maxSegmentRetryCount)return;this.baseUrlsIndex=(this.baseUrlsIndex+1)%this.baseUrls.length;let e=this.baseUrls[this.baseUrlsIndex];for(let t of this.representations.values())rt(t.segmentReference)?t.segmentReference.baseUrl=e:t.segmentReference.url=e}async loadByteRangeSegments(e,t,i="auto"){if(!e.length)return;for(let u of e)u.status="downloading",this.activeSegments.add({segment:u,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:r,url:a,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(await(0,A.abortable)(n,async function*(){let u=(0,A.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),(0,A.fromEvent)(window,"online").pipe((0,A.once)()).subscribe(()=>{l(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(a,{range:r,onProgress:o,signal:n,priority:i}),this.lastDataObtainedTimestampMs=(0,A.now)(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),Zs(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}prepareByteRangeFetchSegmentParams(e,t){if(rt(t.segmentReference))throw new Error("Representation is not byte range type");let i=t.segmentReference.url,r={from:(0,Cr.default)(e,0).byte.from,to:(0,Cr.default)(e,-1).byte.to},{signal:a}=this.downloadAbortController;return{url:i,range:r,signal:a,onProgress:async(o,u)=>{if(!a.aborted)try{this.lastDataObtainedTimestampMs=(0,A.now)(),await this.onSomeByteRangesDataLoaded({dataView:o,loaded:u,signal:a,onSegmentAppendFailed:()=>this.abort(),globalFrom:r?r.from:0,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:A.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!rt(t.segmentReference))throw new Error("Representation is not template type");let i=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&i.searchParams.set("low-latency","yes");let r=i.toString(),{signal:a}=this.downloadAbortController,n=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(l,d)=>{if(!a.aborted)try{this.lastDataObtainedTimestampMs=(0,A.now)();let c=this.onSomeTemplateDataLoaded({dataView:l,loaded:d,signal:a,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(c)}catch(c){this.error$.next({id:"SegmentFeeding",category:A.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:c})}}:void 0;return{url:r,signal:a,onProgress:u,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)(0,Jn.default)(e,t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:r,signal:a}){if(!this.activeSegments.size||!Y(this.mediaSource,this.sourceBuffer))return;let n=this.representations.get(t);if(n)for(let o of this.activeSegments){let{segment:u}=o;if(o.representationId===t){if(a.aborted){r();continue}if(o.loadedBytes=i,o.loadedBytes>o.feedingBytes){let l=new DataView(e.buffer,e.byteOffset+o.feedingBytes,o.loadedBytes-o.feedingBytes),d=Js(n.mime).parseFeedableSegmentChunk(l,this.isLive);d?.byteLength&&(u.status="partially_fed",o.feedingBytes+=d.byteLength,await this.sourceBufferTaskQueue.append(d),o.fedBytes+=d.byteLength)}}}}async onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:a,onSegmentAppendFailed:n}){if(!this.activeSegments.size||!Y(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)continue;if(a.aborted){await n();continue}let d=l.byte.from-i,c=l.byte.to-i,p=c-d+1,h=d<r,m=c<=r;if(!h)continue;let g=Js(o.mime);if(l.status==="downloading"&&m){l.status="downloaded";let v=new DataView(e.buffer,e.byteOffset+d,p);await this.sourceBufferTaskQueue.append(v,a)&&!a.aborted?this.onSegmentFullyAppended(u,t):await n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(l.status==="downloading"||l.status==="partially_fed")&&(u.loadedBytes=Math.min(p,r-d),u.loadedBytes>u.feedingBytes)){let v=new DataView(e.buffer,e.byteOffset+d+u.feedingBytes,u.loadedBytes-u.feedingBytes),T=u.loadedBytes===p?v:g.parseFeedableSegmentChunk(v);T?.byteLength&&(l.status="partially_fed",u.feedingBytes+=T.byteLength,await this.sourceBufferTaskQueue.append(T,a)&&!a.aborted?(u.fedBytes+=T.byteLength,u.fedBytes===p&&this.onSegmentFullyAppended(u,t)):await n())}}}onSegmentFullyAppended(e,t){if(!((0,A.isNullable)(this.sourceBuffer)||!Y(this.mediaSource,this.sourceBuffer))){!this.isLive&&W.browser.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(Ye(this.sourceBuffer.buffered,e.segment.time.from,100)&&Ye(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:A.ErrorCategory.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",cc(e.segment)&&(e.segment.size=e.fedBytes);for(let i of this.representations.values())if(i.id!==t)for(let r of this.segments.get(i.id)??[])r.status==="fed"&&Math.round(r.time.from)===Math.round(e.segment.time.from)&&Math.round(r.time.to)===Math.round(e.segment.time.to)&&(r.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,a]of this.initData.entries()){let n=a instanceof Promise;t||=n,a===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let i=this.representations.get(e);i&&(this.initLoadIdleCallback=Mr(()=>(0,hv.default)(this.loadInit(i,"low",!1),()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",i=!1){let r=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!i&&this.failedDownloads>0?(0,A.abortable)(this.destroyAbortController.signal,async function*(){let o=(0,A.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,Js(e.mime),r)).then(async o=>{if(!o)return;let{init:u,dataView:l,segments:d}=o,c=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,c);let p=d;this.isLive&&rt(e.segmentReference)&&(p=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,p),u&&this.parsedInitData.set(e.id,u)}).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:A.ErrorCategory.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n}async dropBuffer(){for(let e of this.segments.values())for(let t of e)t.status="none";await this.pruneBuffer(0,1/0,!0)}async pruneBuffer(e,t,i=!1){if(!this.sourceBuffer||!Y(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||(0,A.isNullable)(e))return!1;let r=[],a=0,n=u=>{u.sort((d,c)=>d.from-c.from);let l=[u[0]];for(let d=1;d<u.length;d++){let{from:c,to:p}=u[d],h=l[l.length-1];h.to>=c?h.to=Math.max(h.to,p):l.push(u[d])}return l},o=u=>{if(a>=t)return r;r.push({...u.time}),r=n(r);let l=cc(u)?u.size??0:u.byte.to-u.byte.from;a+=l};for(let u of this.segments.values())for(let l of u){let d=l.time.to<=e-this.tuning.dash.bufferPruningSafeZone,c=l.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(d||c)&&l.status==="fed"&&o(l)}for(let u=0;u<this.sourceBuffer.buffered.length;u++){let l=this.sourceBuffer.buffered.start(u)*1e3,d=this.sourceBuffer.buffered.end(u)*1e3,c=0;for(let p of this.segments.values())for(let h of p)(0,Jn.default)(["none","partially_ejected"],h.status)&&Math.round(h.time.from)<=Math.round(l)&&Math.round(h.time.to)>=Math.round(d)&&c++;if(c===this.segments.size){let p={time:{from:l,to:d},url:"",status:"none"};o(p)}}if(r.length&&i){let u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let l of this.segments.values())for(let d of l)d.time.from>=e+u&&d.status==="fed"&&o(d)}return r.length?(await Promise.all(r.map(l=>this.sourceBufferTaskQueue.remove(l.from,l.to)))).reduce((l,d)=>l||d,!1):!1}async abortBuffer(){if(!this.sourceBuffer||!Y(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||!Y(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||!Y(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||(0,A.isNullable)(e)?0:ze(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!(!this.sourceBuffer||!Y(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 a=0;a<this.sourceBuffer.buffered.length;a++){let n=this.sourceBuffer.buffered.start(a)*1e3,o=this.sourceBuffer.buffered.end(a)*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(a=>r&&a.from===r.from&&a.to===r.to)&&this.gaps.push(r)}}}detectGapsWhenIdle(e,t){if(!(this.gapDetectionIdleCallback||!this.sourceBuffer||!Y(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=Mr(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:A.ErrorCategory.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if((0,A.isNullable)(this.sourceBuffer)||!Y(this.mediaSource,this.sourceBuffer)||(0,A.isNullable)(this.playingRepresentationId))return;let e=[];for(let i=0;i<this.sourceBuffer.buffered.length;i++){let r=Math.floor(this.sourceBuffer.buffered.start(i)*1e3),a=Math.ceil(this.sourceBuffer.buffered.end(i)*1e3);e.push({from:r,to:a})}let t=100;for(let i of this.segments.values())for(let r of i){let{status:a}=r;if(a!=="fed"&&a!=="partially_ejected")continue;let n=Math.floor(r.time.from),o=Math.ceil(r.time.to),u=e.some(d=>d.from-t<=n&&d.to+t>=o),l=e.filter(d=>n>=d.from&&n<d.to-t||o>d.from+t&&o<=d.to);u||(l.length===1?r.status="partially_ejected":this.gaps.some(d=>d.from===r.time.from||d.to===r.time.to)?r.status="partially_ejected":r.status="none")}}handleAsyncError(e,t){this.error$.next({id:t,category:A.ErrorCategory.VIDEO_PIPELINE,thrown:e,message:"Something went wrong"})}};var Li=s=>{let e=new URL(s);return e.searchParams.set("quic","1"),e.toString()};var eo=s=>{let e=s.get("X-Delivery-Type"),t=s.get("X-Reused"),i=e===null?"http1":e??void 0,r=t===null?void 0:{1:!0,0:!1}[t]??void 0;return{type:i,reused:r}};var Z=require("@vkontakte/videoplayer-shared");var to=s=>{let e=new URL(s);return e.searchParams.set("enable-subtitles","yes"),e.toString()};var ro=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:a=!1}){this.lastConnectionType$=new Z.ValueSubject(void 0);this.lastConnectionReused$=new Z.ValueSubject(void 0);this.lastRequestFirstBytes$=new Z.ValueSubject(void 0);this.recoverableError$=new Z.Subject;this.error$=new Z.Subject;this.abortAllController=new de;this.subscription=new Z.Subscription;this.fetchManifest=(0,Z.abortable)(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=Li(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=to(i));let r=yield this.doFetch(i,{signal:this.abortAllController.signal}).catch(io);return r?(t.log("success",(0,Z.flattenObject)({url:i,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(r.headers),r.text()):(t.error("error",(0,Z.flattenObject)({url:i,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=(0,Z.abortable)(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:i,onProgress:r,priority:a="auto",signal:n,measureThroughput:o=!0,isLowLatency:u=!1}={}){let l=e,d=new Headers,c=this.tracer.createComponentTracer("Fetch");if(i)switch(t){case 0:{d.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let U=new URL(l,location.href);U.searchParams.append("bytes",`${i.from}-${i.to}`),l=U.toString();break}default:(0,Z.assertNever)(t)}this.requestQuic&&(l=Li(l));let p=this.abortAllController.signal,h;if(n){let U=new de;if(h=(0,Z.merge)((0,Z.fromEvent)(this.abortAllController.signal,"abort"),(0,Z.fromEvent)(n,"abort")).subscribe(()=>{try{U.abort()}catch(k){io(k)}}),this.subscription.add(h),this.abortAllController.signal.aborted||n.aborted)try{U.abort()}catch(k){io(k)}p=U.signal}let m=(0,Z.now)();c.log("startRequest",(0,Z.flattenObject)({url:l,priority:a,rangeMethod:t,range:i,isLowLatency:u,requestStartedAt:m}));let g=yield this.doFetch(l,{priority:a,headers:d,signal:p}),v=(0,Z.now)();if(!g)return c.error("error",{message:"No response in request"}),c.end(),h?.unsubscribe(),null;if(this.throughputEstimator?.addRawRtt(v-m),!g.ok||!g.body){h?.unsubscribe();let U=`Fetch error ${g.status}: ${g.statusText}`;return c.error("error",{message:U}),c.end(),Promise.reject(new Error(`Fetch error ${g.status}: ${g.statusText}`))}if(this.onHeadersReceived(g.headers),!r&&!o){h?.unsubscribe();let U=(0,Z.now)(),k={requestStartedAt:m,requestEndedAt:U,duration:U-m};return c.log("endRequest",(0,Z.flattenObject)(k)),c.end(),g.arrayBuffer()}let[T,w]=g.body.tee(),x=T.getReader();o&&this.throughputEstimator?.trackStream(w,u);let M=0,B=new Uint8Array(0),F=!1,G=U=>{h?.unsubscribe(),F=!0,io(U)},$=(0,Z.abortable)(p,async function*({done:U,value:k}){if(M===0&&this.lastRequestFirstBytes$.next((0,Z.now)()-m),p.aborted){h?.unsubscribe();return}if(!U&&k){let R=new Uint8Array(B.length+k.length);R.set(B),R.set(k,B.length),B=R,M+=k.byteLength,r?.(new DataView(B.buffer),M),yield x?.read().then($,G)}}.bind(this));yield x?.read().then($,G),h?.unsubscribe();let D=(0,Z.now)(),I={failed:F,requestStartedAt:m,requestEndedAt:D,duration:D-m};return F?(c.error("endRequest",(0,Z.flattenObject)(I)),c.end(),null):(c.log("endRequest",(0,Z.flattenObject)(I)),c.end(),B.buffer)}.bind(this));this.fetchByteRangeRepresentation=(0,Z.abortable)(this.abortAllController.signal,async function*(e,t,i){if(e.type!=="byteRange")return null;let{from:r,to:a}=e.initRange,n=r,o=a,u=!1,l,d;e.indexRange&&(l=e.indexRange.from,d=e.indexRange.to,u=a+1===l,u&&(n=Math.min(l,r),o=Math.max(d,a))),n=Math.min(n,0);let c=yield this.fetch(e.url,{range:{from:n,to:o},priority:i,measureThroughput:!1});if(!c)return null;let p=new DataView(c,r-n,a-n+1);if(!t.validateData(p))throw new Error("Invalid media file");let h=t.parseInit(p),m=e.indexRange??t.getIndexRange(h);if(!m)throw new ReferenceError("No way to load representation index");let g;if(u)g=new DataView(c,m.from-n,m.to-m.from+1);else{let T=yield this.fetch(e.url,{range:m,priority:i,measureThroughput:!1});if(!T)return null;g=new DataView(T)}let v=t.parseSegments(g,h,m);return{init:h,dataView:new DataView(c),segments:v}}.bind(this));this.fetchTemplateRepresentation=(0,Z.abortable)(this.abortAllController.signal,async function*(e,t){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=>({...n,status:"none",size:void 0})),dataView:new DataView(r)}:null}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=r,this.tracer=i.createComponentTracer("Fetcher"),this.useEnableSubtitlesParam=a}onHeadersReceived(e){let{type:t,reused:i}=eo(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}async fetchRepresentation(e,t,i="auto"){let{type:r}=e;switch(r){case"byteRange":return await this.fetchByteRangeRepresentation(e,t,i)??null;case"template":return await this.fetchTemplateRepresentation(e,i)??null;default:(0,Z.assertNever)(r)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}async doFetch(e,t){let i=await Lt(e,t);if(i.ok)return i;let r=await i.text(),a=parseInt(r);if(!isNaN(a))switch(a){case 1:this.recoverableError$.next({id:"VideoDataLinkExpiredError",message:"Video data links have expired",category:Z.ErrorCategory.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:Z.ErrorCategory.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:Z.ErrorCategory.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:Z.ErrorCategory.FATAL});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${a})`,category:Z.ErrorCategory.FATAL})}}},io=s=>{if(!Zs(s))throw s};var mi=(s,e,t)=>t*e+(1-t)*s,mc=(s,e)=>s.reduce((t,i)=>t+i,0)/e,fv=(s,e,t,i)=>{let r=0,a=t,n=mc(s,e),o=e<i?e:i;for(let u=0;u<o;u++)s[a]>n?r++:r--,a=(s.length+a-1)%s.length;return Math.abs(r)===o};var ia=require("@vkontakte/videoplayer-shared"),Bi=class{constructor(e){this.prevReported=void 0;this.pastMeasures=[];this.takenMeasures=0;this.measuresCursor=0;this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new ia.ValueSubject(e.initial),this.debounced$=new ia.ValueSubject(e.initial);let t=e.label??"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new tt(`raw_${t}`),this.smoothedSeries$=new tt(`smoothed_${t}`),this.reportedSeries$=new tt(`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+=(this.pastMeasures[o]-this.smoothed)**2,i++);this.takenMeasures=i,t/=i;let r=Math.sqrt(t),a=this.smoothed+this.params.deviationFactor*r,n=this.smoothed-this.params.deviationFactor*r;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(e),this.updateSmoothedValue(e),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),!(this.smoothed>a||this.smoothed<n)&&((0,ia.isNullable)(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 so=class extends Bi{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=mi(this.slow,e,this.params.emaAlphaSlow),this.fast=mi(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var ao=class extends Bi{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=mc(this.pastMeasures,this.takenMeasures);this.emaSmoothed=mi(this.emaSmoothed,e,this.params.emaAlpha);let i=fv(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=i?this.emaSmoothed:t}};var no=class extends Bi{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?mi(this.smoothed,t,this.params.emaAlpha):t}};var bi=class{static getSmoothedValue(e,t,i){return i.type==="TwoEma"?new so({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new ao({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 no({initial:e,label:"liveEdgeDelay",...t})}};var Vr=(s,e)=>{s&&s.playbackRate!==e&&(s.playbackRate=e)};var oo=require("@vkontakte/videoplayer-shared");var ra=class s{constructor(e,t){this.currentRepresentation$=new oo.ValueSubject(null);this.maxRepresentations=4;this.representationsCursor=0;this.representations=[];this.currentSegment=null;this.getCurrentPosition=t.getCurrentPosition,this.processStreams(e)}updateLive(e){this.processStreams(e?.streams.text)}seekLive(e){this.processStreams(e)}maintain(e=this.getCurrentPosition()){if(!(0,oo.isNullable)(e))for(let t of this.representations)for(let i of t){let r=i.segmentReference,a=r.segments.length,n=r.segments[0].time.from,o=r.segments[a-1].time.to;if(e<n||e>o)continue;let u=r.segments.find(l=>l.time.from<=e&&l.time.to>=e);!u||this.currentSegment?.time.from===u.time.from&&this.currentSegment.time.to===u.time.to||(this.currentSegment=u,this.currentRepresentation$.next({...i,label:"Live Text",language:"ru",isAuto:!0,url:new URL(u.url,r.baseUrl).toString()}))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e??[]){let i=s.filterRepresentations(t.representations);if(i){this.representations[this.representationsCursor]=i,this.representationsCursor=(this.representationsCursor+1)%this.maxRepresentations;break}}}static isSupported(e){return!!e?.some(t=>s.filterRepresentations(t.representations))}static filterRepresentations(e){return e?.filter(t=>t.kind==="text"&&"segmentReference"in t&&rt(t.segmentReference))}};var lo=H(Ut(),1);var sa=require("@vkontakte/videoplayer-shared");var mv=(s,{useManagedMediaSource:e,useOldMSEDetection:t})=>{let{containers:i,protocols:r,codecs:a,nativeHlsSupported:n}=W.video,o=(a.h264||a.h265)&&a.aac,u=r.mse&&(!t||!!window.MediaStreamTrack)||r.mms&&e;return s.filter(l=>{switch(l){case"DASH_SEP":return u&&i.mp4&&o;case"DASH_WEBM":return u&&i.webm&&a.vp9&&a.opus;case"DASH_WEBM_AV1":return u&&i.webm&&a.av1&&a.opus;case"DASH_STREAMS":return u&&(i.mp4&&o||i.webm&&(a.vp9||a.av1)&&(a.opus||a.aac));case"DASH_LIVE":return u&&i.mp4&&o;case"DASH_LIVE_CMAF":return u&&i.mp4&&o&&i.cmaf;case"DASH_ONDEMAND":return u&&i.mp4&&o;case"HLS":case"HLS_ONDEMAND":case"HLS_LIVE":case"HLS_LIVE_CMAF":return n;case"MPEG":return i.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return r.webrtc&&r.ws&&a.h264&&(i.mp4||i.webm);default:return(0,sa.assertNever)(l)}})},uo=s=>{let{webmDecodingInfo:e}=W.video,t="DASH_WEBM",i="DASH_WEBM_AV1";switch(s){case"vp9":return[t,i];case"av1":return[i,t];case"none":return[];case"smooth":return e?e[i].smooth?[i,t]:e[t].smooth?[t,i]:[i,t]:[t,i];case"power_efficient":return e?e[i].powerEfficient?[i,t]:e[t].powerEfficient?[t,i]:[i,t]:[t,i];default:(0,sa.assertNever)(s)}return[t,i]},bv=({webmCodec:s,androidPreferredFormat:e,preferMultiStream:t})=>{let i=[...t?["DASH_STREAMS"]:[],...uo(s),"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]],r=[...t?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]];if(W.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",...uo(s),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...uo(s),"MPEG",...r,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...uo(s),...r,"HLS","HLS_ONDEMAND"];default:(0,sa.assertNever)(e)}return W.video.nativeHlsSupported?[...i,"HLS","HLS_ONDEMAND","MPEG"]:[...i,"HLS","HLS_ONDEMAND","MPEG"]},gv=({androidPreferredFormat:s,preferCMAF:e,preferWebRTC:t})=>{let i=e?["DASH_LIVE_CMAF","DASH_LIVE"]:["DASH_LIVE","DASH_LIVE_CMAF"],r=e?["HLS_LIVE_CMAF","HLS_LIVE"]:["HLS_LIVE","HLS_LIVE_CMAF"],a=[...i,...r],n=[...r,...i],o,u=W.device.isMac&&W.browser.isSafari;if(W.device.isAndroid)switch(s){case"dash":case"dash_any_mpeg":case"dash_any_webm":case"dash_sep":{o=a;break}case"hls":case"mpeg":{o=n;break}default:(0,sa.assertNever)(s)}else W.video.nativeHlsSupported&&!u?o=n:u?o=e?["DASH_LIVE_CMAF","HLS_LIVE_CMAF","HLS_LIVE","DASH_LIVE"]:["HLS_LIVE","DASH_LIVE","DASH_LIVE_CMAF","HLS_LIVE_CMAF"]:o=a;return t?["WEB_RTC_LIVE",...o]:[...o,"WEB_RTC_LIVE"]},bc=s=>s?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],co=s=>{if(s.size===0)return;if(s.size===1){let t=s.values().next();return(0,lo.default)(t.value.split("."),0)}for(let t of s){let i=(0,lo.default)(t.split("."),0);if(i==="opus"||i==="vp09"||i==="av01")return i}let e=s.values().next();return(0,lo.default)(e.value.split("."),0)};var VM=["timeupdate","progress","play","seeked","stalled","waiting"],OM=["timeupdate","progress","loadeddata","playing","seeked"];var po=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new y.Subscription;this.representationSubscription=new y.Subscription;this.state$=new ie("none");this.currentVideoRepresentation$=new y.ValueSubject(void 0);this.currentVideoRepresentationInit$=new y.ValueSubject(void 0);this.currentAudioRepresentation$=new y.ValueSubject(void 0);this.currentVideoSegmentLength$=new y.ValueSubject(0);this.currentAudioSegmentLength$=new y.ValueSubject(0);this.error$=new y.Subject;this.lastConnectionType$=new y.ValueSubject(void 0);this.lastConnectionReused$=new y.ValueSubject(void 0);this.lastRequestFirstBytes$=new y.ValueSubject(void 0);this.currentLiveTextRepresentation$=new y.ValueSubject(null);this.isLive$=new y.ValueSubject(!1);this.isActiveLive$=new y.ValueSubject(!1);this.isLowLatency$=new y.ValueSubject(!1);this.liveDuration$=new y.ValueSubject(0);this.liveSeekableDuration$=new y.ValueSubject(0);this.liveAvailabilityStartTime$=new y.ValueSubject(0);this.liveStreamStatus$=new y.ValueSubject(void 0);this.bufferLength$=new y.ValueSubject(0);this.liveLatency$=new y.ValueSubject(void 0);this.liveLoadBufferLength$=new y.ValueSubject(0);this.livePositionFromPlayer$=new y.ValueSubject(0);this.currentStallDuration$=new y.ValueSubject(0);this.videoLastDataObtainedTimestamp$=new y.ValueSubject(0);this.fetcherRecoverableError$=new y.Subject;this.fetcherError$=new y.Subject;this.liveStreamEndTimestamp=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.forceEnded$=new y.Subject;this.gapWatchdogActive=!1;this.destroyController=new de;this.initManifest=(0,y.abortable)(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=Le(t,i,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),this.manifest?.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:y.ErrorCategory.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=(0,y.abortable)(this.destroyController.signal,async function*(){this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(n=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:y.ErrorCategory.NETWORK,message:"Failed to load manifest",thrown:n})});if(!e)return null;let t=null;try{t=pv(e??"",this.manifestUrlString)}catch(n){let o=Kn(e)??{id:"ManifestParsing",category:y.ErrorCategory.PARSER,message:"Failed to parse MPD manifest",thrown:n};this.error$.next(o)}if(!t)return null;let i=(n,o,u)=>!!(this.element?.canPlayType?.(o)&&wt()?.isTypeSupported?.(`${o}; codecs="${u}"`)||n==="text");if(t.live){this.isLive$.next(!!t.live);let{availabilityStartTime:n,latestSegmentPublishTime:o,streamIsUnpublished:u,streamIsAlive:l}=t.live,d=(t.duration??0)/1e3;this.liveSeekableDuration$.next(-1*d),this.liveDuration$.next((o-n)/1e3),this.liveAvailabilityStartTime$.next(t.live.availabilityStartTime);let c="active";l||(c=u?"unpublished":"unexpectedly_down"),this.liveStreamStatus$.next(c)}let r={text:t.streams.text,video:[],audio:[]};for(let n of["video","audio"]){let u=t.streams[n].filter(({mime:c,codecs:p})=>i(n,c,p)),l=new Set(u.map(({codecs:c})=>c)),d=co(l);if(d&&(r[n]=u.filter(({codecs:c})=>c.startsWith(d))),n==="video"){let c=this.tuning.preferHDR,p=r.video.some(m=>m.hdr),h=r.video.some(m=>!m.hdr);W.display.isHDR&&c&&p?r.video=r.video.filter(m=>m.hdr):h&&(r.video=r.video.filter(m=>!m.hdr))}}let a={...t,streams:r};return this.tracer.log("updateManifestEnd",(0,y.flattenObject)(a)),a}.bind(this));this.initRepresentations=(0,y.abortable)(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initRepresentationsStart",(0,y.flattenObject)({initialVideo:e,initialAudio:t,sourceHls:i})),(0,y.assertNonNullable)(this.manifest),(0,y.assertNonNullable)(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let r=p=>{this.representationSubscription.add((0,y.fromEvent)(p,"error").pipe((0,y.filter)(h=>!!this.element?.played.length)).subscribe(h=>{this.error$.next({id:"VideoSource",category:y.ErrorCategory.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:h})}))};this.source=this.tuning.useManagedMediaSource?Cn():new MediaSource;let a=document.createElement("source");if(r(a),a.src=URL.createObjectURL(this.source),this.element.appendChild(a),this.tuning.useManagedMediaSource&&xr())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,h)=>[...p,...h.representations],[]);if(this.videoBufferManager=new ta("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],(0,y.isNonNullable)(t)){let p=this.manifest.streams.audio.reduce((h,m)=>[...h,...m.representations],[]);this.audioBufferManager=new ta("audio",this.source,p,n),this.bufferManagers.push(this.audioBufferManager)}ra.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new ra(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=()=>{this.stallWatchdogSubscription?.unsubscribe(),this.currentStallDuration$.next(0)};if(this.representationSubscription.add((0,y.merge)(...OM.map(p=>(0,y.fromEvent)(this.element,p))).pipe((0,y.map)(p=>this.element?ze(this.element.buffered,this.element.currentTime*1e3):0),(0,y.filterChanged)(),(0,y.tap)(p=>{p>this.tuning.dash.bufferEmptinessTolerance&&u()})).subscribe(this.bufferLength$)),this.representationSubscription.add((0,y.merge)((0,y.fromEvent)(this.element,"ended"),this.forceEnded$).subscribe(()=>{u()})),this.isLive$.getValue()){this.subscription.add(this.liveDuration$.pipe((0,y.filterChanged)()).subscribe(h=>this.liveStreamEndTimestamp=(0,y.now)())),this.subscription.add((0,y.fromEvent)(this.element,"pause").subscribe(()=>{this.livePauseWatchdogSubscription=(0,y.interval)(1e3).subscribe(h=>{let m=wi(this.manifestUrlString,2);this.manifestUrlString=Le(this.manifestUrlString,m+1e3,2),this.liveStreamStatus$.getValue()==="active"&&this.updateManifest()}),this.subscription.add(this.livePauseWatchdogSubscription)})).add((0,y.fromEvent)(this.element,"play").subscribe(h=>this.livePauseWatchdogSubscription?.unsubscribe())),this.representationSubscription.add((0,y.combine)({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe((0,y.map)(({isActiveLive:h,isLowLatency:m})=>h&&m),(0,y.filterChanged)()).subscribe(h=>{this.isManualDecreasePlaybackInLive()||Vr(this.element,1)})),this.representationSubscription.add((0,y.combine)({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe((0,y.filter)(({bufferLength:h,isActiveLive:m,isLowLatency:g})=>m&&g&&!!h)).subscribe(({bufferLength:h})=>this.liveBuffer.next(h))),this.representationSubscription.add(this.videoBufferManager.currentLowLatencySegmentLength$.subscribe(h=>{if(!this.isActiveLive$.getValue()&&!this.isLowLatency$.getValue()&&!h)return;let m=this.liveSeekableDuration$.getValue()-h/1e3;this.liveSeekableDuration$.next(Math.max(m,-1*this.tuning.dashCmafLive.maxLiveDuration)),this.liveDuration$.next(this.liveDuration$.getValue()+h/1e3)})),this.representationSubscription.add((0,y.combine)({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe((0,y.filter)(({isLive:h})=>h),(0,y.filterChanged)((h,m)=>m.bufferLength<h.bufferLength),(0,y.map)(({rtt:h,bufferLength:m,segmentServerLatency:g})=>{let v=wi(this.manifestUrlString,2);return(h/2+m+g+v)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add((0,y.combine)({liveBuffer:this.liveBuffer.smoothed$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).subscribe(({liveBuffer:h,isActiveLive:m,isLowLatency:g})=>{if(!g||!m)return;let v=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,T=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,w=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,x=h-v;if(this.isManualDecreasePlaybackInLive())return;let M=1;Math.abs(x)>T&&(M=1+Math.sign(x)*w),Vr(this.element,M)})),this.representationSubscription.add(this.bufferLength$.subscribe(h=>{let m=0;if(h){let g=(this.element?.currentTime??0)*1e3;m=Math.min(...this.bufferManagers.map(T=>T.getLiveSegmentsToLoadState(this.manifest)?.to??g))-g}this.liveLoadBufferLength$.getValue()!==m&&this.liveLoadBufferLength$.next(m)}));let p=0;this.representationSubscription.add((0,y.combine)({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe((0,y.throttle)(1e3)).subscribe(async({liveLoadBufferLength:h,bufferLength:m})=>{if(!this.element||this.isUpdatingLive)return;let g=this.element.playbackRate,v=wi(this.manifestUrlString,2),T=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,w=Math.min(T,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*g),x=this.tuning.dashCmafLive.normalizedActualBufferOffset*g,M=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*g,B=isFinite(h)?h:m,F=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),G=T<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next(G);let $="none";if(F?$="active_low_latency":this.isLowLatency$.getValue()&&G?(this.bufferManagers.forEach(D=>D.proceedLowLatencyLive()),$="active_low_latency"):v!==0&&B<w?$="live_forward_buffering":B<w+M&&($="live_with_target_offset"),isFinite(h)&&(p=h>p?h:p),$==="live_forward_buffering"||$==="live_with_target_offset"){let D=p-(w+x),I=this.normolizeLiveOffset(Math.trunc(v+D/g)),U=Math.abs(I-v),k=0;!h||U<=this.tuning.dashCmafLive.offsetCalculationError?k=v:I>0&&U>this.tuning.dashCmafLive.offsetCalculationError&&(k=I),this.manifestUrlString=Le(this.manifestUrlString,k,2)}($==="live_with_target_offset"||$==="live_forward_buffering")&&(p=0,await this.updateLive())},h=>{this.error$.next({id:"updateLive",category:y.ErrorCategory.VIDEO_PIPELINE,thrown:h,message:"Failed to update live with subscription"})}))}let l=(0,y.merge)(...this.bufferManagers.map(p=>p.fullyBuffered$)).pipe((0,y.map)(()=>this.bufferManagers.every(p=>p.fullyBuffered$.getValue()))),d=(0,y.merge)(...this.bufferManagers.map(p=>p.onLastSegment$)).pipe((0,y.map)(()=>this.bufferManagers.some(p=>p.onLastSegment$.getValue()))),c=(0,y.combine)({allBuffersFull:l,someBufferEnded:d}).pipe((0,y.filterChanged)(),(0,y.map)(({allBuffersFull:p,someBufferEnded:h})=>p&&h),(0,y.filter)(p=>p));if(this.representationSubscription.add((0,y.merge)(this.forceEnded$,c).subscribe(()=>{if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(p=>!p.updating))try{this.source?.endOfStream()}catch(p){this.error$.next({id:"EndOfStream",category:y.ErrorCategory.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:p})}})),this.representationSubscription.add((0,y.merge)(...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(h=>{p&&(this.timeoutSourceOpenId=setTimeout(()=>{if(this.source?.readyState==="open"){h();return}this.error$.next({id:"OpenOfStream",category:y.ErrorCategory.VIDEO_PIPELINE,message:"Failed to open MediaSource",thrown:new Error("Timeout reject when wait sourceopen event"),traceAsLog:!0})},this.tuning.dash.sourceOpenTimeout)),this.source?.addEventListener("sourceopen",()=>{this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),h()},{once:!0})})}if(!this.isLive$.getValue()){let p=[this.manifest.duration??0,...(0,Sc.default)((0,Sc.default)([...this.manifest.streams.audio,...this.manifest.streams.video],h=>h.representations),h=>{let m=[];return h.duration&&m.push(h.duration),rt(h.segmentReference)&&h.segmentReference.totalSegmentsDurationMs&&m.push(h.segmentReference.totalSegmentsDurationMs),m})];this.source.duration=Math.max(...p)/1e3}this.audioBufferManager&&(0,y.isNonNullable)(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=()=>{if(!this.element||!this.videoBufferManager||this.source?.readyState!=="open")return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),this.audioBufferManager?.maintain(e),this.liveTextManager?.maintain(e),(this.videoBufferManager.gaps.length||this.audioBufferManager?.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=(0,y.interval)(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),t=>{this.error$.next({id:"GapWatchdog",category:y.ErrorCategory.WTF,message:"Error handling gaps",thrown:t})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name),this.fetcher=new ro({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=bi.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.bufferEstimator}),this.initTracerSubscription()}async seekLive(e){(0,y.assertNonNullable)(this.element);let t=this.liveStreamStatus$.getValue()!=="active"?(0,y.now)()-this.liveStreamEndTimestamp:0,i=this.normolizeLiveOffset(e+t);this.isActiveLive$.next(i===0),this.manifestUrlString=Le(this.manifestUrlString,i,2),this.manifest=await this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,await this.videoBufferManager?.seekLive(this.manifest.streams.video),await this.audioBufferManager?.seekLive(this.manifest.streams.audio),this.liveTextManager?.seekLive(this.manifest.streams.text))}initBuffer(){(0,y.assertNonNullable)(this.element),this.state$.setState("running"),this.subscription.add((0,y.merge)(...VM.map(e=>(0,y.fromEvent)(this.element,e)),(0,y.fromEvent)(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:y.ErrorCategory.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add((0,y.fromEvent)(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add((0,y.fromEvent)(this.element,"waiting").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&Ye(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{if(!this.element||this.source?.readyState!=="open")return;let t=this.currentStallDuration$.getValue();t+=50,this.currentStallDuration$.next(t);let i={timeInWaiting:t},r=(0,y.now)(),a=100,n=this.videoBufferManager?.lastDataObtainedTimestamp??0;this.videoLastDataObtainedTimestamp$.next(n);let o=this.audioBufferManager?.lastDataObtainedTimestamp??0,u=this.videoBufferManager?.getForwardBufferDuration()??0,l=this.audioBufferManager?.getForwardBufferDuration()??0,d=u<a&&r-n>this.tuning.dash.crashOnStallTWithoutDataTimeout,c=this.audioBufferManager&&l<a&&r-o>this.tuning.dash.crashOnStallTWithoutDataTimeout;if((d||c)&&t>this.tuning.dash.crashOnStallTWithoutDataTimeout||t>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${t} ms`);if(this.isLive$.getValue()&&t%2e3===0){let p=this.normolizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);this.seekLive(p).catch(h=>{this.error$.next({id:"stallIntervalCallback",category:y.ErrorCategory.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:h})}),i.liveLastOffset=p}else{let p=this.element.currentTime*1e3;this.videoBufferManager?.maintain(p),this.audioBufferManager?.maintain(p),i.position=p}this.tracer.log("stallIntervalCallback",(0,y.flattenObject)(i))};this.stallWatchdogSubscription?.unsubscribe(),this.stallWatchdogSubscription=(0,y.interval)(50).subscribe(e,t=>{this.error$.next({id:"StallWatchdogCallback",category:y.ErrorCategory.NETWORK,message:"Can't restore DASH after stall.",thrown:t})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t,i=!1){let r={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return this.tuning.useNewSwitchTo?this.currentStallDuration$.getValue()>0?r?.switchToWithPreviousAbort(t,i):r?.switchTo(t,i):r?.switchToOld(t,i)}async seek(e,t){(0,y.assertNonNullable)(this.element),(0,y.assertNonNullable)(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(this.videoBufferManager.findSegmentStartTime(e)??e,this.audioBufferManager?.findSegmentStartTime(e)??e),this.warmUpMediaSourceIfNeeded(i),Ye(this.element.buffered,i)||await Promise.all([this.videoBufferManager.abort(),this.audioBufferManager?.abort()]),!((0,y.isNullable)(this.element)||(0,y.isNullable)(this.videoBufferManager))&&(this.videoBufferManager.maintain(i),this.audioBufferManager?.maintain(i),this.element.currentTime=i/1e3,this.tracer.log("seek",(0,y.flattenObject)({requestedPosition:e,forcePrecise:t,position:i})))}warmUpMediaSourceIfNeeded(e=this.element?.currentTime){(0,y.isNonNullable)(this.element)&&(0,y.isNonNullable)(this.source)&&(0,y.isNonNullable)(e)&&this.source?.readyState==="ended"&&this.element.duration*1e3-e>this.tuning.dash.seekBiasInTheEnd&&this.bufferManagers.forEach(t=>t.warmUpMediaSource())}get isStreamEnded(){return this.source?.readyState==="ended"}stop(){this.tracer.log("stop"),this.element?.querySelectorAll("source").forEach(e=>{URL.revokeObjectURL(e.src),e.remove()}),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),this.videoBufferManager?.destroy(),this.videoBufferManager=null,this.audioBufferManager?.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getStreams(){return this.manifest?.streams}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),this.source?.readyState==="open"&&Array.from(this.source.sourceBuffers).every(e=>!e.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}initTracerSubscription(){let e=(0,y.getTraceSubscriptionMethod)(this.tracer.error.bind(this.tracer));this.subscription.add(this.error$.subscribe(e("error")))}isManualDecreasePlaybackInLive(){if(!this.element||!this.isLive$.getValue())return!1;let e=1-this.element.playbackRate;return Number(e.toFixed(2))>Number(this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup.toFixed(2))}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}async updateLive(){this.isUpdatingLive=!0,this.manifest=await this.updateManifest(),this.manifest&&(this.bufferManagers?.forEach(e=>e.updateLive(this.manifest)),this.liveTextManager?.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,a=[],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?a.push(1/0):a.push(u.to));if(a.length){let o=Math.max(...a)+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,o===1/0?this.forceEnded$.next():(this.element.currentTime=o/1e3,i={...i,gapEnds:a,jumpTo:o,resultCurrentTime:this.element.currentTime},this.tracer.log("jumpGap",(0,y.flattenObject)(i)))}}};var ho=class{constructor(e,t){this.fov=e,this.orientation=t}};var fo=class{constructor(e,t){this.rotating=!1;this.fading=!1;this.lastTickTS=0;this.lastCameraTurnTS=0;this.fadeStartSpeed=null;this.fadeTime=0;this.camera=e,this.options=t,this.rotationSpeed={x:0,y:0,z:0},this.fadeCorrection=1/(this.options.speedFadeTime/1e3)**2}turnCamera(e=0,t=0,i=0){this.pointCameraTo(this.camera.orientation.x+e,this.camera.orientation.y+t,this.camera.orientation.z+i)}pointCameraTo(e=0,t=0,i=0){t=this.limitCameraRotationY(t);let r=e-this.camera.orientation.x,a=t-this.camera.orientation.y,n=i-this.camera.orientation.z;this.camera.orientation.x=e,this.camera.orientation.y=t,this.camera.orientation.z=i,this.lastCameraTurn={x:r,y:a,z:n},this.lastCameraTurnTS=Date.now()}setRotationSpeed(e,t,i){this.rotationSpeed.x=e??this.rotationSpeed.x,this.rotationSpeed.y=t??this.rotationSpeed.y,this.rotationSpeed.z=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={...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*(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 yv=`attribute vec2 a_vertex;
|
|
125
125
|
attribute vec2 a_texel;
|
|
126
126
|
|
|
127
127
|
varying vec2 v_texel;
|
|
@@ -175,13 +175,13 @@ void main(void) {
|
|
|
175
175
|
// sample using new coordinates
|
|
176
176
|
gl_FragColor = texture2D(u_texture, tc);
|
|
177
177
|
}
|
|
178
|
-
`;var Or=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 ho(this.params.fov,this.params.orientation),this.cameraRotationManager=new fo(this.camera,{rotationSpeed:this.params.rotationSpeed,maxYawAngle:this.params.maxYawAngle,rotationSpeedCorrection:this.params.rotationSpeedCorrection,degreeToPixelCorrection:this.params.degreeToPixelCorrection,speedFadeTime:this.params.speedFadeTime,speedFadeThreshold:this.params.speedFadeThreshold}),this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.textureMappingBuffer=this.createTextureMappingBuffer(),this.updateTextureMappingBuffer(),this.program=this.createProgram(),this.videoTexture=this.createTexture(),this.gl.useProgram(this.program),this.videoElementDataLoadedFn=this.onDataLoadedHandler.bind(this),this.renderFn=this.render.bind(this)}play(){this.active||(this.videoInitialized?this.doPlay():this.sourceVideoElement.readyState>=2?(this.videoInitialized=!0,this.doPlay()):this.sourceVideoElement.addEventListener("loadeddata",this.videoElementDataLoadedFn))}stop(){this.active=!1}startCameraManualRotation(e,t){this.cameraRotationManager.setRotationSpeed(e*this.params.rotationSpeed,t*this.params.rotationSpeed,0),this.cameraRotationManager.startRotation()}stopCameraManualRotation(e=!1){this.cameraRotationManager.stopRotation(e)}turnCamera(e,t){this.cameraRotationManager.turnCamera(e,t)}pointCameraTo(e,t){this.cameraRotationManager.pointCameraTo(e,t)}pixelToDegree(e){return{x:this.params.degreeToPixelCorrection*this.params.fov.x*-e.x/this.viewportWidth,y:this.params.degreeToPixelCorrection*this.params.fov.y*e.y/this.viewportHeight}}getCameraRotation(){return this.camera.orientation}holdCamera(){this.cameraRotationManager.stopRotation(!0)}releaseCamera(){this.cameraRotationManager.onCameraRelease()}destroy(){this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),this.stop(),this.canvas.remove()}setViewportSize(e,t){this.viewportWidth=e,this.viewportHeight=t,this.canvas.width=this.viewportWidth,this.canvas.height=this.viewportHeight,this.gl.viewport(0,0,this.canvas.width,this.canvas.height)}onDataLoadedHandler(){this.videoInitialized=!0,this.doPlay()}doPlay(){this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.active=!0,this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),requestAnimationFrame(this.renderFn)}render(e){this.cameraRotationManager.tick(e),this.updateTexture(),this.updateTextureMappingBuffer();let t=this.gl.getAttribLocation(this.program,"a_vertex"),i=this.gl.getAttribLocation(this.program,"a_texel"),r=this.gl.getUniformLocation(this.program,"u_texture"),a=this.gl.getUniformLocation(this.program,"u_focus");this.gl.enableVertexAttribArray(t),this.gl.enableVertexAttribArray(i),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.vertexBuffer),this.gl.vertexAttribPointer(t,2,this.gl.FLOAT,!1,0,0),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.vertexAttribPointer(i,2,this.gl.FLOAT,!1,0,0),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.uniform1i(r,0),this.gl.uniform2f(a,-this.camera.orientation.x,-this.camera.orientation.y),this.gl.drawArrays(this.gl.TRIANGLE_FAN,0,4),this.gl.bindTexture(this.gl.TEXTURE_2D,null),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),this.gl.disableVertexAttribArray(t),this.gl.disableVertexAttribArray(i),this.active&&requestAnimationFrame(this.renderFn)}createShader(e,t){let i=this.gl.createShader(t);if(!i)throw this.destroy(),new Error(`Could not create shader (${t})`);if(this.gl.shaderSource(i,e),this.gl.compileShader(i),!this.gl.getShaderParameter(i,this.gl.COMPILE_STATUS))throw this.destroy(),new Error("An error occurred while compiling the shader: "+this.gl.getShaderInfoLog(i));return i}createProgram(){let e=this.gl.createProgram();if(!e)throw this.destroy(),new Error("Could not create shader program");let t=this.createShader(yv,this.gl.VERTEX_SHADER),i=this.createShader(Tv,this.gl.FRAGMENT_SHADER);if(this.gl.attachShader(e,t),this.gl.attachShader(e,i),this.gl.linkProgram(e),!this.gl.getProgramParameter(e,this.gl.LINK_STATUS))throw this.destroy(),new Error("Could not link shader program.");return e}createTexture(){let e=this.gl.createTexture();if(!e)throw this.destroy(),new Error("Could not create texture");return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.bindTexture(this.gl.TEXTURE_2D,null),e}updateTexture(){this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,!0),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.sourceVideoElement),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}createVertexBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create vertex buffer");let t=1,i=1,r=this.frameHeight/(this.frameWidth/this.viewportWidth);return r>this.viewportHeight?t=this.viewportHeight/r:i=r/this.viewportHeight,this.gl.bindBuffer(this.gl.ARRAY_BUFFER,e),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-t,-i,t,-i,t,i,-t,i]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),e}createTextureMappingBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create texture mapping buffer");return e}calculateTexturePosition(){let e=.5-this.camera.orientation.x/360,t=.5-this.camera.orientation.y/180,i=this.camera.fov.x/360/2,r=this.camera.fov.y/180/2,a=e-i,n=t-r,o=e+i,u=t-r,l=e+i,p=t+r,c=e-i,d=t+r;return[a,n,o,u,l,p,c,d]}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}};var Se=require("@vkontakte/videoplayer-shared");var mo="stalls_manager_metrics",vc="stalls_manager_abr_params",Iv="stalls_manager_default_tuning_abr_params",yc=class{constructor(){this.isSeeked$=new Se.ValueSubject(!1);this.isBuffering$=new Se.ValueSubject(!1);this.maxQualityLimit=void 0;this.currentStallsCount=0;this.sumStallsDuration=0;this.lastStallDuration=0;this.providerStartWatchingTimestamp=0;this.lastUniqueVideoTrackSelectedTimestamp=0;this.predictedThroughputWithoutData=0;this.subscription=new Se.Subscription;this.severeStallOccurred$=new Se.ValueSubject(!1)}init(e){this.currentStallDuration$=e.currentStallDuration$,this.videoLastDataObtainedTimestamp$=e.videoLastDataObtainedTimestamp$,this.throughput$=e.throughput$,this.rtt$=e.rtt$,this.tuning=e.tuning,this.abrParams=e.abrParams,this.resetStoredAbrParamsIfNeeded(),this.subscribe(e)}get videoMaxQualityLimit(){return this.maxQualityLimit}get predictedThroughput(){return this.predictedThroughputWithoutData}get abrTuningParams(){let e=this.tuning.enabled?this.getStoredData(vc):{};return{...this.abrParams,...e}}set lastVideoTrackSelected(e){this.lastUniqueVideoTrackSelected?.id!==e.id&&(this.lastUniqueVideoTrackSelected=e,this.lastUniqueVideoTrackSelectedTimestamp=(0,Se.now)(),this.currentStallsCount=0)}destroy(){window.clearTimeout(this.qualityRestrictionTimer),this.subscription.unsubscribe(),this.currentStallDuration$.getValue()!==0&&this.updateStallData();let e=((0,Se.now)()-this.providerStartWatchingTimestamp-this.sumStallsDuration)/1e3,t=this.sumStallsDuration;this.addStallInfoToHistory(e,t),this.updateStoredAbrParams()}resetStoredAbrParamsIfNeeded(){let{bitrateFactorAtEmptyBuffer:e,bitrateFactorAtFullBuffer:t,containerSizeFactor:i}={...this.getStoredData(Iv)},{bitrateFactorAtEmptyBuffer:r,bitrateFactorAtFullBuffer:a,containerSizeFactor:n}={...this.abrParams};this.tuning.enabled&&e===r&&t===a&&i===n||(this.removeStoredData(vc),this.setStoredData(Iv,{bitrateFactorAtEmptyBuffer:r,bitrateFactorAtFullBuffer:a,containerSizeFactor:n}))}updateStoredAbrParams(){let e=[],t=this.getStoredData(mo,"[]");if(!this.tuning.enabled||t.length<this.tuning.stallsMetricsHistoryLength)return;let i=t.reduce((a,n)=>a+n.tvt,0);if(this.tuning.useTotalStallsDurationPerTvt){let n=t.reduce((o,u)=>o+u.stallsDuration,0)/i;e.push(this.calculateOptimalAbrParams(n,i))}if(this.tuning.useAverageStallsDurationPerTvt){let a=t.reduce((n,o)=>n+o.stallsDurationPerTvt,0)/t.length;e.push(this.calculateOptimalAbrParams(a,i))}this.tuning.useEmaStallsDurationPerTvt&&e.push(this.calculateOptimalAbrParams(t[t.length-1].stallsDurationPerTvtSmoothed,i));let r={bitrateFactorAtEmptyBuffer:Math.max(...e.map(a=>a.bitrateFactorAtEmptyBuffer)),bitrateFactorAtFullBuffer:Math.max(...e.map(a=>a.bitrateFactorAtFullBuffer)),containerSizeFactor:Math.min(...e.map(a=>a.containerSizeFactor))};this.setStoredData(mo,[]),this.setStoredData(vc,r)}calculateOptimalAbrParams(e,t){let{targetStallsDurationPerTvt:i,deviationStallsDurationPerTvt:r,criticalStallsDurationPerTvt:a,abrAdjustingSpeed:n,significantTvt:o,stallsMetricsHistoryLength:u}=this.tuning,l=n*Math.min(t/(o*u),1),p=this.abrTuningParams;return e<i-r?p={bitrateFactorAtEmptyBuffer:Math.max(p.bitrateFactorAtEmptyBuffer-l,this.abrParams.minBitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.max(p.bitrateFactorAtFullBuffer-l,this.abrParams.minBitrateFactorAtFullBuffer),containerSizeFactor:Math.min(p.containerSizeFactor+l,this.abrParams.maxContainerSizeFactor)}:e>i+r&&(p={bitrateFactorAtEmptyBuffer:Math.min(p.bitrateFactorAtEmptyBuffer+l,this.abrParams.maxBitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.min(p.bitrateFactorAtFullBuffer+l,this.abrParams.maxBitrateFactorAtFullBuffer),containerSizeFactor:Math.max(p.containerSizeFactor-l,this.abrParams.minContainerSizeFactor)}),e>a&&(p={bitrateFactorAtEmptyBuffer:Math.max(p.bitrateFactorAtEmptyBuffer,this.abrParams.bitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.max(p.bitrateFactorAtFullBuffer,this.abrParams.bitrateFactorAtFullBuffer),containerSizeFactor:Math.min(p.containerSizeFactor,this.abrParams.containerSizeFactor)}),p}getStoredData(e,t="{}"){return JSON.parse(Se.safeStorage.get(e)??t)}setStoredData(e,t){Se.safeStorage.set(e,JSON.stringify(t))}removeStoredData(e){Se.safeStorage.remove(e)}addStallInfoToHistory(e,t){if(e<this.tuning.minTvtToBeCounted||e>this.tuning.maxTvtToBeCounted||e*1e3<t)return;let i=this.getStoredData(mo,"[]"),r=t/e,a=i.length?mi(i[i.length-1].stallsDurationPerTvtSmoothed,t/e,this.tuning.emaAlpha):r,n={tvt:e,stallsDuration:t,stallsDurationPerTvt:r,stallsDurationPerTvtSmoothed:a};i.push(n),i.length>this.tuning.stallsMetricsHistoryLength&&i.shift(),this.setStoredData(mo,i)}updateStallData(){this.providerStartWatchingTimestamp&&!this.isSeeked$.getValue()&&(this.sumStallsDuration+=Math.min(this.lastStallDuration,this.tuning.maxPossibleStallDuration),this.currentStallsCount++)}subscribe(e){this.subscription.add(e.isSeeked$.subscribe(this.isSeeked$)),this.subscription.add(e.isBuffering$.subscribe(this.isBuffering$)),this.subscription.add(e.looped$.subscribe(t=>this.currentStallsCount=0)),this.subscription.add(e.playing$.pipe((0,Se.once)()).subscribe(t=>this.providerStartWatchingTimestamp=(0,Se.now)())),this.subscription.add(this.currentStallDuration$.pipe((0,Se.filterChanged)()).subscribe(t=>{let{stallDurationNoDataBeforeQualityDecrease:i,stallCountBeforeQualityDecrease:r,resetQualityRestrictionTimeout:a,ignoreStallsOnSeek:n}=this.tuning;if((0,Se.isNullable)(this.lastUniqueVideoTrackSelected)||n&&this.isSeeked$.getValue())return;let o=this.rtt$.getValue(),u=this.throughput$.getValue(),l=this.videoLastDataObtainedTimestamp$.getValue(),p=(0,Se.now)(),c=r&&this.currentStallsCount>=r,d=i&&p-this.lastUniqueVideoTrackSelectedTimestamp>=i+o&&p-l>=i+o&&t>=i;(c||d)&&(this.severeStallOccurred$.next(!0),window.clearTimeout(this.qualityRestrictionTimer),this.maxQualityLimit=this.lastUniqueVideoTrackSelected.quality,(0,Se.isNonNullable)(this.lastUniqueVideoTrackSelected.bitrate)&&u>this.lastUniqueVideoTrackSelected.bitrate&&(this.predictedThroughputWithoutData=this.lastUniqueVideoTrackSelected.bitrate)),!t&&(0,Se.now)()-this.providerStartWatchingTimestamp>this.lastStallDuration&&(this.updateStallData(),this.severeStallOccurred$.next(!1),window.clearTimeout(this.qualityRestrictionTimer),this.qualityRestrictionTimer=window.setTimeout(()=>{this.maxQualityLimit=void 0,this.predictedThroughputWithoutData=0},a)),this.lastStallDuration=t}))}},bo=yc;var ct=require("@vkontakte/videoplayer-shared"),go=class{constructor(){this.subscription=new ct.Subscription;this.pipSize$=new ct.ValueSubject(void 0);this.videoSize$=new ct.ValueSubject(void 0);this.elementSize$=new ct.ValueSubject(void 0);this.pictureInPictureWindowRemoveEventListener=ct.noop}connect({observableVideo:e,video:t}){let i=r=>{let a=r.target;this.pipSize$.next({width:a.width,height:a.height})};this.subscription.add((0,ct.observeElementSize)(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((0,ct.combine)({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe((0,ct.map)(({videoSize:r,inPip:a,pipSize:n})=>a?n:r)).subscribe(this.elementSize$))}getValue(){return this.elementSize$.getValue()}subscribe(e,t){return this.elementSize$.subscribe(e,t)}getObservable(){return this.elementSize$}destroy(){this.pictureInPictureWindowRemoveEventListener(),this.subscription.unsubscribe()}};var Ji=class{constructor(e){this.subscription=new Z.Subscription;this.videoState=new ie("stopped");this.droppedFramesManager=new Ar;this.stallsManager=new bo;this.elementSizeManager=new go;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new ki;this.audioTrackSwitchHistory=new ki;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?.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"),_(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"),_(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="ready"&&_(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?.to==="playing"&&_(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&_(this.params.desiredState.playbackState,"paused");return;default:return(0,Z.assertNever)(e)}}};this.init3DScene=e=>{if(this.scene3D)return;this.scene3D=new Or(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:e.projectionData?.pose.yaw||0,y:e.projectionData?.pose.pitch||0,z:e.projectionData?.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 Rt(e.source.url),this.params=e,this.video=at(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(We(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 po({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=ut(this.video);this.subscription.add(()=>i.destroy());let r=this.constructor.name,a=o=>{e.error$.next({id:r,category:Z.ErrorCategory.WTF,message:`${r} internal logic error`,thrown:o})};return{output:e,desiredState:t,observableVideo:i,genericErrorListener:a,connect:(o,u)=>this.subscription.add(o.subscribe(u,a))}}subscribe(){let{output:e,desiredState:t,observableVideo:i,genericErrorListener:r,connect:a}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe((0,Z.filter)(l=>!!l.length),(0,Z.once)()).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((0,Z.map)(l=>l.to.state!=="none"),(0,Z.filterChanged)());this.stallsManager.init({isSeeked$:n,currentStallDuration$:this.player.currentStallDuration$,videoLastDataObtainedTimestamp$:this.player.videoLastDataObtainedTimestamp$,throughput$:this.params.dependencies.throughputEstimator.throughput$,rtt$:this.params.dependencies.throughputEstimator.rtt$,tuning:this.params.tuning.stallsManager,abrParams:this.params.tuning.autoTrackSelection,isBuffering$:i.isBuffering$,looped$:i.looped$,playing$:i.playing$}),a(i.ended$,e.endedEvent$),a(i.looped$,e.loopedEvent$),a(i.error$,e.error$),a(i.isBuffering$,e.isBuffering$),a(i.currentBuffer$,e.currentBuffer$),a(i.playing$,e.firstFrameEvent$),a(i.canplay$,e.canplay$),a(i.inPiP$,e.inPiP$),a(i.inFullscreen$,e.inFullscreen$),a(i.loadedMetadata$,e.loadedMetadataEvent$),a(this.player.error$,e.error$),a(this.player.fetcherRecoverableError$,e.fetcherRecoverableError$),a(this.player.fetcherError$,e.fetcherError$),a(this.player.lastConnectionType$,e.httpConnectionType$),a(this.player.lastConnectionReused$,e.httpConnectionReused$),a(this.player.isLive$,e.isLive$),a(this.player.lastRequestFirstBytes$.pipe((0,Z.filter)(Z.isNonNullable),(0,Z.once)()),e.firstBytesEvent$),a(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),a(this.videoState.stateChangeEnded$.pipe((0,Z.map)(l=>l.to)),this.params.output.playbackState$),this.subscription.add(i.looped$.subscribe(()=>this.player.warmUpMediaSourceIfNeeded(),r)),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(Wt(this.video,t.isLooped,r)),this.subscription.add(ot(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(kt(this.video,t.playbackRate,i.playbackRateState$,r)),this.elementSizeManager.connect({video:this.video,observableVideo:i}),a(Mt(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),_(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),_(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 p=this.player.getStreams();if((0,Z.assertNonNullable)(p,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let d=[];for(let h of p.audio){d.push(uc(h));let m=[];for(let g of h.representations){let v=av(g);m.push(v),this.audioTracksMap.set(v,{stream:h,representation:g})}this.audioStreamsMap.set(h,m)}this.params.output.availableAudioStreams$.next(d)}let c=[];for(let d of p.video){c.push(lc(d));let h=[];for(let m of d.representations){let g=sv({...m,streamId:d.id});g&&(h.push(g),this.videoTracksMap.set(g,{stream:d,representation:m}))}this.videoStreamsMap.set(d,h)}this.params.output.availableVideoStreams$.next(c);for(let d of p.text)for(let h of d.representations){let m=nv(d,h);this.textTracksMap.set(m,{stream:d,representation:h})}this.params.output.availableVideoTracks$.next(Array.from(this.videoTracksMap.keys())),this.params.output.availableAudioTracks$.next(Array.from(this.audioTracksMap.keys())),this.params.output.isAudioAvailable$.next(!!this.audioTracksMap.size),this.audioTracksMap.size&&this.textTracksMap.size&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else l==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},r)),this.subscription.add((0,Z.merge)(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$,(0,Z.fromEvent)(this.video,"progress")).pipe((0,Z.filter)(()=>this.videoTracksMap.size>0)).subscribe(async()=>{let l=this.player.state$.getState(),p=this.player.state$.getTransition();if(!(0,xv.default)(["manifest_ready","running"],l)||p)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let c=this.selectVideoAudioRepresentations();if(!c)return;let[d,h]=c,m=[...this.videoTracksMap.keys()].find(v=>this.videoTracksMap.get(v)?.representation.id===d.id);(0,Z.isNonNullable)(m)&&(this.stallsManager.lastVideoTrackSelected=m);let g=this.params.desiredState.autoVideoTrackLimits.getTransition();if(g&&this.params.output.autoVideoTrackLimits$.next(g.to),l==="manifest_ready")await this.player.initRepresentations(d.id,h?.id,this.params.sourceHls);else if(await this.player.switchRepresentation("video",d.id),h){let v=!!t.audioStream.getTransition();await this.player.switchRepresentation("audio",h.id,v)}},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((0,Z.filterChanged)()).subscribe(l=>{let p=[...this.videoTracksMap.entries()].find(([,{representation:m}])=>m.id===l);if(!p){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[c,{stream:d}]=p,h=this.params.desiredState.videoStream.getTransition();h&&h.to&&h.to.id===d.id&&this.params.desiredState.videoStream.setState(h.to),e.currentVideoTrack$.next(c),e.currentVideoStream$.next(lc(d))},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe((0,Z.filterChanged)()).subscribe(l=>{let p=[...this.audioTracksMap.entries()].find(([,{representation:m}])=>m.id===l);if(!p){e.currentAudioStream$.next(void 0);return}let[c,{stream:d}]=p,h=this.params.desiredState.audioStream.getTransition();h&&h.to&&h.to.id===d.id&&this.params.desiredState.audioStream.setState(h.to),e.currentAudioStream$.next(uc(d))},r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(l=>{if(l?.is3dVideo&&this.params.tuning.spherical?.enabled)try{this.init3DScene(l),e.is3DVideo$.next(!0)}catch(p){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${p}`})}else this.destroy3DScene(),this.params.tuning.spherical?.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((0,Z.map)(({to:l})=>l==="ready"),(0,Z.filterChanged)());this.subscription.add((0,Z.merge)(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,(0,Z.observableFrom)(["init"])).subscribe(()=>{let l=t.autoVideoTrackSwitching.getState(),c=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:l?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(c)})),this.subscription.add((0,Z.merge)(o,this.player.state$.stateChangeEnded$,(0,Z.observableFrom)(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let u=(0,Z.merge)(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,Z.observableFrom)(["init"])).pipe((0,Z.debounce)(0));this.subscription.add(u.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?gs:bs,t=this.params.tuning.useNewAutoSelectVideoTrack?zn:jn,i=this.params.tuning.useNewAutoSelectVideoTrack?Yt:Hn,{desiredState:r,output:a}=this.params,n=r.autoVideoTrackSwitching.getState(),o=r.videoTrack.getState()?.id,l=[...this.videoTracksMap.keys()].find(({id:I})=>I===o),p=a.currentVideoTrack$.getValue(),c=r.videoStream.getState()??(l&&this.videoTracksMap.get(l)?.stream)??this.videoStreamsMap.size===1?this.videoStreamsMap.keys().next().value:void 0;if(!c)return;let d=[...this.videoStreamsMap.keys()].find(({id:I})=>I===c.id),h=d&&this.videoStreamsMap.get(d);if(!h)return;let m=ze(this.video.buffered,this.video.currentTime*1e3),g;this.player.isActiveLive$.getValue()?g=this.player.isLowLatency$.getValue()?this.params.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.params.tuning.dashCmafLive.normalizedLiveMinBufferSize:this.player.isLive$.getValue()?g=this.params.tuning.dashCmafLive.normalizedTargetMinBufferSize:g=n?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;let v=(this.video.duration*1e3||1/0)-this.video.currentTime*1e3,T=Math.min(m/Math.min(g,v||1/0),1),P=r.audioStream.getState()??(this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0),x=[...this.audioStreamsMap.keys()].find(({id:I})=>I===P?.id)??this.audioStreamsMap.keys().next().value,L=0;if(x){if(l&&!n){let I=e(l,h,this.audioStreamsMap.get(x)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);L=Math.max(L,I?.bitrate??-1/0)}if(p){let I=e(p,h,this.audioStreamsMap.get(x)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);L=Math.max(L,I?.bitrate??-1/0)}}let B=i(h,{container:this.elementSizeManager.getValue(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.stallsManager.abrTuningParams,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:L,forwardBufferHealth:T,current:p,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}),F=n?B??l:l??B,G=x&&t(F,h,this.audioStreamsMap.get(x)??[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.stallsManager.abrTuningParams,forwardBufferHealth:T,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),$=this.videoTracksMap.get(F)?.representation,D=G&&this.audioTracksMap.get(G)?.representation;if($&&D)return[$,D];if($&&!D&&this.audioTracksMap.size===0)return[$,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){lt(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),_(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Z.ErrorCategory.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),nt(this.video),this.tracer.end()}};var aa=class extends Ji{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)}};var fe=require("@vkontakte/videoplayer-shared");var na=class extends Ji{constructor(e){super(e),this.textTracksManager.destroy()}subscribe(){super.subscribe();let e=-1,{output:t,observableVideo:i,desiredState:r,connect:a}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),a(i.timeUpdate$,t.liveBufferTime$),a(this.player.liveSeekableDuration$,t.duration$),a(this.player.liveLatency$,t.liveLatency$);let n=new fe.ValueSubject(1);a(i.playbackRateState$,n),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(r.isLowLatency.stateChangeEnded$.pipe((0,fe.map)(o=>o.to)).subscribe(this.player.isLowLatency$)).add((0,fe.combine)({liveBufferTime:t.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe((0,fe.map)(({liveBufferTime:o,liveAvailabilityStartTime:u})=>o&&u?o+u:void 0)).subscribe(t.liveTime$)).add(this.player.liveStreamStatus$.pipe((0,fe.filter)(o=>(0,fe.isNonNullable)(o))).subscribe(o=>t.isLiveEnded$.next(o!=="active"&&t.position$.getValue()===0))).add((0,fe.combine)({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:(0,fe.merge)(i.playbackRateState$,new fe.ValueSubject(1))}).pipe((0,fe.filter)(({liveStreamStatus:o,liveDuration:u})=>o==="active"&&!!u)).subscribe(({liveDuration:o,playbackRate:u})=>{let l=t.liveBufferTime$.getValue(),p=t.position$.getValue(),{playbackCatchupSpeedup:c}=this.params.tuning.dashCmafLive.lowLatency;p||u<1-c||this.video.paused||(0,fe.isNullable)(l)||(e=o-l)})).add((0,fe.combine)({time:t.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:(0,fe.merge)(i.playbackRateState$,new fe.ValueSubject(1))}).pipe((0,fe.filterChanged)((o,u)=>this.player.liveStreamStatus$.getValue()==="active"?o.liveDuration===u.liveDuration:o.time===u.time)).subscribe(({time:o,liveDuration:u,playbackRate:l})=>{let p=t.position$.getValue(),{playbackCatchupSpeedup:c}=this.params.tuning.dashCmafLive.lowLatency;if(!p&&!this.video.paused&&l>=1-c||(0,fe.isNullable)(o)||(0,fe.isNullable)(u))return;let d=-1*(u-o-e);t.position$.next(Math.min(d,0))})).add(this.player.currentLiveTextRepresentation$.subscribe(o=>{if(o){let u=ov(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 ee=require("@vkontakte/videoplayer-shared");var Bc=j(ws(),1);var S=require("@vkontakte/videoplayer-shared");var Io=j(xt(),1),Fr=j(Ut(),1),xo=j(ws(),1);var zv=j(Rn(),1);var $i=require("@vkontakte/videoplayer-shared");var UM=18,Ev=!1;try{Ev=W.browser.isSafari&&!!W.browser.safariVersion&&W.browser.safariVersion<=UM}catch(s){console.error(s)}var Tc=class{constructor(e){this.bufferFull$=new $i.Subject;this.error$=new $i.Subject;this.queue=[];this.currentTask=null;this.destroyed=!1;this.abortRequested=!1;this.completeTask=()=>{try{if(this.currentTask){let e=this.currentTask.signal?.aborted;this.currentTask.callback(!e),this.currentTask=null}this.queue.length&&this.pull()}catch(e){this.error$.next({id:"BufferTaskQueueUnknown",category:$i.ErrorCategory.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:e})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(i=>{let r={operation:"append",data:e,signal:t,callback:i};this.queue.push(r),this.pull()})}async remove(e,t,i){return i&&i.aborted?!1:new Promise(r=>{let a={operation:"remove",from:e,to:t,signal:i,callback:r};this.queue.unshift(a),this.pull()})}async abort(e){return new Promise(t=>{let i,r=a=>{this.abortRequested=!1,t(a)};Ev&&e?i={operation:"safariAbort",init:e,callback:r}:i={operation:"abort",callback:r};for(let{callback:a}of this.queue)a(!1);this.abortRequested=!0,i&&(this.queue=[i]),this.pull()})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){if((this.buffer.updating||this.currentTask||this.destroyed)&&!this.abortRequested)return;let e=this.queue.shift();if(!e)return;if(e.signal?.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(r){r instanceof DOMException&&r.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):r instanceof DOMException&&r.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:$i.ErrorCategory.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:r}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){let{operation:t}=e;switch(t){case"append":this.buffer.appendBuffer(e.data);break;case"remove":this.buffer.remove(e.from/1e3,e.to/1e3);break;case"abort":this.buffer.abort();break;case"safariAbort":{this.buffer.abort(),this.buffer.appendBuffer(e.init);break}default:(0,$i.assertNever)(t)}}},wv=Tc;var A=require("@vkontakte/videoplayer-shared");var ne=class{constructor(e,t){this.cursor=0;this.source=e,this.boxParser=t,this.children=[];let i=this.readUint32();this.type=this.readString(4),i>e.byteLength-e.byteOffset&&(this.size32=NaN);let r=this.size32?this.size32-8:void 0,a=e.byteOffset+this.cursor;this.size64=0,this.usertype=0,this.content=new DataView(e.buffer,a,r)}get id(){return this.type}get size(){return this.size32}scanForBoxes(e){return this.boxParser.parse(e)}readString(e,t="ascii"){let r=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,r}readUint8(){let e=this.source.getUint8(this.cursor);return this.cursor+=1,e}readUint16(){let e=this.source.getUint16(this.cursor);return this.cursor+=2,e}readUint32(){let e=this.source.getUint32(this.cursor);return this.cursor+=4,e}readUint64(){let e=this.source.getBigInt64(this.cursor);return this.cursor+=8,e}};var _r=class extends ne{};var oa=class extends ne{constructor(t,i){super(t,i);this.ondemandPrefix="ondemandlivejson";this.ondemandDataReceivedKey="t-in";this.ondemandDataPreparedKey="t-out";let r=this.content.byteOffset,a=r+this.content.byteLength,n=new TextDecoder("ascii").decode(this.content.buffer.slice(r,a)).split(this.ondemandPrefix)[1],o=JSON.parse(n);this.serverDataReceivedTimestamp=o[this.ondemandDataReceivedKey],this.serverDataPreparedTime=o[this.ondemandDataPreparedKey]}};var ua=class extends ne{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 la=class extends ne{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ve=class extends ne{constructor(e,t){super(e,t);let i=this.readUint32();this.version=i>>>24,this.flags=i&16777215}};var ca=class extends ve{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 da=class extends ne{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var pa=class extends ne{constructor(e,t){super(e,t),this.data=this.content}};var Zi=class extends ve{get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e,t){super(e,t),this.segments=[],this.referenceId=this.readUint32(),this.timescale=this.readUint32(),this.earliestPresentationTime32=this.readUint32(),this.firstOffset32=this.readUint32(),this.earliestPresentationTime64=0,this.firstOffset64=0,this.referenceCount=this.readUint32()&65535;for(let i=0;i<this.referenceCount;i++){let r=this.readUint32(),a=r>>>31,n=r<<1>>>1,o=this.readUint32();r=this.readUint32();let u=r>>>28,l=r<<3>>>3;this.segments.push({referenceType:a,referencedSize:n,subsegmentDuration:o,SAPType:u,SAPDeltaTime:l})}}};var ha=class extends ne{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var fa=class extends ne{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ma=class extends ve{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 ba=class extends ve{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var ga=class extends ve{constructor(e,t){super(e,t),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}};var Sa=class extends ne{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var va=class extends ve{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 ya=class extends ne{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ta=class extends ne{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ia=class extends ve{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var xa=class extends ne{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ea=class extends ve{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 wa=class extends ve{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 ve{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 Aa=class extends ne{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ka=class extends ve{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 Ra=class extends ne{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:ua,moov:la,mvhd:ca,moof:da,mdat:pa,sidx:Zi,trak:ha,mdia:Sa,mfhd:Ia,tkhd:va,traf:xa,tfhd:Ea,tfdt:wa,trun:Pa,minf:ya,sv3d:fa,st3d:ma,prhd:ba,proj:Ta,equi:ga,uuid:oa,stbl:Aa,stsd:ka,avc1:Ra,unknown:_r},gi=class s{constructor(e={}){this.options={offset:0,...e}}parse(e){let t=[],i=this.options.offset;for(;i<e.byteLength;)try{let a=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+i+4,4)),n=this.createBox(a,new DataView(e.buffer,e.byteOffset+i,e.byteLength-i));if(!n.size)break;t.push(n),i+=n.size}catch{break}return t}createBox(e,t){let i=HM[e];return i?new i(t,new s):new _r(t,new s)}};var Di=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{this.index[t.type]??=[],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 zM=new TextDecoder("ascii"),QM=s=>zM.decode(new DataView(s.buffer,s.byteOffset+4,4))==="ftyp",GM=s=>{let e=new Zi(s,new gi),t=e.earliestPresentationTime/e.timescale*1e3,i=s.byteOffset+s.byteLength+e.firstOffset;return e.segments.map(a=>{if(a.referenceType!==0)throw new Error("Unsupported multilevel sidx");let n=a.subsegmentDuration/e.timescale*1e3,o={status:"none",time:{from:t,to:t+n},byte:{from:i,to:i+a.referencedSize-1}};return t+=n,i+=a.referencedSize,o})},WM=(s,e)=>{let i=new gi().parse(s),r=new Di(i),a=r.findAll("moof"),n=e?r.findAll("uuid"):r.findAll("mdat");if(!(n.length&&a.length))return null;let o=a[0],u=n[n.length-1],l=o.source.byteOffset,c=u.source.byteOffset-o.source.byteOffset+u.size;return new DataView(s.buffer,l,c)},YM=s=>{let t=new gi().parse(s),i=new Di(t),r={},a=i.findAll("uuid");return a.length?a[a.length-1]:r},KM=s=>{let t=new gi().parse(s);return new Di(t).find("sidx")?.timescale},XM=(s,e)=>{let i=new gi().parse(s),a=new Di(i).findAll("traf"),n=a[a.length-1].children.find(c=>c.type==="tfhd"),o=a[a.length-1].children.find(c=>c.type==="tfdt"),u=a[a.length-1].children.find(c=>c.type==="trun"),l=0;return u.sampleDuration.length?l=u.sampleDuration.reduce((c,d)=>c+d,0):l=n.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+l)/e*1e3},JM=s=>{let e={is3dVideo:!1,stereoMode:0,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}},i=new gi().parse(s),r=new Di(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},Pv={validateData:QM,parseInit:JM,getIndexRange:()=>{},parseSegments:GM,parseFeedableSegmentChunk:WM,getChunkEndTime:XM,getServerLatencyTimestamps:YM,getTimescaleFromIndex:KM};var La=j(xt(),1),Si=require("@vkontakte/videoplayer-shared");var kv=require("@vkontakte/videoplayer-shared");var Av={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"}},Rv=s=>{let e=s.getUint8(0),t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);let i=Ma(s,t),r=i in Av,a=r?Av[i].type:"binary",n=s.getUint8(t),o=0;n&128?o=1:n&64?o=2:n&32?o=3:n&16?o=4:n&8?o=5:n&4?o=6:n&2?o=7:n&1&&(o=8);let u=new DataView(s.buffer,s.byteOffset+t+1,o-1),l=n&255>>o,p=Ma(u),c=l*2**((o-1)*8)+p,d=t+o,h;return d+c>s.byteLength?h=new DataView(s.buffer,s.byteOffset+d):h=new DataView(s.buffer,s.byteOffset+d,c),{tag:r?i:"0x"+i.toString(16).toUpperCase(),type:a,tagHeaderSize:d,tagSize:d+c,value:h,valueSize:c}},Ma=(s,e=s.byteLength)=>{switch(e){case 1:return s.getUint8(0);case 2:return s.getUint16(0);case 3:return s.getUint8(0)*2**16+s.getUint16(1);case 4:return s.getUint32(0);case 5:return s.getUint8(0)*2**32+s.getUint32(1);case 6:return s.getUint16(0)*2**32+s.getUint32(2);case 7:{let t=s.getUint8(0)*281474976710656+s.getUint16(1)*4294967296+s.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},Ht=(s,e)=>{switch(e){case"int":return s.getInt8(0);case"uint":return Ma(s);case"float":return s.byteLength===4?s.getFloat32(0):s.getFloat64(0);case"string":return new TextDecoder("ascii").decode(s);case"utf8":return new TextDecoder("utf-8").decode(s);case"date":return new Date(Date.UTC(2001,0)+s.getInt8(0)).getTime();case"master":return s;case"binary":return s;default:(0,kv.assertNever)(e)}},er=(s,e)=>{let t=0;for(;t<s.byteLength;){let i=new DataView(s.buffer,s.byteOffset+t),r=Rv(i);if(!e(r))return;r.type==="master"&&er(r.value,e),t=r.value.byteOffset-s.byteOffset+r.valueSize}},Mv=s=>{if(s.getUint32(0)!==440786851)return!1;let e,t,i,r=Rv(s);return er(r.value,({tag:a,type:n,value:o})=>(a===17143?e=Ht(o,n):a===17026?t=Ht(o,n):a===17029&&(i=Ht(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)};var Lv=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],ZM=[231,22612,22743,167,171,163,160,175],eL=s=>{let e,t,i,r,a=!1,n=!1,o=!1,u,l,p=!1,c=0;return er(s,({tag:d,type:h,value:m,valueSize:g})=>{if(d===21419){let v=Ht(m,h);l=Ma(v)}else d!==21420&&(l=void 0);return d===408125543?(e=m.byteOffset,t=m.byteOffset+g):d===357149030?a=!0:d===290298740?n=!0:d===2807729?i=Ht(m,h):d===17545?r=Ht(m,h):d===21420&&l===475249515?u=Ht(m,h):d===374648427?er(m,({tag:v,type:T,value:P})=>v===30321?(p=Ht(P,T)===1,!1):!0):a&&n&&(0,La.default)(Lv,d)&&(o=!0),!o}),(0,Si.assertNonNullable)(e,"Failed to parse webm Segment start"),(0,Si.assertNonNullable)(t,"Failed to parse webm Segment end"),(0,Si.assertNonNullable)(r,"Failed to parse webm Segment duration"),i=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:p,stereoMode:c,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},tL=s=>{if((0,Si.isNullable)(s.cuesSeekPosition))return;let e=s.segmentStart+s.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},iL=(s,e)=>{let t=!1,i=!1,r=o=>(0,Si.isNonNullable)(o.time)&&(0,Si.isNonNullable)(o.position),a=[],n;return er(s,({tag:o,type:u,value:l})=>{switch(o){case 475249515:t=!0;break;case 187:n&&r(n)&&a.push(n),n={};break;case 179:n&&(n.time=Ht(l,u));break;case 183:break;case 241:n&&(n.position=Ht(l,u));break;default:t&&(0,La.default)(Lv,o)&&(i=!0)}return!(t&&i)}),n&&r(n)&&a.push(n),a.map((o,u)=>{let{time:l,position:p}=o,c=a[u+1];return{status:"none",time:{from:l,to:c?c.time:e.segmentDuration},byte:{from:e.segmentStart+p,to:c?e.segmentStart+c.position-1:e.segmentEnd-1}}})},rL=s=>{let e=0,t=!1;try{er(s,i=>i.tag===524531317?i.tagSize<=s.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):(0,La.default)(ZM,i.tag)?(e+i.tagSize<=s.byteLength&&(e+=i.tagSize,t||=(0,La.default)([163,160,175],i.tag)),!0):!1)}catch{}return e>0&&e<=s.byteLength&&t?new DataView(s.buffer,s.byteOffset,e):null},Bv={validateData:Mv,parseInit:eL,getIndexRange:tL,parseSegments:iL,parseFeedableSegmentChunk:rL};var Ba=s=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(s);if(e){let[,t,i]=e;if(t==="audio"||t==="video")switch(i){case"webm":return Bv;case"mp4":return Pv}}throw new ReferenceError(`Unsupported mime type ${s}`)};var kc=j(sc(),1),Uv=j(Ui(),1),qv=j(ac(),1),Hv=j(Ut(),1),Rc=j(Gi(),1);var Da=require("@vkontakte/videoplayer-shared");var $v=s=>{try{let e=sL(),t=s.match(e),{groups:i}=t??{};if(i){let r={};if(i.extensions){let o=i.extensions.toLowerCase().match(/(?:[0-9a-wy-z](?:-[a-z0-9]{2,8})+)/g);Array.from(o||[]).forEach(u=>{r[u[0]]=u.slice(2)})}let a=i.variants?.split(/-/).filter(o=>o!==""),n={extlang:i.extlang,langtag:i.langtag,language:i.language,privateuse:i.privateuse||i.privateuse2,region:i.region,script:i.script,extensions:r,variants:a};return Object.keys(n).forEach(o=>{let u=n[o];(typeof u>"u"||u==="")&&delete n[o]}),n}return null}catch{return null}};function sL(){let s="(?<extlang>(?:[a-z]{3}(?:-[a-z]{3}){0,2}))",e="x(?:-[a-z0-9]{1,8})+",p=`^(?:(?<langtag>${`
|
|
178
|
+
`;var Or=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 ho(this.params.fov,this.params.orientation),this.cameraRotationManager=new fo(this.camera,{rotationSpeed:this.params.rotationSpeed,maxYawAngle:this.params.maxYawAngle,rotationSpeedCorrection:this.params.rotationSpeedCorrection,degreeToPixelCorrection:this.params.degreeToPixelCorrection,speedFadeTime:this.params.speedFadeTime,speedFadeThreshold:this.params.speedFadeThreshold}),this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.textureMappingBuffer=this.createTextureMappingBuffer(),this.updateTextureMappingBuffer(),this.program=this.createProgram(),this.videoTexture=this.createTexture(),this.gl.useProgram(this.program),this.videoElementDataLoadedFn=this.onDataLoadedHandler.bind(this),this.renderFn=this.render.bind(this)}play(){this.active||(this.videoInitialized?this.doPlay():this.sourceVideoElement.readyState>=2?(this.videoInitialized=!0,this.doPlay()):this.sourceVideoElement.addEventListener("loadeddata",this.videoElementDataLoadedFn))}stop(){this.active=!1}startCameraManualRotation(e,t){this.cameraRotationManager.setRotationSpeed(e*this.params.rotationSpeed,t*this.params.rotationSpeed,0),this.cameraRotationManager.startRotation()}stopCameraManualRotation(e=!1){this.cameraRotationManager.stopRotation(e)}turnCamera(e,t){this.cameraRotationManager.turnCamera(e,t)}pointCameraTo(e,t){this.cameraRotationManager.pointCameraTo(e,t)}pixelToDegree(e){return{x:this.params.degreeToPixelCorrection*this.params.fov.x*-e.x/this.viewportWidth,y:this.params.degreeToPixelCorrection*this.params.fov.y*e.y/this.viewportHeight}}getCameraRotation(){return this.camera.orientation}holdCamera(){this.cameraRotationManager.stopRotation(!0)}releaseCamera(){this.cameraRotationManager.onCameraRelease()}destroy(){this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),this.stop(),this.canvas.remove()}setViewportSize(e,t){this.viewportWidth=e,this.viewportHeight=t,this.canvas.width=this.viewportWidth,this.canvas.height=this.viewportHeight,this.gl.viewport(0,0,this.canvas.width,this.canvas.height)}onDataLoadedHandler(){this.videoInitialized=!0,this.doPlay()}doPlay(){this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.active=!0,this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),requestAnimationFrame(this.renderFn)}render(e){this.cameraRotationManager.tick(e),this.updateTexture(),this.updateTextureMappingBuffer();let t=this.gl.getAttribLocation(this.program,"a_vertex"),i=this.gl.getAttribLocation(this.program,"a_texel"),r=this.gl.getUniformLocation(this.program,"u_texture"),a=this.gl.getUniformLocation(this.program,"u_focus");this.gl.enableVertexAttribArray(t),this.gl.enableVertexAttribArray(i),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.vertexBuffer),this.gl.vertexAttribPointer(t,2,this.gl.FLOAT,!1,0,0),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.vertexAttribPointer(i,2,this.gl.FLOAT,!1,0,0),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.uniform1i(r,0),this.gl.uniform2f(a,-this.camera.orientation.x,-this.camera.orientation.y),this.gl.drawArrays(this.gl.TRIANGLE_FAN,0,4),this.gl.bindTexture(this.gl.TEXTURE_2D,null),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),this.gl.disableVertexAttribArray(t),this.gl.disableVertexAttribArray(i),this.active&&requestAnimationFrame(this.renderFn)}createShader(e,t){let i=this.gl.createShader(t);if(!i)throw this.destroy(),new Error(`Could not create shader (${t})`);if(this.gl.shaderSource(i,e),this.gl.compileShader(i),!this.gl.getShaderParameter(i,this.gl.COMPILE_STATUS))throw this.destroy(),new Error("An error occurred while compiling the shader: "+this.gl.getShaderInfoLog(i));return i}createProgram(){let e=this.gl.createProgram();if(!e)throw this.destroy(),new Error("Could not create shader program");let t=this.createShader(yv,this.gl.VERTEX_SHADER),i=this.createShader(Tv,this.gl.FRAGMENT_SHADER);if(this.gl.attachShader(e,t),this.gl.attachShader(e,i),this.gl.linkProgram(e),!this.gl.getProgramParameter(e,this.gl.LINK_STATUS))throw this.destroy(),new Error("Could not link shader program.");return e}createTexture(){let e=this.gl.createTexture();if(!e)throw this.destroy(),new Error("Could not create texture");return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.bindTexture(this.gl.TEXTURE_2D,null),e}updateTexture(){this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,!0),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.sourceVideoElement),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}createVertexBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create vertex buffer");let t=1,i=1,r=this.frameHeight/(this.frameWidth/this.viewportWidth);return r>this.viewportHeight?t=this.viewportHeight/r:i=r/this.viewportHeight,this.gl.bindBuffer(this.gl.ARRAY_BUFFER,e),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-t,-i,t,-i,t,i,-t,i]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),e}createTextureMappingBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create texture mapping buffer");return e}calculateTexturePosition(){let e=.5-this.camera.orientation.x/360,t=.5-this.camera.orientation.y/180,i=this.camera.fov.x/360/2,r=this.camera.fov.y/180/2,a=e-i,n=t-r,o=e+i,u=t-r,l=e+i,d=t+r,c=e-i,p=t+r;return[a,n,o,u,l,d,c,p]}updateTextureMappingBuffer(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([...this.calculateTexturePosition()]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}updateFrameSize(){this.frameWidth=this.sourceVideoElement.videoWidth,this.frameHeight=this.sourceVideoElement.videoHeight}createCanvas(){let e=document.createElement("canvas");return e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e}};var Se=require("@vkontakte/videoplayer-shared");var mo="stalls_manager_metrics",vc="stalls_manager_abr_params",Iv="stalls_manager_default_tuning_abr_params",yc=class{constructor(){this.isSeeked$=new Se.ValueSubject(!1);this.isBuffering$=new Se.ValueSubject(!1);this.maxQualityLimit=void 0;this.currentStallsCount=0;this.sumStallsDuration=0;this.lastStallDuration=0;this.providerStartWatchingTimestamp=0;this.lastUniqueVideoTrackSelectedTimestamp=0;this.predictedThroughputWithoutData=0;this.subscription=new Se.Subscription;this.severeStallOccurred$=new Se.ValueSubject(!1)}init(e){this.currentStallDuration$=e.currentStallDuration$,this.videoLastDataObtainedTimestamp$=e.videoLastDataObtainedTimestamp$,this.throughput$=e.throughput$,this.rtt$=e.rtt$,this.tuning=e.tuning,this.abrParams=e.abrParams,this.resetStoredAbrParamsIfNeeded(),this.subscribe(e)}get videoMaxQualityLimit(){return this.maxQualityLimit}get predictedThroughput(){return this.predictedThroughputWithoutData}get abrTuningParams(){let e=this.tuning.enabled?this.getStoredData(vc):{};return{...this.abrParams,...e}}set lastVideoTrackSelected(e){this.lastUniqueVideoTrackSelected?.id!==e.id&&(this.lastUniqueVideoTrackSelected=e,this.lastUniqueVideoTrackSelectedTimestamp=(0,Se.now)(),this.currentStallsCount=0)}destroy(){window.clearTimeout(this.qualityRestrictionTimer),this.subscription.unsubscribe(),this.currentStallDuration$.getValue()!==0&&this.updateStallData();let e=((0,Se.now)()-this.providerStartWatchingTimestamp-this.sumStallsDuration)/1e3,t=this.sumStallsDuration;this.addStallInfoToHistory(e,t),this.updateStoredAbrParams()}resetStoredAbrParamsIfNeeded(){let{bitrateFactorAtEmptyBuffer:e,bitrateFactorAtFullBuffer:t,containerSizeFactor:i}={...this.getStoredData(Iv)},{bitrateFactorAtEmptyBuffer:r,bitrateFactorAtFullBuffer:a,containerSizeFactor:n}={...this.abrParams};this.tuning.enabled&&e===r&&t===a&&i===n||(this.removeStoredData(vc),this.setStoredData(Iv,{bitrateFactorAtEmptyBuffer:r,bitrateFactorAtFullBuffer:a,containerSizeFactor:n}))}updateStoredAbrParams(){let e=[],t=this.getStoredData(mo,"[]");if(!this.tuning.enabled||t.length<this.tuning.stallsMetricsHistoryLength)return;let i=t.reduce((a,n)=>a+n.tvt,0);if(this.tuning.useTotalStallsDurationPerTvt){let n=t.reduce((o,u)=>o+u.stallsDuration,0)/i;e.push(this.calculateOptimalAbrParams(n,i))}if(this.tuning.useAverageStallsDurationPerTvt){let a=t.reduce((n,o)=>n+o.stallsDurationPerTvt,0)/t.length;e.push(this.calculateOptimalAbrParams(a,i))}this.tuning.useEmaStallsDurationPerTvt&&e.push(this.calculateOptimalAbrParams(t[t.length-1].stallsDurationPerTvtSmoothed,i));let r={bitrateFactorAtEmptyBuffer:Math.max(...e.map(a=>a.bitrateFactorAtEmptyBuffer)),bitrateFactorAtFullBuffer:Math.max(...e.map(a=>a.bitrateFactorAtFullBuffer)),containerSizeFactor:Math.min(...e.map(a=>a.containerSizeFactor))};this.setStoredData(mo,[]),this.setStoredData(vc,r)}calculateOptimalAbrParams(e,t){let{targetStallsDurationPerTvt:i,deviationStallsDurationPerTvt:r,criticalStallsDurationPerTvt:a,abrAdjustingSpeed:n,significantTvt:o,stallsMetricsHistoryLength:u}=this.tuning,l=n*Math.min(t/(o*u),1),d=this.abrTuningParams;return e<i-r?d={bitrateFactorAtEmptyBuffer:Math.max(d.bitrateFactorAtEmptyBuffer-l,this.abrParams.minBitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.max(d.bitrateFactorAtFullBuffer-l,this.abrParams.minBitrateFactorAtFullBuffer),containerSizeFactor:Math.min(d.containerSizeFactor+l,this.abrParams.maxContainerSizeFactor)}:e>i+r&&(d={bitrateFactorAtEmptyBuffer:Math.min(d.bitrateFactorAtEmptyBuffer+l,this.abrParams.maxBitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.min(d.bitrateFactorAtFullBuffer+l,this.abrParams.maxBitrateFactorAtFullBuffer),containerSizeFactor:Math.max(d.containerSizeFactor-l,this.abrParams.minContainerSizeFactor)}),e>a&&(d={bitrateFactorAtEmptyBuffer:Math.max(d.bitrateFactorAtEmptyBuffer,this.abrParams.bitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.max(d.bitrateFactorAtFullBuffer,this.abrParams.bitrateFactorAtFullBuffer),containerSizeFactor:Math.min(d.containerSizeFactor,this.abrParams.containerSizeFactor)}),d}getStoredData(e,t="{}"){return JSON.parse(Se.safeStorage.get(e)??t)}setStoredData(e,t){Se.safeStorage.set(e,JSON.stringify(t))}removeStoredData(e){Se.safeStorage.remove(e)}addStallInfoToHistory(e,t){if(e<this.tuning.minTvtToBeCounted||e>this.tuning.maxTvtToBeCounted||e*1e3<t)return;let i=this.getStoredData(mo,"[]"),r=t/e,a=i.length?mi(i[i.length-1].stallsDurationPerTvtSmoothed,t/e,this.tuning.emaAlpha):r,n={tvt:e,stallsDuration:t,stallsDurationPerTvt:r,stallsDurationPerTvtSmoothed:a};i.push(n),i.length>this.tuning.stallsMetricsHistoryLength&&i.shift(),this.setStoredData(mo,i)}updateStallData(){this.providerStartWatchingTimestamp&&!this.isSeeked$.getValue()&&(this.sumStallsDuration+=Math.min(this.lastStallDuration,this.tuning.maxPossibleStallDuration),this.currentStallsCount++)}subscribe(e){this.subscription.add(e.isSeeked$.subscribe(this.isSeeked$)),this.subscription.add(e.isBuffering$.subscribe(this.isBuffering$)),this.subscription.add(e.looped$.subscribe(t=>this.currentStallsCount=0)),this.subscription.add(e.playing$.pipe((0,Se.once)()).subscribe(t=>this.providerStartWatchingTimestamp=(0,Se.now)())),this.subscription.add(this.currentStallDuration$.pipe((0,Se.filterChanged)()).subscribe(t=>{let{stallDurationNoDataBeforeQualityDecrease:i,stallCountBeforeQualityDecrease:r,resetQualityRestrictionTimeout:a,ignoreStallsOnSeek:n}=this.tuning;if((0,Se.isNullable)(this.lastUniqueVideoTrackSelected)||n&&this.isSeeked$.getValue())return;let o=this.rtt$.getValue(),u=this.throughput$.getValue(),l=this.videoLastDataObtainedTimestamp$.getValue(),d=(0,Se.now)(),c=r&&this.currentStallsCount>=r,p=i&&d-this.lastUniqueVideoTrackSelectedTimestamp>=i+o&&d-l>=i+o&&t>=i;(c||p)&&(this.severeStallOccurred$.next(!0),window.clearTimeout(this.qualityRestrictionTimer),this.maxQualityLimit=this.lastUniqueVideoTrackSelected.quality,(0,Se.isNonNullable)(this.lastUniqueVideoTrackSelected.bitrate)&&u>this.lastUniqueVideoTrackSelected.bitrate&&(this.predictedThroughputWithoutData=this.lastUniqueVideoTrackSelected.bitrate)),!t&&(0,Se.now)()-this.providerStartWatchingTimestamp>this.lastStallDuration&&(this.updateStallData(),this.severeStallOccurred$.next(!1),window.clearTimeout(this.qualityRestrictionTimer),this.qualityRestrictionTimer=window.setTimeout(()=>{this.maxQualityLimit=void 0,this.predictedThroughputWithoutData=0},a)),this.lastStallDuration=t}))}},bo=yc;var ct=require("@vkontakte/videoplayer-shared"),go=class{constructor(){this.subscription=new ct.Subscription;this.pipSize$=new ct.ValueSubject(void 0);this.videoSize$=new ct.ValueSubject(void 0);this.elementSize$=new ct.ValueSubject(void 0);this.pictureInPictureWindowRemoveEventListener=ct.noop}connect({observableVideo:e,video:t}){let i=r=>{let a=r.target;this.pipSize$.next({width:a.width,height:a.height})};this.subscription.add((0,ct.observeElementSize)(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((0,ct.combine)({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe((0,ct.map)(({videoSize:r,inPip:a,pipSize:n})=>a?n:r)).subscribe(this.elementSize$))}getValue(){return this.elementSize$.getValue()}subscribe(e,t){return this.elementSize$.subscribe(e,t)}getObservable(){return this.elementSize$}destroy(){this.pictureInPictureWindowRemoveEventListener(),this.subscription.unsubscribe()}};var Ji=class{constructor(e){this.subscription=new K.Subscription;this.videoState=new ie("stopped");this.observableVideo=null;this.droppedFramesManager=new Pr;this.stallsManager=new bo;this.elementSizeManager=new go;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new ki;this.audioTrackSwitchHistory=new ki;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?.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"),_(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"),_(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="ready"&&_(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?.to==="playing"&&_(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&_(this.params.desiredState.playbackState,"paused");return;default:return(0,K.assertNever)(e)}}};this.init3DScene=e=>{if(this.scene3D)return;this.scene3D=new Or(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:e.projectionData?.pose.yaw||0,y:e.projectionData?.pose.pitch||0,z:e.projectionData?.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 Rt(e.source.url),this.params=e,this.video=at(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(We(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 po({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;(0,K.isNullable)(this.observableVideo)&&(this.observableVideo=ut(this.video),this.subscription.add(()=>this.observableVideo?.destroy()));let i=this.constructor.name,r=n=>{e.error$.next({id:i,category:K.ErrorCategory.WTF,message:`${i} internal logic error`,thrown:n})},a=(n,o)=>this.subscription.add(n.subscribe(o,r));return{output:e,desiredState:t,observableVideo:this.observableVideo,genericErrorListener:r,connect:a}}subscribe(){let{output:e,desiredState:t,observableVideo:i,genericErrorListener:r,connect:a}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe((0,K.filter)(l=>!!l.length),(0,K.once)()).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((0,K.map)(l=>l.to.state!=="none"),(0,K.filterChanged)());this.stallsManager.init({isSeeked$:n,currentStallDuration$:this.player.currentStallDuration$,videoLastDataObtainedTimestamp$:this.player.videoLastDataObtainedTimestamp$,throughput$:this.params.dependencies.throughputEstimator.throughput$,rtt$:this.params.dependencies.throughputEstimator.rtt$,tuning:this.params.tuning.stallsManager,abrParams:this.params.tuning.autoTrackSelection,isBuffering$:i.isBuffering$,looped$:i.looped$,playing$:i.playing$}),a(i.ended$,e.endedEvent$),a(i.looped$,e.loopedEvent$),a(i.error$,e.error$),a(i.isBuffering$,e.isBuffering$),a(i.currentBuffer$,e.currentBuffer$),a(i.playing$,e.firstFrameEvent$),a(i.canplay$,e.canplay$),a(i.inPiP$,e.inPiP$),a(i.inFullscreen$,e.inFullscreen$),a(i.loadedMetadata$,e.loadedMetadataEvent$),a(this.player.error$,e.error$),a(this.player.fetcherRecoverableError$,e.fetcherRecoverableError$),a(this.player.fetcherError$,e.fetcherError$),a(this.player.lastConnectionType$,e.httpConnectionType$),a(this.player.lastConnectionReused$,e.httpConnectionReused$),a(this.player.isLive$,e.isLive$),a(this.player.lastRequestFirstBytes$.pipe((0,K.filter)(K.isNonNullable),(0,K.once)()),e.firstBytesEvent$),a(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),a(this.videoState.stateChangeEnded$.pipe((0,K.map)(l=>l.to)),this.params.output.playbackState$),this.subscription.add(i.looped$.subscribe(()=>this.player.warmUpMediaSourceIfNeeded(),r)),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(Wt(this.video,t.isLooped,r)),this.subscription.add(ot(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(kt(this.video,t.playbackRate,i.playbackRateState$,r)),this.elementSizeManager.connect({video:this.video,observableVideo:i}),a(Mt(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),_(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),_(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:l})=>{if(l==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let d=this.player.getStreams();if((0,K.assertNonNullable)(d,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let p=[];for(let h of d.audio){p.push(uc(h));let m=[];for(let g of h.representations){let v=av(g);m.push(v),this.audioTracksMap.set(v,{stream:h,representation:g})}this.audioStreamsMap.set(h,m)}this.params.output.availableAudioStreams$.next(p)}let c=[];for(let p of d.video){c.push(lc(p));let h=[];for(let m of p.representations){let g=sv({...m,streamId:p.id});g&&(h.push(g),this.videoTracksMap.set(g,{stream:p,representation:m}))}this.videoStreamsMap.set(p,h)}this.params.output.availableVideoStreams$.next(c);for(let p of d.text)for(let h of p.representations){let m=nv(p,h);this.textTracksMap.set(m,{stream:p,representation:h})}this.params.output.availableVideoTracks$.next(Array.from(this.videoTracksMap.keys())),this.params.output.availableAudioTracks$.next(Array.from(this.audioTracksMap.keys())),this.params.output.isAudioAvailable$.next(!!this.audioTracksMap.size),this.audioTracksMap.size&&this.textTracksMap.size&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else l==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},r)),this.subscription.add((0,K.merge)(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$,(0,K.fromEvent)(this.video,"progress")).pipe((0,K.filter)(()=>this.videoTracksMap.size>0)).subscribe(async()=>{let l=this.player.state$.getState(),d=this.player.state$.getTransition();if(!(0,xv.default)(["manifest_ready","running"],l)||d)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let c=this.selectVideoAudioRepresentations();if(!c)return;let[p,h]=c,m=[...this.videoTracksMap.keys()].find(v=>this.videoTracksMap.get(v)?.representation.id===p.id);(0,K.isNonNullable)(m)&&(this.stallsManager.lastVideoTrackSelected=m);let g=this.params.desiredState.autoVideoTrackLimits.getTransition();if(g&&this.params.output.autoVideoTrackLimits$.next(g.to),l==="manifest_ready")await this.player.initRepresentations(p.id,h?.id,this.params.sourceHls);else if(await this.player.switchRepresentation("video",p.id),h){let v=!!t.audioStream.getTransition();await this.player.switchRepresentation("audio",h.id,v)}},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((0,K.filterChanged)()).subscribe(l=>{let d=[...this.videoTracksMap.entries()].find(([,{representation:m}])=>m.id===l);if(!d){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[c,{stream:p}]=d,h=this.params.desiredState.videoStream.getTransition();h&&h.to&&h.to.id===p.id&&this.params.desiredState.videoStream.setState(h.to),e.currentVideoTrack$.next(c),e.currentVideoStream$.next(lc(p))},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe((0,K.filterChanged)()).subscribe(l=>{let d=[...this.audioTracksMap.entries()].find(([,{representation:m}])=>m.id===l);if(!d){e.currentAudioStream$.next(void 0);return}let[c,{stream:p}]=d,h=this.params.desiredState.audioStream.getTransition();h&&h.to&&h.to.id===p.id&&this.params.desiredState.audioStream.setState(h.to),e.currentAudioStream$.next(uc(p))},r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(l=>{if(l?.is3dVideo&&this.params.tuning.spherical?.enabled)try{this.init3DScene(l),e.is3DVideo$.next(!0)}catch(d){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${d}`})}else this.destroy3DScene(),this.params.tuning.spherical?.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((0,K.map)(({to:l})=>l==="ready"),(0,K.filterChanged)());this.subscription.add((0,K.merge)(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,(0,K.observableFrom)(["init"])).subscribe(()=>{let l=t.autoVideoTrackSwitching.getState(),c=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:l?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(c)})),this.subscription.add((0,K.merge)(o,this.player.state$.stateChangeEnded$,(0,K.observableFrom)(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let u=(0,K.merge)(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,K.observableFrom)(["init"])).pipe((0,K.debounce)(0));this.subscription.add(u.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?gs:bs,t=this.params.tuning.useNewAutoSelectVideoTrack?zn:Hn,i=this.params.tuning.useNewAutoSelectVideoTrack?Yt:jn,{desiredState:r,output:a}=this.params,n=r.autoVideoTrackSwitching.getState(),o=r.videoTrack.getState()?.id,l=[...this.videoTracksMap.keys()].find(({id:I})=>I===o),d=a.currentVideoTrack$.getValue(),c=r.videoStream.getState()??(l&&this.videoTracksMap.get(l)?.stream)??this.videoStreamsMap.size===1?this.videoStreamsMap.keys().next().value:void 0;if(!c)return;let p=[...this.videoStreamsMap.keys()].find(({id:I})=>I===c.id),h=p&&this.videoStreamsMap.get(p);if(!h)return;let m=ze(this.video.buffered,this.video.currentTime*1e3),g;this.player.isActiveLive$.getValue()?g=this.player.isLowLatency$.getValue()?this.params.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.params.tuning.dashCmafLive.normalizedLiveMinBufferSize:this.player.isLive$.getValue()?g=this.params.tuning.dashCmafLive.normalizedTargetMinBufferSize:g=n?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;let v=(this.video.duration*1e3||1/0)-this.video.currentTime*1e3,T=Math.min(m/Math.min(g,v||1/0),1),w=r.audioStream.getState()??(this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0),x=[...this.audioStreamsMap.keys()].find(({id:I})=>I===w?.id)??this.audioStreamsMap.keys().next().value,M=0;if(x){if(l&&!n){let I=e(l,h,this.audioStreamsMap.get(x)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);M=Math.max(M,I?.bitrate??-1/0)}if(d){let I=e(d,h,this.audioStreamsMap.get(x)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);M=Math.max(M,I?.bitrate??-1/0)}}let B=i(h,{container:this.elementSizeManager.getValue(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.stallsManager.abrTuningParams,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:M,forwardBufferHealth:T,current:d,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}),F=n?B??l:l??B,G=x&&t(F,h,this.audioStreamsMap.get(x)??[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.stallsManager.abrTuningParams,forwardBufferHealth:T,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),$=this.videoTracksMap.get(F)?.representation,D=G&&this.audioTracksMap.get(G)?.representation;if($&&D)return[$,D];if($&&!D&&this.audioTracksMap.size===0)return[$,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){lt(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),_(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:K.ErrorCategory.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),nt(this.video),this.tracer.end()}};var aa=class extends Ji{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)}};var fe=require("@vkontakte/videoplayer-shared");var na=class extends Ji{constructor(e){super(e),this.textTracksManager.destroy()}subscribe(){super.subscribe();let e=-1,{output:t,observableVideo:i,desiredState:r,connect:a}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),a(i.timeUpdate$,t.liveBufferTime$),a(this.player.liveSeekableDuration$,t.duration$),a(this.player.liveLatency$,t.liveLatency$);let n=new fe.ValueSubject(1);a(i.playbackRateState$,n),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(r.isLowLatency.stateChangeEnded$.pipe((0,fe.map)(o=>o.to)).subscribe(this.player.isLowLatency$)).add((0,fe.combine)({liveBufferTime:t.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe((0,fe.map)(({liveBufferTime:o,liveAvailabilityStartTime:u})=>o&&u?o+u:void 0)).subscribe(t.liveTime$)).add(this.player.liveStreamStatus$.pipe((0,fe.filter)(o=>(0,fe.isNonNullable)(o))).subscribe(o=>t.isLiveEnded$.next(o!=="active"&&t.position$.getValue()===0))).add((0,fe.combine)({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:(0,fe.merge)(i.playbackRateState$,new fe.ValueSubject(1))}).pipe((0,fe.filter)(({liveStreamStatus:o,liveDuration:u})=>o==="active"&&!!u)).subscribe(({liveDuration:o,playbackRate:u})=>{let l=t.liveBufferTime$.getValue(),d=t.position$.getValue(),{playbackCatchupSpeedup:c}=this.params.tuning.dashCmafLive.lowLatency;d||u<1-c||this.video.paused||(0,fe.isNullable)(l)||(e=o-l)})).add((0,fe.combine)({time:t.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:(0,fe.merge)(i.playbackRateState$,new fe.ValueSubject(1))}).pipe((0,fe.filterChanged)((o,u)=>this.player.liveStreamStatus$.getValue()==="active"?o.liveDuration===u.liveDuration:o.time===u.time)).subscribe(({time:o,liveDuration:u,playbackRate:l})=>{let d=t.position$.getValue(),{playbackCatchupSpeedup:c}=this.params.tuning.dashCmafLive.lowLatency;if(!d&&!this.video.paused&&l>=1-c||(0,fe.isNullable)(o)||(0,fe.isNullable)(u))return;let p=-1*(u-o-e);t.position$.next(Math.min(p,0))})).add(this.player.currentLiveTextRepresentation$.subscribe(o=>{if(o){let u=ov(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 X=require("@vkontakte/videoplayer-shared");var Bc=H(ws(),1);var S=require("@vkontakte/videoplayer-shared");var Io=H(xt(),1),Fr=H(Ut(),1),xo=H(ws(),1);var zv=H(Rn(),1);var $i=require("@vkontakte/videoplayer-shared");var UM=18,Ev=!1;try{Ev=W.browser.isSafari&&!!W.browser.safariVersion&&W.browser.safariVersion<=UM}catch(s){console.error(s)}var Tc=class{constructor(e){this.bufferFull$=new $i.Subject;this.error$=new $i.Subject;this.queue=[];this.currentTask=null;this.destroyed=!1;this.abortRequested=!1;this.completeTask=()=>{try{if(this.currentTask){let e=this.currentTask.signal?.aborted;this.currentTask.callback(!e),this.currentTask=null}this.queue.length&&this.pull()}catch(e){this.error$.next({id:"BufferTaskQueueUnknown",category:$i.ErrorCategory.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:e})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(i=>{let r={operation:"append",data:e,signal:t,callback:i};this.queue.push(r),this.pull()})}async remove(e,t,i){return i&&i.aborted?!1:new Promise(r=>{let a={operation:"remove",from:e,to:t,signal:i,callback:r};this.queue.unshift(a),this.pull()})}async abort(e){return new Promise(t=>{let i,r=a=>{this.abortRequested=!1,t(a)};Ev&&e?i={operation:"safariAbort",init:e,callback:r}:i={operation:"abort",callback:r};for(let{callback:a}of this.queue)a(!1);this.abortRequested=!0,i&&(this.queue=[i]),this.pull()})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){if((this.buffer.updating||this.currentTask||this.destroyed)&&!this.abortRequested)return;let e=this.queue.shift();if(!e)return;if(e.signal?.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(r){r instanceof DOMException&&r.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):r instanceof DOMException&&r.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:$i.ErrorCategory.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:r}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){let{operation:t}=e;switch(t){case"append":this.buffer.appendBuffer(e.data);break;case"remove":this.buffer.remove(e.from/1e3,e.to/1e3);break;case"abort":this.buffer.abort();break;case"safariAbort":{this.buffer.abort(),this.buffer.appendBuffer(e.init);break}default:(0,$i.assertNever)(t)}}},wv=Tc;var P=require("@vkontakte/videoplayer-shared");var ne=class{constructor(e,t){this.cursor=0;this.source=e,this.boxParser=t,this.children=[];let i=this.readUint32();this.type=this.readString(4),i>e.byteLength-e.byteOffset&&(this.size32=NaN);let r=this.size32?this.size32-8:void 0,a=e.byteOffset+this.cursor;this.size64=0,this.usertype=0,this.content=new DataView(e.buffer,a,r)}get id(){return this.type}get size(){return this.size32}scanForBoxes(e){return this.boxParser.parse(e)}readString(e,t="ascii"){let r=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,r}readUint8(){let e=this.source.getUint8(this.cursor);return this.cursor+=1,e}readUint16(){let e=this.source.getUint16(this.cursor);return this.cursor+=2,e}readUint32(){let e=this.source.getUint32(this.cursor);return this.cursor+=4,e}readUint64(){let e=this.source.getBigInt64(this.cursor);return this.cursor+=8,e}};var _r=class extends ne{};var oa=class extends ne{constructor(t,i){super(t,i);this.ondemandPrefix="ondemandlivejson";this.ondemandDataReceivedKey="t-in";this.ondemandDataPreparedKey="t-out";let r=this.content.byteOffset,a=r+this.content.byteLength,n=new TextDecoder("ascii").decode(this.content.buffer.slice(r,a)).split(this.ondemandPrefix)[1],o=JSON.parse(n);this.serverDataReceivedTimestamp=o[this.ondemandDataReceivedKey],this.serverDataPreparedTime=o[this.ondemandDataPreparedKey]}};var ua=class extends ne{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 la=class extends ne{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ve=class extends ne{constructor(e,t){super(e,t);let i=this.readUint32();this.version=i>>>24,this.flags=i&16777215}};var ca=class extends ve{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 da=class extends ne{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var pa=class extends ne{constructor(e,t){super(e,t),this.data=this.content}};var Zi=class extends ve{get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e,t){super(e,t),this.segments=[],this.referenceId=this.readUint32(),this.timescale=this.readUint32(),this.earliestPresentationTime32=this.readUint32(),this.firstOffset32=this.readUint32(),this.earliestPresentationTime64=0,this.firstOffset64=0,this.referenceCount=this.readUint32()&65535;for(let i=0;i<this.referenceCount;i++){let r=this.readUint32(),a=r>>>31,n=r<<1>>>1,o=this.readUint32();r=this.readUint32();let u=r>>>28,l=r<<3>>>3;this.segments.push({referenceType:a,referencedSize:n,subsegmentDuration:o,SAPType:u,SAPDeltaTime:l})}}};var ha=class extends ne{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var fa=class extends ne{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ma=class extends ve{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 ba=class extends ve{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var ga=class extends ve{constructor(e,t){super(e,t),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}};var Sa=class extends ne{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var va=class extends ve{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 ya=class extends ne{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ta=class extends ne{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ia=class extends ve{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var xa=class extends ne{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ea=class extends ve{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 wa=class extends ve{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 Aa=class extends ve{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 ne{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ka=class extends ve{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 Ra=class extends ne{constructor(e,t){super(e,t),this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+78,this.content.byteLength-78))}};var jM={ftyp:ua,moov:la,mvhd:ca,moof:da,mdat:pa,sidx:Zi,trak:ha,mdia:Sa,mfhd:Ia,tkhd:va,traf:xa,tfhd:Ea,tfdt:wa,trun:Aa,minf:ya,sv3d:fa,st3d:ma,prhd:ba,proj:Ta,equi:ga,uuid:oa,stbl:Pa,stsd:ka,avc1:Ra,unknown:_r},gi=class s{constructor(e={}){this.options={offset:0,...e}}parse(e){let t=[],i=this.options.offset;for(;i<e.byteLength;)try{let a=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+i+4,4)),n=this.createBox(a,new DataView(e.buffer,e.byteOffset+i,e.byteLength-i));if(!n.size)break;t.push(n),i+=n.size}catch{break}return t}createBox(e,t){let i=jM[e];return i?new i(t,new s):new _r(t,new s)}};var Di=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{this.index[t.type]??=[],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 zM=new TextDecoder("ascii"),QM=s=>zM.decode(new DataView(s.buffer,s.byteOffset+4,4))==="ftyp",GM=s=>{let e=new Zi(s,new gi),t=e.earliestPresentationTime/e.timescale*1e3,i=s.byteOffset+s.byteLength+e.firstOffset;return e.segments.map(a=>{if(a.referenceType!==0)throw new Error("Unsupported multilevel sidx");let n=a.subsegmentDuration/e.timescale*1e3,o={status:"none",time:{from:t,to:t+n},byte:{from:i,to:i+a.referencedSize-1}};return t+=n,i+=a.referencedSize,o})},WM=(s,e)=>{let i=new gi().parse(s),r=new Di(i),a=r.findAll("moof"),n=e?r.findAll("uuid"):r.findAll("mdat");if(!(n.length&&a.length))return null;let o=a[0],u=n[n.length-1],l=o.source.byteOffset,c=u.source.byteOffset-o.source.byteOffset+u.size;return new DataView(s.buffer,l,c)},YM=s=>{let t=new gi().parse(s),i=new Di(t),r={},a=i.findAll("uuid");return a.length?a[a.length-1]:r},KM=s=>{let t=new gi().parse(s);return new Di(t).find("sidx")?.timescale},XM=(s,e)=>{let i=new gi().parse(s),a=new Di(i).findAll("traf"),n=a[a.length-1].children.find(c=>c.type==="tfhd"),o=a[a.length-1].children.find(c=>c.type==="tfdt"),u=a[a.length-1].children.find(c=>c.type==="trun"),l=0;return u.sampleDuration.length?l=u.sampleDuration.reduce((c,p)=>c+p,0):l=n.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+l)/e*1e3},JM=s=>{let e={is3dVideo:!1,stereoMode:0,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}},i=new gi().parse(s),r=new Di(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},Av={validateData:QM,parseInit:JM,getIndexRange:()=>{},parseSegments:GM,parseFeedableSegmentChunk:WM,getChunkEndTime:XM,getServerLatencyTimestamps:YM,getTimescaleFromIndex:KM};var La=H(xt(),1),Si=require("@vkontakte/videoplayer-shared");var kv=require("@vkontakte/videoplayer-shared");var Pv={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"}},Rv=s=>{let e=s.getUint8(0),t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);let i=Ma(s,t),r=i in Pv,a=r?Pv[i].type:"binary",n=s.getUint8(t),o=0;n&128?o=1:n&64?o=2:n&32?o=3:n&16?o=4:n&8?o=5:n&4?o=6:n&2?o=7:n&1&&(o=8);let u=new DataView(s.buffer,s.byteOffset+t+1,o-1),l=n&255>>o,d=Ma(u),c=l*2**((o-1)*8)+d,p=t+o,h;return p+c>s.byteLength?h=new DataView(s.buffer,s.byteOffset+p):h=new DataView(s.buffer,s.byteOffset+p,c),{tag:r?i:"0x"+i.toString(16).toUpperCase(),type:a,tagHeaderSize:p,tagSize:p+c,value:h,valueSize:c}},Ma=(s,e=s.byteLength)=>{switch(e){case 1:return s.getUint8(0);case 2:return s.getUint16(0);case 3:return s.getUint8(0)*2**16+s.getUint16(1);case 4:return s.getUint32(0);case 5:return s.getUint8(0)*2**32+s.getUint32(1);case 6:return s.getUint16(0)*2**32+s.getUint32(2);case 7:{let t=s.getUint8(0)*281474976710656+s.getUint16(1)*4294967296+s.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},jt=(s,e)=>{switch(e){case"int":return s.getInt8(0);case"uint":return Ma(s);case"float":return s.byteLength===4?s.getFloat32(0):s.getFloat64(0);case"string":return new TextDecoder("ascii").decode(s);case"utf8":return new TextDecoder("utf-8").decode(s);case"date":return new Date(Date.UTC(2001,0)+s.getInt8(0)).getTime();case"master":return s;case"binary":return s;default:(0,kv.assertNever)(e)}},er=(s,e)=>{let t=0;for(;t<s.byteLength;){let i=new DataView(s.buffer,s.byteOffset+t),r=Rv(i);if(!e(r))return;r.type==="master"&&er(r.value,e),t=r.value.byteOffset-s.byteOffset+r.valueSize}},Mv=s=>{if(s.getUint32(0)!==440786851)return!1;let e,t,i,r=Rv(s);return er(r.value,({tag:a,type:n,value:o})=>(a===17143?e=jt(o,n):a===17026?t=jt(o,n):a===17029&&(i=jt(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)};var Lv=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],ZM=[231,22612,22743,167,171,163,160,175],eL=s=>{let e,t,i,r,a=!1,n=!1,o=!1,u,l,d=!1,c=0;return er(s,({tag:p,type:h,value:m,valueSize:g})=>{if(p===21419){let v=jt(m,h);l=Ma(v)}else p!==21420&&(l=void 0);return p===408125543?(e=m.byteOffset,t=m.byteOffset+g):p===357149030?a=!0:p===290298740?n=!0:p===2807729?i=jt(m,h):p===17545?r=jt(m,h):p===21420&&l===475249515?u=jt(m,h):p===374648427?er(m,({tag:v,type:T,value:w})=>v===30321?(d=jt(w,T)===1,!1):!0):a&&n&&(0,La.default)(Lv,p)&&(o=!0),!o}),(0,Si.assertNonNullable)(e,"Failed to parse webm Segment start"),(0,Si.assertNonNullable)(t,"Failed to parse webm Segment end"),(0,Si.assertNonNullable)(r,"Failed to parse webm Segment duration"),i=i??1e6,{segmentStart:Math.round(e/1e9*i*1e3),segmentEnd:Math.round(t/1e9*i*1e3),timeScale:i,segmentDuration:Math.round(r/1e9*i*1e3),cuesSeekPosition:u,is3dVideo:d,stereoMode:c,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},tL=s=>{if((0,Si.isNullable)(s.cuesSeekPosition))return;let e=s.segmentStart+s.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},iL=(s,e)=>{let t=!1,i=!1,r=o=>(0,Si.isNonNullable)(o.time)&&(0,Si.isNonNullable)(o.position),a=[],n;return er(s,({tag:o,type:u,value:l})=>{switch(o){case 475249515:t=!0;break;case 187:n&&r(n)&&a.push(n),n={};break;case 179:n&&(n.time=jt(l,u));break;case 183:break;case 241:n&&(n.position=jt(l,u));break;default:t&&(0,La.default)(Lv,o)&&(i=!0)}return!(t&&i)}),n&&r(n)&&a.push(n),a.map((o,u)=>{let{time:l,position:d}=o,c=a[u+1];return{status:"none",time:{from:l,to:c?c.time:e.segmentDuration},byte:{from:e.segmentStart+d,to:c?e.segmentStart+c.position-1:e.segmentEnd-1}}})},rL=s=>{let e=0,t=!1;try{er(s,i=>i.tag===524531317?i.tagSize<=s.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):(0,La.default)(ZM,i.tag)?(e+i.tagSize<=s.byteLength&&(e+=i.tagSize,t||=(0,La.default)([163,160,175],i.tag)),!0):!1)}catch{}return e>0&&e<=s.byteLength&&t?new DataView(s.buffer,s.byteOffset,e):null},Bv={validateData:Mv,parseInit:eL,getIndexRange:tL,parseSegments:iL,parseFeedableSegmentChunk:rL};var Ba=s=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(s);if(e){let[,t,i]=e;if(t==="audio"||t==="video")switch(i){case"webm":return Bv;case"mp4":return Av}}throw new ReferenceError(`Unsupported mime type ${s}`)};var kc=H(sc(),1),Uv=H(Ui(),1),qv=H(ac(),1),jv=H(Ut(),1),Rc=H(Gi(),1);var Da=require("@vkontakte/videoplayer-shared");var $v=s=>{try{let e=sL(),t=s.match(e),{groups:i}=t??{};if(i){let r={};if(i.extensions){let o=i.extensions.toLowerCase().match(/(?:[0-9a-wy-z](?:-[a-z0-9]{2,8})+)/g);Array.from(o||[]).forEach(u=>{r[u[0]]=u.slice(2)})}let a=i.variants?.split(/-/).filter(o=>o!==""),n={extlang:i.extlang,langtag:i.langtag,language:i.language,privateuse:i.privateuse||i.privateuse2,region:i.region,script:i.script,extensions:r,variants:a};return Object.keys(n).forEach(o=>{let u=n[o];(typeof u>"u"||u==="")&&delete n[o]}),n}return null}catch{return null}};function sL(){let s="(?<extlang>(?:[a-z]{3}(?:-[a-z]{3}){0,2}))",e="x(?:-[a-z0-9]{1,8})+",d=`^(?:(?<langtag>${`
|
|
179
179
|
(?<language>${`(?:[a-z]{2,3}(?:-${s})?|[a-z]{4}|[a-z]{5,8})`})
|
|
180
180
|
(-(?<script>[a-z]{4}))?
|
|
181
181
|
(-(?<region>(?:[a-z]{2}|[0-9]{3})))?
|
|
182
182
|
(?<variants>(?:-(?:[a-z0-9]{5,8}|[0-9][a-z0-9]{3}))*)
|
|
183
183
|
(?<extensions>(?:-[0-9a-wy-z](?:-[a-z0-9]{2,8})+)*)
|
|
184
184
|
(?:-(?<privateuse>(?:${e})))?
|
|
185
|
-
`})|(?<privateuse2>${e}))$`.replace(/[\s\t\n]/g,"");return new RegExp(p,"i")}var Ec=j(Ut(),1);var So=require("@vkontakte/videoplayer-shared"),Dv=({id:s,width:e,height:t,bitrate:i,fps:r,quality:a,streamId:n})=>{let o=(a?Ai(a):void 0)??(0,So.videoSizeToQuality)({width:e,height:t});return o&&{id:s,quality:o,bitrate:i,size:{width:e,height:t},fps:r,streamId:n}},Cv=({id:s,bitrate:e})=>({id:s,bitrate:e}),Vv=({language:s,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:s,label:e}),Ov=({language:s,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:s,label:e}),wc=({id:s,language:e,label:t,codecs:i,isDefault:r})=>({id:s,language:e,label:t,codec:(0,Ec.default)(i.split("."),0),isDefault:r}),Pc=({id:s,language:e,label:t,hdr:i,codecs:r})=>({id:s,language:e,hdr:i,label:t,codec:(0,Ec.default)(r.split("."),0)}),Ac=s=>"url"in s,st=s=>s.type==="template",$a=s=>s instanceof DOMException&&(s.name==="AbortError"||s.code===20);var _v=s=>{s.sort((t,i)=>t.from-i.from);let e=[s[0]];for(let t=1;t<s.length;t++){let{from:i,to:r}=s[t],a=e[e.length-1];a.to>=i?a.to=Math.max(a.to,r):e.push(s[t])}return e},tr=(s,e)=>{for(let t of s)if(e(t))return t;return null},Fv=s=>{let e=!1,t=(0,So.throttleFn)(()=>{e=!0},s);return()=>{try{return t(),e}finally{e=!1}}};var Nv=s=>{if(!s?.startsWith("P"))return;let e=(n,o)=>{let u=n?parseFloat(n.replace(",",".")):NaN;return(isNaN(u)?0:u)*o},i=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(s),r=i?.[1]==="-"?-1:1,a={days:e(i?.[5],r),hours:e(i?.[6],r),minutes:e(i?.[7],r),seconds:e(i?.[8],r)};return a.days*24*60*60*1e3+a.hours*60*60*1e3+a.minutes*60*1e3+a.seconds*1e3},vi=(s,e)=>{let t=s;t=(0,kc.default)(t,"$$","$");let i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[r,a]of(0,Uv.default)(i)){let n=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=(0,kc.default)(t,n,(o,u)=>(0,Da.isNullable)(a)?o:(0,Da.isNullable)(u)?a:(0,qv.default)(a,parseInt(u,10),"0"))}return t},jv=(s,e)=>{let i=new DOMParser().parseFromString(s,"application/xml"),r={video:[],audio:[],text:[]},a=i.children[0],n=Array.from(a.querySelectorAll("MPD > BaseURL").values()).map(D=>D.textContent?.trim()??""),o=(0,Hv.default)(n,0)??"",u=a.getAttribute("type")==="dynamic",l=a.getAttribute("availabilityStartTime"),p=a.getAttribute("publishTime"),c=a.getElementsByTagName("vk:Attrs")[0],d=c?.getElementsByTagName("vk:XLatestSegmentPublishTime")[0].textContent,h=c?.getElementsByTagName("vk:XStreamIsLive")[0].textContent,m=c?.getElementsByTagName("vk:XStreamIsUnpublished")[0].textContent,g=c?.getElementsByTagName("vk:XPlaybackDuration")[0].textContent,v;u&&(v={availabilityStartTime:l?new Date(l).getTime():0,publishTime:p?new Date(p).getTime():0,latestSegmentPublishTime:d?new Date(d).getTime():0,streamIsAlive:h==="yes",streamIsUnpublished:m==="yes"});let T,P=a.getAttribute("mediaPresentationDuration"),x=[...a.getElementsByTagName("Period")],L=x.reduce((D,I)=>({...D,[I.id]:I.children}),{}),B=x.reduce((D,I)=>({...D,[I.id]:I.getAttribute("duration")}),{});P?T=Nv(P):(0,Rc.default)(B).filter(D=>D).length&&!u?T=(0,Rc.default)(B).reduce((D,I)=>D+(Nv(I)??0),0):g&&(T=parseInt(g,10));let F=0,G=a.getAttribute("profiles")?.split(",")??[];for(let D of x.map(I=>I.id))for(let I of L[D]){let U=I.getAttribute("id")??"id"+(F++).toString(10),k=I.getAttribute("mimeType")??"",R=I.getAttribute("codecs")??"",C=I.getAttribute("contentType")??k?.split("/")[0],be=I.getAttribute("profiles")?.split(",")??[],N=$v(I.getAttribute("lang")??"")??{},re=I.querySelector("Label")?.textContent?.trim()??void 0,le=I.querySelectorAll("Representation"),Te=I.querySelector("SegmentTemplate"),Be=I.querySelector("Role")?.getAttribute("value")??void 0,Ie=C,ce={id:U,language:N.language,isDefault:Be==="main",label:re,codecs:R,hdr:Ie==="video"&&Dr(R),mime:k,representations:[]};for(let V of le){let z=V.getAttribute("lang")??void 0,Ne=re??I.getAttribute("label")??V.getAttribute("label")??void 0,$e=V.querySelector("BaseURL")?.textContent?.trim()??"",pe=new URL($e||o,e).toString(),Ce=V.getAttribute("mimeType")??k,pt=V.getAttribute("codecs")??R??"",Ke;if(C==="text"){let Pe=V.getAttribute("id")||"",ht=N.privateuse?.includes("x-auto")||Pe.includes("_auto"),Fe=V.querySelector("SegmentTemplate");if(Fe){let $t={representationId:V.getAttribute("id")??void 0,bandwidth:V.getAttribute("bandwidth")??void 0},Zt=parseInt(V.getAttribute("bandwidth")??"",10)/1e3,ei=parseInt(Fe.getAttribute("startNumber")??"",10)??1,ft=parseInt(Fe.getAttribute("timescale")??"",10),Ci=Fe.querySelectorAll("SegmentTimeline S")??[],mt=Fe.getAttribute("media");if(!mt)continue;let ti=[],ii=0,ri="",bt=0,Dt=ei,oe=0;for(let xe of Ci){let Xe=parseInt(xe.getAttribute("d")??"",10),he=parseInt(xe.getAttribute("r")??"",10)||0,Ue=parseInt(xe.getAttribute("t")??"",10);oe=Number.isFinite(Ue)?Ue:oe;let Je=Xe/ft*1e3,gt=oe/ft*1e3;for(let ke=0;ke<he+1;ke++){let qe=vi(mt,{...$t,segmentNumber:Dt.toString(10),segmentTime:(oe+ke*Xe).toString(10)}),St=(gt??0)+ke*Je,Vt=St+Je;Dt++,ti.push({time:{from:St,to:Vt},url:qe})}oe+=(he+1)*Xe,ii+=(he+1)*Je}bt=oe/ft*1e3,ri=vi(mt,{...$t,segmentNumber:Dt.toString(10),segmentTime:oe.toString(10)});let Ct={time:{from:bt,to:1/0},url:ri},Ve={type:"template",baseUrl:pe,segmentTemplateUrl:mt,initUrl:"",totalSegmentsDurationMs:ii,segments:ti,nextSegmentBeyondManifest:Ct,timescale:ft};Ke={id:Pe,kind:"text",segmentReference:Ve,profiles:[],duration:T,bitrate:Zt,mime:"",codecs:"",width:0,height:0,isAuto:ht}}else Ke={id:Pe,isAuto:ht,kind:"text",url:pe}}else{let Pe=V.getAttribute("contentType")??Ce?.split("/")[0]??C,ht=I.getAttribute("profiles")?.split(",")??[],Fe=parseInt(V.getAttribute("width")??"",10),$t=parseInt(V.getAttribute("height")??"",10),Zt=parseInt(V.getAttribute("bandwidth")??"",10)/1e3,ei=V.getAttribute("frameRate")??"",ft=V.getAttribute("quality")??void 0,Ci=ei?Xn(ei):void 0,mt=V.getAttribute("id")??"id"+(F++).toString(10),ti=Pe==="video"?`${$t}p`:Pe==="audio"?`${Zt}Kbps`:pt,ii=`${mt}@${ti}`,ri=[...G,...be,...ht],bt,Dt=V.querySelector("SegmentBase"),oe=V.querySelector("SegmentTemplate")??Te;if(Dt){let Ve=V.querySelector("SegmentBase Initialization")?.getAttribute("range")??"",[xe,Xe]=Ve.split("-").map(qe=>parseInt(qe,10)),he={from:xe,to:Xe},Ue=V.querySelector("SegmentBase")?.getAttribute("indexRange"),[Je,gt]=Ue?Ue.split("-").map(qe=>parseInt(qe,10)):[],ke=Ue?{from:Je,to:gt}:void 0;bt={type:"byteRange",url:pe,initRange:he,indexRange:ke}}else if(oe){let Ve={representationId:V.getAttribute("id")??void 0,bandwidth:V.getAttribute("bandwidth")??void 0},xe=parseInt(oe.getAttribute("timescale")??"",10),Xe=oe.getAttribute("initialization")??"",he=oe.getAttribute("media"),Ue=parseInt(oe.getAttribute("startNumber")??"",10)??1,Je=vi(Xe,Ve);if(!he)throw new ReferenceError("No media attribute in SegmentTemplate");let gt=oe.querySelectorAll("SegmentTimeline S")??[],ke=[],qe=0,St="",Vt=0;if(gt.length){let si=Ue,Ee=0;for(let vt of gt){let Re=parseInt(vt.getAttribute("d")??"",10),Ze=parseInt(vt.getAttribute("r")??"",10)||0,ai=parseInt(vt.getAttribute("t")??"",10);Ee=Number.isFinite(ai)?ai:Ee;let Vi=Re/xe*1e3,Co=Ee/xe*1e3;for(let ni=0;ni<Ze+1;ni++){let Vo=vi(he,{...Ve,segmentNumber:si.toString(10),segmentTime:(Ee+ni*Re).toString(10)}),Ur=(Co??0)+ni*Vi,Oo=Ur+Vi;si++,ke.push({time:{from:Ur,to:Oo},url:Vo})}Ee+=(Ze+1)*Re,qe+=(Ze+1)*Vi}Vt=Ee/xe*1e3,St=vi(he,{...Ve,segmentNumber:si.toString(10),segmentTime:Ee.toString(10)})}else if((0,Da.isNonNullable)(T)){let Ee=parseInt(oe.getAttribute("duration")??"",10)/xe*1e3,vt=Math.ceil(T/Ee),Re=0;for(let Ze=1;Ze<vt;Ze++){let ai=vi(he,{...Ve,segmentNumber:Ze.toString(10),segmentTime:Re.toString(10)});ke.push({time:{from:Re,to:Re+Ee},url:ai}),Re+=Ee}Vt=Re,St=vi(he,{...Ve,segmentNumber:vt.toString(10),segmentTime:Re.toString(10)})}let Do={time:{from:Vt,to:1/0},url:St};bt={type:"template",baseUrl:pe,segmentTemplateUrl:he,initUrl:Je,totalSegmentsDurationMs:qe,segments:ke,nextSegmentBeyondManifest:Do,timescale:xe}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!Pe||!Ce)continue;let Ct={video:"video",audio:"audio",text:"text"}[Pe];if(!Ct)continue;Ie||=Ct,Ke={id:ii,kind:Ct,segmentReference:bt,profiles:ri,duration:T,bitrate:Zt,mime:Ce,codecs:pt,width:Fe,height:$t,fps:Ci,quality:ft}}ce.language||=z,ce.label||=Ne,ce.mime||=Ce,ce.codecs||=pt,ce.hdr||=Ie==="video"&&Dr(pt),ce.representations.push(Ke)}if(Ie){let V=r[Ie].find(z=>z.id===ce.id);if(V&&ce.representations.every(z=>st(z.segmentReference)))for(let z of V.representations){let $e=ce.representations.find(Ce=>Ce.id===z.id)?.segmentReference,pe=z.segmentReference;pe.segments.push(...$e.segments),pe.nextSegmentBeyondManifest=$e.nextSegmentBeyondManifest}else r[Ie].push(ce)}}return{duration:T,streams:r,baseUrls:n,live:v}};var To=require("@vkontakte/videoplayer-shared");var vo=s=>{let e=[];for(let t=0;t<s.length;t++){let i=Math.floor(s.start(t)*1e3),r=Math.ceil(s.end(t)*1e3);e.push(i,r)}return e};var yo=class{constructor(e,t){this.lastUpdateTs=0;this.lastCallTs=0;this.prevRanges=[];this.subscription=new To.Subscription;this.mediaSource=e,this.sourceBuffer=t,this.subscription.add((0,To.fromEvent)(this.sourceBuffer,"updateend").subscribe(()=>this.updateend()))}updateend(){if(!Y(this.mediaSource,this.sourceBuffer))return;let{prevRanges:e}=this,t=vo(this.sourceBuffer.buffered);this.prevRanges=t,this.isRangesRemoved(e,t)&&(this.lastUpdateTs=Date.now())}isRangesRemoved(e,t){if(e.length!==t.length)return!0;for(let i=0;i<e.length;i+=2){let r=e[i],a=e[i+1],n=t[i],o=t[i+1];if(n>r||o<a)return!0}return!1}wasUpdated(){let{lastCallTs:e,lastUpdateTs:t}=this;return this.lastCallTs=Date.now(),e<=t}destroy(){this.subscription.unsubscribe()}};var Ca=class{constructor(e,t,i,{fetcher:r,tuning:a,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new A.ValueSubject(0);this.currentLowLatencySegmentLength$=new A.ValueSubject(0);this.currentSegmentLength$=new A.ValueSubject(0);this.onLastSegment$=new A.ValueSubject(!1);this.fullyBuffered$=new A.ValueSubject(!1);this.playingRepresentation$=new A.ValueSubject(void 0);this.playingRepresentationInit$=new A.ValueSubject(void 0);this.error$=new A.Subject;this.gaps=[];this.subscription=new A.Subscription;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new de;this.switchAbortController=new de;this.destroyAbortController=new de;this.bufferLimit=1/0;this.failedDownloads=0;this.baseUrls=[];this.baseUrlsIndex=0;this.isLive=!1;this.liveUpdateSegmentIndex=0;this.liveInitialAdditionalOffset=0;this.isSeekingLive=!1;this.index=0;this.lastDataObtainedTimestampMs=0;this.loadByteRangeSegmentsTimeoutId=0;this.sourceBufferBufferedDiff=null;this.startWith=(0,A.abortable)(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);(0,A.assertNonNullable)(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new wv(this.sourceBuffer),this.sourceBufferBufferedDiff=new yo(this.mediaSource,this.sourceBuffer),this.subscription.add((0,A.fromEvent)(this.sourceBuffer,"updateend").subscribe(()=>{this.maintain()})),this.subscription.add((0,A.fromEvent)(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:A.ErrorCategory.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o||!Y(this.mediaSource,this.sourceBuffer))return;let u=Math.min(this.bufferLimit,Lr(this.sourceBuffer.buffered)*.8);this.bufferLimit=u;let l=ze(this.sourceBuffer.buffered,o),p=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(o,n*2,l<p).catch(c=>{this.handleAsyncError(c,"pruneBuffer")})})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(n=>this.error$.next(n))),yield this.loadInit(t,"high",!0);let i=this.initData.get(t.id),r=this.segments.get(t.id),a=this.parsedInitData.get(t.id);(0,A.assertNonNullable)(i,"No init buffer for starting representation"),(0,A.assertNonNullable)(r,"No segments for starting representation"),i instanceof ArrayBuffer&&(this.searchGaps(r,t),yield this.sourceBufferTaskQueue.append(i,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(a))}.bind(this));this.switchTo=(0,A.abortable)(this.destroyAbortController.signal,async function*(e,t=!1){if(!Y(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);(0,A.assertNonNullable)(i,`No such representation ${e}`);let r=this.segments.get(e),a=this.initData.get(e);if((0,A.isNullable)(a)||(0,A.isNullable)(r)?yield this.loadInit(i,"high",!1):a instanceof Promise&&(yield a),r=this.segments.get(e),(0,A.assertNonNullable)(r,"No segments for starting representation"),a=this.initData.get(e),!(!a||!(a instanceof ArrayBuffer)||!this.sourceBuffer||!Y(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(a,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer();else{let n=this.getCurrentPosition();(0,A.isNonNullable)(n)&&!this.isLive&&(this.bufferLimit=1/0,await this.pruneBuffer(n,1/0,!0)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}this.maintain()}}.bind(this));this.switchToOld=(0,A.abortable)(this.destroyAbortController.signal,async function*(e,t=!1){if(!Y(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);(0,A.assertNonNullable)(i,`No such representation ${e}`);let r=this.segments.get(e),a=this.initData.get(e);if((0,A.isNullable)(a)||(0,A.isNullable)(r)?yield this.loadInit(i,"high",!1):a instanceof Promise&&(yield a),r=this.segments.get(e),(0,A.assertNonNullable)(r,"No segments for starting representation"),a=this.initData.get(e),!(!a||!(a instanceof ArrayBuffer)||!this.sourceBuffer||!Y(this.mediaSource,this.sourceBuffer)))if(yield this.abort(),yield this.sourceBufferTaskQueue.append(a,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer(),this.maintain();else{let n=this.getCurrentPosition();(0,A.isNonNullable)(n)&&(this.isLive||(this.bufferLimit=1/0,await this.pruneBuffer(n,1/0,!0)),this.maintain(n)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}}.bind(this));this.seekLive=(0,A.abortable)(this.destroyAbortController.signal,async function*(e){let t=(0,xo.default)(e,u=>u.representations)??[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let u of this.representations.keys()){let l=t.find(d=>d.id===u);l&&this.representations.set(u,l);let p=this.representations.get(u);if(!p||!st(p.segmentReference))return;let c=this.getActualLiveStartingSegments(p.segmentReference);this.segments.set(p.id,c)}let i=this.switchingToRepresentationId??this.downloadingRepresentationId,r=this.representations.get(i);(0,A.assertNonNullable)(r);let a=this.segments.get(i);(0,A.assertNonNullable)(a,"No segments for starting representation");let n=this.initData.get(i);if((0,A.assertNonNullable)(n,"No init buffer for starting representation"),!(n instanceof ArrayBuffer))return;let o=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,yield this.abort(),o&&(yield this.sourceBufferTaskQueue.remove(o.from*1e3,o.to*1e3,this.destroyAbortController.signal)),this.searchGaps(a,r),yield this.sourceBufferTaskQueue.append(n,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this));this.fetcher=r,this.tuning=a,this.compatibilityMode=u,this.forwardBufferTarget=a.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=o,this.isLive=!!l?.live,this.baseUrls=l?.baseUrls??[],this.initData=new Map(i.map(p=>[p.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(i.map(p=>[p.id,p])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}switchToWithPreviousAbort(e,t=!1){!Y(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new de,(0,A.abortable)(this.switchAbortController.signal,async function*(i,r=!1){this.switchingToRepresentationId=i;let a=this.representations.get(i);(0,A.assertNonNullable)(a,`No such representation ${i}`);let n=this.segments.get(i),o=this.initData.get(i);if((0,A.isNullable)(o)||(0,A.isNullable)(n)?yield this.loadInit(a,"high",!1):o instanceof Promise&&(yield o),n=this.segments.get(i),(0,A.assertNonNullable)(n,"No segments for starting representation"),o=this.initData.get(i),!(!(o instanceof ArrayBuffer)||!this.sourceBuffer||!Y(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();(0,A.isNonNullable)(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(){!(0,A.isNullable)(this.sourceBuffer)&&!this.sourceBuffer.updating&&(this.sourceBuffer.mode="segments")}async abort(){for(let e of this.activeSegments)this.abortSegment(e.segment);return this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new de,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if((0,A.isNullable)(e)||(0,A.isNullable)(this.downloadingRepresentationId)||(0,A.isNullable)(this.playingRepresentationId)||(0,A.isNullable)(this.sourceBuffer)||!Y(this.mediaSource,this.sourceBuffer)||(0,A.isNonNullable)(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if((0,A.assertNonNullable)(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;let r=i.find(p=>e>=p.time.from&&e<p.time.to);(0,A.isNonNullable)(r)&&isFinite(r.time.from)&&isFinite(r.time.to)&&this.currentSegmentLength$.next(r?.time.to-r.time.from);let a=e,n=100;if(this.playingRepresentationId!==this.downloadingRepresentationId){let p=ze(this.sourceBuffer.buffered,e),c=r?r.time.to+n:-1/0;r&&r.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&p>=r.time.to-e+n&&(a=c)}if(isFinite(this.bufferLimit)&&Lr(this.sourceBuffer.buffered)>=this.bufferLimit){let p=ze(this.sourceBuffer.buffered,e),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,p<c).catch(d=>{this.handleAsyncError(d,"pruneBuffer")});return}let u=null;if(!this.activeSegments.size&&(u=this.selectForwardBufferSegments(i,t.segmentReference.type,a),u?.length)){let p="auto";if(this.tuning.dash.useFetchPriorityHints&&r)if((0,Io.default)(u,r))p="high";else{let c=(0,Fr.default)(u,0);c&&c.time.from-r.time.to>=this.forwardBufferTarget/2&&(p="low")}this.loadSegments(u,t,p).catch(c=>{this.handleAsyncError(c,"loadSegments")})}(!this.preloadOnly&&!this.allInitsLoaded&&r&&r.status==="fed"&&!u?.length&&ze(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let l=(0,Fr.default)(i,-1);!this.isLive&&l&&(this.fullyBuffered$.next(l.time.to-e-ze(this.sourceBuffer.buffered,e)<n),this.onLastSegment$.next(e-l.time.from>0))}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}searchGaps(e,t){this.gaps=[];let i=0,r=this.isLive?this.liveInitialAdditionalOffset:0;for(let a of e)Math.trunc(a.time.from-i)>0&&this.gaps.push({representation:t.id,from:i,to:a.time.from+r,persistent:!0}),i=a.time.to;(0,A.isNonNullable)(t.duration)&&t.duration-i>0&&!this.isLive&&this.gaps.push({representation:t.id,from:i,to:t.duration,persistent:!0})}getActualLiveStartingSegments(e){let t=e.segments,i=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,r=[],a=0,n=t.length-1;do r.unshift(t[n]),a+=t[n].time.to-t[n].time.from,n--;while(a<i&&n>=0);return this.liveInitialAdditionalOffset=a-i,this.isActiveLowLatency()?[r[0]]:r}getLiveSegmentsToLoadState(e){let t=(0,xo.default)(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?.length)return{from:i[0].time.from,to:i[i.length-1].time.to}}updateLive(e){let t=(0,xo.default)(e?.streams[this.kind],i=>i.representations)??[];if(![...this.segments.values()].every(i=>!i.length))for(let i of t){if(!i||!st(i.segmentReference))return;let r=i.segmentReference.segments.map(l=>({...l,status:"none",size:void 0})),a=100,n=this.segments.get(i.id)??[],o=(0,Fr.default)(n,-1)?.time.to??0,u=r?.findIndex(l=>o>=l.time.from+a&&o<=l.time.to+a);if(u===-1){this.liveUpdateSegmentIndex=0;let l=this.getActualLiveStartingSegments(i.segmentReference);this.segments.set(i.id,l)}else{let l=r.slice(u+1);this.segments.set(i.id,[...n,...l])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;(0,A.assertNonNullable)(e);let t=this.segments.get(e);if(t?.length){let i=t[t.length-1];this.updateLowLatencyLiveIfNeeded(i)}}updateLowLatencyLiveIfNeeded(e){let t=0;for(let i of this.representations.values()){let r=i.segmentReference;if(!st(r))return;let a=this.segments.get(i.id);if(!a)continue;let n=a.find(u=>Math.floor(u.time.from)===Math.floor(e.time.from));if(n&&!isFinite(n.time.to)&&(n.time.to=e.time.to,t=n.time.to-n.time.from),!!!a.find(u=>Math.floor(u.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let u=Math.round(e.time.to*r.timescale/1e3).toString(10),l=vi(r.segmentTemplateUrl,{segmentTime:u});a.push({status:"none",time:{from:e.time.to,to:1/0},url:l})}}this.currentLowLatencySegmentLength$.next(t)}findSegmentStartTime(e){let t=this.switchingToRepresentationId??this.downloadingRepresentationId??this.playingRepresentationId;if(!t)return;let i=this.segments.get(t);return i?i.find(a=>a.time.from<=e&&a.time.to>=e)?.time.from??void 0:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),this.sourceBufferTaskQueue?.destroy(),this.sourceBufferBufferedDiff?.destroy(),this.gapDetectionIdleCallback&&Xt&&Xt(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&Xt&&Xt(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer)try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(e){if(!(e instanceof DOMException&&e.name==="NotFoundError"))throw e}this.sourceBuffer=null,this.downloadAbortController.abort(),this.switchAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,i){return this.checkEjectedSegments(),this.isLive?this.selectForwardBufferSegmentsLive(e,i):this.selectForwardBufferSegmentsRecord(e,t,i)}selectForwardBufferSegmentsLive(e,t){if(this.playingRepresentationId!==this.downloadingRepresentationId){let i=e.findIndex(r=>t>=r.time.from&&t<r.time.to);this.liveUpdateSegmentIndex=i}return this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):null}selectForwardBufferSegmentsRecord(e,t,i){let r=e.findIndex(({status:c,time:{from:d,to:h}},m)=>{let g=d<=i&&h>=i,v=d>i||g||m===0&&i===0,T=Math.min(this.forwardBufferTarget,this.bufferLimit),P=this.preloadOnly&&d<=i+T||h<=i+T;return(c==="none"||c==="partially_ejected"&&v&&P&&this.sourceBuffer&&Y(this.mediaSource,this.sourceBuffer)&&!(Ye(this.sourceBuffer.buffered,d)&&Ye(this.sourceBuffer.buffered,h)))&&v&&P});if(r===-1)return null;if(t!=="byteRange")return e.slice(r,r+1);let a=e,n=0,o=0,u=[],l=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,p=this.preloadOnly?this.forwardBufferTarget:0;for(let c=r;c<a.length&&(n<=l||o<=p);c++){let d=a[c];if(n+=d.byte.to+1-d.byte.from,o+=d.time.to+1-d.time.from,d.status==="none"||d.status==="partially_ejected")u.push(d);else break}return u}async loadSegments(e,t,i="auto"){st(t.segmentReference)?await this.loadTemplateSegment(e[0],t,i):await this.loadByteRangeSegments(e,t,i)}async loadTemplateSegment(e,t,i="auto"){e.status="downloading";let r={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(r);let{range:a,url:n,signal:o,onProgress:u,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(await(0,A.abortable)(o,async function*(){let p=(0,A.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>setTimeout(c,p))}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let p=await this.fetcher.fetch(n,{range:a,signal:o,onProgress:u,priority:i,isLowLatency:this.isActiveLowLatency()});if(this.lastDataObtainedTimestampMs=(0,A.now)(),!p)return;let c=new DataView(p),d=Ba(t.mime);if(!isFinite(r.segment.time.to)){let g=t.segmentReference.timescale;r.segment.time.to=d.getChunkEndTime(c,g)}u&&r.feedingBytes&&l?await Promise.all(l):await this.sourceBufferTaskQueue.append(c,o);let{serverDataReceivedTimestamp:h,serverDataPreparedTime:m}=d.getServerLatencyTimestamps(c);h&&m&&this.currentLiveSegmentServerLatency$.next(m-h),r.segment.status="downloaded",this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(p){this.abortActiveSegments([e]),$a(p)||(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())st(t.segmentReference)?t.segmentReference.baseUrl=e:t.segmentReference.url=e}async loadByteRangeSegments(e,t,i="auto"){if(!e.length)return;for(let u of e)u.status="downloading",this.activeSegments.add({segment:u,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:r,url:a,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(await(0,A.abortable)(n,async function*(){let u=(0,A.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),(0,A.fromEvent)(window,"online").pipe((0,A.once)()).subscribe(()=>{l(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(a,{range:r,onProgress:o,signal:n,priority:i}),this.lastDataObtainedTimestampMs=(0,A.now)(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),$a(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}prepareByteRangeFetchSegmentParams(e,t){if(st(t.segmentReference))throw new Error("Representation is not byte range type");let i=t.segmentReference.url,r={from:(0,Fr.default)(e,0).byte.from,to:(0,Fr.default)(e,-1).byte.to},{signal:a}=this.downloadAbortController;return{url:i,range:r,signal:a,onProgress:async(o,u)=>{if(!a.aborted)try{this.lastDataObtainedTimestampMs=(0,A.now)(),await this.onSomeByteRangesDataLoaded({dataView:o,loaded:u,signal:a,onSegmentAppendFailed:()=>this.abort(),globalFrom:r?r.from:0,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:A.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!st(t.segmentReference))throw new Error("Representation is not template type");let i=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&i.searchParams.set("low-latency","yes");let r=i.toString(),{signal:a}=this.downloadAbortController,n=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(l,p)=>{if(!a.aborted)try{this.lastDataObtainedTimestampMs=(0,A.now)();let c=this.onSomeTemplateDataLoaded({dataView:l,loaded:p,signal:a,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(c)}catch(c){this.error$.next({id:"SegmentFeeding",category:A.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:c})}}:void 0;return{url:r,signal:a,onProgress:u,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)(0,Io.default)(e,t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:r,signal:a}){if(!this.activeSegments.size||!Y(this.mediaSource,this.sourceBuffer))return;let n=this.representations.get(t);if(n)for(let o of this.activeSegments){let{segment:u}=o;if(o.representationId===t){if(a.aborted){r();continue}if(o.loadedBytes=i,o.loadedBytes>o.feedingBytes){let l=new DataView(e.buffer,e.byteOffset+o.feedingBytes,o.loadedBytes-o.feedingBytes),p=Ba(n.mime).parseFeedableSegmentChunk(l,this.isLive);p?.byteLength&&(u.status="partially_fed",o.feedingBytes+=p.byteLength,await this.sourceBufferTaskQueue.append(p),o.fedBytes+=p.byteLength)}}}}async onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:a,onSegmentAppendFailed:n}){if(!this.activeSegments.size||!Y(this.mediaSource,this.sourceBuffer))return;let o=this.representations.get(t);if(o)for(let u of this.activeSegments){if(u.representationId!==t)continue;if(a.aborted){await n();continue}let{segment:l}=u,p=l.byte.from-i,c=l.byte.to-i,d=c-p+1,h=p<r,m=c<=r;if(h){if(l.status==="downloading"&&m){l.status="downloaded";let g=new DataView(e.buffer,e.byteOffset+p,d);await this.sourceBufferTaskQueue.append(g,a)&&!a.aborted?this.onSegmentFullyAppended(u,t):await n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(l.status==="downloading"||l.status==="partially_fed")&&(u.loadedBytes=Math.min(d,r-p),u.loadedBytes>u.feedingBytes)){let g=new DataView(e.buffer,e.byteOffset+p+u.feedingBytes,u.loadedBytes-u.feedingBytes),v=u.loadedBytes===d?g:Ba(o.mime).parseFeedableSegmentChunk(g);v?.byteLength&&(l.status="partially_fed",u.feedingBytes+=v.byteLength,await this.sourceBufferTaskQueue.append(v,a)&&!a.aborted?(u.fedBytes+=v.byteLength,u.fedBytes===d&&this.onSegmentFullyAppended(u,t)):await n())}}}}onSegmentFullyAppended(e,t){if(!((0,A.isNullable)(this.sourceBuffer)||!Y(this.mediaSource,this.sourceBuffer))){!this.isLive&&W.browser.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(Ye(this.sourceBuffer.buffered,e.segment.time.from,100)&&Ye(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:A.ErrorCategory.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",Ac(e.segment)&&(e.segment.size=e.fedBytes);for(let i of this.representations.values()){if(i.id===t)continue;let r=this.segments.get(i.id);if(r)for(let a of r)a.status==="fed"&&Math.round(a.time.from)===Math.round(e.segment.time.from)&&Math.round(a.time.to)===Math.round(e.segment.time.to)&&(a.status="none")}this.isActiveLowLatency()&&this.updateLowLatencyLiveIfNeeded(e.segment),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,e.segment)}}abortSegment(e){e.status==="partially_fed"?e.status="partially_ejected":e.status!=="partially_ejected"&&(e.status="none");for(let t of this.activeSegments.values())if(t.segment===e){this.activeSegments.delete(t);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(let[r,a]of this.initData.entries()){let n=a instanceof Promise;t||=n,a===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let i=this.representations.get(e);i&&(this.initLoadIdleCallback=Mr(()=>(0,zv.default)(this.loadInit(i,"low",!1),()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",i=!1){let r=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!i&&this.failedDownloads>0?(0,A.abortable)(this.destroyAbortController.signal,async function*(){let o=(0,A.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,Ba(e.mime),r)).then(o=>{if(!o)return;let{init:u,dataView:l,segments:p}=o,c=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,c);let d=p;this.isLive&&st(e.segmentReference)&&(d=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,d),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:A.ErrorCategory.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n}async dropBuffer(){for(let e of this.segments.values())for(let t of e)t.status="none";await this.pruneBuffer(0,1/0,!0)}async pruneBuffer(e,t,i=!1){if(!this.sourceBuffer||!Y(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||(0,A.isNullable)(e))return!1;this.checkEjectedSegments();let r=[],a=0,n=o=>{if(a>=t)return;r.push({...o.time});let u=Ac(o)?o.size??0:o.byte.to-o.byte.from;a+=u};for(let o of this.segments.values())for(let u of o){let l=u.time.to<=e-this.tuning.dash.bufferPruningSafeZone,p=u.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(l||p)&&u.status==="fed"&&n(u)}for(let o=0;o<this.sourceBuffer.buffered.length;o++){let u=this.sourceBuffer.buffered.start(o)*1e3,l=this.sourceBuffer.buffered.end(o)*1e3,p=0;for(let c of this.segments.values())for(let d of c)(0,Io.default)(["none","partially_ejected"],d.status)&&Math.round(d.time.from)<=Math.round(u)&&Math.round(d.time.to)>=Math.round(l)&&p++;if(p===this.segments.size){let c={time:{from:u,to:l},url:"",status:"none"};n(c)}}if(r.length&&i){let o=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let u of this.segments.values())for(let l of u)l.time.from>=e+o&&l.status==="fed"&&n(l)}return r.length?(r=_v(r),(await Promise.all(r.map(u=>this.sourceBufferTaskQueue.remove(u.from,u.to)))).reduce((u,l)=>u||l,!1)):!1}async abortBuffer(){if(!this.sourceBuffer||!Y(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||!Y(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}getBufferedTo(){return!this.sourceBuffer||!Y(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length?null:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}getForwardBufferDuration(e=this.getCurrentPosition()){return!this.sourceBuffer||!Y(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||(0,A.isNullable)(e)?0:ze(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!this.sourceBuffer||!Y(this.mediaSource,this.sourceBuffer))return;let{buffered:i}=this.sourceBuffer;this.tuning.useRefactoredSearchGap&&(this.gaps=this.gaps.filter(a=>{if(a.persistent)return!0;let n=Math.round(a.from),o=Math.round(a.to);for(let u=0;u<i.length;u++)if(n>=Math.round(i.start(u)*1e3)&&o<=Math.round(i.end(u)*1e3))return!1;return!0}));let r={representation:e,from:t.time.from,to:t.time.to,persistent:!1};for(let a=0;a<i.length;a++){let n=i.start(a)*1e3,o=i.end(a)*1e3;if(!(o<=t.time.from||n>=t.time.to)){if(n<=t.time.from&&o>=t.time.to){r=void 0;break}o>t.time.from&&o<t.time.to&&(r.from=o),n<t.time.to&&n>t.time.from&&(r.to=n)}}r&&r.to-r.from>1&&!this.gaps.some(a=>r&&a.from===r.from&&a.to===r.to)&&this.gaps.push(r)}detectGapsWhenIdle(e,t){if(!(this.gapDetectionIdleCallback||!this.sourceBuffer||!Y(this.mediaSource,this.sourceBuffer))){if(!this.tuning.useRefactoredSearchGap)for(let i=0;i<this.sourceBuffer.buffered.length;i++)this.gaps=this.gaps.filter(r=>r.persistent||this.sourceBuffer&&(Math.round(r.from)<Math.round(this.sourceBuffer.buffered.start(i)*1e3)||Math.round(r.to)>Math.round(this.sourceBuffer.buffered.end(i)*1e3)));this.gapDetectionIdleCallback=Mr(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:A.ErrorCategory.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if((0,A.isNullable)(this.sourceBuffer)||!Y(this.mediaSource,this.sourceBuffer)||(0,A.isNullable)(this.playingRepresentationId)||this.sourceBufferBufferedDiff&&!this.sourceBufferBufferedDiff.wasUpdated())return;let e=vo(this.sourceBuffer.buffered),t=100;for(let i of this.segments.values())for(let r of i){let{status:a}=r;if(a!=="fed"&&a!=="partially_ejected")continue;let n=Math.floor(r.time.from),o=Math.ceil(r.time.to),u=!1,l=0;for(let p=0;p<e.length;p+=2){let c=e[p],d=e[p+1];u||(u=c-t<=n&&d+t>=o),(n>=c&&n<d-t||o>c+t&&o<=d)&&(l+=1)}u||(l===1?r.status="partially_ejected":this.gaps.some(p=>p.from===r.time.from||p.to===r.time.to)?r.status="partially_ejected":r.status="none")}}handleAsyncError(e,t){this.error$.next({id:t,category:A.ErrorCategory.VIDEO_PIPELINE,thrown:e,message:"Something went wrong"})}};var J=require("@vkontakte/videoplayer-shared");var wo=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:a=!1}){this.lastConnectionType$=new J.ValueSubject(void 0);this.lastConnectionReused$=new J.ValueSubject(void 0);this.lastRequestFirstBytes$=new J.ValueSubject(void 0);this.recoverableError$=new J.Subject;this.error$=new J.Subject;this.abortAllController=new de;this.subscription=new J.SubscriptionRemovable;this.fetchManifest=(0,J.abortable)(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=Li(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=to(i));let r=yield this.doFetch(i,{signal:this.abortAllController.signal}).catch(Eo);return r?(t.log("success",(0,J.flattenObject)({url:i,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(r.headers),r.text()):(t.error("error",(0,J.flattenObject)({url:i,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=(0,J.abortable)(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:i,onProgress:r,priority:a="auto",signal:n,measureThroughput:o=!0,isLowLatency:u=!1}={}){let l=e,p=new Headers,c=this.tracer.createComponentTracer("Fetch");if(i)switch(t){case 0:{p.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let k=new URL(l,location.href);k.searchParams.append("bytes",`${i.from}-${i.to}`),l=k.toString();break}default:(0,J.assertNever)(t)}this.requestQuic&&(l=Li(l));let d=this.abortAllController.signal,h;if(n){let k=new de;if(h=(0,J.merge)((0,J.fromEvent)(this.abortAllController.signal,"abort"),(0,J.fromEvent)(n,"abort")).subscribe(()=>{try{k.abort()}catch(R){Eo(R)}}),this.subscription.add(h),this.abortAllController.signal.aborted||n.aborted)try{k.abort()}catch(R){Eo(R)}d=k.signal}let m=(0,J.now)();c.log("startRequest",(0,J.flattenObject)({url:l,priority:a,rangeMethod:t,range:i,isLowLatency:u,requestStartedAt:m}));let g=yield this.doFetch(l,{priority:a,headers:p,signal:d}),v=(0,J.now)();if(!g)return c.error("error",{message:"No response in request"}),c.end(),this.unsubscribeAbortSubscription(h),null;if(this.throughputEstimator?.addRawRtt(v-m),!g.ok||!g.body){this.unsubscribeAbortSubscription(h);let k=`Fetch error ${g.status}: ${g.statusText}`;return c.error("error",{message:k}),c.end(),Promise.reject(new Error(`Fetch error ${g.status}: ${g.statusText}`))}if(this.onHeadersReceived(g.headers),!r&&!o){this.unsubscribeAbortSubscription(h);let k=(0,J.now)(),R={requestStartedAt:m,requestEndedAt:k,duration:k-m};return c.log("endRequest",(0,J.flattenObject)(R)),c.end(),g.arrayBuffer()}let T=g.body;if(o){let k;[T,k]=g.body.tee(),this.throughputEstimator?.trackStream(k,u)}let P=T.getReader(),x,L=parseInt(g.headers.get("content-length")??"",10);Number.isFinite(L)&&(x=L),!x&&i&&(x=i.to-i.from+1);let B=0,F=x?new Uint8Array(x):new Uint8Array(0),G=!1,$=k=>{this.unsubscribeAbortSubscription(h),G=!0,Eo(k)},D=(0,J.abortable)(d,async function*({done:k,value:R}){if(B===0&&this.lastRequestFirstBytes$.next((0,J.now)()-m),d.aborted){this.unsubscribeAbortSubscription(h);return}if(!k&&R){if(x)F.set(R,B),B+=R.byteLength;else{let C=new Uint8Array(F.length+R.length);C.set(F),C.set(R,F.length),F=C,B+=R.byteLength}r?.(new DataView(F.buffer),B),yield P?.read().then(D,$)}}.bind(this));yield P?.read().then(D,$),this.unsubscribeAbortSubscription(h);let I=(0,J.now)(),U={failed:G,requestStartedAt:m,requestEndedAt:I,duration:I-m};return G?(c.error("endRequest",(0,J.flattenObject)(U)),c.end(),null):(c.log("endRequest",(0,J.flattenObject)(U)),c.end(),F.buffer)}.bind(this));this.fetchByteRangeRepresentation=(0,J.abortable)(this.abortAllController.signal,async function*(e,t,i){if(e.type!=="byteRange")return null;let{from:r,to:a}=e.initRange,n=r,o=a,u=!1,l,p;e.indexRange&&(l=e.indexRange.from,p=e.indexRange.to,u=a+1===l,u&&(n=Math.min(l,r),o=Math.max(p,a))),n=Math.min(n,0);let c=yield this.fetch(e.url,{range:{from:n,to:o},priority:i,measureThroughput:!1});if(!c)return null;let d=new DataView(c,r-n,a-n+1);if(!t.validateData(d))throw new Error("Invalid media file");let h=t.parseInit(d),m=e.indexRange??t.getIndexRange(h);if(!m)throw new ReferenceError("No way to load representation index");let g;if(u)g=new DataView(c,m.from-n,m.to-m.from+1);else{let T=yield this.fetch(e.url,{range:m,priority:i,measureThroughput:!1});if(!T)return null;g=new DataView(T)}let v=t.parseSegments(g,h,m);return{init:h,dataView:new DataView(c),segments:v}}.bind(this));this.fetchTemplateRepresentation=(0,J.abortable)(this.abortAllController.signal,async function*(e,t){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=>({...n,status:"none",size:void 0})),dataView:new DataView(r)}:null}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=r,this.tracer=i.createComponentTracer("Fetcher"),this.useEnableSubtitlesParam=a}onHeadersReceived(e){let{type:t,reused:i}=eo(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}async fetchRepresentation(e,t,i="auto"){let{type:r}=e;switch(r){case"byteRange":return await this.fetchByteRangeRepresentation(e,t,i)??null;case"template":return await this.fetchTemplateRepresentation(e,i)??null;default:(0,J.assertNever)(r)}}destroy(){this.abortAllController.abort(),this.tracer.end(),this.subscription.unsubscribe()}async doFetch(e,t){let i=await Lt(e,t);if(i.ok)return i;let r=await i.text(),a=parseInt(r);if(!isNaN(a))switch(a){case 1:this.recoverableError$.next({id:"VideoDataLinkExpiredError",message:"Video data links have expired",category:J.ErrorCategory.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:J.ErrorCategory.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:J.ErrorCategory.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:J.ErrorCategory.FATAL});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${a})`,category:J.ErrorCategory.FATAL})}}unsubscribeAbortSubscription(e){e&&(e.unsubscribe(),this.subscription.remove(e))}},Eo=s=>{if(!$a(s))throw s};var Po=require("@vkontakte/videoplayer-shared");var Va=class s{constructor(e,t){this.currentRepresentation$=new Po.ValueSubject(null);this.maxRepresentations=4;this.representationsCursor=0;this.representations=[];this.currentSegment=null;this.getCurrentPosition=t.getCurrentPosition,this.processStreams(e)}updateLive(e){this.processStreams(e?.streams.text)}seekLive(e){this.processStreams(e)}maintain(e=this.getCurrentPosition()){if(!(0,Po.isNullable)(e))for(let t of this.representations)for(let i of t){let r=i.segmentReference,a=r.segments.length,n=r.segments[0].time.from,o=r.segments[a-1].time.to;if(e<n||e>o)continue;let u=r.segments.find(l=>l.time.from<=e&&l.time.to>=e);!u||this.currentSegment?.time.from===u.time.from&&this.currentSegment.time.to===u.time.to||(this.currentSegment=u,this.currentRepresentation$.next({...i,label:"Live Text",language:"ru",isAuto:!0,url:new URL(u.url,r.baseUrl).toString()}))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e??[]){let i=s.filterRepresentations(t.representations);if(i){this.representations[this.representationsCursor]=i,this.representationsCursor=(this.representationsCursor+1)%this.maxRepresentations;break}}}static isSupported(e){return!!e?.some(t=>s.filterRepresentations(t.representations))}static filterRepresentations(e){return e?.filter(t=>t.kind==="text"&&"segmentReference"in t&&st(t.segmentReference))}};var oL=["progress","play","seeked","stalled","waiting"],uL=["timeupdate","progress","loadeddata","playing","seeked"];var Ao=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new S.Subscription;this.representationSubscription=new S.Subscription;this.state$=new ie("none");this.currentVideoRepresentation$=new S.ValueSubject(void 0);this.currentVideoRepresentationInit$=new S.ValueSubject(void 0);this.currentAudioRepresentation$=new S.ValueSubject(void 0);this.currentVideoSegmentLength$=new S.ValueSubject(0);this.currentAudioSegmentLength$=new S.ValueSubject(0);this.error$=new S.Subject;this.lastConnectionType$=new S.ValueSubject(void 0);this.lastConnectionReused$=new S.ValueSubject(void 0);this.lastRequestFirstBytes$=new S.ValueSubject(void 0);this.currentLiveTextRepresentation$=new S.ValueSubject(null);this.isLive$=new S.ValueSubject(!1);this.isActiveLive$=new S.ValueSubject(!1);this.isLowLatency$=new S.ValueSubject(!1);this.liveDuration$=new S.ValueSubject(0);this.liveSeekableDuration$=new S.ValueSubject(0);this.liveAvailabilityStartTime$=new S.ValueSubject(0);this.liveStreamStatus$=new S.ValueSubject(void 0);this.bufferLength$=new S.ValueSubject(0);this.liveLatency$=new S.ValueSubject(void 0);this.liveLoadBufferLength$=new S.ValueSubject(0);this.livePositionFromPlayer$=new S.ValueSubject(0);this.currentStallDuration$=new S.ValueSubject(0);this.videoLastDataObtainedTimestamp$=new S.ValueSubject(0);this.fetcherRecoverableError$=new S.Subject;this.fetcherError$=new S.Subject;this.liveStreamEndTimestamp=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.forceEnded$=new S.Subject;this.gapWatchdogActive=!1;this.destroyController=new de;this.initManifest=(0,S.abortable)(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=Le(t,i,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),this.manifest?.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:S.ErrorCategory.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=(0,S.abortable)(this.destroyController.signal,async function*(){this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(n=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:S.ErrorCategory.NETWORK,message:"Failed to load manifest",thrown:n})});if(!e)return null;let t=null;try{t=jv(e??"",this.manifestUrlString)}catch(n){let o=Kn(e)??{id:"ManifestParsing",category:S.ErrorCategory.PARSER,message:"Failed to parse MPD manifest",thrown:n};this.error$.next(o)}if(!t)return null;let i=(n,o,u)=>!!(this.element?.canPlayType?.(o)&&wt()?.isTypeSupported?.(`${o}; codecs="${u}"`)||n==="text");if(t.live){this.isLive$.next(!!t.live);let{availabilityStartTime:n,latestSegmentPublishTime:o,streamIsUnpublished:u,streamIsAlive:l}=t.live,p=(t.duration??0)/1e3;this.liveSeekableDuration$.next(-1*p),this.liveDuration$.next((o-n)/1e3),this.liveAvailabilityStartTime$.next(t.live.availabilityStartTime);let c="active";l||(c=u?"unpublished":"unexpectedly_down"),this.liveStreamStatus$.next(c)}let r={text:t.streams.text,video:[],audio:[]};for(let n of["video","audio"]){let u=t.streams[n].filter(({mime:c,codecs:d})=>i(n,c,d)),l=new Set(u.map(({codecs:c})=>c)),p=co(l);if(p&&(r[n]=u.filter(({codecs:c})=>c.startsWith(p))),n==="video"){let c=this.tuning.preferHDR,d=r.video.some(m=>m.hdr),h=r.video.some(m=>!m.hdr);W.display.isHDR&&c&&d?r.video=r.video.filter(m=>m.hdr):h&&(r.video=r.video.filter(m=>!m.hdr))}}let a={...t,streams:r};return this.tracer.log("updateManifestEnd",(0,S.flattenObject)(a)),a}.bind(this));this.initRepresentations=(0,S.abortable)(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initRepresentationsStart",(0,S.flattenObject)({initialVideo:e,initialAudio:t,sourceHls:i})),(0,S.assertNonNullable)(this.manifest),(0,S.assertNonNullable)(this.element),this.representationSubscription.unsubscribe(),this.representationSubscription=new S.Subscription,this.state$.startTransitionTo("representations_ready");let r=d=>{this.representationSubscription.add((0,S.fromEvent)(d,"error").pipe((0,S.filter)(h=>!!this.element?.played.length)).subscribe(h=>{this.error$.next({id:"VideoSource",category:S.ErrorCategory.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:h})}))};this.source=this.tuning.useManagedMediaSource?Cn():new MediaSource;let a=document.createElement("source");if(r(a),a.src=URL.createObjectURL(this.source),this.element.appendChild(a),this.tuning.useManagedMediaSource&&xr())if(i){let d=document.createElement("source");r(d),d.type="application/x-mpegurl",d.src=i.url,this.element.appendChild(d)}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((d,h)=>[...d,...h.representations],[]);if(this.videoBufferManager=new Ca("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],(0,S.isNonNullable)(t)){let d=this.manifest.streams.audio.reduce((h,m)=>[...h,...m.representations],[]);this.audioBufferManager=new Ca("audio",this.source,d,n),this.bufferManagers.push(this.audioBufferManager)}Va.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new Va(this.manifest.streams.text,n)),this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$));let u=()=>{this.stallWatchdogSubscription?.unsubscribe(),this.currentStallDuration$.next(0)};if(this.representationSubscription.add((0,S.merge)(...uL.map(d=>(0,S.fromEvent)(this.element,d))).pipe((0,S.map)(d=>this.element?ze(this.element.buffered,this.element.currentTime*1e3):0),(0,S.filterChanged)(),(0,S.tap)(d=>{d>this.tuning.dash.bufferEmptinessTolerance&&u()})).subscribe(this.bufferLength$)),this.representationSubscription.add((0,S.merge)((0,S.fromEvent)(this.element,"ended"),this.forceEnded$).subscribe(()=>{u()})),this.isLive$.getValue()){this.subscription.add(this.liveDuration$.pipe((0,S.filterChanged)()).subscribe(h=>this.liveStreamEndTimestamp=(0,S.now)())),this.subscription.add((0,S.fromEvent)(this.element,"pause").subscribe(()=>{this.livePauseWatchdogSubscription=(0,S.interval)(1e3).subscribe(h=>{let m=wi(this.manifestUrlString,2);this.manifestUrlString=Le(this.manifestUrlString,m+1e3,2),this.liveStreamStatus$.getValue()==="active"&&this.updateManifest()}),this.subscription.add(this.livePauseWatchdogSubscription)})).add((0,S.fromEvent)(this.element,"play").subscribe(h=>this.livePauseWatchdogSubscription?.unsubscribe())),this.representationSubscription.add((0,S.combine)({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe((0,S.map)(({isActiveLive:h,isLowLatency:m})=>h&&m),(0,S.filterChanged)()).subscribe(h=>{this.isManualDecreasePlaybackInLive()||Vr(this.element,1)})),this.representationSubscription.add((0,S.combine)({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe((0,S.filter)(({bufferLength:h,isActiveLive:m,isLowLatency:g})=>m&&g&&!!h)).subscribe(({bufferLength:h})=>this.liveBuffer.next(h))),this.representationSubscription.add(this.videoBufferManager.currentLowLatencySegmentLength$.subscribe(h=>{if(!this.isActiveLive$.getValue()&&!this.isLowLatency$.getValue()&&!h)return;let m=this.liveSeekableDuration$.getValue()-h/1e3;this.liveSeekableDuration$.next(Math.max(m,-1*this.tuning.dashCmafLive.maxLiveDuration)),this.liveDuration$.next(this.liveDuration$.getValue()+h/1e3)})),this.representationSubscription.add((0,S.combine)({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe((0,S.filter)(({isLive:h})=>h),(0,S.filterChanged)((h,m)=>m.bufferLength<h.bufferLength),(0,S.map)(({rtt:h,bufferLength:m,segmentServerLatency:g})=>{let v=wi(this.manifestUrlString,2);return(h/2+m+g+v)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add((0,S.combine)({liveBuffer:this.liveBuffer.smoothed$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).subscribe(({liveBuffer:h,isActiveLive:m,isLowLatency:g})=>{if(!g||!m)return;let v=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,T=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,P=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,x=h-v;if(this.isManualDecreasePlaybackInLive())return;let L=1;Math.abs(x)>T&&(L=1+Math.sign(x)*P),Vr(this.element,L)})),this.representationSubscription.add(this.bufferLength$.subscribe(h=>{let m=0;if(h){let g=(this.element?.currentTime??0)*1e3;m=Math.min(...this.bufferManagers.map(T=>T.getLiveSegmentsToLoadState(this.manifest)?.to??g))-g}this.liveLoadBufferLength$.getValue()!==m&&this.liveLoadBufferLength$.next(m)}));let d=0;this.representationSubscription.add((0,S.combine)({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe((0,S.throttle)(1e3)).subscribe(async({liveLoadBufferLength:h,bufferLength:m})=>{if(!this.element||this.isUpdatingLive)return;let g=this.element.playbackRate,v=wi(this.manifestUrlString,2),T=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,P=Math.min(T,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*g),x=this.tuning.dashCmafLive.normalizedActualBufferOffset*g,L=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*g,B=isFinite(h)?h:m,F=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),G=T<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next(G);let $="none";if(F?$="active_low_latency":this.isLowLatency$.getValue()&&G?(this.bufferManagers.forEach(D=>D.proceedLowLatencyLive()),$="active_low_latency"):v!==0&&B<P?$="live_forward_buffering":B<P+L&&($="live_with_target_offset"),isFinite(h)&&(d=h>d?h:d),$==="live_forward_buffering"||$==="live_with_target_offset"){let D=d-(P+x),I=this.normolizeLiveOffset(Math.trunc(v+D/g)),U=Math.abs(I-v),k=0;!h||U<=this.tuning.dashCmafLive.offsetCalculationError?k=v:I>0&&U>this.tuning.dashCmafLive.offsetCalculationError&&(k=I),this.manifestUrlString=Le(this.manifestUrlString,k,2)}($==="live_with_target_offset"||$==="live_forward_buffering")&&(d=0,await this.updateLive())},h=>{this.error$.next({id:"updateLive",category:S.ErrorCategory.VIDEO_PIPELINE,thrown:h,message:"Failed to update live with subscription"})}))}let l=(0,S.merge)(...this.bufferManagers.map(d=>d.fullyBuffered$)).pipe((0,S.map)(()=>this.bufferManagers.every(d=>d.fullyBuffered$.getValue()))),p=(0,S.merge)(...this.bufferManagers.map(d=>d.onLastSegment$)).pipe((0,S.map)(()=>this.bufferManagers.some(d=>d.onLastSegment$.getValue()))),c=(0,S.combine)({allBuffersFull:l,someBufferEnded:p}).pipe((0,S.filterChanged)(),(0,S.map)(({allBuffersFull:d,someBufferEnded:h})=>d&&h),(0,S.filter)(d=>d));if(this.representationSubscription.add((0,S.merge)(this.forceEnded$,c).subscribe(()=>{if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(d=>!d.updating))try{this.source?.endOfStream()}catch(d){this.error$.next({id:"EndOfStream",category:S.ErrorCategory.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:d})}})),this.representationSubscription.add((0,S.merge)(...this.bufferManagers.map(d=>d.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 d=this.tuning.dash.sourceOpenTimeout>=0;yield new Promise(h=>{d&&(this.timeoutSourceOpenId=setTimeout(()=>{if(this.source?.readyState==="open"){h();return}this.error$.next({id:"OpenOfStream",category:S.ErrorCategory.VIDEO_PIPELINE,message:"Failed to open MediaSource",thrown:new Error("Timeout reject when wait sourceopen event"),traceAsLog:!0})},this.tuning.dash.sourceOpenTimeout)),this.source?.addEventListener("sourceopen",()=>{this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),h()},{once:!0})})}if(!this.isLive$.getValue()){let d=[this.manifest.duration??0,...(0,Bc.default)((0,Bc.default)([...this.manifest.streams.audio,...this.manifest.streams.video],h=>h.representations),h=>{let m=[];return h.duration&&m.push(h.duration),st(h.segmentReference)&&h.segmentReference.totalSegmentsDurationMs&&m.push(h.segmentReference.totalSegmentsDurationMs),m})];this.source.duration=Math.max(...d)/1e3}this.audioBufferManager&&(0,S.isNonNullable)(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=()=>{if(!this.element||!this.videoBufferManager||this.source?.readyState!=="open")return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),this.audioBufferManager?.maintain(e),this.liveTextManager?.maintain(e),(this.videoBufferManager.gaps.length||this.audioBufferManager?.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=(0,S.interval)(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),t=>{this.error$.next({id:"GapWatchdog",category:S.ErrorCategory.WTF,message:"Error handling gaps",thrown:t})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name),this.fetcher=new wo({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=bi.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.bufferEstimator}),this.initTracerSubscription()}async seekLive(e){(0,S.assertNonNullable)(this.element);let t=this.liveStreamStatus$.getValue()!=="active"?(0,S.now)()-this.liveStreamEndTimestamp:0,i=this.normolizeLiveOffset(e+t);this.isActiveLive$.next(i===0),this.manifestUrlString=Le(this.manifestUrlString,i,2),this.manifest=await this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,await this.videoBufferManager?.seekLive(this.manifest.streams.video),await this.audioBufferManager?.seekLive(this.manifest.streams.audio),this.liveTextManager?.seekLive(this.manifest.streams.text))}initBuffer(){(0,S.assertNonNullable)(this.element),this.state$.setState("running");let e=(0,S.fromEvent)(this.element,"timeupdate");this.tuning.dash.timeupdateEventTickThrottle&&(e=e.pipe((0,S.throttle)(this.tuning.dash.timeupdateEventTickThrottle))),this.subscription.add((0,S.merge)(...oL.map(t=>(0,S.fromEvent)(this.element,t)),(0,S.fromEvent)(window,"online"),e).subscribe(()=>this.tick(),t=>{this.error$.next({id:"DashVKPlayer",category:S.ErrorCategory.WTF,message:"Internal logic error",thrown:t})})),this.subscription.add((0,S.fromEvent)(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===HTMLMediaElement.HAVE_CURRENT_DATA&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add((0,S.fromEvent)(this.element,"waiting").subscribe(()=>{this.element&&this.element.readyState===HTMLMediaElement.HAVE_CURRENT_DATA&&!this.element.seeking&&Ye(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let t=()=>{if(!this.element||this.source?.readyState!=="open")return;let i=this.currentStallDuration$.getValue();i+=50,this.currentStallDuration$.next(i);let r={timeInWaiting:i},a=(0,S.now)(),n=100,o=this.videoBufferManager?.lastDataObtainedTimestamp??0;this.videoLastDataObtainedTimestamp$.next(o);let u=this.audioBufferManager?.lastDataObtainedTimestamp??0,l=this.videoBufferManager?.getForwardBufferDuration()??0,p=this.audioBufferManager?.getForwardBufferDuration()??0,c=l<n&&a-o>this.tuning.dash.crashOnStallTWithoutDataTimeout,d=this.audioBufferManager&&p<n&&a-u>this.tuning.dash.crashOnStallTWithoutDataTimeout;if((c||d)&&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 h=this.normolizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);this.seekLive(h).catch(m=>{this.error$.next({id:"stallIntervalCallback",category:S.ErrorCategory.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:m})}),r.liveLastOffset=h}else{let h=this.element.currentTime*1e3;this.videoBufferManager?.maintain(h),this.audioBufferManager?.maintain(h),r.position=h}this.tracer.log("stallIntervalCallback",(0,S.flattenObject)(r))};this.stallWatchdogSubscription?.unsubscribe(),this.stallWatchdogSubscription=(0,S.interval)(50).subscribe(t,i=>{this.error$.next({id:"StallWatchdogCallback",category:S.ErrorCategory.NETWORK,message:"Can't restore DASH after stall.",thrown:i})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t,i=!1){let r={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return this.tuning.useNewSwitchTo?this.currentStallDuration$.getValue()>0?r?.switchToWithPreviousAbort(t,i):r?.switchTo(t,i):r?.switchToOld(t,i)}async seek(e,t){(0,S.assertNonNullable)(this.element),(0,S.assertNonNullable)(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(this.videoBufferManager.findSegmentStartTime(e)??e,this.audioBufferManager?.findSegmentStartTime(e)??e),this.warmUpMediaSourceIfNeeded(i),Ye(this.element.buffered,i)||await Promise.all([this.videoBufferManager.abort(),this.audioBufferManager?.abort()]),!((0,S.isNullable)(this.element)||(0,S.isNullable)(this.videoBufferManager))&&(this.videoBufferManager.maintain(i),this.audioBufferManager?.maintain(i),this.element.currentTime=i/1e3,this.tracer.log("seek",(0,S.flattenObject)({requestedPosition:e,forcePrecise:t,position:i})))}warmUpMediaSourceIfNeeded(e=this.element?.currentTime){(0,S.isNonNullable)(this.element)&&(0,S.isNonNullable)(this.source)&&(0,S.isNonNullable)(e)&&this.source?.readyState==="ended"&&this.element.duration*1e3-e>this.tuning.dash.seekBiasInTheEnd&&this.bufferManagers.forEach(t=>t.warmUpMediaSource())}get isStreamEnded(){return this.source?.readyState==="ended"}stop(){this.tracer.log("stop"),this.element?.querySelectorAll("source").forEach(e=>{URL.revokeObjectURL(e.src),e.remove()}),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),this.videoBufferManager?.destroy(),this.videoBufferManager=null,this.audioBufferManager?.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getStreams(){return this.manifest?.streams}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),this.source?.readyState==="open"&&Array.from(this.source.sourceBuffers).every(e=>!e.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}initTracerSubscription(){let e=(0,S.getTraceSubscriptionMethod)(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}async updateLive(){this.isUpdatingLive=!0,this.manifest=await this.updateManifest(),this.manifest&&(this.bufferManagers?.forEach(e=>e.updateLive(this.manifest)),this.liveTextManager?.updateLive(this.manifest)),this.isUpdatingLive=!1}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.getBufferedTo();if(e===null)return;let t=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),i=this.isJumpGapAfterSeekLive,r=this.element.currentTime;this.isJumpGapAfterSeekLive&&!t&&this.element.currentTime>e&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let a=this.element.currentTime*1e3,n=null,o=this.element.readyState===HTMLMediaElement.HAVE_METADATA?this.tuning.endGapTolerance:0;for(let u of this.bufferManagers)for(let l of u.gaps)(l.persistent||u.playingRepresentation$.getValue()===l.representation)&&l.from-o<=a&&l.to+o>a&&(this.element.duration*1e3-l.to<this.tuning.endGapTolerance?n=1/0:(n===null||l.to>n)&&(n=l.to));if(n!==null){let u=n+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,u===1/0?this.forceEnded$.next():(this.element.currentTime=u/1e3,this.tracer.log("jumpGap",(0,S.flattenObject)({isJumpGapAfterSeekLive:i,isActiveLowLatency:t,initialCurrentTime:r,jumpTo:u,resultCurrentTime:this.element.currentTime})))}}};var dt=require("@vkontakte/videoplayer-shared"),ko=class{constructor(){this.subscription=new dt.Subscription;this.pipSize$=new dt.ValueSubject(void 0);this.videoSize$=new dt.ValueSubject(void 0);this.elementSize$=new dt.ValueSubject(void 0);this.pictureInPictureWindowRemoveEventListener=dt.noop}connect({observableVideo:e,video:t}){let i=r=>{let a=r.target;this.pipSize$.next({width:a.width,height:a.height})};this.subscription.add((0,dt.observeElementSize)(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((0,dt.combine)({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe((0,dt.map)(({videoSize:r,inPip:a,pipSize:n})=>a?n:r)).subscribe(this.elementSize$))}getValue(){return this.elementSize$.getValue()}subscribe(e,t){return this.elementSize$.subscribe(e,t)}getObservable(){return this.elementSize$}destroy(){this.pictureInPictureWindowRemoveEventListener(),this.subscription.unsubscribe()}};var ir=class{constructor(e){this.subscription=new ee.Subscription;this.videoState=new ie("stopped");this.droppedFramesManager=new Ar;this.stallsManager=new bo;this.elementSizeManager=new ko;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new ki;this.audioTrackSwitchHistory=new ki;this.selectedRepresentations={audio:null,video:null};this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(r.state==="requested"&&i?.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"),_(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"),_(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="ready"&&_(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?.to==="playing"&&_(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&_(this.params.desiredState.playbackState,"paused");return;default:return(0,ee.assertNever)(e)}}};this.init3DScene=e=>{if(this.scene3D)return;this.scene3D=new Or(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:e.projectionData?.pose.yaw||0,y:e.projectionData?.pose.pitch||0,z:e.projectionData?.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 Rt(e.source.url),this.params=e,this.video=at(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(We(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 Ao({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=ut(this.video);this.subscription.add(()=>i.destroy());let r=this.constructor.name,a=o=>{e.error$.next({id:r,category:ee.ErrorCategory.WTF,message:`${r} internal logic error`,thrown:o})};return{output:e,desiredState:t,observableVideo:i,genericErrorListener:a,connect:(o,u)=>this.subscription.add(o.subscribe(u,a))}}subscribe(){let{output:e,desiredState:t,observableVideo:i,genericErrorListener:r,connect:a}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe((0,ee.filter)(c=>!!c.length),(0,ee.once)()).subscribe(c=>{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:c})}));let n=this.params.desiredState.seekState.stateChangeEnded$.pipe((0,ee.map)(c=>c.to.state!=="none"),(0,ee.filterChanged)());this.stallsManager.init({isSeeked$:n,currentStallDuration$:this.player.currentStallDuration$,videoLastDataObtainedTimestamp$:this.player.videoLastDataObtainedTimestamp$,throughput$:this.params.dependencies.throughputEstimator.throughput$,rtt$:this.params.dependencies.throughputEstimator.rtt$,tuning:this.params.tuning.stallsManager,abrParams:this.params.tuning.autoTrackSelection,isBuffering$:i.isBuffering$,looped$:i.looped$,playing$:i.playing$}),a(i.ended$,e.endedEvent$),a(i.looped$,e.loopedEvent$),a(i.error$,e.error$),a(i.isBuffering$,e.isBuffering$),a(i.currentBuffer$,e.currentBuffer$),a(i.playing$,e.firstFrameEvent$),a(i.canplay$,e.canplay$),a(i.inPiP$,e.inPiP$),a(i.inFullscreen$,e.inFullscreen$),a(i.loadedMetadata$,e.loadedMetadataEvent$),a(this.player.error$,e.error$),a(this.player.fetcherRecoverableError$,e.fetcherRecoverableError$),a(this.player.fetcherError$,e.fetcherError$),a(this.player.lastConnectionType$,e.httpConnectionType$),a(this.player.lastConnectionReused$,e.httpConnectionReused$),a(this.player.isLive$,e.isLive$),a(this.player.lastRequestFirstBytes$.pipe((0,ee.filter)(ee.isNonNullable),(0,ee.once)()),e.firstBytesEvent$),a(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),a(this.videoState.stateChangeEnded$.pipe((0,ee.map)(c=>c.to)),this.params.output.playbackState$),this.subscription.add(i.looped$.subscribe(()=>this.player.warmUpMediaSourceIfNeeded(),r)),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(Wt(this.video,t.isLooped,r)),this.subscription.add(ot(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(kt(this.video,t.playbackRate,i.playbackRateState$,r)),this.elementSizeManager.connect({video:this.video,observableVideo:i}),a(Mt(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),_(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),_(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:c})=>{if(c==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let d=this.player.getStreams();if((0,ee.assertNonNullable)(d,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let m=[];for(let g of d.audio){m.push(wc(g));let v=[];for(let T of g.representations){let P=Cv(T);v.push(P),this.audioTracksMap.set(P,{stream:g,representation:T})}this.audioStreamsMap.set(g,v)}this.params.output.availableAudioStreams$.next(m)}let h=[];for(let m of d.video){h.push(Pc(m));let g=[];for(let v of m.representations){let T=Dv({...v,streamId:m.id});T&&(g.push(T),this.videoTracksMap.set(T,{stream:m,representation:v}))}this.videoStreamsMap.set(m,g)}this.params.output.availableVideoStreams$.next(h);for(let m of d.text)for(let g of m.representations){let v=Vv(m,g);this.textTracksMap.set(v,{stream:m,representation:g})}this.params.output.availableVideoTracks$.next(Array.from(this.videoTracksMap.keys())),this.params.output.availableAudioTracks$.next(Array.from(this.audioTracksMap.keys())),this.params.output.isAudioAvailable$.next(!!this.audioTracksMap.size),this.audioTracksMap.size&&this.textTracksMap.size&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else c==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},r));let{vktvAbrThrottle:o}=this.params.tuning.dash,u=o&&Fv(o)||null;this.subscription.add((0,ee.merge)(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$,(0,ee.fromEvent)(this.video,"progress")).pipe((0,ee.filter)(()=>this.videoTracksMap.size>0)).subscribe(async()=>{let c=this.player.state$.getState(),d=this.player.state$.getTransition();if(c!=="manifest_ready"&&c!=="running"||d||c==="running"&&u&&!u())return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState()),this.selectVideoAudioRepresentations();let{video:h,audio:m}=this.selectedRepresentations;if(!h)return;let g=tr(this.videoTracksMap.keys(),T=>this.videoTracksMap.get(T)?.representation.id===h.id);(0,ee.isNonNullable)(g)&&(this.stallsManager.lastVideoTrackSelected=g);let v=this.params.desiredState.autoVideoTrackLimits.getTransition();if(v&&this.params.output.autoVideoTrackLimits$.next(v.to),c==="manifest_ready")await this.player.initRepresentations(h.id,m?.id,this.params.sourceHls);else if(await this.player.switchRepresentation("video",h.id),m){let T=!!t.audioStream.getTransition();await this.player.switchRepresentation("audio",m.id,T)}},r)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:c})=>{this.scene3D&&c&&this.scene3D.pointCameraTo(c.x,c.y)})),this.subscription.add(this.elementSizeManager.subscribe(c=>{this.scene3D&&c&&this.scene3D.setViewportSize(c.width,c.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe((0,ee.filterChanged)()).subscribe(c=>{let d=tr(this.videoTracksMap.entries(),([,{representation:v}])=>v.id===c);if(!d){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[h,{stream:m}]=d,g=this.params.desiredState.videoStream.getTransition();g&&g.to&&g.to.id===m.id&&this.params.desiredState.videoStream.setState(g.to),e.currentVideoTrack$.next(h),e.currentVideoStream$.next(Pc(m))},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe((0,ee.filterChanged)()).subscribe(c=>{let d=tr(this.audioTracksMap.entries(),([,{representation:v}])=>v.id===c);if(!d){e.currentAudioStream$.next(void 0);return}let[h,{stream:m}]=d,g=this.params.desiredState.audioStream.getTransition();g&&g.to&&g.to.id===m.id&&this.params.desiredState.audioStream.setState(g.to),e.currentAudioStream$.next(wc(m))},r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(c=>{if(c?.is3dVideo&&this.params.tuning.spherical?.enabled)try{this.init3DScene(c),e.is3DVideo$.next(!0)}catch(d){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${d}`})}else this.destroy3DScene(),this.params.tuning.spherical?.enabled&&e.is3DVideo$.next(!1)},r)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,r)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,r)),this.textTracksManager.connect(this.video,t,e);let l=t.playbackState.stateChangeStarted$.pipe((0,ee.map)(({to:c})=>c==="ready"),(0,ee.filterChanged)());this.subscription.add((0,ee.merge)(l,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,(0,ee.observableFrom)(["init"])).subscribe(()=>{let c=t.autoVideoTrackSwitching.getState(),h=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:c?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(h)})),this.subscription.add((0,ee.merge)(l,this.player.state$.stateChangeEnded$,(0,ee.observableFrom)(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let p=(0,ee.merge)(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,ee.observableFrom)(["init"])).pipe((0,ee.debounce)(0));this.subscription.add(p.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?gs:bs,t=this.params.tuning.useNewAutoSelectVideoTrack?zn:jn,i=this.params.tuning.useNewAutoSelectVideoTrack?Yt:Hn,{desiredState:r,output:a}=this.params,n=r.autoVideoTrackSwitching.getState(),o=r.videoTrack.getState()?.id,u=tr(this.videoTracksMap.keys(),$=>$.id===o),l=a.currentVideoTrack$.getValue(),p=r.videoStream.getState()??(u&&this.videoTracksMap.get(u)?.stream)??this.videoStreamsMap.size===1?this.videoStreamsMap.keys().next().value:void 0;if(!p)return;let c=tr(this.videoStreamsMap.keys(),$=>$.id===p.id),d=c&&this.videoStreamsMap.get(c);if(!d)return;let h=ze(this.video.buffered,this.video.currentTime*1e3),m;this.player.isActiveLive$.getValue()?m=this.player.isLowLatency$.getValue()?this.params.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.params.tuning.dashCmafLive.normalizedLiveMinBufferSize:this.player.isLive$.getValue()?m=this.params.tuning.dashCmafLive.normalizedTargetMinBufferSize:m=n?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;let g=(this.video.duration*1e3||1/0)-this.video.currentTime*1e3,v=Math.min(h/Math.min(m,g||1/0),1),T=r.audioStream.getState()??(this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0),P=T?.id&&tr(this.audioStreamsMap.keys(),$=>$.id===T.id)||this.audioStreamsMap.keys().next().value,x=0;if(P){if(u&&!n){let $=e(u,d,this.audioStreamsMap.get(P)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);x=Math.max(x,$?.bitrate??-1/0)}if(l){let $=e(l,d,this.audioStreamsMap.get(P)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);x=Math.max(x,$?.bitrate??-1/0)}}let L=u;(n||!L)&&(L=i(d,{container:this.elementSizeManager.getValue(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.stallsManager.abrTuningParams,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:x,forwardBufferHealth:v,current:l,visible:this.params.output.elementVisible$.getValue(),history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,stallsVideoMaxQualityLimit:this.stallsManager.videoMaxQualityLimit,stallsPredictedThroughput:this.stallsManager.predictedThroughput,abrLogger:this.params.dependencies.abrLogger}));let B=P&&t(L,d,this.audioStreamsMap.get(P)??[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.stallsManager.abrTuningParams,forwardBufferHealth:v,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),F=this.videoTracksMap.get(L)?.representation,G=B&&this.audioTracksMap.get(B)?.representation;F&&G?(this.selectedRepresentations.video=F,this.selectedRepresentations.audio=G):F&&!G&&this.audioTracksMap.size===0&&(this.selectedRepresentations.video=F,this.selectedRepresentations.audio=null)}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){lt(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),_(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:ee.ErrorCategory.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),nt(this.video),this.tracer.end()}};var Oa=class extends ir{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)}};var me=require("@vkontakte/videoplayer-shared");var _a=class extends ir{constructor(e){super(e),this.textTracksManager.destroy()}subscribe(){super.subscribe();let e=-1,{output:t,observableVideo:i,desiredState:r,connect:a}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),a(i.timeUpdate$,t.liveBufferTime$),a(this.player.liveSeekableDuration$,t.duration$),a(this.player.liveLatency$,t.liveLatency$);let n=new me.ValueSubject(1);a(i.playbackRateState$,n),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(r.isLowLatency.stateChangeEnded$.pipe((0,me.map)(o=>o.to)).subscribe(this.player.isLowLatency$)).add((0,me.combine)({liveBufferTime:t.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe((0,me.map)(({liveBufferTime:o,liveAvailabilityStartTime:u})=>o&&u?o+u:void 0)).subscribe(t.liveTime$)).add(this.player.liveStreamStatus$.pipe((0,me.filter)(o=>(0,me.isNonNullable)(o))).subscribe(o=>t.isLiveEnded$.next(o!=="active"&&t.position$.getValue()===0))).add((0,me.combine)({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:(0,me.merge)(i.playbackRateState$,new me.ValueSubject(1))}).pipe((0,me.filter)(({liveStreamStatus:o,liveDuration:u})=>o==="active"&&!!u)).subscribe(({liveDuration:o,playbackRate:u})=>{let l=t.liveBufferTime$.getValue(),p=t.position$.getValue(),{playbackCatchupSpeedup:c}=this.params.tuning.dashCmafLive.lowLatency;p||u<1-c||this.video.paused||(0,me.isNullable)(l)||(e=o-l)})).add((0,me.combine)({time:t.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:(0,me.merge)(i.playbackRateState$,new me.ValueSubject(1))}).pipe((0,me.filterChanged)((o,u)=>this.player.liveStreamStatus$.getValue()==="active"?o.liveDuration===u.liveDuration:o.time===u.time)).subscribe(({time:o,liveDuration:u,playbackRate:l})=>{let p=t.position$.getValue(),{playbackCatchupSpeedup:c}=this.params.tuning.dashCmafLive.lowLatency;if(!p&&!this.video.paused&&l>=1-c||(0,me.isNullable)(o)||(0,me.isNullable)(u))return;let d=-1*(u-o-e);t.position$.next(Math.min(d,0))})).add(this.player.currentLiveTextRepresentation$.subscribe(o=>{if(o){let u=Ov(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 Gv="X-Playback-Duration",$c=async s=>{let e=await Lt(s),t=await e.text(),i=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t)?.[1];return i?parseInt(i,10):e.headers.has(Gv)?parseInt(e.headers.get(Gv),10):void 0};var se=require("@vkontakte/videoplayer-shared");var Cc=j(qu(),1);var Ro=require("@vkontakte/videoplayer-shared");var cL=s=>{let e=null;if(s.QUALITY&&(e=Ai(s.QUALITY)),!e&&s.RESOLUTION){let[t,i]=s.RESOLUTION.split("x").map(r=>parseInt(r,10));e=(0,Ro.videoSizeToQuality)({width:t,height:i})}return e??null},dL=(s,e)=>{let t=s.split(`
|
|
186
|
-
`),i=[],r=[];for(let a=0;a<t.length;a++){let n=t[a],o=n.match(/^#EXT-X-STREAM-INF:(.+)/),u=n.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!o&&!u)){if(o){let l=(0,Cc.default)(o[1].split(",").map(v=>v.split("="))),
|
|
187
|
-
`),a=0;for(let n=0;n<r.length;++n){let o=r[n];switch(!0){case o.startsWith("#EXTINF:"):{let u=r[++n],l=new URL(u,t).toString(),p=Number(this.extractPlaylistRowValue("#EXTINF:",o))*1e3;if(i.segments.push({time:{from:a,to:a+p},url:l}),a=a+p,!i.segmentStartTime){let c=new Date(i.vkStartTime).valueOf(),d=new Date(i.programDateTime).valueOf();i.segmentStartTime=d-c}break}case o.startsWith("#EXT-X-TARGETDURATION:"):i.targetDuration=Number(this.extractPlaylistRowValue("#EXT-X-TARGETDURATION:",o));break;case o.startsWith("#EXT-X-MEDIA-SEQUENCE:"):i.mediaSequence=Number(this.extractPlaylistRowValue("#EXT-X-MEDIA-SEQUENCE:",o));break;case o.startsWith("#EXT-X-VK-PLAYBACK-DURATION:"):i.vkPlaybackDuration=Number(this.extractPlaylistRowValue("#EXT-X-VK-PLAYBACK-DURATION:",o));break;case o.startsWith("#EXT-X-PROGRAM-DATE-TIME:"):{let u=this.extractPlaylistRowValue("#EXT-X-PROGRAM-DATE-TIME:",o);i.programDateTime=u;let l=new Date(u);l.setMilliseconds(0),a=l.valueOf();break}case o.startsWith("#EXT-X-VK-START-TIME:"):i.vkStartTime=this.extractPlaylistRowValue("#EXT-X-VK-START-TIME:",o);break}}return i}extractPlaylistRowValue(e,t){switch(e){case"#EXTINF:":return t.substring(e.length,t.length-1);default:return t.substring(e.length)}}processLiveTime(e){if((0,At.isNonNullable)(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([{...this.currentTextTrackData.textTrack,url:n.url,isAuto:!0}]);break}}}async fetchNextManifestData(){try{if(this.abortControllers.nextManifest)return;this.abortControllers.nextManifest=new de;let{textTracks:e}=await this.fetchManifestData(),t=await 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}}async fetchManifestData(){let e=this.prepareUrl??this.params.sourceUrl;return await this.params.fetchManifestData(e,{signal:this.abortControllers.destroy.signal})}error(e,t){this.error$.next({id:"[LiveTextManager][HLS_LIVE_CMAF]",category:At.ErrorCategory.WTF,thrown:t,message:e})}};var Fa=class{constructor(e){this.subscription=new se.Subscription;this.videoState=new ie("stopped");this.textTracksManager=null;this.liveTextManager=null;this.manifests$=new se.ValueSubject([]);this.liveOffset=new Wi;this.manifestStartTime$=new se.ValueSubject(void 0);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),_(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(a||n||o){let p=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(p),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?.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"?_(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),_(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?.to==="playing"&&_(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 p=this.liveOffset.getTotalOffset();p>=this.maxSeekBackTime$.getValue()&&(p=0,this.liveOffset.resetTo(p)),this.liveOffset.resume(),this.params.output.position$.next(-p/1e3),this.prepare()}else r?.to==="paused"&&(_(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return(0,se.assertNever)(t)}};this.params=e,this.video=at(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:se.VideoQuality.INVARIANT,url:this.params.source.url};let t=(i,r)=>Mo(i,this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},r);this.params.tuning.useHlsLiveNewTextManager?this.liveTextManager=new Lo(this.params.output.liveTime$,this.video,t,this.params.source.url,this.params.tuning.hlsLiveNewTextManagerDownloadThreshold):this.textTracksManager=new Rt(e.source.url),t(this.generateLiveUrl()).then(({qualityManifests:i,textTracks:r})=>{i.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:se.ErrorCategory.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),this.liveTextManager?.processTextTracks(r,this.params.source.url),this.manifests$.next([this.masterManifest,...i])}).catch(i=>{this.params.output.error$.next({id:"ExtractHlsQualities",category:se.ErrorCategory.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:i})}),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(We(this.params.source.url)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.maxSeekBackTime$=new se.ValueSubject(e.source.maxSeekBackTime??1/0),this.subscribe()}selectManifest(){let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),r=t.getTransition(),a=r?.to?.id??t.getState()?.id??"master",n=this.manifests$.getValue();if(!n.length)return;let o=i?"master":a;return i&&!r&&t.startTransitionTo(this.masterManifest),n.find(u=>u.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsLiveProvider",category:se.ErrorCategory.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},r=ut(this.video);this.subscription.add(()=>r.destroy());let a=(o,u)=>this.subscription.add(o.subscribe(u,i));a(r.ended$,e.endedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.loadedMetadata$,e.firstBytesEvent$),a(r.loadedMetadata$,e.loadedMetadataEvent$),a(r.playing$,e.firstFrameEvent$),a(r.canplay$,e.canplay$),a(r.inPiP$,e.inPiP$),a(r.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(ot(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(kt(this.video,t.playbackRate,r.playbackRateState$,i)),a(Mt(this.video),e.elementVisible$),this.liveTextManager?(a(this.liveTextManager.getCurrentTime$,this.params.output.getCurrentTime$),a(this.liveTextManager.error$,this.params.output.error$)):this.textTracksManager&&this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),_(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),_(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.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((0,se.filterChanged)(),(0,se.map)(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(),p=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&(0,se.isNonNullable)(l.to)){let c=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let d=this.manifests$.getValue().find(h=>h.id===c);d&&(this.params.output.currentVideoTrack$.next(d),this.params.output.hostname$.next(We(d.url)))}p&&this.params.desiredState.autoVideoTrackSwitching.setState(p.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(()=>{let o=this.video?.getStartDate?.()?.getTime();this.manifestStartTime$.next(o||void 0)},i)),this.subscription.add((0,se.combine)({startTime:this.manifestStartTime$.pipe((0,se.filter)(se.isNonNullable)),currentTime:r.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),i)),this.subscription.add(this.manifests$.pipe((0,se.map)(o=>o.map(({id:u,quality:l,size:p,bandwidth:c,fps:d})=>({id:u,quality:l,size:p,fps:d,bitrate:c})))).subscribe(this.params.output.availableVideoTracks$,i));let n=(0,se.merge)(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,(0,se.observableFrom)(["init"])).pipe((0,se.debounce)(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager?.destroy(),this.liveTextManager?.destroy(),this.params.output.element$.next(void 0),nt(this.video)}prepare(){let e=this.selectManifest();if((0,se.isNullable)(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}=t?.to??i??{};for(let[l,p]of[[o,"mq"],[u,"lq"]]){let c=String(parseFloat(l||""));p&&l&&r.searchParams.set(p,c)}}let a=this.params.format==="HLS_LIVE_CMAF"?2:0,n=Le(r.toString(),this.liveOffset.getTotalOffset(),a);this.liveTextManager?.prepare(n),this.video.setAttribute("src",n),this.video.load(),$c(n).then(o=>{if(!(0,se.isNullable)(o))this.maxSeekBackTime$.next(o);else{let u=this.params.source.maxSeekBackTime??this.maxSeekBackTime$.getValue();((0,se.isNullable)(u)||!isFinite(u))&&Lt(n).then(l=>l.text()).then(l=>{let p=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(l)?.[1];if(p){let c=new URL(p,n).toString();$c(c).then(d=>{(0,se.isNullable)(d)||this.maxSeekBackTime$.next(d)})}}).catch(()=>{})}})}playIfAllowed(){lt(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),_(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:se.ErrorCategory.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=Le(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}};var ue=require("@vkontakte/videoplayer-shared");var Na=class{constructor(e){this.subscription=new ue.Subscription;this.videoState=new ie("stopped");this.manifests$=new ue.ValueSubject([]);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),_(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(a||n||o){let p=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(p);let{currentTime:c}=this.video;this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:c*1e3,forcePrecise:!0});return}switch(r?.to!=="paused"&&l.state==="requested"&&this.seek(l.position),t){case"ready":i==="ready"?_(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),_(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?.to==="playing"&&_(this.params.desiredState.playbackState,"playing");return;case"paused":i==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):r?.to==="paused"&&_(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return(0,ue.assertNever)(t)}};this.textTracksManager=new Rt(e.source.url),this.params=e,this.video=at(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:ue.VideoQuality.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(We(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),Mo(Le(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:ue.ErrorCategory.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),r=t.getTransition(),a=r?.to?.id??t.getState()?.id??"master",n=this.manifests$.getValue();if(!n.length)return;let o=i?"master":a;return i&&(!r||!r.from)&&t.startTransitionTo(this.masterManifest),n.find(u=>u.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsProvider",category:ue.ErrorCategory.WTF,message:"HlsProvider internal logic error",thrown:o})},r=ut(this.video);this.subscription.add(()=>r.destroy());let a=(o,u)=>this.subscription.add(o.subscribe(u));if(a(r.timeUpdate$,e.position$),a(r.durationChange$,e.duration$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.loadedMetadata$,e.firstBytesEvent$),a(r.loadedMetadata$,e.loadedMetadataEvent$),a(r.playing$,e.firstFrameEvent$),a(r.canplay$,e.canplay$),a(r.seeked$,e.seekedEvent$),a(r.inPiP$,e.inPiP$),a(r.inFullscreen$,e.inFullscreen$),a(this.videoState.stateChangeEnded$.pipe((0,ue.map)(o=>o.to)),this.params.output.playbackState$),this.subscription.add(Wt(this.video,t.isLooped,i)),this.subscription.add(ot(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(kt(this.video,t.playbackRate,r.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),_(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),_(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i).add(r.loadedMetadata$.subscribe(()=>{let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),p=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&(0,ue.isNonNullable)(l.to)){let h=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let m=this.manifests$.getValue().find(g=>g.id===h);m&&(this.params.output.currentVideoTrack$.next(m),this.params.output.hostname$.next(We(m.url)))}let c=this.params.desiredState.playbackRate.getState(),d=this.params.output.element$.getValue()?.playbackRate;if(c!==d){let h=this.params.output.element$.getValue();h&&(this.params.desiredState.playbackRate.setState(c),h.playbackRate=c)}p&&this.params.desiredState.autoVideoTrackSwitching.setState(p.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((0,ue.map)(o=>o.map(({id:u,quality:l,size:p,bandwidth:c,fps:d})=>({id:u,quality:l,size:p,fps:d,bitrate:c})))).subscribe(this.params.output.availableVideoTracks$,i)),!W.device.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add((0,ue.merge)((0,ue.fromEvent)(o,"addtrack"),(0,ue.fromEvent)(o,"removetrack"),(0,ue.fromEvent)(o,"change"),(0,ue.observableFrom)(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},i))}let n=(0,ue.merge)(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,(0,ue.observableFrom)(["init"])).pipe((0,ue.debounce)(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),nt(this.video)}prepare(){let e=this.selectManifest();if((0,ue.isNullable)(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:a,min:n}=t?.to??i??{};for(let[o,u]of[[a,"mq"],[n,"lq"]]){let l=String(parseFloat(o||""));u&&o&&r.searchParams.set(u,l)}}this.video.setAttribute("src",r.toString()),this.video.load()}playIfAllowed(){lt(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),_(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:ue.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};var Yv=j(Ui(),1),Vc=j(Gi(),1),Kv=j(Ut(),1);var ye=require("@vkontakte/videoplayer-shared");var Ua=class{constructor(e){this.subscription=new ye.Subscription;this.videoState=new ie("stopped");this.trackUrls={};this.textTracksManager=new Rt;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"),_(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let a=this.params.desiredState.autoVideoTrackLimits.getTransition(),n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.seekState.getState();if(a&&e!=="ready"&&!n){this.handleQualityLimitTransition(a.to);return}if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(n){let{currentTime:u}=this.video;this.prepare(),o.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:u*1e3,forcePrecise:!0});return}switch(i?.to!=="paused"&&o.state==="requested"&&this.seek(o.position),e){case"ready":t==="ready"?_(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),_(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?.to==="playing"&&_(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&_(this.params.desiredState.playbackState,"paused");return;default:return(0,ye.assertNever)(e)}};this.params=e,this.video=at(e.container,e.tuning),this.params.output.element$.next(this.video),(0,Yv.default)(this.params.source).reverse().forEach(([t,i],r)=>{let a=r.toString(10);this.trackUrls[a]={track:{quality:t,id:a},url:i}}),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next((0,Vc.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:ye.ErrorCategory.WTF,message:"MpegProvider internal logic error",thrown:o})},r=ut(this.video);this.subscription.add(()=>r.destroy());let a=(o,u)=>this.subscription.add(o.subscribe(u,i));a(r.timeUpdate$,e.position$),a(r.durationChange$,e.duration$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.loadedMetadata$,e.firstBytesEvent$),a(r.loadedMetadata$,e.loadedMetadataEvent$),a(r.playing$,e.firstFrameEvent$),a(r.canplay$,e.canplay$),a(r.seeked$,e.seekedEvent$),a(r.inPiP$,e.inPiP$),a(r.inFullscreen$,e.inFullscreen$),a(this.videoState.stateChangeEnded$.pipe((0,ye.map)(o=>o.to)),this.params.output.playbackState$),this.subscription.add(Wt(this.video,t.isLooped,i)),this.subscription.add(ot(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(kt(this.video,t.playbackRate,r.playbackRateState$,i)),a(Mt(this.video),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),_(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),_(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready");let o=this.params.desiredState.videoTrack.getTransition();if(o&&(0,ye.isNonNullable)(o.to)){this.params.desiredState.videoTrack.setState(o.to),this.params.output.currentVideoTrack$.next(this.trackUrls[o.to.id].track);let u=this.params.desiredState.playbackRate.getState(),l=this.params.output.element$.getValue()?.playbackRate;if(u!==l){let p=this.params.output.element$.getValue();p&&(this.params.desiredState.playbackRate.setState(u),p.playbackRate=u)}}this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.textTracksManager.connect(this.video,t,e);let n=(0,ye.merge)(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,(0,ye.observableFrom)(["init"])).pipe((0,ye.debounce)(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),nt(this.video)}prepare(){let e=this.params.desiredState.videoTrack.getState()?.id;(0,ye.assertNonNullable)(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];(0,ye.assertNonNullable)(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=Li(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(We(t))}playIfAllowed(){lt(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),_(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:ye.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){this.params.output.autoVideoTrackLimits$.next(e);let t=l=>{this.params.output.currentVideoTrack$.next(l),this.params.desiredState.videoTrack.startTransitionTo(l)},i=l=>{let p=Yt(n,{container:this.video.getBoundingClientRect(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:0,limits:l,abrLogger:this.params.dependencies.abrLogger});t(p)},r=this.params.output.currentVideoTrack$.getValue()?.quality,a=!!(e.max||e.min),n=(0,Vc.default)(this.trackUrls).map(l=>l.track);if(!r||!a||Er(e,n[0].quality,(0,Kv.default)(n,-1)?.quality)){i();return}let o=e.max?(0,ye.isLowerOrEqual)(r,e.max):!0,u=e.min?(0,ye.isHigherOrEqual)(r,e.min):!0;o&&u||i(e)}};var we=require("@vkontakte/videoplayer-shared");var Jv=require("@vkontakte/videoplayer-shared"),Xv=["stun:videostun.mycdn.me:80"],hL=1e3,fL=3,Oc=()=>null,Bo=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=Oc;this.externalStopCallback=Oc;this.externalErrorCallback=Oc;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}}async handleUpdateMessage(e){try{let t=await this.createOffer();this.peerConnection&&await this.peerConnection.setLocalDescription(t),this.handleAnswer(e.sdp)}catch(t){this.handleRTCError(t)}}async handleLogin(){try{let e={iceServers:[{urls:Xv}]};this.peerConnection=new RTCPeerConnection(e),this.peerConnection.ontrack=this.onPeerConnectionStream.bind(this),this.peerConnection.onicecandidate=this.onPeerConnectionIceCandidate.bind(this),this.peerConnection.oniceconnectionstatechange=this.onPeerConnectionIceConnectionStateChange.bind(this);let t=await this.createOffer();await this.peerConnection.setLocalDescription(t),this.send({type:this.signalingType,inviteType:"OFFER",streamKey:this.streamKey,sdp:t.sdp,callSupport:!1})}catch(e){this.handleRTCError(e)}}async handleAnswer(e){try{this.peerConnection&&await this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e}))}catch(t){this.handleRTCError(t)}}async handleCandidate(e){if(e)try{this.peerConnection&&await this.peerConnection.addIceCandidate(e)}catch(t){this.handleRTCError(t)}}handleUnpublished(){try{this.closeConnections(),this.externalStopCallback()}catch(e){this.handleRTCError(e)}}handleSystemError(e){this.options.errorChanel&&this.options.errorChanel.next({id:"webrtc-provider-error",category:Jv.ErrorCategory.WTF,message:e.message})}async onPeerConnectionStream(e){let t=e.streams[0];this.stream&&this.stream.id===t.id||(this.stream=t,this.externalStartCallback(this.stream))}onPeerConnectionIceCandidate(e){e.candidate&&this.send({type:this.signalingType,inviteType:"CANDIDATE",candidate:e.candidate})}onPeerConnectionIceConnectionStateChange(){if(this.peerConnection){let e=this.peerConnection.iceConnectionState;["failed","closed"].indexOf(e)>-1&&(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():(this.closeConnections(),this.scheduleRetry()))}}async createOffer(){let e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");let t=await this.peerConnection.createOffer(e),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{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),hL)}normalizeOptions(e={}){let t={stunServerList:Xv,maxRetryNumber:fL,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var qa=class{constructor(e){this.videoState=new ie("stopped");this.maxSeekBackTime$=new we.ValueSubject(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"),_(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let a=this.params.desiredState.videoTrack.getTransition();if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(a){this.prepare();return}switch(e){case"ready":t==="paused"?(this.videoState.setState("paused"),_(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?.to==="playing"&&_(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&_(this.params.desiredState.playbackState,"paused");return;default:return(0,we.assertNever)(e)}};this.subscription=new we.Subscription,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=at(e.container,e.tuning),this.liveStreamClient=new Bo(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),nt(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,i=n=>{e.error$.next({id:"WebRTCLiveProvider",category:we.ErrorCategory.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};this.subscription.add((0,we.merge)(this.videoState.stateChangeStarted$.pipe((0,we.map)(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe((0,we.map)(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})}));let r=ut(this.video);this.subscription.add(()=>r.destroy());let a=(n,o)=>this.subscription.add(n.subscribe(o,i));a(r.timeUpdate$,e.liveTime$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(Mt(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(()=>{this.videoState.getTransition()?.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(ot(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(0,we.assertNever)(n.to)}},i)).add((0,we.merge)(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,(0,we.observableFrom)(["init"])).pipe((0,we.debounce)(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(We(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:we.VideoQuality.INVARIANT}),this.video.srcObject=e,_(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:we.ErrorCategory.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){lt(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),_(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:we.ErrorCategory.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var Ha=class{constructor(e){this.iterator=e[Symbol.iterator](),this.next()}next(){this.current=this.iterator.next()}getValue(){if(this.current.done)throw new Error("Iterable is completed");return this.current.value}isCompleted(){return!!this.current.done}};var E=require("@vkontakte/videoplayer-shared");var yi=require("@vkontakte/videoplayer-shared"),Zv=s=>new yi.Observable(e=>{let t=new yi.Subscription,i=s.desiredPlaybackState$.stateChangeStarted$.pipe((0,yi.map)(({from:l,to:p})=>`${l}-${p}`)),r=s.desiredPlaybackState$.stateChangeEnded$,a=s.providerChanged$.pipe((0,yi.map)(({type:l})=>l!==void 0)),n=new yi.Subject,o=0,u="unknown";return t.add(i.subscribe(l=>{o&&window.clearTimeout(o),u=l,o=window.setTimeout(()=>n.next(l),s.maxTransitionInterval)})),t.add(r.subscribe(()=>{window.clearTimeout(o),u="unknown",o=0})),t.add(a.subscribe(l=>{o&&(window.clearTimeout(o),o=0,l&&(o=window.setTimeout(()=>n.next(u),s.maxTransitionInterval)))})),t.add(n.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});var Bt=require("@vkontakte/videoplayer-shared");function ey(){return new(window.AudioContext||window.webkitAudioContext)}var Nr=class s{constructor(e,t,i,r){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=i;this.volumeMultiplier=r;this.destroyController=new de;this.subscriptions=new Bt.Subscription;this.audioContext=null;this.gainNode=null;this.mediaElementSource=null;this.subscriptions.add(this.provider$.pipe((0,Bt.filter)(a=>!!a.type),(0,Bt.once)()).subscribe(({type:a})=>this.subscribe(a)))}static{this.errorId="VolumeMultiplierManager"}subscribe(e){W.browser.isSafari&&e!=="MPEG"||this.subscriptions.add((0,Bt.combine)({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe((0,Bt.filter)(({playbackState:t,video:i,volume:{muted:r,volume:a}})=>t==="playing"&&!!i&&!r&&!!a),(0,Bt.once)()).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}async initAudioContextOnce(e){let{volumeMultiplier:t}=this,i=ey();this.audioContext=i;let r=i.createGain();if(this.gainNode=r,r.gain.value=t,r.connect(i.destination),i.state==="suspended"&&(await i.resume(),this.destroyController.signal.aborted))return!1;let a=i.createMediaElementSource(e);return this.mediaElementSource=a,a.connect(r),!0}cleanup(){this.mediaElementSource&&(this.mediaElementSource.disconnect(),this.mediaElementSource=null),this.gainNode&&(this.gainNode.disconnect(),this.gainNode=null),this.audioContext&&(this.audioContext.state!=="closed"&&this.audioContext.close(),this.audioContext=null)}destroy(){this.destroyController.abort(),this.subscriptions.unsubscribe(),this.cleanup()}handleError(e){this.volumeMultiplierError$.next({id:s.errorId,category:Bt.ErrorCategory.VIDEO_PIPELINE,message:e?.message??`${s.errorId} exception`,thrown:e})}};var mL={chunkDuration:5e3,maxParallelRequests:5},ja=class{constructor(e){this.current$=new E.ValueSubject({type:void 0});this.providerError$=new E.Subject;this.noAvailableProvidersError$=new E.Subject;this.volumeMultiplierError$=new E.Subject;this.providerOutput={position$:new E.ValueSubject(0),duration$:new E.ValueSubject(1/0),volume$:new E.ValueSubject({muted:!1,volume:1}),availableVideoStreams$:new E.ValueSubject([]),currentVideoStream$:new E.ValueSubject(void 0),availableVideoTracks$:new E.ValueSubject([]),currentVideoTrack$:new E.ValueSubject(void 0),availableAudioStreams$:new E.ValueSubject([]),currentAudioStream$:new E.ValueSubject(void 0),availableAudioTracks$:new E.ValueSubject([]),currentVideoSegmentLength$:new E.ValueSubject(0),currentAudioSegmentLength$:new E.ValueSubject(0),isAudioAvailable$:new E.ValueSubject(!0),autoVideoTrackLimitingAvailable$:new E.ValueSubject(!1),autoVideoTrackLimits$:new E.ValueSubject(void 0),currentBuffer$:new E.ValueSubject(void 0),isBuffering$:new E.ValueSubject(!0),error$:new E.Subject,fetcherError$:new E.Subject,fetcherRecoverableError$:new E.Subject,warning$:new E.Subject,willSeekEvent$:new E.Subject,soundProhibitedEvent$:new E.Subject,seekedEvent$:new E.Subject,loopedEvent$:new E.Subject,endedEvent$:new E.Subject,firstBytesEvent$:new E.Subject,loadedMetadataEvent$:new E.Subject,firstFrameEvent$:new E.Subject,canplay$:new E.Subject,isLive$:new E.ValueSubject(void 0),isLiveEnded$:new E.ValueSubject(null),isLowLatency$:new E.ValueSubject(!1),canChangePlaybackSpeed$:new E.ValueSubject(!0),liveTime$:new E.ValueSubject(void 0),liveBufferTime$:new E.ValueSubject(void 0),liveLatency$:new E.ValueSubject(void 0),severeStallOccurred$:new E.Subject,availableTextTracks$:new E.ValueSubject([]),currentTextTrack$:new E.ValueSubject(void 0),hostname$:new E.ValueSubject(void 0),httpConnectionType$:new E.ValueSubject(void 0),httpConnectionReused$:new E.ValueSubject(void 0),inPiP$:new E.ValueSubject(!1),inFullscreen$:new E.ValueSubject(!1),element$:new E.ValueSubject(void 0),elementVisible$:new E.ValueSubject(!0),availableSources$:new E.ValueSubject(void 0),is3DVideo$:new E.ValueSubject(!1),playbackState$:new E.ValueSubject(""),getCurrentTime$:new E.ValueSubject(null)};this.subscription=new E.Subscription;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=mv([...gv(this.params.tuning),...bv(this.params.tuning)],this.params.tuning).filter(l=>(0,E.isNonNullable)(e.sources[l])),{forceFormat:i,formatsToAvoid:r}=this.params.tuning,a=[];i?a=[i]:r.length?a=[...t.filter(l=>!(0,_c.default)(r,l)),...t.filter(l=>(0,_c.default)(r,l))]:a=t,this.log({message:`Selected formats: ${a.join(" > ")}`}),this.tracer.log("Selected formats",(0,E.flattenObject)(a)),this.screenFormatsIterator=new Ha(a);let n=[...bc(!0),...bc(!1)];this.chromecastFormatsIterator=new Ha(n.filter(l=>(0,E.isNonNullable)(e.sources[l]))),this.providerOutput.availableSources$.next(e.sources);let{volumeMultiplier:o=1,tuning:{useVolumeMultiplier:u}}=this.params;u&&o!==1&&Nr.isSupported()&&(this.volumeMultiplierManager=new Nr(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(){this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe(),this.volumeMultiplierManager?.destroy(),this.volumeMultiplierManager=null,this.tracer.end()}initProvider(){let e=this.chooseDestination(),t=this.chooseFormat(e);if((0,E.isNullable)(t)){this.handleNoFormatsError(e);return}let i;try{i=this.createProvider(e,t)}catch(r){this.providerError$.next({id:"ProviderNotConstructed",category:E.ErrorCategory.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"),e.destroy();let t=this.providerOutput.position$.getValue()*1e3,i=this.params.desiredState.seekState.getState(),r=i.state!=="none";if(this.params.desiredState.seekState.setState({state:"requested",position:r?i.position:t,forcePrecise:r?i.forcePrecise:!1}),e.scene3D){let n=e.scene3D.getCameraRotation();this.params.desiredState.cameraOrientation.setState({x:n.x,y:n.y})}let a=this.providerOutput.isBuffering$;a.getValue()||a.next(!0)}createProvider(e,t){switch(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(0,E.assertNever)(e)}}createScreenProvider(e){let{sources:t,container:i,desiredState:r,panelSize:a}=this.params,n=this.providerOutput,o={container:i,source:null,desiredState:r,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning,panelSize:a};switch(e){case"DASH_SEP":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_ONDEMAND":case"DASH_STREAMS":{let u=this.applyFailoverHost(t[e]),l=this.applyFailoverHost(t.HLS_ONDEMAND||t.HLS);return(0,E.assertNonNullable)(u),this.params.tuning.useNewDashProvider?new Oa({...o,source:u,sourceHls:l}):new aa({...o,source:u,sourceHls:l})}case"DASH_LIVE_CMAF":{let u=this.applyFailoverHost(t[e]);return(0,E.assertNonNullable)(u),this.params.tuning.useNewDashProvider?new _a({...o,source:u}):new na({...o,source:u})}case"HLS":case"HLS_ONDEMAND":{let u=this.applyFailoverHost(t[e]);return(0,E.assertNonNullable)(u),new Na({...o,source:u})}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let u=this.applyFailoverHost(t[e]);return(0,E.assertNonNullable)(u),new Fa({...o,source:u,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case"MPEG":{let u=this.applyFailoverHost(t[e]);return(0,E.assertNonNullable)(u),new Ua({...o,source:u})}case"DASH_LIVE":{let u=this.applyFailoverHost(t[e]);return(0,E.assertNonNullable)(u),new Ig({...o,source:u,config:{...mL,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case"WEB_RTC_LIVE":{let u=this.applyFailoverHost(t[e]);return(0,E.assertNonNullable)(u),new qa({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(0,E.assertNever)(e)}}createChromecastProvider(e){let{sources:t,container:i,desiredState:r,meta:a}=this.params,n=this.providerOutput,o=this.params.dependencies.chromecastInitializer.connection$.getValue();return(0,E.assertNonNullable)(o),new hs({connection:o,meta:a,container:i,source:t,format:e,desiredState:r,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?"CHROMECAST":"SCREEN"}chooseFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case"CHROMECAST":return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return(0,E.assertNever)(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return(0,E.assertNever)(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(0,E.assertNever)(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;let t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;let i=r=>{let a=new URL(r);return a.host=t,a.toString()};if(e===void 0)return e;if("type"in e){if(e.type==="raw")return e;if(e.type==="url")return{...e,url:i(e.url)}}return(0,iy.default)((0,ty.default)(e).map(([r,a])=>[r,i(a)]))}initProviderErrorHandling(){let e=new E.Subscription,t=!1,i=0;return e.add((0,E.merge)(this.providerOutput.error$.pipe((0,E.filter)(r=>!this.params.tuning.ignoreAudioRendererError||!r.message||!/AUDIO_RENDERER_ERROR/ig.test(r.message))),Zv({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe((0,E.map)(r=>({id:`ProviderHangup:${r}`,category:E.ErrorCategory.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((0,E.filter)(({to:a})=>a==="playing"),(0,E.once)()).subscribe(()=>t=!0);e.add(r)})),e.add(this.providerError$.subscribe(r=>{let a=this.current$.getValue().destination,n={error:r,currentDestination:a};if(a==="CHROMECAST")this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider("SCREEN"),()=>this.params.dependencies.chromecastInitializer.disconnect());else{let o=r.category===E.ErrorCategory.NETWORK,u=r.category===E.ErrorCategory.FATAL,l=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),p=i<this.params.tuning.providerErrorLimit&&!u,c=l&&!u&&(o&&t||!p);n={...n,isNetworkError:o,isFatalError:u,haveFailoverHost:l,tryFailover:c,canReinitProvider:p},p?(i++,this.reinitProvider()):c?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):(i=0,this.switchToNextProvider(a??"SCREEN"))}r.traceAsLog?this.tracer.log("providerInfo",(0,E.flattenObject)(n)):this.tracer.error("providerError",(0,E.flattenObject)(n))})),e}};var K=require("@vkontakte/videoplayer-shared");var bL=5e3,ry="one_video_throughput",sy="one_video_rtt",za=window.navigator.connection,ay=()=>{let s=za?.downlink;if((0,K.isNonNullable)(s)&&s!==10)return s*1e3},ny=()=>{let s=za?.rtt;if((0,K.isNonNullable)(s)&&s!==3e3)return s},oy=(s,e,t)=>{let i=t*8,r=i/s;return i/(r+e)},Fc=class s{constructor(e){this.subscription=new K.Subscription;this.concurrentDownloads=new Set;this.tuningConfig=e;let t=s.load(ry)||(e.useBrowserEstimation?ay():void 0)||bL,i=s.load(sy)??(e.useBrowserEstimation?ny():void 0)??0;if(this.throughput$=new K.ValueSubject(t),this.rtt$=new K.ValueSubject(i),this.rttAdjustedThroughput$=new K.ValueSubject(oy(t,i,e.rttPenaltyRequestSize)),this.throughput=bi.getSmoothedValue(t,-1,e),this.rtt=bi.getSmoothedValue(i,1,e),e.useBrowserEstimation){let r=()=>{let n=ay();n&&this.throughput.next(n);let o=ny();(0,K.isNonNullable)(o)&&this.rtt.next(o)};za&&"onchange"in za&&this.subscription.add((0,K.fromEvent)(za,"change").subscribe(r)),r()}this.subscription.add(this.throughput.smoothed$.subscribe(r=>{K.safeStorage.set(ry,r.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(r=>{K.safeStorage.set(sy,r.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add((0,K.combine)({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe((0,K.map)(({throughput:r,rtt:a})=>oy(r,a,e.rttPenaltyRequestSize)),(0,K.filter)(r=>{let a=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(r-a)/a>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,i=(0,K.now)(),r=new K.Subscription;switch(this.subscription.add(r),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:r.add((0,K.fromEvent)(e,"progress").pipe((0,K.once)()).subscribe(a=>{t=a.loaded,i=(0,K.now)()}));break;case 1:case 0:r.add((0,K.fromEvent)(e,"loadstart").subscribe(()=>{t=0,i=(0,K.now)()}));break}r.add((0,K.fromEvent)(e,"loadend").subscribe(a=>{if(e.status===200){let n=a.loaded,o=(0,K.now)(),u=n-t,l=o-i;this.addRawSpeed(u,l,1)}this.concurrentDownloads.delete(e),r.unsubscribe()}))}trackStream(e,t=!1){let i=e.getReader();if(!i){e.cancel("Could not get reader");return}let r=0,a=(0,K.now)(),n=0,o=(0,K.now)(),u=p=>{this.concurrentDownloads.delete(e),i.releaseLock(),e.cancel(`Throughput Estimator error: ${p}`).catch(()=>{})},l=async({done:p,value:c})=>{if(p)!t&&this.addRawSpeed(r,(0,K.now)()-a,1),this.concurrentDownloads.delete(e);else if(c){if(t){let d=(0,K.now)();if(d-o>this.tuningConfig.lowLatency.continuesByteSequenceInterval||d-a>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let m=o-a;m&&this.addRawSpeed(n,m,1,t),n=c.byteLength,a=(0,K.now)()}else n+=c.byteLength;o=(0,K.now)()}else r+=c.byteLength,n+=c.byteLength,n>=this.tuningConfig.streamMinSampleSize&&(0,K.now)()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,(0,K.now)()-o,this.concurrentDownloads.size),n=0,o=(0,K.now)());await i?.read().then(l,u)}};this.concurrentDownloads.add(e),i?.read().then(l,u)}addRawSpeed(e,t,i=1,r=!1){if(s.sanityCheck(e,t,r)){let a=e*8/t;this.throughput.next(a*i)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,i=!1){let r=e*8/t;return!(!r||!isFinite(r)||r>1e6||r<30||i&&e<1e4||!i&&e<10*1024||!i&&t<=20)}static load(e){let t=K.safeStorage.get(e);if((0,K.isNonNullable)(t))return parseInt(t,10)??void 0}},uy=Fc;var rr=require("@vkontakte/videoplayer-shared"),ly={configName:["core"],throughputEstimator:{type:"EmaAndMa",emaAlphaSlow:.2,emaAlphaFast:.7,emaAlpha:.45,basisTrendChangeCount:10,changeThreshold:.05,useBrowserEstimation:!0,rttPenaltyRequestSize:1*1024*1024,streamMinSampleSize:10*1024,streamMinSampleTime:300,deviationDepth:20,deviationFactor:.5,lowLatency:{continuesByteSequenceInterval:50,maxLastEvaluationTimeout:300}},autoTrackSelection:{maxBitrateFactorAtEmptyBuffer:4,bitrateFactorAtEmptyBuffer:2.8,minBitrateFactorAtEmptyBuffer:1.5,bitrateAudioFactorAtEmptyBuffer:10,maxBitrateFactorAtFullBuffer:3,bitrateFactorAtFullBuffer:2,minBitrateFactorAtFullBuffer:1,bitrateAudioFactorAtFullBuffer:7,minVideoAudioRatio:5,minAvailableThroughputAudioRatio:5,usePixelRatio:!0,pixelRatioMultiplier:void 0,pixelRatioLogBase:3,pixelRatioLogCoefficients:[1,0,1],limitByContainer:!0,maxContainerSizeFactor:2,containerSizeFactor:1.3,minContainerSizeFactor:1,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldownIncreaseQuality:15e3,trackCooldownDecreaseQuality:3e3,backgroundVideoQualityLimit:rr.VideoQuality.Q_4320P,activeVideoAreaThreshold:.1,highQualityLimit:rr.VideoQuality.Q_720P,trafficSavingLimit:rr.VideoQuality.Q_480P},stallsManager:{enabled:!1,stallDurationNoDataBeforeQualityDecrease:500,stallDurationToBeCount:100,stallCountBeforeQualityDecrease:3,resetQualityRestrictionTimeout:1e4,ignoreStallsOnSeek:!0,stallsMetricsHistoryLength:5,maxPossibleStallDuration:3e4,minTvtToBeCounted:5,maxTvtToBeCounted:10800,significantTvt:600,targetStallsDurationPerTvt:1,deviationStallsDurationPerTvt:.5,criticalStallsDurationPerTvt:6,abrAdjustingSpeed:.1,emaAlpha:.6,useTotalStallsDurationPerTvt:!0,useAverageStallsDurationPerTvt:!0,useEmaStallsDurationPerTvt:!0},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:rr.VideoQuality.Q_480P},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,seekBiasInTheEnd:2e3,maxSegmentDurationLeftToSelectNextSegment:3e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:3e3,crashOnStallTimeout:25e3,crashOnStallTWithoutDataTimeout:5e3,enableSubSegmentBufferFeeding:!0,bufferEmptinessTolerance:100,useFetchPriorityHints:!0,enableBaseUrlSupport:!0,maxSegmentRetryCount:5,sourceOpenTimeout:1e3,vktvAbrThrottle:0,timeupdateEventTickThrottle:300},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,maxLiveDuration:7200,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:250,playbackCatchupSpeedup:.05,isActiveOnDefault:!1,bufferEstimator:{emaAlpha:.45,changeThreshold:.05,deviationDepth:20,deviationFactor:.5,extremumInterval:5}}},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1,lowLatencyActiveLiveDelay:3e3,activeLiveDelay:5e3,maxPausedTime:5e3},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,forceFormat:void 0,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:"07A4434E",useWebmBigRequest:!1,webmCodec:"vp9",androidPreferredFormat:"dash",preferCMAF:!1,preferWebRTC:!1,preferMultiStream:!1,preferHDR:!1,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,seekNearDurationBias:1,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useHlsJs:!1,useNativeHLSTextTracks:!1,useManagedMediaSource:!0,useNewSwitchTo:!1,useNewDashProvider:!1,useNewAutoSelectVideoTrack:!1,useSafariEndlessRequestBugfix:!0,useRefactoredSearchGap:!1,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,manifestRetryInterval:300,manifestRetryMaxInterval:1e4,manifestRetryMaxCount:10,audioVideoSyncRate:20,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50},useVolumeMultiplier:!1,ignoreAudioRendererError:!1,useEnableSubtitlesParam:!1,useOldMSEDetection:!1,useHlsLiveNewTextManager:!1,exposeInternalsToGlobal:!1,hlsLiveNewTextManagerDownloadThreshold:4e3,disableYandexPiP:!1,asyncResolveClientChecker:!1,autostartOnlyIfVisible:!1},cy=s=>({...(0,rr.fillWithDefault)(s,ly),configName:[...s.configName??[],...ly.configName]});var f=require("@vkontakte/videoplayer-shared");var Ti=require("@vkontakte/videoplayer-shared"),Nc=({seekState:s,position$:e})=>(0,Ti.merge)(s.stateChangeEnded$.pipe((0,Ti.map)(({to:t})=>t.state==="none"?void 0:(t.position??NaN)/1e3),(0,Ti.filter)(Ti.isNonNullable)),e.pipe((0,Ti.filter)(()=>s.getState().state==="none")));var dy=require("@vkontakte/videoplayer-shared"),py=s=>{let e=typeof s.container=="string"?document.getElementById(s.container):s.container;return(0,dy.assertNonNullable)(e,`Wrong container or containerId {${s.container}}`),e};var $o=require("@vkontakte/videoplayer-shared"),hy=(s,e,t,i)=>{s!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&t?.getValue().length===0?t.pipe((0,$o.filter)(r=>r.length>0),(0,$o.once)()).subscribe(r=>{r.find(i)&&e.startTransitionTo(s)}):(s===void 0||t?.getValue().find(i))&&e.startTransitionTo(s)};var Qa=class{constructor(e={configName:[]},t=f.TracerFactory.createRootTracer(!1)){this.subscription=new f.Subscription;this.logger=new f.Logger;this.abrLogger=this.logger.createComponentLog("ABR");this.internalsExposure=null;this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new f.ValueSubject(!1);this.hasLiveOffsetByPausedTimer=0;this.playerInitRequest=0;this.playerInited=new f.ValueSubject(!1);this.wasSetStartedQuality=!1;this.desiredState={playbackState:new ie("stopped"),seekState:new ie({state:"none"}),volume:new ie({volume:1,muted:!1}),videoTrack:new ie(void 0),videoStream:new ie(void 0),audioStream:new ie(void 0),autoVideoTrackSwitching:new ie(!0),autoVideoTrackLimits:new ie({}),isLooped:new ie(!1),isLowLatency:new ie(!1),playbackRate:new ie(1),externalTextTracks:new ie([]),internalTextTracks:new ie([]),currentTextTrack:new ie(void 0),textTrackCuesSettings:new ie({}),cameraOrientation:new ie({x:0,y:0})};this.info={playbackState$:new f.ValueSubject(void 0),position$:new f.ValueSubject(0),duration$:new f.ValueSubject(1/0),muted$:new f.ValueSubject(!1),volume$:new f.ValueSubject(1),availableVideoStreams$:new f.ValueSubject([]),currentVideoStream$:new f.ValueSubject(void 0),availableQualities$:new f.ValueSubject([]),availableQualitiesFps$:new f.ValueSubject({}),currentQuality$:new f.ValueSubject(void 0),isAutoQualityEnabled$:new f.ValueSubject(!0),autoQualityLimitingAvailable$:new f.ValueSubject(!1),autoQualityLimits$:new f.ValueSubject({}),predefinedQualityLimitType$:new f.ValueSubject("unknown"),availableAudioStreams$:new f.ValueSubject([]),currentAudioStream$:new f.ValueSubject(void 0),availableAudioTracks$:new f.ValueSubject([]),isAudioAvailable$:new f.ValueSubject(!0),currentPlaybackRate$:new f.ValueSubject(1),currentBuffer$:new f.ValueSubject({start:0,end:0}),isBuffering$:new f.ValueSubject(!0),isStalled$:new f.ValueSubject(!1),isEnded$:new f.ValueSubject(!1),isLooped$:new f.ValueSubject(!1),isLive$:new f.ValueSubject(void 0),isLiveEnded$:new f.ValueSubject(null),canChangePlaybackSpeed$:new f.ValueSubject(void 0),atLiveEdge$:new f.ValueSubject(void 0),atLiveDurationEdge$:new f.ValueSubject(void 0),liveTime$:new f.ValueSubject(void 0),liveBufferTime$:new f.ValueSubject(void 0),liveLatency$:new f.ValueSubject(void 0),currentFormat$:new f.ValueSubject(void 0),availableTextTracks$:new f.ValueSubject([]),currentTextTrack$:new f.ValueSubject(void 0),throughputEstimation$:new f.ValueSubject(void 0),rttEstimation$:new f.ValueSubject(void 0),videoBitrate$:new f.ValueSubject(void 0),hostname$:new f.ValueSubject(void 0),httpConnectionType$:new f.ValueSubject(void 0),httpConnectionReused$:new f.ValueSubject(void 0),surface$:new f.ValueSubject("none"),chromecastState$:new f.ValueSubject("NOT_AVAILABLE"),chromecastDeviceName$:new f.ValueSubject(void 0),intrinsicVideoSize$:new f.ValueSubject(void 0),availableSources$:new f.ValueSubject(void 0),is3DVideo$:new f.ValueSubject(!1),currentVideoSegmentLength$:new f.ValueSubject(0),currentAudioSegmentLength$:new f.ValueSubject(0)};this.events={inited$:new f.Subject,ready$:new f.Subject,started$:new f.Subject,playing$:new f.Subject,paused$:new f.Subject,stopped$:new f.Subject,willReady$:new f.Subject,willStart$:new f.Subject,willResume$:new f.Subject,willPause$:new f.Subject,willStop$:new f.Subject,willDestruct$:new f.Subject,watchCoverageRecord$:new f.Subject,watchCoverageLive$:new f.Subject,managedError$:new f.Subject,fatalError$:new f.Subject,fetcherRecoverableError$:new f.Subject,ended$:new f.Subject,looped$:new f.Subject,seeked$:new f.Subject,willSeek$:new f.Subject,autoplaySoundProhibited$:new f.Subject,firstBytes$:new f.Subject,loadedMetadata$:new f.Subject,firstFrame$:new f.Subject,canplay$:new f.Subject,log$:new f.Subject,fetcherError$:new f.Subject,severeStallOccured$:new f.Subject};this.experimental={element$:new f.ValueSubject(void 0),tuningConfigName$:new f.ValueSubject([]),enableDebugTelemetry$:new f.ValueSubject(!1),dumpTelemetry:ag,getCurrentTime$:new f.ValueSubject(null)};if(this.initLogs(),this.tuning=cy(e),this.tracer=t,this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new en({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new uy(this.tuning.throughputEstimator),e.exposeInternalsToGlobal&&(this.internalsExposure=new f.InternalsExposure("CORE"),this.internalsExposure.expose({player:this})),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(i,r,a)=>{let n=Reflect.get(i,r,a);return typeof n!="function"?n:(...o)=>{try{return n.apply(i,o)}catch(u){let l=o.map(d=>JSON.stringify(d,(h,m)=>{let g=typeof m;return(0,fy.default)(["number","string","boolean"],g)?m:m===null?null:`<${g}>`})),p=`Player.${String(r)}`,c=`Exception calling ${p} (${l.join(", ")})`;throw this.events.fatalError$.next({id:p,category:f.ErrorCategory.WTF,message:c,thrown:u}),u}}}})}initVideo(e){this.config=e,this.internalsExposure?.expose({config:e,logger:this.logger,tuning:this.tuning}),this.setMuted(this.tuning.isAudioDisabled);let t=()=>{let{container:a,...n}=e;this.tracer.log("initVideo",(0,f.flattenObject)(n)),this.domContainer=py(e),this.chromecastInitializer.contentId=e.meta?.videoId,this.providerContainer=new ja({sources:e.sources,meta:e.meta??{},failoverHosts:e.failoverHosts??[],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.initDebugTelemetry(),this.initWakeLock(),this.playerInited.next(!0)},i=()=>{this.tuning.autostartOnlyIfVisible&&window.requestAnimationFrame?this.playerInitRequest=window.requestAnimationFrame(()=>t()):t()},r=()=>{this.tuning.asyncResolveClientChecker?W.isInited$.pipe((0,f.filter)(a=>!!a),(0,f.once)()).subscribe(()=>{console.log("Core SDK async start"),i()}):i()};return this.isNotActiveTabCase()?(this.tracer.log("request play from hidden tab"),(0,f.fromEvent)(document,"visibilitychange").pipe((0,f.once)()).subscribe(r)):r(),this}destroy(){this.tracer.log("destroy"),window.clearTimeout(this.hasLiveOffsetByPausedTimer),this.playerInitRequest&&window.cancelAnimationFrame(this.playerInitRequest),this.events.willDestruct$.next(),this.stop(),this.providerContainer?.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe(),this.tracer.end(),this.internalsExposure?.destroy()}prepare(){return this.subscription.add(this.playerInited.pipe((0,f.filter)(e=>!!e),(0,f.once)()).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((0,f.filter)(e=>!!e),(0,f.once)()).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((0,f.filter)(e=>!!e),(0,f.once)()).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((0,f.filter)(e=>!!e),(0,f.once)()).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((0,f.filter)(i=>!!i),(0,f.once)()).subscribe(()=>{let i=this.info.duration$.getValue(),r=this.info.isLive$.getValue(),a=e;e>=i&&!r&&(a=i-this.tuning.seekNearDurationBias),this.tracer.log("seekTime",{duration:i,isLive:r,time:e,calculatedTime:a,forcePrecise:t}),Number.isFinite(a)&&(this.events.willSeek$.next({from:this.getExactTime(),to:a}),this.desiredState.seekState.setState({state:"requested",position:a*1e3,forcePrecise:t}))})),this}seekPercent(e){return this.subscription.add(this.playerInited.pipe((0,f.filter)(t=>!!t),(0,f.once)()).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((0,f.filter)(i=>!!i),(0,f.once)()).subscribe(()=>{let i=this.desiredState.volume,a=i.getTransition()?.to.muted??this.info.muted$.getValue(),n=t??(this.tuning.isAudioDisabled||a);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,t=!1){return this.subscription.add(this.playerInited.pipe((0,f.filter)(i=>!!i),(0,f.once)()).subscribe(()=>{let i=this.desiredState.volume,r=this.tuning.isAudioDisabled&&!t||e,n=i.getTransition()?.to.volume??this.info.volume$.getValue();this.tracer.log("setMuted",{isMuted:e,nextMuted:r,volume:n,isAudioDisabled:this.tuning.isAudioDisabled,chromecastState:this.chromecastInitializer.castState$.getValue()}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setMuted(r):i.startTransitionTo({volume:n,muted:r})})),this}setVideoStream(e){return this.subscription.add(this.playerInited.pipe((0,f.filter)(t=>!!t),(0,f.once)()).subscribe(()=>{this.desiredState.videoStream.startTransitionTo(e)})),this}setAudioStream(e){return this.subscription.add(this.playerInited.pipe((0,f.filter)(t=>!!t),(0,f.once)()).subscribe(()=>{this.desiredState.audioStream.startTransitionTo(e)})),this}setQuality(e){return this.subscription.add(this.playerInited.pipe((0,f.filter)(t=>!!t),(0,f.once)()).subscribe(()=>{(0,f.assertNonNullable)(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((0,f.filter)(i=>i.length>0),(0,f.once)()).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((0,f.filter)(t=>!!t),(0,f.once)()).subscribe(()=>{this.tracer.log("setAutoQuality",{enable:e}),this.desiredState.autoVideoTrackSwitching.startTransitionTo(e)})),this}setAutoQualityLimits(e){return this.subscription.add(this.playerInited.pipe((0,f.filter)(t=>!!t),(0,f.once)()).subscribe(()=>{this.tracer.log("setAutoQualityLimits",(0,f.flattenObject)(e)),this.desiredState.autoVideoTrackLimits.startTransitionTo(e)})),this}setPredefinedQualityLimits(e){return this.subscription.add(this.playerInited.pipe((0,f.filter)(t=>!!t),(0,f.once)()).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((0,f.filter)(t=>!!t),(0,f.once)()).subscribe(()=>{(0,f.assertNonNullable)(this.providerContainer);let t=this.providerContainer?.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((0,f.filter)(t=>!!t),(0,f.once)()).subscribe(()=>{e.length&&this.tracer.log("setExternalTextTracks",(0,f.flattenObject)(e)),this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>({type:"external",...t})))})),this}selectTextTrack(e){return this.subscription.add(this.playerInited.pipe((0,f.filter)(t=>!!t),(0,f.once)()).subscribe(()=>{hy(e,this.desiredState.currentTextTrack,this.providerContainer?.providerOutput.availableTextTracks$,t=>t.id===e),this.tracer.log("selectTextTrack",{textTrackId:e})})),this}setTextTrackCueSettings(e){return this.subscription.add(this.playerInited.pipe((0,f.filter)(t=>!!t),(0,f.once)()).subscribe(()=>{this.tracer.log("setTextTrackCueSettings",{...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((0,f.filter)(t=>!!t),(0,f.once)()).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((0,f.filter)(i=>!!i),(0,f.once)()).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((0,f.filter)(t=>!!t),(0,f.once)()).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((0,f.filter)(i=>!!i),(0,f.once)()).subscribe(()=>{let i=this.getScene3D();if(this.tracer.log("moveCameraFocusPX",{isScene3DAvailable:!!i,dxpx:e,dypx:t}),i){let r=i.getCameraRotation(),a=i.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:r.x+a.x,y:r.y+a.y})}})),this}holdCamera(){return this.subscription.add(this.playerInited.pipe((0,f.filter)(e=>e),(0,f.once)()).subscribe(()=>{let e=this.getScene3D();e&&e.holdCamera()})),this}releaseCamera(){return this.subscription.add(this.playerInited.pipe((0,f.filter)(e=>!!e),(0,f.once)()).subscribe(()=>{let e=this.getScene3D();e&&e.releaseCamera()})),this}getExactTime(){if(!this.providerContainer)return 0;let e=this.providerContainer.providerOutput.element$.getValue();if((0,f.isNullable)(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),i=t.state==="none"?void 0:t.position;return(0,f.isNonNullable)(i)?i/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}getScene3D(){let e=this.providerContainer?.current$.getValue();if(e?.provider?.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((0,f.merge)(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe((0,f.map)(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe((0,f.map)(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe((0,f.map)(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe((0,f.map)(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe((0,f.map)(e=>e.to)).subscribe(e=>{this.info.autoQualityLimits$.next(e);let{highQualityLimit:t,trafficSavingLimit:i}=this.tuning.autoTrackSelection;this.info.predefinedQualityLimitType$.next(_l(e,t,i))})),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe((0,f.filter)(({from:e})=>e==="stopped"),(0,f.once)()).subscribe(()=>{this.initedAt=(0,f.now)(),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"ready":this.events.willReady$.next();break;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",(0,f.flattenObject)(n)),n.state==="requested"?this.desiredState.seekState.setState({...n,state:"applying"}):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:f.ErrorCategory.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.soundProhibitedEvent$.pipe((0,f.once)()).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",(0,f.flattenObject)(n)),n.state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe((0,f.map)(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe((0,f.map)(n=>n.destination),(0,f.filterChanged)()).subscribe(()=>this.isPlaybackStarted=!1)).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add((0,f.combine)({availableVideoTracks:e.providerOutput.availableVideoTracks$,currentVideoStream:e.providerOutput.currentVideoStream$}).pipe((0,f.map)(({availableVideoTracks:n,currentVideoStream:o})=>n.filter(u=>o?o.id===u.streamId:!0).map(({quality:u})=>u).sort((u,l)=>(0,f.isInvariantQuality)(u)?1:(0,f.isInvariantQuality)(l)?-1:(0,f.isHigher)(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((0,f.filterChanged)()).subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.pipe((0,f.filter)(n=>(0,f.isNonNullable)(n))).subscribe(n=>{this.info.currentQuality$.next(n?.quality),this.info.videoBitrate$.next(n?.bitrate)})).add(e.providerOutput.currentVideoSegmentLength$.pipe((0,f.filterChanged)((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.pipe((0,f.filterChanged)((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe((0,f.filterChanged)()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe((0,f.filterChanged)()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe((0,f.filterChanged)()).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??{})})).add(e.providerOutput.currentBuffer$.pipe((0,f.map)(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((0,f.tap)(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((0,f.combine)({hasLiveOffsetByPaused:(0,f.merge)(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe((0,f.map)(n=>n.to),(0,f.filterChanged)(),(0,f.map)(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((0,f.combine)({atLiveEdge:(0,f.combine)({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:Nc({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe((0,f.map)(({isLive:n,position:o,isLowLatency:u})=>{let l=this.getActiveLiveDelay(u);return n&&Math.abs(o)<l/1e3}),(0,f.filterChanged)(),(0,f.tap)(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe((0,f.map)(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add((0,f.combine)({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe((0,f.map)(({isLive:n,position:o,duration:u})=>n&&(Math.abs(u)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),(0,f.filterChanged)(),(0,f.tap)(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe((0,f.map)(n=>n.muted),(0,f.filterChanged)()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe((0,f.map)(n=>n.volume),(0,f.filterChanged)()).subscribe(this.info.volume$)).add(Nc({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add((0,f.merge)(e.providerOutput.endedEvent$.pipe((0,f.mapTo)(!0)),e.providerOutput.seekedEvent$.pipe((0,f.mapTo)(!1))).pipe((0,f.filterChanged)()).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((0,f.map)(n=>({id:n?`No${n}`:"NoProviders",category:f.ErrorCategory.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((0,f.once)(),(0,f.map)(n=>n??(0,f.now)()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe((0,f.once)(),(0,f.map)(()=>(0,f.now)()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe((0,f.once)(),(0,f.map)(()=>(0,f.now)()-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 f.ValueSubject(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let i=new f.ValueSubject(!0);this.subscription.add(e.current$.subscribe(()=>i.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe((0,f.filter)(({to:n})=>n==="playing"),(0,f.once)()).subscribe(()=>i.next(!1)));let r=0,a=(0,f.merge)(e.providerOutput.isBuffering$,t,i).pipe((0,f.map)(()=>{let n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||i.getValue();return n&&!o}),(0,f.filterChanged)());this.subscription.add(a.subscribe(n=>{n?r=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(r),this.info.isStalled$.next(!1))})),this.subscription.add((0,f.merge)(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{let n=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:n?.videoWidth,height:n?.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{let o=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:n?.size?.width,height:n?.size?.height},{width:o?.videoWidth,height:o?.videoHeight})})).add(e.providerOutput.is3DVideo$.subscribe(this.info.is3DVideo$)),this.subscription.add((0,f.merge)(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(),p=this.chromecastInitializer.castState$.getValue(),c;p==="CONNECTED"?c="second_screen":u?l?n?c="pip":o?c="fullscreen":c="inline":c="invisible":c="none",this.info.surface$.getValue()!==c&&this.info.surface$.next(c)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe((0,f.map)(e=>e?.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){let t=new f.Subscription;this.subscription.add(t),this.subscription.add(e.current$.pipe((0,f.filterChanged)((i,r)=>i.provider===r.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe((0,f.filter)(i=>i.length>0),(0,f.once)()).subscribe(i=>{this.setStartingVideoTrack(i)}))}))}setStartingVideoTrack(e){let t;this.wasSetStartedQuality=!0;let i=this.explicitInitialQuality??this.info.currentQuality$.getValue();i&&(t=e.find(({quality:r})=>r===i),t||this.setAutoQuality(!0)),t||(t=Yt(e,{container:this.domContainer.getBoundingClientRect(),panelSize:this.config.panelSize,estimatedThroughput:this.throughputEstimator.throughput$.getValue(),tuning:this.tuning.autoTrackSelection,limits:this.desiredState.autoVideoTrackLimits.getState(),playbackRate:this.info.currentPlaybackRate$.getValue(),forwardBufferHealth:0,abrLogger:this.abrLogger})),this.desiredState.videoTrack.startTransitionTo(t),this.info.currentQuality$.next(t.quality),this.info.videoBitrate$.next(t.bitrate)}initLogs(){this.subscription.add((0,f.merge)(this.desiredState.videoTrack.stateChangeStarted$.pipe((0,f.map)(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe((0,f.map)(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe((0,f.map)(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe((0,f.map)(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe((0,f.map)(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe((0,f.map)(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe((0,f.map)(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe((0,f.map)(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe((0,f.map)(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(){let e=this.providerContainer?.providerOutput;(0,f.assertNonNullable)(this.providerContainer),(0,f.assertNonNullable)(e),sg(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(t=>rg(t)),this.providerContainer.current$.subscribe(({type:t})=>ms("provider",t)),e.duration$.subscribe(t=>ms("duration",t)),e.availableVideoTracks$.pipe((0,f.filter)(t=>!!t.length),(0,f.once)()).subscribe(t=>ms("tracks",t)),this.events.fatalError$.subscribe(new tt("fatalError")),this.events.managedError$.subscribe(new tt("managedError")),e.position$.subscribe(new tt("position")),e.currentVideoTrack$.pipe((0,f.map)(t=>t?.quality)).subscribe(new tt("quality")),this.info.currentBuffer$.subscribe(new tt("buffer")),e.isBuffering$.subscribe(new tt("isBuffering"))].forEach(t=>this.subscription.add(t)),ms("codecs",W.video.supportedCodecs)}initTracerSubscription(){let e=(0,f.getTraceSubscriptionMethod)(this.tracer.log.bind(this.tracer)),t=(0,f.getTraceSubscriptionMethod)(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((0,f.filterChanged)()).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((0,f.combine)({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe((0,f.filter)(({currentQuality:i,videoBitrate:r})=>!!i&&!!r),(0,f.filterChanged)((i,r)=>i.currentQuality===r.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe((0,f.filter)(i=>i>0),(0,f.filterChanged)()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe((0,f.filter)(i=>i>0),(0,f.filterChanged)()).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((0,f.combine)({currentBuffer:this.info.currentBuffer$.pipe((0,f.filter)(i=>i.end>0),(0,f.filterChanged)((i,r)=>i.end===r.end&&i.start===r.start)),position:this.info.position$.pipe((0,f.filterChanged)())}).pipe((0,f.throttle)(1e3)).subscribe(e("currentBufferAndPosition"))).add(this.info.duration$.pipe((0,f.filterChanged)()).subscribe(e("duration"))).add(this.info.isBuffering$.subscribe(e("isBuffering"))).add(this.info.isLive$.pipe((0,f.filterChanged)()).subscribe(e("isLive"))).add(this.info.canChangePlaybackSpeed$.pipe((0,f.filterChanged)()).subscribe(e("canChangePlaybackSpeed"))).add((0,f.combine)({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe((0,f.filter)(({liveTime:i,liveBufferTime:r})=>!!i&&!!r),(0,f.throttle)(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe((0,f.filterChanged)(),(0,f.filter)(i=>i===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe((0,f.filterChanged)(),(0,f.filter)(i=>i===!0)).subscribe(e("atLiveDurationEdge"))).add(this.info.muted$.pipe((0,f.filterChanged)()).subscribe(e("muted"))).add(this.info.volume$.pipe((0,f.filterChanged)()).subscribe(e("volume"))).add(this.info.isEnded$.pipe((0,f.filterChanged)(),(0,f.filter)(i=>i===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add((0,f.combine)({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe((0,f.filter)(({throughputEstimation:i,rtt:r})=>!!i&&!!r),(0,f.throttle)(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe((0,f.filterChanged)(),(0,f.filter)(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?.release(),e=void 0},i=async()=>{t(),e=await window.navigator.wakeLock.request("screen").catch(r=>{r instanceof DOMException&&r.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:f.ErrorCategory.DOM,message:String(r)})})};this.subscription.add((0,f.merge)((0,f.fromEvent)(document,"visibilitychange"),(0,f.fromEvent)(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{let r=document.visibilityState==="visible",a=this.desiredState.playbackState.getState()==="playing",n=!!e&&!e?.released;r&&a?n||i():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){let i=e.find(r=>r.quality===t);this.tracer.log("setVideoTrackIdByQuality",(0,f.flattenObject)({quality:t,availableTracks:(0,f.flattenObject)(e),track:(0,f.flattenObject)(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&&!Ts()}};var Jt=require("@vkontakte/videoplayer-shared"),gL=`@vkontakte/videoplayer-core@${_o}`;
|
|
185
|
+
`})|(?<privateuse2>${e}))$`.replace(/[\s\t\n]/g,"");return new RegExp(d,"i")}var Ec=H(Ut(),1);var So=require("@vkontakte/videoplayer-shared"),Dv=({id:s,width:e,height:t,bitrate:i,fps:r,quality:a,streamId:n})=>{let o=(a?Pi(a):void 0)??(0,So.videoSizeToQuality)({width:e,height:t});return o&&{id:s,quality:o,bitrate:i,size:{width:e,height:t},fps:r,streamId:n}},Cv=({id:s,bitrate:e})=>({id:s,bitrate:e}),Vv=({language:s,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:s,label:e}),Ov=({language:s,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:s,label:e}),wc=({id:s,language:e,label:t,codecs:i,isDefault:r})=>({id:s,language:e,label:t,codec:(0,Ec.default)(i.split("."),0),isDefault:r}),Ac=({id:s,language:e,label:t,hdr:i,codecs:r})=>({id:s,language:e,hdr:i,label:t,codec:(0,Ec.default)(r.split("."),0)}),Pc=s=>"url"in s,st=s=>s.type==="template",$a=s=>s instanceof DOMException&&(s.name==="AbortError"||s.code===20);var _v=s=>{s.sort((t,i)=>t.from-i.from);let e=[s[0]];for(let t=1;t<s.length;t++){let{from:i,to:r}=s[t],a=e[e.length-1];a.to>=i?a.to=Math.max(a.to,r):e.push(s[t])}return e},tr=(s,e)=>{for(let t of s)if(e(t))return t;return null},Fv=s=>{let e=!1,t=(0,So.throttleFn)(()=>{e=!0},s);return()=>{try{return t(),e}finally{e=!1}}};var Nv=s=>{if(!s?.startsWith("P"))return;let e=(n,o)=>{let u=n?parseFloat(n.replace(",",".")):NaN;return(isNaN(u)?0:u)*o},i=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(s),r=i?.[1]==="-"?-1:1,a={days:e(i?.[5],r),hours:e(i?.[6],r),minutes:e(i?.[7],r),seconds:e(i?.[8],r)};return a.days*24*60*60*1e3+a.hours*60*60*1e3+a.minutes*60*1e3+a.seconds*1e3},vi=(s,e)=>{let t=s;t=(0,kc.default)(t,"$$","$");let i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[r,a]of(0,Uv.default)(i)){let n=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=(0,kc.default)(t,n,(o,u)=>(0,Da.isNullable)(a)?o:(0,Da.isNullable)(u)?a:(0,qv.default)(a,parseInt(u,10),"0"))}return t},Hv=(s,e)=>{let i=new DOMParser().parseFromString(s,"application/xml"),r={video:[],audio:[],text:[]},a=i.children[0],n=Array.from(a.querySelectorAll("MPD > BaseURL").values()).map(D=>D.textContent?.trim()??""),o=(0,jv.default)(n,0)??"",u=a.getAttribute("type")==="dynamic",l=a.getAttribute("availabilityStartTime"),d=a.getAttribute("publishTime"),c=a.getElementsByTagName("vk:Attrs")[0],p=c?.getElementsByTagName("vk:XLatestSegmentPublishTime")[0].textContent,h=c?.getElementsByTagName("vk:XStreamIsLive")[0].textContent,m=c?.getElementsByTagName("vk:XStreamIsUnpublished")[0].textContent,g=c?.getElementsByTagName("vk:XPlaybackDuration")[0].textContent,v;u&&(v={availabilityStartTime:l?new Date(l).getTime():0,publishTime:d?new Date(d).getTime():0,latestSegmentPublishTime:p?new Date(p).getTime():0,streamIsAlive:h==="yes",streamIsUnpublished:m==="yes"});let T,w=a.getAttribute("mediaPresentationDuration"),x=[...a.getElementsByTagName("Period")],M=x.reduce((D,I)=>({...D,[I.id]:I.children}),{}),B=x.reduce((D,I)=>({...D,[I.id]:I.getAttribute("duration")}),{});w?T=Nv(w):(0,Rc.default)(B).filter(D=>D).length&&!u?T=(0,Rc.default)(B).reduce((D,I)=>D+(Nv(I)??0),0):g&&(T=parseInt(g,10));let F=0,G=a.getAttribute("profiles")?.split(",")??[];for(let D of x.map(I=>I.id))for(let I of M[D]){let U=I.getAttribute("id")??"id"+(F++).toString(10),k=I.getAttribute("mimeType")??"",R=I.getAttribute("codecs")??"",C=I.getAttribute("contentType")??k?.split("/")[0],be=I.getAttribute("profiles")?.split(",")??[],N=$v(I.getAttribute("lang")??"")??{},re=I.querySelector("Label")?.textContent?.trim()??void 0,le=I.querySelectorAll("Representation"),Te=I.querySelector("SegmentTemplate"),Be=I.querySelector("Role")?.getAttribute("value")??void 0,Ie=C,ce={id:U,language:N.language,isDefault:Be==="main",label:re,codecs:R,hdr:Ie==="video"&&Dr(R),mime:k,representations:[]};for(let V of le){let z=V.getAttribute("lang")??void 0,Ne=re??I.getAttribute("label")??V.getAttribute("label")??void 0,$e=V.querySelector("BaseURL")?.textContent?.trim()??"",pe=new URL($e||o,e).toString(),Ce=V.getAttribute("mimeType")??k,pt=V.getAttribute("codecs")??R??"",Ke;if(C==="text"){let Ae=V.getAttribute("id")||"",ht=N.privateuse?.includes("x-auto")||Ae.includes("_auto"),Fe=V.querySelector("SegmentTemplate");if(Fe){let $t={representationId:V.getAttribute("id")??void 0,bandwidth:V.getAttribute("bandwidth")??void 0},Zt=parseInt(V.getAttribute("bandwidth")??"",10)/1e3,ei=parseInt(Fe.getAttribute("startNumber")??"",10)??1,ft=parseInt(Fe.getAttribute("timescale")??"",10),Ci=Fe.querySelectorAll("SegmentTimeline S")??[],mt=Fe.getAttribute("media");if(!mt)continue;let ti=[],ii=0,ri="",bt=0,Dt=ei,oe=0;for(let xe of Ci){let Xe=parseInt(xe.getAttribute("d")??"",10),he=parseInt(xe.getAttribute("r")??"",10)||0,Ue=parseInt(xe.getAttribute("t")??"",10);oe=Number.isFinite(Ue)?Ue:oe;let Je=Xe/ft*1e3,gt=oe/ft*1e3;for(let ke=0;ke<he+1;ke++){let qe=vi(mt,{...$t,segmentNumber:Dt.toString(10),segmentTime:(oe+ke*Xe).toString(10)}),St=(gt??0)+ke*Je,Vt=St+Je;Dt++,ti.push({time:{from:St,to:Vt},url:qe})}oe+=(he+1)*Xe,ii+=(he+1)*Je}bt=oe/ft*1e3,ri=vi(mt,{...$t,segmentNumber:Dt.toString(10),segmentTime:oe.toString(10)});let Ct={time:{from:bt,to:1/0},url:ri},Ve={type:"template",baseUrl:pe,segmentTemplateUrl:mt,initUrl:"",totalSegmentsDurationMs:ii,segments:ti,nextSegmentBeyondManifest:Ct,timescale:ft};Ke={id:Ae,kind:"text",segmentReference:Ve,profiles:[],duration:T,bitrate:Zt,mime:"",codecs:"",width:0,height:0,isAuto:ht}}else Ke={id:Ae,isAuto:ht,kind:"text",url:pe}}else{let Ae=V.getAttribute("contentType")??Ce?.split("/")[0]??C,ht=I.getAttribute("profiles")?.split(",")??[],Fe=parseInt(V.getAttribute("width")??"",10),$t=parseInt(V.getAttribute("height")??"",10),Zt=parseInt(V.getAttribute("bandwidth")??"",10)/1e3,ei=V.getAttribute("frameRate")??"",ft=V.getAttribute("quality")??void 0,Ci=ei?Xn(ei):void 0,mt=V.getAttribute("id")??"id"+(F++).toString(10),ti=Ae==="video"?`${$t}p`:Ae==="audio"?`${Zt}Kbps`:pt,ii=`${mt}@${ti}`,ri=[...G,...be,...ht],bt,Dt=V.querySelector("SegmentBase"),oe=V.querySelector("SegmentTemplate")??Te;if(Dt){let Ve=V.querySelector("SegmentBase Initialization")?.getAttribute("range")??"",[xe,Xe]=Ve.split("-").map(qe=>parseInt(qe,10)),he={from:xe,to:Xe},Ue=V.querySelector("SegmentBase")?.getAttribute("indexRange"),[Je,gt]=Ue?Ue.split("-").map(qe=>parseInt(qe,10)):[],ke=Ue?{from:Je,to:gt}:void 0;bt={type:"byteRange",url:pe,initRange:he,indexRange:ke}}else if(oe){let Ve={representationId:V.getAttribute("id")??void 0,bandwidth:V.getAttribute("bandwidth")??void 0},xe=parseInt(oe.getAttribute("timescale")??"",10),Xe=oe.getAttribute("initialization")??"",he=oe.getAttribute("media"),Ue=parseInt(oe.getAttribute("startNumber")??"",10)??1,Je=vi(Xe,Ve);if(!he)throw new ReferenceError("No media attribute in SegmentTemplate");let gt=oe.querySelectorAll("SegmentTimeline S")??[],ke=[],qe=0,St="",Vt=0;if(gt.length){let si=Ue,Ee=0;for(let vt of gt){let Re=parseInt(vt.getAttribute("d")??"",10),Ze=parseInt(vt.getAttribute("r")??"",10)||0,ai=parseInt(vt.getAttribute("t")??"",10);Ee=Number.isFinite(ai)?ai:Ee;let Vi=Re/xe*1e3,Co=Ee/xe*1e3;for(let ni=0;ni<Ze+1;ni++){let Vo=vi(he,{...Ve,segmentNumber:si.toString(10),segmentTime:(Ee+ni*Re).toString(10)}),Ur=(Co??0)+ni*Vi,Oo=Ur+Vi;si++,ke.push({time:{from:Ur,to:Oo},url:Vo})}Ee+=(Ze+1)*Re,qe+=(Ze+1)*Vi}Vt=Ee/xe*1e3,St=vi(he,{...Ve,segmentNumber:si.toString(10),segmentTime:Ee.toString(10)})}else if((0,Da.isNonNullable)(T)){let Ee=parseInt(oe.getAttribute("duration")??"",10)/xe*1e3,vt=Math.ceil(T/Ee),Re=0;for(let Ze=1;Ze<vt;Ze++){let ai=vi(he,{...Ve,segmentNumber:Ze.toString(10),segmentTime:Re.toString(10)});ke.push({time:{from:Re,to:Re+Ee},url:ai}),Re+=Ee}Vt=Re,St=vi(he,{...Ve,segmentNumber:vt.toString(10),segmentTime:Re.toString(10)})}let Do={time:{from:Vt,to:1/0},url:St};bt={type:"template",baseUrl:pe,segmentTemplateUrl:he,initUrl:Je,totalSegmentsDurationMs:qe,segments:ke,nextSegmentBeyondManifest:Do,timescale:xe}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!Ae||!Ce)continue;let Ct={video:"video",audio:"audio",text:"text"}[Ae];if(!Ct)continue;Ie||=Ct,Ke={id:ii,kind:Ct,segmentReference:bt,profiles:ri,duration:T,bitrate:Zt,mime:Ce,codecs:pt,width:Fe,height:$t,fps:Ci,quality:ft}}ce.language||=z,ce.label||=Ne,ce.mime||=Ce,ce.codecs||=pt,ce.hdr||=Ie==="video"&&Dr(pt),ce.representations.push(Ke)}if(Ie){let V=r[Ie].find(z=>z.id===ce.id);if(V&&ce.representations.every(z=>st(z.segmentReference)))for(let z of V.representations){let $e=ce.representations.find(Ce=>Ce.id===z.id)?.segmentReference,pe=z.segmentReference;pe.segments.push(...$e.segments),pe.nextSegmentBeyondManifest=$e.nextSegmentBeyondManifest}else r[Ie].push(ce)}}return{duration:T,streams:r,baseUrls:n,live:v}};var To=require("@vkontakte/videoplayer-shared");var vo=s=>{let e=[];for(let t=0;t<s.length;t++){let i=Math.floor(s.start(t)*1e3),r=Math.ceil(s.end(t)*1e3);e.push(i,r)}return e};var yo=class{constructor(e,t){this.lastUpdateTs=0;this.lastCallTs=0;this.prevRanges=[];this.subscription=new To.Subscription;this.mediaSource=e,this.sourceBuffer=t,this.subscription.add((0,To.fromEvent)(this.sourceBuffer,"updateend").subscribe(()=>this.updateend()))}updateend(){if(!Y(this.mediaSource,this.sourceBuffer))return;let{prevRanges:e}=this,t=vo(this.sourceBuffer.buffered);this.prevRanges=t,this.isRangesRemoved(e,t)&&(this.lastUpdateTs=Date.now())}isRangesRemoved(e,t){if(e.length!==t.length)return!0;for(let i=0;i<e.length;i+=2){let r=e[i],a=e[i+1],n=t[i],o=t[i+1];if(n>r||o<a)return!0}return!1}wasUpdated(){let{lastCallTs:e,lastUpdateTs:t}=this;return this.lastCallTs=Date.now(),e<=t}destroy(){this.subscription.unsubscribe()}};var Ca=class{constructor(e,t,i,{fetcher:r,tuning:a,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new P.ValueSubject(0);this.currentLowLatencySegmentLength$=new P.ValueSubject(0);this.currentSegmentLength$=new P.ValueSubject(0);this.onLastSegment$=new P.ValueSubject(!1);this.fullyBuffered$=new P.ValueSubject(!1);this.playingRepresentation$=new P.ValueSubject(void 0);this.playingRepresentationInit$=new P.ValueSubject(void 0);this.error$=new P.Subject;this.gaps=[];this.subscription=new P.Subscription;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new de;this.switchAbortController=new de;this.destroyAbortController=new de;this.bufferLimit=1/0;this.failedDownloads=0;this.baseUrls=[];this.baseUrlsIndex=0;this.isLive=!1;this.liveUpdateSegmentIndex=0;this.liveInitialAdditionalOffset=0;this.isSeekingLive=!1;this.index=0;this.lastDataObtainedTimestampMs=0;this.loadByteRangeSegmentsTimeoutId=0;this.sourceBufferBufferedDiff=null;this.startWith=(0,P.abortable)(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);(0,P.assertNonNullable)(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new wv(this.sourceBuffer),this.sourceBufferBufferedDiff=new yo(this.mediaSource,this.sourceBuffer),this.subscription.add((0,P.fromEvent)(this.sourceBuffer,"updateend").subscribe(()=>{this.maintain()})),this.subscription.add((0,P.fromEvent)(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:P.ErrorCategory.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o||!Y(this.mediaSource,this.sourceBuffer))return;let u=Math.min(this.bufferLimit,Lr(this.sourceBuffer.buffered)*.8);this.bufferLimit=u;let l=ze(this.sourceBuffer.buffered,o),d=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(o,n*2,l<d).catch(c=>{this.handleAsyncError(c,"pruneBuffer")})})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(n=>this.error$.next(n))),yield this.loadInit(t,"high",!0);let i=this.initData.get(t.id),r=this.segments.get(t.id),a=this.parsedInitData.get(t.id);(0,P.assertNonNullable)(i,"No init buffer for starting representation"),(0,P.assertNonNullable)(r,"No segments for starting representation"),i instanceof ArrayBuffer&&(this.searchGaps(r,t),yield this.sourceBufferTaskQueue.append(i,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(a))}.bind(this));this.switchTo=(0,P.abortable)(this.destroyAbortController.signal,async function*(e,t=!1){if(!Y(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);(0,P.assertNonNullable)(i,`No such representation ${e}`);let r=this.segments.get(e),a=this.initData.get(e);if((0,P.isNullable)(a)||(0,P.isNullable)(r)?yield this.loadInit(i,"high",!1):a instanceof Promise&&(yield a),r=this.segments.get(e),(0,P.assertNonNullable)(r,"No segments for starting representation"),a=this.initData.get(e),!(!a||!(a instanceof ArrayBuffer)||!this.sourceBuffer||!Y(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(a,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer();else{let n=this.getCurrentPosition();(0,P.isNonNullable)(n)&&!this.isLive&&(this.bufferLimit=1/0,await this.pruneBuffer(n,1/0,!0)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}this.maintain()}}.bind(this));this.switchToOld=(0,P.abortable)(this.destroyAbortController.signal,async function*(e,t=!1){if(!Y(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);(0,P.assertNonNullable)(i,`No such representation ${e}`);let r=this.segments.get(e),a=this.initData.get(e);if((0,P.isNullable)(a)||(0,P.isNullable)(r)?yield this.loadInit(i,"high",!1):a instanceof Promise&&(yield a),r=this.segments.get(e),(0,P.assertNonNullable)(r,"No segments for starting representation"),a=this.initData.get(e),!(!a||!(a instanceof ArrayBuffer)||!this.sourceBuffer||!Y(this.mediaSource,this.sourceBuffer)))if(yield this.abort(),yield this.sourceBufferTaskQueue.append(a,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer(),this.maintain();else{let n=this.getCurrentPosition();(0,P.isNonNullable)(n)&&(this.isLive||(this.bufferLimit=1/0,await this.pruneBuffer(n,1/0,!0)),this.maintain(n)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}}.bind(this));this.seekLive=(0,P.abortable)(this.destroyAbortController.signal,async function*(e){let t=(0,xo.default)(e,u=>u.representations)??[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let u of this.representations.keys()){let l=t.find(p=>p.id===u);l&&this.representations.set(u,l);let d=this.representations.get(u);if(!d||!st(d.segmentReference))return;let c=this.getActualLiveStartingSegments(d.segmentReference);this.segments.set(d.id,c)}let i=this.switchingToRepresentationId??this.downloadingRepresentationId,r=this.representations.get(i);(0,P.assertNonNullable)(r);let a=this.segments.get(i);(0,P.assertNonNullable)(a,"No segments for starting representation");let n=this.initData.get(i);if((0,P.assertNonNullable)(n,"No init buffer for starting representation"),!(n instanceof ArrayBuffer))return;let o=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,yield this.abort(),o&&(yield this.sourceBufferTaskQueue.remove(o.from*1e3,o.to*1e3,this.destroyAbortController.signal)),this.searchGaps(a,r),yield this.sourceBufferTaskQueue.append(n,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this));this.fetcher=r,this.tuning=a,this.compatibilityMode=u,this.forwardBufferTarget=a.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=o,this.isLive=!!l?.live,this.baseUrls=l?.baseUrls??[],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){!Y(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new de,(0,P.abortable)(this.switchAbortController.signal,async function*(i,r=!1){this.switchingToRepresentationId=i;let a=this.representations.get(i);(0,P.assertNonNullable)(a,`No such representation ${i}`);let n=this.segments.get(i),o=this.initData.get(i);if((0,P.isNullable)(o)||(0,P.isNullable)(n)?yield this.loadInit(a,"high",!1):o instanceof Promise&&(yield o),n=this.segments.get(i),(0,P.assertNonNullable)(n,"No segments for starting representation"),o=this.initData.get(i),!(!(o instanceof ArrayBuffer)||!this.sourceBuffer||!Y(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();(0,P.isNonNullable)(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(){!(0,P.isNullable)(this.sourceBuffer)&&!this.sourceBuffer.updating&&(this.sourceBuffer.mode="segments")}async abort(){for(let e of this.activeSegments)this.abortSegment(e.segment);return this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new de,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if((0,P.isNullable)(e)||(0,P.isNullable)(this.downloadingRepresentationId)||(0,P.isNullable)(this.playingRepresentationId)||(0,P.isNullable)(this.sourceBuffer)||!Y(this.mediaSource,this.sourceBuffer)||(0,P.isNonNullable)(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if((0,P.assertNonNullable)(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;let r=i.find(d=>e>=d.time.from&&e<d.time.to);(0,P.isNonNullable)(r)&&isFinite(r.time.from)&&isFinite(r.time.to)&&this.currentSegmentLength$.next(r?.time.to-r.time.from);let a=e,n=100;if(this.playingRepresentationId!==this.downloadingRepresentationId){let d=ze(this.sourceBuffer.buffered,e),c=r?r.time.to+n:-1/0;r&&r.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&d>=r.time.to-e+n&&(a=c)}if(isFinite(this.bufferLimit)&&Lr(this.sourceBuffer.buffered)>=this.bufferLimit){let d=ze(this.sourceBuffer.buffered,e),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,d<c).catch(p=>{this.handleAsyncError(p,"pruneBuffer")});return}let u=null;if(!this.activeSegments.size&&(u=this.selectForwardBufferSegments(i,t.segmentReference.type,a),u?.length)){let d="auto";if(this.tuning.dash.useFetchPriorityHints&&r)if((0,Io.default)(u,r))d="high";else{let c=(0,Fr.default)(u,0);c&&c.time.from-r.time.to>=this.forwardBufferTarget/2&&(d="low")}this.loadSegments(u,t,d).catch(c=>{this.handleAsyncError(c,"loadSegments")})}(!this.preloadOnly&&!this.allInitsLoaded&&r&&r.status==="fed"&&!u?.length&&ze(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let l=(0,Fr.default)(i,-1);!this.isLive&&l&&(this.fullyBuffered$.next(l.time.to-e-ze(this.sourceBuffer.buffered,e)<n),this.onLastSegment$.next(e-l.time.from>0))}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}searchGaps(e,t){this.gaps=[];let i=0,r=this.isLive?this.liveInitialAdditionalOffset:0;for(let a of e)Math.trunc(a.time.from-i)>0&&this.gaps.push({representation:t.id,from:i,to:a.time.from+r,persistent:!0}),i=a.time.to;(0,P.isNonNullable)(t.duration)&&t.duration-i>0&&!this.isLive&&this.gaps.push({representation:t.id,from:i,to:t.duration,persistent:!0})}getActualLiveStartingSegments(e){let t=e.segments,i=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,r=[],a=0,n=t.length-1;do r.unshift(t[n]),a+=t[n].time.to-t[n].time.from,n--;while(a<i&&n>=0);return this.liveInitialAdditionalOffset=a-i,this.isActiveLowLatency()?[r[0]]:r}getLiveSegmentsToLoadState(e){let t=(0,xo.default)(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?.length)return{from:i[0].time.from,to:i[i.length-1].time.to}}updateLive(e){let t=(0,xo.default)(e?.streams[this.kind],i=>i.representations)??[];if(![...this.segments.values()].every(i=>!i.length))for(let i of t){if(!i||!st(i.segmentReference))return;let r=i.segmentReference.segments.map(l=>({...l,status:"none",size:void 0})),a=100,n=this.segments.get(i.id)??[],o=(0,Fr.default)(n,-1)?.time.to??0,u=r?.findIndex(l=>o>=l.time.from+a&&o<=l.time.to+a);if(u===-1){this.liveUpdateSegmentIndex=0;let l=this.getActualLiveStartingSegments(i.segmentReference);this.segments.set(i.id,l)}else{let l=r.slice(u+1);this.segments.set(i.id,[...n,...l])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;(0,P.assertNonNullable)(e);let t=this.segments.get(e);if(t?.length){let i=t[t.length-1];this.updateLowLatencyLiveIfNeeded(i)}}updateLowLatencyLiveIfNeeded(e){let t=0;for(let i of this.representations.values()){let r=i.segmentReference;if(!st(r))return;let a=this.segments.get(i.id);if(!a)continue;let n=a.find(u=>Math.floor(u.time.from)===Math.floor(e.time.from));if(n&&!isFinite(n.time.to)&&(n.time.to=e.time.to,t=n.time.to-n.time.from),!!!a.find(u=>Math.floor(u.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let u=Math.round(e.time.to*r.timescale/1e3).toString(10),l=vi(r.segmentTemplateUrl,{segmentTime:u});a.push({status:"none",time:{from:e.time.to,to:1/0},url:l})}}this.currentLowLatencySegmentLength$.next(t)}findSegmentStartTime(e){let t=this.switchingToRepresentationId??this.downloadingRepresentationId??this.playingRepresentationId;if(!t)return;let i=this.segments.get(t);return i?i.find(a=>a.time.from<=e&&a.time.to>=e)?.time.from??void 0:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),this.sourceBufferTaskQueue?.destroy(),this.sourceBufferBufferedDiff?.destroy(),this.gapDetectionIdleCallback&&Xt&&Xt(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&Xt&&Xt(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer)try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(e){if(!(e instanceof DOMException&&e.name==="NotFoundError"))throw e}this.sourceBuffer=null,this.downloadAbortController.abort(),this.switchAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,i){return this.checkEjectedSegments(),this.isLive?this.selectForwardBufferSegmentsLive(e,i):this.selectForwardBufferSegmentsRecord(e,t,i)}selectForwardBufferSegmentsLive(e,t){if(this.playingRepresentationId!==this.downloadingRepresentationId){let i=e.findIndex(r=>t>=r.time.from&&t<r.time.to);this.liveUpdateSegmentIndex=i}return this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):null}selectForwardBufferSegmentsRecord(e,t,i){let r=this.getForwardBufferDuration(i),a=e.findIndex(({status:p,time:{from:h,to:m}},g)=>{let v=h<=i&&m>=i,T=h>i||v||g===0&&i===0,w=Math.min(this.forwardBufferTarget,this.bufferLimit),x=this.preloadOnly&&h<=i+w||r<w&&m-h>=w||m<=i+w;return(p==="none"||p==="partially_ejected"&&T&&x&&this.sourceBuffer&&Y(this.mediaSource,this.sourceBuffer)&&!(Ye(this.sourceBuffer.buffered,h)&&Ye(this.sourceBuffer.buffered,m)))&&T&&x});if(a===-1)return null;if(t!=="byteRange")return e.slice(a,a+1);let n=e,o=0,u=0,l=[],d=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,c=this.preloadOnly?this.forwardBufferTarget:0;for(let p=a;p<n.length&&(o<=d||u<=c);p++){let h=n[p];if(o+=h.byte.to+1-h.byte.from,u+=h.time.to+1-h.time.from,h.status==="none"||h.status==="partially_ejected")l.push(h);else break}return l}async loadSegments(e,t,i="auto"){st(t.segmentReference)?await this.loadTemplateSegment(e[0],t,i):await this.loadByteRangeSegments(e,t,i)}async loadTemplateSegment(e,t,i="auto"){e.status="downloading";let r={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(r);let{range:a,url:n,signal:o,onProgress:u,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(await(0,P.abortable)(o,async function*(){let d=(0,P.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>setTimeout(c,d))}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let d=await this.fetcher.fetch(n,{range:a,signal:o,onProgress:u,priority:i,isLowLatency:this.isActiveLowLatency()});if(this.lastDataObtainedTimestampMs=(0,P.now)(),!d)return;let c=new DataView(d),p=Ba(t.mime);if(!isFinite(r.segment.time.to)){let g=t.segmentReference.timescale;r.segment.time.to=p.getChunkEndTime(c,g)}u&&r.feedingBytes&&l?await Promise.all(l):await this.sourceBufferTaskQueue.append(c,o);let{serverDataReceivedTimestamp:h,serverDataPreparedTime:m}=p.getServerLatencyTimestamps(c);h&&m&&this.currentLiveSegmentServerLatency$.next(m-h),r.segment.status="downloaded",this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(d){this.abortActiveSegments([e]),$a(d)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}updateRepresentationsBaseUrlIfNeeded(){if(!this.tuning.dash.enableBaseUrlSupport||!this.baseUrls.length||this.failedDownloads<=this.tuning.dash.maxSegmentRetryCount)return;this.baseUrlsIndex=(this.baseUrlsIndex+1)%this.baseUrls.length;let e=this.baseUrls[this.baseUrlsIndex];for(let t of this.representations.values())st(t.segmentReference)?t.segmentReference.baseUrl=e:t.segmentReference.url=e}async loadByteRangeSegments(e,t,i="auto"){if(!e.length)return;for(let u of e)u.status="downloading",this.activeSegments.add({segment:u,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:r,url:a,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(await(0,P.abortable)(n,async function*(){let u=(0,P.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),(0,P.fromEvent)(window,"online").pipe((0,P.once)()).subscribe(()=>{l(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(a,{range:r,onProgress:o,signal:n,priority:i}),this.lastDataObtainedTimestampMs=(0,P.now)(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),$a(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}prepareByteRangeFetchSegmentParams(e,t){if(st(t.segmentReference))throw new Error("Representation is not byte range type");let i=t.segmentReference.url,r={from:(0,Fr.default)(e,0).byte.from,to:(0,Fr.default)(e,-1).byte.to},{signal:a}=this.downloadAbortController;return{url:i,range:r,signal:a,onProgress:async(o,u)=>{if(!a.aborted)try{this.lastDataObtainedTimestampMs=(0,P.now)(),await this.onSomeByteRangesDataLoaded({dataView:o,loaded:u,signal:a,onSegmentAppendFailed:()=>this.abort(),globalFrom:r?r.from:0,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:P.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!st(t.segmentReference))throw new Error("Representation is not template type");let i=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&i.searchParams.set("low-latency","yes");let r=i.toString(),{signal:a}=this.downloadAbortController,n=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(l,d)=>{if(!a.aborted)try{this.lastDataObtainedTimestampMs=(0,P.now)();let c=this.onSomeTemplateDataLoaded({dataView:l,loaded:d,signal:a,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(c)}catch(c){this.error$.next({id:"SegmentFeeding",category:P.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:c})}}:void 0;return{url:r,signal:a,onProgress:u,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)(0,Io.default)(e,t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:r,signal:a}){if(!this.activeSegments.size||!Y(this.mediaSource,this.sourceBuffer))return;let n=this.representations.get(t);if(n)for(let o of this.activeSegments){let{segment:u}=o;if(o.representationId===t){if(a.aborted){r();continue}if(o.loadedBytes=i,o.loadedBytes>o.feedingBytes){let l=new DataView(e.buffer,e.byteOffset+o.feedingBytes,o.loadedBytes-o.feedingBytes),d=Ba(n.mime).parseFeedableSegmentChunk(l,this.isLive);d?.byteLength&&(u.status="partially_fed",o.feedingBytes+=d.byteLength,await this.sourceBufferTaskQueue.append(d),o.fedBytes+=d.byteLength)}}}}async onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:a,onSegmentAppendFailed:n}){if(!this.activeSegments.size||!Y(this.mediaSource,this.sourceBuffer))return;let o=this.representations.get(t);if(o)for(let u of this.activeSegments){if(u.representationId!==t)continue;if(a.aborted){await n();continue}let{segment:l}=u,d=l.byte.from-i,c=l.byte.to-i,p=c-d+1,h=d<r,m=c<=r;if(h){if(l.status==="downloading"&&m){l.status="downloaded";let g=new DataView(e.buffer,e.byteOffset+d,p);await this.sourceBufferTaskQueue.append(g,a)&&!a.aborted?this.onSegmentFullyAppended(u,t):await n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(l.status==="downloading"||l.status==="partially_fed")&&(u.loadedBytes=Math.min(p,r-d),u.loadedBytes>u.feedingBytes)){let g=new DataView(e.buffer,e.byteOffset+d+u.feedingBytes,u.loadedBytes-u.feedingBytes),v=u.loadedBytes===p?g:Ba(o.mime).parseFeedableSegmentChunk(g);v?.byteLength&&(l.status="partially_fed",u.feedingBytes+=v.byteLength,await this.sourceBufferTaskQueue.append(v,a)&&!a.aborted?(u.fedBytes+=v.byteLength,u.fedBytes===p&&this.onSegmentFullyAppended(u,t)):await n())}}}}onSegmentFullyAppended(e,t){if(!((0,P.isNullable)(this.sourceBuffer)||!Y(this.mediaSource,this.sourceBuffer))){!this.isLive&&W.browser.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(Ye(this.sourceBuffer.buffered,e.segment.time.from,100)&&Ye(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:P.ErrorCategory.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",Pc(e.segment)&&(e.segment.size=e.fedBytes);for(let i of this.representations.values()){if(i.id===t)continue;let r=this.segments.get(i.id);if(r)for(let a of r)a.status==="fed"&&Math.round(a.time.from)===Math.round(e.segment.time.from)&&Math.round(a.time.to)===Math.round(e.segment.time.to)&&(a.status="none")}this.isActiveLowLatency()&&this.updateLowLatencyLiveIfNeeded(e.segment),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,e.segment)}}abortSegment(e){e.status==="partially_fed"?e.status="partially_ejected":e.status!=="partially_ejected"&&(e.status="none");for(let t of this.activeSegments.values())if(t.segment===e){this.activeSegments.delete(t);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(let[r,a]of this.initData.entries()){let n=a instanceof Promise;t||=n,a===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let i=this.representations.get(e);i&&(this.initLoadIdleCallback=Mr(()=>(0,zv.default)(this.loadInit(i,"low",!1),()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",i=!1){let r=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!i&&this.failedDownloads>0?(0,P.abortable)(this.destroyAbortController.signal,async function*(){let o=(0,P.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,Ba(e.mime),r)).then(o=>{if(!o)return;let{init:u,dataView:l,segments:d}=o,c=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,c);let p=d;this.isLive&&st(e.segmentReference)&&(p=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,p),u&&this.parsedInitData.set(e.id,u)}).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:P.ErrorCategory.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n}async dropBuffer(){for(let e of this.segments.values())for(let t of e)t.status="none";await this.pruneBuffer(0,1/0,!0)}async pruneBuffer(e,t,i=!1){if(!this.sourceBuffer||!Y(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||(0,P.isNullable)(e))return!1;this.checkEjectedSegments();let r=[],a=0,n=o=>{if(a>=t)return;r.push({...o.time});let u=Pc(o)?o.size??0:o.byte.to-o.byte.from;a+=u};for(let o of this.segments.values())for(let u of o){let l=u.time.to<=e-this.tuning.dash.bufferPruningSafeZone,d=u.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(l||d)&&u.status==="fed"&&n(u)}for(let o=0;o<this.sourceBuffer.buffered.length;o++){let u=this.sourceBuffer.buffered.start(o)*1e3,l=this.sourceBuffer.buffered.end(o)*1e3,d=0;for(let c of this.segments.values())for(let p of c)(0,Io.default)(["none","partially_ejected"],p.status)&&Math.round(p.time.from)<=Math.round(u)&&Math.round(p.time.to)>=Math.round(l)&&d++;if(d===this.segments.size){let c={time:{from:u,to:l},url:"",status:"none"};n(c)}}if(r.length&&i){let o=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let u of this.segments.values())for(let l of u)l.time.from>=e+o&&l.status==="fed"&&n(l)}return r.length?(r=_v(r),(await Promise.all(r.map(u=>this.sourceBufferTaskQueue.remove(u.from,u.to)))).reduce((u,l)=>u||l,!1)):!1}async abortBuffer(){if(!this.sourceBuffer||!Y(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||!Y(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}getBufferedTo(){return!this.sourceBuffer||!Y(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length?null:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}getForwardBufferDuration(e=this.getCurrentPosition()){return!this.sourceBuffer||!Y(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||(0,P.isNullable)(e)?0:ze(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!this.sourceBuffer||!Y(this.mediaSource,this.sourceBuffer))return;let{buffered:i}=this.sourceBuffer;this.tuning.useRefactoredSearchGap&&(this.gaps=this.gaps.filter(a=>{if(a.persistent)return!0;let n=Math.round(a.from),o=Math.round(a.to);for(let u=0;u<i.length;u++)if(n>=Math.round(i.start(u)*1e3)&&o<=Math.round(i.end(u)*1e3))return!1;return!0}));let r={representation:e,from:t.time.from,to:t.time.to,persistent:!1};for(let a=0;a<i.length;a++){let n=i.start(a)*1e3,o=i.end(a)*1e3;if(!(o<=t.time.from||n>=t.time.to)){if(n<=t.time.from&&o>=t.time.to){r=void 0;break}o>t.time.from&&o<t.time.to&&(r.from=o),n<t.time.to&&n>t.time.from&&(r.to=n)}}r&&r.to-r.from>1&&!this.gaps.some(a=>r&&a.from===r.from&&a.to===r.to)&&this.gaps.push(r)}detectGapsWhenIdle(e,t){if(!(this.gapDetectionIdleCallback||!this.sourceBuffer||!Y(this.mediaSource,this.sourceBuffer))){if(!this.tuning.useRefactoredSearchGap)for(let i=0;i<this.sourceBuffer.buffered.length;i++)this.gaps=this.gaps.filter(r=>r.persistent||this.sourceBuffer&&(Math.round(r.from)<Math.round(this.sourceBuffer.buffered.start(i)*1e3)||Math.round(r.to)>Math.round(this.sourceBuffer.buffered.end(i)*1e3)));this.gapDetectionIdleCallback=Mr(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:P.ErrorCategory.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if((0,P.isNullable)(this.sourceBuffer)||!Y(this.mediaSource,this.sourceBuffer)||(0,P.isNullable)(this.playingRepresentationId)||this.sourceBufferBufferedDiff&&!this.sourceBufferBufferedDiff.wasUpdated())return;let e=vo(this.sourceBuffer.buffered),t=100;for(let i of this.segments.values())for(let r of i){let{status:a}=r;if(a!=="fed"&&a!=="partially_ejected")continue;let n=Math.floor(r.time.from),o=Math.ceil(r.time.to),u=!1,l=0;for(let d=0;d<e.length;d+=2){let c=e[d],p=e[d+1];u||(u=c-t<=n&&p+t>=o),(n>=c&&n<p-t||o>c+t&&o<=p)&&(l+=1)}u||(l===1?r.status="partially_ejected":this.gaps.some(d=>d.from===r.time.from||d.to===r.time.to)?r.status="partially_ejected":r.status="none")}}handleAsyncError(e,t){this.error$.next({id:t,category:P.ErrorCategory.VIDEO_PIPELINE,thrown:e,message:"Something went wrong"})}};var ee=require("@vkontakte/videoplayer-shared");var wo=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:a=!1}){this.lastConnectionType$=new ee.ValueSubject(void 0);this.lastConnectionReused$=new ee.ValueSubject(void 0);this.lastRequestFirstBytes$=new ee.ValueSubject(void 0);this.recoverableError$=new ee.Subject;this.error$=new ee.Subject;this.abortAllController=new de;this.subscription=new ee.SubscriptionRemovable;this.fetchManifest=(0,ee.abortable)(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=Li(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=to(i));let r=yield this.doFetch(i,{signal:this.abortAllController.signal}).catch(Eo);return r?(t.log("success",(0,ee.flattenObject)({url:i,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(r.headers),r.text()):(t.error("error",(0,ee.flattenObject)({url:i,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=(0,ee.abortable)(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:i,onProgress:r,priority:a="auto",signal:n,measureThroughput:o=!0,isLowLatency:u=!1}={}){let l=e,d=new Headers,c=this.tracer.createComponentTracer("Fetch");if(i)switch(t){case 0:{d.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let k=new URL(l,location.href);k.searchParams.append("bytes",`${i.from}-${i.to}`),l=k.toString();break}default:(0,ee.assertNever)(t)}this.requestQuic&&(l=Li(l));let p=this.abortAllController.signal,h;if(n){let k=new de;if(h=(0,ee.merge)((0,ee.fromEvent)(this.abortAllController.signal,"abort"),(0,ee.fromEvent)(n,"abort")).subscribe(()=>{try{k.abort()}catch(R){Eo(R)}}),this.subscription.add(h),this.abortAllController.signal.aborted||n.aborted)try{k.abort()}catch(R){Eo(R)}p=k.signal}let m=(0,ee.now)();c.log("startRequest",(0,ee.flattenObject)({url:l,priority:a,rangeMethod:t,range:i,isLowLatency:u,requestStartedAt:m}));let g=yield this.doFetch(l,{priority:a,headers:d,signal:p}),v=(0,ee.now)();if(!g)return c.error("error",{message:"No response in request"}),c.end(),this.unsubscribeAbortSubscription(h),null;if(this.throughputEstimator?.addRawRtt(v-m),!g.ok||!g.body){this.unsubscribeAbortSubscription(h);let k=`Fetch error ${g.status}: ${g.statusText}`;return c.error("error",{message:k}),c.end(),Promise.reject(new Error(`Fetch error ${g.status}: ${g.statusText}`))}if(this.onHeadersReceived(g.headers),!r&&!o){this.unsubscribeAbortSubscription(h);let k=(0,ee.now)(),R={requestStartedAt:m,requestEndedAt:k,duration:k-m};return c.log("endRequest",(0,ee.flattenObject)(R)),c.end(),g.arrayBuffer()}let T=g.body;if(o){let k;[T,k]=g.body.tee(),this.throughputEstimator?.trackStream(k,u)}let w=T.getReader(),x,M=parseInt(g.headers.get("content-length")??"",10);Number.isFinite(M)&&(x=M),!x&&i&&(x=i.to-i.from+1);let B=0,F=x?new Uint8Array(x):new Uint8Array(0),G=!1,$=k=>{this.unsubscribeAbortSubscription(h),G=!0,Eo(k)},D=(0,ee.abortable)(p,async function*({done:k,value:R}){if(B===0&&this.lastRequestFirstBytes$.next((0,ee.now)()-m),p.aborted){this.unsubscribeAbortSubscription(h);return}if(!k&&R){if(x)F.set(R,B),B+=R.byteLength;else{let C=new Uint8Array(F.length+R.length);C.set(F),C.set(R,F.length),F=C,B+=R.byteLength}r?.(new DataView(F.buffer),B),yield w?.read().then(D,$)}}.bind(this));yield w?.read().then(D,$),this.unsubscribeAbortSubscription(h);let I=(0,ee.now)(),U={failed:G,requestStartedAt:m,requestEndedAt:I,duration:I-m};return G?(c.error("endRequest",(0,ee.flattenObject)(U)),c.end(),null):(c.log("endRequest",(0,ee.flattenObject)(U)),c.end(),F.buffer)}.bind(this));this.fetchByteRangeRepresentation=(0,ee.abortable)(this.abortAllController.signal,async function*(e,t,i){if(e.type!=="byteRange")return null;let{from:r,to:a}=e.initRange,n=r,o=a,u=!1,l,d;e.indexRange&&(l=e.indexRange.from,d=e.indexRange.to,u=a+1===l,u&&(n=Math.min(l,r),o=Math.max(d,a))),n=Math.min(n,0);let c=yield this.fetch(e.url,{range:{from:n,to:o},priority:i,measureThroughput:!1});if(!c)return null;let p=new DataView(c,r-n,a-n+1);if(!t.validateData(p))throw new Error("Invalid media file");let h=t.parseInit(p),m=e.indexRange??t.getIndexRange(h);if(!m)throw new ReferenceError("No way to load representation index");let g;if(u)g=new DataView(c,m.from-n,m.to-m.from+1);else{let T=yield this.fetch(e.url,{range:m,priority:i,measureThroughput:!1});if(!T)return null;g=new DataView(T)}let v=t.parseSegments(g,h,m);return{init:h,dataView:new DataView(c),segments:v}}.bind(this));this.fetchTemplateRepresentation=(0,ee.abortable)(this.abortAllController.signal,async function*(e,t){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=>({...n,status:"none",size:void 0})),dataView:new DataView(r)}:null}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=r,this.tracer=i.createComponentTracer("Fetcher"),this.useEnableSubtitlesParam=a}onHeadersReceived(e){let{type:t,reused:i}=eo(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}async fetchRepresentation(e,t,i="auto"){let{type:r}=e;switch(r){case"byteRange":return await this.fetchByteRangeRepresentation(e,t,i)??null;case"template":return await this.fetchTemplateRepresentation(e,i)??null;default:(0,ee.assertNever)(r)}}destroy(){this.abortAllController.abort(),this.tracer.end(),this.subscription.unsubscribe()}async doFetch(e,t){let i=await Lt(e,t);if(i.ok)return i;let r=await i.text(),a=parseInt(r);if(!isNaN(a))switch(a){case 1:this.recoverableError$.next({id:"VideoDataLinkExpiredError",message:"Video data links have expired",category:ee.ErrorCategory.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:ee.ErrorCategory.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:ee.ErrorCategory.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:ee.ErrorCategory.FATAL});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${a})`,category:ee.ErrorCategory.FATAL})}}unsubscribeAbortSubscription(e){e&&(e.unsubscribe(),this.subscription.remove(e))}},Eo=s=>{if(!$a(s))throw s};var Ao=require("@vkontakte/videoplayer-shared");var Va=class s{constructor(e,t){this.currentRepresentation$=new Ao.ValueSubject(null);this.maxRepresentations=4;this.representationsCursor=0;this.representations=[];this.currentSegment=null;this.getCurrentPosition=t.getCurrentPosition,this.processStreams(e)}updateLive(e){this.processStreams(e?.streams.text)}seekLive(e){this.processStreams(e)}maintain(e=this.getCurrentPosition()){if(!(0,Ao.isNullable)(e))for(let t of this.representations)for(let i of t){let r=i.segmentReference,a=r.segments.length,n=r.segments[0].time.from,o=r.segments[a-1].time.to;if(e<n||e>o)continue;let u=r.segments.find(l=>l.time.from<=e&&l.time.to>=e);!u||this.currentSegment?.time.from===u.time.from&&this.currentSegment.time.to===u.time.to||(this.currentSegment=u,this.currentRepresentation$.next({...i,label:"Live Text",language:"ru",isAuto:!0,url:new URL(u.url,r.baseUrl).toString()}))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e??[]){let i=s.filterRepresentations(t.representations);if(i){this.representations[this.representationsCursor]=i,this.representationsCursor=(this.representationsCursor+1)%this.maxRepresentations;break}}}static isSupported(e){return!!e?.some(t=>s.filterRepresentations(t.representations))}static filterRepresentations(e){return e?.filter(t=>t.kind==="text"&&"segmentReference"in t&&st(t.segmentReference))}};var oL=["progress","play","seeked","stalled","waiting"],uL=["timeupdate","progress","loadeddata","playing","seeked"];var Po=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new S.Subscription;this.representationSubscription=new S.Subscription;this.state$=new ie("none");this.currentVideoRepresentation$=new S.ValueSubject(void 0);this.currentVideoRepresentationInit$=new S.ValueSubject(void 0);this.currentAudioRepresentation$=new S.ValueSubject(void 0);this.currentVideoSegmentLength$=new S.ValueSubject(0);this.currentAudioSegmentLength$=new S.ValueSubject(0);this.error$=new S.Subject;this.lastConnectionType$=new S.ValueSubject(void 0);this.lastConnectionReused$=new S.ValueSubject(void 0);this.lastRequestFirstBytes$=new S.ValueSubject(void 0);this.currentLiveTextRepresentation$=new S.ValueSubject(null);this.isLive$=new S.ValueSubject(!1);this.isActiveLive$=new S.ValueSubject(!1);this.isLowLatency$=new S.ValueSubject(!1);this.liveDuration$=new S.ValueSubject(0);this.liveSeekableDuration$=new S.ValueSubject(0);this.liveAvailabilityStartTime$=new S.ValueSubject(0);this.liveStreamStatus$=new S.ValueSubject(void 0);this.bufferLength$=new S.ValueSubject(0);this.liveLatency$=new S.ValueSubject(void 0);this.liveLoadBufferLength$=new S.ValueSubject(0);this.livePositionFromPlayer$=new S.ValueSubject(0);this.currentStallDuration$=new S.ValueSubject(0);this.videoLastDataObtainedTimestamp$=new S.ValueSubject(0);this.fetcherRecoverableError$=new S.Subject;this.fetcherError$=new S.Subject;this.liveStreamEndTimestamp=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.forceEnded$=new S.Subject;this.gapWatchdogActive=!1;this.destroyController=new de;this.initManifest=(0,S.abortable)(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=Le(t,i,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),this.manifest?.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:S.ErrorCategory.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=(0,S.abortable)(this.destroyController.signal,async function*(){this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(n=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:S.ErrorCategory.NETWORK,message:"Failed to load manifest",thrown:n})});if(!e)return null;let t=null;try{t=Hv(e??"",this.manifestUrlString)}catch(n){let o=Kn(e)??{id:"ManifestParsing",category:S.ErrorCategory.PARSER,message:"Failed to parse MPD manifest",thrown:n};this.error$.next(o)}if(!t)return null;let i=(n,o,u)=>!!(this.element?.canPlayType?.(o)&&wt()?.isTypeSupported?.(`${o}; codecs="${u}"`)||n==="text");if(t.live){this.isLive$.next(!!t.live);let{availabilityStartTime:n,latestSegmentPublishTime:o,streamIsUnpublished:u,streamIsAlive:l}=t.live,d=(t.duration??0)/1e3;this.liveSeekableDuration$.next(-1*d),this.liveDuration$.next((o-n)/1e3),this.liveAvailabilityStartTime$.next(t.live.availabilityStartTime);let c="active";l||(c=u?"unpublished":"unexpectedly_down"),this.liveStreamStatus$.next(c)}let r={text:t.streams.text,video:[],audio:[]};for(let n of["video","audio"]){let u=t.streams[n].filter(({mime:c,codecs:p})=>i(n,c,p)),l=new Set(u.map(({codecs:c})=>c)),d=co(l);if(d&&(r[n]=u.filter(({codecs:c})=>c.startsWith(d))),n==="video"){let c=this.tuning.preferHDR,p=r.video.some(m=>m.hdr),h=r.video.some(m=>!m.hdr);W.display.isHDR&&c&&p?r.video=r.video.filter(m=>m.hdr):h&&(r.video=r.video.filter(m=>!m.hdr))}}let a={...t,streams:r};return this.tracer.log("updateManifestEnd",(0,S.flattenObject)(a)),a}.bind(this));this.initRepresentations=(0,S.abortable)(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initRepresentationsStart",(0,S.flattenObject)({initialVideo:e,initialAudio:t,sourceHls:i})),(0,S.assertNonNullable)(this.manifest),(0,S.assertNonNullable)(this.element),this.representationSubscription.unsubscribe(),this.representationSubscription=new S.Subscription,this.state$.startTransitionTo("representations_ready");let r=p=>{this.representationSubscription.add((0,S.fromEvent)(p,"error").pipe((0,S.filter)(h=>!!this.element?.played.length)).subscribe(h=>{this.error$.next({id:"VideoSource",category:S.ErrorCategory.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:h})}))};this.source=this.tuning.useManagedMediaSource?Cn():new MediaSource;let a=document.createElement("source");if(r(a),a.src=URL.createObjectURL(this.source),this.element.appendChild(a),this.tuning.useManagedMediaSource&&xr())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,h)=>[...p,...h.representations],[]);if(this.videoBufferManager=new Ca("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],(0,S.isNonNullable)(t)){let p=this.manifest.streams.audio.reduce((h,m)=>[...h,...m.representations],[]);this.audioBufferManager=new Ca("audio",this.source,p,n),this.bufferManagers.push(this.audioBufferManager)}Va.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new Va(this.manifest.streams.text,n)),this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$));let u=()=>{this.stallWatchdogSubscription?.unsubscribe(),this.currentStallDuration$.next(0)};if(this.representationSubscription.add((0,S.merge)(...uL.map(p=>(0,S.fromEvent)(this.element,p))).pipe((0,S.map)(p=>this.element?ze(this.element.buffered,this.element.currentTime*1e3):0),(0,S.filterChanged)(),(0,S.tap)(p=>{p>this.tuning.dash.bufferEmptinessTolerance&&u()})).subscribe(this.bufferLength$)),this.representationSubscription.add((0,S.merge)((0,S.fromEvent)(this.element,"ended"),this.forceEnded$).subscribe(()=>{u()})),this.isLive$.getValue()){this.subscription.add(this.liveDuration$.pipe((0,S.filterChanged)()).subscribe(h=>this.liveStreamEndTimestamp=(0,S.now)())),this.subscription.add((0,S.fromEvent)(this.element,"pause").subscribe(()=>{this.livePauseWatchdogSubscription=(0,S.interval)(1e3).subscribe(h=>{let m=wi(this.manifestUrlString,2);this.manifestUrlString=Le(this.manifestUrlString,m+1e3,2),this.liveStreamStatus$.getValue()==="active"&&this.updateManifest()}),this.subscription.add(this.livePauseWatchdogSubscription)})).add((0,S.fromEvent)(this.element,"play").subscribe(h=>this.livePauseWatchdogSubscription?.unsubscribe())),this.representationSubscription.add((0,S.combine)({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe((0,S.map)(({isActiveLive:h,isLowLatency:m})=>h&&m),(0,S.filterChanged)()).subscribe(h=>{this.isManualDecreasePlaybackInLive()||Vr(this.element,1)})),this.representationSubscription.add((0,S.combine)({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe((0,S.filter)(({bufferLength:h,isActiveLive:m,isLowLatency:g})=>m&&g&&!!h)).subscribe(({bufferLength:h})=>this.liveBuffer.next(h))),this.representationSubscription.add(this.videoBufferManager.currentLowLatencySegmentLength$.subscribe(h=>{if(!this.isActiveLive$.getValue()&&!this.isLowLatency$.getValue()&&!h)return;let m=this.liveSeekableDuration$.getValue()-h/1e3;this.liveSeekableDuration$.next(Math.max(m,-1*this.tuning.dashCmafLive.maxLiveDuration)),this.liveDuration$.next(this.liveDuration$.getValue()+h/1e3)})),this.representationSubscription.add((0,S.combine)({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe((0,S.filter)(({isLive:h})=>h),(0,S.filterChanged)((h,m)=>m.bufferLength<h.bufferLength),(0,S.map)(({rtt:h,bufferLength:m,segmentServerLatency:g})=>{let v=wi(this.manifestUrlString,2);return(h/2+m+g+v)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add((0,S.combine)({liveBuffer:this.liveBuffer.smoothed$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).subscribe(({liveBuffer:h,isActiveLive:m,isLowLatency:g})=>{if(!g||!m)return;let v=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,T=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,w=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,x=h-v;if(this.isManualDecreasePlaybackInLive())return;let M=1;Math.abs(x)>T&&(M=1+Math.sign(x)*w),Vr(this.element,M)})),this.representationSubscription.add(this.bufferLength$.subscribe(h=>{let m=0;if(h){let g=(this.element?.currentTime??0)*1e3;m=Math.min(...this.bufferManagers.map(T=>T.getLiveSegmentsToLoadState(this.manifest)?.to??g))-g}this.liveLoadBufferLength$.getValue()!==m&&this.liveLoadBufferLength$.next(m)}));let p=0;this.representationSubscription.add((0,S.combine)({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe((0,S.throttle)(1e3)).subscribe(async({liveLoadBufferLength:h,bufferLength:m})=>{if(!this.element||this.isUpdatingLive)return;let g=this.element.playbackRate,v=wi(this.manifestUrlString,2),T=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,w=Math.min(T,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*g),x=this.tuning.dashCmafLive.normalizedActualBufferOffset*g,M=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*g,B=isFinite(h)?h:m,F=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),G=T<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next(G);let $="none";if(F?$="active_low_latency":this.isLowLatency$.getValue()&&G?(this.bufferManagers.forEach(D=>D.proceedLowLatencyLive()),$="active_low_latency"):v!==0&&B<w?$="live_forward_buffering":B<w+M&&($="live_with_target_offset"),isFinite(h)&&(p=h>p?h:p),$==="live_forward_buffering"||$==="live_with_target_offset"){let D=p-(w+x),I=this.normolizeLiveOffset(Math.trunc(v+D/g)),U=Math.abs(I-v),k=0;!h||U<=this.tuning.dashCmafLive.offsetCalculationError?k=v:I>0&&U>this.tuning.dashCmafLive.offsetCalculationError&&(k=I),this.manifestUrlString=Le(this.manifestUrlString,k,2)}($==="live_with_target_offset"||$==="live_forward_buffering")&&(p=0,await this.updateLive())},h=>{this.error$.next({id:"updateLive",category:S.ErrorCategory.VIDEO_PIPELINE,thrown:h,message:"Failed to update live with subscription"})}))}let l=(0,S.merge)(...this.bufferManagers.map(p=>p.fullyBuffered$)).pipe((0,S.map)(()=>this.bufferManagers.every(p=>p.fullyBuffered$.getValue()))),d=(0,S.merge)(...this.bufferManagers.map(p=>p.onLastSegment$)).pipe((0,S.map)(()=>this.bufferManagers.some(p=>p.onLastSegment$.getValue()))),c=(0,S.combine)({allBuffersFull:l,someBufferEnded:d}).pipe((0,S.filterChanged)(),(0,S.map)(({allBuffersFull:p,someBufferEnded:h})=>p&&h),(0,S.filter)(p=>p));if(this.representationSubscription.add((0,S.merge)(this.forceEnded$,c).subscribe(()=>{if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(p=>!p.updating))try{this.source?.endOfStream()}catch(p){this.error$.next({id:"EndOfStream",category:S.ErrorCategory.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:p})}})),this.representationSubscription.add((0,S.merge)(...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(h=>{p&&(this.timeoutSourceOpenId=setTimeout(()=>{if(this.source?.readyState==="open"){h();return}this.error$.next({id:"OpenOfStream",category:S.ErrorCategory.VIDEO_PIPELINE,message:"Failed to open MediaSource",thrown:new Error("Timeout reject when wait sourceopen event"),traceAsLog:!0})},this.tuning.dash.sourceOpenTimeout)),this.source?.addEventListener("sourceopen",()=>{this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),h()},{once:!0})})}if(!this.isLive$.getValue()){let p=[this.manifest.duration??0,...(0,Bc.default)((0,Bc.default)([...this.manifest.streams.audio,...this.manifest.streams.video],h=>h.representations),h=>{let m=[];return h.duration&&m.push(h.duration),st(h.segmentReference)&&h.segmentReference.totalSegmentsDurationMs&&m.push(h.segmentReference.totalSegmentsDurationMs),m})];this.source.duration=Math.max(...p)/1e3}this.audioBufferManager&&(0,S.isNonNullable)(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=()=>{if(!this.element||!this.videoBufferManager||this.source?.readyState!=="open")return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),this.audioBufferManager?.maintain(e),this.liveTextManager?.maintain(e),(this.videoBufferManager.gaps.length||this.audioBufferManager?.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=(0,S.interval)(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),t=>{this.error$.next({id:"GapWatchdog",category:S.ErrorCategory.WTF,message:"Error handling gaps",thrown:t})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name),this.fetcher=new wo({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=bi.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.bufferEstimator}),this.initTracerSubscription()}async seekLive(e){(0,S.assertNonNullable)(this.element);let t=this.liveStreamStatus$.getValue()!=="active"?(0,S.now)()-this.liveStreamEndTimestamp:0,i=this.normolizeLiveOffset(e+t);this.isActiveLive$.next(i===0),this.manifestUrlString=Le(this.manifestUrlString,i,2),this.manifest=await this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,await this.videoBufferManager?.seekLive(this.manifest.streams.video),await this.audioBufferManager?.seekLive(this.manifest.streams.audio),this.liveTextManager?.seekLive(this.manifest.streams.text))}initBuffer(){(0,S.assertNonNullable)(this.element),this.state$.setState("running");let e=(0,S.fromEvent)(this.element,"timeupdate");this.tuning.dash.timeupdateEventTickThrottle&&(e=e.pipe((0,S.throttle)(this.tuning.dash.timeupdateEventTickThrottle))),this.subscription.add((0,S.merge)(...oL.map(t=>(0,S.fromEvent)(this.element,t)),(0,S.fromEvent)(window,"online"),e).subscribe(()=>this.tick(),t=>{this.error$.next({id:"DashVKPlayer",category:S.ErrorCategory.WTF,message:"Internal logic error",thrown:t})})),this.subscription.add((0,S.fromEvent)(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===HTMLMediaElement.HAVE_CURRENT_DATA&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add((0,S.fromEvent)(this.element,"waiting").subscribe(()=>{this.element&&this.element.readyState===HTMLMediaElement.HAVE_CURRENT_DATA&&!this.element.seeking&&Ye(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let t=()=>{if(!this.element||this.source?.readyState!=="open")return;let i=this.currentStallDuration$.getValue();i+=50,this.currentStallDuration$.next(i);let r={timeInWaiting:i},a=(0,S.now)(),n=100,o=this.videoBufferManager?.lastDataObtainedTimestamp??0;this.videoLastDataObtainedTimestamp$.next(o);let u=this.audioBufferManager?.lastDataObtainedTimestamp??0,l=this.videoBufferManager?.getForwardBufferDuration()??0,d=this.audioBufferManager?.getForwardBufferDuration()??0,c=l<n&&a-o>this.tuning.dash.crashOnStallTWithoutDataTimeout,p=this.audioBufferManager&&d<n&&a-u>this.tuning.dash.crashOnStallTWithoutDataTimeout;if((c||p)&&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 h=this.normolizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);this.seekLive(h).catch(m=>{this.error$.next({id:"stallIntervalCallback",category:S.ErrorCategory.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:m})}),r.liveLastOffset=h}else{let h=this.element.currentTime*1e3;this.videoBufferManager?.maintain(h),this.audioBufferManager?.maintain(h),r.position=h}this.tracer.log("stallIntervalCallback",(0,S.flattenObject)(r))};this.stallWatchdogSubscription?.unsubscribe(),this.stallWatchdogSubscription=(0,S.interval)(50).subscribe(t,i=>{this.error$.next({id:"StallWatchdogCallback",category:S.ErrorCategory.NETWORK,message:"Can't restore DASH after stall.",thrown:i})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t,i=!1){let r={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return this.tuning.useNewSwitchTo?this.currentStallDuration$.getValue()>0?r?.switchToWithPreviousAbort(t,i):r?.switchTo(t,i):r?.switchToOld(t,i)}async seek(e,t){(0,S.assertNonNullable)(this.element),(0,S.assertNonNullable)(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(this.videoBufferManager.findSegmentStartTime(e)??e,this.audioBufferManager?.findSegmentStartTime(e)??e),this.warmUpMediaSourceIfNeeded(i),Ye(this.element.buffered,i)||await Promise.all([this.videoBufferManager.abort(),this.audioBufferManager?.abort()]),!((0,S.isNullable)(this.element)||(0,S.isNullable)(this.videoBufferManager))&&(this.videoBufferManager.maintain(i),this.audioBufferManager?.maintain(i),this.element.currentTime=i/1e3,this.tracer.log("seek",(0,S.flattenObject)({requestedPosition:e,forcePrecise:t,position:i})))}warmUpMediaSourceIfNeeded(e=this.element?.currentTime){(0,S.isNonNullable)(this.element)&&(0,S.isNonNullable)(this.source)&&(0,S.isNonNullable)(e)&&this.source?.readyState==="ended"&&this.element.duration*1e3-e>this.tuning.dash.seekBiasInTheEnd&&this.bufferManagers.forEach(t=>t.warmUpMediaSource())}get isStreamEnded(){return this.source?.readyState==="ended"}stop(){this.tracer.log("stop"),this.element?.querySelectorAll("source").forEach(e=>{URL.revokeObjectURL(e.src),e.remove()}),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),this.videoBufferManager?.destroy(),this.videoBufferManager=null,this.audioBufferManager?.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getStreams(){return this.manifest?.streams}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),this.source?.readyState==="open"&&Array.from(this.source.sourceBuffers).every(e=>!e.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}initTracerSubscription(){let e=(0,S.getTraceSubscriptionMethod)(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}async updateLive(){this.isUpdatingLive=!0,this.manifest=await this.updateManifest(),this.manifest&&(this.bufferManagers?.forEach(e=>e.updateLive(this.manifest)),this.liveTextManager?.updateLive(this.manifest)),this.isUpdatingLive=!1}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.getBufferedTo();if(e===null)return;let t=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),i=this.isJumpGapAfterSeekLive,r=this.element.currentTime;this.isJumpGapAfterSeekLive&&!t&&this.element.currentTime>e&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let a=this.element.currentTime*1e3,n=null,o=this.element.readyState===HTMLMediaElement.HAVE_METADATA?this.tuning.endGapTolerance:0;for(let u of this.bufferManagers)for(let l of u.gaps)(l.persistent||u.playingRepresentation$.getValue()===l.representation)&&l.from-o<=a&&l.to+o>a&&(this.element.duration*1e3-l.to<this.tuning.endGapTolerance?n=1/0:(n===null||l.to>n)&&(n=l.to));if(n!==null){let u=n+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,u===1/0?this.forceEnded$.next():(this.element.currentTime=u/1e3,this.tracer.log("jumpGap",(0,S.flattenObject)({isJumpGapAfterSeekLive:i,isActiveLowLatency:t,initialCurrentTime:r,jumpTo:u,resultCurrentTime:this.element.currentTime})))}}};var dt=require("@vkontakte/videoplayer-shared"),ko=class{constructor(){this.subscription=new dt.Subscription;this.pipSize$=new dt.ValueSubject(void 0);this.videoSize$=new dt.ValueSubject(void 0);this.elementSize$=new dt.ValueSubject(void 0);this.pictureInPictureWindowRemoveEventListener=dt.noop}connect({observableVideo:e,video:t}){let i=r=>{let a=r.target;this.pipSize$.next({width:a.width,height:a.height})};this.subscription.add((0,dt.observeElementSize)(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((0,dt.combine)({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe((0,dt.map)(({videoSize:r,inPip:a,pipSize:n})=>a?n:r)).subscribe(this.elementSize$))}getValue(){return this.elementSize$.getValue()}subscribe(e,t){return this.elementSize$.subscribe(e,t)}getObservable(){return this.elementSize$}destroy(){this.pictureInPictureWindowRemoveEventListener(),this.subscription.unsubscribe()}};var ir=class{constructor(e){this.subscription=new X.Subscription;this.videoState=new ie("stopped");this.observableVideo=null;this.droppedFramesManager=new Pr;this.stallsManager=new bo;this.elementSizeManager=new ko;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new ki;this.audioTrackSwitchHistory=new ki;this.selectedRepresentations={audio:null,video:null};this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(r.state==="requested"&&i?.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"),_(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"),_(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="ready"&&_(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?.to==="playing"&&_(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&_(this.params.desiredState.playbackState,"paused");return;default:return(0,X.assertNever)(e)}}};this.init3DScene=e=>{if(this.scene3D)return;this.scene3D=new Or(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:e.projectionData?.pose.yaw||0,y:e.projectionData?.pose.pitch||0,z:e.projectionData?.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 Rt(e.source.url),this.params=e,this.video=at(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(We(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 Po({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;(0,X.isNullable)(this.observableVideo)&&(this.observableVideo=ut(this.video),this.subscription.add(()=>this.observableVideo?.destroy()));let i=this.constructor.name,r=n=>{e.error$.next({id:i,category:X.ErrorCategory.WTF,message:`${i} internal logic error`,thrown:n})},a=(n,o)=>this.subscription.add(n.subscribe(o,r));return{output:e,desiredState:t,observableVideo:this.observableVideo,genericErrorListener:r,connect:a}}subscribe(){let{output:e,desiredState:t,observableVideo:i,genericErrorListener:r,connect:a}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe((0,X.filter)(c=>!!c.length),(0,X.once)()).subscribe(c=>{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:c})}));let n=this.params.desiredState.seekState.stateChangeEnded$.pipe((0,X.map)(c=>c.to.state!=="none"),(0,X.filterChanged)());this.stallsManager.init({isSeeked$:n,currentStallDuration$:this.player.currentStallDuration$,videoLastDataObtainedTimestamp$:this.player.videoLastDataObtainedTimestamp$,throughput$:this.params.dependencies.throughputEstimator.throughput$,rtt$:this.params.dependencies.throughputEstimator.rtt$,tuning:this.params.tuning.stallsManager,abrParams:this.params.tuning.autoTrackSelection,isBuffering$:i.isBuffering$,looped$:i.looped$,playing$:i.playing$}),a(i.ended$,e.endedEvent$),a(i.looped$,e.loopedEvent$),a(i.error$,e.error$),a(i.isBuffering$,e.isBuffering$),a(i.currentBuffer$,e.currentBuffer$),a(i.playing$,e.firstFrameEvent$),a(i.canplay$,e.canplay$),a(i.inPiP$,e.inPiP$),a(i.inFullscreen$,e.inFullscreen$),a(i.loadedMetadata$,e.loadedMetadataEvent$),a(this.player.error$,e.error$),a(this.player.fetcherRecoverableError$,e.fetcherRecoverableError$),a(this.player.fetcherError$,e.fetcherError$),a(this.player.lastConnectionType$,e.httpConnectionType$),a(this.player.lastConnectionReused$,e.httpConnectionReused$),a(this.player.isLive$,e.isLive$),a(this.player.lastRequestFirstBytes$.pipe((0,X.filter)(X.isNonNullable),(0,X.once)()),e.firstBytesEvent$),a(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),a(this.videoState.stateChangeEnded$.pipe((0,X.map)(c=>c.to)),this.params.output.playbackState$),this.subscription.add(i.looped$.subscribe(()=>this.player.warmUpMediaSourceIfNeeded(),r)),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(Wt(this.video,t.isLooped,r)),this.subscription.add(ot(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(kt(this.video,t.playbackRate,i.playbackRateState$,r)),this.elementSizeManager.connect({video:this.video,observableVideo:i}),a(Mt(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),_(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),_(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:c})=>{if(c==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let p=this.player.getStreams();if((0,X.assertNonNullable)(p,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let m=[];for(let g of p.audio){m.push(wc(g));let v=[];for(let T of g.representations){let w=Cv(T);v.push(w),this.audioTracksMap.set(w,{stream:g,representation:T})}this.audioStreamsMap.set(g,v)}this.params.output.availableAudioStreams$.next(m)}let h=[];for(let m of p.video){h.push(Ac(m));let g=[];for(let v of m.representations){let T=Dv({...v,streamId:m.id});T&&(g.push(T),this.videoTracksMap.set(T,{stream:m,representation:v}))}this.videoStreamsMap.set(m,g)}this.params.output.availableVideoStreams$.next(h);for(let m of p.text)for(let g of m.representations){let v=Vv(m,g);this.textTracksMap.set(v,{stream:m,representation:g})}this.params.output.availableVideoTracks$.next(Array.from(this.videoTracksMap.keys())),this.params.output.availableAudioTracks$.next(Array.from(this.audioTracksMap.keys())),this.params.output.isAudioAvailable$.next(!!this.audioTracksMap.size),this.audioTracksMap.size&&this.textTracksMap.size&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else c==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},r));let{vktvAbrThrottle:o}=this.params.tuning.dash,u=o&&Fv(o)||null;this.subscription.add((0,X.merge)(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$,(0,X.fromEvent)(this.video,"progress")).pipe((0,X.filter)(()=>this.videoTracksMap.size>0)).subscribe(async()=>{let c=this.player.state$.getState(),p=this.player.state$.getTransition();if(c!=="manifest_ready"&&c!=="running"||p||c==="running"&&u&&!u())return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState()),this.selectVideoAudioRepresentations();let{video:h,audio:m}=this.selectedRepresentations;if(!h)return;let g=tr(this.videoTracksMap.keys(),T=>this.videoTracksMap.get(T)?.representation.id===h.id);(0,X.isNonNullable)(g)&&(this.stallsManager.lastVideoTrackSelected=g);let v=this.params.desiredState.autoVideoTrackLimits.getTransition();if(v&&this.params.output.autoVideoTrackLimits$.next(v.to),c==="manifest_ready")await this.player.initRepresentations(h.id,m?.id,this.params.sourceHls);else if(await this.player.switchRepresentation("video",h.id),m){let T=!!t.audioStream.getTransition();await this.player.switchRepresentation("audio",m.id,T)}},r)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:c})=>{this.scene3D&&c&&this.scene3D.pointCameraTo(c.x,c.y)})),this.subscription.add(this.elementSizeManager.subscribe(c=>{this.scene3D&&c&&this.scene3D.setViewportSize(c.width,c.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe((0,X.filterChanged)()).subscribe(c=>{let p=tr(this.videoTracksMap.entries(),([,{representation:v}])=>v.id===c);if(!p){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[h,{stream:m}]=p,g=this.params.desiredState.videoStream.getTransition();g&&g.to&&g.to.id===m.id&&this.params.desiredState.videoStream.setState(g.to),e.currentVideoTrack$.next(h),e.currentVideoStream$.next(Ac(m))},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe((0,X.filterChanged)()).subscribe(c=>{let p=tr(this.audioTracksMap.entries(),([,{representation:v}])=>v.id===c);if(!p){e.currentAudioStream$.next(void 0);return}let[h,{stream:m}]=p,g=this.params.desiredState.audioStream.getTransition();g&&g.to&&g.to.id===m.id&&this.params.desiredState.audioStream.setState(g.to),e.currentAudioStream$.next(wc(m))},r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(c=>{if(c?.is3dVideo&&this.params.tuning.spherical?.enabled)try{this.init3DScene(c),e.is3DVideo$.next(!0)}catch(p){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${p}`})}else this.destroy3DScene(),this.params.tuning.spherical?.enabled&&e.is3DVideo$.next(!1)},r)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,r)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,r)),this.textTracksManager.connect(this.video,t,e);let l=t.playbackState.stateChangeStarted$.pipe((0,X.map)(({to:c})=>c==="ready"),(0,X.filterChanged)());this.subscription.add((0,X.merge)(l,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,(0,X.observableFrom)(["init"])).subscribe(()=>{let c=t.autoVideoTrackSwitching.getState(),h=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:c?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(h)})),this.subscription.add((0,X.merge)(l,this.player.state$.stateChangeEnded$,(0,X.observableFrom)(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let d=(0,X.merge)(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,X.observableFrom)(["init"])).pipe((0,X.debounce)(0));this.subscription.add(d.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?gs:bs,t=this.params.tuning.useNewAutoSelectVideoTrack?zn:Hn,i=this.params.tuning.useNewAutoSelectVideoTrack?Yt:jn,{desiredState:r,output:a}=this.params,n=r.autoVideoTrackSwitching.getState(),o=r.videoTrack.getState()?.id,u=tr(this.videoTracksMap.keys(),$=>$.id===o),l=a.currentVideoTrack$.getValue(),d=r.videoStream.getState()??(u&&this.videoTracksMap.get(u)?.stream)??this.videoStreamsMap.size===1?this.videoStreamsMap.keys().next().value:void 0;if(!d)return;let c=tr(this.videoStreamsMap.keys(),$=>$.id===d.id),p=c&&this.videoStreamsMap.get(c);if(!p)return;let h=ze(this.video.buffered,this.video.currentTime*1e3),m;this.player.isActiveLive$.getValue()?m=this.player.isLowLatency$.getValue()?this.params.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.params.tuning.dashCmafLive.normalizedLiveMinBufferSize:this.player.isLive$.getValue()?m=this.params.tuning.dashCmafLive.normalizedTargetMinBufferSize:m=n?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;let g=(this.video.duration*1e3||1/0)-this.video.currentTime*1e3,v=Math.min(h/Math.min(m,g||1/0),1),T=r.audioStream.getState()??(this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0),w=T?.id&&tr(this.audioStreamsMap.keys(),$=>$.id===T.id)||this.audioStreamsMap.keys().next().value,x=0;if(w){if(u&&!n){let $=e(u,p,this.audioStreamsMap.get(w)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);x=Math.max(x,$?.bitrate??-1/0)}if(l){let $=e(l,p,this.audioStreamsMap.get(w)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);x=Math.max(x,$?.bitrate??-1/0)}}let M=u;(n||!M)&&(M=i(p,{container:this.elementSizeManager.getValue(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.stallsManager.abrTuningParams,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:x,forwardBufferHealth:v,current:l,visible:this.params.output.elementVisible$.getValue(),history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,stallsVideoMaxQualityLimit:this.stallsManager.videoMaxQualityLimit,stallsPredictedThroughput:this.stallsManager.predictedThroughput,abrLogger:this.params.dependencies.abrLogger}));let B=w&&t(M,p,this.audioStreamsMap.get(w)??[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.stallsManager.abrTuningParams,forwardBufferHealth:v,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),F=this.videoTracksMap.get(M)?.representation,G=B&&this.audioTracksMap.get(B)?.representation;F&&G?(this.selectedRepresentations.video=F,this.selectedRepresentations.audio=G):F&&!G&&this.audioTracksMap.size===0&&(this.selectedRepresentations.video=F,this.selectedRepresentations.audio=null)}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){lt(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),_(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:X.ErrorCategory.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),nt(this.video),this.tracer.end()}};var Oa=class extends ir{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)}};var me=require("@vkontakte/videoplayer-shared");var _a=class extends ir{constructor(e){super(e),this.textTracksManager.destroy()}subscribe(){super.subscribe();let e=-1,{output:t,observableVideo:i,desiredState:r,connect:a}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),a(i.timeUpdate$,t.liveBufferTime$),a(this.player.liveSeekableDuration$,t.duration$),a(this.player.liveLatency$,t.liveLatency$);let n=new me.ValueSubject(1);a(i.playbackRateState$,n),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(r.isLowLatency.stateChangeEnded$.pipe((0,me.map)(o=>o.to)).subscribe(this.player.isLowLatency$)).add((0,me.combine)({liveBufferTime:t.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe((0,me.map)(({liveBufferTime:o,liveAvailabilityStartTime:u})=>o&&u?o+u:void 0)).subscribe(t.liveTime$)).add(this.player.liveStreamStatus$.pipe((0,me.filter)(o=>(0,me.isNonNullable)(o))).subscribe(o=>t.isLiveEnded$.next(o!=="active"&&t.position$.getValue()===0))).add((0,me.combine)({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:(0,me.merge)(i.playbackRateState$,new me.ValueSubject(1))}).pipe((0,me.filter)(({liveStreamStatus:o,liveDuration:u})=>o==="active"&&!!u)).subscribe(({liveDuration:o,playbackRate:u})=>{let l=t.liveBufferTime$.getValue(),d=t.position$.getValue(),{playbackCatchupSpeedup:c}=this.params.tuning.dashCmafLive.lowLatency;d||u<1-c||this.video.paused||(0,me.isNullable)(l)||(e=o-l)})).add((0,me.combine)({time:t.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:(0,me.merge)(i.playbackRateState$,new me.ValueSubject(1))}).pipe((0,me.filterChanged)((o,u)=>this.player.liveStreamStatus$.getValue()==="active"?o.liveDuration===u.liveDuration:o.time===u.time)).subscribe(({time:o,liveDuration:u,playbackRate:l})=>{let d=t.position$.getValue(),{playbackCatchupSpeedup:c}=this.params.tuning.dashCmafLive.lowLatency;if(!d&&!this.video.paused&&l>=1-c||(0,me.isNullable)(o)||(0,me.isNullable)(u))return;let p=-1*(u-o-e);t.position$.next(Math.min(p,0))})).add(this.player.currentLiveTextRepresentation$.subscribe(o=>{if(o){let u=Ov(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 Gv="X-Playback-Duration",$c=async s=>{let e=await Lt(s),t=await e.text(),i=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t)?.[1];return i?parseInt(i,10):e.headers.has(Gv)?parseInt(e.headers.get(Gv),10):void 0};var se=require("@vkontakte/videoplayer-shared");var Cc=H(qu(),1);var Ro=require("@vkontakte/videoplayer-shared");var cL=s=>{let e=null;if(s.QUALITY&&(e=Pi(s.QUALITY)),!e&&s.RESOLUTION){let[t,i]=s.RESOLUTION.split("x").map(r=>parseInt(r,10));e=(0,Ro.videoSizeToQuality)({width:t,height:i})}return e??null},dL=(s,e)=>{let t=s.split(`
|
|
186
|
+
`),i=[],r=[];for(let a=0;a<t.length;a++){let n=t[a],o=n.match(/^#EXT-X-STREAM-INF:(.+)/),u=n.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!o&&!u)){if(o){let l=(0,Cc.default)(o[1].split(",").map(v=>v.split("="))),d=l.QUALITY??`stream-${l.BANDWIDTH}`,c=cL(l),p;l.BANDWIDTH&&(p=parseInt(l.BANDWIDTH,10)/1e3||void 0),!p&&l["AVERAGE-BANDWIDTH"]&&(p=parseInt(l["AVERAGE-BANDWIDTH"],10)/1e3||void 0);let h=l["FRAME-RATE"]?parseFloat(l["FRAME-RATE"]):void 0,m;if(l.RESOLUTION){let[v,T]=l.RESOLUTION.split("x").map(w=>parseInt(w,10));v&&T&&(m={width:v,height:T})}let g=new URL(t[++a],e).toString();c&&i.push({id:d,quality:c,url:g,bandwidth:p,size:m,fps:h})}if(u){let l=(0,Cc.default)(u[1].split(",").map(h=>{let m=h.indexOf("=");return[h.substring(0,m),h.substring(m+1)]}).map(([h,m])=>[h,m.replace(/^"|"$/g,"")])),d=l.URI?.replace(/playlist$/,"subtitles.vtt"),c=l.LANGUAGE,p=l.NAME;d&&c&&r.push({type:"internal",id:c,label:p,language:c,url:d,isAuto:!1})}}}if(!i.length)throw new Error("Empty manifest");return{qualityManifests:i,textTracks:r}},pL=s=>new Promise(e=>{setTimeout(()=>{e()},s)}),Dc=0,Wv=async(s,e=s,t,i)=>{let a=await(await Lt(s,i)).text();Dc+=1;try{let{qualityManifests:n,textTracks:o}=dL(a,e);return{qualityManifests:n,textTracks:o}}catch{if(Dc<=t.manifestRetryMaxCount)return await pL((0,Ro.getExponentialDelay)(Dc-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),Wv(s,e,t)}return{qualityManifests:[],textTracks:[]}},Mo=Wv;var Pt=require("@vkontakte/videoplayer-shared");var Lo=class{constructor(e,t,i,r,a){this.subscription=new Pt.Subscription;this.abortControllers={destroy:new de,nextManifest:null};this.prepareUrl=void 0;this.currentTextTrackData=null;this.availableTextTracks$=new Pt.ValueSubject(null);this.getCurrentTime$=new Pt.ValueSubject(null);this.error$=new Pt.Subject;this.params={fetchManifestData:i,sourceUrl:r,downloadThreshold:a},this.subscription.add(e.pipe((0,Pt.throttle)(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()}async prepare(e){try{let t=new URL(e);t.searchParams.set("enable-subtitles","yes"),this.prepareUrl=t.toString();let{textTracks:i}=await this.fetchManifestData();await this.processTextTracks(i,this.params.sourceUrl)}catch(t){this.error("prepare",t)}}async processTextTracks(e,t){try{let i=await this.parseTextTracks(e,t);i&&(this.currentTextTrackData=i)}catch(i){this.error("processTextTracks",i)}}async parseTextTracks(e,t){for(let i of e){let r=new URL(i.url,t).toString(),n=await(await 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(`
|
|
187
|
+
`),a=0;for(let n=0;n<r.length;++n){let o=r[n];switch(!0){case o.startsWith("#EXTINF:"):{let u=r[++n],l=new URL(u,t).toString(),d=Number(this.extractPlaylistRowValue("#EXTINF:",o))*1e3;if(i.segments.push({time:{from:a,to:a+d},url:l}),a=a+d,!i.segmentStartTime){let c=new Date(i.vkStartTime).valueOf(),p=new Date(i.programDateTime).valueOf();i.segmentStartTime=p-c}break}case o.startsWith("#EXT-X-TARGETDURATION:"):i.targetDuration=Number(this.extractPlaylistRowValue("#EXT-X-TARGETDURATION:",o));break;case o.startsWith("#EXT-X-MEDIA-SEQUENCE:"):i.mediaSequence=Number(this.extractPlaylistRowValue("#EXT-X-MEDIA-SEQUENCE:",o));break;case o.startsWith("#EXT-X-VK-PLAYBACK-DURATION:"):i.vkPlaybackDuration=Number(this.extractPlaylistRowValue("#EXT-X-VK-PLAYBACK-DURATION:",o));break;case o.startsWith("#EXT-X-PROGRAM-DATE-TIME:"):{let u=this.extractPlaylistRowValue("#EXT-X-PROGRAM-DATE-TIME:",o);i.programDateTime=u;let l=new Date(u);l.setMilliseconds(0),a=l.valueOf();break}case o.startsWith("#EXT-X-VK-START-TIME:"):i.vkStartTime=this.extractPlaylistRowValue("#EXT-X-VK-START-TIME:",o);break}}return i}extractPlaylistRowValue(e,t){switch(e){case"#EXTINF:":return t.substring(e.length,t.length-1);default:return t.substring(e.length)}}processLiveTime(e){if((0,Pt.isNonNullable)(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([{...this.currentTextTrackData.textTrack,url:n.url,isAuto:!0}]);break}}}async fetchNextManifestData(){try{if(this.abortControllers.nextManifest)return;this.abortControllers.nextManifest=new de;let{textTracks:e}=await this.fetchManifestData(),t=await 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}}async fetchManifestData(){let e=this.prepareUrl??this.params.sourceUrl;return await this.params.fetchManifestData(e,{signal:this.abortControllers.destroy.signal})}error(e,t){this.error$.next({id:"[LiveTextManager][HLS_LIVE_CMAF]",category:Pt.ErrorCategory.WTF,thrown:t,message:e})}};var Fa=class{constructor(e){this.subscription=new se.Subscription;this.videoState=new ie("stopped");this.textTracksManager=null;this.liveTextManager=null;this.manifests$=new se.ValueSubject([]);this.liveOffset=new Wi;this.manifestStartTime$=new se.ValueSubject(void 0);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),_(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(a||n||o){let d=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(d),this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if(r?.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"?_(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),_(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?.to==="playing"&&_(this.params.desiredState.playbackState,"playing");return;case"paused":if(i==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let d=this.liveOffset.getTotalOffset();d>=this.maxSeekBackTime$.getValue()&&(d=0,this.liveOffset.resetTo(d)),this.liveOffset.resume(),this.params.output.position$.next(-d/1e3),this.prepare()}else r?.to==="paused"&&(_(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return(0,se.assertNever)(t)}};this.params=e,this.video=at(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:se.VideoQuality.INVARIANT,url:this.params.source.url};let t=(i,r)=>Mo(i,this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},r);this.params.tuning.useHlsLiveNewTextManager?this.liveTextManager=new Lo(this.params.output.liveTime$,this.video,t,this.params.source.url,this.params.tuning.hlsLiveNewTextManagerDownloadThreshold):this.textTracksManager=new Rt(e.source.url),t(this.generateLiveUrl()).then(({qualityManifests:i,textTracks:r})=>{i.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:se.ErrorCategory.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),this.liveTextManager?.processTextTracks(r,this.params.source.url),this.manifests$.next([this.masterManifest,...i])}).catch(i=>{this.params.output.error$.next({id:"ExtractHlsQualities",category:se.ErrorCategory.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:i})}),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(We(this.params.source.url)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.maxSeekBackTime$=new se.ValueSubject(e.source.maxSeekBackTime??1/0),this.subscribe()}selectManifest(){let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),r=t.getTransition(),a=r?.to?.id??t.getState()?.id??"master",n=this.manifests$.getValue();if(!n.length)return;let o=i?"master":a;return i&&!r&&t.startTransitionTo(this.masterManifest),n.find(u=>u.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsLiveProvider",category:se.ErrorCategory.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},r=ut(this.video);this.subscription.add(()=>r.destroy());let a=(o,u)=>this.subscription.add(o.subscribe(u,i));a(r.ended$,e.endedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.loadedMetadata$,e.firstBytesEvent$),a(r.loadedMetadata$,e.loadedMetadataEvent$),a(r.playing$,e.firstFrameEvent$),a(r.canplay$,e.canplay$),a(r.inPiP$,e.inPiP$),a(r.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(ot(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(kt(this.video,t.playbackRate,r.playbackRateState$,i)),a(Mt(this.video),e.elementVisible$),this.liveTextManager?(a(this.liveTextManager.getCurrentTime$,this.params.output.getCurrentTime$),a(this.liveTextManager.error$,this.params.output.error$)):this.textTracksManager&&this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),_(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),_(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.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((0,se.filterChanged)(),(0,se.map)(o=>-o/1e3)).subscribe(this.params.output.duration$,i)),this.subscription.add(r.loadedMetadata$.subscribe(()=>{let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&(0,se.isNonNullable)(l.to)){let c=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let p=this.manifests$.getValue().find(h=>h.id===c);p&&(this.params.output.currentVideoTrack$.next(p),this.params.output.hostname$.next(We(p.url)))}d&&this.params.desiredState.autoVideoTrackSwitching.setState(d.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o&&o.state==="requested"&&this.seek(o.position)},i)),this.subscription.add(r.loadedData$.subscribe(()=>{let o=this.video?.getStartDate?.()?.getTime();this.manifestStartTime$.next(o||void 0)},i)),this.subscription.add((0,se.combine)({startTime:this.manifestStartTime$.pipe((0,se.filter)(se.isNonNullable)),currentTime:r.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),i)),this.subscription.add(this.manifests$.pipe((0,se.map)(o=>o.map(({id:u,quality:l,size:d,bandwidth:c,fps:p})=>({id:u,quality:l,size:d,fps:p,bitrate:c})))).subscribe(this.params.output.availableVideoTracks$,i));let n=(0,se.merge)(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,(0,se.observableFrom)(["init"])).pipe((0,se.debounce)(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager?.destroy(),this.liveTextManager?.destroy(),this.params.output.element$.next(void 0),nt(this.video)}prepare(){let e=this.selectManifest();if((0,se.isNullable)(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}=t?.to??i??{};for(let[l,d]of[[o,"mq"],[u,"lq"]]){let c=String(parseFloat(l||""));d&&l&&r.searchParams.set(d,c)}}let a=this.params.format==="HLS_LIVE_CMAF"?2:0,n=Le(r.toString(),this.liveOffset.getTotalOffset(),a);this.liveTextManager?.prepare(n),this.video.setAttribute("src",n),this.video.load(),$c(n).then(o=>{if(!(0,se.isNullable)(o))this.maxSeekBackTime$.next(o);else{let u=this.params.source.maxSeekBackTime??this.maxSeekBackTime$.getValue();((0,se.isNullable)(u)||!isFinite(u))&&Lt(n).then(l=>l.text()).then(l=>{let d=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(l)?.[1];if(d){let c=new URL(d,n).toString();$c(c).then(p=>{(0,se.isNullable)(p)||this.maxSeekBackTime$.next(p)})}}).catch(()=>{})}})}playIfAllowed(){lt(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),_(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:se.ErrorCategory.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=Le(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}};var ue=require("@vkontakte/videoplayer-shared");var Na=class{constructor(e){this.subscription=new ue.Subscription;this.videoState=new ie("stopped");this.manifests$=new ue.ValueSubject([]);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),_(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(a||n||o){let d=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(d);let{currentTime:c}=this.video;this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:c*1e3,forcePrecise:!0});return}switch(r?.to!=="paused"&&l.state==="requested"&&this.seek(l.position),t){case"ready":i==="ready"?_(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),_(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?.to==="playing"&&_(this.params.desiredState.playbackState,"playing");return;case"paused":i==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):r?.to==="paused"&&_(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return(0,ue.assertNever)(t)}};this.textTracksManager=new Rt(e.source.url),this.params=e,this.video=at(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:ue.VideoQuality.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(We(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),Mo(Le(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:ue.ErrorCategory.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),r=t.getTransition(),a=r?.to?.id??t.getState()?.id??"master",n=this.manifests$.getValue();if(!n.length)return;let o=i?"master":a;return i&&(!r||!r.from)&&t.startTransitionTo(this.masterManifest),n.find(u=>u.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsProvider",category:ue.ErrorCategory.WTF,message:"HlsProvider internal logic error",thrown:o})},r=ut(this.video);this.subscription.add(()=>r.destroy());let a=(o,u)=>this.subscription.add(o.subscribe(u));if(a(r.timeUpdate$,e.position$),a(r.durationChange$,e.duration$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.loadedMetadata$,e.firstBytesEvent$),a(r.loadedMetadata$,e.loadedMetadataEvent$),a(r.playing$,e.firstFrameEvent$),a(r.canplay$,e.canplay$),a(r.seeked$,e.seekedEvent$),a(r.inPiP$,e.inPiP$),a(r.inFullscreen$,e.inFullscreen$),a(this.videoState.stateChangeEnded$.pipe((0,ue.map)(o=>o.to)),this.params.output.playbackState$),this.subscription.add(Wt(this.video,t.isLooped,i)),this.subscription.add(ot(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(kt(this.video,t.playbackRate,r.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),_(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),_(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i).add(r.loadedMetadata$.subscribe(()=>{let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&(0,ue.isNonNullable)(l.to)){let h=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let m=this.manifests$.getValue().find(g=>g.id===h);m&&(this.params.output.currentVideoTrack$.next(m),this.params.output.hostname$.next(We(m.url)))}let c=this.params.desiredState.playbackRate.getState(),p=this.params.output.element$.getValue()?.playbackRate;if(c!==p){let h=this.params.output.element$.getValue();h&&(this.params.desiredState.playbackRate.setState(c),h.playbackRate=c)}d&&this.params.desiredState.autoVideoTrackSwitching.setState(d.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o.state==="requested"&&this.seek(o.position)},i))),this.subscription.add(this.manifests$.pipe((0,ue.map)(o=>o.map(({id:u,quality:l,size:d,bandwidth:c,fps:p})=>({id:u,quality:l,size:d,fps:p,bitrate:c})))).subscribe(this.params.output.availableVideoTracks$,i)),!W.device.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add((0,ue.merge)((0,ue.fromEvent)(o,"addtrack"),(0,ue.fromEvent)(o,"removetrack"),(0,ue.fromEvent)(o,"change"),(0,ue.observableFrom)(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},i))}let n=(0,ue.merge)(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,(0,ue.observableFrom)(["init"])).pipe((0,ue.debounce)(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),nt(this.video)}prepare(){let e=this.selectManifest();if((0,ue.isNullable)(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:a,min:n}=t?.to??i??{};for(let[o,u]of[[a,"mq"],[n,"lq"]]){let l=String(parseFloat(o||""));u&&o&&r.searchParams.set(u,l)}}this.video.setAttribute("src",r.toString()),this.video.load()}playIfAllowed(){lt(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),_(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:ue.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};var Yv=H(Ui(),1),Vc=H(Gi(),1),Kv=H(Ut(),1);var ye=require("@vkontakte/videoplayer-shared");var Ua=class{constructor(e){this.subscription=new ye.Subscription;this.videoState=new ie("stopped");this.trackUrls={};this.textTracksManager=new Rt;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"),_(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let a=this.params.desiredState.autoVideoTrackLimits.getTransition(),n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.seekState.getState();if(a&&e!=="ready"&&!n){this.handleQualityLimitTransition(a.to);return}if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(n){let{currentTime:u}=this.video;this.prepare(),o.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:u*1e3,forcePrecise:!0});return}switch(i?.to!=="paused"&&o.state==="requested"&&this.seek(o.position),e){case"ready":t==="ready"?_(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),_(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?.to==="playing"&&_(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&_(this.params.desiredState.playbackState,"paused");return;default:return(0,ye.assertNever)(e)}};this.params=e,this.video=at(e.container,e.tuning),this.params.output.element$.next(this.video),(0,Yv.default)(this.params.source).reverse().forEach(([t,i],r)=>{let a=r.toString(10);this.trackUrls[a]={track:{quality:t,id:a},url:i}}),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next((0,Vc.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:ye.ErrorCategory.WTF,message:"MpegProvider internal logic error",thrown:o})},r=ut(this.video);this.subscription.add(()=>r.destroy());let a=(o,u)=>this.subscription.add(o.subscribe(u,i));a(r.timeUpdate$,e.position$),a(r.durationChange$,e.duration$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.loadedMetadata$,e.firstBytesEvent$),a(r.loadedMetadata$,e.loadedMetadataEvent$),a(r.playing$,e.firstFrameEvent$),a(r.canplay$,e.canplay$),a(r.seeked$,e.seekedEvent$),a(r.inPiP$,e.inPiP$),a(r.inFullscreen$,e.inFullscreen$),a(this.videoState.stateChangeEnded$.pipe((0,ye.map)(o=>o.to)),this.params.output.playbackState$),this.subscription.add(Wt(this.video,t.isLooped,i)),this.subscription.add(ot(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(kt(this.video,t.playbackRate,r.playbackRateState$,i)),a(Mt(this.video),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),_(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),_(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready");let o=this.params.desiredState.videoTrack.getTransition();if(o&&(0,ye.isNonNullable)(o.to)){this.params.desiredState.videoTrack.setState(o.to),this.params.output.currentVideoTrack$.next(this.trackUrls[o.to.id].track);let u=this.params.desiredState.playbackRate.getState(),l=this.params.output.element$.getValue()?.playbackRate;if(u!==l){let d=this.params.output.element$.getValue();d&&(this.params.desiredState.playbackRate.setState(u),d.playbackRate=u)}}this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.textTracksManager.connect(this.video,t,e);let n=(0,ye.merge)(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,(0,ye.observableFrom)(["init"])).pipe((0,ye.debounce)(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),nt(this.video)}prepare(){let e=this.params.desiredState.videoTrack.getState()?.id;(0,ye.assertNonNullable)(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];(0,ye.assertNonNullable)(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=Li(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(We(t))}playIfAllowed(){lt(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),_(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:ye.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){this.params.output.autoVideoTrackLimits$.next(e);let t=l=>{this.params.output.currentVideoTrack$.next(l),this.params.desiredState.videoTrack.startTransitionTo(l)},i=l=>{let d=Yt(n,{container:this.video.getBoundingClientRect(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:0,limits:l,abrLogger:this.params.dependencies.abrLogger});t(d)},r=this.params.output.currentVideoTrack$.getValue()?.quality,a=!!(e.max||e.min),n=(0,Vc.default)(this.trackUrls).map(l=>l.track);if(!r||!a||Er(e,n[0].quality,(0,Kv.default)(n,-1)?.quality)){i();return}let o=e.max?(0,ye.isLowerOrEqual)(r,e.max):!0,u=e.min?(0,ye.isHigherOrEqual)(r,e.min):!0;o&&u||i(e)}};var we=require("@vkontakte/videoplayer-shared");var Jv=require("@vkontakte/videoplayer-shared"),Xv=["stun:videostun.mycdn.me:80"],hL=1e3,fL=3,Oc=()=>null,Bo=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=Oc;this.externalStopCallback=Oc;this.externalErrorCallback=Oc;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}}async handleUpdateMessage(e){try{let t=await this.createOffer();this.peerConnection&&await this.peerConnection.setLocalDescription(t),this.handleAnswer(e.sdp)}catch(t){this.handleRTCError(t)}}async handleLogin(){try{let e={iceServers:[{urls:Xv}]};this.peerConnection=new RTCPeerConnection(e),this.peerConnection.ontrack=this.onPeerConnectionStream.bind(this),this.peerConnection.onicecandidate=this.onPeerConnectionIceCandidate.bind(this),this.peerConnection.oniceconnectionstatechange=this.onPeerConnectionIceConnectionStateChange.bind(this);let t=await this.createOffer();await this.peerConnection.setLocalDescription(t),this.send({type:this.signalingType,inviteType:"OFFER",streamKey:this.streamKey,sdp:t.sdp,callSupport:!1})}catch(e){this.handleRTCError(e)}}async handleAnswer(e){try{this.peerConnection&&await this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e}))}catch(t){this.handleRTCError(t)}}async handleCandidate(e){if(e)try{this.peerConnection&&await this.peerConnection.addIceCandidate(e)}catch(t){this.handleRTCError(t)}}handleUnpublished(){try{this.closeConnections(),this.externalStopCallback()}catch(e){this.handleRTCError(e)}}handleSystemError(e){this.options.errorChanel&&this.options.errorChanel.next({id:"webrtc-provider-error",category:Jv.ErrorCategory.WTF,message:e.message})}async onPeerConnectionStream(e){let t=e.streams[0];this.stream&&this.stream.id===t.id||(this.stream=t,this.externalStartCallback(this.stream))}onPeerConnectionIceCandidate(e){e.candidate&&this.send({type:this.signalingType,inviteType:"CANDIDATE",candidate:e.candidate})}onPeerConnectionIceConnectionStateChange(){if(this.peerConnection){let e=this.peerConnection.iceConnectionState;["failed","closed"].indexOf(e)>-1&&(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():(this.closeConnections(),this.scheduleRetry()))}}async createOffer(){let e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");let t=await this.peerConnection.createOffer(e),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{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),hL)}normalizeOptions(e={}){let t={stunServerList:Xv,maxRetryNumber:fL,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var qa=class{constructor(e){this.videoState=new ie("stopped");this.maxSeekBackTime$=new we.ValueSubject(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"),_(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let a=this.params.desiredState.videoTrack.getTransition();if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(a){this.prepare();return}switch(e){case"ready":t==="paused"?(this.videoState.setState("paused"),_(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?.to==="playing"&&_(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&_(this.params.desiredState.playbackState,"paused");return;default:return(0,we.assertNever)(e)}};this.subscription=new we.Subscription,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=at(e.container,e.tuning),this.liveStreamClient=new Bo(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),nt(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,i=n=>{e.error$.next({id:"WebRTCLiveProvider",category:we.ErrorCategory.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};this.subscription.add((0,we.merge)(this.videoState.stateChangeStarted$.pipe((0,we.map)(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe((0,we.map)(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})}));let r=ut(this.video);this.subscription.add(()=>r.destroy());let a=(n,o)=>this.subscription.add(n.subscribe(o,i));a(r.timeUpdate$,e.liveTime$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(Mt(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(()=>{this.videoState.getTransition()?.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(ot(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(0,we.assertNever)(n.to)}},i)).add((0,we.merge)(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,(0,we.observableFrom)(["init"])).pipe((0,we.debounce)(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(We(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:we.VideoQuality.INVARIANT}),this.video.srcObject=e,_(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:we.ErrorCategory.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){lt(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),_(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:we.ErrorCategory.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var ja=class{constructor(e){this.iterator=e[Symbol.iterator](),this.next()}next(){this.current=this.iterator.next()}getValue(){if(this.current.done)throw new Error("Iterable is completed");return this.current.value}isCompleted(){return!!this.current.done}};var E=require("@vkontakte/videoplayer-shared");var yi=require("@vkontakte/videoplayer-shared"),Zv=s=>new yi.Observable(e=>{let t=new yi.Subscription,i=s.desiredPlaybackState$.stateChangeStarted$.pipe((0,yi.map)(({from:l,to:d})=>`${l}-${d}`)),r=s.desiredPlaybackState$.stateChangeEnded$,a=s.providerChanged$.pipe((0,yi.map)(({type:l})=>l!==void 0)),n=new yi.Subject,o=0,u="unknown";return t.add(i.subscribe(l=>{o&&window.clearTimeout(o),u=l,o=window.setTimeout(()=>n.next(l),s.maxTransitionInterval)})),t.add(r.subscribe(()=>{window.clearTimeout(o),u="unknown",o=0})),t.add(a.subscribe(l=>{o&&(window.clearTimeout(o),o=0,l&&(o=window.setTimeout(()=>n.next(u),s.maxTransitionInterval)))})),t.add(n.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});var Bt=require("@vkontakte/videoplayer-shared");function ey(){return new(window.AudioContext||window.webkitAudioContext)}var Nr=class s{constructor(e,t,i,r){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=i;this.volumeMultiplier=r;this.destroyController=new de;this.subscriptions=new Bt.Subscription;this.audioContext=null;this.gainNode=null;this.mediaElementSource=null;this.subscriptions.add(this.provider$.pipe((0,Bt.filter)(a=>!!a.type),(0,Bt.once)()).subscribe(({type:a})=>this.subscribe(a)))}static{this.errorId="VolumeMultiplierManager"}subscribe(e){W.browser.isSafari&&e!=="MPEG"||this.subscriptions.add((0,Bt.combine)({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe((0,Bt.filter)(({playbackState:t,video:i,volume:{muted:r,volume:a}})=>t==="playing"&&!!i&&!r&&!!a),(0,Bt.once)()).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}async initAudioContextOnce(e){let{volumeMultiplier:t}=this,i=ey();this.audioContext=i;let r=i.createGain();if(this.gainNode=r,r.gain.value=t,r.connect(i.destination),i.state==="suspended"&&(await i.resume(),this.destroyController.signal.aborted))return!1;let a=i.createMediaElementSource(e);return this.mediaElementSource=a,a.connect(r),!0}cleanup(){this.mediaElementSource&&(this.mediaElementSource.disconnect(),this.mediaElementSource=null),this.gainNode&&(this.gainNode.disconnect(),this.gainNode=null),this.audioContext&&(this.audioContext.state!=="closed"&&this.audioContext.close(),this.audioContext=null)}destroy(){this.destroyController.abort(),this.subscriptions.unsubscribe(),this.cleanup()}handleError(e){this.volumeMultiplierError$.next({id:s.errorId,category:Bt.ErrorCategory.VIDEO_PIPELINE,message:e?.message??`${s.errorId} exception`,thrown:e})}};var mL={chunkDuration:5e3,maxParallelRequests:5},Ha=class{constructor(e){this.current$=new E.ValueSubject({type:void 0});this.providerError$=new E.Subject;this.noAvailableProvidersError$=new E.Subject;this.volumeMultiplierError$=new E.Subject;this.providerOutput={position$:new E.ValueSubject(0),duration$:new E.ValueSubject(1/0),volume$:new E.ValueSubject({muted:!1,volume:1}),availableVideoStreams$:new E.ValueSubject([]),currentVideoStream$:new E.ValueSubject(void 0),availableVideoTracks$:new E.ValueSubject([]),currentVideoTrack$:new E.ValueSubject(void 0),availableAudioStreams$:new E.ValueSubject([]),currentAudioStream$:new E.ValueSubject(void 0),availableAudioTracks$:new E.ValueSubject([]),currentVideoSegmentLength$:new E.ValueSubject(0),currentAudioSegmentLength$:new E.ValueSubject(0),isAudioAvailable$:new E.ValueSubject(!0),autoVideoTrackLimitingAvailable$:new E.ValueSubject(!1),autoVideoTrackLimits$:new E.ValueSubject(void 0),currentBuffer$:new E.ValueSubject(void 0),isBuffering$:new E.ValueSubject(!0),error$:new E.Subject,fetcherError$:new E.Subject,fetcherRecoverableError$:new E.Subject,warning$:new E.Subject,willSeekEvent$:new E.Subject,soundProhibitedEvent$:new E.Subject,seekedEvent$:new E.Subject,loopedEvent$:new E.Subject,endedEvent$:new E.Subject,firstBytesEvent$:new E.Subject,loadedMetadataEvent$:new E.Subject,firstFrameEvent$:new E.Subject,canplay$:new E.Subject,isLive$:new E.ValueSubject(void 0),isLiveEnded$:new E.ValueSubject(null),isLowLatency$:new E.ValueSubject(!1),canChangePlaybackSpeed$:new E.ValueSubject(!0),liveTime$:new E.ValueSubject(void 0),liveBufferTime$:new E.ValueSubject(void 0),liveLatency$:new E.ValueSubject(void 0),severeStallOccurred$:new E.Subject,availableTextTracks$:new E.ValueSubject([]),currentTextTrack$:new E.ValueSubject(void 0),hostname$:new E.ValueSubject(void 0),httpConnectionType$:new E.ValueSubject(void 0),httpConnectionReused$:new E.ValueSubject(void 0),inPiP$:new E.ValueSubject(!1),inFullscreen$:new E.ValueSubject(!1),element$:new E.ValueSubject(void 0),elementVisible$:new E.ValueSubject(!0),availableSources$:new E.ValueSubject(void 0),is3DVideo$:new E.ValueSubject(!1),playbackState$:new E.ValueSubject(""),getCurrentTime$:new E.ValueSubject(null)};this.subscription=new E.Subscription;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=mv([...gv(this.params.tuning),...bv(this.params.tuning)],this.params.tuning).filter(l=>(0,E.isNonNullable)(e.sources[l])),{forceFormat:i,formatsToAvoid:r}=this.params.tuning,a=[];i?a=[i]:r.length?a=[...t.filter(l=>!(0,_c.default)(r,l)),...t.filter(l=>(0,_c.default)(r,l))]:a=t,this.log({message:`Selected formats: ${a.join(" > ")}`}),this.tracer.log("Selected formats",(0,E.flattenObject)(a)),this.screenFormatsIterator=new ja(a);let n=[...bc(!0),...bc(!1)];this.chromecastFormatsIterator=new ja(n.filter(l=>(0,E.isNonNullable)(e.sources[l]))),this.providerOutput.availableSources$.next(e.sources);let{volumeMultiplier:o=1,tuning:{useVolumeMultiplier:u}}=this.params;u&&o!==1&&Nr.isSupported()&&(this.volumeMultiplierManager=new Nr(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(){this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe(),this.volumeMultiplierManager?.destroy(),this.volumeMultiplierManager=null,this.tracer.end()}initProvider(){let e=this.chooseDestination(),t=this.chooseFormat(e);if((0,E.isNullable)(t)){this.handleNoFormatsError(e);return}let i;try{i=this.createProvider(e,t)}catch(r){this.providerError$.next({id:"ProviderNotConstructed",category:E.ErrorCategory.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"),e.destroy();let t=this.providerOutput.position$.getValue()*1e3,i=this.params.desiredState.seekState.getState(),r=i.state!=="none";if(this.params.desiredState.seekState.setState({state:"requested",position:r?i.position:t,forcePrecise:r?i.forcePrecise:!1}),e.scene3D){let n=e.scene3D.getCameraRotation();this.params.desiredState.cameraOrientation.setState({x:n.x,y:n.y})}let a=this.providerOutput.isBuffering$;a.getValue()||a.next(!0)}createProvider(e,t){switch(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(0,E.assertNever)(e)}}createScreenProvider(e){let{sources:t,container:i,desiredState:r,panelSize:a}=this.params,n=this.providerOutput,o={container:i,source:null,desiredState:r,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning,panelSize:a};switch(e){case"DASH_SEP":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_ONDEMAND":case"DASH_STREAMS":{let u=this.applyFailoverHost(t[e]),l=this.applyFailoverHost(t.HLS_ONDEMAND||t.HLS);return(0,E.assertNonNullable)(u),this.params.tuning.useNewDashProvider?new Oa({...o,source:u,sourceHls:l}):new aa({...o,source:u,sourceHls:l})}case"DASH_LIVE_CMAF":{let u=this.applyFailoverHost(t[e]);return(0,E.assertNonNullable)(u),this.params.tuning.useNewDashProvider?new _a({...o,source:u}):new na({...o,source:u})}case"HLS":case"HLS_ONDEMAND":{let u=this.applyFailoverHost(t[e]);return(0,E.assertNonNullable)(u),new Na({...o,source:u})}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let u=this.applyFailoverHost(t[e]);return(0,E.assertNonNullable)(u),new Fa({...o,source:u,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case"MPEG":{let u=this.applyFailoverHost(t[e]);return(0,E.assertNonNullable)(u),new Ua({...o,source:u})}case"DASH_LIVE":{let u=this.applyFailoverHost(t[e]);return(0,E.assertNonNullable)(u),new Ig({...o,source:u,config:{...mL,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case"WEB_RTC_LIVE":{let u=this.applyFailoverHost(t[e]);return(0,E.assertNonNullable)(u),new qa({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(0,E.assertNever)(e)}}createChromecastProvider(e){let{sources:t,container:i,desiredState:r,meta:a}=this.params,n=this.providerOutput,o=this.params.dependencies.chromecastInitializer.connection$.getValue();return(0,E.assertNonNullable)(o),new hs({connection:o,meta:a,container:i,source:t,format:e,desiredState:r,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?"CHROMECAST":"SCREEN"}chooseFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case"CHROMECAST":return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return(0,E.assertNever)(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return(0,E.assertNever)(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(0,E.assertNever)(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;let t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;let i=r=>{let a=new URL(r);return a.host=t,a.toString()};if(e===void 0)return e;if("type"in e){if(e.type==="raw")return e;if(e.type==="url")return{...e,url:i(e.url)}}return(0,iy.default)((0,ty.default)(e).map(([r,a])=>[r,i(a)]))}initProviderErrorHandling(){let e=new E.Subscription,t=!1,i=0;return e.add((0,E.merge)(this.providerOutput.error$.pipe((0,E.filter)(r=>!this.params.tuning.ignoreAudioRendererError||!r.message||!/AUDIO_RENDERER_ERROR/ig.test(r.message))),Zv({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe((0,E.map)(r=>({id:`ProviderHangup:${r}`,category:E.ErrorCategory.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((0,E.filter)(({to:a})=>a==="playing"),(0,E.once)()).subscribe(()=>t=!0);e.add(r)})),e.add(this.providerError$.subscribe(r=>{let a=this.current$.getValue().destination,n={error:r,currentDestination:a};if(a==="CHROMECAST")this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider("SCREEN"),()=>this.params.dependencies.chromecastInitializer.disconnect());else{let o=r.category===E.ErrorCategory.NETWORK,u=r.category===E.ErrorCategory.FATAL,l=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),d=i<this.params.tuning.providerErrorLimit&&!u,c=l&&!u&&(o&&t||!d);n={...n,isNetworkError:o,isFatalError:u,haveFailoverHost:l,tryFailover:c,canReinitProvider:d},d?(i++,this.reinitProvider()):c?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):(i=0,this.switchToNextProvider(a??"SCREEN"))}r.traceAsLog?this.tracer.log("providerInfo",(0,E.flattenObject)(n)):this.tracer.error("providerError",(0,E.flattenObject)(n))})),e}};var J=require("@vkontakte/videoplayer-shared");var bL=5e3,ry="one_video_throughput",sy="one_video_rtt",za=window.navigator.connection,ay=()=>{let s=za?.downlink;if((0,J.isNonNullable)(s)&&s!==10)return s*1e3},ny=()=>{let s=za?.rtt;if((0,J.isNonNullable)(s)&&s!==3e3)return s},oy=(s,e,t)=>{let i=t*8,r=i/s;return i/(r+e)},Fc=class s{constructor(e){this.subscription=new J.Subscription;this.concurrentDownloads=new Set;this.tuningConfig=e;let t=s.load(ry)||(e.useBrowserEstimation?ay():void 0)||bL,i=s.load(sy)??(e.useBrowserEstimation?ny():void 0)??0;if(this.throughput$=new J.ValueSubject(t),this.rtt$=new J.ValueSubject(i),this.rttAdjustedThroughput$=new J.ValueSubject(oy(t,i,e.rttPenaltyRequestSize)),this.throughput=bi.getSmoothedValue(t,-1,e),this.rtt=bi.getSmoothedValue(i,1,e),e.useBrowserEstimation){let r=()=>{let n=ay();n&&this.throughput.next(n);let o=ny();(0,J.isNonNullable)(o)&&this.rtt.next(o)};za&&"onchange"in za&&this.subscription.add((0,J.fromEvent)(za,"change").subscribe(r)),r()}this.subscription.add(this.throughput.smoothed$.subscribe(r=>{J.safeStorage.set(ry,r.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(r=>{J.safeStorage.set(sy,r.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add((0,J.combine)({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe((0,J.map)(({throughput:r,rtt:a})=>oy(r,a,e.rttPenaltyRequestSize)),(0,J.filter)(r=>{let a=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(r-a)/a>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,i=(0,J.now)(),r=new J.Subscription;switch(this.subscription.add(r),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:r.add((0,J.fromEvent)(e,"progress").pipe((0,J.once)()).subscribe(a=>{t=a.loaded,i=(0,J.now)()}));break;case 1:case 0:r.add((0,J.fromEvent)(e,"loadstart").subscribe(()=>{t=0,i=(0,J.now)()}));break}r.add((0,J.fromEvent)(e,"loadend").subscribe(a=>{if(e.status===200){let n=a.loaded,o=(0,J.now)(),u=n-t,l=o-i;this.addRawSpeed(u,l,1)}this.concurrentDownloads.delete(e),r.unsubscribe()}))}trackStream(e,t=!1){let i=e.getReader();if(!i){e.cancel("Could not get reader");return}let r=0,a=(0,J.now)(),n=0,o=(0,J.now)(),u=d=>{this.concurrentDownloads.delete(e),i.releaseLock(),e.cancel(`Throughput Estimator error: ${d}`).catch(()=>{})},l=async({done:d,value:c})=>{if(d)!t&&this.addRawSpeed(r,(0,J.now)()-a,1),this.concurrentDownloads.delete(e);else if(c){if(t){let p=(0,J.now)();if(p-o>this.tuningConfig.lowLatency.continuesByteSequenceInterval||p-a>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let m=o-a;m&&this.addRawSpeed(n,m,1,t),n=c.byteLength,a=(0,J.now)()}else n+=c.byteLength;o=(0,J.now)()}else r+=c.byteLength,n+=c.byteLength,n>=this.tuningConfig.streamMinSampleSize&&(0,J.now)()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,(0,J.now)()-o,this.concurrentDownloads.size),n=0,o=(0,J.now)());await i?.read().then(l,u)}};this.concurrentDownloads.add(e),i?.read().then(l,u)}addRawSpeed(e,t,i=1,r=!1){if(s.sanityCheck(e,t,r)){let a=e*8/t;this.throughput.next(a*i)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,i=!1){let r=e*8/t;return!(!r||!isFinite(r)||r>1e6||r<30||i&&e<1e4||!i&&e<10*1024||!i&&t<=20)}static load(e){let t=J.safeStorage.get(e);if((0,J.isNonNullable)(t))return parseInt(t,10)??void 0}},uy=Fc;var rr=require("@vkontakte/videoplayer-shared"),ly={configName:["core"],throughputEstimator:{type:"EmaAndMa",emaAlphaSlow:.2,emaAlphaFast:.7,emaAlpha:.45,basisTrendChangeCount:10,changeThreshold:.05,useBrowserEstimation:!0,rttPenaltyRequestSize:1*1024*1024,streamMinSampleSize:10*1024,streamMinSampleTime:300,deviationDepth:20,deviationFactor:.5,lowLatency:{continuesByteSequenceInterval:50,maxLastEvaluationTimeout:300}},autoTrackSelection:{maxBitrateFactorAtEmptyBuffer:4,bitrateFactorAtEmptyBuffer:2.8,minBitrateFactorAtEmptyBuffer:1.5,bitrateAudioFactorAtEmptyBuffer:10,maxBitrateFactorAtFullBuffer:3,bitrateFactorAtFullBuffer:2,minBitrateFactorAtFullBuffer:1,bitrateAudioFactorAtFullBuffer:7,minVideoAudioRatio:5,minAvailableThroughputAudioRatio:5,usePixelRatio:!0,pixelRatioMultiplier:void 0,pixelRatioLogBase:3,pixelRatioLogCoefficients:[1,0,1],limitByContainer:!0,maxContainerSizeFactor:2,containerSizeFactor:1.3,minContainerSizeFactor:1,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldownIncreaseQuality:15e3,trackCooldownDecreaseQuality:3e3,backgroundVideoQualityLimit:rr.VideoQuality.Q_4320P,activeVideoAreaThreshold:.1,highQualityLimit:rr.VideoQuality.Q_720P,trafficSavingLimit:rr.VideoQuality.Q_480P},stallsManager:{enabled:!1,stallDurationNoDataBeforeQualityDecrease:500,stallDurationToBeCount:100,stallCountBeforeQualityDecrease:3,resetQualityRestrictionTimeout:1e4,ignoreStallsOnSeek:!0,stallsMetricsHistoryLength:5,maxPossibleStallDuration:3e4,minTvtToBeCounted:5,maxTvtToBeCounted:10800,significantTvt:600,targetStallsDurationPerTvt:1,deviationStallsDurationPerTvt:.5,criticalStallsDurationPerTvt:6,abrAdjustingSpeed:.1,emaAlpha:.6,useTotalStallsDurationPerTvt:!0,useAverageStallsDurationPerTvt:!0,useEmaStallsDurationPerTvt:!0},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:rr.VideoQuality.Q_480P},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,seekBiasInTheEnd:2e3,maxSegmentDurationLeftToSelectNextSegment:3e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:3e3,crashOnStallTimeout:25e3,crashOnStallTWithoutDataTimeout:5e3,enableSubSegmentBufferFeeding:!0,bufferEmptinessTolerance:100,useFetchPriorityHints:!0,enableBaseUrlSupport:!0,maxSegmentRetryCount:5,sourceOpenTimeout:1e3,vktvAbrThrottle:0,timeupdateEventTickThrottle:300},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,maxLiveDuration:7200,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:250,playbackCatchupSpeedup:.05,isActiveOnDefault:!1,bufferEstimator:{emaAlpha:.45,changeThreshold:.05,deviationDepth:20,deviationFactor:.5,extremumInterval:5}}},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1,lowLatencyActiveLiveDelay:3e3,activeLiveDelay:5e3,maxPausedTime:5e3},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,forceFormat:void 0,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:"07A4434E",useWebmBigRequest:!1,webmCodec:"vp9",androidPreferredFormat:"dash",preferCMAF:!1,preferWebRTC:!1,preferMultiStream:!1,preferHDR:!1,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,seekNearDurationBias:1,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useHlsJs:!1,useNativeHLSTextTracks:!1,useManagedMediaSource:!0,useNewSwitchTo:!1,useNewDashProvider:!1,useNewAutoSelectVideoTrack:!1,useSafariEndlessRequestBugfix:!0,useRefactoredSearchGap:!1,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,manifestRetryInterval:300,manifestRetryMaxInterval:1e4,manifestRetryMaxCount:10,audioVideoSyncRate:20,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50},useVolumeMultiplier:!1,ignoreAudioRendererError:!1,useEnableSubtitlesParam:!1,useOldMSEDetection:!1,useHlsLiveNewTextManager:!1,exposeInternalsToGlobal:!1,hlsLiveNewTextManagerDownloadThreshold:4e3,disableYandexPiP:!1,asyncResolveClientChecker:!1,autostartOnlyIfVisible:!1},cy=s=>({...(0,rr.fillWithDefault)(s,ly),configName:[...s.configName??[],...ly.configName]});var f=require("@vkontakte/videoplayer-shared");var Ti=require("@vkontakte/videoplayer-shared"),Nc=({seekState:s,position$:e})=>(0,Ti.merge)(s.stateChangeEnded$.pipe((0,Ti.map)(({to:t})=>t.state==="none"?void 0:(t.position??NaN)/1e3),(0,Ti.filter)(Ti.isNonNullable)),e.pipe((0,Ti.filter)(()=>s.getState().state==="none")));var dy=require("@vkontakte/videoplayer-shared"),py=s=>{let e=typeof s.container=="string"?document.getElementById(s.container):s.container;return(0,dy.assertNonNullable)(e,`Wrong container or containerId {${s.container}}`),e};var $o=require("@vkontakte/videoplayer-shared"),hy=(s,e,t,i)=>{s!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&t?.getValue().length===0?t.pipe((0,$o.filter)(r=>r.length>0),(0,$o.once)()).subscribe(r=>{r.find(i)&&e.startTransitionTo(s)}):(s===void 0||t?.getValue().find(i))&&e.startTransitionTo(s)};var Qa=class{constructor(e={configName:[]},t=f.TracerFactory.createRootTracer(!1)){this.subscription=new f.Subscription;this.logger=new f.Logger;this.abrLogger=this.logger.createComponentLog("ABR");this.internalsExposure=null;this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new f.ValueSubject(!1);this.hasLiveOffsetByPausedTimer=0;this.playerInitRequest=0;this.playerInited=new f.ValueSubject(!1);this.wasSetStartedQuality=!1;this.desiredState={playbackState:new ie("stopped"),seekState:new ie({state:"none"}),volume:new ie({volume:1,muted:!1}),videoTrack:new ie(void 0),videoStream:new ie(void 0),audioStream:new ie(void 0),autoVideoTrackSwitching:new ie(!0),autoVideoTrackLimits:new ie({}),isLooped:new ie(!1),isLowLatency:new ie(!1),playbackRate:new ie(1),externalTextTracks:new ie([]),internalTextTracks:new ie([]),currentTextTrack:new ie(void 0),textTrackCuesSettings:new ie({}),cameraOrientation:new ie({x:0,y:0})};this.info={playbackState$:new f.ValueSubject(void 0),position$:new f.ValueSubject(0),duration$:new f.ValueSubject(1/0),muted$:new f.ValueSubject(!1),volume$:new f.ValueSubject(1),availableVideoStreams$:new f.ValueSubject([]),currentVideoStream$:new f.ValueSubject(void 0),availableQualities$:new f.ValueSubject([]),availableQualitiesFps$:new f.ValueSubject({}),currentQuality$:new f.ValueSubject(void 0),isAutoQualityEnabled$:new f.ValueSubject(!0),autoQualityLimitingAvailable$:new f.ValueSubject(!1),autoQualityLimits$:new f.ValueSubject({}),predefinedQualityLimitType$:new f.ValueSubject("unknown"),availableAudioStreams$:new f.ValueSubject([]),currentAudioStream$:new f.ValueSubject(void 0),availableAudioTracks$:new f.ValueSubject([]),isAudioAvailable$:new f.ValueSubject(!0),currentPlaybackRate$:new f.ValueSubject(1),currentBuffer$:new f.ValueSubject({start:0,end:0}),isBuffering$:new f.ValueSubject(!0),isStalled$:new f.ValueSubject(!1),isEnded$:new f.ValueSubject(!1),isLooped$:new f.ValueSubject(!1),isLive$:new f.ValueSubject(void 0),isLiveEnded$:new f.ValueSubject(null),canChangePlaybackSpeed$:new f.ValueSubject(void 0),atLiveEdge$:new f.ValueSubject(void 0),atLiveDurationEdge$:new f.ValueSubject(void 0),liveTime$:new f.ValueSubject(void 0),liveBufferTime$:new f.ValueSubject(void 0),liveLatency$:new f.ValueSubject(void 0),currentFormat$:new f.ValueSubject(void 0),availableTextTracks$:new f.ValueSubject([]),currentTextTrack$:new f.ValueSubject(void 0),throughputEstimation$:new f.ValueSubject(void 0),rttEstimation$:new f.ValueSubject(void 0),videoBitrate$:new f.ValueSubject(void 0),hostname$:new f.ValueSubject(void 0),httpConnectionType$:new f.ValueSubject(void 0),httpConnectionReused$:new f.ValueSubject(void 0),surface$:new f.ValueSubject("none"),chromecastState$:new f.ValueSubject("NOT_AVAILABLE"),chromecastDeviceName$:new f.ValueSubject(void 0),intrinsicVideoSize$:new f.ValueSubject(void 0),availableSources$:new f.ValueSubject(void 0),is3DVideo$:new f.ValueSubject(!1),currentVideoSegmentLength$:new f.ValueSubject(0),currentAudioSegmentLength$:new f.ValueSubject(0)};this.events={inited$:new f.Subject,ready$:new f.Subject,started$:new f.Subject,playing$:new f.Subject,paused$:new f.Subject,stopped$:new f.Subject,willReady$:new f.Subject,willStart$:new f.Subject,willResume$:new f.Subject,willPause$:new f.Subject,willStop$:new f.Subject,willDestruct$:new f.Subject,watchCoverageRecord$:new f.Subject,watchCoverageLive$:new f.Subject,managedError$:new f.Subject,fatalError$:new f.Subject,fetcherRecoverableError$:new f.Subject,ended$:new f.Subject,looped$:new f.Subject,seeked$:new f.Subject,willSeek$:new f.Subject,autoplaySoundProhibited$:new f.Subject,firstBytes$:new f.Subject,loadedMetadata$:new f.Subject,firstFrame$:new f.Subject,canplay$:new f.Subject,log$:new f.Subject,fetcherError$:new f.Subject,severeStallOccured$:new f.Subject};this.experimental={element$:new f.ValueSubject(void 0),tuningConfigName$:new f.ValueSubject([]),enableDebugTelemetry$:new f.ValueSubject(!1),dumpTelemetry:ag,getCurrentTime$:new f.ValueSubject(null)};if(this.initLogs(),this.tuning=cy(e),this.tracer=t,this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new en({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new uy(this.tuning.throughputEstimator),e.exposeInternalsToGlobal&&(this.internalsExposure=new f.InternalsExposure("CORE"),this.internalsExposure.expose({player:this})),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(i,r,a)=>{let n=Reflect.get(i,r,a);return typeof n!="function"?n:(...o)=>{try{return n.apply(i,o)}catch(u){let l=o.map(p=>JSON.stringify(p,(h,m)=>{let g=typeof m;return(0,fy.default)(["number","string","boolean"],g)?m:m===null?null:`<${g}>`})),d=`Player.${String(r)}`,c=`Exception calling ${d} (${l.join(", ")})`;throw this.events.fatalError$.next({id:d,category:f.ErrorCategory.WTF,message:c,thrown:u}),u}}}})}initVideo(e){this.config=e,this.internalsExposure?.expose({config:e,logger:this.logger,tuning:this.tuning}),this.setMuted(this.tuning.isAudioDisabled);let t=()=>{let{container:a,...n}=e;this.tracer.log("initVideo",(0,f.flattenObject)(n)),this.domContainer=py(e),this.chromecastInitializer.contentId=e.meta?.videoId,this.providerContainer=new Ha({sources:e.sources,meta:e.meta??{},failoverHosts:e.failoverHosts??[],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.initDebugTelemetry(),this.initWakeLock(),this.playerInited.next(!0)},i=()=>{this.tuning.autostartOnlyIfVisible&&window.requestAnimationFrame?this.playerInitRequest=window.requestAnimationFrame(()=>t()):t()},r=()=>{this.tuning.asyncResolveClientChecker?W.isInited$.pipe((0,f.filter)(a=>!!a),(0,f.once)()).subscribe(()=>{console.log("Core SDK async start"),i()}):i()};return this.isNotActiveTabCase()?(this.tracer.log("request play from hidden tab"),(0,f.fromEvent)(document,"visibilitychange").pipe((0,f.once)()).subscribe(r)):r(),this}destroy(){this.tracer.log("destroy"),window.clearTimeout(this.hasLiveOffsetByPausedTimer),this.playerInitRequest&&window.cancelAnimationFrame(this.playerInitRequest),this.events.willDestruct$.next(),this.stop(),this.providerContainer?.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe(),this.tracer.end(),this.internalsExposure?.destroy()}prepare(){return this.subscription.add(this.playerInited.pipe((0,f.filter)(e=>!!e),(0,f.once)()).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((0,f.filter)(e=>!!e),(0,f.once)()).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((0,f.filter)(e=>!!e),(0,f.once)()).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((0,f.filter)(e=>!!e),(0,f.once)()).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((0,f.filter)(i=>!!i),(0,f.once)()).subscribe(()=>{let i=this.info.duration$.getValue(),r=this.info.isLive$.getValue(),a=e;e>=i&&!r&&(a=i-this.tuning.seekNearDurationBias),this.tracer.log("seekTime",{duration:i,isLive:r,time:e,calculatedTime:a,forcePrecise:t}),Number.isFinite(a)&&(this.events.willSeek$.next({from:this.getExactTime(),to:a}),this.desiredState.seekState.setState({state:"requested",position:a*1e3,forcePrecise:t}))})),this}seekPercent(e){return this.subscription.add(this.playerInited.pipe((0,f.filter)(t=>!!t),(0,f.once)()).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((0,f.filter)(i=>!!i),(0,f.once)()).subscribe(()=>{let i=this.desiredState.volume,a=i.getTransition()?.to.muted??this.info.muted$.getValue(),n=t??(this.tuning.isAudioDisabled||a);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,t=!1){return this.subscription.add(this.playerInited.pipe((0,f.filter)(i=>!!i),(0,f.once)()).subscribe(()=>{let i=this.desiredState.volume,r=this.tuning.isAudioDisabled&&!t||e,n=i.getTransition()?.to.volume??this.info.volume$.getValue();this.tracer.log("setMuted",{isMuted:e,nextMuted:r,volume:n,isAudioDisabled:this.tuning.isAudioDisabled,chromecastState:this.chromecastInitializer.castState$.getValue()}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setMuted(r):i.startTransitionTo({volume:n,muted:r})})),this}setVideoStream(e){return this.subscription.add(this.playerInited.pipe((0,f.filter)(t=>!!t),(0,f.once)()).subscribe(()=>{this.desiredState.videoStream.startTransitionTo(e)})),this}setAudioStream(e){return this.subscription.add(this.playerInited.pipe((0,f.filter)(t=>!!t),(0,f.once)()).subscribe(()=>{this.desiredState.audioStream.startTransitionTo(e)})),this}setQuality(e){return this.subscription.add(this.playerInited.pipe((0,f.filter)(t=>!!t),(0,f.once)()).subscribe(()=>{(0,f.assertNonNullable)(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((0,f.filter)(i=>i.length>0),(0,f.once)()).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((0,f.filter)(t=>!!t),(0,f.once)()).subscribe(()=>{this.tracer.log("setAutoQuality",{enable:e}),this.desiredState.autoVideoTrackSwitching.startTransitionTo(e)})),this}setAutoQualityLimits(e){return this.subscription.add(this.playerInited.pipe((0,f.filter)(t=>!!t),(0,f.once)()).subscribe(()=>{this.tracer.log("setAutoQualityLimits",(0,f.flattenObject)(e)),this.desiredState.autoVideoTrackLimits.startTransitionTo(e)})),this}setPredefinedQualityLimits(e){return this.subscription.add(this.playerInited.pipe((0,f.filter)(t=>!!t),(0,f.once)()).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((0,f.filter)(t=>!!t),(0,f.once)()).subscribe(()=>{(0,f.assertNonNullable)(this.providerContainer);let t=this.providerContainer?.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((0,f.filter)(t=>!!t),(0,f.once)()).subscribe(()=>{e.length&&this.tracer.log("setExternalTextTracks",(0,f.flattenObject)(e)),this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>({type:"external",...t})))})),this}selectTextTrack(e){return this.subscription.add(this.playerInited.pipe((0,f.filter)(t=>!!t),(0,f.once)()).subscribe(()=>{hy(e,this.desiredState.currentTextTrack,this.providerContainer?.providerOutput.availableTextTracks$,t=>t.id===e),this.tracer.log("selectTextTrack",{textTrackId:e})})),this}setTextTrackCueSettings(e){return this.subscription.add(this.playerInited.pipe((0,f.filter)(t=>!!t),(0,f.once)()).subscribe(()=>{this.tracer.log("setTextTrackCueSettings",{...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((0,f.filter)(t=>!!t),(0,f.once)()).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((0,f.filter)(i=>!!i),(0,f.once)()).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((0,f.filter)(t=>!!t),(0,f.once)()).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((0,f.filter)(i=>!!i),(0,f.once)()).subscribe(()=>{let i=this.getScene3D();if(this.tracer.log("moveCameraFocusPX",{isScene3DAvailable:!!i,dxpx:e,dypx:t}),i){let r=i.getCameraRotation(),a=i.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:r.x+a.x,y:r.y+a.y})}})),this}holdCamera(){return this.subscription.add(this.playerInited.pipe((0,f.filter)(e=>e),(0,f.once)()).subscribe(()=>{let e=this.getScene3D();e&&e.holdCamera()})),this}releaseCamera(){return this.subscription.add(this.playerInited.pipe((0,f.filter)(e=>!!e),(0,f.once)()).subscribe(()=>{let e=this.getScene3D();e&&e.releaseCamera()})),this}getExactTime(){if(!this.providerContainer)return 0;let e=this.providerContainer.providerOutput.element$.getValue();if((0,f.isNullable)(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),i=t.state==="none"?void 0:t.position;return(0,f.isNonNullable)(i)?i/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}getScene3D(){let e=this.providerContainer?.current$.getValue();if(e?.provider?.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((0,f.merge)(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe((0,f.map)(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe((0,f.map)(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe((0,f.map)(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe((0,f.map)(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe((0,f.map)(e=>e.to)).subscribe(e=>{this.info.autoQualityLimits$.next(e);let{highQualityLimit:t,trafficSavingLimit:i}=this.tuning.autoTrackSelection;this.info.predefinedQualityLimitType$.next(_l(e,t,i))})),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe((0,f.filter)(({from:e})=>e==="stopped"),(0,f.once)()).subscribe(()=>{this.initedAt=(0,f.now)(),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"ready":this.events.willReady$.next();break;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",(0,f.flattenObject)(n)),n.state==="requested"?this.desiredState.seekState.setState({...n,state:"applying"}):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:f.ErrorCategory.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.soundProhibitedEvent$.pipe((0,f.once)()).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",(0,f.flattenObject)(n)),n.state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe((0,f.map)(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe((0,f.map)(n=>n.destination),(0,f.filterChanged)()).subscribe(()=>this.isPlaybackStarted=!1)).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add((0,f.combine)({availableVideoTracks:e.providerOutput.availableVideoTracks$,currentVideoStream:e.providerOutput.currentVideoStream$}).pipe((0,f.map)(({availableVideoTracks:n,currentVideoStream:o})=>n.filter(u=>o?o.id===u.streamId:!0).map(({quality:u})=>u).sort((u,l)=>(0,f.isInvariantQuality)(u)?1:(0,f.isInvariantQuality)(l)?-1:(0,f.isHigher)(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((0,f.filterChanged)()).subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.pipe((0,f.filter)(n=>(0,f.isNonNullable)(n))).subscribe(n=>{this.info.currentQuality$.next(n?.quality),this.info.videoBitrate$.next(n?.bitrate)})).add(e.providerOutput.currentVideoSegmentLength$.pipe((0,f.filterChanged)((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.pipe((0,f.filterChanged)((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe((0,f.filterChanged)()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe((0,f.filterChanged)()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe((0,f.filterChanged)()).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??{})})).add(e.providerOutput.currentBuffer$.pipe((0,f.map)(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((0,f.tap)(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((0,f.combine)({hasLiveOffsetByPaused:(0,f.merge)(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe((0,f.map)(n=>n.to),(0,f.filterChanged)(),(0,f.map)(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((0,f.combine)({atLiveEdge:(0,f.combine)({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:Nc({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe((0,f.map)(({isLive:n,position:o,isLowLatency:u})=>{let l=this.getActiveLiveDelay(u);return n&&Math.abs(o)<l/1e3}),(0,f.filterChanged)(),(0,f.tap)(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe((0,f.map)(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add((0,f.combine)({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe((0,f.map)(({isLive:n,position:o,duration:u})=>n&&(Math.abs(u)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),(0,f.filterChanged)(),(0,f.tap)(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe((0,f.map)(n=>n.muted),(0,f.filterChanged)()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe((0,f.map)(n=>n.volume),(0,f.filterChanged)()).subscribe(this.info.volume$)).add(Nc({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add((0,f.merge)(e.providerOutput.endedEvent$.pipe((0,f.mapTo)(!0)),e.providerOutput.seekedEvent$.pipe((0,f.mapTo)(!1))).pipe((0,f.filterChanged)()).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((0,f.map)(n=>({id:n?`No${n}`:"NoProviders",category:f.ErrorCategory.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((0,f.once)(),(0,f.map)(n=>n??(0,f.now)()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe((0,f.once)(),(0,f.map)(()=>(0,f.now)()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe((0,f.once)(),(0,f.map)(()=>(0,f.now)()-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 f.ValueSubject(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let i=new f.ValueSubject(!0);this.subscription.add(e.current$.subscribe(()=>i.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe((0,f.filter)(({to:n})=>n==="playing"),(0,f.once)()).subscribe(()=>i.next(!1)));let r=0,a=(0,f.merge)(e.providerOutput.isBuffering$,t,i).pipe((0,f.map)(()=>{let n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||i.getValue();return n&&!o}),(0,f.filterChanged)());this.subscription.add(a.subscribe(n=>{n?r=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(r),this.info.isStalled$.next(!1))})),this.subscription.add((0,f.merge)(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{let n=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:n?.videoWidth,height:n?.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{let o=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:n?.size?.width,height:n?.size?.height},{width:o?.videoWidth,height:o?.videoHeight})})).add(e.providerOutput.is3DVideo$.subscribe(this.info.is3DVideo$)),this.subscription.add((0,f.merge)(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,e.providerOutput.elementVisible$,this.chromecastInitializer.castState$).subscribe(()=>{let n=e.providerOutput.inPiP$.getValue(),o=e.providerOutput.inFullscreen$.getValue(),u=e.providerOutput.element$.getValue(),l=e.providerOutput.elementVisible$.getValue(),d=this.chromecastInitializer.castState$.getValue(),c;d==="CONNECTED"?c="second_screen":u?l?n?c="pip":o?c="fullscreen":c="inline":c="invisible":c="none",this.info.surface$.getValue()!==c&&this.info.surface$.next(c)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe((0,f.map)(e=>e?.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){let t=new f.Subscription;this.subscription.add(t),this.subscription.add(e.current$.pipe((0,f.filterChanged)((i,r)=>i.provider===r.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe((0,f.filter)(i=>i.length>0),(0,f.once)()).subscribe(i=>{this.setStartingVideoTrack(i)}))}))}setStartingVideoTrack(e){let t;this.wasSetStartedQuality=!0;let i=this.explicitInitialQuality??this.info.currentQuality$.getValue();i&&(t=e.find(({quality:r})=>r===i),t||this.setAutoQuality(!0)),t||(t=Yt(e,{container:this.domContainer.getBoundingClientRect(),panelSize:this.config.panelSize,estimatedThroughput:this.throughputEstimator.throughput$.getValue(),tuning:this.tuning.autoTrackSelection,limits:this.desiredState.autoVideoTrackLimits.getState(),playbackRate:this.info.currentPlaybackRate$.getValue(),forwardBufferHealth:0,abrLogger:this.abrLogger})),this.desiredState.videoTrack.startTransitionTo(t),this.info.currentQuality$.next(t.quality),this.info.videoBitrate$.next(t.bitrate)}initLogs(){this.subscription.add((0,f.merge)(this.desiredState.videoTrack.stateChangeStarted$.pipe((0,f.map)(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe((0,f.map)(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe((0,f.map)(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe((0,f.map)(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe((0,f.map)(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe((0,f.map)(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe((0,f.map)(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe((0,f.map)(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe((0,f.map)(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(){let e=this.providerContainer?.providerOutput;(0,f.assertNonNullable)(this.providerContainer),(0,f.assertNonNullable)(e),sg(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(t=>rg(t)),this.providerContainer.current$.subscribe(({type:t})=>ms("provider",t)),e.duration$.subscribe(t=>ms("duration",t)),e.availableVideoTracks$.pipe((0,f.filter)(t=>!!t.length),(0,f.once)()).subscribe(t=>ms("tracks",t)),this.events.fatalError$.subscribe(new tt("fatalError")),this.events.managedError$.subscribe(new tt("managedError")),e.position$.subscribe(new tt("position")),e.currentVideoTrack$.pipe((0,f.map)(t=>t?.quality)).subscribe(new tt("quality")),this.info.currentBuffer$.subscribe(new tt("buffer")),e.isBuffering$.subscribe(new tt("isBuffering"))].forEach(t=>this.subscription.add(t)),ms("codecs",W.video.supportedCodecs)}initTracerSubscription(){let e=(0,f.getTraceSubscriptionMethod)(this.tracer.log.bind(this.tracer)),t=(0,f.getTraceSubscriptionMethod)(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((0,f.filterChanged)()).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((0,f.combine)({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe((0,f.filter)(({currentQuality:i,videoBitrate:r})=>!!i&&!!r),(0,f.filterChanged)((i,r)=>i.currentQuality===r.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe((0,f.filter)(i=>i>0),(0,f.filterChanged)()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe((0,f.filter)(i=>i>0),(0,f.filterChanged)()).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((0,f.combine)({currentBuffer:this.info.currentBuffer$.pipe((0,f.filter)(i=>i.end>0),(0,f.filterChanged)((i,r)=>i.end===r.end&&i.start===r.start)),position:this.info.position$.pipe((0,f.filterChanged)())}).pipe((0,f.throttle)(1e3)).subscribe(e("currentBufferAndPosition"))).add(this.info.duration$.pipe((0,f.filterChanged)()).subscribe(e("duration"))).add(this.info.isBuffering$.subscribe(e("isBuffering"))).add(this.info.isLive$.pipe((0,f.filterChanged)()).subscribe(e("isLive"))).add(this.info.canChangePlaybackSpeed$.pipe((0,f.filterChanged)()).subscribe(e("canChangePlaybackSpeed"))).add((0,f.combine)({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe((0,f.filter)(({liveTime:i,liveBufferTime:r})=>!!i&&!!r),(0,f.throttle)(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe((0,f.filterChanged)(),(0,f.filter)(i=>i===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe((0,f.filterChanged)(),(0,f.filter)(i=>i===!0)).subscribe(e("atLiveDurationEdge"))).add(this.info.muted$.pipe((0,f.filterChanged)()).subscribe(e("muted"))).add(this.info.volume$.pipe((0,f.filterChanged)()).subscribe(e("volume"))).add(this.info.isEnded$.pipe((0,f.filterChanged)(),(0,f.filter)(i=>i===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add((0,f.combine)({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe((0,f.filter)(({throughputEstimation:i,rtt:r})=>!!i&&!!r),(0,f.throttle)(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe((0,f.filterChanged)(),(0,f.filter)(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?.release(),e=void 0},i=async()=>{t(),e=await window.navigator.wakeLock.request("screen").catch(r=>{r instanceof DOMException&&r.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:f.ErrorCategory.DOM,message:String(r)})})};this.subscription.add((0,f.merge)((0,f.fromEvent)(document,"visibilitychange"),(0,f.fromEvent)(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{let r=document.visibilityState==="visible",a=this.desiredState.playbackState.getState()==="playing",n=!!e&&!e?.released;r&&a?n||i():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){let i=e.find(r=>r.quality===t);this.tracer.log("setVideoTrackIdByQuality",(0,f.flattenObject)({quality:t,availableTracks:(0,f.flattenObject)(e),track:(0,f.flattenObject)(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&&!Ts()}};var Jt=require("@vkontakte/videoplayer-shared"),gL=`@vkontakte/videoplayer-core@${_o}`;
|