@vkontakte/videoplayer-core 2.0.119-dev.df6b2fd8.0 → 2.0.119-dev.e9ac9f0e.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.cjs.js CHANGED
@@ -1,51 +1,51 @@
1
1
  /**
2
- * @vkontakte/videoplayer-core v2.0.119-dev.df6b2fd8.0
3
- * Sun, 08 Dec 2024 16:20:23 GMT
2
+ * @vkontakte/videoplayer-core v2.0.119-dev.e9ac9f0e.0
3
+ * Wed, 11 Dec 2024 12:46:31 GMT
4
4
  * https://st.mycdn.me/static/vkontakte-videoplayer/2-0-119/doc/
5
5
  */
6
- "use strict";var Gg=Object.create;var La=Object.defineProperty;var Wg=Object.getOwnPropertyDescriptor;var Yg=Object.getOwnPropertyNames;var zg=Object.getPrototypeOf,Kg=Object.prototype.hasOwnProperty;var f=(i,e)=>()=>(e||i((e={exports:{}}).exports,e),e.exports),Jg=(i,e)=>{for(var t in e)La(i,t,{get:e[t],enumerable:!0})},Du=(i,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of Yg(e))!Kg.call(i,a)&&a!==t&&La(i,a,{get:()=>e[a],enumerable:!(r=Wg(e,a))||r.enumerable});return i};var G=(i,e,t)=>(t=i!=null?Gg(zg(i)):{},Du(e||!i||!i.__esModule?La(t,"default",{value:i,enumerable:!0}):t,i)),Xg=i=>Du(La({},"__esModule",{value:!0}),i);var ne=f((Qs,Vu)=>{"use strict";var ei=function(i){return i&&i.Math===Math&&i};Vu.exports=ei(typeof globalThis=="object"&&globalThis)||ei(typeof window=="object"&&window)||ei(typeof self=="object"&&self)||ei(typeof global=="object"&&global)||ei(typeof Qs=="object"&&Qs)||function(){return this}()||Function("return this")()});var fe=f(($w,Ou)=>{"use strict";Ou.exports=function(i){try{return!!i()}catch{return!0}}});var ti=f((Lw,Bu)=>{"use strict";var Zg=fe();Bu.exports=!Zg(function(){var i=function(){}.bind();return typeof i!="function"||i.hasOwnProperty("prototype")})});var Gs=f((Mw,qu)=>{"use strict";var eS=ti(),Fu=Function.prototype,_u=Fu.apply,Nu=Fu.call;qu.exports=typeof Reflect=="object"&&Reflect.apply||(eS?Nu.bind(_u):function(){return Nu.apply(_u,arguments)})});var ce=f((Cw,ju)=>{"use strict";var Uu=ti(),Hu=Function.prototype,Ws=Hu.call,tS=Uu&&Hu.bind.bind(Ws,Ws);ju.exports=Uu?tS:function(i){return function(){return Ws.apply(i,arguments)}}});var zt=f((Dw,Gu)=>{"use strict";var Qu=ce(),rS=Qu({}.toString),iS=Qu("".slice);Gu.exports=function(i){return iS(rS(i),8,-1)}});var Ys=f((Vw,Wu)=>{"use strict";var aS=zt(),sS=ce();Wu.exports=function(i){if(aS(i)==="Function")return sS(i)}});var se=f((Ow,Yu)=>{"use strict";var zs=typeof document=="object"&&document.all;Yu.exports=typeof zs>"u"&&zs!==void 0?function(i){return typeof i=="function"||i===zs}:function(i){return typeof i=="function"}});var Le=f((Bw,zu)=>{"use strict";var nS=fe();zu.exports=!nS(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var Me=f((_w,Ku)=>{"use strict";var oS=ti(),Da=Function.prototype.call;Ku.exports=oS?Da.bind(Da):function(){return Da.apply(Da,arguments)}});var Ks=f(Zu=>{"use strict";var Ju={}.propertyIsEnumerable,Xu=Object.getOwnPropertyDescriptor,uS=Xu&&!Ju.call({1:2},1);Zu.f=uS?function(e){var t=Xu(this,e);return!!t&&t.enumerable}:Ju});var ri=f((Fw,el)=>{"use strict";el.exports=function(i,e){return{enumerable:!(i&1),configurable:!(i&2),writable:!(i&4),value:e}}});var rl=f((qw,tl)=>{"use strict";var lS=ce(),cS=fe(),dS=zt(),Js=Object,pS=lS("".split);tl.exports=cS(function(){return!Js("z").propertyIsEnumerable(0)})?function(i){return dS(i)==="String"?pS(i,""):Js(i)}:Js});var vr=f((Uw,il)=>{"use strict";il.exports=function(i){return i==null}});var Ct=f((Hw,al)=>{"use strict";var hS=vr(),mS=TypeError;al.exports=function(i){if(hS(i))throw new mS("Can't call method on "+i);return i}});var Kt=f((jw,sl)=>{"use strict";var fS=rl(),bS=Ct();sl.exports=function(i){return fS(bS(i))}});var Ce=f((Qw,nl)=>{"use strict";var gS=se();nl.exports=function(i){return typeof i=="object"?i!==null:gS(i)}});var yr=f((Gw,ol)=>{"use strict";ol.exports={}});var gt=f((Ww,ll)=>{"use strict";var Xs=yr(),Zs=ne(),SS=se(),ul=function(i){return SS(i)?i:void 0};ll.exports=function(i,e){return arguments.length<2?ul(Xs[i])||ul(Zs[i]):Xs[i]&&Xs[i][e]||Zs[i]&&Zs[i][e]}});var ii=f((Yw,cl)=>{"use strict";var vS=ce();cl.exports=vS({}.isPrototypeOf)});var Jt=f((zw,hl)=>{"use strict";var yS=ne(),dl=yS.navigator,pl=dl&&dl.userAgent;hl.exports=pl?String(pl):""});var tn=f((Kw,vl)=>{"use strict";var Sl=ne(),en=Jt(),ml=Sl.process,fl=Sl.Deno,bl=ml&&ml.versions||fl&&fl.version,gl=bl&&bl.v8,We,Va;gl&&(We=gl.split("."),Va=We[0]>0&&We[0]<4?1:+(We[0]+We[1]));!Va&&en&&(We=en.match(/Edge\/(\d+)/),(!We||We[1]>=74)&&(We=en.match(/Chrome\/(\d+)/),We&&(Va=+We[1])));vl.exports=Va});var rn=f((Jw,Tl)=>{"use strict";var yl=tn(),TS=fe(),IS=ne(),ES=IS.String;Tl.exports=!!Object.getOwnPropertySymbols&&!TS(function(){var i=Symbol("symbol detection");return!ES(i)||!(Object(i)instanceof Symbol)||!Symbol.sham&&yl&&yl<41})});var an=f((Xw,Il)=>{"use strict";var xS=rn();Il.exports=xS&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var sn=f((Zw,El)=>{"use strict";var PS=gt(),AS=se(),kS=ii(),wS=an(),RS=Object;El.exports=wS?function(i){return typeof i=="symbol"}:function(i){var e=PS("Symbol");return AS(e)&&kS(e.prototype,RS(i))}});var ai=f((eR,xl)=>{"use strict";var $S=String;xl.exports=function(i){try{return $S(i)}catch{return"Object"}}});var it=f((tR,Pl)=>{"use strict";var LS=se(),MS=ai(),CS=TypeError;Pl.exports=function(i){if(LS(i))return i;throw new CS(MS(i)+" is not a function")}});var si=f((rR,Al)=>{"use strict";var DS=it(),VS=vr();Al.exports=function(i,e){var t=i[e];return VS(t)?void 0:DS(t)}});var wl=f((iR,kl)=>{"use strict";var nn=Me(),on=se(),un=Ce(),OS=TypeError;kl.exports=function(i,e){var t,r;if(e==="string"&&on(t=i.toString)&&!un(r=nn(t,i))||on(t=i.valueOf)&&!un(r=nn(t,i))||e!=="string"&&on(t=i.toString)&&!un(r=nn(t,i)))return r;throw new OS("Can't convert object to primitive value")}});var Ye=f((aR,Rl)=>{"use strict";Rl.exports=!0});var Ml=f((sR,Ll)=>{"use strict";var $l=ne(),BS=Object.defineProperty;Ll.exports=function(i,e){try{BS($l,i,{value:e,configurable:!0,writable:!0})}catch{$l[i]=e}return e}});var ni=f((nR,Vl)=>{"use strict";var _S=Ye(),NS=ne(),FS=Ml(),Cl="__core-js_shared__",Dl=Vl.exports=NS[Cl]||FS(Cl,{});(Dl.versions||(Dl.versions=[])).push({version:"3.38.0",mode:_S?"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 ln=f((oR,Bl)=>{"use strict";var Ol=ni();Bl.exports=function(i,e){return Ol[i]||(Ol[i]=e||{})}});var Tr=f((uR,_l)=>{"use strict";var qS=Ct(),US=Object;_l.exports=function(i){return US(qS(i))}});var ze=f((lR,Nl)=>{"use strict";var HS=ce(),jS=Tr(),QS=HS({}.hasOwnProperty);Nl.exports=Object.hasOwn||function(e,t){return QS(jS(e),t)}});var cn=f((cR,Fl)=>{"use strict";var GS=ce(),WS=0,YS=Math.random(),zS=GS(1 .toString);Fl.exports=function(i){return"Symbol("+(i===void 0?"":i)+")_"+zS(++WS+YS,36)}});var be=f((dR,Ul)=>{"use strict";var KS=ne(),JS=ln(),ql=ze(),XS=cn(),ZS=rn(),ev=an(),Ir=KS.Symbol,dn=JS("wks"),tv=ev?Ir.for||Ir:Ir&&Ir.withoutSetter||XS;Ul.exports=function(i){return ql(dn,i)||(dn[i]=ZS&&ql(Ir,i)?Ir[i]:tv("Symbol."+i)),dn[i]}});var Gl=f((pR,Ql)=>{"use strict";var rv=Me(),Hl=Ce(),jl=sn(),iv=si(),av=wl(),sv=be(),nv=TypeError,ov=sv("toPrimitive");Ql.exports=function(i,e){if(!Hl(i)||jl(i))return i;var t=iv(i,ov),r;if(t){if(e===void 0&&(e="default"),r=rv(t,i,e),!Hl(r)||jl(r))return r;throw new nv("Can't convert object to primitive value")}return e===void 0&&(e="number"),av(i,e)}});var pn=f((hR,Wl)=>{"use strict";var uv=Gl(),lv=sn();Wl.exports=function(i){var e=uv(i,"string");return lv(e)?e:e+""}});var Oa=f((mR,zl)=>{"use strict";var cv=ne(),Yl=Ce(),hn=cv.document,dv=Yl(hn)&&Yl(hn.createElement);zl.exports=function(i){return dv?hn.createElement(i):{}}});var mn=f((fR,Kl)=>{"use strict";var pv=Le(),hv=fe(),mv=Oa();Kl.exports=!pv&&!hv(function(){return Object.defineProperty(mv("div"),"a",{get:function(){return 7}}).a!==7})});var Zl=f(Xl=>{"use strict";var fv=Le(),bv=Me(),gv=Ks(),Sv=ri(),vv=Kt(),yv=pn(),Tv=ze(),Iv=mn(),Jl=Object.getOwnPropertyDescriptor;Xl.f=fv?Jl:function(e,t){if(e=vv(e),t=yv(t),Iv)try{return Jl(e,t)}catch{}if(Tv(e,t))return Sv(!bv(gv.f,e,t),e[t])}});var fn=f((gR,ec)=>{"use strict";var Ev=fe(),xv=se(),Pv=/#|\.prototype\./,oi=function(i,e){var t=kv[Av(i)];return t===Rv?!0:t===wv?!1:xv(e)?Ev(e):!!e},Av=oi.normalize=function(i){return String(i).replace(Pv,".").toLowerCase()},kv=oi.data={},wv=oi.NATIVE="N",Rv=oi.POLYFILL="P";ec.exports=oi});var Er=f((SR,rc)=>{"use strict";var tc=Ys(),$v=it(),Lv=ti(),Mv=tc(tc.bind);rc.exports=function(i,e){return $v(i),e===void 0?i:Lv?Mv(i,e):function(){return i.apply(e,arguments)}}});var bn=f((vR,ic)=>{"use strict";var Cv=Le(),Dv=fe();ic.exports=Cv&&Dv(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var at=f((yR,ac)=>{"use strict";var Vv=Ce(),Ov=String,Bv=TypeError;ac.exports=function(i){if(Vv(i))return i;throw new Bv(Ov(i)+" is not an object")}});var Xt=f(nc=>{"use strict";var _v=Le(),Nv=mn(),Fv=bn(),Ba=at(),sc=pn(),qv=TypeError,gn=Object.defineProperty,Uv=Object.getOwnPropertyDescriptor,Sn="enumerable",vn="configurable",yn="writable";nc.f=_v?Fv?function(e,t,r){if(Ba(e),t=sc(t),Ba(r),typeof e=="function"&&t==="prototype"&&"value"in r&&yn in r&&!r[yn]){var a=Uv(e,t);a&&a[yn]&&(e[t]=r.value,r={configurable:vn in r?r[vn]:a[vn],enumerable:Sn in r?r[Sn]:a[Sn],writable:!1})}return gn(e,t,r)}:gn:function(e,t,r){if(Ba(e),t=sc(t),Ba(r),Nv)try{return gn(e,t,r)}catch{}if("get"in r||"set"in r)throw new qv("Accessors not supported");return"value"in r&&(e[t]=r.value),e}});var xr=f((IR,oc)=>{"use strict";var Hv=Le(),jv=Xt(),Qv=ri();oc.exports=Hv?function(i,e,t){return jv.f(i,e,Qv(1,t))}:function(i,e,t){return i[e]=t,i}});var le=f((ER,lc)=>{"use strict";var ui=ne(),Gv=Gs(),Wv=Ys(),Yv=se(),zv=Zl().f,Kv=fn(),Pr=yr(),Jv=Er(),Ar=xr(),uc=ze();ni();var Xv=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 Gv(i,this,arguments)};return e.prototype=i.prototype,e};lc.exports=function(i,e){var t=i.target,r=i.global,a=i.stat,s=i.proto,n=r?ui:a?ui[t]:ui[t]&&ui[t].prototype,o=r?Pr:Pr[t]||Ar(Pr,t,{})[t],u=o.prototype,l,c,d,h,m,b,g,y,T;for(h in e)l=Kv(r?h:t+(a?".":"#")+h,i.forced),c=!l&&n&&uc(n,h),b=o[h],c&&(i.dontCallGetSet?(T=zv(n,h),g=T&&T.value):g=n[h]),m=c&&g?g:e[h],!(!l&&!s&&typeof b==typeof m)&&(i.bind&&c?y=Jv(m,ui):i.wrap&&c?y=Xv(m):s&&Yv(m)?y=Wv(m):y=m,(i.sham||m&&m.sham||b&&b.sham)&&Ar(y,"sham",!0),Ar(o,h,y),s&&(d=t+"Prototype",uc(Pr,d)||Ar(Pr,d,{}),Ar(Pr[d],h,m),i.real&&u&&(l||!u[h])&&Ar(u,h,m)))}});var dc=f((xR,cc)=>{"use strict";var Zv=Math.ceil,ey=Math.floor;cc.exports=Math.trunc||function(e){var t=+e;return(t>0?ey:Zv)(t)}});var li=f((PR,pc)=>{"use strict";var ty=dc();pc.exports=function(i){var e=+i;return e!==e||e===0?0:ty(e)}});var mc=f((AR,hc)=>{"use strict";var ry=li(),iy=Math.max,ay=Math.min;hc.exports=function(i,e){var t=ry(i);return t<0?iy(t+e,0):ay(t,e)}});var Tn=f((kR,fc)=>{"use strict";var sy=li(),ny=Math.min;fc.exports=function(i){var e=sy(i);return e>0?ny(e,9007199254740991):0}});var kr=f((wR,bc)=>{"use strict";var oy=Tn();bc.exports=function(i){return oy(i.length)}});var In=f((RR,Sc)=>{"use strict";var uy=Kt(),ly=mc(),cy=kr(),gc=function(i){return function(e,t,r){var a=uy(e),s=cy(a);if(s===0)return!i&&-1;var n=ly(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}};Sc.exports={includes:gc(!0),indexOf:gc(!1)}});var ci=f(($R,vc)=>{"use strict";vc.exports=function(){}});var yc=f(()=>{"use strict";var dy=le(),py=In().includes,hy=fe(),my=ci(),fy=hy(function(){return!Array(1).includes()});dy({target:"Array",proto:!0,forced:fy},{includes:function(e){return py(this,e,arguments.length>1?arguments[1]:void 0)}});my("includes")});var Dt=f((CR,Tc)=>{"use strict";var by=gt();Tc.exports=by});var Ec=f((DR,Ic)=>{"use strict";yc();var gy=Dt();Ic.exports=gy("Array","includes")});var Pc=f((VR,xc)=>{"use strict";var Sy=Ec();xc.exports=Sy});var st=f((OR,Ac)=>{"use strict";var vy=Pc();Ac.exports=vy});var Na=f((WR,Rc)=>{"use strict";var Ty=ln(),Iy=cn(),wc=Ty("keys");Rc.exports=function(i){return wc[i]||(wc[i]=Iy(i))}});var Lc=f((YR,$c)=>{"use strict";var Ey=fe();$c.exports=!Ey(function(){function i(){}return i.prototype.constructor=null,Object.getPrototypeOf(new i)!==i.prototype})});var Fa=f((zR,Cc)=>{"use strict";var xy=ze(),Py=se(),Ay=Tr(),ky=Na(),wy=Lc(),Mc=ky("IE_PROTO"),En=Object,Ry=En.prototype;Cc.exports=wy?En.getPrototypeOf:function(i){var e=Ay(i);if(xy(e,Mc))return e[Mc];var t=e.constructor;return Py(t)&&e instanceof t?t.prototype:e instanceof En?Ry:null}});var qa=f((KR,Dc)=>{"use strict";Dc.exports={}});var Bc=f((JR,Oc)=>{"use strict";var $y=ce(),xn=ze(),Ly=Kt(),My=In().indexOf,Cy=qa(),Vc=$y([].push);Oc.exports=function(i,e){var t=Ly(i),r=0,a=[],s;for(s in t)!xn(Cy,s)&&xn(t,s)&&Vc(a,s);for(;e.length>r;)xn(t,s=e[r++])&&(~My(a,s)||Vc(a,s));return a}});var Pn=f((XR,_c)=>{"use strict";_c.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var An=f((ZR,Nc)=>{"use strict";var Dy=Bc(),Vy=Pn();Nc.exports=Object.keys||function(e){return Dy(e,Vy)}});var kn=f((e$,jc)=>{"use strict";var qc=Le(),Oy=fe(),Uc=ce(),By=Fa(),_y=An(),Ny=Kt(),Fy=Ks().f,Hc=Uc(Fy),qy=Uc([].push),Uy=qc&&Oy(function(){var i=Object.create(null);return i[2]=2,!Hc(i,2)}),Fc=function(i){return function(e){for(var t=Ny(e),r=_y(t),a=Uy&&By(t)===null,s=r.length,n=0,o=[],u;s>n;)u=r[n++],(!qc||(a?u in t:Hc(t,u)))&&qy(o,i?[u,t[u]]:t[u]);return o}};jc.exports={entries:Fc(!0),values:Fc(!1)}});var Qc=f(()=>{"use strict";var Hy=le(),jy=kn().entries;Hy({target:"Object",stat:!0},{entries:function(e){return jy(e)}})});var Wc=f((i$,Gc)=>{"use strict";Qc();var Qy=yr();Gc.exports=Qy.Object.entries});var zc=f((a$,Yc)=>{"use strict";var Gy=Wc();Yc.exports=Gy});var wr=f((s$,Kc)=>{"use strict";var Wy=zc();Kc.exports=Wy});var Zt=f((n$,Jc)=>{"use strict";Jc.exports={}});var ed=f((o$,Zc)=>{"use strict";var Yy=ne(),zy=se(),Xc=Yy.WeakMap;Zc.exports=zy(Xc)&&/native code/.test(String(Xc))});var Ln=f((u$,id)=>{"use strict";var Ky=ed(),rd=ne(),Jy=Ce(),Xy=xr(),wn=ze(),Rn=ni(),Zy=Na(),eT=qa(),td="Object already initialized",$n=rd.TypeError,tT=rd.WeakMap,Ua,di,Ha,rT=function(i){return Ha(i)?di(i):Ua(i,{})},iT=function(i){return function(e){var t;if(!Jy(e)||(t=di(e)).type!==i)throw new $n("Incompatible receiver, "+i+" required");return t}};Ky||Rn.state?(Ke=Rn.state||(Rn.state=new tT),Ke.get=Ke.get,Ke.has=Ke.has,Ke.set=Ke.set,Ua=function(i,e){if(Ke.has(i))throw new $n(td);return e.facade=i,Ke.set(i,e),e},di=function(i){return Ke.get(i)||{}},Ha=function(i){return Ke.has(i)}):(er=Zy("state"),eT[er]=!0,Ua=function(i,e){if(wn(i,er))throw new $n(td);return e.facade=i,Xy(i,er,e),e},di=function(i){return wn(i,er)?i[er]:{}},Ha=function(i){return wn(i,er)});var Ke,er;id.exports={set:Ua,get:di,has:Ha,enforce:rT,getterFor:iT}});var Dn=f((l$,sd)=>{"use strict";var Mn=Le(),aT=ze(),ad=Function.prototype,sT=Mn&&Object.getOwnPropertyDescriptor,Cn=aT(ad,"name"),nT=Cn&&function(){}.name==="something",oT=Cn&&(!Mn||Mn&&sT(ad,"name").configurable);sd.exports={EXISTS:Cn,PROPER:nT,CONFIGURABLE:oT}});var od=f(nd=>{"use strict";var uT=Le(),lT=bn(),cT=Xt(),dT=at(),pT=Kt(),hT=An();nd.f=uT&&!lT?Object.defineProperties:function(e,t){dT(e);for(var r=pT(t),a=hT(t),s=a.length,n=0,o;s>n;)cT.f(e,o=a[n++],r[o]);return e}});var Vn=f((d$,ud)=>{"use strict";var mT=gt();ud.exports=mT("document","documentElement")});var Nn=f((p$,fd)=>{"use strict";var fT=at(),bT=od(),ld=Pn(),gT=qa(),ST=Vn(),vT=Oa(),yT=Na(),cd=">",dd="<",Bn="prototype",_n="script",hd=yT("IE_PROTO"),On=function(){},md=function(i){return dd+_n+cd+i+dd+"/"+_n+cd},pd=function(i){i.write(md("")),i.close();var e=i.parentWindow.Object;return i=null,e},TT=function(){var i=vT("iframe"),e="java"+_n+":",t;return i.style.display="none",ST.appendChild(i),i.src=String(e),t=i.contentWindow.document,t.open(),t.write(md("document.F=Object")),t.close(),t.F},ja,Qa=function(){try{ja=new ActiveXObject("htmlfile")}catch{}Qa=typeof document<"u"?document.domain&&ja?pd(ja):TT():pd(ja);for(var i=ld.length;i--;)delete Qa[Bn][ld[i]];return Qa()};gT[hd]=!0;fd.exports=Object.create||function(e,t){var r;return e!==null?(On[Bn]=fT(e),r=new On,On[Bn]=null,r[hd]=e):r=Qa(),t===void 0?r:bT.f(r,t)}});var Rr=f((h$,bd)=>{"use strict";var IT=xr();bd.exports=function(i,e,t,r){return r&&r.enumerable?i[e]=t:IT(i,e,t),i}});var Hn=f((m$,vd)=>{"use strict";var ET=fe(),xT=se(),PT=Ce(),AT=Nn(),gd=Fa(),kT=Rr(),wT=be(),RT=Ye(),Un=wT("iterator"),Sd=!1,St,Fn,qn;[].keys&&(qn=[].keys(),"next"in qn?(Fn=gd(gd(qn)),Fn!==Object.prototype&&(St=Fn)):Sd=!0);var $T=!PT(St)||ET(function(){var i={};return St[Un].call(i)!==i});$T?St={}:RT&&(St=AT(St));xT(St[Un])||kT(St,Un,function(){return this});vd.exports={IteratorPrototype:St,BUGGY_SAFARI_ITERATORS:Sd}});var Ga=f((f$,Td)=>{"use strict";var LT=be(),MT=LT("toStringTag"),yd={};yd[MT]="z";Td.exports=String(yd)==="[object z]"});var pi=f((b$,Id)=>{"use strict";var CT=Ga(),DT=se(),Wa=zt(),VT=be(),OT=VT("toStringTag"),BT=Object,_T=Wa(function(){return arguments}())==="Arguments",NT=function(i,e){try{return i[e]}catch{}};Id.exports=CT?Wa:function(i){var e,t,r;return i===void 0?"Undefined":i===null?"Null":typeof(t=NT(e=BT(i),OT))=="string"?t:_T?Wa(e):(r=Wa(e))==="Object"&&DT(e.callee)?"Arguments":r}});var xd=f((g$,Ed)=>{"use strict";var FT=Ga(),qT=pi();Ed.exports=FT?{}.toString:function(){return"[object "+qT(this)+"]"}});var hi=f((S$,Ad)=>{"use strict";var UT=Ga(),HT=Xt().f,jT=xr(),QT=ze(),GT=xd(),WT=be(),Pd=WT("toStringTag");Ad.exports=function(i,e,t,r){var a=t?i:i&&i.prototype;a&&(QT(a,Pd)||HT(a,Pd,{configurable:!0,value:e}),r&&!UT&&jT(a,"toString",GT))}});var wd=f((v$,kd)=>{"use strict";var YT=Hn().IteratorPrototype,zT=Nn(),KT=ri(),JT=hi(),XT=Zt(),ZT=function(){return this};kd.exports=function(i,e,t,r){var a=e+" Iterator";return i.prototype=zT(YT,{next:KT(+!r,t)}),JT(i,a,!1,!0),XT[a]=ZT,i}});var $d=f((y$,Rd)=>{"use strict";var eI=ce(),tI=it();Rd.exports=function(i,e,t){try{return eI(tI(Object.getOwnPropertyDescriptor(i,e)[t]))}catch{}}});var Md=f((T$,Ld)=>{"use strict";var rI=Ce();Ld.exports=function(i){return rI(i)||i===null}});var Dd=f((I$,Cd)=>{"use strict";var iI=Md(),aI=String,sI=TypeError;Cd.exports=function(i){if(iI(i))return i;throw new sI("Can't set "+aI(i)+" as a prototype")}});var jn=f((E$,Vd)=>{"use strict";var nI=$d(),oI=Ce(),uI=Ct(),lI=Dd();Vd.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var i=!1,e={},t;try{t=nI(Object.prototype,"__proto__","set"),t(e,[]),i=e instanceof Array}catch{}return function(a,s){return uI(a),lI(s),oI(a)&&(i?t(a,s):a.__proto__=s),a}}():void 0)});var Gd=f((x$,Qd)=>{"use strict";var cI=le(),dI=Me(),Ya=Ye(),Hd=Dn(),pI=se(),hI=wd(),Od=Fa(),Bd=jn(),mI=hi(),fI=xr(),Qn=Rr(),bI=be(),_d=Zt(),jd=Hn(),gI=Hd.PROPER,SI=Hd.CONFIGURABLE,Nd=jd.IteratorPrototype,za=jd.BUGGY_SAFARI_ITERATORS,mi=bI("iterator"),Fd="keys",fi="values",qd="entries",Ud=function(){return this};Qd.exports=function(i,e,t,r,a,s,n){hI(t,e,r);var o=function(T){if(T===a&&h)return h;if(!za&&T&&T in c)return c[T];switch(T){case Fd:return function(){return new t(this,T)};case fi:return function(){return new t(this,T)};case qd:return function(){return new t(this,T)}}return function(){return new t(this)}},u=e+" Iterator",l=!1,c=i.prototype,d=c[mi]||c["@@iterator"]||a&&c[a],h=!za&&d||o(a),m=e==="Array"&&c.entries||d,b,g,y;if(m&&(b=Od(m.call(new i)),b!==Object.prototype&&b.next&&(!Ya&&Od(b)!==Nd&&(Bd?Bd(b,Nd):pI(b[mi])||Qn(b,mi,Ud)),mI(b,u,!0,!0),Ya&&(_d[u]=Ud))),gI&&a===fi&&d&&d.name!==fi&&(!Ya&&SI?fI(c,"name",fi):(l=!0,h=function(){return dI(d,this)})),a)if(g={values:o(fi),keys:s?h:o(Fd),entries:o(qd)},n)for(y in g)(za||l||!(y in c))&&Qn(c,y,g[y]);else cI({target:e,proto:!0,forced:za||l},g);return(!Ya||n)&&c[mi]!==h&&Qn(c,mi,h,{name:a}),_d[e]=h,g}});var Yd=f((P$,Wd)=>{"use strict";Wd.exports=function(i,e){return{value:i,done:e}}});var Wn=f((A$,Zd)=>{"use strict";var vI=Kt(),Gn=ci(),zd=Zt(),Jd=Ln(),yI=Xt().f,TI=Gd(),Ka=Yd(),II=Ye(),EI=Le(),Xd="Array Iterator",xI=Jd.set,PI=Jd.getterFor(Xd);Zd.exports=TI(Array,"Array",function(i,e){xI(this,{type:Xd,target:vI(i),index:0,kind:e})},function(){var i=PI(this),e=i.target,t=i.index++;if(!e||t>=e.length)return i.target=void 0,Ka(void 0,!0);switch(i.kind){case"keys":return Ka(t,!1);case"values":return Ka(e[t],!1)}return Ka([t,e[t]],!1)},"values");var Kd=zd.Arguments=zd.Array;Gn("keys");Gn("values");Gn("entries");if(!II&&EI&&Kd.name!=="values")try{yI(Kd,"name",{value:"values"})}catch{}});var tp=f((k$,ep)=>{"use strict";var AI=be(),kI=Zt(),wI=AI("iterator"),RI=Array.prototype;ep.exports=function(i){return i!==void 0&&(kI.Array===i||RI[wI]===i)}});var Yn=f((w$,ip)=>{"use strict";var $I=pi(),rp=si(),LI=vr(),MI=Zt(),CI=be(),DI=CI("iterator");ip.exports=function(i){if(!LI(i))return rp(i,DI)||rp(i,"@@iterator")||MI[$I(i)]}});var sp=f((R$,ap)=>{"use strict";var VI=Me(),OI=it(),BI=at(),_I=ai(),NI=Yn(),FI=TypeError;ap.exports=function(i,e){var t=arguments.length<2?NI(i):e;if(OI(t))return BI(VI(t,i));throw new FI(_I(i)+" is not iterable")}});var up=f(($$,op)=>{"use strict";var qI=Me(),np=at(),UI=si();op.exports=function(i,e,t){var r,a;np(i);try{if(r=UI(i,"return"),!r){if(e==="throw")throw t;return t}r=qI(r,i)}catch(s){a=!0,r=s}if(e==="throw")throw t;if(a)throw r;return np(r),t}});var Xa=f((L$,pp)=>{"use strict";var HI=Er(),jI=Me(),QI=at(),GI=ai(),WI=tp(),YI=kr(),lp=ii(),zI=sp(),KI=Yn(),cp=up(),JI=TypeError,Ja=function(i,e){this.stopped=i,this.result=e},dp=Ja.prototype;pp.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),u=HI(e,r),l,c,d,h,m,b,g,y=function($){return l&&cp(l,"normal",$),new Ja(!0,$)},T=function($){return a?(QI($),o?u($[0],$[1],y):u($[0],$[1])):o?u($,y):u($)};if(s)l=i.iterator;else if(n)l=i;else{if(c=KI(i),!c)throw new JI(GI(i)+" is not iterable");if(WI(c)){for(d=0,h=YI(i);h>d;d++)if(m=T(i[d]),m&&lp(dp,m))return m;return new Ja(!1)}l=zI(i,c)}for(b=s?i.next:l.next;!(g=jI(b,l)).done;){try{m=T(g.value)}catch($){cp(l,"throw",$)}if(typeof m=="object"&&m&&lp(dp,m))return m}return new Ja(!1)}});var mp=f((M$,hp)=>{"use strict";var XI=Le(),ZI=Xt(),eE=ri();hp.exports=function(i,e,t){XI?ZI.f(i,e,eE(0,t)):i[e]=t}});var fp=f(()=>{"use strict";var tE=le(),rE=Xa(),iE=mp();tE({target:"Object",stat:!0},{fromEntries:function(e){var t={};return rE(e,function(r,a){iE(t,r,a)},{AS_ENTRIES:!0}),t}})});var gp=f((V$,bp)=>{"use strict";Wn();fp();var aE=yr();bp.exports=aE.Object.fromEntries});var vp=f((O$,Sp)=>{"use strict";Sp.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 Tp=f(()=>{"use strict";Wn();var sE=vp(),nE=ne(),oE=hi(),yp=Zt();for(Za in sE)oE(nE[Za],Za),yp[Za]=yp.Array;var Za});var Ep=f((N$,Ip)=>{"use strict";var uE=gp();Tp();Ip.exports=uE});var zn=f((F$,xp)=>{"use strict";var lE=Ep();xp.exports=lE});var Pp=f(()=>{"use strict"});var Kn=f((H$,Ap)=>{"use strict";var bi=ne(),cE=Jt(),dE=zt(),es=function(i){return cE.slice(0,i.length)===i};Ap.exports=function(){return es("Bun/")?"BUN":es("Cloudflare-Workers")?"CLOUDFLARE":es("Deno/")?"DENO":es("Node.js/")?"NODE":bi.Bun&&typeof Bun.version=="string"?"BUN":bi.Deno&&typeof Deno.version=="object"?"DENO":dE(bi.process)==="process"?"NODE":bi.window&&bi.document?"BROWSER":"REST"}()});var ts=f((j$,kp)=>{"use strict";var pE=Kn();kp.exports=pE==="NODE"});var Rp=f((Q$,wp)=>{"use strict";var hE=Xt();wp.exports=function(i,e,t){return hE.f(i,e,t)}});var Mp=f((G$,Lp)=>{"use strict";var mE=gt(),fE=Rp(),bE=be(),gE=Le(),$p=bE("species");Lp.exports=function(i){var e=mE(i);gE&&e&&!e[$p]&&fE(e,$p,{configurable:!0,get:function(){return this}})}});var Dp=f((W$,Cp)=>{"use strict";var SE=ii(),vE=TypeError;Cp.exports=function(i,e){if(SE(e,i))return i;throw new vE("Incorrect invocation")}});var Xn=f((Y$,Vp)=>{"use strict";var yE=ce(),TE=se(),Jn=ni(),IE=yE(Function.toString);TE(Jn.inspectSource)||(Jn.inspectSource=function(i){return IE(i)});Vp.exports=Jn.inspectSource});var eo=f((z$,Fp)=>{"use strict";var EE=ce(),xE=fe(),Op=se(),PE=pi(),AE=gt(),kE=Xn(),Bp=function(){},_p=AE("Reflect","construct"),Zn=/^\s*(?:class|function)\b/,wE=EE(Zn.exec),RE=!Zn.test(Bp),gi=function(e){if(!Op(e))return!1;try{return _p(Bp,[],e),!0}catch{return!1}},Np=function(e){if(!Op(e))return!1;switch(PE(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return RE||!!wE(Zn,kE(e))}catch{return!0}};Np.sham=!0;Fp.exports=!_p||xE(function(){var i;return gi(gi.call)||!gi(Object)||!gi(function(){i=!0})||i})?Np:gi});var Up=f((K$,qp)=>{"use strict";var $E=eo(),LE=ai(),ME=TypeError;qp.exports=function(i){if($E(i))return i;throw new ME(LE(i)+" is not a constructor")}});var to=f((J$,jp)=>{"use strict";var Hp=at(),CE=Up(),DE=vr(),VE=be(),OE=VE("species");jp.exports=function(i,e){var t=Hp(i).constructor,r;return t===void 0||DE(r=Hp(t)[OE])?e:CE(r)}});var Gp=f((X$,Qp)=>{"use strict";var BE=ce();Qp.exports=BE([].slice)});var Yp=f((Z$,Wp)=>{"use strict";var _E=TypeError;Wp.exports=function(i,e){if(i<e)throw new _E("Not enough arguments");return i}});var ro=f((eL,zp)=>{"use strict";var NE=Jt();zp.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(NE)});var po=f((tL,ah)=>{"use strict";var De=ne(),FE=Gs(),qE=Er(),Kp=se(),UE=ze(),ih=fe(),Jp=Vn(),HE=Gp(),Xp=Oa(),jE=Yp(),QE=ro(),GE=ts(),uo=De.setImmediate,lo=De.clearImmediate,WE=De.process,io=De.Dispatch,YE=De.Function,Zp=De.MessageChannel,zE=De.String,ao=0,Si={},eh="onreadystatechange",vi,tr,so,no;ih(function(){vi=De.location});var co=function(i){if(UE(Si,i)){var e=Si[i];delete Si[i],e()}},oo=function(i){return function(){co(i)}},th=function(i){co(i.data)},rh=function(i){De.postMessage(zE(i),vi.protocol+"//"+vi.host)};(!uo||!lo)&&(uo=function(e){jE(arguments.length,1);var t=Kp(e)?e:YE(e),r=HE(arguments,1);return Si[++ao]=function(){FE(t,void 0,r)},tr(ao),ao},lo=function(e){delete Si[e]},GE?tr=function(i){WE.nextTick(oo(i))}:io&&io.now?tr=function(i){io.now(oo(i))}:Zp&&!QE?(so=new Zp,no=so.port2,so.port1.onmessage=th,tr=qE(no.postMessage,no)):De.addEventListener&&Kp(De.postMessage)&&!De.importScripts&&vi&&vi.protocol!=="file:"&&!ih(rh)?(tr=rh,De.addEventListener("message",th,!1)):eh in Xp("script")?tr=function(i){Jp.appendChild(Xp("script"))[eh]=function(){Jp.removeChild(this),co(i)}}:tr=function(i){setTimeout(oo(i),0)});ah.exports={set:uo,clear:lo}});var oh=f((rL,nh)=>{"use strict";var sh=ne(),KE=Le(),JE=Object.getOwnPropertyDescriptor;nh.exports=function(i){if(!KE)return sh[i];var e=JE(sh,i);return e&&e.value}});var ho=f((iL,lh)=>{"use strict";var uh=function(){this.head=null,this.tail=null};uh.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}}};lh.exports=uh});var dh=f((aL,ch)=>{"use strict";var XE=Jt();ch.exports=/ipad|iphone|ipod/i.test(XE)&&typeof Pebble<"u"});var hh=f((sL,ph)=>{"use strict";var ZE=Jt();ph.exports=/web0s(?!.*chrome)/i.test(ZE)});var yh=f((nL,vh)=>{"use strict";var Lr=ne(),ex=oh(),mh=Er(),mo=po().set,tx=ho(),rx=ro(),ix=dh(),ax=hh(),fo=ts(),fh=Lr.MutationObserver||Lr.WebKitMutationObserver,bh=Lr.document,gh=Lr.process,rs=Lr.Promise,So=ex("queueMicrotask"),$r,bo,go,is,Sh;So||(yi=new tx,Ti=function(){var i,e;for(fo&&(i=gh.domain)&&i.exit();e=yi.get();)try{e()}catch(t){throw yi.head&&$r(),t}i&&i.enter()},!rx&&!fo&&!ax&&fh&&bh?(bo=!0,go=bh.createTextNode(""),new fh(Ti).observe(go,{characterData:!0}),$r=function(){go.data=bo=!bo}):!ix&&rs&&rs.resolve?(is=rs.resolve(void 0),is.constructor=rs,Sh=mh(is.then,is),$r=function(){Sh(Ti)}):fo?$r=function(){gh.nextTick(Ti)}:(mo=mh(mo,Lr),$r=function(){mo(Ti)}),So=function(i){yi.head||$r(),yi.add(i)});var yi,Ti;vh.exports=So});var Ih=f((oL,Th)=>{"use strict";Th.exports=function(i,e){try{arguments.length===1?console.error(i):console.error(i,e)}catch{}}});var as=f((uL,Eh)=>{"use strict";Eh.exports=function(i){try{return{error:!1,value:i()}}catch(e){return{error:!0,value:e}}}});var rr=f((lL,xh)=>{"use strict";var sx=ne();xh.exports=sx.Promise});var Mr=f((cL,wh)=>{"use strict";var nx=ne(),Ii=rr(),ox=se(),ux=fn(),lx=Xn(),cx=be(),Ph=Kn(),dx=Ye(),vo=tn(),Ah=Ii&&Ii.prototype,px=cx("species"),yo=!1,kh=ox(nx.PromiseRejectionEvent),hx=ux("Promise",function(){var i=lx(Ii),e=i!==String(Ii);if(!e&&vo===66||dx&&!(Ah.catch&&Ah.finally))return!0;if(!vo||vo<51||!/native code/.test(i)){var t=new Ii(function(s){s(1)}),r=function(s){s(function(){},function(){})},a=t.constructor={};if(a[px]=r,yo=t.then(function(){})instanceof r,!yo)return!0}return!e&&(Ph==="BROWSER"||Ph==="DENO")&&!kh});wh.exports={CONSTRUCTOR:hx,REJECTION_EVENT:kh,SUBCLASSING:yo}});var Cr=f((dL,$h)=>{"use strict";var Rh=it(),mx=TypeError,fx=function(i){var e,t;this.promise=new i(function(r,a){if(e!==void 0||t!==void 0)throw new mx("Bad Promise constructor");e=r,t=a}),this.resolve=Rh(e),this.reject=Rh(t)};$h.exports.f=function(i){return new fx(i)}});var zh=f(()=>{"use strict";var bx=le(),gx=Ye(),us=ts(),Vt=ne(),Br=Me(),Lh=Rr(),Mh=jn(),Sx=hi(),vx=Mp(),yx=it(),os=se(),Tx=Ce(),Ix=Dp(),Ex=to(),Bh=po().set,Po=yh(),xx=Ih(),Px=as(),Ax=ho(),_h=Ln(),ls=rr(),Ao=Mr(),Nh=Cr(),cs="Promise",Fh=Ao.CONSTRUCTOR,kx=Ao.REJECTION_EVENT,wx=Ao.SUBCLASSING,To=_h.getterFor(cs),Rx=_h.set,Dr=ls&&ls.prototype,ir=ls,ss=Dr,qh=Vt.TypeError,Io=Vt.document,ko=Vt.process,Eo=Nh.f,$x=Eo,Lx=!!(Io&&Io.createEvent&&Vt.dispatchEvent),Uh="unhandledrejection",Mx="rejectionhandled",Ch=0,Hh=1,Cx=2,wo=1,jh=2,ns,Dh,Dx,Vh,Qh=function(i){var e;return Tx(i)&&os(e=i.then)?e:!1},Gh=function(i,e){var t=e.value,r=e.state===Hh,a=r?i.ok:i.fail,s=i.resolve,n=i.reject,o=i.domain,u,l,c;try{a?(r||(e.rejection===jh&&Ox(e),e.rejection=wo),a===!0?u=t:(o&&o.enter(),u=a(t),o&&(o.exit(),c=!0)),u===i.promise?n(new qh("Promise-chain cycle")):(l=Qh(u))?Br(l,u,s,n):s(u)):n(t)}catch(d){o&&!c&&o.exit(),n(d)}},Wh=function(i,e){i.notified||(i.notified=!0,Po(function(){for(var t=i.reactions,r;r=t.get();)Gh(r,i);i.notified=!1,e&&!i.rejection&&Vx(i)}))},Yh=function(i,e,t){var r,a;Lx?(r=Io.createEvent("Event"),r.promise=e,r.reason=t,r.initEvent(i,!1,!0),Vt.dispatchEvent(r)):r={promise:e,reason:t},!kx&&(a=Vt["on"+i])?a(r):i===Uh&&xx("Unhandled promise rejection",t)},Vx=function(i){Br(Bh,Vt,function(){var e=i.facade,t=i.value,r=Oh(i),a;if(r&&(a=Px(function(){us?ko.emit("unhandledRejection",t,e):Yh(Uh,e,t)}),i.rejection=us||Oh(i)?jh:wo,a.error))throw a.value})},Oh=function(i){return i.rejection!==wo&&!i.parent},Ox=function(i){Br(Bh,Vt,function(){var e=i.facade;us?ko.emit("rejectionHandled",e):Yh(Mx,e,i.value)})},Vr=function(i,e,t){return function(r){i(e,r,t)}},Or=function(i,e,t){i.done||(i.done=!0,t&&(i=t),i.value=e,i.state=Cx,Wh(i,!0))},xo=function(i,e,t){if(!i.done){i.done=!0,t&&(i=t);try{if(i.facade===e)throw new qh("Promise can't be resolved itself");var r=Qh(e);r?Po(function(){var a={done:!1};try{Br(r,e,Vr(xo,a,i),Vr(Or,a,i))}catch(s){Or(a,s,i)}}):(i.value=e,i.state=Hh,Wh(i,!1))}catch(a){Or({done:!1},a,i)}}};if(Fh&&(ir=function(e){Ix(this,ss),yx(e),Br(ns,this);var t=To(this);try{e(Vr(xo,t),Vr(Or,t))}catch(r){Or(t,r)}},ss=ir.prototype,ns=function(e){Rx(this,{type:cs,done:!1,notified:!1,parent:!1,reactions:new Ax,rejection:!1,state:Ch,value:void 0})},ns.prototype=Lh(ss,"then",function(e,t){var r=To(this),a=Eo(Ex(this,ir));return r.parent=!0,a.ok=os(e)?e:!0,a.fail=os(t)&&t,a.domain=us?ko.domain:void 0,r.state===Ch?r.reactions.add(a):Po(function(){Gh(a,r)}),a.promise}),Dh=function(){var i=new ns,e=To(i);this.promise=i,this.resolve=Vr(xo,e),this.reject=Vr(Or,e)},Nh.f=Eo=function(i){return i===ir||i===Dx?new Dh(i):$x(i)},!gx&&os(ls)&&Dr!==Object.prototype)){Vh=Dr.then,wx||Lh(Dr,"then",function(e,t){var r=this;return new ir(function(a,s){Br(Vh,r,a,s)}).then(e,t)},{unsafe:!0});try{delete Dr.constructor}catch{}Mh&&Mh(Dr,ss)}bx({global:!0,constructor:!0,wrap:!0,forced:Fh},{Promise:ir});Sx(ir,cs,!1,!0);vx(cs)});var em=f((mL,Zh)=>{"use strict";var Bx=be(),Jh=Bx("iterator"),Xh=!1;try{Kh=0,Ro={next:function(){return{done:!!Kh++}},return:function(){Xh=!0}},Ro[Jh]=function(){return this},Array.from(Ro,function(){throw 2})}catch{}var Kh,Ro;Zh.exports=function(i,e){try{if(!e&&!Xh)return!1}catch{return!1}var t=!1;try{var r={};r[Jh]=function(){return{next:function(){return{done:t=!0}}}},i(r)}catch{}return t}});var $o=f((fL,tm)=>{"use strict";var _x=rr(),Nx=em(),Fx=Mr().CONSTRUCTOR;tm.exports=Fx||!Nx(function(i){_x.all(i).then(void 0,function(){})})});var rm=f(()=>{"use strict";var qx=le(),Ux=Me(),Hx=it(),jx=Cr(),Qx=as(),Gx=Xa(),Wx=$o();qx({target:"Promise",stat:!0,forced:Wx},{all:function(e){var t=this,r=jx.f(t),a=r.resolve,s=r.reject,n=Qx(function(){var o=Hx(t.resolve),u=[],l=0,c=1;Gx(e,function(d){var h=l++,m=!1;c++,Ux(o,t,d).then(function(b){m||(m=!0,u[h]=b,--c||a(u))},s)}),--c||a(u)});return n.error&&s(n.value),r.promise}})});var am=f(()=>{"use strict";var Yx=le(),zx=Ye(),Kx=Mr().CONSTRUCTOR,Mo=rr(),Jx=gt(),Xx=se(),Zx=Rr(),im=Mo&&Mo.prototype;Yx({target:"Promise",proto:!0,forced:Kx,real:!0},{catch:function(i){return this.then(void 0,i)}});!zx&&Xx(Mo)&&(Lo=Jx("Promise").prototype.catch,im.catch!==Lo&&Zx(im,"catch",Lo,{unsafe:!0}));var Lo});var sm=f(()=>{"use strict";var eP=le(),tP=Me(),rP=it(),iP=Cr(),aP=as(),sP=Xa(),nP=$o();eP({target:"Promise",stat:!0,forced:nP},{race:function(e){var t=this,r=iP.f(t),a=r.reject,s=aP(function(){var n=rP(t.resolve);sP(e,function(o){tP(n,t,o).then(r.resolve,a)})});return s.error&&a(s.value),r.promise}})});var nm=f(()=>{"use strict";var oP=le(),uP=Cr(),lP=Mr().CONSTRUCTOR;oP({target:"Promise",stat:!0,forced:lP},{reject:function(e){var t=uP.f(this),r=t.reject;return r(e),t.promise}})});var Co=f((xL,om)=>{"use strict";var cP=at(),dP=Ce(),pP=Cr();om.exports=function(i,e){if(cP(i),dP(e)&&e.constructor===i)return e;var t=pP.f(i),r=t.resolve;return r(e),t.promise}});var cm=f(()=>{"use strict";var hP=le(),mP=gt(),um=Ye(),fP=rr(),lm=Mr().CONSTRUCTOR,bP=Co(),gP=mP("Promise"),SP=um&&!lm;hP({target:"Promise",stat:!0,forced:um||lm},{resolve:function(e){return bP(SP&&this===gP?fP:this,e)}})});var dm=f(()=>{"use strict";zh();rm();am();sm();nm();cm()});var fm=f(()=>{"use strict";var vP=le(),yP=Ye(),ds=rr(),TP=fe(),hm=gt(),mm=se(),IP=to(),pm=Co(),EP=Rr(),Vo=ds&&ds.prototype,xP=!!ds&&TP(function(){Vo.finally.call({then:function(){}},function(){})});vP({target:"Promise",proto:!0,real:!0,forced:xP},{finally:function(i){var e=IP(this,hm("Promise")),t=mm(i);return this.then(t?function(r){return pm(e,i()).then(function(){return r})}:i,t?function(r){return pm(e,i()).then(function(){throw r})}:i)}});!yP&&mm(ds)&&(Do=hm("Promise").prototype.finally,Vo.finally!==Do&&EP(Vo,"finally",Do,{unsafe:!0}));var Do});var gm=f((LL,bm)=>{"use strict";Pp();dm();fm();var PP=Dt();bm.exports=PP("Promise","finally")});var vm=f((ML,Sm)=>{"use strict";var AP=gm();Sm.exports=AP});var ps=f((CL,ym)=>{"use strict";var kP=vm();ym.exports=kP});var km=f(()=>{"use strict";var MP=le(),CP=kn().values;MP({target:"Object",stat:!0},{values:function(e){return CP(e)}})});var Rm=f((cM,wm)=>{"use strict";km();var DP=yr();wm.exports=DP.Object.values});var Lm=f((dM,$m)=>{"use strict";var VP=Rm();$m.exports=VP});var xi=f((pM,Mm)=>{"use strict";var OP=Lm();Mm.exports=OP});var Om=f(()=>{"use strict";var FP=le(),qP=Tr(),UP=kr(),HP=li(),jP=ci();FP({target:"Array",proto:!0},{at:function(e){var t=qP(this),r=UP(t),a=HP(e),s=a>=0?a:r+a;return s<0||s>=r?void 0:t[s]}});jP("at")});var _m=f((OM,Bm)=>{"use strict";Om();var QP=Dt();Bm.exports=QP("Array","at")});var Fm=f((BM,Nm)=>{"use strict";var GP=_m();Nm.exports=GP});var _r=f((_M,qm)=>{"use strict";var WP=Fm();qm.exports=WP});var Xo=f((l0,uf)=>{"use strict";var sA=zt();uf.exports=Array.isArray||function(e){return sA(e)==="Array"}});var cf=f((c0,lf)=>{"use strict";var nA=TypeError,oA=9007199254740991;lf.exports=function(i){if(i>oA)throw nA("Maximum allowed index exceeded");return i}});var hf=f((d0,pf)=>{"use strict";var uA=Xo(),lA=kr(),cA=cf(),dA=Er(),df=function(i,e,t,r,a,s,n,o){for(var u=a,l=0,c=n?dA(n,o):!1,d,h;l<r;)l in t&&(d=c?c(t[l],l,e):t[l],s>0&&uA(d)?(h=lA(d),u=df(i,e,d,h,u,s-1)-1):(cA(u+1),i[u]=d),u++),l++;return u};pf.exports=df});var gf=f((p0,bf)=>{"use strict";var mf=Xo(),pA=eo(),hA=Ce(),mA=be(),fA=mA("species"),ff=Array;bf.exports=function(i){var e;return mf(i)&&(e=i.constructor,pA(e)&&(e===ff||mf(e.prototype))?e=void 0:hA(e)&&(e=e[fA],e===null&&(e=void 0))),e===void 0?ff:e}});var vf=f((h0,Sf)=>{"use strict";var bA=gf();Sf.exports=function(i,e){return new(bA(i))(e===0?0:e)}});var yf=f(()=>{"use strict";var gA=le(),SA=hf(),vA=it(),yA=Tr(),TA=kr(),IA=vf();gA({target:"Array",proto:!0},{flatMap:function(e){var t=yA(this),r=TA(t),a;return vA(e),a=IA(t,0),a.length=SA(a,t,t,r,0,1,e,arguments.length>1?arguments[1]:void 0),a}})});var Tf=f(()=>{"use strict";var EA=ci();EA("flatMap")});var Ef=f((S0,If)=>{"use strict";yf();Tf();var xA=Dt();If.exports=xA("Array","flatMap")});var Pf=f((v0,xf)=>{"use strict";var PA=Ef();xf.exports=PA});var Zo=f((y0,Af)=>{"use strict";var AA=Pf();Af.exports=AA});var Vi=f((R0,Of)=>{"use strict";var DA=pi(),VA=String;Of.exports=function(i){if(DA(i)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return VA(i)}});var tu=f(($0,Bf)=>{"use strict";Bf.exports=`
7
- \v\f\r \xA0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028\u2029\uFEFF`});var Ff=f((L0,Nf)=>{"use strict";var OA=ce(),BA=Ct(),_A=Vi(),iu=tu(),_f=OA("".replace),NA=RegExp("^["+iu+"]+"),FA=RegExp("(^|[^"+iu+"])["+iu+"]+$"),ru=function(i){return function(e){var t=_A(BA(e));return i&1&&(t=_f(t,NA,"")),i&2&&(t=_f(t,FA,"$1")),t}};Nf.exports={start:ru(1),end:ru(2),trim:ru(3)}});var jf=f((M0,Hf)=>{"use strict";var qA=Dn().PROPER,UA=fe(),qf=tu(),Uf="\u200B\x85\u180E";Hf.exports=function(i){return UA(function(){return!!qf[i]()||Uf[i]()!==Uf||qA&&qf[i].name!==i})}});var au=f((C0,Qf)=>{"use strict";var HA=Ff().start,jA=jf();Qf.exports=jA("trimStart")?function(){return HA(this)}:"".trimStart});var Wf=f(()=>{"use strict";var QA=le(),Gf=au();QA({target:"String",proto:!0,name:"trimStart",forced:"".trimLeft!==Gf},{trimLeft:Gf})});var zf=f(()=>{"use strict";Wf();var GA=le(),Yf=au();GA({target:"String",proto:!0,name:"trimStart",forced:"".trimStart!==Yf},{trimStart:Yf})});var Jf=f((_0,Kf)=>{"use strict";zf();var WA=Dt();Kf.exports=WA("String","trimLeft")});var Zf=f((N0,Xf)=>{"use strict";var YA=Jf();Xf.exports=YA});var tb=f((F0,eb)=>{"use strict";var zA=Zf();eb.exports=zA});var fb=f(()=>{"use strict"});var bb=f(()=>{"use strict"});var Sb=f((nO,gb)=>{"use strict";var fk=Ce(),bk=zt(),gk=be(),Sk=gk("match");gb.exports=function(i){var e;return fk(i)&&((e=i[Sk])!==void 0?!!e:bk(i)==="RegExp")}});var yb=f((oO,vb)=>{"use strict";var vk=at();vb.exports=function(){var i=vk(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 Eb=f((uO,Ib)=>{"use strict";var yk=Me(),Tk=ze(),Ik=ii(),Ek=yb(),Tb=RegExp.prototype;Ib.exports=function(i){var e=i.flags;return e===void 0&&!("flags"in Tb)&&!Tk(i,"flags")&&Ik(Tb,i)?yk(Ek,i):e}});var Pb=f((lO,xb)=>{"use strict";var du=ce(),xk=Tr(),Pk=Math.floor,lu=du("".charAt),Ak=du("".replace),cu=du("".slice),kk=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,wk=/\$([$&'`]|\d{1,2})/g;xb.exports=function(i,e,t,r,a,s){var n=t+i.length,o=r.length,u=wk;return a!==void 0&&(a=xk(a),u=kk),Ak(s,u,function(l,c){var d;switch(lu(c,0)){case"$":return"$";case"&":return i;case"`":return cu(e,0,t);case"'":return cu(e,n);case"<":d=a[cu(c,1,-1)];break;default:var h=+c;if(h===0)return l;if(h>o){var m=Pk(h/10);return m===0?l:m<=o?r[m-1]===void 0?lu(c,1):r[m-1]+lu(c,1):l}d=r[h-1]}return d===void 0?"":d})}});var wb=f(()=>{"use strict";var Rk=le(),$k=Me(),hu=ce(),Ab=Ct(),Lk=se(),Mk=vr(),Ck=Sb(),Qr=Vi(),Dk=si(),Vk=Eb(),Ok=Pb(),Bk=be(),_k=Ye(),Nk=Bk("replace"),Fk=TypeError,pu=hu("".indexOf),qk=hu("".replace),kb=hu("".slice),Uk=Math.max;Rk({target:"String",proto:!0},{replaceAll:function(e,t){var r=Ab(this),a,s,n,o,u,l,c,d,h,m,b=0,g="";if(!Mk(e)){if(a=Ck(e),a&&(s=Qr(Ab(Vk(e))),!~pu(s,"g")))throw new Fk("`.replaceAll` does not allow non-global regexes");if(n=Dk(e,Nk),n)return $k(n,e,r,t);if(_k&&a)return qk(Qr(r),e,t)}for(o=Qr(r),u=Qr(e),l=Lk(t),l||(t=Qr(t)),c=u.length,d=Uk(1,c),h=pu(o,u);h!==-1;)m=l?Qr(t(u,h,o)):Ok(u,o,h,[],void 0,t),g+=kb(o,b,h)+m,b=h+c,h=h+d>o.length?-1:pu(o,u,h+d);return b<o.length&&(g+=kb(o,b)),g}})});var $b=f((pO,Rb)=>{"use strict";fb();bb();wb();var Hk=Dt();Rb.exports=Hk("String","replaceAll")});var Mb=f((hO,Lb)=>{"use strict";var jk=$b();Lb.exports=jk});var Db=f((mO,Cb)=>{"use strict";var Qk=Mb();Cb.exports=Qk});var Ob=f((fO,Vb)=>{"use strict";var Gk=li(),Wk=Vi(),Yk=Ct(),zk=RangeError;Vb.exports=function(e){var t=Wk(Yk(this)),r="",a=Gk(e);if(a<0||a===1/0)throw new zk("Wrong number of repetitions");for(;a>0;(a>>>=1)&&(t+=t))a&1&&(r+=t);return r}});var qb=f((bO,Fb)=>{"use strict";var Nb=ce(),Kk=Tn(),Bb=Vi(),Jk=Ob(),Xk=Ct(),Zk=Nb(Jk),ew=Nb("".slice),tw=Math.ceil,_b=function(i){return function(e,t,r){var a=Bb(Xk(e)),s=Kk(t),n=a.length,o=r===void 0?" ":Bb(r),u,l;return s<=n||o===""?a:(u=s-n,l=Zk(o,tw(u/o.length)),l.length>u&&(l=ew(l,0,u)),i?a+l:l+a)}};Fb.exports={start:_b(!1),end:_b(!0)}});var Hb=f((gO,Ub)=>{"use strict";var rw=Jt();Ub.exports=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(rw)});var jb=f(()=>{"use strict";var iw=le(),aw=qb().start,sw=Hb();iw({target:"String",proto:!0,forced:sw},{padStart:function(e){return aw(this,e,arguments.length>1?arguments[1]:void 0)}})});var Gb=f((yO,Qb)=>{"use strict";jb();var nw=Dt();Qb.exports=nw("String","padStart")});var Yb=f((TO,Wb)=>{"use strict";var ow=Gb();Wb.exports=ow});var Kb=f((IO,zb)=>{"use strict";var uw=Yb();zb.exports=uw});var Aw={};Jg(Aw,{ChromecastState:()=>Zr,HttpConnectionType:()=>Ma,Observable:()=>dt.Observable,PlaybackState:()=>ve,Player:()=>xa,PredefinedQualityLimits:()=>Sr,SDK_VERSION:()=>Pw,Subject:()=>dt.Subject,Subscription:()=>dt.Subscription,Surface:()=>Ca,VERSION:()=>js,ValueSubject:()=>dt.ValueSubject,VideoFormat:()=>bt,VideoQuality:()=>dt.VideoQuality});module.exports=Xg(Aw);var js="2.0.119-dev.df6b2fd8.0";var ve=(a=>(a.STOPPED="stopped",a.READY="ready",a.PLAYING="playing",a.PAUSED="paused",a))(ve||{}),bt=(P=>(P.MPEG="MPEG",P.DASH="DASH",P.DASH_SEP="DASH_SEP",P.DASH_SEP_VK="DASH_SEP",P.DASH_WEBM="DASH_WEBM",P.DASH_WEBM_AV1="DASH_WEBM_AV1",P.DASH_STREAMS="DASH_STREAMS",P.DASH_WEBM_VK="DASH_WEBM",P.DASH_ONDEMAND="DASH_ONDEMAND",P.DASH_ONDEMAND_VK="DASH_ONDEMAND",P.DASH_LIVE="DASH_LIVE",P.DASH_LIVE_CMAF="DASH_LIVE_CMAF",P.DASH_LIVE_WEBM="DASH_LIVE_WEBM",P.HLS="HLS",P.HLS_ONDEMAND="HLS_ONDEMAND",P.HLS_JS="HLS",P.HLS_LIVE="HLS_LIVE",P.HLS_LIVE_CMAF="HLS_LIVE_CMAF",P.WEB_RTC_LIVE="WEB_RTC_LIVE",P))(bt||{});var Zr=(a=>(a.NOT_AVAILABLE="NOT_AVAILABLE",a.AVAILABLE="AVAILABLE",a.CONNECTING="CONNECTING",a.CONNECTED="CONNECTED",a))(Zr||{}),Ma=(r=>(r.HTTP1="http1",r.HTTP2="http2",r.QUIC="quic",r))(Ma||{});var Ca=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(Ca||{}),Sr=(r=>(r.TRAFFIC_SAVING="traffic_saving",r.HIGH_QUALITY="high_quality",r.UNKNOWN="unknown",r))(Sr||{});var qg=G(st(),1);var q=require("@vkontakte/videoplayer-shared");var kc=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 _a=class{constructor(e){this.connection$=new q.ValueSubject(void 0);this.castState$=new q.ValueSubject("NOT_AVAILABLE");this.errorEvent$=new q.Subject;this.realCastState$=new q.ValueSubject("NOT_AVAILABLE");this.subscription=new q.Subscription;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=(0,q.isNonNullable)(window.chrome?.cast),a=!!window.__onGCastApiAvailable;r?this.initializeCastApi():(window.__onGCastApiAvailable=s=>{delete window.__onGCastApiAvailable,s&&this.initializeCastApi()},a||kc("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:q.ErrorCategory.NETWORK,message:"Script loading failed!"})))}connect(){cast.framework.CastContext.getInstance()?.requestSession()}disconnect(){cast.framework.CastContext.getInstance()?.getCurrentSession()?.endSession(!0)}stopMedia(){return new Promise((e,t)=>{cast.framework.CastContext.getInstance()?.getCurrentSession()?.getMediaSession()?.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){(0,q.isNonNullable)(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();(0,q.isNullable)(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();(0,q.isNullable)(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((0,q.fromEvent)(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(0,q.assertNever)(a.sessionState)}})).add((0,q.merge)((0,q.fromEvent)(r,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe((0,q.tap)(a=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(a)}`})}),(0,q.map)(a=>a.castState)),(0,q.observableFrom)([r.getCastState()])).pipe((0,q.filterChanged)(),(0,q.map)(yy),(0,q.tap)(a=>{this.log({message:`realCastState$: ${a}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(a=>{let s=a==="CONNECTED",n=(0,q.isNonNullable)(this.connection$.getValue());if(s&&!n){let o=r.getCurrentSession();(0,q.assertNonNullable)(o);let u=o.getCastDevice(),l=o.getMediaSession()?.media?.contentId;((0,q.isNullable)(l)||l===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:o,castDevice:u}))}else!s&&n&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(a==="CONNECTED"?(0,q.isNonNullable)(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:q.ErrorCategory.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:a})}}},yy=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(0,q.assertNever)(i)}};var $u=G(st(),1),wg=G(wr(),1),Rg=G(zn(),1);var xm=G(ps(),1);var Oo=require("@vkontakte/videoplayer-shared");var ge=(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:(0,Oo.assertNever)(t)}return i},hs=(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:(0,Oo.assertNever)(e)}};var x=(i,e,t=!1)=>{let r=i.getTransition();(t||!r||r.to===e)&&i.setState(e)};var nt=require("@vkontakte/videoplayer-shared"),U=class{constructor(e){this.transitionStarted$=new nt.Subject;this.transitionEnded$=new nt.Subject;this.transitionUpdated$=new nt.Subject;this.forceChanged$=new nt.Subject;this.stateChangeStarted$=(0,nt.merge)(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=(0,nt.merge)(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||(0,nt.isNonNullable)(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}};var Tm=require("@vkontakte/videoplayer-shared"),Im=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(0,Tm.assertNever)(i)}};var k=require("@vkontakte/videoplayer-shared");var wP=5,RP=5,$P=500,Em=7e3,Ei=class{constructor(e){this.subscription=new k.Subscription;this.loadMediaTimeoutSubscription=new k.Subscription;this.videoState=new U("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:(0,k.assertNever)(e)}break}case"playing":{switch(e){case"playing":break;case"paused":this.videoState.startTransitionTo("playing"),this.params.connection.remotePlayerController.playOrPause();break;case"ready":this.videoState.startTransitionTo("playing"),this.params.connection.remotePlayerController.playOrPause();break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:(0,k.assertNever)(e)}break}case"paused":{switch(e){case"playing":this.videoState.startTransitionTo("paused"),this.params.connection.remotePlayerController.playOrPause();break;case"paused":break;case"ready":this.videoState.startTransitionTo("paused"),this.videoState.setState("paused");break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:(0,k.assertNever)(e)}break}default:(0,k.assertNever)(r)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(Im(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 k.Subscription;this.subscription.add(e),this.subscription.add((0,k.merge)(this.videoState.stateChangeStarted$.pipe((0,k.map)(a=>`stateChangeStarted$ ${JSON.stringify(a)}`)),this.videoState.stateChangeEnded$.pipe((0,k.map)(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 k.Subject;e.add(a.pipe((0,k.debounce)($P)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add((0,k.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe(n=>{this.logRemoteEvent(n);let o=n.value;this.params.output.position$.next(o),(this.params.desiredState.seekState.getState().state==="applying"||Math.abs(o-s)>wP)&&a.next(o),s=o})),e.add((0,k.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t((0,k.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),a=>{this.logRemoteEvent(a),a.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t((0,k.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),a=>{this.logRemoteEvent(a),a.value?this.handleRemotePause():this.handleRemotePlay()}),t((0,k.fromEvent)(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(),u=n===chrome.cast.media.PlayerState.BUFFERING;switch(o!==u&&this.params.output.isBuffering$.next(u),n){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&s.duration-s.currentTime<RP&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),x(this.params.desiredState.playbackState,"stopped");break;case chrome.cast.media.PlayerState.PAUSED:{this.handleRemotePause();break}case chrome.cast.media.PlayerState.PLAYING:this.handleRemotePlay();break;case chrome.cast.media.PlayerState.BUFFERING:break;default:(0,k.assertNever)(n)}}),t((0,k.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),a=>{this.logRemoteEvent(a),this.handleRemoteVolumeChange({volume:a.value})}),t((0,k.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),a=>{this.logRemoteEvent(a),this.handleRemoteVolumeChange({muted:a.value})});let r=(0,k.merge)(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,k.observableFrom)(["init"])).pipe((0,k.debounce)(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"),x(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),x(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"),x(this.params.desiredState.playbackState,"paused"))}handleRemotePlay(){let e=this.videoState.getState();(this.videoState.getTransition()?.to==="playing"||e==="paused")&&(this.videoState.setState("playing"),x(this.params.desiredState.playbackState,"playing"))}handleRemoteReady(){this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.params.desiredState.playbackState.getTransition()?.to==="ready"&&x(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 l=t[e];(0,k.assertNonNullable)(l);let c=(0,k.getHighestQuality)(Object.keys(l));(0,k.assertNonNullable)(c);let d=l[c];(0,k.assertNonNullable)(d),r=d,a="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let l=t[e];(0,k.assertNonNullable)(l),r=l.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 l=t[e];(0,k.assertNonNullable)(l),r=l.url,a="application/dash+xml",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let l=t[e];(0,k.assertNonNullable)(l),r=l.url,a="application/dash+xml",s=chrome.cast.media.StreamType.LIVE;break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let l=t[e];(0,k.assertNonNullable)(l),r=ge(l.url),a="application/x-mpegurl",s=chrome.cast.media.StreamType.LIVE;break}case"DASH_LIVE":case"WEB_RTC_LIVE":{let l="Unsupported format for Chromecast",c=new Error(l);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:k.ErrorCategory.VIDEO_PIPELINE,message:l,thrown:c}),c}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return(0,k.assertNever)(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:u}=this.params.meta;return(0,k.isNonNullable)(o)&&(n.metadata.title=o),(0,k.isNonNullable)(u)&&(n.metadata.subtitle=u),n}createLoadRequest(e){let t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;let r=this.params.desiredState.seekState.getState();return r.state==="applying"||r.state==="requested"?t.currentTime=this.params.output.isLive$.getValue()?0:r.position/1e3:t.currentTime=0,t}loadMedia(e){let t=this.params.connection.session.loadMedia(e),r=new Promise((a,s)=>{this.loadMediaTimeoutSubscription.add((0,k.timeout)(Em).subscribe(()=>s(`timeout(${Em})`)))});(0,xm.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:k.ErrorCategory.VIDEO_PIPELINE,message:s,thrown:a})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var Ko=G(st(),1);var Fo=require("@vkontakte/videoplayer-shared");var Pm=require("@vkontakte/videoplayer-shared"),Am=i=>{try{i.pause(),i.playbackRate=0,(0,Pm.clearVideoElement)(i),i.remove()}catch(e){console.error(e)}};var ms=require("@vkontakte/videoplayer-shared"),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)}},_o=window.WeakMap?new WeakMap:new Bo,No=window.WeakMap?new WeakMap:new Map,LP=(i,e=20)=>{let t=0;return(0,ms.fromEvent)(i,"ratechange").subscribe(r=>{t++,t>=e&&(i.currentTime=i.currentTime,t=0)})},Ie=(i,{audioVideoSyncRate:e})=>{let t=i.querySelector("video"),r=!!t;t?(0,Fo.clearVideoElement)(t):(t=document.createElement("video"),i.appendChild(t)),_o.set(t,r);let a=new ms.Subscription;return a.add(LP(t,e)),No.set(t,a),t.setAttribute("crossorigin","anonymous"),t.setAttribute("playsinline","playsinline"),t.controls=!1,t.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),t},Ee=i=>{No.get(i)?.unsubscribe(),No.delete(i);let t=_o.get(i);_o.delete(i),t?(0,Fo.clearVideoElement)(i):Am(i)};var qo=G(xi(),1),w=require("@vkontakte/videoplayer-shared");var Ot=require("@vkontakte/videoplayer-shared"),fs=(i,e,t,{equal:r=(n,o)=>n===o,changed$:a,onError:s}={})=>{let n=i.getState(),o=e(),u=(0,Ot.isNullable)(a),l=new Ot.Subscription;return a&&l.add(a.subscribe(c=>{let d=i.getState();r(c,d)&&i.setState(c)},s)),r(o,n)||(t(n),u&&i.setState(n)),l.add(i.stateChangeStarted$.subscribe(c=>{t(c.to),u&&i.setState(c.to)},s)),l},ot=(i,e,t)=>fs(e,()=>i.loop,r=>{(0,Ot.isNonNullable)(r)&&(i.loop=r)},{onError:t}),xe=(i,e,t,r)=>fs(e,()=>({muted:i.muted,volume:i.volume}),a=>{(0,Ot.isNonNullable)(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}),Ne=(i,e,t,r)=>fs(e,()=>i.playbackRate,a=>{(0,Ot.isNonNullable)(a)&&(i.playbackRate=a)},{changed$:t,onError:r}),Bt=fs;var BP=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},Uo=class i{constructor(){this.available$=new w.Subject;this.current$=new w.ValueSubject(void 0);this.error$=new w.Subject;this.subscription=new w.Subscription;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:w.ErrorCategory.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,()=>(0,qo.default)(this.internalTracks),s=>{(0,w.isNonNullable)(s)&&this.setInternal(s)},{equal:(s,n)=>(0,w.isNonNullable)(s)&&(0,w.isNonNullable)(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe((0,w.map)(s=>s.filter(({type:n})=>n==="internal"))),onError:a})),this.subscription.add(Bt(t.externalTextTracks,()=>(0,qo.default)(this.externalTracks),s=>{(0,w.isNonNullable)(s)&&this.setExternal(s)},{equal:(s,n)=>(0,w.isNonNullable)(s)&&(0,w.isNonNullable)(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe((0,w.map)(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(){(0,w.assertNonNullable)(this.video);let{textTracks:e}=this.video;this.subscription.add((0,w.fromEvent)(e,"addtrack").subscribe(()=>{let r=this.current$.getValue();r&&this.select(r)})),this.subscription.add((0,w.merge)((0,w.fromEvent)(e,"addtrack"),(0,w.fromEvent)(e,"removetrack"),(0,w.observableFrom)(["init"])).pipe((0,w.map)(()=>this.htmlTextTracksAsArray().map(r=>this.htmlTextTrackToITextTrack(r))),(0,w.filterChanged)((r,a)=>r.length===a.length&&r.every(({id:s},n)=>s===a[n].id))).subscribe(this.available$)),this.subscription.add((0,w.merge)((0,w.fromEvent)(e,"change"),(0,w.observableFrom)(["init"])).pipe((0,w.map)(()=>this.htmlTextTracksAsArray().find(({mode:r})=>r==="showing")),(0,w.map)(r=>r&&this.htmlTextTrackToITextTrack(r).id),(0,w.filterChanged)()).subscribe(this.current$));let t=r=>this.applyCueSettings(r.target?.activeCues??null);this.subscription.add((0,w.fromEvent)(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((0,w.fromEvent)(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;(0,w.isNonNullable)(t.align)&&(a.align=t.align),(0,w.isNonNullable)(t.position)&&(a.position=t.position),(0,w.isNonNullable)(t.size)&&(a.size=t.size),(0,w.isNonNullable)(t.line)&&(a.line=t.line)}}htmlTextTracksAsArray(e=!1){(0,w.assertNonNullable)(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:BP(e),s=this.externalTracks.has(a),n=(s?this.externalTracks.get(a)?.isAuto:this.internalTracks.get(a)?.isAuto)??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){(0,w.assertNonNullable)(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))((0,w.isNullable)(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){(0,w.assertNonNullable)(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){(0,w.assertNonNullable)(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)}},Fe=Uo;var yt=class{constructor(){this.pausedTime=0;this.streamOffset=0;this.pauseTimestamp=0}getTotalPausedTime(){return this.pausedTime+this.getCurrentPausedTime()}getCurrentPausedTime(){return this.pauseTimestamp>0?Date.now()-this.pauseTimestamp:0}getStreamOffset(){return this.streamOffset}getTotalOffset(){return this.getTotalPausedTime()+this.streamOffset}pause(){this.pauseTimestamp===0&&(this.pauseTimestamp=Date.now())}resume(){this.pauseTimestamp>0&&(this.pausedTime+=this.getCurrentPausedTime(),this.pauseTimestamp=0)}resetTo(e,t=!1){this.streamOffset=e,this.pauseTimestamp=0,this.pausedTime=0,t&&this.pause()}};var Cm=i=>{let e=i;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e?.parentNode;return e??void 0},Ho=i=>{let e=Cm(i);return!!(e&&e.fullscreenElement&&e.fullscreenElement===i)},Dm=i=>{let e=Cm(i);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===i)};var C=require("@vkontakte/videoplayer-shared");var NP=3,Vm=(i,e,t=NP)=>{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 u=s-1;u>=0;u--)i.end(u)+t>=r&&(r=i.start(u));for(let u=s+1;u<i.length;u++)i.start(u)-t<=a&&(a=i.end(u))}}return{from:r,to:a}};var Pe=i=>{let e=P=>(0,C.fromEvent)(i,P).pipe((0,C.mapTo)(void 0)),r=(0,C.merge)(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(P=>(0,C.fromEvent)(i,P))).pipe((0,C.map)(P=>P.type==="ended"?i.readyState<2:i.readyState<3),(0,C.filterChanged)()),a=(0,C.merge)((0,C.fromEvent)(i,"progress"),(0,C.fromEvent)(i,"timeupdate")).pipe((0,C.map)(()=>Vm(i.buffered,i.currentTime))),s=C.clientChecker.isSafari?(0,C.combine)({play:e("play").pipe((0,C.once)()),playing:e("playing")}).pipe((0,C.mapTo)(void 0)):e("playing"),n=(0,C.fromEvent)(i,"volumechange").pipe((0,C.map)(()=>({muted:i.muted,volume:i.volume}))),o=(0,C.fromEvent)(i,"ratechange").pipe((0,C.map)(()=>i.playbackRate)),u=(0,C.fromEvent)(i,"error").pipe((0,C.filter)(()=>!!(i.error||i.played.length)),(0,C.map)(()=>{let P=i.error;return{id:P?`MediaError#${P.code}`:"HtmlVideoError",category:C.ErrorCategory.VIDEO_PIPELINE,message:P?P.message:"Error event from HTML video element",thrown:i.error??void 0}})),l=(0,C.fromEvent)(i,"timeupdate").pipe((0,C.map)(()=>i.currentTime)),c=new C.Subject,d=.3,h;l.subscribe(P=>{i.loop&&(0,C.isNonNullable)(h)&&(0,C.isNonNullable)(P)&&h>=i.duration-d&&P<=d&&c.next(h),h=P});let m=e("pause").pipe((0,C.filter)(()=>!i.error&&h!==i.duration)),b=(0,C.fromEvent)(i,"enterpictureinpicture"),g=(0,C.fromEvent)(i,"leavepictureinpicture"),y=new C.ValueSubject(Dm(i));b.subscribe(()=>y.next(!0)),g.subscribe(()=>y.next(!1));let T=new C.ValueSubject(Ho(i));return(0,C.fromEvent)(i,"fullscreenchange").pipe((0,C.map)(()=>Ho(i))).subscribe(T),{playing$:s,pause$:m,canplay$:e("canplay"),ended$:e("ended"),looped$:c,error$:u,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:l,durationChange$:(0,C.fromEvent)(i,"durationchange").pipe((0,C.map)(()=>i.duration)),isBuffering$:r,currentBuffer$:a,volumeState$:n,playbackRateState$:o,inPiP$:y,inFullscreen$:T}};var Tt=require("@vkontakte/videoplayer-shared"),_t=i=>{switch(i){case"mobile":return Tt.VideoQuality.Q_144P;case"lowest":return Tt.VideoQuality.Q_240P;case"low":return Tt.VideoQuality.Q_360P;case"sd":case"medium":return Tt.VideoQuality.Q_480P;case"hd":case"high":return Tt.VideoQuality.Q_720P;case"fullhd":case"full":return Tt.VideoQuality.Q_1080P;case"quadhd":case"quad":return Tt.VideoQuality.Q_1440P;case"ultrahd":case"ultra":return Tt.VideoQuality.Q_2160P}};var Nt=G(_r(),1),Gm=G(st(),1),gs=G(wr(),1),R=require("@vkontakte/videoplayer-shared");var jo=!1,It={},Um=i=>{jo=i},Hm=()=>{It={}},jm=i=>{i(It)},Pi=(i,e)=>{jo&&(It.meta=It.meta??{},It.meta[i]=e)},ye=class{constructor(e){this.name=e}next(e){if(!jo)return;It.series=It.series??{};let t=It.series[this.name]??[];t.push([Date.now(),e]),It.series[this.name]=t}};function bs({limits:i,highQualityLimit:e,trafficSavingLimit:t}){return!i.max&&i.min===e?"high_quality":!i.min&&i.max===t?"traffic_saving":"unknown"}var YP=new ye("best_bitrate"),Wm=(i,e,t)=>(e-t)*Math.pow(2,-10*i)+t;var Qo=i=>(e,t)=>i*(Number(e.bitrate)-Number(t.bitrate)),Ai=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=(0,R.now)()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},Ym='Assertion "ABR Tracks is empty array" failed',Ss=(i,e,t,r)=>{let a=[...e].sort(Qo(1)),s=[...t].sort(Qo(1)),n=s.filter(u=>(0,R.isNonNullable)(u.bitrate)&&(0,R.isNonNullable)(i.bitrate)?i.bitrate/u.bitrate>r:!0),o=(0,Nt.default)(s,Math.round(s.length*a.indexOf(i)/(a.length+1)))??(0,Nt.default)(s,-1);return o&&(0,Gm.default)(n,o)?o:n.length?(0,Nt.default)(n,-1):(0,Nt.default)(s,0)},Qm=i=>"quality"in i,zm=(i,e,t,r)=>{let a=(0,R.isNonNullable)(r?.last?.bitrate)&&(0,R.isNonNullable)(t?.bitrate)&&r.last.bitrate<t.bitrate?i.trackCooldownIncreaseQuality:i.trackCooldownDecreaseQuality,s=t&&r&&r.history[t.id]&&(0,R.now)()-r.history[t.id]<=a&&(!r.last||t.id!==r.last.id);if(t?.id&&r&&!s&&r.recordSelection(t),s&&r?.last){let n=r.last;r?.recordSwitch(n);let o=Qm(n)?"video":"audio",u=Qm(n)?n.quality:n.bitrate;return e({message:`
6
+ "use strict";var jg=Object.create;var $a=Object.defineProperty;var Gg=Object.getOwnPropertyDescriptor;var Qg=Object.getOwnPropertyNames;var Wg=Object.getPrototypeOf,Yg=Object.prototype.hasOwnProperty;var f=(i,e)=>()=>(e||i((e={exports:{}}).exports,e),e.exports),zg=(i,e)=>{for(var t in e)$a(i,t,{get:e[t],enumerable:!0})},Mu=(i,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of Qg(e))!Yg.call(i,a)&&a!==t&&$a(i,a,{get:()=>e[a],enumerable:!(r=Gg(e,a))||r.enumerable});return i};var j=(i,e,t)=>(t=i!=null?jg(Wg(i)):{},Mu(e||!i||!i.__esModule?$a(t,"default",{value:i,enumerable:!0}):t,i)),Kg=i=>Mu($a({},"__esModule",{value:!0}),i);var ne=f((Hs,Cu)=>{"use strict";var Xr=function(i){return i&&i.Math===Math&&i};Cu.exports=Xr(typeof globalThis=="object"&&globalThis)||Xr(typeof window=="object"&&window)||Xr(typeof self=="object"&&self)||Xr(typeof global=="object"&&global)||Xr(typeof Hs=="object"&&Hs)||function(){return this}()||Function("return this")()});var be=f((Aw,Du)=>{"use strict";Du.exports=function(i){try{return!!i()}catch{return!0}}});var Zr=f((ww,Vu)=>{"use strict";var Jg=be();Vu.exports=!Jg(function(){var i=function(){}.bind();return typeof i!="function"||i.hasOwnProperty("prototype")})});var js=f((Rw,Nu)=>{"use strict";var Xg=Zr(),_u=Function.prototype,Bu=_u.apply,Ou=_u.call;Nu.exports=typeof Reflect=="object"&&Reflect.apply||(Xg?Ou.bind(Bu):function(){return Ou.apply(Bu,arguments)})});var ce=f(($w,Uu)=>{"use strict";var Fu=Zr(),qu=Function.prototype,Gs=qu.call,Zg=Fu&&qu.bind.bind(Gs,Gs);Uu.exports=Fu?Zg:function(i){return function(){return Gs.apply(i,arguments)}}});var zt=f((Lw,ju)=>{"use strict";var Hu=ce(),eS=Hu({}.toString),tS=Hu("".slice);ju.exports=function(i){return tS(eS(i),8,-1)}});var Qs=f((Mw,Gu)=>{"use strict";var rS=zt(),iS=ce();Gu.exports=function(i){if(rS(i)==="Function")return iS(i)}});var se=f((Cw,Qu)=>{"use strict";var Ws=typeof document=="object"&&document.all;Qu.exports=typeof Ws>"u"&&Ws!==void 0?function(i){return typeof i=="function"||i===Ws}:function(i){return typeof i=="function"}});var Me=f((Dw,Wu)=>{"use strict";var aS=be();Wu.exports=!aS(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var Ce=f((Vw,Yu)=>{"use strict";var sS=Zr(),Ca=Function.prototype.call;Yu.exports=sS?Ca.bind(Ca):function(){return Ca.apply(Ca,arguments)}});var Ys=f(Ju=>{"use strict";var zu={}.propertyIsEnumerable,Ku=Object.getOwnPropertyDescriptor,nS=Ku&&!zu.call({1:2},1);Ju.f=nS?function(e){var t=Ku(this,e);return!!t&&t.enumerable}:zu});var ei=f((Ow,Xu)=>{"use strict";Xu.exports=function(i,e){return{enumerable:!(i&1),configurable:!(i&2),writable:!(i&4),value:e}}});var el=f((_w,Zu)=>{"use strict";var oS=ce(),uS=be(),lS=zt(),zs=Object,cS=oS("".split);Zu.exports=uS(function(){return!zs("z").propertyIsEnumerable(0)})?function(i){return lS(i)==="String"?cS(i,""):zs(i)}:zs});var gr=f((Nw,tl)=>{"use strict";tl.exports=function(i){return i==null}});var Ct=f((Fw,rl)=>{"use strict";var dS=gr(),pS=TypeError;rl.exports=function(i){if(dS(i))throw new pS("Can't call method on "+i);return i}});var Kt=f((qw,il)=>{"use strict";var hS=el(),mS=Ct();il.exports=function(i){return hS(mS(i))}});var De=f((Uw,al)=>{"use strict";var fS=se();al.exports=function(i){return typeof i=="object"?i!==null:fS(i)}});var Sr=f((Hw,sl)=>{"use strict";sl.exports={}});var gt=f((jw,ol)=>{"use strict";var Ks=Sr(),Js=ne(),bS=se(),nl=function(i){return bS(i)?i:void 0};ol.exports=function(i,e){return arguments.length<2?nl(Ks[i])||nl(Js[i]):Ks[i]&&Ks[i][e]||Js[i]&&Js[i][e]}});var ti=f((Gw,ul)=>{"use strict";var gS=ce();ul.exports=gS({}.isPrototypeOf)});var Jt=f((Qw,dl)=>{"use strict";var SS=ne(),ll=SS.navigator,cl=ll&&ll.userAgent;dl.exports=cl?String(cl):""});var Zs=f((Ww,gl)=>{"use strict";var bl=ne(),Xs=Jt(),pl=bl.process,hl=bl.Deno,ml=pl&&pl.versions||hl&&hl.version,fl=ml&&ml.v8,Ye,Da;fl&&(Ye=fl.split("."),Da=Ye[0]>0&&Ye[0]<4?1:+(Ye[0]+Ye[1]));!Da&&Xs&&(Ye=Xs.match(/Edge\/(\d+)/),(!Ye||Ye[1]>=74)&&(Ye=Xs.match(/Chrome\/(\d+)/),Ye&&(Da=+Ye[1])));gl.exports=Da});var en=f((Yw,vl)=>{"use strict";var Sl=Zs(),vS=be(),yS=ne(),TS=yS.String;vl.exports=!!Object.getOwnPropertySymbols&&!vS(function(){var i=Symbol("symbol detection");return!TS(i)||!(Object(i)instanceof Symbol)||!Symbol.sham&&Sl&&Sl<41})});var tn=f((zw,yl)=>{"use strict";var IS=en();yl.exports=IS&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var rn=f((Kw,Tl)=>{"use strict";var ES=gt(),xS=se(),PS=ti(),kS=tn(),AS=Object;Tl.exports=kS?function(i){return typeof i=="symbol"}:function(i){var e=ES("Symbol");return xS(e)&&PS(e.prototype,AS(i))}});var ri=f((Jw,Il)=>{"use strict";var wS=String;Il.exports=function(i){try{return wS(i)}catch{return"Object"}}});var at=f((Xw,El)=>{"use strict";var RS=se(),$S=ri(),LS=TypeError;El.exports=function(i){if(RS(i))return i;throw new LS($S(i)+" is not a function")}});var ii=f((Zw,xl)=>{"use strict";var MS=at(),CS=gr();xl.exports=function(i,e){var t=i[e];return CS(t)?void 0:MS(t)}});var kl=f((eR,Pl)=>{"use strict";var an=Ce(),sn=se(),nn=De(),DS=TypeError;Pl.exports=function(i,e){var t,r;if(e==="string"&&sn(t=i.toString)&&!nn(r=an(t,i))||sn(t=i.valueOf)&&!nn(r=an(t,i))||e!=="string"&&sn(t=i.toString)&&!nn(r=an(t,i)))return r;throw new DS("Can't convert object to primitive value")}});var ze=f((tR,Al)=>{"use strict";Al.exports=!0});var $l=f((rR,Rl)=>{"use strict";var wl=ne(),VS=Object.defineProperty;Rl.exports=function(i,e){try{VS(wl,i,{value:e,configurable:!0,writable:!0})}catch{wl[i]=e}return e}});var ai=f((iR,Cl)=>{"use strict";var BS=ze(),OS=ne(),_S=$l(),Ll="__core-js_shared__",Ml=Cl.exports=OS[Ll]||_S(Ll,{});(Ml.versions||(Ml.versions=[])).push({version:"3.38.0",mode:BS?"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 on=f((aR,Vl)=>{"use strict";var Dl=ai();Vl.exports=function(i,e){return Dl[i]||(Dl[i]=e||{})}});var vr=f((sR,Bl)=>{"use strict";var NS=Ct(),FS=Object;Bl.exports=function(i){return FS(NS(i))}});var Ke=f((nR,Ol)=>{"use strict";var qS=ce(),US=vr(),HS=qS({}.hasOwnProperty);Ol.exports=Object.hasOwn||function(e,t){return HS(US(e),t)}});var un=f((oR,_l)=>{"use strict";var jS=ce(),GS=0,QS=Math.random(),WS=jS(1 .toString);_l.exports=function(i){return"Symbol("+(i===void 0?"":i)+")_"+WS(++GS+QS,36)}});var ge=f((uR,Fl)=>{"use strict";var YS=ne(),zS=on(),Nl=Ke(),KS=un(),JS=en(),XS=tn(),yr=YS.Symbol,ln=zS("wks"),ZS=XS?yr.for||yr:yr&&yr.withoutSetter||KS;Fl.exports=function(i){return Nl(ln,i)||(ln[i]=JS&&Nl(yr,i)?yr[i]:ZS("Symbol."+i)),ln[i]}});var jl=f((lR,Hl)=>{"use strict";var ev=Ce(),ql=De(),Ul=rn(),tv=ii(),rv=kl(),iv=ge(),av=TypeError,sv=iv("toPrimitive");Hl.exports=function(i,e){if(!ql(i)||Ul(i))return i;var t=tv(i,sv),r;if(t){if(e===void 0&&(e="default"),r=ev(t,i,e),!ql(r)||Ul(r))return r;throw new av("Can't convert object to primitive value")}return e===void 0&&(e="number"),rv(i,e)}});var cn=f((cR,Gl)=>{"use strict";var nv=jl(),ov=rn();Gl.exports=function(i){var e=nv(i,"string");return ov(e)?e:e+""}});var Va=f((dR,Wl)=>{"use strict";var uv=ne(),Ql=De(),dn=uv.document,lv=Ql(dn)&&Ql(dn.createElement);Wl.exports=function(i){return lv?dn.createElement(i):{}}});var pn=f((pR,Yl)=>{"use strict";var cv=Me(),dv=be(),pv=Va();Yl.exports=!cv&&!dv(function(){return Object.defineProperty(pv("div"),"a",{get:function(){return 7}}).a!==7})});var Jl=f(Kl=>{"use strict";var hv=Me(),mv=Ce(),fv=Ys(),bv=ei(),gv=Kt(),Sv=cn(),vv=Ke(),yv=pn(),zl=Object.getOwnPropertyDescriptor;Kl.f=hv?zl:function(e,t){if(e=gv(e),t=Sv(t),yv)try{return zl(e,t)}catch{}if(vv(e,t))return bv(!mv(fv.f,e,t),e[t])}});var hn=f((mR,Xl)=>{"use strict";var Tv=be(),Iv=se(),Ev=/#|\.prototype\./,si=function(i,e){var t=Pv[xv(i)];return t===Av?!0:t===kv?!1:Iv(e)?Tv(e):!!e},xv=si.normalize=function(i){return String(i).replace(Ev,".").toLowerCase()},Pv=si.data={},kv=si.NATIVE="N",Av=si.POLYFILL="P";Xl.exports=si});var Tr=f((fR,ec)=>{"use strict";var Zl=Qs(),wv=at(),Rv=Zr(),$v=Zl(Zl.bind);ec.exports=function(i,e){return wv(i),e===void 0?i:Rv?$v(i,e):function(){return i.apply(e,arguments)}}});var mn=f((bR,tc)=>{"use strict";var Lv=Me(),Mv=be();tc.exports=Lv&&Mv(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var st=f((gR,rc)=>{"use strict";var Cv=De(),Dv=String,Vv=TypeError;rc.exports=function(i){if(Cv(i))return i;throw new Vv(Dv(i)+" is not an object")}});var Xt=f(ac=>{"use strict";var Bv=Me(),Ov=pn(),_v=mn(),Ba=st(),ic=cn(),Nv=TypeError,fn=Object.defineProperty,Fv=Object.getOwnPropertyDescriptor,bn="enumerable",gn="configurable",Sn="writable";ac.f=Bv?_v?function(e,t,r){if(Ba(e),t=ic(t),Ba(r),typeof e=="function"&&t==="prototype"&&"value"in r&&Sn in r&&!r[Sn]){var a=Fv(e,t);a&&a[Sn]&&(e[t]=r.value,r={configurable:gn in r?r[gn]:a[gn],enumerable:bn in r?r[bn]:a[bn],writable:!1})}return fn(e,t,r)}:fn:function(e,t,r){if(Ba(e),t=ic(t),Ba(r),Ov)try{return fn(e,t,r)}catch{}if("get"in r||"set"in r)throw new Nv("Accessors not supported");return"value"in r&&(e[t]=r.value),e}});var Ir=f((vR,sc)=>{"use strict";var qv=Me(),Uv=Xt(),Hv=ei();sc.exports=qv?function(i,e,t){return Uv.f(i,e,Hv(1,t))}:function(i,e,t){return i[e]=t,i}});var ue=f((yR,oc)=>{"use strict";var ni=ne(),jv=js(),Gv=Qs(),Qv=se(),Wv=Jl().f,Yv=hn(),Er=Sr(),zv=Tr(),xr=Ir(),nc=Ke();ai();var Kv=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 jv(i,this,arguments)};return e.prototype=i.prototype,e};oc.exports=function(i,e){var t=i.target,r=i.global,a=i.stat,s=i.proto,n=r?ni:a?ni[t]:ni[t]&&ni[t].prototype,o=r?Er:Er[t]||xr(Er,t,{})[t],u=o.prototype,l,c,d,h,m,b,g,y,T;for(h in e)l=Yv(r?h:t+(a?".":"#")+h,i.forced),c=!l&&n&&nc(n,h),b=o[h],c&&(i.dontCallGetSet?(T=Wv(n,h),g=T&&T.value):g=n[h]),m=c&&g?g:e[h],!(!l&&!s&&typeof b==typeof m)&&(i.bind&&c?y=zv(m,ni):i.wrap&&c?y=Kv(m):s&&Qv(m)?y=Gv(m):y=m,(i.sham||m&&m.sham||b&&b.sham)&&xr(y,"sham",!0),xr(o,h,y),s&&(d=t+"Prototype",nc(Er,d)||xr(Er,d,{}),xr(Er[d],h,m),i.real&&u&&(l||!u[h])&&xr(u,h,m)))}});var lc=f((TR,uc)=>{"use strict";var Jv=Math.ceil,Xv=Math.floor;uc.exports=Math.trunc||function(e){var t=+e;return(t>0?Xv:Jv)(t)}});var oi=f((IR,cc)=>{"use strict";var Zv=lc();cc.exports=function(i){var e=+i;return e!==e||e===0?0:Zv(e)}});var pc=f((ER,dc)=>{"use strict";var ey=oi(),ty=Math.max,ry=Math.min;dc.exports=function(i,e){var t=ey(i);return t<0?ty(t+e,0):ry(t,e)}});var vn=f((xR,hc)=>{"use strict";var iy=oi(),ay=Math.min;hc.exports=function(i){var e=iy(i);return e>0?ay(e,9007199254740991):0}});var Pr=f((PR,mc)=>{"use strict";var sy=vn();mc.exports=function(i){return sy(i.length)}});var yn=f((kR,bc)=>{"use strict";var ny=Kt(),oy=pc(),uy=Pr(),fc=function(i){return function(e,t,r){var a=ny(e),s=uy(a);if(s===0)return!i&&-1;var n=oy(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}};bc.exports={includes:fc(!0),indexOf:fc(!1)}});var ui=f((AR,gc)=>{"use strict";gc.exports=function(){}});var Sc=f(()=>{"use strict";var ly=ue(),cy=yn().includes,dy=be(),py=ui(),hy=dy(function(){return!Array(1).includes()});ly({target:"Array",proto:!0,forced:hy},{includes:function(e){return cy(this,e,arguments.length>1?arguments[1]:void 0)}});py("includes")});var Dt=f(($R,vc)=>{"use strict";var my=gt();vc.exports=my});var Tc=f((LR,yc)=>{"use strict";Sc();var fy=Dt();yc.exports=fy("Array","includes")});var Ec=f((MR,Ic)=>{"use strict";var by=Tc();Ic.exports=by});var nt=f((CR,xc)=>{"use strict";var gy=Ec();xc.exports=gy});var _a=f((jR,Ac)=>{"use strict";var vy=on(),yy=un(),kc=vy("keys");Ac.exports=function(i){return kc[i]||(kc[i]=yy(i))}});var Rc=f((GR,wc)=>{"use strict";var Ty=be();wc.exports=!Ty(function(){function i(){}return i.prototype.constructor=null,Object.getPrototypeOf(new i)!==i.prototype})});var Na=f((QR,Lc)=>{"use strict";var Iy=Ke(),Ey=se(),xy=vr(),Py=_a(),ky=Rc(),$c=Py("IE_PROTO"),Tn=Object,Ay=Tn.prototype;Lc.exports=ky?Tn.getPrototypeOf:function(i){var e=xy(i);if(Iy(e,$c))return e[$c];var t=e.constructor;return Ey(t)&&e instanceof t?t.prototype:e instanceof Tn?Ay:null}});var Fa=f((WR,Mc)=>{"use strict";Mc.exports={}});var Vc=f((YR,Dc)=>{"use strict";var wy=ce(),In=Ke(),Ry=Kt(),$y=yn().indexOf,Ly=Fa(),Cc=wy([].push);Dc.exports=function(i,e){var t=Ry(i),r=0,a=[],s;for(s in t)!In(Ly,s)&&In(t,s)&&Cc(a,s);for(;e.length>r;)In(t,s=e[r++])&&(~$y(a,s)||Cc(a,s));return a}});var En=f((zR,Bc)=>{"use strict";Bc.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var xn=f((KR,Oc)=>{"use strict";var My=Vc(),Cy=En();Oc.exports=Object.keys||function(e){return My(e,Cy)}});var Pn=f((JR,Uc)=>{"use strict";var Nc=Me(),Dy=be(),Fc=ce(),Vy=Na(),By=xn(),Oy=Kt(),_y=Ys().f,qc=Fc(_y),Ny=Fc([].push),Fy=Nc&&Dy(function(){var i=Object.create(null);return i[2]=2,!qc(i,2)}),_c=function(i){return function(e){for(var t=Oy(e),r=By(t),a=Fy&&Vy(t)===null,s=r.length,n=0,o=[],u;s>n;)u=r[n++],(!Nc||(a?u in t:qc(t,u)))&&Ny(o,i?[u,t[u]]:t[u]);return o}};Uc.exports={entries:_c(!0),values:_c(!1)}});var Hc=f(()=>{"use strict";var qy=ue(),Uy=Pn().entries;qy({target:"Object",stat:!0},{entries:function(e){return Uy(e)}})});var Gc=f((e$,jc)=>{"use strict";Hc();var Hy=Sr();jc.exports=Hy.Object.entries});var Wc=f((t$,Qc)=>{"use strict";var jy=Gc();Qc.exports=jy});var kr=f((r$,Yc)=>{"use strict";var Gy=Wc();Yc.exports=Gy});var Zt=f((i$,zc)=>{"use strict";zc.exports={}});var Xc=f((a$,Jc)=>{"use strict";var Qy=ne(),Wy=se(),Kc=Qy.WeakMap;Jc.exports=Wy(Kc)&&/native code/.test(String(Kc))});var Rn=f((s$,td)=>{"use strict";var Yy=Xc(),ed=ne(),zy=De(),Ky=Ir(),kn=Ke(),An=ai(),Jy=_a(),Xy=Fa(),Zc="Object already initialized",wn=ed.TypeError,Zy=ed.WeakMap,qa,li,Ua,eT=function(i){return Ua(i)?li(i):qa(i,{})},tT=function(i){return function(e){var t;if(!zy(e)||(t=li(e)).type!==i)throw new wn("Incompatible receiver, "+i+" required");return t}};Yy||An.state?(Je=An.state||(An.state=new Zy),Je.get=Je.get,Je.has=Je.has,Je.set=Je.set,qa=function(i,e){if(Je.has(i))throw new wn(Zc);return e.facade=i,Je.set(i,e),e},li=function(i){return Je.get(i)||{}},Ua=function(i){return Je.has(i)}):(er=Jy("state"),Xy[er]=!0,qa=function(i,e){if(kn(i,er))throw new wn(Zc);return e.facade=i,Ky(i,er,e),e},li=function(i){return kn(i,er)?i[er]:{}},Ua=function(i){return kn(i,er)});var Je,er;td.exports={set:qa,get:li,has:Ua,enforce:eT,getterFor:tT}});var Mn=f((n$,id)=>{"use strict";var $n=Me(),rT=Ke(),rd=Function.prototype,iT=$n&&Object.getOwnPropertyDescriptor,Ln=rT(rd,"name"),aT=Ln&&function(){}.name==="something",sT=Ln&&(!$n||$n&&iT(rd,"name").configurable);id.exports={EXISTS:Ln,PROPER:aT,CONFIGURABLE:sT}});var sd=f(ad=>{"use strict";var nT=Me(),oT=mn(),uT=Xt(),lT=st(),cT=Kt(),dT=xn();ad.f=nT&&!oT?Object.defineProperties:function(e,t){lT(e);for(var r=cT(t),a=dT(t),s=a.length,n=0,o;s>n;)uT.f(e,o=a[n++],r[o]);return e}});var Cn=f((u$,nd)=>{"use strict";var pT=gt();nd.exports=pT("document","documentElement")});var On=f((l$,hd)=>{"use strict";var hT=st(),mT=sd(),od=En(),fT=Fa(),bT=Cn(),gT=Va(),ST=_a(),ud=">",ld="<",Vn="prototype",Bn="script",dd=ST("IE_PROTO"),Dn=function(){},pd=function(i){return ld+Bn+ud+i+ld+"/"+Bn+ud},cd=function(i){i.write(pd("")),i.close();var e=i.parentWindow.Object;return i=null,e},vT=function(){var i=gT("iframe"),e="java"+Bn+":",t;return i.style.display="none",bT.appendChild(i),i.src=String(e),t=i.contentWindow.document,t.open(),t.write(pd("document.F=Object")),t.close(),t.F},Ha,ja=function(){try{Ha=new ActiveXObject("htmlfile")}catch{}ja=typeof document<"u"?document.domain&&Ha?cd(Ha):vT():cd(Ha);for(var i=od.length;i--;)delete ja[Vn][od[i]];return ja()};fT[dd]=!0;hd.exports=Object.create||function(e,t){var r;return e!==null?(Dn[Vn]=hT(e),r=new Dn,Dn[Vn]=null,r[dd]=e):r=ja(),t===void 0?r:mT.f(r,t)}});var Ar=f((c$,md)=>{"use strict";var yT=Ir();md.exports=function(i,e,t,r){return r&&r.enumerable?i[e]=t:yT(i,e,t),i}});var qn=f((d$,gd)=>{"use strict";var TT=be(),IT=se(),ET=De(),xT=On(),fd=Na(),PT=Ar(),kT=ge(),AT=ze(),Fn=kT("iterator"),bd=!1,St,_n,Nn;[].keys&&(Nn=[].keys(),"next"in Nn?(_n=fd(fd(Nn)),_n!==Object.prototype&&(St=_n)):bd=!0);var wT=!ET(St)||TT(function(){var i={};return St[Fn].call(i)!==i});wT?St={}:AT&&(St=xT(St));IT(St[Fn])||PT(St,Fn,function(){return this});gd.exports={IteratorPrototype:St,BUGGY_SAFARI_ITERATORS:bd}});var Ga=f((p$,vd)=>{"use strict";var RT=ge(),$T=RT("toStringTag"),Sd={};Sd[$T]="z";vd.exports=String(Sd)==="[object z]"});var ci=f((h$,yd)=>{"use strict";var LT=Ga(),MT=se(),Qa=zt(),CT=ge(),DT=CT("toStringTag"),VT=Object,BT=Qa(function(){return arguments}())==="Arguments",OT=function(i,e){try{return i[e]}catch{}};yd.exports=LT?Qa:function(i){var e,t,r;return i===void 0?"Undefined":i===null?"Null":typeof(t=OT(e=VT(i),DT))=="string"?t:BT?Qa(e):(r=Qa(e))==="Object"&&MT(e.callee)?"Arguments":r}});var Id=f((m$,Td)=>{"use strict";var _T=Ga(),NT=ci();Td.exports=_T?{}.toString:function(){return"[object "+NT(this)+"]"}});var di=f((f$,xd)=>{"use strict";var FT=Ga(),qT=Xt().f,UT=Ir(),HT=Ke(),jT=Id(),GT=ge(),Ed=GT("toStringTag");xd.exports=function(i,e,t,r){var a=t?i:i&&i.prototype;a&&(HT(a,Ed)||qT(a,Ed,{configurable:!0,value:e}),r&&!FT&&UT(a,"toString",jT))}});var kd=f((b$,Pd)=>{"use strict";var QT=qn().IteratorPrototype,WT=On(),YT=ei(),zT=di(),KT=Zt(),JT=function(){return this};Pd.exports=function(i,e,t,r){var a=e+" Iterator";return i.prototype=WT(QT,{next:YT(+!r,t)}),zT(i,a,!1,!0),KT[a]=JT,i}});var wd=f((g$,Ad)=>{"use strict";var XT=ce(),ZT=at();Ad.exports=function(i,e,t){try{return XT(ZT(Object.getOwnPropertyDescriptor(i,e)[t]))}catch{}}});var $d=f((S$,Rd)=>{"use strict";var eI=De();Rd.exports=function(i){return eI(i)||i===null}});var Md=f((v$,Ld)=>{"use strict";var tI=$d(),rI=String,iI=TypeError;Ld.exports=function(i){if(tI(i))return i;throw new iI("Can't set "+rI(i)+" as a prototype")}});var Un=f((y$,Cd)=>{"use strict";var aI=wd(),sI=De(),nI=Ct(),oI=Md();Cd.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var i=!1,e={},t;try{t=aI(Object.prototype,"__proto__","set"),t(e,[]),i=e instanceof Array}catch{}return function(a,s){return nI(a),oI(s),sI(a)&&(i?t(a,s):a.__proto__=s),a}}():void 0)});var jd=f((T$,Hd)=>{"use strict";var uI=ue(),lI=Ce(),Wa=ze(),qd=Mn(),cI=se(),dI=kd(),Dd=Na(),Vd=Un(),pI=di(),hI=Ir(),Hn=Ar(),mI=ge(),Bd=Zt(),Ud=qn(),fI=qd.PROPER,bI=qd.CONFIGURABLE,Od=Ud.IteratorPrototype,Ya=Ud.BUGGY_SAFARI_ITERATORS,pi=mI("iterator"),_d="keys",hi="values",Nd="entries",Fd=function(){return this};Hd.exports=function(i,e,t,r,a,s,n){dI(t,e,r);var o=function(T){if(T===a&&h)return h;if(!Ya&&T&&T in c)return c[T];switch(T){case _d:return function(){return new t(this,T)};case hi:return function(){return new t(this,T)};case Nd:return function(){return new t(this,T)}}return function(){return new t(this)}},u=e+" Iterator",l=!1,c=i.prototype,d=c[pi]||c["@@iterator"]||a&&c[a],h=!Ya&&d||o(a),m=e==="Array"&&c.entries||d,b,g,y;if(m&&(b=Dd(m.call(new i)),b!==Object.prototype&&b.next&&(!Wa&&Dd(b)!==Od&&(Vd?Vd(b,Od):cI(b[pi])||Hn(b,pi,Fd)),pI(b,u,!0,!0),Wa&&(Bd[u]=Fd))),fI&&a===hi&&d&&d.name!==hi&&(!Wa&&bI?hI(c,"name",hi):(l=!0,h=function(){return lI(d,this)})),a)if(g={values:o(hi),keys:s?h:o(_d),entries:o(Nd)},n)for(y in g)(Ya||l||!(y in c))&&Hn(c,y,g[y]);else uI({target:e,proto:!0,forced:Ya||l},g);return(!Wa||n)&&c[pi]!==h&&Hn(c,pi,h,{name:a}),Bd[e]=h,g}});var Qd=f((I$,Gd)=>{"use strict";Gd.exports=function(i,e){return{value:i,done:e}}});var Gn=f((E$,Jd)=>{"use strict";var gI=Kt(),jn=ui(),Wd=Zt(),zd=Rn(),SI=Xt().f,vI=jd(),za=Qd(),yI=ze(),TI=Me(),Kd="Array Iterator",II=zd.set,EI=zd.getterFor(Kd);Jd.exports=vI(Array,"Array",function(i,e){II(this,{type:Kd,target:gI(i),index:0,kind:e})},function(){var i=EI(this),e=i.target,t=i.index++;if(!e||t>=e.length)return i.target=void 0,za(void 0,!0);switch(i.kind){case"keys":return za(t,!1);case"values":return za(e[t],!1)}return za([t,e[t]],!1)},"values");var Yd=Wd.Arguments=Wd.Array;jn("keys");jn("values");jn("entries");if(!yI&&TI&&Yd.name!=="values")try{SI(Yd,"name",{value:"values"})}catch{}});var Zd=f((x$,Xd)=>{"use strict";var xI=ge(),PI=Zt(),kI=xI("iterator"),AI=Array.prototype;Xd.exports=function(i){return i!==void 0&&(PI.Array===i||AI[kI]===i)}});var Qn=f((P$,tp)=>{"use strict";var wI=ci(),ep=ii(),RI=gr(),$I=Zt(),LI=ge(),MI=LI("iterator");tp.exports=function(i){if(!RI(i))return ep(i,MI)||ep(i,"@@iterator")||$I[wI(i)]}});var ip=f((k$,rp)=>{"use strict";var CI=Ce(),DI=at(),VI=st(),BI=ri(),OI=Qn(),_I=TypeError;rp.exports=function(i,e){var t=arguments.length<2?OI(i):e;if(DI(t))return VI(CI(t,i));throw new _I(BI(i)+" is not iterable")}});var np=f((A$,sp)=>{"use strict";var NI=Ce(),ap=st(),FI=ii();sp.exports=function(i,e,t){var r,a;ap(i);try{if(r=FI(i,"return"),!r){if(e==="throw")throw t;return t}r=NI(r,i)}catch(s){a=!0,r=s}if(e==="throw")throw t;if(a)throw r;return ap(r),t}});var Ja=f((w$,cp)=>{"use strict";var qI=Tr(),UI=Ce(),HI=st(),jI=ri(),GI=Zd(),QI=Pr(),op=ti(),WI=ip(),YI=Qn(),up=np(),zI=TypeError,Ka=function(i,e){this.stopped=i,this.result=e},lp=Ka.prototype;cp.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),u=qI(e,r),l,c,d,h,m,b,g,y=function(R){return l&&up(l,"normal",R),new Ka(!0,R)},T=function(R){return a?(HI(R),o?u(R[0],R[1],y):u(R[0],R[1])):o?u(R,y):u(R)};if(s)l=i.iterator;else if(n)l=i;else{if(c=YI(i),!c)throw new zI(jI(i)+" is not iterable");if(GI(c)){for(d=0,h=QI(i);h>d;d++)if(m=T(i[d]),m&&op(lp,m))return m;return new Ka(!1)}l=WI(i,c)}for(b=s?i.next:l.next;!(g=UI(b,l)).done;){try{m=T(g.value)}catch(R){up(l,"throw",R)}if(typeof m=="object"&&m&&op(lp,m))return m}return new Ka(!1)}});var pp=f((R$,dp)=>{"use strict";var KI=Me(),JI=Xt(),XI=ei();dp.exports=function(i,e,t){KI?JI.f(i,e,XI(0,t)):i[e]=t}});var hp=f(()=>{"use strict";var ZI=ue(),eE=Ja(),tE=pp();ZI({target:"Object",stat:!0},{fromEntries:function(e){var t={};return eE(e,function(r,a){tE(t,r,a)},{AS_ENTRIES:!0}),t}})});var fp=f((M$,mp)=>{"use strict";Gn();hp();var rE=Sr();mp.exports=rE.Object.fromEntries});var gp=f((C$,bp)=>{"use strict";bp.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 vp=f(()=>{"use strict";Gn();var iE=gp(),aE=ne(),sE=di(),Sp=Zt();for(Xa in iE)sE(aE[Xa],Xa),Sp[Xa]=Sp.Array;var Xa});var Tp=f((B$,yp)=>{"use strict";var nE=fp();vp();yp.exports=nE});var Wn=f((O$,Ip)=>{"use strict";var oE=Tp();Ip.exports=oE});var Ep=f(()=>{"use strict"});var Yn=f((F$,xp)=>{"use strict";var mi=ne(),uE=Jt(),lE=zt(),Za=function(i){return uE.slice(0,i.length)===i};xp.exports=function(){return Za("Bun/")?"BUN":Za("Cloudflare-Workers")?"CLOUDFLARE":Za("Deno/")?"DENO":Za("Node.js/")?"NODE":mi.Bun&&typeof Bun.version=="string"?"BUN":mi.Deno&&typeof Deno.version=="object"?"DENO":lE(mi.process)==="process"?"NODE":mi.window&&mi.document?"BROWSER":"REST"}()});var es=f((q$,Pp)=>{"use strict";var cE=Yn();Pp.exports=cE==="NODE"});var Ap=f((U$,kp)=>{"use strict";var dE=Xt();kp.exports=function(i,e,t){return dE.f(i,e,t)}});var $p=f((H$,Rp)=>{"use strict";var pE=gt(),hE=Ap(),mE=ge(),fE=Me(),wp=mE("species");Rp.exports=function(i){var e=pE(i);fE&&e&&!e[wp]&&hE(e,wp,{configurable:!0,get:function(){return this}})}});var Mp=f((j$,Lp)=>{"use strict";var bE=ti(),gE=TypeError;Lp.exports=function(i,e){if(bE(e,i))return i;throw new gE("Incorrect invocation")}});var Kn=f((G$,Cp)=>{"use strict";var SE=ce(),vE=se(),zn=ai(),yE=SE(Function.toString);vE(zn.inspectSource)||(zn.inspectSource=function(i){return yE(i)});Cp.exports=zn.inspectSource});var Xn=f((Q$,_p)=>{"use strict";var TE=ce(),IE=be(),Dp=se(),EE=ci(),xE=gt(),PE=Kn(),Vp=function(){},Bp=xE("Reflect","construct"),Jn=/^\s*(?:class|function)\b/,kE=TE(Jn.exec),AE=!Jn.test(Vp),fi=function(e){if(!Dp(e))return!1;try{return Bp(Vp,[],e),!0}catch{return!1}},Op=function(e){if(!Dp(e))return!1;switch(EE(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return AE||!!kE(Jn,PE(e))}catch{return!0}};Op.sham=!0;_p.exports=!Bp||IE(function(){var i;return fi(fi.call)||!fi(Object)||!fi(function(){i=!0})||i})?Op:fi});var Fp=f((W$,Np)=>{"use strict";var wE=Xn(),RE=ri(),$E=TypeError;Np.exports=function(i){if(wE(i))return i;throw new $E(RE(i)+" is not a constructor")}});var Zn=f((Y$,Up)=>{"use strict";var qp=st(),LE=Fp(),ME=gr(),CE=ge(),DE=CE("species");Up.exports=function(i,e){var t=qp(i).constructor,r;return t===void 0||ME(r=qp(t)[DE])?e:LE(r)}});var jp=f((z$,Hp)=>{"use strict";var VE=ce();Hp.exports=VE([].slice)});var Qp=f((K$,Gp)=>{"use strict";var BE=TypeError;Gp.exports=function(i,e){if(i<e)throw new BE("Not enough arguments");return i}});var eo=f((J$,Wp)=>{"use strict";var OE=Jt();Wp.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(OE)});var lo=f((X$,rh)=>{"use strict";var Ve=ne(),_E=js(),NE=Tr(),Yp=se(),FE=Ke(),th=be(),zp=Cn(),qE=jp(),Kp=Va(),UE=Qp(),HE=eo(),jE=es(),no=Ve.setImmediate,oo=Ve.clearImmediate,GE=Ve.process,to=Ve.Dispatch,QE=Ve.Function,Jp=Ve.MessageChannel,WE=Ve.String,ro=0,bi={},Xp="onreadystatechange",gi,tr,io,ao;th(function(){gi=Ve.location});var uo=function(i){if(FE(bi,i)){var e=bi[i];delete bi[i],e()}},so=function(i){return function(){uo(i)}},Zp=function(i){uo(i.data)},eh=function(i){Ve.postMessage(WE(i),gi.protocol+"//"+gi.host)};(!no||!oo)&&(no=function(e){UE(arguments.length,1);var t=Yp(e)?e:QE(e),r=qE(arguments,1);return bi[++ro]=function(){_E(t,void 0,r)},tr(ro),ro},oo=function(e){delete bi[e]},jE?tr=function(i){GE.nextTick(so(i))}:to&&to.now?tr=function(i){to.now(so(i))}:Jp&&!HE?(io=new Jp,ao=io.port2,io.port1.onmessage=Zp,tr=NE(ao.postMessage,ao)):Ve.addEventListener&&Yp(Ve.postMessage)&&!Ve.importScripts&&gi&&gi.protocol!=="file:"&&!th(eh)?(tr=eh,Ve.addEventListener("message",Zp,!1)):Xp in Kp("script")?tr=function(i){zp.appendChild(Kp("script"))[Xp]=function(){zp.removeChild(this),uo(i)}}:tr=function(i){setTimeout(so(i),0)});rh.exports={set:no,clear:oo}});var sh=f((Z$,ah)=>{"use strict";var ih=ne(),YE=Me(),zE=Object.getOwnPropertyDescriptor;ah.exports=function(i){if(!YE)return ih[i];var e=zE(ih,i);return e&&e.value}});var co=f((eL,oh)=>{"use strict";var nh=function(){this.head=null,this.tail=null};nh.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}}};oh.exports=nh});var lh=f((tL,uh)=>{"use strict";var KE=Jt();uh.exports=/ipad|iphone|ipod/i.test(KE)&&typeof Pebble<"u"});var dh=f((rL,ch)=>{"use strict";var JE=Jt();ch.exports=/web0s(?!.*chrome)/i.test(JE)});var Sh=f((iL,gh)=>{"use strict";var Rr=ne(),XE=sh(),ph=Tr(),po=lo().set,ZE=co(),ex=eo(),tx=lh(),rx=dh(),ho=es(),hh=Rr.MutationObserver||Rr.WebKitMutationObserver,mh=Rr.document,fh=Rr.process,ts=Rr.Promise,bo=XE("queueMicrotask"),wr,mo,fo,rs,bh;bo||(Si=new ZE,vi=function(){var i,e;for(ho&&(i=fh.domain)&&i.exit();e=Si.get();)try{e()}catch(t){throw Si.head&&wr(),t}i&&i.enter()},!ex&&!ho&&!rx&&hh&&mh?(mo=!0,fo=mh.createTextNode(""),new hh(vi).observe(fo,{characterData:!0}),wr=function(){fo.data=mo=!mo}):!tx&&ts&&ts.resolve?(rs=ts.resolve(void 0),rs.constructor=ts,bh=ph(rs.then,rs),wr=function(){bh(vi)}):ho?wr=function(){fh.nextTick(vi)}:(po=ph(po,Rr),wr=function(){po(vi)}),bo=function(i){Si.head||wr(),Si.add(i)});var Si,vi;gh.exports=bo});var yh=f((aL,vh)=>{"use strict";vh.exports=function(i,e){try{arguments.length===1?console.error(i):console.error(i,e)}catch{}}});var is=f((sL,Th)=>{"use strict";Th.exports=function(i){try{return{error:!1,value:i()}}catch(e){return{error:!0,value:e}}}});var rr=f((nL,Ih)=>{"use strict";var ix=ne();Ih.exports=ix.Promise});var $r=f((oL,kh)=>{"use strict";var ax=ne(),yi=rr(),sx=se(),nx=hn(),ox=Kn(),ux=ge(),Eh=Yn(),lx=ze(),go=Zs(),xh=yi&&yi.prototype,cx=ux("species"),So=!1,Ph=sx(ax.PromiseRejectionEvent),dx=nx("Promise",function(){var i=ox(yi),e=i!==String(yi);if(!e&&go===66||lx&&!(xh.catch&&xh.finally))return!0;if(!go||go<51||!/native code/.test(i)){var t=new yi(function(s){s(1)}),r=function(s){s(function(){},function(){})},a=t.constructor={};if(a[cx]=r,So=t.then(function(){})instanceof r,!So)return!0}return!e&&(Eh==="BROWSER"||Eh==="DENO")&&!Ph});kh.exports={CONSTRUCTOR:dx,REJECTION_EVENT:Ph,SUBCLASSING:So}});var Lr=f((uL,wh)=>{"use strict";var Ah=at(),px=TypeError,hx=function(i){var e,t;this.promise=new i(function(r,a){if(e!==void 0||t!==void 0)throw new px("Bad Promise constructor");e=r,t=a}),this.resolve=Ah(e),this.reject=Ah(t)};wh.exports.f=function(i){return new hx(i)}});var Wh=f(()=>{"use strict";var mx=ue(),fx=ze(),os=es(),Vt=ne(),Vr=Ce(),Rh=Ar(),$h=Un(),bx=di(),gx=$p(),Sx=at(),ns=se(),vx=De(),yx=Mp(),Tx=Zn(),Vh=lo().set,Eo=Sh(),Ix=yh(),Ex=is(),xx=co(),Bh=Rn(),us=rr(),xo=$r(),Oh=Lr(),ls="Promise",_h=xo.CONSTRUCTOR,Px=xo.REJECTION_EVENT,kx=xo.SUBCLASSING,vo=Bh.getterFor(ls),Ax=Bh.set,Mr=us&&us.prototype,ir=us,as=Mr,Nh=Vt.TypeError,yo=Vt.document,Po=Vt.process,To=Oh.f,wx=To,Rx=!!(yo&&yo.createEvent&&Vt.dispatchEvent),Fh="unhandledrejection",$x="rejectionhandled",Lh=0,qh=1,Lx=2,ko=1,Uh=2,ss,Mh,Mx,Ch,Hh=function(i){var e;return vx(i)&&ns(e=i.then)?e:!1},jh=function(i,e){var t=e.value,r=e.state===qh,a=r?i.ok:i.fail,s=i.resolve,n=i.reject,o=i.domain,u,l,c;try{a?(r||(e.rejection===Uh&&Dx(e),e.rejection=ko),a===!0?u=t:(o&&o.enter(),u=a(t),o&&(o.exit(),c=!0)),u===i.promise?n(new Nh("Promise-chain cycle")):(l=Hh(u))?Vr(l,u,s,n):s(u)):n(t)}catch(d){o&&!c&&o.exit(),n(d)}},Gh=function(i,e){i.notified||(i.notified=!0,Eo(function(){for(var t=i.reactions,r;r=t.get();)jh(r,i);i.notified=!1,e&&!i.rejection&&Cx(i)}))},Qh=function(i,e,t){var r,a;Rx?(r=yo.createEvent("Event"),r.promise=e,r.reason=t,r.initEvent(i,!1,!0),Vt.dispatchEvent(r)):r={promise:e,reason:t},!Px&&(a=Vt["on"+i])?a(r):i===Fh&&Ix("Unhandled promise rejection",t)},Cx=function(i){Vr(Vh,Vt,function(){var e=i.facade,t=i.value,r=Dh(i),a;if(r&&(a=Ex(function(){os?Po.emit("unhandledRejection",t,e):Qh(Fh,e,t)}),i.rejection=os||Dh(i)?Uh:ko,a.error))throw a.value})},Dh=function(i){return i.rejection!==ko&&!i.parent},Dx=function(i){Vr(Vh,Vt,function(){var e=i.facade;os?Po.emit("rejectionHandled",e):Qh($x,e,i.value)})},Cr=function(i,e,t){return function(r){i(e,r,t)}},Dr=function(i,e,t){i.done||(i.done=!0,t&&(i=t),i.value=e,i.state=Lx,Gh(i,!0))},Io=function(i,e,t){if(!i.done){i.done=!0,t&&(i=t);try{if(i.facade===e)throw new Nh("Promise can't be resolved itself");var r=Hh(e);r?Eo(function(){var a={done:!1};try{Vr(r,e,Cr(Io,a,i),Cr(Dr,a,i))}catch(s){Dr(a,s,i)}}):(i.value=e,i.state=qh,Gh(i,!1))}catch(a){Dr({done:!1},a,i)}}};if(_h&&(ir=function(e){yx(this,as),Sx(e),Vr(ss,this);var t=vo(this);try{e(Cr(Io,t),Cr(Dr,t))}catch(r){Dr(t,r)}},as=ir.prototype,ss=function(e){Ax(this,{type:ls,done:!1,notified:!1,parent:!1,reactions:new xx,rejection:!1,state:Lh,value:void 0})},ss.prototype=Rh(as,"then",function(e,t){var r=vo(this),a=To(Tx(this,ir));return r.parent=!0,a.ok=ns(e)?e:!0,a.fail=ns(t)&&t,a.domain=os?Po.domain:void 0,r.state===Lh?r.reactions.add(a):Eo(function(){jh(a,r)}),a.promise}),Mh=function(){var i=new ss,e=vo(i);this.promise=i,this.resolve=Cr(Io,e),this.reject=Cr(Dr,e)},Oh.f=To=function(i){return i===ir||i===Mx?new Mh(i):wx(i)},!fx&&ns(us)&&Mr!==Object.prototype)){Ch=Mr.then,kx||Rh(Mr,"then",function(e,t){var r=this;return new ir(function(a,s){Vr(Ch,r,a,s)}).then(e,t)},{unsafe:!0});try{delete Mr.constructor}catch{}$h&&$h(Mr,as)}mx({global:!0,constructor:!0,wrap:!0,forced:_h},{Promise:ir});bx(ir,ls,!1,!0);gx(ls)});var Xh=f((dL,Jh)=>{"use strict";var Vx=ge(),zh=Vx("iterator"),Kh=!1;try{Yh=0,Ao={next:function(){return{done:!!Yh++}},return:function(){Kh=!0}},Ao[zh]=function(){return this},Array.from(Ao,function(){throw 2})}catch{}var Yh,Ao;Jh.exports=function(i,e){try{if(!e&&!Kh)return!1}catch{return!1}var t=!1;try{var r={};r[zh]=function(){return{next:function(){return{done:t=!0}}}},i(r)}catch{}return t}});var wo=f((pL,Zh)=>{"use strict";var Bx=rr(),Ox=Xh(),_x=$r().CONSTRUCTOR;Zh.exports=_x||!Ox(function(i){Bx.all(i).then(void 0,function(){})})});var em=f(()=>{"use strict";var Nx=ue(),Fx=Ce(),qx=at(),Ux=Lr(),Hx=is(),jx=Ja(),Gx=wo();Nx({target:"Promise",stat:!0,forced:Gx},{all:function(e){var t=this,r=Ux.f(t),a=r.resolve,s=r.reject,n=Hx(function(){var o=qx(t.resolve),u=[],l=0,c=1;jx(e,function(d){var h=l++,m=!1;c++,Fx(o,t,d).then(function(b){m||(m=!0,u[h]=b,--c||a(u))},s)}),--c||a(u)});return n.error&&s(n.value),r.promise}})});var rm=f(()=>{"use strict";var Qx=ue(),Wx=ze(),Yx=$r().CONSTRUCTOR,$o=rr(),zx=gt(),Kx=se(),Jx=Ar(),tm=$o&&$o.prototype;Qx({target:"Promise",proto:!0,forced:Yx,real:!0},{catch:function(i){return this.then(void 0,i)}});!Wx&&Kx($o)&&(Ro=zx("Promise").prototype.catch,tm.catch!==Ro&&Jx(tm,"catch",Ro,{unsafe:!0}));var Ro});var im=f(()=>{"use strict";var Xx=ue(),Zx=Ce(),eP=at(),tP=Lr(),rP=is(),iP=Ja(),aP=wo();Xx({target:"Promise",stat:!0,forced:aP},{race:function(e){var t=this,r=tP.f(t),a=r.reject,s=rP(function(){var n=eP(t.resolve);iP(e,function(o){Zx(n,t,o).then(r.resolve,a)})});return s.error&&a(s.value),r.promise}})});var am=f(()=>{"use strict";var sP=ue(),nP=Lr(),oP=$r().CONSTRUCTOR;sP({target:"Promise",stat:!0,forced:oP},{reject:function(e){var t=nP.f(this),r=t.reject;return r(e),t.promise}})});var Lo=f((TL,sm)=>{"use strict";var uP=st(),lP=De(),cP=Lr();sm.exports=function(i,e){if(uP(i),lP(e)&&e.constructor===i)return e;var t=cP.f(i),r=t.resolve;return r(e),t.promise}});var um=f(()=>{"use strict";var dP=ue(),pP=gt(),nm=ze(),hP=rr(),om=$r().CONSTRUCTOR,mP=Lo(),fP=pP("Promise"),bP=nm&&!om;dP({target:"Promise",stat:!0,forced:nm||om},{resolve:function(e){return mP(bP&&this===fP?hP:this,e)}})});var lm=f(()=>{"use strict";Wh();em();rm();im();am();um()});var hm=f(()=>{"use strict";var gP=ue(),SP=ze(),cs=rr(),vP=be(),dm=gt(),pm=se(),yP=Zn(),cm=Lo(),TP=Ar(),Co=cs&&cs.prototype,IP=!!cs&&vP(function(){Co.finally.call({then:function(){}},function(){})});gP({target:"Promise",proto:!0,real:!0,forced:IP},{finally:function(i){var e=yP(this,dm("Promise")),t=pm(i);return this.then(t?function(r){return cm(e,i()).then(function(){return r})}:i,t?function(r){return cm(e,i()).then(function(){throw r})}:i)}});!SP&&pm(cs)&&(Mo=dm("Promise").prototype.finally,Co.finally!==Mo&&TP(Co,"finally",Mo,{unsafe:!0}));var Mo});var fm=f((wL,mm)=>{"use strict";Ep();lm();hm();var EP=Dt();mm.exports=EP("Promise","finally")});var gm=f((RL,bm)=>{"use strict";var xP=fm();bm.exports=xP});var ds=f(($L,Sm)=>{"use strict";var PP=gm();Sm.exports=PP});var Pm=f(()=>{"use strict";var $P=ue(),LP=Pn().values;$P({target:"Object",stat:!0},{values:function(e){return LP(e)}})});var Am=f((oM,km)=>{"use strict";Pm();var MP=Sr();km.exports=MP.Object.values});var Rm=f((uM,wm)=>{"use strict";var CP=Am();wm.exports=CP});var Ii=f((lM,$m)=>{"use strict";var DP=Rm();$m.exports=DP});var Dm=f(()=>{"use strict";var _P=ue(),NP=vr(),FP=Pr(),qP=oi(),UP=ui();_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 Bm=f((CM,Vm)=>{"use strict";Dm();var HP=Dt();Vm.exports=HP("Array","at")});var _m=f((DM,Om)=>{"use strict";var jP=Bm();Om.exports=jP});var Br=f((VM,Nm)=>{"use strict";var GP=_m();Nm.exports=GP});var Ko=f((ZC,nf)=>{"use strict";var rk=zt();nf.exports=Array.isArray||function(e){return rk(e)==="Array"}});var uf=f((e0,of)=>{"use strict";var ik=TypeError,ak=9007199254740991;of.exports=function(i){if(i>ak)throw ik("Maximum allowed index exceeded");return i}});var df=f((t0,cf)=>{"use strict";var sk=Ko(),nk=Pr(),ok=uf(),uk=Tr(),lf=function(i,e,t,r,a,s,n,o){for(var u=a,l=0,c=n?uk(n,o):!1,d,h;l<r;)l in t&&(d=c?c(t[l],l,e):t[l],s>0&&sk(d)?(h=nk(d),u=lf(i,e,d,h,u,s-1)-1):(ok(u+1),i[u]=d),u++),l++;return u};cf.exports=lf});var ff=f((r0,mf)=>{"use strict";var pf=Ko(),lk=Xn(),ck=De(),dk=ge(),pk=dk("species"),hf=Array;mf.exports=function(i){var e;return pf(i)&&(e=i.constructor,lk(e)&&(e===hf||pf(e.prototype))?e=void 0:ck(e)&&(e=e[pk],e===null&&(e=void 0))),e===void 0?hf:e}});var gf=f((i0,bf)=>{"use strict";var hk=ff();bf.exports=function(i,e){return new(hk(i))(e===0?0:e)}});var Sf=f(()=>{"use strict";var mk=ue(),fk=df(),bk=at(),gk=vr(),Sk=Pr(),vk=gf();mk({target:"Array",proto:!0},{flatMap:function(e){var t=gk(this),r=Sk(t),a;return bk(e),a=vk(t,0),a.length=fk(a,t,t,r,0,1,e,arguments.length>1?arguments[1]:void 0),a}})});var vf=f(()=>{"use strict";var yk=ui();yk("flatMap")});var Tf=f((u0,yf)=>{"use strict";Sf();vf();var Tk=Dt();yf.exports=Tk("Array","flatMap")});var Ef=f((l0,If)=>{"use strict";var Ik=Tf();If.exports=Ik});var Jo=f((c0,xf)=>{"use strict";var Ek=Ef();xf.exports=Ek});var Ci=f((v0,Df)=>{"use strict";var Lk=ci(),Mk=String;Df.exports=function(i){if(Lk(i)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return Mk(i)}});var Zo=f((y0,Vf)=>{"use strict";Vf.exports=`
7
+ \v\f\r \xA0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028\u2029\uFEFF`});var _f=f((T0,Of)=>{"use strict";var Ck=ce(),Dk=Ct(),Vk=Ci(),tu=Zo(),Bf=Ck("".replace),Bk=RegExp("^["+tu+"]+"),Ok=RegExp("(^|[^"+tu+"])["+tu+"]+$"),eu=function(i){return function(e){var t=Vk(Dk(e));return i&1&&(t=Bf(t,Bk,"")),i&2&&(t=Bf(t,Ok,"$1")),t}};Of.exports={start:eu(1),end:eu(2),trim:eu(3)}});var Uf=f((I0,qf)=>{"use strict";var _k=Mn().PROPER,Nk=be(),Nf=Zo(),Ff="\u200B\x85\u180E";qf.exports=function(i){return Nk(function(){return!!Nf[i]()||Ff[i]()!==Ff||_k&&Nf[i].name!==i})}});var ru=f((E0,Hf)=>{"use strict";var Fk=_f().start,qk=Uf();Hf.exports=qk("trimStart")?function(){return Fk(this)}:"".trimStart});var Gf=f(()=>{"use strict";var Uk=ue(),jf=ru();Uk({target:"String",proto:!0,name:"trimStart",forced:"".trimLeft!==jf},{trimLeft:jf})});var Wf=f(()=>{"use strict";Gf();var Hk=ue(),Qf=ru();Hk({target:"String",proto:!0,name:"trimStart",forced:"".trimStart!==Qf},{trimStart:Qf})});var zf=f((w0,Yf)=>{"use strict";Wf();var jk=Dt();Yf.exports=jk("String","trimLeft")});var Jf=f((R0,Kf)=>{"use strict";var Gk=zf();Kf.exports=Gk});var Zf=f(($0,Xf)=>{"use strict";var Qk=Jf();Xf.exports=Qk});var hb=f(()=>{"use strict"});var mb=f(()=>{"use strict"});var bb=f((KV,fb)=>{"use strict";var pA=De(),hA=zt(),mA=ge(),fA=mA("match");fb.exports=function(i){var e;return pA(i)&&((e=i[fA])!==void 0?!!e:hA(i)==="RegExp")}});var Sb=f((JV,gb)=>{"use strict";var bA=st();gb.exports=function(){var i=bA(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 Tb=f((XV,yb)=>{"use strict";var gA=Ce(),SA=Ke(),vA=ti(),yA=Sb(),vb=RegExp.prototype;yb.exports=function(i){var e=i.flags;return e===void 0&&!("flags"in vb)&&!SA(i,"flags")&&vA(vb,i)?gA(yA,i):e}});var Eb=f((ZV,Ib)=>{"use strict";var lu=ce(),TA=vr(),IA=Math.floor,ou=lu("".charAt),EA=lu("".replace),uu=lu("".slice),xA=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,PA=/\$([$&'`]|\d{1,2})/g;Ib.exports=function(i,e,t,r,a,s){var n=t+i.length,o=r.length,u=PA;return a!==void 0&&(a=TA(a),u=xA),EA(s,u,function(l,c){var d;switch(ou(c,0)){case"$":return"$";case"&":return i;case"`":return uu(e,0,t);case"'":return uu(e,n);case"<":d=a[uu(c,1,-1)];break;default:var h=+c;if(h===0)return l;if(h>o){var m=IA(h/10);return m===0?l:m<=o?r[m-1]===void 0?ou(c,1):r[m-1]+ou(c,1):l}d=r[h-1]}return d===void 0?"":d})}});var kb=f(()=>{"use strict";var kA=ue(),AA=Ce(),du=ce(),xb=Ct(),wA=se(),RA=gr(),$A=bb(),Hr=Ci(),LA=ii(),MA=Tb(),CA=Eb(),DA=ge(),VA=ze(),BA=DA("replace"),OA=TypeError,cu=du("".indexOf),_A=du("".replace),Pb=du("".slice),NA=Math.max;kA({target:"String",proto:!0},{replaceAll:function(e,t){var r=xb(this),a,s,n,o,u,l,c,d,h,m,b=0,g="";if(!RA(e)){if(a=$A(e),a&&(s=Hr(xb(MA(e))),!~cu(s,"g")))throw new OA("`.replaceAll` does not allow non-global regexes");if(n=LA(e,BA),n)return AA(n,e,r,t);if(VA&&a)return _A(Hr(r),e,t)}for(o=Hr(r),u=Hr(e),l=wA(t),l||(t=Hr(t)),c=u.length,d=NA(1,c),h=cu(o,u);h!==-1;)m=l?Hr(t(u,h,o)):CA(u,o,h,[],void 0,t),g+=Pb(o,b,h)+m,b=h+c,h=h+d>o.length?-1:cu(o,u,h+d);return b<o.length&&(g+=Pb(o,b)),g}})});var wb=f((rB,Ab)=>{"use strict";hb();mb();kb();var FA=Dt();Ab.exports=FA("String","replaceAll")});var $b=f((iB,Rb)=>{"use strict";var qA=wb();Rb.exports=qA});var Mb=f((aB,Lb)=>{"use strict";var UA=$b();Lb.exports=UA});var Db=f((sB,Cb)=>{"use strict";var HA=oi(),jA=Ci(),GA=Ct(),QA=RangeError;Cb.exports=function(e){var t=jA(GA(this)),r="",a=HA(e);if(a<0||a===1/0)throw new QA("Wrong number of repetitions");for(;a>0;(a>>>=1)&&(t+=t))a&1&&(r+=t);return r}});var Nb=f((nB,_b)=>{"use strict";var Ob=ce(),WA=vn(),Vb=Ci(),YA=Db(),zA=Ct(),KA=Ob(YA),JA=Ob("".slice),XA=Math.ceil,Bb=function(i){return function(e,t,r){var a=Vb(zA(e)),s=WA(t),n=a.length,o=r===void 0?" ":Vb(r),u,l;return s<=n||o===""?a:(u=s-n,l=KA(o,XA(u/o.length)),l.length>u&&(l=JA(l,0,u)),i?a+l:l+a)}};_b.exports={start:Bb(!1),end:Bb(!0)}});var qb=f((oB,Fb)=>{"use strict";var ZA=Jt();Fb.exports=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(ZA)});var Ub=f(()=>{"use strict";var ew=ue(),tw=Nb().start,rw=qb();ew({target:"String",proto:!0,forced:rw},{padStart:function(e){return tw(this,e,arguments.length>1?arguments[1]:void 0)}})});var jb=f((cB,Hb)=>{"use strict";Ub();var iw=Dt();Hb.exports=iw("String","padStart")});var Qb=f((dB,Gb)=>{"use strict";var aw=jb();Gb.exports=aw});var Yb=f((pB,Wb)=>{"use strict";var sw=Qb();Wb.exports=sw});var Ew={};zg(Ew,{ChromecastState:()=>Jr,HttpConnectionType:()=>La,Observable:()=>pt.Observable,PlaybackState:()=>ye,Player:()=>Ea,SDK_VERSION:()=>Iw,Subject:()=>pt.Subject,Subscription:()=>pt.Subscription,Surface:()=>Ma,VERSION:()=>Us,ValueSubject:()=>pt.ValueSubject,VideoFormat:()=>bt,VideoQuality:()=>pt.VideoQuality});module.exports=Kg(Ew);var Us="2.0.119-dev.e9ac9f0e.0";var ye=(a=>(a.STOPPED="stopped",a.READY="ready",a.PLAYING="playing",a.PAUSED="paused",a))(ye||{}),bt=(A=>(A.MPEG="MPEG",A.DASH="DASH",A.DASH_SEP="DASH_SEP",A.DASH_SEP_VK="DASH_SEP",A.DASH_WEBM="DASH_WEBM",A.DASH_WEBM_AV1="DASH_WEBM_AV1",A.DASH_STREAMS="DASH_STREAMS",A.DASH_WEBM_VK="DASH_WEBM",A.DASH_ONDEMAND="DASH_ONDEMAND",A.DASH_ONDEMAND_VK="DASH_ONDEMAND",A.DASH_LIVE="DASH_LIVE",A.DASH_LIVE_CMAF="DASH_LIVE_CMAF",A.DASH_LIVE_WEBM="DASH_LIVE_WEBM",A.HLS="HLS",A.HLS_ONDEMAND="HLS_ONDEMAND",A.HLS_JS="HLS",A.HLS_LIVE="HLS_LIVE",A.HLS_LIVE_CMAF="HLS_LIVE_CMAF",A.WEB_RTC_LIVE="WEB_RTC_LIVE",A))(bt||{});var Jr=(a=>(a.NOT_AVAILABLE="NOT_AVAILABLE",a.AVAILABLE="AVAILABLE",a.CONNECTING="CONNECTING",a.CONNECTED="CONNECTED",a))(Jr||{}),La=(r=>(r.HTTP1="http1",r.HTTP2="http2",r.QUIC="quic",r))(La||{});var Ma=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(Ma||{});var Ng=j(nt(),1);var F=require("@vkontakte/videoplayer-shared");var Pc=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 Oa=class{constructor(e){this.connection$=new F.ValueSubject(void 0);this.castState$=new F.ValueSubject("NOT_AVAILABLE");this.errorEvent$=new F.Subject;this.realCastState$=new F.ValueSubject("NOT_AVAILABLE");this.subscription=new F.Subscription;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=(0,F.isNonNullable)(window.chrome?.cast),a=!!window.__onGCastApiAvailable;r?this.initializeCastApi():(window.__onGCastApiAvailable=s=>{delete window.__onGCastApiAvailable,s&&this.initializeCastApi()},a||Pc("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:F.ErrorCategory.NETWORK,message:"Script loading failed!"})))}connect(){cast.framework.CastContext.getInstance()?.requestSession()}disconnect(){cast.framework.CastContext.getInstance()?.getCurrentSession()?.endSession(!0)}stopMedia(){return new Promise((e,t)=>{cast.framework.CastContext.getInstance()?.getCurrentSession()?.getMediaSession()?.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){(0,F.isNonNullable)(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();(0,F.isNullable)(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();(0,F.isNullable)(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((0,F.fromEvent)(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(0,F.assertNever)(a.sessionState)}})).add((0,F.merge)((0,F.fromEvent)(r,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe((0,F.tap)(a=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(a)}`})}),(0,F.map)(a=>a.castState)),(0,F.observableFrom)([r.getCastState()])).pipe((0,F.filterChanged)(),(0,F.map)(Sy),(0,F.tap)(a=>{this.log({message:`realCastState$: ${a}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(a=>{let s=a==="CONNECTED",n=(0,F.isNonNullable)(this.connection$.getValue());if(s&&!n){let o=r.getCurrentSession();(0,F.assertNonNullable)(o);let u=o.getCastDevice(),l=o.getMediaSession()?.media?.contentId;((0,F.isNullable)(l)||l===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:o,castDevice:u}))}else!s&&n&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(a==="CONNECTED"?(0,F.isNonNullable)(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:F.ErrorCategory.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:a})}}},Sy=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(0,F.assertNever)(i)}};var wu=j(nt(),1),kg=j(kr(),1),Ag=j(Wn(),1);var Im=j(ds(),1);var Do=require("@vkontakte/videoplayer-shared");var Se=(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:(0,Do.assertNever)(t)}return i},ps=(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:(0,Do.assertNever)(e)}};var k=(i,e,t=!1)=>{let r=i.getTransition();(t||!r||r.to===e)&&i.setState(e)};var ot=require("@vkontakte/videoplayer-shared"),q=class{constructor(e){this.transitionStarted$=new ot.Subject;this.transitionEnded$=new ot.Subject;this.transitionUpdated$=new ot.Subject;this.forceChanged$=new ot.Subject;this.stateChangeStarted$=(0,ot.merge)(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=(0,ot.merge)(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||(0,ot.isNonNullable)(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}};var vm=require("@vkontakte/videoplayer-shared"),ym=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(0,vm.assertNever)(i)}};var $=require("@vkontakte/videoplayer-shared");var kP=5,AP=5,wP=500,Tm=7e3,Ti=class{constructor(e){this.subscription=new $.Subscription;this.loadMediaTimeoutSubscription=new $.Subscription;this.videoState=new q("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:(0,$.assertNever)(e)}break}case"playing":{switch(e){case"playing":break;case"paused":this.videoState.startTransitionTo("playing"),this.params.connection.remotePlayerController.playOrPause();break;case"ready":this.videoState.startTransitionTo("playing"),this.params.connection.remotePlayerController.playOrPause();break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:(0,$.assertNever)(e)}break}case"paused":{switch(e){case"playing":this.videoState.startTransitionTo("paused"),this.params.connection.remotePlayerController.playOrPause();break;case"paused":break;case"ready":this.videoState.startTransitionTo("paused"),this.videoState.setState("paused");break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:(0,$.assertNever)(e)}break}default:(0,$.assertNever)(r)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(ym(e.format)),this.params.output.isAudioAvailable$.next(!0),this.handleRemoteVolumeChange({volume:this.params.connection.remotePlayer.volumeLevel,muted:this.params.connection.remotePlayer.isMuted});let t=this.params.connection.session.getMediaSession();t&&this.restoreSession(t),this.subscribe()}destroy(){this.log({message:"[destroy]"}),this.subscription.unsubscribe()}subscribe(){this.subscription.add(this.loadMediaTimeoutSubscription);let e=new $.Subscription;this.subscription.add(e),this.subscription.add((0,$.merge)(this.videoState.stateChangeStarted$.pipe((0,$.map)(a=>`stateChangeStarted$ ${JSON.stringify(a)}`)),this.videoState.stateChangeEnded$.pipe((0,$.map)(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 $.Subject;e.add(a.pipe((0,$.debounce)(wP)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add((0,$.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe(n=>{this.logRemoteEvent(n);let o=n.value;this.params.output.position$.next(o),(this.params.desiredState.seekState.getState().state==="applying"||Math.abs(o-s)>kP)&&a.next(o),s=o})),e.add((0,$.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t((0,$.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),a=>{this.logRemoteEvent(a),a.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t((0,$.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),a=>{this.logRemoteEvent(a),a.value?this.handleRemotePause():this.handleRemotePlay()}),t((0,$.fromEvent)(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(),u=n===chrome.cast.media.PlayerState.BUFFERING;switch(o!==u&&this.params.output.isBuffering$.next(u),n){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&s.duration-s.currentTime<AP&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),k(this.params.desiredState.playbackState,"stopped");break;case chrome.cast.media.PlayerState.PAUSED:{this.handleRemotePause();break}case chrome.cast.media.PlayerState.PLAYING:this.handleRemotePlay();break;case chrome.cast.media.PlayerState.BUFFERING:break;default:(0,$.assertNever)(n)}}),t((0,$.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),a=>{this.logRemoteEvent(a),this.handleRemoteVolumeChange({volume:a.value})}),t((0,$.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),a=>{this.logRemoteEvent(a),this.handleRemoteVolumeChange({muted:a.value})});let r=(0,$.merge)(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,$.observableFrom)(["init"])).pipe((0,$.debounce)(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"),k(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),k(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"),k(this.params.desiredState.playbackState,"paused"))}handleRemotePlay(){let e=this.videoState.getState();(this.videoState.getTransition()?.to==="playing"||e==="paused")&&(this.videoState.setState("playing"),k(this.params.desiredState.playbackState,"playing"))}handleRemoteReady(){this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.params.desiredState.playbackState.getTransition()?.to==="ready"&&k(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 l=t[e];(0,$.assertNonNullable)(l);let c=(0,$.getHighestQuality)(Object.keys(l));(0,$.assertNonNullable)(c);let d=l[c];(0,$.assertNonNullable)(d),r=d,a="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let l=t[e];(0,$.assertNonNullable)(l),r=l.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 l=t[e];(0,$.assertNonNullable)(l),r=l.url,a="application/dash+xml",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let l=t[e];(0,$.assertNonNullable)(l),r=l.url,a="application/dash+xml",s=chrome.cast.media.StreamType.LIVE;break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let l=t[e];(0,$.assertNonNullable)(l),r=Se(l.url),a="application/x-mpegurl",s=chrome.cast.media.StreamType.LIVE;break}case"DASH_LIVE":case"WEB_RTC_LIVE":{let l="Unsupported format for Chromecast",c=new Error(l);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:$.ErrorCategory.VIDEO_PIPELINE,message:l,thrown:c}),c}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return(0,$.assertNever)(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:u}=this.params.meta;return(0,$.isNonNullable)(o)&&(n.metadata.title=o),(0,$.isNonNullable)(u)&&(n.metadata.subtitle=u),n}createLoadRequest(e){let t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;let r=this.params.desiredState.seekState.getState();return r.state==="applying"||r.state==="requested"?t.currentTime=this.params.output.isLive$.getValue()?0:r.position/1e3:t.currentTime=0,t}loadMedia(e){let t=this.params.connection.session.loadMedia(e),r=new Promise((a,s)=>{this.loadMediaTimeoutSubscription.add((0,$.timeout)(Tm).subscribe(()=>s(`timeout(${Tm})`)))});(0,Im.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:$.ErrorCategory.VIDEO_PIPELINE,message:s,thrown:a})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var Yo=j(nt(),1);var _o=require("@vkontakte/videoplayer-shared");var Em=require("@vkontakte/videoplayer-shared"),xm=i=>{try{i.pause(),i.playbackRate=0,(0,Em.clearVideoElement)(i),i.remove()}catch(e){console.error(e)}};var hs=require("@vkontakte/videoplayer-shared"),Vo=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)}},Bo=window.WeakMap?new WeakMap:new Vo,Oo=window.WeakMap?new WeakMap:new Map,RP=(i,e=20)=>{let t=0;return(0,hs.fromEvent)(i,"ratechange").subscribe(r=>{t++,t>=e&&(i.currentTime=i.currentTime,t=0)})},Ee=(i,{audioVideoSyncRate:e})=>{let t=i.querySelector("video"),r=!!t;t?(0,_o.clearVideoElement)(t):(t=document.createElement("video"),i.appendChild(t)),Bo.set(t,r);let a=new hs.Subscription;return a.add(RP(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},xe=i=>{Oo.get(i)?.unsubscribe(),Oo.delete(i);let t=Bo.get(i);Bo.delete(i),t?(0,_o.clearVideoElement)(i):xm(i)};var No=j(Ii(),1),L=require("@vkontakte/videoplayer-shared");var Bt=require("@vkontakte/videoplayer-shared"),ms=(i,e,t,{equal:r=(n,o)=>n===o,changed$:a,onError:s}={})=>{let n=i.getState(),o=e(),u=(0,Bt.isNullable)(a),l=new Bt.Subscription;return a&&l.add(a.subscribe(c=>{let d=i.getState();r(c,d)&&i.setState(c)},s)),r(o,n)||(t(n),u&&i.setState(n)),l.add(i.stateChangeStarted$.subscribe(c=>{t(c.to),u&&i.setState(c.to)},s)),l},ut=(i,e,t)=>ms(e,()=>i.loop,r=>{(0,Bt.isNonNullable)(r)&&(i.loop=r)},{onError:t}),Pe=(i,e,t,r)=>ms(e,()=>({muted:i.muted,volume:i.volume}),a=>{(0,Bt.isNonNullable)(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}),Fe=(i,e,t,r)=>ms(e,()=>i.playbackRate,a=>{(0,Bt.isNonNullable)(a)&&(i.playbackRate=a)},{changed$:t,onError:r}),Ot=ms;var VP=i=>["__",i.language,i.label].join("|"),BP=(i,e)=>{if(i.id===e)return!0;let[t,r,a]=e.split("|");return i.language===r&&i.label===a},Fo=class i{constructor(){this.available$=new L.Subject;this.current$=new L.ValueSubject(void 0);this.error$=new L.Subject;this.subscription=new L.Subscription;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:L.ErrorCategory.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(Ot(t.internalTextTracks,()=>(0,No.default)(this.internalTracks),s=>{(0,L.isNonNullable)(s)&&this.setInternal(s)},{equal:(s,n)=>(0,L.isNonNullable)(s)&&(0,L.isNonNullable)(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe((0,L.map)(s=>s.filter(({type:n})=>n==="internal"))),onError:a})),this.subscription.add(Ot(t.externalTextTracks,()=>(0,No.default)(this.externalTracks),s=>{(0,L.isNonNullable)(s)&&this.setExternal(s)},{equal:(s,n)=>(0,L.isNonNullable)(s)&&(0,L.isNonNullable)(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe((0,L.map)(s=>s.filter(({type:n})=>n==="external"))),onError:a})),this.subscription.add(Ot(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(Ot(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.activeCues)}))}subscribe(){(0,L.assertNonNullable)(this.video);let{textTracks:e}=this.video;this.subscription.add((0,L.fromEvent)(e,"addtrack").subscribe(()=>{let r=this.current$.getValue();r&&this.select(r)})),this.subscription.add((0,L.merge)((0,L.fromEvent)(e,"addtrack"),(0,L.fromEvent)(e,"removetrack"),(0,L.observableFrom)(["init"])).pipe((0,L.map)(()=>this.htmlTextTracksAsArray().map(r=>this.htmlTextTrackToITextTrack(r))),(0,L.filterChanged)((r,a)=>r.length===a.length&&r.every(({id:s},n)=>s===a[n].id))).subscribe(this.available$)),this.subscription.add((0,L.merge)((0,L.fromEvent)(e,"change"),(0,L.observableFrom)(["init"])).pipe((0,L.map)(()=>this.htmlTextTracksAsArray().find(({mode:r})=>r==="showing")),(0,L.map)(r=>r&&this.htmlTextTrackToITextTrack(r).id),(0,L.filterChanged)()).subscribe(this.current$));let t=r=>this.applyCueSettings(r.target?.activeCues??null);this.subscription.add((0,L.fromEvent)(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((0,L.fromEvent)(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;(0,L.isNonNullable)(t.align)&&(a.align=t.align),(0,L.isNonNullable)(t.position)&&(a.position=t.position),(0,L.isNonNullable)(t.size)&&(a.size=t.size),(0,L.isNonNullable)(t.line)&&(a.line=t.line)}}htmlTextTracksAsArray(e=!1){(0,L.assertNonNullable)(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:VP(e),s=this.externalTracks.has(a),n=(s?this.externalTracks.get(a)?.isAuto:this.internalTracks.get(a)?.isAuto)??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){(0,L.assertNonNullable)(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))((0,L.isNullable)(e)||!BP(t,e))&&(t.mode="disabled")}destroy(){if(this.subscription.unsubscribe(),this.video)for(let e of Array.from(this.video.getElementsByTagName("track"))){let t=e.getAttribute("id");t&&this.externalTracks.has(t)&&this.video.removeChild(e)}this.externalTracks.clear()}attach(e){(0,L.assertNonNullable)(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){(0,L.assertNonNullable)(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)}},qe=Fo;var yt=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 Lm=i=>{let e=i;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e?.parentNode;return e??void 0},qo=i=>{let e=Lm(i);return!!(e&&e.fullscreenElement&&e.fullscreenElement===i)},Mm=i=>{let e=Lm(i);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===i)};var C=require("@vkontakte/videoplayer-shared");var OP=3,Cm=(i,e,t=OP)=>{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 u=s-1;u>=0;u--)i.end(u)+t>=r&&(r=i.start(u));for(let u=s+1;u<i.length;u++)i.start(u)-t<=a&&(a=i.end(u))}}return{from:r,to:a}};var ke=i=>{let e=A=>(0,C.fromEvent)(i,A).pipe((0,C.mapTo)(void 0)),r=(0,C.merge)(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(A=>(0,C.fromEvent)(i,A))).pipe((0,C.map)(A=>A.type==="ended"?i.readyState<2:i.readyState<3),(0,C.filterChanged)()),a=(0,C.merge)((0,C.fromEvent)(i,"progress"),(0,C.fromEvent)(i,"timeupdate")).pipe((0,C.map)(()=>Cm(i.buffered,i.currentTime))),s=C.clientChecker.isSafari?(0,C.combine)({play:e("play").pipe((0,C.once)()),playing:e("playing")}).pipe((0,C.mapTo)(void 0)):e("playing"),n=(0,C.fromEvent)(i,"volumechange").pipe((0,C.map)(()=>({muted:i.muted,volume:i.volume}))),o=(0,C.fromEvent)(i,"ratechange").pipe((0,C.map)(()=>i.playbackRate)),u=(0,C.fromEvent)(i,"error").pipe((0,C.filter)(()=>!!(i.error||i.played.length)),(0,C.map)(()=>{let A=i.error;return{id:A?`MediaError#${A.code}`:"HtmlVideoError",category:C.ErrorCategory.VIDEO_PIPELINE,message:A?A.message:"Error event from HTML video element",thrown:i.error??void 0}})),l=(0,C.fromEvent)(i,"timeupdate").pipe((0,C.map)(()=>i.currentTime)),c=new C.Subject,d=.3,h;l.subscribe(A=>{i.loop&&(0,C.isNonNullable)(h)&&(0,C.isNonNullable)(A)&&h>=i.duration-d&&A<=d&&c.next(h),h=A});let m=e("pause").pipe((0,C.filter)(()=>!i.error&&h!==i.duration)),b=(0,C.fromEvent)(i,"enterpictureinpicture"),g=(0,C.fromEvent)(i,"leavepictureinpicture"),y=new C.ValueSubject(Mm(i));b.subscribe(()=>y.next(!0)),g.subscribe(()=>y.next(!1));let T=new C.ValueSubject(qo(i));return(0,C.fromEvent)(i,"fullscreenchange").pipe((0,C.map)(()=>qo(i))).subscribe(T),{playing$:s,pause$:m,canplay$:e("canplay"),ended$:e("ended"),looped$:c,error$:u,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:l,durationChange$:(0,C.fromEvent)(i,"durationchange").pipe((0,C.map)(()=>i.duration)),isBuffering$:r,currentBuffer$:a,volumeState$:n,playbackRateState$:o,inPiP$:y,inFullscreen$:T}};var Tt=require("@vkontakte/videoplayer-shared"),_t=i=>{switch(i){case"mobile":return Tt.VideoQuality.Q_144P;case"lowest":return Tt.VideoQuality.Q_240P;case"low":return Tt.VideoQuality.Q_360P;case"sd":case"medium":return Tt.VideoQuality.Q_480P;case"hd":case"high":return Tt.VideoQuality.Q_720P;case"fullhd":case"full":return Tt.VideoQuality.Q_1080P;case"quadhd":case"quad":return Tt.VideoQuality.Q_1440P;case"ultrahd":case"ultra":return Tt.VideoQuality.Q_2160P}};var Nt=j(Br(),1),jm=j(nt(),1),fs=j(kr(),1),M=require("@vkontakte/videoplayer-shared");var Uo=!1,It={},Fm=i=>{Uo=i},qm=()=>{It={}},Um=i=>{i(It)},Ei=(i,e)=>{Uo&&(It.meta=It.meta??{},It.meta[i]=e)},Te=class{constructor(e){this.name=e}next(e){if(!Uo)return;It.series=It.series??{};let t=It.series[this.name]??[];t.push([Date.now(),e]),It.series[this.name]=t}};var QP=new Te("best_bitrate"),Gm=(i,e,t)=>(e-t)*Math.pow(2,-10*i)+t;var Ho=i=>(e,t)=>i*(Number(e.bitrate)-Number(t.bitrate)),xi=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=(0,M.now)()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},Qm='Assertion "ABR Tracks is empty array" failed',bs=(i,e,t,r)=>{let a=[...e].sort(Ho(1)),s=[...t].sort(Ho(1)),n=s.filter(u=>(0,M.isNonNullable)(u.bitrate)&&(0,M.isNonNullable)(i.bitrate)?i.bitrate/u.bitrate>r:!0),o=(0,Nt.default)(s,Math.round(s.length*a.indexOf(i)/(a.length+1)))??(0,Nt.default)(s,-1);return o&&(0,jm.default)(n,o)?o:n.length?(0,Nt.default)(n,-1):(0,Nt.default)(s,0)},Hm=i=>"quality"in i,Wm=(i,e,t,r)=>{let a=(0,M.isNonNullable)(r?.last?.bitrate)&&(0,M.isNonNullable)(t?.bitrate)&&r.last.bitrate<t.bitrate?i.trackCooldownIncreaseQuality:i.trackCooldownDecreaseQuality,s=t&&r&&r.history[t.id]&&(0,M.now)()-r.history[t.id]<=a&&(!r.last||t.id!==r.last.id);if(t?.id&&r&&!s&&r.recordSelection(t),s&&r?.last){let n=r.last;r?.recordSwitch(n);let o=Hm(n)?"video":"audio",u=Hm(n)?n.quality:n.bitrate;return e({message:`
8
8
  [last ${o} selected] ${u}
9
- `}),n}return r?.recordSwitch(t),t},zP=(i,e)=>Math.log(e)/Math.log(i),KP=({tuning:i,container:e,limits:t})=>{let r=i.containerSizeFactor;if(i.usePixelRatio&&window.devicePixelRatio){let n=window.devicePixelRatio;if(i.pixelRatioMultiplier)r*=i.pixelRatioMultiplier*(n-1)+1;else{let o=i.pixelRatioLogBase,[u=0,l=0,c=0]=i.pixelRatioLogCoefficients,d=zP(o,u*n+l)+c;Number.isFinite(d)&&(r*=d)}}let{highQualityLimit:a,trafficSavingLimit:s}=i;return t&&bs({limits:t,highQualityLimit:a,trafficSavingLimit:s})==="high_quality"&&(r*=2),i.limitByContainer&&e&&e.width>0&&e.height>0?{width:e.width*r,height:e.height*r}:void 0},Ft=(i,{container:e,estimatedThroughput:t,tuning:r,limits:a,reserve:s=0,forwardBufferHealth:n,playbackRate:o,current:u,history:l,visible:c,droppedVideoMaxQualityLimit:d,stallsVideoMaxQualityLimit:h,stallsPredictedThroughput:m,abrLogger:b})=>{(0,R.assertNotEmptyArray)(i,Ym);let g=KP({container:e,tuning:r,limits:a}),y=r.considerPlaybackRate&&(0,R.isNonNullable)(o)?o:1,T=i.filter(A=>!(0,R.isInvariantQuality)(A.quality)).sort((A,D)=>(0,R.isHigher)(A.quality,D.quality)?-1:1),$=(0,Nt.default)(T,-1)?.quality,P=(0,Nt.default)(T,0)?.quality,O=(0,R.isNullable)(a)||(0,R.isNonNullable)(a.min)&&(0,R.isNonNullable)(a.max)&&(0,R.isLower)(a.max,a.min)||(0,R.isNonNullable)(a.min)&&P&&(0,R.isHigher)(a.min,P)||(0,R.isNonNullable)(a.max)&&$&&(0,R.isLower)(a.max,$),E=y*Wm(n??.5,r.bitrateFactorAtEmptyBuffer,r.bitrateFactorAtFullBuffer),V={},z=T.filter(A=>{let D=!0;if(g)if(A.size)D=A.size.width<=g.width&&A.size.height<=g.height;else{let oe=g&&(0,R.videoSizeToQuality)(g);D=oe?(0,R.isLowerOrEqual)(A.quality,oe):!0}if(!D)return V[A.quality]="FitsContainer",!1;let L=m||t;if(!((0,R.isNonNullable)(L)&&isFinite(L)&&(0,R.isNonNullable)(A.bitrate)?L-s>=A.bitrate*E:!0))return V[A.quality]="FitsThroughput",!1;if(r.lazyQualitySwitch&&(0,R.isNonNullable)(r.minBufferToSwitchUp)&&u&&!(0,R.isInvariantQuality)(u.quality)&&(n??0)<r.minBufferToSwitchUp&&(0,R.isHigher)(A.quality,u.quality))return V[A.quality]="Buffer",!1;if(!!d&&(0,R.isHigherOrEqual)(A.quality,d))return V[A.quality]="DroppedFramesLimit",!1;if(!!h&&(0,R.isHigherOrEqual)(A.quality,h))return V[A.quality]="StallsLimit",!1;let Q=O||((0,R.isNullable)(a.max)||(0,R.isLowerOrEqual)(A.quality,a.max))&&((0,R.isNullable)(a.min)||(0,R.isHigherOrEqual)(A.quality,a.min)),N=(0,R.isNonNullable)(c)&&!c?(0,R.isLowerOrEqual)(A.quality,r.backgroundVideoQualityLimit):!0;return!Q||!N?(V[A.quality]="FitsQualityLimits",!1):!0})[0];z&&z.bitrate&&YP.next(z.bitrate);let Z=z??(0,Nt.default)(T,-1)??i[0];return Z.quality!==l?.last?.quality&&b({message:`
9
+ `}),n}return r?.recordSwitch(t),t},WP=(i,e)=>Math.log(e)/Math.log(i),Ft=(i,{container:e,estimatedThroughput:t,tuning:r,limits:a,reserve:s=0,forwardBufferHealth:n,playbackRate:o,current:u,history:l,visible:c,droppedVideoMaxQualityLimit:d,stallsVideoMaxQualityLimit:h,stallsPredictedThroughput:m,abrLogger:b})=>{(0,M.assertNotEmptyArray)(i,Qm);let g=r.containerSizeFactor;if(r.usePixelRatio&&window.devicePixelRatio){let E=window.devicePixelRatio;if(r.pixelRatioMultiplier)g*=r.pixelRatioMultiplier*(E-1)+1;else{let P=r.pixelRatioLogBase,[ee=0,$e=0,Ge=0]=r.pixelRatioLogCoefficients,w=WP(P,ee*E+$e)+Ge;Number.isFinite(w)&&(g*=w)}}let y=r.limitByContainer&&e&&e.width>0&&e.height>0?{width:e.width*g,height:e.height*g}:void 0,T=r.considerPlaybackRate&&(0,M.isNonNullable)(o)?o:1,R=i.filter(E=>!(0,M.isInvariantQuality)(E.quality)).sort((E,P)=>(0,M.isHigher)(E.quality,P.quality)?-1:1),A=(0,Nt.default)(R,-1)?.quality,D=(0,Nt.default)(R,0)?.quality,x=(0,M.isNullable)(a)||(0,M.isNonNullable)(a.min)&&(0,M.isNonNullable)(a.max)&&(0,M.isLower)(a.max,a.min)||(0,M.isNonNullable)(a.min)&&D&&(0,M.isHigher)(a.min,D)||(0,M.isNonNullable)(a.max)&&A&&(0,M.isLower)(a.max,A),N=T*Gm(n??.5,r.bitrateFactorAtEmptyBuffer,r.bitrateFactorAtFullBuffer),z={},K=R.filter(E=>{let P=!0;if(y)if(E.size)P=E.size.width<=y.width&&E.size.height<=y.height;else{let me=y&&(0,M.videoSizeToQuality)(y);P=me?(0,M.isLowerOrEqual)(E.quality,me):!0}if(!P)return z[E.quality]="FitsContainer",!1;let ee=m||t;if(!((0,M.isNonNullable)(ee)&&isFinite(ee)&&(0,M.isNonNullable)(E.bitrate)?ee-s>=E.bitrate*N:!0))return z[E.quality]="FitsThroughput",!1;if(r.lazyQualitySwitch&&(0,M.isNonNullable)(r.minBufferToSwitchUp)&&u&&!(0,M.isInvariantQuality)(u.quality)&&(n??0)<r.minBufferToSwitchUp&&(0,M.isHigher)(E.quality,u.quality))return z[E.quality]="Buffer",!1;if(!!d&&(0,M.isHigherOrEqual)(E.quality,d))return z[E.quality]="DroppedFramesLimit",!1;if(!!h&&(0,M.isHigherOrEqual)(E.quality,h))return z[E.quality]="StallsLimit",!1;let O=x||((0,M.isNullable)(a.max)||(0,M.isLowerOrEqual)(E.quality,a.max))&&((0,M.isNullable)(a.min)||(0,M.isHigherOrEqual)(E.quality,a.min)),le=(0,M.isNonNullable)(c)&&!c?(0,M.isLowerOrEqual)(E.quality,r.backgroundVideoQualityLimit):!0;return!O||!le?(z[E.quality]="FitsQualityLimits",!1):!0})[0];K&&K.bitrate&&QP.next(K.bitrate);let te=K??(0,Nt.default)(R,-1)??i[0];return te.quality!==l?.last?.quality&&b({message:`
10
10
  [VIDEO TRACKS ABR]
11
11
  [available video tracks]
12
- ${i.map(A=>`{ id: ${A.id}, quality: ${A.quality}, bitrate: ${A.bitrate} }`).join(`
12
+ ${i.map(E=>`{ id: ${E.id}, quality: ${E.quality}, bitrate: ${E.bitrate} }`).join(`
13
13
  `)}
14
14
 
15
15
  [tuning]
16
- ${(0,gs.default)(r??{}).map(([A,D])=>`${A}: ${D}`).join(`
16
+ ${(0,fs.default)(r??{}).map(([E,P])=>`${E}: ${P}`).join(`
17
17
  `)}
18
18
 
19
19
  [limit params]
20
- containerSizeLimit: ${g?.width??0} x ${g?.width??0},
20
+ containerSizeLimit: ${y?.width??0} x ${y?.width??0},
21
21
  estimatedThroughput: ${t},
22
22
  stallsPredictedThroughput: ${m},
23
23
  reserve: ${s},
24
24
  playbackRate: ${o},
25
- playbackRateFactor: ${y},
25
+ playbackRateFactor: ${T},
26
26
  forwardBufferHealth: ${n},
27
- bitrateFactor: ${E},
27
+ bitrateFactor: ${N},
28
28
  minBufferToSwitchUp: ${r.minBufferToSwitchUp},
29
29
  droppedVideoMaxQualityLimit: ${d},
30
30
  stallsVideoMaxQualityLimit: ${h},
31
- limitsAreInvalid: ${O},
31
+ limitsAreInvalid: ${x},
32
32
  maxQualityLimit: ${a?.max},
33
33
  minQualityLimit: ${a?.min},
34
34
 
35
35
  [limited video tracks]
36
- ${(0,gs.default)(V).map(([A,D])=>`${A}: ${D}`).join(`
36
+ ${(0,fs.default)(z).map(([E,P])=>`${E}: ${P}`).join(`
37
37
  `)||"All tracks are available"}
38
38
 
39
- [best video track] ${z?.quality}
40
- [selected video track] ${Z?.quality}
41
- `}),zm(r,b,Z,l)},Km=(i,e,t,{estimatedThroughput:r,tuning:a,playbackRate:s,forwardBufferHealth:n,history:o,abrLogger:u,stallsPredictedThroughput:l})=>{(0,R.assertNotEmptyArray)(t,Ym);let c=a.considerPlaybackRate&&(0,R.isNonNullable)(s)?s:1,d=[...t].sort(Qo(-1)),h=i.bitrate;(0,R.assertNonNullable)(h);let m=c*Wm(n??.5,a.bitrateAudioFactorAtEmptyBuffer,a.bitrateAudioFactorAtFullBuffer),b,g=Ss(i,e,t,a.minVideoAudioRatio),y=l||r;return(0,R.isNonNullable)(y)&&isFinite(y)&&(b=d.find(T=>(0,R.isNonNullable)(T.bitrate)&&(0,R.isNonNullable)(g?.bitrate)?y-h>=T.bitrate*m&&T.bitrate>=g.bitrate:!1)),b||(b=g),b?.bitrate!==o?.last?.bitrate&&u({message:`
39
+ [best video track] ${K?.quality}
40
+ [selected video track] ${te?.quality}
41
+ `}),Wm(r,b,te,l)},Ym=(i,e,t,{estimatedThroughput:r,tuning:a,playbackRate:s,forwardBufferHealth:n,history:o,abrLogger:u,stallsPredictedThroughput:l})=>{(0,M.assertNotEmptyArray)(t,Qm);let c=a.considerPlaybackRate&&(0,M.isNonNullable)(s)?s:1,d=[...t].sort(Ho(-1)),h=i.bitrate;(0,M.assertNonNullable)(h);let m=c*Gm(n??.5,a.bitrateAudioFactorAtEmptyBuffer,a.bitrateAudioFactorAtFullBuffer),b,g=bs(i,e,t,a.minVideoAudioRatio),y=l||r;return(0,M.isNonNullable)(y)&&isFinite(y)&&(b=d.find(T=>(0,M.isNonNullable)(T.bitrate)&&(0,M.isNonNullable)(g?.bitrate)?y-h>=T.bitrate*m&&T.bitrate>=g.bitrate:!1)),b||(b=g),b?.bitrate!==o?.last?.bitrate&&u({message:`
42
42
  [AUDIO TRACKS ABR]
43
43
  [available audio tracks]
44
44
  ${t.map(T=>`{ id: ${T.id}, bitrate: ${T.bitrate} }`).join(`
45
45
  `)}
46
46
 
47
47
  [tuning]
48
- ${(0,gs.default)(a??{}).map(([T,$])=>`${T}: ${$}`).join(`
48
+ ${(0,fs.default)(a??{}).map(([T,R])=>`${T}: ${R}`).join(`
49
49
  `)}
50
50
 
51
51
  [limit params]
@@ -59,14 +59,14 @@
59
59
  minBufferToSwitchUp: ${a.minBufferToSwitchUp},
60
60
 
61
61
  [selected audio track] ${b?.id}
62
- `}),b&&zm(a,u,b,o)};var de=i=>new URL(i).hostname;var B=require("@vkontakte/videoplayer-shared");var Xm=G(st(),1),Jm=i=>{if(i instanceof DOMException&&(0,Xm.default)(["Failed to load because no supported source was found.","The element has no supported sources."],i.message))throw i;return!(i instanceof DOMException&&(i.code===20||i.name==="AbortError"))},Ae=async(i,e)=>{let t=i.muted;try{await i.play()}catch(r){if(!Jm(r))return!1;if(e&&e(),t)return console.warn(r),!1;i.muted=!0;try{await i.play()}catch(a){return Jm(a)&&(i.muted=!1,console.warn(a)),!1}}return!0};var Ve=require("@vkontakte/videoplayer-shared");var Zm=G(xi(),1),ut=require("@vkontakte/videoplayer-shared");function pe(){return(0,ut.now)()}function Go(i){return pe()-i}function Wo(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,u=!1)=>{a(n)||(n.startsWith("/")||(n="/"+n),n=t+n);let l=n.indexOf("?")>-1?"&":"?";return u&&(n+=l+"lowLat=1",l="&"),o&&(n+=l+"_rnd="+Math.floor(999999999*Math.random())),n}}}function ef(i,e,t){let r=(...a)=>{t.apply(null,a),i.removeEventListener(e,r)};i.addEventListener(e,r)}function Nr(i,e,t,r){let a=window.XMLHttpRequest,s,n,o,u=!1,l=0,c,d,h=!1,m="arraybuffer",b=7e3,g=2e3,y=()=>{if(u)return;(0,ut.assertNonNullable)(c);let L=Go(c),re;if(L<g){re=g-L,setTimeout(y,re);return}g*=2,g>b&&(g=b),n&&n.abort(),n=new a,V()},T=L=>(s=L,D),$=L=>(d=L,D),P=()=>(m="json",D),O=()=>{if(!u){if(--l>=0){y(),r&&r();return}u=!0,d&&d(),t&&t()}},E=L=>(h=L,D),V=()=>{c=pe(),n=new a,n.open("get",i);let L=0,re,je=0,pt=()=>((0,ut.assertNonNullable)(c),Math.max(c,Math.max(re||0,je||0)));if(s&&n.addEventListener("progress",M=>{let Q=pe();s.updateChunk&&M.loaded>L&&(s.updateChunk(pt(),M.loaded-L),L=M.loaded,re=Q)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>O())),n.addEventListener("load",()=>{if(u)return;(0,ut.assertNonNullable)(n);let M=n.status;if(M>=200&&M<300){if(n.response.byteLength&&s){let Q=n.response.byteLength-L;Q&&s.updateChunk&&s.updateChunk(pt(),Q)}n.responseType==="json"&&!(0,Zm.default)(n.response).length?O():(d&&d(),e(n.response))}else O()}),n.addEventListener("error",()=>{O()}),h){let M=()=>{(0,ut.assertNonNullable)(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(je=pe(),n.removeEventListener("readystatechange",M))};n.addEventListener("readystatechange",M)}return n.responseType=m,n.send(),D},D={withBitrateReporting:T,withParallel:E,withJSONResponse:P,withRetryCount:L=>(l=L,D),withRetryInterval:(L,re)=>((0,ut.isNonNullable)(L)&&(g=L),(0,ut.isNonNullable)(re)&&(b=re),D),withTimeout:L=>(o=L,D),withFinally:$,send:V,abort:()=>{n&&(n.abort(),n=void 0),u=!0,d&&d()}};return D}var ki=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 u=s.bytes*n/o;a+=u,s.start=t,s.bytes-=u}}}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 tf=G(xi(),1);var wi=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=pe(),a=u=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=u,e._errorCB?e._errorCB(u):(this.limitCompleteCount(),this.completeRequests[t]=e)},s=u=>{e._complete=1,e._responseData=u,e._downloadTime=pe()-r,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(u,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},n=()=>{e._finallyCB&&e._finallyCB()},o=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=Nr(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=pe()}_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=pe();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(){(0,tf.default)(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 rf=require("@vkontakte/videoplayer-shared"),vs=1e4,Yo=3;var XP=6e4,ZP=10,eA=1,tA=500,Ri=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.soundProhibitedEvent$=new rf.Subject,this.chunkRateEstimator=new ki(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=Wo(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=Wo(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||(0,Ve.isNonNullable)(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=()=>{ef(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 wi(Yo,vs,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,u=null,l=null,c=!1,d=()=>{let O=s&&(!c||c===this.rep);return O||t("Not running!"),O},h=(O,E,V)=>{u&&u.abort(),u=Nr(this.urlResolver.resolve(O,!1),E,V,()=>this._retryCallback()).withTimeout(vs).withBitrateReporting(this.bitrateSwitcher).withRetryCount(Yo).withFinally(()=>{u=null}).send()},m=(O,E,V)=>{(0,Ve.assertNonNullable)(this.filesFetcher),o?.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(O,!1),E,V,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},b=O=>{let E=r.playbackRate;r.playbackRate!==O&&(t(`Playback rate switch: ${E}=>${O}`),r.playbackRate=O)},g=O=>{this.lowLatency=O,t(`lowLatency changed to ${O}`),y()},y=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)b(1);else{let O=this._getBufferSizeSec();if(this.bufferStates.length<5){b(1);return}let V=pe()-1e4,ee=0;for(let Z=0;Z<this.bufferStates.length;Z++){let A=this.bufferStates[Z];O=Math.min(O,A.buf),A.ts<V&&ee++}this.bufferStates.splice(0,ee),t(`update playback rate; minBuffer=${O} drop=${ee} jitter=${this.sourceJitter}`);let z=O-eA;this.sourceJitter>=0?z-=this.sourceJitter/2:this.sourceJitter-=1,z>3?b(1.15):z>1?b(1.1):z>.3?b(1.05):b(1)}},T=O=>{let E,V=()=>E&&E.start?E.start.length:0,ee=M=>E.start[M]/1e3,z=M=>E.dur[M]/1e3,Z=M=>E.fragIndex+M,A=(M,Q)=>({chunkIdx:Z(M),startTS:ee(M),dur:z(M),discontinuity:Q}),D=()=>{let M=0;if(E&&E.dur){let Q=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,N=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,oe=Q;this.sourceJitter>1&&(oe+=this.sourceJitter-1);let Re=E.dur.length-1;for(;Re>=0&&(oe-=E.dur[Re],!(oe<=0));--Re);M=Math.min(Re,E.dur.length-1-N),M=Math.max(M,0)}return A(M,!0)},L=M=>{let Q=V();if(!(Q<=0)){if((0,Ve.isNonNullable)(M)){for(let N=0;N<Q;N++)if(ee(N)>M)return A(N)}return D()}},re=M=>{let Q=V(),N=M?M.chunkIdx+1:0,oe=N-E.fragIndex;if(!(Q<=0)){if(!M||oe<0||oe-Q>ZP)return t(`Resync: offset=${oe} bChunks=${Q} chunk=`+JSON.stringify(M)),D();if(!(oe>=Q))return A(N-E.fragIndex,!1)}},je=(M,Q,N)=>{l&&l.abort(),l=Nr(this.urlResolver.resolve(M,!0,this.lowLatency),Q,N,()=>this._retryCallback()).withTimeout(vs).withRetryCount(Yo).withFinally(()=>{l=null}).withJSONResponse().send()};return{seek:(M,Q)=>{je(O,N=>{if(!d())return;E=N;let oe=!!E.lowLatency;oe!==this.lowLatency&&g(oe);let Re=0;for(let $t=0;$t<E.dur.length;++$t)Re+=E.dur[$t];Re>0&&((0,Ve.assertNonNullable)(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(Re/E.dur.length)),a({name:"index",zeroTime:E.zeroTime,shiftDuration:E.shiftDuration}),this.sourceJitter=E.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,E.jitter/1e3)):1,M(L(Q))},()=>this._handleNetworkError())},nextChunk:re}},$=()=>{s=!1,o&&o.abort(),u&&u.abort(),l&&l.abort(),(0,Ve.assertNonNullable)(this.filesFetcher),this.filesFetcher.abortAll()};return c={start:O=>{let{videoElement:E,logger:V}=this.params,ee=T(e.jidxUrl),z,Z,A,D,L=0,re,je,pt,M=()=>{re&&(clearTimeout(re),re=void 0);let K=Math.max(tA,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),me=L+K,ue=pe(),Te=Math.min(1e4,me-ue);L=ue;let $e=()=>{l||d()&&ee.seek(()=>{d()&&(L=pe(),Q(),M())})};Te>0?re=window.setTimeout(()=>{this.paused?M():$e()},Te):$e()},Q=()=>{let K;for(;K=ee.nextChunk(D);)D=K,dr(K);let me=ee.nextChunk(A);if(me){if(A&&me.discontinuity){V("Detected discontinuity; restarting playback"),this.paused?M():($(),this._initPlayerWith(e));return}$t(me)}else M()},N=(K,me)=>{if(!d()||!this.sourceBuffer)return;let ue,Te,$e,ht=Ze=>{window.setTimeout(()=>{d()&&N(K,me)},Ze)};if(this.sourceBuffer.updating)V("Source buffer is updating; delaying appendBuffer"),ht(100);else{let Ze=pe(),mt=E.currentTime;!this.paused&&E.buffered.length>1&&je===mt&&Ze-pt>500&&(V("Stall suspected; trying to fix"),this._fixupStall()),je!==mt&&(je=mt,pt=Ze);let et=this._getBufferSizeSec();if(et>30)V(`Buffered ${et} seconds; delaying appendBuffer`),ht(2e3);else try{this.sourceBuffer.appendBuffer(K),this.videoPlayStarted?(this.bufferStates.push({ts:Ze,buf:et}),y(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),me&&me()}catch(pr){if(pr.name==="QuotaExceededError")V("QuotaExceededError; delaying appendBuffer"),$e=this.sourceBuffer.buffered.length,$e!==0&&(ue=this.sourceBuffer.buffered.start(0),Te=mt,Te-ue>4&&this.sourceBuffer.remove(ue,Te-3)),ht(1e3);else throw pr}}},oe=()=>{Z&&z&&(V([`Appending chunk, sz=${Z.byteLength}:`,JSON.stringify(A)]),N(Z,function(){Z=null,Q()}))},Re=K=>e.fragUrlTemplate.replace("%%id%%",K.chunkIdx),$t=K=>{d()&&m(Re(K),(me,ue)=>{if(d()){if(ue/=1e3,Z=me,A=K,n=K.startTS,ue){let Te=Math.min(10,K.dur/ue);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*Te:Te}oe()}},()=>this._handleNetworkError())},dr=K=>{d()&&((0,Ve.assertNonNullable)(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(Re(K),!1)))},Qt=K=>{d()&&(e.cachedHeader=K,N(K,()=>{z=!0,oe()}))};s=!0,ee.seek(K=>{if(d()){if(L=pe(),!K){M();return}D=K,!(0,Ve.isNullable)(O)||K.startTS>O?$t(K):(A=K,Q())}},O),e.cachedHeader?Qt(e.cachedHeader):h(e.headerUrl,Qt,()=>this._handleNetworkError())},stop:$,getTimestampSec:()=>n},c}_switchToQuality(e){let{logger:t,playerCallback:r}=this.params,a;e.bitrate!==this.bitrate&&(this.rep&&(a=this.rep.getTimestampSec(),(0,Ve.isNonNullable)(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,(0,Ve.assertNonNullable)(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(a),r({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return(0,Ve.isNonNullable)(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,r=d=>{if(!this.autoQuality)return;let h,m,b;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&d<this.bitrate&&(m=this._getBufferSizeSec(),b=d/this.bitrate,m>10&&b>.8||m>15&&b>.5||m>20&&b>.3)){e(`Not switching: buffer=${Math.floor(m)}; bitrate=${this.bitrate}; newRate=${Math.floor(d)}`);return}h=this._selectQuality(d),h?this._switchToQuality(h):e(`Could not find quality by bitrate ${d}`)},s={updateChunk:(h,m)=>{let b=pe();if(this.chunkRateEstimator.addInterval(h,b,m)){let y=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:m,duration:b-h,speed:y}),!0}},get:()=>{let h=this.chunkRateEstimator.getBitRate();return h?h*.85:0}},n=-1/0,o,u=!0,l=()=>{let d=s.get();if(d&&o&&this.autoQuality){if(u&&d>o&&Go(n)<3e4)return;r(d)}u=this.autoQuality};return{updateChunk:(d,h)=>{let m=s.updateChunk(d,h);return m&&l(),m},notifySwitch:d=>{let h=pe();d<o&&(n=h),o=d}}}_fetchManifest(e,t,r){this.manifestRequest=Nr(this.urlResolver.resolve(e,!0),t,r,()=>this._retryCallback()).withJSONResponse().withTimeout(vs).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;Ae(e,()=>{this.soundProhibitedEvent$.next()}).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((u,l)=>{u.video&&a.canPlayType(u.codecs).replace(/no/,"")&&window.MediaSource.isTypeSupported(u.codecs)&&(u.index=l,o.push(u))}),o.sort(function(u,l){return u.video&&l.video?l.video.height-u.video.height:l.bitrate-u.bitrate}),o):(r({name:"error",type:"empty_manifest"}),[])};this.manifest=s(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),r({name:"manifest",manifest:this.manifest})}_refetchManifest(e){this.destroyed||(this.manifestRefetchTimer&&clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=window.setTimeout(()=>{this._fetchManifest(e,t=>{this.destroyed||(this._handleManifestUpdate(t),this._refetchManifest(e))},()=>this._refetchManifest(e))},XP))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};var af=G(wr(),1),ie=require("@vkontakte/videoplayer-shared"),zo=class{constructor(){this.onDroopedVideoFramesLimit$=new ie.Subject;this.subscription=new ie.Subscription;this.playing=!1;this.tracks=[];this.forceChecker$=new ie.Subject;this.isForceCheckCounter=0;this.prevTotalVideoFrames=0;this.prevDroppedVideoFrames=0;this.limitCounts={};this.handleChangeVideoQuality=()=>{let e=this.tracks.find(({size:t})=>t?.height===this.video.videoHeight&&t?.width===this.video.videoWidth);e&&!(0,ie.isInvariantQuality)(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&&(0,ie.isHigher)(this.currentQuality,this.droppedFramesChecker.minQualityBanLimit)&&(this.limitCounts[this.currentQuality]=(this.limitCounts[this.currentQuality]??0)+1,this.maxQualityLimit=this.getMaxQualityLimit(this.currentQuality),this.currentTimer&&window.clearTimeout(this.currentTimer),this.currentTimer=window.setTimeout(()=>this.maxQualityLimit=this.getMaxQualityLimit(),this.droppedFramesChecker.qualityUpWaitingTime),this.onDroopedVideoFramesLimitTrigger()),this.savePrevFrameCounts(e,t)}}connect(e){this.log=e.logger.createComponentLog("DroppedFramesManager"),this.video=e.video,this.isAuto=e.isAuto,this.tracks=e.tracks,this.droppedFramesChecker=e.droppedFramesChecker,this.subscription.add(e.playing$.subscribe(()=>this.playing=!0)),this.subscription.add(e.pause$.subscribe(()=>this.playing=!1)),this.isEnabled&&this.subscribe()}destroy(){this.currentTimer&&window.clearTimeout(this.currentTimer),this.subscription.unsubscribe()}get droppedVideoMaxQualityLimit(){return this.maxQualityLimit}subscribe(){this.subscription.add((0,ie.fromEvent)(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=(0,ie.interval)(this.droppedFramesChecker.checkTime).pipe((0,ie.filter)(()=>this.playing),(0,ie.filter)(()=>{let a=!!this.isForceCheckCounter;return a&&(this.isForceCheckCounter-=1),!a})),t=this.forceChecker$.pipe((0,ie.debounce)(this.droppedFramesChecker.checkTime)),r=(0,ie.merge)(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=(0,af.default)(this.limitCounts).filter(([,r])=>r>=this.droppedFramesChecker.countLimit).sort(([r],[a])=>(0,ie.isLower)(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}},ys=zo;var Ts=require("@vkontakte/videoplayer-shared"),sf=require("@vkontakte/videoplayer-shared");var $i=()=>!!window.documentPictureInPicture?.window||!!document.pictureInPictureElement;var rA=(i,e)=>new Ts.Observable(t=>{if(!window.IntersectionObserver)return;let r={root:null},a=new IntersectionObserver((n,o)=>{n.forEach(u=>t.next(u.isIntersecting||$i()))},{...r,...e});a.observe(i);let s=(0,sf.fromEvent)(document,"visibilitychange").pipe((0,Ts.map)(n=>!document.hidden||$i())).subscribe(n=>t.next(n));return()=>{a.unobserve(i),s.unsubscribe}}),qe=rA;var iA=["paused","playing","ready"],aA=["paused","playing","ready"],Li=class{constructor(e){this.subscription=new B.Subscription;this.videoState=new U("stopped");this.representations$=new B.ValueSubject([]);this.textTracksManager=new Fe;this.droppedFramesManager=new ys;this.maxSeekBackTime$=new B.ValueSubject(1/0);this.zeroTime$=new B.ValueSubject(void 0);this.liveOffset=new yt;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:B.ErrorCategory.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=_t(a.name)??(0,B.videoSizeToQuality)(a.video),o=a.bitrate/1e3,u={...a.video};if(!n)continue;let l={id:s,quality:n,bitrate:o,size:u};r.push({track:l,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),(0,B.isNonNullable)(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((0,Ko.default)(aA,e)&&(n||o)){this.prepare();return}if(a?.to!=="paused"&&s.state==="requested"&&(0,Ko.default)(iA,e)){this.seek(s.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(ge(this.params.source.url));return;case"manifest_ready":this.videoState.startTransitionTo("ready"),this.prepare();break;case"ready":if(r==="paused")this.videoState.setState("paused");else if(r==="playing"){this.videoState.startTransitionTo("playing");let u=a?.from;u&&u==="ready"&&this.dash.catchUp(),this.dash.play()}return;case"playing":r==="paused"&&(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.dash.pause());return;case"paused":if(r==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.dash.play(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let u=this.liveOffset.getTotalOffset();u>=this.maxSeekBackTime$.getValue()&&(u=0,this.liveOffset.resetTo(u)),this.liveOffset.resume(),this.params.output.position$.next(-u/1e3),this.dash.reinit(ge(this.params.source.url,u))}return;default:return(0,B.assertNever)(e)}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=a=>{e.output.error$.next({id:"DashLiveProvider",category:B.ErrorCategory.WTF,message:"DashLiveProvider internal logic error",thrown:a})};(0,B.merge)(this.videoState.stateChangeStarted$.pipe((0,B.map)(a=>({transition:a,type:"start"}))),this.videoState.stateChangeEnded$.pipe((0,B.map)(a=>({transition:a,type:"end"})))).subscribe(({transition:a,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(a)}`})}),this.video=Ie(e.container,e.tuning),this.params.output.element$.next(this.video),this.dash=this.createLiveDashPlayer(),this.subscription.add(this.dash.soundProhibitedEvent$.subscribe(this.params.output.soundProhibitedEvent$)),this.params.output.duration$.next(1/0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(de(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=Pe(this.video);this.subscription.add(this.representations$.pipe((0,B.map)(a=>a.map(({track:s})=>s)),(0,B.filter)(a=>!!a.length),(0,B.once)()).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((0,B.filterChanged)(),(0,B.map)(a=>-a/1e3)).subscribe(this.params.output.duration$)).add((0,B.combine)({zeroTime:this.zeroTime$.pipe((0,B.filter)(B.isNonNullable)),position:r.timeUpdate$}).subscribe(({zeroTime:a,position:s})=>this.params.output.liveTime$.next(a+s*1e3),t)).add(ot(this.video,this.params.desiredState.isLooped,t)).add(xe(this.video,this.params.desiredState.volume,r.volumeState$,t)).add(r.volumeState$.subscribe(this.params.output.volume$,t)).add(Ne(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(qe(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:a}})=>{let s=a&&(0,B.videoQualityToHeight)(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(0,B.assertNever)(a.to)}},t)).add((0,B.merge)(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,(0,B.observableFrom)(["init"])).pipe((0,B.debounce)(0)).subscribe(this.syncPlayback,t))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.droppedFramesManager.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),Ee(this.video)}createLiveDashPlayer(){let e=new Ri({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&&(0,B.isNonNullable)(t)?t:Ft(e.map(({track:l})=>l),{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),s=a?.id,n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.videoTrack.getState()?.id,u=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(a&&(n||s!==o)&&this.setVideoTrack(a),u&&this.setAutoQuality(r),n||u||s!==o){let l=e.find(({track:c})=>c.id===s)?.representation;(0,B.assertNonNullable)(l,"Representations missing"),this.dash.startPlay(l,r)}}setVideoTrack(e){let t=this.representations$.getValue().find(({track:r})=>r.id===e.id)?.representation;(0,B.assertNonNullable)(t,`No such representation ${e.id}`),this.dash.switchByName(t.name),this.params.desiredState.videoTrack.setState(e)}setAutoQuality(e){this.dash.setAutoQualityEnabled(e),this.params.desiredState.autoVideoTrackSwitching.setState(e)}seek(e){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),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(ge(this.params.source.url,n)),a&&this.dash.pause(),this.liveOffset.resetTo(n,a)}};var nf=Li;var Sg=G(st(),1);var lt=(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)};var _=require("@vkontakte/videoplayer-shared");var Is=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}},Fr=class extends Is{constructor(){super(),this.listeners||Is.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)}},Mi=class{constructor(){Object.defineProperty(this,"signal",{value:new Fr,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&&(Mi.prototype[Symbol.toStringTag]="AbortController",Fr.prototype[Symbol.toStringTag]="AbortSignal");function Es(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 Jo(i){typeof i=="function"&&(i={fetch:i});let{fetch:e,Request:t=e.Request,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:a=!1}=i;if(!Es({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(l,c){let d;c&&c.signal&&(d=c.signal,delete c.signal);let h=new t(l,c);return d&&Object.defineProperty(h,"signal",{writable:!1,enumerable:!1,configurable:!0,value:d}),h},s.prototype=t.prototype);let n=e;return{fetch:(u,l)=>{let c=s&&s.prototype.isPrototypeOf(u)?u.signal:l?l.signal:void 0;if(c){let d;try{d=new DOMException("Aborted","AbortError")}catch{d=new Error("Aborted"),d.name="AbortError"}if(c.aborted)return Promise.reject(d);let h=new Promise((m,b)=>{c.addEventListener("abort",()=>b(d),{once:!0})});return l&&l.signal&&delete l.signal,Promise.race([h,n(u,l)])}return n(u,l)},Request:s}}var Ci=Es({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),of=Ci?Jo({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,Et=Ci?of.fetch:window.fetch,n0=Ci?of.Request:window.Request,Oe=Ci?Mi:window.AbortController,o0=Ci?Fr:window.AbortSignal;var xu=G(Zo(),1);var As=G(_r(),1);var xt=()=>window.ManagedMediaSource||window.MediaSource,xs=()=>!!(window.ManagedMediaSource&&window.ManagedSourceBuffer?.prototype?.appendBuffer),kf=()=>!!(window.MediaSource&&window.SourceBuffer?.prototype?.appendBuffer),wf=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;var ct=require("@vkontakte/videoplayer-shared"),ks=document.createElement("video"),RA='video/mp4; codecs="avc1.42000a,mp4a.40.2"',$A='video/mp4; codecs="hev1.1.6.L93.B0"',Rf='video/webm; codecs="vp09.00.10.08"',$f='video/webm; codecs="av01.0.00M.08"',LA='audio/mp4; codecs="mp4a.40.2"',MA='audio/webm; codecs="opus"',Di={mms:xs(),mse:kf(),hls:!!(ks.canPlayType?.("application/x-mpegurl")||ks.canPlayType?.("vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},ke={mp4:!!ks.canPlayType?.("video/mp4"),webm:!!ks.canPlayType?.("video/webm"),cmaf:!0},we={h264:!!xt()?.isTypeSupported?.(RA),h265:!!xt()?.isTypeSupported?.($A),vp9:!!xt()?.isTypeSupported?.(Rf),av1:!!xt()?.isTypeSupported?.($f),aac:!!xt()?.isTypeSupported?.(LA),opus:!!xt()?.isTypeSupported?.(MA)},qr=(we.h264||we.h265)&&we.aac,ar,CA=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:$f}}),window.navigator.mediaCapabilities.decodingInfo({...i,video:{...i.video,contentType:Rf}})]);ar={DASH_WEBM_AV1:e,DASH_WEBM:t}};try{CA()}catch(i){console.error(i)}var Ur=Di.hls&&ke.mp4,Lf=()=>Object.keys(we).filter(i=>we[i]),Mf=(i,{useHlsJs:e,useManagedMediaSource:t,useOldMSEDetection:r})=>{let a=Di.mse&&(!r||!!window.MediaStreamTrack)||Di.mms&&t;return i.filter(s=>{switch(s){case"DASH_SEP":return a&&ke.mp4&&qr;case"DASH_WEBM":return a&&ke.webm&&we.vp9&&we.opus;case"DASH_WEBM_AV1":return a&&ke.webm&&we.av1&&we.opus;case"DASH_STREAMS":return a&&(ke.mp4&&qr||ke.webm&&(we.vp9||we.av1)&&(we.opus||we.aac));case"DASH_LIVE":return a&&ke.mp4&&qr;case"DASH_LIVE_CMAF":return a&&ke.mp4&&qr&&ke.cmaf;case"DASH_ONDEMAND":return a&&ke.mp4&&qr;case"HLS":case"HLS_ONDEMAND":return Ur||e&&a&&ke.mp4&&qr;case"HLS_LIVE":case"HLS_LIVE_CMAF":return Ur;case"MPEG":return ke.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return Di.webrtc&&Di.ws&&we.h264&&(ke.mp4||ke.webm);default:return(0,ct.assertNever)(s)}})},Ps=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 ar?ar[t].smooth?[t,e]:ar[e].smooth?[e,t]:[t,e]:[e,t];case"power_efficient":return ar?ar[t].powerEfficient?[t,e]:ar[e].powerEfficient?[e,t]:[t,e]:[e,t];default:(0,ct.assertNever)(i)}return[e,t]},Cf=({webmCodec:i,androidPreferredFormat:e,preferMultiStream:t})=>{let r=[...t?["DASH_STREAMS"]:[],...Ps(i),"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]],a=[...t?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]];if(ct.clientChecker.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",...Ps(i),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...Ps(i),"MPEG",...a,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...Ps(i),...a,"HLS","HLS_ONDEMAND"];default:(0,ct.assertNever)(e)}return Ur?[...r,"HLS","HLS_ONDEMAND","MPEG"]:[...r,"HLS","HLS_ONDEMAND","MPEG"]},Df=({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,u=ct.clientChecker.isMac&&ct.clientChecker.isSafari;if(ct.clientChecker.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:(0,ct.assertNever)(i)}else Ur&&!u?o=n:u?o=e?["DASH_LIVE_CMAF","HLS_LIVE_CMAF","HLS_LIVE","DASH_LIVE"]:["HLS_LIVE","DASH_LIVE","DASH_LIVE_CMAF","HLS_LIVE_CMAF"]:o=s;return t?["WEB_RTC_LIVE",...o]:[...o,"WEB_RTC_LIVE"]},eu=i=>i?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],Vf=i=>{if(i.size===0)return;if(i.size===1){let t=i.values().next();return(0,As.default)(t.value.split("."),0)}for(let t of i){let r=(0,As.default)(t.split("."),0);if(r==="opus"||r==="vp09"||r==="av01")return r}let e=i.values().next();return(0,As.default)(e.value.split("."),0)};var rb=G(tb(),1),Hr=require("@vkontakte/videoplayer-shared"),ib=i=>{if(!i)return{id:"EmptyResponse",category:Hr.ErrorCategory.PARSER,message:"Empty response"};if(i.length<=2&&i.match(/^\d+$/))return{id:`UVError#${i}`,category:Hr.ErrorCategory.NETWORK,message:`UV Error ${i}`};let e=(0,rb.default)(i).substring(0,100).toLowerCase();if(e.startsWith("<!doctype")||e.startsWith("<html>")||e.startsWith("<body>")||e.startsWith("<head>"))return{id:"UnexpectedHTML",category:Hr.ErrorCategory.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:Hr.ErrorCategory.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:Hr.ErrorCategory.PARSER,message:"Response is valid XML, but parser failed"}};var qt=(i,e,t=0)=>{for(let r=0;r<i.length;r++)if(i.start(r)*1e3-t<=e&&i.end(r)*1e3+t>e)return!0;return!1};var S=require("@vkontakte/videoplayer-shared");var ws=G(st(),1),Wr=G(_r(),1),Rs=G(Zo(),1);var KA=(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)},JA=i=>window.clearTimeout(i),ab=i=>typeof i=="function"&&i?.toString().endsWith("{ [native code] }"),sb=!ab(window.requestIdleCallback)||!ab(window.cancelIdleCallback),su=sb?KA:window.requestIdleCallback,Oi=sb?JA:window.cancelIdleCallback;var cg=G(ps(),1);var Ue=require("@vkontakte/videoplayer-shared"),XA=18,nb=!1;try{nb=Ue.clientChecker.isSafari&&!!Ue.clientChecker.macVersion&&Ue.clientChecker.macVersion<=XA}catch(i){console.error(i)}var nu=class{constructor(e){this.bufferFull$=new Ue.Subject;this.error$=new Ue.Subject;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:Ue.ErrorCategory.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:e})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(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;nb&&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:Ue.ErrorCategory.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:(0,Ue.assertNever)(t)}}},ob=nu;var ou=i=>{let e=0;for(let t=0;t<i.length;t++)e+=i.end(t)-i.start(t);return e*1e3};var I=require("@vkontakte/videoplayer-shared");var J=class{constructor(e,t){this.cursor=0;this.source=e,this.boxParser=t,this.children=[];let r=this.readUint32();this.type=this.readString(4),this.size32=r<=e.buffer.byteLength-e.byteOffset?r:NaN;let 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 jr=class extends J{};var Bi=class extends J{constructor(t,r){super(t,r);this.ondemandPrefix="ondemandlivejson";this.ondemandDataReceivedKey="t-in";this.ondemandDataPreparedKey="t-out";let a=this.content.byteOffset,s=a+this.content.byteLength,n=new TextDecoder("ascii").decode(this.content.buffer.slice(a,s)).split(this.ondemandPrefix)[1],o=JSON.parse(n);this.serverDataReceivedTimestamp=o[this.ondemandDataReceivedKey],this.serverDataPreparedTime=o[this.ondemandDataPreparedKey]}};var _i=class extends J{constructor(e,t){super(e,t),this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let r=this.size-this.cursor;for(;r;){let a=this.readString(4);this.compatibleBrands.push(a),r-=4}}};var Ni=class extends J{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ae=class extends J{constructor(e,t){super(e,t);let r=this.readUint32();this.version=r>>>24,this.flags=r&16777215}};var Fi=class extends ae{constructor(e,t){super(e,t),this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.timescale=this.readUint32(),this.duration=this.readUint32(),this.rate=this.readUint32(),this.volume=this.readUint16()}};var qi=class extends J{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Ui=class extends J{constructor(e,t){super(e,t),this.data=this.content}};var sr=class extends ae{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 u=a>>>28,l=a<<3>>>3;this.segments.push({referenceType:s,referencedSize:n,subsegmentDuration:o,SAPType:u,SAPDeltaTime:l})}}};var Hi=class extends J{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ji=class extends J{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Qi=class extends ae{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 Gi=class extends ae{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var Wi=class extends ae{constructor(e,t){super(e,t),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}};var Yi=class extends J{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var zi=class extends ae{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 J{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Ji=class extends J{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Xi=class extends ae{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var Zi=class extends J{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ea=class extends ae{constructor(e,t){super(e,t),this.trackId=this.readUint32(),this.flags&1&&(this.baseDataOffset=this.readUint64()),this.flags&2&&(this.sampleDescriptionIndex=this.readUint32()),this.flags&8&&(this.defaultSampleDuration=this.readUint32()),this.flags&16&&(this.defaultSampleSize=this.readUint32()),this.flags&32&&(this.defaultSampleFlags=this.readUint32())}};var ta=class extends ae{constructor(t,r){super(t,r);this.baseMediaDecodeTime32=0;this.baseMediaDecodeTime64=BigInt(0);this.version===1?this.baseMediaDecodeTime64=this.readUint64():this.baseMediaDecodeTime32=this.readUint32()}get baseMediaDecodeTime(){return this.version===1?this.baseMediaDecodeTime64:this.baseMediaDecodeTime32}};var ra=class extends ae{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 ek={ftyp:_i,moov:Ni,mvhd:Fi,moof:qi,mdat:Ui,sidx:sr,trak:Hi,mdia:Yi,mfhd:Xi,tkhd:zi,traf:Zi,tfhd:ea,tfdt:ta,trun:ra,minf:Ki,sv3d:ji,st3d:Qi,prhd:Gi,proj:Ji,equi:Wi,uuid:Bi,unknown:jr},Pt=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=ek[e];return r?new r(t,new i):new jr(t,new i)}};var Ut=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 rk=new TextDecoder("ascii"),ik=i=>rk.decode(new DataView(i.buffer,i.byteOffset+4,4))==="ftyp",ak=i=>{let e=new sr(i,new Pt),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})},sk=(i,e)=>{let r=new Pt().parse(i),a=new Ut(r),s=a.findAll("moof"),n=e?a.findAll("uuid"):a.findAll("mdat");if(!(n.length&&s.length))return null;let o=s[0],u=n[n.length-1],l=o.source.byteOffset,d=u.source.byteOffset-o.source.byteOffset+u.size;return new DataView(i.buffer,l,d)},nk=i=>{let t=new Pt().parse(i),r=new Ut(t),a={},s=r.findAll("uuid");return s.length?s[s.length-1]:a},ok=i=>{let t=new Pt().parse(i);return new Ut(t).find("sidx")?.timescale},uk=(i,e)=>{let r=new Pt().parse(i),s=new Ut(r).findAll("traf"),n=s[s.length-1].children.find(d=>d.type==="tfhd"),o=s[s.length-1].children.find(d=>d.type==="tfdt"),u=s[s.length-1].children.find(d=>d.type==="trun"),l=0;return u.sampleDuration.length?l=u.sampleDuration.reduce((d,h)=>d+h,0):l=n.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+l)/e*1e3},lk=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 Pt().parse(i),a=new Ut(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 u=a.find("equi");u&&(e.projectionData.bounds.top=u.projectionBoundsTop,e.projectionData.bounds.right=u.projectionBoundsRight,e.projectionData.bounds.bottom=u.projectionBoundsBottom,e.projectionData.bounds.left=u.projectionBoundsLeft)}return e},ub={validateData:ik,parseInit:lk,getIndexRange:()=>{},parseSegments:ak,parseFeedableSegmentChunk:sk,getChunkEndTime:uk,getServerLatencyTimestamps:nk,getTimescaleFromIndex:ok};var aa=G(st(),1),At=require("@vkontakte/videoplayer-shared");var cb=require("@vkontakte/videoplayer-shared");var lb={440786851:{type:"master"},17030:{type:"uint"},17143:{type:"uint"},17138:{type:"uint"},17139:{type:"uint"},17026:{type:"string"},17031:{type:"uint"},17029:{type:"uint"},236:{type:"binary"},408125543:{type:"master"},290298740:{type:"master"},19899:{type:"master"},21419:{type:"binary"},21420:{type:"uint"},357149030:{type:"master"},2807729:{type:"uint"},17545:{type:"float"},374648427:{type:"master"},174:{type:"master"},224:{type:"master"},30320:{type:"master"},30321:{type:"uint"},30322:{type:"master"},272869232:{type:"master"},524531317:{type:"master"},231:{type:"uint"},22612:{type:"master"},22743:{type:"uint"},167:{type:"uint"},171:{type:"uint"},163:{type:"binary"},160:{type:"master"},175:{type:"binary"},423732329:{type:"master"},307544935:{type:"master"},475249515:{type:"master"},187:{type:"master"},179:{type:"uint"},183:{type:"master"},247:{type:"uint"},241:{type:"uint"},240:{type:"uint"},178:{type:"uint"},21368:{type:"uint"},234:{type:"uint"},219:{type:"master"},150:{type:"uint"}},db=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=ia(i,t),a=r in lb,s=a?lb[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 u=new DataView(i.buffer,i.byteOffset+t+1,o-1),l=n&255>>o,c=ia(u),d=l*2**((o-1)*8)+c,h=t+o,m;return h+d>i.byteLength?m=new DataView(i.buffer,i.byteOffset+h):m=new DataView(i.buffer,i.byteOffset+h,d),{tag:a?r:"0x"+r.toString(16).toUpperCase(),type:s,tagHeaderSize:h,tagSize:h+d,value:m,valueSize:d}},ia=(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},Je=(i,e)=>{switch(e){case"int":return i.getInt8(0);case"uint":return ia(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:(0,cb.assertNever)(e)}},nr=(i,e)=>{let t=0;for(;t<i.byteLength;){let r=new DataView(i.buffer,i.byteOffset+t),a=db(r);if(!e(a))return;a.type==="master"&&nr(a.value,e),t=a.value.byteOffset-i.byteOffset+a.valueSize}},pb=i=>{if(i.getUint32(0)!==440786851)return!1;let e,t,r,a=db(i);return nr(a.value,({tag:s,type:n,value:o})=>(s===17143?e=Je(o,n):s===17026?t=Je(o,n):s===17029&&(r=Je(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(r===void 0||r<=2)};var hb=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],ck=[231,22612,22743,167,171,163,160,175],dk=i=>{let e,t,r,a,s=!1,n=!1,o=!1,u,l,c=!1,d=0;return nr(i,({tag:h,type:m,value:b,valueSize:g})=>{if(h===21419){let y=Je(b,m);l=ia(y)}else h!==21420&&(l=void 0);return h===408125543?(e=b.byteOffset,t=b.byteOffset+g):h===357149030?s=!0:h===290298740?n=!0:h===2807729?r=Je(b,m):h===17545?a=Je(b,m):h===21420&&l===475249515?u=Je(b,m):h===374648427?nr(b,({tag:y,type:T,value:$})=>y===30321?(c=Je($,T)===1,!1):!0):s&&n&&(0,aa.default)(hb,h)&&(o=!0),!o}),(0,At.assertNonNullable)(e,"Failed to parse webm Segment start"),(0,At.assertNonNullable)(t,"Failed to parse webm Segment end"),(0,At.assertNonNullable)(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:u,is3dVideo:c,stereoMode:d,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},pk=i=>{if((0,At.isNullable)(i.cuesSeekPosition))return;let e=i.segmentStart+i.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},hk=(i,e)=>{let t=!1,r=!1,a=o=>(0,At.isNonNullable)(o.time)&&(0,At.isNonNullable)(o.position),s=[],n;return nr(i,({tag:o,type:u,value:l})=>{switch(o){case 475249515:t=!0;break;case 187:n&&a(n)&&s.push(n),n={};break;case 179:n&&(n.time=Je(l,u));break;case 183:break;case 241:n&&(n.position=Je(l,u));break;default:t&&(0,aa.default)(hb,o)&&(r=!0)}return!(t&&r)}),n&&a(n)&&s.push(n),s.map((o,u)=>{let{time:l,position:c}=o,d=s[u+1];return{status:"none",time:{from:l,to:d?d.time:e.segmentDuration},byte:{from:e.segmentStart+c,to:d?e.segmentStart+d.position-1:e.segmentEnd-1}}})},mk=i=>{let e=0,t=!1;try{nr(i,r=>r.tag===524531317?r.tagSize<=i.byteLength?(e=r.tagSize,!1):(e+=r.tagHeaderSize,!0):(0,aa.default)(ck,r.tag)?(e+r.tagSize<=i.byteLength&&(e+=r.tagSize,t||=(0,aa.default)([163,160,175],r.tag)),!0):!1)}catch{}return e>0&&e<=i.byteLength&&t?new DataView(i.buffer,i.byteOffset,e):null},mb={validateData:pb,parseInit:dk,getIndexRange:pk,parseSegments:hk,parseFeedableSegmentChunk:mk};var sa=i=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(i);if(e){let[,t,r]=e;if(t==="audio"||t==="video")switch(r){case"webm":return mb;case"mp4":return ub}}throw new ReferenceError(`Unsupported mime type ${i}`)};var fu=G(Db(),1),tg=G(wr(),1),rg=G(Kb(),1),ig=G(_r(),1);var Jb=G(st(),1),mu=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(0,Jb.default)(["6E","7A","F4"],o)}}return!1};var Gr=require("@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 Zb=i=>{try{let e=lw(),t=i.match(e),{groups:r}=t??{};if(r){let a={};if(r.extensions){let o=r.extensions.toLowerCase().match(/(?:[0-9a-wy-z](?:-[a-z0-9]{2,8})+)/g);Array.from(o||[]).forEach(u=>{a[u[0]]=u.slice(2)})}let s=r.variants?.split(/-/).filter(o=>o!==""),n={extlang:r.extlang,langtag:r.langtag,language:r.language,privateuse:r.privateuse||r.privateuse2,region:r.region,script:r.script,extensions:a,variants:s};return Object.keys(n).forEach(o=>{let u=n[o];(typeof u>"u"||u==="")&&delete n[o]}),n}return null}catch{return null}};function lw(){let i="(?<extlang>(?:[a-z]{3}(?:-[a-z]{3}){0,2}))",e="x(?:-[a-z0-9]{1,8})+",c=`^(?:(?<langtag>${`
62
+ `}),b&&Wm(a,u,b,o)};var de=i=>new URL(i).hostname;var V=require("@vkontakte/videoplayer-shared");var Km=j(nt(),1),zm=i=>{if(i instanceof DOMException&&(0,Km.default)(["Failed to load because no supported source was found.","The element has no supported sources."],i.message))throw i;return!(i instanceof DOMException&&(i.code===20||i.name==="AbortError"))},Ae=async(i,e)=>{let t=i.muted;try{await i.play()}catch(r){if(!zm(r))return!1;if(e&&e(),t)return console.warn(r),!1;i.muted=!0;try{await i.play()}catch(a){return zm(a)&&(i.muted=!1,console.warn(a)),!1}}return!0};var Be=require("@vkontakte/videoplayer-shared");var Jm=j(Ii(),1),lt=require("@vkontakte/videoplayer-shared");function pe(){return(0,lt.now)()}function jo(i){return pe()-i}function Go(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,u=!1)=>{a(n)||(n.startsWith("/")||(n="/"+n),n=t+n);let l=n.indexOf("?")>-1?"&":"?";return u&&(n+=l+"lowLat=1",l="&"),o&&(n+=l+"_rnd="+Math.floor(999999999*Math.random())),n}}}function Xm(i,e,t){let r=(...a)=>{t.apply(null,a),i.removeEventListener(e,r)};i.addEventListener(e,r)}function Or(i,e,t,r){let a=window.XMLHttpRequest,s,n,o,u=!1,l=0,c,d,h=!1,m="arraybuffer",b=7e3,g=2e3,y=()=>{if(u)return;(0,lt.assertNonNullable)(c);let P=jo(c),ee;if(P<g){ee=g-P,setTimeout(y,ee);return}g*=2,g>b&&(g=b),n&&n.abort(),n=new a,N()},T=P=>(s=P,E),R=P=>(d=P,E),A=()=>(m="json",E),D=()=>{if(!u){if(--l>=0){y(),r&&r();return}u=!0,d&&d(),t&&t()}},x=P=>(h=P,E),N=()=>{c=pe(),n=new a,n.open("get",i);let P=0,ee,$e=0,Ge=()=>((0,lt.assertNonNullable)(c),Math.max(c,Math.max(ee||0,$e||0)));if(s&&n.addEventListener("progress",w=>{let G=pe();s.updateChunk&&w.loaded>P&&(s.updateChunk(Ge(),w.loaded-P),P=w.loaded,ee=G)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>D())),n.addEventListener("load",()=>{if(u)return;(0,lt.assertNonNullable)(n);let w=n.status;if(w>=200&&w<300){if(n.response.byteLength&&s){let G=n.response.byteLength-P;G&&s.updateChunk&&s.updateChunk(Ge(),G)}n.responseType==="json"&&!(0,Jm.default)(n.response).length?D():(d&&d(),e(n.response))}else D()}),n.addEventListener("error",()=>{D()}),h){let w=()=>{(0,lt.assertNonNullable)(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&($e=pe(),n.removeEventListener("readystatechange",w))};n.addEventListener("readystatechange",w)}return n.responseType=m,n.send(),E},E={withBitrateReporting:T,withParallel:x,withJSONResponse:A,withRetryCount:P=>(l=P,E),withRetryInterval:(P,ee)=>((0,lt.isNonNullable)(P)&&(g=P),(0,lt.isNonNullable)(ee)&&(b=ee),E),withTimeout:P=>(o=P,E),withFinally:R,send:N,abort:()=>{n&&(n.abort(),n=void 0),u=!0,d&&d()}};return E}var Pi=class{constructor(e){this.intervals=[];this.currentRate=0;this.logger=e}_updateRate(e){let t=.2;this.currentRate&&(e<this.currentRate*.1?t=.8:e<this.currentRate*.5?t=.5:e<this.currentRate*.7&&(t=.3)),e=Math.max(1,Math.min(e,100*1024*1024)),this.currentRate=this.currentRate?this.currentRate*(1-t)+e*t:e}_createInterval(e,t,r){return{start:e,end:t,bytes:r}}_doMergeIntervals(e,t){e.start=Math.min(t.start,e.start),e.end=Math.max(t.end,e.end),e.bytes+=t.bytes}_mergeIntervals(e,t){return e.start<=t.end&&t.start<=e.end?(this._doMergeIntervals(e,t),!0):!1}_flushIntervals(){if(!this.intervals.length)return!1;let e=this.intervals[0].start,t=this.intervals[this.intervals.length-1].end-500;if(t-e>2e3){let r=0,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 u=s.bytes*n/o;a+=u,s.start=t,s.bytes-=u}}}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 Zm=j(Ii(),1);var ki=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=pe(),a=u=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=u,e._errorCB?e._errorCB(u):(this.limitCompleteCount(),this.completeRequests[t]=e)},s=u=>{e._complete=1,e._responseData=u,e._downloadTime=pe()-r,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(u,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},n=()=>{e._finallyCB&&e._finallyCB()},o=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=Or(t,s,()=>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=pe()}_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=pe();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(){(0,Zm.default)(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 ef=require("@vkontakte/videoplayer-shared"),gs=1e4,Qo=3;var zP=6e4,KP=10,JP=1,XP=500,Ai=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.soundProhibitedEvent$=new ef.Subject,this.chunkRateEstimator=new Pi(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=Go(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=Go(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||(0,Be.isNonNullable)(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=()=>{Xm(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 ki(Qo,gs,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,u=null,l=null,c=!1,d=()=>{let D=s&&(!c||c===this.rep);return D||t("Not running!"),D},h=(D,x,N)=>{u&&u.abort(),u=Or(this.urlResolver.resolve(D,!1),x,N,()=>this._retryCallback()).withTimeout(gs).withBitrateReporting(this.bitrateSwitcher).withRetryCount(Qo).withFinally(()=>{u=null}).send()},m=(D,x,N)=>{(0,Be.assertNonNullable)(this.filesFetcher),o?.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(D,!1),x,N,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},b=D=>{let x=r.playbackRate;r.playbackRate!==D&&(t(`Playback rate switch: ${x}=>${D}`),r.playbackRate=D)},g=D=>{this.lowLatency=D,t(`lowLatency changed to ${D}`),y()},y=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)b(1);else{let D=this._getBufferSizeSec();if(this.bufferStates.length<5){b(1);return}let N=pe()-1e4,z=0;for(let K=0;K<this.bufferStates.length;K++){let te=this.bufferStates[K];D=Math.min(D,te.buf),te.ts<N&&z++}this.bufferStates.splice(0,z),t(`update playback rate; minBuffer=${D} drop=${z} jitter=${this.sourceJitter}`);let Z=D-JP;this.sourceJitter>=0?Z-=this.sourceJitter/2:this.sourceJitter-=1,Z>3?b(1.15):Z>1?b(1.1):Z>.3?b(1.05):b(1)}},T=D=>{let x,N=()=>x&&x.start?x.start.length:0,z=w=>x.start[w]/1e3,Z=w=>x.dur[w]/1e3,K=w=>x.fragIndex+w,te=(w,G)=>({chunkIdx:K(w),startTS:z(w),dur:Z(w),discontinuity:G}),E=()=>{let w=0;if(x&&x.dur){let G=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,O=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,le=G;this.sourceJitter>1&&(le+=this.sourceJitter-1);let me=x.dur.length-1;for(;me>=0&&(le-=x.dur[me],!(le<=0));--me);w=Math.min(me,x.dur.length-1-O),w=Math.max(w,0)}return te(w,!0)},P=w=>{let G=N();if(!(G<=0)){if((0,Be.isNonNullable)(w)){for(let O=0;O<G;O++)if(z(O)>w)return te(O)}return E()}},ee=w=>{let G=N(),O=w?w.chunkIdx+1:0,le=O-x.fragIndex;if(!(G<=0)){if(!w||le<0||le-G>KP)return t(`Resync: offset=${le} bChunks=${G} chunk=`+JSON.stringify(w)),E();if(!(le>=G))return te(O-x.fragIndex,!1)}},$e=(w,G,O)=>{l&&l.abort(),l=Or(this.urlResolver.resolve(w,!0,this.lowLatency),G,O,()=>this._retryCallback()).withTimeout(gs).withRetryCount(Qo).withFinally(()=>{l=null}).withJSONResponse().send()};return{seek:(w,G)=>{$e(D,O=>{if(!d())return;x=O;let le=!!x.lowLatency;le!==this.lowLatency&&g(le);let me=0;for(let $t=0;$t<x.dur.length;++$t)me+=x.dur[$t];me>0&&((0,Be.assertNonNullable)(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(me/x.dur.length)),a({name:"index",zeroTime:x.zeroTime,shiftDuration:x.shiftDuration}),this.sourceJitter=x.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,x.jitter/1e3)):1,w(P(G))},()=>this._handleNetworkError())},nextChunk:ee}},R=()=>{s=!1,o&&o.abort(),u&&u.abort(),l&&l.abort(),(0,Be.assertNonNullable)(this.filesFetcher),this.filesFetcher.abortAll()};return c={start:D=>{let{videoElement:x,logger:N}=this.params,z=T(e.jidxUrl),Z,K,te,E,P=0,ee,$e,Ge,w=()=>{ee&&(clearTimeout(ee),ee=void 0);let Y=Math.max(XP,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),fe=P+Y,oe=pe(),Ie=Math.min(1e4,fe-oe);P=oe;let Le=()=>{l||d()&&z.seek(()=>{d()&&(P=pe(),G(),w())})};Ie>0?ee=window.setTimeout(()=>{this.paused?w():Le()},Ie):Le()},G=()=>{let Y;for(;Y=z.nextChunk(E);)E=Y,cr(Y);let fe=z.nextChunk(te);if(fe){if(te&&fe.discontinuity){N("Detected discontinuity; restarting playback"),this.paused?w():(R(),this._initPlayerWith(e));return}$t(fe)}else w()},O=(Y,fe)=>{if(!d()||!this.sourceBuffer)return;let oe,Ie,Le,ht=et=>{window.setTimeout(()=>{d()&&O(Y,fe)},et)};if(this.sourceBuffer.updating)N("Source buffer is updating; delaying appendBuffer"),ht(100);else{let et=pe(),mt=x.currentTime;!this.paused&&x.buffered.length>1&&$e===mt&&et-Ge>500&&(N("Stall suspected; trying to fix"),this._fixupStall()),$e!==mt&&($e=mt,Ge=et);let tt=this._getBufferSizeSec();if(tt>30)N(`Buffered ${tt} seconds; delaying appendBuffer`),ht(2e3);else try{this.sourceBuffer.appendBuffer(Y),this.videoPlayStarted?(this.bufferStates.push({ts:et,buf:tt}),y(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),fe&&fe()}catch(dr){if(dr.name==="QuotaExceededError")N("QuotaExceededError; delaying appendBuffer"),Le=this.sourceBuffer.buffered.length,Le!==0&&(oe=this.sourceBuffer.buffered.start(0),Ie=mt,Ie-oe>4&&this.sourceBuffer.remove(oe,Ie-3)),ht(1e3);else throw dr}}},le=()=>{K&&Z&&(N([`Appending chunk, sz=${K.byteLength}:`,JSON.stringify(te)]),O(K,function(){K=null,G()}))},me=Y=>e.fragUrlTemplate.replace("%%id%%",Y.chunkIdx),$t=Y=>{d()&&m(me(Y),(fe,oe)=>{if(d()){if(oe/=1e3,K=fe,te=Y,n=Y.startTS,oe){let Ie=Math.min(10,Y.dur/oe);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*Ie:Ie}le()}},()=>this._handleNetworkError())},cr=Y=>{d()&&((0,Be.assertNonNullable)(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(me(Y),!1)))},Gt=Y=>{d()&&(e.cachedHeader=Y,O(Y,()=>{Z=!0,le()}))};s=!0,z.seek(Y=>{if(d()){if(P=pe(),!Y){w();return}E=Y,!(0,Be.isNullable)(D)||Y.startTS>D?$t(Y):(te=Y,G())}},D),e.cachedHeader?Gt(e.cachedHeader):h(e.headerUrl,Gt,()=>this._handleNetworkError())},stop:R,getTimestampSec:()=>n},c}_switchToQuality(e){let{logger:t,playerCallback:r}=this.params,a;e.bitrate!==this.bitrate&&(this.rep&&(a=this.rep.getTimestampSec(),(0,Be.isNonNullable)(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,(0,Be.assertNonNullable)(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(a),r({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return(0,Be.isNonNullable)(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,r=d=>{if(!this.autoQuality)return;let h,m,b;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&d<this.bitrate&&(m=this._getBufferSizeSec(),b=d/this.bitrate,m>10&&b>.8||m>15&&b>.5||m>20&&b>.3)){e(`Not switching: buffer=${Math.floor(m)}; bitrate=${this.bitrate}; newRate=${Math.floor(d)}`);return}h=this._selectQuality(d),h?this._switchToQuality(h):e(`Could not find quality by bitrate ${d}`)},s={updateChunk:(h,m)=>{let b=pe();if(this.chunkRateEstimator.addInterval(h,b,m)){let y=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:m,duration:b-h,speed:y}),!0}},get:()=>{let h=this.chunkRateEstimator.getBitRate();return h?h*.85:0}},n=-1/0,o,u=!0,l=()=>{let d=s.get();if(d&&o&&this.autoQuality){if(u&&d>o&&jo(n)<3e4)return;r(d)}u=this.autoQuality};return{updateChunk:(d,h)=>{let m=s.updateChunk(d,h);return m&&l(),m},notifySwitch:d=>{let h=pe();d<o&&(n=h),o=d}}}_fetchManifest(e,t,r){this.manifestRequest=Or(this.urlResolver.resolve(e,!0),t,r,()=>this._retryCallback()).withJSONResponse().withTimeout(gs).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;Ae(e,()=>{this.soundProhibitedEvent$.next()}).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((u,l)=>{u.video&&a.canPlayType(u.codecs).replace(/no/,"")&&window.MediaSource.isTypeSupported(u.codecs)&&(u.index=l,o.push(u))}),o.sort(function(u,l){return u.video&&l.video?l.video.height-u.video.height:l.bitrate-u.bitrate}),o):(r({name:"error",type:"empty_manifest"}),[])};this.manifest=s(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),r({name:"manifest",manifest:this.manifest})}_refetchManifest(e){this.destroyed||(this.manifestRefetchTimer&&clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=window.setTimeout(()=>{this._fetchManifest(e,t=>{this.destroyed||(this._handleManifestUpdate(t),this._refetchManifest(e))},()=>this._refetchManifest(e))},zP))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};var tf=j(kr(),1),ie=require("@vkontakte/videoplayer-shared"),Wo=class{constructor(){this.onDroopedVideoFramesLimit$=new ie.Subject;this.subscription=new ie.Subscription;this.playing=!1;this.tracks=[];this.forceChecker$=new ie.Subject;this.isForceCheckCounter=0;this.prevTotalVideoFrames=0;this.prevDroppedVideoFrames=0;this.limitCounts={};this.handleChangeVideoQuality=()=>{let e=this.tracks.find(({size:t})=>t?.height===this.video.videoHeight&&t?.width===this.video.videoWidth);e&&!(0,ie.isInvariantQuality)(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&&(0,ie.isHigher)(this.currentQuality,this.droppedFramesChecker.minQualityBanLimit)&&(this.limitCounts[this.currentQuality]=(this.limitCounts[this.currentQuality]??0)+1,this.maxQualityLimit=this.getMaxQualityLimit(this.currentQuality),this.currentTimer&&window.clearTimeout(this.currentTimer),this.currentTimer=window.setTimeout(()=>this.maxQualityLimit=this.getMaxQualityLimit(),this.droppedFramesChecker.qualityUpWaitingTime),this.onDroopedVideoFramesLimitTrigger()),this.savePrevFrameCounts(e,t)}}connect(e){this.log=e.logger.createComponentLog("DroppedFramesManager"),this.video=e.video,this.isAuto=e.isAuto,this.tracks=e.tracks,this.droppedFramesChecker=e.droppedFramesChecker,this.subscription.add(e.playing$.subscribe(()=>this.playing=!0)),this.subscription.add(e.pause$.subscribe(()=>this.playing=!1)),this.isEnabled&&this.subscribe()}destroy(){this.currentTimer&&window.clearTimeout(this.currentTimer),this.subscription.unsubscribe()}get droppedVideoMaxQualityLimit(){return this.maxQualityLimit}subscribe(){this.subscription.add((0,ie.fromEvent)(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=(0,ie.interval)(this.droppedFramesChecker.checkTime).pipe((0,ie.filter)(()=>this.playing),(0,ie.filter)(()=>{let a=!!this.isForceCheckCounter;return a&&(this.isForceCheckCounter-=1),!a})),t=this.forceChecker$.pipe((0,ie.debounce)(this.droppedFramesChecker.checkTime)),r=(0,ie.merge)(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=(0,tf.default)(this.limitCounts).filter(([,r])=>r>=this.droppedFramesChecker.countLimit).sort(([r],[a])=>(0,ie.isLower)(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}},Ss=Wo;var vs=require("@vkontakte/videoplayer-shared"),rf=require("@vkontakte/videoplayer-shared");var wi=()=>!!window.documentPictureInPicture?.window||!!document.pictureInPictureElement;var ZP=(i,e)=>new vs.Observable(t=>{if(!window.IntersectionObserver)return;let r={root:null},a=new IntersectionObserver((n,o)=>{n.forEach(u=>t.next(u.isIntersecting||wi()))},{...r,...e});a.observe(i);let s=(0,rf.fromEvent)(document,"visibilitychange").pipe((0,vs.map)(n=>!document.hidden||wi())).subscribe(n=>t.next(n));return()=>{a.unobserve(i),s.unsubscribe}}),Ue=ZP;var ek=["paused","playing","ready"],tk=["paused","playing","ready"],Ri=class{constructor(e){this.subscription=new V.Subscription;this.videoState=new q("stopped");this.representations$=new V.ValueSubject([]);this.textTracksManager=new qe;this.droppedFramesManager=new Ss;this.maxSeekBackTime$=new V.ValueSubject(1/0);this.zeroTime$=new V.ValueSubject(void 0);this.liveOffset=new yt;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:V.ErrorCategory.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=_t(a.name)??(0,V.videoSizeToQuality)(a.video),o=a.bitrate/1e3,u={...a.video};if(!n)continue;let l={id:s,quality:n,bitrate:o,size:u};r.push({track:l,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),(0,V.isNonNullable)(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((0,Yo.default)(tk,e)&&(n||o)){this.prepare();return}if(a?.to!=="paused"&&s.state==="requested"&&(0,Yo.default)(ek,e)){this.seek(s.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(Se(this.params.source.url));return;case"manifest_ready":this.videoState.startTransitionTo("ready"),this.prepare();break;case"ready":if(r==="paused")this.videoState.setState("paused");else if(r==="playing"){this.videoState.startTransitionTo("playing");let u=a?.from;u&&u==="ready"&&this.dash.catchUp(),this.dash.play()}return;case"playing":r==="paused"&&(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.dash.pause());return;case"paused":if(r==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.dash.play(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let u=this.liveOffset.getTotalOffset();u>=this.maxSeekBackTime$.getValue()&&(u=0,this.liveOffset.resetTo(u)),this.liveOffset.resume(),this.params.output.position$.next(-u/1e3),this.dash.reinit(Se(this.params.source.url,u))}return;default:return(0,V.assertNever)(e)}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=a=>{e.output.error$.next({id:"DashLiveProvider",category:V.ErrorCategory.WTF,message:"DashLiveProvider internal logic error",thrown:a})};(0,V.merge)(this.videoState.stateChangeStarted$.pipe((0,V.map)(a=>({transition:a,type:"start"}))),this.videoState.stateChangeEnded$.pipe((0,V.map)(a=>({transition:a,type:"end"})))).subscribe(({transition:a,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(a)}`})}),this.video=Ee(e.container,e.tuning),this.params.output.element$.next(this.video),this.dash=this.createLiveDashPlayer(),this.subscription.add(this.dash.soundProhibitedEvent$.subscribe(this.params.output.soundProhibitedEvent$)),this.params.output.duration$.next(1/0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(de(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=ke(this.video);this.subscription.add(this.representations$.pipe((0,V.map)(a=>a.map(({track:s})=>s)),(0,V.filter)(a=>!!a.length),(0,V.once)()).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((0,V.filterChanged)(),(0,V.map)(a=>-a/1e3)).subscribe(this.params.output.duration$)).add((0,V.combine)({zeroTime:this.zeroTime$.pipe((0,V.filter)(V.isNonNullable)),position:r.timeUpdate$}).subscribe(({zeroTime:a,position:s})=>this.params.output.liveTime$.next(a+s*1e3),t)).add(ut(this.video,this.params.desiredState.isLooped,t)).add(Pe(this.video,this.params.desiredState.volume,r.volumeState$,t)).add(r.volumeState$.subscribe(this.params.output.volume$,t)).add(Fe(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(Ue(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:a}})=>{let s=a&&(0,V.videoQualityToHeight)(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(0,V.assertNever)(a.to)}},t)).add((0,V.merge)(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,(0,V.observableFrom)(["init"])).pipe((0,V.debounce)(0)).subscribe(this.syncPlayback,t))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.droppedFramesManager.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),xe(this.video)}createLiveDashPlayer(){let e=new Ai({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&&(0,V.isNonNullable)(t)?t:Ft(e.map(({track:l})=>l),{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),s=a?.id,n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.videoTrack.getState()?.id,u=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(a&&(n||s!==o)&&this.setVideoTrack(a),u&&this.setAutoQuality(r),n||u||s!==o){let l=e.find(({track:c})=>c.id===s)?.representation;(0,V.assertNonNullable)(l,"Representations missing"),this.dash.startPlay(l,r)}}setVideoTrack(e){let t=this.representations$.getValue().find(({track:r})=>r.id===e.id)?.representation;(0,V.assertNonNullable)(t,`No such representation ${e.id}`),this.dash.switchByName(t.name),this.params.desiredState.videoTrack.setState(e)}setAutoQuality(e){this.dash.setAutoQualityEnabled(e),this.params.desiredState.autoVideoTrackSwitching.setState(e)}seek(e){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),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(Se(this.params.source.url,n)),a&&this.dash.pause(),this.liveOffset.resetTo(n,a)}};var af=Ri;var bg=j(nt(),1);var ct=(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)};var B=require("@vkontakte/videoplayer-shared");var ys=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}},_r=class extends ys{constructor(){super(),this.listeners||ys.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)}},$i=class{constructor(){Object.defineProperty(this,"signal",{value:new _r,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&&($i.prototype[Symbol.toStringTag]="AbortController",_r.prototype[Symbol.toStringTag]="AbortSignal");function Ts(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 zo(i){typeof i=="function"&&(i={fetch:i});let{fetch:e,Request:t=e.Request,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:a=!1}=i;if(!Ts({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(l,c){let d;c&&c.signal&&(d=c.signal,delete c.signal);let h=new t(l,c);return d&&Object.defineProperty(h,"signal",{writable:!1,enumerable:!1,configurable:!0,value:d}),h},s.prototype=t.prototype);let n=e;return{fetch:(u,l)=>{let c=s&&s.prototype.isPrototypeOf(u)?u.signal:l?l.signal:void 0;if(c){let d;try{d=new DOMException("Aborted","AbortError")}catch{d=new Error("Aborted"),d.name="AbortError"}if(c.aborted)return Promise.reject(d);let h=new Promise((m,b)=>{c.addEventListener("abort",()=>b(d),{once:!0})});return l&&l.signal&&delete l.signal,Promise.race([h,n(u,l)])}return n(u,l)},Request:s}}var Li=Ts({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),sf=Li?zo({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,Et=Li?sf.fetch:window.fetch,KC=Li?sf.Request:window.Request,Oe=Li?$i:window.AbortController,JC=Li?_r:window.AbortSignal;var Iu=j(Jo(),1);var xs=j(Br(),1);var xt=()=>window.ManagedMediaSource||window.MediaSource,Is=()=>!!(window.ManagedMediaSource&&window.ManagedSourceBuffer?.prototype?.appendBuffer),Pf=()=>!!(window.MediaSource&&window.SourceBuffer?.prototype?.appendBuffer),kf=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;var dt=require("@vkontakte/videoplayer-shared"),Ps=document.createElement("video"),kk='video/mp4; codecs="avc1.42000a,mp4a.40.2"',Ak='video/mp4; codecs="hev1.1.6.L93.B0"',Af='video/webm; codecs="vp09.00.10.08"',wf='video/webm; codecs="av01.0.00M.08"',wk='audio/mp4; codecs="mp4a.40.2"',Rk='audio/webm; codecs="opus"',Mi={mms:Is(),mse:Pf(),hls:!!(Ps.canPlayType?.("application/x-mpegurl")||Ps.canPlayType?.("vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},we={mp4:!!Ps.canPlayType?.("video/mp4"),webm:!!Ps.canPlayType?.("video/webm"),cmaf:!0},Re={h264:!!xt()?.isTypeSupported?.(kk),h265:!!xt()?.isTypeSupported?.(Ak),vp9:!!xt()?.isTypeSupported?.(Af),av1:!!xt()?.isTypeSupported?.(wf),aac:!!xt()?.isTypeSupported?.(wk),opus:!!xt()?.isTypeSupported?.(Rk)},Nr=(Re.h264||Re.h265)&&Re.aac,ar,$k=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:wf}}),window.navigator.mediaCapabilities.decodingInfo({...i,video:{...i.video,contentType:Af}})]);ar={DASH_WEBM_AV1:e,DASH_WEBM:t}};try{$k()}catch(i){console.error(i)}var Fr=Mi.hls&&we.mp4,Rf=()=>Object.keys(Re).filter(i=>Re[i]),$f=(i,{useHlsJs:e,useManagedMediaSource:t,useOldMSEDetection:r})=>{let a=Mi.mse&&(!r||!!window.MediaStreamTrack)||Mi.mms&&t;return i.filter(s=>{switch(s){case"DASH_SEP":return a&&we.mp4&&Nr;case"DASH_WEBM":return a&&we.webm&&Re.vp9&&Re.opus;case"DASH_WEBM_AV1":return a&&we.webm&&Re.av1&&Re.opus;case"DASH_STREAMS":return a&&(we.mp4&&Nr||we.webm&&(Re.vp9||Re.av1)&&(Re.opus||Re.aac));case"DASH_LIVE":return a&&we.mp4&&Nr;case"DASH_LIVE_CMAF":return a&&we.mp4&&Nr&&we.cmaf;case"DASH_ONDEMAND":return a&&we.mp4&&Nr;case"HLS":case"HLS_ONDEMAND":return Fr||e&&a&&we.mp4&&Nr;case"HLS_LIVE":case"HLS_LIVE_CMAF":return Fr;case"MPEG":return we.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return Mi.webrtc&&Mi.ws&&Re.h264&&(we.mp4||we.webm);default:return(0,dt.assertNever)(s)}})},Es=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 ar?ar[t].smooth?[t,e]:ar[e].smooth?[e,t]:[t,e]:[e,t];case"power_efficient":return ar?ar[t].powerEfficient?[t,e]:ar[e].powerEfficient?[e,t]:[t,e]:[e,t];default:(0,dt.assertNever)(i)}return[e,t]},Lf=({webmCodec:i,androidPreferredFormat:e,preferMultiStream:t})=>{let r=[...t?["DASH_STREAMS"]:[],...Es(i),"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]],a=[...t?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]];if(dt.clientChecker.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",...Es(i),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...Es(i),"MPEG",...a,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...Es(i),...a,"HLS","HLS_ONDEMAND"];default:(0,dt.assertNever)(e)}return Fr?[...r,"HLS","HLS_ONDEMAND","MPEG"]:[...r,"HLS","HLS_ONDEMAND","MPEG"]},Mf=({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,u=dt.clientChecker.isMac&&dt.clientChecker.isSafari;if(dt.clientChecker.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:(0,dt.assertNever)(i)}else Fr&&!u?o=n:u?o=e?["DASH_LIVE_CMAF","HLS_LIVE_CMAF","HLS_LIVE","DASH_LIVE"]:["HLS_LIVE","DASH_LIVE","DASH_LIVE_CMAF","HLS_LIVE_CMAF"]:o=s;return t?["WEB_RTC_LIVE",...o]:[...o,"WEB_RTC_LIVE"]},Xo=i=>i?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],Cf=i=>{if(i.size===0)return;if(i.size===1){let t=i.values().next();return(0,xs.default)(t.value.split("."),0)}for(let t of i){let r=(0,xs.default)(t.split("."),0);if(r==="opus"||r==="vp09"||r==="av01")return r}let e=i.values().next();return(0,xs.default)(e.value.split("."),0)};var eb=j(Zf(),1),qr=require("@vkontakte/videoplayer-shared"),tb=i=>{if(!i)return{id:"EmptyResponse",category:qr.ErrorCategory.PARSER,message:"Empty response"};if(i.length<=2&&i.match(/^\d+$/))return{id:`UVError#${i}`,category:qr.ErrorCategory.NETWORK,message:`UV Error ${i}`};let e=(0,eb.default)(i).substring(0,100).toLowerCase();if(e.startsWith("<!doctype")||e.startsWith("<html>")||e.startsWith("<body>")||e.startsWith("<head>"))return{id:"UnexpectedHTML",category:qr.ErrorCategory.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:qr.ErrorCategory.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:qr.ErrorCategory.PARSER,message:"Response is valid XML, but parser failed"}};var qt=(i,e,t=0)=>{for(let r=0;r<i.length;r++)if(i.start(r)*1e3-t<=e&&i.end(r)*1e3+t>e)return!0;return!1};var S=require("@vkontakte/videoplayer-shared");var ks=j(nt(),1),Gr=j(Br(),1),As=j(Jo(),1);var Wk=(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)},Yk=i=>window.clearTimeout(i),rb=i=>typeof i=="function"&&i?.toString().endsWith("{ [native code] }"),ib=!rb(window.requestIdleCallback)||!rb(window.cancelIdleCallback),iu=ib?Wk:window.requestIdleCallback,Di=ib?Yk:window.cancelIdleCallback;var ug=j(ds(),1);var He=require("@vkontakte/videoplayer-shared"),zk=18,ab=!1;try{ab=He.clientChecker.isSafari&&!!He.clientChecker.macVersion&&He.clientChecker.macVersion<=zk}catch(i){console.error(i)}var au=class{constructor(e){this.bufferFull$=new He.Subject;this.error$=new He.Subject;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:He.ErrorCategory.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:e})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(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;ab&&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:He.ErrorCategory.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:(0,He.assertNever)(t)}}},sb=au;var su=i=>{let e=0;for(let t=0;t<i.length;t++)e+=i.end(t)-i.start(t);return e*1e3};var I=require("@vkontakte/videoplayer-shared");var J=class{constructor(e,t){this.cursor=0;this.source=e,this.boxParser=t,this.children=[];let r=this.readUint32();this.type=this.readString(4),this.size32=r<=e.buffer.byteLength-e.byteOffset?r:NaN;let 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 Ur=class extends J{};var Vi=class extends J{constructor(t,r){super(t,r);this.ondemandPrefix="ondemandlivejson";this.ondemandDataReceivedKey="t-in";this.ondemandDataPreparedKey="t-out";let a=this.content.byteOffset,s=a+this.content.byteLength,n=new TextDecoder("ascii").decode(this.content.buffer.slice(a,s)).split(this.ondemandPrefix)[1],o=JSON.parse(n);this.serverDataReceivedTimestamp=o[this.ondemandDataReceivedKey],this.serverDataPreparedTime=o[this.ondemandDataPreparedKey]}};var Bi=class extends J{constructor(e,t){super(e,t),this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let r=this.size-this.cursor;for(;r;){let a=this.readString(4);this.compatibleBrands.push(a),r-=4}}};var Oi=class extends J{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ae=class extends J{constructor(e,t){super(e,t);let r=this.readUint32();this.version=r>>>24,this.flags=r&16777215}};var _i=class extends ae{constructor(e,t){super(e,t),this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.timescale=this.readUint32(),this.duration=this.readUint32(),this.rate=this.readUint32(),this.volume=this.readUint16()}};var Ni=class extends J{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Fi=class extends J{constructor(e,t){super(e,t),this.data=this.content}};var sr=class extends ae{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 u=a>>>28,l=a<<3>>>3;this.segments.push({referenceType:s,referencedSize:n,subsegmentDuration:o,SAPType:u,SAPDeltaTime:l})}}};var qi=class extends J{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Ui=class extends J{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Hi=class extends ae{constructor(e,t){switch(super(e,t),this.readUint8()){case 0:this.stereoMode=0;break;case 1:this.stereoMode=1;break;case 2:this.stereoMode=2;break;case 3:this.stereoMode=3;break;case 4:this.stereoMode=4;break}this.cursor+=1}};var ji=class extends ae{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var Gi=class extends ae{constructor(e,t){super(e,t),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}};var Qi=class extends J{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Wi=class extends ae{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 Yi=class extends J{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var zi=class extends J{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Ki=class extends ae{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var Ji=class extends J{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Xi=class extends ae{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 Zi=class extends ae{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 ea=class extends ae{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 Jk={ftyp:Bi,moov:Oi,mvhd:_i,moof:Ni,mdat:Fi,sidx:sr,trak:qi,mdia:Qi,mfhd:Ki,tkhd:Wi,traf:Ji,tfhd:Xi,tfdt:Zi,trun:ea,minf:Yi,sv3d:Ui,st3d:Hi,prhd:ji,proj:zi,equi:Gi,uuid:Vi,unknown:Ur},Pt=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=Jk[e];return r?new r(t,new i):new Ur(t,new i)}};var Ut=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 Zk=new TextDecoder("ascii"),eA=i=>Zk.decode(new DataView(i.buffer,i.byteOffset+4,4))==="ftyp",tA=i=>{let e=new sr(i,new Pt),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})},rA=(i,e)=>{let r=new Pt().parse(i),a=new Ut(r),s=a.findAll("moof"),n=e?a.findAll("uuid"):a.findAll("mdat");if(!(n.length&&s.length))return null;let o=s[0],u=n[n.length-1],l=o.source.byteOffset,d=u.source.byteOffset-o.source.byteOffset+u.size;return new DataView(i.buffer,l,d)},iA=i=>{let t=new Pt().parse(i),r=new Ut(t),a={},s=r.findAll("uuid");return s.length?s[s.length-1]:a},aA=i=>{let t=new Pt().parse(i);return new Ut(t).find("sidx")?.timescale},sA=(i,e)=>{let r=new Pt().parse(i),s=new Ut(r).findAll("traf"),n=s[s.length-1].children.find(d=>d.type==="tfhd"),o=s[s.length-1].children.find(d=>d.type==="tfdt"),u=s[s.length-1].children.find(d=>d.type==="trun"),l=0;return u.sampleDuration.length?l=u.sampleDuration.reduce((d,h)=>d+h,0):l=n.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+l)/e*1e3},nA=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 Pt().parse(i),a=new Ut(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 u=a.find("equi");u&&(e.projectionData.bounds.top=u.projectionBoundsTop,e.projectionData.bounds.right=u.projectionBoundsRight,e.projectionData.bounds.bottom=u.projectionBoundsBottom,e.projectionData.bounds.left=u.projectionBoundsLeft)}return e},nb={validateData:eA,parseInit:nA,getIndexRange:()=>{},parseSegments:tA,parseFeedableSegmentChunk:rA,getChunkEndTime:sA,getServerLatencyTimestamps:iA,getTimescaleFromIndex:aA};var ra=j(nt(),1),kt=require("@vkontakte/videoplayer-shared");var ub=require("@vkontakte/videoplayer-shared");var ob={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"}},lb=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=ta(i,t),a=r in ob,s=a?ob[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 u=new DataView(i.buffer,i.byteOffset+t+1,o-1),l=n&255>>o,c=ta(u),d=l*2**((o-1)*8)+c,h=t+o,m;return h+d>i.byteLength?m=new DataView(i.buffer,i.byteOffset+h):m=new DataView(i.buffer,i.byteOffset+h,d),{tag:a?r:"0x"+r.toString(16).toUpperCase(),type:s,tagHeaderSize:h,tagSize:h+d,value:m,valueSize:d}},ta=(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},Xe=(i,e)=>{switch(e){case"int":return i.getInt8(0);case"uint":return ta(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:(0,ub.assertNever)(e)}},nr=(i,e)=>{let t=0;for(;t<i.byteLength;){let r=new DataView(i.buffer,i.byteOffset+t),a=lb(r);if(!e(a))return;a.type==="master"&&nr(a.value,e),t=a.value.byteOffset-i.byteOffset+a.valueSize}},cb=i=>{if(i.getUint32(0)!==440786851)return!1;let e,t,r,a=lb(i);return nr(a.value,({tag:s,type:n,value:o})=>(s===17143?e=Xe(o,n):s===17026?t=Xe(o,n):s===17029&&(r=Xe(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(r===void 0||r<=2)};var db=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],oA=[231,22612,22743,167,171,163,160,175],uA=i=>{let e,t,r,a,s=!1,n=!1,o=!1,u,l,c=!1,d=0;return nr(i,({tag:h,type:m,value:b,valueSize:g})=>{if(h===21419){let y=Xe(b,m);l=ta(y)}else h!==21420&&(l=void 0);return h===408125543?(e=b.byteOffset,t=b.byteOffset+g):h===357149030?s=!0:h===290298740?n=!0:h===2807729?r=Xe(b,m):h===17545?a=Xe(b,m):h===21420&&l===475249515?u=Xe(b,m):h===374648427?nr(b,({tag:y,type:T,value:R})=>y===30321?(c=Xe(R,T)===1,!1):!0):s&&n&&(0,ra.default)(db,h)&&(o=!0),!o}),(0,kt.assertNonNullable)(e,"Failed to parse webm Segment start"),(0,kt.assertNonNullable)(t,"Failed to parse webm Segment end"),(0,kt.assertNonNullable)(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:u,is3dVideo:c,stereoMode:d,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},lA=i=>{if((0,kt.isNullable)(i.cuesSeekPosition))return;let e=i.segmentStart+i.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},cA=(i,e)=>{let t=!1,r=!1,a=o=>(0,kt.isNonNullable)(o.time)&&(0,kt.isNonNullable)(o.position),s=[],n;return nr(i,({tag:o,type:u,value:l})=>{switch(o){case 475249515:t=!0;break;case 187:n&&a(n)&&s.push(n),n={};break;case 179:n&&(n.time=Xe(l,u));break;case 183:break;case 241:n&&(n.position=Xe(l,u));break;default:t&&(0,ra.default)(db,o)&&(r=!0)}return!(t&&r)}),n&&a(n)&&s.push(n),s.map((o,u)=>{let{time:l,position:c}=o,d=s[u+1];return{status:"none",time:{from:l,to:d?d.time:e.segmentDuration},byte:{from:e.segmentStart+c,to:d?e.segmentStart+d.position-1:e.segmentEnd-1}}})},dA=i=>{let e=0,t=!1;try{nr(i,r=>r.tag===524531317?r.tagSize<=i.byteLength?(e=r.tagSize,!1):(e+=r.tagHeaderSize,!0):(0,ra.default)(oA,r.tag)?(e+r.tagSize<=i.byteLength&&(e+=r.tagSize,t||=(0,ra.default)([163,160,175],r.tag)),!0):!1)}catch{}return e>0&&e<=i.byteLength&&t?new DataView(i.buffer,i.byteOffset,e):null},pb={validateData:cb,parseInit:uA,getIndexRange:lA,parseSegments:cA,parseFeedableSegmentChunk:dA};var ia=i=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(i);if(e){let[,t,r]=e;if(t==="audio"||t==="video")switch(r){case"webm":return pb;case"mp4":return nb}}throw new ReferenceError(`Unsupported mime type ${i}`)};var hu=j(Mb(),1),Zb=j(kr(),1),eg=j(Yb(),1),tg=j(Br(),1);var zb=j(nt(),1),pu=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(0,zb.default)(["6E","7A","F4"],o)}}return!1};var jr=require("@vkontakte/videoplayer-shared");var Kb=i=>{if(i.includes("/")){let e=i.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(i)};var Jb=i=>{try{let e=nw(),t=i.match(e),{groups:r}=t??{};if(r){let a={};if(r.extensions){let o=r.extensions.toLowerCase().match(/(?:[0-9a-wy-z](?:-[a-z0-9]{2,8})+)/g);Array.from(o||[]).forEach(u=>{a[u[0]]=u.slice(2)})}let s=r.variants?.split(/-/).filter(o=>o!==""),n={extlang:r.extlang,langtag:r.langtag,language:r.language,privateuse:r.privateuse||r.privateuse2,region:r.region,script:r.script,extensions:a,variants:s};return Object.keys(n).forEach(o=>{let u=n[o];(typeof u>"u"||u==="")&&delete n[o]}),n}return null}catch{return null}};function nw(){let i="(?<extlang>(?:[a-z]{3}(?:-[a-z]{3}){0,2}))",e="x(?:-[a-z0-9]{1,8})+",c=`^(?:(?<langtag>${`
63
63
  (?<language>${`(?:[a-z]{2,3}(?:-${i})?|[a-z]{4}|[a-z]{5,8})`})
64
64
  (-(?<script>[a-z]{4}))?
65
65
  (-(?<region>(?:[a-z]{2}|[0-9]{3})))?
66
66
  (?<variants>(?:-(?:[a-z0-9]{5,8}|[0-9][a-z0-9]{3}))*)
67
67
  (?<extensions>(?:-[0-9a-wy-z](?:-[a-z0-9]{2,8})+)*)
68
68
  (?:-(?<privateuse>(?:${e})))?
69
- `})|(?<privateuse2>${e}))$`.replace(/[\s\t\n]/g,"");return new RegExp(c,"i")}var eg=i=>{if(!i.startsWith("P"))return;let e=(n,o)=>{let u=n?parseFloat(n.replace(",",".")):NaN;return(isNaN(u)?0:u)*o},r=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(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},kt=(i,e)=>{let t=i;t=(0,fu.default)(t,"$$","$");let r={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[a,s]of(0,tg.default)(r)){let n=new RegExp(`\\$${a}(?:%0(\\d+)d)?\\$`,"g");t=(0,fu.default)(t,n,(o,u)=>(0,Gr.isNullable)(s)?o:(0,Gr.isNullable)(u)?s:(0,rg.default)(s,parseInt(u,10),"0"))}return t},ag=(i,e)=>{let r=new DOMParser().parseFromString(i,"application/xml"),a={video:[],audio:[],text:[]},s=r.children[0],n=s.getElementsByTagName("Period")[0],o=Array.from(s.querySelectorAll("MPD > BaseURL").values()).map(E=>E.textContent?.trim()??""),u=(0,ig.default)(o,0)??"",l=n.children,c=s.getAttribute("type")==="dynamic",d=s.getAttribute("availabilityStartTime"),h=d?new Date(d).getTime():void 0,m,b=s.getAttribute("mediaPresentationDuration"),g=n.getAttribute("duration"),T=s.getElementsByTagName("vk:Attrs")[0]?.getElementsByTagName("vk:XPlaybackDuration")[0].textContent;if(b)m=eg(b);else if(g){let E=eg(g);(0,Gr.isNonNullable)(E)&&(m=E)}else T&&(m=parseInt(T,10));let $=0,P=s.getAttribute("profiles")?.split(",")??[];for(let E of l){let V=E.getAttribute("id")??"id"+($++).toString(10),ee=E.getAttribute("mimeType")??"",z=E.getAttribute("codecs")??"",Z=E.getAttribute("contentType")??ee?.split("/")[0],A=E.getAttribute("profiles")?.split(",")??[],D=Zb(E.getAttribute("lang")??"")??{},L=E.querySelector("Label")?.textContent?.trim()??void 0,re=E.querySelectorAll("Representation"),je=E.querySelector("SegmentTemplate"),pt=E.querySelector("Role")?.getAttribute("value")??void 0,M=Z,Q={id:V,language:D.language,isDefault:pt==="main",label:L,codecs:z,hdr:M==="video"&&mu(z),mime:ee,representations:[]};for(let N of re){let oe=N.getAttribute("lang")??void 0,Re=N.getAttribute("label")??void 0,$t=N.querySelector("BaseURL")?.textContent?.trim()??"",dr=new URL($t||u,e).toString(),Qt=N.getAttribute("mimeType")??ee,K=N.getAttribute("codecs")??z??"",me;if(Z==="text"){let ue=N.getAttribute("id")||"",Te=D.privateuse?.includes("x-auto")||ue.includes("_auto"),$e=N.querySelector("SegmentTemplate");if($e){let ht={representationId:N.getAttribute("id")??void 0,bandwidth:N.getAttribute("bandwidth")??void 0},Ze=parseInt(N.getAttribute("bandwidth")??"",10)/1e3,mt=parseInt($e.getAttribute("startNumber")??"",10)??1,et=parseInt($e.getAttribute("timescale")??"",10),pr=$e.querySelectorAll("SegmentTimeline S")??[],hr=$e.getAttribute("media");if(!hr)continue;let Pa=[],Aa=0,ka="",mr=0,Kr=mt,Se=0;for(let Qe of pr){let Gt=parseInt(Qe.getAttribute("d")??"",10),_e=parseInt(Qe.getAttribute("r")??"",10)||0,Lt=parseInt(Qe.getAttribute("t")??"",10);Se=Number.isFinite(Lt)?Lt:Se;let Wt=Gt/et*1e3,fr=Se/et*1e3;for(let tt=0;tt<_e+1;tt++){let Mt=kt(hr,{...ht,segmentNumber:Kr.toString(10),segmentTime:(Se+tt*Gt).toString(10)}),br=(fr??0)+tt*Wt,Xr=br+Wt;Kr++,Pa.push({time:{from:br,to:Xr},url:Mt})}Se+=(_e+1)*Gt,Aa+=(_e+1)*Wt}mr=Se/et*1e3,ka=kt(hr,{...ht,segmentNumber:Kr.toString(10),segmentTime:Se.toString(10)});let Jr={time:{from:mr,to:1/0},url:ka},ft={type:"template",baseUrl:dr,segmentTemplateUrl:hr,initUrl:"",totalSegmentsDurationMs:Aa,segments:Pa,nextSegmentBeyondManifest:Jr,timescale:et};me={id:ue,kind:"text",segmentReference:ft,profiles:[],duration:m,bitrate:Ze,mime:"",codecs:"",width:0,height:0,isAuto:Te}}else me={id:ue,isAuto:Te,kind:"text",url:dr}}else{let ue=N.getAttribute("contentType")??Qt?.split("/")[0]??Z,Te=E.getAttribute("profiles")?.split(",")??[],$e=parseInt(N.getAttribute("width")??"",10),ht=parseInt(N.getAttribute("height")??"",10),Ze=parseInt(N.getAttribute("bandwidth")??"",10)/1e3,mt=N.getAttribute("frameRate")??"",et=N.getAttribute("quality")??void 0,pr=mt?Xb(mt):void 0,hr=N.getAttribute("id")??"id"+($++).toString(10),Pa=ue==="video"?`${ht}p`:ue==="audio"?`${Ze}Kbps`:K,Aa=`${hr}@${Pa}`,ka=[...P,...A,...Te],mr,Kr=N.querySelector("SegmentBase"),Se=N.querySelector("SegmentTemplate")??je;if(Kr){let ft=N.querySelector("SegmentBase Initialization")?.getAttribute("range")??"",[Qe,Gt]=ft.split("-").map(Mt=>parseInt(Mt,10)),_e={from:Qe,to:Gt},Lt=N.querySelector("SegmentBase")?.getAttribute("indexRange"),[Wt,fr]=Lt?Lt.split("-").map(Mt=>parseInt(Mt,10)):[],tt=Lt?{from:Wt,to:fr}:void 0;mr={type:"byteRange",url:dr,initRange:_e,indexRange:tt}}else if(Se){let ft={representationId:N.getAttribute("id")??void 0,bandwidth:N.getAttribute("bandwidth")??void 0},Qe=parseInt(Se.getAttribute("timescale")??"",10),Gt=Se.getAttribute("initialization")??"",_e=Se.getAttribute("media"),Lt=parseInt(Se.getAttribute("startNumber")??"",10)??1,Wt=kt(Gt,ft);if(!_e)throw new ReferenceError("No media attribute in SegmentTemplate");let fr=Se.querySelectorAll("SegmentTimeline S")??[],tt=[],Mt=0,br="",Xr=0;if(fr.length){let wa=Lt,Ge=0;for(let gr of fr){let rt=parseInt(gr.getAttribute("d")??"",10),Yt=parseInt(gr.getAttribute("r")??"",10)||0,Ra=parseInt(gr.getAttribute("t")??"",10);Ge=Number.isFinite(Ra)?Ra:Ge;let Hs=rt/Qe*1e3,Hg=Ge/Qe*1e3;for(let $a=0;$a<Yt+1;$a++){let jg=kt(_e,{...ft,segmentNumber:wa.toString(10),segmentTime:(Ge+$a*rt).toString(10)}),Cu=(Hg??0)+$a*Hs,Qg=Cu+Hs;wa++,tt.push({time:{from:Cu,to:Qg},url:jg})}Ge+=(Yt+1)*rt,Mt+=(Yt+1)*Hs}Xr=Ge/Qe*1e3,br=kt(_e,{...ft,segmentNumber:wa.toString(10),segmentTime:Ge.toString(10)})}else if((0,Gr.isNonNullable)(m)){let Ge=parseInt(Se.getAttribute("duration")??"",10)/Qe*1e3,gr=Math.ceil(m/Ge),rt=0;for(let Yt=1;Yt<gr;Yt++){let Ra=kt(_e,{...ft,segmentNumber:Yt.toString(10),segmentTime:rt.toString(10)});tt.push({time:{from:rt,to:rt+Ge},url:Ra}),rt+=Ge}Xr=rt,br=kt(_e,{...ft,segmentNumber:gr.toString(10),segmentTime:rt.toString(10)})}let Ug={time:{from:Xr,to:1/0},url:br};mr={type:"template",baseUrl:dr,segmentTemplateUrl:_e,initUrl:Wt,totalSegmentsDurationMs:Mt,segments:tt,nextSegmentBeyondManifest:Ug,timescale:Qe}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!ue||!Qt)continue;let Jr={video:"video",audio:"audio",text:"text"}[ue];if(!Jr)continue;M||=Jr,me={id:Aa,kind:Jr,segmentReference:mr,profiles:ka,duration:m,bitrate:Ze,mime:Qt,codecs:K,width:$e,height:ht,fps:pr,quality:et}}Q.language||=oe,Q.label||=Re,Q.mime||=Qt,Q.codecs||=K,Q.hdr||=M==="video"&&mu(K),Q.representations.push(me)}M&&a[M].push(Q)}return{dynamic:c,liveAvailabilityStartTime:h,duration:m,streams:a,baseUrls:o}};var Su=G(_r(),1);var sg=require("@vkontakte/videoplayer-shared"),ng=({id:i,width:e,height:t,bitrate:r,fps:a,quality:s,streamId:n})=>{let o=(s?_t(s):void 0)??(0,sg.videoSizeToQuality)({width:e,height:t});return o&&{id:i,quality:o,bitrate:r,size:{width:e,height:t},fps:a,streamId:n}},og=({id:i,bitrate:e})=>({id:i,bitrate:e}),ug=({language:i,label:e},{id:t,url:r,isAuto:a})=>({id:t,url:r,isAuto:a,type:"internal",language:i,label:e}),lg=({language:i,label:e,id:t,url:r,isAuto:a})=>({id:t,url:r,isAuto:a,type:"internal",language:i,label:e}),vu=({id:i,language:e,label:t,codecs:r,isDefault:a})=>({id:i,language:e,label:t,codec:(0,Su.default)(r.split("."),0),isDefault:a}),yu=({id:i,language:e,label:t,hdr:r,codecs:a})=>({id:i,language:e,hdr:r,label:t,codec:(0,Su.default)(a.split("."),0)}),Tu=i=>"url"in i,Be=i=>i.type==="template",na=i=>i instanceof DOMException&&(i.name==="AbortError"||i.code===20);var oa=class{constructor(e,t,r,{fetcher:a,tuning:s,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new I.ValueSubject(0);this.currentSegmentLength$=new I.ValueSubject(0);this.onLastSegment$=new I.ValueSubject(!1);this.fullyBuffered$=new I.ValueSubject(!1);this.playingRepresentation$=new I.ValueSubject(void 0);this.playingRepresentationInit$=new I.ValueSubject(void 0);this.error$=new I.Subject;this.gaps=[];this.subscription=new I.Subscription;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new Oe;this.switchAbortController=new Oe;this.destroyAbortController=new Oe;this.bufferLimit=1/0;this.failedDownloads=0;this.baseUrls=[];this.baseUrlsIndex=0;this.isLive=!1;this.liveUpdateSegmentIndex=0;this.liveInitialAdditionalOffset=0;this.isSeekingLive=!1;this.index=0;this.lastDataObtainedTimestampMs=0;this.loadByteRangeSegmentsTimeoutId=0;this.startWith=(0,I.abortable)(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);(0,I.assertNonNullable)(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new ob(this.sourceBuffer),this.subscription.add((0,I.fromEvent)(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let o,u=this.mediaSource.readyState;u!=="open"&&(o={id:`SegmentEjection_source_${u}`,category:I.ErrorCategory.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o??={id:"SegmentEjection",category:I.ErrorCategory.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n},this.error$.next(o)})),this.subscription.add((0,I.fromEvent)(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:I.ErrorCategory.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o)return;let u=Math.min(this.bufferLimit,ou(this.sourceBuffer.buffered)*.8);this.bufferLimit=u;let l=lt(this.sourceBuffer.buffered,o),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(o,n*2,l<c)})),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);(0,I.assertNonNullable)(r,"No init buffer for starting representation"),(0,I.assertNonNullable)(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.switchToOld=(0,I.abortable)(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);(0,I.assertNonNullable)(r,`No such representation ${e}`);let a=this.segments.get(e),s=this.initData.get(e);if((0,I.isNullable)(s)||(0,I.isNullable)(a)?yield this.loadInit(r,"high",!1):s instanceof Promise&&(yield s),a=this.segments.get(e),(0,I.assertNonNullable)(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();(0,I.isNonNullable)(n)&&(this.isLive||(this.bufferLimit=1/0,await this.pruneBuffer(n,1/0,!0)),this.maintain(n)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}}.bind(this));this.seekLive=(0,I.abortable)(this.destroyAbortController.signal,async function*(e){let t=(0,Rs.default)(e,u=>u.representations)??[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let u of this.representations.keys()){let l=t.find(h=>h.id===u);l&&this.representations.set(u,l);let c=this.representations.get(u);if(!c||!Be(c.segmentReference))return;let d=this.getActualLiveStartingSegments(c.segmentReference);this.segments.set(c.id,d)}let r=this.switchingToRepresentationId??this.downloadingRepresentationId,a=this.representations.get(r);(0,I.assertNonNullable)(a);let s=this.segments.get(r);(0,I.assertNonNullable)(s,"No segments for starting representation");let n=this.initData.get(r);if((0,I.assertNonNullable)(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=u,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=o,this.isLive=!!l?.dynamic,this.baseUrls=l?.baseUrls??[],this.initData=new Map(r.map(c=>[c.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(r.map(c=>[c.id,c])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}switchTo(e,t=!1){return this.tuning.useNewSwitchTo?this.switchToNew(e,t):this.switchToOld(e,t)}switchToNew(e,t=!1){e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new Oe,(0,I.abortable)(this.switchAbortController.signal,async function*(r,a=!1){this.switchingToRepresentationId=r;let s=this.representations.get(r);(0,I.assertNonNullable)(s,`No such representation ${r}`);let n=this.segments.get(r),o=this.initData.get(r);if((0,I.isNullable)(o)||(0,I.isNullable)(n)?yield this.loadInit(s,"high",!1):o instanceof Promise&&(yield o),n=this.segments.get(r),(0,I.assertNonNullable)(n,"No segments for starting representation"),o=this.initData.get(r),!(!(o instanceof ArrayBuffer)||!this.sourceBuffer)){if(this.abort(),yield this.sourceBufferTaskQueue.append(o,this.downloadAbortController.signal),a)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=r,yield this.dropBuffer();else{let u=this.getCurrentPosition();(0,I.isNonNullable)(u)&&!this.isLive&&(this.bufferLimit=this.forwardBufferTarget,yield this.pruneBuffer(u,1/0,!0)),this.downloadingRepresentationId=r,this.switchingToRepresentationId=void 0}this.maintain()}}.bind(this))(e,t))}abort(){for(let e of this.activeSegments)this.abortSegment(e.segment);this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new Oe,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if((0,I.isNullable)(e)||(0,I.isNullable)(this.downloadingRepresentationId)||(0,I.isNullable)(this.playingRepresentationId)||(0,I.isNullable)(this.sourceBuffer)||(0,I.isNonNullable)(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),r=this.segments.get(this.downloadingRepresentationId);if((0,I.assertNonNullable)(t,`No such representation ${this.downloadingRepresentationId}`),!r)return;let a=r.find(l=>e>=l.time.from&&e<l.time.to);this.currentSegmentLength$.next((a?.time.to??0)-(a?.time.from??0));let s=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){let c=lt(this.sourceBuffer.buffered,e),d=a?a.time.to+100:-1/0;a&&a.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&c>=a.time.to-e+100&&(s=d)}if(isFinite(this.bufferLimit)&&ou(this.sourceBuffer.buffered)>=this.bufferLimit){let l=lt(this.sourceBuffer.buffered,e),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,l<c);return}let o=[];if(!this.activeSegments.size&&(o=this.selectForwardBufferSegments(r,t.segmentReference.type,s),o.length)){let l="auto";if(this.tuning.dash.useFetchPriorityHints&&a)if((0,ws.default)(o,a))l="high";else{let c=(0,Wr.default)(o,0);c&&c.time.from-a.time.to>=this.forwardBufferTarget/2&&(l="low")}this.loadSegments(o,t,l)}(!this.preloadOnly&&!this.allInitsLoaded&&a&&a.status==="fed"&&!o.length&&lt(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let u=(0,Wr.default)(r,-1);u&&u.status==="fed"&&(this.fullyBuffered$.next(!0),this.isLive||this.onLastSegment$.next(a===u))}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}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;(0,I.isNonNullable)(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=(0,Rs.default)(e?.streams[this.kind],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=(0,Rs.default)(e?.streams[this.kind],r=>r.representations)??[];for(let r of t){if(!r||!Be(r.segmentReference))return;let a=r.segmentReference.segments.map(u=>({...u,status:"none",size:void 0})),s=this.segments.get(r.id)??[],n=(0,Wr.default)(s,-1)?.time.to??0,o=a?.findIndex(u=>Math.floor(n)>=Math.floor(u.time.from)&&Math.floor(n)<=Math.floor(u.time.to));if(o===-1){this.liveUpdateSegmentIndex=0;let u=this.getActualLiveStartingSegments(r.segmentReference);this.segments.set(r.id,u)}else{let u=a.slice(o+1);this.segments.set(r.id,[...s,...u])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;(0,I.assertNonNullable)(e);let t=this.segments.get(e);if(t?.length){let r=t[t.length-1];this.updateLowLatencyLiveIfNeeded(r)}}updateLowLatencyLiveIfNeeded(e){for(let t of this.representations.values()){let r=t.segmentReference;if(!Be(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),u=kt(r.segmentTemplateUrl,{segmentTime:o});a.push({status:"none",time:{from:e.time.to,to:1/0},url:u})}}}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&&Oi&&Oi(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&Oi&&Oi(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.switchAbortController.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:d,time:{from:h,to:m}},b)=>{let g=h<=r&&m>=r,y=h>r||g||b===0&&r===0,T=Math.min(this.forwardBufferTarget,this.bufferLimit),$=this.preloadOnly&&h<=r+T||m<=r+T;return(d==="none"||d==="partially_ejected"&&y&&$&&this.sourceBuffer&&!(qt(this.sourceBuffer.buffered,h)&&qt(this.sourceBuffer.buffered,m)))&&y&&$});if(a===-1)return[];if(t!=="byteRange")return e.slice(a,a+1);let s=e,n=0,o=0,u=[],l=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,c=this.preloadOnly?this.forwardBufferTarget:0;for(let d=a;d<s.length&&(n<=l||o<=c);d++){let h=s[d];if(n+=h.byte.to+1-h.byte.from,o+=h.time.to+1-h.time.from,h.status==="none"||h.status==="partially_ejected")u.push(h);else break}return u}async loadSegments(e,t,r="auto"){Be(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:u,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(await(0,I.abortable)(o,async function*(){let c=(0,I.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(d=>setTimeout(d,c))}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let c=await this.fetcher.fetch(n,{range:s,signal:o,onProgress:u,priority:r,isLowLatency:this.isActiveLowLatency()});if(this.lastDataObtainedTimestampMs=(0,I.now)(),!c)return;let d=new DataView(c),h=sa(t.mime);if(!isFinite(a.segment.time.to)){let g=t.segmentReference.timescale;a.segment.time.to=h.getChunkEndTime(d,g)}u&&a.feedingBytes&&l?await Promise.all(l):await this.sourceBufferTaskQueue.append(d,o);let{serverDataReceivedTimestamp:m,serverDataPreparedTime:b}=h.getServerLatencyTimestamps(d);m&&b&&this.currentLiveSegmentServerLatency$.next(b-m),a.segment.status="downloaded",this.onSegmentFullyAppended(a,t.id),this.failedDownloads=0}catch(c){this.abortActiveSegments([e]),na(c)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}updateRepresentationsBaseUrlIfNeeded(){if(!this.tuning.dash.enableBaseUrlSupport||!this.baseUrls.length||this.failedDownloads<=this.tuning.dash.maxSegmentRetryCount)return;this.baseUrlsIndex=(this.baseUrlsIndex+1)%this.baseUrls.length;let e=this.baseUrls[this.baseUrlsIndex];for(let t of this.representations.values())Be(t.segmentReference)?t.segmentReference.baseUrl=e:t.segmentReference.url=e}async loadByteRangeSegments(e,t,r="auto"){if(!e.length)return;for(let u of e)u.status="downloading",this.activeSegments.add({segment:u,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:a,url:s,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(await(0,I.abortable)(n,async function*(){let u=(0,I.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),(0,I.fromEvent)(window,"online").pipe((0,I.once)()).subscribe(()=>{l(),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.lastDataObtainedTimestampMs=(0,I.now)(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),na(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}prepareByteRangeFetchSegmentParams(e,t){if(Be(t.segmentReference))throw new Error("Representation is not byte range type");let r=t.segmentReference.url,a={from:(0,Wr.default)(e,0).byte.from,to:(0,Wr.default)(e,-1).byte.to},{signal:s}=this.downloadAbortController;return{url:r,range:a,signal:s,onProgress:(o,u)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=(0,I.now)(),this.onSomeByteRangesDataLoaded({dataView:o,loaded:u,signal:s,onSegmentAppendFailed:()=>this.abort(),globalFrom:a?a.from:0,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:I.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!Be(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=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(l,c)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=(0,I.now)();let d=this.onSomeTemplateDataLoaded({dataView:l,loaded:c,signal:s,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(d)}catch(d){this.error$.next({id:"SegmentFeeding",category:I.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:d})}}:void 0;return{url:a,signal:s,onProgress:u,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)(0,ws.default)(e,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:u}=o;if(o.representationId===t){if(s.aborted){a();continue}if(o.loadedBytes=r,o.loadedBytes>o.feedingBytes){let l=new DataView(e.buffer,e.byteOffset+o.feedingBytes,o.loadedBytes-o.feedingBytes),c=sa(n.mime).parseFeedableSegmentChunk(l,this.isLive);c?.byteLength&&(u.status="partially_fed",o.feedingBytes+=c.byteLength,await this.sourceBufferTaskQueue.append(c),o.fedBytes+=c.byteLength)}}}}async onSomeByteRangesDataLoaded({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 u of this.activeSegments){let{segment:l}=u;if(u.representationId!==t)continue;if(s.aborted){n();continue}let c=l.byte.from-r,d=l.byte.to-r,h=d-c+1,m=c<a,b=d<=a;if(!m)continue;let g=sa(o.mime);if(l.status==="downloading"&&b){l.status="downloaded";let y=new DataView(e.buffer,e.byteOffset+c,h);await this.sourceBufferTaskQueue.append(y,s)&&!s.aborted?this.onSegmentFullyAppended(u,t):n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(l.status==="downloading"||l.status==="partially_fed")&&(u.loadedBytes=Math.min(h,a-c),u.loadedBytes>u.feedingBytes)){let y=new DataView(e.buffer,e.byteOffset+c+u.feedingBytes,u.loadedBytes-u.feedingBytes),T=u.loadedBytes===h?y:g.parseFeedableSegmentChunk(y);T?.byteLength&&(l.status="partially_fed",u.feedingBytes+=T.byteLength,await this.sourceBufferTaskQueue.append(T,s)&&!s.aborted?(u.fedBytes+=T.byteLength,u.fedBytes===h&&this.onSegmentFullyAppended(u,t)):n())}}}onSegmentFullyAppended(e,t){this.tuning.useSafariEndlessRequestBugfix&&!this.isLive&&((0,I.assertNonNullable)(this.sourceBuffer),qt(this.sourceBuffer.buffered,e.segment.time.from,100)&&qt(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"SafariEmptyAppendBuffer",category:I.ErrorCategory.VIDEO_PIPELINE,message:"Safari stuck on empty result of adding segment to source buffer"})),this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status="fed",Tu(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");(0,I.assertNonNullable)(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,cg.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?(0,I.abortable)(this.destroyAbortController.signal,async function*(){let o=(0,I.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,sa(e.mime),a)).then(async o=>{if(!o)return;let{init:u,dataView:l,segments:c}=o,d=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,d);let h=c;this.isLive&&Be(e.segmentReference)&&(h=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,h),u&&this.parsedInitData.set(e.id,u)}).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),r&&this.error$.next({id:"LoadInits",category:I.ErrorCategory.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n}async dropBuffer(){for(let e of this.segments.values())for(let t of e)t.status="none";await this.pruneBuffer(0,1/0,!0)}async pruneBuffer(e,t,r=!1){if(!this.sourceBuffer||!this.playingRepresentationId||(0,I.isNullable)(e)||this.sourceBuffer.updating)return!1;let a=[],s=0,n=u=>{u.sort((c,d)=>c.from-d.from);let l=[u[0]];for(let c=1;c<u.length;c++){let{from:d,to:h}=u[c],m=l[l.length-1];m.to>=d?m.to=Math.max(m.to,h):l.push(u[c])}return l},o=u=>{if(s>=t)return a;a.push({...u.time}),a=n(a);let l=Tu(u)?u.size??0:u.byte.to-u.byte.from;s+=l};for(let u of this.segments.values())for(let l of u){let c=l.time.to<=e-this.tuning.dash.bufferPruningSafeZone,d=l.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(c||d)&&l.status==="fed"&&o(l)}for(let u=0;u<this.sourceBuffer.buffered.length;u++){let l=this.sourceBuffer.buffered.start(u)*1e3,c=this.sourceBuffer.buffered.end(u)*1e3,d=0;for(let h of this.segments.values())for(let m of h)(0,ws.default)(["none","partially_ejected"],m.status)&&Math.round(m.time.from)<=Math.round(l)&&Math.round(m.time.to)>=Math.round(c)&&d++;if(d===this.segments.size){let h={time:{from:l,to:c},url:"",status:"none"};o(h)}}if(a.length&&r){let u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let l of this.segments.values())for(let c of l)c.time.from>=e+u&&c.status==="fed"&&o(c)}return a.length?(await Promise.all(a.map(l=>this.sourceBufferTaskQueue.remove(l.from,l.to)))).reduce((l,c)=>l||c,!1):!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)}}getForwardBufferDuration(){let e=this.getCurrentPosition();return!this.sourceBuffer||!this.sourceBuffer.buffered.length||(0,I.isNullable)(e)?0:lt(this.sourceBuffer.buffered,e)}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){(0,I.assertNonNullable)(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:I.ErrorCategory.WTF,message:"detectGaps threw",thrown:r})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if((0,I.isNullable)(this.sourceBuffer)||(0,I.isNullable)(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),u=e.some(c=>c.from-t<=n&&c.to+t>=o),l=e.filter(c=>n>=c.from&&n<c.to-t||o>c.from+t&&o<=c.to);u||(l.length===1?a.status="partially_ejected":this.gaps.some(c=>c.from===a.time.from||c.to===a.time.to)?a.status="partially_ejected":a.status="none")}}};var ua=i=>{let e=new URL(i);return e.searchParams.set("quic","1"),e.toString()};var dg=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}};var W=require("@vkontakte/videoplayer-shared");var pg=i=>{let e=new URL(i);return e.searchParams.set("enable-subtitles","yes"),e.toString()};var $s=class{constructor({throughputEstimator:e,requestQuic:t,tracer:r,compatibilityMode:a=!1,useEnableSubtitlesParam:s=!1}){this.lastConnectionType$=new W.ValueSubject(void 0);this.lastConnectionReused$=new W.ValueSubject(void 0);this.lastRequestFirstBytes$=new W.ValueSubject(void 0);this.abortAllController=new Oe;this.subscription=new W.Subscription;this.fetchManifest=(0,W.abortable)(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),r=e;this.requestQuic&&(r=ua(r)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(r=pg(r));let a=yield Et(r,{signal:this.abortAllController.signal}).catch(la);return a?(t.log("success",(0,W.flattenObject)({url:r,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(a.headers),a.text()):(t.error("error",(0,W.flattenObject)({url:r,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=(0,W.abortable)(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:u=!1}={}){let l=e,c=new Headers,d=this.tracer.createComponentTracer("Fetch");if(r)switch(t){case 0:{c.append("Range",`bytes=${r.from}-${r.to}`);break}case 1:{let D=new URL(l,location.href);D.searchParams.append("bytes",`${r.from}-${r.to}`),l=D.toString();break}default:(0,W.assertNever)(t)}this.requestQuic&&(l=ua(l));let h=this.abortAllController.signal,m;if(n){let D=new Oe;if(m=(0,W.merge)((0,W.fromEvent)(this.abortAllController.signal,"abort"),(0,W.fromEvent)(n,"abort")).subscribe(()=>{try{D.abort()}catch(L){la(L)}}),this.abortAllController.signal.aborted||n.aborted)try{D.abort()}catch(L){la(L)}h=D.signal}let b=(0,W.now)();d.log("startRequest",(0,W.flattenObject)({url:l,priority:s,rangeMethod:t,range:r,isLowLatency:u,requestStartedAt:b}));let g=yield Et(l,{priority:s,headers:c,signal:h}).catch(la),y=(0,W.now)();if(!g)return d.error("error",{message:"No response in request"}),d.end(),m?.unsubscribe(),null;if(this.throughputEstimator?.addRawRtt(y-b),!g.ok||!g.body){m?.unsubscribe();let D=`Fetch error ${g.status}: ${g.statusText}`;return d.error("error",{message:D}),d.end(),Promise.reject(new Error(`Fetch error ${g.status}: ${g.statusText}`))}if(this.onHeadersReceived(g.headers),!a&&!o){m?.unsubscribe();let D=(0,W.now)(),L={requestStartedAt:b,requestEndedAt:D,duration:D-b};return d.log("endRequest",(0,W.flattenObject)(L)),d.end(),g.arrayBuffer()}let[T,$]=g.body.tee(),P=T.getReader();o&&this.throughputEstimator?.trackStream($,u);let O=0,E=new Uint8Array(0),V=!1,ee=D=>{m?.unsubscribe(),V=!0,la(D)},z=(0,W.abortable)(h,async function*({done:D,value:L}){if(O===0&&this.lastRequestFirstBytes$.next((0,W.now)()-b),h.aborted){m?.unsubscribe();return}if(!D&&L){let re=new Uint8Array(E.length+L.length);re.set(E),re.set(L,E.length),E=re,O+=L.byteLength,a?.(new DataView(E.buffer),O),yield P?.read().then(z,ee)}}.bind(this));yield P?.read().then(z,ee),m?.unsubscribe();let Z=(0,W.now)(),A={failed:V,requestStartedAt:b,requestEndedAt:Z,duration:Z-b};return V?(d.error("endRequest",(0,W.flattenObject)(A)),d.end(),null):(d.log("endRequest",(0,W.flattenObject)(A)),d.end(),E.buffer)}.bind(this));this.fetchByteRangeRepresentation=(0,W.abortable)(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,u=!1,l,c;e.indexRange&&(l=e.indexRange.from,c=e.indexRange.to,u=s+1===l,u&&(n=Math.min(l,a),o=Math.max(c,s))),n=Math.min(n,0);let d=yield this.fetch(e.url,{range:{from:n,to:o},priority:r,measureThroughput:!1});if(!d)return null;let h=new DataView(d,a-n,s-n+1);if(!t.validateData(h))throw new Error("Invalid media file");let m=t.parseInit(h),b=e.indexRange??t.getIndexRange(m);if(!b)throw new ReferenceError("No way to load representation index");let g;if(u)g=new DataView(d,b.from-n,b.to-b.from+1);else{let T=yield this.fetch(e.url,{range:b,priority:r,measureThroughput:!1});if(!T)return null;g=new DataView(T)}let y=t.parseSegments(g,m,b);return{init:m,dataView:new DataView(d),segments:y}}.bind(this));this.fetchTemplateRepresentation=(0,W.abortable)(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"),this.useEnableSubtitlesParam=s}onHeadersReceived(e){let{type:t,reused:r}=dg(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:(0,W.assertNever)(a)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}},la=i=>{if(!na(i))throw i};var or=(i,e,t)=>t*e+(1-t)*i,Iu=(i,e)=>i.reduce((t,r)=>t+r,0)/e,hg=(i,e,t,r)=>{let a=0,s=t,n=Iu(i,e),o=e<r?e:r;for(let u=0;u<o;u++)i[s]>n?a++:a--,s=(i.length+s-1)%i.length;return Math.abs(a)===o};var ca=require("@vkontakte/videoplayer-shared"),Ht=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 ca.ValueSubject(e.initial),this.debounced$=new ca.ValueSubject(e.initial);let t=e.label??"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new ye(`raw_${t}`),this.smoothedSeries$=new ye(`smoothed_${t}`),this.reportedSeries$=new ye(`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)&&((0,ca.isNullable)(this.prevReported)||Math.abs(this.smoothed-this.prevReported)/this.prevReported>=this.params.changeThreshold)&&(this.prevReported=this.smoothed,this.debounced$.next(this.smoothed),this.reportedSeries$.next(this.smoothed))}};var Ls=class extends Ht{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=or(this.slow,e,this.params.emaAlphaSlow),this.fast=or(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var Ms=class extends Ht{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=Iu(this.pastMeasures,this.takenMeasures);this.emaSmoothed=or(this.emaSmoothed,e,this.params.emaAlpha);let r=hg(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=r?this.emaSmoothed:t}};var Cs=class extends Ht{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?or(this.smoothed,t,this.params.emaAlpha):t}};var ur=class{static getSmoothedValue(e,t,r){return r.type==="TwoEma"?new Ls({initial:e,emaAlphaSlow:r.emaAlphaSlow,emaAlphaFast:r.emaAlphaFast,changeThreshold:r.changeThreshold,fastDirection:t,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"}):new Ms({initial:e,emaAlpha:r.emaAlpha,basisTrendChangeCount:r.basisTrendChangeCount,changeThreshold:r.changeThreshold,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"})}static getLiveBufferSmoothedValue(e,t){return new Cs({initial:e,label:"liveEdgeDelay",...t})}};var Eu=(i,e)=>{i&&i.playbackRate!==e&&(i.playbackRate=e)};var Ds=require("@vkontakte/videoplayer-shared");var da=class i{constructor(e,t){this.currentRepresentation$=new Ds.ValueSubject(null);this.maxRepresentations=4;this.representationsCursor=0;this.representations=[];this.currentSegment=null;this.getCurrentPosition=t.getCurrentPosition,this.processStreams(e)}updateLive(e){this.processStreams(e?.streams.text)}seekLive(e){this.processStreams(e)}maintain(e=this.getCurrentPosition()){if(!(0,Ds.isNullable)(e))for(let t of this.representations)for(let r of t){let a=r.segmentReference,s=a.segments.length,n=a.segments[0].time.from,o=a.segments[s-1].time.to;if(e<n||e>o)continue;let u=a.segments.find(l=>l.time.from<=e&&l.time.to>=e);!u||this.currentSegment?.time.from===u.time.from&&this.currentSegment.time.to===u.time.to||(this.currentSegment=u,this.currentRepresentation$.next({...r,label:"Live Text",language:"ru",isAuto:!0,url:new URL(u.url,a.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[this.representationsCursor]=r,this.representationsCursor=(this.representationsCursor+1)%this.maxRepresentations;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&&Be(t.segmentReference))}};var pw=["timeupdate","progress","play","seeked","stalled","waiting"],hw=["timeupdate","progress","loadeddata","playing","seeked"];var Vs=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new S.Subscription;this.representationSubscription=new S.Subscription;this.state$=new U("none");this.currentVideoRepresentation$=new S.ValueSubject(void 0);this.currentVideoRepresentationInit$=new S.ValueSubject(void 0);this.currentAudioRepresentation$=new S.ValueSubject(void 0);this.currentVideoSegmentLength$=new S.ValueSubject(0);this.currentAudioSegmentLength$=new S.ValueSubject(0);this.error$=new S.Subject;this.lastConnectionType$=new S.ValueSubject(void 0);this.lastConnectionReused$=new S.ValueSubject(void 0);this.lastRequestFirstBytes$=new S.ValueSubject(void 0);this.currentLiveTextRepresentation$=new S.ValueSubject(null);this.isLive$=new S.ValueSubject(!1);this.liveDuration$=new S.ValueSubject(0);this.liveAvailabilityStartTime$=new S.ValueSubject(void 0);this.bufferLength$=new S.ValueSubject(0);this.liveLatency$=new S.ValueSubject(void 0);this.liveLoadBufferLength$=new S.ValueSubject(0);this.livePositionFromPlayer$=new S.ValueSubject(0);this.isLowLatency$=new S.ValueSubject(!1);this.isActiveLowLatency$=new S.ValueSubject(!1);this.currentStallDuration$=new S.ValueSubject(0);this.videoLastDataObtainedTimestamp$=new S.ValueSubject(0);this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.liveLastSeekOffset=0;this.forceEnded$=new S.Subject;this.gapWatchdogActive=!1;this.destroyController=new Oe;this.initManifest=(0,S.abortable)(this.destroyController.signal,async function*(e,t,r){this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=ge(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:S.ErrorCategory.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=(0,S.abortable)(this.destroyController.signal,async function*(){this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(n=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:S.ErrorCategory.NETWORK,message:"Failed to load manifest",thrown:n})});if(!e)return null;let t=null;try{t=ag(e??"",this.manifestUrlString)}catch(n){let o=ib(e)??{id:"ManifestParsing",category:S.ErrorCategory.PARSER,message:"Failed to parse MPD manifest",thrown:n};this.error$.next(o)}if(!t)return null;let r=(n,o,u)=>!!(this.element?.canPlayType?.(o)&&xt()?.isTypeSupported?.(`${o}; codecs="${u}"`)||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 u=t.streams[n].filter(({mime:d,codecs:h})=>r(n,d,h)),l=new Set(u.map(({codecs:d})=>d)),c=Vf(l);if(c&&(a[n]=u.filter(({codecs:d})=>d.startsWith(c))),n==="video"){let d=this.tuning.preferHDR,h=a.video.some(b=>b.hdr),m=a.video.some(b=>!b.hdr);S.clientChecker.isHDR&&d&&h?a.video=a.video.filter(b=>b.hdr):m&&(a.video=a.video.filter(b=>!b.hdr))}}let s={...t,streams:a};return this.tracer.log("updateManifestEnd",(0,S.flattenObject)(s)),s}.bind(this));this.initRepresentations=(0,S.abortable)(this.destroyController.signal,async function*(e,t,r){this.tracer.log("initRepresentationsStart",(0,S.flattenObject)({initialVideo:e,initialAudio:t,sourceHls:r})),(0,S.assertNonNullable)(this.manifest),(0,S.assertNonNullable)(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let a=h=>{this.representationSubscription.add((0,S.fromEvent)(h,"error").pipe((0,S.filter)(m=>!!this.element?.played.length)).subscribe(m=>{this.error$.next({id:"VideoSource",category:S.ErrorCategory.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:m})}))};this.source=this.tuning.useManagedMediaSource?wf():new MediaSource;let s=document.createElement("source");if(a(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),this.tuning.useManagedMediaSource&&xs())if(r){let h=document.createElement("source");a(h),h.type="application/x-mpegurl",h.src=r.url,this.element.appendChild(h)}else this.element.disableRemotePlayback=!0;this.isActiveLowLatency$.next(this.isLive$.getValue()&&this.isLowLatency$.getValue());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((h,m)=>[...h,...m.representations],[]);if(this.videoBufferManager=new oa("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],(0,S.isNonNullable)(t)){let h=this.manifest.streams.audio.reduce((m,b)=>[...m,...b.representations],[]);this.audioBufferManager=new oa("audio",this.source,h,n),this.bufferManagers.push(this.audioBufferManager)}da.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new da(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((0,S.interval)(1e3).subscribe(h=>{if(this.element?.paused){let m=hs(this.manifestUrlString,2);this.manifestUrlString=ge(this.manifestUrlString,m+1e3,2)}}));let u=()=>{this.stallWatchdogSubscription?.unsubscribe(),this.currentStallDuration$.next(0)};if(this.representationSubscription.add((0,S.merge)(...hw.map(h=>(0,S.fromEvent)(this.element,h))).pipe((0,S.map)(h=>this.element?lt(this.element.buffered,this.element.currentTime*1e3):0),(0,S.filterChanged)(),(0,S.tap)(h=>{h>this.tuning.dash.bufferEmptinessTolerance&&u()})).subscribe(this.bufferLength$)),this.representationSubscription.add((0,S.merge)((0,S.fromEvent)(this.element,"ended"),this.forceEnded$).subscribe(()=>{u()})),this.isLive$.getValue()){this.representationSubscription.add(this.isActiveLowLatency$.pipe((0,S.filterChanged)()).subscribe(m=>Eu(this.element,1))),this.representationSubscription.add((0,S.combine)({bufferLength:this.bufferLength$,isActiveLowLatency:this.isActiveLowLatency$}).pipe((0,S.filter)(({bufferLength:m,isActiveLowLatency:b})=>b&&!!m)).subscribe(({bufferLength:m})=>this.liveBuffer.next(m))),this.representationSubscription.add((0,S.combine)({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe((0,S.filter)(({isLive:m})=>m),(0,S.map)(m=>({...m})),(0,S.filterChanged)((m,b)=>b.bufferLength<m.bufferLength),(0,S.map)(({rtt:m,bufferLength:b,segmentServerLatency:g})=>{let y=hs(this.manifestUrlString,2);return(m/2+b+g+y)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add((0,S.combine)({liveBuffer:this.liveBuffer.smoothed$,isActiveLowLatency:this.isActiveLowLatency$}).subscribe(({liveBuffer:m,isActiveLowLatency:b})=>{if(!b)return;let g=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,y=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,T=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,$=m-g,P=1;Math.abs($)>y&&(P=1+Math.sign($)*T),Eu(this.element,P)})),this.representationSubscription.add(this.bufferLength$.subscribe(m=>{let b=0;if(m){let g=(this.element?.currentTime??0)*1e3;b=Math.min(...this.bufferManagers.map(T=>T.getLiveSegmentsToLoadState(this.manifest)?.to??g))-g}this.liveLoadBufferLength$.getValue()!==b&&this.liveLoadBufferLength$.next(b)}));let h=0;this.representationSubscription.add((0,S.combine)({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe((0,S.throttle)(1e3)).subscribe(async({liveLoadBufferLength:m,bufferLength:b})=>{if((0,S.assertNonNullable)(this.element),this.isUpdatingLive)return;let g=this.element.playbackRate,y=hs(this.manifestUrlString,2),T=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,$=Math.min(T,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*g),P=this.tuning.dashCmafLive.normalizedActualBufferOffset*g,O=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*g,E=isFinite(m)?m:b,V=this.isActiveLowLatency$.getValue(),ee=T<=this.tuning.live.activeLiveDelay&&y===0;this.isActiveLowLatency$.next(V&&ee);let z="none";if(V?z="active_low_latency":this.isLowLatency$.getValue()&&ee?(this.isActiveLowLatency$.next(!0),this.bufferManagers.forEach(Z=>Z.proceedLowLatencyLive()),z="active_low_latency"):y!==0&&E<$?z="live_forward_buffering":E<$+O&&(z="live_with_target_offset"),isFinite(m)&&(h=m>h?m:h),z==="live_forward_buffering"||z==="live_with_target_offset"){let Z=h-($+P),A=this.normolizeLiveOffset(Math.trunc(y+Z/g)),D=Math.abs(A-y),L;!m||D<=this.tuning.dashCmafLive.offsetCalculationError?L=y:A>0&&D>this.tuning.dashCmafLive.offsetCalculationError?L=A:L=0,this.manifestUrlString=ge(this.manifestUrlString,L,2)}z!=="none"&&z!=="active_low_latency"&&(h=0,this.updateLive())}))}let l=(0,S.merge)(...this.bufferManagers.map(h=>h.fullyBuffered$)).pipe((0,S.map)(()=>this.bufferManagers.every(h=>h.fullyBuffered$.getValue()))),c=(0,S.merge)(...this.bufferManagers.map(h=>h.onLastSegment$)).pipe((0,S.map)(()=>this.bufferManagers.some(h=>h.onLastSegment$.getValue())));this.representationSubscription.add((0,S.merge)(this.forceEnded$,(0,S.combine)({allBuffersFull:l,someBufferEnded:c}).pipe((0,S.filter)(({allBuffersFull:h,someBufferEnded:m})=>h&&m))).subscribe(()=>{if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(h=>!h.updating))try{this.source?.endOfStream()}catch(h){this.error$.next({id:"EndOfStream",category:S.ErrorCategory.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:h})}})),this.representationSubscription.add((0,S.merge)(...this.bufferManagers.map(h=>h.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.representationSubscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&(this.representationSubscription.add(this.audioBufferManager.playingRepresentation$.subscribe(this.currentAudioRepresentation$)),this.representationSubscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$))),this.liveTextManager&&this.representationSubscription.add(this.liveTextManager.currentRepresentation$.subscribe(this.currentLiveTextRepresentation$)),this.source.readyState!=="open"&&(yield new Promise(h=>this.source?.addEventListener("sourceopen",h)));let d=[this.manifest.duration??0,...(0,xu.default)((0,xu.default)([...this.manifest.streams.audio,...this.manifest.streams.video],h=>h.representations),h=>{let m=[];return h.duration&&m.push(h.duration),Be(h.segmentReference)&&h.segmentReference.totalSegmentsDurationMs&&m.push(h.segmentReference.totalSegmentsDurationMs),m})];this.source.duration=Math.max(...d)/1e3,this.audioBufferManager&&(0,S.isNonNullable)(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState("representations_ready"),this.tracer.log("initRepresentationsEnd")}.bind(this));this.tick=()=>{if(!this.element||!this.videoBufferManager)return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),this.audioBufferManager?.maintain(e),this.liveTextManager?.maintain(e),(this.videoBufferManager.gaps.length||this.audioBufferManager?.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=(0,S.interval)(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),t=>{this.error$.next({id:"GapWatchdog",category:S.ErrorCategory.WTF,message:"Error handling gaps",thrown:t})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name),this.fetcher=new $s({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer,useEnableSubtitlesParam:e.tuning.useEnableSubtitlesParam}),this.liveBuffer=ur.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.bufferEstimator}),this.initTracerSubscription()}async seekLive(e){(0,S.assertNonNullable)(this.element);let t=this.normolizeLiveOffset(e);this.isActiveLowLatency$.next(this.isLowLatency$.getValue()&&t===0),this.liveLastSeekOffset=t,this.manifestUrlString=ge(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(){(0,S.assertNonNullable)(this.element),this.state$.setState("running"),this.subscription.add((0,S.merge)(...pw.map(e=>(0,S.fromEvent)(this.element,e)),(0,S.fromEvent)(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:S.ErrorCategory.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add((0,S.fromEvent)(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add((0,S.fromEvent)(this.element,"waiting").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&qt(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{if(!this.element)return;let t=this.currentStallDuration$.getValue();t+=50,this.currentStallDuration$.next(t);let r={timeInWaiting:t},a=(0,S.now)(),s=100,n=this.videoBufferManager?.lastDataObtainedTimestamp??0;this.videoLastDataObtainedTimestamp$.next(n);let o=this.audioBufferManager?.lastDataObtainedTimestamp??0,u=this.videoBufferManager?.getForwardBufferDuration()??0,l=this.audioBufferManager?.getForwardBufferDuration()??0,c=u<s&&a-n>this.tuning.dash.crashOnStallTWithoutDataTimeout,d=this.audioBufferManager&&l<s&&a-o>this.tuning.dash.crashOnStallTWithoutDataTimeout;if((c||d)&&t>this.tuning.dash.crashOnStallTWithoutDataTimeout||t>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${t} ms`);if(this.isLive$.getValue()&&t%5e3===0)this.seekLive(this.liveLastSeekOffset),r.liveLastSeekOffset=this.liveLastSeekOffset;else{let h=this.element.currentTime*1e3;this.videoBufferManager?.maintain(h),this.audioBufferManager?.maintain(h),r.position=h}this.tracer.log("stallIntervalCallback",(0,S.flattenObject)(r))};this.stallWatchdogSubscription?.unsubscribe(),this.stallWatchdogSubscription=(0,S.interval)(50).subscribe(e,t=>{this.error$.next({id:"StallWatchdogCallback",category:S.ErrorCategory.NETWORK,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){(0,S.assertNonNullable)(this.element),(0,S.assertNonNullable)(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),qt(this.element.buffered,r)||(this.videoBufferManager.abort(),this.audioBufferManager?.abort()),this.videoBufferManager.maintain(r),this.audioBufferManager?.maintain(r),this.element.currentTime=r/1e3,this.tracer.log("seek",(0,S.flattenObject)({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=(0,S.getTraceSubscriptionMethod)(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",(0,S.flattenObject)(t)))}}};var Os=class{constructor(e,t){this.fov=e,this.orientation=t}};var Bs=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 fg=`attribute vec2 a_vertex;
69
+ `})|(?<privateuse2>${e}))$`.replace(/[\s\t\n]/g,"");return new RegExp(c,"i")}var Xb=i=>{if(!i.startsWith("P"))return;let e=(n,o)=>{let u=n?parseFloat(n.replace(",",".")):NaN;return(isNaN(u)?0:u)*o},r=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(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},At=(i,e)=>{let t=i;t=(0,hu.default)(t,"$$","$");let r={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[a,s]of(0,Zb.default)(r)){let n=new RegExp(`\\$${a}(?:%0(\\d+)d)?\\$`,"g");t=(0,hu.default)(t,n,(o,u)=>(0,jr.isNullable)(s)?o:(0,jr.isNullable)(u)?s:(0,eg.default)(s,parseInt(u,10),"0"))}return t},rg=(i,e)=>{let r=new DOMParser().parseFromString(i,"application/xml"),a={video:[],audio:[],text:[]},s=r.children[0],n=s.getElementsByTagName("Period")[0],o=Array.from(s.querySelectorAll("MPD > BaseURL").values()).map(x=>x.textContent?.trim()??""),u=(0,tg.default)(o,0)??"",l=n.children,c=s.getAttribute("type")==="dynamic",d=s.getAttribute("availabilityStartTime"),h=d?new Date(d).getTime():void 0,m,b=s.getAttribute("mediaPresentationDuration"),g=n.getAttribute("duration"),T=s.getElementsByTagName("vk:Attrs")[0]?.getElementsByTagName("vk:XPlaybackDuration")[0].textContent;if(b)m=Xb(b);else if(g){let x=Xb(g);(0,jr.isNonNullable)(x)&&(m=x)}else T&&(m=parseInt(T,10));let R=0,A=s.getAttribute("profiles")?.split(",")??[];for(let x of l){let N=x.getAttribute("id")??"id"+(R++).toString(10),z=x.getAttribute("mimeType")??"",Z=x.getAttribute("codecs")??"",K=x.getAttribute("contentType")??z?.split("/")[0],te=x.getAttribute("profiles")?.split(",")??[],E=Jb(x.getAttribute("lang")??"")??{},P=x.querySelector("Label")?.textContent?.trim()??void 0,ee=x.querySelectorAll("Representation"),$e=x.querySelector("SegmentTemplate"),Ge=x.querySelector("Role")?.getAttribute("value")??void 0,w=K,G={id:N,language:E.language,isDefault:Ge==="main",label:P,codecs:Z,hdr:w==="video"&&pu(Z),mime:z,representations:[]};for(let O of ee){let le=O.getAttribute("lang")??void 0,me=O.getAttribute("label")??void 0,$t=O.querySelector("BaseURL")?.textContent?.trim()??"",cr=new URL($t||u,e).toString(),Gt=O.getAttribute("mimeType")??z,Y=O.getAttribute("codecs")??Z??"",fe;if(K==="text"){let oe=O.getAttribute("id")||"",Ie=E.privateuse?.includes("x-auto")||oe.includes("_auto"),Le=O.querySelector("SegmentTemplate");if(Le){let ht={representationId:O.getAttribute("id")??void 0,bandwidth:O.getAttribute("bandwidth")??void 0},et=parseInt(O.getAttribute("bandwidth")??"",10)/1e3,mt=parseInt(Le.getAttribute("startNumber")??"",10)??1,tt=parseInt(Le.getAttribute("timescale")??"",10),dr=Le.querySelectorAll("SegmentTimeline S")??[],pr=Le.getAttribute("media");if(!pr)continue;let xa=[],Pa=0,ka="",hr=0,Yr=mt,ve=0;for(let Qe of dr){let Qt=parseInt(Qe.getAttribute("d")??"",10),Ne=parseInt(Qe.getAttribute("r")??"",10)||0,Lt=parseInt(Qe.getAttribute("t")??"",10);ve=Number.isFinite(Lt)?Lt:ve;let Wt=Qt/tt*1e3,mr=ve/tt*1e3;for(let rt=0;rt<Ne+1;rt++){let Mt=At(pr,{...ht,segmentNumber:Yr.toString(10),segmentTime:(ve+rt*Qt).toString(10)}),fr=(mr??0)+rt*Wt,Kr=fr+Wt;Yr++,xa.push({time:{from:fr,to:Kr},url:Mt})}ve+=(Ne+1)*Qt,Pa+=(Ne+1)*Wt}hr=ve/tt*1e3,ka=At(pr,{...ht,segmentNumber:Yr.toString(10),segmentTime:ve.toString(10)});let zr={time:{from:hr,to:1/0},url:ka},ft={type:"template",baseUrl:cr,segmentTemplateUrl:pr,initUrl:"",totalSegmentsDurationMs:Pa,segments:xa,nextSegmentBeyondManifest:zr,timescale:tt};fe={id:oe,kind:"text",segmentReference:ft,profiles:[],duration:m,bitrate:et,mime:"",codecs:"",width:0,height:0,isAuto:Ie}}else fe={id:oe,isAuto:Ie,kind:"text",url:cr}}else{let oe=O.getAttribute("contentType")??Gt?.split("/")[0]??K,Ie=x.getAttribute("profiles")?.split(",")??[],Le=parseInt(O.getAttribute("width")??"",10),ht=parseInt(O.getAttribute("height")??"",10),et=parseInt(O.getAttribute("bandwidth")??"",10)/1e3,mt=O.getAttribute("frameRate")??"",tt=O.getAttribute("quality")??void 0,dr=mt?Kb(mt):void 0,pr=O.getAttribute("id")??"id"+(R++).toString(10),xa=oe==="video"?`${ht}p`:oe==="audio"?`${et}Kbps`:Y,Pa=`${pr}@${xa}`,ka=[...A,...te,...Ie],hr,Yr=O.querySelector("SegmentBase"),ve=O.querySelector("SegmentTemplate")??$e;if(Yr){let ft=O.querySelector("SegmentBase Initialization")?.getAttribute("range")??"",[Qe,Qt]=ft.split("-").map(Mt=>parseInt(Mt,10)),Ne={from:Qe,to:Qt},Lt=O.querySelector("SegmentBase")?.getAttribute("indexRange"),[Wt,mr]=Lt?Lt.split("-").map(Mt=>parseInt(Mt,10)):[],rt=Lt?{from:Wt,to:mr}:void 0;hr={type:"byteRange",url:cr,initRange:Ne,indexRange:rt}}else if(ve){let ft={representationId:O.getAttribute("id")??void 0,bandwidth:O.getAttribute("bandwidth")??void 0},Qe=parseInt(ve.getAttribute("timescale")??"",10),Qt=ve.getAttribute("initialization")??"",Ne=ve.getAttribute("media"),Lt=parseInt(ve.getAttribute("startNumber")??"",10)??1,Wt=At(Qt,ft);if(!Ne)throw new ReferenceError("No media attribute in SegmentTemplate");let mr=ve.querySelectorAll("SegmentTimeline S")??[],rt=[],Mt=0,fr="",Kr=0;if(mr.length){let Aa=Lt,We=0;for(let br of mr){let it=parseInt(br.getAttribute("d")??"",10),Yt=parseInt(br.getAttribute("r")??"",10)||0,wa=parseInt(br.getAttribute("t")??"",10);We=Number.isFinite(wa)?wa:We;let qs=it/Qe*1e3,qg=We/Qe*1e3;for(let Ra=0;Ra<Yt+1;Ra++){let Ug=At(Ne,{...ft,segmentNumber:Aa.toString(10),segmentTime:(We+Ra*it).toString(10)}),Lu=(qg??0)+Ra*qs,Hg=Lu+qs;Aa++,rt.push({time:{from:Lu,to:Hg},url:Ug})}We+=(Yt+1)*it,Mt+=(Yt+1)*qs}Kr=We/Qe*1e3,fr=At(Ne,{...ft,segmentNumber:Aa.toString(10),segmentTime:We.toString(10)})}else if((0,jr.isNonNullable)(m)){let We=parseInt(ve.getAttribute("duration")??"",10)/Qe*1e3,br=Math.ceil(m/We),it=0;for(let Yt=1;Yt<br;Yt++){let wa=At(Ne,{...ft,segmentNumber:Yt.toString(10),segmentTime:it.toString(10)});rt.push({time:{from:it,to:it+We},url:wa}),it+=We}Kr=it,fr=At(Ne,{...ft,segmentNumber:br.toString(10),segmentTime:it.toString(10)})}let Fg={time:{from:Kr,to:1/0},url:fr};hr={type:"template",baseUrl:cr,segmentTemplateUrl:Ne,initUrl:Wt,totalSegmentsDurationMs:Mt,segments:rt,nextSegmentBeyondManifest:Fg,timescale:Qe}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!oe||!Gt)continue;let zr={video:"video",audio:"audio",text:"text"}[oe];if(!zr)continue;w||=zr,fe={id:Pa,kind:zr,segmentReference:hr,profiles:ka,duration:m,bitrate:et,mime:Gt,codecs:Y,width:Le,height:ht,fps:dr,quality:tt}}G.language||=le,G.label||=me,G.mime||=Gt,G.codecs||=Y,G.hdr||=w==="video"&&pu(Y),G.representations.push(fe)}w&&a[w].push(G)}return{dynamic:c,liveAvailabilityStartTime:h,duration:m,streams:a,baseUrls:o}};var bu=j(Br(),1);var ig=require("@vkontakte/videoplayer-shared"),ag=({id:i,width:e,height:t,bitrate:r,fps:a,quality:s,streamId:n})=>{let o=(s?_t(s):void 0)??(0,ig.videoSizeToQuality)({width:e,height:t});return o&&{id:i,quality:o,bitrate:r,size:{width:e,height:t},fps:a,streamId:n}},sg=({id:i,bitrate:e})=>({id:i,bitrate:e}),ng=({language:i,label:e},{id:t,url:r,isAuto:a})=>({id:t,url:r,isAuto:a,type:"internal",language:i,label:e}),og=({language:i,label:e,id:t,url:r,isAuto:a})=>({id:t,url:r,isAuto:a,type:"internal",language:i,label:e}),gu=({id:i,language:e,label:t,codecs:r,isDefault:a})=>({id:i,language:e,label:t,codec:(0,bu.default)(r.split("."),0),isDefault:a}),Su=({id:i,language:e,label:t,hdr:r,codecs:a})=>({id:i,language:e,hdr:r,label:t,codec:(0,bu.default)(a.split("."),0)}),vu=i=>"url"in i,_e=i=>i.type==="template",aa=i=>i instanceof DOMException&&(i.name==="AbortError"||i.code===20);var sa=class{constructor(e,t,r,{fetcher:a,tuning:s,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new I.ValueSubject(0);this.currentSegmentLength$=new I.ValueSubject(0);this.onLastSegment$=new I.ValueSubject(!1);this.fullyBuffered$=new I.ValueSubject(!1);this.playingRepresentation$=new I.ValueSubject(void 0);this.playingRepresentationInit$=new I.ValueSubject(void 0);this.error$=new I.Subject;this.gaps=[];this.subscription=new I.Subscription;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new Oe;this.switchAbortController=new Oe;this.destroyAbortController=new Oe;this.bufferLimit=1/0;this.failedDownloads=0;this.baseUrls=[];this.baseUrlsIndex=0;this.isLive=!1;this.liveUpdateSegmentIndex=0;this.liveInitialAdditionalOffset=0;this.isSeekingLive=!1;this.index=0;this.lastDataObtainedTimestampMs=0;this.loadByteRangeSegmentsTimeoutId=0;this.startWith=(0,I.abortable)(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);(0,I.assertNonNullable)(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new sb(this.sourceBuffer),this.subscription.add((0,I.fromEvent)(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let o,u=this.mediaSource.readyState;u!=="open"&&(o={id:`SegmentEjection_source_${u}`,category:I.ErrorCategory.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o??={id:"SegmentEjection",category:I.ErrorCategory.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n},this.error$.next(o)})),this.subscription.add((0,I.fromEvent)(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:I.ErrorCategory.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o)return;let u=Math.min(this.bufferLimit,su(this.sourceBuffer.buffered)*.8);this.bufferLimit=u;let l=ct(this.sourceBuffer.buffered,o),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(o,n*2,l<c)})),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);(0,I.assertNonNullable)(r,"No init buffer for starting representation"),(0,I.assertNonNullable)(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.switchToOld=(0,I.abortable)(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);(0,I.assertNonNullable)(r,`No such representation ${e}`);let a=this.segments.get(e),s=this.initData.get(e);if((0,I.isNullable)(s)||(0,I.isNullable)(a)?yield this.loadInit(r,"high",!1):s instanceof Promise&&(yield s),a=this.segments.get(e),(0,I.assertNonNullable)(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();(0,I.isNonNullable)(n)&&(this.isLive||(this.bufferLimit=1/0,await this.pruneBuffer(n,1/0,!0)),this.maintain(n)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}}.bind(this));this.seekLive=(0,I.abortable)(this.destroyAbortController.signal,async function*(e){let t=(0,As.default)(e,u=>u.representations)??[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let u of this.representations.keys()){let l=t.find(h=>h.id===u);l&&this.representations.set(u,l);let c=this.representations.get(u);if(!c||!_e(c.segmentReference))return;let d=this.getActualLiveStartingSegments(c.segmentReference);this.segments.set(c.id,d)}let r=this.switchingToRepresentationId??this.downloadingRepresentationId,a=this.representations.get(r);(0,I.assertNonNullable)(a);let s=this.segments.get(r);(0,I.assertNonNullable)(s,"No segments for starting representation");let n=this.initData.get(r);if((0,I.assertNonNullable)(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=u,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=o,this.isLive=!!l?.dynamic,this.baseUrls=l?.baseUrls??[],this.initData=new Map(r.map(c=>[c.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(r.map(c=>[c.id,c])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}switchTo(e,t=!1){return this.tuning.useNewSwitchTo?this.switchToNew(e,t):this.switchToOld(e,t)}switchToNew(e,t=!1){e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new Oe,(0,I.abortable)(this.switchAbortController.signal,async function*(r,a=!1){this.switchingToRepresentationId=r;let s=this.representations.get(r);(0,I.assertNonNullable)(s,`No such representation ${r}`);let n=this.segments.get(r),o=this.initData.get(r);if((0,I.isNullable)(o)||(0,I.isNullable)(n)?yield this.loadInit(s,"high",!1):o instanceof Promise&&(yield o),n=this.segments.get(r),(0,I.assertNonNullable)(n,"No segments for starting representation"),o=this.initData.get(r),!(!(o instanceof ArrayBuffer)||!this.sourceBuffer)){if(this.abort(),yield this.sourceBufferTaskQueue.append(o,this.downloadAbortController.signal),a)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=r,yield this.dropBuffer();else{let u=this.getCurrentPosition();(0,I.isNonNullable)(u)&&!this.isLive&&(this.bufferLimit=this.forwardBufferTarget,yield this.pruneBuffer(u,1/0,!0)),this.downloadingRepresentationId=r,this.switchingToRepresentationId=void 0}this.maintain()}}.bind(this))(e,t))}abort(){for(let e of this.activeSegments)this.abortSegment(e.segment);this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new Oe,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if((0,I.isNullable)(e)||(0,I.isNullable)(this.downloadingRepresentationId)||(0,I.isNullable)(this.playingRepresentationId)||(0,I.isNullable)(this.sourceBuffer)||(0,I.isNonNullable)(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),r=this.segments.get(this.downloadingRepresentationId);if((0,I.assertNonNullable)(t,`No such representation ${this.downloadingRepresentationId}`),!r)return;let a=r.find(l=>e>=l.time.from&&e<l.time.to);this.currentSegmentLength$.next((a?.time.to??0)-(a?.time.from??0));let s=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){let c=ct(this.sourceBuffer.buffered,e),d=a?a.time.to+100:-1/0;a&&a.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&c>=a.time.to-e+100&&(s=d)}if(isFinite(this.bufferLimit)&&su(this.sourceBuffer.buffered)>=this.bufferLimit){let l=ct(this.sourceBuffer.buffered,e),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,l<c);return}let o=[];if(!this.activeSegments.size&&(o=this.selectForwardBufferSegments(r,t.segmentReference.type,s),o.length)){let l="auto";if(this.tuning.dash.useFetchPriorityHints&&a)if((0,ks.default)(o,a))l="high";else{let c=(0,Gr.default)(o,0);c&&c.time.from-a.time.to>=this.forwardBufferTarget/2&&(l="low")}this.loadSegments(o,t,l)}(!this.preloadOnly&&!this.allInitsLoaded&&a&&a.status==="fed"&&!o.length&&ct(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let u=(0,Gr.default)(r,-1);u&&u.status==="fed"&&(this.fullyBuffered$.next(!0),this.isLive||this.onLastSegment$.next(a===u))}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}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;(0,I.isNonNullable)(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=(0,As.default)(e?.streams[this.kind],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=(0,As.default)(e?.streams[this.kind],r=>r.representations)??[];for(let r of t){if(!r||!_e(r.segmentReference))return;let a=r.segmentReference.segments.map(u=>({...u,status:"none",size:void 0})),s=this.segments.get(r.id)??[],n=(0,Gr.default)(s,-1)?.time.to??0,o=a?.findIndex(u=>Math.floor(n)>=Math.floor(u.time.from)&&Math.floor(n)<=Math.floor(u.time.to));if(o===-1){this.liveUpdateSegmentIndex=0;let u=this.getActualLiveStartingSegments(r.segmentReference);this.segments.set(r.id,u)}else{let u=a.slice(o+1);this.segments.set(r.id,[...s,...u])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;(0,I.assertNonNullable)(e);let t=this.segments.get(e);if(t?.length){let r=t[t.length-1];this.updateLowLatencyLiveIfNeeded(r)}}updateLowLatencyLiveIfNeeded(e){for(let t of this.representations.values()){let r=t.segmentReference;if(!_e(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),u=At(r.segmentTemplateUrl,{segmentTime:o});a.push({status:"none",time:{from:e.time.to,to:1/0},url:u})}}}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&&Di&&Di(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&Di&&Di(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.switchAbortController.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:d,time:{from:h,to:m}},b)=>{let g=h<=r&&m>=r,y=h>r||g||b===0&&r===0,T=Math.min(this.forwardBufferTarget,this.bufferLimit),R=this.preloadOnly&&h<=r+T||m<=r+T;return(d==="none"||d==="partially_ejected"&&y&&R&&this.sourceBuffer&&!(qt(this.sourceBuffer.buffered,h)&&qt(this.sourceBuffer.buffered,m)))&&y&&R});if(a===-1)return[];if(t!=="byteRange")return e.slice(a,a+1);let s=e,n=0,o=0,u=[],l=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,c=this.preloadOnly?this.forwardBufferTarget:0;for(let d=a;d<s.length&&(n<=l||o<=c);d++){let h=s[d];if(n+=h.byte.to+1-h.byte.from,o+=h.time.to+1-h.time.from,h.status==="none"||h.status==="partially_ejected")u.push(h);else break}return u}async loadSegments(e,t,r="auto"){_e(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:u,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(await(0,I.abortable)(o,async function*(){let c=(0,I.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(d=>setTimeout(d,c))}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let c=await this.fetcher.fetch(n,{range:s,signal:o,onProgress:u,priority:r,isLowLatency:this.isActiveLowLatency()});if(this.lastDataObtainedTimestampMs=(0,I.now)(),!c)return;let d=new DataView(c),h=ia(t.mime);if(!isFinite(a.segment.time.to)){let g=t.segmentReference.timescale;a.segment.time.to=h.getChunkEndTime(d,g)}u&&a.feedingBytes&&l?await Promise.all(l):await this.sourceBufferTaskQueue.append(d,o);let{serverDataReceivedTimestamp:m,serverDataPreparedTime:b}=h.getServerLatencyTimestamps(d);m&&b&&this.currentLiveSegmentServerLatency$.next(b-m),a.segment.status="downloaded",this.onSegmentFullyAppended(a,t.id),this.failedDownloads=0}catch(c){this.abortActiveSegments([e]),aa(c)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}updateRepresentationsBaseUrlIfNeeded(){if(!this.tuning.dash.enableBaseUrlSupport||!this.baseUrls.length||this.failedDownloads<=this.tuning.dash.maxSegmentRetryCount)return;this.baseUrlsIndex=(this.baseUrlsIndex+1)%this.baseUrls.length;let e=this.baseUrls[this.baseUrlsIndex];for(let t of this.representations.values())_e(t.segmentReference)?t.segmentReference.baseUrl=e:t.segmentReference.url=e}async loadByteRangeSegments(e,t,r="auto"){if(!e.length)return;for(let u of e)u.status="downloading",this.activeSegments.add({segment:u,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:a,url:s,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(await(0,I.abortable)(n,async function*(){let u=(0,I.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),(0,I.fromEvent)(window,"online").pipe((0,I.once)()).subscribe(()=>{l(),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.lastDataObtainedTimestampMs=(0,I.now)(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),aa(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}prepareByteRangeFetchSegmentParams(e,t){if(_e(t.segmentReference))throw new Error("Representation is not byte range type");let r=t.segmentReference.url,a={from:(0,Gr.default)(e,0).byte.from,to:(0,Gr.default)(e,-1).byte.to},{signal:s}=this.downloadAbortController;return{url:r,range:a,signal:s,onProgress:(o,u)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=(0,I.now)(),this.onSomeByteRangesDataLoaded({dataView:o,loaded:u,signal:s,onSegmentAppendFailed:()=>this.abort(),globalFrom:a?a.from:0,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:I.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!_e(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=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(l,c)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=(0,I.now)();let d=this.onSomeTemplateDataLoaded({dataView:l,loaded:c,signal:s,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(d)}catch(d){this.error$.next({id:"SegmentFeeding",category:I.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:d})}}:void 0;return{url:a,signal:s,onProgress:u,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)(0,ks.default)(e,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:u}=o;if(o.representationId===t){if(s.aborted){a();continue}if(o.loadedBytes=r,o.loadedBytes>o.feedingBytes){let l=new DataView(e.buffer,e.byteOffset+o.feedingBytes,o.loadedBytes-o.feedingBytes),c=ia(n.mime).parseFeedableSegmentChunk(l,this.isLive);c?.byteLength&&(u.status="partially_fed",o.feedingBytes+=c.byteLength,await this.sourceBufferTaskQueue.append(c),o.fedBytes+=c.byteLength)}}}}async onSomeByteRangesDataLoaded({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 u of this.activeSegments){let{segment:l}=u;if(u.representationId!==t)continue;if(s.aborted){n();continue}let c=l.byte.from-r,d=l.byte.to-r,h=d-c+1,m=c<a,b=d<=a;if(!m)continue;let g=ia(o.mime);if(l.status==="downloading"&&b){l.status="downloaded";let y=new DataView(e.buffer,e.byteOffset+c,h);await this.sourceBufferTaskQueue.append(y,s)&&!s.aborted?this.onSegmentFullyAppended(u,t):n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(l.status==="downloading"||l.status==="partially_fed")&&(u.loadedBytes=Math.min(h,a-c),u.loadedBytes>u.feedingBytes)){let y=new DataView(e.buffer,e.byteOffset+c+u.feedingBytes,u.loadedBytes-u.feedingBytes),T=u.loadedBytes===h?y:g.parseFeedableSegmentChunk(y);T?.byteLength&&(l.status="partially_fed",u.feedingBytes+=T.byteLength,await this.sourceBufferTaskQueue.append(T,s)&&!s.aborted?(u.fedBytes+=T.byteLength,u.fedBytes===h&&this.onSegmentFullyAppended(u,t)):n())}}}onSegmentFullyAppended(e,t){this.tuning.useSafariEndlessRequestBugfix&&!this.isLive&&((0,I.assertNonNullable)(this.sourceBuffer),qt(this.sourceBuffer.buffered,e.segment.time.from,100)&&qt(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"SafariEmptyAppendBuffer",category:I.ErrorCategory.VIDEO_PIPELINE,message:"Safari stuck on empty result of adding segment to source buffer"})),this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status="fed",vu(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");(0,I.assertNonNullable)(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=iu(()=>(0,ug.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?(0,I.abortable)(this.destroyAbortController.signal,async function*(){let o=(0,I.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,ia(e.mime),a)).then(async o=>{if(!o)return;let{init:u,dataView:l,segments:c}=o,d=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,d);let h=c;this.isLive&&_e(e.segmentReference)&&(h=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,h),u&&this.parsedInitData.set(e.id,u)}).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),r&&this.error$.next({id:"LoadInits",category:I.ErrorCategory.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n}async dropBuffer(){for(let e of this.segments.values())for(let t of e)t.status="none";await this.pruneBuffer(0,1/0,!0)}async pruneBuffer(e,t,r=!1){if(!this.sourceBuffer||!this.playingRepresentationId||(0,I.isNullable)(e)||this.sourceBuffer.updating)return!1;let a=[],s=0,n=u=>{u.sort((c,d)=>c.from-d.from);let l=[u[0]];for(let c=1;c<u.length;c++){let{from:d,to:h}=u[c],m=l[l.length-1];m.to>=d?m.to=Math.max(m.to,h):l.push(u[c])}return l},o=u=>{if(s>=t)return a;a.push({...u.time}),a=n(a);let l=vu(u)?u.size??0:u.byte.to-u.byte.from;s+=l};for(let u of this.segments.values())for(let l of u){let c=l.time.to<=e-this.tuning.dash.bufferPruningSafeZone,d=l.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(c||d)&&l.status==="fed"&&o(l)}for(let u=0;u<this.sourceBuffer.buffered.length;u++){let l=this.sourceBuffer.buffered.start(u)*1e3,c=this.sourceBuffer.buffered.end(u)*1e3,d=0;for(let h of this.segments.values())for(let m of h)(0,ks.default)(["none","partially_ejected"],m.status)&&Math.round(m.time.from)<=Math.round(l)&&Math.round(m.time.to)>=Math.round(c)&&d++;if(d===this.segments.size){let h={time:{from:l,to:c},url:"",status:"none"};o(h)}}if(a.length&&r){let u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let l of this.segments.values())for(let c of l)c.time.from>=e+u&&c.status==="fed"&&o(c)}return a.length?(await Promise.all(a.map(l=>this.sourceBufferTaskQueue.remove(l.from,l.to)))).reduce((l,c)=>l||c,!1):!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)}}getForwardBufferDuration(){let e=this.getCurrentPosition();return!this.sourceBuffer||!this.sourceBuffer.buffered.length||(0,I.isNullable)(e)?0:ct(this.sourceBuffer.buffered,e)}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){(0,I.assertNonNullable)(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=iu(()=>{try{this.detectGaps(e,t)}catch(r){this.error$.next({id:"GapDetection",category:I.ErrorCategory.WTF,message:"detectGaps threw",thrown:r})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if((0,I.isNullable)(this.sourceBuffer)||(0,I.isNullable)(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),u=e.some(c=>c.from-t<=n&&c.to+t>=o),l=e.filter(c=>n>=c.from&&n<c.to-t||o>c.from+t&&o<=c.to);u||(l.length===1?a.status="partially_ejected":this.gaps.some(c=>c.from===a.time.from||c.to===a.time.to)?a.status="partially_ejected":a.status="none")}}};var na=i=>{let e=new URL(i);return e.searchParams.set("quic","1"),e.toString()};var lg=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}};var Q=require("@vkontakte/videoplayer-shared");var cg=i=>{let e=new URL(i);return e.searchParams.set("enable-subtitles","yes"),e.toString()};var ws=class{constructor({throughputEstimator:e,requestQuic:t,tracer:r,compatibilityMode:a=!1,useEnableSubtitlesParam:s=!1}){this.lastConnectionType$=new Q.ValueSubject(void 0);this.lastConnectionReused$=new Q.ValueSubject(void 0);this.lastRequestFirstBytes$=new Q.ValueSubject(void 0);this.abortAllController=new Oe;this.subscription=new Q.Subscription;this.fetchManifest=(0,Q.abortable)(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),r=e;this.requestQuic&&(r=na(r)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(r=cg(r));let a=yield Et(r,{signal:this.abortAllController.signal}).catch(oa);return a?(t.log("success",(0,Q.flattenObject)({url:r,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(a.headers),a.text()):(t.error("error",(0,Q.flattenObject)({url:r,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=(0,Q.abortable)(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:u=!1}={}){let l=e,c=new Headers,d=this.tracer.createComponentTracer("Fetch");if(r)switch(t){case 0:{c.append("Range",`bytes=${r.from}-${r.to}`);break}case 1:{let E=new URL(l,location.href);E.searchParams.append("bytes",`${r.from}-${r.to}`),l=E.toString();break}default:(0,Q.assertNever)(t)}this.requestQuic&&(l=na(l));let h=this.abortAllController.signal,m;if(n){let E=new Oe;if(m=(0,Q.merge)((0,Q.fromEvent)(this.abortAllController.signal,"abort"),(0,Q.fromEvent)(n,"abort")).subscribe(()=>{try{E.abort()}catch(P){oa(P)}}),this.abortAllController.signal.aborted||n.aborted)try{E.abort()}catch(P){oa(P)}h=E.signal}let b=(0,Q.now)();d.log("startRequest",(0,Q.flattenObject)({url:l,priority:s,rangeMethod:t,range:r,isLowLatency:u,requestStartedAt:b}));let g=yield Et(l,{priority:s,headers:c,signal:h}).catch(oa),y=(0,Q.now)();if(!g)return d.error("error",{message:"No response in request"}),d.end(),m?.unsubscribe(),null;if(this.throughputEstimator?.addRawRtt(y-b),!g.ok||!g.body){m?.unsubscribe();let E=`Fetch error ${g.status}: ${g.statusText}`;return d.error("error",{message:E}),d.end(),Promise.reject(new Error(`Fetch error ${g.status}: ${g.statusText}`))}if(this.onHeadersReceived(g.headers),!a&&!o){m?.unsubscribe();let E=(0,Q.now)(),P={requestStartedAt:b,requestEndedAt:E,duration:E-b};return d.log("endRequest",(0,Q.flattenObject)(P)),d.end(),g.arrayBuffer()}let[T,R]=g.body.tee(),A=T.getReader();o&&this.throughputEstimator?.trackStream(R,u);let D=0,x=new Uint8Array(0),N=!1,z=E=>{m?.unsubscribe(),N=!0,oa(E)},Z=(0,Q.abortable)(h,async function*({done:E,value:P}){if(D===0&&this.lastRequestFirstBytes$.next((0,Q.now)()-b),h.aborted){m?.unsubscribe();return}if(!E&&P){let ee=new Uint8Array(x.length+P.length);ee.set(x),ee.set(P,x.length),x=ee,D+=P.byteLength,a?.(new DataView(x.buffer),D),yield A?.read().then(Z,z)}}.bind(this));yield A?.read().then(Z,z),m?.unsubscribe();let K=(0,Q.now)(),te={failed:N,requestStartedAt:b,requestEndedAt:K,duration:K-b};return N?(d.error("endRequest",(0,Q.flattenObject)(te)),d.end(),null):(d.log("endRequest",(0,Q.flattenObject)(te)),d.end(),x.buffer)}.bind(this));this.fetchByteRangeRepresentation=(0,Q.abortable)(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,u=!1,l,c;e.indexRange&&(l=e.indexRange.from,c=e.indexRange.to,u=s+1===l,u&&(n=Math.min(l,a),o=Math.max(c,s))),n=Math.min(n,0);let d=yield this.fetch(e.url,{range:{from:n,to:o},priority:r,measureThroughput:!1});if(!d)return null;let h=new DataView(d,a-n,s-n+1);if(!t.validateData(h))throw new Error("Invalid media file");let m=t.parseInit(h),b=e.indexRange??t.getIndexRange(m);if(!b)throw new ReferenceError("No way to load representation index");let g;if(u)g=new DataView(d,b.from-n,b.to-b.from+1);else{let T=yield this.fetch(e.url,{range:b,priority:r,measureThroughput:!1});if(!T)return null;g=new DataView(T)}let y=t.parseSegments(g,m,b);return{init:m,dataView:new DataView(d),segments:y}}.bind(this));this.fetchTemplateRepresentation=(0,Q.abortable)(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"),this.useEnableSubtitlesParam=s}onHeadersReceived(e){let{type:t,reused:r}=lg(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:(0,Q.assertNever)(a)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}},oa=i=>{if(!aa(i))throw i};var or=(i,e,t)=>t*e+(1-t)*i,yu=(i,e)=>i.reduce((t,r)=>t+r,0)/e,dg=(i,e,t,r)=>{let a=0,s=t,n=yu(i,e),o=e<r?e:r;for(let u=0;u<o;u++)i[s]>n?a++:a--,s=(i.length+s-1)%i.length;return Math.abs(a)===o};var ua=require("@vkontakte/videoplayer-shared"),Ht=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 ua.ValueSubject(e.initial),this.debounced$=new ua.ValueSubject(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)&&((0,ua.isNullable)(this.prevReported)||Math.abs(this.smoothed-this.prevReported)/this.prevReported>=this.params.changeThreshold)&&(this.prevReported=this.smoothed,this.debounced$.next(this.smoothed),this.reportedSeries$.next(this.smoothed))}};var Rs=class extends Ht{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=or(this.slow,e,this.params.emaAlphaSlow),this.fast=or(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var $s=class extends Ht{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=yu(this.pastMeasures,this.takenMeasures);this.emaSmoothed=or(this.emaSmoothed,e,this.params.emaAlpha);let r=dg(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=r?this.emaSmoothed:t}};var Ls=class extends Ht{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?or(this.smoothed,t,this.params.emaAlpha):t}};var ur=class{static getSmoothedValue(e,t,r){return r.type==="TwoEma"?new Rs({initial:e,emaAlphaSlow:r.emaAlphaSlow,emaAlphaFast:r.emaAlphaFast,changeThreshold:r.changeThreshold,fastDirection:t,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"}):new $s({initial:e,emaAlpha:r.emaAlpha,basisTrendChangeCount:r.basisTrendChangeCount,changeThreshold:r.changeThreshold,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"})}static getLiveBufferSmoothedValue(e,t){return new Ls({initial:e,label:"liveEdgeDelay",...t})}};var Tu=(i,e)=>{i&&i.playbackRate!==e&&(i.playbackRate=e)};var Ms=require("@vkontakte/videoplayer-shared");var la=class i{constructor(e,t){this.currentRepresentation$=new Ms.ValueSubject(null);this.maxRepresentations=4;this.representationsCursor=0;this.representations=[];this.currentSegment=null;this.getCurrentPosition=t.getCurrentPosition,this.processStreams(e)}updateLive(e){this.processStreams(e?.streams.text)}seekLive(e){this.processStreams(e)}maintain(e=this.getCurrentPosition()){if(!(0,Ms.isNullable)(e))for(let t of this.representations)for(let r of t){let a=r.segmentReference,s=a.segments.length,n=a.segments[0].time.from,o=a.segments[s-1].time.to;if(e<n||e>o)continue;let u=a.segments.find(l=>l.time.from<=e&&l.time.to>=e);!u||this.currentSegment?.time.from===u.time.from&&this.currentSegment.time.to===u.time.to||(this.currentSegment=u,this.currentRepresentation$.next({...r,label:"Live Text",language:"ru",isAuto:!0,url:new URL(u.url,a.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[this.representationsCursor]=r,this.representationsCursor=(this.representationsCursor+1)%this.maxRepresentations;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&&_e(t.segmentReference))}};var lw=["timeupdate","progress","play","seeked","stalled","waiting"],cw=["timeupdate","progress","loadeddata","playing","seeked"];var Cs=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new S.Subscription;this.representationSubscription=new S.Subscription;this.state$=new q("none");this.currentVideoRepresentation$=new S.ValueSubject(void 0);this.currentVideoRepresentationInit$=new S.ValueSubject(void 0);this.currentAudioRepresentation$=new S.ValueSubject(void 0);this.currentVideoSegmentLength$=new S.ValueSubject(0);this.currentAudioSegmentLength$=new S.ValueSubject(0);this.error$=new S.Subject;this.lastConnectionType$=new S.ValueSubject(void 0);this.lastConnectionReused$=new S.ValueSubject(void 0);this.lastRequestFirstBytes$=new S.ValueSubject(void 0);this.currentLiveTextRepresentation$=new S.ValueSubject(null);this.isLive$=new S.ValueSubject(!1);this.liveDuration$=new S.ValueSubject(0);this.liveAvailabilityStartTime$=new S.ValueSubject(void 0);this.bufferLength$=new S.ValueSubject(0);this.liveLatency$=new S.ValueSubject(void 0);this.liveLoadBufferLength$=new S.ValueSubject(0);this.livePositionFromPlayer$=new S.ValueSubject(0);this.isLowLatency$=new S.ValueSubject(!1);this.isActiveLowLatency$=new S.ValueSubject(!1);this.currentStallDuration$=new S.ValueSubject(0);this.videoLastDataObtainedTimestamp$=new S.ValueSubject(0);this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.liveLastSeekOffset=0;this.forceEnded$=new S.Subject;this.gapWatchdogActive=!1;this.destroyController=new Oe;this.initManifest=(0,S.abortable)(this.destroyController.signal,async function*(e,t,r){this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=Se(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:S.ErrorCategory.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=(0,S.abortable)(this.destroyController.signal,async function*(){this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(n=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:S.ErrorCategory.NETWORK,message:"Failed to load manifest",thrown:n})});if(!e)return null;let t=null;try{t=rg(e??"",this.manifestUrlString)}catch(n){let o=tb(e)??{id:"ManifestParsing",category:S.ErrorCategory.PARSER,message:"Failed to parse MPD manifest",thrown:n};this.error$.next(o)}if(!t)return null;let r=(n,o,u)=>!!(this.element?.canPlayType?.(o)&&xt()?.isTypeSupported?.(`${o}; codecs="${u}"`)||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 u=t.streams[n].filter(({mime:d,codecs:h})=>r(n,d,h)),l=new Set(u.map(({codecs:d})=>d)),c=Cf(l);if(c&&(a[n]=u.filter(({codecs:d})=>d.startsWith(c))),n==="video"){let d=this.tuning.preferHDR,h=a.video.some(b=>b.hdr),m=a.video.some(b=>!b.hdr);S.clientChecker.isHDR&&d&&h?a.video=a.video.filter(b=>b.hdr):m&&(a.video=a.video.filter(b=>!b.hdr))}}let s={...t,streams:a};return this.tracer.log("updateManifestEnd",(0,S.flattenObject)(s)),s}.bind(this));this.initRepresentations=(0,S.abortable)(this.destroyController.signal,async function*(e,t,r){this.tracer.log("initRepresentationsStart",(0,S.flattenObject)({initialVideo:e,initialAudio:t,sourceHls:r})),(0,S.assertNonNullable)(this.manifest),(0,S.assertNonNullable)(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let a=h=>{this.representationSubscription.add((0,S.fromEvent)(h,"error").pipe((0,S.filter)(m=>!!this.element?.played.length)).subscribe(m=>{this.error$.next({id:"VideoSource",category:S.ErrorCategory.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:m})}))};this.source=this.tuning.useManagedMediaSource?kf():new MediaSource;let s=document.createElement("source");if(a(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),this.tuning.useManagedMediaSource&&Is())if(r){let h=document.createElement("source");a(h),h.type="application/x-mpegurl",h.src=r.url,this.element.appendChild(h)}else this.element.disableRemotePlayback=!0;this.isActiveLowLatency$.next(this.isLive$.getValue()&&this.isLowLatency$.getValue());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((h,m)=>[...h,...m.representations],[]);if(this.videoBufferManager=new sa("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],(0,S.isNonNullable)(t)){let h=this.manifest.streams.audio.reduce((m,b)=>[...m,...b.representations],[]);this.audioBufferManager=new sa("audio",this.source,h,n),this.bufferManagers.push(this.audioBufferManager)}la.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new la(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((0,S.interval)(1e3).subscribe(h=>{if(this.element?.paused){let m=ps(this.manifestUrlString,2);this.manifestUrlString=Se(this.manifestUrlString,m+1e3,2)}}));let u=()=>{this.stallWatchdogSubscription?.unsubscribe(),this.currentStallDuration$.next(0)};if(this.representationSubscription.add((0,S.merge)(...cw.map(h=>(0,S.fromEvent)(this.element,h))).pipe((0,S.map)(h=>this.element?ct(this.element.buffered,this.element.currentTime*1e3):0),(0,S.filterChanged)(),(0,S.tap)(h=>{h>this.tuning.dash.bufferEmptinessTolerance&&u()})).subscribe(this.bufferLength$)),this.representationSubscription.add((0,S.merge)((0,S.fromEvent)(this.element,"ended"),this.forceEnded$).subscribe(()=>{u()})),this.isLive$.getValue()){this.representationSubscription.add(this.isActiveLowLatency$.pipe((0,S.filterChanged)()).subscribe(m=>Tu(this.element,1))),this.representationSubscription.add((0,S.combine)({bufferLength:this.bufferLength$,isActiveLowLatency:this.isActiveLowLatency$}).pipe((0,S.filter)(({bufferLength:m,isActiveLowLatency:b})=>b&&!!m)).subscribe(({bufferLength:m})=>this.liveBuffer.next(m))),this.representationSubscription.add((0,S.combine)({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe((0,S.filter)(({isLive:m})=>m),(0,S.map)(m=>({...m})),(0,S.filterChanged)((m,b)=>b.bufferLength<m.bufferLength),(0,S.map)(({rtt:m,bufferLength:b,segmentServerLatency:g})=>{let y=ps(this.manifestUrlString,2);return(m/2+b+g+y)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add((0,S.combine)({liveBuffer:this.liveBuffer.smoothed$,isActiveLowLatency:this.isActiveLowLatency$}).subscribe(({liveBuffer:m,isActiveLowLatency:b})=>{if(!b)return;let g=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,y=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,T=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,R=m-g,A=1;Math.abs(R)>y&&(A=1+Math.sign(R)*T),Tu(this.element,A)})),this.representationSubscription.add(this.bufferLength$.subscribe(m=>{let b=0;if(m){let g=(this.element?.currentTime??0)*1e3;b=Math.min(...this.bufferManagers.map(T=>T.getLiveSegmentsToLoadState(this.manifest)?.to??g))-g}this.liveLoadBufferLength$.getValue()!==b&&this.liveLoadBufferLength$.next(b)}));let h=0;this.representationSubscription.add((0,S.combine)({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe((0,S.throttle)(1e3)).subscribe(async({liveLoadBufferLength:m,bufferLength:b})=>{if((0,S.assertNonNullable)(this.element),this.isUpdatingLive)return;let g=this.element.playbackRate,y=ps(this.manifestUrlString,2),T=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,R=Math.min(T,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*g),A=this.tuning.dashCmafLive.normalizedActualBufferOffset*g,D=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*g,x=isFinite(m)?m:b,N=this.isActiveLowLatency$.getValue(),z=T<=this.tuning.live.activeLiveDelay&&y===0;this.isActiveLowLatency$.next(N&&z);let Z="none";if(N?Z="active_low_latency":this.isLowLatency$.getValue()&&z?(this.isActiveLowLatency$.next(!0),this.bufferManagers.forEach(K=>K.proceedLowLatencyLive()),Z="active_low_latency"):y!==0&&x<R?Z="live_forward_buffering":x<R+D&&(Z="live_with_target_offset"),isFinite(m)&&(h=m>h?m:h),Z==="live_forward_buffering"||Z==="live_with_target_offset"){let K=h-(R+A),te=this.normolizeLiveOffset(Math.trunc(y+K/g)),E=Math.abs(te-y),P;!m||E<=this.tuning.dashCmafLive.offsetCalculationError?P=y:te>0&&E>this.tuning.dashCmafLive.offsetCalculationError?P=te:P=0,this.manifestUrlString=Se(this.manifestUrlString,P,2)}Z!=="none"&&Z!=="active_low_latency"&&(h=0,this.updateLive())}))}let l=(0,S.merge)(...this.bufferManagers.map(h=>h.fullyBuffered$)).pipe((0,S.map)(()=>this.bufferManagers.every(h=>h.fullyBuffered$.getValue()))),c=(0,S.merge)(...this.bufferManagers.map(h=>h.onLastSegment$)).pipe((0,S.map)(()=>this.bufferManagers.some(h=>h.onLastSegment$.getValue())));this.representationSubscription.add((0,S.merge)(this.forceEnded$,(0,S.combine)({allBuffersFull:l,someBufferEnded:c}).pipe((0,S.filter)(({allBuffersFull:h,someBufferEnded:m})=>h&&m))).subscribe(()=>{if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(h=>!h.updating))try{this.source?.endOfStream()}catch(h){this.error$.next({id:"EndOfStream",category:S.ErrorCategory.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:h})}})),this.representationSubscription.add((0,S.merge)(...this.bufferManagers.map(h=>h.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.representationSubscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&(this.representationSubscription.add(this.audioBufferManager.playingRepresentation$.subscribe(this.currentAudioRepresentation$)),this.representationSubscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$))),this.liveTextManager&&this.representationSubscription.add(this.liveTextManager.currentRepresentation$.subscribe(this.currentLiveTextRepresentation$)),this.source.readyState!=="open"&&(yield new Promise(h=>this.source?.addEventListener("sourceopen",h)));let d=[this.manifest.duration??0,...(0,Iu.default)((0,Iu.default)([...this.manifest.streams.audio,...this.manifest.streams.video],h=>h.representations),h=>{let m=[];return h.duration&&m.push(h.duration),_e(h.segmentReference)&&h.segmentReference.totalSegmentsDurationMs&&m.push(h.segmentReference.totalSegmentsDurationMs),m})];this.source.duration=Math.max(...d)/1e3,this.audioBufferManager&&(0,S.isNonNullable)(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState("representations_ready"),this.tracer.log("initRepresentationsEnd")}.bind(this));this.tick=()=>{if(!this.element||!this.videoBufferManager)return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),this.audioBufferManager?.maintain(e),this.liveTextManager?.maintain(e),(this.videoBufferManager.gaps.length||this.audioBufferManager?.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=(0,S.interval)(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),t=>{this.error$.next({id:"GapWatchdog",category:S.ErrorCategory.WTF,message:"Error handling gaps",thrown:t})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name),this.fetcher=new ws({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer,useEnableSubtitlesParam:e.tuning.useEnableSubtitlesParam}),this.liveBuffer=ur.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.bufferEstimator}),this.initTracerSubscription()}async seekLive(e){(0,S.assertNonNullable)(this.element);let t=this.normolizeLiveOffset(e);this.isActiveLowLatency$.next(this.isLowLatency$.getValue()&&t===0),this.liveLastSeekOffset=t,this.manifestUrlString=Se(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(){(0,S.assertNonNullable)(this.element),this.state$.setState("running"),this.subscription.add((0,S.merge)(...lw.map(e=>(0,S.fromEvent)(this.element,e)),(0,S.fromEvent)(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:S.ErrorCategory.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add((0,S.fromEvent)(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add((0,S.fromEvent)(this.element,"waiting").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&qt(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{if(!this.element)return;let t=this.currentStallDuration$.getValue();t+=50,this.currentStallDuration$.next(t);let r={timeInWaiting:t},a=(0,S.now)(),s=100,n=this.videoBufferManager?.lastDataObtainedTimestamp??0;this.videoLastDataObtainedTimestamp$.next(n);let o=this.audioBufferManager?.lastDataObtainedTimestamp??0,u=this.videoBufferManager?.getForwardBufferDuration()??0,l=this.audioBufferManager?.getForwardBufferDuration()??0,c=u<s&&a-n>this.tuning.dash.crashOnStallTWithoutDataTimeout,d=this.audioBufferManager&&l<s&&a-o>this.tuning.dash.crashOnStallTWithoutDataTimeout;if((c||d)&&t>this.tuning.dash.crashOnStallTWithoutDataTimeout||t>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${t} ms`);if(this.isLive$.getValue()&&t%5e3===0)this.seekLive(this.liveLastSeekOffset),r.liveLastSeekOffset=this.liveLastSeekOffset;else{let h=this.element.currentTime*1e3;this.videoBufferManager?.maintain(h),this.audioBufferManager?.maintain(h),r.position=h}this.tracer.log("stallIntervalCallback",(0,S.flattenObject)(r))};this.stallWatchdogSubscription?.unsubscribe(),this.stallWatchdogSubscription=(0,S.interval)(50).subscribe(e,t=>{this.error$.next({id:"StallWatchdogCallback",category:S.ErrorCategory.NETWORK,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){(0,S.assertNonNullable)(this.element),(0,S.assertNonNullable)(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),qt(this.element.buffered,r)||(this.videoBufferManager.abort(),this.audioBufferManager?.abort()),this.videoBufferManager.maintain(r),this.audioBufferManager?.maintain(r),this.element.currentTime=r/1e3,this.tracer.log("seek",(0,S.flattenObject)({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=(0,S.getTraceSubscriptionMethod)(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",(0,S.flattenObject)(t)))}}};var Ds=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 hg=`attribute vec2 a_vertex;
70
70
  attribute vec2 a_texel;
71
71
 
72
72
  varying vec2 v_texel;
@@ -77,7 +77,7 @@ void main(void) {
77
77
  // save texel vector to pass to fragment shader
78
78
  v_texel = a_texel;
79
79
  }
80
- `;var bg=`#ifdef GL_ES
80
+ `;var mg=`#ifdef GL_ES
81
81
  precision highp float;
82
82
  precision highp int;
83
83
  #else
@@ -120,5 +120,5 @@ void main(void) {
120
120
  // sample using new coordinates
121
121
  gl_FragColor = texture2D(u_texture, tc);
122
122
  }
123
- `;var _s=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 Os(this.params.fov,this.params.orientation),this.cameraRotationManager=new Bs(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(fg,this.gl.VERTEX_SHADER),r=this.createShader(bg,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,u=t-a,l=e+r,c=t+a,d=e-r,h=t+a;return[s,n,o,u,l,c,d,h]}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 he=require("@vkontakte/videoplayer-shared"),Pu=class{constructor(){this.isSeeked$=new he.ValueSubject(!1);this.isBuffering$=new he.ValueSubject(!1);this.currentStallsCount=0;this.maxQualityLimit=void 0;this.lastUniqueVideoTrackSelectedTimestamp=0;this.predictedThroughputWithoutData=0;this.subscription=new he.Subscription}connect(e){this.currentStallDuration$=e.currentStallDuration$,this.videoLastDataObtainedTimestamp$=e.videoLastDataObtainedTimestamp$,this.throughput$=e.throughput$,this.rtt$=e.rtt$,this.qualityLimitsOnStall=e.qualityLimitsOnStall,this.subscription.add(e.isSeeked$.subscribe(this.isSeeked$)),this.subscription.add(e.isBuffering$.subscribe(this.isBuffering$)),this.subscription.add((0,he.combine)({isBuffering:this.isBuffering$,isSeeked:this.isSeeked$}).pipe((0,he.filter)(({isBuffering:t,isSeeked:r})=>t&&!r)).subscribe(()=>{this.currentStallsCount++})),this.subscription.add((0,he.combine)({currentStallDuration:this.currentStallDuration$,isSeeked:this.isSeeked$}).subscribe(({currentStallDuration:t,isSeeked:r})=>{if((0,he.isNullable)(this.lastUniqueVideoTrackSelected))return;let{stallDurationBeforeQualityDecrease:a,stallDurationNoDataBeforeQualityDecrease:s,stallCountBeforeQualityDecrease:n,resetQualityRestrictionTimeout:o}=this.qualityLimitsOnStall,u=this.rtt$.getValue(),l=this.throughput$.getValue(),c=this.videoLastDataObtainedTimestamp$.getValue(),d=(0,he.now)(),h=n&&this.currentStallsCount>=n,m=a&&!r&&d-this.lastUniqueVideoTrackSelectedTimestamp>=a+u&&t>=a,b=s&&d-this.lastUniqueVideoTrackSelectedTimestamp>=s+u&&d-c>=s+u&&t>=s;(h||m||b)&&(window.clearTimeout(this.qualityRestrictionTimer),this.maxQualityLimit=this.lastUniqueVideoTrackSelected.quality,(0,he.isNonNullable)(this.lastUniqueVideoTrackSelected.bitrate)&&l>this.lastUniqueVideoTrackSelected.bitrate&&(this.predictedThroughputWithoutData=this.lastUniqueVideoTrackSelected.bitrate)),t||(window.clearTimeout(this.qualityRestrictionTimer),this.qualityRestrictionTimer=window.setTimeout(()=>{this.maxQualityLimit=void 0,this.predictedThroughputWithoutData=0},o))}))}get videoMaxQualityLimit(){return this.maxQualityLimit}get predictedThroughput(){return this.predictedThroughputWithoutData}set lastVideoTrackSelected(e){this.lastUniqueVideoTrackSelected?.id!==e.id&&(this.lastUniqueVideoTrackSelected=e,this.lastUniqueVideoTrackSelectedTimestamp=(0,he.now)(),this.currentStallsCount=0)}destroy(){window.clearTimeout(this.qualityRestrictionTimer),this.subscription.unsubscribe()}},gg=Pu;var lr=class{constructor(e){this.subscription=new _.Subscription;this.videoState=new U("stopped");this.elementSize$=new _.ValueSubject(void 0);this.textTracksManager=new Fe;this.droppedFramesManager=new ys;this.stallsManager=new gg;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new Ai;this.audioTrackSwitchHistory=new Ai;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"),x(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"),x(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):r?.to==="ready"&&x(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"&&x(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"&&x(this.params.desiredState.playbackState,"paused");return;default:return(0,_.assertNever)(e)}}};this.init3DScene=e=>{if(this.scene3D)return;this.scene3D=new _s(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=Ie(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(de(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 Vs({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=Pe(this.video),a=this.constructor.name,s=o=>{e.error$.next({id:a,category:_.ErrorCategory.WTF,message:`${a} internal logic error`,thrown:o})};return{output:e,desiredState:t,observableVideo:r,genericErrorListener:s,connect:(o,u)=>this.subscription.add(o.subscribe(u,s))}}subscribe(){let{output:e,desiredState:t,observableVideo:r,genericErrorListener:a,connect:s}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe((0,_.filter)(c=>!!c.length),(0,_.once)()).subscribe(c=>{this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:r.playing$,pause$:r.pause$,tracks:c})}));let n=this.params.desiredState.seekState.stateChangeEnded$.pipe((0,_.map)(c=>c.to.state!=="none"),(0,_.filterChanged)());this.stallsManager.connect({isSeeked$:n,currentStallDuration$:this.player.currentStallDuration$.pipe((0,_.filterChanged)()),videoLastDataObtainedTimestamp$:this.player.videoLastDataObtainedTimestamp$,throughput$:this.params.dependencies.throughputEstimator.throughput$,rtt$:this.params.dependencies.throughputEstimator.rtt$,qualityLimitsOnStall:this.params.tuning.dash.qualityLimitsOnStall,isBuffering$:r.isBuffering$}),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((0,_.filter)(_.isNonNullable),(0,_.once)()),e.firstBytesEvent$),s(this.videoState.stateChangeEnded$.pipe((0,_.map)(c=>c.to)),this.params.output.playbackState$),this.subscription.add(r.seeked$.subscribe(e.seekedEvent$,a)),this.subscription.add(ot(this.video,t.isLooped,a)),this.subscription.add(xe(this.video,t.volume,r.volumeState$,a)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,a)),this.subscription.add(Ne(this.video,t.playbackRate,r.playbackRateState$,a)),s((0,_.observeElementSize)(this.video),this.elementSize$),s(qe(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),x(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},a)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),x(t.playbackState,"paused")},a)).add(r.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},a)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:c})=>{if(c==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let d=this.player.getStreams();if((0,_.assertNonNullable)(d,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let m=[];for(let b of d.audio){m.push(vu(b));let g=[];for(let y of b.representations){let T=og(y);g.push(T),this.audioTracksMap.set(T,{stream:b,representation:y})}this.audioStreamsMap.set(b,g)}this.params.output.availableAudioStreams$.next(m)}let h=[];for(let m of d.video){h.push(yu(m));let b=[];for(let g of m.representations){let y=ng({...g,streamId:m.id});y&&(b.push(y),this.videoTracksMap.set(y,{stream:m,representation:g}))}this.videoStreamsMap.set(m,b)}if(this.params.output.availableVideoStreams$.next(h),this.textTracksManager)for(let m of d.text)for(let b of m.representations){let g=ug(m,b);this.textTracksMap.set(g,{stream:m,representation:b})}this.params.output.availableVideoTracks$.next(Array.from(this.videoTracksMap.keys())),this.params.output.availableAudioTracks$.next(Array.from(this.audioTracksMap.keys())),this.params.output.isAudioAvailable$.next(!!this.audioTracksMap.size),this.audioTracksMap.size&&this.textTracksMap.size&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else c==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},a));let o=c=>e.error$.next({id:"RepresentationSwitch",category:_.ErrorCategory.WTF,message:"Switching representations threw",thrown:c});this.subscription.add((0,_.merge)(this.player.currentStallDuration$,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$,(0,_.fromEvent)(this.video,"progress")).subscribe(()=>{let c=this.player.state$.getState(),d=this.player.state$.getTransition();if(!(0,Sg.default)(["manifest_ready","running"],c)||d)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let h=this.selectVideoAudioRepresentations();if(!h)return;let[m,b]=h,g=[...this.videoTracksMap.keys()].find(T=>this.videoTracksMap.get(T)?.representation.id===m.id);(0,_.isNonNullable)(g)&&(this.stallsManager.lastVideoTrackSelected=g);let y=this.params.desiredState.autoVideoTrackLimits.getTransition();if(y&&this.params.output.autoVideoTrackLimits$.next(y.to),c==="manifest_ready")this.player.initRepresentations(m.id,b?.id,this.params.sourceHls);else if(this.player.switchRepresentation("video",m.id).catch(o),b){let T=!!t.audioStream.getTransition();this.player.switchRepresentation("audio",b.id,T).catch(o)}},a)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:c})=>{this.scene3D&&c&&this.scene3D.pointCameraTo(c.x,c.y)})),this.subscription.add(this.elementSize$.subscribe(c=>{this.scene3D&&c&&this.scene3D.setViewportSize(c.width,c.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe((0,_.filterChanged)()).subscribe(c=>{let d=[...this.videoTracksMap.entries()].find(([,{representation:g}])=>g.id===c);if(!d){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[h,{stream:m}]=d,b=this.params.desiredState.videoStream.getTransition();b&&b.to&&b.to.id===m.id&&this.params.desiredState.videoStream.setState(b.to),e.currentVideoTrack$.next(h),e.currentVideoStream$.next(yu(m))},a)),this.subscription.add(this.player.currentAudioRepresentation$.pipe((0,_.filterChanged)()).subscribe(c=>{let d=[...this.audioTracksMap.entries()].find(([,{representation:g}])=>g.id===c);if(!d){e.currentAudioStream$.next(void 0);return}let[h,{stream:m}]=d,b=this.params.desiredState.audioStream.getTransition();b&&b.to&&b.to.id===m.id&&this.params.desiredState.audioStream.setState(b.to),e.currentAudioStream$.next(vu(m))},a)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(c=>{if(c?.is3dVideo&&this.params.tuning.spherical?.enabled)try{this.init3DScene(c),e.is3DVideo$.next(!0)}catch(d){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${d}`})}else this.destroy3DScene(),this.params.tuning.spherical?.enabled&&e.is3DVideo$.next(!1)},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 u=t.playbackState.stateChangeStarted$.pipe((0,_.map)(({to:c})=>c==="ready"),(0,_.filterChanged)());this.subscription.add((0,_.merge)(u,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$).subscribe(()=>{let c=t.autoVideoTrackSwitching.getState(),h=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:c?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(h)})),this.subscription.add((0,_.merge)(u,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let l=(0,_.merge)(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,_.observableFrom)(["init"])).pipe((0,_.debounce)(0));this.subscription.add(l.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:V})=>V===a),o=t.currentVideoTrack$.getValue(),u=e.videoStream.getState()??(n&&this.videoTracksMap.get(n)?.stream)??this.videoStreamsMap.size===1?this.videoStreamsMap.keys().next().value:void 0;if(!u)return;let l=[...this.videoStreamsMap.keys()].find(({id:V})=>V===u.id),c=l&&this.videoStreamsMap.get(l);if(!c)return;let d=lt(this.video.buffered,this.video.currentTime*1e3),h=r?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,m=Math.min(d/Math.min(h,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),b=e.audioStream.getState()??(this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0),g=[...this.audioStreamsMap.keys()].find(({id:V})=>V===b?.id)??this.audioStreamsMap.keys().next().value,y=0;if(g){if(n&&!r){let V=Ss(n,c,this.audioStreamsMap.get(g)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);y=Math.max(y,V?.bitrate??-1/0)}if(o){let V=Ss(o,c,this.audioStreamsMap.get(g)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);y=Math.max(y,V?.bitrate??-1/0)}}let T=Ft(c,{container:this.elementSize$.getValue(),estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:y,forwardBufferHealth:m,current:o,visible:this.params.output.elementVisible$.getValue(),history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,stallsVideoMaxQualityLimit:this.stallsManager.videoMaxQualityLimit,stallsPredictedThroughput:this.stallsManager.predictedThroughput,abrLogger:this.params.dependencies.abrLogger}),$=r?T??n:n??T,P=g&&Km($,c,this.audioStreamsMap.get(g)??[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:m,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),O=this.videoTracksMap.get($)?.representation,E=P&&this.audioTracksMap.get(P)?.representation;if(O&&E)return[O,E];if(O&&!E&&this.audioTracksMap.size===0)return[O,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){Ae(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.liveOffset?.pause(),this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:_.ErrorCategory.DOM,thrown:e}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.stallsManager.destroy(),this.destroy3DScene(),this.textTracksManager?.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),Ee(this.video),this.tracer.end()}};var ha=class extends lr{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)}};var jt=require("@vkontakte/videoplayer-shared");var ma=class extends lr{constructor(e){super(e),this.liveOffset=new yt,this.textTracksManager=null}subscribe(){super.subscribe();let{output:e,observableVideo:t,desiredState:r,connect:a}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),a(t.timeUpdate$,e.liveBufferTime$),a(this.player.liveDuration$,e.duration$),a(this.player.liveLatency$,e.liveLatency$),this.subscription.add(r.isLowLatency.stateChangeEnded$.pipe((0,jt.map)(s=>s.to)).subscribe(this.player.isLowLatency$)).add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add((0,jt.combine)({interval:(0,jt.interval)(1e3),playbackRate:t.playbackRateState$}).subscribe(({playbackRate:s})=>{if(this.videoState.getState()==="playing"){let n=e.position$.getValue()+(s-1);n<=0&&e.position$.next(n),this.liveOffset?.resetTo(-n*1e3)}})).add((0,jt.combine)({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe((0,jt.map)(({liveBufferTime:s,liveAvailabilityStartTime:n})=>s&&n?s+n:void 0)).subscribe(e.liveTime$)).add(this.player.currentLiveTextRepresentation$.subscribe(s=>{if(s){let n=lg(s);this.params.output.availableTextTracks$.next([n])}}))}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 vg=G(ps(),1);var j=require("@vkontakte/videoplayer-shared"),Xe={};var Yr=(i,e)=>new j.Observable(t=>{let r=(a,s)=>t.next(s);return i.on(e,r),()=>i.off(e,r)}),fa=class{constructor(e){this.subscription=new j.Subscription;this.videoState=new U("initializing");this.textTracksManager=new Fe;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:(0,j.assertNever)(e)}break;case"ready":switch(e){case"stopped":this.prepare();break;case"ready":case"playing":case"paused":break;default:(0,j.assertNever)(e)}break;case"playing":switch(e){case"playing":break;case"stopped":this.prepare();break;case"ready":case"paused":this.playIfAllowed();break;default:(0,j.assertNever)(e)}break;case"paused":switch(e){case"paused":break;case"stopped":this.prepare();break;case"ready":this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused");break;case"playing":this.pause();break;default:(0,j.assertNever)(e)}break;default:(0,j.assertNever)(t)}};this.video=Ie(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(de(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),Ee(this.video)}loadHlsJs(){let e=!1,t=a=>{e||this.params.output.error$.next({id:a==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:j.ErrorCategory.NETWORK,message:"Failed to load Hls.js",thrown:a}),e=!0},r=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);(0,vg.default)(import("hls.js").then(a=>{e||(Xe.Hls=a.default,Xe.Events=a.default.Events,this.init())},t),()=>{window.clearTimeout(r),e=!0})}init(){(0,j.assertNonNullable)(Xe.Hls,"hls.js not loaded"),this.hls=new Xe.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState("stopped")}subscribe(){(0,j.assertNonNullable)(Xe.Events,"hls.js not loaded");let{desiredState:e,output:t}=this.params,r=l=>{t.error$.next({id:"HlsJsProvider",category:j.ErrorCategory.WTF,message:"HlsJsProvider internal logic error",thrown:l})},a=Pe(this.video),s=(l,c)=>this.subscription.add(l.subscribe(c,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(ot(this.video,e.isLooped,r)),this.subscription.add(xe(this.video,e.volume,a.volumeState$,r)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(Ne(this.video,e.playbackRate,a.playbackRateState$,r)),s(qe(this.video),t.elementVisible$),s(this.videoState.stateChangeEnded$.pipe((0,j.map)(l=>l.to)),this.params.output.playbackState$),this.subscription.add(Yr(this.hls,Xe.Events.ERROR).subscribe(l=>{l.fatal&&t.error$.next({id:["HlsJsFatal",l.type,l.details].join("_"),category:j.ErrorCategory.WTF,message:`HlsJs fatal ${l.type} ${l.details}, ${l.err?.message} ${l.reason}`,thrown:l.error})})),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState("playing"),x(e.playbackState,"playing")},r)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),x(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(Yr(this.hls,Xe.Events.MANIFEST_PARSED).pipe((0,j.map)(({levels:l})=>l.reduce((c,d)=>{let h=d.name||d.height.toString(10),{width:m,height:b}=d,g=_t(d.attrs.QUALITY??"")??(0,j.videoSizeToQuality)({width:m,height:b});if(!g)return c;let y=d.attrs["FRAME-RATE"]?parseFloat(d.attrs["FRAME-RATE"]):void 0,T={id:h.toString(),quality:g,bitrate:d.bitrate/1e3,size:{width:m,height:b},fps:y};return this.trackLevels.set(h,{track:T,level:d}),c.push(T),c},[]))),t.availableVideoTracks$),s(Yr(this.hls,Xe.Events.MANIFEST_PARSED),l=>{if(l.subtitleTracks.length>0){let c=[];for(let d of l.subtitleTracks){let h=d.name,m=d.attrs.URI||"",b=d.lang;c.push({id:h,url:m,language:b,type:"internal"})}e.internalTextTracks.startTransitionTo(c)}}),s(Yr(this.hls,Xe.Events.LEVEL_LOADING).pipe((0,j.map)(({url:l})=>de(l))),t.hostname$),s(Yr(this.hls,Xe.Events.FRAG_CHANGED),l=>{let{video:c,audio:d}=l.frag.elementaryStreams;t.currentVideoSegmentLength$.next(((c?.endPTS??0)-(c?.startPTS??0))*1e3),t.currentAudioSegmentLength$.next(((d?.endPTS??0)-(d?.startPTS??0))*1e3)}),this.subscription.add(Bt(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,l=>{this.hls.nextLevel=l?-1:this.hls.currentLevel,this.hls.loadLevel=l?-1:this.hls.loadLevel},{onError:r}));let n=l=>Array.from(this.trackLevels.values()).find(({level:c})=>c===l)?.track,o=Yr(this.hls,Xe.Events.LEVEL_SWITCHED).pipe((0,j.map)(({level:l})=>n(this.hls.levels[l])));o.pipe((0,j.filter)(j.isNonNullable)).subscribe(t.currentVideoTrack$,r),this.subscription.add(Bt(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel]),l=>{if((0,j.isNullable)(l))return;let c=this.trackLevels.get(l.id)?.level;if(!c)return;let d=this.hls.levels.indexOf(c),h=this.hls.currentLevel,m=this.hls.levels[h];!m||c.bitrate>m.bitrate?this.hls.nextLevel=d:(this.hls.loadLevel=d,this.hls.loadLevel=d)},{changed$:o,onError:r})),s(a.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);let u=(0,j.merge)(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,j.observableFrom)(["init"])).pipe((0,j.debounce)(0));this.subscription.add(u.subscribe(this.syncPlayback,r))}prepare(){this.videoState.startTransitionTo("ready"),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}async playIfAllowed(){this.videoState.startTransitionTo("playing"),await Ae(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:j.ErrorCategory.DOM,thrown:t}))||(this.videoState.setState("paused"),x(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"),x(this.params.desiredState.playbackState,"stopped",!0)}};var yg="X-Playback-Duration",Au=async i=>{let e=await Et(i),t=await e.text(),r=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t)?.[1];return r?parseInt(r,10):e.headers.has(yg)?parseInt(e.headers.get(yg),10):void 0};var H=require("@vkontakte/videoplayer-shared");var wu=G(zn(),1);var Ns=require("@vkontakte/videoplayer-shared");var Sw=i=>{let e=null;if(i.QUALITY&&(e=_t(i.QUALITY)),!e&&i.RESOLUTION){let[t,r]=i.RESOLUTION.split("x").map(a=>parseInt(a,10));e=(0,Ns.videoSizeToQuality)({width:t,height:r})}return e??null},vw=(i,e)=>{let t=i.split(`
124
- `),r=[],a=[];for(let s=0;s<t.length;s++){let n=t[s],o=n.match(/^#EXT-X-STREAM-INF:(.+)/),u=n.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!o&&!u)){if(o){let l=(0,wu.default)(o[1].split(",").map(y=>y.split("="))),c=l.QUALITY??`stream-${l.BANDWIDTH}`,d=Sw(l),h;l.BANDWIDTH&&(h=parseInt(l.BANDWIDTH,10)/1e3||void 0),!h&&l["AVERAGE-BANDWIDTH"]&&(h=parseInt(l["AVERAGE-BANDWIDTH"],10)/1e3||void 0);let m=l["FRAME-RATE"]?parseFloat(l["FRAME-RATE"]):void 0,b;if(l.RESOLUTION){let[y,T]=l.RESOLUTION.split("x").map($=>parseInt($,10));y&&T&&(b={width:y,height:T})}let g=new URL(t[++s],e).toString();d&&r.push({id:c,quality:d,url:g,bandwidth:h,size:b,fps:m})}if(u){let l=(0,wu.default)(u[1].split(",").map(m=>m.split("=")).map(([m,b])=>[m,b.replace(/^"|"$/g,"")])),c=l.URI?.replace(/playlist$/,"subtitles.vtt"),d=l.LANGUAGE,h=l.NAME;c&&d&&a.push({type:"internal",id:d,label:h,language:d,url:c,isAuto:!1})}}}if(!r.length)throw new Error("Empty manifest");return{qualityManifests:r,textTracks:a}},yw=i=>new Promise(e=>{setTimeout(()=>{e()},i)}),ku=0,Tg=async(i,e=i,t)=>{let a=await(await Et(i)).text();ku+=1;try{let{qualityManifests:s,textTracks:n}=vw(a,e);return{qualityManifests:s,textTracks:n}}catch{if(ku<=t.manifestRetryMaxCount)return await yw((0,Ns.getExponentialDelay)(ku-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),Tg(i,e,t)}return{qualityManifests:[],textTracks:[]}},Fs=Tg;var ba=class{constructor(e){this.subscription=new H.Subscription;this.videoState=new U("stopped");this.textTracksManager=new Fe;this.manifests$=new H.ValueSubject([]);this.liveOffset=new yt;this.manifestStartTime$=new H.ValueSubject(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"),x(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||n||o){let c=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(c),this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if(a?.to!=="paused"&&l.state==="requested"){this.videoState.startTransitionTo("ready"),this.seek(l.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(t){case"ready":r==="ready"?x(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),x(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"&&x(this.params.desiredState.playbackState,"playing");return;case"paused":if(r==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let c=this.liveOffset.getTotalOffset();c>=this.maxSeekBackTime$.getValue()&&(c=0,this.liveOffset.resetTo(c)),this.liveOffset.resume(),this.params.output.position$.next(-c/1e3),this.prepare()}else a?.to==="paused"&&(x(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return(0,H.assertNever)(t)}};this.params=e,this.video=Ie(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:H.VideoQuality.INVARIANT,url:this.params.source.url},Fs(ge(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:H.ErrorCategory.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),this.manifests$.next([this.masterManifest,...t])},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:H.ErrorCategory.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(de(this.params.source.url)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.maxSeekBackTime$=new H.ValueSubject(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(u=>u.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"HlsLiveProvider",category:H.ErrorCategory.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},a=Pe(this.video),s=(o,u)=>this.subscription.add(o.subscribe(u,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(xe(this.video,t.volume,a.volumeState$,r)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Ne(this.video,t.playbackRate,a.playbackRateState$,r)),s(qe(this.video),e.elementVisible$),this.textTracksManager.connect(this.video,t,e),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState("playing"),x(t.playbackState,"playing")},r)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),x(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((0,H.filterChanged)(),(0,H.map)(o=>-o/1e3)).subscribe(this.params.output.duration$,r)),this.subscription.add(a.loadedMetadata$.subscribe(()=>{let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&(0,H.isNonNullable)(l.to)){let d=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let h=this.manifests$.getValue().find(m=>m.id===d);h&&(this.params.output.currentVideoTrack$.next(h),this.params.output.hostname$.next(de(h.url)))}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o&&o.state==="requested"&&this.seek(o.position)},r)),this.subscription.add(a.loadedData$.subscribe(()=>{let o=this.video?.getStartDate?.()?.getTime();this.manifestStartTime$.next(o||void 0)},r)),this.subscription.add((0,H.combine)({startTime:this.manifestStartTime$.pipe((0,H.filter)(H.isNonNullable)),currentTime:a.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),r)),this.subscription.add(this.manifests$.pipe((0,H.map)(o=>o.map(({id:u,quality:l,size:c,bandwidth:d,fps:h})=>({id:u,quality:l,size:c,fps:h,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,r));let n=(0,H.merge)(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,(0,H.observableFrom)(["init"])).pipe((0,H.debounce)(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),Ee(this.video)}prepare(){let e=this.selectManifest();if((0,H.isNullable)(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:u}=t?.to??r??{};for(let[l,c]of[[o,"mq"],[u,"lq"]]){let d=String(parseFloat(l||""));c&&l&&a.searchParams.set(c,d)}}let s=this.params.format==="HLS_LIVE_CMAF"?2:0,n=ge(a.toString(),this.liveOffset.getTotalOffset(),s);this.video.setAttribute("src",n),this.video.load(),Au(n).then(o=>{if(!(0,H.isNullable)(o))this.maxSeekBackTime$.next(o);else{let u=this.params.source.maxSeekBackTime??this.maxSeekBackTime$.getValue();if((0,H.isNullable)(u)||!isFinite(u))try{Et(n).then(l=>l.text()).then(l=>{let c=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(l)?.[1];if(c){let d=new URL(c,n).toString();Au(d).then(h=>{(0,H.isNullable)(h)||this.maxSeekBackTime$.next(h)})}})}catch{}}})}playIfAllowed(){Ae(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),x(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:H.ErrorCategory.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()}};var Y=require("@vkontakte/videoplayer-shared");var ga=class{constructor(e){this.subscription=new Y.Subscription;this.videoState=new U("stopped");this.textTracksManager=new Fe;this.manifests$=new Y.ValueSubject([]);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"),x(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||n||o){let c=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(c);let{currentTime:d}=this.video;this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:d*1e3,forcePrecise:!0});return}switch(a?.to!=="paused"&&l.state==="requested"&&this.seek(l.position),t){case"ready":r==="ready"?x(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),x(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"&&x(this.params.desiredState.playbackState,"playing");return;case"paused":r==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):a?.to==="paused"&&x(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return(0,Y.assertNever)(t)}};this.params=e,this.video=Ie(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:Y.VideoQuality.INVARIANT,url:this.params.source.url},this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(de(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),Fs(ge(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:Y.ErrorCategory.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(u=>u.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"HlsProvider",category:Y.ErrorCategory.WTF,message:"HlsProvider internal logic error",thrown:o})},a=Pe(this.video),s=(o,u)=>this.subscription.add(o.subscribe(u));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((0,Y.map)(o=>o.to)),this.params.output.playbackState$),this.subscription.add(ot(this.video,t.isLooped,r)),this.subscription.add(xe(this.video,t.volume,a.volumeState$,r)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Ne(this.video,t.playbackRate,a.playbackRateState$,r)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState("playing"),x(t.playbackState,"playing")},r)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),x(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(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&(0,Y.isNonNullable)(l.to)){let m=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let b=this.manifests$.getValue().find(g=>g.id===m);b&&(this.params.output.currentVideoTrack$.next(b),this.params.output.hostname$.next(de(b.url)))}let d=this.params.desiredState.playbackRate.getState(),h=this.params.output.element$.getValue()?.playbackRate;if(d!==h){let m=this.params.output.element$.getValue();m&&(this.params.desiredState.playbackRate.setState(d),m.playbackRate=d)}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o.state==="requested"&&this.seek(o.position)},r))),this.subscription.add(this.manifests$.pipe((0,Y.map)(o=>o.map(({id:u,quality:l,size:c,bandwidth:d,fps:h})=>({id:u,quality:l,size:c,fps:h,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,r)),!Y.clientChecker.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add((0,Y.merge)((0,Y.fromEvent)(o,"addtrack"),(0,Y.fromEvent)(o,"removetrack"),(0,Y.fromEvent)(o,"change"),(0,Y.observableFrom)(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},r))}let n=(0,Y.merge)(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,(0,Y.observableFrom)(["init"])).pipe((0,Y.debounce)(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),Ee(this.video)}prepare(){let e=this.selectManifest();if((0,Y.isNullable)(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,u]of[[s,"mq"],[n,"lq"]]){let l=String(parseFloat(o||""));u&&o&&a.searchParams.set(u,l)}}this.video.setAttribute("src",a.toString()),this.video.load()}playIfAllowed(){Ae(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Y.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};var Ig=G(wr(),1),Sa=G(xi(),1);var X=require("@vkontakte/videoplayer-shared");var va=class{constructor(e){this.subscription=new X.Subscription;this.videoState=new U("stopped");this.trackUrls={};this.textTracksManager=new Fe;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"),x(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:u}=this.video;this.prepare(),o.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:u*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"?x(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),x(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"&&x(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):r?.to==="paused"&&x(this.params.desiredState.playbackState,"paused");return;default:return(0,X.assertNever)(e)}};this.params=e,this.video=Ie(e.container,e.tuning),this.params.output.element$.next(this.video),(0,Ig.default)(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((0,Sa.default)(this.trackUrls).map(({track:t})=>t)),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.desiredState.autoVideoTrackSwitching.setState(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.subscribe()}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"MpegProvider",category:X.ErrorCategory.WTF,message:"MpegProvider internal logic error",thrown:o})},a=Pe(this.video),s=(o,u)=>this.subscription.add(o.subscribe(u,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((0,X.map)(o=>o.to)),this.params.output.playbackState$),this.subscription.add(ot(this.video,t.isLooped,r)),this.subscription.add(xe(this.video,t.volume,a.volumeState$,r)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Ne(this.video,t.playbackRate,a.playbackRateState$,r)),s(qe(this.video),e.elementVisible$),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState("playing"),x(t.playbackState,"playing")},r)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),x(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&&(0,X.isNonNullable)(o.to)){this.params.desiredState.videoTrack.setState(o.to),this.params.output.currentVideoTrack$.next(this.trackUrls[o.to.id].track);let u=this.params.desiredState.playbackRate.getState(),l=this.params.output.element$.getValue()?.playbackRate;if(u!==l){let c=this.params.output.element$.getValue();c&&(this.params.desiredState.playbackRate.setState(u),c.playbackRate=u)}}this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.textTracksManager.connect(this.video,t,e);let n=(0,X.merge)(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,(0,X.observableFrom)(["init"])).pipe((0,X.debounce)(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),Ee(this.video)}prepare(){let e=this.params.desiredState.videoTrack.getState()?.id;(0,X.assertNonNullable)(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];(0,X.assertNonNullable)(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=ua(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(de(t))}playIfAllowed(){Ae(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:X.ErrorCategory.DOM,thrown:e}))}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=(0,Sa.default)(this.trackUrls).find(o=>!(0,X.isInvariantQuality)(o.track.quality)&&(0,X.isLowerOrEqual)(o.track.quality,e))?.track,s=this.params.desiredState.videoTrack.getState()?.id,n=this.trackUrls[s??"0"]?.track;if(a&&n&&(0,X.isHigherOrEqual)(n.quality,a.quality)&&(t=a),!t){let o=(0,Sa.default)(this.trackUrls).filter(l=>!(0,X.isInvariantQuality)(l.track.quality)&&(0,X.isHigher)(l.track.quality,e)),u=o.length;u&&(t=o[u-1].track)}t&&(r=t.quality)}else if(!e){let a=(0,Sa.default)(this.trackUrls).map(s=>s.track);t=Ft(a,{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},estimatedThroughput: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})}};var te=require("@vkontakte/videoplayer-shared");var xg=require("@vkontakte/videoplayer-shared"),Eg=["stun:videostun.mycdn.me:80"],Tw=1e3,Iw=3,Ru=()=>null,qs=class{constructor(e,t){this.ws=null;this.peerConnection=null;this.serverUrl="";this.streamKey="";this.stream=null;this.signalingType="JOIN";this.retryCount=0;this.externalStartCallback=Ru;this.externalStopCallback=Ru;this.externalErrorCallback=Ru;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:Eg}]};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:xg.ErrorCategory.WTF,message:e.message})}async onPeerConnectionStream(e){let t=e.streams[0];this.stream&&this.stream.id===t.id||(this.stream=t,this.externalStartCallback(this.stream))}onPeerConnectionIceCandidate(e){e.candidate&&this.send({type:this.signalingType,inviteType:"CANDIDATE",candidate:e.candidate})}onPeerConnectionIceConnectionStateChange(){if(this.peerConnection){let e=this.peerConnection.iceConnectionState;["failed","closed"].indexOf(e)>-1&&(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():(this.closeConnections(),this.scheduleRetry()))}}async createOffer(){let e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");let t=await this.peerConnection.createOffer(e),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),Tw)}normalizeOptions(e={}){let t={stunServerList:Eg,maxRetryNumber:Iw,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var ya=class{constructor(e){this.videoState=new U("stopped");this.maxSeekBackTime$=new te.ValueSubject(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"),x(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"),x(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"&&x(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):r?.to==="paused"&&x(this.params.desiredState.playbackState,"paused");return;default:return(0,te.assertNever)(e)}};this.subscription=new te.Subscription,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=Ie(e.container,e.tuning),this.liveStreamClient=new qs(this.params.source.url,{maxRetryNumber:this.params.tuning.webrtc.connectionRetryMaxNumber,errorChanel:this.params.output.error$}),this.liveStreamClient.onStart(this.onLiveStreamStart.bind(this)),this.liveStreamClient.onStop(this.onLiveStreamStop.bind(this)),this.liveStreamClient.onError(this.onLiveStreamError.bind(this)),this.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),Ee(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,r=n=>{e.error$.next({id:"WebRTCLiveProvider",category:te.ErrorCategory.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};(0,te.merge)(this.videoState.stateChangeStarted$.pipe((0,te.map)(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe((0,te.map)(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})});let a=Pe(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(qe(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(xe(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(0,te.assertNever)(n.to)}},r)).add((0,te.merge)(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,(0,te.observableFrom)(["init"])).pipe((0,te.debounce)(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(de(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:te.VideoQuality.INVARIANT}),this.video.srcObject=e,x(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:te.ErrorCategory.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){Ae(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:te.ErrorCategory.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var Ta=class{constructor(e){this.iterator=e[Symbol.iterator](),this.next()}next(){this.current=this.iterator.next()}getValue(){if(this.current.done)throw new Error("Iterable is completed");return this.current.value}isCompleted(){return!!this.current.done}};var v=require("@vkontakte/videoplayer-shared");var wt=require("@vkontakte/videoplayer-shared"),Pg=i=>new wt.Observable(e=>{let t=new wt.Subscription,r=i.desiredPlaybackState$.stateChangeStarted$.pipe((0,wt.map)(({from:l,to:c})=>`${l}-${c}`)),a=i.desiredPlaybackState$.stateChangeEnded$,s=i.providerChanged$.pipe((0,wt.map)(({type:l})=>l!==void 0)),n=new wt.Subject,o=0,u="unknown";return t.add(r.subscribe(l=>{o&&window.clearTimeout(o),u=l,o=window.setTimeout(()=>n.next(l),i.maxTransitionInterval)})),t.add(a.subscribe(()=>{window.clearTimeout(o),u="unknown",o=0})),t.add(s.subscribe(l=>{o&&(window.clearTimeout(o),o=0,l&&(o=window.setTimeout(()=>n.next(u),i.maxTransitionInterval)))})),t.add(n.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});var He=require("@vkontakte/videoplayer-shared");function Ag(){return new(window.AudioContext||window.webkitAudioContext)}var kg=require("@vkontakte/videoplayer-shared");var zr=class i{constructor(e,t,r,a){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=r;this.volumeMultiplier=a;this.destroyController=new Oe;this.subscriptions=new He.Subscription;this.audioContext=null;this.gainNode=null;this.mediaElementSource=null;this.subscriptions.add(this.provider$.pipe((0,He.filter)(s=>!!s.type),(0,He.once)()).subscribe(({type:s})=>this.subscribe(s)))}static{this.errorId="VolumeMultiplierManager"}subscribe(e){kg.clientChecker.isSafari&&e!=="MPEG"||this.subscriptions.add((0,He.combine)({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe((0,He.filter)(({playbackState:t,video:r,volume:{muted:a,volume:s}})=>t==="playing"&&!!r&&!a&&!!s),(0,He.once)()).subscribe(({video:t})=>{this.initAudioContextOnce(t).then(r=>{r||this.destroy()}).catch(r=>{this.handleError(r),this.destroy()})}))}static isSupported(){return"AudioContext"in window&&"GainNode"in window&&"MediaElementAudioSourceNode"in window}async initAudioContextOnce(e){let{volumeMultiplier:t}=this,r=Ag();this.audioContext=r;let a=r.createGain();if(this.gainNode=a,a.gain.value=t,a.connect(r.destination),r.state==="suspended"&&(await r.resume(),this.destroyController.signal.aborted))return!1;let s=r.createMediaElementSource(e);return this.mediaElementSource=s,s.connect(a),!0}cleanup(){this.mediaElementSource&&(this.mediaElementSource.disconnect(),this.mediaElementSource=null),this.gainNode&&(this.gainNode.disconnect(),this.gainNode=null),this.audioContext&&(this.audioContext.state!=="closed"&&this.audioContext.close(),this.audioContext=null)}destroy(){this.destroyController.abort(),this.subscriptions.unsubscribe(),this.cleanup()}handleError(e){this.volumeMultiplierError$.next({id:i.errorId,category:He.ErrorCategory.VIDEO_PIPELINE,message:e?.message??`${i.errorId} exception`,thrown:e})}};var Ew={chunkDuration:5e3,maxParallelRequests:5},Ia=class{constructor(e){this.current$=new v.ValueSubject({type:void 0});this.providerError$=new v.Subject;this.noAvailableProvidersError$=new v.Subject;this.volumeMultiplierError$=new v.Subject;this.providerOutput={position$:new v.ValueSubject(0),duration$:new v.ValueSubject(1/0),volume$:new v.ValueSubject({muted:!1,volume:1}),availableVideoStreams$:new v.ValueSubject([]),currentVideoStream$:new v.ValueSubject(void 0),availableVideoTracks$:new v.ValueSubject([]),currentVideoTrack$:new v.ValueSubject(void 0),availableAudioStreams$:new v.ValueSubject([]),currentAudioStream$:new v.ValueSubject(void 0),availableAudioTracks$:new v.ValueSubject([]),currentVideoSegmentLength$:new v.ValueSubject(0),currentAudioSegmentLength$:new v.ValueSubject(0),isAudioAvailable$:new v.ValueSubject(!0),autoVideoTrackLimitingAvailable$:new v.ValueSubject(!1),autoVideoTrackLimits$:new v.ValueSubject(void 0),currentBuffer$:new v.ValueSubject(void 0),isBuffering$:new v.ValueSubject(!0),error$:new v.Subject,warning$:new v.Subject,willSeekEvent$:new v.Subject,soundProhibitedEvent$:new v.Subject,seekedEvent$:new v.Subject,loopedEvent$:new v.Subject,endedEvent$:new v.Subject,firstBytesEvent$:new v.Subject,loadedMetadataEvent$:new v.Subject,firstFrameEvent$:new v.Subject,canplay$:new v.Subject,isLive$:new v.ValueSubject(void 0),isLowLatency$:new v.ValueSubject(!1),canChangePlaybackSpeed$:new v.ValueSubject(!0),liveTime$:new v.ValueSubject(void 0),liveBufferTime$:new v.ValueSubject(void 0),liveLatency$:new v.ValueSubject(void 0),availableTextTracks$:new v.ValueSubject([]),currentTextTrack$:new v.ValueSubject(void 0),hostname$:new v.ValueSubject(void 0),httpConnectionType$:new v.ValueSubject(void 0),httpConnectionReused$:new v.ValueSubject(void 0),inPiP$:new v.ValueSubject(!1),inFullscreen$:new v.ValueSubject(!1),element$:new v.ValueSubject(void 0),elementVisible$:new v.ValueSubject(!0),availableSources$:new v.ValueSubject(void 0),is3DVideo$:new v.ValueSubject(!1),playbackState$:new v.ValueSubject("")};this.subscription=new v.Subscription;this.volumeMultiplierManager=null;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer"),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name);let t=Mf([...Df(this.params.tuning),...Cf(this.params.tuning)],this.params.tuning).filter(l=>(0,v.isNonNullable)(e.sources[l])),{forceFormat:r,formatsToAvoid:a}=this.params.tuning,s=[];r?s=[r]:a.length?s=[...t.filter(l=>!(0,$u.default)(a,l)),...t.filter(l=>(0,$u.default)(a,l))]:s=t,this.log({message:`Selected formats: ${s.join(" > ")}`}),this.tracer.log("Selected formats",(0,v.flattenObject)(s)),this.screenFormatsIterator=new Ta(s);let n=[...eu(!0),...eu(!1)];this.chromecastFormatsIterator=new Ta(n.filter(l=>(0,v.isNonNullable)(e.sources[l]))),this.providerOutput.availableSources$.next(e.sources);let{volumeMultiplier:o=1,tuning:{useVolumeMultiplier:u}}=this.params;u&&o!==1&&zr.isSupported()&&(this.volumeMultiplierManager=new zr(this.providerOutput,this.current$,this.volumeMultiplierError$,o))}init(){this.subscription.add(this.initProviderErrorHandling()),this.subscription.add(this.params.dependencies.chromecastInitializer.connection$.subscribe(()=>{this.reinitProvider()}))}destroy(){this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe(),this.volumeMultiplierManager?.destroy(),this.volumeMultiplierManager=null,this.tracer.end()}initProvider(){let e=this.chooseDestination(),t=this.chooseFormat(e);if((0,v.isNullable)(t)){this.handleNoFormatsError(e);return}let r;try{r=this.createProvider(e,t)}catch(a){this.providerError$.next({id:"ProviderNotConstructed",category:v.ErrorCategory.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(0,v.assertNever)(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]),u=this.applyFailoverHost(t.HLS_ONDEMAND||t.HLS);return(0,v.assertNonNullable)(o),new ha({...n,source:o,sourceHls:u})}case"DASH_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return(0,v.assertNonNullable)(o),new ma({...n,source:o})}case"HLS":case"HLS_ONDEMAND":{let o=this.applyFailoverHost(t[e]);return(0,v.assertNonNullable)(o),Ur||!this.params.tuning.useHlsJs?new ga({...n,source:o}):new fa({...n,source:o})}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return(0,v.assertNonNullable)(o),new ba({...n,source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case"MPEG":{let o=this.applyFailoverHost(t[e]);return(0,v.assertNonNullable)(o),new va({...n,source:o})}case"DASH_LIVE":{let o=this.applyFailoverHost(t[e]);return(0,v.assertNonNullable)(o),new nf({...n,source:o,config:{...Ew,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case"WEB_RTC_LIVE":{let o=this.applyFailoverHost(t[e]);return(0,v.assertNonNullable)(o),new ya({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(0,v.assertNever)(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(0,v.assertNonNullable)(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(0,v.assertNever)(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return(0,v.assertNever)(e)}}handleNoFormatsError(e){switch(e){case"SCREEN":this.noAvailableProvidersError$.next(this.params.tuning.forceFormat),this.current$.next({type:void 0});return;case"CHROMECAST":this.params.dependencies.chromecastInitializer.disconnect();return;default:return(0,v.assertNever)(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,Rg.default)((0,wg.default)(e).map(([a,s])=>[a,r(s)]))}initProviderErrorHandling(){let e=new v.Subscription,t=!1,r=0;return e.add((0,v.merge)(this.providerOutput.error$.pipe((0,v.filter)(a=>!this.params.tuning.ignoreAudioRendererError||!a.message||!/AUDIO_RENDERER_ERROR/ig.test(a.message))),Pg({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe((0,v.map)(a=>({id:`ProviderHangup:${a}`,category:v.ErrorCategory.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((0,v.filter)(({to:s})=>s==="playing"),(0,v.once)()).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===v.ErrorCategory.NETWORK,u=a.category===v.ErrorCategory.FATAL,l=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),c=r<this.params.tuning.providerErrorLimit&&!u,d=l&&!u&&(o&&t||!c);n={...n,isNetworkError:o,isFatalError:u,haveFailoverHost:l,tryFailover:d,canReinitProvider:c},c?(r++,this.reinitProvider()):d?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):this.switchToNextProvider(s??"SCREEN")}this.tracer.error("providerError",(0,v.flattenObject)(n))})),e}};var F=require("@vkontakte/videoplayer-shared");var xw=5e3,$g="one_video_throughput",Lg="one_video_rtt",Ea=window.navigator.connection,Mg=()=>{let i=Ea?.downlink;if((0,F.isNonNullable)(i)&&i!==10)return i*1e3},Cg=()=>{let i=Ea?.rtt;if((0,F.isNonNullable)(i)&&i!==3e3)return i},Dg=(i,e,t)=>{let r=t*8,a=r/i;return r/(a+e)},Lu=class i{constructor(e){this.subscription=new F.Subscription;this.concurrentDownloads=new Set;this.tuningConfig=e;let t=i.load($g)||(e.useBrowserEstimation?Mg():void 0)||xw,r=i.load(Lg)??(e.useBrowserEstimation?Cg():void 0)??0;if(this.throughput$=new F.ValueSubject(t),this.rtt$=new F.ValueSubject(r),this.rttAdjustedThroughput$=new F.ValueSubject(Dg(t,r,e.rttPenaltyRequestSize)),this.throughput=ur.getSmoothedValue(t,-1,e),this.rtt=ur.getSmoothedValue(r,1,e),e.useBrowserEstimation){let a=()=>{let n=Mg();n&&this.throughput.next(n);let o=Cg();(0,F.isNonNullable)(o)&&this.rtt.next(o)};Ea&&"onchange"in Ea&&this.subscription.add((0,F.fromEvent)(Ea,"change").subscribe(a)),a()}this.subscription.add(this.throughput.smoothed$.subscribe(a=>{F.safeStorage.set($g,a.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(a=>{F.safeStorage.set(Lg,a.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add((0,F.combine)({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe((0,F.map)(({throughput:a,rtt:s})=>Dg(a,s,e.rttPenaltyRequestSize)),(0,F.filter)(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=(0,F.now)(),a=new F.Subscription;switch(this.subscription.add(a),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:a.add((0,F.fromEvent)(e,"progress").pipe((0,F.once)()).subscribe(s=>{t=s.loaded,r=(0,F.now)()}));break;case 1:case 0:a.add((0,F.fromEvent)(e,"loadstart").subscribe(()=>{t=0,r=(0,F.now)()}));break}a.add((0,F.fromEvent)(e,"loadend").subscribe(s=>{if(e.status===200){let n=s.loaded,o=(0,F.now)(),u=n-t,l=o-r;this.addRawSpeed(u,l,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=(0,F.now)(),n=0,o=(0,F.now)(),u=c=>{this.concurrentDownloads.delete(e),r.releaseLock(),e.cancel(`Throughput Estimator error: ${c}`).catch(()=>{})},l=async({done:c,value:d})=>{if(c)!t&&this.addRawSpeed(a,(0,F.now)()-s,1),this.concurrentDownloads.delete(e);else if(d){if(t){let h=(0,F.now)();if(h-o>this.tuningConfig.lowLatency.continuesByteSequenceInterval||h-s>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let b=o-s;b&&this.addRawSpeed(n,b,1,t),n=d.byteLength,s=(0,F.now)()}else n+=d.byteLength;o=(0,F.now)()}else a+=d.byteLength,n+=d.byteLength,n>=this.tuningConfig.streamMinSampleSize&&(0,F.now)()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,(0,F.now)()-o,this.concurrentDownloads.size),n=0,o=(0,F.now)());await r?.read().then(l,u)}};this.concurrentDownloads.add(e),r?.read().then(l,u)}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=F.safeStorage.get(e);if((0,F.isNonNullable)(t))return parseInt(t,10)??void 0}},Vg=Lu;var cr=require("@vkontakte/videoplayer-shared"),Og={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:2.8,bitrateAudioFactorAtEmptyBuffer:10,bitrateFactorAtFullBuffer:2,bitrateAudioFactorAtFullBuffer:7,minVideoAudioRatio:5,minAvailableThroughputAudioRatio:5,usePixelRatio:!0,pixelRatioMultiplier:void 0,pixelRatioLogBase:3,pixelRatioLogCoefficients:[1,0,1],limitByContainer:!0,containerSizeFactor:1.3,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldownIncreaseQuality:3e3,trackCooldownDecreaseQuality:3e3,backgroundVideoQualityLimit:cr.VideoQuality.Q_4320P,activeVideoAreaThreshold:.1,highQualityLimit:cr.VideoQuality.Q_720P,trafficSavingLimit:cr.VideoQuality.Q_480P},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:cr.VideoQuality.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,crashOnStallTWithoutDataTimeout:5e3,enableSubSegmentBufferFeeding:!0,bufferEmptinessTolerance:100,useFetchPriorityHints:!0,qualityLimitsOnStall:{stallDurationBeforeQualityDecrease:0,stallDurationNoDataBeforeQualityDecrease:0,stallCountBeforeQualityDecrease:0,resetQualityRestrictionTimeout:1e4},enableBaseUrlSupport:!0,maxSegmentRetryCount:5},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:250,playbackCatchupSpeedup:.05,isActiveOnDefault:!1,bufferEstimator:{emaAlpha:.45,changeThreshold:.05,deviationDepth:20,deviationFactor:.5,extremumInterval:5}}},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1,lowLatencyActiveLiveDelay:3e3,activeLiveDelay:5e3,maxPausedTime:5e3},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,forceFormat:void 0,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:"07A4434E",useWebmBigRequest:!1,webmCodec:"vp9",androidPreferredFormat:"dash",preferCMAF:!1,preferWebRTC:!1,preferMultiStream:!1,preferHDR:!1,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useHlsJs:!0,useNativeHLSTextTracks:!1,useManagedMediaSource:!0,useNewSwitchTo:!1,useSafariEndlessRequestBugfix:!0,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,manifestRetryInterval:300,manifestRetryMaxInterval:1e4,manifestRetryMaxCount:10,audioVideoSyncRate:20,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50},useVolumeMultiplier:!1,ignoreAudioRendererError:!1,useEnableSubtitlesParam:!1,useOldMSEDetection:!1,exposeInternalsToGlobal:!1},Bg=i=>({...(0,cr.fillWithDefault)(i,Og),configName:[...i.configName??[],...Og.configName]});var p=require("@vkontakte/videoplayer-shared");var Rt=require("@vkontakte/videoplayer-shared"),Mu=({seekState:i,position$:e})=>(0,Rt.merge)(i.stateChangeEnded$.pipe((0,Rt.map)(({to:t})=>t.state==="none"?void 0:(t.position??NaN)/1e3),(0,Rt.filter)(Rt.isNonNullable)),e.pipe((0,Rt.filter)(()=>i.getState().state==="none")));var _g=require("@vkontakte/videoplayer-shared"),Ng=i=>{let e=typeof i.container=="string"?document.getElementById(i.container):i.container;return(0,_g.assertNonNullable)(e,`Wrong container or containerId {${i.container}}`),e};var Us=require("@vkontakte/videoplayer-shared"),Fg=(i,e,t,r)=>{i!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&t?.getValue().length===0?t.pipe((0,Us.filter)(a=>a.length>0),(0,Us.once)()).subscribe(a=>{a.find(r)&&e.startTransitionTo(i)}):(i===void 0||t?.getValue().find(r))&&e.startTransitionTo(i)};var xa=class{constructor(e={configName:[]},t=p.Tracer.createRootTracer(!1)){this.subscription=new p.Subscription;this.logger=new p.Logger;this.abrLogger=this.logger.createComponentLog("ABR");this.internalsExposure=null;this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new p.ValueSubject(!1);this.hasLiveOffsetByPausedTimer=0;this.wasSetStartedQuality=!1;this.desiredState={playbackState:new U("stopped"),seekState:new U({state:"none"}),volume:new U({volume:1,muted:!1}),videoTrack:new U(void 0),videoStream:new U(void 0),audioStream:new U(void 0),autoVideoTrackSwitching:new U(!0),autoVideoTrackLimits:new U({}),isLooped:new U(!1),isLowLatency:new U(!1),playbackRate:new U(1),externalTextTracks:new U([]),internalTextTracks:new U([]),currentTextTrack:new U(void 0),textTrackCuesSettings:new U({}),cameraOrientation:new U({x:0,y:0})};this.info={playbackState$:new p.ValueSubject("stopped"),position$:new p.ValueSubject(0),duration$:new p.ValueSubject(1/0),muted$:new p.ValueSubject(!1),volume$:new p.ValueSubject(1),availableVideoStreams$:new p.ValueSubject([]),currentVideoStream$:new p.ValueSubject(void 0),availableQualities$:new p.ValueSubject([]),availableQualitiesFps$:new p.ValueSubject({}),currentQuality$:new p.ValueSubject(void 0),isAutoQualityEnabled$:new p.ValueSubject(!0),autoQualityLimitingAvailable$:new p.ValueSubject(!1),autoQualityLimits$:new p.ValueSubject({}),predefinedQualityLimitType$:new p.ValueSubject("unknown"),availableAudioStreams$:new p.ValueSubject([]),currentAudioStream$:new p.ValueSubject(void 0),availableAudioTracks$:new p.ValueSubject([]),isAudioAvailable$:new p.ValueSubject(!0),currentPlaybackRate$:new p.ValueSubject(1),currentBuffer$:new p.ValueSubject({start:0,end:0}),isBuffering$:new p.ValueSubject(!0),isStalled$:new p.ValueSubject(!1),isEnded$:new p.ValueSubject(!1),isLooped$:new p.ValueSubject(!1),isLive$:new p.ValueSubject(void 0),canChangePlaybackSpeed$:new p.ValueSubject(void 0),atLiveEdge$:new p.ValueSubject(void 0),atLiveDurationEdge$:new p.ValueSubject(void 0),liveTime$:new p.ValueSubject(void 0),liveBufferTime$:new p.ValueSubject(void 0),liveLatency$:new p.ValueSubject(void 0),currentFormat$:new p.ValueSubject(void 0),availableTextTracks$:new p.ValueSubject([]),currentTextTrack$:new p.ValueSubject(void 0),throughputEstimation$:new p.ValueSubject(void 0),rttEstimation$:new p.ValueSubject(void 0),videoBitrate$:new p.ValueSubject(void 0),hostname$:new p.ValueSubject(void 0),httpConnectionType$:new p.ValueSubject(void 0),httpConnectionReused$:new p.ValueSubject(void 0),surface$:new p.ValueSubject("none"),chromecastState$:new p.ValueSubject("NOT_AVAILABLE"),chromecastDeviceName$:new p.ValueSubject(void 0),intrinsicVideoSize$:new p.ValueSubject(void 0),availableSources$:new p.ValueSubject(void 0),is3DVideo$:new p.ValueSubject(!1),currentVideoSegmentLength$:new p.ValueSubject(0),currentAudioSegmentLength$:new p.ValueSubject(0)};this.events={inited$:new p.Subject,ready$:new p.Subject,started$:new p.Subject,playing$:new p.Subject,paused$:new p.Subject,stopped$:new p.Subject,willStart$:new p.Subject,willResume$:new p.Subject,willPause$:new p.Subject,willStop$:new p.Subject,willDestruct$:new p.Subject,watchCoverageRecord$:new p.Subject,watchCoverageLive$:new p.Subject,managedError$:new p.Subject,fatalError$:new p.Subject,ended$:new p.Subject,looped$:new p.Subject,seeked$:new p.Subject,willSeek$:new p.Subject,autoplaySoundProhibited$:new p.Subject,firstBytes$:new p.Subject,loadedMetadata$:new p.Subject,firstFrame$:new p.Subject,canplay$:new p.Subject,log$:new p.Subject};this.experimental={element$:new p.ValueSubject(void 0),tuningConfigName$:new p.ValueSubject([]),enableDebugTelemetry$:new p.ValueSubject(!1),dumpTelemetry:jm};if(this.initLogs(),this.tuning=Bg(e),this.tracer=t,this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new _a({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new Vg(this.tuning.throughputEstimator),e.exposeInternalsToGlobal&&(this.internalsExposure=new p.InternalsExposure("CORE"),this.internalsExposure.expose({player:this})),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(u){let l=o.map(h=>JSON.stringify(h,(m,b)=>{let g=typeof b;return(0,qg.default)(["number","string","boolean"],g)?b:b===null?null:`<${g}>`})),c=`Player.${String(a)}`,d=`Exception calling ${c} (${l.join(", ")})`;throw this.events.fatalError$.next({id:c,category:p.ErrorCategory.WTF,message:d,thrown:u}),u}}}})}initVideo(e){this.config=e;let{container:t,...r}=e;return this.tracer.log("initVideo",(0,p.flattenObject)(r)),this.domContainer=Ng(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.setLiveLowLatency(this.tuning.dashCmafLive.lowLatency.isActiveOnDefault),this.setMuted(this.tuning.isAudioDisabled),this.initDebugTelemetry(),this.initWakeLock(),this.internalsExposure?.expose({config:e,logger:this.logger,tuning:this.tuning}),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(),this.internalsExposure?.destroy()}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&&!$i()?(this.tracer.log("request play from hidden tab"),(0,p.fromEvent)(document,"visibilitychange").pipe((0,p.once)()).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){(0,p.assertNonNullable)(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.wasSetStartedQuality?this.providerContainer.providerOutput.availableVideoTracks$.pipe((0,p.filter)(r=>r.length>0),(0,p.once)()).subscribe(r=>{this.setVideoTrackIdByQuality(r,e)}):this.explicitInitialQuality=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",(0,p.flattenObject)(e)),this.desiredState.autoVideoTrackLimits.startTransitionTo(e),this}setPredefinedQualityLimits(e){let{highQualityLimit:t,trafficSavingLimit:r}=this.tuning.autoTrackSelection,a;switch(e){case"high_quality":a={min:t,max:void 0};break;case"traffic_saving":a={max:r,min:void 0};break;default:a={max:void 0,min:void 0}}return this.desiredState.autoVideoTrackLimits.startTransitionTo(a),this}setPlaybackRate(e){(0,p.assertNonNullable)(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",(0,p.flattenObject)(e)),this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>({type:"external",...t}))),this}selectTextTrack(e){return Fg(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}setLiveLowLatency(e){let t=this.info.isLive$.getValue(),r=this.desiredState.isLowLatency.getState();return!t||r===e?this:(this.tracer.log("live switch to low latency "+e),this.desiredState.isLowLatency.setState(e),this.seekTime(0))}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((0,p.isNullable)(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),r=t.state==="none"?void 0:t.position;return(0,p.isNonNullable)(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((0,p.merge)(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe((0,p.map)(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe((0,p.map)(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe((0,p.map)(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe((0,p.map)(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe((0,p.map)(e=>e.to)).subscribe(e=>{this.info.autoQualityLimits$.next(e);let{highQualityLimit:t,trafficSavingLimit:r}=this.tuning.autoTrackSelection;this.info.predefinedQualityLimitType$.next(bs({limits:e,highQualityLimit:t,trafficSavingLimit:r}))})),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe((0,p.filter)(({from:e})=>e==="stopped"),(0,p.once)()).subscribe(()=>{this.initedAt=(0,p.now)(),this.events.inited$.next()})).add(this.desiredState.playbackState.stateChangeEnded$.subscribe(e=>{switch(e.to){case"ready":this.events.ready$.next();break;case"playing":this.isPlaybackStarted||this.events.started$.next(),this.isPlaybackStarted=!0,this.events.playing$.next();break;case"paused":this.events.paused$.next();break;case"stopped":this.events.stopped$.next()}})).add(this.desiredState.playbackState.stateChangeStarted$.subscribe(e=>{switch(e.to){case"paused":this.events.willPause$.next();break;case"playing":this.isPlaybackStarted?this.events.willResume$.next():this.events.willStart$.next();break;case"stopped":this.events.willStop$.next();break;default:}}))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();this.tracer.log("willSeekEvent",(0,p.flattenObject)(n)),n.state==="requested"?this.desiredState.seekState.setState({...n,state:"applying"}):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:p.ErrorCategory.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.soundProhibitedEvent$.pipe((0,p.once)()).subscribe(this.events.autoplaySoundProhibited$)).add(e.providerOutput.seekedEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();this.tracer.log("seekedEvent",(0,p.flattenObject)(n)),n.state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe((0,p.map)(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe((0,p.map)(n=>n.destination),(0,p.filterChanged)()).subscribe(()=>this.isPlaybackStarted=!1)).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add((0,p.combine)({availableVideoTracks:e.providerOutput.availableVideoTracks$,currentVideoStream:e.providerOutput.currentVideoStream$}).pipe((0,p.map)(({availableVideoTracks:n,currentVideoStream:o})=>n.filter(u=>o?o.id===u.streamId:!0).map(({quality:u})=>u).sort((u,l)=>(0,p.isInvariantQuality)(u)?1:(0,p.isInvariantQuality)(l)?-1:(0,p.isHigher)(l,u)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(n=>{let o={};for(let u of n)u.fps&&(o[u.quality]=u.fps);this.info.availableQualitiesFps$.next(o)})).add(e.providerOutput.availableAudioStreams$.subscribe(this.info.availableAudioStreams$)).add(e.providerOutput.currentVideoStream$.subscribe(this.info.currentVideoStream$)).add(e.providerOutput.currentAudioStream$.subscribe(this.info.currentAudioStream$)).add(e.providerOutput.availableAudioTracks$.subscribe(this.info.availableAudioTracks$)).add(e.providerOutput.isAudioAvailable$.pipe((0,p.filterChanged)()).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((0,p.filterChanged)((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.pipe((0,p.filterChanged)((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe((0,p.filterChanged)()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe((0,p.filterChanged)()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe((0,p.filterChanged)()).subscribe(this.info.httpConnectionReused$)).add(e.providerOutput.currentTextTrack$.subscribe(this.info.currentTextTrack$)).add(e.providerOutput.availableTextTracks$.subscribe(this.info.availableTextTracks$)).add(e.providerOutput.autoVideoTrackLimitingAvailable$.subscribe(this.info.autoQualityLimitingAvailable$)).add(e.providerOutput.autoVideoTrackLimits$.subscribe(n=>{this.desiredState.autoVideoTrackLimits.setState(n??{})})).add(e.providerOutput.currentBuffer$.pipe((0,p.map)(n=>n?{start:n.from,end:n.to}:{start:0,end:0})).subscribe(this.info.currentBuffer$)).add(e.providerOutput.duration$.subscribe(this.info.duration$)).add(e.providerOutput.isBuffering$.subscribe(this.info.isBuffering$)).add(e.providerOutput.isLive$.subscribe(this.info.isLive$)).add(e.providerOutput.canChangePlaybackSpeed$.subscribe(this.info.canChangePlaybackSpeed$)).add(e.providerOutput.liveTime$.subscribe(this.info.liveTime$)).add(e.providerOutput.liveBufferTime$.subscribe(this.info.liveBufferTime$)).add(e.providerOutput.liveLatency$.subscribe(this.info.liveLatency$)).add((0,p.combine)({hasLiveOffsetByPaused:(0,p.merge)(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe((0,p.map)(n=>n.to),(0,p.filterChanged)(),(0,p.map)(n=>n==="paused")),isLowLatency:e.providerOutput.isLowLatency$}).subscribe(({hasLiveOffsetByPaused:n,isLowLatency:o})=>{if(window.clearTimeout(this.hasLiveOffsetByPausedTimer),n){this.hasLiveOffsetByPausedTimer=window.setTimeout(()=>{this.hasLiveOffsetByPaused.next(!0)},this.getActiveLiveDelay(o));return}this.hasLiveOffsetByPaused.next(!1)})).add((0,p.combine)({atLiveEdge:(0,p.combine)({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:Mu({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe((0,p.map)(({isLive:n,position:o,isLowLatency:u})=>{let l=this.getActiveLiveDelay(u);return n&&Math.abs(o)<l/1e3}),(0,p.filterChanged)(),(0,p.tap)(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe((0,p.map)(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add((0,p.combine)({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe((0,p.map)(({isLive:n,position:o,duration:u})=>n&&(Math.abs(u)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),(0,p.filterChanged)(),(0,p.tap)(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe((0,p.map)(n=>n.muted),(0,p.filterChanged)()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe((0,p.map)(n=>n.volume),(0,p.filterChanged)()).subscribe(this.info.volume$)).add(Mu({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add((0,p.merge)(e.providerOutput.endedEvent$.pipe((0,p.mapTo)(!0)),e.providerOutput.seekedEvent$.pipe((0,p.mapTo)(!1))).pipe((0,p.filterChanged)()).subscribe(this.info.isEnded$)).add(e.providerOutput.endedEvent$.subscribe(this.events.ended$)).add(e.providerOutput.loopedEvent$.subscribe(this.events.looped$)).add(e.providerError$.subscribe(this.events.managedError$)).add(e.volumeMultiplierError$.subscribe(this.events.managedError$)).add(e.noAvailableProvidersError$.pipe((0,p.map)(n=>({id:n?`No${n}`:"NoProviders",category:p.ErrorCategory.VIDEO_PIPELINE,message:n?`${n} was forced but failed or not available`:"No suitable providers or all providers failed"}))).subscribe(this.events.fatalError$)).add(e.providerOutput.element$.subscribe(this.experimental.element$)).add(e.providerOutput.firstBytesEvent$.pipe((0,p.once)(),(0,p.map)(n=>n??(0,p.now)()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe((0,p.once)(),(0,p.map)(()=>(0,p.now)()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe((0,p.once)(),(0,p.map)(()=>(0,p.now)()-this.initedAt)).subscribe(this.events.canplay$)).add(this.throughputEstimator.throughput$.subscribe(this.info.throughputEstimation$)).add(this.throughputEstimator.rtt$.subscribe(this.info.rttEstimation$)).add(e.providerOutput.availableSources$.subscribe(this.info.availableSources$));let t=new p.ValueSubject(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let r=new p.ValueSubject(!0);this.subscription.add(e.current$.subscribe(()=>r.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe((0,p.filter)(({to:n})=>n==="playing"),(0,p.once)()).subscribe(()=>r.next(!1)));let a=0,s=(0,p.merge)(e.providerOutput.isBuffering$,t,r).pipe((0,p.map)(()=>{let n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||r.getValue();return n&&!o}),(0,p.filterChanged)());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((0,p.merge)(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{let n=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:n?.videoWidth,height:n?.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{let o=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:n?.size?.width,height:n?.size?.height},{width:o?.videoWidth,height:o?.videoHeight})})).add(e.providerOutput.is3DVideo$.subscribe(this.info.is3DVideo$)),this.subscription.add((0,p.merge)(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,e.providerOutput.elementVisible$,this.chromecastInitializer.castState$).subscribe(()=>{let n=e.providerOutput.inPiP$.getValue(),o=e.providerOutput.inFullscreen$.getValue(),u=e.providerOutput.element$.getValue(),l=e.providerOutput.elementVisible$.getValue(),c=this.chromecastInitializer.castState$.getValue(),d;c==="CONNECTED"?d="second_screen":u?l?n?d="pip":o?d="fullscreen":d="inline":d="invisible":d="none",this.info.surface$.getValue()!==d&&this.info.surface$.next(d)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe((0,p.map)(e=>e?.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){let t=new p.Subscription;this.subscription.add(t),this.subscription.add(e.current$.pipe((0,p.filterChanged)((r,a)=>r.provider===a.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe((0,p.filter)(r=>r.length>0),(0,p.once)()).subscribe(r=>{this.setStartingVideoTrack(r)}))}))}setStartingVideoTrack(e){let t;this.wasSetStartedQuality=!0;let r=this.explicitInitialQuality??this.desiredState.videoTrack.getState()?.quality;r&&(t=e.find(({quality:a})=>a===r),t||this.setAutoQuality(!0)),t||(t=Ft(e,{container:this.domContainer.getBoundingClientRect(),estimatedThroughput:this.throughputEstimator.throughput$.getValue(),tuning:this.tuning.autoTrackSelection,limits:this.desiredState.autoVideoTrackLimits.getState(),playbackRate:this.info.currentPlaybackRate$.getValue(),forwardBufferHealth:0,abrLogger:this.abrLogger})),this.desiredState.videoTrack.startTransitionTo(t),this.info.currentQuality$.next(t.quality),this.info.videoBitrate$.next(t.bitrate)}initLogs(){this.subscription.add((0,p.merge)(this.desiredState.videoTrack.stateChangeStarted$.pipe((0,p.map)(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe((0,p.map)(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe((0,p.map)(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe((0,p.map)(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe((0,p.map)(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe((0,p.map)(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe((0,p.map)(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe((0,p.map)(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe((0,p.map)(e=>({component:"desiredState",message:`[${e.entity} change] ${e.type}: ${JSON.stringify(e.transition)}`}))).subscribe(this.logger.log)),this.subscription.add(this.logger.log$.subscribe(this.events.log$))}initDebugTelemetry(){let e=this.providerContainer?.providerOutput;(0,p.assertNonNullable)(this.providerContainer),(0,p.assertNonNullable)(e),Hm(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(t=>Um(t)),this.providerContainer.current$.subscribe(({type:t})=>Pi("provider",t)),e.duration$.subscribe(t=>Pi("duration",t)),e.availableVideoTracks$.pipe((0,p.filter)(t=>!!t.length),(0,p.once)()).subscribe(t=>Pi("tracks",t)),this.events.fatalError$.subscribe(new ye("fatalError")),this.events.managedError$.subscribe(new ye("managedError")),e.position$.subscribe(new ye("position")),e.currentVideoTrack$.pipe((0,p.map)(t=>t?.quality)).subscribe(new ye("quality")),this.info.currentBuffer$.subscribe(new ye("buffer")),e.isBuffering$.subscribe(new ye("isBuffering"))].forEach(t=>this.subscription.add(t)),Pi("codecs",Lf())}initTracerSubscription(){let e=(0,p.getTraceSubscriptionMethod)(this.tracer.log.bind(this.tracer)),t=(0,p.getTraceSubscriptionMethod)(this.tracer.error.bind(this.tracer));this.subscription.add(this.info.playbackState$.subscribe(e("playbackState"))).add(this.info.isLooped$.subscribe(e("isLooped"))).add(this.info.currentPlaybackRate$.pipe((0,p.filterChanged)()).subscribe(e("currentPlaybackRate"))).add(this.info.isAutoQualityEnabled$.subscribe(e("isAutoQualityEnabled"))).add(this.info.autoQualityLimits$.subscribe(e("autoQualityLimits"))).add(this.info.currentFormat$.subscribe(e("currentFormat"))).add(this.info.availableQualities$.subscribe(e("availableQualities"))).add(this.info.availableQualitiesFps$.subscribe(e("availableQualitiesFps"))).add(this.info.availableAudioTracks$.subscribe(e("availableAudioTracks"))).add(this.info.isAudioAvailable$.subscribe(e("isAudioAvailable"))).add((0,p.combine)({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe((0,p.filter)(({currentQuality:r,videoBitrate:a})=>!!r&&!!a),(0,p.filterChanged)((r,a)=>r.currentQuality===a.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe((0,p.filter)(r=>r>0),(0,p.filterChanged)()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe((0,p.filter)(r=>r>0),(0,p.filterChanged)()).subscribe(e("currentAudioSegmentLength"))).add(this.info.hostname$.subscribe(e("hostname"))).add(this.info.currentTextTrack$.subscribe(e("currentTextTrack"))).add(this.info.availableTextTracks$.subscribe(e("availableTextTracks"))).add(this.info.autoQualityLimitingAvailable$.subscribe(e("autoQualityLimitingAvailable"))).add((0,p.combine)({currentBuffer:this.info.currentBuffer$.pipe((0,p.filter)(r=>r.end>0),(0,p.filterChanged)((r,a)=>r.end===a.end&&r.start===a.start)),position:this.info.position$.pipe((0,p.filterChanged)())}).pipe((0,p.throttle)(1e3)).subscribe(e("currentBufferAndPosition"))).add(this.info.duration$.pipe((0,p.filterChanged)()).subscribe(e("duration"))).add(this.info.isBuffering$.subscribe(e("isBuffering"))).add(this.info.isLive$.pipe((0,p.filterChanged)()).subscribe(e("isLive"))).add(this.info.canChangePlaybackSpeed$.pipe((0,p.filterChanged)()).subscribe(e("canChangePlaybackSpeed"))).add((0,p.combine)({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe((0,p.filter)(({liveTime:r,liveBufferTime:a})=>!!r&&!!a),(0,p.throttle)(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe((0,p.filterChanged)(),(0,p.filter)(r=>r===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe((0,p.filterChanged)(),(0,p.filter)(r=>r===!0)).subscribe(e("atLiveDurationEdge"))).add(this.info.muted$.pipe((0,p.filterChanged)()).subscribe(e("muted"))).add(this.info.volume$.pipe((0,p.filterChanged)()).subscribe(e("volume"))).add(this.info.isEnded$.pipe((0,p.filterChanged)(),(0,p.filter)(r=>r===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add((0,p.combine)({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe((0,p.filter)(({throughputEstimation:r,rtt:a})=>!!r&&!!a),(0,p.throttle)(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe((0,p.filterChanged)(),(0,p.filter)(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:p.ErrorCategory.DOM,message:String(a)})})};this.subscription.add((0,p.merge)((0,p.fromEvent)(document,"visibilitychange"),(0,p.fromEvent)(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",(0,p.flattenObject)({quality:t,availableTracks:(0,p.flattenObject)(e),track:(0,p.flattenObject)(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}};var dt=require("@vkontakte/videoplayer-shared"),Pw=`@vkontakte/videoplayer-core@${js}`;
123
+ `;var Bs=class{constructor(e,t,r){this.videoInitialized=!1;this.active=!1;this.container=e,this.sourceVideoElement=t,this.params=r,this.canvas=this.createCanvas();let 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 Ds(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(hg,this.gl.VERTEX_SHADER),r=this.createShader(mg,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,u=t-a,l=e+r,c=t+a,d=e-r,h=t+a;return[s,n,o,u,l,c,d,h]}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 he=require("@vkontakte/videoplayer-shared"),Eu=class{constructor(){this.isSeeked$=new he.ValueSubject(!1);this.isBuffering$=new he.ValueSubject(!1);this.currentStallsCount=0;this.maxQualityLimit=void 0;this.lastUniqueVideoTrackSelectedTimestamp=0;this.predictedThroughputWithoutData=0;this.subscription=new he.Subscription}connect(e){this.currentStallDuration$=e.currentStallDuration$,this.videoLastDataObtainedTimestamp$=e.videoLastDataObtainedTimestamp$,this.throughput$=e.throughput$,this.rtt$=e.rtt$,this.qualityLimitsOnStall=e.qualityLimitsOnStall,this.subscription.add(e.isSeeked$.subscribe(this.isSeeked$)),this.subscription.add(e.isBuffering$.subscribe(this.isBuffering$)),this.subscription.add((0,he.combine)({isBuffering:this.isBuffering$,isSeeked:this.isSeeked$}).pipe((0,he.filter)(({isBuffering:t,isSeeked:r})=>t&&!r)).subscribe(()=>{this.currentStallsCount++})),this.subscription.add((0,he.combine)({currentStallDuration:this.currentStallDuration$,isSeeked:this.isSeeked$}).subscribe(({currentStallDuration:t,isSeeked:r})=>{if((0,he.isNullable)(this.lastUniqueVideoTrackSelected))return;let{stallDurationBeforeQualityDecrease:a,stallDurationNoDataBeforeQualityDecrease:s,stallCountBeforeQualityDecrease:n,resetQualityRestrictionTimeout:o}=this.qualityLimitsOnStall,u=this.rtt$.getValue(),l=this.throughput$.getValue(),c=this.videoLastDataObtainedTimestamp$.getValue(),d=(0,he.now)(),h=n&&this.currentStallsCount>=n,m=a&&!r&&d-this.lastUniqueVideoTrackSelectedTimestamp>=a+u&&t>=a,b=s&&d-this.lastUniqueVideoTrackSelectedTimestamp>=s+u&&d-c>=s+u&&t>=s;(h||m||b)&&(window.clearTimeout(this.qualityRestrictionTimer),this.maxQualityLimit=this.lastUniqueVideoTrackSelected.quality,(0,he.isNonNullable)(this.lastUniqueVideoTrackSelected.bitrate)&&l>this.lastUniqueVideoTrackSelected.bitrate&&(this.predictedThroughputWithoutData=this.lastUniqueVideoTrackSelected.bitrate)),t||(window.clearTimeout(this.qualityRestrictionTimer),this.qualityRestrictionTimer=window.setTimeout(()=>{this.maxQualityLimit=void 0,this.predictedThroughputWithoutData=0},o))}))}get videoMaxQualityLimit(){return this.maxQualityLimit}get predictedThroughput(){return this.predictedThroughputWithoutData}set lastVideoTrackSelected(e){this.lastUniqueVideoTrackSelected?.id!==e.id&&(this.lastUniqueVideoTrackSelected=e,this.lastUniqueVideoTrackSelectedTimestamp=(0,he.now)(),this.currentStallsCount=0)}destroy(){window.clearTimeout(this.qualityRestrictionTimer),this.subscription.unsubscribe()}},fg=Eu;var lr=class{constructor(e){this.subscription=new B.Subscription;this.videoState=new q("stopped");this.elementSize$=new B.ValueSubject(void 0);this.textTracksManager=new qe;this.droppedFramesManager=new Ss;this.stallsManager=new fg;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new xi;this.audioTrackSwitchHistory=new xi;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"),k(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"),k(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):r?.to==="ready"&&k(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"&&k(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"&&k(this.params.desiredState.playbackState,"paused");return;default:return(0,B.assertNever)(e)}}};this.init3DScene=e=>{if(this.scene3D)return;this.scene3D=new Bs(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x: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=Ee(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(de(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 Cs({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=ke(this.video),a=this.constructor.name,s=o=>{e.error$.next({id:a,category:B.ErrorCategory.WTF,message:`${a} internal logic error`,thrown:o})};return{output:e,desiredState:t,observableVideo:r,genericErrorListener:s,connect:(o,u)=>this.subscription.add(o.subscribe(u,s))}}subscribe(){let{output:e,desiredState:t,observableVideo:r,genericErrorListener:a,connect:s}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe((0,B.filter)(c=>!!c.length),(0,B.once)()).subscribe(c=>{this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:r.playing$,pause$:r.pause$,tracks:c})}));let n=this.params.desiredState.seekState.stateChangeEnded$.pipe((0,B.map)(c=>c.to.state!=="none"),(0,B.filterChanged)());this.stallsManager.connect({isSeeked$:n,currentStallDuration$:this.player.currentStallDuration$.pipe((0,B.filterChanged)()),videoLastDataObtainedTimestamp$:this.player.videoLastDataObtainedTimestamp$,throughput$:this.params.dependencies.throughputEstimator.throughput$,rtt$:this.params.dependencies.throughputEstimator.rtt$,qualityLimitsOnStall:this.params.tuning.dash.qualityLimitsOnStall,isBuffering$:r.isBuffering$}),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((0,B.filter)(B.isNonNullable),(0,B.once)()),e.firstBytesEvent$),s(this.videoState.stateChangeEnded$.pipe((0,B.map)(c=>c.to)),this.params.output.playbackState$),this.subscription.add(r.seeked$.subscribe(e.seekedEvent$,a)),this.subscription.add(ut(this.video,t.isLooped,a)),this.subscription.add(Pe(this.video,t.volume,r.volumeState$,a)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,a)),this.subscription.add(Fe(this.video,t.playbackRate,r.playbackRateState$,a)),s((0,B.observeElementSize)(this.video),this.elementSize$),s(Ue(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),k(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},a)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),k(t.playbackState,"paused")},a)).add(r.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},a)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:c})=>{if(c==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let d=this.player.getStreams();if((0,B.assertNonNullable)(d,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let m=[];for(let b of d.audio){m.push(gu(b));let g=[];for(let y of b.representations){let T=sg(y);g.push(T),this.audioTracksMap.set(T,{stream:b,representation:y})}this.audioStreamsMap.set(b,g)}this.params.output.availableAudioStreams$.next(m)}let h=[];for(let m of d.video){h.push(Su(m));let b=[];for(let g of m.representations){let y=ag({...g,streamId:m.id});y&&(b.push(y),this.videoTracksMap.set(y,{stream:m,representation:g}))}this.videoStreamsMap.set(m,b)}if(this.params.output.availableVideoStreams$.next(h),this.textTracksManager)for(let m of d.text)for(let b of m.representations){let g=ng(m,b);this.textTracksMap.set(g,{stream:m,representation:b})}this.params.output.availableVideoTracks$.next(Array.from(this.videoTracksMap.keys())),this.params.output.availableAudioTracks$.next(Array.from(this.audioTracksMap.keys())),this.params.output.isAudioAvailable$.next(!!this.audioTracksMap.size),this.audioTracksMap.size&&this.textTracksMap.size&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else c==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},a));let o=c=>e.error$.next({id:"RepresentationSwitch",category:B.ErrorCategory.WTF,message:"Switching representations threw",thrown:c});this.subscription.add((0,B.merge)(this.player.currentStallDuration$,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$,(0,B.fromEvent)(this.video,"progress")).subscribe(()=>{let c=this.player.state$.getState(),d=this.player.state$.getTransition();if(!(0,bg.default)(["manifest_ready","running"],c)||d)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let h=this.selectVideoAudioRepresentations();if(!h)return;let[m,b]=h,g=[...this.videoTracksMap.keys()].find(T=>this.videoTracksMap.get(T)?.representation.id===m.id);(0,B.isNonNullable)(g)&&(this.stallsManager.lastVideoTrackSelected=g);let y=this.params.desiredState.autoVideoTrackLimits.getTransition();if(y&&this.params.output.autoVideoTrackLimits$.next(y.to),c==="manifest_ready")this.player.initRepresentations(m.id,b?.id,this.params.sourceHls);else if(this.player.switchRepresentation("video",m.id).catch(o),b){let T=!!t.audioStream.getTransition();this.player.switchRepresentation("audio",b.id,T).catch(o)}},a)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:c})=>{this.scene3D&&c&&this.scene3D.pointCameraTo(c.x,c.y)})),this.subscription.add(this.elementSize$.subscribe(c=>{this.scene3D&&c&&this.scene3D.setViewportSize(c.width,c.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe((0,B.filterChanged)()).subscribe(c=>{let d=[...this.videoTracksMap.entries()].find(([,{representation:g}])=>g.id===c);if(!d){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[h,{stream:m}]=d,b=this.params.desiredState.videoStream.getTransition();b&&b.to&&b.to.id===m.id&&this.params.desiredState.videoStream.setState(b.to),e.currentVideoTrack$.next(h),e.currentVideoStream$.next(Su(m))},a)),this.subscription.add(this.player.currentAudioRepresentation$.pipe((0,B.filterChanged)()).subscribe(c=>{let d=[...this.audioTracksMap.entries()].find(([,{representation:g}])=>g.id===c);if(!d){e.currentAudioStream$.next(void 0);return}let[h,{stream:m}]=d,b=this.params.desiredState.audioStream.getTransition();b&&b.to&&b.to.id===m.id&&this.params.desiredState.audioStream.setState(b.to),e.currentAudioStream$.next(gu(m))},a)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(c=>{if(c?.is3dVideo&&this.params.tuning.spherical?.enabled)try{this.init3DScene(c),e.is3DVideo$.next(!0)}catch(d){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${d}`})}else this.destroy3DScene(),this.params.tuning.spherical?.enabled&&e.is3DVideo$.next(!1)},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 u=t.playbackState.stateChangeStarted$.pipe((0,B.map)(({to:c})=>c==="ready"),(0,B.filterChanged)());this.subscription.add((0,B.merge)(u,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$).subscribe(()=>{let c=t.autoVideoTrackSwitching.getState(),h=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:c?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(h)})),this.subscription.add((0,B.merge)(u,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let l=(0,B.merge)(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,B.observableFrom)(["init"])).pipe((0,B.debounce)(0));this.subscription.add(l.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:N})=>N===a),o=t.currentVideoTrack$.getValue(),u=e.videoStream.getState()??(n&&this.videoTracksMap.get(n)?.stream)??this.videoStreamsMap.size===1?this.videoStreamsMap.keys().next().value:void 0;if(!u)return;let l=[...this.videoStreamsMap.keys()].find(({id:N})=>N===u.id),c=l&&this.videoStreamsMap.get(l);if(!c)return;let d=ct(this.video.buffered,this.video.currentTime*1e3),h=r?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,m=Math.min(d/Math.min(h,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),b=e.audioStream.getState()??(this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0),g=[...this.audioStreamsMap.keys()].find(({id:N})=>N===b?.id)??this.audioStreamsMap.keys().next().value,y=0;if(g){if(n&&!r){let N=bs(n,c,this.audioStreamsMap.get(g)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);y=Math.max(y,N?.bitrate??-1/0)}if(o){let N=bs(o,c,this.audioStreamsMap.get(g)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);y=Math.max(y,N?.bitrate??-1/0)}}let T=Ft(c,{container:this.elementSize$.getValue(),estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:y,forwardBufferHealth:m,current:o,visible:this.params.output.elementVisible$.getValue(),history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,stallsVideoMaxQualityLimit:this.stallsManager.videoMaxQualityLimit,stallsPredictedThroughput:this.stallsManager.predictedThroughput,abrLogger:this.params.dependencies.abrLogger}),R=r?T??n:n??T,A=g&&Ym(R,c,this.audioStreamsMap.get(g)??[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:m,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),D=this.videoTracksMap.get(R)?.representation,x=A&&this.audioTracksMap.get(A)?.representation;if(D&&x)return[D,x];if(D&&!x&&this.audioTracksMap.size===0)return[D,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){Ae(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.liveOffset?.pause(),this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:B.ErrorCategory.DOM,thrown:e}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.stallsManager.destroy(),this.destroy3DScene(),this.textTracksManager?.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),xe(this.video),this.tracer.end()}};var da=class extends lr{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)}};var jt=require("@vkontakte/videoplayer-shared");var pa=class extends lr{constructor(e){super(e),this.liveOffset=new yt,this.textTracksManager=null}subscribe(){super.subscribe();let{output:e,observableVideo:t,desiredState:r,connect:a}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),a(t.timeUpdate$,e.liveBufferTime$),a(this.player.liveDuration$,e.duration$),a(this.player.liveLatency$,e.liveLatency$),this.subscription.add(r.isLowLatency.stateChangeEnded$.pipe((0,jt.map)(s=>s.to)).subscribe(this.player.isLowLatency$)).add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add((0,jt.combine)({interval:(0,jt.interval)(1e3),playbackRate:t.playbackRateState$}).subscribe(({playbackRate:s})=>{if(this.videoState.getState()==="playing"){let n=e.position$.getValue()+(s-1);n<=0&&e.position$.next(n),this.liveOffset?.resetTo(-n*1e3)}})).add((0,jt.combine)({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe((0,jt.map)(({liveBufferTime:s,liveAvailabilityStartTime:n})=>s&&n?s+n:void 0)).subscribe(e.liveTime$)).add(this.player.currentLiveTextRepresentation$.subscribe(s=>{if(s){let n=og(s);this.params.output.availableTextTracks$.next([n])}}))}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 gg=j(ds(),1);var H=require("@vkontakte/videoplayer-shared"),Ze={};var Qr=(i,e)=>new H.Observable(t=>{let r=(a,s)=>t.next(s);return i.on(e,r),()=>i.off(e,r)}),ha=class{constructor(e){this.subscription=new H.Subscription;this.videoState=new q("initializing");this.textTracksManager=new qe;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:(0,H.assertNever)(e)}break;case"ready":switch(e){case"stopped":this.prepare();break;case"ready":case"playing":case"paused":break;default:(0,H.assertNever)(e)}break;case"playing":switch(e){case"playing":break;case"stopped":this.prepare();break;case"ready":case"paused":this.playIfAllowed();break;default:(0,H.assertNever)(e)}break;case"paused":switch(e){case"paused":break;case"stopped":this.prepare();break;case"ready":this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused");break;case"playing":this.pause();break;default:(0,H.assertNever)(e)}break;default:(0,H.assertNever)(t)}};this.video=Ee(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(de(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),xe(this.video)}loadHlsJs(){let e=!1,t=a=>{e||this.params.output.error$.next({id:a==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:H.ErrorCategory.NETWORK,message:"Failed to load Hls.js",thrown:a}),e=!0},r=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);(0,gg.default)(import("hls.js").then(a=>{e||(Ze.Hls=a.default,Ze.Events=a.default.Events,this.init())},t),()=>{window.clearTimeout(r),e=!0})}init(){(0,H.assertNonNullable)(Ze.Hls,"hls.js not loaded"),this.hls=new Ze.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState("stopped")}subscribe(){(0,H.assertNonNullable)(Ze.Events,"hls.js not loaded");let{desiredState:e,output:t}=this.params,r=l=>{t.error$.next({id:"HlsJsProvider",category:H.ErrorCategory.WTF,message:"HlsJsProvider internal logic error",thrown:l})},a=ke(this.video),s=(l,c)=>this.subscription.add(l.subscribe(c,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(ut(this.video,e.isLooped,r)),this.subscription.add(Pe(this.video,e.volume,a.volumeState$,r)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(Fe(this.video,e.playbackRate,a.playbackRateState$,r)),s(Ue(this.video),t.elementVisible$),s(this.videoState.stateChangeEnded$.pipe((0,H.map)(l=>l.to)),this.params.output.playbackState$),this.subscription.add(Qr(this.hls,Ze.Events.ERROR).subscribe(l=>{l.fatal&&t.error$.next({id:["HlsJsFatal",l.type,l.details].join("_"),category:H.ErrorCategory.WTF,message:`HlsJs fatal ${l.type} ${l.details}, ${l.err?.message} ${l.reason}`,thrown:l.error})})),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState("playing"),k(e.playbackState,"playing")},r)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),k(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(Qr(this.hls,Ze.Events.MANIFEST_PARSED).pipe((0,H.map)(({levels:l})=>l.reduce((c,d)=>{let h=d.name||d.height.toString(10),{width:m,height:b}=d,g=_t(d.attrs.QUALITY??"")??(0,H.videoSizeToQuality)({width:m,height:b});if(!g)return c;let y=d.attrs["FRAME-RATE"]?parseFloat(d.attrs["FRAME-RATE"]):void 0,T={id:h.toString(),quality:g,bitrate:d.bitrate/1e3,size:{width:m,height:b},fps:y};return this.trackLevels.set(h,{track:T,level:d}),c.push(T),c},[]))),t.availableVideoTracks$),s(Qr(this.hls,Ze.Events.MANIFEST_PARSED),l=>{if(l.subtitleTracks.length>0){let c=[];for(let d of l.subtitleTracks){let h=d.name,m=d.attrs.URI||"",b=d.lang;c.push({id:h,url:m,language:b,type:"internal"})}e.internalTextTracks.startTransitionTo(c)}}),s(Qr(this.hls,Ze.Events.LEVEL_LOADING).pipe((0,H.map)(({url:l})=>de(l))),t.hostname$),s(Qr(this.hls,Ze.Events.FRAG_CHANGED),l=>{let{video:c,audio:d}=l.frag.elementaryStreams;t.currentVideoSegmentLength$.next(((c?.endPTS??0)-(c?.startPTS??0))*1e3),t.currentAudioSegmentLength$.next(((d?.endPTS??0)-(d?.startPTS??0))*1e3)}),this.subscription.add(Ot(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,l=>{this.hls.nextLevel=l?-1:this.hls.currentLevel,this.hls.loadLevel=l?-1:this.hls.loadLevel},{onError:r}));let n=l=>Array.from(this.trackLevels.values()).find(({level:c})=>c===l)?.track,o=Qr(this.hls,Ze.Events.LEVEL_SWITCHED).pipe((0,H.map)(({level:l})=>n(this.hls.levels[l])));o.pipe((0,H.filter)(H.isNonNullable)).subscribe(t.currentVideoTrack$,r),this.subscription.add(Ot(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel]),l=>{if((0,H.isNullable)(l))return;let c=this.trackLevels.get(l.id)?.level;if(!c)return;let d=this.hls.levels.indexOf(c),h=this.hls.currentLevel,m=this.hls.levels[h];!m||c.bitrate>m.bitrate?this.hls.nextLevel=d:(this.hls.loadLevel=d,this.hls.loadLevel=d)},{changed$:o,onError:r})),s(a.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);let u=(0,H.merge)(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,H.observableFrom)(["init"])).pipe((0,H.debounce)(0));this.subscription.add(u.subscribe(this.syncPlayback,r))}prepare(){this.videoState.startTransitionTo("ready"),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}async playIfAllowed(){this.videoState.startTransitionTo("playing"),await Ae(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:H.ErrorCategory.DOM,thrown:t}))||(this.videoState.setState("paused"),k(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"),k(this.params.desiredState.playbackState,"stopped",!0)}};var Sg="X-Playback-Duration",xu=async i=>{let e=await Et(i),t=await e.text(),r=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t)?.[1];return r?parseInt(r,10):e.headers.has(Sg)?parseInt(e.headers.get(Sg),10):void 0};var U=require("@vkontakte/videoplayer-shared");var ku=j(Wn(),1);var Os=require("@vkontakte/videoplayer-shared");var fw=i=>{let e=null;if(i.QUALITY&&(e=_t(i.QUALITY)),!e&&i.RESOLUTION){let[t,r]=i.RESOLUTION.split("x").map(a=>parseInt(a,10));e=(0,Os.videoSizeToQuality)({width:t,height:r})}return e??null},bw=(i,e)=>{let t=i.split(`
124
+ `),r=[],a=[];for(let s=0;s<t.length;s++){let n=t[s],o=n.match(/^#EXT-X-STREAM-INF:(.+)/),u=n.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!o&&!u)){if(o){let l=(0,ku.default)(o[1].split(",").map(y=>y.split("="))),c=l.QUALITY??`stream-${l.BANDWIDTH}`,d=fw(l),h;l.BANDWIDTH&&(h=parseInt(l.BANDWIDTH,10)/1e3||void 0),!h&&l["AVERAGE-BANDWIDTH"]&&(h=parseInt(l["AVERAGE-BANDWIDTH"],10)/1e3||void 0);let m=l["FRAME-RATE"]?parseFloat(l["FRAME-RATE"]):void 0,b;if(l.RESOLUTION){let[y,T]=l.RESOLUTION.split("x").map(R=>parseInt(R,10));y&&T&&(b={width:y,height:T})}let g=new URL(t[++s],e).toString();d&&r.push({id:c,quality:d,url:g,bandwidth:h,size:b,fps:m})}if(u){let l=(0,ku.default)(u[1].split(",").map(m=>m.split("=")).map(([m,b])=>[m,b.replace(/^"|"$/g,"")])),c=l.URI?.replace(/playlist$/,"subtitles.vtt"),d=l.LANGUAGE,h=l.NAME;c&&d&&a.push({type:"internal",id:d,label:h,language:d,url:c,isAuto:!1})}}}if(!r.length)throw new Error("Empty manifest");return{qualityManifests:r,textTracks:a}},gw=i=>new Promise(e=>{setTimeout(()=>{e()},i)}),Pu=0,vg=async(i,e=i,t)=>{let a=await(await Et(i)).text();Pu+=1;try{let{qualityManifests:s,textTracks:n}=bw(a,e);return{qualityManifests:s,textTracks:n}}catch{if(Pu<=t.manifestRetryMaxCount)return await gw((0,Os.getExponentialDelay)(Pu-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),vg(i,e,t)}return{qualityManifests:[],textTracks:[]}},_s=vg;var ma=class{constructor(e){this.subscription=new U.Subscription;this.videoState=new q("stopped");this.textTracksManager=new qe;this.manifests$=new U.ValueSubject([]);this.liveOffset=new yt;this.manifestStartTime$=new U.ValueSubject(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"),k(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||n||o){let c=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(c),this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if(a?.to!=="paused"&&l.state==="requested"){this.videoState.startTransitionTo("ready"),this.seek(l.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(t){case"ready":r==="ready"?k(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),k(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"&&k(this.params.desiredState.playbackState,"playing");return;case"paused":if(r==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let c=this.liveOffset.getTotalOffset();c>=this.maxSeekBackTime$.getValue()&&(c=0,this.liveOffset.resetTo(c)),this.liveOffset.resume(),this.params.output.position$.next(-c/1e3),this.prepare()}else a?.to==="paused"&&(k(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return(0,U.assertNever)(t)}};this.params=e,this.video=Ee(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:U.VideoQuality.INVARIANT,url:this.params.source.url},_s(Se(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:U.ErrorCategory.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),this.manifests$.next([this.masterManifest,...t])},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:U.ErrorCategory.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(de(this.params.source.url)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.maxSeekBackTime$=new U.ValueSubject(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(u=>u.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"HlsLiveProvider",category:U.ErrorCategory.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},a=ke(this.video),s=(o,u)=>this.subscription.add(o.subscribe(u,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(Pe(this.video,t.volume,a.volumeState$,r)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Fe(this.video,t.playbackRate,a.playbackRateState$,r)),s(Ue(this.video),e.elementVisible$),this.textTracksManager.connect(this.video,t,e),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState("playing"),k(t.playbackState,"playing")},r)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),k(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((0,U.filterChanged)(),(0,U.map)(o=>-o/1e3)).subscribe(this.params.output.duration$,r)),this.subscription.add(a.loadedMetadata$.subscribe(()=>{let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&(0,U.isNonNullable)(l.to)){let d=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let h=this.manifests$.getValue().find(m=>m.id===d);h&&(this.params.output.currentVideoTrack$.next(h),this.params.output.hostname$.next(de(h.url)))}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o&&o.state==="requested"&&this.seek(o.position)},r)),this.subscription.add(a.loadedData$.subscribe(()=>{let o=this.video?.getStartDate?.()?.getTime();this.manifestStartTime$.next(o||void 0)},r)),this.subscription.add((0,U.combine)({startTime:this.manifestStartTime$.pipe((0,U.filter)(U.isNonNullable)),currentTime:a.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),r)),this.subscription.add(this.manifests$.pipe((0,U.map)(o=>o.map(({id:u,quality:l,size:c,bandwidth:d,fps:h})=>({id:u,quality:l,size:c,fps:h,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,r));let n=(0,U.merge)(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,(0,U.observableFrom)(["init"])).pipe((0,U.debounce)(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),xe(this.video)}prepare(){let e=this.selectManifest();if((0,U.isNullable)(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:u}=t?.to??r??{};for(let[l,c]of[[o,"mq"],[u,"lq"]]){let d=String(parseFloat(l||""));c&&l&&a.searchParams.set(c,d)}}let s=this.params.format==="HLS_LIVE_CMAF"?2:0,n=Se(a.toString(),this.liveOffset.getTotalOffset(),s);this.video.setAttribute("src",n),this.video.load(),xu(n).then(o=>{if(!(0,U.isNullable)(o))this.maxSeekBackTime$.next(o);else{let u=this.params.source.maxSeekBackTime??this.maxSeekBackTime$.getValue();if((0,U.isNullable)(u)||!isFinite(u))try{Et(n).then(l=>l.text()).then(l=>{let c=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(l)?.[1];if(c){let d=new URL(c,n).toString();xu(d).then(h=>{(0,U.isNullable)(h)||this.maxSeekBackTime$.next(h)})}})}catch{}}})}playIfAllowed(){Ae(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),k(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:U.ErrorCategory.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()}};var W=require("@vkontakte/videoplayer-shared");var fa=class{constructor(e){this.subscription=new W.Subscription;this.videoState=new q("stopped");this.textTracksManager=new qe;this.manifests$=new W.ValueSubject([]);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"),k(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||n||o){let c=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(c);let{currentTime:d}=this.video;this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:d*1e3,forcePrecise:!0});return}switch(a?.to!=="paused"&&l.state==="requested"&&this.seek(l.position),t){case"ready":r==="ready"?k(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),k(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"&&k(this.params.desiredState.playbackState,"playing");return;case"paused":r==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):a?.to==="paused"&&k(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return(0,W.assertNever)(t)}};this.params=e,this.video=Ee(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:W.VideoQuality.INVARIANT,url:this.params.source.url},this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(de(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),_s(Se(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:W.ErrorCategory.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(u=>u.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"HlsProvider",category:W.ErrorCategory.WTF,message:"HlsProvider internal logic error",thrown:o})},a=ke(this.video),s=(o,u)=>this.subscription.add(o.subscribe(u));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((0,W.map)(o=>o.to)),this.params.output.playbackState$),this.subscription.add(ut(this.video,t.isLooped,r)),this.subscription.add(Pe(this.video,t.volume,a.volumeState$,r)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Fe(this.video,t.playbackRate,a.playbackRateState$,r)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState("playing"),k(t.playbackState,"playing")},r)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),k(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(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&(0,W.isNonNullable)(l.to)){let m=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let b=this.manifests$.getValue().find(g=>g.id===m);b&&(this.params.output.currentVideoTrack$.next(b),this.params.output.hostname$.next(de(b.url)))}let d=this.params.desiredState.playbackRate.getState(),h=this.params.output.element$.getValue()?.playbackRate;if(d!==h){let m=this.params.output.element$.getValue();m&&(this.params.desiredState.playbackRate.setState(d),m.playbackRate=d)}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o.state==="requested"&&this.seek(o.position)},r))),this.subscription.add(this.manifests$.pipe((0,W.map)(o=>o.map(({id:u,quality:l,size:c,bandwidth:d,fps:h})=>({id:u,quality:l,size:c,fps:h,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,r)),!W.clientChecker.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add((0,W.merge)((0,W.fromEvent)(o,"addtrack"),(0,W.fromEvent)(o,"removetrack"),(0,W.fromEvent)(o,"change"),(0,W.observableFrom)(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},r))}let n=(0,W.merge)(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,(0,W.observableFrom)(["init"])).pipe((0,W.debounce)(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),xe(this.video)}prepare(){let e=this.selectManifest();if((0,W.isNullable)(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,u]of[[s,"mq"],[n,"lq"]]){let l=String(parseFloat(o||""));u&&o&&a.searchParams.set(u,l)}}this.video.setAttribute("src",a.toString()),this.video.load()}playIfAllowed(){Ae(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:W.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};var yg=j(kr(),1),ba=j(Ii(),1);var X=require("@vkontakte/videoplayer-shared");var ga=class{constructor(e){this.subscription=new X.Subscription;this.videoState=new q("stopped");this.trackUrls={};this.textTracksManager=new qe;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"),k(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:u}=this.video;this.prepare(),o.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:u*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"?k(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),k(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"&&k(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):r?.to==="paused"&&k(this.params.desiredState.playbackState,"paused");return;default:return(0,X.assertNever)(e)}};this.params=e,this.video=Ee(e.container,e.tuning),this.params.output.element$.next(this.video),(0,yg.default)(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((0,ba.default)(this.trackUrls).map(({track:t})=>t)),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.desiredState.autoVideoTrackSwitching.setState(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.subscribe()}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"MpegProvider",category:X.ErrorCategory.WTF,message:"MpegProvider internal logic error",thrown:o})},a=ke(this.video),s=(o,u)=>this.subscription.add(o.subscribe(u,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((0,X.map)(o=>o.to)),this.params.output.playbackState$),this.subscription.add(ut(this.video,t.isLooped,r)),this.subscription.add(Pe(this.video,t.volume,a.volumeState$,r)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Fe(this.video,t.playbackRate,a.playbackRateState$,r)),s(Ue(this.video),e.elementVisible$),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState("playing"),k(t.playbackState,"playing")},r)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),k(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&&(0,X.isNonNullable)(o.to)){this.params.desiredState.videoTrack.setState(o.to),this.params.output.currentVideoTrack$.next(this.trackUrls[o.to.id].track);let u=this.params.desiredState.playbackRate.getState(),l=this.params.output.element$.getValue()?.playbackRate;if(u!==l){let c=this.params.output.element$.getValue();c&&(this.params.desiredState.playbackRate.setState(u),c.playbackRate=u)}}this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.textTracksManager.connect(this.video,t,e);let n=(0,X.merge)(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,(0,X.observableFrom)(["init"])).pipe((0,X.debounce)(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),xe(this.video)}prepare(){let e=this.params.desiredState.videoTrack.getState()?.id;(0,X.assertNonNullable)(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];(0,X.assertNonNullable)(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=na(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(de(t))}playIfAllowed(){Ae(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:X.ErrorCategory.DOM,thrown:e}))}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=(0,ba.default)(this.trackUrls).find(o=>!(0,X.isInvariantQuality)(o.track.quality)&&(0,X.isLowerOrEqual)(o.track.quality,e))?.track,s=this.params.desiredState.videoTrack.getState()?.id,n=this.trackUrls[s??"0"]?.track;if(a&&n&&(0,X.isHigherOrEqual)(n.quality,a.quality)&&(t=a),!t){let o=(0,ba.default)(this.trackUrls).filter(l=>!(0,X.isInvariantQuality)(l.track.quality)&&(0,X.isHigher)(l.track.quality,e)),u=o.length;u&&(t=o[u-1].track)}t&&(r=t.quality)}else if(!e){let a=(0,ba.default)(this.trackUrls).map(s=>s.track);t=Ft(a,{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},estimatedThroughput: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})}};var re=require("@vkontakte/videoplayer-shared");var Ig=require("@vkontakte/videoplayer-shared"),Tg=["stun:videostun.mycdn.me:80"],Sw=1e3,vw=3,Au=()=>null,Ns=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=Au;this.externalStopCallback=Au;this.externalErrorCallback=Au;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:Tg}]};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:Ig.ErrorCategory.WTF,message:e.message})}async onPeerConnectionStream(e){let t=e.streams[0];this.stream&&this.stream.id===t.id||(this.stream=t,this.externalStartCallback(this.stream))}onPeerConnectionIceCandidate(e){e.candidate&&this.send({type:this.signalingType,inviteType:"CANDIDATE",candidate:e.candidate})}onPeerConnectionIceConnectionStateChange(){if(this.peerConnection){let e=this.peerConnection.iceConnectionState;["failed","closed"].indexOf(e)>-1&&(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():(this.closeConnections(),this.scheduleRetry()))}}async createOffer(){let e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");let t=await this.peerConnection.createOffer(e),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),Sw)}normalizeOptions(e={}){let t={stunServerList:Tg,maxRetryNumber:vw,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var Sa=class{constructor(e){this.videoState=new q("stopped");this.maxSeekBackTime$=new re.ValueSubject(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"),k(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"),k(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"&&k(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):r?.to==="paused"&&k(this.params.desiredState.playbackState,"paused");return;default:return(0,re.assertNever)(e)}};this.subscription=new re.Subscription,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=Ee(e.container,e.tuning),this.liveStreamClient=new Ns(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),xe(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,r=n=>{e.error$.next({id:"WebRTCLiveProvider",category:re.ErrorCategory.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};(0,re.merge)(this.videoState.stateChangeStarted$.pipe((0,re.map)(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe((0,re.map)(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})});let a=ke(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(Ue(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(Pe(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(0,re.assertNever)(n.to)}},r)).add((0,re.merge)(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,(0,re.observableFrom)(["init"])).pipe((0,re.debounce)(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(de(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:re.VideoQuality.INVARIANT}),this.video.srcObject=e,k(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:re.ErrorCategory.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){Ae(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:re.ErrorCategory.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var va=class{constructor(e){this.iterator=e[Symbol.iterator](),this.next()}next(){this.current=this.iterator.next()}getValue(){if(this.current.done)throw new Error("Iterable is completed");return this.current.value}isCompleted(){return!!this.current.done}};var v=require("@vkontakte/videoplayer-shared");var wt=require("@vkontakte/videoplayer-shared"),Eg=i=>new wt.Observable(e=>{let t=new wt.Subscription,r=i.desiredPlaybackState$.stateChangeStarted$.pipe((0,wt.map)(({from:l,to:c})=>`${l}-${c}`)),a=i.desiredPlaybackState$.stateChangeEnded$,s=i.providerChanged$.pipe((0,wt.map)(({type:l})=>l!==void 0)),n=new wt.Subject,o=0,u="unknown";return t.add(r.subscribe(l=>{o&&window.clearTimeout(o),u=l,o=window.setTimeout(()=>n.next(l),i.maxTransitionInterval)})),t.add(a.subscribe(()=>{window.clearTimeout(o),u="unknown",o=0})),t.add(s.subscribe(l=>{o&&(window.clearTimeout(o),o=0,l&&(o=window.setTimeout(()=>n.next(u),i.maxTransitionInterval)))})),t.add(n.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});var je=require("@vkontakte/videoplayer-shared");function xg(){return new(window.AudioContext||window.webkitAudioContext)}var Pg=require("@vkontakte/videoplayer-shared");var Wr=class i{constructor(e,t,r,a){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=r;this.volumeMultiplier=a;this.destroyController=new Oe;this.subscriptions=new je.Subscription;this.audioContext=null;this.gainNode=null;this.mediaElementSource=null;this.subscriptions.add(this.provider$.pipe((0,je.filter)(s=>!!s.type),(0,je.once)()).subscribe(({type:s})=>this.subscribe(s)))}static{this.errorId="VolumeMultiplierManager"}subscribe(e){Pg.clientChecker.isSafari&&e!=="MPEG"||this.subscriptions.add((0,je.combine)({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe((0,je.filter)(({playbackState:t,video:r,volume:{muted:a,volume:s}})=>t==="playing"&&!!r&&!a&&!!s),(0,je.once)()).subscribe(({video:t})=>{this.initAudioContextOnce(t).then(r=>{r||this.destroy()}).catch(r=>{this.handleError(r),this.destroy()})}))}static isSupported(){return"AudioContext"in window&&"GainNode"in window&&"MediaElementAudioSourceNode"in window}async initAudioContextOnce(e){let{volumeMultiplier:t}=this,r=xg();this.audioContext=r;let a=r.createGain();if(this.gainNode=a,a.gain.value=t,a.connect(r.destination),r.state==="suspended"&&(await r.resume(),this.destroyController.signal.aborted))return!1;let s=r.createMediaElementSource(e);return this.mediaElementSource=s,s.connect(a),!0}cleanup(){this.mediaElementSource&&(this.mediaElementSource.disconnect(),this.mediaElementSource=null),this.gainNode&&(this.gainNode.disconnect(),this.gainNode=null),this.audioContext&&(this.audioContext.state!=="closed"&&this.audioContext.close(),this.audioContext=null)}destroy(){this.destroyController.abort(),this.subscriptions.unsubscribe(),this.cleanup()}handleError(e){this.volumeMultiplierError$.next({id:i.errorId,category:je.ErrorCategory.VIDEO_PIPELINE,message:e?.message??`${i.errorId} exception`,thrown:e})}};var yw={chunkDuration:5e3,maxParallelRequests:5},ya=class{constructor(e){this.current$=new v.ValueSubject({type:void 0});this.providerError$=new v.Subject;this.noAvailableProvidersError$=new v.Subject;this.volumeMultiplierError$=new v.Subject;this.providerOutput={position$:new v.ValueSubject(0),duration$:new v.ValueSubject(1/0),volume$:new v.ValueSubject({muted:!1,volume:1}),availableVideoStreams$:new v.ValueSubject([]),currentVideoStream$:new v.ValueSubject(void 0),availableVideoTracks$:new v.ValueSubject([]),currentVideoTrack$:new v.ValueSubject(void 0),availableAudioStreams$:new v.ValueSubject([]),currentAudioStream$:new v.ValueSubject(void 0),availableAudioTracks$:new v.ValueSubject([]),currentVideoSegmentLength$:new v.ValueSubject(0),currentAudioSegmentLength$:new v.ValueSubject(0),isAudioAvailable$:new v.ValueSubject(!0),autoVideoTrackLimitingAvailable$:new v.ValueSubject(!1),autoVideoTrackLimits$:new v.ValueSubject(void 0),currentBuffer$:new v.ValueSubject(void 0),isBuffering$:new v.ValueSubject(!0),error$:new v.Subject,warning$:new v.Subject,willSeekEvent$:new v.Subject,soundProhibitedEvent$:new v.Subject,seekedEvent$:new v.Subject,loopedEvent$:new v.Subject,endedEvent$:new v.Subject,firstBytesEvent$:new v.Subject,loadedMetadataEvent$:new v.Subject,firstFrameEvent$:new v.Subject,canplay$:new v.Subject,isLive$:new v.ValueSubject(void 0),isLowLatency$:new v.ValueSubject(!1),canChangePlaybackSpeed$:new v.ValueSubject(!0),liveTime$:new v.ValueSubject(void 0),liveBufferTime$:new v.ValueSubject(void 0),liveLatency$:new v.ValueSubject(void 0),availableTextTracks$:new v.ValueSubject([]),currentTextTrack$:new v.ValueSubject(void 0),hostname$:new v.ValueSubject(void 0),httpConnectionType$:new v.ValueSubject(void 0),httpConnectionReused$:new v.ValueSubject(void 0),inPiP$:new v.ValueSubject(!1),inFullscreen$:new v.ValueSubject(!1),element$:new v.ValueSubject(void 0),elementVisible$:new v.ValueSubject(!0),availableSources$:new v.ValueSubject(void 0),is3DVideo$:new v.ValueSubject(!1),playbackState$:new v.ValueSubject("")};this.subscription=new v.Subscription;this.volumeMultiplierManager=null;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer"),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name);let t=$f([...Mf(this.params.tuning),...Lf(this.params.tuning)],this.params.tuning).filter(l=>(0,v.isNonNullable)(e.sources[l])),{forceFormat:r,formatsToAvoid:a}=this.params.tuning,s=[];r?s=[r]:a.length?s=[...t.filter(l=>!(0,wu.default)(a,l)),...t.filter(l=>(0,wu.default)(a,l))]:s=t,this.log({message:`Selected formats: ${s.join(" > ")}`}),this.tracer.log("Selected formats",(0,v.flattenObject)(s)),this.screenFormatsIterator=new va(s);let n=[...Xo(!0),...Xo(!1)];this.chromecastFormatsIterator=new va(n.filter(l=>(0,v.isNonNullable)(e.sources[l]))),this.providerOutput.availableSources$.next(e.sources);let{volumeMultiplier:o=1,tuning:{useVolumeMultiplier:u}}=this.params;u&&o!==1&&Wr.isSupported()&&(this.volumeMultiplierManager=new Wr(this.providerOutput,this.current$,this.volumeMultiplierError$,o))}init(){this.subscription.add(this.initProviderErrorHandling()),this.subscription.add(this.params.dependencies.chromecastInitializer.connection$.subscribe(()=>{this.reinitProvider()}))}destroy(){this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe(),this.volumeMultiplierManager?.destroy(),this.volumeMultiplierManager=null,this.tracer.end()}initProvider(){let e=this.chooseDestination(),t=this.chooseFormat(e);if((0,v.isNullable)(t)){this.handleNoFormatsError(e);return}let r;try{r=this.createProvider(e,t)}catch(a){this.providerError$.next({id:"ProviderNotConstructed",category:v.ErrorCategory.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(0,v.assertNever)(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]),u=this.applyFailoverHost(t.HLS_ONDEMAND||t.HLS);return(0,v.assertNonNullable)(o),new da({...n,source:o,sourceHls:u})}case"DASH_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return(0,v.assertNonNullable)(o),new pa({...n,source:o})}case"HLS":case"HLS_ONDEMAND":{let o=this.applyFailoverHost(t[e]);return(0,v.assertNonNullable)(o),Fr||!this.params.tuning.useHlsJs?new fa({...n,source:o}):new ha({...n,source:o})}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return(0,v.assertNonNullable)(o),new ma({...n,source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case"MPEG":{let o=this.applyFailoverHost(t[e]);return(0,v.assertNonNullable)(o),new ga({...n,source:o})}case"DASH_LIVE":{let o=this.applyFailoverHost(t[e]);return(0,v.assertNonNullable)(o),new af({...n,source:o,config:{...yw,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case"WEB_RTC_LIVE":{let o=this.applyFailoverHost(t[e]);return(0,v.assertNonNullable)(o),new Sa({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(0,v.assertNever)(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(0,v.assertNonNullable)(o),new Ti({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(0,v.assertNever)(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return(0,v.assertNever)(e)}}handleNoFormatsError(e){switch(e){case"SCREEN":this.noAvailableProvidersError$.next(this.params.tuning.forceFormat),this.current$.next({type:void 0});return;case"CHROMECAST":this.params.dependencies.chromecastInitializer.disconnect();return;default:return(0,v.assertNever)(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,Ag.default)((0,kg.default)(e).map(([a,s])=>[a,r(s)]))}initProviderErrorHandling(){let e=new v.Subscription,t=!1,r=0;return e.add((0,v.merge)(this.providerOutput.error$.pipe((0,v.filter)(a=>!this.params.tuning.ignoreAudioRendererError||!a.message||!/AUDIO_RENDERER_ERROR/ig.test(a.message))),Eg({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe((0,v.map)(a=>({id:`ProviderHangup:${a}`,category:v.ErrorCategory.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((0,v.filter)(({to:s})=>s==="playing"),(0,v.once)()).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===v.ErrorCategory.NETWORK,u=a.category===v.ErrorCategory.FATAL,l=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),c=r<this.params.tuning.providerErrorLimit&&!u,d=l&&!u&&(o&&t||!c);n={...n,isNetworkError:o,isFatalError:u,haveFailoverHost:l,tryFailover:d,canReinitProvider:c},c?(r++,this.reinitProvider()):d?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):this.switchToNextProvider(s??"SCREEN")}this.tracer.error("providerError",(0,v.flattenObject)(n))})),e}};var _=require("@vkontakte/videoplayer-shared");var Tw=5e3,wg="one_video_throughput",Rg="one_video_rtt",Ta=window.navigator.connection,$g=()=>{let i=Ta?.downlink;if((0,_.isNonNullable)(i)&&i!==10)return i*1e3},Lg=()=>{let i=Ta?.rtt;if((0,_.isNonNullable)(i)&&i!==3e3)return i},Mg=(i,e,t)=>{let r=t*8,a=r/i;return r/(a+e)},Ru=class i{constructor(e){this.subscription=new _.Subscription;this.concurrentDownloads=new Set;this.tuningConfig=e;let t=i.load(wg)||(e.useBrowserEstimation?$g():void 0)||Tw,r=i.load(Rg)??(e.useBrowserEstimation?Lg():void 0)??0;if(this.throughput$=new _.ValueSubject(t),this.rtt$=new _.ValueSubject(r),this.rttAdjustedThroughput$=new _.ValueSubject(Mg(t,r,e.rttPenaltyRequestSize)),this.throughput=ur.getSmoothedValue(t,-1,e),this.rtt=ur.getSmoothedValue(r,1,e),e.useBrowserEstimation){let a=()=>{let n=$g();n&&this.throughput.next(n);let o=Lg();(0,_.isNonNullable)(o)&&this.rtt.next(o)};Ta&&"onchange"in Ta&&this.subscription.add((0,_.fromEvent)(Ta,"change").subscribe(a)),a()}this.subscription.add(this.throughput.smoothed$.subscribe(a=>{_.safeStorage.set(wg,a.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(a=>{_.safeStorage.set(Rg,a.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add((0,_.combine)({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe((0,_.map)(({throughput:a,rtt:s})=>Mg(a,s,e.rttPenaltyRequestSize)),(0,_.filter)(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=(0,_.now)(),a=new _.Subscription;switch(this.subscription.add(a),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:a.add((0,_.fromEvent)(e,"progress").pipe((0,_.once)()).subscribe(s=>{t=s.loaded,r=(0,_.now)()}));break;case 1:case 0:a.add((0,_.fromEvent)(e,"loadstart").subscribe(()=>{t=0,r=(0,_.now)()}));break}a.add((0,_.fromEvent)(e,"loadend").subscribe(s=>{if(e.status===200){let n=s.loaded,o=(0,_.now)(),u=n-t,l=o-r;this.addRawSpeed(u,l,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=(0,_.now)(),n=0,o=(0,_.now)(),u=c=>{this.concurrentDownloads.delete(e),r.releaseLock(),e.cancel(`Throughput Estimator error: ${c}`).catch(()=>{})},l=async({done:c,value:d})=>{if(c)!t&&this.addRawSpeed(a,(0,_.now)()-s,1),this.concurrentDownloads.delete(e);else if(d){if(t){let h=(0,_.now)();if(h-o>this.tuningConfig.lowLatency.continuesByteSequenceInterval||h-s>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let b=o-s;b&&this.addRawSpeed(n,b,1,t),n=d.byteLength,s=(0,_.now)()}else n+=d.byteLength;o=(0,_.now)()}else a+=d.byteLength,n+=d.byteLength,n>=this.tuningConfig.streamMinSampleSize&&(0,_.now)()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,(0,_.now)()-o,this.concurrentDownloads.size),n=0,o=(0,_.now)());await r?.read().then(l,u)}};this.concurrentDownloads.add(e),r?.read().then(l,u)}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=_.safeStorage.get(e);if((0,_.isNonNullable)(t))return parseInt(t,10)??void 0}},Cg=Ru;var Ia=require("@vkontakte/videoplayer-shared"),Dg={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:2.8,bitrateAudioFactorAtEmptyBuffer:10,bitrateFactorAtFullBuffer:2,bitrateAudioFactorAtFullBuffer:7,minVideoAudioRatio:5,minAvailableThroughputAudioRatio:5,usePixelRatio:!0,pixelRatioMultiplier:void 0,pixelRatioLogBase:3,pixelRatioLogCoefficients:[1,0,1],limitByContainer:!0,containerSizeFactor:1.3,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldownIncreaseQuality:3e3,trackCooldownDecreaseQuality:3e3,backgroundVideoQualityLimit:Ia.VideoQuality.Q_4320P,activeVideoAreaThreshold:.1},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:Ia.VideoQuality.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,crashOnStallTWithoutDataTimeout:5e3,enableSubSegmentBufferFeeding:!0,bufferEmptinessTolerance:100,useFetchPriorityHints:!0,qualityLimitsOnStall:{stallDurationBeforeQualityDecrease:0,stallDurationNoDataBeforeQualityDecrease:0,stallCountBeforeQualityDecrease:0,resetQualityRestrictionTimeout:1e4},enableBaseUrlSupport:!0,maxSegmentRetryCount:5},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:250,playbackCatchupSpeedup:.05,isActiveOnDefault:!1,bufferEstimator:{emaAlpha:.45,changeThreshold:.05,deviationDepth:20,deviationFactor:.5,extremumInterval:5}}},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1,lowLatencyActiveLiveDelay:3e3,activeLiveDelay:5e3,maxPausedTime:5e3},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,forceFormat:void 0,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:"07A4434E",useWebmBigRequest:!1,webmCodec:"vp9",androidPreferredFormat:"dash",preferCMAF:!1,preferWebRTC:!1,preferMultiStream:!1,preferHDR:!1,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useHlsJs:!0,useNativeHLSTextTracks:!1,useManagedMediaSource:!0,useNewSwitchTo:!1,useSafariEndlessRequestBugfix:!0,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,manifestRetryInterval:300,manifestRetryMaxInterval:1e4,manifestRetryMaxCount:10,audioVideoSyncRate:20,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50},useVolumeMultiplier:!1,ignoreAudioRendererError:!1,useEnableSubtitlesParam:!1,useOldMSEDetection:!1,exposeInternalsToGlobal:!1},Vg=i=>({...(0,Ia.fillWithDefault)(i,Dg),configName:[...i.configName??[],...Dg.configName]});var p=require("@vkontakte/videoplayer-shared");var Rt=require("@vkontakte/videoplayer-shared"),$u=({seekState:i,position$:e})=>(0,Rt.merge)(i.stateChangeEnded$.pipe((0,Rt.map)(({to:t})=>t.state==="none"?void 0:(t.position??NaN)/1e3),(0,Rt.filter)(Rt.isNonNullable)),e.pipe((0,Rt.filter)(()=>i.getState().state==="none")));var Bg=require("@vkontakte/videoplayer-shared"),Og=i=>{let e=typeof i.container=="string"?document.getElementById(i.container):i.container;return(0,Bg.assertNonNullable)(e,`Wrong container or containerId {${i.container}}`),e};var Fs=require("@vkontakte/videoplayer-shared"),_g=(i,e,t,r)=>{i!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&t?.getValue().length===0?t.pipe((0,Fs.filter)(a=>a.length>0),(0,Fs.once)()).subscribe(a=>{a.find(r)&&e.startTransitionTo(i)}):(i===void 0||t?.getValue().find(r))&&e.startTransitionTo(i)};var Ea=class{constructor(e={configName:[]},t=p.Tracer.createRootTracer(!1)){this.subscription=new p.Subscription;this.logger=new p.Logger;this.abrLogger=this.logger.createComponentLog("ABR");this.internalsExposure=null;this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new p.ValueSubject(!1);this.hasLiveOffsetByPausedTimer=0;this.wasSetStartedQuality=!1;this.desiredState={playbackState:new q("stopped"),seekState:new q({state:"none"}),volume:new q({volume:1,muted:!1}),videoTrack:new q(void 0),videoStream:new q(void 0),audioStream:new q(void 0),autoVideoTrackSwitching:new q(!0),autoVideoTrackLimits:new q({}),isLooped:new q(!1),isLowLatency:new q(!1),playbackRate:new q(1),externalTextTracks:new q([]),internalTextTracks:new q([]),currentTextTrack:new q(void 0),textTrackCuesSettings:new q({}),cameraOrientation:new q({x:0,y:0})};this.info={playbackState$:new p.ValueSubject("stopped"),position$:new p.ValueSubject(0),duration$:new p.ValueSubject(1/0),muted$:new p.ValueSubject(!1),volume$:new p.ValueSubject(1),availableVideoStreams$:new p.ValueSubject([]),currentVideoStream$:new p.ValueSubject(void 0),availableQualities$:new p.ValueSubject([]),availableQualitiesFps$:new p.ValueSubject({}),currentQuality$:new p.ValueSubject(void 0),isAutoQualityEnabled$:new p.ValueSubject(!0),autoQualityLimitingAvailable$:new p.ValueSubject(!1),autoQualityLimits$:new p.ValueSubject({}),availableAudioStreams$:new p.ValueSubject([]),currentAudioStream$:new p.ValueSubject(void 0),availableAudioTracks$:new p.ValueSubject([]),isAudioAvailable$:new p.ValueSubject(!0),currentPlaybackRate$:new p.ValueSubject(1),currentBuffer$:new p.ValueSubject({start:0,end:0}),isBuffering$:new p.ValueSubject(!0),isStalled$:new p.ValueSubject(!1),isEnded$:new p.ValueSubject(!1),isLooped$:new p.ValueSubject(!1),isLive$:new p.ValueSubject(void 0),canChangePlaybackSpeed$:new p.ValueSubject(void 0),atLiveEdge$:new p.ValueSubject(void 0),atLiveDurationEdge$:new p.ValueSubject(void 0),liveTime$:new p.ValueSubject(void 0),liveBufferTime$:new p.ValueSubject(void 0),liveLatency$:new p.ValueSubject(void 0),currentFormat$:new p.ValueSubject(void 0),availableTextTracks$:new p.ValueSubject([]),currentTextTrack$:new p.ValueSubject(void 0),throughputEstimation$:new p.ValueSubject(void 0),rttEstimation$:new p.ValueSubject(void 0),videoBitrate$:new p.ValueSubject(void 0),hostname$:new p.ValueSubject(void 0),httpConnectionType$:new p.ValueSubject(void 0),httpConnectionReused$:new p.ValueSubject(void 0),surface$:new p.ValueSubject("none"),chromecastState$:new p.ValueSubject("NOT_AVAILABLE"),chromecastDeviceName$:new p.ValueSubject(void 0),intrinsicVideoSize$:new p.ValueSubject(void 0),availableSources$:new p.ValueSubject(void 0),is3DVideo$:new p.ValueSubject(!1),currentVideoSegmentLength$:new p.ValueSubject(0),currentAudioSegmentLength$:new p.ValueSubject(0)};this.events={inited$:new p.Subject,ready$:new p.Subject,started$:new p.Subject,playing$:new p.Subject,paused$:new p.Subject,stopped$:new p.Subject,willStart$:new p.Subject,willResume$:new p.Subject,willPause$:new p.Subject,willStop$:new p.Subject,willDestruct$:new p.Subject,watchCoverageRecord$:new p.Subject,watchCoverageLive$:new p.Subject,managedError$:new p.Subject,fatalError$:new p.Subject,ended$:new p.Subject,looped$:new p.Subject,seeked$:new p.Subject,willSeek$:new p.Subject,autoplaySoundProhibited$:new p.Subject,firstBytes$:new p.Subject,loadedMetadata$:new p.Subject,firstFrame$:new p.Subject,canplay$:new p.Subject,log$:new p.Subject};this.experimental={element$:new p.ValueSubject(void 0),tuningConfigName$:new p.ValueSubject([]),enableDebugTelemetry$:new p.ValueSubject(!1),dumpTelemetry:Um};if(this.initLogs(),this.tuning=Vg(e),this.tracer=t,this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new Oa({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new Cg(this.tuning.throughputEstimator),e.exposeInternalsToGlobal&&(this.internalsExposure=new p.InternalsExposure("CORE"),this.internalsExposure.expose({player:this})),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(u){let l=o.map(h=>JSON.stringify(h,(m,b)=>{let g=typeof b;return(0,Ng.default)(["number","string","boolean"],g)?b:b===null?null:`<${g}>`})),c=`Player.${String(a)}`,d=`Exception calling ${c} (${l.join(", ")})`;throw this.events.fatalError$.next({id:c,category:p.ErrorCategory.WTF,message:d,thrown:u}),u}}}})}initVideo(e){this.config=e;let{container:t,...r}=e;return this.tracer.log("initVideo",(0,p.flattenObject)(r)),this.domContainer=Og(e),this.chromecastInitializer.contentId=e.meta?.videoId,this.providerContainer=new ya({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.setLiveLowLatency(this.tuning.dashCmafLive.lowLatency.isActiveOnDefault),this.setMuted(this.tuning.isAudioDisabled),this.initDebugTelemetry(),this.initWakeLock(),this.internalsExposure?.expose({config:e,logger:this.logger,tuning:this.tuning}),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(),this.internalsExposure?.destroy()}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&&!wi()?(this.tracer.log("request play from hidden tab"),(0,p.fromEvent)(document,"visibilitychange").pipe((0,p.once)()).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){(0,p.assertNonNullable)(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.wasSetStartedQuality?this.providerContainer.providerOutput.availableVideoTracks$.pipe((0,p.filter)(r=>r.length>0),(0,p.once)()).subscribe(r=>{this.setVideoTrackIdByQuality(r,e)}):this.explicitInitialQuality=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",(0,p.flattenObject)(e)),this.desiredState.autoVideoTrackLimits.startTransitionTo(e),this}setPlaybackRate(e){(0,p.assertNonNullable)(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",(0,p.flattenObject)(e)),this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>({type:"external",...t}))),this}selectTextTrack(e){return _g(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}setLiveLowLatency(e){let t=this.info.isLive$.getValue(),r=this.desiredState.isLowLatency.getState();return!t||r===e?this:(this.tracer.log("live switch to low latency "+e),this.desiredState.isLowLatency.setState(e),this.seekTime(0))}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((0,p.isNullable)(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),r=t.state==="none"?void 0:t.position;return(0,p.isNonNullable)(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((0,p.merge)(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe((0,p.map)(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe((0,p.map)(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe((0,p.map)(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe((0,p.map)(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe((0,p.map)(e=>e.to)).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe((0,p.filter)(({from:e})=>e==="stopped"),(0,p.once)()).subscribe(()=>{this.initedAt=(0,p.now)(),this.events.inited$.next()})).add(this.desiredState.playbackState.stateChangeEnded$.subscribe(e=>{switch(e.to){case"ready":this.events.ready$.next();break;case"playing":this.isPlaybackStarted||this.events.started$.next(),this.isPlaybackStarted=!0,this.events.playing$.next();break;case"paused":this.events.paused$.next();break;case"stopped":this.events.stopped$.next()}})).add(this.desiredState.playbackState.stateChangeStarted$.subscribe(e=>{switch(e.to){case"paused":this.events.willPause$.next();break;case"playing":this.isPlaybackStarted?this.events.willResume$.next():this.events.willStart$.next();break;case"stopped":this.events.willStop$.next();break;default:}}))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();this.tracer.log("willSeekEvent",(0,p.flattenObject)(n)),n.state==="requested"?this.desiredState.seekState.setState({...n,state:"applying"}):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:p.ErrorCategory.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.soundProhibitedEvent$.pipe((0,p.once)()).subscribe(this.events.autoplaySoundProhibited$)).add(e.providerOutput.seekedEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();this.tracer.log("seekedEvent",(0,p.flattenObject)(n)),n.state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe((0,p.map)(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe((0,p.map)(n=>n.destination),(0,p.filterChanged)()).subscribe(()=>this.isPlaybackStarted=!1)).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add((0,p.combine)({availableVideoTracks:e.providerOutput.availableVideoTracks$,currentVideoStream:e.providerOutput.currentVideoStream$}).pipe((0,p.map)(({availableVideoTracks:n,currentVideoStream:o})=>n.filter(u=>o?o.id===u.streamId:!0).map(({quality:u})=>u).sort((u,l)=>(0,p.isInvariantQuality)(u)?1:(0,p.isInvariantQuality)(l)?-1:(0,p.isHigher)(l,u)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(n=>{let o={};for(let u of n)u.fps&&(o[u.quality]=u.fps);this.info.availableQualitiesFps$.next(o)})).add(e.providerOutput.availableAudioStreams$.subscribe(this.info.availableAudioStreams$)).add(e.providerOutput.currentVideoStream$.subscribe(this.info.currentVideoStream$)).add(e.providerOutput.currentAudioStream$.subscribe(this.info.currentAudioStream$)).add(e.providerOutput.availableAudioTracks$.subscribe(this.info.availableAudioTracks$)).add(e.providerOutput.isAudioAvailable$.pipe((0,p.filterChanged)()).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((0,p.filterChanged)((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.pipe((0,p.filterChanged)((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe((0,p.filterChanged)()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe((0,p.filterChanged)()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe((0,p.filterChanged)()).subscribe(this.info.httpConnectionReused$)).add(e.providerOutput.currentTextTrack$.subscribe(this.info.currentTextTrack$)).add(e.providerOutput.availableTextTracks$.subscribe(this.info.availableTextTracks$)).add(e.providerOutput.autoVideoTrackLimitingAvailable$.subscribe(this.info.autoQualityLimitingAvailable$)).add(e.providerOutput.autoVideoTrackLimits$.subscribe(n=>{this.desiredState.autoVideoTrackLimits.setState(n??{})})).add(e.providerOutput.currentBuffer$.pipe((0,p.map)(n=>n?{start:n.from,end:n.to}:{start:0,end:0})).subscribe(this.info.currentBuffer$)).add(e.providerOutput.duration$.subscribe(this.info.duration$)).add(e.providerOutput.isBuffering$.subscribe(this.info.isBuffering$)).add(e.providerOutput.isLive$.subscribe(this.info.isLive$)).add(e.providerOutput.canChangePlaybackSpeed$.subscribe(this.info.canChangePlaybackSpeed$)).add(e.providerOutput.liveTime$.subscribe(this.info.liveTime$)).add(e.providerOutput.liveBufferTime$.subscribe(this.info.liveBufferTime$)).add(e.providerOutput.liveLatency$.subscribe(this.info.liveLatency$)).add((0,p.combine)({hasLiveOffsetByPaused:(0,p.merge)(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe((0,p.map)(n=>n.to),(0,p.filterChanged)(),(0,p.map)(n=>n==="paused")),isLowLatency:e.providerOutput.isLowLatency$}).subscribe(({hasLiveOffsetByPaused:n,isLowLatency:o})=>{if(window.clearTimeout(this.hasLiveOffsetByPausedTimer),n){this.hasLiveOffsetByPausedTimer=window.setTimeout(()=>{this.hasLiveOffsetByPaused.next(!0)},this.getActiveLiveDelay(o));return}this.hasLiveOffsetByPaused.next(!1)})).add((0,p.combine)({atLiveEdge:(0,p.combine)({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:$u({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe((0,p.map)(({isLive:n,position:o,isLowLatency:u})=>{let l=this.getActiveLiveDelay(u);return n&&Math.abs(o)<l/1e3}),(0,p.filterChanged)(),(0,p.tap)(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe((0,p.map)(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add((0,p.combine)({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe((0,p.map)(({isLive:n,position:o,duration:u})=>n&&(Math.abs(u)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),(0,p.filterChanged)(),(0,p.tap)(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe((0,p.map)(n=>n.muted),(0,p.filterChanged)()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe((0,p.map)(n=>n.volume),(0,p.filterChanged)()).subscribe(this.info.volume$)).add($u({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add((0,p.merge)(e.providerOutput.endedEvent$.pipe((0,p.mapTo)(!0)),e.providerOutput.seekedEvent$.pipe((0,p.mapTo)(!1))).pipe((0,p.filterChanged)()).subscribe(this.info.isEnded$)).add(e.providerOutput.endedEvent$.subscribe(this.events.ended$)).add(e.providerOutput.loopedEvent$.subscribe(this.events.looped$)).add(e.providerError$.subscribe(this.events.managedError$)).add(e.volumeMultiplierError$.subscribe(this.events.managedError$)).add(e.noAvailableProvidersError$.pipe((0,p.map)(n=>({id:n?`No${n}`:"NoProviders",category:p.ErrorCategory.VIDEO_PIPELINE,message:n?`${n} was forced but failed or not available`:"No suitable providers or all providers failed"}))).subscribe(this.events.fatalError$)).add(e.providerOutput.element$.subscribe(this.experimental.element$)).add(e.providerOutput.firstBytesEvent$.pipe((0,p.once)(),(0,p.map)(n=>n??(0,p.now)()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe((0,p.once)(),(0,p.map)(()=>(0,p.now)()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe((0,p.once)(),(0,p.map)(()=>(0,p.now)()-this.initedAt)).subscribe(this.events.canplay$)).add(this.throughputEstimator.throughput$.subscribe(this.info.throughputEstimation$)).add(this.throughputEstimator.rtt$.subscribe(this.info.rttEstimation$)).add(e.providerOutput.availableSources$.subscribe(this.info.availableSources$));let t=new p.ValueSubject(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let r=new p.ValueSubject(!0);this.subscription.add(e.current$.subscribe(()=>r.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe((0,p.filter)(({to:n})=>n==="playing"),(0,p.once)()).subscribe(()=>r.next(!1)));let a=0,s=(0,p.merge)(e.providerOutput.isBuffering$,t,r).pipe((0,p.map)(()=>{let n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||r.getValue();return n&&!o}),(0,p.filterChanged)());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((0,p.merge)(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{let n=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:n?.videoWidth,height:n?.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{let o=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:n?.size?.width,height:n?.size?.height},{width:o?.videoWidth,height:o?.videoHeight})})).add(e.providerOutput.is3DVideo$.subscribe(this.info.is3DVideo$)),this.subscription.add((0,p.merge)(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,e.providerOutput.elementVisible$,this.chromecastInitializer.castState$).subscribe(()=>{let n=e.providerOutput.inPiP$.getValue(),o=e.providerOutput.inFullscreen$.getValue(),u=e.providerOutput.element$.getValue(),l=e.providerOutput.elementVisible$.getValue(),c=this.chromecastInitializer.castState$.getValue(),d;c==="CONNECTED"?d="second_screen":u?l?n?d="pip":o?d="fullscreen":d="inline":d="invisible":d="none",this.info.surface$.getValue()!==d&&this.info.surface$.next(d)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe((0,p.map)(e=>e?.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){let t=new p.Subscription;this.subscription.add(t),this.subscription.add(e.current$.pipe((0,p.filterChanged)((r,a)=>r.provider===a.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe((0,p.filter)(r=>r.length>0),(0,p.once)()).subscribe(r=>{this.setStartingVideoTrack(r)}))}))}setStartingVideoTrack(e){let t;this.wasSetStartedQuality=!0;let r=this.explicitInitialQuality??this.desiredState.videoTrack.getState()?.quality;r&&(t=e.find(({quality:a})=>a===r),t||this.setAutoQuality(!0)),t||(t=Ft(e,{container:this.domContainer.getBoundingClientRect(),estimatedThroughput:this.throughputEstimator.throughput$.getValue(),tuning:this.tuning.autoTrackSelection,limits:this.desiredState.autoVideoTrackLimits.getState(),playbackRate:this.info.currentPlaybackRate$.getValue(),forwardBufferHealth:0,abrLogger:this.abrLogger})),this.desiredState.videoTrack.startTransitionTo(t),this.info.currentQuality$.next(t.quality),this.info.videoBitrate$.next(t.bitrate)}initLogs(){this.subscription.add((0,p.merge)(this.desiredState.videoTrack.stateChangeStarted$.pipe((0,p.map)(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe((0,p.map)(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe((0,p.map)(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe((0,p.map)(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe((0,p.map)(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe((0,p.map)(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe((0,p.map)(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe((0,p.map)(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe((0,p.map)(e=>({component:"desiredState",message:`[${e.entity} change] ${e.type}: ${JSON.stringify(e.transition)}`}))).subscribe(this.logger.log)),this.subscription.add(this.logger.log$.subscribe(this.events.log$))}initDebugTelemetry(){let e=this.providerContainer?.providerOutput;(0,p.assertNonNullable)(this.providerContainer),(0,p.assertNonNullable)(e),qm(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(t=>Fm(t)),this.providerContainer.current$.subscribe(({type:t})=>Ei("provider",t)),e.duration$.subscribe(t=>Ei("duration",t)),e.availableVideoTracks$.pipe((0,p.filter)(t=>!!t.length),(0,p.once)()).subscribe(t=>Ei("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((0,p.map)(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)),Ei("codecs",Rf())}initTracerSubscription(){let e=(0,p.getTraceSubscriptionMethod)(this.tracer.log.bind(this.tracer)),t=(0,p.getTraceSubscriptionMethod)(this.tracer.error.bind(this.tracer));this.subscription.add(this.info.playbackState$.subscribe(e("playbackState"))).add(this.info.isLooped$.subscribe(e("isLooped"))).add(this.info.currentPlaybackRate$.pipe((0,p.filterChanged)()).subscribe(e("currentPlaybackRate"))).add(this.info.isAutoQualityEnabled$.subscribe(e("isAutoQualityEnabled"))).add(this.info.autoQualityLimits$.subscribe(e("autoQualityLimits"))).add(this.info.currentFormat$.subscribe(e("currentFormat"))).add(this.info.availableQualities$.subscribe(e("availableQualities"))).add(this.info.availableQualitiesFps$.subscribe(e("availableQualitiesFps"))).add(this.info.availableAudioTracks$.subscribe(e("availableAudioTracks"))).add(this.info.isAudioAvailable$.subscribe(e("isAudioAvailable"))).add((0,p.combine)({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe((0,p.filter)(({currentQuality:r,videoBitrate:a})=>!!r&&!!a),(0,p.filterChanged)((r,a)=>r.currentQuality===a.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe((0,p.filter)(r=>r>0),(0,p.filterChanged)()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe((0,p.filter)(r=>r>0),(0,p.filterChanged)()).subscribe(e("currentAudioSegmentLength"))).add(this.info.hostname$.subscribe(e("hostname"))).add(this.info.currentTextTrack$.subscribe(e("currentTextTrack"))).add(this.info.availableTextTracks$.subscribe(e("availableTextTracks"))).add(this.info.autoQualityLimitingAvailable$.subscribe(e("autoQualityLimitingAvailable"))).add((0,p.combine)({currentBuffer:this.info.currentBuffer$.pipe((0,p.filter)(r=>r.end>0),(0,p.filterChanged)((r,a)=>r.end===a.end&&r.start===a.start)),position:this.info.position$.pipe((0,p.filterChanged)())}).pipe((0,p.throttle)(1e3)).subscribe(e("currentBufferAndPosition"))).add(this.info.duration$.pipe((0,p.filterChanged)()).subscribe(e("duration"))).add(this.info.isBuffering$.subscribe(e("isBuffering"))).add(this.info.isLive$.pipe((0,p.filterChanged)()).subscribe(e("isLive"))).add(this.info.canChangePlaybackSpeed$.pipe((0,p.filterChanged)()).subscribe(e("canChangePlaybackSpeed"))).add((0,p.combine)({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe((0,p.filter)(({liveTime:r,liveBufferTime:a})=>!!r&&!!a),(0,p.throttle)(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe((0,p.filterChanged)(),(0,p.filter)(r=>r===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe((0,p.filterChanged)(),(0,p.filter)(r=>r===!0)).subscribe(e("atLiveDurationEdge"))).add(this.info.muted$.pipe((0,p.filterChanged)()).subscribe(e("muted"))).add(this.info.volume$.pipe((0,p.filterChanged)()).subscribe(e("volume"))).add(this.info.isEnded$.pipe((0,p.filterChanged)(),(0,p.filter)(r=>r===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add((0,p.combine)({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe((0,p.filter)(({throughputEstimation:r,rtt:a})=>!!r&&!!a),(0,p.throttle)(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe((0,p.filterChanged)(),(0,p.filter)(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:p.ErrorCategory.DOM,message:String(a)})})};this.subscription.add((0,p.merge)((0,p.fromEvent)(document,"visibilitychange"),(0,p.fromEvent)(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",(0,p.flattenObject)({quality:t,availableTracks:(0,p.flattenObject)(e),track:(0,p.flattenObject)(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}};var pt=require("@vkontakte/videoplayer-shared"),Iw=`@vkontakte/videoplayer-core@${Us}`;