@vkontakte/videoplayer-core 2.0.108-dev.43b53ca1.0 → 2.0.108-dev.9b636631.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 +17 -38
- package/es2015.esm.js +16 -37
- package/es2018.cjs.js +17 -38
- package/es2018.esm.js +16 -37
- package/esnext.cjs.js +18 -39
- package/esnext.esm.js +17 -38
- package/evergreen.esm.js +16 -37
- package/package.json +2 -2
- package/types/player/Player.d.ts +2 -2
- package/types/player/types.d.ts +6 -5
- package/types/providers/DashProvider/baseDashProvider.d.ts +1 -2
- package/types/utils/autoSelectVideoTrack.d.ts +11 -13
- package/types/utils/tuningConfig.d.ts +0 -5
package/es2018.esm.js
CHANGED
|
@@ -1,18 +1,15 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @vkontakte/videoplayer-core v2.0.108-dev.
|
|
3
|
-
*
|
|
2
|
+
* @vkontakte/videoplayer-core v2.0.108-dev.9b636631.0
|
|
3
|
+
* Fri, 30 Aug 2024 14:05:43 GMT
|
|
4
4
|
* https://st.mycdn.me/static/vkontakte-videoplayer/2-0-108/doc/
|
|
5
5
|
*/
|
|
6
|
-
var zS=Object.create;var kl=Object.defineProperty;var KS=Object.getOwnPropertyDescriptor;var JS=Object.getOwnPropertyNames;var XS=Object.getPrototypeOf,ZS=Object.prototype.hasOwnProperty;var m=(a,e)=>()=>(e||a((e={exports:{}}).exports,e),e.exports);var ev=(a,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of JS(e))!ZS.call(a,i)&&i!==t&&kl(a,i,{get:()=>e[i],enumerable:!(r=KS(e,i))||r.enumerable});return a};var Ue=(a,e,t)=>(t=a!=null?zS(XS(a)):{},ev(e||!a||!a.__esModule?kl(t,"default",{value:a,enumerable:!0}):t,a));var be=m((QL,Bl)=>{"use strict";Bl.exports=function(a){try{return!!a()}catch(e){return!0}}});var Br=m((zL,Vl)=>{"use strict";var uv=be();Vl.exports=!uv(function(){var a=function(){}.bind();return typeof a!="function"||a.hasOwnProperty("prototype")})});var ue=m((KL,Fl)=>{"use strict";var _l=Br(),Nl=Function.prototype,dn=Nl.call,lv=_l&&Nl.bind.bind(dn,dn);Fl.exports=_l?lv:function(a){return function(){return dn.apply(a,arguments)}}});var Xt=m((JL,Ul)=>{"use strict";var ql=ue(),cv=ql({}.toString),dv=ql("".slice);Ul.exports=function(a){return dv(cv(a),8,-1)}});var jl=m((XL,Hl)=>{"use strict";var pv=ue(),hv=be(),fv=Xt(),pn=Object,mv=pv("".split);Hl.exports=hv(function(){return!pn("z").propertyIsEnumerable(0)})?function(a){return fv(a)==="String"?mv(a,""):pn(a)}:pn});var Zt=m((ZL,Gl)=>{"use strict";Gl.exports=function(a){return a==null}});var Vr=m((e$,Yl)=>{"use strict";var bv=Zt(),gv=TypeError;Yl.exports=function(a){if(bv(a))throw new gv("Can't call method on "+a);return a}});var er=m((t$,Wl)=>{"use strict";var Sv=jl(),vv=Vr();Wl.exports=function(a){return Sv(vv(a))}});var hn=m((r$,Ql)=>{"use strict";Ql.exports=function(){}});var wt=m((i$,zl)=>{"use strict";zl.exports={}});var Y=m((fn,Kl)=>{"use strict";var _r=function(a){return a&&a.Math===Math&&a};Kl.exports=_r(typeof globalThis=="object"&&globalThis)||_r(typeof window=="object"&&window)||_r(typeof self=="object"&&self)||_r(typeof global=="object"&&global)||_r(typeof fn=="object"&&fn)||function(){return this}()||Function("return this")()});var G=m((a$,Jl)=>{"use strict";var mn=typeof document=="object"&&document.all;Jl.exports=typeof mn=="undefined"&&mn!==void 0?function(a){return typeof a=="function"||a===mn}:function(a){return typeof a=="function"}});var ec=m((s$,Zl)=>{"use strict";var yv=Y(),Tv=G(),Xl=yv.WeakMap;Zl.exports=Tv(Xl)&&/native code/.test(String(Xl))});var Ee=m((n$,tc)=>{"use strict";var Iv=G();tc.exports=function(a){return typeof a=="object"?a!==null:Iv(a)}});var xe=m((o$,rc)=>{"use strict";var Ev=be();rc.exports=!Ev(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var Sa=m((u$,ac)=>{"use strict";var xv=Y(),ic=Ee(),bn=xv.document,Pv=ic(bn)&&ic(bn.createElement);ac.exports=function(a){return Pv?bn.createElement(a):{}}});var gn=m((l$,sc)=>{"use strict";var Av=xe(),wv=be(),kv=Sa();sc.exports=!Av&&!wv(function(){return Object.defineProperty(kv("div"),"a",{get:function(){return 7}}).a!==7})});var Sn=m((c$,nc)=>{"use strict";var Rv=xe(),Lv=be();nc.exports=Rv&&Lv(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var He=m((d$,oc)=>{"use strict";var $v=Ee(),Mv=String,Cv=TypeError;oc.exports=function(a){if($v(a))return a;throw new Cv(Mv(a)+" is not an object")}});var ge=m((p$,uc)=>{"use strict";var Dv=Br(),va=Function.prototype.call;uc.exports=Dv?va.bind(va):function(){return va.apply(va,arguments)}});var ya=m((h$,lc)=>{"use strict";lc.exports={}});var Qe=m((f$,dc)=>{"use strict";var vn=ya(),yn=Y(),Ov=G(),cc=function(a){return Ov(a)?a:void 0};dc.exports=function(a,e){return arguments.length<2?cc(vn[a])||cc(yn[a]):vn[a]&&vn[a][e]||yn[a]&&yn[a][e]}});var Nr=m((m$,pc)=>{"use strict";var Bv=ue();pc.exports=Bv({}.isPrototypeOf)});var tr=m((b$,mc)=>{"use strict";var Vv=Y(),hc=Vv.navigator,fc=hc&&hc.userAgent;mc.exports=fc?String(fc):""});var In=m((g$,Tc)=>{"use strict";var yc=Y(),Tn=tr(),bc=yc.process,gc=yc.Deno,Sc=bc&&bc.versions||gc&&gc.version,vc=Sc&&Sc.v8,De,Ta;vc&&(De=vc.split("."),Ta=De[0]>0&&De[0]<4?1:+(De[0]+De[1]));!Ta&&Tn&&(De=Tn.match(/Edge\/(\d+)/),(!De||De[1]>=74)&&(De=Tn.match(/Chrome\/(\d+)/),De&&(Ta=+De[1])));Tc.exports=Ta});var En=m((S$,Ec)=>{"use strict";var Ic=In(),_v=be(),Nv=Y(),Fv=Nv.String;Ec.exports=!!Object.getOwnPropertySymbols&&!_v(function(){var a=Symbol("symbol detection");return!Fv(a)||!(Object(a)instanceof Symbol)||!Symbol.sham&&Ic&&Ic<41})});var xn=m((v$,xc)=>{"use strict";var qv=En();xc.exports=qv&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var Pn=m((y$,Pc)=>{"use strict";var Uv=Qe(),Hv=G(),jv=Nr(),Gv=xn(),Yv=Object;Pc.exports=Gv?function(a){return typeof a=="symbol"}:function(a){var e=Uv("Symbol");return Hv(e)&&jv(e.prototype,Yv(a))}});var Fr=m((T$,Ac)=>{"use strict";var Wv=String;Ac.exports=function(a){try{return Wv(a)}catch(e){return"Object"}}});var ze=m((I$,wc)=>{"use strict";var Qv=G(),zv=Fr(),Kv=TypeError;wc.exports=function(a){if(Qv(a))return a;throw new Kv(zv(a)+" is not a function")}});var qr=m((E$,kc)=>{"use strict";var Jv=ze(),Xv=Zt();kc.exports=function(a,e){var t=a[e];return Xv(t)?void 0:Jv(t)}});var Lc=m((x$,Rc)=>{"use strict";var An=ge(),wn=G(),kn=Ee(),Zv=TypeError;Rc.exports=function(a,e){var t,r;if(e==="string"&&wn(t=a.toString)&&!kn(r=An(t,a))||wn(t=a.valueOf)&&!kn(r=An(t,a))||e!=="string"&&wn(t=a.toString)&&!kn(r=An(t,a)))return r;throw new Zv("Can't convert object to primitive value")}});var Oe=m((P$,$c)=>{"use strict";$c.exports=!0});var Dc=m((A$,Cc)=>{"use strict";var Mc=Y(),ey=Object.defineProperty;Cc.exports=function(a,e){try{ey(Mc,a,{value:e,configurable:!0,writable:!0})}catch(t){Mc[a]=e}return e}});var Ur=m((w$,Vc)=>{"use strict";var ty=Oe(),ry=Y(),iy=Dc(),Oc="__core-js_shared__",Bc=Vc.exports=ry[Oc]||iy(Oc,{});(Bc.versions||(Bc.versions=[])).push({version:"3.38.0",mode:ty?"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 Rn=m((k$,Nc)=>{"use strict";var _c=Ur();Nc.exports=function(a,e){return _c[a]||(_c[a]=e||{})}});var Hr=m((R$,Fc)=>{"use strict";var ay=Vr(),sy=Object;Fc.exports=function(a){return sy(ay(a))}});var Be=m((L$,qc)=>{"use strict";var ny=ue(),oy=Hr(),uy=ny({}.hasOwnProperty);qc.exports=Object.hasOwn||function(e,t){return uy(oy(e),t)}});var Ln=m(($$,Uc)=>{"use strict";var ly=ue(),cy=0,dy=Math.random(),py=ly(1 .toString);Uc.exports=function(a){return"Symbol("+(a===void 0?"":a)+")_"+py(++cy+dy,36)}});var re=m((M$,jc)=>{"use strict";var hy=Y(),fy=Rn(),Hc=Be(),my=Ln(),by=En(),gy=xn(),rr=hy.Symbol,$n=fy("wks"),Sy=gy?rr.for||rr:rr&&rr.withoutSetter||my;jc.exports=function(a){return Hc($n,a)||($n[a]=by&&Hc(rr,a)?rr[a]:Sy("Symbol."+a)),$n[a]}});var Qc=m((C$,Wc)=>{"use strict";var vy=ge(),Gc=Ee(),Yc=Pn(),yy=qr(),Ty=Lc(),Iy=re(),Ey=TypeError,xy=Iy("toPrimitive");Wc.exports=function(a,e){if(!Gc(a)||Yc(a))return a;var t=yy(a,xy),r;if(t){if(e===void 0&&(e="default"),r=vy(t,a,e),!Gc(r)||Yc(r))return r;throw new Ey("Can't convert object to primitive value")}return e===void 0&&(e="number"),Ty(a,e)}});var Mn=m((D$,zc)=>{"use strict";var Py=Qc(),Ay=Pn();zc.exports=function(a){var e=Py(a,"string");return Ay(e)?e:e+""}});var kt=m(Jc=>{"use strict";var wy=xe(),ky=gn(),Ry=Sn(),Ia=He(),Kc=Mn(),Ly=TypeError,Cn=Object.defineProperty,$y=Object.getOwnPropertyDescriptor,Dn="enumerable",On="configurable",Bn="writable";Jc.f=wy?Ry?function(e,t,r){if(Ia(e),t=Kc(t),Ia(r),typeof e=="function"&&t==="prototype"&&"value"in r&&Bn in r&&!r[Bn]){var i=$y(e,t);i&&i[Bn]&&(e[t]=r.value,r={configurable:On in r?r[On]:i[On],enumerable:Dn in r?r[Dn]:i[Dn],writable:!1})}return Cn(e,t,r)}:Cn:function(e,t,r){if(Ia(e),t=Kc(t),Ia(r),ky)try{return Cn(e,t,r)}catch(i){}if("get"in r||"set"in r)throw new Ly("Accessors not supported");return"value"in r&&(e[t]=r.value),e}});var jr=m((B$,Xc)=>{"use strict";Xc.exports=function(a,e){return{enumerable:!(a&1),configurable:!(a&2),writable:!(a&4),value:e}}});var ir=m((V$,Zc)=>{"use strict";var My=xe(),Cy=kt(),Dy=jr();Zc.exports=My?function(a,e,t){return Cy.f(a,e,Dy(1,t))}:function(a,e,t){return a[e]=t,a}});var Ea=m((_$,td)=>{"use strict";var Oy=Rn(),By=Ln(),ed=Oy("keys");td.exports=function(a){return ed[a]||(ed[a]=By(a))}});var xa=m((N$,rd)=>{"use strict";rd.exports={}});var Fn=m((F$,sd)=>{"use strict";var Vy=ec(),ad=Y(),_y=Ee(),Ny=ir(),Vn=Be(),_n=Ur(),Fy=Ea(),qy=xa(),id="Object already initialized",Nn=ad.TypeError,Uy=ad.WeakMap,Pa,Gr,Aa,Hy=function(a){return Aa(a)?Gr(a):Pa(a,{})},jy=function(a){return function(e){var t;if(!_y(e)||(t=Gr(e)).type!==a)throw new Nn("Incompatible receiver, "+a+" required");return t}};Vy||_n.state?(Ve=_n.state||(_n.state=new Uy),Ve.get=Ve.get,Ve.has=Ve.has,Ve.set=Ve.set,Pa=function(a,e){if(Ve.has(a))throw new Nn(id);return e.facade=a,Ve.set(a,e),e},Gr=function(a){return Ve.get(a)||{}},Aa=function(a){return Ve.has(a)}):(Rt=Fy("state"),qy[Rt]=!0,Pa=function(a,e){if(Vn(a,Rt))throw new Nn(id);return e.facade=a,Ny(a,Rt,e),e},Gr=function(a){return Vn(a,Rt)?a[Rt]:{}},Aa=function(a){return Vn(a,Rt)});var Ve,Rt;sd.exports={set:Pa,get:Gr,has:Aa,enforce:Hy,getterFor:jy}});var qn=m((q$,ld)=>{"use strict";var Gy=Br(),ud=Function.prototype,nd=ud.apply,od=ud.call;ld.exports=typeof Reflect=="object"&&Reflect.apply||(Gy?od.bind(nd):function(){return od.apply(nd,arguments)})});var Un=m((U$,cd)=>{"use strict";var Yy=Xt(),Wy=ue();cd.exports=function(a){if(Yy(a)==="Function")return Wy(a)}});var fd=m(hd=>{"use strict";var dd={}.propertyIsEnumerable,pd=Object.getOwnPropertyDescriptor,Qy=pd&&!dd.call({1:2},1);hd.f=Qy?function(e){var t=pd(this,e);return!!t&&t.enumerable}:dd});var gd=m(bd=>{"use strict";var zy=xe(),Ky=ge(),Jy=fd(),Xy=jr(),Zy=er(),eT=Mn(),tT=Be(),rT=gn(),md=Object.getOwnPropertyDescriptor;bd.f=zy?md:function(e,t){if(e=Zy(e),t=eT(t),rT)try{return md(e,t)}catch(r){}if(tT(e,t))return Xy(!Ky(Jy.f,e,t),e[t])}});var Hn=m((G$,Sd)=>{"use strict";var iT=be(),aT=G(),sT=/#|\.prototype\./,Yr=function(a,e){var t=oT[nT(a)];return t===lT?!0:t===uT?!1:aT(e)?iT(e):!!e},nT=Yr.normalize=function(a){return String(a).replace(sT,".").toLowerCase()},oT=Yr.data={},uT=Yr.NATIVE="N",lT=Yr.POLYFILL="P";Sd.exports=Yr});var Wr=m((Y$,yd)=>{"use strict";var vd=Un(),cT=ze(),dT=Br(),pT=vd(vd.bind);yd.exports=function(a,e){return cT(a),e===void 0?a:dT?pT(a,e):function(){return a.apply(e,arguments)}}});var Pe=m((W$,Id)=>{"use strict";var Qr=Y(),hT=qn(),fT=Un(),mT=G(),bT=gd().f,gT=Hn(),ar=ya(),ST=Wr(),sr=ir(),Td=Be();Ur();var vT=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 hT(a,this,arguments)};return e.prototype=a.prototype,e};Id.exports=function(a,e){var t=a.target,r=a.global,i=a.stat,s=a.proto,n=r?Qr:i?Qr[t]:Qr[t]&&Qr[t].prototype,o=r?ar:ar[t]||sr(ar,t,{})[t],u=o.prototype,l,c,p,d,h,f,b,g,y;for(d in e)l=gT(r?d:t+(i?".":"#")+d,a.forced),c=!l&&n&&Td(n,d),f=o[d],c&&(a.dontCallGetSet?(y=bT(n,d),b=y&&y.value):b=n[d]),h=c&&b?b:e[d],!(!l&&!s&&typeof f==typeof h)&&(a.bind&&c?g=ST(h,Qr):a.wrap&&c?g=vT(h):s&&mT(h)?g=fT(h):g=h,(a.sham||h&&h.sham||f&&f.sham)&&sr(g,"sham",!0),sr(o,d,g),s&&(p=t+"Prototype",Td(ar,p)||sr(ar,p,{}),sr(ar[p],d,h),a.real&&u&&(l||!u[d])&&sr(u,d,h)))}});var Pd=m((Q$,xd)=>{"use strict";var jn=xe(),yT=Be(),Ed=Function.prototype,TT=jn&&Object.getOwnPropertyDescriptor,Gn=yT(Ed,"name"),IT=Gn&&function(){}.name==="something",ET=Gn&&(!jn||jn&&TT(Ed,"name").configurable);xd.exports={EXISTS:Gn,PROPER:IT,CONFIGURABLE:ET}});var wd=m((z$,Ad)=>{"use strict";var xT=Math.ceil,PT=Math.floor;Ad.exports=Math.trunc||function(e){var t=+e;return(t>0?PT:xT)(t)}});var wa=m((K$,kd)=>{"use strict";var AT=wd();kd.exports=function(a){var e=+a;return e!==e||e===0?0:AT(e)}});var Ld=m((J$,Rd)=>{"use strict";var wT=wa(),kT=Math.max,RT=Math.min;Rd.exports=function(a,e){var t=wT(a);return t<0?kT(t+e,0):RT(t,e)}});var Md=m((X$,$d)=>{"use strict";var LT=wa(),$T=Math.min;$d.exports=function(a){var e=LT(a);return e>0?$T(e,9007199254740991):0}});var ka=m((Z$,Cd)=>{"use strict";var MT=Md();Cd.exports=function(a){return MT(a.length)}});var Bd=m((eM,Od)=>{"use strict";var CT=er(),DT=Ld(),OT=ka(),Dd=function(a){return function(e,t,r){var i=CT(e),s=OT(i);if(s===0)return!a&&-1;var n=DT(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}};Od.exports={includes:Dd(!0),indexOf:Dd(!1)}});var Nd=m((tM,_d)=>{"use strict";var BT=ue(),Yn=Be(),VT=er(),_T=Bd().indexOf,NT=xa(),Vd=BT([].push);_d.exports=function(a,e){var t=VT(a),r=0,i=[],s;for(s in t)!Yn(NT,s)&&Yn(t,s)&&Vd(i,s);for(;e.length>r;)Yn(t,s=e[r++])&&(~_T(i,s)||Vd(i,s));return i}});var Wn=m((rM,Fd)=>{"use strict";Fd.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var Ud=m((iM,qd)=>{"use strict";var FT=Nd(),qT=Wn();qd.exports=Object.keys||function(e){return FT(e,qT)}});var jd=m(Hd=>{"use strict";var UT=xe(),HT=Sn(),jT=kt(),GT=He(),YT=er(),WT=Ud();Hd.f=UT&&!HT?Object.defineProperties:function(e,t){GT(e);for(var r=YT(t),i=WT(t),s=i.length,n=0,o;s>n;)jT.f(e,o=i[n++],r[o]);return e}});var Qn=m((sM,Gd)=>{"use strict";var QT=Qe();Gd.exports=QT("document","documentElement")});var Xn=m((nM,Xd)=>{"use strict";var zT=He(),KT=jd(),Yd=Wn(),JT=xa(),XT=Qn(),ZT=Sa(),eI=Ea(),Wd=">",Qd="<",Kn="prototype",Jn="script",Kd=eI("IE_PROTO"),zn=function(){},Jd=function(a){return Qd+Jn+Wd+a+Qd+"/"+Jn+Wd},zd=function(a){a.write(Jd("")),a.close();var e=a.parentWindow.Object;return a=null,e},tI=function(){var a=ZT("iframe"),e="java"+Jn+":",t;return a.style.display="none",XT.appendChild(a),a.src=String(e),t=a.contentWindow.document,t.open(),t.write(Jd("document.F=Object")),t.close(),t.F},Ra,La=function(){try{Ra=new ActiveXObject("htmlfile")}catch(e){}La=typeof document!="undefined"?document.domain&&Ra?zd(Ra):tI():zd(Ra);for(var a=Yd.length;a--;)delete La[Kn][Yd[a]];return La()};JT[Kd]=!0;Xd.exports=Object.create||function(e,t){var r;return e!==null?(zn[Kn]=zT(e),r=new zn,zn[Kn]=null,r[Kd]=e):r=La(),t===void 0?r:KT.f(r,t)}});var ep=m((oM,Zd)=>{"use strict";var rI=be();Zd.exports=!rI(function(){function a(){}return a.prototype.constructor=null,Object.getPrototypeOf(new a)!==a.prototype})});var eo=m((uM,rp)=>{"use strict";var iI=Be(),aI=G(),sI=Hr(),nI=Ea(),oI=ep(),tp=nI("IE_PROTO"),Zn=Object,uI=Zn.prototype;rp.exports=oI?Zn.getPrototypeOf:function(a){var e=sI(a);if(iI(e,tp))return e[tp];var t=e.constructor;return aI(t)&&e instanceof t?t.prototype:e instanceof Zn?uI:null}});var nr=m((lM,ip)=>{"use strict";var lI=ir();ip.exports=function(a,e,t,r){return r&&r.enumerable?a[e]=t:lI(a,e,t),a}});var ao=m((cM,np)=>{"use strict";var cI=be(),dI=G(),pI=Ee(),hI=Xn(),ap=eo(),fI=nr(),mI=re(),bI=Oe(),io=mI("iterator"),sp=!1,Ke,to,ro;[].keys&&(ro=[].keys(),"next"in ro?(to=ap(ap(ro)),to!==Object.prototype&&(Ke=to)):sp=!0);var gI=!pI(Ke)||cI(function(){var a={};return Ke[io].call(a)!==a});gI?Ke={}:bI&&(Ke=hI(Ke));dI(Ke[io])||fI(Ke,io,function(){return this});np.exports={IteratorPrototype:Ke,BUGGY_SAFARI_ITERATORS:sp}});var $a=m((dM,up)=>{"use strict";var SI=re(),vI=SI("toStringTag"),op={};op[vI]="z";up.exports=String(op)==="[object z]"});var zr=m((pM,lp)=>{"use strict";var yI=$a(),TI=G(),Ma=Xt(),II=re(),EI=II("toStringTag"),xI=Object,PI=Ma(function(){return arguments}())==="Arguments",AI=function(a,e){try{return a[e]}catch(t){}};lp.exports=yI?Ma:function(a){var e,t,r;return a===void 0?"Undefined":a===null?"Null":typeof(t=AI(e=xI(a),EI))=="string"?t:PI?Ma(e):(r=Ma(e))==="Object"&&TI(e.callee)?"Arguments":r}});var dp=m((hM,cp)=>{"use strict";var wI=$a(),kI=zr();cp.exports=wI?{}.toString:function(){return"[object "+kI(this)+"]"}});var Kr=m((fM,hp)=>{"use strict";var RI=$a(),LI=kt().f,$I=ir(),MI=Be(),CI=dp(),DI=re(),pp=DI("toStringTag");hp.exports=function(a,e,t,r){var i=t?a:a&&a.prototype;i&&(MI(i,pp)||LI(i,pp,{configurable:!0,value:e}),r&&!RI&&$I(i,"toString",CI))}});var mp=m((mM,fp)=>{"use strict";var OI=ao().IteratorPrototype,BI=Xn(),VI=jr(),_I=Kr(),NI=wt(),FI=function(){return this};fp.exports=function(a,e,t,r){var i=e+" Iterator";return a.prototype=BI(OI,{next:VI(+!r,t)}),_I(a,i,!1,!0),NI[i]=FI,a}});var gp=m((bM,bp)=>{"use strict";var qI=ue(),UI=ze();bp.exports=function(a,e,t){try{return qI(UI(Object.getOwnPropertyDescriptor(a,e)[t]))}catch(r){}}});var vp=m((gM,Sp)=>{"use strict";var HI=Ee();Sp.exports=function(a){return HI(a)||a===null}});var Tp=m((SM,yp)=>{"use strict";var jI=vp(),GI=String,YI=TypeError;yp.exports=function(a){if(jI(a))return a;throw new YI("Can't set "+GI(a)+" as a prototype")}});var so=m((vM,Ip)=>{"use strict";var WI=gp(),QI=Ee(),zI=Vr(),KI=Tp();Ip.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var a=!1,e={},t;try{t=WI(Object.prototype,"__proto__","set"),t(e,[]),a=e instanceof Array}catch(r){}return function(i,s){return zI(i),KI(s),QI(i)&&(a?t(i,s):i.__proto__=s),i}}():void 0)});var Cp=m((yM,Mp)=>{"use strict";var JI=Pe(),XI=ge(),Ca=Oe(),Lp=Pd(),ZI=G(),eE=mp(),Ep=eo(),xp=so(),tE=Kr(),rE=ir(),no=nr(),iE=re(),Pp=wt(),$p=ao(),aE=Lp.PROPER,sE=Lp.CONFIGURABLE,Ap=$p.IteratorPrototype,Da=$p.BUGGY_SAFARI_ITERATORS,Jr=iE("iterator"),wp="keys",Xr="values",kp="entries",Rp=function(){return this};Mp.exports=function(a,e,t,r,i,s,n){eE(t,e,r);var o=function(y){if(y===i&&d)return d;if(!Da&&y&&y in c)return c[y];switch(y){case wp:return function(){return new t(this,y)};case Xr:return function(){return new t(this,y)};case kp:return function(){return new t(this,y)}}return function(){return new t(this)}},u=e+" Iterator",l=!1,c=a.prototype,p=c[Jr]||c["@@iterator"]||i&&c[i],d=!Da&&p||o(i),h=e==="Array"&&c.entries||p,f,b,g;if(h&&(f=Ep(h.call(new a)),f!==Object.prototype&&f.next&&(!Ca&&Ep(f)!==Ap&&(xp?xp(f,Ap):ZI(f[Jr])||no(f,Jr,Rp)),tE(f,u,!0,!0),Ca&&(Pp[u]=Rp))),aE&&i===Xr&&p&&p.name!==Xr&&(!Ca&&sE?rE(c,"name",Xr):(l=!0,d=function(){return XI(p,this)})),i)if(b={values:o(Xr),keys:s?d:o(wp),entries:o(kp)},n)for(g in b)(Da||l||!(g in c))&&no(c,g,b[g]);else JI({target:e,proto:!0,forced:Da||l},b);return(!Ca||n)&&c[Jr]!==d&&no(c,Jr,d,{name:i}),Pp[e]=d,b}});var Op=m((TM,Dp)=>{"use strict";Dp.exports=function(a,e){return{value:a,done:e}}});var uo=m((IM,Fp)=>{"use strict";var nE=er(),oo=hn(),Bp=wt(),_p=Fn(),oE=kt().f,uE=Cp(),Oa=Op(),lE=Oe(),cE=xe(),Np="Array Iterator",dE=_p.set,pE=_p.getterFor(Np);Fp.exports=uE(Array,"Array",function(a,e){dE(this,{type:Np,target:nE(a),index:0,kind:e})},function(){var a=pE(this),e=a.target,t=a.index++;if(!e||t>=e.length)return a.target=void 0,Oa(void 0,!0);switch(a.kind){case"keys":return Oa(t,!1);case"values":return Oa(e[t],!1)}return Oa([t,e[t]],!1)},"values");var Vp=Bp.Arguments=Bp.Array;oo("keys");oo("values");oo("entries");if(!lE&&cE&&Vp.name!=="values")try{oE(Vp,"name",{value:"values"})}catch(a){}});var Up=m((EM,qp)=>{"use strict";var hE=re(),fE=wt(),mE=hE("iterator"),bE=Array.prototype;qp.exports=function(a){return a!==void 0&&(fE.Array===a||bE[mE]===a)}});var lo=m((xM,jp)=>{"use strict";var gE=zr(),Hp=qr(),SE=Zt(),vE=wt(),yE=re(),TE=yE("iterator");jp.exports=function(a){if(!SE(a))return Hp(a,TE)||Hp(a,"@@iterator")||vE[gE(a)]}});var Yp=m((PM,Gp)=>{"use strict";var IE=ge(),EE=ze(),xE=He(),PE=Fr(),AE=lo(),wE=TypeError;Gp.exports=function(a,e){var t=arguments.length<2?AE(a):e;if(EE(t))return xE(IE(t,a));throw new wE(PE(a)+" is not iterable")}});var zp=m((AM,Qp)=>{"use strict";var kE=ge(),Wp=He(),RE=qr();Qp.exports=function(a,e,t){var r,i;Wp(a);try{if(r=RE(a,"return"),!r){if(e==="throw")throw t;return t}r=kE(r,a)}catch(s){i=!0,r=s}if(e==="throw")throw t;if(i)throw r;return Wp(r),t}});var Va=m((wM,Zp)=>{"use strict";var LE=Wr(),$E=ge(),ME=He(),CE=Fr(),DE=Up(),OE=ka(),Kp=Nr(),BE=Yp(),VE=lo(),Jp=zp(),_E=TypeError,Ba=function(a,e){this.stopped=a,this.result=e},Xp=Ba.prototype;Zp.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=LE(e,r),l,c,p,d,h,f,b,g=function(T){return l&&Jp(l,"normal",T),new Ba(!0,T)},y=function(T){return i?(ME(T),o?u(T[0],T[1],g):u(T[0],T[1])):o?u(T,g):u(T)};if(s)l=a.iterator;else if(n)l=a;else{if(c=VE(a),!c)throw new _E(CE(a)+" is not iterable");if(DE(c)){for(p=0,d=OE(a);d>p;p++)if(h=y(a[p]),h&&Kp(Xp,h))return h;return new Ba(!1)}l=BE(a,c)}for(f=s?a.next:l.next;!(b=$E(f,l)).done;){try{h=y(b.value)}catch(T){Jp(l,"throw",T)}if(typeof h=="object"&&h&&Kp(Xp,h))return h}return new Ba(!1)}});var th=m((kM,eh)=>{"use strict";var NE=xe(),FE=kt(),qE=jr();eh.exports=function(a,e,t){NE?FE.f(a,e,qE(0,t)):a[e]=t}});var rh=m(()=>{"use strict";var UE=Pe(),HE=Va(),jE=th();UE({target:"Object",stat:!0},{fromEntries:function(e){var t={};return HE(e,function(r,i){jE(t,r,i)},{AS_ENTRIES:!0}),t}})});var ah=m(($M,ih)=>{"use strict";uo();rh();var GE=ya();ih.exports=GE.Object.fromEntries});var nh=m((MM,sh)=>{"use strict";sh.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 uh=m(()=>{"use strict";uo();var YE=nh(),WE=Y(),QE=Kr(),oh=wt();for(_a in YE)QE(WE[_a],_a),oh[_a]=oh.Array;var _a});var ch=m((OM,lh)=>{"use strict";var zE=ah();uh();lh.exports=zE});var co=m((BM,dh)=>{"use strict";var KE=ch();dh.exports=KE});var ph=m(()=>{"use strict"});var po=m((NM,hh)=>{"use strict";var Zr=Y(),JE=tr(),XE=Xt(),Na=function(a){return JE.slice(0,a.length)===a};hh.exports=function(){return Na("Bun/")?"BUN":Na("Cloudflare-Workers")?"CLOUDFLARE":Na("Deno/")?"DENO":Na("Node.js/")?"NODE":Zr.Bun&&typeof Bun.version=="string"?"BUN":Zr.Deno&&typeof Deno.version=="object"?"DENO":XE(Zr.process)==="process"?"NODE":Zr.window&&Zr.document?"BROWSER":"REST"}()});var Fa=m((FM,fh)=>{"use strict";var ZE=po();fh.exports=ZE==="NODE"});var bh=m((qM,mh)=>{"use strict";var ex=kt();mh.exports=function(a,e,t){return ex.f(a,e,t)}});var vh=m((UM,Sh)=>{"use strict";var tx=Qe(),rx=bh(),ix=re(),ax=xe(),gh=ix("species");Sh.exports=function(a){var e=tx(a);ax&&e&&!e[gh]&&rx(e,gh,{configurable:!0,get:function(){return this}})}});var Th=m((HM,yh)=>{"use strict";var sx=Nr(),nx=TypeError;yh.exports=function(a,e){if(sx(e,a))return a;throw new nx("Incorrect invocation")}});var fo=m((jM,Ih)=>{"use strict";var ox=ue(),ux=G(),ho=Ur(),lx=ox(Function.toString);ux(ho.inspectSource)||(ho.inspectSource=function(a){return lx(a)});Ih.exports=ho.inspectSource});var kh=m((GM,wh)=>{"use strict";var cx=ue(),dx=be(),Eh=G(),px=zr(),hx=Qe(),fx=fo(),xh=function(){},Ph=hx("Reflect","construct"),mo=/^\s*(?:class|function)\b/,mx=cx(mo.exec),bx=!mo.test(xh),ei=function(e){if(!Eh(e))return!1;try{return Ph(xh,[],e),!0}catch(t){return!1}},Ah=function(e){if(!Eh(e))return!1;switch(px(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return bx||!!mx(mo,fx(e))}catch(t){return!0}};Ah.sham=!0;wh.exports=!Ph||dx(function(){var a;return ei(ei.call)||!ei(Object)||!ei(function(){a=!0})||a})?Ah:ei});var Lh=m((YM,Rh)=>{"use strict";var gx=kh(),Sx=Fr(),vx=TypeError;Rh.exports=function(a){if(gx(a))return a;throw new vx(Sx(a)+" is not a constructor")}});var bo=m((WM,Mh)=>{"use strict";var $h=He(),yx=Lh(),Tx=Zt(),Ix=re(),Ex=Ix("species");Mh.exports=function(a,e){var t=$h(a).constructor,r;return t===void 0||Tx(r=$h(t)[Ex])?e:yx(r)}});var Dh=m((QM,Ch)=>{"use strict";var xx=ue();Ch.exports=xx([].slice)});var Bh=m((zM,Oh)=>{"use strict";var Px=TypeError;Oh.exports=function(a,e){if(a<e)throw new Px("Not enough arguments");return a}});var go=m((KM,Vh)=>{"use strict";var Ax=tr();Vh.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(Ax)});var Ao=m((JM,Yh)=>{"use strict";var Se=Y(),wx=qn(),kx=Wr(),_h=G(),Rx=Be(),Gh=be(),Nh=Qn(),Lx=Dh(),Fh=Sa(),$x=Bh(),Mx=go(),Cx=Fa(),Eo=Se.setImmediate,xo=Se.clearImmediate,Dx=Se.process,So=Se.Dispatch,Ox=Se.Function,qh=Se.MessageChannel,Bx=Se.String,vo=0,ti={},Uh="onreadystatechange",ri,Lt,yo,To;Gh(function(){ri=Se.location});var Po=function(a){if(Rx(ti,a)){var e=ti[a];delete ti[a],e()}},Io=function(a){return function(){Po(a)}},Hh=function(a){Po(a.data)},jh=function(a){Se.postMessage(Bx(a),ri.protocol+"//"+ri.host)};(!Eo||!xo)&&(Eo=function(e){$x(arguments.length,1);var t=_h(e)?e:Ox(e),r=Lx(arguments,1);return ti[++vo]=function(){wx(t,void 0,r)},Lt(vo),vo},xo=function(e){delete ti[e]},Cx?Lt=function(a){Dx.nextTick(Io(a))}:So&&So.now?Lt=function(a){So.now(Io(a))}:qh&&!Mx?(yo=new qh,To=yo.port2,yo.port1.onmessage=Hh,Lt=kx(To.postMessage,To)):Se.addEventListener&&_h(Se.postMessage)&&!Se.importScripts&&ri&&ri.protocol!=="file:"&&!Gh(jh)?(Lt=jh,Se.addEventListener("message",Hh,!1)):Uh in Fh("script")?Lt=function(a){Nh.appendChild(Fh("script"))[Uh]=function(){Nh.removeChild(this),Po(a)}}:Lt=function(a){setTimeout(Io(a),0)});Yh.exports={set:Eo,clear:xo}});var zh=m((XM,Qh)=>{"use strict";var Wh=Y(),Vx=xe(),_x=Object.getOwnPropertyDescriptor;Qh.exports=function(a){if(!Vx)return Wh[a];var e=_x(Wh,a);return e&&e.value}});var wo=m((ZM,Jh)=>{"use strict";var Kh=function(){this.head=null,this.tail=null};Kh.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}}};Jh.exports=Kh});var Zh=m((eC,Xh)=>{"use strict";var Nx=tr();Xh.exports=/ipad|iphone|ipod/i.test(Nx)&&typeof Pebble!="undefined"});var tf=m((tC,ef)=>{"use strict";var Fx=tr();ef.exports=/web0s(?!.*chrome)/i.test(Fx)});var lf=m((rC,uf)=>{"use strict";var ur=Y(),qx=zh(),rf=Wr(),ko=Ao().set,Ux=wo(),Hx=go(),jx=Zh(),Gx=tf(),Ro=Fa(),af=ur.MutationObserver||ur.WebKitMutationObserver,sf=ur.document,nf=ur.process,qa=ur.Promise,Mo=qx("queueMicrotask"),or,Lo,$o,Ua,of;Mo||(ii=new Ux,ai=function(){var a,e;for(Ro&&(a=nf.domain)&&a.exit();e=ii.get();)try{e()}catch(t){throw ii.head&&or(),t}a&&a.enter()},!Hx&&!Ro&&!Gx&&af&&sf?(Lo=!0,$o=sf.createTextNode(""),new af(ai).observe($o,{characterData:!0}),or=function(){$o.data=Lo=!Lo}):!jx&&qa&&qa.resolve?(Ua=qa.resolve(void 0),Ua.constructor=qa,of=rf(Ua.then,Ua),or=function(){of(ai)}):Ro?or=function(){nf.nextTick(ai)}:(ko=rf(ko,ur),or=function(){ko(ai)}),Mo=function(a){ii.head||or(),ii.add(a)});var ii,ai;uf.exports=Mo});var df=m((iC,cf)=>{"use strict";cf.exports=function(a,e){try{arguments.length===1?console.error(a):console.error(a,e)}catch(t){}}});var Ha=m((aC,pf)=>{"use strict";pf.exports=function(a){try{return{error:!1,value:a()}}catch(e){return{error:!0,value:e}}}});var $t=m((sC,hf)=>{"use strict";var Yx=Y();hf.exports=Yx.Promise});var lr=m((nC,gf)=>{"use strict";var Wx=Y(),si=$t(),Qx=G(),zx=Hn(),Kx=fo(),Jx=re(),ff=po(),Xx=Oe(),Co=In(),mf=si&&si.prototype,Zx=Jx("species"),Do=!1,bf=Qx(Wx.PromiseRejectionEvent),eP=zx("Promise",function(){var a=Kx(si),e=a!==String(si);if(!e&&Co===66||Xx&&!(mf.catch&&mf.finally))return!0;if(!Co||Co<51||!/native code/.test(a)){var t=new si(function(s){s(1)}),r=function(s){s(function(){},function(){})},i=t.constructor={};if(i[Zx]=r,Do=t.then(function(){})instanceof r,!Do)return!0}return!e&&(ff==="BROWSER"||ff==="DENO")&&!bf});gf.exports={CONSTRUCTOR:eP,REJECTION_EVENT:bf,SUBCLASSING:Do}});var cr=m((oC,vf)=>{"use strict";var Sf=ze(),tP=TypeError,rP=function(a){var e,t;this.promise=new a(function(r,i){if(e!==void 0||t!==void 0)throw new tP("Bad Promise constructor");e=r,t=i}),this.resolve=Sf(e),this.reject=Sf(t)};vf.exports.f=function(a){return new rP(a)}});var _f=m(()=>{"use strict";var iP=Pe(),aP=Oe(),Wa=Fa(),ct=Y(),fr=ge(),yf=nr(),Tf=so(),sP=Kr(),nP=vh(),oP=ze(),Ya=G(),uP=Ee(),lP=Th(),cP=bo(),Af=Ao().set,No=lf(),dP=df(),pP=Ha(),hP=wo(),wf=Fn(),Qa=$t(),Fo=lr(),kf=cr(),za="Promise",Rf=Fo.CONSTRUCTOR,fP=Fo.REJECTION_EVENT,mP=Fo.SUBCLASSING,Oo=wf.getterFor(za),bP=wf.set,dr=Qa&&Qa.prototype,Mt=Qa,ja=dr,Lf=ct.TypeError,Bo=ct.document,qo=ct.process,Vo=kf.f,gP=Vo,SP=!!(Bo&&Bo.createEvent&&ct.dispatchEvent),$f="unhandledrejection",vP="rejectionhandled",If=0,Mf=1,yP=2,Uo=1,Cf=2,Ga,Ef,TP,xf,Df=function(a){var e;return uP(a)&&Ya(e=a.then)?e:!1},Of=function(a,e){var t=e.value,r=e.state===Mf,i=r?a.ok:a.fail,s=a.resolve,n=a.reject,o=a.domain,u,l,c;try{i?(r||(e.rejection===Cf&&EP(e),e.rejection=Uo),i===!0?u=t:(o&&o.enter(),u=i(t),o&&(o.exit(),c=!0)),u===a.promise?n(new Lf("Promise-chain cycle")):(l=Df(u))?fr(l,u,s,n):s(u)):n(t)}catch(p){o&&!c&&o.exit(),n(p)}},Bf=function(a,e){a.notified||(a.notified=!0,No(function(){for(var t=a.reactions,r;r=t.get();)Of(r,a);a.notified=!1,e&&!a.rejection&&IP(a)}))},Vf=function(a,e,t){var r,i;SP?(r=Bo.createEvent("Event"),r.promise=e,r.reason=t,r.initEvent(a,!1,!0),ct.dispatchEvent(r)):r={promise:e,reason:t},!fP&&(i=ct["on"+a])?i(r):a===$f&&dP("Unhandled promise rejection",t)},IP=function(a){fr(Af,ct,function(){var e=a.facade,t=a.value,r=Pf(a),i;if(r&&(i=pP(function(){Wa?qo.emit("unhandledRejection",t,e):Vf($f,e,t)}),a.rejection=Wa||Pf(a)?Cf:Uo,i.error))throw i.value})},Pf=function(a){return a.rejection!==Uo&&!a.parent},EP=function(a){fr(Af,ct,function(){var e=a.facade;Wa?qo.emit("rejectionHandled",e):Vf(vP,e,a.value)})},pr=function(a,e,t){return function(r){a(e,r,t)}},hr=function(a,e,t){a.done||(a.done=!0,t&&(a=t),a.value=e,a.state=yP,Bf(a,!0))},_o=function(a,e,t){if(!a.done){a.done=!0,t&&(a=t);try{if(a.facade===e)throw new Lf("Promise can't be resolved itself");var r=Df(e);r?No(function(){var i={done:!1};try{fr(r,e,pr(_o,i,a),pr(hr,i,a))}catch(s){hr(i,s,a)}}):(a.value=e,a.state=Mf,Bf(a,!1))}catch(i){hr({done:!1},i,a)}}};if(Rf&&(Mt=function(e){lP(this,ja),oP(e),fr(Ga,this);var t=Oo(this);try{e(pr(_o,t),pr(hr,t))}catch(r){hr(t,r)}},ja=Mt.prototype,Ga=function(e){bP(this,{type:za,done:!1,notified:!1,parent:!1,reactions:new hP,rejection:!1,state:If,value:void 0})},Ga.prototype=yf(ja,"then",function(e,t){var r=Oo(this),i=Vo(cP(this,Mt));return r.parent=!0,i.ok=Ya(e)?e:!0,i.fail=Ya(t)&&t,i.domain=Wa?qo.domain:void 0,r.state===If?r.reactions.add(i):No(function(){Of(i,r)}),i.promise}),Ef=function(){var a=new Ga,e=Oo(a);this.promise=a,this.resolve=pr(_o,e),this.reject=pr(hr,e)},kf.f=Vo=function(a){return a===Mt||a===TP?new Ef(a):gP(a)},!aP&&Ya(Qa)&&dr!==Object.prototype)){xf=dr.then,mP||yf(dr,"then",function(e,t){var r=this;return new Mt(function(i,s){fr(xf,r,i,s)}).then(e,t)},{unsafe:!0});try{delete dr.constructor}catch(a){}Tf&&Tf(dr,ja)}iP({global:!0,constructor:!0,wrap:!0,forced:Rf},{Promise:Mt});sP(Mt,za,!1,!0);nP(za)});var Hf=m((cC,Uf)=>{"use strict";var xP=re(),Ff=xP("iterator"),qf=!1;try{Nf=0,Ho={next:function(){return{done:!!Nf++}},return:function(){qf=!0}},Ho[Ff]=function(){return this},Array.from(Ho,function(){throw 2})}catch(a){}var Nf,Ho;Uf.exports=function(a,e){try{if(!e&&!qf)return!1}catch(i){return!1}var t=!1;try{var r={};r[Ff]=function(){return{next:function(){return{done:t=!0}}}},a(r)}catch(i){}return t}});var jo=m((dC,jf)=>{"use strict";var PP=$t(),AP=Hf(),wP=lr().CONSTRUCTOR;jf.exports=wP||!AP(function(a){PP.all(a).then(void 0,function(){})})});var Gf=m(()=>{"use strict";var kP=Pe(),RP=ge(),LP=ze(),$P=cr(),MP=Ha(),CP=Va(),DP=jo();kP({target:"Promise",stat:!0,forced:DP},{all:function(e){var t=this,r=$P.f(t),i=r.resolve,s=r.reject,n=MP(function(){var o=LP(t.resolve),u=[],l=0,c=1;CP(e,function(p){var d=l++,h=!1;c++,RP(o,t,p).then(function(f){h||(h=!0,u[d]=f,--c||i(u))},s)}),--c||i(u)});return n.error&&s(n.value),r.promise}})});var Wf=m(()=>{"use strict";var OP=Pe(),BP=Oe(),VP=lr().CONSTRUCTOR,Yo=$t(),_P=Qe(),NP=G(),FP=nr(),Yf=Yo&&Yo.prototype;OP({target:"Promise",proto:!0,forced:VP,real:!0},{catch:function(a){return this.then(void 0,a)}});!BP&&NP(Yo)&&(Go=_P("Promise").prototype.catch,Yf.catch!==Go&&FP(Yf,"catch",Go,{unsafe:!0}));var Go});var Qf=m(()=>{"use strict";var qP=Pe(),UP=ge(),HP=ze(),jP=cr(),GP=Ha(),YP=Va(),WP=jo();qP({target:"Promise",stat:!0,forced:WP},{race:function(e){var t=this,r=jP.f(t),i=r.reject,s=GP(function(){var n=HP(t.resolve);YP(e,function(o){UP(n,t,o).then(r.resolve,i)})});return s.error&&i(s.value),r.promise}})});var zf=m(()=>{"use strict";var QP=Pe(),zP=cr(),KP=lr().CONSTRUCTOR;QP({target:"Promise",stat:!0,forced:KP},{reject:function(e){var t=zP.f(this),r=t.reject;return r(e),t.promise}})});var Wo=m((yC,Kf)=>{"use strict";var JP=He(),XP=Ee(),ZP=cr();Kf.exports=function(a,e){if(JP(a),XP(e)&&e.constructor===a)return e;var t=ZP.f(a),r=t.resolve;return r(e),t.promise}});var Zf=m(()=>{"use strict";var eA=Pe(),tA=Qe(),Jf=Oe(),rA=$t(),Xf=lr().CONSTRUCTOR,iA=Wo(),aA=tA("Promise"),sA=Jf&&!Xf;eA({target:"Promise",stat:!0,forced:Jf||Xf},{resolve:function(e){return iA(sA&&this===aA?rA:this,e)}})});var em=m(()=>{"use strict";_f();Gf();Wf();Qf();zf();Zf()});var am=m(()=>{"use strict";var nA=Pe(),oA=Oe(),Ka=$t(),uA=be(),rm=Qe(),im=G(),lA=bo(),tm=Wo(),cA=nr(),zo=Ka&&Ka.prototype,dA=!!Ka&&uA(function(){zo.finally.call({then:function(){}},function(){})});nA({target:"Promise",proto:!0,real:!0,forced:dA},{finally:function(a){var e=lA(this,rm("Promise")),t=im(a);return this.then(t?function(r){return tm(e,a()).then(function(){return r})}:a,t?function(r){return tm(e,a()).then(function(){throw r})}:a)}});!oA&&im(Ka)&&(Qo=rm("Promise").prototype.finally,zo.finally!==Qo&&cA(zo,"finally",Qo,{unsafe:!0}));var Qo});var Ja=m((wC,sm)=>{"use strict";var pA=Qe();sm.exports=pA});var om=m((kC,nm)=>{"use strict";ph();em();am();var hA=Ja();nm.exports=hA("Promise","finally")});var lm=m((RC,um)=>{"use strict";var fA=om();um.exports=fA});var Xa=m((LC,cm)=>{"use strict";var mA=lm();cm.exports=mA});var Om=m(()=>{"use strict";var jA=Pe(),GA=Hr(),YA=ka(),WA=wa(),QA=hn();jA({target:"Array",proto:!0},{at:function(e){var t=GA(this),r=YA(t),i=WA(e),s=i>=0?i:r+i;return s<0||s>=r?void 0:t[s]}});QA("at")});var Vm=m((ND,Bm)=>{"use strict";Om();var zA=Ja();Bm.exports=zA("Array","at")});var Nm=m((FD,_m)=>{"use strict";var KA=Vm();_m.exports=KA});var li=m((qD,Fm)=>{"use strict";var JA=Nm();Fm.exports=JA});var jb=m(()=>{"use strict"});var Gb=m(()=>{"use strict"});var Wb=m((qV,Yb)=>{"use strict";var ak=Ee(),sk=Xt(),nk=re(),ok=nk("match");Yb.exports=function(a){var e;return ak(a)&&((e=a[ok])!==void 0?!!e:sk(a)==="RegExp")}});var zb=m((UV,Qb)=>{"use strict";var uk=zr(),lk=String;Qb.exports=function(a){if(uk(a)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return lk(a)}});var Jb=m((HV,Kb)=>{"use strict";var ck=He();Kb.exports=function(){var a=ck(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 eg=m((jV,Zb)=>{"use strict";var dk=ge(),pk=Be(),hk=Nr(),fk=Jb(),Xb=RegExp.prototype;Zb.exports=function(a){var e=a.flags;return e===void 0&&!("flags"in Xb)&&!pk(a,"flags")&&hk(Xb,a)?dk(fk,a):e}});var rg=m((GV,tg)=>{"use strict";var Pu=ue(),mk=Hr(),bk=Math.floor,Eu=Pu("".charAt),gk=Pu("".replace),xu=Pu("".slice),Sk=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,vk=/\$([$&'`]|\d{1,2})/g;tg.exports=function(a,e,t,r,i,s){var n=t+a.length,o=r.length,u=vk;return i!==void 0&&(i=mk(i),u=Sk),gk(s,u,function(l,c){var p;switch(Eu(c,0)){case"$":return"$";case"&":return a;case"`":return xu(e,0,t);case"'":return xu(e,n);case"<":p=i[xu(c,1,-1)];break;default:var d=+c;if(d===0)return l;if(d>o){var h=bk(d/10);return h===0?l:h<=o?r[h-1]===void 0?Eu(c,1):r[h-1]+Eu(c,1):l}p=r[d-1]}return p===void 0?"":p})}});var sg=m(()=>{"use strict";var yk=Pe(),Tk=ge(),wu=ue(),ig=Vr(),Ik=G(),Ek=Zt(),xk=Wb(),xr=zb(),Pk=qr(),Ak=eg(),wk=rg(),kk=re(),Rk=Oe(),Lk=kk("replace"),$k=TypeError,Au=wu("".indexOf),Mk=wu("".replace),ag=wu("".slice),Ck=Math.max;yk({target:"String",proto:!0},{replaceAll:function(e,t){var r=ig(this),i,s,n,o,u,l,c,p,d,h,f=0,b="";if(!Ek(e)){if(i=xk(e),i&&(s=xr(ig(Ak(e))),!~Au(s,"g")))throw new $k("`.replaceAll` does not allow non-global regexes");if(n=Pk(e,Lk),n)return Tk(n,e,r,t);if(Rk&&i)return Mk(xr(r),e,t)}for(o=xr(r),u=xr(e),l=Ik(t),l||(t=xr(t)),c=u.length,p=Ck(1,c),d=Au(o,u);d!==-1;)h=l?xr(t(u,d,o)):wk(u,o,d,[],void 0,t),b+=ag(o,f,d)+h,f=d+c,d=d+p>o.length?-1:Au(o,u,d+p);return f<o.length&&(b+=ag(o,f)),b}})});var og=m((QV,ng)=>{"use strict";jb();Gb();sg();var Dk=Ja();ng.exports=Dk("String","replaceAll")});var lg=m((zV,ug)=>{"use strict";var Ok=og();ug.exports=Ok});var dg=m((KV,cg)=>{"use strict";var Bk=lg();cg.exports=Bk});var Rl="2.0.108-dev.43b53ca1.0";var oe=(i=>(i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused",i))(oe||{}),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 ma=(i=>(i.NOT_AVAILABLE="NOT_AVAILABLE",i.AVAILABLE="AVAILABLE",i.CONNECTING="CONNECTING",i.CONNECTED="CONNECTED",i))(ma||{}),on=(r=>(r.HTTP1="http1",r.HTTP2="http2",r.QUIC="quic",r))(on||{});var un=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(un||{});import{assertNever as Ol,assertNonNullable as tv,isNonNullable as ba,ValueSubject as ln,Subject as rv,Subscription as iv,merge as av,observableFrom as sv,fromEvent as $l,map as Ml,tap as Cl,filterChanged as nv,isNullable as cn,ErrorCategory as Dl}from"@vkontakte/videoplayer-shared";var Ll=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 ga=class{constructor(e){this.connection$=new ln(void 0);this.castState$=new ln("NOT_AVAILABLE");this.errorEvent$=new rv;this.realCastState$=new ln("NOT_AVAILABLE");this.subscription=new iv;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=ba((s=window.chrome)==null?void 0:s.cast),i=!!window.__onGCastApiAvailable;r?this.initializeCastApi():(window.__onGCastApiAvailable=n=>{delete window.__onGCastApiAvailable,n&&this.initializeCastApi()},i||Ll("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:Dl.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(){ba(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();cn(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();cn(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($l(r,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(i=>{var s,n;switch(i.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=(n=(s=r.getCurrentSession())==null?void 0:s.getMediaSession())==null?void 0:n.media.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return Ol(i.sessionState)}})).add(av($l(r,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(Cl(i=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(i)}`})}),Ml(i=>i.castState)),sv([r.getCastState()])).pipe(nv(),Ml(ov),Cl(i=>{this.log({message:`realCastState$: ${i}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(i=>{var o;let s=i==="CONNECTED",n=ba(this.connection$.getValue());if(s&&!n){let u=r.getCurrentSession();tv(u);let l=u.getCastDevice(),c=(o=u.getMediaSession())==null?void 0:o.media.contentId;(cn(c)||c===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:u,castDevice:l}))}else!s&&n&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(i==="CONNECTED"?ba(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:Dl.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:s})}}},ov=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 Ol(a)}};var cS=Ue(co(),1);var ym=Ue(Xa(),1);import{assertNever as dm}from"@vkontakte/videoplayer-shared";var te=(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:dm(t)}return a},Ko=(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:dm(e)}};var E=(a,e,t=!1)=>{let r=a.getTransition();(t||!r||r.to===e)&&a.setState(e)};import{isNonNullable as bA,Subject as Za,merge as pm}from"@vkontakte/videoplayer-shared";var $=class{constructor(e){this.transitionStarted$=new Za;this.transitionEnded$=new Za;this.transitionUpdated$=new Za;this.forceChanged$=new Za;this.stateChangeStarted$=pm(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=pm(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||bA(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 gA}from"@vkontakte/videoplayer-shared";var hm=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 gA(a)}};import{assertNever as mr,assertNonNullable as Ct,debounce as fm,ErrorCategory as mm,fromEvent as Dt,isNonNullable as bm,map as gm,merge as Sm,observableFrom as SA,Subject as vA,Subscription as Jo,timeout as yA,getHighestQuality as TA}from"@vkontakte/videoplayer-shared";var IA=5,EA=5,xA=500,vm=7e3,ni=class{constructor(e){this.subscription=new Jo;this.loadMediaTimeoutSubscription=new Jo;this.videoState=new $("stopped");this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),r=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${r}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(s)};`}),r==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.stop());return}if(!t){if((i==null?void 0:i.to)!=="paused"&&s.state==="requested"&&e!=="stopped"){this.seek(s.position/1e3);return}switch(r){case"ready":{switch(e){case"playing":case"paused":case"ready":break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:mr(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:mr(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:mr(e)}break}default:mr(r)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(hm(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 Jo;this.subscription.add(e),this.subscription.add(Sm(this.videoState.stateChangeStarted$.pipe(gm(i=>`stateChangeStarted$ ${JSON.stringify(i)}`)),this.videoState.stateChangeEnded$.pipe(gm(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 vA;e.add(i.pipe(fm(xA)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add(Dt(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)>IA)&&i.next(o),s=o})),e.add(Dt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(Dt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),i=>{this.logRemoteEvent(i),i.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(Dt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),i=>{this.logRemoteEvent(i),i.value?this.handleRemotePause():this.handleRemotePlay()}),t(Dt(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<EA&&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:mr(n)}}),t(Dt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),i=>{this.logRemoteEvent(i),this.handleRemoteVolumeChange({volume:i.value})}),t(Dt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),i=>{this.logRemoteEvent(i),this.handleRemoteVolumeChange({muted:i.value})});let r=Sm(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,SA(["init"])).pipe(fm(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];Ct(c);let p=TA(Object.keys(c));Ct(p);let d=c[p];Ct(d),r=d,i="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let c=t[e];Ct(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];Ct(c),r=c.url,i="application/dash+xml",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let c=t[e];Ct(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];Ct(c),r=te(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",p=new Error(c);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:mm.VIDEO_PIPELINE,message:c,thrown:p}),p}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return mr(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 bm(o)&&(n.metadata.title=o),bm(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(yA(vm).subscribe(()=>s(`timeout(${vm})`)))});(0,ym.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:mm.VIDEO_PIPELINE,message:s,thrown:i})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};import{clearVideoElement as Im}from"@vkontakte/videoplayer-shared";import{clearVideoElement as PA}from"@vkontakte/videoplayer-shared";var Tm=a=>{try{a.pause(),a.playbackRate=0,PA(a),a.remove()}catch(e){console.error(e)}};import{fromEvent as AA,Subscription as wA}from"@vkontakte/videoplayer-shared";var Xo=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)}},Zo=window.WeakMap?new WeakMap:new Xo,eu=window.WeakMap?new WeakMap:new Map,kA=(a,e=20)=>{let t=0;return AA(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?Im(t):(t=document.createElement("video"),a.appendChild(t)),Zo.set(t,r);let i=new wA;return i.add(kA(t,e)),eu.set(t,i),t.setAttribute("crossorigin","anonymous"),t.setAttribute("playsinline","playsinline"),t.controls=!1,t.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),t},ce=a=>{let e=eu.get(a);e==null||e.unsubscribe(),eu.delete(a);let t=Zo.get(a);Zo.delete(a),t?Im(a):Tm(a)};import{assertNonNullable as oi,isNonNullable as Ge,isNullable as $A,fromEvent as br,merge as Em,observableFrom as xm,filterChanged as Pm,map as ui,Subject as Am,Subscription as MA,ValueSubject as CA,ErrorCategory as DA}from"@vkontakte/videoplayer-shared";import{isNonNullable as tu,isNullable as RA,Subscription as LA}from"@vkontakte/videoplayer-shared";var es=(a,e,t,{equal:r=(n,o)=>n===o,changed$:i,onError:s}={})=>{let n=a.getState(),o=e(),u=RA(i),l=new LA;return i&&l.add(i.subscribe(c=>{let p=a.getState();r(c,p)&&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},je=(a,e,t)=>es(e,()=>a.loop,r=>{tu(r)&&(a.loop=r)},{onError:t}),de=(a,e,t,r)=>es(e,()=>({muted:a.muted,volume:a.volume}),i=>{tu(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}),Ae=(a,e,t,r)=>es(e,()=>a.playbackRate,i=>{tu(i)&&(a.playbackRate=i)},{changed$:t,onError:r}),dt=es;var OA=a=>["__",a.language,a.label].join("|"),BA=(a,e)=>{if(a.id===e)return!0;let[t,r,i]=e.split("|");return a.language===r&&a.label===i},ru=class a{constructor(){this.available$=new Am;this.current$=new CA(void 0);this.error$=new Am;this.subscription=new MA;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:DA.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:s})};this.subscription.add(this.available$.subscribe(r.availableTextTracks$)),this.subscription.add(this.current$.subscribe(r.currentTextTrack$)),this.subscription.add(this.error$.subscribe(r.error$)),this.subscription.add(dt(t.internalTextTracks,()=>Object.values(this.internalTracks),s=>{Ge(s)&&this.setInternal(s)},{equal:(s,n)=>Ge(s)&&Ge(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(ui(s=>s.filter(({type:n})=>n==="internal"))),onError:i})),this.subscription.add(dt(t.externalTextTracks,()=>Object.values(this.externalTracks),s=>{Ge(s)&&this.setExternal(s)},{equal:(s,n)=>Ge(s)&&Ge(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(ui(s=>s.filter(({type:n})=>n==="external"))),onError:i})),this.subscription.add(dt(t.currentTextTrack,()=>{if(this.video)return;let s=this.htmlTextTracksAsArray().find(({mode:n})=>n==="showing");return s&&this.htmlTextTrackToITextTrack(s).id},s=>this.select(s),{changed$:this.current$,onError:i})),this.subscription.add(dt(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.activeCues)}))}subscribe(){oi(this.video);let{textTracks:e}=this.video;this.subscription.add(br(e,"addtrack").subscribe(()=>{let r=this.current$.getValue();r&&this.select(r)})),this.subscription.add(Em(br(e,"addtrack"),br(e,"removetrack"),xm(["init"])).pipe(ui(()=>this.htmlTextTracksAsArray().map(r=>this.htmlTextTrackToITextTrack(r))),Pm((r,i)=>r.length===i.length&&r.every(({id:s},n)=>s===i[n].id))).subscribe(this.available$)),this.subscription.add(Em(br(e,"change"),xm(["init"])).pipe(ui(()=>this.htmlTextTracksAsArray().find(({mode:r})=>r==="showing")),ui(r=>r&&this.htmlTextTrackToITextTrack(r).id),Pm()).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(br(e,"addtrack").subscribe(r=>{var s,n;(s=r.track)==null||s.addEventListener("cuechange",t);let i=o=>{var l,c,p,d,h;let u=(c=(l=o.target)==null?void 0:l.cues)!=null?c:null;u&&u.length&&(this.applyCueSettings((d=(p=o.target)==null?void 0:p.cues)!=null?d:null),(h=o.target)==null||h.removeEventListener("cuechange",i))};(n=r.track)==null||n.addEventListener("cuechange",i)})),this.subscription.add(br(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;Ge(t.align)&&(i.align=t.align),Ge(t.position)&&(i.position=t.position),Ge(t.size)&&(i.size=t.size),Ge(t.line)&&(i.line=t.line)}}htmlTextTracksAsArray(e=!1){oi(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:OA(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){oi(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))($A(e)||!BA(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){oi(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){oi(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)}},we=ru;var Xe=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 wm=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},iu=a=>{let e=wm(a);return!!(e&&e.fullscreenElement&&e.fullscreenElement===a)},km=a=>{let e=wm(a);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===a)};import{fromEvent as ke,map as pt,merge as Lm,filterChanged as _A,isNonNullable as $m,Subject as NA,filter as Mm,mapTo as Cm,combine as FA,once as qA,ErrorCategory as UA,ValueSubject as Dm,clientChecker as HA}from"@vkontakte/videoplayer-shared";var VA=3,Rm=(a,e,t=VA)=>{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 pe=a=>{let e=S=>ke(a,S).pipe(Cm(void 0)),r=Lm(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(S=>ke(a,S))).pipe(pt(S=>S.type==="ended"?a.readyState<2:a.readyState<3),_A()),i=Lm(ke(a,"progress"),ke(a,"timeupdate")).pipe(pt(()=>Rm(a.buffered,a.currentTime))),s=HA.isSafari?FA({play:e("play").pipe(qA()),playing:e("playing")}).pipe(Cm(void 0)):e("playing"),n=ke(a,"volumechange").pipe(pt(()=>({muted:a.muted,volume:a.volume}))),o=ke(a,"ratechange").pipe(pt(()=>a.playbackRate)),u=ke(a,"error").pipe(Mm(()=>!!(a.error||a.played.length)),pt(()=>{var v;let S=a.error;return{id:S?`MediaError#${S.code}`:"HtmlVideoError",category:UA.VIDEO_PIPELINE,message:S?S.message:"Error event from HTML video element",thrown:(v=a.error)!=null?v:void 0}})),l=ke(a,"timeupdate").pipe(pt(()=>a.currentTime)),c=new NA,p=.3,d;l.subscribe(S=>{a.loop&&$m(d)&&$m(S)&&d>=a.duration-p&&S<=p&&c.next(d),d=S});let h=e("pause").pipe(Mm(()=>!a.error&&d!==a.duration)),f=ke(a,"enterpictureinpicture"),b=ke(a,"leavepictureinpicture"),g=new Dm(km(a));f.subscribe(()=>g.next(!0)),b.subscribe(()=>g.next(!1));let y=new Dm(iu(a));return ke(a,"fullscreenchange").pipe(pt(()=>iu(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$:ke(a,"durationchange").pipe(pt(()=>a.duration)),isBuffering$:r,currentBuffer$:i,volumeState$:n,playbackRateState$:o,inPiP$:g,inFullscreen$:y}};import{VideoQuality as ht}from"@vkontakte/videoplayer-shared";var ft=a=>{switch(a){case"mobile":return ht.Q_144P;case"lowest":return ht.Q_240P;case"low":return ht.Q_360P;case"sd":case"medium":return ht.Q_480P;case"hd":case"high":return ht.Q_720P;case"fullhd":case"full":return ht.Q_1080P;case"quadhd":case"quad":return ht.Q_1440P;case"ultrahd":case"ultra":return ht.Q_2160P}};var Ot=Ue(li(),1);import{isNonNullable as ve,isNullable as su,now as Wm,isHigher as nu,isHigherOrEqual as jm,isInvariantQuality as Gm,isLower as ou,isLowerOrEqual as XA,videoSizeToQuality as ZA,assertNotEmptyArray as Qm,assertNonNullable as ew}from"@vkontakte/videoplayer-shared";var au=!1,Ze={},qm=a=>{au=a},Um=()=>{Ze={}},Hm=a=>{a(Ze)},ci=(a,e)=>{var t;au&&(Ze.meta=(t=Ze.meta)!=null?t:{},Ze.meta[a]=e)},ie=class{constructor(e){this.name=e}next(e){var r,i;if(!au)return;Ze.series=(r=Ze.series)!=null?r:{};let t=(i=Ze.series[this.name])!=null?i:[];t.push([Date.now(),e]),Ze.series[this.name]=t}};var tw=new ie("best_bitrate"),zm=(a,e,t)=>(e-t)*Math.pow(2,-10*a)+t;var uu=a=>(e,t)=>a*(Number(e.bitrate)-Number(t.bitrate)),di=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=Wm()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},Km='Assertion "ABR Tracks is empty array" failed',ts=(a,e,t,r)=>{var u;let i=[...e].sort(uu(1)),s=[...t].sort(uu(1)),n=s.filter(l=>ve(l.bitrate)&&ve(a.bitrate)?a.bitrate/l.bitrate>r:!0),o=(u=(0,Ot.default)(s,Math.round(s.length*i.indexOf(a)/(i.length+1))))!=null?u:(0,Ot.default)(s,-1);return o&&n.includes(o)?o:n.length?(0,Ot.default)(n,-1):(0,Ot.default)(s,0)},Ym=a=>"quality"in a,Jm=(a,e,t,r)=>{let i=t&&r&&r.history[t.id]&&Wm()-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=Ym(s)?"video":"audio",o=Ym(s)?s.quality:s.bitrate;return e({message:`
|
|
7
|
-
[
|
|
8
|
-
`}),s}return r==null||r.recordSwitch(t),t},mt=(a,{container:e,throughput:t,tuning:r,limits:i,reserve:s=0,forwardBufferHealth:n,playbackRate:o,current:u,history:l,droppedVideoMaxQualityLimit:c,abrLogger:p})=>{var F,R,L,A,q;Qm(a,Km);let d=r.usePixelRatio&&(F=window.devicePixelRatio)!=null?F:1,h=r.limitByContainer&&e&&e.width>0&&e.height>0&&{width:e.width*d*r.containerSizeFactor,height:e.height*d*r.containerSizeFactor},f=h&&ZA(h),b=r.considerPlaybackRate&&ve(o)?o:1,g=a.filter(k=>!Gm(k.quality)).sort((k,Q)=>nu(k.quality,Q.quality)?-1:1),y=(R=(0,Ot.default)(g,-1))==null?void 0:R.quality,T=(L=(0,Ot.default)(g,0))==null?void 0:L.quality,S=su(i)||ve(i.min)&&ve(i.max)&&ou(i.max,i.min)||ve(i.min)&&T&&nu(i.min,T)||ve(i.max)&&y&&ou(i.max,y),v=b*zm(n!=null?n:.5,r.bitrateFactorAtEmptyBuffer,r.bitrateFactorAtFullBuffer),I={},C=g.filter(k=>(f?ou(k.quality,f):!0)?(ve(t)&&isFinite(t)&&ve(k.bitrate)?t-s>=k.bitrate*v:!0)?r.lazyQualitySwitch&&ve(r.minBufferToSwitchUp)&&u&&!Gm(u.quality)&&(n!=null?n:0)<r.minBufferToSwitchUp&&nu(k.quality,u.quality)?(I[k.quality]="Buffer",!1):!!c&&jm(k.quality,c)?(I[k.quality]="DroppedFramesLimit",!1):S||(su(i.max)||XA(k.quality,i.max))&&(su(i.min)||jm(k.quality,i.min))?!0:(I[k.quality]="FitsQualityLimits",!1):(I[k.quality]="FitsThroughput",!1):(I[k.quality]="FitsContainer",!1))[0];C&&C.bitrate&&tw.next(C.bitrate);let D=(A=C!=null?C:g[Math.ceil((g.length-1)/2)])!=null?A:a[0];return D.quality!==((q=l==null?void 0:l.last)==null?void 0:q.quality)&&p({message:`
|
|
9
|
-
[VIDEO TRACKS ABR]
|
|
10
|
-
[available video tracks]
|
|
6
|
+
var qS=Object.create;var wl=Object.defineProperty;var US=Object.getOwnPropertyDescriptor;var HS=Object.getOwnPropertyNames;var jS=Object.getPrototypeOf,GS=Object.prototype.hasOwnProperty;var m=(a,e)=>()=>(e||a((e={exports:{}}).exports,e),e.exports);var YS=(a,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of HS(e))!GS.call(a,i)&&i!==t&&wl(a,i,{get:()=>e[i],enumerable:!(r=US(e,i))||r.enumerable});return a};var Fe=(a,e,t)=>(t=a!=null?qS(jS(a)):{},YS(e||!a||!a.__esModule?wl(t,"default",{value:a,enumerable:!0}):t,a));var be=m((HL,Dl)=>{"use strict";Dl.exports=function(a){try{return!!a()}catch(e){return!0}}});var Or=m((jL,Ol)=>{"use strict";var ev=be();Ol.exports=!ev(function(){var a=function(){}.bind();return typeof a!="function"||a.hasOwnProperty("prototype")})});var oe=m((GL,_l)=>{"use strict";var Bl=Or(),Vl=Function.prototype,ln=Vl.call,tv=Bl&&Vl.bind.bind(ln,ln);_l.exports=Bl?tv:function(a){return function(){return ln.apply(a,arguments)}}});var Jt=m((YL,Fl)=>{"use strict";var Nl=oe(),rv=Nl({}.toString),iv=Nl("".slice);Fl.exports=function(a){return iv(rv(a),8,-1)}});var Ul=m((WL,ql)=>{"use strict";var av=oe(),sv=be(),nv=Jt(),cn=Object,ov=av("".split);ql.exports=sv(function(){return!cn("z").propertyIsEnumerable(0)})?function(a){return nv(a)==="String"?ov(a,""):cn(a)}:cn});var Xt=m((QL,Hl)=>{"use strict";Hl.exports=function(a){return a==null}});var Br=m((zL,jl)=>{"use strict";var uv=Xt(),lv=TypeError;jl.exports=function(a){if(uv(a))throw new lv("Can't call method on "+a);return a}});var Zt=m((KL,Gl)=>{"use strict";var cv=Ul(),dv=Br();Gl.exports=function(a){return cv(dv(a))}});var dn=m((JL,Yl)=>{"use strict";Yl.exports=function(){}});var Pt=m((XL,Wl)=>{"use strict";Wl.exports={}});var Y=m((pn,Ql)=>{"use strict";var Vr=function(a){return a&&a.Math===Math&&a};Ql.exports=Vr(typeof globalThis=="object"&&globalThis)||Vr(typeof window=="object"&&window)||Vr(typeof self=="object"&&self)||Vr(typeof global=="object"&&global)||Vr(typeof pn=="object"&&pn)||function(){return this}()||Function("return this")()});var G=m((ZL,zl)=>{"use strict";var hn=typeof document=="object"&&document.all;zl.exports=typeof hn=="undefined"&&hn!==void 0?function(a){return typeof a=="function"||a===hn}:function(a){return typeof a=="function"}});var Xl=m((e$,Jl)=>{"use strict";var pv=Y(),hv=G(),Kl=pv.WeakMap;Jl.exports=hv(Kl)&&/native code/.test(String(Kl))});var Ie=m((t$,Zl)=>{"use strict";var fv=G();Zl.exports=function(a){return typeof a=="object"?a!==null:fv(a)}});var Ee=m((r$,ec)=>{"use strict";var mv=be();ec.exports=!mv(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var ba=m((i$,rc)=>{"use strict";var bv=Y(),tc=Ie(),fn=bv.document,gv=tc(fn)&&tc(fn.createElement);rc.exports=function(a){return gv?fn.createElement(a):{}}});var mn=m((a$,ic)=>{"use strict";var Sv=Ee(),vv=be(),yv=ba();ic.exports=!Sv&&!vv(function(){return Object.defineProperty(yv("div"),"a",{get:function(){return 7}}).a!==7})});var bn=m((s$,ac)=>{"use strict";var Tv=Ee(),Iv=be();ac.exports=Tv&&Iv(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var qe=m((n$,sc)=>{"use strict";var Ev=Ie(),xv=String,Pv=TypeError;sc.exports=function(a){if(Ev(a))return a;throw new Pv(xv(a)+" is not an object")}});var ge=m((o$,nc)=>{"use strict";var wv=Or(),ga=Function.prototype.call;nc.exports=wv?ga.bind(ga):function(){return ga.apply(ga,arguments)}});var Sa=m((u$,oc)=>{"use strict";oc.exports={}});var Ge=m((l$,lc)=>{"use strict";var gn=Sa(),Sn=Y(),Av=G(),uc=function(a){return Av(a)?a:void 0};lc.exports=function(a,e){return arguments.length<2?uc(gn[a])||uc(Sn[a]):gn[a]&&gn[a][e]||Sn[a]&&Sn[a][e]}});var _r=m((c$,cc)=>{"use strict";var kv=oe();cc.exports=kv({}.isPrototypeOf)});var er=m((d$,hc)=>{"use strict";var Rv=Y(),dc=Rv.navigator,pc=dc&&dc.userAgent;hc.exports=pc?String(pc):""});var yn=m((p$,vc)=>{"use strict";var Sc=Y(),vn=er(),fc=Sc.process,mc=Sc.Deno,bc=fc&&fc.versions||mc&&mc.version,gc=bc&&bc.v8,Me,va;gc&&(Me=gc.split("."),va=Me[0]>0&&Me[0]<4?1:+(Me[0]+Me[1]));!va&&vn&&(Me=vn.match(/Edge\/(\d+)/),(!Me||Me[1]>=74)&&(Me=vn.match(/Chrome\/(\d+)/),Me&&(va=+Me[1])));vc.exports=va});var Tn=m((h$,Tc)=>{"use strict";var yc=yn(),Lv=be(),$v=Y(),Mv=$v.String;Tc.exports=!!Object.getOwnPropertySymbols&&!Lv(function(){var a=Symbol("symbol detection");return!Mv(a)||!(Object(a)instanceof Symbol)||!Symbol.sham&&yc&&yc<41})});var In=m((f$,Ic)=>{"use strict";var Cv=Tn();Ic.exports=Cv&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var En=m((m$,Ec)=>{"use strict";var Dv=Ge(),Ov=G(),Bv=_r(),Vv=In(),_v=Object;Ec.exports=Vv?function(a){return typeof a=="symbol"}:function(a){var e=Dv("Symbol");return Ov(e)&&Bv(e.prototype,_v(a))}});var Nr=m((b$,xc)=>{"use strict";var Nv=String;xc.exports=function(a){try{return Nv(a)}catch(e){return"Object"}}});var Ye=m((g$,Pc)=>{"use strict";var Fv=G(),qv=Nr(),Uv=TypeError;Pc.exports=function(a){if(Fv(a))return a;throw new Uv(qv(a)+" is not a function")}});var Fr=m((S$,wc)=>{"use strict";var Hv=Ye(),jv=Xt();wc.exports=function(a,e){var t=a[e];return jv(t)?void 0:Hv(t)}});var kc=m((v$,Ac)=>{"use strict";var xn=ge(),Pn=G(),wn=Ie(),Gv=TypeError;Ac.exports=function(a,e){var t,r;if(e==="string"&&Pn(t=a.toString)&&!wn(r=xn(t,a))||Pn(t=a.valueOf)&&!wn(r=xn(t,a))||e!=="string"&&Pn(t=a.toString)&&!wn(r=xn(t,a)))return r;throw new Gv("Can't convert object to primitive value")}});var Ce=m((y$,Rc)=>{"use strict";Rc.exports=!0});var Mc=m((T$,$c)=>{"use strict";var Lc=Y(),Yv=Object.defineProperty;$c.exports=function(a,e){try{Yv(Lc,a,{value:e,configurable:!0,writable:!0})}catch(t){Lc[a]=e}return e}});var qr=m((I$,Oc)=>{"use strict";var Wv=Ce(),Qv=Y(),zv=Mc(),Cc="__core-js_shared__",Dc=Oc.exports=Qv[Cc]||zv(Cc,{});(Dc.versions||(Dc.versions=[])).push({version:"3.38.0",mode:Wv?"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 An=m((E$,Vc)=>{"use strict";var Bc=qr();Vc.exports=function(a,e){return Bc[a]||(Bc[a]=e||{})}});var Ur=m((x$,_c)=>{"use strict";var Kv=Br(),Jv=Object;_c.exports=function(a){return Jv(Kv(a))}});var De=m((P$,Nc)=>{"use strict";var Xv=oe(),Zv=Ur(),ey=Xv({}.hasOwnProperty);Nc.exports=Object.hasOwn||function(e,t){return ey(Zv(e),t)}});var kn=m((w$,Fc)=>{"use strict";var ty=oe(),ry=0,iy=Math.random(),ay=ty(1 .toString);Fc.exports=function(a){return"Symbol("+(a===void 0?"":a)+")_"+ay(++ry+iy,36)}});var te=m((A$,Uc)=>{"use strict";var sy=Y(),ny=An(),qc=De(),oy=kn(),uy=Tn(),ly=In(),tr=sy.Symbol,Rn=ny("wks"),cy=ly?tr.for||tr:tr&&tr.withoutSetter||oy;Uc.exports=function(a){return qc(Rn,a)||(Rn[a]=uy&&qc(tr,a)?tr[a]:cy("Symbol."+a)),Rn[a]}});var Yc=m((k$,Gc)=>{"use strict";var dy=ge(),Hc=Ie(),jc=En(),py=Fr(),hy=kc(),fy=te(),my=TypeError,by=fy("toPrimitive");Gc.exports=function(a,e){if(!Hc(a)||jc(a))return a;var t=py(a,by),r;if(t){if(e===void 0&&(e="default"),r=dy(t,a,e),!Hc(r)||jc(r))return r;throw new my("Can't convert object to primitive value")}return e===void 0&&(e="number"),hy(a,e)}});var Ln=m((R$,Wc)=>{"use strict";var gy=Yc(),Sy=En();Wc.exports=function(a){var e=gy(a,"string");return Sy(e)?e:e+""}});var wt=m(zc=>{"use strict";var vy=Ee(),yy=mn(),Ty=bn(),ya=qe(),Qc=Ln(),Iy=TypeError,$n=Object.defineProperty,Ey=Object.getOwnPropertyDescriptor,Mn="enumerable",Cn="configurable",Dn="writable";zc.f=vy?Ty?function(e,t,r){if(ya(e),t=Qc(t),ya(r),typeof e=="function"&&t==="prototype"&&"value"in r&&Dn in r&&!r[Dn]){var i=Ey(e,t);i&&i[Dn]&&(e[t]=r.value,r={configurable:Cn in r?r[Cn]:i[Cn],enumerable:Mn in r?r[Mn]:i[Mn],writable:!1})}return $n(e,t,r)}:$n:function(e,t,r){if(ya(e),t=Qc(t),ya(r),yy)try{return $n(e,t,r)}catch(i){}if("get"in r||"set"in r)throw new Iy("Accessors not supported");return"value"in r&&(e[t]=r.value),e}});var Hr=m(($$,Kc)=>{"use strict";Kc.exports=function(a,e){return{enumerable:!(a&1),configurable:!(a&2),writable:!(a&4),value:e}}});var rr=m((M$,Jc)=>{"use strict";var xy=Ee(),Py=wt(),wy=Hr();Jc.exports=xy?function(a,e,t){return Py.f(a,e,wy(1,t))}:function(a,e,t){return a[e]=t,a}});var Ta=m((C$,Zc)=>{"use strict";var Ay=An(),ky=kn(),Xc=Ay("keys");Zc.exports=function(a){return Xc[a]||(Xc[a]=ky(a))}});var Ia=m((D$,ed)=>{"use strict";ed.exports={}});var _n=m((O$,id)=>{"use strict";var Ry=Xl(),rd=Y(),Ly=Ie(),$y=rr(),On=De(),Bn=qr(),My=Ta(),Cy=Ia(),td="Object already initialized",Vn=rd.TypeError,Dy=rd.WeakMap,Ea,jr,xa,Oy=function(a){return xa(a)?jr(a):Ea(a,{})},By=function(a){return function(e){var t;if(!Ly(e)||(t=jr(e)).type!==a)throw new Vn("Incompatible receiver, "+a+" required");return t}};Ry||Bn.state?(Oe=Bn.state||(Bn.state=new Dy),Oe.get=Oe.get,Oe.has=Oe.has,Oe.set=Oe.set,Ea=function(a,e){if(Oe.has(a))throw new Vn(td);return e.facade=a,Oe.set(a,e),e},jr=function(a){return Oe.get(a)||{}},xa=function(a){return Oe.has(a)}):(At=My("state"),Cy[At]=!0,Ea=function(a,e){if(On(a,At))throw new Vn(td);return e.facade=a,$y(a,At,e),e},jr=function(a){return On(a,At)?a[At]:{}},xa=function(a){return On(a,At)});var Oe,At;id.exports={set:Ea,get:jr,has:xa,enforce:Oy,getterFor:By}});var Nn=m((B$,od)=>{"use strict";var Vy=Or(),nd=Function.prototype,ad=nd.apply,sd=nd.call;od.exports=typeof Reflect=="object"&&Reflect.apply||(Vy?sd.bind(ad):function(){return sd.apply(ad,arguments)})});var Fn=m((V$,ud)=>{"use strict";var _y=Jt(),Ny=oe();ud.exports=function(a){if(_y(a)==="Function")return Ny(a)}});var pd=m(dd=>{"use strict";var ld={}.propertyIsEnumerable,cd=Object.getOwnPropertyDescriptor,Fy=cd&&!ld.call({1:2},1);dd.f=Fy?function(e){var t=cd(this,e);return!!t&&t.enumerable}:ld});var md=m(fd=>{"use strict";var qy=Ee(),Uy=ge(),Hy=pd(),jy=Hr(),Gy=Zt(),Yy=Ln(),Wy=De(),Qy=mn(),hd=Object.getOwnPropertyDescriptor;fd.f=qy?hd:function(e,t){if(e=Gy(e),t=Yy(t),Qy)try{return hd(e,t)}catch(r){}if(Wy(e,t))return jy(!Uy(Hy.f,e,t),e[t])}});var qn=m((F$,bd)=>{"use strict";var zy=be(),Ky=G(),Jy=/#|\.prototype\./,Gr=function(a,e){var t=Zy[Xy(a)];return t===tT?!0:t===eT?!1:Ky(e)?zy(e):!!e},Xy=Gr.normalize=function(a){return String(a).replace(Jy,".").toLowerCase()},Zy=Gr.data={},eT=Gr.NATIVE="N",tT=Gr.POLYFILL="P";bd.exports=Gr});var Yr=m((q$,Sd)=>{"use strict";var gd=Fn(),rT=Ye(),iT=Or(),aT=gd(gd.bind);Sd.exports=function(a,e){return rT(a),e===void 0?a:iT?aT(a,e):function(){return a.apply(e,arguments)}}});var xe=m((U$,yd)=>{"use strict";var Wr=Y(),sT=Nn(),nT=Fn(),oT=G(),uT=md().f,lT=qn(),ir=Sa(),cT=Yr(),ar=rr(),vd=De();qr();var dT=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 sT(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?Wr:i?Wr[t]:Wr[t]&&Wr[t].prototype,o=r?ir:ir[t]||ar(ir,t,{})[t],u=o.prototype,l,c,p,d,h,f,b,g,v;for(d in e)l=lT(r?d:t+(i?".":"#")+d,a.forced),c=!l&&n&&vd(n,d),f=o[d],c&&(a.dontCallGetSet?(v=uT(n,d),b=v&&v.value):b=n[d]),h=c&&b?b:e[d],!(!l&&!s&&typeof f==typeof h)&&(a.bind&&c?g=cT(h,Wr):a.wrap&&c?g=dT(h):s&&oT(h)?g=nT(h):g=h,(a.sham||h&&h.sham||f&&f.sham)&&ar(g,"sham",!0),ar(o,d,g),s&&(p=t+"Prototype",vd(ir,p)||ar(ir,p,{}),ar(ir[p],d,h),a.real&&u&&(l||!u[d])&&ar(u,d,h)))}});var Ed=m((H$,Id)=>{"use strict";var Un=Ee(),pT=De(),Td=Function.prototype,hT=Un&&Object.getOwnPropertyDescriptor,Hn=pT(Td,"name"),fT=Hn&&function(){}.name==="something",mT=Hn&&(!Un||Un&&hT(Td,"name").configurable);Id.exports={EXISTS:Hn,PROPER:fT,CONFIGURABLE:mT}});var Pd=m((j$,xd)=>{"use strict";var bT=Math.ceil,gT=Math.floor;xd.exports=Math.trunc||function(e){var t=+e;return(t>0?gT:bT)(t)}});var Pa=m((G$,wd)=>{"use strict";var ST=Pd();wd.exports=function(a){var e=+a;return e!==e||e===0?0:ST(e)}});var kd=m((Y$,Ad)=>{"use strict";var vT=Pa(),yT=Math.max,TT=Math.min;Ad.exports=function(a,e){var t=vT(a);return t<0?yT(t+e,0):TT(t,e)}});var Ld=m((W$,Rd)=>{"use strict";var IT=Pa(),ET=Math.min;Rd.exports=function(a){var e=IT(a);return e>0?ET(e,9007199254740991):0}});var wa=m((Q$,$d)=>{"use strict";var xT=Ld();$d.exports=function(a){return xT(a.length)}});var Dd=m((z$,Cd)=>{"use strict";var PT=Zt(),wT=kd(),AT=wa(),Md=function(a){return function(e,t,r){var i=PT(e),s=AT(i);if(s===0)return!a&&-1;var n=wT(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}};Cd.exports={includes:Md(!0),indexOf:Md(!1)}});var Vd=m((K$,Bd)=>{"use strict";var kT=oe(),jn=De(),RT=Zt(),LT=Dd().indexOf,$T=Ia(),Od=kT([].push);Bd.exports=function(a,e){var t=RT(a),r=0,i=[],s;for(s in t)!jn($T,s)&&jn(t,s)&&Od(i,s);for(;e.length>r;)jn(t,s=e[r++])&&(~LT(i,s)||Od(i,s));return i}});var Gn=m((J$,_d)=>{"use strict";_d.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var Fd=m((X$,Nd)=>{"use strict";var MT=Vd(),CT=Gn();Nd.exports=Object.keys||function(e){return MT(e,CT)}});var Ud=m(qd=>{"use strict";var DT=Ee(),OT=bn(),BT=wt(),VT=qe(),_T=Zt(),NT=Fd();qd.f=DT&&!OT?Object.defineProperties:function(e,t){VT(e);for(var r=_T(t),i=NT(t),s=i.length,n=0,o;s>n;)BT.f(e,o=i[n++],r[o]);return e}});var Yn=m((eM,Hd)=>{"use strict";var FT=Ge();Hd.exports=FT("document","documentElement")});var Kn=m((tM,Kd)=>{"use strict";var qT=qe(),UT=Ud(),jd=Gn(),HT=Ia(),jT=Yn(),GT=ba(),YT=Ta(),Gd=">",Yd="<",Qn="prototype",zn="script",Qd=YT("IE_PROTO"),Wn=function(){},zd=function(a){return Yd+zn+Gd+a+Yd+"/"+zn+Gd},Wd=function(a){a.write(zd("")),a.close();var e=a.parentWindow.Object;return a=null,e},WT=function(){var a=GT("iframe"),e="java"+zn+":",t;return a.style.display="none",jT.appendChild(a),a.src=String(e),t=a.contentWindow.document,t.open(),t.write(zd("document.F=Object")),t.close(),t.F},Aa,ka=function(){try{Aa=new ActiveXObject("htmlfile")}catch(e){}ka=typeof document!="undefined"?document.domain&&Aa?Wd(Aa):WT():Wd(Aa);for(var a=jd.length;a--;)delete ka[Qn][jd[a]];return ka()};HT[Qd]=!0;Kd.exports=Object.create||function(e,t){var r;return e!==null?(Wn[Qn]=qT(e),r=new Wn,Wn[Qn]=null,r[Qd]=e):r=ka(),t===void 0?r:UT.f(r,t)}});var Xd=m((rM,Jd)=>{"use strict";var QT=be();Jd.exports=!QT(function(){function a(){}return a.prototype.constructor=null,Object.getPrototypeOf(new a)!==a.prototype})});var Xn=m((iM,ep)=>{"use strict";var zT=De(),KT=G(),JT=Ur(),XT=Ta(),ZT=Xd(),Zd=XT("IE_PROTO"),Jn=Object,eI=Jn.prototype;ep.exports=ZT?Jn.getPrototypeOf:function(a){var e=JT(a);if(zT(e,Zd))return e[Zd];var t=e.constructor;return KT(t)&&e instanceof t?t.prototype:e instanceof Jn?eI:null}});var sr=m((aM,tp)=>{"use strict";var tI=rr();tp.exports=function(a,e,t,r){return r&&r.enumerable?a[e]=t:tI(a,e,t),a}});var ro=m((sM,ap)=>{"use strict";var rI=be(),iI=G(),aI=Ie(),sI=Kn(),rp=Xn(),nI=sr(),oI=te(),uI=Ce(),to=oI("iterator"),ip=!1,We,Zn,eo;[].keys&&(eo=[].keys(),"next"in eo?(Zn=rp(rp(eo)),Zn!==Object.prototype&&(We=Zn)):ip=!0);var lI=!aI(We)||rI(function(){var a={};return We[to].call(a)!==a});lI?We={}:uI&&(We=sI(We));iI(We[to])||nI(We,to,function(){return this});ap.exports={IteratorPrototype:We,BUGGY_SAFARI_ITERATORS:ip}});var Ra=m((nM,np)=>{"use strict";var cI=te(),dI=cI("toStringTag"),sp={};sp[dI]="z";np.exports=String(sp)==="[object z]"});var Qr=m((oM,op)=>{"use strict";var pI=Ra(),hI=G(),La=Jt(),fI=te(),mI=fI("toStringTag"),bI=Object,gI=La(function(){return arguments}())==="Arguments",SI=function(a,e){try{return a[e]}catch(t){}};op.exports=pI?La:function(a){var e,t,r;return a===void 0?"Undefined":a===null?"Null":typeof(t=SI(e=bI(a),mI))=="string"?t:gI?La(e):(r=La(e))==="Object"&&hI(e.callee)?"Arguments":r}});var lp=m((uM,up)=>{"use strict";var vI=Ra(),yI=Qr();up.exports=vI?{}.toString:function(){return"[object "+yI(this)+"]"}});var zr=m((lM,dp)=>{"use strict";var TI=Ra(),II=wt().f,EI=rr(),xI=De(),PI=lp(),wI=te(),cp=wI("toStringTag");dp.exports=function(a,e,t,r){var i=t?a:a&&a.prototype;i&&(xI(i,cp)||II(i,cp,{configurable:!0,value:e}),r&&!TI&&EI(i,"toString",PI))}});var hp=m((cM,pp)=>{"use strict";var AI=ro().IteratorPrototype,kI=Kn(),RI=Hr(),LI=zr(),$I=Pt(),MI=function(){return this};pp.exports=function(a,e,t,r){var i=e+" Iterator";return a.prototype=kI(AI,{next:RI(+!r,t)}),LI(a,i,!1,!0),$I[i]=MI,a}});var mp=m((dM,fp)=>{"use strict";var CI=oe(),DI=Ye();fp.exports=function(a,e,t){try{return CI(DI(Object.getOwnPropertyDescriptor(a,e)[t]))}catch(r){}}});var gp=m((pM,bp)=>{"use strict";var OI=Ie();bp.exports=function(a){return OI(a)||a===null}});var vp=m((hM,Sp)=>{"use strict";var BI=gp(),VI=String,_I=TypeError;Sp.exports=function(a){if(BI(a))return a;throw new _I("Can't set "+VI(a)+" as a prototype")}});var io=m((fM,yp)=>{"use strict";var NI=mp(),FI=Ie(),qI=Br(),UI=vp();yp.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var a=!1,e={},t;try{t=NI(Object.prototype,"__proto__","set"),t(e,[]),a=e instanceof Array}catch(r){}return function(i,s){return qI(i),UI(s),FI(i)&&(a?t(i,s):i.__proto__=s),i}}():void 0)});var $p=m((mM,Lp)=>{"use strict";var HI=xe(),jI=ge(),$a=Ce(),kp=Ed(),GI=G(),YI=hp(),Tp=Xn(),Ip=io(),WI=zr(),QI=rr(),ao=sr(),zI=te(),Ep=Pt(),Rp=ro(),KI=kp.PROPER,JI=kp.CONFIGURABLE,xp=Rp.IteratorPrototype,Ma=Rp.BUGGY_SAFARI_ITERATORS,Kr=zI("iterator"),Pp="keys",Jr="values",wp="entries",Ap=function(){return this};Lp.exports=function(a,e,t,r,i,s,n){YI(t,e,r);var o=function(v){if(v===i&&d)return d;if(!Ma&&v&&v in c)return c[v];switch(v){case Pp:return function(){return new t(this,v)};case Jr:return function(){return new t(this,v)};case wp:return function(){return new t(this,v)}}return function(){return new t(this)}},u=e+" Iterator",l=!1,c=a.prototype,p=c[Kr]||c["@@iterator"]||i&&c[i],d=!Ma&&p||o(i),h=e==="Array"&&c.entries||p,f,b,g;if(h&&(f=Tp(h.call(new a)),f!==Object.prototype&&f.next&&(!$a&&Tp(f)!==xp&&(Ip?Ip(f,xp):GI(f[Kr])||ao(f,Kr,Ap)),WI(f,u,!0,!0),$a&&(Ep[u]=Ap))),KI&&i===Jr&&p&&p.name!==Jr&&(!$a&&JI?QI(c,"name",Jr):(l=!0,d=function(){return jI(p,this)})),i)if(b={values:o(Jr),keys:s?d:o(Pp),entries:o(wp)},n)for(g in b)(Ma||l||!(g in c))&&ao(c,g,b[g]);else HI({target:e,proto:!0,forced:Ma||l},b);return(!$a||n)&&c[Kr]!==d&&ao(c,Kr,d,{name:i}),Ep[e]=d,b}});var Cp=m((bM,Mp)=>{"use strict";Mp.exports=function(a,e){return{value:a,done:e}}});var no=m((gM,_p)=>{"use strict";var XI=Zt(),so=dn(),Dp=Pt(),Bp=_n(),ZI=wt().f,eE=$p(),Ca=Cp(),tE=Ce(),rE=Ee(),Vp="Array Iterator",iE=Bp.set,aE=Bp.getterFor(Vp);_p.exports=eE(Array,"Array",function(a,e){iE(this,{type:Vp,target:XI(a),index:0,kind:e})},function(){var a=aE(this),e=a.target,t=a.index++;if(!e||t>=e.length)return a.target=void 0,Ca(void 0,!0);switch(a.kind){case"keys":return Ca(t,!1);case"values":return Ca(e[t],!1)}return Ca([t,e[t]],!1)},"values");var Op=Dp.Arguments=Dp.Array;so("keys");so("values");so("entries");if(!tE&&rE&&Op.name!=="values")try{ZI(Op,"name",{value:"values"})}catch(a){}});var Fp=m((SM,Np)=>{"use strict";var sE=te(),nE=Pt(),oE=sE("iterator"),uE=Array.prototype;Np.exports=function(a){return a!==void 0&&(nE.Array===a||uE[oE]===a)}});var oo=m((vM,Up)=>{"use strict";var lE=Qr(),qp=Fr(),cE=Xt(),dE=Pt(),pE=te(),hE=pE("iterator");Up.exports=function(a){if(!cE(a))return qp(a,hE)||qp(a,"@@iterator")||dE[lE(a)]}});var jp=m((yM,Hp)=>{"use strict";var fE=ge(),mE=Ye(),bE=qe(),gE=Nr(),SE=oo(),vE=TypeError;Hp.exports=function(a,e){var t=arguments.length<2?SE(a):e;if(mE(t))return bE(fE(t,a));throw new vE(gE(a)+" is not iterable")}});var Wp=m((TM,Yp)=>{"use strict";var yE=ge(),Gp=qe(),TE=Fr();Yp.exports=function(a,e,t){var r,i;Gp(a);try{if(r=TE(a,"return"),!r){if(e==="throw")throw t;return t}r=yE(r,a)}catch(s){i=!0,r=s}if(e==="throw")throw t;if(i)throw r;return Gp(r),t}});var Oa=m((IM,Jp)=>{"use strict";var IE=Yr(),EE=ge(),xE=qe(),PE=Nr(),wE=Fp(),AE=wa(),Qp=_r(),kE=jp(),RE=oo(),zp=Wp(),LE=TypeError,Da=function(a,e){this.stopped=a,this.result=e},Kp=Da.prototype;Jp.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=IE(e,r),l,c,p,d,h,f,b,g=function(T){return l&&zp(l,"normal",T),new Da(!0,T)},v=function(T){return i?(xE(T),o?u(T[0],T[1],g):u(T[0],T[1])):o?u(T,g):u(T)};if(s)l=a.iterator;else if(n)l=a;else{if(c=RE(a),!c)throw new LE(PE(a)+" is not iterable");if(wE(c)){for(p=0,d=AE(a);d>p;p++)if(h=v(a[p]),h&&Qp(Kp,h))return h;return new Da(!1)}l=kE(a,c)}for(f=s?a.next:l.next;!(b=EE(f,l)).done;){try{h=v(b.value)}catch(T){zp(l,"throw",T)}if(typeof h=="object"&&h&&Qp(Kp,h))return h}return new Da(!1)}});var Zp=m((EM,Xp)=>{"use strict";var $E=Ee(),ME=wt(),CE=Hr();Xp.exports=function(a,e,t){$E?ME.f(a,e,CE(0,t)):a[e]=t}});var eh=m(()=>{"use strict";var DE=xe(),OE=Oa(),BE=Zp();DE({target:"Object",stat:!0},{fromEntries:function(e){var t={};return OE(e,function(r,i){BE(t,r,i)},{AS_ENTRIES:!0}),t}})});var rh=m((wM,th)=>{"use strict";no();eh();var VE=Sa();th.exports=VE.Object.fromEntries});var ah=m((AM,ih)=>{"use strict";ih.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 nh=m(()=>{"use strict";no();var _E=ah(),NE=Y(),FE=zr(),sh=Pt();for(Ba in _E)FE(NE[Ba],Ba),sh[Ba]=sh.Array;var Ba});var uh=m((LM,oh)=>{"use strict";var qE=rh();nh();oh.exports=qE});var uo=m(($M,lh)=>{"use strict";var UE=uh();lh.exports=UE});var ch=m(()=>{"use strict"});var lo=m((DM,dh)=>{"use strict";var Xr=Y(),HE=er(),jE=Jt(),Va=function(a){return HE.slice(0,a.length)===a};dh.exports=function(){return Va("Bun/")?"BUN":Va("Cloudflare-Workers")?"CLOUDFLARE":Va("Deno/")?"DENO":Va("Node.js/")?"NODE":Xr.Bun&&typeof Bun.version=="string"?"BUN":Xr.Deno&&typeof Deno.version=="object"?"DENO":jE(Xr.process)==="process"?"NODE":Xr.window&&Xr.document?"BROWSER":"REST"}()});var _a=m((OM,ph)=>{"use strict";var GE=lo();ph.exports=GE==="NODE"});var fh=m((BM,hh)=>{"use strict";var YE=wt();hh.exports=function(a,e,t){return YE.f(a,e,t)}});var gh=m((VM,bh)=>{"use strict";var WE=Ge(),QE=fh(),zE=te(),KE=Ee(),mh=zE("species");bh.exports=function(a){var e=WE(a);KE&&e&&!e[mh]&&QE(e,mh,{configurable:!0,get:function(){return this}})}});var vh=m((_M,Sh)=>{"use strict";var JE=_r(),XE=TypeError;Sh.exports=function(a,e){if(JE(e,a))return a;throw new XE("Incorrect invocation")}});var po=m((NM,yh)=>{"use strict";var ZE=oe(),ex=G(),co=qr(),tx=ZE(Function.toString);ex(co.inspectSource)||(co.inspectSource=function(a){return tx(a)});yh.exports=co.inspectSource});var wh=m((FM,Ph)=>{"use strict";var rx=oe(),ix=be(),Th=G(),ax=Qr(),sx=Ge(),nx=po(),Ih=function(){},Eh=sx("Reflect","construct"),ho=/^\s*(?:class|function)\b/,ox=rx(ho.exec),ux=!ho.test(Ih),Zr=function(e){if(!Th(e))return!1;try{return Eh(Ih,[],e),!0}catch(t){return!1}},xh=function(e){if(!Th(e))return!1;switch(ax(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return ux||!!ox(ho,nx(e))}catch(t){return!0}};xh.sham=!0;Ph.exports=!Eh||ix(function(){var a;return Zr(Zr.call)||!Zr(Object)||!Zr(function(){a=!0})||a})?xh:Zr});var kh=m((qM,Ah)=>{"use strict";var lx=wh(),cx=Nr(),dx=TypeError;Ah.exports=function(a){if(lx(a))return a;throw new dx(cx(a)+" is not a constructor")}});var fo=m((UM,Lh)=>{"use strict";var Rh=qe(),px=kh(),hx=Xt(),fx=te(),mx=fx("species");Lh.exports=function(a,e){var t=Rh(a).constructor,r;return t===void 0||hx(r=Rh(t)[mx])?e:px(r)}});var Mh=m((HM,$h)=>{"use strict";var bx=oe();$h.exports=bx([].slice)});var Dh=m((jM,Ch)=>{"use strict";var gx=TypeError;Ch.exports=function(a,e){if(a<e)throw new gx("Not enough arguments");return a}});var mo=m((GM,Oh)=>{"use strict";var Sx=er();Oh.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(Sx)});var xo=m((YM,jh)=>{"use strict";var Se=Y(),vx=Nn(),yx=Yr(),Bh=G(),Tx=De(),Hh=be(),Vh=Yn(),Ix=Mh(),_h=ba(),Ex=Dh(),xx=mo(),Px=_a(),To=Se.setImmediate,Io=Se.clearImmediate,wx=Se.process,bo=Se.Dispatch,Ax=Se.Function,Nh=Se.MessageChannel,kx=Se.String,go=0,ei={},Fh="onreadystatechange",ti,kt,So,vo;Hh(function(){ti=Se.location});var Eo=function(a){if(Tx(ei,a)){var e=ei[a];delete ei[a],e()}},yo=function(a){return function(){Eo(a)}},qh=function(a){Eo(a.data)},Uh=function(a){Se.postMessage(kx(a),ti.protocol+"//"+ti.host)};(!To||!Io)&&(To=function(e){Ex(arguments.length,1);var t=Bh(e)?e:Ax(e),r=Ix(arguments,1);return ei[++go]=function(){vx(t,void 0,r)},kt(go),go},Io=function(e){delete ei[e]},Px?kt=function(a){wx.nextTick(yo(a))}:bo&&bo.now?kt=function(a){bo.now(yo(a))}:Nh&&!xx?(So=new Nh,vo=So.port2,So.port1.onmessage=qh,kt=yx(vo.postMessage,vo)):Se.addEventListener&&Bh(Se.postMessage)&&!Se.importScripts&&ti&&ti.protocol!=="file:"&&!Hh(Uh)?(kt=Uh,Se.addEventListener("message",qh,!1)):Fh in _h("script")?kt=function(a){Vh.appendChild(_h("script"))[Fh]=function(){Vh.removeChild(this),Eo(a)}}:kt=function(a){setTimeout(yo(a),0)});jh.exports={set:To,clear:Io}});var Wh=m((WM,Yh)=>{"use strict";var Gh=Y(),Rx=Ee(),Lx=Object.getOwnPropertyDescriptor;Yh.exports=function(a){if(!Rx)return Gh[a];var e=Lx(Gh,a);return e&&e.value}});var Po=m((QM,zh)=>{"use strict";var Qh=function(){this.head=null,this.tail=null};Qh.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}}};zh.exports=Qh});var Jh=m((zM,Kh)=>{"use strict";var $x=er();Kh.exports=/ipad|iphone|ipod/i.test($x)&&typeof Pebble!="undefined"});var Zh=m((KM,Xh)=>{"use strict";var Mx=er();Xh.exports=/web0s(?!.*chrome)/i.test(Mx)});var of=m((JM,nf)=>{"use strict";var or=Y(),Cx=Wh(),ef=Yr(),wo=xo().set,Dx=Po(),Ox=mo(),Bx=Jh(),Vx=Zh(),Ao=_a(),tf=or.MutationObserver||or.WebKitMutationObserver,rf=or.document,af=or.process,Na=or.Promise,Lo=Cx("queueMicrotask"),nr,ko,Ro,Fa,sf;Lo||(ri=new Dx,ii=function(){var a,e;for(Ao&&(a=af.domain)&&a.exit();e=ri.get();)try{e()}catch(t){throw ri.head&&nr(),t}a&&a.enter()},!Ox&&!Ao&&!Vx&&tf&&rf?(ko=!0,Ro=rf.createTextNode(""),new tf(ii).observe(Ro,{characterData:!0}),nr=function(){Ro.data=ko=!ko}):!Bx&&Na&&Na.resolve?(Fa=Na.resolve(void 0),Fa.constructor=Na,sf=ef(Fa.then,Fa),nr=function(){sf(ii)}):Ao?nr=function(){af.nextTick(ii)}:(wo=ef(wo,or),nr=function(){wo(ii)}),Lo=function(a){ri.head||nr(),ri.add(a)});var ri,ii;nf.exports=Lo});var lf=m((XM,uf)=>{"use strict";uf.exports=function(a,e){try{arguments.length===1?console.error(a):console.error(a,e)}catch(t){}}});var qa=m((ZM,cf)=>{"use strict";cf.exports=function(a){try{return{error:!1,value:a()}}catch(e){return{error:!0,value:e}}}});var Rt=m((eC,df)=>{"use strict";var _x=Y();df.exports=_x.Promise});var ur=m((tC,mf)=>{"use strict";var Nx=Y(),ai=Rt(),Fx=G(),qx=qn(),Ux=po(),Hx=te(),pf=lo(),jx=Ce(),$o=yn(),hf=ai&&ai.prototype,Gx=Hx("species"),Mo=!1,ff=Fx(Nx.PromiseRejectionEvent),Yx=qx("Promise",function(){var a=Ux(ai),e=a!==String(ai);if(!e&&$o===66||jx&&!(hf.catch&&hf.finally))return!0;if(!$o||$o<51||!/native code/.test(a)){var t=new ai(function(s){s(1)}),r=function(s){s(function(){},function(){})},i=t.constructor={};if(i[Gx]=r,Mo=t.then(function(){})instanceof r,!Mo)return!0}return!e&&(pf==="BROWSER"||pf==="DENO")&&!ff});mf.exports={CONSTRUCTOR:Yx,REJECTION_EVENT:ff,SUBCLASSING:Mo}});var lr=m((rC,gf)=>{"use strict";var bf=Ye(),Wx=TypeError,Qx=function(a){var e,t;this.promise=new a(function(r,i){if(e!==void 0||t!==void 0)throw new Wx("Bad Promise constructor");e=r,t=i}),this.resolve=bf(e),this.reject=bf(t)};gf.exports.f=function(a){return new Qx(a)}});var Bf=m(()=>{"use strict";var zx=xe(),Kx=Ce(),Ga=_a(),ut=Y(),hr=ge(),Sf=sr(),vf=io(),Jx=zr(),Xx=gh(),Zx=Ye(),ja=G(),eP=Ie(),tP=vh(),rP=fo(),xf=xo().set,Vo=of(),iP=lf(),aP=qa(),sP=Po(),Pf=_n(),Ya=Rt(),_o=ur(),wf=lr(),Wa="Promise",Af=_o.CONSTRUCTOR,nP=_o.REJECTION_EVENT,oP=_o.SUBCLASSING,Co=Pf.getterFor(Wa),uP=Pf.set,cr=Ya&&Ya.prototype,Lt=Ya,Ua=cr,kf=ut.TypeError,Do=ut.document,No=ut.process,Oo=wf.f,lP=Oo,cP=!!(Do&&Do.createEvent&&ut.dispatchEvent),Rf="unhandledrejection",dP="rejectionhandled",yf=0,Lf=1,pP=2,Fo=1,$f=2,Ha,Tf,hP,If,Mf=function(a){var e;return eP(a)&&ja(e=a.then)?e:!1},Cf=function(a,e){var t=e.value,r=e.state===Lf,i=r?a.ok:a.fail,s=a.resolve,n=a.reject,o=a.domain,u,l,c;try{i?(r||(e.rejection===$f&&mP(e),e.rejection=Fo),i===!0?u=t:(o&&o.enter(),u=i(t),o&&(o.exit(),c=!0)),u===a.promise?n(new kf("Promise-chain cycle")):(l=Mf(u))?hr(l,u,s,n):s(u)):n(t)}catch(p){o&&!c&&o.exit(),n(p)}},Df=function(a,e){a.notified||(a.notified=!0,Vo(function(){for(var t=a.reactions,r;r=t.get();)Cf(r,a);a.notified=!1,e&&!a.rejection&&fP(a)}))},Of=function(a,e,t){var r,i;cP?(r=Do.createEvent("Event"),r.promise=e,r.reason=t,r.initEvent(a,!1,!0),ut.dispatchEvent(r)):r={promise:e,reason:t},!nP&&(i=ut["on"+a])?i(r):a===Rf&&iP("Unhandled promise rejection",t)},fP=function(a){hr(xf,ut,function(){var e=a.facade,t=a.value,r=Ef(a),i;if(r&&(i=aP(function(){Ga?No.emit("unhandledRejection",t,e):Of(Rf,e,t)}),a.rejection=Ga||Ef(a)?$f:Fo,i.error))throw i.value})},Ef=function(a){return a.rejection!==Fo&&!a.parent},mP=function(a){hr(xf,ut,function(){var e=a.facade;Ga?No.emit("rejectionHandled",e):Of(dP,e,a.value)})},dr=function(a,e,t){return function(r){a(e,r,t)}},pr=function(a,e,t){a.done||(a.done=!0,t&&(a=t),a.value=e,a.state=pP,Df(a,!0))},Bo=function(a,e,t){if(!a.done){a.done=!0,t&&(a=t);try{if(a.facade===e)throw new kf("Promise can't be resolved itself");var r=Mf(e);r?Vo(function(){var i={done:!1};try{hr(r,e,dr(Bo,i,a),dr(pr,i,a))}catch(s){pr(i,s,a)}}):(a.value=e,a.state=Lf,Df(a,!1))}catch(i){pr({done:!1},i,a)}}};if(Af&&(Lt=function(e){tP(this,Ua),Zx(e),hr(Ha,this);var t=Co(this);try{e(dr(Bo,t),dr(pr,t))}catch(r){pr(t,r)}},Ua=Lt.prototype,Ha=function(e){uP(this,{type:Wa,done:!1,notified:!1,parent:!1,reactions:new sP,rejection:!1,state:yf,value:void 0})},Ha.prototype=Sf(Ua,"then",function(e,t){var r=Co(this),i=Oo(rP(this,Lt));return r.parent=!0,i.ok=ja(e)?e:!0,i.fail=ja(t)&&t,i.domain=Ga?No.domain:void 0,r.state===yf?r.reactions.add(i):Vo(function(){Cf(i,r)}),i.promise}),Tf=function(){var a=new Ha,e=Co(a);this.promise=a,this.resolve=dr(Bo,e),this.reject=dr(pr,e)},wf.f=Oo=function(a){return a===Lt||a===hP?new Tf(a):lP(a)},!Kx&&ja(Ya)&&cr!==Object.prototype)){If=cr.then,oP||Sf(cr,"then",function(e,t){var r=this;return new Lt(function(i,s){hr(If,r,i,s)}).then(e,t)},{unsafe:!0});try{delete cr.constructor}catch(a){}vf&&vf(cr,Ua)}zx({global:!0,constructor:!0,wrap:!0,forced:Af},{Promise:Lt});Jx(Lt,Wa,!1,!0);Xx(Wa)});var qf=m((sC,Ff)=>{"use strict";var bP=te(),_f=bP("iterator"),Nf=!1;try{Vf=0,qo={next:function(){return{done:!!Vf++}},return:function(){Nf=!0}},qo[_f]=function(){return this},Array.from(qo,function(){throw 2})}catch(a){}var Vf,qo;Ff.exports=function(a,e){try{if(!e&&!Nf)return!1}catch(i){return!1}var t=!1;try{var r={};r[_f]=function(){return{next:function(){return{done:t=!0}}}},a(r)}catch(i){}return t}});var Uo=m((nC,Uf)=>{"use strict";var gP=Rt(),SP=qf(),vP=ur().CONSTRUCTOR;Uf.exports=vP||!SP(function(a){gP.all(a).then(void 0,function(){})})});var Hf=m(()=>{"use strict";var yP=xe(),TP=ge(),IP=Ye(),EP=lr(),xP=qa(),PP=Oa(),wP=Uo();yP({target:"Promise",stat:!0,forced:wP},{all:function(e){var t=this,r=EP.f(t),i=r.resolve,s=r.reject,n=xP(function(){var o=IP(t.resolve),u=[],l=0,c=1;PP(e,function(p){var d=l++,h=!1;c++,TP(o,t,p).then(function(f){h||(h=!0,u[d]=f,--c||i(u))},s)}),--c||i(u)});return n.error&&s(n.value),r.promise}})});var Gf=m(()=>{"use strict";var AP=xe(),kP=Ce(),RP=ur().CONSTRUCTOR,jo=Rt(),LP=Ge(),$P=G(),MP=sr(),jf=jo&&jo.prototype;AP({target:"Promise",proto:!0,forced:RP,real:!0},{catch:function(a){return this.then(void 0,a)}});!kP&&$P(jo)&&(Ho=LP("Promise").prototype.catch,jf.catch!==Ho&&MP(jf,"catch",Ho,{unsafe:!0}));var Ho});var Yf=m(()=>{"use strict";var CP=xe(),DP=ge(),OP=Ye(),BP=lr(),VP=qa(),_P=Oa(),NP=Uo();CP({target:"Promise",stat:!0,forced:NP},{race:function(e){var t=this,r=BP.f(t),i=r.reject,s=VP(function(){var n=OP(t.resolve);_P(e,function(o){DP(n,t,o).then(r.resolve,i)})});return s.error&&i(s.value),r.promise}})});var Wf=m(()=>{"use strict";var FP=xe(),qP=lr(),UP=ur().CONSTRUCTOR;FP({target:"Promise",stat:!0,forced:UP},{reject:function(e){var t=qP.f(this),r=t.reject;return r(e),t.promise}})});var Go=m((mC,Qf)=>{"use strict";var HP=qe(),jP=Ie(),GP=lr();Qf.exports=function(a,e){if(HP(a),jP(e)&&e.constructor===a)return e;var t=GP.f(a),r=t.resolve;return r(e),t.promise}});var Jf=m(()=>{"use strict";var YP=xe(),WP=Ge(),zf=Ce(),QP=Rt(),Kf=ur().CONSTRUCTOR,zP=Go(),KP=WP("Promise"),JP=zf&&!Kf;YP({target:"Promise",stat:!0,forced:zf||Kf},{resolve:function(e){return zP(JP&&this===KP?QP:this,e)}})});var Xf=m(()=>{"use strict";Bf();Hf();Gf();Yf();Wf();Jf()});var rm=m(()=>{"use strict";var XP=xe(),ZP=Ce(),Qa=Rt(),ew=be(),em=Ge(),tm=G(),tw=fo(),Zf=Go(),rw=sr(),Wo=Qa&&Qa.prototype,iw=!!Qa&&ew(function(){Wo.finally.call({then:function(){}},function(){})});XP({target:"Promise",proto:!0,real:!0,forced:iw},{finally:function(a){var e=tw(this,em("Promise")),t=tm(a);return this.then(t?function(r){return Zf(e,a()).then(function(){return r})}:a,t?function(r){return Zf(e,a()).then(function(){throw r})}:a)}});!ZP&&tm(Qa)&&(Yo=em("Promise").prototype.finally,Wo.finally!==Yo&&rw(Wo,"finally",Yo,{unsafe:!0}));var Yo});var za=m((IC,im)=>{"use strict";var aw=Ge();im.exports=aw});var sm=m((EC,am)=>{"use strict";ch();Xf();rm();var sw=za();am.exports=sw("Promise","finally")});var om=m((xC,nm)=>{"use strict";var nw=sm();nm.exports=nw});var Ka=m((PC,um)=>{"use strict";var ow=om();um.exports=ow});var Cm=m(()=>{"use strict";var Bw=xe(),Vw=Ur(),_w=wa(),Nw=Pa(),Fw=dn();Bw({target:"Array",proto:!0},{at:function(e){var t=Vw(this),r=_w(t),i=Nw(e),s=i>=0?i:r+i;return s<0||s>=r?void 0:t[s]}});Fw("at")});var Om=m((DD,Dm)=>{"use strict";Cm();var qw=za();Dm.exports=qw("Array","at")});var Vm=m((OD,Bm)=>{"use strict";var Uw=Om();Bm.exports=Uw});var ui=m((BD,_m)=>{"use strict";var Hw=Vm();_m.exports=Hw});var Bb=m(()=>{"use strict"});var Vb=m(()=>{"use strict"});var Nb=m((BV,_b)=>{"use strict";var ZA=Ie(),ek=Jt(),tk=te(),rk=tk("match");_b.exports=function(a){var e;return ZA(a)&&((e=a[rk])!==void 0?!!e:ek(a)==="RegExp")}});var qb=m((VV,Fb)=>{"use strict";var ik=Qr(),ak=String;Fb.exports=function(a){if(ik(a)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return ak(a)}});var Hb=m((_V,Ub)=>{"use strict";var sk=qe();Ub.exports=function(){var a=sk(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 Yb=m((NV,Gb)=>{"use strict";var nk=ge(),ok=De(),uk=_r(),lk=Hb(),jb=RegExp.prototype;Gb.exports=function(a){var e=a.flags;return e===void 0&&!("flags"in jb)&&!ok(a,"flags")&&uk(jb,a)?nk(lk,a):e}});var Qb=m((FV,Wb)=>{"use strict";var Eu=oe(),ck=Ur(),dk=Math.floor,Tu=Eu("".charAt),pk=Eu("".replace),Iu=Eu("".slice),hk=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,fk=/\$([$&'`]|\d{1,2})/g;Wb.exports=function(a,e,t,r,i,s){var n=t+a.length,o=r.length,u=fk;return i!==void 0&&(i=ck(i),u=hk),pk(s,u,function(l,c){var p;switch(Tu(c,0)){case"$":return"$";case"&":return a;case"`":return Iu(e,0,t);case"'":return Iu(e,n);case"<":p=i[Iu(c,1,-1)];break;default:var d=+c;if(d===0)return l;if(d>o){var h=dk(d/10);return h===0?l:h<=o?r[h-1]===void 0?Tu(c,1):r[h-1]+Tu(c,1):l}p=r[d-1]}return p===void 0?"":p})}});var Jb=m(()=>{"use strict";var mk=xe(),bk=ge(),Pu=oe(),zb=Br(),gk=G(),Sk=Xt(),vk=Nb(),Er=qb(),yk=Fr(),Tk=Yb(),Ik=Qb(),Ek=te(),xk=Ce(),Pk=Ek("replace"),wk=TypeError,xu=Pu("".indexOf),Ak=Pu("".replace),Kb=Pu("".slice),kk=Math.max;mk({target:"String",proto:!0},{replaceAll:function(e,t){var r=zb(this),i,s,n,o,u,l,c,p,d,h,f=0,b="";if(!Sk(e)){if(i=vk(e),i&&(s=Er(zb(Tk(e))),!~xu(s,"g")))throw new wk("`.replaceAll` does not allow non-global regexes");if(n=yk(e,Pk),n)return bk(n,e,r,t);if(xk&&i)return Ak(Er(r),e,t)}for(o=Er(r),u=Er(e),l=gk(t),l||(t=Er(t)),c=u.length,p=kk(1,c),d=xu(o,u);d!==-1;)h=l?Er(t(u,d,o)):Ik(u,o,d,[],void 0,t),b+=Kb(o,f,d)+h,f=d+c,d=d+p>o.length?-1:xu(o,u,d+p);return f<o.length&&(b+=Kb(o,f)),b}})});var Zb=m((HV,Xb)=>{"use strict";Bb();Vb();Jb();var Rk=za();Xb.exports=Rk("String","replaceAll")});var tg=m((jV,eg)=>{"use strict";var Lk=Zb();eg.exports=Lk});var ig=m((GV,rg)=>{"use strict";var $k=tg();rg.exports=$k});var Al="2.0.108-dev.9b636631.0";var ne=(i=>(i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused",i))(ne||{}),ot=(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))(ot||{});var ha=(i=>(i.NOT_AVAILABLE="NOT_AVAILABLE",i.AVAILABLE="AVAILABLE",i.CONNECTING="CONNECTING",i.CONNECTED="CONNECTED",i))(ha||{}),sn=(r=>(r.HTTP1="http1",r.HTTP2="http2",r.QUIC="quic",r))(sn||{});var nn=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(nn||{});import{assertNever as Cl,assertNonNullable as WS,isNonNullable as fa,ValueSubject as on,Subject as QS,Subscription as zS,merge as KS,observableFrom as JS,fromEvent as Rl,map as Ll,tap as $l,filterChanged as XS,isNullable as un,ErrorCategory as Ml}from"@vkontakte/videoplayer-shared";var kl=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 ma=class{constructor(e){this.connection$=new on(void 0);this.castState$=new on("NOT_AVAILABLE");this.errorEvent$=new QS;this.realCastState$=new on("NOT_AVAILABLE");this.subscription=new zS;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=fa((s=window.chrome)==null?void 0:s.cast),i=!!window.__onGCastApiAvailable;r?this.initializeCastApi():(window.__onGCastApiAvailable=n=>{delete window.__onGCastApiAvailable,n&&this.initializeCastApi()},i||kl("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:Ml.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(){fa(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();un(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();un(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(Rl(r,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(i=>{var s,n;switch(i.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=(n=(s=r.getCurrentSession())==null?void 0:s.getMediaSession())==null?void 0:n.media.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return Cl(i.sessionState)}})).add(KS(Rl(r,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe($l(i=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(i)}`})}),Ll(i=>i.castState)),JS([r.getCastState()])).pipe(XS(),Ll(ZS),$l(i=>{this.log({message:`realCastState$: ${i}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(i=>{var o;let s=i==="CONNECTED",n=fa(this.connection$.getValue());if(s&&!n){let u=r.getCurrentSession();WS(u);let l=u.getCastDevice(),c=(o=u.getMediaSession())==null?void 0:o.media.contentId;(un(c)||c===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:u,castDevice:l}))}else!s&&n&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(i==="CONNECTED"?fa(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:Ml.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:s})}}},ZS=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 Cl(a)}};var rS=Fe(uo(),1);var Sm=Fe(Ka(),1);import{assertNever as lm}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:lm(t)}return a},Qo=(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:lm(e)}};var E=(a,e,t=!1)=>{let r=a.getTransition();(t||!r||r.to===e)&&a.setState(e)};import{isNonNullable as uw,Subject as Ja,merge as cm}from"@vkontakte/videoplayer-shared";var $=class{constructor(e){this.transitionStarted$=new Ja;this.transitionEnded$=new Ja;this.transitionUpdated$=new Ja;this.forceChanged$=new Ja;this.stateChangeStarted$=cm(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=cm(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||uw(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 lw}from"@vkontakte/videoplayer-shared";var dm=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 lw(a)}};import{assertNever as fr,assertNonNullable as $t,debounce as pm,ErrorCategory as hm,fromEvent as Mt,isNonNullable as fm,map as mm,merge as bm,observableFrom as cw,Subject as dw,Subscription as zo,timeout as pw,getHighestQuality as hw}from"@vkontakte/videoplayer-shared";var fw=5,mw=5,bw=500,gm=7e3,si=class{constructor(e){this.subscription=new zo;this.loadMediaTimeoutSubscription=new zo;this.videoState=new $("stopped");this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),r=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${r}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(s)};`}),r==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.stop());return}if(!t){if((i==null?void 0:i.to)!=="paused"&&s.state==="requested"&&e!=="stopped"){this.seek(s.position/1e3);return}switch(r){case"ready":{switch(e){case"playing":case"paused":case"ready":break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:fr(e)}break}case"playing":{switch(e){case"playing":break;case"paused":this.videoState.startTransitionTo("playing"),this.params.connection.remotePlayerController.playOrPause();break;case"ready":this.videoState.startTransitionTo("playing"),this.params.connection.remotePlayerController.playOrPause();break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:fr(e)}break}case"paused":{switch(e){case"playing":this.videoState.startTransitionTo("paused"),this.params.connection.remotePlayerController.playOrPause();break;case"paused":break;case"ready":this.videoState.startTransitionTo("paused"),this.videoState.setState("paused");break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:fr(e)}break}default:fr(r)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(dm(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 zo;this.subscription.add(e),this.subscription.add(bm(this.videoState.stateChangeStarted$.pipe(mm(i=>`stateChangeStarted$ ${JSON.stringify(i)}`)),this.videoState.stateChangeEnded$.pipe(mm(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 dw;e.add(i.pipe(pm(bw)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add(Mt(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)>fw)&&i.next(o),s=o})),e.add(Mt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(Mt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),i=>{this.logRemoteEvent(i),i.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(Mt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),i=>{this.logRemoteEvent(i),i.value?this.handleRemotePause():this.handleRemotePlay()}),t(Mt(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<mw&&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:fr(n)}}),t(Mt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),i=>{this.logRemoteEvent(i),this.handleRemoteVolumeChange({volume:i.value})}),t(Mt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),i=>{this.logRemoteEvent(i),this.handleRemoteVolumeChange({muted:i.value})});let r=bm(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,cw(["init"])).pipe(pm(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];$t(c);let p=hw(Object.keys(c));$t(p);let d=c[p];$t(d),r=d,i="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let c=t[e];$t(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];$t(c),r=c.url,i="application/dash+xml",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let c=t[e];$t(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];$t(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",p=new Error(c);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:hm.VIDEO_PIPELINE,message:c,thrown:p}),p}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return fr(e)}let n=new chrome.cast.media.MediaInfo((l=this.params.meta.videoId)!=null?l:r,i);n.contentUrl=r,n.streamType=s,n.metadata=new chrome.cast.media.GenericMediaMetadata;let{title:o,subtitle:u}=this.params.meta;return fm(o)&&(n.metadata.title=o),fm(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(pw(gm).subscribe(()=>s(`timeout(${gm})`)))});(0,Sm.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:hm.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 gw}from"@vkontakte/videoplayer-shared";var vm=a=>{try{a.pause(),a.playbackRate=0,gw(a),a.remove()}catch(e){console.error(e)}};import{fromEvent as Sw,Subscription as vw}from"@vkontakte/videoplayer-shared";var Ko=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)}},Jo=window.WeakMap?new WeakMap:new Ko,Xo=window.WeakMap?new WeakMap:new Map,yw=(a,e=20)=>{let t=0;return Sw(a,"ratechange").subscribe(r=>{t++,t>=e&&(a.currentTime=a.currentTime,t=0)})},ue=(a,{audioVideoSyncRate:e})=>{let t=a.querySelector("video"),r=!!t;t?ym(t):(t=document.createElement("video"),a.appendChild(t)),Jo.set(t,r);let i=new vw;return i.add(yw(t,e)),Xo.set(t,i),t.setAttribute("crossorigin","anonymous"),t.setAttribute("playsinline","playsinline"),t.controls=!1,t.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),t},le=a=>{let e=Xo.get(a);e==null||e.unsubscribe(),Xo.delete(a);let t=Jo.get(a);Jo.delete(a),t?ym(a):vm(a)};import{assertNonNullable as ni,isNonNullable as He,isNullable as Ew,fromEvent as mr,merge as Tm,observableFrom as Im,filterChanged as Em,map as oi,Subject as xm,Subscription as xw,ValueSubject as Pw,ErrorCategory as ww}from"@vkontakte/videoplayer-shared";import{isNonNullable as Zo,isNullable as Tw,Subscription as Iw}from"@vkontakte/videoplayer-shared";var Xa=(a,e,t,{equal:r=(n,o)=>n===o,changed$:i,onError:s}={})=>{let n=a.getState(),o=e(),u=Tw(i),l=new Iw;return i&&l.add(i.subscribe(c=>{let p=a.getState();r(c,p)&&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},Ue=(a,e,t)=>Xa(e,()=>a.loop,r=>{Zo(r)&&(a.loop=r)},{onError:t}),ce=(a,e,t,r)=>Xa(e,()=>({muted:a.muted,volume:a.volume}),i=>{Zo(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}),Pe=(a,e,t,r)=>Xa(e,()=>a.playbackRate,i=>{Zo(i)&&(a.playbackRate=i)},{changed$:t,onError:r}),lt=Xa;var Aw=a=>["__",a.language,a.label].join("|"),kw=(a,e)=>{if(a.id===e)return!0;let[t,r,i]=e.split("|");return a.language===r&&a.label===i},eu=class a{constructor(){this.available$=new xm;this.current$=new Pw(void 0);this.error$=new xm;this.subscription=new xw;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:ww.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(lt(t.internalTextTracks,()=>Object.values(this.internalTracks),s=>{He(s)&&this.setInternal(s)},{equal:(s,n)=>He(s)&&He(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(oi(s=>s.filter(({type:n})=>n==="internal"))),onError:i})),this.subscription.add(lt(t.externalTextTracks,()=>Object.values(this.externalTracks),s=>{He(s)&&this.setExternal(s)},{equal:(s,n)=>He(s)&&He(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(oi(s=>s.filter(({type:n})=>n==="external"))),onError:i})),this.subscription.add(lt(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(lt(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.activeCues)}))}subscribe(){ni(this.video);let{textTracks:e}=this.video;this.subscription.add(mr(e,"addtrack").subscribe(()=>{let r=this.current$.getValue();r&&this.select(r)})),this.subscription.add(Tm(mr(e,"addtrack"),mr(e,"removetrack"),Im(["init"])).pipe(oi(()=>this.htmlTextTracksAsArray().map(r=>this.htmlTextTrackToITextTrack(r))),Em((r,i)=>r.length===i.length&&r.every(({id:s},n)=>s===i[n].id))).subscribe(this.available$)),this.subscription.add(Tm(mr(e,"change"),Im(["init"])).pipe(oi(()=>this.htmlTextTracksAsArray().find(({mode:r})=>r==="showing")),oi(r=>r&&this.htmlTextTrackToITextTrack(r).id),Em()).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(mr(e,"addtrack").subscribe(r=>{var s,n;(s=r.track)==null||s.addEventListener("cuechange",t);let i=o=>{var l,c,p,d,h;let u=(c=(l=o.target)==null?void 0:l.cues)!=null?c:null;u&&u.length&&(this.applyCueSettings((d=(p=o.target)==null?void 0:p.cues)!=null?d:null),(h=o.target)==null||h.removeEventListener("cuechange",i))};(n=r.track)==null||n.addEventListener("cuechange",i)})),this.subscription.add(mr(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;He(t.align)&&(i.align=t.align),He(t.position)&&(i.position=t.position),He(t.size)&&(i.size=t.size),He(t.line)&&(i.line=t.line)}}htmlTextTracksAsArray(e=!1){ni(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:Aw(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){ni(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(Ew(e)||!kw(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){ni(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){ni(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)}},we=eu;var ze=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 Pm=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},tu=a=>{let e=Pm(a);return!!(e&&e.fullscreenElement&&e.fullscreenElement===a)},wm=a=>{let e=Pm(a);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===a)};import{fromEvent as Ae,map as ct,merge as km,filterChanged as Lw,isNonNullable as Rm,Subject as $w,filter as Lm,mapTo as $m,combine as Mw,once as Cw,ErrorCategory as Dw,ValueSubject as Mm,clientChecker as Ow}from"@vkontakte/videoplayer-shared";var Rw=3,Am=(a,e,t=Rw)=>{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 de=a=>{let e=S=>Ae(a,S).pipe($m(void 0)),r=km(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(S=>Ae(a,S))).pipe(ct(S=>S.type==="ended"?a.readyState<2:a.readyState<3),Lw()),i=km(Ae(a,"progress"),Ae(a,"timeupdate")).pipe(ct(()=>Am(a.buffered,a.currentTime))),s=Ow.isSafari?Mw({play:e("play").pipe(Cw()),playing:e("playing")}).pipe($m(void 0)):e("playing"),n=Ae(a,"volumechange").pipe(ct(()=>({muted:a.muted,volume:a.volume}))),o=Ae(a,"ratechange").pipe(ct(()=>a.playbackRate)),u=Ae(a,"error").pipe(Lm(()=>!!(a.error||a.played.length)),ct(()=>{var y;let S=a.error;return{id:S?`MediaError#${S.code}`:"HtmlVideoError",category:Dw.VIDEO_PIPELINE,message:S?S.message:"Error event from HTML video element",thrown:(y=a.error)!=null?y:void 0}})),l=Ae(a,"timeupdate").pipe(ct(()=>a.currentTime)),c=new $w,p=.3,d;l.subscribe(S=>{a.loop&&Rm(d)&&Rm(S)&&d>=a.duration-p&&S<=p&&c.next(d),d=S});let h=e("pause").pipe(Lm(()=>!a.error&&d!==a.duration)),f=Ae(a,"enterpictureinpicture"),b=Ae(a,"leavepictureinpicture"),g=new Mm(wm(a));f.subscribe(()=>g.next(!0)),b.subscribe(()=>g.next(!1));let v=new Mm(tu(a));return Ae(a,"fullscreenchange").pipe(ct(()=>tu(a))).subscribe(v),{playing$:s,pause$:h,canplay$:e("canplay"),ended$:e("ended"),looped$:c,error$:u,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:l,durationChange$:Ae(a,"durationchange").pipe(ct(()=>a.duration)),isBuffering$:r,currentBuffer$:i,volumeState$:n,playbackRateState$:o,inPiP$:g,inFullscreen$:v}};import{VideoQuality as dt}from"@vkontakte/videoplayer-shared";var pt=a=>{switch(a){case"mobile":return dt.Q_144P;case"lowest":return dt.Q_240P;case"low":return dt.Q_360P;case"sd":case"medium":return dt.Q_480P;case"hd":case"high":return dt.Q_720P;case"fullhd":case"full":return dt.Q_1080P;case"quadhd":case"quad":return dt.Q_1440P;case"ultrahd":case"ultra":return dt.Q_2160P}};var nu=Fe(ui(),1);import{isNonNullable as ht,isNullable as iu,now as jm,isHigher as au,isHigherOrEqual as Um,isInvariantQuality as Hm,isLower as su,isLowerOrEqual as jw,videoSizeToQuality as Gw,assertNotEmptyArray as Yw}from"@vkontakte/videoplayer-shared";var ru=!1,Ke={},Nm=a=>{ru=a},Fm=()=>{Ke={}},qm=a=>{a(Ke)},li=(a,e)=>{var t;ru&&(Ke.meta=(t=Ke.meta)!=null?t:{},Ke.meta[a]=e)},re=class{constructor(e){this.name=e}next(e){var r,i;if(!ru)return;Ke.series=(r=Ke.series)!=null?r:{};let t=(i=Ke.series[this.name])!=null?i:[];t.push([Date.now(),e]),Ke.series[this.name]=t}};var Ww=new re("best_bitrate"),Qw=(a,e,t)=>(e-t)*Math.pow(2,-10*a)+t,Za=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=jm()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},zw='Assertion "ABR Tracks is empty array" failed',Kw=(a,{container:e,throughput:t,tuning:r,limits:i,reserve:s=0,forwardBufferHealth:n,playbackRate:o,current:u,history:l,droppedVideoMaxQualityLimit:c,abrLogger:p})=>{var R,L,w,q,K;Yw(a,zw);let d=r.usePixelRatio&&(R=window.devicePixelRatio)!=null?R:1,h=r.limitByContainer&&e&&e.width>0&&e.height>0&&{width:e.width*d*r.containerSizeFactor,height:e.height*d*r.containerSizeFactor},f=h&&Gw(h),b=r.considerPlaybackRate&&ht(o)?o:1,g=a.filter(k=>!Hm(k.quality)).sort((k,x)=>au(k.quality,x.quality)?-1:1),v=(L=(0,nu.default)(g,-1))==null?void 0:L.quality,T=(w=(0,nu.default)(g,0))==null?void 0:w.quality,S=iu(i)||ht(i.min)&&ht(i.max)&&su(i.max,i.min)||ht(i.min)&&T&&au(i.min,T)||ht(i.max)&&v&&su(i.max,v),y=b*Qw(n!=null?n:.5,r.bitrateFactorAtEmptyBuffer,r.bitrateFactorAtFullBuffer),I={},C=g.filter(k=>(f?su(k.quality,f):!0)?(ht(t)&&isFinite(t)&&ht(k.bitrate)?t-s>=k.bitrate*y:!0)?r.lazyQualitySwitch&&ht(r.minBufferToSwitchUp)&&u&&!Hm(u.quality)&&(n!=null?n:0)<r.minBufferToSwitchUp&&au(k.quality,u.quality)?(I[k.quality]="Buffer",!1):!!c&&Um(k.quality,c)?(I[k.quality]="DroppedFramesLimit",!1):S||(iu(i.max)||jw(k.quality,i.max))&&(iu(i.min)||Um(k.quality,i.min))?!0:(I[k.quality]="FitsQualityLimits",!1):(I[k.quality]="FitsThroughput",!1):(I[k.quality]="FitsContainer",!1))[0];C&&C.bitrate&&Ww.next(C.bitrate);let A=(q=C!=null?C:g[Math.ceil((g.length-1)/2)])!=null?q:a[0];A.quality!==((K=l==null?void 0:l.last)==null?void 0:K.quality)&&p({message:`
|
|
7
|
+
[available tracks]
|
|
11
8
|
${a.map(k=>`{ id: ${k.id}, quality: ${k.quality}, bitrate: ${k.bitrate} }`).join(`
|
|
12
9
|
`)}
|
|
13
10
|
|
|
14
11
|
[tuning]
|
|
15
|
-
${Object.entries(r!=null?r:{}).map(([k,
|
|
12
|
+
${Object.entries(r!=null?r:{}).map(([k,x])=>`${k}: ${x}`).join(`
|
|
16
13
|
`)}
|
|
17
14
|
|
|
18
15
|
[limit params]
|
|
@@ -22,40 +19,22 @@ var zS=Object.create;var kl=Object.defineProperty;var KS=Object.getOwnPropertyDe
|
|
|
22
19
|
playbackRate: ${o},
|
|
23
20
|
playbackRateFactor: ${b},
|
|
24
21
|
forwardBufferHealth: ${n},
|
|
25
|
-
bitrateFactor: ${
|
|
22
|
+
bitrateFactor: ${y},
|
|
26
23
|
minBufferToSwitchUp: ${r.minBufferToSwitchUp},
|
|
27
24
|
droppedVideoMaxQualityLimit: ${c},
|
|
28
25
|
limitsAreInvalid: ${S},
|
|
29
26
|
maxQualityLimit: ${i==null?void 0:i.max},
|
|
30
27
|
minQualityLimit: ${i==null?void 0:i.min},
|
|
31
28
|
|
|
32
|
-
[limited
|
|
33
|
-
${Object.entries(I).map(([k,
|
|
29
|
+
[limited tracks]
|
|
30
|
+
${Object.entries(I).map(([k,x])=>`${k}: ${x}`).join(`
|
|
34
31
|
`)||"All tracks are available"}
|
|
35
32
|
|
|
36
|
-
[best
|
|
37
|
-
[selected
|
|
38
|
-
`})
|
|
39
|
-
[
|
|
40
|
-
[available audio tracks]
|
|
41
|
-
${e.map(b=>`{ id: ${b.id}, quality: ${b.quality}, bitrate: ${b.bitrate} }`).join(`
|
|
42
|
-
`)}
|
|
43
|
-
|
|
44
|
-
[tuning]
|
|
45
|
-
${Object.entries(i!=null?i:{}).map(([b,g])=>`${b}: ${g}`).join(`
|
|
46
|
-
`)}
|
|
47
|
-
|
|
48
|
-
[limit params]
|
|
49
|
-
throughput: ${r},
|
|
50
|
-
reserve: ${p},
|
|
51
|
-
playbackRate: ${s},
|
|
52
|
-
playbackRateFactor: ${l},
|
|
53
|
-
forwardBufferHealth: ${n},
|
|
54
|
-
bitrateFactor: ${d},
|
|
55
|
-
minBufferToSwitchUp: ${i.minBufferToSwitchUp},
|
|
56
|
-
|
|
57
|
-
[selected audio track] ${h==null?void 0:h.bitrate}
|
|
58
|
-
`}),h&&Jm(i,u,h,o)};var Z=a=>new URL(a).hostname;import{assertNever as ab,assertNonNullable as sb,combine as Tw,debounce as Iw,ErrorCategory as nb,filter as ob,filterChanged as Ew,isNonNullable as hu,map as ns,merge as ub,observableFrom as xw,once as Pw,Subscription as Aw,ValueSubject as fu,videoQualityToHeight as ww,videoSizeToQuality as kw}from"@vkontakte/videoplayer-shared";var Zm=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"))},he=async a=>{let e=a.muted;try{await a.play()}catch(t){if(!Zm(t))return!1;if(e)return console.warn(t),!1;a.muted=!0;try{await a.play()}catch(r){return Zm(r)&&(a.muted=!1,console.warn(r)),!1}}return!0};import{isNonNullable as is,isNullable as aw,assertNonNullable as fi}from"@vkontakte/videoplayer-shared";import{isNonNullable as eb,assertNonNullable as rs,now as rw}from"@vkontakte/videoplayer-shared";function ee(){return rw()}function lu(a){return ee()-a}function cu(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 tb(a,e,t){let r=(...i)=>{t.apply(null,i),a.removeEventListener(e,r)};a.addEventListener(e,r)}function gr(a,e,t,r){let i=window.XMLHttpRequest,s,n,o,u=!1,l=0,c,p,d=!1,h="arraybuffer",f=7e3,b=2e3,g=()=>{if(u)return;rs(c);let A=lu(c),q;if(A<b){q=b-A,setTimeout(g,q);return}b*=2,b>f&&(b=f),n&&n.abort(),n=new i,O()},y=A=>(s=A,L),T=A=>(p=A,L),S=()=>(h="json",L),v=()=>{if(!u){if(--l>=0){g(),r&&r();return}u=!0,p&&p(),t&&t()}},I=A=>(d=A,L),O=()=>{c=ee(),n=new i,n.open("get",a);let A=0,q,k=0,Q=()=>(rs(c),Math.max(c,Math.max(q||0,k||0)));if(s&&n.addEventListener("progress",P=>{let _=ee();s.updateChunk&&P.loaded>A&&(s.updateChunk(Q(),P.loaded-A),A=P.loaded,q=_)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>v())),n.addEventListener("load",()=>{if(u)return;rs(n);let P=n.status;if(P>=200&&P<300){if(n.response.byteLength&&s){let _=n.response.byteLength-A;_&&s.updateChunk&&s.updateChunk(Q(),_)}n.responseType==="json"&&!Object.values(n.response).length?v():(p&&p(),e(n.response))}else v()}),n.addEventListener("error",()=>{v()}),d){let P=()=>{rs(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(k=ee(),n.removeEventListener("readystatechange",P))};n.addEventListener("readystatechange",P)}return n.responseType=h,n.send(),L},L={withBitrateReporting:y,withParallel:I,withJSONResponse:S,withRetryCount:A=>(l=A,L),withRetryInterval:(A,q)=>(eb(A)&&(b=A),eb(q)&&(f=q),L),withTimeout:A=>(o=A,L),withFinally:T,send:O,abort:()=>{n&&(n.abort(),n=void 0),u=!0,p&&p()}};return L}var pi=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 hi=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=ee(),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=ee()-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=gr(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=ee()}_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=ee();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,du=3;var sw=6e4,nw=10,ow=1,uw=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 pi(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=cu(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=cu(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||is(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=()=>{tb(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 hi(du,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,p=()=>{let v=s&&(!c||c===this.rep);return v||t("Not running!"),v},d=(v,I,O)=>{u&&u.abort(),u=gr(this.urlResolver.resolve(v,!1),I,O,()=>this._retryCallback()).withTimeout(as).withBitrateReporting(this.bitrateSwitcher).withRetryCount(du).withFinally(()=>{u=null}).send()},h=(v,I,O)=>{fi(this.filesFetcher),o==null||o.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(v,!1),I,O,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},f=v=>{let I=r.playbackRate;r.playbackRate!==v&&(t(`Playback rate switch: ${I}=>${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 O=ee()-1e4,C=0;for(let F=0;F<this.bufferStates.length;F++){let R=this.bufferStates[F];v=Math.min(v,R.buf),R.ts<O&&C++}this.bufferStates.splice(0,C),t(`update playback rate; minBuffer=${v} drop=${C} jitter=${this.sourceJitter}`);let D=v-ow;this.sourceJitter>=0?D-=this.sourceJitter/2:this.sourceJitter-=1,D>3?f(1.15):D>1?f(1.1):D>.3?f(1.05):f(1)}},y=v=>{let I,O=()=>I&&I.start?I.start.length:0,C=P=>I.start[P]/1e3,D=P=>I.dur[P]/1e3,F=P=>I.fragIndex+P,R=(P,_)=>({chunkIdx:F(P),startTS:C(P),dur:D(P),discontinuity:_}),L=()=>{let P=0;if(I&&I.dur){let _=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,U=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,j=_;this.sourceJitter>1&&(j+=this.sourceJitter-1);let K=I.dur.length-1;for(;K>=0&&(j-=I.dur[K],!(j<=0));--K);P=Math.min(K,I.dur.length-1-U),P=Math.max(P,0)}return R(P,!0)},A=P=>{let _=O();if(!(_<=0)){if(is(P)){for(let U=0;U<_;U++)if(C(U)>P)return R(U)}return L()}},q=P=>{let _=O(),U=P?P.chunkIdx+1:0,j=U-I.fragIndex;if(!(_<=0)){if(!P||j<0||j-_>nw)return t(`Resync: offset=${j} bChunks=${_} chunk=`+JSON.stringify(P)),L();if(!(j>=_))return R(U-I.fragIndex,!1)}},k=(P,_,U)=>{l&&l.abort(),l=gr(this.urlResolver.resolve(P,!0,this.lowLatency),_,U,()=>this._retryCallback()).withTimeout(as).withRetryCount(du).withFinally(()=>{l=null}).withJSONResponse().send()};return{seek:(P,_)=>{k(v,U=>{if(!p())return;I=U;let j=!!I.lowLatency;j!==this.lowLatency&&b(j);let K=0;for(let Ie=0;Ie<I.dur.length;++Ie)K+=I.dur[Ie];K>0&&(fi(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(K/I.dur.length)),i({name:"index",zeroTime:I.zeroTime,shiftDuration:I.shiftDuration}),this.sourceJitter=I.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,I.jitter/1e3)):1,P(A(_))},()=>this._handleNetworkError())},nextChunk:q}},T=()=>{s=!1,o&&o.abort(),u&&u.abort(),l&&l.abort(),fi(this.filesFetcher),this.filesFetcher.abortAll()};return c={start:v=>{let{videoElement:I,logger:O}=this.params,C=y(e.jidxUrl),D,F,R,L,A=0,q,k,Q,P=()=>{q&&(clearTimeout(q),q=void 0);let B=Math.max(uw,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),J=A+B,w=ee(),se=Math.min(1e4,J-w);A=w;let Me=()=>{l||p()&&C.seek(()=>{p()&&(A=ee(),_(),P())})};se>0?q=window.setTimeout(()=>{this.paused?P():Me()},se):Me()},_=()=>{let B;for(;B=C.nextChunk(L);)L=B,yt(B);let J=C.nextChunk(R);if(J){if(R&&J.discontinuity){O("Detected discontinuity; restarting playback"),this.paused?P():(T(),this._initPlayerWith(e));return}Ie(J)}else P()},U=(B,J)=>{if(!p()||!this.sourceBuffer)return;let w,se,Me,We=ot=>{window.setTimeout(()=>{p()&&U(B,J)},ot)};if(this.sourceBuffer.updating)O("Source buffer is updating; delaying appendBuffer"),We(100);else{let ot=ee(),Tt=I.currentTime;!this.paused&&I.buffered.length>1&&k===Tt&&ot-Q>500&&(O("Stall suspected; trying to fix"),this._fixupStall()),k!==Tt&&(k=Tt,Q=ot);let Qt=this._getBufferSizeSec();if(Qt>30)O(`Buffered ${Qt} seconds; delaying appendBuffer`),We(2e3);else try{this.sourceBuffer.appendBuffer(B),this.videoPlayStarted?(this.bufferStates.push({ts:ot,buf:Qt}),g(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),J&&J()}catch($r){if($r.name==="QuotaExceededError")O("QuotaExceededError; delaying appendBuffer"),Me=this.sourceBuffer.buffered.length,Me!==0&&(w=this.sourceBuffer.buffered.start(0),se=Tt,se-w>4&&this.sourceBuffer.remove(w,se-3)),We(1e3);else throw $r}}},j=()=>{F&&D&&(O([`Appending chunk, sz=${F.byteLength}:`,JSON.stringify(R)]),U(F,function(){F=null,_()}))},K=B=>e.fragUrlTemplate.replace("%%id%%",B.chunkIdx),Ie=B=>{p()&&h(K(B),(J,w)=>{if(p()){if(w/=1e3,F=J,R=B,n=B.startTS,w){let se=Math.min(10,B.dur/w);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*se:se}j()}},()=>this._handleNetworkError())},yt=B=>{p()&&(fi(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(K(B),!1)))},nt=B=>{p()&&(e.cachedHeader=B,U(B,()=>{D=!0,j()}))};s=!0,C.seek(B=>{if(p()){if(A=ee(),!B){P();return}L=B,!aw(v)||B.startTS>v?Ie(B):(R=B,_())}},v),e.cachedHeader?nt(e.cachedHeader):d(e.headerUrl,nt,()=>this._handleNetworkError())},stop:T,getTimestampSec:()=>n},c}_switchToQuality(e){let{logger:t,playerCallback:r}=this.params,i;e.bitrate!==this.bitrate&&(this.rep&&(i=this.rep.getTimestampSec(),is(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,fi(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(i),r({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return is(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,r=p=>{if(!this.autoQuality)return;let d,h,f;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&p<this.bitrate&&(h=this._getBufferSizeSec(),f=p/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(p)}`);return}d=this._selectQuality(p),d?this._switchToQuality(d):e(`Could not find quality by bitrate ${p}`)},s={updateChunk:(d,h)=>{let f=ee();if(this.chunkRateEstimator.addInterval(d,f,h)){let g=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:h,duration:f-d,speed:g}),!0}},get:()=>{let d=this.chunkRateEstimator.getBitRate();return d?d*.85:0}},n=-1/0,o,u=!0,l=()=>{let p=s.get();if(p&&o&&this.autoQuality){if(u&&p>o&&lu(n)<3e4)return;r(p)}u=this.autoQuality};return{updateChunk:(p,d)=>{let h=s.updateChunk(p,d);return h&&l(),h},notifySwitch:p=>{let d=ee();p<o&&(n=d),o=p}}}_fetchManifest(e,t,r){this.manifestRequest=gr(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;he(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))},sw))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};import{debounce as lw,filter as rb,fromEvent as cw,interval as dw,isHigher as pw,isInvariantQuality as hw,isLower as fw,merge as mw,Subject as ib,Subscription as bw}from"@vkontakte/videoplayer-shared";var pu=class{constructor(){this.onDroopedVideoFramesLimit$=new ib;this.subscription=new bw;this.playing=!1;this.tracks=[];this.forceChecker$=new ib;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&&!hw(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&&pw(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(cw(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=dw(this.droppedFramesChecker.checkTime).pipe(rb(()=>this.playing),rb(()=>{let i=!!this.isForceCheckCounter;return i&&(this.isForceCheckCounter-=1),!i})),t=this.forceChecker$.pipe(lw(this.droppedFramesChecker.checkTime)),r=mw(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])=>fw(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}},ss=pu;import{map as gw,Observable as Sw}from"@vkontakte/videoplayer-shared";import{fromEvent as vw}from"@vkontakte/videoplayer-shared";var bi=()=>{var a;return!!((a=window.documentPictureInPicture)!=null&&a.window)||!!document.pictureInPictureElement};var yw=(a,e)=>new Sw(t=>{if(!window.IntersectionObserver)return;let r={root:null},i=new IntersectionObserver((n,o)=>{n.forEach(u=>t.next(u.isIntersecting||bi()))},{...r,...e});i.observe(a);let s=vw(document,"visibilitychange").pipe(gw(n=>!document.hidden||bi())).subscribe(n=>t.next(n));return()=>{i.unobserve(a),s.unsubscribe}}),Re=yw;var Rw=["paused","playing","ready"],Lw=["paused","playing","ready"],gi=class{constructor(e){this.subscription=new Aw;this.videoState=new $("stopped");this.representations$=new fu([]);this.textTracksManager=new we;this.droppedFramesManager=new ss;this.maxSeekBackTime$=new fu(1/0);this.zeroTime$=new fu(void 0);this.liveOffset=new Xe;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:nb.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=ft(u.name))!=null?r:kw(u.video),p=u.bitrate/1e3,d={...u.video};if(!c)continue;let h={id:l,quality:c,bitrate:p,size:d};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),hu(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(Lw.includes(e)&&(n||o)){this.prepare();return}if((i==null?void 0:i.to)!=="paused"&&s.state==="requested"&&Rw.includes(e)){this.seek(s.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(te(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(te(this.params.source.url,u))}return;default:return ab(e)}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=i=>{e.output.error$.next({id:"DashLiveProvider",category:nb.WTF,message:"DashLiveProvider internal logic error",thrown:i})};ub(this.videoState.stateChangeStarted$.pipe(ns(i=>({transition:i,type:"start"}))),this.videoState.stateChangeEnded$.pipe(ns(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(Z(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=pe(this.video);this.subscription.add(this.representations$.pipe(ns(i=>i.map(({track:s})=>s)),ob(i=>!!i.length),Pw()).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(Ew(),ns(i=>-i/1e3)).subscribe(this.params.output.duration$)).add(Tw({zeroTime:this.zeroTime$.pipe(ob(hu)),position:r.timeUpdate$}).subscribe(({zeroTime:i,position:s})=>this.params.output.liveTime$.next(i+s*1e3),t)).add(je(this.video,this.params.desiredState.isLooped,t)).add(de(this.video,this.params.desiredState.volume,r.volumeState$,t)).add(r.volumeState$.subscribe(this.params.output.volume$,t)).add(Ae(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(Re(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:i}})=>{let s=i&&ww(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 ab(i.to)}},t)).add(ub(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,xw(["init"])).pipe(Iw(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),ce(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,p,d,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=(d=(p=this.params.desiredState.autoVideoTrackSwitching.getTransition())==null?void 0:p.to)!=null?d:this.params.desiredState.autoVideoTrackSwitching.getState(),i=!r&&hu(t)?t:mt(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;sb(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;sb(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(te(this.params.source.url,n)),i&&this.dash.pause(),this.liveOffset.resetTo(n,i)}};var lb=gi;var et=(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 Zk,assertNonNullable as eR,debounce as tR,ErrorCategory as Uu,filter as Bg,filterChanged as Hu,fromEvent as rR,isLowerOrEqual as Vg,isNonNullable as iR,isInvariantQuality as aR,map as _g,merge as $s,observableFrom as sR,observeElementSize as nR,once as Ng,Subscription as oR,ValueSubject as uR}from"@vkontakte/videoplayer-shared";var os=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}},Sr=class extends os{constructor(){super(),this.listeners||os.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)}},Si=class{constructor(){Object.defineProperty(this,"signal",{value:new Sr,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&&(Si.prototype[Symbol.toStringTag]="AbortController",Sr.prototype[Symbol.toStringTag]="AbortSignal");function us(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 mu(a){typeof a=="function"&&(a={fetch:a});let{fetch:e,Request:t=e.Request,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:i=!1}=a;if(!us({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 p;c&&c.signal&&(p=c.signal,delete c.signal);let d=new t(l,c);return p&&Object.defineProperty(d,"signal",{writable:!1,enumerable:!1,configurable:!0,value:p}),d},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 p;try{p=new DOMException("Aborted","AbortError")}catch(h){p=new Error("Aborted"),p.name="AbortError"}if(c.aborted)return Promise.reject(p);let d=new Promise((h,f)=>{c.addEventListener("abort",()=>f(p),{once:!0})});return l&&l.signal&&delete l.signal,Promise.race([d,n(u,l)])}return n(u,l)},Request:s}}var vi=us({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),cb=vi?mu({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,tt=vi?cb.fetch:window.fetch,lO=vi?cb.Request:window.Request,rt=vi?Si:window.AbortController,cO=vi?Sr:window.AbortSignal;var Eb=Ue(li(),1);var it=()=>window.ManagedMediaSource||window.MediaSource,ls=()=>{var a,e;return!!(window.ManagedMediaSource&&((e=(a=window.ManagedSourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},db=()=>{var a,e;return!!(window.MediaSource&&window.MediaStreamTrack&&((e=(a=window.SourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},pb=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;import{assertNever as Ss,clientChecker as gs}from"@vkontakte/videoplayer-shared";var Le=document.createElement("video"),Cw='video/mp4; codecs="avc1.42000a,mp4a.40.2"',Dw='video/mp4; codecs="hev1.1.6.L93.B0"',xb='video/webm; codecs="vp09.00.10.08"',Pb='video/webm; codecs="av01.0.00M.08"',Ow='audio/mp4; codecs="mp4a.40.2"',Bw='audio/webm; codecs="opus"',hb,fb,Bt={mms:ls(),mse:db(),hls:!!((hb=Le.canPlayType)!=null&&hb.call(Le,"application/x-mpegurl")||(fb=Le.canPlayType)!=null&&fb.call(Le,"vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},mb,bb,fe={mp4:!!((mb=Le.canPlayType)!=null&&mb.call(Le,"video/mp4")),webm:!!((bb=Le.canPlayType)!=null&&bb.call(Le,"video/webm")),cmaf:!0},ds,gb,ps,Sb,hs,vb,fs,yb,ms,Tb,bs,Ib,me={h264:!!((gb=(ds=it())==null?void 0:ds.isTypeSupported)!=null&&gb.call(ds,Cw)),h265:!!((Sb=(ps=it())==null?void 0:ps.isTypeSupported)!=null&&Sb.call(ps,Dw)),vp9:!!((vb=(hs=it())==null?void 0:hs.isTypeSupported)!=null&&vb.call(hs,xb)),av1:!!((yb=(fs=it())==null?void 0:fs.isTypeSupported)!=null&&yb.call(fs,Pb)),aac:!!((Tb=(ms=it())==null?void 0:ms.isTypeSupported)!=null&&Tb.call(ms,Ow)),opus:!!((Ib=(bs=it())==null?void 0:bs.isTypeSupported)!=null&&Ib.call(bs,Bw))},vr=(me.h264||me.h265)&&me.aac,Vt,Vw=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:Pb}}),window.navigator.mediaCapabilities.decodingInfo({...a,video:{...a.video,contentType:xb}})]);Vt={DASH_WEBM_AV1:e,DASH_WEBM:t}};try{Vw()}catch(a){console.error(a)}var yr=Bt.hls&&fe.mp4,Ab=()=>Object.keys(me).filter(a=>me[a]),wb=(a,e=!1,t=!1)=>{let r=Bt.mse||Bt.mms&&t;return a.filter(i=>{switch(i){case"DASH_SEP":return r&&fe.mp4&&vr;case"DASH_WEBM":return r&&fe.webm&&me.vp9&&me.opus;case"DASH_WEBM_AV1":return r&&fe.webm&&me.av1&&me.opus;case"DASH_STREAMS":return r&&(fe.mp4&&vr||fe.webm&&(me.vp9||me.av1)&&(me.opus||me.aac));case"DASH_LIVE":return Bt.mse&&fe.mp4&&vr;case"DASH_LIVE_CMAF":return r&&fe.mp4&&vr&&fe.cmaf;case"DASH_ONDEMAND":return r&&fe.mp4&&vr;case"HLS":case"HLS_ONDEMAND":return yr||e&&Bt.mse&&fe.mp4&&vr;case"HLS_LIVE":case"HLS_LIVE_CMAF":return yr;case"MPEG":return fe.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return Bt.webrtc&&Bt.ws&&me.h264&&(fe.mp4||fe.webm);default:return Ss(i)}})},cs=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 Vt?Vt[t].smooth?[t,e]:Vt[e].smooth?[e,t]:[t,e]:[e,t];case"power_efficient":return Vt?Vt[t].powerEfficient?[t,e]:Vt[e].powerEfficient?[e,t]:[t,e]:[e,t];default:Ss(a)}return[e,t]},kb=({webmCodec:a,androidPreferredFormat:e,preferMultiStream:t})=>{let r=[...t?["DASH_STREAMS"]:[],...cs(a),"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]],i=[...t?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]];if(gs.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",...cs(a),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...cs(a),"MPEG",...i,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...cs(a),...i,"HLS","HLS_ONDEMAND"];default:Ss(e)}return yr?[...r,"HLS","HLS_ONDEMAND","MPEG"]:[...r,"HLS","HLS_ONDEMAND","MPEG"]},Rb=({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=gs.isMac&&gs.isSafari;if(gs.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:Ss(a)}else yr&&!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"]},bu=a=>a?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],Lb=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,Eb.default)(e.split("."),0);if(t==="opus"||t==="vp09"||t==="av01")return t}return a.values().next().value.split(".").at(0)}};import{ErrorCategory as yi}from"@vkontakte/videoplayer-shared";var $b=a=>{if(!a)return{id:"EmptyResponse",category:yi.PARSER,message:"Empty response"};if(a.length<=2&&a.match(/^\d+$/))return{id:`UVError#${a}`,category:yi.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:yi.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:yi.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:yi.PARSER,message:"Response is valid XML, but parser failed"}};var Ti=(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 Nu,assertNonNullable as Yt,combine as Ps,ErrorCategory as gt,filter as As,filterChanged as Rg,fromEvent as wr,interval as Fu,isNonNullable as Lg,map as qu,merge as kr,Subject as $g,Subscription as Mg,tap as Yk,throttle as Wk,clientChecker as Qk,ValueSubject as ae}from"@vkontakte/videoplayer-shared";var Ar=Ue(li(),1);var _w=(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)},Nw=a=>window.clearTimeout(a),Mb=typeof window.requestIdleCallback!="function"||typeof window.cancelIdleCallback!="function",gu=Mb?_w:window.requestIdleCallback,xO=Mb?Nw:window.cancelIdleCallback;var Ig=Ue(Xa(),1);import{assertNever as Fw,ErrorCategory as Cb,clientChecker as Su,Subject as Db}from"@vkontakte/videoplayer-shared";var qw=16,Ob=!1;try{Ob=Su.isSafari&&!!Su.macVersion&&Su.macVersion<=qw}catch(a){console.error(a)}var vu=class{constructor(e){this.bufferFull$=new Db;this.error$=new Db;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:Cb.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;Ob&&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:Cb.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:Fw(t)}}},Bb=vu;var yu=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 Pr,assertNonNullable as Ye,ErrorCategory as Ht,fromEvent as Cu,getExponentialDelay as Du,isNonNullable as Tg,isNullable as Ne,once as _k,Subject as Nk,Subscription as Fk,ValueSubject as ji}from"@vkontakte/videoplayer-shared";var N=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 Tr=class extends N{};var Ii=class extends N{};var Ei=class extends N{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 xi=class extends N{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Pi=class extends N{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Ai=class extends N{constructor(e,t){super(e,t),this.data=this.content}};var W=class extends N{constructor(e,t){super(e,t);let r=this.readUint32();this.version=r>>>24,this.flags=r&16777215}};var _t=class extends W{get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e,t){super(e,t),this.segments=[],this.referenceId=this.readUint32(),this.timescale=this.readUint32(),this.earliestPresentationTime32=this.readUint32(),this.firstOffset32=this.readUint32(),this.earliestPresentationTime64=0,this.firstOffset64=0,this.referenceCount=this.readUint32()&65535;for(let r=0;r<this.referenceCount;r++){let i=this.readUint32(),s=i>>>31,n=i<<1>>>1,o=this.readUint32();i=this.readUint32();let u=i>>>28,l=i<<3>>>3;this.segments.push({referenceType:s,referencedSize:n,subsegmentDuration:o,SAPType:u,SAPDeltaTime:l})}}};var wi=class extends N{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ki=class extends N{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Ri=class extends W{constructor(e,t){switch(super(e,t),this.readUint8()){case 0:this.stereoMode=0;break;case 1:this.stereoMode=1;break;case 2:this.stereoMode=2;break;case 3:this.stereoMode=3;break;case 4:this.stereoMode=4;break}this.cursor+=1}};var Li=class extends W{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var $i=class extends W{constructor(e,t){super(e,t),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}};var Mi=class extends N{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Ci=class extends W{constructor(e,t){super(e,t),this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.trackId=this.readUint32(),this.cursor+=4,this.duration=this.readUint32(),this.cursor+=8,this.layer=this.readUint16(),this.alternateGroup=this.readUint16(),this.cursor+=2,this.cursor+=2,this.matrix=[[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()]],this.width=this.readUint32(),this.height=this.readUint32()}};var Di=class extends N{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Oi=class extends N{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Bi=class extends W{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var Vi=class extends N{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var _i=class extends W{constructor(e,t){super(e,t),this.trackId=this.readUint32(),this.flags&1&&(this.baseDataOffset=this.readUint64()),this.flags&2&&(this.sampleDescriptionIndex=this.readUint32()),this.flags&8&&(this.defaultSampleDuration=this.readUint32()),this.flags&16&&(this.defaultSampleSize=this.readUint32()),this.flags&32&&(this.defaultSampleFlags=this.readUint32())}};var Ni=class extends W{constructor(t,r){super(t,r);this.baseMediaDecodeTime32=0;this.baseMediaDecodeTime64=BigInt(0);this.version===1?this.baseMediaDecodeTime64=this.readUint64():this.baseMediaDecodeTime32=this.readUint32()}get baseMediaDecodeTime(){return this.version===1?this.baseMediaDecodeTime64:this.baseMediaDecodeTime32}};var Fi=class extends W{constructor(t,r){super(t,r);this.sampleDuration=[];this.sampleSize=[];this.sampleFlags=[];this.sampleCompositionTimeOffset=[];this.optionalFields=0;this.sampleCount=this.readUint32(),this.flags&1&&(this.dataOffset=this.readUint32()),this.flags&4&&(this.firstSampleFlags=this.readUint32());for(let i=0;i<this.sampleCount;i++)this.flags&256&&this.sampleDuration.push(this.readUint32()),this.flags&512&&this.sampleSize.push(this.readUint32()),this.flags&1024&&this.sampleFlags.push(this.readUint32()),this.flags&2048&&this.sampleCompositionTimeOffset.push(this.readUint32())}};var Hw={ftyp:Ei,moov:xi,moof:Pi,mdat:Ai,sidx:_t,trak:wi,mdia:Mi,mfhd:Bi,tkhd:Ci,traf:Vi,tfhd:_i,tfdt:Ni,trun:Fi,minf:Di,sv3d:ki,st3d:Ri,prhd:Li,proj:Oi,equi:$i,uuid:Ii,unknown:Tr},Nt=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=Hw[e];return r?new r(t,new a):new Tr(t,new a)}};var Ir=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 Gw=new TextDecoder("ascii"),Yw=a=>Gw.decode(new DataView(a.buffer,a.byteOffset+4,4))==="ftyp",Ww=a=>{let e=new _t(a,new Nt),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})},Qw=(a,e)=>{let r=new Nt().parse(a),i=new Ir(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,p=u.source.byteOffset-o.source.byteOffset+u.size;return new DataView(a.buffer,l,p)},zw=(a,e)=>{let r=new Nt().parse(a),s=new Ir(r).findAll("traf"),n=s[s.length-1].children.find(p=>p.type==="tfhd"),o=s[s.length-1].children.find(p=>p.type==="tfdt"),u=s[s.length-1].children.find(p=>p.type==="trun"),l=0;return u.sampleDuration.length?l=u.sampleDuration.reduce((p,d)=>p+d,0):l=n.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+l)/e*1e3},Kw=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 Nt().parse(a),i=new Ir(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},Vb={validateData:Yw,parseInit:Kw,getIndexRange:()=>{},parseSegments:Ww,parseFeedableSegmentChunk:Qw,getSegmentEndTime:zw};import{assertNonNullable as Iu,isNonNullable as qb,isNullable as Xw}from"@vkontakte/videoplayer-shared";import{assertNever as Jw}from"@vkontakte/videoplayer-shared";var _b={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"}},Nb=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=qi(a,t),i=r in _b,s=i?_b[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=qi(u),p=l*2**((o-1)*8)+c,d=t+o,h;return d+p>a.byteLength?h=new DataView(a.buffer,a.byteOffset+d):h=new DataView(a.buffer,a.byteOffset+d,p),{tag:i?r:"0x"+r.toString(16).toUpperCase(),type:s,tagHeaderSize:d,tagSize:d+p,value:h,valueSize:p}},qi=(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},_e=(a,e)=>{switch(e){case"int":return a.getInt8(0);case"uint":return qi(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:Jw(e)}},Ft=(a,e)=>{let t=0;for(;t<a.byteLength;){let r=new DataView(a.buffer,a.byteOffset+t),i=Nb(r);if(!e(i))return;i.type==="master"&&Ft(i.value,e),t=i.value.byteOffset-a.byteOffset+i.valueSize}},Fb=a=>{if(a.getUint32(0)!==440786851)return!1;let e,t,r,i=Nb(a);return Ft(i.value,({tag:s,type:n,value:o})=>(s===17143?e=_e(o,n):s===17026?t=_e(o,n):s===17029&&(r=_e(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(r===void 0||r<=2)};var Ub=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],Zw=[231,22612,22743,167,171,163,160,175],ek=a=>{let e,t,r,i,s=!1,n=!1,o=!1,u,l,c=!1,p=0;return Ft(a,({tag:d,type:h,value:f,valueSize:b})=>{if(d===21419){let g=_e(f,h);l=qi(g)}else d!==21420&&(l=void 0);return d===408125543?(e=f.byteOffset,t=f.byteOffset+b):d===357149030?s=!0:d===290298740?n=!0:d===2807729?r=_e(f,h):d===17545?i=_e(f,h):d===21420&&l===475249515?u=_e(f,h):d===374648427?Ft(f,({tag:g,type:y,value:T})=>g===30321?(c=_e(T,y)===1,!1):!0):s&&n&&Ub.includes(d)&&(o=!0),!o}),Iu(e,"Failed to parse webm Segment start"),Iu(t,"Failed to parse webm Segment end"),Iu(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:p,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},tk=a=>{if(Xw(a.cuesSeekPosition))return;let e=a.segmentStart+a.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},rk=(a,e)=>{let t=!1,r=!1,i=o=>qb(o.time)&&qb(o.position),s=[],n;return Ft(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=_e(l,u));break;case 183:break;case 241:n&&(n.position=_e(l,u));break;default:t&&Ub.includes(o)&&(r=!0)}return!(t&&r)}),n&&i(n)&&s.push(n),s.map((o,u)=>{let{time:l,position:c}=o,p=s[u+1];return{status:"none",time:{from:l,to:p?p.time:e.segmentDuration},byte:{from:e.segmentStart+c,to:p?e.segmentStart+p.position-1:e.segmentEnd-1}}})},ik=a=>{let e=0,t=!1;try{Ft(a,r=>r.tag===524531317?r.tagSize<=a.byteLength?(e=r.tagSize,!1):(e+=r.tagHeaderSize,!0):Zw.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},Hb={validateData:Fb,parseInit:ek,getIndexRange:tk,parseSegments:rk,parseFeedableSegmentChunk:ik};var Er=a=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(a);if(e){let[,t,r]=e;if(t==="audio"||t==="video")switch(r){case"webm":return Hb;case"mp4":return Vb}}throw new ReferenceError(`Unsupported mime type ${a}`)};var Ru=Ue(dg(),1);var ku=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 hg,isNullable as fg}from"@vkontakte/videoplayer-shared";var pg=a=>{if(a.includes("/")){let e=a.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(a)};var mg=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},qt=(a,e)=>{let t=a;t=(0,Ru.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,Ru.default)(t,n,(o,u)=>fg(s)?o:fg(u)?s:s.padStart(parseInt(u,10),"0"))}return t},gg=(a,e)=>{var v,I,O,C,D,F,R,L,A,q,k,Q,P,_,U,j,K,Ie,yt,nt,B,J,w,se,Me,We,ot,Tt,Qt,$r,al,sl,nl,ol,ul,ll,cl,dl,pl,hl,fl,ml,bl,gl,Sl,vl,yl,Tl,Il,El;let r=new DOMParser().parseFromString(a,"application/xml"),i={video:[],audio:[],text:[]},s=r.children[0],n=s.getElementsByTagName("Period")[0],o=(O=(I=(v=s.querySelector("BaseURL"))==null?void 0:v.textContent)==null?void 0:I.trim())!=null?O:"",u=n.children,l=s.getAttribute("type")==="dynamic",c=s.getAttribute("availabilityStartTime"),p=c?new Date(c).getTime():void 0,d,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)d=mg(h);else if(f){let ne=mg(f);hg(ne)&&(d=ne)}else g&&(d=parseInt(g,10));let y=0,T=(D=(C=s.getAttribute("profiles"))==null?void 0:C.split(","))!=null?D:[];for(let ne of u){let kS=(F=ne.getAttribute("id"))!=null?F:"id"+(y++).toString(10),Mr=(R=ne.getAttribute("mimeType"))!=null?R:"",Ws=(L=ne.getAttribute("codecs"))!=null?L:"",Qs=(A=ne.getAttribute("contentType"))!=null?A:Mr==null?void 0:Mr.split("/")[0],RS=(k=(q=ne.getAttribute("profiles"))==null?void 0:q.split(","))!=null?k:[],LS=(Q=ne.getAttribute("lang"))!=null?Q:void 0,$S=(U=(_=(P=ne.querySelector("Label"))==null?void 0:P.textContent)==null?void 0:_.trim())!=null?U:void 0,MS=ne.querySelectorAll("Representation"),CS=ne.querySelector("SegmentTemplate"),DS=(K=(j=ne.querySelector("Role"))==null?void 0:j.getAttribute("value"))!=null?K:void 0,Cr=Qs,X={id:kS,language:LS,isDefault:DS==="main",label:$S,codecs:Ws,hdr:Cr==="video"&&ku(Ws),mime:Mr,representations:[]};for(let z of MS){let OS=(Ie=z.getAttribute("lang"))!=null?Ie:void 0,BS=(yt=z.getAttribute("label"))!=null?yt:void 0,VS=(J=(B=(nt=z.querySelector("BaseURL"))==null?void 0:nt.textContent)==null?void 0:B.trim())!=null?J:"",zs=new URL(VS||o,e).toString(),zt=(w=z.getAttribute("mimeType"))!=null?w:Mr,ca=(Me=(se=z.getAttribute("codecs"))!=null?se:Ws)!=null?Me:"",Ks;if(Qs==="text"){let It=z.getAttribute("id")||"",Js=It.includes("_auto");Ks={id:It,isAuto:Js,kind:"text",url:zs}}else{let It=(ot=(We=z.getAttribute("contentType"))!=null?We:zt==null?void 0:zt.split("/")[0])!=null?ot:Qs,Js=(Qt=(Tt=ne.getAttribute("profiles"))==null?void 0:Tt.split(","))!=null?Qt:[],_S=parseInt(($r=z.getAttribute("width"))!=null?$r:"",10),xl=parseInt((al=z.getAttribute("height"))!=null?al:"",10),Pl=parseInt((sl=z.getAttribute("bandwidth"))!=null?sl:"",10)/1e3,Al=(nl=z.getAttribute("frameRate"))!=null?nl:"",NS=(ol=z.getAttribute("quality"))!=null?ol:void 0,FS=Al?pg(Al):void 0,qS=(ul=z.getAttribute("id"))!=null?ul:"id"+(y++).toString(10),US=It==="video"?`${xl}p`:It==="audio"?`${Pl}Kbps`:ca,HS=`${qS}@${US}`,jS=[...T,...RS,...Js],Xs,GS=z.querySelector("SegmentBase"),Et=(ll=z.querySelector("SegmentTemplate"))!=null?ll:CS;if(GS){let xt=(dl=(cl=z.querySelector("SegmentBase Initialization"))==null?void 0:cl.getAttribute("range"))!=null?dl:"",[Pt,en]=xt.split("-").map(Kt=>parseInt(Kt,10)),ut={from:Pt,to:en},Dr=(pl=z.querySelector("SegmentBase"))==null?void 0:pl.getAttribute("indexRange"),[tn,da]=Dr?Dr.split("-").map(Kt=>parseInt(Kt,10)):[],Or=Dr?{from:tn,to:da}:void 0;Xs={type:"byteRange",url:zs,initRange:ut,indexRange:Or}}else if(Et){let xt={representationId:(hl=z.getAttribute("id"))!=null?hl:void 0,bandwidth:(fl=z.getAttribute("bandwidth"))!=null?fl:void 0},Pt=parseInt((ml=Et.getAttribute("timescale"))!=null?ml:"",10),en=(bl=Et.getAttribute("initialization"))!=null?bl:"",ut=Et.getAttribute("media"),Dr=(Sl=parseInt((gl=Et.getAttribute("startNumber"))!=null?gl:"",10))!=null?Sl:1,tn=qt(en,xt);if(!ut)throw new ReferenceError("No media attribute in SegmentTemplate");let da=(vl=Et.querySelectorAll("SegmentTimeline S"))!=null?vl:[],Or=[],Kt=0,rn="",an=0;if(da.length){let pa=Dr,Ce=0;for(let Jt of da){let qe=parseInt((yl=Jt.getAttribute("d"))!=null?yl:"",10),At=parseInt((Tl=Jt.getAttribute("r"))!=null?Tl:"",10)||0,ha=parseInt((Il=Jt.getAttribute("t"))!=null?Il:"",10);Ce=Number.isFinite(ha)?ha:Ce;let sn=qe/Pt*1e3,nn=Ce/Pt*1e3;for(let fa=0;fa<At+1;fa++){let WS=qt(ut,{...xt,segmentNumber:pa.toString(10),segmentTime:(Ce+fa*qe).toString(10)}),wl=(nn!=null?nn:0)+fa*sn,QS=wl+sn;pa++,Or.push({time:{from:wl,to:QS},url:WS})}Ce+=(At+1)*qe,Kt+=(At+1)*sn}an=Ce/Pt*1e3,rn=qt(ut,{...xt,segmentNumber:pa.toString(10),segmentTime:Ce.toString(10)})}else if(hg(d)){let Ce=parseInt((El=Et.getAttribute("duration"))!=null?El:"",10)/Pt*1e3,Jt=Math.ceil(d/Ce),qe=0;for(let At=1;At<Jt;At++){let ha=qt(ut,{...xt,segmentNumber:At.toString(10),segmentTime:qe.toString(10)});Or.push({time:{from:qe,to:qe+Ce},url:ha}),qe+=Ce}an=qe,rn=qt(ut,{...xt,segmentNumber:Jt.toString(10),segmentTime:qe.toString(10)})}let YS={time:{from:an,to:1/0},url:rn};Xs={type:"template",baseUrl:zs,segmentTemplateUrl:ut,initUrl:tn,totalSegmentsDurationMs:Kt,segments:Or,nextSegmentBeyondManifest:YS,timescale:Pt}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!It||!zt)continue;let Zs={video:"video",audio:"audio",text:"text"}[It];if(!Zs)continue;Cr||(Cr=Zs),Ks={id:HS,kind:Zs,segmentReference:Xs,profiles:jS,duration:d,bitrate:Pl,mime:zt,codecs:ca,width:_S,height:xl,fps:FS,quality:NS}}X.language||(X.language=OS),X.label||(X.label=BS),X.mime||(X.mime=zt),X.codecs||(X.codecs=ca),X.hdr||(X.hdr=Cr==="video"&&ku(ca)),X.representations.push(Ks)}Cr&&i[Cr].push(X)}return{dynamic:l,liveAvailabilityStartTime:p,duration:d,streams:i}};var Ui=Ue(li(),1);import{videoSizeToQuality as Vk}from"@vkontakte/videoplayer-shared";var Sg=({id:a,width:e,height:t,bitrate:r,fps:i,quality:s})=>{var o;let n=(o=s?ft(s):void 0)!=null?o:Vk({width:e,height:t});return n&&{id:a,quality:n,bitrate:r,size:{width:e,height:t},fps:i}},vg=({id:a,bitrate:e})=>({id:a,bitrate:e}),vs=(a,e,t)=>{var i;let r=e.indexOf(a);return(i=(0,Ui.default)(t,Math.round(t.length*r/e.length)))!=null?i:(0,Ui.default)(t,-1)},yg=({language:a,label:e},{id:t,url:r,isAuto:i})=>({id:t,url:r,isAuto:i,type:"internal",language:a,label:e}),$u=({id:a,language:e,label:t,codecs:r,isDefault:i})=>({id:a,language:e,label:t,codec:(0,Ui.default)(r.split("."),0),isDefault:i}),Mu=({id:a,language:e,label:t,hdr:r,codecs:i})=>({id:a,language:e,hdr:r,label:t,codec:(0,Ui.default)(i.split("."),0)}),ys=a=>"url"in a,Ut=a=>a.type==="template",Hi=a=>a instanceof DOMException&&(a.name==="AbortError"||a.code===20);var Gi=class{constructor(e,t,r,{fetcher:i,tuning:s,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentSegmentLength$=new ji(0);this.onLastSegment$=new ji(!1);this.fullyBuffered$=new ji(!1);this.playingRepresentation$=new ji(void 0);this.playingRepresentationInit$=new ji(void 0);this.error$=new Nk;this.gaps=[];this.subscription=new Fk;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new rt;this.destroyAbortController=new rt;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=Pr(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);Ye(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new Bb(this.sourceBuffer),this.subscription.add(Cu(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let o,u=this.mediaSource.readyState;u!=="open"&&(o={id:`SegmentEjection_source_${u}`,category:Ht.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o!=null||(o={id:"SegmentEjection",category:Ht.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),this.error$.next(o)})),this.subscription.add(Cu(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:Ht.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,yu(this.sourceBuffer.buffered)*.8);if(this.bufferLimit=u,this.tuning.useNewPruneBufferStrategy){let l=et(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);Ye(r,"No init buffer for starting representation"),Ye(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=Pr(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);Ye(r,`No such representation ${e}`);let i=this.segments.get(e),s=this.initData.get(e);if(Ne(s)||Ne(i)?yield this.loadInit(r,"high",!1):s instanceof Promise&&(yield s),i=this.segments.get(e),Ye(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();Tg(n)&&(this.isLive||(i.forEach(o=>o.status="none"),this.tuning.useNewPruneBufferStrategy&&(this.bufferLimit=1/0),this.pruneBuffer(n,1/0,!0)),this.maintain(n)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}}.bind(this));this.seekLive=Pr(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 p=t.find(f=>f.id===c);p&&this.representations.set(c,p);let d=this.representations.get(c);if(!d||!Ut(d.segmentReference))return;let h=this.getActualLiveStartingSegments(d.segmentReference);this.segments.set(d.id,h)}let r=(l=this.switchingToRepresentationId)!=null?l:this.downloadingRepresentationId,i=this.representations.get(r);Ye(i);let s=this.segments.get(r);Ye(s,"No segments for starting representation");let n=this.initData.get(r);if(Ye(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.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 rt,this.abortBuffer()}maintain(e=this.getCurrentPosition()){var l,c;if(Ne(e)||Ne(this.downloadingRepresentationId)||Ne(this.playingRepresentationId)||Ne(this.sourceBuffer)||!Ne(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),r=this.segments.get(this.downloadingRepresentationId);if(Ye(t,`No such representation ${this.downloadingRepresentationId}`),!r)return;let i=r.find(p=>e>=p.time.from&&e<p.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 d=et(this.sourceBuffer.buffered,e),h=i?i.time.to+100:-1/0;i&&i.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&d>=i.time.to-e+100&&(s=h)}if(isFinite(this.bufferLimit)&&yu(this.sourceBuffer.buffered)>=this.bufferLimit){let p=et(this.sourceBuffer.buffered,e),d=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,p<d);return}let o=[];if(!this.activeSegments.size&&(o=this.selectForwardBufferSegments(r,t.segmentReference.type,s),o.length)){let p="auto";if(this.tuning.dash.useFetchPriorityHints&&i)if(o.includes(i))p="high";else{let d=(0,Ar.default)(o,0);d&&d.time.from-i.time.to>=this.forwardBufferTarget/2&&(p="low")}this.loadSegments(o,t,p)}(!this.preloadOnly&&!this.allInitsLoaded&&i&&i.status==="fed"&&!o.length&&et(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let u=(0,Ar.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;Tg(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||!Ut(o.segmentReference))return;let u=o.segmentReference.segments.map(d=>({...d,status:"none",size:void 0})),l=(i=this.segments.get(o.id))!=null?i:[],c=(n=(s=(0,Ar.default)(l,-1))==null?void 0:s.time.to)!=null?n:0,p=u==null?void 0:u.findIndex(d=>Math.floor(c)>=Math.floor(d.time.from)&&Math.floor(c)<=Math.floor(d.time.to));if(p===-1){this.liveUpdateSegmentIndex=0;let d=this.getActualLiveStartingSegments(o.segmentReference);this.segments.set(o.id,d)}else{let d=u.slice(p+1);this.segments.set(o.id,[...l,...d])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;Ye(e);let t=this.segments.get(e);if(t!=null&&t.length){let r=t[t.length-1];this.updateLowLatencyLiveIfNeeded(r)}}updateLowLatencyLiveIfNeeded(e){var t;for(let r of this.representations.values()){let i=r.segmentReference;if(!Ut(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=qt(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:p,time:{from:d,to:h}},f)=>{let b=d<=r&&h>=r,g=d>r||b||f===0&&r===0,y=Math.min(this.forwardBufferTarget,this.bufferLimit),T=this.preloadOnly&&d<=r+y||h<=r+y;return(p==="none"||p==="partially_ejected"&&g&&T&&this.sourceBuffer&&!Ti(this.sourceBuffer.buffered,r))&&g&&T});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 p=i;p<s.length&&(n<=l||o<=c);p++){let d=s[p];if(n+=d.byte.to+1-d.byte.from,o+=d.time.to+1-d.time.from,d.status==="none"||d.status==="partially_ejected")u.push(d);else break}return u}async loadSegments(e,t,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:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(await Pr(o,async function*(){let c=Du(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(p=>setTimeout(p,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 p=new DataView(c);if(!isFinite(i.segment.time.to)){let d=t.segmentReference.timescale,h=Er(t.mime);i.segment.time.to=h.getSegmentEndTime(p,d)}u&&i.feedingBytes&&l?await Promise.all(l):await this.sourceBufferTaskQueue.append(p,o),i.segment.status="downloaded",this.onSegmentFullyAppended(i,t.id),this.failedDownloads=0}catch(c){this.abortActiveSegments([e]),Hi(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 Pr(n,async function*(){let u=Du(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),Cu(window,"online").pipe(_k()).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),Hi(u)||this.failedDownloads++}}prepareByteRangeFetchSegmentParams(e,t){if(Ut(t.segmentReference))throw new Error("Representation is not byte range type");let r=t.segmentReference.url,i={from:(0,Ar.default)(e,0).byte.from,to:(0,Ar.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:Ht.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!Ut(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 p=this.onSomeTemplateDataLoaded({dataView:l,loaded:c,signal:s,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(p)}catch(p){this.error$.next({id:"SegmentFeeding",category:Ht.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:p})}}: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=Er(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:p}=c,d=u==="byteRange",h=d?p.byte.to-p.byte.from+1:l;if(c.representationId!==t||!(!d||p.byte.from>=r&&p.byte.to<r+e.byteLength))continue;if(s.aborted){n();continue}let b=d?p.byte.from-r:0,g=d?p.byte.to-r:e.byteLength,y=b<i,T=g<=i;if(p.status==="downloading"&&y&&T){p.status="downloaded";let S=new DataView(e.buffer,e.byteOffset+b,h);this.sourceBufferTaskQueue.append(S,s).then(v=>v&&!s.aborted?this.onSegmentFullyAppended(c,t):n())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&y&&(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:Er(o.mime).parseFeedableSegmentChunk(S);v!=null&&v.byteLength&&(p.status="partially_fed",c.feedingBytes+=v.byteLength,this.sourceBufferTaskQueue.append(v,s).then(I=>{if(s.aborted)n();else if(I)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,p=l.byte.to-r,d=p-c+1,h=c<i,f=p<=i;if(h){if(l.status==="downloading"&&f){l.status="downloaded";let b=new DataView(e.buffer,e.byteOffset+c,d);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(d,i-c),u.loadedBytes>u.feedingBytes)){let b=new DataView(e.buffer,e.byteOffset+c+u.feedingBytes,u.loadedBytes-u.feedingBytes),g=u.loadedBytes===d?b:Er(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===d&&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",ys(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"&&s.time.from===e.segment.time.from&&s.time.to===e.segment.time.to&&(s.status="none");this.updateLowLatencyLiveIfNeeded(e.segment),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment])}abortSegment(e){(this.tuning.useDashAbortPartiallyFedSegment?e.status==="partially_fed"||e.status==="partially_ejected":e.status==="partially_ejected")?(this.sourceBufferTaskQueue.remove(e.time.from,e.time.to).then(()=>e.status="none"),e.status="partially_ejected"):e.status="none";for(let r of this.activeSegments.values())if(r.segment===e){this.activeSegments.delete(r);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=gu(()=>(0,Ig.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?Pr(this.destroyAbortController.signal,async function*(){let o=Du(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,Er(e.mime),i)).then(async o=>{if(!o)return;let{init:u,dataView:l,segments:c}=o,p=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,p);let d=c;this.isLive&&Ut(e.segmentReference)&&(d=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,d),u&&this.parsedInitData.set(e.id,u)}).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),r&&this.error$.next({id:"LoadInits",category:Ht.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||Ne(e)||this.sourceBuffer.updating)return!1;let i=[],s=0,n=u=>{u.sort((c,p)=>c.from-p.from);let l=[u[0]];for(let c=1;c<u.length;c++){let{from:p,to:d}=u[c],h=l[l.length-1];h.to>=p?h.to=Math.max(h.to,d):l.push(u[c])}return l},o=u=>{var c;if(s>=t)return i;i.push(u.time),i=n(i);let l=ys(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,p=l.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(c||p)&&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,p=0;for(let d of this.segments.values())for(let h of d)h.status==="none"&&Math.round(h.time.from)<=Math.round(l)&&Math.round(h.time.to)>=Math.round(c)&&p++;if(p===this.segments.size){let d={time:{from:l,to:c},url:"",status:"none"};o(d)}}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||Ne(e)||this.sourceBuffer.updating)return!1;let i=0,s=1/0,n=-1/0,o=!1,u=l=>{var p;s=Math.min(s,l.time.from),n=Math.max(n,l.time.to);let c=ys(l)?(p=l.size)!=null?p: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,p=this.sourceBuffer.buffered.end(l)*1e3;for(let d of this.segments.values())for(let h of d)if(h.status==="none"&&Math.round(h.time.from)<=Math.round(c)&&Math.round(h.time.to)>=Math.round(p)){s=c,n=p;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 p of c)p.time.from>e+l&&p.status==="fed"&&u(p)}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){this.gapDetectionIdleCallback||(this.gapDetectionIdleCallback=gu(()=>{try{this.detectGaps(e,t)}catch(r){this.error$.next({id:"GapDetection",category:Ht.WTF,message:"detectGaps threw",thrown:r})}finally{this.gapDetectionIdleCallback=null}}))}checkEjectedSegments(){if(Ne(this.sourceBuffer)||Ne(this.playingRepresentationId))return;let e=[];for(let r=0;r<this.sourceBuffer.buffered.length;r++){let i=Math.round(this.sourceBuffer.buffered.start(r)*1e3),s=Math.round(this.sourceBuffer.buffered.end(r)*1e3);e.push({from:i,to:s})}let t=1;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-t&&n<=c.to+t||o>=c.from-t&&o<=c.to+t);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 Yi=a=>{let e=new URL(a);return e.searchParams.set("quic","1"),e.toString()};var Eg=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 Wi,assertNever as xg,fromEvent as Pg,merge as qk,now as Ou,Subscription as Uk,ValueSubject as Bu}from"@vkontakte/videoplayer-shared";var Ts=class{constructor({throughputEstimator:e,requestQuic:t,compatibilityMode:r=!1}){this.lastConnectionType$=new Bu(void 0);this.lastConnectionReused$=new Bu(void 0);this.lastRequestFirstBytes$=new Bu(void 0);this.abortAllController=new rt;this.subscription=new Uk;this.fetchManifest=Wi(this.abortAllController.signal,async function*(e){let t=e;this.requestQuic&&(t=Yi(t));let r=yield tt(t,{signal:this.abortAllController.signal}).catch(Qi);return r?(this.onHeadersReceived(r.headers),r.text()):null}.bind(this));this.fetch=Wi(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 D,F;let l=e,c=new Headers;if(r)switch(t){case 0:{c.append("Range",`bytes=${r.from}-${r.to}`);break}case 1:{let R=new URL(l,location.href);R.searchParams.append("bytes",`${r.from}-${r.to}`),l=R.toString();break}default:xg(t)}this.requestQuic&&(l=Yi(l));let p=this.abortAllController.signal,d;if(n){let R=new rt;if(d=qk(Pg(this.abortAllController.signal,"abort"),Pg(n,"abort")).subscribe(()=>{try{R.abort()}catch(L){Qi(L)}}),this.abortAllController.signal.aborted||n.aborted)try{R.abort()}catch(L){Qi(L)}p=R.signal}let h=Ou(),f=yield tt(l,{priority:s,headers:c,signal:p}).catch(Qi),b=Ou();if(!f)return d==null||d.unsubscribe(),null;if((D=this.throughputEstimator)==null||D.addRawRtt(b-h),!f.ok||!f.body)return d==null||d.unsubscribe(),Promise.reject(new Error(`Fetch error ${f.status}: ${f.statusText}`));if(this.onHeadersReceived(f.headers),!i&&!o)return d==null||d.unsubscribe(),f.arrayBuffer();let[g,y]=f.body.tee(),T=g.getReader();o&&((F=this.throughputEstimator)==null||F.trackStream(y,u));let S=0,v=new Uint8Array(0),I=!1,O=R=>{d==null||d.unsubscribe(),I=!0,Qi(R)},C=Wi(p,async function*({done:R,value:L}){if(S===0&&this.lastRequestFirstBytes$.next(Ou()-h),p.aborted){d==null||d.unsubscribe();return}if(!R&&L){let A=new Uint8Array(v.length+L.length);A.set(v),A.set(L,v.length),v=A,S+=L.byteLength,i==null||i(new DataView(v.buffer),S),yield T==null?void 0:T.read().then(C,O)}}.bind(this));return yield T==null?void 0:T.read().then(C,O),d==null||d.unsubscribe(),I?null:v.buffer}.bind(this));this.fetchByteRangeRepresentation=Wi(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 p=yield this.fetch(e.url,{range:{from:n,to:o},priority:r,measureThroughput:!1});if(!p)return null;let d=new DataView(p,i-n,s-n+1);if(!t.validateData(d))throw new Error("Invalid media file");let h=t.parseInit(d),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(p,f.from-n,f.to-f.from+1);else{let T=yield this.fetch(e.url,{range:f,priority:r,measureThroughput:!1});if(!T)return null;b=new DataView(T)}let g=t.parseSegments(b,h,f);return{init:h,dataView:new DataView(p),segments:g}}.bind(this));this.fetchTemplateRepresentation=Wi(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=r}onHeadersReceived(e){let{type:t,reused:r}=Eg(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:xg(i)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}},Qi=a=>{if(!Hi(a))throw a};var jt=(a,e,t)=>t*e+(1-t)*a,Vu=(a,e)=>a.reduce((t,r)=>t+r,0)/e,Ag=(a,e,t,r)=>{let i=0,s=t,n=Vu(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 Hk,ValueSubject as wg}from"@vkontakte/videoplayer-shared";var bt=class{constructor(e){this.prevReported=void 0;this.pastMeasures=[];this.takenMeasures=0;this.measuresCursor=0;var r;this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new wg(e.initial),this.debounced$=new wg(e.initial);let t=(r=e.label)!=null?r:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new ie(`raw_${t}`),this.smoothedSeries$=new ie(`smoothed_${t}`),this.reportedSeries$=new ie(`reported_${t}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,r=0;for(let o=0;o<this.pastMeasures.length;o++)this.pastMeasures[o]!==void 0&&(t+=(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)&&(Hk(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 Is=class extends bt{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=jt(this.slow,e,this.params.emaAlphaSlow),this.fast=jt(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var Es=class extends bt{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=Vu(this.pastMeasures,this.takenMeasures);this.emaSmoothed=jt(this.emaSmoothed,e,this.params.emaAlpha);let r=Ag(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=r?this.emaSmoothed:t}};var xs=class extends bt{constructor(t){super(t);this.furtherValues=[];this.currentTopExtremumValue=0;this.extremumInterval=t.extremumInterval}next(t){this.currentTopExtremumValue<=t?(this.currentTopExtremumValue=t,this.furtherValues=[]):this.furtherValues.length===this.extremumInterval?(super.next(this.currentTopExtremumValue),this.currentTopExtremumValue=t,this.furtherValues=[]):this.furtherValues.push(t)}updateSmoothedValue(t){this.smoothed=this.smoothed?jt(this.smoothed,t,this.params.emaAlpha):t}};var Gt=class{static getSmoothedValue(e,t,r){return r.type==="TwoEma"?new Is({initial:e,emaAlphaSlow:r.emaAlphaSlow,emaAlphaFast:r.emaAlphaFast,changeThreshold:r.changeThreshold,fastDirection:t,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"}):new Es({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 xs({initial:e,label:"liveEdgeDelay",...t})}};var _u=(a,e)=>{a&&a.playbackRate!==e&&(a.playbackRate=e)};var Cg=["timeupdate","progress","play","seeked","stalled","waiting"];var ws=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new Mg;this.representationSubscription=new Mg;this.state$=new $("none");this.currentVideoRepresentation$=new ae(void 0);this.currentVideoRepresentationInit$=new ae(void 0);this.currentAudioRepresentation$=new ae(void 0);this.currentVideoSegmentLength$=new ae(0);this.currentAudioSegmentLength$=new ae(0);this.error$=new $g;this.lastConnectionType$=new ae(void 0);this.lastConnectionReused$=new ae(void 0);this.lastRequestFirstBytes$=new ae(void 0);this.isLive$=new ae(!1);this.liveDuration$=new ae(0);this.liveAvailabilityStartTime$=new ae(void 0);this.bufferLength$=new ae(0);this.liveLoadBufferLength$=new ae(0);this.livePositionFromPlayer$=new ae(0);this.timeInWaiting=0;this.isActiveLowLatency$=new ae(!1);this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.liveLastSeekOffset=0;this.forceEnded$=new $g;this.gapWatchdogActive=!1;this.destroyController=new rt;this.initManifest=Nu(this.destroyController.signal,async function*(e,t,r){var i;this.element=e,this.manifestUrlString=te(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:gt.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=Nu(this.destroyController.signal,async function*(){var s,n;let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(o=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:gt.NETWORK,message:"Failed to load manifest",thrown:o})});if(!e)return null;let t;try{t=gg(e!=null?e:"",this.manifestUrlString)}catch(o){let u=(s=$b(e))!=null?s:{id:"ManifestParsing",category:gt.PARSER,message:"Failed to parse MPD manifest",thrown:o};this.error$.next(u)}if(!t)return null;let r=(o,u,l)=>{var c,p,d,h;return!!((p=(c=this.element)==null?void 0:c.canPlayType)!=null&&p.call(c,u)&&((h=(d=it())==null?void 0:d.isTypeSupported)!=null&&h.call(d,`${u}; codecs="${l}"`))||o==="text")};t.dynamic&&this.isLive$.getValue()!==t.dynamic&&(this.isLive$.next(t.dynamic),this.liveDuration$.getValue()!==t.duration&&this.liveDuration$.next(-1*((n=t.duration)!=null?n:0)/1e3),this.liveAvailabilityStartTime$.getValue()!==t.liveAvailabilityStartTime&&this.liveAvailabilityStartTime$.next(t.liveAvailabilityStartTime));let i={text:t.streams.text,video:[],audio:[]};for(let o of["video","audio"]){let l=t.streams[o].filter(({mime:d,codecs:h})=>r(o,d,h)),c=new Set(l.map(({codecs:d})=>d)),p=Lb(c);if(p&&(i[o]=l.filter(({codecs:d})=>d.startsWith(p))),o==="video"){let d=this.tuning.preferHDR,h=i.video.some(b=>b.hdr),f=i.video.some(b=>!b.hdr);Qk.isHDR&&d&&h?i.video=i.video.filter(b=>b.hdr):f&&(i.video=i.video.filter(b=>!b.hdr))}}return{...t,streams:i}}.bind(this));this.initRepresentations=Nu(this.destroyController.signal,async function*(e,t,r){var p;Yt(this.manifest),Yt(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let i=d=>{this.representationSubscription.add(wr(d,"error").pipe(As(h=>{var f;return!!((f=this.element)!=null&&f.played.length)})).subscribe(h=>{this.error$.next({id:"VideoSource",category:gt.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:h})}))};this.source=this.tuning.useManagedMediaSource?pb():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 d=document.createElement("source");i(d),d.type="application/x-mpegurl",d.src=r.url,this.element.appendChild(d)}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((d,h)=>[...d,...h.representations],[]);if(this.videoBufferManager=new Gi("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],Lg(t)){let d=this.manifest.streams.audio.reduce((h,f)=>[...h,...f.representations],[]);this.audioBufferManager=new Gi("audio",this.source,d,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(Fu(1e3).subscribe(d=>{var h;if((h=this.element)!=null&&h.paused){let f=Ko(this.manifestUrlString,2);this.manifestUrlString=te(this.manifestUrlString,f+1e3,2)}})),this.representationSubscription.add(kr(...Cg.filter(d=>d!=="waiting").map(d=>wr(this.element,d))).pipe(qu(d=>this.element?et(this.element.buffered,this.element.currentTime*1e3):0),Rg(),As(d=>!!d),Yk(d=>{var h;(h=this.stallWatchdogSubscription)==null||h.unsubscribe(),this.timeInWaiting=0})).subscribe(this.bufferLength$)),this.isLive$.getValue()){this.representationSubscription.add(this.isActiveLowLatency$.pipe(Rg()).subscribe(h=>_u(this.element,1))),this.representationSubscription.add(Ps({bufferLength:this.bufferLength$,isActiveLowLatency:this.isActiveLowLatency$}).pipe(As(({bufferLength:h,isActiveLowLatency:f})=>f&&!!h)).subscribe(({bufferLength:h})=>this.liveEstimatedDelay.next(h))),this.representationSubscription.add(Ps({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,T=h-b,S=1;Math.abs(T)>g&&(S=1+Math.sign(T)*y),_u(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,I;return(I=(v=S.getLiveSegmentsToLoadState(this.manifest))==null?void 0:v.to)!=null?I:y}))-y}this.liveLoadBufferLength$.getValue()!==f&&this.liveLoadBufferLength$.next(f)}));let d=0;this.representationSubscription.add(Ps({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(Wk(1e3)).subscribe(async({liveLoadBufferLength:h,bufferLength:f})=>{if(Yt(this.element),this.isUpdatingLive)return;let b=this.element.playbackRate,g=Ko(this.manifestUrlString,2),y=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,T=Math.min(y,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*b),S=this.tuning.dashCmafLive.normalizedActualBufferOffset*b,v=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*b,I=isFinite(h)?h:f,O=this.isActiveLowLatency$.getValue(),C=y<=this.tuning.live.activeLiveDelay&&g===0;this.isActiveLowLatency$.next(O&&C);let D="none";if(O?D="active_low_latency":this.tuning.dashCmafLive.lowLatency.isActive&&C?(this.isActiveLowLatency$.next(!0),this.bufferManagers.forEach(F=>F.proceedLowLatencyLive()),D="active_low_latency"):g!==0&&I<T?D="live_forward_buffering":I<T+v&&(D="live_with_target_offset"),isFinite(h)&&(d=h>d?h:d),D==="live_forward_buffering"||D==="live_with_target_offset"){let F=d-(T+S),R=this.normolizeLiveOffset(Math.trunc(g+F/b)),L=Math.abs(R-g),A;!h||L<=this.tuning.dashCmafLive.offsetCalculationError?A=g:R>0&&L>this.tuning.dashCmafLive.offsetCalculationError?A=R:A=0,this.manifestUrlString=te(this.manifestUrlString,A,2)}D!=="none"&&D!=="active_low_latency"&&(d=0,this.updateLive())}))}let u=kr(...this.bufferManagers.map(d=>d.fullyBuffered$)).pipe(qu(()=>this.bufferManagers.every(d=>d.fullyBuffered$.getValue()))),l=kr(...this.bufferManagers.map(d=>d.onLastSegment$)).pipe(qu(()=>this.bufferManagers.some(d=>d.onLastSegment$.getValue())));this.representationSubscription.add(kr(this.forceEnded$,Ps({allBuffersFull:u,someBufferEnded:l}).pipe(As(({allBuffersFull:d,someBufferEnded:h})=>d&&h))).subscribe(()=>{var d;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(h=>!h.updating))try{(d=this.source)==null||d.endOfStream()}catch(h){this.error$.next({id:"EndOfStream",category:gt.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:h})}})),this.representationSubscription.add(kr(...this.bufferManagers.map(d=>d.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(d=>{var h;return(h=this.source)==null?void 0:h.addEventListener("sourceopen",d)}));let c=[(p=this.manifest.duration)!=null?p:0,...[...this.manifest.streams.audio,...this.manifest.streams.video].flatMap(d=>d.representations).flatMap(d=>{var h;return(h=d.duration)!=null?h:0})];this.source.duration=Math.max(...c)/1e3,this.audioBufferManager&&Lg(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState("representations_ready")}.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=Fu(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),i=>{this.error$.next({id:"GapWatchdog",category:gt.WTF,message:"Error handling gaps",thrown:i})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.fetcher=new Ts({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode}),this.liveEstimatedDelay=Gt.getLiveEstimatedDelaySmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.delayEstimator})}async seekLive(e){var r,i,s,n;Yt(this.element);let t=this.normolizeLiveOffset(e);this.isActiveLowLatency$.next(this.tuning.dashCmafLive.lowLatency.isActive&&t===0),this.liveLastSeekOffset=t,this.manifestUrlString=te(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(){Yt(this.element),this.state$.setState("running"),this.subscription.add(kr(...Cg.map(e=>wr(this.element,e)),wr(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:gt.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(wr(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(wr(this.element,"waiting").subscribe(()=>{var t;this.element&&this.element.readyState===2&&!this.element.seeking&&Ti(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{var r,i;if(this.element){if(this.timeInWaiting+=1e3,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);else{let s=this.element.currentTime*1e3;(r=this.videoBufferManager)==null||r.maintain(s),(i=this.audioBufferManager)==null||i.maintain(s)}}};(t=this.stallWatchdogSubscription)==null||t.unsubscribe(),this.stallWatchdogSubscription=Fu(1e3).subscribe(e,r=>{this.error$.next({id:"StallWatchdogCallback",category:gt.FATAL,message:"Can't restore DASH after stall.",thrown:r})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t,r=!1){let i={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return i==null?void 0:i.switchTo(t,r)}seek(e,t){var i,s,n,o,u;Yt(this.element),Yt(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),Ti(this.element.buffered,r)||(this.videoBufferManager.abort(),(o=this.audioBufferManager)==null||o.abort()),this.videoBufferManager.maintain(r),(u=this.audioBufferManager)==null||u.maintain(r),this.element.currentTime=r/1e3}stop(){var e,t,r;(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}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;this.isJumpGapAfterSeekLive&&!this.isActiveLowLatency$.getValue()&&this.element.currentTime>e.to&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let t=this.element.currentTime*1e3,r=[],i=this.element.readyState===1?this.tuning.endGapTolerance:0;for(let s of this.bufferManagers)for(let n of s.gaps)s.playingRepresentation$.getValue()===n.representation&&n.from-i<=t&&n.to+i>t&&(this.element.duration*1e3-n.to<this.tuning.endGapTolerance?r.push(1/0):r.push(n.to));if(r.length){let s=Math.max(...r)+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,s===1/0?this.forceEnded$.next():this.element.currentTime=s/1e3}}};var ks=class{constructor(e,t){this.fov=e,this.orientation=t}};var Rs=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 Dg=`attribute vec2 a_vertex;
|
|
33
|
+
[best track] ${C==null?void 0:C.quality}
|
|
34
|
+
[selected track] ${A==null?void 0:A.quality}
|
|
35
|
+
`});let F=A&&l&&l.history[A.id]&&jm()-l.history[A.id]<=r.trackCooldown&&(!l.last||A.id!==l.last.id);if(A!=null&&A.id&&l&&!F&&l.recordSelection(A),F&&(l!=null&&l.last)){let k=l.last;return l==null||l.recordSwitch(k),p({message:`
|
|
36
|
+
[last selected] ${k==null?void 0:k.quality}
|
|
37
|
+
`}),k}return l==null||l.recordSwitch(A),A},ft=Kw;var X=a=>new URL(a).hostname;import{assertNever as Km,assertNonNullable as Jm,combine as bA,debounce as gA,ErrorCategory as Xm,filter as Zm,filterChanged as SA,isNonNullable as du,map as as,merge as eb,observableFrom as vA,once as yA,Subscription as TA,ValueSubject as pu,videoQualityToHeight as IA,videoSizeToQuality as EA}from"@vkontakte/videoplayer-shared";var Gm=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"))},pe=async a=>{let e=a.muted;try{await a.play()}catch(t){if(!Gm(t))return!1;if(e)return console.warn(t),!1;a.muted=!0;try{await a.play()}catch(r){return Gm(r)&&(a.muted=!1,console.warn(r)),!1}}return!0};import{isNonNullable as ts,isNullable as Zw,assertNonNullable as pi}from"@vkontakte/videoplayer-shared";import{isNonNullable as Ym,assertNonNullable as es,now as Jw}from"@vkontakte/videoplayer-shared";function Z(){return Jw()}function ou(a){return Z()-a}function uu(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 Wm(a,e,t){let r=(...i)=>{t.apply(null,i),a.removeEventListener(e,r)};a.addEventListener(e,r)}function br(a,e,t,r){let i=window.XMLHttpRequest,s,n,o,u=!1,l=0,c,p,d=!1,h="arraybuffer",f=7e3,b=2e3,g=()=>{if(u)return;es(c);let w=ou(c),q;if(w<b){q=b-w,setTimeout(g,q);return}b*=2,b>f&&(b=f),n&&n.abort(),n=new i,D()},v=w=>(s=w,L),T=w=>(p=w,L),S=()=>(h="json",L),y=()=>{if(!u){if(--l>=0){g(),r&&r();return}u=!0,p&&p(),t&&t()}},I=w=>(d=w,L),D=()=>{c=Z(),n=new i,n.open("get",a);let w=0,q,K=0,k=()=>(es(c),Math.max(c,Math.max(q||0,K||0)));if(s&&n.addEventListener("progress",x=>{let V=Z();s.updateChunk&&x.loaded>w&&(s.updateChunk(k(),x.loaded-w),w=x.loaded,q=V)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>y())),n.addEventListener("load",()=>{if(u)return;es(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?y():(p&&p(),e(n.response))}else y()}),n.addEventListener("error",()=>{y()}),d){let x=()=>{es(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(K=Z(),n.removeEventListener("readystatechange",x))};n.addEventListener("readystatechange",x)}return n.responseType=h,n.send(),L},L={withBitrateReporting:v,withParallel:I,withJSONResponse:S,withRetryCount:w=>(l=w,L),withRetryInterval:(w,q)=>(Ym(w)&&(b=w),Ym(q)&&(f=q),L),withTimeout:w=>(o=w,L),withFinally:T,send:D,abort:()=>{n&&(n.abort(),n=void 0),u=!0,p&&p()}};return L}var ci=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 di=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=br(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 rs=1e4,lu=3;var eA=6e4,tA=10,rA=1,iA=500,hi=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 ci(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=uu(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=uu(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||ts(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=()=>{Wm(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 di(lu,rs,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,p=()=>{let y=s&&(!c||c===this.rep);return y||t("Not running!"),y},d=(y,I,D)=>{u&&u.abort(),u=br(this.urlResolver.resolve(y,!1),I,D,()=>this._retryCallback()).withTimeout(rs).withBitrateReporting(this.bitrateSwitcher).withRetryCount(lu).withFinally(()=>{u=null}).send()},h=(y,I,D)=>{pi(this.filesFetcher),o==null||o.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(y,!1),I,D,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},f=y=>{let I=r.playbackRate;r.playbackRate!==y&&(t(`Playback rate switch: ${I}=>${y}`),r.playbackRate=y)},b=y=>{this.lowLatency=y,t(`lowLatency changed to ${y}`),g()},g=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)f(1);else{let y=this._getBufferSizeSec();if(this.bufferStates.length<5){f(1);return}let D=Z()-1e4,C=0;for(let F=0;F<this.bufferStates.length;F++){let R=this.bufferStates[F];y=Math.min(y,R.buf),R.ts<D&&C++}this.bufferStates.splice(0,C),t(`update playback rate; minBuffer=${y} drop=${C} jitter=${this.sourceJitter}`);let A=y-rA;this.sourceJitter>=0?A-=this.sourceJitter/2:this.sourceJitter-=1,A>3?f(1.15):A>1?f(1.1):A>.3?f(1.05):f(1)}},v=y=>{let I,D=()=>I&&I.start?I.start.length:0,C=x=>I.start[x]/1e3,A=x=>I.dur[x]/1e3,F=x=>I.fragIndex+x,R=(x,V)=>({chunkIdx:F(x),startTS:C(x),dur:A(x),discontinuity:V}),L=()=>{let x=0;if(I&&I.dur){let V=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,U=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,j=V;this.sourceJitter>1&&(j+=this.sourceJitter-1);let z=I.dur.length-1;for(;z>=0&&(j-=I.dur[z],!(j<=0));--z);x=Math.min(z,I.dur.length-1-U),x=Math.max(x,0)}return R(x,!0)},w=x=>{let V=D();if(!(V<=0)){if(ts(x)){for(let U=0;U<V;U++)if(C(U)>x)return R(U)}return L()}},q=x=>{let V=D(),U=x?x.chunkIdx+1:0,j=U-I.fragIndex;if(!(V<=0)){if(!x||j<0||j-V>tA)return t(`Resync: offset=${j} bChunks=${V} chunk=`+JSON.stringify(x)),L();if(!(j>=V))return R(U-I.fragIndex,!1)}},K=(x,V,U)=>{l&&l.abort(),l=br(this.urlResolver.resolve(x,!0,this.lowLatency),V,U,()=>this._retryCallback()).withTimeout(rs).withRetryCount(lu).withFinally(()=>{l=null}).withJSONResponse().send()};return{seek:(x,V)=>{K(y,U=>{if(!p())return;I=U;let j=!!I.lowLatency;j!==this.lowLatency&&b(j);let z=0;for(let _=0;_<I.dur.length;++_)z+=I.dur[_];z>0&&(pi(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(z/I.dur.length)),i({name:"index",zeroTime:I.zeroTime,shiftDuration:I.shiftDuration}),this.sourceJitter=I.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,I.jitter/1e3)):1,x(w(V))},()=>this._handleNetworkError())},nextChunk:q}},T=()=>{s=!1,o&&o.abort(),u&&u.abort(),l&&l.abort(),pi(this.filesFetcher),this.filesFetcher.abortAll()};return c={start:y=>{let{videoElement:I,logger:D}=this.params,C=v(e.jidxUrl),A,F,R,L,w=0,q,K,k,x=()=>{q&&(clearTimeout(q),q=void 0);let O=Math.max(iA,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),ae=w+O,me=Z(),Te=Math.min(1e4,ae-me);w=me;let at=()=>{l||p()&&C.seek(()=>{p()&&(w=Z(),V(),x())})};Te>0?q=window.setTimeout(()=>{this.paused?x():at()},Te):at()},V=()=>{let O;for(;O=C.nextChunk(L);)L=O,Gt(O);let ae=C.nextChunk(R);if(ae){if(R&&ae.discontinuity){D("Detected discontinuity; restarting playback"),this.paused?x():(T(),this._initPlayerWith(e));return}_(ae)}else x()},U=(O,ae)=>{if(!p()||!this.sourceBuffer)return;let me,Te,at,Yt=st=>{window.setTimeout(()=>{p()&&U(O,ae)},st)};if(this.sourceBuffer.updating)D("Source buffer is updating; delaying appendBuffer"),Yt(100);else{let st=Z(),vt=I.currentTime;!this.paused&&I.buffered.length>1&&K===vt&&st-k>500&&(D("Stall suspected; trying to fix"),this._fixupStall()),K!==vt&&(K=vt,k=st);let Wt=this._getBufferSizeSec();if(Wt>30)D(`Buffered ${Wt} seconds; delaying appendBuffer`),Yt(2e3);else try{this.sourceBuffer.appendBuffer(O),this.videoPlayStarted?(this.bufferStates.push({ts:st,buf:Wt}),g(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),ae&&ae()}catch(Lr){if(Lr.name==="QuotaExceededError")D("QuotaExceededError; delaying appendBuffer"),at=this.sourceBuffer.buffered.length,at!==0&&(me=this.sourceBuffer.buffered.start(0),Te=vt,Te-me>4&&this.sourceBuffer.remove(me,Te-3)),Yt(1e3);else throw Lr}}},j=()=>{F&&A&&(D([`Appending chunk, sz=${F.byteLength}:`,JSON.stringify(R)]),U(F,function(){F=null,V()}))},z=O=>e.fragUrlTemplate.replace("%%id%%",O.chunkIdx),_=O=>{p()&&h(z(O),(ae,me)=>{if(p()){if(me/=1e3,F=ae,R=O,n=O.startTS,me){let Te=Math.min(10,O.dur/me);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*Te:Te}j()}},()=>this._handleNetworkError())},Gt=O=>{p()&&(pi(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(z(O),!1)))},it=O=>{p()&&(e.cachedHeader=O,U(O,()=>{A=!0,j()}))};s=!0,C.seek(O=>{if(p()){if(w=Z(),!O){x();return}L=O,!Zw(y)||O.startTS>y?_(O):(R=O,V())}},y),e.cachedHeader?it(e.cachedHeader):d(e.headerUrl,it,()=>this._handleNetworkError())},stop:T,getTimestampSec:()=>n},c}_switchToQuality(e){let{logger:t,playerCallback:r}=this.params,i;e.bitrate!==this.bitrate&&(this.rep&&(i=this.rep.getTimestampSec(),ts(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,pi(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(i),r({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return ts(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,r=p=>{if(!this.autoQuality)return;let d,h,f;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&p<this.bitrate&&(h=this._getBufferSizeSec(),f=p/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(p)}`);return}d=this._selectQuality(p),d?this._switchToQuality(d):e(`Could not find quality by bitrate ${p}`)},s={updateChunk:(d,h)=>{let f=Z();if(this.chunkRateEstimator.addInterval(d,f,h)){let g=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:h,duration:f-d,speed:g}),!0}},get:()=>{let d=this.chunkRateEstimator.getBitRate();return d?d*.85:0}},n=-1/0,o,u=!0,l=()=>{let p=s.get();if(p&&o&&this.autoQuality){if(u&&p>o&&ou(n)<3e4)return;r(p)}u=this.autoQuality};return{updateChunk:(p,d)=>{let h=s.updateChunk(p,d);return h&&l(),h},notifySwitch:p=>{let d=Z();p<o&&(n=d),o=p}}}_fetchManifest(e,t,r){this.manifestRequest=br(this.urlResolver.resolve(e,!0),t,r,()=>this._retryCallback()).withJSONResponse().withTimeout(rs).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;pe(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))},eA))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};import{debounce as aA,filter as Qm,fromEvent as sA,interval as nA,isHigher as oA,isInvariantQuality as uA,isLower as lA,merge as cA,Subject as zm,Subscription as dA}from"@vkontakte/videoplayer-shared";var cu=class{constructor(){this.onDroopedVideoFramesLimit$=new zm;this.subscription=new dA;this.playing=!1;this.tracks=[];this.forceChecker$=new zm;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&&!uA(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&&oA(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(sA(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=nA(this.droppedFramesChecker.checkTime).pipe(Qm(()=>this.playing),Qm(()=>{let i=!!this.isForceCheckCounter;return i&&(this.isForceCheckCounter-=1),!i})),t=this.forceChecker$.pipe(aA(this.droppedFramesChecker.checkTime)),r=cA(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])=>lA(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}},is=cu;import{map as pA,Observable as hA}from"@vkontakte/videoplayer-shared";import{fromEvent as fA}from"@vkontakte/videoplayer-shared";var fi=()=>{var a;return!!((a=window.documentPictureInPicture)!=null&&a.window)||!!document.pictureInPictureElement};var mA=(a,e)=>new hA(t=>{if(!window.IntersectionObserver)return;let r={root:null},i=new IntersectionObserver((n,o)=>{n.forEach(u=>t.next(u.isIntersecting||fi()))},{...r,...e});i.observe(a);let s=fA(document,"visibilitychange").pipe(pA(n=>!document.hidden||fi())).subscribe(n=>t.next(n));return()=>{i.unobserve(a),s.unsubscribe}}),ke=mA;var xA=["paused","playing","ready"],PA=["paused","playing","ready"],mi=class{constructor(e){this.subscription=new TA;this.videoState=new $("stopped");this.representations$=new pu([]);this.textTracksManager=new we;this.droppedFramesManager=new is;this.maxSeekBackTime$=new pu(1/0);this.zeroTime$=new pu(void 0);this.liveOffset=new ze;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:Xm.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=pt(u.name))!=null?r:EA(u.video),p=u.bitrate/1e3,d={...u.video};if(!c)continue;let h={id:l,quality:c,bitrate:p,size:d};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),du(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(PA.includes(e)&&(n||o)){this.prepare();return}if((i==null?void 0:i.to)!=="paused"&&s.state==="requested"&&xA.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 Km(e)}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=i=>{e.output.error$.next({id:"DashLiveProvider",category:Xm.WTF,message:"DashLiveProvider internal logic error",thrown:i})};eb(this.videoState.stateChangeStarted$.pipe(as(i=>({transition:i,type:"start"}))),this.videoState.stateChangeEnded$.pipe(as(i=>({transition:i,type:"end"})))).subscribe(({transition:i,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(i)}`})}),this.video=ue(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=de(this.video);this.subscription.add(this.representations$.pipe(as(i=>i.map(({track:s})=>s)),Zm(i=>!!i.length),yA()).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(SA(),as(i=>-i/1e3)).subscribe(this.params.output.duration$)).add(bA({zeroTime:this.zeroTime$.pipe(Zm(du)),position:r.timeUpdate$}).subscribe(({zeroTime:i,position:s})=>this.params.output.liveTime$.next(i+s*1e3),t)).add(Ue(this.video,this.params.desiredState.isLooped,t)).add(ce(this.video,this.params.desiredState.volume,r.volumeState$,t)).add(r.volumeState$.subscribe(this.params.output.volume$,t)).add(Pe(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(ke(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:i}})=>{let s=i&&IA(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 Km(i.to)}},t)).add(eb(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,vA(["init"])).pipe(gA(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),le(this.video)}createLiveDashPlayer(){let e=new hi({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,p,d,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=(d=(p=this.params.desiredState.autoVideoTrackSwitching.getTransition())==null?void 0:p.to)!=null?d:this.params.desiredState.autoVideoTrackSwitching.getState(),i=!r&&du(t)?t:ft(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;Jm(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;Jm(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 tb=mi;var Je=(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 Qk,assertNonNullable as zk,debounce as Kk,ErrorCategory as Fu,filter as kg,filterChanged as qu,fromEvent as Jk,isLowerOrEqual as Rg,isNonNullable as Xk,isInvariantQuality as Zk,map as Lg,merge as Rs,observableFrom as eR,observeElementSize as tR,once as $g,Subscription as rR,ValueSubject as iR}from"@vkontakte/videoplayer-shared";var ss=class{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,r){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:r})}removeEventListener(e,t){if(!(e in this.listeners))return;let r=this.listeners[e];for(let i=0,s=r.length;i<s;i++)if(r[i].callback===t){r.splice(i,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;let r=this.listeners[e.type].slice();for(let i=0,s=r.length;i<s;i++){let n=r[i];try{n.callback.call(this,e)}catch(o){Promise.resolve().then(()=>{throw o})}n.options&&n.options.once&&this.removeEventListener(e.type,n.callback)}return!e.defaultPrevented}},gr=class extends ss{constructor(){super(),this.listeners||ss.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 gr,writable:!0,configurable:!0})}abort(e){let t;try{t=new Event("abort")}catch(i){typeof document!="undefined"?document.createEvent?(t=document.createEvent("Event"),t.initEvent("abort",!1,!1)):(t=document.createEventObject(),t.type="abort"):t={type:"abort",bubbles:!1,cancelable:!1}}let r=e;if(r===void 0)if(typeof document=="undefined")r=new Error("This operation was aborted"),r.name="AbortError";else try{r=new DOMException("signal is aborted without reason")}catch(i){r=new Error("This operation was aborted"),r.name="AbortError"}this.signal.reason=r,this.signal.dispatchEvent(t)}toString(){return"[object AbortController]"}};typeof Symbol!="undefined"&&Symbol.toStringTag&&(bi.prototype[Symbol.toStringTag]="AbortController",gr.prototype[Symbol.toStringTag]="AbortSignal");function ns(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 hu(a){typeof a=="function"&&(a={fetch:a});let{fetch:e,Request:t=e.Request,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:i=!1}=a;if(!ns({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 p;c&&c.signal&&(p=c.signal,delete c.signal);let d=new t(l,c);return p&&Object.defineProperty(d,"signal",{writable:!1,enumerable:!1,configurable:!0,value:p}),d},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 p;try{p=new DOMException("Aborted","AbortError")}catch(h){p=new Error("Aborted"),p.name="AbortError"}if(c.aborted)return Promise.reject(p);let d=new Promise((h,f)=>{c.addEventListener("abort",()=>f(p),{once:!0})});return l&&l.signal&&delete l.signal,Promise.race([d,n(u,l)])}return n(u,l)},Request:s}}var gi=ns({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),rb=gi?hu({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,Xe=gi?rb.fetch:window.fetch,aO=gi?rb.Request:window.Request,Ze=gi?bi:window.AbortController,sO=gi?gr:window.AbortSignal;var mb=Fe(ui(),1);var et=()=>window.ManagedMediaSource||window.MediaSource,os=()=>{var a,e;return!!(window.ManagedMediaSource&&((e=(a=window.ManagedSourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},ib=()=>{var a,e;return!!(window.MediaSource&&window.MediaStreamTrack&&((e=(a=window.SourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},ab=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;import{assertNever as bs,clientChecker as ms}from"@vkontakte/videoplayer-shared";var Re=document.createElement("video"),kA='video/mp4; codecs="avc1.42000a,mp4a.40.2"',RA='video/mp4; codecs="hev1.1.6.L93.B0"',bb='video/webm; codecs="vp09.00.10.08"',gb='video/webm; codecs="av01.0.00M.08"',LA='audio/mp4; codecs="mp4a.40.2"',$A='audio/webm; codecs="opus"',sb,nb,Ct={mms:os(),mse:ib(),hls:!!((sb=Re.canPlayType)!=null&&sb.call(Re,"application/x-mpegurl")||(nb=Re.canPlayType)!=null&&nb.call(Re,"vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},ob,ub,he={mp4:!!((ob=Re.canPlayType)!=null&&ob.call(Re,"video/mp4")),webm:!!((ub=Re.canPlayType)!=null&&ub.call(Re,"video/webm")),cmaf:!0},ls,lb,cs,cb,ds,db,ps,pb,hs,hb,fs,fb,fe={h264:!!((lb=(ls=et())==null?void 0:ls.isTypeSupported)!=null&&lb.call(ls,kA)),h265:!!((cb=(cs=et())==null?void 0:cs.isTypeSupported)!=null&&cb.call(cs,RA)),vp9:!!((db=(ds=et())==null?void 0:ds.isTypeSupported)!=null&&db.call(ds,bb)),av1:!!((pb=(ps=et())==null?void 0:ps.isTypeSupported)!=null&&pb.call(ps,gb)),aac:!!((hb=(hs=et())==null?void 0:hs.isTypeSupported)!=null&&hb.call(hs,LA)),opus:!!((fb=(fs=et())==null?void 0:fs.isTypeSupported)!=null&&fb.call(fs,$A))},Sr=(fe.h264||fe.h265)&&fe.aac,Dt,MA=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:gb}}),window.navigator.mediaCapabilities.decodingInfo({...a,video:{...a.video,contentType:bb}})]);Dt={DASH_WEBM_AV1:e,DASH_WEBM:t}};try{MA()}catch(a){console.error(a)}var vr=Ct.hls&&he.mp4,Sb=()=>Object.keys(fe).filter(a=>fe[a]),vb=(a,e=!1,t=!1)=>{let r=Ct.mse||Ct.mms&&t;return a.filter(i=>{switch(i){case"DASH_SEP":return r&&he.mp4&&Sr;case"DASH_WEBM":return r&&he.webm&&fe.vp9&&fe.opus;case"DASH_WEBM_AV1":return r&&he.webm&&fe.av1&&fe.opus;case"DASH_STREAMS":return r&&(he.mp4&&Sr||he.webm&&(fe.vp9||fe.av1)&&(fe.opus||fe.aac));case"DASH_LIVE":return Ct.mse&&he.mp4&&Sr;case"DASH_LIVE_CMAF":return r&&he.mp4&&Sr&&he.cmaf;case"DASH_ONDEMAND":return r&&he.mp4&&Sr;case"HLS":case"HLS_ONDEMAND":return vr||e&&Ct.mse&&he.mp4&&Sr;case"HLS_LIVE":case"HLS_LIVE_CMAF":return vr;case"MPEG":return he.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return Ct.webrtc&&Ct.ws&&fe.h264&&(he.mp4||he.webm);default:return bs(i)}})},us=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 Dt?Dt[t].smooth?[t,e]:Dt[e].smooth?[e,t]:[t,e]:[e,t];case"power_efficient":return Dt?Dt[t].powerEfficient?[t,e]:Dt[e].powerEfficient?[e,t]:[t,e]:[e,t];default:bs(a)}return[e,t]},yb=({webmCodec:a,androidPreferredFormat:e,preferMultiStream:t})=>{let r=[...t?["DASH_STREAMS"]:[],...us(a),"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]],i=[...t?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]];if(ms.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",...us(a),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...us(a),"MPEG",...i,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...us(a),...i,"HLS","HLS_ONDEMAND"];default:bs(e)}return vr?[...r,"HLS","HLS_ONDEMAND","MPEG"]:[...r,"HLS","HLS_ONDEMAND","MPEG"]},Tb=({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=ms.isMac&&ms.isSafari;if(ms.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:bs(a)}else vr&&!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"]},fu=a=>a?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],Ib=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,mb.default)(e.split("."),0);if(t==="opus"||t==="vp09"||t==="av01")return t}return a.values().next().value.split(".").at(0)}};import{ErrorCategory as Si}from"@vkontakte/videoplayer-shared";var Eb=a=>{if(!a)return{id:"EmptyResponse",category:Si.PARSER,message:"Empty response"};if(a.length<=2&&a.match(/^\d+$/))return{id:`UVError#${a}`,category:Si.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:Si.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:Si.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:Si.PARSER,message:"Response is valid XML, but parser failed"}};var vi=(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 Vu,assertNonNullable as Ht,combine as Es,ErrorCategory as bt,filter as xs,filterChanged as Tg,fromEvent as wr,interval as _u,isNonNullable as Ig,map as Nu,merge as Ar,Subject as Eg,Subscription as xg,tap as qk,throttle as Uk,clientChecker as Hk,ValueSubject as ie}from"@vkontakte/videoplayer-shared";var Pr=Fe(ui(),1);var CA=(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)},DA=a=>window.clearTimeout(a),xb=typeof window.requestIdleCallback!="function"||typeof window.cancelIdleCallback!="function",mu=xb?CA:window.requestIdleCallback,vO=xb?DA:window.cancelIdleCallback;var fg=Fe(Ka(),1);import{assertNever as OA,ErrorCategory as Pb,clientChecker as bu,Subject as wb}from"@vkontakte/videoplayer-shared";var BA=16,Ab=!1;try{Ab=bu.isSafari&&!!bu.macVersion&&bu.macVersion<=BA}catch(a){console.error(a)}var gu=class{constructor(e){this.bufferFull$=new wb;this.error$=new wb;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:Pb.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;Ab&&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:Pb.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:OA(t)}}},kb=gu;var Su=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 xr,assertNonNullable as je,ErrorCategory as Ft,fromEvent as $u,getExponentialDelay as Mu,isNonNullable as hg,isNullable as Ve,once as Ck,Subject as Dk,Subscription as Ok,ValueSubject as Ui}from"@vkontakte/videoplayer-shared";var N=class{constructor(e,t){this.cursor=0;this.source=e,this.boxParser=t,this.children=[];let r=this.readUint32();this.type=this.readString(4),this.size32=r<=e.buffer.byteLength-e.byteOffset?r:NaN;let i=this.size32?this.size32-8:void 0,s=e.byteOffset+this.cursor;this.size64=0,this.usertype=0,this.content=new DataView(e.buffer,s,i),this.children=this.parseChildrenBoxes()}get id(){return this.type}get size(){return this.size32}parseChildrenBoxes(){return[]}scanForBoxes(e){return this.boxParser.parse(e)}readString(e,t="ascii"){let i=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,i}readUint8(){let e=this.source.getUint8(this.cursor);return this.cursor+=1,e}readUint16(){let e=this.source.getUint16(this.cursor);return this.cursor+=2,e}readUint32(){let e=this.source.getUint32(this.cursor);return this.cursor+=4,e}readUint64(){let e=this.source.getBigInt64(this.cursor);return this.cursor+=8,e}};var yr=class extends N{};var yi=class extends N{};var Ti=class extends N{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 Ii=class extends N{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Ei=class extends N{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var xi=class extends N{constructor(e,t){super(e,t),this.data=this.content}};var W=class extends N{constructor(e,t){super(e,t);let r=this.readUint32();this.version=r>>>24,this.flags=r&16777215}};var Ot=class extends W{get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e,t){super(e,t),this.segments=[],this.referenceId=this.readUint32(),this.timescale=this.readUint32(),this.earliestPresentationTime32=this.readUint32(),this.firstOffset32=this.readUint32(),this.earliestPresentationTime64=0,this.firstOffset64=0,this.referenceCount=this.readUint32()&65535;for(let r=0;r<this.referenceCount;r++){let i=this.readUint32(),s=i>>>31,n=i<<1>>>1,o=this.readUint32();i=this.readUint32();let u=i>>>28,l=i<<3>>>3;this.segments.push({referenceType:s,referencedSize:n,subsegmentDuration:o,SAPType:u,SAPDeltaTime:l})}}};var Pi=class extends N{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var wi=class extends N{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Ai=class extends W{constructor(e,t){switch(super(e,t),this.readUint8()){case 0:this.stereoMode=0;break;case 1:this.stereoMode=1;break;case 2:this.stereoMode=2;break;case 3:this.stereoMode=3;break;case 4:this.stereoMode=4;break}this.cursor+=1}};var ki=class extends W{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var Ri=class extends W{constructor(e,t){super(e,t),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}};var Li=class extends N{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var $i=class extends W{constructor(e,t){super(e,t),this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.trackId=this.readUint32(),this.cursor+=4,this.duration=this.readUint32(),this.cursor+=8,this.layer=this.readUint16(),this.alternateGroup=this.readUint16(),this.cursor+=2,this.cursor+=2,this.matrix=[[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()]],this.width=this.readUint32(),this.height=this.readUint32()}};var Mi=class extends N{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Ci=class extends N{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Di=class extends W{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var Oi=class extends N{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Bi=class extends W{constructor(e,t){super(e,t),this.trackId=this.readUint32(),this.flags&1&&(this.baseDataOffset=this.readUint64()),this.flags&2&&(this.sampleDescriptionIndex=this.readUint32()),this.flags&8&&(this.defaultSampleDuration=this.readUint32()),this.flags&16&&(this.defaultSampleSize=this.readUint32()),this.flags&32&&(this.defaultSampleFlags=this.readUint32())}};var Vi=class extends W{constructor(t,r){super(t,r);this.baseMediaDecodeTime32=0;this.baseMediaDecodeTime64=BigInt(0);this.version===1?this.baseMediaDecodeTime64=this.readUint64():this.baseMediaDecodeTime32=this.readUint32()}get baseMediaDecodeTime(){return this.version===1?this.baseMediaDecodeTime64:this.baseMediaDecodeTime32}};var _i=class extends W{constructor(t,r){super(t,r);this.sampleDuration=[];this.sampleSize=[];this.sampleFlags=[];this.sampleCompositionTimeOffset=[];this.optionalFields=0;this.sampleCount=this.readUint32(),this.flags&1&&(this.dataOffset=this.readUint32()),this.flags&4&&(this.firstSampleFlags=this.readUint32());for(let i=0;i<this.sampleCount;i++)this.flags&256&&this.sampleDuration.push(this.readUint32()),this.flags&512&&this.sampleSize.push(this.readUint32()),this.flags&1024&&this.sampleFlags.push(this.readUint32()),this.flags&2048&&this.sampleCompositionTimeOffset.push(this.readUint32())}};var _A={ftyp:Ti,moov:Ii,moof:Ei,mdat:xi,sidx:Ot,trak:Pi,mdia:Li,mfhd:Di,tkhd:$i,traf:Oi,tfhd:Bi,tfdt:Vi,trun:_i,minf:Mi,sv3d:wi,st3d:Ai,prhd:ki,proj:Ci,equi:Ri,uuid:yi,unknown:yr},Bt=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=_A[e];return r?new r(t,new a):new yr(t,new a)}};var Tr=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 FA=new TextDecoder("ascii"),qA=a=>FA.decode(new DataView(a.buffer,a.byteOffset+4,4))==="ftyp",UA=a=>{let e=new Ot(a,new Bt),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})},HA=(a,e)=>{let r=new Bt().parse(a),i=new Tr(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,p=u.source.byteOffset-o.source.byteOffset+u.size;return new DataView(a.buffer,l,p)},jA=(a,e)=>{let r=new Bt().parse(a),s=new Tr(r).findAll("traf"),n=s[s.length-1].children.find(p=>p.type==="tfhd"),o=s[s.length-1].children.find(p=>p.type==="tfdt"),u=s[s.length-1].children.find(p=>p.type==="trun"),l=0;return u.sampleDuration.length?l=u.sampleDuration.reduce((p,d)=>p+d,0):l=n.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+l)/e*1e3},GA=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 Bt().parse(a),i=new Tr(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},Rb={validateData:qA,parseInit:GA,getIndexRange:()=>{},parseSegments:UA,parseFeedableSegmentChunk:HA,getSegmentEndTime:jA};import{assertNonNullable as yu,isNonNullable as Cb,isNullable as WA}from"@vkontakte/videoplayer-shared";import{assertNever as YA}from"@vkontakte/videoplayer-shared";var Lb={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"}},$b=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=Ni(a,t),i=r in Lb,s=i?Lb[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=Ni(u),p=l*2**((o-1)*8)+c,d=t+o,h;return d+p>a.byteLength?h=new DataView(a.buffer,a.byteOffset+d):h=new DataView(a.buffer,a.byteOffset+d,p),{tag:i?r:"0x"+r.toString(16).toUpperCase(),type:s,tagHeaderSize:d,tagSize:d+p,value:h,valueSize:p}},Ni=(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},Be=(a,e)=>{switch(e){case"int":return a.getInt8(0);case"uint":return Ni(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:YA(e)}},Vt=(a,e)=>{let t=0;for(;t<a.byteLength;){let r=new DataView(a.buffer,a.byteOffset+t),i=$b(r);if(!e(i))return;i.type==="master"&&Vt(i.value,e),t=i.value.byteOffset-a.byteOffset+i.valueSize}},Mb=a=>{if(a.getUint32(0)!==440786851)return!1;let e,t,r,i=$b(a);return Vt(i.value,({tag:s,type:n,value:o})=>(s===17143?e=Be(o,n):s===17026?t=Be(o,n):s===17029&&(r=Be(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(r===void 0||r<=2)};var Db=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],QA=[231,22612,22743,167,171,163,160,175],zA=a=>{let e,t,r,i,s=!1,n=!1,o=!1,u,l,c=!1,p=0;return Vt(a,({tag:d,type:h,value:f,valueSize:b})=>{if(d===21419){let g=Be(f,h);l=Ni(g)}else d!==21420&&(l=void 0);return d===408125543?(e=f.byteOffset,t=f.byteOffset+b):d===357149030?s=!0:d===290298740?n=!0:d===2807729?r=Be(f,h):d===17545?i=Be(f,h):d===21420&&l===475249515?u=Be(f,h):d===374648427?Vt(f,({tag:g,type:v,value:T})=>g===30321?(c=Be(T,v)===1,!1):!0):s&&n&&Db.includes(d)&&(o=!0),!o}),yu(e,"Failed to parse webm Segment start"),yu(t,"Failed to parse webm Segment end"),yu(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:p,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},KA=a=>{if(WA(a.cuesSeekPosition))return;let e=a.segmentStart+a.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},JA=(a,e)=>{let t=!1,r=!1,i=o=>Cb(o.time)&&Cb(o.position),s=[],n;return Vt(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=Be(l,u));break;case 183:break;case 241:n&&(n.position=Be(l,u));break;default:t&&Db.includes(o)&&(r=!0)}return!(t&&r)}),n&&i(n)&&s.push(n),s.map((o,u)=>{let{time:l,position:c}=o,p=s[u+1];return{status:"none",time:{from:l,to:p?p.time:e.segmentDuration},byte:{from:e.segmentStart+c,to:p?e.segmentStart+p.position-1:e.segmentEnd-1}}})},XA=a=>{let e=0,t=!1;try{Vt(a,r=>r.tag===524531317?r.tagSize<=a.byteLength?(e=r.tagSize,!1):(e+=r.tagHeaderSize,!0):QA.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},Ob={validateData:Mb,parseInit:zA,getIndexRange:KA,parseSegments:JA,parseFeedableSegmentChunk:XA};var Ir=a=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(a);if(e){let[,t,r]=e;if(t==="audio"||t==="video")switch(r){case"webm":return Ob;case"mp4":return Rb}}throw new ReferenceError(`Unsupported mime type ${a}`)};var Au=Fe(ig(),1);var wu=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 sg,isNullable as ng}from"@vkontakte/videoplayer-shared";var ag=a=>{if(a.includes("/")){let e=a.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(a)};var og=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},_t=(a,e)=>{let t=a;t=(0,Au.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,Au.default)(t,n,(o,u)=>ng(s)?o:ng(u)?s:s.padStart(parseInt(u,10),"0"))}return t},lg=(a,e)=>{var y,I,D,C,A,F,R,L,w,q,K,k,x,V,U,j,z,_,Gt,it,O,ae,me,Te,at,Yt,st,vt,Wt,Lr,rl,il,al,sl,nl,ol,ul,ll,cl,dl,pl,hl,fl,ml,bl,gl,Sl,vl,yl,Tl;let r=new DOMParser().parseFromString(a,"application/xml"),i={video:[],audio:[],text:[]},s=r.children[0],n=s.getElementsByTagName("Period")[0],o=(D=(I=(y=s.querySelector("BaseURL"))==null?void 0:y.textContent)==null?void 0:I.trim())!=null?D:"",u=n.children,l=s.getAttribute("type")==="dynamic",c=s.getAttribute("availabilityStartTime"),p=c?new Date(c).getTime():void 0,d,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)d=og(h);else if(f){let se=og(f);sg(se)&&(d=se)}else g&&(d=parseInt(g,10));let v=0,T=(A=(C=s.getAttribute("profiles"))==null?void 0:C.split(","))!=null?A:[];for(let se of u){let yS=(F=se.getAttribute("id"))!=null?F:"id"+(v++).toString(10),$r=(R=se.getAttribute("mimeType"))!=null?R:"",Gs=(L=se.getAttribute("codecs"))!=null?L:"",Ys=(w=se.getAttribute("contentType"))!=null?w:$r==null?void 0:$r.split("/")[0],TS=(K=(q=se.getAttribute("profiles"))==null?void 0:q.split(","))!=null?K:[],IS=(k=se.getAttribute("lang"))!=null?k:void 0,ES=(U=(V=(x=se.querySelector("Label"))==null?void 0:x.textContent)==null?void 0:V.trim())!=null?U:void 0,xS=se.querySelectorAll("Representation"),PS=se.querySelector("SegmentTemplate"),wS=(z=(j=se.querySelector("Role"))==null?void 0:j.getAttribute("value"))!=null?z:void 0,Mr=Ys,J={id:yS,language:IS,isDefault:wS==="main",label:ES,codecs:Gs,hdr:Mr==="video"&&wu(Gs),mime:$r,representations:[]};for(let Q of xS){let AS=(_=Q.getAttribute("lang"))!=null?_:void 0,kS=(Gt=Q.getAttribute("label"))!=null?Gt:void 0,RS=(ae=(O=(it=Q.querySelector("BaseURL"))==null?void 0:it.textContent)==null?void 0:O.trim())!=null?ae:"",Ws=new URL(RS||o,e).toString(),Qt=(me=Q.getAttribute("mimeType"))!=null?me:$r,ua=(at=(Te=Q.getAttribute("codecs"))!=null?Te:Gs)!=null?at:"",Qs;if(Ys==="text"){let yt=Q.getAttribute("id")||"",zs=yt.includes("_auto");Qs={id:yt,isAuto:zs,kind:"text",url:Ws}}else{let yt=(st=(Yt=Q.getAttribute("contentType"))!=null?Yt:Qt==null?void 0:Qt.split("/")[0])!=null?st:Ys,zs=(Wt=(vt=se.getAttribute("profiles"))==null?void 0:vt.split(","))!=null?Wt:[],LS=parseInt((Lr=Q.getAttribute("width"))!=null?Lr:"",10),Il=parseInt((rl=Q.getAttribute("height"))!=null?rl:"",10),El=parseInt((il=Q.getAttribute("bandwidth"))!=null?il:"",10)/1e3,xl=(al=Q.getAttribute("frameRate"))!=null?al:"",$S=(sl=Q.getAttribute("quality"))!=null?sl:void 0,MS=xl?ag(xl):void 0,CS=(nl=Q.getAttribute("id"))!=null?nl:"id"+(v++).toString(10),DS=yt==="video"?`${Il}p`:yt==="audio"?`${El}Kbps`:ua,OS=`${CS}@${DS}`,BS=[...T,...TS,...zs],Ks,VS=Q.querySelector("SegmentBase"),Tt=(ol=Q.querySelector("SegmentTemplate"))!=null?ol:PS;if(VS){let It=(ll=(ul=Q.querySelector("SegmentBase Initialization"))==null?void 0:ul.getAttribute("range"))!=null?ll:"",[Et,Xs]=It.split("-").map(zt=>parseInt(zt,10)),nt={from:Et,to:Xs},Cr=(cl=Q.querySelector("SegmentBase"))==null?void 0:cl.getAttribute("indexRange"),[Zs,la]=Cr?Cr.split("-").map(zt=>parseInt(zt,10)):[],Dr=Cr?{from:Zs,to:la}:void 0;Ks={type:"byteRange",url:Ws,initRange:nt,indexRange:Dr}}else if(Tt){let It={representationId:(dl=Q.getAttribute("id"))!=null?dl:void 0,bandwidth:(pl=Q.getAttribute("bandwidth"))!=null?pl:void 0},Et=parseInt((hl=Tt.getAttribute("timescale"))!=null?hl:"",10),Xs=(fl=Tt.getAttribute("initialization"))!=null?fl:"",nt=Tt.getAttribute("media"),Cr=(bl=parseInt((ml=Tt.getAttribute("startNumber"))!=null?ml:"",10))!=null?bl:1,Zs=_t(Xs,It);if(!nt)throw new ReferenceError("No media attribute in SegmentTemplate");let la=(gl=Tt.querySelectorAll("SegmentTimeline S"))!=null?gl:[],Dr=[],zt=0,en="",tn=0;if(la.length){let ca=Cr,$e=0;for(let Kt of la){let Ne=parseInt((Sl=Kt.getAttribute("d"))!=null?Sl:"",10),xt=parseInt((vl=Kt.getAttribute("r"))!=null?vl:"",10)||0,da=parseInt((yl=Kt.getAttribute("t"))!=null?yl:"",10);$e=Number.isFinite(da)?da:$e;let rn=Ne/Et*1e3,an=$e/Et*1e3;for(let pa=0;pa<xt+1;pa++){let NS=_t(nt,{...It,segmentNumber:ca.toString(10),segmentTime:($e+pa*Ne).toString(10)}),Pl=(an!=null?an:0)+pa*rn,FS=Pl+rn;ca++,Dr.push({time:{from:Pl,to:FS},url:NS})}$e+=(xt+1)*Ne,zt+=(xt+1)*rn}tn=$e/Et*1e3,en=_t(nt,{...It,segmentNumber:ca.toString(10),segmentTime:$e.toString(10)})}else if(sg(d)){let $e=parseInt((Tl=Tt.getAttribute("duration"))!=null?Tl:"",10)/Et*1e3,Kt=Math.ceil(d/$e),Ne=0;for(let xt=1;xt<Kt;xt++){let da=_t(nt,{...It,segmentNumber:xt.toString(10),segmentTime:Ne.toString(10)});Dr.push({time:{from:Ne,to:Ne+$e},url:da}),Ne+=$e}tn=Ne,en=_t(nt,{...It,segmentNumber:Kt.toString(10),segmentTime:Ne.toString(10)})}let _S={time:{from:tn,to:1/0},url:en};Ks={type:"template",baseUrl:Ws,segmentTemplateUrl:nt,initUrl:Zs,totalSegmentsDurationMs:zt,segments:Dr,nextSegmentBeyondManifest:_S,timescale:Et}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!yt||!Qt)continue;let Js={video:"video",audio:"audio",text:"text"}[yt];if(!Js)continue;Mr||(Mr=Js),Qs={id:OS,kind:Js,segmentReference:Ks,profiles:BS,duration:d,bitrate:El,mime:Qt,codecs:ua,width:LS,height:Il,fps:MS,quality:$S}}J.language||(J.language=AS),J.label||(J.label=kS),J.mime||(J.mime=Qt),J.codecs||(J.codecs=ua),J.hdr||(J.hdr=Mr==="video"&&wu(ua)),J.representations.push(Qs)}Mr&&i[Mr].push(J)}return{dynamic:l,liveAvailabilityStartTime:p,duration:d,streams:i}};var Fi=Fe(ui(),1);import{videoSizeToQuality as Mk}from"@vkontakte/videoplayer-shared";var cg=({id:a,width:e,height:t,bitrate:r,fps:i,quality:s})=>{var o;let n=(o=s?pt(s):void 0)!=null?o:Mk({width:e,height:t});return n&&{id:a,quality:n,bitrate:r,size:{width:e,height:t},fps:i}},dg=({id:a,bitrate:e})=>({id:a,bitrate:e}),gs=(a,e,t)=>{var i;let r=e.indexOf(a);return(i=(0,Fi.default)(t,Math.round(t.length*r/e.length)))!=null?i:(0,Fi.default)(t,-1)},pg=({language:a,label:e},{id:t,url:r,isAuto:i})=>({id:t,url:r,isAuto:i,type:"internal",language:a,label:e}),Ru=({id:a,language:e,label:t,codecs:r,isDefault:i})=>({id:a,language:e,label:t,codec:(0,Fi.default)(r.split("."),0),isDefault:i}),Lu=({id:a,language:e,label:t,hdr:r,codecs:i})=>({id:a,language:e,hdr:r,label:t,codec:(0,Fi.default)(i.split("."),0)}),Ss=a=>"url"in a,Nt=a=>a.type==="template",qi=a=>a instanceof DOMException&&(a.name==="AbortError"||a.code===20);var Hi=class{constructor(e,t,r,{fetcher:i,tuning:s,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentSegmentLength$=new Ui(0);this.onLastSegment$=new Ui(!1);this.fullyBuffered$=new Ui(!1);this.playingRepresentation$=new Ui(void 0);this.playingRepresentationInit$=new Ui(void 0);this.error$=new Dk;this.gaps=[];this.subscription=new Ok;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new Ze;this.destroyAbortController=new Ze;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=xr(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);je(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new kb(this.sourceBuffer),this.subscription.add($u(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let o,u=this.mediaSource.readyState;u!=="open"&&(o={id:`SegmentEjection_source_${u}`,category:Ft.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o!=null||(o={id:"SegmentEjection",category:Ft.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),this.error$.next(o)})),this.subscription.add($u(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:Ft.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,Su(this.sourceBuffer.buffered)*.8);if(this.bufferLimit=u,this.tuning.useNewPruneBufferStrategy){let l=Je(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);je(r,"No init buffer for starting representation"),je(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=xr(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);je(r,`No such representation ${e}`);let i=this.segments.get(e),s=this.initData.get(e);if(Ve(s)||Ve(i)?yield this.loadInit(r,"high",!1):s instanceof Promise&&(yield s),i=this.segments.get(e),je(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();hg(n)&&(this.isLive||(i.forEach(o=>o.status="none"),this.tuning.useNewPruneBufferStrategy&&(this.bufferLimit=1/0),this.pruneBuffer(n,1/0,!0)),this.maintain(n)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}}.bind(this));this.seekLive=xr(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 p=t.find(f=>f.id===c);p&&this.representations.set(c,p);let d=this.representations.get(c);if(!d||!Nt(d.segmentReference))return;let h=this.getActualLiveStartingSegments(d.segmentReference);this.segments.set(d.id,h)}let r=(l=this.switchingToRepresentationId)!=null?l:this.downloadingRepresentationId,i=this.representations.get(r);je(i);let s=this.segments.get(r);je(s,"No segments for starting representation");let n=this.initData.get(r);if(je(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.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 Ze,this.abortBuffer()}maintain(e=this.getCurrentPosition()){var l,c;if(Ve(e)||Ve(this.downloadingRepresentationId)||Ve(this.playingRepresentationId)||Ve(this.sourceBuffer)||!Ve(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),r=this.segments.get(this.downloadingRepresentationId);if(je(t,`No such representation ${this.downloadingRepresentationId}`),!r)return;let i=r.find(p=>e>=p.time.from&&e<p.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 d=Je(this.sourceBuffer.buffered,e),h=i?i.time.to+100:-1/0;i&&i.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&d>=i.time.to-e+100&&(s=h)}if(isFinite(this.bufferLimit)&&Su(this.sourceBuffer.buffered)>=this.bufferLimit){let p=Je(this.sourceBuffer.buffered,e),d=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,p<d);return}let o=[];if(!this.activeSegments.size&&(o=this.selectForwardBufferSegments(r,t.segmentReference.type,s),o.length)){let p="auto";if(this.tuning.dash.useFetchPriorityHints&&i)if(o.includes(i))p="high";else{let d=(0,Pr.default)(o,0);d&&d.time.from-i.time.to>=this.forwardBufferTarget/2&&(p="low")}this.loadSegments(o,t,p)}(!this.preloadOnly&&!this.allInitsLoaded&&i&&i.status==="fed"&&!o.length&&Je(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let u=(0,Pr.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;hg(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||!Nt(o.segmentReference))return;let u=o.segmentReference.segments.map(d=>({...d,status:"none",size:void 0})),l=(i=this.segments.get(o.id))!=null?i:[],c=(n=(s=(0,Pr.default)(l,-1))==null?void 0:s.time.to)!=null?n:0,p=u==null?void 0:u.findIndex(d=>Math.floor(c)>=Math.floor(d.time.from)&&Math.floor(c)<=Math.floor(d.time.to));if(p===-1){this.liveUpdateSegmentIndex=0;let d=this.getActualLiveStartingSegments(o.segmentReference);this.segments.set(o.id,d)}else{let d=u.slice(p+1);this.segments.set(o.id,[...l,...d])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;je(e);let t=this.segments.get(e);if(t!=null&&t.length){let r=t[t.length-1];this.updateLowLatencyLiveIfNeeded(r)}}updateLowLatencyLiveIfNeeded(e){var t;for(let r of this.representations.values()){let i=r.segmentReference;if(!Nt(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=_t(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:p,time:{from:d,to:h}},f)=>{let b=d<=r&&h>=r,g=d>r||b||f===0&&r===0,v=Math.min(this.forwardBufferTarget,this.bufferLimit),T=this.preloadOnly&&d<=r+v||h<=r+v;return(p==="none"||p==="partially_ejected"&&g&&T&&this.sourceBuffer&&!vi(this.sourceBuffer.buffered,r))&&g&&T});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 p=i;p<s.length&&(n<=l||o<=c);p++){let d=s[p];if(n+=d.byte.to+1-d.byte.from,o+=d.time.to+1-d.time.from,d.status==="none"||d.status==="partially_ejected")u.push(d);else break}return u}async loadSegments(e,t,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:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(await xr(o,async function*(){let c=Mu(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(p=>setTimeout(p,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 p=new DataView(c);if(!isFinite(i.segment.time.to)){let d=t.segmentReference.timescale,h=Ir(t.mime);i.segment.time.to=h.getSegmentEndTime(p,d)}u&&i.feedingBytes&&l?await Promise.all(l):await this.sourceBufferTaskQueue.append(p,o),i.segment.status="downloaded",this.onSegmentFullyAppended(i,t.id),this.failedDownloads=0}catch(c){this.abortActiveSegments([e]),qi(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 xr(n,async function*(){let u=Mu(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),$u(window,"online").pipe(Ck()).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),qi(u)||this.failedDownloads++}}prepareByteRangeFetchSegmentParams(e,t){if(Nt(t.segmentReference))throw new Error("Representation is not byte range type");let r=t.segmentReference.url,i={from:(0,Pr.default)(e,0).byte.from,to:(0,Pr.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:Ft.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!Nt(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 p=this.onSomeTemplateDataLoaded({dataView:l,loaded:c,signal:s,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(p)}catch(p){this.error$.next({id:"SegmentFeeding",category:Ft.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:p})}}: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=Ir(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:p}=c,d=u==="byteRange",h=d?p.byte.to-p.byte.from+1:l;if(c.representationId!==t||!(!d||p.byte.from>=r&&p.byte.to<r+e.byteLength))continue;if(s.aborted){n();continue}let b=d?p.byte.from-r:0,g=d?p.byte.to-r:e.byteLength,v=b<i,T=g<=i;if(p.status==="downloading"&&v&&T){p.status="downloaded";let S=new DataView(e.buffer,e.byteOffset+b,h);this.sourceBufferTaskQueue.append(S,s).then(y=>y&&!s.aborted?this.onSegmentFullyAppended(c,t):n())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&v&&(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),y=c.loadedBytes===h?S:Ir(o.mime).parseFeedableSegmentChunk(S);y!=null&&y.byteLength&&(p.status="partially_fed",c.feedingBytes+=y.byteLength,this.sourceBufferTaskQueue.append(y,s).then(I=>{if(s.aborted)n();else if(I)c.fedBytes+=y.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,p=l.byte.to-r,d=p-c+1,h=c<i,f=p<=i;if(h){if(l.status==="downloading"&&f){l.status="downloaded";let b=new DataView(e.buffer,e.byteOffset+c,d);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(d,i-c),u.loadedBytes>u.feedingBytes)){let b=new DataView(e.buffer,e.byteOffset+c+u.feedingBytes,u.loadedBytes-u.feedingBytes),g=u.loadedBytes===d?b:Ir(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===d&&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",Ss(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"&&s.time.from===e.segment.time.from&&s.time.to===e.segment.time.to&&(s.status="none");this.updateLowLatencyLiveIfNeeded(e.segment),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment])}abortSegment(e){(this.tuning.useDashAbortPartiallyFedSegment?e.status==="partially_fed"||e.status==="partially_ejected":e.status==="partially_ejected")?(this.sourceBufferTaskQueue.remove(e.time.from,e.time.to).then(()=>e.status="none"),e.status="partially_ejected"):e.status="none";for(let r of this.activeSegments.values())if(r.segment===e){this.activeSegments.delete(r);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=mu(()=>(0,fg.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?xr(this.destroyAbortController.signal,async function*(){let o=Mu(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,Ir(e.mime),i)).then(async o=>{if(!o)return;let{init:u,dataView:l,segments:c}=o,p=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,p);let d=c;this.isLive&&Nt(e.segmentReference)&&(d=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,d),u&&this.parsedInitData.set(e.id,u)}).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),r&&this.error$.next({id:"LoadInits",category:Ft.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||Ve(e)||this.sourceBuffer.updating)return!1;let i=[],s=0,n=u=>{u.sort((c,p)=>c.from-p.from);let l=[u[0]];for(let c=1;c<u.length;c++){let{from:p,to:d}=u[c],h=l[l.length-1];h.to>=p?h.to=Math.max(h.to,d):l.push(u[c])}return l},o=u=>{var c;if(s>=t)return i;i.push(u.time),i=n(i);let l=Ss(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,p=l.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(c||p)&&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,p=0;for(let d of this.segments.values())for(let h of d)h.status==="none"&&Math.round(h.time.from)<=Math.round(l)&&Math.round(h.time.to)>=Math.round(c)&&p++;if(p===this.segments.size){let d={time:{from:l,to:c},url:"",status:"none"};o(d)}}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||Ve(e)||this.sourceBuffer.updating)return!1;let i=0,s=1/0,n=-1/0,o=!1,u=l=>{var p;s=Math.min(s,l.time.from),n=Math.max(n,l.time.to);let c=Ss(l)?(p=l.size)!=null?p: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,p=this.sourceBuffer.buffered.end(l)*1e3;for(let d of this.segments.values())for(let h of d)if(h.status==="none"&&Math.round(h.time.from)<=Math.round(c)&&Math.round(h.time.to)>=Math.round(p)){s=c,n=p;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 p of c)p.time.from>e+l&&p.status==="fed"&&u(p)}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){this.gapDetectionIdleCallback||(this.gapDetectionIdleCallback=mu(()=>{try{this.detectGaps(e,t)}catch(r){this.error$.next({id:"GapDetection",category:Ft.WTF,message:"detectGaps threw",thrown:r})}finally{this.gapDetectionIdleCallback=null}}))}checkEjectedSegments(){if(Ve(this.sourceBuffer)||Ve(this.playingRepresentationId))return;let e=[];for(let r=0;r<this.sourceBuffer.buffered.length;r++){let i=Math.round(this.sourceBuffer.buffered.start(r)*1e3),s=Math.round(this.sourceBuffer.buffered.end(r)*1e3);e.push({from:i,to:s})}let t=1;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-t&&n<=c.to+t||o>=c.from-t&&o<=c.to+t);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 ji=a=>{let e=new URL(a);return e.searchParams.set("quic","1"),e.toString()};var mg=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 Gi,assertNever as bg,fromEvent as gg,merge as Bk,now as Cu,Subscription as Vk,ValueSubject as Du}from"@vkontakte/videoplayer-shared";var vs=class{constructor({throughputEstimator:e,requestQuic:t,compatibilityMode:r=!1}){this.lastConnectionType$=new Du(void 0);this.lastConnectionReused$=new Du(void 0);this.lastRequestFirstBytes$=new Du(void 0);this.abortAllController=new Ze;this.subscription=new Vk;this.fetchManifest=Gi(this.abortAllController.signal,async function*(e){let t=e;this.requestQuic&&(t=ji(t));let r=yield Xe(t,{signal:this.abortAllController.signal}).catch(Yi);return r?(this.onHeadersReceived(r.headers),r.text()):null}.bind(this));this.fetch=Gi(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 A,F;let l=e,c=new Headers;if(r)switch(t){case 0:{c.append("Range",`bytes=${r.from}-${r.to}`);break}case 1:{let R=new URL(l,location.href);R.searchParams.append("bytes",`${r.from}-${r.to}`),l=R.toString();break}default:bg(t)}this.requestQuic&&(l=ji(l));let p=this.abortAllController.signal,d;if(n){let R=new Ze;if(d=Bk(gg(this.abortAllController.signal,"abort"),gg(n,"abort")).subscribe(()=>{try{R.abort()}catch(L){Yi(L)}}),this.abortAllController.signal.aborted||n.aborted)try{R.abort()}catch(L){Yi(L)}p=R.signal}let h=Cu(),f=yield Xe(l,{priority:s,headers:c,signal:p}).catch(Yi),b=Cu();if(!f)return d==null||d.unsubscribe(),null;if((A=this.throughputEstimator)==null||A.addRawRtt(b-h),!f.ok||!f.body)return d==null||d.unsubscribe(),Promise.reject(new Error(`Fetch error ${f.status}: ${f.statusText}`));if(this.onHeadersReceived(f.headers),!i&&!o)return d==null||d.unsubscribe(),f.arrayBuffer();let[g,v]=f.body.tee(),T=g.getReader();o&&((F=this.throughputEstimator)==null||F.trackStream(v,u));let S=0,y=new Uint8Array(0),I=!1,D=R=>{d==null||d.unsubscribe(),I=!0,Yi(R)},C=Gi(p,async function*({done:R,value:L}){if(S===0&&this.lastRequestFirstBytes$.next(Cu()-h),p.aborted){d==null||d.unsubscribe();return}if(!R&&L){let w=new Uint8Array(y.length+L.length);w.set(y),w.set(L,y.length),y=w,S+=L.byteLength,i==null||i(new DataView(y.buffer),S),yield T==null?void 0:T.read().then(C,D)}}.bind(this));return yield T==null?void 0:T.read().then(C,D),d==null||d.unsubscribe(),I?null:y.buffer}.bind(this));this.fetchByteRangeRepresentation=Gi(this.abortAllController.signal,async function*(e,t,r){var v;if(e.type!=="byteRange")return null;let{from:i,to:s}=e.initRange,n=i,o=s,u=!1,l,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 p=yield this.fetch(e.url,{range:{from:n,to:o},priority:r,measureThroughput:!1});if(!p)return null;let d=new DataView(p,i-n,s-n+1);if(!t.validateData(d))throw new Error("Invalid media file");let h=t.parseInit(d),f=(v=e.indexRange)!=null?v:t.getIndexRange(h);if(!f)throw new ReferenceError("No way to load representation index");let b;if(u)b=new DataView(p,f.from-n,f.to-f.from+1);else{let T=yield this.fetch(e.url,{range:f,priority:r,measureThroughput:!1});if(!T)return null;b=new DataView(T)}let g=t.parseSegments(b,h,f);return{init:h,dataView:new DataView(p),segments:g}}.bind(this));this.fetchTemplateRepresentation=Gi(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=r}onHeadersReceived(e){let{type:t,reused:r}=mg(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:bg(i)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}},Yi=a=>{if(!qi(a))throw a};var qt=(a,e,t)=>t*e+(1-t)*a,Ou=(a,e)=>a.reduce((t,r)=>t+r,0)/e,Sg=(a,e,t,r)=>{let i=0,s=t,n=Ou(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 _k,ValueSubject as vg}from"@vkontakte/videoplayer-shared";var mt=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 vg(e.initial),this.debounced$=new vg(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)&&(_k(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 ys=class extends mt{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=qt(this.slow,e,this.params.emaAlphaSlow),this.fast=qt(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var Ts=class extends mt{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=Ou(this.pastMeasures,this.takenMeasures);this.emaSmoothed=qt(this.emaSmoothed,e,this.params.emaAlpha);let r=Sg(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=r?this.emaSmoothed:t}};var Is=class extends mt{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?qt(this.smoothed,t,this.params.emaAlpha):t}};var Ut=class{static getSmoothedValue(e,t,r){return r.type==="TwoEma"?new ys({initial:e,emaAlphaSlow:r.emaAlphaSlow,emaAlphaFast:r.emaAlphaFast,changeThreshold:r.changeThreshold,fastDirection:t,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"}):new Ts({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 Is({initial:e,label:"liveEdgeDelay",...t})}};var Bu=(a,e)=>{a&&a.playbackRate!==e&&(a.playbackRate=e)};var Pg=["timeupdate","progress","play","seeked","stalled","waiting"];var Ps=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new xg;this.representationSubscription=new xg;this.state$=new $("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 Eg;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 Eg;this.gapWatchdogActive=!1;this.destroyController=new Ze;this.initManifest=Vu(this.destroyController.signal,async function*(e,t,r){var i;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:bt.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=Vu(this.destroyController.signal,async function*(){var s,n;let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(o=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:bt.NETWORK,message:"Failed to load manifest",thrown:o})});if(!e)return null;let t;try{t=lg(e!=null?e:"",this.manifestUrlString)}catch(o){let u=(s=Eb(e))!=null?s:{id:"ManifestParsing",category:bt.PARSER,message:"Failed to parse MPD manifest",thrown:o};this.error$.next(u)}if(!t)return null;let r=(o,u,l)=>{var c,p,d,h;return!!((p=(c=this.element)==null?void 0:c.canPlayType)!=null&&p.call(c,u)&&((h=(d=et())==null?void 0:d.isTypeSupported)!=null&&h.call(d,`${u}; codecs="${l}"`))||o==="text")};t.dynamic&&this.isLive$.getValue()!==t.dynamic&&(this.isLive$.next(t.dynamic),this.liveDuration$.getValue()!==t.duration&&this.liveDuration$.next(-1*((n=t.duration)!=null?n:0)/1e3),this.liveAvailabilityStartTime$.getValue()!==t.liveAvailabilityStartTime&&this.liveAvailabilityStartTime$.next(t.liveAvailabilityStartTime));let i={text:t.streams.text,video:[],audio:[]};for(let o of["video","audio"]){let l=t.streams[o].filter(({mime:d,codecs:h})=>r(o,d,h)),c=new Set(l.map(({codecs:d})=>d)),p=Ib(c);if(p&&(i[o]=l.filter(({codecs:d})=>d.startsWith(p))),o==="video"){let d=this.tuning.preferHDR,h=i.video.some(b=>b.hdr),f=i.video.some(b=>!b.hdr);Hk.isHDR&&d&&h?i.video=i.video.filter(b=>b.hdr):f&&(i.video=i.video.filter(b=>!b.hdr))}}return{...t,streams:i}}.bind(this));this.initRepresentations=Vu(this.destroyController.signal,async function*(e,t,r){var p;Ht(this.manifest),Ht(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let i=d=>{this.representationSubscription.add(wr(d,"error").pipe(xs(h=>{var f;return!!((f=this.element)!=null&&f.played.length)})).subscribe(h=>{this.error$.next({id:"VideoSource",category:bt.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:h})}))};this.source=this.tuning.useManagedMediaSource?ab():new MediaSource;let s=document.createElement("source");if(i(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),this.tuning.useManagedMediaSource&&os())if(r){let d=document.createElement("source");i(d),d.type="application/x-mpegurl",d.src=r.url,this.element.appendChild(d)}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((d,h)=>[...d,...h.representations],[]);if(this.videoBufferManager=new Hi("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],Ig(t)){let d=this.manifest.streams.audio.reduce((h,f)=>[...h,...f.representations],[]);this.audioBufferManager=new Hi("audio",this.source,d,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(_u(1e3).subscribe(d=>{var h;if((h=this.element)!=null&&h.paused){let f=Qo(this.manifestUrlString,2);this.manifestUrlString=ee(this.manifestUrlString,f+1e3,2)}})),this.representationSubscription.add(Ar(...Pg.filter(d=>d!=="waiting").map(d=>wr(this.element,d))).pipe(Nu(d=>this.element?Je(this.element.buffered,this.element.currentTime*1e3):0),Tg(),xs(d=>!!d),qk(d=>{var h;(h=this.stallWatchdogSubscription)==null||h.unsubscribe(),this.timeInWaiting=0})).subscribe(this.bufferLength$)),this.isLive$.getValue()){this.representationSubscription.add(this.isActiveLowLatency$.pipe(Tg()).subscribe(h=>Bu(this.element,1))),this.representationSubscription.add(Es({bufferLength:this.bufferLength$,isActiveLowLatency:this.isActiveLowLatency$}).pipe(xs(({bufferLength:h,isActiveLowLatency:f})=>f&&!!h)).subscribe(({bufferLength:h})=>this.liveEstimatedDelay.next(h))),this.representationSubscription.add(Es({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,v=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,T=h-b,S=1;Math.abs(T)>g&&(S=1+Math.sign(T)*v),Bu(this.element,S)})),this.representationSubscription.add(this.bufferLength$.subscribe(h=>{var b,g;let f=0;if(h){let v=((g=(b=this.element)==null?void 0:b.currentTime)!=null?g:0)*1e3;f=Math.min(...this.bufferManagers.map(S=>{var y,I;return(I=(y=S.getLiveSegmentsToLoadState(this.manifest))==null?void 0:y.to)!=null?I:v}))-v}this.liveLoadBufferLength$.getValue()!==f&&this.liveLoadBufferLength$.next(f)}));let d=0;this.representationSubscription.add(Es({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(Uk(1e3)).subscribe(async({liveLoadBufferLength:h,bufferLength:f})=>{if(Ht(this.element),this.isUpdatingLive)return;let b=this.element.playbackRate,g=Qo(this.manifestUrlString,2),v=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,T=Math.min(v,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*b),S=this.tuning.dashCmafLive.normalizedActualBufferOffset*b,y=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*b,I=isFinite(h)?h:f,D=this.isActiveLowLatency$.getValue(),C=v<=this.tuning.live.activeLiveDelay&&g===0;this.isActiveLowLatency$.next(D&&C);let A="none";if(D?A="active_low_latency":this.tuning.dashCmafLive.lowLatency.isActive&&C?(this.isActiveLowLatency$.next(!0),this.bufferManagers.forEach(F=>F.proceedLowLatencyLive()),A="active_low_latency"):g!==0&&I<T?A="live_forward_buffering":I<T+y&&(A="live_with_target_offset"),isFinite(h)&&(d=h>d?h:d),A==="live_forward_buffering"||A==="live_with_target_offset"){let F=d-(T+S),R=this.normolizeLiveOffset(Math.trunc(g+F/b)),L=Math.abs(R-g),w;!h||L<=this.tuning.dashCmafLive.offsetCalculationError?w=g:R>0&&L>this.tuning.dashCmafLive.offsetCalculationError?w=R:w=0,this.manifestUrlString=ee(this.manifestUrlString,w,2)}A!=="none"&&A!=="active_low_latency"&&(d=0,this.updateLive())}))}let u=Ar(...this.bufferManagers.map(d=>d.fullyBuffered$)).pipe(Nu(()=>this.bufferManagers.every(d=>d.fullyBuffered$.getValue()))),l=Ar(...this.bufferManagers.map(d=>d.onLastSegment$)).pipe(Nu(()=>this.bufferManagers.some(d=>d.onLastSegment$.getValue())));this.representationSubscription.add(Ar(this.forceEnded$,Es({allBuffersFull:u,someBufferEnded:l}).pipe(xs(({allBuffersFull:d,someBufferEnded:h})=>d&&h))).subscribe(()=>{var d;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(h=>!h.updating))try{(d=this.source)==null||d.endOfStream()}catch(h){this.error$.next({id:"EndOfStream",category:bt.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:h})}})),this.representationSubscription.add(Ar(...this.bufferManagers.map(d=>d.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(d=>{var h;return(h=this.source)==null?void 0:h.addEventListener("sourceopen",d)}));let c=[(p=this.manifest.duration)!=null?p:0,...[...this.manifest.streams.audio,...this.manifest.streams.video].flatMap(d=>d.representations).flatMap(d=>{var h;return(h=d.duration)!=null?h:0})];this.source.duration=Math.max(...c)/1e3,this.audioBufferManager&&Ig(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState("representations_ready")}.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=_u(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),i=>{this.error$.next({id:"GapWatchdog",category:bt.WTF,message:"Error handling gaps",thrown:i})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.fetcher=new vs({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode}),this.liveEstimatedDelay=Ut.getLiveEstimatedDelaySmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.delayEstimator})}async seekLive(e){var r,i,s,n;Ht(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(){Ht(this.element),this.state$.setState("running"),this.subscription.add(Ar(...Pg.map(e=>wr(this.element,e)),wr(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:bt.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(wr(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(wr(this.element,"waiting").subscribe(()=>{var t;this.element&&this.element.readyState===2&&!this.element.seeking&&vi(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{var r,i;if(this.element){if(this.timeInWaiting+=1e3,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);else{let s=this.element.currentTime*1e3;(r=this.videoBufferManager)==null||r.maintain(s),(i=this.audioBufferManager)==null||i.maintain(s)}}};(t=this.stallWatchdogSubscription)==null||t.unsubscribe(),this.stallWatchdogSubscription=_u(1e3).subscribe(e,r=>{this.error$.next({id:"StallWatchdogCallback",category:bt.FATAL,message:"Can't restore DASH after stall.",thrown:r})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t,r=!1){let i={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return i==null?void 0:i.switchTo(t,r)}seek(e,t){var i,s,n,o,u;Ht(this.element),Ht(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),vi(this.element.buffered,r)||(this.videoBufferManager.abort(),(o=this.audioBufferManager)==null||o.abort()),this.videoBufferManager.maintain(r),(u=this.audioBufferManager)==null||u.maintain(r),this.element.currentTime=r/1e3}stop(){var e,t,r;(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}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;this.isJumpGapAfterSeekLive&&!this.isActiveLowLatency$.getValue()&&this.element.currentTime>e.to&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let t=this.element.currentTime*1e3,r=[],i=this.element.readyState===1?this.tuning.endGapTolerance:0;for(let s of this.bufferManagers)for(let n of s.gaps)s.playingRepresentation$.getValue()===n.representation&&n.from-i<=t&&n.to+i>t&&(this.element.duration*1e3-n.to<this.tuning.endGapTolerance?r.push(1/0):r.push(n.to));if(r.length){let s=Math.max(...r)+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,s===1/0?this.forceEnded$.next():this.element.currentTime=s/1e3}}};var ws=class{constructor(e,t){this.fov=e,this.orientation=t}};var As=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 wg=`attribute vec2 a_vertex;
|
|
59
38
|
attribute vec2 a_texel;
|
|
60
39
|
|
|
61
40
|
varying vec2 v_texel;
|
|
@@ -66,7 +45,7 @@ void main(void) {
|
|
|
66
45
|
// save texel vector to pass to fragment shader
|
|
67
46
|
v_texel = a_texel;
|
|
68
47
|
}
|
|
69
|
-
`;var
|
|
48
|
+
`;var Ag=`#ifdef GL_ES
|
|
70
49
|
precision highp float;
|
|
71
50
|
precision highp int;
|
|
72
51
|
#else
|
|
@@ -109,5 +88,5 @@ void main(void) {
|
|
|
109
88
|
// sample using new coordinates
|
|
110
89
|
gl_FragColor = texture2D(u_texture, tc);
|
|
111
90
|
}
|
|
112
|
-
`;var Ls=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 Rs(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(Dg,this.gl.VERTEX_SHADER),r=this.createShader(Og,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,p=e-r,d=t+i;return[s,n,o,u,l,c,p,d]}updateTextureMappingBuffer(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([...this.calculateTexturePosition()]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}updateFrameSize(){this.frameWidth=this.sourceVideoElement.videoWidth,this.frameHeight=this.sourceVideoElement.videoHeight}createCanvas(){let e=document.createElement("canvas");return e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e}};var Wt=class{constructor(e){this.subscription=new oR;this.videoState=new $("stopped");this.elementSize$=new uR(void 0);this.textTracksManager=new we;this.droppedFramesManager=new ss;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new di;this.audioTrackSwitchHistory=new di;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 Zk(e)}}};this.init3DScene=e=>{var r,i,s;if(this.scene3D)return;this.scene3D=new Ls(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.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(Z(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new ws({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode}),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params,r=pe(this.video),i=this.constructor.name,s=o=>{e.error$.next({id:i,category:Uu.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(Bg(l=>!!l.length),Ng()).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(Bg(iR),Ng()),e.firstBytesEvent$),s(this.videoState.stateChangeEnded$.pipe(_g(l=>l.to)),this.params.output.playbackState$),this.subscription.add(r.seeked$.subscribe(e.seekedEvent$,i)),this.subscription.add(je(this.video,t.isLooped,i)),this.subscription.add(de(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Ae(this.video,t.playbackRate,r.playbackRateState$,i)),s(nR(this.video),this.elementSize$),s(Re(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,this.textTracksMap=new Map;let c=this.player.getStreams();if(eR(c,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let d=[];for(let h of c.audio){d.push($u(h));let f=[];for(let b of h.representations){let g=vg(b);f.push(g),this.audioTracksMap.set(g,{stream:h,representation:b})}this.audioStreamsMap.set(h,f)}this.params.output.availableAudioStreams$.next(d)}let p=[];for(let d of c.video){p.push(Mu(d));let h=[];for(let f of d.representations){let b=Sg(f);b&&(h.push(b),this.videoTracksMap.set(b,{stream:d,representation:f}))}this.videoStreamsMap.set(d,h)}this.params.output.availableVideoStreams$.next(p);for(let d of c.text)for(let h of d.representations){let f=yg(d,h);this.textTracksMap.set(f,{stream:d,representation:h})}this.params.output.availableVideoTracks$.next(Array.from(this.videoTracksMap.keys())),this.params.output.availableAudioTracks$.next(Array.from(this.audioTracksMap.keys())),this.params.output.isAudioAvailable$.next(!!this.audioTracksMap.size),this.audioTracksMap.size>0&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else l==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},i));let n=l=>e.error$.next({id:"RepresentationSwitch",category:Uu.WTF,message:"Switching representations threw",thrown:l});this.subscription.add($s(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$,rR(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 p=this.selectVideoAudioRepresentations();if(!p)return;let[d,h]=p,f=this.params.desiredState.autoVideoTrackLimits.getTransition();if(f&&this.params.output.autoVideoTrackLimits$.next(f.to),l==="manifest_ready")this.player.initRepresentations(d.id,h==null?void 0:h.id,this.params.sourceHls);else if(this.player.switchRepresentation("video",d.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(Hu()).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[p,{stream:d}]=c,h=this.params.desiredState.videoStream.getTransition();h&&h.to&&h.to.id===d.id&&this.params.desiredState.videoStream.setState(h.to),e.currentVideoTrack$.next(p),e.currentVideoStream$.next(Mu(d))},i)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(Hu()).subscribe(l=>{let c=[...this.audioTracksMap.entries()].find(([,{representation:f}])=>f.id===l);if(!c){e.currentAudioStream$.next(void 0);return}let[p,{stream:d}]=c,h=this.params.desiredState.audioStream.getTransition();h&&h.to&&h.to.id===d.id&&this.params.desiredState.audioStream.setState(h.to),e.currentAudioStream$.next($u(d))},i)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(l=>{var c,p;if(l!=null&&l.is3dVideo&&((c=this.params.tuning.spherical)!=null&&c.enabled))try{this.init3DScene(l),e.is3DVideo$.next(!0)}catch(d){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${d}`})}else this.destroy3DScene(),(p=this.params.tuning.spherical)!=null&&p.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(_g(({to:l})=>l==="ready"),Hu());this.subscription.add($s(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$).subscribe(()=>{let l=t.autoVideoTrackSwitching.getState(),p=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:l?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(p)})),this.subscription.add($s(o,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let u=$s(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,sR(["init"])).pipe(tR(0));this.subscription.add(u.subscribe(this.syncPlayback,i))}selectVideoAudioRepresentations(){var C,D,F,R,L,A,q,k,Q,P,_,U,j,K,Ie,yt,nt,B,J;let{desiredState:e,output:t}=this.params,r=e.autoVideoTrackSwitching.getState(),i=(C=e.videoTrack.getState())==null?void 0:C.id,n=[...this.videoTracksMap.keys()].find(({id:w})=>w===i),o=t.currentVideoTrack$.getValue(),u=((R=(F=e.videoStream.getState())!=null?F:n&&((D=this.videoTracksMap.get(n))==null?void 0:D.stream))!=null?R:this.videoStreamsMap.size===1)?this.videoStreamsMap.keys().next().value:void 0;if(!u)return;let l=[...this.videoStreamsMap.keys()].find(({id:w})=>w===u.id),c=l&&this.videoStreamsMap.get(l);if(!c)return;let p=et(this.video.buffered,this.video.currentTime*1e3),d=r?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,h=Math.min(p/Math.min(d,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),f=(L=e.audioStream.getState())!=null?L:this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0,b=(A=[...this.audioStreamsMap.keys()].find(({id:w})=>w===(f==null?void 0:f.id)))!=null?A:this.audioStreamsMap.keys().next().value,g=0;if(b){if(n&&!r)if(this.params.tuning.useSeparateAudioVideoABR){let w=ts(n,c,(q=this.audioStreamsMap.get(b))!=null?q:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);g=Math.max(g,(k=w==null?void 0:w.bitrate)!=null?k:-1/0)}else{let w=vs(n,c,(Q=this.audioStreamsMap.get(b))!=null?Q:[]);g=Math.max(g,(P=w==null?void 0:w.bitrate)!=null?P:-1/0)}if(o)if(this.params.tuning.useSeparateAudioVideoABR){let w=ts(o,c,(_=this.audioStreamsMap.get(b))!=null?_:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);g=Math.max(g,(U=w==null?void 0:w.bitrate)!=null?U:-1/0)}else{let w=vs(o,c,(j=this.audioStreamsMap.get(b))!=null?j:[]);g=Math.max(g,(K=w==null?void 0:w.bitrate)!=null?K:-1/0)}}let y=mt(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,history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),{backgroundVideoQualityLimit:T}=this.params.tuning.autoTrackSelection;!this.params.output.elementVisible$.getValue()&&r&&(y=(Ie=c.filter(w=>!aR(w.quality)).sort((w,se)=>{var Me,We;return((Me=se.bitrate)!=null?Me:0)-((We=w.bitrate)!=null?We:0)}).filter(w=>Vg(w.quality,y.quality)&&Vg(w.quality,T))[0])!=null?Ie:y);let S=r?y!=null?y:n:n!=null?n:y,v;this.params.tuning.useSeparateAudioVideoABR?v=b&&Xm(S,c,(yt=this.audioStreamsMap.get(b))!=null?yt:[],{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}):v=b&&vs(S,c,(nt=this.audioStreamsMap.get(b))!=null?nt:[]);let I=(B=this.videoTracksMap.get(S))==null?void 0:B.representation,O=v&&((J=this.audioTracksMap.get(v))==null?void 0:J.representation);if(I&&O)return[I,O];if(I&&!O&&this.audioTracksMap.size===0)return[I,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){he(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:Uu.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),ce(this.video)}};var Ki=class extends Wt{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 Fg,interval as lR,map as cR}from"@vkontakte/videoplayer-shared";var Ji=class extends Wt{constructor(e){super(e),this.liveOffset=new Xe}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(Fg({interval:lR(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(Fg({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(cR(({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 Ug=Ue(Xa(),1);import{assertNever as Xi,assertNonNullable as qg,debounce as dR,ErrorCategory as Ms,filter as pR,isNonNullable as hR,isNullable as fR,map as Cs,merge as mR,Observable as bR,observableFrom as gR,Subscription as SR,videoSizeToQuality as vR}from"@vkontakte/videoplayer-shared";var Fe={};var Rr=(a,e)=>new bR(t=>{let r=(i,s)=>t.next(s);return a.on(e,r),()=>a.off(e,r)}),Zi=class{constructor(e){this.subscription=new SR;this.videoState=new $("initializing");this.textTracksManager=new we;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:Xi(e)}break;case"ready":switch(e){case"stopped":this.prepare();break;case"ready":case"playing":case"paused":break;default:Xi(e)}break;case"playing":switch(e){case"playing":break;case"stopped":this.prepare();break;case"ready":case"paused":this.playIfAllowed();break;default:Xi(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:Xi(e)}break;default:Xi(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(Z(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),ce(this.video)}loadHlsJs(){let e=!1,t=i=>{e||this.params.output.error$.next({id:i==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:Ms.NETWORK,message:"Failed to load Hls.js",thrown:i}),e=!0},r=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);(0,Ug.default)(import("hls.js").then(i=>{e||(Fe.Hls=i.default,Fe.Events=i.default.Events,this.init())},t),()=>{window.clearTimeout(r),e=!0})}init(){qg(Fe.Hls,"hls.js not loaded"),this.hls=new Fe.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState("stopped")}subscribe(){qg(Fe.Events,"hls.js not loaded");let{desiredState:e,output:t}=this.params,r=l=>{t.error$.next({id:"HlsJsProvider",category:Ms.WTF,message:"HlsJsProvider internal logic error",thrown:l})},i=pe(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(je(this.video,e.isLooped,r)),this.subscription.add(de(this.video,e.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(Ae(this.video,e.playbackRate,i.playbackRateState$,r)),s(Re(this.video),t.elementVisible$),s(this.videoState.stateChangeEnded$.pipe(Cs(l=>l.to)),this.params.output.playbackState$),this.subscription.add(Rr(this.hls,Fe.Events.ERROR).subscribe(l=>{var c;l.fatal&&t.error$.next({id:["HlsJsFatal",l.type,l.details].join("_"),category:Ms.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(Rr(this.hls,Fe.Events.MANIFEST_PARSED).pipe(Cs(({levels:l})=>l.reduce((c,p)=>{var T,S;let d=p.name||p.height.toString(10),{width:h,height:f}=p,b=(S=ft((T=p.attrs.QUALITY)!=null?T:""))!=null?S:vR({width:h,height:f});if(!b)return c;let g=p.attrs["FRAME-RATE"]?parseFloat(p.attrs["FRAME-RATE"]):void 0,y={id:d.toString(),quality:b,bitrate:p.bitrate/1e3,size:{width:h,height:f},fps:g};return this.trackLevels.set(d,{track:y,level:p}),c.push(y),c},[]))),t.availableVideoTracks$),s(Rr(this.hls,Fe.Events.MANIFEST_PARSED),l=>{if(l.subtitleTracks.length>0){let c=[];for(let p of l.subtitleTracks){let d=p.name,h=p.attrs.URI||"",f=p.lang;c.push({id:d,url:h,language:f,type:"internal"})}e.internalTextTracks.startTransitionTo(c)}}),s(Rr(this.hls,Fe.Events.LEVEL_LOADING).pipe(Cs(({url:l})=>Z(l))),t.hostname$),s(Rr(this.hls,Fe.Events.FRAG_CHANGED),l=>{var d,h,f,b;let{video:c,audio:p}=l.frag.elementaryStreams;t.currentVideoSegmentLength$.next((((d=c==null?void 0:c.endPTS)!=null?d:0)-((h=c==null?void 0:c.startPTS)!=null?h:0))*1e3),t.currentAudioSegmentLength$.next((((f=p==null?void 0:p.endPTS)!=null?f:0)-((b=p==null?void 0:p.startPTS)!=null?b:0))*1e3)}),this.subscription.add(dt(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,l=>{this.hls.nextLevel=l?-1:this.hls.currentLevel,this.hls.loadLevel=l?-1:this.hls.loadLevel},{onError:r}));let n=l=>{var c;return(c=Array.from(this.trackLevels.values()).find(({level:p})=>p===l))==null?void 0:c.track},o=Rr(this.hls,Fe.Events.LEVEL_SWITCHED).pipe(Cs(({level:l})=>n(this.hls.levels[l])));o.pipe(pR(hR)).subscribe(t.currentVideoTrack$,r),this.subscription.add(dt(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel]),l=>{var f;if(fR(l))return;let c=(f=this.trackLevels.get(l.id))==null?void 0:f.level;if(!c)return;let p=this.hls.levels.indexOf(c),d=this.hls.currentLevel,h=this.hls.levels[d];!h||c.bitrate>h.bitrate?this.hls.nextLevel=p:(this.hls.loadLevel=p,this.hls.loadLevel=p)},{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=mR(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,gR(["init"])).pipe(dR(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 he(this.video).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Ms.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 Hg="X-Playback-Duration",ju=async a=>{var i;let e=await tt(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(Hg)?parseInt(e.headers.get(Hg),10):void 0};import{assertNever as PR,combine as AR,debounce as wR,ErrorCategory as Os,filter as kR,filterChanged as RR,isNonNullable as Gg,isNullable as Bs,map as Yg,merge as LR,observableFrom as $R,Subscription as MR,ValueSubject as Wu,VideoQuality as CR}from"@vkontakte/videoplayer-shared";var Yu=Ue(co(),1);import{videoSizeToQuality as yR,getExponentialDelay as TR}from"@vkontakte/videoplayer-shared";var IR=a=>{let e=null;if(a.QUALITY&&(e=ft(a.QUALITY)),!e&&a.RESOLUTION){let[t,r]=a.RESOLUTION.split("x").map(i=>parseInt(i,10));e=yR({width:t,height:r})}return e!=null?e:null},ER=(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 p=(0,Yu.default)(l[1].split(",").map(T=>T.split("="))),d=(s=p.QUALITY)!=null?s:`stream-${p.BANDWIDTH}`,h=IR(p),f;p.BANDWIDTH&&(f=parseInt(p.BANDWIDTH,10)/1e3||void 0),!f&&p["AVERAGE-BANDWIDTH"]&&(f=parseInt(p["AVERAGE-BANDWIDTH"],10)/1e3||void 0);let b=p["FRAME-RATE"]?parseFloat(p["FRAME-RATE"]):void 0,g;if(p.RESOLUTION){let[T,S]=p.RESOLUTION.split("x").map(v=>parseInt(v,10));T&&S&&(g={width:T,height:S})}let y=new URL(t[++o],e).toString();h&&r.push({id:d,quality:h,url:y,bandwidth:f,size:g,fps:b})}if(c){let p=(0,Yu.default)(c[1].split(",").map(b=>b.split("=")).map(([b,g])=>[b,g.replace(/^"|"$/g,"")])),d=(n=p.URI)==null?void 0:n.replace(/playlist$/,"subtitles.vtt"),h=p.LANGUAGE,f=p.NAME;d&&h&&i.push({type:"internal",id:h,label:f,language:h,url:d,isAuto:!1})}}}if(!r.length)throw new Error("Empty manifest");return{qualityManifests:r,textTracks:i}},xR=a=>new Promise(e=>{setTimeout(()=>{e()},a)}),Gu=0,jg=async(a,e=a,t)=>{let i=await(await tt(a)).text();Gu+=1;try{let{qualityManifests:s,textTracks:n}=ER(i,e);return{qualityManifests:s,textTracks:n}}catch(s){if(Gu<=t.manifestRetryMaxCount)return await xR(TR(Gu-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),jg(a,e,t)}return{qualityManifests:[],textTracks:[]}},Ds=jg;var ea=class{constructor(e){this.subscription=new MR;this.videoState=new $("stopped");this.textTracksManager=new we;this.manifests$=new Wu([]);this.liveOffset=new Xe;this.manifestStartTime$=new Wu(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 PR(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:CR.INVARIANT,url:this.params.source.url},Ds(te(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:Os.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),this.manifests$.next([this.masterManifest,...r])},r=>this.params.output.error$.next({id:"ExtractHlsQualities",category:Os.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(Z(this.params.source.url)),this.maxSeekBackTime$=new Wu((t=e.source.maxSeekBackTime)!=null?t:1/0),this.subscribe()}selectManifest(){var u,l,c,p;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,r=e.getState(),i=t.getTransition(),s=(p=(c=(u=i==null?void 0:i.to)==null?void 0:u.id)!=null?c:(l=t.getState())==null?void 0:l.id)!=null?p:"master",n=this.manifests$.getValue();if(!n.length)return;let o=r?"master":s;return r&&!i&&t.startTransitionTo(this.masterManifest),n.find(d=>d.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"HlsLiveProvider",category:Os.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},i=pe(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(de(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Ae(this.video,t.playbackRate,i.playbackRateState$,r)),s(Re(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(RR(),Yg(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&&Gg(l.to)){let p=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let d=this.manifests$.getValue().find(h=>h.id===p);d&&(this.params.output.currentVideoTrack$.next(d),this.params.output.hostname$.next(Z(d.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(AR({startTime:this.manifestStartTime$.pipe(kR(Gg)),currentTime:i.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),r)),this.subscription.add(this.manifests$.pipe(Yg(o=>o.map(({id:u,quality:l,size:c,bandwidth:p,fps:d})=>({id:u,quality:l,size:c,fps:d,bitrate:p})))).subscribe(this.params.output.availableVideoTracks$,r));let n=LR(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,$R(["init"])).pipe(wR(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),ce(this.video)}prepare(){var o,u;let e=this.selectManifest();if(Bs(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[p,d]of[[l,"mq"],[c,"lq"]]){let h=String(parseFloat(p||""));d&&p&&i.searchParams.set(d,h)}}let s=this.params.format==="HLS_LIVE_CMAF"?2:0,n=te(i.toString(),this.liveOffset.getTotalOffset(),s);this.video.setAttribute("src",n),this.video.load(),ju(n).then(l=>{var c;if(!Bs(l))this.maxSeekBackTime$.next(l);else{let p=(c=this.params.source.maxSeekBackTime)!=null?c:this.maxSeekBackTime$.getValue();if(Bs(p)||!isFinite(p))try{tt(n).then(d=>d.text()).then(d=>{var f;let h=(f=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(d))==null?void 0:f[1];if(h){let b=new URL(h,n).toString();ju(b).then(g=>{Bs(g)||this.maxSeekBackTime$.next(g)})}})}catch(d){}}})}playIfAllowed(){he(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:Os.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 DR,debounce as OR,ErrorCategory as Qu,fromEvent as zu,isNonNullable as BR,isNullable as VR,map as Wg,merge as Qg,observableFrom as zg,Subscription as _R,ValueSubject as NR,VideoQuality as FR,clientChecker as qR}from"@vkontakte/videoplayer-shared";var ta=class{constructor(e){this.subscription=new _R;this.videoState=new $("stopped");this.textTracksManager=new we;this.manifests$=new NR([]);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:p}=this.video;this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:p*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 DR(t)}};this.params=e,this.video=le(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:FR.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(Z(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),Ds(te(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:Qu.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){var u,l,c,p;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,r=e.getState(),i=t.getTransition(),s=(p=(c=(u=i==null?void 0:i.to)==null?void 0:u.id)!=null?c:(l=t.getState())==null?void 0:l.id)!=null?p:"master",n=this.manifests$.getValue();if(!n.length)return;let o=r?"master":s;return r&&!i&&t.startTransitionTo(this.masterManifest),n.find(d=>d.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"HlsProvider",category:Qu.WTF,message:"HlsProvider internal logic error",thrown:o})},i=pe(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(Wg(o=>o.to)),this.params.output.playbackState$),this.subscription.add(je(this.video,t.isLooped,r)),this.subscription.add(de(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Ae(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 p;let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&BR(l.to)){let d=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let h=this.manifests$.getValue().find(f=>f.id===d);if(h){this.params.output.currentVideoTrack$.next(h),this.params.output.hostname$.next(Z(h.url));let f=this.params.desiredState.playbackRate.getState(),b=(p=this.params.output.element$.getValue())==null?void 0:p.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(Wg(o=>o.map(({id:u,quality:l,size:c,bandwidth:p,fps:d})=>({id:u,quality:l,size:c,fps:d,bitrate:p})))).subscribe(this.params.output.availableVideoTracks$,r)),!qR.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add(Qg(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=Qg(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,zg(["init"])).pipe(OR(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),ce(this.video)}prepare(){var s,n;let e=this.selectManifest();if(VR(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 p=String(parseFloat(l||""));c&&l&&i.searchParams.set(c,p)}}this.video.setAttribute("src",i.toString()),this.video.load()}playIfAllowed(){he(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:Qu.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};import{assertNever as UR,assertNonNullable as Kg,debounce as HR,ErrorCategory as Jg,isHigher as jR,isHigherOrEqual as GR,isInvariantQuality as Xg,isLowerOrEqual as YR,isNonNullable as WR,merge as QR,observableFrom as zR,Subscription as KR,map as JR}from"@vkontakte/videoplayer-shared";var ra=class{constructor(e){this.subscription=new KR;this.videoState=new $("stopped");this.trackUrls={};this.textTracksManager=new we;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:p}=this.video;this.prepare(),o.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:p*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 UR(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:Jg.WTF,message:"MpegProvider internal logic error",thrown:o})},i=pe(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(JR(o=>o.to)),this.params.output.playbackState$),this.subscription.add(je(this.video,t.isLooped,r)),this.subscription.add(de(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Ae(this.video,t.playbackRate,i.playbackRateState$,r)),s(Re(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&&WR(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(),p=(l=this.params.output.element$.getValue())==null?void 0:l.playbackRate;if(c!==p){let d=this.params.output.element$.getValue();d&&(this.params.desiredState.playbackRate.setState(c),d.playbackRate=c)}}this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.textTracksManager.connect(this.video,t,e);let n=QR(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,zR(["init"])).pipe(HR(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),ce(this.video)}prepare(){var r;let e=(r=this.params.desiredState.videoTrack.getState())==null?void 0:r.id;Kg(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];Kg(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=Yi(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(Z(t))}playIfAllowed(){he(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:Jg.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(p=>!Xg(p.track.quality)&&YR(p.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&&GR(c.quality,u.quality)&&(t=u),!t){let p=Object.values(this.trackUrls).filter(h=>!Xg(h.track.quality)&&jR(h.track.quality,e)),d=p.length;d&&(t=p[d-1].track)}t&&(r=t.quality)}else if(!e){let u=Object.values(this.trackUrls).map(l=>l.track);t=mt(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 tL,merge as tS,observableFrom as rL,Subscription as iL,map as rS,ValueSubject as aL,ErrorCategory as Ju,VideoQuality as sL}from"@vkontakte/videoplayer-shared";import{ErrorCategory as XR}from"@vkontakte/videoplayer-shared";var Zg=["stun:videostun.mycdn.me:80"],ZR=1e3,eL=3,Ku=()=>null,Vs=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=Ku;this.externalStopCallback=Ku;this.externalErrorCallback=Ku;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:Zg}]};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:XR.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),ZR)}normalizeOptions(e={}){let t={stunServerList:Zg,maxRetryNumber:eL,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 $("stopped");this.maxSeekBackTime$=new aL(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 iL,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=le(e.container,e.tuning),this.liveStreamClient=new Vs(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),ce(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,r=n=>{e.error$.next({id:"WebRTCLiveProvider",category:Ju.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};tS(this.videoState.stateChangeStarted$.pipe(rS(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe(rS(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})});let i=pe(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(Re(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(de(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(tS(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,rL(["init"])).pipe(tL(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(Z(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:sL.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:Ju.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){he(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:Ju.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var aa=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 oa,assertNonNullable as St,ErrorCategory as Ns,filter as pL,isNonNullable as uS,isNullable as hL,map as fL,merge as mL,once as bL,Subject as ye,Subscription as lS,ValueSubject as M}from"@vkontakte/videoplayer-shared";import{Observable as nL,map as iS,Subscription as oL,Subject as uL}from"@vkontakte/videoplayer-shared";var aS=a=>new nL(e=>{let t=new oL,r=a.desiredPlaybackState$.stateChangeStarted$.pipe(iS(({from:l,to:c})=>`${l}-${c}`)),i=a.desiredPlaybackState$.stateChangeEnded$,s=a.providerChanged$.pipe(iS(({type:l})=>l!==void 0)),n=new uL,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 sS,Subscription as lL,combine as cL,filter as nS,once as oS}from"@vkontakte/videoplayer-shared";var sa=null,_s=null;function Xu(){return sa||(sa=new(window.AudioContext||window.webkitAudioContext)),_s||(_s=new GainNode(sa,{gain:1}),_s.connect(sa.destination)),{audioCtx:sa,gainNode:_s}}import{clientChecker as dL}from"@vkontakte/videoplayer-shared";var Lr=class Lr{constructor(e,t,r,i,s){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=r;this.volumeMultiplier=i;this.subscriptions=new lL;this.lastAudioContextResumeId=0;!s||!this.isSupported()||i===1||this.subscriptions.add(this.provider$.pipe(nS(n=>!!n.type),oS()).subscribe(({type:n})=>this.subscribe(n)))}subscribe(e){dL.isSafari&&e!=="MPEG"||this.subscriptions.add(cL({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe(nS(({playbackState:t,video:r,volume:{muted:i,volume:s}})=>t==="playing"&&!!r&&!i&&!!s),oS()).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}=Xu(),s=(Math.random()+1)*999999;this.lastAudioContextResumeId=s,r.resume().then(()=>{var n;if(s!==this.lastAudioContextResumeId)throw new Error(`AudioContext.resume() resolved after ${Lr.errorId} destroyed`);i.gain.value=t;try{new MediaElementAudioSourceNode(r,{mediaElement:e}).connect(i)}catch(o){this.volumeMultiplierError$.next({id:Lr.errorId,category:sS.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:Lr.errorId,category:sS.VIDEO_PIPELINE,message:(o=n==null?void 0:n.message)!=null?o:"initAudioContextOnce: AudioContext.resume() exception",thrown:n})})}destroy(){let{gainNode:e}=Xu();e.gain.value=1,this.subscriptions.unsubscribe(),this.lastAudioContextResumeId=0}};Lr.errorId="VolumeMultiplierManager";var na=Lr;var gL={chunkDuration:5e3,maxParallelRequests:5},ua=class{constructor(e){this.current$=new M({type:void 0});this.providerError$=new ye;this.noAvailableProvidersError$=new ye;this.volumeMultiplierError$=new ye;this.providerOutput={position$:new M(0),duration$:new M(1/0),volume$:new M({muted:!1,volume:1}),availableVideoStreams$:new M([]),currentVideoStream$:new M(void 0),availableVideoTracks$:new M([]),currentVideoTrack$:new M(void 0),availableAudioStreams$:new M([]),currentAudioStream$:new M(void 0),availableAudioTracks$:new M([]),currentVideoSegmentLength$:new M(0),currentAudioSegmentLength$:new M(0),isAudioAvailable$:new M(!0),autoVideoTrackLimitingAvailable$:new M(!1),autoVideoTrackLimits$:new M(void 0),currentBuffer$:new M(void 0),isBuffering$:new M(!0),error$:new ye,warning$:new ye,willSeekEvent$:new ye,seekedEvent$:new ye,loopedEvent$:new ye,endedEvent$:new ye,firstBytesEvent$:new ye,loadedMetadataEvent$:new ye,firstFrameEvent$:new ye,canplay$:new ye,isLive$:new M(void 0),isLowLatency$:new M(!1),canChangePlaybackSpeed$:new M(!0),liveTime$:new M(void 0),liveBufferTime$:new M(void 0),availableTextTracks$:new M([]),currentTextTrack$:new M(void 0),hostname$:new M(void 0),httpConnectionType$:new M(void 0),httpConnectionReused$:new M(void 0),inPiP$:new M(!1),inFullscreen$:new M(!1),element$:new M(void 0),elementVisible$:new M(!0),availableSources$:new M(void 0),is3DVideo$:new M(!1),playbackState$:new M("")};this.subscription=new lS;var o;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer");let t=wb([...Rb(this.params.tuning),...kb(this.params.tuning)],this.params.tuning.useHlsJs,this.params.tuning.useManagedMediaSource).filter(u=>uS(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.screenFormatsIterator=new aa(s);let n=[...bu(!0),...bu(!1)];this.chromecastFormatsIterator=new aa(n.filter(u=>uS(e.sources[u]))),this.providerOutput.availableSources$.next(e.sources),this.volumeMultiplierManager=new na(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()}initProvider(){let e=this.chooseDestination(),t=this.chooseFormat(e);if(hL(t)){this.handleNoFormatsError(e);return}let r;try{r=this.createProvider(e,t)}catch(i){this.providerError$.next({id:"ProviderNotConstructed",category:Ns.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.destroyProvider(),this.initProvider()}switchToNextProvider(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"});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}`}),e){case"SCREEN":return this.createScreenProvider(t);case"CHROMECAST":return this.createChromecastProvider(t);default:return oa(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 St(o),new Ki({...n,source:o,sourceHls:u})}case"DASH_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return St(o),new Ji({...n,source:o})}case"HLS":case"HLS_ONDEMAND":{let o=this.applyFailoverHost(t[e]);return St(o),yr||!this.params.tuning.useHlsJs?new ta({...n,source:o}):new Zi({...n,source:o})}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return St(o),new ea({...n,source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case"MPEG":{let o=this.applyFailoverHost(t[e]);return St(o),new ra({...n,source:o})}case"DASH_LIVE":{let o=this.applyFailoverHost(t[e]);return St(o),new lb({...n,source:o,config:{...gL,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case"WEB_RTC_LIVE":{let o=this.applyFailoverHost(t[e]);return St(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 oa(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 St(o),new ni({connection:o,meta:s,container:r,source:t,format:e,desiredState:i,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?"CHROMECAST":"SCREEN"}chooseFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case"CHROMECAST":return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return oa(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return oa(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 oa(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,cS.default)(Object.entries(e).map(([i,s])=>[i,r(s)]))}initProviderErrorHandling(){let e=new lS,t=!1,r=0;return e.add(mL(this.providerOutput.error$,aS({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(fL(i=>({id:`ProviderHangup:${i}`,category:Ns.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(pL(({to:s})=>s==="playing"),bL()).subscribe(()=>t=!0);e.add(i)})),e.add(this.providerError$.subscribe(i=>{let s=this.current$.getValue().destination;if(s==="CHROMECAST")this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider("SCREEN"),()=>this.params.dependencies.chromecastInitializer.disconnect());else{let n=i.category===Ns.NETWORK,o=i.category===Ns.FATAL,u=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),l=r<this.params.tuning.providerErrorLimit&&!o;u&&!o&&(n&&t||!l)?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):l?(r++,this.reinitProvider()):this.switchToNextProvider(s!=null?s:"SCREEN")}})),e}};import{fromEvent as Fs,once as SL,combine as vL,Subscription as dS,ValueSubject as Zu,map as yL,filter as TL,isNonNullable as qs,now as Te,safeStorage as el}from"@vkontakte/videoplayer-shared";var IL=5e3,pS="one_video_throughput",hS="one_video_rtt",at=window.navigator.connection,fS=()=>{let a=at==null?void 0:at.downlink;if(qs(a)&&a!==10)return a*1e3},mS=()=>{let a=at==null?void 0:at.rtt;if(qs(a)&&a!==3e3)return a},bS=(a,e,t)=>{let r=t*8,i=r/a;return r/(i+e)},tl=class a{constructor(e){this.subscription=new dS;this.concurrentDownloads=new Set;var i,s;this.tuningConfig=e;let t=a.load(pS)||(e.useBrowserEstimation?fS():void 0)||IL,r=(s=(i=a.load(hS))!=null?i:e.useBrowserEstimation?mS():void 0)!=null?s:0;if(this.throughput$=new Zu(t),this.rtt$=new Zu(r),this.rttAdjustedThroughput$=new Zu(bS(t,r,e.rttPenaltyRequestSize)),this.throughput=Gt.getSmoothedValue(t,-1,e),this.rtt=Gt.getSmoothedValue(r,1,e),e.useBrowserEstimation){let n=()=>{let u=fS();u&&this.throughput.next(u);let l=mS();qs(l)&&this.rtt.next(l)};at&&"onchange"in at&&this.subscription.add(Fs(at,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{el.set(pS,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{el.set(hS,n.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(vL({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(yL(({throughput:n,rtt:o})=>bS(n,o,e.rttPenaltyRequestSize)),TL(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=Te(),i=new dS;switch(this.subscription.add(i),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:i.add(Fs(e,"progress").pipe(SL()).subscribe(s=>{t=s.loaded,r=Te()}));break;case 1:case 0:i.add(Fs(e,"loadstart").subscribe(()=>{t=0,r=Te()}));break}i.add(Fs(e,"loadend").subscribe(s=>{if(e.status===200){let n=s.loaded,o=Te(),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=Te(),n=0,o=Te(),u=c=>{this.concurrentDownloads.delete(e),r.releaseLock(),e.cancel(`Throughput Estimator error: ${c}`).catch(()=>{})},l=async({done:c,value:p})=>{if(c)!t&&this.addRawSpeed(i,Te()-s,1),this.concurrentDownloads.delete(e);else if(p){if(t){let d=Te();if(d-o>this.tuningConfig.lowLatency.continuesByteSequenceInterval||d-s>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let f=o-s;f&&this.addRawSpeed(n,f,1,t),n=p.byteLength,s=Te()}else n+=p.byteLength;o=Te()}else i+=p.byteLength,n+=p.byteLength,n>=this.tuningConfig.streamMinSampleSize&&Te()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,Te()-o,this.concurrentDownloads.size),n=0,o=Te());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=el.get(e);if(qs(t))return(r=parseInt(t,10))!=null?r:void 0}},gS=tl;import{fillWithDefault as EL,VideoQuality as SS}from"@vkontakte/videoplayer-shared";var vS={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:SS.Q_4320P,activeVideoAreaThreshold:.1},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:SS.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,requestQuick:!1,useHlsJs:!0,useDashAbortPartiallyFedSegment:!0,useNativeHLSTextTracks:!1,useManagedMediaSource:!1,useNewPruneBufferStrategy:!1,useNewPartialSegmentFeeding:!1,useSeparateAudioVideoABR:!0,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,manifestRetryInterval:300,manifestRetryMaxInterval:1e4,manifestRetryMaxCount:10,audioVideoSyncRate:20,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50},useVolumeMultiplier:!1},yS=a=>{var e;return{...EL(a,vS),configName:[...(e=a.configName)!=null?e:[],...vS.configName]}};import{assertNonNullable as Us,combine as Hs,ErrorCategory as js,filter as la,filterChanged as $e,fromEvent as il,isNonNullable as LL,isNullable as $L,Logger as ML,map as V,mapTo as xS,merge as vt,now as Gs,once as st,Subject as H,Subscription as PS,tap as AS,ValueSubject as x,isHigher as CL,isInvariantQuality as wS}from"@vkontakte/videoplayer-shared";import{merge as xL,map as PL,filter as TS,isNonNullable as AL}from"@vkontakte/videoplayer-shared";var rl=({seekState:a,position$:e})=>xL(a.stateChangeEnded$.pipe(PL(({to:t})=>{var r;return t.state==="none"?void 0:((r=t.position)!=null?r:NaN)/1e3}),TS(AL)),e.pipe(TS(()=>a.getState().state==="none")));import{assertNonNullable as wL}from"@vkontakte/videoplayer-shared";var IS=a=>{let e=typeof a.container=="string"?document.getElementById(a.container):a.container;return wL(e,`Wrong container or containerId {${a.container}}`),e};import{filter as kL,once as RL}from"@vkontakte/videoplayer-shared";var ES=(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(kL(i=>i.length>0),RL()).subscribe(i=>{i.find(r)&&e.startTransitionTo(a)}):(a===void 0||t!=null&&t.getValue().find(r))&&e.startTransitionTo(a)};var Ys=class{constructor(e={configName:[]}){this.subscription=new PS;this.logger=new ML;this.abrLogger=this.logger.createComponentLog("ABR");this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new x(!1);this.hasLiveOffsetByPausedTimer=0;this.desiredState={playbackState:new $("stopped"),seekState:new $({state:"none"}),volume:new $({volume:1,muted:!1}),videoTrack:new $(void 0),videoStream:new $(void 0),audioStream:new $(void 0),autoVideoTrackSwitching:new $(!0),autoVideoTrackLimits:new $({}),isLooped:new $(!1),playbackRate:new $(1),externalTextTracks:new $([]),internalTextTracks:new $([]),currentTextTrack:new $(void 0),textTrackCuesSettings:new $({}),cameraOrientation:new $({x:0,y:0})};this.info={playbackState$:new x("stopped"),position$:new x(0),duration$:new x(1/0),muted$:new x(!1),volume$:new x(1),availableVideoStreams$:new x([]),currentVideoStream$:new x(void 0),availableQualities$:new x([]),availableQualitiesFps$:new x({}),currentQuality$:new x(void 0),isAutoQualityEnabled$:new x(!0),autoQualityLimitingAvailable$:new x(!1),autoQualityLimits$:new x({}),availableAudioStreams$:new x([]),currentAudioStream$:new x(void 0),availableAudioTracks$:new x([]),isAudioAvailable$:new x(!0),currentPlaybackRate$:new x(1),currentBuffer$:new x({start:0,end:0}),isBuffering$:new x(!0),isStalled$:new x(!1),isEnded$:new x(!1),isLooped$:new x(!1),isLive$:new x(void 0),canChangePlaybackSpeed$:new x(void 0),atLiveEdge$:new x(void 0),atLiveDurationEdge$:new x(void 0),liveTime$:new x(void 0),liveBufferTime$:new x(void 0),currentFormat$:new x(void 0),availableTextTracks$:new x([]),currentTextTrack$:new x(void 0),throughputEstimation$:new x(void 0),rttEstimation$:new x(void 0),videoBitrate$:new x(void 0),hostname$:new x(void 0),httpConnectionType$:new x(void 0),httpConnectionReused$:new x(void 0),surface$:new x("none"),chromecastState$:new x("NOT_AVAILABLE"),chromecastDeviceName$:new x(void 0),intrinsicVideoSize$:new x(void 0),availableSources$:new x(void 0),is3DVideo$:new x(!1),currentVideoSegmentLength$:new x(0),currentAudioSegmentLength$:new x(0)};this.events={inited$:new H,ready$:new H,started$:new H,playing$:new H,paused$:new H,stopped$:new H,willStart$:new H,willResume$:new H,willPause$:new H,willStop$:new H,willDestruct$:new H,watchCoverageRecord$:new H,watchCoverageLive$:new H,managedError$:new H,fatalError$:new H,ended$:new H,looped$:new H,seeked$:new H,willSeek$:new H,firstBytes$:new H,loadedMetadata$:new H,firstFrame$:new H,canplay$:new H,log$:new H};this.experimental={element$:new x(void 0),tuningConfigName$:new x([]),enableDebugTelemetry$:new x(!1),dumpTelemetry:Hm};if(this.initLogs(),this.tuning=yS(e),this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new ga({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new gS(this.tuning.throughputEstimator),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(t,r,i)=>{let s=Reflect.get(t,r,i);return typeof s!="function"?s:(...n)=>{try{return s.apply(t,n)}catch(o){let u=n.map(p=>JSON.stringify(p,(d,h)=>{let f=typeof h;return["number","string","boolean"].includes(f)?h:h===null?null:`<${f}>`})),l=`Player.${String(r)}`,c=`Exception calling ${l} (${u.join(", ")})`;throw this.events.fatalError$.next({id:l,category:js.WTF,message:c,thrown:o}),o}}}})}initVideo(e){var t,r,i;return this.config=e,this.domContainer=IS(e),this.chromecastInitializer.contentId=(t=e.meta)==null?void 0:t.videoId,this.providerContainer=new ua({sources:e.sources,meta:(r=e.meta)!=null?r:{},failoverHosts:(i=e.failoverHosts)!=null?i:[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,logger:this.logger,abrLogger:this.abrLogger},tuning:this.tuning,volumeMultiplier:e.volumeMultiplier}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.providerContainer.init(),this.setMuted(this.tuning.isAudioDisabled),this.initDebugTelemetry(),this.initWakeLock(),this}destroy(){var e;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()}prepare(){let e=this.desiredState.playbackState;return e.getState()==="stopped"&&e.startTransitionTo("ready"),this}play(){let e=()=>{let t=this.desiredState.playbackState;t.getState()!=="playing"&&t.startTransitionTo("playing")};return document.hidden&&this.tuning.autoplayOnlyInActiveTab&&!bi()?il(document,"visibilitychange").pipe(st()).subscribe(e):e(),this}pause(){let e=this.desiredState.playbackState;return e.getState()!=="paused"&&e.startTransitionTo("paused"),this}stop(){let e=this.desiredState.playbackState;return e.getState()!=="stopped"&&e.startTransitionTo("stopped"),this}seekTime(e,t=!0){let r=this.info.duration$.getValue(),i=this.info.isLive$.getValue();return e>=r&&!i&&(e=r-.1),this.events.willSeek$.next({from:this.getExactTime(),to:e}),this.desiredState.seekState.setState({state:"requested",position:e*1e3,forcePrecise:t}),this}seekPercent(e){let t=this.info.duration$.getValue();return isFinite(t)&&this.seekTime(Math.abs(t)*e,!1),this}setVolume(e){let t=this.tuning.isAudioDisabled||this.desiredState.volume.getState().muted;return 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.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){Us(this.providerContainer);let t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();return this.desiredState.videoTrack.getState()===void 0&&this.desiredState.videoTrack.getPrevState()===void 0&&t.length===0?this.providerContainer.providerOutput.availableVideoTracks$.pipe(la(r=>r.length>0),st()).subscribe(r=>{this.setVideoTrackIdByQuality(r,e)}):t.length>0&&this.setVideoTrackIdByQuality(t,e),this}setAutoQuality(e){return this.desiredState.autoVideoTrackSwitching.startTransitionTo(e),this}setAutoQualityLimits(e){return this.desiredState.autoVideoTrackLimits.startTransitionTo(e),this}setPlaybackRate(e){var r;Us(this.providerContainer);let t=(r=this.providerContainer)==null?void 0:r.providerOutput.element$.getValue();return t&&(this.desiredState.playbackRate.setState(e),t.playbackRate=e),this}setExternalTextTracks(e){return this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>({type:"external",...t}))),this}selectTextTrack(e){var t;return ES(e,this.desiredState.currentTextTrack,(t=this.providerContainer)==null?void 0:t.providerOutput.availableTextTracks$,r=>r.id===e),this}setTextTrackCueSettings(e){return this.desiredState.textTrackCuesSettings.startTransitionTo(e),this}setLooped(e){return this.desiredState.isLooped.startTransitionTo(e),this}toggleChromecast(){this.chromecastInitializer.toggleConnection()}startCameraManualRotation(e,t){let r=this.getScene3D();return r&&r.startCameraManualRotation(e,t),this}stopCameraManualRotation(e=!1){let t=this.getScene3D();return t&&t.stopCameraManualRotation(e),this}moveCameraFocusPX(e,t){let r=this.getScene3D();if(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($L(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),r=t.state==="none"?void 0:t.position;return LL(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(vt(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(V(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(V(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(V(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(V(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(V(e=>e.to)).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(la(({from:e})=>e==="stopped"),st()).subscribe(()=>{this.initedAt=Gs(),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();n.state==="requested"?this.desiredState.seekState.setState({...n,state:"applying"}):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:js.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.seekedEvent$.subscribe(()=>{this.desiredState.seekState.getState().state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe(V(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(V(n=>n.destination),$e()).subscribe(()=>{this.isPlaybackStarted=!1})).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add(e.providerOutput.availableVideoTracks$.pipe(V(n=>n.map(({quality:o})=>o).sort((o,u)=>wS(o)?1:wS(u)?-1:CL(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$.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$.subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe($e()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe($e()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe($e()).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(V(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(Hs({hasLiveOffsetByPaused:vt(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(V(n=>n.to),$e(),V(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(Hs({atLiveEdge:Hs({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:rl({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(V(({isLive:n,position:o,isLowLatency:u})=>{let l=this.getActiveLiveDelay(u);return n&&Math.abs(o)<l/1e3}),$e(),AS(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(V(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add(Hs({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(V(({isLive:n,position:o,duration:u})=>n&&(Math.abs(u)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),$e(),AS(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(V(n=>n.muted),$e()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(V(n=>n.volume),$e()).subscribe(this.info.volume$)).add(rl({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(vt(e.providerOutput.endedEvent$.pipe(xS(!0)),e.providerOutput.seekedEvent$.pipe(xS(!1))).pipe($e()).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(V(n=>({id:n?`No${n}`:"NoProviders",category:js.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(),V(n=>n!=null?n:Gs()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe(st(),V(()=>Gs()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(st(),V(()=>Gs()-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 x(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let r=new x(!0);this.subscription.add(e.current$.subscribe(()=>r.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(la(({to:n})=>n==="playing"),st()).subscribe(()=>r.next(!1)));let i=0,s=vt(e.providerOutput.isBuffering$,t,r).pipe(V(()=>{let n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||r.getValue();return n&&!o}),$e());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(vt(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(vt(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(),p;c==="CONNECTED"?p="second_screen":u?l?n?p="pip":o?p="fullscreen":p="inline":p="invisible":p="none",this.info.surface$.getValue()!==p&&this.info.surface$.next(p)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(V(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 PS;this.subscription.add(t),this.subscription.add(e.current$.pipe($e((r,i)=>r.provider===i.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(la(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=mt(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(vt(this.desiredState.videoTrack.stateChangeStarted$.pipe(V(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(V(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(V(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(V(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(V(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(V(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(V(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(V(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(V(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;Us(this.providerContainer),Us(e),Um(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(r=>qm(r)),this.providerContainer.current$.subscribe(({type:r})=>ci("provider",r)),e.duration$.subscribe(r=>ci("duration",r)),e.availableVideoTracks$.pipe(la(r=>!!r.length),st()).subscribe(r=>ci("tracks",r)),this.events.fatalError$.subscribe(new ie("fatalError")),this.events.managedError$.subscribe(new ie("managedError")),e.position$.subscribe(new ie("position")),e.currentVideoTrack$.pipe(V(r=>r==null?void 0:r.quality)).subscribe(new ie("quality")),this.info.currentBuffer$.subscribe(new ie("buffer")),e.isBuffering$.subscribe(new ie("isBuffering"))].forEach(r=>this.subscription.add(r)),ci("codecs",Ab())}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:js.DOM,message:String(i)})})};this.subscription.add(vt(il(document,"visibilitychange"),il(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);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 cG,Observable as dG,Subject as pG,ValueSubject as hG,VideoQuality as fG}from"@vkontakte/videoplayer-shared";var mG=`@vkontakte/videoplayer-core@${Rl}`;export{ma as ChromecastState,on as HttpConnectionType,dG as Observable,oe as PlaybackState,Ys as Player,mG as SDK_VERSION,pG as Subject,cG as Subscription,un as Surface,Rl as VERSION,hG as ValueSubject,lt as VideoFormat,fG as VideoQuality};
|
|
91
|
+
`;var ks=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 ws(this.params.fov,this.params.orientation),this.cameraRotationManager=new As(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(wg,this.gl.VERTEX_SHADER),r=this.createShader(Ag,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,p=e-r,d=t+i;return[s,n,o,u,l,c,p,d]}updateTextureMappingBuffer(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([...this.calculateTexturePosition()]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}updateFrameSize(){this.frameWidth=this.sourceVideoElement.videoWidth,this.frameHeight=this.sourceVideoElement.videoHeight}createCanvas(){let e=document.createElement("canvas");return e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e}};var jt=class{constructor(e){this.subscription=new rR;this.videoState=new $("stopped");this.elementSize$=new iR(void 0);this.textTracksManager=new we;this.droppedFramesManager=new is;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new Za;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 Qk(e)}}};this.init3DScene=e=>{var r,i,s;if(this.scene3D)return;this.scene3D=new ks(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=ue(e.container,e.tuning),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 Ps({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode}),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params,r=de(this.video),i=this.constructor.name,s=o=>{e.error$.next({id:i,category:Fu.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(kg(l=>!!l.length),$g()).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(kg(Xk),$g()),e.firstBytesEvent$),s(this.videoState.stateChangeEnded$.pipe(Lg(l=>l.to)),this.params.output.playbackState$),this.subscription.add(r.seeked$.subscribe(e.seekedEvent$,i)),this.subscription.add(Ue(this.video,t.isLooped,i)),this.subscription.add(ce(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Pe(this.video,t.playbackRate,r.playbackRateState$,i)),s(tR(this.video),this.elementSize$),s(ke(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,this.textTracksMap=new Map;let c=this.player.getStreams();if(zk(c,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let d=[];for(let h of c.audio){d.push(Ru(h));let f=[];for(let b of h.representations){let g=dg(b);f.push(g),this.audioTracksMap.set(g,{stream:h,representation:b})}this.audioStreamsMap.set(h,f)}this.params.output.availableAudioStreams$.next(d)}let p=[];for(let d of c.video){p.push(Lu(d));let h=[];for(let f of d.representations){let b=cg(f);b&&(h.push(b),this.videoTracksMap.set(b,{stream:d,representation:f}))}this.videoStreamsMap.set(d,h)}this.params.output.availableVideoStreams$.next(p);for(let d of c.text)for(let h of d.representations){let f=pg(d,h);this.textTracksMap.set(f,{stream:d,representation:h})}this.params.output.availableVideoTracks$.next(Array.from(this.videoTracksMap.keys())),this.params.output.availableAudioTracks$.next(Array.from(this.audioTracksMap.keys())),this.params.output.isAudioAvailable$.next(!!this.audioTracksMap.size),this.audioTracksMap.size>0&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else l==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},i));let n=l=>e.error$.next({id:"RepresentationSwitch",category:Fu.WTF,message:"Switching representations threw",thrown:l});this.subscription.add(Rs(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$,Jk(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 p=this.selectVideoAudioRepresentations();if(!p)return;let[d,h]=p,f=this.params.desiredState.autoVideoTrackLimits.getTransition();if(f&&this.params.output.autoVideoTrackLimits$.next(f.to),l==="manifest_ready")this.player.initRepresentations(d.id,h==null?void 0:h.id,this.params.sourceHls);else if(this.player.switchRepresentation("video",d.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(qu()).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[p,{stream:d}]=c,h=this.params.desiredState.videoStream.getTransition();h&&h.to&&h.to.id===d.id&&this.params.desiredState.videoStream.setState(h.to),e.currentVideoTrack$.next(p),e.currentVideoStream$.next(Lu(d))},i)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(qu()).subscribe(l=>{let c=[...this.audioTracksMap.entries()].find(([,{representation:f}])=>f.id===l);if(!c){e.currentAudioStream$.next(void 0);return}let[p,{stream:d}]=c,h=this.params.desiredState.audioStream.getTransition();h&&h.to&&h.to.id===d.id&&this.params.desiredState.audioStream.setState(h.to),e.currentAudioStream$.next(Ru(d))},i)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(l=>{var c,p;if(l!=null&&l.is3dVideo&&((c=this.params.tuning.spherical)!=null&&c.enabled))try{this.init3DScene(l),e.is3DVideo$.next(!0)}catch(d){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${d}`})}else this.destroy3DScene(),(p=this.params.tuning.spherical)!=null&&p.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(Lg(({to:l})=>l==="ready"),qu());this.subscription.add(Rs(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$).subscribe(()=>{let l=t.autoVideoTrackSwitching.getState(),p=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:l?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(p)})),this.subscription.add(Rs(o,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let u=Rs(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,eR(["init"])).pipe(Kk(0));this.subscription.add(u.subscribe(this.syncPlayback,i))}selectVideoAudioRepresentations(){var C,A,F,R,L,w,q,K,k,x,V,U,j,z;let{desiredState:e,output:t}=this.params,r=e.autoVideoTrackSwitching.getState(),i=(C=e.videoTrack.getState())==null?void 0:C.id,n=[...this.videoTracksMap.keys()].find(({id:_})=>_===i),o=t.currentVideoTrack$.getValue(),u=((R=(F=e.videoStream.getState())!=null?F:n&&((A=this.videoTracksMap.get(n))==null?void 0:A.stream))!=null?R:this.videoStreamsMap.size===1)?this.videoStreamsMap.keys().next().value:void 0;if(!u)return;let l=[...this.videoStreamsMap.keys()].find(({id:_})=>_===u.id),c=l&&this.videoStreamsMap.get(l);if(!c)return;let p=Je(this.video.buffered,this.video.currentTime*1e3),d=r?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,h=Math.min(p/Math.min(d,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),f=(L=e.audioStream.getState())!=null?L:this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0,b=(w=[...this.audioStreamsMap.keys()].find(({id:_})=>_===(f==null?void 0:f.id)))!=null?w:this.audioStreamsMap.keys().next().value,g=0;if(b){if(n&&!r){let _=gs(n,c,(q=this.audioStreamsMap.get(b))!=null?q:[]);g=Math.max(g,(K=_==null?void 0:_.bitrate)!=null?K:-1/0)}if(o){let _=gs(o,c,(k=this.audioStreamsMap.get(b))!=null?k:[]);g=Math.max(g,(x=_==null?void 0:_.bitrate)!=null?x:-1/0)}}let v=ft(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,history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),{backgroundVideoQualityLimit:T}=this.params.tuning.autoTrackSelection;!this.params.output.elementVisible$.getValue()&&r&&(v=(V=c.filter(_=>!Zk(_.quality)).sort((_,Gt)=>{var it,O;return((it=Gt.bitrate)!=null?it:0)-((O=_.bitrate)!=null?O:0)}).filter(_=>Rg(_.quality,v.quality)&&Rg(_.quality,T))[0])!=null?V:v);let S=r?v!=null?v:n:n!=null?n:v,y=b&&gs(S,c,(U=this.audioStreamsMap.get(b))!=null?U:[]),I=(j=this.videoTracksMap.get(S))==null?void 0:j.representation,D=y&&((z=this.audioTracksMap.get(y))==null?void 0:z.representation);if(I&&D)return[I,D];if(I&&!D&&this.audioTracksMap.size===0)return[I,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){pe(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:Fu.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),le(this.video)}};var Qi=class extends jt{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 Mg,interval as aR,map as sR}from"@vkontakte/videoplayer-shared";var zi=class extends jt{constructor(e){super(e),this.liveOffset=new ze}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(Mg({interval:aR(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(Mg({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(sR(({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 Dg=Fe(Ka(),1);import{assertNever as Ki,assertNonNullable as Cg,debounce as nR,ErrorCategory as Ls,filter as oR,isNonNullable as uR,isNullable as lR,map as $s,merge as cR,Observable as dR,observableFrom as pR,Subscription as hR,videoSizeToQuality as fR}from"@vkontakte/videoplayer-shared";var _e={};var kr=(a,e)=>new dR(t=>{let r=(i,s)=>t.next(s);return a.on(e,r),()=>a.off(e,r)}),Ji=class{constructor(e){this.subscription=new hR;this.videoState=new $("initializing");this.textTracksManager=new we;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:Ki(e)}break;case"ready":switch(e){case"stopped":this.prepare();break;case"ready":case"playing":case"paused":break;default:Ki(e)}break;case"playing":switch(e){case"playing":break;case"stopped":this.prepare();break;case"ready":case"paused":this.playIfAllowed();break;default:Ki(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:Ki(e)}break;default:Ki(t)}};this.video=ue(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),le(this.video)}loadHlsJs(){let e=!1,t=i=>{e||this.params.output.error$.next({id:i==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:Ls.NETWORK,message:"Failed to load Hls.js",thrown:i}),e=!0},r=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);(0,Dg.default)(import("hls.js").then(i=>{e||(_e.Hls=i.default,_e.Events=i.default.Events,this.init())},t),()=>{window.clearTimeout(r),e=!0})}init(){Cg(_e.Hls,"hls.js not loaded"),this.hls=new _e.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState("stopped")}subscribe(){Cg(_e.Events,"hls.js not loaded");let{desiredState:e,output:t}=this.params,r=l=>{t.error$.next({id:"HlsJsProvider",category:Ls.WTF,message:"HlsJsProvider internal logic error",thrown:l})},i=de(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(Ue(this.video,e.isLooped,r)),this.subscription.add(ce(this.video,e.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(Pe(this.video,e.playbackRate,i.playbackRateState$,r)),s(ke(this.video),t.elementVisible$),s(this.videoState.stateChangeEnded$.pipe($s(l=>l.to)),this.params.output.playbackState$),this.subscription.add(kr(this.hls,_e.Events.ERROR).subscribe(l=>{var c;l.fatal&&t.error$.next({id:["HlsJsFatal",l.type,l.details].join("_"),category:Ls.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(kr(this.hls,_e.Events.MANIFEST_PARSED).pipe($s(({levels:l})=>l.reduce((c,p)=>{var T,S;let d=p.name||p.height.toString(10),{width:h,height:f}=p,b=(S=pt((T=p.attrs.QUALITY)!=null?T:""))!=null?S:fR({width:h,height:f});if(!b)return c;let g=p.attrs["FRAME-RATE"]?parseFloat(p.attrs["FRAME-RATE"]):void 0,v={id:d.toString(),quality:b,bitrate:p.bitrate/1e3,size:{width:h,height:f},fps:g};return this.trackLevels.set(d,{track:v,level:p}),c.push(v),c},[]))),t.availableVideoTracks$),s(kr(this.hls,_e.Events.MANIFEST_PARSED),l=>{if(l.subtitleTracks.length>0){let c=[];for(let p of l.subtitleTracks){let d=p.name,h=p.attrs.URI||"",f=p.lang;c.push({id:d,url:h,language:f,type:"internal"})}e.internalTextTracks.startTransitionTo(c)}}),s(kr(this.hls,_e.Events.LEVEL_LOADING).pipe($s(({url:l})=>X(l))),t.hostname$),s(kr(this.hls,_e.Events.FRAG_CHANGED),l=>{var d,h,f,b;let{video:c,audio:p}=l.frag.elementaryStreams;t.currentVideoSegmentLength$.next((((d=c==null?void 0:c.endPTS)!=null?d:0)-((h=c==null?void 0:c.startPTS)!=null?h:0))*1e3),t.currentAudioSegmentLength$.next((((f=p==null?void 0:p.endPTS)!=null?f:0)-((b=p==null?void 0:p.startPTS)!=null?b:0))*1e3)}),this.subscription.add(lt(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:p})=>p===l))==null?void 0:c.track},o=kr(this.hls,_e.Events.LEVEL_SWITCHED).pipe($s(({level:l})=>n(this.hls.levels[l])));o.pipe(oR(uR)).subscribe(t.currentVideoTrack$,r),this.subscription.add(lt(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel]),l=>{var f;if(lR(l))return;let c=(f=this.trackLevels.get(l.id))==null?void 0:f.level;if(!c)return;let p=this.hls.levels.indexOf(c),d=this.hls.currentLevel,h=this.hls.levels[d];!h||c.bitrate>h.bitrate?this.hls.nextLevel=p:(this.hls.loadLevel=p,this.hls.loadLevel=p)},{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$,pR(["init"])).pipe(nR(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 pe(this.video).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Ls.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 Og="X-Playback-Duration",Uu=async a=>{var i;let e=await Xe(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(Og)?parseInt(e.headers.get(Og),10):void 0};import{assertNever as yR,combine as TR,debounce as IR,ErrorCategory as Cs,filter as ER,filterChanged as xR,isNonNullable as Vg,isNullable as Ds,map as _g,merge as PR,observableFrom as wR,Subscription as AR,ValueSubject as Gu,VideoQuality as kR}from"@vkontakte/videoplayer-shared";var ju=Fe(uo(),1);import{videoSizeToQuality as mR,getExponentialDelay as bR}from"@vkontakte/videoplayer-shared";var gR=a=>{let e=null;if(a.QUALITY&&(e=pt(a.QUALITY)),!e&&a.RESOLUTION){let[t,r]=a.RESOLUTION.split("x").map(i=>parseInt(i,10));e=mR({width:t,height:r})}return e!=null?e:null},SR=(a,e)=>{var s,n;let t=a.split(`
|
|
92
|
+
`),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 p=(0,ju.default)(l[1].split(",").map(T=>T.split("="))),d=(s=p.QUALITY)!=null?s:`stream-${p.BANDWIDTH}`,h=gR(p),f;p.BANDWIDTH&&(f=parseInt(p.BANDWIDTH,10)/1e3||void 0),!f&&p["AVERAGE-BANDWIDTH"]&&(f=parseInt(p["AVERAGE-BANDWIDTH"],10)/1e3||void 0);let b=p["FRAME-RATE"]?parseFloat(p["FRAME-RATE"]):void 0,g;if(p.RESOLUTION){let[T,S]=p.RESOLUTION.split("x").map(y=>parseInt(y,10));T&&S&&(g={width:T,height:S})}let v=new URL(t[++o],e).toString();h&&r.push({id:d,quality:h,url:v,bandwidth:f,size:g,fps:b})}if(c){let p=(0,ju.default)(c[1].split(",").map(b=>b.split("=")).map(([b,g])=>[b,g.replace(/^"|"$/g,"")])),d=(n=p.URI)==null?void 0:n.replace(/playlist$/,"subtitles.vtt"),h=p.LANGUAGE,f=p.NAME;d&&h&&i.push({type:"internal",id:h,label:f,language:h,url:d,isAuto:!1})}}}if(!r.length)throw new Error("Empty manifest");return{qualityManifests:r,textTracks:i}},vR=a=>new Promise(e=>{setTimeout(()=>{e()},a)}),Hu=0,Bg=async(a,e=a,t)=>{let i=await(await Xe(a)).text();Hu+=1;try{let{qualityManifests:s,textTracks:n}=SR(i,e);return{qualityManifests:s,textTracks:n}}catch(s){if(Hu<=t.manifestRetryMaxCount)return await vR(bR(Hu-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),Bg(a,e,t)}return{qualityManifests:[],textTracks:[]}},Ms=Bg;var Xi=class{constructor(e){this.subscription=new AR;this.videoState=new $("stopped");this.textTracksManager=new we;this.manifests$=new Gu([]);this.liveOffset=new ze;this.manifestStartTime$=new Gu(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 yR(t)}};var t;this.params=e,this.video=ue(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:kR.INVARIANT,url:this.params.source.url},Ms(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:Cs.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),this.manifests$.next([this.masterManifest,...r])},r=>this.params.output.error$.next({id:"ExtractHlsQualities",category:Cs.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 Gu((t=e.source.maxSeekBackTime)!=null?t:1/0),this.subscribe()}selectManifest(){var u,l,c,p;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,r=e.getState(),i=t.getTransition(),s=(p=(c=(u=i==null?void 0:i.to)==null?void 0:u.id)!=null?c:(l=t.getState())==null?void 0:l.id)!=null?p:"master",n=this.manifests$.getValue();if(!n.length)return;let o=r?"master":s;return r&&!i&&t.startTransitionTo(this.masterManifest),n.find(d=>d.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"HlsLiveProvider",category:Cs.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},i=de(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(ce(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Pe(this.video,t.playbackRate,i.playbackRateState$,r)),s(ke(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(xR(),_g(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&&Vg(l.to)){let p=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let d=this.manifests$.getValue().find(h=>h.id===p);d&&(this.params.output.currentVideoTrack$.next(d),this.params.output.hostname$.next(X(d.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(TR({startTime:this.manifestStartTime$.pipe(ER(Vg)),currentTime:i.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),r)),this.subscription.add(this.manifests$.pipe(_g(o=>o.map(({id:u,quality:l,size:c,bandwidth:p,fps:d})=>({id:u,quality:l,size:c,fps:d,bitrate:p})))).subscribe(this.params.output.availableVideoTracks$,r));let n=PR(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,wR(["init"])).pipe(IR(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),le(this.video)}prepare(){var o,u;let e=this.selectManifest();if(Ds(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[p,d]of[[l,"mq"],[c,"lq"]]){let h=String(parseFloat(p||""));d&&p&&i.searchParams.set(d,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(),Uu(n).then(l=>{var c;if(!Ds(l))this.maxSeekBackTime$.next(l);else{let p=(c=this.params.source.maxSeekBackTime)!=null?c:this.maxSeekBackTime$.getValue();if(Ds(p)||!isFinite(p))try{Xe(n).then(d=>d.text()).then(d=>{var f;let h=(f=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(d))==null?void 0:f[1];if(h){let b=new URL(h,n).toString();Uu(b).then(g=>{Ds(g)||this.maxSeekBackTime$.next(g)})}})}catch(d){}}})}playIfAllowed(){pe(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:Cs.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 RR,debounce as LR,ErrorCategory as Yu,fromEvent as Wu,isNonNullable as $R,isNullable as MR,map as Ng,merge as Fg,observableFrom as qg,Subscription as CR,ValueSubject as DR,VideoQuality as OR,clientChecker as BR}from"@vkontakte/videoplayer-shared";var Zi=class{constructor(e){this.subscription=new CR;this.videoState=new $("stopped");this.textTracksManager=new we;this.manifests$=new DR([]);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:p}=this.video;this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:p*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 RR(t)}};this.params=e,this.video=ue(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:OR.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),Ms(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:Yu.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){var u,l,c,p;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,r=e.getState(),i=t.getTransition(),s=(p=(c=(u=i==null?void 0:i.to)==null?void 0:u.id)!=null?c:(l=t.getState())==null?void 0:l.id)!=null?p:"master",n=this.manifests$.getValue();if(!n.length)return;let o=r?"master":s;return r&&!i&&t.startTransitionTo(this.masterManifest),n.find(d=>d.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"HlsProvider",category:Yu.WTF,message:"HlsProvider internal logic error",thrown:o})},i=de(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(Ng(o=>o.to)),this.params.output.playbackState$),this.subscription.add(Ue(this.video,t.isLooped,r)),this.subscription.add(ce(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Pe(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 p;let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&$R(l.to)){let d=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let h=this.manifests$.getValue().find(f=>f.id===d);if(h){this.params.output.currentVideoTrack$.next(h),this.params.output.hostname$.next(X(h.url));let f=this.params.desiredState.playbackRate.getState(),b=(p=this.params.output.element$.getValue())==null?void 0:p.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(Ng(o=>o.map(({id:u,quality:l,size:c,bandwidth:p,fps:d})=>({id:u,quality:l,size:c,fps:d,bitrate:p})))).subscribe(this.params.output.availableVideoTracks$,r)),!BR.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add(Fg(Wu(o,"addtrack"),Wu(o,"removetrack"),Wu(o,"change"),qg(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},r))}let n=Fg(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,qg(["init"])).pipe(LR(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),le(this.video)}prepare(){var s,n;let e=this.selectManifest();if(MR(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 p=String(parseFloat(l||""));c&&l&&i.searchParams.set(c,p)}}this.video.setAttribute("src",i.toString()),this.video.load()}playIfAllowed(){pe(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:Yu.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};import{assertNever as VR,assertNonNullable as Ug,debounce as _R,ErrorCategory as Hg,isHigher as NR,isHigherOrEqual as FR,isInvariantQuality as jg,isLowerOrEqual as qR,isNonNullable as UR,merge as HR,observableFrom as jR,Subscription as GR,map as YR}from"@vkontakte/videoplayer-shared";var ea=class{constructor(e){this.subscription=new GR;this.videoState=new $("stopped");this.trackUrls={};this.textTracksManager=new we;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:p}=this.video;this.prepare(),o.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:p*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 VR(e)}};this.params=e,this.video=ue(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:Hg.WTF,message:"MpegProvider internal logic error",thrown:o})},i=de(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(YR(o=>o.to)),this.params.output.playbackState$),this.subscription.add(Ue(this.video,t.isLooped,r)),this.subscription.add(ce(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Pe(this.video,t.playbackRate,i.playbackRateState$,r)),s(ke(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&&UR(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(),p=(l=this.params.output.element$.getValue())==null?void 0:l.playbackRate;if(c!==p){let d=this.params.output.element$.getValue();d&&(this.params.desiredState.playbackRate.setState(c),d.playbackRate=c)}}this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.textTracksManager.connect(this.video,t,e);let n=HR(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,jR(["init"])).pipe(_R(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),le(this.video)}prepare(){var r;let e=(r=this.params.desiredState.videoTrack.getState())==null?void 0:r.id;Ug(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];Ug(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=ji(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(X(t))}playIfAllowed(){pe(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:Hg.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(p=>!jg(p.track.quality)&&qR(p.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&&FR(c.quality,u.quality)&&(t=u),!t){let p=Object.values(this.trackUrls).filter(h=>!jg(h.track.quality)&&NR(h.track.quality,e)),d=p.length;d&&(t=p[d-1].track)}t&&(r=t.quality)}else if(!e){let u=Object.values(this.trackUrls).map(l=>l.track);t=ft(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 Yg,debounce as KR,merge as Wg,observableFrom as JR,Subscription as XR,map as Qg,ValueSubject as ZR,ErrorCategory as zu,VideoQuality as eL}from"@vkontakte/videoplayer-shared";import{ErrorCategory as WR}from"@vkontakte/videoplayer-shared";var Gg=["stun:videostun.mycdn.me:80"],QR=1e3,zR=3,Qu=()=>null,Os=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=Qu;this.externalStopCallback=Qu;this.externalErrorCallback=Qu;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:Gg}]};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:WR.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),QR)}normalizeOptions(e={}){let t={stunServerList:Gg,maxRetryNumber:zR,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var ta=class{constructor(e){this.videoState=new $("stopped");this.maxSeekBackTime$=new ZR(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 Yg(e)}};this.subscription=new XR,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=ue(e.container,e.tuning),this.liveStreamClient=new Os(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),le(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,r=n=>{e.error$.next({id:"WebRTCLiveProvider",category:zu.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};Wg(this.videoState.stateChangeStarted$.pipe(Qg(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe(Qg(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})});let i=de(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(ke(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(ce(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 Yg(n.to)}},r)).add(Wg(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,JR(["init"])).pipe(KR(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:eL.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:zu.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){pe(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:zu.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var ra=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 sa,assertNonNullable as gt,ErrorCategory as Vs,filter as oL,isNonNullable as eS,isNullable as uL,map as lL,merge as cL,once as dL,Subject as ve,Subscription as tS,ValueSubject as M}from"@vkontakte/videoplayer-shared";import{Observable as tL,map as zg,Subscription as rL,Subject as iL}from"@vkontakte/videoplayer-shared";var Kg=a=>new tL(e=>{let t=new rL,r=a.desiredPlaybackState$.stateChangeStarted$.pipe(zg(({from:l,to:c})=>`${l}-${c}`)),i=a.desiredPlaybackState$.stateChangeEnded$,s=a.providerChanged$.pipe(zg(({type:l})=>l!==void 0)),n=new iL,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 Jg,Subscription as aL,combine as sL,filter as Xg,once as Zg}from"@vkontakte/videoplayer-shared";var ia=null,Bs=null;function Ku(){return ia||(ia=new(window.AudioContext||window.webkitAudioContext)),Bs||(Bs=new GainNode(ia,{gain:1}),Bs.connect(ia.destination)),{audioCtx:ia,gainNode:Bs}}import{clientChecker as nL}from"@vkontakte/videoplayer-shared";var Rr=class Rr{constructor(e,t,r,i,s){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=r;this.volumeMultiplier=i;this.subscriptions=new aL;this.lastAudioContextResumeId=0;!s||!this.isSupported()||i===1||this.subscriptions.add(this.provider$.pipe(Xg(n=>!!n.type),Zg()).subscribe(({type:n})=>this.subscribe(n)))}subscribe(e){nL.isSafari&&e!=="MPEG"||this.subscriptions.add(sL({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe(Xg(({playbackState:t,video:r,volume:{muted:i,volume:s}})=>t==="playing"&&!!r&&!i&&!!s),Zg()).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}=Ku(),s=(Math.random()+1)*999999;this.lastAudioContextResumeId=s,r.resume().then(()=>{var n;if(s!==this.lastAudioContextResumeId)throw new Error(`AudioContext.resume() resolved after ${Rr.errorId} destroyed`);i.gain.value=t;try{new MediaElementAudioSourceNode(r,{mediaElement:e}).connect(i)}catch(o){this.volumeMultiplierError$.next({id:Rr.errorId,category:Jg.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:Rr.errorId,category:Jg.VIDEO_PIPELINE,message:(o=n==null?void 0:n.message)!=null?o:"initAudioContextOnce: AudioContext.resume() exception",thrown:n})})}destroy(){let{gainNode:e}=Ku();e.gain.value=1,this.subscriptions.unsubscribe(),this.lastAudioContextResumeId=0}};Rr.errorId="VolumeMultiplierManager";var aa=Rr;var pL={chunkDuration:5e3,maxParallelRequests:5},na=class{constructor(e){this.current$=new M({type:void 0});this.providerError$=new ve;this.noAvailableProvidersError$=new ve;this.volumeMultiplierError$=new ve;this.providerOutput={position$:new M(0),duration$:new M(1/0),volume$:new M({muted:!1,volume:1}),availableVideoStreams$:new M([]),currentVideoStream$:new M(void 0),availableVideoTracks$:new M([]),currentVideoTrack$:new M(void 0),availableAudioStreams$:new M([]),currentAudioStream$:new M(void 0),availableAudioTracks$:new M([]),currentVideoSegmentLength$:new M(0),currentAudioSegmentLength$:new M(0),isAudioAvailable$:new M(!0),autoVideoTrackLimitingAvailable$:new M(!1),autoVideoTrackLimits$:new M(void 0),currentBuffer$:new M(void 0),isBuffering$:new M(!0),error$:new ve,warning$:new ve,willSeekEvent$:new ve,seekedEvent$:new ve,loopedEvent$:new ve,endedEvent$:new ve,firstBytesEvent$:new ve,loadedMetadataEvent$:new ve,firstFrameEvent$:new ve,canplay$:new ve,isLive$:new M(void 0),isLowLatency$:new M(!1),canChangePlaybackSpeed$:new M(!0),liveTime$:new M(void 0),liveBufferTime$:new M(void 0),availableTextTracks$:new M([]),currentTextTrack$:new M(void 0),hostname$:new M(void 0),httpConnectionType$:new M(void 0),httpConnectionReused$:new M(void 0),inPiP$:new M(!1),inFullscreen$:new M(!1),element$:new M(void 0),elementVisible$:new M(!0),availableSources$:new M(void 0),is3DVideo$:new M(!1),playbackState$:new M("")};this.subscription=new tS;var o;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer");let t=vb([...Tb(this.params.tuning),...yb(this.params.tuning)],this.params.tuning.useHlsJs,this.params.tuning.useManagedMediaSource).filter(u=>eS(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.screenFormatsIterator=new ra(s);let n=[...fu(!0),...fu(!1)];this.chromecastFormatsIterator=new ra(n.filter(u=>eS(e.sources[u]))),this.providerOutput.availableSources$.next(e.sources),this.volumeMultiplierManager=new aa(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()}initProvider(){let e=this.chooseDestination(),t=this.chooseFormat(e);if(uL(t)){this.handleNoFormatsError(e);return}let r;try{r=this.createProvider(e,t)}catch(i){this.providerError$.next({id:"ProviderNotConstructed",category:Vs.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.destroyProvider(),this.initProvider()}switchToNextProvider(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"});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}`}),e){case"SCREEN":return this.createScreenProvider(t);case"CHROMECAST":return this.createChromecastProvider(t);default:return sa(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 gt(o),new Qi({...n,source:o,sourceHls:u})}case"DASH_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return gt(o),new zi({...n,source:o})}case"HLS":case"HLS_ONDEMAND":{let o=this.applyFailoverHost(t[e]);return gt(o),vr||!this.params.tuning.useHlsJs?new Zi({...n,source:o}):new Ji({...n,source:o})}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return gt(o),new Xi({...n,source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case"MPEG":{let o=this.applyFailoverHost(t[e]);return gt(o),new ea({...n,source:o})}case"DASH_LIVE":{let o=this.applyFailoverHost(t[e]);return gt(o),new tb({...n,source:o,config:{...pL,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case"WEB_RTC_LIVE":{let o=this.applyFailoverHost(t[e]);return gt(o),new ta({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 sa(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 gt(o),new si({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 sa(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return sa(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 sa(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,rS.default)(Object.entries(e).map(([i,s])=>[i,r(s)]))}initProviderErrorHandling(){let e=new tS,t=!1,r=0;return e.add(cL(this.providerOutput.error$,Kg({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(lL(i=>({id:`ProviderHangup:${i}`,category:Vs.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(oL(({to:s})=>s==="playing"),dL()).subscribe(()=>t=!0);e.add(i)})),e.add(this.providerError$.subscribe(i=>{let s=this.current$.getValue().destination;if(s==="CHROMECAST")this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider("SCREEN"),()=>this.params.dependencies.chromecastInitializer.disconnect());else{let n=i.category===Vs.NETWORK,o=i.category===Vs.FATAL,u=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),l=r<this.params.tuning.providerErrorLimit&&!o;u&&!o&&(n&&t||!l)?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):l?(r++,this.reinitProvider()):this.switchToNextProvider(s!=null?s:"SCREEN")}})),e}};import{fromEvent as _s,once as hL,combine as fL,Subscription as iS,ValueSubject as Ju,map as mL,filter as bL,isNonNullable as Ns,now as ye,safeStorage as Xu}from"@vkontakte/videoplayer-shared";var gL=5e3,aS="one_video_throughput",sS="one_video_rtt",tt=window.navigator.connection,nS=()=>{let a=tt==null?void 0:tt.downlink;if(Ns(a)&&a!==10)return a*1e3},oS=()=>{let a=tt==null?void 0:tt.rtt;if(Ns(a)&&a!==3e3)return a},uS=(a,e,t)=>{let r=t*8,i=r/a;return r/(i+e)},Zu=class a{constructor(e){this.subscription=new iS;this.concurrentDownloads=new Set;var i,s;this.tuningConfig=e;let t=a.load(aS)||(e.useBrowserEstimation?nS():void 0)||gL,r=(s=(i=a.load(sS))!=null?i:e.useBrowserEstimation?oS():void 0)!=null?s:0;if(this.throughput$=new Ju(t),this.rtt$=new Ju(r),this.rttAdjustedThroughput$=new Ju(uS(t,r,e.rttPenaltyRequestSize)),this.throughput=Ut.getSmoothedValue(t,-1,e),this.rtt=Ut.getSmoothedValue(r,1,e),e.useBrowserEstimation){let n=()=>{let u=nS();u&&this.throughput.next(u);let l=oS();Ns(l)&&this.rtt.next(l)};tt&&"onchange"in tt&&this.subscription.add(_s(tt,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{Xu.set(aS,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{Xu.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(fL({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(mL(({throughput:n,rtt:o})=>uS(n,o,e.rttPenaltyRequestSize)),bL(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=ye(),i=new iS;switch(this.subscription.add(i),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:i.add(_s(e,"progress").pipe(hL()).subscribe(s=>{t=s.loaded,r=ye()}));break;case 1:case 0:i.add(_s(e,"loadstart").subscribe(()=>{t=0,r=ye()}));break}i.add(_s(e,"loadend").subscribe(s=>{if(e.status===200){let n=s.loaded,o=ye(),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=ye(),n=0,o=ye(),u=c=>{this.concurrentDownloads.delete(e),r.releaseLock(),e.cancel(`Throughput Estimator error: ${c}`).catch(()=>{})},l=async({done:c,value:p})=>{if(c)!t&&this.addRawSpeed(i,ye()-s,1),this.concurrentDownloads.delete(e);else if(p){if(t){let d=ye();if(d-o>this.tuningConfig.lowLatency.continuesByteSequenceInterval||d-s>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let f=o-s;f&&this.addRawSpeed(n,f,1,t),n=p.byteLength,s=ye()}else n+=p.byteLength;o=ye()}else i+=p.byteLength,n+=p.byteLength,n>=this.tuningConfig.streamMinSampleSize&&ye()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,ye()-o,this.concurrentDownloads.size),n=0,o=ye());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=Xu.get(e);if(Ns(t))return(r=parseInt(t,10))!=null?r:void 0}},lS=Zu;import{fillWithDefault as SL,VideoQuality as cS}from"@vkontakte/videoplayer-shared";var dS={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,bitrateFactorAtFullBuffer:1.2,usePixelRatio:!0,limitByContainer:!0,containerSizeFactor:2,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldown:3e3,backgroundVideoQualityLimit:cS.Q_4320P,activeVideoAreaThreshold:.1},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:cS.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,requestQuick:!1,useHlsJs:!0,useDashAbortPartiallyFedSegment:!0,useNativeHLSTextTracks:!1,useManagedMediaSource:!1,useNewPruneBufferStrategy:!1,useNewPartialSegmentFeeding:!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{...SL(a,dS),configName:[...(e=a.configName)!=null?e:[],...dS.configName]}};import{assertNonNullable as Fs,combine as qs,ErrorCategory as Us,filter as oa,filterChanged as Le,fromEvent as tl,isNonNullable as PL,isNullable as wL,Logger as AL,map as B,mapTo as bS,merge as St,now as Hs,once as rt,Subject as H,Subscription as gS,tap as SS,ValueSubject as P,isHigher as kL,isInvariantQuality as vS}from"@vkontakte/videoplayer-shared";import{merge as vL,map as yL,filter as hS,isNonNullable as TL}from"@vkontakte/videoplayer-shared";var el=({seekState:a,position$:e})=>vL(a.stateChangeEnded$.pipe(yL(({to:t})=>{var r;return t.state==="none"?void 0:((r=t.position)!=null?r:NaN)/1e3}),hS(TL)),e.pipe(hS(()=>a.getState().state==="none")));import{assertNonNullable as IL}from"@vkontakte/videoplayer-shared";var fS=a=>{let e=typeof a.container=="string"?document.getElementById(a.container):a.container;return IL(e,`Wrong container or containerId {${a.container}}`),e};import{filter as EL,once as xL}from"@vkontakte/videoplayer-shared";var mS=(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(EL(i=>i.length>0),xL()).subscribe(i=>{i.find(r)&&e.startTransitionTo(a)}):(a===void 0||t!=null&&t.getValue().find(r))&&e.startTransitionTo(a)};var js=class{constructor(e={configName:[]}){this.subscription=new gS;this.logger=new AL;this.abrLogger=this.logger.createComponentLog("ABR");this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new P(!1);this.hasLiveOffsetByPausedTimer=0;this.desiredState={playbackState:new $("stopped"),seekState:new $({state:"none"}),volume:new $({volume:1,muted:!1}),videoTrack:new $(void 0),videoStream:new $(void 0),audioStream:new $(void 0),autoVideoTrackSwitching:new $(!0),autoVideoTrackLimits:new $({}),isLooped:new $(!1),playbackRate:new $(1),externalTextTracks:new $([]),internalTextTracks:new $([]),currentTextTrack:new $(void 0),textTrackCuesSettings:new $({}),cameraOrientation:new $({x:0,y:0})};this.info={playbackState$:new P("stopped"),position$:new P(0),duration$:new P(1/0),muted$:new P(!1),volume$:new P(1),availableVideoStreams$:new P([]),currentVideoStream$:new P(void 0),availableQualities$:new P([]),availableQualitiesFps$:new P({}),currentQuality$:new P(void 0),isAutoQualityEnabled$:new P(!0),autoQualityLimitingAvailable$:new P(!1),autoQualityLimits$:new P({}),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 H,ready$:new H,started$:new H,playing$:new H,paused$:new H,stopped$:new H,willStart$:new H,willResume$:new H,willPause$:new H,willStop$:new H,willDestruct$:new H,watchCoverageRecord$:new H,watchCoverageLive$:new H,managedError$:new H,fatalError$:new H,ended$:new H,looped$:new H,seeked$:new H,willSeek$:new H,firstBytes$:new H,loadedMetadata$:new H,firstFrame$:new H,canplay$:new H,log$:new H};this.experimental={element$:new P(void 0),tuningConfigName$:new P([]),enableDebugTelemetry$:new P(!1),dumpTelemetry:qm};if(this.initLogs(),this.tuning=pS(e),this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new ma({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new lS(this.tuning.throughputEstimator),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(t,r,i)=>{let s=Reflect.get(t,r,i);return typeof s!="function"?s:(...n)=>{try{return s.apply(t,n)}catch(o){let u=n.map(p=>JSON.stringify(p,(d,h)=>{let f=typeof h;return["number","string","boolean"].includes(f)?h:h===null?null:`<${f}>`})),l=`Player.${String(r)}`,c=`Exception calling ${l} (${u.join(", ")})`;throw this.events.fatalError$.next({id:l,category:Us.WTF,message:c,thrown:o}),o}}}})}initVideo(e){var t,r,i;return this.config=e,this.domContainer=fS(e),this.chromecastInitializer.contentId=(t=e.meta)==null?void 0:t.videoId,this.providerContainer=new na({sources:e.sources,meta:(r=e.meta)!=null?r:{},failoverHosts:(i=e.failoverHosts)!=null?i:[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,logger:this.logger,abrLogger:this.abrLogger},tuning:this.tuning,volumeMultiplier:e.volumeMultiplier}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.providerContainer.init(),this.setMuted(this.tuning.isAudioDisabled),this.initDebugTelemetry(),this.initWakeLock(),this}destroy(){var e;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()}prepare(){let e=this.desiredState.playbackState;return e.getState()==="stopped"&&e.startTransitionTo("ready"),this}play(){let e=()=>{let t=this.desiredState.playbackState;t.getState()!=="playing"&&t.startTransitionTo("playing")};return document.hidden&&this.tuning.autoplayOnlyInActiveTab&&!fi()?tl(document,"visibilitychange").pipe(rt()).subscribe(e):e(),this}pause(){let e=this.desiredState.playbackState;return e.getState()!=="paused"&&e.startTransitionTo("paused"),this}stop(){let e=this.desiredState.playbackState;return e.getState()!=="stopped"&&e.startTransitionTo("stopped"),this}seekTime(e,t=!0){let r=this.info.duration$.getValue(),i=this.info.isLive$.getValue();return e>=r&&!i&&(e=r-.1),this.events.willSeek$.next({from:this.getExactTime(),to:e}),this.desiredState.seekState.setState({state:"requested",position:e*1e3,forcePrecise:t}),this}seekPercent(e){let t=this.info.duration$.getValue();return isFinite(t)&&this.seekTime(Math.abs(t)*e,!1),this}setVolume(e){let t=this.tuning.isAudioDisabled||this.desiredState.volume.getState().muted;return 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.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){Fs(this.providerContainer);let t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();return this.desiredState.videoTrack.getState()===void 0&&this.desiredState.videoTrack.getPrevState()===void 0&&t.length===0?this.providerContainer.providerOutput.availableVideoTracks$.pipe(oa(r=>r.length>0),rt()).subscribe(r=>{this.setVideoTrackIdByQuality(r,e)}):t.length>0&&this.setVideoTrackIdByQuality(t,e),this}setAutoQuality(e){return this.desiredState.autoVideoTrackSwitching.startTransitionTo(e),this}setAutoQualityLimits(e){return this.desiredState.autoVideoTrackLimits.startTransitionTo(e),this}setPlaybackRate(e){var r;Fs(this.providerContainer);let t=(r=this.providerContainer)==null?void 0:r.providerOutput.element$.getValue();return t&&(this.desiredState.playbackRate.setState(e),t.playbackRate=e),this}setExternalTextTracks(e){return this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>({type:"external",...t}))),this}selectTextTrack(e){var t;return mS(e,this.desiredState.currentTextTrack,(t=this.providerContainer)==null?void 0:t.providerOutput.availableTextTracks$,r=>r.id===e),this}setTextTrackCueSettings(e){return this.desiredState.textTrackCuesSettings.startTransitionTo(e),this}setLooped(e){return this.desiredState.isLooped.startTransitionTo(e),this}toggleChromecast(){this.chromecastInitializer.toggleConnection()}startCameraManualRotation(e,t){let r=this.getScene3D();return r&&r.startCameraManualRotation(e,t),this}stopCameraManualRotation(e=!1){let t=this.getScene3D();return t&&t.stopCameraManualRotation(e),this}moveCameraFocusPX(e,t){let r=this.getScene3D();if(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(wL(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),r=t.state==="none"?void 0:t.position;return PL(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(St(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(B(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(B(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(B(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(B(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(B(e=>e.to)).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(oa(({from:e})=>e==="stopped"),rt()).subscribe(()=>{this.initedAt=Hs(),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();n.state==="requested"?this.desiredState.seekState.setState({...n,state:"applying"}):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:Us.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.seekedEvent$.subscribe(()=>{this.desiredState.seekState.getState().state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe(B(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(B(n=>n.destination),Le()).subscribe(()=>{this.isPlaybackStarted=!1})).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add(e.providerOutput.availableVideoTracks$.pipe(B(n=>n.map(({quality:o})=>o).sort((o,u)=>vS(o)?1:vS(u)?-1:kL(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$.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$.subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe(Le()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(Le()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(Le()).subscribe(this.info.httpConnectionReused$)).add(e.providerOutput.currentTextTrack$.subscribe(this.info.currentTextTrack$)).add(e.providerOutput.availableTextTracks$.subscribe(this.info.availableTextTracks$)).add(e.providerOutput.autoVideoTrackLimitingAvailable$.subscribe(this.info.autoQualityLimitingAvailable$)).add(e.providerOutput.autoVideoTrackLimits$.subscribe(n=>{this.desiredState.autoVideoTrackLimits.setState(n!=null?n:{})})).add(e.providerOutput.currentBuffer$.pipe(B(n=>n?{start:n.from,end:n.to}:{start:0,end:0})).subscribe(this.info.currentBuffer$)).add(e.providerOutput.duration$.subscribe(this.info.duration$)).add(e.providerOutput.isBuffering$.subscribe(this.info.isBuffering$)).add(e.providerOutput.isLive$.subscribe(this.info.isLive$)).add(e.providerOutput.canChangePlaybackSpeed$.subscribe(this.info.canChangePlaybackSpeed$)).add(e.providerOutput.liveTime$.subscribe(this.info.liveTime$)).add(e.providerOutput.liveBufferTime$.subscribe(this.info.liveBufferTime$)).add(qs({hasLiveOffsetByPaused:St(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(B(n=>n.to),Le(),B(n=>n==="paused")),isLowLatency:e.providerOutput.isLowLatency$}).subscribe(({hasLiveOffsetByPaused:n,isLowLatency:o})=>{if(window.clearTimeout(this.hasLiveOffsetByPausedTimer),n){this.hasLiveOffsetByPausedTimer=window.setTimeout(()=>{this.hasLiveOffsetByPaused.next(!0)},this.getActiveLiveDelay(o));return}this.hasLiveOffsetByPaused.next(!1)})).add(qs({atLiveEdge:qs({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:el({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(B(({isLive:n,position:o,isLowLatency:u})=>{let l=this.getActiveLiveDelay(u);return n&&Math.abs(o)<l/1e3}),Le(),SS(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(B(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add(qs({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(B(({isLive:n,position:o,duration:u})=>n&&(Math.abs(u)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),Le(),SS(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(B(n=>n.muted),Le()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(B(n=>n.volume),Le()).subscribe(this.info.volume$)).add(el({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(St(e.providerOutput.endedEvent$.pipe(bS(!0)),e.providerOutput.seekedEvent$.pipe(bS(!1))).pipe(Le()).subscribe(this.info.isEnded$)).add(e.providerOutput.endedEvent$.subscribe(this.events.ended$)).add(e.providerOutput.loopedEvent$.subscribe(this.events.looped$)).add(e.providerError$.subscribe(this.events.managedError$)).add(e.volumeMultiplierError$.subscribe(this.events.managedError$)).add(e.noAvailableProvidersError$.pipe(B(n=>({id:n?`No${n}`:"NoProviders",category:Us.VIDEO_PIPELINE,message:n?`${n} was forced but failed or not available`:"No suitable providers or all providers failed"}))).subscribe(this.events.fatalError$)).add(e.providerOutput.element$.subscribe(this.experimental.element$)).add(e.providerOutput.firstBytesEvent$.pipe(rt(),B(n=>n!=null?n:Hs()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe(rt(),B(()=>Hs()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(rt(),B(()=>Hs()-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(oa(({to:n})=>n==="playing"),rt()).subscribe(()=>r.next(!1)));let i=0,s=St(e.providerOutput.isBuffering$,t,r).pipe(B(()=>{let n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||r.getValue();return n&&!o}),Le());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(St(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(St(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(),p;c==="CONNECTED"?p="second_screen":u?l?n?p="pip":o?p="fullscreen":p="inline":p="invisible":p="none",this.info.surface$.getValue()!==p&&this.info.surface$.next(p)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(B(e=>e==null?void 0:e.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){let t=new gS;this.subscription.add(t),this.subscription.add(e.current$.pipe(Le((r,i)=>r.provider===i.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(oa(r=>r.length>0),rt()).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=ft(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(St(this.desiredState.videoTrack.stateChangeStarted$.pipe(B(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(B(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(B(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(B(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(B(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(B(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(B(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(B(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(B(e=>({component:"desiredState",message:`[${e.entity} change] ${e.type}: ${JSON.stringify(e.transition)}`}))).subscribe(this.logger.log)),this.subscription.add(this.logger.log$.subscribe(this.events.log$))}initDebugTelemetry(){var t;let e=(t=this.providerContainer)==null?void 0:t.providerOutput;Fs(this.providerContainer),Fs(e),Fm(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(r=>Nm(r)),this.providerContainer.current$.subscribe(({type:r})=>li("provider",r)),e.duration$.subscribe(r=>li("duration",r)),e.availableVideoTracks$.pipe(oa(r=>!!r.length),rt()).subscribe(r=>li("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(B(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)),li("codecs",Sb())}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:Us.DOM,message:String(i)})})};this.subscription.add(St(tl(document,"visibilitychange"),tl(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);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 sG,Observable as nG,Subject as oG,ValueSubject as uG,VideoQuality as lG}from"@vkontakte/videoplayer-shared";var cG=`@vkontakte/videoplayer-core@${Al}`;export{ha as ChromecastState,sn as HttpConnectionType,nG as Observable,ne as PlaybackState,js as Player,cG as SDK_VERSION,oG as Subject,sG as Subscription,nn as Surface,Al as VERSION,uG as ValueSubject,ot as VideoFormat,lG as VideoQuality};
|