@vkontakte/videoplayer-core 2.0.111-dev.974e99b3.0 → 2.0.111-dev.ae3e5b42.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 +15 -15
- package/es2015.esm.js +15 -15
- package/es2018.cjs.js +10 -10
- package/es2018.esm.js +10 -10
- package/esnext.cjs.js +13 -13
- package/esnext.esm.js +12 -12
- package/evergreen.esm.js +14 -14
- package/package.json +2 -2
- package/types/providers/DashProvider/baseDashProvider.d.ts +0 -6
- package/types/providers/DashProvider/lib/LiveTextManager.d.ts +21 -0
- package/types/providers/DashProvider/lib/player.d.ts +3 -1
- package/types/providers/DashProvider/lib/types.d.ts +6 -0
- package/types/providers/DashProvider/lib/utils.d.ts +3 -5
package/es2018.esm.js
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @vkontakte/videoplayer-core v2.0.111-dev.
|
|
3
|
-
*
|
|
2
|
+
* @vkontakte/videoplayer-core v2.0.111-dev.ae3e5b42.0
|
|
3
|
+
* Wed, 02 Oct 2024 09:38:29 GMT
|
|
4
4
|
* https://st.mycdn.me/static/vkontakte-videoplayer/2-0-111/doc/
|
|
5
5
|
*/
|
|
6
|
-
var tv=Object.create;var Cc=Object.defineProperty;var rv=Object.getOwnPropertyDescriptor;var iv=Object.getOwnPropertyNames;var av=Object.getPrototypeOf,sv=Object.prototype.hasOwnProperty;var m=(a,e)=>()=>(e||a((e={exports:{}}).exports,e),e.exports);var nv=(a,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of iv(e))!sv.call(a,i)&&i!==t&&Cc(a,i,{get:()=>e[i],enumerable:!(r=rv(e,i))||r.enumerable});return a};var He=(a,e,t)=>(t=a!=null?tv(av(a)):{},nv(e||!a||!a.__esModule?Cc(t,"default",{value:a,enumerable:!0}):t,a));var ve=m((eL,qc)=>{"use strict";qc.exports=function(a){try{return!!a()}catch(e){return!0}}});var qr=m((tL,Uc)=>{"use strict";var fv=ve();Uc.exports=!fv(function(){var a=function(){}.bind();return typeof a!="function"||a.hasOwnProperty("prototype")})});var ce=m((rL,Gc)=>{"use strict";var Hc=qr(),jc=Function.prototype,mn=jc.call,mv=Hc&&jc.bind.bind(mn,mn);Gc.exports=Hc?mv:function(a){return function(){return mn.apply(a,arguments)}}});var tr=m((iL,Yc)=>{"use strict";var Wc=ce(),bv=Wc({}.toString),gv=Wc("".slice);Yc.exports=function(a){return gv(bv(a),8,-1)}});var zc=m((aL,Qc)=>{"use strict";var Sv=ce(),vv=ve(),yv=tr(),bn=Object,Tv=Sv("".split);Qc.exports=vv(function(){return!bn("z").propertyIsEnumerable(0)})?function(a){return yv(a)==="String"?Tv(a,""):bn(a)}:bn});var rr=m((sL,Kc)=>{"use strict";Kc.exports=function(a){return a==null}});var Ur=m((nL,Jc)=>{"use strict";var Iv=rr(),Ev=TypeError;Jc.exports=function(a){if(Iv(a))throw new Ev("Can't call method on "+a);return a}});var ir=m((oL,Xc)=>{"use strict";var xv=zc(),Pv=Ur();Xc.exports=function(a){return xv(Pv(a))}});var gn=m((uL,Zc)=>{"use strict";Zc.exports=function(){}});var $t=m((cL,el)=>{"use strict";el.exports={}});var Y=m((Sn,tl)=>{"use strict";var Hr=function(a){return a&&a.Math===Math&&a};tl.exports=Hr(typeof globalThis=="object"&&globalThis)||Hr(typeof window=="object"&&window)||Hr(typeof self=="object"&&self)||Hr(typeof global=="object"&&global)||Hr(typeof Sn=="object"&&Sn)||function(){return this}()||Function("return this")()});var W=m((lL,rl)=>{"use strict";var vn=typeof document=="object"&&document.all;rl.exports=typeof vn=="undefined"&&vn!==void 0?function(a){return typeof a=="function"||a===vn}:function(a){return typeof a=="function"}});var sl=m((dL,al)=>{"use strict";var Av=Y(),wv=W(),il=Av.WeakMap;al.exports=wv(il)&&/native code/.test(String(il))});var Pe=m((pL,nl)=>{"use strict";var kv=W();nl.exports=function(a){return typeof a=="object"?a!==null:kv(a)}});var Ae=m((hL,ol)=>{"use strict";var Rv=ve();ol.exports=!Rv(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var Ea=m((fL,cl)=>{"use strict";var $v=Y(),ul=Pe(),yn=$v.document,Lv=ul(yn)&&ul(yn.createElement);cl.exports=function(a){return Lv?yn.createElement(a):{}}});var Tn=m((mL,ll)=>{"use strict";var Mv=Ae(),Cv=ve(),Dv=Ea();ll.exports=!Mv&&!Cv(function(){return Object.defineProperty(Dv("div"),"a",{get:function(){return 7}}).a!==7})});var In=m((bL,dl)=>{"use strict";var Bv=Ae(),Ov=ve();dl.exports=Bv&&Ov(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var je=m((gL,pl)=>{"use strict";var Vv=Pe(),_v=String,Nv=TypeError;pl.exports=function(a){if(Vv(a))return a;throw new Nv(_v(a)+" is not an object")}});var ye=m((SL,hl)=>{"use strict";var Fv=qr(),xa=Function.prototype.call;hl.exports=Fv?xa.bind(xa):function(){return xa.apply(xa,arguments)}});var Pa=m((vL,fl)=>{"use strict";fl.exports={}});var Ye=m((yL,bl)=>{"use strict";var En=Pa(),xn=Y(),qv=W(),ml=function(a){return qv(a)?a:void 0};bl.exports=function(a,e){return arguments.length<2?ml(En[a])||ml(xn[a]):En[a]&&En[a][e]||xn[a]&&xn[a][e]}});var jr=m((TL,gl)=>{"use strict";var Uv=ce();gl.exports=Uv({}.isPrototypeOf)});var ar=m((IL,yl)=>{"use strict";var Hv=Y(),Sl=Hv.navigator,vl=Sl&&Sl.userAgent;yl.exports=vl?String(vl):""});var An=m((EL,Al)=>{"use strict";var Pl=Y(),Pn=ar(),Tl=Pl.process,Il=Pl.Deno,El=Tl&&Tl.versions||Il&&Il.version,xl=El&&El.v8,Oe,Aa;xl&&(Oe=xl.split("."),Aa=Oe[0]>0&&Oe[0]<4?1:+(Oe[0]+Oe[1]));!Aa&&Pn&&(Oe=Pn.match(/Edge\/(\d+)/),(!Oe||Oe[1]>=74)&&(Oe=Pn.match(/Chrome\/(\d+)/),Oe&&(Aa=+Oe[1])));Al.exports=Aa});var wn=m((xL,kl)=>{"use strict";var wl=An(),jv=ve(),Gv=Y(),Wv=Gv.String;kl.exports=!!Object.getOwnPropertySymbols&&!jv(function(){var a=Symbol("symbol detection");return!Wv(a)||!(Object(a)instanceof Symbol)||!Symbol.sham&&wl&&wl<41})});var kn=m((PL,Rl)=>{"use strict";var Yv=wn();Rl.exports=Yv&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var Rn=m((AL,$l)=>{"use strict";var Qv=Ye(),zv=W(),Kv=jr(),Jv=kn(),Xv=Object;$l.exports=Jv?function(a){return typeof a=="symbol"}:function(a){var e=Qv("Symbol");return zv(e)&&Kv(e.prototype,Xv(a))}});var Gr=m((wL,Ll)=>{"use strict";var Zv=String;Ll.exports=function(a){try{return Zv(a)}catch(e){return"Object"}}});var Qe=m((kL,Ml)=>{"use strict";var ey=W(),ty=Gr(),ry=TypeError;Ml.exports=function(a){if(ey(a))return a;throw new ry(ty(a)+" is not a function")}});var Wr=m((RL,Cl)=>{"use strict";var iy=Qe(),ay=rr();Cl.exports=function(a,e){var t=a[e];return ay(t)?void 0:iy(t)}});var Bl=m(($L,Dl)=>{"use strict";var $n=ye(),Ln=W(),Mn=Pe(),sy=TypeError;Dl.exports=function(a,e){var t,r;if(e==="string"&&Ln(t=a.toString)&&!Mn(r=$n(t,a))||Ln(t=a.valueOf)&&!Mn(r=$n(t,a))||e!=="string"&&Ln(t=a.toString)&&!Mn(r=$n(t,a)))return r;throw new sy("Can't convert object to primitive value")}});var Ve=m((LL,Ol)=>{"use strict";Ol.exports=!0});var Nl=m((ML,_l)=>{"use strict";var Vl=Y(),ny=Object.defineProperty;_l.exports=function(a,e){try{ny(Vl,a,{value:e,configurable:!0,writable:!0})}catch(t){Vl[a]=e}return e}});var Yr=m((CL,Ul)=>{"use strict";var oy=Ve(),uy=Y(),cy=Nl(),Fl="__core-js_shared__",ql=Ul.exports=uy[Fl]||cy(Fl,{});(ql.versions||(ql.versions=[])).push({version:"3.38.0",mode:oy?"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 Cn=m((DL,jl)=>{"use strict";var Hl=Yr();jl.exports=function(a,e){return Hl[a]||(Hl[a]=e||{})}});var Qr=m((BL,Gl)=>{"use strict";var ly=Ur(),dy=Object;Gl.exports=function(a){return dy(ly(a))}});var _e=m((OL,Wl)=>{"use strict";var py=ce(),hy=Qr(),fy=py({}.hasOwnProperty);Wl.exports=Object.hasOwn||function(e,t){return fy(hy(e),t)}});var Dn=m((VL,Yl)=>{"use strict";var my=ce(),by=0,gy=Math.random(),Sy=my(1 .toString);Yl.exports=function(a){return"Symbol("+(a===void 0?"":a)+")_"+Sy(++by+gy,36)}});var te=m((_L,zl)=>{"use strict";var vy=Y(),yy=Cn(),Ql=_e(),Ty=Dn(),Iy=wn(),Ey=kn(),sr=vy.Symbol,Bn=yy("wks"),xy=Ey?sr.for||sr:sr&&sr.withoutSetter||Ty;zl.exports=function(a){return Ql(Bn,a)||(Bn[a]=Iy&&Ql(sr,a)?sr[a]:xy("Symbol."+a)),Bn[a]}});var Zl=m((NL,Xl)=>{"use strict";var Py=ye(),Kl=Pe(),Jl=Rn(),Ay=Wr(),wy=Bl(),ky=te(),Ry=TypeError,$y=ky("toPrimitive");Xl.exports=function(a,e){if(!Kl(a)||Jl(a))return a;var t=Ay(a,$y),r;if(t){if(e===void 0&&(e="default"),r=Py(t,a,e),!Kl(r)||Jl(r))return r;throw new Ry("Can't convert object to primitive value")}return e===void 0&&(e="number"),wy(a,e)}});var On=m((FL,ed)=>{"use strict";var Ly=Zl(),My=Rn();ed.exports=function(a){var e=Ly(a,"string");return My(e)?e:e+""}});var Lt=m(rd=>{"use strict";var Cy=Ae(),Dy=Tn(),By=In(),wa=je(),td=On(),Oy=TypeError,Vn=Object.defineProperty,Vy=Object.getOwnPropertyDescriptor,_n="enumerable",Nn="configurable",Fn="writable";rd.f=Cy?By?function(e,t,r){if(wa(e),t=td(t),wa(r),typeof e=="function"&&t==="prototype"&&"value"in r&&Fn in r&&!r[Fn]){var i=Vy(e,t);i&&i[Fn]&&(e[t]=r.value,r={configurable:Nn in r?r[Nn]:i[Nn],enumerable:_n in r?r[_n]:i[_n],writable:!1})}return Vn(e,t,r)}:Vn:function(e,t,r){if(wa(e),t=td(t),wa(r),Dy)try{return Vn(e,t,r)}catch(i){}if("get"in r||"set"in r)throw new Oy("Accessors not supported");return"value"in r&&(e[t]=r.value),e}});var zr=m((UL,id)=>{"use strict";id.exports=function(a,e){return{enumerable:!(a&1),configurable:!(a&2),writable:!(a&4),value:e}}});var nr=m((HL,ad)=>{"use strict";var _y=Ae(),Ny=Lt(),Fy=zr();ad.exports=_y?function(a,e,t){return Ny.f(a,e,Fy(1,t))}:function(a,e,t){return a[e]=t,a}});var ka=m((jL,nd)=>{"use strict";var qy=Cn(),Uy=Dn(),sd=qy("keys");nd.exports=function(a){return sd[a]||(sd[a]=Uy(a))}});var Ra=m((GL,od)=>{"use strict";od.exports={}});var jn=m((WL,ld)=>{"use strict";var Hy=sl(),cd=Y(),jy=Pe(),Gy=nr(),qn=_e(),Un=Yr(),Wy=ka(),Yy=Ra(),ud="Object already initialized",Hn=cd.TypeError,Qy=cd.WeakMap,$a,Kr,La,zy=function(a){return La(a)?Kr(a):$a(a,{})},Ky=function(a){return function(e){var t;if(!jy(e)||(t=Kr(e)).type!==a)throw new Hn("Incompatible receiver, "+a+" required");return t}};Hy||Un.state?(Ne=Un.state||(Un.state=new Qy),Ne.get=Ne.get,Ne.has=Ne.has,Ne.set=Ne.set,$a=function(a,e){if(Ne.has(a))throw new Hn(ud);return e.facade=a,Ne.set(a,e),e},Kr=function(a){return Ne.get(a)||{}},La=function(a){return Ne.has(a)}):(Mt=Wy("state"),Yy[Mt]=!0,$a=function(a,e){if(qn(a,Mt))throw new Hn(ud);return e.facade=a,Gy(a,Mt,e),e},Kr=function(a){return qn(a,Mt)?a[Mt]:{}},La=function(a){return qn(a,Mt)});var Ne,Mt;ld.exports={set:$a,get:Kr,has:La,enforce:zy,getterFor:Ky}});var Gn=m((YL,fd)=>{"use strict";var Jy=qr(),hd=Function.prototype,dd=hd.apply,pd=hd.call;fd.exports=typeof Reflect=="object"&&Reflect.apply||(Jy?pd.bind(dd):function(){return pd.apply(dd,arguments)})});var Wn=m((QL,md)=>{"use strict";var Xy=tr(),Zy=ce();md.exports=function(a){if(Xy(a)==="Function")return Zy(a)}});var vd=m(Sd=>{"use strict";var bd={}.propertyIsEnumerable,gd=Object.getOwnPropertyDescriptor,eT=gd&&!bd.call({1:2},1);Sd.f=eT?function(e){var t=gd(this,e);return!!t&&t.enumerable}:bd});var Id=m(Td=>{"use strict";var tT=Ae(),rT=ye(),iT=vd(),aT=zr(),sT=ir(),nT=On(),oT=_e(),uT=Tn(),yd=Object.getOwnPropertyDescriptor;Td.f=tT?yd:function(e,t){if(e=sT(e),t=nT(t),uT)try{return yd(e,t)}catch(r){}if(oT(e,t))return aT(!rT(iT.f,e,t),e[t])}});var Yn=m((JL,Ed)=>{"use strict";var cT=ve(),lT=W(),dT=/#|\.prototype\./,Jr=function(a,e){var t=hT[pT(a)];return t===mT?!0:t===fT?!1:lT(e)?cT(e):!!e},pT=Jr.normalize=function(a){return String(a).replace(dT,".").toLowerCase()},hT=Jr.data={},fT=Jr.NATIVE="N",mT=Jr.POLYFILL="P";Ed.exports=Jr});var Xr=m((XL,Pd)=>{"use strict";var xd=Wn(),bT=Qe(),gT=qr(),ST=xd(xd.bind);Pd.exports=function(a,e){return bT(a),e===void 0?a:gT?ST(a,e):function(){return a.apply(e,arguments)}}});var we=m((ZL,wd)=>{"use strict";var Zr=Y(),vT=Gn(),yT=Wn(),TT=W(),IT=Id().f,ET=Yn(),or=Pa(),xT=Xr(),ur=nr(),Ad=_e();Yr();var PT=function(a){var e=function(t,r,i){if(this instanceof e){switch(arguments.length){case 0:return new a;case 1:return new a(t);case 2:return new a(t,r)}return new a(t,r,i)}return vT(a,this,arguments)};return e.prototype=a.prototype,e};wd.exports=function(a,e){var t=a.target,r=a.global,i=a.stat,s=a.proto,n=r?Zr:i?Zr[t]:Zr[t]&&Zr[t].prototype,o=r?or:or[t]||ur(or,t,{})[t],u=o.prototype,c,l,d,p,h,f,b,g,y;for(p in e)c=ET(r?p:t+(i?".":"#")+p,a.forced),l=!c&&n&&Ad(n,p),f=o[p],l&&(a.dontCallGetSet?(y=IT(n,p),b=y&&y.value):b=n[p]),h=l&&b?b:e[p],!(!c&&!s&&typeof f==typeof h)&&(a.bind&&l?g=xT(h,Zr):a.wrap&&l?g=PT(h):s&&TT(h)?g=yT(h):g=h,(a.sham||h&&h.sham||f&&f.sham)&&ur(g,"sham",!0),ur(o,p,g),s&&(d=t+"Prototype",Ad(or,d)||ur(or,d,{}),ur(or[d],p,h),a.real&&u&&(c||!u[p])&&ur(u,p,h)))}});var $d=m((eM,Rd)=>{"use strict";var Qn=Ae(),AT=_e(),kd=Function.prototype,wT=Qn&&Object.getOwnPropertyDescriptor,zn=AT(kd,"name"),kT=zn&&function(){}.name==="something",RT=zn&&(!Qn||Qn&&wT(kd,"name").configurable);Rd.exports={EXISTS:zn,PROPER:kT,CONFIGURABLE:RT}});var Md=m((tM,Ld)=>{"use strict";var $T=Math.ceil,LT=Math.floor;Ld.exports=Math.trunc||function(e){var t=+e;return(t>0?LT:$T)(t)}});var Ma=m((rM,Cd)=>{"use strict";var MT=Md();Cd.exports=function(a){var e=+a;return e!==e||e===0?0:MT(e)}});var Bd=m((iM,Dd)=>{"use strict";var CT=Ma(),DT=Math.max,BT=Math.min;Dd.exports=function(a,e){var t=CT(a);return t<0?DT(t+e,0):BT(t,e)}});var Vd=m((aM,Od)=>{"use strict";var OT=Ma(),VT=Math.min;Od.exports=function(a){var e=OT(a);return e>0?VT(e,9007199254740991):0}});var Ca=m((sM,_d)=>{"use strict";var _T=Vd();_d.exports=function(a){return _T(a.length)}});var qd=m((nM,Fd)=>{"use strict";var NT=ir(),FT=Bd(),qT=Ca(),Nd=function(a){return function(e,t,r){var i=NT(e),s=qT(i);if(s===0)return!a&&-1;var n=FT(r,s),o;if(a&&t!==t){for(;s>n;)if(o=i[n++],o!==o)return!0}else for(;s>n;n++)if((a||n in i)&&i[n]===t)return a||n||0;return!a&&-1}};Fd.exports={includes:Nd(!0),indexOf:Nd(!1)}});var jd=m((oM,Hd)=>{"use strict";var UT=ce(),Kn=_e(),HT=ir(),jT=qd().indexOf,GT=Ra(),Ud=UT([].push);Hd.exports=function(a,e){var t=HT(a),r=0,i=[],s;for(s in t)!Kn(GT,s)&&Kn(t,s)&&Ud(i,s);for(;e.length>r;)Kn(t,s=e[r++])&&(~jT(i,s)||Ud(i,s));return i}});var Jn=m((uM,Gd)=>{"use strict";Gd.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var Yd=m((cM,Wd)=>{"use strict";var WT=jd(),YT=Jn();Wd.exports=Object.keys||function(e){return WT(e,YT)}});var zd=m(Qd=>{"use strict";var QT=Ae(),zT=In(),KT=Lt(),JT=je(),XT=ir(),ZT=Yd();Qd.f=QT&&!zT?Object.defineProperties:function(e,t){JT(e);for(var r=XT(t),i=ZT(t),s=i.length,n=0,o;s>n;)KT.f(e,o=i[n++],r[o]);return e}});var Xn=m((dM,Kd)=>{"use strict";var eI=Ye();Kd.exports=eI("document","documentElement")});var ro=m((pM,ip)=>{"use strict";var tI=je(),rI=zd(),Jd=Jn(),iI=Ra(),aI=Xn(),sI=Ea(),nI=ka(),Xd=">",Zd="<",eo="prototype",to="script",tp=nI("IE_PROTO"),Zn=function(){},rp=function(a){return Zd+to+Xd+a+Zd+"/"+to+Xd},ep=function(a){a.write(rp("")),a.close();var e=a.parentWindow.Object;return a=null,e},oI=function(){var a=sI("iframe"),e="java"+to+":",t;return a.style.display="none",aI.appendChild(a),a.src=String(e),t=a.contentWindow.document,t.open(),t.write(rp("document.F=Object")),t.close(),t.F},Da,Ba=function(){try{Da=new ActiveXObject("htmlfile")}catch(e){}Ba=typeof document!="undefined"?document.domain&&Da?ep(Da):oI():ep(Da);for(var a=Jd.length;a--;)delete Ba[eo][Jd[a]];return Ba()};iI[tp]=!0;ip.exports=Object.create||function(e,t){var r;return e!==null?(Zn[eo]=tI(e),r=new Zn,Zn[eo]=null,r[tp]=e):r=Ba(),t===void 0?r:rI.f(r,t)}});var sp=m((hM,ap)=>{"use strict";var uI=ve();ap.exports=!uI(function(){function a(){}return a.prototype.constructor=null,Object.getPrototypeOf(new a)!==a.prototype})});var ao=m((fM,op)=>{"use strict";var cI=_e(),lI=W(),dI=Qr(),pI=ka(),hI=sp(),np=pI("IE_PROTO"),io=Object,fI=io.prototype;op.exports=hI?io.getPrototypeOf:function(a){var e=dI(a);if(cI(e,np))return e[np];var t=e.constructor;return lI(t)&&e instanceof t?t.prototype:e instanceof io?fI:null}});var cr=m((mM,up)=>{"use strict";var mI=nr();up.exports=function(a,e,t,r){return r&&r.enumerable?a[e]=t:mI(a,e,t),a}});var uo=m((bM,dp)=>{"use strict";var bI=ve(),gI=W(),SI=Pe(),vI=ro(),cp=ao(),yI=cr(),TI=te(),II=Ve(),oo=TI("iterator"),lp=!1,ze,so,no;[].keys&&(no=[].keys(),"next"in no?(so=cp(cp(no)),so!==Object.prototype&&(ze=so)):lp=!0);var EI=!SI(ze)||bI(function(){var a={};return ze[oo].call(a)!==a});EI?ze={}:II&&(ze=vI(ze));gI(ze[oo])||yI(ze,oo,function(){return this});dp.exports={IteratorPrototype:ze,BUGGY_SAFARI_ITERATORS:lp}});var Oa=m((gM,hp)=>{"use strict";var xI=te(),PI=xI("toStringTag"),pp={};pp[PI]="z";hp.exports=String(pp)==="[object z]"});var ei=m((SM,fp)=>{"use strict";var AI=Oa(),wI=W(),Va=tr(),kI=te(),RI=kI("toStringTag"),$I=Object,LI=Va(function(){return arguments}())==="Arguments",MI=function(a,e){try{return a[e]}catch(t){}};fp.exports=AI?Va:function(a){var e,t,r;return a===void 0?"Undefined":a===null?"Null":typeof(t=MI(e=$I(a),RI))=="string"?t:LI?Va(e):(r=Va(e))==="Object"&&wI(e.callee)?"Arguments":r}});var bp=m((vM,mp)=>{"use strict";var CI=Oa(),DI=ei();mp.exports=CI?{}.toString:function(){return"[object "+DI(this)+"]"}});var ti=m((yM,Sp)=>{"use strict";var BI=Oa(),OI=Lt().f,VI=nr(),_I=_e(),NI=bp(),FI=te(),gp=FI("toStringTag");Sp.exports=function(a,e,t,r){var i=t?a:a&&a.prototype;i&&(_I(i,gp)||OI(i,gp,{configurable:!0,value:e}),r&&!BI&&VI(i,"toString",NI))}});var yp=m((TM,vp)=>{"use strict";var qI=uo().IteratorPrototype,UI=ro(),HI=zr(),jI=ti(),GI=$t(),WI=function(){return this};vp.exports=function(a,e,t,r){var i=e+" Iterator";return a.prototype=UI(qI,{next:HI(+!r,t)}),jI(a,i,!1,!0),GI[i]=WI,a}});var Ip=m((IM,Tp)=>{"use strict";var YI=ce(),QI=Qe();Tp.exports=function(a,e,t){try{return YI(QI(Object.getOwnPropertyDescriptor(a,e)[t]))}catch(r){}}});var xp=m((EM,Ep)=>{"use strict";var zI=Pe();Ep.exports=function(a){return zI(a)||a===null}});var Ap=m((xM,Pp)=>{"use strict";var KI=xp(),JI=String,XI=TypeError;Pp.exports=function(a){if(KI(a))return a;throw new XI("Can't set "+JI(a)+" as a prototype")}});var co=m((PM,wp)=>{"use strict";var ZI=Ip(),eE=Pe(),tE=Ur(),rE=Ap();wp.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var a=!1,e={},t;try{t=ZI(Object.prototype,"__proto__","set"),t(e,[]),a=e instanceof Array}catch(r){}return function(i,s){return tE(i),rE(s),eE(i)&&(a?t(i,s):i.__proto__=s),i}}():void 0)});var _p=m((AM,Vp)=>{"use strict";var iE=we(),aE=ye(),_a=Ve(),Bp=$d(),sE=W(),nE=yp(),kp=ao(),Rp=co(),oE=ti(),uE=nr(),lo=cr(),cE=te(),$p=$t(),Op=uo(),lE=Bp.PROPER,dE=Bp.CONFIGURABLE,Lp=Op.IteratorPrototype,Na=Op.BUGGY_SAFARI_ITERATORS,ri=cE("iterator"),Mp="keys",ii="values",Cp="entries",Dp=function(){return this};Vp.exports=function(a,e,t,r,i,s,n){nE(t,e,r);var o=function(y){if(y===i&&p)return p;if(!Na&&y&&y in l)return l[y];switch(y){case Mp:return function(){return new t(this,y)};case ii:return function(){return new t(this,y)};case Cp:return function(){return new t(this,y)}}return function(){return new t(this)}},u=e+" Iterator",c=!1,l=a.prototype,d=l[ri]||l["@@iterator"]||i&&l[i],p=!Na&&d||o(i),h=e==="Array"&&l.entries||d,f,b,g;if(h&&(f=kp(h.call(new a)),f!==Object.prototype&&f.next&&(!_a&&kp(f)!==Lp&&(Rp?Rp(f,Lp):sE(f[ri])||lo(f,ri,Dp)),oE(f,u,!0,!0),_a&&($p[u]=Dp))),lE&&i===ii&&d&&d.name!==ii&&(!_a&&dE?uE(l,"name",ii):(c=!0,p=function(){return aE(d,this)})),i)if(b={values:o(ii),keys:s?p:o(Mp),entries:o(Cp)},n)for(g in b)(Na||c||!(g in l))&&lo(l,g,b[g]);else iE({target:e,proto:!0,forced:Na||c},b);return(!_a||n)&&l[ri]!==p&&lo(l,ri,p,{name:i}),$p[e]=p,b}});var Fp=m((wM,Np)=>{"use strict";Np.exports=function(a,e){return{value:a,done:e}}});var ho=m((kM,Gp)=>{"use strict";var pE=ir(),po=gn(),qp=$t(),Hp=jn(),hE=Lt().f,fE=_p(),Fa=Fp(),mE=Ve(),bE=Ae(),jp="Array Iterator",gE=Hp.set,SE=Hp.getterFor(jp);Gp.exports=fE(Array,"Array",function(a,e){gE(this,{type:jp,target:pE(a),index:0,kind:e})},function(){var a=SE(this),e=a.target,t=a.index++;if(!e||t>=e.length)return a.target=void 0,Fa(void 0,!0);switch(a.kind){case"keys":return Fa(t,!1);case"values":return Fa(e[t],!1)}return Fa([t,e[t]],!1)},"values");var Up=qp.Arguments=qp.Array;po("keys");po("values");po("entries");if(!mE&&bE&&Up.name!=="values")try{hE(Up,"name",{value:"values"})}catch(a){}});var Yp=m((RM,Wp)=>{"use strict";var vE=te(),yE=$t(),TE=vE("iterator"),IE=Array.prototype;Wp.exports=function(a){return a!==void 0&&(yE.Array===a||IE[TE]===a)}});var fo=m(($M,zp)=>{"use strict";var EE=ei(),Qp=Wr(),xE=rr(),PE=$t(),AE=te(),wE=AE("iterator");zp.exports=function(a){if(!xE(a))return Qp(a,wE)||Qp(a,"@@iterator")||PE[EE(a)]}});var Jp=m((LM,Kp)=>{"use strict";var kE=ye(),RE=Qe(),$E=je(),LE=Gr(),ME=fo(),CE=TypeError;Kp.exports=function(a,e){var t=arguments.length<2?ME(a):e;if(RE(t))return $E(kE(t,a));throw new CE(LE(a)+" is not iterable")}});var eh=m((MM,Zp)=>{"use strict";var DE=ye(),Xp=je(),BE=Wr();Zp.exports=function(a,e,t){var r,i;Xp(a);try{if(r=BE(a,"return"),!r){if(e==="throw")throw t;return t}r=DE(r,a)}catch(s){i=!0,r=s}if(e==="throw")throw t;if(i)throw r;return Xp(r),t}});var Ua=m((CM,ah)=>{"use strict";var OE=Xr(),VE=ye(),_E=je(),NE=Gr(),FE=Yp(),qE=Ca(),th=jr(),UE=Jp(),HE=fo(),rh=eh(),jE=TypeError,qa=function(a,e){this.stopped=a,this.result=e},ih=qa.prototype;ah.exports=function(a,e,t){var r=t&&t.that,i=!!(t&&t.AS_ENTRIES),s=!!(t&&t.IS_RECORD),n=!!(t&&t.IS_ITERATOR),o=!!(t&&t.INTERRUPTED),u=OE(e,r),c,l,d,p,h,f,b,g=function(I){return c&&rh(c,"normal",I),new qa(!0,I)},y=function(I){return i?(_E(I),o?u(I[0],I[1],g):u(I[0],I[1])):o?u(I,g):u(I)};if(s)c=a.iterator;else if(n)c=a;else{if(l=HE(a),!l)throw new jE(NE(a)+" is not iterable");if(FE(l)){for(d=0,p=qE(a);p>d;d++)if(h=y(a[d]),h&&th(ih,h))return h;return new qa(!1)}c=UE(a,l)}for(f=s?a.next:c.next;!(b=VE(f,c)).done;){try{h=y(b.value)}catch(I){rh(c,"throw",I)}if(typeof h=="object"&&h&&th(ih,h))return h}return new qa(!1)}});var nh=m((DM,sh)=>{"use strict";var GE=Ae(),WE=Lt(),YE=zr();sh.exports=function(a,e,t){GE?WE.f(a,e,YE(0,t)):a[e]=t}});var oh=m(()=>{"use strict";var QE=we(),zE=Ua(),KE=nh();QE({target:"Object",stat:!0},{fromEntries:function(e){var t={};return zE(e,function(r,i){KE(t,r,i)},{AS_ENTRIES:!0}),t}})});var ch=m((VM,uh)=>{"use strict";ho();oh();var JE=Pa();uh.exports=JE.Object.fromEntries});var dh=m((_M,lh)=>{"use strict";lh.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 hh=m(()=>{"use strict";ho();var XE=dh(),ZE=Y(),ex=ti(),ph=$t();for(Ha in XE)ex(ZE[Ha],Ha),ph[Ha]=ph.Array;var Ha});var mh=m((qM,fh)=>{"use strict";var tx=ch();hh();fh.exports=tx});var mo=m((UM,bh)=>{"use strict";var rx=mh();bh.exports=rx});var gh=m(()=>{"use strict"});var bo=m((GM,Sh)=>{"use strict";var ai=Y(),ix=ar(),ax=tr(),ja=function(a){return ix.slice(0,a.length)===a};Sh.exports=function(){return ja("Bun/")?"BUN":ja("Cloudflare-Workers")?"CLOUDFLARE":ja("Deno/")?"DENO":ja("Node.js/")?"NODE":ai.Bun&&typeof Bun.version=="string"?"BUN":ai.Deno&&typeof Deno.version=="object"?"DENO":ax(ai.process)==="process"?"NODE":ai.window&&ai.document?"BROWSER":"REST"}()});var Ga=m((WM,vh)=>{"use strict";var sx=bo();vh.exports=sx==="NODE"});var Th=m((YM,yh)=>{"use strict";var nx=Lt();yh.exports=function(a,e,t){return nx.f(a,e,t)}});var xh=m((QM,Eh)=>{"use strict";var ox=Ye(),ux=Th(),cx=te(),lx=Ae(),Ih=cx("species");Eh.exports=function(a){var e=ox(a);lx&&e&&!e[Ih]&&ux(e,Ih,{configurable:!0,get:function(){return this}})}});var Ah=m((zM,Ph)=>{"use strict";var dx=jr(),px=TypeError;Ph.exports=function(a,e){if(dx(e,a))return a;throw new px("Incorrect invocation")}});var So=m((KM,wh)=>{"use strict";var hx=ce(),fx=W(),go=Yr(),mx=hx(Function.toString);fx(go.inspectSource)||(go.inspectSource=function(a){return mx(a)});wh.exports=go.inspectSource});var Ch=m((JM,Mh)=>{"use strict";var bx=ce(),gx=ve(),kh=W(),Sx=ei(),vx=Ye(),yx=So(),Rh=function(){},$h=vx("Reflect","construct"),vo=/^\s*(?:class|function)\b/,Tx=bx(vo.exec),Ix=!vo.test(Rh),si=function(e){if(!kh(e))return!1;try{return $h(Rh,[],e),!0}catch(t){return!1}},Lh=function(e){if(!kh(e))return!1;switch(Sx(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return Ix||!!Tx(vo,yx(e))}catch(t){return!0}};Lh.sham=!0;Mh.exports=!$h||gx(function(){var a;return si(si.call)||!si(Object)||!si(function(){a=!0})||a})?Lh:si});var Bh=m((XM,Dh)=>{"use strict";var Ex=Ch(),xx=Gr(),Px=TypeError;Dh.exports=function(a){if(Ex(a))return a;throw new Px(xx(a)+" is not a constructor")}});var yo=m((ZM,Vh)=>{"use strict";var Oh=je(),Ax=Bh(),wx=rr(),kx=te(),Rx=kx("species");Vh.exports=function(a,e){var t=Oh(a).constructor,r;return t===void 0||wx(r=Oh(t)[Rx])?e:Ax(r)}});var Nh=m((eC,_h)=>{"use strict";var $x=ce();_h.exports=$x([].slice)});var qh=m((tC,Fh)=>{"use strict";var Lx=TypeError;Fh.exports=function(a,e){if(a<e)throw new Lx("Not enough arguments");return a}});var To=m((rC,Uh)=>{"use strict";var Mx=ar();Uh.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(Mx)});var $o=m((iC,Jh)=>{"use strict";var Te=Y(),Cx=Gn(),Dx=Xr(),Hh=W(),Bx=_e(),Kh=ve(),jh=Xn(),Ox=Nh(),Gh=Ea(),Vx=qh(),_x=To(),Nx=Ga(),wo=Te.setImmediate,ko=Te.clearImmediate,Fx=Te.process,Io=Te.Dispatch,qx=Te.Function,Wh=Te.MessageChannel,Ux=Te.String,Eo=0,ni={},Yh="onreadystatechange",oi,Ct,xo,Po;Kh(function(){oi=Te.location});var Ro=function(a){if(Bx(ni,a)){var e=ni[a];delete ni[a],e()}},Ao=function(a){return function(){Ro(a)}},Qh=function(a){Ro(a.data)},zh=function(a){Te.postMessage(Ux(a),oi.protocol+"//"+oi.host)};(!wo||!ko)&&(wo=function(e){Vx(arguments.length,1);var t=Hh(e)?e:qx(e),r=Ox(arguments,1);return ni[++Eo]=function(){Cx(t,void 0,r)},Ct(Eo),Eo},ko=function(e){delete ni[e]},Nx?Ct=function(a){Fx.nextTick(Ao(a))}:Io&&Io.now?Ct=function(a){Io.now(Ao(a))}:Wh&&!_x?(xo=new Wh,Po=xo.port2,xo.port1.onmessage=Qh,Ct=Dx(Po.postMessage,Po)):Te.addEventListener&&Hh(Te.postMessage)&&!Te.importScripts&&oi&&oi.protocol!=="file:"&&!Kh(zh)?(Ct=zh,Te.addEventListener("message",Qh,!1)):Yh in Gh("script")?Ct=function(a){jh.appendChild(Gh("script"))[Yh]=function(){jh.removeChild(this),Ro(a)}}:Ct=function(a){setTimeout(Ao(a),0)});Jh.exports={set:wo,clear:ko}});var ef=m((aC,Zh)=>{"use strict";var Xh=Y(),Hx=Ae(),jx=Object.getOwnPropertyDescriptor;Zh.exports=function(a){if(!Hx)return Xh[a];var e=jx(Xh,a);return e&&e.value}});var Lo=m((sC,rf)=>{"use strict";var tf=function(){this.head=null,this.tail=null};tf.prototype={add:function(a){var e={item:a,next:null},t=this.tail;t?t.next=e:this.head=e,this.tail=e},get:function(){var a=this.head;if(a){var e=this.head=a.next;return e===null&&(this.tail=null),a.item}}};rf.exports=tf});var sf=m((nC,af)=>{"use strict";var Gx=ar();af.exports=/ipad|iphone|ipod/i.test(Gx)&&typeof Pebble!="undefined"});var of=m((oC,nf)=>{"use strict";var Wx=ar();nf.exports=/web0s(?!.*chrome)/i.test(Wx)});var ff=m((uC,hf)=>{"use strict";var dr=Y(),Yx=ef(),uf=Xr(),Mo=$o().set,Qx=Lo(),zx=To(),Kx=sf(),Jx=of(),Co=Ga(),cf=dr.MutationObserver||dr.WebKitMutationObserver,lf=dr.document,df=dr.process,Wa=dr.Promise,Oo=Yx("queueMicrotask"),lr,Do,Bo,Ya,pf;Oo||(ui=new Qx,ci=function(){var a,e;for(Co&&(a=df.domain)&&a.exit();e=ui.get();)try{e()}catch(t){throw ui.head&&lr(),t}a&&a.enter()},!zx&&!Co&&!Jx&&cf&&lf?(Do=!0,Bo=lf.createTextNode(""),new cf(ci).observe(Bo,{characterData:!0}),lr=function(){Bo.data=Do=!Do}):!Kx&&Wa&&Wa.resolve?(Ya=Wa.resolve(void 0),Ya.constructor=Wa,pf=uf(Ya.then,Ya),lr=function(){pf(ci)}):Co?lr=function(){df.nextTick(ci)}:(Mo=uf(Mo,dr),lr=function(){Mo(ci)}),Oo=function(a){ui.head||lr(),ui.add(a)});var ui,ci;hf.exports=Oo});var bf=m((cC,mf)=>{"use strict";mf.exports=function(a,e){try{arguments.length===1?console.error(a):console.error(a,e)}catch(t){}}});var Qa=m((lC,gf)=>{"use strict";gf.exports=function(a){try{return{error:!1,value:a()}}catch(e){return{error:!0,value:e}}}});var Dt=m((dC,Sf)=>{"use strict";var Xx=Y();Sf.exports=Xx.Promise});var pr=m((pC,If)=>{"use strict";var Zx=Y(),li=Dt(),eP=W(),tP=Yn(),rP=So(),iP=te(),vf=bo(),aP=Ve(),Vo=An(),yf=li&&li.prototype,sP=iP("species"),_o=!1,Tf=eP(Zx.PromiseRejectionEvent),nP=tP("Promise",function(){var a=rP(li),e=a!==String(li);if(!e&&Vo===66||aP&&!(yf.catch&&yf.finally))return!0;if(!Vo||Vo<51||!/native code/.test(a)){var t=new li(function(s){s(1)}),r=function(s){s(function(){},function(){})},i=t.constructor={};if(i[sP]=r,_o=t.then(function(){})instanceof r,!_o)return!0}return!e&&(vf==="BROWSER"||vf==="DENO")&&!Tf});If.exports={CONSTRUCTOR:nP,REJECTION_EVENT:Tf,SUBCLASSING:_o}});var hr=m((hC,xf)=>{"use strict";var Ef=Qe(),oP=TypeError,uP=function(a){var e,t;this.promise=new a(function(r,i){if(e!==void 0||t!==void 0)throw new oP("Bad Promise constructor");e=r,t=i}),this.resolve=Ef(e),this.reject=Ef(t)};xf.exports.f=function(a){return new uP(a)}});var Hf=m(()=>{"use strict";var cP=we(),lP=Ve(),Xa=Ga(),dt=Y(),gr=ye(),Pf=cr(),Af=co(),dP=ti(),pP=xh(),hP=Qe(),Ja=W(),fP=Pe(),mP=Ah(),bP=yo(),Lf=$o().set,Ho=ff(),gP=bf(),SP=Qa(),vP=Lo(),Mf=jn(),Za=Dt(),jo=pr(),Cf=hr(),es="Promise",Df=jo.CONSTRUCTOR,yP=jo.REJECTION_EVENT,TP=jo.SUBCLASSING,No=Mf.getterFor(es),IP=Mf.set,fr=Za&&Za.prototype,Bt=Za,za=fr,Bf=dt.TypeError,Fo=dt.document,Go=dt.process,qo=Cf.f,EP=qo,xP=!!(Fo&&Fo.createEvent&&dt.dispatchEvent),Of="unhandledrejection",PP="rejectionhandled",wf=0,Vf=1,AP=2,Wo=1,_f=2,Ka,kf,wP,Rf,Nf=function(a){var e;return fP(a)&&Ja(e=a.then)?e:!1},Ff=function(a,e){var t=e.value,r=e.state===Vf,i=r?a.ok:a.fail,s=a.resolve,n=a.reject,o=a.domain,u,c,l;try{i?(r||(e.rejection===_f&&RP(e),e.rejection=Wo),i===!0?u=t:(o&&o.enter(),u=i(t),o&&(o.exit(),l=!0)),u===a.promise?n(new Bf("Promise-chain cycle")):(c=Nf(u))?gr(c,u,s,n):s(u)):n(t)}catch(d){o&&!l&&o.exit(),n(d)}},qf=function(a,e){a.notified||(a.notified=!0,Ho(function(){for(var t=a.reactions,r;r=t.get();)Ff(r,a);a.notified=!1,e&&!a.rejection&&kP(a)}))},Uf=function(a,e,t){var r,i;xP?(r=Fo.createEvent("Event"),r.promise=e,r.reason=t,r.initEvent(a,!1,!0),dt.dispatchEvent(r)):r={promise:e,reason:t},!yP&&(i=dt["on"+a])?i(r):a===Of&&gP("Unhandled promise rejection",t)},kP=function(a){gr(Lf,dt,function(){var e=a.facade,t=a.value,r=$f(a),i;if(r&&(i=SP(function(){Xa?Go.emit("unhandledRejection",t,e):Uf(Of,e,t)}),a.rejection=Xa||$f(a)?_f:Wo,i.error))throw i.value})},$f=function(a){return a.rejection!==Wo&&!a.parent},RP=function(a){gr(Lf,dt,function(){var e=a.facade;Xa?Go.emit("rejectionHandled",e):Uf(PP,e,a.value)})},mr=function(a,e,t){return function(r){a(e,r,t)}},br=function(a,e,t){a.done||(a.done=!0,t&&(a=t),a.value=e,a.state=AP,qf(a,!0))},Uo=function(a,e,t){if(!a.done){a.done=!0,t&&(a=t);try{if(a.facade===e)throw new Bf("Promise can't be resolved itself");var r=Nf(e);r?Ho(function(){var i={done:!1};try{gr(r,e,mr(Uo,i,a),mr(br,i,a))}catch(s){br(i,s,a)}}):(a.value=e,a.state=Vf,qf(a,!1))}catch(i){br({done:!1},i,a)}}};if(Df&&(Bt=function(e){mP(this,za),hP(e),gr(Ka,this);var t=No(this);try{e(mr(Uo,t),mr(br,t))}catch(r){br(t,r)}},za=Bt.prototype,Ka=function(e){IP(this,{type:es,done:!1,notified:!1,parent:!1,reactions:new vP,rejection:!1,state:wf,value:void 0})},Ka.prototype=Pf(za,"then",function(e,t){var r=No(this),i=qo(bP(this,Bt));return r.parent=!0,i.ok=Ja(e)?e:!0,i.fail=Ja(t)&&t,i.domain=Xa?Go.domain:void 0,r.state===wf?r.reactions.add(i):Ho(function(){Ff(i,r)}),i.promise}),kf=function(){var a=new Ka,e=No(a);this.promise=a,this.resolve=mr(Uo,e),this.reject=mr(br,e)},Cf.f=qo=function(a){return a===Bt||a===wP?new kf(a):EP(a)},!lP&&Ja(Za)&&fr!==Object.prototype)){Rf=fr.then,TP||Pf(fr,"then",function(e,t){var r=this;return new Bt(function(i,s){gr(Rf,r,i,s)}).then(e,t)},{unsafe:!0});try{delete fr.constructor}catch(a){}Af&&Af(fr,za)}cP({global:!0,constructor:!0,wrap:!0,forced:Df},{Promise:Bt});dP(Bt,es,!1,!0);pP(es)});var Qf=m((bC,Yf)=>{"use strict";var $P=te(),Gf=$P("iterator"),Wf=!1;try{jf=0,Yo={next:function(){return{done:!!jf++}},return:function(){Wf=!0}},Yo[Gf]=function(){return this},Array.from(Yo,function(){throw 2})}catch(a){}var jf,Yo;Yf.exports=function(a,e){try{if(!e&&!Wf)return!1}catch(i){return!1}var t=!1;try{var r={};r[Gf]=function(){return{next:function(){return{done:t=!0}}}},a(r)}catch(i){}return t}});var Qo=m((gC,zf)=>{"use strict";var LP=Dt(),MP=Qf(),CP=pr().CONSTRUCTOR;zf.exports=CP||!MP(function(a){LP.all(a).then(void 0,function(){})})});var Kf=m(()=>{"use strict";var DP=we(),BP=ye(),OP=Qe(),VP=hr(),_P=Qa(),NP=Ua(),FP=Qo();DP({target:"Promise",stat:!0,forced:FP},{all:function(e){var t=this,r=VP.f(t),i=r.resolve,s=r.reject,n=_P(function(){var o=OP(t.resolve),u=[],c=0,l=1;NP(e,function(d){var p=c++,h=!1;l++,BP(o,t,d).then(function(f){h||(h=!0,u[p]=f,--l||i(u))},s)}),--l||i(u)});return n.error&&s(n.value),r.promise}})});var Xf=m(()=>{"use strict";var qP=we(),UP=Ve(),HP=pr().CONSTRUCTOR,Ko=Dt(),jP=Ye(),GP=W(),WP=cr(),Jf=Ko&&Ko.prototype;qP({target:"Promise",proto:!0,forced:HP,real:!0},{catch:function(a){return this.then(void 0,a)}});!UP&&GP(Ko)&&(zo=jP("Promise").prototype.catch,Jf.catch!==zo&&WP(Jf,"catch",zo,{unsafe:!0}));var zo});var Zf=m(()=>{"use strict";var YP=we(),QP=ye(),zP=Qe(),KP=hr(),JP=Qa(),XP=Ua(),ZP=Qo();YP({target:"Promise",stat:!0,forced:ZP},{race:function(e){var t=this,r=KP.f(t),i=r.reject,s=JP(function(){var n=zP(t.resolve);XP(e,function(o){QP(n,t,o).then(r.resolve,i)})});return s.error&&i(s.value),r.promise}})});var em=m(()=>{"use strict";var eA=we(),tA=hr(),rA=pr().CONSTRUCTOR;eA({target:"Promise",stat:!0,forced:rA},{reject:function(e){var t=tA.f(this),r=t.reject;return r(e),t.promise}})});var Jo=m((AC,tm)=>{"use strict";var iA=je(),aA=Pe(),sA=hr();tm.exports=function(a,e){if(iA(a),aA(e)&&e.constructor===a)return e;var t=sA.f(a),r=t.resolve;return r(e),t.promise}});var am=m(()=>{"use strict";var nA=we(),oA=Ye(),rm=Ve(),uA=Dt(),im=pr().CONSTRUCTOR,cA=Jo(),lA=oA("Promise"),dA=rm&&!im;nA({target:"Promise",stat:!0,forced:rm||im},{resolve:function(e){return cA(dA&&this===lA?uA:this,e)}})});var sm=m(()=>{"use strict";Hf();Kf();Xf();Zf();em();am()});var cm=m(()=>{"use strict";var pA=we(),hA=Ve(),ts=Dt(),fA=ve(),om=Ye(),um=W(),mA=yo(),nm=Jo(),bA=cr(),Zo=ts&&ts.prototype,gA=!!ts&&fA(function(){Zo.finally.call({then:function(){}},function(){})});pA({target:"Promise",proto:!0,real:!0,forced:gA},{finally:function(a){var e=mA(this,om("Promise")),t=um(a);return this.then(t?function(r){return nm(e,a()).then(function(){return r})}:a,t?function(r){return nm(e,a()).then(function(){throw r})}:a)}});!hA&&um(ts)&&(Xo=om("Promise").prototype.finally,Zo.finally!==Xo&&bA(Zo,"finally",Xo,{unsafe:!0}));var Xo});var rs=m((CC,lm)=>{"use strict";var SA=Ye();lm.exports=SA});var pm=m((DC,dm)=>{"use strict";gh();sm();cm();var vA=rs();dm.exports=vA("Promise","finally")});var fm=m((BC,hm)=>{"use strict";var yA=pm();hm.exports=yA});var is=m((OC,mm)=>{"use strict";var TA=fm();mm.exports=TA});var Fm=m(()=>{"use strict";var KA=we(),JA=Qr(),XA=Ca(),ZA=Ma(),ew=gn();KA({target:"Array",proto:!0},{at:function(e){var t=JA(this),r=XA(t),i=ZA(e),s=i>=0?i:r+i;return s<0||s>=r?void 0:t[s]}});ew("at")});var Um=m((GD,qm)=>{"use strict";Fm();var tw=rs();qm.exports=tw("Array","at")});var jm=m((WD,Hm)=>{"use strict";var rw=Um();Hm.exports=rw});var fi=m((YD,Gm)=>{"use strict";var iw=jm();Gm.exports=iw});var Kb=m(()=>{"use strict"});var Jb=m(()=>{"use strict"});var Zb=m((YV,Xb)=>{"use strict";var ck=Pe(),lk=tr(),dk=te(),pk=dk("match");Xb.exports=function(a){var e;return ck(a)&&((e=a[pk])!==void 0?!!e:lk(a)==="RegExp")}});var tg=m((QV,eg)=>{"use strict";var hk=ei(),fk=String;eg.exports=function(a){if(hk(a)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return fk(a)}});var ig=m((zV,rg)=>{"use strict";var mk=je();rg.exports=function(){var a=mk(this),e="";return a.hasIndices&&(e+="d"),a.global&&(e+="g"),a.ignoreCase&&(e+="i"),a.multiline&&(e+="m"),a.dotAll&&(e+="s"),a.unicode&&(e+="u"),a.unicodeSets&&(e+="v"),a.sticky&&(e+="y"),e}});var ng=m((KV,sg)=>{"use strict";var bk=ye(),gk=_e(),Sk=jr(),vk=ig(),ag=RegExp.prototype;sg.exports=function(a){var e=a.flags;return e===void 0&&!("flags"in ag)&&!gk(a,"flags")&&Sk(ag,a)?bk(vk,a):e}});var ug=m((JV,og)=>{"use strict";var Ru=ce(),yk=Qr(),Tk=Math.floor,wu=Ru("".charAt),Ik=Ru("".replace),ku=Ru("".slice),Ek=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,xk=/\$([$&'`]|\d{1,2})/g;og.exports=function(a,e,t,r,i,s){var n=t+a.length,o=r.length,u=xk;return i!==void 0&&(i=yk(i),u=Ek),Ik(s,u,function(c,l){var d;switch(wu(l,0)){case"$":return"$";case"&":return a;case"`":return ku(e,0,t);case"'":return ku(e,n);case"<":d=i[ku(l,1,-1)];break;default:var p=+l;if(p===0)return c;if(p>o){var h=Tk(p/10);return h===0?c:h<=o?r[h-1]===void 0?wu(l,1):r[h-1]+wu(l,1):c}d=r[p-1]}return d===void 0?"":d})}});var dg=m(()=>{"use strict";var Pk=we(),Ak=ye(),Lu=ce(),cg=Ur(),wk=W(),kk=rr(),Rk=Zb(),kr=tg(),$k=Wr(),Lk=ng(),Mk=ug(),Ck=te(),Dk=Ve(),Bk=Ck("replace"),Ok=TypeError,$u=Lu("".indexOf),Vk=Lu("".replace),lg=Lu("".slice),_k=Math.max;Pk({target:"String",proto:!0},{replaceAll:function(e,t){var r=cg(this),i,s,n,o,u,c,l,d,p,h,f=0,b="";if(!kk(e)){if(i=Rk(e),i&&(s=kr(cg(Lk(e))),!~$u(s,"g")))throw new Ok("`.replaceAll` does not allow non-global regexes");if(n=$k(e,Bk),n)return Ak(n,e,r,t);if(Dk&&i)return Vk(kr(r),e,t)}for(o=kr(r),u=kr(e),c=wk(t),c||(t=kr(t)),l=u.length,d=_k(1,l),p=$u(o,u);p!==-1;)h=c?kr(t(u,p,o)):Mk(u,o,p,[],void 0,t),b+=lg(o,f,p)+h,f=p+l,p=p+d>o.length?-1:$u(o,u,p+d);return f<o.length&&(b+=lg(o,f)),b}})});var hg=m((e_,pg)=>{"use strict";Kb();Jb();dg();var Nk=rs();pg.exports=Nk("String","replaceAll")});var mg=m((t_,fg)=>{"use strict";var Fk=hg();fg.exports=Fk});var gg=m((r_,bg)=>{"use strict";var qk=mg();bg.exports=qk});var Dc="2.0.111-dev.974e99b3.0";var ue=(i=>(i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused",i))(ue||{}),lt=(S=>(S.MPEG="MPEG",S.DASH="DASH",S.DASH_SEP="DASH_SEP",S.DASH_SEP_VK="DASH_SEP",S.DASH_WEBM="DASH_WEBM",S.DASH_WEBM_AV1="DASH_WEBM_AV1",S.DASH_STREAMS="DASH_STREAMS",S.DASH_WEBM_VK="DASH_WEBM",S.DASH_ONDEMAND="DASH_ONDEMAND",S.DASH_ONDEMAND_VK="DASH_ONDEMAND",S.DASH_LIVE="DASH_LIVE",S.DASH_LIVE_CMAF="DASH_LIVE_CMAF",S.DASH_LIVE_WEBM="DASH_LIVE_WEBM",S.HLS="HLS",S.HLS_ONDEMAND="HLS_ONDEMAND",S.HLS_JS="HLS",S.HLS_LIVE="HLS_LIVE",S.HLS_LIVE_CMAF="HLS_LIVE_CMAF",S.WEB_RTC_LIVE="WEB_RTC_LIVE",S))(lt||{});var ya=(i=>(i.NOT_AVAILABLE="NOT_AVAILABLE",i.AVAILABLE="AVAILABLE",i.CONNECTING="CONNECTING",i.CONNECTED="CONNECTED",i))(ya||{}),dn=(r=>(r.HTTP1="http1",r.HTTP2="http2",r.QUIC="quic",r))(dn||{});var pn=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(pn||{});import{assertNever as Fc,assertNonNullable as ov,isNonNullable as Ta,ValueSubject as hn,Subject as uv,Subscription as cv,merge as lv,observableFrom as dv,fromEvent as Oc,map as Vc,tap as _c,filterChanged as pv,isNullable as fn,ErrorCategory as Nc}from"@vkontakte/videoplayer-shared";var Bc=a=>new Promise((e,t)=>{let r=document.createElement("script");r.setAttribute("src",a),r.onload=()=>e,r.onerror=()=>t,document.body.appendChild(r)});var Ia=class{constructor(e){this.connection$=new hn(void 0);this.castState$=new hn("NOT_AVAILABLE");this.errorEvent$=new uv;this.realCastState$=new hn("NOT_AVAILABLE");this.subscription=new cv;var s;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastInitializer");let t="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${t}`}),e.isDisabled||!t)return;let r=Ta((s=window.chrome)==null?void 0:s.cast),i=!!window.__onGCastApiAvailable;r?this.initializeCastApi():(window.__onGCastApiAvailable=n=>{delete window.__onGCastApiAvailable,n&&this.initializeCastApi()},i||Bc("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:Nc.NETWORK,message:"Script loading failed!"})))}connect(){var e;(e=cast.framework.CastContext.getInstance())==null||e.requestSession()}disconnect(){var e,t;(t=(e=cast.framework.CastContext.getInstance())==null?void 0:e.getCurrentSession())==null||t.endSession(!0)}stopMedia(){return new Promise((e,t)=>{var r,i,s;(s=(i=(r=cast.framework.CastContext.getInstance())==null?void 0:r.getCurrentSession())==null?void 0:i.getMediaSession())==null||s.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){Ta(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();fn(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();fn(t)||e!==t.remotePlayer.isMuted&&t.remotePlayerController.muteOrUnmute()}destroy(){this.subscription.unsubscribe()}initListeners(){let e=new cast.framework.RemotePlayer,t=new cast.framework.RemotePlayerController(e),r=cast.framework.CastContext.getInstance();this.subscription.add(Oc(r,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(i=>{var s,n,o;switch(i.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=(o=(n=(s=r.getCurrentSession())==null?void 0:s.getMediaSession())==null?void 0:n.media)==null?void 0:o.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return Fc(i.sessionState)}})).add(lv(Oc(r,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(_c(i=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(i)}`})}),Vc(i=>i.castState)),dv([r.getCastState()])).pipe(pv(),Vc(hv),_c(i=>{this.log({message:`realCastState$: ${i}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(i=>{var o,u;let s=i==="CONNECTED",n=Ta(this.connection$.getValue());if(s&&!n){let c=r.getCurrentSession();ov(c);let l=c.getCastDevice(),d=(u=(o=c.getMediaSession())==null?void 0:o.media)==null?void 0:u.contentId;(fn(d)||d===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:c,castDevice:l}))}else!s&&n&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(i==="CONNECTED"?Ta(this.connection$.getValue())?"CONNECTED":"AVAILABLE":i)}))}initializeCastApi(){var i;let e,t,r;try{e=cast.framework.CastContext.getInstance(),t=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,r=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch(s){return}try{e.setOptions({receiverApplicationId:(i=this.params.receiverApplicationId)!=null?i:t,autoJoinPolicy:r}),this.initListeners()}catch(s){this.errorEvent$.next({id:"ChromecastInitializer",category:Nc.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:s})}}},hv=a=>{switch(a){case cast.framework.CastState.NO_DEVICES_AVAILABLE:return"NOT_AVAILABLE";case cast.framework.CastState.NOT_CONNECTED:return"AVAILABLE";case cast.framework.CastState.CONNECTING:return"CONNECTING";case cast.framework.CastState.CONNECTED:return"CONNECTED";default:return Fc(a)}};var mS=He(mo(),1);var Pm=He(is(),1);import{assertNever as bm}from"@vkontakte/videoplayer-shared";var ee=(a,e=0,t=0)=>{switch(t){case 0:return a.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case 1:{if(e===0)return a;let r=new URL(a);return r.searchParams.append("playback_shift",e.toFixed(0)),r.toString()}case 2:{let r=new URL(a);return!r.searchParams.get("offset_p")&&e===0?a:(r.searchParams.set("offset_p",e.toFixed(0)),r.toString())}default:bm(t)}return a},eu=(a,e)=>{var t;switch(e){case 0:return NaN;case 1:{let r=new URL(a);return Number(r.searchParams.get("playback_shift"))}case 2:{let r=new URL(a);return Number((t=r.searchParams.get("offset_p"))!=null?t:0)}default:bm(e)}};var E=(a,e,t=!1)=>{let r=a.getTransition();(t||!r||r.to===e)&&a.setState(e)};import{isNonNullable as IA,Subject as as,merge as gm}from"@vkontakte/videoplayer-shared";var M=class{constructor(e){this.transitionStarted$=new as;this.transitionEnded$=new as;this.transitionUpdated$=new as;this.forceChanged$=new as;this.stateChangeStarted$=gm(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=gm(this.transitionEnded$,this.forceChanged$);this.state=e,this.prevState=void 0}setState(e){let t=this.transition,r=this.state;this.transition=void 0,this.prevState=r,this.state=e,t?t.to===e?this.transitionEnded$.next(t):this.forceChanged$.next({from:t.from,to:e,canceledTransition:t}):this.forceChanged$.next({from:r,to:e,canceledTransition:t})}startTransitionTo(e){let t=this.transition,r=this.state;r===e||IA(t)&&t.to===e||(this.prevState=r,this.state=e,t?(this.transition={from:t.from,to:e,canceledTransition:t},this.transitionUpdated$.next(this.transition)):(this.transition={from:r,to:e},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}getPrevState(){return this.prevState}};import{assertNever as EA}from"@vkontakte/videoplayer-shared";var Sm=a=>{switch(a){case"MPEG":case"DASH":case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":case"HLS":case"HLS_ONDEMAND":return!1;case"DASH_LIVE":case"DASH_LIVE_CMAF":case"HLS_LIVE":case"HLS_LIVE_CMAF":case"DASH_LIVE_WEBM":case"WEB_RTC_LIVE":return!0;default:return EA(a)}};import{assertNever as Sr,assertNonNullable as Ot,debounce as vm,ErrorCategory as ym,fromEvent as Vt,isNonNullable as Tm,map as Im,merge as Em,observableFrom as xA,Subject as PA,Subscription as tu,timeout as AA,getHighestQuality as wA}from"@vkontakte/videoplayer-shared";var kA=5,RA=5,$A=500,xm=7e3,di=class{constructor(e){this.subscription=new tu;this.loadMediaTimeoutSubscription=new tu;this.videoState=new M("stopped");this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),r=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${r}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(s)};`}),r==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.stop());return}if(!t){if((i==null?void 0:i.to)!=="paused"&&s.state==="requested"&&e!=="stopped"){this.seek(s.position/1e3);return}switch(r){case"ready":{switch(e){case"playing":case"paused":case"ready":break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:Sr(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:Sr(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:Sr(e)}break}default:Sr(r)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(Sm(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 tu;this.subscription.add(e),this.subscription.add(Em(this.videoState.stateChangeStarted$.pipe(Im(i=>`stateChangeStarted$ ${JSON.stringify(i)}`)),this.videoState.stateChangeEnded$.pipe(Im(i=>`stateChangeEnded$ ${JSON.stringify(i)}`))).subscribe(i=>this.log({message:`[videoState] ${i}`})));let t=(i,s)=>this.subscription.add(i.subscribe(s));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{let i=new PA;e.add(i.pipe(vm($A)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add(Vt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe(n=>{this.logRemoteEvent(n);let o=n.value;this.params.output.position$.next(o),(this.params.desiredState.seekState.getState().state==="applying"||Math.abs(o-s)>kA)&&i.next(o),s=o})),e.add(Vt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(Vt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),i=>{this.logRemoteEvent(i),i.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(Vt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),i=>{this.logRemoteEvent(i),i.value?this.handleRemotePause():this.handleRemotePlay()}),t(Vt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),i=>{this.logRemoteEvent(i);let{remotePlayer:s}=this.params.connection,n=i.value,o=this.params.output.isBuffering$.getValue(),u=n===chrome.cast.media.PlayerState.BUFFERING;switch(o!==u&&this.params.output.isBuffering$.next(u),n){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&s.duration-s.currentTime<RA&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),E(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:Sr(n)}}),t(Vt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),i=>{this.logRemoteEvent(i),this.handleRemoteVolumeChange({volume:i.value})}),t(Vt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),i=>{this.logRemoteEvent(i),this.handleRemoteVolumeChange({muted:i.value})});let r=Em(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,xA(["init"])).pipe(vm(0));t(r,this.syncPlayback)}restoreSession(e){this.log({message:"restoreSession"});let{remotePlayer:t}=this.params.connection;if(e.playerState!==chrome.cast.media.PlayerState.IDLE){t.isPaused?(this.videoState.setState("paused"),E(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),E(this.params.desiredState.playbackState,"playing"));let r=this.params.output.isLive$.getValue();this.params.output.duration$.next(r?0:t.duration),this.params.output.position$.next(r?0:t.currentTime),this.params.desiredState.seekState.setState({state:"none"})}}prepare(){let e=this.params.format;this.log({message:`[prepare] format: ${e}`});let t=this.createMediaInfo(e),r=this.createLoadRequest(t);this.loadMedia(r)}handleRemotePause(){let e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)==="paused"||e==="playing")&&(this.videoState.setState("paused"),E(this.params.desiredState.playbackState,"paused"))}handleRemotePlay(){let e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)==="playing"||e==="paused")&&(this.videoState.setState("playing"),E(this.params.desiredState.playbackState,"playing"))}handleRemoteReady(){var t;let e=this.videoState.getTransition();(e==null?void 0:e.to)==="ready"&&this.videoState.setState("ready"),((t=this.params.desiredState.playbackState.getTransition())==null?void 0:t.to)==="ready"&&E(this.params.desiredState.playbackState,"ready")}handleRemoteStop(){this.videoState.getState()!=="stopped"&&this.videoState.setState("stopped")}handleRemoteVolumeChange(e){var i,s;let t=this.params.output.volume$.getValue(),r={volume:(i=e.volume)!=null?i:t.volume,muted:(s=e.muted)!=null?s:t.muted};(r.volume!==t.volume||r.muted!==r.muted)&&this.params.output.volume$.next(r)}seek(e){this.params.output.willSeekEvent$.next();let{remotePlayer:t,remotePlayerController:r}=this.params.connection;t.currentTime=e,r.seek()}stop(){let{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){var c;let t=this.params.source,r,i,s;switch(e){case"MPEG":{let l=t[e];Ot(l);let d=wA(Object.keys(l));Ot(d);let p=l[d];Ot(p),r=p,i="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let l=t[e];Ot(l),r=l.url,i="application/x-mpegurl",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":{let l=t[e];Ot(l),r=l.url,i="application/dash+xml",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let l=t[e];Ot(l),r=l.url,i="application/dash+xml",s=chrome.cast.media.StreamType.LIVE;break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let l=t[e];Ot(l),r=ee(l.url),i="application/x-mpegurl",s=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:ym.VIDEO_PIPELINE,message:l,thrown:d}),d}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return Sr(e)}let n=new chrome.cast.media.MediaInfo((c=this.params.meta.videoId)!=null?c:r,i);n.contentUrl=r,n.streamType=s,n.metadata=new chrome.cast.media.GenericMediaMetadata;let{title:o,subtitle:u}=this.params.meta;return Tm(o)&&(n.metadata.title=o),Tm(u)&&(n.metadata.subtitle=u),n}createLoadRequest(e){let t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;let r=this.params.desiredState.seekState.getState();return r.state==="applying"||r.state==="requested"?t.currentTime=this.params.output.isLive$.getValue()?0:r.position/1e3:t.currentTime=0,t}loadMedia(e){let t=this.params.connection.session.loadMedia(e),r=new Promise((i,s)=>{this.loadMediaTimeoutSubscription.add(AA(xm).subscribe(()=>s(`timeout(${xm})`)))});(0,Pm.default)(Promise.race([t,r]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},i=>{let s=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${i}`;this.log({message:s}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:ym.VIDEO_PIPELINE,message:s,thrown:i})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};import{clearVideoElement as wm}from"@vkontakte/videoplayer-shared";import{clearVideoElement as LA}from"@vkontakte/videoplayer-shared";var Am=a=>{try{a.pause(),a.playbackRate=0,LA(a),a.remove()}catch(e){console.error(e)}};import{fromEvent as MA,Subscription as CA}from"@vkontakte/videoplayer-shared";var ru=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)}},iu=window.WeakMap?new WeakMap:new ru,au=window.WeakMap?new WeakMap:new Map,DA=(a,e=20)=>{let t=0;return MA(a,"ratechange").subscribe(r=>{t++,t>=e&&(a.currentTime=a.currentTime,t=0)})},le=(a,{audioVideoSyncRate:e})=>{let t=a.querySelector("video"),r=!!t;t?wm(t):(t=document.createElement("video"),a.appendChild(t)),iu.set(t,r);let i=new CA;return i.add(DA(t,e)),au.set(t,i),t.setAttribute("crossorigin","anonymous"),t.setAttribute("playsinline","playsinline"),t.controls=!1,t.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),t},de=a=>{let e=au.get(a);e==null||e.unsubscribe(),au.delete(a);let t=iu.get(a);iu.delete(a),t?wm(a):Am(a)};import{assertNonNullable as pi,isNonNullable as We,isNullable as VA,fromEvent as vr,merge as km,observableFrom as Rm,filterChanged as $m,map as hi,Subject as Lm,Subscription as _A,ValueSubject as NA,ErrorCategory as FA}from"@vkontakte/videoplayer-shared";import{isNonNullable as su,isNullable as BA,Subscription as OA}from"@vkontakte/videoplayer-shared";var ss=(a,e,t,{equal:r=(n,o)=>n===o,changed$:i,onError:s}={})=>{let n=a.getState(),o=e(),u=BA(i),c=new OA;return i&&c.add(i.subscribe(l=>{let d=a.getState();r(l,d)&&a.setState(l)},s)),r(o,n)||(t(n),u&&a.setState(n)),c.add(a.stateChangeStarted$.subscribe(l=>{t(l.to),u&&a.setState(l.to)},s)),c},Ge=(a,e,t)=>ss(e,()=>a.loop,r=>{su(r)&&(a.loop=r)},{onError:t}),pe=(a,e,t,r)=>ss(e,()=>({muted:a.muted,volume:a.volume}),i=>{su(i)&&(a.muted=i.muted,a.volume=i.volume)},{equal:(i,s)=>i===s||(i==null?void 0:i.muted)===(s==null?void 0:s.muted)&&(i==null?void 0:i.volume)===(s==null?void 0:s.volume),changed$:t,onError:r}),ke=(a,e,t,r)=>ss(e,()=>a.playbackRate,i=>{su(i)&&(a.playbackRate=i)},{changed$:t,onError:r}),pt=ss;var qA=a=>["__",a.language,a.label].join("|"),UA=(a,e)=>{if(a.id===e)return!0;let[t,r,i]=e.split("|");return a.language===r&&a.label===i},nu=class a{constructor(){this.available$=new Lm;this.current$=new NA(void 0);this.error$=new Lm;this.subscription=new _A;this.externalTracks=new Map;this.internalTracks=new Map}connect(e,t,r){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();let i=s=>{this.error$.next({id:"TextTracksManager",category:FA.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:s})};this.subscription.add(this.available$.subscribe(r.availableTextTracks$)),this.subscription.add(this.current$.subscribe(r.currentTextTrack$)),this.subscription.add(this.error$.subscribe(r.error$)),this.subscription.add(pt(t.internalTextTracks,()=>Object.values(this.internalTracks),s=>{We(s)&&this.setInternal(s)},{equal:(s,n)=>We(s)&&We(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(hi(s=>s.filter(({type:n})=>n==="internal"))),onError:i})),this.subscription.add(pt(t.externalTextTracks,()=>Object.values(this.externalTracks),s=>{We(s)&&this.setExternal(s)},{equal:(s,n)=>We(s)&&We(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(hi(s=>s.filter(({type:n})=>n==="external"))),onError:i})),this.subscription.add(pt(t.currentTextTrack,()=>{if(this.video)return;let s=this.htmlTextTracksAsArray().find(({mode:n})=>n==="showing");return s&&this.htmlTextTrackToITextTrack(s).id},s=>this.select(s),{changed$:this.current$,onError:i})),this.subscription.add(pt(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.activeCues)}))}subscribe(){pi(this.video);let{textTracks:e}=this.video;this.subscription.add(vr(e,"addtrack").subscribe(()=>{let r=this.current$.getValue();r&&this.select(r)})),this.subscription.add(km(vr(e,"addtrack"),vr(e,"removetrack"),Rm(["init"])).pipe(hi(()=>this.htmlTextTracksAsArray().map(r=>this.htmlTextTrackToITextTrack(r))),$m((r,i)=>r.length===i.length&&r.every(({id:s},n)=>s===i[n].id))).subscribe(this.available$)),this.subscription.add(km(vr(e,"change"),Rm(["init"])).pipe(hi(()=>this.htmlTextTracksAsArray().find(({mode:r})=>r==="showing")),hi(r=>r&&this.htmlTextTrackToITextTrack(r).id),$m()).subscribe(this.current$));let t=r=>{var i,s;return this.applyCueSettings((s=(i=r.target)==null?void 0:i.activeCues)!=null?s:null)};this.subscription.add(vr(e,"addtrack").subscribe(r=>{var s,n;(s=r.track)==null||s.addEventListener("cuechange",t);let i=o=>{var c,l,d,p,h;let u=(l=(c=o.target)==null?void 0:c.cues)!=null?l:null;u&&u.length&&(this.applyCueSettings((p=(d=o.target)==null?void 0:d.cues)!=null?p:null),(h=o.target)==null||h.removeEventListener("cuechange",i))};(n=r.track)==null||n.addEventListener("cuechange",i)})),this.subscription.add(vr(e,"removetrack").subscribe(r=>{var i;(i=r.track)==null||i.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;let t=this.cueSettings.getState();for(let r of Array.from(e)){let i=r;We(t.align)&&(i.align=t.align),We(t.position)&&(i.position=t.position),We(t.size)&&(i.size=t.size),We(t.line)&&(i.line=t.line)}}htmlTextTracksAsArray(e=!1){pi(this.video);let t=[...this.video.textTracks];return e?t:t.filter(a.isHealthyTrack)}htmlTextTrackToITextTrack(e){var o,u;let{language:t,label:r}=e,i=e.id?e.id:qA(e),s=this.externalTracks.has(i),n=i.includes("auto");return s?{id:i,type:"external",isAuto:n,language:t,label:r,url:(o=this.externalTracks.get(i))==null?void 0:o.url}:{id:i,type:"internal",isAuto:n,language:t,label:r,url:(u=this.internalTracks.get(i))==null?void 0:u.url}}static isHealthyTrack(e){return!(e.kind==="metadata"||e.groupId||e.id===""&&e.label===""&&e.language==="")}setExternal(e){this.internalTracks.size>0&&Array.from(this.internalTracks).forEach(([,t])=>this.detach(t)),e.filter(({id:t})=>!this.externalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.externalTracks).filter(([t])=>!e.find(r=>r.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){let t=[...this.externalTracks];e.filter(({id:r,language:i,isAuto:s})=>!this.internalTracks.has(r)&&!t.some(([,n])=>n.language===i&&n.isAuto===s)).forEach(r=>this.attach(r)),Array.from(this.internalTracks).filter(([r])=>!e.find(i=>i.id===r)).forEach(([,r])=>this.detach(r))}select(e){pi(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(VA(e)||!UA(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){pi(this.video);let t=document.createElement("track");t.setAttribute("src",e.url),t.setAttribute("id",e.id),e.label&&t.setAttribute("label",e.label),e.language&&t.setAttribute("srclang",e.language),e.type==="external"?this.externalTracks.set(e.id,e):e.type==="internal"&&this.internalTracks.set(e.id,e),this.video.appendChild(t)}detach(e){pi(this.video);let t=Array.prototype.find.call(this.video.getElementsByTagName("track"),r=>r.getAttribute("id")===e.id);t&&this.video.removeChild(t),e.type==="external"?this.externalTracks.delete(e.id):e.type==="internal"&&this.internalTracks.delete(e.id)}},Re=nu;var Je=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 Mm=a=>{let e=a;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e==null?void 0:e.parentNode;return e!=null?e:void 0},ou=a=>{let e=Mm(a);return!!(e&&e.fullscreenElement&&e.fullscreenElement===a)},Cm=a=>{let e=Mm(a);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===a)};import{fromEvent as $e,map as ht,merge as Bm,filterChanged as jA,isNonNullable as Om,Subject as GA,filter as Vm,mapTo as _m,combine as WA,once as YA,ErrorCategory as QA,ValueSubject as Nm,clientChecker as zA}from"@vkontakte/videoplayer-shared";var HA=3,Dm=(a,e,t=HA)=>{let r=0,i=0;for(let s=0;s<a.length;s++){let n=a.start(s),o=a.end(s);if(n<=e&&e<=o){if(r=n,i=o,!t)return{from:r,to:i};for(let u=s-1;u>=0;u--)a.end(u)+t>=r&&(r=a.start(u));for(let u=s+1;u<a.length;u++)a.start(u)-t<=i&&(i=a.end(u))}}return{from:r,to:i}};var he=a=>{let e=S=>$e(a,S).pipe(_m(void 0)),r=Bm(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(S=>$e(a,S))).pipe(ht(S=>S.type==="ended"?a.readyState<2:a.readyState<3),jA()),i=Bm($e(a,"progress"),$e(a,"timeupdate")).pipe(ht(()=>Dm(a.buffered,a.currentTime))),s=zA.isSafari?WA({play:e("play").pipe(YA()),playing:e("playing")}).pipe(_m(void 0)):e("playing"),n=$e(a,"volumechange").pipe(ht(()=>({muted:a.muted,volume:a.volume}))),o=$e(a,"ratechange").pipe(ht(()=>a.playbackRate)),u=$e(a,"error").pipe(Vm(()=>!!(a.error||a.played.length)),ht(()=>{var v;let S=a.error;return{id:S?`MediaError#${S.code}`:"HtmlVideoError",category:QA.VIDEO_PIPELINE,message:S?S.message:"Error event from HTML video element",thrown:(v=a.error)!=null?v:void 0}})),c=$e(a,"timeupdate").pipe(ht(()=>a.currentTime)),l=new GA,d=.3,p;c.subscribe(S=>{a.loop&&Om(p)&&Om(S)&&p>=a.duration-d&&S<=d&&l.next(p),p=S});let h=e("pause").pipe(Vm(()=>!a.error&&p!==a.duration)),f=$e(a,"enterpictureinpicture"),b=$e(a,"leavepictureinpicture"),g=new Nm(Cm(a));f.subscribe(()=>g.next(!0)),b.subscribe(()=>g.next(!1));let y=new Nm(ou(a));return $e(a,"fullscreenchange").pipe(ht(()=>ou(a))).subscribe(y),{playing$:s,pause$:h,canplay$:e("canplay"),ended$:e("ended"),looped$:l,error$:u,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:c,durationChange$:$e(a,"durationchange").pipe(ht(()=>a.duration)),isBuffering$:r,currentBuffer$:i,volumeState$:n,playbackRateState$:o,inPiP$:g,inFullscreen$:y}};import{VideoQuality as ft}from"@vkontakte/videoplayer-shared";var mt=a=>{switch(a){case"mobile":return ft.Q_144P;case"lowest":return ft.Q_240P;case"low":return ft.Q_360P;case"sd":case"medium":return ft.Q_480P;case"hd":case"high":return ft.Q_720P;case"fullhd":case"full":return ft.Q_1080P;case"quadhd":case"quad":return ft.Q_1440P;case"ultrahd":case"ultra":return ft.Q_2160P}};var _t=He(fi(),1);import{isNonNullable as fe,isNullable as cu,now as Zm,isHigher as lu,isHigherOrEqual as zm,isInvariantQuality as Km,isLower as du,isLowerOrEqual as Jm,videoSizeToQuality as aw,assertNotEmptyArray as eb,assertNonNullable as sw}from"@vkontakte/videoplayer-shared";var uu=!1,Xe={},Wm=a=>{uu=a},Ym=()=>{Xe={}},Qm=a=>{a(Xe)},mi=(a,e)=>{var t;uu&&(Xe.meta=(t=Xe.meta)!=null?t:{},Xe.meta[a]=e)},re=class{constructor(e){this.name=e}next(e){var r,i;if(!uu)return;Xe.series=(r=Xe.series)!=null?r:{};let t=(i=Xe.series[this.name])!=null?i:[];t.push([Date.now(),e]),Xe.series[this.name]=t}};var nw=new re("best_bitrate"),tb=(a,e,t)=>(e-t)*Math.pow(2,-10*a)+t;var pu=a=>(e,t)=>a*(Number(e.bitrate)-Number(t.bitrate)),bi=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=Zm()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},rb='Assertion "ABR Tracks is empty array" failed',ns=(a,e,t,r)=>{var u;let i=[...e].sort(pu(1)),s=[...t].sort(pu(1)),n=s.filter(c=>fe(c.bitrate)&&fe(a.bitrate)?a.bitrate/c.bitrate>r:!0),o=(u=(0,_t.default)(s,Math.round(s.length*i.indexOf(a)/(i.length+1))))!=null?u:(0,_t.default)(s,-1);return o&&n.includes(o)?o:n.length?(0,_t.default)(n,-1):(0,_t.default)(s,0)},Xm=a=>"quality"in a,ib=(a,e,t,r)=>{let i=t&&r&&r.history[t.id]&&Zm()-r.history[t.id]<=a.trackCooldown&&(!r.last||t.id!==r.last.id);if(t!=null&&t.id&&r&&!i&&r.recordSelection(t),i&&(r!=null&&r.last)){let s=r.last;r==null||r.recordSwitch(s);let n=Xm(s)?"video":"audio",o=Xm(s)?s.quality:s.bitrate;return e({message:`
|
|
6
|
+
var pv=Object.create;var Zl=Object.defineProperty;var hv=Object.getOwnPropertyDescriptor;var fv=Object.getOwnPropertyNames;var mv=Object.getPrototypeOf,bv=Object.prototype.hasOwnProperty;var m=(a,e)=>()=>(e||a((e={exports:{}}).exports,e),e.exports);var gv=(a,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of fv(e))!bv.call(a,i)&&i!==t&&Zl(a,i,{get:()=>e[i],enumerable:!(r=hv(e,i))||r.enumerable});return a};var Ye=(a,e,t)=>(t=a!=null?pv(mv(a)):{},gv(e||!a||!a.__esModule?Zl(t,"default",{value:a,enumerable:!0}):t,a));var ye=m((hL,oc)=>{"use strict";oc.exports=function(a){try{return!!a()}catch(e){return!0}}});var Zr=m((fL,uc)=>{"use strict";var Pv=ye();uc.exports=!Pv(function(){var a=function(){}.bind();return typeof a!="function"||a.hasOwnProperty("prototype")})});var ce=m((mL,dc)=>{"use strict";var lc=Zr(),cc=Function.prototype,wn=cc.call,Av=lc&&cc.bind.bind(wn,wn);dc.exports=lc?Av:function(a){return function(){return wn.apply(a,arguments)}}});var dr=m((bL,hc)=>{"use strict";var pc=ce(),wv=pc({}.toString),kv=pc("".slice);hc.exports=function(a){return kv(wv(a),8,-1)}});var mc=m((gL,fc)=>{"use strict";var Rv=ce(),$v=ye(),Lv=dr(),kn=Object,Mv=Rv("".split);fc.exports=$v(function(){return!kn("z").propertyIsEnumerable(0)})?function(a){return Lv(a)==="String"?Mv(a,""):kn(a)}:kn});var pr=m((SL,bc)=>{"use strict";bc.exports=function(a){return a==null}});var ei=m((vL,gc)=>{"use strict";var Cv=pr(),Dv=TypeError;gc.exports=function(a){if(Cv(a))throw new Dv("Can't call method on "+a);return a}});var hr=m((yL,Sc)=>{"use strict";var Bv=mc(),Ov=ei();Sc.exports=function(a){return Bv(Ov(a))}});var Rn=m((TL,vc)=>{"use strict";vc.exports=function(){}});var _t=m((IL,yc)=>{"use strict";yc.exports={}});var Q=m(($n,Tc)=>{"use strict";var ti=function(a){return a&&a.Math===Math&&a};Tc.exports=ti(typeof globalThis=="object"&&globalThis)||ti(typeof window=="object"&&window)||ti(typeof self=="object"&&self)||ti(typeof global=="object"&&global)||ti(typeof $n=="object"&&$n)||function(){return this}()||Function("return this")()});var Y=m((EL,Ic)=>{"use strict";var Ln=typeof document=="object"&&document.all;Ic.exports=typeof Ln=="undefined"&&Ln!==void 0?function(a){return typeof a=="function"||a===Ln}:function(a){return typeof a=="function"}});var Pc=m((xL,xc)=>{"use strict";var Vv=Q(),_v=Y(),Ec=Vv.WeakMap;xc.exports=_v(Ec)&&/native code/.test(String(Ec))});var we=m((PL,Ac)=>{"use strict";var Nv=Y();Ac.exports=function(a){return typeof a=="object"?a!==null:Nv(a)}});var ke=m((AL,wc)=>{"use strict";var Fv=ye();wc.exports=!Fv(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var Fa=m((wL,Rc)=>{"use strict";var qv=Q(),kc=we(),Mn=qv.document,Uv=kc(Mn)&&kc(Mn.createElement);Rc.exports=function(a){return Uv?Mn.createElement(a):{}}});var Cn=m((kL,$c)=>{"use strict";var Hv=ke(),jv=ye(),Gv=Fa();$c.exports=!Hv&&!jv(function(){return Object.defineProperty(Gv("div"),"a",{get:function(){return 7}}).a!==7})});var Dn=m((RL,Lc)=>{"use strict";var Wv=ke(),Yv=ye();Lc.exports=Wv&&Yv(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var Qe=m(($L,Mc)=>{"use strict";var Qv=we(),zv=String,Kv=TypeError;Mc.exports=function(a){if(Qv(a))return a;throw new Kv(zv(a)+" is not an object")}});var Te=m((LL,Cc)=>{"use strict";var Jv=Zr(),qa=Function.prototype.call;Cc.exports=Jv?qa.bind(qa):function(){return qa.apply(qa,arguments)}});var Ua=m((ML,Dc)=>{"use strict";Dc.exports={}});var Ze=m((CL,Oc)=>{"use strict";var Bn=Ua(),On=Q(),Xv=Y(),Bc=function(a){return Xv(a)?a:void 0};Oc.exports=function(a,e){return arguments.length<2?Bc(Bn[a])||Bc(On[a]):Bn[a]&&Bn[a][e]||On[a]&&On[a][e]}});var ri=m((DL,Vc)=>{"use strict";var Zv=ce();Vc.exports=Zv({}.isPrototypeOf)});var fr=m((BL,Fc)=>{"use strict";var ey=Q(),_c=ey.navigator,Nc=_c&&_c.userAgent;Fc.exports=Nc?String(Nc):""});var _n=m((OL,Wc)=>{"use strict";var Gc=Q(),Vn=fr(),qc=Gc.process,Uc=Gc.Deno,Hc=qc&&qc.versions||Uc&&Uc.version,jc=Hc&&Hc.v8,Ne,Ha;jc&&(Ne=jc.split("."),Ha=Ne[0]>0&&Ne[0]<4?1:+(Ne[0]+Ne[1]));!Ha&&Vn&&(Ne=Vn.match(/Edge\/(\d+)/),(!Ne||Ne[1]>=74)&&(Ne=Vn.match(/Chrome\/(\d+)/),Ne&&(Ha=+Ne[1])));Wc.exports=Ha});var Nn=m((VL,Qc)=>{"use strict";var Yc=_n(),ty=ye(),ry=Q(),iy=ry.String;Qc.exports=!!Object.getOwnPropertySymbols&&!ty(function(){var a=Symbol("symbol detection");return!iy(a)||!(Object(a)instanceof Symbol)||!Symbol.sham&&Yc&&Yc<41})});var Fn=m((_L,zc)=>{"use strict";var ay=Nn();zc.exports=ay&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var qn=m((NL,Kc)=>{"use strict";var sy=Ze(),ny=Y(),oy=ri(),uy=Fn(),ly=Object;Kc.exports=uy?function(a){return typeof a=="symbol"}:function(a){var e=sy("Symbol");return ny(e)&&oy(e.prototype,ly(a))}});var ii=m((FL,Jc)=>{"use strict";var cy=String;Jc.exports=function(a){try{return cy(a)}catch(e){return"Object"}}});var et=m((qL,Xc)=>{"use strict";var dy=Y(),py=ii(),hy=TypeError;Xc.exports=function(a){if(dy(a))return a;throw new hy(py(a)+" is not a function")}});var ai=m((UL,Zc)=>{"use strict";var fy=et(),my=pr();Zc.exports=function(a,e){var t=a[e];return my(t)?void 0:fy(t)}});var td=m((HL,ed)=>{"use strict";var Un=Te(),Hn=Y(),jn=we(),by=TypeError;ed.exports=function(a,e){var t,r;if(e==="string"&&Hn(t=a.toString)&&!jn(r=Un(t,a))||Hn(t=a.valueOf)&&!jn(r=Un(t,a))||e!=="string"&&Hn(t=a.toString)&&!jn(r=Un(t,a)))return r;throw new by("Can't convert object to primitive value")}});var Fe=m((jL,rd)=>{"use strict";rd.exports=!0});var sd=m((GL,ad)=>{"use strict";var id=Q(),gy=Object.defineProperty;ad.exports=function(a,e){try{gy(id,a,{value:e,configurable:!0,writable:!0})}catch(t){id[a]=e}return e}});var si=m((WL,ud)=>{"use strict";var Sy=Fe(),vy=Q(),yy=sd(),nd="__core-js_shared__",od=ud.exports=vy[nd]||yy(nd,{});(od.versions||(od.versions=[])).push({version:"3.38.0",mode:Sy?"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 Gn=m((YL,cd)=>{"use strict";var ld=si();cd.exports=function(a,e){return ld[a]||(ld[a]=e||{})}});var ni=m((QL,dd)=>{"use strict";var Ty=ei(),Iy=Object;dd.exports=function(a){return Iy(Ty(a))}});var qe=m((zL,pd)=>{"use strict";var Ey=ce(),xy=ni(),Py=Ey({}.hasOwnProperty);pd.exports=Object.hasOwn||function(e,t){return Py(xy(e),t)}});var Wn=m((KL,hd)=>{"use strict";var Ay=ce(),wy=0,ky=Math.random(),Ry=Ay(1 .toString);hd.exports=function(a){return"Symbol("+(a===void 0?"":a)+")_"+Ry(++wy+ky,36)}});var ie=m((JL,md)=>{"use strict";var $y=Q(),Ly=Gn(),fd=qe(),My=Wn(),Cy=Nn(),Dy=Fn(),mr=$y.Symbol,Yn=Ly("wks"),By=Dy?mr.for||mr:mr&&mr.withoutSetter||My;md.exports=function(a){return fd(Yn,a)||(Yn[a]=Cy&&fd(mr,a)?mr[a]:By("Symbol."+a)),Yn[a]}});var vd=m((XL,Sd)=>{"use strict";var Oy=Te(),bd=we(),gd=qn(),Vy=ai(),_y=td(),Ny=ie(),Fy=TypeError,qy=Ny("toPrimitive");Sd.exports=function(a,e){if(!bd(a)||gd(a))return a;var t=Vy(a,qy),r;if(t){if(e===void 0&&(e="default"),r=Oy(t,a,e),!bd(r)||gd(r))return r;throw new Fy("Can't convert object to primitive value")}return e===void 0&&(e="number"),_y(a,e)}});var Qn=m((ZL,yd)=>{"use strict";var Uy=vd(),Hy=qn();yd.exports=function(a){var e=Uy(a,"string");return Hy(e)?e:e+""}});var Nt=m(Id=>{"use strict";var jy=ke(),Gy=Cn(),Wy=Dn(),ja=Qe(),Td=Qn(),Yy=TypeError,zn=Object.defineProperty,Qy=Object.getOwnPropertyDescriptor,Kn="enumerable",Jn="configurable",Xn="writable";Id.f=jy?Wy?function(e,t,r){if(ja(e),t=Td(t),ja(r),typeof e=="function"&&t==="prototype"&&"value"in r&&Xn in r&&!r[Xn]){var i=Qy(e,t);i&&i[Xn]&&(e[t]=r.value,r={configurable:Jn in r?r[Jn]:i[Jn],enumerable:Kn in r?r[Kn]:i[Kn],writable:!1})}return zn(e,t,r)}:zn:function(e,t,r){if(ja(e),t=Td(t),ja(r),Gy)try{return zn(e,t,r)}catch(i){}if("get"in r||"set"in r)throw new Yy("Accessors not supported");return"value"in r&&(e[t]=r.value),e}});var oi=m((tM,Ed)=>{"use strict";Ed.exports=function(a,e){return{enumerable:!(a&1),configurable:!(a&2),writable:!(a&4),value:e}}});var br=m((rM,xd)=>{"use strict";var zy=ke(),Ky=Nt(),Jy=oi();xd.exports=zy?function(a,e,t){return Ky.f(a,e,Jy(1,t))}:function(a,e,t){return a[e]=t,a}});var Ga=m((iM,Ad)=>{"use strict";var Xy=Gn(),Zy=Wn(),Pd=Xy("keys");Ad.exports=function(a){return Pd[a]||(Pd[a]=Zy(a))}});var Wa=m((aM,wd)=>{"use strict";wd.exports={}});var ro=m((sM,$d)=>{"use strict";var eT=Pc(),Rd=Q(),tT=we(),rT=br(),Zn=qe(),eo=si(),iT=Ga(),aT=Wa(),kd="Object already initialized",to=Rd.TypeError,sT=Rd.WeakMap,Ya,ui,Qa,nT=function(a){return Qa(a)?ui(a):Ya(a,{})},oT=function(a){return function(e){var t;if(!tT(e)||(t=ui(e)).type!==a)throw new to("Incompatible receiver, "+a+" required");return t}};eT||eo.state?(Ue=eo.state||(eo.state=new sT),Ue.get=Ue.get,Ue.has=Ue.has,Ue.set=Ue.set,Ya=function(a,e){if(Ue.has(a))throw new to(kd);return e.facade=a,Ue.set(a,e),e},ui=function(a){return Ue.get(a)||{}},Qa=function(a){return Ue.has(a)}):(Ft=iT("state"),aT[Ft]=!0,Ya=function(a,e){if(Zn(a,Ft))throw new to(kd);return e.facade=a,rT(a,Ft,e),e},ui=function(a){return Zn(a,Ft)?a[Ft]:{}},Qa=function(a){return Zn(a,Ft)});var Ue,Ft;$d.exports={set:Ya,get:ui,has:Qa,enforce:nT,getterFor:oT}});var io=m((nM,Dd)=>{"use strict";var uT=Zr(),Cd=Function.prototype,Ld=Cd.apply,Md=Cd.call;Dd.exports=typeof Reflect=="object"&&Reflect.apply||(uT?Md.bind(Ld):function(){return Md.apply(Ld,arguments)})});var ao=m((oM,Bd)=>{"use strict";var lT=dr(),cT=ce();Bd.exports=function(a){if(lT(a)==="Function")return cT(a)}});var Nd=m(_d=>{"use strict";var Od={}.propertyIsEnumerable,Vd=Object.getOwnPropertyDescriptor,dT=Vd&&!Od.call({1:2},1);_d.f=dT?function(e){var t=Vd(this,e);return!!t&&t.enumerable}:Od});var Ud=m(qd=>{"use strict";var pT=ke(),hT=Te(),fT=Nd(),mT=oi(),bT=hr(),gT=Qn(),ST=qe(),vT=Cn(),Fd=Object.getOwnPropertyDescriptor;qd.f=pT?Fd:function(e,t){if(e=bT(e),t=gT(t),vT)try{return Fd(e,t)}catch(r){}if(ST(e,t))return mT(!hT(fT.f,e,t),e[t])}});var so=m((cM,Hd)=>{"use strict";var yT=ye(),TT=Y(),IT=/#|\.prototype\./,li=function(a,e){var t=xT[ET(a)];return t===AT?!0:t===PT?!1:TT(e)?yT(e):!!e},ET=li.normalize=function(a){return String(a).replace(IT,".").toLowerCase()},xT=li.data={},PT=li.NATIVE="N",AT=li.POLYFILL="P";Hd.exports=li});var ci=m((dM,Gd)=>{"use strict";var jd=ao(),wT=et(),kT=Zr(),RT=jd(jd.bind);Gd.exports=function(a,e){return wT(a),e===void 0?a:kT?RT(a,e):function(){return a.apply(e,arguments)}}});var Re=m((pM,Yd)=>{"use strict";var di=Q(),$T=io(),LT=ao(),MT=Y(),CT=Ud().f,DT=so(),gr=Ua(),BT=ci(),Sr=br(),Wd=qe();si();var OT=function(a){var e=function(t,r,i){if(this instanceof e){switch(arguments.length){case 0:return new a;case 1:return new a(t);case 2:return new a(t,r)}return new a(t,r,i)}return $T(a,this,arguments)};return e.prototype=a.prototype,e};Yd.exports=function(a,e){var t=a.target,r=a.global,i=a.stat,s=a.proto,n=r?di:i?di[t]:di[t]&&di[t].prototype,o=r?gr:gr[t]||Sr(gr,t,{})[t],u=o.prototype,l,c,d,p,h,f,b,g,y;for(p in e)l=DT(r?p:t+(i?".":"#")+p,a.forced),c=!l&&n&&Wd(n,p),f=o[p],c&&(a.dontCallGetSet?(y=CT(n,p),b=y&&y.value):b=n[p]),h=c&&b?b:e[p],!(!l&&!s&&typeof f==typeof h)&&(a.bind&&c?g=BT(h,di):a.wrap&&c?g=OT(h):s&&MT(h)?g=LT(h):g=h,(a.sham||h&&h.sham||f&&f.sham)&&Sr(g,"sham",!0),Sr(o,p,g),s&&(d=t+"Prototype",Wd(gr,d)||Sr(gr,d,{}),Sr(gr[d],p,h),a.real&&u&&(l||!u[p])&&Sr(u,p,h)))}});var Kd=m((hM,zd)=>{"use strict";var no=ke(),VT=qe(),Qd=Function.prototype,_T=no&&Object.getOwnPropertyDescriptor,oo=VT(Qd,"name"),NT=oo&&function(){}.name==="something",FT=oo&&(!no||no&&_T(Qd,"name").configurable);zd.exports={EXISTS:oo,PROPER:NT,CONFIGURABLE:FT}});var Xd=m((fM,Jd)=>{"use strict";var qT=Math.ceil,UT=Math.floor;Jd.exports=Math.trunc||function(e){var t=+e;return(t>0?UT:qT)(t)}});var za=m((mM,Zd)=>{"use strict";var HT=Xd();Zd.exports=function(a){var e=+a;return e!==e||e===0?0:HT(e)}});var tp=m((bM,ep)=>{"use strict";var jT=za(),GT=Math.max,WT=Math.min;ep.exports=function(a,e){var t=jT(a);return t<0?GT(t+e,0):WT(t,e)}});var ip=m((gM,rp)=>{"use strict";var YT=za(),QT=Math.min;rp.exports=function(a){var e=YT(a);return e>0?QT(e,9007199254740991):0}});var Ka=m((SM,ap)=>{"use strict";var zT=ip();ap.exports=function(a){return zT(a.length)}});var op=m((vM,np)=>{"use strict";var KT=hr(),JT=tp(),XT=Ka(),sp=function(a){return function(e,t,r){var i=KT(e),s=XT(i);if(s===0)return!a&&-1;var n=JT(r,s),o;if(a&&t!==t){for(;s>n;)if(o=i[n++],o!==o)return!0}else for(;s>n;n++)if((a||n in i)&&i[n]===t)return a||n||0;return!a&&-1}};np.exports={includes:sp(!0),indexOf:sp(!1)}});var cp=m((yM,lp)=>{"use strict";var ZT=ce(),uo=qe(),eI=hr(),tI=op().indexOf,rI=Wa(),up=ZT([].push);lp.exports=function(a,e){var t=eI(a),r=0,i=[],s;for(s in t)!uo(rI,s)&&uo(t,s)&&up(i,s);for(;e.length>r;)uo(t,s=e[r++])&&(~tI(i,s)||up(i,s));return i}});var lo=m((TM,dp)=>{"use strict";dp.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var hp=m((IM,pp)=>{"use strict";var iI=cp(),aI=lo();pp.exports=Object.keys||function(e){return iI(e,aI)}});var mp=m(fp=>{"use strict";var sI=ke(),nI=Dn(),oI=Nt(),uI=Qe(),lI=hr(),cI=hp();fp.f=sI&&!nI?Object.defineProperties:function(e,t){uI(e);for(var r=lI(t),i=cI(t),s=i.length,n=0,o;s>n;)oI.f(e,o=i[n++],r[o]);return e}});var co=m((xM,bp)=>{"use strict";var dI=Ze();bp.exports=dI("document","documentElement")});var mo=m((PM,Ep)=>{"use strict";var pI=Qe(),hI=mp(),gp=lo(),fI=Wa(),mI=co(),bI=Fa(),gI=Ga(),Sp=">",vp="<",ho="prototype",fo="script",Tp=gI("IE_PROTO"),po=function(){},Ip=function(a){return vp+fo+Sp+a+vp+"/"+fo+Sp},yp=function(a){a.write(Ip("")),a.close();var e=a.parentWindow.Object;return a=null,e},SI=function(){var a=bI("iframe"),e="java"+fo+":",t;return a.style.display="none",mI.appendChild(a),a.src=String(e),t=a.contentWindow.document,t.open(),t.write(Ip("document.F=Object")),t.close(),t.F},Ja,Xa=function(){try{Ja=new ActiveXObject("htmlfile")}catch(e){}Xa=typeof document!="undefined"?document.domain&&Ja?yp(Ja):SI():yp(Ja);for(var a=gp.length;a--;)delete Xa[ho][gp[a]];return Xa()};fI[Tp]=!0;Ep.exports=Object.create||function(e,t){var r;return e!==null?(po[ho]=pI(e),r=new po,po[ho]=null,r[Tp]=e):r=Xa(),t===void 0?r:hI.f(r,t)}});var Pp=m((AM,xp)=>{"use strict";var vI=ye();xp.exports=!vI(function(){function a(){}return a.prototype.constructor=null,Object.getPrototypeOf(new a)!==a.prototype})});var go=m((wM,wp)=>{"use strict";var yI=qe(),TI=Y(),II=ni(),EI=Ga(),xI=Pp(),Ap=EI("IE_PROTO"),bo=Object,PI=bo.prototype;wp.exports=xI?bo.getPrototypeOf:function(a){var e=II(a);if(yI(e,Ap))return e[Ap];var t=e.constructor;return TI(t)&&e instanceof t?t.prototype:e instanceof bo?PI:null}});var vr=m((kM,kp)=>{"use strict";var AI=br();kp.exports=function(a,e,t,r){return r&&r.enumerable?a[e]=t:AI(a,e,t),a}});var To=m((RM,Lp)=>{"use strict";var wI=ye(),kI=Y(),RI=we(),$I=mo(),Rp=go(),LI=vr(),MI=ie(),CI=Fe(),yo=MI("iterator"),$p=!1,tt,So,vo;[].keys&&(vo=[].keys(),"next"in vo?(So=Rp(Rp(vo)),So!==Object.prototype&&(tt=So)):$p=!0);var DI=!RI(tt)||wI(function(){var a={};return tt[yo].call(a)!==a});DI?tt={}:CI&&(tt=$I(tt));kI(tt[yo])||LI(tt,yo,function(){return this});Lp.exports={IteratorPrototype:tt,BUGGY_SAFARI_ITERATORS:$p}});var Za=m(($M,Cp)=>{"use strict";var BI=ie(),OI=BI("toStringTag"),Mp={};Mp[OI]="z";Cp.exports=String(Mp)==="[object z]"});var pi=m((LM,Dp)=>{"use strict";var VI=Za(),_I=Y(),es=dr(),NI=ie(),FI=NI("toStringTag"),qI=Object,UI=es(function(){return arguments}())==="Arguments",HI=function(a,e){try{return a[e]}catch(t){}};Dp.exports=VI?es:function(a){var e,t,r;return a===void 0?"Undefined":a===null?"Null":typeof(t=HI(e=qI(a),FI))=="string"?t:UI?es(e):(r=es(e))==="Object"&&_I(e.callee)?"Arguments":r}});var Op=m((MM,Bp)=>{"use strict";var jI=Za(),GI=pi();Bp.exports=jI?{}.toString:function(){return"[object "+GI(this)+"]"}});var hi=m((CM,_p)=>{"use strict";var WI=Za(),YI=Nt().f,QI=br(),zI=qe(),KI=Op(),JI=ie(),Vp=JI("toStringTag");_p.exports=function(a,e,t,r){var i=t?a:a&&a.prototype;i&&(zI(i,Vp)||YI(i,Vp,{configurable:!0,value:e}),r&&!WI&&QI(i,"toString",KI))}});var Fp=m((DM,Np)=>{"use strict";var XI=To().IteratorPrototype,ZI=mo(),eE=oi(),tE=hi(),rE=_t(),iE=function(){return this};Np.exports=function(a,e,t,r){var i=e+" Iterator";return a.prototype=ZI(XI,{next:eE(+!r,t)}),tE(a,i,!1,!0),rE[i]=iE,a}});var Up=m((BM,qp)=>{"use strict";var aE=ce(),sE=et();qp.exports=function(a,e,t){try{return aE(sE(Object.getOwnPropertyDescriptor(a,e)[t]))}catch(r){}}});var jp=m((OM,Hp)=>{"use strict";var nE=we();Hp.exports=function(a){return nE(a)||a===null}});var Wp=m((VM,Gp)=>{"use strict";var oE=jp(),uE=String,lE=TypeError;Gp.exports=function(a){if(oE(a))return a;throw new lE("Can't set "+uE(a)+" as a prototype")}});var Io=m((_M,Yp)=>{"use strict";var cE=Up(),dE=we(),pE=ei(),hE=Wp();Yp.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var a=!1,e={},t;try{t=cE(Object.prototype,"__proto__","set"),t(e,[]),a=e instanceof Array}catch(r){}return function(i,s){return pE(i),hE(s),dE(i)&&(a?t(i,s):i.__proto__=s),i}}():void 0)});var ah=m((NM,ih)=>{"use strict";var fE=Re(),mE=Te(),ts=Fe(),th=Kd(),bE=Y(),gE=Fp(),Qp=go(),zp=Io(),SE=hi(),vE=br(),Eo=vr(),yE=ie(),Kp=_t(),rh=To(),TE=th.PROPER,IE=th.CONFIGURABLE,Jp=rh.IteratorPrototype,rs=rh.BUGGY_SAFARI_ITERATORS,fi=yE("iterator"),Xp="keys",mi="values",Zp="entries",eh=function(){return this};ih.exports=function(a,e,t,r,i,s,n){gE(t,e,r);var o=function(y){if(y===i&&p)return p;if(!rs&&y&&y in c)return c[y];switch(y){case Xp:return function(){return new t(this,y)};case mi:return function(){return new t(this,y)};case Zp:return function(){return new t(this,y)}}return function(){return new t(this)}},u=e+" Iterator",l=!1,c=a.prototype,d=c[fi]||c["@@iterator"]||i&&c[i],p=!rs&&d||o(i),h=e==="Array"&&c.entries||d,f,b,g;if(h&&(f=Qp(h.call(new a)),f!==Object.prototype&&f.next&&(!ts&&Qp(f)!==Jp&&(zp?zp(f,Jp):bE(f[fi])||Eo(f,fi,eh)),SE(f,u,!0,!0),ts&&(Kp[u]=eh))),TE&&i===mi&&d&&d.name!==mi&&(!ts&&IE?vE(c,"name",mi):(l=!0,p=function(){return mE(d,this)})),i)if(b={values:o(mi),keys:s?p:o(Xp),entries:o(Zp)},n)for(g in b)(rs||l||!(g in c))&&Eo(c,g,b[g]);else fE({target:e,proto:!0,forced:rs||l},b);return(!ts||n)&&c[fi]!==p&&Eo(c,fi,p,{name:i}),Kp[e]=p,b}});var nh=m((FM,sh)=>{"use strict";sh.exports=function(a,e){return{value:a,done:e}}});var Po=m((qM,dh)=>{"use strict";var EE=hr(),xo=Rn(),oh=_t(),lh=ro(),xE=Nt().f,PE=ah(),is=nh(),AE=Fe(),wE=ke(),ch="Array Iterator",kE=lh.set,RE=lh.getterFor(ch);dh.exports=PE(Array,"Array",function(a,e){kE(this,{type:ch,target:EE(a),index:0,kind:e})},function(){var a=RE(this),e=a.target,t=a.index++;if(!e||t>=e.length)return a.target=void 0,is(void 0,!0);switch(a.kind){case"keys":return is(t,!1);case"values":return is(e[t],!1)}return is([t,e[t]],!1)},"values");var uh=oh.Arguments=oh.Array;xo("keys");xo("values");xo("entries");if(!AE&&wE&&uh.name!=="values")try{xE(uh,"name",{value:"values"})}catch(a){}});var hh=m((UM,ph)=>{"use strict";var $E=ie(),LE=_t(),ME=$E("iterator"),CE=Array.prototype;ph.exports=function(a){return a!==void 0&&(LE.Array===a||CE[ME]===a)}});var Ao=m((HM,mh)=>{"use strict";var DE=pi(),fh=ai(),BE=pr(),OE=_t(),VE=ie(),_E=VE("iterator");mh.exports=function(a){if(!BE(a))return fh(a,_E)||fh(a,"@@iterator")||OE[DE(a)]}});var gh=m((jM,bh)=>{"use strict";var NE=Te(),FE=et(),qE=Qe(),UE=ii(),HE=Ao(),jE=TypeError;bh.exports=function(a,e){var t=arguments.length<2?HE(a):e;if(FE(t))return qE(NE(t,a));throw new jE(UE(a)+" is not iterable")}});var yh=m((GM,vh)=>{"use strict";var GE=Te(),Sh=Qe(),WE=ai();vh.exports=function(a,e,t){var r,i;Sh(a);try{if(r=WE(a,"return"),!r){if(e==="throw")throw t;return t}r=GE(r,a)}catch(s){i=!0,r=s}if(e==="throw")throw t;if(i)throw r;return Sh(r),t}});var ss=m((WM,xh)=>{"use strict";var YE=ci(),QE=Te(),zE=Qe(),KE=ii(),JE=hh(),XE=Ka(),Th=ri(),ZE=gh(),ex=Ao(),Ih=yh(),tx=TypeError,as=function(a,e){this.stopped=a,this.result=e},Eh=as.prototype;xh.exports=function(a,e,t){var r=t&&t.that,i=!!(t&&t.AS_ENTRIES),s=!!(t&&t.IS_RECORD),n=!!(t&&t.IS_ITERATOR),o=!!(t&&t.INTERRUPTED),u=YE(e,r),l,c,d,p,h,f,b,g=function(I){return l&&Ih(l,"normal",I),new as(!0,I)},y=function(I){return i?(zE(I),o?u(I[0],I[1],g):u(I[0],I[1])):o?u(I,g):u(I)};if(s)l=a.iterator;else if(n)l=a;else{if(c=ex(a),!c)throw new tx(KE(a)+" is not iterable");if(JE(c)){for(d=0,p=XE(a);p>d;d++)if(h=y(a[d]),h&&Th(Eh,h))return h;return new as(!1)}l=ZE(a,c)}for(f=s?a.next:l.next;!(b=QE(f,l)).done;){try{h=y(b.value)}catch(I){Ih(l,"throw",I)}if(typeof h=="object"&&h&&Th(Eh,h))return h}return new as(!1)}});var Ah=m((YM,Ph)=>{"use strict";var rx=ke(),ix=Nt(),ax=oi();Ph.exports=function(a,e,t){rx?ix.f(a,e,ax(0,t)):a[e]=t}});var wh=m(()=>{"use strict";var sx=Re(),nx=ss(),ox=Ah();sx({target:"Object",stat:!0},{fromEntries:function(e){var t={};return nx(e,function(r,i){ox(t,r,i)},{AS_ENTRIES:!0}),t}})});var Rh=m((KM,kh)=>{"use strict";Po();wh();var ux=Ua();kh.exports=ux.Object.fromEntries});var Lh=m((JM,$h)=>{"use strict";$h.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 Ch=m(()=>{"use strict";Po();var lx=Lh(),cx=Q(),dx=hi(),Mh=_t();for(ns in lx)dx(cx[ns],ns),Mh[ns]=Mh.Array;var ns});var Bh=m((eC,Dh)=>{"use strict";var px=Rh();Ch();Dh.exports=px});var wo=m((tC,Oh)=>{"use strict";var hx=Bh();Oh.exports=hx});var Vh=m(()=>{"use strict"});var ko=m((aC,_h)=>{"use strict";var bi=Q(),fx=fr(),mx=dr(),os=function(a){return fx.slice(0,a.length)===a};_h.exports=function(){return os("Bun/")?"BUN":os("Cloudflare-Workers")?"CLOUDFLARE":os("Deno/")?"DENO":os("Node.js/")?"NODE":bi.Bun&&typeof Bun.version=="string"?"BUN":bi.Deno&&typeof Deno.version=="object"?"DENO":mx(bi.process)==="process"?"NODE":bi.window&&bi.document?"BROWSER":"REST"}()});var us=m((sC,Nh)=>{"use strict";var bx=ko();Nh.exports=bx==="NODE"});var qh=m((nC,Fh)=>{"use strict";var gx=Nt();Fh.exports=function(a,e,t){return gx.f(a,e,t)}});var jh=m((oC,Hh)=>{"use strict";var Sx=Ze(),vx=qh(),yx=ie(),Tx=ke(),Uh=yx("species");Hh.exports=function(a){var e=Sx(a);Tx&&e&&!e[Uh]&&vx(e,Uh,{configurable:!0,get:function(){return this}})}});var Wh=m((uC,Gh)=>{"use strict";var Ix=ri(),Ex=TypeError;Gh.exports=function(a,e){if(Ix(e,a))return a;throw new Ex("Incorrect invocation")}});var $o=m((lC,Yh)=>{"use strict";var xx=ce(),Px=Y(),Ro=si(),Ax=xx(Function.toString);Px(Ro.inspectSource)||(Ro.inspectSource=function(a){return Ax(a)});Yh.exports=Ro.inspectSource});var Zh=m((cC,Xh)=>{"use strict";var wx=ce(),kx=ye(),Qh=Y(),Rx=pi(),$x=Ze(),Lx=$o(),zh=function(){},Kh=$x("Reflect","construct"),Lo=/^\s*(?:class|function)\b/,Mx=wx(Lo.exec),Cx=!Lo.test(zh),gi=function(e){if(!Qh(e))return!1;try{return Kh(zh,[],e),!0}catch(t){return!1}},Jh=function(e){if(!Qh(e))return!1;switch(Rx(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return Cx||!!Mx(Lo,Lx(e))}catch(t){return!0}};Jh.sham=!0;Xh.exports=!Kh||kx(function(){var a;return gi(gi.call)||!gi(Object)||!gi(function(){a=!0})||a})?Jh:gi});var tf=m((dC,ef)=>{"use strict";var Dx=Zh(),Bx=ii(),Ox=TypeError;ef.exports=function(a){if(Dx(a))return a;throw new Ox(Bx(a)+" is not a constructor")}});var Mo=m((pC,af)=>{"use strict";var rf=Qe(),Vx=tf(),_x=pr(),Nx=ie(),Fx=Nx("species");af.exports=function(a,e){var t=rf(a).constructor,r;return t===void 0||_x(r=rf(t)[Fx])?e:Vx(r)}});var nf=m((hC,sf)=>{"use strict";var qx=ce();sf.exports=qx([].slice)});var uf=m((fC,of)=>{"use strict";var Ux=TypeError;of.exports=function(a,e){if(a<e)throw new Ux("Not enough arguments");return a}});var Co=m((mC,lf)=>{"use strict";var Hx=fr();lf.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(Hx)});var Uo=m((bC,Sf)=>{"use strict";var Ie=Q(),jx=io(),Gx=ci(),cf=Y(),Wx=qe(),gf=ye(),df=co(),Yx=nf(),pf=Fa(),Qx=uf(),zx=Co(),Kx=us(),No=Ie.setImmediate,Fo=Ie.clearImmediate,Jx=Ie.process,Do=Ie.Dispatch,Xx=Ie.Function,hf=Ie.MessageChannel,Zx=Ie.String,Bo=0,Si={},ff="onreadystatechange",vi,qt,Oo,Vo;gf(function(){vi=Ie.location});var qo=function(a){if(Wx(Si,a)){var e=Si[a];delete Si[a],e()}},_o=function(a){return function(){qo(a)}},mf=function(a){qo(a.data)},bf=function(a){Ie.postMessage(Zx(a),vi.protocol+"//"+vi.host)};(!No||!Fo)&&(No=function(e){Qx(arguments.length,1);var t=cf(e)?e:Xx(e),r=Yx(arguments,1);return Si[++Bo]=function(){jx(t,void 0,r)},qt(Bo),Bo},Fo=function(e){delete Si[e]},Kx?qt=function(a){Jx.nextTick(_o(a))}:Do&&Do.now?qt=function(a){Do.now(_o(a))}:hf&&!zx?(Oo=new hf,Vo=Oo.port2,Oo.port1.onmessage=mf,qt=Gx(Vo.postMessage,Vo)):Ie.addEventListener&&cf(Ie.postMessage)&&!Ie.importScripts&&vi&&vi.protocol!=="file:"&&!gf(bf)?(qt=bf,Ie.addEventListener("message",mf,!1)):ff in pf("script")?qt=function(a){df.appendChild(pf("script"))[ff]=function(){df.removeChild(this),qo(a)}}:qt=function(a){setTimeout(_o(a),0)});Sf.exports={set:No,clear:Fo}});var Tf=m((gC,yf)=>{"use strict";var vf=Q(),eP=ke(),tP=Object.getOwnPropertyDescriptor;yf.exports=function(a){if(!eP)return vf[a];var e=tP(vf,a);return e&&e.value}});var Ho=m((SC,Ef)=>{"use strict";var If=function(){this.head=null,this.tail=null};If.prototype={add:function(a){var e={item:a,next:null},t=this.tail;t?t.next=e:this.head=e,this.tail=e},get:function(){var a=this.head;if(a){var e=this.head=a.next;return e===null&&(this.tail=null),a.item}}};Ef.exports=If});var Pf=m((vC,xf)=>{"use strict";var rP=fr();xf.exports=/ipad|iphone|ipod/i.test(rP)&&typeof Pebble!="undefined"});var wf=m((yC,Af)=>{"use strict";var iP=fr();Af.exports=/web0s(?!.*chrome)/i.test(iP)});var Df=m((TC,Cf)=>{"use strict";var Tr=Q(),aP=Tf(),kf=ci(),jo=Uo().set,sP=Ho(),nP=Co(),oP=Pf(),uP=wf(),Go=us(),Rf=Tr.MutationObserver||Tr.WebKitMutationObserver,$f=Tr.document,Lf=Tr.process,ls=Tr.Promise,Qo=aP("queueMicrotask"),yr,Wo,Yo,cs,Mf;Qo||(yi=new sP,Ti=function(){var a,e;for(Go&&(a=Lf.domain)&&a.exit();e=yi.get();)try{e()}catch(t){throw yi.head&&yr(),t}a&&a.enter()},!nP&&!Go&&!uP&&Rf&&$f?(Wo=!0,Yo=$f.createTextNode(""),new Rf(Ti).observe(Yo,{characterData:!0}),yr=function(){Yo.data=Wo=!Wo}):!oP&&ls&&ls.resolve?(cs=ls.resolve(void 0),cs.constructor=ls,Mf=kf(cs.then,cs),yr=function(){Mf(Ti)}):Go?yr=function(){Lf.nextTick(Ti)}:(jo=kf(jo,Tr),yr=function(){jo(Ti)}),Qo=function(a){yi.head||yr(),yi.add(a)});var yi,Ti;Cf.exports=Qo});var Of=m((IC,Bf)=>{"use strict";Bf.exports=function(a,e){try{arguments.length===1?console.error(a):console.error(a,e)}catch(t){}}});var ds=m((EC,Vf)=>{"use strict";Vf.exports=function(a){try{return{error:!1,value:a()}}catch(e){return{error:!0,value:e}}}});var Ut=m((xC,_f)=>{"use strict";var lP=Q();_f.exports=lP.Promise});var Ir=m((PC,Uf)=>{"use strict";var cP=Q(),Ii=Ut(),dP=Y(),pP=so(),hP=$o(),fP=ie(),Nf=ko(),mP=Fe(),zo=_n(),Ff=Ii&&Ii.prototype,bP=fP("species"),Ko=!1,qf=dP(cP.PromiseRejectionEvent),gP=pP("Promise",function(){var a=hP(Ii),e=a!==String(Ii);if(!e&&zo===66||mP&&!(Ff.catch&&Ff.finally))return!0;if(!zo||zo<51||!/native code/.test(a)){var t=new Ii(function(s){s(1)}),r=function(s){s(function(){},function(){})},i=t.constructor={};if(i[bP]=r,Ko=t.then(function(){})instanceof r,!Ko)return!0}return!e&&(Nf==="BROWSER"||Nf==="DENO")&&!qf});Uf.exports={CONSTRUCTOR:gP,REJECTION_EVENT:qf,SUBCLASSING:Ko}});var Er=m((AC,jf)=>{"use strict";var Hf=et(),SP=TypeError,vP=function(a){var e,t;this.promise=new a(function(r,i){if(e!==void 0||t!==void 0)throw new SP("Bad Promise constructor");e=r,t=i}),this.resolve=Hf(e),this.reject=Hf(t)};jf.exports.f=function(a){return new vP(a)}});var lm=m(()=>{"use strict";var yP=Re(),TP=Fe(),ms=us(),vt=Q(),wr=Te(),Gf=vr(),Wf=Io(),IP=hi(),EP=jh(),xP=et(),fs=Y(),PP=we(),AP=Wh(),wP=Mo(),Jf=Uo().set,tu=Df(),kP=Of(),RP=ds(),$P=Ho(),Xf=ro(),bs=Ut(),ru=Ir(),Zf=Er(),gs="Promise",em=ru.CONSTRUCTOR,LP=ru.REJECTION_EVENT,MP=ru.SUBCLASSING,Jo=Xf.getterFor(gs),CP=Xf.set,xr=bs&&bs.prototype,Ht=bs,ps=xr,tm=vt.TypeError,Xo=vt.document,iu=vt.process,Zo=Zf.f,DP=Zo,BP=!!(Xo&&Xo.createEvent&&vt.dispatchEvent),rm="unhandledrejection",OP="rejectionhandled",Yf=0,im=1,VP=2,au=1,am=2,hs,Qf,_P,zf,sm=function(a){var e;return PP(a)&&fs(e=a.then)?e:!1},nm=function(a,e){var t=e.value,r=e.state===im,i=r?a.ok:a.fail,s=a.resolve,n=a.reject,o=a.domain,u,l,c;try{i?(r||(e.rejection===am&&FP(e),e.rejection=au),i===!0?u=t:(o&&o.enter(),u=i(t),o&&(o.exit(),c=!0)),u===a.promise?n(new tm("Promise-chain cycle")):(l=sm(u))?wr(l,u,s,n):s(u)):n(t)}catch(d){o&&!c&&o.exit(),n(d)}},om=function(a,e){a.notified||(a.notified=!0,tu(function(){for(var t=a.reactions,r;r=t.get();)nm(r,a);a.notified=!1,e&&!a.rejection&&NP(a)}))},um=function(a,e,t){var r,i;BP?(r=Xo.createEvent("Event"),r.promise=e,r.reason=t,r.initEvent(a,!1,!0),vt.dispatchEvent(r)):r={promise:e,reason:t},!LP&&(i=vt["on"+a])?i(r):a===rm&&kP("Unhandled promise rejection",t)},NP=function(a){wr(Jf,vt,function(){var e=a.facade,t=a.value,r=Kf(a),i;if(r&&(i=RP(function(){ms?iu.emit("unhandledRejection",t,e):um(rm,e,t)}),a.rejection=ms||Kf(a)?am:au,i.error))throw i.value})},Kf=function(a){return a.rejection!==au&&!a.parent},FP=function(a){wr(Jf,vt,function(){var e=a.facade;ms?iu.emit("rejectionHandled",e):um(OP,e,a.value)})},Pr=function(a,e,t){return function(r){a(e,r,t)}},Ar=function(a,e,t){a.done||(a.done=!0,t&&(a=t),a.value=e,a.state=VP,om(a,!0))},eu=function(a,e,t){if(!a.done){a.done=!0,t&&(a=t);try{if(a.facade===e)throw new tm("Promise can't be resolved itself");var r=sm(e);r?tu(function(){var i={done:!1};try{wr(r,e,Pr(eu,i,a),Pr(Ar,i,a))}catch(s){Ar(i,s,a)}}):(a.value=e,a.state=im,om(a,!1))}catch(i){Ar({done:!1},i,a)}}};if(em&&(Ht=function(e){AP(this,ps),xP(e),wr(hs,this);var t=Jo(this);try{e(Pr(eu,t),Pr(Ar,t))}catch(r){Ar(t,r)}},ps=Ht.prototype,hs=function(e){CP(this,{type:gs,done:!1,notified:!1,parent:!1,reactions:new $P,rejection:!1,state:Yf,value:void 0})},hs.prototype=Gf(ps,"then",function(e,t){var r=Jo(this),i=Zo(wP(this,Ht));return r.parent=!0,i.ok=fs(e)?e:!0,i.fail=fs(t)&&t,i.domain=ms?iu.domain:void 0,r.state===Yf?r.reactions.add(i):tu(function(){nm(i,r)}),i.promise}),Qf=function(){var a=new hs,e=Jo(a);this.promise=a,this.resolve=Pr(eu,e),this.reject=Pr(Ar,e)},Zf.f=Zo=function(a){return a===Ht||a===_P?new Qf(a):DP(a)},!TP&&fs(bs)&&xr!==Object.prototype)){zf=xr.then,MP||Gf(xr,"then",function(e,t){var r=this;return new Ht(function(i,s){wr(zf,r,i,s)}).then(e,t)},{unsafe:!0});try{delete xr.constructor}catch(a){}Wf&&Wf(xr,ps)}yP({global:!0,constructor:!0,wrap:!0,forced:em},{Promise:Ht});IP(Ht,gs,!1,!0);EP(gs)});var fm=m((RC,hm)=>{"use strict";var qP=ie(),dm=qP("iterator"),pm=!1;try{cm=0,su={next:function(){return{done:!!cm++}},return:function(){pm=!0}},su[dm]=function(){return this},Array.from(su,function(){throw 2})}catch(a){}var cm,su;hm.exports=function(a,e){try{if(!e&&!pm)return!1}catch(i){return!1}var t=!1;try{var r={};r[dm]=function(){return{next:function(){return{done:t=!0}}}},a(r)}catch(i){}return t}});var nu=m(($C,mm)=>{"use strict";var UP=Ut(),HP=fm(),jP=Ir().CONSTRUCTOR;mm.exports=jP||!HP(function(a){UP.all(a).then(void 0,function(){})})});var bm=m(()=>{"use strict";var GP=Re(),WP=Te(),YP=et(),QP=Er(),zP=ds(),KP=ss(),JP=nu();GP({target:"Promise",stat:!0,forced:JP},{all:function(e){var t=this,r=QP.f(t),i=r.resolve,s=r.reject,n=zP(function(){var o=YP(t.resolve),u=[],l=0,c=1;KP(e,function(d){var p=l++,h=!1;c++,WP(o,t,d).then(function(f){h||(h=!0,u[p]=f,--c||i(u))},s)}),--c||i(u)});return n.error&&s(n.value),r.promise}})});var Sm=m(()=>{"use strict";var XP=Re(),ZP=Fe(),eA=Ir().CONSTRUCTOR,uu=Ut(),tA=Ze(),rA=Y(),iA=vr(),gm=uu&&uu.prototype;XP({target:"Promise",proto:!0,forced:eA,real:!0},{catch:function(a){return this.then(void 0,a)}});!ZP&&rA(uu)&&(ou=tA("Promise").prototype.catch,gm.catch!==ou&&iA(gm,"catch",ou,{unsafe:!0}));var ou});var vm=m(()=>{"use strict";var aA=Re(),sA=Te(),nA=et(),oA=Er(),uA=ds(),lA=ss(),cA=nu();aA({target:"Promise",stat:!0,forced:cA},{race:function(e){var t=this,r=oA.f(t),i=r.reject,s=uA(function(){var n=nA(t.resolve);lA(e,function(o){sA(n,t,o).then(r.resolve,i)})});return s.error&&i(s.value),r.promise}})});var ym=m(()=>{"use strict";var dA=Re(),pA=Er(),hA=Ir().CONSTRUCTOR;dA({target:"Promise",stat:!0,forced:hA},{reject:function(e){var t=pA.f(this),r=t.reject;return r(e),t.promise}})});var lu=m((NC,Tm)=>{"use strict";var fA=Qe(),mA=we(),bA=Er();Tm.exports=function(a,e){if(fA(a),mA(e)&&e.constructor===a)return e;var t=bA.f(a),r=t.resolve;return r(e),t.promise}});var xm=m(()=>{"use strict";var gA=Re(),SA=Ze(),Im=Fe(),vA=Ut(),Em=Ir().CONSTRUCTOR,yA=lu(),TA=SA("Promise"),IA=Im&&!Em;gA({target:"Promise",stat:!0,forced:Im||Em},{resolve:function(e){return yA(IA&&this===TA?vA:this,e)}})});var Pm=m(()=>{"use strict";lm();bm();Sm();vm();ym();xm()});var Rm=m(()=>{"use strict";var EA=Re(),xA=Fe(),Ss=Ut(),PA=ye(),wm=Ze(),km=Y(),AA=Mo(),Am=lu(),wA=vr(),du=Ss&&Ss.prototype,kA=!!Ss&&PA(function(){du.finally.call({then:function(){}},function(){})});EA({target:"Promise",proto:!0,real:!0,forced:kA},{finally:function(a){var e=AA(this,wm("Promise")),t=km(a);return this.then(t?function(r){return Am(e,a()).then(function(){return r})}:a,t?function(r){return Am(e,a()).then(function(){throw r})}:a)}});!xA&&km(Ss)&&(cu=wm("Promise").prototype.finally,du.finally!==cu&&wA(du,"finally",cu,{unsafe:!0}));var cu});var vs=m((WC,$m)=>{"use strict";var RA=Ze();$m.exports=RA});var Mm=m((YC,Lm)=>{"use strict";Vh();Pm();Rm();var $A=vs();Lm.exports=$A("Promise","finally")});var Dm=m((QC,Cm)=>{"use strict";var LA=Mm();Cm.exports=LA});var ys=m((zC,Bm)=>{"use strict";var MA=Dm();Bm.exports=MA});var nb=m(()=>{"use strict";var ow=Re(),uw=ni(),lw=Ka(),cw=za(),dw=Rn();ow({target:"Array",proto:!0},{at:function(e){var t=uw(this),r=lw(t),i=cw(e),s=i>=0?i:r+i;return s<0||s>=r?void 0:t[s]}});dw("at")});var ub=m((a0,ob)=>{"use strict";nb();var pw=vs();ob.exports=pw("Array","at")});var cb=m((s0,lb)=>{"use strict";var hw=ub();lb.exports=hw});var Ai=m((n0,db)=>{"use strict";var fw=cb();db.exports=fw});var bg=m(()=>{"use strict"});var gg=m(()=>{"use strict"});var vg=m((n_,Sg)=>{"use strict";var yk=we(),Tk=dr(),Ik=ie(),Ek=Ik("match");Sg.exports=function(a){var e;return yk(a)&&((e=a[Ek])!==void 0?!!e:Tk(a)==="RegExp")}});var Tg=m((o_,yg)=>{"use strict";var xk=pi(),Pk=String;yg.exports=function(a){if(xk(a)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return Pk(a)}});var Eg=m((u_,Ig)=>{"use strict";var Ak=Qe();Ig.exports=function(){var a=Ak(this),e="";return a.hasIndices&&(e+="d"),a.global&&(e+="g"),a.ignoreCase&&(e+="i"),a.multiline&&(e+="m"),a.dotAll&&(e+="s"),a.unicode&&(e+="u"),a.unicodeSets&&(e+="v"),a.sticky&&(e+="y"),e}});var Ag=m((l_,Pg)=>{"use strict";var wk=Te(),kk=qe(),Rk=ri(),$k=Eg(),xg=RegExp.prototype;Pg.exports=function(a){var e=a.flags;return e===void 0&&!("flags"in xg)&&!kk(a,"flags")&&Rk(xg,a)?wk($k,a):e}});var kg=m((c_,wg)=>{"use strict";var qu=ce(),Lk=ni(),Mk=Math.floor,Nu=qu("".charAt),Ck=qu("".replace),Fu=qu("".slice),Dk=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,Bk=/\$([$&'`]|\d{1,2})/g;wg.exports=function(a,e,t,r,i,s){var n=t+a.length,o=r.length,u=Bk;return i!==void 0&&(i=Lk(i),u=Dk),Ck(s,u,function(l,c){var d;switch(Nu(c,0)){case"$":return"$";case"&":return a;case"`":return Fu(e,0,t);case"'":return Fu(e,n);case"<":d=i[Fu(c,1,-1)];break;default:var p=+c;if(p===0)return l;if(p>o){var h=Mk(p/10);return h===0?l:h<=o?r[h-1]===void 0?Nu(c,1):r[h-1]+Nu(c,1):l}d=r[p-1]}return d===void 0?"":d})}});var Lg=m(()=>{"use strict";var Ok=Re(),Vk=Te(),Hu=ce(),Rg=ei(),_k=Y(),Nk=pr(),Fk=vg(),_r=Tg(),qk=ai(),Uk=Ag(),Hk=kg(),jk=ie(),Gk=Fe(),Wk=jk("replace"),Yk=TypeError,Uu=Hu("".indexOf),Qk=Hu("".replace),$g=Hu("".slice),zk=Math.max;Ok({target:"String",proto:!0},{replaceAll:function(e,t){var r=Rg(this),i,s,n,o,u,l,c,d,p,h,f=0,b="";if(!Nk(e)){if(i=Fk(e),i&&(s=_r(Rg(Uk(e))),!~Uu(s,"g")))throw new Yk("`.replaceAll` does not allow non-global regexes");if(n=qk(e,Wk),n)return Vk(n,e,r,t);if(Gk&&i)return Qk(_r(r),e,t)}for(o=_r(r),u=_r(e),l=_k(t),l||(t=_r(t)),c=u.length,d=zk(1,c),p=Uu(o,u);p!==-1;)h=l?_r(t(u,p,o)):Hk(u,o,p,[],void 0,t),b+=$g(o,f,p)+h,f=p+c,p=p+d>o.length?-1:Uu(o,u,p+d);return f<o.length&&(b+=$g(o,f)),b}})});var Cg=m((h_,Mg)=>{"use strict";bg();gg();Lg();var Kk=vs();Mg.exports=Kk("String","replaceAll")});var Bg=m((f_,Dg)=>{"use strict";var Jk=Cg();Dg.exports=Jk});var Vg=m((m_,Og)=>{"use strict";var Xk=Bg();Og.exports=Xk});var ec="2.0.111-dev.ae3e5b42.0";var le=(i=>(i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused",i))(le||{}),St=(S=>(S.MPEG="MPEG",S.DASH="DASH",S.DASH_SEP="DASH_SEP",S.DASH_SEP_VK="DASH_SEP",S.DASH_WEBM="DASH_WEBM",S.DASH_WEBM_AV1="DASH_WEBM_AV1",S.DASH_STREAMS="DASH_STREAMS",S.DASH_WEBM_VK="DASH_WEBM",S.DASH_ONDEMAND="DASH_ONDEMAND",S.DASH_ONDEMAND_VK="DASH_ONDEMAND",S.DASH_LIVE="DASH_LIVE",S.DASH_LIVE_CMAF="DASH_LIVE_CMAF",S.DASH_LIVE_WEBM="DASH_LIVE_WEBM",S.HLS="HLS",S.HLS_ONDEMAND="HLS_ONDEMAND",S.HLS_JS="HLS",S.HLS_LIVE="HLS_LIVE",S.HLS_LIVE_CMAF="HLS_LIVE_CMAF",S.WEB_RTC_LIVE="WEB_RTC_LIVE",S))(St||{});var Va=(i=>(i.NOT_AVAILABLE="NOT_AVAILABLE",i.AVAILABLE="AVAILABLE",i.CONNECTING="CONNECTING",i.CONNECTED="CONNECTED",i))(Va||{}),En=(r=>(r.HTTP1="http1",r.HTTP2="http2",r.QUIC="quic",r))(En||{});var xn=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(xn||{});import{assertNever as nc,assertNonNullable as Sv,isNonNullable as _a,ValueSubject as Pn,Subject as vv,Subscription as yv,merge as Tv,observableFrom as Iv,fromEvent as rc,map as ic,tap as ac,filterChanged as Ev,isNullable as An,ErrorCategory as sc}from"@vkontakte/videoplayer-shared";var tc=a=>new Promise((e,t)=>{let r=document.createElement("script");r.setAttribute("src",a),r.onload=()=>e,r.onerror=()=>t,document.body.appendChild(r)});var Na=class{constructor(e){this.connection$=new Pn(void 0);this.castState$=new Pn("NOT_AVAILABLE");this.errorEvent$=new vv;this.realCastState$=new Pn("NOT_AVAILABLE");this.subscription=new yv;var s;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastInitializer");let t="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${t}`}),e.isDisabled||!t)return;let r=_a((s=window.chrome)==null?void 0:s.cast),i=!!window.__onGCastApiAvailable;r?this.initializeCastApi():(window.__onGCastApiAvailable=n=>{delete window.__onGCastApiAvailable,n&&this.initializeCastApi()},i||tc("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:sc.NETWORK,message:"Script loading failed!"})))}connect(){var e;(e=cast.framework.CastContext.getInstance())==null||e.requestSession()}disconnect(){var e,t;(t=(e=cast.framework.CastContext.getInstance())==null?void 0:e.getCurrentSession())==null||t.endSession(!0)}stopMedia(){return new Promise((e,t)=>{var r,i,s;(s=(i=(r=cast.framework.CastContext.getInstance())==null?void 0:r.getCurrentSession())==null?void 0:i.getMediaSession())==null||s.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){_a(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();An(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();An(t)||e!==t.remotePlayer.isMuted&&t.remotePlayerController.muteOrUnmute()}destroy(){this.subscription.unsubscribe()}initListeners(){let e=new cast.framework.RemotePlayer,t=new cast.framework.RemotePlayerController(e),r=cast.framework.CastContext.getInstance();this.subscription.add(rc(r,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(i=>{var s,n,o;switch(i.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=(o=(n=(s=r.getCurrentSession())==null?void 0:s.getMediaSession())==null?void 0:n.media)==null?void 0:o.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return nc(i.sessionState)}})).add(Tv(rc(r,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(ac(i=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(i)}`})}),ic(i=>i.castState)),Iv([r.getCastState()])).pipe(Ev(),ic(xv),ac(i=>{this.log({message:`realCastState$: ${i}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(i=>{var o,u;let s=i==="CONNECTED",n=_a(this.connection$.getValue());if(s&&!n){let l=r.getCurrentSession();Sv(l);let c=l.getCastDevice(),d=(u=(o=l.getMediaSession())==null?void 0:o.media)==null?void 0:u.contentId;(An(d)||d===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:l,castDevice:c}))}else!s&&n&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(i==="CONNECTED"?_a(this.connection$.getValue())?"CONNECTED":"AVAILABLE":i)}))}initializeCastApi(){var i;let e,t,r;try{e=cast.framework.CastContext.getInstance(),t=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,r=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch(s){return}try{e.setOptions({receiverApplicationId:(i=this.params.receiverApplicationId)!=null?i:t,autoJoinPolicy:r}),this.initListeners()}catch(s){this.errorEvent$.next({id:"ChromecastInitializer",category:sc.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:s})}}},xv=a=>{switch(a){case cast.framework.CastState.NO_DEVICES_AVAILABLE:return"NOT_AVAILABLE";case cast.framework.CastState.NOT_CONNECTED:return"AVAILABLE";case cast.framework.CastState.CONNECTING:return"CONNECTING";case cast.framework.CastState.CONNECTED:return"CONNECTED";default:return nc(a)}};var DS=Ye(wo(),1);var Gm=Ye(ys(),1);import{assertNever as Om}from"@vkontakte/videoplayer-shared";var ee=(a,e=0,t=0)=>{switch(t){case 0:return a.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case 1:{if(e===0)return a;let r=new URL(a);return r.searchParams.append("playback_shift",e.toFixed(0)),r.toString()}case 2:{let r=new URL(a);return!r.searchParams.get("offset_p")&&e===0?a:(r.searchParams.set("offset_p",e.toFixed(0)),r.toString())}default:Om(t)}return a},pu=(a,e)=>{var t;switch(e){case 0:return NaN;case 1:{let r=new URL(a);return Number(r.searchParams.get("playback_shift"))}case 2:{let r=new URL(a);return Number((t=r.searchParams.get("offset_p"))!=null?t:0)}default:Om(e)}};var E=(a,e,t=!1)=>{let r=a.getTransition();(t||!r||r.to===e)&&a.setState(e)};import{isNonNullable as CA,Subject as Ts,merge as Vm}from"@vkontakte/videoplayer-shared";var M=class{constructor(e){this.transitionStarted$=new Ts;this.transitionEnded$=new Ts;this.transitionUpdated$=new Ts;this.forceChanged$=new Ts;this.stateChangeStarted$=Vm(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=Vm(this.transitionEnded$,this.forceChanged$);this.state=e,this.prevState=void 0}setState(e){let t=this.transition,r=this.state;this.transition=void 0,this.prevState=r,this.state=e,t?t.to===e?this.transitionEnded$.next(t):this.forceChanged$.next({from:t.from,to:e,canceledTransition:t}):this.forceChanged$.next({from:r,to:e,canceledTransition:t})}startTransitionTo(e){let t=this.transition,r=this.state;r===e||CA(t)&&t.to===e||(this.prevState=r,this.state=e,t?(this.transition={from:t.from,to:e,canceledTransition:t},this.transitionUpdated$.next(this.transition)):(this.transition={from:r,to:e},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}getPrevState(){return this.prevState}};import{assertNever as DA}from"@vkontakte/videoplayer-shared";var _m=a=>{switch(a){case"MPEG":case"DASH":case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":case"HLS":case"HLS_ONDEMAND":return!1;case"DASH_LIVE":case"DASH_LIVE_CMAF":case"HLS_LIVE":case"HLS_LIVE_CMAF":case"DASH_LIVE_WEBM":case"WEB_RTC_LIVE":return!0;default:return DA(a)}};import{assertNever as kr,assertNonNullable as jt,debounce as Nm,ErrorCategory as Fm,fromEvent as Gt,isNonNullable as qm,map as Um,merge as Hm,observableFrom as BA,Subject as OA,Subscription as hu,timeout as VA,getHighestQuality as _A}from"@vkontakte/videoplayer-shared";var NA=5,FA=5,qA=500,jm=7e3,Ei=class{constructor(e){this.subscription=new hu;this.loadMediaTimeoutSubscription=new hu;this.videoState=new M("stopped");this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),r=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${r}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(s)};`}),r==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.stop());return}if(!t){if((i==null?void 0:i.to)!=="paused"&&s.state==="requested"&&e!=="stopped"){this.seek(s.position/1e3);return}switch(r){case"ready":{switch(e){case"playing":case"paused":case"ready":break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:kr(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:kr(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:kr(e)}break}default:kr(r)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(_m(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 hu;this.subscription.add(e),this.subscription.add(Hm(this.videoState.stateChangeStarted$.pipe(Um(i=>`stateChangeStarted$ ${JSON.stringify(i)}`)),this.videoState.stateChangeEnded$.pipe(Um(i=>`stateChangeEnded$ ${JSON.stringify(i)}`))).subscribe(i=>this.log({message:`[videoState] ${i}`})));let t=(i,s)=>this.subscription.add(i.subscribe(s));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{let i=new OA;e.add(i.pipe(Nm(qA)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add(Gt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe(n=>{this.logRemoteEvent(n);let o=n.value;this.params.output.position$.next(o),(this.params.desiredState.seekState.getState().state==="applying"||Math.abs(o-s)>NA)&&i.next(o),s=o})),e.add(Gt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(Gt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),i=>{this.logRemoteEvent(i),i.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(Gt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),i=>{this.logRemoteEvent(i),i.value?this.handleRemotePause():this.handleRemotePlay()}),t(Gt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),i=>{this.logRemoteEvent(i);let{remotePlayer:s}=this.params.connection,n=i.value,o=this.params.output.isBuffering$.getValue(),u=n===chrome.cast.media.PlayerState.BUFFERING;switch(o!==u&&this.params.output.isBuffering$.next(u),n){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&s.duration-s.currentTime<FA&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),E(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:kr(n)}}),t(Gt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),i=>{this.logRemoteEvent(i),this.handleRemoteVolumeChange({volume:i.value})}),t(Gt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),i=>{this.logRemoteEvent(i),this.handleRemoteVolumeChange({muted:i.value})});let r=Hm(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,BA(["init"])).pipe(Nm(0));t(r,this.syncPlayback)}restoreSession(e){this.log({message:"restoreSession"});let{remotePlayer:t}=this.params.connection;if(e.playerState!==chrome.cast.media.PlayerState.IDLE){t.isPaused?(this.videoState.setState("paused"),E(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),E(this.params.desiredState.playbackState,"playing"));let r=this.params.output.isLive$.getValue();this.params.output.duration$.next(r?0:t.duration),this.params.output.position$.next(r?0:t.currentTime),this.params.desiredState.seekState.setState({state:"none"})}}prepare(){let e=this.params.format;this.log({message:`[prepare] format: ${e}`});let t=this.createMediaInfo(e),r=this.createLoadRequest(t);this.loadMedia(r)}handleRemotePause(){let e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)==="paused"||e==="playing")&&(this.videoState.setState("paused"),E(this.params.desiredState.playbackState,"paused"))}handleRemotePlay(){let e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)==="playing"||e==="paused")&&(this.videoState.setState("playing"),E(this.params.desiredState.playbackState,"playing"))}handleRemoteReady(){var t;let e=this.videoState.getTransition();(e==null?void 0:e.to)==="ready"&&this.videoState.setState("ready"),((t=this.params.desiredState.playbackState.getTransition())==null?void 0:t.to)==="ready"&&E(this.params.desiredState.playbackState,"ready")}handleRemoteStop(){this.videoState.getState()!=="stopped"&&this.videoState.setState("stopped")}handleRemoteVolumeChange(e){var i,s;let t=this.params.output.volume$.getValue(),r={volume:(i=e.volume)!=null?i:t.volume,muted:(s=e.muted)!=null?s:t.muted};(r.volume!==t.volume||r.muted!==r.muted)&&this.params.output.volume$.next(r)}seek(e){this.params.output.willSeekEvent$.next();let{remotePlayer:t,remotePlayerController:r}=this.params.connection;t.currentTime=e,r.seek()}stop(){let{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){var l;let t=this.params.source,r,i,s;switch(e){case"MPEG":{let c=t[e];jt(c);let d=_A(Object.keys(c));jt(d);let p=c[d];jt(p),r=p,i="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let c=t[e];jt(c),r=c.url,i="application/x-mpegurl",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":{let c=t[e];jt(c),r=c.url,i="application/dash+xml",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let c=t[e];jt(c),r=c.url,i="application/dash+xml",s=chrome.cast.media.StreamType.LIVE;break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let c=t[e];jt(c),r=ee(c.url),i="application/x-mpegurl",s=chrome.cast.media.StreamType.LIVE;break}case"DASH_LIVE":case"WEB_RTC_LIVE":{let c="Unsupported format for Chromecast",d=new Error(c);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:Fm.VIDEO_PIPELINE,message:c,thrown:d}),d}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return kr(e)}let n=new chrome.cast.media.MediaInfo((l=this.params.meta.videoId)!=null?l:r,i);n.contentUrl=r,n.streamType=s,n.metadata=new chrome.cast.media.GenericMediaMetadata;let{title:o,subtitle:u}=this.params.meta;return qm(o)&&(n.metadata.title=o),qm(u)&&(n.metadata.subtitle=u),n}createLoadRequest(e){let t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;let r=this.params.desiredState.seekState.getState();return r.state==="applying"||r.state==="requested"?t.currentTime=this.params.output.isLive$.getValue()?0:r.position/1e3:t.currentTime=0,t}loadMedia(e){let t=this.params.connection.session.loadMedia(e),r=new Promise((i,s)=>{this.loadMediaTimeoutSubscription.add(VA(jm).subscribe(()=>s(`timeout(${jm})`)))});(0,Gm.default)(Promise.race([t,r]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},i=>{let s=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${i}`;this.log({message:s}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:Fm.VIDEO_PIPELINE,message:s,thrown:i})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};import{clearVideoElement as Ym}from"@vkontakte/videoplayer-shared";import{clearVideoElement as UA}from"@vkontakte/videoplayer-shared";var Wm=a=>{try{a.pause(),a.playbackRate=0,UA(a),a.remove()}catch(e){console.error(e)}};import{fromEvent as HA,Subscription as jA}from"@vkontakte/videoplayer-shared";var fu=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)}},mu=window.WeakMap?new WeakMap:new fu,bu=window.WeakMap?new WeakMap:new Map,GA=(a,e=20)=>{let t=0;return HA(a,"ratechange").subscribe(r=>{t++,t>=e&&(a.currentTime=a.currentTime,t=0)})},de=(a,{audioVideoSyncRate:e})=>{let t=a.querySelector("video"),r=!!t;t?Ym(t):(t=document.createElement("video"),a.appendChild(t)),mu.set(t,r);let i=new jA;return i.add(GA(t,e)),bu.set(t,i),t.setAttribute("crossorigin","anonymous"),t.setAttribute("playsinline","playsinline"),t.controls=!1,t.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),t},pe=a=>{let e=bu.get(a);e==null||e.unsubscribe(),bu.delete(a);let t=mu.get(a);mu.delete(a),t?Ym(a):Wm(a)};import{assertNonNullable as xi,isNonNullable as Ke,isNullable as QA,fromEvent as Rr,merge as Qm,observableFrom as zm,filterChanged as Km,map as Pi,Subject as Jm,Subscription as zA,ValueSubject as KA,ErrorCategory as JA}from"@vkontakte/videoplayer-shared";import{isNonNullable as gu,isNullable as WA,Subscription as YA}from"@vkontakte/videoplayer-shared";var Is=(a,e,t,{equal:r=(n,o)=>n===o,changed$:i,onError:s}={})=>{let n=a.getState(),o=e(),u=WA(i),l=new YA;return i&&l.add(i.subscribe(c=>{let d=a.getState();r(c,d)&&a.setState(c)},s)),r(o,n)||(t(n),u&&a.setState(n)),l.add(a.stateChangeStarted$.subscribe(c=>{t(c.to),u&&a.setState(c.to)},s)),l},ze=(a,e,t)=>Is(e,()=>a.loop,r=>{gu(r)&&(a.loop=r)},{onError:t}),he=(a,e,t,r)=>Is(e,()=>({muted:a.muted,volume:a.volume}),i=>{gu(i)&&(a.muted=i.muted,a.volume=i.volume)},{equal:(i,s)=>i===s||(i==null?void 0:i.muted)===(s==null?void 0:s.muted)&&(i==null?void 0:i.volume)===(s==null?void 0:s.volume),changed$:t,onError:r}),$e=(a,e,t,r)=>Is(e,()=>a.playbackRate,i=>{gu(i)&&(a.playbackRate=i)},{changed$:t,onError:r}),yt=Is;var XA=a=>["__",a.language,a.label].join("|"),ZA=(a,e)=>{if(a.id===e)return!0;let[t,r,i]=e.split("|");return a.language===r&&a.label===i},Su=class a{constructor(){this.available$=new Jm;this.current$=new KA(void 0);this.error$=new Jm;this.subscription=new zA;this.externalTracks=new Map;this.internalTracks=new Map}connect(e,t,r){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();let i=s=>{this.error$.next({id:"TextTracksManager",category:JA.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:s})};this.subscription.add(this.available$.subscribe(r.availableTextTracks$)),this.subscription.add(this.current$.subscribe(r.currentTextTrack$)),this.subscription.add(this.error$.subscribe(r.error$)),this.subscription.add(yt(t.internalTextTracks,()=>Object.values(this.internalTracks),s=>{Ke(s)&&this.setInternal(s)},{equal:(s,n)=>Ke(s)&&Ke(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(Pi(s=>s.filter(({type:n})=>n==="internal"))),onError:i})),this.subscription.add(yt(t.externalTextTracks,()=>Object.values(this.externalTracks),s=>{Ke(s)&&this.setExternal(s)},{equal:(s,n)=>Ke(s)&&Ke(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(Pi(s=>s.filter(({type:n})=>n==="external"))),onError:i})),this.subscription.add(yt(t.currentTextTrack,()=>{if(this.video)return;let s=this.htmlTextTracksAsArray().find(({mode:n})=>n==="showing");return s&&this.htmlTextTrackToITextTrack(s).id},s=>this.select(s),{changed$:this.current$,onError:i})),this.subscription.add(yt(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.activeCues)}))}subscribe(){xi(this.video);let{textTracks:e}=this.video;this.subscription.add(Rr(e,"addtrack").subscribe(()=>{let r=this.current$.getValue();r&&this.select(r)})),this.subscription.add(Qm(Rr(e,"addtrack"),Rr(e,"removetrack"),zm(["init"])).pipe(Pi(()=>this.htmlTextTracksAsArray().map(r=>this.htmlTextTrackToITextTrack(r))),Km((r,i)=>r.length===i.length&&r.every(({id:s},n)=>s===i[n].id))).subscribe(this.available$)),this.subscription.add(Qm(Rr(e,"change"),zm(["init"])).pipe(Pi(()=>this.htmlTextTracksAsArray().find(({mode:r})=>r==="showing")),Pi(r=>r&&this.htmlTextTrackToITextTrack(r).id),Km()).subscribe(this.current$));let t=r=>{var i,s;return this.applyCueSettings((s=(i=r.target)==null?void 0:i.activeCues)!=null?s:null)};this.subscription.add(Rr(e,"addtrack").subscribe(r=>{var s,n;(s=r.track)==null||s.addEventListener("cuechange",t);let i=o=>{var l,c,d,p,h;let u=(c=(l=o.target)==null?void 0:l.cues)!=null?c:null;u&&u.length&&(this.applyCueSettings((p=(d=o.target)==null?void 0:d.cues)!=null?p:null),(h=o.target)==null||h.removeEventListener("cuechange",i))};(n=r.track)==null||n.addEventListener("cuechange",i)})),this.subscription.add(Rr(e,"removetrack").subscribe(r=>{var i;(i=r.track)==null||i.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;let t=this.cueSettings.getState();for(let r of Array.from(e)){let i=r;Ke(t.align)&&(i.align=t.align),Ke(t.position)&&(i.position=t.position),Ke(t.size)&&(i.size=t.size),Ke(t.line)&&(i.line=t.line)}}htmlTextTracksAsArray(e=!1){xi(this.video);let t=[...this.video.textTracks];return e?t:t.filter(a.isHealthyTrack)}htmlTextTrackToITextTrack(e){var o,u;let{language:t,label:r}=e,i=e.id?e.id:XA(e),s=this.externalTracks.has(i),n=i.includes("auto");return s?{id:i,type:"external",isAuto:n,language:t,label:r,url:(o=this.externalTracks.get(i))==null?void 0:o.url}:{id:i,type:"internal",isAuto:n,language:t,label:r,url:(u=this.internalTracks.get(i))==null?void 0:u.url}}static isHealthyTrack(e){return!(e.kind==="metadata"||e.groupId||e.id===""&&e.label===""&&e.language==="")}setExternal(e){this.internalTracks.size>0&&Array.from(this.internalTracks).forEach(([,t])=>this.detach(t)),e.filter(({id:t})=>!this.externalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.externalTracks).filter(([t])=>!e.find(r=>r.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){let t=[...this.externalTracks];e.filter(({id:r,language:i,isAuto:s})=>!this.internalTracks.has(r)&&!t.some(([,n])=>n.language===i&&n.isAuto===s)).forEach(r=>this.attach(r)),Array.from(this.internalTracks).filter(([r])=>!e.find(i=>i.id===r)).forEach(([,r])=>this.detach(r))}select(e){xi(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(QA(e)||!ZA(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){xi(this.video);let t=document.createElement("track");t.setAttribute("src",e.url),t.setAttribute("id",e.id),e.label&&t.setAttribute("label",e.label),e.language&&t.setAttribute("srclang",e.language),e.type==="external"?this.externalTracks.set(e.id,e):e.type==="internal"&&this.internalTracks.set(e.id,e),this.video.appendChild(t)}detach(e){xi(this.video);let t=Array.prototype.find.call(this.video.getElementsByTagName("track"),r=>r.getAttribute("id")===e.id);t&&this.video.removeChild(t),e.type==="external"?this.externalTracks.delete(e.id):e.type==="internal"&&this.internalTracks.delete(e.id)}},Je=Su;var it=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 Xm=a=>{let e=a;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e==null?void 0:e.parentNode;return e!=null?e:void 0},vu=a=>{let e=Xm(a);return!!(e&&e.fullscreenElement&&e.fullscreenElement===a)},Zm=a=>{let e=Xm(a);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===a)};import{fromEvent as Le,map as Tt,merge as tb,filterChanged as tw,isNonNullable as rb,Subject as rw,filter as ib,mapTo as ab,combine as iw,once as aw,ErrorCategory as sw,ValueSubject as sb,clientChecker as nw}from"@vkontakte/videoplayer-shared";var ew=3,eb=(a,e,t=ew)=>{let r=0,i=0;for(let s=0;s<a.length;s++){let n=a.start(s),o=a.end(s);if(n<=e&&e<=o){if(r=n,i=o,!t)return{from:r,to:i};for(let u=s-1;u>=0;u--)a.end(u)+t>=r&&(r=a.start(u));for(let u=s+1;u<a.length;u++)a.start(u)-t<=i&&(i=a.end(u))}}return{from:r,to:i}};var fe=a=>{let e=S=>Le(a,S).pipe(ab(void 0)),r=tb(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(S=>Le(a,S))).pipe(Tt(S=>S.type==="ended"?a.readyState<2:a.readyState<3),tw()),i=tb(Le(a,"progress"),Le(a,"timeupdate")).pipe(Tt(()=>eb(a.buffered,a.currentTime))),s=nw.isSafari?iw({play:e("play").pipe(aw()),playing:e("playing")}).pipe(ab(void 0)):e("playing"),n=Le(a,"volumechange").pipe(Tt(()=>({muted:a.muted,volume:a.volume}))),o=Le(a,"ratechange").pipe(Tt(()=>a.playbackRate)),u=Le(a,"error").pipe(ib(()=>!!(a.error||a.played.length)),Tt(()=>{var v;let S=a.error;return{id:S?`MediaError#${S.code}`:"HtmlVideoError",category:sw.VIDEO_PIPELINE,message:S?S.message:"Error event from HTML video element",thrown:(v=a.error)!=null?v:void 0}})),l=Le(a,"timeupdate").pipe(Tt(()=>a.currentTime)),c=new rw,d=.3,p;l.subscribe(S=>{a.loop&&rb(p)&&rb(S)&&p>=a.duration-d&&S<=d&&c.next(p),p=S});let h=e("pause").pipe(ib(()=>!a.error&&p!==a.duration)),f=Le(a,"enterpictureinpicture"),b=Le(a,"leavepictureinpicture"),g=new sb(Zm(a));f.subscribe(()=>g.next(!0)),b.subscribe(()=>g.next(!1));let y=new sb(vu(a));return Le(a,"fullscreenchange").pipe(Tt(()=>vu(a))).subscribe(y),{playing$:s,pause$:h,canplay$:e("canplay"),ended$:e("ended"),looped$:c,error$:u,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:l,durationChange$:Le(a,"durationchange").pipe(Tt(()=>a.duration)),isBuffering$:r,currentBuffer$:i,volumeState$:n,playbackRateState$:o,inPiP$:g,inFullscreen$:y}};import{VideoQuality as It}from"@vkontakte/videoplayer-shared";var Et=a=>{switch(a){case"mobile":return It.Q_144P;case"lowest":return It.Q_240P;case"low":return It.Q_360P;case"sd":case"medium":return It.Q_480P;case"hd":case"high":return It.Q_720P;case"fullhd":case"full":return It.Q_1080P;case"quadhd":case"quad":return It.Q_1440P;case"ultrahd":case"ultra":return It.Q_2160P}};var Wt=Ye(Ai(),1);import{isNonNullable as me,isNullable as Tu,now as vb,isHigher as Iu,isHigherOrEqual as mb,isInvariantQuality as bb,isLower as Eu,isLowerOrEqual as gb,videoSizeToQuality as mw,assertNotEmptyArray as yb,assertNonNullable as bw}from"@vkontakte/videoplayer-shared";var yu=!1,at={},pb=a=>{yu=a},hb=()=>{at={}},fb=a=>{a(at)},wi=(a,e)=>{var t;yu&&(at.meta=(t=at.meta)!=null?t:{},at.meta[a]=e)},ae=class{constructor(e){this.name=e}next(e){var r,i;if(!yu)return;at.series=(r=at.series)!=null?r:{};let t=(i=at.series[this.name])!=null?i:[];t.push([Date.now(),e]),at.series[this.name]=t}};var gw=new ae("best_bitrate"),Tb=(a,e,t)=>(e-t)*Math.pow(2,-10*a)+t;var xu=a=>(e,t)=>a*(Number(e.bitrate)-Number(t.bitrate)),ki=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=vb()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},Ib='Assertion "ABR Tracks is empty array" failed',Es=(a,e,t,r)=>{var u;let i=[...e].sort(xu(1)),s=[...t].sort(xu(1)),n=s.filter(l=>me(l.bitrate)&&me(a.bitrate)?a.bitrate/l.bitrate>r:!0),o=(u=(0,Wt.default)(s,Math.round(s.length*i.indexOf(a)/(i.length+1))))!=null?u:(0,Wt.default)(s,-1);return o&&n.includes(o)?o:n.length?(0,Wt.default)(n,-1):(0,Wt.default)(s,0)},Sb=a=>"quality"in a,Eb=(a,e,t,r)=>{let i=t&&r&&r.history[t.id]&&vb()-r.history[t.id]<=a.trackCooldown&&(!r.last||t.id!==r.last.id);if(t!=null&&t.id&&r&&!i&&r.recordSelection(t),i&&(r!=null&&r.last)){let s=r.last;r==null||r.recordSwitch(s);let n=Sb(s)?"video":"audio",o=Sb(s)?s.quality:s.bitrate;return e({message:`
|
|
7
7
|
[last ${n} selected] ${o}
|
|
8
|
-
`}),s}return r==null||r.recordSwitch(t),t},
|
|
8
|
+
`}),s}return r==null||r.recordSwitch(t),t},xt=(a,{container:e,throughput:t,tuning:r,limits:i,reserve:s=0,forwardBufferHealth:n,playbackRate:o,current:u,history:l,visible:c,droppedVideoMaxQualityLimit:d,abrLogger:p})=>{var N,O,w,L,q;yb(a,Ib);let h=r.usePixelRatio&&(N=window.devicePixelRatio)!=null?N:1,f=r.limitByContainer&&e&&e.width>0&&e.height>0&&{width:e.width*h*r.containerSizeFactor,height:e.height*h*r.containerSizeFactor},b=f&&mw(f),g=r.considerPlaybackRate&&me(o)?o:1,y=a.filter(k=>!bb(k.quality)).sort((k,x)=>Iu(k.quality,x.quality)?-1:1),I=(O=(0,Wt.default)(y,-1))==null?void 0:O.quality,S=(w=(0,Wt.default)(y,0))==null?void 0:w.quality,v=Tu(i)||me(i.min)&&me(i.max)&&Eu(i.max,i.min)||me(i.min)&&S&&Iu(i.min,S)||me(i.max)&&I&&Eu(i.max,I),T=g*Tb(n!=null?n:.5,r.bitrateFactorAtEmptyBuffer,r.bitrateFactorAtFullBuffer),R={},$=y.filter(k=>{if(!(b?Eu(k.quality,b):!0))return R[k.quality]="FitsContainer",!1;if(!(me(t)&&isFinite(t)&&me(k.bitrate)?t-s>=k.bitrate*T:!0))return R[k.quality]="FitsThroughput",!1;if(r.lazyQualitySwitch&&me(r.minBufferToSwitchUp)&&u&&!bb(u.quality)&&(n!=null?n:0)<r.minBufferToSwitchUp&&Iu(k.quality,u.quality))return R[k.quality]="Buffer",!1;if(!!d&&mb(k.quality,d))return R[k.quality]="DroppedFramesLimit",!1;let K=v||(Tu(i.max)||gb(k.quality,i.max))&&(Tu(i.min)||mb(k.quality,i.min)),ne=me(c)&&!c?gb(k.quality,r.backgroundVideoQualityLimit):!0;return!K||!ne?(R[k.quality]="FitsQualityLimits",!1):!0})[0];$&&$.bitrate&&gw.next($.bitrate);let B=(L=$!=null?$:y[Math.ceil((y.length-1)/2)])!=null?L:a[0];return B.quality!==((q=l==null?void 0:l.last)==null?void 0:q.quality)&&p({message:`
|
|
9
9
|
[VIDEO TRACKS ABR]
|
|
10
10
|
[available video tracks]
|
|
11
11
|
${a.map(k=>`{ id: ${k.id}, quality: ${k.quality}, bitrate: ${k.bitrate} }`).join(`
|
|
@@ -35,7 +35,7 @@ var tv=Object.create;var Cc=Object.defineProperty;var rv=Object.getOwnPropertyDe
|
|
|
35
35
|
|
|
36
36
|
[best video track] ${$==null?void 0:$.quality}
|
|
37
37
|
[selected video track] ${B==null?void 0:B.quality}
|
|
38
|
-
`}),
|
|
38
|
+
`}),Eb(r,p,B,l)},xb=(a,e,t,{throughput:r,tuning:i,playbackRate:s,forwardBufferHealth:n,history:o,abrLogger:u})=>{var f;yb(t,Ib);let l=i.considerPlaybackRate&&me(s)?s:1,c=[...t].sort(xu(-1)),d=a.bitrate;bw(d);let p=l*Tb(n!=null?n:.5,i.bitrateAudioFactorAtEmptyBuffer,i.bitrateAudioFactorAtFullBuffer),h;return me(r)&&isFinite(r)&&(h=c.find(b=>me(b.bitrate)?r-d>=b.bitrate*p:!0)),h||(h=Es(a,e,t,i.minVideoAudioRatio)),(h==null?void 0:h.bitrate)!==((f=o==null?void 0:o.last)==null?void 0:f.bitrate)&&u({message:`
|
|
39
39
|
[AUDIO TRACKS ABR]
|
|
40
40
|
[available audio tracks]
|
|
41
41
|
${t.map(b=>`{ id: ${b.id}, bitrate: ${b.bitrate} }`).join(`
|
|
@@ -49,13 +49,13 @@ var tv=Object.create;var Cc=Object.defineProperty;var rv=Object.getOwnPropertyDe
|
|
|
49
49
|
throughput: ${r},
|
|
50
50
|
reserve: ${d},
|
|
51
51
|
playbackRate: ${s},
|
|
52
|
-
playbackRateFactor: ${
|
|
52
|
+
playbackRateFactor: ${l},
|
|
53
53
|
forwardBufferHealth: ${n},
|
|
54
54
|
bitrateFactor: ${p},
|
|
55
55
|
minBufferToSwitchUp: ${i.minBufferToSwitchUp},
|
|
56
56
|
|
|
57
57
|
[selected audio track] ${h==null?void 0:h.id}
|
|
58
|
-
`}),h&&ib(i,u,h,o)};var X=a=>new URL(a).hostname;import{assertNever as lb,assertNonNullable as db,combine as Aw,debounce as ww,ErrorCategory as pb,filter as hb,filterChanged as kw,isNonNullable as gu,map as ds,merge as fb,observableFrom as Rw,once as $w,Subscription as Lw,ValueSubject as Su,videoQualityToHeight as Mw,videoSizeToQuality as Cw}from"@vkontakte/videoplayer-shared";var sb=a=>{if(a instanceof DOMException&&["Failed to load because no supported source was found.","The element has no supported sources."].includes(a.message))throw a;return!(a instanceof DOMException&&(a.code===20||a.name==="AbortError"))},me=async a=>{let e=a.muted;try{await a.play()}catch(t){if(!sb(t))return!1;if(e)return console.warn(t),!1;a.muted=!0;try{await a.play()}catch(r){return sb(r)&&(a.muted=!1,console.warn(r)),!1}}return!0};import{isNonNullable as us,isNullable as cw,assertNonNullable as vi}from"@vkontakte/videoplayer-shared";import{isNonNullable as nb,assertNonNullable as os,now as ow}from"@vkontakte/videoplayer-shared";function Z(){return ow()}function hu(a){return Z()-a}function fu(a){let e=a.split("/"),t=e.slice(0,e.length-1).join("/"),r=/^([a-z]+:)?\/\//i,i=n=>r.test(n);return{resolve:(n,o,u=!1)=>{i(n)||(n.startsWith("/")||(n="/"+n),n=t+n);let c=n.indexOf("?")>-1?"&":"?";return u&&(n+=c+"lowLat=1",c="&"),o&&(n+=c+"_rnd="+Math.floor(999999999*Math.random())),n}}}function ob(a,e,t){let r=(...i)=>{t.apply(null,i),a.removeEventListener(e,r)};a.addEventListener(e,r)}function yr(a,e,t,r){let i=window.XMLHttpRequest,s,n,o,u=!1,c=0,l,d,p=!1,h="arraybuffer",f=7e3,b=2e3,g=()=>{if(u)return;os(l);let w=hu(l),L;if(w<b){L=b-w,setTimeout(g,L);return}b*=2,b>f&&(b=f),n&&n.abort(),n=new i,R()},y=w=>(s=w,O),I=w=>(d=w,O),S=()=>(h="json",O),v=()=>{if(!u){if(--c>=0){g(),r&&r();return}u=!0,d&&d(),t&&t()}},T=w=>(p=w,O),R=()=>{l=Z(),n=new i,n.open("get",a);let w=0,L,q=0,k=()=>(os(l),Math.max(l,Math.max(L||0,q||0)));if(s&&n.addEventListener("progress",x=>{let V=Z();s.updateChunk&&x.loaded>w&&(s.updateChunk(k(),x.loaded-w),w=x.loaded,L=V)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>v())),n.addEventListener("load",()=>{if(u)return;os(n);let x=n.status;if(x>=200&&x<300){if(n.response.byteLength&&s){let V=n.response.byteLength-w;V&&s.updateChunk&&s.updateChunk(k(),V)}n.responseType==="json"&&!Object.values(n.response).length?v():(d&&d(),e(n.response))}else v()}),n.addEventListener("error",()=>{v()}),p){let x=()=>{os(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(q=Z(),n.removeEventListener("readystatechange",x))};n.addEventListener("readystatechange",x)}return n.responseType=h,n.send(),O},O={withBitrateReporting:y,withParallel:T,withJSONResponse:S,withRetryCount:w=>(c=w,O),withRetryInterval:(w,L)=>(nb(w)&&(b=w),nb(L)&&(f=L),O),withTimeout:w=>(o=w,O),withFinally:I,send:R,abort:()=>{n&&(n.abort(),n=void 0),u=!0,d&&d()}};return O}var gi=class{constructor(e){this.intervals=[];this.currentRate=0;this.logger=e}_updateRate(e){let t=.2;this.currentRate&&(e<this.currentRate*.1?t=.8:e<this.currentRate*.5?t=.5:e<this.currentRate*.7&&(t=.3)),e=Math.max(1,Math.min(e,100*1024*1024)),this.currentRate=this.currentRate?this.currentRate*(1-t)+e*t:e}_createInterval(e,t,r){return{start:e,end:t,bytes:r}}_doMergeIntervals(e,t){e.start=Math.min(t.start,e.start),e.end=Math.max(t.end,e.end),e.bytes+=t.bytes}_mergeIntervals(e,t){return e.start<=t.end&&t.start<=e.end?(this._doMergeIntervals(e,t),!0):!1}_flushIntervals(){if(!this.intervals.length)return!1;let e=this.intervals[0].start,t=this.intervals[this.intervals.length-1].end-500;if(t-e>2e3){let r=0,i=0;for(;this.intervals.length>0;){let s=this.intervals[0];if(s.end<=t)r+=s.end-s.start,i+=s.bytes,this.intervals.splice(0,1);else{if(s.start>=t)break;{let n=t-s.start,o=s.end-s.start;r+=n;let u=s.bytes*n/o;i+=u,s.start=t,s.bytes-=u}}}if(i>0&&r>0){let s=i*8/(r/1e3);return this._updateRate(s),this.logger(`rate updated, new=${Math.round(s/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(i)}/${Math.round(r)} interval=${Math.round(t-e)}`),!0}}return!1}_joinIntervals(){let e;do{e=!1;for(let t=0;t<this.intervals.length-1;++t)this._mergeIntervals(this.intervals[t],this.intervals[t+1])&&(this.intervals.splice(t+1,1),e=!0)}while(e)}addInterval(e,t,r){return this.intervals.push(this._createInterval(e,t,r)),this._joinIntervals(),this.intervals.length>100&&(this.logger(`too many intervals (${this.intervals.length}); will merge`,{type:"warn"}),this._doMergeIntervals(this.intervals[1],this.intervals[0]),this.intervals.splice(0,1)),this._flushIntervals()}getBitRate(){return this.currentRate}};var Si=class{constructor(e,t,r,i,s){this.pendingQueue=[];this.activeRequests={};this.completeRequests={};this.averageSegmentDuration=2e3;this.lastPrefetchStart=0;this.throttleTimeout=null;this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=r,this.MAX_PARALLEL_REQUESTS=i,this.logger=s}limitCompleteCount(){let e;for(;(e=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){let t=e[Math.floor(Math.random()*e.length)];this.logger(`Dropping completed request for url ${t}`,{type:"warn"}),delete this.completeRequests[t]}}_sendRequest(e,t){let r=Z(),i=u=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=u,e._errorCB?e._errorCB(u):(this.limitCompleteCount(),this.completeRequests[t]=e)},s=u=>{e._complete=1,e._responseData=u,e._downloadTime=Z()-r,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(u,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},n=()=>{e._finallyCB&&e._finallyCB()},o=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=yr(t,s,()=>i("error"),o),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally(n),this.activeRequests[t]=e,e._request.send(),this.lastPrefetchStart=Z()}_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=Z();if(Object.keys(this.activeRequests).length>=e)return!1;let r=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),r>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),r),!1):!0}_sendPending(){for(;this._canSendPending();){let e=this.pendingQueue.pop();if(e){if(this.activeRequests[e]||this.completeRequests[e])continue;this.logger(`Submitting pending request url=${e}`),this._sendRequest({},e)}else return}}_removeFromActive(e){delete this.completeRequests[e],delete this.activeRequests[e]}abortAll(){Object.values(this.activeRequests).forEach(e=>{e&&e._request&&e._request.abort()}),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,r,i){let s={};return s.send=()=>{let n=this.activeRequests[e]||this.completeRequests[e];if(n)n._cb=t,n._errorCB=r,n._retryCB=i,n._finallyCB=s._finallyCB,n._error||n._complete?(this._removeFromActive(e),setTimeout(()=>{n._complete?(this.logger(`Requested url already prefetched, url=${e}`),t(n._responseData,n._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${e}`),r(n._errorMsg)),s._finallyCB&&s._finallyCB()},0)):this.logger(`Attached to active request, url=${e}`);else{let o=this.pendingQueue.indexOf(e);o!==-1&&this.pendingQueue.splice(o,1),this.logger(`Request not prefetched, starting new request, url=${e}${o===-1?"":"; removed pending"}`),this._sendRequest(s,e)}},s._cb=t,s._errorCB=r,s._retryCB=i,s.abort=function(){s.request&&s.request.abort()},s.withFinally=n=>(s._finallyCB=n,s),s}prefetch(e){this.activeRequests[e]||this.completeRequests[e]?this.logger(`Request already active for url=${e}`):(this.logger(`Added to pending queue; url=${e}`),this.pendingQueue.unshift(e),this._sendPending())}optimizeForSegDuration(e){this.averageSegmentDuration=e}};var cs=1e4,mu=3;var lw=6e4,dw=10,pw=1,hw=500,yi=class{constructor(e){this.paused=!1;this.autoQuality=!0;this.maxAutoQuality=void 0;this.buffering=!0;this.destroyed=!1;this.videoPlayStarted=!1;this.lowLatency=!1;this.bitrate=0;this.manifest=[];this.sourceBuffer=0;this.bufferStates=[];this.sourceJitter=-1;this.params=e,this.chunkRateEstimator=new gi(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=fu(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setMaxAutoQuality(e){this.maxAutoQuality=e}switchByName(e){let t;for(let r=0;r<this.manifest.length;++r)if(t=this.manifest[r],t.name===e){this._switchToQuality(t);return}}catchUp(){this.rep&&this.rep.stop(),this.currentManifestEntry&&(this.paused=!1,this._initPlayerWith(this.currentManifestEntry),this._notifyBuffering(!0))}stop(){this.params.videoElement.pause(),this.rep&&(this.rep.stop(),this.rep=null)}pause(){this.paused=!0,this.params.videoElement.pause(),this.videoPlayStarted=!1,this._notifyBuffering(!1)}play(){this.paused=!1;let e=this.lowLatency&&this._getBufferSizeSec()>this.sourceJitter+5;this.rep&&!e?(this.bufferStates=[],this.videoPlayStarted=!1,this.shouldPlay()?this._playVideoElement():this._notifyBuffering(!0)):this.catchUp()}startPlay(e,t){this.autoQuality=t,this._initPlayerWith(e)}destroy(){this.destroyed=!0,this.rep&&(this.rep.stop(),this.rep=null),this.manifestRequest&&this.manifestRequest.abort(),this.manifestRefetchTimer&&(clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=void 0)}reinit(e){this.manifestUrl=e,this.urlResolver=fu(e),this.catchUp()}_handleNetworkError(){this.params.logger("Fatal network error"),this.params.playerCallback({name:"error",type:"network"})}_retryCallback(){this.params.playerCallback({name:"retry"})}_getBufferSizeSec(){let e=this.params.videoElement,t=0,r=e.buffered.length;return r!==0&&(t=e.buffered.end(r-1)-Math.max(e.currentTime,e.buffered.start(0))),t}_notifyBuffering(e){this.destroyed||(this.params.logger(`buffering: ${e}`),this.params.playerCallback({name:"buffering",isBuffering:e}),this.buffering=e)}_initVideo(){let{videoElement:e,logger:t}=this.params;e.addEventListener("error",()=>{var i;!!e.error&&!this.destroyed&&(t(`Video element error: ${(i=e.error)==null?void 0:i.code}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{let r=this._getBufferSizeSec();!this.paused&&r<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(r+.1)*1e3)):this.buffering&&this.videoPlayStarted&&this._notifyBuffering(!1)}),e.addEventListener("playing",()=>{t("playing")}),e.addEventListener("stalled",()=>this._fixupStall()),e.addEventListener("waiting",()=>this._fixupStall())}_fixupStall(){let{logger:e,videoElement:t}=this.params,r=t.buffered.length,i;r!==0&&(i=t.buffered.start(r-1),t.currentTime<i&&(e("Fixup stall"),t.currentTime=i))}_selectQuality(e){let{videoElement:t}=this.params,r,i,s,n=t&&1.62*(window.devicePixelRatio||1)*t.offsetHeight||520;for(let o=0;o<this.manifest.length;++o)s=this.manifest[o],!(this.maxAutoQuality&&s.video.height>this.maxAutoQuality)&&(s.bitrate<e&&n>Math.min(s.video.height,s.video.width)?(!i||s.bitrate>i.bitrate)&&(i=s):(!r||r.bitrate>s.bitrate)&&(r=s));return i||r}shouldPlay(){if(this.paused)return!1;let t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||us(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){let{logger:r,videoElement:i,playerCallback:s}=this.params;this.mediaSource=new window.MediaSource,r("setting video src"),i.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.videoPlayStarted=!1,i.addEventListener("canplay",()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});let n=()=>{ob(i,"progress",()=>{i.buffered.length?(i.currentTime=i.buffered.start(0),s({name:"playing"})):n()})};n()}_initPlayerWith(e){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new Si(mu,cs,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){let{logger:t,videoElement:r,playerCallback:i}=this.params,s=!1,n=null,o=null,u=null,c=null,l=!1,d=()=>{let v=s&&(!l||l===this.rep);return v||t("Not running!"),v},p=(v,T,R)=>{u&&u.abort(),u=yr(this.urlResolver.resolve(v,!1),T,R,()=>this._retryCallback()).withTimeout(cs).withBitrateReporting(this.bitrateSwitcher).withRetryCount(mu).withFinally(()=>{u=null}).send()},h=(v,T,R)=>{vi(this.filesFetcher),o==null||o.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(v,!1),T,R,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},f=v=>{let T=r.playbackRate;r.playbackRate!==v&&(t(`Playback rate switch: ${T}=>${v}`),r.playbackRate=v)},b=v=>{this.lowLatency=v,t(`lowLatency changed to ${v}`),g()},g=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)f(1);else{let v=this._getBufferSizeSec();if(this.bufferStates.length<5){f(1);return}let R=Z()-1e4,U=0;for(let B=0;B<this.bufferStates.length;B++){let N=this.bufferStates[B];v=Math.min(v,N.buf),N.ts<R&&U++}this.bufferStates.splice(0,U),t(`update playback rate; minBuffer=${v} drop=${U} jitter=${this.sourceJitter}`);let $=v-pw;this.sourceJitter>=0?$-=this.sourceJitter/2:this.sourceJitter-=1,$>3?f(1.15):$>1?f(1.1):$>.3?f(1.05):f(1)}},y=v=>{let T,R=()=>T&&T.start?T.start.length:0,U=x=>T.start[x]/1e3,$=x=>T.dur[x]/1e3,B=x=>T.fragIndex+x,N=(x,V)=>({chunkIdx:B(x),startTS:U(x),dur:$(x),discontinuity:V}),O=()=>{let x=0;if(T&&T.dur){let V=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,H=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,G=V;this.sourceJitter>1&&(G+=this.sourceJitter-1);let z=T.dur.length-1;for(;z>=0&&(G-=T.dur[z],!(G<=0));--z);x=Math.min(z,T.dur.length-1-H),x=Math.max(x,0)}return N(x,!0)},w=x=>{let V=R();if(!(V<=0)){if(us(x)){for(let H=0;H<V;H++)if(U(H)>x)return N(H)}return O()}},L=x=>{let V=R(),H=x?x.chunkIdx+1:0,G=H-T.fragIndex;if(!(V<=0)){if(!x||G<0||G-V>dw)return t(`Resync: offset=${G} bChunks=${V} chunk=`+JSON.stringify(x)),O();if(!(G>=V))return N(H-T.fragIndex,!1)}},q=(x,V,H)=>{c&&c.abort(),c=yr(this.urlResolver.resolve(x,!0,this.lowLatency),V,H,()=>this._retryCallback()).withTimeout(cs).withRetryCount(mu).withFinally(()=>{c=null}).withJSONResponse().send()};return{seek:(x,V)=>{q(v,H=>{if(!d())return;T=H;let G=!!T.lowLatency;G!==this.lowLatency&&b(G);let z=0;for(let se=0;se<T.dur.length;++se)z+=T.dur[se];z>0&&(vi(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(z/T.dur.length)),i({name:"index",zeroTime:T.zeroTime,shiftDuration:T.shiftDuration}),this.sourceJitter=T.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,T.jitter/1e3)):1,x(w(V))},()=>this._handleNetworkError())},nextChunk:L}},I=()=>{s=!1,o&&o.abort(),u&&u.abort(),c&&c.abort(),vi(this.filesFetcher),this.filesFetcher.abortAll()};return l={start:v=>{let{videoElement:T,logger:R}=this.params,U=y(e.jidxUrl),$,B,N,O,w=0,L,q,k,x=()=>{L&&(clearTimeout(L),L=void 0);let A=Math.max(hw,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),ne=w+A,Se=Z(),xe=Math.min(1e4,ne-Se);w=Se;let ot=()=>{c||d()&&U.seek(()=>{d()&&(w=Z(),V(),x())})};xe>0?L=window.setTimeout(()=>{this.paused?x():ot()},xe):ot()},V=()=>{let A;for(;A=U.nextChunk(O);)O=A,Et(A);let ne=U.nextChunk(N);if(ne){if(N&&ne.discontinuity){R("Detected discontinuity; restarting playback"),this.paused?x():(I(),this._initPlayerWith(e));return}se(ne)}else x()},H=(A,ne)=>{if(!d()||!this.sourceBuffer)return;let Se,xe,ot,Kt=ut=>{window.setTimeout(()=>{d()&&H(A,ne)},ut)};if(this.sourceBuffer.updating)R("Source buffer is updating; delaying appendBuffer"),Kt(100);else{let ut=Z(),xt=T.currentTime;!this.paused&&T.buffered.length>1&&q===xt&&ut-k>500&&(R("Stall suspected; trying to fix"),this._fixupStall()),q!==xt&&(q=xt,k=ut);let Jt=this._getBufferSizeSec();if(Jt>30)R(`Buffered ${Jt} seconds; delaying appendBuffer`),Kt(2e3);else try{this.sourceBuffer.appendBuffer(A),this.videoPlayStarted?(this.bufferStates.push({ts:ut,buf:Jt}),g(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),ne&&ne()}catch(Or){if(Or.name==="QuotaExceededError")R("QuotaExceededError; delaying appendBuffer"),ot=this.sourceBuffer.buffered.length,ot!==0&&(Se=this.sourceBuffer.buffered.start(0),xe=xt,xe-Se>4&&this.sourceBuffer.remove(Se,xe-3)),Kt(1e3);else throw Or}}},G=()=>{B&&$&&(R([`Appending chunk, sz=${B.byteLength}:`,JSON.stringify(N)]),H(B,function(){B=null,V()}))},z=A=>e.fragUrlTemplate.replace("%%id%%",A.chunkIdx),se=A=>{d()&&h(z(A),(ne,Se)=>{if(d()){if(Se/=1e3,B=ne,N=A,n=A.startTS,Se){let xe=Math.min(10,A.dur/Se);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*xe:xe}G()}},()=>this._handleNetworkError())},Et=A=>{d()&&(vi(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(z(A),!1)))},nt=A=>{d()&&(e.cachedHeader=A,H(A,()=>{$=!0,G()}))};s=!0,U.seek(A=>{if(d()){if(w=Z(),!A){x();return}O=A,!cw(v)||A.startTS>v?se(A):(N=A,V())}},v),e.cachedHeader?nt(e.cachedHeader):p(e.headerUrl,nt,()=>this._handleNetworkError())},stop:I,getTimestampSec:()=>n},l}_switchToQuality(e){let{logger:t,playerCallback:r}=this.params,i;e.bitrate!==this.bitrate&&(this.rep&&(i=this.rep.getTimestampSec(),us(i)&&(i+=.1),this.rep.stop()),this.currentManifestEntry=e,this.rep=this._representation(e),t(`switch to quality: codecs=${e.codecs}; headerUrl=${e.headerUrl}; bitrate=${e.bitrate}`),this.bitrate=e.bitrate,vi(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(i),r({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return us(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,r=d=>{if(!this.autoQuality)return;let p,h,f;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&d<this.bitrate&&(h=this._getBufferSizeSec(),f=d/this.bitrate,h>10&&f>.8||h>15&&f>.5||h>20&&f>.3)){e(`Not switching: buffer=${Math.floor(h)}; bitrate=${this.bitrate}; newRate=${Math.floor(d)}`);return}p=this._selectQuality(d),p?this._switchToQuality(p):e(`Could not find quality by bitrate ${d}`)},s={updateChunk:(p,h)=>{let f=Z();if(this.chunkRateEstimator.addInterval(p,f,h)){let g=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:h,duration:f-p,speed:g}),!0}},get:()=>{let p=this.chunkRateEstimator.getBitRate();return p?p*.85:0}},n=-1/0,o,u=!0,c=()=>{let d=s.get();if(d&&o&&this.autoQuality){if(u&&d>o&&hu(n)<3e4)return;r(d)}u=this.autoQuality};return{updateChunk:(d,p)=>{let h=s.updateChunk(d,p);return h&&c(),h},notifySwitch:d=>{let p=Z();d<o&&(n=p),o=d}}}_fetchManifest(e,t,r){this.manifestRequest=yr(this.urlResolver.resolve(e,!0),t,r,()=>this._retryCallback()).withJSONResponse().withTimeout(cs).withRetryCount(this.params.config.manifestRetryMaxCount).withRetryInterval(this.params.config.manifestRetryInterval,this.params.config.manifestRetryMaxInterval).send().withFinally(()=>{this.manifestRequest=void 0})}_playVideoElement(){let{videoElement:e}=this.params;me(e).then(t=>{t||(this.params.liveOffset.pause(),this.params.videoState.setState("paused"))})}_handleManifestUpdate(e){let{logger:t,playerCallback:r,videoElement:i}=this.params,s=n=>{let o=[];return n!=null&&n.length?(n.forEach((u,c)=>{u.video&&i.canPlayType(u.codecs).replace(/no/,"")&&window.MediaSource.isTypeSupported(u.codecs)&&(u.index=c,o.push(u))}),o.sort(function(u,c){return u.video&&c.video?c.video.height-u.video.height:c.bitrate-u.bitrate}),o):(r({name:"error",type:"empty_manifest"}),[])};this.manifest=s(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),r({name:"manifest",manifest:this.manifest})}_refetchManifest(e){this.destroyed||(this.manifestRefetchTimer&&clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=window.setTimeout(()=>{this._fetchManifest(e,t=>{this.destroyed||(this._handleManifestUpdate(t),this._refetchManifest(e))},()=>this._refetchManifest(e))},lw))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};import{debounce as fw,filter as ub,fromEvent as mw,interval as bw,isHigher as gw,isInvariantQuality as Sw,isLower as vw,merge as yw,Subject as cb,Subscription as Tw}from"@vkontakte/videoplayer-shared";var bu=class{constructor(){this.onDroopedVideoFramesLimit$=new cb;this.subscription=new Tw;this.playing=!1;this.tracks=[];this.forceChecker$=new cb;this.isForceCheckCounter=0;this.prevTotalVideoFrames=0;this.prevDroppedVideoFrames=0;this.limitCounts={};this.handleChangeVideoQuality=()=>{let e=this.tracks.find(({size:t})=>(t==null?void 0:t.height)===this.video.videoHeight&&(t==null?void 0:t.width)===this.video.videoWidth);e&&!Sw(e.quality)&&this.onChangeQuality(e.quality)};this.checkDroppedFrames=()=>{var n;let{totalVideoFrames:e,droppedVideoFrames:t}=this.video.getVideoPlaybackQuality(),r=e-this.prevTotalVideoFrames,i=t-this.prevDroppedVideoFrames,s=1-(r-i)/r;!isNaN(s)&&s>0&&this.log({message:`[dropped]. current dropped percent: ${s}, limit: ${this.droppedFramesChecker.percentLimit}`}),!isNaN(s)&&s>=this.droppedFramesChecker.percentLimit&&gw(this.currentQuality,this.droppedFramesChecker.minQualityBanLimit)&&(this.limitCounts[this.currentQuality]=((n=this.limitCounts[this.currentQuality])!=null?n:0)+1,this.maxQualityLimit=this.getMaxQualityLimit(this.currentQuality),this.currentTimer&&window.clearTimeout(this.currentTimer),this.currentTimer=window.setTimeout(()=>this.maxQualityLimit=this.getMaxQualityLimit(),this.droppedFramesChecker.qualityUpWaitingTime),this.onDroopedVideoFramesLimitTrigger()),this.savePrevFrameCounts(e,t)}}connect(e){this.log=e.logger.createComponentLog("DroppedFramesManager"),this.video=e.video,this.isAuto=e.isAuto,this.tracks=e.tracks,this.droppedFramesChecker=e.droppedFramesChecker,this.subscription.add(e.playing$.subscribe(()=>this.playing=!0)),this.subscription.add(e.pause$.subscribe(()=>this.playing=!1)),this.isEnabled&&this.subscribe()}destroy(){this.currentTimer&&window.clearTimeout(this.currentTimer),this.subscription.unsubscribe()}get droppedVideoMaxQualityLimit(){return this.maxQualityLimit}subscribe(){this.subscription.add(mw(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=bw(this.droppedFramesChecker.checkTime).pipe(ub(()=>this.playing),ub(()=>{let i=!!this.isForceCheckCounter;return i&&(this.isForceCheckCounter-=1),!i})),t=this.forceChecker$.pipe(fw(this.droppedFramesChecker.checkTime)),r=yw(e,t);this.subscription.add(r.subscribe(this.checkDroppedFrames))}onChangeQuality(e){this.currentQuality=e;let{totalVideoFrames:t,droppedVideoFrames:r}=this.video.getVideoPlaybackQuality();this.savePrevFrameCounts(t,r),this.isForceCheckCounter=this.droppedFramesChecker.tickCountAfterQualityChange,this.forceChecker$.next()}onDroopedVideoFramesLimitTrigger(){this.isAuto.getState()&&(this.log({message:`[onDroopedVideoFramesLimit]. maxQualityLimit: ${this.maxQualityLimit}`}),this.onDroopedVideoFramesLimit$.next())}getMaxQualityLimit(e){var r,i;let t=(i=(r=Object.entries(this.limitCounts).filter(([,s])=>s>=this.droppedFramesChecker.countLimit).sort(([s],[n])=>vw(s,n)?-1:1))==null?void 0:r[0])==null?void 0:i[0];return e!=null?e:t}get isEnabled(){return this.droppedFramesChecker.enabled&&this.isDroppedFramesCheckerSupport}get isDroppedFramesCheckerSupport(){return!!this.video&&typeof this.video.getVideoPlaybackQuality=="function"}savePrevFrameCounts(e,t){this.prevTotalVideoFrames=e,this.prevDroppedVideoFrames=t}},ls=bu;import{map as Iw,Observable as Ew}from"@vkontakte/videoplayer-shared";import{fromEvent as xw}from"@vkontakte/videoplayer-shared";var Ti=()=>{var a;return!!((a=window.documentPictureInPicture)!=null&&a.window)||!!document.pictureInPictureElement};var Pw=(a,e)=>new Ew(t=>{if(!window.IntersectionObserver)return;let r={root:null},i=new IntersectionObserver((n,o)=>{n.forEach(u=>t.next(u.isIntersecting||Ti()))},{...r,...e});i.observe(a);let s=xw(document,"visibilitychange").pipe(Iw(n=>!document.hidden||Ti())).subscribe(n=>t.next(n));return()=>{i.unobserve(a),s.unsubscribe}}),Le=Pw;var Dw=["paused","playing","ready"],Bw=["paused","playing","ready"],Ii=class{constructor(e){this.subscription=new Lw;this.videoState=new M("stopped");this.representations$=new Su([]);this.textTracksManager=new Re;this.droppedFramesManager=new ls;this.maxSeekBackTime$=new Su(1/0);this.zeroTime$=new Su(void 0);this.liveOffset=new Je;this._dashCb=e=>{var t,r,i,s;switch(e.name){case"buffering":{let n=e.isBuffering;this.params.output.isBuffering$.next(n);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${e.type}`,category:pb.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{let n=e.manifest,o=[];for(let u of n){let c=(t=u.name)!=null?t:u.index.toString(10),l=(r=mt(u.name))!=null?r:Cw(u.video),d=u.bitrate/1e3,p={...u.video};if(!l)continue;let h={id:c,quality:l,bitrate:d,size:p};o.push({track:h,representation:u})}this.representations$.next(o),this.params.output.availableVideoTracks$.next(o.map(({track:u})=>u)),((i=this.videoState.getTransition())==null?void 0:i.to)==="manifest_ready"&&this.videoState.setState("manifest_ready");break}case"qualitySwitch":{let n=e.quality,o=(s=this.representations$.getValue().find(({representation:u})=>u===n))==null?void 0:s.track;this.params.output.hostname$.next(new URL(n.headerUrl,this.params.source.url).hostname),gu(o)&&this.params.output.currentVideoTrack$.next(o);break}case"bandwidth":{let{size:n,duration:o}=e;this.params.dependencies.throughputEstimator.addRawSpeed(n,o);break}case"index":{this.maxSeekBackTime$.next(e.shiftDuration||0),this.zeroTime$.next(e.zeroTime);break}}};this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),r=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${r}; seekState: ${JSON.stringify(s)};`}),r==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState("stopped"));return}if(t)return;let n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(Bw.includes(e)&&(n||o)){this.prepare();return}if((i==null?void 0:i.to)!=="paused"&&s.state==="requested"&&Dw.includes(e)){this.seek(s.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(ee(this.params.source.url));return;case"manifest_ready":this.videoState.startTransitionTo("ready"),this.prepare();break;case"ready":if(r==="paused")this.videoState.setState("paused");else if(r==="playing"){this.videoState.startTransitionTo("playing");let u=i==null?void 0:i.from;u&&u==="ready"&&this.dash.catchUp(),this.dash.play()}return;case"playing":r==="paused"&&(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.dash.pause());return;case"paused":if(r==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.dash.play(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let u=this.liveOffset.getTotalOffset();u>=this.maxSeekBackTime$.getValue()&&(u=0,this.liveOffset.resetTo(u)),this.liveOffset.resume(),this.params.output.position$.next(-u/1e3),this.dash.reinit(ee(this.params.source.url,u))}return;default:return lb(e)}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=i=>{e.output.error$.next({id:"DashLiveProvider",category:pb.WTF,message:"DashLiveProvider internal logic error",thrown:i})};fb(this.videoState.stateChangeStarted$.pipe(ds(i=>({transition:i,type:"start"}))),this.videoState.stateChangeEnded$.pipe(ds(i=>({transition:i,type:"end"})))).subscribe(({transition:i,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(i)}`})}),this.video=le(e.container,e.tuning),this.params.output.element$.next(this.video),this.dash=this.createLiveDashPlayer(),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(X(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.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);let r=he(this.video);this.subscription.add(this.representations$.pipe(ds(i=>i.map(({track:s})=>s)),hb(i=>!!i.length),$w()).subscribe(i=>this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:r.playing$,pause$:r.pause$,tracks:i}))),this.subscription.add(r.canplay$.subscribe(()=>{var i;((i=this.videoState.getTransition())==null?void 0:i.to)==="ready"&&this.videoState.setState("ready")},t)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused")},t)).add(r.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.videoState.setState("playing")},t)).add(r.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(kw(),ds(i=>-i/1e3)).subscribe(this.params.output.duration$)).add(Aw({zeroTime:this.zeroTime$.pipe(hb(gu)),position:r.timeUpdate$}).subscribe(({zeroTime:i,position:s})=>this.params.output.liveTime$.next(i+s*1e3),t)).add(Ge(this.video,this.params.desiredState.isLooped,t)).add(pe(this.video,this.params.desiredState.volume,r.volumeState$,t)).add(r.volumeState$.subscribe(this.params.output.volume$,t)).add(ke(this.video,this.params.desiredState.playbackRate,r.playbackRateState$,t)).add(r.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(r.loadedMetadata$.subscribe(this.params.output.loadedMetadataEvent$)).add(r.playing$.subscribe(this.params.output.firstFrameEvent$)).add(r.canplay$.subscribe(this.params.output.canplay$)).add(r.inPiP$.subscribe(this.params.output.inPiP$)).add(r.inFullscreen$.subscribe(this.params.output.inFullscreen$)).add(Le(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:i}})=>{let s=i&&Mw(i);this.dash.setMaxAutoQuality(s),this.params.output.autoVideoTrackLimits$.next({max:i})})).add(this.videoState.stateChangeEnded$.subscribe(i=>{var s;switch(i.to){case"stopped":this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState("stopped");break;case"manifest_ready":case"ready":((s=this.params.desiredState.playbackState.getTransition())==null?void 0:s.to)==="ready"&&this.params.desiredState.playbackState.setState("ready");break;case"paused":this.params.desiredState.playbackState.setState("paused");break;case"playing":this.params.desiredState.playbackState.setState("playing");break;default:return lb(i.to)}},t)).add(fb(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,Rw(["init"])).pipe(ww(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),de(this.video)}createLiveDashPlayer(){let e=new yi({videoElement:this.video,videoState:this.videoState,liveOffset:this.liveOffset,config:{maxParallelRequests:this.params.config.maxParallelRequests,minBuffer:this.params.tuning.live.minBuffer,minBufferSegments:this.params.tuning.live.minBufferSegments,lowLatencyMinBuffer:this.params.tuning.live.lowLatencyMinBuffer,lowLatencyMinBufferSegments:this.params.tuning.live.lowLatencyMinBufferSegments,isLiveCatchUpMode:this.params.tuning.live.isLiveCatchUpMode,manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},playerCallback:this._dashCb,logger:t=>{this.params.dependencies.logger.log({message:String(t),component:"LiveDashPlayer"})}});return e.pause(),e}prepare(){var c,l,d,p,h,f;let e=this.representations$.getValue(),t=(l=(c=this.params.desiredState.videoTrack.getTransition())==null?void 0:c.to)!=null?l:this.params.desiredState.videoTrack.getState(),r=(p=(d=this.params.desiredState.autoVideoTrackSwitching.getTransition())==null?void 0:d.to)!=null?p:this.params.desiredState.autoVideoTrackSwitching.getState(),i=!r&&gu(t)?t:bt(e.map(({track:b})=>b),{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},throughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),s=i==null?void 0:i.id,n=this.params.desiredState.videoTrack.getTransition(),o=(h=this.params.desiredState.videoTrack.getState())==null?void 0:h.id,u=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(i&&(n||s!==o)&&this.setVideoTrack(i),u&&this.setAutoQuality(r),n||u||s!==o){let b=(f=e.find(({track:g})=>g.id===s))==null?void 0:f.representation;db(b,"Representations missing"),this.dash.startPlay(b,r)}}setVideoTrack(e){var r;let t=(r=this.representations$.getValue().find(({track:i})=>i.id===e.id))==null?void 0:r.representation;db(t,`No such representation ${e.id}`),this.dash.switchByName(t.name),this.params.desiredState.videoTrack.setState(e)}setAutoQuality(e){this.dash.setAutoQualityEnabled(e),this.params.desiredState.autoVideoTrackSwitching.setState(e)}seek(e){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),r=this.videoState.getState(),i=t==="paused"&&r==="paused",s=-e,n=s<=this.maxSeekBackTime$.getValue()?s:0;this.params.output.position$.next(e/1e3),this.dash.reinit(ee(this.params.source.url,n)),i&&this.dash.pause(),this.liveOffset.resetTo(n,i)}};var mb=Ii;var Ze=(a,e)=>{let t=0;for(let r=0;r<a.length;r++){let i=a.start(r)*1e3,s=a.end(r)*1e3;i<=e&&e<=s&&(t=s)}return Math.max(t-e,0)};import{assertNever as sR,assertNonNullable as nR,debounce as oR,ErrorCategory as Wu,filter as qg,filterChanged as Yu,fromEvent as uR,isNonNullable as cR,map as Ug,merge as Os,observableFrom as lR,observeElementSize as dR,once as Hg,Subscription as pR,ValueSubject as hR}from"@vkontakte/videoplayer-shared";var ps=class{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,r){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:r})}removeEventListener(e,t){if(!(e in this.listeners))return;let r=this.listeners[e];for(let i=0,s=r.length;i<s;i++)if(r[i].callback===t){r.splice(i,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;let r=this.listeners[e.type].slice();for(let i=0,s=r.length;i<s;i++){let n=r[i];try{n.callback.call(this,e)}catch(o){Promise.resolve().then(()=>{throw o})}n.options&&n.options.once&&this.removeEventListener(e.type,n.callback)}return!e.defaultPrevented}},Tr=class extends ps{constructor(){super(),this.listeners||ps.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)}},Ei=class{constructor(){Object.defineProperty(this,"signal",{value:new Tr,writable:!0,configurable:!0})}abort(e){let t;try{t=new Event("abort")}catch(i){typeof document!="undefined"?document.createEvent?(t=document.createEvent("Event"),t.initEvent("abort",!1,!1)):(t=document.createEventObject(),t.type="abort"):t={type:"abort",bubbles:!1,cancelable:!1}}let r=e;if(r===void 0)if(typeof document=="undefined")r=new Error("This operation was aborted"),r.name="AbortError";else try{r=new DOMException("signal is aborted without reason")}catch(i){r=new Error("This operation was aborted"),r.name="AbortError"}this.signal.reason=r,this.signal.dispatchEvent(t)}toString(){return"[object AbortController]"}};typeof Symbol!="undefined"&&Symbol.toStringTag&&(Ei.prototype[Symbol.toStringTag]="AbortController",Tr.prototype[Symbol.toStringTag]="AbortSignal");function hs(a){return a.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof a.Request=="function"&&!a.Request.prototype.hasOwnProperty("signal")||!a.AbortController}function vu(a){typeof a=="function"&&(a={fetch:a});let{fetch:e,Request:t=e.Request,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:i=!1}=a;if(!hs({fetch:e,Request:t,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:i}))return{fetch:e,Request:s};let s=t;(s&&!s.prototype.hasOwnProperty("signal")||i)&&(s=function(c,l){let d;l&&l.signal&&(d=l.signal,delete l.signal);let p=new t(c,l);return d&&Object.defineProperty(p,"signal",{writable:!1,enumerable:!1,configurable:!0,value:d}),p},s.prototype=t.prototype);let n=e;return{fetch:(u,c)=>{let l=s&&s.prototype.isPrototypeOf(u)?u.signal:c?c.signal:void 0;if(l){let d;try{d=new DOMException("Aborted","AbortError")}catch(h){d=new Error("Aborted"),d.name="AbortError"}if(l.aborted)return Promise.reject(d);let p=new Promise((h,f)=>{l.addEventListener("abort",()=>f(d),{once:!0})});return c&&c.signal&&delete c.signal,Promise.race([p,n(u,c)])}return n(u,c)},Request:s}}var xi=hs({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),bb=xi?vu({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,et=xi?bb.fetch:window.fetch,mB=xi?bb.Request:window.Request,tt=xi?Ei:window.AbortController,bB=xi?Tr:window.AbortSignal;var Rb=He(fi(),1);var rt=()=>window.ManagedMediaSource||window.MediaSource,fs=()=>{var a,e;return!!(window.ManagedMediaSource&&((e=(a=window.ManagedSourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},gb=()=>{var a,e;return!!(window.MediaSource&&window.MediaStreamTrack&&((e=(a=window.SourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},Sb=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;import{assertNever as Es,clientChecker as Is}from"@vkontakte/videoplayer-shared";var Me=document.createElement("video"),_w='video/mp4; codecs="avc1.42000a,mp4a.40.2"',Nw='video/mp4; codecs="hev1.1.6.L93.B0"',$b='video/webm; codecs="vp09.00.10.08"',Lb='video/webm; codecs="av01.0.00M.08"',Fw='audio/mp4; codecs="mp4a.40.2"',qw='audio/webm; codecs="opus"',vb,yb,Nt={mms:fs(),mse:gb(),hls:!!((vb=Me.canPlayType)!=null&&vb.call(Me,"application/x-mpegurl")||(yb=Me.canPlayType)!=null&&yb.call(Me,"vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},Tb,Ib,be={mp4:!!((Tb=Me.canPlayType)!=null&&Tb.call(Me,"video/mp4")),webm:!!((Ib=Me.canPlayType)!=null&&Ib.call(Me,"video/webm")),cmaf:!0},bs,Eb,gs,xb,Ss,Pb,vs,Ab,ys,wb,Ts,kb,ge={h264:!!((Eb=(bs=rt())==null?void 0:bs.isTypeSupported)!=null&&Eb.call(bs,_w)),h265:!!((xb=(gs=rt())==null?void 0:gs.isTypeSupported)!=null&&xb.call(gs,Nw)),vp9:!!((Pb=(Ss=rt())==null?void 0:Ss.isTypeSupported)!=null&&Pb.call(Ss,$b)),av1:!!((Ab=(vs=rt())==null?void 0:vs.isTypeSupported)!=null&&Ab.call(vs,Lb)),aac:!!((wb=(ys=rt())==null?void 0:ys.isTypeSupported)!=null&&wb.call(ys,Fw)),opus:!!((kb=(Ts=rt())==null?void 0:Ts.isTypeSupported)!=null&&kb.call(Ts,qw))},Ir=(ge.h264||ge.h265)&&ge.aac,Ft,Uw=async()=>{if(!window.navigator.mediaCapabilities)return;let a={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=await Promise.all([window.navigator.mediaCapabilities.decodingInfo({...a,video:{...a.video,contentType:Lb}}),window.navigator.mediaCapabilities.decodingInfo({...a,video:{...a.video,contentType:$b}})]);Ft={DASH_WEBM_AV1:e,DASH_WEBM:t}};try{Uw()}catch(a){console.error(a)}var Er=Nt.hls&&be.mp4,Mb=()=>Object.keys(ge).filter(a=>ge[a]),Cb=(a,e=!1,t=!1)=>{let r=Nt.mse||Nt.mms&&t;return a.filter(i=>{switch(i){case"DASH_SEP":return r&&be.mp4&&Ir;case"DASH_WEBM":return r&&be.webm&&ge.vp9&&ge.opus;case"DASH_WEBM_AV1":return r&&be.webm&&ge.av1&&ge.opus;case"DASH_STREAMS":return r&&(be.mp4&&Ir||be.webm&&(ge.vp9||ge.av1)&&(ge.opus||ge.aac));case"DASH_LIVE":return Nt.mse&&be.mp4&&Ir;case"DASH_LIVE_CMAF":return r&&be.mp4&&Ir&&be.cmaf;case"DASH_ONDEMAND":return r&&be.mp4&&Ir;case"HLS":case"HLS_ONDEMAND":return Er||e&&Nt.mse&&be.mp4&&Ir;case"HLS_LIVE":case"HLS_LIVE_CMAF":return Er;case"MPEG":return be.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return Nt.webrtc&&Nt.ws&&ge.h264&&(be.mp4||be.webm);default:return Es(i)}})},ms=a=>{let e="DASH_WEBM",t="DASH_WEBM_AV1";switch(a){case"vp9":return[e,t];case"av1":return[t,e];case"none":return[];case"smooth":return Ft?Ft[t].smooth?[t,e]:Ft[e].smooth?[e,t]:[t,e]:[e,t];case"power_efficient":return Ft?Ft[t].powerEfficient?[t,e]:Ft[e].powerEfficient?[e,t]:[t,e]:[e,t];default:Es(a)}return[e,t]},Db=({webmCodec:a,androidPreferredFormat:e,preferMultiStream:t})=>{let r=[...t?["DASH_STREAMS"]:[],...ms(a),"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]],i=[...t?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]];if(Is.isAndroid)switch(e){case"mpeg":return["MPEG",...r,"HLS","HLS_ONDEMAND"];case"hls":return["HLS","HLS_ONDEMAND",...r,"MPEG"];case"dash":return[...r,"HLS","HLS_ONDEMAND","MPEG"];case"dash_any_mpeg":return[...i,"MPEG",...ms(a),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...ms(a),"MPEG",...i,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...ms(a),...i,"HLS","HLS_ONDEMAND"];default:Es(e)}return Er?[...r,"HLS","HLS_ONDEMAND","MPEG"]:[...r,"HLS","HLS_ONDEMAND","MPEG"]},Bb=({androidPreferredFormat:a,preferCMAF:e,preferWebRTC:t})=>{let r=e?["DASH_LIVE_CMAF","DASH_LIVE"]:["DASH_LIVE","DASH_LIVE_CMAF"],i=e?["HLS_LIVE_CMAF","HLS_LIVE"]:["HLS_LIVE","HLS_LIVE_CMAF"],s=[...r,...i],n=[...i,...r],o,u=Is.isMac&&Is.isSafari;if(Is.isAndroid)switch(a){case"dash":case"dash_any_mpeg":case"dash_any_webm":case"dash_sep":{o=s;break}case"hls":case"mpeg":{o=n;break}default:Es(a)}else Er&&!u?o=n:u?o=e?["DASH_LIVE_CMAF","HLS_LIVE_CMAF","HLS_LIVE","DASH_LIVE"]:["HLS_LIVE","DASH_LIVE","DASH_LIVE_CMAF","HLS_LIVE_CMAF"]:o=s;return t?["WEB_RTC_LIVE",...o]:[...o,"WEB_RTC_LIVE"]},yu=a=>a?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],Ob=a=>{if(a.size!==0){if(a.size===1)return a.values().next().value.split(".").at(0);for(let e of a){let t=(0,Rb.default)(e.split("."),0);if(t==="opus"||t==="vp09"||t==="av01")return t}return a.values().next().value.split(".").at(0)}};import{ErrorCategory as Pi}from"@vkontakte/videoplayer-shared";var Vb=a=>{if(!a)return{id:"EmptyResponse",category:Pi.PARSER,message:"Empty response"};if(a.length<=2&&a.match(/^\d+$/))return{id:`UVError#${a}`,category:Pi.NETWORK,message:`UV Error ${a}`};let e=a.trimStart().substring(0,100).toLowerCase();if(e.startsWith("<!doctype")||e.startsWith("<html>")||e.startsWith("<body>")||e.startsWith("<head>"))return{id:"UnexpectedHTML",category:Pi.NETWORK,message:"Received unexpected HTML, possibly a ISP block"};if(e.startsWith("<?xml"))return new DOMParser().parseFromString(a,"text/xml").querySelector("parsererror")?{id:"InvalidXML",category:Pi.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:Pi.PARSER,message:"Response is valid XML, but parser failed"}};var xr=(a,e)=>{for(let t=0;t<a.length;t++)if(a.start(t)*1e3<=e&&a.end(t)*1e3>e)return!0;return!1};import{abortable as Hu,assertNonNullable as Qt,combine as $s,ErrorCategory as St,filter as Ls,filterChanged as Dg,fromEvent as Mr,interval as ju,isNonNullable as Bg,map as Gu,merge as Cr,Subject as Og,Subscription as Vg,tap as Jk,throttle as Xk,clientChecker as Zk,ValueSubject as ie,flattenObject as ea,getTraceSubscriptionMethod as eR}from"@vkontakte/videoplayer-shared";var $r=He(fi(),1);var Hw=(a,e={})=>{let r=e.timeout||1,i=performance.now();return window.setTimeout(()=>{a({get didTimeout(){return e.timeout?!1:performance.now()-i-1>r},timeRemaining(){return Math.max(0,1+(performance.now()-i))}})},1)},jw=a=>window.clearTimeout(a),_b=typeof window.requestIdleCallback!="function"||typeof window.cancelIdleCallback!="function",Tu=_b?Hw:window.requestIdleCallback,$B=_b?jw:window.cancelIdleCallback;var wg=He(is(),1);import{assertNever as Gw,ErrorCategory as Nb,clientChecker as Iu,Subject as Fb}from"@vkontakte/videoplayer-shared";var Ww=16,qb=!1;try{qb=Iu.isSafari&&!!Iu.macVersion&&Iu.macVersion<=Ww}catch(a){console.error(a)}var Eu=class{constructor(e){this.bufferFull$=new Fb;this.error$=new Fb;this.queue=[];this.currentTask=null;this.destroyed=!1;this.completeTask=()=>{var e;try{if(this.currentTask){let t=(e=this.currentTask.signal)==null?void 0:e.aborted;this.currentTask.callback(!t),this.currentTask=null}this.queue.length&&this.pull()}catch(t){this.error$.next({id:"BufferTaskQueueUnknown",category:Nb.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:t})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(r=>{let i={operation:"append",data:e,signal:t,callback:r};this.queue.push(i),this.pull()})}async remove(e,t,r){return r&&r.aborted?!1:new Promise(i=>{let s={operation:"remove",from:e,to:t,signal:r,callback:i};this.queue.unshift(s),this.pull()})}async abort(e){return new Promise(t=>{let r;qb&&e?r={operation:"safariAbort",init:e,callback:t}:r={operation:"abort",callback:t};for(let{callback:i}of this.queue)i(!1);r&&(this.queue=[r]),this.pull()})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){var i;if(this.buffer.updating||this.currentTask||this.destroyed)return;let e=this.queue.shift();if(!e)return;if((i=e.signal)!=null&&i.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(s){s instanceof DOMException&&s.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):s instanceof DOMException&&s.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:Nb.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:s}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){let{operation:t}=e;switch(t){case"append":this.buffer.appendBuffer(e.data);break;case"remove":this.buffer.remove(e.from/1e3,e.to/1e3);break;case"abort":this.buffer.abort();break;case"safariAbort":{this.buffer.abort(),this.buffer.appendBuffer(e.init);break}default:Gw(t)}}},Ub=Eu;var xu=a=>{let e=0;for(let t=0;t<a.length;t++)e+=a.end(t)-a.start(t);return e*1e3};import{abortable as Rr,assertNonNullable as Ce,ErrorCategory as Gt,fromEvent as Vu,getExponentialDelay as _u,isNonNullable as Nu,isNullable as De,once as Hk,Subject as jk,Subscription as Gk,ValueSubject as Qi}from"@vkontakte/videoplayer-shared";var F=class{constructor(e,t){this.cursor=0;this.source=e,this.boxParser=t,this.children=[];let r=this.readUint32();this.type=this.readString(4),this.size32=r<=e.buffer.byteLength-e.byteOffset?r:NaN;let i=this.size32?this.size32-8:void 0,s=e.byteOffset+this.cursor;this.size64=0,this.usertype=0,this.content=new DataView(e.buffer,s,i),this.children=this.parseChildrenBoxes()}get id(){return this.type}get size(){return this.size32}parseChildrenBoxes(){return[]}scanForBoxes(e){return this.boxParser.parse(e)}readString(e,t="ascii"){let i=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,i}readUint8(){let e=this.source.getUint8(this.cursor);return this.cursor+=1,e}readUint16(){let e=this.source.getUint16(this.cursor);return this.cursor+=2,e}readUint32(){let e=this.source.getUint32(this.cursor);return this.cursor+=4,e}readUint64(){let e=this.source.getBigInt64(this.cursor);return this.cursor+=8,e}};var Pr=class extends F{};var Ai=class extends F{};var wi=class extends F{constructor(e,t){super(e,t),this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let r=this.size-this.cursor;for(;r;){let i=this.readString(4);this.compatibleBrands.push(i),r-=4}}};var ki=class extends F{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Ri=class extends F{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var $i=class extends F{constructor(e,t){super(e,t),this.data=this.content}};var Q=class extends F{constructor(e,t){super(e,t);let r=this.readUint32();this.version=r>>>24,this.flags=r&16777215}};var qt=class extends Q{get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e,t){super(e,t),this.segments=[],this.referenceId=this.readUint32(),this.timescale=this.readUint32(),this.earliestPresentationTime32=this.readUint32(),this.firstOffset32=this.readUint32(),this.earliestPresentationTime64=0,this.firstOffset64=0,this.referenceCount=this.readUint32()&65535;for(let r=0;r<this.referenceCount;r++){let i=this.readUint32(),s=i>>>31,n=i<<1>>>1,o=this.readUint32();i=this.readUint32();let u=i>>>28,c=i<<3>>>3;this.segments.push({referenceType:s,referencedSize:n,subsegmentDuration:o,SAPType:u,SAPDeltaTime:c})}}};var Li=class extends F{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Mi=class extends F{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Ci=class extends Q{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 Di=class extends Q{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var Bi=class extends Q{constructor(e,t){super(e,t),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}};var Oi=class extends F{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Vi=class extends Q{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 _i=class extends F{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Ni=class extends F{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Fi=class extends Q{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var qi=class extends F{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Ui=class extends Q{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 Hi=class extends Q{constructor(t,r){super(t,r);this.baseMediaDecodeTime32=0;this.baseMediaDecodeTime64=BigInt(0);this.version===1?this.baseMediaDecodeTime64=this.readUint64():this.baseMediaDecodeTime32=this.readUint32()}get baseMediaDecodeTime(){return this.version===1?this.baseMediaDecodeTime64:this.baseMediaDecodeTime32}};var ji=class extends Q{constructor(t,r){super(t,r);this.sampleDuration=[];this.sampleSize=[];this.sampleFlags=[];this.sampleCompositionTimeOffset=[];this.optionalFields=0;this.sampleCount=this.readUint32(),this.flags&1&&(this.dataOffset=this.readUint32()),this.flags&4&&(this.firstSampleFlags=this.readUint32());for(let i=0;i<this.sampleCount;i++)this.flags&256&&this.sampleDuration.push(this.readUint32()),this.flags&512&&this.sampleSize.push(this.readUint32()),this.flags&1024&&this.sampleFlags.push(this.readUint32()),this.flags&2048&&this.sampleCompositionTimeOffset.push(this.readUint32())}};var Qw={ftyp:wi,moov:ki,moof:Ri,mdat:$i,sidx:qt,trak:Li,mdia:Oi,mfhd:Fi,tkhd:Vi,traf:qi,tfhd:Ui,tfdt:Hi,trun:ji,minf:_i,sv3d:Mi,st3d:Ci,prhd:Di,proj:Ni,equi:Bi,uuid:Ai,unknown:Pr},Ut=class a{constructor(e={}){this.options={offset:0,...e}}parse(e){let t=[],r=this.options.offset;for(;r<e.byteLength;)try{let s=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+r+4,4)),n=this.createBox(s,new DataView(e.buffer,e.byteOffset+r));if(!n.size)break;t.push(n),r+=n.size}catch(i){break}return t}createBox(e,t){let r=Qw[e];return r?new r(t,new a):new Pr(t,new a)}};var Ar=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{var r,i,s;(s=(r=this.index)[i=t.type])!=null||(r[i]=[]),this.index[t.type].push(t),t.children.length>0&&this.indexBoxLevel(t.children)})}find(e){return this.index[e]&&this.index[e][0]?this.index[e][0]:null}findAll(e){return this.index[e]||[]}};var Kw=new TextDecoder("ascii"),Jw=a=>Kw.decode(new DataView(a.buffer,a.byteOffset+4,4))==="ftyp",Xw=a=>{let e=new qt(a,new Ut),t=e.earliestPresentationTime/e.timescale*1e3,r=a.byteOffset+a.byteLength+e.firstOffset;return e.segments.map(s=>{if(s.referenceType!==0)throw new Error("Unsupported multilevel sidx");let n=s.subsegmentDuration/e.timescale*1e3,o={status:"none",time:{from:t,to:t+n},byte:{from:r,to:r+s.referencedSize-1}};return t+=n,r+=s.referencedSize,o})},Zw=(a,e)=>{let r=new Ut().parse(a),i=new Ar(r),s=i.findAll("moof"),n=e?i.findAll("uuid"):i.findAll("mdat");if(!(n.length&&s.length))return null;let o=s[0],u=n[n.length-1],c=o.source.byteOffset,d=u.source.byteOffset-o.source.byteOffset+u.size;return new DataView(a.buffer,c,d)},ek=(a,e)=>{let r=new Ut().parse(a),s=new Ar(r).findAll("traf"),n=s[s.length-1].children.find(d=>d.type==="tfhd"),o=s[s.length-1].children.find(d=>d.type==="tfdt"),u=s[s.length-1].children.find(d=>d.type==="trun"),c=0;return u.sampleDuration.length?c=u.sampleDuration.reduce((d,p)=>d+p,0):c=n.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+c)/e*1e3},tk=a=>{let e={is3dVideo:!1,stereoMode:0,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}},r=new Ut().parse(a),i=new Ar(r);if(i.find("sv3d")){e.is3dVideo=!0;let n=i.find("st3d");n&&(e.stereoMode=n.stereoMode);let o=i.find("prhd");o&&(e.projectionData.pose.yaw=o.poseYawDegrees,e.projectionData.pose.pitch=o.posePitchDegrees,e.projectionData.pose.roll=o.poseRollDegrees);let u=i.find("equi");u&&(e.projectionData.bounds.top=u.projectionBoundsTop,e.projectionData.bounds.right=u.projectionBoundsRight,e.projectionData.bounds.bottom=u.projectionBoundsBottom,e.projectionData.bounds.left=u.projectionBoundsLeft)}return e},Hb={validateData:Jw,parseInit:tk,getIndexRange:()=>{},parseSegments:Xw,parseFeedableSegmentChunk:Zw,getSegmentEndTime:ek};import{assertNonNullable as Au,isNonNullable as Yb,isNullable as ik}from"@vkontakte/videoplayer-shared";import{assertNever as rk}from"@vkontakte/videoplayer-shared";var jb={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"}},Gb=a=>{let e=a.getUint8(0),t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);let r=Gi(a,t),i=r in jb,s=i?jb[r].type:"binary",n=a.getUint8(t),o=0;n&128?o=1:n&64?o=2:n&32?o=3:n&16?o=4:n&8?o=5:n&4?o=6:n&2?o=7:n&1&&(o=8);let u=new DataView(a.buffer,a.byteOffset+t+1,o-1),c=n&255>>o,l=Gi(u),d=c*2**((o-1)*8)+l,p=t+o,h;return p+d>a.byteLength?h=new DataView(a.buffer,a.byteOffset+p):h=new DataView(a.buffer,a.byteOffset+p,d),{tag:i?r:"0x"+r.toString(16).toUpperCase(),type:s,tagHeaderSize:p,tagSize:p+d,value:h,valueSize:d}},Gi=(a,e=a.byteLength)=>{switch(e){case 1:return a.getUint8(0);case 2:return a.getUint16(0);case 3:return a.getUint8(0)*2**16+a.getUint16(1);case 4:return a.getUint32(0);case 5:return a.getUint8(0)*2**32+a.getUint32(1);case 6:return a.getUint16(0)*2**32+a.getUint32(2);case 7:{let t=a.getUint8(0)*281474976710656+a.getUint16(1)*4294967296+a.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},Fe=(a,e)=>{switch(e){case"int":return a.getInt8(0);case"uint":return Gi(a);case"float":return a.byteLength===4?a.getFloat32(0):a.getFloat64(0);case"string":return new TextDecoder("ascii").decode(a);case"utf8":return new TextDecoder("utf-8").decode(a);case"date":return new Date(Date.UTC(2001,0)+a.getInt8(0)).getTime();case"master":return a;case"binary":return a;default:rk(e)}},Ht=(a,e)=>{let t=0;for(;t<a.byteLength;){let r=new DataView(a.buffer,a.byteOffset+t),i=Gb(r);if(!e(i))return;i.type==="master"&&Ht(i.value,e),t=i.value.byteOffset-a.byteOffset+i.valueSize}},Wb=a=>{if(a.getUint32(0)!==440786851)return!1;let e,t,r,i=Gb(a);return Ht(i.value,({tag:s,type:n,value:o})=>(s===17143?e=Fe(o,n):s===17026?t=Fe(o,n):s===17029&&(r=Fe(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(r===void 0||r<=2)};var Qb=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],ak=[231,22612,22743,167,171,163,160,175],sk=a=>{let e,t,r,i,s=!1,n=!1,o=!1,u,c,l=!1,d=0;return Ht(a,({tag:p,type:h,value:f,valueSize:b})=>{if(p===21419){let g=Fe(f,h);c=Gi(g)}else p!==21420&&(c=void 0);return p===408125543?(e=f.byteOffset,t=f.byteOffset+b):p===357149030?s=!0:p===290298740?n=!0:p===2807729?r=Fe(f,h):p===17545?i=Fe(f,h):p===21420&&c===475249515?u=Fe(f,h):p===374648427?Ht(f,({tag:g,type:y,value:I})=>g===30321?(l=Fe(I,y)===1,!1):!0):s&&n&&Qb.includes(p)&&(o=!0),!o}),Au(e,"Failed to parse webm Segment start"),Au(t,"Failed to parse webm Segment end"),Au(i,"Failed to parse webm Segment duration"),r=r!=null?r:1e6,{segmentStart:Math.round(e/1e9*r*1e3),segmentEnd:Math.round(t/1e9*r*1e3),timeScale:r,segmentDuration:Math.round(i/1e9*r*1e3),cuesSeekPosition:u,is3dVideo:l,stereoMode:d,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},nk=a=>{if(ik(a.cuesSeekPosition))return;let e=a.segmentStart+a.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},ok=(a,e)=>{let t=!1,r=!1,i=o=>Yb(o.time)&&Yb(o.position),s=[],n;return Ht(a,({tag:o,type:u,value:c})=>{switch(o){case 475249515:t=!0;break;case 187:n&&i(n)&&s.push(n),n={};break;case 179:n&&(n.time=Fe(c,u));break;case 183:break;case 241:n&&(n.position=Fe(c,u));break;default:t&&Qb.includes(o)&&(r=!0)}return!(t&&r)}),n&&i(n)&&s.push(n),s.map((o,u)=>{let{time:c,position:l}=o,d=s[u+1];return{status:"none",time:{from:c,to:d?d.time:e.segmentDuration},byte:{from:e.segmentStart+l,to:d?e.segmentStart+d.position-1:e.segmentEnd-1}}})},uk=a=>{let e=0,t=!1;try{Ht(a,r=>r.tag===524531317?r.tagSize<=a.byteLength?(e=r.tagSize,!1):(e+=r.tagHeaderSize,!0):ak.includes(r.tag)?(e+r.tagSize<=a.byteLength&&(e+=r.tagSize,t||(t=[163,160,175].includes(r.tag))),!0):!1)}catch(r){}return e>0&&e<=a.byteLength&&t?new DataView(a.buffer,a.byteOffset,e):null},zb={validateData:Wb,parseInit:sk,getIndexRange:nk,parseSegments:ok,parseFeedableSegmentChunk:uk};var wr=a=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(a);if(e){let[,t,r]=e;if(t==="audio"||t==="video")switch(r){case"webm":return zb;case"mp4":return Hb}}throw new ReferenceError(`Unsupported mime type ${a}`)};var Cu=He(gg(),1);var Mu=a=>{let e=a.split("."),[t,...r]=e;if(!t)return!1;switch(t){case"av01":{let[i,s,n]=r;return!!(n&&parseInt(n,10)>8)}case"vp09":{let[i,s,n]=r;return!!(i&&parseInt(i,10)>=2&&n&&parseInt(n,10)>8)}case"avc1":{let i=r[0];if(!i||i.length!==6)return!1;let[s,n]=i.toUpperCase(),o=s+n;return["6E","7A","F4"].includes(o)}}return!1};import{isNonNullable as vg,isNullable as yg}from"@vkontakte/videoplayer-shared";var Sg=a=>{if(a.includes("/")){let e=a.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(a)};var Tg=a=>{if(!a.startsWith("P"))return;let e=(n,o)=>{let u=n?parseFloat(n.replace(",",".")):NaN;return(isNaN(u)?0:u)*o},r=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(a),i=(r==null?void 0:r[1])==="-"?-1:1,s={days:e(r==null?void 0:r[5],i),hours:e(r==null?void 0:r[6],i),minutes:e(r==null?void 0:r[7],i),seconds:e(r==null?void 0:r[8],i)};return s.days*24*60*60*1e3+s.hours*60*60*1e3+s.minutes*60*1e3+s.seconds*1e3},jt=(a,e)=>{let t=a;t=(0,Cu.default)(t,"$$","$");let r={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[i,s]of Object.entries(r)){let n=new RegExp(`\\$${i}(?:%0(\\d+)d)?\\$`,"g");t=(0,Cu.default)(t,n,(o,u)=>yg(s)?o:yg(u)?s:s.padStart(parseInt(u,10),"0"))}return t},Eg=(a,e)=>{var v,T,R,U,$,B,N,O,w,L,q,k,x,V,H,G,z,se,Et,nt,A,ne,Se,xe,ot,Kt,ut,xt,Jt,Or,cc,lc,dc,pc,hc,fc,mc,bc,gc,Sc,vc,yc,Tc,Ic,Ec,xc,Pc,Ac,wc,kc;let r=new DOMParser().parseFromString(a,"application/xml"),i={video:[],audio:[],text:[]},s=r.children[0],n=s.getElementsByTagName("Period")[0],o=(R=(T=(v=s.querySelector("BaseURL"))==null?void 0:v.textContent)==null?void 0:T.trim())!=null?R:"",u=n.children,c=s.getAttribute("type")==="dynamic",l=s.getAttribute("availabilityStartTime"),d=l?new Date(l).getTime():void 0,p,h=s.getAttribute("mediaPresentationDuration"),f=n.getAttribute("duration"),b=s.getElementsByTagName("vk:Attrs")[0],g=b==null?void 0:b.getElementsByTagName("vk:XPlaybackDuration")[0].textContent;if(h)p=Tg(h);else if(f){let oe=Tg(f);vg(oe)&&(p=oe)}else g&&(p=parseInt(g,10));let y=0,I=($=(U=s.getAttribute("profiles"))==null?void 0:U.split(","))!=null?$:[];for(let oe of u){let DS=(B=oe.getAttribute("id"))!=null?B:"id"+(y++).toString(10),Vr=(N=oe.getAttribute("mimeType"))!=null?N:"",Js=(O=oe.getAttribute("codecs"))!=null?O:"",Xs=(w=oe.getAttribute("contentType"))!=null?w:Vr==null?void 0:Vr.split("/")[0],BS=(q=(L=oe.getAttribute("profiles"))==null?void 0:L.split(","))!=null?q:[],OS=(k=oe.getAttribute("lang"))!=null?k:void 0,VS=(H=(V=(x=oe.querySelector("Label"))==null?void 0:x.textContent)==null?void 0:V.trim())!=null?H:void 0,_S=oe.querySelectorAll("Representation"),NS=oe.querySelector("SegmentTemplate"),FS=(z=(G=oe.querySelector("Role"))==null?void 0:G.getAttribute("value"))!=null?z:void 0,_r=Xs,J={id:DS,language:OS,isDefault:FS==="main",label:VS,codecs:Js,hdr:_r==="video"&&Mu(Js),mime:Vr,representations:[]};for(let K of _S){let qS=(se=K.getAttribute("lang"))!=null?se:void 0,US=(Et=K.getAttribute("label"))!=null?Et:void 0,HS=(ne=(A=(nt=K.querySelector("BaseURL"))==null?void 0:nt.textContent)==null?void 0:A.trim())!=null?ne:"",Zs=new URL(HS||o,e).toString(),Xt=(Se=K.getAttribute("mimeType"))!=null?Se:Vr,ma=(ot=(xe=K.getAttribute("codecs"))!=null?xe:Js)!=null?ot:"",en;if(Xs==="text"){let Pt=K.getAttribute("id")||"",tn=Pt.includes("_auto");en={id:Pt,isAuto:tn,kind:"text",url:Zs}}else{let Pt=(ut=(Kt=K.getAttribute("contentType"))!=null?Kt:Xt==null?void 0:Xt.split("/")[0])!=null?ut:Xs,tn=(Jt=(xt=oe.getAttribute("profiles"))==null?void 0:xt.split(","))!=null?Jt:[],jS=parseInt((Or=K.getAttribute("width"))!=null?Or:"",10),Rc=parseInt((cc=K.getAttribute("height"))!=null?cc:"",10),$c=parseInt((lc=K.getAttribute("bandwidth"))!=null?lc:"",10)/1e3,Lc=(dc=K.getAttribute("frameRate"))!=null?dc:"",GS=(pc=K.getAttribute("quality"))!=null?pc:void 0,WS=Lc?Sg(Lc):void 0,YS=(hc=K.getAttribute("id"))!=null?hc:"id"+(y++).toString(10),QS=Pt==="video"?`${Rc}p`:Pt==="audio"?`${$c}Kbps`:ma,zS=`${YS}@${QS}`,KS=[...I,...BS,...tn],rn,JS=K.querySelector("SegmentBase"),At=(fc=K.querySelector("SegmentTemplate"))!=null?fc:NS;if(JS){let wt=(bc=(mc=K.querySelector("SegmentBase Initialization"))==null?void 0:mc.getAttribute("range"))!=null?bc:"",[kt,sn]=wt.split("-").map(Zt=>parseInt(Zt,10)),ct={from:kt,to:sn},Nr=(gc=K.querySelector("SegmentBase"))==null?void 0:gc.getAttribute("indexRange"),[nn,ba]=Nr?Nr.split("-").map(Zt=>parseInt(Zt,10)):[],Fr=Nr?{from:nn,to:ba}:void 0;rn={type:"byteRange",url:Zs,initRange:ct,indexRange:Fr}}else if(At){let wt={representationId:(Sc=K.getAttribute("id"))!=null?Sc:void 0,bandwidth:(vc=K.getAttribute("bandwidth"))!=null?vc:void 0},kt=parseInt((yc=At.getAttribute("timescale"))!=null?yc:"",10),sn=(Tc=At.getAttribute("initialization"))!=null?Tc:"",ct=At.getAttribute("media"),Nr=(Ec=parseInt((Ic=At.getAttribute("startNumber"))!=null?Ic:"",10))!=null?Ec:1,nn=jt(sn,wt);if(!ct)throw new ReferenceError("No media attribute in SegmentTemplate");let ba=(xc=At.querySelectorAll("SegmentTimeline S"))!=null?xc:[],Fr=[],Zt=0,on="",un=0;if(ba.length){let ga=Nr,Be=0;for(let er of ba){let Ue=parseInt((Pc=er.getAttribute("d"))!=null?Pc:"",10),Rt=parseInt((Ac=er.getAttribute("r"))!=null?Ac:"",10)||0,Sa=parseInt((wc=er.getAttribute("t"))!=null?wc:"",10);Be=Number.isFinite(Sa)?Sa:Be;let cn=Ue/kt*1e3,ln=Be/kt*1e3;for(let va=0;va<Rt+1;va++){let ZS=jt(ct,{...wt,segmentNumber:ga.toString(10),segmentTime:(Be+va*Ue).toString(10)}),Mc=(ln!=null?ln:0)+va*cn,ev=Mc+cn;ga++,Fr.push({time:{from:Mc,to:ev},url:ZS})}Be+=(Rt+1)*Ue,Zt+=(Rt+1)*cn}un=Be/kt*1e3,on=jt(ct,{...wt,segmentNumber:ga.toString(10),segmentTime:Be.toString(10)})}else if(vg(p)){let Be=parseInt((kc=At.getAttribute("duration"))!=null?kc:"",10)/kt*1e3,er=Math.ceil(p/Be),Ue=0;for(let Rt=1;Rt<er;Rt++){let Sa=jt(ct,{...wt,segmentNumber:Rt.toString(10),segmentTime:Ue.toString(10)});Fr.push({time:{from:Ue,to:Ue+Be},url:Sa}),Ue+=Be}un=Ue,on=jt(ct,{...wt,segmentNumber:er.toString(10),segmentTime:Ue.toString(10)})}let XS={time:{from:un,to:1/0},url:on};rn={type:"template",baseUrl:Zs,segmentTemplateUrl:ct,initUrl:nn,totalSegmentsDurationMs:Zt,segments:Fr,nextSegmentBeyondManifest:XS,timescale:kt}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!Pt||!Xt)continue;let an={video:"video",audio:"audio",text:"text"}[Pt];if(!an)continue;_r||(_r=an),en={id:zS,kind:an,segmentReference:rn,profiles:KS,duration:p,bitrate:$c,mime:Xt,codecs:ma,width:jS,height:Rc,fps:WS,quality:GS}}J.language||(J.language=qS),J.label||(J.label=US),J.mime||(J.mime=Xt),J.codecs||(J.codecs=ma),J.hdr||(J.hdr=_r==="video"&&Mu(ma)),J.representations.push(en)}_r&&i[_r].push(J)}return{dynamic:c,liveAvailabilityStartTime:d,duration:p,streams:i}};var Wi=He(fi(),1);import{videoSizeToQuality as Uk}from"@vkontakte/videoplayer-shared";var xg=({id:a,width:e,height:t,bitrate:r,fps:i,quality:s})=>{var o;let n=(o=s?mt(s):void 0)!=null?o:Uk({width:e,height:t});return n&&{id:a,quality:n,bitrate:r,size:{width:e,height:t},fps:i}},Pg=({id:a,bitrate:e})=>({id:a,bitrate:e}),xs=(a,e,t)=>{var i;let r=e.indexOf(a);return(i=(0,Wi.default)(t,Math.round(t.length*r/e.length)))!=null?i:(0,Wi.default)(t,-1)},Ag=({language:a,label:e},{id:t,url:r,isAuto:i})=>({id:t,url:r,isAuto:i,type:"internal",language:a,label:e}),Bu=({id:a,language:e,label:t,codecs:r,isDefault:i})=>({id:a,language:e,label:t,codec:(0,Wi.default)(r.split("."),0),isDefault:i}),Ou=({id:a,language:e,label:t,hdr:r,codecs:i})=>({id:a,language:e,hdr:r,label:t,codec:(0,Wi.default)(i.split("."),0)}),Ps=a=>"url"in a,it=a=>a.type==="template",Yi=a=>a instanceof DOMException&&(a.name==="AbortError"||a.code===20);var zi=class{constructor(e,t,r,{fetcher:i,tuning:s,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:c}){this.currentSegmentLength$=new Qi(0);this.onLastSegment$=new Qi(!1);this.fullyBuffered$=new Qi(!1);this.playingRepresentation$=new Qi(void 0);this.playingRepresentationInit$=new Qi(void 0);this.error$=new jk;this.gaps=[];this.subscription=new Gk;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new tt;this.destroyAbortController=new tt;this.bufferLimit=1/0;this.failedDownloads=0;this.isLive=!1;this.liveUpdateSegmentIndex=0;this.liveInitialAdditionalOffset=0;this.isSeekingLive=!1;this.index=0;this.loadByteRangeSegmentsTimeoutId=0;this.startWith=Rr(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);Ce(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new Ub(this.sourceBuffer),this.subscription.add(Vu(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let o,u=this.mediaSource.readyState;u!=="open"&&(o={id:`SegmentEjection_source_${u}`,category:Gt.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o!=null||(o={id:"SegmentEjection",category:Gt.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),this.error$.next(o)})),this.subscription.add(Vu(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:Gt.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o)return;let u=Math.min(this.bufferLimit,xu(this.sourceBuffer.buffered)*.8);if(this.bufferLimit=u,this.tuning.useNewPruneBufferStrategy){let c=Ze(this.sourceBuffer.buffered,o),l=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBufferNew(o,n*2,c<l)}else this.pruneBufferOld(o,n)})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(n=>this.error$.next(n))),yield this.loadInit(t,"high",!0);let r=this.initData.get(t.id),i=this.segments.get(t.id),s=this.parsedInitData.get(t.id);Ce(r,"No init buffer for starting representation"),Ce(i,"No segments for starting representation"),r instanceof ArrayBuffer&&(this.searchGaps(i,t),yield this.sourceBufferTaskQueue.append(r,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(s))}.bind(this));this.switchTo=Rr(this.destroyAbortController.signal,async function*(e,t=!1){if(e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let r=this.representations.get(e);Ce(r,`No such representation ${e}`);let i=this.segments.get(e),s=this.initData.get(e);if(De(s)||De(i)?yield this.loadInit(r,"high",!1):s instanceof Promise&&(yield s),i=this.segments.get(e),Ce(i,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer))if(this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer(),this.maintain();else{let n=this.getCurrentPosition();Nu(n)&&(this.isLive||(this.tuning.useNewPruneBufferStrategy&&(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=Rr(this.destroyAbortController.signal,async function*(e){var u,c;let t=(u=e==null?void 0:e.flatMap(l=>l.representations))!=null?u:[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let l of this.representations.keys()){let d=t.find(f=>f.id===l);d&&this.representations.set(l,d);let p=this.representations.get(l);if(!p||!it(p.segmentReference))return;let h=this.getActualLiveStartingSegments(p.segmentReference);this.segments.set(p.id,h)}let r=(c=this.switchingToRepresentationId)!=null?c:this.downloadingRepresentationId,i=this.representations.get(r);Ce(i);let s=this.segments.get(r);Ce(s,"No segments for starting representation");let n=this.initData.get(r);if(Ce(n,"No init buffer for starting representation"),!(n instanceof ArrayBuffer))return;let o=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,this.abort(),o&&(yield this.sourceBufferTaskQueue.remove(o.from*1e3,o.to*1e3,this.destroyAbortController.signal)),this.searchGaps(s,i),yield this.sourceBufferTaskQueue.append(n,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this));this.fetcher=i,this.tuning=s,this.compatibilityMode=u,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=o,this.isLive=!!(c!=null&&c.dynamic),this.resetAccumulateBufferAfterStall(),this.startAccumulateBuffer(),this.initData=new Map(r.map(l=>[l.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(r.map(l=>[l.id,l])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}abort(){for(let e of this.activeSegments)this.abortSegment(e.segment);this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new tt,this.abortBuffer()}maintain(e=this.getCurrentPosition()){var c,l;if(De(e)||De(this.downloadingRepresentationId)||De(this.playingRepresentationId)||De(this.sourceBuffer)||!De(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),r=this.segments.get(this.downloadingRepresentationId);if(Ce(t,`No such representation ${this.downloadingRepresentationId}`),!r)return;let i=r.find(d=>e>=d.time.from&&e<d.time.to);this.currentSegmentLength$.next(((c=i==null?void 0:i.time.to)!=null?c:0)-((l=i==null?void 0:i.time.from)!=null?l:0));let s=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){let p=Ze(this.sourceBuffer.buffered,e),h=i?i.time.to+100:-1/0;i&&i.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&p>=i.time.to-e+100&&(s=h)}if(isFinite(this.bufferLimit)&&xu(this.sourceBuffer.buffered)>=this.bufferLimit){let d=Ze(this.sourceBuffer.buffered,e),p=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,d<p);return}let o=[];if(!this.activeSegments.size&&(o=this.selectForwardBufferSegments(r,t.segmentReference.type,s),o.length)){let d="auto";if(this.tuning.dash.useFetchPriorityHints&&i)if(o.includes(i))d="high";else{let p=(0,$r.default)(o,0);p&&p.time.from-i.time.to>=this.forwardBufferTarget/2&&(d="low")}this.loadSegments(o,t,d)}(!this.preloadOnly&&!this.allInitsLoaded&&i&&i.status==="fed"&&!o.length&&Ze(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let u=(0,$r.default)(r,-1);u&&u.status==="fed"&&(this.fullyBuffered$.next(!0),this.isLive||this.onLastSegment$.next(i===u))}searchGaps(e,t){this.gaps=[];let r=0,i=this.isLive?this.liveInitialAdditionalOffset:0;for(let s of e)Math.trunc(s.time.from-r)>0&&this.gaps.push({representation:t.id,from:r,to:s.time.from+i}),r=s.time.to;Nu(t.duration)&&t.duration-r>0&&this.gaps.push({representation:t.id,from:r,to:t.duration})}getActualLiveStartingSegments(e){let t=e.segments,r=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,i=[],s=0,n=t.length-1;do i.unshift(t[n]),s+=t[n].time.to-t[n].time.from,n--;while(s<r&&n>=0);return this.liveInitialAdditionalOffset=s-r,this.isActiveLowLatency()?[i[0]]:i}getLiveSegmentsToLoadState(e){let t=e==null?void 0:e.streams[this.kind].flatMap(i=>i.representations).find(i=>i.id===this.downloadingRepresentationId);if(!t)return;let r=this.segments.get(t.id);if(r!=null&&r.length)return{from:r[0].time.from,to:r[r.length-1].time.to}}updateLive(e){var r,i,s,n;let t=(r=e==null?void 0:e.streams[this.kind].flatMap(o=>o.representations))!=null?r:[];for(let o of t){if(!o||!it(o.segmentReference))return;let u=o.segmentReference.segments.map(p=>({...p,status:"none",size:void 0})),c=(i=this.segments.get(o.id))!=null?i:[],l=(n=(s=(0,$r.default)(c,-1))==null?void 0:s.time.to)!=null?n:0,d=u==null?void 0:u.findIndex(p=>Math.floor(l)>=Math.floor(p.time.from)&&Math.floor(l)<=Math.floor(p.time.to));if(d===-1){this.liveUpdateSegmentIndex=0;let p=this.getActualLiveStartingSegments(o.segmentReference);this.segments.set(o.id,p)}else{let p=u.slice(d+1);this.segments.set(o.id,[...c,...p])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;Ce(e);let t=this.segments.get(e);if(t!=null&&t.length){let r=t[t.length-1];this.updateLowLatencyLiveIfNeeded(r)}}startAccumulateBuffer(){this.bufferAccumulation.enabled=!0}resetAccumulateBufferAfterStall(){this.bufferAccumulation={enabled:!1,targetBufferSizeMs:this.tuning.accumulationBufferStallSizeMs,accumulatedBufferSizeMs:0,accumulated:[]}}updateLowLatencyLiveIfNeeded(e){var t;for(let r of this.representations.values()){let i=r.segmentReference;if(!it(i))return;let s=(t=this.segments.get(r.id))!=null?t:[],n=s.find(u=>Math.floor(u.time.from)===Math.floor(e.time.from));if(n&&!isFinite(n.time.to)&&(n.time.to=e.time.to),!!!s.find(u=>Math.floor(u.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let u=Math.round(e.time.to*i.timescale/1e3).toString(10),c=jt(i.segmentTemplateUrl,{segmentTime:u});s.push({status:"none",time:{from:e.time.to,to:1/0},url:c})}}}findSegmentStartTime(e){var s,n,o;let t=(n=(s=this.switchingToRepresentationId)!=null?s:this.downloadingRepresentationId)!=null?n:this.playingRepresentationId;if(!t)return;let r=this.segments.get(t);if(!r)return;let i=r.find(u=>u.time.from<=e&&u.time.to>=e);return(o=i==null?void 0:i.time.from)!=null?o:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){var e;if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),(e=this.sourceBufferTaskQueue)==null||e.destroy(),this.gapDetectionIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer){this.mediaSource.readyState==="open"&&this.abortBuffer();try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(t){if(!(t instanceof DOMException&&t.name==="NotFoundError"))throw t}}this.sourceBuffer=null,this.downloadAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,r){return this.isLive?this.selectForwardBufferSegmentsLive(e,r):this.selectForwardBufferSegmentsRecord(e,t,r)}selectForwardBufferSegmentsLive(e,t){let r=e.findIndex(i=>t>=i.time.from&&t<i.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=r),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,r){let i=e.findIndex(({status:d,time:{from:p,to:h}},f)=>{let b=p<=r&&h>=r,g=p>r||b||f===0&&r===0,y=Math.min(this.forwardBufferTarget,this.bufferLimit),I=this.preloadOnly&&p<=r+y||h<=r+y;return(d==="none"||d==="partially_ejected"&&g&&I&&this.sourceBuffer&&!(xr(this.sourceBuffer.buffered,p)&&xr(this.sourceBuffer.buffered,h)))&&g&&I});if(i===-1)return[];if(t!=="byteRange")return e.slice(i,i+1);let s=e,n=0,o=0,u=[],c=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,l=this.preloadOnly?this.forwardBufferTarget:0;for(let d=i;d<s.length&&(n<=c||o<=l);d++){let p=s[d];if(n+=p.byte.to+1-p.byte.from,o+=p.time.to+1-p.time.from,p.status==="none"||p.status==="partially_ejected")u.push(p);else break}return u}async loadSegments(e,t,r="auto"){t.segmentReference.type==="template"?await this.loadTemplateSegment(e[0],t,r):await this.loadByteRangeSegments(e,t,r)}async loadTemplateSegment(e,t,r="auto"){e.status="downloading";let i={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(i);let{range:s,url:n,signal:o,onProgress:u,onProgressTasks:c}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(await Rr(o,async function*(){let l=_u(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(d=>setTimeout(d,l))}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let l=await this.fetcher.fetch(n,{range:s,signal:o,onProgress:u,priority:r,isLowLatency:this.isActiveLowLatency()});if(!l)return;let d=new DataView(l);if(!isFinite(i.segment.time.to)){let p=t.segmentReference.timescale,h=wr(t.mime);i.segment.time.to=h.getSegmentEndTime(d,p)}u&&i.feedingBytes&&c?await Promise.all(c):await this.sourceBufferTaskQueue.append(d,o),i.segment.status="downloaded",this.onSegmentFullyAppended(i,t.id),this.failedDownloads=0}catch(l){this.abortActiveSegments([e]),Yi(l)||this.failedDownloads++}}async loadByteRangeSegments(e,t,r="auto"){if(!e.length)return;for(let u of e)u.status="downloading",this.activeSegments.add({segment:u,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:i,url:s,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(await Rr(n,async function*(){let u=_u(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(c,u),Vu(window,"online").pipe(Hk()).subscribe(()=>{c(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(s,{range:i,onProgress:o,signal:n,priority:r}),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),Yi(u)||this.failedDownloads++}}prepareByteRangeFetchSegmentParams(e,t){if(it(t.segmentReference))throw new Error("Representation is not byte range type");let r=t.segmentReference.url,i={from:(0,$r.default)(e,0).byte.from,to:(0,$r.default)(e,-1).byte.to},{signal:s}=this.downloadAbortController;return{url:r,range:i,signal:s,onProgress:(o,u)=>{if(!s.aborted)try{this.onSomeByteRangesDataLoaded({dataView:o,loaded:u,signal:s,onSegmentAppendFailed:()=>this.abort(),globalFrom:i?i.from:0,representationId:t.id})}catch(c){this.error$.next({id:"SegmentFeeding",category:Gt.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:c})}}}}prepareTemplateFetchSegmentParams(e,t){if(!it(t.segmentReference))throw new Error("Representation is not template type");let r=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&r.searchParams.set("low-latency","yes");let i=r.toString(),{signal:s}=this.downloadAbortController,n=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(c,l)=>{if(!s.aborted)try{let d=this.onSomeTemplateDataLoaded({dataView:c,loaded:l,signal:s,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(d)}catch(d){this.error$.next({id:"SegmentFeeding",category:Gt.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:d})}}:void 0;return{url:i,signal:s,onProgress:u,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)e.includes(t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:r,onSegmentAppendFailed:i,signal:s}){if(!this.activeSegments.size)return;let n=this.representations.get(t);if(n)for(let o of this.activeSegments){let{segment:u}=o;if(o.representationId===t){if(s.aborted){i();continue}if(o.loadedBytes=r,o.loadedBytes>o.feedingBytes){let c=new DataView(e.buffer,e.byteOffset+o.feedingBytes,o.loadedBytes-o.feedingBytes),l=wr(n.mime).parseFeedableSegmentChunk(c,this.isLive);l!=null&&l.byteLength&&(u.status="partially_fed",o.feedingBytes+=l.byteLength,await this.sourceBufferTaskQueue.append(l),o.fedBytes+=l.byteLength)}}}}onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:r,loaded:i,signal:s,onSegmentAppendFailed:n}){let o={dataView:e,representationId:t,globalFrom:r,loaded:i,signal:s,onSegmentAppendFailed:n};return this.tuning.useNewPartialSegmentFeeding?this.onSomeByteRangesDataLoadedNew(o):this.onSomeByteRangesDataLoadedOld(o)}onSomeByteRangesDataLoadedOld({dataView:e,representationId:t,globalFrom:r,loaded:i,signal:s,onSegmentAppendFailed:n}){if(!this.activeSegments.size)return;let o=this.representations.get(t);if(!o)return;let u=o.segmentReference.type,c=e.byteLength;for(let l of this.activeSegments){let{segment:d}=l,p=u==="byteRange",h=p?d.byte.to-d.byte.from+1:c;if(l.representationId!==t||!(!p||d.byte.from>=r&&d.byte.to<r+e.byteLength))continue;if(s.aborted){n();continue}let b=p?d.byte.from-r:0,g=p?d.byte.to-r:e.byteLength,y=b<i,I=g<=i;if(d.status==="downloading"&&y&&I){d.status="downloaded";let S=new DataView(e.buffer,e.byteOffset+b,h),v=this.getCurrentPosition();Nu(v)&&(this.bufferAccumulation.accumulatedBufferSizeMs=d.time.to-v,this.bufferAccumulation.accumulated.push({segmentView:S,segmentProgress:l}),this.activeSegments.delete(l));let T=({segmentView:R,segmentProgress:U})=>this.sourceBufferTaskQueue.append(R,s).then($=>$&&!s.aborted?this.onSegmentFullyAppended(U,t):n());this.bufferAccumulation.enabled&&this.bufferAccumulation.targetBufferSizeMs<this.bufferAccumulation.accumulatedBufferSizeMs?(this.bufferAccumulation.accumulated.forEach(T),this.resetAccumulateBufferAfterStall()):(!this.bufferAccumulation.enabled||!this.bufferAccumulation.targetBufferSizeMs||De(v))&&(T({segmentView:S,segmentProgress:l}),this.resetAccumulateBufferAfterStall())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&y&&!I&&(l.loadedBytes=Math.min(h,i-b),l.loadedBytes>l.feedingBytes)){let S=new DataView(e.buffer,e.byteOffset+b+l.feedingBytes,l.loadedBytes-l.feedingBytes),v=l.loadedBytes===h?S:wr(o.mime).parseFeedableSegmentChunk(S);v!=null&&v.byteLength&&(d.status="partially_fed",l.feedingBytes+=v.byteLength,this.sourceBufferTaskQueue.append(v,s).then(T=>{if(s.aborted)n();else if(T)l.fedBytes+=v.byteLength,l.fedBytes===h&&this.onSegmentFullyAppended(l,t);else{if(l.feedingBytes<h)return;n()}}))}}}async onSomeByteRangesDataLoadedNew({dataView:e,representationId:t,globalFrom:r,loaded:i,signal:s,onSegmentAppendFailed:n}){if(!this.activeSegments.size)return;let o=this.representations.get(t);if(o)for(let u of this.activeSegments){let{segment:c}=u;if(u.representationId!==t)continue;if(s.aborted){n();continue}let l=c.byte.from-r,d=c.byte.to-r,p=d-l+1,h=l<i,f=d<=i;if(h){if(c.status==="downloading"&&f){c.status="downloaded";let b=new DataView(e.buffer,e.byteOffset+l,p);await this.sourceBufferTaskQueue.append(b,s)&&!s.aborted?this.onSegmentFullyAppended(u,t):n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(c.status==="downloading"||c.status==="partially_fed")&&(u.loadedBytes=Math.min(p,i-l),u.loadedBytes>u.feedingBytes)){let b=new DataView(e.buffer,e.byteOffset+l+u.feedingBytes,u.loadedBytes-u.feedingBytes),g=u.loadedBytes===p?b:wr(o.mime).parseFeedableSegmentChunk(b);g!=null&&g.byteLength&&(c.status="partially_fed",u.feedingBytes+=g.byteLength,await this.sourceBufferTaskQueue.append(g,s)&&!s.aborted?(u.fedBytes+=g.byteLength,u.fedBytes===p&&this.onSegmentFullyAppended(u,t)):n())}}}}onSegmentFullyAppended(e,t){var r;this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status="fed",Ps(e.segment)&&(e.segment.size=e.fedBytes);for(let i of this.representations.values())if(i.id!==t)for(let s of(r=this.segments.get(i.id))!=null?r:[])s.status==="fed"&&Math.round(s.time.from)===Math.round(e.segment.time.from)&&Math.round(s.time.to)===Math.round(e.segment.time.to)&&(s.status="none");Ce(this.sourceBuffer),this.updateLowLatencyLiveIfNeeded(e.segment),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment])}abortSegment(e){e.status==="partially_fed"?e.status="partially_ejected":e.status!=="partially_ejected"&&(e.status="none");for(let t of this.activeSegments.values())if(t.segment===e){this.activeSegments.delete(t);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(let[i,s]of this.initData.entries()){let n=s instanceof Promise;t||(t=n),s===null&&(e=i)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let r=this.representations.get(e);r&&(this.initLoadIdleCallback=Tu(()=>(0,wg.default)(this.loadInit(r,"low",!1),()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",r=!1){let i=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!r&&this.failedDownloads>0?Rr(this.destroyAbortController.signal,async function*(){let o=_u(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,wr(e.mime),i)).then(async o=>{if(!o)return;let{init:u,dataView:c,segments:l}=o,d=c.buffer.slice(c.byteOffset,c.byteOffset+c.byteLength);this.initData.set(e.id,d);let p=l;this.isLive&&it(e.segmentReference)&&(p=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,p),u&&this.parsedInitData.set(e.id,u)}).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),r&&this.error$.next({id:"LoadInits",category:Gt.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n}async dropBuffer(){for(let e of this.segments.values())for(let t of e)t.status="none";await this.pruneBuffer(0,1/0,!0)}async pruneBuffer(e,t,r=!1){return this.tuning.useNewPruneBufferStrategy?this.pruneBufferNew(e,t,r):this.pruneBufferOld(e,t,r)}async pruneBufferNew(e,t,r=!1){if(!this.sourceBuffer||!this.playingRepresentationId||De(e)||this.sourceBuffer.updating)return!1;let i=[],s=0,n=u=>{u.sort((l,d)=>l.from-d.from);let c=[u[0]];for(let l=1;l<u.length;l++){let{from:d,to:p}=u[l],h=c[c.length-1];h.to>=d?h.to=Math.max(h.to,p):c.push(u[l])}return c},o=u=>{var l;if(s>=t)return i;i.push({...u.time}),i=n(i);let c=Ps(u)?(l=u.size)!=null?l:0:u.byte.to-u.byte.from;s+=c};for(let u of this.segments.values())for(let c of u){let l=c.time.to<=e-this.tuning.dash.bufferPruningSafeZone,d=c.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(l||d)&&c.status==="fed"&&o(c)}for(let u=0;u<this.sourceBuffer.buffered.length;u++){let c=this.sourceBuffer.buffered.start(u)*1e3,l=this.sourceBuffer.buffered.end(u)*1e3,d=0;for(let p of this.segments.values())for(let h of p)["none","partially_ejected"].includes(h.status)&&Math.round(h.time.from)<=Math.round(c)&&Math.round(h.time.to)>=Math.round(l)&&d++;if(d===this.segments.size){let p={time:{from:c,to:l},url:"",status:"none"};o(p)}}if(i.length&&r){let u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let c of this.segments.values())for(let l of c)l.time.from>=e+u&&l.status==="fed"&&o(l)}return i.length?(await Promise.all(i.map(c=>this.sourceBufferTaskQueue.remove(c.from,c.to)))).reduce((c,l)=>c||l,!1):!1}async pruneBufferOld(e,t,r=!1){if(!this.sourceBuffer||!this.playingRepresentationId||De(e)||this.sourceBuffer.updating)return!1;let i=0,s=1/0,n=-1/0,o=!1,u=c=>{var d;s=Math.min(s,c.time.from),n=Math.max(n,c.time.to);let l=Ps(c)?(d=c.size)!=null?d:0:c.byte.to-c.byte.from;i+=l};for(let c of this.segments.values())for(let l of c){if(l.time.to>=e-this.tuning.dash.bufferPruningSafeZone||i>=t)break;l.status==="fed"&&u(l)}if(o=isFinite(s)&&isFinite(n),!o){i=0,s=1/0,n=-1/0;for(let c of this.segments.values())for(let l of c){if(l.time.from<e+Math.min(this.forwardBufferTarget,this.bufferLimit)||i>t)break;l.status==="fed"&&u(l)}}if(o=isFinite(s)&&isFinite(n),!o)for(let c=0;c<this.sourceBuffer.buffered.length;c++){let l=this.sourceBuffer.buffered.start(c)*1e3,d=this.sourceBuffer.buffered.end(c)*1e3;for(let p of this.segments.values())for(let h of p)if(h.status==="none"&&Math.round(h.time.from)<=Math.round(l)&&Math.round(h.time.to)>=Math.round(d)){s=l,n=d;break}}if(o=isFinite(s)&&isFinite(n),!o&&r){i=0,s=1/0,n=-1/0;let c=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+c&&d.status==="fed"&&u(d)}return o=isFinite(s)&&isFinite(n),o?this.sourceBufferTaskQueue.remove(s,n):!1}abortBuffer(){if(!this.sourceBuffer||this.mediaSource.readyState!=="open")return;let e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;this.sourceBufferTaskQueue.abort(t)}getDebugBufferState(){if(!(!this.sourceBuffer||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}detectGaps(e,t){if(this.sourceBuffer)for(let r of t){let i={representation:e,from:r.time.from,to:r.time.to};for(let s=0;s<this.sourceBuffer.buffered.length;s++){let n=this.sourceBuffer.buffered.start(s)*1e3,o=this.sourceBuffer.buffered.end(s)*1e3;if(!(o<=r.time.from||n>=r.time.to)){if(n<=r.time.from&&o>=r.time.to){i=void 0;break}o>r.time.from&&o<r.time.to&&(i.from=o),n<r.time.to&&n>r.time.from&&(i.to=n)}}i&&i.to-i.from>1&&!this.gaps.some(s=>i&&s.from===i.from&&s.to===i.to)&&this.gaps.push(i)}}detectGapsWhenIdle(e,t){if(!this.gapDetectionIdleCallback){Ce(this.sourceBuffer);for(let r=0;r<this.sourceBuffer.buffered.length;r++)this.gaps=this.gaps.filter(i=>this.sourceBuffer&&(Math.round(i.from)<Math.round(this.sourceBuffer.buffered.start(r)*1e3)||Math.round(i.to)>Math.round(this.sourceBuffer.buffered.end(r)*1e3)));this.gapDetectionIdleCallback=Tu(()=>{try{this.detectGaps(e,t)}catch(r){this.error$.next({id:"GapDetection",category:Gt.WTF,message:"detectGaps threw",thrown:r})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if(De(this.sourceBuffer)||De(this.playingRepresentationId))return;let e=[];for(let r=0;r<this.sourceBuffer.buffered.length;r++){let i=Math.floor(this.sourceBuffer.buffered.start(r)*1e3),s=Math.ceil(this.sourceBuffer.buffered.end(r)*1e3);e.push({from:i,to:s})}let t=10;for(let r of this.segments.values())for(let i of r){let{status:s}=i;if(s!=="fed"&&s!=="partially_ejected")continue;let n=Math.floor(i.time.from),o=Math.ceil(i.time.to),u=e.some(l=>l.from-t<=n&&l.to+t>=o),c=e.filter(l=>n>=l.from&&n<l.to-t||o>l.from+t&&o<=l.to);u||(c.length===1?i.status="partially_ejected":this.gaps.some(l=>l.from===i.time.from||l.to===i.time.to)?i.status="partially_ejected":i.status="none")}}};var Ki=a=>{let e=new URL(a);return e.searchParams.set("quic","1"),e.toString()};var kg=a=>{var s;let e=a.get("X-Delivery-Type"),t=a.get("X-Reused"),r=e===null?"http1":e!=null?e:void 0,i=t===null?void 0:(s={1:!0,0:!1}[t])!=null?s:void 0;return{type:r,reused:i}};import{abortable as Ji,assertNever as Rg,fromEvent as $g,merge as Wk,now as Xi,Subscription as Yk,ValueSubject as Fu,flattenObject as Lr}from"@vkontakte/videoplayer-shared";var As=class{constructor({throughputEstimator:e,requestQuic:t,tracer:r,compatibilityMode:i=!1}){this.lastConnectionType$=new Fu(void 0);this.lastConnectionReused$=new Fu(void 0);this.lastRequestFirstBytes$=new Fu(void 0);this.abortAllController=new tt;this.subscription=new Yk;this.fetchManifest=Ji(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),r=e;this.requestQuic&&(r=Ki(r));let i=yield et(r,{signal:this.abortAllController.signal}).catch(Zi);return i?(t.log("success",Lr({url:r,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(i.headers),i.text()):(t.error("error",Lr({url:r,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=Ji(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:r,onProgress:i,priority:s="auto",signal:n,measureThroughput:o=!0,isLowLatency:u=!1}={}){var O,w;let c=e,l=new Headers,d=this.tracer.createComponentTracer("Fetch");if(r)switch(t){case 0:{l.append("Range",`bytes=${r.from}-${r.to}`);break}case 1:{let L=new URL(c,location.href);L.searchParams.append("bytes",`${r.from}-${r.to}`),c=L.toString();break}default:Rg(t)}this.requestQuic&&(c=Ki(c));let p=this.abortAllController.signal,h;if(n){let L=new tt;if(h=Wk($g(this.abortAllController.signal,"abort"),$g(n,"abort")).subscribe(()=>{try{L.abort()}catch(q){Zi(q)}}),this.abortAllController.signal.aborted||n.aborted)try{L.abort()}catch(q){Zi(q)}p=L.signal}let f=Xi();d.log("startRequest",Lr({url:c,priority:s,rangeMethod:t,range:r,isLowLatency:u,requestStartedAt:f}));let b=yield et(c,{priority:s,headers:l,signal:p}).catch(Zi),g=Xi();if(!b)return d.error("error",{message:"No response in request"}),d.end(),h==null||h.unsubscribe(),null;if((O=this.throughputEstimator)==null||O.addRawRtt(g-f),!b.ok||!b.body){h==null||h.unsubscribe();let L=`Fetch error ${b.status}: ${b.statusText}`;return d.error("error",{message:L}),d.end(),Promise.reject(new Error(`Fetch error ${b.status}: ${b.statusText}`))}if(this.onHeadersReceived(b.headers),!i&&!o){h==null||h.unsubscribe();let L=Xi(),q={requestStartedAt:f,requestEndedAt:L,duration:L-f};return d.log("endRequest",Lr(q)),d.end(),b.arrayBuffer()}let[y,I]=b.body.tee(),S=y.getReader();o&&((w=this.throughputEstimator)==null||w.trackStream(I,u));let v=0,T=new Uint8Array(0),R=!1,U=L=>{h==null||h.unsubscribe(),R=!0,Zi(L)},$=Ji(p,async function*({done:L,value:q}){if(v===0&&this.lastRequestFirstBytes$.next(Xi()-f),p.aborted){h==null||h.unsubscribe();return}if(!L&&q){let k=new Uint8Array(T.length+q.length);k.set(T),k.set(q,T.length),T=k,v+=q.byteLength,i==null||i(new DataView(T.buffer),v),yield S==null?void 0:S.read().then($,U)}}.bind(this));yield S==null?void 0:S.read().then($,U),h==null||h.unsubscribe();let B=Xi(),N={failed:R,requestStartedAt:f,requestEndedAt:B,duration:B-f};return R?(d.error("endRequest",Lr(N)),d.end(),null):(d.log("endRequest",Lr(N)),d.end(),T.buffer)}.bind(this));this.fetchByteRangeRepresentation=Ji(this.abortAllController.signal,async function*(e,t,r){var y;if(e.type!=="byteRange")return null;let{from:i,to:s}=e.initRange,n=i,o=s,u=!1,c,l;e.indexRange&&(c=e.indexRange.from,l=e.indexRange.to,u=s+1===c,u&&(n=Math.min(c,i),o=Math.max(l,s))),n=Math.min(n,0);let d=yield this.fetch(e.url,{range:{from:n,to:o},priority:r,measureThroughput:!1});if(!d)return null;let p=new DataView(d,i-n,s-n+1);if(!t.validateData(p))throw new Error("Invalid media file");let h=t.parseInit(p),f=(y=e.indexRange)!=null?y:t.getIndexRange(h);if(!f)throw new ReferenceError("No way to load representation index");let b;if(u)b=new DataView(d,f.from-n,f.to-f.from+1);else{let I=yield this.fetch(e.url,{range:f,priority:r,measureThroughput:!1});if(!I)return null;b=new DataView(I)}let g=t.parseSegments(b,h,f);return{init:h,dataView:new DataView(d),segments:g}}.bind(this));this.fetchTemplateRepresentation=Ji(this.abortAllController.signal,async function*(e,t){if(e.type!=="template")return null;let r=new URL(e.initUrl,e.baseUrl).toString(),i=yield this.fetch(r,{priority:t,measureThroughput:!1});return i?{init:null,segments:e.segments.map(n=>({...n,status:"none",size:void 0})),dataView:new DataView(i)}:null}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=i,this.tracer=r.createComponentTracer("Fetcher")}onHeadersReceived(e){let{type:t,reused:r}=kg(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(r)}async fetchRepresentation(e,t,r="auto"){var s,n;let{type:i}=e;switch(i){case"byteRange":return(s=await this.fetchByteRangeRepresentation(e,t,r))!=null?s:null;case"template":return(n=await this.fetchTemplateRepresentation(e,r))!=null?n:null;default:Rg(i)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}},Zi=a=>{if(!Yi(a))throw a};var Wt=(a,e,t)=>t*e+(1-t)*a,qu=(a,e)=>a.reduce((t,r)=>t+r,0)/e,Lg=(a,e,t,r)=>{let i=0,s=t,n=qu(a,e),o=e<r?e:r;for(let u=0;u<o;u++)a[s]>n?i++:i--,s=(a.length+s-1)%a.length;return Math.abs(i)===o};import{isNullable as Qk,ValueSubject as Mg}from"@vkontakte/videoplayer-shared";var gt=class{constructor(e){this.prevReported=void 0;this.pastMeasures=[];this.takenMeasures=0;this.measuresCursor=0;var r;this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new Mg(e.initial),this.debounced$=new Mg(e.initial);let t=(r=e.label)!=null?r:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new re(`raw_${t}`),this.smoothedSeries$=new re(`smoothed_${t}`),this.reportedSeries$=new re(`reported_${t}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,r=0;for(let o=0;o<this.pastMeasures.length;o++)this.pastMeasures[o]!==void 0&&(t+=(this.pastMeasures[o]-this.smoothed)**2,r++);this.takenMeasures=r,t/=r;let i=Math.sqrt(t),s=this.smoothed+this.params.deviationFactor*i,n=this.smoothed-this.params.deviationFactor*i;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(e),this.updateSmoothedValue(e),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),!(this.smoothed>s||this.smoothed<n)&&(Qk(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 ws=class extends gt{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=Wt(this.slow,e,this.params.emaAlphaSlow),this.fast=Wt(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var ks=class extends gt{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=qu(this.pastMeasures,this.takenMeasures);this.emaSmoothed=Wt(this.emaSmoothed,e,this.params.emaAlpha);let r=Lg(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=r?this.emaSmoothed:t}};var Rs=class extends gt{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?Wt(this.smoothed,t,this.params.emaAlpha):t}};var Yt=class{static getSmoothedValue(e,t,r){return r.type==="TwoEma"?new ws({initial:e,emaAlphaSlow:r.emaAlphaSlow,emaAlphaFast:r.emaAlphaFast,changeThreshold:r.changeThreshold,fastDirection:t,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"}):new ks({initial:e,emaAlpha:r.emaAlpha,basisTrendChangeCount:r.basisTrendChangeCount,changeThreshold:r.changeThreshold,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"})}static getLiveEstimatedDelaySmoothedValue(e,t){return new Rs({initial:e,label:"liveEdgeDelay",...t})}};var Uu=(a,e)=>{a&&a.playbackRate!==e&&(a.playbackRate=e)};var _g=["timeupdate","progress","play","seeked","stalled","waiting"];var Ms=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new Vg;this.representationSubscription=new Vg;this.state$=new M("none");this.currentVideoRepresentation$=new ie(void 0);this.currentVideoRepresentationInit$=new ie(void 0);this.currentAudioRepresentation$=new ie(void 0);this.currentVideoSegmentLength$=new ie(0);this.currentAudioSegmentLength$=new ie(0);this.error$=new Og;this.lastConnectionType$=new ie(void 0);this.lastConnectionReused$=new ie(void 0);this.lastRequestFirstBytes$=new ie(void 0);this.isLive$=new ie(!1);this.liveDuration$=new ie(0);this.liveAvailabilityStartTime$=new ie(void 0);this.bufferLength$=new ie(0);this.liveLoadBufferLength$=new ie(0);this.livePositionFromPlayer$=new ie(0);this.timeInWaiting=0;this.isActiveLowLatency$=new ie(!1);this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.liveLastSeekOffset=0;this.forceEnded$=new Og;this.gapWatchdogActive=!1;this.destroyController=new tt;this.initManifest=Hu(this.destroyController.signal,async function*(e,t,r){var i;this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=ee(t,r,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),(i=this.manifest)!=null&&i.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:St.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=Hu(this.destroyController.signal,async function*(){var n,o;this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(u=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:St.NETWORK,message:"Failed to load manifest",thrown:u})});if(!e)return null;let t;try{t=Eg(e!=null?e:"",this.manifestUrlString)}catch(u){let c=(n=Vb(e))!=null?n:{id:"ManifestParsing",category:St.PARSER,message:"Failed to parse MPD manifest",thrown:u};this.error$.next(c)}if(!t)return null;let r=(u,c,l)=>{var d,p,h,f;return!!((p=(d=this.element)==null?void 0:d.canPlayType)!=null&&p.call(d,c)&&((f=(h=rt())==null?void 0:h.isTypeSupported)!=null&&f.call(h,`${c}; codecs="${l}"`))||u==="text")};t.dynamic&&this.isLive$.getValue()!==t.dynamic&&(this.isLive$.next(t.dynamic),this.liveDuration$.getValue()!==t.duration&&this.liveDuration$.next(-1*((o=t.duration)!=null?o:0)/1e3),this.liveAvailabilityStartTime$.getValue()!==t.liveAvailabilityStartTime&&this.liveAvailabilityStartTime$.next(t.liveAvailabilityStartTime));let i={text:t.streams.text,video:[],audio:[]};for(let u of["video","audio"]){let l=t.streams[u].filter(({mime:h,codecs:f})=>r(u,h,f)),d=new Set(l.map(({codecs:h})=>h)),p=Ob(d);if(p&&(i[u]=l.filter(({codecs:h})=>h.startsWith(p))),u==="video"){let h=this.tuning.preferHDR,f=i.video.some(g=>g.hdr),b=i.video.some(g=>!g.hdr);Zk.isHDR&&h&&f?i.video=i.video.filter(g=>g.hdr):b&&(i.video=i.video.filter(g=>!g.hdr))}}let s={...t,streams:i};return this.tracer.log("updateManifestEnd",ea(s)),s}.bind(this));this.initRepresentations=Hu(this.destroyController.signal,async function*(e,t,r){var d;this.tracer.log("initRepresentationsStart",ea({initialVideo:e,initialAudio:t,sourceHls:r})),Qt(this.manifest),Qt(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let i=p=>{this.representationSubscription.add(Mr(p,"error").pipe(Ls(h=>{var f;return!!((f=this.element)!=null&&f.played.length)})).subscribe(h=>{this.error$.next({id:"VideoSource",category:St.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:h})}))};this.source=this.tuning.useManagedMediaSource?Sb():new MediaSource;let s=document.createElement("source");if(i(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),this.tuning.useManagedMediaSource&&fs())if(r){let p=document.createElement("source");i(p),p.type="application/x-mpegurl",p.src=r.url,this.element.appendChild(p)}else this.element.disableRemotePlayback=!0;this.isActiveLowLatency$.next(this.isLive$.getValue()&&this.tuning.dashCmafLive.lowLatency.isActive);let n={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLowLatency$.getValue(),manifest:this.manifest},o=this.manifest.streams.video.reduce((p,h)=>[...p,...h.representations],[]);if(this.videoBufferManager=new zi("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],Bg(t)){let p=this.manifest.streams.audio.reduce((h,f)=>[...h,...f.representations],[]);this.audioBufferManager=new zi("audio",this.source,p,n),this.bufferManagers.push(this.audioBufferManager)}if(this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$)),this.representationSubscription.add(ju(1e3).subscribe(p=>{var h;if((h=this.element)!=null&&h.paused){let f=eu(this.manifestUrlString,2);this.manifestUrlString=ee(this.manifestUrlString,f+1e3,2)}})),this.representationSubscription.add(Cr(..._g.filter(p=>p!=="waiting").map(p=>Mr(this.element,p))).pipe(Gu(p=>this.element?Ze(this.element.buffered,this.element.currentTime*1e3):0),Dg(),Ls(p=>!!p),Jk(p=>{var h;(h=this.stallWatchdogSubscription)==null||h.unsubscribe(),this.timeInWaiting=0})).subscribe(this.bufferLength$)),this.isLive$.getValue()){this.representationSubscription.add(this.isActiveLowLatency$.pipe(Dg()).subscribe(h=>Uu(this.element,1))),this.representationSubscription.add($s({bufferLength:this.bufferLength$,isActiveLowLatency:this.isActiveLowLatency$}).pipe(Ls(({bufferLength:h,isActiveLowLatency:f})=>f&&!!h)).subscribe(({bufferLength:h})=>this.liveEstimatedDelay.next(h))),this.representationSubscription.add($s({liveEstimatedDelay:this.liveEstimatedDelay.smoothed$,isActiveLowLatency:this.isActiveLowLatency$}).subscribe(({liveEstimatedDelay:h,isActiveLowLatency:f})=>{if(!f)return;let b=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,g=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,y=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,I=h-b,S=1;Math.abs(I)>g&&(S=1+Math.sign(I)*y),Uu(this.element,S)})),this.representationSubscription.add(this.bufferLength$.subscribe(h=>{var b,g;let f=0;if(h){let y=((g=(b=this.element)==null?void 0:b.currentTime)!=null?g:0)*1e3;f=Math.min(...this.bufferManagers.map(S=>{var v,T;return(T=(v=S.getLiveSegmentsToLoadState(this.manifest))==null?void 0:v.to)!=null?T:y}))-y}this.liveLoadBufferLength$.getValue()!==f&&this.liveLoadBufferLength$.next(f)}));let p=0;this.representationSubscription.add($s({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(Xk(1e3)).subscribe(async({liveLoadBufferLength:h,bufferLength:f})=>{if(Qt(this.element),this.isUpdatingLive)return;let b=this.element.playbackRate,g=eu(this.manifestUrlString,2),y=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,I=Math.min(y,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*b),S=this.tuning.dashCmafLive.normalizedActualBufferOffset*b,v=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*b,T=isFinite(h)?h:f,R=this.isActiveLowLatency$.getValue(),U=y<=this.tuning.live.activeLiveDelay&&g===0;this.isActiveLowLatency$.next(R&&U);let $="none";if(R?$="active_low_latency":this.tuning.dashCmafLive.lowLatency.isActive&&U?(this.isActiveLowLatency$.next(!0),this.bufferManagers.forEach(B=>B.proceedLowLatencyLive()),$="active_low_latency"):g!==0&&T<I?$="live_forward_buffering":T<I+v&&($="live_with_target_offset"),isFinite(h)&&(p=h>p?h:p),$==="live_forward_buffering"||$==="live_with_target_offset"){let B=p-(I+S),N=this.normolizeLiveOffset(Math.trunc(g+B/b)),O=Math.abs(N-g),w;!h||O<=this.tuning.dashCmafLive.offsetCalculationError?w=g:N>0&&O>this.tuning.dashCmafLive.offsetCalculationError?w=N:w=0,this.manifestUrlString=ee(this.manifestUrlString,w,2)}$!=="none"&&$!=="active_low_latency"&&(p=0,this.updateLive())}))}let u=Cr(...this.bufferManagers.map(p=>p.fullyBuffered$)).pipe(Gu(()=>this.bufferManagers.every(p=>p.fullyBuffered$.getValue()))),c=Cr(...this.bufferManagers.map(p=>p.onLastSegment$)).pipe(Gu(()=>this.bufferManagers.some(p=>p.onLastSegment$.getValue())));this.representationSubscription.add(Cr(this.forceEnded$,$s({allBuffersFull:u,someBufferEnded:c}).pipe(Ls(({allBuffersFull:p,someBufferEnded:h})=>p&&h))).subscribe(()=>{var p;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(h=>!h.updating))try{(p=this.source)==null||p.endOfStream()}catch(h){this.error$.next({id:"EndOfStream",category:St.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:h})}})),this.representationSubscription.add(Cr(...this.bufferManagers.map(p=>p.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.subscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.subscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&(this.representationSubscription.add(this.audioBufferManager.playingRepresentation$.subscribe(this.currentAudioRepresentation$)),this.subscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$))),this.source.readyState!=="open"&&(yield new Promise(p=>{var h;return(h=this.source)==null?void 0:h.addEventListener("sourceopen",p)}));let l=[(d=this.manifest.duration)!=null?d:0,...[...this.manifest.streams.audio,...this.manifest.streams.video].flatMap(p=>p.representations).flatMap(p=>{let h=[];return p.duration&&h.push(p.duration),it(p.segmentReference)&&p.segmentReference.totalSegmentsDurationMs&&h.push(p.segmentReference.totalSegmentsDurationMs),h})];this.source.duration=Math.max(...l)/1e3,this.audioBufferManager&&Bg(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState("representations_ready"),this.tracer.log("initRepresentationsEnd")}.bind(this));this.tick=()=>{var t,r;if(!this.element||!this.videoBufferManager)return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),(t=this.audioBufferManager)==null||t.maintain(e),(this.videoBufferManager.gaps.length||(r=this.audioBufferManager)!=null&&r.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=ju(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),i=>{this.error$.next({id:"GapWatchdog",category:St.WTF,message:"Error handling gaps",thrown:i})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name),this.fetcher=new As({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer}),this.liveEstimatedDelay=Yt.getLiveEstimatedDelaySmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.delayEstimator}),this.initTracerSubscription()}async seekLive(e){var r,i,s,n;Qt(this.element);let t=this.normolizeLiveOffset(e);this.isActiveLowLatency$.next(this.tuning.dashCmafLive.lowLatency.isActive&&t===0),this.liveLastSeekOffset=t,this.manifestUrlString=ee(this.manifestUrlString,t,2),this.manifest=await this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,await((i=this.videoBufferManager)==null?void 0:i.seekLive((r=this.manifest)==null?void 0:r.streams.video)),await((n=this.audioBufferManager)==null?void 0:n.seekLive((s=this.manifest)==null?void 0:s.streams.audio)))}initBuffer(){Qt(this.element),this.state$.setState("running"),this.subscription.add(Cr(..._g.map(e=>Mr(this.element,e)),Mr(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:St.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(Mr(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(Mr(this.element,"waiting").subscribe(()=>{var t,r,i;this.element&&this.element.readyState===2&&!this.element.seeking&&xr(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{var n,o;if(!this.element)return;this.timeInWaiting+=1e3;let s={timeInWaiting:this.timeInWaiting};if(this.timeInWaiting>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${this.tuning.dash.crashOnStallTimeout} ms`);if(this.isLive$.getValue()&&this.timeInWaiting%5e3===0)this.seekLive(this.liveLastSeekOffset),s={...s,liveLastSeekOffset:this.liveLastSeekOffset};else{let u=this.element.currentTime*1e3;(n=this.videoBufferManager)==null||n.maintain(u),(o=this.audioBufferManager)==null||o.maintain(u),s={...s,position:u}}this.tracer.log("stallIntervalCallback",ea(s))};(t=this.videoBufferManager)==null||t.startAccumulateBuffer(),(r=this.audioBufferManager)==null||r.startAccumulateBuffer(),(i=this.stallWatchdogSubscription)==null||i.unsubscribe(),this.stallWatchdogSubscription=ju(1e3).subscribe(e,s=>{this.error$.next({id:"StallWatchdogCallback",category:St.FATAL,message:"Can't restore DASH after stall.",thrown:s})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t,r=!1){let i={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return i==null?void 0:i.switchTo(t,r)}seek(e,t){var i,s,n,o,u,c;Qt(this.element),Qt(this.videoBufferManager);let r;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?r=e:r=Math.max((i=this.videoBufferManager.findSegmentStartTime(e))!=null?i:e,(n=(s=this.audioBufferManager)==null?void 0:s.findSegmentStartTime(e))!=null?n:e),xr(this.element.buffered,r)||(this.videoBufferManager.abort(),(o=this.audioBufferManager)==null||o.abort()),this.videoBufferManager.startAccumulateBuffer(),this.videoBufferManager.maintain(r),(u=this.audioBufferManager)==null||u.startAccumulateBuffer(),(c=this.audioBufferManager)==null||c.maintain(r),this.element.currentTime=r/1e3,this.tracer.log("seek",ea({requestedPosition:e,forcePrecise:t,position:r}))}stop(){var e,t,r;this.tracer.log("stop"),(e=this.element)==null||e.querySelectorAll("source").forEach(i=>i.remove()),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),(t=this.videoBufferManager)==null||t.destroy(),this.videoBufferManager=null,(r=this.audioBufferManager)==null||r.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getStreams(){var e;return(e=this.manifest)==null?void 0:e.streams}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){var e;this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),((e=this.source)==null?void 0:e.readyState)==="open"&&Array.from(this.source.sourceBuffers).every(t=>!t.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}initTracerSubscription(){let e=eR(this.tracer.error.bind(this.tracer));this.error$.subscribe(e("error"))}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}async updateLive(){var e;this.isUpdatingLive=!0,this.manifest=await this.updateManifest(),this.manifest&&((e=this.bufferManagers)==null||e.forEach(t=>t.updateLive(this.manifest))),this.isUpdatingLive=!1}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.getDebugBufferState();if(!e)return;let t={isJumpGapAfterSeekLive:this.isJumpGapAfterSeekLive,isActiveLowLatency:this.isActiveLowLatency$.getValue(),initialCurrentTime:this.element.currentTime};this.isJumpGapAfterSeekLive&&!this.isActiveLowLatency$.getValue()&&this.element.currentTime>e.to&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let r=this.element.currentTime*1e3,i=[],s=this.element.readyState===1?this.tuning.endGapTolerance:0;for(let n of this.bufferManagers)for(let o of n.gaps)n.playingRepresentation$.getValue()===o.representation&&o.from-s<=r&&o.to+s>r&&(this.element.duration*1e3-o.to<this.tuning.endGapTolerance?i.push(1/0):i.push(o.to));if(i.length){let n=Math.max(...i)+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,n===1/0?this.forceEnded$.next():(this.element.currentTime=n/1e3,t={...t,gapEnds:i,jumpTo:n,resultCurrentTime:this.element.currentTime},this.tracer.log("jumpGap",ea(t)))}}};var Cs=class{constructor(e,t){this.fov=e,this.orientation=t}};var Ds=class{constructor(e,t){this.rotating=!1;this.fading=!1;this.lastTickTS=0;this.lastCameraTurnTS=0;this.fadeStartSpeed=null;this.fadeTime=0;this.camera=e,this.options=t,this.rotationSpeed={x:0,y:0,z:0},this.fadeCorrection=1/(this.options.speedFadeTime/1e3)**2}turnCamera(e=0,t=0,r=0){this.pointCameraTo(this.camera.orientation.x+e,this.camera.orientation.y+t,this.camera.orientation.z+r)}pointCameraTo(e=0,t=0,r=0){t=this.limitCameraRotationY(t);let i=e-this.camera.orientation.x,s=t-this.camera.orientation.y,n=r-this.camera.orientation.z;this.camera.orientation.x=e,this.camera.orientation.y=t,this.camera.orientation.z=r,this.lastCameraTurn={x:i,y:s,z:n},this.lastCameraTurnTS=Date.now()}setRotationSpeed(e,t,r){this.rotationSpeed.x=e!=null?e:this.rotationSpeed.x,this.rotationSpeed.y=t!=null?t:this.rotationSpeed.y,this.rotationSpeed.z=r!=null?r:this.rotationSpeed.z}startRotation(){this.rotating=!0}stopRotation(e=!1){e?(this.setRotationSpeed(0,0,0),this.fadeStartSpeed=null):this.startFading(this.rotationSpeed.x,this.rotationSpeed.y,this.rotationSpeed.z),this.rotating=!1}onCameraRelease(){if(this.lastCameraTurn&&this.lastCameraTurnTS){let e=Date.now()-this.lastCameraTurnTS;if(e<this.options.speedFadeThreshold){let t=(1-e/this.options.speedFadeThreshold)*this.options.rotationSpeedCorrection;this.startFading(this.lastCameraTurn.x*t,this.lastCameraTurn.y*t,this.lastCameraTurn.z*t)}}}startFading(e,t,r){this.setRotationSpeed(e,t,r),this.fadeStartSpeed={...this.rotationSpeed},this.fading=!0}stopFading(){this.fadeStartSpeed=null,this.fading=!0,this.fadeTime=0}limitCameraRotationY(e){return Math.max(-this.options.maxYawAngle,Math.min(e,this.options.maxYawAngle))}tick(e){if(!this.lastTickTS){this.lastTickTS=e,this.lastCameraTurnTS=Date.now();return}let t=e-this.lastTickTS,r=t/1e3;if(this.rotating)this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*r,this.rotationSpeed.y*this.options.rotationSpeedCorrection*r,this.rotationSpeed.z*this.options.rotationSpeedCorrection*r);else if(this.fading&&this.fadeStartSpeed){let i=-this.fadeCorrection*(this.fadeTime/1e3)**2+1;this.setRotationSpeed(this.fadeStartSpeed.x*i,this.fadeStartSpeed.y*i,this.fadeStartSpeed.z*i),i>0?this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*r,this.rotationSpeed.y*this.options.rotationSpeedCorrection*r,this.rotationSpeed.z*this.options.rotationSpeedCorrection*r):(this.stopRotation(!0),this.stopFading()),this.fadeTime=Math.min(this.fadeTime+t,this.options.speedFadeTime)}this.lastTickTS=e}};var Ng=`attribute vec2 a_vertex;
|
|
58
|
+
`}),h&&Eb(i,u,h,o)};var X=a=>new URL(a).hostname;import{assertNever as $b,assertNonNullable as Lb,combine as Vw,debounce as _w,ErrorCategory as Mb,filter as Cb,filterChanged as Nw,isNonNullable as Ru,map as ks,merge as Db,observableFrom as Fw,once as qw,Subscription as Uw,ValueSubject as $u,videoQualityToHeight as Hw,videoSizeToQuality as jw}from"@vkontakte/videoplayer-shared";var Pb=a=>{if(a instanceof DOMException&&["Failed to load because no supported source was found.","The element has no supported sources."].includes(a.message))throw a;return!(a instanceof DOMException&&(a.code===20||a.name==="AbortError"))},be=async a=>{let e=a.muted;try{await a.play()}catch(t){if(!Pb(t))return!1;if(e)return console.warn(t),!1;a.muted=!0;try{await a.play()}catch(r){return Pb(r)&&(a.muted=!1,console.warn(r)),!1}}return!0};import{isNonNullable as Ps,isNullable as yw,assertNonNullable as Li}from"@vkontakte/videoplayer-shared";import{isNonNullable as Ab,assertNonNullable as xs,now as Sw}from"@vkontakte/videoplayer-shared";function Z(){return Sw()}function Pu(a){return Z()-a}function Au(a){let e=a.split("/"),t=e.slice(0,e.length-1).join("/"),r=/^([a-z]+:)?\/\//i,i=n=>r.test(n);return{resolve:(n,o,u=!1)=>{i(n)||(n.startsWith("/")||(n="/"+n),n=t+n);let l=n.indexOf("?")>-1?"&":"?";return u&&(n+=l+"lowLat=1",l="&"),o&&(n+=l+"_rnd="+Math.floor(999999999*Math.random())),n}}}function wb(a,e,t){let r=(...i)=>{t.apply(null,i),a.removeEventListener(e,r)};a.addEventListener(e,r)}function $r(a,e,t,r){let i=window.XMLHttpRequest,s,n,o,u=!1,l=0,c,d,p=!1,h="arraybuffer",f=7e3,b=2e3,g=()=>{if(u)return;xs(c);let w=Pu(c),L;if(w<b){L=b-w,setTimeout(g,L);return}b*=2,b>f&&(b=f),n&&n.abort(),n=new i,R()},y=w=>(s=w,O),I=w=>(d=w,O),S=()=>(h="json",O),v=()=>{if(!u){if(--l>=0){g(),r&&r();return}u=!0,d&&d(),t&&t()}},T=w=>(p=w,O),R=()=>{c=Z(),n=new i,n.open("get",a);let w=0,L,q=0,k=()=>(xs(c),Math.max(c,Math.max(L||0,q||0)));if(s&&n.addEventListener("progress",x=>{let V=Z();s.updateChunk&&x.loaded>w&&(s.updateChunk(k(),x.loaded-w),w=x.loaded,L=V)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>v())),n.addEventListener("load",()=>{if(u)return;xs(n);let x=n.status;if(x>=200&&x<300){if(n.response.byteLength&&s){let V=n.response.byteLength-w;V&&s.updateChunk&&s.updateChunk(k(),V)}n.responseType==="json"&&!Object.values(n.response).length?v():(d&&d(),e(n.response))}else v()}),n.addEventListener("error",()=>{v()}),p){let x=()=>{xs(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(q=Z(),n.removeEventListener("readystatechange",x))};n.addEventListener("readystatechange",x)}return n.responseType=h,n.send(),O},O={withBitrateReporting:y,withParallel:T,withJSONResponse:S,withRetryCount:w=>(l=w,O),withRetryInterval:(w,L)=>(Ab(w)&&(b=w),Ab(L)&&(f=L),O),withTimeout:w=>(o=w,O),withFinally:I,send:R,abort:()=>{n&&(n.abort(),n=void 0),u=!0,d&&d()}};return O}var Ri=class{constructor(e){this.intervals=[];this.currentRate=0;this.logger=e}_updateRate(e){let t=.2;this.currentRate&&(e<this.currentRate*.1?t=.8:e<this.currentRate*.5?t=.5:e<this.currentRate*.7&&(t=.3)),e=Math.max(1,Math.min(e,100*1024*1024)),this.currentRate=this.currentRate?this.currentRate*(1-t)+e*t:e}_createInterval(e,t,r){return{start:e,end:t,bytes:r}}_doMergeIntervals(e,t){e.start=Math.min(t.start,e.start),e.end=Math.max(t.end,e.end),e.bytes+=t.bytes}_mergeIntervals(e,t){return e.start<=t.end&&t.start<=e.end?(this._doMergeIntervals(e,t),!0):!1}_flushIntervals(){if(!this.intervals.length)return!1;let e=this.intervals[0].start,t=this.intervals[this.intervals.length-1].end-500;if(t-e>2e3){let r=0,i=0;for(;this.intervals.length>0;){let s=this.intervals[0];if(s.end<=t)r+=s.end-s.start,i+=s.bytes,this.intervals.splice(0,1);else{if(s.start>=t)break;{let n=t-s.start,o=s.end-s.start;r+=n;let u=s.bytes*n/o;i+=u,s.start=t,s.bytes-=u}}}if(i>0&&r>0){let s=i*8/(r/1e3);return this._updateRate(s),this.logger(`rate updated, new=${Math.round(s/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(i)}/${Math.round(r)} interval=${Math.round(t-e)}`),!0}}return!1}_joinIntervals(){let e;do{e=!1;for(let t=0;t<this.intervals.length-1;++t)this._mergeIntervals(this.intervals[t],this.intervals[t+1])&&(this.intervals.splice(t+1,1),e=!0)}while(e)}addInterval(e,t,r){return this.intervals.push(this._createInterval(e,t,r)),this._joinIntervals(),this.intervals.length>100&&(this.logger(`too many intervals (${this.intervals.length}); will merge`,{type:"warn"}),this._doMergeIntervals(this.intervals[1],this.intervals[0]),this.intervals.splice(0,1)),this._flushIntervals()}getBitRate(){return this.currentRate}};var $i=class{constructor(e,t,r,i,s){this.pendingQueue=[];this.activeRequests={};this.completeRequests={};this.averageSegmentDuration=2e3;this.lastPrefetchStart=0;this.throttleTimeout=null;this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=r,this.MAX_PARALLEL_REQUESTS=i,this.logger=s}limitCompleteCount(){let e;for(;(e=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){let t=e[Math.floor(Math.random()*e.length)];this.logger(`Dropping completed request for url ${t}`,{type:"warn"}),delete this.completeRequests[t]}}_sendRequest(e,t){let r=Z(),i=u=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=u,e._errorCB?e._errorCB(u):(this.limitCompleteCount(),this.completeRequests[t]=e)},s=u=>{e._complete=1,e._responseData=u,e._downloadTime=Z()-r,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(u,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},n=()=>{e._finallyCB&&e._finallyCB()},o=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=$r(t,s,()=>i("error"),o),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally(n),this.activeRequests[t]=e,e._request.send(),this.lastPrefetchStart=Z()}_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=Z();if(Object.keys(this.activeRequests).length>=e)return!1;let r=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),r>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),r),!1):!0}_sendPending(){for(;this._canSendPending();){let e=this.pendingQueue.pop();if(e){if(this.activeRequests[e]||this.completeRequests[e])continue;this.logger(`Submitting pending request url=${e}`),this._sendRequest({},e)}else return}}_removeFromActive(e){delete this.completeRequests[e],delete this.activeRequests[e]}abortAll(){Object.values(this.activeRequests).forEach(e=>{e&&e._request&&e._request.abort()}),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,r,i){let s={};return s.send=()=>{let n=this.activeRequests[e]||this.completeRequests[e];if(n)n._cb=t,n._errorCB=r,n._retryCB=i,n._finallyCB=s._finallyCB,n._error||n._complete?(this._removeFromActive(e),setTimeout(()=>{n._complete?(this.logger(`Requested url already prefetched, url=${e}`),t(n._responseData,n._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${e}`),r(n._errorMsg)),s._finallyCB&&s._finallyCB()},0)):this.logger(`Attached to active request, url=${e}`);else{let o=this.pendingQueue.indexOf(e);o!==-1&&this.pendingQueue.splice(o,1),this.logger(`Request not prefetched, starting new request, url=${e}${o===-1?"":"; removed pending"}`),this._sendRequest(s,e)}},s._cb=t,s._errorCB=r,s._retryCB=i,s.abort=function(){s.request&&s.request.abort()},s.withFinally=n=>(s._finallyCB=n,s),s}prefetch(e){this.activeRequests[e]||this.completeRequests[e]?this.logger(`Request already active for url=${e}`):(this.logger(`Added to pending queue; url=${e}`),this.pendingQueue.unshift(e),this._sendPending())}optimizeForSegDuration(e){this.averageSegmentDuration=e}};var As=1e4,wu=3;var Tw=6e4,Iw=10,Ew=1,xw=500,Mi=class{constructor(e){this.paused=!1;this.autoQuality=!0;this.maxAutoQuality=void 0;this.buffering=!0;this.destroyed=!1;this.videoPlayStarted=!1;this.lowLatency=!1;this.bitrate=0;this.manifest=[];this.sourceBuffer=0;this.bufferStates=[];this.sourceJitter=-1;this.params=e,this.chunkRateEstimator=new Ri(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=Au(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setMaxAutoQuality(e){this.maxAutoQuality=e}switchByName(e){let t;for(let r=0;r<this.manifest.length;++r)if(t=this.manifest[r],t.name===e){this._switchToQuality(t);return}}catchUp(){this.rep&&this.rep.stop(),this.currentManifestEntry&&(this.paused=!1,this._initPlayerWith(this.currentManifestEntry),this._notifyBuffering(!0))}stop(){this.params.videoElement.pause(),this.rep&&(this.rep.stop(),this.rep=null)}pause(){this.paused=!0,this.params.videoElement.pause(),this.videoPlayStarted=!1,this._notifyBuffering(!1)}play(){this.paused=!1;let e=this.lowLatency&&this._getBufferSizeSec()>this.sourceJitter+5;this.rep&&!e?(this.bufferStates=[],this.videoPlayStarted=!1,this.shouldPlay()?this._playVideoElement():this._notifyBuffering(!0)):this.catchUp()}startPlay(e,t){this.autoQuality=t,this._initPlayerWith(e)}destroy(){this.destroyed=!0,this.rep&&(this.rep.stop(),this.rep=null),this.manifestRequest&&this.manifestRequest.abort(),this.manifestRefetchTimer&&(clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=void 0)}reinit(e){this.manifestUrl=e,this.urlResolver=Au(e),this.catchUp()}_handleNetworkError(){this.params.logger("Fatal network error"),this.params.playerCallback({name:"error",type:"network"})}_retryCallback(){this.params.playerCallback({name:"retry"})}_getBufferSizeSec(){let e=this.params.videoElement,t=0,r=e.buffered.length;return r!==0&&(t=e.buffered.end(r-1)-Math.max(e.currentTime,e.buffered.start(0))),t}_notifyBuffering(e){this.destroyed||(this.params.logger(`buffering: ${e}`),this.params.playerCallback({name:"buffering",isBuffering:e}),this.buffering=e)}_initVideo(){let{videoElement:e,logger:t}=this.params;e.addEventListener("error",()=>{var i;!!e.error&&!this.destroyed&&(t(`Video element error: ${(i=e.error)==null?void 0:i.code}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{let r=this._getBufferSizeSec();!this.paused&&r<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(r+.1)*1e3)):this.buffering&&this.videoPlayStarted&&this._notifyBuffering(!1)}),e.addEventListener("playing",()=>{t("playing")}),e.addEventListener("stalled",()=>this._fixupStall()),e.addEventListener("waiting",()=>this._fixupStall())}_fixupStall(){let{logger:e,videoElement:t}=this.params,r=t.buffered.length,i;r!==0&&(i=t.buffered.start(r-1),t.currentTime<i&&(e("Fixup stall"),t.currentTime=i))}_selectQuality(e){let{videoElement:t}=this.params,r,i,s,n=t&&1.62*(window.devicePixelRatio||1)*t.offsetHeight||520;for(let o=0;o<this.manifest.length;++o)s=this.manifest[o],!(this.maxAutoQuality&&s.video.height>this.maxAutoQuality)&&(s.bitrate<e&&n>Math.min(s.video.height,s.video.width)?(!i||s.bitrate>i.bitrate)&&(i=s):(!r||r.bitrate>s.bitrate)&&(r=s));return i||r}shouldPlay(){if(this.paused)return!1;let t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||Ps(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){let{logger:r,videoElement:i,playerCallback:s}=this.params;this.mediaSource=new window.MediaSource,r("setting video src"),i.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.videoPlayStarted=!1,i.addEventListener("canplay",()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});let n=()=>{wb(i,"progress",()=>{i.buffered.length?(i.currentTime=i.buffered.start(0),s({name:"playing"})):n()})};n()}_initPlayerWith(e){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new $i(wu,As,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){let{logger:t,videoElement:r,playerCallback:i}=this.params,s=!1,n=null,o=null,u=null,l=null,c=!1,d=()=>{let v=s&&(!c||c===this.rep);return v||t("Not running!"),v},p=(v,T,R)=>{u&&u.abort(),u=$r(this.urlResolver.resolve(v,!1),T,R,()=>this._retryCallback()).withTimeout(As).withBitrateReporting(this.bitrateSwitcher).withRetryCount(wu).withFinally(()=>{u=null}).send()},h=(v,T,R)=>{Li(this.filesFetcher),o==null||o.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(v,!1),T,R,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},f=v=>{let T=r.playbackRate;r.playbackRate!==v&&(t(`Playback rate switch: ${T}=>${v}`),r.playbackRate=v)},b=v=>{this.lowLatency=v,t(`lowLatency changed to ${v}`),g()},g=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)f(1);else{let v=this._getBufferSizeSec();if(this.bufferStates.length<5){f(1);return}let R=Z()-1e4,U=0;for(let B=0;B<this.bufferStates.length;B++){let N=this.bufferStates[B];v=Math.min(v,N.buf),N.ts<R&&U++}this.bufferStates.splice(0,U),t(`update playback rate; minBuffer=${v} drop=${U} jitter=${this.sourceJitter}`);let $=v-Ew;this.sourceJitter>=0?$-=this.sourceJitter/2:this.sourceJitter-=1,$>3?f(1.15):$>1?f(1.1):$>.3?f(1.05):f(1)}},y=v=>{let T,R=()=>T&&T.start?T.start.length:0,U=x=>T.start[x]/1e3,$=x=>T.dur[x]/1e3,B=x=>T.fragIndex+x,N=(x,V)=>({chunkIdx:B(x),startTS:U(x),dur:$(x),discontinuity:V}),O=()=>{let x=0;if(T&&T.dur){let V=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,H=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,W=V;this.sourceJitter>1&&(W+=this.sourceJitter-1);let K=T.dur.length-1;for(;K>=0&&(W-=T.dur[K],!(W<=0));--K);x=Math.min(K,T.dur.length-1-H),x=Math.max(x,0)}return N(x,!0)},w=x=>{let V=R();if(!(V<=0)){if(Ps(x)){for(let H=0;H<V;H++)if(U(H)>x)return N(H)}return O()}},L=x=>{let V=R(),H=x?x.chunkIdx+1:0,W=H-T.fragIndex;if(!(V<=0)){if(!x||W<0||W-V>Iw)return t(`Resync: offset=${W} bChunks=${V} chunk=`+JSON.stringify(x)),O();if(!(W>=V))return N(H-T.fragIndex,!1)}},q=(x,V,H)=>{l&&l.abort(),l=$r(this.urlResolver.resolve(x,!0,this.lowLatency),V,H,()=>this._retryCallback()).withTimeout(As).withRetryCount(wu).withFinally(()=>{l=null}).withJSONResponse().send()};return{seek:(x,V)=>{q(v,H=>{if(!d())return;T=H;let W=!!T.lowLatency;W!==this.lowLatency&&b(W);let K=0;for(let ne=0;ne<T.dur.length;++ne)K+=T.dur[ne];K>0&&(Li(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(K/T.dur.length)),i({name:"index",zeroTime:T.zeroTime,shiftDuration:T.shiftDuration}),this.sourceJitter=T.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,T.jitter/1e3)):1,x(w(V))},()=>this._handleNetworkError())},nextChunk:L}},I=()=>{s=!1,o&&o.abort(),u&&u.abort(),l&&l.abort(),Li(this.filesFetcher),this.filesFetcher.abortAll()};return c={start:v=>{let{videoElement:T,logger:R}=this.params,U=y(e.jidxUrl),$,B,N,O,w=0,L,q,k,x=()=>{L&&(clearTimeout(L),L=void 0);let A=Math.max(xw,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),oe=w+A,ve=Z(),Pe=Math.min(1e4,oe-ve);w=ve;let ht=()=>{l||d()&&U.seek(()=>{d()&&(w=Z(),V(),x())})};Pe>0?L=window.setTimeout(()=>{this.paused?x():ht()},Pe):ht()},V=()=>{let A;for(;A=U.nextChunk(O);)O=A,Lt(A);let oe=U.nextChunk(N);if(oe){if(N&&oe.discontinuity){R("Detected discontinuity; restarting playback"),this.paused?x():(I(),this._initPlayerWith(e));return}ne(oe)}else x()},H=(A,oe)=>{if(!d()||!this.sourceBuffer)return;let ve,Pe,ht,ir=ft=>{window.setTimeout(()=>{d()&&H(A,oe)},ft)};if(this.sourceBuffer.updating)R("Source buffer is updating; delaying appendBuffer"),ir(100);else{let ft=Z(),Mt=T.currentTime;!this.paused&&T.buffered.length>1&&q===Mt&&ft-k>500&&(R("Stall suspected; trying to fix"),this._fixupStall()),q!==Mt&&(q=Mt,k=ft);let ar=this._getBufferSizeSec();if(ar>30)R(`Buffered ${ar} seconds; delaying appendBuffer`),ir(2e3);else try{this.sourceBuffer.appendBuffer(A),this.videoPlayStarted?(this.bufferStates.push({ts:ft,buf:ar}),g(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),oe&&oe()}catch(Wr){if(Wr.name==="QuotaExceededError")R("QuotaExceededError; delaying appendBuffer"),ht=this.sourceBuffer.buffered.length,ht!==0&&(ve=this.sourceBuffer.buffered.start(0),Pe=Mt,Pe-ve>4&&this.sourceBuffer.remove(ve,Pe-3)),ir(1e3);else throw Wr}}},W=()=>{B&&$&&(R([`Appending chunk, sz=${B.byteLength}:`,JSON.stringify(N)]),H(B,function(){B=null,V()}))},K=A=>e.fragUrlTemplate.replace("%%id%%",A.chunkIdx),ne=A=>{d()&&h(K(A),(oe,ve)=>{if(d()){if(ve/=1e3,B=oe,N=A,n=A.startTS,ve){let Pe=Math.min(10,A.dur/ve);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*Pe:Pe}W()}},()=>this._handleNetworkError())},Lt=A=>{d()&&(Li(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(K(A),!1)))},pt=A=>{d()&&(e.cachedHeader=A,H(A,()=>{$=!0,W()}))};s=!0,U.seek(A=>{if(d()){if(w=Z(),!A){x();return}O=A,!yw(v)||A.startTS>v?ne(A):(N=A,V())}},v),e.cachedHeader?pt(e.cachedHeader):p(e.headerUrl,pt,()=>this._handleNetworkError())},stop:I,getTimestampSec:()=>n},c}_switchToQuality(e){let{logger:t,playerCallback:r}=this.params,i;e.bitrate!==this.bitrate&&(this.rep&&(i=this.rep.getTimestampSec(),Ps(i)&&(i+=.1),this.rep.stop()),this.currentManifestEntry=e,this.rep=this._representation(e),t(`switch to quality: codecs=${e.codecs}; headerUrl=${e.headerUrl}; bitrate=${e.bitrate}`),this.bitrate=e.bitrate,Li(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(i),r({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return Ps(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,r=d=>{if(!this.autoQuality)return;let p,h,f;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&d<this.bitrate&&(h=this._getBufferSizeSec(),f=d/this.bitrate,h>10&&f>.8||h>15&&f>.5||h>20&&f>.3)){e(`Not switching: buffer=${Math.floor(h)}; bitrate=${this.bitrate}; newRate=${Math.floor(d)}`);return}p=this._selectQuality(d),p?this._switchToQuality(p):e(`Could not find quality by bitrate ${d}`)},s={updateChunk:(p,h)=>{let f=Z();if(this.chunkRateEstimator.addInterval(p,f,h)){let g=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:h,duration:f-p,speed:g}),!0}},get:()=>{let p=this.chunkRateEstimator.getBitRate();return p?p*.85:0}},n=-1/0,o,u=!0,l=()=>{let d=s.get();if(d&&o&&this.autoQuality){if(u&&d>o&&Pu(n)<3e4)return;r(d)}u=this.autoQuality};return{updateChunk:(d,p)=>{let h=s.updateChunk(d,p);return h&&l(),h},notifySwitch:d=>{let p=Z();d<o&&(n=p),o=d}}}_fetchManifest(e,t,r){this.manifestRequest=$r(this.urlResolver.resolve(e,!0),t,r,()=>this._retryCallback()).withJSONResponse().withTimeout(As).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;be(e).then(t=>{t||(this.params.liveOffset.pause(),this.params.videoState.setState("paused"))})}_handleManifestUpdate(e){let{logger:t,playerCallback:r,videoElement:i}=this.params,s=n=>{let o=[];return n!=null&&n.length?(n.forEach((u,l)=>{u.video&&i.canPlayType(u.codecs).replace(/no/,"")&&window.MediaSource.isTypeSupported(u.codecs)&&(u.index=l,o.push(u))}),o.sort(function(u,l){return u.video&&l.video?l.video.height-u.video.height:l.bitrate-u.bitrate}),o):(r({name:"error",type:"empty_manifest"}),[])};this.manifest=s(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),r({name:"manifest",manifest:this.manifest})}_refetchManifest(e){this.destroyed||(this.manifestRefetchTimer&&clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=window.setTimeout(()=>{this._fetchManifest(e,t=>{this.destroyed||(this._handleManifestUpdate(t),this._refetchManifest(e))},()=>this._refetchManifest(e))},Tw))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};import{debounce as Pw,filter as kb,fromEvent as Aw,interval as ww,isHigher as kw,isInvariantQuality as Rw,isLower as $w,merge as Lw,Subject as Rb,Subscription as Mw}from"@vkontakte/videoplayer-shared";var ku=class{constructor(){this.onDroopedVideoFramesLimit$=new Rb;this.subscription=new Mw;this.playing=!1;this.tracks=[];this.forceChecker$=new Rb;this.isForceCheckCounter=0;this.prevTotalVideoFrames=0;this.prevDroppedVideoFrames=0;this.limitCounts={};this.handleChangeVideoQuality=()=>{let e=this.tracks.find(({size:t})=>(t==null?void 0:t.height)===this.video.videoHeight&&(t==null?void 0:t.width)===this.video.videoWidth);e&&!Rw(e.quality)&&this.onChangeQuality(e.quality)};this.checkDroppedFrames=()=>{var n;let{totalVideoFrames:e,droppedVideoFrames:t}=this.video.getVideoPlaybackQuality(),r=e-this.prevTotalVideoFrames,i=t-this.prevDroppedVideoFrames,s=1-(r-i)/r;!isNaN(s)&&s>0&&this.log({message:`[dropped]. current dropped percent: ${s}, limit: ${this.droppedFramesChecker.percentLimit}`}),!isNaN(s)&&s>=this.droppedFramesChecker.percentLimit&&kw(this.currentQuality,this.droppedFramesChecker.minQualityBanLimit)&&(this.limitCounts[this.currentQuality]=((n=this.limitCounts[this.currentQuality])!=null?n:0)+1,this.maxQualityLimit=this.getMaxQualityLimit(this.currentQuality),this.currentTimer&&window.clearTimeout(this.currentTimer),this.currentTimer=window.setTimeout(()=>this.maxQualityLimit=this.getMaxQualityLimit(),this.droppedFramesChecker.qualityUpWaitingTime),this.onDroopedVideoFramesLimitTrigger()),this.savePrevFrameCounts(e,t)}}connect(e){this.log=e.logger.createComponentLog("DroppedFramesManager"),this.video=e.video,this.isAuto=e.isAuto,this.tracks=e.tracks,this.droppedFramesChecker=e.droppedFramesChecker,this.subscription.add(e.playing$.subscribe(()=>this.playing=!0)),this.subscription.add(e.pause$.subscribe(()=>this.playing=!1)),this.isEnabled&&this.subscribe()}destroy(){this.currentTimer&&window.clearTimeout(this.currentTimer),this.subscription.unsubscribe()}get droppedVideoMaxQualityLimit(){return this.maxQualityLimit}subscribe(){this.subscription.add(Aw(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=ww(this.droppedFramesChecker.checkTime).pipe(kb(()=>this.playing),kb(()=>{let i=!!this.isForceCheckCounter;return i&&(this.isForceCheckCounter-=1),!i})),t=this.forceChecker$.pipe(Pw(this.droppedFramesChecker.checkTime)),r=Lw(e,t);this.subscription.add(r.subscribe(this.checkDroppedFrames))}onChangeQuality(e){this.currentQuality=e;let{totalVideoFrames:t,droppedVideoFrames:r}=this.video.getVideoPlaybackQuality();this.savePrevFrameCounts(t,r),this.isForceCheckCounter=this.droppedFramesChecker.tickCountAfterQualityChange,this.forceChecker$.next()}onDroopedVideoFramesLimitTrigger(){this.isAuto.getState()&&(this.log({message:`[onDroopedVideoFramesLimit]. maxQualityLimit: ${this.maxQualityLimit}`}),this.onDroopedVideoFramesLimit$.next())}getMaxQualityLimit(e){var r,i;let t=(i=(r=Object.entries(this.limitCounts).filter(([,s])=>s>=this.droppedFramesChecker.countLimit).sort(([s],[n])=>$w(s,n)?-1:1))==null?void 0:r[0])==null?void 0:i[0];return e!=null?e:t}get isEnabled(){return this.droppedFramesChecker.enabled&&this.isDroppedFramesCheckerSupport}get isDroppedFramesCheckerSupport(){return!!this.video&&typeof this.video.getVideoPlaybackQuality=="function"}savePrevFrameCounts(e,t){this.prevTotalVideoFrames=e,this.prevDroppedVideoFrames=t}},ws=ku;import{map as Cw,Observable as Dw}from"@vkontakte/videoplayer-shared";import{fromEvent as Bw}from"@vkontakte/videoplayer-shared";var Ci=()=>{var a;return!!((a=window.documentPictureInPicture)!=null&&a.window)||!!document.pictureInPictureElement};var Ow=(a,e)=>new Dw(t=>{if(!window.IntersectionObserver)return;let r={root:null},i=new IntersectionObserver((n,o)=>{n.forEach(u=>t.next(u.isIntersecting||Ci()))},{...r,...e});i.observe(a);let s=Bw(document,"visibilitychange").pipe(Cw(n=>!document.hidden||Ci())).subscribe(n=>t.next(n));return()=>{i.unobserve(a),s.unsubscribe}}),Me=Ow;var Gw=["paused","playing","ready"],Ww=["paused","playing","ready"],Di=class{constructor(e){this.subscription=new Uw;this.videoState=new M("stopped");this.representations$=new $u([]);this.textTracksManager=new Je;this.droppedFramesManager=new ws;this.maxSeekBackTime$=new $u(1/0);this.zeroTime$=new $u(void 0);this.liveOffset=new it;this._dashCb=e=>{var t,r,i,s;switch(e.name){case"buffering":{let n=e.isBuffering;this.params.output.isBuffering$.next(n);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${e.type}`,category:Mb.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{let n=e.manifest,o=[];for(let u of n){let l=(t=u.name)!=null?t:u.index.toString(10),c=(r=Et(u.name))!=null?r:jw(u.video),d=u.bitrate/1e3,p={...u.video};if(!c)continue;let h={id:l,quality:c,bitrate:d,size:p};o.push({track:h,representation:u})}this.representations$.next(o),this.params.output.availableVideoTracks$.next(o.map(({track:u})=>u)),((i=this.videoState.getTransition())==null?void 0:i.to)==="manifest_ready"&&this.videoState.setState("manifest_ready");break}case"qualitySwitch":{let n=e.quality,o=(s=this.representations$.getValue().find(({representation:u})=>u===n))==null?void 0:s.track;this.params.output.hostname$.next(new URL(n.headerUrl,this.params.source.url).hostname),Ru(o)&&this.params.output.currentVideoTrack$.next(o);break}case"bandwidth":{let{size:n,duration:o}=e;this.params.dependencies.throughputEstimator.addRawSpeed(n,o);break}case"index":{this.maxSeekBackTime$.next(e.shiftDuration||0),this.zeroTime$.next(e.zeroTime);break}}};this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),r=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${r}; seekState: ${JSON.stringify(s)};`}),r==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState("stopped"));return}if(t)return;let n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(Ww.includes(e)&&(n||o)){this.prepare();return}if((i==null?void 0:i.to)!=="paused"&&s.state==="requested"&&Gw.includes(e)){this.seek(s.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(ee(this.params.source.url));return;case"manifest_ready":this.videoState.startTransitionTo("ready"),this.prepare();break;case"ready":if(r==="paused")this.videoState.setState("paused");else if(r==="playing"){this.videoState.startTransitionTo("playing");let u=i==null?void 0:i.from;u&&u==="ready"&&this.dash.catchUp(),this.dash.play()}return;case"playing":r==="paused"&&(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.dash.pause());return;case"paused":if(r==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.dash.play(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let u=this.liveOffset.getTotalOffset();u>=this.maxSeekBackTime$.getValue()&&(u=0,this.liveOffset.resetTo(u)),this.liveOffset.resume(),this.params.output.position$.next(-u/1e3),this.dash.reinit(ee(this.params.source.url,u))}return;default:return $b(e)}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=i=>{e.output.error$.next({id:"DashLiveProvider",category:Mb.WTF,message:"DashLiveProvider internal logic error",thrown:i})};Db(this.videoState.stateChangeStarted$.pipe(ks(i=>({transition:i,type:"start"}))),this.videoState.stateChangeEnded$.pipe(ks(i=>({transition:i,type:"end"})))).subscribe(({transition:i,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(i)}`})}),this.video=de(e.container,e.tuning),this.params.output.element$.next(this.video),this.dash=this.createLiveDashPlayer(),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(X(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);let r=fe(this.video);this.subscription.add(this.representations$.pipe(ks(i=>i.map(({track:s})=>s)),Cb(i=>!!i.length),qw()).subscribe(i=>this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:r.playing$,pause$:r.pause$,tracks:i}))),this.subscription.add(r.canplay$.subscribe(()=>{var i;((i=this.videoState.getTransition())==null?void 0:i.to)==="ready"&&this.videoState.setState("ready")},t)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused")},t)).add(r.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.videoState.setState("playing")},t)).add(r.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(Nw(),ks(i=>-i/1e3)).subscribe(this.params.output.duration$)).add(Vw({zeroTime:this.zeroTime$.pipe(Cb(Ru)),position:r.timeUpdate$}).subscribe(({zeroTime:i,position:s})=>this.params.output.liveTime$.next(i+s*1e3),t)).add(ze(this.video,this.params.desiredState.isLooped,t)).add(he(this.video,this.params.desiredState.volume,r.volumeState$,t)).add(r.volumeState$.subscribe(this.params.output.volume$,t)).add($e(this.video,this.params.desiredState.playbackRate,r.playbackRateState$,t)).add(r.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(r.loadedMetadata$.subscribe(this.params.output.loadedMetadataEvent$)).add(r.playing$.subscribe(this.params.output.firstFrameEvent$)).add(r.canplay$.subscribe(this.params.output.canplay$)).add(r.inPiP$.subscribe(this.params.output.inPiP$)).add(r.inFullscreen$.subscribe(this.params.output.inFullscreen$)).add(Me(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:i}})=>{let s=i&&Hw(i);this.dash.setMaxAutoQuality(s),this.params.output.autoVideoTrackLimits$.next({max:i})})).add(this.videoState.stateChangeEnded$.subscribe(i=>{var s;switch(i.to){case"stopped":this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState("stopped");break;case"manifest_ready":case"ready":((s=this.params.desiredState.playbackState.getTransition())==null?void 0:s.to)==="ready"&&this.params.desiredState.playbackState.setState("ready");break;case"paused":this.params.desiredState.playbackState.setState("paused");break;case"playing":this.params.desiredState.playbackState.setState("playing");break;default:return $b(i.to)}},t)).add(Db(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,Fw(["init"])).pipe(_w(0)).subscribe(this.syncPlayback,t))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.droppedFramesManager.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),pe(this.video)}createLiveDashPlayer(){let e=new Mi({videoElement:this.video,videoState:this.videoState,liveOffset:this.liveOffset,config:{maxParallelRequests:this.params.config.maxParallelRequests,minBuffer:this.params.tuning.live.minBuffer,minBufferSegments:this.params.tuning.live.minBufferSegments,lowLatencyMinBuffer:this.params.tuning.live.lowLatencyMinBuffer,lowLatencyMinBufferSegments:this.params.tuning.live.lowLatencyMinBufferSegments,isLiveCatchUpMode:this.params.tuning.live.isLiveCatchUpMode,manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},playerCallback:this._dashCb,logger:t=>{this.params.dependencies.logger.log({message:String(t),component:"LiveDashPlayer"})}});return e.pause(),e}prepare(){var l,c,d,p,h,f;let e=this.representations$.getValue(),t=(c=(l=this.params.desiredState.videoTrack.getTransition())==null?void 0:l.to)!=null?c:this.params.desiredState.videoTrack.getState(),r=(p=(d=this.params.desiredState.autoVideoTrackSwitching.getTransition())==null?void 0:d.to)!=null?p:this.params.desiredState.autoVideoTrackSwitching.getState(),i=!r&&Ru(t)?t:xt(e.map(({track:b})=>b),{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},throughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),s=i==null?void 0:i.id,n=this.params.desiredState.videoTrack.getTransition(),o=(h=this.params.desiredState.videoTrack.getState())==null?void 0:h.id,u=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(i&&(n||s!==o)&&this.setVideoTrack(i),u&&this.setAutoQuality(r),n||u||s!==o){let b=(f=e.find(({track:g})=>g.id===s))==null?void 0:f.representation;Lb(b,"Representations missing"),this.dash.startPlay(b,r)}}setVideoTrack(e){var r;let t=(r=this.representations$.getValue().find(({track:i})=>i.id===e.id))==null?void 0:r.representation;Lb(t,`No such representation ${e.id}`),this.dash.switchByName(t.name),this.params.desiredState.videoTrack.setState(e)}setAutoQuality(e){this.dash.setAutoQualityEnabled(e),this.params.desiredState.autoVideoTrackSwitching.setState(e)}seek(e){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),r=this.videoState.getState(),i=t==="paused"&&r==="paused",s=-e,n=s<=this.maxSeekBackTime$.getValue()?s:0;this.params.output.position$.next(e/1e3),this.dash.reinit(ee(this.params.source.url,n)),i&&this.dash.pause(),this.liveOffset.resetTo(n,i)}};var Bb=Di;var st=(a,e)=>{let t=0;for(let r=0;r<a.length;r++){let i=a.start(r)*1e3,s=a.end(r)*1e3;i<=e&&e<=s&&(t=s)}return Math.max(t-e,0)};import{assertNever as SR,assertNonNullable as vR,debounce as yR,ErrorCategory as sl,filter as nS,filterChanged as nl,fromEvent as TR,isNonNullable as IR,map as oS,merge as Zs,observableFrom as ER,observeElementSize as xR,once as uS,Subscription as PR,ValueSubject as AR}from"@vkontakte/videoplayer-shared";var Rs=class{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,r){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:r})}removeEventListener(e,t){if(!(e in this.listeners))return;let r=this.listeners[e];for(let i=0,s=r.length;i<s;i++)if(r[i].callback===t){r.splice(i,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;let r=this.listeners[e.type].slice();for(let i=0,s=r.length;i<s;i++){let n=r[i];try{n.callback.call(this,e)}catch(o){Promise.resolve().then(()=>{throw o})}n.options&&n.options.once&&this.removeEventListener(e.type,n.callback)}return!e.defaultPrevented}},Lr=class extends Rs{constructor(){super(),this.listeners||Rs.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)}},Bi=class{constructor(){Object.defineProperty(this,"signal",{value:new Lr,writable:!0,configurable:!0})}abort(e){let t;try{t=new Event("abort")}catch(i){typeof document!="undefined"?document.createEvent?(t=document.createEvent("Event"),t.initEvent("abort",!1,!1)):(t=document.createEventObject(),t.type="abort"):t={type:"abort",bubbles:!1,cancelable:!1}}let r=e;if(r===void 0)if(typeof document=="undefined")r=new Error("This operation was aborted"),r.name="AbortError";else try{r=new DOMException("signal is aborted without reason")}catch(i){r=new Error("This operation was aborted"),r.name="AbortError"}this.signal.reason=r,this.signal.dispatchEvent(t)}toString(){return"[object AbortController]"}};typeof Symbol!="undefined"&&Symbol.toStringTag&&(Bi.prototype[Symbol.toStringTag]="AbortController",Lr.prototype[Symbol.toStringTag]="AbortSignal");function $s(a){return a.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof a.Request=="function"&&!a.Request.prototype.hasOwnProperty("signal")||!a.AbortController}function Lu(a){typeof a=="function"&&(a={fetch:a});let{fetch:e,Request:t=e.Request,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:i=!1}=a;if(!$s({fetch:e,Request:t,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:i}))return{fetch:e,Request:s};let s=t;(s&&!s.prototype.hasOwnProperty("signal")||i)&&(s=function(l,c){let d;c&&c.signal&&(d=c.signal,delete c.signal);let p=new t(l,c);return d&&Object.defineProperty(p,"signal",{writable:!1,enumerable:!1,configurable:!0,value:d}),p},s.prototype=t.prototype);let n=e;return{fetch:(u,l)=>{let c=s&&s.prototype.isPrototypeOf(u)?u.signal:l?l.signal:void 0;if(c){let d;try{d=new DOMException("Aborted","AbortError")}catch(h){d=new Error("Aborted"),d.name="AbortError"}if(c.aborted)return Promise.reject(d);let p=new Promise((h,f)=>{c.addEventListener("abort",()=>f(d),{once:!0})});return l&&l.signal&&delete l.signal,Promise.race([p,n(u,l)])}return n(u,l)},Request:s}}var Oi=$s({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),Ob=Oi?Lu({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,nt=Oi?Ob.fetch:window.fetch,kB=Oi?Ob.Request:window.Request,ot=Oi?Bi:window.AbortController,RB=Oi?Lr:window.AbortSignal;var zb=Ye(Ai(),1);var ut=()=>window.ManagedMediaSource||window.MediaSource,Ls=()=>{var a,e;return!!(window.ManagedMediaSource&&((e=(a=window.ManagedSourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},Vb=()=>{var a,e;return!!(window.MediaSource&&window.MediaStreamTrack&&((e=(a=window.SourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},_b=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;import{assertNever as Fs,clientChecker as Ns}from"@vkontakte/videoplayer-shared";var Ce=document.createElement("video"),zw='video/mp4; codecs="avc1.42000a,mp4a.40.2"',Kw='video/mp4; codecs="hev1.1.6.L93.B0"',Kb='video/webm; codecs="vp09.00.10.08"',Jb='video/webm; codecs="av01.0.00M.08"',Jw='audio/mp4; codecs="mp4a.40.2"',Xw='audio/webm; codecs="opus"',Nb,Fb,Yt={mms:Ls(),mse:Vb(),hls:!!((Nb=Ce.canPlayType)!=null&&Nb.call(Ce,"application/x-mpegurl")||(Fb=Ce.canPlayType)!=null&&Fb.call(Ce,"vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},qb,Ub,ge={mp4:!!((qb=Ce.canPlayType)!=null&&qb.call(Ce,"video/mp4")),webm:!!((Ub=Ce.canPlayType)!=null&&Ub.call(Ce,"video/webm")),cmaf:!0},Cs,Hb,Ds,jb,Bs,Gb,Os,Wb,Vs,Yb,_s,Qb,Se={h264:!!((Hb=(Cs=ut())==null?void 0:Cs.isTypeSupported)!=null&&Hb.call(Cs,zw)),h265:!!((jb=(Ds=ut())==null?void 0:Ds.isTypeSupported)!=null&&jb.call(Ds,Kw)),vp9:!!((Gb=(Bs=ut())==null?void 0:Bs.isTypeSupported)!=null&&Gb.call(Bs,Kb)),av1:!!((Wb=(Os=ut())==null?void 0:Os.isTypeSupported)!=null&&Wb.call(Os,Jb)),aac:!!((Yb=(Vs=ut())==null?void 0:Vs.isTypeSupported)!=null&&Yb.call(Vs,Jw)),opus:!!((Qb=(_s=ut())==null?void 0:_s.isTypeSupported)!=null&&Qb.call(_s,Xw))},Mr=(Se.h264||Se.h265)&&Se.aac,Qt,Zw=async()=>{if(!window.navigator.mediaCapabilities)return;let a={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=await Promise.all([window.navigator.mediaCapabilities.decodingInfo({...a,video:{...a.video,contentType:Jb}}),window.navigator.mediaCapabilities.decodingInfo({...a,video:{...a.video,contentType:Kb}})]);Qt={DASH_WEBM_AV1:e,DASH_WEBM:t}};try{Zw()}catch(a){console.error(a)}var Cr=Yt.hls&&ge.mp4,Xb=()=>Object.keys(Se).filter(a=>Se[a]),Zb=(a,e=!1,t=!1)=>{let r=Yt.mse||Yt.mms&&t;return a.filter(i=>{switch(i){case"DASH_SEP":return r&&ge.mp4&&Mr;case"DASH_WEBM":return r&&ge.webm&&Se.vp9&&Se.opus;case"DASH_WEBM_AV1":return r&&ge.webm&&Se.av1&&Se.opus;case"DASH_STREAMS":return r&&(ge.mp4&&Mr||ge.webm&&(Se.vp9||Se.av1)&&(Se.opus||Se.aac));case"DASH_LIVE":return Yt.mse&&ge.mp4&&Mr;case"DASH_LIVE_CMAF":return r&&ge.mp4&&Mr&&ge.cmaf;case"DASH_ONDEMAND":return r&&ge.mp4&&Mr;case"HLS":case"HLS_ONDEMAND":return Cr||e&&Yt.mse&&ge.mp4&&Mr;case"HLS_LIVE":case"HLS_LIVE_CMAF":return Cr;case"MPEG":return ge.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return Yt.webrtc&&Yt.ws&&Se.h264&&(ge.mp4||ge.webm);default:return Fs(i)}})},Ms=a=>{let e="DASH_WEBM",t="DASH_WEBM_AV1";switch(a){case"vp9":return[e,t];case"av1":return[t,e];case"none":return[];case"smooth":return Qt?Qt[t].smooth?[t,e]:Qt[e].smooth?[e,t]:[t,e]:[e,t];case"power_efficient":return Qt?Qt[t].powerEfficient?[t,e]:Qt[e].powerEfficient?[e,t]:[t,e]:[e,t];default:Fs(a)}return[e,t]},eg=({webmCodec:a,androidPreferredFormat:e,preferMultiStream:t})=>{let r=[...t?["DASH_STREAMS"]:[],...Ms(a),"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]],i=[...t?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]];if(Ns.isAndroid)switch(e){case"mpeg":return["MPEG",...r,"HLS","HLS_ONDEMAND"];case"hls":return["HLS","HLS_ONDEMAND",...r,"MPEG"];case"dash":return[...r,"HLS","HLS_ONDEMAND","MPEG"];case"dash_any_mpeg":return[...i,"MPEG",...Ms(a),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...Ms(a),"MPEG",...i,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...Ms(a),...i,"HLS","HLS_ONDEMAND"];default:Fs(e)}return Cr?[...r,"HLS","HLS_ONDEMAND","MPEG"]:[...r,"HLS","HLS_ONDEMAND","MPEG"]},tg=({androidPreferredFormat:a,preferCMAF:e,preferWebRTC:t})=>{let r=e?["DASH_LIVE_CMAF","DASH_LIVE"]:["DASH_LIVE","DASH_LIVE_CMAF"],i=e?["HLS_LIVE_CMAF","HLS_LIVE"]:["HLS_LIVE","HLS_LIVE_CMAF"],s=[...r,...i],n=[...i,...r],o,u=Ns.isMac&&Ns.isSafari;if(Ns.isAndroid)switch(a){case"dash":case"dash_any_mpeg":case"dash_any_webm":case"dash_sep":{o=s;break}case"hls":case"mpeg":{o=n;break}default:Fs(a)}else Cr&&!u?o=n:u?o=e?["DASH_LIVE_CMAF","HLS_LIVE_CMAF","HLS_LIVE","DASH_LIVE"]:["HLS_LIVE","DASH_LIVE","DASH_LIVE_CMAF","HLS_LIVE_CMAF"]:o=s;return t?["WEB_RTC_LIVE",...o]:[...o,"WEB_RTC_LIVE"]},Mu=a=>a?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],rg=a=>{if(a.size!==0){if(a.size===1)return a.values().next().value.split(".").at(0);for(let e of a){let t=(0,zb.default)(e.split("."),0);if(t==="opus"||t==="vp09"||t==="av01")return t}return a.values().next().value.split(".").at(0)}};import{ErrorCategory as Vi}from"@vkontakte/videoplayer-shared";var ig=a=>{if(!a)return{id:"EmptyResponse",category:Vi.PARSER,message:"Empty response"};if(a.length<=2&&a.match(/^\d+$/))return{id:`UVError#${a}`,category:Vi.NETWORK,message:`UV Error ${a}`};let e=a.trimStart().substring(0,100).toLowerCase();if(e.startsWith("<!doctype")||e.startsWith("<html>")||e.startsWith("<body>")||e.startsWith("<head>"))return{id:"UnexpectedHTML",category:Vi.NETWORK,message:"Received unexpected HTML, possibly a ISP block"};if(e.startsWith("<?xml"))return new DOMParser().parseFromString(a,"text/xml").querySelector("parsererror")?{id:"InvalidXML",category:Vi.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:Vi.PARSER,message:"Response is valid XML, but parser failed"}};var Dr=(a,e)=>{for(let t=0;t<a.length;t++)if(a.start(t)*1e3<=e&&a.end(t)*1e3>e)return!0;return!1};import{abortable as rl,assertNonNullable as tr,combine as Ys,ErrorCategory as At,filter as Qs,filterChanged as Zg,fromEvent as Ur,interval as il,isNonNullable as eS,map as al,merge as Hr,Subject as tS,Subscription as rS,tap as cR,throttle as dR,clientChecker as pR,ValueSubject as te,flattenObject as ha,getTraceSubscriptionMethod as hR}from"@vkontakte/videoplayer-shared";var Fr=Ye(Ai(),1);var ek=(a,e={})=>{let r=e.timeout||1,i=performance.now();return window.setTimeout(()=>{a({get didTimeout(){return e.timeout?!1:performance.now()-i-1>r},timeRemaining(){return Math.max(0,1+(performance.now()-i))}})},1)},tk=a=>window.clearTimeout(a),ag=typeof window.requestIdleCallback!="function"||typeof window.cancelIdleCallback!="function",Cu=ag?ek:window.requestIdleCallback,HB=ag?tk:window.cancelIdleCallback;var Wg=Ye(ys(),1);import{assertNever as rk,ErrorCategory as sg,clientChecker as Du,Subject as ng}from"@vkontakte/videoplayer-shared";var ik=16,og=!1;try{og=Du.isSafari&&!!Du.macVersion&&Du.macVersion<=ik}catch(a){console.error(a)}var Bu=class{constructor(e){this.bufferFull$=new ng;this.error$=new ng;this.queue=[];this.currentTask=null;this.destroyed=!1;this.completeTask=()=>{var e;try{if(this.currentTask){let t=(e=this.currentTask.signal)==null?void 0:e.aborted;this.currentTask.callback(!t),this.currentTask=null}this.queue.length&&this.pull()}catch(t){this.error$.next({id:"BufferTaskQueueUnknown",category:sg.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:t})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(r=>{let i={operation:"append",data:e,signal:t,callback:r};this.queue.push(i),this.pull()})}async remove(e,t,r){return r&&r.aborted?!1:new Promise(i=>{let s={operation:"remove",from:e,to:t,signal:r,callback:i};this.queue.unshift(s),this.pull()})}async abort(e){return new Promise(t=>{let r;og&&e?r={operation:"safariAbort",init:e,callback:t}:r={operation:"abort",callback:t};for(let{callback:i}of this.queue)i(!1);r&&(this.queue=[r]),this.pull()})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){var i;if(this.buffer.updating||this.currentTask||this.destroyed)return;let e=this.queue.shift();if(!e)return;if((i=e.signal)!=null&&i.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(s){s instanceof DOMException&&s.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):s instanceof DOMException&&s.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:sg.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:s}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){let{operation:t}=e;switch(t){case"append":this.buffer.appendBuffer(e.data);break;case"remove":this.buffer.remove(e.from/1e3,e.to/1e3);break;case"abort":this.buffer.abort();break;case"safariAbort":{this.buffer.abort(),this.buffer.appendBuffer(e.init);break}default:rk(t)}}},ug=Bu;var Ou=a=>{let e=0;for(let t=0;t<a.length;t++)e+=a.end(t)-a.start(t);return e*1e3};import{abortable as Nr,assertNonNullable as Be,ErrorCategory as Xt,fromEvent as Ku,getExponentialDelay as Ju,isNonNullable as Xu,isNullable as Oe,once as eR,Subject as tR,Subscription as rR,ValueSubject as na}from"@vkontakte/videoplayer-shared";var F=class{constructor(e,t){this.cursor=0;this.source=e,this.boxParser=t,this.children=[];let r=this.readUint32();this.type=this.readString(4),this.size32=r<=e.buffer.byteLength-e.byteOffset?r:NaN;let i=this.size32?this.size32-8:void 0,s=e.byteOffset+this.cursor;this.size64=0,this.usertype=0,this.content=new DataView(e.buffer,s,i),this.children=this.parseChildrenBoxes()}get id(){return this.type}get size(){return this.size32}parseChildrenBoxes(){return[]}scanForBoxes(e){return this.boxParser.parse(e)}readString(e,t="ascii"){let i=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,i}readUint8(){let e=this.source.getUint8(this.cursor);return this.cursor+=1,e}readUint16(){let e=this.source.getUint16(this.cursor);return this.cursor+=2,e}readUint32(){let e=this.source.getUint32(this.cursor);return this.cursor+=4,e}readUint64(){let e=this.source.getBigInt64(this.cursor);return this.cursor+=8,e}};var Br=class extends F{};var _i=class extends F{};var Ni=class extends F{constructor(e,t){super(e,t),this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let r=this.size-this.cursor;for(;r;){let i=this.readString(4);this.compatibleBrands.push(i),r-=4}}};var Fi=class extends F{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var qi=class extends F{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Ui=class extends F{constructor(e,t){super(e,t),this.data=this.content}};var z=class extends F{constructor(e,t){super(e,t);let r=this.readUint32();this.version=r>>>24,this.flags=r&16777215}};var zt=class extends z{get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e,t){super(e,t),this.segments=[],this.referenceId=this.readUint32(),this.timescale=this.readUint32(),this.earliestPresentationTime32=this.readUint32(),this.firstOffset32=this.readUint32(),this.earliestPresentationTime64=0,this.firstOffset64=0,this.referenceCount=this.readUint32()&65535;for(let r=0;r<this.referenceCount;r++){let i=this.readUint32(),s=i>>>31,n=i<<1>>>1,o=this.readUint32();i=this.readUint32();let u=i>>>28,l=i<<3>>>3;this.segments.push({referenceType:s,referencedSize:n,subsegmentDuration:o,SAPType:u,SAPDeltaTime:l})}}};var Hi=class extends F{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ji=class extends F{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Gi=class extends z{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 Wi=class extends z{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var Yi=class extends z{constructor(e,t){super(e,t),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}};var Qi=class extends F{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var zi=class extends z{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 Ki=class extends F{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Ji=class extends F{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Xi=class extends z{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var Zi=class extends F{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ea=class extends z{constructor(e,t){super(e,t),this.trackId=this.readUint32(),this.flags&1&&(this.baseDataOffset=this.readUint64()),this.flags&2&&(this.sampleDescriptionIndex=this.readUint32()),this.flags&8&&(this.defaultSampleDuration=this.readUint32()),this.flags&16&&(this.defaultSampleSize=this.readUint32()),this.flags&32&&(this.defaultSampleFlags=this.readUint32())}};var ta=class extends z{constructor(t,r){super(t,r);this.baseMediaDecodeTime32=0;this.baseMediaDecodeTime64=BigInt(0);this.version===1?this.baseMediaDecodeTime64=this.readUint64():this.baseMediaDecodeTime32=this.readUint32()}get baseMediaDecodeTime(){return this.version===1?this.baseMediaDecodeTime64:this.baseMediaDecodeTime32}};var ra=class extends z{constructor(t,r){super(t,r);this.sampleDuration=[];this.sampleSize=[];this.sampleFlags=[];this.sampleCompositionTimeOffset=[];this.optionalFields=0;this.sampleCount=this.readUint32(),this.flags&1&&(this.dataOffset=this.readUint32()),this.flags&4&&(this.firstSampleFlags=this.readUint32());for(let i=0;i<this.sampleCount;i++)this.flags&256&&this.sampleDuration.push(this.readUint32()),this.flags&512&&this.sampleSize.push(this.readUint32()),this.flags&1024&&this.sampleFlags.push(this.readUint32()),this.flags&2048&&this.sampleCompositionTimeOffset.push(this.readUint32())}};var sk={ftyp:Ni,moov:Fi,moof:qi,mdat:Ui,sidx:zt,trak:Hi,mdia:Qi,mfhd:Xi,tkhd:zi,traf:Zi,tfhd:ea,tfdt:ta,trun:ra,minf:Ki,sv3d:ji,st3d:Gi,prhd:Wi,proj:Ji,equi:Yi,uuid:_i,unknown:Br},Kt=class a{constructor(e={}){this.options={offset:0,...e}}parse(e){let t=[],r=this.options.offset;for(;r<e.byteLength;)try{let s=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+r+4,4)),n=this.createBox(s,new DataView(e.buffer,e.byteOffset+r));if(!n.size)break;t.push(n),r+=n.size}catch(i){break}return t}createBox(e,t){let r=sk[e];return r?new r(t,new a):new Br(t,new a)}};var Or=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{var r,i,s;(s=(r=this.index)[i=t.type])!=null||(r[i]=[]),this.index[t.type].push(t),t.children.length>0&&this.indexBoxLevel(t.children)})}find(e){return this.index[e]&&this.index[e][0]?this.index[e][0]:null}findAll(e){return this.index[e]||[]}};var ok=new TextDecoder("ascii"),uk=a=>ok.decode(new DataView(a.buffer,a.byteOffset+4,4))==="ftyp",lk=a=>{let e=new zt(a,new Kt),t=e.earliestPresentationTime/e.timescale*1e3,r=a.byteOffset+a.byteLength+e.firstOffset;return e.segments.map(s=>{if(s.referenceType!==0)throw new Error("Unsupported multilevel sidx");let n=s.subsegmentDuration/e.timescale*1e3,o={status:"none",time:{from:t,to:t+n},byte:{from:r,to:r+s.referencedSize-1}};return t+=n,r+=s.referencedSize,o})},ck=(a,e)=>{let r=new Kt().parse(a),i=new Or(r),s=i.findAll("moof"),n=e?i.findAll("uuid"):i.findAll("mdat");if(!(n.length&&s.length))return null;let o=s[0],u=n[n.length-1],l=o.source.byteOffset,d=u.source.byteOffset-o.source.byteOffset+u.size;return new DataView(a.buffer,l,d)},dk=(a,e)=>{let r=new Kt().parse(a),s=new Or(r).findAll("traf"),n=s[s.length-1].children.find(d=>d.type==="tfhd"),o=s[s.length-1].children.find(d=>d.type==="tfdt"),u=s[s.length-1].children.find(d=>d.type==="trun"),l=0;return u.sampleDuration.length?l=u.sampleDuration.reduce((d,p)=>d+p,0):l=n.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+l)/e*1e3},pk=a=>{let e={is3dVideo:!1,stereoMode:0,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}},r=new Kt().parse(a),i=new Or(r);if(i.find("sv3d")){e.is3dVideo=!0;let n=i.find("st3d");n&&(e.stereoMode=n.stereoMode);let o=i.find("prhd");o&&(e.projectionData.pose.yaw=o.poseYawDegrees,e.projectionData.pose.pitch=o.posePitchDegrees,e.projectionData.pose.roll=o.poseRollDegrees);let u=i.find("equi");u&&(e.projectionData.bounds.top=u.projectionBoundsTop,e.projectionData.bounds.right=u.projectionBoundsRight,e.projectionData.bounds.bottom=u.projectionBoundsBottom,e.projectionData.bounds.left=u.projectionBoundsLeft)}return e},lg={validateData:uk,parseInit:pk,getIndexRange:()=>{},parseSegments:lk,parseFeedableSegmentChunk:ck,getSegmentEndTime:dk};import{assertNonNullable as _u,isNonNullable as hg,isNullable as fk}from"@vkontakte/videoplayer-shared";import{assertNever as hk}from"@vkontakte/videoplayer-shared";var cg={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"}},dg=a=>{let e=a.getUint8(0),t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);let r=ia(a,t),i=r in cg,s=i?cg[r].type:"binary",n=a.getUint8(t),o=0;n&128?o=1:n&64?o=2:n&32?o=3:n&16?o=4:n&8?o=5:n&4?o=6:n&2?o=7:n&1&&(o=8);let u=new DataView(a.buffer,a.byteOffset+t+1,o-1),l=n&255>>o,c=ia(u),d=l*2**((o-1)*8)+c,p=t+o,h;return p+d>a.byteLength?h=new DataView(a.buffer,a.byteOffset+p):h=new DataView(a.buffer,a.byteOffset+p,d),{tag:i?r:"0x"+r.toString(16).toUpperCase(),type:s,tagHeaderSize:p,tagSize:p+d,value:h,valueSize:d}},ia=(a,e=a.byteLength)=>{switch(e){case 1:return a.getUint8(0);case 2:return a.getUint16(0);case 3:return a.getUint8(0)*2**16+a.getUint16(1);case 4:return a.getUint32(0);case 5:return a.getUint8(0)*2**32+a.getUint32(1);case 6:return a.getUint16(0)*2**32+a.getUint32(2);case 7:{let t=a.getUint8(0)*281474976710656+a.getUint16(1)*4294967296+a.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},He=(a,e)=>{switch(e){case"int":return a.getInt8(0);case"uint":return ia(a);case"float":return a.byteLength===4?a.getFloat32(0):a.getFloat64(0);case"string":return new TextDecoder("ascii").decode(a);case"utf8":return new TextDecoder("utf-8").decode(a);case"date":return new Date(Date.UTC(2001,0)+a.getInt8(0)).getTime();case"master":return a;case"binary":return a;default:hk(e)}},Jt=(a,e)=>{let t=0;for(;t<a.byteLength;){let r=new DataView(a.buffer,a.byteOffset+t),i=dg(r);if(!e(i))return;i.type==="master"&&Jt(i.value,e),t=i.value.byteOffset-a.byteOffset+i.valueSize}},pg=a=>{if(a.getUint32(0)!==440786851)return!1;let e,t,r,i=dg(a);return Jt(i.value,({tag:s,type:n,value:o})=>(s===17143?e=He(o,n):s===17026?t=He(o,n):s===17029&&(r=He(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(r===void 0||r<=2)};var fg=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],mk=[231,22612,22743,167,171,163,160,175],bk=a=>{let e,t,r,i,s=!1,n=!1,o=!1,u,l,c=!1,d=0;return Jt(a,({tag:p,type:h,value:f,valueSize:b})=>{if(p===21419){let g=He(f,h);l=ia(g)}else p!==21420&&(l=void 0);return p===408125543?(e=f.byteOffset,t=f.byteOffset+b):p===357149030?s=!0:p===290298740?n=!0:p===2807729?r=He(f,h):p===17545?i=He(f,h):p===21420&&l===475249515?u=He(f,h):p===374648427?Jt(f,({tag:g,type:y,value:I})=>g===30321?(c=He(I,y)===1,!1):!0):s&&n&&fg.includes(p)&&(o=!0),!o}),_u(e,"Failed to parse webm Segment start"),_u(t,"Failed to parse webm Segment end"),_u(i,"Failed to parse webm Segment duration"),r=r!=null?r:1e6,{segmentStart:Math.round(e/1e9*r*1e3),segmentEnd:Math.round(t/1e9*r*1e3),timeScale:r,segmentDuration:Math.round(i/1e9*r*1e3),cuesSeekPosition:u,is3dVideo:c,stereoMode:d,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},gk=a=>{if(fk(a.cuesSeekPosition))return;let e=a.segmentStart+a.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},Sk=(a,e)=>{let t=!1,r=!1,i=o=>hg(o.time)&&hg(o.position),s=[],n;return Jt(a,({tag:o,type:u,value:l})=>{switch(o){case 475249515:t=!0;break;case 187:n&&i(n)&&s.push(n),n={};break;case 179:n&&(n.time=He(l,u));break;case 183:break;case 241:n&&(n.position=He(l,u));break;default:t&&fg.includes(o)&&(r=!0)}return!(t&&r)}),n&&i(n)&&s.push(n),s.map((o,u)=>{let{time:l,position:c}=o,d=s[u+1];return{status:"none",time:{from:l,to:d?d.time:e.segmentDuration},byte:{from:e.segmentStart+c,to:d?e.segmentStart+d.position-1:e.segmentEnd-1}}})},vk=a=>{let e=0,t=!1;try{Jt(a,r=>r.tag===524531317?r.tagSize<=a.byteLength?(e=r.tagSize,!1):(e+=r.tagHeaderSize,!0):mk.includes(r.tag)?(e+r.tagSize<=a.byteLength&&(e+=r.tagSize,t||(t=[163,160,175].includes(r.tag))),!0):!1)}catch(r){}return e>0&&e<=a.byteLength&&t?new DataView(a.buffer,a.byteOffset,e):null},mg={validateData:pg,parseInit:bk,getIndexRange:gk,parseSegments:Sk,parseFeedableSegmentChunk:vk};var Vr=a=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(a);if(e){let[,t,r]=e;if(t==="audio"||t==="video")switch(r){case"webm":return mg;case"mp4":return lg}}throw new ReferenceError(`Unsupported mime type ${a}`)};var Gu=Ye(Vg(),1);var ju=a=>{let e=a.split("."),[t,...r]=e;if(!t)return!1;switch(t){case"av01":{let[i,s,n]=r;return!!(n&&parseInt(n,10)>8)}case"vp09":{let[i,s,n]=r;return!!(i&&parseInt(i,10)>=2&&n&&parseInt(n,10)>8)}case"avc1":{let i=r[0];if(!i||i.length!==6)return!1;let[s,n]=i.toUpperCase(),o=s+n;return["6E","7A","F4"].includes(o)}}return!1};import{isNonNullable as Ng,isNullable as Fg}from"@vkontakte/videoplayer-shared";var _g=a=>{if(a.includes("/")){let e=a.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(a)};var qg=a=>{if(!a.startsWith("P"))return;let e=(n,o)=>{let u=n?parseFloat(n.replace(",",".")):NaN;return(isNaN(u)?0:u)*o},r=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(a),i=(r==null?void 0:r[1])==="-"?-1:1,s={days:e(r==null?void 0:r[5],i),hours:e(r==null?void 0:r[6],i),minutes:e(r==null?void 0:r[7],i),seconds:e(r==null?void 0:r[8],i)};return s.days*24*60*60*1e3+s.hours*60*60*1e3+s.minutes*60*1e3+s.seconds*1e3},lt=(a,e)=>{let t=a;t=(0,Gu.default)(t,"$$","$");let r={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[i,s]of Object.entries(r)){let n=new RegExp(`\\$${i}(?:%0(\\d+)d)?\\$`,"g");t=(0,Gu.default)(t,n,(o,u)=>Fg(s)?o:Fg(u)?s:s.padStart(parseInt(u,10),"0"))}return t},Ug=(a,e)=>{var v,T,R,U,$,B,N,O,w,L,q,k,x,V,H,W,K,ne,Lt,pt,A,oe,ve,Pe,ht,ir,ft,Mt,ar,Wr,Il,El,xl,Pl,Al,wl,kl,Rl,$l,Ll,Ml,Cl,Dl,Bl,Ol,Vl,_l,Nl,Fl,ql,Ul,Hl,jl,Gl,Wl,Yl,Ql,zl,Kl,Jl;let r=new DOMParser().parseFromString(a,"application/xml"),i={video:[],audio:[],text:[]},s=r.children[0],n=s.getElementsByTagName("Period")[0],o=(R=(T=(v=s.querySelector("BaseURL"))==null?void 0:v.textContent)==null?void 0:T.trim())!=null?R:"",u=n.children,l=s.getAttribute("type")==="dynamic",c=s.getAttribute("availabilityStartTime"),d=c?new Date(c).getTime():void 0,p,h=s.getAttribute("mediaPresentationDuration"),f=n.getAttribute("duration"),b=s.getElementsByTagName("vk:Attrs")[0],g=b==null?void 0:b.getElementsByTagName("vk:XPlaybackDuration")[0].textContent;if(h)p=qg(h);else if(f){let ue=qg(f);Ng(ue)&&(p=ue)}else g&&(p=parseInt(g,10));let y=0,I=($=(U=s.getAttribute("profiles"))==null?void 0:U.split(","))!=null?$:[];for(let ue of u){let ZS=(B=ue.getAttribute("id"))!=null?B:"id"+(y++).toString(10),Yr=(N=ue.getAttribute("mimeType"))!=null?N:"",mn=(O=ue.getAttribute("codecs"))!=null?O:"",bn=(w=ue.getAttribute("contentType"))!=null?w:Yr==null?void 0:Yr.split("/")[0],ev=(q=(L=ue.getAttribute("profiles"))==null?void 0:L.split(","))!=null?q:[],tv=(k=ue.getAttribute("lang"))!=null?k:void 0,rv=(H=(V=(x=ue.querySelector("Label"))==null?void 0:x.textContent)==null?void 0:V.trim())!=null?H:void 0,iv=ue.querySelectorAll("Representation"),av=ue.querySelector("SegmentTemplate"),sv=(K=(W=ue.querySelector("Role"))==null?void 0:W.getAttribute("value"))!=null?K:void 0,Qr=bn,J={id:ZS,language:tv,isDefault:sv==="main",label:rv,codecs:mn,hdr:Qr==="video"&&ju(mn),mime:Yr,representations:[]};for(let G of iv){let nv=(ne=G.getAttribute("lang"))!=null?ne:void 0,ov=(Lt=G.getAttribute("label"))!=null?Lt:void 0,uv=(oe=(A=(pt=G.querySelector("BaseURL"))==null?void 0:pt.textContent)==null?void 0:A.trim())!=null?oe:"",gn=new URL(uv||o,e).toString(),sr=(ve=G.getAttribute("mimeType"))!=null?ve:Yr,ka=(ht=(Pe=G.getAttribute("codecs"))!=null?Pe:mn)!=null?ht:"",Sn;if(bn==="text"){let Ct=G.getAttribute("id")||"",vn=Ct.includes("_auto"),Dt=G.querySelector("SegmentTemplate");if(!Dt)throw new Error("Unknown MPD segment text referencing type");let zr={representationId:(ir=G.getAttribute("id"))!=null?ir:void 0,bandwidth:(ft=G.getAttribute("bandwidth"))!=null?ft:void 0},Ra=parseInt((Mt=G.getAttribute("bandwidth"))!=null?Mt:"",10)/1e3,$a=(Wr=parseInt((ar=Dt.getAttribute("startNumber"))!=null?ar:"",10))!=null?Wr:1,nr=parseInt((Il=Dt.getAttribute("timescale"))!=null?Il:"",10),yn=(El=Dt.querySelectorAll("SegmentTimeline S"))!=null?El:[],or=Dt.getAttribute("media");if(!or)throw new ReferenceError("No media attribute in SegmentTemplate");let La=[],Ma=0,Ca="",ur=0,Kr=$a,re=0;for(let Ve of yn){let Bt=parseInt((xl=Ve.getAttribute("d"))!=null?xl:"",10),Ae=parseInt((Pl=Ve.getAttribute("r"))!=null?Pl:"",10)||0,mt=parseInt((Al=Ve.getAttribute("t"))!=null?Al:"",10);re=Number.isFinite(mt)?mt:re;let Ot=Bt/nr*1e3,bt=re/nr*1e3;for(let Ge=0;Ge<Ae+1;Ge++){let gt=lt(or,{...zr,segmentNumber:Kr.toString(10),segmentTime:(re+Ge*Bt).toString(10)}),lr=(bt!=null?bt:0)+Ge*Ot,Xr=lr+Ot;Kr++,La.push({time:{from:lr,to:Xr},url:gt})}re+=(Ae+1)*Bt,Ma+=(Ae+1)*Ot}ur=re/nr*1e3,Ca=lt(or,{...zr,segmentNumber:Kr.toString(10),segmentTime:re.toString(10)});let Jr={time:{from:ur,to:1/0},url:Ca},Xe={type:"template",baseUrl:gn,segmentTemplateUrl:or,initUrl:"",totalSegmentsDurationMs:Ma,segments:La,nextSegmentBeyondManifest:Jr,timescale:nr};Sn={id:Ct,kind:"text",segmentReference:Xe,profiles:[],duration:p,bitrate:Ra,mime:"",codecs:"",width:0,height:0,isAuto:vn}}else{let Ct=(kl=(wl=G.getAttribute("contentType"))!=null?wl:sr==null?void 0:sr.split("/")[0])!=null?kl:bn,vn=($l=(Rl=ue.getAttribute("profiles"))==null?void 0:Rl.split(","))!=null?$l:[],Dt=parseInt((Ll=G.getAttribute("width"))!=null?Ll:"",10),zr=parseInt((Ml=G.getAttribute("height"))!=null?Ml:"",10),Ra=parseInt((Cl=G.getAttribute("bandwidth"))!=null?Cl:"",10)/1e3,$a=(Dl=G.getAttribute("frameRate"))!=null?Dl:"",nr=(Bl=G.getAttribute("quality"))!=null?Bl:void 0,yn=$a?_g($a):void 0,or=(Ol=G.getAttribute("id"))!=null?Ol:"id"+(y++).toString(10),La=Ct==="video"?`${zr}p`:Ct==="audio"?`${Ra}Kbps`:ka,Ma=`${or}@${La}`,Ca=[...I,...ev,...vn],ur,Kr=G.querySelector("SegmentBase"),re=(Vl=G.querySelector("SegmentTemplate"))!=null?Vl:av;if(Kr){let Xe=(Nl=(_l=G.querySelector("SegmentBase Initialization"))==null?void 0:_l.getAttribute("range"))!=null?Nl:"",[Ve,Bt]=Xe.split("-").map(gt=>parseInt(gt,10)),Ae={from:Ve,to:Bt},mt=(Fl=G.querySelector("SegmentBase"))==null?void 0:Fl.getAttribute("indexRange"),[Ot,bt]=mt?mt.split("-").map(gt=>parseInt(gt,10)):[],Ge=mt?{from:Ot,to:bt}:void 0;ur={type:"byteRange",url:gn,initRange:Ae,indexRange:Ge}}else if(re){let Xe={representationId:(ql=G.getAttribute("id"))!=null?ql:void 0,bandwidth:(Ul=G.getAttribute("bandwidth"))!=null?Ul:void 0},Ve=parseInt((Hl=re.getAttribute("timescale"))!=null?Hl:"",10),Bt=(jl=re.getAttribute("initialization"))!=null?jl:"",Ae=re.getAttribute("media"),mt=(Wl=parseInt((Gl=re.getAttribute("startNumber"))!=null?Gl:"",10))!=null?Wl:1,Ot=lt(Bt,Xe);if(!Ae)throw new ReferenceError("No media attribute in SegmentTemplate");let bt=(Yl=re.querySelectorAll("SegmentTimeline S"))!=null?Yl:[],Ge=[],gt=0,lr="",Xr=0;if(bt.length){let Da=mt,_e=0;for(let cr of bt){let We=parseInt((Ql=cr.getAttribute("d"))!=null?Ql:"",10),Vt=parseInt((zl=cr.getAttribute("r"))!=null?zl:"",10)||0,Ba=parseInt((Kl=cr.getAttribute("t"))!=null?Kl:"",10);_e=Number.isFinite(Ba)?Ba:_e;let Tn=We/Ve*1e3,In=_e/Ve*1e3;for(let Oa=0;Oa<Vt+1;Oa++){let cv=lt(Ae,{...Xe,segmentNumber:Da.toString(10),segmentTime:(_e+Oa*We).toString(10)}),Xl=(In!=null?In:0)+Oa*Tn,dv=Xl+Tn;Da++,Ge.push({time:{from:Xl,to:dv},url:cv})}_e+=(Vt+1)*We,gt+=(Vt+1)*Tn}Xr=_e/Ve*1e3,lr=lt(Ae,{...Xe,segmentNumber:Da.toString(10),segmentTime:_e.toString(10)})}else if(Ng(p)){let _e=parseInt((Jl=re.getAttribute("duration"))!=null?Jl:"",10)/Ve*1e3,cr=Math.ceil(p/_e),We=0;for(let Vt=1;Vt<cr;Vt++){let Ba=lt(Ae,{...Xe,segmentNumber:Vt.toString(10),segmentTime:We.toString(10)});Ge.push({time:{from:We,to:We+_e},url:Ba}),We+=_e}Xr=We,lr=lt(Ae,{...Xe,segmentNumber:cr.toString(10),segmentTime:We.toString(10)})}let lv={time:{from:Xr,to:1/0},url:lr};ur={type:"template",baseUrl:gn,segmentTemplateUrl:Ae,initUrl:Ot,totalSegmentsDurationMs:gt,segments:Ge,nextSegmentBeyondManifest:lv,timescale:Ve}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!Ct||!sr)continue;let Jr={video:"video",audio:"audio",text:"text"}[Ct];if(!Jr)continue;Qr||(Qr=Jr),Sn={id:Ma,kind:Jr,segmentReference:ur,profiles:Ca,duration:p,bitrate:Ra,mime:sr,codecs:ka,width:Dt,height:zr,fps:yn,quality:nr}}J.language||(J.language=nv),J.label||(J.label=ov),J.mime||(J.mime=sr),J.codecs||(J.codecs=ka),J.hdr||(J.hdr=Qr==="video"&&ju(ka)),J.representations.push(Sn)}Qr&&i[Qr].push(J)}return{dynamic:l,liveAvailabilityStartTime:d,duration:p,streams:i}};var aa=Ye(Ai(),1);import{videoSizeToQuality as Zk}from"@vkontakte/videoplayer-shared";var Hg=({id:a,width:e,height:t,bitrate:r,fps:i,quality:s})=>{var o;let n=(o=s?Et(s):void 0)!=null?o:Zk({width:e,height:t});return n&&{id:a,quality:n,bitrate:r,size:{width:e,height:t},fps:i}},jg=({id:a,bitrate:e})=>({id:a,bitrate:e}),qs=(a,e,t)=>{var i;let r=e.indexOf(a);return(i=(0,aa.default)(t,Math.round(t.length*r/e.length)))!=null?i:(0,aa.default)(t,-1)},Gg=({language:a,label:e,id:t,url:r,isAuto:i})=>({id:t,url:r,isAuto:i,type:"internal",language:a,label:e}),Qu=({id:a,language:e,label:t,codecs:r,isDefault:i})=>({id:a,language:e,label:t,codec:(0,aa.default)(r.split("."),0),isDefault:i}),zu=({id:a,language:e,label:t,hdr:r,codecs:i})=>({id:a,language:e,hdr:r,label:t,codec:(0,aa.default)(i.split("."),0)}),Us=a=>"url"in a,De=a=>a.type==="template",sa=a=>a instanceof DOMException&&(a.name==="AbortError"||a.code===20);var oa=class{constructor(e,t,r,{fetcher:i,tuning:s,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentSegmentLength$=new na(0);this.onLastSegment$=new na(!1);this.fullyBuffered$=new na(!1);this.playingRepresentation$=new na(void 0);this.playingRepresentationInit$=new na(void 0);this.error$=new tR;this.gaps=[];this.subscription=new rR;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new ot;this.destroyAbortController=new ot;this.bufferLimit=1/0;this.failedDownloads=0;this.isLive=!1;this.liveUpdateSegmentIndex=0;this.liveInitialAdditionalOffset=0;this.isSeekingLive=!1;this.index=0;this.loadByteRangeSegmentsTimeoutId=0;this.startWith=Nr(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);Be(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new ug(this.sourceBuffer),this.subscription.add(Ku(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let o,u=this.mediaSource.readyState;u!=="open"&&(o={id:`SegmentEjection_source_${u}`,category:Xt.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o!=null||(o={id:"SegmentEjection",category:Xt.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),this.error$.next(o)})),this.subscription.add(Ku(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:Xt.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o)return;let u=Math.min(this.bufferLimit,Ou(this.sourceBuffer.buffered)*.8);if(this.bufferLimit=u,this.tuning.useNewPruneBufferStrategy){let l=st(this.sourceBuffer.buffered,o),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBufferNew(o,n*2,l<c)}else this.pruneBufferOld(o,n)})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(n=>this.error$.next(n))),yield this.loadInit(t,"high",!0);let r=this.initData.get(t.id),i=this.segments.get(t.id),s=this.parsedInitData.get(t.id);Be(r,"No init buffer for starting representation"),Be(i,"No segments for starting representation"),r instanceof ArrayBuffer&&(this.searchGaps(i,t),yield this.sourceBufferTaskQueue.append(r,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(s))}.bind(this));this.switchTo=Nr(this.destroyAbortController.signal,async function*(e,t=!1){if(e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let r=this.representations.get(e);Be(r,`No such representation ${e}`);let i=this.segments.get(e),s=this.initData.get(e);if(Oe(s)||Oe(i)?yield this.loadInit(r,"high",!1):s instanceof Promise&&(yield s),i=this.segments.get(e),Be(i,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer))if(this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer(),this.maintain();else{let n=this.getCurrentPosition();Xu(n)&&(this.isLive||(this.tuning.useNewPruneBufferStrategy&&(this.bufferLimit=1/0),await this.pruneBuffer(n,1/0,!0)),this.maintain(n)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}}.bind(this));this.seekLive=Nr(this.destroyAbortController.signal,async function*(e){var u,l;let t=(u=e==null?void 0:e.flatMap(c=>c.representations))!=null?u:[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let c of this.representations.keys()){let d=t.find(f=>f.id===c);d&&this.representations.set(c,d);let p=this.representations.get(c);if(!p||!De(p.segmentReference))return;let h=this.getActualLiveStartingSegments(p.segmentReference);this.segments.set(p.id,h)}let r=(l=this.switchingToRepresentationId)!=null?l:this.downloadingRepresentationId,i=this.representations.get(r);Be(i);let s=this.segments.get(r);Be(s,"No segments for starting representation");let n=this.initData.get(r);if(Be(n,"No init buffer for starting representation"),!(n instanceof ArrayBuffer))return;let o=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,this.abort(),o&&(yield this.sourceBufferTaskQueue.remove(o.from*1e3,o.to*1e3,this.destroyAbortController.signal)),this.searchGaps(s,i),yield this.sourceBufferTaskQueue.append(n,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this));this.fetcher=i,this.tuning=s,this.compatibilityMode=u,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=o,this.isLive=!!(l!=null&&l.dynamic),this.resetAccumulateBufferAfterStall(),this.startAccumulateBuffer(),this.initData=new Map(r.map(c=>[c.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(r.map(c=>[c.id,c])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}abort(){for(let e of this.activeSegments)this.abortSegment(e.segment);this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new ot,this.abortBuffer()}maintain(e=this.getCurrentPosition()){var l,c;if(Oe(e)||Oe(this.downloadingRepresentationId)||Oe(this.playingRepresentationId)||Oe(this.sourceBuffer)||!Oe(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),r=this.segments.get(this.downloadingRepresentationId);if(Be(t,`No such representation ${this.downloadingRepresentationId}`),!r)return;let i=r.find(d=>e>=d.time.from&&e<d.time.to);this.currentSegmentLength$.next(((l=i==null?void 0:i.time.to)!=null?l:0)-((c=i==null?void 0:i.time.from)!=null?c:0));let s=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){let p=st(this.sourceBuffer.buffered,e),h=i?i.time.to+100:-1/0;i&&i.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&p>=i.time.to-e+100&&(s=h)}if(isFinite(this.bufferLimit)&&Ou(this.sourceBuffer.buffered)>=this.bufferLimit){let d=st(this.sourceBuffer.buffered,e),p=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,d<p);return}let o=[];if(!this.activeSegments.size&&(o=this.selectForwardBufferSegments(r,t.segmentReference.type,s),o.length)){let d="auto";if(this.tuning.dash.useFetchPriorityHints&&i)if(o.includes(i))d="high";else{let p=(0,Fr.default)(o,0);p&&p.time.from-i.time.to>=this.forwardBufferTarget/2&&(d="low")}this.loadSegments(o,t,d)}(!this.preloadOnly&&!this.allInitsLoaded&&i&&i.status==="fed"&&!o.length&&st(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let u=(0,Fr.default)(r,-1);u&&u.status==="fed"&&(this.fullyBuffered$.next(!0),this.isLive||this.onLastSegment$.next(i===u))}searchGaps(e,t){this.gaps=[];let r=0,i=this.isLive?this.liveInitialAdditionalOffset:0;for(let s of e)Math.trunc(s.time.from-r)>0&&this.gaps.push({representation:t.id,from:r,to:s.time.from+i}),r=s.time.to;Xu(t.duration)&&t.duration-r>0&&this.gaps.push({representation:t.id,from:r,to:t.duration})}getActualLiveStartingSegments(e){let t=e.segments,r=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,i=[],s=0,n=t.length-1;do i.unshift(t[n]),s+=t[n].time.to-t[n].time.from,n--;while(s<r&&n>=0);return this.liveInitialAdditionalOffset=s-r,this.isActiveLowLatency()?[i[0]]:i}getLiveSegmentsToLoadState(e){let t=e==null?void 0:e.streams[this.kind].flatMap(i=>i.representations).find(i=>i.id===this.downloadingRepresentationId);if(!t)return;let r=this.segments.get(t.id);if(r!=null&&r.length)return{from:r[0].time.from,to:r[r.length-1].time.to}}updateLive(e){var r,i,s,n;let t=(r=e==null?void 0:e.streams[this.kind].flatMap(o=>o.representations))!=null?r:[];for(let o of t){if(!o||!De(o.segmentReference))return;let u=o.segmentReference.segments.map(p=>({...p,status:"none",size:void 0})),l=(i=this.segments.get(o.id))!=null?i:[],c=(n=(s=(0,Fr.default)(l,-1))==null?void 0:s.time.to)!=null?n:0,d=u==null?void 0:u.findIndex(p=>Math.floor(c)>=Math.floor(p.time.from)&&Math.floor(c)<=Math.floor(p.time.to));if(d===-1){this.liveUpdateSegmentIndex=0;let p=this.getActualLiveStartingSegments(o.segmentReference);this.segments.set(o.id,p)}else{let p=u.slice(d+1);this.segments.set(o.id,[...l,...p])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;Be(e);let t=this.segments.get(e);if(t!=null&&t.length){let r=t[t.length-1];this.updateLowLatencyLiveIfNeeded(r)}}startAccumulateBuffer(){this.bufferAccumulation.enabled=!0}resetAccumulateBufferAfterStall(){this.bufferAccumulation={enabled:!1,targetBufferSizeMs:this.tuning.accumulationBufferStallSizeMs,accumulatedBufferSizeMs:0,accumulated:[]}}updateLowLatencyLiveIfNeeded(e){var t;for(let r of this.representations.values()){let i=r.segmentReference;if(!De(i))return;let s=(t=this.segments.get(r.id))!=null?t:[],n=s.find(u=>Math.floor(u.time.from)===Math.floor(e.time.from));if(n&&!isFinite(n.time.to)&&(n.time.to=e.time.to),!!!s.find(u=>Math.floor(u.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let u=Math.round(e.time.to*i.timescale/1e3).toString(10),l=lt(i.segmentTemplateUrl,{segmentTime:u});s.push({status:"none",time:{from:e.time.to,to:1/0},url:l})}}}findSegmentStartTime(e){var s,n,o;let t=(n=(s=this.switchingToRepresentationId)!=null?s:this.downloadingRepresentationId)!=null?n:this.playingRepresentationId;if(!t)return;let r=this.segments.get(t);if(!r)return;let i=r.find(u=>u.time.from<=e&&u.time.to>=e);return(o=i==null?void 0:i.time.from)!=null?o:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){var e;if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),(e=this.sourceBufferTaskQueue)==null||e.destroy(),this.gapDetectionIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer){this.mediaSource.readyState==="open"&&this.abortBuffer();try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(t){if(!(t instanceof DOMException&&t.name==="NotFoundError"))throw t}}this.sourceBuffer=null,this.downloadAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,r){return this.isLive?this.selectForwardBufferSegmentsLive(e,r):this.selectForwardBufferSegmentsRecord(e,t,r)}selectForwardBufferSegmentsLive(e,t){let r=e.findIndex(i=>t>=i.time.from&&t<i.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=r),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,r){let i=e.findIndex(({status:d,time:{from:p,to:h}},f)=>{let b=p<=r&&h>=r,g=p>r||b||f===0&&r===0,y=Math.min(this.forwardBufferTarget,this.bufferLimit),I=this.preloadOnly&&p<=r+y||h<=r+y;return(d==="none"||d==="partially_ejected"&&g&&I&&this.sourceBuffer&&!(Dr(this.sourceBuffer.buffered,p)&&Dr(this.sourceBuffer.buffered,h)))&&g&&I});if(i===-1)return[];if(t!=="byteRange")return e.slice(i,i+1);let s=e,n=0,o=0,u=[],l=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,c=this.preloadOnly?this.forwardBufferTarget:0;for(let d=i;d<s.length&&(n<=l||o<=c);d++){let p=s[d];if(n+=p.byte.to+1-p.byte.from,o+=p.time.to+1-p.time.from,p.status==="none"||p.status==="partially_ejected")u.push(p);else break}return u}async loadSegments(e,t,r="auto"){De(t.segmentReference)?await this.loadTemplateSegment(e[0],t,r):await this.loadByteRangeSegments(e,t,r)}async loadTemplateSegment(e,t,r="auto"){e.status="downloading";let i={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(i);let{range:s,url:n,signal:o,onProgress:u,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(await Nr(o,async function*(){let c=Ju(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(d=>setTimeout(d,c))}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let c=await this.fetcher.fetch(n,{range:s,signal:o,onProgress:u,priority:r,isLowLatency:this.isActiveLowLatency()});if(!c)return;let d=new DataView(c);if(!isFinite(i.segment.time.to)){let p=t.segmentReference.timescale,h=Vr(t.mime);i.segment.time.to=h.getSegmentEndTime(d,p)}u&&i.feedingBytes&&l?await Promise.all(l):await this.sourceBufferTaskQueue.append(d,o),i.segment.status="downloaded",this.onSegmentFullyAppended(i,t.id),this.failedDownloads=0}catch(c){this.abortActiveSegments([e]),sa(c)||this.failedDownloads++}}async loadByteRangeSegments(e,t,r="auto"){if(!e.length)return;for(let u of e)u.status="downloading",this.activeSegments.add({segment:u,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:i,url:s,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(await Nr(n,async function*(){let u=Ju(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),Ku(window,"online").pipe(eR()).subscribe(()=>{l(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(s,{range:i,onProgress:o,signal:n,priority:r}),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),sa(u)||this.failedDownloads++}}prepareByteRangeFetchSegmentParams(e,t){if(De(t.segmentReference))throw new Error("Representation is not byte range type");let r=t.segmentReference.url,i={from:(0,Fr.default)(e,0).byte.from,to:(0,Fr.default)(e,-1).byte.to},{signal:s}=this.downloadAbortController;return{url:r,range:i,signal:s,onProgress:(o,u)=>{if(!s.aborted)try{this.onSomeByteRangesDataLoaded({dataView:o,loaded:u,signal:s,onSegmentAppendFailed:()=>this.abort(),globalFrom:i?i.from:0,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:Xt.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!De(t.segmentReference))throw new Error("Representation is not template type");let r=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&r.searchParams.set("low-latency","yes");let i=r.toString(),{signal:s}=this.downloadAbortController,n=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(l,c)=>{if(!s.aborted)try{let d=this.onSomeTemplateDataLoaded({dataView:l,loaded:c,signal:s,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(d)}catch(d){this.error$.next({id:"SegmentFeeding",category:Xt.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:d})}}:void 0;return{url:i,signal:s,onProgress:u,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)e.includes(t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:r,onSegmentAppendFailed:i,signal:s}){if(!this.activeSegments.size)return;let n=this.representations.get(t);if(n)for(let o of this.activeSegments){let{segment:u}=o;if(o.representationId===t){if(s.aborted){i();continue}if(o.loadedBytes=r,o.loadedBytes>o.feedingBytes){let l=new DataView(e.buffer,e.byteOffset+o.feedingBytes,o.loadedBytes-o.feedingBytes),c=Vr(n.mime).parseFeedableSegmentChunk(l,this.isLive);c!=null&&c.byteLength&&(u.status="partially_fed",o.feedingBytes+=c.byteLength,await this.sourceBufferTaskQueue.append(c),o.fedBytes+=c.byteLength)}}}}onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:r,loaded:i,signal:s,onSegmentAppendFailed:n}){let o={dataView:e,representationId:t,globalFrom:r,loaded:i,signal:s,onSegmentAppendFailed:n};return this.tuning.useNewPartialSegmentFeeding?this.onSomeByteRangesDataLoadedNew(o):this.onSomeByteRangesDataLoadedOld(o)}onSomeByteRangesDataLoadedOld({dataView:e,representationId:t,globalFrom:r,loaded:i,signal:s,onSegmentAppendFailed:n}){if(!this.activeSegments.size)return;let o=this.representations.get(t);if(!o)return;let u=o.segmentReference.type,l=e.byteLength;for(let c of this.activeSegments){let{segment:d}=c,p=u==="byteRange",h=p?d.byte.to-d.byte.from+1:l;if(c.representationId!==t||!(!p||d.byte.from>=r&&d.byte.to<r+e.byteLength))continue;if(s.aborted){n();continue}let b=p?d.byte.from-r:0,g=p?d.byte.to-r:e.byteLength,y=b<i,I=g<=i;if(d.status==="downloading"&&y&&I){d.status="downloaded";let S=new DataView(e.buffer,e.byteOffset+b,h),v=this.getCurrentPosition();Xu(v)&&(this.bufferAccumulation.accumulatedBufferSizeMs=d.time.to-v,this.bufferAccumulation.accumulated.push({segmentView:S,segmentProgress:c}),this.activeSegments.delete(c));let T=({segmentView:R,segmentProgress:U})=>this.sourceBufferTaskQueue.append(R,s).then($=>$&&!s.aborted?this.onSegmentFullyAppended(U,t):n());this.bufferAccumulation.enabled&&this.bufferAccumulation.targetBufferSizeMs<this.bufferAccumulation.accumulatedBufferSizeMs?(this.bufferAccumulation.accumulated.forEach(T),this.resetAccumulateBufferAfterStall()):(!this.bufferAccumulation.enabled||!this.bufferAccumulation.targetBufferSizeMs||Oe(v))&&(T({segmentView:S,segmentProgress:c}),this.resetAccumulateBufferAfterStall())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&y&&!I&&(c.loadedBytes=Math.min(h,i-b),c.loadedBytes>c.feedingBytes)){let S=new DataView(e.buffer,e.byteOffset+b+c.feedingBytes,c.loadedBytes-c.feedingBytes),v=c.loadedBytes===h?S:Vr(o.mime).parseFeedableSegmentChunk(S);v!=null&&v.byteLength&&(d.status="partially_fed",c.feedingBytes+=v.byteLength,this.sourceBufferTaskQueue.append(v,s).then(T=>{if(s.aborted)n();else if(T)c.fedBytes+=v.byteLength,c.fedBytes===h&&this.onSegmentFullyAppended(c,t);else{if(c.feedingBytes<h)return;n()}}))}}}async onSomeByteRangesDataLoadedNew({dataView:e,representationId:t,globalFrom:r,loaded:i,signal:s,onSegmentAppendFailed:n}){if(!this.activeSegments.size)return;let o=this.representations.get(t);if(o)for(let u of this.activeSegments){let{segment:l}=u;if(u.representationId!==t)continue;if(s.aborted){n();continue}let c=l.byte.from-r,d=l.byte.to-r,p=d-c+1,h=c<i,f=d<=i;if(h){if(l.status==="downloading"&&f){l.status="downloaded";let b=new DataView(e.buffer,e.byteOffset+c,p);await this.sourceBufferTaskQueue.append(b,s)&&!s.aborted?this.onSegmentFullyAppended(u,t):n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(l.status==="downloading"||l.status==="partially_fed")&&(u.loadedBytes=Math.min(p,i-c),u.loadedBytes>u.feedingBytes)){let b=new DataView(e.buffer,e.byteOffset+c+u.feedingBytes,u.loadedBytes-u.feedingBytes),g=u.loadedBytes===p?b:Vr(o.mime).parseFeedableSegmentChunk(b);g!=null&&g.byteLength&&(l.status="partially_fed",u.feedingBytes+=g.byteLength,await this.sourceBufferTaskQueue.append(g,s)&&!s.aborted?(u.fedBytes+=g.byteLength,u.fedBytes===p&&this.onSegmentFullyAppended(u,t)):n())}}}}onSegmentFullyAppended(e,t){var r;this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status="fed",Us(e.segment)&&(e.segment.size=e.fedBytes);for(let i of this.representations.values())if(i.id!==t)for(let s of(r=this.segments.get(i.id))!=null?r:[])s.status==="fed"&&Math.round(s.time.from)===Math.round(e.segment.time.from)&&Math.round(s.time.to)===Math.round(e.segment.time.to)&&(s.status="none");Be(this.sourceBuffer),this.updateLowLatencyLiveIfNeeded(e.segment),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment])}abortSegment(e){e.status==="partially_fed"?e.status="partially_ejected":e.status!=="partially_ejected"&&(e.status="none");for(let t of this.activeSegments.values())if(t.segment===e){this.activeSegments.delete(t);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(let[i,s]of this.initData.entries()){let n=s instanceof Promise;t||(t=n),s===null&&(e=i)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let r=this.representations.get(e);r&&(this.initLoadIdleCallback=Cu(()=>(0,Wg.default)(this.loadInit(r,"low",!1),()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",r=!1){let i=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!r&&this.failedDownloads>0?Nr(this.destroyAbortController.signal,async function*(){let o=Ju(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,Vr(e.mime),i)).then(async o=>{if(!o)return;let{init:u,dataView:l,segments:c}=o,d=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,d);let p=c;this.isLive&&De(e.segmentReference)&&(p=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,p),u&&this.parsedInitData.set(e.id,u)}).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),r&&this.error$.next({id:"LoadInits",category:Xt.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n}async dropBuffer(){for(let e of this.segments.values())for(let t of e)t.status="none";await this.pruneBuffer(0,1/0,!0)}async pruneBuffer(e,t,r=!1){return this.tuning.useNewPruneBufferStrategy?this.pruneBufferNew(e,t,r):this.pruneBufferOld(e,t,r)}async pruneBufferNew(e,t,r=!1){if(!this.sourceBuffer||!this.playingRepresentationId||Oe(e)||this.sourceBuffer.updating)return!1;let i=[],s=0,n=u=>{u.sort((c,d)=>c.from-d.from);let l=[u[0]];for(let c=1;c<u.length;c++){let{from:d,to:p}=u[c],h=l[l.length-1];h.to>=d?h.to=Math.max(h.to,p):l.push(u[c])}return l},o=u=>{var c;if(s>=t)return i;i.push({...u.time}),i=n(i);let l=Us(u)?(c=u.size)!=null?c:0:u.byte.to-u.byte.from;s+=l};for(let u of this.segments.values())for(let l of u){let c=l.time.to<=e-this.tuning.dash.bufferPruningSafeZone,d=l.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(c||d)&&l.status==="fed"&&o(l)}for(let u=0;u<this.sourceBuffer.buffered.length;u++){let l=this.sourceBuffer.buffered.start(u)*1e3,c=this.sourceBuffer.buffered.end(u)*1e3,d=0;for(let p of this.segments.values())for(let h of p)["none","partially_ejected"].includes(h.status)&&Math.round(h.time.from)<=Math.round(l)&&Math.round(h.time.to)>=Math.round(c)&&d++;if(d===this.segments.size){let p={time:{from:l,to:c},url:"",status:"none"};o(p)}}if(i.length&&r){let u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let l of this.segments.values())for(let c of l)c.time.from>=e+u&&c.status==="fed"&&o(c)}return i.length?(await Promise.all(i.map(l=>this.sourceBufferTaskQueue.remove(l.from,l.to)))).reduce((l,c)=>l||c,!1):!1}async pruneBufferOld(e,t,r=!1){if(!this.sourceBuffer||!this.playingRepresentationId||Oe(e)||this.sourceBuffer.updating)return!1;let i=0,s=1/0,n=-1/0,o=!1,u=l=>{var d;s=Math.min(s,l.time.from),n=Math.max(n,l.time.to);let c=Us(l)?(d=l.size)!=null?d:0:l.byte.to-l.byte.from;i+=c};for(let l of this.segments.values())for(let c of l){if(c.time.to>=e-this.tuning.dash.bufferPruningSafeZone||i>=t)break;c.status==="fed"&&u(c)}if(o=isFinite(s)&&isFinite(n),!o){i=0,s=1/0,n=-1/0;for(let l of this.segments.values())for(let c of l){if(c.time.from<e+Math.min(this.forwardBufferTarget,this.bufferLimit)||i>t)break;c.status==="fed"&&u(c)}}if(o=isFinite(s)&&isFinite(n),!o)for(let l=0;l<this.sourceBuffer.buffered.length;l++){let c=this.sourceBuffer.buffered.start(l)*1e3,d=this.sourceBuffer.buffered.end(l)*1e3;for(let p of this.segments.values())for(let h of p)if(h.status==="none"&&Math.round(h.time.from)<=Math.round(c)&&Math.round(h.time.to)>=Math.round(d)){s=c,n=d;break}}if(o=isFinite(s)&&isFinite(n),!o&&r){i=0,s=1/0,n=-1/0;let l=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let c of this.segments.values())for(let d of c)d.time.from>e+l&&d.status==="fed"&&u(d)}return o=isFinite(s)&&isFinite(n),o?this.sourceBufferTaskQueue.remove(s,n):!1}abortBuffer(){if(!this.sourceBuffer||this.mediaSource.readyState!=="open")return;let e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;this.sourceBufferTaskQueue.abort(t)}getDebugBufferState(){if(!(!this.sourceBuffer||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}detectGaps(e,t){if(this.sourceBuffer)for(let r of t){let i={representation:e,from:r.time.from,to:r.time.to};for(let s=0;s<this.sourceBuffer.buffered.length;s++){let n=this.sourceBuffer.buffered.start(s)*1e3,o=this.sourceBuffer.buffered.end(s)*1e3;if(!(o<=r.time.from||n>=r.time.to)){if(n<=r.time.from&&o>=r.time.to){i=void 0;break}o>r.time.from&&o<r.time.to&&(i.from=o),n<r.time.to&&n>r.time.from&&(i.to=n)}}i&&i.to-i.from>1&&!this.gaps.some(s=>i&&s.from===i.from&&s.to===i.to)&&this.gaps.push(i)}}detectGapsWhenIdle(e,t){if(!this.gapDetectionIdleCallback){Be(this.sourceBuffer);for(let r=0;r<this.sourceBuffer.buffered.length;r++)this.gaps=this.gaps.filter(i=>this.sourceBuffer&&(Math.round(i.from)<Math.round(this.sourceBuffer.buffered.start(r)*1e3)||Math.round(i.to)>Math.round(this.sourceBuffer.buffered.end(r)*1e3)));this.gapDetectionIdleCallback=Cu(()=>{try{this.detectGaps(e,t)}catch(r){this.error$.next({id:"GapDetection",category:Xt.WTF,message:"detectGaps threw",thrown:r})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if(Oe(this.sourceBuffer)||Oe(this.playingRepresentationId))return;let e=[];for(let r=0;r<this.sourceBuffer.buffered.length;r++){let i=Math.floor(this.sourceBuffer.buffered.start(r)*1e3),s=Math.ceil(this.sourceBuffer.buffered.end(r)*1e3);e.push({from:i,to:s})}let t=100;for(let r of this.segments.values())for(let i of r){let{status:s}=i;if(s!=="fed"&&s!=="partially_ejected")continue;let n=Math.floor(i.time.from),o=Math.ceil(i.time.to),u=e.some(c=>c.from-t<=n&&c.to+t>=o),l=e.filter(c=>n>=c.from&&n<c.to-t||o>c.from+t&&o<=c.to);u||(l.length===1?i.status="partially_ejected":this.gaps.some(c=>c.from===i.time.from||c.to===i.time.to)?i.status="partially_ejected":i.status="none")}}};var ua=a=>{let e=new URL(a);return e.searchParams.set("quic","1"),e.toString()};var Yg=a=>{var s;let e=a.get("X-Delivery-Type"),t=a.get("X-Reused"),r=e===null?"http1":e!=null?e:void 0,i=t===null?void 0:(s={1:!0,0:!1}[t])!=null?s:void 0;return{type:r,reused:i}};import{abortable as la,assertNever as Qg,fromEvent as zg,merge as iR,now as ca,Subscription as aR,ValueSubject as Zu,flattenObject as qr}from"@vkontakte/videoplayer-shared";var Hs=class{constructor({throughputEstimator:e,requestQuic:t,tracer:r,compatibilityMode:i=!1}){this.lastConnectionType$=new Zu(void 0);this.lastConnectionReused$=new Zu(void 0);this.lastRequestFirstBytes$=new Zu(void 0);this.abortAllController=new ot;this.subscription=new aR;this.fetchManifest=la(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),r=e;this.requestQuic&&(r=ua(r));let i=yield nt(r,{signal:this.abortAllController.signal}).catch(da);return i?(t.log("success",qr({url:r,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(i.headers),i.text()):(t.error("error",qr({url:r,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=la(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:r,onProgress:i,priority:s="auto",signal:n,measureThroughput:o=!0,isLowLatency:u=!1}={}){var O,w;let l=e,c=new Headers,d=this.tracer.createComponentTracer("Fetch");if(r)switch(t){case 0:{c.append("Range",`bytes=${r.from}-${r.to}`);break}case 1:{let L=new URL(l,location.href);L.searchParams.append("bytes",`${r.from}-${r.to}`),l=L.toString();break}default:Qg(t)}this.requestQuic&&(l=ua(l));let p=this.abortAllController.signal,h;if(n){let L=new ot;if(h=iR(zg(this.abortAllController.signal,"abort"),zg(n,"abort")).subscribe(()=>{try{L.abort()}catch(q){da(q)}}),this.abortAllController.signal.aborted||n.aborted)try{L.abort()}catch(q){da(q)}p=L.signal}let f=ca();d.log("startRequest",qr({url:l,priority:s,rangeMethod:t,range:r,isLowLatency:u,requestStartedAt:f}));let b=yield nt(l,{priority:s,headers:c,signal:p}).catch(da),g=ca();if(!b)return d.error("error",{message:"No response in request"}),d.end(),h==null||h.unsubscribe(),null;if((O=this.throughputEstimator)==null||O.addRawRtt(g-f),!b.ok||!b.body){h==null||h.unsubscribe();let L=`Fetch error ${b.status}: ${b.statusText}`;return d.error("error",{message:L}),d.end(),Promise.reject(new Error(`Fetch error ${b.status}: ${b.statusText}`))}if(this.onHeadersReceived(b.headers),!i&&!o){h==null||h.unsubscribe();let L=ca(),q={requestStartedAt:f,requestEndedAt:L,duration:L-f};return d.log("endRequest",qr(q)),d.end(),b.arrayBuffer()}let[y,I]=b.body.tee(),S=y.getReader();o&&((w=this.throughputEstimator)==null||w.trackStream(I,u));let v=0,T=new Uint8Array(0),R=!1,U=L=>{h==null||h.unsubscribe(),R=!0,da(L)},$=la(p,async function*({done:L,value:q}){if(v===0&&this.lastRequestFirstBytes$.next(ca()-f),p.aborted){h==null||h.unsubscribe();return}if(!L&&q){let k=new Uint8Array(T.length+q.length);k.set(T),k.set(q,T.length),T=k,v+=q.byteLength,i==null||i(new DataView(T.buffer),v),yield S==null?void 0:S.read().then($,U)}}.bind(this));yield S==null?void 0:S.read().then($,U),h==null||h.unsubscribe();let B=ca(),N={failed:R,requestStartedAt:f,requestEndedAt:B,duration:B-f};return R?(d.error("endRequest",qr(N)),d.end(),null):(d.log("endRequest",qr(N)),d.end(),T.buffer)}.bind(this));this.fetchByteRangeRepresentation=la(this.abortAllController.signal,async function*(e,t,r){var y;if(e.type!=="byteRange")return null;let{from:i,to:s}=e.initRange,n=i,o=s,u=!1,l,c;e.indexRange&&(l=e.indexRange.from,c=e.indexRange.to,u=s+1===l,u&&(n=Math.min(l,i),o=Math.max(c,s))),n=Math.min(n,0);let d=yield this.fetch(e.url,{range:{from:n,to:o},priority:r,measureThroughput:!1});if(!d)return null;let p=new DataView(d,i-n,s-n+1);if(!t.validateData(p))throw new Error("Invalid media file");let h=t.parseInit(p),f=(y=e.indexRange)!=null?y:t.getIndexRange(h);if(!f)throw new ReferenceError("No way to load representation index");let b;if(u)b=new DataView(d,f.from-n,f.to-f.from+1);else{let I=yield this.fetch(e.url,{range:f,priority:r,measureThroughput:!1});if(!I)return null;b=new DataView(I)}let g=t.parseSegments(b,h,f);return{init:h,dataView:new DataView(d),segments:g}}.bind(this));this.fetchTemplateRepresentation=la(this.abortAllController.signal,async function*(e,t){if(e.type!=="template")return null;let r=new URL(e.initUrl,e.baseUrl).toString(),i=yield this.fetch(r,{priority:t,measureThroughput:!1});return i?{init:null,segments:e.segments.map(n=>({...n,status:"none",size:void 0})),dataView:new DataView(i)}:null}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=i,this.tracer=r.createComponentTracer("Fetcher")}onHeadersReceived(e){let{type:t,reused:r}=Yg(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(r)}async fetchRepresentation(e,t,r="auto"){var s,n;let{type:i}=e;switch(i){case"byteRange":return(s=await this.fetchByteRangeRepresentation(e,t,r))!=null?s:null;case"template":return(n=await this.fetchTemplateRepresentation(e,r))!=null?n:null;default:Qg(i)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}},da=a=>{if(!sa(a))throw a};var Zt=(a,e,t)=>t*e+(1-t)*a,el=(a,e)=>a.reduce((t,r)=>t+r,0)/e,Kg=(a,e,t,r)=>{let i=0,s=t,n=el(a,e),o=e<r?e:r;for(let u=0;u<o;u++)a[s]>n?i++:i--,s=(a.length+s-1)%a.length;return Math.abs(i)===o};import{isNullable as sR,ValueSubject as Jg}from"@vkontakte/videoplayer-shared";var Pt=class{constructor(e){this.prevReported=void 0;this.pastMeasures=[];this.takenMeasures=0;this.measuresCursor=0;var r;this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new Jg(e.initial),this.debounced$=new Jg(e.initial);let t=(r=e.label)!=null?r:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new ae(`raw_${t}`),this.smoothedSeries$=new ae(`smoothed_${t}`),this.reportedSeries$=new ae(`reported_${t}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,r=0;for(let o=0;o<this.pastMeasures.length;o++)this.pastMeasures[o]!==void 0&&(t+=(this.pastMeasures[o]-this.smoothed)**2,r++);this.takenMeasures=r,t/=r;let i=Math.sqrt(t),s=this.smoothed+this.params.deviationFactor*i,n=this.smoothed-this.params.deviationFactor*i;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(e),this.updateSmoothedValue(e),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),!(this.smoothed>s||this.smoothed<n)&&(sR(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 js=class extends Pt{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=Zt(this.slow,e,this.params.emaAlphaSlow),this.fast=Zt(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var Gs=class extends Pt{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=el(this.pastMeasures,this.takenMeasures);this.emaSmoothed=Zt(this.emaSmoothed,e,this.params.emaAlpha);let r=Kg(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=r?this.emaSmoothed:t}};var Ws=class extends Pt{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?Zt(this.smoothed,t,this.params.emaAlpha):t}};var er=class{static getSmoothedValue(e,t,r){return r.type==="TwoEma"?new js({initial:e,emaAlphaSlow:r.emaAlphaSlow,emaAlphaFast:r.emaAlphaFast,changeThreshold:r.changeThreshold,fastDirection:t,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"}):new Gs({initial:e,emaAlpha:r.emaAlpha,basisTrendChangeCount:r.basisTrendChangeCount,changeThreshold:r.changeThreshold,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"})}static getLiveEstimatedDelaySmoothedValue(e,t){return new Ws({initial:e,label:"liveEdgeDelay",...t})}};var tl=(a,e)=>{a&&a.playbackRate!==e&&(a.playbackRate=e)};import{isNullable as nR,ValueSubject as oR}from"@vkontakte/videoplayer-shared";var pa=class a{constructor(e,t){this.currentRepresentation$=new oR(null);this.currentSegment=null;this.getCurrentPosition=t.getCurrentPosition,this.processStreams(e)}updateLive(e){this.processStreams(e==null?void 0:e.streams.text)}seekLive(e){this.processStreams(e)}maintain(e=this.getCurrentPosition()){var t;if(!nR(e))for(let r of this.representations){let i=r.segmentReference.segments.find(s=>s.time.from<=e&&s.time.to>=e);if(!i||((t=this.currentSegment)==null?void 0:t.time.from)===i.time.from&&this.currentSegment.time.to===i.time.to)return;this.currentSegment=i,this.currentRepresentation$.next({...r,label:"Live Text",language:"ru",isAuto:!0,url:new URL(i.url,r.segmentReference.baseUrl).toString()})}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e!=null?e:[]){let r=a.filterRepresentations(t.representations);if(r){this.representations=r;break}}}static isSupported(e){return!!(e!=null&&e.some(t=>a.filterRepresentations(t.representations)))}static filterRepresentations(e){return e==null?void 0:e.filter(t=>t.kind==="text"&&"segmentReference"in t&&De(t.segmentReference))}};var iS=["timeupdate","progress","play","seeked","stalled","waiting"];var zs=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new rS;this.representationSubscription=new rS;this.state$=new M("none");this.currentVideoRepresentation$=new te(void 0);this.currentVideoRepresentationInit$=new te(void 0);this.currentAudioRepresentation$=new te(void 0);this.currentVideoSegmentLength$=new te(0);this.currentAudioSegmentLength$=new te(0);this.error$=new tS;this.lastConnectionType$=new te(void 0);this.lastConnectionReused$=new te(void 0);this.lastRequestFirstBytes$=new te(void 0);this.currentLiveTextRepresentation$=new te(null);this.isLive$=new te(!1);this.liveDuration$=new te(0);this.liveAvailabilityStartTime$=new te(void 0);this.bufferLength$=new te(0);this.liveLoadBufferLength$=new te(0);this.livePositionFromPlayer$=new te(0);this.timeInWaiting=0;this.isActiveLowLatency$=new te(!1);this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.liveLastSeekOffset=0;this.forceEnded$=new tS;this.gapWatchdogActive=!1;this.destroyController=new ot;this.initManifest=rl(this.destroyController.signal,async function*(e,t,r){var i;this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=ee(t,r,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),(i=this.manifest)!=null&&i.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:At.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=rl(this.destroyController.signal,async function*(){var n,o;this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(u=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:At.NETWORK,message:"Failed to load manifest",thrown:u})});if(!e)return null;let t=null;try{t=Ug(e!=null?e:"",this.manifestUrlString)}catch(u){let l=(n=ig(e))!=null?n:{id:"ManifestParsing",category:At.PARSER,message:"Failed to parse MPD manifest",thrown:u};this.error$.next(l)}if(!t)return null;let r=(u,l,c)=>{var d,p,h,f;return!!((p=(d=this.element)==null?void 0:d.canPlayType)!=null&&p.call(d,l)&&((f=(h=ut())==null?void 0:h.isTypeSupported)!=null&&f.call(h,`${l}; codecs="${c}"`))||u==="text")};t.dynamic&&this.isLive$.getValue()!==t.dynamic&&(this.isLive$.next(t.dynamic),this.liveDuration$.getValue()!==t.duration&&this.liveDuration$.next(-1*((o=t.duration)!=null?o:0)/1e3),this.liveAvailabilityStartTime$.getValue()!==t.liveAvailabilityStartTime&&this.liveAvailabilityStartTime$.next(t.liveAvailabilityStartTime));let i={text:t.streams.text,video:[],audio:[]};for(let u of["video","audio"]){let c=t.streams[u].filter(({mime:h,codecs:f})=>r(u,h,f)),d=new Set(c.map(({codecs:h})=>h)),p=rg(d);if(p&&(i[u]=c.filter(({codecs:h})=>h.startsWith(p))),u==="video"){let h=this.tuning.preferHDR,f=i.video.some(g=>g.hdr),b=i.video.some(g=>!g.hdr);pR.isHDR&&h&&f?i.video=i.video.filter(g=>g.hdr):b&&(i.video=i.video.filter(g=>!g.hdr))}}let s={...t,streams:i};return this.tracer.log("updateManifestEnd",ha(s)),s}.bind(this));this.initRepresentations=rl(this.destroyController.signal,async function*(e,t,r){var d;this.tracer.log("initRepresentationsStart",ha({initialVideo:e,initialAudio:t,sourceHls:r})),tr(this.manifest),tr(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let i=p=>{this.representationSubscription.add(Ur(p,"error").pipe(Qs(h=>{var f;return!!((f=this.element)!=null&&f.played.length)})).subscribe(h=>{this.error$.next({id:"VideoSource",category:At.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:h})}))};this.source=this.tuning.useManagedMediaSource?_b():new MediaSource;let s=document.createElement("source");if(i(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),this.tuning.useManagedMediaSource&&Ls())if(r){let p=document.createElement("source");i(p),p.type="application/x-mpegurl",p.src=r.url,this.element.appendChild(p)}else this.element.disableRemotePlayback=!0;this.isActiveLowLatency$.next(this.isLive$.getValue()&&this.tuning.dashCmafLive.lowLatency.isActive);let n={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLowLatency$.getValue(),manifest:this.manifest},o=this.manifest.streams.video.reduce((p,h)=>[...p,...h.representations],[]);if(this.videoBufferManager=new oa("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],eS(t)){let p=this.manifest.streams.audio.reduce((h,f)=>[...h,...f.representations],[]);this.audioBufferManager=new oa("audio",this.source,p,n),this.bufferManagers.push(this.audioBufferManager)}if(pa.isSupported(this.manifest.streams.text)&&!this.tuning.dashCmafLive.lowLatency.isActive&&(this.liveTextManager=new pa(this.manifest.streams.text,n)),this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$)),this.representationSubscription.add(il(1e3).subscribe(p=>{var h;if((h=this.element)!=null&&h.paused){let f=pu(this.manifestUrlString,2);this.manifestUrlString=ee(this.manifestUrlString,f+1e3,2)}})),this.representationSubscription.add(Hr(...iS.filter(p=>p!=="waiting").map(p=>Ur(this.element,p))).pipe(al(p=>this.element?st(this.element.buffered,this.element.currentTime*1e3):0),Zg(),Qs(p=>!!p),cR(p=>{var h;(h=this.stallWatchdogSubscription)==null||h.unsubscribe(),this.timeInWaiting=0})).subscribe(this.bufferLength$)),this.isLive$.getValue()){this.representationSubscription.add(this.isActiveLowLatency$.pipe(Zg()).subscribe(h=>tl(this.element,1))),this.representationSubscription.add(Ys({bufferLength:this.bufferLength$,isActiveLowLatency:this.isActiveLowLatency$}).pipe(Qs(({bufferLength:h,isActiveLowLatency:f})=>f&&!!h)).subscribe(({bufferLength:h})=>this.liveEstimatedDelay.next(h))),this.representationSubscription.add(Ys({liveEstimatedDelay:this.liveEstimatedDelay.smoothed$,isActiveLowLatency:this.isActiveLowLatency$}).subscribe(({liveEstimatedDelay:h,isActiveLowLatency:f})=>{if(!f)return;let b=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,g=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,y=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,I=h-b,S=1;Math.abs(I)>g&&(S=1+Math.sign(I)*y),tl(this.element,S)})),this.representationSubscription.add(this.bufferLength$.subscribe(h=>{var b,g;let f=0;if(h){let y=((g=(b=this.element)==null?void 0:b.currentTime)!=null?g:0)*1e3;f=Math.min(...this.bufferManagers.map(S=>{var v,T;return(T=(v=S.getLiveSegmentsToLoadState(this.manifest))==null?void 0:v.to)!=null?T:y}))-y}this.liveLoadBufferLength$.getValue()!==f&&this.liveLoadBufferLength$.next(f)}));let p=0;this.representationSubscription.add(Ys({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(dR(1e3)).subscribe(async({liveLoadBufferLength:h,bufferLength:f})=>{if(tr(this.element),this.isUpdatingLive)return;let b=this.element.playbackRate,g=pu(this.manifestUrlString,2),y=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,I=Math.min(y,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*b),S=this.tuning.dashCmafLive.normalizedActualBufferOffset*b,v=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*b,T=isFinite(h)?h:f,R=this.isActiveLowLatency$.getValue(),U=y<=this.tuning.live.activeLiveDelay&&g===0;this.isActiveLowLatency$.next(R&&U);let $="none";if(R?$="active_low_latency":this.tuning.dashCmafLive.lowLatency.isActive&&U?(this.isActiveLowLatency$.next(!0),this.bufferManagers.forEach(B=>B.proceedLowLatencyLive()),$="active_low_latency"):g!==0&&T<I?$="live_forward_buffering":T<I+v&&($="live_with_target_offset"),isFinite(h)&&(p=h>p?h:p),$==="live_forward_buffering"||$==="live_with_target_offset"){let B=p-(I+S),N=this.normolizeLiveOffset(Math.trunc(g+B/b)),O=Math.abs(N-g),w;!h||O<=this.tuning.dashCmafLive.offsetCalculationError?w=g:N>0&&O>this.tuning.dashCmafLive.offsetCalculationError?w=N:w=0,this.manifestUrlString=ee(this.manifestUrlString,w,2)}$!=="none"&&$!=="active_low_latency"&&(p=0,this.updateLive())}))}let u=Hr(...this.bufferManagers.map(p=>p.fullyBuffered$)).pipe(al(()=>this.bufferManagers.every(p=>p.fullyBuffered$.getValue()))),l=Hr(...this.bufferManagers.map(p=>p.onLastSegment$)).pipe(al(()=>this.bufferManagers.some(p=>p.onLastSegment$.getValue())));this.representationSubscription.add(Hr(this.forceEnded$,Ys({allBuffersFull:u,someBufferEnded:l}).pipe(Qs(({allBuffersFull:p,someBufferEnded:h})=>p&&h))).subscribe(()=>{var p;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(h=>!h.updating))try{(p=this.source)==null||p.endOfStream()}catch(h){this.error$.next({id:"EndOfStream",category:At.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:h})}})),this.representationSubscription.add(Hr(...this.bufferManagers.map(p=>p.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.subscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.subscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&(this.representationSubscription.add(this.audioBufferManager.playingRepresentation$.subscribe(this.currentAudioRepresentation$)),this.subscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$))),this.liveTextManager&&this.subscription.add(this.liveTextManager.currentRepresentation$.subscribe(this.currentLiveTextRepresentation$)),this.source.readyState!=="open"&&(yield new Promise(p=>{var h;return(h=this.source)==null?void 0:h.addEventListener("sourceopen",p)}));let c=[(d=this.manifest.duration)!=null?d:0,...[...this.manifest.streams.audio,...this.manifest.streams.video].flatMap(p=>p.representations).flatMap(p=>{let h=[];return p.duration&&h.push(p.duration),De(p.segmentReference)&&p.segmentReference.totalSegmentsDurationMs&&h.push(p.segmentReference.totalSegmentsDurationMs),h})];this.source.duration=Math.max(...c)/1e3,this.audioBufferManager&&eS(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState("representations_ready"),this.tracer.log("initRepresentationsEnd")}.bind(this));this.tick=()=>{var t,r,i;if(!this.element||!this.videoBufferManager)return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),(t=this.audioBufferManager)==null||t.maintain(e),(r=this.liveTextManager)==null||r.maintain(e),(this.videoBufferManager.gaps.length||(i=this.audioBufferManager)!=null&&i.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=il(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),s=>{this.error$.next({id:"GapWatchdog",category:At.WTF,message:"Error handling gaps",thrown:s})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name),this.fetcher=new Hs({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer}),this.liveEstimatedDelay=er.getLiveEstimatedDelaySmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.delayEstimator}),this.initTracerSubscription()}async seekLive(e){var r,i,s;tr(this.element);let t=this.normolizeLiveOffset(e);this.isActiveLowLatency$.next(this.tuning.dashCmafLive.lowLatency.isActive&&t===0),this.liveLastSeekOffset=t,this.manifestUrlString=ee(this.manifestUrlString,t,2),this.manifest=await this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,await((r=this.videoBufferManager)==null?void 0:r.seekLive(this.manifest.streams.video)),await((i=this.audioBufferManager)==null?void 0:i.seekLive(this.manifest.streams.audio)),(s=this.liveTextManager)==null||s.seekLive(this.manifest.streams.text))}initBuffer(){tr(this.element),this.state$.setState("running"),this.subscription.add(Hr(...iS.map(e=>Ur(this.element,e)),Ur(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:At.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(Ur(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(Ur(this.element,"waiting").subscribe(()=>{var t,r,i;this.element&&this.element.readyState===2&&!this.element.seeking&&Dr(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{var n,o;if(!this.element)return;this.timeInWaiting+=1e3;let s={timeInWaiting:this.timeInWaiting};if(this.timeInWaiting>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${this.tuning.dash.crashOnStallTimeout} ms`);if(this.isLive$.getValue()&&this.timeInWaiting%5e3===0)this.seekLive(this.liveLastSeekOffset),s={...s,liveLastSeekOffset:this.liveLastSeekOffset};else{let u=this.element.currentTime*1e3;(n=this.videoBufferManager)==null||n.maintain(u),(o=this.audioBufferManager)==null||o.maintain(u),s={...s,position:u}}this.tracer.log("stallIntervalCallback",ha(s))};(t=this.videoBufferManager)==null||t.startAccumulateBuffer(),(r=this.audioBufferManager)==null||r.startAccumulateBuffer(),(i=this.stallWatchdogSubscription)==null||i.unsubscribe(),this.stallWatchdogSubscription=il(1e3).subscribe(e,s=>{this.error$.next({id:"StallWatchdogCallback",category:At.FATAL,message:"Can't restore DASH after stall.",thrown:s})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t,r=!1){let i={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return i==null?void 0:i.switchTo(t,r)}seek(e,t){var i,s,n,o,u,l;tr(this.element),tr(this.videoBufferManager);let r;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?r=e:r=Math.max((i=this.videoBufferManager.findSegmentStartTime(e))!=null?i:e,(n=(s=this.audioBufferManager)==null?void 0:s.findSegmentStartTime(e))!=null?n:e),Dr(this.element.buffered,r)||(this.videoBufferManager.abort(),(o=this.audioBufferManager)==null||o.abort()),this.videoBufferManager.startAccumulateBuffer(),this.videoBufferManager.maintain(r),(u=this.audioBufferManager)==null||u.startAccumulateBuffer(),(l=this.audioBufferManager)==null||l.maintain(r),this.element.currentTime=r/1e3,this.tracer.log("seek",ha({requestedPosition:e,forcePrecise:t,position:r}))}stop(){var e,t,r;this.tracer.log("stop"),(e=this.element)==null||e.querySelectorAll("source").forEach(i=>i.remove()),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),(t=this.videoBufferManager)==null||t.destroy(),this.videoBufferManager=null,(r=this.audioBufferManager)==null||r.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getStreams(){var e;return(e=this.manifest)==null?void 0:e.streams}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){var e;this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),((e=this.source)==null?void 0:e.readyState)==="open"&&Array.from(this.source.sourceBuffers).every(t=>!t.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}initTracerSubscription(){let e=hR(this.tracer.error.bind(this.tracer));this.error$.subscribe(e("error"))}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}async updateLive(){var e,t;this.isUpdatingLive=!0,this.manifest=await this.updateManifest(),this.manifest&&((e=this.bufferManagers)==null||e.forEach(r=>r.updateLive(this.manifest)),(t=this.liveTextManager)==null||t.updateLive(this.manifest)),this.isUpdatingLive=!1}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.getDebugBufferState();if(!e)return;let t={isJumpGapAfterSeekLive:this.isJumpGapAfterSeekLive,isActiveLowLatency:this.isActiveLowLatency$.getValue(),initialCurrentTime:this.element.currentTime};this.isJumpGapAfterSeekLive&&!this.isActiveLowLatency$.getValue()&&this.element.currentTime>e.to&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let r=this.element.currentTime*1e3,i=[],s=this.element.readyState===1?this.tuning.endGapTolerance:0;for(let n of this.bufferManagers)for(let o of n.gaps)n.playingRepresentation$.getValue()===o.representation&&o.from-s<=r&&o.to+s>r&&(this.element.duration*1e3-o.to<this.tuning.endGapTolerance?i.push(1/0):i.push(o.to));if(i.length){let n=Math.max(...i)+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,n===1/0?this.forceEnded$.next():(this.element.currentTime=n/1e3,t={...t,gapEnds:i,jumpTo:n,resultCurrentTime:this.element.currentTime},this.tracer.log("jumpGap",ha(t)))}}};var Ks=class{constructor(e,t){this.fov=e,this.orientation=t}};var Js=class{constructor(e,t){this.rotating=!1;this.fading=!1;this.lastTickTS=0;this.lastCameraTurnTS=0;this.fadeStartSpeed=null;this.fadeTime=0;this.camera=e,this.options=t,this.rotationSpeed={x:0,y:0,z:0},this.fadeCorrection=1/(this.options.speedFadeTime/1e3)**2}turnCamera(e=0,t=0,r=0){this.pointCameraTo(this.camera.orientation.x+e,this.camera.orientation.y+t,this.camera.orientation.z+r)}pointCameraTo(e=0,t=0,r=0){t=this.limitCameraRotationY(t);let i=e-this.camera.orientation.x,s=t-this.camera.orientation.y,n=r-this.camera.orientation.z;this.camera.orientation.x=e,this.camera.orientation.y=t,this.camera.orientation.z=r,this.lastCameraTurn={x:i,y:s,z:n},this.lastCameraTurnTS=Date.now()}setRotationSpeed(e,t,r){this.rotationSpeed.x=e!=null?e:this.rotationSpeed.x,this.rotationSpeed.y=t!=null?t:this.rotationSpeed.y,this.rotationSpeed.z=r!=null?r:this.rotationSpeed.z}startRotation(){this.rotating=!0}stopRotation(e=!1){e?(this.setRotationSpeed(0,0,0),this.fadeStartSpeed=null):this.startFading(this.rotationSpeed.x,this.rotationSpeed.y,this.rotationSpeed.z),this.rotating=!1}onCameraRelease(){if(this.lastCameraTurn&&this.lastCameraTurnTS){let e=Date.now()-this.lastCameraTurnTS;if(e<this.options.speedFadeThreshold){let t=(1-e/this.options.speedFadeThreshold)*this.options.rotationSpeedCorrection;this.startFading(this.lastCameraTurn.x*t,this.lastCameraTurn.y*t,this.lastCameraTurn.z*t)}}}startFading(e,t,r){this.setRotationSpeed(e,t,r),this.fadeStartSpeed={...this.rotationSpeed},this.fading=!0}stopFading(){this.fadeStartSpeed=null,this.fading=!0,this.fadeTime=0}limitCameraRotationY(e){return Math.max(-this.options.maxYawAngle,Math.min(e,this.options.maxYawAngle))}tick(e){if(!this.lastTickTS){this.lastTickTS=e,this.lastCameraTurnTS=Date.now();return}let t=e-this.lastTickTS,r=t/1e3;if(this.rotating)this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*r,this.rotationSpeed.y*this.options.rotationSpeedCorrection*r,this.rotationSpeed.z*this.options.rotationSpeedCorrection*r);else if(this.fading&&this.fadeStartSpeed){let i=-this.fadeCorrection*(this.fadeTime/1e3)**2+1;this.setRotationSpeed(this.fadeStartSpeed.x*i,this.fadeStartSpeed.y*i,this.fadeStartSpeed.z*i),i>0?this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*r,this.rotationSpeed.y*this.options.rotationSpeedCorrection*r,this.rotationSpeed.z*this.options.rotationSpeedCorrection*r):(this.stopRotation(!0),this.stopFading()),this.fadeTime=Math.min(this.fadeTime+t,this.options.speedFadeTime)}this.lastTickTS=e}};var aS=`attribute vec2 a_vertex;
|
|
59
59
|
attribute vec2 a_texel;
|
|
60
60
|
|
|
61
61
|
varying vec2 v_texel;
|
|
@@ -66,7 +66,7 @@ void main(void) {
|
|
|
66
66
|
// save texel vector to pass to fragment shader
|
|
67
67
|
v_texel = a_texel;
|
|
68
68
|
}
|
|
69
|
-
`;var
|
|
69
|
+
`;var sS=`#ifdef GL_ES
|
|
70
70
|
precision highp float;
|
|
71
71
|
precision highp int;
|
|
72
72
|
#else
|
|
@@ -109,5 +109,5 @@ void main(void) {
|
|
|
109
109
|
// sample using new coordinates
|
|
110
110
|
gl_FragColor = texture2D(u_texture, tc);
|
|
111
111
|
}
|
|
112
|
-
`;var Bs=class{constructor(e,t,r){this.videoInitialized=!1;this.active=!1;this.container=e,this.sourceVideoElement=t,this.params=r,this.canvas=this.createCanvas();let i=this.canvas.getContext("webgl");if(!i)throw new Error("Could not initialize WebGL context");this.gl=i,this.container.appendChild(this.canvas),this.camera=new Cs(this.params.fov,this.params.orientation),this.cameraRotationManager=new Ds(this.camera,{rotationSpeed:this.params.rotationSpeed,maxYawAngle:this.params.maxYawAngle,rotationSpeedCorrection:this.params.rotationSpeedCorrection,degreeToPixelCorrection:this.params.degreeToPixelCorrection,speedFadeTime:this.params.speedFadeTime,speedFadeThreshold:this.params.speedFadeThreshold}),this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.textureMappingBuffer=this.createTextureMappingBuffer(),this.updateTextureMappingBuffer(),this.program=this.createProgram(),this.videoTexture=this.createTexture(),this.gl.useProgram(this.program),this.videoElementDataLoadedFn=this.onDataLoadedHandler.bind(this),this.renderFn=this.render.bind(this)}play(){this.active||(this.videoInitialized?this.doPlay():this.sourceVideoElement.readyState>=2?(this.videoInitialized=!0,this.doPlay()):this.sourceVideoElement.addEventListener("loadeddata",this.videoElementDataLoadedFn))}stop(){this.active=!1}startCameraManualRotation(e,t){this.cameraRotationManager.setRotationSpeed(e*this.params.rotationSpeed,t*this.params.rotationSpeed,0),this.cameraRotationManager.startRotation()}stopCameraManualRotation(e=!1){this.cameraRotationManager.stopRotation(e)}turnCamera(e,t){this.cameraRotationManager.turnCamera(e,t)}pointCameraTo(e,t){this.cameraRotationManager.pointCameraTo(e,t)}pixelToDegree(e){return{x:this.params.degreeToPixelCorrection*this.params.fov.x*-e.x/this.viewportWidth,y:this.params.degreeToPixelCorrection*this.params.fov.y*e.y/this.viewportHeight}}getCameraRotation(){return this.camera.orientation}holdCamera(){this.cameraRotationManager.stopRotation(!0)}releaseCamera(){this.cameraRotationManager.onCameraRelease()}destroy(){this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),this.stop(),this.canvas.remove()}setViewportSize(e,t){this.viewportWidth=e,this.viewportHeight=t,this.canvas.width=this.viewportWidth,this.canvas.height=this.viewportHeight,this.gl.viewport(0,0,this.canvas.width,this.canvas.height)}onDataLoadedHandler(){this.videoInitialized=!0,this.doPlay()}doPlay(){this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.active=!0,this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),requestAnimationFrame(this.renderFn)}render(e){this.cameraRotationManager.tick(e),this.updateTexture(),this.updateTextureMappingBuffer();let t=this.gl.getAttribLocation(this.program,"a_vertex"),r=this.gl.getAttribLocation(this.program,"a_texel"),i=this.gl.getUniformLocation(this.program,"u_texture"),s=this.gl.getUniformLocation(this.program,"u_focus");this.gl.enableVertexAttribArray(t),this.gl.enableVertexAttribArray(r),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.vertexBuffer),this.gl.vertexAttribPointer(t,2,this.gl.FLOAT,!1,0,0),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.vertexAttribPointer(r,2,this.gl.FLOAT,!1,0,0),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.uniform1i(i,0),this.gl.uniform2f(s,-this.camera.orientation.x,-this.camera.orientation.y),this.gl.drawArrays(this.gl.TRIANGLE_FAN,0,4),this.gl.bindTexture(this.gl.TEXTURE_2D,null),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),this.gl.disableVertexAttribArray(t),this.gl.disableVertexAttribArray(r),this.active&&requestAnimationFrame(this.renderFn)}createShader(e,t){let r=this.gl.createShader(t);if(!r)throw this.destroy(),new Error(`Could not create shader (${t})`);if(this.gl.shaderSource(r,e),this.gl.compileShader(r),!this.gl.getShaderParameter(r,this.gl.COMPILE_STATUS))throw this.destroy(),new Error("An error occurred while compiling the shader: "+this.gl.getShaderInfoLog(r));return r}createProgram(){let e=this.gl.createProgram();if(!e)throw this.destroy(),new Error("Could not create shader program");let t=this.createShader(Ng,this.gl.VERTEX_SHADER),r=this.createShader(Fg,this.gl.FRAGMENT_SHADER);if(this.gl.attachShader(e,t),this.gl.attachShader(e,r),this.gl.linkProgram(e),!this.gl.getProgramParameter(e,this.gl.LINK_STATUS))throw this.destroy(),new Error("Could not link shader program.");return e}createTexture(){let e=this.gl.createTexture();if(!e)throw this.destroy(),new Error("Could not create texture");return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.bindTexture(this.gl.TEXTURE_2D,null),e}updateTexture(){this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,!0),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.sourceVideoElement),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}createVertexBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create vertex buffer");let t=1,r=1,i=this.frameHeight/(this.frameWidth/this.viewportWidth);return i>this.viewportHeight?t=this.viewportHeight/i:r=i/this.viewportHeight,this.gl.bindBuffer(this.gl.ARRAY_BUFFER,e),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-t,-r,t,-r,t,r,-t,r]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),e}createTextureMappingBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create texture mapping buffer");return e}calculateTexturePosition(){let e=.5-this.camera.orientation.x/360,t=.5-this.camera.orientation.y/180,r=this.camera.fov.x/360/2,i=this.camera.fov.y/180/2,s=e-r,n=t-i,o=e+r,u=t-i,c=e+r,l=t+i,d=e-r,p=t+i;return[s,n,o,u,c,l,d,p]}updateTextureMappingBuffer(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([...this.calculateTexturePosition()]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}updateFrameSize(){this.frameWidth=this.sourceVideoElement.videoWidth,this.frameHeight=this.sourceVideoElement.videoHeight}createCanvas(){let e=document.createElement("canvas");return e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e}};var zt=class{constructor(e){this.subscription=new pR;this.videoState=new M("stopped");this.elementSize$=new hR(void 0);this.textTracksManager=new Re;this.droppedFramesManager=new ls;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new bi;this.audioTrackSwitchHistory=new bi;this.textTracks=[];this.syncPlayback=()=>{var n,o,u;let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),i=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(i.state==="requested"&&(r==null?void 0:r.to)!=="paused"&&e!=="stopped"&&t!=="stopped"){let c=(o=(n=this.liveOffset)==null?void 0:n.getTotalPausedTime())!=null?o:0;this.seek(i.position-c,i.forcePrecise)}if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.player.stop(),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),E(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"),E(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="ready"&&E(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),(u=this.liveOffset)==null||u.pause(),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(r==null?void 0:r.to)==="playing"&&E(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.liveOffset?this.liveOffset.getTotalOffset()/1e3<Math.abs(this.params.output.duration$.getValue())?(this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(0,!1):this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&E(this.params.desiredState.playbackState,"paused");return;default:return sR(e)}}};this.init3DScene=e=>{var r,i,s;if(this.scene3D)return;this.scene3D=new Bs(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:((r=e.projectionData)==null?void 0:r.pose.yaw)||0,y:((i=e.projectionData)==null?void 0:i.pose.pitch)||0,z:((s=e.projectionData)==null?void 0:s.pose.roll)||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});let t=this.elementSize$.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};this.params=e,this.video=le(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(X(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new Ms({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode,tracer:this.tracer}),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params,r=he(this.video),i=this.constructor.name,s=o=>{e.error$.next({id:i,category:Wu.WTF,message:`${i} internal logic error`,thrown:o})};return{output:e,desiredState:t,observableVideo:r,genericErrorListener:s,connect:(o,u)=>this.subscription.add(o.subscribe(u,s))}}subscribe(){let{output:e,desiredState:t,observableVideo:r,genericErrorListener:i,connect:s}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe(qg(c=>!!c.length),Hg()).subscribe(c=>{this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:r.playing$,pause$:r.pause$,tracks:c})})),s(r.ended$,e.endedEvent$),s(r.looped$,e.loopedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentBuffer$),s(r.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),s(r.loadedMetadata$,e.loadedMetadataEvent$),s(this.player.error$,e.error$),s(this.player.lastConnectionType$,e.httpConnectionType$),s(this.player.lastConnectionReused$,e.httpConnectionReused$),s(this.player.isLive$,e.isLive$),s(this.player.lastRequestFirstBytes$.pipe(qg(cR),Hg()),e.firstBytesEvent$),s(this.videoState.stateChangeEnded$.pipe(Ug(c=>c.to)),this.params.output.playbackState$),this.subscription.add(r.seeked$.subscribe(e.seekedEvent$,i)),this.subscription.add(Ge(this.video,t.isLooped,i)),this.subscription.add(pe(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(ke(this.video,t.playbackRate,r.playbackRateState$,i)),s(dR(this.video),this.elementSize$),s(Le(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),E(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),E(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:c})=>{if(c==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let l=this.player.getStreams();if(nR(l,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let p=[];for(let h of l.audio){p.push(Bu(h));let f=[];for(let b of h.representations){let g=Pg(b);f.push(g),this.audioTracksMap.set(g,{stream:h,representation:b})}this.audioStreamsMap.set(h,f)}this.params.output.availableAudioStreams$.next(p)}let d=[];for(let p of l.video){d.push(Ou(p));let h=[];for(let f of p.representations){let b=xg(f);b&&(h.push(b),this.videoTracksMap.set(b,{stream:p,representation:f}))}this.videoStreamsMap.set(p,h)}this.params.output.availableVideoStreams$.next(d);for(let p of l.text)for(let h of p.representations){let f=Ag(p,h);this.textTracksMap.set(f,{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>0&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else c==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},i));let n=c=>e.error$.next({id:"RepresentationSwitch",category:Wu.WTF,message:"Switching representations threw",thrown:c});this.subscription.add(Os(this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,t.videoStream.stateChangeStarted$,t.audioStream.stateChangeStarted$,this.elementSize$,this.params.output.elementVisible$,this.droppedFramesManager.onDroopedVideoFramesLimit$,uR(this.video,"progress")).subscribe(()=>{let c=this.player.state$.getState(),l=this.player.state$.getTransition();if(!["manifest_ready","running"].includes(c)||l)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let d=this.selectVideoAudioRepresentations();if(!d)return;let[p,h]=d,f=this.params.desiredState.autoVideoTrackLimits.getTransition();if(f&&this.params.output.autoVideoTrackLimits$.next(f.to),c==="manifest_ready")this.player.initRepresentations(p.id,h==null?void 0:h.id,this.params.sourceHls);else if(this.player.switchRepresentation("video",p.id).catch(n),h){let b=!!t.audioStream.getTransition();this.player.switchRepresentation("audio",h.id,b).catch(n)}},i)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:c})=>{this.scene3D&&c&&this.scene3D.pointCameraTo(c.x,c.y)})),this.subscription.add(this.elementSize$.subscribe(c=>{this.scene3D&&c&&this.scene3D.setViewportSize(c.width,c.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(Yu()).subscribe(c=>{let l=[...this.videoTracksMap.entries()].find(([,{representation:f}])=>f.id===c);if(!l){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[d,{stream:p}]=l,h=this.params.desiredState.videoStream.getTransition();h&&h.to&&h.to.id===p.id&&this.params.desiredState.videoStream.setState(h.to),e.currentVideoTrack$.next(d),e.currentVideoStream$.next(Ou(p))},i)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(Yu()).subscribe(c=>{let l=[...this.audioTracksMap.entries()].find(([,{representation:f}])=>f.id===c);if(!l){e.currentAudioStream$.next(void 0);return}let[d,{stream:p}]=l,h=this.params.desiredState.audioStream.getTransition();h&&h.to&&h.to.id===p.id&&this.params.desiredState.audioStream.setState(h.to),e.currentAudioStream$.next(Bu(p))},i)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(c=>{var l,d;if(c!=null&&c.is3dVideo&&((l=this.params.tuning.spherical)!=null&&l.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(),(d=this.params.tuning.spherical)!=null&&d.enabled&&e.is3DVideo$.next(!1)},i)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,i)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,i)),this.textTracksManager.connect(this.video,t,e);let o=t.playbackState.stateChangeStarted$.pipe(Ug(({to:c})=>c==="ready"),Yu());this.subscription.add(Os(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$).subscribe(()=>{let c=t.autoVideoTrackSwitching.getState(),d=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:c?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(d)})),this.subscription.add(Os(o,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let u=Os(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,lR(["init"])).pipe(oR(0));this.subscription.add(u.subscribe(this.syncPlayback,i))}selectVideoAudioRepresentations(){var R,U,$,B,N,O,w,L,q,k,x,V,H,G,z,se,Et,nt;let{desiredState:e,output:t}=this.params,r=e.autoVideoTrackSwitching.getState(),i=(R=e.videoTrack.getState())==null?void 0:R.id,n=[...this.videoTracksMap.keys()].find(({id:A})=>A===i),o=t.currentVideoTrack$.getValue(),u=((B=($=e.videoStream.getState())!=null?$:n&&((U=this.videoTracksMap.get(n))==null?void 0:U.stream))!=null?B:this.videoStreamsMap.size===1)?this.videoStreamsMap.keys().next().value:void 0;if(!u)return;let c=[...this.videoStreamsMap.keys()].find(({id:A})=>A===u.id),l=c&&this.videoStreamsMap.get(c);if(!l)return;let d=Ze(this.video.buffered,this.video.currentTime*1e3),p=r?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,h=Math.min(d/Math.min(p,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),f=(N=e.audioStream.getState())!=null?N:this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0,b=(O=[...this.audioStreamsMap.keys()].find(({id:A})=>A===(f==null?void 0:f.id)))!=null?O:this.audioStreamsMap.keys().next().value,g=0;if(b){if(n&&!r)if(this.params.tuning.useSeparateAudioVideoABR){let A=ns(n,l,(w=this.audioStreamsMap.get(b))!=null?w:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);g=Math.max(g,(L=A==null?void 0:A.bitrate)!=null?L:-1/0)}else{let A=xs(n,l,(q=this.audioStreamsMap.get(b))!=null?q:[]);g=Math.max(g,(k=A==null?void 0:A.bitrate)!=null?k:-1/0)}if(o)if(this.params.tuning.useSeparateAudioVideoABR){let A=ns(o,l,(x=this.audioStreamsMap.get(b))!=null?x:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);g=Math.max(g,(V=A==null?void 0:A.bitrate)!=null?V:-1/0)}else{let A=xs(o,l,(H=this.audioStreamsMap.get(b))!=null?H:[]);g=Math.max(g,(G=A==null?void 0:A.bitrate)!=null?G:-1/0)}}let y=bt(l,{container:this.elementSize$.getValue(),throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:g,forwardBufferHealth:h,current:o,visible:this.params.output.elementVisible$.getValue(),history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),I=r?y!=null?y:n:n!=null?n:y,S;this.params.tuning.useSeparateAudioVideoABR?S=b&&ab(I,l,(z=this.audioStreamsMap.get(b))!=null?z:[],{throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:h,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}):S=b&&xs(I,l,(se=this.audioStreamsMap.get(b))!=null?se:[]);let v=(Et=this.videoTracksMap.get(I))==null?void 0:Et.representation,T=S&&((nt=this.audioTracksMap.get(S))==null?void 0:nt.representation);if(v&&T)return[v,T];if(v&&!T&&this.audioTracksMap.size===0)return[v,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){me(this.video).then(e=>{var t;e||((t=this.liveOffset)==null||t.pause(),this.videoState.setState("paused"),E(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Wu.DOM,thrown:e}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.destroy3DScene(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),de(this.video),this.tracer.end()}};var ra=class extends zt{subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:r}=this.getProviderSubscriptionInfo();r(t.timeUpdate$,e.position$),r(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}};import{combine as jg,interval as fR,map as mR}from"@vkontakte/videoplayer-shared";var ia=class extends zt{constructor(e){super(e),this.liveOffset=new Je}subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:r}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),r(t.timeUpdate$,e.liveBufferTime$),r(this.player.liveDuration$,e.duration$),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(jg({interval:fR(1e3),playbackRate:t.playbackRateState$}).subscribe(({playbackRate:i})=>{var s;if(this.videoState.getState()==="playing"){let n=e.position$.getValue()+(i-1);n<=0&&e.position$.next(n),(s=this.liveOffset)==null||s.resetTo(-n*1e3)}})).add(jg({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(mR(({liveBufferTime:i,liveAvailabilityStartTime:s})=>i&&s?i+s:void 0)).subscribe(e.liveTime$))}seek(e){this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),r=this.videoState.getState(),i=t==="paused"&&r==="paused",s=-e,n=Math.trunc(s/1e3<=Math.abs(this.params.output.duration$.getValue())?s:0);this.player.seekLive(n).then(()=>{var o;this.params.output.position$.next(e/1e3),(o=this.liveOffset)==null||o.resetTo(n,i)})}};var Wg=He(is(),1);import{assertNever as aa,assertNonNullable as Gg,debounce as bR,ErrorCategory as Vs,filter as gR,isNonNullable as SR,isNullable as vR,map as _s,merge as yR,Observable as TR,observableFrom as IR,Subscription as ER,videoSizeToQuality as xR}from"@vkontakte/videoplayer-shared";var qe={};var Dr=(a,e)=>new TR(t=>{let r=(i,s)=>t.next(s);return a.on(e,r),()=>a.off(e,r)}),sa=class{constructor(e){this.subscription=new ER;this.videoState=new M("initializing");this.textTracksManager=new Re;this.trackLevels=new Map;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),i=this.params.desiredState.seekState.getState();if(e!=="initializing")switch((r==null?void 0:r.to)!=="paused"&&i.state==="requested"&&this.seek(i.position),t){case"stopped":switch(e){case"stopped":break;case"ready":case"playing":case"paused":this.stop();break;default:aa(e)}break;case"ready":switch(e){case"stopped":this.prepare();break;case"ready":case"playing":case"paused":break;default:aa(e)}break;case"playing":switch(e){case"playing":break;case"stopped":this.prepare();break;case"ready":case"paused":this.playIfAllowed();break;default:aa(e)}break;case"paused":switch(e){case"paused":break;case"stopped":this.prepare();break;case"ready":this.videoState.setState("paused"),E(this.params.desiredState.playbackState,"paused");break;case"playing":this.pause();break;default:aa(e)}break;default:aa(t)}};this.video=le(e.container,e.tuning),this.params=e,this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(X(this.params.source.url)),this.loadHlsJs()}destroy(){var e,t;this.subscription.unsubscribe(),this.trackLevels.clear(),this.textTracksManager.destroy(),(e=this.hls)==null||e.detachMedia(),(t=this.hls)==null||t.destroy(),this.params.output.element$.next(void 0),de(this.video)}loadHlsJs(){let e=!1,t=i=>{e||this.params.output.error$.next({id:i==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:Vs.NETWORK,message:"Failed to load Hls.js",thrown:i}),e=!0},r=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);(0,Wg.default)(import("hls.js").then(i=>{e||(qe.Hls=i.default,qe.Events=i.default.Events,this.init())},t),()=>{window.clearTimeout(r),e=!0})}init(){Gg(qe.Hls,"hls.js not loaded"),this.hls=new qe.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState("stopped")}subscribe(){Gg(qe.Events,"hls.js not loaded");let{desiredState:e,output:t}=this.params,r=c=>{t.error$.next({id:"HlsJsProvider",category:Vs.WTF,message:"HlsJsProvider internal logic error",thrown:c})},i=he(this.video),s=(c,l)=>this.subscription.add(c.subscribe(l,r));s(i.timeUpdate$,t.position$),s(i.durationChange$,t.duration$),s(i.ended$,t.endedEvent$),s(i.looped$,t.loopedEvent$),s(i.error$,t.error$),s(i.isBuffering$,t.isBuffering$),s(i.currentBuffer$,t.currentBuffer$),s(i.loadStart$,t.firstBytesEvent$),s(i.loadedMetadata$,t.loadedMetadataEvent$),s(i.playing$,t.firstFrameEvent$),s(i.canplay$,t.canplay$),s(i.seeked$,t.seekedEvent$),s(i.inPiP$,t.inPiP$),s(i.inFullscreen$,t.inFullscreen$),this.subscription.add(Ge(this.video,e.isLooped,r)),this.subscription.add(pe(this.video,e.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(ke(this.video,e.playbackRate,i.playbackRateState$,r)),s(Le(this.video),t.elementVisible$),s(this.videoState.stateChangeEnded$.pipe(_s(c=>c.to)),this.params.output.playbackState$),this.subscription.add(Dr(this.hls,qe.Events.ERROR).subscribe(c=>{var l;c.fatal&&t.error$.next({id:["HlsJsFatal",c.type,c.details].join("_"),category:Vs.WTF,message:`HlsJs fatal ${c.type} ${c.details}, ${(l=c.err)==null?void 0:l.message} ${c.reason}`,thrown:c.error})})),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),E(e.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),E(e.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{var c;((c=this.videoState.getTransition())==null?void 0:c.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),s(Dr(this.hls,qe.Events.MANIFEST_PARSED).pipe(_s(({levels:c})=>c.reduce((l,d)=>{var I,S;let p=d.name||d.height.toString(10),{width:h,height:f}=d,b=(S=mt((I=d.attrs.QUALITY)!=null?I:""))!=null?S:xR({width:h,height:f});if(!b)return l;let g=d.attrs["FRAME-RATE"]?parseFloat(d.attrs["FRAME-RATE"]):void 0,y={id:p.toString(),quality:b,bitrate:d.bitrate/1e3,size:{width:h,height:f},fps:g};return this.trackLevels.set(p,{track:y,level:d}),l.push(y),l},[]))),t.availableVideoTracks$),s(Dr(this.hls,qe.Events.MANIFEST_PARSED),c=>{if(c.subtitleTracks.length>0){let l=[];for(let d of c.subtitleTracks){let p=d.name,h=d.attrs.URI||"",f=d.lang;l.push({id:p,url:h,language:f,type:"internal"})}e.internalTextTracks.startTransitionTo(l)}}),s(Dr(this.hls,qe.Events.LEVEL_LOADING).pipe(_s(({url:c})=>X(c))),t.hostname$),s(Dr(this.hls,qe.Events.FRAG_CHANGED),c=>{var p,h,f,b;let{video:l,audio:d}=c.frag.elementaryStreams;t.currentVideoSegmentLength$.next((((p=l==null?void 0:l.endPTS)!=null?p:0)-((h=l==null?void 0:l.startPTS)!=null?h:0))*1e3),t.currentAudioSegmentLength$.next((((f=d==null?void 0:d.endPTS)!=null?f:0)-((b=d==null?void 0:d.startPTS)!=null?b:0))*1e3)}),this.subscription.add(pt(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,c=>{this.hls.nextLevel=c?-1:this.hls.currentLevel,this.hls.loadLevel=c?-1:this.hls.loadLevel},{onError:r}));let n=c=>{var l;return(l=Array.from(this.trackLevels.values()).find(({level:d})=>d===c))==null?void 0:l.track},o=Dr(this.hls,qe.Events.LEVEL_SWITCHED).pipe(_s(({level:c})=>n(this.hls.levels[c])));o.pipe(gR(SR)).subscribe(t.currentVideoTrack$,r),this.subscription.add(pt(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel]),c=>{var f;if(vR(c))return;let l=(f=this.trackLevels.get(c.id))==null?void 0:f.level;if(!l)return;let d=this.hls.levels.indexOf(l),p=this.hls.currentLevel,h=this.hls.levels[p];!h||l.bitrate>h.bitrate?this.hls.nextLevel=d:(this.hls.loadLevel=d,this.hls.loadLevel=d)},{changed$:o,onError:r})),s(i.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);let u=yR(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,IR(["init"])).pipe(bR(0));this.subscription.add(u.subscribe(this.syncPlayback,r))}prepare(){this.videoState.startTransitionTo("ready"),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}async playIfAllowed(){this.videoState.startTransitionTo("playing"),await me(this.video).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Vs.DOM,thrown:t}))||(this.videoState.setState("paused"),E(this.params.desiredState.playbackState,"paused",!0))}pause(){this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}stop(){this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.hls.stopLoad(),this.hls.detachMedia(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState("stopped"),E(this.params.desiredState.playbackState,"stopped",!0)}};var Yg="X-Playback-Duration",Qu=async a=>{var i;let e=await et(a),t=await e.text(),r=(i=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t))==null?void 0:i[1];return r?parseInt(r,10):e.headers.has(Yg)?parseInt(e.headers.get(Yg),10):void 0};import{assertNever as $R,combine as LR,debounce as MR,ErrorCategory as Fs,filter as CR,filterChanged as DR,isNonNullable as zg,isNullable as qs,map as Kg,merge as BR,observableFrom as OR,Subscription as VR,ValueSubject as Ju,VideoQuality as _R}from"@vkontakte/videoplayer-shared";var Ku=He(mo(),1);import{videoSizeToQuality as PR,getExponentialDelay as AR}from"@vkontakte/videoplayer-shared";var wR=a=>{let e=null;if(a.QUALITY&&(e=mt(a.QUALITY)),!e&&a.RESOLUTION){let[t,r]=a.RESOLUTION.split("x").map(i=>parseInt(i,10));e=PR({width:t,height:r})}return e!=null?e:null},kR=(a,e)=>{var s,n;let t=a.split(`
|
|
113
|
-
`),r=[],i=[];for(let o=0;o<t.length;o++){let u=t[o],c=u.match(/^#EXT-X-STREAM-INF:(.+)/),l=u.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!c&&!l)){if(c){let d=(0,Ku.default)(c[1].split(",").map(I=>I.split("="))),p=(s=d.QUALITY)!=null?s:`stream-${d.BANDWIDTH}`,h=wR(d),f;d.BANDWIDTH&&(f=parseInt(d.BANDWIDTH,10)/1e3||void 0),!f&&d["AVERAGE-BANDWIDTH"]&&(f=parseInt(d["AVERAGE-BANDWIDTH"],10)/1e3||void 0);let b=d["FRAME-RATE"]?parseFloat(d["FRAME-RATE"]):void 0,g;if(d.RESOLUTION){let[I,S]=d.RESOLUTION.split("x").map(v=>parseInt(v,10));I&&S&&(g={width:I,height:S})}let y=new URL(t[++o],e).toString();h&&r.push({id:p,quality:h,url:y,bandwidth:f,size:g,fps:b})}if(l){let d=(0,Ku.default)(l[1].split(",").map(b=>b.split("=")).map(([b,g])=>[b,g.replace(/^"|"$/g,"")])),p=(n=d.URI)==null?void 0:n.replace(/playlist$/,"subtitles.vtt"),h=d.LANGUAGE,f=d.NAME;p&&h&&i.push({type:"internal",id:h,label:f,language:h,url:p,isAuto:!1})}}}if(!r.length)throw new Error("Empty manifest");return{qualityManifests:r,textTracks:i}},RR=a=>new Promise(e=>{setTimeout(()=>{e()},a)}),zu=0,Qg=async(a,e=a,t)=>{let i=await(await et(a)).text();zu+=1;try{let{qualityManifests:s,textTracks:n}=kR(i,e);return{qualityManifests:s,textTracks:n}}catch(s){if(zu<=t.manifestRetryMaxCount)return await RR(AR(zu-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),Qg(a,e,t)}return{qualityManifests:[],textTracks:[]}},Ns=Qg;var na=class{constructor(e){this.subscription=new VR;this.videoState=new M("stopped");this.textTracksManager=new Re;this.manifests$=new Ju([]);this.liveOffset=new Je;this.manifestStartTime$=new Ju(void 0);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),r=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(r==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),E(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let c=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||n||o){let l=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(l),this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),c.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if((i==null?void 0:i.to)!=="paused"&&c.state==="requested"){this.videoState.startTransitionTo("ready"),this.seek(c.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(t){case"ready":r==="ready"?E(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),E(this.params.desiredState.playbackState,"paused")):r==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":r==="paused"?(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(i==null?void 0:i.to)==="playing"&&E(this.params.desiredState.playbackState,"playing");return;case"paused":if(r==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let l=this.liveOffset.getTotalOffset();l>=this.maxSeekBackTime$.getValue()&&(l=0,this.liveOffset.resetTo(l)),this.liveOffset.resume(),this.params.output.position$.next(-l/1e3),this.prepare()}else(i==null?void 0:i.to)==="paused"&&(E(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return $R(t)}};var t;this.params=e,this.video=le(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:_R.INVARIANT,url:this.params.source.url},Ns(ee(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:r})=>{r.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:Fs.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),this.manifests$.next([this.masterManifest,...r])},r=>this.params.output.error$.next({id:"ExtractHlsQualities",category:Fs.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:r})),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(X(this.params.source.url)),this.maxSeekBackTime$=new Ju((t=e.source.maxSeekBackTime)!=null?t:1/0),this.subscribe()}selectManifest(){var u,c,l,d;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,r=e.getState(),i=t.getTransition(),s=(d=(l=(u=i==null?void 0:i.to)==null?void 0:u.id)!=null?l:(c=t.getState())==null?void 0:c.id)!=null?d:"master",n=this.manifests$.getValue();if(!n.length)return;let o=r?"master":s;return r&&!i&&t.startTransitionTo(this.masterManifest),n.find(p=>p.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"HlsLiveProvider",category:Fs.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},i=he(this.video),s=(o,u)=>this.subscription.add(o.subscribe(u,r));s(i.ended$,e.endedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(i.loadedMetadata$,e.firstBytesEvent$),s(i.loadedMetadata$,e.loadedMetadataEvent$),s(i.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),r)),this.subscription.add(pe(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(ke(this.video,t.playbackRate,i.playbackRateState$,r)),s(Le(this.video),e.elementVisible$),this.textTracksManager.connect(this.video,t,e),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),E(t.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),E(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())==null?void 0:o.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.subscription.add(this.maxSeekBackTime$.pipe(DR(),Kg(o=>-o/1e3)).subscribe(this.params.output.duration$,r)),this.subscription.add(i.loadedMetadata$.subscribe(()=>{let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),c=this.params.desiredState.videoTrack.getTransition(),l=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(c&&zg(c.to)){let d=c.to.id;this.params.desiredState.videoTrack.setState(c.to);let p=this.manifests$.getValue().find(h=>h.id===d);p&&(this.params.output.currentVideoTrack$.next(p),this.params.output.hostname$.next(X(p.url)))}l&&this.params.desiredState.autoVideoTrackSwitching.setState(l.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o&&o.state==="requested"&&this.seek(o.position)},r)),this.subscription.add(i.loadedData$.subscribe(()=>{var u,c,l;let o=(l=(c=(u=this.video)==null?void 0:u.getStartDate)==null?void 0:c.call(u))==null?void 0:l.getTime();this.manifestStartTime$.next(o||void 0)},r)),this.subscription.add(LR({startTime:this.manifestStartTime$.pipe(CR(zg)),currentTime:i.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),r)),this.subscription.add(this.manifests$.pipe(Kg(o=>o.map(({id:u,quality:c,size:l,bandwidth:d,fps:p})=>({id:u,quality:c,size:l,fps:p,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,r));let n=BR(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,OR(["init"])).pipe(MR(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),de(this.video)}prepare(){var o,u;let e=this.selectManifest();if(qs(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),r=this.params.desiredState.autoVideoTrackLimits.getState(),i=new URL(e.url);if((t||r)&&e.id===this.masterManifest.id){let{max:c,min:l}=(u=(o=t==null?void 0:t.to)!=null?o:r)!=null?u:{};for(let[d,p]of[[c,"mq"],[l,"lq"]]){let h=String(parseFloat(d||""));p&&d&&i.searchParams.set(p,h)}}let s=this.params.format==="HLS_LIVE_CMAF"?2:0,n=ee(i.toString(),this.liveOffset.getTotalOffset(),s);this.video.setAttribute("src",n),this.video.load(),Qu(n).then(c=>{var l;if(!qs(c))this.maxSeekBackTime$.next(c);else{let d=(l=this.params.source.maxSeekBackTime)!=null?l:this.maxSeekBackTime$.getValue();if(qs(d)||!isFinite(d))try{et(n).then(p=>p.text()).then(p=>{var f;let h=(f=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(p))==null?void 0:f[1];if(h){let b=new URL(h,n).toString();Qu(b).then(g=>{qs(g)||this.maxSeekBackTime$.next(g)})}})}catch(p){}}})}playIfAllowed(){me(this.video).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),E(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Fs.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,r=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(r),this.params.output.position$.next(-r/1e3),this.params.output.seekedEvent$.next()}};import{assertNever as NR,debounce as FR,ErrorCategory as Xu,fromEvent as Zu,isNonNullable as qR,isNullable as UR,map as Jg,merge as Xg,observableFrom as Zg,Subscription as HR,ValueSubject as jR,VideoQuality as GR,clientChecker as WR}from"@vkontakte/videoplayer-shared";var oa=class{constructor(e){this.subscription=new HR;this.videoState=new M("stopped");this.textTracksManager=new Re;this.manifests$=new jR([]);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),r=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(r==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),E(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let c=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||n||o){let l=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(l);let{currentTime:d}=this.video;this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),c.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:d*1e3,forcePrecise:!0});return}switch((i==null?void 0:i.to)!=="paused"&&c.state==="requested"&&this.seek(c.position),t){case"ready":r==="ready"?E(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),E(this.params.desiredState.playbackState,"paused")):r==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":r==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(i==null?void 0:i.to)==="playing"&&E(this.params.desiredState.playbackState,"playing");return;case"paused":r==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&E(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return NR(t)}};this.params=e,this.video=le(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:GR.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(X(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),Ns(ee(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:t,textTracks:r})=>{this.manifests$.next([this.masterManifest,...t]),this.params.tuning.useNativeHLSTextTracks||this.params.desiredState.internalTextTracks.startTransitionTo(r)},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:Xu.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){var u,c,l,d;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,r=e.getState(),i=t.getTransition(),s=(d=(l=(u=i==null?void 0:i.to)==null?void 0:u.id)!=null?l:(c=t.getState())==null?void 0:c.id)!=null?d:"master",n=this.manifests$.getValue();if(!n.length)return;let o=r?"master":s;return r&&!i&&t.startTransitionTo(this.masterManifest),n.find(p=>p.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"HlsProvider",category:Xu.WTF,message:"HlsProvider internal logic error",thrown:o})},i=he(this.video),s=(o,u)=>this.subscription.add(o.subscribe(u));if(s(i.timeUpdate$,e.position$),s(i.durationChange$,e.duration$),s(i.ended$,e.endedEvent$),s(i.looped$,e.loopedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(i.loadedMetadata$,e.firstBytesEvent$),s(i.loadedMetadata$,e.loadedMetadataEvent$),s(i.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.seeked$,e.seekedEvent$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe(Jg(o=>o.to)),this.params.output.playbackState$),this.subscription.add(Ge(this.video,t.isLooped,r)),this.subscription.add(pe(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(ke(this.video,t.playbackRate,i.playbackRateState$,r)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),E(t.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),E(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())==null?void 0:o.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},r).add(i.loadedMetadata$.subscribe(()=>{var d;let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),c=this.params.desiredState.videoTrack.getTransition(),l=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(c&&qR(c.to)){let p=c.to.id;this.params.desiredState.videoTrack.setState(c.to);let h=this.manifests$.getValue().find(f=>f.id===p);if(h){this.params.output.currentVideoTrack$.next(h),this.params.output.hostname$.next(X(h.url));let f=this.params.desiredState.playbackRate.getState(),b=(d=this.params.output.element$.getValue())==null?void 0:d.playbackRate;if(f!==b){let g=this.params.output.element$.getValue();g&&(this.params.desiredState.playbackRate.setState(f),g.playbackRate=f)}}}l&&this.params.desiredState.autoVideoTrackSwitching.setState(l.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o.state==="requested"&&this.seek(o.position)},r))),this.subscription.add(this.manifests$.pipe(Jg(o=>o.map(({id:u,quality:c,size:l,bandwidth:d,fps:p})=>({id:u,quality:c,size:l,fps:p,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,r)),!WR.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add(Xg(Zu(o,"addtrack"),Zu(o,"removetrack"),Zu(o,"change"),Zg(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},r))}let n=Xg(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,Zg(["init"])).pipe(FR(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),de(this.video)}prepare(){var s,n;let e=this.selectManifest();if(UR(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),r=this.params.desiredState.autoVideoTrackLimits.getState(),i=new URL(e.url);if((t||r)&&e.id===this.masterManifest.id){let{max:o,min:u}=(n=(s=t==null?void 0:t.to)!=null?s:r)!=null?n:{};for(let[c,l]of[[o,"mq"],[u,"lq"]]){let d=String(parseFloat(c||""));l&&c&&i.searchParams.set(l,d)}}this.video.setAttribute("src",i.toString()),this.video.load()}playIfAllowed(){me(this.video).then(e=>{e||(this.videoState.setState("paused"),E(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Xu.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};import{assertNever as YR,assertNonNullable as eS,debounce as QR,ErrorCategory as tS,isHigher as zR,isHigherOrEqual as KR,isInvariantQuality as rS,isLowerOrEqual as JR,isNonNullable as XR,merge as ZR,observableFrom as e$,Subscription as t$,map as r$}from"@vkontakte/videoplayer-shared";var ua=class{constructor(e){this.subscription=new t$;this.videoState=new M("stopped");this.trackUrls={};this.textTracksManager=new Re;this.syncPlayback=()=>{var u,c,l;let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),E(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let s=this.params.desiredState.autoVideoTrackLimits.getTransition(),n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.seekState.getState();if(s&&e!=="ready"&&!n){this.handleQualityLimitTransition(s.to.max);return}if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(n){let{currentTime:d}=this.video;this.prepare(),o.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:d*1e3,forcePrecise:!0}),n.to&&((u=this.params.desiredState.autoVideoTrackLimits.getState())==null?void 0:u.max)!==((l=(c=this.trackUrls[n.to.id])==null?void 0:c.track)==null?void 0:l.quality)&&this.params.output.autoVideoTrackLimits$.next({max:void 0});return}switch((r==null?void 0:r.to)!=="paused"&&o.state==="requested"&&this.seek(o.position),e){case"ready":t==="ready"?E(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),E(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(r==null?void 0:r.to)==="playing"&&E(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&E(this.params.desiredState.playbackState,"paused");return;default:return YR(e)}};this.params=e,this.video=le(e.container,e.tuning),this.params.output.element$.next(this.video),Object.entries(this.params.source).reverse().forEach(([t,r],i)=>{let s=i.toString(10);this.trackUrls[s]={track:{quality:t,id:s},url:r}}),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next(Object.values(this.trackUrls).map(({track:t})=>t)),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.desiredState.autoVideoTrackSwitching.setState(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.subscribe()}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"MpegProvider",category:tS.WTF,message:"MpegProvider internal logic error",thrown:o})},i=he(this.video),s=(o,u)=>this.subscription.add(o.subscribe(u,r));s(i.timeUpdate$,e.position$),s(i.durationChange$,e.duration$),s(i.ended$,e.endedEvent$),s(i.looped$,e.loopedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(i.loadedMetadata$,e.firstBytesEvent$),s(i.loadedMetadata$,e.loadedMetadataEvent$),s(i.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.seeked$,e.seekedEvent$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe(r$(o=>o.to)),this.params.output.playbackState$),this.subscription.add(Ge(this.video,t.isLooped,r)),this.subscription.add(pe(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(ke(this.video,t.playbackRate,i.playbackRateState$,r)),s(Le(this.video),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),E(t.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),E(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{var u,c;((u=this.videoState.getTransition())==null?void 0:u.to)==="ready"&&this.videoState.setState("ready");let o=this.params.desiredState.videoTrack.getTransition();if(o&&XR(o.to)){this.params.desiredState.videoTrack.setState(o.to),this.params.output.currentVideoTrack$.next(this.trackUrls[o.to.id].track);let l=this.params.desiredState.playbackRate.getState(),d=(c=this.params.output.element$.getValue())==null?void 0:c.playbackRate;if(l!==d){let p=this.params.output.element$.getValue();p&&(this.params.desiredState.playbackRate.setState(l),p.playbackRate=l)}}this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.textTracksManager.connect(this.video,t,e);let n=ZR(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,e$(["init"])).pipe(QR(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.params.output.element$.next(void 0),de(this.video)}prepare(){var r;let e=(r=this.params.desiredState.videoTrack.getState())==null?void 0:r.id;eS(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];eS(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=Ki(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(X(t))}playIfAllowed(){me(this.video).then(e=>{e||(this.videoState.setState("paused"),E(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:tS.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){var i,s,n,o;let t,r=e;if(e&&((i=this.params.output.currentVideoTrack$.getValue())==null?void 0:i.quality)!==e){let u=(s=Object.values(this.trackUrls).find(d=>!rS(d.track.quality)&&JR(d.track.quality,e)))==null?void 0:s.track,c=(n=this.params.desiredState.videoTrack.getState())==null?void 0:n.id,l=(o=this.trackUrls[c!=null?c:"0"])==null?void 0:o.track;if(u&&l&&KR(l.quality,u.quality)&&(t=u),!t){let d=Object.values(this.trackUrls).filter(h=>!rS(h.track.quality)&&zR(h.track.quality,e)),p=d.length;p&&(t=d[p-1].track)}t&&(r=t.quality)}else if(!e){let u=Object.values(this.trackUrls).map(c=>c.track);t=bt(u,{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},throughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:0,abrLogger:this.params.dependencies.abrLogger})}t&&(this.params.output.currentVideoTrack$.next(t),this.params.desiredState.videoTrack.startTransitionTo(t)),this.params.output.autoVideoTrackLimits$.next({max:r})}};import{assertNever as aS,debounce as n$,merge as sS,observableFrom as o$,Subscription as u$,map as nS,ValueSubject as c$,ErrorCategory as tc,VideoQuality as l$}from"@vkontakte/videoplayer-shared";import{ErrorCategory as i$}from"@vkontakte/videoplayer-shared";var iS=["stun:videostun.mycdn.me:80"],a$=1e3,s$=3,ec=()=>null,Us=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=ec;this.externalStopCallback=ec;this.externalErrorCallback=ec;this.options=this.normalizeOptions(t);let r=e.split("/");this.serverUrl=r.slice(0,r.length-1).join("/"),this.streamKey=r[r.length-1]}onStart(e){try{this.externalStartCallback=e}catch(t){this.handleSystemError(t)}}onStop(e){try{this.externalStopCallback=e}catch(t){this.handleSystemError(t)}}onError(e){try{this.externalErrorCallback=e}catch(t){this.handleSystemError(t)}}connect(){this.connectWS()}disconnect(){try{this.externalStopCallback(),this.closeConnections()}catch(e){this.handleSystemError(e)}}connectWS(){this.ws||(this.ws=new WebSocket(this.serverUrl),this.ws.onopen=this.onSocketOpen.bind(this),this.ws.onmessage=this.onSocketMessage.bind(this),this.ws.onclose=this.onSocketClose.bind(this),this.ws.onerror=this.onSocketError.bind(this))}onSocketOpen(){this.handleLogin()}onSocketClose(e){try{if(!this.ws)return;this.ws=null,e.code>1e3?(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():this.scheduleRetry()):this.externalStopCallback()}catch(t){this.handleRTCError(t)}}onSocketError(e){try{this.externalErrorCallback(new Error(e.toString()))}catch(t){this.handleRTCError(t)}}onSocketMessage(e){try{let t=this.parseMessage(e.data);switch(t.type){case"JOIN":case"CALL_JOIN":this.handleJoinMessage(t);break;case"UPDATE":this.handleUpdateMessage(t);break;case"STATUS":this.handleStatusMessage(t);break}}catch(t){this.handleRTCError(t)}}handleJoinMessage(e){switch(e.inviteType){case"ANSWER":this.handleAnswer(e.sdp);break;case"CANDIDATE":this.handleCandidate(e.candidate);break}}handleStatusMessage(e){switch(e.status){case"UNPUBLISHED":this.handleUnpublished();break}}async handleUpdateMessage(e){try{let t=await this.createOffer();this.peerConnection&&await this.peerConnection.setLocalDescription(t),this.handleAnswer(e.sdp)}catch(t){this.handleRTCError(t)}}async handleLogin(){try{let e={iceServers:[{urls:iS}]};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:i$.WTF,message:e.message})}async onPeerConnectionStream(e){let t=e.streams[0];this.stream&&this.stream.id===t.id||(this.stream=t,this.externalStartCallback(this.stream))}onPeerConnectionIceCandidate(e){e.candidate&&this.send({type:this.signalingType,inviteType:"CANDIDATE",candidate:e.candidate})}onPeerConnectionIceConnectionStateChange(){if(this.peerConnection){let e=this.peerConnection.iceConnectionState;["failed","closed"].indexOf(e)>-1&&(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():(this.closeConnections(),this.scheduleRetry()))}}async createOffer(){let e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");let t=await this.peerConnection.createOffer(e),r=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(r))throw new Error("No h264 codec support error");return t}handleRTCError(e){try{this.externalErrorCallback(e||new Error("RTC connection error"))}catch(t){this.handleSystemError(t)}}handleNetworkError(){try{this.externalErrorCallback(new Error("Network error"))}catch(e){this.handleSystemError(e)}}send(e){this.ws&&this.ws.send(JSON.stringify(e))}parseMessage(e){try{return JSON.parse(e)}catch(t){throw new Error("Can not parse socket message")}}closeConnections(){let e=this.ws;e&&(this.ws=null,e.close(1e3)),this.removePeerConnection()}removePeerConnection(){let e=this.peerConnection;e&&(this.peerConnection=null,e.close(),e.ontrack=null,e.onicecandidate=null,e.oniceconnectionstatechange=null,e=null)}scheduleRetry(){this.retryTimeout=setTimeout(this.connectWS.bind(this),a$)}normalizeOptions(e={}){let t={stunServerList:iS,maxRetryNumber:s$,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var ca=class{constructor(e){this.videoState=new M("stopped");this.maxSeekBackTime$=new c$(0);this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.pause(),this.video.srcObject=null,this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),E(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let s=this.params.desiredState.videoTrack.getTransition();if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s){this.prepare();return}switch(e){case"ready":t==="paused"?(this.videoState.setState("paused"),E(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(r==null?void 0:r.to)==="playing"&&E(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&E(this.params.desiredState.playbackState,"paused");return;default:return aS(e)}};this.subscription=new u$,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=le(e.container,e.tuning),this.liveStreamClient=new Us(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.subscribe()}destroy(){this.subscription.unsubscribe(),this.liveStreamClient.disconnect(),this.params.output.element$.next(void 0),de(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,r=n=>{e.error$.next({id:"WebRTCLiveProvider",category:tc.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};sS(this.videoState.stateChangeStarted$.pipe(nS(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe(nS(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})});let i=he(this.video),s=(n,o)=>this.subscription.add(n.subscribe(o,r));s(i.timeUpdate$,e.liveTime$),s(i.ended$,e.endedEvent$),s(i.looped$,e.loopedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(Le(this.video),this.params.output.elementVisible$),this.subscription.add(i.durationChange$.subscribe(n=>{e.duration$.next(n===1/0?0:n)})).add(i.canplay$.subscribe(()=>{var n;((n=this.videoState.getTransition())==null?void 0:n.to)==="ready"&&this.videoState.setState("ready")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused")},r)).add(i.playing$.subscribe(()=>{this.videoState.setState("playing")},r)).add(i.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(pe(this.video,t.volume,i.volumeState$,r)).add(i.volumeState$.subscribe(e.volume$,r)).add(this.videoState.stateChangeEnded$.subscribe(n=>{switch(n.to){case"stopped":e.position$.next(0),e.duration$.next(0),t.playbackState.setState("stopped");break;case"ready":break;case"paused":t.playbackState.setState("paused");break;case"playing":t.playbackState.setState("playing");break;default:return aS(n.to)}},r)).add(sS(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,o$(["init"])).pipe(n$(0)).subscribe(this.syncPlayback.bind(this),r)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),r)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),r))}onLiveStreamStart(e){this.params.output.element$.next(this.video),this.params.output.duration$.next(0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(X(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:l$.INVARIANT}),this.video.srcObject=e,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:tc.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){me(this.video).then(e=>{e||(this.videoState.setState("paused"),E(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:tc.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var la=class{constructor(e){this.iterator=e[Symbol.iterator](),this.next()}next(){this.current=this.iterator.next()}getValue(){if(this.current.done)throw new Error("Iterable is completed");return this.current.value}isCompleted(){return!!this.current.done}};import{assertNever as ha,assertNonNullable as vt,ErrorCategory as js,filter as g$,isNonNullable as pS,isNullable as S$,map as v$,merge as y$,once as T$,Subject as Ie,Subscription as hS,ValueSubject as C,flattenObject as fS}from"@vkontakte/videoplayer-shared";import{Observable as d$,map as oS,Subscription as p$,Subject as h$}from"@vkontakte/videoplayer-shared";var uS=a=>new d$(e=>{let t=new p$,r=a.desiredPlaybackState$.stateChangeStarted$.pipe(oS(({from:c,to:l})=>`${c}-${l}`)),i=a.desiredPlaybackState$.stateChangeEnded$,s=a.providerChanged$.pipe(oS(({type:c})=>c!==void 0)),n=new h$,o=0,u="unknown";return t.add(r.subscribe(c=>{o&&window.clearTimeout(o),u=c,o=window.setTimeout(()=>n.next(c),a.maxTransitionInterval)})),t.add(i.subscribe(()=>{window.clearTimeout(o),u="unknown",o=0})),t.add(s.subscribe(c=>{o&&(window.clearTimeout(o),o=0,c&&(o=window.setTimeout(()=>n.next(u),a.maxTransitionInterval)))})),t.add(n.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});import{ErrorCategory as cS,Subscription as f$,combine as m$,filter as lS,once as dS}from"@vkontakte/videoplayer-shared";var da=null,Hs=null;function rc(){return da||(da=new(window.AudioContext||window.webkitAudioContext)),Hs||(Hs=new GainNode(da,{gain:1}),Hs.connect(da.destination)),{audioCtx:da,gainNode:Hs}}import{clientChecker as b$}from"@vkontakte/videoplayer-shared";var Br=class Br{constructor(e,t,r,i,s){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=r;this.volumeMultiplier=i;this.subscriptions=new f$;this.lastAudioContextResumeId=0;!s||!this.isSupported()||i===1||this.subscriptions.add(this.provider$.pipe(lS(n=>!!n.type),dS()).subscribe(({type:n})=>this.subscribe(n)))}subscribe(e){b$.isSafari&&e!=="MPEG"||this.subscriptions.add(m$({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe(lS(({playbackState:t,video:r,volume:{muted:i,volume:s}})=>t==="playing"&&!!r&&!i&&!!s),dS()).subscribe(({video:t})=>this.initAudioContextOnce(t)))}isSupported(){return"AudioContext"in window&&"GainNode"in window&&"MediaElementAudioSourceNode"in window}initAudioContextOnce(e){let{volumeMultiplier:t}=this,{audioCtx:r,gainNode:i}=rc(),s=(Math.random()+1)*999999;this.lastAudioContextResumeId=s,r.resume().then(()=>{var n;if(s!==this.lastAudioContextResumeId)throw new Error(`AudioContext.resume() resolved after ${Br.errorId} destroyed`);i.gain.value=t;try{new MediaElementAudioSourceNode(r,{mediaElement:e}).connect(i)}catch(o){this.volumeMultiplierError$.next({id:Br.errorId,category:cS.VIDEO_PIPELINE,message:(n=o==null?void 0:o.message)!=null?n:"initAudioContextOnce: (new MediaElementAudioSourceNode).connect() exception",thrown:o})}}).catch(n=>{var o;this.volumeMultiplierError$.next({id:Br.errorId,category:cS.VIDEO_PIPELINE,message:(o=n==null?void 0:n.message)!=null?o:"initAudioContextOnce: AudioContext.resume() exception",thrown:n})})}destroy(){let{gainNode:e}=rc();e.gain.value=1,this.subscriptions.unsubscribe(),this.lastAudioContextResumeId=0}};Br.errorId="VolumeMultiplierManager";var pa=Br;var I$={chunkDuration:5e3,maxParallelRequests:5},fa=class{constructor(e){this.current$=new C({type:void 0});this.providerError$=new Ie;this.noAvailableProvidersError$=new Ie;this.volumeMultiplierError$=new Ie;this.providerOutput={position$:new C(0),duration$:new C(1/0),volume$:new C({muted:!1,volume:1}),availableVideoStreams$:new C([]),currentVideoStream$:new C(void 0),availableVideoTracks$:new C([]),currentVideoTrack$:new C(void 0),availableAudioStreams$:new C([]),currentAudioStream$:new C(void 0),availableAudioTracks$:new C([]),currentVideoSegmentLength$:new C(0),currentAudioSegmentLength$:new C(0),isAudioAvailable$:new C(!0),autoVideoTrackLimitingAvailable$:new C(!1),autoVideoTrackLimits$:new C(void 0),currentBuffer$:new C(void 0),isBuffering$:new C(!0),error$:new Ie,warning$:new Ie,willSeekEvent$:new Ie,seekedEvent$:new Ie,loopedEvent$:new Ie,endedEvent$:new Ie,firstBytesEvent$:new Ie,loadedMetadataEvent$:new Ie,firstFrameEvent$:new Ie,canplay$:new Ie,isLive$:new C(void 0),isLowLatency$:new C(!1),canChangePlaybackSpeed$:new C(!0),liveTime$:new C(void 0),liveBufferTime$:new C(void 0),availableTextTracks$:new C([]),currentTextTrack$:new C(void 0),hostname$:new C(void 0),httpConnectionType$:new C(void 0),httpConnectionReused$:new C(void 0),inPiP$:new C(!1),inFullscreen$:new C(!1),element$:new C(void 0),elementVisible$:new C(!0),availableSources$:new C(void 0),is3DVideo$:new C(!1),playbackState$:new C("")};this.subscription=new hS;var o;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer"),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name);let t=Cb([...Bb(this.params.tuning),...Db(this.params.tuning)],this.params.tuning.useHlsJs,this.params.tuning.useManagedMediaSource).filter(u=>pS(e.sources[u])),{forceFormat:r,formatsToAvoid:i}=this.params.tuning,s=[];r?s=[r]:i.length?s=[...t.filter(u=>!i.includes(u)),...t.filter(u=>i.includes(u))]:s=t,this.log({message:`Selected formats: ${s.join(" > ")}`}),this.tracer.log("Selected formats",fS(s)),this.screenFormatsIterator=new la(s);let n=[...yu(!0),...yu(!1)];this.chromecastFormatsIterator=new la(n.filter(u=>pS(e.sources[u]))),this.providerOutput.availableSources$.next(e.sources),this.volumeMultiplierManager=new pa(this.providerOutput,this.current$,this.volumeMultiplierError$,(o=this.params.volumeMultiplier)!=null?o:1,this.params.tuning.useVolumeMultiplier)}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.tracer.end()}initProvider(){let e=this.chooseDestination(),t=this.chooseFormat(e);if(S$(t)){this.handleNoFormatsError(e);return}let r;try{r=this.createProvider(e,t)}catch(i){this.providerError$.next({id:"ProviderNotConstructed",category:js.WTF,message:"Failed to create provider",thrown:i})}r?this.current$.next({type:t,provider:r,destination:e}):this.current$.next({type:void 0})}reinitProvider(){this.tracer.log("reinitProvider"),this.destroyProvider(),this.initProvider()}switchToNextProvider(e){this.tracer.log("switchToNextProvider",{destination:e}),this.destroyProvider(),this.failoverIndex=void 0,this.skipFormat(e),this.initProvider()}destroyProvider(){let e=this.current$.getValue().provider;if(!e)return;this.log({message:"destroyProvider"}),this.tracer.log("destroyProvider");let t=this.providerOutput.position$.getValue()*1e3,r=this.params.desiredState.seekState.getState(),i=r.state!=="none";if(this.params.desiredState.seekState.setState({state:"requested",position:i?r.position:t,forcePrecise:i?r.forcePrecise:!1}),e.scene3D){let n=e.scene3D.getCameraRotation();this.params.desiredState.cameraOrientation.setState({x:n.x,y:n.y})}e.destroy();let s=this.providerOutput.isBuffering$;s.getValue()||s.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),this.tracer.log("createProvider",{destination:e,format:t}),e){case"SCREEN":return this.createScreenProvider(t);case"CHROMECAST":return this.createChromecastProvider(t);default:return ha(e)}}createScreenProvider(e){let{sources:t,container:r,desiredState:i}=this.params,s=this.providerOutput,n={container:r,source:null,desiredState:i,output:s,dependencies:this.params.dependencies,tuning:this.params.tuning};switch(e){case"DASH_SEP":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_ONDEMAND":case"DASH_STREAMS":{let o=this.applyFailoverHost(t[e]),u=this.applyFailoverHost(t.HLS_ONDEMAND||t.HLS);return vt(o),new ra({...n,source:o,sourceHls:u})}case"DASH_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return vt(o),new ia({...n,source:o})}case"HLS":case"HLS_ONDEMAND":{let o=this.applyFailoverHost(t[e]);return vt(o),Er||!this.params.tuning.useHlsJs?new oa({...n,source:o}):new sa({...n,source:o})}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return vt(o),new na({...n,source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case"MPEG":{let o=this.applyFailoverHost(t[e]);return vt(o),new ua({...n,source:o})}case"DASH_LIVE":{let o=this.applyFailoverHost(t[e]);return vt(o),new mb({...n,source:o,config:{...I$,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case"WEB_RTC_LIVE":{let o=this.applyFailoverHost(t[e]);return vt(o),new ca({container:r,source:o,desiredState:i,output:s,dependencies:this.params.dependencies,tuning:this.params.tuning})}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return ha(e)}}createChromecastProvider(e){let{sources:t,container:r,desiredState:i,meta:s}=this.params,n=this.providerOutput,o=this.params.dependencies.chromecastInitializer.connection$.getValue();return vt(o),new di({connection:o,meta:s,container:r,source:t,format:e,desiredState:i,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?"CHROMECAST":"SCREEN"}chooseFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case"CHROMECAST":return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return ha(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return ha(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 ha(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;let t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;let r=i=>{let s=new URL(i);return s.host=t,s.toString()};if(e===void 0)return e;if("type"in e){if(e.type==="raw")return e;if(e.type==="url")return{...e,url:r(e.url)}}return(0,mS.default)(Object.entries(e).map(([i,s])=>[i,r(s)]))}initProviderErrorHandling(){let e=new hS,t=!1,r=0;return e.add(y$(this.providerOutput.error$,uS({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(v$(i=>({id:`ProviderHangup:${i}`,category:js.WTF,message:`A ${i} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;let i=this.params.desiredState.playbackState.transitionEnded$.pipe(g$(({to:s})=>s==="playing"),T$()).subscribe(()=>t=!0);e.add(i)})),e.add(this.providerError$.subscribe(i=>{let s=this.current$.getValue().destination,n={error:i,currentDestination:s};if(s==="CHROMECAST")this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider("SCREEN"),()=>this.params.dependencies.chromecastInitializer.disconnect());else{let o=i.category===js.NETWORK,u=i.category===js.FATAL,c=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),l=r<this.params.tuning.providerErrorLimit&&!u,d=c&&!u&&(o&&t||!l);n={...n,isNetworkError:o,isFatalError:u,haveFailoverHost:c,tryFailover:d,canReinitProvider:l},d?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):l?(r++,this.reinitProvider()):this.switchToNextProvider(s!=null?s:"SCREEN")}this.tracer.error("providerError",fS(n))})),e}};import{fromEvent as Gs,once as E$,combine as x$,Subscription as bS,ValueSubject as ic,map as P$,filter as A$,isNonNullable as Ws,now as Ee,safeStorage as ac}from"@vkontakte/videoplayer-shared";var w$=5e3,gS="one_video_throughput",SS="one_video_rtt",at=window.navigator.connection,vS=()=>{let a=at==null?void 0:at.downlink;if(Ws(a)&&a!==10)return a*1e3},yS=()=>{let a=at==null?void 0:at.rtt;if(Ws(a)&&a!==3e3)return a},TS=(a,e,t)=>{let r=t*8,i=r/a;return r/(i+e)},sc=class a{constructor(e){this.subscription=new bS;this.concurrentDownloads=new Set;var i,s;this.tuningConfig=e;let t=a.load(gS)||(e.useBrowserEstimation?vS():void 0)||w$,r=(s=(i=a.load(SS))!=null?i:e.useBrowserEstimation?yS():void 0)!=null?s:0;if(this.throughput$=new ic(t),this.rtt$=new ic(r),this.rttAdjustedThroughput$=new ic(TS(t,r,e.rttPenaltyRequestSize)),this.throughput=Yt.getSmoothedValue(t,-1,e),this.rtt=Yt.getSmoothedValue(r,1,e),e.useBrowserEstimation){let n=()=>{let u=vS();u&&this.throughput.next(u);let c=yS();Ws(c)&&this.rtt.next(c)};at&&"onchange"in at&&this.subscription.add(Gs(at,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{ac.set(gS,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{ac.set(SS,n.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(x$({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(P$(({throughput:n,rtt:o})=>TS(n,o,e.rttPenaltyRequestSize)),A$(n=>{let o=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(n-o)/o>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,r=Ee(),i=new bS;switch(this.subscription.add(i),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:i.add(Gs(e,"progress").pipe(E$()).subscribe(s=>{t=s.loaded,r=Ee()}));break;case 1:case 0:i.add(Gs(e,"loadstart").subscribe(()=>{t=0,r=Ee()}));break}i.add(Gs(e,"loadend").subscribe(s=>{if(e.status===200){let n=s.loaded,o=Ee(),u=n-t,c=o-r;this.addRawSpeed(u,c,1)}this.concurrentDownloads.delete(e),i.unsubscribe()}))}trackStream(e,t=!1){let r=e.getReader();if(!r){e.cancel("Could not get reader");return}let i=0,s=Ee(),n=0,o=Ee(),u=l=>{this.concurrentDownloads.delete(e),r.releaseLock(),e.cancel(`Throughput Estimator error: ${l}`).catch(()=>{})},c=async({done:l,value:d})=>{if(l)!t&&this.addRawSpeed(i,Ee()-s,1),this.concurrentDownloads.delete(e);else if(d){if(t){let p=Ee();if(p-o>this.tuningConfig.lowLatency.continuesByteSequenceInterval||p-s>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let f=o-s;f&&this.addRawSpeed(n,f,1,t),n=d.byteLength,s=Ee()}else n+=d.byteLength;o=Ee()}else i+=d.byteLength,n+=d.byteLength,n>=this.tuningConfig.streamMinSampleSize&&Ee()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,Ee()-o,this.concurrentDownloads.size),n=0,o=Ee());await(r==null?void 0:r.read().then(c,u))}};this.concurrentDownloads.add(e),r==null||r.read().then(c,u)}addRawSpeed(e,t,r=1,i=!1){if(a.sanityCheck(e,t,i)){let s=e*8/t;this.throughput.next(s*r)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,r=!1){let i=e*8/t;return!(!i||!isFinite(i)||i>1e6||i<30||r&&e<1e4||!r&&e<10*1024||!r&&t<=20)}static load(e){var r;let t=ac.get(e);if(Ws(t))return(r=parseInt(t,10))!=null?r:void 0}},IS=sc;import{fillWithDefault as k$,VideoQuality as ES}from"@vkontakte/videoplayer-shared";var xS={configName:["core"],throughputEstimator:{type:"EmaAndMa",emaAlphaSlow:.2,emaAlphaFast:.7,emaAlpha:.45,basisTrendChangeCount:10,changeThreshold:.05,useBrowserEstimation:!0,rttPenaltyRequestSize:1*1024*1024,streamMinSampleSize:10*1024,streamMinSampleTime:300,deviationDepth:20,deviationFactor:.5,lowLatency:{continuesByteSequenceInterval:50,maxLastEvaluationTimeout:300}},autoTrackSelection:{bitrateFactorAtEmptyBuffer:1.8,bitrateAudioFactorAtEmptyBuffer:7,bitrateFactorAtFullBuffer:1.2,bitrateAudioFactorAtFullBuffer:5,minVideoAudioRatio:5,minAvailableThroughputAudioRatio:5,usePixelRatio:!0,limitByContainer:!0,containerSizeFactor:2,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldown:3e3,backgroundVideoQualityLimit:ES.Q_4320P,activeVideoAreaThreshold:.1},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:ES.Q_480P},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,maxSegmentDurationLeftToSelectNextSegment:3e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:3e3,crashOnStallTimeout:25e3,enableSubSegmentBufferFeeding:!0,segmentTimelineTolerance:100,useFetchPriorityHints:!0},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:250,playbackCatchupSpeedup:.05,isActive:!1,delayEstimator:{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:void 0,useWebmBigRequest:!1,webmCodec:"vp9",androidPreferredFormat:"mpeg",preferCMAF:!1,preferWebRTC:!1,preferMultiStream:!1,preferHDR:!1,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,accumulationBufferStallSizeMs:0,requestQuick:!1,useHlsJs:!0,useNativeHLSTextTracks:!1,useManagedMediaSource:!1,useNewPruneBufferStrategy:!1,useNewPartialSegmentFeeding:!1,useSeparateAudioVideoABR:!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},PS=a=>{var e;return{...k$(a,xS),configName:[...(e=a.configName)!=null?e:[],...xS.configName]}};import{assertNonNullable as Ys,combine as yt,ErrorCategory as Qs,filter as ae,filterChanged as _,fromEvent as oc,isNonNullable as B$,isNullable as O$,Logger as V$,map as D,mapTo as RS,merge as Tt,now as zs,once as st,Subject as j,Subscription as $S,tap as LS,ValueSubject as P,isHigher as _$,isInvariantQuality as MS,flattenObject as It,throttle as uc,getTraceSubscriptionMethod as CS,Tracer as N$}from"@vkontakte/videoplayer-shared";import{merge as R$,map as $$,filter as AS,isNonNullable as L$}from"@vkontakte/videoplayer-shared";var nc=({seekState:a,position$:e})=>R$(a.stateChangeEnded$.pipe($$(({to:t})=>{var r;return t.state==="none"?void 0:((r=t.position)!=null?r:NaN)/1e3}),AS(L$)),e.pipe(AS(()=>a.getState().state==="none")));import{assertNonNullable as M$}from"@vkontakte/videoplayer-shared";var wS=a=>{let e=typeof a.container=="string"?document.getElementById(a.container):a.container;return M$(e,`Wrong container or containerId {${a.container}}`),e};import{filter as C$,once as D$}from"@vkontakte/videoplayer-shared";var kS=(a,e,t,r)=>{a!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&(t==null?void 0:t.getValue().length)===0?t.pipe(C$(i=>i.length>0),D$()).subscribe(i=>{i.find(r)&&e.startTransitionTo(a)}):(a===void 0||t!=null&&t.getValue().find(r))&&e.startTransitionTo(a)};var Ks=class{constructor(e={configName:[]},t=N$.createRootTracer(!1)){this.subscription=new $S;this.logger=new V$;this.abrLogger=this.logger.createComponentLog("ABR");this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new P(!1);this.hasLiveOffsetByPausedTimer=0;this.desiredState={playbackState:new M("stopped"),seekState:new M({state:"none"}),volume:new M({volume:1,muted:!1}),videoTrack:new M(void 0),videoStream:new M(void 0),audioStream:new M(void 0),autoVideoTrackSwitching:new M(!0),autoVideoTrackLimits:new M({}),isLooped:new M(!1),playbackRate:new M(1),externalTextTracks:new M([]),internalTextTracks:new M([]),currentTextTrack:new M(void 0),textTrackCuesSettings:new M({}),cameraOrientation:new M({x:0,y:0})};this.info={playbackState$:new P("stopped"),position$:new P(0),duration$:new P(1/0),muted$:new P(!1),volume$:new P(1),availableVideoStreams$:new P([]),currentVideoStream$:new P(void 0),availableQualities$:new P([]),availableQualitiesFps$:new P({}),currentQuality$:new P(void 0),isAutoQualityEnabled$:new P(!0),autoQualityLimitingAvailable$:new P(!1),autoQualityLimits$:new P({}),availableAudioStreams$:new P([]),currentAudioStream$:new P(void 0),availableAudioTracks$:new P([]),isAudioAvailable$:new P(!0),currentPlaybackRate$:new P(1),currentBuffer$:new P({start:0,end:0}),isBuffering$:new P(!0),isStalled$:new P(!1),isEnded$:new P(!1),isLooped$:new P(!1),isLive$:new P(void 0),canChangePlaybackSpeed$:new P(void 0),atLiveEdge$:new P(void 0),atLiveDurationEdge$:new P(void 0),liveTime$:new P(void 0),liveBufferTime$:new P(void 0),currentFormat$:new P(void 0),availableTextTracks$:new P([]),currentTextTrack$:new P(void 0),throughputEstimation$:new P(void 0),rttEstimation$:new P(void 0),videoBitrate$:new P(void 0),hostname$:new P(void 0),httpConnectionType$:new P(void 0),httpConnectionReused$:new P(void 0),surface$:new P("none"),chromecastState$:new P("NOT_AVAILABLE"),chromecastDeviceName$:new P(void 0),intrinsicVideoSize$:new P(void 0),availableSources$:new P(void 0),is3DVideo$:new P(!1),currentVideoSegmentLength$:new P(0),currentAudioSegmentLength$:new P(0)};this.events={inited$:new j,ready$:new j,started$:new j,playing$:new j,paused$:new j,stopped$:new j,willStart$:new j,willResume$:new j,willPause$:new j,willStop$:new j,willDestruct$:new j,watchCoverageRecord$:new j,watchCoverageLive$:new j,managedError$:new j,fatalError$:new j,ended$:new j,looped$:new j,seeked$:new j,willSeek$:new j,firstBytes$:new j,loadedMetadata$:new j,firstFrame$:new j,canplay$:new j,log$:new j};this.experimental={element$:new P(void 0),tuningConfigName$:new P([]),enableDebugTelemetry$:new P(!1),dumpTelemetry:Qm};if(this.initLogs(),this.tuning=PS(e),this.tracer=t,this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new Ia({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new IS(this.tuning.throughputEstimator),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(r,i,s)=>{let n=Reflect.get(r,i,s);return typeof n!="function"?n:(...o)=>{try{return n.apply(r,o)}catch(u){let c=o.map(p=>JSON.stringify(p,(h,f)=>{let b=typeof f;return["number","string","boolean"].includes(b)?f:f===null?null:`<${b}>`})),l=`Player.${String(i)}`,d=`Exception calling ${l} (${c.join(", ")})`;throw this.events.fatalError$.next({id:l,category:Qs.WTF,message:d,thrown:u}),u}}}})}initVideo(e){var i,s,n;this.config=e;let{container:t,...r}=e;return this.tracer.log("initVideo",It(r)),this.domContainer=wS(e),this.chromecastInitializer.contentId=(i=e.meta)==null?void 0:i.videoId,this.providerContainer=new fa({sources:e.sources,meta:(s=e.meta)!=null?s:{},failoverHosts:(n=e.failoverHosts)!=null?n:[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,tracer:this.tracer,logger:this.logger,abrLogger:this.abrLogger},tuning:this.tuning,volumeMultiplier:e.volumeMultiplier}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.initTracerSubscription(),this.providerContainer.init(),this.setMuted(this.tuning.isAudioDisabled),this.initDebugTelemetry(),this.initWakeLock(),this}destroy(){var e;this.tracer.log("destroy"),window.clearTimeout(this.hasLiveOffsetByPausedTimer),this.events.willDestruct$.next(),this.stop(),(e=this.providerContainer)==null||e.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe(),this.tracer.end()}prepare(){let e=this.desiredState.playbackState;return this.tracer.log("prepare",{currentPlayBackState:e.getState()}),e.getState()==="stopped"&&e.startTransitionTo("ready"),this}play(){let e=()=>{let t=this.desiredState.playbackState;this.tracer.log("play",{currentPlayBackState:t.getState()}),t.getState()!=="playing"&&t.startTransitionTo("playing")};return document.hidden&&this.tuning.autoplayOnlyInActiveTab&&!Ti()?(this.tracer.log("request play from hidden tab"),oc(document,"visibilitychange").pipe(st()).subscribe(e)):e(),this}pause(){let e=this.desiredState.playbackState;return this.tracer.log("pause",{currentPlayBackState:e.getState()}),e.getState()!=="paused"&&e.startTransitionTo("paused"),this}stop(){let e=this.desiredState.playbackState;return this.tracer.log("stop",{currentPlayBackState:e.getState()}),e.getState()!=="stopped"&&e.startTransitionTo("stopped"),this}seekTime(e,t=!0){let r=this.info.duration$.getValue(),i=this.info.isLive$.getValue(),s=e;return e>=r&&!i&&(s=r-.1),this.tracer.log("seekTime",{duration:r,isLive:i,time:e,calculatedTime:s,forcePrecise:t}),this.events.willSeek$.next({from:this.getExactTime(),to:s}),this.desiredState.seekState.setState({state:"requested",position:s*1e3,forcePrecise:t}),this}seekPercent(e){let t=this.info.duration$.getValue();return this.tracer.log("seekPercent",{percent:e,duration:t}),isFinite(t)&&this.seekTime(Math.abs(t)*e,!1),this}setVolume(e){let t=this.tuning.isAudioDisabled||this.desiredState.volume.getState().muted;return this.tracer.log("setVolume",{volume:e,isAudioDisabled:this.tuning.isAudioDisabled,isDesiredStateMuted:this.desiredState.volume.getState().muted,chromecastState:this.chromecastInitializer.castState$.getValue(),muted:t}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setVolume(e):this.desiredState.volume.startTransitionTo({volume:e,muted:t}),this}setMuted(e){let t=this.tuning.isAudioDisabled||e;return this.tracer.log("setMuted",{isMuted:e,isAudioDisabled:this.tuning.isAudioDisabled,desiredStateVolume:this.desiredState.volume.getState().volume,chromecastState:this.chromecastInitializer.castState$.getValue(),muted:t}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setMuted(t):this.desiredState.volume.startTransitionTo({volume:this.desiredState.volume.getState().volume,muted:t}),this}setVideoStream(e){return this.desiredState.videoStream.startTransitionTo(e),this}setAudioStream(e){return this.desiredState.audioStream.startTransitionTo(e),this}setQuality(e){Ys(this.providerContainer);let t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();return this.tracer.log("setQuality",{isDelayed:t.length===0,quality:e}),this.desiredState.videoTrack.getState()===void 0&&this.desiredState.videoTrack.getPrevState()===void 0&&t.length===0?this.providerContainer.providerOutput.availableVideoTracks$.pipe(ae(r=>r.length>0),st()).subscribe(r=>{this.setVideoTrackIdByQuality(r,e)}):t.length>0&&this.setVideoTrackIdByQuality(t,e),this}setAutoQuality(e){return this.tracer.log("setAutoQuality",{enable:e}),this.desiredState.autoVideoTrackSwitching.startTransitionTo(e),this}setAutoQualityLimits(e){return this.tracer.log("setAutoQualityLimits",It(e)),this.desiredState.autoVideoTrackLimits.startTransitionTo(e),this}setPlaybackRate(e){var r;Ys(this.providerContainer);let t=(r=this.providerContainer)==null?void 0:r.providerOutput.element$.getValue();return this.tracer.log("setPlaybackRate",{playbackRate:e,isVideoElementAvailable:!!t}),t&&(this.desiredState.playbackRate.setState(e),t.playbackRate=e),this}setExternalTextTracks(e){return e.length&&this.tracer.log("setExternalTextTracks",It(e)),this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>({type:"external",...t}))),this}selectTextTrack(e){var t;return kS(e,this.desiredState.currentTextTrack,(t=this.providerContainer)==null?void 0:t.providerOutput.availableTextTracks$,r=>r.id===e),this.tracer.log("selectTextTrack",{textTrackId:e}),this}setTextTrackCueSettings(e){return this.tracer.log("setTextTrackCueSettings",{...e}),this.desiredState.textTrackCuesSettings.startTransitionTo(e),this}setLooped(e){return this.tracer.log("setLooped",{isLooped:e}),this.desiredState.isLooped.startTransitionTo(e),this}toggleChromecast(){this.tracer.log("toggleChromecast"),this.chromecastInitializer.toggleConnection()}startCameraManualRotation(e,t){let r=this.getScene3D();return this.tracer.log("startCameraManualRotation",{isScene3DAvailable:!!r,mx:e,my:t}),r&&r.startCameraManualRotation(e,t),this}stopCameraManualRotation(e=!1){let t=this.getScene3D();return this.tracer.log("stopCameraManualRotation",{isScene3DAvailable:!!t,immediate:e}),t&&t.stopCameraManualRotation(e),this}moveCameraFocusPX(e,t){let r=this.getScene3D();if(this.tracer.log("moveCameraFocusPX",{isScene3DAvailable:!!r,dxpx:e,dypx:t}),r){let i=r.getCameraRotation(),s=r.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:i.x+s.x,y:i.y+s.y})}return this}holdCamera(){let e=this.getScene3D();return e&&e.holdCamera(),this}releaseCamera(){let e=this.getScene3D();return e&&e.releaseCamera(),this}getExactTime(){if(!this.providerContainer)return 0;let e=this.providerContainer.providerOutput.element$.getValue();if(O$(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),r=t.state==="none"?void 0:t.position;return B$(r)?r/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}getScene3D(){var t,r;let e=(t=this.providerContainer)==null?void 0:t.current$.getValue();if((r=e==null?void 0:e.provider)!=null&&r.scene3D)return e.provider.scene3D}setIntrinsicVideoSize(...e){let t={width:e.reduce((r,{width:i})=>r||i||0,0),height:e.reduce((r,{height:i})=>r||i||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add(Tt(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(D(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(D(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(D(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(D(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(D(e=>e.to)).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(ae(({from:e})=>e==="stopped"),st()).subscribe(()=>{this.initedAt=zs(),this.events.inited$.next()})).add(this.desiredState.playbackState.stateChangeEnded$.subscribe(e=>{switch(e.to){case"ready":this.events.ready$.next();break;case"playing":this.isPlaybackStarted||this.events.started$.next(),this.isPlaybackStarted=!0,this.events.playing$.next();break;case"paused":this.events.paused$.next();break;case"stopped":this.events.stopped$.next()}})).add(this.desiredState.playbackState.stateChangeStarted$.subscribe(e=>{switch(e.to){case"paused":this.events.willPause$.next();break;case"playing":this.isPlaybackStarted?this.events.willResume$.next():this.events.willStart$.next();break;case"stopped":this.events.willStop$.next();break;default:}}))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();this.tracer.log("willSeekEvent",It(n)),n.state==="requested"?this.desiredState.seekState.setState({...n,state:"applying"}):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:Qs.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.seekedEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();this.tracer.log("seekedEvent",It(n)),n.state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe(D(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(D(n=>n.destination),_()).subscribe(()=>this.isPlaybackStarted=!1)).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add(e.providerOutput.availableVideoTracks$.pipe(D(n=>n.map(({quality:o})=>o).sort((o,u)=>MS(o)?1:MS(u)?-1:_$(u,o)?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(_()).subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{this.info.currentQuality$.next(n==null?void 0:n.quality),this.info.videoBitrate$.next(n==null?void 0:n.bitrate)})).add(e.providerOutput.currentVideoSegmentLength$.pipe(_((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.pipe(_((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe(_()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(_()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(_()).subscribe(this.info.httpConnectionReused$)).add(e.providerOutput.currentTextTrack$.subscribe(this.info.currentTextTrack$)).add(e.providerOutput.availableTextTracks$.subscribe(this.info.availableTextTracks$)).add(e.providerOutput.autoVideoTrackLimitingAvailable$.subscribe(this.info.autoQualityLimitingAvailable$)).add(e.providerOutput.autoVideoTrackLimits$.subscribe(n=>{this.desiredState.autoVideoTrackLimits.setState(n!=null?n:{})})).add(e.providerOutput.currentBuffer$.pipe(D(n=>n?{start:n.from,end:n.to}:{start:0,end:0})).subscribe(this.info.currentBuffer$)).add(e.providerOutput.duration$.subscribe(this.info.duration$)).add(e.providerOutput.isBuffering$.subscribe(this.info.isBuffering$)).add(e.providerOutput.isLive$.subscribe(this.info.isLive$)).add(e.providerOutput.canChangePlaybackSpeed$.subscribe(this.info.canChangePlaybackSpeed$)).add(e.providerOutput.liveTime$.subscribe(this.info.liveTime$)).add(e.providerOutput.liveBufferTime$.subscribe(this.info.liveBufferTime$)).add(yt({hasLiveOffsetByPaused:Tt(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(D(n=>n.to),_(),D(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(yt({atLiveEdge:yt({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:nc({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(D(({isLive:n,position:o,isLowLatency:u})=>{let c=this.getActiveLiveDelay(u);return n&&Math.abs(o)<c/1e3}),_(),LS(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(D(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add(yt({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(D(({isLive:n,position:o,duration:u})=>n&&(Math.abs(u)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),_(),LS(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(D(n=>n.muted),_()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(D(n=>n.volume),_()).subscribe(this.info.volume$)).add(nc({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(Tt(e.providerOutput.endedEvent$.pipe(RS(!0)),e.providerOutput.seekedEvent$.pipe(RS(!1))).pipe(_()).subscribe(this.info.isEnded$)).add(e.providerOutput.endedEvent$.subscribe(this.events.ended$)).add(e.providerOutput.loopedEvent$.subscribe(this.events.looped$)).add(e.providerError$.subscribe(this.events.managedError$)).add(e.volumeMultiplierError$.subscribe(this.events.managedError$)).add(e.noAvailableProvidersError$.pipe(D(n=>({id:n?`No${n}`:"NoProviders",category:Qs.VIDEO_PIPELINE,message:n?`${n} was forced but failed or not available`:"No suitable providers or all providers failed"}))).subscribe(this.events.fatalError$)).add(e.providerOutput.element$.subscribe(this.experimental.element$)).add(e.providerOutput.firstBytesEvent$.pipe(st(),D(n=>n!=null?n:zs()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe(st(),D(()=>zs()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(st(),D(()=>zs()-this.initedAt)).subscribe(this.events.canplay$)).add(this.throughputEstimator.throughput$.subscribe(this.info.throughputEstimation$)).add(this.throughputEstimator.rtt$.subscribe(this.info.rttEstimation$)).add(e.providerOutput.availableSources$.subscribe(this.info.availableSources$));let t=new P(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let r=new P(!0);this.subscription.add(e.current$.subscribe(()=>r.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(ae(({to:n})=>n==="playing"),st()).subscribe(()=>r.next(!1)));let i=0,s=Tt(e.providerOutput.isBuffering$,t,r).pipe(D(()=>{let n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||r.getValue();return n&&!o}),_());this.subscription.add(s.subscribe(n=>{n?i=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(i),this.info.isStalled$.next(!1))})),this.subscription.add(Tt(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{let n=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:n==null?void 0:n.videoWidth,height:n==null?void 0:n.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{var u,c;let o=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:(u=n==null?void 0:n.size)==null?void 0:u.width,height:(c=n==null?void 0:n.size)==null?void 0:c.height},{width:o==null?void 0:o.videoWidth,height:o==null?void 0:o.videoHeight})})).add(e.providerOutput.is3DVideo$.subscribe(this.info.is3DVideo$)),this.subscription.add(Tt(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(),c=e.providerOutput.elementVisible$.getValue(),l=this.chromecastInitializer.castState$.getValue(),d;l==="CONNECTED"?d="second_screen":u?c?n?d="pip":o?d="fullscreen":d="inline":d="invisible":d="none",this.info.surface$.getValue()!==d&&this.info.surface$.next(d)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(D(e=>e==null?void 0:e.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){let t=new $S;this.subscription.add(t),this.subscription.add(e.current$.pipe(_((r,i)=>r.provider===i.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(ae(r=>r.length>0),st()).subscribe(r=>{this.setStartingVideoTrack(r)}))}))}setStartingVideoTrack(e){var i;let t,r=(i=this.desiredState.videoTrack.getState())==null?void 0:i.quality;r&&(t=e.find(({quality:s})=>s===r),t||this.setAutoQuality(!0)),t||(t=bt(e,{container:this.domContainer.getBoundingClientRect(),throughput: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(Tt(this.desiredState.videoTrack.stateChangeStarted$.pipe(D(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(D(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(D(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(D(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(D(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(D(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(D(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(D(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(D(e=>({component:"desiredState",message:`[${e.entity} change] ${e.type}: ${JSON.stringify(e.transition)}`}))).subscribe(this.logger.log)),this.subscription.add(this.logger.log$.subscribe(this.events.log$))}initDebugTelemetry(){var t;let e=(t=this.providerContainer)==null?void 0:t.providerOutput;Ys(this.providerContainer),Ys(e),Ym(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(r=>Wm(r)),this.providerContainer.current$.subscribe(({type:r})=>mi("provider",r)),e.duration$.subscribe(r=>mi("duration",r)),e.availableVideoTracks$.pipe(ae(r=>!!r.length),st()).subscribe(r=>mi("tracks",r)),this.events.fatalError$.subscribe(new re("fatalError")),this.events.managedError$.subscribe(new re("managedError")),e.position$.subscribe(new re("position")),e.currentVideoTrack$.pipe(D(r=>r==null?void 0:r.quality)).subscribe(new re("quality")),this.info.currentBuffer$.subscribe(new re("buffer")),e.isBuffering$.subscribe(new re("isBuffering"))].forEach(r=>this.subscription.add(r)),mi("codecs",Mb())}initTracerSubscription(){let e=CS(this.tracer.log.bind(this.tracer)),t=CS(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(_()).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(yt({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe(ae(({currentQuality:r,videoBitrate:i})=>!!r&&!!i),_((r,i)=>r.currentQuality===i.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe(ae(r=>r>0),_()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe(ae(r=>r>0),_()).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(yt({currentBuffer:this.info.currentBuffer$.pipe(ae(r=>r.end>0),_((r,i)=>r.end===i.end&&r.start===i.start)),position:this.info.position$.pipe(_())}).pipe(uc(1e3)).subscribe(e("currentBufferAndPosition"))).add(this.info.duration$.pipe(_()).subscribe(e("duration"))).add(this.info.isBuffering$.subscribe(e("isBuffering"))).add(this.info.isLive$.pipe(_()).subscribe(e("isLive"))).add(this.info.canChangePlaybackSpeed$.pipe(_()).subscribe(e("canChangePlaybackSpeed"))).add(yt({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe(ae(({liveTime:r,liveBufferTime:i})=>!!r&&!!i),uc(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe(_(),ae(r=>r===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe(_(),ae(r=>r===!0)).subscribe(e("atLiveDurationEdge"))).add(this.info.muted$.pipe(_()).subscribe(e("muted"))).add(this.info.volume$.pipe(_()).subscribe(e("volume"))).add(this.info.isEnded$.pipe(_(),ae(r=>r===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add(yt({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe(ae(({throughputEstimation:r,rtt:i})=>!!r&&!!i),uc(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe(_(),ae(r=>r===!0)).subscribe(e("is3DVideo"))).add(this.info.surface$.subscribe(e("surface"))).add(this.events.ended$.subscribe(e("ended"))).add(this.events.looped$.subscribe(e("looped"))).add(this.events.managedError$.subscribe(t("managedError"))).add(this.events.fatalError$.subscribe(t("fatalError"))).add(this.events.firstBytes$.subscribe(e("firstBytes"))).add(this.events.firstFrame$.subscribe(e("firstFrame"))).add(this.events.canplay$.subscribe(e("canplay")))}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e,t=()=>{e==null||e.release(),e=void 0},r=async()=>{t(),e=await window.navigator.wakeLock.request("screen").catch(i=>{i instanceof DOMException&&i.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:Qs.DOM,message:String(i)})})};this.subscription.add(Tt(oc(document,"visibilitychange"),oc(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{let i=document.visibilityState==="visible",s=this.desiredState.playbackState.getState()==="playing",n=!!e&&!(e!=null&&e.released);i&&s?n||r():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){let r=e.find(i=>i.quality===t);this.tracer.log("setVideoTrackIdByQuality",It({quality:t,availableTracks:It(e),track:It(r),isAutoQuality:!r})),r?this.desiredState.videoTrack.startTransitionTo(r):this.setAutoQuality(!0)}getActiveLiveDelay(e=!1){return e?this.tuning.live.lowLatencyActiveLiveDelay:this.tuning.live.activeLiveDelay}};import{Subscription as IG,Observable as EG,Subject as xG,ValueSubject as PG,VideoQuality as AG}from"@vkontakte/videoplayer-shared";var wG=`@vkontakte/videoplayer-core@${Dc}`;export{ya as ChromecastState,dn as HttpConnectionType,EG as Observable,ue as PlaybackState,Ks as Player,wG as SDK_VERSION,xG as Subject,IG as Subscription,pn as Surface,Dc as VERSION,PG as ValueSubject,lt as VideoFormat,AG as VideoQuality};
|
|
112
|
+
`;var Xs=class{constructor(e,t,r){this.videoInitialized=!1;this.active=!1;this.container=e,this.sourceVideoElement=t,this.params=r,this.canvas=this.createCanvas();let i=this.canvas.getContext("webgl");if(!i)throw new Error("Could not initialize WebGL context");this.gl=i,this.container.appendChild(this.canvas),this.camera=new Ks(this.params.fov,this.params.orientation),this.cameraRotationManager=new Js(this.camera,{rotationSpeed:this.params.rotationSpeed,maxYawAngle:this.params.maxYawAngle,rotationSpeedCorrection:this.params.rotationSpeedCorrection,degreeToPixelCorrection:this.params.degreeToPixelCorrection,speedFadeTime:this.params.speedFadeTime,speedFadeThreshold:this.params.speedFadeThreshold}),this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.textureMappingBuffer=this.createTextureMappingBuffer(),this.updateTextureMappingBuffer(),this.program=this.createProgram(),this.videoTexture=this.createTexture(),this.gl.useProgram(this.program),this.videoElementDataLoadedFn=this.onDataLoadedHandler.bind(this),this.renderFn=this.render.bind(this)}play(){this.active||(this.videoInitialized?this.doPlay():this.sourceVideoElement.readyState>=2?(this.videoInitialized=!0,this.doPlay()):this.sourceVideoElement.addEventListener("loadeddata",this.videoElementDataLoadedFn))}stop(){this.active=!1}startCameraManualRotation(e,t){this.cameraRotationManager.setRotationSpeed(e*this.params.rotationSpeed,t*this.params.rotationSpeed,0),this.cameraRotationManager.startRotation()}stopCameraManualRotation(e=!1){this.cameraRotationManager.stopRotation(e)}turnCamera(e,t){this.cameraRotationManager.turnCamera(e,t)}pointCameraTo(e,t){this.cameraRotationManager.pointCameraTo(e,t)}pixelToDegree(e){return{x:this.params.degreeToPixelCorrection*this.params.fov.x*-e.x/this.viewportWidth,y:this.params.degreeToPixelCorrection*this.params.fov.y*e.y/this.viewportHeight}}getCameraRotation(){return this.camera.orientation}holdCamera(){this.cameraRotationManager.stopRotation(!0)}releaseCamera(){this.cameraRotationManager.onCameraRelease()}destroy(){this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),this.stop(),this.canvas.remove()}setViewportSize(e,t){this.viewportWidth=e,this.viewportHeight=t,this.canvas.width=this.viewportWidth,this.canvas.height=this.viewportHeight,this.gl.viewport(0,0,this.canvas.width,this.canvas.height)}onDataLoadedHandler(){this.videoInitialized=!0,this.doPlay()}doPlay(){this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.active=!0,this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),requestAnimationFrame(this.renderFn)}render(e){this.cameraRotationManager.tick(e),this.updateTexture(),this.updateTextureMappingBuffer();let t=this.gl.getAttribLocation(this.program,"a_vertex"),r=this.gl.getAttribLocation(this.program,"a_texel"),i=this.gl.getUniformLocation(this.program,"u_texture"),s=this.gl.getUniformLocation(this.program,"u_focus");this.gl.enableVertexAttribArray(t),this.gl.enableVertexAttribArray(r),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.vertexBuffer),this.gl.vertexAttribPointer(t,2,this.gl.FLOAT,!1,0,0),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.vertexAttribPointer(r,2,this.gl.FLOAT,!1,0,0),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.uniform1i(i,0),this.gl.uniform2f(s,-this.camera.orientation.x,-this.camera.orientation.y),this.gl.drawArrays(this.gl.TRIANGLE_FAN,0,4),this.gl.bindTexture(this.gl.TEXTURE_2D,null),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),this.gl.disableVertexAttribArray(t),this.gl.disableVertexAttribArray(r),this.active&&requestAnimationFrame(this.renderFn)}createShader(e,t){let r=this.gl.createShader(t);if(!r)throw this.destroy(),new Error(`Could not create shader (${t})`);if(this.gl.shaderSource(r,e),this.gl.compileShader(r),!this.gl.getShaderParameter(r,this.gl.COMPILE_STATUS))throw this.destroy(),new Error("An error occurred while compiling the shader: "+this.gl.getShaderInfoLog(r));return r}createProgram(){let e=this.gl.createProgram();if(!e)throw this.destroy(),new Error("Could not create shader program");let t=this.createShader(aS,this.gl.VERTEX_SHADER),r=this.createShader(sS,this.gl.FRAGMENT_SHADER);if(this.gl.attachShader(e,t),this.gl.attachShader(e,r),this.gl.linkProgram(e),!this.gl.getProgramParameter(e,this.gl.LINK_STATUS))throw this.destroy(),new Error("Could not link shader program.");return e}createTexture(){let e=this.gl.createTexture();if(!e)throw this.destroy(),new Error("Could not create texture");return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.bindTexture(this.gl.TEXTURE_2D,null),e}updateTexture(){this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,!0),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.sourceVideoElement),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}createVertexBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create vertex buffer");let t=1,r=1,i=this.frameHeight/(this.frameWidth/this.viewportWidth);return i>this.viewportHeight?t=this.viewportHeight/i:r=i/this.viewportHeight,this.gl.bindBuffer(this.gl.ARRAY_BUFFER,e),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-t,-r,t,-r,t,r,-t,r]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),e}createTextureMappingBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create texture mapping buffer");return e}calculateTexturePosition(){let e=.5-this.camera.orientation.x/360,t=.5-this.camera.orientation.y/180,r=this.camera.fov.x/360/2,i=this.camera.fov.y/180/2,s=e-r,n=t-i,o=e+r,u=t-i,l=e+r,c=t+i,d=e-r,p=t+i;return[s,n,o,u,l,c,d,p]}updateTextureMappingBuffer(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([...this.calculateTexturePosition()]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}updateFrameSize(){this.frameWidth=this.sourceVideoElement.videoWidth,this.frameHeight=this.sourceVideoElement.videoHeight}createCanvas(){let e=document.createElement("canvas");return e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e}};var rr=class{constructor(e){this.subscription=new PR;this.videoState=new M("stopped");this.elementSize$=new AR(void 0);this.droppedFramesManager=new ws;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new ki;this.audioTrackSwitchHistory=new ki;this.textTracks=[];this.syncPlayback=()=>{var n,o,u;let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),i=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(i.state==="requested"&&(r==null?void 0:r.to)!=="paused"&&e!=="stopped"&&t!=="stopped"){let l=(o=(n=this.liveOffset)==null?void 0:n.getTotalPausedTime())!=null?o:0;this.seek(i.position-l,i.forcePrecise)}if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.player.stop(),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),E(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"),E(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="ready"&&E(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),(u=this.liveOffset)==null||u.pause(),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(r==null?void 0:r.to)==="playing"&&E(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.liveOffset?this.liveOffset.getTotalOffset()/1e3<Math.abs(this.params.output.duration$.getValue())?(this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(0,!1):this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&E(this.params.desiredState.playbackState,"paused");return;default:return SR(e)}}};this.init3DScene=e=>{var r,i,s;if(this.scene3D)return;this.scene3D=new Xs(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:((r=e.projectionData)==null?void 0:r.pose.yaw)||0,y:((i=e.projectionData)==null?void 0:i.pose.pitch)||0,z:((s=e.projectionData)==null?void 0:s.pose.roll)||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});let t=this.elementSize$.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};this.params=e,this.video=de(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(X(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 zs({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode,tracer:this.tracer}),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params,r=fe(this.video),i=this.constructor.name,s=o=>{e.error$.next({id:i,category:sl.WTF,message:`${i} internal logic error`,thrown:o})};return{output:e,desiredState:t,observableVideo:r,genericErrorListener:s,connect:(o,u)=>this.subscription.add(o.subscribe(u,s))}}subscribe(){let{output:e,desiredState:t,observableVideo:r,genericErrorListener:i,connect:s}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe(nS(l=>!!l.length),uS()).subscribe(l=>{this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:r.playing$,pause$:r.pause$,tracks:l})})),s(r.ended$,e.endedEvent$),s(r.looped$,e.loopedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentBuffer$),s(r.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),s(r.loadedMetadata$,e.loadedMetadataEvent$),s(this.player.error$,e.error$),s(this.player.lastConnectionType$,e.httpConnectionType$),s(this.player.lastConnectionReused$,e.httpConnectionReused$),s(this.player.isLive$,e.isLive$),s(this.player.lastRequestFirstBytes$.pipe(nS(IR),uS()),e.firstBytesEvent$),s(this.videoState.stateChangeEnded$.pipe(oS(l=>l.to)),this.params.output.playbackState$),this.subscription.add(r.seeked$.subscribe(e.seekedEvent$,i)),this.subscription.add(ze(this.video,t.isLooped,i)),this.subscription.add(he(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add($e(this.video,t.playbackRate,r.playbackRateState$,i)),s(xR(this.video),this.elementSize$),s(Me(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),E(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),E(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:l})=>{if(l==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map;let c=this.player.getStreams();if(vR(c,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let p=[];for(let h of c.audio){p.push(Qu(h));let f=[];for(let b of h.representations){let g=jg(b);f.push(g),this.audioTracksMap.set(g,{stream:h,representation:b})}this.audioStreamsMap.set(h,f)}this.params.output.availableAudioStreams$.next(p)}let d=[];for(let p of c.video){d.push(zu(p));let h=[];for(let f of p.representations){let b=Hg(f);b&&(h.push(b),this.videoTracksMap.set(b,{stream:p,representation:f}))}this.videoStreamsMap.set(p,h)}this.params.output.availableVideoStreams$.next(d),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)}else l==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},i));let n=l=>e.error$.next({id:"RepresentationSwitch",category:sl.WTF,message:"Switching representations threw",thrown:l});this.subscription.add(Zs(this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,t.videoStream.stateChangeStarted$,t.audioStream.stateChangeStarted$,this.elementSize$,this.params.output.elementVisible$,this.droppedFramesManager.onDroopedVideoFramesLimit$,TR(this.video,"progress")).subscribe(()=>{let l=this.player.state$.getState(),c=this.player.state$.getTransition();if(!["manifest_ready","running"].includes(l)||c)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let d=this.selectVideoAudioRepresentations();if(!d)return;let[p,h]=d,f=this.params.desiredState.autoVideoTrackLimits.getTransition();if(f&&this.params.output.autoVideoTrackLimits$.next(f.to),l==="manifest_ready")this.player.initRepresentations(p.id,h==null?void 0:h.id,this.params.sourceHls);else if(this.player.switchRepresentation("video",p.id).catch(n),h){let b=!!t.audioStream.getTransition();this.player.switchRepresentation("audio",h.id,b).catch(n)}},i)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:l})=>{this.scene3D&&l&&this.scene3D.pointCameraTo(l.x,l.y)})),this.subscription.add(this.elementSize$.subscribe(l=>{this.scene3D&&l&&this.scene3D.setViewportSize(l.width,l.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(nl()).subscribe(l=>{let c=[...this.videoTracksMap.entries()].find(([,{representation:f}])=>f.id===l);if(!c){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[d,{stream:p}]=c,h=this.params.desiredState.videoStream.getTransition();h&&h.to&&h.to.id===p.id&&this.params.desiredState.videoStream.setState(h.to),e.currentVideoTrack$.next(d),e.currentVideoStream$.next(zu(p))},i)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(nl()).subscribe(l=>{let c=[...this.audioTracksMap.entries()].find(([,{representation:f}])=>f.id===l);if(!c){e.currentAudioStream$.next(void 0);return}let[d,{stream:p}]=c,h=this.params.desiredState.audioStream.getTransition();h&&h.to&&h.to.id===p.id&&this.params.desiredState.audioStream.setState(h.to),e.currentAudioStream$.next(Qu(p))},i)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(l=>{var c,d;if(l!=null&&l.is3dVideo&&((c=this.params.tuning.spherical)!=null&&c.enabled))try{this.init3DScene(l),e.is3DVideo$.next(!0)}catch(p){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${p}`})}else this.destroy3DScene(),(d=this.params.tuning.spherical)!=null&&d.enabled&&e.is3DVideo$.next(!1)},i)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,i)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,i));let o=t.playbackState.stateChangeStarted$.pipe(oS(({to:l})=>l==="ready"),nl());this.subscription.add(Zs(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$).subscribe(()=>{let l=t.autoVideoTrackSwitching.getState(),d=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:l?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(d)})),this.subscription.add(Zs(o,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let u=Zs(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,ER(["init"])).pipe(yR(0));this.subscription.add(u.subscribe(this.syncPlayback,i))}selectVideoAudioRepresentations(){var R,U,$,B,N,O,w,L,q,k,x,V,H,W,K,ne,Lt,pt;let{desiredState:e,output:t}=this.params,r=e.autoVideoTrackSwitching.getState(),i=(R=e.videoTrack.getState())==null?void 0:R.id,n=[...this.videoTracksMap.keys()].find(({id:A})=>A===i),o=t.currentVideoTrack$.getValue(),u=((B=($=e.videoStream.getState())!=null?$:n&&((U=this.videoTracksMap.get(n))==null?void 0:U.stream))!=null?B:this.videoStreamsMap.size===1)?this.videoStreamsMap.keys().next().value:void 0;if(!u)return;let l=[...this.videoStreamsMap.keys()].find(({id:A})=>A===u.id),c=l&&this.videoStreamsMap.get(l);if(!c)return;let d=st(this.video.buffered,this.video.currentTime*1e3),p=r?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,h=Math.min(d/Math.min(p,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),f=(N=e.audioStream.getState())!=null?N:this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0,b=(O=[...this.audioStreamsMap.keys()].find(({id:A})=>A===(f==null?void 0:f.id)))!=null?O:this.audioStreamsMap.keys().next().value,g=0;if(b){if(n&&!r)if(this.params.tuning.useSeparateAudioVideoABR){let A=Es(n,c,(w=this.audioStreamsMap.get(b))!=null?w:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);g=Math.max(g,(L=A==null?void 0:A.bitrate)!=null?L:-1/0)}else{let A=qs(n,c,(q=this.audioStreamsMap.get(b))!=null?q:[]);g=Math.max(g,(k=A==null?void 0:A.bitrate)!=null?k:-1/0)}if(o)if(this.params.tuning.useSeparateAudioVideoABR){let A=Es(o,c,(x=this.audioStreamsMap.get(b))!=null?x:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);g=Math.max(g,(V=A==null?void 0:A.bitrate)!=null?V:-1/0)}else{let A=qs(o,c,(H=this.audioStreamsMap.get(b))!=null?H:[]);g=Math.max(g,(W=A==null?void 0:A.bitrate)!=null?W:-1/0)}}let y=xt(c,{container:this.elementSize$.getValue(),throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:g,forwardBufferHealth:h,current:o,visible:this.params.output.elementVisible$.getValue(),history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),I=r?y!=null?y:n:n!=null?n:y,S;this.params.tuning.useSeparateAudioVideoABR?S=b&&xb(I,c,(K=this.audioStreamsMap.get(b))!=null?K:[],{throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:h,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}):S=b&&qs(I,c,(ne=this.audioStreamsMap.get(b))!=null?ne:[]);let v=(Lt=this.videoTracksMap.get(I))==null?void 0:Lt.representation,T=S&&((pt=this.audioTracksMap.get(S))==null?void 0:pt.representation);if(v&&T)return[v,T];if(v&&!T&&this.audioTracksMap.size===0)return[v,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){be(this.video).then(e=>{var t;e||((t=this.liveOffset)==null||t.pause(),this.videoState.setState("paused"),E(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:sl.DOM,thrown:e}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.destroy3DScene(),this.player.destroy(),this.params.output.element$.next(void 0),pe(this.video),this.tracer.end()}};var ma=class extends rr{subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:r}=this.getProviderSubscriptionInfo();r(t.timeUpdate$,e.position$),r(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}};import{combine as lS,interval as wR,map as kR}from"@vkontakte/videoplayer-shared";var ba=class extends rr{constructor(e){super(e),this.liveOffset=new it}subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:r}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),r(t.timeUpdate$,e.liveBufferTime$),r(this.player.liveDuration$,e.duration$),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(lS({interval:wR(1e3),playbackRate:t.playbackRateState$}).subscribe(({playbackRate:i})=>{var s;if(this.videoState.getState()==="playing"){let n=e.position$.getValue()+(i-1);n<=0&&e.position$.next(n),(s=this.liveOffset)==null||s.resetTo(-n*1e3)}})).add(lS({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(kR(({liveBufferTime:i,liveAvailabilityStartTime:s})=>i&&s?i+s:void 0)).subscribe(e.liveTime$)).add(this.player.currentLiveTextRepresentation$.subscribe(i=>{if(i){let s=Gg(i);this.params.output.availableTextTracks$.next([s])}}))}seek(e){this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),r=this.videoState.getState(),i=t==="paused"&&r==="paused",s=-e,n=Math.trunc(s/1e3<=Math.abs(this.params.output.duration$.getValue())?s:0);this.player.seekLive(n).then(()=>{var o;this.params.output.position$.next(e/1e3),(o=this.liveOffset)==null||o.resetTo(n,i)})}};var dS=Ye(ys(),1);import{assertNever as ga,assertNonNullable as cS,debounce as RR,ErrorCategory as en,filter as $R,isNonNullable as LR,isNullable as MR,map as tn,merge as CR,Observable as DR,observableFrom as BR,Subscription as OR,videoSizeToQuality as VR}from"@vkontakte/videoplayer-shared";var je={};var jr=(a,e)=>new DR(t=>{let r=(i,s)=>t.next(s);return a.on(e,r),()=>a.off(e,r)}),Sa=class{constructor(e){this.subscription=new OR;this.videoState=new M("initializing");this.textTracksManager=new Je;this.trackLevels=new Map;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),i=this.params.desiredState.seekState.getState();if(e!=="initializing")switch((r==null?void 0:r.to)!=="paused"&&i.state==="requested"&&this.seek(i.position),t){case"stopped":switch(e){case"stopped":break;case"ready":case"playing":case"paused":this.stop();break;default:ga(e)}break;case"ready":switch(e){case"stopped":this.prepare();break;case"ready":case"playing":case"paused":break;default:ga(e)}break;case"playing":switch(e){case"playing":break;case"stopped":this.prepare();break;case"ready":case"paused":this.playIfAllowed();break;default:ga(e)}break;case"paused":switch(e){case"paused":break;case"stopped":this.prepare();break;case"ready":this.videoState.setState("paused"),E(this.params.desiredState.playbackState,"paused");break;case"playing":this.pause();break;default:ga(e)}break;default:ga(t)}};this.video=de(e.container,e.tuning),this.params=e,this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(X(this.params.source.url)),this.loadHlsJs()}destroy(){var e,t;this.subscription.unsubscribe(),this.trackLevels.clear(),this.textTracksManager.destroy(),(e=this.hls)==null||e.detachMedia(),(t=this.hls)==null||t.destroy(),this.params.output.element$.next(void 0),pe(this.video)}loadHlsJs(){let e=!1,t=i=>{e||this.params.output.error$.next({id:i==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:en.NETWORK,message:"Failed to load Hls.js",thrown:i}),e=!0},r=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);(0,dS.default)(import("hls.js").then(i=>{e||(je.Hls=i.default,je.Events=i.default.Events,this.init())},t),()=>{window.clearTimeout(r),e=!0})}init(){cS(je.Hls,"hls.js not loaded"),this.hls=new je.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState("stopped")}subscribe(){cS(je.Events,"hls.js not loaded");let{desiredState:e,output:t}=this.params,r=l=>{t.error$.next({id:"HlsJsProvider",category:en.WTF,message:"HlsJsProvider internal logic error",thrown:l})},i=fe(this.video),s=(l,c)=>this.subscription.add(l.subscribe(c,r));s(i.timeUpdate$,t.position$),s(i.durationChange$,t.duration$),s(i.ended$,t.endedEvent$),s(i.looped$,t.loopedEvent$),s(i.error$,t.error$),s(i.isBuffering$,t.isBuffering$),s(i.currentBuffer$,t.currentBuffer$),s(i.loadStart$,t.firstBytesEvent$),s(i.loadedMetadata$,t.loadedMetadataEvent$),s(i.playing$,t.firstFrameEvent$),s(i.canplay$,t.canplay$),s(i.seeked$,t.seekedEvent$),s(i.inPiP$,t.inPiP$),s(i.inFullscreen$,t.inFullscreen$),this.subscription.add(ze(this.video,e.isLooped,r)),this.subscription.add(he(this.video,e.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add($e(this.video,e.playbackRate,i.playbackRateState$,r)),s(Me(this.video),t.elementVisible$),s(this.videoState.stateChangeEnded$.pipe(tn(l=>l.to)),this.params.output.playbackState$),this.subscription.add(jr(this.hls,je.Events.ERROR).subscribe(l=>{var c;l.fatal&&t.error$.next({id:["HlsJsFatal",l.type,l.details].join("_"),category:en.WTF,message:`HlsJs fatal ${l.type} ${l.details}, ${(c=l.err)==null?void 0:c.message} ${l.reason}`,thrown:l.error})})),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),E(e.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),E(e.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{var l;((l=this.videoState.getTransition())==null?void 0:l.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),s(jr(this.hls,je.Events.MANIFEST_PARSED).pipe(tn(({levels:l})=>l.reduce((c,d)=>{var I,S;let p=d.name||d.height.toString(10),{width:h,height:f}=d,b=(S=Et((I=d.attrs.QUALITY)!=null?I:""))!=null?S:VR({width:h,height:f});if(!b)return c;let g=d.attrs["FRAME-RATE"]?parseFloat(d.attrs["FRAME-RATE"]):void 0,y={id:p.toString(),quality:b,bitrate:d.bitrate/1e3,size:{width:h,height:f},fps:g};return this.trackLevels.set(p,{track:y,level:d}),c.push(y),c},[]))),t.availableVideoTracks$),s(jr(this.hls,je.Events.MANIFEST_PARSED),l=>{if(l.subtitleTracks.length>0){let c=[];for(let d of l.subtitleTracks){let p=d.name,h=d.attrs.URI||"",f=d.lang;c.push({id:p,url:h,language:f,type:"internal"})}e.internalTextTracks.startTransitionTo(c)}}),s(jr(this.hls,je.Events.LEVEL_LOADING).pipe(tn(({url:l})=>X(l))),t.hostname$),s(jr(this.hls,je.Events.FRAG_CHANGED),l=>{var p,h,f,b;let{video:c,audio:d}=l.frag.elementaryStreams;t.currentVideoSegmentLength$.next((((p=c==null?void 0:c.endPTS)!=null?p:0)-((h=c==null?void 0:c.startPTS)!=null?h:0))*1e3),t.currentAudioSegmentLength$.next((((f=d==null?void 0:d.endPTS)!=null?f:0)-((b=d==null?void 0:d.startPTS)!=null?b:0))*1e3)}),this.subscription.add(yt(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,l=>{this.hls.nextLevel=l?-1:this.hls.currentLevel,this.hls.loadLevel=l?-1:this.hls.loadLevel},{onError:r}));let n=l=>{var c;return(c=Array.from(this.trackLevels.values()).find(({level:d})=>d===l))==null?void 0:c.track},o=jr(this.hls,je.Events.LEVEL_SWITCHED).pipe(tn(({level:l})=>n(this.hls.levels[l])));o.pipe($R(LR)).subscribe(t.currentVideoTrack$,r),this.subscription.add(yt(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel]),l=>{var f;if(MR(l))return;let c=(f=this.trackLevels.get(l.id))==null?void 0:f.level;if(!c)return;let d=this.hls.levels.indexOf(c),p=this.hls.currentLevel,h=this.hls.levels[p];!h||c.bitrate>h.bitrate?this.hls.nextLevel=d:(this.hls.loadLevel=d,this.hls.loadLevel=d)},{changed$:o,onError:r})),s(i.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);let u=CR(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,BR(["init"])).pipe(RR(0));this.subscription.add(u.subscribe(this.syncPlayback,r))}prepare(){this.videoState.startTransitionTo("ready"),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}async playIfAllowed(){this.videoState.startTransitionTo("playing"),await be(this.video).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:en.DOM,thrown:t}))||(this.videoState.setState("paused"),E(this.params.desiredState.playbackState,"paused",!0))}pause(){this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}stop(){this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.hls.stopLoad(),this.hls.detachMedia(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState("stopped"),E(this.params.desiredState.playbackState,"stopped",!0)}};var pS="X-Playback-Duration",ol=async a=>{var i;let e=await nt(a),t=await e.text(),r=(i=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t))==null?void 0:i[1];return r?parseInt(r,10):e.headers.has(pS)?parseInt(e.headers.get(pS),10):void 0};import{assertNever as HR,combine as jR,debounce as GR,ErrorCategory as an,filter as WR,filterChanged as YR,isNonNullable as fS,isNullable as sn,map as mS,merge as QR,observableFrom as zR,Subscription as KR,ValueSubject as cl,VideoQuality as JR}from"@vkontakte/videoplayer-shared";var ll=Ye(wo(),1);import{videoSizeToQuality as _R,getExponentialDelay as NR}from"@vkontakte/videoplayer-shared";var FR=a=>{let e=null;if(a.QUALITY&&(e=Et(a.QUALITY)),!e&&a.RESOLUTION){let[t,r]=a.RESOLUTION.split("x").map(i=>parseInt(i,10));e=_R({width:t,height:r})}return e!=null?e:null},qR=(a,e)=>{var s,n;let t=a.split(`
|
|
113
|
+
`),r=[],i=[];for(let o=0;o<t.length;o++){let u=t[o],l=u.match(/^#EXT-X-STREAM-INF:(.+)/),c=u.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!l&&!c)){if(l){let d=(0,ll.default)(l[1].split(",").map(I=>I.split("="))),p=(s=d.QUALITY)!=null?s:`stream-${d.BANDWIDTH}`,h=FR(d),f;d.BANDWIDTH&&(f=parseInt(d.BANDWIDTH,10)/1e3||void 0),!f&&d["AVERAGE-BANDWIDTH"]&&(f=parseInt(d["AVERAGE-BANDWIDTH"],10)/1e3||void 0);let b=d["FRAME-RATE"]?parseFloat(d["FRAME-RATE"]):void 0,g;if(d.RESOLUTION){let[I,S]=d.RESOLUTION.split("x").map(v=>parseInt(v,10));I&&S&&(g={width:I,height:S})}let y=new URL(t[++o],e).toString();h&&r.push({id:p,quality:h,url:y,bandwidth:f,size:g,fps:b})}if(c){let d=(0,ll.default)(c[1].split(",").map(b=>b.split("=")).map(([b,g])=>[b,g.replace(/^"|"$/g,"")])),p=(n=d.URI)==null?void 0:n.replace(/playlist$/,"subtitles.vtt"),h=d.LANGUAGE,f=d.NAME;p&&h&&i.push({type:"internal",id:h,label:f,language:h,url:p,isAuto:!1})}}}if(!r.length)throw new Error("Empty manifest");return{qualityManifests:r,textTracks:i}},UR=a=>new Promise(e=>{setTimeout(()=>{e()},a)}),ul=0,hS=async(a,e=a,t)=>{let i=await(await nt(a)).text();ul+=1;try{let{qualityManifests:s,textTracks:n}=qR(i,e);return{qualityManifests:s,textTracks:n}}catch(s){if(ul<=t.manifestRetryMaxCount)return await UR(NR(ul-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),hS(a,e,t)}return{qualityManifests:[],textTracks:[]}},rn=hS;var va=class{constructor(e){this.subscription=new KR;this.videoState=new M("stopped");this.textTracksManager=new Je;this.manifests$=new cl([]);this.liveOffset=new it;this.manifestStartTime$=new cl(void 0);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),r=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(r==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),E(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||n||o){let c=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(c),this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if((i==null?void 0:i.to)!=="paused"&&l.state==="requested"){this.videoState.startTransitionTo("ready"),this.seek(l.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(t){case"ready":r==="ready"?E(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),E(this.params.desiredState.playbackState,"paused")):r==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":r==="paused"?(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(i==null?void 0:i.to)==="playing"&&E(this.params.desiredState.playbackState,"playing");return;case"paused":if(r==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let c=this.liveOffset.getTotalOffset();c>=this.maxSeekBackTime$.getValue()&&(c=0,this.liveOffset.resetTo(c)),this.liveOffset.resume(),this.params.output.position$.next(-c/1e3),this.prepare()}else(i==null?void 0:i.to)==="paused"&&(E(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return HR(t)}};var t;this.params=e,this.video=de(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:JR.INVARIANT,url:this.params.source.url},rn(ee(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:r})=>{r.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:an.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),this.manifests$.next([this.masterManifest,...r])},r=>this.params.output.error$.next({id:"ExtractHlsQualities",category:an.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:r})),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(X(this.params.source.url)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.maxSeekBackTime$=new cl((t=e.source.maxSeekBackTime)!=null?t:1/0),this.subscribe()}selectManifest(){var u,l,c,d;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,r=e.getState(),i=t.getTransition(),s=(d=(c=(u=i==null?void 0:i.to)==null?void 0:u.id)!=null?c:(l=t.getState())==null?void 0:l.id)!=null?d:"master",n=this.manifests$.getValue();if(!n.length)return;let o=r?"master":s;return r&&!i&&t.startTransitionTo(this.masterManifest),n.find(p=>p.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"HlsLiveProvider",category:an.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},i=fe(this.video),s=(o,u)=>this.subscription.add(o.subscribe(u,r));s(i.ended$,e.endedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(i.loadedMetadata$,e.firstBytesEvent$),s(i.loadedMetadata$,e.loadedMetadataEvent$),s(i.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),r)),this.subscription.add(he(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add($e(this.video,t.playbackRate,i.playbackRateState$,r)),s(Me(this.video),e.elementVisible$),this.textTracksManager.connect(this.video,t,e),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),E(t.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),E(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())==null?void 0:o.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.subscription.add(this.maxSeekBackTime$.pipe(YR(),mS(o=>-o/1e3)).subscribe(this.params.output.duration$,r)),this.subscription.add(i.loadedMetadata$.subscribe(()=>{let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&fS(l.to)){let d=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let p=this.manifests$.getValue().find(h=>h.id===d);p&&(this.params.output.currentVideoTrack$.next(p),this.params.output.hostname$.next(X(p.url)))}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o&&o.state==="requested"&&this.seek(o.position)},r)),this.subscription.add(i.loadedData$.subscribe(()=>{var u,l,c;let o=(c=(l=(u=this.video)==null?void 0:u.getStartDate)==null?void 0:l.call(u))==null?void 0:c.getTime();this.manifestStartTime$.next(o||void 0)},r)),this.subscription.add(jR({startTime:this.manifestStartTime$.pipe(WR(fS)),currentTime:i.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),r)),this.subscription.add(this.manifests$.pipe(mS(o=>o.map(({id:u,quality:l,size:c,bandwidth:d,fps:p})=>({id:u,quality:l,size:c,fps:p,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,r));let n=QR(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,zR(["init"])).pipe(GR(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),pe(this.video)}prepare(){var o,u;let e=this.selectManifest();if(sn(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),r=this.params.desiredState.autoVideoTrackLimits.getState(),i=new URL(e.url);if((t||r)&&e.id===this.masterManifest.id){let{max:l,min:c}=(u=(o=t==null?void 0:t.to)!=null?o:r)!=null?u:{};for(let[d,p]of[[l,"mq"],[c,"lq"]]){let h=String(parseFloat(d||""));p&&d&&i.searchParams.set(p,h)}}let s=this.params.format==="HLS_LIVE_CMAF"?2:0,n=ee(i.toString(),this.liveOffset.getTotalOffset(),s);this.video.setAttribute("src",n),this.video.load(),ol(n).then(l=>{var c;if(!sn(l))this.maxSeekBackTime$.next(l);else{let d=(c=this.params.source.maxSeekBackTime)!=null?c:this.maxSeekBackTime$.getValue();if(sn(d)||!isFinite(d))try{nt(n).then(p=>p.text()).then(p=>{var f;let h=(f=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(p))==null?void 0:f[1];if(h){let b=new URL(h,n).toString();ol(b).then(g=>{sn(g)||this.maxSeekBackTime$.next(g)})}})}catch(p){}}})}playIfAllowed(){be(this.video).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),E(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:an.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,r=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(r),this.params.output.position$.next(-r/1e3),this.params.output.seekedEvent$.next()}};import{assertNever as XR,debounce as ZR,ErrorCategory as dl,fromEvent as pl,isNonNullable as e$,isNullable as t$,map as bS,merge as gS,observableFrom as SS,Subscription as r$,ValueSubject as i$,VideoQuality as a$,clientChecker as s$}from"@vkontakte/videoplayer-shared";var ya=class{constructor(e){this.subscription=new r$;this.videoState=new M("stopped");this.textTracksManager=new Je;this.manifests$=new i$([]);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),r=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(r==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),E(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||n||o){let c=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(c);let{currentTime:d}=this.video;this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:d*1e3,forcePrecise:!0});return}switch((i==null?void 0:i.to)!=="paused"&&l.state==="requested"&&this.seek(l.position),t){case"ready":r==="ready"?E(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),E(this.params.desiredState.playbackState,"paused")):r==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":r==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(i==null?void 0:i.to)==="playing"&&E(this.params.desiredState.playbackState,"playing");return;case"paused":r==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&E(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return XR(t)}};this.params=e,this.video=de(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:a$.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(X(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),rn(ee(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:t,textTracks:r})=>{this.manifests$.next([this.masterManifest,...t]),this.params.tuning.useNativeHLSTextTracks||this.params.desiredState.internalTextTracks.startTransitionTo(r)},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:dl.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){var u,l,c,d;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,r=e.getState(),i=t.getTransition(),s=(d=(c=(u=i==null?void 0:i.to)==null?void 0:u.id)!=null?c:(l=t.getState())==null?void 0:l.id)!=null?d:"master",n=this.manifests$.getValue();if(!n.length)return;let o=r?"master":s;return r&&!i&&t.startTransitionTo(this.masterManifest),n.find(p=>p.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"HlsProvider",category:dl.WTF,message:"HlsProvider internal logic error",thrown:o})},i=fe(this.video),s=(o,u)=>this.subscription.add(o.subscribe(u));if(s(i.timeUpdate$,e.position$),s(i.durationChange$,e.duration$),s(i.ended$,e.endedEvent$),s(i.looped$,e.loopedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(i.loadedMetadata$,e.firstBytesEvent$),s(i.loadedMetadata$,e.loadedMetadataEvent$),s(i.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.seeked$,e.seekedEvent$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe(bS(o=>o.to)),this.params.output.playbackState$),this.subscription.add(ze(this.video,t.isLooped,r)),this.subscription.add(he(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add($e(this.video,t.playbackRate,i.playbackRateState$,r)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),E(t.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),E(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())==null?void 0:o.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},r).add(i.loadedMetadata$.subscribe(()=>{var d;let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&e$(l.to)){let p=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let h=this.manifests$.getValue().find(f=>f.id===p);if(h){this.params.output.currentVideoTrack$.next(h),this.params.output.hostname$.next(X(h.url));let f=this.params.desiredState.playbackRate.getState(),b=(d=this.params.output.element$.getValue())==null?void 0:d.playbackRate;if(f!==b){let g=this.params.output.element$.getValue();g&&(this.params.desiredState.playbackRate.setState(f),g.playbackRate=f)}}}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o.state==="requested"&&this.seek(o.position)},r))),this.subscription.add(this.manifests$.pipe(bS(o=>o.map(({id:u,quality:l,size:c,bandwidth:d,fps:p})=>({id:u,quality:l,size:c,fps:p,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,r)),!s$.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add(gS(pl(o,"addtrack"),pl(o,"removetrack"),pl(o,"change"),SS(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},r))}let n=gS(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,SS(["init"])).pipe(ZR(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),pe(this.video)}prepare(){var s,n;let e=this.selectManifest();if(t$(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),r=this.params.desiredState.autoVideoTrackLimits.getState(),i=new URL(e.url);if((t||r)&&e.id===this.masterManifest.id){let{max:o,min:u}=(n=(s=t==null?void 0:t.to)!=null?s:r)!=null?n:{};for(let[l,c]of[[o,"mq"],[u,"lq"]]){let d=String(parseFloat(l||""));c&&l&&i.searchParams.set(c,d)}}this.video.setAttribute("src",i.toString()),this.video.load()}playIfAllowed(){be(this.video).then(e=>{e||(this.videoState.setState("paused"),E(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:dl.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};import{assertNever as n$,assertNonNullable as vS,debounce as o$,ErrorCategory as yS,isHigher as u$,isHigherOrEqual as l$,isInvariantQuality as TS,isLowerOrEqual as c$,isNonNullable as d$,merge as p$,observableFrom as h$,Subscription as f$,map as m$}from"@vkontakte/videoplayer-shared";var Ta=class{constructor(e){this.subscription=new f$;this.videoState=new M("stopped");this.trackUrls={};this.textTracksManager=new Je;this.syncPlayback=()=>{var u,l,c;let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),E(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let s=this.params.desiredState.autoVideoTrackLimits.getTransition(),n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.seekState.getState();if(s&&e!=="ready"&&!n){this.handleQualityLimitTransition(s.to.max);return}if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(n){let{currentTime:d}=this.video;this.prepare(),o.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:d*1e3,forcePrecise:!0}),n.to&&((u=this.params.desiredState.autoVideoTrackLimits.getState())==null?void 0:u.max)!==((c=(l=this.trackUrls[n.to.id])==null?void 0:l.track)==null?void 0:c.quality)&&this.params.output.autoVideoTrackLimits$.next({max:void 0});return}switch((r==null?void 0:r.to)!=="paused"&&o.state==="requested"&&this.seek(o.position),e){case"ready":t==="ready"?E(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),E(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(r==null?void 0:r.to)==="playing"&&E(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&E(this.params.desiredState.playbackState,"paused");return;default:return n$(e)}};this.params=e,this.video=de(e.container,e.tuning),this.params.output.element$.next(this.video),Object.entries(this.params.source).reverse().forEach(([t,r],i)=>{let s=i.toString(10);this.trackUrls[s]={track:{quality:t,id:s},url:r}}),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next(Object.values(this.trackUrls).map(({track:t})=>t)),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.desiredState.autoVideoTrackSwitching.setState(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.subscribe()}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"MpegProvider",category:yS.WTF,message:"MpegProvider internal logic error",thrown:o})},i=fe(this.video),s=(o,u)=>this.subscription.add(o.subscribe(u,r));s(i.timeUpdate$,e.position$),s(i.durationChange$,e.duration$),s(i.ended$,e.endedEvent$),s(i.looped$,e.loopedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(i.loadedMetadata$,e.firstBytesEvent$),s(i.loadedMetadata$,e.loadedMetadataEvent$),s(i.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.seeked$,e.seekedEvent$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe(m$(o=>o.to)),this.params.output.playbackState$),this.subscription.add(ze(this.video,t.isLooped,r)),this.subscription.add(he(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add($e(this.video,t.playbackRate,i.playbackRateState$,r)),s(Me(this.video),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),E(t.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),E(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{var u,l;((u=this.videoState.getTransition())==null?void 0:u.to)==="ready"&&this.videoState.setState("ready");let o=this.params.desiredState.videoTrack.getTransition();if(o&&d$(o.to)){this.params.desiredState.videoTrack.setState(o.to),this.params.output.currentVideoTrack$.next(this.trackUrls[o.to.id].track);let c=this.params.desiredState.playbackRate.getState(),d=(l=this.params.output.element$.getValue())==null?void 0:l.playbackRate;if(c!==d){let p=this.params.output.element$.getValue();p&&(this.params.desiredState.playbackRate.setState(c),p.playbackRate=c)}}this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.textTracksManager.connect(this.video,t,e);let n=p$(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,h$(["init"])).pipe(o$(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.params.output.element$.next(void 0),pe(this.video)}prepare(){var r;let e=(r=this.params.desiredState.videoTrack.getState())==null?void 0:r.id;vS(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];vS(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=ua(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(X(t))}playIfAllowed(){be(this.video).then(e=>{e||(this.videoState.setState("paused"),E(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:yS.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){var i,s,n,o;let t,r=e;if(e&&((i=this.params.output.currentVideoTrack$.getValue())==null?void 0:i.quality)!==e){let u=(s=Object.values(this.trackUrls).find(d=>!TS(d.track.quality)&&c$(d.track.quality,e)))==null?void 0:s.track,l=(n=this.params.desiredState.videoTrack.getState())==null?void 0:n.id,c=(o=this.trackUrls[l!=null?l:"0"])==null?void 0:o.track;if(u&&c&&l$(c.quality,u.quality)&&(t=u),!t){let d=Object.values(this.trackUrls).filter(h=>!TS(h.track.quality)&&u$(h.track.quality,e)),p=d.length;p&&(t=d[p-1].track)}t&&(r=t.quality)}else if(!e){let u=Object.values(this.trackUrls).map(l=>l.track);t=xt(u,{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},throughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:0,abrLogger:this.params.dependencies.abrLogger})}t&&(this.params.output.currentVideoTrack$.next(t),this.params.desiredState.videoTrack.startTransitionTo(t)),this.params.output.autoVideoTrackLimits$.next({max:r})}};import{assertNever as ES,debounce as v$,merge as xS,observableFrom as y$,Subscription as T$,map as PS,ValueSubject as I$,ErrorCategory as fl,VideoQuality as E$}from"@vkontakte/videoplayer-shared";import{ErrorCategory as b$}from"@vkontakte/videoplayer-shared";var IS=["stun:videostun.mycdn.me:80"],g$=1e3,S$=3,hl=()=>null,nn=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=hl;this.externalStopCallback=hl;this.externalErrorCallback=hl;this.options=this.normalizeOptions(t);let r=e.split("/");this.serverUrl=r.slice(0,r.length-1).join("/"),this.streamKey=r[r.length-1]}onStart(e){try{this.externalStartCallback=e}catch(t){this.handleSystemError(t)}}onStop(e){try{this.externalStopCallback=e}catch(t){this.handleSystemError(t)}}onError(e){try{this.externalErrorCallback=e}catch(t){this.handleSystemError(t)}}connect(){this.connectWS()}disconnect(){try{this.externalStopCallback(),this.closeConnections()}catch(e){this.handleSystemError(e)}}connectWS(){this.ws||(this.ws=new WebSocket(this.serverUrl),this.ws.onopen=this.onSocketOpen.bind(this),this.ws.onmessage=this.onSocketMessage.bind(this),this.ws.onclose=this.onSocketClose.bind(this),this.ws.onerror=this.onSocketError.bind(this))}onSocketOpen(){this.handleLogin()}onSocketClose(e){try{if(!this.ws)return;this.ws=null,e.code>1e3?(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():this.scheduleRetry()):this.externalStopCallback()}catch(t){this.handleRTCError(t)}}onSocketError(e){try{this.externalErrorCallback(new Error(e.toString()))}catch(t){this.handleRTCError(t)}}onSocketMessage(e){try{let t=this.parseMessage(e.data);switch(t.type){case"JOIN":case"CALL_JOIN":this.handleJoinMessage(t);break;case"UPDATE":this.handleUpdateMessage(t);break;case"STATUS":this.handleStatusMessage(t);break}}catch(t){this.handleRTCError(t)}}handleJoinMessage(e){switch(e.inviteType){case"ANSWER":this.handleAnswer(e.sdp);break;case"CANDIDATE":this.handleCandidate(e.candidate);break}}handleStatusMessage(e){switch(e.status){case"UNPUBLISHED":this.handleUnpublished();break}}async handleUpdateMessage(e){try{let t=await this.createOffer();this.peerConnection&&await this.peerConnection.setLocalDescription(t),this.handleAnswer(e.sdp)}catch(t){this.handleRTCError(t)}}async handleLogin(){try{let e={iceServers:[{urls:IS}]};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:b$.WTF,message:e.message})}async onPeerConnectionStream(e){let t=e.streams[0];this.stream&&this.stream.id===t.id||(this.stream=t,this.externalStartCallback(this.stream))}onPeerConnectionIceCandidate(e){e.candidate&&this.send({type:this.signalingType,inviteType:"CANDIDATE",candidate:e.candidate})}onPeerConnectionIceConnectionStateChange(){if(this.peerConnection){let e=this.peerConnection.iceConnectionState;["failed","closed"].indexOf(e)>-1&&(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():(this.closeConnections(),this.scheduleRetry()))}}async createOffer(){let e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");let t=await this.peerConnection.createOffer(e),r=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(r))throw new Error("No h264 codec support error");return t}handleRTCError(e){try{this.externalErrorCallback(e||new Error("RTC connection error"))}catch(t){this.handleSystemError(t)}}handleNetworkError(){try{this.externalErrorCallback(new Error("Network error"))}catch(e){this.handleSystemError(e)}}send(e){this.ws&&this.ws.send(JSON.stringify(e))}parseMessage(e){try{return JSON.parse(e)}catch(t){throw new Error("Can not parse socket message")}}closeConnections(){let e=this.ws;e&&(this.ws=null,e.close(1e3)),this.removePeerConnection()}removePeerConnection(){let e=this.peerConnection;e&&(this.peerConnection=null,e.close(),e.ontrack=null,e.onicecandidate=null,e.oniceconnectionstatechange=null,e=null)}scheduleRetry(){this.retryTimeout=setTimeout(this.connectWS.bind(this),g$)}normalizeOptions(e={}){let t={stunServerList:IS,maxRetryNumber:S$,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var Ia=class{constructor(e){this.videoState=new M("stopped");this.maxSeekBackTime$=new I$(0);this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.pause(),this.video.srcObject=null,this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),E(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let s=this.params.desiredState.videoTrack.getTransition();if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s){this.prepare();return}switch(e){case"ready":t==="paused"?(this.videoState.setState("paused"),E(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(r==null?void 0:r.to)==="playing"&&E(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&E(this.params.desiredState.playbackState,"paused");return;default:return ES(e)}};this.subscription=new T$,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=de(e.container,e.tuning),this.liveStreamClient=new nn(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),pe(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,r=n=>{e.error$.next({id:"WebRTCLiveProvider",category:fl.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};xS(this.videoState.stateChangeStarted$.pipe(PS(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe(PS(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})});let i=fe(this.video),s=(n,o)=>this.subscription.add(n.subscribe(o,r));s(i.timeUpdate$,e.liveTime$),s(i.ended$,e.endedEvent$),s(i.looped$,e.loopedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(Me(this.video),this.params.output.elementVisible$),this.subscription.add(i.durationChange$.subscribe(n=>{e.duration$.next(n===1/0?0:n)})).add(i.canplay$.subscribe(()=>{var n;((n=this.videoState.getTransition())==null?void 0:n.to)==="ready"&&this.videoState.setState("ready")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused")},r)).add(i.playing$.subscribe(()=>{this.videoState.setState("playing")},r)).add(i.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(he(this.video,t.volume,i.volumeState$,r)).add(i.volumeState$.subscribe(e.volume$,r)).add(this.videoState.stateChangeEnded$.subscribe(n=>{switch(n.to){case"stopped":e.position$.next(0),e.duration$.next(0),t.playbackState.setState("stopped");break;case"ready":break;case"paused":t.playbackState.setState("paused");break;case"playing":t.playbackState.setState("playing");break;default:return ES(n.to)}},r)).add(xS(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,y$(["init"])).pipe(v$(0)).subscribe(this.syncPlayback.bind(this),r)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),r)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),r))}onLiveStreamStart(e){this.params.output.element$.next(this.video),this.params.output.duration$.next(0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(X(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:E$.INVARIANT}),this.video.srcObject=e,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:fl.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){be(this.video).then(e=>{e||(this.videoState.setState("paused"),E(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:fl.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var Ea=class{constructor(e){this.iterator=e[Symbol.iterator](),this.next()}next(){this.current=this.iterator.next()}getValue(){if(this.current.done)throw new Error("Iterable is completed");return this.current.value}isCompleted(){return!!this.current.done}};import{assertNever as Aa,assertNonNullable as wt,ErrorCategory as un,filter as $$,isNonNullable as LS,isNullable as L$,map as M$,merge as C$,once as D$,Subject as Ee,Subscription as MS,ValueSubject as C,flattenObject as CS}from"@vkontakte/videoplayer-shared";import{Observable as x$,map as AS,Subscription as P$,Subject as A$}from"@vkontakte/videoplayer-shared";var wS=a=>new x$(e=>{let t=new P$,r=a.desiredPlaybackState$.stateChangeStarted$.pipe(AS(({from:l,to:c})=>`${l}-${c}`)),i=a.desiredPlaybackState$.stateChangeEnded$,s=a.providerChanged$.pipe(AS(({type:l})=>l!==void 0)),n=new A$,o=0,u="unknown";return t.add(r.subscribe(l=>{o&&window.clearTimeout(o),u=l,o=window.setTimeout(()=>n.next(l),a.maxTransitionInterval)})),t.add(i.subscribe(()=>{window.clearTimeout(o),u="unknown",o=0})),t.add(s.subscribe(l=>{o&&(window.clearTimeout(o),o=0,l&&(o=window.setTimeout(()=>n.next(u),a.maxTransitionInterval)))})),t.add(n.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});import{ErrorCategory as kS,Subscription as w$,combine as k$,filter as RS,once as $S}from"@vkontakte/videoplayer-shared";var xa=null,on=null;function ml(){return xa||(xa=new(window.AudioContext||window.webkitAudioContext)),on||(on=new GainNode(xa,{gain:1}),on.connect(xa.destination)),{audioCtx:xa,gainNode:on}}import{clientChecker as R$}from"@vkontakte/videoplayer-shared";var Gr=class Gr{constructor(e,t,r,i,s){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=r;this.volumeMultiplier=i;this.subscriptions=new w$;this.lastAudioContextResumeId=0;!s||!this.isSupported()||i===1||this.subscriptions.add(this.provider$.pipe(RS(n=>!!n.type),$S()).subscribe(({type:n})=>this.subscribe(n)))}subscribe(e){R$.isSafari&&e!=="MPEG"||this.subscriptions.add(k$({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe(RS(({playbackState:t,video:r,volume:{muted:i,volume:s}})=>t==="playing"&&!!r&&!i&&!!s),$S()).subscribe(({video:t})=>this.initAudioContextOnce(t)))}isSupported(){return"AudioContext"in window&&"GainNode"in window&&"MediaElementAudioSourceNode"in window}initAudioContextOnce(e){let{volumeMultiplier:t}=this,{audioCtx:r,gainNode:i}=ml(),s=(Math.random()+1)*999999;this.lastAudioContextResumeId=s,r.resume().then(()=>{var n;if(s!==this.lastAudioContextResumeId)throw new Error(`AudioContext.resume() resolved after ${Gr.errorId} destroyed`);i.gain.value=t;try{new MediaElementAudioSourceNode(r,{mediaElement:e}).connect(i)}catch(o){this.volumeMultiplierError$.next({id:Gr.errorId,category:kS.VIDEO_PIPELINE,message:(n=o==null?void 0:o.message)!=null?n:"initAudioContextOnce: (new MediaElementAudioSourceNode).connect() exception",thrown:o})}}).catch(n=>{var o;this.volumeMultiplierError$.next({id:Gr.errorId,category:kS.VIDEO_PIPELINE,message:(o=n==null?void 0:n.message)!=null?o:"initAudioContextOnce: AudioContext.resume() exception",thrown:n})})}destroy(){let{gainNode:e}=ml();e.gain.value=1,this.subscriptions.unsubscribe(),this.lastAudioContextResumeId=0}};Gr.errorId="VolumeMultiplierManager";var Pa=Gr;var B$={chunkDuration:5e3,maxParallelRequests:5},wa=class{constructor(e){this.current$=new C({type:void 0});this.providerError$=new Ee;this.noAvailableProvidersError$=new Ee;this.volumeMultiplierError$=new Ee;this.providerOutput={position$:new C(0),duration$:new C(1/0),volume$:new C({muted:!1,volume:1}),availableVideoStreams$:new C([]),currentVideoStream$:new C(void 0),availableVideoTracks$:new C([]),currentVideoTrack$:new C(void 0),availableAudioStreams$:new C([]),currentAudioStream$:new C(void 0),availableAudioTracks$:new C([]),currentVideoSegmentLength$:new C(0),currentAudioSegmentLength$:new C(0),isAudioAvailable$:new C(!0),autoVideoTrackLimitingAvailable$:new C(!1),autoVideoTrackLimits$:new C(void 0),currentBuffer$:new C(void 0),isBuffering$:new C(!0),error$:new Ee,warning$:new Ee,willSeekEvent$:new Ee,seekedEvent$:new Ee,loopedEvent$:new Ee,endedEvent$:new Ee,firstBytesEvent$:new Ee,loadedMetadataEvent$:new Ee,firstFrameEvent$:new Ee,canplay$:new Ee,isLive$:new C(void 0),isLowLatency$:new C(!1),canChangePlaybackSpeed$:new C(!0),liveTime$:new C(void 0),liveBufferTime$:new C(void 0),availableTextTracks$:new C([]),currentTextTrack$:new C(void 0),hostname$:new C(void 0),httpConnectionType$:new C(void 0),httpConnectionReused$:new C(void 0),inPiP$:new C(!1),inFullscreen$:new C(!1),element$:new C(void 0),elementVisible$:new C(!0),availableSources$:new C(void 0),is3DVideo$:new C(!1),playbackState$:new C("")};this.subscription=new MS;var o;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer"),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name);let t=Zb([...tg(this.params.tuning),...eg(this.params.tuning)],this.params.tuning.useHlsJs,this.params.tuning.useManagedMediaSource).filter(u=>LS(e.sources[u])),{forceFormat:r,formatsToAvoid:i}=this.params.tuning,s=[];r?s=[r]:i.length?s=[...t.filter(u=>!i.includes(u)),...t.filter(u=>i.includes(u))]:s=t,this.log({message:`Selected formats: ${s.join(" > ")}`}),this.tracer.log("Selected formats",CS(s)),this.screenFormatsIterator=new Ea(s);let n=[...Mu(!0),...Mu(!1)];this.chromecastFormatsIterator=new Ea(n.filter(u=>LS(e.sources[u]))),this.providerOutput.availableSources$.next(e.sources),this.volumeMultiplierManager=new Pa(this.providerOutput,this.current$,this.volumeMultiplierError$,(o=this.params.volumeMultiplier)!=null?o:1,this.params.tuning.useVolumeMultiplier)}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.tracer.end()}initProvider(){let e=this.chooseDestination(),t=this.chooseFormat(e);if(L$(t)){this.handleNoFormatsError(e);return}let r;try{r=this.createProvider(e,t)}catch(i){this.providerError$.next({id:"ProviderNotConstructed",category:un.WTF,message:"Failed to create provider",thrown:i})}r?this.current$.next({type:t,provider:r,destination:e}):this.current$.next({type:void 0})}reinitProvider(){this.tracer.log("reinitProvider"),this.destroyProvider(),this.initProvider()}switchToNextProvider(e){this.tracer.log("switchToNextProvider",{destination:e}),this.destroyProvider(),this.failoverIndex=void 0,this.skipFormat(e),this.initProvider()}destroyProvider(){let e=this.current$.getValue().provider;if(!e)return;this.log({message:"destroyProvider"}),this.tracer.log("destroyProvider");let t=this.providerOutput.position$.getValue()*1e3,r=this.params.desiredState.seekState.getState(),i=r.state!=="none";if(this.params.desiredState.seekState.setState({state:"requested",position:i?r.position:t,forcePrecise:i?r.forcePrecise:!1}),e.scene3D){let n=e.scene3D.getCameraRotation();this.params.desiredState.cameraOrientation.setState({x:n.x,y:n.y})}e.destroy();let s=this.providerOutput.isBuffering$;s.getValue()||s.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),this.tracer.log("createProvider",{destination:e,format:t}),e){case"SCREEN":return this.createScreenProvider(t);case"CHROMECAST":return this.createChromecastProvider(t);default:return Aa(e)}}createScreenProvider(e){let{sources:t,container:r,desiredState:i}=this.params,s=this.providerOutput,n={container:r,source:null,desiredState:i,output:s,dependencies:this.params.dependencies,tuning:this.params.tuning};switch(e){case"DASH_SEP":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_ONDEMAND":case"DASH_STREAMS":{let o=this.applyFailoverHost(t[e]),u=this.applyFailoverHost(t.HLS_ONDEMAND||t.HLS);return wt(o),new ma({...n,source:o,sourceHls:u})}case"DASH_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return wt(o),new ba({...n,source:o})}case"HLS":case"HLS_ONDEMAND":{let o=this.applyFailoverHost(t[e]);return wt(o),Cr||!this.params.tuning.useHlsJs?new ya({...n,source:o}):new Sa({...n,source:o})}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return wt(o),new va({...n,source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case"MPEG":{let o=this.applyFailoverHost(t[e]);return wt(o),new Ta({...n,source:o})}case"DASH_LIVE":{let o=this.applyFailoverHost(t[e]);return wt(o),new Bb({...n,source:o,config:{...B$,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case"WEB_RTC_LIVE":{let o=this.applyFailoverHost(t[e]);return wt(o),new Ia({container:r,source:o,desiredState:i,output:s,dependencies:this.params.dependencies,tuning:this.params.tuning})}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return Aa(e)}}createChromecastProvider(e){let{sources:t,container:r,desiredState:i,meta:s}=this.params,n=this.providerOutput,o=this.params.dependencies.chromecastInitializer.connection$.getValue();return wt(o),new Ei({connection:o,meta:s,container:r,source:t,format:e,desiredState:i,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?"CHROMECAST":"SCREEN"}chooseFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case"CHROMECAST":return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return Aa(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return Aa(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 Aa(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;let t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;let r=i=>{let s=new URL(i);return s.host=t,s.toString()};if(e===void 0)return e;if("type"in e){if(e.type==="raw")return e;if(e.type==="url")return{...e,url:r(e.url)}}return(0,DS.default)(Object.entries(e).map(([i,s])=>[i,r(s)]))}initProviderErrorHandling(){let e=new MS,t=!1,r=0;return e.add(C$(this.providerOutput.error$,wS({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(M$(i=>({id:`ProviderHangup:${i}`,category:un.WTF,message:`A ${i} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;let i=this.params.desiredState.playbackState.transitionEnded$.pipe($$(({to:s})=>s==="playing"),D$()).subscribe(()=>t=!0);e.add(i)})),e.add(this.providerError$.subscribe(i=>{let s=this.current$.getValue().destination,n={error:i,currentDestination:s};if(s==="CHROMECAST")this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider("SCREEN"),()=>this.params.dependencies.chromecastInitializer.disconnect());else{let o=i.category===un.NETWORK,u=i.category===un.FATAL,l=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),c=r<this.params.tuning.providerErrorLimit&&!u,d=l&&!u&&(o&&t||!c);n={...n,isNetworkError:o,isFatalError:u,haveFailoverHost:l,tryFailover:d,canReinitProvider:c},d?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):c?(r++,this.reinitProvider()):this.switchToNextProvider(s!=null?s:"SCREEN")}this.tracer.error("providerError",CS(n))})),e}};import{fromEvent as ln,once as O$,combine as V$,Subscription as BS,ValueSubject as bl,map as _$,filter as N$,isNonNullable as cn,now as xe,safeStorage as gl}from"@vkontakte/videoplayer-shared";var F$=5e3,OS="one_video_throughput",VS="one_video_rtt",ct=window.navigator.connection,_S=()=>{let a=ct==null?void 0:ct.downlink;if(cn(a)&&a!==10)return a*1e3},NS=()=>{let a=ct==null?void 0:ct.rtt;if(cn(a)&&a!==3e3)return a},FS=(a,e,t)=>{let r=t*8,i=r/a;return r/(i+e)},Sl=class a{constructor(e){this.subscription=new BS;this.concurrentDownloads=new Set;var i,s;this.tuningConfig=e;let t=a.load(OS)||(e.useBrowserEstimation?_S():void 0)||F$,r=(s=(i=a.load(VS))!=null?i:e.useBrowserEstimation?NS():void 0)!=null?s:0;if(this.throughput$=new bl(t),this.rtt$=new bl(r),this.rttAdjustedThroughput$=new bl(FS(t,r,e.rttPenaltyRequestSize)),this.throughput=er.getSmoothedValue(t,-1,e),this.rtt=er.getSmoothedValue(r,1,e),e.useBrowserEstimation){let n=()=>{let u=_S();u&&this.throughput.next(u);let l=NS();cn(l)&&this.rtt.next(l)};ct&&"onchange"in ct&&this.subscription.add(ln(ct,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{gl.set(OS,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{gl.set(VS,n.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(V$({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(_$(({throughput:n,rtt:o})=>FS(n,o,e.rttPenaltyRequestSize)),N$(n=>{let o=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(n-o)/o>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,r=xe(),i=new BS;switch(this.subscription.add(i),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:i.add(ln(e,"progress").pipe(O$()).subscribe(s=>{t=s.loaded,r=xe()}));break;case 1:case 0:i.add(ln(e,"loadstart").subscribe(()=>{t=0,r=xe()}));break}i.add(ln(e,"loadend").subscribe(s=>{if(e.status===200){let n=s.loaded,o=xe(),u=n-t,l=o-r;this.addRawSpeed(u,l,1)}this.concurrentDownloads.delete(e),i.unsubscribe()}))}trackStream(e,t=!1){let r=e.getReader();if(!r){e.cancel("Could not get reader");return}let i=0,s=xe(),n=0,o=xe(),u=c=>{this.concurrentDownloads.delete(e),r.releaseLock(),e.cancel(`Throughput Estimator error: ${c}`).catch(()=>{})},l=async({done:c,value:d})=>{if(c)!t&&this.addRawSpeed(i,xe()-s,1),this.concurrentDownloads.delete(e);else if(d){if(t){let p=xe();if(p-o>this.tuningConfig.lowLatency.continuesByteSequenceInterval||p-s>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let f=o-s;f&&this.addRawSpeed(n,f,1,t),n=d.byteLength,s=xe()}else n+=d.byteLength;o=xe()}else i+=d.byteLength,n+=d.byteLength,n>=this.tuningConfig.streamMinSampleSize&&xe()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,xe()-o,this.concurrentDownloads.size),n=0,o=xe());await(r==null?void 0:r.read().then(l,u))}};this.concurrentDownloads.add(e),r==null||r.read().then(l,u)}addRawSpeed(e,t,r=1,i=!1){if(a.sanityCheck(e,t,i)){let s=e*8/t;this.throughput.next(s*r)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,r=!1){let i=e*8/t;return!(!i||!isFinite(i)||i>1e6||i<30||r&&e<1e4||!r&&e<10*1024||!r&&t<=20)}static load(e){var r;let t=gl.get(e);if(cn(t))return(r=parseInt(t,10))!=null?r:void 0}},qS=Sl;import{fillWithDefault as q$,VideoQuality as US}from"@vkontakte/videoplayer-shared";var HS={configName:["core"],throughputEstimator:{type:"EmaAndMa",emaAlphaSlow:.2,emaAlphaFast:.7,emaAlpha:.45,basisTrendChangeCount:10,changeThreshold:.05,useBrowserEstimation:!0,rttPenaltyRequestSize:1*1024*1024,streamMinSampleSize:10*1024,streamMinSampleTime:300,deviationDepth:20,deviationFactor:.5,lowLatency:{continuesByteSequenceInterval:50,maxLastEvaluationTimeout:300}},autoTrackSelection:{bitrateFactorAtEmptyBuffer:1.8,bitrateAudioFactorAtEmptyBuffer:7,bitrateFactorAtFullBuffer:1.2,bitrateAudioFactorAtFullBuffer:5,minVideoAudioRatio:5,minAvailableThroughputAudioRatio:5,usePixelRatio:!0,limitByContainer:!0,containerSizeFactor:2,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldown:3e3,backgroundVideoQualityLimit:US.Q_4320P,activeVideoAreaThreshold:.1},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:US.Q_480P},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,maxSegmentDurationLeftToSelectNextSegment:3e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:3e3,crashOnStallTimeout:25e3,enableSubSegmentBufferFeeding:!0,segmentTimelineTolerance:100,useFetchPriorityHints:!0},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:250,playbackCatchupSpeedup:.05,isActive:!1,delayEstimator:{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:void 0,useWebmBigRequest:!1,webmCodec:"vp9",androidPreferredFormat:"mpeg",preferCMAF:!1,preferWebRTC:!1,preferMultiStream:!1,preferHDR:!1,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,accumulationBufferStallSizeMs:0,requestQuick:!1,useHlsJs:!0,useNativeHLSTextTracks:!1,useManagedMediaSource:!1,useNewPruneBufferStrategy:!1,useNewPartialSegmentFeeding:!1,useSeparateAudioVideoABR:!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},jS=a=>{var e;return{...q$(a,HS),configName:[...(e=a.configName)!=null?e:[],...HS.configName]}};import{assertNonNullable as dn,combine as kt,ErrorCategory as pn,filter as se,filterChanged as _,fromEvent as yl,isNonNullable as Q$,isNullable as z$,Logger as K$,map as D,mapTo as QS,merge as Rt,now as hn,once as dt,Subject as j,Subscription as zS,tap as KS,ValueSubject as P,isHigher as J$,isInvariantQuality as JS,flattenObject as $t,throttle as Tl,getTraceSubscriptionMethod as XS,Tracer as X$}from"@vkontakte/videoplayer-shared";import{merge as U$,map as H$,filter as GS,isNonNullable as j$}from"@vkontakte/videoplayer-shared";var vl=({seekState:a,position$:e})=>U$(a.stateChangeEnded$.pipe(H$(({to:t})=>{var r;return t.state==="none"?void 0:((r=t.position)!=null?r:NaN)/1e3}),GS(j$)),e.pipe(GS(()=>a.getState().state==="none")));import{assertNonNullable as G$}from"@vkontakte/videoplayer-shared";var WS=a=>{let e=typeof a.container=="string"?document.getElementById(a.container):a.container;return G$(e,`Wrong container or containerId {${a.container}}`),e};import{filter as W$,once as Y$}from"@vkontakte/videoplayer-shared";var YS=(a,e,t,r)=>{a!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&(t==null?void 0:t.getValue().length)===0?t.pipe(W$(i=>i.length>0),Y$()).subscribe(i=>{i.find(r)&&e.startTransitionTo(a)}):(a===void 0||t!=null&&t.getValue().find(r))&&e.startTransitionTo(a)};var fn=class{constructor(e={configName:[]},t=X$.createRootTracer(!1)){this.subscription=new zS;this.logger=new K$;this.abrLogger=this.logger.createComponentLog("ABR");this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new P(!1);this.hasLiveOffsetByPausedTimer=0;this.desiredState={playbackState:new M("stopped"),seekState:new M({state:"none"}),volume:new M({volume:1,muted:!1}),videoTrack:new M(void 0),videoStream:new M(void 0),audioStream:new M(void 0),autoVideoTrackSwitching:new M(!0),autoVideoTrackLimits:new M({}),isLooped:new M(!1),playbackRate:new M(1),externalTextTracks:new M([]),internalTextTracks:new M([]),currentTextTrack:new M(void 0),textTrackCuesSettings:new M({}),cameraOrientation:new M({x:0,y:0})};this.info={playbackState$:new P("stopped"),position$:new P(0),duration$:new P(1/0),muted$:new P(!1),volume$:new P(1),availableVideoStreams$:new P([]),currentVideoStream$:new P(void 0),availableQualities$:new P([]),availableQualitiesFps$:new P({}),currentQuality$:new P(void 0),isAutoQualityEnabled$:new P(!0),autoQualityLimitingAvailable$:new P(!1),autoQualityLimits$:new P({}),availableAudioStreams$:new P([]),currentAudioStream$:new P(void 0),availableAudioTracks$:new P([]),isAudioAvailable$:new P(!0),currentPlaybackRate$:new P(1),currentBuffer$:new P({start:0,end:0}),isBuffering$:new P(!0),isStalled$:new P(!1),isEnded$:new P(!1),isLooped$:new P(!1),isLive$:new P(void 0),canChangePlaybackSpeed$:new P(void 0),atLiveEdge$:new P(void 0),atLiveDurationEdge$:new P(void 0),liveTime$:new P(void 0),liveBufferTime$:new P(void 0),currentFormat$:new P(void 0),availableTextTracks$:new P([]),currentTextTrack$:new P(void 0),throughputEstimation$:new P(void 0),rttEstimation$:new P(void 0),videoBitrate$:new P(void 0),hostname$:new P(void 0),httpConnectionType$:new P(void 0),httpConnectionReused$:new P(void 0),surface$:new P("none"),chromecastState$:new P("NOT_AVAILABLE"),chromecastDeviceName$:new P(void 0),intrinsicVideoSize$:new P(void 0),availableSources$:new P(void 0),is3DVideo$:new P(!1),currentVideoSegmentLength$:new P(0),currentAudioSegmentLength$:new P(0)};this.events={inited$:new j,ready$:new j,started$:new j,playing$:new j,paused$:new j,stopped$:new j,willStart$:new j,willResume$:new j,willPause$:new j,willStop$:new j,willDestruct$:new j,watchCoverageRecord$:new j,watchCoverageLive$:new j,managedError$:new j,fatalError$:new j,ended$:new j,looped$:new j,seeked$:new j,willSeek$:new j,firstBytes$:new j,loadedMetadata$:new j,firstFrame$:new j,canplay$:new j,log$:new j};this.experimental={element$:new P(void 0),tuningConfigName$:new P([]),enableDebugTelemetry$:new P(!1),dumpTelemetry:fb};if(this.initLogs(),this.tuning=jS(e),this.tracer=t,this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new Na({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new qS(this.tuning.throughputEstimator),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(r,i,s)=>{let n=Reflect.get(r,i,s);return typeof n!="function"?n:(...o)=>{try{return n.apply(r,o)}catch(u){let l=o.map(p=>JSON.stringify(p,(h,f)=>{let b=typeof f;return["number","string","boolean"].includes(b)?f:f===null?null:`<${b}>`})),c=`Player.${String(i)}`,d=`Exception calling ${c} (${l.join(", ")})`;throw this.events.fatalError$.next({id:c,category:pn.WTF,message:d,thrown:u}),u}}}})}initVideo(e){var i,s,n;this.config=e;let{container:t,...r}=e;return this.tracer.log("initVideo",$t(r)),this.domContainer=WS(e),this.chromecastInitializer.contentId=(i=e.meta)==null?void 0:i.videoId,this.providerContainer=new wa({sources:e.sources,meta:(s=e.meta)!=null?s:{},failoverHosts:(n=e.failoverHosts)!=null?n:[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,tracer:this.tracer,logger:this.logger,abrLogger:this.abrLogger},tuning:this.tuning,volumeMultiplier:e.volumeMultiplier}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.initTracerSubscription(),this.providerContainer.init(),this.setMuted(this.tuning.isAudioDisabled),this.initDebugTelemetry(),this.initWakeLock(),this}destroy(){var e;this.tracer.log("destroy"),window.clearTimeout(this.hasLiveOffsetByPausedTimer),this.events.willDestruct$.next(),this.stop(),(e=this.providerContainer)==null||e.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe(),this.tracer.end()}prepare(){let e=this.desiredState.playbackState;return this.tracer.log("prepare",{currentPlayBackState:e.getState()}),e.getState()==="stopped"&&e.startTransitionTo("ready"),this}play(){let e=()=>{let t=this.desiredState.playbackState;this.tracer.log("play",{currentPlayBackState:t.getState()}),t.getState()!=="playing"&&t.startTransitionTo("playing")};return document.hidden&&this.tuning.autoplayOnlyInActiveTab&&!Ci()?(this.tracer.log("request play from hidden tab"),yl(document,"visibilitychange").pipe(dt()).subscribe(e)):e(),this}pause(){let e=this.desiredState.playbackState;return this.tracer.log("pause",{currentPlayBackState:e.getState()}),e.getState()!=="paused"&&e.startTransitionTo("paused"),this}stop(){let e=this.desiredState.playbackState;return this.tracer.log("stop",{currentPlayBackState:e.getState()}),e.getState()!=="stopped"&&e.startTransitionTo("stopped"),this}seekTime(e,t=!0){let r=this.info.duration$.getValue(),i=this.info.isLive$.getValue(),s=e;return e>=r&&!i&&(s=r-.1),this.tracer.log("seekTime",{duration:r,isLive:i,time:e,calculatedTime:s,forcePrecise:t}),this.events.willSeek$.next({from:this.getExactTime(),to:s}),this.desiredState.seekState.setState({state:"requested",position:s*1e3,forcePrecise:t}),this}seekPercent(e){let t=this.info.duration$.getValue();return this.tracer.log("seekPercent",{percent:e,duration:t}),isFinite(t)&&this.seekTime(Math.abs(t)*e,!1),this}setVolume(e){let t=this.tuning.isAudioDisabled||this.desiredState.volume.getState().muted;return this.tracer.log("setVolume",{volume:e,isAudioDisabled:this.tuning.isAudioDisabled,isDesiredStateMuted:this.desiredState.volume.getState().muted,chromecastState:this.chromecastInitializer.castState$.getValue(),muted:t}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setVolume(e):this.desiredState.volume.startTransitionTo({volume:e,muted:t}),this}setMuted(e){let t=this.tuning.isAudioDisabled||e;return this.tracer.log("setMuted",{isMuted:e,isAudioDisabled:this.tuning.isAudioDisabled,desiredStateVolume:this.desiredState.volume.getState().volume,chromecastState:this.chromecastInitializer.castState$.getValue(),muted:t}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setMuted(t):this.desiredState.volume.startTransitionTo({volume:this.desiredState.volume.getState().volume,muted:t}),this}setVideoStream(e){return this.desiredState.videoStream.startTransitionTo(e),this}setAudioStream(e){return this.desiredState.audioStream.startTransitionTo(e),this}setQuality(e){dn(this.providerContainer);let t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();return this.tracer.log("setQuality",{isDelayed:t.length===0,quality:e}),this.desiredState.videoTrack.getState()===void 0&&this.desiredState.videoTrack.getPrevState()===void 0&&t.length===0?this.providerContainer.providerOutput.availableVideoTracks$.pipe(se(r=>r.length>0),dt()).subscribe(r=>{this.setVideoTrackIdByQuality(r,e)}):t.length>0&&this.setVideoTrackIdByQuality(t,e),this}setAutoQuality(e){return this.tracer.log("setAutoQuality",{enable:e}),this.desiredState.autoVideoTrackSwitching.startTransitionTo(e),this}setAutoQualityLimits(e){return this.tracer.log("setAutoQualityLimits",$t(e)),this.desiredState.autoVideoTrackLimits.startTransitionTo(e),this}setPlaybackRate(e){var r;dn(this.providerContainer);let t=(r=this.providerContainer)==null?void 0:r.providerOutput.element$.getValue();return this.tracer.log("setPlaybackRate",{playbackRate:e,isVideoElementAvailable:!!t}),t&&(this.desiredState.playbackRate.setState(e),t.playbackRate=e),this}setExternalTextTracks(e){return e.length&&this.tracer.log("setExternalTextTracks",$t(e)),this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>({type:"external",...t}))),this}selectTextTrack(e){var t;return YS(e,this.desiredState.currentTextTrack,(t=this.providerContainer)==null?void 0:t.providerOutput.availableTextTracks$,r=>r.id===e),this.tracer.log("selectTextTrack",{textTrackId:e}),this}setTextTrackCueSettings(e){return this.tracer.log("setTextTrackCueSettings",{...e}),this.desiredState.textTrackCuesSettings.startTransitionTo(e),this}setLooped(e){return this.tracer.log("setLooped",{isLooped:e}),this.desiredState.isLooped.startTransitionTo(e),this}toggleChromecast(){this.tracer.log("toggleChromecast"),this.chromecastInitializer.toggleConnection()}startCameraManualRotation(e,t){let r=this.getScene3D();return this.tracer.log("startCameraManualRotation",{isScene3DAvailable:!!r,mx:e,my:t}),r&&r.startCameraManualRotation(e,t),this}stopCameraManualRotation(e=!1){let t=this.getScene3D();return this.tracer.log("stopCameraManualRotation",{isScene3DAvailable:!!t,immediate:e}),t&&t.stopCameraManualRotation(e),this}moveCameraFocusPX(e,t){let r=this.getScene3D();if(this.tracer.log("moveCameraFocusPX",{isScene3DAvailable:!!r,dxpx:e,dypx:t}),r){let i=r.getCameraRotation(),s=r.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:i.x+s.x,y:i.y+s.y})}return this}holdCamera(){let e=this.getScene3D();return e&&e.holdCamera(),this}releaseCamera(){let e=this.getScene3D();return e&&e.releaseCamera(),this}getExactTime(){if(!this.providerContainer)return 0;let e=this.providerContainer.providerOutput.element$.getValue();if(z$(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),r=t.state==="none"?void 0:t.position;return Q$(r)?r/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}getScene3D(){var t,r;let e=(t=this.providerContainer)==null?void 0:t.current$.getValue();if((r=e==null?void 0:e.provider)!=null&&r.scene3D)return e.provider.scene3D}setIntrinsicVideoSize(...e){let t={width:e.reduce((r,{width:i})=>r||i||0,0),height:e.reduce((r,{height:i})=>r||i||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add(Rt(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(D(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(D(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(D(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(D(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(D(e=>e.to)).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(se(({from:e})=>e==="stopped"),dt()).subscribe(()=>{this.initedAt=hn(),this.events.inited$.next()})).add(this.desiredState.playbackState.stateChangeEnded$.subscribe(e=>{switch(e.to){case"ready":this.events.ready$.next();break;case"playing":this.isPlaybackStarted||this.events.started$.next(),this.isPlaybackStarted=!0,this.events.playing$.next();break;case"paused":this.events.paused$.next();break;case"stopped":this.events.stopped$.next()}})).add(this.desiredState.playbackState.stateChangeStarted$.subscribe(e=>{switch(e.to){case"paused":this.events.willPause$.next();break;case"playing":this.isPlaybackStarted?this.events.willResume$.next():this.events.willStart$.next();break;case"stopped":this.events.willStop$.next();break;default:}}))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();this.tracer.log("willSeekEvent",$t(n)),n.state==="requested"?this.desiredState.seekState.setState({...n,state:"applying"}):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:pn.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.seekedEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();this.tracer.log("seekedEvent",$t(n)),n.state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe(D(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(D(n=>n.destination),_()).subscribe(()=>this.isPlaybackStarted=!1)).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add(e.providerOutput.availableVideoTracks$.pipe(D(n=>n.map(({quality:o})=>o).sort((o,u)=>JS(o)?1:JS(u)?-1:J$(u,o)?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(_()).subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{this.info.currentQuality$.next(n==null?void 0:n.quality),this.info.videoBitrate$.next(n==null?void 0:n.bitrate)})).add(e.providerOutput.currentVideoSegmentLength$.pipe(_((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.pipe(_((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe(_()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(_()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(_()).subscribe(this.info.httpConnectionReused$)).add(e.providerOutput.currentTextTrack$.subscribe(this.info.currentTextTrack$)).add(e.providerOutput.availableTextTracks$.subscribe(this.info.availableTextTracks$)).add(e.providerOutput.autoVideoTrackLimitingAvailable$.subscribe(this.info.autoQualityLimitingAvailable$)).add(e.providerOutput.autoVideoTrackLimits$.subscribe(n=>{this.desiredState.autoVideoTrackLimits.setState(n!=null?n:{})})).add(e.providerOutput.currentBuffer$.pipe(D(n=>n?{start:n.from,end:n.to}:{start:0,end:0})).subscribe(this.info.currentBuffer$)).add(e.providerOutput.duration$.subscribe(this.info.duration$)).add(e.providerOutput.isBuffering$.subscribe(this.info.isBuffering$)).add(e.providerOutput.isLive$.subscribe(this.info.isLive$)).add(e.providerOutput.canChangePlaybackSpeed$.subscribe(this.info.canChangePlaybackSpeed$)).add(e.providerOutput.liveTime$.subscribe(this.info.liveTime$)).add(e.providerOutput.liveBufferTime$.subscribe(this.info.liveBufferTime$)).add(kt({hasLiveOffsetByPaused:Rt(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(D(n=>n.to),_(),D(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(kt({atLiveEdge:kt({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:vl({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(D(({isLive:n,position:o,isLowLatency:u})=>{let l=this.getActiveLiveDelay(u);return n&&Math.abs(o)<l/1e3}),_(),KS(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(D(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add(kt({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(D(({isLive:n,position:o,duration:u})=>n&&(Math.abs(u)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),_(),KS(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(D(n=>n.muted),_()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(D(n=>n.volume),_()).subscribe(this.info.volume$)).add(vl({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(Rt(e.providerOutput.endedEvent$.pipe(QS(!0)),e.providerOutput.seekedEvent$.pipe(QS(!1))).pipe(_()).subscribe(this.info.isEnded$)).add(e.providerOutput.endedEvent$.subscribe(this.events.ended$)).add(e.providerOutput.loopedEvent$.subscribe(this.events.looped$)).add(e.providerError$.subscribe(this.events.managedError$)).add(e.volumeMultiplierError$.subscribe(this.events.managedError$)).add(e.noAvailableProvidersError$.pipe(D(n=>({id:n?`No${n}`:"NoProviders",category:pn.VIDEO_PIPELINE,message:n?`${n} was forced but failed or not available`:"No suitable providers or all providers failed"}))).subscribe(this.events.fatalError$)).add(e.providerOutput.element$.subscribe(this.experimental.element$)).add(e.providerOutput.firstBytesEvent$.pipe(dt(),D(n=>n!=null?n:hn()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe(dt(),D(()=>hn()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(dt(),D(()=>hn()-this.initedAt)).subscribe(this.events.canplay$)).add(this.throughputEstimator.throughput$.subscribe(this.info.throughputEstimation$)).add(this.throughputEstimator.rtt$.subscribe(this.info.rttEstimation$)).add(e.providerOutput.availableSources$.subscribe(this.info.availableSources$));let t=new P(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let r=new P(!0);this.subscription.add(e.current$.subscribe(()=>r.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(se(({to:n})=>n==="playing"),dt()).subscribe(()=>r.next(!1)));let i=0,s=Rt(e.providerOutput.isBuffering$,t,r).pipe(D(()=>{let n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||r.getValue();return n&&!o}),_());this.subscription.add(s.subscribe(n=>{n?i=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(i),this.info.isStalled$.next(!1))})),this.subscription.add(Rt(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{let n=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:n==null?void 0:n.videoWidth,height:n==null?void 0:n.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{var u,l;let o=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:(u=n==null?void 0:n.size)==null?void 0:u.width,height:(l=n==null?void 0:n.size)==null?void 0:l.height},{width:o==null?void 0:o.videoWidth,height:o==null?void 0:o.videoHeight})})).add(e.providerOutput.is3DVideo$.subscribe(this.info.is3DVideo$)),this.subscription.add(Rt(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,e.providerOutput.elementVisible$,this.chromecastInitializer.castState$).subscribe(()=>{let n=e.providerOutput.inPiP$.getValue(),o=e.providerOutput.inFullscreen$.getValue(),u=e.providerOutput.element$.getValue(),l=e.providerOutput.elementVisible$.getValue(),c=this.chromecastInitializer.castState$.getValue(),d;c==="CONNECTED"?d="second_screen":u?l?n?d="pip":o?d="fullscreen":d="inline":d="invisible":d="none",this.info.surface$.getValue()!==d&&this.info.surface$.next(d)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(D(e=>e==null?void 0:e.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){let t=new zS;this.subscription.add(t),this.subscription.add(e.current$.pipe(_((r,i)=>r.provider===i.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(se(r=>r.length>0),dt()).subscribe(r=>{this.setStartingVideoTrack(r)}))}))}setStartingVideoTrack(e){var i;let t,r=(i=this.desiredState.videoTrack.getState())==null?void 0:i.quality;r&&(t=e.find(({quality:s})=>s===r),t||this.setAutoQuality(!0)),t||(t=xt(e,{container:this.domContainer.getBoundingClientRect(),throughput: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(Rt(this.desiredState.videoTrack.stateChangeStarted$.pipe(D(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(D(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(D(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(D(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(D(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(D(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(D(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(D(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(D(e=>({component:"desiredState",message:`[${e.entity} change] ${e.type}: ${JSON.stringify(e.transition)}`}))).subscribe(this.logger.log)),this.subscription.add(this.logger.log$.subscribe(this.events.log$))}initDebugTelemetry(){var t;let e=(t=this.providerContainer)==null?void 0:t.providerOutput;dn(this.providerContainer),dn(e),hb(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(r=>pb(r)),this.providerContainer.current$.subscribe(({type:r})=>wi("provider",r)),e.duration$.subscribe(r=>wi("duration",r)),e.availableVideoTracks$.pipe(se(r=>!!r.length),dt()).subscribe(r=>wi("tracks",r)),this.events.fatalError$.subscribe(new ae("fatalError")),this.events.managedError$.subscribe(new ae("managedError")),e.position$.subscribe(new ae("position")),e.currentVideoTrack$.pipe(D(r=>r==null?void 0:r.quality)).subscribe(new ae("quality")),this.info.currentBuffer$.subscribe(new ae("buffer")),e.isBuffering$.subscribe(new ae("isBuffering"))].forEach(r=>this.subscription.add(r)),wi("codecs",Xb())}initTracerSubscription(){let e=XS(this.tracer.log.bind(this.tracer)),t=XS(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(_()).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(kt({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe(se(({currentQuality:r,videoBitrate:i})=>!!r&&!!i),_((r,i)=>r.currentQuality===i.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe(se(r=>r>0),_()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe(se(r=>r>0),_()).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(kt({currentBuffer:this.info.currentBuffer$.pipe(se(r=>r.end>0),_((r,i)=>r.end===i.end&&r.start===i.start)),position:this.info.position$.pipe(_())}).pipe(Tl(1e3)).subscribe(e("currentBufferAndPosition"))).add(this.info.duration$.pipe(_()).subscribe(e("duration"))).add(this.info.isBuffering$.subscribe(e("isBuffering"))).add(this.info.isLive$.pipe(_()).subscribe(e("isLive"))).add(this.info.canChangePlaybackSpeed$.pipe(_()).subscribe(e("canChangePlaybackSpeed"))).add(kt({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe(se(({liveTime:r,liveBufferTime:i})=>!!r&&!!i),Tl(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe(_(),se(r=>r===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe(_(),se(r=>r===!0)).subscribe(e("atLiveDurationEdge"))).add(this.info.muted$.pipe(_()).subscribe(e("muted"))).add(this.info.volume$.pipe(_()).subscribe(e("volume"))).add(this.info.isEnded$.pipe(_(),se(r=>r===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add(kt({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe(se(({throughputEstimation:r,rtt:i})=>!!r&&!!i),Tl(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe(_(),se(r=>r===!0)).subscribe(e("is3DVideo"))).add(this.info.surface$.subscribe(e("surface"))).add(this.events.ended$.subscribe(e("ended"))).add(this.events.looped$.subscribe(e("looped"))).add(this.events.managedError$.subscribe(t("managedError"))).add(this.events.fatalError$.subscribe(t("fatalError"))).add(this.events.firstBytes$.subscribe(e("firstBytes"))).add(this.events.firstFrame$.subscribe(e("firstFrame"))).add(this.events.canplay$.subscribe(e("canplay")))}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e,t=()=>{e==null||e.release(),e=void 0},r=async()=>{t(),e=await window.navigator.wakeLock.request("screen").catch(i=>{i instanceof DOMException&&i.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:pn.DOM,message:String(i)})})};this.subscription.add(Rt(yl(document,"visibilitychange"),yl(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{let i=document.visibilityState==="visible",s=this.desiredState.playbackState.getState()==="playing",n=!!e&&!(e!=null&&e.released);i&&s?n||r():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){let r=e.find(i=>i.quality===t);this.tracer.log("setVideoTrackIdByQuality",$t({quality:t,availableTracks:$t(e),track:$t(r),isAutoQuality:!r})),r?this.desiredState.videoTrack.startTransitionTo(r):this.setAutoQuality(!0)}getActiveLiveDelay(e=!1){return e?this.tuning.live.lowLatencyActiveLiveDelay:this.tuning.live.activeLiveDelay}};import{Subscription as KG,Observable as JG,Subject as XG,ValueSubject as ZG,VideoQuality as eW}from"@vkontakte/videoplayer-shared";var tW=`@vkontakte/videoplayer-core@${ec}`;export{Va as ChromecastState,En as HttpConnectionType,JG as Observable,le as PlaybackState,fn as Player,tW as SDK_VERSION,XG as Subject,KG as Subscription,xn as Surface,ec as VERSION,ZG as ValueSubject,St as VideoFormat,eW as VideoQuality};
|