@vkontakte/videoplayer-core 2.0.119-dev.76657cc8.0 → 2.0.119-dev.df6b2fd8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/esnext.esm.js CHANGED
@@ -1,51 +1,51 @@
1
1
  /**
2
- * @vkontakte/videoplayer-core v2.0.119-dev.76657cc8.0
3
- * Thu, 05 Dec 2024 09:23:06 GMT
2
+ * @vkontakte/videoplayer-core v2.0.119-dev.df6b2fd8.0
3
+ * Sun, 08 Dec 2024 16:20:23 GMT
4
4
  * https://st.mycdn.me/static/vkontakte-videoplayer/2-0-119/doc/
5
5
  */
6
- var ry=Object.create;var Al=Object.defineProperty;var iy=Object.getOwnPropertyDescriptor;var ay=Object.getOwnPropertyNames;var sy=Object.getPrototypeOf,ny=Object.prototype.hasOwnProperty;var m=(i,e)=>()=>(e||i((e={exports:{}}).exports,e),e.exports);var oy=(i,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of ay(e))!ny.call(i,a)&&a!==t&&Al(i,a,{get:()=>e[a],enumerable:!(r=iy(e,a))||r.enumerable});return i};var C=(i,e,t)=>(t=i!=null?ry(sy(i)):{},oy(e||!i||!i.__esModule?Al(t,"default",{value:i,enumerable:!0}):t,i));var Q=m((pn,wl)=>{"use strict";var zr=function(i){return i&&i.Math===Math&&i};wl.exports=zr(typeof globalThis=="object"&&globalThis)||zr(typeof window=="object"&&window)||zr(typeof self=="object"&&self)||zr(typeof global=="object"&&global)||zr(typeof pn=="object"&&pn)||function(){return this}()||Function("return this")()});var ie=m((k0,Rl)=>{"use strict";Rl.exports=function(i){try{return!!i()}catch{return!0}}});var Kr=m((w0,$l)=>{"use strict";var uy=ie();$l.exports=!uy(function(){var i=function(){}.bind();return typeof i!="function"||i.hasOwnProperty("prototype")})});var hn=m((R0,Dl)=>{"use strict";var ly=Kr(),Cl=Function.prototype,Ll=Cl.apply,Ml=Cl.call;Dl.exports=typeof Reflect=="object"&&Reflect.apply||(ly?Ml.bind(Ll):function(){return Ml.apply(Ll,arguments)})});var J=m(($0,Ol)=>{"use strict";var Vl=Kr(),Bl=Function.prototype,mn=Bl.call,cy=Vl&&Bl.bind.bind(mn,mn);Ol.exports=Vl?cy:function(i){return function(){return mn.apply(i,arguments)}}});var Nt=m((L0,Nl)=>{"use strict";var _l=J(),dy=_l({}.toString),py=_l("".slice);Nl.exports=function(i){return py(dy(i),8,-1)}});var fn=m((M0,Fl)=>{"use strict";var hy=Nt(),my=J();Fl.exports=function(i){if(hy(i)==="Function")return my(i)}});var G=m((C0,ql)=>{"use strict";var bn=typeof document=="object"&&document.all;ql.exports=typeof bn>"u"&&bn!==void 0?function(i){return typeof i=="function"||i===bn}:function(i){return typeof i=="function"}});var Ie=m((D0,Ul)=>{"use strict";var fy=ie();Ul.exports=!fy(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var Ee=m((V0,Hl)=>{"use strict";var by=Kr(),Oa=Function.prototype.call;Hl.exports=by?Oa.bind(Oa):function(){return Oa.apply(Oa,arguments)}});var gn=m(Ql=>{"use strict";var jl={}.propertyIsEnumerable,Gl=Object.getOwnPropertyDescriptor,gy=Gl&&!jl.call({1:2},1);Ql.f=gy?function(e){var t=Gl(this,e);return!!t&&t.enumerable}:jl});var Jr=m((O0,Wl)=>{"use strict";Wl.exports=function(i,e){return{enumerable:!(i&1),configurable:!(i&2),writable:!(i&4),value:e}}});var zl=m((_0,Yl)=>{"use strict";var Sy=J(),vy=ie(),yy=Nt(),Sn=Object,Ty=Sy("".split);Yl.exports=vy(function(){return!Sn("z").propertyIsEnumerable(0)})?function(i){return yy(i)==="String"?Ty(i,""):Sn(i)}:Sn});var hr=m((N0,Kl)=>{"use strict";Kl.exports=function(i){return i==null}});var St=m((F0,Jl)=>{"use strict";var Iy=hr(),Ey=TypeError;Jl.exports=function(i){if(Iy(i))throw new Ey("Can't call method on "+i);return i}});var Ft=m((q0,Xl)=>{"use strict";var xy=zl(),Py=St();Xl.exports=function(i){return xy(Py(i))}});var xe=m((U0,Zl)=>{"use strict";var Ay=G();Zl.exports=function(i){return typeof i=="object"?i!==null:Ay(i)}});var mr=m((H0,ec)=>{"use strict";ec.exports={}});var at=m((j0,rc)=>{"use strict";var vn=mr(),yn=Q(),ky=G(),tc=function(i){return ky(i)?i:void 0};rc.exports=function(i,e){return arguments.length<2?tc(vn[i])||tc(yn[i]):vn[i]&&vn[i][e]||yn[i]&&yn[i][e]}});var Xr=m((G0,ic)=>{"use strict";var wy=J();ic.exports=wy({}.isPrototypeOf)});var qt=m((Q0,nc)=>{"use strict";var Ry=Q(),ac=Ry.navigator,sc=ac&&ac.userAgent;nc.exports=sc?String(sc):""});var In=m((W0,pc)=>{"use strict";var dc=Q(),Tn=qt(),oc=dc.process,uc=dc.Deno,lc=oc&&oc.versions||uc&&uc.version,cc=lc&&lc.v8,_e,_a;cc&&(_e=cc.split("."),_a=_e[0]>0&&_e[0]<4?1:+(_e[0]+_e[1]));!_a&&Tn&&(_e=Tn.match(/Edge\/(\d+)/),(!_e||_e[1]>=74)&&(_e=Tn.match(/Chrome\/(\d+)/),_e&&(_a=+_e[1])));pc.exports=_a});var En=m((Y0,mc)=>{"use strict";var hc=In(),$y=ie(),Ly=Q(),My=Ly.String;mc.exports=!!Object.getOwnPropertySymbols&&!$y(function(){var i=Symbol("symbol detection");return!My(i)||!(Object(i)instanceof Symbol)||!Symbol.sham&&hc&&hc<41})});var xn=m((z0,fc)=>{"use strict";var Cy=En();fc.exports=Cy&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var Pn=m((K0,bc)=>{"use strict";var Dy=at(),Vy=G(),By=Xr(),Oy=xn(),_y=Object;bc.exports=Oy?function(i){return typeof i=="symbol"}:function(i){var e=Dy("Symbol");return Vy(e)&&By(e.prototype,_y(i))}});var Zr=m((J0,gc)=>{"use strict";var Ny=String;gc.exports=function(i){try{return Ny(i)}catch{return"Object"}}});var Ye=m((X0,Sc)=>{"use strict";var Fy=G(),qy=Zr(),Uy=TypeError;Sc.exports=function(i){if(Fy(i))return i;throw new Uy(qy(i)+" is not a function")}});var ei=m((Z0,vc)=>{"use strict";var Hy=Ye(),jy=hr();vc.exports=function(i,e){var t=i[e];return jy(t)?void 0:Hy(t)}});var Tc=m((eC,yc)=>{"use strict";var An=Ee(),kn=G(),wn=xe(),Gy=TypeError;yc.exports=function(i,e){var t,r;if(e==="string"&&kn(t=i.toString)&&!wn(r=An(t,i))||kn(t=i.valueOf)&&!wn(r=An(t,i))||e!=="string"&&kn(t=i.toString)&&!wn(r=An(t,i)))return r;throw new Gy("Can't convert object to primitive value")}});var Ne=m((tC,Ic)=>{"use strict";Ic.exports=!0});var Pc=m((rC,xc)=>{"use strict";var Ec=Q(),Qy=Object.defineProperty;xc.exports=function(i,e){try{Qy(Ec,i,{value:e,configurable:!0,writable:!0})}catch{Ec[i]=e}return e}});var ti=m((iC,wc)=>{"use strict";var Wy=Ne(),Yy=Q(),zy=Pc(),Ac="__core-js_shared__",kc=wc.exports=Yy[Ac]||zy(Ac,{});(kc.versions||(kc.versions=[])).push({version:"3.38.0",mode:Wy?"pure":"global",copyright:"\xA9 2014-2024 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.38.0/LICENSE",source:"https://github.com/zloirock/core-js"})});var Rn=m((aC,$c)=>{"use strict";var Rc=ti();$c.exports=function(i,e){return Rc[i]||(Rc[i]=e||{})}});var fr=m((sC,Lc)=>{"use strict";var Ky=St(),Jy=Object;Lc.exports=function(i){return Jy(Ky(i))}});var Fe=m((nC,Mc)=>{"use strict";var Xy=J(),Zy=fr(),eT=Xy({}.hasOwnProperty);Mc.exports=Object.hasOwn||function(e,t){return eT(Zy(e),t)}});var $n=m((oC,Cc)=>{"use strict";var tT=J(),rT=0,iT=Math.random(),aT=tT(1 .toString);Cc.exports=function(i){return"Symbol("+(i===void 0?"":i)+")_"+aT(++rT+iT,36)}});var ae=m((uC,Vc)=>{"use strict";var sT=Q(),nT=Rn(),Dc=Fe(),oT=$n(),uT=En(),lT=xn(),br=sT.Symbol,Ln=nT("wks"),cT=lT?br.for||br:br&&br.withoutSetter||oT;Vc.exports=function(i){return Dc(Ln,i)||(Ln[i]=uT&&Dc(br,i)?br[i]:cT("Symbol."+i)),Ln[i]}});var Nc=m((lC,_c)=>{"use strict";var dT=Ee(),Bc=xe(),Oc=Pn(),pT=ei(),hT=Tc(),mT=ae(),fT=TypeError,bT=mT("toPrimitive");_c.exports=function(i,e){if(!Bc(i)||Oc(i))return i;var t=pT(i,bT),r;if(t){if(e===void 0&&(e="default"),r=dT(t,i,e),!Bc(r)||Oc(r))return r;throw new fT("Can't convert object to primitive value")}return e===void 0&&(e="number"),hT(i,e)}});var Mn=m((cC,Fc)=>{"use strict";var gT=Nc(),ST=Pn();Fc.exports=function(i){var e=gT(i,"string");return ST(e)?e:e+""}});var Na=m((dC,Uc)=>{"use strict";var vT=Q(),qc=xe(),Cn=vT.document,yT=qc(Cn)&&qc(Cn.createElement);Uc.exports=function(i){return yT?Cn.createElement(i):{}}});var Dn=m((pC,Hc)=>{"use strict";var TT=Ie(),IT=ie(),ET=Na();Hc.exports=!TT&&!IT(function(){return Object.defineProperty(ET("div"),"a",{get:function(){return 7}}).a!==7})});var Qc=m(Gc=>{"use strict";var xT=Ie(),PT=Ee(),AT=gn(),kT=Jr(),wT=Ft(),RT=Mn(),$T=Fe(),LT=Dn(),jc=Object.getOwnPropertyDescriptor;Gc.f=xT?jc:function(e,t){if(e=wT(e),t=RT(t),LT)try{return jc(e,t)}catch{}if($T(e,t))return kT(!PT(AT.f,e,t),e[t])}});var Vn=m((mC,Wc)=>{"use strict";var MT=ie(),CT=G(),DT=/#|\.prototype\./,ri=function(i,e){var t=BT[VT(i)];return t===_T?!0:t===OT?!1:CT(e)?MT(e):!!e},VT=ri.normalize=function(i){return String(i).replace(DT,".").toLowerCase()},BT=ri.data={},OT=ri.NATIVE="N",_T=ri.POLYFILL="P";Wc.exports=ri});var gr=m((fC,zc)=>{"use strict";var Yc=fn(),NT=Ye(),FT=Kr(),qT=Yc(Yc.bind);zc.exports=function(i,e){return NT(i),e===void 0?i:FT?qT(i,e):function(){return i.apply(e,arguments)}}});var Bn=m((bC,Kc)=>{"use strict";var UT=Ie(),HT=ie();Kc.exports=UT&&HT(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var ze=m((gC,Jc)=>{"use strict";var jT=xe(),GT=String,QT=TypeError;Jc.exports=function(i){if(jT(i))return i;throw new QT(GT(i)+" is not an object")}});var Ut=m(Zc=>{"use strict";var WT=Ie(),YT=Dn(),zT=Bn(),Fa=ze(),Xc=Mn(),KT=TypeError,On=Object.defineProperty,JT=Object.getOwnPropertyDescriptor,_n="enumerable",Nn="configurable",Fn="writable";Zc.f=WT?zT?function(e,t,r){if(Fa(e),t=Xc(t),Fa(r),typeof e=="function"&&t==="prototype"&&"value"in r&&Fn in r&&!r[Fn]){var a=JT(e,t);a&&a[Fn]&&(e[t]=r.value,r={configurable:Nn in r?r[Nn]:a[Nn],enumerable:_n in r?r[_n]:a[_n],writable:!1})}return On(e,t,r)}:On:function(e,t,r){if(Fa(e),t=Xc(t),Fa(r),YT)try{return On(e,t,r)}catch{}if("get"in r||"set"in r)throw new KT("Accessors not supported");return"value"in r&&(e[t]=r.value),e}});var Sr=m((vC,ed)=>{"use strict";var XT=Ie(),ZT=Ut(),eI=Jr();ed.exports=XT?function(i,e,t){return ZT.f(i,e,eI(1,t))}:function(i,e,t){return i[e]=t,i}});var z=m((yC,rd)=>{"use strict";var ii=Q(),tI=hn(),rI=fn(),iI=G(),aI=Qc().f,sI=Vn(),vr=mr(),nI=gr(),yr=Sr(),td=Fe();ti();var oI=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 tI(i,this,arguments)};return e.prototype=i.prototype,e};rd.exports=function(i,e){var t=i.target,r=i.global,a=i.stat,s=i.proto,n=r?ii:a?ii[t]:ii[t]&&ii[t].prototype,o=r?vr:vr[t]||yr(vr,t,{})[t],u=o.prototype,l,c,d,p,h,f,b,g,S;for(p in e)l=sI(r?p:t+(a?".":"#")+p,i.forced),c=!l&&n&&td(n,p),f=o[p],c&&(i.dontCallGetSet?(S=aI(n,p),b=S&&S.value):b=n[p]),h=c&&b?b:e[p],!(!l&&!s&&typeof f==typeof h)&&(i.bind&&c?g=nI(h,ii):i.wrap&&c?g=oI(h):s&&iI(h)?g=rI(h):g=h,(i.sham||h&&h.sham||f&&f.sham)&&yr(g,"sham",!0),yr(o,p,g),s&&(d=t+"Prototype",td(vr,d)||yr(vr,d,{}),yr(vr[d],p,h),i.real&&u&&(l||!u[p])&&yr(u,p,h)))}});var ad=m((TC,id)=>{"use strict";var uI=Math.ceil,lI=Math.floor;id.exports=Math.trunc||function(e){var t=+e;return(t>0?lI:uI)(t)}});var ai=m((IC,sd)=>{"use strict";var cI=ad();sd.exports=function(i){var e=+i;return e!==e||e===0?0:cI(e)}});var od=m((EC,nd)=>{"use strict";var dI=ai(),pI=Math.max,hI=Math.min;nd.exports=function(i,e){var t=dI(i);return t<0?pI(t+e,0):hI(t,e)}});var qn=m((xC,ud)=>{"use strict";var mI=ai(),fI=Math.min;ud.exports=function(i){var e=mI(i);return e>0?fI(e,9007199254740991):0}});var Tr=m((PC,ld)=>{"use strict";var bI=qn();ld.exports=function(i){return bI(i.length)}});var Un=m((AC,dd)=>{"use strict";var gI=Ft(),SI=od(),vI=Tr(),cd=function(i){return function(e,t,r){var a=gI(e),s=vI(a);if(s===0)return!i&&-1;var n=SI(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}};dd.exports={includes:cd(!0),indexOf:cd(!1)}});var si=m((kC,pd)=>{"use strict";pd.exports=function(){}});var hd=m(()=>{"use strict";var yI=z(),TI=Un().includes,II=ie(),EI=si(),xI=II(function(){return!Array(1).includes()});yI({target:"Array",proto:!0,forced:xI},{includes:function(e){return TI(this,e,arguments.length>1?arguments[1]:void 0)}});EI("includes")});var vt=m(($C,md)=>{"use strict";var PI=at();md.exports=PI});var bd=m((LC,fd)=>{"use strict";hd();var AI=vt();fd.exports=AI("Array","includes")});var Sd=m((MC,gd)=>{"use strict";var kI=bd();gd.exports=kI});var Ke=m((CC,vd)=>{"use strict";var wI=Sd();vd.exports=wI});var Ha=m((GC,kd)=>{"use strict";var BI=Rn(),OI=$n(),Ad=BI("keys");kd.exports=function(i){return Ad[i]||(Ad[i]=OI(i))}});var Rd=m((QC,wd)=>{"use strict";var _I=ie();wd.exports=!_I(function(){function i(){}return i.prototype.constructor=null,Object.getPrototypeOf(new i)!==i.prototype})});var ja=m((WC,Ld)=>{"use strict";var NI=Fe(),FI=G(),qI=fr(),UI=Ha(),HI=Rd(),$d=UI("IE_PROTO"),Gn=Object,jI=Gn.prototype;Ld.exports=HI?Gn.getPrototypeOf:function(i){var e=qI(i);if(NI(e,$d))return e[$d];var t=e.constructor;return FI(t)&&e instanceof t?t.prototype:e instanceof Gn?jI:null}});var Ga=m((YC,Md)=>{"use strict";Md.exports={}});var Vd=m((zC,Dd)=>{"use strict";var GI=J(),Qn=Fe(),QI=Ft(),WI=Un().indexOf,YI=Ga(),Cd=GI([].push);Dd.exports=function(i,e){var t=QI(i),r=0,a=[],s;for(s in t)!Qn(YI,s)&&Qn(t,s)&&Cd(a,s);for(;e.length>r;)Qn(t,s=e[r++])&&(~WI(a,s)||Cd(a,s));return a}});var Wn=m((KC,Bd)=>{"use strict";Bd.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var Yn=m((JC,Od)=>{"use strict";var zI=Vd(),KI=Wn();Od.exports=Object.keys||function(e){return zI(e,KI)}});var zn=m((XC,Ud)=>{"use strict";var Nd=Ie(),JI=ie(),Fd=J(),XI=ja(),ZI=Yn(),eE=Ft(),tE=gn().f,qd=Fd(tE),rE=Fd([].push),iE=Nd&&JI(function(){var i=Object.create(null);return i[2]=2,!qd(i,2)}),_d=function(i){return function(e){for(var t=eE(e),r=ZI(t),a=iE&&XI(t)===null,s=r.length,n=0,o=[],u;s>n;)u=r[n++],(!Nd||(a?u in t:qd(t,u)))&&rE(o,i?[u,t[u]]:t[u]);return o}};Ud.exports={entries:_d(!0),values:_d(!1)}});var Hd=m(()=>{"use strict";var aE=z(),sE=zn().entries;aE({target:"Object",stat:!0},{entries:function(e){return sE(e)}})});var Gd=m((tD,jd)=>{"use strict";Hd();var nE=mr();jd.exports=nE.Object.entries});var Wd=m((rD,Qd)=>{"use strict";var oE=Gd();Qd.exports=oE});var Ir=m((iD,Yd)=>{"use strict";var uE=Wd();Yd.exports=uE});var Ht=m((aD,zd)=>{"use strict";zd.exports={}});var Xd=m((sD,Jd)=>{"use strict";var lE=Q(),cE=G(),Kd=lE.WeakMap;Jd.exports=cE(Kd)&&/native code/.test(String(Kd))});var Zn=m((nD,tp)=>{"use strict";var dE=Xd(),ep=Q(),pE=xe(),hE=Sr(),Kn=Fe(),Jn=ti(),mE=Ha(),fE=Ga(),Zd="Object already initialized",Xn=ep.TypeError,bE=ep.WeakMap,Qa,ni,Wa,gE=function(i){return Wa(i)?ni(i):Qa(i,{})},SE=function(i){return function(e){var t;if(!pE(e)||(t=ni(e)).type!==i)throw new Xn("Incompatible receiver, "+i+" required");return t}};dE||Jn.state?(qe=Jn.state||(Jn.state=new bE),qe.get=qe.get,qe.has=qe.has,qe.set=qe.set,Qa=function(i,e){if(qe.has(i))throw new Xn(Zd);return e.facade=i,qe.set(i,e),e},ni=function(i){return qe.get(i)||{}},Wa=function(i){return qe.has(i)}):(jt=mE("state"),fE[jt]=!0,Qa=function(i,e){if(Kn(i,jt))throw new Xn(Zd);return e.facade=i,hE(i,jt,e),e},ni=function(i){return Kn(i,jt)?i[jt]:{}},Wa=function(i){return Kn(i,jt)});var qe,jt;tp.exports={set:Qa,get:ni,has:Wa,enforce:gE,getterFor:SE}});var ro=m((oD,ip)=>{"use strict";var eo=Ie(),vE=Fe(),rp=Function.prototype,yE=eo&&Object.getOwnPropertyDescriptor,to=vE(rp,"name"),TE=to&&function(){}.name==="something",IE=to&&(!eo||eo&&yE(rp,"name").configurable);ip.exports={EXISTS:to,PROPER:TE,CONFIGURABLE:IE}});var sp=m(ap=>{"use strict";var EE=Ie(),xE=Bn(),PE=Ut(),AE=ze(),kE=Ft(),wE=Yn();ap.f=EE&&!xE?Object.defineProperties:function(e,t){AE(e);for(var r=kE(t),a=wE(t),s=a.length,n=0,o;s>n;)PE.f(e,o=a[n++],r[o]);return e}});var io=m((lD,np)=>{"use strict";var RE=at();np.exports=RE("document","documentElement")});var oo=m((cD,hp)=>{"use strict";var $E=ze(),LE=sp(),op=Wn(),ME=Ga(),CE=io(),DE=Na(),VE=Ha(),up=">",lp="<",so="prototype",no="script",dp=VE("IE_PROTO"),ao=function(){},pp=function(i){return lp+no+up+i+lp+"/"+no+up},cp=function(i){i.write(pp("")),i.close();var e=i.parentWindow.Object;return i=null,e},BE=function(){var i=DE("iframe"),e="java"+no+":",t;return i.style.display="none",CE.appendChild(i),i.src=String(e),t=i.contentWindow.document,t.open(),t.write(pp("document.F=Object")),t.close(),t.F},Ya,za=function(){try{Ya=new ActiveXObject("htmlfile")}catch{}za=typeof document<"u"?document.domain&&Ya?cp(Ya):BE():cp(Ya);for(var i=op.length;i--;)delete za[so][op[i]];return za()};ME[dp]=!0;hp.exports=Object.create||function(e,t){var r;return e!==null?(ao[so]=$E(e),r=new ao,ao[so]=null,r[dp]=e):r=za(),t===void 0?r:LE.f(r,t)}});var Er=m((dD,mp)=>{"use strict";var OE=Sr();mp.exports=function(i,e,t,r){return r&&r.enumerable?i[e]=t:OE(i,e,t),i}});var po=m((pD,gp)=>{"use strict";var _E=ie(),NE=G(),FE=xe(),qE=oo(),fp=ja(),UE=Er(),HE=ae(),jE=Ne(),co=HE("iterator"),bp=!1,st,uo,lo;[].keys&&(lo=[].keys(),"next"in lo?(uo=fp(fp(lo)),uo!==Object.prototype&&(st=uo)):bp=!0);var GE=!FE(st)||_E(function(){var i={};return st[co].call(i)!==i});GE?st={}:jE&&(st=qE(st));NE(st[co])||UE(st,co,function(){return this});gp.exports={IteratorPrototype:st,BUGGY_SAFARI_ITERATORS:bp}});var Ka=m((hD,vp)=>{"use strict";var QE=ae(),WE=QE("toStringTag"),Sp={};Sp[WE]="z";vp.exports=String(Sp)==="[object z]"});var oi=m((mD,yp)=>{"use strict";var YE=Ka(),zE=G(),Ja=Nt(),KE=ae(),JE=KE("toStringTag"),XE=Object,ZE=Ja(function(){return arguments}())==="Arguments",ex=function(i,e){try{return i[e]}catch{}};yp.exports=YE?Ja:function(i){var e,t,r;return i===void 0?"Undefined":i===null?"Null":typeof(t=ex(e=XE(i),JE))=="string"?t:ZE?Ja(e):(r=Ja(e))==="Object"&&zE(e.callee)?"Arguments":r}});var Ip=m((fD,Tp)=>{"use strict";var tx=Ka(),rx=oi();Tp.exports=tx?{}.toString:function(){return"[object "+rx(this)+"]"}});var ui=m((bD,xp)=>{"use strict";var ix=Ka(),ax=Ut().f,sx=Sr(),nx=Fe(),ox=Ip(),ux=ae(),Ep=ux("toStringTag");xp.exports=function(i,e,t,r){var a=t?i:i&&i.prototype;a&&(nx(a,Ep)||ax(a,Ep,{configurable:!0,value:e}),r&&!ix&&sx(a,"toString",ox))}});var Ap=m((gD,Pp)=>{"use strict";var lx=po().IteratorPrototype,cx=oo(),dx=Jr(),px=ui(),hx=Ht(),mx=function(){return this};Pp.exports=function(i,e,t,r){var a=e+" Iterator";return i.prototype=cx(lx,{next:dx(+!r,t)}),px(i,a,!1,!0),hx[a]=mx,i}});var wp=m((SD,kp)=>{"use strict";var fx=J(),bx=Ye();kp.exports=function(i,e,t){try{return fx(bx(Object.getOwnPropertyDescriptor(i,e)[t]))}catch{}}});var $p=m((vD,Rp)=>{"use strict";var gx=xe();Rp.exports=function(i){return gx(i)||i===null}});var Mp=m((yD,Lp)=>{"use strict";var Sx=$p(),vx=String,yx=TypeError;Lp.exports=function(i){if(Sx(i))return i;throw new yx("Can't set "+vx(i)+" as a prototype")}});var ho=m((TD,Cp)=>{"use strict";var Tx=wp(),Ix=xe(),Ex=St(),xx=Mp();Cp.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var i=!1,e={},t;try{t=Tx(Object.prototype,"__proto__","set"),t(e,[]),i=e instanceof Array}catch{}return function(a,s){return Ex(a),xx(s),Ix(a)&&(i?t(a,s):a.__proto__=s),a}}():void 0)});var jp=m((ID,Hp)=>{"use strict";var Px=z(),Ax=Ee(),Xa=Ne(),qp=ro(),kx=G(),wx=Ap(),Dp=ja(),Vp=ho(),Rx=ui(),$x=Sr(),mo=Er(),Lx=ae(),Bp=Ht(),Up=po(),Mx=qp.PROPER,Cx=qp.CONFIGURABLE,Op=Up.IteratorPrototype,Za=Up.BUGGY_SAFARI_ITERATORS,li=Lx("iterator"),_p="keys",ci="values",Np="entries",Fp=function(){return this};Hp.exports=function(i,e,t,r,a,s,n){wx(t,e,r);var o=function(S){if(S===a&&p)return p;if(!Za&&S&&S in c)return c[S];switch(S){case _p:return function(){return new t(this,S)};case ci:return function(){return new t(this,S)};case Np:return function(){return new t(this,S)}}return function(){return new t(this)}},u=e+" Iterator",l=!1,c=i.prototype,d=c[li]||c["@@iterator"]||a&&c[a],p=!Za&&d||o(a),h=e==="Array"&&c.entries||d,f,b,g;if(h&&(f=Dp(h.call(new i)),f!==Object.prototype&&f.next&&(!Xa&&Dp(f)!==Op&&(Vp?Vp(f,Op):kx(f[li])||mo(f,li,Fp)),Rx(f,u,!0,!0),Xa&&(Bp[u]=Fp))),Mx&&a===ci&&d&&d.name!==ci&&(!Xa&&Cx?$x(c,"name",ci):(l=!0,p=function(){return Ax(d,this)})),a)if(b={values:o(ci),keys:s?p:o(_p),entries:o(Np)},n)for(g in b)(Za||l||!(g in c))&&mo(c,g,b[g]);else Px({target:e,proto:!0,forced:Za||l},b);return(!Xa||n)&&c[li]!==p&&mo(c,li,p,{name:a}),Bp[e]=p,b}});var Qp=m((ED,Gp)=>{"use strict";Gp.exports=function(i,e){return{value:i,done:e}}});var bo=m((xD,Jp)=>{"use strict";var Dx=Ft(),fo=si(),Wp=Ht(),zp=Zn(),Vx=Ut().f,Bx=jp(),es=Qp(),Ox=Ne(),_x=Ie(),Kp="Array Iterator",Nx=zp.set,Fx=zp.getterFor(Kp);Jp.exports=Bx(Array,"Array",function(i,e){Nx(this,{type:Kp,target:Dx(i),index:0,kind:e})},function(){var i=Fx(this),e=i.target,t=i.index++;if(!e||t>=e.length)return i.target=void 0,es(void 0,!0);switch(i.kind){case"keys":return es(t,!1);case"values":return es(e[t],!1)}return es([t,e[t]],!1)},"values");var Yp=Wp.Arguments=Wp.Array;fo("keys");fo("values");fo("entries");if(!Ox&&_x&&Yp.name!=="values")try{Vx(Yp,"name",{value:"values"})}catch{}});var Zp=m((PD,Xp)=>{"use strict";var qx=ae(),Ux=Ht(),Hx=qx("iterator"),jx=Array.prototype;Xp.exports=function(i){return i!==void 0&&(Ux.Array===i||jx[Hx]===i)}});var go=m((AD,th)=>{"use strict";var Gx=oi(),eh=ei(),Qx=hr(),Wx=Ht(),Yx=ae(),zx=Yx("iterator");th.exports=function(i){if(!Qx(i))return eh(i,zx)||eh(i,"@@iterator")||Wx[Gx(i)]}});var ih=m((kD,rh)=>{"use strict";var Kx=Ee(),Jx=Ye(),Xx=ze(),Zx=Zr(),eP=go(),tP=TypeError;rh.exports=function(i,e){var t=arguments.length<2?eP(i):e;if(Jx(t))return Xx(Kx(t,i));throw new tP(Zx(i)+" is not iterable")}});var nh=m((wD,sh)=>{"use strict";var rP=Ee(),ah=ze(),iP=ei();sh.exports=function(i,e,t){var r,a;ah(i);try{if(r=iP(i,"return"),!r){if(e==="throw")throw t;return t}r=rP(r,i)}catch(s){a=!0,r=s}if(e==="throw")throw t;if(a)throw r;return ah(r),t}});var rs=m((RD,ch)=>{"use strict";var aP=gr(),sP=Ee(),nP=ze(),oP=Zr(),uP=Zp(),lP=Tr(),oh=Xr(),cP=ih(),dP=go(),uh=nh(),pP=TypeError,ts=function(i,e){this.stopped=i,this.result=e},lh=ts.prototype;ch.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=aP(e,r),l,c,d,p,h,f,b,g=function(A){return l&&uh(l,"normal",A),new ts(!0,A)},S=function(A){return a?(nP(A),o?u(A[0],A[1],g):u(A[0],A[1])):o?u(A,g):u(A)};if(s)l=i.iterator;else if(n)l=i;else{if(c=dP(i),!c)throw new pP(oP(i)+" is not iterable");if(uP(c)){for(d=0,p=lP(i);p>d;d++)if(h=S(i[d]),h&&oh(lh,h))return h;return new ts(!1)}l=cP(i,c)}for(f=s?i.next:l.next;!(b=sP(f,l)).done;){try{h=S(b.value)}catch(A){uh(l,"throw",A)}if(typeof h=="object"&&h&&oh(lh,h))return h}return new ts(!1)}});var ph=m(($D,dh)=>{"use strict";var hP=Ie(),mP=Ut(),fP=Jr();dh.exports=function(i,e,t){hP?mP.f(i,e,fP(0,t)):i[e]=t}});var hh=m(()=>{"use strict";var bP=z(),gP=rs(),SP=ph();bP({target:"Object",stat:!0},{fromEntries:function(e){var t={};return gP(e,function(r,a){SP(t,r,a)},{AS_ENTRIES:!0}),t}})});var fh=m((CD,mh)=>{"use strict";bo();hh();var vP=mr();mh.exports=vP.Object.fromEntries});var gh=m((DD,bh)=>{"use strict";bh.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 vh=m(()=>{"use strict";bo();var yP=gh(),TP=Q(),IP=ui(),Sh=Ht();for(is in yP)IP(TP[is],is),Sh[is]=Sh.Array;var is});var Th=m((OD,yh)=>{"use strict";var EP=fh();vh();yh.exports=EP});var So=m((_D,Ih)=>{"use strict";var xP=Th();Ih.exports=xP});var Eh=m(()=>{"use strict"});var vo=m((qD,xh)=>{"use strict";var di=Q(),PP=qt(),AP=Nt(),as=function(i){return PP.slice(0,i.length)===i};xh.exports=function(){return as("Bun/")?"BUN":as("Cloudflare-Workers")?"CLOUDFLARE":as("Deno/")?"DENO":as("Node.js/")?"NODE":di.Bun&&typeof Bun.version=="string"?"BUN":di.Deno&&typeof Deno.version=="object"?"DENO":AP(di.process)==="process"?"NODE":di.window&&di.document?"BROWSER":"REST"}()});var ss=m((UD,Ph)=>{"use strict";var kP=vo();Ph.exports=kP==="NODE"});var kh=m((HD,Ah)=>{"use strict";var wP=Ut();Ah.exports=function(i,e,t){return wP.f(i,e,t)}});var $h=m((jD,Rh)=>{"use strict";var RP=at(),$P=kh(),LP=ae(),MP=Ie(),wh=LP("species");Rh.exports=function(i){var e=RP(i);MP&&e&&!e[wh]&&$P(e,wh,{configurable:!0,get:function(){return this}})}});var Mh=m((GD,Lh)=>{"use strict";var CP=Xr(),DP=TypeError;Lh.exports=function(i,e){if(CP(e,i))return i;throw new DP("Incorrect invocation")}});var To=m((QD,Ch)=>{"use strict";var VP=J(),BP=G(),yo=ti(),OP=VP(Function.toString);BP(yo.inspectSource)||(yo.inspectSource=function(i){return OP(i)});Ch.exports=yo.inspectSource});var Eo=m((WD,_h)=>{"use strict";var _P=J(),NP=ie(),Dh=G(),FP=oi(),qP=at(),UP=To(),Vh=function(){},Bh=qP("Reflect","construct"),Io=/^\s*(?:class|function)\b/,HP=_P(Io.exec),jP=!Io.test(Vh),pi=function(e){if(!Dh(e))return!1;try{return Bh(Vh,[],e),!0}catch{return!1}},Oh=function(e){if(!Dh(e))return!1;switch(FP(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return jP||!!HP(Io,UP(e))}catch{return!0}};Oh.sham=!0;_h.exports=!Bh||NP(function(){var i;return pi(pi.call)||!pi(Object)||!pi(function(){i=!0})||i})?Oh:pi});var Fh=m((YD,Nh)=>{"use strict";var GP=Eo(),QP=Zr(),WP=TypeError;Nh.exports=function(i){if(GP(i))return i;throw new WP(QP(i)+" is not a constructor")}});var xo=m((zD,Uh)=>{"use strict";var qh=ze(),YP=Fh(),zP=hr(),KP=ae(),JP=KP("species");Uh.exports=function(i,e){var t=qh(i).constructor,r;return t===void 0||zP(r=qh(t)[JP])?e:YP(r)}});var jh=m((KD,Hh)=>{"use strict";var XP=J();Hh.exports=XP([].slice)});var Qh=m((JD,Gh)=>{"use strict";var ZP=TypeError;Gh.exports=function(i,e){if(i<e)throw new ZP("Not enough arguments");return i}});var Po=m((XD,Wh)=>{"use strict";var eA=qt();Wh.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(eA)});var Do=m((ZD,rm)=>{"use strict";var Pe=Q(),tA=hn(),rA=gr(),Yh=G(),iA=Fe(),tm=ie(),zh=io(),aA=jh(),Kh=Na(),sA=Qh(),nA=Po(),oA=ss(),Lo=Pe.setImmediate,Mo=Pe.clearImmediate,uA=Pe.process,Ao=Pe.Dispatch,lA=Pe.Function,Jh=Pe.MessageChannel,cA=Pe.String,ko=0,hi={},Xh="onreadystatechange",mi,Gt,wo,Ro;tm(function(){mi=Pe.location});var Co=function(i){if(iA(hi,i)){var e=hi[i];delete hi[i],e()}},$o=function(i){return function(){Co(i)}},Zh=function(i){Co(i.data)},em=function(i){Pe.postMessage(cA(i),mi.protocol+"//"+mi.host)};(!Lo||!Mo)&&(Lo=function(e){sA(arguments.length,1);var t=Yh(e)?e:lA(e),r=aA(arguments,1);return hi[++ko]=function(){tA(t,void 0,r)},Gt(ko),ko},Mo=function(e){delete hi[e]},oA?Gt=function(i){uA.nextTick($o(i))}:Ao&&Ao.now?Gt=function(i){Ao.now($o(i))}:Jh&&!nA?(wo=new Jh,Ro=wo.port2,wo.port1.onmessage=Zh,Gt=rA(Ro.postMessage,Ro)):Pe.addEventListener&&Yh(Pe.postMessage)&&!Pe.importScripts&&mi&&mi.protocol!=="file:"&&!tm(em)?(Gt=em,Pe.addEventListener("message",Zh,!1)):Xh in Kh("script")?Gt=function(i){zh.appendChild(Kh("script"))[Xh]=function(){zh.removeChild(this),Co(i)}}:Gt=function(i){setTimeout($o(i),0)});rm.exports={set:Lo,clear:Mo}});var sm=m((eV,am)=>{"use strict";var im=Q(),dA=Ie(),pA=Object.getOwnPropertyDescriptor;am.exports=function(i){if(!dA)return im[i];var e=pA(im,i);return e&&e.value}});var Vo=m((tV,om)=>{"use strict";var nm=function(){this.head=null,this.tail=null};nm.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}}};om.exports=nm});var lm=m((rV,um)=>{"use strict";var hA=qt();um.exports=/ipad|iphone|ipod/i.test(hA)&&typeof Pebble<"u"});var dm=m((iV,cm)=>{"use strict";var mA=qt();cm.exports=/web0s(?!.*chrome)/i.test(mA)});var Sm=m((aV,gm)=>{"use strict";var Pr=Q(),fA=sm(),pm=gr(),Bo=Do().set,bA=Vo(),gA=Po(),SA=lm(),vA=dm(),Oo=ss(),hm=Pr.MutationObserver||Pr.WebKitMutationObserver,mm=Pr.document,fm=Pr.process,ns=Pr.Promise,Fo=fA("queueMicrotask"),xr,_o,No,os,bm;Fo||(fi=new bA,bi=function(){var i,e;for(Oo&&(i=fm.domain)&&i.exit();e=fi.get();)try{e()}catch(t){throw fi.head&&xr(),t}i&&i.enter()},!gA&&!Oo&&!vA&&hm&&mm?(_o=!0,No=mm.createTextNode(""),new hm(bi).observe(No,{characterData:!0}),xr=function(){No.data=_o=!_o}):!SA&&ns&&ns.resolve?(os=ns.resolve(void 0),os.constructor=ns,bm=pm(os.then,os),xr=function(){bm(bi)}):Oo?xr=function(){fm.nextTick(bi)}:(Bo=pm(Bo,Pr),xr=function(){Bo(bi)}),Fo=function(i){fi.head||xr(),fi.add(i)});var fi,bi;gm.exports=Fo});var ym=m((sV,vm)=>{"use strict";vm.exports=function(i,e){try{arguments.length===1?console.error(i):console.error(i,e)}catch{}}});var us=m((nV,Tm)=>{"use strict";Tm.exports=function(i){try{return{error:!1,value:i()}}catch(e){return{error:!0,value:e}}}});var Qt=m((oV,Im)=>{"use strict";var yA=Q();Im.exports=yA.Promise});var Ar=m((uV,Am)=>{"use strict";var TA=Q(),gi=Qt(),IA=G(),EA=Vn(),xA=To(),PA=ae(),Em=vo(),AA=Ne(),qo=In(),xm=gi&&gi.prototype,kA=PA("species"),Uo=!1,Pm=IA(TA.PromiseRejectionEvent),wA=EA("Promise",function(){var i=xA(gi),e=i!==String(gi);if(!e&&qo===66||AA&&!(xm.catch&&xm.finally))return!0;if(!qo||qo<51||!/native code/.test(i)){var t=new gi(function(s){s(1)}),r=function(s){s(function(){},function(){})},a=t.constructor={};if(a[kA]=r,Uo=t.then(function(){})instanceof r,!Uo)return!0}return!e&&(Em==="BROWSER"||Em==="DENO")&&!Pm});Am.exports={CONSTRUCTOR:wA,REJECTION_EVENT:Pm,SUBCLASSING:Uo}});var kr=m((lV,wm)=>{"use strict";var km=Ye(),RA=TypeError,$A=function(i){var e,t;this.promise=new i(function(r,a){if(e!==void 0||t!==void 0)throw new RA("Bad Promise constructor");e=r,t=a}),this.resolve=km(e),this.reject=km(t)};wm.exports.f=function(i){return new $A(i)}});var Wm=m(()=>{"use strict";var LA=z(),MA=Ne(),ps=ss(),yt=Q(),Lr=Ee(),Rm=Er(),$m=ho(),CA=ui(),DA=$h(),VA=Ye(),ds=G(),BA=xe(),OA=Mh(),_A=xo(),Vm=Do().set,Wo=Sm(),NA=ym(),FA=us(),qA=Vo(),Bm=Zn(),hs=Qt(),Yo=Ar(),Om=kr(),ms="Promise",_m=Yo.CONSTRUCTOR,UA=Yo.REJECTION_EVENT,HA=Yo.SUBCLASSING,Ho=Bm.getterFor(ms),jA=Bm.set,wr=hs&&hs.prototype,Wt=hs,ls=wr,Nm=yt.TypeError,jo=yt.document,zo=yt.process,Go=Om.f,GA=Go,QA=!!(jo&&jo.createEvent&&yt.dispatchEvent),Fm="unhandledrejection",WA="rejectionhandled",Lm=0,qm=1,YA=2,Ko=1,Um=2,cs,Mm,zA,Cm,Hm=function(i){var e;return BA(i)&&ds(e=i.then)?e:!1},jm=function(i,e){var t=e.value,r=e.state===qm,a=r?i.ok:i.fail,s=i.resolve,n=i.reject,o=i.domain,u,l,c;try{a?(r||(e.rejection===Um&&JA(e),e.rejection=Ko),a===!0?u=t:(o&&o.enter(),u=a(t),o&&(o.exit(),c=!0)),u===i.promise?n(new Nm("Promise-chain cycle")):(l=Hm(u))?Lr(l,u,s,n):s(u)):n(t)}catch(d){o&&!c&&o.exit(),n(d)}},Gm=function(i,e){i.notified||(i.notified=!0,Wo(function(){for(var t=i.reactions,r;r=t.get();)jm(r,i);i.notified=!1,e&&!i.rejection&&KA(i)}))},Qm=function(i,e,t){var r,a;QA?(r=jo.createEvent("Event"),r.promise=e,r.reason=t,r.initEvent(i,!1,!0),yt.dispatchEvent(r)):r={promise:e,reason:t},!UA&&(a=yt["on"+i])?a(r):i===Fm&&NA("Unhandled promise rejection",t)},KA=function(i){Lr(Vm,yt,function(){var e=i.facade,t=i.value,r=Dm(i),a;if(r&&(a=FA(function(){ps?zo.emit("unhandledRejection",t,e):Qm(Fm,e,t)}),i.rejection=ps||Dm(i)?Um:Ko,a.error))throw a.value})},Dm=function(i){return i.rejection!==Ko&&!i.parent},JA=function(i){Lr(Vm,yt,function(){var e=i.facade;ps?zo.emit("rejectionHandled",e):Qm(WA,e,i.value)})},Rr=function(i,e,t){return function(r){i(e,r,t)}},$r=function(i,e,t){i.done||(i.done=!0,t&&(i=t),i.value=e,i.state=YA,Gm(i,!0))},Qo=function(i,e,t){if(!i.done){i.done=!0,t&&(i=t);try{if(i.facade===e)throw new Nm("Promise can't be resolved itself");var r=Hm(e);r?Wo(function(){var a={done:!1};try{Lr(r,e,Rr(Qo,a,i),Rr($r,a,i))}catch(s){$r(a,s,i)}}):(i.value=e,i.state=qm,Gm(i,!1))}catch(a){$r({done:!1},a,i)}}};if(_m&&(Wt=function(e){OA(this,ls),VA(e),Lr(cs,this);var t=Ho(this);try{e(Rr(Qo,t),Rr($r,t))}catch(r){$r(t,r)}},ls=Wt.prototype,cs=function(e){jA(this,{type:ms,done:!1,notified:!1,parent:!1,reactions:new qA,rejection:!1,state:Lm,value:void 0})},cs.prototype=Rm(ls,"then",function(e,t){var r=Ho(this),a=Go(_A(this,Wt));return r.parent=!0,a.ok=ds(e)?e:!0,a.fail=ds(t)&&t,a.domain=ps?zo.domain:void 0,r.state===Lm?r.reactions.add(a):Wo(function(){jm(a,r)}),a.promise}),Mm=function(){var i=new cs,e=Ho(i);this.promise=i,this.resolve=Rr(Qo,e),this.reject=Rr($r,e)},Om.f=Go=function(i){return i===Wt||i===zA?new Mm(i):GA(i)},!MA&&ds(hs)&&wr!==Object.prototype)){Cm=wr.then,HA||Rm(wr,"then",function(e,t){var r=this;return new Wt(function(a,s){Lr(Cm,r,a,s)}).then(e,t)},{unsafe:!0});try{delete wr.constructor}catch{}$m&&$m(wr,ls)}LA({global:!0,constructor:!0,wrap:!0,forced:_m},{Promise:Wt});CA(Wt,ms,!1,!0);DA(ms)});var Xm=m((pV,Jm)=>{"use strict";var XA=ae(),zm=XA("iterator"),Km=!1;try{Ym=0,Jo={next:function(){return{done:!!Ym++}},return:function(){Km=!0}},Jo[zm]=function(){return this},Array.from(Jo,function(){throw 2})}catch{}var Ym,Jo;Jm.exports=function(i,e){try{if(!e&&!Km)return!1}catch{return!1}var t=!1;try{var r={};r[zm]=function(){return{next:function(){return{done:t=!0}}}},i(r)}catch{}return t}});var Xo=m((hV,Zm)=>{"use strict";var ZA=Qt(),ek=Xm(),tk=Ar().CONSTRUCTOR;Zm.exports=tk||!ek(function(i){ZA.all(i).then(void 0,function(){})})});var ef=m(()=>{"use strict";var rk=z(),ik=Ee(),ak=Ye(),sk=kr(),nk=us(),ok=rs(),uk=Xo();rk({target:"Promise",stat:!0,forced:uk},{all:function(e){var t=this,r=sk.f(t),a=r.resolve,s=r.reject,n=nk(function(){var o=ak(t.resolve),u=[],l=0,c=1;ok(e,function(d){var p=l++,h=!1;c++,ik(o,t,d).then(function(f){h||(h=!0,u[p]=f,--c||a(u))},s)}),--c||a(u)});return n.error&&s(n.value),r.promise}})});var rf=m(()=>{"use strict";var lk=z(),ck=Ne(),dk=Ar().CONSTRUCTOR,eu=Qt(),pk=at(),hk=G(),mk=Er(),tf=eu&&eu.prototype;lk({target:"Promise",proto:!0,forced:dk,real:!0},{catch:function(i){return this.then(void 0,i)}});!ck&&hk(eu)&&(Zo=pk("Promise").prototype.catch,tf.catch!==Zo&&mk(tf,"catch",Zo,{unsafe:!0}));var Zo});var af=m(()=>{"use strict";var fk=z(),bk=Ee(),gk=Ye(),Sk=kr(),vk=us(),yk=rs(),Tk=Xo();fk({target:"Promise",stat:!0,forced:Tk},{race:function(e){var t=this,r=Sk.f(t),a=r.reject,s=vk(function(){var n=gk(t.resolve);yk(e,function(o){bk(n,t,o).then(r.resolve,a)})});return s.error&&a(s.value),r.promise}})});var sf=m(()=>{"use strict";var Ik=z(),Ek=kr(),xk=Ar().CONSTRUCTOR;Ik({target:"Promise",stat:!0,forced:xk},{reject:function(e){var t=Ek.f(this),r=t.reject;return r(e),t.promise}})});var tu=m((IV,nf)=>{"use strict";var Pk=ze(),Ak=xe(),kk=kr();nf.exports=function(i,e){if(Pk(i),Ak(e)&&e.constructor===i)return e;var t=kk.f(i),r=t.resolve;return r(e),t.promise}});var lf=m(()=>{"use strict";var wk=z(),Rk=at(),of=Ne(),$k=Qt(),uf=Ar().CONSTRUCTOR,Lk=tu(),Mk=Rk("Promise"),Ck=of&&!uf;wk({target:"Promise",stat:!0,forced:of||uf},{resolve:function(e){return Lk(Ck&&this===Mk?$k:this,e)}})});var cf=m(()=>{"use strict";Wm();ef();rf();af();sf();lf()});var mf=m(()=>{"use strict";var Dk=z(),Vk=Ne(),fs=Qt(),Bk=ie(),pf=at(),hf=G(),Ok=xo(),df=tu(),_k=Er(),iu=fs&&fs.prototype,Nk=!!fs&&Bk(function(){iu.finally.call({then:function(){}},function(){})});Dk({target:"Promise",proto:!0,real:!0,forced:Nk},{finally:function(i){var e=Ok(this,pf("Promise")),t=hf(i);return this.then(t?function(r){return df(e,i()).then(function(){return r})}:i,t?function(r){return df(e,i()).then(function(){throw r})}:i)}});!Vk&&hf(fs)&&(ru=pf("Promise").prototype.finally,iu.finally!==ru&&_k(iu,"finally",ru,{unsafe:!0}));var ru});var bf=m((RV,ff)=>{"use strict";Eh();cf();mf();var Fk=vt();ff.exports=Fk("Promise","finally")});var Sf=m(($V,gf)=>{"use strict";var qk=bf();gf.exports=qk});var bs=m((LV,vf)=>{"use strict";var Uk=Sf();vf.exports=Uk});var Mf=m(()=>{"use strict";var rw=z(),iw=zn().values;rw({target:"Object",stat:!0},{values:function(e){return iw(e)}})});var Df=m((fB,Cf)=>{"use strict";Mf();var aw=mr();Cf.exports=aw.Object.values});var Bf=m((bB,Vf)=>{"use strict";var sw=Df();Vf.exports=sw});var vi=m((gB,Of)=>{"use strict";var nw=Bf();Of.exports=nw});var Kf=m(()=>{"use strict";var Iw=z(),Ew=fr(),xw=Tr(),Pw=ai(),Aw=si();Iw({target:"Array",proto:!0},{at:function(e){var t=Ew(this),r=xw(t),a=Pw(e),s=a>=0?a:r+a;return s<0||s>=r?void 0:t[s]}});Aw("at")});var Xf=m((GB,Jf)=>{"use strict";Kf();var kw=vt();Jf.exports=kw("Array","at")});var eb=m((QB,Zf)=>{"use strict";var ww=Xf();Zf.exports=ww});var Dr=m((WB,tb)=>{"use strict";var Rw=eb();tb.exports=Rw});var Au=m((v_,Lb)=>{"use strict";var cR=Nt();Lb.exports=Array.isArray||function(e){return cR(e)==="Array"}});var Cb=m((y_,Mb)=>{"use strict";var dR=TypeError,pR=9007199254740991;Mb.exports=function(i){if(i>pR)throw dR("Maximum allowed index exceeded");return i}});var Bb=m((T_,Vb)=>{"use strict";var hR=Au(),mR=Tr(),fR=Cb(),bR=gr(),Db=function(i,e,t,r,a,s,n,o){for(var u=a,l=0,c=n?bR(n,o):!1,d,p;l<r;)l in t&&(d=c?c(t[l],l,e):t[l],s>0&&hR(d)?(p=mR(d),u=Db(i,e,d,p,u,s-1)-1):(fR(u+1),i[u]=d),u++),l++;return u};Vb.exports=Db});var Fb=m((I_,Nb)=>{"use strict";var Ob=Au(),gR=Eo(),SR=xe(),vR=ae(),yR=vR("species"),_b=Array;Nb.exports=function(i){var e;return Ob(i)&&(e=i.constructor,gR(e)&&(e===_b||Ob(e.prototype))?e=void 0:SR(e)&&(e=e[yR],e===null&&(e=void 0))),e===void 0?_b:e}});var Ub=m((E_,qb)=>{"use strict";var TR=Fb();qb.exports=function(i,e){return new(TR(i))(e===0?0:e)}});var Hb=m(()=>{"use strict";var IR=z(),ER=Bb(),xR=Ye(),PR=fr(),AR=Tr(),kR=Ub();IR({target:"Array",proto:!0},{flatMap:function(e){var t=PR(this),r=AR(t),a;return xR(e),a=kR(t,0),a.length=ER(a,t,t,r,0,1,e,arguments.length>1?arguments[1]:void 0),a}})});var jb=m(()=>{"use strict";var wR=si();wR("flatMap")});var Qb=m((w_,Gb)=>{"use strict";Hb();jb();var RR=vt();Gb.exports=RR("Array","flatMap")});var Yb=m((R_,Wb)=>{"use strict";var $R=Qb();Wb.exports=$R});var ku=m(($_,zb)=>{"use strict";var LR=Yb();zb.exports=LR});var Ci=m((F_,sg)=>{"use strict";var NR=oi(),FR=String;sg.exports=function(i){if(NR(i)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return FR(i)}});var Ru=m((q_,ng)=>{"use strict";ng.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 lg=m((U_,ug)=>{"use strict";var qR=J(),UR=St(),HR=Ci(),Lu=Ru(),og=qR("".replace),jR=RegExp("^["+Lu+"]+"),GR=RegExp("(^|[^"+Lu+"])["+Lu+"]+$"),$u=function(i){return function(e){var t=HR(UR(e));return i&1&&(t=og(t,jR,"")),i&2&&(t=og(t,GR,"$1")),t}};ug.exports={start:$u(1),end:$u(2),trim:$u(3)}});var hg=m((H_,pg)=>{"use strict";var QR=ro().PROPER,WR=ie(),cg=Ru(),dg="\u200B\x85\u180E";pg.exports=function(i){return WR(function(){return!!cg[i]()||dg[i]()!==dg||QR&&cg[i].name!==i})}});var Mu=m((j_,mg)=>{"use strict";var YR=lg().start,zR=hg();mg.exports=zR("trimStart")?function(){return YR(this)}:"".trimStart});var bg=m(()=>{"use strict";var KR=z(),fg=Mu();KR({target:"String",proto:!0,name:"trimStart",forced:"".trimLeft!==fg},{trimLeft:fg})});var Sg=m(()=>{"use strict";bg();var JR=z(),gg=Mu();JR({target:"String",proto:!0,name:"trimStart",forced:"".trimStart!==gg},{trimStart:gg})});var yg=m((z_,vg)=>{"use strict";Sg();var XR=vt();vg.exports=XR("String","trimLeft")});var Ig=m((K_,Tg)=>{"use strict";var ZR=yg();Tg.exports=ZR});var xg=m((J_,Eg)=>{"use strict";var e$=Ig();Eg.exports=e$});var Fg=m(()=>{"use strict"});var qg=m(()=>{"use strict"});var Hg=m((Tq,Ug)=>{"use strict";var E$=xe(),x$=Nt(),P$=ae(),A$=P$("match");Ug.exports=function(i){var e;return E$(i)&&((e=i[A$])!==void 0?!!e:x$(i)==="RegExp")}});var Gg=m((Iq,jg)=>{"use strict";var k$=ze();jg.exports=function(){var i=k$(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 Yg=m((Eq,Wg)=>{"use strict";var w$=Ee(),R$=Fe(),$$=Xr(),L$=Gg(),Qg=RegExp.prototype;Wg.exports=function(i){var e=i.flags;return e===void 0&&!("flags"in Qg)&&!R$(i,"flags")&&$$(Qg,i)?w$(L$,i):e}});var Kg=m((xq,zg)=>{"use strict";var qu=J(),M$=fr(),C$=Math.floor,Nu=qu("".charAt),D$=qu("".replace),Fu=qu("".slice),V$=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,B$=/\$([$&'`]|\d{1,2})/g;zg.exports=function(i,e,t,r,a,s){var n=t+i.length,o=r.length,u=B$;return a!==void 0&&(a=M$(a),u=V$),D$(s,u,function(l,c){var d;switch(Nu(c,0)){case"$":return"$";case"&":return i;case"`":return Fu(e,0,t);case"'":return Fu(e,n);case"<":d=a[Fu(c,1,-1)];break;default:var p=+c;if(p===0)return l;if(p>o){var h=C$(p/10);return h===0?l:h<=o?r[h-1]===void 0?Nu(c,1):r[h-1]+Nu(c,1):l}d=r[p-1]}return d===void 0?"":d})}});var Zg=m(()=>{"use strict";var O$=z(),_$=Ee(),Hu=J(),Jg=St(),N$=G(),F$=hr(),q$=Hg(),Fr=Ci(),U$=ei(),H$=Yg(),j$=Kg(),G$=ae(),Q$=Ne(),W$=G$("replace"),Y$=TypeError,Uu=Hu("".indexOf),z$=Hu("".replace),Xg=Hu("".slice),K$=Math.max;O$({target:"String",proto:!0},{replaceAll:function(e,t){var r=Jg(this),a,s,n,o,u,l,c,d,p,h,f=0,b="";if(!F$(e)){if(a=q$(e),a&&(s=Fr(Jg(H$(e))),!~Uu(s,"g")))throw new Y$("`.replaceAll` does not allow non-global regexes");if(n=U$(e,W$),n)return _$(n,e,r,t);if(Q$&&a)return z$(Fr(r),e,t)}for(o=Fr(r),u=Fr(e),l=N$(t),l||(t=Fr(t)),c=u.length,d=K$(1,c),p=Uu(o,u);p!==-1;)h=l?Fr(t(u,p,o)):j$(u,o,p,[],void 0,t),b+=Xg(o,f,p)+h,f=p+c,p=p+d>o.length?-1:Uu(o,u,p+d);return f<o.length&&(b+=Xg(o,f)),b}})});var tS=m((kq,eS)=>{"use strict";Fg();qg();Zg();var J$=vt();eS.exports=J$("String","replaceAll")});var iS=m((wq,rS)=>{"use strict";var X$=tS();rS.exports=X$});var sS=m((Rq,aS)=>{"use strict";var Z$=iS();aS.exports=Z$});var oS=m(($q,nS)=>{"use strict";var eL=ai(),tL=Ci(),rL=St(),iL=RangeError;nS.exports=function(e){var t=tL(rL(this)),r="",a=eL(e);if(a<0||a===1/0)throw new iL("Wrong number of repetitions");for(;a>0;(a>>>=1)&&(t+=t))a&1&&(r+=t);return r}});var pS=m((Lq,dS)=>{"use strict";var cS=J(),aL=qn(),uS=Ci(),sL=oS(),nL=St(),oL=cS(sL),uL=cS("".slice),lL=Math.ceil,lS=function(i){return function(e,t,r){var a=uS(nL(e)),s=aL(t),n=a.length,o=r===void 0?" ":uS(r),u,l;return s<=n||o===""?a:(u=s-n,l=oL(o,lL(u/o.length)),l.length>u&&(l=uL(l,0,u)),i?a+l:l+a)}};dS.exports={start:lS(!1),end:lS(!0)}});var mS=m((Mq,hS)=>{"use strict";var cL=qt();hS.exports=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(cL)});var fS=m(()=>{"use strict";var dL=z(),pL=pS().start,hL=mS();dL({target:"String",proto:!0,forced:hL},{padStart:function(e){return pL(this,e,arguments.length>1?arguments[1]:void 0)}})});var gS=m((Vq,bS)=>{"use strict";fS();var mL=vt();bS.exports=mL("String","padStart")});var vS=m((Bq,SS)=>{"use strict";var fL=gS();SS.exports=fL});var TS=m((Oq,yS)=>{"use strict";var bL=vS();yS.exports=bL});var kl="2.0.119-dev.76657cc8.0";var de=(a=>(a.STOPPED="stopped",a.READY="ready",a.PLAYING="playing",a.PAUSED="paused",a))(de||{}),gt=(E=>(E.MPEG="MPEG",E.DASH="DASH",E.DASH_SEP="DASH_SEP",E.DASH_SEP_VK="DASH_SEP",E.DASH_WEBM="DASH_WEBM",E.DASH_WEBM_AV1="DASH_WEBM_AV1",E.DASH_STREAMS="DASH_STREAMS",E.DASH_WEBM_VK="DASH_WEBM",E.DASH_ONDEMAND="DASH_ONDEMAND",E.DASH_ONDEMAND_VK="DASH_ONDEMAND",E.DASH_LIVE="DASH_LIVE",E.DASH_LIVE_CMAF="DASH_LIVE_CMAF",E.DASH_LIVE_WEBM="DASH_LIVE_WEBM",E.HLS="HLS",E.HLS_ONDEMAND="HLS_ONDEMAND",E.HLS_JS="HLS",E.HLS_LIVE="HLS_LIVE",E.HLS_LIVE_CMAF="HLS_LIVE_CMAF",E.WEB_RTC_LIVE="WEB_RTC_LIVE",E))(gt||{});var Ba=(a=>(a.NOT_AVAILABLE="NOT_AVAILABLE",a.AVAILABLE="AVAILABLE",a.CONNECTING="CONNECTING",a.CONNECTED="CONNECTED",a))(Ba||{}),cn=(r=>(r.HTTP1="http1",r.HTTP2="http2",r.QUIC="quic",r))(cn||{});var dn=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(dn||{});var Jv=C(Ke(),1);import{assertNever as Pd,assertNonNullable as RI,isNonNullable as qa,ValueSubject as Hn,Subject as $I,Subscription as LI,merge as MI,observableFrom as CI,fromEvent as Td,map as Id,tap as Ed,filterChanged as DI,isNullable as jn,ErrorCategory as xd}from"@vkontakte/videoplayer-shared";var yd=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 Ua=class{constructor(e){this.connection$=new Hn(void 0);this.castState$=new Hn("NOT_AVAILABLE");this.errorEvent$=new $I;this.realCastState$=new Hn("NOT_AVAILABLE");this.subscription=new LI;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=qa(window.chrome?.cast),a=!!window.__onGCastApiAvailable;r?this.initializeCastApi():(window.__onGCastApiAvailable=s=>{delete window.__onGCastApiAvailable,s&&this.initializeCastApi()},a||yd("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:xd.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(){qa(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();jn(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();jn(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(Td(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 Pd(a.sessionState)}})).add(MI(Td(r,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(Ed(a=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(a)}`})}),Id(a=>a.castState)),CI([r.getCastState()])).pipe(DI(),Id(VI),Ed(a=>{this.log({message:`realCastState$: ${a}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(a=>{let s=a==="CONNECTED",n=qa(this.connection$.getValue());if(s&&!n){let o=r.getCurrentSession();RI(o);let u=o.getCastDevice(),l=o.getMediaSession()?.media?.contentId;(jn(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"?qa(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:xd.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:a})}}},VI=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 Pd(i)}};var Sl=C(Ke(),1),Lv=C(Ir(),1),Mv=C(So(),1);var Rf=C(bs(),1);import{assertNever as yf}from"@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:yf(t)}return i},gs=(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:yf(e)}};var I=(i,e,t=!1)=>{let r=i.getTransition();(t||!r||r.to===e)&&i.setState(e)};import{isNonNullable as Hk,Subject as Ss,merge as Tf}from"@vkontakte/videoplayer-shared";var $=class{constructor(e){this.transitionStarted$=new Ss;this.transitionEnded$=new Ss;this.transitionUpdated$=new Ss;this.forceChanged$=new Ss;this.stateChangeStarted$=Tf(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=Tf(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||Hk(t)&&t.to===e||(this.prevState=r,this.state=e,t?(this.transition={from:t.from,to:e,canceledTransition:t},this.transitionUpdated$.next(this.transition)):(this.transition={from:r,to:e},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}getPrevState(){return this.prevState}};import{assertNever as jk}from"@vkontakte/videoplayer-shared";var If=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 jk(i)}};import{assertNever as Mr,assertNonNullable as Yt,debounce as Ef,ErrorCategory as xf,fromEvent as zt,isNonNullable as Pf,map as Af,merge as kf,observableFrom as Gk,Subject as Qk,Subscription as au,timeout as Wk,getHighestQuality as Yk}from"@vkontakte/videoplayer-shared";var zk=5,Kk=5,Jk=500,wf=7e3,Si=class{constructor(e){this.subscription=new au;this.loadMediaTimeoutSubscription=new au;this.videoState=new $("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:Mr(e)}break}case"playing":{switch(e){case"playing":break;case"paused":this.videoState.startTransitionTo("playing"),this.params.connection.remotePlayerController.playOrPause();break;case"ready":this.videoState.startTransitionTo("playing"),this.params.connection.remotePlayerController.playOrPause();break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:Mr(e)}break}case"paused":{switch(e){case"playing":this.videoState.startTransitionTo("paused"),this.params.connection.remotePlayerController.playOrPause();break;case"paused":break;case"ready":this.videoState.startTransitionTo("paused"),this.videoState.setState("paused");break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:Mr(e)}break}default:Mr(r)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(If(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 au;this.subscription.add(e),this.subscription.add(kf(this.videoState.stateChangeStarted$.pipe(Af(a=>`stateChangeStarted$ ${JSON.stringify(a)}`)),this.videoState.stateChangeEnded$.pipe(Af(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 Qk;e.add(a.pipe(Ef(Jk)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add(zt(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)>zk)&&a.next(o),s=o})),e.add(zt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(zt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),a=>{this.logRemoteEvent(a),a.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(zt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),a=>{this.logRemoteEvent(a),a.value?this.handleRemotePause():this.handleRemotePlay()}),t(zt(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<Kk&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),I(this.params.desiredState.playbackState,"stopped");break;case chrome.cast.media.PlayerState.PAUSED:{this.handleRemotePause();break}case chrome.cast.media.PlayerState.PLAYING:this.handleRemotePlay();break;case chrome.cast.media.PlayerState.BUFFERING:break;default:Mr(n)}}),t(zt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),a=>{this.logRemoteEvent(a),this.handleRemoteVolumeChange({volume:a.value})}),t(zt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),a=>{this.logRemoteEvent(a),this.handleRemoteVolumeChange({muted:a.value})});let r=kf(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Gk(["init"])).pipe(Ef(0));t(r,this.syncPlayback)}restoreSession(e){this.log({message:"restoreSession"});let{remotePlayer:t}=this.params.connection;if(e.playerState!==chrome.cast.media.PlayerState.IDLE){t.isPaused?(this.videoState.setState("paused"),I(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),I(this.params.desiredState.playbackState,"playing"));let r=this.params.output.isLive$.getValue();this.params.output.duration$.next(r?0:t.duration),this.params.output.position$.next(r?0:t.currentTime),this.params.desiredState.seekState.setState({state:"none"})}}prepare(){let e=this.params.format;this.log({message:`[prepare] format: ${e}`});let t=this.createMediaInfo(e),r=this.createLoadRequest(t);this.loadMedia(r)}handleRemotePause(){let e=this.videoState.getState();(this.videoState.getTransition()?.to==="paused"||e==="playing")&&(this.videoState.setState("paused"),I(this.params.desiredState.playbackState,"paused"))}handleRemotePlay(){let e=this.videoState.getState();(this.videoState.getTransition()?.to==="playing"||e==="paused")&&(this.videoState.setState("playing"),I(this.params.desiredState.playbackState,"playing"))}handleRemoteReady(){this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.params.desiredState.playbackState.getTransition()?.to==="ready"&&I(this.params.desiredState.playbackState,"ready")}handleRemoteStop(){this.videoState.getState()!=="stopped"&&this.videoState.setState("stopped")}handleRemoteVolumeChange(e){let t=this.params.output.volume$.getValue(),r={volume:e.volume??t.volume,muted:e.muted??t.muted};(r.volume!==t.volume||r.muted!==r.muted)&&this.params.output.volume$.next(r)}seek(e){this.params.output.willSeekEvent$.next();let{remotePlayer:t,remotePlayerController:r}=this.params.connection;t.currentTime=e,r.seek()}stop(){let{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){let t=this.params.source,r,a,s;switch(e){case"MPEG":{let l=t[e];Yt(l);let c=Yk(Object.keys(l));Yt(c);let d=l[c];Yt(d),r=d,a="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let l=t[e];Yt(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];Yt(l),r=l.url,a="application/dash+xml",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let l=t[e];Yt(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];Yt(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:xf.VIDEO_PIPELINE,message:l,thrown:c}),c}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return Mr(e)}let n=new chrome.cast.media.MediaInfo(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 Pf(o)&&(n.metadata.title=o),Pf(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(Wk(wf).subscribe(()=>s(`timeout(${wf})`)))});(0,Rf.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:xf.VIDEO_PIPELINE,message:s,thrown:a})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var xu=C(Ke(),1);import{clearVideoElement as Lf}from"@vkontakte/videoplayer-shared";import{clearVideoElement as Xk}from"@vkontakte/videoplayer-shared";var $f=i=>{try{i.pause(),i.playbackRate=0,Xk(i),i.remove()}catch(e){console.error(e)}};import{fromEvent as Zk,Subscription as ew}from"@vkontakte/videoplayer-shared";var su=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)}},nu=window.WeakMap?new WeakMap:new su,ou=window.WeakMap?new WeakMap:new Map,tw=(i,e=20)=>{let t=0;return Zk(i,"ratechange").subscribe(r=>{t++,t>=e&&(i.currentTime=i.currentTime,t=0)})},pe=(i,{audioVideoSyncRate:e})=>{let t=i.querySelector("video"),r=!!t;t?Lf(t):(t=document.createElement("video"),i.appendChild(t)),nu.set(t,r);let a=new ew;return a.add(tw(t,e)),ou.set(t,a),t.setAttribute("crossorigin","anonymous"),t.setAttribute("playsinline","playsinline"),t.controls=!1,t.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),t},he=i=>{ou.get(i)?.unsubscribe(),ou.delete(i);let t=nu.get(i);nu.delete(i),t?Lf(i):$f(i)};var lu=C(vi(),1);import{assertNonNullable as yi,isNonNullable as Xe,isNullable as lw,fromEvent as Cr,merge as _f,observableFrom as Nf,filterChanged as Ff,map as Ti,Subject as qf,Subscription as cw,ValueSubject as dw,ErrorCategory as pw}from"@vkontakte/videoplayer-shared";import{isNonNullable as uu,isNullable as ow,Subscription as uw}from"@vkontakte/videoplayer-shared";var vs=(i,e,t,{equal:r=(n,o)=>n===o,changed$:a,onError:s}={})=>{let n=i.getState(),o=e(),u=ow(a),l=new uw;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},Je=(i,e,t)=>vs(e,()=>i.loop,r=>{uu(r)&&(i.loop=r)},{onError:t}),me=(i,e,t,r)=>vs(e,()=>({muted:i.muted,volume:i.volume}),a=>{uu(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}),$e=(i,e,t,r)=>vs(e,()=>i.playbackRate,a=>{uu(a)&&(i.playbackRate=a)},{changed$:t,onError:r}),Tt=vs;var hw=i=>["__",i.language,i.label].join("|"),mw=(i,e)=>{if(i.id===e)return!0;let[t,r,a]=e.split("|");return i.language===r&&i.label===a},cu=class i{constructor(){this.available$=new qf;this.current$=new dw(void 0);this.error$=new qf;this.subscription=new cw;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:pw.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(Tt(t.internalTextTracks,()=>(0,lu.default)(this.internalTracks),s=>{Xe(s)&&this.setInternal(s)},{equal:(s,n)=>Xe(s)&&Xe(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(Ti(s=>s.filter(({type:n})=>n==="internal"))),onError:a})),this.subscription.add(Tt(t.externalTextTracks,()=>(0,lu.default)(this.externalTracks),s=>{Xe(s)&&this.setExternal(s)},{equal:(s,n)=>Xe(s)&&Xe(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(Ti(s=>s.filter(({type:n})=>n==="external"))),onError:a})),this.subscription.add(Tt(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(Tt(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.activeCues)}))}subscribe(){yi(this.video);let{textTracks:e}=this.video;this.subscription.add(Cr(e,"addtrack").subscribe(()=>{let r=this.current$.getValue();r&&this.select(r)})),this.subscription.add(_f(Cr(e,"addtrack"),Cr(e,"removetrack"),Nf(["init"])).pipe(Ti(()=>this.htmlTextTracksAsArray().map(r=>this.htmlTextTrackToITextTrack(r))),Ff((r,a)=>r.length===a.length&&r.every(({id:s},n)=>s===a[n].id))).subscribe(this.available$)),this.subscription.add(_f(Cr(e,"change"),Nf(["init"])).pipe(Ti(()=>this.htmlTextTracksAsArray().find(({mode:r})=>r==="showing")),Ti(r=>r&&this.htmlTextTrackToITextTrack(r).id),Ff()).subscribe(this.current$));let t=r=>this.applyCueSettings(r.target?.activeCues??null);this.subscription.add(Cr(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(Cr(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;Xe(t.align)&&(a.align=t.align),Xe(t.position)&&(a.position=t.position),Xe(t.size)&&(a.size=t.size),Xe(t.line)&&(a.line=t.line)}}htmlTextTracksAsArray(e=!1){yi(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:hw(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){yi(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(lw(e)||!mw(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){yi(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){yi(this.video);let t=Array.prototype.find.call(this.video.getElementsByTagName("track"),r=>r.getAttribute("id")===e.id);t&&this.video.removeChild(t),e.type==="external"?this.externalTracks.delete(e.id):e.type==="internal"&&this.internalTracks.delete(e.id)}},Le=cu;var ot=class{constructor(){this.pausedTime=0;this.streamOffset=0;this.pauseTimestamp=0}getTotalPausedTime(){return this.pausedTime+this.getCurrentPausedTime()}getCurrentPausedTime(){return this.pauseTimestamp>0?Date.now()-this.pauseTimestamp:0}getStreamOffset(){return this.streamOffset}getTotalOffset(){return this.getTotalPausedTime()+this.streamOffset}pause(){this.pauseTimestamp===0&&(this.pauseTimestamp=Date.now())}resume(){this.pauseTimestamp>0&&(this.pausedTime+=this.getCurrentPausedTime(),this.pauseTimestamp=0)}resetTo(e,t=!1){this.streamOffset=e,this.pauseTimestamp=0,this.pausedTime=0,t&&this.pause()}};var Uf=i=>{let e=i;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e?.parentNode;return e??void 0},du=i=>{let e=Uf(i);return!!(e&&e.fullscreenElement&&e.fullscreenElement===i)},Hf=i=>{let e=Uf(i);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===i)};import{fromEvent as Me,map as It,merge as Gf,filterChanged as bw,isNonNullable as Qf,Subject as gw,filter as Wf,mapTo as Yf,combine as Sw,once as vw,ErrorCategory as yw,ValueSubject as zf,clientChecker as Tw}from"@vkontakte/videoplayer-shared";var fw=3,jf=(i,e,t=fw)=>{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 fe=i=>{let e=E=>Me(i,E).pipe(Yf(void 0)),r=Gf(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(E=>Me(i,E))).pipe(It(E=>E.type==="ended"?i.readyState<2:i.readyState<3),bw()),a=Gf(Me(i,"progress"),Me(i,"timeupdate")).pipe(It(()=>jf(i.buffered,i.currentTime))),s=Tw.isSafari?Sw({play:e("play").pipe(vw()),playing:e("playing")}).pipe(Yf(void 0)):e("playing"),n=Me(i,"volumechange").pipe(It(()=>({muted:i.muted,volume:i.volume}))),o=Me(i,"ratechange").pipe(It(()=>i.playbackRate)),u=Me(i,"error").pipe(Wf(()=>!!(i.error||i.played.length)),It(()=>{let E=i.error;return{id:E?`MediaError#${E.code}`:"HtmlVideoError",category:yw.VIDEO_PIPELINE,message:E?E.message:"Error event from HTML video element",thrown:i.error??void 0}})),l=Me(i,"timeupdate").pipe(It(()=>i.currentTime)),c=new gw,d=.3,p;l.subscribe(E=>{i.loop&&Qf(p)&&Qf(E)&&p>=i.duration-d&&E<=d&&c.next(p),p=E});let h=e("pause").pipe(Wf(()=>!i.error&&p!==i.duration)),f=Me(i,"enterpictureinpicture"),b=Me(i,"leavepictureinpicture"),g=new zf(Hf(i));f.subscribe(()=>g.next(!0)),b.subscribe(()=>g.next(!1));let S=new zf(du(i));return Me(i,"fullscreenchange").pipe(It(()=>du(i))).subscribe(S),{playing$:s,pause$:h,canplay$:e("canplay"),ended$:e("ended"),looped$:c,error$:u,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:l,durationChange$:Me(i,"durationchange").pipe(It(()=>i.duration)),isBuffering$:r,currentBuffer$:a,volumeState$:n,playbackRateState$:o,inPiP$:g,inFullscreen$:S}};import{VideoQuality as Et}from"@vkontakte/videoplayer-shared";var xt=i=>{switch(i){case"mobile":return Et.Q_144P;case"lowest":return Et.Q_240P;case"low":return Et.Q_360P;case"sd":case"medium":return Et.Q_480P;case"hd":case"high":return Et.Q_720P;case"fullhd":case"full":return Et.Q_1080P;case"quadhd":case"quad":return Et.Q_1440P;case"ultrahd":case"ultra":return Et.Q_2160P}};var Pt=C(Dr(),1),ub=C(Ke(),1),ys=C(Ir(),1);import{isNonNullable as X,isNullable as hu,now as lb,isHigher as mu,isHigherOrEqual as fu,isInvariantQuality as sb,isLower as nb,isLowerOrEqual as bu,videoSizeToQuality as $w,assertNotEmptyArray as cb,assertNonNullable as Lw}from"@vkontakte/videoplayer-shared";var pu=!1,ut={},rb=i=>{pu=i},ib=()=>{ut={}},ab=i=>{i(ut)},Ii=(i,e)=>{pu&&(ut.meta=ut.meta??{},ut.meta[i]=e)},oe=class{constructor(e){this.name=e}next(e){if(!pu)return;ut.series=ut.series??{};let t=ut.series[this.name]??[];t.push([Date.now(),e]),ut.series[this.name]=t}};var Mw=new oe("best_bitrate"),db=(i,e,t)=>(e-t)*Math.pow(2,-10*i)+t;var gu=i=>(e,t)=>i*(Number(e.bitrate)-Number(t.bitrate)),Ei=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=lb()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},pb='Assertion "ABR Tracks is empty array" failed',Ts=(i,e,t,r)=>{let a=[...e].sort(gu(1)),s=[...t].sort(gu(1)),n=s.filter(u=>X(u.bitrate)&&X(i.bitrate)?i.bitrate/u.bitrate>r:!0),o=(0,Pt.default)(s,Math.round(s.length*a.indexOf(i)/(a.length+1)))??(0,Pt.default)(s,-1);return o&&(0,ub.default)(n,o)?o:n.length?(0,Pt.default)(n,-1):(0,Pt.default)(s,0)},ob=i=>"quality"in i,hb=(i,e,t,r)=>{let a=X(r?.last?.bitrate)&&X(t?.bitrate)&&r.last.bitrate<t.bitrate?i.trackCooldownIncreaseQuality:i.trackCooldownDecreaseQuality,s=t&&r&&r.history[t.id]&&lb()-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=ob(n)?"video":"audio",u=ob(n)?n.quality:n.bitrate;return e({message:`
6
+ var ay=Object.create;var Rl=Object.defineProperty;var sy=Object.getOwnPropertyDescriptor;var ny=Object.getOwnPropertyNames;var oy=Object.getPrototypeOf,uy=Object.prototype.hasOwnProperty;var m=(i,e)=>()=>(e||i((e={exports:{}}).exports,e),e.exports);var ly=(i,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of ny(e))!uy.call(i,a)&&a!==t&&Rl(i,a,{get:()=>e[a],enumerable:!(r=sy(e,a))||r.enumerable});return i};var D=(i,e,t)=>(t=i!=null?ay(oy(i)):{},ly(e||!i||!i.__esModule?Rl(t,"default",{value:i,enumerable:!0}):t,i));var G=m((fn,Ll)=>{"use strict";var Kr=function(i){return i&&i.Math===Math&&i};Ll.exports=Kr(typeof globalThis=="object"&&globalThis)||Kr(typeof window=="object"&&window)||Kr(typeof self=="object"&&self)||Kr(typeof global=="object"&&global)||Kr(typeof fn=="object"&&fn)||function(){return this}()||Function("return this")()});var re=m(($C,Ml)=>{"use strict";Ml.exports=function(i){try{return!!i()}catch{return!0}}});var Jr=m((LC,Cl)=>{"use strict";var cy=re();Cl.exports=!cy(function(){var i=function(){}.bind();return typeof i!="function"||i.hasOwnProperty("prototype")})});var bn=m((MC,Bl)=>{"use strict";var dy=Jr(),Ol=Function.prototype,Dl=Ol.apply,Vl=Ol.call;Bl.exports=typeof Reflect=="object"&&Reflect.apply||(dy?Vl.bind(Dl):function(){return Vl.apply(Dl,arguments)})});var J=m((CC,Fl)=>{"use strict";var _l=Jr(),Nl=Function.prototype,gn=Nl.call,py=_l&&Nl.bind.bind(gn,gn);Fl.exports=_l?py:function(i){return function(){return gn.apply(i,arguments)}}});var Nt=m((DC,Ul)=>{"use strict";var ql=J(),hy=ql({}.toString),my=ql("".slice);Ul.exports=function(i){return my(hy(i),8,-1)}});var Sn=m((VC,Hl)=>{"use strict";var fy=Nt(),by=J();Hl.exports=function(i){if(fy(i)==="Function")return by(i)}});var Q=m((OC,jl)=>{"use strict";var vn=typeof document=="object"&&document.all;jl.exports=typeof vn>"u"&&vn!==void 0?function(i){return typeof i=="function"||i===vn}:function(i){return typeof i=="function"}});var Te=m((BC,Ql)=>{"use strict";var gy=re();Ql.exports=!gy(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var Ie=m((_C,Gl)=>{"use strict";var Sy=Jr(),_a=Function.prototype.call;Gl.exports=Sy?_a.bind(_a):function(){return _a.apply(_a,arguments)}});var yn=m(zl=>{"use strict";var Wl={}.propertyIsEnumerable,Yl=Object.getOwnPropertyDescriptor,vy=Yl&&!Wl.call({1:2},1);zl.f=vy?function(e){var t=Yl(this,e);return!!t&&t.enumerable}:Wl});var Xr=m((FC,Kl)=>{"use strict";Kl.exports=function(i,e){return{enumerable:!(i&1),configurable:!(i&2),writable:!(i&4),value:e}}});var Xl=m((qC,Jl)=>{"use strict";var yy=J(),Ty=re(),Iy=Nt(),Tn=Object,Ey=yy("".split);Jl.exports=Ty(function(){return!Tn("z").propertyIsEnumerable(0)})?function(i){return Iy(i)==="String"?Ey(i,""):Tn(i)}:Tn});var hr=m((UC,Zl)=>{"use strict";Zl.exports=function(i){return i==null}});var St=m((HC,ec)=>{"use strict";var xy=hr(),Py=TypeError;ec.exports=function(i){if(xy(i))throw new Py("Can't call method on "+i);return i}});var Ft=m((jC,tc)=>{"use strict";var Ay=Xl(),ky=St();tc.exports=function(i){return Ay(ky(i))}});var Ee=m((QC,rc)=>{"use strict";var wy=Q();rc.exports=function(i){return typeof i=="object"?i!==null:wy(i)}});var mr=m((GC,ic)=>{"use strict";ic.exports={}});var at=m((WC,sc)=>{"use strict";var In=mr(),En=G(),Ry=Q(),ac=function(i){return Ry(i)?i:void 0};sc.exports=function(i,e){return arguments.length<2?ac(In[i])||ac(En[i]):In[i]&&In[i][e]||En[i]&&En[i][e]}});var Zr=m((YC,nc)=>{"use strict";var $y=J();nc.exports=$y({}.isPrototypeOf)});var qt=m((zC,lc)=>{"use strict";var Ly=G(),oc=Ly.navigator,uc=oc&&oc.userAgent;lc.exports=uc?String(uc):""});var Pn=m((KC,fc)=>{"use strict";var mc=G(),xn=qt(),cc=mc.process,dc=mc.Deno,pc=cc&&cc.versions||dc&&dc.version,hc=pc&&pc.v8,Be,Na;hc&&(Be=hc.split("."),Na=Be[0]>0&&Be[0]<4?1:+(Be[0]+Be[1]));!Na&&xn&&(Be=xn.match(/Edge\/(\d+)/),(!Be||Be[1]>=74)&&(Be=xn.match(/Chrome\/(\d+)/),Be&&(Na=+Be[1])));fc.exports=Na});var An=m((JC,gc)=>{"use strict";var bc=Pn(),My=re(),Cy=G(),Dy=Cy.String;gc.exports=!!Object.getOwnPropertySymbols&&!My(function(){var i=Symbol("symbol detection");return!Dy(i)||!(Object(i)instanceof Symbol)||!Symbol.sham&&bc&&bc<41})});var kn=m((XC,Sc)=>{"use strict";var Vy=An();Sc.exports=Vy&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var wn=m((ZC,vc)=>{"use strict";var Oy=at(),By=Q(),_y=Zr(),Ny=kn(),Fy=Object;vc.exports=Ny?function(i){return typeof i=="symbol"}:function(i){var e=Oy("Symbol");return By(e)&&_y(e.prototype,Fy(i))}});var ei=m((e0,yc)=>{"use strict";var qy=String;yc.exports=function(i){try{return qy(i)}catch{return"Object"}}});var We=m((t0,Tc)=>{"use strict";var Uy=Q(),Hy=ei(),jy=TypeError;Tc.exports=function(i){if(Uy(i))return i;throw new jy(Hy(i)+" is not a function")}});var ti=m((r0,Ic)=>{"use strict";var Qy=We(),Gy=hr();Ic.exports=function(i,e){var t=i[e];return Gy(t)?void 0:Qy(t)}});var xc=m((i0,Ec)=>{"use strict";var Rn=Ie(),$n=Q(),Ln=Ee(),Wy=TypeError;Ec.exports=function(i,e){var t,r;if(e==="string"&&$n(t=i.toString)&&!Ln(r=Rn(t,i))||$n(t=i.valueOf)&&!Ln(r=Rn(t,i))||e!=="string"&&$n(t=i.toString)&&!Ln(r=Rn(t,i)))return r;throw new Wy("Can't convert object to primitive value")}});var _e=m((a0,Pc)=>{"use strict";Pc.exports=!0});var wc=m((s0,kc)=>{"use strict";var Ac=G(),Yy=Object.defineProperty;kc.exports=function(i,e){try{Yy(Ac,i,{value:e,configurable:!0,writable:!0})}catch{Ac[i]=e}return e}});var ri=m((n0,Lc)=>{"use strict";var zy=_e(),Ky=G(),Jy=wc(),Rc="__core-js_shared__",$c=Lc.exports=Ky[Rc]||Jy(Rc,{});($c.versions||($c.versions=[])).push({version:"3.38.0",mode:zy?"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 Mn=m((o0,Cc)=>{"use strict";var Mc=ri();Cc.exports=function(i,e){return Mc[i]||(Mc[i]=e||{})}});var fr=m((u0,Dc)=>{"use strict";var Xy=St(),Zy=Object;Dc.exports=function(i){return Zy(Xy(i))}});var Ne=m((l0,Vc)=>{"use strict";var eT=J(),tT=fr(),rT=eT({}.hasOwnProperty);Vc.exports=Object.hasOwn||function(e,t){return rT(tT(e),t)}});var Cn=m((c0,Oc)=>{"use strict";var iT=J(),aT=0,sT=Math.random(),nT=iT(1 .toString);Oc.exports=function(i){return"Symbol("+(i===void 0?"":i)+")_"+nT(++aT+sT,36)}});var ie=m((d0,_c)=>{"use strict";var oT=G(),uT=Mn(),Bc=Ne(),lT=Cn(),cT=An(),dT=kn(),br=oT.Symbol,Dn=uT("wks"),pT=dT?br.for||br:br&&br.withoutSetter||lT;_c.exports=function(i){return Bc(Dn,i)||(Dn[i]=cT&&Bc(br,i)?br[i]:pT("Symbol."+i)),Dn[i]}});var Uc=m((p0,qc)=>{"use strict";var hT=Ie(),Nc=Ee(),Fc=wn(),mT=ti(),fT=xc(),bT=ie(),gT=TypeError,ST=bT("toPrimitive");qc.exports=function(i,e){if(!Nc(i)||Fc(i))return i;var t=mT(i,ST),r;if(t){if(e===void 0&&(e="default"),r=hT(t,i,e),!Nc(r)||Fc(r))return r;throw new gT("Can't convert object to primitive value")}return e===void 0&&(e="number"),fT(i,e)}});var Vn=m((h0,Hc)=>{"use strict";var vT=Uc(),yT=wn();Hc.exports=function(i){var e=vT(i,"string");return yT(e)?e:e+""}});var Fa=m((m0,Qc)=>{"use strict";var TT=G(),jc=Ee(),On=TT.document,IT=jc(On)&&jc(On.createElement);Qc.exports=function(i){return IT?On.createElement(i):{}}});var Bn=m((f0,Gc)=>{"use strict";var ET=Te(),xT=re(),PT=Fa();Gc.exports=!ET&&!xT(function(){return Object.defineProperty(PT("div"),"a",{get:function(){return 7}}).a!==7})});var zc=m(Yc=>{"use strict";var AT=Te(),kT=Ie(),wT=yn(),RT=Xr(),$T=Ft(),LT=Vn(),MT=Ne(),CT=Bn(),Wc=Object.getOwnPropertyDescriptor;Yc.f=AT?Wc:function(e,t){if(e=$T(e),t=LT(t),CT)try{return Wc(e,t)}catch{}if(MT(e,t))return RT(!kT(wT.f,e,t),e[t])}});var _n=m((g0,Kc)=>{"use strict";var DT=re(),VT=Q(),OT=/#|\.prototype\./,ii=function(i,e){var t=_T[BT(i)];return t===FT?!0:t===NT?!1:VT(e)?DT(e):!!e},BT=ii.normalize=function(i){return String(i).replace(OT,".").toLowerCase()},_T=ii.data={},NT=ii.NATIVE="N",FT=ii.POLYFILL="P";Kc.exports=ii});var gr=m((S0,Xc)=>{"use strict";var Jc=Sn(),qT=We(),UT=Jr(),HT=Jc(Jc.bind);Xc.exports=function(i,e){return qT(i),e===void 0?i:UT?HT(i,e):function(){return i.apply(e,arguments)}}});var Nn=m((v0,Zc)=>{"use strict";var jT=Te(),QT=re();Zc.exports=jT&&QT(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var Ye=m((y0,ed)=>{"use strict";var GT=Ee(),WT=String,YT=TypeError;ed.exports=function(i){if(GT(i))return i;throw new YT(WT(i)+" is not an object")}});var Ut=m(rd=>{"use strict";var zT=Te(),KT=Bn(),JT=Nn(),qa=Ye(),td=Vn(),XT=TypeError,Fn=Object.defineProperty,ZT=Object.getOwnPropertyDescriptor,qn="enumerable",Un="configurable",Hn="writable";rd.f=zT?JT?function(e,t,r){if(qa(e),t=td(t),qa(r),typeof e=="function"&&t==="prototype"&&"value"in r&&Hn in r&&!r[Hn]){var a=ZT(e,t);a&&a[Hn]&&(e[t]=r.value,r={configurable:Un in r?r[Un]:a[Un],enumerable:qn in r?r[qn]:a[qn],writable:!1})}return Fn(e,t,r)}:Fn:function(e,t,r){if(qa(e),t=td(t),qa(r),KT)try{return Fn(e,t,r)}catch{}if("get"in r||"set"in r)throw new XT("Accessors not supported");return"value"in r&&(e[t]=r.value),e}});var Sr=m((I0,id)=>{"use strict";var eI=Te(),tI=Ut(),rI=Xr();id.exports=eI?function(i,e,t){return tI.f(i,e,rI(1,t))}:function(i,e,t){return i[e]=t,i}});var K=m((E0,sd)=>{"use strict";var ai=G(),iI=bn(),aI=Sn(),sI=Q(),nI=zc().f,oI=_n(),vr=mr(),uI=gr(),yr=Sr(),ad=Ne();ri();var lI=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 iI(i,this,arguments)};return e.prototype=i.prototype,e};sd.exports=function(i,e){var t=i.target,r=i.global,a=i.stat,s=i.proto,n=r?ai:a?ai[t]:ai[t]&&ai[t].prototype,o=r?vr:vr[t]||yr(vr,t,{})[t],u=o.prototype,l,c,d,p,h,f,b,g,S;for(p in e)l=oI(r?p:t+(a?".":"#")+p,i.forced),c=!l&&n&&ad(n,p),f=o[p],c&&(i.dontCallGetSet?(S=nI(n,p),b=S&&S.value):b=n[p]),h=c&&b?b:e[p],!(!l&&!s&&typeof f==typeof h)&&(i.bind&&c?g=uI(h,ai):i.wrap&&c?g=lI(h):s&&sI(h)?g=aI(h):g=h,(i.sham||h&&h.sham||f&&f.sham)&&yr(g,"sham",!0),yr(o,p,g),s&&(d=t+"Prototype",ad(vr,d)||yr(vr,d,{}),yr(vr[d],p,h),i.real&&u&&(l||!u[p])&&yr(u,p,h)))}});var od=m((x0,nd)=>{"use strict";var cI=Math.ceil,dI=Math.floor;nd.exports=Math.trunc||function(e){var t=+e;return(t>0?dI:cI)(t)}});var si=m((P0,ud)=>{"use strict";var pI=od();ud.exports=function(i){var e=+i;return e!==e||e===0?0:pI(e)}});var cd=m((A0,ld)=>{"use strict";var hI=si(),mI=Math.max,fI=Math.min;ld.exports=function(i,e){var t=hI(i);return t<0?mI(t+e,0):fI(t,e)}});var jn=m((k0,dd)=>{"use strict";var bI=si(),gI=Math.min;dd.exports=function(i){var e=bI(i);return e>0?gI(e,9007199254740991):0}});var Tr=m((w0,pd)=>{"use strict";var SI=jn();pd.exports=function(i){return SI(i.length)}});var Qn=m((R0,md)=>{"use strict";var vI=Ft(),yI=cd(),TI=Tr(),hd=function(i){return function(e,t,r){var a=vI(e),s=TI(a);if(s===0)return!i&&-1;var n=yI(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}};md.exports={includes:hd(!0),indexOf:hd(!1)}});var ni=m(($0,fd)=>{"use strict";fd.exports=function(){}});var bd=m(()=>{"use strict";var II=K(),EI=Qn().includes,xI=re(),PI=ni(),AI=xI(function(){return!Array(1).includes()});II({target:"Array",proto:!0,forced:AI},{includes:function(e){return EI(this,e,arguments.length>1?arguments[1]:void 0)}});PI("includes")});var vt=m((C0,gd)=>{"use strict";var kI=at();gd.exports=kI});var vd=m((D0,Sd)=>{"use strict";bd();var wI=vt();Sd.exports=wI("Array","includes")});var Td=m((V0,yd)=>{"use strict";var RI=vd();yd.exports=RI});var ze=m((O0,Id)=>{"use strict";var $I=Td();Id.exports=$I});var ja=m((Y0,$d)=>{"use strict";var _I=Mn(),NI=Cn(),Rd=_I("keys");$d.exports=function(i){return Rd[i]||(Rd[i]=NI(i))}});var Md=m((z0,Ld)=>{"use strict";var FI=re();Ld.exports=!FI(function(){function i(){}return i.prototype.constructor=null,Object.getPrototypeOf(new i)!==i.prototype})});var Qa=m((K0,Dd)=>{"use strict";var qI=Ne(),UI=Q(),HI=fr(),jI=ja(),QI=Md(),Cd=jI("IE_PROTO"),Yn=Object,GI=Yn.prototype;Dd.exports=QI?Yn.getPrototypeOf:function(i){var e=HI(i);if(qI(e,Cd))return e[Cd];var t=e.constructor;return UI(t)&&e instanceof t?t.prototype:e instanceof Yn?GI:null}});var Ga=m((J0,Vd)=>{"use strict";Vd.exports={}});var _d=m((X0,Bd)=>{"use strict";var WI=J(),zn=Ne(),YI=Ft(),zI=Qn().indexOf,KI=Ga(),Od=WI([].push);Bd.exports=function(i,e){var t=YI(i),r=0,a=[],s;for(s in t)!zn(KI,s)&&zn(t,s)&&Od(a,s);for(;e.length>r;)zn(t,s=e[r++])&&(~zI(a,s)||Od(a,s));return a}});var Kn=m((Z0,Nd)=>{"use strict";Nd.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var Jn=m((eD,Fd)=>{"use strict";var JI=_d(),XI=Kn();Fd.exports=Object.keys||function(e){return JI(e,XI)}});var Xn=m((tD,Qd)=>{"use strict";var Ud=Te(),ZI=re(),Hd=J(),eE=Qa(),tE=Jn(),rE=Ft(),iE=yn().f,jd=Hd(iE),aE=Hd([].push),sE=Ud&&ZI(function(){var i=Object.create(null);return i[2]=2,!jd(i,2)}),qd=function(i){return function(e){for(var t=rE(e),r=tE(t),a=sE&&eE(t)===null,s=r.length,n=0,o=[],u;s>n;)u=r[n++],(!Ud||(a?u in t:jd(t,u)))&&aE(o,i?[u,t[u]]:t[u]);return o}};Qd.exports={entries:qd(!0),values:qd(!1)}});var Gd=m(()=>{"use strict";var nE=K(),oE=Xn().entries;nE({target:"Object",stat:!0},{entries:function(e){return oE(e)}})});var Yd=m((aD,Wd)=>{"use strict";Gd();var uE=mr();Wd.exports=uE.Object.entries});var Kd=m((sD,zd)=>{"use strict";var lE=Yd();zd.exports=lE});var Ir=m((nD,Jd)=>{"use strict";var cE=Kd();Jd.exports=cE});var Ht=m((oD,Xd)=>{"use strict";Xd.exports={}});var tp=m((uD,ep)=>{"use strict";var dE=G(),pE=Q(),Zd=dE.WeakMap;ep.exports=pE(Zd)&&/native code/.test(String(Zd))});var ro=m((lD,ap)=>{"use strict";var hE=tp(),ip=G(),mE=Ee(),fE=Sr(),Zn=Ne(),eo=ri(),bE=ja(),gE=Ga(),rp="Object already initialized",to=ip.TypeError,SE=ip.WeakMap,Wa,oi,Ya,vE=function(i){return Ya(i)?oi(i):Wa(i,{})},yE=function(i){return function(e){var t;if(!mE(e)||(t=oi(e)).type!==i)throw new to("Incompatible receiver, "+i+" required");return t}};hE||eo.state?(Fe=eo.state||(eo.state=new SE),Fe.get=Fe.get,Fe.has=Fe.has,Fe.set=Fe.set,Wa=function(i,e){if(Fe.has(i))throw new to(rp);return e.facade=i,Fe.set(i,e),e},oi=function(i){return Fe.get(i)||{}},Ya=function(i){return Fe.has(i)}):(jt=bE("state"),gE[jt]=!0,Wa=function(i,e){if(Zn(i,jt))throw new to(rp);return e.facade=i,fE(i,jt,e),e},oi=function(i){return Zn(i,jt)?i[jt]:{}},Ya=function(i){return Zn(i,jt)});var Fe,jt;ap.exports={set:Wa,get:oi,has:Ya,enforce:vE,getterFor:yE}});var so=m((cD,np)=>{"use strict";var io=Te(),TE=Ne(),sp=Function.prototype,IE=io&&Object.getOwnPropertyDescriptor,ao=TE(sp,"name"),EE=ao&&function(){}.name==="something",xE=ao&&(!io||io&&IE(sp,"name").configurable);np.exports={EXISTS:ao,PROPER:EE,CONFIGURABLE:xE}});var up=m(op=>{"use strict";var PE=Te(),AE=Nn(),kE=Ut(),wE=Ye(),RE=Ft(),$E=Jn();op.f=PE&&!AE?Object.defineProperties:function(e,t){wE(e);for(var r=RE(t),a=$E(t),s=a.length,n=0,o;s>n;)kE.f(e,o=a[n++],r[o]);return e}});var no=m((pD,lp)=>{"use strict";var LE=at();lp.exports=LE("document","documentElement")});var co=m((hD,bp)=>{"use strict";var ME=Ye(),CE=up(),cp=Kn(),DE=Ga(),VE=no(),OE=Fa(),BE=ja(),dp=">",pp="<",uo="prototype",lo="script",mp=BE("IE_PROTO"),oo=function(){},fp=function(i){return pp+lo+dp+i+pp+"/"+lo+dp},hp=function(i){i.write(fp("")),i.close();var e=i.parentWindow.Object;return i=null,e},_E=function(){var i=OE("iframe"),e="java"+lo+":",t;return i.style.display="none",VE.appendChild(i),i.src=String(e),t=i.contentWindow.document,t.open(),t.write(fp("document.F=Object")),t.close(),t.F},za,Ka=function(){try{za=new ActiveXObject("htmlfile")}catch{}Ka=typeof document<"u"?document.domain&&za?hp(za):_E():hp(za);for(var i=cp.length;i--;)delete Ka[uo][cp[i]];return Ka()};DE[mp]=!0;bp.exports=Object.create||function(e,t){var r;return e!==null?(oo[uo]=ME(e),r=new oo,oo[uo]=null,r[mp]=e):r=Ka(),t===void 0?r:CE.f(r,t)}});var Er=m((mD,gp)=>{"use strict";var NE=Sr();gp.exports=function(i,e,t,r){return r&&r.enumerable?i[e]=t:NE(i,e,t),i}});var fo=m((fD,yp)=>{"use strict";var FE=re(),qE=Q(),UE=Ee(),HE=co(),Sp=Qa(),jE=Er(),QE=ie(),GE=_e(),mo=QE("iterator"),vp=!1,st,po,ho;[].keys&&(ho=[].keys(),"next"in ho?(po=Sp(Sp(ho)),po!==Object.prototype&&(st=po)):vp=!0);var WE=!UE(st)||FE(function(){var i={};return st[mo].call(i)!==i});WE?st={}:GE&&(st=HE(st));qE(st[mo])||jE(st,mo,function(){return this});yp.exports={IteratorPrototype:st,BUGGY_SAFARI_ITERATORS:vp}});var Ja=m((bD,Ip)=>{"use strict";var YE=ie(),zE=YE("toStringTag"),Tp={};Tp[zE]="z";Ip.exports=String(Tp)==="[object z]"});var ui=m((gD,Ep)=>{"use strict";var KE=Ja(),JE=Q(),Xa=Nt(),XE=ie(),ZE=XE("toStringTag"),ex=Object,tx=Xa(function(){return arguments}())==="Arguments",rx=function(i,e){try{return i[e]}catch{}};Ep.exports=KE?Xa:function(i){var e,t,r;return i===void 0?"Undefined":i===null?"Null":typeof(t=rx(e=ex(i),ZE))=="string"?t:tx?Xa(e):(r=Xa(e))==="Object"&&JE(e.callee)?"Arguments":r}});var Pp=m((SD,xp)=>{"use strict";var ix=Ja(),ax=ui();xp.exports=ix?{}.toString:function(){return"[object "+ax(this)+"]"}});var li=m((vD,kp)=>{"use strict";var sx=Ja(),nx=Ut().f,ox=Sr(),ux=Ne(),lx=Pp(),cx=ie(),Ap=cx("toStringTag");kp.exports=function(i,e,t,r){var a=t?i:i&&i.prototype;a&&(ux(a,Ap)||nx(a,Ap,{configurable:!0,value:e}),r&&!sx&&ox(a,"toString",lx))}});var Rp=m((yD,wp)=>{"use strict";var dx=fo().IteratorPrototype,px=co(),hx=Xr(),mx=li(),fx=Ht(),bx=function(){return this};wp.exports=function(i,e,t,r){var a=e+" Iterator";return i.prototype=px(dx,{next:hx(+!r,t)}),mx(i,a,!1,!0),fx[a]=bx,i}});var Lp=m((TD,$p)=>{"use strict";var gx=J(),Sx=We();$p.exports=function(i,e,t){try{return gx(Sx(Object.getOwnPropertyDescriptor(i,e)[t]))}catch{}}});var Cp=m((ID,Mp)=>{"use strict";var vx=Ee();Mp.exports=function(i){return vx(i)||i===null}});var Vp=m((ED,Dp)=>{"use strict";var yx=Cp(),Tx=String,Ix=TypeError;Dp.exports=function(i){if(yx(i))return i;throw new Ix("Can't set "+Tx(i)+" as a prototype")}});var bo=m((xD,Op)=>{"use strict";var Ex=Lp(),xx=Ee(),Px=St(),Ax=Vp();Op.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var i=!1,e={},t;try{t=Ex(Object.prototype,"__proto__","set"),t(e,[]),i=e instanceof Array}catch{}return function(a,s){return Px(a),Ax(s),xx(a)&&(i?t(a,s):a.__proto__=s),a}}():void 0)});var Wp=m((PD,Gp)=>{"use strict";var kx=K(),wx=Ie(),Za=_e(),jp=so(),Rx=Q(),$x=Rp(),Bp=Qa(),_p=bo(),Lx=li(),Mx=Sr(),go=Er(),Cx=ie(),Np=Ht(),Qp=fo(),Dx=jp.PROPER,Vx=jp.CONFIGURABLE,Fp=Qp.IteratorPrototype,es=Qp.BUGGY_SAFARI_ITERATORS,ci=Cx("iterator"),qp="keys",di="values",Up="entries",Hp=function(){return this};Gp.exports=function(i,e,t,r,a,s,n){$x(t,e,r);var o=function(S){if(S===a&&p)return p;if(!es&&S&&S in c)return c[S];switch(S){case qp:return function(){return new t(this,S)};case di:return function(){return new t(this,S)};case Up:return function(){return new t(this,S)}}return function(){return new t(this)}},u=e+" Iterator",l=!1,c=i.prototype,d=c[ci]||c["@@iterator"]||a&&c[a],p=!es&&d||o(a),h=e==="Array"&&c.entries||d,f,b,g;if(h&&(f=Bp(h.call(new i)),f!==Object.prototype&&f.next&&(!Za&&Bp(f)!==Fp&&(_p?_p(f,Fp):Rx(f[ci])||go(f,ci,Hp)),Lx(f,u,!0,!0),Za&&(Np[u]=Hp))),Dx&&a===di&&d&&d.name!==di&&(!Za&&Vx?Mx(c,"name",di):(l=!0,p=function(){return wx(d,this)})),a)if(b={values:o(di),keys:s?p:o(qp),entries:o(Up)},n)for(g in b)(es||l||!(g in c))&&go(c,g,b[g]);else kx({target:e,proto:!0,forced:es||l},b);return(!Za||n)&&c[ci]!==p&&go(c,ci,p,{name:a}),Np[e]=p,b}});var zp=m((AD,Yp)=>{"use strict";Yp.exports=function(i,e){return{value:i,done:e}}});var vo=m((kD,eh)=>{"use strict";var Ox=Ft(),So=ni(),Kp=Ht(),Xp=ro(),Bx=Ut().f,_x=Wp(),ts=zp(),Nx=_e(),Fx=Te(),Zp="Array Iterator",qx=Xp.set,Ux=Xp.getterFor(Zp);eh.exports=_x(Array,"Array",function(i,e){qx(this,{type:Zp,target:Ox(i),index:0,kind:e})},function(){var i=Ux(this),e=i.target,t=i.index++;if(!e||t>=e.length)return i.target=void 0,ts(void 0,!0);switch(i.kind){case"keys":return ts(t,!1);case"values":return ts(e[t],!1)}return ts([t,e[t]],!1)},"values");var Jp=Kp.Arguments=Kp.Array;So("keys");So("values");So("entries");if(!Nx&&Fx&&Jp.name!=="values")try{Bx(Jp,"name",{value:"values"})}catch{}});var rh=m((wD,th)=>{"use strict";var Hx=ie(),jx=Ht(),Qx=Hx("iterator"),Gx=Array.prototype;th.exports=function(i){return i!==void 0&&(jx.Array===i||Gx[Qx]===i)}});var yo=m((RD,ah)=>{"use strict";var Wx=ui(),ih=ti(),Yx=hr(),zx=Ht(),Kx=ie(),Jx=Kx("iterator");ah.exports=function(i){if(!Yx(i))return ih(i,Jx)||ih(i,"@@iterator")||zx[Wx(i)]}});var nh=m(($D,sh)=>{"use strict";var Xx=Ie(),Zx=We(),eP=Ye(),tP=ei(),rP=yo(),iP=TypeError;sh.exports=function(i,e){var t=arguments.length<2?rP(i):e;if(Zx(t))return eP(Xx(t,i));throw new iP(tP(i)+" is not iterable")}});var lh=m((LD,uh)=>{"use strict";var aP=Ie(),oh=Ye(),sP=ti();uh.exports=function(i,e,t){var r,a;oh(i);try{if(r=sP(i,"return"),!r){if(e==="throw")throw t;return t}r=aP(r,i)}catch(s){a=!0,r=s}if(e==="throw")throw t;if(a)throw r;return oh(r),t}});var is=m((MD,hh)=>{"use strict";var nP=gr(),oP=Ie(),uP=Ye(),lP=ei(),cP=rh(),dP=Tr(),ch=Zr(),pP=nh(),hP=yo(),dh=lh(),mP=TypeError,rs=function(i,e){this.stopped=i,this.result=e},ph=rs.prototype;hh.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=nP(e,r),l,c,d,p,h,f,b,g=function(x){return l&&dh(l,"normal",x),new rs(!0,x)},S=function(x){return a?(uP(x),o?u(x[0],x[1],g):u(x[0],x[1])):o?u(x,g):u(x)};if(s)l=i.iterator;else if(n)l=i;else{if(c=hP(i),!c)throw new mP(lP(i)+" is not iterable");if(cP(c)){for(d=0,p=dP(i);p>d;d++)if(h=S(i[d]),h&&ch(ph,h))return h;return new rs(!1)}l=pP(i,c)}for(f=s?i.next:l.next;!(b=oP(f,l)).done;){try{h=S(b.value)}catch(x){dh(l,"throw",x)}if(typeof h=="object"&&h&&ch(ph,h))return h}return new rs(!1)}});var fh=m((CD,mh)=>{"use strict";var fP=Te(),bP=Ut(),gP=Xr();mh.exports=function(i,e,t){fP?bP.f(i,e,gP(0,t)):i[e]=t}});var bh=m(()=>{"use strict";var SP=K(),vP=is(),yP=fh();SP({target:"Object",stat:!0},{fromEntries:function(e){var t={};return vP(e,function(r,a){yP(t,r,a)},{AS_ENTRIES:!0}),t}})});var Sh=m((OD,gh)=>{"use strict";vo();bh();var TP=mr();gh.exports=TP.Object.fromEntries});var yh=m((BD,vh)=>{"use strict";vh.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 Ih=m(()=>{"use strict";vo();var IP=yh(),EP=G(),xP=li(),Th=Ht();for(as in IP)xP(EP[as],as),Th[as]=Th.Array;var as});var xh=m((FD,Eh)=>{"use strict";var PP=Sh();Ih();Eh.exports=PP});var To=m((qD,Ph)=>{"use strict";var AP=xh();Ph.exports=AP});var Ah=m(()=>{"use strict"});var Io=m((jD,kh)=>{"use strict";var pi=G(),kP=qt(),wP=Nt(),ss=function(i){return kP.slice(0,i.length)===i};kh.exports=function(){return ss("Bun/")?"BUN":ss("Cloudflare-Workers")?"CLOUDFLARE":ss("Deno/")?"DENO":ss("Node.js/")?"NODE":pi.Bun&&typeof Bun.version=="string"?"BUN":pi.Deno&&typeof Deno.version=="object"?"DENO":wP(pi.process)==="process"?"NODE":pi.window&&pi.document?"BROWSER":"REST"}()});var ns=m((QD,wh)=>{"use strict";var RP=Io();wh.exports=RP==="NODE"});var $h=m((GD,Rh)=>{"use strict";var $P=Ut();Rh.exports=function(i,e,t){return $P.f(i,e,t)}});var Ch=m((WD,Mh)=>{"use strict";var LP=at(),MP=$h(),CP=ie(),DP=Te(),Lh=CP("species");Mh.exports=function(i){var e=LP(i);DP&&e&&!e[Lh]&&MP(e,Lh,{configurable:!0,get:function(){return this}})}});var Vh=m((YD,Dh)=>{"use strict";var VP=Zr(),OP=TypeError;Dh.exports=function(i,e){if(VP(e,i))return i;throw new OP("Incorrect invocation")}});var xo=m((zD,Oh)=>{"use strict";var BP=J(),_P=Q(),Eo=ri(),NP=BP(Function.toString);_P(Eo.inspectSource)||(Eo.inspectSource=function(i){return NP(i)});Oh.exports=Eo.inspectSource});var Ao=m((KD,qh)=>{"use strict";var FP=J(),qP=re(),Bh=Q(),UP=ui(),HP=at(),jP=xo(),_h=function(){},Nh=HP("Reflect","construct"),Po=/^\s*(?:class|function)\b/,QP=FP(Po.exec),GP=!Po.test(_h),hi=function(e){if(!Bh(e))return!1;try{return Nh(_h,[],e),!0}catch{return!1}},Fh=function(e){if(!Bh(e))return!1;switch(UP(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return GP||!!QP(Po,jP(e))}catch{return!0}};Fh.sham=!0;qh.exports=!Nh||qP(function(){var i;return hi(hi.call)||!hi(Object)||!hi(function(){i=!0})||i})?Fh:hi});var Hh=m((JD,Uh)=>{"use strict";var WP=Ao(),YP=ei(),zP=TypeError;Uh.exports=function(i){if(WP(i))return i;throw new zP(YP(i)+" is not a constructor")}});var ko=m((XD,Qh)=>{"use strict";var jh=Ye(),KP=Hh(),JP=hr(),XP=ie(),ZP=XP("species");Qh.exports=function(i,e){var t=jh(i).constructor,r;return t===void 0||JP(r=jh(t)[ZP])?e:KP(r)}});var Wh=m((ZD,Gh)=>{"use strict";var eA=J();Gh.exports=eA([].slice)});var zh=m((eV,Yh)=>{"use strict";var tA=TypeError;Yh.exports=function(i,e){if(i<e)throw new tA("Not enough arguments");return i}});var wo=m((tV,Kh)=>{"use strict";var rA=qt();Kh.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(rA)});var Bo=m((rV,sm)=>{"use strict";var xe=G(),iA=bn(),aA=gr(),Jh=Q(),sA=Ne(),am=re(),Xh=no(),nA=Wh(),Zh=Fa(),oA=zh(),uA=wo(),lA=ns(),Do=xe.setImmediate,Vo=xe.clearImmediate,cA=xe.process,Ro=xe.Dispatch,dA=xe.Function,em=xe.MessageChannel,pA=xe.String,$o=0,mi={},tm="onreadystatechange",fi,Qt,Lo,Mo;am(function(){fi=xe.location});var Oo=function(i){if(sA(mi,i)){var e=mi[i];delete mi[i],e()}},Co=function(i){return function(){Oo(i)}},rm=function(i){Oo(i.data)},im=function(i){xe.postMessage(pA(i),fi.protocol+"//"+fi.host)};(!Do||!Vo)&&(Do=function(e){oA(arguments.length,1);var t=Jh(e)?e:dA(e),r=nA(arguments,1);return mi[++$o]=function(){iA(t,void 0,r)},Qt($o),$o},Vo=function(e){delete mi[e]},lA?Qt=function(i){cA.nextTick(Co(i))}:Ro&&Ro.now?Qt=function(i){Ro.now(Co(i))}:em&&!uA?(Lo=new em,Mo=Lo.port2,Lo.port1.onmessage=rm,Qt=aA(Mo.postMessage,Mo)):xe.addEventListener&&Jh(xe.postMessage)&&!xe.importScripts&&fi&&fi.protocol!=="file:"&&!am(im)?(Qt=im,xe.addEventListener("message",rm,!1)):tm in Zh("script")?Qt=function(i){Xh.appendChild(Zh("script"))[tm]=function(){Xh.removeChild(this),Oo(i)}}:Qt=function(i){setTimeout(Co(i),0)});sm.exports={set:Do,clear:Vo}});var um=m((iV,om)=>{"use strict";var nm=G(),hA=Te(),mA=Object.getOwnPropertyDescriptor;om.exports=function(i){if(!hA)return nm[i];var e=mA(nm,i);return e&&e.value}});var _o=m((aV,cm)=>{"use strict";var lm=function(){this.head=null,this.tail=null};lm.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}}};cm.exports=lm});var pm=m((sV,dm)=>{"use strict";var fA=qt();dm.exports=/ipad|iphone|ipod/i.test(fA)&&typeof Pebble<"u"});var mm=m((nV,hm)=>{"use strict";var bA=qt();hm.exports=/web0s(?!.*chrome)/i.test(bA)});var Tm=m((oV,ym)=>{"use strict";var Pr=G(),gA=um(),fm=gr(),No=Bo().set,SA=_o(),vA=wo(),yA=pm(),TA=mm(),Fo=ns(),bm=Pr.MutationObserver||Pr.WebKitMutationObserver,gm=Pr.document,Sm=Pr.process,os=Pr.Promise,Ho=gA("queueMicrotask"),xr,qo,Uo,us,vm;Ho||(bi=new SA,gi=function(){var i,e;for(Fo&&(i=Sm.domain)&&i.exit();e=bi.get();)try{e()}catch(t){throw bi.head&&xr(),t}i&&i.enter()},!vA&&!Fo&&!TA&&bm&&gm?(qo=!0,Uo=gm.createTextNode(""),new bm(gi).observe(Uo,{characterData:!0}),xr=function(){Uo.data=qo=!qo}):!yA&&os&&os.resolve?(us=os.resolve(void 0),us.constructor=os,vm=fm(us.then,us),xr=function(){vm(gi)}):Fo?xr=function(){Sm.nextTick(gi)}:(No=fm(No,Pr),xr=function(){No(gi)}),Ho=function(i){bi.head||xr(),bi.add(i)});var bi,gi;ym.exports=Ho});var Em=m((uV,Im)=>{"use strict";Im.exports=function(i,e){try{arguments.length===1?console.error(i):console.error(i,e)}catch{}}});var ls=m((lV,xm)=>{"use strict";xm.exports=function(i){try{return{error:!1,value:i()}}catch(e){return{error:!0,value:e}}}});var Gt=m((cV,Pm)=>{"use strict";var IA=G();Pm.exports=IA.Promise});var Ar=m((dV,Rm)=>{"use strict";var EA=G(),Si=Gt(),xA=Q(),PA=_n(),AA=xo(),kA=ie(),Am=Io(),wA=_e(),jo=Pn(),km=Si&&Si.prototype,RA=kA("species"),Qo=!1,wm=xA(EA.PromiseRejectionEvent),$A=PA("Promise",function(){var i=AA(Si),e=i!==String(Si);if(!e&&jo===66||wA&&!(km.catch&&km.finally))return!0;if(!jo||jo<51||!/native code/.test(i)){var t=new Si(function(s){s(1)}),r=function(s){s(function(){},function(){})},a=t.constructor={};if(a[RA]=r,Qo=t.then(function(){})instanceof r,!Qo)return!0}return!e&&(Am==="BROWSER"||Am==="DENO")&&!wm});Rm.exports={CONSTRUCTOR:$A,REJECTION_EVENT:wm,SUBCLASSING:Qo}});var kr=m((pV,Lm)=>{"use strict";var $m=We(),LA=TypeError,MA=function(i){var e,t;this.promise=new i(function(r,a){if(e!==void 0||t!==void 0)throw new LA("Bad Promise constructor");e=r,t=a}),this.resolve=$m(e),this.reject=$m(t)};Lm.exports.f=function(i){return new MA(i)}});var Km=m(()=>{"use strict";var CA=K(),DA=_e(),hs=ns(),yt=G(),Lr=Ie(),Mm=Er(),Cm=bo(),VA=li(),OA=Ch(),BA=We(),ps=Q(),_A=Ee(),NA=Vh(),FA=ko(),_m=Bo().set,Ko=Tm(),qA=Em(),UA=ls(),HA=_o(),Nm=ro(),ms=Gt(),Jo=Ar(),Fm=kr(),fs="Promise",qm=Jo.CONSTRUCTOR,jA=Jo.REJECTION_EVENT,QA=Jo.SUBCLASSING,Go=Nm.getterFor(fs),GA=Nm.set,wr=ms&&ms.prototype,Wt=ms,cs=wr,Um=yt.TypeError,Wo=yt.document,Xo=yt.process,Yo=Fm.f,WA=Yo,YA=!!(Wo&&Wo.createEvent&&yt.dispatchEvent),Hm="unhandledrejection",zA="rejectionhandled",Dm=0,jm=1,KA=2,Zo=1,Qm=2,ds,Vm,JA,Om,Gm=function(i){var e;return _A(i)&&ps(e=i.then)?e:!1},Wm=function(i,e){var t=e.value,r=e.state===jm,a=r?i.ok:i.fail,s=i.resolve,n=i.reject,o=i.domain,u,l,c;try{a?(r||(e.rejection===Qm&&ZA(e),e.rejection=Zo),a===!0?u=t:(o&&o.enter(),u=a(t),o&&(o.exit(),c=!0)),u===i.promise?n(new Um("Promise-chain cycle")):(l=Gm(u))?Lr(l,u,s,n):s(u)):n(t)}catch(d){o&&!c&&o.exit(),n(d)}},Ym=function(i,e){i.notified||(i.notified=!0,Ko(function(){for(var t=i.reactions,r;r=t.get();)Wm(r,i);i.notified=!1,e&&!i.rejection&&XA(i)}))},zm=function(i,e,t){var r,a;YA?(r=Wo.createEvent("Event"),r.promise=e,r.reason=t,r.initEvent(i,!1,!0),yt.dispatchEvent(r)):r={promise:e,reason:t},!jA&&(a=yt["on"+i])?a(r):i===Hm&&qA("Unhandled promise rejection",t)},XA=function(i){Lr(_m,yt,function(){var e=i.facade,t=i.value,r=Bm(i),a;if(r&&(a=UA(function(){hs?Xo.emit("unhandledRejection",t,e):zm(Hm,e,t)}),i.rejection=hs||Bm(i)?Qm:Zo,a.error))throw a.value})},Bm=function(i){return i.rejection!==Zo&&!i.parent},ZA=function(i){Lr(_m,yt,function(){var e=i.facade;hs?Xo.emit("rejectionHandled",e):zm(zA,e,i.value)})},Rr=function(i,e,t){return function(r){i(e,r,t)}},$r=function(i,e,t){i.done||(i.done=!0,t&&(i=t),i.value=e,i.state=KA,Ym(i,!0))},zo=function(i,e,t){if(!i.done){i.done=!0,t&&(i=t);try{if(i.facade===e)throw new Um("Promise can't be resolved itself");var r=Gm(e);r?Ko(function(){var a={done:!1};try{Lr(r,e,Rr(zo,a,i),Rr($r,a,i))}catch(s){$r(a,s,i)}}):(i.value=e,i.state=jm,Ym(i,!1))}catch(a){$r({done:!1},a,i)}}};if(qm&&(Wt=function(e){NA(this,cs),BA(e),Lr(ds,this);var t=Go(this);try{e(Rr(zo,t),Rr($r,t))}catch(r){$r(t,r)}},cs=Wt.prototype,ds=function(e){GA(this,{type:fs,done:!1,notified:!1,parent:!1,reactions:new HA,rejection:!1,state:Dm,value:void 0})},ds.prototype=Mm(cs,"then",function(e,t){var r=Go(this),a=Yo(FA(this,Wt));return r.parent=!0,a.ok=ps(e)?e:!0,a.fail=ps(t)&&t,a.domain=hs?Xo.domain:void 0,r.state===Dm?r.reactions.add(a):Ko(function(){Wm(a,r)}),a.promise}),Vm=function(){var i=new ds,e=Go(i);this.promise=i,this.resolve=Rr(zo,e),this.reject=Rr($r,e)},Fm.f=Yo=function(i){return i===Wt||i===JA?new Vm(i):WA(i)},!DA&&ps(ms)&&wr!==Object.prototype)){Om=wr.then,QA||Mm(wr,"then",function(e,t){var r=this;return new Wt(function(a,s){Lr(Om,r,a,s)}).then(e,t)},{unsafe:!0});try{delete wr.constructor}catch{}Cm&&Cm(wr,cs)}CA({global:!0,constructor:!0,wrap:!0,forced:qm},{Promise:Wt});VA(Wt,fs,!1,!0);OA(fs)});var tf=m((fV,ef)=>{"use strict";var ek=ie(),Xm=ek("iterator"),Zm=!1;try{Jm=0,eu={next:function(){return{done:!!Jm++}},return:function(){Zm=!0}},eu[Xm]=function(){return this},Array.from(eu,function(){throw 2})}catch{}var Jm,eu;ef.exports=function(i,e){try{if(!e&&!Zm)return!1}catch{return!1}var t=!1;try{var r={};r[Xm]=function(){return{next:function(){return{done:t=!0}}}},i(r)}catch{}return t}});var tu=m((bV,rf)=>{"use strict";var tk=Gt(),rk=tf(),ik=Ar().CONSTRUCTOR;rf.exports=ik||!rk(function(i){tk.all(i).then(void 0,function(){})})});var af=m(()=>{"use strict";var ak=K(),sk=Ie(),nk=We(),ok=kr(),uk=ls(),lk=is(),ck=tu();ak({target:"Promise",stat:!0,forced:ck},{all:function(e){var t=this,r=ok.f(t),a=r.resolve,s=r.reject,n=uk(function(){var o=nk(t.resolve),u=[],l=0,c=1;lk(e,function(d){var p=l++,h=!1;c++,sk(o,t,d).then(function(f){h||(h=!0,u[p]=f,--c||a(u))},s)}),--c||a(u)});return n.error&&s(n.value),r.promise}})});var nf=m(()=>{"use strict";var dk=K(),pk=_e(),hk=Ar().CONSTRUCTOR,iu=Gt(),mk=at(),fk=Q(),bk=Er(),sf=iu&&iu.prototype;dk({target:"Promise",proto:!0,forced:hk,real:!0},{catch:function(i){return this.then(void 0,i)}});!pk&&fk(iu)&&(ru=mk("Promise").prototype.catch,sf.catch!==ru&&bk(sf,"catch",ru,{unsafe:!0}));var ru});var of=m(()=>{"use strict";var gk=K(),Sk=Ie(),vk=We(),yk=kr(),Tk=ls(),Ik=is(),Ek=tu();gk({target:"Promise",stat:!0,forced:Ek},{race:function(e){var t=this,r=yk.f(t),a=r.reject,s=Tk(function(){var n=vk(t.resolve);Ik(e,function(o){Sk(n,t,o).then(r.resolve,a)})});return s.error&&a(s.value),r.promise}})});var uf=m(()=>{"use strict";var xk=K(),Pk=kr(),Ak=Ar().CONSTRUCTOR;xk({target:"Promise",stat:!0,forced:Ak},{reject:function(e){var t=Pk.f(this),r=t.reject;return r(e),t.promise}})});var au=m((PV,lf)=>{"use strict";var kk=Ye(),wk=Ee(),Rk=kr();lf.exports=function(i,e){if(kk(i),wk(e)&&e.constructor===i)return e;var t=Rk.f(i),r=t.resolve;return r(e),t.promise}});var pf=m(()=>{"use strict";var $k=K(),Lk=at(),cf=_e(),Mk=Gt(),df=Ar().CONSTRUCTOR,Ck=au(),Dk=Lk("Promise"),Vk=cf&&!df;$k({target:"Promise",stat:!0,forced:cf||df},{resolve:function(e){return Ck(Vk&&this===Dk?Mk:this,e)}})});var hf=m(()=>{"use strict";Km();af();nf();of();uf();pf()});var gf=m(()=>{"use strict";var Ok=K(),Bk=_e(),bs=Gt(),_k=re(),ff=at(),bf=Q(),Nk=ko(),mf=au(),Fk=Er(),nu=bs&&bs.prototype,qk=!!bs&&_k(function(){nu.finally.call({then:function(){}},function(){})});Ok({target:"Promise",proto:!0,real:!0,forced:qk},{finally:function(i){var e=Nk(this,ff("Promise")),t=bf(i);return this.then(t?function(r){return mf(e,i()).then(function(){return r})}:i,t?function(r){return mf(e,i()).then(function(){throw r})}:i)}});!Bk&&bf(bs)&&(su=ff("Promise").prototype.finally,nu.finally!==su&&Fk(nu,"finally",su,{unsafe:!0}));var su});var vf=m((MV,Sf)=>{"use strict";Ah();hf();gf();var Uk=vt();Sf.exports=Uk("Promise","finally")});var Tf=m((CV,yf)=>{"use strict";var Hk=vf();yf.exports=Hk});var gs=m((DV,If)=>{"use strict";var jk=Tf();If.exports=jk});var Vf=m(()=>{"use strict";var aw=K(),sw=Xn().values;aw({target:"Object",stat:!0},{values:function(e){return sw(e)}})});var Bf=m((SO,Of)=>{"use strict";Vf();var nw=mr();Of.exports=nw.Object.values});var Nf=m((vO,_f)=>{"use strict";var ow=Bf();_f.exports=ow});var yi=m((yO,Ff)=>{"use strict";var uw=Nf();Ff.exports=uw});var Zf=m(()=>{"use strict";var xw=K(),Pw=fr(),Aw=Tr(),kw=si(),ww=ni();xw({target:"Array",proto:!0},{at:function(e){var t=Pw(this),r=Aw(t),a=kw(e),s=a>=0?a:r+a;return s<0||s>=r?void 0:t[s]}});ww("at")});var tb=m((YO,eb)=>{"use strict";Zf();var Rw=vt();eb.exports=Rw("Array","at")});var ib=m((zO,rb)=>{"use strict";var $w=tb();rb.exports=$w});var Dr=m((KO,ab)=>{"use strict";var Lw=ib();ab.exports=Lw});var Ru=m((R_,Db)=>{"use strict";var hR=Nt();Db.exports=Array.isArray||function(e){return hR(e)==="Array"}});var Ob=m(($_,Vb)=>{"use strict";var mR=TypeError,fR=9007199254740991;Vb.exports=function(i){if(i>fR)throw mR("Maximum allowed index exceeded");return i}});var Nb=m((L_,_b)=>{"use strict";var bR=Ru(),gR=Tr(),SR=Ob(),vR=gr(),Bb=function(i,e,t,r,a,s,n,o){for(var u=a,l=0,c=n?vR(n,o):!1,d,p;l<r;)l in t&&(d=c?c(t[l],l,e):t[l],s>0&&bR(d)?(p=gR(d),u=Bb(i,e,d,p,u,s-1)-1):(SR(u+1),i[u]=d),u++),l++;return u};_b.exports=Bb});var Hb=m((M_,Ub)=>{"use strict";var Fb=Ru(),yR=Ao(),TR=Ee(),IR=ie(),ER=IR("species"),qb=Array;Ub.exports=function(i){var e;return Fb(i)&&(e=i.constructor,yR(e)&&(e===qb||Fb(e.prototype))?e=void 0:TR(e)&&(e=e[ER],e===null&&(e=void 0))),e===void 0?qb:e}});var Qb=m((C_,jb)=>{"use strict";var xR=Hb();jb.exports=function(i,e){return new(xR(i))(e===0?0:e)}});var Gb=m(()=>{"use strict";var PR=K(),AR=Nb(),kR=We(),wR=fr(),RR=Tr(),$R=Qb();PR({target:"Array",proto:!0},{flatMap:function(e){var t=wR(this),r=RR(t),a;return kR(e),a=$R(t,0),a.length=AR(a,t,t,r,0,1,e,arguments.length>1?arguments[1]:void 0),a}})});var Wb=m(()=>{"use strict";var LR=ni();LR("flatMap")});var zb=m((__,Yb)=>{"use strict";Gb();Wb();var MR=vt();Yb.exports=MR("Array","flatMap")});var Jb=m((N_,Kb)=>{"use strict";var CR=zb();Kb.exports=CR});var $u=m((F_,Xb)=>{"use strict";var DR=Jb();Xb.exports=DR});var Di=m((K_,ug)=>{"use strict";var UR=ui(),HR=String;ug.exports=function(i){if(UR(i)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return HR(i)}});var Mu=m((J_,lg)=>{"use strict";lg.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 pg=m((X_,dg)=>{"use strict";var jR=J(),QR=St(),GR=Di(),Du=Mu(),cg=jR("".replace),WR=RegExp("^["+Du+"]+"),YR=RegExp("(^|[^"+Du+"])["+Du+"]+$"),Cu=function(i){return function(e){var t=GR(QR(e));return i&1&&(t=cg(t,WR,"")),i&2&&(t=cg(t,YR,"$1")),t}};dg.exports={start:Cu(1),end:Cu(2),trim:Cu(3)}});var bg=m((Z_,fg)=>{"use strict";var zR=so().PROPER,KR=re(),hg=Mu(),mg="\u200B\x85\u180E";fg.exports=function(i){return KR(function(){return!!hg[i]()||mg[i]()!==mg||zR&&hg[i].name!==i})}});var Vu=m((eN,gg)=>{"use strict";var JR=pg().start,XR=bg();gg.exports=XR("trimStart")?function(){return JR(this)}:"".trimStart});var vg=m(()=>{"use strict";var ZR=K(),Sg=Vu();ZR({target:"String",proto:!0,name:"trimStart",forced:"".trimLeft!==Sg},{trimLeft:Sg})});var Tg=m(()=>{"use strict";vg();var e$=K(),yg=Vu();e$({target:"String",proto:!0,name:"trimStart",forced:"".trimStart!==yg},{trimStart:yg})});var Eg=m((sN,Ig)=>{"use strict";Tg();var t$=vt();Ig.exports=t$("String","trimLeft")});var Pg=m((nN,xg)=>{"use strict";var r$=Eg();xg.exports=r$});var kg=m((oN,Ag)=>{"use strict";var i$=Pg();Ag.exports=i$});var Hg=m(()=>{"use strict"});var jg=m(()=>{"use strict"});var Gg=m((Lq,Qg)=>{"use strict";var A$=Ee(),k$=Nt(),w$=ie(),R$=w$("match");Qg.exports=function(i){var e;return A$(i)&&((e=i[R$])!==void 0?!!e:k$(i)==="RegExp")}});var Yg=m((Mq,Wg)=>{"use strict";var $$=Ye();Wg.exports=function(){var i=$$(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 Jg=m((Cq,Kg)=>{"use strict";var L$=Ie(),M$=Ne(),C$=Zr(),D$=Yg(),zg=RegExp.prototype;Kg.exports=function(i){var e=i.flags;return e===void 0&&!("flags"in zg)&&!M$(i,"flags")&&C$(zg,i)?L$(D$,i):e}});var Zg=m((Dq,Xg)=>{"use strict";var ju=J(),V$=fr(),O$=Math.floor,Uu=ju("".charAt),B$=ju("".replace),Hu=ju("".slice),_$=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,N$=/\$([$&'`]|\d{1,2})/g;Xg.exports=function(i,e,t,r,a,s){var n=t+i.length,o=r.length,u=N$;return a!==void 0&&(a=V$(a),u=_$),B$(s,u,function(l,c){var d;switch(Uu(c,0)){case"$":return"$";case"&":return i;case"`":return Hu(e,0,t);case"'":return Hu(e,n);case"<":d=a[Hu(c,1,-1)];break;default:var p=+c;if(p===0)return l;if(p>o){var h=O$(p/10);return h===0?l:h<=o?r[h-1]===void 0?Uu(c,1):r[h-1]+Uu(c,1):l}d=r[p-1]}return d===void 0?"":d})}});var rS=m(()=>{"use strict";var F$=K(),q$=Ie(),Gu=J(),eS=St(),U$=Q(),H$=hr(),j$=Gg(),Fr=Di(),Q$=ti(),G$=Jg(),W$=Zg(),Y$=ie(),z$=_e(),K$=Y$("replace"),J$=TypeError,Qu=Gu("".indexOf),X$=Gu("".replace),tS=Gu("".slice),Z$=Math.max;F$({target:"String",proto:!0},{replaceAll:function(e,t){var r=eS(this),a,s,n,o,u,l,c,d,p,h,f=0,b="";if(!H$(e)){if(a=j$(e),a&&(s=Fr(eS(G$(e))),!~Qu(s,"g")))throw new J$("`.replaceAll` does not allow non-global regexes");if(n=Q$(e,K$),n)return q$(n,e,r,t);if(z$&&a)return X$(Fr(r),e,t)}for(o=Fr(r),u=Fr(e),l=U$(t),l||(t=Fr(t)),c=u.length,d=Z$(1,c),p=Qu(o,u);p!==-1;)h=l?Fr(t(u,p,o)):W$(u,o,p,[],void 0,t),b+=tS(o,f,p)+h,f=p+c,p=p+d>o.length?-1:Qu(o,u,p+d);return f<o.length&&(b+=tS(o,f)),b}})});var aS=m((Bq,iS)=>{"use strict";Hg();jg();rS();var eL=vt();iS.exports=eL("String","replaceAll")});var nS=m((_q,sS)=>{"use strict";var tL=aS();sS.exports=tL});var uS=m((Nq,oS)=>{"use strict";var rL=nS();oS.exports=rL});var cS=m((Fq,lS)=>{"use strict";var iL=si(),aL=Di(),sL=St(),nL=RangeError;lS.exports=function(e){var t=aL(sL(this)),r="",a=iL(e);if(a<0||a===1/0)throw new nL("Wrong number of repetitions");for(;a>0;(a>>>=1)&&(t+=t))a&1&&(r+=t);return r}});var fS=m((qq,mS)=>{"use strict";var hS=J(),oL=jn(),dS=Di(),uL=cS(),lL=St(),cL=hS(uL),dL=hS("".slice),pL=Math.ceil,pS=function(i){return function(e,t,r){var a=dS(lL(e)),s=oL(t),n=a.length,o=r===void 0?" ":dS(r),u,l;return s<=n||o===""?a:(u=s-n,l=cL(o,pL(u/o.length)),l.length>u&&(l=dL(l,0,u)),i?a+l:l+a)}};mS.exports={start:pS(!1),end:pS(!0)}});var gS=m((Uq,bS)=>{"use strict";var hL=qt();bS.exports=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(hL)});var SS=m(()=>{"use strict";var mL=K(),fL=fS().start,bL=gS();mL({target:"String",proto:!0,forced:bL},{padStart:function(e){return fL(this,e,arguments.length>1?arguments[1]:void 0)}})});var yS=m((Qq,vS)=>{"use strict";SS();var gL=vt();vS.exports=gL("String","padStart")});var IS=m((Gq,TS)=>{"use strict";var SL=yS();TS.exports=SL});var xS=m((Wq,ES)=>{"use strict";var vL=IS();ES.exports=vL});var $l="2.0.119-dev.df6b2fd8.0";var ce=(a=>(a.STOPPED="stopped",a.READY="ready",a.PLAYING="playing",a.PAUSED="paused",a))(ce||{}),gt=(T=>(T.MPEG="MPEG",T.DASH="DASH",T.DASH_SEP="DASH_SEP",T.DASH_SEP_VK="DASH_SEP",T.DASH_WEBM="DASH_WEBM",T.DASH_WEBM_AV1="DASH_WEBM_AV1",T.DASH_STREAMS="DASH_STREAMS",T.DASH_WEBM_VK="DASH_WEBM",T.DASH_ONDEMAND="DASH_ONDEMAND",T.DASH_ONDEMAND_VK="DASH_ONDEMAND",T.DASH_LIVE="DASH_LIVE",T.DASH_LIVE_CMAF="DASH_LIVE_CMAF",T.DASH_LIVE_WEBM="DASH_LIVE_WEBM",T.HLS="HLS",T.HLS_ONDEMAND="HLS_ONDEMAND",T.HLS_JS="HLS",T.HLS_LIVE="HLS_LIVE",T.HLS_LIVE_CMAF="HLS_LIVE_CMAF",T.WEB_RTC_LIVE="WEB_RTC_LIVE",T))(gt||{});var Ba=(a=>(a.NOT_AVAILABLE="NOT_AVAILABLE",a.AVAILABLE="AVAILABLE",a.CONNECTING="CONNECTING",a.CONNECTED="CONNECTED",a))(Ba||{}),hn=(r=>(r.HTTP1="http1",r.HTTP2="http2",r.QUIC="quic",r))(hn||{});var mn=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(mn||{}),zr=(r=>(r.TRAFFIC_SAVING="traffic_saving",r.HIGH_QUALITY="high_quality",r.UNKNOWN="unknown",r))(zr||{});var Zv=D(ze(),1);import{assertNever as wd,assertNonNullable as LI,isNonNullable as Ua,ValueSubject as Gn,Subject as MI,Subscription as CI,merge as DI,observableFrom as VI,fromEvent as xd,map as Pd,tap as Ad,filterChanged as OI,isNullable as Wn,ErrorCategory as kd}from"@vkontakte/videoplayer-shared";var Ed=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 Ha=class{constructor(e){this.connection$=new Gn(void 0);this.castState$=new Gn("NOT_AVAILABLE");this.errorEvent$=new MI;this.realCastState$=new Gn("NOT_AVAILABLE");this.subscription=new CI;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=Ua(window.chrome?.cast),a=!!window.__onGCastApiAvailable;r?this.initializeCastApi():(window.__onGCastApiAvailable=s=>{delete window.__onGCastApiAvailable,s&&this.initializeCastApi()},a||Ed("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:kd.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(){Ua(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();Wn(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();Wn(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(xd(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 wd(a.sessionState)}})).add(DI(xd(r,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(Ad(a=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(a)}`})}),Pd(a=>a.castState)),VI([r.getCastState()])).pipe(OI(),Pd(BI),Ad(a=>{this.log({message:`realCastState$: ${a}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(a=>{let s=a==="CONNECTED",n=Ua(this.connection$.getValue());if(s&&!n){let o=r.getCurrentSession();LI(o);let u=o.getCastDevice(),l=o.getMediaSession()?.media?.contentId;(Wn(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"?Ua(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:kd.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:a})}}},BI=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 wd(i)}};var Tl=D(ze(),1),Dv=D(Ir(),1),Vv=D(To(),1);var Mf=D(gs(),1);import{assertNever as Ef}from"@vkontakte/videoplayer-shared";var ae=(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:Ef(t)}return i},Ss=(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:Ef(e)}};var y=(i,e,t=!1)=>{let r=i.getTransition();(t||!r||r.to===e)&&i.setState(e)};import{isNonNullable as Qk,Subject as vs,merge as xf}from"@vkontakte/videoplayer-shared";var L=class{constructor(e){this.transitionStarted$=new vs;this.transitionEnded$=new vs;this.transitionUpdated$=new vs;this.forceChanged$=new vs;this.stateChangeStarted$=xf(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=xf(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||Qk(t)&&t.to===e||(this.prevState=r,this.state=e,t?(this.transition={from:t.from,to:e,canceledTransition:t},this.transitionUpdated$.next(this.transition)):(this.transition={from:r,to:e},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}getPrevState(){return this.prevState}};import{assertNever as Gk}from"@vkontakte/videoplayer-shared";var Pf=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 Gk(i)}};import{assertNever as Mr,assertNonNullable as Yt,debounce as Af,ErrorCategory as kf,fromEvent as zt,isNonNullable as wf,map as Rf,merge as $f,observableFrom as Wk,Subject as Yk,Subscription as ou,timeout as zk,getHighestQuality as Kk}from"@vkontakte/videoplayer-shared";var Jk=5,Xk=5,Zk=500,Lf=7e3,vi=class{constructor(e){this.subscription=new ou;this.loadMediaTimeoutSubscription=new ou;this.videoState=new L("stopped");this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),r=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${r}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(s)};`}),r==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.stop());return}if(!t){if(a?.to!=="paused"&&s.state==="requested"&&e!=="stopped"){this.seek(s.position/1e3);return}switch(r){case"ready":{switch(e){case"playing":case"paused":case"ready":break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:Mr(e)}break}case"playing":{switch(e){case"playing":break;case"paused":this.videoState.startTransitionTo("playing"),this.params.connection.remotePlayerController.playOrPause();break;case"ready":this.videoState.startTransitionTo("playing"),this.params.connection.remotePlayerController.playOrPause();break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:Mr(e)}break}case"paused":{switch(e){case"playing":this.videoState.startTransitionTo("paused"),this.params.connection.remotePlayerController.playOrPause();break;case"paused":break;case"ready":this.videoState.startTransitionTo("paused"),this.videoState.setState("paused");break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:Mr(e)}break}default:Mr(r)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(Pf(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 ou;this.subscription.add(e),this.subscription.add($f(this.videoState.stateChangeStarted$.pipe(Rf(a=>`stateChangeStarted$ ${JSON.stringify(a)}`)),this.videoState.stateChangeEnded$.pipe(Rf(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 Yk;e.add(a.pipe(Af(Zk)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add(zt(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)>Jk)&&a.next(o),s=o})),e.add(zt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(zt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),a=>{this.logRemoteEvent(a),a.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(zt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),a=>{this.logRemoteEvent(a),a.value?this.handleRemotePause():this.handleRemotePlay()}),t(zt(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<Xk&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),y(this.params.desiredState.playbackState,"stopped");break;case chrome.cast.media.PlayerState.PAUSED:{this.handleRemotePause();break}case chrome.cast.media.PlayerState.PLAYING:this.handleRemotePlay();break;case chrome.cast.media.PlayerState.BUFFERING:break;default:Mr(n)}}),t(zt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),a=>{this.logRemoteEvent(a),this.handleRemoteVolumeChange({volume:a.value})}),t(zt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),a=>{this.logRemoteEvent(a),this.handleRemoteVolumeChange({muted:a.value})});let r=$f(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Wk(["init"])).pipe(Af(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"),y(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),y(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"),y(this.params.desiredState.playbackState,"paused"))}handleRemotePlay(){let e=this.videoState.getState();(this.videoState.getTransition()?.to==="playing"||e==="paused")&&(this.videoState.setState("playing"),y(this.params.desiredState.playbackState,"playing"))}handleRemoteReady(){this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.params.desiredState.playbackState.getTransition()?.to==="ready"&&y(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];Yt(l);let c=Kk(Object.keys(l));Yt(c);let d=l[c];Yt(d),r=d,a="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let l=t[e];Yt(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];Yt(l),r=l.url,a="application/dash+xml",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let l=t[e];Yt(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];Yt(l),r=ae(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:kf.VIDEO_PIPELINE,message:l,thrown:c}),c}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return Mr(e)}let n=new chrome.cast.media.MediaInfo(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 wf(o)&&(n.metadata.title=o),wf(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(zk(Lf).subscribe(()=>s(`timeout(${Lf})`)))});(0,Mf.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:kf.VIDEO_PIPELINE,message:s,thrown:a})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var ku=D(ze(),1);import{clearVideoElement as Df}from"@vkontakte/videoplayer-shared";import{clearVideoElement as ew}from"@vkontakte/videoplayer-shared";var Cf=i=>{try{i.pause(),i.playbackRate=0,ew(i),i.remove()}catch(e){console.error(e)}};import{fromEvent as tw,Subscription as rw}from"@vkontakte/videoplayer-shared";var uu=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)}},lu=window.WeakMap?new WeakMap:new uu,cu=window.WeakMap?new WeakMap:new Map,iw=(i,e=20)=>{let t=0;return tw(i,"ratechange").subscribe(r=>{t++,t>=e&&(i.currentTime=i.currentTime,t=0)})},de=(i,{audioVideoSyncRate:e})=>{let t=i.querySelector("video"),r=!!t;t?Df(t):(t=document.createElement("video"),i.appendChild(t)),lu.set(t,r);let a=new rw;return a.add(iw(t,e)),cu.set(t,a),t.setAttribute("crossorigin","anonymous"),t.setAttribute("playsinline","playsinline"),t.controls=!1,t.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),t},pe=i=>{cu.get(i)?.unsubscribe(),cu.delete(i);let t=lu.get(i);lu.delete(i),t?Df(i):Cf(i)};var pu=D(yi(),1);import{assertNonNullable as Ti,isNonNullable as Je,isNullable as dw,fromEvent as Cr,merge as qf,observableFrom as Uf,filterChanged as Hf,map as Ii,Subject as jf,Subscription as pw,ValueSubject as hw,ErrorCategory as mw}from"@vkontakte/videoplayer-shared";import{isNonNullable as du,isNullable as lw,Subscription as cw}from"@vkontakte/videoplayer-shared";var ys=(i,e,t,{equal:r=(n,o)=>n===o,changed$:a,onError:s}={})=>{let n=i.getState(),o=e(),u=lw(a),l=new cw;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},Ke=(i,e,t)=>ys(e,()=>i.loop,r=>{du(r)&&(i.loop=r)},{onError:t}),he=(i,e,t,r)=>ys(e,()=>({muted:i.muted,volume:i.volume}),a=>{du(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}),Re=(i,e,t,r)=>ys(e,()=>i.playbackRate,a=>{du(a)&&(i.playbackRate=a)},{changed$:t,onError:r}),Tt=ys;var fw=i=>["__",i.language,i.label].join("|"),bw=(i,e)=>{if(i.id===e)return!0;let[t,r,a]=e.split("|");return i.language===r&&i.label===a},hu=class i{constructor(){this.available$=new jf;this.current$=new hw(void 0);this.error$=new jf;this.subscription=new pw;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:mw.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(Tt(t.internalTextTracks,()=>(0,pu.default)(this.internalTracks),s=>{Je(s)&&this.setInternal(s)},{equal:(s,n)=>Je(s)&&Je(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(Ii(s=>s.filter(({type:n})=>n==="internal"))),onError:a})),this.subscription.add(Tt(t.externalTextTracks,()=>(0,pu.default)(this.externalTracks),s=>{Je(s)&&this.setExternal(s)},{equal:(s,n)=>Je(s)&&Je(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(Ii(s=>s.filter(({type:n})=>n==="external"))),onError:a})),this.subscription.add(Tt(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(Tt(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.activeCues)}))}subscribe(){Ti(this.video);let{textTracks:e}=this.video;this.subscription.add(Cr(e,"addtrack").subscribe(()=>{let r=this.current$.getValue();r&&this.select(r)})),this.subscription.add(qf(Cr(e,"addtrack"),Cr(e,"removetrack"),Uf(["init"])).pipe(Ii(()=>this.htmlTextTracksAsArray().map(r=>this.htmlTextTrackToITextTrack(r))),Hf((r,a)=>r.length===a.length&&r.every(({id:s},n)=>s===a[n].id))).subscribe(this.available$)),this.subscription.add(qf(Cr(e,"change"),Uf(["init"])).pipe(Ii(()=>this.htmlTextTracksAsArray().find(({mode:r})=>r==="showing")),Ii(r=>r&&this.htmlTextTrackToITextTrack(r).id),Hf()).subscribe(this.current$));let t=r=>this.applyCueSettings(r.target?.activeCues??null);this.subscription.add(Cr(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(Cr(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;Je(t.align)&&(a.align=t.align),Je(t.position)&&(a.position=t.position),Je(t.size)&&(a.size=t.size),Je(t.line)&&(a.line=t.line)}}htmlTextTracksAsArray(e=!1){Ti(this.video);let t=[...this.video.textTracks];return e?t:t.filter(i.isHealthyTrack)}htmlTextTrackToITextTrack(e){let{language:t,label:r}=e,a=e.id?e.id:fw(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){Ti(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(dw(e)||!bw(t,e))&&(t.mode="disabled")}destroy(){if(this.subscription.unsubscribe(),this.video)for(let e of Array.from(this.video.getElementsByTagName("track"))){let t=e.getAttribute("id");t&&this.externalTracks.has(t)&&this.video.removeChild(e)}this.externalTracks.clear()}attach(e){Ti(this.video);let t=document.createElement("track");t.setAttribute("src",e.url),t.setAttribute("id",e.id),e.label&&t.setAttribute("label",e.label),e.language&&t.setAttribute("srclang",e.language),e.type==="external"?this.externalTracks.set(e.id,e):e.type==="internal"&&this.internalTracks.set(e.id,e),this.video.appendChild(t)}detach(e){Ti(this.video);let t=Array.prototype.find.call(this.video.getElementsByTagName("track"),r=>r.getAttribute("id")===e.id);t&&this.video.removeChild(t),e.type==="external"?this.externalTracks.delete(e.id):e.type==="internal"&&this.internalTracks.delete(e.id)}},$e=hu;var ot=class{constructor(){this.pausedTime=0;this.streamOffset=0;this.pauseTimestamp=0}getTotalPausedTime(){return this.pausedTime+this.getCurrentPausedTime()}getCurrentPausedTime(){return this.pauseTimestamp>0?Date.now()-this.pauseTimestamp:0}getStreamOffset(){return this.streamOffset}getTotalOffset(){return this.getTotalPausedTime()+this.streamOffset}pause(){this.pauseTimestamp===0&&(this.pauseTimestamp=Date.now())}resume(){this.pauseTimestamp>0&&(this.pausedTime+=this.getCurrentPausedTime(),this.pauseTimestamp=0)}resetTo(e,t=!1){this.streamOffset=e,this.pauseTimestamp=0,this.pausedTime=0,t&&this.pause()}};var Qf=i=>{let e=i;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e?.parentNode;return e??void 0},mu=i=>{let e=Qf(i);return!!(e&&e.fullscreenElement&&e.fullscreenElement===i)},Gf=i=>{let e=Qf(i);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===i)};import{fromEvent as Le,map as It,merge as Yf,filterChanged as Sw,isNonNullable as zf,Subject as vw,filter as Kf,mapTo as Jf,combine as yw,once as Tw,ErrorCategory as Iw,ValueSubject as Xf,clientChecker as Ew}from"@vkontakte/videoplayer-shared";var gw=3,Wf=(i,e,t=gw)=>{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 me=i=>{let e=T=>Le(i,T).pipe(Jf(void 0)),r=Yf(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(T=>Le(i,T))).pipe(It(T=>T.type==="ended"?i.readyState<2:i.readyState<3),Sw()),a=Yf(Le(i,"progress"),Le(i,"timeupdate")).pipe(It(()=>Wf(i.buffered,i.currentTime))),s=Ew.isSafari?yw({play:e("play").pipe(Tw()),playing:e("playing")}).pipe(Jf(void 0)):e("playing"),n=Le(i,"volumechange").pipe(It(()=>({muted:i.muted,volume:i.volume}))),o=Le(i,"ratechange").pipe(It(()=>i.playbackRate)),u=Le(i,"error").pipe(Kf(()=>!!(i.error||i.played.length)),It(()=>{let T=i.error;return{id:T?`MediaError#${T.code}`:"HtmlVideoError",category:Iw.VIDEO_PIPELINE,message:T?T.message:"Error event from HTML video element",thrown:i.error??void 0}})),l=Le(i,"timeupdate").pipe(It(()=>i.currentTime)),c=new vw,d=.3,p;l.subscribe(T=>{i.loop&&zf(p)&&zf(T)&&p>=i.duration-d&&T<=d&&c.next(p),p=T});let h=e("pause").pipe(Kf(()=>!i.error&&p!==i.duration)),f=Le(i,"enterpictureinpicture"),b=Le(i,"leavepictureinpicture"),g=new Xf(Gf(i));f.subscribe(()=>g.next(!0)),b.subscribe(()=>g.next(!1));let S=new Xf(mu(i));return Le(i,"fullscreenchange").pipe(It(()=>mu(i))).subscribe(S),{playing$:s,pause$:h,canplay$:e("canplay"),ended$:e("ended"),looped$:c,error$:u,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:l,durationChange$:Le(i,"durationchange").pipe(It(()=>i.duration)),isBuffering$:r,currentBuffer$:a,volumeState$:n,playbackRateState$:o,inPiP$:g,inFullscreen$:S}};import{VideoQuality as Et}from"@vkontakte/videoplayer-shared";var xt=i=>{switch(i){case"mobile":return Et.Q_144P;case"lowest":return Et.Q_240P;case"low":return Et.Q_360P;case"sd":case"medium":return Et.Q_480P;case"hd":case"high":return Et.Q_720P;case"fullhd":case"full":return Et.Q_1080P;case"quadhd":case"quad":return Et.Q_1440P;case"ultrahd":case"ultra":return Et.Q_2160P}};var Pt=D(Dr(),1),db=D(ze(),1),Is=D(Ir(),1);import{isNonNullable as X,isNullable as bu,now as pb,isHigher as gu,isHigherOrEqual as Su,isInvariantQuality as ub,isLower as lb,isLowerOrEqual as vu,videoSizeToQuality as Mw,assertNotEmptyArray as hb,assertNonNullable as Cw}from"@vkontakte/videoplayer-shared";var fu=!1,ut={},sb=i=>{fu=i},nb=()=>{ut={}},ob=i=>{i(ut)},Ei=(i,e)=>{fu&&(ut.meta=ut.meta??{},ut.meta[i]=e)},ne=class{constructor(e){this.name=e}next(e){if(!fu)return;ut.series=ut.series??{};let t=ut.series[this.name]??[];t.push([Date.now(),e]),ut.series[this.name]=t}};function Ts({limits:i,highQualityLimit:e,trafficSavingLimit:t}){return!i.max&&i.min===e?"high_quality":!i.min&&i.max===t?"traffic_saving":"unknown"}var Dw=new ne("best_bitrate"),mb=(i,e,t)=>(e-t)*Math.pow(2,-10*i)+t;var yu=i=>(e,t)=>i*(Number(e.bitrate)-Number(t.bitrate)),xi=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=pb()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},fb='Assertion "ABR Tracks is empty array" failed',Es=(i,e,t,r)=>{let a=[...e].sort(yu(1)),s=[...t].sort(yu(1)),n=s.filter(u=>X(u.bitrate)&&X(i.bitrate)?i.bitrate/u.bitrate>r:!0),o=(0,Pt.default)(s,Math.round(s.length*a.indexOf(i)/(a.length+1)))??(0,Pt.default)(s,-1);return o&&(0,db.default)(n,o)?o:n.length?(0,Pt.default)(n,-1):(0,Pt.default)(s,0)},cb=i=>"quality"in i,bb=(i,e,t,r)=>{let a=X(r?.last?.bitrate)&&X(t?.bitrate)&&r.last.bitrate<t.bitrate?i.trackCooldownIncreaseQuality:i.trackCooldownDecreaseQuality,s=t&&r&&r.history[t.id]&&pb()-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=cb(n)?"video":"audio",u=cb(n)?n.quality:n.bitrate;return e({message:`
8
8
  [last ${o} selected] ${u}
9
- `}),n}return r?.recordSwitch(t),t},Cw=(i,e)=>Math.log(e)/Math.log(i),At=(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:p,stallsPredictedThroughput:h,abrLogger:f})=>{cb(i,pb);let b=r.containerSizeFactor;if(r.usePixelRatio&&window.devicePixelRatio){let v=window.devicePixelRatio;if(r.pixelRatioMultiplier)b*=r.pixelRatioMultiplier*(v-1)+1;else{let T=r.pixelRatioLogBase,[q=0,ye=0,Ve=0]=r.pixelRatioLogCoefficients,P=Cw(T,q*v+ye)+Ve;Number.isFinite(P)&&(b*=P)}}let g=r.limitByContainer&&e&&e.width>0&&e.height>0?{width:e.width*b,height:e.height*b}:void 0,S=r.considerPlaybackRate&&X(o)?o:1,A=i.filter(v=>!sb(v.quality)).sort((v,T)=>mu(v.quality,T.quality)?-1:1),E=(0,Pt.default)(A,-1)?.quality,k=(0,Pt.default)(A,0)?.quality,y=hu(a)||X(a.min)&&X(a.max)&&nb(a.max,a.min)||X(a.min)&&k&&mu(a.min,k)||X(a.max)&&E&&nb(a.max,E),R=S*db(n??.5,r.bitrateFactorAtEmptyBuffer,r.bitrateFactorAtFullBuffer),B={},_=A.filter(v=>{let T=!0;if(g)if(v.size)T=v.size.width<=g.width&&v.size.height<=g.height;else{let te=g&&$w(g);T=te?bu(v.quality,te):!0}if(!T)return B[v.quality]="FitsContainer",!1;let q=h||t;if(!(X(q)&&isFinite(q)&&X(v.bitrate)?q-s>=v.bitrate*R:!0))return B[v.quality]="FitsThroughput",!1;if(r.lazyQualitySwitch&&X(r.minBufferToSwitchUp)&&u&&!sb(u.quality)&&(n??0)<r.minBufferToSwitchUp&&mu(v.quality,u.quality))return B[v.quality]="Buffer",!1;if(!!d&&fu(v.quality,d))return B[v.quality]="DroppedFramesLimit",!1;if(!!p&&fu(v.quality,p))return B[v.quality]="StallsLimit",!1;let w=y||(hu(a.max)||bu(v.quality,a.max))&&(hu(a.min)||fu(v.quality,a.min)),K=X(c)&&!c?bu(v.quality,r.backgroundVideoQualityLimit):!0;return!w||!K?(B[v.quality]="FitsQualityLimits",!1):!0})[0];_&&_.bitrate&&Mw.next(_.bitrate);let U=_??(0,Pt.default)(A,-1)??i[0];return U.quality!==l?.last?.quality&&f({message:`
9
+ `}),n}return r?.recordSwitch(t),t},Vw=(i,e)=>Math.log(e)/Math.log(i),Ow=({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=Vw(o,u*n+l)+c;Number.isFinite(d)&&(r*=d)}}let{highQualityLimit:a,trafficSavingLimit:s}=i;return t&&Ts({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},At=(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:p,stallsPredictedThroughput:h,abrLogger:f})=>{hb(i,fb);let b=Ow({container:e,tuning:r,limits:a}),g=r.considerPlaybackRate&&X(o)?o:1,S=i.filter(E=>!ub(E.quality)).sort((E,k)=>gu(E.quality,k.quality)?-1:1),x=(0,Pt.default)(S,-1)?.quality,T=(0,Pt.default)(S,0)?.quality,R=bu(a)||X(a.min)&&X(a.max)&&lb(a.max,a.min)||X(a.min)&&T&&gu(a.min,T)||X(a.max)&&x&&lb(a.max,x),v=g*mb(n??.5,r.bitrateFactorAtEmptyBuffer,r.bitrateFactorAtFullBuffer),w={},V=S.filter(E=>{let k=!0;if(b)if(E.size)k=E.size.width<=b.width&&E.size.height<=b.height;else{let Y=b&&Mw(b);k=Y?vu(E.quality,Y):!0}if(!k)return w[E.quality]="FitsContainer",!1;let P=h||t;if(!(X(P)&&isFinite(P)&&X(E.bitrate)?P-s>=E.bitrate*v:!0))return w[E.quality]="FitsThroughput",!1;if(r.lazyQualitySwitch&&X(r.minBufferToSwitchUp)&&u&&!ub(u.quality)&&(n??0)<r.minBufferToSwitchUp&&gu(E.quality,u.quality))return w[E.quality]="Buffer",!1;if(!!d&&Su(E.quality,d))return w[E.quality]="DroppedFramesLimit",!1;if(!!p&&Su(E.quality,p))return w[E.quality]="StallsLimit",!1;let C=R||(bu(a.max)||vu(E.quality,a.max))&&(bu(a.min)||Su(E.quality,a.min)),$=X(c)&&!c?vu(E.quality,r.backgroundVideoQualityLimit):!0;return!C||!$?(w[E.quality]="FitsQualityLimits",!1):!0})[0];V&&V.bitrate&&Dw.next(V.bitrate);let F=V??(0,Pt.default)(S,-1)??i[0];return F.quality!==l?.last?.quality&&f({message:`
10
10
  [VIDEO TRACKS ABR]
11
11
  [available video tracks]
12
- ${i.map(v=>`{ id: ${v.id}, quality: ${v.quality}, bitrate: ${v.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,ys.default)(r??{}).map(([v,T])=>`${v}: ${T}`).join(`
16
+ ${(0,Is.default)(r??{}).map(([E,k])=>`${E}: ${k}`).join(`
17
17
  `)}
18
18
 
19
19
  [limit params]
20
- containerSizeLimit: ${g?.width??0} x ${g?.width??0},
20
+ containerSizeLimit: ${b?.width??0} x ${b?.width??0},
21
21
  estimatedThroughput: ${t},
22
22
  stallsPredictedThroughput: ${h},
23
23
  reserve: ${s},
24
24
  playbackRate: ${o},
25
- playbackRateFactor: ${S},
25
+ playbackRateFactor: ${g},
26
26
  forwardBufferHealth: ${n},
27
- bitrateFactor: ${R},
27
+ bitrateFactor: ${v},
28
28
  minBufferToSwitchUp: ${r.minBufferToSwitchUp},
29
29
  droppedVideoMaxQualityLimit: ${d},
30
30
  stallsVideoMaxQualityLimit: ${p},
31
- limitsAreInvalid: ${y},
31
+ limitsAreInvalid: ${R},
32
32
  maxQualityLimit: ${a?.max},
33
33
  minQualityLimit: ${a?.min},
34
34
 
35
35
  [limited video tracks]
36
- ${(0,ys.default)(B).map(([v,T])=>`${v}: ${T}`).join(`
36
+ ${(0,Is.default)(w).map(([E,k])=>`${E}: ${k}`).join(`
37
37
  `)||"All tracks are available"}
38
38
 
39
- [best video track] ${_?.quality}
40
- [selected video track] ${U?.quality}
41
- `}),hb(r,f,U,l)},mb=(i,e,t,{estimatedThroughput:r,tuning:a,playbackRate:s,forwardBufferHealth:n,history:o,abrLogger:u,stallsPredictedThroughput:l})=>{cb(t,pb);let c=a.considerPlaybackRate&&X(s)?s:1,d=[...t].sort(gu(-1)),p=i.bitrate;Lw(p);let h=c*db(n??.5,a.bitrateAudioFactorAtEmptyBuffer,a.bitrateAudioFactorAtFullBuffer),f,b=Ts(i,e,t,a.minVideoAudioRatio),g=l||r;return X(g)&&isFinite(g)&&(f=d.find(S=>X(S.bitrate)&&X(b?.bitrate)?g-p>=S.bitrate*h&&S.bitrate>=b.bitrate:!1)),f||(f=b),f?.bitrate!==o?.last?.bitrate&&u({message:`
39
+ [best video track] ${V?.quality}
40
+ [selected video track] ${F?.quality}
41
+ `}),bb(r,f,F,l)},gb=(i,e,t,{estimatedThroughput:r,tuning:a,playbackRate:s,forwardBufferHealth:n,history:o,abrLogger:u,stallsPredictedThroughput:l})=>{hb(t,fb);let c=a.considerPlaybackRate&&X(s)?s:1,d=[...t].sort(yu(-1)),p=i.bitrate;Cw(p);let h=c*mb(n??.5,a.bitrateAudioFactorAtEmptyBuffer,a.bitrateAudioFactorAtFullBuffer),f,b=Es(i,e,t,a.minVideoAudioRatio),g=l||r;return X(g)&&isFinite(g)&&(f=d.find(S=>X(S.bitrate)&&X(b?.bitrate)?g-p>=S.bitrate*h&&S.bitrate>=b.bitrate:!1)),f||(f=b),f?.bitrate!==o?.last?.bitrate&&u({message:`
42
42
  [AUDIO TRACKS ABR]
43
43
  [available audio tracks]
44
44
  ${t.map(S=>`{ id: ${S.id}, bitrate: ${S.bitrate} }`).join(`
45
45
  `)}
46
46
 
47
47
  [tuning]
48
- ${(0,ys.default)(a??{}).map(([S,A])=>`${S}: ${A}`).join(`
48
+ ${(0,Is.default)(a??{}).map(([S,x])=>`${S}: ${x}`).join(`
49
49
  `)}
50
50
 
51
51
  [limit params]
@@ -59,14 +59,14 @@ var ry=Object.create;var Al=Object.defineProperty;var iy=Object.getOwnPropertyDe
59
59
  minBufferToSwitchUp: ${a.minBufferToSwitchUp},
60
60
 
61
61
  [selected audio track] ${f?.id}
62
- `}),f&&hb(a,u,f,o)};var Z=i=>new URL(i).hostname;import{assertNever as xb,assertNonNullable as Pb,combine as eR,debounce as tR,ErrorCategory as Ab,filter as kb,filterChanged as rR,isNonNullable as Iu,map as As,merge as wb,observableFrom as iR,once as aR,Subscription as sR,ValueSubject as Eu,videoQualityToHeight as nR,videoSizeToQuality as oR}from"@vkontakte/videoplayer-shared";var bb=C(Ke(),1),fb=i=>{if(i instanceof DOMException&&(0,bb.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"))},be=async(i,e)=>{let t=i.muted;try{await i.play()}catch(r){if(!fb(r))return!1;if(e&&e(),t)return console.warn(r),!1;i.muted=!0;try{await i.play()}catch(a){return fb(a)&&(i.muted=!1,console.warn(a)),!1}}return!0};import{isNonNullable as Es,isNullable as Bw,assertNonNullable as Ai}from"@vkontakte/videoplayer-shared";var Sb=C(vi(),1);import{isNonNullable as gb,assertNonNullable as Is,now as Dw}from"@vkontakte/videoplayer-shared";function ee(){return Dw()}function Su(i){return ee()-i}function vu(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 vb(i,e,t){let r=(...a)=>{t.apply(null,a),i.removeEventListener(e,r)};i.addEventListener(e,r)}function Vr(i,e,t,r){let a=window.XMLHttpRequest,s,n,o,u=!1,l=0,c,d,p=!1,h="arraybuffer",f=7e3,b=2e3,g=()=>{if(u)return;Is(c);let T=Su(c),q;if(T<b){q=b-T,setTimeout(g,q);return}b*=2,b>f&&(b=f),n&&n.abort(),n=new a,R()},S=T=>(s=T,v),A=T=>(d=T,v),E=()=>(h="json",v),k=()=>{if(!u){if(--l>=0){g(),r&&r();return}u=!0,d&&d(),t&&t()}},y=T=>(p=T,v),R=()=>{c=ee(),n=new a,n.open("get",i);let T=0,q,ye=0,Ve=()=>(Is(c),Math.max(c,Math.max(q||0,ye||0)));if(s&&n.addEventListener("progress",P=>{let M=ee();s.updateChunk&&P.loaded>T&&(s.updateChunk(Ve(),P.loaded-T),T=P.loaded,q=M)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>k())),n.addEventListener("load",()=>{if(u)return;Is(n);let P=n.status;if(P>=200&&P<300){if(n.response.byteLength&&s){let M=n.response.byteLength-T;M&&s.updateChunk&&s.updateChunk(Ve(),M)}n.responseType==="json"&&!(0,Sb.default)(n.response).length?k():(d&&d(),e(n.response))}else k()}),n.addEventListener("error",()=>{k()}),p){let P=()=>{Is(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(ye=ee(),n.removeEventListener("readystatechange",P))};n.addEventListener("readystatechange",P)}return n.responseType=h,n.send(),v},v={withBitrateReporting:S,withParallel:y,withJSONResponse:E,withRetryCount:T=>(l=T,v),withRetryInterval:(T,q)=>(gb(T)&&(b=T),gb(q)&&(f=q),v),withTimeout:T=>(o=T,v),withFinally:A,send:R,abort:()=>{n&&(n.abort(),n=void 0),u=!0,d&&d()}};return v}var xi=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 yb=C(vi(),1);var Pi=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=ee(),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=ee()-r,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(u,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},n=()=>{e._finallyCB&&e._finallyCB()},o=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=Vr(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=ee()}_getParallelRequestCount(){return Math.min(this.MAX_PARALLEL_REQUESTS,this.averageSegmentDuration<3e3?3:2)}_getPrefetchDelay(){return Math.max(100,Math.min(5e3,this.averageSegmentDuration/3))}_canSendPending(){let e=this._getParallelRequestCount(),t=ee();if(Object.keys(this.activeRequests).length>=e)return!1;let r=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),r>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),r),!1):!0}_sendPending(){for(;this._canSendPending();){let e=this.pendingQueue.pop();if(e){if(this.activeRequests[e]||this.completeRequests[e])continue;this.logger(`Submitting pending request url=${e}`),this._sendRequest({},e)}else return}}_removeFromActive(e){delete this.completeRequests[e],delete this.activeRequests[e]}abortAll(){(0,yb.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}};import{Subject as Ow}from"@vkontakte/videoplayer-shared";var xs=1e4,yu=3;var _w=6e4,Nw=10,Fw=1,qw=500,ki=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 Ow,this.chunkRateEstimator=new xi(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=vu(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=vu(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||Es(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=()=>{vb(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 Pi(yu,xs,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 k=s&&(!c||c===this.rep);return k||t("Not running!"),k},p=(k,y,R)=>{u&&u.abort(),u=Vr(this.urlResolver.resolve(k,!1),y,R,()=>this._retryCallback()).withTimeout(xs).withBitrateReporting(this.bitrateSwitcher).withRetryCount(yu).withFinally(()=>{u=null}).send()},h=(k,y,R)=>{Ai(this.filesFetcher),o?.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(k,!1),y,R,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},f=k=>{let y=r.playbackRate;r.playbackRate!==k&&(t(`Playback rate switch: ${y}=>${k}`),r.playbackRate=k)},b=k=>{this.lowLatency=k,t(`lowLatency changed to ${k}`),g()},g=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)f(1);else{let k=this._getBufferSizeSec();if(this.bufferStates.length<5){f(1);return}let R=ee()-1e4,B=0;for(let _=0;_<this.bufferStates.length;_++){let U=this.bufferStates[_];k=Math.min(k,U.buf),U.ts<R&&B++}this.bufferStates.splice(0,B),t(`update playback rate; minBuffer=${k} drop=${B} jitter=${this.sourceJitter}`);let F=k-Fw;this.sourceJitter>=0?F-=this.sourceJitter/2:this.sourceJitter-=1,F>3?f(1.15):F>1?f(1.1):F>.3?f(1.05):f(1)}},S=k=>{let y,R=()=>y&&y.start?y.start.length:0,B=P=>y.start[P]/1e3,F=P=>y.dur[P]/1e3,_=P=>y.fragIndex+P,U=(P,M)=>({chunkIdx:_(P),startTS:B(P),dur:F(P),discontinuity:M}),v=()=>{let P=0;if(y&&y.dur){let M=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,w=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,K=M;this.sourceJitter>1&&(K+=this.sourceJitter-1);let te=y.dur.length-1;for(;te>=0&&(K-=y.dur[te],!(K<=0));--te);P=Math.min(te,y.dur.length-1-w),P=Math.max(P,0)}return U(P,!0)},T=P=>{let M=R();if(!(M<=0)){if(Es(P)){for(let w=0;w<M;w++)if(B(w)>P)return U(w)}return v()}},q=P=>{let M=R(),w=P?P.chunkIdx+1:0,K=w-y.fragIndex;if(!(M<=0)){if(!P||K<0||K-M>Nw)return t(`Resync: offset=${K} bChunks=${M} chunk=`+JSON.stringify(P)),v();if(!(K>=M))return U(w-y.fragIndex,!1)}},ye=(P,M,w)=>{l&&l.abort(),l=Vr(this.urlResolver.resolve(P,!0,this.lowLatency),M,w,()=>this._retryCallback()).withTimeout(xs).withRetryCount(yu).withFinally(()=>{l=null}).withJSONResponse().send()};return{seek:(P,M)=>{ye(k,w=>{if(!d())return;y=w;let K=!!y.lowLatency;K!==this.lowLatency&&b(K);let te=0;for(let mt=0;mt<y.dur.length;++mt)te+=y.dur[mt];te>0&&(Ai(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(te/y.dur.length)),a({name:"index",zeroTime:y.zeroTime,shiftDuration:y.shiftDuration}),this.sourceJitter=y.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,y.jitter/1e3)):1,P(T(M))},()=>this._handleNetworkError())},nextChunk:q}},A=()=>{s=!1,o&&o.abort(),u&&u.abort(),l&&l.abort(),Ai(this.filesFetcher),this.filesFetcher.abortAll()};return c={start:k=>{let{videoElement:y,logger:R}=this.params,B=S(e.jidxUrl),F,_,U,v,T=0,q,ye,Ve,P=()=>{q&&(clearTimeout(q),q=void 0);let V=Math.max(qw,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),re=T+V,Y=ee(),ce=Math.min(1e4,re-Y);T=Y;let Te=()=>{l||d()&&B.seek(()=>{d()&&(T=ee(),M(),P())})};ce>0?q=window.setTimeout(()=>{this.paused?P():Te()},ce):Te()},M=()=>{let V;for(;V=B.nextChunk(v);)v=V,nr(V);let re=B.nextChunk(U);if(re){if(U&&re.discontinuity){R("Detected discontinuity; restarting playback"),this.paused?P():(A(),this._initPlayerWith(e));return}mt(re)}else P()},w=(V,re)=>{if(!d()||!this.sourceBuffer)return;let Y,ce,Te,tt=je=>{window.setTimeout(()=>{d()&&w(V,re)},je)};if(this.sourceBuffer.updating)R("Source buffer is updating; delaying appendBuffer"),tt(100);else{let je=ee(),rt=y.currentTime;!this.paused&&y.buffered.length>1&&ye===rt&&je-Ve>500&&(R("Stall suspected; trying to fix"),this._fixupStall()),ye!==rt&&(ye=rt,Ve=je);let Ge=this._getBufferSizeSec();if(Ge>30)R(`Buffered ${Ge} seconds; delaying appendBuffer`),tt(2e3);else try{this.sourceBuffer.appendBuffer(V),this.videoPlayStarted?(this.bufferStates.push({ts:je,buf:Ge}),g(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),re&&re()}catch(or){if(or.name==="QuotaExceededError")R("QuotaExceededError; delaying appendBuffer"),Te=this.sourceBuffer.buffered.length,Te!==0&&(Y=this.sourceBuffer.buffered.start(0),ce=rt,ce-Y>4&&this.sourceBuffer.remove(Y,ce-3)),tt(1e3);else throw or}}},K=()=>{_&&F&&(R([`Appending chunk, sz=${_.byteLength}:`,JSON.stringify(U)]),w(_,function(){_=null,M()}))},te=V=>e.fragUrlTemplate.replace("%%id%%",V.chunkIdx),mt=V=>{d()&&h(te(V),(re,Y)=>{if(d()){if(Y/=1e3,_=re,U=V,n=V.startTS,Y){let ce=Math.min(10,V.dur/Y);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*ce:ce}K()}},()=>this._handleNetworkError())},nr=V=>{d()&&(Ai(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(te(V),!1)))},Vt=V=>{d()&&(e.cachedHeader=V,w(V,()=>{F=!0,K()}))};s=!0,B.seek(V=>{if(d()){if(T=ee(),!V){P();return}v=V,!Bw(k)||V.startTS>k?mt(V):(U=V,M())}},k),e.cachedHeader?Vt(e.cachedHeader):p(e.headerUrl,Vt,()=>this._handleNetworkError())},stop:A,getTimestampSec:()=>n},c}_switchToQuality(e){let{logger:t,playerCallback:r}=this.params,a;e.bitrate!==this.bitrate&&(this.rep&&(a=this.rep.getTimestampSec(),Es(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,Ai(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(a),r({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return Es(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,r=d=>{if(!this.autoQuality)return;let p,h,f;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&d<this.bitrate&&(h=this._getBufferSizeSec(),f=d/this.bitrate,h>10&&f>.8||h>15&&f>.5||h>20&&f>.3)){e(`Not switching: buffer=${Math.floor(h)}; bitrate=${this.bitrate}; newRate=${Math.floor(d)}`);return}p=this._selectQuality(d),p?this._switchToQuality(p):e(`Could not find quality by bitrate ${d}`)},s={updateChunk:(p,h)=>{let f=ee();if(this.chunkRateEstimator.addInterval(p,f,h)){let g=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:h,duration:f-p,speed:g}),!0}},get:()=>{let p=this.chunkRateEstimator.getBitRate();return p?p*.85:0}},n=-1/0,o,u=!0,l=()=>{let d=s.get();if(d&&o&&this.autoQuality){if(u&&d>o&&Su(n)<3e4)return;r(d)}u=this.autoQuality};return{updateChunk:(d,p)=>{let h=s.updateChunk(d,p);return h&&l(),h},notifySwitch:d=>{let p=ee();d<o&&(n=p),o=d}}}_fetchManifest(e,t,r){this.manifestRequest=Vr(this.urlResolver.resolve(e,!0),t,r,()=>this._retryCallback()).withJSONResponse().withTimeout(xs).withRetryCount(this.params.config.manifestRetryMaxCount).withRetryInterval(this.params.config.manifestRetryInterval,this.params.config.manifestRetryMaxInterval).send().withFinally(()=>{this.manifestRequest=void 0})}_playVideoElement(){let{videoElement:e}=this.params;be(e,()=>{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))},_w))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};var Eb=C(Ir(),1);import{debounce as Uw,filter as Tb,fromEvent as Hw,interval as jw,isHigher as Gw,isInvariantQuality as Qw,isLower as Ww,merge as Yw,Subject as Ib,Subscription as zw}from"@vkontakte/videoplayer-shared";var Tu=class{constructor(){this.onDroopedVideoFramesLimit$=new Ib;this.subscription=new zw;this.playing=!1;this.tracks=[];this.forceChecker$=new Ib;this.isForceCheckCounter=0;this.prevTotalVideoFrames=0;this.prevDroppedVideoFrames=0;this.limitCounts={};this.handleChangeVideoQuality=()=>{let e=this.tracks.find(({size:t})=>t?.height===this.video.videoHeight&&t?.width===this.video.videoWidth);e&&!Qw(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&&Gw(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(Hw(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=jw(this.droppedFramesChecker.checkTime).pipe(Tb(()=>this.playing),Tb(()=>{let a=!!this.isForceCheckCounter;return a&&(this.isForceCheckCounter-=1),!a})),t=this.forceChecker$.pipe(Uw(this.droppedFramesChecker.checkTime)),r=Yw(e,t);this.subscription.add(r.subscribe(this.checkDroppedFrames))}onChangeQuality(e){this.currentQuality=e;let{totalVideoFrames:t,droppedVideoFrames:r}=this.video.getVideoPlaybackQuality();this.savePrevFrameCounts(t,r),this.isForceCheckCounter=this.droppedFramesChecker.tickCountAfterQualityChange,this.forceChecker$.next()}onDroopedVideoFramesLimitTrigger(){this.isAuto.getState()&&(this.log({message:`[onDroopedVideoFramesLimit]. maxQualityLimit: ${this.maxQualityLimit}`}),this.onDroopedVideoFramesLimit$.next())}getMaxQualityLimit(e){let t=(0,Eb.default)(this.limitCounts).filter(([,r])=>r>=this.droppedFramesChecker.countLimit).sort(([r],[a])=>Ww(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}},Ps=Tu;import{map as Kw,Observable as Jw}from"@vkontakte/videoplayer-shared";import{fromEvent as Xw}from"@vkontakte/videoplayer-shared";var wi=()=>!!window.documentPictureInPicture?.window||!!document.pictureInPictureElement;var Zw=(i,e)=>new Jw(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=Xw(document,"visibilitychange").pipe(Kw(n=>!document.hidden||wi())).subscribe(n=>t.next(n));return()=>{a.unobserve(i),s.unsubscribe}}),Ce=Zw;var uR=["paused","playing","ready"],lR=["paused","playing","ready"],Ri=class{constructor(e){this.subscription=new sR;this.videoState=new $("stopped");this.representations$=new Eu([]);this.textTracksManager=new Le;this.droppedFramesManager=new Ps;this.maxSeekBackTime$=new Eu(1/0);this.zeroTime$=new Eu(void 0);this.liveOffset=new ot;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:Ab.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=xt(a.name)??oR(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),Iu(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,xu.default)(lR,e)&&(n||o)){this.prepare();return}if(a?.to!=="paused"&&s.state==="requested"&&(0,xu.default)(uR,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 xb(e)}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=a=>{e.output.error$.next({id:"DashLiveProvider",category:Ab.WTF,message:"DashLiveProvider internal logic error",thrown:a})};wb(this.videoState.stateChangeStarted$.pipe(As(a=>({transition:a,type:"start"}))),this.videoState.stateChangeEnded$.pipe(As(a=>({transition:a,type:"end"})))).subscribe(({transition:a,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(a)}`})}),this.video=pe(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(Z(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);let r=fe(this.video);this.subscription.add(this.representations$.pipe(As(a=>a.map(({track:s})=>s)),kb(a=>!!a.length),aR()).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(rR(),As(a=>-a/1e3)).subscribe(this.params.output.duration$)).add(eR({zeroTime:this.zeroTime$.pipe(kb(Iu)),position:r.timeUpdate$}).subscribe(({zeroTime:a,position:s})=>this.params.output.liveTime$.next(a+s*1e3),t)).add(Je(this.video,this.params.desiredState.isLooped,t)).add(me(this.video,this.params.desiredState.volume,r.volumeState$,t)).add(r.volumeState$.subscribe(this.params.output.volume$,t)).add($e(this.video,this.params.desiredState.playbackRate,r.playbackRateState$,t)).add(r.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(r.loadedMetadata$.subscribe(this.params.output.loadedMetadataEvent$)).add(r.playing$.subscribe(this.params.output.firstFrameEvent$)).add(r.canplay$.subscribe(this.params.output.canplay$)).add(r.inPiP$.subscribe(this.params.output.inPiP$)).add(r.inFullscreen$.subscribe(this.params.output.inFullscreen$)).add(Ce(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:a}})=>{let s=a&&nR(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 xb(a.to)}},t)).add(wb(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,iR(["init"])).pipe(tR(0)).subscribe(this.syncPlayback,t))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.droppedFramesManager.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),he(this.video)}createLiveDashPlayer(){let e=new ki({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&&Iu(t)?t:At(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;Pb(l,"Representations missing"),this.dash.startPlay(l,r)}}setVideoTrack(e){let t=this.representations$.getValue().find(({track:r})=>r.id===e.id)?.representation;Pb(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 Rb=Ri;var rv=C(Ke(),1);var Ze=(i,e)=>{let t=0;for(let r=0;r<i.length;r++){let a=i.start(r)*1e3,s=i.end(r)*1e3;a<=e&&e<=s&&(t=s)}return Math.max(t-e,0)};import{assertNever as jL,assertNonNullable as GL,debounce as QL,ErrorCategory as ul,filter as ZS,filterChanged as ba,fromEvent as WL,isNonNullable as ev,map as ll,merge as Ys,observableFrom as YL,observeElementSize as zL,once as tv,Subscription as KL,ValueSubject as JL}from"@vkontakte/videoplayer-shared";var ks=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}},Br=class extends ks{constructor(){super(),this.listeners||ks.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 Br,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",Br.prototype[Symbol.toStringTag]="AbortSignal");function ws(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 Pu(i){typeof i=="function"&&(i={fetch:i});let{fetch:e,Request:t=e.Request,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:a=!1}=i;if(!ws({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 p=new t(l,c);return d&&Object.defineProperty(p,"signal",{writable:!1,enumerable:!1,configurable:!0,value:d}),p},s.prototype=t.prototype);let n=e;return{fetch:(u,l)=>{let c=s&&s.prototype.isPrototypeOf(u)?u.signal:l?l.signal:void 0;if(c){let d;try{d=new DOMException("Aborted","AbortError")}catch{d=new Error("Aborted"),d.name="AbortError"}if(c.aborted)return Promise.reject(d);let p=new Promise((h,f)=>{c.addEventListener("abort",()=>f(d),{once:!0})});return l&&l.signal&&delete l.signal,Promise.race([p,n(u,l)])}return n(u,l)},Request:s}}var Li=ws({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),$b=Li?Pu({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,lt=Li?$b.fetch:window.fetch,b_=Li?$b.Request:window.Request,Ae=Li?$i:window.AbortController,g_=Li?Br:window.AbortSignal;var nl=C(ku(),1);var Ls=C(Dr(),1);var ct=()=>window.ManagedMediaSource||window.MediaSource,Rs=()=>!!(window.ManagedMediaSource&&window.ManagedSourceBuffer?.prototype?.appendBuffer),Kb=()=>!!(window.MediaSource&&window.SourceBuffer?.prototype?.appendBuffer),Jb=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;import{assertNever as Ds,clientChecker as Ms}from"@vkontakte/videoplayer-shared";var Cs=document.createElement("video"),DR='video/mp4; codecs="avc1.42000a,mp4a.40.2"',VR='video/mp4; codecs="hev1.1.6.L93.B0"',Xb='video/webm; codecs="vp09.00.10.08"',Zb='video/webm; codecs="av01.0.00M.08"',BR='audio/mp4; codecs="mp4a.40.2"',OR='audio/webm; codecs="opus"',Mi={mms:Rs(),mse:Kb(),hls:!!(Cs.canPlayType?.("application/x-mpegurl")||Cs.canPlayType?.("vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},ge={mp4:!!Cs.canPlayType?.("video/mp4"),webm:!!Cs.canPlayType?.("video/webm"),cmaf:!0},Se={h264:!!ct()?.isTypeSupported?.(DR),h265:!!ct()?.isTypeSupported?.(VR),vp9:!!ct()?.isTypeSupported?.(Xb),av1:!!ct()?.isTypeSupported?.(Zb),aac:!!ct()?.isTypeSupported?.(BR),opus:!!ct()?.isTypeSupported?.(OR)},Or=(Se.h264||Se.h265)&&Se.aac,Kt,_R=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:Zb}}),window.navigator.mediaCapabilities.decodingInfo({...i,video:{...i.video,contentType:Xb}})]);Kt={DASH_WEBM_AV1:e,DASH_WEBM:t}};try{_R()}catch(i){console.error(i)}var _r=Mi.hls&&ge.mp4,eg=()=>Object.keys(Se).filter(i=>Se[i]),tg=(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&&ge.mp4&&Or;case"DASH_WEBM":return a&&ge.webm&&Se.vp9&&Se.opus;case"DASH_WEBM_AV1":return a&&ge.webm&&Se.av1&&Se.opus;case"DASH_STREAMS":return a&&(ge.mp4&&Or||ge.webm&&(Se.vp9||Se.av1)&&(Se.opus||Se.aac));case"DASH_LIVE":return a&&ge.mp4&&Or;case"DASH_LIVE_CMAF":return a&&ge.mp4&&Or&&ge.cmaf;case"DASH_ONDEMAND":return a&&ge.mp4&&Or;case"HLS":case"HLS_ONDEMAND":return _r||e&&a&&ge.mp4&&Or;case"HLS_LIVE":case"HLS_LIVE_CMAF":return _r;case"MPEG":return ge.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return Mi.webrtc&&Mi.ws&&Se.h264&&(ge.mp4||ge.webm);default:return Ds(s)}})},$s=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 Kt?Kt[t].smooth?[t,e]:Kt[e].smooth?[e,t]:[t,e]:[e,t];case"power_efficient":return Kt?Kt[t].powerEfficient?[t,e]:Kt[e].powerEfficient?[e,t]:[t,e]:[e,t];default:Ds(i)}return[e,t]},rg=({webmCodec:i,androidPreferredFormat:e,preferMultiStream:t})=>{let r=[...t?["DASH_STREAMS"]:[],...$s(i),"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]],a=[...t?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]];if(Ms.isAndroid)switch(e){case"mpeg":return["MPEG",...r,"HLS","HLS_ONDEMAND"];case"hls":return["HLS","HLS_ONDEMAND",...r,"MPEG"];case"dash":return[...r,"HLS","HLS_ONDEMAND","MPEG"];case"dash_any_mpeg":return[...a,"MPEG",...$s(i),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...$s(i),"MPEG",...a,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...$s(i),...a,"HLS","HLS_ONDEMAND"];default:Ds(e)}return _r?[...r,"HLS","HLS_ONDEMAND","MPEG"]:[...r,"HLS","HLS_ONDEMAND","MPEG"]},ig=({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=Ms.isMac&&Ms.isSafari;if(Ms.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:Ds(i)}else _r&&!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"]},wu=i=>i?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],ag=i=>{if(i.size===0)return;if(i.size===1){let t=i.values().next();return(0,Ls.default)(t.value.split("."),0)}for(let t of i){let r=(0,Ls.default)(t.split("."),0);if(r==="opus"||r==="vp09"||r==="av01")return r}let e=i.values().next();return(0,Ls.default)(e.value.split("."),0)};var Pg=C(xg(),1);import{ErrorCategory as Di}from"@vkontakte/videoplayer-shared";var Ag=i=>{if(!i)return{id:"EmptyResponse",category:Di.PARSER,message:"Empty response"};if(i.length<=2&&i.match(/^\d+$/))return{id:`UVError#${i}`,category:Di.NETWORK,message:`UV Error ${i}`};let e=(0,Pg.default)(i).substring(0,100).toLowerCase();if(e.startsWith("<!doctype")||e.startsWith("<html>")||e.startsWith("<body>")||e.startsWith("<head>"))return{id:"UnexpectedHTML",category:Di.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:Di.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:Di.PARSER,message:"Response is valid XML, but parser failed"}};var kt=(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};import{abortable as il,assertNonNullable as rr,clientChecker as RL,combine as pa,ErrorCategory as Lt,filter as Hs,filterChanged as al,flattenObject as ha,fromEvent as ir,getTraceSubscriptionMethod as $L,interval as sl,isNonNullable as jS,map as ma,merge as ar,now as LL,Subject as GS,Subscription as QS,tap as ML,throttle as CL,ValueSubject as W}from"@vkontakte/videoplayer-shared";var Os=C(Ke(),1),Ur=C(Dr(),1),_s=C(ku(),1);var t$=(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)},r$=i=>window.clearTimeout(i),kg=i=>typeof i=="function"&&i?.toString().endsWith("{ [native code] }"),wg=!kg(window.requestIdleCallback)||!kg(window.cancelIdleCallback),Cu=wg?t$:window.requestIdleCallback,Vi=wg?r$:window.cancelIdleCallback;var BS=C(bs(),1);import{assertNever as i$,ErrorCategory as Rg,clientChecker as Du,Subject as $g}from"@vkontakte/videoplayer-shared";var a$=18,Lg=!1;try{Lg=Du.isSafari&&!!Du.macVersion&&Du.macVersion<=a$}catch(i){console.error(i)}var Vu=class{constructor(e){this.bufferFull$=new $g;this.error$=new $g;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:Rg.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;Lg&&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:Rg.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:i$(t)}}},Mg=Vu;var Bu=i=>{let e=0;for(let t=0;t<i.length;t++)e+=i.end(t)-i.start(t);return e*1e3};import{abortable as Zt,assertNonNullable as ue,ErrorCategory as Rt,fromEvent as Xu,getExponentialDelay as Zu,isNonNullable as Vs,isNullable as De,now as Bs,once as vL,Subject as yL,Subscription as TL,ValueSubject as qr}from"@vkontakte/videoplayer-shared";var N=class{constructor(e,t){this.cursor=0;this.source=e,this.boxParser=t,this.children=[];let r=this.readUint32();this.type=this.readString(4),this.size32=r<=e.buffer.byteLength-e.byteOffset?r:NaN;let 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 Nr=class extends N{};var Bi=class extends N{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 Oi=class extends N{constructor(e,t){super(e,t),this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let r=this.size-this.cursor;for(;r;){let a=this.readString(4);this.compatibleBrands.push(a),r-=4}}};var _i=class extends N{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var j=class extends N{constructor(e,t){super(e,t);let r=this.readUint32();this.version=r>>>24,this.flags=r&16777215}};var Ni=class extends j{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 Fi=class extends N{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var qi=class extends N{constructor(e,t){super(e,t),this.data=this.content}};var Jt=class extends j{get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e,t){super(e,t),this.segments=[],this.referenceId=this.readUint32(),this.timescale=this.readUint32(),this.earliestPresentationTime32=this.readUint32(),this.firstOffset32=this.readUint32(),this.earliestPresentationTime64=0,this.firstOffset64=0,this.referenceCount=this.readUint32()&65535;for(let r=0;r<this.referenceCount;r++){let a=this.readUint32(),s=a>>>31,n=a<<1>>>1,o=this.readUint32();a=this.readUint32();let u=a>>>28,l=a<<3>>>3;this.segments.push({referenceType:s,referencedSize:n,subsegmentDuration:o,SAPType:u,SAPDeltaTime:l})}}};var Ui=class extends N{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Hi=class extends N{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ji=class extends j{constructor(e,t){switch(super(e,t),this.readUint8()){case 0:this.stereoMode=0;break;case 1:this.stereoMode=1;break;case 2:this.stereoMode=2;break;case 3:this.stereoMode=3;break;case 4:this.stereoMode=4;break}this.cursor+=1}};var Gi=class extends j{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var Qi=class extends j{constructor(e,t){super(e,t),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}};var Wi=class extends N{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Yi=class extends j{constructor(e,t){super(e,t),this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.trackId=this.readUint32(),this.cursor+=4,this.duration=this.readUint32(),this.cursor+=8,this.layer=this.readUint16(),this.alternateGroup=this.readUint16(),this.cursor+=2,this.cursor+=2,this.matrix=[[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()]],this.width=this.readUint32(),this.height=this.readUint32()}};var zi=class extends N{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Ki=class extends N{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Ji=class extends j{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var Xi=class extends N{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Zi=class extends j{constructor(e,t){super(e,t),this.trackId=this.readUint32(),this.flags&1&&(this.baseDataOffset=this.readUint64()),this.flags&2&&(this.sampleDescriptionIndex=this.readUint32()),this.flags&8&&(this.defaultSampleDuration=this.readUint32()),this.flags&16&&(this.defaultSampleSize=this.readUint32()),this.flags&32&&(this.defaultSampleFlags=this.readUint32())}};var ea=class extends j{constructor(t,r){super(t,r);this.baseMediaDecodeTime32=0;this.baseMediaDecodeTime64=BigInt(0);this.version===1?this.baseMediaDecodeTime64=this.readUint64():this.baseMediaDecodeTime32=this.readUint32()}get baseMediaDecodeTime(){return this.version===1?this.baseMediaDecodeTime64:this.baseMediaDecodeTime32}};var ta=class extends j{constructor(t,r){super(t,r);this.sampleDuration=[];this.sampleSize=[];this.sampleFlags=[];this.sampleCompositionTimeOffset=[];this.optionalFields=0;this.sampleCount=this.readUint32(),this.flags&1&&(this.dataOffset=this.readUint32()),this.flags&4&&(this.firstSampleFlags=this.readUint32());for(let a=0;a<this.sampleCount;a++)this.flags&256&&this.sampleDuration.push(this.readUint32()),this.flags&512&&this.sampleSize.push(this.readUint32()),this.flags&1024&&this.sampleFlags.push(this.readUint32()),this.flags&2048&&this.sampleCompositionTimeOffset.push(this.readUint32())}};var n$={ftyp:Oi,moov:_i,mvhd:Ni,moof:Fi,mdat:qi,sidx:Jt,trak:Ui,mdia:Wi,mfhd:Ji,tkhd:Yi,traf:Xi,tfhd:Zi,tfdt:ea,trun:ta,minf:zi,sv3d:Hi,st3d:ji,prhd:Gi,proj:Ki,equi:Qi,uuid:Bi,unknown:Nr},dt=class i{constructor(e={}){this.options={offset:0,...e}}parse(e){let t=[],r=this.options.offset;for(;r<e.byteLength;)try{let s=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+r+4,4)),n=this.createBox(s,new DataView(e.buffer,e.byteOffset+r));if(!n.size)break;t.push(n),r+=n.size}catch{break}return t}createBox(e,t){let r=n$[e];return r?new r(t,new i):new Nr(t,new i)}};var wt=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 u$=new TextDecoder("ascii"),l$=i=>u$.decode(new DataView(i.buffer,i.byteOffset+4,4))==="ftyp",c$=i=>{let e=new Jt(i,new dt),t=e.earliestPresentationTime/e.timescale*1e3,r=i.byteOffset+i.byteLength+e.firstOffset;return e.segments.map(s=>{if(s.referenceType!==0)throw new Error("Unsupported multilevel sidx");let n=s.subsegmentDuration/e.timescale*1e3,o={status:"none",time:{from:t,to:t+n},byte:{from:r,to:r+s.referencedSize-1}};return t+=n,r+=s.referencedSize,o})},d$=(i,e)=>{let r=new dt().parse(i),a=new wt(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)},p$=i=>{let t=new dt().parse(i),r=new wt(t),a={},s=r.findAll("uuid");return s.length?s[s.length-1]:a},h$=i=>{let t=new dt().parse(i);return new wt(t).find("sidx")?.timescale},m$=(i,e)=>{let r=new dt().parse(i),s=new wt(r).findAll("traf"),n=s[s.length-1].children.find(d=>d.type==="tfhd"),o=s[s.length-1].children.find(d=>d.type==="tfdt"),u=s[s.length-1].children.find(d=>d.type==="trun"),l=0;return u.sampleDuration.length?l=u.sampleDuration.reduce((d,p)=>d+p,0):l=n.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+l)/e*1e3},f$=i=>{let e={is3dVideo:!1,stereoMode:0,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}},r=new dt().parse(i),a=new wt(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},Cg={validateData:l$,parseInit:f$,getIndexRange:()=>{},parseSegments:c$,parseFeedableSegmentChunk:d$,getChunkEndTime:m$,getServerLatencyTimestamps:p$,getTimescaleFromIndex:h$};var ia=C(Ke(),1);import{assertNonNullable as _u,isNonNullable as Og,isNullable as g$}from"@vkontakte/videoplayer-shared";import{assertNever as b$}from"@vkontakte/videoplayer-shared";var Dg={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"}},Vg=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=ra(i,t),a=r in Dg,s=a?Dg[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=ra(u),d=l*2**((o-1)*8)+c,p=t+o,h;return p+d>i.byteLength?h=new DataView(i.buffer,i.byteOffset+p):h=new DataView(i.buffer,i.byteOffset+p,d),{tag:a?r:"0x"+r.toString(16).toUpperCase(),type:s,tagHeaderSize:p,tagSize:p+d,value:h,valueSize:d}},ra=(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},Ue=(i,e)=>{switch(e){case"int":return i.getInt8(0);case"uint":return ra(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:b$(e)}},Xt=(i,e)=>{let t=0;for(;t<i.byteLength;){let r=new DataView(i.buffer,i.byteOffset+t),a=Vg(r);if(!e(a))return;a.type==="master"&&Xt(a.value,e),t=a.value.byteOffset-i.byteOffset+a.valueSize}},Bg=i=>{if(i.getUint32(0)!==440786851)return!1;let e,t,r,a=Vg(i);return Xt(a.value,({tag:s,type:n,value:o})=>(s===17143?e=Ue(o,n):s===17026?t=Ue(o,n):s===17029&&(r=Ue(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(r===void 0||r<=2)};var _g=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],S$=[231,22612,22743,167,171,163,160,175],v$=i=>{let e,t,r,a,s=!1,n=!1,o=!1,u,l,c=!1,d=0;return Xt(i,({tag:p,type:h,value:f,valueSize:b})=>{if(p===21419){let g=Ue(f,h);l=ra(g)}else p!==21420&&(l=void 0);return p===408125543?(e=f.byteOffset,t=f.byteOffset+b):p===357149030?s=!0:p===290298740?n=!0:p===2807729?r=Ue(f,h):p===17545?a=Ue(f,h):p===21420&&l===475249515?u=Ue(f,h):p===374648427?Xt(f,({tag:g,type:S,value:A})=>g===30321?(c=Ue(A,S)===1,!1):!0):s&&n&&(0,ia.default)(_g,p)&&(o=!0),!o}),_u(e,"Failed to parse webm Segment start"),_u(t,"Failed to parse webm Segment end"),_u(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}}}},y$=i=>{if(g$(i.cuesSeekPosition))return;let e=i.segmentStart+i.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},T$=(i,e)=>{let t=!1,r=!1,a=o=>Og(o.time)&&Og(o.position),s=[],n;return Xt(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=Ue(l,u));break;case 183:break;case 241:n&&(n.position=Ue(l,u));break;default:t&&(0,ia.default)(_g,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}}})},I$=i=>{let e=0,t=!1;try{Xt(i,r=>r.tag===524531317?r.tagSize<=i.byteLength?(e=r.tagSize,!1):(e+=r.tagHeaderSize,!0):(0,ia.default)(S$,r.tag)?(e+r.tagSize<=i.byteLength&&(e+=r.tagSize,t||=(0,ia.default)([163,160,175],r.tag)),!0):!1)}catch{}return e>0&&e<=i.byteLength&&t?new DataView(i.buffer,i.byteOffset,e):null},Ng={validateData:Bg,parseInit:v$,getIndexRange:y$,parseSegments:T$,parseFeedableSegmentChunk:I$};var aa=i=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(i);if(e){let[,t,r]=e;if(t==="audio"||t==="video")switch(r){case"webm":return Ng;case"mp4":return Cg}}throw new ReferenceError(`Unsupported mime type ${i}`)};var Gu=C(sS(),1),wS=C(Ir(),1),RS=C(TS(),1),$S=C(Dr(),1);var IS=C(Ke(),1),ju=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,IS.default)(["6E","7A","F4"],o)}}return!1};import{isNonNullable as PS,isNullable as AS}from"@vkontakte/videoplayer-shared";var ES=i=>{if(i.includes("/")){let e=i.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(i)};var xS=i=>{try{let e=gL(),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 gL(){let i="(?<extlang>(?:[a-z]{3}(?:-[a-z]{3}){0,2}))",e="x(?:-[a-z0-9]{1,8})+",c=`^(?:(?<langtag>${`
62
+ `}),f&&bb(a,u,f,o)};var Z=i=>new URL(i).hostname;import{assertNever as kb,assertNonNullable as wb,combine as iR,debounce as aR,ErrorCategory as Rb,filter as $b,filterChanged as sR,isNonNullable as Pu,map as ws,merge as Lb,observableFrom as nR,once as oR,Subscription as uR,ValueSubject as Au,videoQualityToHeight as lR,videoSizeToQuality as cR}from"@vkontakte/videoplayer-shared";var vb=D(ze(),1),Sb=i=>{if(i instanceof DOMException&&(0,vb.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"))},fe=async(i,e)=>{let t=i.muted;try{await i.play()}catch(r){if(!Sb(r))return!1;if(e&&e(),t)return console.warn(r),!1;i.muted=!0;try{await i.play()}catch(a){return Sb(a)&&(i.muted=!1,console.warn(a)),!1}}return!0};import{isNonNullable as Ps,isNullable as Nw,assertNonNullable as ki}from"@vkontakte/videoplayer-shared";var Tb=D(yi(),1);import{isNonNullable as yb,assertNonNullable as xs,now as Bw}from"@vkontakte/videoplayer-shared";function ee(){return Bw()}function Tu(i){return ee()-i}function Iu(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 Ib(i,e,t){let r=(...a)=>{t.apply(null,a),i.removeEventListener(e,r)};i.addEventListener(e,r)}function Vr(i,e,t,r){let a=window.XMLHttpRequest,s,n,o,u=!1,l=0,c,d,p=!1,h="arraybuffer",f=7e3,b=2e3,g=()=>{if(u)return;xs(c);let P=Tu(c),H;if(P<b){H=b-P,setTimeout(g,H);return}b*=2,b>f&&(b=f),n&&n.abort(),n=new a,w()},S=P=>(s=P,k),x=P=>(d=P,k),T=()=>(h="json",k),R=()=>{if(!u){if(--l>=0){g(),r&&r();return}u=!0,d&&d(),t&&t()}},v=P=>(p=P,k),w=()=>{c=ee(),n=new a,n.open("get",i);let P=0,H,De=0,et=()=>(xs(c),Math.max(c,Math.max(H||0,De||0)));if(s&&n.addEventListener("progress",A=>{let C=ee();s.updateChunk&&A.loaded>P&&(s.updateChunk(et(),A.loaded-P),P=A.loaded,H=C)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>R())),n.addEventListener("load",()=>{if(u)return;xs(n);let A=n.status;if(A>=200&&A<300){if(n.response.byteLength&&s){let C=n.response.byteLength-P;C&&s.updateChunk&&s.updateChunk(et(),C)}n.responseType==="json"&&!(0,Tb.default)(n.response).length?R():(d&&d(),e(n.response))}else R()}),n.addEventListener("error",()=>{R()}),p){let A=()=>{xs(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(De=ee(),n.removeEventListener("readystatechange",A))};n.addEventListener("readystatechange",A)}return n.responseType=h,n.send(),k},k={withBitrateReporting:S,withParallel:v,withJSONResponse:T,withRetryCount:P=>(l=P,k),withRetryInterval:(P,H)=>(yb(P)&&(b=P),yb(H)&&(f=H),k),withTimeout:P=>(o=P,k),withFinally:x,send:w,abort:()=>{n&&(n.abort(),n=void 0),u=!0,d&&d()}};return k}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 Eb=D(yi(),1);var Ai=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=ee(),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=ee()-r,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(u,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},n=()=>{e._finallyCB&&e._finallyCB()},o=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=Vr(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=ee()}_getParallelRequestCount(){return Math.min(this.MAX_PARALLEL_REQUESTS,this.averageSegmentDuration<3e3?3:2)}_getPrefetchDelay(){return Math.max(100,Math.min(5e3,this.averageSegmentDuration/3))}_canSendPending(){let e=this._getParallelRequestCount(),t=ee();if(Object.keys(this.activeRequests).length>=e)return!1;let r=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),r>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),r),!1):!0}_sendPending(){for(;this._canSendPending();){let e=this.pendingQueue.pop();if(e){if(this.activeRequests[e]||this.completeRequests[e])continue;this.logger(`Submitting pending request url=${e}`),this._sendRequest({},e)}else return}}_removeFromActive(e){delete this.completeRequests[e],delete this.activeRequests[e]}abortAll(){(0,Eb.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}};import{Subject as Fw}from"@vkontakte/videoplayer-shared";var As=1e4,Eu=3;var qw=6e4,Uw=10,Hw=1,jw=500,wi=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 Fw,this.chunkRateEstimator=new Pi(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=Iu(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=Iu(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||Ps(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=()=>{Ib(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 Ai(Eu,As,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 R=s&&(!c||c===this.rep);return R||t("Not running!"),R},p=(R,v,w)=>{u&&u.abort(),u=Vr(this.urlResolver.resolve(R,!1),v,w,()=>this._retryCallback()).withTimeout(As).withBitrateReporting(this.bitrateSwitcher).withRetryCount(Eu).withFinally(()=>{u=null}).send()},h=(R,v,w)=>{ki(this.filesFetcher),o?.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(R,!1),v,w,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},f=R=>{let v=r.playbackRate;r.playbackRate!==R&&(t(`Playback rate switch: ${v}=>${R}`),r.playbackRate=R)},b=R=>{this.lowLatency=R,t(`lowLatency changed to ${R}`),g()},g=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)f(1);else{let R=this._getBufferSizeSec();if(this.bufferStates.length<5){f(1);return}let w=ee()-1e4,U=0;for(let F=0;F<this.bufferStates.length;F++){let E=this.bufferStates[F];R=Math.min(R,E.buf),E.ts<w&&U++}this.bufferStates.splice(0,U),t(`update playback rate; minBuffer=${R} drop=${U} jitter=${this.sourceJitter}`);let V=R-Hw;this.sourceJitter>=0?V-=this.sourceJitter/2:this.sourceJitter-=1,V>3?f(1.15):V>1?f(1.1):V>.3?f(1.05):f(1)}},S=R=>{let v,w=()=>v&&v.start?v.start.length:0,U=A=>v.start[A]/1e3,V=A=>v.dur[A]/1e3,F=A=>v.fragIndex+A,E=(A,C)=>({chunkIdx:F(A),startTS:U(A),dur:V(A),discontinuity:C}),k=()=>{let A=0;if(v&&v.dur){let C=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,$=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,Y=C;this.sourceJitter>1&&(Y+=this.sourceJitter-1);let ve=v.dur.length-1;for(;ve>=0&&(Y-=v.dur[ve],!(Y<=0));--ve);A=Math.min(ve,v.dur.length-1-$),A=Math.max(A,0)}return E(A,!0)},P=A=>{let C=w();if(!(C<=0)){if(Ps(A)){for(let $=0;$<C;$++)if(U($)>A)return E($)}return k()}},H=A=>{let C=w(),$=A?A.chunkIdx+1:0,Y=$-v.fragIndex;if(!(C<=0)){if(!A||Y<0||Y-C>Uw)return t(`Resync: offset=${Y} bChunks=${C} chunk=`+JSON.stringify(A)),k();if(!(Y>=C))return E($-v.fragIndex,!1)}},De=(A,C,$)=>{l&&l.abort(),l=Vr(this.urlResolver.resolve(A,!0,this.lowLatency),C,$,()=>this._retryCallback()).withTimeout(As).withRetryCount(Eu).withFinally(()=>{l=null}).withJSONResponse().send()};return{seek:(A,C)=>{De(R,$=>{if(!d())return;v=$;let Y=!!v.lowLatency;Y!==this.lowLatency&&b(Y);let ve=0;for(let mt=0;mt<v.dur.length;++mt)ve+=v.dur[mt];ve>0&&(ki(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(ve/v.dur.length)),a({name:"index",zeroTime:v.zeroTime,shiftDuration:v.shiftDuration}),this.sourceJitter=v.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,v.jitter/1e3)):1,A(P(C))},()=>this._handleNetworkError())},nextChunk:H}},x=()=>{s=!1,o&&o.abort(),u&&u.abort(),l&&l.abort(),ki(this.filesFetcher),this.filesFetcher.abortAll()};return c={start:R=>{let{videoElement:v,logger:w}=this.params,U=S(e.jidxUrl),V,F,E,k,P=0,H,De,et,A=()=>{H&&(clearTimeout(H),H=void 0);let B=Math.max(jw,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),te=P+B,z=ee(),le=Math.min(1e4,te-z);P=z;let ye=()=>{l||d()&&U.seek(()=>{d()&&(P=ee(),C(),A())})};le>0?H=window.setTimeout(()=>{this.paused?A():ye()},le):ye()},C=()=>{let B;for(;B=U.nextChunk(k);)k=B,nr(B);let te=U.nextChunk(E);if(te){if(E&&te.discontinuity){w("Detected discontinuity; restarting playback"),this.paused?A():(x(),this._initPlayerWith(e));return}mt(te)}else A()},$=(B,te)=>{if(!d()||!this.sourceBuffer)return;let z,le,ye,tt=He=>{window.setTimeout(()=>{d()&&$(B,te)},He)};if(this.sourceBuffer.updating)w("Source buffer is updating; delaying appendBuffer"),tt(100);else{let He=ee(),rt=v.currentTime;!this.paused&&v.buffered.length>1&&De===rt&&He-et>500&&(w("Stall suspected; trying to fix"),this._fixupStall()),De!==rt&&(De=rt,et=He);let je=this._getBufferSizeSec();if(je>30)w(`Buffered ${je} seconds; delaying appendBuffer`),tt(2e3);else try{this.sourceBuffer.appendBuffer(B),this.videoPlayStarted?(this.bufferStates.push({ts:He,buf:je}),g(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),te&&te()}catch(or){if(or.name==="QuotaExceededError")w("QuotaExceededError; delaying appendBuffer"),ye=this.sourceBuffer.buffered.length,ye!==0&&(z=this.sourceBuffer.buffered.start(0),le=rt,le-z>4&&this.sourceBuffer.remove(z,le-3)),tt(1e3);else throw or}}},Y=()=>{F&&V&&(w([`Appending chunk, sz=${F.byteLength}:`,JSON.stringify(E)]),$(F,function(){F=null,C()}))},ve=B=>e.fragUrlTemplate.replace("%%id%%",B.chunkIdx),mt=B=>{d()&&h(ve(B),(te,z)=>{if(d()){if(z/=1e3,F=te,E=B,n=B.startTS,z){let le=Math.min(10,B.dur/z);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*le:le}Y()}},()=>this._handleNetworkError())},nr=B=>{d()&&(ki(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(ve(B),!1)))},Vt=B=>{d()&&(e.cachedHeader=B,$(B,()=>{V=!0,Y()}))};s=!0,U.seek(B=>{if(d()){if(P=ee(),!B){A();return}k=B,!Nw(R)||B.startTS>R?mt(B):(E=B,C())}},R),e.cachedHeader?Vt(e.cachedHeader):p(e.headerUrl,Vt,()=>this._handleNetworkError())},stop:x,getTimestampSec:()=>n},c}_switchToQuality(e){let{logger:t,playerCallback:r}=this.params,a;e.bitrate!==this.bitrate&&(this.rep&&(a=this.rep.getTimestampSec(),Ps(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,ki(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(a),r({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return Ps(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,r=d=>{if(!this.autoQuality)return;let p,h,f;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&d<this.bitrate&&(h=this._getBufferSizeSec(),f=d/this.bitrate,h>10&&f>.8||h>15&&f>.5||h>20&&f>.3)){e(`Not switching: buffer=${Math.floor(h)}; bitrate=${this.bitrate}; newRate=${Math.floor(d)}`);return}p=this._selectQuality(d),p?this._switchToQuality(p):e(`Could not find quality by bitrate ${d}`)},s={updateChunk:(p,h)=>{let f=ee();if(this.chunkRateEstimator.addInterval(p,f,h)){let g=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:h,duration:f-p,speed:g}),!0}},get:()=>{let p=this.chunkRateEstimator.getBitRate();return p?p*.85:0}},n=-1/0,o,u=!0,l=()=>{let d=s.get();if(d&&o&&this.autoQuality){if(u&&d>o&&Tu(n)<3e4)return;r(d)}u=this.autoQuality};return{updateChunk:(d,p)=>{let h=s.updateChunk(d,p);return h&&l(),h},notifySwitch:d=>{let p=ee();d<o&&(n=p),o=d}}}_fetchManifest(e,t,r){this.manifestRequest=Vr(this.urlResolver.resolve(e,!0),t,r,()=>this._retryCallback()).withJSONResponse().withTimeout(As).withRetryCount(this.params.config.manifestRetryMaxCount).withRetryInterval(this.params.config.manifestRetryInterval,this.params.config.manifestRetryMaxInterval).send().withFinally(()=>{this.manifestRequest=void 0})}_playVideoElement(){let{videoElement:e}=this.params;fe(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))},qw))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};var Ab=D(Ir(),1);import{debounce as Qw,filter as xb,fromEvent as Gw,interval as Ww,isHigher as Yw,isInvariantQuality as zw,isLower as Kw,merge as Jw,Subject as Pb,Subscription as Xw}from"@vkontakte/videoplayer-shared";var xu=class{constructor(){this.onDroopedVideoFramesLimit$=new Pb;this.subscription=new Xw;this.playing=!1;this.tracks=[];this.forceChecker$=new Pb;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&&!zw(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&&Yw(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(Gw(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=Ww(this.droppedFramesChecker.checkTime).pipe(xb(()=>this.playing),xb(()=>{let a=!!this.isForceCheckCounter;return a&&(this.isForceCheckCounter-=1),!a})),t=this.forceChecker$.pipe(Qw(this.droppedFramesChecker.checkTime)),r=Jw(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,Ab.default)(this.limitCounts).filter(([,r])=>r>=this.droppedFramesChecker.countLimit).sort(([r],[a])=>Kw(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}},ks=xu;import{map as Zw,Observable as eR}from"@vkontakte/videoplayer-shared";import{fromEvent as tR}from"@vkontakte/videoplayer-shared";var Ri=()=>!!window.documentPictureInPicture?.window||!!document.pictureInPictureElement;var rR=(i,e)=>new eR(t=>{if(!window.IntersectionObserver)return;let r={root:null},a=new IntersectionObserver((n,o)=>{n.forEach(u=>t.next(u.isIntersecting||Ri()))},{...r,...e});a.observe(i);let s=tR(document,"visibilitychange").pipe(Zw(n=>!document.hidden||Ri())).subscribe(n=>t.next(n));return()=>{a.unobserve(i),s.unsubscribe}}),Me=rR;var dR=["paused","playing","ready"],pR=["paused","playing","ready"],$i=class{constructor(e){this.subscription=new uR;this.videoState=new L("stopped");this.representations$=new Au([]);this.textTracksManager=new $e;this.droppedFramesManager=new ks;this.maxSeekBackTime$=new Au(1/0);this.zeroTime$=new Au(void 0);this.liveOffset=new ot;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:Rb.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=xt(a.name)??cR(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),Pu(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,ku.default)(pR,e)&&(n||o)){this.prepare();return}if(a?.to!=="paused"&&s.state==="requested"&&(0,ku.default)(dR,e)){this.seek(s.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(ae(this.params.source.url));return;case"manifest_ready":this.videoState.startTransitionTo("ready"),this.prepare();break;case"ready":if(r==="paused")this.videoState.setState("paused");else if(r==="playing"){this.videoState.startTransitionTo("playing");let u=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(ae(this.params.source.url,u))}return;default:return kb(e)}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=a=>{e.output.error$.next({id:"DashLiveProvider",category:Rb.WTF,message:"DashLiveProvider internal logic error",thrown:a})};Lb(this.videoState.stateChangeStarted$.pipe(ws(a=>({transition:a,type:"start"}))),this.videoState.stateChangeEnded$.pipe(ws(a=>({transition:a,type:"end"})))).subscribe(({transition:a,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(a)}`})}),this.video=de(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(Z(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);let r=me(this.video);this.subscription.add(this.representations$.pipe(ws(a=>a.map(({track:s})=>s)),$b(a=>!!a.length),oR()).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(sR(),ws(a=>-a/1e3)).subscribe(this.params.output.duration$)).add(iR({zeroTime:this.zeroTime$.pipe($b(Pu)),position:r.timeUpdate$}).subscribe(({zeroTime:a,position:s})=>this.params.output.liveTime$.next(a+s*1e3),t)).add(Ke(this.video,this.params.desiredState.isLooped,t)).add(he(this.video,this.params.desiredState.volume,r.volumeState$,t)).add(r.volumeState$.subscribe(this.params.output.volume$,t)).add(Re(this.video,this.params.desiredState.playbackRate,r.playbackRateState$,t)).add(r.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(r.loadedMetadata$.subscribe(this.params.output.loadedMetadataEvent$)).add(r.playing$.subscribe(this.params.output.firstFrameEvent$)).add(r.canplay$.subscribe(this.params.output.canplay$)).add(r.inPiP$.subscribe(this.params.output.inPiP$)).add(r.inFullscreen$.subscribe(this.params.output.inFullscreen$)).add(Me(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:a}})=>{let s=a&&lR(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 kb(a.to)}},t)).add(Lb(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,nR(["init"])).pipe(aR(0)).subscribe(this.syncPlayback,t))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.droppedFramesManager.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),pe(this.video)}createLiveDashPlayer(){let e=new wi({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&&Pu(t)?t:At(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;wb(l,"Representations missing"),this.dash.startPlay(l,r)}}setVideoTrack(e){let t=this.representations$.getValue().find(({track:r})=>r.id===e.id)?.representation;wb(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(ae(this.params.source.url,n)),a&&this.dash.pause(),this.liveOffset.resetTo(n,a)}};var Mb=$i;var sv=D(ze(),1);var Xe=(i,e)=>{let t=0;for(let r=0;r<i.length;r++){let a=i.start(r)*1e3,s=i.end(r)*1e3;a<=e&&e<=s&&(t=s)}return Math.max(t-e,0)};import{assertNever as WL,assertNonNullable as YL,debounce as zL,ErrorCategory as dl,filter as rv,filterChanged as ga,fromEvent as KL,isNonNullable as iv,map as pl,merge as Ks,observableFrom as JL,observeElementSize as XL,once as av,Subscription as ZL,ValueSubject as eM}from"@vkontakte/videoplayer-shared";var Rs=class{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,r){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:r})}removeEventListener(e,t){if(!(e in this.listeners))return;let r=this.listeners[e];for(let a=0,s=r.length;a<s;a++)if(r[a].callback===t){r.splice(a,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;let r=this.listeners[e.type].slice();for(let a=0,s=r.length;a<s;a++){let n=r[a];try{n.callback.call(this,e)}catch(o){Promise.resolve().then(()=>{throw o})}n.options&&n.options.once&&this.removeEventListener(e.type,n.callback)}return!e.defaultPrevented}},Or=class extends Rs{constructor(){super(),this.listeners||Rs.call(this),Object.defineProperty(this,"aborted",{value:!1,writable:!0,configurable:!0}),Object.defineProperty(this,"onabort",{value:null,writable:!0,configurable:!0}),Object.defineProperty(this,"reason",{value:void 0,writable:!0,configurable:!0})}toString(){return"[object AbortSignal]"}dispatchEvent(e){e.type==="abort"&&(this.aborted=!0,typeof this.onabort=="function"&&this.onabort.call(this,e)),super.dispatchEvent(e)}},Li=class{constructor(){Object.defineProperty(this,"signal",{value:new Or,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&&(Li.prototype[Symbol.toStringTag]="AbortController",Or.prototype[Symbol.toStringTag]="AbortSignal");function $s(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 wu(i){typeof i=="function"&&(i={fetch:i});let{fetch:e,Request:t=e.Request,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:a=!1}=i;if(!$s({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 p=new t(l,c);return d&&Object.defineProperty(p,"signal",{writable:!1,enumerable:!1,configurable:!0,value:d}),p},s.prototype=t.prototype);let n=e;return{fetch:(u,l)=>{let c=s&&s.prototype.isPrototypeOf(u)?u.signal:l?l.signal:void 0;if(c){let d;try{d=new DOMException("Aborted","AbortError")}catch{d=new Error("Aborted"),d.name="AbortError"}if(c.aborted)return Promise.reject(d);let p=new Promise((h,f)=>{c.addEventListener("abort",()=>f(d),{once:!0})});return l&&l.signal&&delete l.signal,Promise.race([p,n(u,l)])}return n(u,l)},Request:s}}var Mi=$s({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),Cb=Mi?wu({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,lt=Mi?Cb.fetch:window.fetch,A_=Mi?Cb.Request:window.Request,Pe=Mi?Li:window.AbortController,k_=Mi?Or:window.AbortSignal;var ll=D($u(),1);var Cs=D(Dr(),1);var ct=()=>window.ManagedMediaSource||window.MediaSource,Ls=()=>!!(window.ManagedMediaSource&&window.ManagedSourceBuffer?.prototype?.appendBuffer),Zb=()=>!!(window.MediaSource&&window.SourceBuffer?.prototype?.appendBuffer),eg=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;import{assertNever as Os,clientChecker as Ds}from"@vkontakte/videoplayer-shared";var Vs=document.createElement("video"),BR='video/mp4; codecs="avc1.42000a,mp4a.40.2"',_R='video/mp4; codecs="hev1.1.6.L93.B0"',tg='video/webm; codecs="vp09.00.10.08"',rg='video/webm; codecs="av01.0.00M.08"',NR='audio/mp4; codecs="mp4a.40.2"',FR='audio/webm; codecs="opus"',Ci={mms:Ls(),mse:Zb(),hls:!!(Vs.canPlayType?.("application/x-mpegurl")||Vs.canPlayType?.("vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},be={mp4:!!Vs.canPlayType?.("video/mp4"),webm:!!Vs.canPlayType?.("video/webm"),cmaf:!0},ge={h264:!!ct()?.isTypeSupported?.(BR),h265:!!ct()?.isTypeSupported?.(_R),vp9:!!ct()?.isTypeSupported?.(tg),av1:!!ct()?.isTypeSupported?.(rg),aac:!!ct()?.isTypeSupported?.(NR),opus:!!ct()?.isTypeSupported?.(FR)},Br=(ge.h264||ge.h265)&&ge.aac,Kt,qR=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:rg}}),window.navigator.mediaCapabilities.decodingInfo({...i,video:{...i.video,contentType:tg}})]);Kt={DASH_WEBM_AV1:e,DASH_WEBM:t}};try{qR()}catch(i){console.error(i)}var _r=Ci.hls&&be.mp4,ig=()=>Object.keys(ge).filter(i=>ge[i]),ag=(i,{useHlsJs:e,useManagedMediaSource:t,useOldMSEDetection:r})=>{let a=Ci.mse&&(!r||!!window.MediaStreamTrack)||Ci.mms&&t;return i.filter(s=>{switch(s){case"DASH_SEP":return a&&be.mp4&&Br;case"DASH_WEBM":return a&&be.webm&&ge.vp9&&ge.opus;case"DASH_WEBM_AV1":return a&&be.webm&&ge.av1&&ge.opus;case"DASH_STREAMS":return a&&(be.mp4&&Br||be.webm&&(ge.vp9||ge.av1)&&(ge.opus||ge.aac));case"DASH_LIVE":return a&&be.mp4&&Br;case"DASH_LIVE_CMAF":return a&&be.mp4&&Br&&be.cmaf;case"DASH_ONDEMAND":return a&&be.mp4&&Br;case"HLS":case"HLS_ONDEMAND":return _r||e&&a&&be.mp4&&Br;case"HLS_LIVE":case"HLS_LIVE_CMAF":return _r;case"MPEG":return be.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return Ci.webrtc&&Ci.ws&&ge.h264&&(be.mp4||be.webm);default:return Os(s)}})},Ms=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 Kt?Kt[t].smooth?[t,e]:Kt[e].smooth?[e,t]:[t,e]:[e,t];case"power_efficient":return Kt?Kt[t].powerEfficient?[t,e]:Kt[e].powerEfficient?[e,t]:[t,e]:[e,t];default:Os(i)}return[e,t]},sg=({webmCodec:i,androidPreferredFormat:e,preferMultiStream:t})=>{let r=[...t?["DASH_STREAMS"]:[],...Ms(i),"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]],a=[...t?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]];if(Ds.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",...Ms(i),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...Ms(i),"MPEG",...a,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...Ms(i),...a,"HLS","HLS_ONDEMAND"];default:Os(e)}return _r?[...r,"HLS","HLS_ONDEMAND","MPEG"]:[...r,"HLS","HLS_ONDEMAND","MPEG"]},ng=({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=Ds.isMac&&Ds.isSafari;if(Ds.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:Os(i)}else _r&&!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"]},Lu=i=>i?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],og=i=>{if(i.size===0)return;if(i.size===1){let t=i.values().next();return(0,Cs.default)(t.value.split("."),0)}for(let t of i){let r=(0,Cs.default)(t.split("."),0);if(r==="opus"||r==="vp09"||r==="av01")return r}let e=i.values().next();return(0,Cs.default)(e.value.split("."),0)};var wg=D(kg(),1);import{ErrorCategory as Vi}from"@vkontakte/videoplayer-shared";var Rg=i=>{if(!i)return{id:"EmptyResponse",category:Vi.PARSER,message:"Empty response"};if(i.length<=2&&i.match(/^\d+$/))return{id:`UVError#${i}`,category:Vi.NETWORK,message:`UV Error ${i}`};let e=(0,wg.default)(i).substring(0,100).toLowerCase();if(e.startsWith("<!doctype")||e.startsWith("<html>")||e.startsWith("<body>")||e.startsWith("<head>"))return{id:"UnexpectedHTML",category:Vi.NETWORK,message:"Received unexpected HTML, possibly a ISP block"};if(e.startsWith("<?xml"))return new DOMParser().parseFromString(i,"text/xml").querySelector("parsererror")?{id:"InvalidXML",category:Vi.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:Vi.PARSER,message:"Response is valid XML, but parser failed"}};var kt=(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};import{abortable as nl,assertNonNullable as rr,clientChecker as ML,combine as ha,ErrorCategory as Lt,filter as Qs,filterChanged as ol,flattenObject as ma,fromEvent as ir,getTraceSubscriptionMethod as CL,interval as ul,isNonNullable as WS,map as fa,merge as ar,now as DL,Subject as YS,Subscription as zS,tap as VL,throttle as OL,ValueSubject as W}from"@vkontakte/videoplayer-shared";var Ns=D(ze(),1),Ur=D(Dr(),1),Fs=D($u(),1);var a$=(i,e={})=>{let r=e.timeout||1,a=performance.now();return window.setTimeout(()=>{i({get didTimeout(){return e.timeout?!1:performance.now()-a-1>r},timeRemaining(){return Math.max(0,1+(performance.now()-a))}})},1)},s$=i=>window.clearTimeout(i),$g=i=>typeof i=="function"&&i?.toString().endsWith("{ [native code] }"),Lg=!$g(window.requestIdleCallback)||!$g(window.cancelIdleCallback),Ou=Lg?a$:window.requestIdleCallback,Oi=Lg?s$:window.cancelIdleCallback;var NS=D(gs(),1);import{assertNever as n$,ErrorCategory as Mg,clientChecker as Bu,Subject as Cg}from"@vkontakte/videoplayer-shared";var o$=18,Dg=!1;try{Dg=Bu.isSafari&&!!Bu.macVersion&&Bu.macVersion<=o$}catch(i){console.error(i)}var _u=class{constructor(e){this.bufferFull$=new Cg;this.error$=new Cg;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:Mg.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;Dg&&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:Mg.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:n$(t)}}},Vg=_u;var Nu=i=>{let e=0;for(let t=0;t<i.length;t++)e+=i.end(t)-i.start(t);return e*1e3};import{abortable as Zt,assertNonNullable as oe,ErrorCategory as Rt,fromEvent as tl,getExponentialDelay as rl,isNonNullable as Bs,isNullable as Ce,now as _s,once as IL,Subject as EL,Subscription as xL,ValueSubject as qr}from"@vkontakte/videoplayer-shared";var N=class{constructor(e,t){this.cursor=0;this.source=e,this.boxParser=t,this.children=[];let r=this.readUint32();this.type=this.readString(4),this.size32=r<=e.buffer.byteLength-e.byteOffset?r:NaN;let 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 Nr=class extends N{};var Bi=class extends N{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 N{constructor(e,t){super(e,t),this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let r=this.size-this.cursor;for(;r;){let a=this.readString(4);this.compatibleBrands.push(a),r-=4}}};var Ni=class extends N{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var j=class extends N{constructor(e,t){super(e,t);let r=this.readUint32();this.version=r>>>24,this.flags=r&16777215}};var Fi=class extends j{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 N{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Ui=class extends N{constructor(e,t){super(e,t),this.data=this.content}};var Jt=class extends j{get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e,t){super(e,t),this.segments=[],this.referenceId=this.readUint32(),this.timescale=this.readUint32(),this.earliestPresentationTime32=this.readUint32(),this.firstOffset32=this.readUint32(),this.earliestPresentationTime64=0,this.firstOffset64=0,this.referenceCount=this.readUint32()&65535;for(let r=0;r<this.referenceCount;r++){let a=this.readUint32(),s=a>>>31,n=a<<1>>>1,o=this.readUint32();a=this.readUint32();let u=a>>>28,l=a<<3>>>3;this.segments.push({referenceType:s,referencedSize:n,subsegmentDuration:o,SAPType:u,SAPDeltaTime:l})}}};var Hi=class extends N{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ji=class extends N{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Qi=class extends j{constructor(e,t){switch(super(e,t),this.readUint8()){case 0:this.stereoMode=0;break;case 1:this.stereoMode=1;break;case 2:this.stereoMode=2;break;case 3:this.stereoMode=3;break;case 4:this.stereoMode=4;break}this.cursor+=1}};var Gi=class extends j{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var Wi=class extends j{constructor(e,t){super(e,t),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}};var Yi=class extends N{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var zi=class extends j{constructor(e,t){super(e,t),this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.trackId=this.readUint32(),this.cursor+=4,this.duration=this.readUint32(),this.cursor+=8,this.layer=this.readUint16(),this.alternateGroup=this.readUint16(),this.cursor+=2,this.cursor+=2,this.matrix=[[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()]],this.width=this.readUint32(),this.height=this.readUint32()}};var Ki=class extends N{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Ji=class extends N{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Xi=class extends j{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var Zi=class extends N{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ea=class extends j{constructor(e,t){super(e,t),this.trackId=this.readUint32(),this.flags&1&&(this.baseDataOffset=this.readUint64()),this.flags&2&&(this.sampleDescriptionIndex=this.readUint32()),this.flags&8&&(this.defaultSampleDuration=this.readUint32()),this.flags&16&&(this.defaultSampleSize=this.readUint32()),this.flags&32&&(this.defaultSampleFlags=this.readUint32())}};var ta=class extends j{constructor(t,r){super(t,r);this.baseMediaDecodeTime32=0;this.baseMediaDecodeTime64=BigInt(0);this.version===1?this.baseMediaDecodeTime64=this.readUint64():this.baseMediaDecodeTime32=this.readUint32()}get baseMediaDecodeTime(){return this.version===1?this.baseMediaDecodeTime64:this.baseMediaDecodeTime32}};var ra=class extends j{constructor(t,r){super(t,r);this.sampleDuration=[];this.sampleSize=[];this.sampleFlags=[];this.sampleCompositionTimeOffset=[];this.optionalFields=0;this.sampleCount=this.readUint32(),this.flags&1&&(this.dataOffset=this.readUint32()),this.flags&4&&(this.firstSampleFlags=this.readUint32());for(let a=0;a<this.sampleCount;a++)this.flags&256&&this.sampleDuration.push(this.readUint32()),this.flags&512&&this.sampleSize.push(this.readUint32()),this.flags&1024&&this.sampleFlags.push(this.readUint32()),this.flags&2048&&this.sampleCompositionTimeOffset.push(this.readUint32())}};var l$={ftyp:_i,moov:Ni,mvhd:Fi,moof:qi,mdat:Ui,sidx:Jt,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:Nr},dt=class i{constructor(e={}){this.options={offset:0,...e}}parse(e){let t=[],r=this.options.offset;for(;r<e.byteLength;)try{let s=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+r+4,4)),n=this.createBox(s,new DataView(e.buffer,e.byteOffset+r));if(!n.size)break;t.push(n),r+=n.size}catch{break}return t}createBox(e,t){let r=l$[e];return r?new r(t,new i):new Nr(t,new i)}};var wt=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 d$=new TextDecoder("ascii"),p$=i=>d$.decode(new DataView(i.buffer,i.byteOffset+4,4))==="ftyp",h$=i=>{let e=new Jt(i,new dt),t=e.earliestPresentationTime/e.timescale*1e3,r=i.byteOffset+i.byteLength+e.firstOffset;return e.segments.map(s=>{if(s.referenceType!==0)throw new Error("Unsupported multilevel sidx");let n=s.subsegmentDuration/e.timescale*1e3,o={status:"none",time:{from:t,to:t+n},byte:{from:r,to:r+s.referencedSize-1}};return t+=n,r+=s.referencedSize,o})},m$=(i,e)=>{let r=new dt().parse(i),a=new wt(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)},f$=i=>{let t=new dt().parse(i),r=new wt(t),a={},s=r.findAll("uuid");return s.length?s[s.length-1]:a},b$=i=>{let t=new dt().parse(i);return new wt(t).find("sidx")?.timescale},g$=(i,e)=>{let r=new dt().parse(i),s=new wt(r).findAll("traf"),n=s[s.length-1].children.find(d=>d.type==="tfhd"),o=s[s.length-1].children.find(d=>d.type==="tfdt"),u=s[s.length-1].children.find(d=>d.type==="trun"),l=0;return u.sampleDuration.length?l=u.sampleDuration.reduce((d,p)=>d+p,0):l=n.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+l)/e*1e3},S$=i=>{let e={is3dVideo:!1,stereoMode:0,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}},r=new dt().parse(i),a=new wt(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},Og={validateData:p$,parseInit:S$,getIndexRange:()=>{},parseSegments:h$,parseFeedableSegmentChunk:m$,getChunkEndTime:g$,getServerLatencyTimestamps:f$,getTimescaleFromIndex:b$};var aa=D(ze(),1);import{assertNonNullable as qu,isNonNullable as Fg,isNullable as y$}from"@vkontakte/videoplayer-shared";import{assertNever as v$}from"@vkontakte/videoplayer-shared";var Bg={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"}},_g=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 Bg,s=a?Bg[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,p=t+o,h;return p+d>i.byteLength?h=new DataView(i.buffer,i.byteOffset+p):h=new DataView(i.buffer,i.byteOffset+p,d),{tag:a?r:"0x"+r.toString(16).toUpperCase(),type:s,tagHeaderSize:p,tagSize:p+d,value:h,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},qe=(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:v$(e)}},Xt=(i,e)=>{let t=0;for(;t<i.byteLength;){let r=new DataView(i.buffer,i.byteOffset+t),a=_g(r);if(!e(a))return;a.type==="master"&&Xt(a.value,e),t=a.value.byteOffset-i.byteOffset+a.valueSize}},Ng=i=>{if(i.getUint32(0)!==440786851)return!1;let e,t,r,a=_g(i);return Xt(a.value,({tag:s,type:n,value:o})=>(s===17143?e=qe(o,n):s===17026?t=qe(o,n):s===17029&&(r=qe(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(r===void 0||r<=2)};var qg=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],T$=[231,22612,22743,167,171,163,160,175],I$=i=>{let e,t,r,a,s=!1,n=!1,o=!1,u,l,c=!1,d=0;return Xt(i,({tag:p,type:h,value:f,valueSize:b})=>{if(p===21419){let g=qe(f,h);l=ia(g)}else p!==21420&&(l=void 0);return p===408125543?(e=f.byteOffset,t=f.byteOffset+b):p===357149030?s=!0:p===290298740?n=!0:p===2807729?r=qe(f,h):p===17545?a=qe(f,h):p===21420&&l===475249515?u=qe(f,h):p===374648427?Xt(f,({tag:g,type:S,value:x})=>g===30321?(c=qe(x,S)===1,!1):!0):s&&n&&(0,aa.default)(qg,p)&&(o=!0),!o}),qu(e,"Failed to parse webm Segment start"),qu(t,"Failed to parse webm Segment end"),qu(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}}}},E$=i=>{if(y$(i.cuesSeekPosition))return;let e=i.segmentStart+i.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},x$=(i,e)=>{let t=!1,r=!1,a=o=>Fg(o.time)&&Fg(o.position),s=[],n;return Xt(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=qe(l,u));break;case 183:break;case 241:n&&(n.position=qe(l,u));break;default:t&&(0,aa.default)(qg,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}}})},P$=i=>{let e=0,t=!1;try{Xt(i,r=>r.tag===524531317?r.tagSize<=i.byteLength?(e=r.tagSize,!1):(e+=r.tagHeaderSize,!0):(0,aa.default)(T$,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},Ug={validateData:Ng,parseInit:I$,getIndexRange:E$,parseSegments:x$,parseFeedableSegmentChunk:P$};var sa=i=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(i);if(e){let[,t,r]=e;if(t==="audio"||t==="video")switch(r){case"webm":return Ug;case"mp4":return Og}}throw new ReferenceError(`Unsupported mime type ${i}`)};var Yu=D(uS(),1),LS=D(Ir(),1),MS=D(xS(),1),CS=D(Dr(),1);var PS=D(ze(),1),Wu=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,PS.default)(["6E","7A","F4"],o)}}return!1};import{isNonNullable as wS,isNullable as RS}from"@vkontakte/videoplayer-shared";var AS=i=>{if(i.includes("/")){let e=i.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(i)};var kS=i=>{try{let e=yL(),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 yL(){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 kS=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},pt=(i,e)=>{let t=i;t=(0,Gu.default)(t,"$$","$");let r={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[a,s]of(0,wS.default)(r)){let n=new RegExp(`\\$${a}(?:%0(\\d+)d)?\\$`,"g");t=(0,Gu.default)(t,n,(o,u)=>AS(s)?o:AS(u)?s:(0,RS.default)(s,parseInt(u,10),"0"))}return t},LS=(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(y=>y.textContent?.trim()??""),u=(0,$S.default)(o,0)??"",l=n.children,c=s.getAttribute("type")==="dynamic",d=s.getAttribute("availabilityStartTime"),p=d?new Date(d).getTime():void 0,h,f=s.getAttribute("mediaPresentationDuration"),b=n.getAttribute("duration"),S=s.getElementsByTagName("vk:Attrs")[0]?.getElementsByTagName("vk:XPlaybackDuration")[0].textContent;if(f)h=kS(f);else if(b){let y=kS(b);PS(y)&&(h=y)}else S&&(h=parseInt(S,10));let A=0,E=s.getAttribute("profiles")?.split(",")??[];for(let y of l){let R=y.getAttribute("id")??"id"+(A++).toString(10),B=y.getAttribute("mimeType")??"",F=y.getAttribute("codecs")??"",_=y.getAttribute("contentType")??B?.split("/")[0],U=y.getAttribute("profiles")?.split(",")??[],v=xS(y.getAttribute("lang")??"")??{},T=y.querySelector("Label")?.textContent?.trim()??void 0,q=y.querySelectorAll("Representation"),ye=y.querySelector("SegmentTemplate"),Ve=y.querySelector("Role")?.getAttribute("value")??void 0,P=_,M={id:R,language:v.language,isDefault:Ve==="main",label:T,codecs:F,hdr:P==="video"&&ju(F),mime:B,representations:[]};for(let w of q){let K=w.getAttribute("lang")??void 0,te=w.getAttribute("label")??void 0,mt=w.querySelector("BaseURL")?.textContent?.trim()??"",nr=new URL(mt||u,e).toString(),Vt=w.getAttribute("mimeType")??B,V=w.getAttribute("codecs")??F??"",re;if(_==="text"){let Y=w.getAttribute("id")||"",ce=v.privateuse?.includes("x-auto")||Y.includes("_auto"),Te=w.querySelector("SegmentTemplate");if(Te){let tt={representationId:w.getAttribute("id")??void 0,bandwidth:w.getAttribute("bandwidth")??void 0},je=parseInt(w.getAttribute("bandwidth")??"",10)/1e3,rt=parseInt(Te.getAttribute("startNumber")??"",10)??1,Ge=parseInt(Te.getAttribute("timescale")??"",10),or=Te.querySelectorAll("SegmentTimeline S")??[],ur=Te.getAttribute("media");if(!ur)continue;let $a=[],La=0,Ma="",lr=0,Qr=rt,ne=0;for(let Be of or){let Bt=parseInt(Be.getAttribute("d")??"",10),Re=parseInt(Be.getAttribute("r")??"",10)||0,ft=parseInt(Be.getAttribute("t")??"",10);ne=Number.isFinite(ft)?ft:ne;let Ot=Bt/Ge*1e3,cr=ne/Ge*1e3;for(let Qe=0;Qe<Re+1;Qe++){let bt=pt(ur,{...tt,segmentNumber:Qr.toString(10),segmentTime:(ne+Qe*Bt).toString(10)}),dr=(cr??0)+Qe*Ot,Yr=dr+Ot;Qr++,$a.push({time:{from:dr,to:Yr},url:bt})}ne+=(Re+1)*Bt,La+=(Re+1)*Ot}lr=ne/Ge*1e3,Ma=pt(ur,{...tt,segmentNumber:Qr.toString(10),segmentTime:ne.toString(10)});let Wr={time:{from:lr,to:1/0},url:Ma},it={type:"template",baseUrl:nr,segmentTemplateUrl:ur,initUrl:"",totalSegmentsDurationMs:La,segments:$a,nextSegmentBeyondManifest:Wr,timescale:Ge};re={id:Y,kind:"text",segmentReference:it,profiles:[],duration:h,bitrate:je,mime:"",codecs:"",width:0,height:0,isAuto:ce}}else re={id:Y,isAuto:ce,kind:"text",url:nr}}else{let Y=w.getAttribute("contentType")??Vt?.split("/")[0]??_,ce=y.getAttribute("profiles")?.split(",")??[],Te=parseInt(w.getAttribute("width")??"",10),tt=parseInt(w.getAttribute("height")??"",10),je=parseInt(w.getAttribute("bandwidth")??"",10)/1e3,rt=w.getAttribute("frameRate")??"",Ge=w.getAttribute("quality")??void 0,or=rt?ES(rt):void 0,ur=w.getAttribute("id")??"id"+(A++).toString(10),$a=Y==="video"?`${tt}p`:Y==="audio"?`${je}Kbps`:V,La=`${ur}@${$a}`,Ma=[...E,...U,...ce],lr,Qr=w.querySelector("SegmentBase"),ne=w.querySelector("SegmentTemplate")??ye;if(Qr){let it=w.querySelector("SegmentBase Initialization")?.getAttribute("range")??"",[Be,Bt]=it.split("-").map(bt=>parseInt(bt,10)),Re={from:Be,to:Bt},ft=w.querySelector("SegmentBase")?.getAttribute("indexRange"),[Ot,cr]=ft?ft.split("-").map(bt=>parseInt(bt,10)):[],Qe=ft?{from:Ot,to:cr}:void 0;lr={type:"byteRange",url:nr,initRange:Re,indexRange:Qe}}else if(ne){let it={representationId:w.getAttribute("id")??void 0,bandwidth:w.getAttribute("bandwidth")??void 0},Be=parseInt(ne.getAttribute("timescale")??"",10),Bt=ne.getAttribute("initialization")??"",Re=ne.getAttribute("media"),ft=parseInt(ne.getAttribute("startNumber")??"",10)??1,Ot=pt(Bt,it);if(!Re)throw new ReferenceError("No media attribute in SegmentTemplate");let cr=ne.querySelectorAll("SegmentTimeline S")??[],Qe=[],bt=0,dr="",Yr=0;if(cr.length){let Ca=ft,Oe=0;for(let pr of cr){let We=parseInt(pr.getAttribute("d")??"",10),_t=parseInt(pr.getAttribute("r")??"",10)||0,Da=parseInt(pr.getAttribute("t")??"",10);Oe=Number.isFinite(Da)?Da:Oe;let ln=We/Be*1e3,Zv=Oe/Be*1e3;for(let Va=0;Va<_t+1;Va++){let ey=pt(Re,{...it,segmentNumber:Ca.toString(10),segmentTime:(Oe+Va*We).toString(10)}),Pl=(Zv??0)+Va*ln,ty=Pl+ln;Ca++,Qe.push({time:{from:Pl,to:ty},url:ey})}Oe+=(_t+1)*We,bt+=(_t+1)*ln}Yr=Oe/Be*1e3,dr=pt(Re,{...it,segmentNumber:Ca.toString(10),segmentTime:Oe.toString(10)})}else if(PS(h)){let Oe=parseInt(ne.getAttribute("duration")??"",10)/Be*1e3,pr=Math.ceil(h/Oe),We=0;for(let _t=1;_t<pr;_t++){let Da=pt(Re,{...it,segmentNumber:_t.toString(10),segmentTime:We.toString(10)});Qe.push({time:{from:We,to:We+Oe},url:Da}),We+=Oe}Yr=We,dr=pt(Re,{...it,segmentNumber:pr.toString(10),segmentTime:We.toString(10)})}let Xv={time:{from:Yr,to:1/0},url:dr};lr={type:"template",baseUrl:nr,segmentTemplateUrl:Re,initUrl:Ot,totalSegmentsDurationMs:bt,segments:Qe,nextSegmentBeyondManifest:Xv,timescale:Be}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!Y||!Vt)continue;let Wr={video:"video",audio:"audio",text:"text"}[Y];if(!Wr)continue;P||=Wr,re={id:La,kind:Wr,segmentReference:lr,profiles:Ma,duration:h,bitrate:je,mime:Vt,codecs:V,width:Te,height:tt,fps:or,quality:Ge}}M.language||=K,M.label||=te,M.mime||=Vt,M.codecs||=V,M.hdr||=P==="video"&&ju(V),M.representations.push(re)}P&&a[P].push(M)}return{dynamic:c,liveAvailabilityStartTime:p,duration:h,streams:a,baseUrls:o}};var Yu=C(Dr(),1);import{videoSizeToQuality as SL}from"@vkontakte/videoplayer-shared";var MS=({id:i,width:e,height:t,bitrate:r,fps:a,quality:s,streamId:n})=>{let o=(s?xt(s):void 0)??SL({width:e,height:t});return o&&{id:i,quality:o,bitrate:r,size:{width:e,height:t},fps:a,streamId:n}},CS=({id:i,bitrate:e})=>({id:i,bitrate:e}),DS=({language:i,label:e},{id:t,url:r,isAuto:a})=>({id:t,url:r,isAuto:a,type:"internal",language:i,label:e}),VS=({language:i,label:e,id:t,url:r,isAuto:a})=>({id:t,url:r,isAuto:a,type:"internal",language:i,label:e}),zu=({id:i,language:e,label:t,codecs:r,isDefault:a})=>({id:i,language:e,label:t,codec:(0,Yu.default)(r.split("."),0),isDefault:a}),Ku=({id:i,language:e,label:t,hdr:r,codecs:a})=>({id:i,language:e,hdr:r,label:t,codec:(0,Yu.default)(a.split("."),0)}),Ju=i=>"url"in i,ke=i=>i.type==="template",sa=i=>i instanceof DOMException&&(i.name==="AbortError"||i.code===20);var na=class{constructor(e,t,r,{fetcher:a,tuning:s,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new qr(0);this.currentSegmentLength$=new qr(0);this.onLastSegment$=new qr(!1);this.fullyBuffered$=new qr(!1);this.playingRepresentation$=new qr(void 0);this.playingRepresentationInit$=new qr(void 0);this.error$=new yL;this.gaps=[];this.subscription=new TL;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new Ae;this.switchAbortController=new Ae;this.destroyAbortController=new Ae;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=Zt(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);ue(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new Mg(this.sourceBuffer),this.subscription.add(Xu(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let o,u=this.mediaSource.readyState;u!=="open"&&(o={id:`SegmentEjection_source_${u}`,category:Rt.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o??={id:"SegmentEjection",category:Rt.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n},this.error$.next(o)})),this.subscription.add(Xu(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:Rt.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,Bu(this.sourceBuffer.buffered)*.8);this.bufferLimit=u;let l=Ze(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);ue(r,"No init buffer for starting representation"),ue(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=Zt(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);ue(r,`No such representation ${e}`);let a=this.segments.get(e),s=this.initData.get(e);if(De(s)||De(a)?yield this.loadInit(r,"high",!1):s instanceof Promise&&(yield s),a=this.segments.get(e),ue(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();Vs(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=Zt(this.destroyAbortController.signal,async function*(e){let t=(0,_s.default)(e,u=>u.representations)??[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let u of this.representations.keys()){let l=t.find(p=>p.id===u);l&&this.representations.set(u,l);let c=this.representations.get(u);if(!c||!ke(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);ue(a);let s=this.segments.get(r);ue(s,"No segments for starting representation");let n=this.initData.get(r);if(ue(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 Ae,Zt(this.switchAbortController.signal,async function*(r,a=!1){this.switchingToRepresentationId=r;let s=this.representations.get(r);ue(s,`No such representation ${r}`);let n=this.segments.get(r),o=this.initData.get(r);if(De(o)||De(n)?yield this.loadInit(s,"high",!1):o instanceof Promise&&(yield o),n=this.segments.get(r),ue(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();Vs(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 Ae,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(De(e)||De(this.downloadingRepresentationId)||De(this.playingRepresentationId)||De(this.sourceBuffer)||Vs(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),r=this.segments.get(this.downloadingRepresentationId);if(ue(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=Ze(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)&&Bu(this.sourceBuffer.buffered)>=this.bufferLimit){let l=Ze(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,Os.default)(o,a))l="high";else{let c=(0,Ur.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&&Ze(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let u=(0,Ur.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;Vs(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,_s.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,_s.default)(e?.streams[this.kind],r=>r.representations)??[];for(let r of t){if(!r||!ke(r.segmentReference))return;let a=r.segmentReference.segments.map(u=>({...u,status:"none",size:void 0})),s=this.segments.get(r.id)??[],n=(0,Ur.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;ue(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(!ke(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=pt(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&&Vi&&Vi(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&Vi&&Vi(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:p,to:h}},f)=>{let b=p<=r&&h>=r,g=p>r||b||f===0&&r===0,S=Math.min(this.forwardBufferTarget,this.bufferLimit),A=this.preloadOnly&&p<=r+S||h<=r+S;return(d==="none"||d==="partially_ejected"&&g&&A&&this.sourceBuffer&&!(kt(this.sourceBuffer.buffered,p)&&kt(this.sourceBuffer.buffered,h)))&&g&&A});if(a===-1)return[];if(t!=="byteRange")return e.slice(a,a+1);let s=e,n=0,o=0,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 p=s[d];if(n+=p.byte.to+1-p.byte.from,o+=p.time.to+1-p.time.from,p.status==="none"||p.status==="partially_ejected")u.push(p);else break}return u}async loadSegments(e,t,r="auto"){ke(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 Zt(o,async function*(){let c=Zu(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=Bs(),!c)return;let d=new DataView(c),p=aa(t.mime);if(!isFinite(a.segment.time.to)){let b=t.segmentReference.timescale;a.segment.time.to=p.getChunkEndTime(d,b)}u&&a.feedingBytes&&l?await Promise.all(l):await this.sourceBufferTaskQueue.append(d,o);let{serverDataReceivedTimestamp:h,serverDataPreparedTime:f}=p.getServerLatencyTimestamps(d);h&&f&&this.currentLiveSegmentServerLatency$.next(f-h),a.segment.status="downloaded",this.onSegmentFullyAppended(a,t.id),this.failedDownloads=0}catch(c){this.abortActiveSegments([e]),sa(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())ke(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 Zt(n,async function*(){let u=Zu(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),Xu(window,"online").pipe(vL()).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=Bs(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),sa(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}prepareByteRangeFetchSegmentParams(e,t){if(ke(t.segmentReference))throw new Error("Representation is not byte range type");let r=t.segmentReference.url,a={from:(0,Ur.default)(e,0).byte.from,to:(0,Ur.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=Bs(),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:Rt.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!ke(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=Bs();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:Rt.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,Os.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=aa(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,p=d-c+1,h=c<a,f=d<=a;if(!h)continue;let b=aa(o.mime);if(l.status==="downloading"&&f){l.status="downloaded";let g=new DataView(e.buffer,e.byteOffset+c,p);await this.sourceBufferTaskQueue.append(g,s)&&!s.aborted?this.onSegmentFullyAppended(u,t):n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(l.status==="downloading"||l.status==="partially_fed")&&(u.loadedBytes=Math.min(p,a-c),u.loadedBytes>u.feedingBytes)){let g=new DataView(e.buffer,e.byteOffset+c+u.feedingBytes,u.loadedBytes-u.feedingBytes),S=u.loadedBytes===p?g:b.parseFeedableSegmentChunk(g);S?.byteLength&&(l.status="partially_fed",u.feedingBytes+=S.byteLength,await this.sourceBufferTaskQueue.append(S,s)&&!s.aborted?(u.fedBytes+=S.byteLength,u.fedBytes===p&&this.onSegmentFullyAppended(u,t)):n())}}}onSegmentFullyAppended(e,t){this.tuning.useSafariEndlessRequestBugfix&&!this.isLive&&(ue(this.sourceBuffer),kt(this.sourceBuffer.buffered,e.segment.time.from,100)&&kt(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"SafariEmptyAppendBuffer",category:Rt.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",Ju(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");ue(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=Cu(()=>(0,BS.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?Zt(this.destroyAbortController.signal,async function*(){let o=Zu(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,aa(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 p=c;this.isLive&&ke(e.segmentReference)&&(p=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,p),u&&this.parsedInitData.set(e.id,u)}).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),r&&this.error$.next({id:"LoadInits",category:Rt.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||De(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:p}=u[c],h=l[l.length-1];h.to>=d?h.to=Math.max(h.to,p):l.push(u[c])}return l},o=u=>{if(s>=t)return a;a.push({...u.time}),a=n(a);let l=Ju(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 p of this.segments.values())for(let h of p)(0,Os.default)(["none","partially_ejected"],h.status)&&Math.round(h.time.from)<=Math.round(l)&&Math.round(h.time.to)>=Math.round(c)&&d++;if(d===this.segments.size){let p={time:{from:l,to:c},url:"",status:"none"};o(p)}}if(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||De(e)?0:Ze(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){ue(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=Cu(()=>{try{this.detectGaps(e,t)}catch(r){this.error$.next({id:"GapDetection",category:Rt.WTF,message:"detectGaps threw",thrown:r})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if(De(this.sourceBuffer)||De(this.playingRepresentationId))return;let e=[];for(let r=0;r<this.sourceBuffer.buffered.length;r++){let 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 oa=i=>{let e=new URL(i);return e.searchParams.set("quic","1"),e.toString()};var OS=i=>{let e=i.get("X-Delivery-Type"),t=i.get("X-Reused"),r=e===null?"http1":e??void 0,a=t===null?void 0:{1:!0,0:!1}[t]??void 0;return{type:r,reused:a}};import{abortable as ua,assertNever as NS,fromEvent as FS,merge as IL,now as la,Subscription as EL,ValueSubject as el,flattenObject as Hr}from"@vkontakte/videoplayer-shared";var _S=i=>{let e=new URL(i);return e.searchParams.set("enable-subtitles","yes"),e.toString()};var Ns=class{constructor({throughputEstimator:e,requestQuic:t,tracer:r,compatibilityMode:a=!1,useEnableSubtitlesParam:s=!1}){this.lastConnectionType$=new el(void 0);this.lastConnectionReused$=new el(void 0);this.lastRequestFirstBytes$=new el(void 0);this.abortAllController=new Ae;this.subscription=new EL;this.fetchManifest=ua(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),r=e;this.requestQuic&&(r=oa(r)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(r=_S(r));let a=yield lt(r,{signal:this.abortAllController.signal}).catch(ca);return a?(t.log("success",Hr({url:r,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(a.headers),a.text()):(t.error("error",Hr({url:r,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=ua(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 v=new URL(l,location.href);v.searchParams.append("bytes",`${r.from}-${r.to}`),l=v.toString();break}default:NS(t)}this.requestQuic&&(l=oa(l));let p=this.abortAllController.signal,h;if(n){let v=new Ae;if(h=IL(FS(this.abortAllController.signal,"abort"),FS(n,"abort")).subscribe(()=>{try{v.abort()}catch(T){ca(T)}}),this.abortAllController.signal.aborted||n.aborted)try{v.abort()}catch(T){ca(T)}p=v.signal}let f=la();d.log("startRequest",Hr({url:l,priority:s,rangeMethod:t,range:r,isLowLatency:u,requestStartedAt:f}));let b=yield lt(l,{priority:s,headers:c,signal:p}).catch(ca),g=la();if(!b)return d.error("error",{message:"No response in request"}),d.end(),h?.unsubscribe(),null;if(this.throughputEstimator?.addRawRtt(g-f),!b.ok||!b.body){h?.unsubscribe();let v=`Fetch error ${b.status}: ${b.statusText}`;return d.error("error",{message:v}),d.end(),Promise.reject(new Error(`Fetch error ${b.status}: ${b.statusText}`))}if(this.onHeadersReceived(b.headers),!a&&!o){h?.unsubscribe();let v=la(),T={requestStartedAt:f,requestEndedAt:v,duration:v-f};return d.log("endRequest",Hr(T)),d.end(),b.arrayBuffer()}let[S,A]=b.body.tee(),E=S.getReader();o&&this.throughputEstimator?.trackStream(A,u);let k=0,y=new Uint8Array(0),R=!1,B=v=>{h?.unsubscribe(),R=!0,ca(v)},F=ua(p,async function*({done:v,value:T}){if(k===0&&this.lastRequestFirstBytes$.next(la()-f),p.aborted){h?.unsubscribe();return}if(!v&&T){let q=new Uint8Array(y.length+T.length);q.set(y),q.set(T,y.length),y=q,k+=T.byteLength,a?.(new DataView(y.buffer),k),yield E?.read().then(F,B)}}.bind(this));yield E?.read().then(F,B),h?.unsubscribe();let _=la(),U={failed:R,requestStartedAt:f,requestEndedAt:_,duration:_-f};return R?(d.error("endRequest",Hr(U)),d.end(),null):(d.log("endRequest",Hr(U)),d.end(),y.buffer)}.bind(this));this.fetchByteRangeRepresentation=ua(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 p=new DataView(d,a-n,s-n+1);if(!t.validateData(p))throw new Error("Invalid media file");let h=t.parseInit(p),f=e.indexRange??t.getIndexRange(h);if(!f)throw new ReferenceError("No way to load representation index");let b;if(u)b=new DataView(d,f.from-n,f.to-f.from+1);else{let S=yield this.fetch(e.url,{range:f,priority:r,measureThroughput:!1});if(!S)return null;b=new DataView(S)}let g=t.parseSegments(b,h,f);return{init:h,dataView:new DataView(d),segments:g}}.bind(this));this.fetchTemplateRepresentation=ua(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}=OS(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:NS(a)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}},ca=i=>{if(!sa(i))throw i};var er=(i,e,t)=>t*e+(1-t)*i,tl=(i,e)=>i.reduce((t,r)=>t+r,0)/e,qS=(i,e,t,r)=>{let a=0,s=t,n=tl(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};import{isNullable as xL,ValueSubject as US}from"@vkontakte/videoplayer-shared";var $t=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 US(e.initial),this.debounced$=new US(e.initial);let t=e.label??"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new oe(`raw_${t}`),this.smoothedSeries$=new oe(`smoothed_${t}`),this.reportedSeries$=new oe(`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)&&(xL(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 Fs=class extends $t{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=er(this.slow,e,this.params.emaAlphaSlow),this.fast=er(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var qs=class extends $t{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=tl(this.pastMeasures,this.takenMeasures);this.emaSmoothed=er(this.emaSmoothed,e,this.params.emaAlpha);let r=qS(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=r?this.emaSmoothed:t}};var Us=class extends $t{constructor(t){super(t);this.furtherValues=[];this.currentTopExtremumValue=0;this.extremumInterval=t.extremumInterval}next(t){this.currentTopExtremumValue<=t?(this.currentTopExtremumValue=t,this.furtherValues=[]):this.furtherValues.length===this.extremumInterval?(super.next(this.currentTopExtremumValue),this.currentTopExtremumValue=t,this.furtherValues=[]):this.furtherValues.push(t)}updateSmoothedValue(t){this.smoothed=this.smoothed?er(this.smoothed,t,this.params.emaAlpha):t}};var tr=class{static getSmoothedValue(e,t,r){return r.type==="TwoEma"?new Fs({initial:e,emaAlphaSlow:r.emaAlphaSlow,emaAlphaFast:r.emaAlphaFast,changeThreshold:r.changeThreshold,fastDirection:t,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"}):new qs({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 Us({initial:e,label:"liveEdgeDelay",...t})}};var rl=(i,e)=>{i&&i.playbackRate!==e&&(i.playbackRate=e)};import{isNullable as PL,ValueSubject as AL}from"@vkontakte/videoplayer-shared";var da=class i{constructor(e,t){this.currentRepresentation$=new AL(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(!PL(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&&ke(t.segmentReference))}};var DL=["timeupdate","progress","play","seeked","stalled","waiting"],VL=["timeupdate","progress","loadeddata","playing","seeked"];var js=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new QS;this.representationSubscription=new QS;this.state$=new $("none");this.currentVideoRepresentation$=new W(void 0);this.currentVideoRepresentationInit$=new W(void 0);this.currentAudioRepresentation$=new W(void 0);this.currentVideoSegmentLength$=new W(0);this.currentAudioSegmentLength$=new W(0);this.error$=new GS;this.lastConnectionType$=new W(void 0);this.lastConnectionReused$=new W(void 0);this.lastRequestFirstBytes$=new W(void 0);this.currentLiveTextRepresentation$=new W(null);this.isLive$=new W(!1);this.liveDuration$=new W(0);this.liveAvailabilityStartTime$=new W(void 0);this.bufferLength$=new W(0);this.liveLatency$=new W(void 0);this.liveLoadBufferLength$=new W(0);this.livePositionFromPlayer$=new W(0);this.isLowLatency$=new W(!1);this.isActiveLowLatency$=new W(!1);this.currentStallDuration$=new W(0);this.videoLastDataObtainedTimestamp$=new W(0);this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.liveLastSeekOffset=0;this.forceEnded$=new GS;this.gapWatchdogActive=!1;this.destroyController=new Ae;this.initManifest=il(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:Lt.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=il(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:Lt.NETWORK,message:"Failed to load manifest",thrown:n})});if(!e)return null;let t=null;try{t=LS(e??"",this.manifestUrlString)}catch(n){let o=Ag(e)??{id:"ManifestParsing",category:Lt.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)&&ct()?.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:p})=>r(n,d,p)),l=new Set(u.map(({codecs:d})=>d)),c=ag(l);if(c&&(a[n]=u.filter(({codecs:d})=>d.startsWith(c))),n==="video"){let d=this.tuning.preferHDR,p=a.video.some(f=>f.hdr),h=a.video.some(f=>!f.hdr);RL.isHDR&&d&&p?a.video=a.video.filter(f=>f.hdr):h&&(a.video=a.video.filter(f=>!f.hdr))}}let s={...t,streams:a};return this.tracer.log("updateManifestEnd",ha(s)),s}.bind(this));this.initRepresentations=il(this.destroyController.signal,async function*(e,t,r){this.tracer.log("initRepresentationsStart",ha({initialVideo:e,initialAudio:t,sourceHls:r})),rr(this.manifest),rr(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let a=p=>{this.representationSubscription.add(ir(p,"error").pipe(Hs(h=>!!this.element?.played.length)).subscribe(h=>{this.error$.next({id:"VideoSource",category:Lt.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:h})}))};this.source=this.tuning.useManagedMediaSource?Jb():new MediaSource;let s=document.createElement("source");if(a(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),this.tuning.useManagedMediaSource&&Rs())if(r){let p=document.createElement("source");a(p),p.type="application/x-mpegurl",p.src=r.url,this.element.appendChild(p)}else this.element.disableRemotePlayback=!0;this.isActiveLowLatency$.next(this.isLive$.getValue()&&this.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((p,h)=>[...p,...h.representations],[]);if(this.videoBufferManager=new na("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],jS(t)){let p=this.manifest.streams.audio.reduce((h,f)=>[...h,...f.representations],[]);this.audioBufferManager=new na("audio",this.source,p,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(sl(1e3).subscribe(p=>{if(this.element?.paused){let h=gs(this.manifestUrlString,2);this.manifestUrlString=se(this.manifestUrlString,h+1e3,2)}}));let u=()=>{this.stallWatchdogSubscription?.unsubscribe(),this.currentStallDuration$.next(0)};if(this.representationSubscription.add(ar(...VL.map(p=>ir(this.element,p))).pipe(ma(p=>this.element?Ze(this.element.buffered,this.element.currentTime*1e3):0),al(),ML(p=>{p>this.tuning.dash.bufferEmptinessTolerance&&u()})).subscribe(this.bufferLength$)),this.representationSubscription.add(ar(ir(this.element,"ended"),this.forceEnded$).subscribe(()=>{u()})),this.isLive$.getValue()){this.representationSubscription.add(this.isActiveLowLatency$.pipe(al()).subscribe(h=>rl(this.element,1))),this.representationSubscription.add(pa({bufferLength:this.bufferLength$,isActiveLowLatency:this.isActiveLowLatency$}).pipe(Hs(({bufferLength:h,isActiveLowLatency:f})=>f&&!!h)).subscribe(({bufferLength:h})=>this.liveBuffer.next(h))),this.representationSubscription.add(pa({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe(Hs(({isLive:h})=>h),ma(h=>({...h})),al((h,f)=>f.bufferLength<h.bufferLength),ma(({rtt:h,bufferLength:f,segmentServerLatency:b})=>{let g=gs(this.manifestUrlString,2);return(h/2+f+b+g)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add(pa({liveBuffer:this.liveBuffer.smoothed$,isActiveLowLatency:this.isActiveLowLatency$}).subscribe(({liveBuffer:h,isActiveLowLatency:f})=>{if(!f)return;let b=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,g=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,S=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,A=h-b,E=1;Math.abs(A)>g&&(E=1+Math.sign(A)*S),rl(this.element,E)})),this.representationSubscription.add(this.bufferLength$.subscribe(h=>{let f=0;if(h){let b=(this.element?.currentTime??0)*1e3;f=Math.min(...this.bufferManagers.map(S=>S.getLiveSegmentsToLoadState(this.manifest)?.to??b))-b}this.liveLoadBufferLength$.getValue()!==f&&this.liveLoadBufferLength$.next(f)}));let p=0;this.representationSubscription.add(pa({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(CL(1e3)).subscribe(async({liveLoadBufferLength:h,bufferLength:f})=>{if(rr(this.element),this.isUpdatingLive)return;let b=this.element.playbackRate,g=gs(this.manifestUrlString,2),S=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,A=Math.min(S,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*b),E=this.tuning.dashCmafLive.normalizedActualBufferOffset*b,k=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*b,y=isFinite(h)?h:f,R=this.isActiveLowLatency$.getValue(),B=S<=this.tuning.live.activeLiveDelay&&g===0;this.isActiveLowLatency$.next(R&&B);let F="none";if(R?F="active_low_latency":this.isLowLatency$.getValue()&&B?(this.isActiveLowLatency$.next(!0),this.bufferManagers.forEach(_=>_.proceedLowLatencyLive()),F="active_low_latency"):g!==0&&y<A?F="live_forward_buffering":y<A+k&&(F="live_with_target_offset"),isFinite(h)&&(p=h>p?h:p),F==="live_forward_buffering"||F==="live_with_target_offset"){let _=p-(A+E),U=this.normolizeLiveOffset(Math.trunc(g+_/b)),v=Math.abs(U-g),T;!h||v<=this.tuning.dashCmafLive.offsetCalculationError?T=g:U>0&&v>this.tuning.dashCmafLive.offsetCalculationError?T=U:T=0,this.manifestUrlString=se(this.manifestUrlString,T,2)}F!=="none"&&F!=="active_low_latency"&&(p=0,this.updateLive())}))}let l=ar(...this.bufferManagers.map(p=>p.fullyBuffered$)).pipe(ma(()=>this.bufferManagers.every(p=>p.fullyBuffered$.getValue()))),c=ar(...this.bufferManagers.map(p=>p.onLastSegment$)).pipe(ma(()=>this.bufferManagers.some(p=>p.onLastSegment$.getValue())));this.representationSubscription.add(ar(this.forceEnded$,pa({allBuffersFull:l,someBufferEnded:c}).pipe(Hs(({allBuffersFull:p,someBufferEnded:h})=>p&&h))).subscribe(()=>{if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(p=>!p.updating))try{this.source?.endOfStream()}catch(p){this.error$.next({id:"EndOfStream",category:Lt.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:p})}})),this.representationSubscription.add(ar(...this.bufferManagers.map(p=>p.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(p=>this.source?.addEventListener("sourceopen",p)));let d=[this.manifest.duration??0,...(0,nl.default)((0,nl.default)([...this.manifest.streams.audio,...this.manifest.streams.video],p=>p.representations),p=>{let h=[];return p.duration&&h.push(p.duration),ke(p.segmentReference)&&p.segmentReference.totalSegmentsDurationMs&&h.push(p.segmentReference.totalSegmentsDurationMs),h})];this.source.duration=Math.max(...d)/1e3,this.audioBufferManager&&jS(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=sl(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),t=>{this.error$.next({id:"GapWatchdog",category:Lt.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 Ns({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer,useEnableSubtitlesParam:e.tuning.useEnableSubtitlesParam}),this.liveBuffer=tr.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.bufferEstimator}),this.initTracerSubscription()}async seekLive(e){rr(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(){rr(this.element),this.state$.setState("running"),this.subscription.add(ar(...DL.map(e=>ir(this.element,e)),ir(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:Lt.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(ir(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(ir(this.element,"waiting").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&kt(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=LL(),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 p=this.element.currentTime*1e3;this.videoBufferManager?.maintain(p),this.audioBufferManager?.maintain(p),r.position=p}this.tracer.log("stallIntervalCallback",ha(r))};this.stallWatchdogSubscription?.unsubscribe(),this.stallWatchdogSubscription=sl(50).subscribe(e,t=>{this.error$.next({id:"StallWatchdogCallback",category:Lt.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){rr(this.element),rr(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),kt(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",ha({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=$L(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",ha(t)))}}};var Gs=class{constructor(e,t){this.fov=e,this.orientation=t}};var Qs=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 WS=`attribute vec2 a_vertex;
69
+ `})|(?<privateuse2>${e}))$`.replace(/[\s\t\n]/g,"");return new RegExp(c,"i")}var $S=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},pt=(i,e)=>{let t=i;t=(0,Yu.default)(t,"$$","$");let r={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[a,s]of(0,LS.default)(r)){let n=new RegExp(`\\$${a}(?:%0(\\d+)d)?\\$`,"g");t=(0,Yu.default)(t,n,(o,u)=>RS(s)?o:RS(u)?s:(0,MS.default)(s,parseInt(u,10),"0"))}return t},DS=(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(v=>v.textContent?.trim()??""),u=(0,CS.default)(o,0)??"",l=n.children,c=s.getAttribute("type")==="dynamic",d=s.getAttribute("availabilityStartTime"),p=d?new Date(d).getTime():void 0,h,f=s.getAttribute("mediaPresentationDuration"),b=n.getAttribute("duration"),S=s.getElementsByTagName("vk:Attrs")[0]?.getElementsByTagName("vk:XPlaybackDuration")[0].textContent;if(f)h=$S(f);else if(b){let v=$S(b);wS(v)&&(h=v)}else S&&(h=parseInt(S,10));let x=0,T=s.getAttribute("profiles")?.split(",")??[];for(let v of l){let w=v.getAttribute("id")??"id"+(x++).toString(10),U=v.getAttribute("mimeType")??"",V=v.getAttribute("codecs")??"",F=v.getAttribute("contentType")??U?.split("/")[0],E=v.getAttribute("profiles")?.split(",")??[],k=kS(v.getAttribute("lang")??"")??{},P=v.querySelector("Label")?.textContent?.trim()??void 0,H=v.querySelectorAll("Representation"),De=v.querySelector("SegmentTemplate"),et=v.querySelector("Role")?.getAttribute("value")??void 0,A=F,C={id:w,language:k.language,isDefault:et==="main",label:P,codecs:V,hdr:A==="video"&&Wu(V),mime:U,representations:[]};for(let $ of H){let Y=$.getAttribute("lang")??void 0,ve=$.getAttribute("label")??void 0,mt=$.querySelector("BaseURL")?.textContent?.trim()??"",nr=new URL(mt||u,e).toString(),Vt=$.getAttribute("mimeType")??U,B=$.getAttribute("codecs")??V??"",te;if(F==="text"){let z=$.getAttribute("id")||"",le=k.privateuse?.includes("x-auto")||z.includes("_auto"),ye=$.querySelector("SegmentTemplate");if(ye){let tt={representationId:$.getAttribute("id")??void 0,bandwidth:$.getAttribute("bandwidth")??void 0},He=parseInt($.getAttribute("bandwidth")??"",10)/1e3,rt=parseInt(ye.getAttribute("startNumber")??"",10)??1,je=parseInt(ye.getAttribute("timescale")??"",10),or=ye.querySelectorAll("SegmentTimeline S")??[],ur=ye.getAttribute("media");if(!ur)continue;let La=[],Ma=0,Ca="",lr=0,Gr=rt,se=0;for(let Ve of or){let Ot=parseInt(Ve.getAttribute("d")??"",10),we=parseInt(Ve.getAttribute("r")??"",10)||0,ft=parseInt(Ve.getAttribute("t")??"",10);se=Number.isFinite(ft)?ft:se;let Bt=Ot/je*1e3,cr=se/je*1e3;for(let Qe=0;Qe<we+1;Qe++){let bt=pt(ur,{...tt,segmentNumber:Gr.toString(10),segmentTime:(se+Qe*Ot).toString(10)}),dr=(cr??0)+Qe*Bt,Yr=dr+Bt;Gr++,La.push({time:{from:dr,to:Yr},url:bt})}se+=(we+1)*Ot,Ma+=(we+1)*Bt}lr=se/je*1e3,Ca=pt(ur,{...tt,segmentNumber:Gr.toString(10),segmentTime:se.toString(10)});let Wr={time:{from:lr,to:1/0},url:Ca},it={type:"template",baseUrl:nr,segmentTemplateUrl:ur,initUrl:"",totalSegmentsDurationMs:Ma,segments:La,nextSegmentBeyondManifest:Wr,timescale:je};te={id:z,kind:"text",segmentReference:it,profiles:[],duration:h,bitrate:He,mime:"",codecs:"",width:0,height:0,isAuto:le}}else te={id:z,isAuto:le,kind:"text",url:nr}}else{let z=$.getAttribute("contentType")??Vt?.split("/")[0]??F,le=v.getAttribute("profiles")?.split(",")??[],ye=parseInt($.getAttribute("width")??"",10),tt=parseInt($.getAttribute("height")??"",10),He=parseInt($.getAttribute("bandwidth")??"",10)/1e3,rt=$.getAttribute("frameRate")??"",je=$.getAttribute("quality")??void 0,or=rt?AS(rt):void 0,ur=$.getAttribute("id")??"id"+(x++).toString(10),La=z==="video"?`${tt}p`:z==="audio"?`${He}Kbps`:B,Ma=`${ur}@${La}`,Ca=[...T,...E,...le],lr,Gr=$.querySelector("SegmentBase"),se=$.querySelector("SegmentTemplate")??De;if(Gr){let it=$.querySelector("SegmentBase Initialization")?.getAttribute("range")??"",[Ve,Ot]=it.split("-").map(bt=>parseInt(bt,10)),we={from:Ve,to:Ot},ft=$.querySelector("SegmentBase")?.getAttribute("indexRange"),[Bt,cr]=ft?ft.split("-").map(bt=>parseInt(bt,10)):[],Qe=ft?{from:Bt,to:cr}:void 0;lr={type:"byteRange",url:nr,initRange:we,indexRange:Qe}}else if(se){let it={representationId:$.getAttribute("id")??void 0,bandwidth:$.getAttribute("bandwidth")??void 0},Ve=parseInt(se.getAttribute("timescale")??"",10),Ot=se.getAttribute("initialization")??"",we=se.getAttribute("media"),ft=parseInt(se.getAttribute("startNumber")??"",10)??1,Bt=pt(Ot,it);if(!we)throw new ReferenceError("No media attribute in SegmentTemplate");let cr=se.querySelectorAll("SegmentTimeline S")??[],Qe=[],bt=0,dr="",Yr=0;if(cr.length){let Da=ft,Oe=0;for(let pr of cr){let Ge=parseInt(pr.getAttribute("d")??"",10),_t=parseInt(pr.getAttribute("r")??"",10)||0,Va=parseInt(pr.getAttribute("t")??"",10);Oe=Number.isFinite(Va)?Va:Oe;let pn=Ge/Ve*1e3,ty=Oe/Ve*1e3;for(let Oa=0;Oa<_t+1;Oa++){let ry=pt(we,{...it,segmentNumber:Da.toString(10),segmentTime:(Oe+Oa*Ge).toString(10)}),wl=(ty??0)+Oa*pn,iy=wl+pn;Da++,Qe.push({time:{from:wl,to:iy},url:ry})}Oe+=(_t+1)*Ge,bt+=(_t+1)*pn}Yr=Oe/Ve*1e3,dr=pt(we,{...it,segmentNumber:Da.toString(10),segmentTime:Oe.toString(10)})}else if(wS(h)){let Oe=parseInt(se.getAttribute("duration")??"",10)/Ve*1e3,pr=Math.ceil(h/Oe),Ge=0;for(let _t=1;_t<pr;_t++){let Va=pt(we,{...it,segmentNumber:_t.toString(10),segmentTime:Ge.toString(10)});Qe.push({time:{from:Ge,to:Ge+Oe},url:Va}),Ge+=Oe}Yr=Ge,dr=pt(we,{...it,segmentNumber:pr.toString(10),segmentTime:Ge.toString(10)})}let ey={time:{from:Yr,to:1/0},url:dr};lr={type:"template",baseUrl:nr,segmentTemplateUrl:we,initUrl:Bt,totalSegmentsDurationMs:bt,segments:Qe,nextSegmentBeyondManifest:ey,timescale:Ve}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!z||!Vt)continue;let Wr={video:"video",audio:"audio",text:"text"}[z];if(!Wr)continue;A||=Wr,te={id:Ma,kind:Wr,segmentReference:lr,profiles:Ca,duration:h,bitrate:He,mime:Vt,codecs:B,width:ye,height:tt,fps:or,quality:je}}C.language||=Y,C.label||=ve,C.mime||=Vt,C.codecs||=B,C.hdr||=A==="video"&&Wu(B),C.representations.push(te)}A&&a[A].push(C)}return{dynamic:c,liveAvailabilityStartTime:p,duration:h,streams:a,baseUrls:o}};var Ju=D(Dr(),1);import{videoSizeToQuality as TL}from"@vkontakte/videoplayer-shared";var VS=({id:i,width:e,height:t,bitrate:r,fps:a,quality:s,streamId:n})=>{let o=(s?xt(s):void 0)??TL({width:e,height:t});return o&&{id:i,quality:o,bitrate:r,size:{width:e,height:t},fps:a,streamId:n}},OS=({id:i,bitrate:e})=>({id:i,bitrate:e}),BS=({language:i,label:e},{id:t,url:r,isAuto:a})=>({id:t,url:r,isAuto:a,type:"internal",language:i,label:e}),_S=({language:i,label:e,id:t,url:r,isAuto:a})=>({id:t,url:r,isAuto:a,type:"internal",language:i,label:e}),Xu=({id:i,language:e,label:t,codecs:r,isDefault:a})=>({id:i,language:e,label:t,codec:(0,Ju.default)(r.split("."),0),isDefault:a}),Zu=({id:i,language:e,label:t,hdr:r,codecs:a})=>({id:i,language:e,hdr:r,label:t,codec:(0,Ju.default)(a.split("."),0)}),el=i=>"url"in i,Ae=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 qr(0);this.currentSegmentLength$=new qr(0);this.onLastSegment$=new qr(!1);this.fullyBuffered$=new qr(!1);this.playingRepresentation$=new qr(void 0);this.playingRepresentationInit$=new qr(void 0);this.error$=new EL;this.gaps=[];this.subscription=new xL;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new Pe;this.switchAbortController=new Pe;this.destroyAbortController=new Pe;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=Zt(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);oe(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new Vg(this.sourceBuffer),this.subscription.add(tl(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let o,u=this.mediaSource.readyState;u!=="open"&&(o={id:`SegmentEjection_source_${u}`,category:Rt.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o??={id:"SegmentEjection",category:Rt.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n},this.error$.next(o)})),this.subscription.add(tl(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:Rt.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,Nu(this.sourceBuffer.buffered)*.8);this.bufferLimit=u;let l=Xe(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);oe(r,"No init buffer for starting representation"),oe(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=Zt(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);oe(r,`No such representation ${e}`);let a=this.segments.get(e),s=this.initData.get(e);if(Ce(s)||Ce(a)?yield this.loadInit(r,"high",!1):s instanceof Promise&&(yield s),a=this.segments.get(e),oe(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();Bs(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=Zt(this.destroyAbortController.signal,async function*(e){let t=(0,Fs.default)(e,u=>u.representations)??[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let u of this.representations.keys()){let l=t.find(p=>p.id===u);l&&this.representations.set(u,l);let c=this.representations.get(u);if(!c||!Ae(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);oe(a);let s=this.segments.get(r);oe(s,"No segments for starting representation");let n=this.initData.get(r);if(oe(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 Pe,Zt(this.switchAbortController.signal,async function*(r,a=!1){this.switchingToRepresentationId=r;let s=this.representations.get(r);oe(s,`No such representation ${r}`);let n=this.segments.get(r),o=this.initData.get(r);if(Ce(o)||Ce(n)?yield this.loadInit(s,"high",!1):o instanceof Promise&&(yield o),n=this.segments.get(r),oe(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();Bs(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 Pe,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(Ce(e)||Ce(this.downloadingRepresentationId)||Ce(this.playingRepresentationId)||Ce(this.sourceBuffer)||Bs(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),r=this.segments.get(this.downloadingRepresentationId);if(oe(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=Xe(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)&&Nu(this.sourceBuffer.buffered)>=this.bufferLimit){let l=Xe(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,Ns.default)(o,a))l="high";else{let c=(0,Ur.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&&Xe(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let u=(0,Ur.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;Bs(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,Fs.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,Fs.default)(e?.streams[this.kind],r=>r.representations)??[];for(let r of t){if(!r||!Ae(r.segmentReference))return;let a=r.segmentReference.segments.map(u=>({...u,status:"none",size:void 0})),s=this.segments.get(r.id)??[],n=(0,Ur.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;oe(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(!Ae(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=pt(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:p,to:h}},f)=>{let b=p<=r&&h>=r,g=p>r||b||f===0&&r===0,S=Math.min(this.forwardBufferTarget,this.bufferLimit),x=this.preloadOnly&&p<=r+S||h<=r+S;return(d==="none"||d==="partially_ejected"&&g&&x&&this.sourceBuffer&&!(kt(this.sourceBuffer.buffered,p)&&kt(this.sourceBuffer.buffered,h)))&&g&&x});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 p=s[d];if(n+=p.byte.to+1-p.byte.from,o+=p.time.to+1-p.time.from,p.status==="none"||p.status==="partially_ejected")u.push(p);else break}return u}async loadSegments(e,t,r="auto"){Ae(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 Zt(o,async function*(){let c=rl(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=_s(),!c)return;let d=new DataView(c),p=sa(t.mime);if(!isFinite(a.segment.time.to)){let b=t.segmentReference.timescale;a.segment.time.to=p.getChunkEndTime(d,b)}u&&a.feedingBytes&&l?await Promise.all(l):await this.sourceBufferTaskQueue.append(d,o);let{serverDataReceivedTimestamp:h,serverDataPreparedTime:f}=p.getServerLatencyTimestamps(d);h&&f&&this.currentLiveSegmentServerLatency$.next(f-h),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())Ae(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 Zt(n,async function*(){let u=rl(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),tl(window,"online").pipe(IL()).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=_s(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),na(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}prepareByteRangeFetchSegmentParams(e,t){if(Ae(t.segmentReference))throw new Error("Representation is not byte range type");let r=t.segmentReference.url,a={from:(0,Ur.default)(e,0).byte.from,to:(0,Ur.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=_s(),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:Rt.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!Ae(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=_s();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:Rt.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,Ns.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,p=d-c+1,h=c<a,f=d<=a;if(!h)continue;let b=sa(o.mime);if(l.status==="downloading"&&f){l.status="downloaded";let g=new DataView(e.buffer,e.byteOffset+c,p);await this.sourceBufferTaskQueue.append(g,s)&&!s.aborted?this.onSegmentFullyAppended(u,t):n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(l.status==="downloading"||l.status==="partially_fed")&&(u.loadedBytes=Math.min(p,a-c),u.loadedBytes>u.feedingBytes)){let g=new DataView(e.buffer,e.byteOffset+c+u.feedingBytes,u.loadedBytes-u.feedingBytes),S=u.loadedBytes===p?g:b.parseFeedableSegmentChunk(g);S?.byteLength&&(l.status="partially_fed",u.feedingBytes+=S.byteLength,await this.sourceBufferTaskQueue.append(S,s)&&!s.aborted?(u.fedBytes+=S.byteLength,u.fedBytes===p&&this.onSegmentFullyAppended(u,t)):n())}}}onSegmentFullyAppended(e,t){this.tuning.useSafariEndlessRequestBugfix&&!this.isLive&&(oe(this.sourceBuffer),kt(this.sourceBuffer.buffered,e.segment.time.from,100)&&kt(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"SafariEmptyAppendBuffer",category:Rt.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",el(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");oe(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=Ou(()=>(0,NS.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?Zt(this.destroyAbortController.signal,async function*(){let o=rl(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 p=c;this.isLive&&Ae(e.segmentReference)&&(p=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,p),u&&this.parsedInitData.set(e.id,u)}).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),r&&this.error$.next({id:"LoadInits",category:Rt.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||Ce(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:p}=u[c],h=l[l.length-1];h.to>=d?h.to=Math.max(h.to,p):l.push(u[c])}return l},o=u=>{if(s>=t)return a;a.push({...u.time}),a=n(a);let l=el(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 p of this.segments.values())for(let h of p)(0,Ns.default)(["none","partially_ejected"],h.status)&&Math.round(h.time.from)<=Math.round(l)&&Math.round(h.time.to)>=Math.round(c)&&d++;if(d===this.segments.size){let p={time:{from:l,to:c},url:"",status:"none"};o(p)}}if(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||Ce(e)?0:Xe(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){oe(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=Ou(()=>{try{this.detectGaps(e,t)}catch(r){this.error$.next({id:"GapDetection",category:Rt.WTF,message:"detectGaps threw",thrown:r})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if(Ce(this.sourceBuffer)||Ce(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 FS=i=>{let e=i.get("X-Delivery-Type"),t=i.get("X-Reused"),r=e===null?"http1":e??void 0,a=t===null?void 0:{1:!0,0:!1}[t]??void 0;return{type:r,reused:a}};import{abortable as la,assertNever as US,fromEvent as HS,merge as PL,now as ca,Subscription as AL,ValueSubject as il,flattenObject as Hr}from"@vkontakte/videoplayer-shared";var qS=i=>{let e=new URL(i);return e.searchParams.set("enable-subtitles","yes"),e.toString()};var qs=class{constructor({throughputEstimator:e,requestQuic:t,tracer:r,compatibilityMode:a=!1,useEnableSubtitlesParam:s=!1}){this.lastConnectionType$=new il(void 0);this.lastConnectionReused$=new il(void 0);this.lastRequestFirstBytes$=new il(void 0);this.abortAllController=new Pe;this.subscription=new AL;this.fetchManifest=la(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),r=e;this.requestQuic&&(r=ua(r)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(r=qS(r));let a=yield lt(r,{signal:this.abortAllController.signal}).catch(da);return a?(t.log("success",Hr({url:r,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(a.headers),a.text()):(t.error("error",Hr({url:r,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=la(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:r,onProgress: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 k=new URL(l,location.href);k.searchParams.append("bytes",`${r.from}-${r.to}`),l=k.toString();break}default:US(t)}this.requestQuic&&(l=ua(l));let p=this.abortAllController.signal,h;if(n){let k=new Pe;if(h=PL(HS(this.abortAllController.signal,"abort"),HS(n,"abort")).subscribe(()=>{try{k.abort()}catch(P){da(P)}}),this.abortAllController.signal.aborted||n.aborted)try{k.abort()}catch(P){da(P)}p=k.signal}let f=ca();d.log("startRequest",Hr({url:l,priority:s,rangeMethod:t,range:r,isLowLatency:u,requestStartedAt:f}));let b=yield lt(l,{priority:s,headers:c,signal:p}).catch(da),g=ca();if(!b)return d.error("error",{message:"No response in request"}),d.end(),h?.unsubscribe(),null;if(this.throughputEstimator?.addRawRtt(g-f),!b.ok||!b.body){h?.unsubscribe();let k=`Fetch error ${b.status}: ${b.statusText}`;return d.error("error",{message:k}),d.end(),Promise.reject(new Error(`Fetch error ${b.status}: ${b.statusText}`))}if(this.onHeadersReceived(b.headers),!a&&!o){h?.unsubscribe();let k=ca(),P={requestStartedAt:f,requestEndedAt:k,duration:k-f};return d.log("endRequest",Hr(P)),d.end(),b.arrayBuffer()}let[S,x]=b.body.tee(),T=S.getReader();o&&this.throughputEstimator?.trackStream(x,u);let R=0,v=new Uint8Array(0),w=!1,U=k=>{h?.unsubscribe(),w=!0,da(k)},V=la(p,async function*({done:k,value:P}){if(R===0&&this.lastRequestFirstBytes$.next(ca()-f),p.aborted){h?.unsubscribe();return}if(!k&&P){let H=new Uint8Array(v.length+P.length);H.set(v),H.set(P,v.length),v=H,R+=P.byteLength,a?.(new DataView(v.buffer),R),yield T?.read().then(V,U)}}.bind(this));yield T?.read().then(V,U),h?.unsubscribe();let F=ca(),E={failed:w,requestStartedAt:f,requestEndedAt:F,duration:F-f};return w?(d.error("endRequest",Hr(E)),d.end(),null):(d.log("endRequest",Hr(E)),d.end(),v.buffer)}.bind(this));this.fetchByteRangeRepresentation=la(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 p=new DataView(d,a-n,s-n+1);if(!t.validateData(p))throw new Error("Invalid media file");let h=t.parseInit(p),f=e.indexRange??t.getIndexRange(h);if(!f)throw new ReferenceError("No way to load representation index");let b;if(u)b=new DataView(d,f.from-n,f.to-f.from+1);else{let S=yield this.fetch(e.url,{range:f,priority:r,measureThroughput:!1});if(!S)return null;b=new DataView(S)}let g=t.parseSegments(b,h,f);return{init:h,dataView:new DataView(d),segments:g}}.bind(this));this.fetchTemplateRepresentation=la(this.abortAllController.signal,async function*(e,t){if(e.type!=="template")return null;let r=new URL(e.initUrl,e.baseUrl).toString(),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}=FS(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:US(a)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}},da=i=>{if(!na(i))throw i};var er=(i,e,t)=>t*e+(1-t)*i,al=(i,e)=>i.reduce((t,r)=>t+r,0)/e,jS=(i,e,t,r)=>{let a=0,s=t,n=al(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};import{isNullable as kL,ValueSubject as QS}from"@vkontakte/videoplayer-shared";var $t=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 QS(e.initial),this.debounced$=new QS(e.initial);let t=e.label??"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new ne(`raw_${t}`),this.smoothedSeries$=new ne(`smoothed_${t}`),this.reportedSeries$=new ne(`reported_${t}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,r=0;for(let o=0;o<this.pastMeasures.length;o++)this.pastMeasures[o]!==void 0&&(t+=(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)&&(kL(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 Us=class extends $t{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=er(this.slow,e,this.params.emaAlphaSlow),this.fast=er(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var Hs=class extends $t{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=al(this.pastMeasures,this.takenMeasures);this.emaSmoothed=er(this.emaSmoothed,e,this.params.emaAlpha);let r=jS(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=r?this.emaSmoothed:t}};var js=class extends $t{constructor(t){super(t);this.furtherValues=[];this.currentTopExtremumValue=0;this.extremumInterval=t.extremumInterval}next(t){this.currentTopExtremumValue<=t?(this.currentTopExtremumValue=t,this.furtherValues=[]):this.furtherValues.length===this.extremumInterval?(super.next(this.currentTopExtremumValue),this.currentTopExtremumValue=t,this.furtherValues=[]):this.furtherValues.push(t)}updateSmoothedValue(t){this.smoothed=this.smoothed?er(this.smoothed,t,this.params.emaAlpha):t}};var tr=class{static getSmoothedValue(e,t,r){return r.type==="TwoEma"?new Us({initial:e,emaAlphaSlow:r.emaAlphaSlow,emaAlphaFast:r.emaAlphaFast,changeThreshold:r.changeThreshold,fastDirection:t,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"}):new Hs({initial:e,emaAlpha:r.emaAlpha,basisTrendChangeCount:r.basisTrendChangeCount,changeThreshold:r.changeThreshold,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"})}static getLiveBufferSmoothedValue(e,t){return new js({initial:e,label:"liveEdgeDelay",...t})}};var sl=(i,e)=>{i&&i.playbackRate!==e&&(i.playbackRate=e)};import{isNullable as wL,ValueSubject as RL}from"@vkontakte/videoplayer-shared";var pa=class i{constructor(e,t){this.currentRepresentation$=new RL(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(!wL(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&&Ae(t.segmentReference))}};var BL=["timeupdate","progress","play","seeked","stalled","waiting"],_L=["timeupdate","progress","loadeddata","playing","seeked"];var Gs=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new zS;this.representationSubscription=new zS;this.state$=new L("none");this.currentVideoRepresentation$=new W(void 0);this.currentVideoRepresentationInit$=new W(void 0);this.currentAudioRepresentation$=new W(void 0);this.currentVideoSegmentLength$=new W(0);this.currentAudioSegmentLength$=new W(0);this.error$=new YS;this.lastConnectionType$=new W(void 0);this.lastConnectionReused$=new W(void 0);this.lastRequestFirstBytes$=new W(void 0);this.currentLiveTextRepresentation$=new W(null);this.isLive$=new W(!1);this.liveDuration$=new W(0);this.liveAvailabilityStartTime$=new W(void 0);this.bufferLength$=new W(0);this.liveLatency$=new W(void 0);this.liveLoadBufferLength$=new W(0);this.livePositionFromPlayer$=new W(0);this.isLowLatency$=new W(!1);this.isActiveLowLatency$=new W(!1);this.currentStallDuration$=new W(0);this.videoLastDataObtainedTimestamp$=new W(0);this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.liveLastSeekOffset=0;this.forceEnded$=new YS;this.gapWatchdogActive=!1;this.destroyController=new Pe;this.initManifest=nl(this.destroyController.signal,async function*(e,t,r){this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=ae(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:Lt.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=nl(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:Lt.NETWORK,message:"Failed to load manifest",thrown:n})});if(!e)return null;let t=null;try{t=DS(e??"",this.manifestUrlString)}catch(n){let o=Rg(e)??{id:"ManifestParsing",category:Lt.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)&&ct()?.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:p})=>r(n,d,p)),l=new Set(u.map(({codecs:d})=>d)),c=og(l);if(c&&(a[n]=u.filter(({codecs:d})=>d.startsWith(c))),n==="video"){let d=this.tuning.preferHDR,p=a.video.some(f=>f.hdr),h=a.video.some(f=>!f.hdr);ML.isHDR&&d&&p?a.video=a.video.filter(f=>f.hdr):h&&(a.video=a.video.filter(f=>!f.hdr))}}let s={...t,streams:a};return this.tracer.log("updateManifestEnd",ma(s)),s}.bind(this));this.initRepresentations=nl(this.destroyController.signal,async function*(e,t,r){this.tracer.log("initRepresentationsStart",ma({initialVideo:e,initialAudio:t,sourceHls:r})),rr(this.manifest),rr(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let a=p=>{this.representationSubscription.add(ir(p,"error").pipe(Qs(h=>!!this.element?.played.length)).subscribe(h=>{this.error$.next({id:"VideoSource",category:Lt.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:h})}))};this.source=this.tuning.useManagedMediaSource?eg():new MediaSource;let s=document.createElement("source");if(a(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),this.tuning.useManagedMediaSource&&Ls())if(r){let p=document.createElement("source");a(p),p.type="application/x-mpegurl",p.src=r.url,this.element.appendChild(p)}else this.element.disableRemotePlayback=!0;this.isActiveLowLatency$.next(this.isLive$.getValue()&&this.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((p,h)=>[...p,...h.representations],[]);if(this.videoBufferManager=new oa("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],WS(t)){let p=this.manifest.streams.audio.reduce((h,f)=>[...h,...f.representations],[]);this.audioBufferManager=new oa("audio",this.source,p,n),this.bufferManagers.push(this.audioBufferManager)}pa.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new pa(this.manifest.streams.text,n)),this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$)),this.representationSubscription.add(ul(1e3).subscribe(p=>{if(this.element?.paused){let h=Ss(this.manifestUrlString,2);this.manifestUrlString=ae(this.manifestUrlString,h+1e3,2)}}));let u=()=>{this.stallWatchdogSubscription?.unsubscribe(),this.currentStallDuration$.next(0)};if(this.representationSubscription.add(ar(..._L.map(p=>ir(this.element,p))).pipe(fa(p=>this.element?Xe(this.element.buffered,this.element.currentTime*1e3):0),ol(),VL(p=>{p>this.tuning.dash.bufferEmptinessTolerance&&u()})).subscribe(this.bufferLength$)),this.representationSubscription.add(ar(ir(this.element,"ended"),this.forceEnded$).subscribe(()=>{u()})),this.isLive$.getValue()){this.representationSubscription.add(this.isActiveLowLatency$.pipe(ol()).subscribe(h=>sl(this.element,1))),this.representationSubscription.add(ha({bufferLength:this.bufferLength$,isActiveLowLatency:this.isActiveLowLatency$}).pipe(Qs(({bufferLength:h,isActiveLowLatency:f})=>f&&!!h)).subscribe(({bufferLength:h})=>this.liveBuffer.next(h))),this.representationSubscription.add(ha({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe(Qs(({isLive:h})=>h),fa(h=>({...h})),ol((h,f)=>f.bufferLength<h.bufferLength),fa(({rtt:h,bufferLength:f,segmentServerLatency:b})=>{let g=Ss(this.manifestUrlString,2);return(h/2+f+b+g)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add(ha({liveBuffer:this.liveBuffer.smoothed$,isActiveLowLatency:this.isActiveLowLatency$}).subscribe(({liveBuffer:h,isActiveLowLatency:f})=>{if(!f)return;let b=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,g=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,S=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,x=h-b,T=1;Math.abs(x)>g&&(T=1+Math.sign(x)*S),sl(this.element,T)})),this.representationSubscription.add(this.bufferLength$.subscribe(h=>{let f=0;if(h){let b=(this.element?.currentTime??0)*1e3;f=Math.min(...this.bufferManagers.map(S=>S.getLiveSegmentsToLoadState(this.manifest)?.to??b))-b}this.liveLoadBufferLength$.getValue()!==f&&this.liveLoadBufferLength$.next(f)}));let p=0;this.representationSubscription.add(ha({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(OL(1e3)).subscribe(async({liveLoadBufferLength:h,bufferLength:f})=>{if(rr(this.element),this.isUpdatingLive)return;let b=this.element.playbackRate,g=Ss(this.manifestUrlString,2),S=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,x=Math.min(S,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*b),T=this.tuning.dashCmafLive.normalizedActualBufferOffset*b,R=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*b,v=isFinite(h)?h:f,w=this.isActiveLowLatency$.getValue(),U=S<=this.tuning.live.activeLiveDelay&&g===0;this.isActiveLowLatency$.next(w&&U);let V="none";if(w?V="active_low_latency":this.isLowLatency$.getValue()&&U?(this.isActiveLowLatency$.next(!0),this.bufferManagers.forEach(F=>F.proceedLowLatencyLive()),V="active_low_latency"):g!==0&&v<x?V="live_forward_buffering":v<x+R&&(V="live_with_target_offset"),isFinite(h)&&(p=h>p?h:p),V==="live_forward_buffering"||V==="live_with_target_offset"){let F=p-(x+T),E=this.normolizeLiveOffset(Math.trunc(g+F/b)),k=Math.abs(E-g),P;!h||k<=this.tuning.dashCmafLive.offsetCalculationError?P=g:E>0&&k>this.tuning.dashCmafLive.offsetCalculationError?P=E:P=0,this.manifestUrlString=ae(this.manifestUrlString,P,2)}V!=="none"&&V!=="active_low_latency"&&(p=0,this.updateLive())}))}let l=ar(...this.bufferManagers.map(p=>p.fullyBuffered$)).pipe(fa(()=>this.bufferManagers.every(p=>p.fullyBuffered$.getValue()))),c=ar(...this.bufferManagers.map(p=>p.onLastSegment$)).pipe(fa(()=>this.bufferManagers.some(p=>p.onLastSegment$.getValue())));this.representationSubscription.add(ar(this.forceEnded$,ha({allBuffersFull:l,someBufferEnded:c}).pipe(Qs(({allBuffersFull:p,someBufferEnded:h})=>p&&h))).subscribe(()=>{if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(p=>!p.updating))try{this.source?.endOfStream()}catch(p){this.error$.next({id:"EndOfStream",category:Lt.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:p})}})),this.representationSubscription.add(ar(...this.bufferManagers.map(p=>p.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(p=>this.source?.addEventListener("sourceopen",p)));let d=[this.manifest.duration??0,...(0,ll.default)((0,ll.default)([...this.manifest.streams.audio,...this.manifest.streams.video],p=>p.representations),p=>{let h=[];return p.duration&&h.push(p.duration),Ae(p.segmentReference)&&p.segmentReference.totalSegmentsDurationMs&&h.push(p.segmentReference.totalSegmentsDurationMs),h})];this.source.duration=Math.max(...d)/1e3,this.audioBufferManager&&WS(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=ul(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),t=>{this.error$.next({id:"GapWatchdog",category:Lt.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 qs({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer,useEnableSubtitlesParam:e.tuning.useEnableSubtitlesParam}),this.liveBuffer=tr.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.bufferEstimator}),this.initTracerSubscription()}async seekLive(e){rr(this.element);let t=this.normolizeLiveOffset(e);this.isActiveLowLatency$.next(this.isLowLatency$.getValue()&&t===0),this.liveLastSeekOffset=t,this.manifestUrlString=ae(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(){rr(this.element),this.state$.setState("running"),this.subscription.add(ar(...BL.map(e=>ir(this.element,e)),ir(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:Lt.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(ir(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(ir(this.element,"waiting").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&kt(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=DL(),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 p=this.element.currentTime*1e3;this.videoBufferManager?.maintain(p),this.audioBufferManager?.maintain(p),r.position=p}this.tracer.log("stallIntervalCallback",ma(r))};this.stallWatchdogSubscription?.unsubscribe(),this.stallWatchdogSubscription=ul(50).subscribe(e,t=>{this.error$.next({id:"StallWatchdogCallback",category:Lt.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){rr(this.element),rr(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),kt(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",ma({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=CL(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",ma(t)))}}};var Ws=class{constructor(e,t){this.fov=e,this.orientation=t}};var Ys=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 KS=`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 YS=`#ifdef GL_ES
80
+ `;var JS=`#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 Ws=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 Gs(this.params.fov,this.params.orientation),this.cameraRotationManager=new Qs(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(WS,this.gl.VERTEX_SHADER),r=this.createShader(YS,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,p=t+a;return[s,n,o,u,l,c,d,p]}updateTextureMappingBuffer(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([...this.calculateTexturePosition()]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}updateFrameSize(){this.frameWidth=this.sourceVideoElement.videoWidth,this.frameHeight=this.sourceVideoElement.videoHeight}createCanvas(){let e=document.createElement("canvas");return e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e}};import{isNullable as _L,now as zS,Subscription as NL,filter as FL,combine as KS,ValueSubject as JS,isNonNullable as qL}from"@vkontakte/videoplayer-shared";var ol=class{constructor(){this.isSeeked$=new JS(!1);this.isBuffering$=new JS(!1);this.currentStallsCount=0;this.maxQualityLimit=void 0;this.lastUniqueVideoTrackSelectedTimestamp=0;this.predictedThroughputWithoutData=0;this.subscription=new NL}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(KS({isBuffering:this.isBuffering$,isSeeked:this.isSeeked$}).pipe(FL(({isBuffering:t,isSeeked:r})=>t&&!r)).subscribe(()=>{this.currentStallsCount++})),this.subscription.add(KS({currentStallDuration:this.currentStallDuration$,isSeeked:this.isSeeked$}).subscribe(({currentStallDuration:t,isSeeked:r})=>{if(_L(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=zS(),p=n&&this.currentStallsCount>=n,h=a&&!r&&d-this.lastUniqueVideoTrackSelectedTimestamp>=a+u&&t>=a,f=s&&d-this.lastUniqueVideoTrackSelectedTimestamp>=s+u&&d-c>=s+u&&t>=s;(p||h||f)&&(window.clearTimeout(this.qualityRestrictionTimer),this.maxQualityLimit=this.lastUniqueVideoTrackSelected.quality,qL(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=zS(),this.currentStallsCount=0)}destroy(){window.clearTimeout(this.qualityRestrictionTimer),this.subscription.unsubscribe()}},XS=ol;var sr=class{constructor(e){this.subscription=new KL;this.videoState=new $("stopped");this.elementSize$=new JL(void 0);this.textTracksManager=new Le;this.droppedFramesManager=new Ps;this.stallsManager=new XS;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new Ei;this.audioTrackSwitchHistory=new Ei;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(a.state==="requested"&&r?.to!=="paused"&&e!=="stopped"&&t!=="stopped"){let n=this.liveOffset?.getTotalPausedTime()??0;this.seek(a.position-n,a.forcePrecise)}if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.player.stop(),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),I(this.params.desiredState.playbackState,"stopped",!0));return}switch(e){case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();return;case"ready":t==="paused"?(this.videoState.setState("paused"),I(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):r?.to==="ready"&&I(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.liveOffset?.pause(),this.video.paused?this.videoState.setState("paused"):this.video.pause()):r?.to==="playing"&&I(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.liveOffset?this.liveOffset.getTotalOffset()/1e3<Math.abs(this.params.output.duration$.getValue())?(this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(0,!1):this.playIfAllowed()):r?.to==="paused"&&I(this.params.desiredState.playbackState,"paused");return;default:return jL(e)}}};this.init3DScene=e=>{if(this.scene3D)return;this.scene3D=new Ws(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=pe(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(Z(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 js({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode,tracer:this.tracer}),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params,r=fe(this.video),a=this.constructor.name,s=o=>{e.error$.next({id:a,category:ul.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(ZS(c=>!!c.length),tv()).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(ll(c=>c.to.state!=="none"),ba());this.stallsManager.connect({isSeeked$:n,currentStallDuration$:this.player.currentStallDuration$.pipe(ba()),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(ZS(ev),tv()),e.firstBytesEvent$),s(this.videoState.stateChangeEnded$.pipe(ll(c=>c.to)),this.params.output.playbackState$),this.subscription.add(r.seeked$.subscribe(e.seekedEvent$,a)),this.subscription.add(Je(this.video,t.isLooped,a)),this.subscription.add(me(this.video,t.volume,r.volumeState$,a)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,a)),this.subscription.add($e(this.video,t.playbackRate,r.playbackRateState$,a)),s(zL(this.video),this.elementSize$),s(Ce(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),I(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},a)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),I(t.playbackState,"paused")},a)).add(r.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},a)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:c})=>{if(c==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let d=this.player.getStreams();if(GL(d,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let h=[];for(let f of d.audio){h.push(zu(f));let b=[];for(let g of f.representations){let S=CS(g);b.push(S),this.audioTracksMap.set(S,{stream:f,representation:g})}this.audioStreamsMap.set(f,b)}this.params.output.availableAudioStreams$.next(h)}let p=[];for(let h of d.video){p.push(Ku(h));let f=[];for(let b of h.representations){let g=MS({...b,streamId:h.id});g&&(f.push(g),this.videoTracksMap.set(g,{stream:h,representation:b}))}this.videoStreamsMap.set(h,f)}if(this.params.output.availableVideoStreams$.next(p),this.textTracksManager)for(let h of d.text)for(let f of h.representations){let b=DS(h,f);this.textTracksMap.set(b,{stream:h,representation:f})}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:ul.WTF,message:"Switching representations threw",thrown:c});this.subscription.add(Ys(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$,WL(this.video,"progress")).subscribe(()=>{let c=this.player.state$.getState(),d=this.player.state$.getTransition();if(!(0,rv.default)(["manifest_ready","running"],c)||d)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let p=this.selectVideoAudioRepresentations();if(!p)return;let[h,f]=p,b=[...this.videoTracksMap.keys()].find(S=>this.videoTracksMap.get(S)?.representation.id===h.id);ev(b)&&(this.stallsManager.lastVideoTrackSelected=b);let g=this.params.desiredState.autoVideoTrackLimits.getTransition();if(g&&this.params.output.autoVideoTrackLimits$.next(g.to),c==="manifest_ready")this.player.initRepresentations(h.id,f?.id,this.params.sourceHls);else if(this.player.switchRepresentation("video",h.id).catch(o),f){let S=!!t.audioStream.getTransition();this.player.switchRepresentation("audio",f.id,S).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(ba()).subscribe(c=>{let d=[...this.videoTracksMap.entries()].find(([,{representation:b}])=>b.id===c);if(!d){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[p,{stream:h}]=d,f=this.params.desiredState.videoStream.getTransition();f&&f.to&&f.to.id===h.id&&this.params.desiredState.videoStream.setState(f.to),e.currentVideoTrack$.next(p),e.currentVideoStream$.next(Ku(h))},a)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(ba()).subscribe(c=>{let d=[...this.audioTracksMap.entries()].find(([,{representation:b}])=>b.id===c);if(!d){e.currentAudioStream$.next(void 0);return}let[p,{stream:h}]=d,f=this.params.desiredState.audioStream.getTransition();f&&f.to&&f.to.id===h.id&&this.params.desiredState.audioStream.setState(f.to),e.currentAudioStream$.next(zu(h))},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(ll(({to:c})=>c==="ready"),ba());this.subscription.add(Ys(u,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$).subscribe(()=>{let c=t.autoVideoTrackSwitching.getState(),p=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:c?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(p)})),this.subscription.add(Ys(u,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let l=Ys(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,YL(["init"])).pipe(QL(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:R})=>R===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:R})=>R===u.id),c=l&&this.videoStreamsMap.get(l);if(!c)return;let d=Ze(this.video.buffered,this.video.currentTime*1e3),p=r?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,h=Math.min(d/Math.min(p,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),f=e.audioStream.getState()??(this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0),b=[...this.audioStreamsMap.keys()].find(({id:R})=>R===f?.id)??this.audioStreamsMap.keys().next().value,g=0;if(b){if(n&&!r){let R=Ts(n,c,this.audioStreamsMap.get(b)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);g=Math.max(g,R?.bitrate??-1/0)}if(o){let R=Ts(o,c,this.audioStreamsMap.get(b)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);g=Math.max(g,R?.bitrate??-1/0)}}let S=At(c,{container:this.elementSize$.getValue(),estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:g,forwardBufferHealth:h,current:o,visible:this.params.output.elementVisible$.getValue(),history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,stallsVideoMaxQualityLimit:this.stallsManager.videoMaxQualityLimit,stallsPredictedThroughput:this.stallsManager.predictedThroughput,abrLogger:this.params.dependencies.abrLogger}),A=r?S??n:n??S,E=b&&mb(A,c,this.audioStreamsMap.get(b)??[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:h,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),k=this.videoTracksMap.get(A)?.representation,y=E&&this.audioTracksMap.get(E)?.representation;if(k&&y)return[k,y];if(k&&!y&&this.audioTracksMap.size===0)return[k,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){be(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.liveOffset?.pause(),this.videoState.setState("paused"),I(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:ul.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),he(this.video),this.tracer.end()}};var ga=class extends sr{subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:r}=this.getProviderSubscriptionInfo();r(t.timeUpdate$,e.position$),r(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}};import{combine as iv,interval as XL,map as av}from"@vkontakte/videoplayer-shared";var Sa=class extends sr{constructor(e){super(e),this.liveOffset=new ot,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(av(s=>s.to)).subscribe(this.player.isLowLatency$)).add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(iv({interval:XL(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(iv({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(av(({liveBufferTime:s,liveAvailabilityStartTime:n})=>s&&n?s+n:void 0)).subscribe(e.liveTime$)).add(this.player.currentLiveTextRepresentation$.subscribe(s=>{if(s){let n=VS(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 nv=C(bs(),1);import{assertNever as va,assertNonNullable as sv,debounce as ZL,ErrorCategory as zs,filter as eM,isNonNullable as tM,isNullable as rM,map as Ks,merge as iM,Observable as aM,observableFrom as sM,Subscription as nM,videoSizeToQuality as oM}from"@vkontakte/videoplayer-shared";var He={};var jr=(i,e)=>new aM(t=>{let r=(a,s)=>t.next(s);return i.on(e,r),()=>i.off(e,r)}),ya=class{constructor(e){this.subscription=new nM;this.videoState=new $("initializing");this.textTracksManager=new Le;this.trackLevels=new Map;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),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:va(e)}break;case"ready":switch(e){case"stopped":this.prepare();break;case"ready":case"playing":case"paused":break;default:va(e)}break;case"playing":switch(e){case"playing":break;case"stopped":this.prepare();break;case"ready":case"paused":this.playIfAllowed();break;default:va(e)}break;case"paused":switch(e){case"paused":break;case"stopped":this.prepare();break;case"ready":this.videoState.setState("paused"),I(this.params.desiredState.playbackState,"paused");break;case"playing":this.pause();break;default:va(e)}break;default:va(t)}};this.video=pe(e.container,e.tuning),this.params=e,this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Z(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),he(this.video)}loadHlsJs(){let e=!1,t=a=>{e||this.params.output.error$.next({id:a==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:zs.NETWORK,message:"Failed to load Hls.js",thrown:a}),e=!0},r=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);(0,nv.default)(import("hls.js").then(a=>{e||(He.Hls=a.default,He.Events=a.default.Events,this.init())},t),()=>{window.clearTimeout(r),e=!0})}init(){sv(He.Hls,"hls.js not loaded"),this.hls=new He.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState("stopped")}subscribe(){sv(He.Events,"hls.js not loaded");let{desiredState:e,output:t}=this.params,r=l=>{t.error$.next({id:"HlsJsProvider",category:zs.WTF,message:"HlsJsProvider internal logic error",thrown:l})},a=fe(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(Je(this.video,e.isLooped,r)),this.subscription.add(me(this.video,e.volume,a.volumeState$,r)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add($e(this.video,e.playbackRate,a.playbackRateState$,r)),s(Ce(this.video),t.elementVisible$),s(this.videoState.stateChangeEnded$.pipe(Ks(l=>l.to)),this.params.output.playbackState$),this.subscription.add(jr(this.hls,He.Events.ERROR).subscribe(l=>{l.fatal&&t.error$.next({id:["HlsJsFatal",l.type,l.details].join("_"),category:zs.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"),I(e.playbackState,"playing")},r)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),I(e.playbackState,"paused")},r)).add(a.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),s(jr(this.hls,He.Events.MANIFEST_PARSED).pipe(Ks(({levels:l})=>l.reduce((c,d)=>{let p=d.name||d.height.toString(10),{width:h,height:f}=d,b=xt(d.attrs.QUALITY??"")??oM({width:h,height:f});if(!b)return c;let g=d.attrs["FRAME-RATE"]?parseFloat(d.attrs["FRAME-RATE"]):void 0,S={id:p.toString(),quality:b,bitrate:d.bitrate/1e3,size:{width:h,height:f},fps:g};return this.trackLevels.set(p,{track:S,level:d}),c.push(S),c},[]))),t.availableVideoTracks$),s(jr(this.hls,He.Events.MANIFEST_PARSED),l=>{if(l.subtitleTracks.length>0){let c=[];for(let d of l.subtitleTracks){let p=d.name,h=d.attrs.URI||"",f=d.lang;c.push({id:p,url:h,language:f,type:"internal"})}e.internalTextTracks.startTransitionTo(c)}}),s(jr(this.hls,He.Events.LEVEL_LOADING).pipe(Ks(({url:l})=>Z(l))),t.hostname$),s(jr(this.hls,He.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(Tt(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=jr(this.hls,He.Events.LEVEL_SWITCHED).pipe(Ks(({level:l})=>n(this.hls.levels[l])));o.pipe(eM(tM)).subscribe(t.currentVideoTrack$,r),this.subscription.add(Tt(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel]),l=>{if(rM(l))return;let c=this.trackLevels.get(l.id)?.level;if(!c)return;let d=this.hls.levels.indexOf(c),p=this.hls.currentLevel,h=this.hls.levels[p];!h||c.bitrate>h.bitrate?this.hls.nextLevel=d:(this.hls.loadLevel=d,this.hls.loadLevel=d)},{changed$:o,onError:r})),s(a.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);let u=iM(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,sM(["init"])).pipe(ZL(0));this.subscription.add(u.subscribe(this.syncPlayback,r))}prepare(){this.videoState.startTransitionTo("ready"),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}async playIfAllowed(){this.videoState.startTransitionTo("playing"),await be(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:zs.DOM,thrown:t}))||(this.videoState.setState("paused"),I(this.params.desiredState.playbackState,"paused",!0))}pause(){this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}stop(){this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.hls.stopLoad(),this.hls.detachMedia(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState("stopped"),I(this.params.desiredState.playbackState,"stopped",!0)}};var ov="X-Playback-Duration",cl=async i=>{let e=await lt(i),t=await e.text(),r=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t)?.[1];return r?parseInt(r,10):e.headers.has(ov)?parseInt(e.headers.get(ov),10):void 0};import{assertNever as hM,combine as mM,debounce as fM,ErrorCategory as Xs,filter as bM,filterChanged as gM,isNonNullable as lv,isNullable as Zs,map as cv,merge as SM,observableFrom as vM,Subscription as yM,ValueSubject as hl,VideoQuality as TM}from"@vkontakte/videoplayer-shared";var pl=C(So(),1);import{videoSizeToQuality as uM,getExponentialDelay as lM}from"@vkontakte/videoplayer-shared";var cM=i=>{let e=null;if(i.QUALITY&&(e=xt(i.QUALITY)),!e&&i.RESOLUTION){let[t,r]=i.RESOLUTION.split("x").map(a=>parseInt(a,10));e=uM({width:t,height:r})}return e??null},dM=(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,pl.default)(o[1].split(",").map(g=>g.split("="))),c=l.QUALITY??`stream-${l.BANDWIDTH}`,d=cM(l),p;l.BANDWIDTH&&(p=parseInt(l.BANDWIDTH,10)/1e3||void 0),!p&&l["AVERAGE-BANDWIDTH"]&&(p=parseInt(l["AVERAGE-BANDWIDTH"],10)/1e3||void 0);let h=l["FRAME-RATE"]?parseFloat(l["FRAME-RATE"]):void 0,f;if(l.RESOLUTION){let[g,S]=l.RESOLUTION.split("x").map(A=>parseInt(A,10));g&&S&&(f={width:g,height:S})}let b=new URL(t[++s],e).toString();d&&r.push({id:c,quality:d,url:b,bandwidth:p,size:f,fps:h})}if(u){let l=(0,pl.default)(u[1].split(",").map(h=>h.split("=")).map(([h,f])=>[h,f.replace(/^"|"$/g,"")])),c=l.URI?.replace(/playlist$/,"subtitles.vtt"),d=l.LANGUAGE,p=l.NAME;c&&d&&a.push({type:"internal",id:d,label:p,language:d,url:c,isAuto:!1})}}}if(!r.length)throw new Error("Empty manifest");return{qualityManifests:r,textTracks:a}},pM=i=>new Promise(e=>{setTimeout(()=>{e()},i)}),dl=0,uv=async(i,e=i,t)=>{let a=await(await lt(i)).text();dl+=1;try{let{qualityManifests:s,textTracks:n}=dM(a,e);return{qualityManifests:s,textTracks:n}}catch{if(dl<=t.manifestRetryMaxCount)return await pM(lM(dl-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),uv(i,e,t)}return{qualityManifests:[],textTracks:[]}},Js=uv;var Ta=class{constructor(e){this.subscription=new yM;this.videoState=new $("stopped");this.textTracksManager=new Le;this.manifests$=new hl([]);this.liveOffset=new ot;this.manifestStartTime$=new hl(void 0);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),r=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(r==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),I(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let 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"?I(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),I(this.params.desiredState.playbackState,"paused")):r==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":r==="paused"?(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.video.paused?this.videoState.setState("paused"):this.video.pause()):a?.to==="playing"&&I(this.params.desiredState.playbackState,"playing");return;case"paused":if(r==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let 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"&&(I(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return hM(t)}};this.params=e,this.video=pe(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:TM.INVARIANT,url:this.params.source.url},Js(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:Xs.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),this.manifests$.next([this.masterManifest,...t])},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:Xs.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(Z(this.params.source.url)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.maxSeekBackTime$=new hl(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:Xs.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},a=fe(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(me(this.video,t.volume,a.volumeState$,r)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add($e(this.video,t.playbackRate,a.playbackRateState$,r)),s(Ce(this.video),e.elementVisible$),this.textTracksManager.connect(this.video,t,e),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState("playing"),I(t.playbackState,"playing")},r)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),I(t.playbackState,"paused")},r)).add(a.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.subscription.add(this.maxSeekBackTime$.pipe(gM(),cv(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&&lv(l.to)){let d=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let p=this.manifests$.getValue().find(h=>h.id===d);p&&(this.params.output.currentVideoTrack$.next(p),this.params.output.hostname$.next(Z(p.url)))}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o&&o.state==="requested"&&this.seek(o.position)},r)),this.subscription.add(a.loadedData$.subscribe(()=>{let o=this.video?.getStartDate?.()?.getTime();this.manifestStartTime$.next(o||void 0)},r)),this.subscription.add(mM({startTime:this.manifestStartTime$.pipe(bM(lv)),currentTime:a.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),r)),this.subscription.add(this.manifests$.pipe(cv(o=>o.map(({id:u,quality:l,size:c,bandwidth:d,fps:p})=>({id:u,quality:l,size:c,fps:p,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,r));let n=SM(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,vM(["init"])).pipe(fM(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),he(this.video)}prepare(){let e=this.selectManifest();if(Zs(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(),cl(n).then(o=>{if(!Zs(o))this.maxSeekBackTime$.next(o);else{let u=this.params.source.maxSeekBackTime??this.maxSeekBackTime$.getValue();if(Zs(u)||!isFinite(u))try{lt(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();cl(d).then(p=>{Zs(p)||this.maxSeekBackTime$.next(p)})}})}catch{}}})}playIfAllowed(){be(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),I(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Xs.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,r=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(r),this.params.output.position$.next(-r/1e3),this.params.output.seekedEvent$.next()}};import{assertNever as IM,debounce as EM,ErrorCategory as ml,fromEvent as fl,isNonNullable as xM,isNullable as PM,map as dv,merge as pv,observableFrom as hv,Subscription as AM,ValueSubject as kM,VideoQuality as wM,clientChecker as RM}from"@vkontakte/videoplayer-shared";var Ia=class{constructor(e){this.subscription=new AM;this.videoState=new $("stopped");this.textTracksManager=new Le;this.manifests$=new kM([]);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),r=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(r==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),I(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let 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"?I(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),I(this.params.desiredState.playbackState,"paused")):r==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":r==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):a?.to==="playing"&&I(this.params.desiredState.playbackState,"playing");return;case"paused":r==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):a?.to==="paused"&&I(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return IM(t)}};this.params=e,this.video=pe(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:wM.INVARIANT,url:this.params.source.url},this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Z(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),Js(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:ml.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:ml.WTF,message:"HlsProvider internal logic error",thrown:o})},a=fe(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(dv(o=>o.to)),this.params.output.playbackState$),this.subscription.add(Je(this.video,t.isLooped,r)),this.subscription.add(me(this.video,t.volume,a.volumeState$,r)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add($e(this.video,t.playbackRate,a.playbackRateState$,r)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState("playing"),I(t.playbackState,"playing")},r)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),I(t.playbackState,"paused")},r)).add(a.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},r).add(a.loadedMetadata$.subscribe(()=>{let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&xM(l.to)){let h=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let f=this.manifests$.getValue().find(b=>b.id===h);f&&(this.params.output.currentVideoTrack$.next(f),this.params.output.hostname$.next(Z(f.url)))}let d=this.params.desiredState.playbackRate.getState(),p=this.params.output.element$.getValue()?.playbackRate;if(d!==p){let h=this.params.output.element$.getValue();h&&(this.params.desiredState.playbackRate.setState(d),h.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(dv(o=>o.map(({id:u,quality:l,size:c,bandwidth:d,fps:p})=>({id:u,quality:l,size:c,fps:p,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,r)),!RM.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add(pv(fl(o,"addtrack"),fl(o,"removetrack"),fl(o,"change"),hv(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},r))}let n=pv(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,hv(["init"])).pipe(EM(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),he(this.video)}prepare(){let e=this.selectManifest();if(PM(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(){be(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),I(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:ml.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};var gv=C(Ir(),1),Ea=C(vi(),1);import{assertNever as $M,assertNonNullable as mv,debounce as LM,ErrorCategory as fv,isHigher as MM,isHigherOrEqual as CM,isInvariantQuality as bv,isLowerOrEqual as DM,isNonNullable as VM,merge as BM,observableFrom as OM,Subscription as _M,map as NM}from"@vkontakte/videoplayer-shared";var xa=class{constructor(e){this.subscription=new _M;this.videoState=new $("stopped");this.trackUrls={};this.textTracksManager=new Le;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),I(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let s=this.params.desiredState.autoVideoTrackLimits.getTransition(),n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.seekState.getState();if(s&&e!=="ready"&&!n){this.handleQualityLimitTransition(s.to.max);return}if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(n){let{currentTime: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"?I(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),I(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):r?.to==="playing"&&I(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):r?.to==="paused"&&I(this.params.desiredState.playbackState,"paused");return;default:return $M(e)}};this.params=e,this.video=pe(e.container,e.tuning),this.params.output.element$.next(this.video),(0,gv.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,Ea.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:fv.WTF,message:"MpegProvider internal logic error",thrown:o})},a=fe(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(NM(o=>o.to)),this.params.output.playbackState$),this.subscription.add(Je(this.video,t.isLooped,r)),this.subscription.add(me(this.video,t.volume,a.volumeState$,r)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add($e(this.video,t.playbackRate,a.playbackRateState$,r)),s(Ce(this.video),e.elementVisible$),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState("playing"),I(t.playbackState,"playing")},r)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),I(t.playbackState,"paused")},r)).add(a.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready");let o=this.params.desiredState.videoTrack.getTransition();if(o&&VM(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=BM(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,OM(["init"])).pipe(LM(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.params.output.element$.next(void 0),he(this.video)}prepare(){let e=this.params.desiredState.videoTrack.getState()?.id;mv(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];mv(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=oa(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(Z(t))}playIfAllowed(){be(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),I(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:fv.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,Ea.default)(this.trackUrls).find(o=>!bv(o.track.quality)&&DM(o.track.quality,e))?.track,s=this.params.desiredState.videoTrack.getState()?.id,n=this.trackUrls[s??"0"]?.track;if(a&&n&&CM(n.quality,a.quality)&&(t=a),!t){let o=(0,Ea.default)(this.trackUrls).filter(l=>!bv(l.track.quality)&&MM(l.track.quality,e)),u=o.length;u&&(t=o[u-1].track)}t&&(r=t.quality)}else if(!e){let a=(0,Ea.default)(this.trackUrls).map(s=>s.track);t=At(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})}};import{assertNever as vv,debounce as HM,merge as yv,observableFrom as jM,Subscription as GM,map as Tv,ValueSubject as QM,ErrorCategory as gl,VideoQuality as WM}from"@vkontakte/videoplayer-shared";import{ErrorCategory as FM}from"@vkontakte/videoplayer-shared";var Sv=["stun:videostun.mycdn.me:80"],qM=1e3,UM=3,bl=()=>null,en=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=bl;this.externalStopCallback=bl;this.externalErrorCallback=bl;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:Sv}]};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:FM.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),qM)}normalizeOptions(e={}){let t={stunServerList:Sv,maxRetryNumber:UM,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var Pa=class{constructor(e){this.videoState=new $("stopped");this.maxSeekBackTime$=new QM(0);this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.pause(),this.video.srcObject=null,this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),I(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let s=this.params.desiredState.videoTrack.getTransition();if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s){this.prepare();return}switch(e){case"ready":t==="paused"?(this.videoState.setState("paused"),I(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):r?.to==="playing"&&I(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):r?.to==="paused"&&I(this.params.desiredState.playbackState,"paused");return;default:return vv(e)}};this.subscription=new GM,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=pe(e.container,e.tuning),this.liveStreamClient=new en(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),he(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,r=n=>{e.error$.next({id:"WebRTCLiveProvider",category:gl.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};yv(this.videoState.stateChangeStarted$.pipe(Tv(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe(Tv(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})});let a=fe(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(Ce(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(me(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 vv(n.to)}},r)).add(yv(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,jM(["init"])).pipe(HM(0)).subscribe(this.syncPlayback.bind(this),r)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),r)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),r))}onLiveStreamStart(e){this.params.output.element$.next(this.video),this.params.output.duration$.next(0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(Z(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.currentVideoTrack$.next({id:"webrtc",quality:WM.INVARIANT}),this.video.srcObject=e,I(this.params.desiredState.playbackState,"playing")}onLiveStreamStop(){this.videoState.startTransitionTo("stopped"),this.syncPlayback(),this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.params.output.endedEvent$.next()}onLiveStreamError(e){this.onLiveStreamStop(),this.params.output.error$.next({id:"WebRTC stream runtime error",category:gl.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){be(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),I(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:gl.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var Aa=class{constructor(e){this.iterator=e[Symbol.iterator](),this.next()}next(){this.current=this.iterator.next()}getValue(){if(this.current.done)throw new Error("Iterable is completed");return this.current.value}isCompleted(){return!!this.current.done}};import{assertNever as ka,assertNonNullable as Mt,ErrorCategory as tn,filter as kv,isNonNullable as wv,isNullable as t0,map as r0,merge as i0,once as a0,Subject as ve,Subscription as Rv,ValueSubject as L,flattenObject as $v}from"@vkontakte/videoplayer-shared";import{Observable as YM,map as Iv,Subscription as zM,Subject as KM}from"@vkontakte/videoplayer-shared";var Ev=i=>new YM(e=>{let t=new zM,r=i.desiredPlaybackState$.stateChangeStarted$.pipe(Iv(({from:l,to:c})=>`${l}-${c}`)),a=i.desiredPlaybackState$.stateChangeEnded$,s=i.providerChanged$.pipe(Iv(({type:l})=>l!==void 0)),n=new KM,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()}});import{ErrorCategory as JM,Subscription as XM,combine as ZM,filter as Pv,once as Av}from"@vkontakte/videoplayer-shared";function xv(){return new(window.AudioContext||window.webkitAudioContext)}import{clientChecker as e0}from"@vkontakte/videoplayer-shared";var Gr=class i{constructor(e,t,r,a){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=r;this.volumeMultiplier=a;this.destroyController=new Ae;this.subscriptions=new XM;this.audioContext=null;this.gainNode=null;this.mediaElementSource=null;this.subscriptions.add(this.provider$.pipe(Pv(s=>!!s.type),Av()).subscribe(({type:s})=>this.subscribe(s)))}static{this.errorId="VolumeMultiplierManager"}subscribe(e){e0.isSafari&&e!=="MPEG"||this.subscriptions.add(ZM({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe(Pv(({playbackState:t,video:r,volume:{muted:a,volume:s}})=>t==="playing"&&!!r&&!a&&!!s),Av()).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=xv();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:JM.VIDEO_PIPELINE,message:e?.message??`${i.errorId} exception`,thrown:e})}};var s0={chunkDuration:5e3,maxParallelRequests:5},wa=class{constructor(e){this.current$=new L({type:void 0});this.providerError$=new ve;this.noAvailableProvidersError$=new ve;this.volumeMultiplierError$=new ve;this.providerOutput={position$:new L(0),duration$:new L(1/0),volume$:new L({muted:!1,volume:1}),availableVideoStreams$:new L([]),currentVideoStream$:new L(void 0),availableVideoTracks$:new L([]),currentVideoTrack$:new L(void 0),availableAudioStreams$:new L([]),currentAudioStream$:new L(void 0),availableAudioTracks$:new L([]),currentVideoSegmentLength$:new L(0),currentAudioSegmentLength$:new L(0),isAudioAvailable$:new L(!0),autoVideoTrackLimitingAvailable$:new L(!1),autoVideoTrackLimits$:new L(void 0),currentBuffer$:new L(void 0),isBuffering$:new L(!0),error$:new ve,warning$:new ve,willSeekEvent$:new ve,soundProhibitedEvent$:new ve,seekedEvent$:new ve,loopedEvent$:new ve,endedEvent$:new ve,firstBytesEvent$:new ve,loadedMetadataEvent$:new ve,firstFrameEvent$:new ve,canplay$:new ve,isLive$:new L(void 0),isLowLatency$:new L(!1),canChangePlaybackSpeed$:new L(!0),liveTime$:new L(void 0),liveBufferTime$:new L(void 0),liveLatency$:new L(void 0),availableTextTracks$:new L([]),currentTextTrack$:new L(void 0),hostname$:new L(void 0),httpConnectionType$:new L(void 0),httpConnectionReused$:new L(void 0),inPiP$:new L(!1),inFullscreen$:new L(!1),element$:new L(void 0),elementVisible$:new L(!0),availableSources$:new L(void 0),is3DVideo$:new L(!1),playbackState$:new L("")};this.subscription=new Rv;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=tg([...ig(this.params.tuning),...rg(this.params.tuning)],this.params.tuning).filter(l=>wv(e.sources[l])),{forceFormat:r,formatsToAvoid:a}=this.params.tuning,s=[];r?s=[r]:a.length?s=[...t.filter(l=>!(0,Sl.default)(a,l)),...t.filter(l=>(0,Sl.default)(a,l))]:s=t,this.log({message:`Selected formats: ${s.join(" > ")}`}),this.tracer.log("Selected formats",$v(s)),this.screenFormatsIterator=new Aa(s);let n=[...wu(!0),...wu(!1)];this.chromecastFormatsIterator=new Aa(n.filter(l=>wv(e.sources[l]))),this.providerOutput.availableSources$.next(e.sources);let{volumeMultiplier:o=1,tuning:{useVolumeMultiplier:u}}=this.params;u&&o!==1&&Gr.isSupported()&&(this.volumeMultiplierManager=new Gr(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(t0(t)){this.handleNoFormatsError(e);return}let r;try{r=this.createProvider(e,t)}catch(a){this.providerError$.next({id:"ProviderNotConstructed",category:tn.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 ka(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 Mt(o),new ga({...n,source:o,sourceHls:u})}case"DASH_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return Mt(o),new Sa({...n,source:o})}case"HLS":case"HLS_ONDEMAND":{let o=this.applyFailoverHost(t[e]);return Mt(o),_r||!this.params.tuning.useHlsJs?new Ia({...n,source:o}):new ya({...n,source:o})}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return Mt(o),new Ta({...n,source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case"MPEG":{let o=this.applyFailoverHost(t[e]);return Mt(o),new xa({...n,source:o})}case"DASH_LIVE":{let o=this.applyFailoverHost(t[e]);return Mt(o),new Rb({...n,source:o,config:{...s0,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case"WEB_RTC_LIVE":{let o=this.applyFailoverHost(t[e]);return Mt(o),new Pa({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 ka(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 Mt(o),new Si({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 ka(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return ka(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 ka(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,Mv.default)((0,Lv.default)(e).map(([a,s])=>[a,r(s)]))}initProviderErrorHandling(){let e=new Rv,t=!1,r=0;return e.add(i0(this.providerOutput.error$.pipe(kv(a=>!this.params.tuning.ignoreAudioRendererError||!a.message||!/AUDIO_RENDERER_ERROR/ig.test(a.message))),Ev({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(r0(a=>({id:`ProviderHangup:${a}`,category:tn.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(kv(({to:s})=>s==="playing"),a0()).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===tn.NETWORK,u=a.category===tn.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",$v(n))})),e}};import{fromEvent as rn,once as n0,combine as o0,Subscription as Cv,ValueSubject as vl,map as u0,filter as l0,isNonNullable as an,now as we,safeStorage as yl}from"@vkontakte/videoplayer-shared";var c0=5e3,Dv="one_video_throughput",Vv="one_video_rtt",Ra=window.navigator.connection,Bv=()=>{let i=Ra?.downlink;if(an(i)&&i!==10)return i*1e3},Ov=()=>{let i=Ra?.rtt;if(an(i)&&i!==3e3)return i},_v=(i,e,t)=>{let r=t*8,a=r/i;return r/(a+e)},Tl=class i{constructor(e){this.subscription=new Cv;this.concurrentDownloads=new Set;this.tuningConfig=e;let t=i.load(Dv)||(e.useBrowserEstimation?Bv():void 0)||c0,r=i.load(Vv)??(e.useBrowserEstimation?Ov():void 0)??0;if(this.throughput$=new vl(t),this.rtt$=new vl(r),this.rttAdjustedThroughput$=new vl(_v(t,r,e.rttPenaltyRequestSize)),this.throughput=tr.getSmoothedValue(t,-1,e),this.rtt=tr.getSmoothedValue(r,1,e),e.useBrowserEstimation){let a=()=>{let n=Bv();n&&this.throughput.next(n);let o=Ov();an(o)&&this.rtt.next(o)};Ra&&"onchange"in Ra&&this.subscription.add(rn(Ra,"change").subscribe(a)),a()}this.subscription.add(this.throughput.smoothed$.subscribe(a=>{yl.set(Dv,a.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(a=>{yl.set(Vv,a.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(o0({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(u0(({throughput:a,rtt:s})=>_v(a,s,e.rttPenaltyRequestSize)),l0(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=we(),a=new Cv;switch(this.subscription.add(a),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:a.add(rn(e,"progress").pipe(n0()).subscribe(s=>{t=s.loaded,r=we()}));break;case 1:case 0:a.add(rn(e,"loadstart").subscribe(()=>{t=0,r=we()}));break}a.add(rn(e,"loadend").subscribe(s=>{if(e.status===200){let n=s.loaded,o=we(),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=we(),n=0,o=we(),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,we()-s,1),this.concurrentDownloads.delete(e);else if(d){if(t){let p=we();if(p-o>this.tuningConfig.lowLatency.continuesByteSequenceInterval||p-s>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let f=o-s;f&&this.addRawSpeed(n,f,1,t),n=d.byteLength,s=we()}else n+=d.byteLength;o=we()}else a+=d.byteLength,n+=d.byteLength,n>=this.tuningConfig.streamMinSampleSize&&we()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,we()-o,this.concurrentDownloads.size),n=0,o=we());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=yl.get(e);if(an(t))return parseInt(t,10)??void 0}},Nv=Tl;import{fillWithDefault as d0,VideoQuality as Fv}from"@vkontakte/videoplayer-shared";var qv={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:Fv.Q_4320P,activeVideoAreaThreshold:.1},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:Fv.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},Uv=i=>({...d0(i,qv),configName:[...i.configName??[],...qv.configName]});import{assertNonNullable as sn,combine as ht,ErrorCategory as nn,filter as le,filterChanged as O,fromEvent as El,isNonNullable as S0,isNullable as v0,Logger as y0,map as D,mapTo as Qv,merge as Ct,now as on,once as et,Subject as H,Subscription as Wv,tap as Yv,ValueSubject as x,isHigher as T0,isInvariantQuality as zv,flattenObject as Dt,throttle as xl,getTraceSubscriptionMethod as Kv,Tracer as I0,InternalsExposure as E0}from"@vkontakte/videoplayer-shared";import{merge as p0,map as h0,filter as Hv,isNonNullable as m0}from"@vkontakte/videoplayer-shared";var Il=({seekState:i,position$:e})=>p0(i.stateChangeEnded$.pipe(h0(({to:t})=>t.state==="none"?void 0:(t.position??NaN)/1e3),Hv(m0)),e.pipe(Hv(()=>i.getState().state==="none")));import{assertNonNullable as f0}from"@vkontakte/videoplayer-shared";var jv=i=>{let e=typeof i.container=="string"?document.getElementById(i.container):i.container;return f0(e,`Wrong container or containerId {${i.container}}`),e};import{filter as b0,once as g0}from"@vkontakte/videoplayer-shared";var Gv=(i,e,t,r)=>{i!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&t?.getValue().length===0?t.pipe(b0(a=>a.length>0),g0()).subscribe(a=>{a.find(r)&&e.startTransitionTo(i)}):(i===void 0||t?.getValue().find(r))&&e.startTransitionTo(i)};var un=class{constructor(e={configName:[]},t=I0.createRootTracer(!1)){this.subscription=new Wv;this.logger=new y0;this.abrLogger=this.logger.createComponentLog("ABR");this.internalsExposure=null;this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new x(!1);this.hasLiveOffsetByPausedTimer=0;this.wasSetStartedQuality=!1;this.desiredState={playbackState:new $("stopped"),seekState:new $({state:"none"}),volume:new $({volume:1,muted:!1}),videoTrack:new $(void 0),videoStream:new $(void 0),audioStream:new $(void 0),autoVideoTrackSwitching:new $(!0),autoVideoTrackLimits:new $({}),isLooped:new $(!1),isLowLatency:new $(!1),playbackRate:new $(1),externalTextTracks:new $([]),internalTextTracks:new $([]),currentTextTrack:new $(void 0),textTrackCuesSettings:new $({}),cameraOrientation:new $({x:0,y:0})};this.info={playbackState$:new x("stopped"),position$:new x(0),duration$:new x(1/0),muted$:new x(!1),volume$:new x(1),availableVideoStreams$:new x([]),currentVideoStream$:new x(void 0),availableQualities$:new x([]),availableQualitiesFps$:new x({}),currentQuality$:new x(void 0),isAutoQualityEnabled$:new x(!0),autoQualityLimitingAvailable$:new x(!1),autoQualityLimits$:new x({}),availableAudioStreams$:new x([]),currentAudioStream$:new x(void 0),availableAudioTracks$:new x([]),isAudioAvailable$:new x(!0),currentPlaybackRate$:new x(1),currentBuffer$:new x({start:0,end:0}),isBuffering$:new x(!0),isStalled$:new x(!1),isEnded$:new x(!1),isLooped$:new x(!1),isLive$:new x(void 0),canChangePlaybackSpeed$:new x(void 0),atLiveEdge$:new x(void 0),atLiveDurationEdge$:new x(void 0),liveTime$:new x(void 0),liveBufferTime$:new x(void 0),liveLatency$:new x(void 0),currentFormat$:new x(void 0),availableTextTracks$:new x([]),currentTextTrack$:new x(void 0),throughputEstimation$:new x(void 0),rttEstimation$:new x(void 0),videoBitrate$:new x(void 0),hostname$:new x(void 0),httpConnectionType$:new x(void 0),httpConnectionReused$:new x(void 0),surface$:new x("none"),chromecastState$:new x("NOT_AVAILABLE"),chromecastDeviceName$:new x(void 0),intrinsicVideoSize$:new x(void 0),availableSources$:new x(void 0),is3DVideo$:new x(!1),currentVideoSegmentLength$:new x(0),currentAudioSegmentLength$:new x(0)};this.events={inited$:new H,ready$:new H,started$:new H,playing$:new H,paused$:new H,stopped$:new H,willStart$:new H,willResume$:new H,willPause$:new H,willStop$:new H,willDestruct$:new H,watchCoverageRecord$:new H,watchCoverageLive$:new H,managedError$:new H,fatalError$:new H,ended$:new H,looped$:new H,seeked$:new H,willSeek$:new H,autoplaySoundProhibited$:new H,firstBytes$:new H,loadedMetadata$:new H,firstFrame$:new H,canplay$:new H,log$:new H};this.experimental={element$:new x(void 0),tuningConfigName$:new x([]),enableDebugTelemetry$:new x(!1),dumpTelemetry:ab};if(this.initLogs(),this.tuning=Uv(e),this.tracer=t,this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new Ua({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new Nv(this.tuning.throughputEstimator),e.exposeInternalsToGlobal&&(this.internalsExposure=new E0("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(p=>JSON.stringify(p,(h,f)=>{let b=typeof f;return(0,Jv.default)(["number","string","boolean"],b)?f:f===null?null:`<${b}>`})),c=`Player.${String(a)}`,d=`Exception calling ${c} (${l.join(", ")})`;throw this.events.fatalError$.next({id:c,category:nn.WTF,message:d,thrown:u}),u}}}})}initVideo(e){this.config=e;let{container:t,...r}=e;return this.tracer.log("initVideo",Dt(r)),this.domContainer=jv(e),this.chromecastInitializer.contentId=e.meta?.videoId,this.providerContainer=new wa({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"),El(document,"visibilitychange").pipe(et()).subscribe(e)):e(),this}pause(){let e=this.desiredState.playbackState;return this.tracer.log("pause",{currentPlayBackState:e.getState()}),e.getState()!=="paused"&&e.startTransitionTo("paused"),this}stop(){let e=this.desiredState.playbackState;return this.tracer.log("stop",{currentPlayBackState:e.getState()}),e.getState()!=="stopped"&&e.startTransitionTo("stopped"),this}seekTime(e,t=!0){let r=this.info.duration$.getValue(),a=this.info.isLive$.getValue(),s=e;return e>=r&&!a&&(s=r-.1),this.tracer.log("seekTime",{duration:r,isLive:a,time:e,calculatedTime:s,forcePrecise:t}),this.events.willSeek$.next({from:this.getExactTime(),to:s}),this.desiredState.seekState.setState({state:"requested",position:s*1e3,forcePrecise:t}),this}seekPercent(e){let t=this.info.duration$.getValue();return this.tracer.log("seekPercent",{percent:e,duration:t}),isFinite(t)&&this.seekTime(Math.abs(t)*e,!1),this}setVolume(e){let t=this.tuning.isAudioDisabled||this.desiredState.volume.getState().muted;return this.tracer.log("setVolume",{volume:e,isAudioDisabled:this.tuning.isAudioDisabled,isDesiredStateMuted:this.desiredState.volume.getState().muted,chromecastState:this.chromecastInitializer.castState$.getValue(),muted:t}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setVolume(e):this.desiredState.volume.startTransitionTo({volume:e,muted:t}),this}setMuted(e){let t=this.tuning.isAudioDisabled||e;return this.tracer.log("setMuted",{isMuted:e,isAudioDisabled:this.tuning.isAudioDisabled,desiredStateVolume:this.desiredState.volume.getState().volume,chromecastState:this.chromecastInitializer.castState$.getValue(),muted:t}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setMuted(t):this.desiredState.volume.startTransitionTo({volume:this.desiredState.volume.getState().volume,muted:t}),this}setVideoStream(e){return this.desiredState.videoStream.startTransitionTo(e),this}setAudioStream(e){return this.desiredState.audioStream.startTransitionTo(e),this}setQuality(e){sn(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(le(r=>r.length>0),et()).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",Dt(e)),this.desiredState.autoVideoTrackLimits.startTransitionTo(e),this}setPlaybackRate(e){sn(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",Dt(e)),this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>({type:"external",...t}))),this}selectTextTrack(e){return Gv(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(v0(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),r=t.state==="none"?void 0:t.position;return S0(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(Ct(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(D(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(D(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(D(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(D(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(D(e=>e.to)).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(le(({from:e})=>e==="stopped"),et()).subscribe(()=>{this.initedAt=on(),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",Dt(n)),n.state==="requested"?this.desiredState.seekState.setState({...n,state:"applying"}):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:nn.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.soundProhibitedEvent$.pipe(et()).subscribe(this.events.autoplaySoundProhibited$)).add(e.providerOutput.seekedEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();this.tracer.log("seekedEvent",Dt(n)),n.state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe(D(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(D(n=>n.destination),O()).subscribe(()=>this.isPlaybackStarted=!1)).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add(ht({availableVideoTracks:e.providerOutput.availableVideoTracks$,currentVideoStream:e.providerOutput.currentVideoStream$}).pipe(D(({availableVideoTracks:n,currentVideoStream:o})=>n.filter(u=>o?o.id===u.streamId:!0).map(({quality:u})=>u).sort((u,l)=>zv(u)?1:zv(l)?-1:T0(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(O()).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(O((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.pipe(O((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe(O()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(O()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(O()).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(D(n=>n?{start:n.from,end:n.to}:{start:0,end:0})).subscribe(this.info.currentBuffer$)).add(e.providerOutput.duration$.subscribe(this.info.duration$)).add(e.providerOutput.isBuffering$.subscribe(this.info.isBuffering$)).add(e.providerOutput.isLive$.subscribe(this.info.isLive$)).add(e.providerOutput.canChangePlaybackSpeed$.subscribe(this.info.canChangePlaybackSpeed$)).add(e.providerOutput.liveTime$.subscribe(this.info.liveTime$)).add(e.providerOutput.liveBufferTime$.subscribe(this.info.liveBufferTime$)).add(e.providerOutput.liveLatency$.subscribe(this.info.liveLatency$)).add(ht({hasLiveOffsetByPaused:Ct(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(D(n=>n.to),O(),D(n=>n==="paused")),isLowLatency:e.providerOutput.isLowLatency$}).subscribe(({hasLiveOffsetByPaused:n,isLowLatency:o})=>{if(window.clearTimeout(this.hasLiveOffsetByPausedTimer),n){this.hasLiveOffsetByPausedTimer=window.setTimeout(()=>{this.hasLiveOffsetByPaused.next(!0)},this.getActiveLiveDelay(o));return}this.hasLiveOffsetByPaused.next(!1)})).add(ht({atLiveEdge:ht({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:Il({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(D(({isLive:n,position:o,isLowLatency:u})=>{let l=this.getActiveLiveDelay(u);return n&&Math.abs(o)<l/1e3}),O(),Yv(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(D(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add(ht({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(D(({isLive:n,position:o,duration:u})=>n&&(Math.abs(u)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),O(),Yv(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(D(n=>n.muted),O()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(D(n=>n.volume),O()).subscribe(this.info.volume$)).add(Il({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(Ct(e.providerOutput.endedEvent$.pipe(Qv(!0)),e.providerOutput.seekedEvent$.pipe(Qv(!1))).pipe(O()).subscribe(this.info.isEnded$)).add(e.providerOutput.endedEvent$.subscribe(this.events.ended$)).add(e.providerOutput.loopedEvent$.subscribe(this.events.looped$)).add(e.providerError$.subscribe(this.events.managedError$)).add(e.volumeMultiplierError$.subscribe(this.events.managedError$)).add(e.noAvailableProvidersError$.pipe(D(n=>({id:n?`No${n}`:"NoProviders",category:nn.VIDEO_PIPELINE,message:n?`${n} was forced but failed or not available`:"No suitable providers or all providers failed"}))).subscribe(this.events.fatalError$)).add(e.providerOutput.element$.subscribe(this.experimental.element$)).add(e.providerOutput.firstBytesEvent$.pipe(et(),D(n=>n??on()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe(et(),D(()=>on()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(et(),D(()=>on()-this.initedAt)).subscribe(this.events.canplay$)).add(this.throughputEstimator.throughput$.subscribe(this.info.throughputEstimation$)).add(this.throughputEstimator.rtt$.subscribe(this.info.rttEstimation$)).add(e.providerOutput.availableSources$.subscribe(this.info.availableSources$));let t=new x(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let r=new x(!0);this.subscription.add(e.current$.subscribe(()=>r.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(le(({to:n})=>n==="playing"),et()).subscribe(()=>r.next(!1)));let a=0,s=Ct(e.providerOutput.isBuffering$,t,r).pipe(D(()=>{let n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||r.getValue();return n&&!o}),O());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(Ct(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(Ct(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,e.providerOutput.elementVisible$,this.chromecastInitializer.castState$).subscribe(()=>{let n=e.providerOutput.inPiP$.getValue(),o=e.providerOutput.inFullscreen$.getValue(),u=e.providerOutput.element$.getValue(),l=e.providerOutput.elementVisible$.getValue(),c=this.chromecastInitializer.castState$.getValue(),d;c==="CONNECTED"?d="second_screen":u?l?n?d="pip":o?d="fullscreen":d="inline":d="invisible":d="none",this.info.surface$.getValue()!==d&&this.info.surface$.next(d)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(D(e=>e?.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){let t=new Wv;this.subscription.add(t),this.subscription.add(e.current$.pipe(O((r,a)=>r.provider===a.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(le(r=>r.length>0),et()).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=At(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(Ct(this.desiredState.videoTrack.stateChangeStarted$.pipe(D(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(D(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(D(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(D(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(D(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(D(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(D(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(D(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(D(e=>({component:"desiredState",message:`[${e.entity} change] ${e.type}: ${JSON.stringify(e.transition)}`}))).subscribe(this.logger.log)),this.subscription.add(this.logger.log$.subscribe(this.events.log$))}initDebugTelemetry(){let e=this.providerContainer?.providerOutput;sn(this.providerContainer),sn(e),ib(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(t=>rb(t)),this.providerContainer.current$.subscribe(({type:t})=>Ii("provider",t)),e.duration$.subscribe(t=>Ii("duration",t)),e.availableVideoTracks$.pipe(le(t=>!!t.length),et()).subscribe(t=>Ii("tracks",t)),this.events.fatalError$.subscribe(new oe("fatalError")),this.events.managedError$.subscribe(new oe("managedError")),e.position$.subscribe(new oe("position")),e.currentVideoTrack$.pipe(D(t=>t?.quality)).subscribe(new oe("quality")),this.info.currentBuffer$.subscribe(new oe("buffer")),e.isBuffering$.subscribe(new oe("isBuffering"))].forEach(t=>this.subscription.add(t)),Ii("codecs",eg())}initTracerSubscription(){let e=Kv(this.tracer.log.bind(this.tracer)),t=Kv(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(O()).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(ht({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe(le(({currentQuality:r,videoBitrate:a})=>!!r&&!!a),O((r,a)=>r.currentQuality===a.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe(le(r=>r>0),O()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe(le(r=>r>0),O()).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(ht({currentBuffer:this.info.currentBuffer$.pipe(le(r=>r.end>0),O((r,a)=>r.end===a.end&&r.start===a.start)),position:this.info.position$.pipe(O())}).pipe(xl(1e3)).subscribe(e("currentBufferAndPosition"))).add(this.info.duration$.pipe(O()).subscribe(e("duration"))).add(this.info.isBuffering$.subscribe(e("isBuffering"))).add(this.info.isLive$.pipe(O()).subscribe(e("isLive"))).add(this.info.canChangePlaybackSpeed$.pipe(O()).subscribe(e("canChangePlaybackSpeed"))).add(ht({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe(le(({liveTime:r,liveBufferTime:a})=>!!r&&!!a),xl(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe(O(),le(r=>r===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe(O(),le(r=>r===!0)).subscribe(e("atLiveDurationEdge"))).add(this.info.muted$.pipe(O()).subscribe(e("muted"))).add(this.info.volume$.pipe(O()).subscribe(e("volume"))).add(this.info.isEnded$.pipe(O(),le(r=>r===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add(ht({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe(le(({throughputEstimation:r,rtt:a})=>!!r&&!!a),xl(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe(O(),le(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:nn.DOM,message:String(a)})})};this.subscription.add(Ct(El(document,"visibilitychange"),El(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",Dt({quality:t,availableTracks:Dt(e),track:Dt(r),isAutoQuality:!r})),r?this.desiredState.videoTrack.startTransitionTo(r):this.setAutoQuality(!0)}getActiveLiveDelay(e=!1){return e?this.tuning.live.lowLatencyActiveLiveDelay:this.tuning.live.activeLiveDelay}};import{Subscription as C3,Observable as D3,Subject as V3,ValueSubject as B3,VideoQuality as O3}from"@vkontakte/videoplayer-shared";var _3=`@vkontakte/videoplayer-core@${kl}`;export{Ba as ChromecastState,cn as HttpConnectionType,D3 as Observable,de as PlaybackState,un as Player,_3 as SDK_VERSION,V3 as Subject,C3 as Subscription,dn as Surface,kl as VERSION,B3 as ValueSubject,gt as VideoFormat,O3 as VideoQuality};
123
+ `;var zs=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 Ws(this.params.fov,this.params.orientation),this.cameraRotationManager=new Ys(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(KS,this.gl.VERTEX_SHADER),r=this.createShader(JS,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,p=t+a;return[s,n,o,u,l,c,d,p]}updateTextureMappingBuffer(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([...this.calculateTexturePosition()]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}updateFrameSize(){this.frameWidth=this.sourceVideoElement.videoWidth,this.frameHeight=this.sourceVideoElement.videoHeight}createCanvas(){let e=document.createElement("canvas");return e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e}};import{isNullable as qL,now as XS,Subscription as UL,filter as HL,combine as ZS,ValueSubject as ev,isNonNullable as jL}from"@vkontakte/videoplayer-shared";var cl=class{constructor(){this.isSeeked$=new ev(!1);this.isBuffering$=new ev(!1);this.currentStallsCount=0;this.maxQualityLimit=void 0;this.lastUniqueVideoTrackSelectedTimestamp=0;this.predictedThroughputWithoutData=0;this.subscription=new UL}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(ZS({isBuffering:this.isBuffering$,isSeeked:this.isSeeked$}).pipe(HL(({isBuffering:t,isSeeked:r})=>t&&!r)).subscribe(()=>{this.currentStallsCount++})),this.subscription.add(ZS({currentStallDuration:this.currentStallDuration$,isSeeked:this.isSeeked$}).subscribe(({currentStallDuration:t,isSeeked:r})=>{if(qL(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=XS(),p=n&&this.currentStallsCount>=n,h=a&&!r&&d-this.lastUniqueVideoTrackSelectedTimestamp>=a+u&&t>=a,f=s&&d-this.lastUniqueVideoTrackSelectedTimestamp>=s+u&&d-c>=s+u&&t>=s;(p||h||f)&&(window.clearTimeout(this.qualityRestrictionTimer),this.maxQualityLimit=this.lastUniqueVideoTrackSelected.quality,jL(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=XS(),this.currentStallsCount=0)}destroy(){window.clearTimeout(this.qualityRestrictionTimer),this.subscription.unsubscribe()}},tv=cl;var sr=class{constructor(e){this.subscription=new ZL;this.videoState=new L("stopped");this.elementSize$=new eM(void 0);this.textTracksManager=new $e;this.droppedFramesManager=new ks;this.stallsManager=new tv;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"),y(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"),y(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):r?.to==="ready"&&y(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"&&y(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"&&y(this.params.desiredState.playbackState,"paused");return;default:return WL(e)}}};this.init3DScene=e=>{if(this.scene3D)return;this.scene3D=new zs(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=de(e.container,e.tuning),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Z(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 Gs({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode,tracer:this.tracer}),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params,r=me(this.video),a=this.constructor.name,s=o=>{e.error$.next({id:a,category:dl.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(rv(c=>!!c.length),av()).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(pl(c=>c.to.state!=="none"),ga());this.stallsManager.connect({isSeeked$:n,currentStallDuration$:this.player.currentStallDuration$.pipe(ga()),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(rv(iv),av()),e.firstBytesEvent$),s(this.videoState.stateChangeEnded$.pipe(pl(c=>c.to)),this.params.output.playbackState$),this.subscription.add(r.seeked$.subscribe(e.seekedEvent$,a)),this.subscription.add(Ke(this.video,t.isLooped,a)),this.subscription.add(he(this.video,t.volume,r.volumeState$,a)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,a)),this.subscription.add(Re(this.video,t.playbackRate,r.playbackRateState$,a)),s(XL(this.video),this.elementSize$),s(Me(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),y(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},a)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),y(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(YL(d,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let h=[];for(let f of d.audio){h.push(Xu(f));let b=[];for(let g of f.representations){let S=OS(g);b.push(S),this.audioTracksMap.set(S,{stream:f,representation:g})}this.audioStreamsMap.set(f,b)}this.params.output.availableAudioStreams$.next(h)}let p=[];for(let h of d.video){p.push(Zu(h));let f=[];for(let b of h.representations){let g=VS({...b,streamId:h.id});g&&(f.push(g),this.videoTracksMap.set(g,{stream:h,representation:b}))}this.videoStreamsMap.set(h,f)}if(this.params.output.availableVideoStreams$.next(p),this.textTracksManager)for(let h of d.text)for(let f of h.representations){let b=BS(h,f);this.textTracksMap.set(b,{stream:h,representation:f})}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:dl.WTF,message:"Switching representations threw",thrown:c});this.subscription.add(Ks(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$,KL(this.video,"progress")).subscribe(()=>{let c=this.player.state$.getState(),d=this.player.state$.getTransition();if(!(0,sv.default)(["manifest_ready","running"],c)||d)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let p=this.selectVideoAudioRepresentations();if(!p)return;let[h,f]=p,b=[...this.videoTracksMap.keys()].find(S=>this.videoTracksMap.get(S)?.representation.id===h.id);iv(b)&&(this.stallsManager.lastVideoTrackSelected=b);let g=this.params.desiredState.autoVideoTrackLimits.getTransition();if(g&&this.params.output.autoVideoTrackLimits$.next(g.to),c==="manifest_ready")this.player.initRepresentations(h.id,f?.id,this.params.sourceHls);else if(this.player.switchRepresentation("video",h.id).catch(o),f){let S=!!t.audioStream.getTransition();this.player.switchRepresentation("audio",f.id,S).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(ga()).subscribe(c=>{let d=[...this.videoTracksMap.entries()].find(([,{representation:b}])=>b.id===c);if(!d){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[p,{stream:h}]=d,f=this.params.desiredState.videoStream.getTransition();f&&f.to&&f.to.id===h.id&&this.params.desiredState.videoStream.setState(f.to),e.currentVideoTrack$.next(p),e.currentVideoStream$.next(Zu(h))},a)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(ga()).subscribe(c=>{let d=[...this.audioTracksMap.entries()].find(([,{representation:b}])=>b.id===c);if(!d){e.currentAudioStream$.next(void 0);return}let[p,{stream:h}]=d,f=this.params.desiredState.audioStream.getTransition();f&&f.to&&f.to.id===h.id&&this.params.desiredState.audioStream.setState(f.to),e.currentAudioStream$.next(Xu(h))},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(pl(({to:c})=>c==="ready"),ga());this.subscription.add(Ks(u,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$).subscribe(()=>{let c=t.autoVideoTrackSwitching.getState(),p=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:c?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(p)})),this.subscription.add(Ks(u,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let l=Ks(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,JL(["init"])).pipe(zL(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:w})=>w===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:w})=>w===u.id),c=l&&this.videoStreamsMap.get(l);if(!c)return;let d=Xe(this.video.buffered,this.video.currentTime*1e3),p=r?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,h=Math.min(d/Math.min(p,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),f=e.audioStream.getState()??(this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0),b=[...this.audioStreamsMap.keys()].find(({id:w})=>w===f?.id)??this.audioStreamsMap.keys().next().value,g=0;if(b){if(n&&!r){let w=Es(n,c,this.audioStreamsMap.get(b)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);g=Math.max(g,w?.bitrate??-1/0)}if(o){let w=Es(o,c,this.audioStreamsMap.get(b)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);g=Math.max(g,w?.bitrate??-1/0)}}let S=At(c,{container:this.elementSize$.getValue(),estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:g,forwardBufferHealth:h,current:o,visible:this.params.output.elementVisible$.getValue(),history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,stallsVideoMaxQualityLimit:this.stallsManager.videoMaxQualityLimit,stallsPredictedThroughput:this.stallsManager.predictedThroughput,abrLogger:this.params.dependencies.abrLogger}),x=r?S??n:n??S,T=b&&gb(x,c,this.audioStreamsMap.get(b)??[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:h,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),R=this.videoTracksMap.get(x)?.representation,v=T&&this.audioTracksMap.get(T)?.representation;if(R&&v)return[R,v];if(R&&!v&&this.audioTracksMap.size===0)return[R,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){fe(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.liveOffset?.pause(),this.videoState.setState("paused"),y(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:dl.DOM,thrown:e}))}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),pe(this.video),this.tracer.end()}};var Sa=class extends sr{subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:r}=this.getProviderSubscriptionInfo();r(t.timeUpdate$,e.position$),r(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}};import{combine as nv,interval as tM,map as ov}from"@vkontakte/videoplayer-shared";var va=class extends sr{constructor(e){super(e),this.liveOffset=new ot,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(ov(s=>s.to)).subscribe(this.player.isLowLatency$)).add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(nv({interval:tM(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(nv({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(ov(({liveBufferTime:s,liveAvailabilityStartTime:n})=>s&&n?s+n:void 0)).subscribe(e.liveTime$)).add(this.player.currentLiveTextRepresentation$.subscribe(s=>{if(s){let n=_S(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 lv=D(gs(),1);import{assertNever as ya,assertNonNullable as uv,debounce as rM,ErrorCategory as Js,filter as iM,isNonNullable as aM,isNullable as sM,map as Xs,merge as nM,Observable as oM,observableFrom as uM,Subscription as lM,videoSizeToQuality as cM}from"@vkontakte/videoplayer-shared";var Ue={};var jr=(i,e)=>new oM(t=>{let r=(a,s)=>t.next(s);return i.on(e,r),()=>i.off(e,r)}),Ta=class{constructor(e){this.subscription=new lM;this.videoState=new L("initializing");this.textTracksManager=new $e;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:ya(e)}break;case"ready":switch(e){case"stopped":this.prepare();break;case"ready":case"playing":case"paused":break;default:ya(e)}break;case"playing":switch(e){case"playing":break;case"stopped":this.prepare();break;case"ready":case"paused":this.playIfAllowed();break;default:ya(e)}break;case"paused":switch(e){case"paused":break;case"stopped":this.prepare();break;case"ready":this.videoState.setState("paused"),y(this.params.desiredState.playbackState,"paused");break;case"playing":this.pause();break;default:ya(e)}break;default:ya(t)}};this.video=de(e.container,e.tuning),this.params=e,this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Z(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),pe(this.video)}loadHlsJs(){let e=!1,t=a=>{e||this.params.output.error$.next({id:a==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:Js.NETWORK,message:"Failed to load Hls.js",thrown:a}),e=!0},r=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);(0,lv.default)(import("hls.js").then(a=>{e||(Ue.Hls=a.default,Ue.Events=a.default.Events,this.init())},t),()=>{window.clearTimeout(r),e=!0})}init(){uv(Ue.Hls,"hls.js not loaded"),this.hls=new Ue.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState("stopped")}subscribe(){uv(Ue.Events,"hls.js not loaded");let{desiredState:e,output:t}=this.params,r=l=>{t.error$.next({id:"HlsJsProvider",category:Js.WTF,message:"HlsJsProvider internal logic error",thrown:l})},a=me(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(Ke(this.video,e.isLooped,r)),this.subscription.add(he(this.video,e.volume,a.volumeState$,r)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(Re(this.video,e.playbackRate,a.playbackRateState$,r)),s(Me(this.video),t.elementVisible$),s(this.videoState.stateChangeEnded$.pipe(Xs(l=>l.to)),this.params.output.playbackState$),this.subscription.add(jr(this.hls,Ue.Events.ERROR).subscribe(l=>{l.fatal&&t.error$.next({id:["HlsJsFatal",l.type,l.details].join("_"),category:Js.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"),y(e.playbackState,"playing")},r)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),y(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(jr(this.hls,Ue.Events.MANIFEST_PARSED).pipe(Xs(({levels:l})=>l.reduce((c,d)=>{let p=d.name||d.height.toString(10),{width:h,height:f}=d,b=xt(d.attrs.QUALITY??"")??cM({width:h,height:f});if(!b)return c;let g=d.attrs["FRAME-RATE"]?parseFloat(d.attrs["FRAME-RATE"]):void 0,S={id:p.toString(),quality:b,bitrate:d.bitrate/1e3,size:{width:h,height:f},fps:g};return this.trackLevels.set(p,{track:S,level:d}),c.push(S),c},[]))),t.availableVideoTracks$),s(jr(this.hls,Ue.Events.MANIFEST_PARSED),l=>{if(l.subtitleTracks.length>0){let c=[];for(let d of l.subtitleTracks){let p=d.name,h=d.attrs.URI||"",f=d.lang;c.push({id:p,url:h,language:f,type:"internal"})}e.internalTextTracks.startTransitionTo(c)}}),s(jr(this.hls,Ue.Events.LEVEL_LOADING).pipe(Xs(({url:l})=>Z(l))),t.hostname$),s(jr(this.hls,Ue.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(Tt(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=jr(this.hls,Ue.Events.LEVEL_SWITCHED).pipe(Xs(({level:l})=>n(this.hls.levels[l])));o.pipe(iM(aM)).subscribe(t.currentVideoTrack$,r),this.subscription.add(Tt(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel]),l=>{if(sM(l))return;let c=this.trackLevels.get(l.id)?.level;if(!c)return;let d=this.hls.levels.indexOf(c),p=this.hls.currentLevel,h=this.hls.levels[p];!h||c.bitrate>h.bitrate?this.hls.nextLevel=d:(this.hls.loadLevel=d,this.hls.loadLevel=d)},{changed$:o,onError:r})),s(a.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);let u=nM(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,uM(["init"])).pipe(rM(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 fe(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Js.DOM,thrown:t}))||(this.videoState.setState("paused"),y(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"),y(this.params.desiredState.playbackState,"stopped",!0)}};var cv="X-Playback-Duration",hl=async i=>{let e=await lt(i),t=await e.text(),r=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t)?.[1];return r?parseInt(r,10):e.headers.has(cv)?parseInt(e.headers.get(cv),10):void 0};import{assertNever as bM,combine as gM,debounce as SM,ErrorCategory as en,filter as vM,filterChanged as yM,isNonNullable as pv,isNullable as tn,map as hv,merge as TM,observableFrom as IM,Subscription as EM,ValueSubject as bl,VideoQuality as xM}from"@vkontakte/videoplayer-shared";var fl=D(To(),1);import{videoSizeToQuality as dM,getExponentialDelay as pM}from"@vkontakte/videoplayer-shared";var hM=i=>{let e=null;if(i.QUALITY&&(e=xt(i.QUALITY)),!e&&i.RESOLUTION){let[t,r]=i.RESOLUTION.split("x").map(a=>parseInt(a,10));e=dM({width:t,height:r})}return e??null},mM=(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,fl.default)(o[1].split(",").map(g=>g.split("="))),c=l.QUALITY??`stream-${l.BANDWIDTH}`,d=hM(l),p;l.BANDWIDTH&&(p=parseInt(l.BANDWIDTH,10)/1e3||void 0),!p&&l["AVERAGE-BANDWIDTH"]&&(p=parseInt(l["AVERAGE-BANDWIDTH"],10)/1e3||void 0);let h=l["FRAME-RATE"]?parseFloat(l["FRAME-RATE"]):void 0,f;if(l.RESOLUTION){let[g,S]=l.RESOLUTION.split("x").map(x=>parseInt(x,10));g&&S&&(f={width:g,height:S})}let b=new URL(t[++s],e).toString();d&&r.push({id:c,quality:d,url:b,bandwidth:p,size:f,fps:h})}if(u){let l=(0,fl.default)(u[1].split(",").map(h=>h.split("=")).map(([h,f])=>[h,f.replace(/^"|"$/g,"")])),c=l.URI?.replace(/playlist$/,"subtitles.vtt"),d=l.LANGUAGE,p=l.NAME;c&&d&&a.push({type:"internal",id:d,label:p,language:d,url:c,isAuto:!1})}}}if(!r.length)throw new Error("Empty manifest");return{qualityManifests:r,textTracks:a}},fM=i=>new Promise(e=>{setTimeout(()=>{e()},i)}),ml=0,dv=async(i,e=i,t)=>{let a=await(await lt(i)).text();ml+=1;try{let{qualityManifests:s,textTracks:n}=mM(a,e);return{qualityManifests:s,textTracks:n}}catch{if(ml<=t.manifestRetryMaxCount)return await fM(pM(ml-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),dv(i,e,t)}return{qualityManifests:[],textTracks:[]}},Zs=dv;var Ia=class{constructor(e){this.subscription=new EM;this.videoState=new L("stopped");this.textTracksManager=new $e;this.manifests$=new bl([]);this.liveOffset=new ot;this.manifestStartTime$=new bl(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"),y(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"?y(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),y(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"&&y(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"&&(y(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return bM(t)}};this.params=e,this.video=de(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:xM.INVARIANT,url:this.params.source.url},Zs(ae(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:t})=>{t.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:en.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),this.manifests$.next([this.masterManifest,...t])},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:en.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(Z(this.params.source.url)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.maxSeekBackTime$=new bl(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:en.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},a=me(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(he(this.video,t.volume,a.volumeState$,r)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Re(this.video,t.playbackRate,a.playbackRateState$,r)),s(Me(this.video),e.elementVisible$),this.textTracksManager.connect(this.video,t,e),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState("playing"),y(t.playbackState,"playing")},r)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),y(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(yM(),hv(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&&pv(l.to)){let d=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let p=this.manifests$.getValue().find(h=>h.id===d);p&&(this.params.output.currentVideoTrack$.next(p),this.params.output.hostname$.next(Z(p.url)))}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o&&o.state==="requested"&&this.seek(o.position)},r)),this.subscription.add(a.loadedData$.subscribe(()=>{let o=this.video?.getStartDate?.()?.getTime();this.manifestStartTime$.next(o||void 0)},r)),this.subscription.add(gM({startTime:this.manifestStartTime$.pipe(vM(pv)),currentTime:a.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),r)),this.subscription.add(this.manifests$.pipe(hv(o=>o.map(({id:u,quality:l,size:c,bandwidth:d,fps:p})=>({id:u,quality:l,size:c,fps:p,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,r));let n=TM(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,IM(["init"])).pipe(SM(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),pe(this.video)}prepare(){let e=this.selectManifest();if(tn(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=ae(a.toString(),this.liveOffset.getTotalOffset(),s);this.video.setAttribute("src",n),this.video.load(),hl(n).then(o=>{if(!tn(o))this.maxSeekBackTime$.next(o);else{let u=this.params.source.maxSeekBackTime??this.maxSeekBackTime$.getValue();if(tn(u)||!isFinite(u))try{lt(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();hl(d).then(p=>{tn(p)||this.maxSeekBackTime$.next(p)})}})}catch{}}})}playIfAllowed(){fe(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),y(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:en.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,r=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(r),this.params.output.position$.next(-r/1e3),this.params.output.seekedEvent$.next()}};import{assertNever as PM,debounce as AM,ErrorCategory as gl,fromEvent as Sl,isNonNullable as kM,isNullable as wM,map as mv,merge as fv,observableFrom as bv,Subscription as RM,ValueSubject as $M,VideoQuality as LM,clientChecker as MM}from"@vkontakte/videoplayer-shared";var Ea=class{constructor(e){this.subscription=new RM;this.videoState=new L("stopped");this.textTracksManager=new $e;this.manifests$=new $M([]);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"),y(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"?y(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),y(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"&&y(this.params.desiredState.playbackState,"playing");return;case"paused":r==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):a?.to==="paused"&&y(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return PM(t)}};this.params=e,this.video=de(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:LM.INVARIANT,url:this.params.source.url},this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Z(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),Zs(ae(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:t,textTracks:r})=>{this.manifests$.next([this.masterManifest,...t]),this.params.tuning.useNativeHLSTextTracks||this.params.desiredState.internalTextTracks.startTransitionTo(r)},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:gl.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:gl.WTF,message:"HlsProvider internal logic error",thrown:o})},a=me(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(mv(o=>o.to)),this.params.output.playbackState$),this.subscription.add(Ke(this.video,t.isLooped,r)),this.subscription.add(he(this.video,t.volume,a.volumeState$,r)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Re(this.video,t.playbackRate,a.playbackRateState$,r)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState("playing"),y(t.playbackState,"playing")},r)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),y(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&&kM(l.to)){let h=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let f=this.manifests$.getValue().find(b=>b.id===h);f&&(this.params.output.currentVideoTrack$.next(f),this.params.output.hostname$.next(Z(f.url)))}let d=this.params.desiredState.playbackRate.getState(),p=this.params.output.element$.getValue()?.playbackRate;if(d!==p){let h=this.params.output.element$.getValue();h&&(this.params.desiredState.playbackRate.setState(d),h.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(mv(o=>o.map(({id:u,quality:l,size:c,bandwidth:d,fps:p})=>({id:u,quality:l,size:c,fps:p,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,r)),!MM.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add(fv(Sl(o,"addtrack"),Sl(o,"removetrack"),Sl(o,"change"),bv(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},r))}let n=fv(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,bv(["init"])).pipe(AM(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),pe(this.video)}prepare(){let e=this.selectManifest();if(wM(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(){fe(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),y(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:gl.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};var yv=D(Ir(),1),xa=D(yi(),1);import{assertNever as CM,assertNonNullable as gv,debounce as DM,ErrorCategory as Sv,isHigher as VM,isHigherOrEqual as OM,isInvariantQuality as vv,isLowerOrEqual as BM,isNonNullable as _M,merge as NM,observableFrom as FM,Subscription as qM,map as UM}from"@vkontakte/videoplayer-shared";var Pa=class{constructor(e){this.subscription=new qM;this.videoState=new L("stopped");this.trackUrls={};this.textTracksManager=new $e;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"),y(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"?y(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),y(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"&&y(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):r?.to==="paused"&&y(this.params.desiredState.playbackState,"paused");return;default:return CM(e)}};this.params=e,this.video=de(e.container,e.tuning),this.params.output.element$.next(this.video),(0,yv.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,xa.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:Sv.WTF,message:"MpegProvider internal logic error",thrown:o})},a=me(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(UM(o=>o.to)),this.params.output.playbackState$),this.subscription.add(Ke(this.video,t.isLooped,r)),this.subscription.add(he(this.video,t.volume,a.volumeState$,r)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Re(this.video,t.playbackRate,a.playbackRateState$,r)),s(Me(this.video),e.elementVisible$),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState("playing"),y(t.playbackState,"playing")},r)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),y(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&&_M(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=NM(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,FM(["init"])).pipe(DM(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.params.output.element$.next(void 0),pe(this.video)}prepare(){let e=this.params.desiredState.videoTrack.getState()?.id;gv(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];gv(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(Z(t))}playIfAllowed(){fe(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),y(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Sv.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,xa.default)(this.trackUrls).find(o=>!vv(o.track.quality)&&BM(o.track.quality,e))?.track,s=this.params.desiredState.videoTrack.getState()?.id,n=this.trackUrls[s??"0"]?.track;if(a&&n&&OM(n.quality,a.quality)&&(t=a),!t){let o=(0,xa.default)(this.trackUrls).filter(l=>!vv(l.track.quality)&&VM(l.track.quality,e)),u=o.length;u&&(t=o[u-1].track)}t&&(r=t.quality)}else if(!e){let a=(0,xa.default)(this.trackUrls).map(s=>s.track);t=At(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})}};import{assertNever as Iv,debounce as GM,merge as Ev,observableFrom as WM,Subscription as YM,map as xv,ValueSubject as zM,ErrorCategory as yl,VideoQuality as KM}from"@vkontakte/videoplayer-shared";import{ErrorCategory as HM}from"@vkontakte/videoplayer-shared";var Tv=["stun:videostun.mycdn.me:80"],jM=1e3,QM=3,vl=()=>null,rn=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=vl;this.externalStopCallback=vl;this.externalErrorCallback=vl;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:Tv}]};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:HM.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),jM)}normalizeOptions(e={}){let t={stunServerList:Tv,maxRetryNumber:QM,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var Aa=class{constructor(e){this.videoState=new L("stopped");this.maxSeekBackTime$=new zM(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"),y(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"),y(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"&&y(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):r?.to==="paused"&&y(this.params.desiredState.playbackState,"paused");return;default:return Iv(e)}};this.subscription=new YM,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=de(e.container,e.tuning),this.liveStreamClient=new rn(this.params.source.url,{maxRetryNumber:this.params.tuning.webrtc.connectionRetryMaxNumber,errorChanel:this.params.output.error$}),this.liveStreamClient.onStart(this.onLiveStreamStart.bind(this)),this.liveStreamClient.onStop(this.onLiveStreamStop.bind(this)),this.liveStreamClient.onError(this.onLiveStreamError.bind(this)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.subscribe()}destroy(){this.subscription.unsubscribe(),this.liveStreamClient.disconnect(),this.params.output.element$.next(void 0),pe(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,r=n=>{e.error$.next({id:"WebRTCLiveProvider",category:yl.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};Ev(this.videoState.stateChangeStarted$.pipe(xv(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe(xv(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})});let a=me(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(Me(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(he(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 Iv(n.to)}},r)).add(Ev(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,WM(["init"])).pipe(GM(0)).subscribe(this.syncPlayback.bind(this),r)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),r)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),r))}onLiveStreamStart(e){this.params.output.element$.next(this.video),this.params.output.duration$.next(0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(Z(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.currentVideoTrack$.next({id:"webrtc",quality:KM.INVARIANT}),this.video.srcObject=e,y(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:yl.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){fe(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),y(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:yl.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var ka=class{constructor(e){this.iterator=e[Symbol.iterator](),this.next()}next(){this.current=this.iterator.next()}getValue(){if(this.current.done)throw new Error("Iterable is completed");return this.current.value}isCompleted(){return!!this.current.done}};import{assertNever as wa,assertNonNullable as Mt,ErrorCategory as an,filter as $v,isNonNullable as Lv,isNullable as aC,map as sC,merge as nC,once as oC,Subject as Se,Subscription as Mv,ValueSubject as M,flattenObject as Cv}from"@vkontakte/videoplayer-shared";import{Observable as JM,map as Pv,Subscription as XM,Subject as ZM}from"@vkontakte/videoplayer-shared";var Av=i=>new JM(e=>{let t=new XM,r=i.desiredPlaybackState$.stateChangeStarted$.pipe(Pv(({from:l,to:c})=>`${l}-${c}`)),a=i.desiredPlaybackState$.stateChangeEnded$,s=i.providerChanged$.pipe(Pv(({type:l})=>l!==void 0)),n=new ZM,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()}});import{ErrorCategory as eC,Subscription as tC,combine as rC,filter as wv,once as Rv}from"@vkontakte/videoplayer-shared";function kv(){return new(window.AudioContext||window.webkitAudioContext)}import{clientChecker as iC}from"@vkontakte/videoplayer-shared";var Qr=class i{constructor(e,t,r,a){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=r;this.volumeMultiplier=a;this.destroyController=new Pe;this.subscriptions=new tC;this.audioContext=null;this.gainNode=null;this.mediaElementSource=null;this.subscriptions.add(this.provider$.pipe(wv(s=>!!s.type),Rv()).subscribe(({type:s})=>this.subscribe(s)))}static{this.errorId="VolumeMultiplierManager"}subscribe(e){iC.isSafari&&e!=="MPEG"||this.subscriptions.add(rC({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe(wv(({playbackState:t,video:r,volume:{muted:a,volume:s}})=>t==="playing"&&!!r&&!a&&!!s),Rv()).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=kv();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:eC.VIDEO_PIPELINE,message:e?.message??`${i.errorId} exception`,thrown:e})}};var uC={chunkDuration:5e3,maxParallelRequests:5},Ra=class{constructor(e){this.current$=new M({type:void 0});this.providerError$=new Se;this.noAvailableProvidersError$=new Se;this.volumeMultiplierError$=new Se;this.providerOutput={position$:new M(0),duration$:new M(1/0),volume$:new M({muted:!1,volume:1}),availableVideoStreams$:new M([]),currentVideoStream$:new M(void 0),availableVideoTracks$:new M([]),currentVideoTrack$:new M(void 0),availableAudioStreams$:new M([]),currentAudioStream$:new M(void 0),availableAudioTracks$:new M([]),currentVideoSegmentLength$:new M(0),currentAudioSegmentLength$:new M(0),isAudioAvailable$:new M(!0),autoVideoTrackLimitingAvailable$:new M(!1),autoVideoTrackLimits$:new M(void 0),currentBuffer$:new M(void 0),isBuffering$:new M(!0),error$:new Se,warning$:new Se,willSeekEvent$:new Se,soundProhibitedEvent$:new Se,seekedEvent$:new Se,loopedEvent$:new Se,endedEvent$:new Se,firstBytesEvent$:new Se,loadedMetadataEvent$:new Se,firstFrameEvent$:new Se,canplay$:new Se,isLive$:new M(void 0),isLowLatency$:new M(!1),canChangePlaybackSpeed$:new M(!0),liveTime$:new M(void 0),liveBufferTime$:new M(void 0),liveLatency$:new M(void 0),availableTextTracks$:new M([]),currentTextTrack$:new M(void 0),hostname$:new M(void 0),httpConnectionType$:new M(void 0),httpConnectionReused$:new M(void 0),inPiP$:new M(!1),inFullscreen$:new M(!1),element$:new M(void 0),elementVisible$:new M(!0),availableSources$:new M(void 0),is3DVideo$:new M(!1),playbackState$:new M("")};this.subscription=new Mv;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=ag([...ng(this.params.tuning),...sg(this.params.tuning)],this.params.tuning).filter(l=>Lv(e.sources[l])),{forceFormat:r,formatsToAvoid:a}=this.params.tuning,s=[];r?s=[r]:a.length?s=[...t.filter(l=>!(0,Tl.default)(a,l)),...t.filter(l=>(0,Tl.default)(a,l))]:s=t,this.log({message:`Selected formats: ${s.join(" > ")}`}),this.tracer.log("Selected formats",Cv(s)),this.screenFormatsIterator=new ka(s);let n=[...Lu(!0),...Lu(!1)];this.chromecastFormatsIterator=new ka(n.filter(l=>Lv(e.sources[l]))),this.providerOutput.availableSources$.next(e.sources);let{volumeMultiplier:o=1,tuning:{useVolumeMultiplier:u}}=this.params;u&&o!==1&&Qr.isSupported()&&(this.volumeMultiplierManager=new Qr(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(aC(t)){this.handleNoFormatsError(e);return}let r;try{r=this.createProvider(e,t)}catch(a){this.providerError$.next({id:"ProviderNotConstructed",category:an.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 wa(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 Mt(o),new Sa({...n,source:o,sourceHls:u})}case"DASH_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return Mt(o),new va({...n,source:o})}case"HLS":case"HLS_ONDEMAND":{let o=this.applyFailoverHost(t[e]);return Mt(o),_r||!this.params.tuning.useHlsJs?new Ea({...n,source:o}):new Ta({...n,source:o})}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return Mt(o),new Ia({...n,source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case"MPEG":{let o=this.applyFailoverHost(t[e]);return Mt(o),new Pa({...n,source:o})}case"DASH_LIVE":{let o=this.applyFailoverHost(t[e]);return Mt(o),new Mb({...n,source:o,config:{...uC,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case"WEB_RTC_LIVE":{let o=this.applyFailoverHost(t[e]);return Mt(o),new Aa({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 wa(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 Mt(o),new vi({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 wa(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return wa(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 wa(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,Vv.default)((0,Dv.default)(e).map(([a,s])=>[a,r(s)]))}initProviderErrorHandling(){let e=new Mv,t=!1,r=0;return e.add(nC(this.providerOutput.error$.pipe($v(a=>!this.params.tuning.ignoreAudioRendererError||!a.message||!/AUDIO_RENDERER_ERROR/ig.test(a.message))),Av({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(sC(a=>({id:`ProviderHangup:${a}`,category:an.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($v(({to:s})=>s==="playing"),oC()).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===an.NETWORK,u=a.category===an.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",Cv(n))})),e}};import{fromEvent as sn,once as lC,combine as cC,Subscription as Ov,ValueSubject as Il,map as dC,filter as pC,isNonNullable as nn,now as ke,safeStorage as El}from"@vkontakte/videoplayer-shared";var hC=5e3,Bv="one_video_throughput",_v="one_video_rtt",$a=window.navigator.connection,Nv=()=>{let i=$a?.downlink;if(nn(i)&&i!==10)return i*1e3},Fv=()=>{let i=$a?.rtt;if(nn(i)&&i!==3e3)return i},qv=(i,e,t)=>{let r=t*8,a=r/i;return r/(a+e)},xl=class i{constructor(e){this.subscription=new Ov;this.concurrentDownloads=new Set;this.tuningConfig=e;let t=i.load(Bv)||(e.useBrowserEstimation?Nv():void 0)||hC,r=i.load(_v)??(e.useBrowserEstimation?Fv():void 0)??0;if(this.throughput$=new Il(t),this.rtt$=new Il(r),this.rttAdjustedThroughput$=new Il(qv(t,r,e.rttPenaltyRequestSize)),this.throughput=tr.getSmoothedValue(t,-1,e),this.rtt=tr.getSmoothedValue(r,1,e),e.useBrowserEstimation){let a=()=>{let n=Nv();n&&this.throughput.next(n);let o=Fv();nn(o)&&this.rtt.next(o)};$a&&"onchange"in $a&&this.subscription.add(sn($a,"change").subscribe(a)),a()}this.subscription.add(this.throughput.smoothed$.subscribe(a=>{El.set(Bv,a.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(a=>{El.set(_v,a.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(cC({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(dC(({throughput:a,rtt:s})=>qv(a,s,e.rttPenaltyRequestSize)),pC(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=ke(),a=new Ov;switch(this.subscription.add(a),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:a.add(sn(e,"progress").pipe(lC()).subscribe(s=>{t=s.loaded,r=ke()}));break;case 1:case 0:a.add(sn(e,"loadstart").subscribe(()=>{t=0,r=ke()}));break}a.add(sn(e,"loadend").subscribe(s=>{if(e.status===200){let n=s.loaded,o=ke(),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=ke(),n=0,o=ke(),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,ke()-s,1),this.concurrentDownloads.delete(e);else if(d){if(t){let p=ke();if(p-o>this.tuningConfig.lowLatency.continuesByteSequenceInterval||p-s>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let f=o-s;f&&this.addRawSpeed(n,f,1,t),n=d.byteLength,s=ke()}else n+=d.byteLength;o=ke()}else a+=d.byteLength,n+=d.byteLength,n>=this.tuningConfig.streamMinSampleSize&&ke()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,ke()-o,this.concurrentDownloads.size),n=0,o=ke());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=El.get(e);if(nn(t))return parseInt(t,10)??void 0}},Uv=xl;import{fillWithDefault as mC,VideoQuality as on}from"@vkontakte/videoplayer-shared";var Hv={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:on.Q_4320P,activeVideoAreaThreshold:.1,highQualityLimit:on.Q_720P,trafficSavingLimit:on.Q_480P},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:on.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},jv=i=>({...mC(i,Hv),configName:[...i.configName??[],...Hv.configName]});import{assertNonNullable as un,combine as ht,ErrorCategory as ln,filter as ue,filterChanged as _,fromEvent as Al,isNonNullable as TC,isNullable as IC,Logger as EC,map as O,mapTo as Yv,merge as Ct,now as cn,once as Ze,Subject as q,Subscription as zv,tap as Kv,ValueSubject as I,isHigher as xC,isInvariantQuality as Jv,flattenObject as Dt,throttle as kl,getTraceSubscriptionMethod as Xv,Tracer as PC,InternalsExposure as AC}from"@vkontakte/videoplayer-shared";import{merge as fC,map as bC,filter as Qv,isNonNullable as gC}from"@vkontakte/videoplayer-shared";var Pl=({seekState:i,position$:e})=>fC(i.stateChangeEnded$.pipe(bC(({to:t})=>t.state==="none"?void 0:(t.position??NaN)/1e3),Qv(gC)),e.pipe(Qv(()=>i.getState().state==="none")));import{assertNonNullable as SC}from"@vkontakte/videoplayer-shared";var Gv=i=>{let e=typeof i.container=="string"?document.getElementById(i.container):i.container;return SC(e,`Wrong container or containerId {${i.container}}`),e};import{filter as vC,once as yC}from"@vkontakte/videoplayer-shared";var Wv=(i,e,t,r)=>{i!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&t?.getValue().length===0?t.pipe(vC(a=>a.length>0),yC()).subscribe(a=>{a.find(r)&&e.startTransitionTo(i)}):(i===void 0||t?.getValue().find(r))&&e.startTransitionTo(i)};var dn=class{constructor(e={configName:[]},t=PC.createRootTracer(!1)){this.subscription=new zv;this.logger=new EC;this.abrLogger=this.logger.createComponentLog("ABR");this.internalsExposure=null;this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new I(!1);this.hasLiveOffsetByPausedTimer=0;this.wasSetStartedQuality=!1;this.desiredState={playbackState:new L("stopped"),seekState:new L({state:"none"}),volume:new L({volume:1,muted:!1}),videoTrack:new L(void 0),videoStream:new L(void 0),audioStream:new L(void 0),autoVideoTrackSwitching:new L(!0),autoVideoTrackLimits:new L({}),isLooped:new L(!1),isLowLatency:new L(!1),playbackRate:new L(1),externalTextTracks:new L([]),internalTextTracks:new L([]),currentTextTrack:new L(void 0),textTrackCuesSettings:new L({}),cameraOrientation:new L({x:0,y:0})};this.info={playbackState$:new I("stopped"),position$:new I(0),duration$:new I(1/0),muted$:new I(!1),volume$:new I(1),availableVideoStreams$:new I([]),currentVideoStream$:new I(void 0),availableQualities$:new I([]),availableQualitiesFps$:new I({}),currentQuality$:new I(void 0),isAutoQualityEnabled$:new I(!0),autoQualityLimitingAvailable$:new I(!1),autoQualityLimits$:new I({}),predefinedQualityLimitType$:new I("unknown"),availableAudioStreams$:new I([]),currentAudioStream$:new I(void 0),availableAudioTracks$:new I([]),isAudioAvailable$:new I(!0),currentPlaybackRate$:new I(1),currentBuffer$:new I({start:0,end:0}),isBuffering$:new I(!0),isStalled$:new I(!1),isEnded$:new I(!1),isLooped$:new I(!1),isLive$:new I(void 0),canChangePlaybackSpeed$:new I(void 0),atLiveEdge$:new I(void 0),atLiveDurationEdge$:new I(void 0),liveTime$:new I(void 0),liveBufferTime$:new I(void 0),liveLatency$:new I(void 0),currentFormat$:new I(void 0),availableTextTracks$:new I([]),currentTextTrack$:new I(void 0),throughputEstimation$:new I(void 0),rttEstimation$:new I(void 0),videoBitrate$:new I(void 0),hostname$:new I(void 0),httpConnectionType$:new I(void 0),httpConnectionReused$:new I(void 0),surface$:new I("none"),chromecastState$:new I("NOT_AVAILABLE"),chromecastDeviceName$:new I(void 0),intrinsicVideoSize$:new I(void 0),availableSources$:new I(void 0),is3DVideo$:new I(!1),currentVideoSegmentLength$:new I(0),currentAudioSegmentLength$:new I(0)};this.events={inited$:new q,ready$:new q,started$:new q,playing$:new q,paused$:new q,stopped$:new q,willStart$:new q,willResume$:new q,willPause$:new q,willStop$:new q,willDestruct$:new q,watchCoverageRecord$:new q,watchCoverageLive$:new q,managedError$:new q,fatalError$:new q,ended$:new q,looped$:new q,seeked$:new q,willSeek$:new q,autoplaySoundProhibited$:new q,firstBytes$:new q,loadedMetadata$:new q,firstFrame$:new q,canplay$:new q,log$:new q};this.experimental={element$:new I(void 0),tuningConfigName$:new I([]),enableDebugTelemetry$:new I(!1),dumpTelemetry:ob};if(this.initLogs(),this.tuning=jv(e),this.tracer=t,this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new Ha({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new Uv(this.tuning.throughputEstimator),e.exposeInternalsToGlobal&&(this.internalsExposure=new AC("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(p=>JSON.stringify(p,(h,f)=>{let b=typeof f;return(0,Zv.default)(["number","string","boolean"],b)?f:f===null?null:`<${b}>`})),c=`Player.${String(a)}`,d=`Exception calling ${c} (${l.join(", ")})`;throw this.events.fatalError$.next({id:c,category:ln.WTF,message:d,thrown:u}),u}}}})}initVideo(e){this.config=e;let{container:t,...r}=e;return this.tracer.log("initVideo",Dt(r)),this.domContainer=Gv(e),this.chromecastInitializer.contentId=e.meta?.videoId,this.providerContainer=new Ra({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&&!Ri()?(this.tracer.log("request play from hidden tab"),Al(document,"visibilitychange").pipe(Ze()).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){un(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(ue(r=>r.length>0),Ze()).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",Dt(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){un(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",Dt(e)),this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>({type:"external",...t}))),this}selectTextTrack(e){return Wv(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(IC(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),r=t.state==="none"?void 0:t.position;return TC(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(Ct(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(O(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(O(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(O(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(O(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(O(e=>e.to)).subscribe(e=>{this.info.autoQualityLimits$.next(e);let{highQualityLimit:t,trafficSavingLimit:r}=this.tuning.autoTrackSelection;this.info.predefinedQualityLimitType$.next(Ts({limits:e,highQualityLimit:t,trafficSavingLimit:r}))})),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(ue(({from:e})=>e==="stopped"),Ze()).subscribe(()=>{this.initedAt=cn(),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",Dt(n)),n.state==="requested"?this.desiredState.seekState.setState({...n,state:"applying"}):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:ln.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.soundProhibitedEvent$.pipe(Ze()).subscribe(this.events.autoplaySoundProhibited$)).add(e.providerOutput.seekedEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();this.tracer.log("seekedEvent",Dt(n)),n.state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe(O(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(O(n=>n.destination),_()).subscribe(()=>this.isPlaybackStarted=!1)).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add(ht({availableVideoTracks:e.providerOutput.availableVideoTracks$,currentVideoStream:e.providerOutput.currentVideoStream$}).pipe(O(({availableVideoTracks:n,currentVideoStream:o})=>n.filter(u=>o?o.id===u.streamId:!0).map(({quality:u})=>u).sort((u,l)=>Jv(u)?1:Jv(l)?-1:xC(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(_()).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(_((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.pipe(_((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe(_()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(_()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(_()).subscribe(this.info.httpConnectionReused$)).add(e.providerOutput.currentTextTrack$.subscribe(this.info.currentTextTrack$)).add(e.providerOutput.availableTextTracks$.subscribe(this.info.availableTextTracks$)).add(e.providerOutput.autoVideoTrackLimitingAvailable$.subscribe(this.info.autoQualityLimitingAvailable$)).add(e.providerOutput.autoVideoTrackLimits$.subscribe(n=>{this.desiredState.autoVideoTrackLimits.setState(n??{})})).add(e.providerOutput.currentBuffer$.pipe(O(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(ht({hasLiveOffsetByPaused:Ct(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(O(n=>n.to),_(),O(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(ht({atLiveEdge:ht({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:Pl({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(O(({isLive:n,position:o,isLowLatency:u})=>{let l=this.getActiveLiveDelay(u);return n&&Math.abs(o)<l/1e3}),_(),Kv(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(O(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add(ht({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(O(({isLive:n,position:o,duration:u})=>n&&(Math.abs(u)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),_(),Kv(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(O(n=>n.muted),_()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(O(n=>n.volume),_()).subscribe(this.info.volume$)).add(Pl({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(Ct(e.providerOutput.endedEvent$.pipe(Yv(!0)),e.providerOutput.seekedEvent$.pipe(Yv(!1))).pipe(_()).subscribe(this.info.isEnded$)).add(e.providerOutput.endedEvent$.subscribe(this.events.ended$)).add(e.providerOutput.loopedEvent$.subscribe(this.events.looped$)).add(e.providerError$.subscribe(this.events.managedError$)).add(e.volumeMultiplierError$.subscribe(this.events.managedError$)).add(e.noAvailableProvidersError$.pipe(O(n=>({id:n?`No${n}`:"NoProviders",category:ln.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(Ze(),O(n=>n??cn()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe(Ze(),O(()=>cn()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(Ze(),O(()=>cn()-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 I(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let r=new I(!0);this.subscription.add(e.current$.subscribe(()=>r.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(ue(({to:n})=>n==="playing"),Ze()).subscribe(()=>r.next(!1)));let a=0,s=Ct(e.providerOutput.isBuffering$,t,r).pipe(O(()=>{let n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||r.getValue();return n&&!o}),_());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(Ct(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(Ct(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(O(e=>e?.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){let t=new zv;this.subscription.add(t),this.subscription.add(e.current$.pipe(_((r,a)=>r.provider===a.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(ue(r=>r.length>0),Ze()).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=At(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(Ct(this.desiredState.videoTrack.stateChangeStarted$.pipe(O(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(O(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(O(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(O(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(O(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(O(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(O(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(O(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(O(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;un(this.providerContainer),un(e),nb(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(t=>sb(t)),this.providerContainer.current$.subscribe(({type:t})=>Ei("provider",t)),e.duration$.subscribe(t=>Ei("duration",t)),e.availableVideoTracks$.pipe(ue(t=>!!t.length),Ze()).subscribe(t=>Ei("tracks",t)),this.events.fatalError$.subscribe(new ne("fatalError")),this.events.managedError$.subscribe(new ne("managedError")),e.position$.subscribe(new ne("position")),e.currentVideoTrack$.pipe(O(t=>t?.quality)).subscribe(new ne("quality")),this.info.currentBuffer$.subscribe(new ne("buffer")),e.isBuffering$.subscribe(new ne("isBuffering"))].forEach(t=>this.subscription.add(t)),Ei("codecs",ig())}initTracerSubscription(){let e=Xv(this.tracer.log.bind(this.tracer)),t=Xv(this.tracer.error.bind(this.tracer));this.subscription.add(this.info.playbackState$.subscribe(e("playbackState"))).add(this.info.isLooped$.subscribe(e("isLooped"))).add(this.info.currentPlaybackRate$.pipe(_()).subscribe(e("currentPlaybackRate"))).add(this.info.isAutoQualityEnabled$.subscribe(e("isAutoQualityEnabled"))).add(this.info.autoQualityLimits$.subscribe(e("autoQualityLimits"))).add(this.info.currentFormat$.subscribe(e("currentFormat"))).add(this.info.availableQualities$.subscribe(e("availableQualities"))).add(this.info.availableQualitiesFps$.subscribe(e("availableQualitiesFps"))).add(this.info.availableAudioTracks$.subscribe(e("availableAudioTracks"))).add(this.info.isAudioAvailable$.subscribe(e("isAudioAvailable"))).add(ht({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe(ue(({currentQuality:r,videoBitrate:a})=>!!r&&!!a),_((r,a)=>r.currentQuality===a.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe(ue(r=>r>0),_()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe(ue(r=>r>0),_()).subscribe(e("currentAudioSegmentLength"))).add(this.info.hostname$.subscribe(e("hostname"))).add(this.info.currentTextTrack$.subscribe(e("currentTextTrack"))).add(this.info.availableTextTracks$.subscribe(e("availableTextTracks"))).add(this.info.autoQualityLimitingAvailable$.subscribe(e("autoQualityLimitingAvailable"))).add(ht({currentBuffer:this.info.currentBuffer$.pipe(ue(r=>r.end>0),_((r,a)=>r.end===a.end&&r.start===a.start)),position:this.info.position$.pipe(_())}).pipe(kl(1e3)).subscribe(e("currentBufferAndPosition"))).add(this.info.duration$.pipe(_()).subscribe(e("duration"))).add(this.info.isBuffering$.subscribe(e("isBuffering"))).add(this.info.isLive$.pipe(_()).subscribe(e("isLive"))).add(this.info.canChangePlaybackSpeed$.pipe(_()).subscribe(e("canChangePlaybackSpeed"))).add(ht({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe(ue(({liveTime:r,liveBufferTime:a})=>!!r&&!!a),kl(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe(_(),ue(r=>r===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe(_(),ue(r=>r===!0)).subscribe(e("atLiveDurationEdge"))).add(this.info.muted$.pipe(_()).subscribe(e("muted"))).add(this.info.volume$.pipe(_()).subscribe(e("volume"))).add(this.info.isEnded$.pipe(_(),ue(r=>r===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add(ht({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe(ue(({throughputEstimation:r,rtt:a})=>!!r&&!!a),kl(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe(_(),ue(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:ln.DOM,message:String(a)})})};this.subscription.add(Ct(Al(document,"visibilitychange"),Al(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",Dt({quality:t,availableTracks:Dt(e),track:Dt(r),isAutoQuality:!r})),r?this.desiredState.videoTrack.startTransitionTo(r):this.setAutoQuality(!0)}getActiveLiveDelay(e=!1){return e?this.tuning.live.lowLatencyActiveLiveDelay:this.tuning.live.activeLiveDelay}};import{Subscription as j3,Observable as Q3,Subject as G3,ValueSubject as W3,VideoQuality as Y3}from"@vkontakte/videoplayer-shared";var z3=`@vkontakte/videoplayer-core@${$l}`;export{Ba as ChromecastState,hn as HttpConnectionType,Q3 as Observable,ce as PlaybackState,dn as Player,zr as PredefinedQualityLimits,z3 as SDK_VERSION,G3 as Subject,j3 as Subscription,mn as Surface,$l as VERSION,W3 as ValueSubject,gt as VideoFormat,Y3 as VideoQuality};