@vkontakte/videoplayer-core 2.0.111-dev.974e99b3.0 → 2.0.111-dev.ae3e5b42.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/esnext.esm.js CHANGED
@@ -1,18 +1,18 @@
1
1
  /**
2
- * @vkontakte/videoplayer-core v2.0.111-dev.974e99b3.0
3
- * Thu, 19 Sep 2024 08:04:36 GMT
2
+ * @vkontakte/videoplayer-core v2.0.111-dev.ae3e5b42.0
3
+ * Wed, 02 Oct 2024 09:38:29 GMT
4
4
  * https://st.mycdn.me/static/vkontakte-videoplayer/2-0-111/doc/
5
5
  */
6
- var Ug=Object.create;var Hu=Object.defineProperty;var Hg=Object.getOwnPropertyDescriptor;var jg=Object.getOwnPropertyNames;var Gg=Object.getPrototypeOf,Wg=Object.prototype.hasOwnProperty;var f=(i,e)=>()=>(e||i((e={exports:{}}).exports,e),e.exports);var Yg=(i,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of jg(e))!Wg.call(i,a)&&a!==t&&Hu(i,a,{get:()=>e[a],enumerable:!(r=Hg(e,a))||r.enumerable});return i};var Ne=(i,e,t)=>(t=i!=null?Ug(Gg(i)):{},Yg(e||!i||!i.__esModule?Hu(t,"default",{value:i,enumerable:!0}):t,i));var fe=f((qR,Ju)=>{"use strict";Ju.exports=function(i){try{return!!i()}catch{return!0}}});var $r=f((UR,Xu)=>{"use strict";var tS=fe();Xu.exports=!tS(function(){var i=function(){}.bind();return typeof i!="function"||i.hasOwnProperty("prototype")})});var ae=f((HR,tc)=>{"use strict";var Zu=$r(),ec=Function.prototype,Ys=ec.call,rS=Zu&&ec.bind.bind(Ys,Ys);tc.exports=Zu?rS:function(i){return function(){return Ys.apply(i,arguments)}}});var Yt=f((jR,ic)=>{"use strict";var rc=ae(),iS=rc({}.toString),aS=rc("".slice);ic.exports=function(i){return aS(iS(i),8,-1)}});var sc=f((GR,ac)=>{"use strict";var sS=ae(),nS=fe(),oS=Yt(),Qs=Object,uS=sS("".split);ac.exports=nS(function(){return!Qs("z").propertyIsEnumerable(0)})?function(i){return oS(i)==="String"?uS(i,""):Qs(i)}:Qs});var Qt=f((WR,nc)=>{"use strict";nc.exports=function(i){return i==null}});var Lr=f((YR,oc)=>{"use strict";var cS=Qt(),lS=TypeError;oc.exports=function(i){if(cS(i))throw new lS("Can't call method on "+i);return i}});var zt=f((QR,uc)=>{"use strict";var dS=sc(),pS=Lr();uc.exports=function(i){return dS(pS(i))}});var zs=f((zR,cc)=>{"use strict";cc.exports=function(){}});var It=f((KR,lc)=>{"use strict";lc.exports={}});var H=f((Ks,dc)=>{"use strict";var Mr=function(i){return i&&i.Math===Math&&i};dc.exports=Mr(typeof globalThis=="object"&&globalThis)||Mr(typeof window=="object"&&window)||Mr(typeof self=="object"&&self)||Mr(typeof global=="object"&&global)||Mr(typeof Ks=="object"&&Ks)||function(){return this}()||Function("return this")()});var U=f((JR,pc)=>{"use strict";var Js=typeof document=="object"&&document.all;pc.exports=typeof Js>"u"&&Js!==void 0?function(i){return typeof i=="function"||i===Js}:function(i){return typeof i=="function"}});var mc=f((XR,fc)=>{"use strict";var hS=H(),fS=U(),hc=hS.WeakMap;fc.exports=fS(hc)&&/native code/.test(String(hc))});var ve=f((ZR,bc)=>{"use strict";var mS=U();bc.exports=function(i){return typeof i=="object"?i!==null:mS(i)}});var ye=f((e$,gc)=>{"use strict";var bS=fe();gc.exports=!bS(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var ha=f((t$,vc)=>{"use strict";var gS=H(),Sc=ve(),Xs=gS.document,SS=Sc(Xs)&&Sc(Xs.createElement);vc.exports=function(i){return SS?Xs.createElement(i):{}}});var Zs=f((r$,yc)=>{"use strict";var vS=ye(),yS=fe(),TS=ha();yc.exports=!vS&&!yS(function(){return Object.defineProperty(TS("div"),"a",{get:function(){return 7}}).a!==7})});var en=f((i$,Tc)=>{"use strict";var IS=ye(),ES=fe();Tc.exports=IS&&ES(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var Fe=f((a$,Ic)=>{"use strict";var xS=ve(),PS=String,AS=TypeError;Ic.exports=function(i){if(xS(i))return i;throw new AS(PS(i)+" is not an object")}});var me=f((s$,Ec)=>{"use strict";var kS=$r(),fa=Function.prototype.call;Ec.exports=kS?fa.bind(fa):function(){return fa.apply(fa,arguments)}});var ma=f((n$,xc)=>{"use strict";xc.exports={}});var He=f((o$,Ac)=>{"use strict";var tn=ma(),rn=H(),wS=U(),Pc=function(i){return wS(i)?i:void 0};Ac.exports=function(i,e){return arguments.length<2?Pc(tn[i])||Pc(rn[i]):tn[i]&&tn[i][e]||rn[i]&&rn[i][e]}});var Cr=f((u$,kc)=>{"use strict";var RS=ae();kc.exports=RS({}.isPrototypeOf)});var Kt=f((c$,$c)=>{"use strict";var $S=H(),wc=$S.navigator,Rc=wc&&wc.userAgent;$c.exports=Rc?String(Rc):""});var sn=f((l$,Vc)=>{"use strict";var Bc=H(),an=Kt(),Lc=Bc.process,Mc=Bc.Deno,Cc=Lc&&Lc.versions||Mc&&Mc.version,Dc=Cc&&Cc.v8,Le,ba;Dc&&(Le=Dc.split("."),ba=Le[0]>0&&Le[0]<4?1:+(Le[0]+Le[1]));!ba&&an&&(Le=an.match(/Edge\/(\d+)/),(!Le||Le[1]>=74)&&(Le=an.match(/Chrome\/(\d+)/),Le&&(ba=+Le[1])));Vc.exports=ba});var nn=f((d$,_c)=>{"use strict";var Oc=sn(),LS=fe(),MS=H(),CS=MS.String;_c.exports=!!Object.getOwnPropertySymbols&&!LS(function(){var i=Symbol("symbol detection");return!CS(i)||!(Object(i)instanceof Symbol)||!Symbol.sham&&Oc&&Oc<41})});var on=f((p$,Nc)=>{"use strict";var DS=nn();Nc.exports=DS&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var un=f((h$,Fc)=>{"use strict";var BS=He(),VS=U(),OS=Cr(),_S=on(),NS=Object;Fc.exports=_S?function(i){return typeof i=="symbol"}:function(i){var e=BS("Symbol");return VS(e)&&OS(e.prototype,NS(i))}});var Dr=f((f$,qc)=>{"use strict";var FS=String;qc.exports=function(i){try{return FS(i)}catch{return"Object"}}});var je=f((m$,Uc)=>{"use strict";var qS=U(),US=Dr(),HS=TypeError;Uc.exports=function(i){if(qS(i))return i;throw new HS(US(i)+" is not a function")}});var Br=f((b$,Hc)=>{"use strict";var jS=je(),GS=Qt();Hc.exports=function(i,e){var t=i[e];return GS(t)?void 0:jS(t)}});var Gc=f((g$,jc)=>{"use strict";var cn=me(),ln=U(),dn=ve(),WS=TypeError;jc.exports=function(i,e){var t,r;if(e==="string"&&ln(t=i.toString)&&!dn(r=cn(t,i))||ln(t=i.valueOf)&&!dn(r=cn(t,i))||e!=="string"&&ln(t=i.toString)&&!dn(r=cn(t,i)))return r;throw new WS("Can't convert object to primitive value")}});var Me=f((S$,Wc)=>{"use strict";Wc.exports=!0});var zc=f((v$,Qc)=>{"use strict";var Yc=H(),YS=Object.defineProperty;Qc.exports=function(i,e){try{YS(Yc,i,{value:e,configurable:!0,writable:!0})}catch{Yc[i]=e}return e}});var Vr=f((y$,Xc)=>{"use strict";var QS=Me(),zS=H(),KS=zc(),Kc="__core-js_shared__",Jc=Xc.exports=zS[Kc]||KS(Kc,{});(Jc.versions||(Jc.versions=[])).push({version:"3.38.0",mode:QS?"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 pn=f((T$,el)=>{"use strict";var Zc=Vr();el.exports=function(i,e){return Zc[i]||(Zc[i]=e||{})}});var Or=f((I$,tl)=>{"use strict";var JS=Lr(),XS=Object;tl.exports=function(i){return XS(JS(i))}});var Ce=f((E$,rl)=>{"use strict";var ZS=ae(),ev=Or(),tv=ZS({}.hasOwnProperty);rl.exports=Object.hasOwn||function(e,t){return tv(ev(e),t)}});var hn=f((x$,il)=>{"use strict";var rv=ae(),iv=0,av=Math.random(),sv=rv(1 .toString);il.exports=function(i){return"Symbol("+(i===void 0?"":i)+")_"+sv(++iv+av,36)}});var J=f((P$,sl)=>{"use strict";var nv=H(),ov=pn(),al=Ce(),uv=hn(),cv=nn(),lv=on(),Jt=nv.Symbol,fn=ov("wks"),dv=lv?Jt.for||Jt:Jt&&Jt.withoutSetter||uv;sl.exports=function(i){return al(fn,i)||(fn[i]=cv&&al(Jt,i)?Jt[i]:dv("Symbol."+i)),fn[i]}});var cl=f((A$,ul)=>{"use strict";var pv=me(),nl=ve(),ol=un(),hv=Br(),fv=Gc(),mv=J(),bv=TypeError,gv=mv("toPrimitive");ul.exports=function(i,e){if(!nl(i)||ol(i))return i;var t=hv(i,gv),r;if(t){if(e===void 0&&(e="default"),r=pv(t,i,e),!nl(r)||ol(r))return r;throw new bv("Can't convert object to primitive value")}return e===void 0&&(e="number"),fv(i,e)}});var mn=f((k$,ll)=>{"use strict";var Sv=cl(),vv=un();ll.exports=function(i){var e=Sv(i,"string");return vv(e)?e:e+""}});var Et=f(pl=>{"use strict";var yv=ye(),Tv=Zs(),Iv=en(),ga=Fe(),dl=mn(),Ev=TypeError,bn=Object.defineProperty,xv=Object.getOwnPropertyDescriptor,gn="enumerable",Sn="configurable",vn="writable";pl.f=yv?Iv?function(e,t,r){if(ga(e),t=dl(t),ga(r),typeof e=="function"&&t==="prototype"&&"value"in r&&vn in r&&!r[vn]){var a=xv(e,t);a&&a[vn]&&(e[t]=r.value,r={configurable:Sn in r?r[Sn]:a[Sn],enumerable:gn in r?r[gn]:a[gn],writable:!1})}return bn(e,t,r)}:bn:function(e,t,r){if(ga(e),t=dl(t),ga(r),Tv)try{return bn(e,t,r)}catch{}if("get"in r||"set"in r)throw new Ev("Accessors not supported");return"value"in r&&(e[t]=r.value),e}});var _r=f((R$,hl)=>{"use strict";hl.exports=function(i,e){return{enumerable:!(i&1),configurable:!(i&2),writable:!(i&4),value:e}}});var Xt=f(($$,fl)=>{"use strict";var Pv=ye(),Av=Et(),kv=_r();fl.exports=Pv?function(i,e,t){return Av.f(i,e,kv(1,t))}:function(i,e,t){return i[e]=t,i}});var Sa=f((L$,bl)=>{"use strict";var wv=pn(),Rv=hn(),ml=wv("keys");bl.exports=function(i){return ml[i]||(ml[i]=Rv(i))}});var va=f((M$,gl)=>{"use strict";gl.exports={}});var En=f((C$,yl)=>{"use strict";var $v=mc(),vl=H(),Lv=ve(),Mv=Xt(),yn=Ce(),Tn=Vr(),Cv=Sa(),Dv=va(),Sl="Object already initialized",In=vl.TypeError,Bv=vl.WeakMap,ya,Nr,Ta,Vv=function(i){return Ta(i)?Nr(i):ya(i,{})},Ov=function(i){return function(e){var t;if(!Lv(e)||(t=Nr(e)).type!==i)throw new In("Incompatible receiver, "+i+" required");return t}};$v||Tn.state?(De=Tn.state||(Tn.state=new Bv),De.get=De.get,De.has=De.has,De.set=De.set,ya=function(i,e){if(De.has(i))throw new In(Sl);return e.facade=i,De.set(i,e),e},Nr=function(i){return De.get(i)||{}},Ta=function(i){return De.has(i)}):(xt=Cv("state"),Dv[xt]=!0,ya=function(i,e){if(yn(i,xt))throw new In(Sl);return e.facade=i,Mv(i,xt,e),e},Nr=function(i){return yn(i,xt)?i[xt]:{}},Ta=function(i){return yn(i,xt)});var De,xt;yl.exports={set:ya,get:Nr,has:Ta,enforce:Vv,getterFor:Ov}});var xn=f((D$,xl)=>{"use strict";var _v=$r(),El=Function.prototype,Tl=El.apply,Il=El.call;xl.exports=typeof Reflect=="object"&&Reflect.apply||(_v?Il.bind(Tl):function(){return Il.apply(Tl,arguments)})});var Pn=f((B$,Pl)=>{"use strict";var Nv=Yt(),Fv=ae();Pl.exports=function(i){if(Nv(i)==="Function")return Fv(i)}});var Rl=f(wl=>{"use strict";var Al={}.propertyIsEnumerable,kl=Object.getOwnPropertyDescriptor,qv=kl&&!Al.call({1:2},1);wl.f=qv?function(e){var t=kl(this,e);return!!t&&t.enumerable}:Al});var Ml=f(Ll=>{"use strict";var Uv=ye(),Hv=me(),jv=Rl(),Gv=_r(),Wv=zt(),Yv=mn(),Qv=Ce(),zv=Zs(),$l=Object.getOwnPropertyDescriptor;Ll.f=Uv?$l:function(e,t){if(e=Wv(e),t=Yv(t),zv)try{return $l(e,t)}catch{}if(Qv(e,t))return Gv(!Hv(jv.f,e,t),e[t])}});var An=f((_$,Cl)=>{"use strict";var Kv=fe(),Jv=U(),Xv=/#|\.prototype\./,Fr=function(i,e){var t=ey[Zv(i)];return t===ry?!0:t===ty?!1:Jv(e)?Kv(e):!!e},Zv=Fr.normalize=function(i){return String(i).replace(Xv,".").toLowerCase()},ey=Fr.data={},ty=Fr.NATIVE="N",ry=Fr.POLYFILL="P";Cl.exports=Fr});var qr=f((N$,Bl)=>{"use strict";var Dl=Pn(),iy=je(),ay=$r(),sy=Dl(Dl.bind);Bl.exports=function(i,e){return iy(i),e===void 0?i:ay?sy(i,e):function(){return i.apply(e,arguments)}}});var Te=f((F$,Ol)=>{"use strict";var Ur=H(),ny=xn(),oy=Pn(),uy=U(),cy=Ml().f,ly=An(),Zt=ma(),dy=qr(),er=Xt(),Vl=Ce();Vr();var py=function(i){var e=function(t,r,a){if(this instanceof e){switch(arguments.length){case 0:return new i;case 1:return new i(t);case 2:return new i(t,r)}return new i(t,r,a)}return ny(i,this,arguments)};return e.prototype=i.prototype,e};Ol.exports=function(i,e){var t=i.target,r=i.global,a=i.stat,s=i.proto,n=r?Ur:a?Ur[t]:Ur[t]&&Ur[t].prototype,o=r?Zt:Zt[t]||er(Zt,t,{})[t],c=o.prototype,u,d,l,p,h,m,b,g,v;for(p in e)u=ly(r?p:t+(a?".":"#")+p,i.forced),d=!u&&n&&Vl(n,p),m=o[p],d&&(i.dontCallGetSet?(v=cy(n,p),b=v&&v.value):b=n[p]),h=d&&b?b:e[p],!(!u&&!s&&typeof m==typeof h)&&(i.bind&&d?g=dy(h,Ur):i.wrap&&d?g=py(h):s&&uy(h)?g=oy(h):g=h,(i.sham||h&&h.sham||m&&m.sham)&&er(g,"sham",!0),er(o,p,g),s&&(l=t+"Prototype",Vl(Zt,l)||er(Zt,l,{}),er(Zt[l],p,h),i.real&&c&&(u||!c[p])&&er(c,p,h)))}});var Fl=f((q$,Nl)=>{"use strict";var kn=ye(),hy=Ce(),_l=Function.prototype,fy=kn&&Object.getOwnPropertyDescriptor,wn=hy(_l,"name"),my=wn&&function(){}.name==="something",by=wn&&(!kn||kn&&fy(_l,"name").configurable);Nl.exports={EXISTS:wn,PROPER:my,CONFIGURABLE:by}});var Ul=f((U$,ql)=>{"use strict";var gy=Math.ceil,Sy=Math.floor;ql.exports=Math.trunc||function(e){var t=+e;return(t>0?Sy:gy)(t)}});var Ia=f((H$,Hl)=>{"use strict";var vy=Ul();Hl.exports=function(i){var e=+i;return e!==e||e===0?0:vy(e)}});var Gl=f((j$,jl)=>{"use strict";var yy=Ia(),Ty=Math.max,Iy=Math.min;jl.exports=function(i,e){var t=yy(i);return t<0?Ty(t+e,0):Iy(t,e)}});var Yl=f((G$,Wl)=>{"use strict";var Ey=Ia(),xy=Math.min;Wl.exports=function(i){var e=Ey(i);return e>0?xy(e,9007199254740991):0}});var Ea=f((W$,Ql)=>{"use strict";var Py=Yl();Ql.exports=function(i){return Py(i.length)}});var Jl=f((Y$,Kl)=>{"use strict";var Ay=zt(),ky=Gl(),wy=Ea(),zl=function(i){return function(e,t,r){var a=Ay(e),s=wy(a);if(s===0)return!i&&-1;var n=ky(r,s),o;if(i&&t!==t){for(;s>n;)if(o=a[n++],o!==o)return!0}else for(;s>n;n++)if((i||n in a)&&a[n]===t)return i||n||0;return!i&&-1}};Kl.exports={includes:zl(!0),indexOf:zl(!1)}});var ed=f((Q$,Zl)=>{"use strict";var Ry=ae(),Rn=Ce(),$y=zt(),Ly=Jl().indexOf,My=va(),Xl=Ry([].push);Zl.exports=function(i,e){var t=$y(i),r=0,a=[],s;for(s in t)!Rn(My,s)&&Rn(t,s)&&Xl(a,s);for(;e.length>r;)Rn(t,s=e[r++])&&(~Ly(a,s)||Xl(a,s));return a}});var $n=f((z$,td)=>{"use strict";td.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var id=f((K$,rd)=>{"use strict";var Cy=ed(),Dy=$n();rd.exports=Object.keys||function(e){return Cy(e,Dy)}});var sd=f(ad=>{"use strict";var By=ye(),Vy=en(),Oy=Et(),_y=Fe(),Ny=zt(),Fy=id();ad.f=By&&!Vy?Object.defineProperties:function(e,t){_y(e);for(var r=Ny(t),a=Fy(t),s=a.length,n=0,o;s>n;)Oy.f(e,o=a[n++],r[o]);return e}});var Ln=f((X$,nd)=>{"use strict";var qy=He();nd.exports=qy("document","documentElement")});var Bn=f((Z$,hd)=>{"use strict";var Uy=Fe(),Hy=sd(),od=$n(),jy=va(),Gy=Ln(),Wy=ha(),Yy=Sa(),ud=">",cd="<",Cn="prototype",Dn="script",dd=Yy("IE_PROTO"),Mn=function(){},pd=function(i){return cd+Dn+ud+i+cd+"/"+Dn+ud},ld=function(i){i.write(pd("")),i.close();var e=i.parentWindow.Object;return i=null,e},Qy=function(){var i=Wy("iframe"),e="java"+Dn+":",t;return i.style.display="none",Gy.appendChild(i),i.src=String(e),t=i.contentWindow.document,t.open(),t.write(pd("document.F=Object")),t.close(),t.F},xa,Pa=function(){try{xa=new ActiveXObject("htmlfile")}catch{}Pa=typeof document<"u"?document.domain&&xa?ld(xa):Qy():ld(xa);for(var i=od.length;i--;)delete Pa[Cn][od[i]];return Pa()};jy[dd]=!0;hd.exports=Object.create||function(e,t){var r;return e!==null?(Mn[Cn]=Uy(e),r=new Mn,Mn[Cn]=null,r[dd]=e):r=Pa(),t===void 0?r:Hy.f(r,t)}});var md=f((eL,fd)=>{"use strict";var zy=fe();fd.exports=!zy(function(){function i(){}return i.prototype.constructor=null,Object.getPrototypeOf(new i)!==i.prototype})});var On=f((tL,gd)=>{"use strict";var Ky=Ce(),Jy=U(),Xy=Or(),Zy=Sa(),eT=md(),bd=Zy("IE_PROTO"),Vn=Object,tT=Vn.prototype;gd.exports=eT?Vn.getPrototypeOf:function(i){var e=Xy(i);if(Ky(e,bd))return e[bd];var t=e.constructor;return Jy(t)&&e instanceof t?t.prototype:e instanceof Vn?tT:null}});var tr=f((rL,Sd)=>{"use strict";var rT=Xt();Sd.exports=function(i,e,t,r){return r&&r.enumerable?i[e]=t:rT(i,e,t),i}});var qn=f((iL,Td)=>{"use strict";var iT=fe(),aT=U(),sT=ve(),nT=Bn(),vd=On(),oT=tr(),uT=J(),cT=Me(),Fn=uT("iterator"),yd=!1,Ge,_n,Nn;[].keys&&(Nn=[].keys(),"next"in Nn?(_n=vd(vd(Nn)),_n!==Object.prototype&&(Ge=_n)):yd=!0);var lT=!sT(Ge)||iT(function(){var i={};return Ge[Fn].call(i)!==i});lT?Ge={}:cT&&(Ge=nT(Ge));aT(Ge[Fn])||oT(Ge,Fn,function(){return this});Td.exports={IteratorPrototype:Ge,BUGGY_SAFARI_ITERATORS:yd}});var Aa=f((aL,Ed)=>{"use strict";var dT=J(),pT=dT("toStringTag"),Id={};Id[pT]="z";Ed.exports=String(Id)==="[object z]"});var Hr=f((sL,xd)=>{"use strict";var hT=Aa(),fT=U(),ka=Yt(),mT=J(),bT=mT("toStringTag"),gT=Object,ST=ka(function(){return arguments}())==="Arguments",vT=function(i,e){try{return i[e]}catch{}};xd.exports=hT?ka:function(i){var e,t,r;return i===void 0?"Undefined":i===null?"Null":typeof(t=vT(e=gT(i),bT))=="string"?t:ST?ka(e):(r=ka(e))==="Object"&&fT(e.callee)?"Arguments":r}});var Ad=f((nL,Pd)=>{"use strict";var yT=Aa(),TT=Hr();Pd.exports=yT?{}.toString:function(){return"[object "+TT(this)+"]"}});var jr=f((oL,wd)=>{"use strict";var IT=Aa(),ET=Et().f,xT=Xt(),PT=Ce(),AT=Ad(),kT=J(),kd=kT("toStringTag");wd.exports=function(i,e,t,r){var a=t?i:i&&i.prototype;a&&(PT(a,kd)||ET(a,kd,{configurable:!0,value:e}),r&&!IT&&xT(a,"toString",AT))}});var $d=f((uL,Rd)=>{"use strict";var wT=qn().IteratorPrototype,RT=Bn(),$T=_r(),LT=jr(),MT=It(),CT=function(){return this};Rd.exports=function(i,e,t,r){var a=e+" Iterator";return i.prototype=RT(wT,{next:$T(+!r,t)}),LT(i,a,!1,!0),MT[a]=CT,i}});var Md=f((cL,Ld)=>{"use strict";var DT=ae(),BT=je();Ld.exports=function(i,e,t){try{return DT(BT(Object.getOwnPropertyDescriptor(i,e)[t]))}catch{}}});var Dd=f((lL,Cd)=>{"use strict";var VT=ve();Cd.exports=function(i){return VT(i)||i===null}});var Vd=f((dL,Bd)=>{"use strict";var OT=Dd(),_T=String,NT=TypeError;Bd.exports=function(i){if(OT(i))return i;throw new NT("Can't set "+_T(i)+" as a prototype")}});var Un=f((pL,Od)=>{"use strict";var FT=Md(),qT=ve(),UT=Lr(),HT=Vd();Od.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var i=!1,e={},t;try{t=FT(Object.prototype,"__proto__","set"),t(e,[]),i=e instanceof Array}catch{}return function(a,s){return UT(a),HT(s),qT(a)&&(i?t(a,s):a.__proto__=s),a}}():void 0)});var Qd=f((hL,Yd)=>{"use strict";var jT=Te(),GT=me(),wa=Me(),Gd=Fl(),WT=U(),YT=$d(),_d=On(),Nd=Un(),QT=jr(),zT=Xt(),Hn=tr(),KT=J(),Fd=It(),Wd=qn(),JT=Gd.PROPER,XT=Gd.CONFIGURABLE,qd=Wd.IteratorPrototype,Ra=Wd.BUGGY_SAFARI_ITERATORS,Gr=KT("iterator"),Ud="keys",Wr="values",Hd="entries",jd=function(){return this};Yd.exports=function(i,e,t,r,a,s,n){YT(t,e,r);var o=function(v){if(v===a&&p)return p;if(!Ra&&v&&v in d)return d[v];switch(v){case Ud:return function(){return new t(this,v)};case Wr:return function(){return new t(this,v)};case Hd:return function(){return new t(this,v)}}return function(){return new t(this)}},c=e+" Iterator",u=!1,d=i.prototype,l=d[Gr]||d["@@iterator"]||a&&d[a],p=!Ra&&l||o(a),h=e==="Array"&&d.entries||l,m,b,g;if(h&&(m=_d(h.call(new i)),m!==Object.prototype&&m.next&&(!wa&&_d(m)!==qd&&(Nd?Nd(m,qd):WT(m[Gr])||Hn(m,Gr,jd)),QT(m,c,!0,!0),wa&&(Fd[c]=jd))),JT&&a===Wr&&l&&l.name!==Wr&&(!wa&&XT?zT(d,"name",Wr):(u=!0,p=function(){return GT(l,this)})),a)if(b={values:o(Wr),keys:s?p:o(Ud),entries:o(Hd)},n)for(g in b)(Ra||u||!(g in d))&&Hn(d,g,b[g]);else jT({target:e,proto:!0,forced:Ra||u},b);return(!wa||n)&&d[Gr]!==p&&Hn(d,Gr,p,{name:a}),Fd[e]=p,b}});var Kd=f((fL,zd)=>{"use strict";zd.exports=function(i,e){return{value:i,done:e}}});var Gn=f((mL,tp)=>{"use strict";var ZT=zt(),jn=zs(),Jd=It(),Zd=En(),eI=Et().f,tI=Qd(),$a=Kd(),rI=Me(),iI=ye(),ep="Array Iterator",aI=Zd.set,sI=Zd.getterFor(ep);tp.exports=tI(Array,"Array",function(i,e){aI(this,{type:ep,target:ZT(i),index:0,kind:e})},function(){var i=sI(this),e=i.target,t=i.index++;if(!e||t>=e.length)return i.target=void 0,$a(void 0,!0);switch(i.kind){case"keys":return $a(t,!1);case"values":return $a(e[t],!1)}return $a([t,e[t]],!1)},"values");var Xd=Jd.Arguments=Jd.Array;jn("keys");jn("values");jn("entries");if(!rI&&iI&&Xd.name!=="values")try{eI(Xd,"name",{value:"values"})}catch{}});var ip=f((bL,rp)=>{"use strict";var nI=J(),oI=It(),uI=nI("iterator"),cI=Array.prototype;rp.exports=function(i){return i!==void 0&&(oI.Array===i||cI[uI]===i)}});var Wn=f((gL,sp)=>{"use strict";var lI=Hr(),ap=Br(),dI=Qt(),pI=It(),hI=J(),fI=hI("iterator");sp.exports=function(i){if(!dI(i))return ap(i,fI)||ap(i,"@@iterator")||pI[lI(i)]}});var op=f((SL,np)=>{"use strict";var mI=me(),bI=je(),gI=Fe(),SI=Dr(),vI=Wn(),yI=TypeError;np.exports=function(i,e){var t=arguments.length<2?vI(i):e;if(bI(t))return gI(mI(t,i));throw new yI(SI(i)+" is not iterable")}});var lp=f((vL,cp)=>{"use strict";var TI=me(),up=Fe(),II=Br();cp.exports=function(i,e,t){var r,a;up(i);try{if(r=II(i,"return"),!r){if(e==="throw")throw t;return t}r=TI(r,i)}catch(s){a=!0,r=s}if(e==="throw")throw t;if(a)throw r;return up(r),t}});var Ma=f((yL,fp)=>{"use strict";var EI=qr(),xI=me(),PI=Fe(),AI=Dr(),kI=ip(),wI=Ea(),dp=Cr(),RI=op(),$I=Wn(),pp=lp(),LI=TypeError,La=function(i,e){this.stopped=i,this.result=e},hp=La.prototype;fp.exports=function(i,e,t){var r=t&&t.that,a=!!(t&&t.AS_ENTRIES),s=!!(t&&t.IS_RECORD),n=!!(t&&t.IS_ITERATOR),o=!!(t&&t.INTERRUPTED),c=EI(e,r),u,d,l,p,h,m,b,g=function(A){return u&&pp(u,"normal",A),new La(!0,A)},v=function(A){return a?(PI(A),o?c(A[0],A[1],g):c(A[0],A[1])):o?c(A,g):c(A)};if(s)u=i.iterator;else if(n)u=i;else{if(d=$I(i),!d)throw new LI(AI(i)+" is not iterable");if(kI(d)){for(l=0,p=wI(i);p>l;l++)if(h=v(i[l]),h&&dp(hp,h))return h;return new La(!1)}u=RI(i,d)}for(m=s?i.next:u.next;!(b=xI(m,u)).done;){try{h=v(b.value)}catch(A){pp(u,"throw",A)}if(typeof h=="object"&&h&&dp(hp,h))return h}return new La(!1)}});var bp=f((TL,mp)=>{"use strict";var MI=ye(),CI=Et(),DI=_r();mp.exports=function(i,e,t){MI?CI.f(i,e,DI(0,t)):i[e]=t}});var gp=f(()=>{"use strict";var BI=Te(),VI=Ma(),OI=bp();BI({target:"Object",stat:!0},{fromEntries:function(e){var t={};return VI(e,function(r,a){OI(t,r,a)},{AS_ENTRIES:!0}),t}})});var vp=f((xL,Sp)=>{"use strict";Gn();gp();var _I=ma();Sp.exports=_I.Object.fromEntries});var Tp=f((PL,yp)=>{"use strict";yp.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 Ep=f(()=>{"use strict";Gn();var NI=Tp(),FI=H(),qI=jr(),Ip=It();for(Ca in NI)qI(FI[Ca],Ca),Ip[Ca]=Ip.Array;var Ca});var Pp=f((wL,xp)=>{"use strict";var UI=vp();Ep();xp.exports=UI});var Yn=f((RL,Ap)=>{"use strict";var HI=Pp();Ap.exports=HI});var kp=f(()=>{"use strict"});var Qn=f((ML,wp)=>{"use strict";var Yr=H(),jI=Kt(),GI=Yt(),Da=function(i){return jI.slice(0,i.length)===i};wp.exports=function(){return Da("Bun/")?"BUN":Da("Cloudflare-Workers")?"CLOUDFLARE":Da("Deno/")?"DENO":Da("Node.js/")?"NODE":Yr.Bun&&typeof Bun.version=="string"?"BUN":Yr.Deno&&typeof Deno.version=="object"?"DENO":GI(Yr.process)==="process"?"NODE":Yr.window&&Yr.document?"BROWSER":"REST"}()});var Ba=f((CL,Rp)=>{"use strict";var WI=Qn();Rp.exports=WI==="NODE"});var Lp=f((DL,$p)=>{"use strict";var YI=Et();$p.exports=function(i,e,t){return YI.f(i,e,t)}});var Dp=f((BL,Cp)=>{"use strict";var QI=He(),zI=Lp(),KI=J(),JI=ye(),Mp=KI("species");Cp.exports=function(i){var e=QI(i);JI&&e&&!e[Mp]&&zI(e,Mp,{configurable:!0,get:function(){return this}})}});var Vp=f((VL,Bp)=>{"use strict";var XI=Cr(),ZI=TypeError;Bp.exports=function(i,e){if(XI(e,i))return i;throw new ZI("Incorrect invocation")}});var Kn=f((OL,Op)=>{"use strict";var eE=ae(),tE=U(),zn=Vr(),rE=eE(Function.toString);tE(zn.inspectSource)||(zn.inspectSource=function(i){return rE(i)});Op.exports=zn.inspectSource});var Hp=f((_L,Up)=>{"use strict";var iE=ae(),aE=fe(),_p=U(),sE=Hr(),nE=He(),oE=Kn(),Np=function(){},Fp=nE("Reflect","construct"),Jn=/^\s*(?:class|function)\b/,uE=iE(Jn.exec),cE=!Jn.test(Np),Qr=function(e){if(!_p(e))return!1;try{return Fp(Np,[],e),!0}catch{return!1}},qp=function(e){if(!_p(e))return!1;switch(sE(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return cE||!!uE(Jn,oE(e))}catch{return!0}};qp.sham=!0;Up.exports=!Fp||aE(function(){var i;return Qr(Qr.call)||!Qr(Object)||!Qr(function(){i=!0})||i})?qp:Qr});var Gp=f((NL,jp)=>{"use strict";var lE=Hp(),dE=Dr(),pE=TypeError;jp.exports=function(i){if(lE(i))return i;throw new pE(dE(i)+" is not a constructor")}});var Xn=f((FL,Yp)=>{"use strict";var Wp=Fe(),hE=Gp(),fE=Qt(),mE=J(),bE=mE("species");Yp.exports=function(i,e){var t=Wp(i).constructor,r;return t===void 0||fE(r=Wp(t)[bE])?e:hE(r)}});var zp=f((qL,Qp)=>{"use strict";var gE=ae();Qp.exports=gE([].slice)});var Jp=f((UL,Kp)=>{"use strict";var SE=TypeError;Kp.exports=function(i,e){if(i<e)throw new SE("Not enough arguments");return i}});var Zn=f((HL,Xp)=>{"use strict";var vE=Kt();Xp.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(vE)});var uo=f((jL,oh)=>{"use strict";var be=H(),yE=xn(),TE=qr(),Zp=U(),IE=Ce(),nh=fe(),eh=Ln(),EE=zp(),th=ha(),xE=Jp(),PE=Zn(),AE=Ba(),so=be.setImmediate,no=be.clearImmediate,kE=be.process,eo=be.Dispatch,wE=be.Function,rh=be.MessageChannel,RE=be.String,to=0,zr={},ih="onreadystatechange",Kr,Pt,ro,io;nh(function(){Kr=be.location});var oo=function(i){if(IE(zr,i)){var e=zr[i];delete zr[i],e()}},ao=function(i){return function(){oo(i)}},ah=function(i){oo(i.data)},sh=function(i){be.postMessage(RE(i),Kr.protocol+"//"+Kr.host)};(!so||!no)&&(so=function(e){xE(arguments.length,1);var t=Zp(e)?e:wE(e),r=EE(arguments,1);return zr[++to]=function(){yE(t,void 0,r)},Pt(to),to},no=function(e){delete zr[e]},AE?Pt=function(i){kE.nextTick(ao(i))}:eo&&eo.now?Pt=function(i){eo.now(ao(i))}:rh&&!PE?(ro=new rh,io=ro.port2,ro.port1.onmessage=ah,Pt=TE(io.postMessage,io)):be.addEventListener&&Zp(be.postMessage)&&!be.importScripts&&Kr&&Kr.protocol!=="file:"&&!nh(sh)?(Pt=sh,be.addEventListener("message",ah,!1)):ih in th("script")?Pt=function(i){eh.appendChild(th("script"))[ih]=function(){eh.removeChild(this),oo(i)}}:Pt=function(i){setTimeout(ao(i),0)});oh.exports={set:so,clear:no}});var lh=f((GL,ch)=>{"use strict";var uh=H(),$E=ye(),LE=Object.getOwnPropertyDescriptor;ch.exports=function(i){if(!$E)return uh[i];var e=LE(uh,i);return e&&e.value}});var co=f((WL,ph)=>{"use strict";var dh=function(){this.head=null,this.tail=null};dh.prototype={add:function(i){var e={item:i,next:null},t=this.tail;t?t.next=e:this.head=e,this.tail=e},get:function(){var i=this.head;if(i){var e=this.head=i.next;return e===null&&(this.tail=null),i.item}}};ph.exports=dh});var fh=f((YL,hh)=>{"use strict";var ME=Kt();hh.exports=/ipad|iphone|ipod/i.test(ME)&&typeof Pebble<"u"});var bh=f((QL,mh)=>{"use strict";var CE=Kt();mh.exports=/web0s(?!.*chrome)/i.test(CE)});var Eh=f((zL,Ih)=>{"use strict";var ir=H(),DE=lh(),gh=qr(),lo=uo().set,BE=co(),VE=Zn(),OE=fh(),_E=bh(),po=Ba(),Sh=ir.MutationObserver||ir.WebKitMutationObserver,vh=ir.document,yh=ir.process,Va=ir.Promise,mo=DE("queueMicrotask"),rr,ho,fo,Oa,Th;mo||(Jr=new BE,Xr=function(){var i,e;for(po&&(i=yh.domain)&&i.exit();e=Jr.get();)try{e()}catch(t){throw Jr.head&&rr(),t}i&&i.enter()},!VE&&!po&&!_E&&Sh&&vh?(ho=!0,fo=vh.createTextNode(""),new Sh(Xr).observe(fo,{characterData:!0}),rr=function(){fo.data=ho=!ho}):!OE&&Va&&Va.resolve?(Oa=Va.resolve(void 0),Oa.constructor=Va,Th=gh(Oa.then,Oa),rr=function(){Th(Xr)}):po?rr=function(){yh.nextTick(Xr)}:(lo=gh(lo,ir),rr=function(){lo(Xr)}),mo=function(i){Jr.head||rr(),Jr.add(i)});var Jr,Xr;Ih.exports=mo});var Ph=f((KL,xh)=>{"use strict";xh.exports=function(i,e){try{arguments.length===1?console.error(i):console.error(i,e)}catch{}}});var _a=f((JL,Ah)=>{"use strict";Ah.exports=function(i){try{return{error:!1,value:i()}}catch(e){return{error:!0,value:e}}}});var At=f((XL,kh)=>{"use strict";var NE=H();kh.exports=NE.Promise});var ar=f((ZL,Lh)=>{"use strict";var FE=H(),Zr=At(),qE=U(),UE=An(),HE=Kn(),jE=J(),wh=Qn(),GE=Me(),bo=sn(),Rh=Zr&&Zr.prototype,WE=jE("species"),go=!1,$h=qE(FE.PromiseRejectionEvent),YE=UE("Promise",function(){var i=HE(Zr),e=i!==String(Zr);if(!e&&bo===66||GE&&!(Rh.catch&&Rh.finally))return!0;if(!bo||bo<51||!/native code/.test(i)){var t=new Zr(function(s){s(1)}),r=function(s){s(function(){},function(){})},a=t.constructor={};if(a[WE]=r,go=t.then(function(){})instanceof r,!go)return!0}return!e&&(wh==="BROWSER"||wh==="DENO")&&!$h});Lh.exports={CONSTRUCTOR:YE,REJECTION_EVENT:$h,SUBCLASSING:go}});var sr=f((eM,Ch)=>{"use strict";var Mh=je(),QE=TypeError,zE=function(i){var e,t;this.promise=new i(function(r,a){if(e!==void 0||t!==void 0)throw new QE("Bad Promise constructor");e=r,t=a}),this.resolve=Mh(e),this.reject=Mh(t)};Ch.exports.f=function(i){return new zE(i)}});var Xh=f(()=>{"use strict";var KE=Te(),JE=Me(),Ua=Ba(),st=H(),cr=me(),Dh=tr(),Bh=Un(),XE=jr(),ZE=Dp(),ex=je(),qa=U(),tx=ve(),rx=Vp(),ix=Xn(),Fh=uo().set,Io=Eh(),ax=Ph(),sx=_a(),nx=co(),qh=En(),Ha=At(),Eo=ar(),Uh=sr(),ja="Promise",Hh=Eo.CONSTRUCTOR,ox=Eo.REJECTION_EVENT,ux=Eo.SUBCLASSING,So=qh.getterFor(ja),cx=qh.set,nr=Ha&&Ha.prototype,kt=Ha,Na=nr,jh=st.TypeError,vo=st.document,xo=st.process,yo=Uh.f,lx=yo,dx=!!(vo&&vo.createEvent&&st.dispatchEvent),Gh="unhandledrejection",px="rejectionhandled",Vh=0,Wh=1,hx=2,Po=1,Yh=2,Fa,Oh,fx,_h,Qh=function(i){var e;return tx(i)&&qa(e=i.then)?e:!1},zh=function(i,e){var t=e.value,r=e.state===Wh,a=r?i.ok:i.fail,s=i.resolve,n=i.reject,o=i.domain,c,u,d;try{a?(r||(e.rejection===Yh&&bx(e),e.rejection=Po),a===!0?c=t:(o&&o.enter(),c=a(t),o&&(o.exit(),d=!0)),c===i.promise?n(new jh("Promise-chain cycle")):(u=Qh(c))?cr(u,c,s,n):s(c)):n(t)}catch(l){o&&!d&&o.exit(),n(l)}},Kh=function(i,e){i.notified||(i.notified=!0,Io(function(){for(var t=i.reactions,r;r=t.get();)zh(r,i);i.notified=!1,e&&!i.rejection&&mx(i)}))},Jh=function(i,e,t){var r,a;dx?(r=vo.createEvent("Event"),r.promise=e,r.reason=t,r.initEvent(i,!1,!0),st.dispatchEvent(r)):r={promise:e,reason:t},!ox&&(a=st["on"+i])?a(r):i===Gh&&ax("Unhandled promise rejection",t)},mx=function(i){cr(Fh,st,function(){var e=i.facade,t=i.value,r=Nh(i),a;if(r&&(a=sx(function(){Ua?xo.emit("unhandledRejection",t,e):Jh(Gh,e,t)}),i.rejection=Ua||Nh(i)?Yh:Po,a.error))throw a.value})},Nh=function(i){return i.rejection!==Po&&!i.parent},bx=function(i){cr(Fh,st,function(){var e=i.facade;Ua?xo.emit("rejectionHandled",e):Jh(px,e,i.value)})},or=function(i,e,t){return function(r){i(e,r,t)}},ur=function(i,e,t){i.done||(i.done=!0,t&&(i=t),i.value=e,i.state=hx,Kh(i,!0))},To=function(i,e,t){if(!i.done){i.done=!0,t&&(i=t);try{if(i.facade===e)throw new jh("Promise can't be resolved itself");var r=Qh(e);r?Io(function(){var a={done:!1};try{cr(r,e,or(To,a,i),or(ur,a,i))}catch(s){ur(a,s,i)}}):(i.value=e,i.state=Wh,Kh(i,!1))}catch(a){ur({done:!1},a,i)}}};if(Hh&&(kt=function(e){rx(this,Na),ex(e),cr(Fa,this);var t=So(this);try{e(or(To,t),or(ur,t))}catch(r){ur(t,r)}},Na=kt.prototype,Fa=function(e){cx(this,{type:ja,done:!1,notified:!1,parent:!1,reactions:new nx,rejection:!1,state:Vh,value:void 0})},Fa.prototype=Dh(Na,"then",function(e,t){var r=So(this),a=yo(ix(this,kt));return r.parent=!0,a.ok=qa(e)?e:!0,a.fail=qa(t)&&t,a.domain=Ua?xo.domain:void 0,r.state===Vh?r.reactions.add(a):Io(function(){zh(a,r)}),a.promise}),Oh=function(){var i=new Fa,e=So(i);this.promise=i,this.resolve=or(To,e),this.reject=or(ur,e)},Uh.f=yo=function(i){return i===kt||i===fx?new Oh(i):lx(i)},!JE&&qa(Ha)&&nr!==Object.prototype)){_h=nr.then,ux||Dh(nr,"then",function(e,t){var r=this;return new kt(function(a,s){cr(_h,r,a,s)}).then(e,t)},{unsafe:!0});try{delete nr.constructor}catch{}Bh&&Bh(nr,Na)}KE({global:!0,constructor:!0,wrap:!0,forced:Hh},{Promise:kt});XE(kt,ja,!1,!0);ZE(ja)});var af=f((iM,rf)=>{"use strict";var gx=J(),ef=gx("iterator"),tf=!1;try{Zh=0,Ao={next:function(){return{done:!!Zh++}},return:function(){tf=!0}},Ao[ef]=function(){return this},Array.from(Ao,function(){throw 2})}catch{}var Zh,Ao;rf.exports=function(i,e){try{if(!e&&!tf)return!1}catch{return!1}var t=!1;try{var r={};r[ef]=function(){return{next:function(){return{done:t=!0}}}},i(r)}catch{}return t}});var ko=f((aM,sf)=>{"use strict";var Sx=At(),vx=af(),yx=ar().CONSTRUCTOR;sf.exports=yx||!vx(function(i){Sx.all(i).then(void 0,function(){})})});var nf=f(()=>{"use strict";var Tx=Te(),Ix=me(),Ex=je(),xx=sr(),Px=_a(),Ax=Ma(),kx=ko();Tx({target:"Promise",stat:!0,forced:kx},{all:function(e){var t=this,r=xx.f(t),a=r.resolve,s=r.reject,n=Px(function(){var o=Ex(t.resolve),c=[],u=0,d=1;Ax(e,function(l){var p=u++,h=!1;d++,Ix(o,t,l).then(function(m){h||(h=!0,c[p]=m,--d||a(c))},s)}),--d||a(c)});return n.error&&s(n.value),r.promise}})});var uf=f(()=>{"use strict";var wx=Te(),Rx=Me(),$x=ar().CONSTRUCTOR,Ro=At(),Lx=He(),Mx=U(),Cx=tr(),of=Ro&&Ro.prototype;wx({target:"Promise",proto:!0,forced:$x,real:!0},{catch:function(i){return this.then(void 0,i)}});!Rx&&Mx(Ro)&&(wo=Lx("Promise").prototype.catch,of.catch!==wo&&Cx(of,"catch",wo,{unsafe:!0}));var wo});var cf=f(()=>{"use strict";var Dx=Te(),Bx=me(),Vx=je(),Ox=sr(),_x=_a(),Nx=Ma(),Fx=ko();Dx({target:"Promise",stat:!0,forced:Fx},{race:function(e){var t=this,r=Ox.f(t),a=r.reject,s=_x(function(){var n=Vx(t.resolve);Nx(e,function(o){Bx(n,t,o).then(r.resolve,a)})});return s.error&&a(s.value),r.promise}})});var lf=f(()=>{"use strict";var qx=Te(),Ux=sr(),Hx=ar().CONSTRUCTOR;qx({target:"Promise",stat:!0,forced:Hx},{reject:function(e){var t=Ux.f(this),r=t.reject;return r(e),t.promise}})});var $o=f((hM,df)=>{"use strict";var jx=Fe(),Gx=ve(),Wx=sr();df.exports=function(i,e){if(jx(i),Gx(e)&&e.constructor===i)return e;var t=Wx.f(i),r=t.resolve;return r(e),t.promise}});var ff=f(()=>{"use strict";var Yx=Te(),Qx=He(),pf=Me(),zx=At(),hf=ar().CONSTRUCTOR,Kx=$o(),Jx=Qx("Promise"),Xx=pf&&!hf;Yx({target:"Promise",stat:!0,forced:pf||hf},{resolve:function(e){return Kx(Xx&&this===Jx?zx:this,e)}})});var mf=f(()=>{"use strict";Xh();nf();uf();cf();lf();ff()});var vf=f(()=>{"use strict";var Zx=Te(),eP=Me(),Ga=At(),tP=fe(),gf=He(),Sf=U(),rP=Xn(),bf=$o(),iP=tr(),Mo=Ga&&Ga.prototype,aP=!!Ga&&tP(function(){Mo.finally.call({then:function(){}},function(){})});Zx({target:"Promise",proto:!0,real:!0,forced:aP},{finally:function(i){var e=rP(this,gf("Promise")),t=Sf(i);return this.then(t?function(r){return bf(e,i()).then(function(){return r})}:i,t?function(r){return bf(e,i()).then(function(){throw r})}:i)}});!eP&&Sf(Ga)&&(Lo=gf("Promise").prototype.finally,Mo.finally!==Lo&&iP(Mo,"finally",Lo,{unsafe:!0}));var Lo});var Wa=f((yM,yf)=>{"use strict";var sP=He();yf.exports=sP});var If=f((TM,Tf)=>{"use strict";kp();mf();vf();var nP=Wa();Tf.exports=nP("Promise","finally")});var xf=f((IM,Ef)=>{"use strict";var oP=If();Ef.exports=oP});var Ya=f((EM,Pf)=>{"use strict";var uP=xf();Pf.exports=uP});var Kf=f(()=>{"use strict";var OP=Te(),_P=Or(),NP=Ea(),FP=Ia(),qP=zs();OP({target:"Array",proto:!0},{at:function(e){var t=_P(this),r=NP(t),a=FP(e),s=a>=0?a:r+a;return s<0||s>=r?void 0:t[s]}});qP("at")});var Xf=f((MC,Jf)=>{"use strict";Kf();var UP=Wa();Jf.exports=UP("Array","at")});var em=f((CC,Zf)=>{"use strict";var HP=Xf();Zf.exports=HP});var ii=f((DC,tm)=>{"use strict";var jP=em();tm.exports=jP});var Km=f(()=>{"use strict"});var Jm=f(()=>{"use strict"});var Zm=f((DV,Xm)=>{"use strict";var KA=ve(),JA=Yt(),XA=J(),ZA=XA("match");Xm.exports=function(i){var e;return KA(i)&&((e=i[ZA])!==void 0?!!e:JA(i)==="RegExp")}});var tb=f((BV,eb)=>{"use strict";var ek=Hr(),tk=String;eb.exports=function(i){if(ek(i)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return tk(i)}});var ib=f((VV,rb)=>{"use strict";var rk=Fe();rb.exports=function(){var i=rk(this),e="";return i.hasIndices&&(e+="d"),i.global&&(e+="g"),i.ignoreCase&&(e+="i"),i.multiline&&(e+="m"),i.dotAll&&(e+="s"),i.unicode&&(e+="u"),i.unicodeSets&&(e+="v"),i.sticky&&(e+="y"),e}});var nb=f((OV,sb)=>{"use strict";var ik=me(),ak=Ce(),sk=Cr(),nk=ib(),ab=RegExp.prototype;sb.exports=function(i){var e=i.flags;return e===void 0&&!("flags"in ab)&&!ak(i,"flags")&&sk(ab,i)?ik(nk,i):e}});var ub=f((_V,ob)=>{"use strict";var uu=ae(),ok=Or(),uk=Math.floor,nu=uu("".charAt),ck=uu("".replace),ou=uu("".slice),lk=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,dk=/\$([$&'`]|\d{1,2})/g;ob.exports=function(i,e,t,r,a,s){var n=t+i.length,o=r.length,c=dk;return a!==void 0&&(a=ok(a),c=lk),ck(s,c,function(u,d){var l;switch(nu(d,0)){case"$":return"$";case"&":return i;case"`":return ou(e,0,t);case"'":return ou(e,n);case"<":l=a[ou(d,1,-1)];break;default:var p=+d;if(p===0)return u;if(p>o){var h=uk(p/10);return h===0?u:h<=o?r[h-1]===void 0?nu(d,1):r[h-1]+nu(d,1):u}l=r[p-1]}return l===void 0?"":l})}});var db=f(()=>{"use strict";var pk=Te(),hk=me(),lu=ae(),cb=Lr(),fk=U(),mk=Qt(),bk=Zm(),yr=tb(),gk=Br(),Sk=nb(),vk=ub(),yk=J(),Tk=Me(),Ik=yk("replace"),Ek=TypeError,cu=lu("".indexOf),xk=lu("".replace),lb=lu("".slice),Pk=Math.max;pk({target:"String",proto:!0},{replaceAll:function(e,t){var r=cb(this),a,s,n,o,c,u,d,l,p,h,m=0,b="";if(!mk(e)){if(a=bk(e),a&&(s=yr(cb(Sk(e))),!~cu(s,"g")))throw new Ek("`.replaceAll` does not allow non-global regexes");if(n=gk(e,Ik),n)return hk(n,e,r,t);if(Tk&&a)return xk(yr(r),e,t)}for(o=yr(r),c=yr(e),u=fk(t),u||(t=yr(t)),d=c.length,l=Pk(1,d),p=cu(o,c);p!==-1;)h=u?yr(t(c,p,o)):vk(c,o,p,[],void 0,t),b+=lb(o,m,p)+h,m=p+d,p=p+l>o.length?-1:cu(o,c,p+l);return m<o.length&&(b+=lb(o,m)),b}})});var hb=f((qV,pb)=>{"use strict";Km();Jm();db();var Ak=Wa();pb.exports=Ak("String","replaceAll")});var mb=f((UV,fb)=>{"use strict";var kk=hb();fb.exports=kk});var gb=f((HV,bb)=>{"use strict";var wk=mb();bb.exports=wk});var ju="2.0.111-dev.974e99b3.0";var ie=(a=>(a.STOPPED="stopped",a.READY="ready",a.PLAYING="playing",a.PAUSED="paused",a))(ie||{}),at=(y=>(y.MPEG="MPEG",y.DASH="DASH",y.DASH_SEP="DASH_SEP",y.DASH_SEP_VK="DASH_SEP",y.DASH_WEBM="DASH_WEBM",y.DASH_WEBM_AV1="DASH_WEBM_AV1",y.DASH_STREAMS="DASH_STREAMS",y.DASH_WEBM_VK="DASH_WEBM",y.DASH_ONDEMAND="DASH_ONDEMAND",y.DASH_ONDEMAND_VK="DASH_ONDEMAND",y.DASH_LIVE="DASH_LIVE",y.DASH_LIVE_CMAF="DASH_LIVE_CMAF",y.DASH_LIVE_WEBM="DASH_LIVE_WEBM",y.HLS="HLS",y.HLS_ONDEMAND="HLS_ONDEMAND",y.HLS_JS="HLS",y.HLS_LIVE="HLS_LIVE",y.HLS_LIVE_CMAF="HLS_LIVE_CMAF",y.WEB_RTC_LIVE="WEB_RTC_LIVE",y))(at||{});var la=(a=>(a.NOT_AVAILABLE="NOT_AVAILABLE",a.AVAILABLE="AVAILABLE",a.CONNECTING="CONNECTING",a.CONNECTED="CONNECTED",a))(la||{}),Hs=(r=>(r.HTTP1="http1",r.HTTP2="http2",r.QUIC="quic",r))(Hs||{});var js=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(js||{});import{assertNever as Ku,assertNonNullable as Qg,isNonNullable as da,ValueSubject as Gs,Subject as zg,Subscription as Kg,merge as Jg,observableFrom as Xg,fromEvent as Wu,map as Yu,tap as Qu,filterChanged as Zg,isNullable as Ws,ErrorCategory as zu}from"@vkontakte/videoplayer-shared";var Gu=i=>new Promise((e,t)=>{let r=document.createElement("script");r.setAttribute("src",i),r.onload=()=>e,r.onerror=()=>t,document.body.appendChild(r)});var pa=class{constructor(e){this.connection$=new Gs(void 0);this.castState$=new Gs("NOT_AVAILABLE");this.errorEvent$=new zg;this.realCastState$=new Gs("NOT_AVAILABLE");this.subscription=new Kg;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=da(window.chrome?.cast),a=!!window.__onGCastApiAvailable;r?this.initializeCastApi():(window.__onGCastApiAvailable=s=>{delete window.__onGCastApiAvailable,s&&this.initializeCastApi()},a||Gu("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:zu.NETWORK,message:"Script loading failed!"})))}connect(){cast.framework.CastContext.getInstance()?.requestSession()}disconnect(){cast.framework.CastContext.getInstance()?.getCurrentSession()?.endSession(!0)}stopMedia(){return new Promise((e,t)=>{cast.framework.CastContext.getInstance()?.getCurrentSession()?.getMediaSession()?.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){da(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();Ws(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();Ws(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(Wu(r,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(a=>{switch(a.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=r.getCurrentSession()?.getMediaSession()?.media?.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return Ku(a.sessionState)}})).add(Jg(Wu(r,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(Qu(a=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(a)}`})}),Yu(a=>a.castState)),Xg([r.getCastState()])).pipe(Zg(),Yu(eS),Qu(a=>{this.log({message:`realCastState$: ${a}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(a=>{let s=a==="CONNECTED",n=da(this.connection$.getValue());if(s&&!n){let o=r.getCurrentSession();Qg(o);let c=o.getCastDevice(),u=o.getMediaSession()?.media?.contentId;(Ws(u)||u===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:o,castDevice:c}))}else!s&&n&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(a==="CONNECTED"?da(this.connection$.getValue())?"CONNECTED":"AVAILABLE":a)}))}initializeCastApi(){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{return}try{e.setOptions({receiverApplicationId:this.params.receiverApplicationId??t,autoJoinPolicy:r}),this.initListeners()}catch(a){this.errorEvent$.next({id:"ChromecastInitializer",category:zu.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:a})}}},eS=i=>{switch(i){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 Ku(i)}};var mg=Ne(Yn(),1);var Bf=Ne(Ya(),1);import{assertNever as Af}from"@vkontakte/videoplayer-shared";var K=(i,e=0,t=0)=>{switch(t){case 0:return i.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case 1:{if(e===0)return i;let r=new URL(i);return r.searchParams.append("playback_shift",e.toFixed(0)),r.toString()}case 2:{let r=new URL(i);return!r.searchParams.get("offset_p")&&e===0?i:(r.searchParams.set("offset_p",e.toFixed(0)),r.toString())}default:Af(t)}return i},Co=(i,e)=>{switch(e){case 0:return NaN;case 1:{let t=new URL(i);return Number(t.searchParams.get("playback_shift"))}case 2:{let t=new URL(i);return Number(t.searchParams.get("offset_p")??0)}default:Af(e)}};var I=(i,e,t=!1)=>{let r=i.getTransition();(t||!r||r.to===e)&&i.setState(e)};import{isNonNullable as cP,Subject as Qa,merge as kf}from"@vkontakte/videoplayer-shared";var L=class{constructor(e){this.transitionStarted$=new Qa;this.transitionEnded$=new Qa;this.transitionUpdated$=new Qa;this.forceChanged$=new Qa;this.stateChangeStarted$=kf(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=kf(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||cP(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 lP}from"@vkontakte/videoplayer-shared";var wf=i=>{switch(i){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 lP(i)}};import{assertNever as lr,assertNonNullable as wt,debounce as Rf,ErrorCategory as $f,fromEvent as Rt,isNonNullable as Lf,map as Mf,merge as Cf,observableFrom as dP,Subject as pP,Subscription as Do,timeout as hP,getHighestQuality as fP}from"@vkontakte/videoplayer-shared";var mP=5,bP=5,gP=500,Df=7e3,ei=class{constructor(e){this.subscription=new Do;this.loadMediaTimeoutSubscription=new Do;this.videoState=new L("stopped");this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),r=this.params.desiredState.playbackState.getState(),a=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(a?.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:lr(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:lr(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:lr(e)}break}default:lr(r)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(wf(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 Do;this.subscription.add(e),this.subscription.add(Cf(this.videoState.stateChangeStarted$.pipe(Mf(a=>`stateChangeStarted$ ${JSON.stringify(a)}`)),this.videoState.stateChangeEnded$.pipe(Mf(a=>`stateChangeEnded$ ${JSON.stringify(a)}`))).subscribe(a=>this.log({message:`[videoState] ${a}`})));let t=(a,s)=>this.subscription.add(a.subscribe(s));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{let a=new pP;e.add(a.pipe(Rf(gP)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add(Rt(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)>mP)&&a.next(o),s=o})),e.add(Rt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(Rt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),a=>{this.logRemoteEvent(a),a.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(Rt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),a=>{this.logRemoteEvent(a),a.value?this.handleRemotePause():this.handleRemotePlay()}),t(Rt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),a=>{this.logRemoteEvent(a);let{remotePlayer:s}=this.params.connection,n=a.value,o=this.params.output.isBuffering$.getValue(),c=n===chrome.cast.media.PlayerState.BUFFERING;switch(o!==c&&this.params.output.isBuffering$.next(c),n){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&s.duration-s.currentTime<bP&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),I(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:lr(n)}}),t(Rt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),a=>{this.logRemoteEvent(a),this.handleRemoteVolumeChange({volume:a.value})}),t(Rt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),a=>{this.logRemoteEvent(a),this.handleRemoteVolumeChange({muted:a.value})});let r=Cf(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,dP(["init"])).pipe(Rf(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"),I(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),I(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();(this.videoState.getTransition()?.to==="paused"||e==="playing")&&(this.videoState.setState("paused"),I(this.params.desiredState.playbackState,"paused"))}handleRemotePlay(){let e=this.videoState.getState();(this.videoState.getTransition()?.to==="playing"||e==="paused")&&(this.videoState.setState("playing"),I(this.params.desiredState.playbackState,"playing"))}handleRemoteReady(){this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.params.desiredState.playbackState.getTransition()?.to==="ready"&&I(this.params.desiredState.playbackState,"ready")}handleRemoteStop(){this.videoState.getState()!=="stopped"&&this.videoState.setState("stopped")}handleRemoteVolumeChange(e){let t=this.params.output.volume$.getValue(),r={volume:e.volume??t.volume,muted:e.muted??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){let t=this.params.source,r,a,s;switch(e){case"MPEG":{let u=t[e];wt(u);let d=fP(Object.keys(u));wt(d);let l=u[d];wt(l),r=l,a="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let u=t[e];wt(u),r=u.url,a="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 u=t[e];wt(u),r=u.url,a="application/dash+xml",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let u=t[e];wt(u),r=u.url,a="application/dash+xml",s=chrome.cast.media.StreamType.LIVE;break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let u=t[e];wt(u),r=K(u.url),a="application/x-mpegurl",s=chrome.cast.media.StreamType.LIVE;break}case"DASH_LIVE":case"WEB_RTC_LIVE":{let u="Unsupported format for Chromecast",d=new Error(u);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:$f.VIDEO_PIPELINE,message:u,thrown:d}),d}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return lr(e)}let n=new chrome.cast.media.MediaInfo(this.params.meta.videoId??r,a);n.contentUrl=r,n.streamType=s,n.metadata=new chrome.cast.media.GenericMediaMetadata;let{title:o,subtitle:c}=this.params.meta;return Lf(o)&&(n.metadata.title=o),Lf(c)&&(n.metadata.subtitle=c),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((a,s)=>{this.loadMediaTimeoutSubscription.add(hP(Df).subscribe(()=>s(`timeout(${Df})`)))});(0,Bf.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()},a=>{let s=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${a}`;this.log({message:s}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:$f.VIDEO_PIPELINE,message:s,thrown:a})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};import{clearVideoElement as Of}from"@vkontakte/videoplayer-shared";import{clearVideoElement as SP}from"@vkontakte/videoplayer-shared";var Vf=i=>{try{i.pause(),i.playbackRate=0,SP(i),i.remove()}catch(e){console.error(e)}};import{fromEvent as vP,Subscription as yP}from"@vkontakte/videoplayer-shared";var Bo=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)}},Vo=window.WeakMap?new WeakMap:new Bo,Oo=window.WeakMap?new WeakMap:new Map,TP=(i,e=20)=>{let t=0;return vP(i,"ratechange").subscribe(r=>{t++,t>=e&&(i.currentTime=i.currentTime,t=0)})},se=(i,{audioVideoSyncRate:e})=>{let t=i.querySelector("video"),r=!!t;t?Of(t):(t=document.createElement("video"),i.appendChild(t)),Vo.set(t,r);let a=new yP;return a.add(TP(t,e)),Oo.set(t,a),t.setAttribute("crossorigin","anonymous"),t.setAttribute("playsinline","playsinline"),t.controls=!1,t.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),t},ne=i=>{Oo.get(i)?.unsubscribe(),Oo.delete(i);let t=Vo.get(i);Vo.delete(i),t?Of(i):Vf(i)};import{assertNonNullable as ti,isNonNullable as Ue,isNullable as xP,fromEvent as dr,merge as _f,observableFrom as Nf,filterChanged as Ff,map as ri,Subject as qf,Subscription as PP,ValueSubject as AP,ErrorCategory as kP}from"@vkontakte/videoplayer-shared";import{isNonNullable as _o,isNullable as IP,Subscription as EP}from"@vkontakte/videoplayer-shared";var za=(i,e,t,{equal:r=(n,o)=>n===o,changed$:a,onError:s}={})=>{let n=i.getState(),o=e(),c=IP(a),u=new EP;return a&&u.add(a.subscribe(d=>{let l=i.getState();r(d,l)&&i.setState(d)},s)),r(o,n)||(t(n),c&&i.setState(n)),u.add(i.stateChangeStarted$.subscribe(d=>{t(d.to),c&&i.setState(d.to)},s)),u},qe=(i,e,t)=>za(e,()=>i.loop,r=>{_o(r)&&(i.loop=r)},{onError:t}),oe=(i,e,t,r)=>za(e,()=>({muted:i.muted,volume:i.volume}),a=>{_o(a)&&(i.muted=a.muted,i.volume=a.volume)},{equal:(a,s)=>a===s||a?.muted===s?.muted&&a?.volume===s?.volume,changed$:t,onError:r}),Ie=(i,e,t,r)=>za(e,()=>i.playbackRate,a=>{_o(a)&&(i.playbackRate=a)},{changed$:t,onError:r}),nt=za;var wP=i=>["__",i.language,i.label].join("|"),RP=(i,e)=>{if(i.id===e)return!0;let[t,r,a]=e.split("|");return i.language===r&&i.label===a},No=class i{constructor(){this.available$=new qf;this.current$=new AP(void 0);this.error$=new qf;this.subscription=new PP;this.externalTracks=new Map;this.internalTracks=new Map}connect(e,t,r){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();let a=s=>{this.error$.next({id:"TextTracksManager",category:kP.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(nt(t.internalTextTracks,()=>Object.values(this.internalTracks),s=>{Ue(s)&&this.setInternal(s)},{equal:(s,n)=>Ue(s)&&Ue(n)&&s.length===n.length&&s.every(({id:o},c)=>o===n[c].id),changed$:this.available$.pipe(ri(s=>s.filter(({type:n})=>n==="internal"))),onError:a})),this.subscription.add(nt(t.externalTextTracks,()=>Object.values(this.externalTracks),s=>{Ue(s)&&this.setExternal(s)},{equal:(s,n)=>Ue(s)&&Ue(n)&&s.length===n.length&&s.every(({id:o},c)=>o===n[c].id),changed$:this.available$.pipe(ri(s=>s.filter(({type:n})=>n==="external"))),onError:a})),this.subscription.add(nt(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:a})),this.subscription.add(nt(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.activeCues)}))}subscribe(){ti(this.video);let{textTracks:e}=this.video;this.subscription.add(dr(e,"addtrack").subscribe(()=>{let r=this.current$.getValue();r&&this.select(r)})),this.subscription.add(_f(dr(e,"addtrack"),dr(e,"removetrack"),Nf(["init"])).pipe(ri(()=>this.htmlTextTracksAsArray().map(r=>this.htmlTextTrackToITextTrack(r))),Ff((r,a)=>r.length===a.length&&r.every(({id:s},n)=>s===a[n].id))).subscribe(this.available$)),this.subscription.add(_f(dr(e,"change"),Nf(["init"])).pipe(ri(()=>this.htmlTextTracksAsArray().find(({mode:r})=>r==="showing")),ri(r=>r&&this.htmlTextTrackToITextTrack(r).id),Ff()).subscribe(this.current$));let t=r=>this.applyCueSettings(r.target?.activeCues??null);this.subscription.add(dr(e,"addtrack").subscribe(r=>{r.track?.addEventListener("cuechange",t);let a=s=>{let n=s.target?.cues??null;n&&n.length&&(this.applyCueSettings(s.target?.cues??null),s.target?.removeEventListener("cuechange",a))};r.track?.addEventListener("cuechange",a)})),this.subscription.add(dr(e,"removetrack").subscribe(r=>{r.track?.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;let t=this.cueSettings.getState();for(let r of Array.from(e)){let a=r;Ue(t.align)&&(a.align=t.align),Ue(t.position)&&(a.position=t.position),Ue(t.size)&&(a.size=t.size),Ue(t.line)&&(a.line=t.line)}}htmlTextTracksAsArray(e=!1){ti(this.video);let t=[...this.video.textTracks];return e?t:t.filter(i.isHealthyTrack)}htmlTextTrackToITextTrack(e){let{language:t,label:r}=e,a=e.id?e.id:wP(e),s=this.externalTracks.has(a),n=a.includes("auto");return s?{id:a,type:"external",isAuto:n,language:t,label:r,url:this.externalTracks.get(a)?.url}:{id:a,type:"internal",isAuto:n,language:t,label:r,url:this.internalTracks.get(a)?.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:a,isAuto:s})=>!this.internalTracks.has(r)&&!t.some(([,n])=>n.language===a&&n.isAuto===s)).forEach(r=>this.attach(r)),Array.from(this.internalTracks).filter(([r])=>!e.find(a=>a.id===r)).forEach(([,r])=>this.detach(r))}select(e){ti(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(xP(e)||!RP(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){ti(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){ti(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)}},Ee=No;var Ye=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 Uf=i=>{let e=i;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e?.parentNode;return e??void 0},Fo=i=>{let e=Uf(i);return!!(e&&e.fullscreenElement&&e.fullscreenElement===i)},Hf=i=>{let e=Uf(i);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===i)};import{fromEvent as xe,map as ot,merge as Gf,filterChanged as LP,isNonNullable as Wf,Subject as MP,filter as Yf,mapTo as Qf,combine as CP,once as DP,ErrorCategory as BP,ValueSubject as zf,clientChecker as VP}from"@vkontakte/videoplayer-shared";var $P=3,jf=(i,e,t=$P)=>{let r=0,a=0;for(let s=0;s<i.length;s++){let n=i.start(s),o=i.end(s);if(n<=e&&e<=o){if(r=n,a=o,!t)return{from:r,to:a};for(let c=s-1;c>=0;c--)i.end(c)+t>=r&&(r=i.start(c));for(let c=s+1;c<i.length;c++)i.start(c)-t<=a&&(a=i.end(c))}}return{from:r,to:a}};var ue=i=>{let e=y=>xe(i,y).pipe(Qf(void 0)),r=Gf(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(y=>xe(i,y))).pipe(ot(y=>y.type==="ended"?i.readyState<2:i.readyState<3),LP()),a=Gf(xe(i,"progress"),xe(i,"timeupdate")).pipe(ot(()=>jf(i.buffered,i.currentTime))),s=VP.isSafari?CP({play:e("play").pipe(DP()),playing:e("playing")}).pipe(Qf(void 0)):e("playing"),n=xe(i,"volumechange").pipe(ot(()=>({muted:i.muted,volume:i.volume}))),o=xe(i,"ratechange").pipe(ot(()=>i.playbackRate)),c=xe(i,"error").pipe(Yf(()=>!!(i.error||i.played.length)),ot(()=>{let y=i.error;return{id:y?`MediaError#${y.code}`:"HtmlVideoError",category:BP.VIDEO_PIPELINE,message:y?y.message:"Error event from HTML video element",thrown:i.error??void 0}})),u=xe(i,"timeupdate").pipe(ot(()=>i.currentTime)),d=new MP,l=.3,p;u.subscribe(y=>{i.loop&&Wf(p)&&Wf(y)&&p>=i.duration-l&&y<=l&&d.next(p),p=y});let h=e("pause").pipe(Yf(()=>!i.error&&p!==i.duration)),m=xe(i,"enterpictureinpicture"),b=xe(i,"leavepictureinpicture"),g=new zf(Hf(i));m.subscribe(()=>g.next(!0)),b.subscribe(()=>g.next(!1));let v=new zf(Fo(i));return xe(i,"fullscreenchange").pipe(ot(()=>Fo(i))).subscribe(v),{playing$:s,pause$:h,canplay$:e("canplay"),ended$:e("ended"),looped$:d,error$:c,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:u,durationChange$:xe(i,"durationchange").pipe(ot(()=>i.duration)),isBuffering$:r,currentBuffer$:a,volumeState$:n,playbackRateState$:o,inPiP$:g,inFullscreen$:v}};import{VideoQuality as ut}from"@vkontakte/videoplayer-shared";var ct=i=>{switch(i){case"mobile":return ut.Q_144P;case"lowest":return ut.Q_240P;case"low":return ut.Q_360P;case"sd":case"medium":return ut.Q_480P;case"hd":case"high":return ut.Q_720P;case"fullhd":case"full":return ut.Q_1080P;case"quadhd":case"quad":return ut.Q_1440P;case"ultrahd":case"ultra":return ut.Q_2160P}};var $t=Ne(ii(),1);import{isNonNullable as ce,isNullable as Uo,now as cm,isHigher as Ho,isHigherOrEqual as sm,isInvariantQuality as nm,isLower as jo,isLowerOrEqual as om,videoSizeToQuality as GP,assertNotEmptyArray as lm,assertNonNullable as WP}from"@vkontakte/videoplayer-shared";var qo=!1,Qe={},rm=i=>{qo=i},im=()=>{Qe={}},am=i=>{i(Qe)},ai=(i,e)=>{qo&&(Qe.meta=Qe.meta??{},Qe.meta[i]=e)},X=class{constructor(e){this.name=e}next(e){if(!qo)return;Qe.series=Qe.series??{};let t=Qe.series[this.name]??[];t.push([Date.now(),e]),Qe.series[this.name]=t}};var YP=new X("best_bitrate"),dm=(i,e,t)=>(e-t)*Math.pow(2,-10*i)+t;var Go=i=>(e,t)=>i*(Number(e.bitrate)-Number(t.bitrate)),si=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=cm()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},pm='Assertion "ABR Tracks is empty array" failed',Ka=(i,e,t,r)=>{let a=[...e].sort(Go(1)),s=[...t].sort(Go(1)),n=s.filter(c=>ce(c.bitrate)&&ce(i.bitrate)?i.bitrate/c.bitrate>r:!0),o=(0,$t.default)(s,Math.round(s.length*a.indexOf(i)/(a.length+1)))??(0,$t.default)(s,-1);return o&&n.includes(o)?o:n.length?(0,$t.default)(n,-1):(0,$t.default)(s,0)},um=i=>"quality"in i,hm=(i,e,t,r)=>{let a=t&&r&&r.history[t.id]&&cm()-r.history[t.id]<=i.trackCooldown&&(!r.last||t.id!==r.last.id);if(t?.id&&r&&!a&&r.recordSelection(t),a&&r?.last){let s=r.last;r?.recordSwitch(s);let n=um(s)?"video":"audio",o=um(s)?s.quality:s.bitrate;return e({message:`
6
+ var Hg=Object.create;var zu=Object.defineProperty;var jg=Object.getOwnPropertyDescriptor;var Gg=Object.getOwnPropertyNames;var Wg=Object.getPrototypeOf,Yg=Object.prototype.hasOwnProperty;var f=(i,e)=>()=>(e||i((e={exports:{}}).exports,e),e.exports);var Qg=(i,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of Gg(e))!Yg.call(i,a)&&a!==t&&zu(i,a,{get:()=>e[a],enumerable:!(r=jg(e,a))||r.enumerable});return i};var We=(i,e,t)=>(t=i!=null?Hg(Wg(i)):{},Qg(e||!i||!i.__esModule?zu(t,"default",{value:i,enumerable:!0}):t,i));var be=f((jR,ic)=>{"use strict";ic.exports=function(i){try{return!!i()}catch{return!0}}});var Nr=f((GR,ac)=>{"use strict";var rS=be();ac.exports=!rS(function(){var i=function(){}.bind();return typeof i!="function"||i.hasOwnProperty("prototype")})});var ne=f((WR,oc)=>{"use strict";var sc=Nr(),nc=Function.prototype,Xs=nc.call,iS=sc&&nc.bind.bind(Xs,Xs);oc.exports=sc?iS:function(i){return function(){return Xs.apply(i,arguments)}}});var rr=f((YR,cc)=>{"use strict";var uc=ne(),aS=uc({}.toString),sS=uc("".slice);cc.exports=function(i){return sS(aS(i),8,-1)}});var dc=f((QR,lc)=>{"use strict";var nS=ne(),oS=be(),uS=rr(),Zs=Object,cS=nS("".split);lc.exports=oS(function(){return!Zs("z").propertyIsEnumerable(0)})?function(i){return uS(i)==="String"?cS(i,""):Zs(i)}:Zs});var ir=f((zR,pc)=>{"use strict";pc.exports=function(i){return i==null}});var Fr=f((KR,hc)=>{"use strict";var lS=ir(),dS=TypeError;hc.exports=function(i){if(lS(i))throw new dS("Can't call method on "+i);return i}});var ar=f((JR,fc)=>{"use strict";var pS=dc(),hS=Fr();fc.exports=function(i){return pS(hS(i))}});var en=f((XR,mc)=>{"use strict";mc.exports=function(){}});var Mt=f((ZR,bc)=>{"use strict";bc.exports={}});var H=f((tn,gc)=>{"use strict";var qr=function(i){return i&&i.Math===Math&&i};gc.exports=qr(typeof globalThis=="object"&&globalThis)||qr(typeof window=="object"&&window)||qr(typeof self=="object"&&self)||qr(typeof global=="object"&&global)||qr(typeof tn=="object"&&tn)||function(){return this}()||Function("return this")()});var U=f((e$,Sc)=>{"use strict";var rn=typeof document=="object"&&document.all;Sc.exports=typeof rn>"u"&&rn!==void 0?function(i){return typeof i=="function"||i===rn}:function(i){return typeof i=="function"}});var Tc=f((t$,yc)=>{"use strict";var fS=H(),mS=U(),vc=fS.WeakMap;yc.exports=mS(vc)&&/native code/.test(String(vc))});var Ie=f((r$,Ic)=>{"use strict";var bS=U();Ic.exports=function(i){return typeof i=="object"?i!==null:bS(i)}});var Ee=f((i$,Ec)=>{"use strict";var gS=be();Ec.exports=!gS(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var xa=f((a$,Pc)=>{"use strict";var SS=H(),xc=Ie(),an=SS.document,vS=xc(an)&&xc(an.createElement);Pc.exports=function(i){return vS?an.createElement(i):{}}});var sn=f((s$,Ac)=>{"use strict";var yS=Ee(),TS=be(),IS=xa();Ac.exports=!yS&&!TS(function(){return Object.defineProperty(IS("div"),"a",{get:function(){return 7}}).a!==7})});var nn=f((n$,kc)=>{"use strict";var ES=Ee(),xS=be();kc.exports=ES&&xS(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var Ye=f((o$,wc)=>{"use strict";var PS=Ie(),AS=String,kS=TypeError;wc.exports=function(i){if(PS(i))return i;throw new kS(AS(i)+" is not an object")}});var ge=f((u$,Rc)=>{"use strict";var wS=Nr(),Pa=Function.prototype.call;Rc.exports=wS?Pa.bind(Pa):function(){return Pa.apply(Pa,arguments)}});var Aa=f((c$,$c)=>{"use strict";$c.exports={}});var Ze=f((l$,Mc)=>{"use strict";var on=Aa(),un=H(),RS=U(),Lc=function(i){return RS(i)?i:void 0};Mc.exports=function(i,e){return arguments.length<2?Lc(on[i])||Lc(un[i]):on[i]&&on[i][e]||un[i]&&un[i][e]}});var Ur=f((d$,Cc)=>{"use strict";var $S=ne();Cc.exports=$S({}.isPrototypeOf)});var sr=f((p$,Vc)=>{"use strict";var LS=H(),Dc=LS.navigator,Bc=Dc&&Dc.userAgent;Vc.exports=Bc?String(Bc):""});var ln=f((h$,Uc)=>{"use strict";var qc=H(),cn=sr(),Oc=qc.process,_c=qc.Deno,Nc=Oc&&Oc.versions||_c&&_c.version,Fc=Nc&&Nc.v8,Ve,ka;Fc&&(Ve=Fc.split("."),ka=Ve[0]>0&&Ve[0]<4?1:+(Ve[0]+Ve[1]));!ka&&cn&&(Ve=cn.match(/Edge\/(\d+)/),(!Ve||Ve[1]>=74)&&(Ve=cn.match(/Chrome\/(\d+)/),Ve&&(ka=+Ve[1])));Uc.exports=ka});var dn=f((f$,jc)=>{"use strict";var Hc=ln(),MS=be(),CS=H(),DS=CS.String;jc.exports=!!Object.getOwnPropertySymbols&&!MS(function(){var i=Symbol("symbol detection");return!DS(i)||!(Object(i)instanceof Symbol)||!Symbol.sham&&Hc&&Hc<41})});var pn=f((m$,Gc)=>{"use strict";var BS=dn();Gc.exports=BS&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var hn=f((b$,Wc)=>{"use strict";var VS=Ze(),OS=U(),_S=Ur(),NS=pn(),FS=Object;Wc.exports=NS?function(i){return typeof i=="symbol"}:function(i){var e=VS("Symbol");return OS(e)&&_S(e.prototype,FS(i))}});var Hr=f((g$,Yc)=>{"use strict";var qS=String;Yc.exports=function(i){try{return qS(i)}catch{return"Object"}}});var et=f((S$,Qc)=>{"use strict";var US=U(),HS=Hr(),jS=TypeError;Qc.exports=function(i){if(US(i))return i;throw new jS(HS(i)+" is not a function")}});var jr=f((v$,zc)=>{"use strict";var GS=et(),WS=ir();zc.exports=function(i,e){var t=i[e];return WS(t)?void 0:GS(t)}});var Jc=f((y$,Kc)=>{"use strict";var fn=ge(),mn=U(),bn=Ie(),YS=TypeError;Kc.exports=function(i,e){var t,r;if(e==="string"&&mn(t=i.toString)&&!bn(r=fn(t,i))||mn(t=i.valueOf)&&!bn(r=fn(t,i))||e!=="string"&&mn(t=i.toString)&&!bn(r=fn(t,i)))return r;throw new YS("Can't convert object to primitive value")}});var Oe=f((T$,Xc)=>{"use strict";Xc.exports=!0});var tl=f((I$,el)=>{"use strict";var Zc=H(),QS=Object.defineProperty;el.exports=function(i,e){try{QS(Zc,i,{value:e,configurable:!0,writable:!0})}catch{Zc[i]=e}return e}});var Gr=f((E$,al)=>{"use strict";var zS=Oe(),KS=H(),JS=tl(),rl="__core-js_shared__",il=al.exports=KS[rl]||JS(rl,{});(il.versions||(il.versions=[])).push({version:"3.38.0",mode:zS?"pure":"global",copyright:"\xA9 2014-2024 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.38.0/LICENSE",source:"https://github.com/zloirock/core-js"})});var gn=f((x$,nl)=>{"use strict";var sl=Gr();nl.exports=function(i,e){return sl[i]||(sl[i]=e||{})}});var Wr=f((P$,ol)=>{"use strict";var XS=Fr(),ZS=Object;ol.exports=function(i){return ZS(XS(i))}});var _e=f((A$,ul)=>{"use strict";var ev=ne(),tv=Wr(),rv=ev({}.hasOwnProperty);ul.exports=Object.hasOwn||function(e,t){return rv(tv(e),t)}});var Sn=f((k$,cl)=>{"use strict";var iv=ne(),av=0,sv=Math.random(),nv=iv(1 .toString);cl.exports=function(i){return"Symbol("+(i===void 0?"":i)+")_"+nv(++av+sv,36)}});var ee=f((w$,dl)=>{"use strict";var ov=H(),uv=gn(),ll=_e(),cv=Sn(),lv=dn(),dv=pn(),nr=ov.Symbol,vn=uv("wks"),pv=dv?nr.for||nr:nr&&nr.withoutSetter||cv;dl.exports=function(i){return ll(vn,i)||(vn[i]=lv&&ll(nr,i)?nr[i]:pv("Symbol."+i)),vn[i]}});var ml=f((R$,fl)=>{"use strict";var hv=ge(),pl=Ie(),hl=hn(),fv=jr(),mv=Jc(),bv=ee(),gv=TypeError,Sv=bv("toPrimitive");fl.exports=function(i,e){if(!pl(i)||hl(i))return i;var t=fv(i,Sv),r;if(t){if(e===void 0&&(e="default"),r=hv(t,i,e),!pl(r)||hl(r))return r;throw new gv("Can't convert object to primitive value")}return e===void 0&&(e="number"),mv(i,e)}});var yn=f(($$,bl)=>{"use strict";var vv=ml(),yv=hn();bl.exports=function(i){var e=vv(i,"string");return yv(e)?e:e+""}});var Ct=f(Sl=>{"use strict";var Tv=Ee(),Iv=sn(),Ev=nn(),wa=Ye(),gl=yn(),xv=TypeError,Tn=Object.defineProperty,Pv=Object.getOwnPropertyDescriptor,In="enumerable",En="configurable",xn="writable";Sl.f=Tv?Ev?function(e,t,r){if(wa(e),t=gl(t),wa(r),typeof e=="function"&&t==="prototype"&&"value"in r&&xn in r&&!r[xn]){var a=Pv(e,t);a&&a[xn]&&(e[t]=r.value,r={configurable:En in r?r[En]:a[En],enumerable:In in r?r[In]:a[In],writable:!1})}return Tn(e,t,r)}:Tn:function(e,t,r){if(wa(e),t=gl(t),wa(r),Iv)try{return Tn(e,t,r)}catch{}if("get"in r||"set"in r)throw new xv("Accessors not supported");return"value"in r&&(e[t]=r.value),e}});var Yr=f((M$,vl)=>{"use strict";vl.exports=function(i,e){return{enumerable:!(i&1),configurable:!(i&2),writable:!(i&4),value:e}}});var or=f((C$,yl)=>{"use strict";var Av=Ee(),kv=Ct(),wv=Yr();yl.exports=Av?function(i,e,t){return kv.f(i,e,wv(1,t))}:function(i,e,t){return i[e]=t,i}});var Ra=f((D$,Il)=>{"use strict";var Rv=gn(),$v=Sn(),Tl=Rv("keys");Il.exports=function(i){return Tl[i]||(Tl[i]=$v(i))}});var $a=f((B$,El)=>{"use strict";El.exports={}});var wn=f((V$,Al)=>{"use strict";var Lv=Tc(),Pl=H(),Mv=Ie(),Cv=or(),Pn=_e(),An=Gr(),Dv=Ra(),Bv=$a(),xl="Object already initialized",kn=Pl.TypeError,Vv=Pl.WeakMap,La,Qr,Ma,Ov=function(i){return Ma(i)?Qr(i):La(i,{})},_v=function(i){return function(e){var t;if(!Mv(e)||(t=Qr(e)).type!==i)throw new kn("Incompatible receiver, "+i+" required");return t}};Lv||An.state?(Ne=An.state||(An.state=new Vv),Ne.get=Ne.get,Ne.has=Ne.has,Ne.set=Ne.set,La=function(i,e){if(Ne.has(i))throw new kn(xl);return e.facade=i,Ne.set(i,e),e},Qr=function(i){return Ne.get(i)||{}},Ma=function(i){return Ne.has(i)}):(Dt=Dv("state"),Bv[Dt]=!0,La=function(i,e){if(Pn(i,Dt))throw new kn(xl);return e.facade=i,Cv(i,Dt,e),e},Qr=function(i){return Pn(i,Dt)?i[Dt]:{}},Ma=function(i){return Pn(i,Dt)});var Ne,Dt;Al.exports={set:La,get:Qr,has:Ma,enforce:Ov,getterFor:_v}});var Rn=f((O$,$l)=>{"use strict";var Nv=Nr(),Rl=Function.prototype,kl=Rl.apply,wl=Rl.call;$l.exports=typeof Reflect=="object"&&Reflect.apply||(Nv?wl.bind(kl):function(){return wl.apply(kl,arguments)})});var $n=f((_$,Ll)=>{"use strict";var Fv=rr(),qv=ne();Ll.exports=function(i){if(Fv(i)==="Function")return qv(i)}});var Bl=f(Dl=>{"use strict";var Ml={}.propertyIsEnumerable,Cl=Object.getOwnPropertyDescriptor,Uv=Cl&&!Ml.call({1:2},1);Dl.f=Uv?function(e){var t=Cl(this,e);return!!t&&t.enumerable}:Ml});var _l=f(Ol=>{"use strict";var Hv=Ee(),jv=ge(),Gv=Bl(),Wv=Yr(),Yv=ar(),Qv=yn(),zv=_e(),Kv=sn(),Vl=Object.getOwnPropertyDescriptor;Ol.f=Hv?Vl:function(e,t){if(e=Yv(e),t=Qv(t),Kv)try{return Vl(e,t)}catch{}if(zv(e,t))return Wv(!jv(Gv.f,e,t),e[t])}});var Ln=f((q$,Nl)=>{"use strict";var Jv=be(),Xv=U(),Zv=/#|\.prototype\./,zr=function(i,e){var t=ty[ey(i)];return t===iy?!0:t===ry?!1:Xv(e)?Jv(e):!!e},ey=zr.normalize=function(i){return String(i).replace(Zv,".").toLowerCase()},ty=zr.data={},ry=zr.NATIVE="N",iy=zr.POLYFILL="P";Nl.exports=zr});var Kr=f((U$,ql)=>{"use strict";var Fl=$n(),ay=et(),sy=Nr(),ny=Fl(Fl.bind);ql.exports=function(i,e){return ay(i),e===void 0?i:sy?ny(i,e):function(){return i.apply(e,arguments)}}});var xe=f((H$,Hl)=>{"use strict";var Jr=H(),oy=Rn(),uy=$n(),cy=U(),ly=_l().f,dy=Ln(),ur=Aa(),py=Kr(),cr=or(),Ul=_e();Gr();var hy=function(i){var e=function(t,r,a){if(this instanceof e){switch(arguments.length){case 0:return new i;case 1:return new i(t);case 2:return new i(t,r)}return new i(t,r,a)}return oy(i,this,arguments)};return e.prototype=i.prototype,e};Hl.exports=function(i,e){var t=i.target,r=i.global,a=i.stat,s=i.proto,n=r?Jr:a?Jr[t]:Jr[t]&&Jr[t].prototype,o=r?ur:ur[t]||cr(ur,t,{})[t],c=o.prototype,u,d,l,p,h,m,b,g,v;for(p in e)u=dy(r?p:t+(a?".":"#")+p,i.forced),d=!u&&n&&Ul(n,p),m=o[p],d&&(i.dontCallGetSet?(v=ly(n,p),b=v&&v.value):b=n[p]),h=d&&b?b:e[p],!(!u&&!s&&typeof m==typeof h)&&(i.bind&&d?g=py(h,Jr):i.wrap&&d?g=hy(h):s&&cy(h)?g=uy(h):g=h,(i.sham||h&&h.sham||m&&m.sham)&&cr(g,"sham",!0),cr(o,p,g),s&&(l=t+"Prototype",Ul(ur,l)||cr(ur,l,{}),cr(ur[l],p,h),i.real&&c&&(u||!c[p])&&cr(c,p,h)))}});var Wl=f((j$,Gl)=>{"use strict";var Mn=Ee(),fy=_e(),jl=Function.prototype,my=Mn&&Object.getOwnPropertyDescriptor,Cn=fy(jl,"name"),by=Cn&&function(){}.name==="something",gy=Cn&&(!Mn||Mn&&my(jl,"name").configurable);Gl.exports={EXISTS:Cn,PROPER:by,CONFIGURABLE:gy}});var Ql=f((G$,Yl)=>{"use strict";var Sy=Math.ceil,vy=Math.floor;Yl.exports=Math.trunc||function(e){var t=+e;return(t>0?vy:Sy)(t)}});var Ca=f((W$,zl)=>{"use strict";var yy=Ql();zl.exports=function(i){var e=+i;return e!==e||e===0?0:yy(e)}});var Jl=f((Y$,Kl)=>{"use strict";var Ty=Ca(),Iy=Math.max,Ey=Math.min;Kl.exports=function(i,e){var t=Ty(i);return t<0?Iy(t+e,0):Ey(t,e)}});var Zl=f((Q$,Xl)=>{"use strict";var xy=Ca(),Py=Math.min;Xl.exports=function(i){var e=xy(i);return e>0?Py(e,9007199254740991):0}});var Da=f((z$,ed)=>{"use strict";var Ay=Zl();ed.exports=function(i){return Ay(i.length)}});var id=f((K$,rd)=>{"use strict";var ky=ar(),wy=Jl(),Ry=Da(),td=function(i){return function(e,t,r){var a=ky(e),s=Ry(a);if(s===0)return!i&&-1;var n=wy(r,s),o;if(i&&t!==t){for(;s>n;)if(o=a[n++],o!==o)return!0}else for(;s>n;n++)if((i||n in a)&&a[n]===t)return i||n||0;return!i&&-1}};rd.exports={includes:td(!0),indexOf:td(!1)}});var nd=f((J$,sd)=>{"use strict";var $y=ne(),Dn=_e(),Ly=ar(),My=id().indexOf,Cy=$a(),ad=$y([].push);sd.exports=function(i,e){var t=Ly(i),r=0,a=[],s;for(s in t)!Dn(Cy,s)&&Dn(t,s)&&ad(a,s);for(;e.length>r;)Dn(t,s=e[r++])&&(~My(a,s)||ad(a,s));return a}});var Bn=f((X$,od)=>{"use strict";od.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var cd=f((Z$,ud)=>{"use strict";var Dy=nd(),By=Bn();ud.exports=Object.keys||function(e){return Dy(e,By)}});var dd=f(ld=>{"use strict";var Vy=Ee(),Oy=nn(),_y=Ct(),Ny=Ye(),Fy=ar(),qy=cd();ld.f=Vy&&!Oy?Object.defineProperties:function(e,t){Ny(e);for(var r=Fy(t),a=qy(t),s=a.length,n=0,o;s>n;)_y.f(e,o=a[n++],r[o]);return e}});var Vn=f((tL,pd)=>{"use strict";var Uy=Ze();pd.exports=Uy("document","documentElement")});var Fn=f((rL,vd)=>{"use strict";var Hy=Ye(),jy=dd(),hd=Bn(),Gy=$a(),Wy=Vn(),Yy=xa(),Qy=Ra(),fd=">",md="<",_n="prototype",Nn="script",gd=Qy("IE_PROTO"),On=function(){},Sd=function(i){return md+Nn+fd+i+md+"/"+Nn+fd},bd=function(i){i.write(Sd("")),i.close();var e=i.parentWindow.Object;return i=null,e},zy=function(){var i=Yy("iframe"),e="java"+Nn+":",t;return i.style.display="none",Wy.appendChild(i),i.src=String(e),t=i.contentWindow.document,t.open(),t.write(Sd("document.F=Object")),t.close(),t.F},Ba,Va=function(){try{Ba=new ActiveXObject("htmlfile")}catch{}Va=typeof document<"u"?document.domain&&Ba?bd(Ba):zy():bd(Ba);for(var i=hd.length;i--;)delete Va[_n][hd[i]];return Va()};Gy[gd]=!0;vd.exports=Object.create||function(e,t){var r;return e!==null?(On[_n]=Hy(e),r=new On,On[_n]=null,r[gd]=e):r=Va(),t===void 0?r:jy.f(r,t)}});var Td=f((iL,yd)=>{"use strict";var Ky=be();yd.exports=!Ky(function(){function i(){}return i.prototype.constructor=null,Object.getPrototypeOf(new i)!==i.prototype})});var Un=f((aL,Ed)=>{"use strict";var Jy=_e(),Xy=U(),Zy=Wr(),eT=Ra(),tT=Td(),Id=eT("IE_PROTO"),qn=Object,rT=qn.prototype;Ed.exports=tT?qn.getPrototypeOf:function(i){var e=Zy(i);if(Jy(e,Id))return e[Id];var t=e.constructor;return Xy(t)&&e instanceof t?t.prototype:e instanceof qn?rT:null}});var lr=f((sL,xd)=>{"use strict";var iT=or();xd.exports=function(i,e,t,r){return r&&r.enumerable?i[e]=t:iT(i,e,t),i}});var Wn=f((nL,kd)=>{"use strict";var aT=be(),sT=U(),nT=Ie(),oT=Fn(),Pd=Un(),uT=lr(),cT=ee(),lT=Oe(),Gn=cT("iterator"),Ad=!1,tt,Hn,jn;[].keys&&(jn=[].keys(),"next"in jn?(Hn=Pd(Pd(jn)),Hn!==Object.prototype&&(tt=Hn)):Ad=!0);var dT=!nT(tt)||aT(function(){var i={};return tt[Gn].call(i)!==i});dT?tt={}:lT&&(tt=oT(tt));sT(tt[Gn])||uT(tt,Gn,function(){return this});kd.exports={IteratorPrototype:tt,BUGGY_SAFARI_ITERATORS:Ad}});var Oa=f((oL,Rd)=>{"use strict";var pT=ee(),hT=pT("toStringTag"),wd={};wd[hT]="z";Rd.exports=String(wd)==="[object z]"});var Xr=f((uL,$d)=>{"use strict";var fT=Oa(),mT=U(),_a=rr(),bT=ee(),gT=bT("toStringTag"),ST=Object,vT=_a(function(){return arguments}())==="Arguments",yT=function(i,e){try{return i[e]}catch{}};$d.exports=fT?_a:function(i){var e,t,r;return i===void 0?"Undefined":i===null?"Null":typeof(t=yT(e=ST(i),gT))=="string"?t:vT?_a(e):(r=_a(e))==="Object"&&mT(e.callee)?"Arguments":r}});var Md=f((cL,Ld)=>{"use strict";var TT=Oa(),IT=Xr();Ld.exports=TT?{}.toString:function(){return"[object "+IT(this)+"]"}});var Zr=f((lL,Dd)=>{"use strict";var ET=Oa(),xT=Ct().f,PT=or(),AT=_e(),kT=Md(),wT=ee(),Cd=wT("toStringTag");Dd.exports=function(i,e,t,r){var a=t?i:i&&i.prototype;a&&(AT(a,Cd)||xT(a,Cd,{configurable:!0,value:e}),r&&!ET&&PT(a,"toString",kT))}});var Vd=f((dL,Bd)=>{"use strict";var RT=Wn().IteratorPrototype,$T=Fn(),LT=Yr(),MT=Zr(),CT=Mt(),DT=function(){return this};Bd.exports=function(i,e,t,r){var a=e+" Iterator";return i.prototype=$T(RT,{next:LT(+!r,t)}),MT(i,a,!1,!0),CT[a]=DT,i}});var _d=f((pL,Od)=>{"use strict";var BT=ne(),VT=et();Od.exports=function(i,e,t){try{return BT(VT(Object.getOwnPropertyDescriptor(i,e)[t]))}catch{}}});var Fd=f((hL,Nd)=>{"use strict";var OT=Ie();Nd.exports=function(i){return OT(i)||i===null}});var Ud=f((fL,qd)=>{"use strict";var _T=Fd(),NT=String,FT=TypeError;qd.exports=function(i){if(_T(i))return i;throw new FT("Can't set "+NT(i)+" as a prototype")}});var Yn=f((mL,Hd)=>{"use strict";var qT=_d(),UT=Ie(),HT=Fr(),jT=Ud();Hd.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var i=!1,e={},t;try{t=qT(Object.prototype,"__proto__","set"),t(e,[]),i=e instanceof Array}catch{}return function(a,s){return HT(a),jT(s),UT(a)&&(i?t(a,s):a.__proto__=s),a}}():void 0)});var ep=f((bL,Zd)=>{"use strict";var GT=xe(),WT=ge(),Na=Oe(),Jd=Wl(),YT=U(),QT=Vd(),jd=Un(),Gd=Yn(),zT=Zr(),KT=or(),Qn=lr(),JT=ee(),Wd=Mt(),Xd=Wn(),XT=Jd.PROPER,ZT=Jd.CONFIGURABLE,Yd=Xd.IteratorPrototype,Fa=Xd.BUGGY_SAFARI_ITERATORS,ei=JT("iterator"),Qd="keys",ti="values",zd="entries",Kd=function(){return this};Zd.exports=function(i,e,t,r,a,s,n){QT(t,e,r);var o=function(v){if(v===a&&p)return p;if(!Fa&&v&&v in d)return d[v];switch(v){case Qd:return function(){return new t(this,v)};case ti:return function(){return new t(this,v)};case zd:return function(){return new t(this,v)}}return function(){return new t(this)}},c=e+" Iterator",u=!1,d=i.prototype,l=d[ei]||d["@@iterator"]||a&&d[a],p=!Fa&&l||o(a),h=e==="Array"&&d.entries||l,m,b,g;if(h&&(m=jd(h.call(new i)),m!==Object.prototype&&m.next&&(!Na&&jd(m)!==Yd&&(Gd?Gd(m,Yd):YT(m[ei])||Qn(m,ei,Kd)),zT(m,c,!0,!0),Na&&(Wd[c]=Kd))),XT&&a===ti&&l&&l.name!==ti&&(!Na&&ZT?KT(d,"name",ti):(u=!0,p=function(){return WT(l,this)})),a)if(b={values:o(ti),keys:s?p:o(Qd),entries:o(zd)},n)for(g in b)(Fa||u||!(g in d))&&Qn(d,g,b[g]);else GT({target:e,proto:!0,forced:Fa||u},b);return(!Na||n)&&d[ei]!==p&&Qn(d,ei,p,{name:a}),Wd[e]=p,b}});var rp=f((gL,tp)=>{"use strict";tp.exports=function(i,e){return{value:i,done:e}}});var Kn=f((SL,op)=>{"use strict";var eI=ar(),zn=en(),ip=Mt(),sp=wn(),tI=Ct().f,rI=ep(),qa=rp(),iI=Oe(),aI=Ee(),np="Array Iterator",sI=sp.set,nI=sp.getterFor(np);op.exports=rI(Array,"Array",function(i,e){sI(this,{type:np,target:eI(i),index:0,kind:e})},function(){var i=nI(this),e=i.target,t=i.index++;if(!e||t>=e.length)return i.target=void 0,qa(void 0,!0);switch(i.kind){case"keys":return qa(t,!1);case"values":return qa(e[t],!1)}return qa([t,e[t]],!1)},"values");var ap=ip.Arguments=ip.Array;zn("keys");zn("values");zn("entries");if(!iI&&aI&&ap.name!=="values")try{tI(ap,"name",{value:"values"})}catch{}});var cp=f((vL,up)=>{"use strict";var oI=ee(),uI=Mt(),cI=oI("iterator"),lI=Array.prototype;up.exports=function(i){return i!==void 0&&(uI.Array===i||lI[cI]===i)}});var Jn=f((yL,dp)=>{"use strict";var dI=Xr(),lp=jr(),pI=ir(),hI=Mt(),fI=ee(),mI=fI("iterator");dp.exports=function(i){if(!pI(i))return lp(i,mI)||lp(i,"@@iterator")||hI[dI(i)]}});var hp=f((TL,pp)=>{"use strict";var bI=ge(),gI=et(),SI=Ye(),vI=Hr(),yI=Jn(),TI=TypeError;pp.exports=function(i,e){var t=arguments.length<2?yI(i):e;if(gI(t))return SI(bI(t,i));throw new TI(vI(i)+" is not iterable")}});var bp=f((IL,mp)=>{"use strict";var II=ge(),fp=Ye(),EI=jr();mp.exports=function(i,e,t){var r,a;fp(i);try{if(r=EI(i,"return"),!r){if(e==="throw")throw t;return t}r=II(r,i)}catch(s){a=!0,r=s}if(e==="throw")throw t;if(a)throw r;return fp(r),t}});var Ha=f((EL,yp)=>{"use strict";var xI=Kr(),PI=ge(),AI=Ye(),kI=Hr(),wI=cp(),RI=Da(),gp=Ur(),$I=hp(),LI=Jn(),Sp=bp(),MI=TypeError,Ua=function(i,e){this.stopped=i,this.result=e},vp=Ua.prototype;yp.exports=function(i,e,t){var r=t&&t.that,a=!!(t&&t.AS_ENTRIES),s=!!(t&&t.IS_RECORD),n=!!(t&&t.IS_ITERATOR),o=!!(t&&t.INTERRUPTED),c=xI(e,r),u,d,l,p,h,m,b,g=function(k){return u&&Sp(u,"normal",k),new Ua(!0,k)},v=function(k){return a?(AI(k),o?c(k[0],k[1],g):c(k[0],k[1])):o?c(k,g):c(k)};if(s)u=i.iterator;else if(n)u=i;else{if(d=LI(i),!d)throw new MI(kI(i)+" is not iterable");if(wI(d)){for(l=0,p=RI(i);p>l;l++)if(h=v(i[l]),h&&gp(vp,h))return h;return new Ua(!1)}u=$I(i,d)}for(m=s?i.next:u.next;!(b=PI(m,u)).done;){try{h=v(b.value)}catch(k){Sp(u,"throw",k)}if(typeof h=="object"&&h&&gp(vp,h))return h}return new Ua(!1)}});var Ip=f((xL,Tp)=>{"use strict";var CI=Ee(),DI=Ct(),BI=Yr();Tp.exports=function(i,e,t){CI?DI.f(i,e,BI(0,t)):i[e]=t}});var Ep=f(()=>{"use strict";var VI=xe(),OI=Ha(),_I=Ip();VI({target:"Object",stat:!0},{fromEntries:function(e){var t={};return OI(e,function(r,a){_I(t,r,a)},{AS_ENTRIES:!0}),t}})});var Pp=f((kL,xp)=>{"use strict";Kn();Ep();var NI=Aa();xp.exports=NI.Object.fromEntries});var kp=f((wL,Ap)=>{"use strict";Ap.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 Rp=f(()=>{"use strict";Kn();var FI=kp(),qI=H(),UI=Zr(),wp=Mt();for(ja in FI)UI(qI[ja],ja),wp[ja]=wp.Array;var ja});var Lp=f((LL,$p)=>{"use strict";var HI=Pp();Rp();$p.exports=HI});var Xn=f((ML,Mp)=>{"use strict";var jI=Lp();Mp.exports=jI});var Cp=f(()=>{"use strict"});var Zn=f((BL,Dp)=>{"use strict";var ri=H(),GI=sr(),WI=rr(),Ga=function(i){return GI.slice(0,i.length)===i};Dp.exports=function(){return Ga("Bun/")?"BUN":Ga("Cloudflare-Workers")?"CLOUDFLARE":Ga("Deno/")?"DENO":Ga("Node.js/")?"NODE":ri.Bun&&typeof Bun.version=="string"?"BUN":ri.Deno&&typeof Deno.version=="object"?"DENO":WI(ri.process)==="process"?"NODE":ri.window&&ri.document?"BROWSER":"REST"}()});var Wa=f((VL,Bp)=>{"use strict";var YI=Zn();Bp.exports=YI==="NODE"});var Op=f((OL,Vp)=>{"use strict";var QI=Ct();Vp.exports=function(i,e,t){return QI.f(i,e,t)}});var Fp=f((_L,Np)=>{"use strict";var zI=Ze(),KI=Op(),JI=ee(),XI=Ee(),_p=JI("species");Np.exports=function(i){var e=zI(i);XI&&e&&!e[_p]&&KI(e,_p,{configurable:!0,get:function(){return this}})}});var Up=f((NL,qp)=>{"use strict";var ZI=Ur(),eE=TypeError;qp.exports=function(i,e){if(ZI(e,i))return i;throw new eE("Incorrect invocation")}});var to=f((FL,Hp)=>{"use strict";var tE=ne(),rE=U(),eo=Gr(),iE=tE(Function.toString);rE(eo.inspectSource)||(eo.inspectSource=function(i){return iE(i)});Hp.exports=eo.inspectSource});var zp=f((qL,Qp)=>{"use strict";var aE=ne(),sE=be(),jp=U(),nE=Xr(),oE=Ze(),uE=to(),Gp=function(){},Wp=oE("Reflect","construct"),ro=/^\s*(?:class|function)\b/,cE=aE(ro.exec),lE=!ro.test(Gp),ii=function(e){if(!jp(e))return!1;try{return Wp(Gp,[],e),!0}catch{return!1}},Yp=function(e){if(!jp(e))return!1;switch(nE(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return lE||!!cE(ro,uE(e))}catch{return!0}};Yp.sham=!0;Qp.exports=!Wp||sE(function(){var i;return ii(ii.call)||!ii(Object)||!ii(function(){i=!0})||i})?Yp:ii});var Jp=f((UL,Kp)=>{"use strict";var dE=zp(),pE=Hr(),hE=TypeError;Kp.exports=function(i){if(dE(i))return i;throw new hE(pE(i)+" is not a constructor")}});var io=f((HL,Zp)=>{"use strict";var Xp=Ye(),fE=Jp(),mE=ir(),bE=ee(),gE=bE("species");Zp.exports=function(i,e){var t=Xp(i).constructor,r;return t===void 0||mE(r=Xp(t)[gE])?e:fE(r)}});var th=f((jL,eh)=>{"use strict";var SE=ne();eh.exports=SE([].slice)});var ih=f((GL,rh)=>{"use strict";var vE=TypeError;rh.exports=function(i,e){if(i<e)throw new vE("Not enough arguments");return i}});var ao=f((WL,ah)=>{"use strict";var yE=sr();ah.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(yE)});var fo=f((YL,hh)=>{"use strict";var Se=H(),TE=Rn(),IE=Kr(),sh=U(),EE=_e(),ph=be(),nh=Vn(),xE=th(),oh=xa(),PE=ih(),AE=ao(),kE=Wa(),lo=Se.setImmediate,po=Se.clearImmediate,wE=Se.process,so=Se.Dispatch,RE=Se.Function,uh=Se.MessageChannel,$E=Se.String,no=0,ai={},ch="onreadystatechange",si,Bt,oo,uo;ph(function(){si=Se.location});var ho=function(i){if(EE(ai,i)){var e=ai[i];delete ai[i],e()}},co=function(i){return function(){ho(i)}},lh=function(i){ho(i.data)},dh=function(i){Se.postMessage($E(i),si.protocol+"//"+si.host)};(!lo||!po)&&(lo=function(e){PE(arguments.length,1);var t=sh(e)?e:RE(e),r=xE(arguments,1);return ai[++no]=function(){TE(t,void 0,r)},Bt(no),no},po=function(e){delete ai[e]},kE?Bt=function(i){wE.nextTick(co(i))}:so&&so.now?Bt=function(i){so.now(co(i))}:uh&&!AE?(oo=new uh,uo=oo.port2,oo.port1.onmessage=lh,Bt=IE(uo.postMessage,uo)):Se.addEventListener&&sh(Se.postMessage)&&!Se.importScripts&&si&&si.protocol!=="file:"&&!ph(dh)?(Bt=dh,Se.addEventListener("message",lh,!1)):ch in oh("script")?Bt=function(i){nh.appendChild(oh("script"))[ch]=function(){nh.removeChild(this),ho(i)}}:Bt=function(i){setTimeout(co(i),0)});hh.exports={set:lo,clear:po}});var bh=f((QL,mh)=>{"use strict";var fh=H(),LE=Ee(),ME=Object.getOwnPropertyDescriptor;mh.exports=function(i){if(!LE)return fh[i];var e=ME(fh,i);return e&&e.value}});var mo=f((zL,Sh)=>{"use strict";var gh=function(){this.head=null,this.tail=null};gh.prototype={add:function(i){var e={item:i,next:null},t=this.tail;t?t.next=e:this.head=e,this.tail=e},get:function(){var i=this.head;if(i){var e=this.head=i.next;return e===null&&(this.tail=null),i.item}}};Sh.exports=gh});var yh=f((KL,vh)=>{"use strict";var CE=sr();vh.exports=/ipad|iphone|ipod/i.test(CE)&&typeof Pebble<"u"});var Ih=f((JL,Th)=>{"use strict";var DE=sr();Th.exports=/web0s(?!.*chrome)/i.test(DE)});var Rh=f((XL,wh)=>{"use strict";var pr=H(),BE=bh(),Eh=Kr(),bo=fo().set,VE=mo(),OE=ao(),_E=yh(),NE=Ih(),go=Wa(),xh=pr.MutationObserver||pr.WebKitMutationObserver,Ph=pr.document,Ah=pr.process,Ya=pr.Promise,yo=BE("queueMicrotask"),dr,So,vo,Qa,kh;yo||(ni=new VE,oi=function(){var i,e;for(go&&(i=Ah.domain)&&i.exit();e=ni.get();)try{e()}catch(t){throw ni.head&&dr(),t}i&&i.enter()},!OE&&!go&&!NE&&xh&&Ph?(So=!0,vo=Ph.createTextNode(""),new xh(oi).observe(vo,{characterData:!0}),dr=function(){vo.data=So=!So}):!_E&&Ya&&Ya.resolve?(Qa=Ya.resolve(void 0),Qa.constructor=Ya,kh=Eh(Qa.then,Qa),dr=function(){kh(oi)}):go?dr=function(){Ah.nextTick(oi)}:(bo=Eh(bo,pr),dr=function(){bo(oi)}),yo=function(i){ni.head||dr(),ni.add(i)});var ni,oi;wh.exports=yo});var Lh=f((ZL,$h)=>{"use strict";$h.exports=function(i,e){try{arguments.length===1?console.error(i):console.error(i,e)}catch{}}});var za=f((eM,Mh)=>{"use strict";Mh.exports=function(i){try{return{error:!1,value:i()}}catch(e){return{error:!0,value:e}}}});var Vt=f((tM,Ch)=>{"use strict";var FE=H();Ch.exports=FE.Promise});var hr=f((rM,Oh)=>{"use strict";var qE=H(),ui=Vt(),UE=U(),HE=Ln(),jE=to(),GE=ee(),Dh=Zn(),WE=Oe(),To=ln(),Bh=ui&&ui.prototype,YE=GE("species"),Io=!1,Vh=UE(qE.PromiseRejectionEvent),QE=HE("Promise",function(){var i=jE(ui),e=i!==String(ui);if(!e&&To===66||WE&&!(Bh.catch&&Bh.finally))return!0;if(!To||To<51||!/native code/.test(i)){var t=new ui(function(s){s(1)}),r=function(s){s(function(){},function(){})},a=t.constructor={};if(a[YE]=r,Io=t.then(function(){})instanceof r,!Io)return!0}return!e&&(Dh==="BROWSER"||Dh==="DENO")&&!Vh});Oh.exports={CONSTRUCTOR:QE,REJECTION_EVENT:Vh,SUBCLASSING:Io}});var fr=f((iM,Nh)=>{"use strict";var _h=et(),zE=TypeError,KE=function(i){var e,t;this.promise=new i(function(r,a){if(e!==void 0||t!==void 0)throw new zE("Bad Promise constructor");e=r,t=a}),this.resolve=_h(e),this.reject=_h(t)};Nh.exports.f=function(i){return new KE(i)}});var sf=f(()=>{"use strict";var JE=xe(),XE=Oe(),Za=Wa(),mt=H(),Sr=ge(),Fh=lr(),qh=Yn(),ZE=Zr(),ex=Fp(),tx=et(),Xa=U(),rx=Ie(),ix=Up(),ax=io(),Wh=fo().set,ko=Rh(),sx=Lh(),nx=za(),ox=mo(),Yh=wn(),es=Vt(),wo=hr(),Qh=fr(),ts="Promise",zh=wo.CONSTRUCTOR,ux=wo.REJECTION_EVENT,cx=wo.SUBCLASSING,Eo=Yh.getterFor(ts),lx=Yh.set,mr=es&&es.prototype,Ot=es,Ka=mr,Kh=mt.TypeError,xo=mt.document,Ro=mt.process,Po=Qh.f,dx=Po,px=!!(xo&&xo.createEvent&&mt.dispatchEvent),Jh="unhandledrejection",hx="rejectionhandled",Uh=0,Xh=1,fx=2,$o=1,Zh=2,Ja,Hh,mx,jh,ef=function(i){var e;return rx(i)&&Xa(e=i.then)?e:!1},tf=function(i,e){var t=e.value,r=e.state===Xh,a=r?i.ok:i.fail,s=i.resolve,n=i.reject,o=i.domain,c,u,d;try{a?(r||(e.rejection===Zh&&gx(e),e.rejection=$o),a===!0?c=t:(o&&o.enter(),c=a(t),o&&(o.exit(),d=!0)),c===i.promise?n(new Kh("Promise-chain cycle")):(u=ef(c))?Sr(u,c,s,n):s(c)):n(t)}catch(l){o&&!d&&o.exit(),n(l)}},rf=function(i,e){i.notified||(i.notified=!0,ko(function(){for(var t=i.reactions,r;r=t.get();)tf(r,i);i.notified=!1,e&&!i.rejection&&bx(i)}))},af=function(i,e,t){var r,a;px?(r=xo.createEvent("Event"),r.promise=e,r.reason=t,r.initEvent(i,!1,!0),mt.dispatchEvent(r)):r={promise:e,reason:t},!ux&&(a=mt["on"+i])?a(r):i===Jh&&sx("Unhandled promise rejection",t)},bx=function(i){Sr(Wh,mt,function(){var e=i.facade,t=i.value,r=Gh(i),a;if(r&&(a=nx(function(){Za?Ro.emit("unhandledRejection",t,e):af(Jh,e,t)}),i.rejection=Za||Gh(i)?Zh:$o,a.error))throw a.value})},Gh=function(i){return i.rejection!==$o&&!i.parent},gx=function(i){Sr(Wh,mt,function(){var e=i.facade;Za?Ro.emit("rejectionHandled",e):af(hx,e,i.value)})},br=function(i,e,t){return function(r){i(e,r,t)}},gr=function(i,e,t){i.done||(i.done=!0,t&&(i=t),i.value=e,i.state=fx,rf(i,!0))},Ao=function(i,e,t){if(!i.done){i.done=!0,t&&(i=t);try{if(i.facade===e)throw new Kh("Promise can't be resolved itself");var r=ef(e);r?ko(function(){var a={done:!1};try{Sr(r,e,br(Ao,a,i),br(gr,a,i))}catch(s){gr(a,s,i)}}):(i.value=e,i.state=Xh,rf(i,!1))}catch(a){gr({done:!1},a,i)}}};if(zh&&(Ot=function(e){ix(this,Ka),tx(e),Sr(Ja,this);var t=Eo(this);try{e(br(Ao,t),br(gr,t))}catch(r){gr(t,r)}},Ka=Ot.prototype,Ja=function(e){lx(this,{type:ts,done:!1,notified:!1,parent:!1,reactions:new ox,rejection:!1,state:Uh,value:void 0})},Ja.prototype=Fh(Ka,"then",function(e,t){var r=Eo(this),a=Po(ax(this,Ot));return r.parent=!0,a.ok=Xa(e)?e:!0,a.fail=Xa(t)&&t,a.domain=Za?Ro.domain:void 0,r.state===Uh?r.reactions.add(a):ko(function(){tf(a,r)}),a.promise}),Hh=function(){var i=new Ja,e=Eo(i);this.promise=i,this.resolve=br(Ao,e),this.reject=br(gr,e)},Qh.f=Po=function(i){return i===Ot||i===mx?new Hh(i):dx(i)},!XE&&Xa(es)&&mr!==Object.prototype)){jh=mr.then,cx||Fh(mr,"then",function(e,t){var r=this;return new Ot(function(a,s){Sr(jh,r,a,s)}).then(e,t)},{unsafe:!0});try{delete mr.constructor}catch{}qh&&qh(mr,Ka)}JE({global:!0,constructor:!0,wrap:!0,forced:zh},{Promise:Ot});ZE(Ot,ts,!1,!0);ex(ts)});var lf=f((nM,cf)=>{"use strict";var Sx=ee(),of=Sx("iterator"),uf=!1;try{nf=0,Lo={next:function(){return{done:!!nf++}},return:function(){uf=!0}},Lo[of]=function(){return this},Array.from(Lo,function(){throw 2})}catch{}var nf,Lo;cf.exports=function(i,e){try{if(!e&&!uf)return!1}catch{return!1}var t=!1;try{var r={};r[of]=function(){return{next:function(){return{done:t=!0}}}},i(r)}catch{}return t}});var Mo=f((oM,df)=>{"use strict";var vx=Vt(),yx=lf(),Tx=hr().CONSTRUCTOR;df.exports=Tx||!yx(function(i){vx.all(i).then(void 0,function(){})})});var pf=f(()=>{"use strict";var Ix=xe(),Ex=ge(),xx=et(),Px=fr(),Ax=za(),kx=Ha(),wx=Mo();Ix({target:"Promise",stat:!0,forced:wx},{all:function(e){var t=this,r=Px.f(t),a=r.resolve,s=r.reject,n=Ax(function(){var o=xx(t.resolve),c=[],u=0,d=1;kx(e,function(l){var p=u++,h=!1;d++,Ex(o,t,l).then(function(m){h||(h=!0,c[p]=m,--d||a(c))},s)}),--d||a(c)});return n.error&&s(n.value),r.promise}})});var ff=f(()=>{"use strict";var Rx=xe(),$x=Oe(),Lx=hr().CONSTRUCTOR,Do=Vt(),Mx=Ze(),Cx=U(),Dx=lr(),hf=Do&&Do.prototype;Rx({target:"Promise",proto:!0,forced:Lx,real:!0},{catch:function(i){return this.then(void 0,i)}});!$x&&Cx(Do)&&(Co=Mx("Promise").prototype.catch,hf.catch!==Co&&Dx(hf,"catch",Co,{unsafe:!0}));var Co});var mf=f(()=>{"use strict";var Bx=xe(),Vx=ge(),Ox=et(),_x=fr(),Nx=za(),Fx=Ha(),qx=Mo();Bx({target:"Promise",stat:!0,forced:qx},{race:function(e){var t=this,r=_x.f(t),a=r.reject,s=Nx(function(){var n=Ox(t.resolve);Fx(e,function(o){Vx(n,t,o).then(r.resolve,a)})});return s.error&&a(s.value),r.promise}})});var bf=f(()=>{"use strict";var Ux=xe(),Hx=fr(),jx=hr().CONSTRUCTOR;Ux({target:"Promise",stat:!0,forced:jx},{reject:function(e){var t=Hx.f(this),r=t.reject;return r(e),t.promise}})});var Bo=f((bM,gf)=>{"use strict";var Gx=Ye(),Wx=Ie(),Yx=fr();gf.exports=function(i,e){if(Gx(i),Wx(e)&&e.constructor===i)return e;var t=Yx.f(i),r=t.resolve;return r(e),t.promise}});var yf=f(()=>{"use strict";var Qx=xe(),zx=Ze(),Sf=Oe(),Kx=Vt(),vf=hr().CONSTRUCTOR,Jx=Bo(),Xx=zx("Promise"),Zx=Sf&&!vf;Qx({target:"Promise",stat:!0,forced:Sf||vf},{resolve:function(e){return Jx(Zx&&this===Xx?Kx:this,e)}})});var Tf=f(()=>{"use strict";sf();pf();ff();mf();bf();yf()});var Pf=f(()=>{"use strict";var eP=xe(),tP=Oe(),rs=Vt(),rP=be(),Ef=Ze(),xf=U(),iP=io(),If=Bo(),aP=lr(),Oo=rs&&rs.prototype,sP=!!rs&&rP(function(){Oo.finally.call({then:function(){}},function(){})});eP({target:"Promise",proto:!0,real:!0,forced:sP},{finally:function(i){var e=iP(this,Ef("Promise")),t=xf(i);return this.then(t?function(r){return If(e,i()).then(function(){return r})}:i,t?function(r){return If(e,i()).then(function(){throw r})}:i)}});!tP&&xf(rs)&&(Vo=Ef("Promise").prototype.finally,Oo.finally!==Vo&&aP(Oo,"finally",Vo,{unsafe:!0}));var Vo});var is=f((EM,Af)=>{"use strict";var nP=Ze();Af.exports=nP});var wf=f((xM,kf)=>{"use strict";Cp();Tf();Pf();var oP=is();kf.exports=oP("Promise","finally")});var $f=f((PM,Rf)=>{"use strict";var uP=wf();Rf.exports=uP});var as=f((AM,Lf)=>{"use strict";var cP=$f();Lf.exports=cP});var rm=f(()=>{"use strict";var _P=xe(),NP=Wr(),FP=Da(),qP=Ca(),UP=en();_P({target:"Array",proto:!0},{at:function(e){var t=NP(this),r=FP(t),a=qP(e),s=a>=0?a:r+a;return s<0||s>=r?void 0:t[s]}});UP("at")});var am=f((BC,im)=>{"use strict";rm();var HP=is();im.exports=HP("Array","at")});var nm=f((VC,sm)=>{"use strict";var jP=am();sm.exports=jP});var pi=f((OC,om)=>{"use strict";var GP=nm();om.exports=GP});var rb=f(()=>{"use strict"});var ib=f(()=>{"use strict"});var sb=f((OV,ab)=>{"use strict";var JA=Ie(),XA=rr(),ZA=ee(),ek=ZA("match");ab.exports=function(i){var e;return JA(i)&&((e=i[ek])!==void 0?!!e:XA(i)==="RegExp")}});var ob=f((_V,nb)=>{"use strict";var tk=Xr(),rk=String;nb.exports=function(i){if(tk(i)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return rk(i)}});var cb=f((NV,ub)=>{"use strict";var ik=Ye();ub.exports=function(){var i=ik(this),e="";return i.hasIndices&&(e+="d"),i.global&&(e+="g"),i.ignoreCase&&(e+="i"),i.multiline&&(e+="m"),i.dotAll&&(e+="s"),i.unicode&&(e+="u"),i.unicodeSets&&(e+="v"),i.sticky&&(e+="y"),e}});var pb=f((FV,db)=>{"use strict";var ak=ge(),sk=_e(),nk=Ur(),ok=cb(),lb=RegExp.prototype;db.exports=function(i){var e=i.flags;return e===void 0&&!("flags"in lb)&&!sk(i,"flags")&&nk(lb,i)?ak(ok,i):e}});var fb=f((qV,hb)=>{"use strict";var hu=ne(),uk=Wr(),ck=Math.floor,du=hu("".charAt),lk=hu("".replace),pu=hu("".slice),dk=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,pk=/\$([$&'`]|\d{1,2})/g;hb.exports=function(i,e,t,r,a,s){var n=t+i.length,o=r.length,c=pk;return a!==void 0&&(a=uk(a),c=dk),lk(s,c,function(u,d){var l;switch(du(d,0)){case"$":return"$";case"&":return i;case"`":return pu(e,0,t);case"'":return pu(e,n);case"<":l=a[pu(d,1,-1)];break;default:var p=+d;if(p===0)return u;if(p>o){var h=ck(p/10);return h===0?u:h<=o?r[h-1]===void 0?du(d,1):r[h-1]+du(d,1):u}l=r[p-1]}return l===void 0?"":l})}});var gb=f(()=>{"use strict";var hk=xe(),fk=ge(),mu=ne(),mb=Fr(),mk=U(),bk=ir(),gk=sb(),Rr=ob(),Sk=jr(),vk=pb(),yk=fb(),Tk=ee(),Ik=Oe(),Ek=Tk("replace"),xk=TypeError,fu=mu("".indexOf),Pk=mu("".replace),bb=mu("".slice),Ak=Math.max;hk({target:"String",proto:!0},{replaceAll:function(e,t){var r=mb(this),a,s,n,o,c,u,d,l,p,h,m=0,b="";if(!bk(e)){if(a=gk(e),a&&(s=Rr(mb(vk(e))),!~fu(s,"g")))throw new xk("`.replaceAll` does not allow non-global regexes");if(n=Sk(e,Ek),n)return fk(n,e,r,t);if(Ik&&a)return Pk(Rr(r),e,t)}for(o=Rr(r),c=Rr(e),u=mk(t),u||(t=Rr(t)),d=c.length,l=Ak(1,d),p=fu(o,c);p!==-1;)h=u?Rr(t(c,p,o)):yk(c,o,p,[],void 0,t),b+=bb(o,m,p)+h,m=p+d,p=p+l>o.length?-1:fu(o,c,p+l);return m<o.length&&(b+=bb(o,m)),b}})});var vb=f((jV,Sb)=>{"use strict";rb();ib();gb();var kk=is();Sb.exports=kk("String","replaceAll")});var Tb=f((GV,yb)=>{"use strict";var wk=vb();yb.exports=wk});var Eb=f((WV,Ib)=>{"use strict";var Rk=Tb();Ib.exports=Rk});var Ku="2.0.111-dev.ae3e5b42.0";var se=(a=>(a.STOPPED="stopped",a.READY="ready",a.PLAYING="playing",a.PAUSED="paused",a))(se||{}),ft=(y=>(y.MPEG="MPEG",y.DASH="DASH",y.DASH_SEP="DASH_SEP",y.DASH_SEP_VK="DASH_SEP",y.DASH_WEBM="DASH_WEBM",y.DASH_WEBM_AV1="DASH_WEBM_AV1",y.DASH_STREAMS="DASH_STREAMS",y.DASH_WEBM_VK="DASH_WEBM",y.DASH_ONDEMAND="DASH_ONDEMAND",y.DASH_ONDEMAND_VK="DASH_ONDEMAND",y.DASH_LIVE="DASH_LIVE",y.DASH_LIVE_CMAF="DASH_LIVE_CMAF",y.DASH_LIVE_WEBM="DASH_LIVE_WEBM",y.HLS="HLS",y.HLS_ONDEMAND="HLS_ONDEMAND",y.HLS_JS="HLS",y.HLS_LIVE="HLS_LIVE",y.HLS_LIVE_CMAF="HLS_LIVE_CMAF",y.WEB_RTC_LIVE="WEB_RTC_LIVE",y))(ft||{});var Ta=(a=>(a.NOT_AVAILABLE="NOT_AVAILABLE",a.AVAILABLE="AVAILABLE",a.CONNECTING="CONNECTING",a.CONNECTED="CONNECTED",a))(Ta||{}),Qs=(r=>(r.HTTP1="http1",r.HTTP2="http2",r.QUIC="quic",r))(Qs||{});var zs=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(zs||{});import{assertNever as rc,assertNonNullable as zg,isNonNullable as Ia,ValueSubject as Ks,Subject as Kg,Subscription as Jg,merge as Xg,observableFrom as Zg,fromEvent as Xu,map as Zu,tap as ec,filterChanged as eS,isNullable as Js,ErrorCategory as tc}from"@vkontakte/videoplayer-shared";var Ju=i=>new Promise((e,t)=>{let r=document.createElement("script");r.setAttribute("src",i),r.onload=()=>e,r.onerror=()=>t,document.body.appendChild(r)});var Ea=class{constructor(e){this.connection$=new Ks(void 0);this.castState$=new Ks("NOT_AVAILABLE");this.errorEvent$=new Kg;this.realCastState$=new Ks("NOT_AVAILABLE");this.subscription=new Jg;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=Ia(window.chrome?.cast),a=!!window.__onGCastApiAvailable;r?this.initializeCastApi():(window.__onGCastApiAvailable=s=>{delete window.__onGCastApiAvailable,s&&this.initializeCastApi()},a||Ju("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:tc.NETWORK,message:"Script loading failed!"})))}connect(){cast.framework.CastContext.getInstance()?.requestSession()}disconnect(){cast.framework.CastContext.getInstance()?.getCurrentSession()?.endSession(!0)}stopMedia(){return new Promise((e,t)=>{cast.framework.CastContext.getInstance()?.getCurrentSession()?.getMediaSession()?.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){Ia(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();Js(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();Js(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(Xu(r,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(a=>{switch(a.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=r.getCurrentSession()?.getMediaSession()?.media?.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return rc(a.sessionState)}})).add(Xg(Xu(r,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(ec(a=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(a)}`})}),Zu(a=>a.castState)),Zg([r.getCastState()])).pipe(eS(),Zu(tS),ec(a=>{this.log({message:`realCastState$: ${a}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(a=>{let s=a==="CONNECTED",n=Ia(this.connection$.getValue());if(s&&!n){let o=r.getCurrentSession();zg(o);let c=o.getCastDevice(),u=o.getMediaSession()?.media?.contentId;(Js(u)||u===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:o,castDevice:c}))}else!s&&n&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(a==="CONNECTED"?Ia(this.connection$.getValue())?"CONNECTED":"AVAILABLE":a)}))}initializeCastApi(){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{return}try{e.setOptions({receiverApplicationId:this.params.receiverApplicationId??t,autoJoinPolicy:r}),this.initListeners()}catch(a){this.errorEvent$.next({id:"ChromecastInitializer",category:tc.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:a})}}},tS=i=>{switch(i){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 rc(i)}};var yg=We(Xn(),1);var qf=We(as(),1);import{assertNever as Mf}from"@vkontakte/videoplayer-shared";var J=(i,e=0,t=0)=>{switch(t){case 0:return i.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case 1:{if(e===0)return i;let r=new URL(i);return r.searchParams.append("playback_shift",e.toFixed(0)),r.toString()}case 2:{let r=new URL(i);return!r.searchParams.get("offset_p")&&e===0?i:(r.searchParams.set("offset_p",e.toFixed(0)),r.toString())}default:Mf(t)}return i},_o=(i,e)=>{switch(e){case 0:return NaN;case 1:{let t=new URL(i);return Number(t.searchParams.get("playback_shift"))}case 2:{let t=new URL(i);return Number(t.searchParams.get("offset_p")??0)}default:Mf(e)}};var I=(i,e,t=!1)=>{let r=i.getTransition();(t||!r||r.to===e)&&i.setState(e)};import{isNonNullable as lP,Subject as ss,merge as Cf}from"@vkontakte/videoplayer-shared";var L=class{constructor(e){this.transitionStarted$=new ss;this.transitionEnded$=new ss;this.transitionUpdated$=new ss;this.forceChanged$=new ss;this.stateChangeStarted$=Cf(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=Cf(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||lP(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 dP}from"@vkontakte/videoplayer-shared";var Df=i=>{switch(i){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 dP(i)}};import{assertNever as vr,assertNonNullable as _t,debounce as Bf,ErrorCategory as Vf,fromEvent as Nt,isNonNullable as Of,map as _f,merge as Nf,observableFrom as pP,Subject as hP,Subscription as No,timeout as fP,getHighestQuality as mP}from"@vkontakte/videoplayer-shared";var bP=5,gP=5,SP=500,Ff=7e3,ci=class{constructor(e){this.subscription=new No;this.loadMediaTimeoutSubscription=new No;this.videoState=new L("stopped");this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),r=this.params.desiredState.playbackState.getState(),a=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(a?.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(Df(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 No;this.subscription.add(e),this.subscription.add(Nf(this.videoState.stateChangeStarted$.pipe(_f(a=>`stateChangeStarted$ ${JSON.stringify(a)}`)),this.videoState.stateChangeEnded$.pipe(_f(a=>`stateChangeEnded$ ${JSON.stringify(a)}`))).subscribe(a=>this.log({message:`[videoState] ${a}`})));let t=(a,s)=>this.subscription.add(a.subscribe(s));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{let a=new hP;e.add(a.pipe(Bf(SP)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add(Nt(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)>bP)&&a.next(o),s=o})),e.add(Nt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(Nt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),a=>{this.logRemoteEvent(a),a.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(Nt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),a=>{this.logRemoteEvent(a),a.value?this.handleRemotePause():this.handleRemotePlay()}),t(Nt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),a=>{this.logRemoteEvent(a);let{remotePlayer:s}=this.params.connection,n=a.value,o=this.params.output.isBuffering$.getValue(),c=n===chrome.cast.media.PlayerState.BUFFERING;switch(o!==c&&this.params.output.isBuffering$.next(c),n){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&s.duration-s.currentTime<gP&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),I(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(Nt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),a=>{this.logRemoteEvent(a),this.handleRemoteVolumeChange({volume:a.value})}),t(Nt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),a=>{this.logRemoteEvent(a),this.handleRemoteVolumeChange({muted:a.value})});let r=Nf(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,pP(["init"])).pipe(Bf(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"),I(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),I(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();(this.videoState.getTransition()?.to==="paused"||e==="playing")&&(this.videoState.setState("paused"),I(this.params.desiredState.playbackState,"paused"))}handleRemotePlay(){let e=this.videoState.getState();(this.videoState.getTransition()?.to==="playing"||e==="paused")&&(this.videoState.setState("playing"),I(this.params.desiredState.playbackState,"playing"))}handleRemoteReady(){this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.params.desiredState.playbackState.getTransition()?.to==="ready"&&I(this.params.desiredState.playbackState,"ready")}handleRemoteStop(){this.videoState.getState()!=="stopped"&&this.videoState.setState("stopped")}handleRemoteVolumeChange(e){let t=this.params.output.volume$.getValue(),r={volume:e.volume??t.volume,muted:e.muted??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){let t=this.params.source,r,a,s;switch(e){case"MPEG":{let u=t[e];_t(u);let d=mP(Object.keys(u));_t(d);let l=u[d];_t(l),r=l,a="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let u=t[e];_t(u),r=u.url,a="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 u=t[e];_t(u),r=u.url,a="application/dash+xml",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let u=t[e];_t(u),r=u.url,a="application/dash+xml",s=chrome.cast.media.StreamType.LIVE;break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let u=t[e];_t(u),r=J(u.url),a="application/x-mpegurl",s=chrome.cast.media.StreamType.LIVE;break}case"DASH_LIVE":case"WEB_RTC_LIVE":{let u="Unsupported format for Chromecast",d=new Error(u);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:Vf.VIDEO_PIPELINE,message:u,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(this.params.meta.videoId??r,a);n.contentUrl=r,n.streamType=s,n.metadata=new chrome.cast.media.GenericMediaMetadata;let{title:o,subtitle:c}=this.params.meta;return Of(o)&&(n.metadata.title=o),Of(c)&&(n.metadata.subtitle=c),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((a,s)=>{this.loadMediaTimeoutSubscription.add(fP(Ff).subscribe(()=>s(`timeout(${Ff})`)))});(0,qf.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()},a=>{let s=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${a}`;this.log({message:s}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:Vf.VIDEO_PIPELINE,message:s,thrown:a})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};import{clearVideoElement as Hf}from"@vkontakte/videoplayer-shared";import{clearVideoElement as vP}from"@vkontakte/videoplayer-shared";var Uf=i=>{try{i.pause(),i.playbackRate=0,vP(i),i.remove()}catch(e){console.error(e)}};import{fromEvent as yP,Subscription as TP}from"@vkontakte/videoplayer-shared";var Fo=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)}},qo=window.WeakMap?new WeakMap:new Fo,Uo=window.WeakMap?new WeakMap:new Map,IP=(i,e=20)=>{let t=0;return yP(i,"ratechange").subscribe(r=>{t++,t>=e&&(i.currentTime=i.currentTime,t=0)})},oe=(i,{audioVideoSyncRate:e})=>{let t=i.querySelector("video"),r=!!t;t?Hf(t):(t=document.createElement("video"),i.appendChild(t)),qo.set(t,r);let a=new TP;return a.add(IP(t,e)),Uo.set(t,a),t.setAttribute("crossorigin","anonymous"),t.setAttribute("playsinline","playsinline"),t.controls=!1,t.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),t},ue=i=>{Uo.get(i)?.unsubscribe(),Uo.delete(i);let t=qo.get(i);qo.delete(i),t?Hf(i):Uf(i)};import{assertNonNullable as li,isNonNullable as ze,isNullable as PP,fromEvent as yr,merge as jf,observableFrom as Gf,filterChanged as Wf,map as di,Subject as Yf,Subscription as AP,ValueSubject as kP,ErrorCategory as wP}from"@vkontakte/videoplayer-shared";import{isNonNullable as Ho,isNullable as EP,Subscription as xP}from"@vkontakte/videoplayer-shared";var ns=(i,e,t,{equal:r=(n,o)=>n===o,changed$:a,onError:s}={})=>{let n=i.getState(),o=e(),c=EP(a),u=new xP;return a&&u.add(a.subscribe(d=>{let l=i.getState();r(d,l)&&i.setState(d)},s)),r(o,n)||(t(n),c&&i.setState(n)),u.add(i.stateChangeStarted$.subscribe(d=>{t(d.to),c&&i.setState(d.to)},s)),u},Qe=(i,e,t)=>ns(e,()=>i.loop,r=>{Ho(r)&&(i.loop=r)},{onError:t}),ce=(i,e,t,r)=>ns(e,()=>({muted:i.muted,volume:i.volume}),a=>{Ho(a)&&(i.muted=a.muted,i.volume=a.volume)},{equal:(a,s)=>a===s||a?.muted===s?.muted&&a?.volume===s?.volume,changed$:t,onError:r}),Pe=(i,e,t,r)=>ns(e,()=>i.playbackRate,a=>{Ho(a)&&(i.playbackRate=a)},{changed$:t,onError:r}),bt=ns;var RP=i=>["__",i.language,i.label].join("|"),$P=(i,e)=>{if(i.id===e)return!0;let[t,r,a]=e.split("|");return i.language===r&&i.label===a},jo=class i{constructor(){this.available$=new Yf;this.current$=new kP(void 0);this.error$=new Yf;this.subscription=new AP;this.externalTracks=new Map;this.internalTracks=new Map}connect(e,t,r){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();let a=s=>{this.error$.next({id:"TextTracksManager",category:wP.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(bt(t.internalTextTracks,()=>Object.values(this.internalTracks),s=>{ze(s)&&this.setInternal(s)},{equal:(s,n)=>ze(s)&&ze(n)&&s.length===n.length&&s.every(({id:o},c)=>o===n[c].id),changed$:this.available$.pipe(di(s=>s.filter(({type:n})=>n==="internal"))),onError:a})),this.subscription.add(bt(t.externalTextTracks,()=>Object.values(this.externalTracks),s=>{ze(s)&&this.setExternal(s)},{equal:(s,n)=>ze(s)&&ze(n)&&s.length===n.length&&s.every(({id:o},c)=>o===n[c].id),changed$:this.available$.pipe(di(s=>s.filter(({type:n})=>n==="external"))),onError:a})),this.subscription.add(bt(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:a})),this.subscription.add(bt(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.activeCues)}))}subscribe(){li(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(jf(yr(e,"addtrack"),yr(e,"removetrack"),Gf(["init"])).pipe(di(()=>this.htmlTextTracksAsArray().map(r=>this.htmlTextTrackToITextTrack(r))),Wf((r,a)=>r.length===a.length&&r.every(({id:s},n)=>s===a[n].id))).subscribe(this.available$)),this.subscription.add(jf(yr(e,"change"),Gf(["init"])).pipe(di(()=>this.htmlTextTracksAsArray().find(({mode:r})=>r==="showing")),di(r=>r&&this.htmlTextTrackToITextTrack(r).id),Wf()).subscribe(this.current$));let t=r=>this.applyCueSettings(r.target?.activeCues??null);this.subscription.add(yr(e,"addtrack").subscribe(r=>{r.track?.addEventListener("cuechange",t);let a=s=>{let n=s.target?.cues??null;n&&n.length&&(this.applyCueSettings(s.target?.cues??null),s.target?.removeEventListener("cuechange",a))};r.track?.addEventListener("cuechange",a)})),this.subscription.add(yr(e,"removetrack").subscribe(r=>{r.track?.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;let t=this.cueSettings.getState();for(let r of Array.from(e)){let a=r;ze(t.align)&&(a.align=t.align),ze(t.position)&&(a.position=t.position),ze(t.size)&&(a.size=t.size),ze(t.line)&&(a.line=t.line)}}htmlTextTracksAsArray(e=!1){li(this.video);let t=[...this.video.textTracks];return e?t:t.filter(i.isHealthyTrack)}htmlTextTrackToITextTrack(e){let{language:t,label:r}=e,a=e.id?e.id:RP(e),s=this.externalTracks.has(a),n=a.includes("auto");return s?{id:a,type:"external",isAuto:n,language:t,label:r,url:this.externalTracks.get(a)?.url}:{id:a,type:"internal",isAuto:n,language:t,label:r,url:this.internalTracks.get(a)?.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:a,isAuto:s})=>!this.internalTracks.has(r)&&!t.some(([,n])=>n.language===a&&n.isAuto===s)).forEach(r=>this.attach(r)),Array.from(this.internalTracks).filter(([r])=>!e.find(a=>a.id===r)).forEach(([,r])=>this.detach(r))}select(e){li(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(PP(e)||!$P(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){li(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){li(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)}},Ke=jo;var it=class{constructor(){this.pausedTime=0;this.streamOffset=0;this.pauseTimestamp=0}getTotalPausedTime(){return this.pausedTime+this.getCurrentPausedTime()}getCurrentPausedTime(){return this.pauseTimestamp>0?Date.now()-this.pauseTimestamp:0}getStreamOffset(){return this.streamOffset}getTotalOffset(){return this.getTotalPausedTime()+this.streamOffset}pause(){this.pauseTimestamp===0&&(this.pauseTimestamp=Date.now())}resume(){this.pauseTimestamp>0&&(this.pausedTime+=this.getCurrentPausedTime(),this.pauseTimestamp=0)}resetTo(e,t=!1){this.streamOffset=e,this.pauseTimestamp=0,this.pausedTime=0,t&&this.pause()}};var Qf=i=>{let e=i;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e?.parentNode;return e??void 0},Go=i=>{let e=Qf(i);return!!(e&&e.fullscreenElement&&e.fullscreenElement===i)},zf=i=>{let e=Qf(i);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===i)};import{fromEvent as Ae,map as gt,merge as Jf,filterChanged as MP,isNonNullable as Xf,Subject as CP,filter as Zf,mapTo as em,combine as DP,once as BP,ErrorCategory as VP,ValueSubject as tm,clientChecker as OP}from"@vkontakte/videoplayer-shared";var LP=3,Kf=(i,e,t=LP)=>{let r=0,a=0;for(let s=0;s<i.length;s++){let n=i.start(s),o=i.end(s);if(n<=e&&e<=o){if(r=n,a=o,!t)return{from:r,to:a};for(let c=s-1;c>=0;c--)i.end(c)+t>=r&&(r=i.start(c));for(let c=s+1;c<i.length;c++)i.start(c)-t<=a&&(a=i.end(c))}}return{from:r,to:a}};var le=i=>{let e=y=>Ae(i,y).pipe(em(void 0)),r=Jf(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(y=>Ae(i,y))).pipe(gt(y=>y.type==="ended"?i.readyState<2:i.readyState<3),MP()),a=Jf(Ae(i,"progress"),Ae(i,"timeupdate")).pipe(gt(()=>Kf(i.buffered,i.currentTime))),s=OP.isSafari?DP({play:e("play").pipe(BP()),playing:e("playing")}).pipe(em(void 0)):e("playing"),n=Ae(i,"volumechange").pipe(gt(()=>({muted:i.muted,volume:i.volume}))),o=Ae(i,"ratechange").pipe(gt(()=>i.playbackRate)),c=Ae(i,"error").pipe(Zf(()=>!!(i.error||i.played.length)),gt(()=>{let y=i.error;return{id:y?`MediaError#${y.code}`:"HtmlVideoError",category:VP.VIDEO_PIPELINE,message:y?y.message:"Error event from HTML video element",thrown:i.error??void 0}})),u=Ae(i,"timeupdate").pipe(gt(()=>i.currentTime)),d=new CP,l=.3,p;u.subscribe(y=>{i.loop&&Xf(p)&&Xf(y)&&p>=i.duration-l&&y<=l&&d.next(p),p=y});let h=e("pause").pipe(Zf(()=>!i.error&&p!==i.duration)),m=Ae(i,"enterpictureinpicture"),b=Ae(i,"leavepictureinpicture"),g=new tm(zf(i));m.subscribe(()=>g.next(!0)),b.subscribe(()=>g.next(!1));let v=new tm(Go(i));return Ae(i,"fullscreenchange").pipe(gt(()=>Go(i))).subscribe(v),{playing$:s,pause$:h,canplay$:e("canplay"),ended$:e("ended"),looped$:d,error$:c,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:u,durationChange$:Ae(i,"durationchange").pipe(gt(()=>i.duration)),isBuffering$:r,currentBuffer$:a,volumeState$:n,playbackRateState$:o,inPiP$:g,inFullscreen$:v}};import{VideoQuality as St}from"@vkontakte/videoplayer-shared";var vt=i=>{switch(i){case"mobile":return St.Q_144P;case"lowest":return St.Q_240P;case"low":return St.Q_360P;case"sd":case"medium":return St.Q_480P;case"hd":case"high":return St.Q_720P;case"fullhd":case"full":return St.Q_1080P;case"quadhd":case"quad":return St.Q_1440P;case"ultrahd":case"ultra":return St.Q_2160P}};var Ft=We(pi(),1);import{isNonNullable as de,isNullable as Yo,now as mm,isHigher as Qo,isHigherOrEqual as dm,isInvariantQuality as pm,isLower as zo,isLowerOrEqual as hm,videoSizeToQuality as WP,assertNotEmptyArray as bm,assertNonNullable as YP}from"@vkontakte/videoplayer-shared";var Wo=!1,at={},um=i=>{Wo=i},cm=()=>{at={}},lm=i=>{i(at)},hi=(i,e)=>{Wo&&(at.meta=at.meta??{},at.meta[i]=e)},te=class{constructor(e){this.name=e}next(e){if(!Wo)return;at.series=at.series??{};let t=at.series[this.name]??[];t.push([Date.now(),e]),at.series[this.name]=t}};var QP=new te("best_bitrate"),gm=(i,e,t)=>(e-t)*Math.pow(2,-10*i)+t;var Ko=i=>(e,t)=>i*(Number(e.bitrate)-Number(t.bitrate)),fi=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=mm()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},Sm='Assertion "ABR Tracks is empty array" failed',os=(i,e,t,r)=>{let a=[...e].sort(Ko(1)),s=[...t].sort(Ko(1)),n=s.filter(c=>de(c.bitrate)&&de(i.bitrate)?i.bitrate/c.bitrate>r:!0),o=(0,Ft.default)(s,Math.round(s.length*a.indexOf(i)/(a.length+1)))??(0,Ft.default)(s,-1);return o&&n.includes(o)?o:n.length?(0,Ft.default)(n,-1):(0,Ft.default)(s,0)},fm=i=>"quality"in i,vm=(i,e,t,r)=>{let a=t&&r&&r.history[t.id]&&mm()-r.history[t.id]<=i.trackCooldown&&(!r.last||t.id!==r.last.id);if(t?.id&&r&&!a&&r.recordSelection(t),a&&r?.last){let s=r.last;r?.recordSwitch(s);let n=fm(s)?"video":"audio",o=fm(s)?s.quality:s.bitrate;return e({message:`
7
7
  [last ${n} selected] ${o}
8
- `}),s}return r?.recordSwitch(t),t},lt=(i,{container:e,throughput:t,tuning:r,limits:a,reserve:s=0,forwardBufferHealth:n,playbackRate:o,current:c,history:u,visible:d,droppedVideoMaxQualityLimit:l,abrLogger:p})=>{lm(i,pm);let h=r.usePixelRatio?window.devicePixelRatio??1:1,m=r.limitByContainer&&e&&e.width>0&&e.height>0&&{width:e.width*h*r.containerSizeFactor,height:e.height*h*r.containerSizeFactor},b=m&&GP(m),g=r.considerPlaybackRate&&ce(o)?o:1,v=i.filter(k=>!nm(k.quality)).sort((k,w)=>Ho(k.quality,w.quality)?-1:1),A=(0,$t.default)(v,-1)?.quality,y=(0,$t.default)(v,0)?.quality,S=Uo(a)||ce(a.min)&&ce(a.max)&&jo(a.max,a.min)||ce(a.min)&&y&&Ho(a.min,y)||ce(a.max)&&A&&jo(a.max,A),T=g*dm(n??.5,r.bitrateFactorAtEmptyBuffer,r.bitrateFactorAtFullBuffer),E={},O=v.filter(k=>{if(!(b?jo(k.quality,b):!0))return E[k.quality]="FitsContainer",!1;if(!(ce(t)&&isFinite(t)&&ce(k.bitrate)?t-s>=k.bitrate*T:!0))return E[k.quality]="FitsThroughput",!1;if(r.lazyQualitySwitch&&ce(r.minBufferToSwitchUp)&&c&&!nm(c.quality)&&(n??0)<r.minBufferToSwitchUp&&Ho(k.quality,c.quality))return E[k.quality]="Buffer",!1;if(!!l&&sm(k.quality,l))return E[k.quality]="DroppedFramesLimit",!1;let te=S||(Uo(a.max)||om(k.quality,a.max))&&(Uo(a.min)||sm(k.quality,a.min)),x=ce(d)&&!d?om(k.quality,r.backgroundVideoQualityLimit):!0;return!te||!x?(E[k.quality]="FitsQualityLimits",!1):!0})[0];O&&O.bitrate&&YP.next(O.bitrate);let N=O??v[Math.ceil((v.length-1)/2)]??i[0];return N.quality!==u?.last?.quality&&p({message:`
8
+ `}),s}return r?.recordSwitch(t),t},yt=(i,{container:e,throughput:t,tuning:r,limits:a,reserve:s=0,forwardBufferHealth:n,playbackRate:o,current:c,history:u,visible:d,droppedVideoMaxQualityLimit:l,abrLogger:p})=>{bm(i,Sm);let h=r.usePixelRatio?window.devicePixelRatio??1:1,m=r.limitByContainer&&e&&e.width>0&&e.height>0&&{width:e.width*h*r.containerSizeFactor,height:e.height*h*r.containerSizeFactor},b=m&&WP(m),g=r.considerPlaybackRate&&de(o)?o:1,v=i.filter(w=>!pm(w.quality)).sort((w,R)=>Qo(w.quality,R.quality)?-1:1),k=(0,Ft.default)(v,-1)?.quality,y=(0,Ft.default)(v,0)?.quality,S=Yo(a)||de(a.min)&&de(a.max)&&zo(a.max,a.min)||de(a.min)&&y&&Qo(a.min,y)||de(a.max)&&k&&zo(a.max,k),T=g*gm(n??.5,r.bitrateFactorAtEmptyBuffer,r.bitrateFactorAtFullBuffer),E={},O=v.filter(w=>{if(!(b?zo(w.quality,b):!0))return E[w.quality]="FitsContainer",!1;if(!(de(t)&&isFinite(t)&&de(w.bitrate)?t-s>=w.bitrate*T:!0))return E[w.quality]="FitsThroughput",!1;if(r.lazyQualitySwitch&&de(r.minBufferToSwitchUp)&&c&&!pm(c.quality)&&(n??0)<r.minBufferToSwitchUp&&Qo(w.quality,c.quality))return E[w.quality]="Buffer",!1;if(!!l&&dm(w.quality,l))return E[w.quality]="DroppedFramesLimit",!1;let ie=S||(Yo(a.max)||hm(w.quality,a.max))&&(Yo(a.min)||dm(w.quality,a.min)),x=de(d)&&!d?hm(w.quality,r.backgroundVideoQualityLimit):!0;return!ie||!x?(E[w.quality]="FitsQualityLimits",!1):!0})[0];O&&O.bitrate&&QP.next(O.bitrate);let N=O??v[Math.ceil((v.length-1)/2)]??i[0];return N.quality!==u?.last?.quality&&p({message:`
9
9
  [VIDEO TRACKS ABR]
10
10
  [available video tracks]
11
- ${i.map(k=>`{ id: ${k.id}, quality: ${k.quality}, bitrate: ${k.bitrate} }`).join(`
11
+ ${i.map(w=>`{ id: ${w.id}, quality: ${w.quality}, bitrate: ${w.bitrate} }`).join(`
12
12
  `)}
13
13
 
14
14
  [tuning]
15
- ${Object.entries(r??{}).map(([k,w])=>`${k}: ${w}`).join(`
15
+ ${Object.entries(r??{}).map(([w,R])=>`${w}: ${R}`).join(`
16
16
  `)}
17
17
 
18
18
  [limit params]
@@ -30,12 +30,12 @@ var Ug=Object.create;var Hu=Object.defineProperty;var Hg=Object.getOwnPropertyDe
30
30
  minQualityLimit: ${a?.min},
31
31
 
32
32
  [limited video tracks]
33
- ${Object.entries(E).map(([k,w])=>`${k}: ${w}`).join(`
33
+ ${Object.entries(E).map(([w,R])=>`${w}: ${R}`).join(`
34
34
  `)||"All tracks are available"}
35
35
 
36
36
  [best video track] ${O?.quality}
37
37
  [selected video track] ${N?.quality}
38
- `}),hm(r,p,N,u)},fm=(i,e,t,{throughput:r,tuning:a,playbackRate:s,forwardBufferHealth:n,history:o,abrLogger:c})=>{lm(t,pm);let u=a.considerPlaybackRate&&ce(s)?s:1,d=[...t].sort(Go(-1)),l=i.bitrate;WP(l);let p=u*dm(n??.5,a.bitrateAudioFactorAtEmptyBuffer,a.bitrateAudioFactorAtFullBuffer),h;return ce(r)&&isFinite(r)&&(h=d.find(m=>ce(m.bitrate)?r-l>=m.bitrate*p:!0)),h||(h=Ka(i,e,t,a.minVideoAudioRatio)),h?.bitrate!==o?.last?.bitrate&&c({message:`
38
+ `}),vm(r,p,N,u)},ym=(i,e,t,{throughput:r,tuning:a,playbackRate:s,forwardBufferHealth:n,history:o,abrLogger:c})=>{bm(t,Sm);let u=a.considerPlaybackRate&&de(s)?s:1,d=[...t].sort(Ko(-1)),l=i.bitrate;YP(l);let p=u*gm(n??.5,a.bitrateAudioFactorAtEmptyBuffer,a.bitrateAudioFactorAtFullBuffer),h;return de(r)&&isFinite(r)&&(h=d.find(m=>de(m.bitrate)?r-l>=m.bitrate*p:!0)),h||(h=os(i,e,t,a.minVideoAudioRatio)),h?.bitrate!==o?.last?.bitrate&&c({message:`
39
39
  [AUDIO TRACKS ABR]
40
40
  [available audio tracks]
41
41
  ${t.map(m=>`{ id: ${m.id}, bitrate: ${m.bitrate} }`).join(`
@@ -55,7 +55,7 @@ var Ug=Object.create;var Hu=Object.defineProperty;var Hg=Object.getOwnPropertyDe
55
55
  minBufferToSwitchUp: ${a.minBufferToSwitchUp},
56
56
 
57
57
  [selected audio track] ${h?.id}
58
- `}),h&&hm(a,c,h,o)};var Y=i=>new URL(i).hostname;import{assertNever as ym,assertNonNullable as Tm,combine as hA,debounce as fA,ErrorCategory as Im,filter as Em,filterChanged as mA,isNonNullable as Ko,map as ts,merge as xm,observableFrom as bA,once as gA,Subscription as SA,ValueSubject as Jo,videoQualityToHeight as vA,videoSizeToQuality as yA}from"@vkontakte/videoplayer-shared";var mm=i=>{if(i instanceof DOMException&&["Failed to load because no supported source was found.","The element has no supported sources."].includes(i.message))throw i;return!(i instanceof DOMException&&(i.code===20||i.name==="AbortError"))},le=async i=>{let e=i.muted;try{await i.play()}catch(t){if(!mm(t))return!1;if(e)return console.warn(t),!1;i.muted=!0;try{await i.play()}catch(r){return mm(r)&&(i.muted=!1,console.warn(r)),!1}}return!0};import{isNonNullable as Xa,isNullable as KP,assertNonNullable as ui}from"@vkontakte/videoplayer-shared";import{isNonNullable as bm,assertNonNullable as Ja,now as QP}from"@vkontakte/videoplayer-shared";function Q(){return QP()}function Wo(i){return Q()-i}function Yo(i){let e=i.split("/"),t=e.slice(0,e.length-1).join("/"),r=/^([a-z]+:)?\/\//i,a=n=>r.test(n);return{resolve:(n,o,c=!1)=>{a(n)||(n.startsWith("/")||(n="/"+n),n=t+n);let u=n.indexOf("?")>-1?"&":"?";return c&&(n+=u+"lowLat=1",u="&"),o&&(n+=u+"_rnd="+Math.floor(999999999*Math.random())),n}}}function gm(i,e,t){let r=(...a)=>{t.apply(null,a),i.removeEventListener(e,r)};i.addEventListener(e,r)}function pr(i,e,t,r){let a=window.XMLHttpRequest,s,n,o,c=!1,u=0,d,l,p=!1,h="arraybuffer",m=7e3,b=2e3,g=()=>{if(c)return;Ja(d);let $=Wo(d),q;if($<b){q=b-$,setTimeout(g,q);return}b*=2,b>m&&(b=m),n&&n.abort(),n=new a,E()},v=$=>(s=$,w),A=$=>(l=$,w),y=()=>(h="json",w),S=()=>{if(!c){if(--u>=0){g(),r&&r();return}c=!0,l&&l(),t&&t()}},T=$=>(p=$,w),E=()=>{d=Q(),n=new a,n.open("get",i);let $=0,q,we=0,te=()=>(Ja(d),Math.max(d,Math.max(q||0,we||0)));if(s&&n.addEventListener("progress",x=>{let R=Q();s.updateChunk&&x.loaded>$&&(s.updateChunk(te(),x.loaded-$),$=x.loaded,q=R)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>S())),n.addEventListener("load",()=>{if(c)return;Ja(n);let x=n.status;if(x>=200&&x<300){if(n.response.byteLength&&s){let R=n.response.byteLength-$;R&&s.updateChunk&&s.updateChunk(te(),R)}n.responseType==="json"&&!Object.values(n.response).length?S():(l&&l(),e(n.response))}else S()}),n.addEventListener("error",()=>{S()}),p){let x=()=>{Ja(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(we=Q(),n.removeEventListener("readystatechange",x))};n.addEventListener("readystatechange",x)}return n.responseType=h,n.send(),w},w={withBitrateReporting:v,withParallel:T,withJSONResponse:y,withRetryCount:$=>(u=$,w),withRetryInterval:($,q)=>(bm($)&&(b=$),bm(q)&&(m=q),w),withTimeout:$=>(o=$,w),withFinally:A,send:E,abort:()=>{n&&(n.abort(),n=void 0),c=!0,l&&l()}};return w}var ni=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,a=0;for(;this.intervals.length>0;){let s=this.intervals[0];if(s.end<=t)r+=s.end-s.start,a+=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 c=s.bytes*n/o;a+=c,s.start=t,s.bytes-=c}}}if(a>0&&r>0){let s=a*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(a)}/${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 oi=class{constructor(e,t,r,a,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=a,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=Q(),a=c=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=c,e._errorCB?e._errorCB(c):(this.limitCompleteCount(),this.completeRequests[t]=e)},s=c=>{e._complete=1,e._responseData=c,e._downloadTime=Q()-r,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(c,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},n=()=>{e._finallyCB&&e._finallyCB()},o=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=pr(t,s,()=>a("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=Q()}_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=Q();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,a){let s={};return s.send=()=>{let n=this.activeRequests[e]||this.completeRequests[e];if(n)n._cb=t,n._errorCB=r,n._retryCB=a,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=a,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 Za=1e4,Qo=3;var JP=6e4,XP=10,ZP=1,eA=500,ci=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 ni(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=Yo(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=Yo(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",()=>{!!e.error&&!this.destroyed&&(t(`Video element error: ${e.error?.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,a;r!==0&&(a=t.buffered.start(r-1),t.currentTime<a&&(e("Fixup stall"),t.currentTime=a))}_selectQuality(e){let{videoElement:t}=this.params,r,a,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)?(!a||s.bitrate>a.bitrate)&&(a=s):(!r||r.bitrate>s.bitrate)&&(r=s));return a||r}shouldPlay(){if(this.paused)return!1;let t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||Xa(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){let{logger:r,videoElement:a,playerCallback:s}=this.params;this.mediaSource=new window.MediaSource,r("setting video src"),a.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.videoPlayStarted=!1,a.addEventListener("canplay",()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});let n=()=>{gm(a,"progress",()=>{a.buffered.length?(a.currentTime=a.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 oi(Qo,Za,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){let{logger:t,videoElement:r,playerCallback:a}=this.params,s=!1,n=null,o=null,c=null,u=null,d=!1,l=()=>{let S=s&&(!d||d===this.rep);return S||t("Not running!"),S},p=(S,T,E)=>{c&&c.abort(),c=pr(this.urlResolver.resolve(S,!1),T,E,()=>this._retryCallback()).withTimeout(Za).withBitrateReporting(this.bitrateSwitcher).withRetryCount(Qo).withFinally(()=>{c=null}).send()},h=(S,T,E)=>{ui(this.filesFetcher),o?.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(S,!1),T,E,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},m=S=>{let T=r.playbackRate;r.playbackRate!==S&&(t(`Playback rate switch: ${T}=>${S}`),r.playbackRate=S)},b=S=>{this.lowLatency=S,t(`lowLatency changed to ${S}`),g()},g=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)m(1);else{let S=this._getBufferSizeSec();if(this.bufferStates.length<5){m(1);return}let E=Q()-1e4,D=0;for(let N=0;N<this.bufferStates.length;N++){let k=this.bufferStates[N];S=Math.min(S,k.buf),k.ts<E&&D++}this.bufferStates.splice(0,D),t(`update playback rate; minBuffer=${S} drop=${D} jitter=${this.sourceJitter}`);let O=S-ZP;this.sourceJitter>=0?O-=this.sourceJitter/2:this.sourceJitter-=1,O>3?m(1.15):O>1?m(1.1):O>.3?m(1.05):m(1)}},v=S=>{let T,E=()=>T&&T.start?T.start.length:0,D=x=>T.start[x]/1e3,O=x=>T.dur[x]/1e3,N=x=>T.fragIndex+x,k=(x,R)=>({chunkIdx:N(x),startTS:D(x),dur:O(x),discontinuity:R}),w=()=>{let x=0;if(T&&T.dur){let R=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,G=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,z=R;this.sourceJitter>1&&(z+=this.sourceJitter-1);let he=T.dur.length-1;for(;he>=0&&(z-=T.dur[he],!(z<=0));--he);x=Math.min(he,T.dur.length-1-G),x=Math.max(x,0)}return k(x,!0)},$=x=>{let R=E();if(!(R<=0)){if(Xa(x)){for(let G=0;G<R;G++)if(D(G)>x)return k(G)}return w()}},q=x=>{let R=E(),G=x?x.chunkIdx+1:0,z=G-T.fragIndex;if(!(R<=0)){if(!x||z<0||z-R>XP)return t(`Resync: offset=${z} bChunks=${R} chunk=`+JSON.stringify(x)),w();if(!(z>=R))return k(G-T.fragIndex,!1)}},we=(x,R,G)=>{u&&u.abort(),u=pr(this.urlResolver.resolve(x,!0,this.lowLatency),R,G,()=>this._retryCallback()).withTimeout(Za).withRetryCount(Qo).withFinally(()=>{u=null}).withJSONResponse().send()};return{seek:(x,R)=>{we(S,G=>{if(!l())return;T=G;let z=!!T.lowLatency;z!==this.lowLatency&&b(z);let he=0;for(let Oe=0;Oe<T.dur.length;++Oe)he+=T.dur[Oe];he>0&&(ui(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(he/T.dur.length)),a({name:"index",zeroTime:T.zeroTime,shiftDuration:T.shiftDuration}),this.sourceJitter=T.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,T.jitter/1e3)):1,x($(R))},()=>this._handleNetworkError())},nextChunk:q}},A=()=>{s=!1,o&&o.abort(),c&&c.abort(),u&&u.abort(),ui(this.filesFetcher),this.filesFetcher.abortAll()};return d={start:S=>{let{videoElement:T,logger:E}=this.params,D=v(e.jidxUrl),O,N,k,w,$=0,q,we,te,x=()=>{q&&(clearTimeout(q),q=void 0);let B=Math.max(eA,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),W=$+B,re=Q(),Re=Math.min(1e4,W-re);$=re;let tt=()=>{u||l()&&D.seek(()=>{l()&&($=Q(),R(),x())})};Re>0?q=window.setTimeout(()=>{this.paused?x():tt()},Re):tt()},R=()=>{let B;for(;B=D.nextChunk(w);)w=B,Ut(B);let W=D.nextChunk(k);if(W){if(k&&W.discontinuity){E("Detected discontinuity; restarting playback"),this.paused?x():(A(),this._initPlayerWith(e));return}Oe(W)}else x()},G=(B,W)=>{if(!l()||!this.sourceBuffer)return;let re,Re,tt,Ht=rt=>{window.setTimeout(()=>{l()&&G(B,W)},rt)};if(this.sourceBuffer.updating)E("Source buffer is updating; delaying appendBuffer"),Ht(100);else{let rt=Q(),jt=T.currentTime;!this.paused&&T.buffered.length>1&&we===jt&&rt-te>500&&(E("Stall suspected; trying to fix"),this._fixupStall()),we!==jt&&(we=jt,te=rt);let kr=this._getBufferSizeSec();if(kr>30)E(`Buffered ${kr} seconds; delaying appendBuffer`),Ht(2e3);else try{this.sourceBuffer.appendBuffer(B),this.videoPlayStarted?(this.bufferStates.push({ts:rt,buf:kr}),g(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),W&&W()}catch(sa){if(sa.name==="QuotaExceededError")E("QuotaExceededError; delaying appendBuffer"),tt=this.sourceBuffer.buffered.length,tt!==0&&(re=this.sourceBuffer.buffered.start(0),Re=jt,Re-re>4&&this.sourceBuffer.remove(re,Re-3)),Ht(1e3);else throw sa}}},z=()=>{N&&O&&(E([`Appending chunk, sz=${N.byteLength}:`,JSON.stringify(k)]),G(N,function(){N=null,R()}))},he=B=>e.fragUrlTemplate.replace("%%id%%",B.chunkIdx),Oe=B=>{l()&&h(he(B),(W,re)=>{if(l()){if(re/=1e3,N=W,k=B,n=B.startTS,re){let Re=Math.min(10,B.dur/re);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*Re:Re}z()}},()=>this._handleNetworkError())},Ut=B=>{l()&&(ui(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(he(B),!1)))},gt=B=>{l()&&(e.cachedHeader=B,G(B,()=>{O=!0,z()}))};s=!0,D.seek(B=>{if(l()){if($=Q(),!B){x();return}w=B,!KP(S)||B.startTS>S?Oe(B):(k=B,R())}},S),e.cachedHeader?gt(e.cachedHeader):p(e.headerUrl,gt,()=>this._handleNetworkError())},stop:A,getTimestampSec:()=>n},d}_switchToQuality(e){let{logger:t,playerCallback:r}=this.params,a;e.bitrate!==this.bitrate&&(this.rep&&(a=this.rep.getTimestampSec(),Xa(a)&&(a+=.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,ui(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(a),r({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return Xa(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,r=l=>{if(!this.autoQuality)return;let p,h,m;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&l<this.bitrate&&(h=this._getBufferSizeSec(),m=l/this.bitrate,h>10&&m>.8||h>15&&m>.5||h>20&&m>.3)){e(`Not switching: buffer=${Math.floor(h)}; bitrate=${this.bitrate}; newRate=${Math.floor(l)}`);return}p=this._selectQuality(l),p?this._switchToQuality(p):e(`Could not find quality by bitrate ${l}`)},s={updateChunk:(p,h)=>{let m=Q();if(this.chunkRateEstimator.addInterval(p,m,h)){let g=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:h,duration:m-p,speed:g}),!0}},get:()=>{let p=this.chunkRateEstimator.getBitRate();return p?p*.85:0}},n=-1/0,o,c=!0,u=()=>{let l=s.get();if(l&&o&&this.autoQuality){if(c&&l>o&&Wo(n)<3e4)return;r(l)}c=this.autoQuality};return{updateChunk:(l,p)=>{let h=s.updateChunk(l,p);return h&&u(),h},notifySwitch:l=>{let p=Q();l<o&&(n=p),o=l}}}_fetchManifest(e,t,r){this.manifestRequest=pr(this.urlResolver.resolve(e,!0),t,r,()=>this._retryCallback()).withJSONResponse().withTimeout(Za).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;le(e).then(t=>{t||(this.params.liveOffset.pause(),this.params.videoState.setState("paused"))})}_handleManifestUpdate(e){let{logger:t,playerCallback:r,videoElement:a}=this.params,s=n=>{let o=[];return n?.length?(n.forEach((c,u)=>{c.video&&a.canPlayType(c.codecs).replace(/no/,"")&&window.MediaSource.isTypeSupported(c.codecs)&&(c.index=u,o.push(c))}),o.sort(function(c,u){return c.video&&u.video?u.video.height-c.video.height:u.bitrate-c.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))},JP))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};import{debounce as tA,filter as Sm,fromEvent as rA,interval as iA,isHigher as aA,isInvariantQuality as sA,isLower as nA,merge as oA,Subject as vm,Subscription as uA}from"@vkontakte/videoplayer-shared";var zo=class{constructor(){this.onDroopedVideoFramesLimit$=new vm;this.subscription=new uA;this.playing=!1;this.tracks=[];this.forceChecker$=new vm;this.isForceCheckCounter=0;this.prevTotalVideoFrames=0;this.prevDroppedVideoFrames=0;this.limitCounts={};this.handleChangeVideoQuality=()=>{let e=this.tracks.find(({size:t})=>t?.height===this.video.videoHeight&&t?.width===this.video.videoWidth);e&&!sA(e.quality)&&this.onChangeQuality(e.quality)};this.checkDroppedFrames=()=>{let{totalVideoFrames:e,droppedVideoFrames:t}=this.video.getVideoPlaybackQuality(),r=e-this.prevTotalVideoFrames,a=t-this.prevDroppedVideoFrames,s=1-(r-a)/r;!isNaN(s)&&s>0&&this.log({message:`[dropped]. current dropped percent: ${s}, limit: ${this.droppedFramesChecker.percentLimit}`}),!isNaN(s)&&s>=this.droppedFramesChecker.percentLimit&&aA(this.currentQuality,this.droppedFramesChecker.minQualityBanLimit)&&(this.limitCounts[this.currentQuality]=(this.limitCounts[this.currentQuality]??0)+1,this.maxQualityLimit=this.getMaxQualityLimit(this.currentQuality),this.currentTimer&&window.clearTimeout(this.currentTimer),this.currentTimer=window.setTimeout(()=>this.maxQualityLimit=this.getMaxQualityLimit(),this.droppedFramesChecker.qualityUpWaitingTime),this.onDroopedVideoFramesLimitTrigger()),this.savePrevFrameCounts(e,t)}}connect(e){this.log=e.logger.createComponentLog("DroppedFramesManager"),this.video=e.video,this.isAuto=e.isAuto,this.tracks=e.tracks,this.droppedFramesChecker=e.droppedFramesChecker,this.subscription.add(e.playing$.subscribe(()=>this.playing=!0)),this.subscription.add(e.pause$.subscribe(()=>this.playing=!1)),this.isEnabled&&this.subscribe()}destroy(){this.currentTimer&&window.clearTimeout(this.currentTimer),this.subscription.unsubscribe()}get droppedVideoMaxQualityLimit(){return this.maxQualityLimit}subscribe(){this.subscription.add(rA(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=iA(this.droppedFramesChecker.checkTime).pipe(Sm(()=>this.playing),Sm(()=>{let a=!!this.isForceCheckCounter;return a&&(this.isForceCheckCounter-=1),!a})),t=this.forceChecker$.pipe(tA(this.droppedFramesChecker.checkTime)),r=oA(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){let t=Object.entries(this.limitCounts).filter(([,r])=>r>=this.droppedFramesChecker.countLimit).sort(([r],[a])=>nA(r,a)?-1:1)?.[0]?.[0];return e??t}get isEnabled(){return this.droppedFramesChecker.enabled&&this.isDroppedFramesCheckerSupport}get isDroppedFramesCheckerSupport(){return!!this.video&&typeof this.video.getVideoPlaybackQuality=="function"}savePrevFrameCounts(e,t){this.prevTotalVideoFrames=e,this.prevDroppedVideoFrames=t}},es=zo;import{map as cA,Observable as lA}from"@vkontakte/videoplayer-shared";import{fromEvent as dA}from"@vkontakte/videoplayer-shared";var li=()=>!!window.documentPictureInPicture?.window||!!document.pictureInPictureElement;var pA=(i,e)=>new lA(t=>{if(!window.IntersectionObserver)return;let r={root:null},a=new IntersectionObserver((n,o)=>{n.forEach(c=>t.next(c.isIntersecting||li()))},{...r,...e});a.observe(i);let s=dA(document,"visibilitychange").pipe(cA(n=>!document.hidden||li())).subscribe(n=>t.next(n));return()=>{a.unobserve(i),s.unsubscribe}}),Pe=pA;var TA=["paused","playing","ready"],IA=["paused","playing","ready"],di=class{constructor(e){this.subscription=new SA;this.videoState=new L("stopped");this.representations$=new Jo([]);this.textTracksManager=new Ee;this.droppedFramesManager=new es;this.maxSeekBackTime$=new Jo(1/0);this.zeroTime$=new Jo(void 0);this.liveOffset=new Ye;this._dashCb=e=>{switch(e.name){case"buffering":{let t=e.isBuffering;this.params.output.isBuffering$.next(t);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${e.type}`,category:Im.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{let t=e.manifest,r=[];for(let a of t){let s=a.name??a.index.toString(10),n=ct(a.name)??yA(a.video),o=a.bitrate/1e3,c={...a.video};if(!n)continue;let u={id:s,quality:n,bitrate:o,size:c};r.push({track:u,representation:a})}this.representations$.next(r),this.params.output.availableVideoTracks$.next(r.map(({track:a})=>a)),this.videoState.getTransition()?.to==="manifest_ready"&&this.videoState.setState("manifest_ready");break}case"qualitySwitch":{let t=e.quality,r=this.representations$.getValue().find(({representation:a})=>a===t)?.track;this.params.output.hostname$.next(new URL(t.headerUrl,this.params.source.url).hostname),Ko(r)&&this.params.output.currentVideoTrack$.next(r);break}case"bandwidth":{let{size:t,duration:r}=e;this.params.dependencies.throughputEstimator.addRawSpeed(t,r);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(),a=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(IA.includes(e)&&(n||o)){this.prepare();return}if(a?.to!=="paused"&&s.state==="requested"&&TA.includes(e)){this.seek(s.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(K(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 c=a?.from;c&&c==="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 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.dash.reinit(K(this.params.source.url,c))}return;default:return ym(e)}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=a=>{e.output.error$.next({id:"DashLiveProvider",category:Im.WTF,message:"DashLiveProvider internal logic error",thrown:a})};xm(this.videoState.stateChangeStarted$.pipe(ts(a=>({transition:a,type:"start"}))),this.videoState.stateChangeEnded$.pipe(ts(a=>({transition:a,type:"end"})))).subscribe(({transition:a,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(a)}`})}),this.video=se(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(Y(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=ue(this.video);this.subscription.add(this.representations$.pipe(ts(a=>a.map(({track:s})=>s)),Em(a=>!!a.length),gA()).subscribe(a=>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:a}))),this.subscription.add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.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(mA(),ts(a=>-a/1e3)).subscribe(this.params.output.duration$)).add(hA({zeroTime:this.zeroTime$.pipe(Em(Ko)),position:r.timeUpdate$}).subscribe(({zeroTime:a,position:s})=>this.params.output.liveTime$.next(a+s*1e3),t)).add(qe(this.video,this.params.desiredState.isLooped,t)).add(oe(this.video,this.params.desiredState.volume,r.volumeState$,t)).add(r.volumeState$.subscribe(this.params.output.volume$,t)).add(Ie(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(Pe(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:a}})=>{let s=a&&vA(a);this.dash.setMaxAutoQuality(s),this.params.output.autoVideoTrackLimits$.next({max:a})})).add(this.videoState.stateChangeEnded$.subscribe(a=>{switch(a.to){case"stopped":this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState("stopped");break;case"manifest_ready":case"ready":this.params.desiredState.playbackState.getTransition()?.to==="ready"&&this.params.desiredState.playbackState.setState("ready");break;case"paused":this.params.desiredState.playbackState.setState("paused");break;case"playing":this.params.desiredState.playbackState.setState("playing");break;default:return ym(a.to)}},t)).add(xm(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,bA(["init"])).pipe(fA(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),ne(this.video)}createLiveDashPlayer(){let e=new ci({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(){let e=this.representations$.getValue(),t=this.params.desiredState.videoTrack.getTransition()?.to??this.params.desiredState.videoTrack.getState(),r=this.params.desiredState.autoVideoTrackSwitching.getTransition()?.to??this.params.desiredState.autoVideoTrackSwitching.getState(),a=!r&&Ko(t)?t:lt(e.map(({track:u})=>u),{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=a?.id,n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.videoTrack.getState()?.id,c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(a&&(n||s!==o)&&this.setVideoTrack(a),c&&this.setAutoQuality(r),n||c||s!==o){let u=e.find(({track:d})=>d.id===s)?.representation;Tm(u,"Representations missing"),this.dash.startPlay(u,r)}}setVideoTrack(e){let t=this.representations$.getValue().find(({track:r})=>r.id===e.id)?.representation;Tm(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(),a=t==="paused"&&r==="paused",s=-e,n=s<=this.maxSeekBackTime$.getValue()?s:0;this.params.output.position$.next(e/1e3),this.dash.reinit(K(this.params.source.url,n)),a&&this.dash.pause(),this.liveOffset.resetTo(n,a)}};var Pm=di;var ze=(i,e)=>{let t=0;for(let r=0;r<i.length;r++){let a=i.start(r)*1e3,s=i.end(r)*1e3;a<=e&&e<=s&&(t=s)}return Math.max(t-e,0)};import{assertNever as Wk,assertNonNullable as Yk,debounce as Qk,ErrorCategory as Pu,filter as qb,filterChanged as Au,fromEvent as zk,isNonNullable as Kk,map as Ub,merge as Ts,observableFrom as Jk,observeElementSize as Xk,once as Hb,Subscription as Zk,ValueSubject as ew}from"@vkontakte/videoplayer-shared";var rs=class{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,r){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:r})}removeEventListener(e,t){if(!(e in this.listeners))return;let r=this.listeners[e];for(let a=0,s=r.length;a<s;a++)if(r[a].callback===t){r.splice(a,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;let r=this.listeners[e.type].slice();for(let a=0,s=r.length;a<s;a++){let n=r[a];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}},hr=class extends rs{constructor(){super(),this.listeners||rs.call(this),Object.defineProperty(this,"aborted",{value:!1,writable:!0,configurable:!0}),Object.defineProperty(this,"onabort",{value:null,writable:!0,configurable:!0}),Object.defineProperty(this,"reason",{value:void 0,writable:!0,configurable:!0})}toString(){return"[object AbortSignal]"}dispatchEvent(e){e.type==="abort"&&(this.aborted=!0,typeof this.onabort=="function"&&this.onabort.call(this,e)),super.dispatchEvent(e)}},pi=class{constructor(){Object.defineProperty(this,"signal",{value:new hr,writable:!0,configurable:!0})}abort(e){let t;try{t=new Event("abort")}catch{typeof document<"u"?document.createEvent?(t=document.createEvent("Event"),t.initEvent("abort",!1,!1)):(t=document.createEventObject(),t.type="abort"):t={type:"abort",bubbles:!1,cancelable:!1}}let r=e;if(r===void 0)if(typeof document>"u")r=new Error("This operation was aborted"),r.name="AbortError";else try{r=new DOMException("signal is aborted without reason")}catch{r=new Error("This operation was aborted"),r.name="AbortError"}this.signal.reason=r,this.signal.dispatchEvent(t)}toString(){return"[object AbortController]"}};typeof Symbol<"u"&&Symbol.toStringTag&&(pi.prototype[Symbol.toStringTag]="AbortController",hr.prototype[Symbol.toStringTag]="AbortSignal");function is(i){return i.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof i.Request=="function"&&!i.Request.prototype.hasOwnProperty("signal")||!i.AbortController}function Xo(i){typeof i=="function"&&(i={fetch:i});let{fetch:e,Request:t=e.Request,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:a=!1}=i;if(!is({fetch:e,Request:t,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:a}))return{fetch:e,Request:s};let s=t;(s&&!s.prototype.hasOwnProperty("signal")||a)&&(s=function(u,d){let l;d&&d.signal&&(l=d.signal,delete d.signal);let p=new t(u,d);return l&&Object.defineProperty(p,"signal",{writable:!1,enumerable:!1,configurable:!0,value:l}),p},s.prototype=t.prototype);let n=e;return{fetch:(c,u)=>{let d=s&&s.prototype.isPrototypeOf(c)?c.signal:u?u.signal:void 0;if(d){let l;try{l=new DOMException("Aborted","AbortError")}catch{l=new Error("Aborted"),l.name="AbortError"}if(d.aborted)return Promise.reject(l);let p=new Promise((h,m)=>{d.addEventListener("abort",()=>m(l),{once:!0})});return u&&u.signal&&delete u.signal,Promise.race([p,n(c,u)])}return n(c,u)},Request:s}}var hi=is({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),Am=hi?Xo({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,Ke=hi?Am.fetch:window.fetch,r0=hi?Am.Request:window.Request,Je=hi?pi:window.AbortController,i0=hi?hr:window.AbortSignal;var Rm=Ne(ii(),1);var Xe=()=>window.ManagedMediaSource||window.MediaSource,as=()=>!!(window.ManagedMediaSource&&window.ManagedSourceBuffer?.prototype?.appendBuffer),km=()=>!!(window.MediaSource&&window.MediaStreamTrack&&window.SourceBuffer?.prototype?.appendBuffer),wm=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;import{assertNever as us,clientChecker as ns}from"@vkontakte/videoplayer-shared";var os=document.createElement("video"),PA='video/mp4; codecs="avc1.42000a,mp4a.40.2"',AA='video/mp4; codecs="hev1.1.6.L93.B0"',$m='video/webm; codecs="vp09.00.10.08"',Lm='video/webm; codecs="av01.0.00M.08"',kA='audio/mp4; codecs="mp4a.40.2"',wA='audio/webm; codecs="opus"',Lt={mms:as(),mse:km(),hls:!!(os.canPlayType?.("application/x-mpegurl")||os.canPlayType?.("vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},de={mp4:!!os.canPlayType?.("video/mp4"),webm:!!os.canPlayType?.("video/webm"),cmaf:!0},pe={h264:!!Xe()?.isTypeSupported?.(PA),h265:!!Xe()?.isTypeSupported?.(AA),vp9:!!Xe()?.isTypeSupported?.($m),av1:!!Xe()?.isTypeSupported?.(Lm),aac:!!Xe()?.isTypeSupported?.(kA),opus:!!Xe()?.isTypeSupported?.(wA)},fr=(pe.h264||pe.h265)&&pe.aac,Mt,RA=async()=>{if(!window.navigator.mediaCapabilities)return;let i={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=await Promise.all([window.navigator.mediaCapabilities.decodingInfo({...i,video:{...i.video,contentType:Lm}}),window.navigator.mediaCapabilities.decodingInfo({...i,video:{...i.video,contentType:$m}})]);Mt={DASH_WEBM_AV1:e,DASH_WEBM:t}};try{RA()}catch(i){console.error(i)}var mr=Lt.hls&&de.mp4,Mm=()=>Object.keys(pe).filter(i=>pe[i]),Cm=(i,e=!1,t=!1)=>{let r=Lt.mse||Lt.mms&&t;return i.filter(a=>{switch(a){case"DASH_SEP":return r&&de.mp4&&fr;case"DASH_WEBM":return r&&de.webm&&pe.vp9&&pe.opus;case"DASH_WEBM_AV1":return r&&de.webm&&pe.av1&&pe.opus;case"DASH_STREAMS":return r&&(de.mp4&&fr||de.webm&&(pe.vp9||pe.av1)&&(pe.opus||pe.aac));case"DASH_LIVE":return Lt.mse&&de.mp4&&fr;case"DASH_LIVE_CMAF":return r&&de.mp4&&fr&&de.cmaf;case"DASH_ONDEMAND":return r&&de.mp4&&fr;case"HLS":case"HLS_ONDEMAND":return mr||e&&Lt.mse&&de.mp4&&fr;case"HLS_LIVE":case"HLS_LIVE_CMAF":return mr;case"MPEG":return de.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return Lt.webrtc&&Lt.ws&&pe.h264&&(de.mp4||de.webm);default:return us(a)}})},ss=i=>{let e="DASH_WEBM",t="DASH_WEBM_AV1";switch(i){case"vp9":return[e,t];case"av1":return[t,e];case"none":return[];case"smooth":return Mt?Mt[t].smooth?[t,e]:Mt[e].smooth?[e,t]:[t,e]:[e,t];case"power_efficient":return Mt?Mt[t].powerEfficient?[t,e]:Mt[e].powerEfficient?[e,t]:[t,e]:[e,t];default:us(i)}return[e,t]},Dm=({webmCodec:i,androidPreferredFormat:e,preferMultiStream:t})=>{let r=[...t?["DASH_STREAMS"]:[],...ss(i),"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]],a=[...t?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]];if(ns.isAndroid)switch(e){case"mpeg":return["MPEG",...r,"HLS","HLS_ONDEMAND"];case"hls":return["HLS","HLS_ONDEMAND",...r,"MPEG"];case"dash":return[...r,"HLS","HLS_ONDEMAND","MPEG"];case"dash_any_mpeg":return[...a,"MPEG",...ss(i),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...ss(i),"MPEG",...a,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...ss(i),...a,"HLS","HLS_ONDEMAND"];default:us(e)}return mr?[...r,"HLS","HLS_ONDEMAND","MPEG"]:[...r,"HLS","HLS_ONDEMAND","MPEG"]},Bm=({androidPreferredFormat:i,preferCMAF:e,preferWebRTC:t})=>{let r=e?["DASH_LIVE_CMAF","DASH_LIVE"]:["DASH_LIVE","DASH_LIVE_CMAF"],a=e?["HLS_LIVE_CMAF","HLS_LIVE"]:["HLS_LIVE","HLS_LIVE_CMAF"],s=[...r,...a],n=[...a,...r],o,c=ns.isMac&&ns.isSafari;if(ns.isAndroid)switch(i){case"dash":case"dash_any_mpeg":case"dash_any_webm":case"dash_sep":{o=s;break}case"hls":case"mpeg":{o=n;break}default:us(i)}else mr&&!c?o=n:c?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"]},Zo=i=>i?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],Vm=i=>{if(i.size!==0){if(i.size===1)return i.values().next().value.split(".").at(0);for(let e of i){let t=(0,Rm.default)(e.split("."),0);if(t==="opus"||t==="vp09"||t==="av01")return t}return i.values().next().value.split(".").at(0)}};import{ErrorCategory as fi}from"@vkontakte/videoplayer-shared";var Om=i=>{if(!i)return{id:"EmptyResponse",category:fi.PARSER,message:"Empty response"};if(i.length<=2&&i.match(/^\d+$/))return{id:`UVError#${i}`,category:fi.NETWORK,message:`UV Error ${i}`};let e=i.trimStart().substring(0,100).toLowerCase();if(e.startsWith("<!doctype")||e.startsWith("<html>")||e.startsWith("<body>")||e.startsWith("<head>"))return{id:"UnexpectedHTML",category:fi.NETWORK,message:"Received unexpected HTML, possibly a ISP block"};if(e.startsWith("<?xml"))return new DOMParser().parseFromString(i,"text/xml").querySelector("parsererror")?{id:"InvalidXML",category:fi.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:fi.PARSER,message:"Response is valid XML, but parser failed"}};var br=(i,e)=>{for(let t=0;t<i.length;t++)if(i.start(t)*1e3<=e&&i.end(t)*1e3>e)return!0;return!1};import{abortable as Iu,assertNonNullable as Ft,combine as ms,ErrorCategory as pt,filter as bs,filterChanged as Db,fromEvent as xr,interval as Eu,isNonNullable as Bb,map as xu,merge as Pr,Subject as Vb,Subscription as Ob,tap as _k,throttle as Nk,clientChecker as Fk,ValueSubject as Z,flattenObject as Hi,getTraceSubscriptionMethod as qk}from"@vkontakte/videoplayer-shared";var Ir=Ne(ii(),1);var $A=(i,e={})=>{let r=e.timeout||1,a=performance.now();return window.setTimeout(()=>{i({get didTimeout(){return e.timeout?!1:performance.now()-a-1>r},timeRemaining(){return Math.max(0,1+(performance.now()-a))}})},1)},LA=i=>window.clearTimeout(i),_m=typeof window.requestIdleCallback!="function"||typeof window.cancelIdleCallback!="function",eu=_m?$A:window.requestIdleCallback,g0=_m?LA:window.cancelIdleCallback;var kb=Ne(Ya(),1);import{assertNever as MA,ErrorCategory as Nm,clientChecker as tu,Subject as Fm}from"@vkontakte/videoplayer-shared";var CA=16,qm=!1;try{qm=tu.isSafari&&!!tu.macVersion&&tu.macVersion<=CA}catch(i){console.error(i)}var ru=class{constructor(e){this.bufferFull$=new Fm;this.error$=new Fm;this.queue=[];this.currentTask=null;this.destroyed=!1;this.completeTask=()=>{try{if(this.currentTask){let e=this.currentTask.signal?.aborted;this.currentTask.callback(!e),this.currentTask=null}this.queue.length&&this.pull()}catch(e){this.error$.next({id:"BufferTaskQueueUnknown",category:Nm.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:e})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(r=>{let a={operation:"append",data:e,signal:t,callback:r};this.queue.push(a),this.pull()})}async remove(e,t,r){return r&&r.aborted?!1:new Promise(a=>{let s={operation:"remove",from:e,to:t,signal:r,callback:a};this.queue.unshift(s),this.pull()})}async abort(e){return new Promise(t=>{let r;qm&&e?r={operation:"safariAbort",init:e,callback:t}:r={operation:"abort",callback:t};for(let{callback:a}of this.queue)a(!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(){if(this.buffer.updating||this.currentTask||this.destroyed)return;let e=this.queue.shift();if(!e)return;if(e.signal?.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(a){a instanceof DOMException&&a.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):a instanceof DOMException&&a.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:Nm.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:a}),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:MA(t)}}},Um=ru;var iu=i=>{let e=0;for(let t=0;t<i.length;t++)e+=i.end(t)-i.start(t);return e*1e3};import{abortable as Tr,assertNonNullable as Ae,ErrorCategory as Ot,fromEvent as bu,getExponentialDelay as gu,isNonNullable as Su,isNullable as ke,once as $k,Subject as Lk,Subscription as Mk,ValueSubject as Oi}from"@vkontakte/videoplayer-shared";var _=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 a=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,a),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 a=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,a}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 gr=class extends _{};var mi=class extends _{};var bi=class extends _{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 a=this.readString(4);this.compatibleBrands.push(a),r-=4}}};var gi=class extends _{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Si=class extends _{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var vi=class extends _{constructor(e,t){super(e,t),this.data=this.content}};var j=class extends _{constructor(e,t){super(e,t);let r=this.readUint32();this.version=r>>>24,this.flags=r&16777215}};var Ct=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 a=this.readUint32(),s=a>>>31,n=a<<1>>>1,o=this.readUint32();a=this.readUint32();let c=a>>>28,u=a<<3>>>3;this.segments.push({referenceType:s,referencedSize:n,subsegmentDuration:o,SAPType:c,SAPDeltaTime:u})}}};var yi=class extends _{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Ti=class extends _{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Ii=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 Ei=class extends j{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var xi=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 Pi=class extends _{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Ai=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 ki=class extends _{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var wi=class extends _{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Ri=class extends j{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var $i=class extends _{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Li=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 Mi=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 Ci=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 a=0;a<this.sampleCount;a++)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 BA={ftyp:bi,moov:gi,moof:Si,mdat:vi,sidx:Ct,trak:yi,mdia:Pi,mfhd:Ri,tkhd:Ai,traf:$i,tfhd:Li,tfdt:Mi,trun:Ci,minf:ki,sv3d:Ti,st3d:Ii,prhd:Ei,proj:wi,equi:xi,uuid:mi,unknown:gr},Dt=class i{constructor(e={}){this.options={offset:0,...e}}parse(e){let t=[],r=this.options.offset;for(;r<e.byteLength;)try{let s=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+r+4,4)),n=this.createBox(s,new DataView(e.buffer,e.byteOffset+r));if(!n.size)break;t.push(n),r+=n.size}catch{break}return t}createBox(e,t){let r=BA[e];return r?new r(t,new i):new gr(t,new i)}};var Sr=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{this.index[t.type]??=[],this.index[t.type].push(t),t.children.length>0&&this.indexBoxLevel(t.children)})}find(e){return this.index[e]&&this.index[e][0]?this.index[e][0]:null}findAll(e){return this.index[e]||[]}};var OA=new TextDecoder("ascii"),_A=i=>OA.decode(new DataView(i.buffer,i.byteOffset+4,4))==="ftyp",NA=i=>{let e=new Ct(i,new Dt),t=e.earliestPresentationTime/e.timescale*1e3,r=i.byteOffset+i.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})},FA=(i,e)=>{let r=new Dt().parse(i),a=new Sr(r),s=a.findAll("moof"),n=e?a.findAll("uuid"):a.findAll("mdat");if(!(n.length&&s.length))return null;let o=s[0],c=n[n.length-1],u=o.source.byteOffset,l=c.source.byteOffset-o.source.byteOffset+c.size;return new DataView(i.buffer,u,l)},qA=(i,e)=>{let r=new Dt().parse(i),s=new Sr(r).findAll("traf"),n=s[s.length-1].children.find(l=>l.type==="tfhd"),o=s[s.length-1].children.find(l=>l.type==="tfdt"),c=s[s.length-1].children.find(l=>l.type==="trun"),u=0;return c.sampleDuration.length?u=c.sampleDuration.reduce((l,p)=>l+p,0):u=n.defaultSampleDuration*c.sampleCount,(Number(o.baseMediaDecodeTime)+u)/e*1e3},UA=i=>{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 Dt().parse(i),a=new Sr(r);if(a.find("sv3d")){e.is3dVideo=!0;let n=a.find("st3d");n&&(e.stereoMode=n.stereoMode);let o=a.find("prhd");o&&(e.projectionData.pose.yaw=o.poseYawDegrees,e.projectionData.pose.pitch=o.posePitchDegrees,e.projectionData.pose.roll=o.poseRollDegrees);let c=a.find("equi");c&&(e.projectionData.bounds.top=c.projectionBoundsTop,e.projectionData.bounds.right=c.projectionBoundsRight,e.projectionData.bounds.bottom=c.projectionBoundsBottom,e.projectionData.bounds.left=c.projectionBoundsLeft)}return e},Hm={validateData:_A,parseInit:UA,getIndexRange:()=>{},parseSegments:NA,parseFeedableSegmentChunk:FA,getSegmentEndTime:qA};import{assertNonNullable as su,isNonNullable as Ym,isNullable as jA}from"@vkontakte/videoplayer-shared";import{assertNever as HA}from"@vkontakte/videoplayer-shared";var jm={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"}},Gm=i=>{let e=i.getUint8(0),t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);let r=Di(i,t),a=r in jm,s=a?jm[r].type:"binary",n=i.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 c=new DataView(i.buffer,i.byteOffset+t+1,o-1),u=n&255>>o,d=Di(c),l=u*2**((o-1)*8)+d,p=t+o,h;return p+l>i.byteLength?h=new DataView(i.buffer,i.byteOffset+p):h=new DataView(i.buffer,i.byteOffset+p,l),{tag:a?r:"0x"+r.toString(16).toUpperCase(),type:s,tagHeaderSize:p,tagSize:p+l,value:h,valueSize:l}},Di=(i,e=i.byteLength)=>{switch(e){case 1:return i.getUint8(0);case 2:return i.getUint16(0);case 3:return i.getUint8(0)*2**16+i.getUint16(1);case 4:return i.getUint32(0);case 5:return i.getUint8(0)*2**32+i.getUint32(1);case 6:return i.getUint16(0)*2**32+i.getUint32(2);case 7:{let t=i.getUint8(0)*281474976710656+i.getUint16(1)*4294967296+i.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},Be=(i,e)=>{switch(e){case"int":return i.getInt8(0);case"uint":return Di(i);case"float":return i.byteLength===4?i.getFloat32(0):i.getFloat64(0);case"string":return new TextDecoder("ascii").decode(i);case"utf8":return new TextDecoder("utf-8").decode(i);case"date":return new Date(Date.UTC(2001,0)+i.getInt8(0)).getTime();case"master":return i;case"binary":return i;default:HA(e)}},Bt=(i,e)=>{let t=0;for(;t<i.byteLength;){let r=new DataView(i.buffer,i.byteOffset+t),a=Gm(r);if(!e(a))return;a.type==="master"&&Bt(a.value,e),t=a.value.byteOffset-i.byteOffset+a.valueSize}},Wm=i=>{if(i.getUint32(0)!==440786851)return!1;let e,t,r,a=Gm(i);return Bt(a.value,({tag:s,type:n,value:o})=>(s===17143?e=Be(o,n):s===17026?t=Be(o,n):s===17029&&(r=Be(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(r===void 0||r<=2)};var Qm=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],GA=[231,22612,22743,167,171,163,160,175],WA=i=>{let e,t,r,a,s=!1,n=!1,o=!1,c,u,d=!1,l=0;return Bt(i,({tag:p,type:h,value:m,valueSize:b})=>{if(p===21419){let g=Be(m,h);u=Di(g)}else p!==21420&&(u=void 0);return p===408125543?(e=m.byteOffset,t=m.byteOffset+b):p===357149030?s=!0:p===290298740?n=!0:p===2807729?r=Be(m,h):p===17545?a=Be(m,h):p===21420&&u===475249515?c=Be(m,h):p===374648427?Bt(m,({tag:g,type:v,value:A})=>g===30321?(d=Be(A,v)===1,!1):!0):s&&n&&Qm.includes(p)&&(o=!0),!o}),su(e,"Failed to parse webm Segment start"),su(t,"Failed to parse webm Segment end"),su(a,"Failed to parse webm Segment duration"),r=r??1e6,{segmentStart:Math.round(e/1e9*r*1e3),segmentEnd:Math.round(t/1e9*r*1e3),timeScale:r,segmentDuration:Math.round(a/1e9*r*1e3),cuesSeekPosition:c,is3dVideo:d,stereoMode:l,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},YA=i=>{if(jA(i.cuesSeekPosition))return;let e=i.segmentStart+i.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},QA=(i,e)=>{let t=!1,r=!1,a=o=>Ym(o.time)&&Ym(o.position),s=[],n;return Bt(i,({tag:o,type:c,value:u})=>{switch(o){case 475249515:t=!0;break;case 187:n&&a(n)&&s.push(n),n={};break;case 179:n&&(n.time=Be(u,c));break;case 183:break;case 241:n&&(n.position=Be(u,c));break;default:t&&Qm.includes(o)&&(r=!0)}return!(t&&r)}),n&&a(n)&&s.push(n),s.map((o,c)=>{let{time:u,position:d}=o,l=s[c+1];return{status:"none",time:{from:u,to:l?l.time:e.segmentDuration},byte:{from:e.segmentStart+d,to:l?e.segmentStart+l.position-1:e.segmentEnd-1}}})},zA=i=>{let e=0,t=!1;try{Bt(i,r=>r.tag===524531317?r.tagSize<=i.byteLength?(e=r.tagSize,!1):(e+=r.tagHeaderSize,!0):GA.includes(r.tag)?(e+r.tagSize<=i.byteLength&&(e+=r.tagSize,t||=[163,160,175].includes(r.tag)),!0):!1)}catch{}return e>0&&e<=i.byteLength&&t?new DataView(i.buffer,i.byteOffset,e):null},zm={validateData:Wm,parseInit:WA,getIndexRange:YA,parseSegments:QA,parseFeedableSegmentChunk:zA};var vr=i=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(i);if(e){let[,t,r]=e;if(t==="audio"||t==="video")switch(r){case"webm":return zm;case"mp4":return Hm}}throw new ReferenceError(`Unsupported mime type ${i}`)};var pu=Ne(gb(),1);var du=i=>{let e=i.split("."),[t,...r]=e;if(!t)return!1;switch(t){case"av01":{let[a,s,n]=r;return!!(n&&parseInt(n,10)>8)}case"vp09":{let[a,s,n]=r;return!!(a&&parseInt(a,10)>=2&&n&&parseInt(n,10)>8)}case"avc1":{let a=r[0];if(!a||a.length!==6)return!1;let[s,n]=a.toUpperCase(),o=s+n;return["6E","7A","F4"].includes(o)}}return!1};import{isNonNullable as vb,isNullable as yb}from"@vkontakte/videoplayer-shared";var Sb=i=>{if(i.includes("/")){let e=i.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(i)};var Tb=i=>{if(!i.startsWith("P"))return;let e=(n,o)=>{let c=n?parseFloat(n.replace(",",".")):NaN;return(isNaN(c)?0:c)*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(i),a=r?.[1]==="-"?-1:1,s={days:e(r?.[5],a),hours:e(r?.[6],a),minutes:e(r?.[7],a),seconds:e(r?.[8],a)};return s.days*24*60*60*1e3+s.hours*60*60*1e3+s.minutes*60*1e3+s.seconds*1e3},Vt=(i,e)=>{let t=i;t=(0,pu.default)(t,"$$","$");let r={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[a,s]of Object.entries(r)){let n=new RegExp(`\\$${a}(?:%0(\\d+)d)?\\$`,"g");t=(0,pu.default)(t,n,(o,c)=>yb(s)?o:yb(c)?s:s.padStart(parseInt(c,10),"0"))}return t},Eb=(i,e)=>{let r=new DOMParser().parseFromString(i,"application/xml"),a={video:[],audio:[],text:[]},s=r.children[0],n=s.getElementsByTagName("Period")[0],o=s.querySelector("BaseURL")?.textContent?.trim()??"",c=n.children,u=s.getAttribute("type")==="dynamic",d=s.getAttribute("availabilityStartTime"),l=d?new Date(d).getTime():void 0,p,h=s.getAttribute("mediaPresentationDuration"),m=n.getAttribute("duration"),g=s.getElementsByTagName("vk:Attrs")[0]?.getElementsByTagName("vk:XPlaybackDuration")[0].textContent;if(h)p=Tb(h);else if(m){let S=Tb(m);vb(S)&&(p=S)}else g&&(p=parseInt(g,10));let v=0,A=s.getAttribute("profiles")?.split(",")??[];for(let S of c){let T=S.getAttribute("id")??"id"+(v++).toString(10),E=S.getAttribute("mimeType")??"",D=S.getAttribute("codecs")??"",O=S.getAttribute("contentType")??E?.split("/")[0],N=S.getAttribute("profiles")?.split(",")??[],k=S.getAttribute("lang")??void 0,w=S.querySelector("Label")?.textContent?.trim()??void 0,$=S.querySelectorAll("Representation"),q=S.querySelector("SegmentTemplate"),we=S.querySelector("Role")?.getAttribute("value")??void 0,te=O,x={id:T,language:k,isDefault:we==="main",label:w,codecs:D,hdr:te==="video"&&du(D),mime:E,representations:[]};for(let R of $){let G=R.getAttribute("lang")??void 0,z=R.getAttribute("label")??void 0,he=R.querySelector("BaseURL")?.textContent?.trim()??"",Oe=new URL(he||o,e).toString(),Ut=R.getAttribute("mimeType")??E,gt=R.getAttribute("codecs")??D??"",B;if(O==="text"){let W=R.getAttribute("id")||"",re=W.includes("_auto");B={id:W,isAuto:re,kind:"text",url:Oe}}else{let W=R.getAttribute("contentType")??Ut?.split("/")[0]??O,re=S.getAttribute("profiles")?.split(",")??[],Re=parseInt(R.getAttribute("width")??"",10),tt=parseInt(R.getAttribute("height")??"",10),Ht=parseInt(R.getAttribute("bandwidth")??"",10)/1e3,rt=R.getAttribute("frameRate")??"",jt=R.getAttribute("quality")??void 0,kr=rt?Sb(rt):void 0,sa=R.getAttribute("id")??"id"+(v++).toString(10),Dg=W==="video"?`${tt}p`:W==="audio"?`${Ht}Kbps`:gt,Bg=`${sa}@${Dg}`,Vg=[...A,...N,...re],Vs,Og=R.querySelector("SegmentBase"),St=R.querySelector("SegmentTemplate")??q;if(Og){let vt=R.querySelector("SegmentBase Initialization")?.getAttribute("range")??"",[yt,_s]=vt.split("-").map(Gt=>parseInt(Gt,10)),it={from:yt,to:_s},wr=R.querySelector("SegmentBase")?.getAttribute("indexRange"),[Ns,na]=wr?wr.split("-").map(Gt=>parseInt(Gt,10)):[],Rr=wr?{from:Ns,to:na}:void 0;Vs={type:"byteRange",url:Oe,initRange:it,indexRange:Rr}}else if(St){let vt={representationId:R.getAttribute("id")??void 0,bandwidth:R.getAttribute("bandwidth")??void 0},yt=parseInt(St.getAttribute("timescale")??"",10),_s=St.getAttribute("initialization")??"",it=St.getAttribute("media"),wr=parseInt(St.getAttribute("startNumber")??"",10)??1,Ns=Vt(_s,vt);if(!it)throw new ReferenceError("No media attribute in SegmentTemplate");let na=St.querySelectorAll("SegmentTimeline S")??[],Rr=[],Gt=0,Fs="",qs=0;if(na.length){let oa=wr,$e=0;for(let Wt of na){let _e=parseInt(Wt.getAttribute("d")??"",10),Tt=parseInt(Wt.getAttribute("r")??"",10)||0,ua=parseInt(Wt.getAttribute("t")??"",10);$e=Number.isFinite(ua)?ua:$e;let Us=_e/yt*1e3,Ng=$e/yt*1e3;for(let ca=0;ca<Tt+1;ca++){let Fg=Vt(it,{...vt,segmentNumber:oa.toString(10),segmentTime:($e+ca*_e).toString(10)}),Uu=(Ng??0)+ca*Us,qg=Uu+Us;oa++,Rr.push({time:{from:Uu,to:qg},url:Fg})}$e+=(Tt+1)*_e,Gt+=(Tt+1)*Us}qs=$e/yt*1e3,Fs=Vt(it,{...vt,segmentNumber:oa.toString(10),segmentTime:$e.toString(10)})}else if(vb(p)){let $e=parseInt(St.getAttribute("duration")??"",10)/yt*1e3,Wt=Math.ceil(p/$e),_e=0;for(let Tt=1;Tt<Wt;Tt++){let ua=Vt(it,{...vt,segmentNumber:Tt.toString(10),segmentTime:_e.toString(10)});Rr.push({time:{from:_e,to:_e+$e},url:ua}),_e+=$e}qs=_e,Fs=Vt(it,{...vt,segmentNumber:Wt.toString(10),segmentTime:_e.toString(10)})}let _g={time:{from:qs,to:1/0},url:Fs};Vs={type:"template",baseUrl:Oe,segmentTemplateUrl:it,initUrl:Ns,totalSegmentsDurationMs:Gt,segments:Rr,nextSegmentBeyondManifest:_g,timescale:yt}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!W||!Ut)continue;let Os={video:"video",audio:"audio",text:"text"}[W];if(!Os)continue;te||=Os,B={id:Bg,kind:Os,segmentReference:Vs,profiles:Vg,duration:p,bitrate:Ht,mime:Ut,codecs:gt,width:Re,height:tt,fps:kr,quality:jt}}x.language||=G,x.label||=z,x.mime||=Ut,x.codecs||=gt,x.hdr||=te==="video"&&du(gt),x.representations.push(B)}te&&a[te].push(x)}return{dynamic:u,liveAvailabilityStartTime:l,duration:p,streams:a}};var Bi=Ne(ii(),1);import{videoSizeToQuality as Rk}from"@vkontakte/videoplayer-shared";var xb=({id:i,width:e,height:t,bitrate:r,fps:a,quality:s})=>{let n=(s?ct(s):void 0)??Rk({width:e,height:t});return n&&{id:i,quality:n,bitrate:r,size:{width:e,height:t},fps:a}},Pb=({id:i,bitrate:e})=>({id:i,bitrate:e}),cs=(i,e,t)=>{let r=e.indexOf(i);return(0,Bi.default)(t,Math.round(t.length*r/e.length))??(0,Bi.default)(t,-1)},Ab=({language:i,label:e},{id:t,url:r,isAuto:a})=>({id:t,url:r,isAuto:a,type:"internal",language:i,label:e}),fu=({id:i,language:e,label:t,codecs:r,isDefault:a})=>({id:i,language:e,label:t,codec:(0,Bi.default)(r.split("."),0),isDefault:a}),mu=({id:i,language:e,label:t,hdr:r,codecs:a})=>({id:i,language:e,hdr:r,label:t,codec:(0,Bi.default)(a.split("."),0)}),ls=i=>"url"in i,Ze=i=>i.type==="template",Vi=i=>i instanceof DOMException&&(i.name==="AbortError"||i.code===20);var _i=class{constructor(e,t,r,{fetcher:a,tuning:s,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:c=!1,manifest:u}){this.currentSegmentLength$=new Oi(0);this.onLastSegment$=new Oi(!1);this.fullyBuffered$=new Oi(!1);this.playingRepresentation$=new Oi(void 0);this.playingRepresentationInit$=new Oi(void 0);this.error$=new Lk;this.gaps=[];this.subscription=new Mk;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new Je;this.destroyAbortController=new Je;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=Tr(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);Ae(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new Um(this.sourceBuffer),this.subscription.add(bu(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let o,c=this.mediaSource.readyState;c!=="open"&&(o={id:`SegmentEjection_source_${c}`,category:Ot.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o??={id:"SegmentEjection",category:Ot.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n},this.error$.next(o)})),this.subscription.add(bu(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:Ot.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 c=Math.min(this.bufferLimit,iu(this.sourceBuffer.buffered)*.8);if(this.bufferLimit=c,this.tuning.useNewPruneBufferStrategy){let u=ze(this.sourceBuffer.buffered,o),d=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBufferNew(o,n*2,u<d)}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),a=this.segments.get(t.id),s=this.parsedInitData.get(t.id);Ae(r,"No init buffer for starting representation"),Ae(a,"No segments for starting representation"),r instanceof ArrayBuffer&&(this.searchGaps(a,t),yield this.sourceBufferTaskQueue.append(r,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(s))}.bind(this));this.switchTo=Tr(this.destroyAbortController.signal,async function*(e,t=!1){if(e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let r=this.representations.get(e);Ae(r,`No such representation ${e}`);let a=this.segments.get(e),s=this.initData.get(e);if(ke(s)||ke(a)?yield this.loadInit(r,"high",!1):s instanceof Promise&&(yield s),a=this.segments.get(e),Ae(a,"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();Su(n)&&(this.isLive||(this.tuning.useNewPruneBufferStrategy&&(this.bufferLimit=1/0),await this.pruneBuffer(n,1/0,!0)),this.maintain(n)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}}.bind(this));this.seekLive=Tr(this.destroyAbortController.signal,async function*(e){let t=e?.flatMap(c=>c.representations)??[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let c of this.representations.keys()){let u=t.find(p=>p.id===c);u&&this.representations.set(c,u);let d=this.representations.get(c);if(!d||!Ze(d.segmentReference))return;let l=this.getActualLiveStartingSegments(d.segmentReference);this.segments.set(d.id,l)}let r=this.switchingToRepresentationId??this.downloadingRepresentationId,a=this.representations.get(r);Ae(a);let s=this.segments.get(r);Ae(s,"No segments for starting representation");let n=this.initData.get(r);if(Ae(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,a),yield this.sourceBufferTaskQueue.append(n,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this));this.fetcher=a,this.tuning=s,this.compatibilityMode=c,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=o,this.isLive=!!u?.dynamic,this.resetAccumulateBufferAfterStall(),this.startAccumulateBuffer(),this.initData=new Map(r.map(d=>[d.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(r.map(d=>[d.id,d])),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 Je,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(ke(e)||ke(this.downloadingRepresentationId)||ke(this.playingRepresentationId)||ke(this.sourceBuffer)||!ke(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),r=this.segments.get(this.downloadingRepresentationId);if(Ae(t,`No such representation ${this.downloadingRepresentationId}`),!r)return;let a=r.find(u=>e>=u.time.from&&e<u.time.to);this.currentSegmentLength$.next((a?.time.to??0)-(a?.time.from??0));let s=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){let d=ze(this.sourceBuffer.buffered,e),l=a?a.time.to+100:-1/0;a&&a.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&d>=a.time.to-e+100&&(s=l)}if(isFinite(this.bufferLimit)&&iu(this.sourceBuffer.buffered)>=this.bufferLimit){let u=ze(this.sourceBuffer.buffered,e),d=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,u<d);return}let o=[];if(!this.activeSegments.size&&(o=this.selectForwardBufferSegments(r,t.segmentReference.type,s),o.length)){let u="auto";if(this.tuning.dash.useFetchPriorityHints&&a)if(o.includes(a))u="high";else{let d=(0,Ir.default)(o,0);d&&d.time.from-a.time.to>=this.forwardBufferTarget/2&&(u="low")}this.loadSegments(o,t,u)}(!this.preloadOnly&&!this.allInitsLoaded&&a&&a.status==="fed"&&!o.length&&ze(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let c=(0,Ir.default)(r,-1);c&&c.status==="fed"&&(this.fullyBuffered$.next(!0),this.isLive||this.onLastSegment$.next(a===c))}searchGaps(e,t){this.gaps=[];let r=0,a=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+a}),r=s.time.to;Su(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,a=[],s=0,n=t.length-1;do a.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()?[a[0]]:a}getLiveSegmentsToLoadState(e){let t=e?.streams[this.kind].flatMap(a=>a.representations).find(a=>a.id===this.downloadingRepresentationId);if(!t)return;let r=this.segments.get(t.id);if(r?.length)return{from:r[0].time.from,to:r[r.length-1].time.to}}updateLive(e){let t=e?.streams[this.kind].flatMap(r=>r.representations)??[];for(let r of t){if(!r||!Ze(r.segmentReference))return;let a=r.segmentReference.segments.map(c=>({...c,status:"none",size:void 0})),s=this.segments.get(r.id)??[],n=(0,Ir.default)(s,-1)?.time.to??0,o=a?.findIndex(c=>Math.floor(n)>=Math.floor(c.time.from)&&Math.floor(n)<=Math.floor(c.time.to));if(o===-1){this.liveUpdateSegmentIndex=0;let c=this.getActualLiveStartingSegments(r.segmentReference);this.segments.set(r.id,c)}else{let c=a.slice(o+1);this.segments.set(r.id,[...s,...c])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;Ae(e);let t=this.segments.get(e);if(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){for(let t of this.representations.values()){let r=t.segmentReference;if(!Ze(r))return;let a=this.segments.get(t.id)??[],s=a.find(o=>Math.floor(o.time.from)===Math.floor(e.time.from));if(s&&!isFinite(s.time.to)&&(s.time.to=e.time.to),!!!a.find(o=>Math.floor(o.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let o=Math.round(e.time.to*r.timescale/1e3).toString(10),c=Vt(r.segmentTemplateUrl,{segmentTime:o});a.push({status:"none",time:{from:e.time.to,to:1/0},url:c})}}}findSegmentStartTime(e){let t=this.switchingToRepresentationId??this.downloadingRepresentationId??this.playingRepresentationId;if(!t)return;let r=this.segments.get(t);return r?r.find(s=>s.time.from<=e&&s.time.to>=e)?.time.from??void 0:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),this.sourceBufferTaskQueue?.destroy(),this.gapDetectionIdleCallback&&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(e){if(!(e instanceof DOMException&&e.name==="NotFoundError"))throw e}}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(a=>t>=a.time.from&&t<a.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=r),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,r){let a=e.findIndex(({status:l,time:{from:p,to:h}},m)=>{let b=p<=r&&h>=r,g=p>r||b||m===0&&r===0,v=Math.min(this.forwardBufferTarget,this.bufferLimit),A=this.preloadOnly&&p<=r+v||h<=r+v;return(l==="none"||l==="partially_ejected"&&g&&A&&this.sourceBuffer&&!(br(this.sourceBuffer.buffered,p)&&br(this.sourceBuffer.buffered,h)))&&g&&A});if(a===-1)return[];if(t!=="byteRange")return e.slice(a,a+1);let s=e,n=0,o=0,c=[],u=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,d=this.preloadOnly?this.forwardBufferTarget:0;for(let l=a;l<s.length&&(n<=u||o<=d);l++){let p=s[l];if(n+=p.byte.to+1-p.byte.from,o+=p.time.to+1-p.time.from,p.status==="none"||p.status==="partially_ejected")c.push(p);else break}return c}async loadSegments(e,t,r="auto"){t.segmentReference.type==="template"?await this.loadTemplateSegment(e[0],t,r):await this.loadByteRangeSegments(e,t,r)}async loadTemplateSegment(e,t,r="auto"){e.status="downloading";let a={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(a);let{range:s,url:n,signal:o,onProgress:c,onProgressTasks:u}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(await Tr(o,async function*(){let d=gu(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>setTimeout(l,d))}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let d=await this.fetcher.fetch(n,{range:s,signal:o,onProgress:c,priority:r,isLowLatency:this.isActiveLowLatency()});if(!d)return;let l=new DataView(d);if(!isFinite(a.segment.time.to)){let p=t.segmentReference.timescale,h=vr(t.mime);a.segment.time.to=h.getSegmentEndTime(l,p)}c&&a.feedingBytes&&u?await Promise.all(u):await this.sourceBufferTaskQueue.append(l,o),a.segment.status="downloaded",this.onSegmentFullyAppended(a,t.id),this.failedDownloads=0}catch(d){this.abortActiveSegments([e]),Vi(d)||this.failedDownloads++}}async loadByteRangeSegments(e,t,r="auto"){if(!e.length)return;for(let c of e)c.status="downloading",this.activeSegments.add({segment:c,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:a,url:s,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(await Tr(n,async function*(){let c=gu(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(u,c),bu(window,"online").pipe($k()).subscribe(()=>{u(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(s,{range:a,onProgress:o,signal:n,priority:r}),this.failedDownloads=0}catch(c){this.abortActiveSegments(e),Vi(c)||this.failedDownloads++}}prepareByteRangeFetchSegmentParams(e,t){if(Ze(t.segmentReference))throw new Error("Representation is not byte range type");let r=t.segmentReference.url,a={from:(0,Ir.default)(e,0).byte.from,to:(0,Ir.default)(e,-1).byte.to},{signal:s}=this.downloadAbortController;return{url:r,range:a,signal:s,onProgress:(o,c)=>{if(!s.aborted)try{this.onSomeByteRangesDataLoaded({dataView:o,loaded:c,signal:s,onSegmentAppendFailed:()=>this.abort(),globalFrom:a?a.from:0,representationId:t.id})}catch(u){this.error$.next({id:"SegmentFeeding",category:Ot.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:u})}}}}prepareTemplateFetchSegmentParams(e,t){if(!Ze(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 a=r.toString(),{signal:s}=this.downloadAbortController,n=[],c=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(u,d)=>{if(!s.aborted)try{let l=this.onSomeTemplateDataLoaded({dataView:u,loaded:d,signal:s,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(l)}catch(l){this.error$.next({id:"SegmentFeeding",category:Ot.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}:void 0;return{url:a,signal:s,onProgress:c,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)e.includes(t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:r,onSegmentAppendFailed:a,signal:s}){if(!this.activeSegments.size)return;let n=this.representations.get(t);if(n)for(let o of this.activeSegments){let{segment:c}=o;if(o.representationId===t){if(s.aborted){a();continue}if(o.loadedBytes=r,o.loadedBytes>o.feedingBytes){let u=new DataView(e.buffer,e.byteOffset+o.feedingBytes,o.loadedBytes-o.feedingBytes),d=vr(n.mime).parseFeedableSegmentChunk(u,this.isLive);d?.byteLength&&(c.status="partially_fed",o.feedingBytes+=d.byteLength,await this.sourceBufferTaskQueue.append(d),o.fedBytes+=d.byteLength)}}}}onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:r,loaded:a,signal:s,onSegmentAppendFailed:n}){let o={dataView:e,representationId:t,globalFrom:r,loaded:a,signal:s,onSegmentAppendFailed:n};return this.tuning.useNewPartialSegmentFeeding?this.onSomeByteRangesDataLoadedNew(o):this.onSomeByteRangesDataLoadedOld(o)}onSomeByteRangesDataLoadedOld({dataView:e,representationId:t,globalFrom:r,loaded:a,signal:s,onSegmentAppendFailed:n}){if(!this.activeSegments.size)return;let o=this.representations.get(t);if(!o)return;let c=o.segmentReference.type,u=e.byteLength;for(let d of this.activeSegments){let{segment:l}=d,p=c==="byteRange",h=p?l.byte.to-l.byte.from+1:u;if(d.representationId!==t||!(!p||l.byte.from>=r&&l.byte.to<r+e.byteLength))continue;if(s.aborted){n();continue}let b=p?l.byte.from-r:0,g=p?l.byte.to-r:e.byteLength,v=b<a,A=g<=a;if(l.status==="downloading"&&v&&A){l.status="downloaded";let y=new DataView(e.buffer,e.byteOffset+b,h),S=this.getCurrentPosition();Su(S)&&(this.bufferAccumulation.accumulatedBufferSizeMs=l.time.to-S,this.bufferAccumulation.accumulated.push({segmentView:y,segmentProgress:d}),this.activeSegments.delete(d));let T=({segmentView:E,segmentProgress:D})=>this.sourceBufferTaskQueue.append(E,s).then(O=>O&&!s.aborted?this.onSegmentFullyAppended(D,t):n());this.bufferAccumulation.enabled&&this.bufferAccumulation.targetBufferSizeMs<this.bufferAccumulation.accumulatedBufferSizeMs?(this.bufferAccumulation.accumulated.forEach(T),this.resetAccumulateBufferAfterStall()):(!this.bufferAccumulation.enabled||!this.bufferAccumulation.targetBufferSizeMs||ke(S))&&(T({segmentView:y,segmentProgress:d}),this.resetAccumulateBufferAfterStall())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&v&&!A&&(d.loadedBytes=Math.min(h,a-b),d.loadedBytes>d.feedingBytes)){let y=new DataView(e.buffer,e.byteOffset+b+d.feedingBytes,d.loadedBytes-d.feedingBytes),S=d.loadedBytes===h?y:vr(o.mime).parseFeedableSegmentChunk(y);S?.byteLength&&(l.status="partially_fed",d.feedingBytes+=S.byteLength,this.sourceBufferTaskQueue.append(S,s).then(T=>{if(s.aborted)n();else if(T)d.fedBytes+=S.byteLength,d.fedBytes===h&&this.onSegmentFullyAppended(d,t);else{if(d.feedingBytes<h)return;n()}}))}}}async onSomeByteRangesDataLoadedNew({dataView:e,representationId:t,globalFrom:r,loaded:a,signal:s,onSegmentAppendFailed:n}){if(!this.activeSegments.size)return;let o=this.representations.get(t);if(o)for(let c of this.activeSegments){let{segment:u}=c;if(c.representationId!==t)continue;if(s.aborted){n();continue}let d=u.byte.from-r,l=u.byte.to-r,p=l-d+1,h=d<a,m=l<=a;if(h){if(u.status==="downloading"&&m){u.status="downloaded";let b=new DataView(e.buffer,e.byteOffset+d,p);await this.sourceBufferTaskQueue.append(b,s)&&!s.aborted?this.onSegmentFullyAppended(c,t):n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(u.status==="downloading"||u.status==="partially_fed")&&(c.loadedBytes=Math.min(p,a-d),c.loadedBytes>c.feedingBytes)){let b=new DataView(e.buffer,e.byteOffset+d+c.feedingBytes,c.loadedBytes-c.feedingBytes),g=c.loadedBytes===p?b:vr(o.mime).parseFeedableSegmentChunk(b);g?.byteLength&&(u.status="partially_fed",c.feedingBytes+=g.byteLength,await this.sourceBufferTaskQueue.append(g,s)&&!s.aborted?(c.fedBytes+=g.byteLength,c.fedBytes===p&&this.onSegmentFullyAppended(c,t)):n())}}}}onSegmentFullyAppended(e,t){this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status="fed",ls(e.segment)&&(e.segment.size=e.fedBytes);for(let r of this.representations.values())if(r.id!==t)for(let a of this.segments.get(r.id)??[])a.status==="fed"&&Math.round(a.time.from)===Math.round(e.segment.time.from)&&Math.round(a.time.to)===Math.round(e.segment.time.to)&&(a.status="none");Ae(this.sourceBuffer),this.updateLowLatencyLiveIfNeeded(e.segment),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment])}abortSegment(e){e.status==="partially_fed"?e.status="partially_ejected":e.status!=="partially_ejected"&&(e.status="none");for(let t of this.activeSegments.values())if(t.segment===e){this.activeSegments.delete(t);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(let[a,s]of this.initData.entries()){let n=s instanceof Promise;t||=n,s===null&&(e=a)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let r=this.representations.get(e);r&&(this.initLoadIdleCallback=eu(()=>(0,kb.default)(this.loadInit(r,"low",!1),()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",r=!1){let a=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!r&&this.failedDownloads>0?Tr(this.destroyAbortController.signal,async function*(){let o=gu(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>setTimeout(c,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,vr(e.mime),a)).then(async o=>{if(!o)return;let{init:c,dataView:u,segments:d}=o,l=u.buffer.slice(u.byteOffset,u.byteOffset+u.byteLength);this.initData.set(e.id,l);let p=d;this.isLive&&Ze(e.segmentReference)&&(p=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,p),c&&this.parsedInitData.set(e.id,c)}).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),r&&this.error$.next({id:"LoadInits",category:Ot.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n}async dropBuffer(){for(let e of this.segments.values())for(let t of e)t.status="none";await this.pruneBuffer(0,1/0,!0)}async pruneBuffer(e,t,r=!1){return this.tuning.useNewPruneBufferStrategy?this.pruneBufferNew(e,t,r):this.pruneBufferOld(e,t,r)}async pruneBufferNew(e,t,r=!1){if(!this.sourceBuffer||!this.playingRepresentationId||ke(e)||this.sourceBuffer.updating)return!1;let a=[],s=0,n=c=>{c.sort((d,l)=>d.from-l.from);let u=[c[0]];for(let d=1;d<c.length;d++){let{from:l,to:p}=c[d],h=u[u.length-1];h.to>=l?h.to=Math.max(h.to,p):u.push(c[d])}return u},o=c=>{if(s>=t)return a;a.push({...c.time}),a=n(a);let u=ls(c)?c.size??0:c.byte.to-c.byte.from;s+=u};for(let c of this.segments.values())for(let u of c){let d=u.time.to<=e-this.tuning.dash.bufferPruningSafeZone,l=u.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(d||l)&&u.status==="fed"&&o(u)}for(let c=0;c<this.sourceBuffer.buffered.length;c++){let u=this.sourceBuffer.buffered.start(c)*1e3,d=this.sourceBuffer.buffered.end(c)*1e3,l=0;for(let p of this.segments.values())for(let h of p)["none","partially_ejected"].includes(h.status)&&Math.round(h.time.from)<=Math.round(u)&&Math.round(h.time.to)>=Math.round(d)&&l++;if(l===this.segments.size){let p={time:{from:u,to:d},url:"",status:"none"};o(p)}}if(a.length&&r){let c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let u of this.segments.values())for(let d of u)d.time.from>=e+c&&d.status==="fed"&&o(d)}return a.length?(await Promise.all(a.map(u=>this.sourceBufferTaskQueue.remove(u.from,u.to)))).reduce((u,d)=>u||d,!1):!1}async pruneBufferOld(e,t,r=!1){if(!this.sourceBuffer||!this.playingRepresentationId||ke(e)||this.sourceBuffer.updating)return!1;let a=0,s=1/0,n=-1/0,o=!1,c=u=>{s=Math.min(s,u.time.from),n=Math.max(n,u.time.to);let d=ls(u)?u.size??0:u.byte.to-u.byte.from;a+=d};for(let u of this.segments.values())for(let d of u){if(d.time.to>=e-this.tuning.dash.bufferPruningSafeZone||a>=t)break;d.status==="fed"&&c(d)}if(o=isFinite(s)&&isFinite(n),!o){a=0,s=1/0,n=-1/0;for(let u of this.segments.values())for(let d of u){if(d.time.from<e+Math.min(this.forwardBufferTarget,this.bufferLimit)||a>t)break;d.status==="fed"&&c(d)}}if(o=isFinite(s)&&isFinite(n),!o)for(let u=0;u<this.sourceBuffer.buffered.length;u++){let d=this.sourceBuffer.buffered.start(u)*1e3,l=this.sourceBuffer.buffered.end(u)*1e3;for(let p of this.segments.values())for(let h of p)if(h.status==="none"&&Math.round(h.time.from)<=Math.round(d)&&Math.round(h.time.to)>=Math.round(l)){s=d,n=l;break}}if(o=isFinite(s)&&isFinite(n),!o&&r){a=0,s=1/0,n=-1/0;let u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let d of this.segments.values())for(let l of d)l.time.from>e+u&&l.status==="fed"&&c(l)}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 a={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){a=void 0;break}o>r.time.from&&o<r.time.to&&(a.from=o),n<r.time.to&&n>r.time.from&&(a.to=n)}}a&&a.to-a.from>1&&!this.gaps.some(s=>a&&s.from===a.from&&s.to===a.to)&&this.gaps.push(a)}}detectGapsWhenIdle(e,t){if(!this.gapDetectionIdleCallback){Ae(this.sourceBuffer);for(let r=0;r<this.sourceBuffer.buffered.length;r++)this.gaps=this.gaps.filter(a=>this.sourceBuffer&&(Math.round(a.from)<Math.round(this.sourceBuffer.buffered.start(r)*1e3)||Math.round(a.to)>Math.round(this.sourceBuffer.buffered.end(r)*1e3)));this.gapDetectionIdleCallback=eu(()=>{try{this.detectGaps(e,t)}catch(r){this.error$.next({id:"GapDetection",category:Ot.WTF,message:"detectGaps threw",thrown:r})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if(ke(this.sourceBuffer)||ke(this.playingRepresentationId))return;let e=[];for(let r=0;r<this.sourceBuffer.buffered.length;r++){let a=Math.floor(this.sourceBuffer.buffered.start(r)*1e3),s=Math.ceil(this.sourceBuffer.buffered.end(r)*1e3);e.push({from:a,to:s})}let t=10;for(let r of this.segments.values())for(let a of r){let{status:s}=a;if(s!=="fed"&&s!=="partially_ejected")continue;let n=Math.floor(a.time.from),o=Math.ceil(a.time.to),c=e.some(d=>d.from-t<=n&&d.to+t>=o),u=e.filter(d=>n>=d.from&&n<d.to-t||o>d.from+t&&o<=d.to);c||(u.length===1?a.status="partially_ejected":this.gaps.some(d=>d.from===a.time.from||d.to===a.time.to)?a.status="partially_ejected":a.status="none")}}};var Ni=i=>{let e=new URL(i);return e.searchParams.set("quic","1"),e.toString()};var wb=i=>{let e=i.get("X-Delivery-Type"),t=i.get("X-Reused"),r=e===null?"http1":e??void 0,a=t===null?void 0:{1:!0,0:!1}[t]??void 0;return{type:r,reused:a}};import{abortable as Fi,assertNever as Rb,fromEvent as $b,merge as Ck,now as qi,Subscription as Dk,ValueSubject as vu,flattenObject as Er}from"@vkontakte/videoplayer-shared";var ds=class{constructor({throughputEstimator:e,requestQuic:t,tracer:r,compatibilityMode:a=!1}){this.lastConnectionType$=new vu(void 0);this.lastConnectionReused$=new vu(void 0);this.lastRequestFirstBytes$=new vu(void 0);this.abortAllController=new Je;this.subscription=new Dk;this.fetchManifest=Fi(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),r=e;this.requestQuic&&(r=Ni(r));let a=yield Ke(r,{signal:this.abortAllController.signal}).catch(Ui);return a?(t.log("success",Er({url:r,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(a.headers),a.text()):(t.error("error",Er({url:r,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=Fi(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:r,onProgress:a,priority:s="auto",signal:n,measureThroughput:o=!0,isLowLatency:c=!1}={}){let u=e,d=new Headers,l=this.tracer.createComponentTracer("Fetch");if(r)switch(t){case 0:{d.append("Range",`bytes=${r.from}-${r.to}`);break}case 1:{let w=new URL(u,location.href);w.searchParams.append("bytes",`${r.from}-${r.to}`),u=w.toString();break}default:Rb(t)}this.requestQuic&&(u=Ni(u));let p=this.abortAllController.signal,h;if(n){let w=new Je;if(h=Ck($b(this.abortAllController.signal,"abort"),$b(n,"abort")).subscribe(()=>{try{w.abort()}catch($){Ui($)}}),this.abortAllController.signal.aborted||n.aborted)try{w.abort()}catch($){Ui($)}p=w.signal}let m=qi();l.log("startRequest",Er({url:u,priority:s,rangeMethod:t,range:r,isLowLatency:c,requestStartedAt:m}));let b=yield Ke(u,{priority:s,headers:d,signal:p}).catch(Ui),g=qi();if(!b)return l.error("error",{message:"No response in request"}),l.end(),h?.unsubscribe(),null;if(this.throughputEstimator?.addRawRtt(g-m),!b.ok||!b.body){h?.unsubscribe();let w=`Fetch error ${b.status}: ${b.statusText}`;return l.error("error",{message:w}),l.end(),Promise.reject(new Error(`Fetch error ${b.status}: ${b.statusText}`))}if(this.onHeadersReceived(b.headers),!a&&!o){h?.unsubscribe();let w=qi(),$={requestStartedAt:m,requestEndedAt:w,duration:w-m};return l.log("endRequest",Er($)),l.end(),b.arrayBuffer()}let[v,A]=b.body.tee(),y=v.getReader();o&&this.throughputEstimator?.trackStream(A,c);let S=0,T=new Uint8Array(0),E=!1,D=w=>{h?.unsubscribe(),E=!0,Ui(w)},O=Fi(p,async function*({done:w,value:$}){if(S===0&&this.lastRequestFirstBytes$.next(qi()-m),p.aborted){h?.unsubscribe();return}if(!w&&$){let q=new Uint8Array(T.length+$.length);q.set(T),q.set($,T.length),T=q,S+=$.byteLength,a?.(new DataView(T.buffer),S),yield y?.read().then(O,D)}}.bind(this));yield y?.read().then(O,D),h?.unsubscribe();let N=qi(),k={failed:E,requestStartedAt:m,requestEndedAt:N,duration:N-m};return E?(l.error("endRequest",Er(k)),l.end(),null):(l.log("endRequest",Er(k)),l.end(),T.buffer)}.bind(this));this.fetchByteRangeRepresentation=Fi(this.abortAllController.signal,async function*(e,t,r){if(e.type!=="byteRange")return null;let{from:a,to:s}=e.initRange,n=a,o=s,c=!1,u,d;e.indexRange&&(u=e.indexRange.from,d=e.indexRange.to,c=s+1===u,c&&(n=Math.min(u,a),o=Math.max(d,s))),n=Math.min(n,0);let l=yield this.fetch(e.url,{range:{from:n,to:o},priority:r,measureThroughput:!1});if(!l)return null;let p=new DataView(l,a-n,s-n+1);if(!t.validateData(p))throw new Error("Invalid media file");let h=t.parseInit(p),m=e.indexRange??t.getIndexRange(h);if(!m)throw new ReferenceError("No way to load representation index");let b;if(c)b=new DataView(l,m.from-n,m.to-m.from+1);else{let v=yield this.fetch(e.url,{range:m,priority:r,measureThroughput:!1});if(!v)return null;b=new DataView(v)}let g=t.parseSegments(b,h,m);return{init:h,dataView:new DataView(l),segments:g}}.bind(this));this.fetchTemplateRepresentation=Fi(this.abortAllController.signal,async function*(e,t){if(e.type!=="template")return null;let r=new URL(e.initUrl,e.baseUrl).toString(),a=yield this.fetch(r,{priority:t,measureThroughput:!1});return a?{init:null,segments:e.segments.map(n=>({...n,status:"none",size:void 0})),dataView:new DataView(a)}:null}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=a,this.tracer=r.createComponentTracer("Fetcher")}onHeadersReceived(e){let{type:t,reused:r}=wb(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(r)}async fetchRepresentation(e,t,r="auto"){let{type:a}=e;switch(a){case"byteRange":return await this.fetchByteRangeRepresentation(e,t,r)??null;case"template":return await this.fetchTemplateRepresentation(e,r)??null;default:Rb(a)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}},Ui=i=>{if(!Vi(i))throw i};var _t=(i,e,t)=>t*e+(1-t)*i,yu=(i,e)=>i.reduce((t,r)=>t+r,0)/e,Lb=(i,e,t,r)=>{let a=0,s=t,n=yu(i,e),o=e<r?e:r;for(let c=0;c<o;c++)i[s]>n?a++:a--,s=(i.length+s-1)%i.length;return Math.abs(a)===o};import{isNullable as Bk,ValueSubject as Mb}from"@vkontakte/videoplayer-shared";var dt=class{constructor(e){this.prevReported=void 0;this.pastMeasures=[];this.takenMeasures=0;this.measuresCursor=0;this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new Mb(e.initial),this.debounced$=new Mb(e.initial);let t=e.label??"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new X(`raw_${t}`),this.smoothedSeries$=new X(`smoothed_${t}`),this.reportedSeries$=new X(`reported_${t}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,r=0;for(let o=0;o<this.pastMeasures.length;o++)this.pastMeasures[o]!==void 0&&(t+=(this.pastMeasures[o]-this.smoothed)**2,r++);this.takenMeasures=r,t/=r;let a=Math.sqrt(t),s=this.smoothed+this.params.deviationFactor*a,n=this.smoothed-this.params.deviationFactor*a;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)&&(Bk(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 ps=class extends dt{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=_t(this.slow,e,this.params.emaAlphaSlow),this.fast=_t(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var hs=class extends dt{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=yu(this.pastMeasures,this.takenMeasures);this.emaSmoothed=_t(this.emaSmoothed,e,this.params.emaAlpha);let r=Lb(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=r?this.emaSmoothed:t}};var fs=class extends dt{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?_t(this.smoothed,t,this.params.emaAlpha):t}};var Nt=class{static getSmoothedValue(e,t,r){return r.type==="TwoEma"?new ps({initial:e,emaAlphaSlow:r.emaAlphaSlow,emaAlphaFast:r.emaAlphaFast,changeThreshold:r.changeThreshold,fastDirection:t,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"}):new hs({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 fs({initial:e,label:"liveEdgeDelay",...t})}};var Tu=(i,e)=>{i&&i.playbackRate!==e&&(i.playbackRate=e)};var _b=["timeupdate","progress","play","seeked","stalled","waiting"];var gs=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new Ob;this.representationSubscription=new Ob;this.state$=new L("none");this.currentVideoRepresentation$=new Z(void 0);this.currentVideoRepresentationInit$=new Z(void 0);this.currentAudioRepresentation$=new Z(void 0);this.currentVideoSegmentLength$=new Z(0);this.currentAudioSegmentLength$=new Z(0);this.error$=new Vb;this.lastConnectionType$=new Z(void 0);this.lastConnectionReused$=new Z(void 0);this.lastRequestFirstBytes$=new Z(void 0);this.isLive$=new Z(!1);this.liveDuration$=new Z(0);this.liveAvailabilityStartTime$=new Z(void 0);this.bufferLength$=new Z(0);this.liveLoadBufferLength$=new Z(0);this.livePositionFromPlayer$=new Z(0);this.timeInWaiting=0;this.isActiveLowLatency$=new Z(!1);this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.liveLastSeekOffset=0;this.forceEnded$=new Vb;this.gapWatchdogActive=!1;this.destroyController=new Je;this.initManifest=Iu(this.destroyController.signal,async function*(e,t,r){this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=K(t,r,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),this.manifest?.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:pt.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=Iu(this.destroyController.signal,async function*(){this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(n=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:pt.NETWORK,message:"Failed to load manifest",thrown:n})});if(!e)return null;let t;try{t=Eb(e??"",this.manifestUrlString)}catch(n){let o=Om(e)??{id:"ManifestParsing",category:pt.PARSER,message:"Failed to parse MPD manifest",thrown:n};this.error$.next(o)}if(!t)return null;let r=(n,o,c)=>!!(this.element?.canPlayType?.(o)&&Xe()?.isTypeSupported?.(`${o}; codecs="${c}"`)||n==="text");t.dynamic&&this.isLive$.getValue()!==t.dynamic&&(this.isLive$.next(t.dynamic),this.liveDuration$.getValue()!==t.duration&&this.liveDuration$.next(-1*(t.duration??0)/1e3),this.liveAvailabilityStartTime$.getValue()!==t.liveAvailabilityStartTime&&this.liveAvailabilityStartTime$.next(t.liveAvailabilityStartTime));let a={text:t.streams.text,video:[],audio:[]};for(let n of["video","audio"]){let c=t.streams[n].filter(({mime:l,codecs:p})=>r(n,l,p)),u=new Set(c.map(({codecs:l})=>l)),d=Vm(u);if(d&&(a[n]=c.filter(({codecs:l})=>l.startsWith(d))),n==="video"){let l=this.tuning.preferHDR,p=a.video.some(m=>m.hdr),h=a.video.some(m=>!m.hdr);Fk.isHDR&&l&&p?a.video=a.video.filter(m=>m.hdr):h&&(a.video=a.video.filter(m=>!m.hdr))}}let s={...t,streams:a};return this.tracer.log("updateManifestEnd",Hi(s)),s}.bind(this));this.initRepresentations=Iu(this.destroyController.signal,async function*(e,t,r){this.tracer.log("initRepresentationsStart",Hi({initialVideo:e,initialAudio:t,sourceHls:r})),Ft(this.manifest),Ft(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let a=l=>{this.representationSubscription.add(xr(l,"error").pipe(bs(p=>!!this.element?.played.length)).subscribe(p=>{this.error$.next({id:"VideoSource",category:pt.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:p})}))};this.source=this.tuning.useManagedMediaSource?wm():new MediaSource;let s=document.createElement("source");if(a(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),this.tuning.useManagedMediaSource&&as())if(r){let l=document.createElement("source");a(l),l.type="application/x-mpegurl",l.src=r.url,this.element.appendChild(l)}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((l,p)=>[...l,...p.representations],[]);if(this.videoBufferManager=new _i("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],Bb(t)){let l=this.manifest.streams.audio.reduce((p,h)=>[...p,...h.representations],[]);this.audioBufferManager=new _i("audio",this.source,l,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(Eu(1e3).subscribe(l=>{if(this.element?.paused){let p=Co(this.manifestUrlString,2);this.manifestUrlString=K(this.manifestUrlString,p+1e3,2)}})),this.representationSubscription.add(Pr(..._b.filter(l=>l!=="waiting").map(l=>xr(this.element,l))).pipe(xu(l=>this.element?ze(this.element.buffered,this.element.currentTime*1e3):0),Db(),bs(l=>!!l),_k(l=>{this.stallWatchdogSubscription?.unsubscribe(),this.timeInWaiting=0})).subscribe(this.bufferLength$)),this.isLive$.getValue()){this.representationSubscription.add(this.isActiveLowLatency$.pipe(Db()).subscribe(p=>Tu(this.element,1))),this.representationSubscription.add(ms({bufferLength:this.bufferLength$,isActiveLowLatency:this.isActiveLowLatency$}).pipe(bs(({bufferLength:p,isActiveLowLatency:h})=>h&&!!p)).subscribe(({bufferLength:p})=>this.liveEstimatedDelay.next(p))),this.representationSubscription.add(ms({liveEstimatedDelay:this.liveEstimatedDelay.smoothed$,isActiveLowLatency:this.isActiveLowLatency$}).subscribe(({liveEstimatedDelay:p,isActiveLowLatency:h})=>{if(!h)return;let m=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,b=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,g=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,v=p-m,A=1;Math.abs(v)>b&&(A=1+Math.sign(v)*g),Tu(this.element,A)})),this.representationSubscription.add(this.bufferLength$.subscribe(p=>{let h=0;if(p){let m=(this.element?.currentTime??0)*1e3;h=Math.min(...this.bufferManagers.map(g=>g.getLiveSegmentsToLoadState(this.manifest)?.to??m))-m}this.liveLoadBufferLength$.getValue()!==h&&this.liveLoadBufferLength$.next(h)}));let l=0;this.representationSubscription.add(ms({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(Nk(1e3)).subscribe(async({liveLoadBufferLength:p,bufferLength:h})=>{if(Ft(this.element),this.isUpdatingLive)return;let m=this.element.playbackRate,b=Co(this.manifestUrlString,2),g=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,v=Math.min(g,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*m),A=this.tuning.dashCmafLive.normalizedActualBufferOffset*m,y=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*m,S=isFinite(p)?p:h,T=this.isActiveLowLatency$.getValue(),E=g<=this.tuning.live.activeLiveDelay&&b===0;this.isActiveLowLatency$.next(T&&E);let D="none";if(T?D="active_low_latency":this.tuning.dashCmafLive.lowLatency.isActive&&E?(this.isActiveLowLatency$.next(!0),this.bufferManagers.forEach(O=>O.proceedLowLatencyLive()),D="active_low_latency"):b!==0&&S<v?D="live_forward_buffering":S<v+y&&(D="live_with_target_offset"),isFinite(p)&&(l=p>l?p:l),D==="live_forward_buffering"||D==="live_with_target_offset"){let O=l-(v+A),N=this.normolizeLiveOffset(Math.trunc(b+O/m)),k=Math.abs(N-b),w;!p||k<=this.tuning.dashCmafLive.offsetCalculationError?w=b:N>0&&k>this.tuning.dashCmafLive.offsetCalculationError?w=N:w=0,this.manifestUrlString=K(this.manifestUrlString,w,2)}D!=="none"&&D!=="active_low_latency"&&(l=0,this.updateLive())}))}let c=Pr(...this.bufferManagers.map(l=>l.fullyBuffered$)).pipe(xu(()=>this.bufferManagers.every(l=>l.fullyBuffered$.getValue()))),u=Pr(...this.bufferManagers.map(l=>l.onLastSegment$)).pipe(xu(()=>this.bufferManagers.some(l=>l.onLastSegment$.getValue())));this.representationSubscription.add(Pr(this.forceEnded$,ms({allBuffersFull:c,someBufferEnded:u}).pipe(bs(({allBuffersFull:l,someBufferEnded:p})=>l&&p))).subscribe(()=>{if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(l=>!l.updating))try{this.source?.endOfStream()}catch(l){this.error$.next({id:"EndOfStream",category:pt.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:l})}})),this.representationSubscription.add(Pr(...this.bufferManagers.map(l=>l.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(l=>this.source?.addEventListener("sourceopen",l)));let d=[this.manifest.duration??0,...[...this.manifest.streams.audio,...this.manifest.streams.video].flatMap(l=>l.representations).flatMap(l=>{let p=[];return l.duration&&p.push(l.duration),Ze(l.segmentReference)&&l.segmentReference.totalSegmentsDurationMs&&p.push(l.segmentReference.totalSegmentsDurationMs),p})];this.source.duration=Math.max(...d)/1e3,this.audioBufferManager&&Bb(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState("representations_ready"),this.tracer.log("initRepresentationsEnd")}.bind(this));this.tick=()=>{if(!this.element||!this.videoBufferManager)return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),this.audioBufferManager?.maintain(e),(this.videoBufferManager.gaps.length||this.audioBufferManager?.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=Eu(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),t=>{this.error$.next({id:"GapWatchdog",category:pt.WTF,message:"Error handling gaps",thrown:t})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name),this.fetcher=new ds({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer}),this.liveEstimatedDelay=Nt.getLiveEstimatedDelaySmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.delayEstimator}),this.initTracerSubscription()}async seekLive(e){Ft(this.element);let t=this.normolizeLiveOffset(e);this.isActiveLowLatency$.next(this.tuning.dashCmafLive.lowLatency.isActive&&t===0),this.liveLastSeekOffset=t,this.manifestUrlString=K(this.manifestUrlString,t,2),this.manifest=await this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,await this.videoBufferManager?.seekLive(this.manifest?.streams.video),await this.audioBufferManager?.seekLive(this.manifest?.streams.audio))}initBuffer(){Ft(this.element),this.state$.setState("running"),this.subscription.add(Pr(..._b.map(e=>xr(this.element,e)),xr(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:pt.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(xr(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(xr(this.element,"waiting").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&br(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{if(!this.element)return;this.timeInWaiting+=1e3;let t={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),t={...t,liveLastSeekOffset:this.liveLastSeekOffset};else{let r=this.element.currentTime*1e3;this.videoBufferManager?.maintain(r),this.audioBufferManager?.maintain(r),t={...t,position:r}}this.tracer.log("stallIntervalCallback",Hi(t))};this.videoBufferManager?.startAccumulateBuffer(),this.audioBufferManager?.startAccumulateBuffer(),this.stallWatchdogSubscription?.unsubscribe(),this.stallWatchdogSubscription=Eu(1e3).subscribe(e,t=>{this.error$.next({id:"StallWatchdogCallback",category:pt.FATAL,message:"Can't restore DASH after stall.",thrown:t})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t,r=!1){return{video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e]?.switchTo(t,r)}seek(e,t){Ft(this.element),Ft(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(this.videoBufferManager.findSegmentStartTime(e)??e,this.audioBufferManager?.findSegmentStartTime(e)??e),br(this.element.buffered,r)||(this.videoBufferManager.abort(),this.audioBufferManager?.abort()),this.videoBufferManager.startAccumulateBuffer(),this.videoBufferManager.maintain(r),this.audioBufferManager?.startAccumulateBuffer(),this.audioBufferManager?.maintain(r),this.element.currentTime=r/1e3,this.tracer.log("seek",Hi({requestedPosition:e,forcePrecise:t,position:r}))}stop(){this.tracer.log("stop"),this.element?.querySelectorAll("source").forEach(e=>e.remove()),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),this.videoBufferManager?.destroy(),this.videoBufferManager=null,this.audioBufferManager?.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getStreams(){return this.manifest?.streams}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),this.source?.readyState==="open"&&Array.from(this.source.sourceBuffers).every(e=>!e.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}initTracerSubscription(){let e=qk(this.tracer.error.bind(this.tracer));this.error$.subscribe(e("error"))}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}async updateLive(){this.isUpdatingLive=!0,this.manifest=await this.updateManifest(),this.manifest&&this.bufferManagers?.forEach(e=>e.updateLive(this.manifest)),this.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,a=[],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?a.push(1/0):a.push(o.to));if(a.length){let n=Math.max(...a)+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,n===1/0?this.forceEnded$.next():(this.element.currentTime=n/1e3,t={...t,gapEnds:a,jumpTo:n,resultCurrentTime:this.element.currentTime},this.tracer.log("jumpGap",Hi(t)))}}};var Ss=class{constructor(e,t){this.fov=e,this.orientation=t}};var vs=class{constructor(e,t){this.rotating=!1;this.fading=!1;this.lastTickTS=0;this.lastCameraTurnTS=0;this.fadeStartSpeed=null;this.fadeTime=0;this.camera=e,this.options=t,this.rotationSpeed={x:0,y:0,z:0},this.fadeCorrection=1/(this.options.speedFadeTime/1e3)**2}turnCamera(e=0,t=0,r=0){this.pointCameraTo(this.camera.orientation.x+e,this.camera.orientation.y+t,this.camera.orientation.z+r)}pointCameraTo(e=0,t=0,r=0){t=this.limitCameraRotationY(t);let a=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:a,y:s,z:n},this.lastCameraTurnTS=Date.now()}setRotationSpeed(e,t,r){this.rotationSpeed.x=e??this.rotationSpeed.x,this.rotationSpeed.y=t??this.rotationSpeed.y,this.rotationSpeed.z=r??this.rotationSpeed.z}startRotation(){this.rotating=!0}stopRotation(e=!1){e?(this.setRotationSpeed(0,0,0),this.fadeStartSpeed=null):this.startFading(this.rotationSpeed.x,this.rotationSpeed.y,this.rotationSpeed.z),this.rotating=!1}onCameraRelease(){if(this.lastCameraTurn&&this.lastCameraTurnTS){let e=Date.now()-this.lastCameraTurnTS;if(e<this.options.speedFadeThreshold){let t=(1-e/this.options.speedFadeThreshold)*this.options.rotationSpeedCorrection;this.startFading(this.lastCameraTurn.x*t,this.lastCameraTurn.y*t,this.lastCameraTurn.z*t)}}}startFading(e,t,r){this.setRotationSpeed(e,t,r),this.fadeStartSpeed={...this.rotationSpeed},this.fading=!0}stopFading(){this.fadeStartSpeed=null,this.fading=!0,this.fadeTime=0}limitCameraRotationY(e){return Math.max(-this.options.maxYawAngle,Math.min(e,this.options.maxYawAngle))}tick(e){if(!this.lastTickTS){this.lastTickTS=e,this.lastCameraTurnTS=Date.now();return}let t=e-this.lastTickTS,r=t/1e3;if(this.rotating)this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*r,this.rotationSpeed.y*this.options.rotationSpeedCorrection*r,this.rotationSpeed.z*this.options.rotationSpeedCorrection*r);else if(this.fading&&this.fadeStartSpeed){let a=-this.fadeCorrection*(this.fadeTime/1e3)**2+1;this.setRotationSpeed(this.fadeStartSpeed.x*a,this.fadeStartSpeed.y*a,this.fadeStartSpeed.z*a),a>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 Nb=`attribute vec2 a_vertex;
58
+ `}),h&&vm(a,c,h,o)};var Q=i=>new URL(i).hostname;import{assertNever as Am,assertNonNullable as km,combine as fA,debounce as mA,ErrorCategory as wm,filter as Rm,filterChanged as bA,isNonNullable as tu,map as ps,merge as $m,observableFrom as gA,once as SA,Subscription as vA,ValueSubject as ru,videoQualityToHeight as yA,videoSizeToQuality as TA}from"@vkontakte/videoplayer-shared";var Tm=i=>{if(i instanceof DOMException&&["Failed to load because no supported source was found.","The element has no supported sources."].includes(i.message))throw i;return!(i instanceof DOMException&&(i.code===20||i.name==="AbortError"))},pe=async i=>{let e=i.muted;try{await i.play()}catch(t){if(!Tm(t))return!1;if(e)return console.warn(t),!1;i.muted=!0;try{await i.play()}catch(r){return Tm(r)&&(i.muted=!1,console.warn(r)),!1}}return!0};import{isNonNullable as cs,isNullable as JP,assertNonNullable as gi}from"@vkontakte/videoplayer-shared";import{isNonNullable as Im,assertNonNullable as us,now as zP}from"@vkontakte/videoplayer-shared";function z(){return zP()}function Jo(i){return z()-i}function Xo(i){let e=i.split("/"),t=e.slice(0,e.length-1).join("/"),r=/^([a-z]+:)?\/\//i,a=n=>r.test(n);return{resolve:(n,o,c=!1)=>{a(n)||(n.startsWith("/")||(n="/"+n),n=t+n);let u=n.indexOf("?")>-1?"&":"?";return c&&(n+=u+"lowLat=1",u="&"),o&&(n+=u+"_rnd="+Math.floor(999999999*Math.random())),n}}}function Em(i,e,t){let r=(...a)=>{t.apply(null,a),i.removeEventListener(e,r)};i.addEventListener(e,r)}function Tr(i,e,t,r){let a=window.XMLHttpRequest,s,n,o,c=!1,u=0,d,l,p=!1,h="arraybuffer",m=7e3,b=2e3,g=()=>{if(c)return;us(d);let $=Jo(d),q;if($<b){q=b-$,setTimeout(g,q);return}b*=2,b>m&&(b=m),n&&n.abort(),n=new a,E()},v=$=>(s=$,R),k=$=>(l=$,R),y=()=>(h="json",R),S=()=>{if(!c){if(--u>=0){g(),r&&r();return}c=!0,l&&l(),t&&t()}},T=$=>(p=$,R),E=()=>{d=z(),n=new a,n.open("get",i);let $=0,q,Le=0,ie=()=>(us(d),Math.max(d,Math.max(q||0,Le||0)));if(s&&n.addEventListener("progress",x=>{let A=z();s.updateChunk&&x.loaded>$&&(s.updateChunk(ie(),x.loaded-$),$=x.loaded,q=A)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>S())),n.addEventListener("load",()=>{if(c)return;us(n);let x=n.status;if(x>=200&&x<300){if(n.response.byteLength&&s){let A=n.response.byteLength-$;A&&s.updateChunk&&s.updateChunk(ie(),A)}n.responseType==="json"&&!Object.values(n.response).length?S():(l&&l(),e(n.response))}else S()}),n.addEventListener("error",()=>{S()}),p){let x=()=>{us(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(Le=z(),n.removeEventListener("readystatechange",x))};n.addEventListener("readystatechange",x)}return n.responseType=h,n.send(),R},R={withBitrateReporting:v,withParallel:T,withJSONResponse:y,withRetryCount:$=>(u=$,R),withRetryInterval:($,q)=>(Im($)&&(b=$),Im(q)&&(m=q),R),withTimeout:$=>(o=$,R),withFinally:k,send:E,abort:()=>{n&&(n.abort(),n=void 0),c=!0,l&&l()}};return R}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,a=0;for(;this.intervals.length>0;){let s=this.intervals[0];if(s.end<=t)r+=s.end-s.start,a+=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 c=s.bytes*n/o;a+=c,s.start=t,s.bytes-=c}}}if(a>0&&r>0){let s=a*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(a)}/${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,a,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=a,this.logger=s}limitCompleteCount(){let e;for(;(e=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){let t=e[Math.floor(Math.random()*e.length)];this.logger(`Dropping completed request for url ${t}`,{type:"warn"}),delete this.completeRequests[t]}}_sendRequest(e,t){let r=z(),a=c=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=c,e._errorCB?e._errorCB(c):(this.limitCompleteCount(),this.completeRequests[t]=e)},s=c=>{e._complete=1,e._responseData=c,e._downloadTime=z()-r,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(c,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,()=>a("error"),o),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally(n),this.activeRequests[t]=e,e._request.send(),this.lastPrefetchStart=z()}_getParallelRequestCount(){return Math.min(this.MAX_PARALLEL_REQUESTS,this.averageSegmentDuration<3e3?3:2)}_getPrefetchDelay(){return Math.max(100,Math.min(5e3,this.averageSegmentDuration/3))}_canSendPending(){let e=this._getParallelRequestCount(),t=z();if(Object.keys(this.activeRequests).length>=e)return!1;let r=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),r>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),r),!1):!0}_sendPending(){for(;this._canSendPending();){let e=this.pendingQueue.pop();if(e){if(this.activeRequests[e]||this.completeRequests[e])continue;this.logger(`Submitting pending request url=${e}`),this._sendRequest({},e)}else return}}_removeFromActive(e){delete this.completeRequests[e],delete this.activeRequests[e]}abortAll(){Object.values(this.activeRequests).forEach(e=>{e&&e._request&&e._request.abort()}),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,r,a){let s={};return s.send=()=>{let n=this.activeRequests[e]||this.completeRequests[e];if(n)n._cb=t,n._errorCB=r,n._retryCB=a,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=a,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 ls=1e4,Zo=3;var XP=6e4,ZP=10,eA=1,tA=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=Xo(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=Xo(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",()=>{!!e.error&&!this.destroyed&&(t(`Video element error: ${e.error?.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,a;r!==0&&(a=t.buffered.start(r-1),t.currentTime<a&&(e("Fixup stall"),t.currentTime=a))}_selectQuality(e){let{videoElement:t}=this.params,r,a,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)?(!a||s.bitrate>a.bitrate)&&(a=s):(!r||r.bitrate>s.bitrate)&&(r=s));return a||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:a,playerCallback:s}=this.params;this.mediaSource=new window.MediaSource,r("setting video src"),a.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.videoPlayStarted=!1,a.addEventListener("canplay",()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});let n=()=>{Em(a,"progress",()=>{a.buffered.length?(a.currentTime=a.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(Zo,ls,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){let{logger:t,videoElement:r,playerCallback:a}=this.params,s=!1,n=null,o=null,c=null,u=null,d=!1,l=()=>{let S=s&&(!d||d===this.rep);return S||t("Not running!"),S},p=(S,T,E)=>{c&&c.abort(),c=Tr(this.urlResolver.resolve(S,!1),T,E,()=>this._retryCallback()).withTimeout(ls).withBitrateReporting(this.bitrateSwitcher).withRetryCount(Zo).withFinally(()=>{c=null}).send()},h=(S,T,E)=>{gi(this.filesFetcher),o?.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(S,!1),T,E,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},m=S=>{let T=r.playbackRate;r.playbackRate!==S&&(t(`Playback rate switch: ${T}=>${S}`),r.playbackRate=S)},b=S=>{this.lowLatency=S,t(`lowLatency changed to ${S}`),g()},g=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)m(1);else{let S=this._getBufferSizeSec();if(this.bufferStates.length<5){m(1);return}let E=z()-1e4,D=0;for(let N=0;N<this.bufferStates.length;N++){let w=this.bufferStates[N];S=Math.min(S,w.buf),w.ts<E&&D++}this.bufferStates.splice(0,D),t(`update playback rate; minBuffer=${S} drop=${D} jitter=${this.sourceJitter}`);let O=S-eA;this.sourceJitter>=0?O-=this.sourceJitter/2:this.sourceJitter-=1,O>3?m(1.15):O>1?m(1.1):O>.3?m(1.05):m(1)}},v=S=>{let T,E=()=>T&&T.start?T.start.length:0,D=x=>T.start[x]/1e3,O=x=>T.dur[x]/1e3,N=x=>T.fragIndex+x,w=(x,A)=>({chunkIdx:N(x),startTS:D(x),dur:O(x),discontinuity:A}),R=()=>{let x=0;if(T&&T.dur){let A=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,G=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,K=A;this.sourceJitter>1&&(K+=this.sourceJitter-1);let me=T.dur.length-1;for(;me>=0&&(K-=T.dur[me],!(K<=0));--me);x=Math.min(me,T.dur.length-1-G),x=Math.max(x,0)}return w(x,!0)},$=x=>{let A=E();if(!(A<=0)){if(cs(x)){for(let G=0;G<A;G++)if(D(G)>x)return w(G)}return R()}},q=x=>{let A=E(),G=x?x.chunkIdx+1:0,K=G-T.fragIndex;if(!(A<=0)){if(!x||K<0||K-A>ZP)return t(`Resync: offset=${K} bChunks=${A} chunk=`+JSON.stringify(x)),R();if(!(K>=A))return w(G-T.fragIndex,!1)}},Le=(x,A,G)=>{u&&u.abort(),u=Tr(this.urlResolver.resolve(x,!0,this.lowLatency),A,G,()=>this._retryCallback()).withTimeout(ls).withRetryCount(Zo).withFinally(()=>{u=null}).withJSONResponse().send()};return{seek:(x,A)=>{Le(S,G=>{if(!l())return;T=G;let K=!!T.lowLatency;K!==this.lowLatency&&b(K);let me=0;for(let Ue=0;Ue<T.dur.length;++Ue)me+=T.dur[Ue];me>0&&(gi(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(me/T.dur.length)),a({name:"index",zeroTime:T.zeroTime,shiftDuration:T.shiftDuration}),this.sourceJitter=T.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,T.jitter/1e3)):1,x($(A))},()=>this._handleNetworkError())},nextChunk:q}},k=()=>{s=!1,o&&o.abort(),c&&c.abort(),u&&u.abort(),gi(this.filesFetcher),this.filesFetcher.abortAll()};return d={start:S=>{let{videoElement:T,logger:E}=this.params,D=v(e.jidxUrl),O,N,w,R,$=0,q,Le,ie,x=()=>{q&&(clearTimeout(q),q=void 0);let B=Math.max(tA,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),W=$+B,ae=z(),Y=Math.min(1e4,W-ae);$=ae;let Me=()=>{u||l()&&D.seek(()=>{l()&&($=z(),A(),x())})};Y>0?q=window.setTimeout(()=>{this.paused?x():Me()},Y):Me()},A=()=>{let B;for(;B=D.nextChunk(R);)R=B,Jt(B);let W=D.nextChunk(w);if(W){if(w&&W.discontinuity){E("Detected discontinuity; restarting playback"),this.paused?x():(k(),this._initPlayerWith(e));return}Ue(W)}else x()},G=(B,W)=>{if(!l()||!this.sourceBuffer)return;let ae,Y,Me,dt=He=>{window.setTimeout(()=>{l()&&G(B,W)},He)};if(this.sourceBuffer.updating)E("Source buffer is updating; delaying appendBuffer"),dt(100);else{let He=z(),Ce=T.currentTime;!this.paused&&T.buffered.length>1&&Le===Ce&&He-ie>500&&(E("Stall suspected; trying to fix"),this._fixupStall()),Le!==Ce&&(Le=Ce,ie=He);let wt=this._getBufferSizeSec();if(wt>30)E(`Buffered ${wt} seconds; delaying appendBuffer`),dt(2e3);else try{this.sourceBuffer.appendBuffer(B),this.videoPlayStarted?(this.bufferStates.push({ts:He,buf:wt}),g(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),W&&W()}catch(Je){if(Je.name==="QuotaExceededError")E("QuotaExceededError; delaying appendBuffer"),Me=this.sourceBuffer.buffered.length,Me!==0&&(ae=this.sourceBuffer.buffered.start(0),Y=Ce,Y-ae>4&&this.sourceBuffer.remove(ae,Y-3)),dt(1e3);else throw Je}}},K=()=>{N&&O&&(E([`Appending chunk, sz=${N.byteLength}:`,JSON.stringify(w)]),G(N,function(){N=null,A()}))},me=B=>e.fragUrlTemplate.replace("%%id%%",B.chunkIdx),Ue=B=>{l()&&h(me(B),(W,ae)=>{if(l()){if(ae/=1e3,N=W,w=B,n=B.startTS,ae){let Y=Math.min(10,B.dur/ae);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*Y:Y}K()}},()=>this._handleNetworkError())},Jt=B=>{l()&&(gi(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(me(B),!1)))},kt=B=>{l()&&(e.cachedHeader=B,G(B,()=>{O=!0,K()}))};s=!0,D.seek(B=>{if(l()){if($=z(),!B){x();return}R=B,!JP(S)||B.startTS>S?Ue(B):(w=B,A())}},S),e.cachedHeader?kt(e.cachedHeader):p(e.headerUrl,kt,()=>this._handleNetworkError())},stop:k,getTimestampSec:()=>n},d}_switchToQuality(e){let{logger:t,playerCallback:r}=this.params,a;e.bitrate!==this.bitrate&&(this.rep&&(a=this.rep.getTimestampSec(),cs(a)&&(a+=.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(a),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=l=>{if(!this.autoQuality)return;let p,h,m;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&l<this.bitrate&&(h=this._getBufferSizeSec(),m=l/this.bitrate,h>10&&m>.8||h>15&&m>.5||h>20&&m>.3)){e(`Not switching: buffer=${Math.floor(h)}; bitrate=${this.bitrate}; newRate=${Math.floor(l)}`);return}p=this._selectQuality(l),p?this._switchToQuality(p):e(`Could not find quality by bitrate ${l}`)},s={updateChunk:(p,h)=>{let m=z();if(this.chunkRateEstimator.addInterval(p,m,h)){let g=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:h,duration:m-p,speed:g}),!0}},get:()=>{let p=this.chunkRateEstimator.getBitRate();return p?p*.85:0}},n=-1/0,o,c=!0,u=()=>{let l=s.get();if(l&&o&&this.autoQuality){if(c&&l>o&&Jo(n)<3e4)return;r(l)}c=this.autoQuality};return{updateChunk:(l,p)=>{let h=s.updateChunk(l,p);return h&&u(),h},notifySwitch:l=>{let p=z();l<o&&(n=p),o=l}}}_fetchManifest(e,t,r){this.manifestRequest=Tr(this.urlResolver.resolve(e,!0),t,r,()=>this._retryCallback()).withJSONResponse().withTimeout(ls).withRetryCount(this.params.config.manifestRetryMaxCount).withRetryInterval(this.params.config.manifestRetryInterval,this.params.config.manifestRetryMaxInterval).send().withFinally(()=>{this.manifestRequest=void 0})}_playVideoElement(){let{videoElement:e}=this.params;pe(e).then(t=>{t||(this.params.liveOffset.pause(),this.params.videoState.setState("paused"))})}_handleManifestUpdate(e){let{logger:t,playerCallback:r,videoElement:a}=this.params,s=n=>{let o=[];return n?.length?(n.forEach((c,u)=>{c.video&&a.canPlayType(c.codecs).replace(/no/,"")&&window.MediaSource.isTypeSupported(c.codecs)&&(c.index=u,o.push(c))}),o.sort(function(c,u){return c.video&&u.video?u.video.height-c.video.height:u.bitrate-c.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))},XP))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};import{debounce as rA,filter as xm,fromEvent as iA,interval as aA,isHigher as sA,isInvariantQuality as nA,isLower as oA,merge as uA,Subject as Pm,Subscription as cA}from"@vkontakte/videoplayer-shared";var eu=class{constructor(){this.onDroopedVideoFramesLimit$=new Pm;this.subscription=new cA;this.playing=!1;this.tracks=[];this.forceChecker$=new Pm;this.isForceCheckCounter=0;this.prevTotalVideoFrames=0;this.prevDroppedVideoFrames=0;this.limitCounts={};this.handleChangeVideoQuality=()=>{let e=this.tracks.find(({size:t})=>t?.height===this.video.videoHeight&&t?.width===this.video.videoWidth);e&&!nA(e.quality)&&this.onChangeQuality(e.quality)};this.checkDroppedFrames=()=>{let{totalVideoFrames:e,droppedVideoFrames:t}=this.video.getVideoPlaybackQuality(),r=e-this.prevTotalVideoFrames,a=t-this.prevDroppedVideoFrames,s=1-(r-a)/r;!isNaN(s)&&s>0&&this.log({message:`[dropped]. current dropped percent: ${s}, limit: ${this.droppedFramesChecker.percentLimit}`}),!isNaN(s)&&s>=this.droppedFramesChecker.percentLimit&&sA(this.currentQuality,this.droppedFramesChecker.minQualityBanLimit)&&(this.limitCounts[this.currentQuality]=(this.limitCounts[this.currentQuality]??0)+1,this.maxQualityLimit=this.getMaxQualityLimit(this.currentQuality),this.currentTimer&&window.clearTimeout(this.currentTimer),this.currentTimer=window.setTimeout(()=>this.maxQualityLimit=this.getMaxQualityLimit(),this.droppedFramesChecker.qualityUpWaitingTime),this.onDroopedVideoFramesLimitTrigger()),this.savePrevFrameCounts(e,t)}}connect(e){this.log=e.logger.createComponentLog("DroppedFramesManager"),this.video=e.video,this.isAuto=e.isAuto,this.tracks=e.tracks,this.droppedFramesChecker=e.droppedFramesChecker,this.subscription.add(e.playing$.subscribe(()=>this.playing=!0)),this.subscription.add(e.pause$.subscribe(()=>this.playing=!1)),this.isEnabled&&this.subscribe()}destroy(){this.currentTimer&&window.clearTimeout(this.currentTimer),this.subscription.unsubscribe()}get droppedVideoMaxQualityLimit(){return this.maxQualityLimit}subscribe(){this.subscription.add(iA(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=aA(this.droppedFramesChecker.checkTime).pipe(xm(()=>this.playing),xm(()=>{let a=!!this.isForceCheckCounter;return a&&(this.isForceCheckCounter-=1),!a})),t=this.forceChecker$.pipe(rA(this.droppedFramesChecker.checkTime)),r=uA(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){let t=Object.entries(this.limitCounts).filter(([,r])=>r>=this.droppedFramesChecker.countLimit).sort(([r],[a])=>oA(r,a)?-1:1)?.[0]?.[0];return e??t}get isEnabled(){return this.droppedFramesChecker.enabled&&this.isDroppedFramesCheckerSupport}get isDroppedFramesCheckerSupport(){return!!this.video&&typeof this.video.getVideoPlaybackQuality=="function"}savePrevFrameCounts(e,t){this.prevTotalVideoFrames=e,this.prevDroppedVideoFrames=t}},ds=eu;import{map as lA,Observable as dA}from"@vkontakte/videoplayer-shared";import{fromEvent as pA}from"@vkontakte/videoplayer-shared";var vi=()=>!!window.documentPictureInPicture?.window||!!document.pictureInPictureElement;var hA=(i,e)=>new dA(t=>{if(!window.IntersectionObserver)return;let r={root:null},a=new IntersectionObserver((n,o)=>{n.forEach(c=>t.next(c.isIntersecting||vi()))},{...r,...e});a.observe(i);let s=pA(document,"visibilitychange").pipe(lA(n=>!document.hidden||vi())).subscribe(n=>t.next(n));return()=>{a.unobserve(i),s.unsubscribe}}),ke=hA;var IA=["paused","playing","ready"],EA=["paused","playing","ready"],yi=class{constructor(e){this.subscription=new vA;this.videoState=new L("stopped");this.representations$=new ru([]);this.textTracksManager=new Ke;this.droppedFramesManager=new ds;this.maxSeekBackTime$=new ru(1/0);this.zeroTime$=new ru(void 0);this.liveOffset=new it;this._dashCb=e=>{switch(e.name){case"buffering":{let t=e.isBuffering;this.params.output.isBuffering$.next(t);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${e.type}`,category:wm.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{let t=e.manifest,r=[];for(let a of t){let s=a.name??a.index.toString(10),n=vt(a.name)??TA(a.video),o=a.bitrate/1e3,c={...a.video};if(!n)continue;let u={id:s,quality:n,bitrate:o,size:c};r.push({track:u,representation:a})}this.representations$.next(r),this.params.output.availableVideoTracks$.next(r.map(({track:a})=>a)),this.videoState.getTransition()?.to==="manifest_ready"&&this.videoState.setState("manifest_ready");break}case"qualitySwitch":{let t=e.quality,r=this.representations$.getValue().find(({representation:a})=>a===t)?.track;this.params.output.hostname$.next(new URL(t.headerUrl,this.params.source.url).hostname),tu(r)&&this.params.output.currentVideoTrack$.next(r);break}case"bandwidth":{let{size:t,duration:r}=e;this.params.dependencies.throughputEstimator.addRawSpeed(t,r);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(),a=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(EA.includes(e)&&(n||o)){this.prepare();return}if(a?.to!=="paused"&&s.state==="requested"&&IA.includes(e)){this.seek(s.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(J(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 c=a?.from;c&&c==="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 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.dash.reinit(J(this.params.source.url,c))}return;default:return Am(e)}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=a=>{e.output.error$.next({id:"DashLiveProvider",category:wm.WTF,message:"DashLiveProvider internal logic error",thrown:a})};$m(this.videoState.stateChangeStarted$.pipe(ps(a=>({transition:a,type:"start"}))),this.videoState.stateChangeEnded$.pipe(ps(a=>({transition:a,type:"end"})))).subscribe(({transition:a,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(a)}`})}),this.video=oe(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(Q(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);let r=le(this.video);this.subscription.add(this.representations$.pipe(ps(a=>a.map(({track:s})=>s)),Rm(a=>!!a.length),SA()).subscribe(a=>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:a}))),this.subscription.add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.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(bA(),ps(a=>-a/1e3)).subscribe(this.params.output.duration$)).add(fA({zeroTime:this.zeroTime$.pipe(Rm(tu)),position:r.timeUpdate$}).subscribe(({zeroTime:a,position:s})=>this.params.output.liveTime$.next(a+s*1e3),t)).add(Qe(this.video,this.params.desiredState.isLooped,t)).add(ce(this.video,this.params.desiredState.volume,r.volumeState$,t)).add(r.volumeState$.subscribe(this.params.output.volume$,t)).add(Pe(this.video,this.params.desiredState.playbackRate,r.playbackRateState$,t)).add(r.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(r.loadedMetadata$.subscribe(this.params.output.loadedMetadataEvent$)).add(r.playing$.subscribe(this.params.output.firstFrameEvent$)).add(r.canplay$.subscribe(this.params.output.canplay$)).add(r.inPiP$.subscribe(this.params.output.inPiP$)).add(r.inFullscreen$.subscribe(this.params.output.inFullscreen$)).add(ke(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:a}})=>{let s=a&&yA(a);this.dash.setMaxAutoQuality(s),this.params.output.autoVideoTrackLimits$.next({max:a})})).add(this.videoState.stateChangeEnded$.subscribe(a=>{switch(a.to){case"stopped":this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState("stopped");break;case"manifest_ready":case"ready":this.params.desiredState.playbackState.getTransition()?.to==="ready"&&this.params.desiredState.playbackState.setState("ready");break;case"paused":this.params.desiredState.playbackState.setState("paused");break;case"playing":this.params.desiredState.playbackState.setState("playing");break;default:return Am(a.to)}},t)).add($m(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,gA(["init"])).pipe(mA(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),ue(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(){let e=this.representations$.getValue(),t=this.params.desiredState.videoTrack.getTransition()?.to??this.params.desiredState.videoTrack.getState(),r=this.params.desiredState.autoVideoTrackSwitching.getTransition()?.to??this.params.desiredState.autoVideoTrackSwitching.getState(),a=!r&&tu(t)?t:yt(e.map(({track:u})=>u),{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=a?.id,n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.videoTrack.getState()?.id,c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(a&&(n||s!==o)&&this.setVideoTrack(a),c&&this.setAutoQuality(r),n||c||s!==o){let u=e.find(({track:d})=>d.id===s)?.representation;km(u,"Representations missing"),this.dash.startPlay(u,r)}}setVideoTrack(e){let t=this.representations$.getValue().find(({track:r})=>r.id===e.id)?.representation;km(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(),a=t==="paused"&&r==="paused",s=-e,n=s<=this.maxSeekBackTime$.getValue()?s:0;this.params.output.position$.next(e/1e3),this.dash.reinit(J(this.params.source.url,n)),a&&this.dash.pause(),this.liveOffset.resetTo(n,a)}};var Lm=yi;var st=(i,e)=>{let t=0;for(let r=0;r<i.length;r++){let a=i.start(r)*1e3,s=i.end(r)*1e3;a<=e&&e<=s&&(t=s)}return Math.max(t-e,0)};import{assertNever as zk,assertNonNullable as Kk,debounce as Jk,ErrorCategory as Lu,filter as Wb,filterChanged as Mu,fromEvent as Xk,isNonNullable as Zk,map as Yb,merge as Ms,observableFrom as ew,observeElementSize as tw,once as Qb,Subscription as rw,ValueSubject as iw}from"@vkontakte/videoplayer-shared";var hs=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 a=0,s=r.length;a<s;a++)if(r[a].callback===t){r.splice(a,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;let r=this.listeners[e.type].slice();for(let a=0,s=r.length;a<s;a++){let n=r[a];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 hs{constructor(){super(),this.listeners||hs.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{typeof document<"u"?document.createEvent?(t=document.createEvent("Event"),t.initEvent("abort",!1,!1)):(t=document.createEventObject(),t.type="abort"):t={type:"abort",bubbles:!1,cancelable:!1}}let r=e;if(r===void 0)if(typeof document>"u")r=new Error("This operation was aborted"),r.name="AbortError";else try{r=new DOMException("signal is aborted without reason")}catch{r=new Error("This operation was aborted"),r.name="AbortError"}this.signal.reason=r,this.signal.dispatchEvent(t)}toString(){return"[object AbortController]"}};typeof Symbol<"u"&&Symbol.toStringTag&&(Ti.prototype[Symbol.toStringTag]="AbortController",Ir.prototype[Symbol.toStringTag]="AbortSignal");function fs(i){return i.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof i.Request=="function"&&!i.Request.prototype.hasOwnProperty("signal")||!i.AbortController}function iu(i){typeof i=="function"&&(i={fetch:i});let{fetch:e,Request:t=e.Request,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:a=!1}=i;if(!fs({fetch:e,Request:t,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:a}))return{fetch:e,Request:s};let s=t;(s&&!s.prototype.hasOwnProperty("signal")||a)&&(s=function(u,d){let l;d&&d.signal&&(l=d.signal,delete d.signal);let p=new t(u,d);return l&&Object.defineProperty(p,"signal",{writable:!1,enumerable:!1,configurable:!0,value:l}),p},s.prototype=t.prototype);let n=e;return{fetch:(c,u)=>{let d=s&&s.prototype.isPrototypeOf(c)?c.signal:u?u.signal:void 0;if(d){let l;try{l=new DOMException("Aborted","AbortError")}catch{l=new Error("Aborted"),l.name="AbortError"}if(d.aborted)return Promise.reject(l);let p=new Promise((h,m)=>{d.addEventListener("abort",()=>m(l),{once:!0})});return u&&u.signal&&delete u.signal,Promise.race([p,n(c,u)])}return n(c,u)},Request:s}}var Ii=fs({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),Mm=Ii?iu({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,nt=Ii?Mm.fetch:window.fetch,s0=Ii?Mm.Request:window.Request,ot=Ii?Ti:window.AbortController,n0=Ii?Ir:window.AbortSignal;var Bm=We(pi(),1);var ut=()=>window.ManagedMediaSource||window.MediaSource,ms=()=>!!(window.ManagedMediaSource&&window.ManagedSourceBuffer?.prototype?.appendBuffer),Cm=()=>!!(window.MediaSource&&window.MediaStreamTrack&&window.SourceBuffer?.prototype?.appendBuffer),Dm=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;import{assertNever as vs,clientChecker as gs}from"@vkontakte/videoplayer-shared";var Ss=document.createElement("video"),AA='video/mp4; codecs="avc1.42000a,mp4a.40.2"',kA='video/mp4; codecs="hev1.1.6.L93.B0"',Vm='video/webm; codecs="vp09.00.10.08"',Om='video/webm; codecs="av01.0.00M.08"',wA='audio/mp4; codecs="mp4a.40.2"',RA='audio/webm; codecs="opus"',qt={mms:ms(),mse:Cm(),hls:!!(Ss.canPlayType?.("application/x-mpegurl")||Ss.canPlayType?.("vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},he={mp4:!!Ss.canPlayType?.("video/mp4"),webm:!!Ss.canPlayType?.("video/webm"),cmaf:!0},fe={h264:!!ut()?.isTypeSupported?.(AA),h265:!!ut()?.isTypeSupported?.(kA),vp9:!!ut()?.isTypeSupported?.(Vm),av1:!!ut()?.isTypeSupported?.(Om),aac:!!ut()?.isTypeSupported?.(wA),opus:!!ut()?.isTypeSupported?.(RA)},Er=(fe.h264||fe.h265)&&fe.aac,Ut,$A=async()=>{if(!window.navigator.mediaCapabilities)return;let i={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=await Promise.all([window.navigator.mediaCapabilities.decodingInfo({...i,video:{...i.video,contentType:Om}}),window.navigator.mediaCapabilities.decodingInfo({...i,video:{...i.video,contentType:Vm}})]);Ut={DASH_WEBM_AV1:e,DASH_WEBM:t}};try{$A()}catch(i){console.error(i)}var xr=qt.hls&&he.mp4,_m=()=>Object.keys(fe).filter(i=>fe[i]),Nm=(i,e=!1,t=!1)=>{let r=qt.mse||qt.mms&&t;return i.filter(a=>{switch(a){case"DASH_SEP":return r&&he.mp4&&Er;case"DASH_WEBM":return r&&he.webm&&fe.vp9&&fe.opus;case"DASH_WEBM_AV1":return r&&he.webm&&fe.av1&&fe.opus;case"DASH_STREAMS":return r&&(he.mp4&&Er||he.webm&&(fe.vp9||fe.av1)&&(fe.opus||fe.aac));case"DASH_LIVE":return qt.mse&&he.mp4&&Er;case"DASH_LIVE_CMAF":return r&&he.mp4&&Er&&he.cmaf;case"DASH_ONDEMAND":return r&&he.mp4&&Er;case"HLS":case"HLS_ONDEMAND":return xr||e&&qt.mse&&he.mp4&&Er;case"HLS_LIVE":case"HLS_LIVE_CMAF":return xr;case"MPEG":return he.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return qt.webrtc&&qt.ws&&fe.h264&&(he.mp4||he.webm);default:return vs(a)}})},bs=i=>{let e="DASH_WEBM",t="DASH_WEBM_AV1";switch(i){case"vp9":return[e,t];case"av1":return[t,e];case"none":return[];case"smooth":return Ut?Ut[t].smooth?[t,e]:Ut[e].smooth?[e,t]:[t,e]:[e,t];case"power_efficient":return Ut?Ut[t].powerEfficient?[t,e]:Ut[e].powerEfficient?[e,t]:[t,e]:[e,t];default:vs(i)}return[e,t]},Fm=({webmCodec:i,androidPreferredFormat:e,preferMultiStream:t})=>{let r=[...t?["DASH_STREAMS"]:[],...bs(i),"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]],a=[...t?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]];if(gs.isAndroid)switch(e){case"mpeg":return["MPEG",...r,"HLS","HLS_ONDEMAND"];case"hls":return["HLS","HLS_ONDEMAND",...r,"MPEG"];case"dash":return[...r,"HLS","HLS_ONDEMAND","MPEG"];case"dash_any_mpeg":return[...a,"MPEG",...bs(i),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...bs(i),"MPEG",...a,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...bs(i),...a,"HLS","HLS_ONDEMAND"];default:vs(e)}return xr?[...r,"HLS","HLS_ONDEMAND","MPEG"]:[...r,"HLS","HLS_ONDEMAND","MPEG"]},qm=({androidPreferredFormat:i,preferCMAF:e,preferWebRTC:t})=>{let r=e?["DASH_LIVE_CMAF","DASH_LIVE"]:["DASH_LIVE","DASH_LIVE_CMAF"],a=e?["HLS_LIVE_CMAF","HLS_LIVE"]:["HLS_LIVE","HLS_LIVE_CMAF"],s=[...r,...a],n=[...a,...r],o,c=gs.isMac&&gs.isSafari;if(gs.isAndroid)switch(i){case"dash":case"dash_any_mpeg":case"dash_any_webm":case"dash_sep":{o=s;break}case"hls":case"mpeg":{o=n;break}default:vs(i)}else xr&&!c?o=n:c?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"]},au=i=>i?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],Um=i=>{if(i.size!==0){if(i.size===1)return i.values().next().value.split(".").at(0);for(let e of i){let t=(0,Bm.default)(e.split("."),0);if(t==="opus"||t==="vp09"||t==="av01")return t}return i.values().next().value.split(".").at(0)}};import{ErrorCategory as Ei}from"@vkontakte/videoplayer-shared";var Hm=i=>{if(!i)return{id:"EmptyResponse",category:Ei.PARSER,message:"Empty response"};if(i.length<=2&&i.match(/^\d+$/))return{id:`UVError#${i}`,category:Ei.NETWORK,message:`UV Error ${i}`};let e=i.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(i,"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 Pr=(i,e)=>{for(let t=0;t<i.length;t++)if(i.start(t)*1e3<=e&&i.end(t)*1e3>e)return!0;return!1};import{abortable as wu,assertNonNullable as zt,combine as As,ErrorCategory as It,filter as ks,filterChanged as Nb,fromEvent as Cr,interval as Ru,isNonNullable as Fb,map as $u,merge as Dr,Subject as qb,Subscription as Ub,tap as qk,throttle as Uk,clientChecker as Hk,ValueSubject as X,flattenObject as Zi,getTraceSubscriptionMethod as jk}from"@vkontakte/videoplayer-shared";var Lr=We(pi(),1);var LA=(i,e={})=>{let r=e.timeout||1,a=performance.now();return window.setTimeout(()=>{i({get didTimeout(){return e.timeout?!1:performance.now()-a-1>r},timeRemaining(){return Math.max(0,1+(performance.now()-a))}})},1)},MA=i=>window.clearTimeout(i),jm=typeof window.requestIdleCallback!="function"||typeof window.cancelIdleCallback!="function",su=jm?LA:window.requestIdleCallback,y0=jm?MA:window.cancelIdleCallback;var Mb=We(as(),1);import{assertNever as CA,ErrorCategory as Gm,clientChecker as nu,Subject as Wm}from"@vkontakte/videoplayer-shared";var DA=16,Ym=!1;try{Ym=nu.isSafari&&!!nu.macVersion&&nu.macVersion<=DA}catch(i){console.error(i)}var ou=class{constructor(e){this.bufferFull$=new Wm;this.error$=new Wm;this.queue=[];this.currentTask=null;this.destroyed=!1;this.completeTask=()=>{try{if(this.currentTask){let e=this.currentTask.signal?.aborted;this.currentTask.callback(!e),this.currentTask=null}this.queue.length&&this.pull()}catch(e){this.error$.next({id:"BufferTaskQueueUnknown",category:Gm.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:e})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(r=>{let a={operation:"append",data:e,signal:t,callback:r};this.queue.push(a),this.pull()})}async remove(e,t,r){return r&&r.aborted?!1:new Promise(a=>{let s={operation:"remove",from:e,to:t,signal:r,callback:a};this.queue.unshift(s),this.pull()})}async abort(e){return new Promise(t=>{let r;Ym&&e?r={operation:"safariAbort",init:e,callback:t}:r={operation:"abort",callback:t};for(let{callback:a}of this.queue)a(!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(){if(this.buffer.updating||this.currentTask||this.destroyed)return;let e=this.queue.shift();if(!e)return;if(e.signal?.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(a){a instanceof DOMException&&a.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):a instanceof DOMException&&a.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:Gm.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:a}),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:CA(t)}}},Qm=ou;var uu=i=>{let e=0;for(let t=0;t<i.length;t++)e+=i.end(t)-i.start(t);return e*1e3};import{abortable as $r,assertNonNullable as Re,ErrorCategory as Wt,fromEvent as Iu,getExponentialDelay as Eu,isNonNullable as xu,isNullable as $e,once as Lk,Subject as Mk,Subscription as Ck,ValueSubject as Wi}from"@vkontakte/videoplayer-shared";var _=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 a=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,a),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 a=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,a}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 Ar=class extends _{};var xi=class extends _{};var Pi=class extends _{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 a=this.readString(4);this.compatibleBrands.push(a),r-=4}}};var Ai=class extends _{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ki=class extends _{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var wi=class extends _{constructor(e,t){super(e,t),this.data=this.content}};var j=class extends _{constructor(e,t){super(e,t);let r=this.readUint32();this.version=r>>>24,this.flags=r&16777215}};var Ht=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 a=this.readUint32(),s=a>>>31,n=a<<1>>>1,o=this.readUint32();a=this.readUint32();let c=a>>>28,u=a<<3>>>3;this.segments.push({referenceType:s,referencedSize:n,subsegmentDuration:o,SAPType:c,SAPDeltaTime:u})}}};var Ri=class extends _{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var $i=class extends _{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Li=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 Mi=class extends j{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var Ci=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 Di=class extends _{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 _{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Oi=class extends _{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var _i=class extends j{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var Ni=class extends _{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Fi=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 qi=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 Ui=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 a=0;a<this.sampleCount;a++)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 VA={ftyp:Pi,moov:Ai,moof:ki,mdat:wi,sidx:Ht,trak:Ri,mdia:Di,mfhd:_i,tkhd:Bi,traf:Ni,tfhd:Fi,tfdt:qi,trun:Ui,minf:Vi,sv3d:$i,st3d:Li,prhd:Mi,proj:Oi,equi:Ci,uuid:xi,unknown:Ar},jt=class i{constructor(e={}){this.options={offset:0,...e}}parse(e){let t=[],r=this.options.offset;for(;r<e.byteLength;)try{let s=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+r+4,4)),n=this.createBox(s,new DataView(e.buffer,e.byteOffset+r));if(!n.size)break;t.push(n),r+=n.size}catch{break}return t}createBox(e,t){let r=VA[e];return r?new r(t,new i):new Ar(t,new i)}};var kr=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{this.index[t.type]??=[],this.index[t.type].push(t),t.children.length>0&&this.indexBoxLevel(t.children)})}find(e){return this.index[e]&&this.index[e][0]?this.index[e][0]:null}findAll(e){return this.index[e]||[]}};var _A=new TextDecoder("ascii"),NA=i=>_A.decode(new DataView(i.buffer,i.byteOffset+4,4))==="ftyp",FA=i=>{let e=new Ht(i,new jt),t=e.earliestPresentationTime/e.timescale*1e3,r=i.byteOffset+i.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})},qA=(i,e)=>{let r=new jt().parse(i),a=new kr(r),s=a.findAll("moof"),n=e?a.findAll("uuid"):a.findAll("mdat");if(!(n.length&&s.length))return null;let o=s[0],c=n[n.length-1],u=o.source.byteOffset,l=c.source.byteOffset-o.source.byteOffset+c.size;return new DataView(i.buffer,u,l)},UA=(i,e)=>{let r=new jt().parse(i),s=new kr(r).findAll("traf"),n=s[s.length-1].children.find(l=>l.type==="tfhd"),o=s[s.length-1].children.find(l=>l.type==="tfdt"),c=s[s.length-1].children.find(l=>l.type==="trun"),u=0;return c.sampleDuration.length?u=c.sampleDuration.reduce((l,p)=>l+p,0):u=n.defaultSampleDuration*c.sampleCount,(Number(o.baseMediaDecodeTime)+u)/e*1e3},HA=i=>{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 jt().parse(i),a=new kr(r);if(a.find("sv3d")){e.is3dVideo=!0;let n=a.find("st3d");n&&(e.stereoMode=n.stereoMode);let o=a.find("prhd");o&&(e.projectionData.pose.yaw=o.poseYawDegrees,e.projectionData.pose.pitch=o.posePitchDegrees,e.projectionData.pose.roll=o.poseRollDegrees);let c=a.find("equi");c&&(e.projectionData.bounds.top=c.projectionBoundsTop,e.projectionData.bounds.right=c.projectionBoundsRight,e.projectionData.bounds.bottom=c.projectionBoundsBottom,e.projectionData.bounds.left=c.projectionBoundsLeft)}return e},zm={validateData:NA,parseInit:HA,getIndexRange:()=>{},parseSegments:FA,parseFeedableSegmentChunk:qA,getSegmentEndTime:UA};import{assertNonNullable as lu,isNonNullable as Zm,isNullable as GA}from"@vkontakte/videoplayer-shared";import{assertNever as jA}from"@vkontakte/videoplayer-shared";var Km={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"}},Jm=i=>{let e=i.getUint8(0),t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);let r=Hi(i,t),a=r in Km,s=a?Km[r].type:"binary",n=i.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 c=new DataView(i.buffer,i.byteOffset+t+1,o-1),u=n&255>>o,d=Hi(c),l=u*2**((o-1)*8)+d,p=t+o,h;return p+l>i.byteLength?h=new DataView(i.buffer,i.byteOffset+p):h=new DataView(i.buffer,i.byteOffset+p,l),{tag:a?r:"0x"+r.toString(16).toUpperCase(),type:s,tagHeaderSize:p,tagSize:p+l,value:h,valueSize:l}},Hi=(i,e=i.byteLength)=>{switch(e){case 1:return i.getUint8(0);case 2:return i.getUint16(0);case 3:return i.getUint8(0)*2**16+i.getUint16(1);case 4:return i.getUint32(0);case 5:return i.getUint8(0)*2**32+i.getUint32(1);case 6:return i.getUint16(0)*2**32+i.getUint32(2);case 7:{let t=i.getUint8(0)*281474976710656+i.getUint16(1)*4294967296+i.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},Fe=(i,e)=>{switch(e){case"int":return i.getInt8(0);case"uint":return Hi(i);case"float":return i.byteLength===4?i.getFloat32(0):i.getFloat64(0);case"string":return new TextDecoder("ascii").decode(i);case"utf8":return new TextDecoder("utf-8").decode(i);case"date":return new Date(Date.UTC(2001,0)+i.getInt8(0)).getTime();case"master":return i;case"binary":return i;default:jA(e)}},Gt=(i,e)=>{let t=0;for(;t<i.byteLength;){let r=new DataView(i.buffer,i.byteOffset+t),a=Jm(r);if(!e(a))return;a.type==="master"&&Gt(a.value,e),t=a.value.byteOffset-i.byteOffset+a.valueSize}},Xm=i=>{if(i.getUint32(0)!==440786851)return!1;let e,t,r,a=Jm(i);return Gt(a.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 eb=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],WA=[231,22612,22743,167,171,163,160,175],YA=i=>{let e,t,r,a,s=!1,n=!1,o=!1,c,u,d=!1,l=0;return Gt(i,({tag:p,type:h,value:m,valueSize:b})=>{if(p===21419){let g=Fe(m,h);u=Hi(g)}else p!==21420&&(u=void 0);return p===408125543?(e=m.byteOffset,t=m.byteOffset+b):p===357149030?s=!0:p===290298740?n=!0:p===2807729?r=Fe(m,h):p===17545?a=Fe(m,h):p===21420&&u===475249515?c=Fe(m,h):p===374648427?Gt(m,({tag:g,type:v,value:k})=>g===30321?(d=Fe(k,v)===1,!1):!0):s&&n&&eb.includes(p)&&(o=!0),!o}),lu(e,"Failed to parse webm Segment start"),lu(t,"Failed to parse webm Segment end"),lu(a,"Failed to parse webm Segment duration"),r=r??1e6,{segmentStart:Math.round(e/1e9*r*1e3),segmentEnd:Math.round(t/1e9*r*1e3),timeScale:r,segmentDuration:Math.round(a/1e9*r*1e3),cuesSeekPosition:c,is3dVideo:d,stereoMode:l,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},QA=i=>{if(GA(i.cuesSeekPosition))return;let e=i.segmentStart+i.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},zA=(i,e)=>{let t=!1,r=!1,a=o=>Zm(o.time)&&Zm(o.position),s=[],n;return Gt(i,({tag:o,type:c,value:u})=>{switch(o){case 475249515:t=!0;break;case 187:n&&a(n)&&s.push(n),n={};break;case 179:n&&(n.time=Fe(u,c));break;case 183:break;case 241:n&&(n.position=Fe(u,c));break;default:t&&eb.includes(o)&&(r=!0)}return!(t&&r)}),n&&a(n)&&s.push(n),s.map((o,c)=>{let{time:u,position:d}=o,l=s[c+1];return{status:"none",time:{from:u,to:l?l.time:e.segmentDuration},byte:{from:e.segmentStart+d,to:l?e.segmentStart+l.position-1:e.segmentEnd-1}}})},KA=i=>{let e=0,t=!1;try{Gt(i,r=>r.tag===524531317?r.tagSize<=i.byteLength?(e=r.tagSize,!1):(e+=r.tagHeaderSize,!0):WA.includes(r.tag)?(e+r.tagSize<=i.byteLength&&(e+=r.tagSize,t||=[163,160,175].includes(r.tag)),!0):!1)}catch{}return e>0&&e<=i.byteLength&&t?new DataView(i.buffer,i.byteOffset,e):null},tb={validateData:Xm,parseInit:YA,getIndexRange:QA,parseSegments:zA,parseFeedableSegmentChunk:KA};var wr=i=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(i);if(e){let[,t,r]=e;if(t==="audio"||t==="video")switch(r){case"webm":return tb;case"mp4":return zm}}throw new ReferenceError(`Unsupported mime type ${i}`)};var gu=We(Eb(),1);var bu=i=>{let e=i.split("."),[t,...r]=e;if(!t)return!1;switch(t){case"av01":{let[a,s,n]=r;return!!(n&&parseInt(n,10)>8)}case"vp09":{let[a,s,n]=r;return!!(a&&parseInt(a,10)>=2&&n&&parseInt(n,10)>8)}case"avc1":{let a=r[0];if(!a||a.length!==6)return!1;let[s,n]=a.toUpperCase(),o=s+n;return["6E","7A","F4"].includes(o)}}return!1};import{isNonNullable as Pb,isNullable as Ab}from"@vkontakte/videoplayer-shared";var xb=i=>{if(i.includes("/")){let e=i.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(i)};var kb=i=>{if(!i.startsWith("P"))return;let e=(n,o)=>{let c=n?parseFloat(n.replace(",",".")):NaN;return(isNaN(c)?0:c)*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(i),a=r?.[1]==="-"?-1:1,s={days:e(r?.[5],a),hours:e(r?.[6],a),minutes:e(r?.[7],a),seconds:e(r?.[8],a)};return s.days*24*60*60*1e3+s.hours*60*60*1e3+s.minutes*60*1e3+s.seconds*1e3},ct=(i,e)=>{let t=i;t=(0,gu.default)(t,"$$","$");let r={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[a,s]of Object.entries(r)){let n=new RegExp(`\\$${a}(?:%0(\\d+)d)?\\$`,"g");t=(0,gu.default)(t,n,(o,c)=>Ab(s)?o:Ab(c)?s:s.padStart(parseInt(c,10),"0"))}return t},wb=(i,e)=>{let r=new DOMParser().parseFromString(i,"application/xml"),a={video:[],audio:[],text:[]},s=r.children[0],n=s.getElementsByTagName("Period")[0],o=s.querySelector("BaseURL")?.textContent?.trim()??"",c=n.children,u=s.getAttribute("type")==="dynamic",d=s.getAttribute("availabilityStartTime"),l=d?new Date(d).getTime():void 0,p,h=s.getAttribute("mediaPresentationDuration"),m=n.getAttribute("duration"),g=s.getElementsByTagName("vk:Attrs")[0]?.getElementsByTagName("vk:XPlaybackDuration")[0].textContent;if(h)p=kb(h);else if(m){let S=kb(m);Pb(S)&&(p=S)}else g&&(p=parseInt(g,10));let v=0,k=s.getAttribute("profiles")?.split(",")??[];for(let S of c){let T=S.getAttribute("id")??"id"+(v++).toString(10),E=S.getAttribute("mimeType")??"",D=S.getAttribute("codecs")??"",O=S.getAttribute("contentType")??E?.split("/")[0],N=S.getAttribute("profiles")?.split(",")??[],w=S.getAttribute("lang")??void 0,R=S.querySelector("Label")?.textContent?.trim()??void 0,$=S.querySelectorAll("Representation"),q=S.querySelector("SegmentTemplate"),Le=S.querySelector("Role")?.getAttribute("value")??void 0,ie=O,x={id:T,language:w,isDefault:Le==="main",label:R,codecs:D,hdr:ie==="video"&&bu(D),mime:E,representations:[]};for(let A of $){let G=A.getAttribute("lang")??void 0,K=A.getAttribute("label")??void 0,me=A.querySelector("BaseURL")?.textContent?.trim()??"",Ue=new URL(me||o,e).toString(),Jt=A.getAttribute("mimeType")??E,kt=A.getAttribute("codecs")??D??"",B;if(O==="text"){let W=A.getAttribute("id")||"",ae=W.includes("_auto"),Y=A.querySelector("SegmentTemplate");if(!Y)throw new Error("Unknown MPD segment text referencing type");let Me={representationId:A.getAttribute("id")??void 0,bandwidth:A.getAttribute("bandwidth")??void 0},dt=parseInt(A.getAttribute("bandwidth")??"",10)/1e3,He=parseInt(Y.getAttribute("startNumber")??"",10)??1,Ce=parseInt(Y.getAttribute("timescale")??"",10),wt=Y.querySelectorAll("SegmentTimeline S")??[],Je=Y.getAttribute("media");if(!Je)throw new ReferenceError("No media attribute in SegmentTemplate");let ma=[],ba=0,ga="",Xt=0,Vr=He,Z=0;for(let De of wt){let Rt=parseInt(De.getAttribute("d")??"",10),Te=parseInt(De.getAttribute("r")??"",10)||0,pt=parseInt(De.getAttribute("t")??"",10);Z=Number.isFinite(pt)?pt:Z;let $t=Rt/Ce*1e3,Zt=Z/Ce*1e3;for(let je=0;je<Te+1;je++){let ht=ct(Je,{...Me,segmentNumber:Vr.toString(10),segmentTime:(Z+je*Rt).toString(10)}),er=(Zt??0)+je*$t,_r=er+$t;Vr++,ma.push({time:{from:er,to:_r},url:ht})}Z+=(Te+1)*Rt,ba+=(Te+1)*$t}Xt=Z/Ce*1e3,ga=ct(Je,{...Me,segmentNumber:Vr.toString(10),segmentTime:Z.toString(10)});let Or={time:{from:Xt,to:1/0},url:ga},Xe={type:"template",baseUrl:Ue,segmentTemplateUrl:Je,initUrl:"",totalSegmentsDurationMs:ba,segments:ma,nextSegmentBeyondManifest:Or,timescale:Ce};B={id:W,kind:"text",segmentReference:Xe,profiles:[],duration:p,bitrate:dt,mime:"",codecs:"",width:0,height:0,isAuto:ae}}else{let W=A.getAttribute("contentType")??Jt?.split("/")[0]??O,ae=S.getAttribute("profiles")?.split(",")??[],Y=parseInt(A.getAttribute("width")??"",10),Me=parseInt(A.getAttribute("height")??"",10),dt=parseInt(A.getAttribute("bandwidth")??"",10)/1e3,He=A.getAttribute("frameRate")??"",Ce=A.getAttribute("quality")??void 0,wt=He?xb(He):void 0,Je=A.getAttribute("id")??"id"+(v++).toString(10),ma=W==="video"?`${Me}p`:W==="audio"?`${dt}Kbps`:kt,ba=`${Je}@${ma}`,ga=[...k,...N,...ae],Xt,Vr=A.querySelector("SegmentBase"),Z=A.querySelector("SegmentTemplate")??q;if(Vr){let Xe=A.querySelector("SegmentBase Initialization")?.getAttribute("range")??"",[De,Rt]=Xe.split("-").map(ht=>parseInt(ht,10)),Te={from:De,to:Rt},pt=A.querySelector("SegmentBase")?.getAttribute("indexRange"),[$t,Zt]=pt?pt.split("-").map(ht=>parseInt(ht,10)):[],je=pt?{from:$t,to:Zt}:void 0;Xt={type:"byteRange",url:Ue,initRange:Te,indexRange:je}}else if(Z){let Xe={representationId:A.getAttribute("id")??void 0,bandwidth:A.getAttribute("bandwidth")??void 0},De=parseInt(Z.getAttribute("timescale")??"",10),Rt=Z.getAttribute("initialization")??"",Te=Z.getAttribute("media"),pt=parseInt(Z.getAttribute("startNumber")??"",10)??1,$t=ct(Rt,Xe);if(!Te)throw new ReferenceError("No media attribute in SegmentTemplate");let Zt=Z.querySelectorAll("SegmentTimeline S")??[],je=[],ht=0,er="",_r=0;if(Zt.length){let Sa=pt,Be=0;for(let tr of Zt){let Ge=parseInt(tr.getAttribute("d")??"",10),Lt=parseInt(tr.getAttribute("r")??"",10)||0,va=parseInt(tr.getAttribute("t")??"",10);Be=Number.isFinite(va)?va:Be;let Ys=Ge/De*1e3,Fg=Be/De*1e3;for(let ya=0;ya<Lt+1;ya++){let qg=ct(Te,{...Xe,segmentNumber:Sa.toString(10),segmentTime:(Be+ya*Ge).toString(10)}),Qu=(Fg??0)+ya*Ys,Ug=Qu+Ys;Sa++,je.push({time:{from:Qu,to:Ug},url:qg})}Be+=(Lt+1)*Ge,ht+=(Lt+1)*Ys}_r=Be/De*1e3,er=ct(Te,{...Xe,segmentNumber:Sa.toString(10),segmentTime:Be.toString(10)})}else if(Pb(p)){let Be=parseInt(Z.getAttribute("duration")??"",10)/De*1e3,tr=Math.ceil(p/Be),Ge=0;for(let Lt=1;Lt<tr;Lt++){let va=ct(Te,{...Xe,segmentNumber:Lt.toString(10),segmentTime:Ge.toString(10)});je.push({time:{from:Ge,to:Ge+Be},url:va}),Ge+=Be}_r=Ge,er=ct(Te,{...Xe,segmentNumber:tr.toString(10),segmentTime:Ge.toString(10)})}let Ng={time:{from:_r,to:1/0},url:er};Xt={type:"template",baseUrl:Ue,segmentTemplateUrl:Te,initUrl:$t,totalSegmentsDurationMs:ht,segments:je,nextSegmentBeyondManifest:Ng,timescale:De}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!W||!Jt)continue;let Or={video:"video",audio:"audio",text:"text"}[W];if(!Or)continue;ie||=Or,B={id:ba,kind:Or,segmentReference:Xt,profiles:ga,duration:p,bitrate:dt,mime:Jt,codecs:kt,width:Y,height:Me,fps:wt,quality:Ce}}x.language||=G,x.label||=K,x.mime||=Jt,x.codecs||=kt,x.hdr||=ie==="video"&&bu(kt),x.representations.push(B)}ie&&a[ie].push(x)}return{dynamic:u,liveAvailabilityStartTime:l,duration:p,streams:a}};var ji=We(pi(),1);import{videoSizeToQuality as $k}from"@vkontakte/videoplayer-shared";var Rb=({id:i,width:e,height:t,bitrate:r,fps:a,quality:s})=>{let n=(s?vt(s):void 0)??$k({width:e,height:t});return n&&{id:i,quality:n,bitrate:r,size:{width:e,height:t},fps:a}},$b=({id:i,bitrate:e})=>({id:i,bitrate:e}),ys=(i,e,t)=>{let r=e.indexOf(i);return(0,ji.default)(t,Math.round(t.length*r/e.length))??(0,ji.default)(t,-1)},Lb=({language:i,label:e,id:t,url:r,isAuto:a})=>({id:t,url:r,isAuto:a,type:"internal",language:i,label:e}),yu=({id:i,language:e,label:t,codecs:r,isDefault:a})=>({id:i,language:e,label:t,codec:(0,ji.default)(r.split("."),0),isDefault:a}),Tu=({id:i,language:e,label:t,hdr:r,codecs:a})=>({id:i,language:e,hdr:r,label:t,codec:(0,ji.default)(a.split("."),0)}),Ts=i=>"url"in i,we=i=>i.type==="template",Gi=i=>i instanceof DOMException&&(i.name==="AbortError"||i.code===20);var Yi=class{constructor(e,t,r,{fetcher:a,tuning:s,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:c=!1,manifest:u}){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 Mk;this.gaps=[];this.subscription=new Ck;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new ot;this.destroyAbortController=new ot;this.bufferLimit=1/0;this.failedDownloads=0;this.isLive=!1;this.liveUpdateSegmentIndex=0;this.liveInitialAdditionalOffset=0;this.isSeekingLive=!1;this.index=0;this.loadByteRangeSegmentsTimeoutId=0;this.startWith=$r(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);Re(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new Qm(this.sourceBuffer),this.subscription.add(Iu(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let o,c=this.mediaSource.readyState;c!=="open"&&(o={id:`SegmentEjection_source_${c}`,category:Wt.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o??={id:"SegmentEjection",category:Wt.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n},this.error$.next(o)})),this.subscription.add(Iu(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:Wt.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 c=Math.min(this.bufferLimit,uu(this.sourceBuffer.buffered)*.8);if(this.bufferLimit=c,this.tuning.useNewPruneBufferStrategy){let u=st(this.sourceBuffer.buffered,o),d=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBufferNew(o,n*2,u<d)}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),a=this.segments.get(t.id),s=this.parsedInitData.get(t.id);Re(r,"No init buffer for starting representation"),Re(a,"No segments for starting representation"),r instanceof ArrayBuffer&&(this.searchGaps(a,t),yield this.sourceBufferTaskQueue.append(r,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(s))}.bind(this));this.switchTo=$r(this.destroyAbortController.signal,async function*(e,t=!1){if(e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let r=this.representations.get(e);Re(r,`No such representation ${e}`);let a=this.segments.get(e),s=this.initData.get(e);if($e(s)||$e(a)?yield this.loadInit(r,"high",!1):s instanceof Promise&&(yield s),a=this.segments.get(e),Re(a,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer))if(this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer(),this.maintain();else{let n=this.getCurrentPosition();xu(n)&&(this.isLive||(this.tuning.useNewPruneBufferStrategy&&(this.bufferLimit=1/0),await this.pruneBuffer(n,1/0,!0)),this.maintain(n)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}}.bind(this));this.seekLive=$r(this.destroyAbortController.signal,async function*(e){let t=e?.flatMap(c=>c.representations)??[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let c of this.representations.keys()){let u=t.find(p=>p.id===c);u&&this.representations.set(c,u);let d=this.representations.get(c);if(!d||!we(d.segmentReference))return;let l=this.getActualLiveStartingSegments(d.segmentReference);this.segments.set(d.id,l)}let r=this.switchingToRepresentationId??this.downloadingRepresentationId,a=this.representations.get(r);Re(a);let s=this.segments.get(r);Re(s,"No segments for starting representation");let n=this.initData.get(r);if(Re(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,a),yield this.sourceBufferTaskQueue.append(n,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this));this.fetcher=a,this.tuning=s,this.compatibilityMode=c,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=o,this.isLive=!!u?.dynamic,this.resetAccumulateBufferAfterStall(),this.startAccumulateBuffer(),this.initData=new Map(r.map(d=>[d.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(r.map(d=>[d.id,d])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}abort(){for(let e of this.activeSegments)this.abortSegment(e.segment);this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new ot,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if($e(e)||$e(this.downloadingRepresentationId)||$e(this.playingRepresentationId)||$e(this.sourceBuffer)||!$e(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),r=this.segments.get(this.downloadingRepresentationId);if(Re(t,`No such representation ${this.downloadingRepresentationId}`),!r)return;let a=r.find(u=>e>=u.time.from&&e<u.time.to);this.currentSegmentLength$.next((a?.time.to??0)-(a?.time.from??0));let s=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){let d=st(this.sourceBuffer.buffered,e),l=a?a.time.to+100:-1/0;a&&a.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&d>=a.time.to-e+100&&(s=l)}if(isFinite(this.bufferLimit)&&uu(this.sourceBuffer.buffered)>=this.bufferLimit){let u=st(this.sourceBuffer.buffered,e),d=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,u<d);return}let o=[];if(!this.activeSegments.size&&(o=this.selectForwardBufferSegments(r,t.segmentReference.type,s),o.length)){let u="auto";if(this.tuning.dash.useFetchPriorityHints&&a)if(o.includes(a))u="high";else{let d=(0,Lr.default)(o,0);d&&d.time.from-a.time.to>=this.forwardBufferTarget/2&&(u="low")}this.loadSegments(o,t,u)}(!this.preloadOnly&&!this.allInitsLoaded&&a&&a.status==="fed"&&!o.length&&st(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let c=(0,Lr.default)(r,-1);c&&c.status==="fed"&&(this.fullyBuffered$.next(!0),this.isLive||this.onLastSegment$.next(a===c))}searchGaps(e,t){this.gaps=[];let r=0,a=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+a}),r=s.time.to;xu(t.duration)&&t.duration-r>0&&this.gaps.push({representation:t.id,from:r,to:t.duration})}getActualLiveStartingSegments(e){let t=e.segments,r=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,a=[],s=0,n=t.length-1;do a.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()?[a[0]]:a}getLiveSegmentsToLoadState(e){let t=e?.streams[this.kind].flatMap(a=>a.representations).find(a=>a.id===this.downloadingRepresentationId);if(!t)return;let r=this.segments.get(t.id);if(r?.length)return{from:r[0].time.from,to:r[r.length-1].time.to}}updateLive(e){let t=e?.streams[this.kind].flatMap(r=>r.representations)??[];for(let r of t){if(!r||!we(r.segmentReference))return;let a=r.segmentReference.segments.map(c=>({...c,status:"none",size:void 0})),s=this.segments.get(r.id)??[],n=(0,Lr.default)(s,-1)?.time.to??0,o=a?.findIndex(c=>Math.floor(n)>=Math.floor(c.time.from)&&Math.floor(n)<=Math.floor(c.time.to));if(o===-1){this.liveUpdateSegmentIndex=0;let c=this.getActualLiveStartingSegments(r.segmentReference);this.segments.set(r.id,c)}else{let c=a.slice(o+1);this.segments.set(r.id,[...s,...c])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;Re(e);let t=this.segments.get(e);if(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){for(let t of this.representations.values()){let r=t.segmentReference;if(!we(r))return;let a=this.segments.get(t.id)??[],s=a.find(o=>Math.floor(o.time.from)===Math.floor(e.time.from));if(s&&!isFinite(s.time.to)&&(s.time.to=e.time.to),!!!a.find(o=>Math.floor(o.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let o=Math.round(e.time.to*r.timescale/1e3).toString(10),c=ct(r.segmentTemplateUrl,{segmentTime:o});a.push({status:"none",time:{from:e.time.to,to:1/0},url:c})}}}findSegmentStartTime(e){let t=this.switchingToRepresentationId??this.downloadingRepresentationId??this.playingRepresentationId;if(!t)return;let r=this.segments.get(t);return r?r.find(s=>s.time.from<=e&&s.time.to>=e)?.time.from??void 0:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),this.sourceBufferTaskQueue?.destroy(),this.gapDetectionIdleCallback&&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(e){if(!(e instanceof DOMException&&e.name==="NotFoundError"))throw e}}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(a=>t>=a.time.from&&t<a.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=r),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,r){let a=e.findIndex(({status:l,time:{from:p,to:h}},m)=>{let b=p<=r&&h>=r,g=p>r||b||m===0&&r===0,v=Math.min(this.forwardBufferTarget,this.bufferLimit),k=this.preloadOnly&&p<=r+v||h<=r+v;return(l==="none"||l==="partially_ejected"&&g&&k&&this.sourceBuffer&&!(Pr(this.sourceBuffer.buffered,p)&&Pr(this.sourceBuffer.buffered,h)))&&g&&k});if(a===-1)return[];if(t!=="byteRange")return e.slice(a,a+1);let s=e,n=0,o=0,c=[],u=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,d=this.preloadOnly?this.forwardBufferTarget:0;for(let l=a;l<s.length&&(n<=u||o<=d);l++){let p=s[l];if(n+=p.byte.to+1-p.byte.from,o+=p.time.to+1-p.time.from,p.status==="none"||p.status==="partially_ejected")c.push(p);else break}return c}async loadSegments(e,t,r="auto"){we(t.segmentReference)?await this.loadTemplateSegment(e[0],t,r):await this.loadByteRangeSegments(e,t,r)}async loadTemplateSegment(e,t,r="auto"){e.status="downloading";let a={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(a);let{range:s,url:n,signal:o,onProgress:c,onProgressTasks:u}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(await $r(o,async function*(){let d=Eu(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>setTimeout(l,d))}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let d=await this.fetcher.fetch(n,{range:s,signal:o,onProgress:c,priority:r,isLowLatency:this.isActiveLowLatency()});if(!d)return;let l=new DataView(d);if(!isFinite(a.segment.time.to)){let p=t.segmentReference.timescale,h=wr(t.mime);a.segment.time.to=h.getSegmentEndTime(l,p)}c&&a.feedingBytes&&u?await Promise.all(u):await this.sourceBufferTaskQueue.append(l,o),a.segment.status="downloaded",this.onSegmentFullyAppended(a,t.id),this.failedDownloads=0}catch(d){this.abortActiveSegments([e]),Gi(d)||this.failedDownloads++}}async loadByteRangeSegments(e,t,r="auto"){if(!e.length)return;for(let c of e)c.status="downloading",this.activeSegments.add({segment:c,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:a,url:s,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(await $r(n,async function*(){let c=Eu(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(u,c),Iu(window,"online").pipe(Lk()).subscribe(()=>{u(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(s,{range:a,onProgress:o,signal:n,priority:r}),this.failedDownloads=0}catch(c){this.abortActiveSegments(e),Gi(c)||this.failedDownloads++}}prepareByteRangeFetchSegmentParams(e,t){if(we(t.segmentReference))throw new Error("Representation is not byte range type");let r=t.segmentReference.url,a={from:(0,Lr.default)(e,0).byte.from,to:(0,Lr.default)(e,-1).byte.to},{signal:s}=this.downloadAbortController;return{url:r,range:a,signal:s,onProgress:(o,c)=>{if(!s.aborted)try{this.onSomeByteRangesDataLoaded({dataView:o,loaded:c,signal:s,onSegmentAppendFailed:()=>this.abort(),globalFrom:a?a.from:0,representationId:t.id})}catch(u){this.error$.next({id:"SegmentFeeding",category:Wt.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:u})}}}}prepareTemplateFetchSegmentParams(e,t){if(!we(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 a=r.toString(),{signal:s}=this.downloadAbortController,n=[],c=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(u,d)=>{if(!s.aborted)try{let l=this.onSomeTemplateDataLoaded({dataView:u,loaded:d,signal:s,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(l)}catch(l){this.error$.next({id:"SegmentFeeding",category:Wt.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}:void 0;return{url:a,signal:s,onProgress:c,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)e.includes(t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:r,onSegmentAppendFailed:a,signal:s}){if(!this.activeSegments.size)return;let n=this.representations.get(t);if(n)for(let o of this.activeSegments){let{segment:c}=o;if(o.representationId===t){if(s.aborted){a();continue}if(o.loadedBytes=r,o.loadedBytes>o.feedingBytes){let u=new DataView(e.buffer,e.byteOffset+o.feedingBytes,o.loadedBytes-o.feedingBytes),d=wr(n.mime).parseFeedableSegmentChunk(u,this.isLive);d?.byteLength&&(c.status="partially_fed",o.feedingBytes+=d.byteLength,await this.sourceBufferTaskQueue.append(d),o.fedBytes+=d.byteLength)}}}}onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:r,loaded:a,signal:s,onSegmentAppendFailed:n}){let o={dataView:e,representationId:t,globalFrom:r,loaded:a,signal:s,onSegmentAppendFailed:n};return this.tuning.useNewPartialSegmentFeeding?this.onSomeByteRangesDataLoadedNew(o):this.onSomeByteRangesDataLoadedOld(o)}onSomeByteRangesDataLoadedOld({dataView:e,representationId:t,globalFrom:r,loaded:a,signal:s,onSegmentAppendFailed:n}){if(!this.activeSegments.size)return;let o=this.representations.get(t);if(!o)return;let c=o.segmentReference.type,u=e.byteLength;for(let d of this.activeSegments){let{segment:l}=d,p=c==="byteRange",h=p?l.byte.to-l.byte.from+1:u;if(d.representationId!==t||!(!p||l.byte.from>=r&&l.byte.to<r+e.byteLength))continue;if(s.aborted){n();continue}let b=p?l.byte.from-r:0,g=p?l.byte.to-r:e.byteLength,v=b<a,k=g<=a;if(l.status==="downloading"&&v&&k){l.status="downloaded";let y=new DataView(e.buffer,e.byteOffset+b,h),S=this.getCurrentPosition();xu(S)&&(this.bufferAccumulation.accumulatedBufferSizeMs=l.time.to-S,this.bufferAccumulation.accumulated.push({segmentView:y,segmentProgress:d}),this.activeSegments.delete(d));let T=({segmentView:E,segmentProgress:D})=>this.sourceBufferTaskQueue.append(E,s).then(O=>O&&!s.aborted?this.onSegmentFullyAppended(D,t):n());this.bufferAccumulation.enabled&&this.bufferAccumulation.targetBufferSizeMs<this.bufferAccumulation.accumulatedBufferSizeMs?(this.bufferAccumulation.accumulated.forEach(T),this.resetAccumulateBufferAfterStall()):(!this.bufferAccumulation.enabled||!this.bufferAccumulation.targetBufferSizeMs||$e(S))&&(T({segmentView:y,segmentProgress:d}),this.resetAccumulateBufferAfterStall())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&v&&!k&&(d.loadedBytes=Math.min(h,a-b),d.loadedBytes>d.feedingBytes)){let y=new DataView(e.buffer,e.byteOffset+b+d.feedingBytes,d.loadedBytes-d.feedingBytes),S=d.loadedBytes===h?y:wr(o.mime).parseFeedableSegmentChunk(y);S?.byteLength&&(l.status="partially_fed",d.feedingBytes+=S.byteLength,this.sourceBufferTaskQueue.append(S,s).then(T=>{if(s.aborted)n();else if(T)d.fedBytes+=S.byteLength,d.fedBytes===h&&this.onSegmentFullyAppended(d,t);else{if(d.feedingBytes<h)return;n()}}))}}}async onSomeByteRangesDataLoadedNew({dataView:e,representationId:t,globalFrom:r,loaded:a,signal:s,onSegmentAppendFailed:n}){if(!this.activeSegments.size)return;let o=this.representations.get(t);if(o)for(let c of this.activeSegments){let{segment:u}=c;if(c.representationId!==t)continue;if(s.aborted){n();continue}let d=u.byte.from-r,l=u.byte.to-r,p=l-d+1,h=d<a,m=l<=a;if(h){if(u.status==="downloading"&&m){u.status="downloaded";let b=new DataView(e.buffer,e.byteOffset+d,p);await this.sourceBufferTaskQueue.append(b,s)&&!s.aborted?this.onSegmentFullyAppended(c,t):n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(u.status==="downloading"||u.status==="partially_fed")&&(c.loadedBytes=Math.min(p,a-d),c.loadedBytes>c.feedingBytes)){let b=new DataView(e.buffer,e.byteOffset+d+c.feedingBytes,c.loadedBytes-c.feedingBytes),g=c.loadedBytes===p?b:wr(o.mime).parseFeedableSegmentChunk(b);g?.byteLength&&(u.status="partially_fed",c.feedingBytes+=g.byteLength,await this.sourceBufferTaskQueue.append(g,s)&&!s.aborted?(c.fedBytes+=g.byteLength,c.fedBytes===p&&this.onSegmentFullyAppended(c,t)):n())}}}}onSegmentFullyAppended(e,t){this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status="fed",Ts(e.segment)&&(e.segment.size=e.fedBytes);for(let r of this.representations.values())if(r.id!==t)for(let a of this.segments.get(r.id)??[])a.status==="fed"&&Math.round(a.time.from)===Math.round(e.segment.time.from)&&Math.round(a.time.to)===Math.round(e.segment.time.to)&&(a.status="none");Re(this.sourceBuffer),this.updateLowLatencyLiveIfNeeded(e.segment),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment])}abortSegment(e){e.status==="partially_fed"?e.status="partially_ejected":e.status!=="partially_ejected"&&(e.status="none");for(let t of this.activeSegments.values())if(t.segment===e){this.activeSegments.delete(t);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(let[a,s]of this.initData.entries()){let n=s instanceof Promise;t||=n,s===null&&(e=a)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let r=this.representations.get(e);r&&(this.initLoadIdleCallback=su(()=>(0,Mb.default)(this.loadInit(r,"low",!1),()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",r=!1){let a=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!r&&this.failedDownloads>0?$r(this.destroyAbortController.signal,async function*(){let o=Eu(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>setTimeout(c,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,wr(e.mime),a)).then(async o=>{if(!o)return;let{init:c,dataView:u,segments:d}=o,l=u.buffer.slice(u.byteOffset,u.byteOffset+u.byteLength);this.initData.set(e.id,l);let p=d;this.isLive&&we(e.segmentReference)&&(p=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,p),c&&this.parsedInitData.set(e.id,c)}).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),r&&this.error$.next({id:"LoadInits",category:Wt.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n}async dropBuffer(){for(let e of this.segments.values())for(let t of e)t.status="none";await this.pruneBuffer(0,1/0,!0)}async pruneBuffer(e,t,r=!1){return this.tuning.useNewPruneBufferStrategy?this.pruneBufferNew(e,t,r):this.pruneBufferOld(e,t,r)}async pruneBufferNew(e,t,r=!1){if(!this.sourceBuffer||!this.playingRepresentationId||$e(e)||this.sourceBuffer.updating)return!1;let a=[],s=0,n=c=>{c.sort((d,l)=>d.from-l.from);let u=[c[0]];for(let d=1;d<c.length;d++){let{from:l,to:p}=c[d],h=u[u.length-1];h.to>=l?h.to=Math.max(h.to,p):u.push(c[d])}return u},o=c=>{if(s>=t)return a;a.push({...c.time}),a=n(a);let u=Ts(c)?c.size??0:c.byte.to-c.byte.from;s+=u};for(let c of this.segments.values())for(let u of c){let d=u.time.to<=e-this.tuning.dash.bufferPruningSafeZone,l=u.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(d||l)&&u.status==="fed"&&o(u)}for(let c=0;c<this.sourceBuffer.buffered.length;c++){let u=this.sourceBuffer.buffered.start(c)*1e3,d=this.sourceBuffer.buffered.end(c)*1e3,l=0;for(let p of this.segments.values())for(let h of p)["none","partially_ejected"].includes(h.status)&&Math.round(h.time.from)<=Math.round(u)&&Math.round(h.time.to)>=Math.round(d)&&l++;if(l===this.segments.size){let p={time:{from:u,to:d},url:"",status:"none"};o(p)}}if(a.length&&r){let c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let u of this.segments.values())for(let d of u)d.time.from>=e+c&&d.status==="fed"&&o(d)}return a.length?(await Promise.all(a.map(u=>this.sourceBufferTaskQueue.remove(u.from,u.to)))).reduce((u,d)=>u||d,!1):!1}async pruneBufferOld(e,t,r=!1){if(!this.sourceBuffer||!this.playingRepresentationId||$e(e)||this.sourceBuffer.updating)return!1;let a=0,s=1/0,n=-1/0,o=!1,c=u=>{s=Math.min(s,u.time.from),n=Math.max(n,u.time.to);let d=Ts(u)?u.size??0:u.byte.to-u.byte.from;a+=d};for(let u of this.segments.values())for(let d of u){if(d.time.to>=e-this.tuning.dash.bufferPruningSafeZone||a>=t)break;d.status==="fed"&&c(d)}if(o=isFinite(s)&&isFinite(n),!o){a=0,s=1/0,n=-1/0;for(let u of this.segments.values())for(let d of u){if(d.time.from<e+Math.min(this.forwardBufferTarget,this.bufferLimit)||a>t)break;d.status==="fed"&&c(d)}}if(o=isFinite(s)&&isFinite(n),!o)for(let u=0;u<this.sourceBuffer.buffered.length;u++){let d=this.sourceBuffer.buffered.start(u)*1e3,l=this.sourceBuffer.buffered.end(u)*1e3;for(let p of this.segments.values())for(let h of p)if(h.status==="none"&&Math.round(h.time.from)<=Math.round(d)&&Math.round(h.time.to)>=Math.round(l)){s=d,n=l;break}}if(o=isFinite(s)&&isFinite(n),!o&&r){a=0,s=1/0,n=-1/0;let u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let d of this.segments.values())for(let l of d)l.time.from>e+u&&l.status==="fed"&&c(l)}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 a={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){a=void 0;break}o>r.time.from&&o<r.time.to&&(a.from=o),n<r.time.to&&n>r.time.from&&(a.to=n)}}a&&a.to-a.from>1&&!this.gaps.some(s=>a&&s.from===a.from&&s.to===a.to)&&this.gaps.push(a)}}detectGapsWhenIdle(e,t){if(!this.gapDetectionIdleCallback){Re(this.sourceBuffer);for(let r=0;r<this.sourceBuffer.buffered.length;r++)this.gaps=this.gaps.filter(a=>this.sourceBuffer&&(Math.round(a.from)<Math.round(this.sourceBuffer.buffered.start(r)*1e3)||Math.round(a.to)>Math.round(this.sourceBuffer.buffered.end(r)*1e3)));this.gapDetectionIdleCallback=su(()=>{try{this.detectGaps(e,t)}catch(r){this.error$.next({id:"GapDetection",category:Wt.WTF,message:"detectGaps threw",thrown:r})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if($e(this.sourceBuffer)||$e(this.playingRepresentationId))return;let e=[];for(let r=0;r<this.sourceBuffer.buffered.length;r++){let a=Math.floor(this.sourceBuffer.buffered.start(r)*1e3),s=Math.ceil(this.sourceBuffer.buffered.end(r)*1e3);e.push({from:a,to:s})}let t=100;for(let r of this.segments.values())for(let a of r){let{status:s}=a;if(s!=="fed"&&s!=="partially_ejected")continue;let n=Math.floor(a.time.from),o=Math.ceil(a.time.to),c=e.some(d=>d.from-t<=n&&d.to+t>=o),u=e.filter(d=>n>=d.from&&n<d.to-t||o>d.from+t&&o<=d.to);c||(u.length===1?a.status="partially_ejected":this.gaps.some(d=>d.from===a.time.from||d.to===a.time.to)?a.status="partially_ejected":a.status="none")}}};var Qi=i=>{let e=new URL(i);return e.searchParams.set("quic","1"),e.toString()};var Cb=i=>{let e=i.get("X-Delivery-Type"),t=i.get("X-Reused"),r=e===null?"http1":e??void 0,a=t===null?void 0:{1:!0,0:!1}[t]??void 0;return{type:r,reused:a}};import{abortable as zi,assertNever as Db,fromEvent as Bb,merge as Dk,now as Ki,Subscription as Bk,ValueSubject as Pu,flattenObject as Mr}from"@vkontakte/videoplayer-shared";var Is=class{constructor({throughputEstimator:e,requestQuic:t,tracer:r,compatibilityMode:a=!1}){this.lastConnectionType$=new Pu(void 0);this.lastConnectionReused$=new Pu(void 0);this.lastRequestFirstBytes$=new Pu(void 0);this.abortAllController=new ot;this.subscription=new Bk;this.fetchManifest=zi(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),r=e;this.requestQuic&&(r=Qi(r));let a=yield nt(r,{signal:this.abortAllController.signal}).catch(Ji);return a?(t.log("success",Mr({url:r,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(a.headers),a.text()):(t.error("error",Mr({url:r,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=zi(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:r,onProgress:a,priority:s="auto",signal:n,measureThroughput:o=!0,isLowLatency:c=!1}={}){let u=e,d=new Headers,l=this.tracer.createComponentTracer("Fetch");if(r)switch(t){case 0:{d.append("Range",`bytes=${r.from}-${r.to}`);break}case 1:{let R=new URL(u,location.href);R.searchParams.append("bytes",`${r.from}-${r.to}`),u=R.toString();break}default:Db(t)}this.requestQuic&&(u=Qi(u));let p=this.abortAllController.signal,h;if(n){let R=new ot;if(h=Dk(Bb(this.abortAllController.signal,"abort"),Bb(n,"abort")).subscribe(()=>{try{R.abort()}catch($){Ji($)}}),this.abortAllController.signal.aborted||n.aborted)try{R.abort()}catch($){Ji($)}p=R.signal}let m=Ki();l.log("startRequest",Mr({url:u,priority:s,rangeMethod:t,range:r,isLowLatency:c,requestStartedAt:m}));let b=yield nt(u,{priority:s,headers:d,signal:p}).catch(Ji),g=Ki();if(!b)return l.error("error",{message:"No response in request"}),l.end(),h?.unsubscribe(),null;if(this.throughputEstimator?.addRawRtt(g-m),!b.ok||!b.body){h?.unsubscribe();let R=`Fetch error ${b.status}: ${b.statusText}`;return l.error("error",{message:R}),l.end(),Promise.reject(new Error(`Fetch error ${b.status}: ${b.statusText}`))}if(this.onHeadersReceived(b.headers),!a&&!o){h?.unsubscribe();let R=Ki(),$={requestStartedAt:m,requestEndedAt:R,duration:R-m};return l.log("endRequest",Mr($)),l.end(),b.arrayBuffer()}let[v,k]=b.body.tee(),y=v.getReader();o&&this.throughputEstimator?.trackStream(k,c);let S=0,T=new Uint8Array(0),E=!1,D=R=>{h?.unsubscribe(),E=!0,Ji(R)},O=zi(p,async function*({done:R,value:$}){if(S===0&&this.lastRequestFirstBytes$.next(Ki()-m),p.aborted){h?.unsubscribe();return}if(!R&&$){let q=new Uint8Array(T.length+$.length);q.set(T),q.set($,T.length),T=q,S+=$.byteLength,a?.(new DataView(T.buffer),S),yield y?.read().then(O,D)}}.bind(this));yield y?.read().then(O,D),h?.unsubscribe();let N=Ki(),w={failed:E,requestStartedAt:m,requestEndedAt:N,duration:N-m};return E?(l.error("endRequest",Mr(w)),l.end(),null):(l.log("endRequest",Mr(w)),l.end(),T.buffer)}.bind(this));this.fetchByteRangeRepresentation=zi(this.abortAllController.signal,async function*(e,t,r){if(e.type!=="byteRange")return null;let{from:a,to:s}=e.initRange,n=a,o=s,c=!1,u,d;e.indexRange&&(u=e.indexRange.from,d=e.indexRange.to,c=s+1===u,c&&(n=Math.min(u,a),o=Math.max(d,s))),n=Math.min(n,0);let l=yield this.fetch(e.url,{range:{from:n,to:o},priority:r,measureThroughput:!1});if(!l)return null;let p=new DataView(l,a-n,s-n+1);if(!t.validateData(p))throw new Error("Invalid media file");let h=t.parseInit(p),m=e.indexRange??t.getIndexRange(h);if(!m)throw new ReferenceError("No way to load representation index");let b;if(c)b=new DataView(l,m.from-n,m.to-m.from+1);else{let v=yield this.fetch(e.url,{range:m,priority:r,measureThroughput:!1});if(!v)return null;b=new DataView(v)}let g=t.parseSegments(b,h,m);return{init:h,dataView:new DataView(l),segments:g}}.bind(this));this.fetchTemplateRepresentation=zi(this.abortAllController.signal,async function*(e,t){if(e.type!=="template")return null;let r=new URL(e.initUrl,e.baseUrl).toString(),a=yield this.fetch(r,{priority:t,measureThroughput:!1});return a?{init:null,segments:e.segments.map(n=>({...n,status:"none",size:void 0})),dataView:new DataView(a)}:null}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=a,this.tracer=r.createComponentTracer("Fetcher")}onHeadersReceived(e){let{type:t,reused:r}=Cb(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(r)}async fetchRepresentation(e,t,r="auto"){let{type:a}=e;switch(a){case"byteRange":return await this.fetchByteRangeRepresentation(e,t,r)??null;case"template":return await this.fetchTemplateRepresentation(e,r)??null;default:Db(a)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}},Ji=i=>{if(!Gi(i))throw i};var Yt=(i,e,t)=>t*e+(1-t)*i,Au=(i,e)=>i.reduce((t,r)=>t+r,0)/e,Vb=(i,e,t,r)=>{let a=0,s=t,n=Au(i,e),o=e<r?e:r;for(let c=0;c<o;c++)i[s]>n?a++:a--,s=(i.length+s-1)%i.length;return Math.abs(a)===o};import{isNullable as Vk,ValueSubject as Ob}from"@vkontakte/videoplayer-shared";var Tt=class{constructor(e){this.prevReported=void 0;this.pastMeasures=[];this.takenMeasures=0;this.measuresCursor=0;this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new Ob(e.initial),this.debounced$=new Ob(e.initial);let t=e.label??"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new te(`raw_${t}`),this.smoothedSeries$=new te(`smoothed_${t}`),this.reportedSeries$=new te(`reported_${t}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,r=0;for(let o=0;o<this.pastMeasures.length;o++)this.pastMeasures[o]!==void 0&&(t+=(this.pastMeasures[o]-this.smoothed)**2,r++);this.takenMeasures=r,t/=r;let a=Math.sqrt(t),s=this.smoothed+this.params.deviationFactor*a,n=this.smoothed-this.params.deviationFactor*a;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)&&(Vk(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 Es=class extends Tt{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 xs=class extends Tt{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=Au(this.pastMeasures,this.takenMeasures);this.emaSmoothed=Yt(this.emaSmoothed,e,this.params.emaAlpha);let r=Vb(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=r?this.emaSmoothed:t}};var Ps=class extends Tt{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 Qt=class{static getSmoothedValue(e,t,r){return r.type==="TwoEma"?new Es({initial:e,emaAlphaSlow:r.emaAlphaSlow,emaAlphaFast:r.emaAlphaFast,changeThreshold:r.changeThreshold,fastDirection:t,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"}):new xs({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 Ps({initial:e,label:"liveEdgeDelay",...t})}};var ku=(i,e)=>{i&&i.playbackRate!==e&&(i.playbackRate=e)};import{isNullable as Ok,ValueSubject as _k}from"@vkontakte/videoplayer-shared";var Xi=class i{constructor(e,t){this.currentRepresentation$=new _k(null);this.currentSegment=null;this.getCurrentPosition=t.getCurrentPosition,this.processStreams(e)}updateLive(e){this.processStreams(e?.streams.text)}seekLive(e){this.processStreams(e)}maintain(e=this.getCurrentPosition()){if(!Ok(e))for(let t of this.representations){let r=t.segmentReference.segments.find(a=>a.time.from<=e&&a.time.to>=e);if(!r||this.currentSegment?.time.from===r.time.from&&this.currentSegment.time.to===r.time.to)return;this.currentSegment=r,this.currentRepresentation$.next({...t,label:"Live Text",language:"ru",isAuto:!0,url:new URL(r.url,t.segmentReference.baseUrl).toString()})}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e??[]){let r=i.filterRepresentations(t.representations);if(r){this.representations=r;break}}}static isSupported(e){return!!e?.some(t=>i.filterRepresentations(t.representations))}static filterRepresentations(e){return e?.filter(t=>t.kind==="text"&&"segmentReference"in t&&we(t.segmentReference))}};var Hb=["timeupdate","progress","play","seeked","stalled","waiting"];var ws=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new Ub;this.representationSubscription=new Ub;this.state$=new L("none");this.currentVideoRepresentation$=new X(void 0);this.currentVideoRepresentationInit$=new X(void 0);this.currentAudioRepresentation$=new X(void 0);this.currentVideoSegmentLength$=new X(0);this.currentAudioSegmentLength$=new X(0);this.error$=new qb;this.lastConnectionType$=new X(void 0);this.lastConnectionReused$=new X(void 0);this.lastRequestFirstBytes$=new X(void 0);this.currentLiveTextRepresentation$=new X(null);this.isLive$=new X(!1);this.liveDuration$=new X(0);this.liveAvailabilityStartTime$=new X(void 0);this.bufferLength$=new X(0);this.liveLoadBufferLength$=new X(0);this.livePositionFromPlayer$=new X(0);this.timeInWaiting=0;this.isActiveLowLatency$=new X(!1);this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.liveLastSeekOffset=0;this.forceEnded$=new qb;this.gapWatchdogActive=!1;this.destroyController=new ot;this.initManifest=wu(this.destroyController.signal,async function*(e,t,r){this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=J(t,r,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),this.manifest?.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:It.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=wu(this.destroyController.signal,async function*(){this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(n=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:It.NETWORK,message:"Failed to load manifest",thrown:n})});if(!e)return null;let t=null;try{t=wb(e??"",this.manifestUrlString)}catch(n){let o=Hm(e)??{id:"ManifestParsing",category:It.PARSER,message:"Failed to parse MPD manifest",thrown:n};this.error$.next(o)}if(!t)return null;let r=(n,o,c)=>!!(this.element?.canPlayType?.(o)&&ut()?.isTypeSupported?.(`${o}; codecs="${c}"`)||n==="text");t.dynamic&&this.isLive$.getValue()!==t.dynamic&&(this.isLive$.next(t.dynamic),this.liveDuration$.getValue()!==t.duration&&this.liveDuration$.next(-1*(t.duration??0)/1e3),this.liveAvailabilityStartTime$.getValue()!==t.liveAvailabilityStartTime&&this.liveAvailabilityStartTime$.next(t.liveAvailabilityStartTime));let a={text:t.streams.text,video:[],audio:[]};for(let n of["video","audio"]){let c=t.streams[n].filter(({mime:l,codecs:p})=>r(n,l,p)),u=new Set(c.map(({codecs:l})=>l)),d=Um(u);if(d&&(a[n]=c.filter(({codecs:l})=>l.startsWith(d))),n==="video"){let l=this.tuning.preferHDR,p=a.video.some(m=>m.hdr),h=a.video.some(m=>!m.hdr);Hk.isHDR&&l&&p?a.video=a.video.filter(m=>m.hdr):h&&(a.video=a.video.filter(m=>!m.hdr))}}let s={...t,streams:a};return this.tracer.log("updateManifestEnd",Zi(s)),s}.bind(this));this.initRepresentations=wu(this.destroyController.signal,async function*(e,t,r){this.tracer.log("initRepresentationsStart",Zi({initialVideo:e,initialAudio:t,sourceHls:r})),zt(this.manifest),zt(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let a=l=>{this.representationSubscription.add(Cr(l,"error").pipe(ks(p=>!!this.element?.played.length)).subscribe(p=>{this.error$.next({id:"VideoSource",category:It.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:p})}))};this.source=this.tuning.useManagedMediaSource?Dm():new MediaSource;let s=document.createElement("source");if(a(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),this.tuning.useManagedMediaSource&&ms())if(r){let l=document.createElement("source");a(l),l.type="application/x-mpegurl",l.src=r.url,this.element.appendChild(l)}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((l,p)=>[...l,...p.representations],[]);if(this.videoBufferManager=new Yi("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],Fb(t)){let l=this.manifest.streams.audio.reduce((p,h)=>[...p,...h.representations],[]);this.audioBufferManager=new Yi("audio",this.source,l,n),this.bufferManagers.push(this.audioBufferManager)}if(Xi.isSupported(this.manifest.streams.text)&&!this.tuning.dashCmafLive.lowLatency.isActive&&(this.liveTextManager=new Xi(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(Ru(1e3).subscribe(l=>{if(this.element?.paused){let p=_o(this.manifestUrlString,2);this.manifestUrlString=J(this.manifestUrlString,p+1e3,2)}})),this.representationSubscription.add(Dr(...Hb.filter(l=>l!=="waiting").map(l=>Cr(this.element,l))).pipe($u(l=>this.element?st(this.element.buffered,this.element.currentTime*1e3):0),Nb(),ks(l=>!!l),qk(l=>{this.stallWatchdogSubscription?.unsubscribe(),this.timeInWaiting=0})).subscribe(this.bufferLength$)),this.isLive$.getValue()){this.representationSubscription.add(this.isActiveLowLatency$.pipe(Nb()).subscribe(p=>ku(this.element,1))),this.representationSubscription.add(As({bufferLength:this.bufferLength$,isActiveLowLatency:this.isActiveLowLatency$}).pipe(ks(({bufferLength:p,isActiveLowLatency:h})=>h&&!!p)).subscribe(({bufferLength:p})=>this.liveEstimatedDelay.next(p))),this.representationSubscription.add(As({liveEstimatedDelay:this.liveEstimatedDelay.smoothed$,isActiveLowLatency:this.isActiveLowLatency$}).subscribe(({liveEstimatedDelay:p,isActiveLowLatency:h})=>{if(!h)return;let m=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,b=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,g=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,v=p-m,k=1;Math.abs(v)>b&&(k=1+Math.sign(v)*g),ku(this.element,k)})),this.representationSubscription.add(this.bufferLength$.subscribe(p=>{let h=0;if(p){let m=(this.element?.currentTime??0)*1e3;h=Math.min(...this.bufferManagers.map(g=>g.getLiveSegmentsToLoadState(this.manifest)?.to??m))-m}this.liveLoadBufferLength$.getValue()!==h&&this.liveLoadBufferLength$.next(h)}));let l=0;this.representationSubscription.add(As({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(Uk(1e3)).subscribe(async({liveLoadBufferLength:p,bufferLength:h})=>{if(zt(this.element),this.isUpdatingLive)return;let m=this.element.playbackRate,b=_o(this.manifestUrlString,2),g=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,v=Math.min(g,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*m),k=this.tuning.dashCmafLive.normalizedActualBufferOffset*m,y=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*m,S=isFinite(p)?p:h,T=this.isActiveLowLatency$.getValue(),E=g<=this.tuning.live.activeLiveDelay&&b===0;this.isActiveLowLatency$.next(T&&E);let D="none";if(T?D="active_low_latency":this.tuning.dashCmafLive.lowLatency.isActive&&E?(this.isActiveLowLatency$.next(!0),this.bufferManagers.forEach(O=>O.proceedLowLatencyLive()),D="active_low_latency"):b!==0&&S<v?D="live_forward_buffering":S<v+y&&(D="live_with_target_offset"),isFinite(p)&&(l=p>l?p:l),D==="live_forward_buffering"||D==="live_with_target_offset"){let O=l-(v+k),N=this.normolizeLiveOffset(Math.trunc(b+O/m)),w=Math.abs(N-b),R;!p||w<=this.tuning.dashCmafLive.offsetCalculationError?R=b:N>0&&w>this.tuning.dashCmafLive.offsetCalculationError?R=N:R=0,this.manifestUrlString=J(this.manifestUrlString,R,2)}D!=="none"&&D!=="active_low_latency"&&(l=0,this.updateLive())}))}let c=Dr(...this.bufferManagers.map(l=>l.fullyBuffered$)).pipe($u(()=>this.bufferManagers.every(l=>l.fullyBuffered$.getValue()))),u=Dr(...this.bufferManagers.map(l=>l.onLastSegment$)).pipe($u(()=>this.bufferManagers.some(l=>l.onLastSegment$.getValue())));this.representationSubscription.add(Dr(this.forceEnded$,As({allBuffersFull:c,someBufferEnded:u}).pipe(ks(({allBuffersFull:l,someBufferEnded:p})=>l&&p))).subscribe(()=>{if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(l=>!l.updating))try{this.source?.endOfStream()}catch(l){this.error$.next({id:"EndOfStream",category:It.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:l})}})),this.representationSubscription.add(Dr(...this.bufferManagers.map(l=>l.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(l=>this.source?.addEventListener("sourceopen",l)));let d=[this.manifest.duration??0,...[...this.manifest.streams.audio,...this.manifest.streams.video].flatMap(l=>l.representations).flatMap(l=>{let p=[];return l.duration&&p.push(l.duration),we(l.segmentReference)&&l.segmentReference.totalSegmentsDurationMs&&p.push(l.segmentReference.totalSegmentsDurationMs),p})];this.source.duration=Math.max(...d)/1e3,this.audioBufferManager&&Fb(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState("representations_ready"),this.tracer.log("initRepresentationsEnd")}.bind(this));this.tick=()=>{if(!this.element||!this.videoBufferManager)return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),this.audioBufferManager?.maintain(e),this.liveTextManager?.maintain(e),(this.videoBufferManager.gaps.length||this.audioBufferManager?.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=Ru(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),t=>{this.error$.next({id:"GapWatchdog",category:It.WTF,message:"Error handling gaps",thrown:t})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name),this.fetcher=new Is({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer}),this.liveEstimatedDelay=Qt.getLiveEstimatedDelaySmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.delayEstimator}),this.initTracerSubscription()}async seekLive(e){zt(this.element);let t=this.normolizeLiveOffset(e);this.isActiveLowLatency$.next(this.tuning.dashCmafLive.lowLatency.isActive&&t===0),this.liveLastSeekOffset=t,this.manifestUrlString=J(this.manifestUrlString,t,2),this.manifest=await this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,await this.videoBufferManager?.seekLive(this.manifest.streams.video),await this.audioBufferManager?.seekLive(this.manifest.streams.audio),this.liveTextManager?.seekLive(this.manifest.streams.text))}initBuffer(){zt(this.element),this.state$.setState("running"),this.subscription.add(Dr(...Hb.map(e=>Cr(this.element,e)),Cr(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:It.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(Cr(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(Cr(this.element,"waiting").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&Pr(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{if(!this.element)return;this.timeInWaiting+=1e3;let t={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),t={...t,liveLastSeekOffset:this.liveLastSeekOffset};else{let r=this.element.currentTime*1e3;this.videoBufferManager?.maintain(r),this.audioBufferManager?.maintain(r),t={...t,position:r}}this.tracer.log("stallIntervalCallback",Zi(t))};this.videoBufferManager?.startAccumulateBuffer(),this.audioBufferManager?.startAccumulateBuffer(),this.stallWatchdogSubscription?.unsubscribe(),this.stallWatchdogSubscription=Ru(1e3).subscribe(e,t=>{this.error$.next({id:"StallWatchdogCallback",category:It.FATAL,message:"Can't restore DASH after stall.",thrown:t})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t,r=!1){return{video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e]?.switchTo(t,r)}seek(e,t){zt(this.element),zt(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(this.videoBufferManager.findSegmentStartTime(e)??e,this.audioBufferManager?.findSegmentStartTime(e)??e),Pr(this.element.buffered,r)||(this.videoBufferManager.abort(),this.audioBufferManager?.abort()),this.videoBufferManager.startAccumulateBuffer(),this.videoBufferManager.maintain(r),this.audioBufferManager?.startAccumulateBuffer(),this.audioBufferManager?.maintain(r),this.element.currentTime=r/1e3,this.tracer.log("seek",Zi({requestedPosition:e,forcePrecise:t,position:r}))}stop(){this.tracer.log("stop"),this.element?.querySelectorAll("source").forEach(e=>e.remove()),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),this.videoBufferManager?.destroy(),this.videoBufferManager=null,this.audioBufferManager?.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getStreams(){return this.manifest?.streams}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),this.source?.readyState==="open"&&Array.from(this.source.sourceBuffers).every(e=>!e.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}initTracerSubscription(){let e=jk(this.tracer.error.bind(this.tracer));this.error$.subscribe(e("error"))}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}async updateLive(){this.isUpdatingLive=!0,this.manifest=await this.updateManifest(),this.manifest&&(this.bufferManagers?.forEach(e=>e.updateLive(this.manifest)),this.liveTextManager?.updateLive(this.manifest)),this.isUpdatingLive=!1}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.getDebugBufferState();if(!e)return;let t={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,a=[],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?a.push(1/0):a.push(o.to));if(a.length){let n=Math.max(...a)+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,n===1/0?this.forceEnded$.next():(this.element.currentTime=n/1e3,t={...t,gapEnds:a,jumpTo:n,resultCurrentTime:this.element.currentTime},this.tracer.log("jumpGap",Zi(t)))}}};var Rs=class{constructor(e,t){this.fov=e,this.orientation=t}};var $s=class{constructor(e,t){this.rotating=!1;this.fading=!1;this.lastTickTS=0;this.lastCameraTurnTS=0;this.fadeStartSpeed=null;this.fadeTime=0;this.camera=e,this.options=t,this.rotationSpeed={x:0,y:0,z:0},this.fadeCorrection=1/(this.options.speedFadeTime/1e3)**2}turnCamera(e=0,t=0,r=0){this.pointCameraTo(this.camera.orientation.x+e,this.camera.orientation.y+t,this.camera.orientation.z+r)}pointCameraTo(e=0,t=0,r=0){t=this.limitCameraRotationY(t);let a=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:a,y:s,z:n},this.lastCameraTurnTS=Date.now()}setRotationSpeed(e,t,r){this.rotationSpeed.x=e??this.rotationSpeed.x,this.rotationSpeed.y=t??this.rotationSpeed.y,this.rotationSpeed.z=r??this.rotationSpeed.z}startRotation(){this.rotating=!0}stopRotation(e=!1){e?(this.setRotationSpeed(0,0,0),this.fadeStartSpeed=null):this.startFading(this.rotationSpeed.x,this.rotationSpeed.y,this.rotationSpeed.z),this.rotating=!1}onCameraRelease(){if(this.lastCameraTurn&&this.lastCameraTurnTS){let e=Date.now()-this.lastCameraTurnTS;if(e<this.options.speedFadeThreshold){let t=(1-e/this.options.speedFadeThreshold)*this.options.rotationSpeedCorrection;this.startFading(this.lastCameraTurn.x*t,this.lastCameraTurn.y*t,this.lastCameraTurn.z*t)}}}startFading(e,t,r){this.setRotationSpeed(e,t,r),this.fadeStartSpeed={...this.rotationSpeed},this.fading=!0}stopFading(){this.fadeStartSpeed=null,this.fading=!0,this.fadeTime=0}limitCameraRotationY(e){return Math.max(-this.options.maxYawAngle,Math.min(e,this.options.maxYawAngle))}tick(e){if(!this.lastTickTS){this.lastTickTS=e,this.lastCameraTurnTS=Date.now();return}let t=e-this.lastTickTS,r=t/1e3;if(this.rotating)this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*r,this.rotationSpeed.y*this.options.rotationSpeedCorrection*r,this.rotationSpeed.z*this.options.rotationSpeedCorrection*r);else if(this.fading&&this.fadeStartSpeed){let a=-this.fadeCorrection*(this.fadeTime/1e3)**2+1;this.setRotationSpeed(this.fadeStartSpeed.x*a,this.fadeStartSpeed.y*a,this.fadeStartSpeed.z*a),a>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 jb=`attribute vec2 a_vertex;
59
59
  attribute vec2 a_texel;
60
60
 
61
61
  varying vec2 v_texel;
@@ -66,7 +66,7 @@ void main(void) {
66
66
  // save texel vector to pass to fragment shader
67
67
  v_texel = a_texel;
68
68
  }
69
- `;var Fb=`#ifdef GL_ES
69
+ `;var Gb=`#ifdef GL_ES
70
70
  precision highp float;
71
71
  precision highp int;
72
72
  #else
@@ -109,5 +109,5 @@ void main(void) {
109
109
  // sample using new coordinates
110
110
  gl_FragColor = texture2D(u_texture, tc);
111
111
  }
112
- `;var ys=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 a=this.canvas.getContext("webgl");if(!a)throw new Error("Could not initialize WebGL context");this.gl=a,this.container.appendChild(this.canvas),this.camera=new Ss(this.params.fov,this.params.orientation),this.cameraRotationManager=new vs(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"),a=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(a,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(Nb,this.gl.VERTEX_SHADER),r=this.createShader(Fb,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,a=this.frameHeight/(this.frameWidth/this.viewportWidth);return a>this.viewportHeight?t=this.viewportHeight/a:r=a/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,a=this.camera.fov.y/180/2,s=e-r,n=t-a,o=e+r,c=t-a,u=e+r,d=t+a,l=e-r,p=t+a;return[s,n,o,c,u,d,l,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 qt=class{constructor(e){this.subscription=new Zk;this.videoState=new L("stopped");this.elementSize$=new ew(void 0);this.textTracksManager=new Ee;this.droppedFramesManager=new es;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new si;this.audioTrackSwitchHistory=new si;this.textTracks=[];this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(a.state==="requested"&&r?.to!=="paused"&&e!=="stopped"&&t!=="stopped"){let n=this.liveOffset?.getTotalPausedTime()??0;this.seek(a.position-n,a.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"),I(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"),I(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):r?.to==="ready"&&I(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.liveOffset?.pause(),this.video.paused?this.videoState.setState("paused"):this.video.pause()):r?.to==="playing"&&I(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?.to==="paused"&&I(this.params.desiredState.playbackState,"paused");return;default:return Wk(e)}}};this.init3DScene=e=>{if(this.scene3D)return;this.scene3D=new ys(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:e.projectionData?.pose.yaw||0,y:e.projectionData?.pose.pitch||0,z:e.projectionData?.pose.roll||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});let t=this.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=se(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(Y(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new gs({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=ue(this.video),a=this.constructor.name,s=o=>{e.error$.next({id:a,category:Pu.WTF,message:`${a} internal logic error`,thrown:o})};return{output:e,desiredState:t,observableVideo:r,genericErrorListener:s,connect:(o,c)=>this.subscription.add(o.subscribe(c,s))}}subscribe(){let{output:e,desiredState:t,observableVideo:r,genericErrorListener:a,connect:s}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe(qb(u=>!!u.length),Hb()).subscribe(u=>{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:u})})),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(qb(Kk),Hb()),e.firstBytesEvent$),s(this.videoState.stateChangeEnded$.pipe(Ub(u=>u.to)),this.params.output.playbackState$),this.subscription.add(r.seeked$.subscribe(e.seekedEvent$,a)),this.subscription.add(qe(this.video,t.isLooped,a)),this.subscription.add(oe(this.video,t.volume,r.volumeState$,a)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,a)),this.subscription.add(Ie(this.video,t.playbackRate,r.playbackRateState$,a)),s(Xk(this.video),this.elementSize$),s(Pe(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),I(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},a)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),I(t.playbackState,"paused")},a)).add(r.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},a)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:u})=>{if(u==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let d=this.player.getStreams();if(Yk(d,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let p=[];for(let h of d.audio){p.push(fu(h));let m=[];for(let b of h.representations){let g=Pb(b);m.push(g),this.audioTracksMap.set(g,{stream:h,representation:b})}this.audioStreamsMap.set(h,m)}this.params.output.availableAudioStreams$.next(p)}let l=[];for(let p of d.video){l.push(mu(p));let h=[];for(let m of p.representations){let b=xb(m);b&&(h.push(b),this.videoTracksMap.set(b,{stream:p,representation:m}))}this.videoStreamsMap.set(p,h)}this.params.output.availableVideoStreams$.next(l);for(let p of d.text)for(let h of p.representations){let m=Ab(p,h);this.textTracksMap.set(m,{stream:p,representation:h})}this.params.output.availableVideoTracks$.next(Array.from(this.videoTracksMap.keys())),this.params.output.availableAudioTracks$.next(Array.from(this.audioTracksMap.keys())),this.params.output.isAudioAvailable$.next(!!this.audioTracksMap.size),this.audioTracksMap.size>0&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else u==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},a));let n=u=>e.error$.next({id:"RepresentationSwitch",category:Pu.WTF,message:"Switching representations threw",thrown:u});this.subscription.add(Ts(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$,zk(this.video,"progress")).subscribe(()=>{let u=this.player.state$.getState(),d=this.player.state$.getTransition();if(!["manifest_ready","running"].includes(u)||d)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let l=this.selectVideoAudioRepresentations();if(!l)return;let[p,h]=l,m=this.params.desiredState.autoVideoTrackLimits.getTransition();if(m&&this.params.output.autoVideoTrackLimits$.next(m.to),u==="manifest_ready")this.player.initRepresentations(p.id,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)}},a)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:u})=>{this.scene3D&&u&&this.scene3D.pointCameraTo(u.x,u.y)})),this.subscription.add(this.elementSize$.subscribe(u=>{this.scene3D&&u&&this.scene3D.setViewportSize(u.width,u.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(Au()).subscribe(u=>{let d=[...this.videoTracksMap.entries()].find(([,{representation:m}])=>m.id===u);if(!d){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[l,{stream:p}]=d,h=this.params.desiredState.videoStream.getTransition();h&&h.to&&h.to.id===p.id&&this.params.desiredState.videoStream.setState(h.to),e.currentVideoTrack$.next(l),e.currentVideoStream$.next(mu(p))},a)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(Au()).subscribe(u=>{let d=[...this.audioTracksMap.entries()].find(([,{representation:m}])=>m.id===u);if(!d){e.currentAudioStream$.next(void 0);return}let[l,{stream:p}]=d,h=this.params.desiredState.audioStream.getTransition();h&&h.to&&h.to.id===p.id&&this.params.desiredState.audioStream.setState(h.to),e.currentAudioStream$.next(fu(p))},a)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(u=>{if(u?.is3dVideo&&this.params.tuning.spherical?.enabled)try{this.init3DScene(u),e.is3DVideo$.next(!0)}catch(d){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${d}`})}else this.destroy3DScene(),this.params.tuning.spherical?.enabled&&e.is3DVideo$.next(!1)},a)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,a)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,a)),this.textTracksManager.connect(this.video,t,e);let o=t.playbackState.stateChangeStarted$.pipe(Ub(({to:u})=>u==="ready"),Au());this.subscription.add(Ts(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$).subscribe(()=>{let u=t.autoVideoTrackSwitching.getState(),l=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:u?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(l)})),this.subscription.add(Ts(o,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let c=Ts(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Jk(["init"])).pipe(Qk(0));this.subscription.add(c.subscribe(this.syncPlayback,a))}selectVideoAudioRepresentations(){let{desiredState:e,output:t}=this.params,r=e.autoVideoTrackSwitching.getState(),a=e.videoTrack.getState()?.id,n=[...this.videoTracksMap.keys()].find(({id:E})=>E===a),o=t.currentVideoTrack$.getValue(),c=e.videoStream.getState()??(n&&this.videoTracksMap.get(n)?.stream)??this.videoStreamsMap.size===1?this.videoStreamsMap.keys().next().value:void 0;if(!c)return;let u=[...this.videoStreamsMap.keys()].find(({id:E})=>E===c.id),d=u&&this.videoStreamsMap.get(u);if(!d)return;let l=ze(this.video.buffered,this.video.currentTime*1e3),p=r?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,h=Math.min(l/Math.min(p,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),m=e.audioStream.getState()??(this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0),b=[...this.audioStreamsMap.keys()].find(({id:E})=>E===m?.id)??this.audioStreamsMap.keys().next().value,g=0;if(b){if(n&&!r)if(this.params.tuning.useSeparateAudioVideoABR){let E=Ka(n,d,this.audioStreamsMap.get(b)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);g=Math.max(g,E?.bitrate??-1/0)}else{let E=cs(n,d,this.audioStreamsMap.get(b)??[]);g=Math.max(g,E?.bitrate??-1/0)}if(o)if(this.params.tuning.useSeparateAudioVideoABR){let E=Ka(o,d,this.audioStreamsMap.get(b)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);g=Math.max(g,E?.bitrate??-1/0)}else{let E=cs(o,d,this.audioStreamsMap.get(b)??[]);g=Math.max(g,E?.bitrate??-1/0)}}let v=lt(d,{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}),A=r?v??n:n??v,y;this.params.tuning.useSeparateAudioVideoABR?y=b&&fm(A,d,this.audioStreamsMap.get(b)??[],{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}):y=b&&cs(A,d,this.audioStreamsMap.get(b)??[]);let S=this.videoTracksMap.get(A)?.representation,T=y&&this.audioTracksMap.get(y)?.representation;if(S&&T)return[S,T];if(S&&!T&&this.audioTracksMap.size===0)return[S,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){le(this.video).then(e=>{e||(this.liveOffset?.pause(),this.videoState.setState("paused"),I(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Pu.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),ne(this.video),this.tracer.end()}};var Gi=class extends qt{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 jb,interval as tw,map as rw}from"@vkontakte/videoplayer-shared";var Wi=class extends qt{constructor(e){super(e),this.liveOffset=new Ye}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(jb({interval:tw(1e3),playbackRate:t.playbackRateState$}).subscribe(({playbackRate:a})=>{if(this.videoState.getState()==="playing"){let s=e.position$.getValue()+(a-1);s<=0&&e.position$.next(s),this.liveOffset?.resetTo(-s*1e3)}})).add(jb({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(rw(({liveBufferTime:a,liveAvailabilityStartTime:s})=>a&&s?a+s:void 0)).subscribe(e.liveTime$))}seek(e){this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),r=this.videoState.getState(),a=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(()=>{this.params.output.position$.next(e/1e3),this.liveOffset?.resetTo(n,a)})}};var Wb=Ne(Ya(),1);import{assertNever as Yi,assertNonNullable as Gb,debounce as iw,ErrorCategory as Is,filter as aw,isNonNullable as sw,isNullable as nw,map as Es,merge as ow,Observable as uw,observableFrom as cw,Subscription as lw,videoSizeToQuality as dw}from"@vkontakte/videoplayer-shared";var Ve={};var Ar=(i,e)=>new uw(t=>{let r=(a,s)=>t.next(s);return i.on(e,r),()=>i.off(e,r)}),Qi=class{constructor(e){this.subscription=new lw;this.videoState=new L("initializing");this.textTracksManager=new Ee;this.trackLevels=new Map;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(e!=="initializing")switch(r?.to!=="paused"&&a.state==="requested"&&this.seek(a.position),t){case"stopped":switch(e){case"stopped":break;case"ready":case"playing":case"paused":this.stop();break;default:Yi(e)}break;case"ready":switch(e){case"stopped":this.prepare();break;case"ready":case"playing":case"paused":break;default:Yi(e)}break;case"playing":switch(e){case"playing":break;case"stopped":this.prepare();break;case"ready":case"paused":this.playIfAllowed();break;default:Yi(e)}break;case"paused":switch(e){case"paused":break;case"stopped":this.prepare();break;case"ready":this.videoState.setState("paused"),I(this.params.desiredState.playbackState,"paused");break;case"playing":this.pause();break;default:Yi(e)}break;default:Yi(t)}};this.video=se(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(Y(this.params.source.url)),this.loadHlsJs()}destroy(){this.subscription.unsubscribe(),this.trackLevels.clear(),this.textTracksManager.destroy(),this.hls?.detachMedia(),this.hls?.destroy(),this.params.output.element$.next(void 0),ne(this.video)}loadHlsJs(){let e=!1,t=a=>{e||this.params.output.error$.next({id:a==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:Is.NETWORK,message:"Failed to load Hls.js",thrown:a}),e=!0},r=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);(0,Wb.default)(import("hls.js").then(a=>{e||(Ve.Hls=a.default,Ve.Events=a.default.Events,this.init())},t),()=>{window.clearTimeout(r),e=!0})}init(){Gb(Ve.Hls,"hls.js not loaded"),this.hls=new Ve.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState("stopped")}subscribe(){Gb(Ve.Events,"hls.js not loaded");let{desiredState:e,output:t}=this.params,r=u=>{t.error$.next({id:"HlsJsProvider",category:Is.WTF,message:"HlsJsProvider internal logic error",thrown:u})},a=ue(this.video),s=(u,d)=>this.subscription.add(u.subscribe(d,r));s(a.timeUpdate$,t.position$),s(a.durationChange$,t.duration$),s(a.ended$,t.endedEvent$),s(a.looped$,t.loopedEvent$),s(a.error$,t.error$),s(a.isBuffering$,t.isBuffering$),s(a.currentBuffer$,t.currentBuffer$),s(a.loadStart$,t.firstBytesEvent$),s(a.loadedMetadata$,t.loadedMetadataEvent$),s(a.playing$,t.firstFrameEvent$),s(a.canplay$,t.canplay$),s(a.seeked$,t.seekedEvent$),s(a.inPiP$,t.inPiP$),s(a.inFullscreen$,t.inFullscreen$),this.subscription.add(qe(this.video,e.isLooped,r)),this.subscription.add(oe(this.video,e.volume,a.volumeState$,r)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(Ie(this.video,e.playbackRate,a.playbackRateState$,r)),s(Pe(this.video),t.elementVisible$),s(this.videoState.stateChangeEnded$.pipe(Es(u=>u.to)),this.params.output.playbackState$),this.subscription.add(Ar(this.hls,Ve.Events.ERROR).subscribe(u=>{u.fatal&&t.error$.next({id:["HlsJsFatal",u.type,u.details].join("_"),category:Is.WTF,message:`HlsJs fatal ${u.type} ${u.details}, ${u.err?.message} ${u.reason}`,thrown:u.error})})),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState("playing"),I(e.playbackState,"playing")},r)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),I(e.playbackState,"paused")},r)).add(a.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),s(Ar(this.hls,Ve.Events.MANIFEST_PARSED).pipe(Es(({levels:u})=>u.reduce((d,l)=>{let p=l.name||l.height.toString(10),{width:h,height:m}=l,b=ct(l.attrs.QUALITY??"")??dw({width:h,height:m});if(!b)return d;let g=l.attrs["FRAME-RATE"]?parseFloat(l.attrs["FRAME-RATE"]):void 0,v={id:p.toString(),quality:b,bitrate:l.bitrate/1e3,size:{width:h,height:m},fps:g};return this.trackLevels.set(p,{track:v,level:l}),d.push(v),d},[]))),t.availableVideoTracks$),s(Ar(this.hls,Ve.Events.MANIFEST_PARSED),u=>{if(u.subtitleTracks.length>0){let d=[];for(let l of u.subtitleTracks){let p=l.name,h=l.attrs.URI||"",m=l.lang;d.push({id:p,url:h,language:m,type:"internal"})}e.internalTextTracks.startTransitionTo(d)}}),s(Ar(this.hls,Ve.Events.LEVEL_LOADING).pipe(Es(({url:u})=>Y(u))),t.hostname$),s(Ar(this.hls,Ve.Events.FRAG_CHANGED),u=>{let{video:d,audio:l}=u.frag.elementaryStreams;t.currentVideoSegmentLength$.next(((d?.endPTS??0)-(d?.startPTS??0))*1e3),t.currentAudioSegmentLength$.next(((l?.endPTS??0)-(l?.startPTS??0))*1e3)}),this.subscription.add(nt(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,u=>{this.hls.nextLevel=u?-1:this.hls.currentLevel,this.hls.loadLevel=u?-1:this.hls.loadLevel},{onError:r}));let n=u=>Array.from(this.trackLevels.values()).find(({level:d})=>d===u)?.track,o=Ar(this.hls,Ve.Events.LEVEL_SWITCHED).pipe(Es(({level:u})=>n(this.hls.levels[u])));o.pipe(aw(sw)).subscribe(t.currentVideoTrack$,r),this.subscription.add(nt(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel]),u=>{if(nw(u))return;let d=this.trackLevels.get(u.id)?.level;if(!d)return;let l=this.hls.levels.indexOf(d),p=this.hls.currentLevel,h=this.hls.levels[p];!h||d.bitrate>h.bitrate?this.hls.nextLevel=l:(this.hls.loadLevel=l,this.hls.loadLevel=l)},{changed$:o,onError:r})),s(a.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);let c=ow(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,cw(["init"])).pipe(iw(0));this.subscription.add(c.subscribe(this.syncPlayback,r))}prepare(){this.videoState.startTransitionTo("ready"),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}async playIfAllowed(){this.videoState.startTransitionTo("playing"),await le(this.video).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Is.DOM,thrown:t}))||(this.videoState.setState("paused"),I(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"),I(this.params.desiredState.playbackState,"stopped",!0)}};var Yb="X-Playback-Duration",ku=async i=>{let e=await Ke(i),t=await e.text(),r=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t)?.[1];return r?parseInt(r,10):e.headers.has(Yb)?parseInt(e.headers.get(Yb),10):void 0};import{assertNever as gw,combine as Sw,debounce as vw,ErrorCategory as Ps,filter as yw,filterChanged as Tw,isNonNullable as zb,isNullable as As,map as Kb,merge as Iw,observableFrom as Ew,Subscription as xw,ValueSubject as $u,VideoQuality as Pw}from"@vkontakte/videoplayer-shared";var Ru=Ne(Yn(),1);import{videoSizeToQuality as pw,getExponentialDelay as hw}from"@vkontakte/videoplayer-shared";var fw=i=>{let e=null;if(i.QUALITY&&(e=ct(i.QUALITY)),!e&&i.RESOLUTION){let[t,r]=i.RESOLUTION.split("x").map(a=>parseInt(a,10));e=pw({width:t,height:r})}return e??null},mw=(i,e)=>{let t=i.split(`
113
- `),r=[],a=[];for(let s=0;s<t.length;s++){let n=t[s],o=n.match(/^#EXT-X-STREAM-INF:(.+)/),c=n.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!o&&!c)){if(o){let u=(0,Ru.default)(o[1].split(",").map(g=>g.split("="))),d=u.QUALITY??`stream-${u.BANDWIDTH}`,l=fw(u),p;u.BANDWIDTH&&(p=parseInt(u.BANDWIDTH,10)/1e3||void 0),!p&&u["AVERAGE-BANDWIDTH"]&&(p=parseInt(u["AVERAGE-BANDWIDTH"],10)/1e3||void 0);let h=u["FRAME-RATE"]?parseFloat(u["FRAME-RATE"]):void 0,m;if(u.RESOLUTION){let[g,v]=u.RESOLUTION.split("x").map(A=>parseInt(A,10));g&&v&&(m={width:g,height:v})}let b=new URL(t[++s],e).toString();l&&r.push({id:d,quality:l,url:b,bandwidth:p,size:m,fps:h})}if(c){let u=(0,Ru.default)(c[1].split(",").map(h=>h.split("=")).map(([h,m])=>[h,m.replace(/^"|"$/g,"")])),d=u.URI?.replace(/playlist$/,"subtitles.vtt"),l=u.LANGUAGE,p=u.NAME;d&&l&&a.push({type:"internal",id:l,label:p,language:l,url:d,isAuto:!1})}}}if(!r.length)throw new Error("Empty manifest");return{qualityManifests:r,textTracks:a}},bw=i=>new Promise(e=>{setTimeout(()=>{e()},i)}),wu=0,Qb=async(i,e=i,t)=>{let a=await(await Ke(i)).text();wu+=1;try{let{qualityManifests:s,textTracks:n}=mw(a,e);return{qualityManifests:s,textTracks:n}}catch{if(wu<=t.manifestRetryMaxCount)return await bw(hw(wu-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),Qb(i,e,t)}return{qualityManifests:[],textTracks:[]}},xs=Qb;var zi=class{constructor(e){this.subscription=new xw;this.videoState=new L("stopped");this.textTracksManager=new Ee;this.manifests$=new $u([]);this.liveOffset=new Ye;this.manifestStartTime$=new $u(void 0);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),r=this.params.desiredState.playbackState.getState(),a=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"),I(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let u=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||n||o){let d=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(d),this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),u.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if(a?.to!=="paused"&&u.state==="requested"){this.videoState.startTransitionTo("ready"),this.seek(u.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(t){case"ready":r==="ready"?I(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),I(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()):a?.to==="playing"&&I(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 d=this.liveOffset.getTotalOffset();d>=this.maxSeekBackTime$.getValue()&&(d=0,this.liveOffset.resetTo(d)),this.liveOffset.resume(),this.params.output.position$.next(-d/1e3),this.prepare()}else a?.to==="paused"&&(I(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return gw(t)}};this.params=e,this.video=se(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:Pw.INVARIANT,url:this.params.source.url},xs(K(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})=>{t.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:Ps.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),this.manifests$.next([this.masterManifest,...t])},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:Ps.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),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(Y(this.params.source.url)),this.maxSeekBackTime$=new $u(e.source.maxSeekBackTime??1/0),this.subscribe()}selectManifest(){let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,r=e.getState(),a=t.getTransition(),s=a?.to?.id??t.getState()?.id??"master",n=this.manifests$.getValue();if(!n.length)return;let o=r?"master":s;return r&&!a&&t.startTransitionTo(this.masterManifest),n.find(c=>c.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"HlsLiveProvider",category:Ps.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},a=ue(this.video),s=(o,c)=>this.subscription.add(o.subscribe(c,r));s(a.ended$,e.endedEvent$),s(a.error$,e.error$),s(a.isBuffering$,e.isBuffering$),s(a.currentBuffer$,e.currentBuffer$),s(a.loadedMetadata$,e.firstBytesEvent$),s(a.loadedMetadata$,e.loadedMetadataEvent$),s(a.playing$,e.firstFrameEvent$),s(a.canplay$,e.canplay$),s(a.inPiP$,e.inPiP$),s(a.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),r)),this.subscription.add(oe(this.video,t.volume,a.volumeState$,r)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Ie(this.video,t.playbackRate,a.playbackRateState$,r)),s(Pe(this.video),e.elementVisible$),this.textTracksManager.connect(this.video,t,e),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState("playing"),I(t.playbackState,"playing")},r)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),I(t.playbackState,"paused")},r)).add(a.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.subscription.add(this.maxSeekBackTime$.pipe(Tw(),Kb(o=>-o/1e3)).subscribe(this.params.output.duration$,r)),this.subscription.add(a.loadedMetadata$.subscribe(()=>{let o=this.params.desiredState.seekState.getState(),c=this.videoState.getTransition(),u=this.params.desiredState.videoTrack.getTransition(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(u&&zb(u.to)){let l=u.to.id;this.params.desiredState.videoTrack.setState(u.to);let p=this.manifests$.getValue().find(h=>h.id===l);p&&(this.params.output.currentVideoTrack$.next(p),this.params.output.hostname$.next(Y(p.url)))}d&&this.params.desiredState.autoVideoTrackSwitching.setState(d.to),c&&c.from==="changing_manifest"&&this.videoState.setState(c.to),o&&o.state==="requested"&&this.seek(o.position)},r)),this.subscription.add(a.loadedData$.subscribe(()=>{let o=this.video?.getStartDate?.()?.getTime();this.manifestStartTime$.next(o||void 0)},r)),this.subscription.add(Sw({startTime:this.manifestStartTime$.pipe(yw(zb)),currentTime:a.timeUpdate$}).subscribe(({startTime:o,currentTime:c})=>this.params.output.liveTime$.next(o+c*1e3),r)),this.subscription.add(this.manifests$.pipe(Kb(o=>o.map(({id:c,quality:u,size:d,bandwidth:l,fps:p})=>({id:c,quality:u,size:d,fps:p,bitrate:l})))).subscribe(this.params.output.availableVideoTracks$,r));let n=Iw(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,Ew(["init"])).pipe(vw(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),ne(this.video)}prepare(){let e=this.selectManifest();if(As(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),r=this.params.desiredState.autoVideoTrackLimits.getState(),a=new URL(e.url);if((t||r)&&e.id===this.masterManifest.id){let{max:o,min:c}=t?.to??r??{};for(let[u,d]of[[o,"mq"],[c,"lq"]]){let l=String(parseFloat(u||""));d&&u&&a.searchParams.set(d,l)}}let s=this.params.format==="HLS_LIVE_CMAF"?2:0,n=K(a.toString(),this.liveOffset.getTotalOffset(),s);this.video.setAttribute("src",n),this.video.load(),ku(n).then(o=>{if(!As(o))this.maxSeekBackTime$.next(o);else{let c=this.params.source.maxSeekBackTime??this.maxSeekBackTime$.getValue();if(As(c)||!isFinite(c))try{Ke(n).then(u=>u.text()).then(u=>{let d=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(u)?.[1];if(d){let l=new URL(d,n).toString();ku(l).then(p=>{As(p)||this.maxSeekBackTime$.next(p)})}})}catch{}}})}playIfAllowed(){le(this.video).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),I(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Ps.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 Aw,debounce as kw,ErrorCategory as Lu,fromEvent as Mu,isNonNullable as ww,isNullable as Rw,map as Jb,merge as Xb,observableFrom as Zb,Subscription as $w,ValueSubject as Lw,VideoQuality as Mw,clientChecker as Cw}from"@vkontakte/videoplayer-shared";var Ki=class{constructor(e){this.subscription=new $w;this.videoState=new L("stopped");this.textTracksManager=new Ee;this.manifests$=new Lw([]);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),r=this.params.desiredState.playbackState.getState(),a=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"),I(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let u=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||n||o){let d=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(d);let{currentTime:l}=this.video;this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),u.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:l*1e3,forcePrecise:!0});return}switch(a?.to!=="paused"&&u.state==="requested"&&this.seek(u.position),t){case"ready":r==="ready"?I(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),I(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()):a?.to==="playing"&&I(this.params.desiredState.playbackState,"playing");return;case"paused":r==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):a?.to==="paused"&&I(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return Aw(t)}};this.params=e,this.video=se(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:Mw.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(Y(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),xs(K(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:Lu.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,r=e.getState(),a=t.getTransition(),s=a?.to?.id??t.getState()?.id??"master",n=this.manifests$.getValue();if(!n.length)return;let o=r?"master":s;return r&&!a&&t.startTransitionTo(this.masterManifest),n.find(c=>c.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"HlsProvider",category:Lu.WTF,message:"HlsProvider internal logic error",thrown:o})},a=ue(this.video),s=(o,c)=>this.subscription.add(o.subscribe(c));if(s(a.timeUpdate$,e.position$),s(a.durationChange$,e.duration$),s(a.ended$,e.endedEvent$),s(a.looped$,e.loopedEvent$),s(a.error$,e.error$),s(a.isBuffering$,e.isBuffering$),s(a.currentBuffer$,e.currentBuffer$),s(a.loadedMetadata$,e.firstBytesEvent$),s(a.loadedMetadata$,e.loadedMetadataEvent$),s(a.playing$,e.firstFrameEvent$),s(a.canplay$,e.canplay$),s(a.seeked$,e.seekedEvent$),s(a.inPiP$,e.inPiP$),s(a.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe(Jb(o=>o.to)),this.params.output.playbackState$),this.subscription.add(qe(this.video,t.isLooped,r)),this.subscription.add(oe(this.video,t.volume,a.volumeState$,r)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Ie(this.video,t.playbackRate,a.playbackRateState$,r)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState("playing"),I(t.playbackState,"playing")},r)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),I(t.playbackState,"paused")},r)).add(a.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},r).add(a.loadedMetadata$.subscribe(()=>{let o=this.params.desiredState.seekState.getState(),c=this.videoState.getTransition(),u=this.params.desiredState.videoTrack.getTransition(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(u&&ww(u.to)){let l=u.to.id;this.params.desiredState.videoTrack.setState(u.to);let p=this.manifests$.getValue().find(h=>h.id===l);if(p){this.params.output.currentVideoTrack$.next(p),this.params.output.hostname$.next(Y(p.url));let h=this.params.desiredState.playbackRate.getState(),m=this.params.output.element$.getValue()?.playbackRate;if(h!==m){let b=this.params.output.element$.getValue();b&&(this.params.desiredState.playbackRate.setState(h),b.playbackRate=h)}}}d&&this.params.desiredState.autoVideoTrackSwitching.setState(d.to),c&&c.from==="changing_manifest"&&this.videoState.setState(c.to),o.state==="requested"&&this.seek(o.position)},r))),this.subscription.add(this.manifests$.pipe(Jb(o=>o.map(({id:c,quality:u,size:d,bandwidth:l,fps:p})=>({id:c,quality:u,size:d,fps:p,bitrate:l})))).subscribe(this.params.output.availableVideoTracks$,r)),!Cw.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add(Xb(Mu(o,"addtrack"),Mu(o,"removetrack"),Mu(o,"change"),Zb(["init"])).subscribe(()=>{for(let c=0;c<o.length;c++)o[c].mode="hidden"},r))}let n=Xb(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,Zb(["init"])).pipe(kw(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),ne(this.video)}prepare(){let e=this.selectManifest();if(Rw(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),r=this.params.desiredState.autoVideoTrackLimits.getState(),a=new URL(e.url);if((t||r)&&e.id===this.masterManifest.id){let{max:s,min:n}=t?.to??r??{};for(let[o,c]of[[s,"mq"],[n,"lq"]]){let u=String(parseFloat(o||""));c&&o&&a.searchParams.set(c,u)}}this.video.setAttribute("src",a.toString()),this.video.load()}playIfAllowed(){le(this.video).then(e=>{e||(this.videoState.setState("paused"),I(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Lu.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};import{assertNever as Dw,assertNonNullable as eg,debounce as Bw,ErrorCategory as tg,isHigher as Vw,isHigherOrEqual as Ow,isInvariantQuality as rg,isLowerOrEqual as _w,isNonNullable as Nw,merge as Fw,observableFrom as qw,Subscription as Uw,map as Hw}from"@vkontakte/videoplayer-shared";var Ji=class{constructor(e){this.subscription=new Uw;this.videoState=new L("stopped");this.trackUrls={};this.textTracksManager=new Ee;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.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"),I(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:c}=this.video;this.prepare(),o.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:c*1e3,forcePrecise:!0}),n.to&&this.params.desiredState.autoVideoTrackLimits.getState()?.max!==this.trackUrls[n.to.id]?.track?.quality&&this.params.output.autoVideoTrackLimits$.next({max:void 0});return}switch(r?.to!=="paused"&&o.state==="requested"&&this.seek(o.position),e){case"ready":t==="ready"?I(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),I(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?.to==="playing"&&I(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):r?.to==="paused"&&I(this.params.desiredState.playbackState,"paused");return;default:return Dw(e)}};this.params=e,this.video=se(e.container,e.tuning),this.params.output.element$.next(this.video),Object.entries(this.params.source).reverse().forEach(([t,r],a)=>{let s=a.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:tg.WTF,message:"MpegProvider internal logic error",thrown:o})},a=ue(this.video),s=(o,c)=>this.subscription.add(o.subscribe(c,r));s(a.timeUpdate$,e.position$),s(a.durationChange$,e.duration$),s(a.ended$,e.endedEvent$),s(a.looped$,e.loopedEvent$),s(a.error$,e.error$),s(a.isBuffering$,e.isBuffering$),s(a.currentBuffer$,e.currentBuffer$),s(a.loadedMetadata$,e.firstBytesEvent$),s(a.loadedMetadata$,e.loadedMetadataEvent$),s(a.playing$,e.firstFrameEvent$),s(a.canplay$,e.canplay$),s(a.seeked$,e.seekedEvent$),s(a.inPiP$,e.inPiP$),s(a.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe(Hw(o=>o.to)),this.params.output.playbackState$),this.subscription.add(qe(this.video,t.isLooped,r)),this.subscription.add(oe(this.video,t.volume,a.volumeState$,r)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Ie(this.video,t.playbackRate,a.playbackRateState$,r)),s(Pe(this.video),e.elementVisible$),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState("playing"),I(t.playbackState,"playing")},r)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),I(t.playbackState,"paused")},r)).add(a.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready");let o=this.params.desiredState.videoTrack.getTransition();if(o&&Nw(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(),u=this.params.output.element$.getValue()?.playbackRate;if(c!==u){let d=this.params.output.element$.getValue();d&&(this.params.desiredState.playbackRate.setState(c),d.playbackRate=c)}}this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.textTracksManager.connect(this.video,t,e);let n=Fw(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,qw(["init"])).pipe(Bw(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),ne(this.video)}prepare(){let e=this.params.desiredState.videoTrack.getState()?.id;eg(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];eg(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=Ni(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(Y(t))}playIfAllowed(){le(this.video).then(e=>{e||(this.videoState.setState("paused"),I(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:tg.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){let t,r=e;if(e&&this.params.output.currentVideoTrack$.getValue()?.quality!==e){let a=Object.values(this.trackUrls).find(o=>!rg(o.track.quality)&&_w(o.track.quality,e))?.track,s=this.params.desiredState.videoTrack.getState()?.id,n=this.trackUrls[s??"0"]?.track;if(a&&n&&Ow(n.quality,a.quality)&&(t=a),!t){let o=Object.values(this.trackUrls).filter(u=>!rg(u.track.quality)&&Vw(u.track.quality,e)),c=o.length;c&&(t=o[c-1].track)}t&&(r=t.quality)}else if(!e){let a=Object.values(this.trackUrls).map(s=>s.track);t=lt(a,{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 ag,debounce as Yw,merge as sg,observableFrom as Qw,Subscription as zw,map as ng,ValueSubject as Kw,ErrorCategory as Du,VideoQuality as Jw}from"@vkontakte/videoplayer-shared";import{ErrorCategory as jw}from"@vkontakte/videoplayer-shared";var ig=["stun:videostun.mycdn.me:80"],Gw=1e3,Ww=3,Cu=()=>null,ks=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=Cu;this.externalStopCallback=Cu;this.externalErrorCallback=Cu;this.options=this.normalizeOptions(t);let r=e.split("/");this.serverUrl=r.slice(0,r.length-1).join("/"),this.streamKey=r[r.length-1]}onStart(e){try{this.externalStartCallback=e}catch(t){this.handleSystemError(t)}}onStop(e){try{this.externalStopCallback=e}catch(t){this.handleSystemError(t)}}onError(e){try{this.externalErrorCallback=e}catch(t){this.handleSystemError(t)}}connect(){this.connectWS()}disconnect(){try{this.externalStopCallback(),this.closeConnections()}catch(e){this.handleSystemError(e)}}connectWS(){this.ws||(this.ws=new WebSocket(this.serverUrl),this.ws.onopen=this.onSocketOpen.bind(this),this.ws.onmessage=this.onSocketMessage.bind(this),this.ws.onclose=this.onSocketClose.bind(this),this.ws.onerror=this.onSocketError.bind(this))}onSocketOpen(){this.handleLogin()}onSocketClose(e){try{if(!this.ws)return;this.ws=null,e.code>1e3?(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():this.scheduleRetry()):this.externalStopCallback()}catch(t){this.handleRTCError(t)}}onSocketError(e){try{this.externalErrorCallback(new Error(e.toString()))}catch(t){this.handleRTCError(t)}}onSocketMessage(e){try{let t=this.parseMessage(e.data);switch(t.type){case"JOIN":case"CALL_JOIN":this.handleJoinMessage(t);break;case"UPDATE":this.handleUpdateMessage(t);break;case"STATUS":this.handleStatusMessage(t);break}}catch(t){this.handleRTCError(t)}}handleJoinMessage(e){switch(e.inviteType){case"ANSWER":this.handleAnswer(e.sdp);break;case"CANDIDATE":this.handleCandidate(e.candidate);break}}handleStatusMessage(e){switch(e.status){case"UNPUBLISHED":this.handleUnpublished();break}}async handleUpdateMessage(e){try{let t=await this.createOffer();this.peerConnection&&await this.peerConnection.setLocalDescription(t),this.handleAnswer(e.sdp)}catch(t){this.handleRTCError(t)}}async handleLogin(){try{let e={iceServers:[{urls:ig}]};this.peerConnection=new RTCPeerConnection(e),this.peerConnection.ontrack=this.onPeerConnectionStream.bind(this),this.peerConnection.onicecandidate=this.onPeerConnectionIceCandidate.bind(this),this.peerConnection.oniceconnectionstatechange=this.onPeerConnectionIceConnectionStateChange.bind(this);let t=await this.createOffer();await this.peerConnection.setLocalDescription(t),this.send({type:this.signalingType,inviteType:"OFFER",streamKey:this.streamKey,sdp:t.sdp,callSupport:!1})}catch(e){this.handleRTCError(e)}}async handleAnswer(e){try{this.peerConnection&&await this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e}))}catch(t){this.handleRTCError(t)}}async handleCandidate(e){if(e)try{this.peerConnection&&await this.peerConnection.addIceCandidate(e)}catch(t){this.handleRTCError(t)}}handleUnpublished(){try{this.closeConnections(),this.externalStopCallback()}catch(e){this.handleRTCError(e)}}handleSystemError(e){this.options.errorChanel&&this.options.errorChanel.next({id:"webrtc-provider-error",category:jw.WTF,message:e.message})}async onPeerConnectionStream(e){let t=e.streams[0];this.stream&&this.stream.id===t.id||(this.stream=t,this.externalStartCallback(this.stream))}onPeerConnectionIceCandidate(e){e.candidate&&this.send({type:this.signalingType,inviteType:"CANDIDATE",candidate:e.candidate})}onPeerConnectionIceConnectionStateChange(){if(this.peerConnection){let e=this.peerConnection.iceConnectionState;["failed","closed"].indexOf(e)>-1&&(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():(this.closeConnections(),this.scheduleRetry()))}}async createOffer(){let e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");let t=await this.peerConnection.createOffer(e),r=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(r))throw new Error("No h264 codec support error");return t}handleRTCError(e){try{this.externalErrorCallback(e||new Error("RTC connection error"))}catch(t){this.handleSystemError(t)}}handleNetworkError(){try{this.externalErrorCallback(new Error("Network error"))}catch(e){this.handleSystemError(e)}}send(e){this.ws&&this.ws.send(JSON.stringify(e))}parseMessage(e){try{return JSON.parse(e)}catch{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),Gw)}normalizeOptions(e={}){let t={stunServerList:ig,maxRetryNumber:Ww,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var Xi=class{constructor(e){this.videoState=new L("stopped");this.maxSeekBackTime$=new Kw(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"),I(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"),I(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?.to==="playing"&&I(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):r?.to==="paused"&&I(this.params.desiredState.playbackState,"paused");return;default:return ag(e)}};this.subscription=new zw,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=se(e.container,e.tuning),this.liveStreamClient=new ks(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),ne(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,r=n=>{e.error$.next({id:"WebRTCLiveProvider",category:Du.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};sg(this.videoState.stateChangeStarted$.pipe(ng(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe(ng(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})});let a=ue(this.video),s=(n,o)=>this.subscription.add(n.subscribe(o,r));s(a.timeUpdate$,e.liveTime$),s(a.ended$,e.endedEvent$),s(a.looped$,e.loopedEvent$),s(a.error$,e.error$),s(a.isBuffering$,e.isBuffering$),s(a.currentBuffer$,e.currentBuffer$),s(Pe(this.video),this.params.output.elementVisible$),this.subscription.add(a.durationChange$.subscribe(n=>{e.duration$.next(n===1/0?0:n)})).add(a.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready")},r)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused")},r)).add(a.playing$.subscribe(()=>{this.videoState.setState("playing")},r)).add(a.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(oe(this.video,t.volume,a.volumeState$,r)).add(a.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 ag(n.to)}},r)).add(sg(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,Qw(["init"])).pipe(Yw(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(Y(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:Jw.INVARIANT}),this.video.srcObject=e,I(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:Du.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){le(this.video).then(e=>{e||(this.videoState.setState("paused"),I(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Du.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var Zi=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 ra,assertNonNullable as ht,ErrorCategory as Rs,filter as aR,isNonNullable as pg,isNullable as sR,map as nR,merge as oR,once as uR,Subject as ge,Subscription as hg,ValueSubject as M,flattenObject as fg}from"@vkontakte/videoplayer-shared";import{Observable as Xw,map as og,Subscription as Zw,Subject as eR}from"@vkontakte/videoplayer-shared";var ug=i=>new Xw(e=>{let t=new Zw,r=i.desiredPlaybackState$.stateChangeStarted$.pipe(og(({from:u,to:d})=>`${u}-${d}`)),a=i.desiredPlaybackState$.stateChangeEnded$,s=i.providerChanged$.pipe(og(({type:u})=>u!==void 0)),n=new eR,o=0,c="unknown";return t.add(r.subscribe(u=>{o&&window.clearTimeout(o),c=u,o=window.setTimeout(()=>n.next(u),i.maxTransitionInterval)})),t.add(a.subscribe(()=>{window.clearTimeout(o),c="unknown",o=0})),t.add(s.subscribe(u=>{o&&(window.clearTimeout(o),o=0,u&&(o=window.setTimeout(()=>n.next(c),i.maxTransitionInterval)))})),t.add(n.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});import{ErrorCategory as cg,Subscription as tR,combine as rR,filter as lg,once as dg}from"@vkontakte/videoplayer-shared";var ea=null,ws=null;function Bu(){return ea||(ea=new(window.AudioContext||window.webkitAudioContext)),ws||(ws=new GainNode(ea,{gain:1}),ws.connect(ea.destination)),{audioCtx:ea,gainNode:ws}}import{clientChecker as iR}from"@vkontakte/videoplayer-shared";var ta=class i{constructor(e,t,r,a,s){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=r;this.volumeMultiplier=a;this.subscriptions=new tR;this.lastAudioContextResumeId=0;!s||!this.isSupported()||a===1||this.subscriptions.add(this.provider$.pipe(lg(n=>!!n.type),dg()).subscribe(({type:n})=>this.subscribe(n)))}static{this.errorId="VolumeMultiplierManager"}subscribe(e){iR.isSafari&&e!=="MPEG"||this.subscriptions.add(rR({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe(lg(({playbackState:t,video:r,volume:{muted:a,volume:s}})=>t==="playing"&&!!r&&!a&&!!s),dg()).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:a}=Bu(),s=(Math.random()+1)*999999;this.lastAudioContextResumeId=s,r.resume().then(()=>{if(s!==this.lastAudioContextResumeId)throw new Error(`AudioContext.resume() resolved after ${i.errorId} destroyed`);a.gain.value=t;try{new MediaElementAudioSourceNode(r,{mediaElement:e}).connect(a)}catch(n){this.volumeMultiplierError$.next({id:i.errorId,category:cg.VIDEO_PIPELINE,message:n?.message??"initAudioContextOnce: (new MediaElementAudioSourceNode).connect() exception",thrown:n})}}).catch(n=>{this.volumeMultiplierError$.next({id:i.errorId,category:cg.VIDEO_PIPELINE,message:n?.message??"initAudioContextOnce: AudioContext.resume() exception",thrown:n})})}destroy(){let{gainNode:e}=Bu();e.gain.value=1,this.subscriptions.unsubscribe(),this.lastAudioContextResumeId=0}};var cR={chunkDuration:5e3,maxParallelRequests:5},ia=class{constructor(e){this.current$=new M({type:void 0});this.providerError$=new ge;this.noAvailableProvidersError$=new ge;this.volumeMultiplierError$=new ge;this.providerOutput={position$:new M(0),duration$:new M(1/0),volume$:new M({muted:!1,volume:1}),availableVideoStreams$:new M([]),currentVideoStream$:new M(void 0),availableVideoTracks$:new M([]),currentVideoTrack$:new M(void 0),availableAudioStreams$:new M([]),currentAudioStream$:new M(void 0),availableAudioTracks$:new M([]),currentVideoSegmentLength$:new M(0),currentAudioSegmentLength$:new M(0),isAudioAvailable$:new M(!0),autoVideoTrackLimitingAvailable$:new M(!1),autoVideoTrackLimits$:new M(void 0),currentBuffer$:new M(void 0),isBuffering$:new M(!0),error$:new ge,warning$:new ge,willSeekEvent$:new ge,seekedEvent$:new ge,loopedEvent$:new ge,endedEvent$:new ge,firstBytesEvent$:new ge,loadedMetadataEvent$:new ge,firstFrameEvent$:new ge,canplay$:new ge,isLive$:new M(void 0),isLowLatency$:new M(!1),canChangePlaybackSpeed$:new M(!0),liveTime$:new M(void 0),liveBufferTime$:new M(void 0),availableTextTracks$:new M([]),currentTextTrack$:new M(void 0),hostname$:new M(void 0),httpConnectionType$:new M(void 0),httpConnectionReused$:new M(void 0),inPiP$:new M(!1),inFullscreen$:new M(!1),element$:new M(void 0),elementVisible$:new M(!0),availableSources$:new M(void 0),is3DVideo$:new M(!1),playbackState$:new M("")};this.subscription=new hg;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer"),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name);let t=Cm([...Bm(this.params.tuning),...Dm(this.params.tuning)],this.params.tuning.useHlsJs,this.params.tuning.useManagedMediaSource).filter(o=>pg(e.sources[o])),{forceFormat:r,formatsToAvoid:a}=this.params.tuning,s=[];r?s=[r]:a.length?s=[...t.filter(o=>!a.includes(o)),...t.filter(o=>a.includes(o))]:s=t,this.log({message:`Selected formats: ${s.join(" > ")}`}),this.tracer.log("Selected formats",fg(s)),this.screenFormatsIterator=new Zi(s);let n=[...Zo(!0),...Zo(!1)];this.chromecastFormatsIterator=new Zi(n.filter(o=>pg(e.sources[o]))),this.providerOutput.availableSources$.next(e.sources),this.volumeMultiplierManager=new ta(this.providerOutput,this.current$,this.volumeMultiplierError$,this.params.volumeMultiplier??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(sR(t)){this.handleNoFormatsError(e);return}let r;try{r=this.createProvider(e,t)}catch(a){this.providerError$.next({id:"ProviderNotConstructed",category:Rs.WTF,message:"Failed to create provider",thrown:a})}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(),a=r.state!=="none";if(this.params.desiredState.seekState.setState({state:"requested",position:a?r.position:t,forcePrecise:a?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 ra(e)}}createScreenProvider(e){let{sources:t,container:r,desiredState:a}=this.params,s=this.providerOutput,n={container:r,source:null,desiredState:a,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]),c=this.applyFailoverHost(t.HLS_ONDEMAND||t.HLS);return ht(o),new Gi({...n,source:o,sourceHls:c})}case"DASH_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return ht(o),new Wi({...n,source:o})}case"HLS":case"HLS_ONDEMAND":{let o=this.applyFailoverHost(t[e]);return ht(o),mr||!this.params.tuning.useHlsJs?new Ki({...n,source:o}):new Qi({...n,source:o})}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return ht(o),new zi({...n,source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case"MPEG":{let o=this.applyFailoverHost(t[e]);return ht(o),new Ji({...n,source:o})}case"DASH_LIVE":{let o=this.applyFailoverHost(t[e]);return ht(o),new Pm({...n,source:o,config:{...cR,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case"WEB_RTC_LIVE":{let o=this.applyFailoverHost(t[e]);return ht(o),new Xi({container:r,source:o,desiredState:a,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 ra(e)}}createChromecastProvider(e){let{sources:t,container:r,desiredState:a,meta:s}=this.params,n=this.providerOutput,o=this.params.dependencies.chromecastInitializer.connection$.getValue();return ht(o),new ei({connection:o,meta:s,container:r,source:t,format:e,desiredState:a,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 ra(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return ra(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 ra(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;let t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;let r=a=>{let s=new URL(a);return s.host=t,s.toString()};if(e===void 0)return e;if("type"in e){if(e.type==="raw")return e;if(e.type==="url")return{...e,url:r(e.url)}}return(0,mg.default)(Object.entries(e).map(([a,s])=>[a,r(s)]))}initProviderErrorHandling(){let e=new hg,t=!1,r=0;return e.add(oR(this.providerOutput.error$,ug({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(nR(a=>({id:`ProviderHangup:${a}`,category:Rs.WTF,message:`A ${a} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;let a=this.params.desiredState.playbackState.transitionEnded$.pipe(aR(({to:s})=>s==="playing"),uR()).subscribe(()=>t=!0);e.add(a)})),e.add(this.providerError$.subscribe(a=>{let s=this.current$.getValue().destination,n={error:a,currentDestination:s};if(s==="CHROMECAST")this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider("SCREEN"),()=>this.params.dependencies.chromecastInitializer.disconnect());else{let o=a.category===Rs.NETWORK,c=a.category===Rs.FATAL,u=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),d=r<this.params.tuning.providerErrorLimit&&!c,l=u&&!c&&(o&&t||!d);n={...n,isNetworkError:o,isFatalError:c,haveFailoverHost:u,tryFailover:l,canReinitProvider:d},l?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):d?(r++,this.reinitProvider()):this.switchToNextProvider(s??"SCREEN")}this.tracer.error("providerError",fg(n))})),e}};import{fromEvent as $s,once as lR,combine as dR,Subscription as bg,ValueSubject as Vu,map as pR,filter as hR,isNonNullable as Ls,now as Se,safeStorage as Ou}from"@vkontakte/videoplayer-shared";var fR=5e3,gg="one_video_throughput",Sg="one_video_rtt",aa=window.navigator.connection,vg=()=>{let i=aa?.downlink;if(Ls(i)&&i!==10)return i*1e3},yg=()=>{let i=aa?.rtt;if(Ls(i)&&i!==3e3)return i},Tg=(i,e,t)=>{let r=t*8,a=r/i;return r/(a+e)},_u=class i{constructor(e){this.subscription=new bg;this.concurrentDownloads=new Set;this.tuningConfig=e;let t=i.load(gg)||(e.useBrowserEstimation?vg():void 0)||fR,r=i.load(Sg)??(e.useBrowserEstimation?yg():void 0)??0;if(this.throughput$=new Vu(t),this.rtt$=new Vu(r),this.rttAdjustedThroughput$=new Vu(Tg(t,r,e.rttPenaltyRequestSize)),this.throughput=Nt.getSmoothedValue(t,-1,e),this.rtt=Nt.getSmoothedValue(r,1,e),e.useBrowserEstimation){let a=()=>{let n=vg();n&&this.throughput.next(n);let o=yg();Ls(o)&&this.rtt.next(o)};aa&&"onchange"in aa&&this.subscription.add($s(aa,"change").subscribe(a)),a()}this.subscription.add(this.throughput.smoothed$.subscribe(a=>{Ou.set(gg,a.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(a=>{Ou.set(Sg,a.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(dR({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(pR(({throughput:a,rtt:s})=>Tg(a,s,e.rttPenaltyRequestSize)),hR(a=>{let s=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(a-s)/s>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,r=Se(),a=new bg;switch(this.subscription.add(a),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:a.add($s(e,"progress").pipe(lR()).subscribe(s=>{t=s.loaded,r=Se()}));break;case 1:case 0:a.add($s(e,"loadstart").subscribe(()=>{t=0,r=Se()}));break}a.add($s(e,"loadend").subscribe(s=>{if(e.status===200){let n=s.loaded,o=Se(),c=n-t,u=o-r;this.addRawSpeed(c,u,1)}this.concurrentDownloads.delete(e),a.unsubscribe()}))}trackStream(e,t=!1){let r=e.getReader();if(!r){e.cancel("Could not get reader");return}let a=0,s=Se(),n=0,o=Se(),c=d=>{this.concurrentDownloads.delete(e),r.releaseLock(),e.cancel(`Throughput Estimator error: ${d}`).catch(()=>{})},u=async({done:d,value:l})=>{if(d)!t&&this.addRawSpeed(a,Se()-s,1),this.concurrentDownloads.delete(e);else if(l){if(t){let p=Se();if(p-o>this.tuningConfig.lowLatency.continuesByteSequenceInterval||p-s>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let m=o-s;m&&this.addRawSpeed(n,m,1,t),n=l.byteLength,s=Se()}else n+=l.byteLength;o=Se()}else a+=l.byteLength,n+=l.byteLength,n>=this.tuningConfig.streamMinSampleSize&&Se()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,Se()-o,this.concurrentDownloads.size),n=0,o=Se());await r?.read().then(u,c)}};this.concurrentDownloads.add(e),r?.read().then(u,c)}addRawSpeed(e,t,r=1,a=!1){if(i.sanityCheck(e,t,a)){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 a=e*8/t;return!(!a||!isFinite(a)||a>1e6||a<30||r&&e<1e4||!r&&e<10*1024||!r&&t<=20)}static load(e){let t=Ou.get(e);if(Ls(t))return parseInt(t,10)??void 0}},Ig=_u;import{fillWithDefault as mR,VideoQuality as Eg}from"@vkontakte/videoplayer-shared";var xg={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:Eg.Q_4320P,activeVideoAreaThreshold:.1},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:Eg.Q_480P},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,maxSegmentDurationLeftToSelectNextSegment:3e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:3e3,crashOnStallTimeout:25e3,enableSubSegmentBufferFeeding:!0,segmentTimelineTolerance:100,useFetchPriorityHints:!0},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:250,playbackCatchupSpeedup:.05,isActive:!1,delayEstimator:{emaAlpha:.45,changeThreshold:.05,deviationDepth:20,deviationFactor:.5,extremumInterval:5}}},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1,lowLatencyActiveLiveDelay:3e3,activeLiveDelay:5e3,maxPausedTime:5e3},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,forceFormat:void 0,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:void 0,useWebmBigRequest:!1,webmCodec:"vp9",androidPreferredFormat:"mpeg",preferCMAF:!1,preferWebRTC:!1,preferMultiStream:!1,preferHDR:!1,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,accumulationBufferStallSizeMs:0,requestQuick:!1,useHlsJs:!0,useNativeHLSTextTracks:!1,useManagedMediaSource:!1,useNewPruneBufferStrategy:!1,useNewPartialSegmentFeeding:!1,useSeparateAudioVideoABR:!1,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,manifestRetryInterval:300,manifestRetryMaxInterval:1e4,manifestRetryMaxCount:10,audioVideoSyncRate:20,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50},useVolumeMultiplier:!1},Pg=i=>({...mR(i,xg),configName:[...i.configName??[],...xg.configName]});import{assertNonNullable as Ms,combine as ft,ErrorCategory as Cs,filter as ee,filterChanged as V,fromEvent as Fu,isNonNullable as IR,isNullable as ER,Logger as xR,map as C,mapTo as Rg,merge as mt,now as Ds,once as et,Subject as F,Subscription as $g,tap as Lg,ValueSubject as P,isHigher as PR,isInvariantQuality as Mg,flattenObject as bt,throttle as qu,getTraceSubscriptionMethod as Cg,Tracer as AR}from"@vkontakte/videoplayer-shared";import{merge as bR,map as gR,filter as Ag,isNonNullable as SR}from"@vkontakte/videoplayer-shared";var Nu=({seekState:i,position$:e})=>bR(i.stateChangeEnded$.pipe(gR(({to:t})=>t.state==="none"?void 0:(t.position??NaN)/1e3),Ag(SR)),e.pipe(Ag(()=>i.getState().state==="none")));import{assertNonNullable as vR}from"@vkontakte/videoplayer-shared";var kg=i=>{let e=typeof i.container=="string"?document.getElementById(i.container):i.container;return vR(e,`Wrong container or containerId {${i.container}}`),e};import{filter as yR,once as TR}from"@vkontakte/videoplayer-shared";var wg=(i,e,t,r)=>{i!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&t?.getValue().length===0?t.pipe(yR(a=>a.length>0),TR()).subscribe(a=>{a.find(r)&&e.startTransitionTo(i)}):(i===void 0||t?.getValue().find(r))&&e.startTransitionTo(i)};var Bs=class{constructor(e={configName:[]},t=AR.createRootTracer(!1)){this.subscription=new $g;this.logger=new xR;this.abrLogger=this.logger.createComponentLog("ABR");this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new P(!1);this.hasLiveOffsetByPausedTimer=0;this.desiredState={playbackState:new L("stopped"),seekState:new L({state:"none"}),volume:new L({volume:1,muted:!1}),videoTrack:new L(void 0),videoStream:new L(void 0),audioStream:new L(void 0),autoVideoTrackSwitching:new L(!0),autoVideoTrackLimits:new L({}),isLooped:new L(!1),playbackRate:new L(1),externalTextTracks:new L([]),internalTextTracks:new L([]),currentTextTrack:new L(void 0),textTrackCuesSettings:new L({}),cameraOrientation:new L({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 F,ready$:new F,started$:new F,playing$:new F,paused$:new F,stopped$:new F,willStart$:new F,willResume$:new F,willPause$:new F,willStop$:new F,willDestruct$:new F,watchCoverageRecord$:new F,watchCoverageLive$:new F,managedError$:new F,fatalError$:new F,ended$:new F,looped$:new F,seeked$:new F,willSeek$:new F,firstBytes$:new F,loadedMetadata$:new F,firstFrame$:new F,canplay$:new F,log$:new F};this.experimental={element$:new P(void 0),tuningConfigName$:new P([]),enableDebugTelemetry$:new P(!1),dumpTelemetry:am};if(this.initLogs(),this.tuning=Pg(e),this.tracer=t,this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new pa({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new Ig(this.tuning.throughputEstimator),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(r,a,s)=>{let n=Reflect.get(r,a,s);return typeof n!="function"?n:(...o)=>{try{return n.apply(r,o)}catch(c){let u=o.map(p=>JSON.stringify(p,(h,m)=>{let b=typeof m;return["number","string","boolean"].includes(b)?m:m===null?null:`<${b}>`})),d=`Player.${String(a)}`,l=`Exception calling ${d} (${u.join(", ")})`;throw this.events.fatalError$.next({id:d,category:Cs.WTF,message:l,thrown:c}),c}}}})}initVideo(e){this.config=e;let{container:t,...r}=e;return this.tracer.log("initVideo",bt(r)),this.domContainer=kg(e),this.chromecastInitializer.contentId=e.meta?.videoId,this.providerContainer=new ia({sources:e.sources,meta:e.meta??{},failoverHosts:e.failoverHosts??[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,tracer:this.tracer,logger:this.logger,abrLogger:this.abrLogger},tuning:this.tuning,volumeMultiplier:e.volumeMultiplier}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.initTracerSubscription(),this.providerContainer.init(),this.setMuted(this.tuning.isAudioDisabled),this.initDebugTelemetry(),this.initWakeLock(),this}destroy(){this.tracer.log("destroy"),window.clearTimeout(this.hasLiveOffsetByPausedTimer),this.events.willDestruct$.next(),this.stop(),this.providerContainer?.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&&!li()?(this.tracer.log("request play from hidden tab"),Fu(document,"visibilitychange").pipe(et()).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(),a=this.info.isLive$.getValue(),s=e;return e>=r&&!a&&(s=r-.1),this.tracer.log("seekTime",{duration:r,isLive:a,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){Ms(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(ee(r=>r.length>0),et()).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){Ms(this.providerContainer);let t=this.providerContainer?.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=>({type:"external",...t}))),this}selectTextTrack(e){return wg(e,this.desiredState.currentTextTrack,this.providerContainer?.providerOutput.availableTextTracks$,t=>t.id===e),this.tracer.log("selectTextTrack",{textTrackId:e}),this}setTextTrackCueSettings(e){return this.tracer.log("setTextTrackCueSettings",{...e}),this.desiredState.textTrackCuesSettings.startTransitionTo(e),this}setLooped(e){return this.tracer.log("setLooped",{isLooped:e}),this.desiredState.isLooped.startTransitionTo(e),this}toggleChromecast(){this.tracer.log("toggleChromecast"),this.chromecastInitializer.toggleConnection()}startCameraManualRotation(e,t){let r=this.getScene3D();return this.tracer.log("startCameraManualRotation",{isScene3DAvailable:!!r,mx:e,my:t}),r&&r.startCameraManualRotation(e,t),this}stopCameraManualRotation(e=!1){let t=this.getScene3D();return this.tracer.log("stopCameraManualRotation",{isScene3DAvailable:!!t,immediate:e}),t&&t.stopCameraManualRotation(e),this}moveCameraFocusPX(e,t){let r=this.getScene3D();if(this.tracer.log("moveCameraFocusPX",{isScene3DAvailable:!!r,dxpx:e,dypx:t}),r){let a=r.getCameraRotation(),s=r.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:a.x+s.x,y:a.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(ER(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),r=t.state==="none"?void 0:t.position;return IR(r)?r/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}getScene3D(){let e=this.providerContainer?.current$.getValue();if(e?.provider?.scene3D)return e.provider.scene3D}setIntrinsicVideoSize(...e){let t={width:e.reduce((r,{width:a})=>r||a||0,0),height:e.reduce((r,{height:a})=>r||a||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add(mt(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(C(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(C(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(C(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(C(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(C(e=>e.to)).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(ee(({from:e})=>e==="stopped"),et()).subscribe(()=>{this.initedAt=Ds(),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({...n,state:"applying"}):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:Cs.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(C(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(C(n=>n.destination),V()).subscribe(()=>this.isPlaybackStarted=!1)).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add(e.providerOutput.availableVideoTracks$.pipe(C(n=>n.map(({quality:o})=>o).sort((o,c)=>Mg(o)?1:Mg(c)?-1:PR(c,o)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(n=>{let o={};for(let c of n)c.fps&&(o[c.quality]=c.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(V()).subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{this.info.currentQuality$.next(n?.quality),this.info.videoBitrate$.next(n?.bitrate)})).add(e.providerOutput.currentVideoSegmentLength$.pipe(V((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.pipe(V((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe(V()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(V()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(V()).subscribe(this.info.httpConnectionReused$)).add(e.providerOutput.currentTextTrack$.subscribe(this.info.currentTextTrack$)).add(e.providerOutput.availableTextTracks$.subscribe(this.info.availableTextTracks$)).add(e.providerOutput.autoVideoTrackLimitingAvailable$.subscribe(this.info.autoQualityLimitingAvailable$)).add(e.providerOutput.autoVideoTrackLimits$.subscribe(n=>{this.desiredState.autoVideoTrackLimits.setState(n??{})})).add(e.providerOutput.currentBuffer$.pipe(C(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(ft({hasLiveOffsetByPaused:mt(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(C(n=>n.to),V(),C(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(ft({atLiveEdge:ft({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:Nu({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(C(({isLive:n,position:o,isLowLatency:c})=>{let u=this.getActiveLiveDelay(c);return n&&Math.abs(o)<u/1e3}),V(),Lg(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(C(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add(ft({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(C(({isLive:n,position:o,duration:c})=>n&&(Math.abs(c)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),V(),Lg(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(C(n=>n.muted),V()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(C(n=>n.volume),V()).subscribe(this.info.volume$)).add(Nu({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(mt(e.providerOutput.endedEvent$.pipe(Rg(!0)),e.providerOutput.seekedEvent$.pipe(Rg(!1))).pipe(V()).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(C(n=>({id:n?`No${n}`:"NoProviders",category:Cs.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(et(),C(n=>n??Ds()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe(et(),C(()=>Ds()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(et(),C(()=>Ds()-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(ee(({to:n})=>n==="playing"),et()).subscribe(()=>r.next(!1)));let a=0,s=mt(e.providerOutput.isBuffering$,t,r).pipe(C(()=>{let n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||r.getValue();return n&&!o}),V());this.subscription.add(s.subscribe(n=>{n?a=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(a),this.info.isStalled$.next(!1))})),this.subscription.add(mt(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{let n=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:n?.videoWidth,height:n?.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{let o=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:n?.size?.width,height:n?.size?.height},{width:o?.videoWidth,height:o?.videoHeight})})).add(e.providerOutput.is3DVideo$.subscribe(this.info.is3DVideo$)),this.subscription.add(mt(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(),c=e.providerOutput.element$.getValue(),u=e.providerOutput.elementVisible$.getValue(),d=this.chromecastInitializer.castState$.getValue(),l;d==="CONNECTED"?l="second_screen":c?u?n?l="pip":o?l="fullscreen":l="inline":l="invisible":l="none",this.info.surface$.getValue()!==l&&this.info.surface$.next(l)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(C(e=>e?.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){let t=new $g;this.subscription.add(t),this.subscription.add(e.current$.pipe(V((r,a)=>r.provider===a.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(ee(r=>r.length>0),et()).subscribe(r=>{this.setStartingVideoTrack(r)}))}))}setStartingVideoTrack(e){let t,r=this.desiredState.videoTrack.getState()?.quality;r&&(t=e.find(({quality:a})=>a===r),t||this.setAutoQuality(!0)),t||(t=lt(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(mt(this.desiredState.videoTrack.stateChangeStarted$.pipe(C(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(C(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(C(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(C(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(C(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(C(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(C(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(C(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(C(e=>({component:"desiredState",message:`[${e.entity} change] ${e.type}: ${JSON.stringify(e.transition)}`}))).subscribe(this.logger.log)),this.subscription.add(this.logger.log$.subscribe(this.events.log$))}initDebugTelemetry(){let e=this.providerContainer?.providerOutput;Ms(this.providerContainer),Ms(e),im(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(t=>rm(t)),this.providerContainer.current$.subscribe(({type:t})=>ai("provider",t)),e.duration$.subscribe(t=>ai("duration",t)),e.availableVideoTracks$.pipe(ee(t=>!!t.length),et()).subscribe(t=>ai("tracks",t)),this.events.fatalError$.subscribe(new X("fatalError")),this.events.managedError$.subscribe(new X("managedError")),e.position$.subscribe(new X("position")),e.currentVideoTrack$.pipe(C(t=>t?.quality)).subscribe(new X("quality")),this.info.currentBuffer$.subscribe(new X("buffer")),e.isBuffering$.subscribe(new X("isBuffering"))].forEach(t=>this.subscription.add(t)),ai("codecs",Mm())}initTracerSubscription(){let e=Cg(this.tracer.log.bind(this.tracer)),t=Cg(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(V()).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(ft({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe(ee(({currentQuality:r,videoBitrate:a})=>!!r&&!!a),V((r,a)=>r.currentQuality===a.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe(ee(r=>r>0),V()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe(ee(r=>r>0),V()).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(ft({currentBuffer:this.info.currentBuffer$.pipe(ee(r=>r.end>0),V((r,a)=>r.end===a.end&&r.start===a.start)),position:this.info.position$.pipe(V())}).pipe(qu(1e3)).subscribe(e("currentBufferAndPosition"))).add(this.info.duration$.pipe(V()).subscribe(e("duration"))).add(this.info.isBuffering$.subscribe(e("isBuffering"))).add(this.info.isLive$.pipe(V()).subscribe(e("isLive"))).add(this.info.canChangePlaybackSpeed$.pipe(V()).subscribe(e("canChangePlaybackSpeed"))).add(ft({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe(ee(({liveTime:r,liveBufferTime:a})=>!!r&&!!a),qu(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe(V(),ee(r=>r===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe(V(),ee(r=>r===!0)).subscribe(e("atLiveDurationEdge"))).add(this.info.muted$.pipe(V()).subscribe(e("muted"))).add(this.info.volume$.pipe(V()).subscribe(e("volume"))).add(this.info.isEnded$.pipe(V(),ee(r=>r===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add(ft({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe(ee(({throughputEstimation:r,rtt:a})=>!!r&&!!a),qu(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe(V(),ee(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?.release(),e=void 0},r=async()=>{t(),e=await window.navigator.wakeLock.request("screen").catch(a=>{a instanceof DOMException&&a.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:Cs.DOM,message:String(a)})})};this.subscription.add(mt(Fu(document,"visibilitychange"),Fu(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{let a=document.visibilityState==="visible",s=this.desiredState.playbackState.getState()==="playing",n=!!e&&!e?.released;a&&s?n||r():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){let r=e.find(a=>a.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 cj,Observable as lj,Subject as dj,ValueSubject as pj,VideoQuality as hj}from"@vkontakte/videoplayer-shared";var fj=`@vkontakte/videoplayer-core@${ju}`;export{la as ChromecastState,Hs as HttpConnectionType,lj as Observable,ie as PlaybackState,Bs as Player,fj as SDK_VERSION,dj as Subject,cj as Subscription,js as Surface,ju as VERSION,pj as ValueSubject,at as VideoFormat,hj as VideoQuality};
112
+ `;var Ls=class{constructor(e,t,r){this.videoInitialized=!1;this.active=!1;this.container=e,this.sourceVideoElement=t,this.params=r,this.canvas=this.createCanvas();let a=this.canvas.getContext("webgl");if(!a)throw new Error("Could not initialize WebGL context");this.gl=a,this.container.appendChild(this.canvas),this.camera=new Rs(this.params.fov,this.params.orientation),this.cameraRotationManager=new $s(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"),a=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(a,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(jb,this.gl.VERTEX_SHADER),r=this.createShader(Gb,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,a=this.frameHeight/(this.frameWidth/this.viewportWidth);return a>this.viewportHeight?t=this.viewportHeight/a:r=a/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,a=this.camera.fov.y/180/2,s=e-r,n=t-a,o=e+r,c=t-a,u=e+r,d=t+a,l=e-r,p=t+a;return[s,n,o,c,u,d,l,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 Kt=class{constructor(e){this.subscription=new rw;this.videoState=new L("stopped");this.elementSize$=new iw(void 0);this.droppedFramesManager=new ds;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new fi;this.audioTrackSwitchHistory=new fi;this.textTracks=[];this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(a.state==="requested"&&r?.to!=="paused"&&e!=="stopped"&&t!=="stopped"){let n=this.liveOffset?.getTotalPausedTime()??0;this.seek(a.position-n,a.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"),I(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"),I(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):r?.to==="ready"&&I(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.liveOffset?.pause(),this.video.paused?this.videoState.setState("paused"):this.video.pause()):r?.to==="playing"&&I(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?.to==="paused"&&I(this.params.desiredState.playbackState,"paused");return;default:return zk(e)}}};this.init3DScene=e=>{if(this.scene3D)return;this.scene3D=new Ls(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:e.projectionData?.pose.yaw||0,y:e.projectionData?.pose.pitch||0,z:e.projectionData?.pose.roll||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});let t=this.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=oe(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(Q(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.player=new ws({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=le(this.video),a=this.constructor.name,s=o=>{e.error$.next({id:a,category:Lu.WTF,message:`${a} internal logic error`,thrown:o})};return{output:e,desiredState:t,observableVideo:r,genericErrorListener:s,connect:(o,c)=>this.subscription.add(o.subscribe(c,s))}}subscribe(){let{output:e,desiredState:t,observableVideo:r,genericErrorListener:a,connect:s}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe(Wb(u=>!!u.length),Qb()).subscribe(u=>{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:u})})),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(Wb(Zk),Qb()),e.firstBytesEvent$),s(this.videoState.stateChangeEnded$.pipe(Yb(u=>u.to)),this.params.output.playbackState$),this.subscription.add(r.seeked$.subscribe(e.seekedEvent$,a)),this.subscription.add(Qe(this.video,t.isLooped,a)),this.subscription.add(ce(this.video,t.volume,r.volumeState$,a)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,a)),this.subscription.add(Pe(this.video,t.playbackRate,r.playbackRateState$,a)),s(tw(this.video),this.elementSize$),s(ke(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),I(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},a)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),I(t.playbackState,"paused")},a)).add(r.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},a)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:u})=>{if(u==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map;let d=this.player.getStreams();if(Kk(d,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let p=[];for(let h of d.audio){p.push(yu(h));let m=[];for(let b of h.representations){let g=$b(b);m.push(g),this.audioTracksMap.set(g,{stream:h,representation:b})}this.audioStreamsMap.set(h,m)}this.params.output.availableAudioStreams$.next(p)}let l=[];for(let p of d.video){l.push(Tu(p));let h=[];for(let m of p.representations){let b=Rb(m);b&&(h.push(b),this.videoTracksMap.set(b,{stream:p,representation:m}))}this.videoStreamsMap.set(p,h)}this.params.output.availableVideoStreams$.next(l),this.params.output.availableVideoTracks$.next(Array.from(this.videoTracksMap.keys())),this.params.output.availableAudioTracks$.next(Array.from(this.audioTracksMap.keys())),this.params.output.isAudioAvailable$.next(!!this.audioTracksMap.size)}else u==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},a));let n=u=>e.error$.next({id:"RepresentationSwitch",category:Lu.WTF,message:"Switching representations threw",thrown:u});this.subscription.add(Ms(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$,Xk(this.video,"progress")).subscribe(()=>{let u=this.player.state$.getState(),d=this.player.state$.getTransition();if(!["manifest_ready","running"].includes(u)||d)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let l=this.selectVideoAudioRepresentations();if(!l)return;let[p,h]=l,m=this.params.desiredState.autoVideoTrackLimits.getTransition();if(m&&this.params.output.autoVideoTrackLimits$.next(m.to),u==="manifest_ready")this.player.initRepresentations(p.id,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)}},a)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:u})=>{this.scene3D&&u&&this.scene3D.pointCameraTo(u.x,u.y)})),this.subscription.add(this.elementSize$.subscribe(u=>{this.scene3D&&u&&this.scene3D.setViewportSize(u.width,u.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(Mu()).subscribe(u=>{let d=[...this.videoTracksMap.entries()].find(([,{representation:m}])=>m.id===u);if(!d){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[l,{stream:p}]=d,h=this.params.desiredState.videoStream.getTransition();h&&h.to&&h.to.id===p.id&&this.params.desiredState.videoStream.setState(h.to),e.currentVideoTrack$.next(l),e.currentVideoStream$.next(Tu(p))},a)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(Mu()).subscribe(u=>{let d=[...this.audioTracksMap.entries()].find(([,{representation:m}])=>m.id===u);if(!d){e.currentAudioStream$.next(void 0);return}let[l,{stream:p}]=d,h=this.params.desiredState.audioStream.getTransition();h&&h.to&&h.to.id===p.id&&this.params.desiredState.audioStream.setState(h.to),e.currentAudioStream$.next(yu(p))},a)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(u=>{if(u?.is3dVideo&&this.params.tuning.spherical?.enabled)try{this.init3DScene(u),e.is3DVideo$.next(!0)}catch(d){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${d}`})}else this.destroy3DScene(),this.params.tuning.spherical?.enabled&&e.is3DVideo$.next(!1)},a)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,a)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,a));let o=t.playbackState.stateChangeStarted$.pipe(Yb(({to:u})=>u==="ready"),Mu());this.subscription.add(Ms(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$).subscribe(()=>{let u=t.autoVideoTrackSwitching.getState(),l=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:u?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(l)})),this.subscription.add(Ms(o,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let c=Ms(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,ew(["init"])).pipe(Jk(0));this.subscription.add(c.subscribe(this.syncPlayback,a))}selectVideoAudioRepresentations(){let{desiredState:e,output:t}=this.params,r=e.autoVideoTrackSwitching.getState(),a=e.videoTrack.getState()?.id,n=[...this.videoTracksMap.keys()].find(({id:E})=>E===a),o=t.currentVideoTrack$.getValue(),c=e.videoStream.getState()??(n&&this.videoTracksMap.get(n)?.stream)??this.videoStreamsMap.size===1?this.videoStreamsMap.keys().next().value:void 0;if(!c)return;let u=[...this.videoStreamsMap.keys()].find(({id:E})=>E===c.id),d=u&&this.videoStreamsMap.get(u);if(!d)return;let l=st(this.video.buffered,this.video.currentTime*1e3),p=r?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,h=Math.min(l/Math.min(p,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),m=e.audioStream.getState()??(this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0),b=[...this.audioStreamsMap.keys()].find(({id:E})=>E===m?.id)??this.audioStreamsMap.keys().next().value,g=0;if(b){if(n&&!r)if(this.params.tuning.useSeparateAudioVideoABR){let E=os(n,d,this.audioStreamsMap.get(b)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);g=Math.max(g,E?.bitrate??-1/0)}else{let E=ys(n,d,this.audioStreamsMap.get(b)??[]);g=Math.max(g,E?.bitrate??-1/0)}if(o)if(this.params.tuning.useSeparateAudioVideoABR){let E=os(o,d,this.audioStreamsMap.get(b)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);g=Math.max(g,E?.bitrate??-1/0)}else{let E=ys(o,d,this.audioStreamsMap.get(b)??[]);g=Math.max(g,E?.bitrate??-1/0)}}let v=yt(d,{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}),k=r?v??n:n??v,y;this.params.tuning.useSeparateAudioVideoABR?y=b&&ym(k,d,this.audioStreamsMap.get(b)??[],{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}):y=b&&ys(k,d,this.audioStreamsMap.get(b)??[]);let S=this.videoTracksMap.get(k)?.representation,T=y&&this.audioTracksMap.get(y)?.representation;if(S&&T)return[S,T];if(S&&!T&&this.audioTracksMap.size===0)return[S,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){pe(this.video).then(e=>{e||(this.liveOffset?.pause(),this.videoState.setState("paused"),I(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Lu.DOM,thrown:e}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.destroy3DScene(),this.player.destroy(),this.params.output.element$.next(void 0),ue(this.video),this.tracer.end()}};var ta=class extends Kt{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 zb,interval as aw,map as sw}from"@vkontakte/videoplayer-shared";var ra=class extends Kt{constructor(e){super(e),this.liveOffset=new it}subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:r}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),r(t.timeUpdate$,e.liveBufferTime$),r(this.player.liveDuration$,e.duration$),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(zb({interval:aw(1e3),playbackRate:t.playbackRateState$}).subscribe(({playbackRate:a})=>{if(this.videoState.getState()==="playing"){let s=e.position$.getValue()+(a-1);s<=0&&e.position$.next(s),this.liveOffset?.resetTo(-s*1e3)}})).add(zb({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(sw(({liveBufferTime:a,liveAvailabilityStartTime:s})=>a&&s?a+s:void 0)).subscribe(e.liveTime$)).add(this.player.currentLiveTextRepresentation$.subscribe(a=>{if(a){let s=Lb(a);this.params.output.availableTextTracks$.next([s])}}))}seek(e){this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),r=this.videoState.getState(),a=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(()=>{this.params.output.position$.next(e/1e3),this.liveOffset?.resetTo(n,a)})}};var Jb=We(as(),1);import{assertNever as ia,assertNonNullable as Kb,debounce as nw,ErrorCategory as Cs,filter as ow,isNonNullable as uw,isNullable as cw,map as Ds,merge as lw,Observable as dw,observableFrom as pw,Subscription as hw,videoSizeToQuality as fw}from"@vkontakte/videoplayer-shared";var qe={};var Br=(i,e)=>new dw(t=>{let r=(a,s)=>t.next(s);return i.on(e,r),()=>i.off(e,r)}),aa=class{constructor(e){this.subscription=new hw;this.videoState=new L("initializing");this.textTracksManager=new Ke;this.trackLevels=new Map;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(e!=="initializing")switch(r?.to!=="paused"&&a.state==="requested"&&this.seek(a.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"),I(this.params.desiredState.playbackState,"paused");break;case"playing":this.pause();break;default:ia(e)}break;default:ia(t)}};this.video=oe(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(Q(this.params.source.url)),this.loadHlsJs()}destroy(){this.subscription.unsubscribe(),this.trackLevels.clear(),this.textTracksManager.destroy(),this.hls?.detachMedia(),this.hls?.destroy(),this.params.output.element$.next(void 0),ue(this.video)}loadHlsJs(){let e=!1,t=a=>{e||this.params.output.error$.next({id:a==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:Cs.NETWORK,message:"Failed to load Hls.js",thrown:a}),e=!0},r=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);(0,Jb.default)(import("hls.js").then(a=>{e||(qe.Hls=a.default,qe.Events=a.default.Events,this.init())},t),()=>{window.clearTimeout(r),e=!0})}init(){Kb(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(){Kb(qe.Events,"hls.js not loaded");let{desiredState:e,output:t}=this.params,r=u=>{t.error$.next({id:"HlsJsProvider",category:Cs.WTF,message:"HlsJsProvider internal logic error",thrown:u})},a=le(this.video),s=(u,d)=>this.subscription.add(u.subscribe(d,r));s(a.timeUpdate$,t.position$),s(a.durationChange$,t.duration$),s(a.ended$,t.endedEvent$),s(a.looped$,t.loopedEvent$),s(a.error$,t.error$),s(a.isBuffering$,t.isBuffering$),s(a.currentBuffer$,t.currentBuffer$),s(a.loadStart$,t.firstBytesEvent$),s(a.loadedMetadata$,t.loadedMetadataEvent$),s(a.playing$,t.firstFrameEvent$),s(a.canplay$,t.canplay$),s(a.seeked$,t.seekedEvent$),s(a.inPiP$,t.inPiP$),s(a.inFullscreen$,t.inFullscreen$),this.subscription.add(Qe(this.video,e.isLooped,r)),this.subscription.add(ce(this.video,e.volume,a.volumeState$,r)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(Pe(this.video,e.playbackRate,a.playbackRateState$,r)),s(ke(this.video),t.elementVisible$),s(this.videoState.stateChangeEnded$.pipe(Ds(u=>u.to)),this.params.output.playbackState$),this.subscription.add(Br(this.hls,qe.Events.ERROR).subscribe(u=>{u.fatal&&t.error$.next({id:["HlsJsFatal",u.type,u.details].join("_"),category:Cs.WTF,message:`HlsJs fatal ${u.type} ${u.details}, ${u.err?.message} ${u.reason}`,thrown:u.error})})),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState("playing"),I(e.playbackState,"playing")},r)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),I(e.playbackState,"paused")},r)).add(a.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),s(Br(this.hls,qe.Events.MANIFEST_PARSED).pipe(Ds(({levels:u})=>u.reduce((d,l)=>{let p=l.name||l.height.toString(10),{width:h,height:m}=l,b=vt(l.attrs.QUALITY??"")??fw({width:h,height:m});if(!b)return d;let g=l.attrs["FRAME-RATE"]?parseFloat(l.attrs["FRAME-RATE"]):void 0,v={id:p.toString(),quality:b,bitrate:l.bitrate/1e3,size:{width:h,height:m},fps:g};return this.trackLevels.set(p,{track:v,level:l}),d.push(v),d},[]))),t.availableVideoTracks$),s(Br(this.hls,qe.Events.MANIFEST_PARSED),u=>{if(u.subtitleTracks.length>0){let d=[];for(let l of u.subtitleTracks){let p=l.name,h=l.attrs.URI||"",m=l.lang;d.push({id:p,url:h,language:m,type:"internal"})}e.internalTextTracks.startTransitionTo(d)}}),s(Br(this.hls,qe.Events.LEVEL_LOADING).pipe(Ds(({url:u})=>Q(u))),t.hostname$),s(Br(this.hls,qe.Events.FRAG_CHANGED),u=>{let{video:d,audio:l}=u.frag.elementaryStreams;t.currentVideoSegmentLength$.next(((d?.endPTS??0)-(d?.startPTS??0))*1e3),t.currentAudioSegmentLength$.next(((l?.endPTS??0)-(l?.startPTS??0))*1e3)}),this.subscription.add(bt(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,u=>{this.hls.nextLevel=u?-1:this.hls.currentLevel,this.hls.loadLevel=u?-1:this.hls.loadLevel},{onError:r}));let n=u=>Array.from(this.trackLevels.values()).find(({level:d})=>d===u)?.track,o=Br(this.hls,qe.Events.LEVEL_SWITCHED).pipe(Ds(({level:u})=>n(this.hls.levels[u])));o.pipe(ow(uw)).subscribe(t.currentVideoTrack$,r),this.subscription.add(bt(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel]),u=>{if(cw(u))return;let d=this.trackLevels.get(u.id)?.level;if(!d)return;let l=this.hls.levels.indexOf(d),p=this.hls.currentLevel,h=this.hls.levels[p];!h||d.bitrate>h.bitrate?this.hls.nextLevel=l:(this.hls.loadLevel=l,this.hls.loadLevel=l)},{changed$:o,onError:r})),s(a.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);let c=lw(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,pw(["init"])).pipe(nw(0));this.subscription.add(c.subscribe(this.syncPlayback,r))}prepare(){this.videoState.startTransitionTo("ready"),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}async playIfAllowed(){this.videoState.startTransitionTo("playing"),await pe(this.video).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Cs.DOM,thrown:t}))||(this.videoState.setState("paused"),I(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"),I(this.params.desiredState.playbackState,"stopped",!0)}};var Xb="X-Playback-Duration",Cu=async i=>{let e=await nt(i),t=await e.text(),r=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t)?.[1];return r?parseInt(r,10):e.headers.has(Xb)?parseInt(e.headers.get(Xb),10):void 0};import{assertNever as yw,combine as Tw,debounce as Iw,ErrorCategory as Vs,filter as Ew,filterChanged as xw,isNonNullable as eg,isNullable as Os,map as tg,merge as Pw,observableFrom as Aw,Subscription as kw,ValueSubject as Vu,VideoQuality as ww}from"@vkontakte/videoplayer-shared";var Bu=We(Xn(),1);import{videoSizeToQuality as mw,getExponentialDelay as bw}from"@vkontakte/videoplayer-shared";var gw=i=>{let e=null;if(i.QUALITY&&(e=vt(i.QUALITY)),!e&&i.RESOLUTION){let[t,r]=i.RESOLUTION.split("x").map(a=>parseInt(a,10));e=mw({width:t,height:r})}return e??null},Sw=(i,e)=>{let t=i.split(`
113
+ `),r=[],a=[];for(let s=0;s<t.length;s++){let n=t[s],o=n.match(/^#EXT-X-STREAM-INF:(.+)/),c=n.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!o&&!c)){if(o){let u=(0,Bu.default)(o[1].split(",").map(g=>g.split("="))),d=u.QUALITY??`stream-${u.BANDWIDTH}`,l=gw(u),p;u.BANDWIDTH&&(p=parseInt(u.BANDWIDTH,10)/1e3||void 0),!p&&u["AVERAGE-BANDWIDTH"]&&(p=parseInt(u["AVERAGE-BANDWIDTH"],10)/1e3||void 0);let h=u["FRAME-RATE"]?parseFloat(u["FRAME-RATE"]):void 0,m;if(u.RESOLUTION){let[g,v]=u.RESOLUTION.split("x").map(k=>parseInt(k,10));g&&v&&(m={width:g,height:v})}let b=new URL(t[++s],e).toString();l&&r.push({id:d,quality:l,url:b,bandwidth:p,size:m,fps:h})}if(c){let u=(0,Bu.default)(c[1].split(",").map(h=>h.split("=")).map(([h,m])=>[h,m.replace(/^"|"$/g,"")])),d=u.URI?.replace(/playlist$/,"subtitles.vtt"),l=u.LANGUAGE,p=u.NAME;d&&l&&a.push({type:"internal",id:l,label:p,language:l,url:d,isAuto:!1})}}}if(!r.length)throw new Error("Empty manifest");return{qualityManifests:r,textTracks:a}},vw=i=>new Promise(e=>{setTimeout(()=>{e()},i)}),Du=0,Zb=async(i,e=i,t)=>{let a=await(await nt(i)).text();Du+=1;try{let{qualityManifests:s,textTracks:n}=Sw(a,e);return{qualityManifests:s,textTracks:n}}catch{if(Du<=t.manifestRetryMaxCount)return await vw(bw(Du-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),Zb(i,e,t)}return{qualityManifests:[],textTracks:[]}},Bs=Zb;var sa=class{constructor(e){this.subscription=new kw;this.videoState=new L("stopped");this.textTracksManager=new Ke;this.manifests$=new Vu([]);this.liveOffset=new it;this.manifestStartTime$=new Vu(void 0);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),r=this.params.desiredState.playbackState.getState(),a=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"),I(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let u=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||n||o){let d=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(d),this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),u.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if(a?.to!=="paused"&&u.state==="requested"){this.videoState.startTransitionTo("ready"),this.seek(u.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(t){case"ready":r==="ready"?I(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),I(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()):a?.to==="playing"&&I(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 d=this.liveOffset.getTotalOffset();d>=this.maxSeekBackTime$.getValue()&&(d=0,this.liveOffset.resetTo(d)),this.liveOffset.resume(),this.params.output.position$.next(-d/1e3),this.prepare()}else a?.to==="paused"&&(I(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return yw(t)}};this.params=e,this.video=oe(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:ww.INVARIANT,url:this.params.source.url},Bs(J(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})=>{t.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:Vs.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),this.manifests$.next([this.masterManifest,...t])},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:Vs.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),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(Q(this.params.source.url)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.maxSeekBackTime$=new Vu(e.source.maxSeekBackTime??1/0),this.subscribe()}selectManifest(){let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,r=e.getState(),a=t.getTransition(),s=a?.to?.id??t.getState()?.id??"master",n=this.manifests$.getValue();if(!n.length)return;let o=r?"master":s;return r&&!a&&t.startTransitionTo(this.masterManifest),n.find(c=>c.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"HlsLiveProvider",category:Vs.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},a=le(this.video),s=(o,c)=>this.subscription.add(o.subscribe(c,r));s(a.ended$,e.endedEvent$),s(a.error$,e.error$),s(a.isBuffering$,e.isBuffering$),s(a.currentBuffer$,e.currentBuffer$),s(a.loadedMetadata$,e.firstBytesEvent$),s(a.loadedMetadata$,e.loadedMetadataEvent$),s(a.playing$,e.firstFrameEvent$),s(a.canplay$,e.canplay$),s(a.inPiP$,e.inPiP$),s(a.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),r)),this.subscription.add(ce(this.video,t.volume,a.volumeState$,r)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Pe(this.video,t.playbackRate,a.playbackRateState$,r)),s(ke(this.video),e.elementVisible$),this.textTracksManager.connect(this.video,t,e),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState("playing"),I(t.playbackState,"playing")},r)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),I(t.playbackState,"paused")},r)).add(a.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.subscription.add(this.maxSeekBackTime$.pipe(xw(),tg(o=>-o/1e3)).subscribe(this.params.output.duration$,r)),this.subscription.add(a.loadedMetadata$.subscribe(()=>{let o=this.params.desiredState.seekState.getState(),c=this.videoState.getTransition(),u=this.params.desiredState.videoTrack.getTransition(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(u&&eg(u.to)){let l=u.to.id;this.params.desiredState.videoTrack.setState(u.to);let p=this.manifests$.getValue().find(h=>h.id===l);p&&(this.params.output.currentVideoTrack$.next(p),this.params.output.hostname$.next(Q(p.url)))}d&&this.params.desiredState.autoVideoTrackSwitching.setState(d.to),c&&c.from==="changing_manifest"&&this.videoState.setState(c.to),o&&o.state==="requested"&&this.seek(o.position)},r)),this.subscription.add(a.loadedData$.subscribe(()=>{let o=this.video?.getStartDate?.()?.getTime();this.manifestStartTime$.next(o||void 0)},r)),this.subscription.add(Tw({startTime:this.manifestStartTime$.pipe(Ew(eg)),currentTime:a.timeUpdate$}).subscribe(({startTime:o,currentTime:c})=>this.params.output.liveTime$.next(o+c*1e3),r)),this.subscription.add(this.manifests$.pipe(tg(o=>o.map(({id:c,quality:u,size:d,bandwidth:l,fps:p})=>({id:c,quality:u,size:d,fps:p,bitrate:l})))).subscribe(this.params.output.availableVideoTracks$,r));let n=Pw(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,Aw(["init"])).pipe(Iw(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),ue(this.video)}prepare(){let e=this.selectManifest();if(Os(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),r=this.params.desiredState.autoVideoTrackLimits.getState(),a=new URL(e.url);if((t||r)&&e.id===this.masterManifest.id){let{max:o,min:c}=t?.to??r??{};for(let[u,d]of[[o,"mq"],[c,"lq"]]){let l=String(parseFloat(u||""));d&&u&&a.searchParams.set(d,l)}}let s=this.params.format==="HLS_LIVE_CMAF"?2:0,n=J(a.toString(),this.liveOffset.getTotalOffset(),s);this.video.setAttribute("src",n),this.video.load(),Cu(n).then(o=>{if(!Os(o))this.maxSeekBackTime$.next(o);else{let c=this.params.source.maxSeekBackTime??this.maxSeekBackTime$.getValue();if(Os(c)||!isFinite(c))try{nt(n).then(u=>u.text()).then(u=>{let d=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(u)?.[1];if(d){let l=new URL(d,n).toString();Cu(l).then(p=>{Os(p)||this.maxSeekBackTime$.next(p)})}})}catch{}}})}playIfAllowed(){pe(this.video).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),I(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Vs.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 Rw,debounce as $w,ErrorCategory as Ou,fromEvent as _u,isNonNullable as Lw,isNullable as Mw,map as rg,merge as ig,observableFrom as ag,Subscription as Cw,ValueSubject as Dw,VideoQuality as Bw,clientChecker as Vw}from"@vkontakte/videoplayer-shared";var na=class{constructor(e){this.subscription=new Cw;this.videoState=new L("stopped");this.textTracksManager=new Ke;this.manifests$=new Dw([]);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),r=this.params.desiredState.playbackState.getState(),a=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"),I(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let u=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||n||o){let d=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(d);let{currentTime:l}=this.video;this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),u.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:l*1e3,forcePrecise:!0});return}switch(a?.to!=="paused"&&u.state==="requested"&&this.seek(u.position),t){case"ready":r==="ready"?I(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),I(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()):a?.to==="playing"&&I(this.params.desiredState.playbackState,"playing");return;case"paused":r==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):a?.to==="paused"&&I(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return Rw(t)}};this.params=e,this.video=oe(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:Bw.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(Q(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),Bs(J(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:Ou.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,r=e.getState(),a=t.getTransition(),s=a?.to?.id??t.getState()?.id??"master",n=this.manifests$.getValue();if(!n.length)return;let o=r?"master":s;return r&&!a&&t.startTransitionTo(this.masterManifest),n.find(c=>c.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"HlsProvider",category:Ou.WTF,message:"HlsProvider internal logic error",thrown:o})},a=le(this.video),s=(o,c)=>this.subscription.add(o.subscribe(c));if(s(a.timeUpdate$,e.position$),s(a.durationChange$,e.duration$),s(a.ended$,e.endedEvent$),s(a.looped$,e.loopedEvent$),s(a.error$,e.error$),s(a.isBuffering$,e.isBuffering$),s(a.currentBuffer$,e.currentBuffer$),s(a.loadedMetadata$,e.firstBytesEvent$),s(a.loadedMetadata$,e.loadedMetadataEvent$),s(a.playing$,e.firstFrameEvent$),s(a.canplay$,e.canplay$),s(a.seeked$,e.seekedEvent$),s(a.inPiP$,e.inPiP$),s(a.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe(rg(o=>o.to)),this.params.output.playbackState$),this.subscription.add(Qe(this.video,t.isLooped,r)),this.subscription.add(ce(this.video,t.volume,a.volumeState$,r)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Pe(this.video,t.playbackRate,a.playbackRateState$,r)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState("playing"),I(t.playbackState,"playing")},r)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),I(t.playbackState,"paused")},r)).add(a.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},r).add(a.loadedMetadata$.subscribe(()=>{let o=this.params.desiredState.seekState.getState(),c=this.videoState.getTransition(),u=this.params.desiredState.videoTrack.getTransition(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(u&&Lw(u.to)){let l=u.to.id;this.params.desiredState.videoTrack.setState(u.to);let p=this.manifests$.getValue().find(h=>h.id===l);if(p){this.params.output.currentVideoTrack$.next(p),this.params.output.hostname$.next(Q(p.url));let h=this.params.desiredState.playbackRate.getState(),m=this.params.output.element$.getValue()?.playbackRate;if(h!==m){let b=this.params.output.element$.getValue();b&&(this.params.desiredState.playbackRate.setState(h),b.playbackRate=h)}}}d&&this.params.desiredState.autoVideoTrackSwitching.setState(d.to),c&&c.from==="changing_manifest"&&this.videoState.setState(c.to),o.state==="requested"&&this.seek(o.position)},r))),this.subscription.add(this.manifests$.pipe(rg(o=>o.map(({id:c,quality:u,size:d,bandwidth:l,fps:p})=>({id:c,quality:u,size:d,fps:p,bitrate:l})))).subscribe(this.params.output.availableVideoTracks$,r)),!Vw.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add(ig(_u(o,"addtrack"),_u(o,"removetrack"),_u(o,"change"),ag(["init"])).subscribe(()=>{for(let c=0;c<o.length;c++)o[c].mode="hidden"},r))}let n=ig(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,ag(["init"])).pipe($w(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),ue(this.video)}prepare(){let e=this.selectManifest();if(Mw(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),r=this.params.desiredState.autoVideoTrackLimits.getState(),a=new URL(e.url);if((t||r)&&e.id===this.masterManifest.id){let{max:s,min:n}=t?.to??r??{};for(let[o,c]of[[s,"mq"],[n,"lq"]]){let u=String(parseFloat(o||""));c&&o&&a.searchParams.set(c,u)}}this.video.setAttribute("src",a.toString()),this.video.load()}playIfAllowed(){pe(this.video).then(e=>{e||(this.videoState.setState("paused"),I(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Ou.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};import{assertNever as Ow,assertNonNullable as sg,debounce as _w,ErrorCategory as ng,isHigher as Nw,isHigherOrEqual as Fw,isInvariantQuality as og,isLowerOrEqual as qw,isNonNullable as Uw,merge as Hw,observableFrom as jw,Subscription as Gw,map as Ww}from"@vkontakte/videoplayer-shared";var oa=class{constructor(e){this.subscription=new Gw;this.videoState=new L("stopped");this.trackUrls={};this.textTracksManager=new Ke;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.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"),I(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:c}=this.video;this.prepare(),o.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:c*1e3,forcePrecise:!0}),n.to&&this.params.desiredState.autoVideoTrackLimits.getState()?.max!==this.trackUrls[n.to.id]?.track?.quality&&this.params.output.autoVideoTrackLimits$.next({max:void 0});return}switch(r?.to!=="paused"&&o.state==="requested"&&this.seek(o.position),e){case"ready":t==="ready"?I(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),I(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?.to==="playing"&&I(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):r?.to==="paused"&&I(this.params.desiredState.playbackState,"paused");return;default:return Ow(e)}};this.params=e,this.video=oe(e.container,e.tuning),this.params.output.element$.next(this.video),Object.entries(this.params.source).reverse().forEach(([t,r],a)=>{let s=a.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:ng.WTF,message:"MpegProvider internal logic error",thrown:o})},a=le(this.video),s=(o,c)=>this.subscription.add(o.subscribe(c,r));s(a.timeUpdate$,e.position$),s(a.durationChange$,e.duration$),s(a.ended$,e.endedEvent$),s(a.looped$,e.loopedEvent$),s(a.error$,e.error$),s(a.isBuffering$,e.isBuffering$),s(a.currentBuffer$,e.currentBuffer$),s(a.loadedMetadata$,e.firstBytesEvent$),s(a.loadedMetadata$,e.loadedMetadataEvent$),s(a.playing$,e.firstFrameEvent$),s(a.canplay$,e.canplay$),s(a.seeked$,e.seekedEvent$),s(a.inPiP$,e.inPiP$),s(a.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe(Ww(o=>o.to)),this.params.output.playbackState$),this.subscription.add(Qe(this.video,t.isLooped,r)),this.subscription.add(ce(this.video,t.volume,a.volumeState$,r)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Pe(this.video,t.playbackRate,a.playbackRateState$,r)),s(ke(this.video),e.elementVisible$),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState("playing"),I(t.playbackState,"playing")},r)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),I(t.playbackState,"paused")},r)).add(a.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready");let o=this.params.desiredState.videoTrack.getTransition();if(o&&Uw(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(),u=this.params.output.element$.getValue()?.playbackRate;if(c!==u){let d=this.params.output.element$.getValue();d&&(this.params.desiredState.playbackRate.setState(c),d.playbackRate=c)}}this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.textTracksManager.connect(this.video,t,e);let n=Hw(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,jw(["init"])).pipe(_w(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),ue(this.video)}prepare(){let e=this.params.desiredState.videoTrack.getState()?.id;sg(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];sg(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=Qi(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(Q(t))}playIfAllowed(){pe(this.video).then(e=>{e||(this.videoState.setState("paused"),I(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:ng.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){let t,r=e;if(e&&this.params.output.currentVideoTrack$.getValue()?.quality!==e){let a=Object.values(this.trackUrls).find(o=>!og(o.track.quality)&&qw(o.track.quality,e))?.track,s=this.params.desiredState.videoTrack.getState()?.id,n=this.trackUrls[s??"0"]?.track;if(a&&n&&Fw(n.quality,a.quality)&&(t=a),!t){let o=Object.values(this.trackUrls).filter(u=>!og(u.track.quality)&&Nw(u.track.quality,e)),c=o.length;c&&(t=o[c-1].track)}t&&(r=t.quality)}else if(!e){let a=Object.values(this.trackUrls).map(s=>s.track);t=yt(a,{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 cg,debounce as Kw,merge as lg,observableFrom as Jw,Subscription as Xw,map as dg,ValueSubject as Zw,ErrorCategory as Fu,VideoQuality as eR}from"@vkontakte/videoplayer-shared";import{ErrorCategory as Yw}from"@vkontakte/videoplayer-shared";var ug=["stun:videostun.mycdn.me:80"],Qw=1e3,zw=3,Nu=()=>null,_s=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=Nu;this.externalStopCallback=Nu;this.externalErrorCallback=Nu;this.options=this.normalizeOptions(t);let r=e.split("/");this.serverUrl=r.slice(0,r.length-1).join("/"),this.streamKey=r[r.length-1]}onStart(e){try{this.externalStartCallback=e}catch(t){this.handleSystemError(t)}}onStop(e){try{this.externalStopCallback=e}catch(t){this.handleSystemError(t)}}onError(e){try{this.externalErrorCallback=e}catch(t){this.handleSystemError(t)}}connect(){this.connectWS()}disconnect(){try{this.externalStopCallback(),this.closeConnections()}catch(e){this.handleSystemError(e)}}connectWS(){this.ws||(this.ws=new WebSocket(this.serverUrl),this.ws.onopen=this.onSocketOpen.bind(this),this.ws.onmessage=this.onSocketMessage.bind(this),this.ws.onclose=this.onSocketClose.bind(this),this.ws.onerror=this.onSocketError.bind(this))}onSocketOpen(){this.handleLogin()}onSocketClose(e){try{if(!this.ws)return;this.ws=null,e.code>1e3?(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():this.scheduleRetry()):this.externalStopCallback()}catch(t){this.handleRTCError(t)}}onSocketError(e){try{this.externalErrorCallback(new Error(e.toString()))}catch(t){this.handleRTCError(t)}}onSocketMessage(e){try{let t=this.parseMessage(e.data);switch(t.type){case"JOIN":case"CALL_JOIN":this.handleJoinMessage(t);break;case"UPDATE":this.handleUpdateMessage(t);break;case"STATUS":this.handleStatusMessage(t);break}}catch(t){this.handleRTCError(t)}}handleJoinMessage(e){switch(e.inviteType){case"ANSWER":this.handleAnswer(e.sdp);break;case"CANDIDATE":this.handleCandidate(e.candidate);break}}handleStatusMessage(e){switch(e.status){case"UNPUBLISHED":this.handleUnpublished();break}}async handleUpdateMessage(e){try{let t=await this.createOffer();this.peerConnection&&await this.peerConnection.setLocalDescription(t),this.handleAnswer(e.sdp)}catch(t){this.handleRTCError(t)}}async handleLogin(){try{let e={iceServers:[{urls:ug}]};this.peerConnection=new RTCPeerConnection(e),this.peerConnection.ontrack=this.onPeerConnectionStream.bind(this),this.peerConnection.onicecandidate=this.onPeerConnectionIceCandidate.bind(this),this.peerConnection.oniceconnectionstatechange=this.onPeerConnectionIceConnectionStateChange.bind(this);let t=await this.createOffer();await this.peerConnection.setLocalDescription(t),this.send({type:this.signalingType,inviteType:"OFFER",streamKey:this.streamKey,sdp:t.sdp,callSupport:!1})}catch(e){this.handleRTCError(e)}}async handleAnswer(e){try{this.peerConnection&&await this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e}))}catch(t){this.handleRTCError(t)}}async handleCandidate(e){if(e)try{this.peerConnection&&await this.peerConnection.addIceCandidate(e)}catch(t){this.handleRTCError(t)}}handleUnpublished(){try{this.closeConnections(),this.externalStopCallback()}catch(e){this.handleRTCError(e)}}handleSystemError(e){this.options.errorChanel&&this.options.errorChanel.next({id:"webrtc-provider-error",category:Yw.WTF,message:e.message})}async onPeerConnectionStream(e){let t=e.streams[0];this.stream&&this.stream.id===t.id||(this.stream=t,this.externalStartCallback(this.stream))}onPeerConnectionIceCandidate(e){e.candidate&&this.send({type:this.signalingType,inviteType:"CANDIDATE",candidate:e.candidate})}onPeerConnectionIceConnectionStateChange(){if(this.peerConnection){let e=this.peerConnection.iceConnectionState;["failed","closed"].indexOf(e)>-1&&(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():(this.closeConnections(),this.scheduleRetry()))}}async createOffer(){let e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");let t=await this.peerConnection.createOffer(e),r=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(r))throw new Error("No h264 codec support error");return t}handleRTCError(e){try{this.externalErrorCallback(e||new Error("RTC connection error"))}catch(t){this.handleSystemError(t)}}handleNetworkError(){try{this.externalErrorCallback(new Error("Network error"))}catch(e){this.handleSystemError(e)}}send(e){this.ws&&this.ws.send(JSON.stringify(e))}parseMessage(e){try{return JSON.parse(e)}catch{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),Qw)}normalizeOptions(e={}){let t={stunServerList:ug,maxRetryNumber:zw,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var ua=class{constructor(e){this.videoState=new L("stopped");this.maxSeekBackTime$=new Zw(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"),I(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"),I(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?.to==="playing"&&I(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):r?.to==="paused"&&I(this.params.desiredState.playbackState,"paused");return;default:return cg(e)}};this.subscription=new Xw,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=oe(e.container,e.tuning),this.liveStreamClient=new _s(this.params.source.url,{maxRetryNumber:this.params.tuning.webrtc.connectionRetryMaxNumber,errorChanel:this.params.output.error$}),this.liveStreamClient.onStart(this.onLiveStreamStart.bind(this)),this.liveStreamClient.onStop(this.onLiveStreamStop.bind(this)),this.liveStreamClient.onError(this.onLiveStreamError.bind(this)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.subscribe()}destroy(){this.subscription.unsubscribe(),this.liveStreamClient.disconnect(),this.params.output.element$.next(void 0),ue(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,r=n=>{e.error$.next({id:"WebRTCLiveProvider",category:Fu.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};lg(this.videoState.stateChangeStarted$.pipe(dg(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe(dg(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})});let a=le(this.video),s=(n,o)=>this.subscription.add(n.subscribe(o,r));s(a.timeUpdate$,e.liveTime$),s(a.ended$,e.endedEvent$),s(a.looped$,e.loopedEvent$),s(a.error$,e.error$),s(a.isBuffering$,e.isBuffering$),s(a.currentBuffer$,e.currentBuffer$),s(ke(this.video),this.params.output.elementVisible$),this.subscription.add(a.durationChange$.subscribe(n=>{e.duration$.next(n===1/0?0:n)})).add(a.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready")},r)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused")},r)).add(a.playing$.subscribe(()=>{this.videoState.setState("playing")},r)).add(a.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(ce(this.video,t.volume,a.volumeState$,r)).add(a.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 cg(n.to)}},r)).add(lg(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,Jw(["init"])).pipe(Kw(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(Q(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:eR.INVARIANT}),this.video.srcObject=e,I(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:Fu.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){pe(this.video).then(e=>{e||(this.videoState.setState("paused"),I(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Fu.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var ca=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 pa,assertNonNullable as Et,ErrorCategory as Fs,filter as oR,isNonNullable as gg,isNullable as uR,map as cR,merge as lR,once as dR,Subject as ve,Subscription as Sg,ValueSubject as M,flattenObject as vg}from"@vkontakte/videoplayer-shared";import{Observable as tR,map as pg,Subscription as rR,Subject as iR}from"@vkontakte/videoplayer-shared";var hg=i=>new tR(e=>{let t=new rR,r=i.desiredPlaybackState$.stateChangeStarted$.pipe(pg(({from:u,to:d})=>`${u}-${d}`)),a=i.desiredPlaybackState$.stateChangeEnded$,s=i.providerChanged$.pipe(pg(({type:u})=>u!==void 0)),n=new iR,o=0,c="unknown";return t.add(r.subscribe(u=>{o&&window.clearTimeout(o),c=u,o=window.setTimeout(()=>n.next(u),i.maxTransitionInterval)})),t.add(a.subscribe(()=>{window.clearTimeout(o),c="unknown",o=0})),t.add(s.subscribe(u=>{o&&(window.clearTimeout(o),o=0,u&&(o=window.setTimeout(()=>n.next(c),i.maxTransitionInterval)))})),t.add(n.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});import{ErrorCategory as fg,Subscription as aR,combine as sR,filter as mg,once as bg}from"@vkontakte/videoplayer-shared";var la=null,Ns=null;function qu(){return la||(la=new(window.AudioContext||window.webkitAudioContext)),Ns||(Ns=new GainNode(la,{gain:1}),Ns.connect(la.destination)),{audioCtx:la,gainNode:Ns}}import{clientChecker as nR}from"@vkontakte/videoplayer-shared";var da=class i{constructor(e,t,r,a,s){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=r;this.volumeMultiplier=a;this.subscriptions=new aR;this.lastAudioContextResumeId=0;!s||!this.isSupported()||a===1||this.subscriptions.add(this.provider$.pipe(mg(n=>!!n.type),bg()).subscribe(({type:n})=>this.subscribe(n)))}static{this.errorId="VolumeMultiplierManager"}subscribe(e){nR.isSafari&&e!=="MPEG"||this.subscriptions.add(sR({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe(mg(({playbackState:t,video:r,volume:{muted:a,volume:s}})=>t==="playing"&&!!r&&!a&&!!s),bg()).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:a}=qu(),s=(Math.random()+1)*999999;this.lastAudioContextResumeId=s,r.resume().then(()=>{if(s!==this.lastAudioContextResumeId)throw new Error(`AudioContext.resume() resolved after ${i.errorId} destroyed`);a.gain.value=t;try{new MediaElementAudioSourceNode(r,{mediaElement:e}).connect(a)}catch(n){this.volumeMultiplierError$.next({id:i.errorId,category:fg.VIDEO_PIPELINE,message:n?.message??"initAudioContextOnce: (new MediaElementAudioSourceNode).connect() exception",thrown:n})}}).catch(n=>{this.volumeMultiplierError$.next({id:i.errorId,category:fg.VIDEO_PIPELINE,message:n?.message??"initAudioContextOnce: AudioContext.resume() exception",thrown:n})})}destroy(){let{gainNode:e}=qu();e.gain.value=1,this.subscriptions.unsubscribe(),this.lastAudioContextResumeId=0}};var pR={chunkDuration:5e3,maxParallelRequests:5},ha=class{constructor(e){this.current$=new M({type:void 0});this.providerError$=new ve;this.noAvailableProvidersError$=new ve;this.volumeMultiplierError$=new ve;this.providerOutput={position$:new M(0),duration$:new M(1/0),volume$:new M({muted:!1,volume:1}),availableVideoStreams$:new M([]),currentVideoStream$:new M(void 0),availableVideoTracks$:new M([]),currentVideoTrack$:new M(void 0),availableAudioStreams$:new M([]),currentAudioStream$:new M(void 0),availableAudioTracks$:new M([]),currentVideoSegmentLength$:new M(0),currentAudioSegmentLength$:new M(0),isAudioAvailable$:new M(!0),autoVideoTrackLimitingAvailable$:new M(!1),autoVideoTrackLimits$:new M(void 0),currentBuffer$:new M(void 0),isBuffering$:new M(!0),error$:new ve,warning$:new ve,willSeekEvent$:new ve,seekedEvent$:new ve,loopedEvent$:new ve,endedEvent$:new ve,firstBytesEvent$:new ve,loadedMetadataEvent$:new ve,firstFrameEvent$:new ve,canplay$:new ve,isLive$:new M(void 0),isLowLatency$:new M(!1),canChangePlaybackSpeed$:new M(!0),liveTime$:new M(void 0),liveBufferTime$:new M(void 0),availableTextTracks$:new M([]),currentTextTrack$:new M(void 0),hostname$:new M(void 0),httpConnectionType$:new M(void 0),httpConnectionReused$:new M(void 0),inPiP$:new M(!1),inFullscreen$:new M(!1),element$:new M(void 0),elementVisible$:new M(!0),availableSources$:new M(void 0),is3DVideo$:new M(!1),playbackState$:new M("")};this.subscription=new Sg;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer"),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name);let t=Nm([...qm(this.params.tuning),...Fm(this.params.tuning)],this.params.tuning.useHlsJs,this.params.tuning.useManagedMediaSource).filter(o=>gg(e.sources[o])),{forceFormat:r,formatsToAvoid:a}=this.params.tuning,s=[];r?s=[r]:a.length?s=[...t.filter(o=>!a.includes(o)),...t.filter(o=>a.includes(o))]:s=t,this.log({message:`Selected formats: ${s.join(" > ")}`}),this.tracer.log("Selected formats",vg(s)),this.screenFormatsIterator=new ca(s);let n=[...au(!0),...au(!1)];this.chromecastFormatsIterator=new ca(n.filter(o=>gg(e.sources[o]))),this.providerOutput.availableSources$.next(e.sources),this.volumeMultiplierManager=new da(this.providerOutput,this.current$,this.volumeMultiplierError$,this.params.volumeMultiplier??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(uR(t)){this.handleNoFormatsError(e);return}let r;try{r=this.createProvider(e,t)}catch(a){this.providerError$.next({id:"ProviderNotConstructed",category:Fs.WTF,message:"Failed to create provider",thrown:a})}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(),a=r.state!=="none";if(this.params.desiredState.seekState.setState({state:"requested",position:a?r.position:t,forcePrecise:a?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 pa(e)}}createScreenProvider(e){let{sources:t,container:r,desiredState:a}=this.params,s=this.providerOutput,n={container:r,source:null,desiredState:a,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]),c=this.applyFailoverHost(t.HLS_ONDEMAND||t.HLS);return Et(o),new ta({...n,source:o,sourceHls:c})}case"DASH_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return Et(o),new ra({...n,source:o})}case"HLS":case"HLS_ONDEMAND":{let o=this.applyFailoverHost(t[e]);return Et(o),xr||!this.params.tuning.useHlsJs?new na({...n,source:o}):new aa({...n,source:o})}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return Et(o),new sa({...n,source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case"MPEG":{let o=this.applyFailoverHost(t[e]);return Et(o),new oa({...n,source:o})}case"DASH_LIVE":{let o=this.applyFailoverHost(t[e]);return Et(o),new Lm({...n,source:o,config:{...pR,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case"WEB_RTC_LIVE":{let o=this.applyFailoverHost(t[e]);return Et(o),new ua({container:r,source:o,desiredState:a,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 pa(e)}}createChromecastProvider(e){let{sources:t,container:r,desiredState:a,meta:s}=this.params,n=this.providerOutput,o=this.params.dependencies.chromecastInitializer.connection$.getValue();return Et(o),new ci({connection:o,meta:s,container:r,source:t,format:e,desiredState:a,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 pa(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return pa(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 pa(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;let t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;let r=a=>{let s=new URL(a);return s.host=t,s.toString()};if(e===void 0)return e;if("type"in e){if(e.type==="raw")return e;if(e.type==="url")return{...e,url:r(e.url)}}return(0,yg.default)(Object.entries(e).map(([a,s])=>[a,r(s)]))}initProviderErrorHandling(){let e=new Sg,t=!1,r=0;return e.add(lR(this.providerOutput.error$,hg({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(cR(a=>({id:`ProviderHangup:${a}`,category:Fs.WTF,message:`A ${a} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;let a=this.params.desiredState.playbackState.transitionEnded$.pipe(oR(({to:s})=>s==="playing"),dR()).subscribe(()=>t=!0);e.add(a)})),e.add(this.providerError$.subscribe(a=>{let s=this.current$.getValue().destination,n={error:a,currentDestination:s};if(s==="CHROMECAST")this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider("SCREEN"),()=>this.params.dependencies.chromecastInitializer.disconnect());else{let o=a.category===Fs.NETWORK,c=a.category===Fs.FATAL,u=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),d=r<this.params.tuning.providerErrorLimit&&!c,l=u&&!c&&(o&&t||!d);n={...n,isNetworkError:o,isFatalError:c,haveFailoverHost:u,tryFailover:l,canReinitProvider:d},l?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):d?(r++,this.reinitProvider()):this.switchToNextProvider(s??"SCREEN")}this.tracer.error("providerError",vg(n))})),e}};import{fromEvent as qs,once as hR,combine as fR,Subscription as Tg,ValueSubject as Uu,map as mR,filter as bR,isNonNullable as Us,now as ye,safeStorage as Hu}from"@vkontakte/videoplayer-shared";var gR=5e3,Ig="one_video_throughput",Eg="one_video_rtt",fa=window.navigator.connection,xg=()=>{let i=fa?.downlink;if(Us(i)&&i!==10)return i*1e3},Pg=()=>{let i=fa?.rtt;if(Us(i)&&i!==3e3)return i},Ag=(i,e,t)=>{let r=t*8,a=r/i;return r/(a+e)},ju=class i{constructor(e){this.subscription=new Tg;this.concurrentDownloads=new Set;this.tuningConfig=e;let t=i.load(Ig)||(e.useBrowserEstimation?xg():void 0)||gR,r=i.load(Eg)??(e.useBrowserEstimation?Pg():void 0)??0;if(this.throughput$=new Uu(t),this.rtt$=new Uu(r),this.rttAdjustedThroughput$=new Uu(Ag(t,r,e.rttPenaltyRequestSize)),this.throughput=Qt.getSmoothedValue(t,-1,e),this.rtt=Qt.getSmoothedValue(r,1,e),e.useBrowserEstimation){let a=()=>{let n=xg();n&&this.throughput.next(n);let o=Pg();Us(o)&&this.rtt.next(o)};fa&&"onchange"in fa&&this.subscription.add(qs(fa,"change").subscribe(a)),a()}this.subscription.add(this.throughput.smoothed$.subscribe(a=>{Hu.set(Ig,a.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(a=>{Hu.set(Eg,a.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(fR({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(mR(({throughput:a,rtt:s})=>Ag(a,s,e.rttPenaltyRequestSize)),bR(a=>{let s=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(a-s)/s>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,r=ye(),a=new Tg;switch(this.subscription.add(a),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:a.add(qs(e,"progress").pipe(hR()).subscribe(s=>{t=s.loaded,r=ye()}));break;case 1:case 0:a.add(qs(e,"loadstart").subscribe(()=>{t=0,r=ye()}));break}a.add(qs(e,"loadend").subscribe(s=>{if(e.status===200){let n=s.loaded,o=ye(),c=n-t,u=o-r;this.addRawSpeed(c,u,1)}this.concurrentDownloads.delete(e),a.unsubscribe()}))}trackStream(e,t=!1){let r=e.getReader();if(!r){e.cancel("Could not get reader");return}let a=0,s=ye(),n=0,o=ye(),c=d=>{this.concurrentDownloads.delete(e),r.releaseLock(),e.cancel(`Throughput Estimator error: ${d}`).catch(()=>{})},u=async({done:d,value:l})=>{if(d)!t&&this.addRawSpeed(a,ye()-s,1),this.concurrentDownloads.delete(e);else if(l){if(t){let p=ye();if(p-o>this.tuningConfig.lowLatency.continuesByteSequenceInterval||p-s>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let m=o-s;m&&this.addRawSpeed(n,m,1,t),n=l.byteLength,s=ye()}else n+=l.byteLength;o=ye()}else a+=l.byteLength,n+=l.byteLength,n>=this.tuningConfig.streamMinSampleSize&&ye()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,ye()-o,this.concurrentDownloads.size),n=0,o=ye());await r?.read().then(u,c)}};this.concurrentDownloads.add(e),r?.read().then(u,c)}addRawSpeed(e,t,r=1,a=!1){if(i.sanityCheck(e,t,a)){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 a=e*8/t;return!(!a||!isFinite(a)||a>1e6||a<30||r&&e<1e4||!r&&e<10*1024||!r&&t<=20)}static load(e){let t=Hu.get(e);if(Us(t))return parseInt(t,10)??void 0}},kg=ju;import{fillWithDefault as SR,VideoQuality as wg}from"@vkontakte/videoplayer-shared";var Rg={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:wg.Q_4320P,activeVideoAreaThreshold:.1},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:wg.Q_480P},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,maxSegmentDurationLeftToSelectNextSegment:3e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:3e3,crashOnStallTimeout:25e3,enableSubSegmentBufferFeeding:!0,segmentTimelineTolerance:100,useFetchPriorityHints:!0},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:250,playbackCatchupSpeedup:.05,isActive:!1,delayEstimator:{emaAlpha:.45,changeThreshold:.05,deviationDepth:20,deviationFactor:.5,extremumInterval:5}}},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1,lowLatencyActiveLiveDelay:3e3,activeLiveDelay:5e3,maxPausedTime:5e3},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,forceFormat:void 0,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:void 0,useWebmBigRequest:!1,webmCodec:"vp9",androidPreferredFormat:"mpeg",preferCMAF:!1,preferWebRTC:!1,preferMultiStream:!1,preferHDR:!1,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,accumulationBufferStallSizeMs:0,requestQuick:!1,useHlsJs:!0,useNativeHLSTextTracks:!1,useManagedMediaSource:!1,useNewPruneBufferStrategy:!1,useNewPartialSegmentFeeding:!1,useSeparateAudioVideoABR:!1,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,manifestRetryInterval:300,manifestRetryMaxInterval:1e4,manifestRetryMaxCount:10,audioVideoSyncRate:20,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50},useVolumeMultiplier:!1},$g=i=>({...SR(i,Rg),configName:[...i.configName??[],...Rg.configName]});import{assertNonNullable as Hs,combine as xt,ErrorCategory as js,filter as re,filterChanged as V,fromEvent as Wu,isNonNullable as PR,isNullable as AR,Logger as kR,map as C,mapTo as Dg,merge as Pt,now as Gs,once as lt,Subject as F,Subscription as Bg,tap as Vg,ValueSubject as P,isHigher as wR,isInvariantQuality as Og,flattenObject as At,throttle as Yu,getTraceSubscriptionMethod as _g,Tracer as RR}from"@vkontakte/videoplayer-shared";import{merge as vR,map as yR,filter as Lg,isNonNullable as TR}from"@vkontakte/videoplayer-shared";var Gu=({seekState:i,position$:e})=>vR(i.stateChangeEnded$.pipe(yR(({to:t})=>t.state==="none"?void 0:(t.position??NaN)/1e3),Lg(TR)),e.pipe(Lg(()=>i.getState().state==="none")));import{assertNonNullable as IR}from"@vkontakte/videoplayer-shared";var Mg=i=>{let e=typeof i.container=="string"?document.getElementById(i.container):i.container;return IR(e,`Wrong container or containerId {${i.container}}`),e};import{filter as ER,once as xR}from"@vkontakte/videoplayer-shared";var Cg=(i,e,t,r)=>{i!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&t?.getValue().length===0?t.pipe(ER(a=>a.length>0),xR()).subscribe(a=>{a.find(r)&&e.startTransitionTo(i)}):(i===void 0||t?.getValue().find(r))&&e.startTransitionTo(i)};var Ws=class{constructor(e={configName:[]},t=RR.createRootTracer(!1)){this.subscription=new Bg;this.logger=new kR;this.abrLogger=this.logger.createComponentLog("ABR");this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new P(!1);this.hasLiveOffsetByPausedTimer=0;this.desiredState={playbackState:new L("stopped"),seekState:new L({state:"none"}),volume:new L({volume:1,muted:!1}),videoTrack:new L(void 0),videoStream:new L(void 0),audioStream:new L(void 0),autoVideoTrackSwitching:new L(!0),autoVideoTrackLimits:new L({}),isLooped:new L(!1),playbackRate:new L(1),externalTextTracks:new L([]),internalTextTracks:new L([]),currentTextTrack:new L(void 0),textTrackCuesSettings:new L({}),cameraOrientation:new L({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 F,ready$:new F,started$:new F,playing$:new F,paused$:new F,stopped$:new F,willStart$:new F,willResume$:new F,willPause$:new F,willStop$:new F,willDestruct$:new F,watchCoverageRecord$:new F,watchCoverageLive$:new F,managedError$:new F,fatalError$:new F,ended$:new F,looped$:new F,seeked$:new F,willSeek$:new F,firstBytes$:new F,loadedMetadata$:new F,firstFrame$:new F,canplay$:new F,log$:new F};this.experimental={element$:new P(void 0),tuningConfigName$:new P([]),enableDebugTelemetry$:new P(!1),dumpTelemetry:lm};if(this.initLogs(),this.tuning=$g(e),this.tracer=t,this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new Ea({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new kg(this.tuning.throughputEstimator),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(r,a,s)=>{let n=Reflect.get(r,a,s);return typeof n!="function"?n:(...o)=>{try{return n.apply(r,o)}catch(c){let u=o.map(p=>JSON.stringify(p,(h,m)=>{let b=typeof m;return["number","string","boolean"].includes(b)?m:m===null?null:`<${b}>`})),d=`Player.${String(a)}`,l=`Exception calling ${d} (${u.join(", ")})`;throw this.events.fatalError$.next({id:d,category:js.WTF,message:l,thrown:c}),c}}}})}initVideo(e){this.config=e;let{container:t,...r}=e;return this.tracer.log("initVideo",At(r)),this.domContainer=Mg(e),this.chromecastInitializer.contentId=e.meta?.videoId,this.providerContainer=new ha({sources:e.sources,meta:e.meta??{},failoverHosts:e.failoverHosts??[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,tracer:this.tracer,logger:this.logger,abrLogger:this.abrLogger},tuning:this.tuning,volumeMultiplier:e.volumeMultiplier}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.initTracerSubscription(),this.providerContainer.init(),this.setMuted(this.tuning.isAudioDisabled),this.initDebugTelemetry(),this.initWakeLock(),this}destroy(){this.tracer.log("destroy"),window.clearTimeout(this.hasLiveOffsetByPausedTimer),this.events.willDestruct$.next(),this.stop(),this.providerContainer?.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"),Wu(document,"visibilitychange").pipe(lt()).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(),a=this.info.isLive$.getValue(),s=e;return e>=r&&!a&&(s=r-.1),this.tracer.log("seekTime",{duration:r,isLive:a,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){Hs(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(re(r=>r.length>0),lt()).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",At(e)),this.desiredState.autoVideoTrackLimits.startTransitionTo(e),this}setPlaybackRate(e){Hs(this.providerContainer);let t=this.providerContainer?.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",At(e)),this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>({type:"external",...t}))),this}selectTextTrack(e){return Cg(e,this.desiredState.currentTextTrack,this.providerContainer?.providerOutput.availableTextTracks$,t=>t.id===e),this.tracer.log("selectTextTrack",{textTrackId:e}),this}setTextTrackCueSettings(e){return this.tracer.log("setTextTrackCueSettings",{...e}),this.desiredState.textTrackCuesSettings.startTransitionTo(e),this}setLooped(e){return this.tracer.log("setLooped",{isLooped:e}),this.desiredState.isLooped.startTransitionTo(e),this}toggleChromecast(){this.tracer.log("toggleChromecast"),this.chromecastInitializer.toggleConnection()}startCameraManualRotation(e,t){let r=this.getScene3D();return this.tracer.log("startCameraManualRotation",{isScene3DAvailable:!!r,mx:e,my:t}),r&&r.startCameraManualRotation(e,t),this}stopCameraManualRotation(e=!1){let t=this.getScene3D();return this.tracer.log("stopCameraManualRotation",{isScene3DAvailable:!!t,immediate:e}),t&&t.stopCameraManualRotation(e),this}moveCameraFocusPX(e,t){let r=this.getScene3D();if(this.tracer.log("moveCameraFocusPX",{isScene3DAvailable:!!r,dxpx:e,dypx:t}),r){let a=r.getCameraRotation(),s=r.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:a.x+s.x,y:a.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(AR(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),r=t.state==="none"?void 0:t.position;return PR(r)?r/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}getScene3D(){let e=this.providerContainer?.current$.getValue();if(e?.provider?.scene3D)return e.provider.scene3D}setIntrinsicVideoSize(...e){let t={width:e.reduce((r,{width:a})=>r||a||0,0),height:e.reduce((r,{height:a})=>r||a||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add(Pt(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(C(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(C(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(C(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(C(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(C(e=>e.to)).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(re(({from:e})=>e==="stopped"),lt()).subscribe(()=>{this.initedAt=Gs(),this.events.inited$.next()})).add(this.desiredState.playbackState.stateChangeEnded$.subscribe(e=>{switch(e.to){case"ready":this.events.ready$.next();break;case"playing":this.isPlaybackStarted||this.events.started$.next(),this.isPlaybackStarted=!0,this.events.playing$.next();break;case"paused":this.events.paused$.next();break;case"stopped":this.events.stopped$.next()}})).add(this.desiredState.playbackState.stateChangeStarted$.subscribe(e=>{switch(e.to){case"paused":this.events.willPause$.next();break;case"playing":this.isPlaybackStarted?this.events.willResume$.next():this.events.willStart$.next();break;case"stopped":this.events.willStop$.next();break;default:}}))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();this.tracer.log("willSeekEvent",At(n)),n.state==="requested"?this.desiredState.seekState.setState({...n,state:"applying"}):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:js.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.seekedEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();this.tracer.log("seekedEvent",At(n)),n.state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe(C(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(C(n=>n.destination),V()).subscribe(()=>this.isPlaybackStarted=!1)).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add(e.providerOutput.availableVideoTracks$.pipe(C(n=>n.map(({quality:o})=>o).sort((o,c)=>Og(o)?1:Og(c)?-1:wR(c,o)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(n=>{let o={};for(let c of n)c.fps&&(o[c.quality]=c.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(V()).subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{this.info.currentQuality$.next(n?.quality),this.info.videoBitrate$.next(n?.bitrate)})).add(e.providerOutput.currentVideoSegmentLength$.pipe(V((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.pipe(V((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe(V()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(V()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(V()).subscribe(this.info.httpConnectionReused$)).add(e.providerOutput.currentTextTrack$.subscribe(this.info.currentTextTrack$)).add(e.providerOutput.availableTextTracks$.subscribe(this.info.availableTextTracks$)).add(e.providerOutput.autoVideoTrackLimitingAvailable$.subscribe(this.info.autoQualityLimitingAvailable$)).add(e.providerOutput.autoVideoTrackLimits$.subscribe(n=>{this.desiredState.autoVideoTrackLimits.setState(n??{})})).add(e.providerOutput.currentBuffer$.pipe(C(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(xt({hasLiveOffsetByPaused:Pt(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(C(n=>n.to),V(),C(n=>n==="paused")),isLowLatency:e.providerOutput.isLowLatency$}).subscribe(({hasLiveOffsetByPaused:n,isLowLatency:o})=>{if(window.clearTimeout(this.hasLiveOffsetByPausedTimer),n){this.hasLiveOffsetByPausedTimer=window.setTimeout(()=>{this.hasLiveOffsetByPaused.next(!0)},this.getActiveLiveDelay(o));return}this.hasLiveOffsetByPaused.next(!1)})).add(xt({atLiveEdge:xt({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:Gu({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(C(({isLive:n,position:o,isLowLatency:c})=>{let u=this.getActiveLiveDelay(c);return n&&Math.abs(o)<u/1e3}),V(),Vg(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(C(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add(xt({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(C(({isLive:n,position:o,duration:c})=>n&&(Math.abs(c)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),V(),Vg(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(C(n=>n.muted),V()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(C(n=>n.volume),V()).subscribe(this.info.volume$)).add(Gu({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(Pt(e.providerOutput.endedEvent$.pipe(Dg(!0)),e.providerOutput.seekedEvent$.pipe(Dg(!1))).pipe(V()).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(C(n=>({id:n?`No${n}`:"NoProviders",category:js.VIDEO_PIPELINE,message:n?`${n} was forced but failed or not available`:"No suitable providers or all providers failed"}))).subscribe(this.events.fatalError$)).add(e.providerOutput.element$.subscribe(this.experimental.element$)).add(e.providerOutput.firstBytesEvent$.pipe(lt(),C(n=>n??Gs()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe(lt(),C(()=>Gs()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(lt(),C(()=>Gs()-this.initedAt)).subscribe(this.events.canplay$)).add(this.throughputEstimator.throughput$.subscribe(this.info.throughputEstimation$)).add(this.throughputEstimator.rtt$.subscribe(this.info.rttEstimation$)).add(e.providerOutput.availableSources$.subscribe(this.info.availableSources$));let t=new 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(re(({to:n})=>n==="playing"),lt()).subscribe(()=>r.next(!1)));let a=0,s=Pt(e.providerOutput.isBuffering$,t,r).pipe(C(()=>{let n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||r.getValue();return n&&!o}),V());this.subscription.add(s.subscribe(n=>{n?a=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(a),this.info.isStalled$.next(!1))})),this.subscription.add(Pt(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{let n=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:n?.videoWidth,height:n?.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{let o=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:n?.size?.width,height:n?.size?.height},{width:o?.videoWidth,height:o?.videoHeight})})).add(e.providerOutput.is3DVideo$.subscribe(this.info.is3DVideo$)),this.subscription.add(Pt(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(),c=e.providerOutput.element$.getValue(),u=e.providerOutput.elementVisible$.getValue(),d=this.chromecastInitializer.castState$.getValue(),l;d==="CONNECTED"?l="second_screen":c?u?n?l="pip":o?l="fullscreen":l="inline":l="invisible":l="none",this.info.surface$.getValue()!==l&&this.info.surface$.next(l)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(C(e=>e?.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){let t=new Bg;this.subscription.add(t),this.subscription.add(e.current$.pipe(V((r,a)=>r.provider===a.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(re(r=>r.length>0),lt()).subscribe(r=>{this.setStartingVideoTrack(r)}))}))}setStartingVideoTrack(e){let t,r=this.desiredState.videoTrack.getState()?.quality;r&&(t=e.find(({quality:a})=>a===r),t||this.setAutoQuality(!0)),t||(t=yt(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(Pt(this.desiredState.videoTrack.stateChangeStarted$.pipe(C(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(C(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(C(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(C(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(C(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(C(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(C(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(C(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(C(e=>({component:"desiredState",message:`[${e.entity} change] ${e.type}: ${JSON.stringify(e.transition)}`}))).subscribe(this.logger.log)),this.subscription.add(this.logger.log$.subscribe(this.events.log$))}initDebugTelemetry(){let e=this.providerContainer?.providerOutput;Hs(this.providerContainer),Hs(e),cm(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(t=>um(t)),this.providerContainer.current$.subscribe(({type:t})=>hi("provider",t)),e.duration$.subscribe(t=>hi("duration",t)),e.availableVideoTracks$.pipe(re(t=>!!t.length),lt()).subscribe(t=>hi("tracks",t)),this.events.fatalError$.subscribe(new te("fatalError")),this.events.managedError$.subscribe(new te("managedError")),e.position$.subscribe(new te("position")),e.currentVideoTrack$.pipe(C(t=>t?.quality)).subscribe(new te("quality")),this.info.currentBuffer$.subscribe(new te("buffer")),e.isBuffering$.subscribe(new te("isBuffering"))].forEach(t=>this.subscription.add(t)),hi("codecs",_m())}initTracerSubscription(){let e=_g(this.tracer.log.bind(this.tracer)),t=_g(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(V()).subscribe(e("currentPlaybackRate"))).add(this.info.isAutoQualityEnabled$.subscribe(e("isAutoQualityEnabled"))).add(this.info.autoQualityLimits$.subscribe(e("autoQualityLimits"))).add(this.info.currentFormat$.subscribe(e("currentFormat"))).add(this.info.availableQualities$.subscribe(e("availableQualities"))).add(this.info.availableQualitiesFps$.subscribe(e("availableQualitiesFps"))).add(this.info.availableAudioTracks$.subscribe(e("availableAudioTracks"))).add(this.info.isAudioAvailable$.subscribe(e("isAudioAvailable"))).add(xt({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe(re(({currentQuality:r,videoBitrate:a})=>!!r&&!!a),V((r,a)=>r.currentQuality===a.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe(re(r=>r>0),V()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe(re(r=>r>0),V()).subscribe(e("currentAudioSegmentLength"))).add(this.info.hostname$.subscribe(e("hostname"))).add(this.info.currentTextTrack$.subscribe(e("currentTextTrack"))).add(this.info.availableTextTracks$.subscribe(e("availableTextTracks"))).add(this.info.autoQualityLimitingAvailable$.subscribe(e("autoQualityLimitingAvailable"))).add(xt({currentBuffer:this.info.currentBuffer$.pipe(re(r=>r.end>0),V((r,a)=>r.end===a.end&&r.start===a.start)),position:this.info.position$.pipe(V())}).pipe(Yu(1e3)).subscribe(e("currentBufferAndPosition"))).add(this.info.duration$.pipe(V()).subscribe(e("duration"))).add(this.info.isBuffering$.subscribe(e("isBuffering"))).add(this.info.isLive$.pipe(V()).subscribe(e("isLive"))).add(this.info.canChangePlaybackSpeed$.pipe(V()).subscribe(e("canChangePlaybackSpeed"))).add(xt({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe(re(({liveTime:r,liveBufferTime:a})=>!!r&&!!a),Yu(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe(V(),re(r=>r===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe(V(),re(r=>r===!0)).subscribe(e("atLiveDurationEdge"))).add(this.info.muted$.pipe(V()).subscribe(e("muted"))).add(this.info.volume$.pipe(V()).subscribe(e("volume"))).add(this.info.isEnded$.pipe(V(),re(r=>r===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add(xt({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe(re(({throughputEstimation:r,rtt:a})=>!!r&&!!a),Yu(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe(V(),re(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?.release(),e=void 0},r=async()=>{t(),e=await window.navigator.wakeLock.request("screen").catch(a=>{a instanceof DOMException&&a.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:js.DOM,message:String(a)})})};this.subscription.add(Pt(Wu(document,"visibilitychange"),Wu(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{let a=document.visibilityState==="visible",s=this.desiredState.playbackState.getState()==="playing",n=!!e&&!e?.released;a&&s?n||r():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){let r=e.find(a=>a.quality===t);this.tracer.log("setVideoTrackIdByQuality",At({quality:t,availableTracks:At(e),track:At(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 kj,Observable as wj,Subject as Rj,ValueSubject as $j,VideoQuality as Lj}from"@vkontakte/videoplayer-shared";var Mj=`@vkontakte/videoplayer-core@${Ku}`;export{Ta as ChromecastState,Qs as HttpConnectionType,wj as Observable,se as PlaybackState,Ws as Player,Mj as SDK_VERSION,Rj as Subject,kj as Subscription,zs as Surface,Ku as VERSION,$j as ValueSubject,ft as VideoFormat,Lj as VideoQuality};