@vkontakte/videoplayer-core 2.0.108-dev.2cb388c2.0 → 2.0.108-dev.34728b10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/es2015.esm.js CHANGED
@@ -1,10 +1,13 @@
1
1
  /**
2
- * @vkontakte/videoplayer-core v2.0.108-dev.2cb388c2.0
3
- * Tue, 03 Sep 2024 00:40:34 GMT
2
+ * @vkontakte/videoplayer-core v2.0.108-dev.34728b10.0
3
+ * Fri, 06 Sep 2024 07:12:12 GMT
4
4
  * https://st.mycdn.me/static/vkontakte-videoplayer/2-0-108/doc/
5
5
  */
6
- var zS=Object.create;var dn=Object.defineProperty,KS=Object.defineProperties,JS=Object.getOwnPropertyDescriptor,XS=Object.getOwnPropertyDescriptors,ZS=Object.getOwnPropertyNames,Ml=Object.getOwnPropertySymbols,ev=Object.getPrototypeOf,Dl=Object.prototype.hasOwnProperty,tv=Object.prototype.propertyIsEnumerable;var rv=(a,e)=>(e=Symbol[a])?e:Symbol.for("Symbol."+a);var je=Math.pow,Cl=(a,e,t)=>e in a?dn(a,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):a[e]=t,R=(a,e)=>{for(var t in e||(e={}))Dl.call(e,t)&&Cl(a,t,e[t]);if(Ml)for(var t of Ml(e))tv.call(e,t)&&Cl(a,t,e[t]);return a},q=(a,e)=>KS(a,XS(e));var m=(a,e)=>()=>(e||a((e={exports:{}}).exports,e),e.exports);var iv=(a,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of ZS(e))!Dl.call(a,i)&&i!==t&&dn(a,i,{get:()=>e[i],enumerable:!(r=JS(e,i))||r.enumerable});return a};var Ge=(a,e,t)=>(t=a!=null?zS(ev(a)):{},iv(e||!a||!a.__esModule?dn(t,"default",{value:a,enumerable:!0}):t,a));var A=(a,e,t)=>new Promise((r,i)=>{var s=u=>{try{o(t.next(u))}catch(l){i(l)}},n=u=>{try{o(t.throw(u))}catch(l){i(l)}},o=u=>u.done?r(u.value):Promise.resolve(u.value).then(s,n);o((t=t.apply(a,e)).next())}),av=function(a,e){this[0]=a,this[1]=e},te=(a,e,t)=>{var r=(n,o,u,l)=>{try{var c=t[n](o),d=(o=c.value)instanceof av,p=c.done;Promise.resolve(d?o[0]:o).then(h=>d?r(n==="return"?n:"next",o[1]?{done:h.done,value:h.value}:h,u,l):u({value:h,done:p})).catch(h=>r("throw",h,u,l))}catch(h){l(h)}},i=n=>s[n]=o=>new Promise((u,l)=>r(n,o,u,l)),s={};return t=t.apply(a,e),s[rv("asyncIterator")]=()=>s,i("next"),i("throw"),i("return"),s};var ye=m((t$,Ul)=>{"use strict";Ul.exports=function(a){try{return!!a()}catch(e){return!0}}});var Fr=m((r$,Hl)=>{"use strict";var pv=ye();Hl.exports=!pv(function(){var a=function(){}.bind();return typeof a!="function"||a.hasOwnProperty("prototype")})});var de=m((i$,Yl)=>{"use strict";var jl=Fr(),Gl=Function.prototype,bn=Gl.call,hv=jl&&Gl.bind.bind(bn,bn);Yl.exports=jl?hv:function(a){return function(){return bn.apply(a,arguments)}}});var rr=m((a$,Ql)=>{"use strict";var Wl=de(),fv=Wl({}.toString),mv=Wl("".slice);Ql.exports=function(a){return mv(fv(a),8,-1)}});var Kl=m((s$,zl)=>{"use strict";var bv=de(),gv=ye(),Sv=rr(),gn=Object,vv=bv("".split);zl.exports=gv(function(){return!gn("z").propertyIsEnumerable(0)})?function(a){return Sv(a)==="String"?vv(a,""):gn(a)}:gn});var ir=m((n$,Jl)=>{"use strict";Jl.exports=function(a){return a==null}});var qr=m((o$,Xl)=>{"use strict";var yv=ir(),Tv=TypeError;Xl.exports=function(a){if(yv(a))throw new Tv("Can't call method on "+a);return a}});var ar=m((u$,Zl)=>{"use strict";var Iv=Kl(),Ev=qr();Zl.exports=function(a){return Iv(Ev(a))}});var Sn=m((l$,ec)=>{"use strict";ec.exports=function(){}});var Lt=m((c$,tc)=>{"use strict";tc.exports={}});var K=m((vn,rc)=>{"use strict";var Ur=function(a){return a&&a.Math===Math&&a};rc.exports=Ur(typeof globalThis=="object"&&globalThis)||Ur(typeof window=="object"&&window)||Ur(typeof self=="object"&&self)||Ur(typeof global=="object"&&global)||Ur(typeof vn=="object"&&vn)||function(){return this}()||Function("return this")()});var z=m((d$,ic)=>{"use strict";var yn=typeof document=="object"&&document.all;ic.exports=typeof yn=="undefined"&&yn!==void 0?function(a){return typeof a=="function"||a===yn}:function(a){return typeof a=="function"}});var nc=m((p$,sc)=>{"use strict";var xv=K(),Pv=z(),ac=xv.WeakMap;sc.exports=Pv(ac)&&/native code/.test(String(ac))});var we=m((h$,oc)=>{"use strict";var wv=z();oc.exports=function(a){return typeof a=="object"?a!==null:wv(a)}});var Ae=m((f$,uc)=>{"use strict";var Av=ye();uc.exports=!Av(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var Ta=m((m$,cc)=>{"use strict";var kv=K(),lc=we(),Tn=kv.document,Rv=lc(Tn)&&lc(Tn.createElement);cc.exports=function(a){return Rv?Tn.createElement(a):{}}});var In=m((b$,dc)=>{"use strict";var Lv=Ae(),$v=ye(),Mv=Ta();dc.exports=!Lv&&!$v(function(){return Object.defineProperty(Mv("div"),"a",{get:function(){return 7}}).a!==7})});var En=m((g$,pc)=>{"use strict";var Cv=Ae(),Dv=ye();pc.exports=Cv&&Dv(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var Ye=m((S$,hc)=>{"use strict";var Ov=we(),Bv=String,Vv=TypeError;hc.exports=function(a){if(Ov(a))return a;throw new Vv(Bv(a)+" is not an object")}});var Te=m((v$,fc)=>{"use strict";var _v=Fr(),Ia=Function.prototype.call;fc.exports=_v?Ia.bind(Ia):function(){return Ia.apply(Ia,arguments)}});var Ea=m((y$,mc)=>{"use strict";mc.exports={}});var Ke=m((T$,gc)=>{"use strict";var xn=Ea(),Pn=K(),Nv=z(),bc=function(a){return Nv(a)?a:void 0};gc.exports=function(a,e){return arguments.length<2?bc(xn[a])||bc(Pn[a]):xn[a]&&xn[a][e]||Pn[a]&&Pn[a][e]}});var Hr=m((I$,Sc)=>{"use strict";var Fv=de();Sc.exports=Fv({}.isPrototypeOf)});var sr=m((E$,Tc)=>{"use strict";var qv=K(),vc=qv.navigator,yc=vc&&vc.userAgent;Tc.exports=yc?String(yc):""});var An=m((x$,Ac)=>{"use strict";var wc=K(),wn=sr(),Ic=wc.process,Ec=wc.Deno,xc=Ic&&Ic.versions||Ec&&Ec.version,Pc=xc&&xc.v8,Be,xa;Pc&&(Be=Pc.split("."),xa=Be[0]>0&&Be[0]<4?1:+(Be[0]+Be[1]));!xa&&wn&&(Be=wn.match(/Edge\/(\d+)/),(!Be||Be[1]>=74)&&(Be=wn.match(/Chrome\/(\d+)/),Be&&(xa=+Be[1])));Ac.exports=xa});var kn=m((P$,Rc)=>{"use strict";var kc=An(),Uv=ye(),Hv=K(),jv=Hv.String;Rc.exports=!!Object.getOwnPropertySymbols&&!Uv(function(){var a=Symbol("symbol detection");return!jv(a)||!(Object(a)instanceof Symbol)||!Symbol.sham&&kc&&kc<41})});var Rn=m((w$,Lc)=>{"use strict";var Gv=kn();Lc.exports=Gv&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var Ln=m((A$,$c)=>{"use strict";var Yv=Ke(),Wv=z(),Qv=Hr(),zv=Rn(),Kv=Object;$c.exports=zv?function(a){return typeof a=="symbol"}:function(a){var e=Yv("Symbol");return Wv(e)&&Qv(e.prototype,Kv(a))}});var jr=m((k$,Mc)=>{"use strict";var Jv=String;Mc.exports=function(a){try{return Jv(a)}catch(e){return"Object"}}});var Je=m((R$,Cc)=>{"use strict";var Xv=z(),Zv=jr(),ey=TypeError;Cc.exports=function(a){if(Xv(a))return a;throw new ey(Zv(a)+" is not a function")}});var Gr=m((L$,Dc)=>{"use strict";var ty=Je(),ry=ir();Dc.exports=function(a,e){var t=a[e];return ry(t)?void 0:ty(t)}});var Bc=m(($$,Oc)=>{"use strict";var $n=Te(),Mn=z(),Cn=we(),iy=TypeError;Oc.exports=function(a,e){var t,r;if(e==="string"&&Mn(t=a.toString)&&!Cn(r=$n(t,a))||Mn(t=a.valueOf)&&!Cn(r=$n(t,a))||e!=="string"&&Mn(t=a.toString)&&!Cn(r=$n(t,a)))return r;throw new iy("Can't convert object to primitive value")}});var Ve=m((M$,Vc)=>{"use strict";Vc.exports=!0});var Fc=m((C$,Nc)=>{"use strict";var _c=K(),ay=Object.defineProperty;Nc.exports=function(a,e){try{ay(_c,a,{value:e,configurable:!0,writable:!0})}catch(t){_c[a]=e}return e}});var Yr=m((D$,Hc)=>{"use strict";var sy=Ve(),ny=K(),oy=Fc(),qc="__core-js_shared__",Uc=Hc.exports=ny[qc]||oy(qc,{});(Uc.versions||(Uc.versions=[])).push({version:"3.38.0",mode:sy?"pure":"global",copyright:"\xA9 2014-2024 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.38.0/LICENSE",source:"https://github.com/zloirock/core-js"})});var Dn=m((O$,Gc)=>{"use strict";var jc=Yr();Gc.exports=function(a,e){return jc[a]||(jc[a]=e||{})}});var Wr=m((B$,Yc)=>{"use strict";var uy=qr(),ly=Object;Yc.exports=function(a){return ly(uy(a))}});var _e=m((V$,Wc)=>{"use strict";var cy=de(),dy=Wr(),py=cy({}.hasOwnProperty);Wc.exports=Object.hasOwn||function(e,t){return py(dy(e),t)}});var On=m((_$,Qc)=>{"use strict";var hy=de(),fy=0,my=Math.random(),by=hy(1 .toString);Qc.exports=function(a){return"Symbol("+(a===void 0?"":a)+")_"+by(++fy+my,36)}});var se=m((N$,Kc)=>{"use strict";var gy=K(),Sy=Dn(),zc=_e(),vy=On(),yy=kn(),Ty=Rn(),nr=gy.Symbol,Bn=Sy("wks"),Iy=Ty?nr.for||nr:nr&&nr.withoutSetter||vy;Kc.exports=function(a){return zc(Bn,a)||(Bn[a]=yy&&zc(nr,a)?nr[a]:Iy("Symbol."+a)),Bn[a]}});var ed=m((F$,Zc)=>{"use strict";var Ey=Te(),Jc=we(),Xc=Ln(),xy=Gr(),Py=Bc(),wy=se(),Ay=TypeError,ky=wy("toPrimitive");Zc.exports=function(a,e){if(!Jc(a)||Xc(a))return a;var t=xy(a,ky),r;if(t){if(e===void 0&&(e="default"),r=Ey(t,a,e),!Jc(r)||Xc(r))return r;throw new Ay("Can't convert object to primitive value")}return e===void 0&&(e="number"),Py(a,e)}});var Vn=m((q$,td)=>{"use strict";var Ry=ed(),Ly=Ln();td.exports=function(a){var e=Ry(a,"string");return Ly(e)?e:e+""}});var $t=m(id=>{"use strict";var $y=Ae(),My=In(),Cy=En(),Pa=Ye(),rd=Vn(),Dy=TypeError,_n=Object.defineProperty,Oy=Object.getOwnPropertyDescriptor,Nn="enumerable",Fn="configurable",qn="writable";id.f=$y?Cy?function(e,t,r){if(Pa(e),t=rd(t),Pa(r),typeof e=="function"&&t==="prototype"&&"value"in r&&qn in r&&!r[qn]){var i=Oy(e,t);i&&i[qn]&&(e[t]=r.value,r={configurable:Fn in r?r[Fn]:i[Fn],enumerable:Nn in r?r[Nn]:i[Nn],writable:!1})}return _n(e,t,r)}:_n:function(e,t,r){if(Pa(e),t=rd(t),Pa(r),My)try{return _n(e,t,r)}catch(i){}if("get"in r||"set"in r)throw new Dy("Accessors not supported");return"value"in r&&(e[t]=r.value),e}});var Qr=m((H$,ad)=>{"use strict";ad.exports=function(a,e){return{enumerable:!(a&1),configurable:!(a&2),writable:!(a&4),value:e}}});var or=m((j$,sd)=>{"use strict";var By=Ae(),Vy=$t(),_y=Qr();sd.exports=By?function(a,e,t){return Vy.f(a,e,_y(1,t))}:function(a,e,t){return a[e]=t,a}});var wa=m((G$,od)=>{"use strict";var Ny=Dn(),Fy=On(),nd=Ny("keys");od.exports=function(a){return nd[a]||(nd[a]=Fy(a))}});var Aa=m((Y$,ud)=>{"use strict";ud.exports={}});var Gn=m((W$,dd)=>{"use strict";var qy=nc(),cd=K(),Uy=we(),Hy=or(),Un=_e(),Hn=Yr(),jy=wa(),Gy=Aa(),ld="Object already initialized",jn=cd.TypeError,Yy=cd.WeakMap,ka,zr,Ra,Wy=function(a){return Ra(a)?zr(a):ka(a,{})},Qy=function(a){return function(e){var t;if(!Uy(e)||(t=zr(e)).type!==a)throw new jn("Incompatible receiver, "+a+" required");return t}};qy||Hn.state?(Ne=Hn.state||(Hn.state=new Yy),Ne.get=Ne.get,Ne.has=Ne.has,Ne.set=Ne.set,ka=function(a,e){if(Ne.has(a))throw new jn(ld);return e.facade=a,Ne.set(a,e),e},zr=function(a){return Ne.get(a)||{}},Ra=function(a){return Ne.has(a)}):(Mt=jy("state"),Gy[Mt]=!0,ka=function(a,e){if(Un(a,Mt))throw new jn(ld);return e.facade=a,Hy(a,Mt,e),e},zr=function(a){return Un(a,Mt)?a[Mt]:{}},Ra=function(a){return Un(a,Mt)});var Ne,Mt;dd.exports={set:ka,get:zr,has:Ra,enforce:Wy,getterFor:Qy}});var Yn=m((Q$,md)=>{"use strict";var zy=Fr(),fd=Function.prototype,pd=fd.apply,hd=fd.call;md.exports=typeof Reflect=="object"&&Reflect.apply||(zy?hd.bind(pd):function(){return hd.apply(pd,arguments)})});var Wn=m((z$,bd)=>{"use strict";var Ky=rr(),Jy=de();bd.exports=function(a){if(Ky(a)==="Function")return Jy(a)}});var yd=m(vd=>{"use strict";var gd={}.propertyIsEnumerable,Sd=Object.getOwnPropertyDescriptor,Xy=Sd&&!gd.call({1:2},1);vd.f=Xy?function(e){var t=Sd(this,e);return!!t&&t.enumerable}:gd});var Ed=m(Id=>{"use strict";var Zy=Ae(),eT=Te(),tT=yd(),rT=Qr(),iT=ar(),aT=Vn(),sT=_e(),nT=In(),Td=Object.getOwnPropertyDescriptor;Id.f=Zy?Td:function(e,t){if(e=iT(e),t=aT(t),nT)try{return Td(e,t)}catch(r){}if(sT(e,t))return rT(!eT(tT.f,e,t),e[t])}});var Qn=m((X$,xd)=>{"use strict";var oT=ye(),uT=z(),lT=/#|\.prototype\./,Kr=function(a,e){var t=dT[cT(a)];return t===hT?!0:t===pT?!1:uT(e)?oT(e):!!e},cT=Kr.normalize=function(a){return String(a).replace(lT,".").toLowerCase()},dT=Kr.data={},pT=Kr.NATIVE="N",hT=Kr.POLYFILL="P";xd.exports=Kr});var Jr=m((Z$,wd)=>{"use strict";var Pd=Wn(),fT=Je(),mT=Fr(),bT=Pd(Pd.bind);wd.exports=function(a,e){return fT(a),e===void 0?a:mT?bT(a,e):function(){return a.apply(e,arguments)}}});var ke=m((eM,kd)=>{"use strict";var Xr=K(),gT=Yn(),ST=Wn(),vT=z(),yT=Ed().f,TT=Qn(),ur=Ea(),IT=Jr(),lr=or(),Ad=_e();Yr();var ET=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 gT(a,this,arguments)};return e.prototype=a.prototype,e};kd.exports=function(a,e){var t=a.target,r=a.global,i=a.stat,s=a.proto,n=r?Xr:i?Xr[t]:Xr[t]&&Xr[t].prototype,o=r?ur:ur[t]||lr(ur,t,{})[t],u=o.prototype,l,c,d,p,h,f,b,g,S;for(p in e)l=TT(r?p:t+(i?".":"#")+p,a.forced),c=!l&&n&&Ad(n,p),f=o[p],c&&(a.dontCallGetSet?(S=yT(n,p),b=S&&S.value):b=n[p]),h=c&&b?b:e[p],!(!l&&!s&&typeof f==typeof h)&&(a.bind&&c?g=IT(h,Xr):a.wrap&&c?g=ET(h):s&&vT(h)?g=ST(h):g=h,(a.sham||h&&h.sham||f&&f.sham)&&lr(g,"sham",!0),lr(o,p,g),s&&(d=t+"Prototype",Ad(ur,d)||lr(ur,d,{}),lr(ur[d],p,h),a.real&&u&&(l||!u[p])&&lr(u,p,h)))}});var $d=m((tM,Ld)=>{"use strict";var zn=Ae(),xT=_e(),Rd=Function.prototype,PT=zn&&Object.getOwnPropertyDescriptor,Kn=xT(Rd,"name"),wT=Kn&&function(){}.name==="something",AT=Kn&&(!zn||zn&&PT(Rd,"name").configurable);Ld.exports={EXISTS:Kn,PROPER:wT,CONFIGURABLE:AT}});var Cd=m((rM,Md)=>{"use strict";var kT=Math.ceil,RT=Math.floor;Md.exports=Math.trunc||function(e){var t=+e;return(t>0?RT:kT)(t)}});var La=m((iM,Dd)=>{"use strict";var LT=Cd();Dd.exports=function(a){var e=+a;return e!==e||e===0?0:LT(e)}});var Bd=m((aM,Od)=>{"use strict";var $T=La(),MT=Math.max,CT=Math.min;Od.exports=function(a,e){var t=$T(a);return t<0?MT(t+e,0):CT(t,e)}});var _d=m((sM,Vd)=>{"use strict";var DT=La(),OT=Math.min;Vd.exports=function(a){var e=DT(a);return e>0?OT(e,9007199254740991):0}});var $a=m((nM,Nd)=>{"use strict";var BT=_d();Nd.exports=function(a){return BT(a.length)}});var Ud=m((oM,qd)=>{"use strict";var VT=ar(),_T=Bd(),NT=$a(),Fd=function(a){return function(e,t,r){var i=VT(e),s=NT(i);if(s===0)return!a&&-1;var n=_T(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}};qd.exports={includes:Fd(!0),indexOf:Fd(!1)}});var Gd=m((uM,jd)=>{"use strict";var FT=de(),Jn=_e(),qT=ar(),UT=Ud().indexOf,HT=Aa(),Hd=FT([].push);jd.exports=function(a,e){var t=qT(a),r=0,i=[],s;for(s in t)!Jn(HT,s)&&Jn(t,s)&&Hd(i,s);for(;e.length>r;)Jn(t,s=e[r++])&&(~UT(i,s)||Hd(i,s));return i}});var Xn=m((lM,Yd)=>{"use strict";Yd.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var Qd=m((cM,Wd)=>{"use strict";var jT=Gd(),GT=Xn();Wd.exports=Object.keys||function(e){return jT(e,GT)}});var Kd=m(zd=>{"use strict";var YT=Ae(),WT=En(),QT=$t(),zT=Ye(),KT=ar(),JT=Qd();zd.f=YT&&!WT?Object.defineProperties:function(e,t){zT(e);for(var r=KT(t),i=JT(t),s=i.length,n=0,o;s>n;)QT.f(e,o=i[n++],r[o]);return e}});var Zn=m((pM,Jd)=>{"use strict";var XT=Ke();Jd.exports=XT("document","documentElement")});var io=m((hM,ap)=>{"use strict";var ZT=Ye(),eI=Kd(),Xd=Xn(),tI=Aa(),rI=Zn(),iI=Ta(),aI=wa(),Zd=">",ep="<",to="prototype",ro="script",rp=aI("IE_PROTO"),eo=function(){},ip=function(a){return ep+ro+Zd+a+ep+"/"+ro+Zd},tp=function(a){a.write(ip("")),a.close();var e=a.parentWindow.Object;return a=null,e},sI=function(){var a=iI("iframe"),e="java"+ro+":",t;return a.style.display="none",rI.appendChild(a),a.src=String(e),t=a.contentWindow.document,t.open(),t.write(ip("document.F=Object")),t.close(),t.F},Ma,Ca=function(){try{Ma=new ActiveXObject("htmlfile")}catch(e){}Ca=typeof document!="undefined"?document.domain&&Ma?tp(Ma):sI():tp(Ma);for(var a=Xd.length;a--;)delete Ca[to][Xd[a]];return Ca()};tI[rp]=!0;ap.exports=Object.create||function(e,t){var r;return e!==null?(eo[to]=ZT(e),r=new eo,eo[to]=null,r[rp]=e):r=Ca(),t===void 0?r:eI.f(r,t)}});var np=m((fM,sp)=>{"use strict";var nI=ye();sp.exports=!nI(function(){function a(){}return a.prototype.constructor=null,Object.getPrototypeOf(new a)!==a.prototype})});var so=m((mM,up)=>{"use strict";var oI=_e(),uI=z(),lI=Wr(),cI=wa(),dI=np(),op=cI("IE_PROTO"),ao=Object,pI=ao.prototype;up.exports=dI?ao.getPrototypeOf:function(a){var e=lI(a);if(oI(e,op))return e[op];var t=e.constructor;return uI(t)&&e instanceof t?t.prototype:e instanceof ao?pI:null}});var cr=m((bM,lp)=>{"use strict";var hI=or();lp.exports=function(a,e,t,r){return r&&r.enumerable?a[e]=t:hI(a,e,t),a}});var lo=m((gM,pp)=>{"use strict";var fI=ye(),mI=z(),bI=we(),gI=io(),cp=so(),SI=cr(),vI=se(),yI=Ve(),uo=vI("iterator"),dp=!1,Xe,no,oo;[].keys&&(oo=[].keys(),"next"in oo?(no=cp(cp(oo)),no!==Object.prototype&&(Xe=no)):dp=!0);var TI=!bI(Xe)||fI(function(){var a={};return Xe[uo].call(a)!==a});TI?Xe={}:yI&&(Xe=gI(Xe));mI(Xe[uo])||SI(Xe,uo,function(){return this});pp.exports={IteratorPrototype:Xe,BUGGY_SAFARI_ITERATORS:dp}});var Da=m((SM,fp)=>{"use strict";var II=se(),EI=II("toStringTag"),hp={};hp[EI]="z";fp.exports=String(hp)==="[object z]"});var Zr=m((vM,mp)=>{"use strict";var xI=Da(),PI=z(),Oa=rr(),wI=se(),AI=wI("toStringTag"),kI=Object,RI=Oa(function(){return arguments}())==="Arguments",LI=function(a,e){try{return a[e]}catch(t){}};mp.exports=xI?Oa:function(a){var e,t,r;return a===void 0?"Undefined":a===null?"Null":typeof(t=LI(e=kI(a),AI))=="string"?t:RI?Oa(e):(r=Oa(e))==="Object"&&PI(e.callee)?"Arguments":r}});var gp=m((yM,bp)=>{"use strict";var $I=Da(),MI=Zr();bp.exports=$I?{}.toString:function(){return"[object "+MI(this)+"]"}});var ei=m((TM,vp)=>{"use strict";var CI=Da(),DI=$t().f,OI=or(),BI=_e(),VI=gp(),_I=se(),Sp=_I("toStringTag");vp.exports=function(a,e,t,r){var i=t?a:a&&a.prototype;i&&(BI(i,Sp)||DI(i,Sp,{configurable:!0,value:e}),r&&!CI&&OI(i,"toString",VI))}});var Tp=m((IM,yp)=>{"use strict";var NI=lo().IteratorPrototype,FI=io(),qI=Qr(),UI=ei(),HI=Lt(),jI=function(){return this};yp.exports=function(a,e,t,r){var i=e+" Iterator";return a.prototype=FI(NI,{next:qI(+!r,t)}),UI(a,i,!1,!0),HI[i]=jI,a}});var Ep=m((EM,Ip)=>{"use strict";var GI=de(),YI=Je();Ip.exports=function(a,e,t){try{return GI(YI(Object.getOwnPropertyDescriptor(a,e)[t]))}catch(r){}}});var Pp=m((xM,xp)=>{"use strict";var WI=we();xp.exports=function(a){return WI(a)||a===null}});var Ap=m((PM,wp)=>{"use strict";var QI=Pp(),zI=String,KI=TypeError;wp.exports=function(a){if(QI(a))return a;throw new KI("Can't set "+zI(a)+" as a prototype")}});var co=m((wM,kp)=>{"use strict";var JI=Ep(),XI=we(),ZI=qr(),eE=Ap();kp.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var a=!1,e={},t;try{t=JI(Object.prototype,"__proto__","set"),t(e,[]),a=e instanceof Array}catch(r){}return function(i,s){return ZI(i),eE(s),XI(i)&&(a?t(i,s):i.__proto__=s),i}}():void 0)});var Np=m((AM,_p)=>{"use strict";var tE=ke(),rE=Te(),Ba=Ve(),Bp=$d(),iE=z(),aE=Tp(),Rp=so(),Lp=co(),sE=ei(),nE=or(),po=cr(),oE=se(),$p=Lt(),Vp=lo(),uE=Bp.PROPER,lE=Bp.CONFIGURABLE,Mp=Vp.IteratorPrototype,Va=Vp.BUGGY_SAFARI_ITERATORS,ti=oE("iterator"),Cp="keys",ri="values",Dp="entries",Op=function(){return this};_p.exports=function(a,e,t,r,i,s,n){aE(t,e,r);var o=function(S){if(S===i&&p)return p;if(!Va&&S&&S in c)return c[S];switch(S){case Cp:return function(){return new t(this,S)};case ri:return function(){return new t(this,S)};case Dp:return function(){return new t(this,S)}}return function(){return new t(this)}},u=e+" Iterator",l=!1,c=a.prototype,d=c[ti]||c["@@iterator"]||i&&c[i],p=!Va&&d||o(i),h=e==="Array"&&c.entries||d,f,b,g;if(h&&(f=Rp(h.call(new a)),f!==Object.prototype&&f.next&&(!Ba&&Rp(f)!==Mp&&(Lp?Lp(f,Mp):iE(f[ti])||po(f,ti,Op)),sE(f,u,!0,!0),Ba&&($p[u]=Op))),uE&&i===ri&&d&&d.name!==ri&&(!Ba&&lE?nE(c,"name",ri):(l=!0,p=function(){return rE(d,this)})),i)if(b={values:o(ri),keys:s?p:o(Cp),entries:o(Dp)},n)for(g in b)(Va||l||!(g in c))&&po(c,g,b[g]);else tE({target:e,proto:!0,forced:Va||l},b);return(!Ba||n)&&c[ti]!==p&&po(c,ti,p,{name:i}),$p[e]=p,b}});var qp=m((kM,Fp)=>{"use strict";Fp.exports=function(a,e){return{value:a,done:e}}});var fo=m((RM,Yp)=>{"use strict";var cE=ar(),ho=Sn(),Up=Lt(),jp=Gn(),dE=$t().f,pE=Np(),_a=qp(),hE=Ve(),fE=Ae(),Gp="Array Iterator",mE=jp.set,bE=jp.getterFor(Gp);Yp.exports=pE(Array,"Array",function(a,e){mE(this,{type:Gp,target:cE(a),index:0,kind:e})},function(){var a=bE(this),e=a.target,t=a.index++;if(!e||t>=e.length)return a.target=void 0,_a(void 0,!0);switch(a.kind){case"keys":return _a(t,!1);case"values":return _a(e[t],!1)}return _a([t,e[t]],!1)},"values");var Hp=Up.Arguments=Up.Array;ho("keys");ho("values");ho("entries");if(!hE&&fE&&Hp.name!=="values")try{dE(Hp,"name",{value:"values"})}catch(a){}});var Qp=m((LM,Wp)=>{"use strict";var gE=se(),SE=Lt(),vE=gE("iterator"),yE=Array.prototype;Wp.exports=function(a){return a!==void 0&&(SE.Array===a||yE[vE]===a)}});var mo=m(($M,Kp)=>{"use strict";var TE=Zr(),zp=Gr(),IE=ir(),EE=Lt(),xE=se(),PE=xE("iterator");Kp.exports=function(a){if(!IE(a))return zp(a,PE)||zp(a,"@@iterator")||EE[TE(a)]}});var Xp=m((MM,Jp)=>{"use strict";var wE=Te(),AE=Je(),kE=Ye(),RE=jr(),LE=mo(),$E=TypeError;Jp.exports=function(a,e){var t=arguments.length<2?LE(a):e;if(AE(t))return kE(wE(t,a));throw new $E(RE(a)+" is not iterable")}});var th=m((CM,eh)=>{"use strict";var ME=Te(),Zp=Ye(),CE=Gr();eh.exports=function(a,e,t){var r,i;Zp(a);try{if(r=CE(a,"return"),!r){if(e==="throw")throw t;return t}r=ME(r,a)}catch(s){i=!0,r=s}if(e==="throw")throw t;if(i)throw r;return Zp(r),t}});var Fa=m((DM,sh)=>{"use strict";var DE=Jr(),OE=Te(),BE=Ye(),VE=jr(),_E=Qp(),NE=$a(),rh=Hr(),FE=Xp(),qE=mo(),ih=th(),UE=TypeError,Na=function(a,e){this.stopped=a,this.result=e},ah=Na.prototype;sh.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=DE(e,r),l,c,d,p,h,f,b,g=function(I){return l&&ih(l,"normal",I),new Na(!0,I)},S=function(I){return i?(BE(I),o?u(I[0],I[1],g):u(I[0],I[1])):o?u(I,g):u(I)};if(s)l=a.iterator;else if(n)l=a;else{if(c=qE(a),!c)throw new UE(VE(a)+" is not iterable");if(_E(c)){for(d=0,p=NE(a);p>d;d++)if(h=S(a[d]),h&&rh(ah,h))return h;return new Na(!1)}l=FE(a,c)}for(f=s?a.next:l.next;!(b=OE(f,l)).done;){try{h=S(b.value)}catch(I){ih(l,"throw",I)}if(typeof h=="object"&&h&&rh(ah,h))return h}return new Na(!1)}});var oh=m((OM,nh)=>{"use strict";var HE=Ae(),jE=$t(),GE=Qr();nh.exports=function(a,e,t){HE?jE.f(a,e,GE(0,t)):a[e]=t}});var uh=m(()=>{"use strict";var YE=ke(),WE=Fa(),QE=oh();YE({target:"Object",stat:!0},{fromEntries:function(e){var t={};return WE(e,function(r,i){QE(t,r,i)},{AS_ENTRIES:!0}),t}})});var ch=m((_M,lh)=>{"use strict";fo();uh();var zE=Ea();lh.exports=zE.Object.fromEntries});var ph=m((NM,dh)=>{"use strict";dh.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 fh=m(()=>{"use strict";fo();var KE=ph(),JE=K(),XE=ei(),hh=Lt();for(qa in KE)XE(JE[qa],qa),hh[qa]=hh.Array;var qa});var bh=m((UM,mh)=>{"use strict";var ZE=ch();fh();mh.exports=ZE});var bo=m((HM,gh)=>{"use strict";var ex=bh();gh.exports=ex});var Sh=m(()=>{"use strict"});var go=m((YM,vh)=>{"use strict";var ii=K(),tx=sr(),rx=rr(),Ua=function(a){return tx.slice(0,a.length)===a};vh.exports=function(){return Ua("Bun/")?"BUN":Ua("Cloudflare-Workers")?"CLOUDFLARE":Ua("Deno/")?"DENO":Ua("Node.js/")?"NODE":ii.Bun&&typeof Bun.version=="string"?"BUN":ii.Deno&&typeof Deno.version=="object"?"DENO":rx(ii.process)==="process"?"NODE":ii.window&&ii.document?"BROWSER":"REST"}()});var Ha=m((WM,yh)=>{"use strict";var ix=go();yh.exports=ix==="NODE"});var Ih=m((QM,Th)=>{"use strict";var ax=$t();Th.exports=function(a,e,t){return ax.f(a,e,t)}});var Ph=m((zM,xh)=>{"use strict";var sx=Ke(),nx=Ih(),ox=se(),ux=Ae(),Eh=ox("species");xh.exports=function(a){var e=sx(a);ux&&e&&!e[Eh]&&nx(e,Eh,{configurable:!0,get:function(){return this}})}});var Ah=m((KM,wh)=>{"use strict";var lx=Hr(),cx=TypeError;wh.exports=function(a,e){if(lx(e,a))return a;throw new cx("Incorrect invocation")}});var vo=m((JM,kh)=>{"use strict";var dx=de(),px=z(),So=Yr(),hx=dx(Function.toString);px(So.inspectSource)||(So.inspectSource=function(a){return hx(a)});kh.exports=So.inspectSource});var Dh=m((XM,Ch)=>{"use strict";var fx=de(),mx=ye(),Rh=z(),bx=Zr(),gx=Ke(),Sx=vo(),Lh=function(){},$h=gx("Reflect","construct"),yo=/^\s*(?:class|function)\b/,vx=fx(yo.exec),yx=!yo.test(Lh),ai=function(e){if(!Rh(e))return!1;try{return $h(Lh,[],e),!0}catch(t){return!1}},Mh=function(e){if(!Rh(e))return!1;switch(bx(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return yx||!!vx(yo,Sx(e))}catch(t){return!0}};Mh.sham=!0;Ch.exports=!$h||mx(function(){var a;return ai(ai.call)||!ai(Object)||!ai(function(){a=!0})||a})?Mh:ai});var Bh=m((ZM,Oh)=>{"use strict";var Tx=Dh(),Ix=jr(),Ex=TypeError;Oh.exports=function(a){if(Tx(a))return a;throw new Ex(Ix(a)+" is not a constructor")}});var To=m((eC,_h)=>{"use strict";var Vh=Ye(),xx=Bh(),Px=ir(),wx=se(),Ax=wx("species");_h.exports=function(a,e){var t=Vh(a).constructor,r;return t===void 0||Px(r=Vh(t)[Ax])?e:xx(r)}});var Fh=m((tC,Nh)=>{"use strict";var kx=de();Nh.exports=kx([].slice)});var Uh=m((rC,qh)=>{"use strict";var Rx=TypeError;qh.exports=function(a,e){if(a<e)throw new Rx("Not enough arguments");return a}});var Io=m((iC,Hh)=>{"use strict";var Lx=sr();Hh.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(Lx)});var $o=m((aC,Xh)=>{"use strict";var Ie=K(),$x=Yn(),Mx=Jr(),jh=z(),Cx=_e(),Jh=ye(),Gh=Zn(),Dx=Fh(),Yh=Ta(),Ox=Uh(),Bx=Io(),Vx=Ha(),ko=Ie.setImmediate,Ro=Ie.clearImmediate,_x=Ie.process,Eo=Ie.Dispatch,Nx=Ie.Function,Wh=Ie.MessageChannel,Fx=Ie.String,xo=0,si={},Qh="onreadystatechange",ni,Ct,Po,wo;Jh(function(){ni=Ie.location});var Lo=function(a){if(Cx(si,a)){var e=si[a];delete si[a],e()}},Ao=function(a){return function(){Lo(a)}},zh=function(a){Lo(a.data)},Kh=function(a){Ie.postMessage(Fx(a),ni.protocol+"//"+ni.host)};(!ko||!Ro)&&(ko=function(e){Ox(arguments.length,1);var t=jh(e)?e:Nx(e),r=Dx(arguments,1);return si[++xo]=function(){$x(t,void 0,r)},Ct(xo),xo},Ro=function(e){delete si[e]},Vx?Ct=function(a){_x.nextTick(Ao(a))}:Eo&&Eo.now?Ct=function(a){Eo.now(Ao(a))}:Wh&&!Bx?(Po=new Wh,wo=Po.port2,Po.port1.onmessage=zh,Ct=Mx(wo.postMessage,wo)):Ie.addEventListener&&jh(Ie.postMessage)&&!Ie.importScripts&&ni&&ni.protocol!=="file:"&&!Jh(Kh)?(Ct=Kh,Ie.addEventListener("message",zh,!1)):Qh in Yh("script")?Ct=function(a){Gh.appendChild(Yh("script"))[Qh]=function(){Gh.removeChild(this),Lo(a)}}:Ct=function(a){setTimeout(Ao(a),0)});Xh.exports={set:ko,clear:Ro}});var tf=m((sC,ef)=>{"use strict";var Zh=K(),qx=Ae(),Ux=Object.getOwnPropertyDescriptor;ef.exports=function(a){if(!qx)return Zh[a];var e=Ux(Zh,a);return e&&e.value}});var Mo=m((nC,af)=>{"use strict";var rf=function(){this.head=null,this.tail=null};rf.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}}};af.exports=rf});var nf=m((oC,sf)=>{"use strict";var Hx=sr();sf.exports=/ipad|iphone|ipod/i.test(Hx)&&typeof Pebble!="undefined"});var uf=m((uC,of)=>{"use strict";var jx=sr();of.exports=/web0s(?!.*chrome)/i.test(jx)});var mf=m((lC,ff)=>{"use strict";var pr=K(),Gx=tf(),lf=Jr(),Co=$o().set,Yx=Mo(),Wx=Io(),Qx=nf(),zx=uf(),Do=Ha(),cf=pr.MutationObserver||pr.WebKitMutationObserver,df=pr.document,pf=pr.process,ja=pr.Promise,Vo=Gx("queueMicrotask"),dr,Oo,Bo,Ga,hf;Vo||(oi=new Yx,ui=function(){var a,e;for(Do&&(a=pf.domain)&&a.exit();e=oi.get();)try{e()}catch(t){throw oi.head&&dr(),t}a&&a.enter()},!Wx&&!Do&&!zx&&cf&&df?(Oo=!0,Bo=df.createTextNode(""),new cf(ui).observe(Bo,{characterData:!0}),dr=function(){Bo.data=Oo=!Oo}):!Qx&&ja&&ja.resolve?(Ga=ja.resolve(void 0),Ga.constructor=ja,hf=lf(Ga.then,Ga),dr=function(){hf(ui)}):Do?dr=function(){pf.nextTick(ui)}:(Co=lf(Co,pr),dr=function(){Co(ui)}),Vo=function(a){oi.head||dr(),oi.add(a)});var oi,ui;ff.exports=Vo});var gf=m((cC,bf)=>{"use strict";bf.exports=function(a,e){try{arguments.length===1?console.error(a):console.error(a,e)}catch(t){}}});var Ya=m((dC,Sf)=>{"use strict";Sf.exports=function(a){try{return{error:!1,value:a()}}catch(e){return{error:!0,value:e}}}});var Dt=m((pC,vf)=>{"use strict";var Kx=K();vf.exports=Kx.Promise});var hr=m((hC,Ef)=>{"use strict";var Jx=K(),li=Dt(),Xx=z(),Zx=Qn(),eP=vo(),tP=se(),yf=go(),rP=Ve(),_o=An(),Tf=li&&li.prototype,iP=tP("species"),No=!1,If=Xx(Jx.PromiseRejectionEvent),aP=Zx("Promise",function(){var a=eP(li),e=a!==String(li);if(!e&&_o===66||rP&&!(Tf.catch&&Tf.finally))return!0;if(!_o||_o<51||!/native code/.test(a)){var t=new li(function(s){s(1)}),r=function(s){s(function(){},function(){})},i=t.constructor={};if(i[iP]=r,No=t.then(function(){})instanceof r,!No)return!0}return!e&&(yf==="BROWSER"||yf==="DENO")&&!If});Ef.exports={CONSTRUCTOR:aP,REJECTION_EVENT:If,SUBCLASSING:No}});var fr=m((fC,Pf)=>{"use strict";var xf=Je(),sP=TypeError,nP=function(a){var e,t;this.promise=new a(function(r,i){if(e!==void 0||t!==void 0)throw new sP("Bad Promise constructor");e=r,t=i}),this.resolve=xf(e),this.reject=xf(t)};Pf.exports.f=function(a){return new nP(a)}});var jf=m(()=>{"use strict";var oP=ke(),uP=Ve(),Ka=Ha(),ht=K(),Sr=Te(),wf=cr(),Af=co(),lP=ei(),cP=Ph(),dP=Je(),za=z(),pP=we(),hP=Ah(),fP=To(),Mf=$o().set,jo=mf(),mP=gf(),bP=Ya(),gP=Mo(),Cf=Gn(),Ja=Dt(),Go=hr(),Df=fr(),Xa="Promise",Of=Go.CONSTRUCTOR,SP=Go.REJECTION_EVENT,vP=Go.SUBCLASSING,Fo=Cf.getterFor(Xa),yP=Cf.set,mr=Ja&&Ja.prototype,Ot=Ja,Wa=mr,Bf=ht.TypeError,qo=ht.document,Yo=ht.process,Uo=Df.f,TP=Uo,IP=!!(qo&&qo.createEvent&&ht.dispatchEvent),Vf="unhandledrejection",EP="rejectionhandled",kf=0,_f=1,xP=2,Wo=1,Nf=2,Qa,Rf,PP,Lf,Ff=function(a){var e;return pP(a)&&za(e=a.then)?e:!1},qf=function(a,e){var t=e.value,r=e.state===_f,i=r?a.ok:a.fail,s=a.resolve,n=a.reject,o=a.domain,u,l,c;try{i?(r||(e.rejection===Nf&&AP(e),e.rejection=Wo),i===!0?u=t:(o&&o.enter(),u=i(t),o&&(o.exit(),c=!0)),u===a.promise?n(new Bf("Promise-chain cycle")):(l=Ff(u))?Sr(l,u,s,n):s(u)):n(t)}catch(d){o&&!c&&o.exit(),n(d)}},Uf=function(a,e){a.notified||(a.notified=!0,jo(function(){for(var t=a.reactions,r;r=t.get();)qf(r,a);a.notified=!1,e&&!a.rejection&&wP(a)}))},Hf=function(a,e,t){var r,i;IP?(r=qo.createEvent("Event"),r.promise=e,r.reason=t,r.initEvent(a,!1,!0),ht.dispatchEvent(r)):r={promise:e,reason:t},!SP&&(i=ht["on"+a])?i(r):a===Vf&&mP("Unhandled promise rejection",t)},wP=function(a){Sr(Mf,ht,function(){var e=a.facade,t=a.value,r=$f(a),i;if(r&&(i=bP(function(){Ka?Yo.emit("unhandledRejection",t,e):Hf(Vf,e,t)}),a.rejection=Ka||$f(a)?Nf:Wo,i.error))throw i.value})},$f=function(a){return a.rejection!==Wo&&!a.parent},AP=function(a){Sr(Mf,ht,function(){var e=a.facade;Ka?Yo.emit("rejectionHandled",e):Hf(EP,e,a.value)})},br=function(a,e,t){return function(r){a(e,r,t)}},gr=function(a,e,t){a.done||(a.done=!0,t&&(a=t),a.value=e,a.state=xP,Uf(a,!0))},Ho=function(a,e,t){if(!a.done){a.done=!0,t&&(a=t);try{if(a.facade===e)throw new Bf("Promise can't be resolved itself");var r=Ff(e);r?jo(function(){var i={done:!1};try{Sr(r,e,br(Ho,i,a),br(gr,i,a))}catch(s){gr(i,s,a)}}):(a.value=e,a.state=_f,Uf(a,!1))}catch(i){gr({done:!1},i,a)}}};if(Of&&(Ot=function(e){hP(this,Wa),dP(e),Sr(Qa,this);var t=Fo(this);try{e(br(Ho,t),br(gr,t))}catch(r){gr(t,r)}},Wa=Ot.prototype,Qa=function(e){yP(this,{type:Xa,done:!1,notified:!1,parent:!1,reactions:new gP,rejection:!1,state:kf,value:void 0})},Qa.prototype=wf(Wa,"then",function(e,t){var r=Fo(this),i=Uo(fP(this,Ot));return r.parent=!0,i.ok=za(e)?e:!0,i.fail=za(t)&&t,i.domain=Ka?Yo.domain:void 0,r.state===kf?r.reactions.add(i):jo(function(){qf(i,r)}),i.promise}),Rf=function(){var a=new Qa,e=Fo(a);this.promise=a,this.resolve=br(Ho,e),this.reject=br(gr,e)},Df.f=Uo=function(a){return a===Ot||a===PP?new Rf(a):TP(a)},!uP&&za(Ja)&&mr!==Object.prototype)){Lf=mr.then,vP||wf(mr,"then",function(e,t){var r=this;return new Ot(function(i,s){Sr(Lf,r,i,s)}).then(e,t)},{unsafe:!0});try{delete mr.constructor}catch(a){}Af&&Af(mr,Wa)}oP({global:!0,constructor:!0,wrap:!0,forced:Of},{Promise:Ot});lP(Ot,Xa,!1,!0);cP(Xa)});var zf=m((gC,Qf)=>{"use strict";var kP=se(),Yf=kP("iterator"),Wf=!1;try{Gf=0,Qo={next:function(){return{done:!!Gf++}},return:function(){Wf=!0}},Qo[Yf]=function(){return this},Array.from(Qo,function(){throw 2})}catch(a){}var Gf,Qo;Qf.exports=function(a,e){try{if(!e&&!Wf)return!1}catch(i){return!1}var t=!1;try{var r={};r[Yf]=function(){return{next:function(){return{done:t=!0}}}},a(r)}catch(i){}return t}});var zo=m((SC,Kf)=>{"use strict";var RP=Dt(),LP=zf(),$P=hr().CONSTRUCTOR;Kf.exports=$P||!LP(function(a){RP.all(a).then(void 0,function(){})})});var Jf=m(()=>{"use strict";var MP=ke(),CP=Te(),DP=Je(),OP=fr(),BP=Ya(),VP=Fa(),_P=zo();MP({target:"Promise",stat:!0,forced:_P},{all:function(e){var t=this,r=OP.f(t),i=r.resolve,s=r.reject,n=BP(function(){var o=DP(t.resolve),u=[],l=0,c=1;VP(e,function(d){var p=l++,h=!1;c++,CP(o,t,d).then(function(f){h||(h=!0,u[p]=f,--c||i(u))},s)}),--c||i(u)});return n.error&&s(n.value),r.promise}})});var Zf=m(()=>{"use strict";var NP=ke(),FP=Ve(),qP=hr().CONSTRUCTOR,Jo=Dt(),UP=Ke(),HP=z(),jP=cr(),Xf=Jo&&Jo.prototype;NP({target:"Promise",proto:!0,forced:qP,real:!0},{catch:function(a){return this.then(void 0,a)}});!FP&&HP(Jo)&&(Ko=UP("Promise").prototype.catch,Xf.catch!==Ko&&jP(Xf,"catch",Ko,{unsafe:!0}));var Ko});var em=m(()=>{"use strict";var GP=ke(),YP=Te(),WP=Je(),QP=fr(),zP=Ya(),KP=Fa(),JP=zo();GP({target:"Promise",stat:!0,forced:JP},{race:function(e){var t=this,r=QP.f(t),i=r.reject,s=zP(function(){var n=WP(t.resolve);KP(e,function(o){YP(n,t,o).then(r.resolve,i)})});return s.error&&i(s.value),r.promise}})});var tm=m(()=>{"use strict";var XP=ke(),ZP=fr(),ew=hr().CONSTRUCTOR;XP({target:"Promise",stat:!0,forced:ew},{reject:function(e){var t=ZP.f(this),r=t.reject;return r(e),t.promise}})});var Xo=m((AC,rm)=>{"use strict";var tw=Ye(),rw=we(),iw=fr();rm.exports=function(a,e){if(tw(a),rw(e)&&e.constructor===a)return e;var t=iw.f(a),r=t.resolve;return r(e),t.promise}});var sm=m(()=>{"use strict";var aw=ke(),sw=Ke(),im=Ve(),nw=Dt(),am=hr().CONSTRUCTOR,ow=Xo(),uw=sw("Promise"),lw=im&&!am;aw({target:"Promise",stat:!0,forced:im||am},{resolve:function(e){return ow(lw&&this===uw?nw:this,e)}})});var nm=m(()=>{"use strict";jf();Jf();Zf();em();tm();sm()});var cm=m(()=>{"use strict";var cw=ke(),dw=Ve(),Za=Dt(),pw=ye(),um=Ke(),lm=z(),hw=To(),om=Xo(),fw=cr(),eu=Za&&Za.prototype,mw=!!Za&&pw(function(){eu.finally.call({then:function(){}},function(){})});cw({target:"Promise",proto:!0,real:!0,forced:mw},{finally:function(a){var e=hw(this,um("Promise")),t=lm(a);return this.then(t?function(r){return om(e,a()).then(function(){return r})}:a,t?function(r){return om(e,a()).then(function(){throw r})}:a)}});!dw&&lm(Za)&&(Zo=um("Promise").prototype.finally,eu.finally!==Zo&&fw(eu,"finally",Zo,{unsafe:!0}));var Zo});var es=m((DC,dm)=>{"use strict";var bw=Ke();dm.exports=bw});var hm=m((OC,pm)=>{"use strict";Sh();nm();cm();var gw=es();pm.exports=gw("Promise","finally")});var mm=m((BC,fm)=>{"use strict";var Sw=hm();fm.exports=Sw});var ts=m((VC,bm)=>{"use strict";var vw=mm();bm.exports=vw});var qm=m(()=>{"use strict";var Qw=ke(),zw=Wr(),Kw=$a(),Jw=La(),Xw=Sn();Qw({target:"Array",proto:!0},{at:function(e){var t=zw(this),r=Kw(t),i=Jw(e),s=i>=0?i:r+i;return s<0||s>=r?void 0:t[s]}});Xw("at")});var Hm=m((YD,Um)=>{"use strict";qm();var Zw=es();Um.exports=Zw("Array","at")});var Gm=m((WD,jm)=>{"use strict";var eA=Hm();jm.exports=eA});var hi=m((QD,Ym)=>{"use strict";var tA=Gm();Ym.exports=tA});var jb=m(()=>{"use strict"});var Gb=m(()=>{"use strict"});var Wb=m((t_,Yb)=>{"use strict";var dk=we(),pk=rr(),hk=se(),fk=hk("match");Yb.exports=function(a){var e;return dk(a)&&((e=a[fk])!==void 0?!!e:pk(a)==="RegExp")}});var zb=m((r_,Qb)=>{"use strict";var mk=Zr(),bk=String;Qb.exports=function(a){if(mk(a)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return bk(a)}});var Jb=m((i_,Kb)=>{"use strict";var gk=Ye();Kb.exports=function(){var a=gk(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((a_,Zb)=>{"use strict";var Sk=Te(),vk=_e(),yk=Hr(),Tk=Jb(),Xb=RegExp.prototype;Zb.exports=function(a){var e=a.flags;return e===void 0&&!("flags"in Xb)&&!vk(a,"flags")&&yk(Xb,a)?Sk(Tk,a):e}});var rg=m((s_,tg)=>{"use strict";var Lu=de(),Ik=Wr(),Ek=Math.floor,ku=Lu("".charAt),xk=Lu("".replace),Ru=Lu("".slice),Pk=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,wk=/\$([$&'`]|\d{1,2})/g;tg.exports=function(a,e,t,r,i,s){var n=t+a.length,o=r.length,u=wk;return i!==void 0&&(i=Ik(i),u=Pk),xk(s,u,function(l,c){var d;switch(ku(c,0)){case"$":return"$";case"&":return a;case"`":return Ru(e,0,t);case"'":return Ru(e,n);case"<":d=i[Ru(c,1,-1)];break;default:var p=+c;if(p===0)return l;if(p>o){var h=Ek(p/10);return h===0?l:h<=o?r[h-1]===void 0?ku(c,1):r[h-1]+ku(c,1):l}d=r[p-1]}return d===void 0?"":d})}});var sg=m(()=>{"use strict";var Ak=ke(),kk=Te(),Mu=de(),ig=qr(),Rk=z(),Lk=ir(),$k=Wb(),kr=zb(),Mk=Gr(),Ck=eg(),Dk=rg(),Ok=se(),Bk=Ve(),Vk=Ok("replace"),_k=TypeError,$u=Mu("".indexOf),Nk=Mu("".replace),ag=Mu("".slice),Fk=Math.max;Ak({target:"String",proto:!0},{replaceAll:function(e,t){var r=ig(this),i,s,n,o,u,l,c,d,p,h,f=0,b="";if(!Lk(e)){if(i=$k(e),i&&(s=kr(ig(Ck(e))),!~$u(s,"g")))throw new _k("`.replaceAll` does not allow non-global regexes");if(n=Mk(e,Vk),n)return kk(n,e,r,t);if(Bk&&i)return Nk(kr(r),e,t)}for(o=kr(r),u=kr(e),l=Rk(t),l||(t=kr(t)),c=u.length,d=Fk(1,c),p=$u(o,u);p!==-1;)h=l?kr(t(u,p,o)):Dk(u,o,p,[],void 0,t),b+=ag(o,f,p)+h,f=p+c,p=p+d>o.length?-1:$u(o,u,p+d);return f<o.length&&(b+=ag(o,f)),b}})});var og=m((u_,ng)=>{"use strict";jb();Gb();sg();var qk=es();ng.exports=qk("String","replaceAll")});var lg=m((l_,ug)=>{"use strict";var Uk=og();ug.exports=Uk});var dg=m((c_,cg)=>{"use strict";var Hk=lg();cg.exports=Hk});var Ol="2.0.108-dev.2cb388c2.0";var ce=(i=>(i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused",i))(ce||{}),pt=(v=>(v.MPEG="MPEG",v.DASH="DASH",v.DASH_SEP="DASH_SEP",v.DASH_SEP_VK="DASH_SEP",v.DASH_WEBM="DASH_WEBM",v.DASH_WEBM_AV1="DASH_WEBM_AV1",v.DASH_STREAMS="DASH_STREAMS",v.DASH_WEBM_VK="DASH_WEBM",v.DASH_ONDEMAND="DASH_ONDEMAND",v.DASH_ONDEMAND_VK="DASH_ONDEMAND",v.DASH_LIVE="DASH_LIVE",v.DASH_LIVE_CMAF="DASH_LIVE_CMAF",v.DASH_LIVE_WEBM="DASH_LIVE_WEBM",v.HLS="HLS",v.HLS_ONDEMAND="HLS_ONDEMAND",v.HLS_JS="HLS",v.HLS_LIVE="HLS_LIVE",v.HLS_LIVE_CMAF="HLS_LIVE_CMAF",v.WEB_RTC_LIVE="WEB_RTC_LIVE",v))(pt||{});var Sa=(i=>(i.NOT_AVAILABLE="NOT_AVAILABLE",i.AVAILABLE="AVAILABLE",i.CONNECTING="CONNECTING",i.CONNECTED="CONNECTED",i))(Sa||{}),pn=(r=>(r.HTTP1="http1",r.HTTP2="http2",r.QUIC="quic",r))(pn||{});var hn=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(hn||{});import{assertNever as ql,assertNonNullable as sv,isNonNullable as va,ValueSubject as fn,Subject as nv,Subscription as ov,merge as uv,observableFrom as lv,fromEvent as Vl,map as _l,tap as Nl,filterChanged as cv,isNullable as mn,ErrorCategory as Fl}from"@vkontakte/videoplayer-shared";var Bl=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 ya=class{constructor(e){this.connection$=new fn(void 0);this.castState$=new fn("NOT_AVAILABLE");this.errorEvent$=new nv;this.realCastState$=new fn("NOT_AVAILABLE");this.subscription=new ov;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=va((s=window.chrome)==null?void 0:s.cast),i=!!window.__onGCastApiAvailable;r?this.initializeCastApi():(window.__onGCastApiAvailable=n=>{delete window.__onGCastApiAvailable,n&&this.initializeCastApi()},i||Bl("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:Fl.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(){va(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();mn(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();mn(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(Vl(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 ql(i.sessionState)}})).add(uv(Vl(r,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(Nl(i=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(i)}`})}),_l(i=>i.castState)),lv([r.getCastState()])).pipe(cv(),_l(dv),Nl(i=>{this.log({message:`realCastState$: ${i}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(i=>{var o;let s=i==="CONNECTED",n=va(this.connection$.getValue());if(s&&!n){let u=r.getCurrentSession();sv(u);let l=u.getCastDevice(),c=(o=u.getMediaSession())==null?void 0:o.media.contentId;(mn(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"?va(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:Fl.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:s})}}},dv=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 ql(a)}};var cS=Ge(bo(),1);var wm=Ge(ts(),1);import{assertNever as gm}from"@vkontakte/videoplayer-shared";var ae=(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:gm(t)}return a},tu=(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:gm(e)}};var E=(a,e,t=!1)=>{let r=a.getTransition();(t||!r||r.to===e)&&a.setState(e)};import{isNonNullable as yw,Subject as rs,merge as Sm}from"@vkontakte/videoplayer-shared";var M=class{constructor(e){this.transitionStarted$=new rs;this.transitionEnded$=new rs;this.transitionUpdated$=new rs;this.forceChanged$=new rs;this.stateChangeStarted$=Sm(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=Sm(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||yw(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 Tw}from"@vkontakte/videoplayer-shared";var vm=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 Tw(a)}};import{assertNever as vr,assertNonNullable as Bt,debounce as ym,ErrorCategory as Tm,fromEvent as Vt,isNonNullable as Im,map as Em,merge as xm,observableFrom as Iw,Subject as Ew,Subscription as ru,timeout as xw,getHighestQuality as Pw}from"@vkontakte/videoplayer-shared";var ww=5,Aw=5,kw=500,Pm=7e3,ci=class{constructor(e){this.subscription=new ru;this.loadMediaTimeoutSubscription=new ru;this.videoState=new M("stopped");this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),r=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${r}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(s)};`}),r==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.stop());return}if(!t){if((i==null?void 0:i.to)!=="paused"&&s.state==="requested"&&e!=="stopped"){this.seek(s.position/1e3);return}switch(r){case"ready":{switch(e){case"playing":case"paused":case"ready":break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:vr(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:vr(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:vr(e)}break}default:vr(r)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(vm(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 ru;this.subscription.add(e),this.subscription.add(xm(this.videoState.stateChangeStarted$.pipe(Em(i=>`stateChangeStarted$ ${JSON.stringify(i)}`)),this.videoState.stateChangeEnded$.pipe(Em(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 Ew;e.add(i.pipe(ym(kw)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add(Vt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe(n=>{this.logRemoteEvent(n);let o=n.value;this.params.output.position$.next(o),(this.params.desiredState.seekState.getState().state==="applying"||Math.abs(o-s)>ww)&&i.next(o),s=o})),e.add(Vt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(Vt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),i=>{this.logRemoteEvent(i),i.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(Vt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),i=>{this.logRemoteEvent(i),i.value?this.handleRemotePause():this.handleRemotePlay()}),t(Vt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),i=>{this.logRemoteEvent(i);let{remotePlayer:s}=this.params.connection,n=i.value,o=this.params.output.isBuffering$.getValue(),u=n===chrome.cast.media.PlayerState.BUFFERING;switch(o!==u&&this.params.output.isBuffering$.next(u),n){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&s.duration-s.currentTime<Aw&&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:vr(n)}}),t(Vt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),i=>{this.logRemoteEvent(i),this.handleRemoteVolumeChange({volume:i.value})}),t(Vt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),i=>{this.logRemoteEvent(i),this.handleRemoteVolumeChange({muted:i.value})});let r=xm(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Iw(["init"])).pipe(ym(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];Bt(c);let d=Pw(Object.keys(c));Bt(d);let p=c[d];Bt(p),r=p,i="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let c=t[e];Bt(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];Bt(c),r=c.url,i="application/dash+xml",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let c=t[e];Bt(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];Bt(c),r=ae(c.url),i="application/x-mpegurl",s=chrome.cast.media.StreamType.LIVE;break}case"DASH_LIVE":case"WEB_RTC_LIVE":{let c="Unsupported format for Chromecast",d=new Error(c);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:Tm.VIDEO_PIPELINE,message:c,thrown:d}),d}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return vr(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 Im(o)&&(n.metadata.title=o),Im(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(xw(Pm).subscribe(()=>s(`timeout(${Pm})`)))});(0,wm.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:Tm.VIDEO_PIPELINE,message:s,thrown:i})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};import{clearVideoElement as km}from"@vkontakte/videoplayer-shared";import{clearVideoElement as Rw}from"@vkontakte/videoplayer-shared";var Am=a=>{try{a.pause(),a.playbackRate=0,Rw(a),a.remove()}catch(e){console.error(e)}};import{fromEvent as Lw,Subscription as $w}from"@vkontakte/videoplayer-shared";var iu=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)}},au=window.WeakMap?new WeakMap:new iu,su=window.WeakMap?new WeakMap:new Map,Mw=(a,e=20)=>{let t=0;return Lw(a,"ratechange").subscribe(r=>{t++,t>=e&&(a.currentTime=a.currentTime,t=0)})},pe=(a,{audioVideoSyncRate:e})=>{let t=a.querySelector("video"),r=!!t;t?km(t):(t=document.createElement("video"),a.appendChild(t)),au.set(t,r);let i=new $w;return i.add(Mw(t,e)),su.set(t,i),t.setAttribute("crossorigin","anonymous"),t.setAttribute("playsinline","playsinline"),t.controls=!1,t.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),t},he=a=>{let e=su.get(a);e==null||e.unsubscribe(),su.delete(a);let t=au.get(a);au.delete(a),t?km(a):Am(a)};import{assertNonNullable as di,isNonNullable as Qe,isNullable as Ow,fromEvent as yr,merge as Rm,observableFrom as Lm,filterChanged as $m,map as pi,Subject as Mm,Subscription as Bw,ValueSubject as Vw,ErrorCategory as _w}from"@vkontakte/videoplayer-shared";import{isNonNullable as nu,isNullable as Cw,Subscription as Dw}from"@vkontakte/videoplayer-shared";var is=(a,e,t,{equal:r=(n,o)=>n===o,changed$:i,onError:s}={})=>{let n=a.getState(),o=e(),u=Cw(i),l=new Dw;return i&&l.add(i.subscribe(c=>{let d=a.getState();r(c,d)&&a.setState(c)},s)),r(o,n)||(t(n),u&&a.setState(n)),l.add(a.stateChangeStarted$.subscribe(c=>{t(c.to),u&&a.setState(c.to)},s)),l},We=(a,e,t)=>is(e,()=>a.loop,r=>{nu(r)&&(a.loop=r)},{onError:t}),fe=(a,e,t,r)=>is(e,()=>({muted:a.muted,volume:a.volume}),i=>{nu(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}),Re=(a,e,t,r)=>is(e,()=>a.playbackRate,i=>{nu(i)&&(a.playbackRate=i)},{changed$:t,onError:r}),ft=is;var Nw=a=>["__",a.language,a.label].join("|"),Fw=(a,e)=>{if(a.id===e)return!0;let[t,r,i]=e.split("|");return a.language===r&&a.label===i},ou=class a{constructor(){this.available$=new Mm;this.current$=new Vw(void 0);this.error$=new Mm;this.subscription=new Bw;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:_w.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(ft(t.internalTextTracks,()=>Object.values(this.internalTracks),s=>{Qe(s)&&this.setInternal(s)},{equal:(s,n)=>Qe(s)&&Qe(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(pi(s=>s.filter(({type:n})=>n==="internal"))),onError:i})),this.subscription.add(ft(t.externalTextTracks,()=>Object.values(this.externalTracks),s=>{Qe(s)&&this.setExternal(s)},{equal:(s,n)=>Qe(s)&&Qe(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(pi(s=>s.filter(({type:n})=>n==="external"))),onError:i})),this.subscription.add(ft(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(ft(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.activeCues)}))}subscribe(){di(this.video);let{textTracks:e}=this.video;this.subscription.add(yr(e,"addtrack").subscribe(()=>{let r=this.current$.getValue();r&&this.select(r)})),this.subscription.add(Rm(yr(e,"addtrack"),yr(e,"removetrack"),Lm(["init"])).pipe(pi(()=>this.htmlTextTracksAsArray().map(r=>this.htmlTextTrackToITextTrack(r))),$m((r,i)=>r.length===i.length&&r.every(({id:s},n)=>s===i[n].id))).subscribe(this.available$)),this.subscription.add(Rm(yr(e,"change"),Lm(["init"])).pipe(pi(()=>this.htmlTextTracksAsArray().find(({mode:r})=>r==="showing")),pi(r=>r&&this.htmlTextTrackToITextTrack(r).id),$m()).subscribe(this.current$));let t=r=>{var i,s;return this.applyCueSettings((s=(i=r.target)==null?void 0:i.activeCues)!=null?s:null)};this.subscription.add(yr(e,"addtrack").subscribe(r=>{var s,n;(s=r.track)==null||s.addEventListener("cuechange",t);let i=o=>{var l,c,d,p,h;let u=(c=(l=o.target)==null?void 0:l.cues)!=null?c:null;u&&u.length&&(this.applyCueSettings((p=(d=o.target)==null?void 0:d.cues)!=null?p:null),(h=o.target)==null||h.removeEventListener("cuechange",i))};(n=r.track)==null||n.addEventListener("cuechange",i)})),this.subscription.add(yr(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;Qe(t.align)&&(i.align=t.align),Qe(t.position)&&(i.position=t.position),Qe(t.size)&&(i.size=t.size),Qe(t.line)&&(i.line=t.line)}}htmlTextTracksAsArray(e=!1){di(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:Nw(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){di(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(Ow(e)||!Fw(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){di(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){di(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)}},Le=ou;var et=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 Cm=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},uu=a=>{let e=Cm(a);return!!(e&&e.fullscreenElement&&e.fullscreenElement===a)},Dm=a=>{let e=Cm(a);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===a)};import{fromEvent as $e,map as mt,merge as Bm,filterChanged as Uw,isNonNullable as Vm,Subject as Hw,filter as _m,mapTo as Nm,combine as jw,once as Gw,ErrorCategory as Yw,ValueSubject as Fm,clientChecker as Ww}from"@vkontakte/videoplayer-shared";var qw=3,Om=(a,e,t=qw)=>{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 me=a=>{let e=v=>$e(a,v).pipe(Nm(void 0)),r=Bm(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(v=>$e(a,v))).pipe(mt(v=>v.type==="ended"?a.readyState<2:a.readyState<3),Uw()),i=Bm($e(a,"progress"),$e(a,"timeupdate")).pipe(mt(()=>Om(a.buffered,a.currentTime))),s=Ww.isSafari?jw({play:e("play").pipe(Gw()),playing:e("playing")}).pipe(Nm(void 0)):e("playing"),n=$e(a,"volumechange").pipe(mt(()=>({muted:a.muted,volume:a.volume}))),o=$e(a,"ratechange").pipe(mt(()=>a.playbackRate)),u=$e(a,"error").pipe(_m(()=>!!(a.error||a.played.length)),mt(()=>{var T;let v=a.error;return{id:v?`MediaError#${v.code}`:"HtmlVideoError",category:Yw.VIDEO_PIPELINE,message:v?v.message:"Error event from HTML video element",thrown:(T=a.error)!=null?T:void 0}})),l=$e(a,"timeupdate").pipe(mt(()=>a.currentTime)),c=new Hw,d=.3,p;l.subscribe(v=>{a.loop&&Vm(p)&&Vm(v)&&p>=a.duration-d&&v<=d&&c.next(p),p=v});let h=e("pause").pipe(_m(()=>!a.error&&p!==a.duration)),f=$e(a,"enterpictureinpicture"),b=$e(a,"leavepictureinpicture"),g=new Fm(Dm(a));f.subscribe(()=>g.next(!0)),b.subscribe(()=>g.next(!1));let S=new Fm(uu(a));return $e(a,"fullscreenchange").pipe(mt(()=>uu(a))).subscribe(S),{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$:$e(a,"durationchange").pipe(mt(()=>a.duration)),isBuffering$:r,currentBuffer$:i,volumeState$:n,playbackRateState$:o,inPiP$:g,inFullscreen$:S}};import{VideoQuality as bt}from"@vkontakte/videoplayer-shared";var gt=a=>{switch(a){case"mobile":return bt.Q_144P;case"lowest":return bt.Q_240P;case"low":return bt.Q_360P;case"sd":case"medium":return bt.Q_480P;case"hd":case"high":return bt.Q_720P;case"fullhd":case"full":return bt.Q_1080P;case"quadhd":case"quad":return bt.Q_1440P;case"ultrahd":case"ultra":return bt.Q_2160P}};var hu=Ge(hi(),1);import{isNonNullable as St,isNullable as cu,now as Xm,isHigher as du,isHigherOrEqual as Km,isInvariantQuality as Jm,isLower as pu,isLowerOrEqual as rA,videoSizeToQuality as iA,assertNotEmptyArray as aA}from"@vkontakte/videoplayer-shared";var lu=!1,tt={},Wm=a=>{lu=a},Qm=()=>{tt={}},zm=a=>{a(tt)},fi=(a,e)=>{var t;lu&&(tt.meta=(t=tt.meta)!=null?t:{},tt.meta[a]=e)},ne=class{constructor(e){this.name=e}next(e){var r,i;if(!lu)return;tt.series=(r=tt.series)!=null?r:{};let t=(i=tt.series[this.name])!=null?i:[];t.push([Date.now(),e]),tt.series[this.name]=t}};var sA=new ne("best_bitrate"),nA=(a,e,t)=>(e-t)*Math.pow(2,-10*a)+t,as=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=Xm()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},oA='Assertion "ABR Tracks is empty array" failed',uA=(a,{container:e,throughput:t,tuning:r,limits:i,reserve:s=0,forwardBufferHealth:n,playbackRate:o,current:u,history:l,droppedVideoMaxQualityLimit:c,abrLogger:d})=>{var U,L,w,H,W;aA(a,oA);let p=r.usePixelRatio&&(U=window.devicePixelRatio)!=null?U:1,h=r.limitByContainer&&e&&e.width>0&&e.height>0&&{width:e.width*p*r.containerSizeFactor,height:e.height*p*r.containerSizeFactor},f=h&&iA(h),b=r.considerPlaybackRate&&St(o)?o:1,g=a.filter(k=>!Jm(k.quality)).sort((k,x)=>du(k.quality,x.quality)?-1:1),S=(L=(0,hu.default)(g,-1))==null?void 0:L.quality,I=(w=(0,hu.default)(g,0))==null?void 0:w.quality,v=cu(i)||St(i.min)&&St(i.max)&&pu(i.max,i.min)||St(i.min)&&I&&du(i.min,I)||St(i.max)&&S&&pu(i.max,S),T=b*nA(n!=null?n:.5,r.bitrateFactorAtEmptyBuffer,r.bitrateFactorAtFullBuffer),y={},D=g.filter(k=>(f?pu(k.quality,f):!0)?(St(t)&&isFinite(t)&&St(k.bitrate)?t-s>=k.bitrate*T:!0)?r.lazyQualitySwitch&&St(r.minBufferToSwitchUp)&&u&&!Jm(u.quality)&&(n!=null?n:0)<r.minBufferToSwitchUp&&du(k.quality,u.quality)?(y[k.quality]="Buffer",!1):!!c&&Km(k.quality,c)?(y[k.quality]="DroppedFramesLimit",!1):v||(cu(i.max)||rA(k.quality,i.max))&&(cu(i.min)||Km(k.quality,i.min))?!0:(y[k.quality]="FitsQualityLimits",!1):(y[k.quality]="FitsThroughput",!1):(y[k.quality]="FitsContainer",!1))[0];D&&D.bitrate&&sA.next(D.bitrate);let $=(H=D!=null?D:g[Math.ceil((g.length-1)/2)])!=null?H:a[0];$.quality!==((W=l==null?void 0:l.last)==null?void 0:W.quality)&&d({message:`
7
- [available tracks]
6
+ var yv=Object.create;var Rn=Object.defineProperty,Tv=Object.defineProperties,Iv=Object.getOwnPropertyDescriptor,Ev=Object.getOwnPropertyDescriptors,xv=Object.getOwnPropertyNames,nl=Object.getOwnPropertySymbols,Av=Object.getPrototypeOf,ul=Object.prototype.hasOwnProperty,Pv=Object.prototype.propertyIsEnumerable;var wv=(a,e)=>(e=Symbol[a])?e:Symbol.for("Symbol."+a);var Je=Math.pow,ol=(a,e,t)=>e in a?Rn(a,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):a[e]=t,A=(a,e)=>{for(var t in e||(e={}))ul.call(e,t)&&ol(a,t,e[t]);if(nl)for(var t of nl(e))Pv.call(e,t)&&ol(a,t,e[t]);return a},M=(a,e)=>Tv(a,Ev(e));var m=(a,e)=>()=>(e||a((e={exports:{}}).exports,e),e.exports);var kv=(a,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of xv(e))!ul.call(a,i)&&i!==t&&Rn(a,i,{get:()=>e[i],enumerable:!(r=Iv(e,i))||r.enumerable});return a};var Xe=(a,e,t)=>(t=a!=null?yv(Av(a)):{},kv(e||!a||!a.__esModule?Rn(t,"default",{value:a,enumerable:!0}):t,a));var R=(a,e,t)=>new Promise((r,i)=>{var s=u=>{try{o(t.next(u))}catch(c){i(c)}},n=u=>{try{o(t.throw(u))}catch(c){i(c)}},o=u=>u.done?r(u.value):Promise.resolve(u.value).then(s,n);o((t=t.apply(a,e)).next())}),Rv=function(a,e){this[0]=a,this[1]=e},te=(a,e,t)=>{var r=(n,o,u,c)=>{try{var l=t[n](o),d=(o=l.value)instanceof Rv,p=l.done;Promise.resolve(d?o[0]:o).then(h=>d?r(n==="return"?n:"next",o[1]?{done:h.done,value:h.value}:h,u,c):u({value:h,done:p})).catch(h=>r("throw",h,u,c))}catch(h){c(h)}},i=n=>s[n]=o=>new Promise((u,c)=>r(n,o,u,c)),s={};return t=t.apply(a,e),s[wv("asyncIterator")]=()=>s,i("next"),i("throw"),i("return"),s};var xe=m((AL,bl)=>{"use strict";bl.exports=function(a){try{return!!a()}catch(e){return!0}}});var ii=m((PL,gl)=>{"use strict";var Vv=xe();gl.exports=!Vv(function(){var a=function(){}.bind();return typeof a!="function"||a.hasOwnProperty("prototype")})});var fe=m((wL,yl)=>{"use strict";var Sl=ii(),vl=Function.prototype,Dn=vl.call,_v=Sl&&vl.bind.bind(Dn,Dn);yl.exports=Sl?_v:function(a){return function(){return Dn.apply(a,arguments)}}});var gr=m((kL,Il)=>{"use strict";var Tl=fe(),Nv=Tl({}.toString),Fv=Tl("".slice);Il.exports=function(a){return Fv(Nv(a),8,-1)}});var xl=m((RL,El)=>{"use strict";var qv=fe(),Uv=xe(),Hv=gr(),Bn=Object,jv=qv("".split);El.exports=Uv(function(){return!Bn("z").propertyIsEnumerable(0)})?function(a){return Hv(a)==="String"?jv(a,""):Bn(a)}:Bn});var Sr=m(($L,Al)=>{"use strict";Al.exports=function(a){return a==null}});var ai=m((LL,Pl)=>{"use strict";var Gv=Sr(),Wv=TypeError;Pl.exports=function(a){if(Gv(a))throw new Wv("Can't call method on "+a);return a}});var vr=m((ML,wl)=>{"use strict";var Yv=xl(),Qv=ai();wl.exports=function(a){return Yv(Qv(a))}});var On=m((CL,kl)=>{"use strict";kl.exports=function(){}});var Ht=m((DL,Rl)=>{"use strict";Rl.exports={}});var J=m((Vn,$l)=>{"use strict";var si=function(a){return a&&a.Math===Math&&a};$l.exports=si(typeof globalThis=="object"&&globalThis)||si(typeof window=="object"&&window)||si(typeof self=="object"&&self)||si(typeof global=="object"&&global)||si(typeof Vn=="object"&&Vn)||function(){return this}()||Function("return this")()});var K=m((BL,Ll)=>{"use strict";var _n=typeof document=="object"&&document.all;Ll.exports=typeof _n=="undefined"&&_n!==void 0?function(a){return typeof a=="function"||a===_n}:function(a){return typeof a=="function"}});var Dl=m((OL,Cl)=>{"use strict";var zv=J(),Kv=K(),Ml=zv.WeakMap;Cl.exports=Kv(Ml)&&/native code/.test(String(Ml))});var Le=m((VL,Bl)=>{"use strict";var Jv=K();Bl.exports=function(a){return typeof a=="object"?a!==null:Jv(a)}});var Me=m((_L,Ol)=>{"use strict";var Xv=xe();Ol.exports=!Xv(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var Qa=m((NL,_l)=>{"use strict";var Zv=J(),Vl=Le(),Nn=Zv.document,ey=Vl(Nn)&&Vl(Nn.createElement);_l.exports=function(a){return ey?Nn.createElement(a):{}}});var Fn=m((FL,Nl)=>{"use strict";var ty=Me(),ry=xe(),iy=Qa();Nl.exports=!ty&&!ry(function(){return Object.defineProperty(iy("div"),"a",{get:function(){return 7}}).a!==7})});var qn=m((qL,Fl)=>{"use strict";var ay=Me(),sy=xe();Fl.exports=ay&&sy(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var Ze=m((UL,ql)=>{"use strict";var ny=Le(),oy=String,uy=TypeError;ql.exports=function(a){if(ny(a))return a;throw new uy(oy(a)+" is not an object")}});var Ae=m((HL,Ul)=>{"use strict";var cy=ii(),za=Function.prototype.call;Ul.exports=cy?za.bind(za):function(){return za.apply(za,arguments)}});var Ka=m((jL,Hl)=>{"use strict";Hl.exports={}});var at=m((GL,Gl)=>{"use strict";var Un=Ka(),Hn=J(),ly=K(),jl=function(a){return ly(a)?a:void 0};Gl.exports=function(a,e){return arguments.length<2?jl(Un[a])||jl(Hn[a]):Un[a]&&Un[a][e]||Hn[a]&&Hn[a][e]}});var ni=m((WL,Wl)=>{"use strict";var dy=fe();Wl.exports=dy({}.isPrototypeOf)});var yr=m((YL,zl)=>{"use strict";var py=J(),Yl=py.navigator,Ql=Yl&&Yl.userAgent;zl.exports=Ql?String(Ql):""});var Gn=m((QL,td)=>{"use strict";var ed=J(),jn=yr(),Kl=ed.process,Jl=ed.Deno,Xl=Kl&&Kl.versions||Jl&&Jl.version,Zl=Xl&&Xl.v8,Ue,Ja;Zl&&(Ue=Zl.split("."),Ja=Ue[0]>0&&Ue[0]<4?1:+(Ue[0]+Ue[1]));!Ja&&jn&&(Ue=jn.match(/Edge\/(\d+)/),(!Ue||Ue[1]>=74)&&(Ue=jn.match(/Chrome\/(\d+)/),Ue&&(Ja=+Ue[1])));td.exports=Ja});var Wn=m((zL,id)=>{"use strict";var rd=Gn(),hy=xe(),fy=J(),my=fy.String;id.exports=!!Object.getOwnPropertySymbols&&!hy(function(){var a=Symbol("symbol detection");return!my(a)||!(Object(a)instanceof Symbol)||!Symbol.sham&&rd&&rd<41})});var Yn=m((KL,ad)=>{"use strict";var by=Wn();ad.exports=by&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var Qn=m((JL,sd)=>{"use strict";var gy=at(),Sy=K(),vy=ni(),yy=Yn(),Ty=Object;sd.exports=yy?function(a){return typeof a=="symbol"}:function(a){var e=gy("Symbol");return Sy(e)&&vy(e.prototype,Ty(a))}});var oi=m((XL,nd)=>{"use strict";var Iy=String;nd.exports=function(a){try{return Iy(a)}catch(e){return"Object"}}});var st=m((ZL,od)=>{"use strict";var Ey=K(),xy=oi(),Ay=TypeError;od.exports=function(a){if(Ey(a))return a;throw new Ay(xy(a)+" is not a function")}});var ui=m((eM,ud)=>{"use strict";var Py=st(),wy=Sr();ud.exports=function(a,e){var t=a[e];return wy(t)?void 0:Py(t)}});var ld=m((tM,cd)=>{"use strict";var zn=Ae(),Kn=K(),Jn=Le(),ky=TypeError;cd.exports=function(a,e){var t,r;if(e==="string"&&Kn(t=a.toString)&&!Jn(r=zn(t,a))||Kn(t=a.valueOf)&&!Jn(r=zn(t,a))||e!=="string"&&Kn(t=a.toString)&&!Jn(r=zn(t,a)))return r;throw new ky("Can't convert object to primitive value")}});var He=m((rM,dd)=>{"use strict";dd.exports=!0});var fd=m((iM,hd)=>{"use strict";var pd=J(),Ry=Object.defineProperty;hd.exports=function(a,e){try{Ry(pd,a,{value:e,configurable:!0,writable:!0})}catch(t){pd[a]=e}return e}});var ci=m((aM,gd)=>{"use strict";var $y=He(),Ly=J(),My=fd(),md="__core-js_shared__",bd=gd.exports=Ly[md]||My(md,{});(bd.versions||(bd.versions=[])).push({version:"3.38.0",mode:$y?"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 Xn=m((sM,vd)=>{"use strict";var Sd=ci();vd.exports=function(a,e){return Sd[a]||(Sd[a]=e||{})}});var li=m((nM,yd)=>{"use strict";var Cy=ai(),Dy=Object;yd.exports=function(a){return Dy(Cy(a))}});var je=m((oM,Td)=>{"use strict";var By=fe(),Oy=li(),Vy=By({}.hasOwnProperty);Td.exports=Object.hasOwn||function(e,t){return Vy(Oy(e),t)}});var Zn=m((uM,Id)=>{"use strict";var _y=fe(),Ny=0,Fy=Math.random(),qy=_y(1 .toString);Id.exports=function(a){return"Symbol("+(a===void 0?"":a)+")_"+qy(++Ny+Fy,36)}});var oe=m((cM,xd)=>{"use strict";var Uy=J(),Hy=Xn(),Ed=je(),jy=Zn(),Gy=Wn(),Wy=Yn(),Tr=Uy.Symbol,eo=Hy("wks"),Yy=Wy?Tr.for||Tr:Tr&&Tr.withoutSetter||jy;xd.exports=function(a){return Ed(eo,a)||(eo[a]=Gy&&Ed(Tr,a)?Tr[a]:Yy("Symbol."+a)),eo[a]}});var kd=m((lM,wd)=>{"use strict";var Qy=Ae(),Ad=Le(),Pd=Qn(),zy=ui(),Ky=ld(),Jy=oe(),Xy=TypeError,Zy=Jy("toPrimitive");wd.exports=function(a,e){if(!Ad(a)||Pd(a))return a;var t=zy(a,Zy),r;if(t){if(e===void 0&&(e="default"),r=Qy(t,a,e),!Ad(r)||Pd(r))return r;throw new Xy("Can't convert object to primitive value")}return e===void 0&&(e="number"),Ky(a,e)}});var to=m((dM,Rd)=>{"use strict";var eT=kd(),tT=Qn();Rd.exports=function(a){var e=eT(a,"string");return tT(e)?e:e+""}});var jt=m(Ld=>{"use strict";var rT=Me(),iT=Fn(),aT=qn(),Xa=Ze(),$d=to(),sT=TypeError,ro=Object.defineProperty,nT=Object.getOwnPropertyDescriptor,io="enumerable",ao="configurable",so="writable";Ld.f=rT?aT?function(e,t,r){if(Xa(e),t=$d(t),Xa(r),typeof e=="function"&&t==="prototype"&&"value"in r&&so in r&&!r[so]){var i=nT(e,t);i&&i[so]&&(e[t]=r.value,r={configurable:ao in r?r[ao]:i[ao],enumerable:io in r?r[io]:i[io],writable:!1})}return ro(e,t,r)}:ro:function(e,t,r){if(Xa(e),t=$d(t),Xa(r),iT)try{return ro(e,t,r)}catch(i){}if("get"in r||"set"in r)throw new sT("Accessors not supported");return"value"in r&&(e[t]=r.value),e}});var di=m((hM,Md)=>{"use strict";Md.exports=function(a,e){return{enumerable:!(a&1),configurable:!(a&2),writable:!(a&4),value:e}}});var Ir=m((fM,Cd)=>{"use strict";var oT=Me(),uT=jt(),cT=di();Cd.exports=oT?function(a,e,t){return uT.f(a,e,cT(1,t))}:function(a,e,t){return a[e]=t,a}});var Za=m((mM,Bd)=>{"use strict";var lT=Xn(),dT=Zn(),Dd=lT("keys");Bd.exports=function(a){return Dd[a]||(Dd[a]=dT(a))}});var es=m((bM,Od)=>{"use strict";Od.exports={}});var co=m((gM,Nd)=>{"use strict";var pT=Dl(),_d=J(),hT=Le(),fT=Ir(),no=je(),oo=ci(),mT=Za(),bT=es(),Vd="Object already initialized",uo=_d.TypeError,gT=_d.WeakMap,ts,pi,rs,ST=function(a){return rs(a)?pi(a):ts(a,{})},vT=function(a){return function(e){var t;if(!hT(e)||(t=pi(e)).type!==a)throw new uo("Incompatible receiver, "+a+" required");return t}};pT||oo.state?(Ge=oo.state||(oo.state=new gT),Ge.get=Ge.get,Ge.has=Ge.has,Ge.set=Ge.set,ts=function(a,e){if(Ge.has(a))throw new uo(Vd);return e.facade=a,Ge.set(a,e),e},pi=function(a){return Ge.get(a)||{}},rs=function(a){return Ge.has(a)}):(Gt=mT("state"),bT[Gt]=!0,ts=function(a,e){if(no(a,Gt))throw new uo(Vd);return e.facade=a,fT(a,Gt,e),e},pi=function(a){return no(a,Gt)?a[Gt]:{}},rs=function(a){return no(a,Gt)});var Ge,Gt;Nd.exports={set:ts,get:pi,has:rs,enforce:ST,getterFor:vT}});var lo=m((SM,Hd)=>{"use strict";var yT=ii(),Ud=Function.prototype,Fd=Ud.apply,qd=Ud.call;Hd.exports=typeof Reflect=="object"&&Reflect.apply||(yT?qd.bind(Fd):function(){return qd.apply(Fd,arguments)})});var po=m((vM,jd)=>{"use strict";var TT=gr(),IT=fe();jd.exports=function(a){if(TT(a)==="Function")return IT(a)}});var Qd=m(Yd=>{"use strict";var Gd={}.propertyIsEnumerable,Wd=Object.getOwnPropertyDescriptor,ET=Wd&&!Gd.call({1:2},1);Yd.f=ET?function(e){var t=Wd(this,e);return!!t&&t.enumerable}:Gd});var Jd=m(Kd=>{"use strict";var xT=Me(),AT=Ae(),PT=Qd(),wT=di(),kT=vr(),RT=to(),$T=je(),LT=Fn(),zd=Object.getOwnPropertyDescriptor;Kd.f=xT?zd:function(e,t){if(e=kT(e),t=RT(t),LT)try{return zd(e,t)}catch(r){}if($T(e,t))return wT(!AT(PT.f,e,t),e[t])}});var ho=m((IM,Xd)=>{"use strict";var MT=xe(),CT=K(),DT=/#|\.prototype\./,hi=function(a,e){var t=OT[BT(a)];return t===_T?!0:t===VT?!1:CT(e)?MT(e):!!e},BT=hi.normalize=function(a){return String(a).replace(DT,".").toLowerCase()},OT=hi.data={},VT=hi.NATIVE="N",_T=hi.POLYFILL="P";Xd.exports=hi});var fi=m((EM,ep)=>{"use strict";var Zd=po(),NT=st(),FT=ii(),qT=Zd(Zd.bind);ep.exports=function(a,e){return NT(a),e===void 0?a:FT?qT(a,e):function(){return a.apply(e,arguments)}}});var Ce=m((xM,rp)=>{"use strict";var mi=J(),UT=lo(),HT=po(),jT=K(),GT=Jd().f,WT=ho(),Er=Ka(),YT=fi(),xr=Ir(),tp=je();ci();var QT=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 UT(a,this,arguments)};return e.prototype=a.prototype,e};rp.exports=function(a,e){var t=a.target,r=a.global,i=a.stat,s=a.proto,n=r?mi:i?mi[t]:mi[t]&&mi[t].prototype,o=r?Er:Er[t]||xr(Er,t,{})[t],u=o.prototype,c,l,d,p,h,f,b,g,S;for(p in e)c=WT(r?p:t+(i?".":"#")+p,a.forced),l=!c&&n&&tp(n,p),f=o[p],l&&(a.dontCallGetSet?(S=GT(n,p),b=S&&S.value):b=n[p]),h=l&&b?b:e[p],!(!c&&!s&&typeof f==typeof h)&&(a.bind&&l?g=YT(h,mi):a.wrap&&l?g=QT(h):s&&jT(h)?g=HT(h):g=h,(a.sham||h&&h.sham||f&&f.sham)&&xr(g,"sham",!0),xr(o,p,g),s&&(d=t+"Prototype",tp(Er,d)||xr(Er,d,{}),xr(Er[d],p,h),a.real&&u&&(c||!u[p])&&xr(u,p,h)))}});var sp=m((AM,ap)=>{"use strict";var fo=Me(),zT=je(),ip=Function.prototype,KT=fo&&Object.getOwnPropertyDescriptor,mo=zT(ip,"name"),JT=mo&&function(){}.name==="something",XT=mo&&(!fo||fo&&KT(ip,"name").configurable);ap.exports={EXISTS:mo,PROPER:JT,CONFIGURABLE:XT}});var op=m((PM,np)=>{"use strict";var ZT=Math.ceil,eI=Math.floor;np.exports=Math.trunc||function(e){var t=+e;return(t>0?eI:ZT)(t)}});var is=m((wM,up)=>{"use strict";var tI=op();up.exports=function(a){var e=+a;return e!==e||e===0?0:tI(e)}});var lp=m((kM,cp)=>{"use strict";var rI=is(),iI=Math.max,aI=Math.min;cp.exports=function(a,e){var t=rI(a);return t<0?iI(t+e,0):aI(t,e)}});var pp=m((RM,dp)=>{"use strict";var sI=is(),nI=Math.min;dp.exports=function(a){var e=sI(a);return e>0?nI(e,9007199254740991):0}});var as=m(($M,hp)=>{"use strict";var oI=pp();hp.exports=function(a){return oI(a.length)}});var bp=m((LM,mp)=>{"use strict";var uI=vr(),cI=lp(),lI=as(),fp=function(a){return function(e,t,r){var i=uI(e),s=lI(i);if(s===0)return!a&&-1;var n=cI(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}};mp.exports={includes:fp(!0),indexOf:fp(!1)}});var vp=m((MM,Sp)=>{"use strict";var dI=fe(),bo=je(),pI=vr(),hI=bp().indexOf,fI=es(),gp=dI([].push);Sp.exports=function(a,e){var t=pI(a),r=0,i=[],s;for(s in t)!bo(fI,s)&&bo(t,s)&&gp(i,s);for(;e.length>r;)bo(t,s=e[r++])&&(~hI(i,s)||gp(i,s));return i}});var go=m((CM,yp)=>{"use strict";yp.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var Ip=m((DM,Tp)=>{"use strict";var mI=vp(),bI=go();Tp.exports=Object.keys||function(e){return mI(e,bI)}});var xp=m(Ep=>{"use strict";var gI=Me(),SI=qn(),vI=jt(),yI=Ze(),TI=vr(),II=Ip();Ep.f=gI&&!SI?Object.defineProperties:function(e,t){yI(e);for(var r=TI(t),i=II(t),s=i.length,n=0,o;s>n;)vI.f(e,o=i[n++],r[o]);return e}});var So=m((OM,Ap)=>{"use strict";var EI=at();Ap.exports=EI("document","documentElement")});var Io=m((VM,Mp)=>{"use strict";var xI=Ze(),AI=xp(),Pp=go(),PI=es(),wI=So(),kI=Qa(),RI=Za(),wp=">",kp="<",yo="prototype",To="script",$p=RI("IE_PROTO"),vo=function(){},Lp=function(a){return kp+To+wp+a+kp+"/"+To+wp},Rp=function(a){a.write(Lp("")),a.close();var e=a.parentWindow.Object;return a=null,e},$I=function(){var a=kI("iframe"),e="java"+To+":",t;return a.style.display="none",wI.appendChild(a),a.src=String(e),t=a.contentWindow.document,t.open(),t.write(Lp("document.F=Object")),t.close(),t.F},ss,ns=function(){try{ss=new ActiveXObject("htmlfile")}catch(e){}ns=typeof document!="undefined"?document.domain&&ss?Rp(ss):$I():Rp(ss);for(var a=Pp.length;a--;)delete ns[yo][Pp[a]];return ns()};PI[$p]=!0;Mp.exports=Object.create||function(e,t){var r;return e!==null?(vo[yo]=xI(e),r=new vo,vo[yo]=null,r[$p]=e):r=ns(),t===void 0?r:AI.f(r,t)}});var Dp=m((_M,Cp)=>{"use strict";var LI=xe();Cp.exports=!LI(function(){function a(){}return a.prototype.constructor=null,Object.getPrototypeOf(new a)!==a.prototype})});var xo=m((NM,Op)=>{"use strict";var MI=je(),CI=K(),DI=li(),BI=Za(),OI=Dp(),Bp=BI("IE_PROTO"),Eo=Object,VI=Eo.prototype;Op.exports=OI?Eo.getPrototypeOf:function(a){var e=DI(a);if(MI(e,Bp))return e[Bp];var t=e.constructor;return CI(t)&&e instanceof t?t.prototype:e instanceof Eo?VI:null}});var Ar=m((FM,Vp)=>{"use strict";var _I=Ir();Vp.exports=function(a,e,t,r){return r&&r.enumerable?a[e]=t:_I(a,e,t),a}});var ko=m((qM,Fp)=>{"use strict";var NI=xe(),FI=K(),qI=Le(),UI=Io(),_p=xo(),HI=Ar(),jI=oe(),GI=He(),wo=jI("iterator"),Np=!1,nt,Ao,Po;[].keys&&(Po=[].keys(),"next"in Po?(Ao=_p(_p(Po)),Ao!==Object.prototype&&(nt=Ao)):Np=!0);var WI=!qI(nt)||NI(function(){var a={};return nt[wo].call(a)!==a});WI?nt={}:GI&&(nt=UI(nt));FI(nt[wo])||HI(nt,wo,function(){return this});Fp.exports={IteratorPrototype:nt,BUGGY_SAFARI_ITERATORS:Np}});var os=m((UM,Up)=>{"use strict";var YI=oe(),QI=YI("toStringTag"),qp={};qp[QI]="z";Up.exports=String(qp)==="[object z]"});var bi=m((HM,Hp)=>{"use strict";var zI=os(),KI=K(),us=gr(),JI=oe(),XI=JI("toStringTag"),ZI=Object,eE=us(function(){return arguments}())==="Arguments",tE=function(a,e){try{return a[e]}catch(t){}};Hp.exports=zI?us:function(a){var e,t,r;return a===void 0?"Undefined":a===null?"Null":typeof(t=tE(e=ZI(a),XI))=="string"?t:eE?us(e):(r=us(e))==="Object"&&KI(e.callee)?"Arguments":r}});var Gp=m((jM,jp)=>{"use strict";var rE=os(),iE=bi();jp.exports=rE?{}.toString:function(){return"[object "+iE(this)+"]"}});var gi=m((GM,Yp)=>{"use strict";var aE=os(),sE=jt().f,nE=Ir(),oE=je(),uE=Gp(),cE=oe(),Wp=cE("toStringTag");Yp.exports=function(a,e,t,r){var i=t?a:a&&a.prototype;i&&(oE(i,Wp)||sE(i,Wp,{configurable:!0,value:e}),r&&!aE&&nE(i,"toString",uE))}});var zp=m((WM,Qp)=>{"use strict";var lE=ko().IteratorPrototype,dE=Io(),pE=di(),hE=gi(),fE=Ht(),mE=function(){return this};Qp.exports=function(a,e,t,r){var i=e+" Iterator";return a.prototype=dE(lE,{next:pE(+!r,t)}),hE(a,i,!1,!0),fE[i]=mE,a}});var Jp=m((YM,Kp)=>{"use strict";var bE=fe(),gE=st();Kp.exports=function(a,e,t){try{return bE(gE(Object.getOwnPropertyDescriptor(a,e)[t]))}catch(r){}}});var Zp=m((QM,Xp)=>{"use strict";var SE=Le();Xp.exports=function(a){return SE(a)||a===null}});var th=m((zM,eh)=>{"use strict";var vE=Zp(),yE=String,TE=TypeError;eh.exports=function(a){if(vE(a))return a;throw new TE("Can't set "+yE(a)+" as a prototype")}});var Ro=m((KM,rh)=>{"use strict";var IE=Jp(),EE=Le(),xE=ai(),AE=th();rh.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var a=!1,e={},t;try{t=IE(Object.prototype,"__proto__","set"),t(e,[]),a=e instanceof Array}catch(r){}return function(i,s){return xE(i),AE(s),EE(i)&&(a?t(i,s):i.__proto__=s),i}}():void 0)});var hh=m((JM,ph)=>{"use strict";var PE=Ce(),wE=Ae(),cs=He(),lh=sp(),kE=K(),RE=zp(),ih=xo(),ah=Ro(),$E=gi(),LE=Ir(),$o=Ar(),ME=oe(),sh=Ht(),dh=ko(),CE=lh.PROPER,DE=lh.CONFIGURABLE,nh=dh.IteratorPrototype,ls=dh.BUGGY_SAFARI_ITERATORS,Si=ME("iterator"),oh="keys",vi="values",uh="entries",ch=function(){return this};ph.exports=function(a,e,t,r,i,s,n){RE(t,e,r);var o=function(S){if(S===i&&p)return p;if(!ls&&S&&S in l)return l[S];switch(S){case oh:return function(){return new t(this,S)};case vi:return function(){return new t(this,S)};case uh:return function(){return new t(this,S)}}return function(){return new t(this)}},u=e+" Iterator",c=!1,l=a.prototype,d=l[Si]||l["@@iterator"]||i&&l[i],p=!ls&&d||o(i),h=e==="Array"&&l.entries||d,f,b,g;if(h&&(f=ih(h.call(new a)),f!==Object.prototype&&f.next&&(!cs&&ih(f)!==nh&&(ah?ah(f,nh):kE(f[Si])||$o(f,Si,ch)),$E(f,u,!0,!0),cs&&(sh[u]=ch))),CE&&i===vi&&d&&d.name!==vi&&(!cs&&DE?LE(l,"name",vi):(c=!0,p=function(){return wE(d,this)})),i)if(b={values:o(vi),keys:s?p:o(oh),entries:o(uh)},n)for(g in b)(ls||c||!(g in l))&&$o(l,g,b[g]);else PE({target:e,proto:!0,forced:ls||c},b);return(!cs||n)&&l[Si]!==p&&$o(l,Si,p,{name:i}),sh[e]=p,b}});var mh=m((XM,fh)=>{"use strict";fh.exports=function(a,e){return{value:a,done:e}}});var Mo=m((ZM,yh)=>{"use strict";var BE=vr(),Lo=On(),bh=Ht(),Sh=co(),OE=jt().f,VE=hh(),ds=mh(),_E=He(),NE=Me(),vh="Array Iterator",FE=Sh.set,qE=Sh.getterFor(vh);yh.exports=VE(Array,"Array",function(a,e){FE(this,{type:vh,target:BE(a),index:0,kind:e})},function(){var a=qE(this),e=a.target,t=a.index++;if(!e||t>=e.length)return a.target=void 0,ds(void 0,!0);switch(a.kind){case"keys":return ds(t,!1);case"values":return ds(e[t],!1)}return ds([t,e[t]],!1)},"values");var gh=bh.Arguments=bh.Array;Lo("keys");Lo("values");Lo("entries");if(!_E&&NE&&gh.name!=="values")try{OE(gh,"name",{value:"values"})}catch(a){}});var Ih=m((eC,Th)=>{"use strict";var UE=oe(),HE=Ht(),jE=UE("iterator"),GE=Array.prototype;Th.exports=function(a){return a!==void 0&&(HE.Array===a||GE[jE]===a)}});var Co=m((tC,xh)=>{"use strict";var WE=bi(),Eh=ui(),YE=Sr(),QE=Ht(),zE=oe(),KE=zE("iterator");xh.exports=function(a){if(!YE(a))return Eh(a,KE)||Eh(a,"@@iterator")||QE[WE(a)]}});var Ph=m((rC,Ah)=>{"use strict";var JE=Ae(),XE=st(),ZE=Ze(),ex=oi(),tx=Co(),rx=TypeError;Ah.exports=function(a,e){var t=arguments.length<2?tx(a):e;if(XE(t))return ZE(JE(t,a));throw new rx(ex(a)+" is not iterable")}});var Rh=m((iC,kh)=>{"use strict";var ix=Ae(),wh=Ze(),ax=ui();kh.exports=function(a,e,t){var r,i;wh(a);try{if(r=ax(a,"return"),!r){if(e==="throw")throw t;return t}r=ix(r,a)}catch(s){i=!0,r=s}if(e==="throw")throw t;if(i)throw r;return wh(r),t}});var hs=m((aC,Ch)=>{"use strict";var sx=fi(),nx=Ae(),ox=Ze(),ux=oi(),cx=Ih(),lx=as(),$h=ni(),dx=Ph(),px=Co(),Lh=Rh(),hx=TypeError,ps=function(a,e){this.stopped=a,this.result=e},Mh=ps.prototype;Ch.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=sx(e,r),c,l,d,p,h,f,b,g=function(T){return c&&Lh(c,"normal",T),new ps(!0,T)},S=function(T){return i?(ox(T),o?u(T[0],T[1],g):u(T[0],T[1])):o?u(T,g):u(T)};if(s)c=a.iterator;else if(n)c=a;else{if(l=px(a),!l)throw new hx(ux(a)+" is not iterable");if(cx(l)){for(d=0,p=lx(a);p>d;d++)if(h=S(a[d]),h&&$h(Mh,h))return h;return new ps(!1)}c=dx(a,l)}for(f=s?a.next:c.next;!(b=nx(f,c)).done;){try{h=S(b.value)}catch(T){Lh(c,"throw",T)}if(typeof h=="object"&&h&&$h(Mh,h))return h}return new ps(!1)}});var Bh=m((sC,Dh)=>{"use strict";var fx=Me(),mx=jt(),bx=di();Dh.exports=function(a,e,t){fx?mx.f(a,e,bx(0,t)):a[e]=t}});var Oh=m(()=>{"use strict";var gx=Ce(),Sx=hs(),vx=Bh();gx({target:"Object",stat:!0},{fromEntries:function(e){var t={};return Sx(e,function(r,i){vx(t,r,i)},{AS_ENTRIES:!0}),t}})});var _h=m((uC,Vh)=>{"use strict";Mo();Oh();var yx=Ka();Vh.exports=yx.Object.fromEntries});var Fh=m((cC,Nh)=>{"use strict";Nh.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";Mo();var Tx=Fh(),Ix=J(),Ex=gi(),qh=Ht();for(fs in Tx)Ex(Ix[fs],fs),qh[fs]=qh.Array;var fs});var jh=m((pC,Hh)=>{"use strict";var xx=_h();Uh();Hh.exports=xx});var Do=m((hC,Gh)=>{"use strict";var Ax=jh();Gh.exports=Ax});var Wh=m(()=>{"use strict"});var Bo=m((bC,Yh)=>{"use strict";var yi=J(),Px=yr(),wx=gr(),ms=function(a){return Px.slice(0,a.length)===a};Yh.exports=function(){return ms("Bun/")?"BUN":ms("Cloudflare-Workers")?"CLOUDFLARE":ms("Deno/")?"DENO":ms("Node.js/")?"NODE":yi.Bun&&typeof Bun.version=="string"?"BUN":yi.Deno&&typeof Deno.version=="object"?"DENO":wx(yi.process)==="process"?"NODE":yi.window&&yi.document?"BROWSER":"REST"}()});var bs=m((gC,Qh)=>{"use strict";var kx=Bo();Qh.exports=kx==="NODE"});var Kh=m((SC,zh)=>{"use strict";var Rx=jt();zh.exports=function(a,e,t){return Rx.f(a,e,t)}});var Zh=m((vC,Xh)=>{"use strict";var $x=at(),Lx=Kh(),Mx=oe(),Cx=Me(),Jh=Mx("species");Xh.exports=function(a){var e=$x(a);Cx&&e&&!e[Jh]&&Lx(e,Jh,{configurable:!0,get:function(){return this}})}});var tf=m((yC,ef)=>{"use strict";var Dx=ni(),Bx=TypeError;ef.exports=function(a,e){if(Dx(e,a))return a;throw new Bx("Incorrect invocation")}});var Vo=m((TC,rf)=>{"use strict";var Ox=fe(),Vx=K(),Oo=ci(),_x=Ox(Function.toString);Vx(Oo.inspectSource)||(Oo.inspectSource=function(a){return _x(a)});rf.exports=Oo.inspectSource});var cf=m((IC,uf)=>{"use strict";var Nx=fe(),Fx=xe(),af=K(),qx=bi(),Ux=at(),Hx=Vo(),sf=function(){},nf=Ux("Reflect","construct"),_o=/^\s*(?:class|function)\b/,jx=Nx(_o.exec),Gx=!_o.test(sf),Ti=function(e){if(!af(e))return!1;try{return nf(sf,[],e),!0}catch(t){return!1}},of=function(e){if(!af(e))return!1;switch(qx(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return Gx||!!jx(_o,Hx(e))}catch(t){return!0}};of.sham=!0;uf.exports=!nf||Fx(function(){var a;return Ti(Ti.call)||!Ti(Object)||!Ti(function(){a=!0})||a})?of:Ti});var df=m((EC,lf)=>{"use strict";var Wx=cf(),Yx=oi(),Qx=TypeError;lf.exports=function(a){if(Wx(a))return a;throw new Qx(Yx(a)+" is not a constructor")}});var No=m((xC,hf)=>{"use strict";var pf=Ze(),zx=df(),Kx=Sr(),Jx=oe(),Xx=Jx("species");hf.exports=function(a,e){var t=pf(a).constructor,r;return t===void 0||Kx(r=pf(t)[Xx])?e:zx(r)}});var mf=m((AC,ff)=>{"use strict";var Zx=fe();ff.exports=Zx([].slice)});var gf=m((PC,bf)=>{"use strict";var eA=TypeError;bf.exports=function(a,e){if(a<e)throw new eA("Not enough arguments");return a}});var Fo=m((wC,Sf)=>{"use strict";var tA=yr();Sf.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(tA)});var zo=m((kC,wf)=>{"use strict";var Pe=J(),rA=lo(),iA=fi(),vf=K(),aA=je(),Pf=xe(),yf=So(),sA=mf(),Tf=Qa(),nA=gf(),oA=Fo(),uA=bs(),Wo=Pe.setImmediate,Yo=Pe.clearImmediate,cA=Pe.process,qo=Pe.Dispatch,lA=Pe.Function,If=Pe.MessageChannel,dA=Pe.String,Uo=0,Ii={},Ef="onreadystatechange",Ei,Wt,Ho,jo;Pf(function(){Ei=Pe.location});var Qo=function(a){if(aA(Ii,a)){var e=Ii[a];delete Ii[a],e()}},Go=function(a){return function(){Qo(a)}},xf=function(a){Qo(a.data)},Af=function(a){Pe.postMessage(dA(a),Ei.protocol+"//"+Ei.host)};(!Wo||!Yo)&&(Wo=function(e){nA(arguments.length,1);var t=vf(e)?e:lA(e),r=sA(arguments,1);return Ii[++Uo]=function(){rA(t,void 0,r)},Wt(Uo),Uo},Yo=function(e){delete Ii[e]},uA?Wt=function(a){cA.nextTick(Go(a))}:qo&&qo.now?Wt=function(a){qo.now(Go(a))}:If&&!oA?(Ho=new If,jo=Ho.port2,Ho.port1.onmessage=xf,Wt=iA(jo.postMessage,jo)):Pe.addEventListener&&vf(Pe.postMessage)&&!Pe.importScripts&&Ei&&Ei.protocol!=="file:"&&!Pf(Af)?(Wt=Af,Pe.addEventListener("message",xf,!1)):Ef in Tf("script")?Wt=function(a){yf.appendChild(Tf("script"))[Ef]=function(){yf.removeChild(this),Qo(a)}}:Wt=function(a){setTimeout(Go(a),0)});wf.exports={set:Wo,clear:Yo}});var $f=m((RC,Rf)=>{"use strict";var kf=J(),pA=Me(),hA=Object.getOwnPropertyDescriptor;Rf.exports=function(a){if(!pA)return kf[a];var e=hA(kf,a);return e&&e.value}});var Ko=m(($C,Mf)=>{"use strict";var Lf=function(){this.head=null,this.tail=null};Lf.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}}};Mf.exports=Lf});var Df=m((LC,Cf)=>{"use strict";var fA=yr();Cf.exports=/ipad|iphone|ipod/i.test(fA)&&typeof Pebble!="undefined"});var Of=m((MC,Bf)=>{"use strict";var mA=yr();Bf.exports=/web0s(?!.*chrome)/i.test(mA)});var Hf=m((CC,Uf)=>{"use strict";var wr=J(),bA=$f(),Vf=fi(),Jo=zo().set,gA=Ko(),SA=Fo(),vA=Df(),yA=Of(),Xo=bs(),_f=wr.MutationObserver||wr.WebKitMutationObserver,Nf=wr.document,Ff=wr.process,gs=wr.Promise,tu=bA("queueMicrotask"),Pr,Zo,eu,Ss,qf;tu||(xi=new gA,Ai=function(){var a,e;for(Xo&&(a=Ff.domain)&&a.exit();e=xi.get();)try{e()}catch(t){throw xi.head&&Pr(),t}a&&a.enter()},!SA&&!Xo&&!yA&&_f&&Nf?(Zo=!0,eu=Nf.createTextNode(""),new _f(Ai).observe(eu,{characterData:!0}),Pr=function(){eu.data=Zo=!Zo}):!vA&&gs&&gs.resolve?(Ss=gs.resolve(void 0),Ss.constructor=gs,qf=Vf(Ss.then,Ss),Pr=function(){qf(Ai)}):Xo?Pr=function(){Ff.nextTick(Ai)}:(Jo=Vf(Jo,wr),Pr=function(){Jo(Ai)}),tu=function(a){xi.head||Pr(),xi.add(a)});var xi,Ai;Uf.exports=tu});var Gf=m((DC,jf)=>{"use strict";jf.exports=function(a,e){try{arguments.length===1?console.error(a):console.error(a,e)}catch(t){}}});var vs=m((BC,Wf)=>{"use strict";Wf.exports=function(a){try{return{error:!1,value:a()}}catch(e){return{error:!0,value:e}}}});var Yt=m((OC,Yf)=>{"use strict";var TA=J();Yf.exports=TA.Promise});var kr=m((VC,Jf)=>{"use strict";var IA=J(),Pi=Yt(),EA=K(),xA=ho(),AA=Vo(),PA=oe(),Qf=Bo(),wA=He(),ru=Gn(),zf=Pi&&Pi.prototype,kA=PA("species"),iu=!1,Kf=EA(IA.PromiseRejectionEvent),RA=xA("Promise",function(){var a=AA(Pi),e=a!==String(Pi);if(!e&&ru===66||wA&&!(zf.catch&&zf.finally))return!0;if(!ru||ru<51||!/native code/.test(a)){var t=new Pi(function(s){s(1)}),r=function(s){s(function(){},function(){})},i=t.constructor={};if(i[kA]=r,iu=t.then(function(){})instanceof r,!iu)return!0}return!e&&(Qf==="BROWSER"||Qf==="DENO")&&!Kf});Jf.exports={CONSTRUCTOR:RA,REJECTION_EVENT:Kf,SUBCLASSING:iu}});var Rr=m((_C,Zf)=>{"use strict";var Xf=st(),$A=TypeError,LA=function(a){var e,t;this.promise=new a(function(r,i){if(e!==void 0||t!==void 0)throw new $A("Bad Promise constructor");e=r,t=i}),this.resolve=Xf(e),this.reject=Xf(t)};Zf.exports.f=function(a){return new LA(a)}});var Sm=m(()=>{"use strict";var MA=Ce(),CA=He(),Es=bs(),xt=J(),Cr=Ae(),em=Ar(),tm=Ro(),DA=gi(),BA=Zh(),OA=st(),Is=K(),VA=Le(),_A=tf(),NA=No(),nm=zo().set,uu=Hf(),FA=Gf(),qA=vs(),UA=Ko(),om=co(),xs=Yt(),cu=kr(),um=Rr(),As="Promise",cm=cu.CONSTRUCTOR,HA=cu.REJECTION_EVENT,jA=cu.SUBCLASSING,au=om.getterFor(As),GA=om.set,$r=xs&&xs.prototype,Qt=xs,ys=$r,lm=xt.TypeError,su=xt.document,lu=xt.process,nu=um.f,WA=nu,YA=!!(su&&su.createEvent&&xt.dispatchEvent),dm="unhandledrejection",QA="rejectionhandled",rm=0,pm=1,zA=2,du=1,hm=2,Ts,im,KA,am,fm=function(a){var e;return VA(a)&&Is(e=a.then)?e:!1},mm=function(a,e){var t=e.value,r=e.state===pm,i=r?a.ok:a.fail,s=a.resolve,n=a.reject,o=a.domain,u,c,l;try{i?(r||(e.rejection===hm&&XA(e),e.rejection=du),i===!0?u=t:(o&&o.enter(),u=i(t),o&&(o.exit(),l=!0)),u===a.promise?n(new lm("Promise-chain cycle")):(c=fm(u))?Cr(c,u,s,n):s(u)):n(t)}catch(d){o&&!l&&o.exit(),n(d)}},bm=function(a,e){a.notified||(a.notified=!0,uu(function(){for(var t=a.reactions,r;r=t.get();)mm(r,a);a.notified=!1,e&&!a.rejection&&JA(a)}))},gm=function(a,e,t){var r,i;YA?(r=su.createEvent("Event"),r.promise=e,r.reason=t,r.initEvent(a,!1,!0),xt.dispatchEvent(r)):r={promise:e,reason:t},!HA&&(i=xt["on"+a])?i(r):a===dm&&FA("Unhandled promise rejection",t)},JA=function(a){Cr(nm,xt,function(){var e=a.facade,t=a.value,r=sm(a),i;if(r&&(i=qA(function(){Es?lu.emit("unhandledRejection",t,e):gm(dm,e,t)}),a.rejection=Es||sm(a)?hm:du,i.error))throw i.value})},sm=function(a){return a.rejection!==du&&!a.parent},XA=function(a){Cr(nm,xt,function(){var e=a.facade;Es?lu.emit("rejectionHandled",e):gm(QA,e,a.value)})},Lr=function(a,e,t){return function(r){a(e,r,t)}},Mr=function(a,e,t){a.done||(a.done=!0,t&&(a=t),a.value=e,a.state=zA,bm(a,!0))},ou=function(a,e,t){if(!a.done){a.done=!0,t&&(a=t);try{if(a.facade===e)throw new lm("Promise can't be resolved itself");var r=fm(e);r?uu(function(){var i={done:!1};try{Cr(r,e,Lr(ou,i,a),Lr(Mr,i,a))}catch(s){Mr(i,s,a)}}):(a.value=e,a.state=pm,bm(a,!1))}catch(i){Mr({done:!1},i,a)}}};if(cm&&(Qt=function(e){_A(this,ys),OA(e),Cr(Ts,this);var t=au(this);try{e(Lr(ou,t),Lr(Mr,t))}catch(r){Mr(t,r)}},ys=Qt.prototype,Ts=function(e){GA(this,{type:As,done:!1,notified:!1,parent:!1,reactions:new UA,rejection:!1,state:rm,value:void 0})},Ts.prototype=em(ys,"then",function(e,t){var r=au(this),i=nu(NA(this,Qt));return r.parent=!0,i.ok=Is(e)?e:!0,i.fail=Is(t)&&t,i.domain=Es?lu.domain:void 0,r.state===rm?r.reactions.add(i):uu(function(){mm(i,r)}),i.promise}),im=function(){var a=new Ts,e=au(a);this.promise=a,this.resolve=Lr(ou,e),this.reject=Lr(Mr,e)},um.f=nu=function(a){return a===Qt||a===KA?new im(a):WA(a)},!CA&&Is(xs)&&$r!==Object.prototype)){am=$r.then,jA||em($r,"then",function(e,t){var r=this;return new Qt(function(i,s){Cr(am,r,i,s)}).then(e,t)},{unsafe:!0});try{delete $r.constructor}catch(a){}tm&&tm($r,ys)}MA({global:!0,constructor:!0,wrap:!0,forced:cm},{Promise:Qt});DA(Qt,As,!1,!0);BA(As)});var Em=m((qC,Im)=>{"use strict";var ZA=oe(),ym=ZA("iterator"),Tm=!1;try{vm=0,pu={next:function(){return{done:!!vm++}},return:function(){Tm=!0}},pu[ym]=function(){return this},Array.from(pu,function(){throw 2})}catch(a){}var vm,pu;Im.exports=function(a,e){try{if(!e&&!Tm)return!1}catch(i){return!1}var t=!1;try{var r={};r[ym]=function(){return{next:function(){return{done:t=!0}}}},a(r)}catch(i){}return t}});var hu=m((UC,xm)=>{"use strict";var eP=Yt(),tP=Em(),rP=kr().CONSTRUCTOR;xm.exports=rP||!tP(function(a){eP.all(a).then(void 0,function(){})})});var Am=m(()=>{"use strict";var iP=Ce(),aP=Ae(),sP=st(),nP=Rr(),oP=vs(),uP=hs(),cP=hu();iP({target:"Promise",stat:!0,forced:cP},{all:function(e){var t=this,r=nP.f(t),i=r.resolve,s=r.reject,n=oP(function(){var o=sP(t.resolve),u=[],c=0,l=1;uP(e,function(d){var p=c++,h=!1;l++,aP(o,t,d).then(function(f){h||(h=!0,u[p]=f,--l||i(u))},s)}),--l||i(u)});return n.error&&s(n.value),r.promise}})});var wm=m(()=>{"use strict";var lP=Ce(),dP=He(),pP=kr().CONSTRUCTOR,mu=Yt(),hP=at(),fP=K(),mP=Ar(),Pm=mu&&mu.prototype;lP({target:"Promise",proto:!0,forced:pP,real:!0},{catch:function(a){return this.then(void 0,a)}});!dP&&fP(mu)&&(fu=hP("Promise").prototype.catch,Pm.catch!==fu&&mP(Pm,"catch",fu,{unsafe:!0}));var fu});var km=m(()=>{"use strict";var bP=Ce(),gP=Ae(),SP=st(),vP=Rr(),yP=vs(),TP=hs(),IP=hu();bP({target:"Promise",stat:!0,forced:IP},{race:function(e){var t=this,r=vP.f(t),i=r.reject,s=yP(function(){var n=SP(t.resolve);TP(e,function(o){gP(n,t,o).then(r.resolve,i)})});return s.error&&i(s.value),r.promise}})});var Rm=m(()=>{"use strict";var EP=Ce(),xP=Rr(),AP=kr().CONSTRUCTOR;EP({target:"Promise",stat:!0,forced:AP},{reject:function(e){var t=xP.f(this),r=t.reject;return r(e),t.promise}})});var bu=m((JC,$m)=>{"use strict";var PP=Ze(),wP=Le(),kP=Rr();$m.exports=function(a,e){if(PP(a),wP(e)&&e.constructor===a)return e;var t=kP.f(a),r=t.resolve;return r(e),t.promise}});var Cm=m(()=>{"use strict";var RP=Ce(),$P=at(),Lm=He(),LP=Yt(),Mm=kr().CONSTRUCTOR,MP=bu(),CP=$P("Promise"),DP=Lm&&!Mm;RP({target:"Promise",stat:!0,forced:Lm||Mm},{resolve:function(e){return MP(DP&&this===CP?LP:this,e)}})});var Dm=m(()=>{"use strict";Sm();Am();wm();km();Rm();Cm()});var _m=m(()=>{"use strict";var BP=Ce(),OP=He(),Ps=Yt(),VP=xe(),Om=at(),Vm=K(),_P=No(),Bm=bu(),NP=Ar(),Su=Ps&&Ps.prototype,FP=!!Ps&&VP(function(){Su.finally.call({then:function(){}},function(){})});BP({target:"Promise",proto:!0,real:!0,forced:FP},{finally:function(a){var e=_P(this,Om("Promise")),t=Vm(a);return this.then(t?function(r){return Bm(e,a()).then(function(){return r})}:a,t?function(r){return Bm(e,a()).then(function(){throw r})}:a)}});!OP&&Vm(Ps)&&(gu=Om("Promise").prototype.finally,Su.finally!==gu&&NP(Su,"finally",gu,{unsafe:!0}));var gu});var ws=m((aD,Nm)=>{"use strict";var qP=at();Nm.exports=qP});var qm=m((sD,Fm)=>{"use strict";Wh();Dm();_m();var UP=ws();Fm.exports=UP("Promise","finally")});var Hm=m((nD,Um)=>{"use strict";var HP=qm();Um.exports=HP});var ks=m((oD,jm)=>{"use strict";var jP=Hm();jm.exports=jP});var mb=m(()=>{"use strict";var vw=Ce(),yw=li(),Tw=as(),Iw=is(),Ew=On();vw({target:"Array",proto:!0},{at:function(e){var t=yw(this),r=Tw(t),i=Iw(e),s=i>=0?i:r+i;return s<0||s>=r?void 0:t[s]}});Ew("at")});var gb=m((b0,bb)=>{"use strict";mb();var xw=ws();bb.exports=xw("Array","at")});var vb=m((g0,Sb)=>{"use strict";var Aw=gb();Sb.exports=Aw});var $i=m((S0,yb)=>{"use strict";var Pw=vb();yb.exports=Pw});var Ag=m(()=>{"use strict"});var Pg=m(()=>{"use strict"});var kg=m((A_,wg)=>{"use strict";var Mk=Le(),Ck=gr(),Dk=oe(),Bk=Dk("match");wg.exports=function(a){var e;return Mk(a)&&((e=a[Bk])!==void 0?!!e:Ck(a)==="RegExp")}});var $g=m((P_,Rg)=>{"use strict";var Ok=bi(),Vk=String;Rg.exports=function(a){if(Ok(a)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return Vk(a)}});var Mg=m((w_,Lg)=>{"use strict";var _k=Ze();Lg.exports=function(){var a=_k(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 Bg=m((k_,Dg)=>{"use strict";var Nk=Ae(),Fk=je(),qk=ni(),Uk=Mg(),Cg=RegExp.prototype;Dg.exports=function(a){var e=a.flags;return e===void 0&&!("flags"in Cg)&&!Fk(a,"flags")&&qk(Cg,a)?Nk(Uk,a):e}});var Vg=m((R_,Og)=>{"use strict";var Qu=fe(),Hk=li(),jk=Math.floor,Wu=Qu("".charAt),Gk=Qu("".replace),Yu=Qu("".slice),Wk=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,Yk=/\$([$&'`]|\d{1,2})/g;Og.exports=function(a,e,t,r,i,s){var n=t+a.length,o=r.length,u=Yk;return i!==void 0&&(i=Hk(i),u=Wk),Gk(s,u,function(c,l){var d;switch(Wu(l,0)){case"$":return"$";case"&":return a;case"`":return Yu(e,0,t);case"'":return Yu(e,n);case"<":d=i[Yu(l,1,-1)];break;default:var p=+l;if(p===0)return c;if(p>o){var h=jk(p/10);return h===0?c:h<=o?r[h-1]===void 0?Wu(l,1):r[h-1]+Wu(l,1):c}d=r[p-1]}return d===void 0?"":d})}});var Fg=m(()=>{"use strict";var Qk=Ce(),zk=Ae(),Ku=fe(),_g=ai(),Kk=K(),Jk=Sr(),Xk=kg(),Hr=$g(),Zk=ui(),eR=Bg(),tR=Vg(),rR=oe(),iR=He(),aR=rR("replace"),sR=TypeError,zu=Ku("".indexOf),nR=Ku("".replace),Ng=Ku("".slice),oR=Math.max;Qk({target:"String",proto:!0},{replaceAll:function(e,t){var r=_g(this),i,s,n,o,u,c,l,d,p,h,f=0,b="";if(!Jk(e)){if(i=Xk(e),i&&(s=Hr(_g(eR(e))),!~zu(s,"g")))throw new sR("`.replaceAll` does not allow non-global regexes");if(n=Zk(e,aR),n)return zk(n,e,r,t);if(iR&&i)return nR(Hr(r),e,t)}for(o=Hr(r),u=Hr(e),c=Kk(t),c||(t=Hr(t)),l=u.length,d=oR(1,l),p=zu(o,u);p!==-1;)h=c?Hr(t(u,p,o)):tR(u,o,p,[],void 0,t),b+=Ng(o,f,p)+h,f=p+l,p=p+d>o.length?-1:zu(o,u,p+d);return f<o.length&&(b+=Ng(o,f)),b}})});var Ug=m((M_,qg)=>{"use strict";Ag();Pg();Fg();var uR=ws();qg.exports=uR("String","replaceAll")});var jg=m((C_,Hg)=>{"use strict";var cR=Ug();Hg.exports=cR});var Wg=m((D_,Gg)=>{"use strict";var lR=jg();Gg.exports=lR});var cl="2.0.108-dev.34728b10.0";var he=(i=>(i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused",i))(he||{}),Et=(v=>(v.MPEG="MPEG",v.DASH="DASH",v.DASH_SEP="DASH_SEP",v.DASH_SEP_VK="DASH_SEP",v.DASH_WEBM="DASH_WEBM",v.DASH_WEBM_AV1="DASH_WEBM_AV1",v.DASH_STREAMS="DASH_STREAMS",v.DASH_WEBM_VK="DASH_WEBM",v.DASH_ONDEMAND="DASH_ONDEMAND",v.DASH_ONDEMAND_VK="DASH_ONDEMAND",v.DASH_LIVE="DASH_LIVE",v.DASH_LIVE_CMAF="DASH_LIVE_CMAF",v.DASH_LIVE_WEBM="DASH_LIVE_WEBM",v.HLS="HLS",v.HLS_ONDEMAND="HLS_ONDEMAND",v.HLS_JS="HLS",v.HLS_LIVE="HLS_LIVE",v.HLS_LIVE_CMAF="HLS_LIVE_CMAF",v.WEB_RTC_LIVE="WEB_RTC_LIVE",v))(Et||{});var Ga=(i=>(i.NOT_AVAILABLE="NOT_AVAILABLE",i.AVAILABLE="AVAILABLE",i.CONNECTING="CONNECTING",i.CONNECTED="CONNECTED",i))(Ga||{}),$n=(r=>(r.HTTP1="http1",r.HTTP2="http2",r.QUIC="quic",r))($n||{});var Ln=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(Ln||{});import{assertNever as ml,assertNonNullable as $v,isNonNullable as Wa,ValueSubject as Mn,Subject as Lv,Subscription as Mv,merge as Cv,observableFrom as Dv,fromEvent as dl,map as pl,tap as hl,filterChanged as Bv,isNullable as Cn,ErrorCategory as fl}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 Ya=class{constructor(e){this.connection$=new Mn(void 0);this.castState$=new Mn("NOT_AVAILABLE");this.errorEvent$=new Lv;this.realCastState$=new Mn("NOT_AVAILABLE");this.subscription=new Mv;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=Wa((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:fl.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(){Wa(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(dl(r,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(i=>{var s,n,o;switch(i.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=(o=(n=(s=r.getCurrentSession())==null?void 0:s.getMediaSession())==null?void 0:n.media)==null?void 0:o.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return ml(i.sessionState)}})).add(Cv(dl(r,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(hl(i=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(i)}`})}),pl(i=>i.castState)),Dv([r.getCastState()])).pipe(Bv(),pl(Ov),hl(i=>{this.log({message:`realCastState$: ${i}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(i=>{var o,u;let s=i==="CONNECTED",n=Wa(this.connection$.getValue());if(s&&!n){let c=r.getCurrentSession();$v(c);let l=c.getCastDevice(),d=(u=(o=c.getMediaSession())==null?void 0:o.media)==null?void 0:u.contentId;(Cn(d)||d===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:c,castDevice:l}))}else!s&&n&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(i==="CONNECTED"?Wa(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:fl.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 ml(a)}};var US=Xe(Do(),1);var eb=Xe(ks(),1);import{assertNever as Gm}from"@vkontakte/videoplayer-shared";var ae=(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:Gm(t)}return a},vu=(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:Gm(e)}};var E=(a,e,t=!1)=>{let r=a.getTransition();(t||!r||r.to===e)&&a.setState(e)};import{isNonNullable as GP,Subject as Rs,merge as Wm}from"@vkontakte/videoplayer-shared";var C=class{constructor(e){this.transitionStarted$=new Rs;this.transitionEnded$=new Rs;this.transitionUpdated$=new Rs;this.forceChanged$=new Rs;this.stateChangeStarted$=Wm(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=Wm(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||GP(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 WP}from"@vkontakte/videoplayer-shared";var Ym=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 WP(a)}};import{assertNever as Dr,assertNonNullable as zt,debounce as Qm,ErrorCategory as zm,fromEvent as Kt,isNonNullable as Km,map as Jm,merge as Xm,observableFrom as YP,Subject as QP,Subscription as yu,timeout as zP,getHighestQuality as KP}from"@vkontakte/videoplayer-shared";var JP=5,XP=5,ZP=500,Zm=7e3,wi=class{constructor(e){this.subscription=new yu;this.loadMediaTimeoutSubscription=new yu;this.videoState=new C("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:Dr(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:Dr(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:Dr(e)}break}default:Dr(r)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(Ym(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 yu;this.subscription.add(e),this.subscription.add(Xm(this.videoState.stateChangeStarted$.pipe(Jm(i=>`stateChangeStarted$ ${JSON.stringify(i)}`)),this.videoState.stateChangeEnded$.pipe(Jm(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 QP;e.add(i.pipe(Qm(ZP)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add(Kt(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)>JP)&&i.next(o),s=o})),e.add(Kt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(Kt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),i=>{this.logRemoteEvent(i),i.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(Kt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),i=>{this.logRemoteEvent(i),i.value?this.handleRemotePause():this.handleRemotePlay()}),t(Kt(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<XP&&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:Dr(n)}}),t(Kt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),i=>{this.logRemoteEvent(i),this.handleRemoteVolumeChange({volume:i.value})}),t(Kt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),i=>{this.logRemoteEvent(i),this.handleRemoteVolumeChange({muted:i.value})});let r=Xm(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,YP(["init"])).pipe(Qm(0));t(r,this.syncPlayback)}restoreSession(e){this.log({message:"restoreSession"});let{remotePlayer:t}=this.params.connection;if(e.playerState!==chrome.cast.media.PlayerState.IDLE){t.isPaused?(this.videoState.setState("paused"),E(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),E(this.params.desiredState.playbackState,"playing"));let r=this.params.output.isLive$.getValue();this.params.output.duration$.next(r?0:t.duration),this.params.output.position$.next(r?0:t.currentTime),this.params.desiredState.seekState.setState({state:"none"})}}prepare(){let e=this.params.format;this.log({message:`[prepare] format: ${e}`});let t=this.createMediaInfo(e),r=this.createLoadRequest(t);this.loadMedia(r)}handleRemotePause(){let e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)==="paused"||e==="playing")&&(this.videoState.setState("paused"),E(this.params.desiredState.playbackState,"paused"))}handleRemotePlay(){let e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)==="playing"||e==="paused")&&(this.videoState.setState("playing"),E(this.params.desiredState.playbackState,"playing"))}handleRemoteReady(){var t;let e=this.videoState.getTransition();(e==null?void 0:e.to)==="ready"&&this.videoState.setState("ready"),((t=this.params.desiredState.playbackState.getTransition())==null?void 0:t.to)==="ready"&&E(this.params.desiredState.playbackState,"ready")}handleRemoteStop(){this.videoState.getState()!=="stopped"&&this.videoState.setState("stopped")}handleRemoteVolumeChange(e){var i,s;let t=this.params.output.volume$.getValue(),r={volume:(i=e.volume)!=null?i:t.volume,muted:(s=e.muted)!=null?s:t.muted};(r.volume!==t.volume||r.muted!==r.muted)&&this.params.output.volume$.next(r)}seek(e){this.params.output.willSeekEvent$.next();let{remotePlayer:t,remotePlayerController:r}=this.params.connection;t.currentTime=e,r.seek()}stop(){let{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){var c;let t=this.params.source,r,i,s;switch(e){case"MPEG":{let l=t[e];zt(l);let d=KP(Object.keys(l));zt(d);let p=l[d];zt(p),r=p,i="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let l=t[e];zt(l),r=l.url,i="application/x-mpegurl",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":{let l=t[e];zt(l),r=l.url,i="application/dash+xml",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let l=t[e];zt(l),r=l.url,i="application/dash+xml",s=chrome.cast.media.StreamType.LIVE;break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let l=t[e];zt(l),r=ae(l.url),i="application/x-mpegurl",s=chrome.cast.media.StreamType.LIVE;break}case"DASH_LIVE":case"WEB_RTC_LIVE":{let l="Unsupported format for Chromecast",d=new Error(l);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:zm.VIDEO_PIPELINE,message:l,thrown:d}),d}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return Dr(e)}let n=new chrome.cast.media.MediaInfo((c=this.params.meta.videoId)!=null?c:r,i);n.contentUrl=r,n.streamType=s,n.metadata=new chrome.cast.media.GenericMediaMetadata;let{title:o,subtitle:u}=this.params.meta;return Km(o)&&(n.metadata.title=o),Km(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(zP(Zm).subscribe(()=>s(`timeout(${Zm})`)))});(0,eb.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:zm.VIDEO_PIPELINE,message:s,thrown:i})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};import{clearVideoElement as rb}from"@vkontakte/videoplayer-shared";import{clearVideoElement as ew}from"@vkontakte/videoplayer-shared";var tb=a=>{try{a.pause(),a.playbackRate=0,ew(a),a.remove()}catch(e){console.error(e)}};import{fromEvent as tw,Subscription as rw}from"@vkontakte/videoplayer-shared";var Tu=class{constructor(){this.attribute="data-pool-reused"}get(e){return e.hasAttribute(this.attribute)}set(e,t){e.toggleAttribute(this.attribute,t)}delete(e){e.removeAttribute(this.attribute)}},Iu=window.WeakMap?new WeakMap:new Tu,Eu=window.WeakMap?new WeakMap:new Map,iw=(a,e=20)=>{let t=0;return tw(a,"ratechange").subscribe(r=>{t++,t>=e&&(a.currentTime=a.currentTime,t=0)})},me=(a,{audioVideoSyncRate:e})=>{let t=a.querySelector("video"),r=!!t;t?rb(t):(t=document.createElement("video"),a.appendChild(t)),Iu.set(t,r);let i=new rw;return i.add(iw(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},be=a=>{let e=Eu.get(a);e==null||e.unsubscribe(),Eu.delete(a);let t=Iu.get(a);Iu.delete(a),t?rb(a):tb(a)};import{assertNonNullable as ki,isNonNullable as tt,isNullable as nw,fromEvent as Br,merge as ib,observableFrom as ab,filterChanged as sb,map as Ri,Subject as nb,Subscription as ow,ValueSubject as uw,ErrorCategory as cw}from"@vkontakte/videoplayer-shared";import{isNonNullable as xu,isNullable as aw,Subscription as sw}from"@vkontakte/videoplayer-shared";var $s=(a,e,t,{equal:r=(n,o)=>n===o,changed$:i,onError:s}={})=>{let n=a.getState(),o=e(),u=aw(i),c=new sw;return i&&c.add(i.subscribe(l=>{let d=a.getState();r(l,d)&&a.setState(l)},s)),r(o,n)||(t(n),u&&a.setState(n)),c.add(a.stateChangeStarted$.subscribe(l=>{t(l.to),u&&a.setState(l.to)},s)),c},et=(a,e,t)=>$s(e,()=>a.loop,r=>{xu(r)&&(a.loop=r)},{onError:t}),ge=(a,e,t,r)=>$s(e,()=>({muted:a.muted,volume:a.volume}),i=>{xu(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}),De=(a,e,t,r)=>$s(e,()=>a.playbackRate,i=>{xu(i)&&(a.playbackRate=i)},{changed$:t,onError:r}),At=$s;var lw=a=>["__",a.language,a.label].join("|"),dw=(a,e)=>{if(a.id===e)return!0;let[t,r,i]=e.split("|");return a.language===r&&a.label===i},Au=class a{constructor(){this.available$=new nb;this.current$=new uw(void 0);this.error$=new nb;this.subscription=new ow;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:cw.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(At(t.internalTextTracks,()=>Object.values(this.internalTracks),s=>{tt(s)&&this.setInternal(s)},{equal:(s,n)=>tt(s)&&tt(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(Ri(s=>s.filter(({type:n})=>n==="internal"))),onError:i})),this.subscription.add(At(t.externalTextTracks,()=>Object.values(this.externalTracks),s=>{tt(s)&&this.setExternal(s)},{equal:(s,n)=>tt(s)&&tt(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(Ri(s=>s.filter(({type:n})=>n==="external"))),onError:i})),this.subscription.add(At(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(At(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.activeCues)}))}subscribe(){ki(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(ib(Br(e,"addtrack"),Br(e,"removetrack"),ab(["init"])).pipe(Ri(()=>this.htmlTextTracksAsArray().map(r=>this.htmlTextTrackToITextTrack(r))),sb((r,i)=>r.length===i.length&&r.every(({id:s},n)=>s===i[n].id))).subscribe(this.available$)),this.subscription.add(ib(Br(e,"change"),ab(["init"])).pipe(Ri(()=>this.htmlTextTracksAsArray().find(({mode:r})=>r==="showing")),Ri(r=>r&&this.htmlTextTrackToITextTrack(r).id),sb()).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 c,l,d,p,h;let u=(l=(c=o.target)==null?void 0:c.cues)!=null?l:null;u&&u.length&&(this.applyCueSettings((p=(d=o.target)==null?void 0:d.cues)!=null?p:null),(h=o.target)==null||h.removeEventListener("cuechange",i))};(n=r.track)==null||n.addEventListener("cuechange",i)})),this.subscription.add(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;tt(t.align)&&(i.align=t.align),tt(t.position)&&(i.position=t.position),tt(t.size)&&(i.size=t.size),tt(t.line)&&(i.line=t.line)}}htmlTextTracksAsArray(e=!1){ki(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:lw(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){ki(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(nw(e)||!dw(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){ki(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){ki(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)}},Be=Au;var ut=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 ob=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},Pu=a=>{let e=ob(a);return!!(e&&e.fullscreenElement&&e.fullscreenElement===a)},ub=a=>{let e=ob(a);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===a)};import{fromEvent as Oe,map as Pt,merge as lb,filterChanged as hw,isNonNullable as db,Subject as fw,filter as pb,mapTo as hb,combine as mw,once as bw,ErrorCategory as gw,ValueSubject as fb,clientChecker as Sw}from"@vkontakte/videoplayer-shared";var pw=3,cb=(a,e,t=pw)=>{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 Se=a=>{let e=v=>Oe(a,v).pipe(hb(void 0)),r=lb(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(v=>Oe(a,v))).pipe(Pt(v=>v.type==="ended"?a.readyState<2:a.readyState<3),hw()),i=lb(Oe(a,"progress"),Oe(a,"timeupdate")).pipe(Pt(()=>cb(a.buffered,a.currentTime))),s=Sw.isSafari?mw({play:e("play").pipe(bw()),playing:e("playing")}).pipe(hb(void 0)):e("playing"),n=Oe(a,"volumechange").pipe(Pt(()=>({muted:a.muted,volume:a.volume}))),o=Oe(a,"ratechange").pipe(Pt(()=>a.playbackRate)),u=Oe(a,"error").pipe(pb(()=>!!(a.error||a.played.length)),Pt(()=>{var y;let v=a.error;return{id:v?`MediaError#${v.code}`:"HtmlVideoError",category:gw.VIDEO_PIPELINE,message:v?v.message:"Error event from HTML video element",thrown:(y=a.error)!=null?y:void 0}})),c=Oe(a,"timeupdate").pipe(Pt(()=>a.currentTime)),l=new fw,d=.3,p;c.subscribe(v=>{a.loop&&db(p)&&db(v)&&p>=a.duration-d&&v<=d&&l.next(p),p=v});let h=e("pause").pipe(pb(()=>!a.error&&p!==a.duration)),f=Oe(a,"enterpictureinpicture"),b=Oe(a,"leavepictureinpicture"),g=new fb(ub(a));f.subscribe(()=>g.next(!0)),b.subscribe(()=>g.next(!1));let S=new fb(Pu(a));return Oe(a,"fullscreenchange").pipe(Pt(()=>Pu(a))).subscribe(S),{playing$:s,pause$:h,canplay$:e("canplay"),ended$:e("ended"),looped$:l,error$:u,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:c,durationChange$:Oe(a,"durationchange").pipe(Pt(()=>a.duration)),isBuffering$:r,currentBuffer$:i,volumeState$:n,playbackRateState$:o,inPiP$:g,inFullscreen$:S}};import{VideoQuality as wt}from"@vkontakte/videoplayer-shared";var kt=a=>{switch(a){case"mobile":return wt.Q_144P;case"lowest":return wt.Q_240P;case"low":return wt.Q_360P;case"sd":case"medium":return wt.Q_480P;case"hd":case"high":return wt.Q_720P;case"fullhd":case"full":return wt.Q_1080P;case"quadhd":case"quad":return wt.Q_1440P;case"ultrahd":case"ultra":return wt.Q_2160P}};var Jt=Xe($i(),1);import{isNonNullable as ve,isNullable as ku,now as kb,isHigher as Ru,isHigherOrEqual as xb,isInvariantQuality as Ab,isLower as $u,isLowerOrEqual as Pb,videoSizeToQuality as ww,assertNotEmptyArray as Rb,assertNonNullable as kw}from"@vkontakte/videoplayer-shared";var wu=!1,ct={},Tb=a=>{wu=a},Ib=()=>{ct={}},Eb=a=>{a(ct)},Li=(a,e)=>{var t;wu&&(ct.meta=(t=ct.meta)!=null?t:{},ct.meta[a]=e)},ue=class{constructor(e){this.name=e}next(e){var r,i;if(!wu)return;ct.series=(r=ct.series)!=null?r:{};let t=(i=ct.series[this.name])!=null?i:[];t.push([Date.now(),e]),ct.series[this.name]=t}};var Rw=new ue("best_bitrate"),$b=(a,e,t)=>(e-t)*Math.pow(2,-10*a)+t;var Lu=a=>(e,t)=>a*(Number(e.bitrate)-Number(t.bitrate)),Mi=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=kb()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},Lb='Assertion "ABR Tracks is empty array" failed',Ls=(a,e,t,r)=>{var u;let i=[...e].sort(Lu(1)),s=[...t].sort(Lu(1)),n=s.filter(c=>ve(c.bitrate)&&ve(a.bitrate)?a.bitrate/c.bitrate>r:!0),o=(u=(0,Jt.default)(s,Math.round(s.length*i.indexOf(a)/(i.length+1))))!=null?u:(0,Jt.default)(s,-1);return o&&n.includes(o)?o:n.length?(0,Jt.default)(n,-1):(0,Jt.default)(s,0)},wb=a=>"quality"in a,Mb=(a,e,t,r)=>{let i=t&&r&&r.history[t.id]&&kb()-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=wb(s)?"video":"audio",o=wb(s)?s.quality:s.bitrate;return e({message:`
7
+ [last ${n} selected] ${o}
8
+ `}),s}return r==null||r.recordSwitch(t),t},Rt=(a,{container:e,throughput:t,tuning:r,limits:i,reserve:s=0,forwardBufferHealth:n,playbackRate:o,current:u,history:c,visible:l,droppedVideoMaxQualityLimit:d,abrLogger:p})=>{var H,N,L,F,_;Rb(a,Lb);let h=r.usePixelRatio&&(H=window.devicePixelRatio)!=null?H:1,f=r.limitByContainer&&e&&e.width>0&&e.height>0&&{width:e.width*h*r.containerSizeFactor,height:e.height*h*r.containerSizeFactor},b=f&&ww(f),g=r.considerPlaybackRate&&ve(o)?o:1,S=a.filter(k=>!Ab(k.quality)).sort((k,x)=>Ru(k.quality,x.quality)?-1:1),T=(N=(0,Jt.default)(S,-1))==null?void 0:N.quality,v=(L=(0,Jt.default)(S,0))==null?void 0:L.quality,y=ku(i)||ve(i.min)&&ve(i.max)&&$u(i.max,i.min)||ve(i.min)&&v&&Ru(i.min,v)||ve(i.max)&&T&&$u(i.max,T),I=g*$b(n!=null?n:.5,r.bitrateFactorAtEmptyBuffer,r.bitrateFactorAtFullBuffer),$={},V=S.filter(k=>{if(!(b?$u(k.quality,b):!0))return $[k.quality]="FitsContainer",!1;if(!(ve(t)&&isFinite(t)&&ve(k.bitrate)?t-s>=k.bitrate*I:!0))return $[k.quality]="FitsThroughput",!1;if(r.lazyQualitySwitch&&ve(r.minBufferToSwitchUp)&&u&&!Ab(u.quality)&&(n!=null?n:0)<r.minBufferToSwitchUp&&Ru(k.quality,u.quality))return $[k.quality]="Buffer",!1;if(!!d&&xb(k.quality,d))return $[k.quality]="DroppedFramesLimit",!1;let Z=y||(ku(i.max)||Pb(k.quality,i.max))&&(ku(i.min)||xb(k.quality,i.min)),le=ve(l)&&!l?Pb(k.quality,r.backgroundVideoQualityLimit):!0;return!Z||!le?($[k.quality]="FitsQualityLimits",!1):!0})[0];V&&V.bitrate&&Rw.next(V.bitrate);let D=(F=V!=null?V:S[Math.ceil((S.length-1)/2)])!=null?F:a[0];return D.quality!==((_=c==null?void 0:c.last)==null?void 0:_.quality)&&p({message:`
9
+ [VIDEO TRACKS ABR]
10
+ [available video tracks]
8
11
  ${a.map(k=>`{ id: ${k.id}, quality: ${k.quality}, bitrate: ${k.bitrate} }`).join(`
9
12
  `)}
10
13
 
@@ -13,28 +16,46 @@ var zS=Object.create;var dn=Object.defineProperty,KS=Object.defineProperties,JS=
13
16
  `)}
14
17
 
15
18
  [limit params]
16
- containerQualityLimit: ${f},
19
+ containerQualityLimit: ${b},
17
20
  throughput: ${t},
18
21
  reserve: ${s},
19
22
  playbackRate: ${o},
20
- playbackRateFactor: ${b},
23
+ playbackRateFactor: ${g},
21
24
  forwardBufferHealth: ${n},
22
- bitrateFactor: ${T},
25
+ bitrateFactor: ${I},
23
26
  minBufferToSwitchUp: ${r.minBufferToSwitchUp},
24
- droppedVideoMaxQualityLimit: ${c},
25
- limitsAreInvalid: ${v},
27
+ droppedVideoMaxQualityLimit: ${d},
28
+ limitsAreInvalid: ${y},
26
29
  maxQualityLimit: ${i==null?void 0:i.max},
27
30
  minQualityLimit: ${i==null?void 0:i.min},
28
31
 
29
- [limited tracks]
30
- ${Object.entries(y).map(([k,x])=>`${k}: ${x}`).join(`
32
+ [limited video tracks]
33
+ ${Object.entries($).map(([k,x])=>`${k}: ${x}`).join(`
31
34
  `)||"All tracks are available"}
32
35
 
33
- [best track] ${D==null?void 0:D.quality}
34
- [selected track] ${$==null?void 0:$.quality}
35
- `});let O=$&&l&&l.history[$.id]&&Xm()-l.history[$.id]<=r.trackCooldown&&(!l.last||$.id!==l.last.id);if($!=null&&$.id&&l&&!O&&l.recordSelection($),O&&(l!=null&&l.last)){let k=l.last;return l==null||l.recordSwitch(k),d({message:`
36
- [last selected] ${k==null?void 0:k.quality}
37
- `}),k}return l==null||l.recordSwitch($),$},vt=uA;var re=a=>new URL(a).hostname;import{assertNever as ab,assertNonNullable as sb,combine as kA,debounce as RA,ErrorCategory as nb,filter as ob,filterChanged as LA,isNonNullable as Su,map as ls,merge as ub,observableFrom as $A,once as MA,Subscription as CA,ValueSubject as vu,videoQualityToHeight as DA,videoSizeToQuality as OA}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"))},be=a=>A(void 0,null,function*(){let e=a.muted;try{yield a.play()}catch(t){if(!Zm(t))return!1;if(e)return console.warn(t),!1;a.muted=!0;try{yield a.play()}catch(r){return Zm(r)&&(a.muted=!1,console.warn(r)),!1}}return!0});import{isNonNullable as ns,isNullable as dA,assertNonNullable as gi}from"@vkontakte/videoplayer-shared";import{isNonNullable as eb,assertNonNullable as ss,now as lA}from"@vkontakte/videoplayer-shared";function ie(){return lA()}function fu(a){return ie()-a}function mu(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 Tr(a,e,t,r){let i=window.XMLHttpRequest,s,n,o,u=!1,l=0,c,d,p=!1,h="arraybuffer",f=7e3,b=2e3,g=()=>{if(u)return;ss(c);let w=fu(c),H;if(w<b){H=b-w,setTimeout(g,H);return}b*=2,b>f&&(b=f),n&&n.abort(),n=new i,B()},S=w=>(s=w,L),I=w=>(d=w,L),v=()=>(h="json",L),T=()=>{if(!u){if(--l>=0){g(),r&&r();return}u=!0,d&&d(),t&&t()}},y=w=>(p=w,L),B=()=>{c=ie(),n=new i,n.open("get",a);let w=0,H,W=0,k=()=>(ss(c),Math.max(c,Math.max(H||0,W||0)));if(s&&n.addEventListener("progress",x=>{let N=ie();s.updateChunk&&x.loaded>w&&(s.updateChunk(k(),x.loaded-w),w=x.loaded,H=N)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>T())),n.addEventListener("load",()=>{if(u)return;ss(n);let x=n.status;if(x>=200&&x<300){if(n.response.byteLength&&s){let N=n.response.byteLength-w;N&&s.updateChunk&&s.updateChunk(k(),N)}n.responseType==="json"&&!Object.values(n.response).length?T():(d&&d(),e(n.response))}else T()}),n.addEventListener("error",()=>{T()}),p){let x=()=>{ss(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(W=ie(),n.removeEventListener("readystatechange",x))};n.addEventListener("readystatechange",x)}return n.responseType=h,n.send(),L},L={withBitrateReporting:S,withParallel:y,withJSONResponse:v,withRetryCount:w=>(l=w,L),withRetryInterval:(w,H)=>(eb(w)&&(b=w),eb(H)&&(f=H),L),withTimeout:w=>(o=w,L),withFinally:I,send:B,abort:()=>{n&&(n.abort(),n=void 0),u=!0,d&&d()}};return L}var mi=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 bi=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=ie(),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=ie()-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=Tr(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=ie()}_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=ie();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 os=1e4,bu=3;var pA=6e4,hA=10,fA=1,mA=500,Si=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 mi(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=mu(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=mu(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||ns(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 bi(bu,os,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){let{logger:t,videoElement:r,playerCallback:i}=this.params,s=!1,n=null,o=null,u=null,l=null,c=!1,d=()=>{let T=s&&(!c||c===this.rep);return T||t("Not running!"),T},p=(T,y,B)=>{u&&u.abort(),u=Tr(this.urlResolver.resolve(T,!1),y,B,()=>this._retryCallback()).withTimeout(os).withBitrateReporting(this.bitrateSwitcher).withRetryCount(bu).withFinally(()=>{u=null}).send()},h=(T,y,B)=>{gi(this.filesFetcher),o==null||o.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(T,!1),y,B,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},f=T=>{let y=r.playbackRate;r.playbackRate!==T&&(t(`Playback rate switch: ${y}=>${T}`),r.playbackRate=T)},b=T=>{this.lowLatency=T,t(`lowLatency changed to ${T}`),g()},g=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)f(1);else{let T=this._getBufferSizeSec();if(this.bufferStates.length<5){f(1);return}let B=ie()-1e4,D=0;for(let O=0;O<this.bufferStates.length;O++){let U=this.bufferStates[O];T=Math.min(T,U.buf),U.ts<B&&D++}this.bufferStates.splice(0,D),t(`update playback rate; minBuffer=${T} drop=${D} jitter=${this.sourceJitter}`);let $=T-fA;this.sourceJitter>=0?$-=this.sourceJitter/2:this.sourceJitter-=1,$>3?f(1.15):$>1?f(1.1):$>.3?f(1.05):f(1)}},S=T=>{let y,B=()=>y&&y.start?y.start.length:0,D=x=>y.start[x]/1e3,$=x=>y.dur[x]/1e3,O=x=>y.fragIndex+x,U=(x,N)=>({chunkIdx:O(x),startTS:D(x),dur:$(x),discontinuity:N}),L=()=>{let x=0;if(y&&y.dur){let N=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,G=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,Q=N;this.sourceJitter>1&&(Q+=this.sourceJitter-1);let Z=y.dur.length-1;for(;Z>=0&&(Q-=y.dur[Z],!(Q<=0));--Z);x=Math.min(Z,y.dur.length-1-G),x=Math.max(x,0)}return U(x,!0)},w=x=>{let N=B();if(!(N<=0)){if(ns(x)){for(let G=0;G<N;G++)if(D(G)>x)return U(G)}return L()}},H=x=>{let N=B(),G=x?x.chunkIdx+1:0,Q=G-y.fragIndex;if(!(N<=0)){if(!x||Q<0||Q-N>hA)return t(`Resync: offset=${Q} bChunks=${N} chunk=`+JSON.stringify(x)),L();if(!(Q>=N))return U(G-y.fragIndex,!1)}},W=(x,N,G)=>{l&&l.abort(),l=Tr(this.urlResolver.resolve(x,!0,this.lowLatency),N,G,()=>this._retryCallback()).withTimeout(os).withRetryCount(bu).withFinally(()=>{l=null}).withJSONResponse().send()};return{seek:(x,N)=>{W(T,G=>{if(!d())return;y=G;let Q=!!y.lowLatency;Q!==this.lowLatency&&b(Q);let Z=0;for(let F=0;F<y.dur.length;++F)Z+=y.dur[F];Z>0&&(gi(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(Z/y.dur.length)),i({name:"index",zeroTime:y.zeroTime,shiftDuration:y.shiftDuration}),this.sourceJitter=y.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,y.jitter/1e3)):1,x(w(N))},()=>this._handleNetworkError())},nextChunk:H}},I=()=>{s=!1,o&&o.abort(),u&&u.abort(),l&&l.abort(),gi(this.filesFetcher),this.filesFetcher.abortAll()};return c={start:T=>{let{videoElement:y,logger:B}=this.params,D=S(e.jidxUrl),$,O,U,L,w=0,H,W,k,x=()=>{H&&(clearTimeout(H),H=void 0);let V=Math.max(mA,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),ue=w+V,ve=ie(),Pe=Math.min(1e4,ue-ve);w=ve;let lt=()=>{l||d()&&D.seek(()=>{d()&&(w=ie(),N(),x())})};Pe>0?H=window.setTimeout(()=>{this.paused?x():lt()},Pe):lt()},N=()=>{let V;for(;V=D.nextChunk(L);)L=V,Kt(V);let ue=D.nextChunk(U);if(ue){if(U&&ue.discontinuity){B("Detected discontinuity; restarting playback"),this.paused?x():(I(),this._initPlayerWith(e));return}F(ue)}else x()},G=(V,ue)=>{if(!d()||!this.sourceBuffer)return;let ve,Pe,lt,Jt=ct=>{window.setTimeout(()=>{d()&&G(V,ue)},ct)};if(this.sourceBuffer.updating)B("Source buffer is updating; delaying appendBuffer"),Jt(100);else{let ct=ie(),xt=y.currentTime;!this.paused&&y.buffered.length>1&&W===xt&&ct-k>500&&(B("Stall suspected; trying to fix"),this._fixupStall()),W!==xt&&(W=xt,k=ct);let Xt=this._getBufferSizeSec();if(Xt>30)B(`Buffered ${Xt} seconds; delaying appendBuffer`),Jt(2e3);else try{this.sourceBuffer.appendBuffer(V),this.videoPlayStarted?(this.bufferStates.push({ts:ct,buf:Xt}),g(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),ue&&ue()}catch(Or){if(Or.name==="QuotaExceededError")B("QuotaExceededError; delaying appendBuffer"),lt=this.sourceBuffer.buffered.length,lt!==0&&(ve=this.sourceBuffer.buffered.start(0),Pe=xt,Pe-ve>4&&this.sourceBuffer.remove(ve,Pe-3)),Jt(1e3);else throw Or}}},Q=()=>{O&&$&&(B([`Appending chunk, sz=${O.byteLength}:`,JSON.stringify(U)]),G(O,function(){O=null,N()}))},Z=V=>e.fragUrlTemplate.replace("%%id%%",V.chunkIdx),F=V=>{d()&&h(Z(V),(ue,ve)=>{if(d()){if(ve/=1e3,O=ue,U=V,n=V.startTS,ve){let Pe=Math.min(10,V.dur/ve);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*Pe:Pe}Q()}},()=>this._handleNetworkError())},Kt=V=>{d()&&(gi(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(Z(V),!1)))},ut=V=>{d()&&(e.cachedHeader=V,G(V,()=>{$=!0,Q()}))};s=!0,D.seek(V=>{if(d()){if(w=ie(),!V){x();return}L=V,!dA(T)||V.startTS>T?F(V):(U=V,N())}},T),e.cachedHeader?ut(e.cachedHeader):p(e.headerUrl,ut,()=>this._handleNetworkError())},stop:I,getTimestampSec:()=>n},c}_switchToQuality(e){let{logger:t,playerCallback:r}=this.params,i;e.bitrate!==this.bitrate&&(this.rep&&(i=this.rep.getTimestampSec(),ns(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,gi(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(i),r({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return ns(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,r=d=>{if(!this.autoQuality)return;let p,h,f;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&d<this.bitrate&&(h=this._getBufferSizeSec(),f=d/this.bitrate,h>10&&f>.8||h>15&&f>.5||h>20&&f>.3)){e(`Not switching: buffer=${Math.floor(h)}; bitrate=${this.bitrate}; newRate=${Math.floor(d)}`);return}p=this._selectQuality(d),p?this._switchToQuality(p):e(`Could not find quality by bitrate ${d}`)},s={updateChunk:(p,h)=>{let f=ie();if(this.chunkRateEstimator.addInterval(p,f,h)){let g=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:h,duration:f-p,speed:g}),!0}},get:()=>{let p=this.chunkRateEstimator.getBitRate();return p?p*.85:0}},n=-1/0,o,u=!0,l=()=>{let d=s.get();if(d&&o&&this.autoQuality){if(u&&d>o&&fu(n)<3e4)return;r(d)}u=this.autoQuality};return{updateChunk:(d,p)=>{let h=s.updateChunk(d,p);return h&&l(),h},notifySwitch:d=>{let p=ie();d<o&&(n=p),o=d}}}_fetchManifest(e,t,r){this.manifestRequest=Tr(this.urlResolver.resolve(e,!0),t,r,()=>this._retryCallback()).withJSONResponse().withTimeout(os).withRetryCount(this.params.config.manifestRetryMaxCount).withRetryInterval(this.params.config.manifestRetryInterval,this.params.config.manifestRetryMaxInterval).send().withFinally(()=>{this.manifestRequest=void 0})}_playVideoElement(){let{videoElement:e}=this.params;be(e).then(t=>{t||(this.params.liveOffset.pause(),this.params.videoState.setState("paused"))})}_handleManifestUpdate(e){let{logger:t,playerCallback:r,videoElement:i}=this.params,s=n=>{let o=[];return n!=null&&n.length?(n.forEach((u,l)=>{u.video&&i.canPlayType(u.codecs).replace(/no/,"")&&window.MediaSource.isTypeSupported(u.codecs)&&(u.index=l,o.push(u))}),o.sort(function(u,l){return u.video&&l.video?l.video.height-u.video.height:l.bitrate-u.bitrate}),o):(r({name:"error",type:"empty_manifest"}),[])};this.manifest=s(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),r({name:"manifest",manifest:this.manifest})}_refetchManifest(e){this.destroyed||(this.manifestRefetchTimer&&clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=window.setTimeout(()=>{this._fetchManifest(e,t=>{this.destroyed||(this._handleManifestUpdate(t),this._refetchManifest(e))},()=>this._refetchManifest(e))},pA))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};import{debounce as bA,filter as rb,fromEvent as gA,interval as SA,isHigher as vA,isInvariantQuality as yA,isLower as TA,merge as IA,Subject as ib,Subscription as EA}from"@vkontakte/videoplayer-shared";var gu=class{constructor(){this.onDroopedVideoFramesLimit$=new ib;this.subscription=new EA;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&&!yA(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&&vA(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(gA(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=SA(this.droppedFramesChecker.checkTime).pipe(rb(()=>this.playing),rb(()=>{let i=!!this.isForceCheckCounter;return i&&(this.isForceCheckCounter-=1),!i})),t=this.forceChecker$.pipe(bA(this.droppedFramesChecker.checkTime)),r=IA(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])=>TA(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}},us=gu;import{map as xA,Observable as PA}from"@vkontakte/videoplayer-shared";import{fromEvent as wA}from"@vkontakte/videoplayer-shared";var vi=()=>{var a;return!!((a=window.documentPictureInPicture)!=null&&a.window)||!!document.pictureInPictureElement};var AA=(a,e)=>new PA(t=>{if(!window.IntersectionObserver)return;let r={root:null},i=new IntersectionObserver((n,o)=>{n.forEach(u=>t.next(u.isIntersecting||vi()))},R(R({},r),e));i.observe(a);let s=wA(document,"visibilitychange").pipe(xA(n=>!document.hidden||vi())).subscribe(n=>t.next(n));return()=>{i.unobserve(a),s.unsubscribe}}),Me=AA;var BA=["paused","playing","ready"],VA=["paused","playing","ready"],yi=class{constructor(e){this.subscription=new CA;this.videoState=new M("stopped");this.representations$=new vu([]);this.textTracksManager=new Le;this.droppedFramesManager=new us;this.maxSeekBackTime$=new vu(1/0);this.zeroTime$=new vu(void 0);this.liveOffset=new et;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=gt(u.name))!=null?r:OA(u.video),d=u.bitrate/1e3,p=R({},u.video);if(!c)continue;let h={id:l,quality:c,bitrate:d,size:p};o.push({track:h,representation:u})}this.representations$.next(o),this.params.output.availableVideoTracks$.next(o.map(({track:u})=>u)),((i=this.videoState.getTransition())==null?void 0:i.to)==="manifest_ready"&&this.videoState.setState("manifest_ready");break}case"qualitySwitch":{let n=e.quality,o=(s=this.representations$.getValue().find(({representation:u})=>u===n))==null?void 0:s.track;this.params.output.hostname$.next(new URL(n.headerUrl,this.params.source.url).hostname),Su(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(VA.includes(e)&&(n||o)){this.prepare();return}if((i==null?void 0:i.to)!=="paused"&&s.state==="requested"&&BA.includes(e)){this.seek(s.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(ae(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(ae(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(ls(i=>({transition:i,type:"start"}))),this.videoState.stateChangeEnded$.pipe(ls(i=>({transition:i,type:"end"})))).subscribe(({transition:i,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(i)}`})}),this.video=pe(e.container,e.tuning),this.params.output.element$.next(this.video),this.dash=this.createLiveDashPlayer(),this.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(re(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=me(this.video);this.subscription.add(this.representations$.pipe(ls(i=>i.map(({track:s})=>s)),ob(i=>!!i.length),MA()).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(LA(),ls(i=>-i/1e3)).subscribe(this.params.output.duration$)).add(kA({zeroTime:this.zeroTime$.pipe(ob(Su)),position:r.timeUpdate$}).subscribe(({zeroTime:i,position:s})=>this.params.output.liveTime$.next(i+s*1e3),t)).add(We(this.video,this.params.desiredState.isLooped,t)).add(fe(this.video,this.params.desiredState.volume,r.volumeState$,t)).add(r.volumeState$.subscribe(this.params.output.volume$,t)).add(Re(this.video,this.params.desiredState.playbackRate,r.playbackRateState$,t)).add(r.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(r.loadedMetadata$.subscribe(this.params.output.loadedMetadataEvent$)).add(r.playing$.subscribe(this.params.output.firstFrameEvent$)).add(r.canplay$.subscribe(this.params.output.canplay$)).add(r.inPiP$.subscribe(this.params.output.inPiP$)).add(r.inFullscreen$.subscribe(this.params.output.inFullscreen$)).add(Me(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:i}})=>{let s=i&&DA(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$,$A(["init"])).pipe(RA(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),he(this.video)}createLiveDashPlayer(){let e=new Si({videoElement:this.video,videoState:this.videoState,liveOffset:this.liveOffset,config:{maxParallelRequests:this.params.config.maxParallelRequests,minBuffer:this.params.tuning.live.minBuffer,minBufferSegments:this.params.tuning.live.minBufferSegments,lowLatencyMinBuffer:this.params.tuning.live.lowLatencyMinBuffer,lowLatencyMinBufferSegments:this.params.tuning.live.lowLatencyMinBufferSegments,isLiveCatchUpMode:this.params.tuning.live.isLiveCatchUpMode,manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},playerCallback:this._dashCb,logger:t=>{this.params.dependencies.logger.log({message:String(t),component:"LiveDashPlayer"})}});return e.pause(),e}prepare(){var l,c,d,p,h,f;let e=this.representations$.getValue(),t=(c=(l=this.params.desiredState.videoTrack.getTransition())==null?void 0:l.to)!=null?c:this.params.desiredState.videoTrack.getState(),r=(p=(d=this.params.desiredState.autoVideoTrackSwitching.getTransition())==null?void 0:d.to)!=null?p:this.params.desiredState.autoVideoTrackSwitching.getState(),i=!r&&Su(t)?t:vt(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(ae(this.params.source.url,n)),i&&this.dash.pause(),this.liveOffset.resetTo(n,i)}};var lb=yi;var rt=(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 nR,assertNonNullable as oR,debounce as uR,ErrorCategory as Yu,filter as Bg,filterChanged as Wu,fromEvent as lR,isLowerOrEqual as Vg,isNonNullable as cR,isInvariantQuality as dR,map as _g,merge as Os,observableFrom as pR,observeElementSize as hR,once as Ng,Subscription as fR,ValueSubject as mR}from"@vkontakte/videoplayer-shared";var cs=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}},Ir=class extends cs{constructor(){super(),this.listeners||cs.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)}},Ti=class{constructor(){Object.defineProperty(this,"signal",{value:new Ir,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&&(Ti.prototype[Symbol.toStringTag]="AbortController",Ir.prototype[Symbol.toStringTag]="AbortSignal");function ds(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 yu(a){typeof a=="function"&&(a={fetch:a});let{fetch:e,Request:t=e.Request,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:i=!1}=a;if(!ds({fetch:e,Request:t,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:i}))return{fetch:e,Request:s};let s=t;(s&&!s.prototype.hasOwnProperty("signal")||i)&&(s=function(l,c){let d;c&&c.signal&&(d=c.signal,delete c.signal);let p=new t(l,c);return d&&Object.defineProperty(p,"signal",{writable:!1,enumerable:!1,configurable:!0,value:d}),p},s.prototype=t.prototype);let n=e;return{fetch:(u,l)=>{let c=s&&s.prototype.isPrototypeOf(u)?u.signal:l?l.signal:void 0;if(c){let d;try{d=new DOMException("Aborted","AbortError")}catch(h){d=new Error("Aborted"),d.name="AbortError"}if(c.aborted)return Promise.reject(d);let p=new Promise((h,f)=>{c.addEventListener("abort",()=>f(d),{once:!0})});return l&&l.signal&&delete l.signal,Promise.race([p,n(u,l)])}return n(u,l)},Request:s}}var Ii=ds({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),cb=Ii?yu({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,it=Ii?cb.fetch:window.fetch,vO=Ii?cb.Request:window.Request,at=Ii?Ti:window.AbortController,yO=Ii?Ir:window.AbortSignal;var Eb=Ge(hi(),1);var st=()=>window.ManagedMediaSource||window.MediaSource,ps=()=>{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 Ts,clientChecker as ys}from"@vkontakte/videoplayer-shared";var Ce=document.createElement("video"),FA='video/mp4; codecs="avc1.42000a,mp4a.40.2"',qA='video/mp4; codecs="hev1.1.6.L93.B0"',xb='video/webm; codecs="vp09.00.10.08"',Pb='video/webm; codecs="av01.0.00M.08"',UA='audio/mp4; codecs="mp4a.40.2"',HA='audio/webm; codecs="opus"',hb,fb,_t={mms:ps(),mse:db(),hls:!!((hb=Ce.canPlayType)!=null&&hb.call(Ce,"application/x-mpegurl")||(fb=Ce.canPlayType)!=null&&fb.call(Ce,"vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},mb,bb,ge={mp4:!!((mb=Ce.canPlayType)!=null&&mb.call(Ce,"video/mp4")),webm:!!((bb=Ce.canPlayType)!=null&&bb.call(Ce,"video/webm")),cmaf:!0},fs,gb,ms,Sb,bs,vb,gs,yb,Ss,Tb,vs,Ib,Se={h264:!!((gb=(fs=st())==null?void 0:fs.isTypeSupported)!=null&&gb.call(fs,FA)),h265:!!((Sb=(ms=st())==null?void 0:ms.isTypeSupported)!=null&&Sb.call(ms,qA)),vp9:!!((vb=(bs=st())==null?void 0:bs.isTypeSupported)!=null&&vb.call(bs,xb)),av1:!!((yb=(gs=st())==null?void 0:gs.isTypeSupported)!=null&&yb.call(gs,Pb)),aac:!!((Tb=(Ss=st())==null?void 0:Ss.isTypeSupported)!=null&&Tb.call(Ss,UA)),opus:!!((Ib=(vs=st())==null?void 0:vs.isTypeSupported)!=null&&Ib.call(vs,HA))},Er=(Se.h264||Se.h265)&&Se.aac,Nt,jA=()=>A(void 0,null,function*(){if(!window.navigator.mediaCapabilities)return;let a={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=yield Promise.all([window.navigator.mediaCapabilities.decodingInfo(q(R({},a),{video:q(R({},a.video),{contentType:Pb})})),window.navigator.mediaCapabilities.decodingInfo(q(R({},a),{video:q(R({},a.video),{contentType:xb})}))]);Nt={DASH_WEBM_AV1:e,DASH_WEBM:t}});try{jA()}catch(a){console.error(a)}var xr=_t.hls&&ge.mp4,wb=()=>Object.keys(Se).filter(a=>Se[a]),Ab=(a,e=!1,t=!1)=>{let r=_t.mse||_t.mms&&t;return a.filter(i=>{switch(i){case"DASH_SEP":return r&&ge.mp4&&Er;case"DASH_WEBM":return r&&ge.webm&&Se.vp9&&Se.opus;case"DASH_WEBM_AV1":return r&&ge.webm&&Se.av1&&Se.opus;case"DASH_STREAMS":return r&&(ge.mp4&&Er||ge.webm&&(Se.vp9||Se.av1)&&(Se.opus||Se.aac));case"DASH_LIVE":return _t.mse&&ge.mp4&&Er;case"DASH_LIVE_CMAF":return r&&ge.mp4&&Er&&ge.cmaf;case"DASH_ONDEMAND":return r&&ge.mp4&&Er;case"HLS":case"HLS_ONDEMAND":return xr||e&&_t.mse&&ge.mp4&&Er;case"HLS_LIVE":case"HLS_LIVE_CMAF":return xr;case"MPEG":return ge.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return _t.webrtc&&_t.ws&&Se.h264&&(ge.mp4||ge.webm);default:return Ts(i)}})},hs=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 Nt?Nt[t].smooth?[t,e]:Nt[e].smooth?[e,t]:[t,e]:[e,t];case"power_efficient":return Nt?Nt[t].powerEfficient?[t,e]:Nt[e].powerEfficient?[e,t]:[t,e]:[e,t];default:Ts(a)}return[e,t]},kb=({webmCodec:a,androidPreferredFormat:e,preferMultiStream:t})=>{let r=[...t?["DASH_STREAMS"]:[],...hs(a),"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]],i=[...t?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]];if(ys.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",...hs(a),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...hs(a),"MPEG",...i,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...hs(a),...i,"HLS","HLS_ONDEMAND"];default:Ts(e)}return xr?[...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=ys.isMac&&ys.isSafari;if(ys.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:Ts(a)}else xr&&!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"]},Tu=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 Ei}from"@vkontakte/videoplayer-shared";var $b=a=>{if(!a)return{id:"EmptyResponse",category:Ei.PARSER,message:"Empty response"};if(a.length<=2&&a.match(/^\d+$/))return{id:`UVError#${a}`,category:Ei.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:Ei.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:Ei.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:Ei.PARSER,message:"Response is valid XML, but parser failed"}};var xi=(a,e)=>{for(let t=0;t<a.length;t++)if(a.start(t)*1e3<=e&&a.end(t)*1e3>e)return!0;return!1};import{abortable as Hu,assertNonNullable as Qt,combine as Rs,ErrorCategory as Tt,filter as Ls,filterChanged as Rg,fromEvent as $r,interval as ju,isNonNullable as Lg,map as Gu,merge as Mr,Subject as $g,Subscription as Mg,tap as Zk,throttle as eR,clientChecker as tR,ValueSubject as oe}from"@vkontakte/videoplayer-shared";var Lr=Ge(hi(),1);var GA=(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)},YA=a=>window.clearTimeout(a),Mb=typeof window.requestIdleCallback!="function"||typeof window.cancelIdleCallback!="function",Iu=Mb?GA:window.requestIdleCallback,OO=Mb?YA:window.cancelIdleCallback;var Ig=Ge(ts(),1);import{assertNever as WA,ErrorCategory as Cb,clientChecker as Eu,Subject as Db}from"@vkontakte/videoplayer-shared";var QA=16,Ob=!1;try{Ob=Eu.isSafari&&!!Eu.macVersion&&Eu.macVersion<=QA}catch(a){console.error(a)}var xu=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)}append(e,t){return A(this,null,function*(){return t&&t.aborted?!1:new Promise(r=>{let i={operation:"append",data:e,signal:t,callback:r};this.queue.push(i),this.pull()})})}remove(e,t,r){return A(this,null,function*(){return r&&r.aborted?!1:new Promise(i=>{let s={operation:"remove",from:e,to:t,signal:r,callback:i};this.queue.unshift(s),this.pull()})})}abort(e){return A(this,null,function*(){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:WA(t)}}},Bb=xu;var Pu=a=>{let e=0;for(let t=0;t<a.length;t++)e+=a.end(t)-a.start(t);return e*1e3};import{abortable as Rr,assertNonNullable as ze,ErrorCategory as Gt,fromEvent as Vu,getExponentialDelay as _u,isNonNullable as Tg,isNullable as qe,once as Gk,Subject as Yk,Subscription as Wk,ValueSubject as Wi}from"@vkontakte/videoplayer-shared";var j=class{constructor(e,t){this.cursor=0;this.source=e,this.boxParser=t,this.children=[];let r=this.readUint32();this.type=this.readString(4),this.size32=r<=e.buffer.byteLength-e.byteOffset?r:NaN;let i=this.size32?this.size32-8:void 0,s=e.byteOffset+this.cursor;this.size64=0,this.usertype=0,this.content=new DataView(e.buffer,s,i),this.children=this.parseChildrenBoxes()}get id(){return this.type}get size(){return this.size32}parseChildrenBoxes(){return[]}scanForBoxes(e){return this.boxParser.parse(e)}readString(e,t="ascii"){let i=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,i}readUint8(){let e=this.source.getUint8(this.cursor);return this.cursor+=1,e}readUint16(){let e=this.source.getUint16(this.cursor);return this.cursor+=2,e}readUint32(){let e=this.source.getUint32(this.cursor);return this.cursor+=4,e}readUint64(){let e=this.source.getBigInt64(this.cursor);return this.cursor+=8,e}};var Pr=class extends j{};var Pi=class extends j{};var wi=class extends j{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 Ai=class extends j{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ki=class extends j{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Ri=class extends j{constructor(e,t){super(e,t),this.data=this.content}};var J=class extends j{constructor(e,t){super(e,t);let r=this.readUint32();this.version=r>>>24,this.flags=r&16777215}};var Ft=class extends J{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 Li=class extends j{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var $i=class extends j{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Mi=class extends J{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 Ci=class extends J{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var Di=class extends J{constructor(e,t){super(e,t),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}};var Oi=class extends j{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Bi=class extends J{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 Vi=class extends j{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var _i=class extends j{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Ni=class extends J{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var Fi=class extends j{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var qi=class extends J{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 Ui=class extends J{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 Hi=class extends J{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 KA={ftyp:wi,moov:Ai,moof:ki,mdat:Ri,sidx:Ft,trak:Li,mdia:Oi,mfhd:Ni,tkhd:Bi,traf:Fi,tfhd:qi,tfdt:Ui,trun:Hi,minf:Vi,sv3d:$i,st3d:Mi,prhd:Ci,proj:_i,equi:Di,uuid:Pi,unknown:Pr},qt=class a{constructor(e={}){this.options=R({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=KA[e];return r?new r(t,new a):new Pr(t,new a)}};var wr=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 XA=new TextDecoder("ascii"),ZA=a=>XA.decode(new DataView(a.buffer,a.byteOffset+4,4))==="ftyp",ek=a=>{let e=new Ft(a,new qt),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})},tk=(a,e)=>{let r=new qt().parse(a),i=new wr(r),s=i.findAll("moof"),n=e?i.findAll("uuid"):i.findAll("mdat");if(!(n.length&&s.length))return null;let o=s[0],u=n[n.length-1],l=o.source.byteOffset,d=u.source.byteOffset-o.source.byteOffset+u.size;return new DataView(a.buffer,l,d)},rk=(a,e)=>{let r=new qt().parse(a),s=new wr(r).findAll("traf"),n=s[s.length-1].children.find(d=>d.type==="tfhd"),o=s[s.length-1].children.find(d=>d.type==="tfdt"),u=s[s.length-1].children.find(d=>d.type==="trun"),l=0;return u.sampleDuration.length?l=u.sampleDuration.reduce((d,p)=>d+p,0):l=n.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+l)/e*1e3},ik=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 qt().parse(a),i=new wr(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:ZA,parseInit:ik,getIndexRange:()=>{},parseSegments:ek,parseFeedableSegmentChunk:tk,getSegmentEndTime:rk};import{assertNonNullable as Au,isNonNullable as qb,isNullable as sk}from"@vkontakte/videoplayer-shared";import{assertNever as ak}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=ji(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=ji(u),d=l*je(2,(o-1)*8)+c,p=t+o,h;return p+d>a.byteLength?h=new DataView(a.buffer,a.byteOffset+p):h=new DataView(a.buffer,a.byteOffset+p,d),{tag:i?r:"0x"+r.toString(16).toUpperCase(),type:s,tagHeaderSize:p,tagSize:p+d,value:h,valueSize:d}},ji=(a,e=a.byteLength)=>{switch(e){case 1:return a.getUint8(0);case 2:return a.getUint16(0);case 3:return a.getUint8(0)*je(2,16)+a.getUint16(1);case 4:return a.getUint32(0);case 5:return a.getUint8(0)*je(2,32)+a.getUint32(1);case 6:return a.getUint16(0)*je(2,32)+a.getUint32(2);case 7:{let t=a.getUint8(0)*281474976710656+a.getUint16(1)*4294967296+a.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},Fe=(a,e)=>{switch(e){case"int":return a.getInt8(0);case"uint":return ji(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:ak(e)}},Ut=(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"&&Ut(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 Ut(i.value,({tag:s,type:n,value:o})=>(s===17143?e=Fe(o,n):s===17026?t=Fe(o,n):s===17029&&(r=Fe(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(r===void 0||r<=2)};var Ub=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],nk=[231,22612,22743,167,171,163,160,175],ok=a=>{let e,t,r,i,s=!1,n=!1,o=!1,u,l,c=!1,d=0;return Ut(a,({tag:p,type:h,value:f,valueSize:b})=>{if(p===21419){let g=Fe(f,h);l=ji(g)}else p!==21420&&(l=void 0);return p===408125543?(e=f.byteOffset,t=f.byteOffset+b):p===357149030?s=!0:p===290298740?n=!0:p===2807729?r=Fe(f,h):p===17545?i=Fe(f,h):p===21420&&l===475249515?u=Fe(f,h):p===374648427?Ut(f,({tag:g,type:S,value:I})=>g===30321?(c=Fe(I,S)===1,!1):!0):s&&n&&Ub.includes(p)&&(o=!0),!o}),Au(e,"Failed to parse webm Segment start"),Au(t,"Failed to parse webm Segment end"),Au(i,"Failed to parse webm Segment duration"),r=r!=null?r:1e6,{segmentStart:Math.round(e/1e9*r*1e3),segmentEnd:Math.round(t/1e9*r*1e3),timeScale:r,segmentDuration:Math.round(i/1e9*r*1e3),cuesSeekPosition:u,is3dVideo:c,stereoMode:d,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},uk=a=>{if(sk(a.cuesSeekPosition))return;let e=a.segmentStart+a.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},lk=(a,e)=>{let t=!1,r=!1,i=o=>qb(o.time)&&qb(o.position),s=[],n;return Ut(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=Fe(l,u));break;case 183:break;case 241:n&&(n.position=Fe(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,d=s[u+1];return{status:"none",time:{from:l,to:d?d.time:e.segmentDuration},byte:{from:e.segmentStart+c,to:d?e.segmentStart+d.position-1:e.segmentEnd-1}}})},ck=a=>{let e=0,t=!1;try{Ut(a,r=>r.tag===524531317?r.tagSize<=a.byteLength?(e=r.tagSize,!1):(e+=r.tagHeaderSize,!0):nk.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:ok,getIndexRange:uk,parseSegments:lk,parseFeedableSegmentChunk:ck};var Ar=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 Du=Ge(dg(),1);var Cu=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},Ht=(a,e)=>{let t=a;t=(0,Du.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,Du.default)(t,n,(o,u)=>fg(s)?o:fg(u)?s:s.padStart(parseInt(u,10),"0"))}return t},gg=(a,e)=>{var T,y,B,D,$,O,U,L,w,H,W,k,x,N,G,Q,Z,F,Kt,ut,V,ue,ve,Pe,lt,Jt,ct,xt,Xt,Or,ul,ll,cl,dl,pl,hl,fl,ml,bl,gl,Sl,vl,yl,Tl,Il,El,xl,Pl,wl,Al;let r=new DOMParser().parseFromString(a,"application/xml"),i={video:[],audio:[],text:[]},s=r.children[0],n=s.getElementsByTagName("Period")[0],o=(B=(y=(T=s.querySelector("BaseURL"))==null?void 0:T.textContent)==null?void 0:y.trim())!=null?B:"",u=n.children,l=s.getAttribute("type")==="dynamic",c=s.getAttribute("availabilityStartTime"),d=c?new Date(c).getTime():void 0,p,h=s.getAttribute("mediaPresentationDuration"),f=n.getAttribute("duration"),b=s.getElementsByTagName("vk:Attrs")[0],g=b==null?void 0:b.getElementsByTagName("vk:XPlaybackDuration")[0].textContent;if(h)p=mg(h);else if(f){let le=mg(f);hg(le)&&(p=le)}else g&&(p=parseInt(g,10));let S=0,I=($=(D=s.getAttribute("profiles"))==null?void 0:D.split(","))!=null?$:[];for(let le of u){let kS=(O=le.getAttribute("id"))!=null?O:"id"+(S++).toString(10),Br=(U=le.getAttribute("mimeType"))!=null?U:"",Js=(L=le.getAttribute("codecs"))!=null?L:"",Xs=(w=le.getAttribute("contentType"))!=null?w:Br==null?void 0:Br.split("/")[0],RS=(W=(H=le.getAttribute("profiles"))==null?void 0:H.split(","))!=null?W:[],LS=(k=le.getAttribute("lang"))!=null?k:void 0,$S=(G=(N=(x=le.querySelector("Label"))==null?void 0:x.textContent)==null?void 0:N.trim())!=null?G:void 0,MS=le.querySelectorAll("Representation"),CS=le.querySelector("SegmentTemplate"),DS=(Z=(Q=le.querySelector("Role"))==null?void 0:Q.getAttribute("value"))!=null?Z:void 0,Vr=Xs,ee={id:kS,language:LS,isDefault:DS==="main",label:$S,codecs:Js,hdr:Vr==="video"&&Cu(Js),mime:Br,representations:[]};for(let X of MS){let OS=(F=X.getAttribute("lang"))!=null?F:void 0,BS=(Kt=X.getAttribute("label"))!=null?Kt:void 0,VS=(ue=(V=(ut=X.querySelector("BaseURL"))==null?void 0:ut.textContent)==null?void 0:V.trim())!=null?ue:"",Zs=new URL(VS||o,e).toString(),Zt=(ve=X.getAttribute("mimeType"))!=null?ve:Br,ha=(lt=(Pe=X.getAttribute("codecs"))!=null?Pe:Js)!=null?lt:"",en;if(Xs==="text"){let Pt=X.getAttribute("id")||"",tn=Pt.includes("_auto");en={id:Pt,isAuto:tn,kind:"text",url:Zs}}else{let Pt=(ct=(Jt=X.getAttribute("contentType"))!=null?Jt:Zt==null?void 0:Zt.split("/")[0])!=null?ct:Xs,tn=(Xt=(xt=le.getAttribute("profiles"))==null?void 0:xt.split(","))!=null?Xt:[],_S=parseInt((Or=X.getAttribute("width"))!=null?Or:"",10),kl=parseInt((ul=X.getAttribute("height"))!=null?ul:"",10),Rl=parseInt((ll=X.getAttribute("bandwidth"))!=null?ll:"",10)/1e3,Ll=(cl=X.getAttribute("frameRate"))!=null?cl:"",NS=(dl=X.getAttribute("quality"))!=null?dl:void 0,FS=Ll?pg(Ll):void 0,qS=(pl=X.getAttribute("id"))!=null?pl:"id"+(S++).toString(10),US=Pt==="video"?`${kl}p`:Pt==="audio"?`${Rl}Kbps`:ha,HS=`${qS}@${US}`,jS=[...I,...RS,...tn],rn,GS=X.querySelector("SegmentBase"),wt=(hl=X.querySelector("SegmentTemplate"))!=null?hl:CS;if(GS){let At=(ml=(fl=X.querySelector("SegmentBase Initialization"))==null?void 0:fl.getAttribute("range"))!=null?ml:"",[kt,sn]=At.split("-").map(er=>parseInt(er,10)),dt={from:kt,to:sn},_r=(bl=X.querySelector("SegmentBase"))==null?void 0:bl.getAttribute("indexRange"),[nn,fa]=_r?_r.split("-").map(er=>parseInt(er,10)):[],Nr=_r?{from:nn,to:fa}:void 0;rn={type:"byteRange",url:Zs,initRange:dt,indexRange:Nr}}else if(wt){let At={representationId:(gl=X.getAttribute("id"))!=null?gl:void 0,bandwidth:(Sl=X.getAttribute("bandwidth"))!=null?Sl:void 0},kt=parseInt((vl=wt.getAttribute("timescale"))!=null?vl:"",10),sn=(yl=wt.getAttribute("initialization"))!=null?yl:"",dt=wt.getAttribute("media"),_r=(Il=parseInt((Tl=wt.getAttribute("startNumber"))!=null?Tl:"",10))!=null?Il:1,nn=Ht(sn,At);if(!dt)throw new ReferenceError("No media attribute in SegmentTemplate");let fa=(El=wt.querySelectorAll("SegmentTimeline S"))!=null?El:[],Nr=[],er=0,on="",un=0;if(fa.length){let ma=_r,Oe=0;for(let tr of fa){let He=parseInt((xl=tr.getAttribute("d"))!=null?xl:"",10),Rt=parseInt((Pl=tr.getAttribute("r"))!=null?Pl:"",10)||0,ba=parseInt((wl=tr.getAttribute("t"))!=null?wl:"",10);Oe=Number.isFinite(ba)?ba:Oe;let ln=He/kt*1e3,cn=Oe/kt*1e3;for(let ga=0;ga<Rt+1;ga++){let WS=Ht(dt,q(R({},At),{segmentNumber:ma.toString(10),segmentTime:(Oe+ga*He).toString(10)})),$l=(cn!=null?cn:0)+ga*ln,QS=$l+ln;ma++,Nr.push({time:{from:$l,to:QS},url:WS})}Oe+=(Rt+1)*He,er+=(Rt+1)*ln}un=Oe/kt*1e3,on=Ht(dt,q(R({},At),{segmentNumber:ma.toString(10),segmentTime:Oe.toString(10)}))}else if(hg(p)){let Oe=parseInt((Al=wt.getAttribute("duration"))!=null?Al:"",10)/kt*1e3,tr=Math.ceil(p/Oe),He=0;for(let Rt=1;Rt<tr;Rt++){let ba=Ht(dt,q(R({},At),{segmentNumber:Rt.toString(10),segmentTime:He.toString(10)}));Nr.push({time:{from:He,to:He+Oe},url:ba}),He+=Oe}un=He,on=Ht(dt,q(R({},At),{segmentNumber:tr.toString(10),segmentTime:He.toString(10)}))}let YS={time:{from:un,to:1/0},url:on};rn={type:"template",baseUrl:Zs,segmentTemplateUrl:dt,initUrl:nn,totalSegmentsDurationMs:er,segments:Nr,nextSegmentBeyondManifest:YS,timescale:kt}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!Pt||!Zt)continue;let an={video:"video",audio:"audio",text:"text"}[Pt];if(!an)continue;Vr||(Vr=an),en={id:HS,kind:an,segmentReference:rn,profiles:jS,duration:p,bitrate:Rl,mime:Zt,codecs:ha,width:_S,height:kl,fps:FS,quality:NS}}ee.language||(ee.language=OS),ee.label||(ee.label=BS),ee.mime||(ee.mime=Zt),ee.codecs||(ee.codecs=ha),ee.hdr||(ee.hdr=Vr==="video"&&Cu(ha)),ee.representations.push(en)}Vr&&i[Vr].push(ee)}return{dynamic:l,liveAvailabilityStartTime:d,duration:p,streams:i}};var Gi=Ge(hi(),1);import{videoSizeToQuality as jk}from"@vkontakte/videoplayer-shared";var Sg=({id:a,width:e,height:t,bitrate:r,fps:i,quality:s})=>{var o;let n=(o=s?gt(s):void 0)!=null?o:jk({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}),Es=(a,e,t)=>{var i;let r=e.indexOf(a);return(i=(0,Gi.default)(t,Math.round(t.length*r/e.length)))!=null?i:(0,Gi.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}),Ou=({id:a,language:e,label:t,codecs:r,isDefault:i})=>({id:a,language:e,label:t,codec:(0,Gi.default)(r.split("."),0),isDefault:i}),Bu=({id:a,language:e,label:t,hdr:r,codecs:i})=>({id:a,language:e,hdr:r,label:t,codec:(0,Gi.default)(i.split("."),0)}),xs=a=>"url"in a,jt=a=>a.type==="template",Yi=a=>a instanceof DOMException&&(a.name==="AbortError"||a.code===20);var Qi=class{constructor(e,t,r,{fetcher:i,tuning:s,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentSegmentLength$=new Wi(0);this.onLastSegment$=new Wi(!1);this.fullyBuffered$=new Wi(!1);this.playingRepresentation$=new Wi(void 0);this.playingRepresentationInit$=new Wi(void 0);this.error$=new Yk;this.gaps=[];this.subscription=new Wk;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new at;this.destroyAbortController=new at;this.bufferLimit=1/0;this.failedDownloads=0;this.isLive=!1;this.liveUpdateSegmentIndex=0;this.liveInitialAdditionalOffset=0;this.isSeekingLive=!1;this.index=0;this.loadByteRangeSegmentsTimeoutId=0;this.startWith=Rr(this.destroyAbortController.signal,function(e){return te(this,null,function*(){let t=this.representations.get(e);ze(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(Vu(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let o,u=this.mediaSource.readyState;u!=="open"&&(o={id:`SegmentEjection_source_${u}`,category:Gt.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o!=null||(o={id:"SegmentEjection",category:Gt.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),this.error$.next(o)})),this.subscription.add(Vu(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:Gt.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o)return;let u=Math.min(this.bufferLimit,Pu(this.sourceBuffer.buffered)*.8);if(this.bufferLimit=u,this.tuning.useNewPruneBufferStrategy){let l=rt(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);ze(r,"No init buffer for starting representation"),ze(i,"No segments for starting representation"),r instanceof ArrayBuffer&&(this.searchGaps(i,t),yield this.sourceBufferTaskQueue.append(r,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(s))})}.bind(this));this.switchTo=Rr(this.destroyAbortController.signal,function(e,t=!1){return te(this,null,function*(){if(e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let r=this.representations.get(e);ze(r,`No such representation ${e}`);let i=this.segments.get(e),s=this.initData.get(e);if(qe(s)||qe(i)?yield this.loadInit(r,"high",!1):s instanceof Promise&&(yield s),i=this.segments.get(e),ze(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=Rr(this.destroyAbortController.signal,function(e){return te(this,null,function*(){var u,l;let t=(u=e==null?void 0:e.flatMap(c=>c.representations))!=null?u:[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let c of this.representations.keys()){let d=t.find(f=>f.id===c);d&&this.representations.set(c,d);let p=this.representations.get(c);if(!p||!jt(p.segmentReference))return;let h=this.getActualLiveStartingSegments(p.segmentReference);this.segments.set(p.id,h)}let r=(l=this.switchingToRepresentationId)!=null?l:this.downloadingRepresentationId,i=this.representations.get(r);ze(i);let s=this.segments.get(r);ze(s,"No segments for starting representation");let n=this.initData.get(r);if(ze(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 at,this.abortBuffer()}maintain(e=this.getCurrentPosition()){var l,c;if(qe(e)||qe(this.downloadingRepresentationId)||qe(this.playingRepresentationId)||qe(this.sourceBuffer)||!qe(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),r=this.segments.get(this.downloadingRepresentationId);if(ze(t,`No such representation ${this.downloadingRepresentationId}`),!r)return;let i=r.find(d=>e>=d.time.from&&e<d.time.to);this.currentSegmentLength$.next(((l=i==null?void 0:i.time.to)!=null?l:0)-((c=i==null?void 0:i.time.from)!=null?c:0));let s=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){let p=rt(this.sourceBuffer.buffered,e),h=i?i.time.to+100:-1/0;i&&i.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&p>=i.time.to-e+100&&(s=h)}if(isFinite(this.bufferLimit)&&Pu(this.sourceBuffer.buffered)>=this.bufferLimit){let d=rt(this.sourceBuffer.buffered,e),p=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,d<p);return}let o=[];if(!this.activeSegments.size&&(o=this.selectForwardBufferSegments(r,t.segmentReference.type,s),o.length)){let d="auto";if(this.tuning.dash.useFetchPriorityHints&&i)if(o.includes(i))d="high";else{let p=(0,Lr.default)(o,0);p&&p.time.from-i.time.to>=this.forwardBufferTarget/2&&(d="low")}this.loadSegments(o,t,d)}(!this.preloadOnly&&!this.allInitsLoaded&&i&&i.status==="fed"&&!o.length&&rt(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let u=(0,Lr.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||!jt(o.segmentReference))return;let u=o.segmentReference.segments.map(p=>q(R({},p),{status:"none",size:void 0})),l=(i=this.segments.get(o.id))!=null?i:[],c=(n=(s=(0,Lr.default)(l,-1))==null?void 0:s.time.to)!=null?n:0,d=u==null?void 0:u.findIndex(p=>Math.floor(c)>=Math.floor(p.time.from)&&Math.floor(c)<=Math.floor(p.time.to));if(d===-1){this.liveUpdateSegmentIndex=0;let p=this.getActualLiveStartingSegments(o.segmentReference);this.segments.set(o.id,p)}else{let p=u.slice(d+1);this.segments.set(o.id,[...l,...p])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;ze(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(!jt(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=Ht(i.segmentTemplateUrl,{segmentTime:u});s.push({status:"none",time:{from:e.time.to,to:1/0},url:l})}}}findSegmentStartTime(e){var s,n,o;let t=(n=(s=this.switchingToRepresentationId)!=null?s:this.downloadingRepresentationId)!=null?n:this.playingRepresentationId;if(!t)return;let r=this.segments.get(t);if(!r)return;let i=r.find(u=>u.time.from<=e&&u.time.to>=e);return(o=i==null?void 0:i.time.from)!=null?o:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){var e;if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),(e=this.sourceBufferTaskQueue)==null||e.destroy(),this.gapDetectionIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer){this.mediaSource.readyState==="open"&&this.abortBuffer();try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(t){if(!(t instanceof DOMException&&t.name==="NotFoundError"))throw t}}this.sourceBuffer=null,this.downloadAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,r){return this.isLive?this.selectForwardBufferSegmentsLive(e,r):this.selectForwardBufferSegmentsRecord(e,t,r)}selectForwardBufferSegmentsLive(e,t){let r=e.findIndex(i=>t>=i.time.from&&t<i.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=r),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,r){let i=e.findIndex(({status:d,time:{from:p,to:h}},f)=>{let b=p<=r&&h>=r,g=p>r||b||f===0&&r===0,S=Math.min(this.forwardBufferTarget,this.bufferLimit),I=this.preloadOnly&&p<=r+S||h<=r+S;return(d==="none"||d==="partially_ejected"&&g&&I&&this.sourceBuffer&&!xi(this.sourceBuffer.buffered,r))&&g&&I});if(i===-1)return[];if(t!=="byteRange")return e.slice(i,i+1);let s=e,n=0,o=0,u=[],l=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,c=this.preloadOnly?this.forwardBufferTarget:0;for(let d=i;d<s.length&&(n<=l||o<=c);d++){let p=s[d];if(n+=p.byte.to+1-p.byte.from,o+=p.time.to+1-p.time.from,p.status==="none"||p.status==="partially_ejected")u.push(p);else break}return u}loadSegments(e,t,r="auto"){return A(this,null,function*(){t.segmentReference.type==="template"?yield this.loadTemplateSegment(e[0],t,r):yield this.loadByteRangeSegments(e,t,r)})}loadTemplateSegment(e,t,r="auto"){return A(this,null,function*(){e.status="downloading";let i={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(i);let{range:s,url:n,signal:o,onProgress:u,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(yield Rr(o,function(){return te(this,null,function*(){let c=_u(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(d=>setTimeout(d,c))})}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let c=yield this.fetcher.fetch(n,{range:s,signal:o,onProgress:u,priority:r,isLowLatency:this.isActiveLowLatency()});if(!c)return;let d=new DataView(c);if(!isFinite(i.segment.time.to)){let p=t.segmentReference.timescale,h=Ar(t.mime);i.segment.time.to=h.getSegmentEndTime(d,p)}u&&i.feedingBytes&&l?yield Promise.all(l):yield this.sourceBufferTaskQueue.append(d,o),i.segment.status="downloaded",this.onSegmentFullyAppended(i,t.id),this.failedDownloads=0}catch(c){this.abortActiveSegments([e]),Yi(c)||this.failedDownloads++}})}loadByteRangeSegments(e,t,r="auto"){return A(this,null,function*(){if(!e.length)return;for(let u of e)u.status="downloading",this.activeSegments.add({segment:u,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:i,url:s,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(yield Rr(n,function(){return te(this,null,function*(){let u=_u(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),Vu(window,"online").pipe(Gk()).subscribe(()=>{l(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{yield this.fetcher.fetch(s,{range:i,onProgress:o,signal:n,priority:r}),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),Yi(u)||this.failedDownloads++}})}prepareByteRangeFetchSegmentParams(e,t){if(jt(t.segmentReference))throw new Error("Representation is not byte range type");let r=t.segmentReference.url,i={from:(0,Lr.default)(e,0).byte.from,to:(0,Lr.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:Gt.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!jt(t.segmentReference))throw new Error("Representation is not template type");let r=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&r.searchParams.set("low-latency","yes");let i=r.toString(),{signal:s}=this.downloadAbortController,n=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(l,c)=>{if(!s.aborted)try{let d=this.onSomeTemplateDataLoaded({dataView:l,loaded:c,signal:s,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(d)}catch(d){this.error$.next({id:"SegmentFeeding",category:Gt.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:d})}}:void 0;return{url:i,signal:s,onProgress:u,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)e.includes(t.segment)&&this.abortSegment(t.segment)}onSomeTemplateDataLoaded(n){return A(this,arguments,function*({dataView:e,representationId:t,loaded:r,onSegmentAppendFailed:i,signal:s}){if(!this.activeSegments.size)return;let o=this.representations.get(t);if(o)for(let u of this.activeSegments){let{segment:l}=u;if(u.representationId===t){if(s.aborted){i();continue}if(u.loadedBytes=r,u.loadedBytes>u.feedingBytes){let c=new DataView(e.buffer,e.byteOffset+u.feedingBytes,u.loadedBytes-u.feedingBytes),d=Ar(o.mime).parseFeedableSegmentChunk(c,this.isLive);d!=null&&d.byteLength&&(l.status="partially_fed",u.feedingBytes+=d.byteLength,yield this.sourceBufferTaskQueue.append(d),u.fedBytes+=d.byteLength)}}}})}onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:r,loaded:i,signal:s,onSegmentAppendFailed:n}){let o={dataView:e,representationId:t,globalFrom:r,loaded:i,signal:s,onSegmentAppendFailed:n};return this.tuning.useNewPartialSegmentFeeding?this.onSomeByteRangesDataLoadedNew(o):this.onSomeByteRangesDataLoadedOld(o)}onSomeByteRangesDataLoadedOld({dataView:e,representationId:t,globalFrom:r,loaded:i,signal:s,onSegmentAppendFailed:n}){if(!this.activeSegments.size)return;let o=this.representations.get(t);if(!o)return;let u=o.segmentReference.type,l=e.byteLength;for(let c of this.activeSegments){let{segment:d}=c,p=u==="byteRange",h=p?d.byte.to-d.byte.from+1:l;if(c.representationId!==t||!(!p||d.byte.from>=r&&d.byte.to<r+e.byteLength))continue;if(s.aborted){n();continue}let b=p?d.byte.from-r:0,g=p?d.byte.to-r:e.byteLength,S=b<i,I=g<=i;if(d.status==="downloading"&&S&&I){d.status="downloaded";let v=new DataView(e.buffer,e.byteOffset+b,h);this.sourceBufferTaskQueue.append(v,s).then(T=>T&&!s.aborted?this.onSegmentFullyAppended(c,t):n())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&S&&(c.loadedBytes=Math.min(h,i-b),c.loadedBytes>c.feedingBytes)){let v=new DataView(e.buffer,e.byteOffset+b+c.feedingBytes,c.loadedBytes-c.feedingBytes),T=c.loadedBytes===h?v:Ar(o.mime).parseFeedableSegmentChunk(v);T!=null&&T.byteLength&&(d.status="partially_fed",c.feedingBytes+=T.byteLength,this.sourceBufferTaskQueue.append(T,s).then(y=>{if(s.aborted)n();else if(y)c.fedBytes+=T.byteLength,c.fedBytes===h&&this.onSegmentFullyAppended(c,t);else{if(c.feedingBytes<h)return;n()}}))}}}onSomeByteRangesDataLoadedNew(o){return A(this,arguments,function*({dataView:e,representationId:t,globalFrom:r,loaded:i,signal:s,onSegmentAppendFailed:n}){if(!this.activeSegments.size)return;let u=this.representations.get(t);if(u)for(let l of this.activeSegments){let{segment:c}=l;if(l.representationId!==t)continue;if(s.aborted){n();continue}let d=c.byte.from-r,p=c.byte.to-r,h=p-d+1,f=d<i,b=p<=i;if(f){if(c.status==="downloading"&&b){c.status="downloaded";let g=new DataView(e.buffer,e.byteOffset+d,h);(yield this.sourceBufferTaskQueue.append(g,s))&&!s.aborted?this.onSegmentFullyAppended(l,t):n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(c.status==="downloading"||c.status==="partially_fed")&&(l.loadedBytes=Math.min(h,i-d),l.loadedBytes>l.feedingBytes)){let g=new DataView(e.buffer,e.byteOffset+d+l.feedingBytes,l.loadedBytes-l.feedingBytes),S=l.loadedBytes===h?g:Ar(u.mime).parseFeedableSegmentChunk(g);S!=null&&S.byteLength&&(c.status="partially_fed",l.feedingBytes+=S.byteLength,(yield this.sourceBufferTaskQueue.append(S,s))&&!s.aborted?(l.fedBytes+=S.byteLength,l.fedBytes===h&&this.onSegmentFullyAppended(l,t)):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",xs(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=Iu(()=>(0,Ig.default)(this.loadInit(r,"low",!1),()=>this.initLoadIdleCallback=null)))}loadInit(e,t="auto",r=!1){return A(this,null,function*(){let i=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!r&&this.failedDownloads>0?Rr(this.destroyAbortController.signal,function(){return te(this,null,function*(){let o=_u(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))})}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,Ar(e.mime),i)).then(o=>A(this,null,function*(){if(!o)return;let{init:u,dataView:l,segments:c}=o,d=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,d);let p=c;this.isLive&&jt(e.segmentReference)&&(p=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,p),u&&this.parsedInitData.set(e.id,u)})).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),r&&this.error$.next({id:"LoadInits",category:Gt.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n})}dropBuffer(){return A(this,null,function*(){for(let e of this.segments.values())for(let t of e)t.status="none";yield this.pruneBuffer(0,1/0,!0)})}pruneBuffer(e,t,r=!1){return A(this,null,function*(){return this.tuning.useNewPruneBufferStrategy?this.pruneBufferNew(e,t,r):this.pruneBufferOld(e,t,r)})}pruneBufferNew(e,t,r=!1){return A(this,null,function*(){if(!this.sourceBuffer||!this.playingRepresentationId||qe(e)||this.sourceBuffer.updating)return!1;let i=[],s=0,n=u=>{u.sort((c,d)=>c.from-d.from);let l=[u[0]];for(let c=1;c<u.length;c++){let{from:d,to:p}=u[c],h=l[l.length-1];h.to>=d?h.to=Math.max(h.to,p):l.push(u[c])}return l},o=u=>{var c;if(s>=t)return i;i.push(u.time),i=n(i);let l=xs(u)?(c=u.size)!=null?c:0:u.byte.to-u.byte.from;s+=l};for(let u of this.segments.values())for(let l of u){let c=l.time.to<=e-this.tuning.dash.bufferPruningSafeZone,d=l.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(c||d)&&l.status==="fed"&&o(l)}for(let u=0;u<this.sourceBuffer.buffered.length;u++){let l=this.sourceBuffer.buffered.start(u)*1e3,c=this.sourceBuffer.buffered.end(u)*1e3,d=0;for(let p of this.segments.values())for(let h of p)h.status==="none"&&Math.round(h.time.from)<=Math.round(l)&&Math.round(h.time.to)>=Math.round(c)&&d++;if(d===this.segments.size){let p={time:{from:l,to:c},url:"",status:"none"};o(p)}}if(i.length&&r){let u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let l of this.segments.values())for(let c of l)c.time.from>=e+u&&c.status==="fed"&&o(c)}return i.length?(yield Promise.all(i.map(l=>this.sourceBufferTaskQueue.remove(l.from,l.to)))).reduce((l,c)=>l||c,!1):!1})}pruneBufferOld(e,t,r=!1){return A(this,null,function*(){if(!this.sourceBuffer||!this.playingRepresentationId||qe(e)||this.sourceBuffer.updating)return!1;let i=0,s=1/0,n=-1/0,o=!1,u=l=>{var d;s=Math.min(s,l.time.from),n=Math.max(n,l.time.to);let c=xs(l)?(d=l.size)!=null?d:0:l.byte.to-l.byte.from;i+=c};for(let l of this.segments.values())for(let c of l){if(c.time.to>=e-this.tuning.dash.bufferPruningSafeZone||i>=t)break;c.status==="fed"&&u(c)}if(o=isFinite(s)&&isFinite(n),!o){i=0,s=1/0,n=-1/0;for(let l of this.segments.values())for(let c of l){if(c.time.from<e+Math.min(this.forwardBufferTarget,this.bufferLimit)||i>t)break;c.status==="fed"&&u(c)}}if(o=isFinite(s)&&isFinite(n),!o)for(let l=0;l<this.sourceBuffer.buffered.length;l++){let c=this.sourceBuffer.buffered.start(l)*1e3,d=this.sourceBuffer.buffered.end(l)*1e3;for(let p of this.segments.values())for(let h of p)if(h.status==="none"&&Math.round(h.time.from)<=Math.round(c)&&Math.round(h.time.to)>=Math.round(d)){s=c,n=d;break}}if(o=isFinite(s)&&isFinite(n),!o&&r){i=0,s=1/0,n=-1/0;let l=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let c of this.segments.values())for(let d of c)d.time.from>e+l&&d.status==="fed"&&u(d)}return o=isFinite(s)&&isFinite(n),o?this.sourceBufferTaskQueue.remove(s,n):!1})}abortBuffer(){if(!this.sourceBuffer||this.mediaSource.readyState!=="open")return;let e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;this.sourceBufferTaskQueue.abort(t)}getDebugBufferState(){if(!(!this.sourceBuffer||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}detectGaps(e,t){if(this.sourceBuffer)for(let r of t){let i={representation:e,from:r.time.from,to:r.time.to};for(let s=0;s<this.sourceBuffer.buffered.length;s++){let n=this.sourceBuffer.buffered.start(s)*1e3,o=this.sourceBuffer.buffered.end(s)*1e3;if(!(o<=r.time.from||n>=r.time.to)){if(n<=r.time.from&&o>=r.time.to){i=void 0;break}o>r.time.from&&o<r.time.to&&(i.from=o),n<r.time.to&&n>r.time.from&&(i.to=n)}}i&&i.to-i.from>1&&!this.gaps.some(s=>i&&s.from===i.from&&s.to===i.to)&&this.gaps.push(i)}}detectGapsWhenIdle(e,t){this.gapDetectionIdleCallback||(this.gapDetectionIdleCallback=Iu(()=>{try{this.detectGaps(e,t)}catch(r){this.error$.next({id:"GapDetection",category:Gt.WTF,message:"detectGaps threw",thrown:r})}finally{this.gapDetectionIdleCallback=null}}))}checkEjectedSegments(){if(qe(this.sourceBuffer)||qe(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 zi=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 Ki,assertNever as xg,fromEvent as Pg,merge as Qk,now as Nu,Subscription as zk,ValueSubject as Fu}from"@vkontakte/videoplayer-shared";var Ps=class{constructor({throughputEstimator:e,requestQuic:t,compatibilityMode:r=!1}){this.lastConnectionType$=new Fu(void 0);this.lastConnectionReused$=new Fu(void 0);this.lastRequestFirstBytes$=new Fu(void 0);this.abortAllController=new at;this.subscription=new zk;this.fetchManifest=Ki(this.abortAllController.signal,function(e){return te(this,null,function*(){let t=e;this.requestQuic&&(t=zi(t));let r=yield it(t,{signal:this.abortAllController.signal}).catch(Ji);return r?(this.onHeadersReceived(r.headers),r.text()):null})}.bind(this));this.fetch=Ki(this.abortAllController.signal,function(l){return te(this,arguments,function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:r,onProgress:i,priority:s="auto",signal:n,measureThroughput:o=!0,isLowLatency:u=!1}={}){var O,U;let c=e,d=new Headers;if(r)switch(t){case 0:{d.append("Range",`bytes=${r.from}-${r.to}`);break}case 1:{let L=new URL(c,location.href);L.searchParams.append("bytes",`${r.from}-${r.to}`),c=L.toString();break}default:xg(t)}this.requestQuic&&(c=zi(c));let p=this.abortAllController.signal,h;if(n){let L=new at;if(h=Qk(Pg(this.abortAllController.signal,"abort"),Pg(n,"abort")).subscribe(()=>{try{L.abort()}catch(w){Ji(w)}}),this.abortAllController.signal.aborted||n.aborted)try{L.abort()}catch(w){Ji(w)}p=L.signal}let f=Nu(),b=yield it(c,{priority:s,headers:d,signal:p}).catch(Ji),g=Nu();if(!b)return h==null||h.unsubscribe(),null;if((O=this.throughputEstimator)==null||O.addRawRtt(g-f),!b.ok||!b.body)return h==null||h.unsubscribe(),Promise.reject(new Error(`Fetch error ${b.status}: ${b.statusText}`));if(this.onHeadersReceived(b.headers),!i&&!o)return h==null||h.unsubscribe(),b.arrayBuffer();let[S,I]=b.body.tee(),v=S.getReader();o&&((U=this.throughputEstimator)==null||U.trackStream(I,u));let T=0,y=new Uint8Array(0),B=!1,D=L=>{h==null||h.unsubscribe(),B=!0,Ji(L)},$=Ki(p,function(H){return te(this,arguments,function*({done:L,value:w}){if(T===0&&this.lastRequestFirstBytes$.next(Nu()-f),p.aborted){h==null||h.unsubscribe();return}if(!L&&w){let W=new Uint8Array(y.length+w.length);W.set(y),W.set(w,y.length),y=W,T+=w.byteLength,i==null||i(new DataView(y.buffer),T),yield v==null?void 0:v.read().then($,D)}})}.bind(this));return yield v==null?void 0:v.read().then($,D),h==null||h.unsubscribe(),B?null:y.buffer})}.bind(this));this.fetchByteRangeRepresentation=Ki(this.abortAllController.signal,function(e,t,r){return te(this,null,function*(){var S;if(e.type!=="byteRange")return null;let{from:i,to:s}=e.initRange,n=i,o=s,u=!1,l,c;e.indexRange&&(l=e.indexRange.from,c=e.indexRange.to,u=s+1===l,u&&(n=Math.min(l,i),o=Math.max(c,s))),n=Math.min(n,0);let d=yield this.fetch(e.url,{range:{from:n,to:o},priority:r,measureThroughput:!1});if(!d)return null;let p=new DataView(d,i-n,s-n+1);if(!t.validateData(p))throw new Error("Invalid media file");let h=t.parseInit(p),f=(S=e.indexRange)!=null?S:t.getIndexRange(h);if(!f)throw new ReferenceError("No way to load representation index");let b;if(u)b=new DataView(d,f.from-n,f.to-f.from+1);else{let I=yield this.fetch(e.url,{range:f,priority:r,measureThroughput:!1});if(!I)return null;b=new DataView(I)}let g=t.parseSegments(b,h,f);return{init:h,dataView:new DataView(d),segments:g}})}.bind(this));this.fetchTemplateRepresentation=Ki(this.abortAllController.signal,function(e,t){return te(this,null,function*(){if(e.type!=="template")return null;let r=new URL(e.initUrl,e.baseUrl).toString(),i=yield this.fetch(r,{priority:t,measureThroughput:!1});return i?{init:null,segments:e.segments.map(n=>q(R({},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)}fetchRepresentation(e,t,r="auto"){return A(this,null,function*(){var s,n;let{type:i}=e;switch(i){case"byteRange":return(s=yield this.fetchByteRangeRepresentation(e,t,r))!=null?s:null;case"template":return(n=yield this.fetchTemplateRepresentation(e,r))!=null?n:null;default:xg(i)}})}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}},Ji=a=>{if(!Yi(a))throw a};var Yt=(a,e,t)=>t*e+(1-t)*a,qu=(a,e)=>a.reduce((t,r)=>t+r,0)/e,wg=(a,e,t,r)=>{let i=0,s=t,n=qu(a,e),o=e<r?e:r;for(let u=0;u<o;u++)a[s]>n?i++:i--,s=(a.length+s-1)%a.length;return Math.abs(i)===o};import{isNullable as Kk,ValueSubject as Ag}from"@vkontakte/videoplayer-shared";var yt=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 Ag(e.initial),this.debounced$=new Ag(e.initial);let t=(r=e.label)!=null?r:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new ne(`raw_${t}`),this.smoothedSeries$=new ne(`smoothed_${t}`),this.reportedSeries$=new ne(`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+=je(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)&&(Kk(this.prevReported)||Math.abs(this.smoothed-this.prevReported)/this.prevReported>=this.params.changeThreshold)&&(this.prevReported=this.smoothed,this.debounced$.next(this.smoothed),this.reportedSeries$.next(this.smoothed))}};var ws=class extends yt{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=Yt(this.slow,e,this.params.emaAlphaSlow),this.fast=Yt(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var As=class extends yt{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=qu(this.pastMeasures,this.takenMeasures);this.emaSmoothed=Yt(this.emaSmoothed,e,this.params.emaAlpha);let r=wg(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=r?this.emaSmoothed:t}};var ks=class extends yt{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?Yt(this.smoothed,t,this.params.emaAlpha):t}};var Wt=class{static getSmoothedValue(e,t,r){return r.type==="TwoEma"?new ws({initial:e,emaAlphaSlow:r.emaAlphaSlow,emaAlphaFast:r.emaAlphaFast,changeThreshold:r.changeThreshold,fastDirection:t,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"}):new As({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 ks(R({initial:e,label:"liveEdgeDelay"},t))}};var Uu=(a,e)=>{a&&a.playbackRate!==e&&(a.playbackRate=e)};var Cg=["timeupdate","progress","play","seeked","stalled","waiting"];var $s=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 M("none");this.currentVideoRepresentation$=new oe(void 0);this.currentVideoRepresentationInit$=new oe(void 0);this.currentAudioRepresentation$=new oe(void 0);this.currentVideoSegmentLength$=new oe(0);this.currentAudioSegmentLength$=new oe(0);this.error$=new $g;this.lastConnectionType$=new oe(void 0);this.lastConnectionReused$=new oe(void 0);this.lastRequestFirstBytes$=new oe(void 0);this.isLive$=new oe(!1);this.liveDuration$=new oe(0);this.liveAvailabilityStartTime$=new oe(void 0);this.bufferLength$=new oe(0);this.liveLoadBufferLength$=new oe(0);this.livePositionFromPlayer$=new oe(0);this.timeInWaiting=0;this.isActiveLowLatency$=new oe(!1);this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.liveLastSeekOffset=0;this.forceEnded$=new $g;this.gapWatchdogActive=!1;this.destroyController=new at;this.initManifest=Hu(this.destroyController.signal,function(e,t,r){return te(this,null,function*(){var i;this.element=e,this.manifestUrlString=ae(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:Tt.PARSER,message:"No playable video representations"})})}.bind(this));this.updateManifest=Hu(this.destroyController.signal,function(){return te(this,null,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:Tt.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:Tt.PARSER,message:"Failed to parse MPD manifest",thrown:o};this.error$.next(u)}if(!t)return null;let r=(o,u,l)=>{var c,d,p,h;return!!((d=(c=this.element)==null?void 0:c.canPlayType)!=null&&d.call(c,u)&&((h=(p=st())==null?void 0:p.isTypeSupported)!=null&&h.call(p,`${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:p,codecs:h})=>r(o,p,h)),c=new Set(l.map(({codecs:p})=>p)),d=Lb(c);if(d&&(i[o]=l.filter(({codecs:p})=>p.startsWith(d))),o==="video"){let p=this.tuning.preferHDR,h=i.video.some(b=>b.hdr),f=i.video.some(b=>!b.hdr);tR.isHDR&&p&&h?i.video=i.video.filter(b=>b.hdr):f&&(i.video=i.video.filter(b=>!b.hdr))}}return q(R({},t),{streams:i})})}.bind(this));this.initRepresentations=Hu(this.destroyController.signal,function(e,t,r){return te(this,null,function*(){var d;Qt(this.manifest),Qt(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let i=p=>{this.representationSubscription.add($r(p,"error").pipe(Ls(h=>{var f;return!!((f=this.element)!=null&&f.played.length)})).subscribe(h=>{this.error$.next({id:"VideoSource",category:Tt.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&&ps())if(r){let p=document.createElement("source");i(p),p.type="application/x-mpegurl",p.src=r.url,this.element.appendChild(p)}else this.element.disableRemotePlayback=!0;this.isActiveLowLatency$.next(this.isLive$.getValue()&&this.tuning.dashCmafLive.lowLatency.isActive);let n={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLowLatency$.getValue(),manifest:this.manifest},o=this.manifest.streams.video.reduce((p,h)=>[...p,...h.representations],[]);if(this.videoBufferManager=new Qi("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],Lg(t)){let p=this.manifest.streams.audio.reduce((h,f)=>[...h,...f.representations],[]);this.audioBufferManager=new Qi("audio",this.source,p,n),this.bufferManagers.push(this.audioBufferManager)}if(this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$)),this.representationSubscription.add(ju(1e3).subscribe(p=>{var h;if((h=this.element)!=null&&h.paused){let f=tu(this.manifestUrlString,2);this.manifestUrlString=ae(this.manifestUrlString,f+1e3,2)}})),this.representationSubscription.add(Mr(...Cg.filter(p=>p!=="waiting").map(p=>$r(this.element,p))).pipe(Gu(p=>this.element?rt(this.element.buffered,this.element.currentTime*1e3):0),Rg(),Ls(p=>!!p),Zk(p=>{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=>Uu(this.element,1))),this.representationSubscription.add(Rs({bufferLength:this.bufferLength$,isActiveLowLatency:this.isActiveLowLatency$}).pipe(Ls(({bufferLength:h,isActiveLowLatency:f})=>f&&!!h)).subscribe(({bufferLength:h})=>this.liveEstimatedDelay.next(h))),this.representationSubscription.add(Rs({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,S=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,I=h-b,v=1;Math.abs(I)>g&&(v=1+Math.sign(I)*S),Uu(this.element,v)})),this.representationSubscription.add(this.bufferLength$.subscribe(h=>{var b,g;let f=0;if(h){let S=((g=(b=this.element)==null?void 0:b.currentTime)!=null?g:0)*1e3;f=Math.min(...this.bufferManagers.map(v=>{var T,y;return(y=(T=v.getLiveSegmentsToLoadState(this.manifest))==null?void 0:T.to)!=null?y:S}))-S}this.liveLoadBufferLength$.getValue()!==f&&this.liveLoadBufferLength$.next(f)}));let p=0;this.representationSubscription.add(Rs({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(eR(1e3)).subscribe(b=>A(this,[b],function*({liveLoadBufferLength:h,bufferLength:f}){if(Qt(this.element),this.isUpdatingLive)return;let g=this.element.playbackRate,S=tu(this.manifestUrlString,2),I=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,v=Math.min(I,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*g),T=this.tuning.dashCmafLive.normalizedActualBufferOffset*g,y=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*g,B=isFinite(h)?h:f,D=this.isActiveLowLatency$.getValue(),$=I<=this.tuning.live.activeLiveDelay&&S===0;this.isActiveLowLatency$.next(D&&$);let O="none";if(D?O="active_low_latency":this.tuning.dashCmafLive.lowLatency.isActive&&$?(this.isActiveLowLatency$.next(!0),this.bufferManagers.forEach(U=>U.proceedLowLatencyLive()),O="active_low_latency"):S!==0&&B<v?O="live_forward_buffering":B<v+y&&(O="live_with_target_offset"),isFinite(h)&&(p=h>p?h:p),O==="live_forward_buffering"||O==="live_with_target_offset"){let U=p-(v+T),L=this.normolizeLiveOffset(Math.trunc(S+U/g)),w=Math.abs(L-S),H;!h||w<=this.tuning.dashCmafLive.offsetCalculationError?H=S:L>0&&w>this.tuning.dashCmafLive.offsetCalculationError?H=L:H=0,this.manifestUrlString=ae(this.manifestUrlString,H,2)}O!=="none"&&O!=="active_low_latency"&&(p=0,this.updateLive())})))}let u=Mr(...this.bufferManagers.map(p=>p.fullyBuffered$)).pipe(Gu(()=>this.bufferManagers.every(p=>p.fullyBuffered$.getValue()))),l=Mr(...this.bufferManagers.map(p=>p.onLastSegment$)).pipe(Gu(()=>this.bufferManagers.some(p=>p.onLastSegment$.getValue())));this.representationSubscription.add(Mr(this.forceEnded$,Rs({allBuffersFull:u,someBufferEnded:l}).pipe(Ls(({allBuffersFull:p,someBufferEnded:h})=>p&&h))).subscribe(()=>{var p;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(h=>!h.updating))try{(p=this.source)==null||p.endOfStream()}catch(h){this.error$.next({id:"EndOfStream",category:Tt.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:h})}})),this.representationSubscription.add(Mr(...this.bufferManagers.map(p=>p.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.subscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.subscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&(this.representationSubscription.add(this.audioBufferManager.playingRepresentation$.subscribe(this.currentAudioRepresentation$)),this.subscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$))),this.source.readyState!=="open"&&(yield new Promise(p=>{var h;return(h=this.source)==null?void 0:h.addEventListener("sourceopen",p)}));let c=[(d=this.manifest.duration)!=null?d:0,...[...this.manifest.streams.audio,...this.manifest.streams.video].flatMap(p=>p.representations).flatMap(p=>{let h=[];if(p.duration&&h.push(p.duration),p.segmentReference.type==="template"){let f=p.segmentReference.segments;h.push(f[f.length-1].time.to)}return h})];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=ju(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),i=>{this.error$.next({id:"GapWatchdog",category:Tt.WTF,message:"Error handling gaps",thrown:i})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.fetcher=new Ps({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode}),this.liveEstimatedDelay=Wt.getLiveEstimatedDelaySmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,R({},e.tuning.dashCmafLive.lowLatency.delayEstimator))}seekLive(e){return A(this,null,function*(){var r,i,s,n;Qt(this.element);let t=this.normolizeLiveOffset(e);this.isActiveLowLatency$.next(this.tuning.dashCmafLive.lowLatency.isActive&&t===0),this.liveLastSeekOffset=t,this.manifestUrlString=ae(this.manifestUrlString,t,2),this.manifest=yield this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,yield(i=this.videoBufferManager)==null?void 0:i.seekLive((r=this.manifest)==null?void 0:r.streams.video),yield(n=this.audioBufferManager)==null?void 0:n.seekLive((s=this.manifest)==null?void 0:s.streams.audio))})}initBuffer(){Qt(this.element),this.state$.setState("running"),this.subscription.add(Mr(...Cg.map(e=>$r(this.element,e)),$r(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:Tt.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add($r(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add($r(this.element,"waiting").subscribe(()=>{var t;this.element&&this.element.readyState===2&&!this.element.seeking&&xi(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=ju(1e3).subscribe(e,r=>{this.error$.next({id:"StallWatchdogCallback",category:Tt.FATAL,message:"Can't restore DASH after stall.",thrown:r})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}switchRepresentation(e,t,r=!1){return A(this,null,function*(){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;Qt(this.element),Qt(this.videoBufferManager);let r;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?r=e:r=Math.max((i=this.videoBufferManager.findSegmentStartTime(e))!=null?i:e,(n=(s=this.audioBufferManager)==null?void 0:s.findSegmentStartTime(e))!=null?n:e),xi(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}updateLive(){return A(this,null,function*(){var e;this.isUpdatingLive=!0,this.manifest=yield 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 Ms=class{constructor(e,t){this.fov=e,this.orientation=t}};var Cs=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/je(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=R({},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*je(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;
36
+ [best video track] ${V==null?void 0:V.quality}
37
+ [selected video track] ${D==null?void 0:D.quality}
38
+ `}),Mb(r,p,D,c)},Cb=(a,e,t,{throughput:r,tuning:i,playbackRate:s,forwardBufferHealth:n,history:o,abrLogger:u})=>{var f;Rb(t,Lb);let c=i.considerPlaybackRate&&ve(s)?s:1,l=[...t].sort(Lu(-1)),d=a.bitrate;kw(d);let p=c*$b(n!=null?n:.5,i.bitrateAudioFactorAtEmptyBuffer,i.bitrateAudioFactorAtFullBuffer),h;return ve(r)&&isFinite(r)&&(h=l.find(b=>ve(b.bitrate)?r-d>=b.bitrate*p:!0)),h||(h=Ls(a,e,t,i.minVideoAudioRatio)),(h==null?void 0:h.bitrate)!==((f=o==null?void 0:o.last)==null?void 0:f.bitrate)&&u({message:`
39
+ [AUDIO TRACKS ABR]
40
+ [available audio tracks]
41
+ ${t.map(b=>`{ id: ${b.id}, 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: ${d},
51
+ playbackRate: ${s},
52
+ playbackRateFactor: ${c},
53
+ forwardBufferHealth: ${n},
54
+ bitrateFactor: ${p},
55
+ minBufferToSwitchUp: ${i.minBufferToSwitchUp},
56
+
57
+ [selected audio track] ${h==null?void 0:h.id}
58
+ `}),h&&Mb(i,u,h,o)};var re=a=>new URL(a).hostname;import{assertNever as Nb,assertNonNullable as Fb,combine as zw,debounce as Kw,ErrorCategory as qb,filter as Ub,filterChanged as Jw,isNonNullable as Ou,map as Os,merge as Hb,observableFrom as Xw,once as Zw,Subscription as ek,ValueSubject as Vu,videoQualityToHeight as tk,videoSizeToQuality as rk}from"@vkontakte/videoplayer-shared";var Db=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"))},ye=a=>R(void 0,null,function*(){let e=a.muted;try{yield a.play()}catch(t){if(!Db(t))return!1;if(e)return console.warn(t),!1;a.muted=!0;try{yield a.play()}catch(r){return Db(r)&&(a.muted=!1,console.warn(r)),!1}}return!0});import{isNonNullable as Cs,isNullable as Mw,assertNonNullable as Bi}from"@vkontakte/videoplayer-shared";import{isNonNullable as Bb,assertNonNullable as Ms,now as $w}from"@vkontakte/videoplayer-shared";function ie(){return $w()}function Mu(a){return ie()-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 c=n.indexOf("?")>-1?"&":"?";return u&&(n+=c+"lowLat=1",c="&"),o&&(n+=c+"_rnd="+Math.floor(999999999*Math.random())),n}}}function Ob(a,e,t){let r=(...i)=>{t.apply(null,i),a.removeEventListener(e,r)};a.addEventListener(e,r)}function Or(a,e,t,r){let i=window.XMLHttpRequest,s,n,o,u=!1,c=0,l,d,p=!1,h="arraybuffer",f=7e3,b=2e3,g=()=>{if(u)return;Ms(l);let L=Mu(l),F;if(L<b){F=b-L,setTimeout(g,F);return}b*=2,b>f&&(b=f),n&&n.abort(),n=new i,$()},S=L=>(s=L,N),T=L=>(d=L,N),v=()=>(h="json",N),y=()=>{if(!u){if(--c>=0){g(),r&&r();return}u=!0,d&&d(),t&&t()}},I=L=>(p=L,N),$=()=>{l=ie(),n=new i,n.open("get",a);let L=0,F,_=0,k=()=>(Ms(l),Math.max(l,Math.max(F||0,_||0)));if(s&&n.addEventListener("progress",x=>{let B=ie();s.updateChunk&&x.loaded>L&&(s.updateChunk(k(),x.loaded-L),L=x.loaded,F=B)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>y())),n.addEventListener("load",()=>{if(u)return;Ms(n);let x=n.status;if(x>=200&&x<300){if(n.response.byteLength&&s){let B=n.response.byteLength-L;B&&s.updateChunk&&s.updateChunk(k(),B)}n.responseType==="json"&&!Object.values(n.response).length?y():(d&&d(),e(n.response))}else y()}),n.addEventListener("error",()=>{y()}),p){let x=()=>{Ms(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(_=ie(),n.removeEventListener("readystatechange",x))};n.addEventListener("readystatechange",x)}return n.responseType=h,n.send(),N},N={withBitrateReporting:S,withParallel:I,withJSONResponse:v,withRetryCount:L=>(c=L,N),withRetryInterval:(L,F)=>(Bb(L)&&(b=L),Bb(F)&&(f=F),N),withTimeout:L=>(o=L,N),withFinally:T,send:$,abort:()=>{n&&(n.abort(),n=void 0),u=!0,d&&d()}};return N}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=ie(),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=ie()-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=Or(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=ie()}_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=ie();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 Ds=1e4,Du=3;var Cw=6e4,Dw=10,Bw=1,Ow=500,Oi=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=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||Cs(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){let{logger:r,videoElement:i,playerCallback:s}=this.params;this.mediaSource=new window.MediaSource,r("setting video src"),i.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.videoPlayStarted=!1,i.addEventListener("canplay",()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});let n=()=>{Ob(i,"progress",()=>{i.buffered.length?(i.currentTime=i.buffered.start(0),s({name:"playing"})):n()})};n()}_initPlayerWith(e){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new Di(Du,Ds,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){let{logger:t,videoElement:r,playerCallback:i}=this.params,s=!1,n=null,o=null,u=null,c=null,l=!1,d=()=>{let y=s&&(!l||l===this.rep);return y||t("Not running!"),y},p=(y,I,$)=>{u&&u.abort(),u=Or(this.urlResolver.resolve(y,!1),I,$,()=>this._retryCallback()).withTimeout(Ds).withBitrateReporting(this.bitrateSwitcher).withRetryCount(Du).withFinally(()=>{u=null}).send()},h=(y,I,$)=>{Bi(this.filesFetcher),o==null||o.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(y,!1),I,$,()=>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 $=ie()-1e4,G=0;for(let D=0;D<this.bufferStates.length;D++){let H=this.bufferStates[D];y=Math.min(y,H.buf),H.ts<$&&G++}this.bufferStates.splice(0,G),t(`update playback rate; minBuffer=${y} drop=${G} jitter=${this.sourceJitter}`);let V=y-Bw;this.sourceJitter>=0?V-=this.sourceJitter/2:this.sourceJitter-=1,V>3?f(1.15):V>1?f(1.1):V>.3?f(1.05):f(1)}},S=y=>{let I,$=()=>I&&I.start?I.start.length:0,G=x=>I.start[x]/1e3,V=x=>I.dur[x]/1e3,D=x=>I.fragIndex+x,H=(x,B)=>({chunkIdx:D(x),startTS:G(x),dur:V(x),discontinuity:B}),N=()=>{let x=0;if(I&&I.dur){let B=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,W=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,z=B;this.sourceJitter>1&&(z+=this.sourceJitter-1);let Z=I.dur.length-1;for(;Z>=0&&(z-=I.dur[Z],!(z<=0));--Z);x=Math.min(Z,I.dur.length-1-W),x=Math.max(x,0)}return H(x,!0)},L=x=>{let B=$();if(!(B<=0)){if(Cs(x)){for(let W=0;W<B;W++)if(G(W)>x)return H(W)}return N()}},F=x=>{let B=$(),W=x?x.chunkIdx+1:0,z=W-I.fragIndex;if(!(B<=0)){if(!x||z<0||z-B>Dw)return t(`Resync: offset=${z} bChunks=${B} chunk=`+JSON.stringify(x)),N();if(!(z>=B))return H(W-I.fragIndex,!1)}},_=(x,B,W)=>{c&&c.abort(),c=Or(this.urlResolver.resolve(x,!0,this.lowLatency),B,W,()=>this._retryCallback()).withTimeout(Ds).withRetryCount(Du).withFinally(()=>{c=null}).withJSONResponse().send()};return{seek:(x,B)=>{_(y,W=>{if(!d())return;I=W;let z=!!I.lowLatency;z!==this.lowLatency&&b(z);let Z=0;for(let le=0;le<I.dur.length;++le)Z+=I.dur[le];Z>0&&(Bi(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(L(B))},()=>this._handleNetworkError())},nextChunk:F}},T=()=>{s=!1,o&&o.abort(),u&&u.abort(),c&&c.abort(),Bi(this.filesFetcher),this.filesFetcher.abortAll()};return l={start:y=>{let{videoElement:I,logger:$}=this.params,G=S(e.jidxUrl),V,D,H,N,L=0,F,_,k,x=()=>{F&&(clearTimeout(F),F=void 0);let w=Math.max(Ow,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),de=L+w,Ee=ie(),Re=Math.min(1e4,de-Ee);L=Ee;let St=()=>{c||d()&&G.seek(()=>{d()&&(L=ie(),B(),x())})};Re>0?F=window.setTimeout(()=>{this.paused?x():St()},Re):St()},B=()=>{let w;for(;w=G.nextChunk(N);)N=w,Ot(w);let de=G.nextChunk(H);if(de){if(H&&de.discontinuity){$("Detected discontinuity; restarting playback"),this.paused?x():(T(),this._initPlayerWith(e));return}le(de)}else x()},W=(w,de)=>{if(!d()||!this.sourceBuffer)return;let Ee,Re,St,ur=vt=>{window.setTimeout(()=>{d()&&W(w,de)},vt)};if(this.sourceBuffer.updating)$("Source buffer is updating; delaying appendBuffer"),ur(100);else{let vt=ie(),Vt=I.currentTime;!this.paused&&I.buffered.length>1&&_===Vt&&vt-k>500&&($("Stall suspected; trying to fix"),this._fixupStall()),_!==Vt&&(_=Vt,k=vt);let cr=this._getBufferSizeSec();if(cr>30)$(`Buffered ${cr} seconds; delaying appendBuffer`),ur(2e3);else try{this.sourceBuffer.appendBuffer(w),this.videoPlayStarted?(this.bufferStates.push({ts:vt,buf:cr}),g(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),de&&de()}catch(Jr){if(Jr.name==="QuotaExceededError")$("QuotaExceededError; delaying appendBuffer"),St=this.sourceBuffer.buffered.length,St!==0&&(Ee=this.sourceBuffer.buffered.start(0),Re=Vt,Re-Ee>4&&this.sourceBuffer.remove(Ee,Re-3)),ur(1e3);else throw Jr}}},z=()=>{D&&V&&($([`Appending chunk, sz=${D.byteLength}:`,JSON.stringify(H)]),W(D,function(){D=null,B()}))},Z=w=>e.fragUrlTemplate.replace("%%id%%",w.chunkIdx),le=w=>{d()&&h(Z(w),(de,Ee)=>{if(d()){if(Ee/=1e3,D=de,H=w,n=w.startTS,Ee){let Re=Math.min(10,w.dur/Ee);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*Re:Re}z()}},()=>this._handleNetworkError())},Ot=w=>{d()&&(Bi(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(Z(w),!1)))},gt=w=>{d()&&(e.cachedHeader=w,W(w,()=>{V=!0,z()}))};s=!0,G.seek(w=>{if(d()){if(L=ie(),!w){x();return}N=w,!Mw(y)||w.startTS>y?le(w):(H=w,B())}},y),e.cachedHeader?gt(e.cachedHeader):p(e.headerUrl,gt,()=>this._handleNetworkError())},stop:T,getTimestampSec:()=>n},l}_switchToQuality(e){let{logger:t,playerCallback:r}=this.params,i;e.bitrate!==this.bitrate&&(this.rep&&(i=this.rep.getTimestampSec(),Cs(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,Bi(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(i),r({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return Cs(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,r=d=>{if(!this.autoQuality)return;let p,h,f;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&d<this.bitrate&&(h=this._getBufferSizeSec(),f=d/this.bitrate,h>10&&f>.8||h>15&&f>.5||h>20&&f>.3)){e(`Not switching: buffer=${Math.floor(h)}; bitrate=${this.bitrate}; newRate=${Math.floor(d)}`);return}p=this._selectQuality(d),p?this._switchToQuality(p):e(`Could not find quality by bitrate ${d}`)},s={updateChunk:(p,h)=>{let f=ie();if(this.chunkRateEstimator.addInterval(p,f,h)){let g=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:h,duration:f-p,speed:g}),!0}},get:()=>{let p=this.chunkRateEstimator.getBitRate();return p?p*.85:0}},n=-1/0,o,u=!0,c=()=>{let d=s.get();if(d&&o&&this.autoQuality){if(u&&d>o&&Mu(n)<3e4)return;r(d)}u=this.autoQuality};return{updateChunk:(d,p)=>{let h=s.updateChunk(d,p);return h&&c(),h},notifySwitch:d=>{let p=ie();d<o&&(n=p),o=d}}}_fetchManifest(e,t,r){this.manifestRequest=Or(this.urlResolver.resolve(e,!0),t,r,()=>this._retryCallback()).withJSONResponse().withTimeout(Ds).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;ye(e).then(t=>{t||(this.params.liveOffset.pause(),this.params.videoState.setState("paused"))})}_handleManifestUpdate(e){let{logger:t,playerCallback:r,videoElement:i}=this.params,s=n=>{let o=[];return n!=null&&n.length?(n.forEach((u,c)=>{u.video&&i.canPlayType(u.codecs).replace(/no/,"")&&window.MediaSource.isTypeSupported(u.codecs)&&(u.index=c,o.push(u))}),o.sort(function(u,c){return u.video&&c.video?c.video.height-u.video.height:c.bitrate-u.bitrate}),o):(r({name:"error",type:"empty_manifest"}),[])};this.manifest=s(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),r({name:"manifest",manifest:this.manifest})}_refetchManifest(e){this.destroyed||(this.manifestRefetchTimer&&clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=window.setTimeout(()=>{this._fetchManifest(e,t=>{this.destroyed||(this._handleManifestUpdate(t),this._refetchManifest(e))},()=>this._refetchManifest(e))},Cw))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};import{debounce as Vw,filter as Vb,fromEvent as _w,interval as Nw,isHigher as Fw,isInvariantQuality as qw,isLower as Uw,merge as Hw,Subject as _b,Subscription as jw}from"@vkontakte/videoplayer-shared";var Bu=class{constructor(){this.onDroopedVideoFramesLimit$=new _b;this.subscription=new jw;this.playing=!1;this.tracks=[];this.forceChecker$=new _b;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&&!qw(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&&Fw(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(_w(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=Nw(this.droppedFramesChecker.checkTime).pipe(Vb(()=>this.playing),Vb(()=>{let i=!!this.isForceCheckCounter;return i&&(this.isForceCheckCounter-=1),!i})),t=this.forceChecker$.pipe(Vw(this.droppedFramesChecker.checkTime)),r=Hw(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])=>Uw(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}},Bs=Bu;import{map as Gw,Observable as Ww}from"@vkontakte/videoplayer-shared";import{fromEvent as Yw}from"@vkontakte/videoplayer-shared";var Vi=()=>{var a;return!!((a=window.documentPictureInPicture)!=null&&a.window)||!!document.pictureInPictureElement};var Qw=(a,e)=>new Ww(t=>{if(!window.IntersectionObserver)return;let r={root:null},i=new IntersectionObserver((n,o)=>{n.forEach(u=>t.next(u.isIntersecting||Vi()))},A(A({},r),e));i.observe(a);let s=Yw(document,"visibilitychange").pipe(Gw(n=>!document.hidden||Vi())).subscribe(n=>t.next(n));return()=>{i.unobserve(a),s.unsubscribe}}),Ve=Qw;var ik=["paused","playing","ready"],ak=["paused","playing","ready"],_i=class{constructor(e){this.subscription=new ek;this.videoState=new C("stopped");this.representations$=new Vu([]);this.textTracksManager=new Be;this.droppedFramesManager=new Bs;this.maxSeekBackTime$=new Vu(1/0);this.zeroTime$=new Vu(void 0);this.liveOffset=new ut;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:qb.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{let n=e.manifest,o=[];for(let u of n){let c=(t=u.name)!=null?t:u.index.toString(10),l=(r=kt(u.name))!=null?r:rk(u.video),d=u.bitrate/1e3,p=A({},u.video);if(!l)continue;let h={id:c,quality:l,bitrate:d,size:p};o.push({track:h,representation:u})}this.representations$.next(o),this.params.output.availableVideoTracks$.next(o.map(({track:u})=>u)),((i=this.videoState.getTransition())==null?void 0:i.to)==="manifest_ready"&&this.videoState.setState("manifest_ready");break}case"qualitySwitch":{let n=e.quality,o=(s=this.representations$.getValue().find(({representation:u})=>u===n))==null?void 0:s.track;this.params.output.hostname$.next(new URL(n.headerUrl,this.params.source.url).hostname),Ou(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(ak.includes(e)&&(n||o)){this.prepare();return}if((i==null?void 0:i.to)!=="paused"&&s.state==="requested"&&ik.includes(e)){this.seek(s.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(ae(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(ae(this.params.source.url,u))}return;default:return Nb(e)}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=i=>{e.output.error$.next({id:"DashLiveProvider",category:qb.WTF,message:"DashLiveProvider internal logic error",thrown:i})};Hb(this.videoState.stateChangeStarted$.pipe(Os(i=>({transition:i,type:"start"}))),this.videoState.stateChangeEnded$.pipe(Os(i=>({transition:i,type:"end"})))).subscribe(({transition:i,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(i)}`})}),this.video=me(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(re(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=Se(this.video);this.subscription.add(this.representations$.pipe(Os(i=>i.map(({track:s})=>s)),Ub(i=>!!i.length),Zw()).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(Jw(),Os(i=>-i/1e3)).subscribe(this.params.output.duration$)).add(zw({zeroTime:this.zeroTime$.pipe(Ub(Ou)),position:r.timeUpdate$}).subscribe(({zeroTime:i,position:s})=>this.params.output.liveTime$.next(i+s*1e3),t)).add(et(this.video,this.params.desiredState.isLooped,t)).add(ge(this.video,this.params.desiredState.volume,r.volumeState$,t)).add(r.volumeState$.subscribe(this.params.output.volume$,t)).add(De(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(Ve(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:i}})=>{let s=i&&tk(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 Nb(i.to)}},t)).add(Hb(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(Kw(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),be(this.video)}createLiveDashPlayer(){let e=new Oi({videoElement:this.video,videoState:this.videoState,liveOffset:this.liveOffset,config:{maxParallelRequests:this.params.config.maxParallelRequests,minBuffer:this.params.tuning.live.minBuffer,minBufferSegments:this.params.tuning.live.minBufferSegments,lowLatencyMinBuffer:this.params.tuning.live.lowLatencyMinBuffer,lowLatencyMinBufferSegments:this.params.tuning.live.lowLatencyMinBufferSegments,isLiveCatchUpMode:this.params.tuning.live.isLiveCatchUpMode,manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},playerCallback:this._dashCb,logger:t=>{this.params.dependencies.logger.log({message:String(t),component:"LiveDashPlayer"})}});return e.pause(),e}prepare(){var c,l,d,p,h,f;let e=this.representations$.getValue(),t=(l=(c=this.params.desiredState.videoTrack.getTransition())==null?void 0:c.to)!=null?l:this.params.desiredState.videoTrack.getState(),r=(p=(d=this.params.desiredState.autoVideoTrackSwitching.getTransition())==null?void 0:d.to)!=null?p:this.params.desiredState.autoVideoTrackSwitching.getState(),i=!r&&Ou(t)?t:Rt(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;Fb(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;Fb(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(ae(this.params.source.url,n)),i&&this.dash.pause(),this.liveOffset.resetTo(n,i)}};var jb=_i;var lt=(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 $R,assertNonNullable as LR,debounce as MR,ErrorCategory as pc,filter as fS,filterChanged as hc,fromEvent as CR,isNonNullable as DR,map as mS,merge as cn,observableFrom as BR,observeElementSize as OR,once as bS,Subscription as VR,ValueSubject as _R}from"@vkontakte/videoplayer-shared";var Vs=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}},Vr=class extends Vs{constructor(){super(),this.listeners||Vs.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)}},Ni=class{constructor(){Object.defineProperty(this,"signal",{value:new Vr,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&&(Ni.prototype[Symbol.toStringTag]="AbortController",Vr.prototype[Symbol.toStringTag]="AbortSignal");function _s(a){return a.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof a.Request=="function"&&!a.Request.prototype.hasOwnProperty("signal")||!a.AbortController}function _u(a){typeof a=="function"&&(a={fetch:a});let{fetch:e,Request:t=e.Request,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:i=!1}=a;if(!_s({fetch:e,Request:t,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:i}))return{fetch:e,Request:s};let s=t;(s&&!s.prototype.hasOwnProperty("signal")||i)&&(s=function(c,l){let d;l&&l.signal&&(d=l.signal,delete l.signal);let p=new t(c,l);return d&&Object.defineProperty(p,"signal",{writable:!1,enumerable:!1,configurable:!0,value:d}),p},s.prototype=t.prototype);let n=e;return{fetch:(u,c)=>{let l=s&&s.prototype.isPrototypeOf(u)?u.signal:c?c.signal:void 0;if(l){let d;try{d=new DOMException("Aborted","AbortError")}catch(h){d=new Error("Aborted"),d.name="AbortError"}if(l.aborted)return Promise.reject(d);let p=new Promise((h,f)=>{l.addEventListener("abort",()=>f(d),{once:!0})});return c&&c.signal&&delete c.signal,Promise.race([p,n(u,c)])}return n(u,c)},Request:s}}var Fi=_s({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),Gb=Fi?_u({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,dt=Fi?Gb.fetch:window.fetch,HB=Fi?Gb.Request:window.Request,pt=Fi?Ni:window.AbortController,jB=Fi?Vr:window.AbortSignal;var ag=Xe($i(),1);var ht=()=>window.ManagedMediaSource||window.MediaSource,Ns=()=>{var a,e;return!!(window.ManagedMediaSource&&((e=(a=window.ManagedSourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},Wb=()=>{var a,e;return!!(window.MediaSource&&window.MediaStreamTrack&&((e=(a=window.SourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},Yb=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;import{assertNever as Qs,clientChecker as Ys}from"@vkontakte/videoplayer-shared";var _e=document.createElement("video"),ok='video/mp4; codecs="avc1.42000a,mp4a.40.2"',uk='video/mp4; codecs="hev1.1.6.L93.B0"',sg='video/webm; codecs="vp09.00.10.08"',ng='video/webm; codecs="av01.0.00M.08"',ck='audio/mp4; codecs="mp4a.40.2"',lk='audio/webm; codecs="opus"',Qb,zb,Xt={mms:Ns(),mse:Wb(),hls:!!((Qb=_e.canPlayType)!=null&&Qb.call(_e,"application/x-mpegurl")||(zb=_e.canPlayType)!=null&&zb.call(_e,"vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},Kb,Jb,Te={mp4:!!((Kb=_e.canPlayType)!=null&&Kb.call(_e,"video/mp4")),webm:!!((Jb=_e.canPlayType)!=null&&Jb.call(_e,"video/webm")),cmaf:!0},qs,Xb,Us,Zb,Hs,eg,js,tg,Gs,rg,Ws,ig,Ie={h264:!!((Xb=(qs=ht())==null?void 0:qs.isTypeSupported)!=null&&Xb.call(qs,ok)),h265:!!((Zb=(Us=ht())==null?void 0:Us.isTypeSupported)!=null&&Zb.call(Us,uk)),vp9:!!((eg=(Hs=ht())==null?void 0:Hs.isTypeSupported)!=null&&eg.call(Hs,sg)),av1:!!((tg=(js=ht())==null?void 0:js.isTypeSupported)!=null&&tg.call(js,ng)),aac:!!((rg=(Gs=ht())==null?void 0:Gs.isTypeSupported)!=null&&rg.call(Gs,ck)),opus:!!((ig=(Ws=ht())==null?void 0:Ws.isTypeSupported)!=null&&ig.call(Ws,lk))},_r=(Ie.h264||Ie.h265)&&Ie.aac,Zt,dk=()=>R(void 0,null,function*(){if(!window.navigator.mediaCapabilities)return;let a={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=yield Promise.all([window.navigator.mediaCapabilities.decodingInfo(M(A({},a),{video:M(A({},a.video),{contentType:ng})})),window.navigator.mediaCapabilities.decodingInfo(M(A({},a),{video:M(A({},a.video),{contentType:sg})}))]);Zt={DASH_WEBM_AV1:e,DASH_WEBM:t}});try{dk()}catch(a){console.error(a)}var Nr=Xt.hls&&Te.mp4,og=()=>Object.keys(Ie).filter(a=>Ie[a]),ug=(a,e=!1,t=!1)=>{let r=Xt.mse||Xt.mms&&t;return a.filter(i=>{switch(i){case"DASH_SEP":return r&&Te.mp4&&_r;case"DASH_WEBM":return r&&Te.webm&&Ie.vp9&&Ie.opus;case"DASH_WEBM_AV1":return r&&Te.webm&&Ie.av1&&Ie.opus;case"DASH_STREAMS":return r&&(Te.mp4&&_r||Te.webm&&(Ie.vp9||Ie.av1)&&(Ie.opus||Ie.aac));case"DASH_LIVE":return Xt.mse&&Te.mp4&&_r;case"DASH_LIVE_CMAF":return r&&Te.mp4&&_r&&Te.cmaf;case"DASH_ONDEMAND":return r&&Te.mp4&&_r;case"HLS":case"HLS_ONDEMAND":return Nr||e&&Xt.mse&&Te.mp4&&_r;case"HLS_LIVE":case"HLS_LIVE_CMAF":return Nr;case"MPEG":return Te.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return Xt.webrtc&&Xt.ws&&Ie.h264&&(Te.mp4||Te.webm);default:return Qs(i)}})},Fs=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 Zt?Zt[t].smooth?[t,e]:Zt[e].smooth?[e,t]:[t,e]:[e,t];case"power_efficient":return Zt?Zt[t].powerEfficient?[t,e]:Zt[e].powerEfficient?[e,t]:[t,e]:[e,t];default:Qs(a)}return[e,t]},cg=({webmCodec:a,androidPreferredFormat:e,preferMultiStream:t})=>{let r=[...t?["DASH_STREAMS"]:[],...Fs(a),"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]],i=[...t?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]];if(Ys.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",...Fs(a),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...Fs(a),"MPEG",...i,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...Fs(a),...i,"HLS","HLS_ONDEMAND"];default:Qs(e)}return Nr?[...r,"HLS","HLS_ONDEMAND","MPEG"]:[...r,"HLS","HLS_ONDEMAND","MPEG"]},lg=({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=Ys.isMac&&Ys.isSafari;if(Ys.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:Qs(a)}else Nr&&!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"]},Nu=a=>a?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],dg=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,ag.default)(e.split("."),0);if(t==="opus"||t==="vp09"||t==="av01")return t}return a.values().next().value.split(".").at(0)}};import{ErrorCategory as qi}from"@vkontakte/videoplayer-shared";var pg=a=>{if(!a)return{id:"EmptyResponse",category:qi.PARSER,message:"Empty response"};if(a.length<=2&&a.match(/^\d+$/))return{id:`UVError#${a}`,category:qi.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:qi.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:qi.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:qi.PARSER,message:"Response is valid XML, but parser failed"}};var Ui=(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 cc,assertNonNullable as nr,combine as rn,ErrorCategory as Lt,filter as an,filterChanged as oS,fromEvent as Yr,interval as lc,isNonNullable as uS,map as dc,merge as Qr,Subject as cS,Subscription as lS,tap as IR,throttle as ER,clientChecker as xR,ValueSubject as se,flattenObject as Sa,getTraceSubscriptionMethod as AR}from"@vkontakte/videoplayer-shared";var Gr=Xe($i(),1);var pk=(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)},hk=a=>window.clearTimeout(a),hg=typeof window.requestIdleCallback!="function"||typeof window.cancelIdleCallback!="function",Fu=hg?pk:window.requestIdleCallback,sO=hg?hk:window.cancelIdleCallback;var eS=Xe(ks(),1);import{assertNever as fk,ErrorCategory as fg,clientChecker as qu,Subject as mg}from"@vkontakte/videoplayer-shared";var mk=16,bg=!1;try{bg=qu.isSafari&&!!qu.macVersion&&qu.macVersion<=mk}catch(a){console.error(a)}var Uu=class{constructor(e){this.bufferFull$=new mg;this.error$=new mg;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:fg.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:t})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}append(e,t){return R(this,null,function*(){return t&&t.aborted?!1:new Promise(r=>{let i={operation:"append",data:e,signal:t,callback:r};this.queue.push(i),this.pull()})})}remove(e,t,r){return R(this,null,function*(){return r&&r.aborted?!1:new Promise(i=>{let s={operation:"remove",from:e,to:t,signal:r,callback:i};this.queue.unshift(s),this.pull()})})}abort(e){return R(this,null,function*(){return new Promise(t=>{let r;bg&&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:fg.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:fk(t)}}},gg=Uu;var Hu=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 jr,assertNonNullable as rt,ErrorCategory as ir,fromEvent as ic,getExponentialDelay as ac,isNonNullable as sc,isNullable as Ne,once as pR,Subject as hR,Subscription as fR,ValueSubject as da}from"@vkontakte/videoplayer-shared";var j=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 Fr=class extends j{};var Hi=class extends j{};var ji=class extends j{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 Gi=class extends j{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Wi=class extends j{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Yi=class extends j{constructor(e,t){super(e,t),this.data=this.content}};var X=class extends j{constructor(e,t){super(e,t);let r=this.readUint32();this.version=r>>>24,this.flags=r&16777215}};var er=class extends X{get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e,t){super(e,t),this.segments=[],this.referenceId=this.readUint32(),this.timescale=this.readUint32(),this.earliestPresentationTime32=this.readUint32(),this.firstOffset32=this.readUint32(),this.earliestPresentationTime64=0,this.firstOffset64=0,this.referenceCount=this.readUint32()&65535;for(let r=0;r<this.referenceCount;r++){let i=this.readUint32(),s=i>>>31,n=i<<1>>>1,o=this.readUint32();i=this.readUint32();let u=i>>>28,c=i<<3>>>3;this.segments.push({referenceType:s,referencedSize:n,subsegmentDuration:o,SAPType:u,SAPDeltaTime:c})}}};var Qi=class extends j{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var zi=class extends j{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Ki=class extends X{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 Ji=class extends X{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var Xi=class extends X{constructor(e,t){super(e,t),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}};var Zi=class extends j{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ea=class extends X{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 ta=class extends j{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ra=class extends j{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ia=class extends X{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var aa=class extends j{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var sa=class extends X{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 na=class extends X{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 oa=class extends X{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 gk={ftyp:ji,moov:Gi,moof:Wi,mdat:Yi,sidx:er,trak:Qi,mdia:Zi,mfhd:ia,tkhd:ea,traf:aa,tfhd:sa,tfdt:na,trun:oa,minf:ta,sv3d:zi,st3d:Ki,prhd:Ji,proj:ra,equi:Xi,uuid:Hi,unknown:Fr},tr=class a{constructor(e={}){this.options=A({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=gk[e];return r?new r(t,new a):new Fr(t,new a)}};var qr=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 vk=new TextDecoder("ascii"),yk=a=>vk.decode(new DataView(a.buffer,a.byteOffset+4,4))==="ftyp",Tk=a=>{let e=new er(a,new tr),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})},Ik=(a,e)=>{let r=new tr().parse(a),i=new qr(r),s=i.findAll("moof"),n=e?i.findAll("uuid"):i.findAll("mdat");if(!(n.length&&s.length))return null;let o=s[0],u=n[n.length-1],c=o.source.byteOffset,d=u.source.byteOffset-o.source.byteOffset+u.size;return new DataView(a.buffer,c,d)},Ek=(a,e)=>{let r=new tr().parse(a),s=new qr(r).findAll("traf"),n=s[s.length-1].children.find(d=>d.type==="tfhd"),o=s[s.length-1].children.find(d=>d.type==="tfdt"),u=s[s.length-1].children.find(d=>d.type==="trun"),c=0;return u.sampleDuration.length?c=u.sampleDuration.reduce((d,p)=>d+p,0):c=n.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+c)/e*1e3},xk=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 tr().parse(a),i=new qr(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},Sg={validateData:yk,parseInit:xk,getIndexRange:()=>{},parseSegments:Tk,parseFeedableSegmentChunk:Ik,getSegmentEndTime:Ek};import{assertNonNullable as Gu,isNonNullable as Ig,isNullable as Pk}from"@vkontakte/videoplayer-shared";import{assertNever as Ak}from"@vkontakte/videoplayer-shared";var vg={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"}},yg=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=ua(a,t),i=r in vg,s=i?vg[r].type:"binary",n=a.getUint8(t),o=0;n&128?o=1:n&64?o=2:n&32?o=3:n&16?o=4:n&8?o=5:n&4?o=6:n&2?o=7:n&1&&(o=8);let u=new DataView(a.buffer,a.byteOffset+t+1,o-1),c=n&255>>o,l=ua(u),d=c*Je(2,(o-1)*8)+l,p=t+o,h;return p+d>a.byteLength?h=new DataView(a.buffer,a.byteOffset+p):h=new DataView(a.buffer,a.byteOffset+p,d),{tag:i?r:"0x"+r.toString(16).toUpperCase(),type:s,tagHeaderSize:p,tagSize:p+d,value:h,valueSize:d}},ua=(a,e=a.byteLength)=>{switch(e){case 1:return a.getUint8(0);case 2:return a.getUint16(0);case 3:return a.getUint8(0)*Je(2,16)+a.getUint16(1);case 4:return a.getUint32(0);case 5:return a.getUint8(0)*Je(2,32)+a.getUint32(1);case 6:return a.getUint16(0)*Je(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},We=(a,e)=>{switch(e){case"int":return a.getInt8(0);case"uint":return ua(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:Ak(e)}},rr=(a,e)=>{let t=0;for(;t<a.byteLength;){let r=new DataView(a.buffer,a.byteOffset+t),i=yg(r);if(!e(i))return;i.type==="master"&&rr(i.value,e),t=i.value.byteOffset-a.byteOffset+i.valueSize}},Tg=a=>{if(a.getUint32(0)!==440786851)return!1;let e,t,r,i=yg(a);return rr(i.value,({tag:s,type:n,value:o})=>(s===17143?e=We(o,n):s===17026?t=We(o,n):s===17029&&(r=We(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(r===void 0||r<=2)};var Eg=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],wk=[231,22612,22743,167,171,163,160,175],kk=a=>{let e,t,r,i,s=!1,n=!1,o=!1,u,c,l=!1,d=0;return rr(a,({tag:p,type:h,value:f,valueSize:b})=>{if(p===21419){let g=We(f,h);c=ua(g)}else p!==21420&&(c=void 0);return p===408125543?(e=f.byteOffset,t=f.byteOffset+b):p===357149030?s=!0:p===290298740?n=!0:p===2807729?r=We(f,h):p===17545?i=We(f,h):p===21420&&c===475249515?u=We(f,h):p===374648427?rr(f,({tag:g,type:S,value:T})=>g===30321?(l=We(T,S)===1,!1):!0):s&&n&&Eg.includes(p)&&(o=!0),!o}),Gu(e,"Failed to parse webm Segment start"),Gu(t,"Failed to parse webm Segment end"),Gu(i,"Failed to parse webm Segment duration"),r=r!=null?r:1e6,{segmentStart:Math.round(e/1e9*r*1e3),segmentEnd:Math.round(t/1e9*r*1e3),timeScale:r,segmentDuration:Math.round(i/1e9*r*1e3),cuesSeekPosition:u,is3dVideo:l,stereoMode:d,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},Rk=a=>{if(Pk(a.cuesSeekPosition))return;let e=a.segmentStart+a.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},$k=(a,e)=>{let t=!1,r=!1,i=o=>Ig(o.time)&&Ig(o.position),s=[],n;return rr(a,({tag:o,type:u,value:c})=>{switch(o){case 475249515:t=!0;break;case 187:n&&i(n)&&s.push(n),n={};break;case 179:n&&(n.time=We(c,u));break;case 183:break;case 241:n&&(n.position=We(c,u));break;default:t&&Eg.includes(o)&&(r=!0)}return!(t&&r)}),n&&i(n)&&s.push(n),s.map((o,u)=>{let{time:c,position:l}=o,d=s[u+1];return{status:"none",time:{from:c,to:d?d.time:e.segmentDuration},byte:{from:e.segmentStart+l,to:d?e.segmentStart+d.position-1:e.segmentEnd-1}}})},Lk=a=>{let e=0,t=!1;try{rr(a,r=>r.tag===524531317?r.tagSize<=a.byteLength?(e=r.tagSize,!1):(e+=r.tagHeaderSize,!0):wk.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},xg={validateData:Tg,parseInit:kk,getIndexRange:Rk,parseSegments:$k,parseFeedableSegmentChunk:Lk};var Ur=a=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(a);if(e){let[,t,r]=e;if(t==="audio"||t==="video")switch(r){case"webm":return xg;case"mp4":return Sg}}throw new ReferenceError(`Unsupported mime type ${a}`)};var Xu=Xe(Wg(),1);var Ju=a=>{let e=a.split("."),[t,...r]=e;if(!t)return!1;switch(t){case"av01":{let[i,s,n]=r;return!!(n&&parseInt(n,10)>8)}case"vp09":{let[i,s,n]=r;return!!(i&&parseInt(i,10)>=2&&n&&parseInt(n,10)>8)}case"avc1":{let i=r[0];if(!i||i.length!==6)return!1;let[s,n]=i.toUpperCase(),o=s+n;return["6E","7A","F4"].includes(o)}}return!1};import{isNonNullable as Qg,isNullable as zg}from"@vkontakte/videoplayer-shared";var Yg=a=>{if(a.includes("/")){let e=a.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(a)};var Kg=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},ft=(a,e)=>{let t=a;t=(0,Xu.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,Xu.default)(t,n,(o,u)=>zg(s)?o:zg(u)?s:s.padStart(parseInt(u,10),"0"))}return t},Jg=(a,e)=>{var y,I,$,G,V,D,H,N,L,F,_,k,x,B,W,z,Z,le,Ot,gt,w,de,Ee,Re,St,ur,vt,Vt,cr,Jr,Rc,$c,Lc,Mc,Cc,Dc,Bc,Oc,Vc,_c,Nc,Fc,qc,Uc,Hc,jc,Gc,Wc,Yc,Qc,zc,Kc,Jc,Xc,Zc,el,tl,rl,il,al;let r=new DOMParser().parseFromString(a,"application/xml"),i={video:[],audio:[],text:[]},s=r.children[0],n=s.getElementsByTagName("Period")[0],o=($=(I=(y=s.querySelector("BaseURL"))==null?void 0:y.textContent)==null?void 0:I.trim())!=null?$:"",u=n.children,c=s.getAttribute("type")==="dynamic",l=s.getAttribute("availabilityStartTime"),d=l?new Date(l).getTime():void 0,p,h=s.getAttribute("mediaPresentationDuration"),f=n.getAttribute("duration"),b=s.getElementsByTagName("vk:Attrs")[0],g=b==null?void 0:b.getElementsByTagName("vk:XPlaybackDuration")[0].textContent;if(h)p=Kg(h);else if(f){let pe=Kg(f);Qg(pe)&&(p=pe)}else g&&(p=parseInt(g,10));let S=0,T=(V=(G=s.getAttribute("profiles"))==null?void 0:G.split(","))!=null?V:[];for(let pe of u){let ov=(D=pe.getAttribute("id"))!=null?D:"id"+(S++).toString(10),Xr=(H=pe.getAttribute("mimeType"))!=null?H:"",xn=(N=pe.getAttribute("codecs"))!=null?N:"",An=(L=pe.getAttribute("contentType"))!=null?L:Xr==null?void 0:Xr.split("/")[0],uv=(_=(F=pe.getAttribute("profiles"))==null?void 0:F.split(","))!=null?_:[],cv=(k=pe.getAttribute("lang"))!=null?k:void 0,lv=(W=(B=(x=pe.querySelector("Label"))==null?void 0:x.textContent)==null?void 0:B.trim())!=null?W:void 0,dv=pe.querySelectorAll("Representation"),pv=pe.querySelector("SegmentTemplate"),hv=(Z=(z=pe.querySelector("Role"))==null?void 0:z.getAttribute("value"))!=null?Z:void 0,Zr=An,ee={id:ov,language:cv,isDefault:hv==="main",label:lv,codecs:xn,hdr:Zr==="video"&&Ju(xn),mime:Xr,representations:[]};for(let Y of dv){let fv=(le=Y.getAttribute("lang"))!=null?le:void 0,mv=(Ot=Y.getAttribute("label"))!=null?Ot:void 0,bv=(de=(w=(gt=Y.querySelector("BaseURL"))==null?void 0:gt.textContent)==null?void 0:w.trim())!=null?de:"",Ca=new URL(bv||o,e).toString(),lr=(Ee=Y.getAttribute("mimeType"))!=null?Ee:Xr,Da=(St=(Re=Y.getAttribute("codecs"))!=null?Re:xn)!=null?St:"",Ba;if(An==="text"){let _t=Y.getAttribute("id")||"",Oa=_t.includes("_auto"),Nt=Y.querySelector("SegmentTemplate");if(Nt){let dr={representationId:(ur=Y.getAttribute("id"))!=null?ur:void 0,bandwidth:(vt=Y.getAttribute("bandwidth"))!=null?vt:void 0},Va=parseInt((Vt=Y.getAttribute("bandwidth"))!=null?Vt:"",10)/1e3,_a=(Jr=parseInt((cr=Nt.getAttribute("startNumber"))!=null?cr:"",10))!=null?Jr:1,pr=parseInt((Rc=Nt.getAttribute("timescale"))!=null?Rc:"",10),Pn=($c=Nt.querySelectorAll("SegmentTimeline S"))!=null?$c:[],hr=Nt.getAttribute("media");if(!hr)throw new ReferenceError("No media attribute in SegmentTemplate");let Na=[],Fa=0,qa="",fr=0,ei=_a,ne=0;for(let Fe of Pn){let Ft=parseInt((Lc=Fe.getAttribute("d"))!=null?Lc:"",10),$e=parseInt((Mc=Fe.getAttribute("r"))!=null?Mc:"",10)||0,yt=parseInt((Cc=Fe.getAttribute("t"))!=null?Cc:"",10);ne=Number.isFinite(yt)?yt:ne;let qt=Ft/pr*1e3,Tt=ne/pr*1e3;for(let ze=0;ze<$e+1;ze++){let It=ft(hr,M(A({},dr),{segmentNumber:ei.toString(10),segmentTime:(ne+ze*Ft).toString(10)})),mr=(Tt!=null?Tt:0)+ze*qt,ri=mr+qt;ei++,Na.push({time:{from:mr,to:ri},url:It})}ne+=($e+1)*Ft,Fa+=($e+1)*qt}fr=ne/pr*1e3,qa=ft(hr,M(A({},dr),{segmentNumber:ei.toString(10),segmentTime:ne.toString(10)}));let ti={time:{from:fr,to:1/0},url:qa},it={type:"template",baseUrl:Ca,segmentTemplateUrl:hr,initUrl:"",totalSegmentsDurationMs:Fa,segments:Na,nextSegmentBeyondManifest:ti,timescale:pr};Ba={id:_t,kind:"text",segmentReference:it,profiles:[],duration:p,bitrate:Va,mime:"",codecs:"",width:0,height:0,isAuto:Oa}}else Ba={id:Y.getAttribute("id")||"",isAuto:Oa,kind:"text",url:Ca}}else{let _t=(Bc=(Dc=Y.getAttribute("contentType"))!=null?Dc:lr==null?void 0:lr.split("/")[0])!=null?Bc:An,Oa=(Vc=(Oc=pe.getAttribute("profiles"))==null?void 0:Oc.split(","))!=null?Vc:[],Nt=parseInt((_c=Y.getAttribute("width"))!=null?_c:"",10),dr=parseInt((Nc=Y.getAttribute("height"))!=null?Nc:"",10),Va=parseInt((Fc=Y.getAttribute("bandwidth"))!=null?Fc:"",10)/1e3,_a=(qc=Y.getAttribute("frameRate"))!=null?qc:"",pr=(Uc=Y.getAttribute("quality"))!=null?Uc:void 0,Pn=_a?Yg(_a):void 0,hr=(Hc=Y.getAttribute("id"))!=null?Hc:"id"+(S++).toString(10),Na=_t==="video"?`${dr}p`:_t==="audio"?`${Va}Kbps`:Da,Fa=`${hr}@${Na}`,qa=[...T,...uv,...Oa],fr,ei=Y.querySelector("SegmentBase"),ne=(jc=Y.querySelector("SegmentTemplate"))!=null?jc:pv;if(ei){let it=(Wc=(Gc=Y.querySelector("SegmentBase Initialization"))==null?void 0:Gc.getAttribute("range"))!=null?Wc:"",[Fe,Ft]=it.split("-").map(It=>parseInt(It,10)),$e={from:Fe,to:Ft},yt=(Yc=Y.querySelector("SegmentBase"))==null?void 0:Yc.getAttribute("indexRange"),[qt,Tt]=yt?yt.split("-").map(It=>parseInt(It,10)):[],ze=yt?{from:qt,to:Tt}:void 0;fr={type:"byteRange",url:Ca,initRange:$e,indexRange:ze}}else if(ne){let it={representationId:(Qc=Y.getAttribute("id"))!=null?Qc:void 0,bandwidth:(zc=Y.getAttribute("bandwidth"))!=null?zc:void 0},Fe=parseInt((Kc=ne.getAttribute("timescale"))!=null?Kc:"",10),Ft=(Jc=ne.getAttribute("initialization"))!=null?Jc:"",$e=ne.getAttribute("media"),yt=(Zc=parseInt((Xc=ne.getAttribute("startNumber"))!=null?Xc:"",10))!=null?Zc:1,qt=ft(Ft,it);if(!$e)throw new ReferenceError("No media attribute in SegmentTemplate");let Tt=(el=ne.querySelectorAll("SegmentTimeline S"))!=null?el:[],ze=[],It=0,mr="",ri=0;if(Tt.length){let Ua=yt,qe=0;for(let br of Tt){let Ke=parseInt((tl=br.getAttribute("d"))!=null?tl:"",10),Ut=parseInt((rl=br.getAttribute("r"))!=null?rl:"",10)||0,Ha=parseInt((il=br.getAttribute("t"))!=null?il:"",10);qe=Number.isFinite(Ha)?Ha:qe;let wn=Ke/Fe*1e3,kn=qe/Fe*1e3;for(let ja=0;ja<Ut+1;ja++){let Sv=ft($e,M(A({},it),{segmentNumber:Ua.toString(10),segmentTime:(qe+ja*Ke).toString(10)})),sl=(kn!=null?kn:0)+ja*wn,vv=sl+wn;Ua++,ze.push({time:{from:sl,to:vv},url:Sv})}qe+=(Ut+1)*Ke,It+=(Ut+1)*wn}ri=qe/Fe*1e3,mr=ft($e,M(A({},it),{segmentNumber:Ua.toString(10),segmentTime:qe.toString(10)}))}else if(Qg(p)){let qe=parseInt((al=ne.getAttribute("duration"))!=null?al:"",10)/Fe*1e3,br=Math.ceil(p/qe),Ke=0;for(let Ut=1;Ut<br;Ut++){let Ha=ft($e,M(A({},it),{segmentNumber:Ut.toString(10),segmentTime:Ke.toString(10)}));ze.push({time:{from:Ke,to:Ke+qe},url:Ha}),Ke+=qe}ri=Ke,mr=ft($e,M(A({},it),{segmentNumber:br.toString(10),segmentTime:Ke.toString(10)}))}let gv={time:{from:ri,to:1/0},url:mr};fr={type:"template",baseUrl:Ca,segmentTemplateUrl:$e,initUrl:qt,totalSegmentsDurationMs:It,segments:ze,nextSegmentBeyondManifest:gv,timescale:Fe}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!_t||!lr)continue;let ti={video:"video",audio:"audio",text:"text"}[_t];if(!ti)continue;Zr||(Zr=ti),Ba={id:Fa,kind:ti,segmentReference:fr,profiles:qa,duration:p,bitrate:Va,mime:lr,codecs:Da,width:Nt,height:dr,fps:Pn,quality:pr}}ee.language||(ee.language=fv),ee.label||(ee.label=mv),ee.mime||(ee.mime=lr),ee.codecs||(ee.codecs=Da),ee.hdr||(ee.hdr=Zr==="video"&&Ju(Da)),ee.representations.push(Ba)}Zr&&i[Zr].push(ee)}return{dynamic:c,liveAvailabilityStartTime:d,duration:p,streams:i}};var ca=Xe($i(),1);import{videoSizeToQuality as dR}from"@vkontakte/videoplayer-shared";var Xg=({id:a,width:e,height:t,bitrate:r,fps:i,quality:s})=>{var o;let n=(o=s?kt(s):void 0)!=null?o:dR({width:e,height:t});return n&&{id:a,quality:n,bitrate:r,size:{width:e,height:t},fps:i}},Zg=({id:a,bitrate:e})=>({id:a,bitrate:e}),zs=(a,e,t)=>{var i;let r=e.indexOf(a);return(i=(0,ca.default)(t,Math.round(t.length*r/e.length)))!=null?i:(0,ca.default)(t,-1)},Ks=({language:a,label:e},{id:t,url:r,isAuto:i})=>({id:t,url:r,isAuto:i,type:"internal",language:a,label:e}),tc=({id:a,language:e,label:t,codecs:r,isDefault:i})=>({id:a,language:e,label:t,codec:(0,ca.default)(r.split("."),0),isDefault:i}),rc=({id:a,language:e,label:t,hdr:r,codecs:i})=>({id:a,language:e,hdr:r,label:t,codec:(0,ca.default)(i.split("."),0)}),Js=a=>"url"in a,Ye=a=>a.type==="template",la=a=>a instanceof DOMException&&(a.name==="AbortError"||a.code===20);var pa=class{constructor(e,t,r,{fetcher:i,tuning:s,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:c}){this.currentSegmentLength$=new da(0);this.onLastSegment$=new da(!1);this.fullyBuffered$=new da(!1);this.playingRepresentation$=new da(void 0);this.playingRepresentationInit$=new da(void 0);this.error$=new hR;this.gaps=[];this.subscription=new fR;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new pt;this.destroyAbortController=new pt;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=jr(this.destroyAbortController.signal,function(e){return te(this,null,function*(){let t=this.representations.get(e);rt(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new gg(this.sourceBuffer),this.subscription.add(ic(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let o,u=this.mediaSource.readyState;u!=="open"&&(o={id:`SegmentEjection_source_${u}`,category:ir.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o!=null||(o={id:"SegmentEjection",category:ir.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),this.error$.next(o)})),this.subscription.add(ic(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:ir.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,Hu(this.sourceBuffer.buffered)*.8);if(this.bufferLimit=u,this.tuning.useNewPruneBufferStrategy){let c=lt(this.sourceBuffer.buffered,o),l=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBufferNew(o,n*2,c<l)}else this.pruneBufferOld(o,n)})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(n=>this.error$.next(n))),yield this.loadInit(t,"high",!0);let r=this.initData.get(t.id),i=this.segments.get(t.id),s=this.parsedInitData.get(t.id);rt(r,"No init buffer for starting representation"),rt(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=jr(this.destroyAbortController.signal,function(e,t=!1){return te(this,null,function*(){if(e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let r=this.representations.get(e);rt(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),rt(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();sc(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=jr(this.destroyAbortController.signal,function(e){return te(this,null,function*(){var u,c;let t=(u=e==null?void 0:e.flatMap(l=>l.representations))!=null?u:[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let l of this.representations.keys()){let d=t.find(f=>f.id===l);d&&this.representations.set(l,d);let p=this.representations.get(l);if(!p||!Ye(p.segmentReference))return;let h=this.getActualLiveStartingSegments(p.segmentReference);this.segments.set(p.id,h)}let r=(c=this.switchingToRepresentationId)!=null?c:this.downloadingRepresentationId,i=this.representations.get(r);rt(i);let s=this.segments.get(r);rt(s,"No segments for starting representation");let n=this.initData.get(r);if(rt(n,"No init buffer for starting representation"),!(n instanceof ArrayBuffer))return;let o=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,this.abort(),o&&(yield this.sourceBufferTaskQueue.remove(o.from*1e3,o.to*1e3,this.destroyAbortController.signal)),this.searchGaps(s,i),yield this.sourceBufferTaskQueue.append(n,this.destroyAbortController.signal),this.isSeekingLive=!1})}.bind(this));this.fetcher=i,this.tuning=s,this.compatibilityMode=u,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=o,this.isLive=!!(c!=null&&c.dynamic),this.resetAccumulateBufferAfterStall(),this.startAccumulateBuffer(),this.initData=new Map(r.map(l=>[l.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(r.map(l=>[l.id,l])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}abort(){for(let e of this.activeSegments)this.abortSegment(e.segment);this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new pt,this.abortBuffer()}maintain(e=this.getCurrentPosition()){var c,l;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(rt(t,`No such representation ${this.downloadingRepresentationId}`),!r)return;let i=r.find(d=>e>=d.time.from&&e<d.time.to);this.currentSegmentLength$.next(((c=i==null?void 0:i.time.to)!=null?c:0)-((l=i==null?void 0:i.time.from)!=null?l:0));let s=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){let p=lt(this.sourceBuffer.buffered,e),h=i?i.time.to+100:-1/0;i&&i.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&p>=i.time.to-e+100&&(s=h)}if(isFinite(this.bufferLimit)&&Hu(this.sourceBuffer.buffered)>=this.bufferLimit){let d=lt(this.sourceBuffer.buffered,e),p=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,d<p);return}let o=[];if(!this.activeSegments.size&&(o=this.selectForwardBufferSegments(r,t.segmentReference.type,s),o.length)){let d="auto";if(this.tuning.dash.useFetchPriorityHints&&i)if(o.includes(i))d="high";else{let p=(0,Gr.default)(o,0);p&&p.time.from-i.time.to>=this.forwardBufferTarget/2&&(d="low")}this.loadSegments(o,t,d)}(!this.preloadOnly&&!this.allInitsLoaded&&i&&i.status==="fed"&&!o.length&&lt(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let u=(0,Gr.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;sc(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||!Ye(o.segmentReference))return;let u=o.segmentReference.segments.map(p=>M(A({},p),{status:"none",size:void 0})),c=(i=this.segments.get(o.id))!=null?i:[],l=(n=(s=(0,Gr.default)(c,-1))==null?void 0:s.time.to)!=null?n:0,d=u==null?void 0:u.findIndex(p=>Math.floor(l)>=Math.floor(p.time.from)&&Math.floor(l)<=Math.floor(p.time.to));if(d===-1){this.liveUpdateSegmentIndex=0;let p=this.getActualLiveStartingSegments(o.segmentReference);this.segments.set(o.id,p)}else{let p=u.slice(d+1);this.segments.set(o.id,[...c,...p])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;rt(e);let t=this.segments.get(e);if(t!=null&&t.length){let r=t[t.length-1];this.updateLowLatencyLiveIfNeeded(r)}}startAccumulateBuffer(){this.bufferAccumulation.enabled=!0}resetAccumulateBufferAfterStall(){this.bufferAccumulation={enabled:!1,targetBufferSizeMs:this.tuning.accumulationBufferStallSizeMs,accumulatedBufferSizeMs:0,accumulated:[]}}updateLowLatencyLiveIfNeeded(e){var t;for(let r of this.representations.values()){let i=r.segmentReference;if(!Ye(i))return;let s=(t=this.segments.get(r.id))!=null?t:[],n=s.find(u=>Math.floor(u.time.from)===Math.floor(e.time.from));if(n&&!isFinite(n.time.to)&&(n.time.to=e.time.to),!!!s.find(u=>Math.floor(u.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let u=Math.round(e.time.to*i.timescale/1e3).toString(10),c=ft(i.segmentTemplateUrl,{segmentTime:u});s.push({status:"none",time:{from:e.time.to,to:1/0},url:c})}}}findSegmentStartTime(e){var s,n,o;let t=(n=(s=this.switchingToRepresentationId)!=null?s:this.downloadingRepresentationId)!=null?n:this.playingRepresentationId;if(!t)return;let r=this.segments.get(t);if(!r)return;let i=r.find(u=>u.time.from<=e&&u.time.to>=e);return(o=i==null?void 0:i.time.from)!=null?o:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){var e;if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),(e=this.sourceBufferTaskQueue)==null||e.destroy(),this.gapDetectionIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer){this.mediaSource.readyState==="open"&&this.abortBuffer();try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(t){if(!(t instanceof DOMException&&t.name==="NotFoundError"))throw t}}this.sourceBuffer=null,this.downloadAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,r){return this.isLive?this.selectForwardBufferSegmentsLive(e,r):this.selectForwardBufferSegmentsRecord(e,t,r)}selectForwardBufferSegmentsLive(e,t){let r=e.findIndex(i=>t>=i.time.from&&t<i.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=r),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,r){let i=e.findIndex(({status:d,time:{from:p,to:h}},f)=>{let b=p<=r&&h>=r,g=p>r||b||f===0&&r===0,S=Math.min(this.forwardBufferTarget,this.bufferLimit),T=this.preloadOnly&&p<=r+S||h<=r+S;return(d==="none"||d==="partially_ejected"&&g&&T&&this.sourceBuffer&&!Ui(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=[],c=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,l=this.preloadOnly?this.forwardBufferTarget:0;for(let d=i;d<s.length&&(n<=c||o<=l);d++){let p=s[d];if(n+=p.byte.to+1-p.byte.from,o+=p.time.to+1-p.time.from,p.status==="none"||p.status==="partially_ejected")u.push(p);else break}return u}loadSegments(e,t,r="auto"){return R(this,null,function*(){t.segmentReference.type==="template"?yield this.loadTemplateSegment(e[0],t,r):yield this.loadByteRangeSegments(e,t,r)})}loadTemplateSegment(e,t,r="auto"){return R(this,null,function*(){e.status="downloading";let i={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(i);let{range:s,url:n,signal:o,onProgress:u,onProgressTasks:c}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(yield jr(o,function(){return te(this,null,function*(){let l=ac(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(d=>setTimeout(d,l))})}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let l=yield this.fetcher.fetch(n,{range:s,signal:o,onProgress:u,priority:r,isLowLatency:this.isActiveLowLatency()});if(!l)return;let d=new DataView(l);if(!isFinite(i.segment.time.to)){let p=t.segmentReference.timescale,h=Ur(t.mime);i.segment.time.to=h.getSegmentEndTime(d,p)}u&&i.feedingBytes&&c?yield Promise.all(c):yield this.sourceBufferTaskQueue.append(d,o),i.segment.status="downloaded",this.onSegmentFullyAppended(i,t.id),this.failedDownloads=0}catch(l){this.abortActiveSegments([e]),la(l)||this.failedDownloads++}})}loadByteRangeSegments(e,t,r="auto"){return R(this,null,function*(){if(!e.length)return;for(let u of e)u.status="downloading",this.activeSegments.add({segment:u,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:i,url:s,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(yield jr(n,function(){return te(this,null,function*(){let u=ac(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(c,u),ic(window,"online").pipe(pR()).subscribe(()=>{c(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{yield this.fetcher.fetch(s,{range:i,onProgress:o,signal:n,priority:r}),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),la(u)||this.failedDownloads++}})}prepareByteRangeFetchSegmentParams(e,t){if(Ye(t.segmentReference))throw new Error("Representation is not byte range type");let r=t.segmentReference.url,i={from:(0,Gr.default)(e,0).byte.from,to:(0,Gr.default)(e,-1).byte.to},{signal:s}=this.downloadAbortController;return{url:r,range:i,signal:s,onProgress:(o,u)=>{if(!s.aborted)try{this.onSomeByteRangesDataLoaded({dataView:o,loaded:u,signal:s,onSegmentAppendFailed:()=>this.abort(),globalFrom:i?i.from:0,representationId:t.id})}catch(c){this.error$.next({id:"SegmentFeeding",category:ir.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:c})}}}}prepareTemplateFetchSegmentParams(e,t){if(!Ye(t.segmentReference))throw new Error("Representation is not template type");let r=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&r.searchParams.set("low-latency","yes");let i=r.toString(),{signal:s}=this.downloadAbortController,n=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(c,l)=>{if(!s.aborted)try{let d=this.onSomeTemplateDataLoaded({dataView:c,loaded:l,signal:s,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(d)}catch(d){this.error$.next({id:"SegmentFeeding",category:ir.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:d})}}:void 0;return{url:i,signal:s,onProgress:u,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)e.includes(t.segment)&&this.abortSegment(t.segment)}onSomeTemplateDataLoaded(n){return R(this,arguments,function*({dataView:e,representationId:t,loaded:r,onSegmentAppendFailed:i,signal:s}){if(!this.activeSegments.size)return;let o=this.representations.get(t);if(o)for(let u of this.activeSegments){let{segment:c}=u;if(u.representationId===t){if(s.aborted){i();continue}if(u.loadedBytes=r,u.loadedBytes>u.feedingBytes){let l=new DataView(e.buffer,e.byteOffset+u.feedingBytes,u.loadedBytes-u.feedingBytes),d=Ur(o.mime).parseFeedableSegmentChunk(l,this.isLive);d!=null&&d.byteLength&&(c.status="partially_fed",u.feedingBytes+=d.byteLength,yield this.sourceBufferTaskQueue.append(d),u.fedBytes+=d.byteLength)}}}})}onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:r,loaded:i,signal:s,onSegmentAppendFailed:n}){let o={dataView:e,representationId:t,globalFrom:r,loaded:i,signal:s,onSegmentAppendFailed:n};return this.tuning.useNewPartialSegmentFeeding?this.onSomeByteRangesDataLoadedNew(o):this.onSomeByteRangesDataLoadedOld(o)}onSomeByteRangesDataLoadedOld({dataView:e,representationId:t,globalFrom:r,loaded:i,signal:s,onSegmentAppendFailed:n}){if(!this.activeSegments.size)return;let o=this.representations.get(t);if(!o)return;let u=o.segmentReference.type,c=e.byteLength;for(let l of this.activeSegments){let{segment:d}=l,p=u==="byteRange",h=p?d.byte.to-d.byte.from+1:c;if(l.representationId!==t||!(!p||d.byte.from>=r&&d.byte.to<r+e.byteLength))continue;if(s.aborted){n();continue}let b=p?d.byte.from-r:0,g=p?d.byte.to-r:e.byteLength,S=b<i,T=g<=i;if(d.status==="downloading"&&S&&T){d.status="downloaded";let v=new DataView(e.buffer,e.byteOffset+b,h),y=this.getCurrentPosition();sc(y)&&(this.bufferAccumulation.accumulatedBufferSizeMs=d.time.to-y,this.bufferAccumulation.accumulated.push({segmentView:v,segmentProgress:l}),this.activeSegments.delete(l));let I=({segmentView:$,segmentProgress:G})=>this.sourceBufferTaskQueue.append($,s).then(V=>V&&!s.aborted?this.onSegmentFullyAppended(G,t):n());this.bufferAccumulation.enabled&&this.bufferAccumulation.targetBufferSizeMs<this.bufferAccumulation.accumulatedBufferSizeMs?(this.bufferAccumulation.accumulated.forEach(I),this.resetAccumulateBufferAfterStall()):(!this.bufferAccumulation.enabled||!this.bufferAccumulation.targetBufferSizeMs||Ne(y))&&(I({segmentView:v,segmentProgress:l}),this.resetAccumulateBufferAfterStall())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&S&&!T&&(l.loadedBytes=Math.min(h,i-b),l.loadedBytes>l.feedingBytes)){let v=new DataView(e.buffer,e.byteOffset+b+l.feedingBytes,l.loadedBytes-l.feedingBytes),y=l.loadedBytes===h?v:Ur(o.mime).parseFeedableSegmentChunk(v);y!=null&&y.byteLength&&(d.status="partially_fed",l.feedingBytes+=y.byteLength,this.sourceBufferTaskQueue.append(y,s).then(I=>{if(s.aborted)n();else if(I)l.fedBytes+=y.byteLength,l.fedBytes===h&&this.onSegmentFullyAppended(l,t);else{if(l.feedingBytes<h)return;n()}}))}}}onSomeByteRangesDataLoadedNew(o){return R(this,arguments,function*({dataView:e,representationId:t,globalFrom:r,loaded:i,signal:s,onSegmentAppendFailed:n}){if(!this.activeSegments.size)return;let u=this.representations.get(t);if(u)for(let c of this.activeSegments){let{segment:l}=c;if(c.representationId!==t)continue;if(s.aborted){n();continue}let d=l.byte.from-r,p=l.byte.to-r,h=p-d+1,f=d<i,b=p<=i;if(f){if(l.status==="downloading"&&b){l.status="downloaded";let g=new DataView(e.buffer,e.byteOffset+d,h);(yield this.sourceBufferTaskQueue.append(g,s))&&!s.aborted?this.onSegmentFullyAppended(c,t):n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(l.status==="downloading"||l.status==="partially_fed")&&(c.loadedBytes=Math.min(h,i-d),c.loadedBytes>c.feedingBytes)){let g=new DataView(e.buffer,e.byteOffset+d+c.feedingBytes,c.loadedBytes-c.feedingBytes),S=c.loadedBytes===h?g:Ur(u.mime).parseFeedableSegmentChunk(g);S!=null&&S.byteLength&&(l.status="partially_fed",c.feedingBytes+=S.byteLength,(yield this.sourceBufferTaskQueue.append(S,s))&&!s.aborted?(c.fedBytes+=S.byteLength,c.fedBytes===h&&this.onSegmentFullyAppended(c,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",Js(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=Fu(()=>(0,eS.default)(this.loadInit(r,"low",!1),()=>this.initLoadIdleCallback=null)))}loadInit(e,t="auto",r=!1){return R(this,null,function*(){let i=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!r&&this.failedDownloads>0?jr(this.destroyAbortController.signal,function(){return te(this,null,function*(){let o=ac(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))})}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,Ur(e.mime),i)).then(o=>R(this,null,function*(){if(!o)return;let{init:u,dataView:c,segments:l}=o,d=c.buffer.slice(c.byteOffset,c.byteOffset+c.byteLength);this.initData.set(e.id,d);let p=l;this.isLive&&Ye(e.segmentReference)&&(p=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,p),u&&this.parsedInitData.set(e.id,u)})).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),r&&this.error$.next({id:"LoadInits",category:ir.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n})}dropBuffer(){return R(this,null,function*(){for(let e of this.segments.values())for(let t of e)t.status="none";yield this.pruneBuffer(0,1/0,!0)})}pruneBuffer(e,t,r=!1){return R(this,null,function*(){return this.tuning.useNewPruneBufferStrategy?this.pruneBufferNew(e,t,r):this.pruneBufferOld(e,t,r)})}pruneBufferNew(e,t,r=!1){return R(this,null,function*(){if(!this.sourceBuffer||!this.playingRepresentationId||Ne(e)||this.sourceBuffer.updating)return!1;let i=[],s=0,n=u=>{u.sort((l,d)=>l.from-d.from);let c=[u[0]];for(let l=1;l<u.length;l++){let{from:d,to:p}=u[l],h=c[c.length-1];h.to>=d?h.to=Math.max(h.to,p):c.push(u[l])}return c},o=u=>{var l;if(s>=t)return i;i.push(u.time),i=n(i);let c=Js(u)?(l=u.size)!=null?l:0:u.byte.to-u.byte.from;s+=c};for(let u of this.segments.values())for(let c of u){let l=c.time.to<=e-this.tuning.dash.bufferPruningSafeZone,d=c.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(l||d)&&c.status==="fed"&&o(c)}for(let u=0;u<this.sourceBuffer.buffered.length;u++){let c=this.sourceBuffer.buffered.start(u)*1e3,l=this.sourceBuffer.buffered.end(u)*1e3,d=0;for(let p of this.segments.values())for(let h of p)h.status==="none"&&Math.round(h.time.from)<=Math.round(c)&&Math.round(h.time.to)>=Math.round(l)&&d++;if(d===this.segments.size){let p={time:{from:c,to:l},url:"",status:"none"};o(p)}}if(i.length&&r){let u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let c of this.segments.values())for(let l of c)l.time.from>=e+u&&l.status==="fed"&&o(l)}return i.length?(yield Promise.all(i.map(c=>this.sourceBufferTaskQueue.remove(c.from,c.to)))).reduce((c,l)=>c||l,!1):!1})}pruneBufferOld(e,t,r=!1){return R(this,null,function*(){if(!this.sourceBuffer||!this.playingRepresentationId||Ne(e)||this.sourceBuffer.updating)return!1;let i=0,s=1/0,n=-1/0,o=!1,u=c=>{var d;s=Math.min(s,c.time.from),n=Math.max(n,c.time.to);let l=Js(c)?(d=c.size)!=null?d:0:c.byte.to-c.byte.from;i+=l};for(let c of this.segments.values())for(let l of c){if(l.time.to>=e-this.tuning.dash.bufferPruningSafeZone||i>=t)break;l.status==="fed"&&u(l)}if(o=isFinite(s)&&isFinite(n),!o){i=0,s=1/0,n=-1/0;for(let c of this.segments.values())for(let l of c){if(l.time.from<e+Math.min(this.forwardBufferTarget,this.bufferLimit)||i>t)break;l.status==="fed"&&u(l)}}if(o=isFinite(s)&&isFinite(n),!o)for(let c=0;c<this.sourceBuffer.buffered.length;c++){let l=this.sourceBuffer.buffered.start(c)*1e3,d=this.sourceBuffer.buffered.end(c)*1e3;for(let p of this.segments.values())for(let h of p)if(h.status==="none"&&Math.round(h.time.from)<=Math.round(l)&&Math.round(h.time.to)>=Math.round(d)){s=l,n=d;break}}if(o=isFinite(s)&&isFinite(n),!o&&r){i=0,s=1/0,n=-1/0;let c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let l of this.segments.values())for(let d of l)d.time.from>e+c&&d.status==="fed"&&u(d)}return o=isFinite(s)&&isFinite(n),o?this.sourceBufferTaskQueue.remove(s,n):!1})}abortBuffer(){if(!this.sourceBuffer||this.mediaSource.readyState!=="open")return;let e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;this.sourceBufferTaskQueue.abort(t)}getDebugBufferState(){if(!(!this.sourceBuffer||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}detectGaps(e,t){if(this.sourceBuffer)for(let r of t){let i={representation:e,from:r.time.from,to:r.time.to};for(let s=0;s<this.sourceBuffer.buffered.length;s++){let n=this.sourceBuffer.buffered.start(s)*1e3,o=this.sourceBuffer.buffered.end(s)*1e3;if(!(o<=r.time.from||n>=r.time.to)){if(n<=r.time.from&&o>=r.time.to){i=void 0;break}o>r.time.from&&o<r.time.to&&(i.from=o),n<r.time.to&&n>r.time.from&&(i.to=n)}}i&&i.to-i.from>1&&!this.gaps.some(s=>i&&s.from===i.from&&s.to===i.to)&&this.gaps.push(i)}}detectGapsWhenIdle(e,t){this.gapDetectionIdleCallback||(this.gapDetectionIdleCallback=Fu(()=>{try{this.detectGaps(e,t)}catch(r){this.error$.next({id:"GapDetection",category:ir.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(l=>l.from-t<=n&&l.to+t>=o),c=e.filter(l=>n>=l.from-t&&n<=l.to+t||o>=l.from-t&&o<=l.to+t);u||(c.length===1?i.status="partially_ejected":this.gaps.some(l=>l.from===i.time.from||l.to===i.time.to)?i.status="partially_ejected":i.status="none")}}};var ha=a=>{let e=new URL(a);return e.searchParams.set("quic","1"),e.toString()};var tS=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 fa,assertNever as rS,fromEvent as iS,merge as mR,now as ma,Subscription as bR,ValueSubject as nc,flattenObject as Wr}from"@vkontakte/videoplayer-shared";var Xs=class{constructor({throughputEstimator:e,requestQuic:t,tracer:r,compatibilityMode:i=!1}){this.lastConnectionType$=new nc(void 0);this.lastConnectionReused$=new nc(void 0);this.lastRequestFirstBytes$=new nc(void 0);this.abortAllController=new pt;this.subscription=new bR;this.fetchManifest=fa(this.abortAllController.signal,function(e){return te(this,null,function*(){let t=this.tracer.createComponentTracer("FetchManifest"),r=e;this.requestQuic&&(r=ha(r));let i=yield dt(r,{signal:this.abortAllController.signal}).catch(ba);return i?(t.log("success",Wr({url:r,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(i.headers),i.text()):(t.error("error",Wr({url:r,message:"No data in request manifest"})),t.end(),null)})}.bind(this));this.fetch=fa(this.abortAllController.signal,function(c){return te(this,arguments,function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:r,onProgress:i,priority:s="auto",signal:n,measureThroughput:o=!0,isLowLatency:u=!1}={}){var L,F;let l=e,d=new Headers,p=this.tracer.createComponentTracer("Fetch");if(r)switch(t){case 0:{d.append("Range",`bytes=${r.from}-${r.to}`);break}case 1:{let _=new URL(l,location.href);_.searchParams.append("bytes",`${r.from}-${r.to}`),l=_.toString();break}default:rS(t)}this.requestQuic&&(l=ha(l));let h=this.abortAllController.signal,f;if(n){let _=new pt;if(f=mR(iS(this.abortAllController.signal,"abort"),iS(n,"abort")).subscribe(()=>{try{_.abort()}catch(k){ba(k)}}),this.abortAllController.signal.aborted||n.aborted)try{_.abort()}catch(k){ba(k)}h=_.signal}let b=ma();p.log("startRequest",Wr({url:l,priority:s,rangeMethod:t,range:r,isLowLatency:u,requestStartedAt:b}));let g=yield dt(l,{priority:s,headers:d,signal:h}).catch(ba),S=ma();if(!g)return p.error("error",{message:"No response in request"}),p.end(),f==null||f.unsubscribe(),null;if((L=this.throughputEstimator)==null||L.addRawRtt(S-b),!g.ok||!g.body){f==null||f.unsubscribe();let _=`Fetch error ${g.status}: ${g.statusText}`;return p.error("error",{message:_}),p.end(),Promise.reject(new Error(`Fetch error ${g.status}: ${g.statusText}`))}if(this.onHeadersReceived(g.headers),!i&&!o){f==null||f.unsubscribe();let _=ma(),k={requestStartedAt:b,requestEndedAt:_,duration:_-b};return p.log("endRequest",Wr(k)),p.end(),g.arrayBuffer()}let[T,v]=g.body.tee(),y=T.getReader();o&&((F=this.throughputEstimator)==null||F.trackStream(v,u));let I=0,$=new Uint8Array(0),G=!1,V=_=>{f==null||f.unsubscribe(),G=!0,ba(_)},D=fa(h,function(x){return te(this,arguments,function*({done:_,value:k}){if(I===0&&this.lastRequestFirstBytes$.next(ma()-b),h.aborted){f==null||f.unsubscribe();return}if(!_&&k){let B=new Uint8Array($.length+k.length);B.set($),B.set(k,$.length),$=B,I+=k.byteLength,i==null||i(new DataView($.buffer),I),yield y==null?void 0:y.read().then(D,V)}})}.bind(this));yield y==null?void 0:y.read().then(D,V),f==null||f.unsubscribe();let H=ma(),N={failed:G,requestStartedAt:b,requestEndedAt:H,duration:H-b};return G?(p.error("endRequest",Wr(N)),p.end(),null):(p.log("endRequest",Wr(N)),p.end(),$.buffer)})}.bind(this));this.fetchByteRangeRepresentation=fa(this.abortAllController.signal,function(e,t,r){return te(this,null,function*(){var S;if(e.type!=="byteRange")return null;let{from:i,to:s}=e.initRange,n=i,o=s,u=!1,c,l;e.indexRange&&(c=e.indexRange.from,l=e.indexRange.to,u=s+1===c,u&&(n=Math.min(c,i),o=Math.max(l,s))),n=Math.min(n,0);let d=yield this.fetch(e.url,{range:{from:n,to:o},priority:r,measureThroughput:!1});if(!d)return null;let p=new DataView(d,i-n,s-n+1);if(!t.validateData(p))throw new Error("Invalid media file");let h=t.parseInit(p),f=(S=e.indexRange)!=null?S:t.getIndexRange(h);if(!f)throw new ReferenceError("No way to load representation index");let b;if(u)b=new DataView(d,f.from-n,f.to-f.from+1);else{let 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(d),segments:g}})}.bind(this));this.fetchTemplateRepresentation=fa(this.abortAllController.signal,function(e,t){return te(this,null,function*(){if(e.type!=="template")return null;let r=new URL(e.initUrl,e.baseUrl).toString(),i=yield this.fetch(r,{priority:t,measureThroughput:!1});return i?{init:null,segments:e.segments.map(n=>M(A({},n),{status:"none",size:void 0})),dataView:new DataView(i)}:null})}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=i,this.tracer=r.createComponentTracer("Fetcher")}onHeadersReceived(e){let{type:t,reused:r}=tS(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(r)}fetchRepresentation(e,t,r="auto"){return R(this,null,function*(){var s,n;let{type:i}=e;switch(i){case"byteRange":return(s=yield this.fetchByteRangeRepresentation(e,t,r))!=null?s:null;case"template":return(n=yield this.fetchTemplateRepresentation(e,r))!=null?n:null;default:rS(i)}})}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}},ba=a=>{if(!la(a))throw a};var ar=(a,e,t)=>t*e+(1-t)*a,oc=(a,e)=>a.reduce((t,r)=>t+r,0)/e,aS=(a,e,t,r)=>{let i=0,s=t,n=oc(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 gR,ValueSubject as sS}from"@vkontakte/videoplayer-shared";var $t=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 sS(e.initial),this.debounced$=new sS(e.initial);let t=(r=e.label)!=null?r:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new ue(`raw_${t}`),this.smoothedSeries$=new ue(`smoothed_${t}`),this.reportedSeries$=new ue(`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+=Je(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)&&(gR(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 Zs=class extends $t{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=ar(this.slow,e,this.params.emaAlphaSlow),this.fast=ar(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var en=class extends $t{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=oc(this.pastMeasures,this.takenMeasures);this.emaSmoothed=ar(this.emaSmoothed,e,this.params.emaAlpha);let r=aS(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=r?this.emaSmoothed:t}};var tn=class extends $t{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?ar(this.smoothed,t,this.params.emaAlpha):t}};var sr=class{static getSmoothedValue(e,t,r){return r.type==="TwoEma"?new Zs({initial:e,emaAlphaSlow:r.emaAlphaSlow,emaAlphaFast:r.emaAlphaFast,changeThreshold:r.changeThreshold,fastDirection:t,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"}):new en({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 tn(A({initial:e,label:"liveEdgeDelay"},t))}};var uc=(a,e)=>{a&&a.playbackRate!==e&&(a.playbackRate=e)};import{isNullable as SR,ValueSubject as vR}from"@vkontakte/videoplayer-shared";var ga=class a{constructor(e,t){this.currentRepresentation$=new vR(null);this.currentSegment=null;this.currentSegmentId=0;this.getCurrentPosition=t.getCurrentPosition,this.processStreams(e)}updateLive(e){this.processStreams(e==null?void 0:e.streams.text)}seekLive(e){this.processStreams(e)}maintain(e=this.getCurrentPosition()){var i;if(SR(e))return;let t=null,r=null;for(let s of this.representations){let n=s.segmentReference.segments.find(o=>o.time.from<=e&&o.time.to>=e);if(n){t=n,r=s;break}}!t||!r||((i=this.currentSegment)==null?void 0:i.time.from)===t.time.from&&this.currentSegment.time.to===t.time.to||(this.currentSegment=t,this.currentSegmentId=(this.currentSegmentId+1)%Number.MAX_SAFE_INTEGER,this.currentRepresentation$.next(M(A({},r),{label:"Live Text",language:"ru",isAuto:!0,url:new URL(t.url,r.segmentReference.baseUrl).toString(),id:`subtitle-${this.currentSegmentId.toString(10)}`})))}destroy(){this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e!=null?e:[]){let r=a.filterRepresentations(t.representations);if(r){this.representations=r;break}}}static isSupported(e){return!!(e!=null&&e.some(t=>a.filterRepresentations(t.representations)))}static filterRepresentations(e){return e==null?void 0:e.filter(t=>t.kind==="text"&&"segmentReference"in t&&Ye(t.segmentReference))}};var dS=["timeupdate","progress","play","seeked","stalled","waiting"];var sn=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new lS;this.representationSubscription=new lS;this.state$=new C("none");this.currentVideoRepresentation$=new se(void 0);this.currentVideoRepresentationInit$=new se(void 0);this.currentAudioRepresentation$=new se(void 0);this.currentVideoSegmentLength$=new se(0);this.currentAudioSegmentLength$=new se(0);this.error$=new cS;this.lastConnectionType$=new se(void 0);this.lastConnectionReused$=new se(void 0);this.lastRequestFirstBytes$=new se(void 0);this.currentLiveTextRepresentation$=new se(null);this.isLive$=new se(!1);this.liveDuration$=new se(0);this.liveAvailabilityStartTime$=new se(void 0);this.bufferLength$=new se(0);this.liveLoadBufferLength$=new se(0);this.livePositionFromPlayer$=new se(0);this.timeInWaiting=0;this.isActiveLowLatency$=new se(!1);this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.liveLastSeekOffset=0;this.forceEnded$=new cS;this.gapWatchdogActive=!1;this.destroyController=new pt;this.initManifest=cc(this.destroyController.signal,function(e,t,r){return te(this,null,function*(){var i;this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=ae(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:Lt.PARSER,message:"No playable video representations"})})}.bind(this));this.updateManifest=cc(this.destroyController.signal,function(){return te(this,null,function*(){var n,o;this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(u=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:Lt.NETWORK,message:"Failed to load manifest",thrown:u})});if(!e)return null;let t=null;try{t=Jg(e!=null?e:"",this.manifestUrlString)}catch(u){let c=(n=pg(e))!=null?n:{id:"ManifestParsing",category:Lt.PARSER,message:"Failed to parse MPD manifest",thrown:u};this.error$.next(c)}if(!t)return null;let r=(u,c,l)=>{var d,p,h,f;return!!((p=(d=this.element)==null?void 0:d.canPlayType)!=null&&p.call(d,c)&&((f=(h=ht())==null?void 0:h.isTypeSupported)!=null&&f.call(h,`${c}; codecs="${l}"`))||u==="text")};t.dynamic&&this.isLive$.getValue()!==t.dynamic&&(this.isLive$.next(t.dynamic),this.liveDuration$.getValue()!==t.duration&&this.liveDuration$.next(-1*((o=t.duration)!=null?o:0)/1e3),this.liveAvailabilityStartTime$.getValue()!==t.liveAvailabilityStartTime&&this.liveAvailabilityStartTime$.next(t.liveAvailabilityStartTime));let i={text:t.streams.text,video:[],audio:[]};for(let u of["video","audio"]){let l=t.streams[u].filter(({mime:h,codecs:f})=>r(u,h,f)),d=new Set(l.map(({codecs:h})=>h)),p=dg(d);if(p&&(i[u]=l.filter(({codecs:h})=>h.startsWith(p))),u==="video"){let h=this.tuning.preferHDR,f=i.video.some(g=>g.hdr),b=i.video.some(g=>!g.hdr);xR.isHDR&&h&&f?i.video=i.video.filter(g=>g.hdr):b&&(i.video=i.video.filter(g=>!g.hdr))}}let s=M(A({},t),{streams:i});return this.tracer.log("updateManifestEnd",Sa(s)),s})}.bind(this));this.initRepresentations=cc(this.destroyController.signal,function(e,t,r){return te(this,null,function*(){var d;this.tracer.log("initRepresentationsStart",Sa({initialVideo:e,initialAudio:t,sourceHls:r})),nr(this.manifest),nr(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let i=p=>{this.representationSubscription.add(Yr(p,"error").pipe(an(h=>{var f;return!!((f=this.element)!=null&&f.played.length)})).subscribe(h=>{this.error$.next({id:"VideoSource",category:Lt.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:h})}))};this.source=this.tuning.useManagedMediaSource?Yb():new MediaSource;let s=document.createElement("source");if(i(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),this.tuning.useManagedMediaSource&&Ns())if(r){let p=document.createElement("source");i(p),p.type="application/x-mpegurl",p.src=r.url,this.element.appendChild(p)}else this.element.disableRemotePlayback=!0;this.isActiveLowLatency$.next(this.isLive$.getValue()&&this.tuning.dashCmafLive.lowLatency.isActive);let n={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLowLatency$.getValue(),manifest:this.manifest},o=this.manifest.streams.video.reduce((p,h)=>[...p,...h.representations],[]);if(this.videoBufferManager=new pa("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],uS(t)){let p=this.manifest.streams.audio.reduce((h,f)=>[...h,...f.representations],[]);this.audioBufferManager=new pa("audio",this.source,p,n),this.bufferManagers.push(this.audioBufferManager)}if(ga.isSupported(this.manifest.streams.text)&&!this.tuning.dashCmafLive.lowLatency.isActive&&(this.liveTextManager=new ga(this.manifest.streams.text,n)),this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$)),this.representationSubscription.add(lc(1e3).subscribe(p=>{var h;if((h=this.element)!=null&&h.paused){let f=vu(this.manifestUrlString,2);this.manifestUrlString=ae(this.manifestUrlString,f+1e3,2)}})),this.representationSubscription.add(Qr(...dS.filter(p=>p!=="waiting").map(p=>Yr(this.element,p))).pipe(dc(p=>this.element?lt(this.element.buffered,this.element.currentTime*1e3):0),oS(),an(p=>!!p),IR(p=>{var h;(h=this.stallWatchdogSubscription)==null||h.unsubscribe(),this.timeInWaiting=0})).subscribe(this.bufferLength$)),this.isLive$.getValue()){this.representationSubscription.add(this.isActiveLowLatency$.pipe(oS()).subscribe(h=>uc(this.element,1))),this.representationSubscription.add(rn({bufferLength:this.bufferLength$,isActiveLowLatency:this.isActiveLowLatency$}).pipe(an(({bufferLength:h,isActiveLowLatency:f})=>f&&!!h)).subscribe(({bufferLength:h})=>this.liveEstimatedDelay.next(h))),this.representationSubscription.add(rn({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,S=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,T=h-b,v=1;Math.abs(T)>g&&(v=1+Math.sign(T)*S),uc(this.element,v)})),this.representationSubscription.add(this.bufferLength$.subscribe(h=>{var b,g;let f=0;if(h){let S=((g=(b=this.element)==null?void 0:b.currentTime)!=null?g:0)*1e3;f=Math.min(...this.bufferManagers.map(v=>{var y,I;return(I=(y=v.getLiveSegmentsToLoadState(this.manifest))==null?void 0:y.to)!=null?I:S}))-S}this.liveLoadBufferLength$.getValue()!==f&&this.liveLoadBufferLength$.next(f)}));let p=0;this.representationSubscription.add(rn({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(ER(1e3)).subscribe(b=>R(this,[b],function*({liveLoadBufferLength:h,bufferLength:f}){if(nr(this.element),this.isUpdatingLive)return;let g=this.element.playbackRate,S=vu(this.manifestUrlString,2),T=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,v=Math.min(T,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*g),y=this.tuning.dashCmafLive.normalizedActualBufferOffset*g,I=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*g,$=isFinite(h)?h:f,G=this.isActiveLowLatency$.getValue(),V=T<=this.tuning.live.activeLiveDelay&&S===0;this.isActiveLowLatency$.next(G&&V);let D="none";if(G?D="active_low_latency":this.tuning.dashCmafLive.lowLatency.isActive&&V?(this.isActiveLowLatency$.next(!0),this.bufferManagers.forEach(H=>H.proceedLowLatencyLive()),D="active_low_latency"):S!==0&&$<v?D="live_forward_buffering":$<v+I&&(D="live_with_target_offset"),isFinite(h)&&(p=h>p?h:p),D==="live_forward_buffering"||D==="live_with_target_offset"){let H=p-(v+y),N=this.normolizeLiveOffset(Math.trunc(S+H/g)),L=Math.abs(N-S),F;!h||L<=this.tuning.dashCmafLive.offsetCalculationError?F=S:N>0&&L>this.tuning.dashCmafLive.offsetCalculationError?F=N:F=0,this.manifestUrlString=ae(this.manifestUrlString,F,2)}D!=="none"&&D!=="active_low_latency"&&(p=0,this.updateLive())})))}let u=Qr(...this.bufferManagers.map(p=>p.fullyBuffered$)).pipe(dc(()=>this.bufferManagers.every(p=>p.fullyBuffered$.getValue()))),c=Qr(...this.bufferManagers.map(p=>p.onLastSegment$)).pipe(dc(()=>this.bufferManagers.some(p=>p.onLastSegment$.getValue())));this.representationSubscription.add(Qr(this.forceEnded$,rn({allBuffersFull:u,someBufferEnded:c}).pipe(an(({allBuffersFull:p,someBufferEnded:h})=>p&&h))).subscribe(()=>{var p;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(h=>!h.updating))try{(p=this.source)==null||p.endOfStream()}catch(h){this.error$.next({id:"EndOfStream",category:Lt.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:h})}})),this.representationSubscription.add(Qr(...this.bufferManagers.map(p=>p.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.subscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.subscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&(this.representationSubscription.add(this.audioBufferManager.playingRepresentation$.subscribe(this.currentAudioRepresentation$)),this.subscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$))),this.liveTextManager&&this.subscription.add(this.liveTextManager.currentRepresentation$.subscribe(this.currentLiveTextRepresentation$)),this.source.readyState!=="open"&&(yield new Promise(p=>{var h;return(h=this.source)==null?void 0:h.addEventListener("sourceopen",p)}));let l=[(d=this.manifest.duration)!=null?d:0,...[...this.manifest.streams.audio,...this.manifest.streams.video].flatMap(p=>p.representations).flatMap(p=>{let h=[];return p.duration&&h.push(p.duration),Ye(p.segmentReference)&&p.segmentReference.totalSegmentsDurationMs&&h.push(p.segmentReference.totalSegmentsDurationMs),h})];this.source.duration=Math.max(...l)/1e3,this.audioBufferManager&&uS(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState("representations_ready"),this.tracer.log("initRepresentationsEnd")})}.bind(this));this.tick=()=>{var t,r,i;if(!this.element||!this.videoBufferManager)return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),(t=this.audioBufferManager)==null||t.maintain(e),(r=this.liveTextManager)==null||r.maintain(e),(this.videoBufferManager.gaps.length||(i=this.audioBufferManager)!=null&&i.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=lc(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),s=>{this.error$.next({id:"GapWatchdog",category:Lt.WTF,message:"Error handling gaps",thrown:s})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name),this.fetcher=new Xs({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer}),this.liveEstimatedDelay=sr.getLiveEstimatedDelaySmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,A({},e.tuning.dashCmafLive.lowLatency.delayEstimator)),this.initTracerSubscription()}seekLive(e){return R(this,null,function*(){var r,i,s,n,o;nr(this.element);let t=this.normolizeLiveOffset(e);this.isActiveLowLatency$.next(this.tuning.dashCmafLive.lowLatency.isActive&&t===0),this.liveLastSeekOffset=t,this.manifestUrlString=ae(this.manifestUrlString,t,2),this.manifest=yield this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,yield(i=this.videoBufferManager)==null?void 0:i.seekLive((r=this.manifest)==null?void 0:r.streams.video),yield(n=this.audioBufferManager)==null?void 0:n.seekLive((s=this.manifest)==null?void 0:s.streams.audio),(o=this.liveTextManager)==null||o.seekLive(this.manifest.streams.text))})}initBuffer(){nr(this.element),this.state$.setState("running"),this.subscription.add(Qr(...dS.map(e=>Yr(this.element,e)),Yr(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:Lt.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(Yr(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(Yr(this.element,"waiting").subscribe(()=>{var t,r,i;this.element&&this.element.readyState===2&&!this.element.seeking&&Ui(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{var n,o;if(!this.element)return;this.timeInWaiting+=1e3;let s={timeInWaiting:this.timeInWaiting};if(this.timeInWaiting>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${this.tuning.dash.crashOnStallTimeout} ms`);if(this.isLive$.getValue()&&this.timeInWaiting%5e3===0)this.seekLive(this.liveLastSeekOffset),s=M(A({},s),{liveLastSeekOffset:this.liveLastSeekOffset});else{let u=this.element.currentTime*1e3;(n=this.videoBufferManager)==null||n.maintain(u),(o=this.audioBufferManager)==null||o.maintain(u),s=M(A({},s),{position:u})}this.tracer.log("stallIntervalCallback",Sa(s))};(t=this.videoBufferManager)==null||t.startAccumulateBuffer(),(r=this.audioBufferManager)==null||r.startAccumulateBuffer(),(i=this.stallWatchdogSubscription)==null||i.unsubscribe(),this.stallWatchdogSubscription=lc(1e3).subscribe(e,s=>{this.error$.next({id:"StallWatchdogCallback",category:Lt.FATAL,message:"Can't restore DASH after stall.",thrown:s})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}switchRepresentation(e,t,r=!1){return R(this,null,function*(){let i={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return i==null?void 0:i.switchTo(t,r)})}seek(e,t){var i,s,n,o,u,c;nr(this.element),nr(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),Ui(this.element.buffered,r)||(this.videoBufferManager.abort(),(o=this.audioBufferManager)==null||o.abort()),this.videoBufferManager.startAccumulateBuffer(),this.videoBufferManager.maintain(r),(u=this.audioBufferManager)==null||u.startAccumulateBuffer(),(c=this.audioBufferManager)==null||c.maintain(r),this.element.currentTime=r/1e3,this.tracer.log("seek",Sa({requestedPosition:e,forcePrecise:t,position:r}))}stop(){var e,t,r;this.tracer.log("stop"),(e=this.element)==null||e.querySelectorAll("source").forEach(i=>i.remove()),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),(t=this.videoBufferManager)==null||t.destroy(),this.videoBufferManager=null,(r=this.audioBufferManager)==null||r.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getStreams(){var e;return(e=this.manifest)==null?void 0:e.streams}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){var e;this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),((e=this.source)==null?void 0:e.readyState)==="open"&&Array.from(this.source.sourceBuffers).every(t=>!t.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}initTracerSubscription(){let e=AR(this.tracer.error.bind(this.tracer));this.error$.subscribe(e("error"))}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}updateLive(){return R(this,null,function*(){var e,t;this.isUpdatingLive=!0,this.manifest=yield this.updateManifest(),this.manifest&&((e=this.bufferManagers)==null||e.forEach(r=>r.updateLive(this.manifest)),(t=this.liveTextManager)==null||t.updateLive(this.manifest)),this.isUpdatingLive=!1})}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.getDebugBufferState();if(!e)return;let t={isJumpGapAfterSeekLive:this.isJumpGapAfterSeekLive,isActiveLowLatency:this.isActiveLowLatency$.getValue(),initialCurrentTime:this.element.currentTime};this.isJumpGapAfterSeekLive&&!this.isActiveLowLatency$.getValue()&&this.element.currentTime>e.to&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let r=this.element.currentTime*1e3,i=[],s=this.element.readyState===1?this.tuning.endGapTolerance:0;for(let n of this.bufferManagers)for(let o of n.gaps)n.playingRepresentation$.getValue()===o.representation&&o.from-s<=r&&o.to+s>r&&(this.element.duration*1e3-o.to<this.tuning.endGapTolerance?i.push(1/0):i.push(o.to));if(i.length){let n=Math.max(...i)+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,n===1/0?this.forceEnded$.next():(this.element.currentTime=n/1e3,t=M(A({},t),{gapEnds:i,jumpTo:n,resultCurrentTime:this.element.currentTime}),this.tracer.log("jumpGap",Sa(t)))}}};var nn=class{constructor(e,t){this.fov=e,this.orientation=t}};var on=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/Je(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=A({},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*Je(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 pS=`attribute vec2 a_vertex;
38
59
  attribute vec2 a_texel;
39
60
 
40
61
  varying vec2 v_texel;
@@ -45,7 +66,7 @@ void main(void) {
45
66
  // save texel vector to pass to fragment shader
46
67
  v_texel = a_texel;
47
68
  }
48
- `;var Og=`#ifdef GL_ES
69
+ `;var hS=`#ifdef GL_ES
49
70
  precision highp float;
50
71
  precision highp int;
51
72
  #else
@@ -88,5 +109,5 @@ void main(void) {
88
109
  // sample using new coordinates
89
110
  gl_FragColor = texture2D(u_texture, tc);
90
111
  }
91
- `;var Ds=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 Ms(this.params.fov,this.params.orientation),this.cameraRotationManager=new Cs(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,d=e-r,p=t+i;return[s,n,o,u,l,c,d,p]}updateTextureMappingBuffer(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([...this.calculateTexturePosition()]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}updateFrameSize(){this.frameWidth=this.sourceVideoElement.videoWidth,this.frameHeight=this.sourceVideoElement.videoHeight}createCanvas(){let e=document.createElement("canvas");return e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e}};var zt=class{constructor(e){this.subscription=new fR;this.videoState=new M("stopped");this.elementSize$=new mR(void 0);this.textTracksManager=new Le;this.droppedFramesManager=new us;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new as;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 nR(e)}}};this.init3DScene=e=>{var r,i,s;if(this.scene3D)return;this.scene3D=new Ds(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=pe(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(re(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new $s({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=me(this.video),i=this.constructor.name,s=o=>{e.error$.next({id:i,category:Yu.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(cR),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(We(this.video,t.isLooped,i)),this.subscription.add(fe(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Re(this.video,t.playbackRate,r.playbackRateState$,i)),s(hR(this.video),this.elementSize$),s(Me(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),E(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),E(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:l})=>{if(l==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let c=this.player.getStreams();if(oR(c,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let p=[];for(let h of c.audio){p.push(Ou(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(p)}let d=[];for(let p of c.video){d.push(Bu(p));let h=[];for(let f of p.representations){let b=Sg(f);b&&(h.push(b),this.videoTracksMap.set(b,{stream:p,representation:f}))}this.videoStreamsMap.set(p,h)}this.params.output.availableVideoStreams$.next(d);for(let p of c.text)for(let h of p.representations){let f=yg(p,h);this.textTracksMap.set(f,{stream:p,representation:h})}this.params.output.availableVideoTracks$.next(Array.from(this.videoTracksMap.keys())),this.params.output.availableAudioTracks$.next(Array.from(this.audioTracksMap.keys())),this.params.output.isAudioAvailable$.next(!!this.audioTracksMap.size),this.audioTracksMap.size>0&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else l==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},i));let n=l=>e.error$.next({id:"RepresentationSwitch",category:Yu.WTF,message:"Switching representations threw",thrown:l});this.subscription.add(Os(this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,t.videoStream.stateChangeStarted$,t.audioStream.stateChangeStarted$,this.elementSize$,this.params.output.elementVisible$,this.droppedFramesManager.onDroopedVideoFramesLimit$,lR(this.video,"progress")).subscribe(()=>{let l=this.player.state$.getState(),c=this.player.state$.getTransition();if(!["manifest_ready","running"].includes(l)||c)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let d=this.selectVideoAudioRepresentations();if(!d)return;let[p,h]=d,f=this.params.desiredState.autoVideoTrackLimits.getTransition();if(f&&this.params.output.autoVideoTrackLimits$.next(f.to),l==="manifest_ready")this.player.initRepresentations(p.id,h==null?void 0:h.id,this.params.sourceHls);else if(this.player.switchRepresentation("video",p.id).catch(n),h){let b=!!t.audioStream.getTransition();this.player.switchRepresentation("audio",h.id,b).catch(n)}},i)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:l})=>{this.scene3D&&l&&this.scene3D.pointCameraTo(l.x,l.y)})),this.subscription.add(this.elementSize$.subscribe(l=>{this.scene3D&&l&&this.scene3D.setViewportSize(l.width,l.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(Wu()).subscribe(l=>{let c=[...this.videoTracksMap.entries()].find(([,{representation:f}])=>f.id===l);if(!c){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[d,{stream:p}]=c,h=this.params.desiredState.videoStream.getTransition();h&&h.to&&h.to.id===p.id&&this.params.desiredState.videoStream.setState(h.to),e.currentVideoTrack$.next(d),e.currentVideoStream$.next(Bu(p))},i)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(Wu()).subscribe(l=>{let c=[...this.audioTracksMap.entries()].find(([,{representation:f}])=>f.id===l);if(!c){e.currentAudioStream$.next(void 0);return}let[d,{stream:p}]=c,h=this.params.desiredState.audioStream.getTransition();h&&h.to&&h.to.id===p.id&&this.params.desiredState.audioStream.setState(h.to),e.currentAudioStream$.next(Ou(p))},i)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(l=>{var c,d;if(l!=null&&l.is3dVideo&&((c=this.params.tuning.spherical)!=null&&c.enabled))try{this.init3DScene(l),e.is3DVideo$.next(!0)}catch(p){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${p}`})}else this.destroy3DScene(),(d=this.params.tuning.spherical)!=null&&d.enabled&&e.is3DVideo$.next(!1)},i)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,i)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,i)),this.textTracksManager.connect(this.video,t,e);let o=t.playbackState.stateChangeStarted$.pipe(_g(({to:l})=>l==="ready"),Wu());this.subscription.add(Os(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$).subscribe(()=>{let l=t.autoVideoTrackSwitching.getState(),d=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:l?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(d)})),this.subscription.add(Os(o,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let u=Os(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,pR(["init"])).pipe(uR(0));this.subscription.add(u.subscribe(this.syncPlayback,i))}selectVideoAudioRepresentations(){var D,$,O,U,L,w,H,W,k,x,N,G,Q,Z;let{desiredState:e,output:t}=this.params,r=e.autoVideoTrackSwitching.getState(),i=(D=e.videoTrack.getState())==null?void 0:D.id,n=[...this.videoTracksMap.keys()].find(({id:F})=>F===i),o=t.currentVideoTrack$.getValue(),u=((U=(O=e.videoStream.getState())!=null?O:n&&(($=this.videoTracksMap.get(n))==null?void 0:$.stream))!=null?U:this.videoStreamsMap.size===1)?this.videoStreamsMap.keys().next().value:void 0;if(!u)return;let l=[...this.videoStreamsMap.keys()].find(({id:F})=>F===u.id),c=l&&this.videoStreamsMap.get(l);if(!c)return;let d=rt(this.video.buffered,this.video.currentTime*1e3),p=r?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,h=Math.min(d/Math.min(p,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),f=(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})=>F===(f==null?void 0:f.id)))!=null?w:this.audioStreamsMap.keys().next().value,g=0;if(b){if(n&&!r){let F=Es(n,c,(H=this.audioStreamsMap.get(b))!=null?H:[]);g=Math.max(g,(W=F==null?void 0:F.bitrate)!=null?W:-1/0)}if(o){let F=Es(o,c,(k=this.audioStreamsMap.get(b))!=null?k:[]);g=Math.max(g,(x=F==null?void 0:F.bitrate)!=null?x:-1/0)}}let S=vt(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:I}=this.params.tuning.autoTrackSelection;!this.params.output.elementVisible$.getValue()&&r&&(S=(N=c.filter(F=>!dR(F.quality)).sort((F,Kt)=>{var ut,V;return((ut=Kt.bitrate)!=null?ut:0)-((V=F.bitrate)!=null?V:0)}).filter(F=>Vg(F.quality,S.quality)&&Vg(F.quality,I))[0])!=null?N:S);let v=r?S!=null?S:n:n!=null?n:S,T=b&&Es(v,c,(G=this.audioStreamsMap.get(b))!=null?G:[]),y=(Q=this.videoTracksMap.get(v))==null?void 0:Q.representation,B=T&&((Z=this.audioTracksMap.get(T))==null?void 0:Z.representation);if(y&&B)return[y,B];if(y&&!B&&this.audioTracksMap.size===0)return[y,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){be(this.video).then(e=>{var t;e||((t=this.liveOffset)==null||t.pause(),this.videoState.setState("paused"),E(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Yu.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),he(this.video)}};var Zi=class extends zt{subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:r}=this.getProviderSubscriptionInfo();r(t.timeUpdate$,e.position$),r(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}};import{combine as Fg,interval as bR,map as gR}from"@vkontakte/videoplayer-shared";var ea=class extends zt{constructor(e){super(e),this.liveOffset=new et}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:bR(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(gR(({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=Ge(ts(),1);import{assertNever as ta,assertNonNullable as qg,debounce as SR,ErrorCategory as Bs,filter as vR,isNonNullable as yR,isNullable as TR,map as Vs,merge as IR,Observable as ER,observableFrom as xR,Subscription as PR,videoSizeToQuality as wR}from"@vkontakte/videoplayer-shared";var Ue={};var Cr=(a,e)=>new ER(t=>{let r=(i,s)=>t.next(s);return a.on(e,r),()=>a.off(e,r)}),ra=class{constructor(e){this.subscription=new PR;this.videoState=new M("initializing");this.textTracksManager=new Le;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:ta(e)}break;case"ready":switch(e){case"stopped":this.prepare();break;case"ready":case"playing":case"paused":break;default:ta(e)}break;case"playing":switch(e){case"playing":break;case"stopped":this.prepare();break;case"ready":case"paused":this.playIfAllowed();break;default:ta(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:ta(e)}break;default:ta(t)}};this.video=pe(e.container,e.tuning),this.params=e,this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(re(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),he(this.video)}loadHlsJs(){let e=!1,t=i=>{e||this.params.output.error$.next({id:i==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:Bs.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||(Ue.Hls=i.default,Ue.Events=i.default.Events,this.init())},t),()=>{window.clearTimeout(r),e=!0})}init(){qg(Ue.Hls,"hls.js not loaded"),this.hls=new Ue.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState("stopped")}subscribe(){qg(Ue.Events,"hls.js not loaded");let{desiredState:e,output:t}=this.params,r=l=>{t.error$.next({id:"HlsJsProvider",category:Bs.WTF,message:"HlsJsProvider internal logic error",thrown:l})},i=me(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(We(this.video,e.isLooped,r)),this.subscription.add(fe(this.video,e.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(Re(this.video,e.playbackRate,i.playbackRateState$,r)),s(Me(this.video),t.elementVisible$),s(this.videoState.stateChangeEnded$.pipe(Vs(l=>l.to)),this.params.output.playbackState$),this.subscription.add(Cr(this.hls,Ue.Events.ERROR).subscribe(l=>{var c;l.fatal&&t.error$.next({id:["HlsJsFatal",l.type,l.details].join("_"),category:Bs.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(Cr(this.hls,Ue.Events.MANIFEST_PARSED).pipe(Vs(({levels:l})=>l.reduce((c,d)=>{var I,v;let p=d.name||d.height.toString(10),{width:h,height:f}=d,b=(v=gt((I=d.attrs.QUALITY)!=null?I:""))!=null?v:wR({width:h,height:f});if(!b)return c;let g=d.attrs["FRAME-RATE"]?parseFloat(d.attrs["FRAME-RATE"]):void 0,S={id:p.toString(),quality:b,bitrate:d.bitrate/1e3,size:{width:h,height:f},fps:g};return this.trackLevels.set(p,{track:S,level:d}),c.push(S),c},[]))),t.availableVideoTracks$),s(Cr(this.hls,Ue.Events.MANIFEST_PARSED),l=>{if(l.subtitleTracks.length>0){let c=[];for(let d of l.subtitleTracks){let p=d.name,h=d.attrs.URI||"",f=d.lang;c.push({id:p,url:h,language:f,type:"internal"})}e.internalTextTracks.startTransitionTo(c)}}),s(Cr(this.hls,Ue.Events.LEVEL_LOADING).pipe(Vs(({url:l})=>re(l))),t.hostname$),s(Cr(this.hls,Ue.Events.FRAG_CHANGED),l=>{var p,h,f,b;let{video:c,audio:d}=l.frag.elementaryStreams;t.currentVideoSegmentLength$.next((((p=c==null?void 0:c.endPTS)!=null?p:0)-((h=c==null?void 0:c.startPTS)!=null?h:0))*1e3),t.currentAudioSegmentLength$.next((((f=d==null?void 0:d.endPTS)!=null?f:0)-((b=d==null?void 0:d.startPTS)!=null?b:0))*1e3)}),this.subscription.add(ft(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,l=>{this.hls.nextLevel=l?-1:this.hls.currentLevel,this.hls.loadLevel=l?-1:this.hls.loadLevel},{onError:r}));let n=l=>{var c;return(c=Array.from(this.trackLevels.values()).find(({level:d})=>d===l))==null?void 0:c.track},o=Cr(this.hls,Ue.Events.LEVEL_SWITCHED).pipe(Vs(({level:l})=>n(this.hls.levels[l])));o.pipe(vR(yR)).subscribe(t.currentVideoTrack$,r),this.subscription.add(ft(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel]),l=>{var f;if(TR(l))return;let c=(f=this.trackLevels.get(l.id))==null?void 0:f.level;if(!c)return;let d=this.hls.levels.indexOf(c),p=this.hls.currentLevel,h=this.hls.levels[p];!h||c.bitrate>h.bitrate?this.hls.nextLevel=d:(this.hls.loadLevel=d,this.hls.loadLevel=d)},{changed$:o,onError:r})),s(i.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);let u=IR(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,xR(["init"])).pipe(SR(0));this.subscription.add(u.subscribe(this.syncPlayback,r))}prepare(){this.videoState.startTransitionTo("ready"),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}playIfAllowed(){return A(this,null,function*(){this.videoState.startTransitionTo("playing"),(yield be(this.video).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Bs.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",Qu=a=>A(void 0,null,function*(){var i;let e=yield it(a),t=yield e.text(),r=(i=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t))==null?void 0:i[1];return r?parseInt(r,10):e.headers.has(Hg)?parseInt(e.headers.get(Hg),10):void 0});import{assertNever as MR,combine as CR,debounce as DR,ErrorCategory as Ns,filter as OR,filterChanged as BR,isNonNullable as Gg,isNullable as Fs,map as Yg,merge as VR,observableFrom as _R,Subscription as NR,ValueSubject as Ju,VideoQuality as FR}from"@vkontakte/videoplayer-shared";var Ku=Ge(bo(),1);import{videoSizeToQuality as AR,getExponentialDelay as kR}from"@vkontakte/videoplayer-shared";var RR=a=>{let e=null;if(a.QUALITY&&(e=gt(a.QUALITY)),!e&&a.RESOLUTION){let[t,r]=a.RESOLUTION.split("x").map(i=>parseInt(i,10));e=AR({width:t,height:r})}return e!=null?e:null},LR=(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 d=(0,Ku.default)(l[1].split(",").map(I=>I.split("="))),p=(s=d.QUALITY)!=null?s:`stream-${d.BANDWIDTH}`,h=RR(d),f;d.BANDWIDTH&&(f=parseInt(d.BANDWIDTH,10)/1e3||void 0),!f&&d["AVERAGE-BANDWIDTH"]&&(f=parseInt(d["AVERAGE-BANDWIDTH"],10)/1e3||void 0);let b=d["FRAME-RATE"]?parseFloat(d["FRAME-RATE"]):void 0,g;if(d.RESOLUTION){let[I,v]=d.RESOLUTION.split("x").map(T=>parseInt(T,10));I&&v&&(g={width:I,height:v})}let S=new URL(t[++o],e).toString();h&&r.push({id:p,quality:h,url:S,bandwidth:f,size:g,fps:b})}if(c){let d=(0,Ku.default)(c[1].split(",").map(b=>b.split("=")).map(([b,g])=>[b,g.replace(/^"|"$/g,"")])),p=(n=d.URI)==null?void 0:n.replace(/playlist$/,"subtitles.vtt"),h=d.LANGUAGE,f=d.NAME;p&&h&&i.push({type:"internal",id:h,label:f,language:h,url:p,isAuto:!1})}}}if(!r.length)throw new Error("Empty manifest");return{qualityManifests:r,textTracks:i}},$R=a=>new Promise(e=>{setTimeout(()=>{e()},a)}),zu=0,jg=(r,...i)=>A(void 0,[r,...i],function*(a,e=a,t){let n=yield(yield it(a)).text();zu+=1;try{let{qualityManifests:o,textTracks:u}=LR(n,e);return{qualityManifests:o,textTracks:u}}catch(o){if(zu<=t.manifestRetryMaxCount)return yield $R(kR(zu-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),jg(a,e,t)}return{qualityManifests:[],textTracks:[]}}),_s=jg;var ia=class{constructor(e){this.subscription=new NR;this.videoState=new M("stopped");this.textTracksManager=new Le;this.manifests$=new Ju([]);this.liveOffset=new et;this.manifestStartTime$=new Ju(void 0);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),r=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(r==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),E(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let 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 MR(t)}};var t;this.params=e,this.video=pe(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:FR.INVARIANT,url:this.params.source.url},_s(ae(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:Ns.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),this.manifests$.next([this.masterManifest,...r])},r=>this.params.output.error$.next({id:"ExtractHlsQualities",category:Ns.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(re(this.params.source.url)),this.maxSeekBackTime$=new Ju((t=e.source.maxSeekBackTime)!=null?t:1/0),this.subscribe()}selectManifest(){var u,l,c,d;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,r=e.getState(),i=t.getTransition(),s=(d=(c=(u=i==null?void 0:i.to)==null?void 0:u.id)!=null?c:(l=t.getState())==null?void 0:l.id)!=null?d:"master",n=this.manifests$.getValue();if(!n.length)return;let o=r?"master":s;return r&&!i&&t.startTransitionTo(this.masterManifest),n.find(p=>p.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"HlsLiveProvider",category:Ns.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},i=me(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(fe(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Re(this.video,t.playbackRate,i.playbackRateState$,r)),s(Me(this.video),e.elementVisible$),this.textTracksManager.connect(this.video,t,e),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),E(t.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),E(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())==null?void 0:o.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.subscription.add(this.maxSeekBackTime$.pipe(BR(),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 d=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let p=this.manifests$.getValue().find(h=>h.id===d);p&&(this.params.output.currentVideoTrack$.next(p),this.params.output.hostname$.next(re(p.url)))}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o&&o.state==="requested"&&this.seek(o.position)},r)),this.subscription.add(i.loadedData$.subscribe(()=>{var u,l,c;let o=(c=(l=(u=this.video)==null?void 0:u.getStartDate)==null?void 0:l.call(u))==null?void 0:c.getTime();this.manifestStartTime$.next(o||void 0)},r)),this.subscription.add(CR({startTime:this.manifestStartTime$.pipe(OR(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:d,fps:p})=>({id:u,quality:l,size:c,fps:p,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,r));let n=VR(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,_R(["init"])).pipe(DR(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),he(this.video)}prepare(){var o,u;let e=this.selectManifest();if(Fs(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),r=this.params.desiredState.autoVideoTrackLimits.getState(),i=new URL(e.url);if((t||r)&&e.id===this.masterManifest.id){let{max:l,min:c}=(u=(o=t==null?void 0:t.to)!=null?o:r)!=null?u:{};for(let[d,p]of[[l,"mq"],[c,"lq"]]){let h=String(parseFloat(d||""));p&&d&&i.searchParams.set(p,h)}}let s=this.params.format==="HLS_LIVE_CMAF"?2:0,n=ae(i.toString(),this.liveOffset.getTotalOffset(),s);this.video.setAttribute("src",n),this.video.load(),Qu(n).then(l=>{var c;if(!Fs(l))this.maxSeekBackTime$.next(l);else{let d=(c=this.params.source.maxSeekBackTime)!=null?c:this.maxSeekBackTime$.getValue();if(Fs(d)||!isFinite(d))try{it(n).then(p=>p.text()).then(p=>{var f;let h=(f=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(p))==null?void 0:f[1];if(h){let b=new URL(h,n).toString();Qu(b).then(g=>{Fs(g)||this.maxSeekBackTime$.next(g)})}})}catch(p){}}})}playIfAllowed(){be(this.video).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),E(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Ns.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 qR,debounce as UR,ErrorCategory as Xu,fromEvent as Zu,isNonNullable as HR,isNullable as jR,map as Wg,merge as Qg,observableFrom as zg,Subscription as GR,ValueSubject as YR,VideoQuality as WR,clientChecker as QR}from"@vkontakte/videoplayer-shared";var aa=class{constructor(e){this.subscription=new GR;this.videoState=new M("stopped");this.textTracksManager=new Le;this.manifests$=new YR([]);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),r=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(r==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),E(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||n||o){let c=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(c);let{currentTime:d}=this.video;this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:d*1e3,forcePrecise:!0});return}switch((i==null?void 0:i.to)!=="paused"&&l.state==="requested"&&this.seek(l.position),t){case"ready":r==="ready"?E(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),E(this.params.desiredState.playbackState,"paused")):r==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":r==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(i==null?void 0:i.to)==="playing"&&E(this.params.desiredState.playbackState,"playing");return;case"paused":r==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&E(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return qR(t)}};this.params=e,this.video=pe(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:WR.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(re(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),_s(ae(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:t,textTracks:r})=>{this.manifests$.next([this.masterManifest,...t]),this.params.tuning.useNativeHLSTextTracks||this.params.desiredState.internalTextTracks.startTransitionTo(r)},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:Xu.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){var u,l,c,d;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,r=e.getState(),i=t.getTransition(),s=(d=(c=(u=i==null?void 0:i.to)==null?void 0:u.id)!=null?c:(l=t.getState())==null?void 0:l.id)!=null?d:"master",n=this.manifests$.getValue();if(!n.length)return;let o=r?"master":s;return r&&!i&&t.startTransitionTo(this.masterManifest),n.find(p=>p.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"HlsProvider",category:Xu.WTF,message:"HlsProvider internal logic error",thrown:o})},i=me(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(We(this.video,t.isLooped,r)),this.subscription.add(fe(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Re(this.video,t.playbackRate,i.playbackRateState$,r)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),E(t.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),E(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())==null?void 0:o.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},r).add(i.loadedMetadata$.subscribe(()=>{var d;let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&HR(l.to)){let p=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let h=this.manifests$.getValue().find(f=>f.id===p);if(h){this.params.output.currentVideoTrack$.next(h),this.params.output.hostname$.next(re(h.url));let f=this.params.desiredState.playbackRate.getState(),b=(d=this.params.output.element$.getValue())==null?void 0:d.playbackRate;if(f!==b){let g=this.params.output.element$.getValue();g&&(this.params.desiredState.playbackRate.setState(f),g.playbackRate=f)}}}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o.state==="requested"&&this.seek(o.position)},r))),this.subscription.add(this.manifests$.pipe(Wg(o=>o.map(({id:u,quality:l,size:c,bandwidth:d,fps:p})=>({id:u,quality:l,size:c,fps:p,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,r)),!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(UR(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),he(this.video)}prepare(){var s,n;let e=this.selectManifest();if(jR(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),r=this.params.desiredState.autoVideoTrackLimits.getState(),i=new URL(e.url);if((t||r)&&e.id===this.masterManifest.id){let{max:o,min:u}=(n=(s=t==null?void 0:t.to)!=null?s:r)!=null?n:{};for(let[l,c]of[[o,"mq"],[u,"lq"]]){let d=String(parseFloat(l||""));c&&l&&i.searchParams.set(c,d)}}this.video.setAttribute("src",i.toString()),this.video.load()}playIfAllowed(){be(this.video).then(e=>{e||(this.videoState.setState("paused"),E(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Xu.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};import{assertNever as zR,assertNonNullable as Kg,debounce as KR,ErrorCategory as Jg,isHigher as JR,isHigherOrEqual as XR,isInvariantQuality as Xg,isLowerOrEqual as ZR,isNonNullable as eL,merge as tL,observableFrom as rL,Subscription as iL,map as aL}from"@vkontakte/videoplayer-shared";var sa=class{constructor(e){this.subscription=new iL;this.videoState=new M("stopped");this.trackUrls={};this.textTracksManager=new Le;this.syncPlayback=()=>{var u,l,c;let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),E(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let s=this.params.desiredState.autoVideoTrackLimits.getTransition(),n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.seekState.getState();if(s&&e!=="ready"&&!n){this.handleQualityLimitTransition(s.to.max);return}if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(n){let{currentTime:d}=this.video;this.prepare(),o.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:d*1e3,forcePrecise:!0}),n.to&&((u=this.params.desiredState.autoVideoTrackLimits.getState())==null?void 0:u.max)!==((c=(l=this.trackUrls[n.to.id])==null?void 0:l.track)==null?void 0:c.quality)&&this.params.output.autoVideoTrackLimits$.next({max:void 0});return}switch((r==null?void 0:r.to)!=="paused"&&o.state==="requested"&&this.seek(o.position),e){case"ready":t==="ready"?E(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),E(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(r==null?void 0:r.to)==="playing"&&E(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&E(this.params.desiredState.playbackState,"paused");return;default:return zR(e)}};this.params=e,this.video=pe(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=me(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(aL(o=>o.to)),this.params.output.playbackState$),this.subscription.add(We(this.video,t.isLooped,r)),this.subscription.add(fe(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Re(this.video,t.playbackRate,i.playbackRateState$,r)),s(Me(this.video),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),E(t.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),E(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{var u,l;((u=this.videoState.getTransition())==null?void 0:u.to)==="ready"&&this.videoState.setState("ready");let o=this.params.desiredState.videoTrack.getTransition();if(o&&eL(o.to)){this.params.desiredState.videoTrack.setState(o.to),this.params.output.currentVideoTrack$.next(this.trackUrls[o.to.id].track);let c=this.params.desiredState.playbackRate.getState(),d=(l=this.params.output.element$.getValue())==null?void 0:l.playbackRate;if(c!==d){let p=this.params.output.element$.getValue();p&&(this.params.desiredState.playbackRate.setState(c),p.playbackRate=c)}}this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.textTracksManager.connect(this.video,t,e);let n=tL(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,rL(["init"])).pipe(KR(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),he(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=zi(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(re(t))}playIfAllowed(){be(this.video).then(e=>{e||(this.videoState.setState("paused"),E(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category: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(d=>!Xg(d.track.quality)&&ZR(d.track.quality,e)))==null?void 0:s.track,l=(n=this.params.desiredState.videoTrack.getState())==null?void 0:n.id,c=(o=this.trackUrls[l!=null?l:"0"])==null?void 0:o.track;if(u&&c&&XR(c.quality,u.quality)&&(t=u),!t){let d=Object.values(this.trackUrls).filter(h=>!Xg(h.track.quality)&&JR(h.track.quality,e)),p=d.length;p&&(t=d[p-1].track)}t&&(r=t.quality)}else if(!e){let u=Object.values(this.trackUrls).map(l=>l.track);t=vt(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 uL,merge as tS,observableFrom as lL,Subscription as cL,map as rS,ValueSubject as dL,ErrorCategory as tl,VideoQuality as pL}from"@vkontakte/videoplayer-shared";import{ErrorCategory as sL}from"@vkontakte/videoplayer-shared";var Zg=["stun:videostun.mycdn.me:80"],nL=1e3,oL=3,el=()=>null,qs=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=el;this.externalStopCallback=el;this.externalErrorCallback=el;this.options=this.normalizeOptions(t);let r=e.split("/");this.serverUrl=r.slice(0,r.length-1).join("/"),this.streamKey=r[r.length-1]}onStart(e){try{this.externalStartCallback=e}catch(t){this.handleSystemError(t)}}onStop(e){try{this.externalStopCallback=e}catch(t){this.handleSystemError(t)}}onError(e){try{this.externalErrorCallback=e}catch(t){this.handleSystemError(t)}}connect(){this.connectWS()}disconnect(){try{this.externalStopCallback(),this.closeConnections()}catch(e){this.handleSystemError(e)}}connectWS(){this.ws||(this.ws=new WebSocket(this.serverUrl),this.ws.onopen=this.onSocketOpen.bind(this),this.ws.onmessage=this.onSocketMessage.bind(this),this.ws.onclose=this.onSocketClose.bind(this),this.ws.onerror=this.onSocketError.bind(this))}onSocketOpen(){this.handleLogin()}onSocketClose(e){try{if(!this.ws)return;this.ws=null,e.code>1e3?(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():this.scheduleRetry()):this.externalStopCallback()}catch(t){this.handleRTCError(t)}}onSocketError(e){try{this.externalErrorCallback(new Error(e.toString()))}catch(t){this.handleRTCError(t)}}onSocketMessage(e){try{let t=this.parseMessage(e.data);switch(t.type){case"JOIN":case"CALL_JOIN":this.handleJoinMessage(t);break;case"UPDATE":this.handleUpdateMessage(t);break;case"STATUS":this.handleStatusMessage(t);break}}catch(t){this.handleRTCError(t)}}handleJoinMessage(e){switch(e.inviteType){case"ANSWER":this.handleAnswer(e.sdp);break;case"CANDIDATE":this.handleCandidate(e.candidate);break}}handleStatusMessage(e){switch(e.status){case"UNPUBLISHED":this.handleUnpublished();break}}handleUpdateMessage(e){return A(this,null,function*(){try{let t=yield this.createOffer();this.peerConnection&&(yield this.peerConnection.setLocalDescription(t)),this.handleAnswer(e.sdp)}catch(t){this.handleRTCError(t)}})}handleLogin(){return A(this,null,function*(){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=yield this.createOffer();yield this.peerConnection.setLocalDescription(t),this.send({type:this.signalingType,inviteType:"OFFER",streamKey:this.streamKey,sdp:t.sdp,callSupport:!1})}catch(e){this.handleRTCError(e)}})}handleAnswer(e){return A(this,null,function*(){try{this.peerConnection&&(yield this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e})))}catch(t){this.handleRTCError(t)}})}handleCandidate(e){return A(this,null,function*(){if(e)try{this.peerConnection&&(yield this.peerConnection.addIceCandidate(e))}catch(t){this.handleRTCError(t)}})}handleUnpublished(){try{this.closeConnections(),this.externalStopCallback()}catch(e){this.handleRTCError(e)}}handleSystemError(e){this.options.errorChanel&&this.options.errorChanel.next({id:"webrtc-provider-error",category:sL.WTF,message:e.message})}onPeerConnectionStream(e){return A(this,null,function*(){let t=e.streams[0];this.stream&&this.stream.id===t.id||(this.stream=t,this.externalStartCallback(this.stream))})}onPeerConnectionIceCandidate(e){e.candidate&&this.send({type:this.signalingType,inviteType:"CANDIDATE",candidate:e.candidate})}onPeerConnectionIceConnectionStateChange(){if(this.peerConnection){let e=this.peerConnection.iceConnectionState;["failed","closed"].indexOf(e)>-1&&(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():(this.closeConnections(),this.scheduleRetry()))}}createOffer(){return A(this,null,function*(){let e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");let t=yield this.peerConnection.createOffer(e),r=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(r))throw new Error("No h264 codec support error");return t})}handleRTCError(e){try{this.externalErrorCallback(e||new Error("RTC connection error"))}catch(t){this.handleSystemError(t)}}handleNetworkError(){try{this.externalErrorCallback(new Error("Network error"))}catch(e){this.handleSystemError(e)}}send(e){this.ws&&this.ws.send(JSON.stringify(e))}parseMessage(e){try{return JSON.parse(e)}catch(t){throw new Error("Can not parse socket message")}}closeConnections(){let e=this.ws;e&&(this.ws=null,e.close(1e3)),this.removePeerConnection()}removePeerConnection(){let e=this.peerConnection;e&&(this.peerConnection=null,e.close(),e.ontrack=null,e.onicecandidate=null,e.oniceconnectionstatechange=null,e=null)}scheduleRetry(){this.retryTimeout=setTimeout(this.connectWS.bind(this),nL)}normalizeOptions(e={}){let t={stunServerList:Zg,maxRetryNumber:oL,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var na=class{constructor(e){this.videoState=new M("stopped");this.maxSeekBackTime$=new dL(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 cL,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=pe(e.container,e.tuning),this.liveStreamClient=new qs(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),he(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,r=n=>{e.error$.next({id:"WebRTCLiveProvider",category:tl.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=me(this.video),s=(n,o)=>this.subscription.add(n.subscribe(o,r));s(i.timeUpdate$,e.liveTime$),s(i.ended$,e.endedEvent$),s(i.looped$,e.loopedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(Me(this.video),this.params.output.elementVisible$),this.subscription.add(i.durationChange$.subscribe(n=>{e.duration$.next(n===1/0?0:n)})).add(i.canplay$.subscribe(()=>{var n;((n=this.videoState.getTransition())==null?void 0:n.to)==="ready"&&this.videoState.setState("ready")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused")},r)).add(i.playing$.subscribe(()=>{this.videoState.setState("playing")},r)).add(i.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(fe(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$,lL(["init"])).pipe(uL(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(re(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:pL.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:tl.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){be(this.video).then(e=>{e||(this.videoState.setState("paused"),E(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:tl.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var oa=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 ca,assertNonNullable as It,ErrorCategory as Hs,filter as vL,isNonNullable as uS,isNullable as yL,map as TL,merge as IL,once as EL,Subject as Ee,Subscription as lS,ValueSubject as C}from"@vkontakte/videoplayer-shared";import{Observable as hL,map as iS,Subscription as fL,Subject as mL}from"@vkontakte/videoplayer-shared";var aS=a=>new hL(e=>{let t=new fL,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 mL,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 bL,combine as gL,filter as nS,once as oS}from"@vkontakte/videoplayer-shared";var ua=null,Us=null;function rl(){return ua||(ua=new(window.AudioContext||window.webkitAudioContext)),Us||(Us=new GainNode(ua,{gain:1}),Us.connect(ua.destination)),{audioCtx:ua,gainNode:Us}}import{clientChecker as SL}from"@vkontakte/videoplayer-shared";var Dr=class Dr{constructor(e,t,r,i,s){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=r;this.volumeMultiplier=i;this.subscriptions=new bL;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){SL.isSafari&&e!=="MPEG"||this.subscriptions.add(gL({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}=rl(),s=(Math.random()+1)*999999;this.lastAudioContextResumeId=s,r.resume().then(()=>{var n;if(s!==this.lastAudioContextResumeId)throw new Error(`AudioContext.resume() resolved after ${Dr.errorId} destroyed`);i.gain.value=t;try{new MediaElementAudioSourceNode(r,{mediaElement:e}).connect(i)}catch(o){this.volumeMultiplierError$.next({id:Dr.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:Dr.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}=rl();e.gain.value=1,this.subscriptions.unsubscribe(),this.lastAudioContextResumeId=0}};Dr.errorId="VolumeMultiplierManager";var la=Dr;var xL={chunkDuration:5e3,maxParallelRequests:5},da=class{constructor(e){this.current$=new C({type:void 0});this.providerError$=new Ee;this.noAvailableProvidersError$=new Ee;this.volumeMultiplierError$=new Ee;this.providerOutput={position$:new C(0),duration$:new C(1/0),volume$:new C({muted:!1,volume:1}),availableVideoStreams$:new C([]),currentVideoStream$:new C(void 0),availableVideoTracks$:new C([]),currentVideoTrack$:new C(void 0),availableAudioStreams$:new C([]),currentAudioStream$:new C(void 0),availableAudioTracks$:new C([]),currentVideoSegmentLength$:new C(0),currentAudioSegmentLength$:new C(0),isAudioAvailable$:new C(!0),autoVideoTrackLimitingAvailable$:new C(!1),autoVideoTrackLimits$:new C(void 0),currentBuffer$:new C(void 0),isBuffering$:new C(!0),error$:new Ee,warning$:new Ee,willSeekEvent$:new Ee,seekedEvent$:new Ee,loopedEvent$:new Ee,endedEvent$:new Ee,firstBytesEvent$:new Ee,loadedMetadataEvent$:new Ee,firstFrameEvent$:new Ee,canplay$:new Ee,isLive$:new C(void 0),isLowLatency$:new C(!1),canChangePlaybackSpeed$:new C(!0),liveTime$:new C(void 0),liveBufferTime$:new C(void 0),availableTextTracks$:new C([]),currentTextTrack$:new C(void 0),hostname$:new C(void 0),httpConnectionType$:new C(void 0),httpConnectionReused$:new C(void 0),inPiP$:new C(!1),inFullscreen$:new C(!1),element$:new C(void 0),elementVisible$:new C(!0),availableSources$:new C(void 0),is3DVideo$:new C(!1),playbackState$:new C("")};this.subscription=new lS;var o;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer");let t=Ab([...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 oa(s);let n=[...Tu(!0),...Tu(!1)];this.chromecastFormatsIterator=new oa(n.filter(u=>uS(e.sources[u]))),this.providerOutput.availableSources$.next(e.sources),this.volumeMultiplierManager=new la(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(yL(t)){this.handleNoFormatsError(e);return}let r;try{r=this.createProvider(e,t)}catch(i){this.providerError$.next({id:"ProviderNotConstructed",category:Hs.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 ca(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 It(o),new Zi(q(R({},n),{source:o,sourceHls:u}))}case"DASH_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return It(o),new ea(q(R({},n),{source:o}))}case"HLS":case"HLS_ONDEMAND":{let o=this.applyFailoverHost(t[e]);return It(o),xr||!this.params.tuning.useHlsJs?new aa(q(R({},n),{source:o})):new ra(q(R({},n),{source:o}))}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return It(o),new ia(q(R({},n),{source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e}))}case"MPEG":{let o=this.applyFailoverHost(t[e]);return It(o),new sa(q(R({},n),{source:o}))}case"DASH_LIVE":{let o=this.applyFailoverHost(t[e]);return It(o),new lb(q(R({},n),{source:o,config:q(R({},xL),{maxPausedTime:this.params.tuning.live.maxPausedTime})}))}case"WEB_RTC_LIVE":{let o=this.applyFailoverHost(t[e]);return It(o),new na({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 ca(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 It(o),new ci({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 ca(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return ca(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 ca(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 q(R({},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(IL(this.providerOutput.error$,aS({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(TL(i=>({id:`ProviderHangup:${i}`,category:Hs.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(vL(({to:s})=>s==="playing"),EL()).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===Hs.NETWORK,o=i.category===Hs.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 js,once as PL,combine as wL,Subscription as dS,ValueSubject as il,map as AL,filter as kL,isNonNullable as Gs,now as xe,safeStorage as al}from"@vkontakte/videoplayer-shared";var RL=5e3,pS="one_video_throughput",hS="one_video_rtt",nt=window.navigator.connection,fS=()=>{let a=nt==null?void 0:nt.downlink;if(Gs(a)&&a!==10)return a*1e3},mS=()=>{let a=nt==null?void 0:nt.rtt;if(Gs(a)&&a!==3e3)return a},bS=(a,e,t)=>{let r=t*8,i=r/a;return r/(i+e)},sl=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)||RL,r=(s=(i=a.load(hS))!=null?i:e.useBrowserEstimation?mS():void 0)!=null?s:0;if(this.throughput$=new il(t),this.rtt$=new il(r),this.rttAdjustedThroughput$=new il(bS(t,r,e.rttPenaltyRequestSize)),this.throughput=Wt.getSmoothedValue(t,-1,e),this.rtt=Wt.getSmoothedValue(r,1,e),e.useBrowserEstimation){let n=()=>{let u=fS();u&&this.throughput.next(u);let l=mS();Gs(l)&&this.rtt.next(l)};nt&&"onchange"in nt&&this.subscription.add(js(nt,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{al.set(pS,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{al.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(wL({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(AL(({throughput:n,rtt:o})=>bS(n,o,e.rttPenaltyRequestSize)),kL(n=>{let o=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(n-o)/o>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,r=xe(),i=new dS;switch(this.subscription.add(i),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:i.add(js(e,"progress").pipe(PL()).subscribe(s=>{t=s.loaded,r=xe()}));break;case 1:case 0:i.add(js(e,"loadstart").subscribe(()=>{t=0,r=xe()}));break}i.add(js(e,"loadend").subscribe(s=>{if(e.status===200){let n=s.loaded,o=xe(),u=n-t,l=o-r;this.addRawSpeed(u,l,1)}this.concurrentDownloads.delete(e),i.unsubscribe()}))}trackStream(e,t=!1){let r=e.getReader();if(!r){e.cancel("Could not get reader");return}let i=0,s=xe(),n=0,o=xe(),u=c=>{this.concurrentDownloads.delete(e),r.releaseLock(),e.cancel(`Throughput Estimator error: ${c}`).catch(()=>{})},l=p=>A(this,[p],function*({done:c,value:d}){if(c)!t&&this.addRawSpeed(i,xe()-s,1),this.concurrentDownloads.delete(e);else if(d){if(t){let h=xe();if(h-o>this.tuningConfig.lowLatency.continuesByteSequenceInterval||h-s>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let b=o-s;b&&this.addRawSpeed(n,b,1,t),n=d.byteLength,s=xe()}else n+=d.byteLength;o=xe()}else i+=d.byteLength,n+=d.byteLength,n>=this.tuningConfig.streamMinSampleSize&&xe()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,xe()-o,this.concurrentDownloads.size),n=0,o=xe());yield r==null?void 0:r.read().then(l,u)}});this.concurrentDownloads.add(e),r==null||r.read().then(l,u)}addRawSpeed(e,t,r=1,i=!1){if(a.sanityCheck(e,t,i)){let s=e*8/t;this.throughput.next(s*r)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,r=!1){let i=e*8/t;return!(!i||!isFinite(i)||i>1e6||i<30||r&&e<1e4||!r&&e<10*1024||!r&&t<=20)}static load(e){var r;let t=al.get(e);if(Gs(t))return(r=parseInt(t,10))!=null?r:void 0}},gS=sl;import{fillWithDefault as LL,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,bitrateFactorAtFullBuffer:1.2,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,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 q(R({},LL(a,vS)),{configName:[...(e=a.configName)!=null?e:[],...vS.configName]})};import{assertNonNullable as Ys,combine as Ws,ErrorCategory as Qs,filter as pa,filterChanged as De,fromEvent as ol,isNonNullable as VL,isNullable as _L,Logger as NL,map as _,mapTo as xS,merge as Et,now as zs,once as ot,Subject as Y,Subscription as PS,tap as wS,ValueSubject as P,isHigher as FL,isInvariantQuality as AS}from"@vkontakte/videoplayer-shared";import{merge as $L,map as ML,filter as TS,isNonNullable as CL}from"@vkontakte/videoplayer-shared";var nl=({seekState:a,position$:e})=>$L(a.stateChangeEnded$.pipe(ML(({to:t})=>{var r;return t.state==="none"?void 0:((r=t.position)!=null?r:NaN)/1e3}),TS(CL)),e.pipe(TS(()=>a.getState().state==="none")));import{assertNonNullable as DL}from"@vkontakte/videoplayer-shared";var IS=a=>{let e=typeof a.container=="string"?document.getElementById(a.container):a.container;return DL(e,`Wrong container or containerId {${a.container}}`),e};import{filter as OL,once as BL}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(OL(i=>i.length>0),BL()).subscribe(i=>{i.find(r)&&e.startTransitionTo(a)}):(a===void 0||t!=null&&t.getValue().find(r))&&e.startTransitionTo(a)};var Ks=class{constructor(e={configName:[]}){this.subscription=new PS;this.logger=new NL;this.abrLogger=this.logger.createComponentLog("ABR");this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new P(!1);this.hasLiveOffsetByPausedTimer=0;this.desiredState={playbackState:new M("stopped"),seekState:new M({state:"none"}),volume:new M({volume:1,muted:!1}),videoTrack:new M(void 0),videoStream:new M(void 0),audioStream:new M(void 0),autoVideoTrackSwitching:new M(!0),autoVideoTrackLimits:new M({}),isLooped:new M(!1),playbackRate:new M(1),externalTextTracks:new M([]),internalTextTracks:new M([]),currentTextTrack:new M(void 0),textTrackCuesSettings:new M({}),cameraOrientation:new M({x:0,y:0})};this.info={playbackState$:new P("stopped"),position$:new P(0),duration$:new P(1/0),muted$:new P(!1),volume$:new P(1),availableVideoStreams$:new P([]),currentVideoStream$:new P(void 0),availableQualities$:new P([]),availableQualitiesFps$:new P({}),currentQuality$:new P(void 0),isAutoQualityEnabled$:new P(!0),autoQualityLimitingAvailable$:new P(!1),autoQualityLimits$:new P({}),availableAudioStreams$:new P([]),currentAudioStream$:new P(void 0),availableAudioTracks$:new P([]),isAudioAvailable$:new P(!0),currentPlaybackRate$:new P(1),currentBuffer$:new P({start:0,end:0}),isBuffering$:new P(!0),isStalled$:new P(!1),isEnded$:new P(!1),isLooped$:new P(!1),isLive$:new P(void 0),canChangePlaybackSpeed$:new P(void 0),atLiveEdge$:new P(void 0),atLiveDurationEdge$:new P(void 0),liveTime$:new P(void 0),liveBufferTime$:new P(void 0),currentFormat$:new P(void 0),availableTextTracks$:new P([]),currentTextTrack$:new P(void 0),throughputEstimation$:new P(void 0),rttEstimation$:new P(void 0),videoBitrate$:new P(void 0),hostname$:new P(void 0),httpConnectionType$:new P(void 0),httpConnectionReused$:new P(void 0),surface$:new P("none"),chromecastState$:new P("NOT_AVAILABLE"),chromecastDeviceName$:new P(void 0),intrinsicVideoSize$:new P(void 0),availableSources$:new P(void 0),is3DVideo$:new P(!1),currentVideoSegmentLength$:new P(0),currentAudioSegmentLength$:new P(0)};this.events={inited$:new Y,ready$:new Y,started$:new Y,playing$:new Y,paused$:new Y,stopped$:new Y,willStart$:new Y,willResume$:new Y,willPause$:new Y,willStop$:new Y,willDestruct$:new Y,watchCoverageRecord$:new Y,watchCoverageLive$:new Y,managedError$:new Y,fatalError$:new Y,ended$:new Y,looped$:new Y,seeked$:new Y,willSeek$:new Y,firstBytes$:new Y,loadedMetadata$:new Y,firstFrame$:new Y,canplay$:new Y,log$:new Y};this.experimental={element$:new P(void 0),tuningConfigName$:new P([]),enableDebugTelemetry$:new P(!1),dumpTelemetry:zm};if(this.initLogs(),this.tuning=yS(e),this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new ya({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(d=>JSON.stringify(d,(p,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:Qs.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 da({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&&!vi()?ol(document,"visibilitychange").pipe(ot()).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){Ys(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(pa(r=>r.length>0),ot()).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;Ys(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=>R({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 VL(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(Et(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(_(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(_(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(_(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(_(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(_(e=>e.to)).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(pa(({from:e})=>e==="stopped"),ot()).subscribe(()=>{this.initedAt=zs(),this.events.inited$.next()})).add(this.desiredState.playbackState.stateChangeEnded$.subscribe(e=>{switch(e.to){case"ready":this.events.ready$.next();break;case"playing":this.isPlaybackStarted||this.events.started$.next(),this.isPlaybackStarted=!0,this.events.playing$.next();break;case"paused":this.events.paused$.next();break;case"stopped":this.events.stopped$.next()}})).add(this.desiredState.playbackState.stateChangeStarted$.subscribe(e=>{switch(e.to){case"paused":this.events.willPause$.next();break;case"playing":this.isPlaybackStarted?this.events.willResume$.next():this.events.willStart$.next();break;case"stopped":this.events.willStop$.next();break;default:}}))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();n.state==="requested"?this.desiredState.seekState.setState(q(R({},n),{state:"applying"})):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:Qs.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(_(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(_(n=>n.destination),De()).subscribe(()=>{this.isPlaybackStarted=!1})).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add(e.providerOutput.availableVideoTracks$.pipe(_(n=>n.map(({quality:o})=>o).sort((o,u)=>AS(o)?1:AS(u)?-1:FL(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(De()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(De()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(De()).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(_(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(Ws({hasLiveOffsetByPaused:Et(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(_(n=>n.to),De(),_(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(Ws({atLiveEdge:Ws({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:nl({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(_(({isLive:n,position:o,isLowLatency:u})=>{let l=this.getActiveLiveDelay(u);return n&&Math.abs(o)<l/1e3}),De(),wS(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(_(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add(Ws({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(_(({isLive:n,position:o,duration:u})=>n&&(Math.abs(u)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),De(),wS(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(_(n=>n.muted),De()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(_(n=>n.volume),De()).subscribe(this.info.volume$)).add(nl({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(Et(e.providerOutput.endedEvent$.pipe(xS(!0)),e.providerOutput.seekedEvent$.pipe(xS(!1))).pipe(De()).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(_(n=>({id:n?`No${n}`:"NoProviders",category:Qs.VIDEO_PIPELINE,message:n?`${n} was forced but failed or not available`:"No suitable providers or all providers failed"}))).subscribe(this.events.fatalError$)).add(e.providerOutput.element$.subscribe(this.experimental.element$)).add(e.providerOutput.firstBytesEvent$.pipe(ot(),_(n=>n!=null?n:zs()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe(ot(),_(()=>zs()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(ot(),_(()=>zs()-this.initedAt)).subscribe(this.events.canplay$)).add(this.throughputEstimator.throughput$.subscribe(this.info.throughputEstimation$)).add(this.throughputEstimator.rtt$.subscribe(this.info.rttEstimation$)).add(e.providerOutput.availableSources$.subscribe(this.info.availableSources$));let t=new P(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let r=new P(!0);this.subscription.add(e.current$.subscribe(()=>r.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(pa(({to:n})=>n==="playing"),ot()).subscribe(()=>r.next(!1)));let i=0,s=Et(e.providerOutput.isBuffering$,t,r).pipe(_(()=>{let n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||r.getValue();return n&&!o}),De());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(Et(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(Et(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,e.providerOutput.elementVisible$,this.chromecastInitializer.castState$).subscribe(()=>{let n=e.providerOutput.inPiP$.getValue(),o=e.providerOutput.inFullscreen$.getValue(),u=e.providerOutput.element$.getValue(),l=e.providerOutput.elementVisible$.getValue(),c=this.chromecastInitializer.castState$.getValue(),d;c==="CONNECTED"?d="second_screen":u?l?n?d="pip":o?d="fullscreen":d="inline":d="invisible":d="none",this.info.surface$.getValue()!==d&&this.info.surface$.next(d)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(_(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(De((r,i)=>r.provider===i.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(pa(r=>r.length>0),ot()).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=vt(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(Et(this.desiredState.videoTrack.stateChangeStarted$.pipe(_(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(_(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(_(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(_(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(_(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(_(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(_(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(_(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(_(e=>({component:"desiredState",message:`[${e.entity} change] ${e.type}: ${JSON.stringify(e.transition)}`}))).subscribe(this.logger.log)),this.subscription.add(this.logger.log$.subscribe(this.events.log$))}initDebugTelemetry(){var t;let e=(t=this.providerContainer)==null?void 0:t.providerOutput;Ys(this.providerContainer),Ys(e),Qm(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(r=>Wm(r)),this.providerContainer.current$.subscribe(({type:r})=>fi("provider",r)),e.duration$.subscribe(r=>fi("duration",r)),e.availableVideoTracks$.pipe(pa(r=>!!r.length),ot()).subscribe(r=>fi("tracks",r)),this.events.fatalError$.subscribe(new ne("fatalError")),this.events.managedError$.subscribe(new ne("managedError")),e.position$.subscribe(new ne("position")),e.currentVideoTrack$.pipe(_(r=>r==null?void 0:r.quality)).subscribe(new ne("quality")),this.info.currentBuffer$.subscribe(new ne("buffer")),e.isBuffering$.subscribe(new ne("isBuffering"))].forEach(r=>this.subscription.add(r)),fi("codecs",wb())}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e,t=()=>{e==null||e.release(),e=void 0},r=()=>A(this,null,function*(){t(),e=yield window.navigator.wakeLock.request("screen").catch(i=>{i instanceof DOMException&&i.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:Qs.DOM,message:String(i)})})});this.subscription.add(Et(ol(document,"visibilitychange"),ol(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 NG,Observable as FG,Subject as qG,ValueSubject as UG,VideoQuality as HG}from"@vkontakte/videoplayer-shared";var jG=`@vkontakte/videoplayer-core@${Ol}`;export{Sa as ChromecastState,pn as HttpConnectionType,FG as Observable,ce as PlaybackState,Ks as Player,jG as SDK_VERSION,qG as Subject,NG as Subscription,hn as Surface,Ol as VERSION,UG as ValueSubject,pt as VideoFormat,HG as VideoQuality};
112
+ `;var un=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 nn(this.params.fov,this.params.orientation),this.cameraRotationManager=new on(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(pS,this.gl.VERTEX_SHADER),r=this.createShader(hS,this.gl.FRAGMENT_SHADER);if(this.gl.attachShader(e,t),this.gl.attachShader(e,r),this.gl.linkProgram(e),!this.gl.getProgramParameter(e,this.gl.LINK_STATUS))throw this.destroy(),new Error("Could not link shader program.");return e}createTexture(){let e=this.gl.createTexture();if(!e)throw this.destroy(),new Error("Could not create texture");return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.bindTexture(this.gl.TEXTURE_2D,null),e}updateTexture(){this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,!0),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.sourceVideoElement),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}createVertexBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create vertex buffer");let t=1,r=1,i=this.frameHeight/(this.frameWidth/this.viewportWidth);return i>this.viewportHeight?t=this.viewportHeight/i:r=i/this.viewportHeight,this.gl.bindBuffer(this.gl.ARRAY_BUFFER,e),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-t,-r,t,-r,t,r,-t,r]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),e}createTextureMappingBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create texture mapping buffer");return e}calculateTexturePosition(){let e=.5-this.camera.orientation.x/360,t=.5-this.camera.orientation.y/180,r=this.camera.fov.x/360/2,i=this.camera.fov.y/180/2,s=e-r,n=t-i,o=e+r,u=t-i,c=e+r,l=t+i,d=e-r,p=t+i;return[s,n,o,u,c,l,d,p]}updateTextureMappingBuffer(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([...this.calculateTexturePosition()]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}updateFrameSize(){this.frameWidth=this.sourceVideoElement.videoWidth,this.frameHeight=this.sourceVideoElement.videoHeight}createCanvas(){let e=document.createElement("canvas");return e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e}};var or=class{constructor(e){this.subscription=new VR;this.videoState=new C("stopped");this.elementSize$=new _R(void 0);this.textTracksManager=new Be;this.droppedFramesManager=new Bs;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new Mi;this.audioTrackSwitchHistory=new Mi;this.textTracks=[];this.syncPlayback=()=>{var n,o,u;let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),i=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(i.state==="requested"&&(r==null?void 0:r.to)!=="paused"&&e!=="stopped"&&t!=="stopped"){let c=(o=(n=this.liveOffset)==null?void 0:n.getTotalPausedTime())!=null?o:0;this.seek(i.position-c,i.forcePrecise)}if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.player.stop(),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),E(this.params.desiredState.playbackState,"stopped",!0));return}switch(e){case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();return;case"ready":t==="paused"?(this.videoState.setState("paused"),E(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="ready"&&E(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),(u=this.liveOffset)==null||u.pause(),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(r==null?void 0:r.to)==="playing"&&E(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.liveOffset?this.liveOffset.getTotalOffset()/1e3<Math.abs(this.params.output.duration$.getValue())?(this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(0,!1):this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&E(this.params.desiredState.playbackState,"paused");return;default:return $R(e)}}};this.init3DScene=e=>{var r,i,s;if(this.scene3D)return;this.scene3D=new un(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=me(e.container,e.tuning),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(re(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new sn({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode,tracer:this.tracer}),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params,r=Se(this.video),i=this.constructor.name,s=o=>{e.error$.next({id:i,category:pc.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(fS(c=>!!c.length),bS()).subscribe(c=>{this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:r.playing$,pause$:r.pause$,tracks:c})})),s(r.ended$,e.endedEvent$),s(r.looped$,e.loopedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentBuffer$),s(r.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),s(r.loadedMetadata$,e.loadedMetadataEvent$),s(this.player.error$,e.error$),s(this.player.lastConnectionType$,e.httpConnectionType$),s(this.player.lastConnectionReused$,e.httpConnectionReused$),s(this.player.isLive$,e.isLive$),s(this.player.lastRequestFirstBytes$.pipe(fS(DR),bS()),e.firstBytesEvent$),s(this.videoState.stateChangeEnded$.pipe(mS(c=>c.to)),this.params.output.playbackState$),this.subscription.add(r.seeked$.subscribe(e.seekedEvent$,i)),this.subscription.add(et(this.video,t.isLooped,i)),this.subscription.add(ge(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(De(this.video,t.playbackRate,r.playbackRateState$,i)),s(OR(this.video),this.elementSize$),s(Ve(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),E(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),E(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:c})=>{if(c==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let l=this.player.getStreams();if(LR(l,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let p=[];for(let h of l.audio){p.push(tc(h));let f=[];for(let b of h.representations){let g=Zg(b);f.push(g),this.audioTracksMap.set(g,{stream:h,representation:b})}this.audioStreamsMap.set(h,f)}this.params.output.availableAudioStreams$.next(p)}let d=[];for(let p of l.video){d.push(rc(p));let h=[];for(let f of p.representations){let b=Xg(f);b&&(h.push(b),this.videoTracksMap.set(b,{stream:p,representation:f}))}this.videoStreamsMap.set(p,h)}this.params.output.availableVideoStreams$.next(d);for(let p of l.text)for(let h of p.representations){let f=Ks(p,h);this.textTracksMap.set(f,{stream:p,representation:h})}this.params.output.availableVideoTracks$.next(Array.from(this.videoTracksMap.keys())),this.params.output.availableAudioTracks$.next(Array.from(this.audioTracksMap.keys())),this.params.output.isAudioAvailable$.next(!!this.audioTracksMap.size),this.audioTracksMap.size>0&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else c==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},i));let n=c=>e.error$.next({id:"RepresentationSwitch",category:pc.WTF,message:"Switching representations threw",thrown:c});this.subscription.add(cn(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$,CR(this.video,"progress")).subscribe(()=>{let c=this.player.state$.getState(),l=this.player.state$.getTransition();if(!["manifest_ready","running"].includes(c)||l)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let d=this.selectVideoAudioRepresentations();if(!d)return;let[p,h]=d,f=this.params.desiredState.autoVideoTrackLimits.getTransition();if(f&&this.params.output.autoVideoTrackLimits$.next(f.to),c==="manifest_ready")this.player.initRepresentations(p.id,h==null?void 0:h.id,this.params.sourceHls);else if(this.player.switchRepresentation("video",p.id).catch(n),h){let b=!!t.audioStream.getTransition();this.player.switchRepresentation("audio",h.id,b).catch(n)}},i)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:c})=>{this.scene3D&&c&&this.scene3D.pointCameraTo(c.x,c.y)})),this.subscription.add(this.elementSize$.subscribe(c=>{this.scene3D&&c&&this.scene3D.setViewportSize(c.width,c.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(hc()).subscribe(c=>{let l=[...this.videoTracksMap.entries()].find(([,{representation:f}])=>f.id===c);if(!l){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[d,{stream:p}]=l,h=this.params.desiredState.videoStream.getTransition();h&&h.to&&h.to.id===p.id&&this.params.desiredState.videoStream.setState(h.to),e.currentVideoTrack$.next(d),e.currentVideoStream$.next(rc(p))},i)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(hc()).subscribe(c=>{let l=[...this.audioTracksMap.entries()].find(([,{representation:f}])=>f.id===c);if(!l){e.currentAudioStream$.next(void 0);return}let[d,{stream:p}]=l,h=this.params.desiredState.audioStream.getTransition();h&&h.to&&h.to.id===p.id&&this.params.desiredState.audioStream.setState(h.to),e.currentAudioStream$.next(tc(p))},i)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(c=>{var l,d;if(c!=null&&c.is3dVideo&&((l=this.params.tuning.spherical)!=null&&l.enabled))try{this.init3DScene(c),e.is3DVideo$.next(!0)}catch(p){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${p}`})}else this.destroy3DScene(),(d=this.params.tuning.spherical)!=null&&d.enabled&&e.is3DVideo$.next(!1)},i)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,i)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,i)),this.textTracksManager.connect(this.video,t,e);let o=t.playbackState.stateChangeStarted$.pipe(mS(({to:c})=>c==="ready"),hc());this.subscription.add(cn(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$).subscribe(()=>{let c=t.autoVideoTrackSwitching.getState(),d=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:c?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(d)})),this.subscription.add(cn(o,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let u=cn(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,BR(["init"])).pipe(MR(0));this.subscription.add(u.subscribe(this.syncPlayback,i))}selectVideoAudioRepresentations(){var $,G,V,D,H,N,L,F,_,k,x,B,W,z,Z,le,Ot,gt;let{desiredState:e,output:t}=this.params,r=e.autoVideoTrackSwitching.getState(),i=($=e.videoTrack.getState())==null?void 0:$.id,n=[...this.videoTracksMap.keys()].find(({id:w})=>w===i),o=t.currentVideoTrack$.getValue(),u=((D=(V=e.videoStream.getState())!=null?V:n&&((G=this.videoTracksMap.get(n))==null?void 0:G.stream))!=null?D:this.videoStreamsMap.size===1)?this.videoStreamsMap.keys().next().value:void 0;if(!u)return;let c=[...this.videoStreamsMap.keys()].find(({id:w})=>w===u.id),l=c&&this.videoStreamsMap.get(c);if(!l)return;let d=lt(this.video.buffered,this.video.currentTime*1e3),p=r?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,h=Math.min(d/Math.min(p,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),f=(H=e.audioStream.getState())!=null?H:this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0,b=(N=[...this.audioStreamsMap.keys()].find(({id:w})=>w===(f==null?void 0:f.id)))!=null?N:this.audioStreamsMap.keys().next().value,g=0;if(b){if(n&&!r)if(this.params.tuning.useSeparateAudioVideoABR){let w=Ls(n,l,(L=this.audioStreamsMap.get(b))!=null?L:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);g=Math.max(g,(F=w==null?void 0:w.bitrate)!=null?F:-1/0)}else{let w=zs(n,l,(_=this.audioStreamsMap.get(b))!=null?_:[]);g=Math.max(g,(k=w==null?void 0:w.bitrate)!=null?k:-1/0)}if(o)if(this.params.tuning.useSeparateAudioVideoABR){let w=Ls(o,l,(x=this.audioStreamsMap.get(b))!=null?x:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);g=Math.max(g,(B=w==null?void 0:w.bitrate)!=null?B:-1/0)}else{let w=zs(o,l,(W=this.audioStreamsMap.get(b))!=null?W:[]);g=Math.max(g,(z=w==null?void 0:w.bitrate)!=null?z:-1/0)}}let S=Rt(l,{container:this.elementSize$.getValue(),throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:g,forwardBufferHealth:h,current:o,visible:this.params.output.elementVisible$.getValue(),history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),T=r?S!=null?S:n:n!=null?n:S,v;this.params.tuning.useSeparateAudioVideoABR?v=b&&Cb(T,l,(Z=this.audioStreamsMap.get(b))!=null?Z:[],{throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:h,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}):v=b&&zs(T,l,(le=this.audioStreamsMap.get(b))!=null?le:[]);let y=(Ot=this.videoTracksMap.get(T))==null?void 0:Ot.representation,I=v&&((gt=this.audioTracksMap.get(v))==null?void 0:gt.representation);if(y&&I)return[y,I];if(y&&!I&&this.audioTracksMap.size===0)return[y,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){ye(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:pc.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),be(this.video),this.tracer.end()}};var ya=class extends or{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 gS,interval as NR,map as FR}from"@vkontakte/videoplayer-shared";var Ta=class extends or{constructor(e){super(e),this.liveOffset=new ut}subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:r}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),r(t.timeUpdate$,e.liveBufferTime$),r(this.player.liveDuration$,e.duration$),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(gS({interval:NR(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(gS({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(FR(({liveBufferTime:i,liveAvailabilityStartTime:s})=>i&&s?i+s:void 0)).subscribe(e.liveTime$)).add(this.player.currentLiveTextRepresentation$.subscribe(i=>{if(i){let s=Ks(i,i);this.params.desiredState.internalTextTracks.startTransitionTo([s])}else this.params.desiredState.internalTextTracks.startTransitionTo([])}))}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 vS=Xe(ks(),1);import{assertNever as Ia,assertNonNullable as SS,debounce as qR,ErrorCategory as ln,filter as UR,isNonNullable as HR,isNullable as jR,map as dn,merge as GR,Observable as WR,observableFrom as YR,Subscription as QR,videoSizeToQuality as zR}from"@vkontakte/videoplayer-shared";var Qe={};var zr=(a,e)=>new WR(t=>{let r=(i,s)=>t.next(s);return a.on(e,r),()=>a.off(e,r)}),Ea=class{constructor(e){this.subscription=new QR;this.videoState=new C("initializing");this.textTracksManager=new Be;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:Ia(e)}break;case"ready":switch(e){case"stopped":this.prepare();break;case"ready":case"playing":case"paused":break;default:Ia(e)}break;case"playing":switch(e){case"playing":break;case"stopped":this.prepare();break;case"ready":case"paused":this.playIfAllowed();break;default:Ia(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:Ia(e)}break;default:Ia(t)}};this.video=me(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(re(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),be(this.video)}loadHlsJs(){let e=!1,t=i=>{e||this.params.output.error$.next({id:i==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:ln.NETWORK,message:"Failed to load Hls.js",thrown:i}),e=!0},r=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);(0,vS.default)(import("hls.js").then(i=>{e||(Qe.Hls=i.default,Qe.Events=i.default.Events,this.init())},t),()=>{window.clearTimeout(r),e=!0})}init(){SS(Qe.Hls,"hls.js not loaded"),this.hls=new Qe.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState("stopped")}subscribe(){SS(Qe.Events,"hls.js not loaded");let{desiredState:e,output:t}=this.params,r=c=>{t.error$.next({id:"HlsJsProvider",category:ln.WTF,message:"HlsJsProvider internal logic error",thrown:c})},i=Se(this.video),s=(c,l)=>this.subscription.add(c.subscribe(l,r));s(i.timeUpdate$,t.position$),s(i.durationChange$,t.duration$),s(i.ended$,t.endedEvent$),s(i.looped$,t.loopedEvent$),s(i.error$,t.error$),s(i.isBuffering$,t.isBuffering$),s(i.currentBuffer$,t.currentBuffer$),s(i.loadStart$,t.firstBytesEvent$),s(i.loadedMetadata$,t.loadedMetadataEvent$),s(i.playing$,t.firstFrameEvent$),s(i.canplay$,t.canplay$),s(i.seeked$,t.seekedEvent$),s(i.inPiP$,t.inPiP$),s(i.inFullscreen$,t.inFullscreen$),this.subscription.add(et(this.video,e.isLooped,r)),this.subscription.add(ge(this.video,e.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(De(this.video,e.playbackRate,i.playbackRateState$,r)),s(Ve(this.video),t.elementVisible$),s(this.videoState.stateChangeEnded$.pipe(dn(c=>c.to)),this.params.output.playbackState$),this.subscription.add(zr(this.hls,Qe.Events.ERROR).subscribe(c=>{var l;c.fatal&&t.error$.next({id:["HlsJsFatal",c.type,c.details].join("_"),category:ln.WTF,message:`HlsJs fatal ${c.type} ${c.details}, ${(l=c.err)==null?void 0:l.message} ${c.reason}`,thrown:c.error})})),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),E(e.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),E(e.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{var c;((c=this.videoState.getTransition())==null?void 0:c.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),s(zr(this.hls,Qe.Events.MANIFEST_PARSED).pipe(dn(({levels:c})=>c.reduce((l,d)=>{var T,v;let p=d.name||d.height.toString(10),{width:h,height:f}=d,b=(v=kt((T=d.attrs.QUALITY)!=null?T:""))!=null?v:zR({width:h,height:f});if(!b)return l;let g=d.attrs["FRAME-RATE"]?parseFloat(d.attrs["FRAME-RATE"]):void 0,S={id:p.toString(),quality:b,bitrate:d.bitrate/1e3,size:{width:h,height:f},fps:g};return this.trackLevels.set(p,{track:S,level:d}),l.push(S),l},[]))),t.availableVideoTracks$),s(zr(this.hls,Qe.Events.MANIFEST_PARSED),c=>{if(c.subtitleTracks.length>0){let l=[];for(let d of c.subtitleTracks){let p=d.name,h=d.attrs.URI||"",f=d.lang;l.push({id:p,url:h,language:f,type:"internal"})}e.internalTextTracks.startTransitionTo(l)}}),s(zr(this.hls,Qe.Events.LEVEL_LOADING).pipe(dn(({url:c})=>re(c))),t.hostname$),s(zr(this.hls,Qe.Events.FRAG_CHANGED),c=>{var p,h,f,b;let{video:l,audio:d}=c.frag.elementaryStreams;t.currentVideoSegmentLength$.next((((p=l==null?void 0:l.endPTS)!=null?p:0)-((h=l==null?void 0:l.startPTS)!=null?h:0))*1e3),t.currentAudioSegmentLength$.next((((f=d==null?void 0:d.endPTS)!=null?f:0)-((b=d==null?void 0:d.startPTS)!=null?b:0))*1e3)}),this.subscription.add(At(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,c=>{this.hls.nextLevel=c?-1:this.hls.currentLevel,this.hls.loadLevel=c?-1:this.hls.loadLevel},{onError:r}));let n=c=>{var l;return(l=Array.from(this.trackLevels.values()).find(({level:d})=>d===c))==null?void 0:l.track},o=zr(this.hls,Qe.Events.LEVEL_SWITCHED).pipe(dn(({level:c})=>n(this.hls.levels[c])));o.pipe(UR(HR)).subscribe(t.currentVideoTrack$,r),this.subscription.add(At(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel]),c=>{var f;if(jR(c))return;let l=(f=this.trackLevels.get(c.id))==null?void 0:f.level;if(!l)return;let d=this.hls.levels.indexOf(l),p=this.hls.currentLevel,h=this.hls.levels[p];!h||l.bitrate>h.bitrate?this.hls.nextLevel=d:(this.hls.loadLevel=d,this.hls.loadLevel=d)},{changed$:o,onError:r})),s(i.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);let u=GR(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,YR(["init"])).pipe(qR(0));this.subscription.add(u.subscribe(this.syncPlayback,r))}prepare(){this.videoState.startTransitionTo("ready"),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}playIfAllowed(){return R(this,null,function*(){this.videoState.startTransitionTo("playing"),(yield ye(this.video).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:ln.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 yS="X-Playback-Duration",fc=a=>R(void 0,null,function*(){var i;let e=yield dt(a),t=yield e.text(),r=(i=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t))==null?void 0:i[1];return r?parseInt(r,10):e.headers.has(yS)?parseInt(e.headers.get(yS),10):void 0});import{assertNever as t$,combine as r$,debounce as i$,ErrorCategory as hn,filter as a$,filterChanged as s$,isNonNullable as IS,isNullable as fn,map as ES,merge as n$,observableFrom as o$,Subscription as u$,ValueSubject as gc,VideoQuality as c$}from"@vkontakte/videoplayer-shared";var bc=Xe(Do(),1);import{videoSizeToQuality as KR,getExponentialDelay as JR}from"@vkontakte/videoplayer-shared";var XR=a=>{let e=null;if(a.QUALITY&&(e=kt(a.QUALITY)),!e&&a.RESOLUTION){let[t,r]=a.RESOLUTION.split("x").map(i=>parseInt(i,10));e=KR({width:t,height:r})}return e!=null?e:null},ZR=(a,e)=>{var s,n;let t=a.split(`
113
+ `),r=[],i=[];for(let o=0;o<t.length;o++){let u=t[o],c=u.match(/^#EXT-X-STREAM-INF:(.+)/),l=u.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!c&&!l)){if(c){let d=(0,bc.default)(c[1].split(",").map(T=>T.split("="))),p=(s=d.QUALITY)!=null?s:`stream-${d.BANDWIDTH}`,h=XR(d),f;d.BANDWIDTH&&(f=parseInt(d.BANDWIDTH,10)/1e3||void 0),!f&&d["AVERAGE-BANDWIDTH"]&&(f=parseInt(d["AVERAGE-BANDWIDTH"],10)/1e3||void 0);let b=d["FRAME-RATE"]?parseFloat(d["FRAME-RATE"]):void 0,g;if(d.RESOLUTION){let[T,v]=d.RESOLUTION.split("x").map(y=>parseInt(y,10));T&&v&&(g={width:T,height:v})}let S=new URL(t[++o],e).toString();h&&r.push({id:p,quality:h,url:S,bandwidth:f,size:g,fps:b})}if(l){let d=(0,bc.default)(l[1].split(",").map(b=>b.split("=")).map(([b,g])=>[b,g.replace(/^"|"$/g,"")])),p=(n=d.URI)==null?void 0:n.replace(/playlist$/,"subtitles.vtt"),h=d.LANGUAGE,f=d.NAME;p&&h&&i.push({type:"internal",id:h,label:f,language:h,url:p,isAuto:!1})}}}if(!r.length)throw new Error("Empty manifest");return{qualityManifests:r,textTracks:i}},e$=a=>new Promise(e=>{setTimeout(()=>{e()},a)}),mc=0,TS=(r,...i)=>R(void 0,[r,...i],function*(a,e=a,t){let n=yield(yield dt(a)).text();mc+=1;try{let{qualityManifests:o,textTracks:u}=ZR(n,e);return{qualityManifests:o,textTracks:u}}catch(o){if(mc<=t.manifestRetryMaxCount)return yield e$(JR(mc-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),TS(a,e,t)}return{qualityManifests:[],textTracks:[]}}),pn=TS;var xa=class{constructor(e){this.subscription=new u$;this.videoState=new C("stopped");this.textTracksManager=new Be;this.manifests$=new gc([]);this.liveOffset=new ut;this.manifestStartTime$=new gc(void 0);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),r=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(r==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),E(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let c=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||n||o){let l=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(l),this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),c.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if((i==null?void 0:i.to)!=="paused"&&c.state==="requested"){this.videoState.startTransitionTo("ready"),this.seek(c.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(t){case"ready":r==="ready"?E(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),E(this.params.desiredState.playbackState,"paused")):r==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":r==="paused"?(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(i==null?void 0:i.to)==="playing"&&E(this.params.desiredState.playbackState,"playing");return;case"paused":if(r==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let l=this.liveOffset.getTotalOffset();l>=this.maxSeekBackTime$.getValue()&&(l=0,this.liveOffset.resetTo(l)),this.liveOffset.resume(),this.params.output.position$.next(-l/1e3),this.prepare()}else(i==null?void 0:i.to)==="paused"&&(E(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return t$(t)}};var t;this.params=e,this.video=me(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:c$.INVARIANT,url:this.params.source.url},pn(ae(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:hn.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),this.manifests$.next([this.masterManifest,...r])},r=>this.params.output.error$.next({id:"ExtractHlsQualities",category:hn.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:r})),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(re(this.params.source.url)),this.maxSeekBackTime$=new gc((t=e.source.maxSeekBackTime)!=null?t:1/0),this.subscribe()}selectManifest(){var u,c,l,d;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,r=e.getState(),i=t.getTransition(),s=(d=(l=(u=i==null?void 0:i.to)==null?void 0:u.id)!=null?l:(c=t.getState())==null?void 0:c.id)!=null?d:"master",n=this.manifests$.getValue();if(!n.length)return;let o=r?"master":s;return r&&!i&&t.startTransitionTo(this.masterManifest),n.find(p=>p.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"HlsLiveProvider",category:hn.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},i=Se(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(ge(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(De(this.video,t.playbackRate,i.playbackRateState$,r)),s(Ve(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(s$(),ES(o=>-o/1e3)).subscribe(this.params.output.duration$,r)),this.subscription.add(i.loadedMetadata$.subscribe(()=>{let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),c=this.params.desiredState.videoTrack.getTransition(),l=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(c&&IS(c.to)){let d=c.to.id;this.params.desiredState.videoTrack.setState(c.to);let p=this.manifests$.getValue().find(h=>h.id===d);p&&(this.params.output.currentVideoTrack$.next(p),this.params.output.hostname$.next(re(p.url)))}l&&this.params.desiredState.autoVideoTrackSwitching.setState(l.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o&&o.state==="requested"&&this.seek(o.position)},r)),this.subscription.add(i.loadedData$.subscribe(()=>{var u,c,l;let o=(l=(c=(u=this.video)==null?void 0:u.getStartDate)==null?void 0:c.call(u))==null?void 0:l.getTime();this.manifestStartTime$.next(o||void 0)},r)),this.subscription.add(r$({startTime:this.manifestStartTime$.pipe(a$(IS)),currentTime:i.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),r)),this.subscription.add(this.manifests$.pipe(ES(o=>o.map(({id:u,quality:c,size:l,bandwidth:d,fps:p})=>({id:u,quality:c,size:l,fps:p,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,r));let n=n$(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,o$(["init"])).pipe(i$(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),be(this.video)}prepare(){var o,u;let e=this.selectManifest();if(fn(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),r=this.params.desiredState.autoVideoTrackLimits.getState(),i=new URL(e.url);if((t||r)&&e.id===this.masterManifest.id){let{max:c,min:l}=(u=(o=t==null?void 0:t.to)!=null?o:r)!=null?u:{};for(let[d,p]of[[c,"mq"],[l,"lq"]]){let h=String(parseFloat(d||""));p&&d&&i.searchParams.set(p,h)}}let s=this.params.format==="HLS_LIVE_CMAF"?2:0,n=ae(i.toString(),this.liveOffset.getTotalOffset(),s);this.video.setAttribute("src",n),this.video.load(),fc(n).then(c=>{var l;if(!fn(c))this.maxSeekBackTime$.next(c);else{let d=(l=this.params.source.maxSeekBackTime)!=null?l:this.maxSeekBackTime$.getValue();if(fn(d)||!isFinite(d))try{dt(n).then(p=>p.text()).then(p=>{var f;let h=(f=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(p))==null?void 0:f[1];if(h){let b=new URL(h,n).toString();fc(b).then(g=>{fn(g)||this.maxSeekBackTime$.next(g)})}})}catch(p){}}})}playIfAllowed(){ye(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:hn.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 l$,debounce as d$,ErrorCategory as Sc,fromEvent as vc,isNonNullable as p$,isNullable as h$,map as xS,merge as AS,observableFrom as PS,Subscription as f$,ValueSubject as m$,VideoQuality as b$,clientChecker as g$}from"@vkontakte/videoplayer-shared";var Aa=class{constructor(e){this.subscription=new f$;this.videoState=new C("stopped");this.textTracksManager=new Be;this.manifests$=new m$([]);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),r=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(r==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),E(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let c=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||n||o){let l=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(l);let{currentTime:d}=this.video;this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),c.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:d*1e3,forcePrecise:!0});return}switch((i==null?void 0:i.to)!=="paused"&&c.state==="requested"&&this.seek(c.position),t){case"ready":r==="ready"?E(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),E(this.params.desiredState.playbackState,"paused")):r==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":r==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(i==null?void 0:i.to)==="playing"&&E(this.params.desiredState.playbackState,"playing");return;case"paused":r==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&E(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return l$(t)}};this.params=e,this.video=me(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:b$.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(re(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),pn(ae(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:Sc.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){var u,c,l,d;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,r=e.getState(),i=t.getTransition(),s=(d=(l=(u=i==null?void 0:i.to)==null?void 0:u.id)!=null?l:(c=t.getState())==null?void 0:c.id)!=null?d:"master",n=this.manifests$.getValue();if(!n.length)return;let o=r?"master":s;return r&&!i&&t.startTransitionTo(this.masterManifest),n.find(p=>p.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"HlsProvider",category:Sc.WTF,message:"HlsProvider internal logic error",thrown:o})},i=Se(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(xS(o=>o.to)),this.params.output.playbackState$),this.subscription.add(et(this.video,t.isLooped,r)),this.subscription.add(ge(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(De(this.video,t.playbackRate,i.playbackRateState$,r)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),E(t.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),E(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())==null?void 0:o.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},r).add(i.loadedMetadata$.subscribe(()=>{var d;let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),c=this.params.desiredState.videoTrack.getTransition(),l=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(c&&p$(c.to)){let p=c.to.id;this.params.desiredState.videoTrack.setState(c.to);let h=this.manifests$.getValue().find(f=>f.id===p);if(h){this.params.output.currentVideoTrack$.next(h),this.params.output.hostname$.next(re(h.url));let f=this.params.desiredState.playbackRate.getState(),b=(d=this.params.output.element$.getValue())==null?void 0:d.playbackRate;if(f!==b){let g=this.params.output.element$.getValue();g&&(this.params.desiredState.playbackRate.setState(f),g.playbackRate=f)}}}l&&this.params.desiredState.autoVideoTrackSwitching.setState(l.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o.state==="requested"&&this.seek(o.position)},r))),this.subscription.add(this.manifests$.pipe(xS(o=>o.map(({id:u,quality:c,size:l,bandwidth:d,fps:p})=>({id:u,quality:c,size:l,fps:p,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,r)),!g$.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add(AS(vc(o,"addtrack"),vc(o,"removetrack"),vc(o,"change"),PS(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},r))}let n=AS(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,PS(["init"])).pipe(d$(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),be(this.video)}prepare(){var s,n;let e=this.selectManifest();if(h$(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),r=this.params.desiredState.autoVideoTrackLimits.getState(),i=new URL(e.url);if((t||r)&&e.id===this.masterManifest.id){let{max:o,min:u}=(n=(s=t==null?void 0:t.to)!=null?s:r)!=null?n:{};for(let[c,l]of[[o,"mq"],[u,"lq"]]){let d=String(parseFloat(c||""));l&&c&&i.searchParams.set(l,d)}}this.video.setAttribute("src",i.toString()),this.video.load()}playIfAllowed(){ye(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:Sc.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};import{assertNever as S$,assertNonNullable as wS,debounce as v$,ErrorCategory as kS,isHigher as y$,isHigherOrEqual as T$,isInvariantQuality as RS,isLowerOrEqual as I$,isNonNullable as E$,merge as x$,observableFrom as A$,Subscription as P$,map as w$}from"@vkontakte/videoplayer-shared";var Pa=class{constructor(e){this.subscription=new P$;this.videoState=new C("stopped");this.trackUrls={};this.textTracksManager=new Be;this.syncPlayback=()=>{var u,c,l;let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),E(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let s=this.params.desiredState.autoVideoTrackLimits.getTransition(),n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.seekState.getState();if(s&&e!=="ready"&&!n){this.handleQualityLimitTransition(s.to.max);return}if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(n){let{currentTime:d}=this.video;this.prepare(),o.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:d*1e3,forcePrecise:!0}),n.to&&((u=this.params.desiredState.autoVideoTrackLimits.getState())==null?void 0:u.max)!==((l=(c=this.trackUrls[n.to.id])==null?void 0:c.track)==null?void 0:l.quality)&&this.params.output.autoVideoTrackLimits$.next({max:void 0});return}switch((r==null?void 0:r.to)!=="paused"&&o.state==="requested"&&this.seek(o.position),e){case"ready":t==="ready"?E(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),E(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(r==null?void 0:r.to)==="playing"&&E(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&E(this.params.desiredState.playbackState,"paused");return;default:return S$(e)}};this.params=e,this.video=me(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:kS.WTF,message:"MpegProvider internal logic error",thrown:o})},i=Se(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(w$(o=>o.to)),this.params.output.playbackState$),this.subscription.add(et(this.video,t.isLooped,r)),this.subscription.add(ge(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(De(this.video,t.playbackRate,i.playbackRateState$,r)),s(Ve(this.video),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),E(t.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),E(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{var u,c;((u=this.videoState.getTransition())==null?void 0:u.to)==="ready"&&this.videoState.setState("ready");let o=this.params.desiredState.videoTrack.getTransition();if(o&&E$(o.to)){this.params.desiredState.videoTrack.setState(o.to),this.params.output.currentVideoTrack$.next(this.trackUrls[o.to.id].track);let l=this.params.desiredState.playbackRate.getState(),d=(c=this.params.output.element$.getValue())==null?void 0:c.playbackRate;if(l!==d){let p=this.params.output.element$.getValue();p&&(this.params.desiredState.playbackRate.setState(l),p.playbackRate=l)}}this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.textTracksManager.connect(this.video,t,e);let n=x$(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,A$(["init"])).pipe(v$(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),be(this.video)}prepare(){var r;let e=(r=this.params.desiredState.videoTrack.getState())==null?void 0:r.id;wS(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];wS(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=ha(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(re(t))}playIfAllowed(){ye(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:kS.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){var i,s,n,o;let t,r=e;if(e&&((i=this.params.output.currentVideoTrack$.getValue())==null?void 0:i.quality)!==e){let u=(s=Object.values(this.trackUrls).find(d=>!RS(d.track.quality)&&I$(d.track.quality,e)))==null?void 0:s.track,c=(n=this.params.desiredState.videoTrack.getState())==null?void 0:n.id,l=(o=this.trackUrls[c!=null?c:"0"])==null?void 0:o.track;if(u&&l&&T$(l.quality,u.quality)&&(t=u),!t){let d=Object.values(this.trackUrls).filter(h=>!RS(h.track.quality)&&y$(h.track.quality,e)),p=d.length;p&&(t=d[p-1].track)}t&&(r=t.quality)}else if(!e){let u=Object.values(this.trackUrls).map(c=>c.track);t=Rt(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 LS,debounce as L$,merge as MS,observableFrom as M$,Subscription as C$,map as CS,ValueSubject as D$,ErrorCategory as Tc,VideoQuality as B$}from"@vkontakte/videoplayer-shared";import{ErrorCategory as k$}from"@vkontakte/videoplayer-shared";var $S=["stun:videostun.mycdn.me:80"],R$=1e3,$$=3,yc=()=>null,mn=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=yc;this.externalStopCallback=yc;this.externalErrorCallback=yc;this.options=this.normalizeOptions(t);let r=e.split("/");this.serverUrl=r.slice(0,r.length-1).join("/"),this.streamKey=r[r.length-1]}onStart(e){try{this.externalStartCallback=e}catch(t){this.handleSystemError(t)}}onStop(e){try{this.externalStopCallback=e}catch(t){this.handleSystemError(t)}}onError(e){try{this.externalErrorCallback=e}catch(t){this.handleSystemError(t)}}connect(){this.connectWS()}disconnect(){try{this.externalStopCallback(),this.closeConnections()}catch(e){this.handleSystemError(e)}}connectWS(){this.ws||(this.ws=new WebSocket(this.serverUrl),this.ws.onopen=this.onSocketOpen.bind(this),this.ws.onmessage=this.onSocketMessage.bind(this),this.ws.onclose=this.onSocketClose.bind(this),this.ws.onerror=this.onSocketError.bind(this))}onSocketOpen(){this.handleLogin()}onSocketClose(e){try{if(!this.ws)return;this.ws=null,e.code>1e3?(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():this.scheduleRetry()):this.externalStopCallback()}catch(t){this.handleRTCError(t)}}onSocketError(e){try{this.externalErrorCallback(new Error(e.toString()))}catch(t){this.handleRTCError(t)}}onSocketMessage(e){try{let t=this.parseMessage(e.data);switch(t.type){case"JOIN":case"CALL_JOIN":this.handleJoinMessage(t);break;case"UPDATE":this.handleUpdateMessage(t);break;case"STATUS":this.handleStatusMessage(t);break}}catch(t){this.handleRTCError(t)}}handleJoinMessage(e){switch(e.inviteType){case"ANSWER":this.handleAnswer(e.sdp);break;case"CANDIDATE":this.handleCandidate(e.candidate);break}}handleStatusMessage(e){switch(e.status){case"UNPUBLISHED":this.handleUnpublished();break}}handleUpdateMessage(e){return R(this,null,function*(){try{let t=yield this.createOffer();this.peerConnection&&(yield this.peerConnection.setLocalDescription(t)),this.handleAnswer(e.sdp)}catch(t){this.handleRTCError(t)}})}handleLogin(){return R(this,null,function*(){try{let e={iceServers:[{urls:$S}]};this.peerConnection=new RTCPeerConnection(e),this.peerConnection.ontrack=this.onPeerConnectionStream.bind(this),this.peerConnection.onicecandidate=this.onPeerConnectionIceCandidate.bind(this),this.peerConnection.oniceconnectionstatechange=this.onPeerConnectionIceConnectionStateChange.bind(this);let t=yield this.createOffer();yield this.peerConnection.setLocalDescription(t),this.send({type:this.signalingType,inviteType:"OFFER",streamKey:this.streamKey,sdp:t.sdp,callSupport:!1})}catch(e){this.handleRTCError(e)}})}handleAnswer(e){return R(this,null,function*(){try{this.peerConnection&&(yield this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e})))}catch(t){this.handleRTCError(t)}})}handleCandidate(e){return R(this,null,function*(){if(e)try{this.peerConnection&&(yield this.peerConnection.addIceCandidate(e))}catch(t){this.handleRTCError(t)}})}handleUnpublished(){try{this.closeConnections(),this.externalStopCallback()}catch(e){this.handleRTCError(e)}}handleSystemError(e){this.options.errorChanel&&this.options.errorChanel.next({id:"webrtc-provider-error",category:k$.WTF,message:e.message})}onPeerConnectionStream(e){return R(this,null,function*(){let t=e.streams[0];this.stream&&this.stream.id===t.id||(this.stream=t,this.externalStartCallback(this.stream))})}onPeerConnectionIceCandidate(e){e.candidate&&this.send({type:this.signalingType,inviteType:"CANDIDATE",candidate:e.candidate})}onPeerConnectionIceConnectionStateChange(){if(this.peerConnection){let e=this.peerConnection.iceConnectionState;["failed","closed"].indexOf(e)>-1&&(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():(this.closeConnections(),this.scheduleRetry()))}}createOffer(){return R(this,null,function*(){let e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");let t=yield this.peerConnection.createOffer(e),r=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(r))throw new Error("No h264 codec support error");return t})}handleRTCError(e){try{this.externalErrorCallback(e||new Error("RTC connection error"))}catch(t){this.handleSystemError(t)}}handleNetworkError(){try{this.externalErrorCallback(new Error("Network error"))}catch(e){this.handleSystemError(e)}}send(e){this.ws&&this.ws.send(JSON.stringify(e))}parseMessage(e){try{return JSON.parse(e)}catch(t){throw new Error("Can not parse socket message")}}closeConnections(){let e=this.ws;e&&(this.ws=null,e.close(1e3)),this.removePeerConnection()}removePeerConnection(){let e=this.peerConnection;e&&(this.peerConnection=null,e.close(),e.ontrack=null,e.onicecandidate=null,e.oniceconnectionstatechange=null,e=null)}scheduleRetry(){this.retryTimeout=setTimeout(this.connectWS.bind(this),R$)}normalizeOptions(e={}){let t={stunServerList:$S,maxRetryNumber:$$,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var wa=class{constructor(e){this.videoState=new C("stopped");this.maxSeekBackTime$=new D$(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 LS(e)}};this.subscription=new C$,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=me(e.container,e.tuning),this.liveStreamClient=new mn(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),be(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,r=n=>{e.error$.next({id:"WebRTCLiveProvider",category:Tc.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};MS(this.videoState.stateChangeStarted$.pipe(CS(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe(CS(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})});let i=Se(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(Ve(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(ge(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 LS(n.to)}},r)).add(MS(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,M$(["init"])).pipe(L$(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(re(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:B$.INVARIANT}),this.video.srcObject=e,E(this.params.desiredState.playbackState,"playing")}onLiveStreamStop(){this.videoState.startTransitionTo("stopped"),this.syncPlayback(),this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.params.output.endedEvent$.next()}onLiveStreamError(e){this.onLiveStreamStop(),this.params.output.error$.next({id:"WebRTC stream runtime error",category:Tc.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){ye(this.video).then(e=>{e||(this.videoState.setState("paused"),E(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Tc.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var ka=class{constructor(e){this.iterator=e[Symbol.iterator](),this.next()}next(){this.current=this.iterator.next()}getValue(){if(this.current.done)throw new Error("Iterable is completed");return this.current.value}isCompleted(){return!!this.current.done}};import{assertNever as La,assertNonNullable as Mt,ErrorCategory as gn,filter as U$,isNonNullable as NS,isNullable as H$,map as j$,merge as G$,once as W$,Subject as we,Subscription as FS,ValueSubject as O,flattenObject as qS}from"@vkontakte/videoplayer-shared";import{Observable as O$,map as DS,Subscription as V$,Subject as _$}from"@vkontakte/videoplayer-shared";var BS=a=>new O$(e=>{let t=new V$,r=a.desiredPlaybackState$.stateChangeStarted$.pipe(DS(({from:c,to:l})=>`${c}-${l}`)),i=a.desiredPlaybackState$.stateChangeEnded$,s=a.providerChanged$.pipe(DS(({type:c})=>c!==void 0)),n=new _$,o=0,u="unknown";return t.add(r.subscribe(c=>{o&&window.clearTimeout(o),u=c,o=window.setTimeout(()=>n.next(c),a.maxTransitionInterval)})),t.add(i.subscribe(()=>{window.clearTimeout(o),u="unknown",o=0})),t.add(s.subscribe(c=>{o&&(window.clearTimeout(o),o=0,c&&(o=window.setTimeout(()=>n.next(u),a.maxTransitionInterval)))})),t.add(n.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});import{ErrorCategory as OS,Subscription as N$,combine as F$,filter as VS,once as _S}from"@vkontakte/videoplayer-shared";var Ra=null,bn=null;function Ic(){return Ra||(Ra=new(window.AudioContext||window.webkitAudioContext)),bn||(bn=new GainNode(Ra,{gain:1}),bn.connect(Ra.destination)),{audioCtx:Ra,gainNode:bn}}import{clientChecker as q$}from"@vkontakte/videoplayer-shared";var Kr=class Kr{constructor(e,t,r,i,s){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=r;this.volumeMultiplier=i;this.subscriptions=new N$;this.lastAudioContextResumeId=0;!s||!this.isSupported()||i===1||this.subscriptions.add(this.provider$.pipe(VS(n=>!!n.type),_S()).subscribe(({type:n})=>this.subscribe(n)))}subscribe(e){q$.isSafari&&e!=="MPEG"||this.subscriptions.add(F$({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe(VS(({playbackState:t,video:r,volume:{muted:i,volume:s}})=>t==="playing"&&!!r&&!i&&!!s),_S()).subscribe(({video:t})=>this.initAudioContextOnce(t)))}isSupported(){return"AudioContext"in window&&"GainNode"in window&&"MediaElementAudioSourceNode"in window}initAudioContextOnce(e){let{volumeMultiplier:t}=this,{audioCtx:r,gainNode:i}=Ic(),s=(Math.random()+1)*999999;this.lastAudioContextResumeId=s,r.resume().then(()=>{var n;if(s!==this.lastAudioContextResumeId)throw new Error(`AudioContext.resume() resolved after ${Kr.errorId} destroyed`);i.gain.value=t;try{new MediaElementAudioSourceNode(r,{mediaElement:e}).connect(i)}catch(o){this.volumeMultiplierError$.next({id:Kr.errorId,category:OS.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:Kr.errorId,category:OS.VIDEO_PIPELINE,message:(o=n==null?void 0:n.message)!=null?o:"initAudioContextOnce: AudioContext.resume() exception",thrown:n})})}destroy(){let{gainNode:e}=Ic();e.gain.value=1,this.subscriptions.unsubscribe(),this.lastAudioContextResumeId=0}};Kr.errorId="VolumeMultiplierManager";var $a=Kr;var Y$={chunkDuration:5e3,maxParallelRequests:5},Ma=class{constructor(e){this.current$=new O({type:void 0});this.providerError$=new we;this.noAvailableProvidersError$=new we;this.volumeMultiplierError$=new we;this.providerOutput={position$:new O(0),duration$:new O(1/0),volume$:new O({muted:!1,volume:1}),availableVideoStreams$:new O([]),currentVideoStream$:new O(void 0),availableVideoTracks$:new O([]),currentVideoTrack$:new O(void 0),availableAudioStreams$:new O([]),currentAudioStream$:new O(void 0),availableAudioTracks$:new O([]),currentVideoSegmentLength$:new O(0),currentAudioSegmentLength$:new O(0),isAudioAvailable$:new O(!0),autoVideoTrackLimitingAvailable$:new O(!1),autoVideoTrackLimits$:new O(void 0),currentBuffer$:new O(void 0),isBuffering$:new O(!0),error$:new we,warning$:new we,willSeekEvent$:new we,seekedEvent$:new we,loopedEvent$:new we,endedEvent$:new we,firstBytesEvent$:new we,loadedMetadataEvent$:new we,firstFrameEvent$:new we,canplay$:new we,isLive$:new O(void 0),isLowLatency$:new O(!1),canChangePlaybackSpeed$:new O(!0),liveTime$:new O(void 0),liveBufferTime$:new O(void 0),availableTextTracks$:new O([]),currentTextTrack$:new O(void 0),hostname$:new O(void 0),httpConnectionType$:new O(void 0),httpConnectionReused$:new O(void 0),inPiP$:new O(!1),inFullscreen$:new O(!1),element$:new O(void 0),elementVisible$:new O(!0),availableSources$:new O(void 0),is3DVideo$:new O(!1),playbackState$:new O("")};this.subscription=new FS;var o;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer"),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name);let t=ug([...lg(this.params.tuning),...cg(this.params.tuning)],this.params.tuning.useHlsJs,this.params.tuning.useManagedMediaSource).filter(u=>NS(e.sources[u])),{forceFormat:r,formatsToAvoid:i}=this.params.tuning,s=[];r?s=[r]:i.length?s=[...t.filter(u=>!i.includes(u)),...t.filter(u=>i.includes(u))]:s=t,this.log({message:`Selected formats: ${s.join(" > ")}`}),this.tracer.log("Selected formats",qS(s)),this.screenFormatsIterator=new ka(s);let n=[...Nu(!0),...Nu(!1)];this.chromecastFormatsIterator=new ka(n.filter(u=>NS(e.sources[u]))),this.providerOutput.availableSources$.next(e.sources),this.volumeMultiplierManager=new $a(this.providerOutput,this.current$,this.volumeMultiplierError$,(o=this.params.volumeMultiplier)!=null?o:1,this.params.tuning.useVolumeMultiplier)}init(){this.subscription.add(this.initProviderErrorHandling()),this.subscription.add(this.params.dependencies.chromecastInitializer.connection$.subscribe(()=>{this.reinitProvider()}))}destroy(){this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe(),this.volumeMultiplierManager.destroy(),this.tracer.end()}initProvider(){let e=this.chooseDestination(),t=this.chooseFormat(e);if(H$(t)){this.handleNoFormatsError(e);return}let r;try{r=this.createProvider(e,t)}catch(i){this.providerError$.next({id:"ProviderNotConstructed",category:gn.WTF,message:"Failed to create provider",thrown:i})}r?this.current$.next({type:t,provider:r,destination:e}):this.current$.next({type:void 0})}reinitProvider(){this.tracer.log("reinitProvider"),this.destroyProvider(),this.initProvider()}switchToNextProvider(e){this.tracer.log("switchToNextProvider",{destination:e}),this.destroyProvider(),this.failoverIndex=void 0,this.skipFormat(e),this.initProvider()}destroyProvider(){let e=this.current$.getValue().provider;if(!e)return;this.log({message:"destroyProvider"}),this.tracer.log("destroyProvider");let t=this.providerOutput.position$.getValue()*1e3,r=this.params.desiredState.seekState.getState(),i=r.state!=="none";if(this.params.desiredState.seekState.setState({state:"requested",position:i?r.position:t,forcePrecise:i?r.forcePrecise:!1}),e.scene3D){let n=e.scene3D.getCameraRotation();this.params.desiredState.cameraOrientation.setState({x:n.x,y:n.y})}e.destroy();let s=this.providerOutput.isBuffering$;s.getValue()||s.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),this.tracer.log("createProvider",{destination:e,format:t}),e){case"SCREEN":return this.createScreenProvider(t);case"CHROMECAST":return this.createChromecastProvider(t);default:return La(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 Mt(o),new ya(M(A({},n),{source:o,sourceHls:u}))}case"DASH_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return Mt(o),new Ta(M(A({},n),{source:o}))}case"HLS":case"HLS_ONDEMAND":{let o=this.applyFailoverHost(t[e]);return Mt(o),Nr||!this.params.tuning.useHlsJs?new Aa(M(A({},n),{source:o})):new Ea(M(A({},n),{source:o}))}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return Mt(o),new xa(M(A({},n),{source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e}))}case"MPEG":{let o=this.applyFailoverHost(t[e]);return Mt(o),new Pa(M(A({},n),{source:o}))}case"DASH_LIVE":{let o=this.applyFailoverHost(t[e]);return Mt(o),new jb(M(A({},n),{source:o,config:M(A({},Y$),{maxPausedTime:this.params.tuning.live.maxPausedTime})}))}case"WEB_RTC_LIVE":{let o=this.applyFailoverHost(t[e]);return Mt(o),new wa({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 La(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 Mt(o),new wi({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 La(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return La(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 La(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;let t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;let r=i=>{let s=new URL(i);return s.host=t,s.toString()};if(e===void 0)return e;if("type"in e){if(e.type==="raw")return e;if(e.type==="url")return M(A({},e),{url:r(e.url)})}return(0,US.default)(Object.entries(e).map(([i,s])=>[i,r(s)]))}initProviderErrorHandling(){let e=new FS,t=!1,r=0;return e.add(G$(this.providerOutput.error$,BS({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(j$(i=>({id:`ProviderHangup:${i}`,category:gn.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(U$(({to:s})=>s==="playing"),W$()).subscribe(()=>t=!0);e.add(i)})),e.add(this.providerError$.subscribe(i=>{let s=this.current$.getValue().destination,n={error:i,currentDestination:s};if(s==="CHROMECAST")this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider("SCREEN"),()=>this.params.dependencies.chromecastInitializer.disconnect());else{let o=i.category===gn.NETWORK,u=i.category===gn.FATAL,c=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),l=r<this.params.tuning.providerErrorLimit&&!u,d=c&&!u&&(o&&t||!l);n=M(A({},n),{isNetworkError:o,isFatalError:u,haveFailoverHost:c,tryFailover:d,canReinitProvider:l}),d?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):l?(r++,this.reinitProvider()):this.switchToNextProvider(s!=null?s:"SCREEN")}this.tracer.error("providerError",qS(n))})),e}};import{fromEvent as Sn,once as Q$,combine as z$,Subscription as HS,ValueSubject as Ec,map as K$,filter as J$,isNonNullable as vn,now as ke,safeStorage as xc}from"@vkontakte/videoplayer-shared";var X$=5e3,jS="one_video_throughput",GS="one_video_rtt",mt=window.navigator.connection,WS=()=>{let a=mt==null?void 0:mt.downlink;if(vn(a)&&a!==10)return a*1e3},YS=()=>{let a=mt==null?void 0:mt.rtt;if(vn(a)&&a!==3e3)return a},QS=(a,e,t)=>{let r=t*8,i=r/a;return r/(i+e)},Ac=class a{constructor(e){this.subscription=new HS;this.concurrentDownloads=new Set;var i,s;this.tuningConfig=e;let t=a.load(jS)||(e.useBrowserEstimation?WS():void 0)||X$,r=(s=(i=a.load(GS))!=null?i:e.useBrowserEstimation?YS():void 0)!=null?s:0;if(this.throughput$=new Ec(t),this.rtt$=new Ec(r),this.rttAdjustedThroughput$=new Ec(QS(t,r,e.rttPenaltyRequestSize)),this.throughput=sr.getSmoothedValue(t,-1,e),this.rtt=sr.getSmoothedValue(r,1,e),e.useBrowserEstimation){let n=()=>{let u=WS();u&&this.throughput.next(u);let c=YS();vn(c)&&this.rtt.next(c)};mt&&"onchange"in mt&&this.subscription.add(Sn(mt,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{xc.set(jS,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{xc.set(GS,n.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(z$({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(K$(({throughput:n,rtt:o})=>QS(n,o,e.rttPenaltyRequestSize)),J$(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=ke(),i=new HS;switch(this.subscription.add(i),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:i.add(Sn(e,"progress").pipe(Q$()).subscribe(s=>{t=s.loaded,r=ke()}));break;case 1:case 0:i.add(Sn(e,"loadstart").subscribe(()=>{t=0,r=ke()}));break}i.add(Sn(e,"loadend").subscribe(s=>{if(e.status===200){let n=s.loaded,o=ke(),u=n-t,c=o-r;this.addRawSpeed(u,c,1)}this.concurrentDownloads.delete(e),i.unsubscribe()}))}trackStream(e,t=!1){let r=e.getReader();if(!r){e.cancel("Could not get reader");return}let i=0,s=ke(),n=0,o=ke(),u=l=>{this.concurrentDownloads.delete(e),r.releaseLock(),e.cancel(`Throughput Estimator error: ${l}`).catch(()=>{})},c=p=>R(this,[p],function*({done:l,value:d}){if(l)!t&&this.addRawSpeed(i,ke()-s,1),this.concurrentDownloads.delete(e);else if(d){if(t){let h=ke();if(h-o>this.tuningConfig.lowLatency.continuesByteSequenceInterval||h-s>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let b=o-s;b&&this.addRawSpeed(n,b,1,t),n=d.byteLength,s=ke()}else n+=d.byteLength;o=ke()}else i+=d.byteLength,n+=d.byteLength,n>=this.tuningConfig.streamMinSampleSize&&ke()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,ke()-o,this.concurrentDownloads.size),n=0,o=ke());yield r==null?void 0:r.read().then(c,u)}});this.concurrentDownloads.add(e),r==null||r.read().then(c,u)}addRawSpeed(e,t,r=1,i=!1){if(a.sanityCheck(e,t,i)){let s=e*8/t;this.throughput.next(s*r)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,r=!1){let i=e*8/t;return!(!i||!isFinite(i)||i>1e6||i<30||r&&e<1e4||!r&&e<10*1024||!r&&t<=20)}static load(e){var r;let t=xc.get(e);if(vn(t))return(r=parseInt(t,10))!=null?r:void 0}},zS=Ac;import{fillWithDefault as Z$,VideoQuality as KS}from"@vkontakte/videoplayer-shared";var JS={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:KS.Q_4320P,activeVideoAreaThreshold:.1},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:KS.Q_480P},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,maxSegmentDurationLeftToSelectNextSegment:3e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:3e3,crashOnStallTimeout:25e3,enableSubSegmentBufferFeeding:!0,segmentTimelineTolerance:100,useFetchPriorityHints:!0},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:250,playbackCatchupSpeedup:.05,isActive:!1,delayEstimator:{emaAlpha:.45,changeThreshold:.05,deviationDepth:20,deviationFactor:.5,extremumInterval:5}}},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1,lowLatencyActiveLiveDelay:3e3,activeLiveDelay:5e3,maxPausedTime:5e3},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,forceFormat:void 0,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:void 0,useWebmBigRequest:!1,webmCodec:"vp9",androidPreferredFormat:"mpeg",preferCMAF:!1,preferWebRTC:!1,preferMultiStream:!1,preferHDR:!1,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,accumulationBufferStallSizeMs:0,requestQuick:!1,useHlsJs:!0,useDashAbortPartiallyFedSegment:!0,useNativeHLSTextTracks:!1,useManagedMediaSource:!1,useNewPruneBufferStrategy:!1,useNewPartialSegmentFeeding:!1,useSeparateAudioVideoABR:!1,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,manifestRetryInterval:300,manifestRetryMaxInterval:1e4,manifestRetryMaxCount:10,audioVideoSyncRate:20,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50},useVolumeMultiplier:!1},XS=a=>{var e;return M(A({},Z$(a,JS)),{configName:[...(e=a.configName)!=null?e:[],...JS.configName]})};import{assertNonNullable as yn,combine as Ct,ErrorCategory as Tn,filter as ce,filterChanged as U,fromEvent as wc,isNonNullable as nL,isNullable as oL,Logger as uL,map as q,mapTo as rv,merge as Dt,now as In,once as bt,Subject as Q,Subscription as iv,tap as av,ValueSubject as P,isHigher as cL,isInvariantQuality as sv,flattenObject as Bt,throttle as kc,getTraceSubscriptionMethod as nv,Tracer as lL}from"@vkontakte/videoplayer-shared";import{merge as eL,map as tL,filter as ZS,isNonNullable as rL}from"@vkontakte/videoplayer-shared";var Pc=({seekState:a,position$:e})=>eL(a.stateChangeEnded$.pipe(tL(({to:t})=>{var r;return t.state==="none"?void 0:((r=t.position)!=null?r:NaN)/1e3}),ZS(rL)),e.pipe(ZS(()=>a.getState().state==="none")));import{assertNonNullable as iL}from"@vkontakte/videoplayer-shared";var ev=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 aL,once as sL}from"@vkontakte/videoplayer-shared";var tv=(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(aL(i=>i.length>0),sL()).subscribe(i=>{i.find(r)&&e.startTransitionTo(a)}):(a===void 0||t!=null&&t.getValue().find(r))&&e.startTransitionTo(a)};var En=class{constructor(e={configName:[]},t=lL.createRootTracer(!1)){this.subscription=new iv;this.logger=new uL;this.abrLogger=this.logger.createComponentLog("ABR");this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new P(!1);this.hasLiveOffsetByPausedTimer=0;this.desiredState={playbackState:new C("stopped"),seekState:new C({state:"none"}),volume:new C({volume:1,muted:!1}),videoTrack:new C(void 0),videoStream:new C(void 0),audioStream:new C(void 0),autoVideoTrackSwitching:new C(!0),autoVideoTrackLimits:new C({}),isLooped:new C(!1),playbackRate:new C(1),externalTextTracks:new C([]),internalTextTracks:new C([]),currentTextTrack:new C(void 0),textTrackCuesSettings:new C({}),cameraOrientation:new C({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 Q,ready$:new Q,started$:new Q,playing$:new Q,paused$:new Q,stopped$:new Q,willStart$:new Q,willResume$:new Q,willPause$:new Q,willStop$:new Q,willDestruct$:new Q,watchCoverageRecord$:new Q,watchCoverageLive$:new Q,managedError$:new Q,fatalError$:new Q,ended$:new Q,looped$:new Q,seeked$:new Q,willSeek$:new Q,firstBytes$:new Q,loadedMetadata$:new Q,firstFrame$:new Q,canplay$:new Q,log$:new Q};this.experimental={element$:new P(void 0),tuningConfigName$:new P([]),enableDebugTelemetry$:new P(!1),dumpTelemetry:Eb};if(this.initLogs(),this.tuning=XS(e),this.tracer=t,this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new Ya({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new zS(this.tuning.throughputEstimator),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(r,i,s)=>{let n=Reflect.get(r,i,s);return typeof n!="function"?n:(...o)=>{try{return n.apply(r,o)}catch(u){let c=o.map(p=>JSON.stringify(p,(h,f)=>{let b=typeof f;return["number","string","boolean"].includes(b)?f:f===null?null:`<${b}>`})),l=`Player.${String(i)}`,d=`Exception calling ${l} (${c.join(", ")})`;throw this.events.fatalError$.next({id:l,category:Tn.WTF,message:d,thrown:u}),u}}}})}initVideo(e){var t,r,i;return this.config=e,this.tracer.log("initVideo",Bt(e)),this.domContainer=ev(e),this.chromecastInitializer.contentId=(t=e.meta)==null?void 0:t.videoId,this.providerContainer=new Ma({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,tracer:this.tracer,logger:this.logger,abrLogger:this.abrLogger},tuning:this.tuning,volumeMultiplier:e.volumeMultiplier}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.initTracerSubscription(),this.providerContainer.init(),this.setMuted(this.tuning.isAudioDisabled),this.initDebugTelemetry(),this.initWakeLock(),this}destroy(){var e;this.tracer.log("destroy"),window.clearTimeout(this.hasLiveOffsetByPausedTimer),this.events.willDestruct$.next(),this.stop(),(e=this.providerContainer)==null||e.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe(),this.tracer.end()}prepare(){let e=this.desiredState.playbackState;return this.tracer.log("prepare",{currentPlayBackState:e.getState()}),e.getState()==="stopped"&&e.startTransitionTo("ready"),this}play(){let e=()=>{let t=this.desiredState.playbackState;this.tracer.log("play",{currentPlayBackState:t.getState()}),t.getState()!=="playing"&&t.startTransitionTo("playing")};return document.hidden&&this.tuning.autoplayOnlyInActiveTab&&!Vi()?(this.tracer.log("request play from hidden tab"),wc(document,"visibilitychange").pipe(bt()).subscribe(e)):e(),this}pause(){let e=this.desiredState.playbackState;return this.tracer.log("pause",{currentPlayBackState:e.getState()}),e.getState()!=="paused"&&e.startTransitionTo("paused"),this}stop(){let e=this.desiredState.playbackState;return this.tracer.log("stop",{currentPlayBackState:e.getState()}),e.getState()!=="stopped"&&e.startTransitionTo("stopped"),this}seekTime(e,t=!0){let r=this.info.duration$.getValue(),i=this.info.isLive$.getValue(),s=e;return e>=r&&!i&&(s=r-.1),this.tracer.log("seekTime",{duration:r,isLive:i,time:e,calculatedTime:s,forcePrecise:t}),this.events.willSeek$.next({from:this.getExactTime(),to:s}),this.desiredState.seekState.setState({state:"requested",position:s*1e3,forcePrecise:t}),this}seekPercent(e){let t=this.info.duration$.getValue();return this.tracer.log("seekPercent",{percent:e,duration:t}),isFinite(t)&&this.seekTime(Math.abs(t)*e,!1),this}setVolume(e){let t=this.tuning.isAudioDisabled||this.desiredState.volume.getState().muted;return this.tracer.log("setVolume",{volume:e,isAudioDisabled:this.tuning.isAudioDisabled,isDesiredStateMuted:this.desiredState.volume.getState().muted,chromecastState:this.chromecastInitializer.castState$.getValue(),muted:t}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setVolume(e):this.desiredState.volume.startTransitionTo({volume:e,muted:t}),this}setMuted(e){let t=this.tuning.isAudioDisabled||e;return this.tracer.log("setMuted",{isMuted:e,isAudioDisabled:this.tuning.isAudioDisabled,desiredStateVolume:this.desiredState.volume.getState().volume,chromecastState:this.chromecastInitializer.castState$.getValue(),muted:t}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setMuted(t):this.desiredState.volume.startTransitionTo({volume:this.desiredState.volume.getState().volume,muted:t}),this}setVideoStream(e){return this.desiredState.videoStream.startTransitionTo(e),this}setAudioStream(e){return this.desiredState.audioStream.startTransitionTo(e),this}setQuality(e){yn(this.providerContainer);let t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();return this.tracer.log("setQuality",{isDelayed:t.length===0,quality:e}),this.desiredState.videoTrack.getState()===void 0&&this.desiredState.videoTrack.getPrevState()===void 0&&t.length===0?this.providerContainer.providerOutput.availableVideoTracks$.pipe(ce(r=>r.length>0),bt()).subscribe(r=>{this.setVideoTrackIdByQuality(r,e)}):t.length>0&&this.setVideoTrackIdByQuality(t,e),this}setAutoQuality(e){return this.tracer.log("setAutoQuality",{enable:e}),this.desiredState.autoVideoTrackSwitching.startTransitionTo(e),this}setAutoQualityLimits(e){return this.tracer.log("setAutoQualityLimits",Bt(e)),this.desiredState.autoVideoTrackLimits.startTransitionTo(e),this}setPlaybackRate(e){var r;yn(this.providerContainer);let t=(r=this.providerContainer)==null?void 0:r.providerOutput.element$.getValue();return this.tracer.log("setPlaybackRate",{playbackRate:e,isVideoElementAvailable:!!t}),t&&(this.desiredState.playbackRate.setState(e),t.playbackRate=e),this}setExternalTextTracks(e){return e.length&&this.tracer.log("setExternalTextTracks",Bt(e)),this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>A({type:"external"},t))),this}selectTextTrack(e){var t;return tv(e,this.desiredState.currentTextTrack,(t=this.providerContainer)==null?void 0:t.providerOutput.availableTextTracks$,r=>r.id===e),this.tracer.log("selectTextTrack",{textTrackId:e}),this}setTextTrackCueSettings(e){return this.tracer.log("setTextTrackCueSettings",A({},e)),this.desiredState.textTrackCuesSettings.startTransitionTo(e),this}setLooped(e){return this.tracer.log("setLooped",{isLooped:e}),this.desiredState.isLooped.startTransitionTo(e),this}toggleChromecast(){this.tracer.log("toggleChromecast"),this.chromecastInitializer.toggleConnection()}startCameraManualRotation(e,t){let r=this.getScene3D();return this.tracer.log("startCameraManualRotation",{isScene3DAvailable:!!r,mx:e,my:t}),r&&r.startCameraManualRotation(e,t),this}stopCameraManualRotation(e=!1){let t=this.getScene3D();return this.tracer.log("stopCameraManualRotation",{isScene3DAvailable:!!t,immediate:e}),t&&t.stopCameraManualRotation(e),this}moveCameraFocusPX(e,t){let r=this.getScene3D();if(this.tracer.log("moveCameraFocusPX",{isScene3DAvailable:!!r,dxpx:e,dypx:t}),r){let i=r.getCameraRotation(),s=r.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:i.x+s.x,y:i.y+s.y})}return this}holdCamera(){let e=this.getScene3D();return e&&e.holdCamera(),this}releaseCamera(){let e=this.getScene3D();return e&&e.releaseCamera(),this}getExactTime(){if(!this.providerContainer)return 0;let e=this.providerContainer.providerOutput.element$.getValue();if(oL(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),r=t.state==="none"?void 0:t.position;return nL(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(Dt(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(q(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(q(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(q(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(q(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(q(e=>e.to)).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(ce(({from:e})=>e==="stopped"),bt()).subscribe(()=>{this.initedAt=In(),this.events.inited$.next()})).add(this.desiredState.playbackState.stateChangeEnded$.subscribe(e=>{switch(e.to){case"ready":this.events.ready$.next();break;case"playing":this.isPlaybackStarted||this.events.started$.next(),this.isPlaybackStarted=!0,this.events.playing$.next();break;case"paused":this.events.paused$.next();break;case"stopped":this.events.stopped$.next()}})).add(this.desiredState.playbackState.stateChangeStarted$.subscribe(e=>{switch(e.to){case"paused":this.events.willPause$.next();break;case"playing":this.isPlaybackStarted?this.events.willResume$.next():this.events.willStart$.next();break;case"stopped":this.events.willStop$.next();break;default:}}))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();this.tracer.log("willSeekEvent",Bt(n)),n.state==="requested"?this.desiredState.seekState.setState(M(A({},n),{state:"applying"})):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:Tn.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.seekedEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();this.tracer.log("seekedEvent",Bt(n)),n.state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe(q(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(q(n=>n.destination),U()).subscribe(()=>this.isPlaybackStarted=!1)).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add(e.providerOutput.availableVideoTracks$.pipe(q(n=>n.map(({quality:o})=>o).sort((o,u)=>sv(o)?1:sv(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$.pipe(U()).subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{this.info.currentQuality$.next(n==null?void 0:n.quality),this.info.videoBitrate$.next(n==null?void 0:n.bitrate)})).add(e.providerOutput.currentVideoSegmentLength$.pipe(U((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.pipe(U((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe(U()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(U()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(U()).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(q(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(Ct({hasLiveOffsetByPaused:Dt(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(q(n=>n.to),U(),q(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(Ct({atLiveEdge:Ct({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:Pc({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(q(({isLive:n,position:o,isLowLatency:u})=>{let c=this.getActiveLiveDelay(u);return n&&Math.abs(o)<c/1e3}),U(),av(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(q(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add(Ct({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(q(({isLive:n,position:o,duration:u})=>n&&(Math.abs(u)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),U(),av(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(q(n=>n.muted),U()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(q(n=>n.volume),U()).subscribe(this.info.volume$)).add(Pc({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(Dt(e.providerOutput.endedEvent$.pipe(rv(!0)),e.providerOutput.seekedEvent$.pipe(rv(!1))).pipe(U()).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(q(n=>({id:n?`No${n}`:"NoProviders",category:Tn.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(bt(),q(n=>n!=null?n:In()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe(bt(),q(()=>In()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(bt(),q(()=>In()-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(ce(({to:n})=>n==="playing"),bt()).subscribe(()=>r.next(!1)));let i=0,s=Dt(e.providerOutput.isBuffering$,t,r).pipe(q(()=>{let n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||r.getValue();return n&&!o}),U());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(Dt(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{let n=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:n==null?void 0:n.videoWidth,height:n==null?void 0:n.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{var u,c;let o=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:(u=n==null?void 0:n.size)==null?void 0:u.width,height:(c=n==null?void 0:n.size)==null?void 0:c.height},{width:o==null?void 0:o.videoWidth,height:o==null?void 0:o.videoHeight})})).add(e.providerOutput.is3DVideo$.subscribe(this.info.is3DVideo$)),this.subscription.add(Dt(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,e.providerOutput.elementVisible$,this.chromecastInitializer.castState$).subscribe(()=>{let n=e.providerOutput.inPiP$.getValue(),o=e.providerOutput.inFullscreen$.getValue(),u=e.providerOutput.element$.getValue(),c=e.providerOutput.elementVisible$.getValue(),l=this.chromecastInitializer.castState$.getValue(),d;l==="CONNECTED"?d="second_screen":u?c?n?d="pip":o?d="fullscreen":d="inline":d="invisible":d="none",this.info.surface$.getValue()!==d&&this.info.surface$.next(d)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(q(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 iv;this.subscription.add(t),this.subscription.add(e.current$.pipe(U((r,i)=>r.provider===i.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(ce(r=>r.length>0),bt()).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=Rt(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(Dt(this.desiredState.videoTrack.stateChangeStarted$.pipe(q(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(q(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(q(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(q(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(q(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(q(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(q(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(q(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(q(e=>({component:"desiredState",message:`[${e.entity} change] ${e.type}: ${JSON.stringify(e.transition)}`}))).subscribe(this.logger.log)),this.subscription.add(this.logger.log$.subscribe(this.events.log$))}initDebugTelemetry(){var t;let e=(t=this.providerContainer)==null?void 0:t.providerOutput;yn(this.providerContainer),yn(e),Ib(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(r=>Tb(r)),this.providerContainer.current$.subscribe(({type:r})=>Li("provider",r)),e.duration$.subscribe(r=>Li("duration",r)),e.availableVideoTracks$.pipe(ce(r=>!!r.length),bt()).subscribe(r=>Li("tracks",r)),this.events.fatalError$.subscribe(new ue("fatalError")),this.events.managedError$.subscribe(new ue("managedError")),e.position$.subscribe(new ue("position")),e.currentVideoTrack$.pipe(q(r=>r==null?void 0:r.quality)).subscribe(new ue("quality")),this.info.currentBuffer$.subscribe(new ue("buffer")),e.isBuffering$.subscribe(new ue("isBuffering"))].forEach(r=>this.subscription.add(r)),Li("codecs",og())}initTracerSubscription(){let e=nv(this.tracer.log.bind(this.tracer)),t=nv(this.tracer.error.bind(this.tracer));this.subscription.add(this.info.playbackState$.subscribe(e("playbackState"))).add(this.info.isLooped$.subscribe(e("isLooped"))).add(this.info.currentPlaybackRate$.pipe(U()).subscribe(e("currentPlaybackRate"))).add(this.info.isAutoQualityEnabled$.subscribe(e("isAutoQualityEnabled"))).add(this.info.autoQualityLimits$.subscribe(e("autoQualityLimits"))).add(this.info.currentFormat$.subscribe(e("currentFormat"))).add(this.info.availableQualities$.subscribe(e("availableQualities"))).add(this.info.availableQualitiesFps$.subscribe(e("availableQualitiesFps"))).add(this.info.availableAudioTracks$.subscribe(e("availableAudioTracks"))).add(this.info.isAudioAvailable$.subscribe(e("isAudioAvailable"))).add(Ct({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe(ce(({currentQuality:r,videoBitrate:i})=>!!r&&!!i),U((r,i)=>r.currentQuality===i.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe(ce(r=>r>0),U()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe(ce(r=>r>0),U()).subscribe(e("currentAudioSegmentLength"))).add(this.info.hostname$.subscribe(e("hostname"))).add(this.info.currentTextTrack$.subscribe(e("currentTextTrack"))).add(this.info.availableTextTracks$.subscribe(e("availableTextTracks"))).add(this.info.autoQualityLimitingAvailable$.subscribe(e("autoQualityLimitingAvailable"))).add(Ct({currentBuffer:this.info.currentBuffer$.pipe(ce(r=>r.end>0),U((r,i)=>r.end===i.end&&r.start===i.start)),position:this.info.position$.pipe(U())}).pipe(kc(1e3)).subscribe(e("currentBufferAndPosition"))).add(this.info.duration$.pipe(U()).subscribe(e("duration"))).add(this.info.isBuffering$.subscribe(e("isBuffering"))).add(this.info.isLive$.pipe(U()).subscribe(e("isLive"))).add(this.info.canChangePlaybackSpeed$.pipe(U()).subscribe(e("canChangePlaybackSpeed"))).add(Ct({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe(ce(({liveTime:r,liveBufferTime:i})=>!!r&&!!i),kc(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe(U(),ce(r=>r===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe(U(),ce(r=>r===!0)).subscribe(e("atLiveDurationEdge"))).add(this.info.muted$.pipe(U()).subscribe(e("muted"))).add(this.info.volume$.pipe(U()).subscribe(e("volume"))).add(this.info.isEnded$.pipe(U(),ce(r=>r===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add(Ct({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe(ce(({throughputEstimation:r,rtt:i})=>!!r&&!!i),kc(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe(U(),ce(r=>r===!0)).subscribe(e("is3DVideo"))).add(this.info.surface$.subscribe(e("surface"))).add(this.events.ended$.subscribe(e("ended"))).add(this.events.looped$.subscribe(e("looped"))).add(this.events.managedError$.subscribe(t("managedError"))).add(this.events.fatalError$.subscribe(t("fatalError"))).add(this.events.firstBytes$.subscribe(e("firstBytes"))).add(this.events.firstFrame$.subscribe(e("firstFrame"))).add(this.events.canplay$.subscribe(e("canplay")))}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e,t=()=>{e==null||e.release(),e=void 0},r=()=>R(this,null,function*(){t(),e=yield window.navigator.wakeLock.request("screen").catch(i=>{i instanceof DOMException&&i.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:Tn.DOM,message:String(i)})})});this.subscription.add(Dt(wc(document,"visibilitychange"),wc(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{let i=document.visibilityState==="visible",s=this.desiredState.playbackState.getState()==="playing",n=!!e&&!(e!=null&&e.released);i&&s?n||r():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){let r=e.find(i=>i.quality===t);this.tracer.log("setVideoTrackIdByQuality",Bt({quality:t,availableTracks:Bt(e),track:Bt(r),isAutoQuality:!r})),r?this.desiredState.videoTrack.startTransitionTo(r):this.setAutoQuality(!0)}getActiveLiveDelay(e=!1){return e?this.tuning.live.lowLatencyActiveLiveDelay:this.tuning.live.activeLiveDelay}};import{Subscription as MW,Observable as CW,Subject as DW,ValueSubject as BW,VideoQuality as OW}from"@vkontakte/videoplayer-shared";var VW=`@vkontakte/videoplayer-core@${cl}`;export{Ga as ChromecastState,$n as HttpConnectionType,CW as Observable,he as PlaybackState,En as Player,VW as SDK_VERSION,DW as Subject,MW as Subscription,Ln as Surface,cl as VERSION,BW as ValueSubject,Et as VideoFormat,OW as VideoQuality};