@vkontakte/videoplayer-core 2.0.119-dev.c81726f6.0 → 2.0.119-dev.dc40b896.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,10 +1,10 @@
1
1
  /**
2
- * @vkontakte/videoplayer-core v2.0.119-dev.c81726f6.0
3
- * Tue, 10 Dec 2024 13:48:30 GMT
2
+ * @vkontakte/videoplayer-core v2.0.119-dev.dc40b896.0
3
+ * Wed, 11 Dec 2024 12:41:21 GMT
4
4
  * https://st.mycdn.me/static/vkontakte-videoplayer/2-0-119/doc/
5
5
  */
6
6
  var ry=Object.create;var kl=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&&kl(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?kl(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((AC,Rl)=>{"use strict";Rl.exports=function(i){try{return!!i()}catch{return!0}}});var Kr=m((wC,$l)=>{"use strict";var uy=ie();$l.exports=!uy(function(){var i=function(){}.bind();return typeof i!="function"||i.hasOwnProperty("prototype")})});var hn=m((RC,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(($C,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((LC,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((MC,Fl)=>{"use strict";var hy=Nt(),my=J();Fl.exports=function(i){if(hy(i)==="Function")return my(i)}});var G=m((CC,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((DC,Ul)=>{"use strict";var fy=ie();Ul.exports=!fy(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var Ee=m((VC,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((OC,Wl)=>{"use strict";Wl.exports=function(i,e){return{enumerable:!(i&1),configurable:!(i&2),writable:!(i&4),value:e}}});var zl=m((_C,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((NC,Kl)=>{"use strict";Kl.exports=function(i){return i==null}});var St=m((FC,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((qC,Xl)=>{"use strict";var xy=zl(),Py=St();Xl.exports=function(i){return xy(Py(i))}});var xe=m((UC,Zl)=>{"use strict";var ky=G();Zl.exports=function(i){return typeof i=="object"?i!==null:ky(i)}});var mr=m((HC,ec)=>{"use strict";ec.exports={}});var at=m((jC,rc)=>{"use strict";var vn=mr(),yn=Q(),Ay=G(),tc=function(i){return Ay(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((GC,ic)=>{"use strict";var wy=J();ic.exports=wy({}.isPrototypeOf)});var qt=m((QC,nc)=>{"use strict";var Ry=Q(),ac=Ry.navigator,sc=ac&&ac.userAgent;nc.exports=sc?String(sc):""});var In=m((WC,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((YC,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((zC,fc)=>{"use strict";var Cy=En();fc.exports=Cy&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var Pn=m((KC,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((JC,gc)=>{"use strict";var Ny=String;gc.exports=function(i){try{return Ny(i)}catch{return"Object"}}});var Ye=m((XC,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((ZC,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((e0,yc)=>{"use strict";var kn=Ee(),An=G(),wn=xe(),Gy=TypeError;yc.exports=function(i,e){var t,r;if(e==="string"&&An(t=i.toString)&&!wn(r=kn(t,i))||An(t=i.valueOf)&&!wn(r=kn(t,i))||e!=="string"&&An(t=i.toString)&&!wn(r=kn(t,i)))return r;throw new Gy("Can't convert object to primitive value")}});var Ne=m((t0,Ic)=>{"use strict";Ic.exports=!0});var Pc=m((r0,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((i0,wc)=>{"use strict";var Wy=Ne(),Yy=Q(),zy=Pc(),kc="__core-js_shared__",Ac=wc.exports=Yy[kc]||zy(kc,{});(Ac.versions||(Ac.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((a0,$c)=>{"use strict";var Rc=ti();$c.exports=function(i,e){return Rc[i]||(Rc[i]=e||{})}});var fr=m((s0,Lc)=>{"use strict";var Ky=St(),Jy=Object;Lc.exports=function(i){return Jy(Ky(i))}});var Fe=m((n0,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((o0,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((u0,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((l0,_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((c0,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((d0,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((p0,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(),kT=gn(),AT=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 AT(!PT(kT.f,e,t),e[t])}});var Vn=m((m0,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((f0,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((b0,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((g0,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((v0,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((y0,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((T0,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((I0,sd)=>{"use strict";var cI=ad();sd.exports=function(i){var e=+i;return e!==e||e===0?0:cI(e)}});var od=m((E0,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((x0,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((P0,ld)=>{"use strict";var bI=qn();ld.exports=function(i){return bI(i.length)}});var Un=m((k0,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((A0,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(($0,md)=>{"use strict";var PI=at();md.exports=PI});var bd=m((L0,fd)=>{"use strict";hd();var kI=vt();fd.exports=kI("Array","includes")});var Sd=m((M0,gd)=>{"use strict";var AI=bd();gd.exports=AI});var Ke=m((C0,vd)=>{"use strict";var wI=Sd();vd.exports=wI});var Ha=m((G0,Ad)=>{"use strict";var BI=Rn(),OI=$n(),kd=BI("keys");Ad.exports=function(i){return kd[i]||(kd[i]=OI(i))}});var Rd=m((Q0,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((W0,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((Y0,Md)=>{"use strict";Md.exports={}});var Vd=m((z0,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((K0,Bd)=>{"use strict";Bd.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var Yn=m((J0,Od)=>{"use strict";var zI=Vd(),KI=Wn();Od.exports=Object.keys||function(e){return zI(e,KI)}});var zn=m((X0,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(),kE=ze(),AE=Ft(),wE=Yn();ap.f=EE&&!xE?Object.defineProperties:function(e,t){kE(e);for(var r=AE(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 kp=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,Ap)=>{"use strict";var fx=J(),bx=Ye();Ap.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(),kx=Ee(),Xa=Ne(),qp=ro(),Ax=G(),wx=kp(),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):Ax(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 kx(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((kD,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((AD,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(k){return l&&uh(l,"normal",k),new ts(!0,k)},S=function(k){return a?(nP(k),o?u(k[0],k[1],g):u(k[0],k[1])):o?u(k,g):u(k)};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(k){uh(l,"throw",k)}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(),kP=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":kP(di.process)==="process"?"NODE":di.window&&di.document?"BROWSER":"REST"}()});var ss=m((UD,Ph)=>{"use strict";var AP=vo();Ph.exports=AP==="NODE"});var Ah=m((HD,kh)=>{"use strict";var wP=Ut();kh.exports=function(i,e,t){return wP.f(i,e,t)}});var $h=m((jD,Rh)=>{"use strict";var RP=at(),$P=Ah(),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 ek=qt();Wh.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(ek)});var Do=m((ZD,rm)=>{"use strict";var Pe=Q(),tk=hn(),rk=gr(),Yh=G(),ik=Fe(),tm=ie(),zh=io(),ak=jh(),Kh=Na(),sk=Qh(),nk=Po(),ok=ss(),Lo=Pe.setImmediate,Mo=Pe.clearImmediate,uk=Pe.process,ko=Pe.Dispatch,lk=Pe.Function,Jh=Pe.MessageChannel,ck=Pe.String,Ao=0,hi={},Xh="onreadystatechange",mi,Gt,wo,Ro;tm(function(){mi=Pe.location});var Co=function(i){if(ik(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(ck(i),mi.protocol+"//"+mi.host)};(!Lo||!Mo)&&(Lo=function(e){sk(arguments.length,1);var t=Yh(e)?e:lk(e),r=ak(arguments,1);return hi[++Ao]=function(){tk(t,void 0,r)},Gt(Ao),Ao},Mo=function(e){delete hi[e]},ok?Gt=function(i){uk.nextTick($o(i))}:ko&&ko.now?Gt=function(i){ko.now($o(i))}:Jh&&!nk?(wo=new Jh,Ro=wo.port2,wo.port1.onmessage=Zh,Gt=rk(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(),dk=Ie(),pk=Object.getOwnPropertyDescriptor;am.exports=function(i){if(!dk)return im[i];var e=pk(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 hk=qt();um.exports=/ipad|iphone|ipod/i.test(hk)&&typeof Pebble<"u"});var dm=m((iV,cm)=>{"use strict";var mk=qt();cm.exports=/web0s(?!.*chrome)/i.test(mk)});var Sm=m((aV,gm)=>{"use strict";var Pr=Q(),fk=sm(),pm=gr(),Bo=Do().set,bk=Vo(),gk=Po(),Sk=lm(),vk=dm(),Oo=ss(),hm=Pr.MutationObserver||Pr.WebKitMutationObserver,mm=Pr.document,fm=Pr.process,ns=Pr.Promise,Fo=fk("queueMicrotask"),xr,_o,No,os,bm;Fo||(fi=new bk,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()},!gk&&!Oo&&!vk&&hm&&mm?(_o=!0,No=mm.createTextNode(""),new hm(bi).observe(No,{characterData:!0}),xr=function(){No.data=_o=!_o}):!Sk&&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 yk=Q();Im.exports=yk.Promise});var kr=m((uV,km)=>{"use strict";var Tk=Q(),gi=Qt(),Ik=G(),Ek=Vn(),xk=To(),Pk=ae(),Em=vo(),kk=Ne(),qo=In(),xm=gi&&gi.prototype,Ak=Pk("species"),Uo=!1,Pm=Ik(Tk.PromiseRejectionEvent),wk=Ek("Promise",function(){var i=xk(gi),e=i!==String(gi);if(!e&&qo===66||kk&&!(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[Ak]=r,Uo=t.then(function(){})instanceof r,!Uo)return!0}return!e&&(Em==="BROWSER"||Em==="DENO")&&!Pm});km.exports={CONSTRUCTOR:wk,REJECTION_EVENT:Pm,SUBCLASSING:Uo}});var Ar=m((lV,wm)=>{"use strict";var Am=Ye(),Rk=TypeError,$k=function(i){var e,t;this.promise=new i(function(r,a){if(e!==void 0||t!==void 0)throw new Rk("Bad Promise constructor");e=r,t=a}),this.resolve=Am(e),this.reject=Am(t)};wm.exports.f=function(i){return new $k(i)}});var Wm=m(()=>{"use strict";var Lk=z(),Mk=Ne(),ps=ss(),yt=Q(),Lr=Ee(),Rm=Er(),$m=ho(),Ck=ui(),Dk=$h(),Vk=Ye(),ds=G(),Bk=xe(),Ok=Mh(),_k=xo(),Vm=Do().set,Wo=Sm(),Nk=ym(),Fk=us(),qk=Vo(),Bm=Zn(),hs=Qt(),Yo=kr(),Om=Ar(),ms="Promise",_m=Yo.CONSTRUCTOR,Uk=Yo.REJECTION_EVENT,Hk=Yo.SUBCLASSING,Ho=Bm.getterFor(ms),jk=Bm.set,wr=hs&&hs.prototype,Wt=hs,ls=wr,Nm=yt.TypeError,jo=yt.document,zo=yt.process,Go=Om.f,Gk=Go,Qk=!!(jo&&jo.createEvent&&yt.dispatchEvent),Fm="unhandledrejection",Wk="rejectionhandled",Lm=0,qm=1,Yk=2,Ko=1,Um=2,cs,Mm,zk,Cm,Hm=function(i){var e;return Bk(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&&Jk(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&&Kk(i)}))},Qm=function(i,e,t){var r,a;Qk?(r=jo.createEvent("Event"),r.promise=e,r.reason=t,r.initEvent(i,!1,!0),yt.dispatchEvent(r)):r={promise:e,reason:t},!Uk&&(a=yt["on"+i])?a(r):i===Fm&&Nk("Unhandled promise rejection",t)},Kk=function(i){Lr(Vm,yt,function(){var e=i.facade,t=i.value,r=Dm(i),a;if(r&&(a=Fk(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},Jk=function(i){Lr(Vm,yt,function(){var e=i.facade;ps?zo.emit("rejectionHandled",e):Qm(Wk,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=Yk,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){Ok(this,ls),Vk(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){jk(this,{type:ms,done:!1,notified:!1,parent:!1,reactions:new qk,rejection:!1,state:Lm,value:void 0})},cs.prototype=Rm(ls,"then",function(e,t){var r=Ho(this),a=Go(_k(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===zk?new Mm(i):Gk(i)},!Mk&&ds(hs)&&wr!==Object.prototype)){Cm=wr.then,Hk||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)}Lk({global:!0,constructor:!0,wrap:!0,forced:_m},{Promise:Wt});Ck(Wt,ms,!1,!0);Dk(ms)});var Xm=m((pV,Jm)=>{"use strict";var Xk=ae(),zm=Xk("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 Zk=Qt(),eA=Xm(),tA=kr().CONSTRUCTOR;Zm.exports=tA||!eA(function(i){Zk.all(i).then(void 0,function(){})})});var ef=m(()=>{"use strict";var rA=z(),iA=Ee(),aA=Ye(),sA=Ar(),nA=us(),oA=rs(),uA=Xo();rA({target:"Promise",stat:!0,forced:uA},{all:function(e){var t=this,r=sA.f(t),a=r.resolve,s=r.reject,n=nA(function(){var o=aA(t.resolve),u=[],l=0,c=1;oA(e,function(d){var p=l++,h=!1;c++,iA(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 lA=z(),cA=Ne(),dA=kr().CONSTRUCTOR,eu=Qt(),pA=at(),hA=G(),mA=Er(),tf=eu&&eu.prototype;lA({target:"Promise",proto:!0,forced:dA,real:!0},{catch:function(i){return this.then(void 0,i)}});!cA&&hA(eu)&&(Zo=pA("Promise").prototype.catch,tf.catch!==Zo&&mA(tf,"catch",Zo,{unsafe:!0}));var Zo});var af=m(()=>{"use strict";var fA=z(),bA=Ee(),gA=Ye(),SA=Ar(),vA=us(),yA=rs(),TA=Xo();fA({target:"Promise",stat:!0,forced:TA},{race:function(e){var t=this,r=SA.f(t),a=r.reject,s=vA(function(){var n=gA(t.resolve);yA(e,function(o){bA(n,t,o).then(r.resolve,a)})});return s.error&&a(s.value),r.promise}})});var sf=m(()=>{"use strict";var IA=z(),EA=Ar(),xA=kr().CONSTRUCTOR;IA({target:"Promise",stat:!0,forced:xA},{reject:function(e){var t=EA.f(this),r=t.reject;return r(e),t.promise}})});var tu=m((IV,nf)=>{"use strict";var PA=ze(),kA=xe(),AA=Ar();nf.exports=function(i,e){if(PA(i),kA(e)&&e.constructor===i)return e;var t=AA.f(i),r=t.resolve;return r(e),t.promise}});var lf=m(()=>{"use strict";var wA=z(),RA=at(),of=Ne(),$A=Qt(),uf=kr().CONSTRUCTOR,LA=tu(),MA=RA("Promise"),CA=of&&!uf;wA({target:"Promise",stat:!0,forced:of||uf},{resolve:function(e){return LA(CA&&this===MA?$A:this,e)}})});var cf=m(()=>{"use strict";Wm();ef();rf();af();sf();lf()});var mf=m(()=>{"use strict";var DA=z(),VA=Ne(),fs=Qt(),BA=ie(),pf=at(),hf=G(),OA=xo(),df=tu(),_A=Er(),iu=fs&&fs.prototype,NA=!!fs&&BA(function(){iu.finally.call({then:function(){}},function(){})});DA({target:"Promise",proto:!0,real:!0,forced:NA},{finally:function(i){var e=OA(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)}});!VA&&hf(fs)&&(ru=pf("Promise").prototype.finally,iu.finally!==ru&&_A(iu,"finally",ru,{unsafe:!0}));var ru});var bf=m((RV,ff)=>{"use strict";Eh();cf();mf();var FA=vt();ff.exports=FA("Promise","finally")});var Sf=m(($V,gf)=>{"use strict";var qA=bf();gf.exports=qA});var bs=m((LV,vf)=>{"use strict";var UA=Sf();vf.exports=UA});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(),kw=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]}});kw("at")});var Xf=m((GB,Jf)=>{"use strict";Kf();var Aw=vt();Jf.exports=Aw("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 ku=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=ku(),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=ku(),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(),kR=Tr(),AR=Ub();IR({target:"Array",proto:!0},{flatMap:function(e){var t=PR(this),r=kR(t),a;return xR(e),a=AR(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 Au=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(),k$=P$("match");Ug.exports=function(i){var e;return E$(i)&&((e=i[k$])!==void 0?!!e:x$(i)==="RegExp")}});var Gg=m((Iq,jg)=>{"use strict";var A$=ze();jg.exports=function(){var i=A$(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((Aq,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 Al="2.0.119-dev.c81726f6.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 HA,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||HA(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 jA}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 jA(i)}};import{assertNever as Mr,assertNonNullable as Yt,debounce as Ef,ErrorCategory as xf,fromEvent as zt,isNonNullable as Pf,map as kf,merge as Af,observableFrom as GA,Subject as QA,Subscription as au,timeout as WA,getHighestQuality as YA}from"@vkontakte/videoplayer-shared";var zA=5,KA=5,JA=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(Af(this.videoState.stateChangeStarted$.pipe(kf(a=>`stateChangeStarted$ ${JSON.stringify(a)}`)),this.videoState.stateChangeEnded$.pipe(kf(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 QA;e.add(a.pipe(Ef(JA)).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)>zA)&&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<KA&&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=Af(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,GA(["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=YA(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(WA(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 XA}from"@vkontakte/videoplayer-shared";var $f=i=>{try{i.pause(),i.playbackRate=0,XA(i),i.remove()}catch(e){console.error(e)}};import{fromEvent as ZA,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 ZA(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:`
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(),k$=P$("match");Ug.exports=function(i){var e;return E$(i)&&((e=i[k$])!==void 0?!!e:x$(i)==="RegExp")}});var Gg=m((Iq,jg)=>{"use strict";var A$=ze();jg.exports=function(){var i=A$(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((Aq,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 Al="2.0.119-dev.dc40b896.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 HA,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||HA(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 jA}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 jA(i)}};import{assertNever as Mr,assertNonNullable as Yt,debounce as Ef,ErrorCategory as xf,fromEvent as zt,isNonNullable as Pf,map as kf,merge as Af,observableFrom as GA,Subject as QA,Subscription as au,timeout as WA,getHighestQuality as YA}from"@vkontakte/videoplayer-shared";var zA=5,KA=5,JA=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(Af(this.videoState.stateChangeStarted$.pipe(kf(a=>`stateChangeStarted$ ${JSON.stringify(a)}`)),this.videoState.stateChangeEnded$.pipe(kf(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 QA;e.add(a.pipe(Ef(JA)).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)>zA)&&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<KA&&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=Af(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,GA(["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=YA(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(WA(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 XA}from"@vkontakte/videoplayer-shared";var $f=i=>{try{i.pause(),i.playbackRate=0,XA(i),i.remove()}catch(e){console.error(e)}};import{fromEvent as ZA,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 ZA(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:`
8
8
  [last ${o} selected] ${u}
9
9
  `}),n}return r?.recordSwitch(t),t},Cw=(i,e)=>Math.log(e)/Math.log(i),kt=(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,k=i.filter(v=>!sb(v.quality)).sort((v,T)=>mu(v.quality,T.quality)?-1:1),E=(0,Pt.default)(k,-1)?.quality,A=(0,Pt.default)(k,0)?.quality,y=hu(a)||X(a.min)&&X(a.max)&&nb(a.max,a.min)||X(a.min)&&A&&mu(a.min,A)||X(a.max)&&E&&nb(a.max,E),R=S*db(n??.5,r.bitrateFactorAtEmptyBuffer,r.bitrateFactorAtFullBuffer),B={},_=k.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)(k,-1)??i[0];return U.quality!==l?.last?.quality&&f({message:`
10
10
  [VIDEO TRACKS ABR]
@@ -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=kt(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}),k=r?S??n:n??S,E=b&&mb(k,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}),A=this.videoTracksMap.get(k)?.representation,y=E&&this.audioTracksMap.get(E)?.representation;if(A&&y)return[A,y];if(A&&!y&&this.audioTracksMap.size===0)return[A,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?.destroy()}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(k=>parseInt(k,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 kM,ValueSubject as AM,VideoQuality as wM,clientChecker as RM}from"@vkontakte/videoplayer-shared";var Ia=class{constructor(e){this.subscription=new kM;this.videoState=new $("stopped");this.textTracksManager=new Le;this.manifests$=new AM([]);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=kt(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 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 Aa,assertNonNullable as Mt,ErrorCategory as tn,filter as Av,isNonNullable as wv,isNullable as tC,map as rC,merge as iC,once as aC,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 kv}from"@vkontakte/videoplayer-shared";function xv(){return new(window.AudioContext||window.webkitAudioContext)}import{clientChecker as eC}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 ke;this.subscriptions=new XM;this.audioContext=null;this.gainNode=null;this.mediaElementSource=null;this.subscriptions.add(this.provider$.pipe(Pv(s=>!!s.type),kv()).subscribe(({type:s})=>this.subscribe(s)))}static{this.errorId="VolumeMultiplierManager"}subscribe(e){eC.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),kv()).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 sC={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 ka(s);let n=[...wu(!0),...wu(!1)];this.chromecastFormatsIterator=new ka(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(tC(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 Aa(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:{...sC,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 Aa(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 Aa(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return Aa(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 Aa(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(iC(this.providerOutput.error$.pipe(Av(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(rC(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(Av(({to:s})=>s==="playing"),aC()).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 nC,combine as oC,Subscription as Cv,ValueSubject as vl,map as uC,filter as lC,isNonNullable as an,now as we,safeStorage as yl}from"@vkontakte/videoplayer-shared";var cC=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)||cC,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(oC({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(uC(({throughput:a,rtt:s})=>_v(a,s,e.rttPenaltyRequestSize)),lC(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(nC()).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 dC,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=>({...dC(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 SC,isNullable as vC,Logger as yC,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 TC,isInvariantQuality as zv,flattenObject as Dt,throttle as xl,getTraceSubscriptionMethod as Kv,Tracer as IC,InternalsExposure as EC}from"@vkontakte/videoplayer-shared";import{merge as pC,map as hC,filter as Hv,isNonNullable as mC}from"@vkontakte/videoplayer-shared";var Il=({seekState:i,position$:e})=>pC(i.stateChangeEnded$.pipe(hC(({to:t})=>t.state==="none"?void 0:(t.position??NaN)/1e3),Hv(mC)),e.pipe(Hv(()=>i.getState().state==="none")));import{assertNonNullable as fC}from"@vkontakte/videoplayer-shared";var jv=i=>{let e=typeof i.container=="string"?document.getElementById(i.container):i.container;return fC(e,`Wrong container or containerId {${i.container}}`),e};import{filter as bC,once as gC}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(bC(a=>a.length>0),gC()).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=IC.createRootTracer(!1)){this.subscription=new Wv;this.logger=new yC;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 EC("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(vC(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),r=t.state==="none"?void 0:t.position;return SC(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:TC(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=kt(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@${Al}`;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,Al as VERSION,B3 as ValueSubject,gt as VideoFormat,O3 as VideoQuality};
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=kt(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}),k=r?S??n:n??S,E=b&&mb(k,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}),A=this.videoTracksMap.get(k)?.representation,y=E&&this.audioTracksMap.get(E)?.representation;if(A&&y)return[A,y];if(A&&!y&&this.audioTracksMap.size===0)return[A,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(k=>parseInt(k,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 kM,ValueSubject as AM,VideoQuality as wM,clientChecker as RM}from"@vkontakte/videoplayer-shared";var Ia=class{constructor(e){this.subscription=new kM;this.videoState=new $("stopped");this.textTracksManager=new Le;this.manifests$=new AM([]);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=kt(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 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 Aa,assertNonNullable as Mt,ErrorCategory as tn,filter as Av,isNonNullable as wv,isNullable as tC,map as rC,merge as iC,once as aC,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 kv}from"@vkontakte/videoplayer-shared";function xv(){return new(window.AudioContext||window.webkitAudioContext)}import{clientChecker as eC}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 ke;this.subscriptions=new XM;this.audioContext=null;this.gainNode=null;this.mediaElementSource=null;this.subscriptions.add(this.provider$.pipe(Pv(s=>!!s.type),kv()).subscribe(({type:s})=>this.subscribe(s)))}static{this.errorId="VolumeMultiplierManager"}subscribe(e){eC.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),kv()).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 sC={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 ka(s);let n=[...wu(!0),...wu(!1)];this.chromecastFormatsIterator=new ka(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(tC(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 Aa(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:{...sC,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 Aa(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 Aa(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return Aa(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 Aa(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(iC(this.providerOutput.error$.pipe(Av(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(rC(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(Av(({to:s})=>s==="playing"),aC()).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 nC,combine as oC,Subscription as Cv,ValueSubject as vl,map as uC,filter as lC,isNonNullable as an,now as we,safeStorage as yl}from"@vkontakte/videoplayer-shared";var cC=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)||cC,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(oC({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(uC(({throughput:a,rtt:s})=>_v(a,s,e.rttPenaltyRequestSize)),lC(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(nC()).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 dC,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=>({...dC(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 SC,isNullable as vC,Logger as yC,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 TC,isInvariantQuality as zv,flattenObject as Dt,throttle as xl,getTraceSubscriptionMethod as Kv,Tracer as IC,InternalsExposure as EC}from"@vkontakte/videoplayer-shared";import{merge as pC,map as hC,filter as Hv,isNonNullable as mC}from"@vkontakte/videoplayer-shared";var Il=({seekState:i,position$:e})=>pC(i.stateChangeEnded$.pipe(hC(({to:t})=>t.state==="none"?void 0:(t.position??NaN)/1e3),Hv(mC)),e.pipe(Hv(()=>i.getState().state==="none")));import{assertNonNullable as fC}from"@vkontakte/videoplayer-shared";var jv=i=>{let e=typeof i.container=="string"?document.getElementById(i.container):i.container;return fC(e,`Wrong container or containerId {${i.container}}`),e};import{filter as bC,once as gC}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(bC(a=>a.length>0),gC()).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=IC.createRootTracer(!1)){this.subscription=new Wv;this.logger=new yC;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 EC("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(vC(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),r=t.state==="none"?void 0:t.position;return SC(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:TC(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=kt(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 CY,Observable as DY,Subject as VY,ValueSubject as BY,VideoQuality as OY}from"@vkontakte/videoplayer-shared";var _Y=`@vkontakte/videoplayer-core@${Al}`;export{Ba as ChromecastState,cn as HttpConnectionType,DY as Observable,de as PlaybackState,un as Player,_Y as SDK_VERSION,VY as Subject,CY as Subscription,dn as Surface,Al as VERSION,BY as ValueSubject,gt as VideoFormat,OY as VideoQuality};