@vkontakte/videoplayer-core 2.0.116-dev.32c949ec.0 → 2.0.116-dev.d1ccc575.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/es2015.esm.js CHANGED
@@ -1,11 +1,11 @@
1
1
  /**
2
- * @vkontakte/videoplayer-core v2.0.116-dev.32c949ec.0
3
- * Wed, 30 Oct 2024 00:04:03 GMT
2
+ * @vkontakte/videoplayer-core v2.0.116-dev.d1ccc575.0
3
+ * Sat, 02 Nov 2024 12:30:15 GMT
4
4
  * https://st.mycdn.me/static/vkontakte-videoplayer/2-0-116/doc/
5
5
  */
6
- var kv=Object.create;var Rn=Object.defineProperty,Rv=Object.defineProperties,$v=Object.getOwnPropertyDescriptor,Lv=Object.getOwnPropertyDescriptors,Mv=Object.getOwnPropertyNames,Ga=Object.getOwnPropertySymbols,Cv=Object.getPrototypeOf,$n=Object.prototype.hasOwnProperty,hc=Object.prototype.propertyIsEnumerable;var Dv=(a,e)=>(e=Symbol[a])?e:Symbol.for("Symbol."+a);var et=Math.pow,pc=(a,e,t)=>e in a?Rn(a,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):a[e]=t,A=(a,e)=>{for(var t in e||(e={}))$n.call(e,t)&&pc(a,t,e[t]);if(Ga)for(var t of Ga(e))hc.call(e,t)&&pc(a,t,e[t]);return a},D=(a,e)=>Rv(a,Lv(e));var fc=(a,e)=>{var t={};for(var r in a)$n.call(a,r)&&e.indexOf(r)<0&&(t[r]=a[r]);if(a!=null&&Ga)for(var r of Ga(a))e.indexOf(r)<0&&hc.call(a,r)&&(t[r]=a[r]);return t};var m=(a,e)=>()=>(e||a((e={exports:{}}).exports,e),e.exports);var Bv=(a,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Mv(e))!$n.call(a,i)&&i!==t&&Rn(a,i,{get:()=>e[i],enumerable:!(r=$v(e,i))||r.enumerable});return a};var je=(a,e,t)=>(t=a!=null?kv(Cv(a)):{},Bv(e||!a||!a.__esModule?Rn(t,"default",{value:a,enumerable:!0}):t,a));var R=(a,e,t)=>new Promise((r,i)=>{var s=u=>{try{o(t.next(u))}catch(l){i(l)}},n=u=>{try{o(t.throw(u))}catch(l){i(l)}},o=u=>u.done?r(u.value):Promise.resolve(u.value).then(s,n);o((t=t.apply(a,e)).next())}),Ln=function(a,e){this[0]=a,this[1]=e},Z=(a,e,t)=>{var r=(n,o,u,l)=>{try{var c=t[n](o),d=(o=c.value)instanceof Ln,h=c.done;Promise.resolve(d?o[0]:o).then(p=>d?r(n==="return"?n:"next",o[1]?{done:p.done,value:p.value}:p,u,l):u({value:p,done:h})).catch(p=>r("throw",p,u,l))}catch(p){l(p)}},i=n=>s[n]=o=>new Promise((u,l)=>r(n,o,u,l)),s={};return t=t.apply(a,e),s[Dv("asyncIterator")]=()=>s,i("next"),i("throw"),i("return"),s};var Pe=m((BL,Ic)=>{"use strict";Ic.exports=function(a){try{return!!a()}catch(e){return!0}}});var si=m((OL,Ec)=>{"use strict";var Hv=Pe();Ec.exports=!Hv(function(){var a=function(){}.bind();return typeof a!="function"||a.hasOwnProperty("prototype")})});var me=m((VL,Ac)=>{"use strict";var xc=si(),Pc=Function.prototype,On=Pc.call,jv=xc&&Pc.bind.bind(On,On);Ac.exports=xc?jv:function(a){return function(){return On.apply(a,arguments)}}});var yr=m((_L,kc)=>{"use strict";var wc=me(),Gv=wc({}.toString),Wv=wc("".slice);kc.exports=function(a){return Wv(Gv(a),8,-1)}});var $c=m((NL,Rc)=>{"use strict";var Yv=me(),Qv=Pe(),zv=yr(),Vn=Object,Kv=Yv("".split);Rc.exports=Qv(function(){return!Vn("z").propertyIsEnumerable(0)})?function(a){return zv(a)==="String"?Kv(a,""):Vn(a)}:Vn});var Tr=m((FL,Lc)=>{"use strict";Lc.exports=function(a){return a==null}});var ni=m((UL,Mc)=>{"use strict";var Jv=Tr(),Xv=TypeError;Mc.exports=function(a){if(Jv(a))throw new Xv("Can't call method on "+a);return a}});var Ir=m((qL,Cc)=>{"use strict";var Zv=$c(),ey=ni();Cc.exports=function(a){return Zv(ey(a))}});var _n=m((HL,Dc)=>{"use strict";Dc.exports=function(){}});var jt=m((jL,Bc)=>{"use strict";Bc.exports={}});var J=m((Nn,Oc)=>{"use strict";var oi=function(a){return a&&a.Math===Math&&a};Oc.exports=oi(typeof globalThis=="object"&&globalThis)||oi(typeof window=="object"&&window)||oi(typeof self=="object"&&self)||oi(typeof global=="object"&&global)||oi(typeof Nn=="object"&&Nn)||function(){return this}()||Function("return this")()});var K=m((GL,Vc)=>{"use strict";var Fn=typeof document=="object"&&document.all;Vc.exports=typeof Fn=="undefined"&&Fn!==void 0?function(a){return typeof a=="function"||a===Fn}:function(a){return typeof a=="function"}});var Fc=m((WL,Nc)=>{"use strict";var ty=J(),ry=K(),_c=ty.WeakMap;Nc.exports=ry(_c)&&/native code/.test(String(_c))});var Me=m((YL,Uc)=>{"use strict";var iy=K();Uc.exports=function(a){return typeof a=="object"?a!==null:iy(a)}});var Ce=m((QL,qc)=>{"use strict";var ay=Pe();qc.exports=!ay(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var za=m((zL,jc)=>{"use strict";var sy=J(),Hc=Me(),Un=sy.document,ny=Hc(Un)&&Hc(Un.createElement);jc.exports=function(a){return ny?Un.createElement(a):{}}});var qn=m((KL,Gc)=>{"use strict";var oy=Ce(),uy=Pe(),ly=za();Gc.exports=!oy&&!uy(function(){return Object.defineProperty(ly("div"),"a",{get:function(){return 7}}).a!==7})});var Hn=m((JL,Wc)=>{"use strict";var cy=Ce(),dy=Pe();Wc.exports=cy&&dy(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var tt=m((XL,Yc)=>{"use strict";var py=Me(),hy=String,fy=TypeError;Yc.exports=function(a){if(py(a))return a;throw new fy(hy(a)+" is not an object")}});var Ae=m((ZL,Qc)=>{"use strict";var my=si(),Ka=Function.prototype.call;Qc.exports=my?Ka.bind(Ka):function(){return Ka.apply(Ka,arguments)}});var Ja=m((eM,zc)=>{"use strict";zc.exports={}});var ot=m((tM,Jc)=>{"use strict";var jn=Ja(),Gn=J(),by=K(),Kc=function(a){return by(a)?a:void 0};Jc.exports=function(a,e){return arguments.length<2?Kc(jn[a])||Kc(Gn[a]):jn[a]&&jn[a][e]||Gn[a]&&Gn[a][e]}});var ui=m((rM,Xc)=>{"use strict";var gy=me();Xc.exports=gy({}.isPrototypeOf)});var Er=m((iM,td)=>{"use strict";var Sy=J(),Zc=Sy.navigator,ed=Zc&&Zc.userAgent;td.exports=ed?String(ed):""});var Yn=m((aM,od)=>{"use strict";var nd=J(),Wn=Er(),rd=nd.process,id=nd.Deno,ad=rd&&rd.versions||id&&id.version,sd=ad&&ad.v8,Ge,Xa;sd&&(Ge=sd.split("."),Xa=Ge[0]>0&&Ge[0]<4?1:+(Ge[0]+Ge[1]));!Xa&&Wn&&(Ge=Wn.match(/Edge\/(\d+)/),(!Ge||Ge[1]>=74)&&(Ge=Wn.match(/Chrome\/(\d+)/),Ge&&(Xa=+Ge[1])));od.exports=Xa});var Qn=m((sM,ld)=>{"use strict";var ud=Yn(),vy=Pe(),yy=J(),Ty=yy.String;ld.exports=!!Object.getOwnPropertySymbols&&!vy(function(){var a=Symbol("symbol detection");return!Ty(a)||!(Object(a)instanceof Symbol)||!Symbol.sham&&ud&&ud<41})});var zn=m((nM,cd)=>{"use strict";var Iy=Qn();cd.exports=Iy&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var Kn=m((oM,dd)=>{"use strict";var Ey=ot(),xy=K(),Py=ui(),Ay=zn(),wy=Object;dd.exports=Ay?function(a){return typeof a=="symbol"}:function(a){var e=Ey("Symbol");return xy(e)&&Py(e.prototype,wy(a))}});var li=m((uM,pd)=>{"use strict";var ky=String;pd.exports=function(a){try{return ky(a)}catch(e){return"Object"}}});var ut=m((lM,hd)=>{"use strict";var Ry=K(),$y=li(),Ly=TypeError;hd.exports=function(a){if(Ry(a))return a;throw new Ly($y(a)+" is not a function")}});var ci=m((cM,fd)=>{"use strict";var My=ut(),Cy=Tr();fd.exports=function(a,e){var t=a[e];return Cy(t)?void 0:My(t)}});var bd=m((dM,md)=>{"use strict";var Jn=Ae(),Xn=K(),Zn=Me(),Dy=TypeError;md.exports=function(a,e){var t,r;if(e==="string"&&Xn(t=a.toString)&&!Zn(r=Jn(t,a))||Xn(t=a.valueOf)&&!Zn(r=Jn(t,a))||e!=="string"&&Xn(t=a.toString)&&!Zn(r=Jn(t,a)))return r;throw new Dy("Can't convert object to primitive value")}});var We=m((pM,gd)=>{"use strict";gd.exports=!0});var yd=m((hM,vd)=>{"use strict";var Sd=J(),By=Object.defineProperty;vd.exports=function(a,e){try{By(Sd,a,{value:e,configurable:!0,writable:!0})}catch(t){Sd[a]=e}return e}});var di=m((fM,Ed)=>{"use strict";var Oy=We(),Vy=J(),_y=yd(),Td="__core-js_shared__",Id=Ed.exports=Vy[Td]||_y(Td,{});(Id.versions||(Id.versions=[])).push({version:"3.38.0",mode:Oy?"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 eo=m((mM,Pd)=>{"use strict";var xd=di();Pd.exports=function(a,e){return xd[a]||(xd[a]=e||{})}});var pi=m((bM,Ad)=>{"use strict";var Ny=ni(),Fy=Object;Ad.exports=function(a){return Fy(Ny(a))}});var Ye=m((gM,wd)=>{"use strict";var Uy=me(),qy=pi(),Hy=Uy({}.hasOwnProperty);wd.exports=Object.hasOwn||function(e,t){return Hy(qy(e),t)}});var to=m((SM,kd)=>{"use strict";var jy=me(),Gy=0,Wy=Math.random(),Yy=jy(1 .toString);kd.exports=function(a){return"Symbol("+(a===void 0?"":a)+")_"+Yy(++Gy+Wy,36)}});var le=m((vM,$d)=>{"use strict";var Qy=J(),zy=eo(),Rd=Ye(),Ky=to(),Jy=Qn(),Xy=zn(),xr=Qy.Symbol,ro=zy("wks"),Zy=Xy?xr.for||xr:xr&&xr.withoutSetter||Ky;$d.exports=function(a){return Rd(ro,a)||(ro[a]=Jy&&Rd(xr,a)?xr[a]:Zy("Symbol."+a)),ro[a]}});var Dd=m((yM,Cd)=>{"use strict";var eT=Ae(),Ld=Me(),Md=Kn(),tT=ci(),rT=bd(),iT=le(),aT=TypeError,sT=iT("toPrimitive");Cd.exports=function(a,e){if(!Ld(a)||Md(a))return a;var t=tT(a,sT),r;if(t){if(e===void 0&&(e="default"),r=eT(t,a,e),!Ld(r)||Md(r))return r;throw new aT("Can't convert object to primitive value")}return e===void 0&&(e="number"),rT(a,e)}});var io=m((TM,Bd)=>{"use strict";var nT=Dd(),oT=Kn();Bd.exports=function(a){var e=nT(a,"string");return oT(e)?e:e+""}});var Gt=m(Vd=>{"use strict";var uT=Ce(),lT=qn(),cT=Hn(),Za=tt(),Od=io(),dT=TypeError,ao=Object.defineProperty,pT=Object.getOwnPropertyDescriptor,so="enumerable",no="configurable",oo="writable";Vd.f=uT?cT?function(e,t,r){if(Za(e),t=Od(t),Za(r),typeof e=="function"&&t==="prototype"&&"value"in r&&oo in r&&!r[oo]){var i=pT(e,t);i&&i[oo]&&(e[t]=r.value,r={configurable:no in r?r[no]:i[no],enumerable:so in r?r[so]:i[so],writable:!1})}return ao(e,t,r)}:ao:function(e,t,r){if(Za(e),t=Od(t),Za(r),lT)try{return ao(e,t,r)}catch(i){}if("get"in r||"set"in r)throw new dT("Accessors not supported");return"value"in r&&(e[t]=r.value),e}});var hi=m((EM,_d)=>{"use strict";_d.exports=function(a,e){return{enumerable:!(a&1),configurable:!(a&2),writable:!(a&4),value:e}}});var Pr=m((xM,Nd)=>{"use strict";var hT=Ce(),fT=Gt(),mT=hi();Nd.exports=hT?function(a,e,t){return fT.f(a,e,mT(1,t))}:function(a,e,t){return a[e]=t,a}});var es=m((PM,Ud)=>{"use strict";var bT=eo(),gT=to(),Fd=bT("keys");Ud.exports=function(a){return Fd[a]||(Fd[a]=gT(a))}});var ts=m((AM,qd)=>{"use strict";qd.exports={}});var po=m((wM,Gd)=>{"use strict";var ST=Fc(),jd=J(),vT=Me(),yT=Pr(),uo=Ye(),lo=di(),TT=es(),IT=ts(),Hd="Object already initialized",co=jd.TypeError,ET=jd.WeakMap,rs,fi,is,xT=function(a){return is(a)?fi(a):rs(a,{})},PT=function(a){return function(e){var t;if(!vT(e)||(t=fi(e)).type!==a)throw new co("Incompatible receiver, "+a+" required");return t}};ST||lo.state?(Qe=lo.state||(lo.state=new ET),Qe.get=Qe.get,Qe.has=Qe.has,Qe.set=Qe.set,rs=function(a,e){if(Qe.has(a))throw new co(Hd);return e.facade=a,Qe.set(a,e),e},fi=function(a){return Qe.get(a)||{}},is=function(a){return Qe.has(a)}):(Wt=TT("state"),IT[Wt]=!0,rs=function(a,e){if(uo(a,Wt))throw new co(Hd);return e.facade=a,yT(a,Wt,e),e},fi=function(a){return uo(a,Wt)?a[Wt]:{}},is=function(a){return uo(a,Wt)});var Qe,Wt;Gd.exports={set:rs,get:fi,has:is,enforce:xT,getterFor:PT}});var ho=m((kM,zd)=>{"use strict";var AT=si(),Qd=Function.prototype,Wd=Qd.apply,Yd=Qd.call;zd.exports=typeof Reflect=="object"&&Reflect.apply||(AT?Yd.bind(Wd):function(){return Yd.apply(Wd,arguments)})});var fo=m((RM,Kd)=>{"use strict";var wT=yr(),kT=me();Kd.exports=function(a){if(wT(a)==="Function")return kT(a)}});var ep=m(Zd=>{"use strict";var Jd={}.propertyIsEnumerable,Xd=Object.getOwnPropertyDescriptor,RT=Xd&&!Jd.call({1:2},1);Zd.f=RT?function(e){var t=Xd(this,e);return!!t&&t.enumerable}:Jd});var ip=m(rp=>{"use strict";var $T=Ce(),LT=Ae(),MT=ep(),CT=hi(),DT=Ir(),BT=io(),OT=Ye(),VT=qn(),tp=Object.getOwnPropertyDescriptor;rp.f=$T?tp:function(e,t){if(e=DT(e),t=BT(t),VT)try{return tp(e,t)}catch(r){}if(OT(e,t))return CT(!LT(MT.f,e,t),e[t])}});var mo=m((MM,ap)=>{"use strict";var _T=Pe(),NT=K(),FT=/#|\.prototype\./,mi=function(a,e){var t=qT[UT(a)];return t===jT?!0:t===HT?!1:NT(e)?_T(e):!!e},UT=mi.normalize=function(a){return String(a).replace(FT,".").toLowerCase()},qT=mi.data={},HT=mi.NATIVE="N",jT=mi.POLYFILL="P";ap.exports=mi});var bi=m((CM,np)=>{"use strict";var sp=fo(),GT=ut(),WT=si(),YT=sp(sp.bind);np.exports=function(a,e){return GT(a),e===void 0?a:WT?YT(a,e):function(){return a.apply(e,arguments)}}});var De=m((DM,up)=>{"use strict";var gi=J(),QT=ho(),zT=fo(),KT=K(),JT=ip().f,XT=mo(),Ar=Ja(),ZT=bi(),wr=Pr(),op=Ye();di();var eI=function(a){var e=function(t,r,i){if(this instanceof e){switch(arguments.length){case 0:return new a;case 1:return new a(t);case 2:return new a(t,r)}return new a(t,r,i)}return QT(a,this,arguments)};return e.prototype=a.prototype,e};up.exports=function(a,e){var t=a.target,r=a.global,i=a.stat,s=a.proto,n=r?gi:i?gi[t]:gi[t]&&gi[t].prototype,o=r?Ar:Ar[t]||wr(Ar,t,{})[t],u=o.prototype,l,c,d,h,p,f,b,g,S;for(h in e)l=XT(r?h:t+(i?".":"#")+h,a.forced),c=!l&&n&&op(n,h),f=o[h],c&&(a.dontCallGetSet?(S=JT(n,h),b=S&&S.value):b=n[h]),p=c&&b?b:e[h],!(!l&&!s&&typeof f==typeof p)&&(a.bind&&c?g=ZT(p,gi):a.wrap&&c?g=eI(p):s&&KT(p)?g=zT(p):g=p,(a.sham||p&&p.sham||f&&f.sham)&&wr(g,"sham",!0),wr(o,h,g),s&&(d=t+"Prototype",op(Ar,d)||wr(Ar,d,{}),wr(Ar[d],h,p),a.real&&u&&(l||!u[h])&&wr(u,h,p)))}});var dp=m((BM,cp)=>{"use strict";var bo=Ce(),tI=Ye(),lp=Function.prototype,rI=bo&&Object.getOwnPropertyDescriptor,go=tI(lp,"name"),iI=go&&function(){}.name==="something",aI=go&&(!bo||bo&&rI(lp,"name").configurable);cp.exports={EXISTS:go,PROPER:iI,CONFIGURABLE:aI}});var hp=m((OM,pp)=>{"use strict";var sI=Math.ceil,nI=Math.floor;pp.exports=Math.trunc||function(e){var t=+e;return(t>0?nI:sI)(t)}});var as=m((VM,fp)=>{"use strict";var oI=hp();fp.exports=function(a){var e=+a;return e!==e||e===0?0:oI(e)}});var bp=m((_M,mp)=>{"use strict";var uI=as(),lI=Math.max,cI=Math.min;mp.exports=function(a,e){var t=uI(a);return t<0?lI(t+e,0):cI(t,e)}});var Sp=m((NM,gp)=>{"use strict";var dI=as(),pI=Math.min;gp.exports=function(a){var e=dI(a);return e>0?pI(e,9007199254740991):0}});var ss=m((FM,vp)=>{"use strict";var hI=Sp();vp.exports=function(a){return hI(a.length)}});var Ip=m((UM,Tp)=>{"use strict";var fI=Ir(),mI=bp(),bI=ss(),yp=function(a){return function(e,t,r){var i=fI(e),s=bI(i);if(s===0)return!a&&-1;var n=mI(r,s),o;if(a&&t!==t){for(;s>n;)if(o=i[n++],o!==o)return!0}else for(;s>n;n++)if((a||n in i)&&i[n]===t)return a||n||0;return!a&&-1}};Tp.exports={includes:yp(!0),indexOf:yp(!1)}});var Pp=m((qM,xp)=>{"use strict";var gI=me(),So=Ye(),SI=Ir(),vI=Ip().indexOf,yI=ts(),Ep=gI([].push);xp.exports=function(a,e){var t=SI(a),r=0,i=[],s;for(s in t)!So(yI,s)&&So(t,s)&&Ep(i,s);for(;e.length>r;)So(t,s=e[r++])&&(~vI(i,s)||Ep(i,s));return i}});var vo=m((HM,Ap)=>{"use strict";Ap.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var kp=m((jM,wp)=>{"use strict";var TI=Pp(),II=vo();wp.exports=Object.keys||function(e){return TI(e,II)}});var $p=m(Rp=>{"use strict";var EI=Ce(),xI=Hn(),PI=Gt(),AI=tt(),wI=Ir(),kI=kp();Rp.f=EI&&!xI?Object.defineProperties:function(e,t){AI(e);for(var r=wI(t),i=kI(t),s=i.length,n=0,o;s>n;)PI.f(e,o=i[n++],r[o]);return e}});var yo=m((WM,Lp)=>{"use strict";var RI=ot();Lp.exports=RI("document","documentElement")});var xo=m((YM,_p)=>{"use strict";var $I=tt(),LI=$p(),Mp=vo(),MI=ts(),CI=yo(),DI=za(),BI=es(),Cp=">",Dp="<",Io="prototype",Eo="script",Op=BI("IE_PROTO"),To=function(){},Vp=function(a){return Dp+Eo+Cp+a+Dp+"/"+Eo+Cp},Bp=function(a){a.write(Vp("")),a.close();var e=a.parentWindow.Object;return a=null,e},OI=function(){var a=DI("iframe"),e="java"+Eo+":",t;return a.style.display="none",CI.appendChild(a),a.src=String(e),t=a.contentWindow.document,t.open(),t.write(Vp("document.F=Object")),t.close(),t.F},ns,os=function(){try{ns=new ActiveXObject("htmlfile")}catch(e){}os=typeof document!="undefined"?document.domain&&ns?Bp(ns):OI():Bp(ns);for(var a=Mp.length;a--;)delete os[Io][Mp[a]];return os()};MI[Op]=!0;_p.exports=Object.create||function(e,t){var r;return e!==null?(To[Io]=$I(e),r=new To,To[Io]=null,r[Op]=e):r=os(),t===void 0?r:LI.f(r,t)}});var Fp=m((QM,Np)=>{"use strict";var VI=Pe();Np.exports=!VI(function(){function a(){}return a.prototype.constructor=null,Object.getPrototypeOf(new a)!==a.prototype})});var Ao=m((zM,qp)=>{"use strict";var _I=Ye(),NI=K(),FI=pi(),UI=es(),qI=Fp(),Up=UI("IE_PROTO"),Po=Object,HI=Po.prototype;qp.exports=qI?Po.getPrototypeOf:function(a){var e=FI(a);if(_I(e,Up))return e[Up];var t=e.constructor;return NI(t)&&e instanceof t?t.prototype:e instanceof Po?HI:null}});var kr=m((KM,Hp)=>{"use strict";var jI=Pr();Hp.exports=function(a,e,t,r){return r&&r.enumerable?a[e]=t:jI(a,e,t),a}});var $o=m((JM,Wp)=>{"use strict";var GI=Pe(),WI=K(),YI=Me(),QI=xo(),jp=Ao(),zI=kr(),KI=le(),JI=We(),Ro=KI("iterator"),Gp=!1,lt,wo,ko;[].keys&&(ko=[].keys(),"next"in ko?(wo=jp(jp(ko)),wo!==Object.prototype&&(lt=wo)):Gp=!0);var XI=!YI(lt)||GI(function(){var a={};return lt[Ro].call(a)!==a});XI?lt={}:JI&&(lt=QI(lt));WI(lt[Ro])||zI(lt,Ro,function(){return this});Wp.exports={IteratorPrototype:lt,BUGGY_SAFARI_ITERATORS:Gp}});var us=m((XM,Qp)=>{"use strict";var ZI=le(),eE=ZI("toStringTag"),Yp={};Yp[eE]="z";Qp.exports=String(Yp)==="[object z]"});var Si=m((ZM,zp)=>{"use strict";var tE=us(),rE=K(),ls=yr(),iE=le(),aE=iE("toStringTag"),sE=Object,nE=ls(function(){return arguments}())==="Arguments",oE=function(a,e){try{return a[e]}catch(t){}};zp.exports=tE?ls:function(a){var e,t,r;return a===void 0?"Undefined":a===null?"Null":typeof(t=oE(e=sE(a),aE))=="string"?t:nE?ls(e):(r=ls(e))==="Object"&&rE(e.callee)?"Arguments":r}});var Jp=m((eC,Kp)=>{"use strict";var uE=us(),lE=Si();Kp.exports=uE?{}.toString:function(){return"[object "+lE(this)+"]"}});var vi=m((tC,Zp)=>{"use strict";var cE=us(),dE=Gt().f,pE=Pr(),hE=Ye(),fE=Jp(),mE=le(),Xp=mE("toStringTag");Zp.exports=function(a,e,t,r){var i=t?a:a&&a.prototype;i&&(hE(i,Xp)||dE(i,Xp,{configurable:!0,value:e}),r&&!cE&&pE(i,"toString",fE))}});var th=m((rC,eh)=>{"use strict";var bE=$o().IteratorPrototype,gE=xo(),SE=hi(),vE=vi(),yE=jt(),TE=function(){return this};eh.exports=function(a,e,t,r){var i=e+" Iterator";return a.prototype=gE(bE,{next:SE(+!r,t)}),vE(a,i,!1,!0),yE[i]=TE,a}});var ih=m((iC,rh)=>{"use strict";var IE=me(),EE=ut();rh.exports=function(a,e,t){try{return IE(EE(Object.getOwnPropertyDescriptor(a,e)[t]))}catch(r){}}});var sh=m((aC,ah)=>{"use strict";var xE=Me();ah.exports=function(a){return xE(a)||a===null}});var oh=m((sC,nh)=>{"use strict";var PE=sh(),AE=String,wE=TypeError;nh.exports=function(a){if(PE(a))return a;throw new wE("Can't set "+AE(a)+" as a prototype")}});var Lo=m((nC,uh)=>{"use strict";var kE=ih(),RE=Me(),$E=ni(),LE=oh();uh.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var a=!1,e={},t;try{t=kE(Object.prototype,"__proto__","set"),t(e,[]),a=e instanceof Array}catch(r){}return function(i,s){return $E(i),LE(s),RE(i)&&(a?t(i,s):i.__proto__=s),i}}():void 0)});var vh=m((oC,Sh)=>{"use strict";var ME=De(),CE=Ae(),cs=We(),bh=dp(),DE=K(),BE=th(),lh=Ao(),ch=Lo(),OE=vi(),VE=Pr(),Mo=kr(),_E=le(),dh=jt(),gh=$o(),NE=bh.PROPER,FE=bh.CONFIGURABLE,ph=gh.IteratorPrototype,ds=gh.BUGGY_SAFARI_ITERATORS,yi=_E("iterator"),hh="keys",Ti="values",fh="entries",mh=function(){return this};Sh.exports=function(a,e,t,r,i,s,n){BE(t,e,r);var o=function(S){if(S===i&&h)return h;if(!ds&&S&&S in c)return c[S];switch(S){case hh:return function(){return new t(this,S)};case Ti:return function(){return new t(this,S)};case fh:return function(){return new t(this,S)}}return function(){return new t(this)}},u=e+" Iterator",l=!1,c=a.prototype,d=c[yi]||c["@@iterator"]||i&&c[i],h=!ds&&d||o(i),p=e==="Array"&&c.entries||d,f,b,g;if(p&&(f=lh(p.call(new a)),f!==Object.prototype&&f.next&&(!cs&&lh(f)!==ph&&(ch?ch(f,ph):DE(f[yi])||Mo(f,yi,mh)),OE(f,u,!0,!0),cs&&(dh[u]=mh))),NE&&i===Ti&&d&&d.name!==Ti&&(!cs&&FE?VE(c,"name",Ti):(l=!0,h=function(){return CE(d,this)})),i)if(b={values:o(Ti),keys:s?h:o(hh),entries:o(fh)},n)for(g in b)(ds||l||!(g in c))&&Mo(c,g,b[g]);else ME({target:e,proto:!0,forced:ds||l},b);return(!cs||n)&&c[yi]!==h&&Mo(c,yi,h,{name:i}),dh[e]=h,b}});var Th=m((uC,yh)=>{"use strict";yh.exports=function(a,e){return{value:a,done:e}}});var Do=m((lC,Ah)=>{"use strict";var UE=Ir(),Co=_n(),Ih=jt(),xh=po(),qE=Gt().f,HE=vh(),ps=Th(),jE=We(),GE=Ce(),Ph="Array Iterator",WE=xh.set,YE=xh.getterFor(Ph);Ah.exports=HE(Array,"Array",function(a,e){WE(this,{type:Ph,target:UE(a),index:0,kind:e})},function(){var a=YE(this),e=a.target,t=a.index++;if(!e||t>=e.length)return a.target=void 0,ps(void 0,!0);switch(a.kind){case"keys":return ps(t,!1);case"values":return ps(e[t],!1)}return ps([t,e[t]],!1)},"values");var Eh=Ih.Arguments=Ih.Array;Co("keys");Co("values");Co("entries");if(!jE&&GE&&Eh.name!=="values")try{qE(Eh,"name",{value:"values"})}catch(a){}});var kh=m((cC,wh)=>{"use strict";var QE=le(),zE=jt(),KE=QE("iterator"),JE=Array.prototype;wh.exports=function(a){return a!==void 0&&(zE.Array===a||JE[KE]===a)}});var Bo=m((dC,$h)=>{"use strict";var XE=Si(),Rh=ci(),ZE=Tr(),ex=jt(),tx=le(),rx=tx("iterator");$h.exports=function(a){if(!ZE(a))return Rh(a,rx)||Rh(a,"@@iterator")||ex[XE(a)]}});var Mh=m((pC,Lh)=>{"use strict";var ix=Ae(),ax=ut(),sx=tt(),nx=li(),ox=Bo(),ux=TypeError;Lh.exports=function(a,e){var t=arguments.length<2?ox(a):e;if(ax(t))return sx(ix(t,a));throw new ux(nx(a)+" is not iterable")}});var Bh=m((hC,Dh)=>{"use strict";var lx=Ae(),Ch=tt(),cx=ci();Dh.exports=function(a,e,t){var r,i;Ch(a);try{if(r=cx(a,"return"),!r){if(e==="throw")throw t;return t}r=lx(r,a)}catch(s){i=!0,r=s}if(e==="throw")throw t;if(i)throw r;return Ch(r),t}});var fs=m((fC,Nh)=>{"use strict";var dx=bi(),px=Ae(),hx=tt(),fx=li(),mx=kh(),bx=ss(),Oh=ui(),gx=Mh(),Sx=Bo(),Vh=Bh(),vx=TypeError,hs=function(a,e){this.stopped=a,this.result=e},_h=hs.prototype;Nh.exports=function(a,e,t){var r=t&&t.that,i=!!(t&&t.AS_ENTRIES),s=!!(t&&t.IS_RECORD),n=!!(t&&t.IS_ITERATOR),o=!!(t&&t.INTERRUPTED),u=dx(e,r),l,c,d,h,p,f,b,g=function(y){return l&&Vh(l,"normal",y),new hs(!0,y)},S=function(y){return i?(hx(y),o?u(y[0],y[1],g):u(y[0],y[1])):o?u(y,g):u(y)};if(s)l=a.iterator;else if(n)l=a;else{if(c=Sx(a),!c)throw new vx(fx(a)+" is not iterable");if(mx(c)){for(d=0,h=bx(a);h>d;d++)if(p=S(a[d]),p&&Oh(_h,p))return p;return new hs(!1)}l=gx(a,c)}for(f=s?a.next:l.next;!(b=px(f,l)).done;){try{p=S(b.value)}catch(y){Vh(l,"throw",y)}if(typeof p=="object"&&p&&Oh(_h,p))return p}return new hs(!1)}});var Uh=m((mC,Fh)=>{"use strict";var yx=Ce(),Tx=Gt(),Ix=hi();Fh.exports=function(a,e,t){yx?Tx.f(a,e,Ix(0,t)):a[e]=t}});var qh=m(()=>{"use strict";var Ex=De(),xx=fs(),Px=Uh();Ex({target:"Object",stat:!0},{fromEntries:function(e){var t={};return xx(e,function(r,i){Px(t,r,i)},{AS_ENTRIES:!0}),t}})});var jh=m((SC,Hh)=>{"use strict";Do();qh();var Ax=Ja();Hh.exports=Ax.Object.fromEntries});var Wh=m((vC,Gh)=>{"use strict";Gh.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 Qh=m(()=>{"use strict";Do();var wx=Wh(),kx=J(),Rx=vi(),Yh=jt();for(ms in wx)Rx(kx[ms],ms),Yh[ms]=Yh.Array;var ms});var Kh=m((IC,zh)=>{"use strict";var $x=jh();Qh();zh.exports=$x});var Oo=m((EC,Jh)=>{"use strict";var Lx=Kh();Jh.exports=Lx});var Xh=m(()=>{"use strict"});var Vo=m((AC,Zh)=>{"use strict";var Ii=J(),Mx=Er(),Cx=yr(),bs=function(a){return Mx.slice(0,a.length)===a};Zh.exports=function(){return bs("Bun/")?"BUN":bs("Cloudflare-Workers")?"CLOUDFLARE":bs("Deno/")?"DENO":bs("Node.js/")?"NODE":Ii.Bun&&typeof Bun.version=="string"?"BUN":Ii.Deno&&typeof Deno.version=="object"?"DENO":Cx(Ii.process)==="process"?"NODE":Ii.window&&Ii.document?"BROWSER":"REST"}()});var gs=m((wC,ef)=>{"use strict";var Dx=Vo();ef.exports=Dx==="NODE"});var rf=m((kC,tf)=>{"use strict";var Bx=Gt();tf.exports=function(a,e,t){return Bx.f(a,e,t)}});var nf=m((RC,sf)=>{"use strict";var Ox=ot(),Vx=rf(),_x=le(),Nx=Ce(),af=_x("species");sf.exports=function(a){var e=Ox(a);Nx&&e&&!e[af]&&Vx(e,af,{configurable:!0,get:function(){return this}})}});var uf=m(($C,of)=>{"use strict";var Fx=ui(),Ux=TypeError;of.exports=function(a,e){if(Fx(e,a))return a;throw new Ux("Incorrect invocation")}});var No=m((LC,lf)=>{"use strict";var qx=me(),Hx=K(),_o=di(),jx=qx(Function.toString);Hx(_o.inspectSource)||(_o.inspectSource=function(a){return jx(a)});lf.exports=_o.inspectSource});var mf=m((MC,ff)=>{"use strict";var Gx=me(),Wx=Pe(),cf=K(),Yx=Si(),Qx=ot(),zx=No(),df=function(){},pf=Qx("Reflect","construct"),Fo=/^\s*(?:class|function)\b/,Kx=Gx(Fo.exec),Jx=!Fo.test(df),Ei=function(e){if(!cf(e))return!1;try{return pf(df,[],e),!0}catch(t){return!1}},hf=function(e){if(!cf(e))return!1;switch(Yx(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return Jx||!!Kx(Fo,zx(e))}catch(t){return!0}};hf.sham=!0;ff.exports=!pf||Wx(function(){var a;return Ei(Ei.call)||!Ei(Object)||!Ei(function(){a=!0})||a})?hf:Ei});var gf=m((CC,bf)=>{"use strict";var Xx=mf(),Zx=li(),eP=TypeError;bf.exports=function(a){if(Xx(a))return a;throw new eP(Zx(a)+" is not a constructor")}});var Uo=m((DC,vf)=>{"use strict";var Sf=tt(),tP=gf(),rP=Tr(),iP=le(),aP=iP("species");vf.exports=function(a,e){var t=Sf(a).constructor,r;return t===void 0||rP(r=Sf(t)[aP])?e:tP(r)}});var Tf=m((BC,yf)=>{"use strict";var sP=me();yf.exports=sP([].slice)});var Ef=m((OC,If)=>{"use strict";var nP=TypeError;If.exports=function(a,e){if(a<e)throw new nP("Not enough arguments");return a}});var qo=m((VC,xf)=>{"use strict";var oP=Er();xf.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(oP)});var Jo=m((_C,Cf)=>{"use strict";var we=J(),uP=ho(),lP=bi(),Pf=K(),cP=Ye(),Mf=Pe(),Af=yo(),dP=Tf(),wf=za(),pP=Ef(),hP=qo(),fP=gs(),Qo=we.setImmediate,zo=we.clearImmediate,mP=we.process,Ho=we.Dispatch,bP=we.Function,kf=we.MessageChannel,gP=we.String,jo=0,xi={},Rf="onreadystatechange",Pi,Yt,Go,Wo;Mf(function(){Pi=we.location});var Ko=function(a){if(cP(xi,a)){var e=xi[a];delete xi[a],e()}},Yo=function(a){return function(){Ko(a)}},$f=function(a){Ko(a.data)},Lf=function(a){we.postMessage(gP(a),Pi.protocol+"//"+Pi.host)};(!Qo||!zo)&&(Qo=function(e){pP(arguments.length,1);var t=Pf(e)?e:bP(e),r=dP(arguments,1);return xi[++jo]=function(){uP(t,void 0,r)},Yt(jo),jo},zo=function(e){delete xi[e]},fP?Yt=function(a){mP.nextTick(Yo(a))}:Ho&&Ho.now?Yt=function(a){Ho.now(Yo(a))}:kf&&!hP?(Go=new kf,Wo=Go.port2,Go.port1.onmessage=$f,Yt=lP(Wo.postMessage,Wo)):we.addEventListener&&Pf(we.postMessage)&&!we.importScripts&&Pi&&Pi.protocol!=="file:"&&!Mf(Lf)?(Yt=Lf,we.addEventListener("message",$f,!1)):Rf in wf("script")?Yt=function(a){Af.appendChild(wf("script"))[Rf]=function(){Af.removeChild(this),Ko(a)}}:Yt=function(a){setTimeout(Yo(a),0)});Cf.exports={set:Qo,clear:zo}});var Of=m((NC,Bf)=>{"use strict";var Df=J(),SP=Ce(),vP=Object.getOwnPropertyDescriptor;Bf.exports=function(a){if(!SP)return Df[a];var e=vP(Df,a);return e&&e.value}});var Xo=m((FC,_f)=>{"use strict";var Vf=function(){this.head=null,this.tail=null};Vf.prototype={add:function(a){var e={item:a,next:null},t=this.tail;t?t.next=e:this.head=e,this.tail=e},get:function(){var a=this.head;if(a){var e=this.head=a.next;return e===null&&(this.tail=null),a.item}}};_f.exports=Vf});var Ff=m((UC,Nf)=>{"use strict";var yP=Er();Nf.exports=/ipad|iphone|ipod/i.test(yP)&&typeof Pebble!="undefined"});var qf=m((qC,Uf)=>{"use strict";var TP=Er();Uf.exports=/web0s(?!.*chrome)/i.test(TP)});var zf=m((HC,Qf)=>{"use strict";var $r=J(),IP=Of(),Hf=bi(),Zo=Jo().set,EP=Xo(),xP=qo(),PP=Ff(),AP=qf(),eu=gs(),jf=$r.MutationObserver||$r.WebKitMutationObserver,Gf=$r.document,Wf=$r.process,Ss=$r.Promise,iu=IP("queueMicrotask"),Rr,tu,ru,vs,Yf;iu||(Ai=new EP,wi=function(){var a,e;for(eu&&(a=Wf.domain)&&a.exit();e=Ai.get();)try{e()}catch(t){throw Ai.head&&Rr(),t}a&&a.enter()},!xP&&!eu&&!AP&&jf&&Gf?(tu=!0,ru=Gf.createTextNode(""),new jf(wi).observe(ru,{characterData:!0}),Rr=function(){ru.data=tu=!tu}):!PP&&Ss&&Ss.resolve?(vs=Ss.resolve(void 0),vs.constructor=Ss,Yf=Hf(vs.then,vs),Rr=function(){Yf(wi)}):eu?Rr=function(){Wf.nextTick(wi)}:(Zo=Hf(Zo,$r),Rr=function(){Zo(wi)}),iu=function(a){Ai.head||Rr(),Ai.add(a)});var Ai,wi;Qf.exports=iu});var Jf=m((jC,Kf)=>{"use strict";Kf.exports=function(a,e){try{arguments.length===1?console.error(a):console.error(a,e)}catch(t){}}});var ys=m((GC,Xf)=>{"use strict";Xf.exports=function(a){try{return{error:!1,value:a()}}catch(e){return{error:!0,value:e}}}});var Qt=m((WC,Zf)=>{"use strict";var wP=J();Zf.exports=wP.Promise});var Lr=m((YC,im)=>{"use strict";var kP=J(),ki=Qt(),RP=K(),$P=mo(),LP=No(),MP=le(),em=Vo(),CP=We(),au=Yn(),tm=ki&&ki.prototype,DP=MP("species"),su=!1,rm=RP(kP.PromiseRejectionEvent),BP=$P("Promise",function(){var a=LP(ki),e=a!==String(ki);if(!e&&au===66||CP&&!(tm.catch&&tm.finally))return!0;if(!au||au<51||!/native code/.test(a)){var t=new ki(function(s){s(1)}),r=function(s){s(function(){},function(){})},i=t.constructor={};if(i[DP]=r,su=t.then(function(){})instanceof r,!su)return!0}return!e&&(em==="BROWSER"||em==="DENO")&&!rm});im.exports={CONSTRUCTOR:BP,REJECTION_EVENT:rm,SUBCLASSING:su}});var Mr=m((QC,sm)=>{"use strict";var am=ut(),OP=TypeError,VP=function(a){var e,t;this.promise=new a(function(r,i){if(e!==void 0||t!==void 0)throw new OP("Bad Promise constructor");e=r,t=i}),this.resolve=am(e),this.reject=am(t)};sm.exports.f=function(a){return new VP(a)}});var xm=m(()=>{"use strict";var _P=De(),NP=We(),xs=gs(),Pt=J(),Or=Ae(),nm=kr(),om=Lo(),FP=vi(),UP=nf(),qP=ut(),Es=K(),HP=Me(),jP=uf(),GP=Uo(),pm=Jo().set,cu=zf(),WP=Jf(),YP=ys(),QP=Xo(),hm=po(),Ps=Qt(),du=Lr(),fm=Mr(),As="Promise",mm=du.CONSTRUCTOR,zP=du.REJECTION_EVENT,KP=du.SUBCLASSING,nu=hm.getterFor(As),JP=hm.set,Cr=Ps&&Ps.prototype,zt=Ps,Ts=Cr,bm=Pt.TypeError,ou=Pt.document,pu=Pt.process,uu=fm.f,XP=uu,ZP=!!(ou&&ou.createEvent&&Pt.dispatchEvent),gm="unhandledrejection",eA="rejectionhandled",um=0,Sm=1,tA=2,hu=1,vm=2,Is,lm,rA,cm,ym=function(a){var e;return HP(a)&&Es(e=a.then)?e:!1},Tm=function(a,e){var t=e.value,r=e.state===Sm,i=r?a.ok:a.fail,s=a.resolve,n=a.reject,o=a.domain,u,l,c;try{i?(r||(e.rejection===vm&&aA(e),e.rejection=hu),i===!0?u=t:(o&&o.enter(),u=i(t),o&&(o.exit(),c=!0)),u===a.promise?n(new bm("Promise-chain cycle")):(l=ym(u))?Or(l,u,s,n):s(u)):n(t)}catch(d){o&&!c&&o.exit(),n(d)}},Im=function(a,e){a.notified||(a.notified=!0,cu(function(){for(var t=a.reactions,r;r=t.get();)Tm(r,a);a.notified=!1,e&&!a.rejection&&iA(a)}))},Em=function(a,e,t){var r,i;ZP?(r=ou.createEvent("Event"),r.promise=e,r.reason=t,r.initEvent(a,!1,!0),Pt.dispatchEvent(r)):r={promise:e,reason:t},!zP&&(i=Pt["on"+a])?i(r):a===gm&&WP("Unhandled promise rejection",t)},iA=function(a){Or(pm,Pt,function(){var e=a.facade,t=a.value,r=dm(a),i;if(r&&(i=YP(function(){xs?pu.emit("unhandledRejection",t,e):Em(gm,e,t)}),a.rejection=xs||dm(a)?vm:hu,i.error))throw i.value})},dm=function(a){return a.rejection!==hu&&!a.parent},aA=function(a){Or(pm,Pt,function(){var e=a.facade;xs?pu.emit("rejectionHandled",e):Em(eA,e,a.value)})},Dr=function(a,e,t){return function(r){a(e,r,t)}},Br=function(a,e,t){a.done||(a.done=!0,t&&(a=t),a.value=e,a.state=tA,Im(a,!0))},lu=function(a,e,t){if(!a.done){a.done=!0,t&&(a=t);try{if(a.facade===e)throw new bm("Promise can't be resolved itself");var r=ym(e);r?cu(function(){var i={done:!1};try{Or(r,e,Dr(lu,i,a),Dr(Br,i,a))}catch(s){Br(i,s,a)}}):(a.value=e,a.state=Sm,Im(a,!1))}catch(i){Br({done:!1},i,a)}}};if(mm&&(zt=function(e){jP(this,Ts),qP(e),Or(Is,this);var t=nu(this);try{e(Dr(lu,t),Dr(Br,t))}catch(r){Br(t,r)}},Ts=zt.prototype,Is=function(e){JP(this,{type:As,done:!1,notified:!1,parent:!1,reactions:new QP,rejection:!1,state:um,value:void 0})},Is.prototype=nm(Ts,"then",function(e,t){var r=nu(this),i=uu(GP(this,zt));return r.parent=!0,i.ok=Es(e)?e:!0,i.fail=Es(t)&&t,i.domain=xs?pu.domain:void 0,r.state===um?r.reactions.add(i):cu(function(){Tm(i,r)}),i.promise}),lm=function(){var a=new Is,e=nu(a);this.promise=a,this.resolve=Dr(lu,e),this.reject=Dr(Br,e)},fm.f=uu=function(a){return a===zt||a===rA?new lm(a):XP(a)},!NP&&Es(Ps)&&Cr!==Object.prototype)){cm=Cr.then,KP||nm(Cr,"then",function(e,t){var r=this;return new zt(function(i,s){Or(cm,r,i,s)}).then(e,t)},{unsafe:!0});try{delete Cr.constructor}catch(a){}om&&om(Cr,Ts)}_P({global:!0,constructor:!0,wrap:!0,forced:mm},{Promise:zt});FP(zt,As,!1,!0);UP(As)});var Rm=m((JC,km)=>{"use strict";var sA=le(),Am=sA("iterator"),wm=!1;try{Pm=0,fu={next:function(){return{done:!!Pm++}},return:function(){wm=!0}},fu[Am]=function(){return this},Array.from(fu,function(){throw 2})}catch(a){}var Pm,fu;km.exports=function(a,e){try{if(!e&&!wm)return!1}catch(i){return!1}var t=!1;try{var r={};r[Am]=function(){return{next:function(){return{done:t=!0}}}},a(r)}catch(i){}return t}});var mu=m((XC,$m)=>{"use strict";var nA=Qt(),oA=Rm(),uA=Lr().CONSTRUCTOR;$m.exports=uA||!oA(function(a){nA.all(a).then(void 0,function(){})})});var Lm=m(()=>{"use strict";var lA=De(),cA=Ae(),dA=ut(),pA=Mr(),hA=ys(),fA=fs(),mA=mu();lA({target:"Promise",stat:!0,forced:mA},{all:function(e){var t=this,r=pA.f(t),i=r.resolve,s=r.reject,n=hA(function(){var o=dA(t.resolve),u=[],l=0,c=1;fA(e,function(d){var h=l++,p=!1;c++,cA(o,t,d).then(function(f){p||(p=!0,u[h]=f,--c||i(u))},s)}),--c||i(u)});return n.error&&s(n.value),r.promise}})});var Cm=m(()=>{"use strict";var bA=De(),gA=We(),SA=Lr().CONSTRUCTOR,gu=Qt(),vA=ot(),yA=K(),TA=kr(),Mm=gu&&gu.prototype;bA({target:"Promise",proto:!0,forced:SA,real:!0},{catch:function(a){return this.then(void 0,a)}});!gA&&yA(gu)&&(bu=vA("Promise").prototype.catch,Mm.catch!==bu&&TA(Mm,"catch",bu,{unsafe:!0}));var bu});var Dm=m(()=>{"use strict";var IA=De(),EA=Ae(),xA=ut(),PA=Mr(),AA=ys(),wA=fs(),kA=mu();IA({target:"Promise",stat:!0,forced:kA},{race:function(e){var t=this,r=PA.f(t),i=r.reject,s=AA(function(){var n=xA(t.resolve);wA(e,function(o){EA(n,t,o).then(r.resolve,i)})});return s.error&&i(s.value),r.promise}})});var Bm=m(()=>{"use strict";var RA=De(),$A=Mr(),LA=Lr().CONSTRUCTOR;RA({target:"Promise",stat:!0,forced:LA},{reject:function(e){var t=$A.f(this),r=t.reject;return r(e),t.promise}})});var Su=m((oD,Om)=>{"use strict";var MA=tt(),CA=Me(),DA=Mr();Om.exports=function(a,e){if(MA(a),CA(e)&&e.constructor===a)return e;var t=DA.f(a),r=t.resolve;return r(e),t.promise}});var Nm=m(()=>{"use strict";var BA=De(),OA=ot(),Vm=We(),VA=Qt(),_m=Lr().CONSTRUCTOR,_A=Su(),NA=OA("Promise"),FA=Vm&&!_m;BA({target:"Promise",stat:!0,forced:Vm||_m},{resolve:function(e){return _A(FA&&this===NA?VA:this,e)}})});var Fm=m(()=>{"use strict";xm();Lm();Cm();Dm();Bm();Nm()});var jm=m(()=>{"use strict";var UA=De(),qA=We(),ws=Qt(),HA=Pe(),qm=ot(),Hm=K(),jA=Uo(),Um=Su(),GA=kr(),yu=ws&&ws.prototype,WA=!!ws&&HA(function(){yu.finally.call({then:function(){}},function(){})});UA({target:"Promise",proto:!0,real:!0,forced:WA},{finally:function(a){var e=jA(this,qm("Promise")),t=Hm(a);return this.then(t?function(r){return Um(e,a()).then(function(){return r})}:a,t?function(r){return Um(e,a()).then(function(){throw r})}:a)}});!qA&&Hm(ws)&&(vu=qm("Promise").prototype.finally,yu.finally!==vu&&GA(yu,"finally",vu,{unsafe:!0}));var vu});var ks=m((fD,Gm)=>{"use strict";var YA=ot();Gm.exports=YA});var Ym=m((mD,Wm)=>{"use strict";Xh();Fm();jm();var QA=ks();Wm.exports=QA("Promise","finally")});var zm=m((bD,Qm)=>{"use strict";var zA=Ym();Qm.exports=zA});var Rs=m((gD,Km)=>{"use strict";var KA=zm();Km.exports=KA});var Tb=m(()=>{"use strict";var Pw=De(),Aw=pi(),ww=ss(),kw=as(),Rw=_n();Pw({target:"Array",proto:!0},{at:function(e){var t=Aw(this),r=ww(t),i=kw(e),s=i>=0?i:r+i;return s<0||s>=r?void 0:t[s]}});Rw("at")});var Eb=m((A0,Ib)=>{"use strict";Tb();var $w=ks();Ib.exports=$w("Array","at")});var Pb=m((w0,xb)=>{"use strict";var Lw=Eb();xb.exports=Lw});var Nr=m((k0,Ab)=>{"use strict";var Mw=Pb();Ab.exports=Mw});var Lg=m(()=>{"use strict"});var Mg=m(()=>{"use strict"});var Dg=m((O_,Cg)=>{"use strict";var Nk=Me(),Fk=yr(),Uk=le(),qk=Uk("match");Cg.exports=function(a){var e;return Nk(a)&&((e=a[qk])!==void 0?!!e:Fk(a)==="RegExp")}});var Og=m((V_,Bg)=>{"use strict";var Hk=Si(),jk=String;Bg.exports=function(a){if(Hk(a)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return jk(a)}});var _g=m((__,Vg)=>{"use strict";var Gk=tt();Vg.exports=function(){var a=Gk(this),e="";return a.hasIndices&&(e+="d"),a.global&&(e+="g"),a.ignoreCase&&(e+="i"),a.multiline&&(e+="m"),a.dotAll&&(e+="s"),a.unicode&&(e+="u"),a.unicodeSets&&(e+="v"),a.sticky&&(e+="y"),e}});var Ug=m((N_,Fg)=>{"use strict";var Wk=Ae(),Yk=Ye(),Qk=ui(),zk=_g(),Ng=RegExp.prototype;Fg.exports=function(a){var e=a.flags;return e===void 0&&!("flags"in Ng)&&!Yk(a,"flags")&&Qk(Ng,a)?Wk(zk,a):e}});var Hg=m((F_,qg)=>{"use strict";var Ku=me(),Kk=pi(),Jk=Math.floor,Qu=Ku("".charAt),Xk=Ku("".replace),zu=Ku("".slice),Zk=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,eR=/\$([$&'`]|\d{1,2})/g;qg.exports=function(a,e,t,r,i,s){var n=t+a.length,o=r.length,u=eR;return i!==void 0&&(i=Kk(i),u=Zk),Xk(s,u,function(l,c){var d;switch(Qu(c,0)){case"$":return"$";case"&":return a;case"`":return zu(e,0,t);case"'":return zu(e,n);case"<":d=i[zu(c,1,-1)];break;default:var h=+c;if(h===0)return l;if(h>o){var p=Jk(h/10);return p===0?l:p<=o?r[p-1]===void 0?Qu(c,1):r[p-1]+Qu(c,1):l}d=r[h-1]}return d===void 0?"":d})}});var Wg=m(()=>{"use strict";var tR=De(),rR=Ae(),Xu=me(),jg=ni(),iR=K(),aR=Tr(),sR=Dg(),Wr=Og(),nR=ci(),oR=Ug(),uR=Hg(),lR=le(),cR=We(),dR=lR("replace"),pR=TypeError,Ju=Xu("".indexOf),hR=Xu("".replace),Gg=Xu("".slice),fR=Math.max;tR({target:"String",proto:!0},{replaceAll:function(e,t){var r=jg(this),i,s,n,o,u,l,c,d,h,p,f=0,b="";if(!aR(e)){if(i=sR(e),i&&(s=Wr(jg(oR(e))),!~Ju(s,"g")))throw new pR("`.replaceAll` does not allow non-global regexes");if(n=nR(e,dR),n)return rR(n,e,r,t);if(cR&&i)return hR(Wr(r),e,t)}for(o=Wr(r),u=Wr(e),l=iR(t),l||(t=Wr(t)),c=u.length,d=fR(1,c),h=Ju(o,u);h!==-1;)p=l?Wr(t(u,h,o)):uR(u,o,h,[],void 0,t),b+=Gg(o,f,h)+p,f=h+c,h=h+d>o.length?-1:Ju(o,u,h+d);return f<o.length&&(b+=Gg(o,f)),b}})});var Qg=m((H_,Yg)=>{"use strict";Lg();Mg();Wg();var mR=ks();Yg.exports=mR("String","replaceAll")});var Kg=m((j_,zg)=>{"use strict";var bR=Qg();zg.exports=bR});var Xg=m((G_,Jg)=>{"use strict";var gR=Kg();Jg.exports=gR});var mc="2.0.116-dev.32c949ec.0";var fe=(i=>(i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused",i))(fe||{}),xt=(T=>(T.MPEG="MPEG",T.DASH="DASH",T.DASH_SEP="DASH_SEP",T.DASH_SEP_VK="DASH_SEP",T.DASH_WEBM="DASH_WEBM",T.DASH_WEBM_AV1="DASH_WEBM_AV1",T.DASH_STREAMS="DASH_STREAMS",T.DASH_WEBM_VK="DASH_WEBM",T.DASH_ONDEMAND="DASH_ONDEMAND",T.DASH_ONDEMAND_VK="DASH_ONDEMAND",T.DASH_LIVE="DASH_LIVE",T.DASH_LIVE_CMAF="DASH_LIVE_CMAF",T.DASH_LIVE_WEBM="DASH_LIVE_WEBM",T.HLS="HLS",T.HLS_ONDEMAND="HLS_ONDEMAND",T.HLS_JS="HLS",T.HLS_LIVE="HLS_LIVE",T.HLS_LIVE_CMAF="HLS_LIVE_CMAF",T.WEB_RTC_LIVE="WEB_RTC_LIVE",T))(xt||{});var Wa=(i=>(i.NOT_AVAILABLE="NOT_AVAILABLE",i.AVAILABLE="AVAILABLE",i.CONNECTING="CONNECTING",i.CONNECTED="CONNECTED",i))(Wa||{}),Mn=(r=>(r.HTTP1="http1",r.HTTP2="http2",r.QUIC="quic",r))(Mn||{});var Cn=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(Cn||{});import{assertNever as Tc,assertNonNullable as Ov,isNonNullable as Ya,ValueSubject as Dn,Subject as Vv,Subscription as _v,merge as Nv,observableFrom as Fv,fromEvent as gc,map as Sc,tap as vc,filterChanged as Uv,isNullable as Bn,ErrorCategory as yc}from"@vkontakte/videoplayer-shared";var bc=a=>new Promise((e,t)=>{let r=document.createElement("script");r.setAttribute("src",a),r.onload=()=>e,r.onerror=()=>t,document.body.appendChild(r)});var Qa=class{constructor(e){this.connection$=new Dn(void 0);this.castState$=new Dn("NOT_AVAILABLE");this.errorEvent$=new Vv;this.realCastState$=new Dn("NOT_AVAILABLE");this.subscription=new _v;var s;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastInitializer");let t="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${t}`}),e.isDisabled||!t)return;let r=Ya((s=window.chrome)==null?void 0:s.cast),i=!!window.__onGCastApiAvailable;r?this.initializeCastApi():(window.__onGCastApiAvailable=n=>{delete window.__onGCastApiAvailable,n&&this.initializeCastApi()},i||bc("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:yc.NETWORK,message:"Script loading failed!"})))}connect(){var e;(e=cast.framework.CastContext.getInstance())==null||e.requestSession()}disconnect(){var e,t;(t=(e=cast.framework.CastContext.getInstance())==null?void 0:e.getCurrentSession())==null||t.endSession(!0)}stopMedia(){return new Promise((e,t)=>{var r,i,s;(s=(i=(r=cast.framework.CastContext.getInstance())==null?void 0:r.getCurrentSession())==null?void 0:i.getMediaSession())==null||s.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){Ya(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();Bn(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();Bn(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(gc(r,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(i=>{var s,n,o;switch(i.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=(o=(n=(s=r.getCurrentSession())==null?void 0:s.getMediaSession())==null?void 0:n.media)==null?void 0:o.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return Tc(i.sessionState)}})).add(Nv(gc(r,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(vc(i=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(i)}`})}),Sc(i=>i.castState)),Fv([r.getCastState()])).pipe(Uv(),Sc(qv),vc(i=>{this.log({message:`realCastState$: ${i}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(i=>{var o,u;let s=i==="CONNECTED",n=Ya(this.connection$.getValue());if(s&&!n){let l=r.getCurrentSession();Ov(l);let c=l.getCastDevice(),d=(u=(o=l.getMediaSession())==null?void 0:o.media)==null?void 0:u.contentId;(Bn(d)||d===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:l,castDevice:c}))}else!s&&n&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(i==="CONNECTED"?Ya(this.connection$.getValue())?"CONNECTED":"AVAILABLE":i)}))}initializeCastApi(){var i;let e,t,r;try{e=cast.framework.CastContext.getInstance(),t=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,r=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch(s){return}try{e.setOptions({receiverApplicationId:(i=this.params.receiverApplicationId)!=null?i:t,autoJoinPolicy:r}),this.initListeners()}catch(s){this.errorEvent$.next({id:"ChromecastInitializer",category:yc.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:s})}}},qv=a=>{switch(a){case cast.framework.CastState.NO_DEVICES_AVAILABLE:return"NOT_AVAILABLE";case cast.framework.CastState.NOT_CONNECTED:return"AVAILABLE";case cast.framework.CastState.CONNECTING:return"CONNECTING";case cast.framework.CastState.CONNECTED:return"CONNECTED";default:return Tc(a)}};var XS=je(Oo(),1);var nb=je(Rs(),1);import{assertNever as Jm}from"@vkontakte/videoplayer-shared";var se=(a,e=0,t=0)=>{switch(t){case 0:return a.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case 1:{if(e===0)return a;let r=new URL(a);return r.searchParams.append("playback_shift",e.toFixed(0)),r.toString()}case 2:{let r=new URL(a);return!r.searchParams.get("offset_p")&&e===0?a:(r.searchParams.set("offset_p",e.toFixed(0)),r.toString())}default:Jm(t)}return a},Tu=(a,e)=>{var t;switch(e){case 0:return NaN;case 1:{let r=new URL(a);return Number(r.searchParams.get("playback_shift"))}case 2:{let r=new URL(a);return Number((t=r.searchParams.get("offset_p"))!=null?t:0)}default:Jm(e)}};var x=(a,e,t=!1)=>{let r=a.getTransition();(t||!r||r.to===e)&&a.setState(e)};import{isNonNullable as JA,Subject as $s,merge as Xm}from"@vkontakte/videoplayer-shared";var C=class{constructor(e){this.transitionStarted$=new $s;this.transitionEnded$=new $s;this.transitionUpdated$=new $s;this.forceChanged$=new $s;this.stateChangeStarted$=Xm(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=Xm(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||JA(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 XA}from"@vkontakte/videoplayer-shared";var Zm=a=>{switch(a){case"MPEG":case"DASH":case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":case"HLS":case"HLS_ONDEMAND":return!1;case"DASH_LIVE":case"DASH_LIVE_CMAF":case"HLS_LIVE":case"HLS_LIVE_CMAF":case"DASH_LIVE_WEBM":case"WEB_RTC_LIVE":return!0;default:return XA(a)}};import{assertNever as Vr,assertNonNullable as Kt,debounce as eb,ErrorCategory as tb,fromEvent as Jt,isNonNullable as rb,map as ib,merge as ab,observableFrom as ZA,Subject as ew,Subscription as Iu,timeout as tw,getHighestQuality as rw}from"@vkontakte/videoplayer-shared";var iw=5,aw=5,sw=500,sb=7e3,Ri=class{constructor(e){this.subscription=new Iu;this.loadMediaTimeoutSubscription=new Iu;this.videoState=new C("stopped");this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),r=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${r}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(s)};`}),r==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.stop());return}if(!t){if((i==null?void 0:i.to)!=="paused"&&s.state==="requested"&&e!=="stopped"){this.seek(s.position/1e3);return}switch(r){case"ready":{switch(e){case"playing":case"paused":case"ready":break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:Vr(e)}break}case"playing":{switch(e){case"playing":break;case"paused":this.videoState.startTransitionTo("playing"),this.params.connection.remotePlayerController.playOrPause();break;case"ready":this.videoState.startTransitionTo("playing"),this.params.connection.remotePlayerController.playOrPause();break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:Vr(e)}break}case"paused":{switch(e){case"playing":this.videoState.startTransitionTo("paused"),this.params.connection.remotePlayerController.playOrPause();break;case"paused":break;case"ready":this.videoState.startTransitionTo("paused"),this.videoState.setState("paused");break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:Vr(e)}break}default:Vr(r)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(Zm(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 Iu;this.subscription.add(e),this.subscription.add(ab(this.videoState.stateChangeStarted$.pipe(ib(i=>`stateChangeStarted$ ${JSON.stringify(i)}`)),this.videoState.stateChangeEnded$.pipe(ib(i=>`stateChangeEnded$ ${JSON.stringify(i)}`))).subscribe(i=>this.log({message:`[videoState] ${i}`})));let t=(i,s)=>this.subscription.add(i.subscribe(s));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{let i=new ew;e.add(i.pipe(eb(sw)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add(Jt(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)>iw)&&i.next(o),s=o})),e.add(Jt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(Jt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),i=>{this.logRemoteEvent(i),i.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(Jt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),i=>{this.logRemoteEvent(i),i.value?this.handleRemotePause():this.handleRemotePlay()}),t(Jt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),i=>{this.logRemoteEvent(i);let{remotePlayer:s}=this.params.connection,n=i.value,o=this.params.output.isBuffering$.getValue(),u=n===chrome.cast.media.PlayerState.BUFFERING;switch(o!==u&&this.params.output.isBuffering$.next(u),n){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&s.duration-s.currentTime<aw&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),x(this.params.desiredState.playbackState,"stopped");break;case chrome.cast.media.PlayerState.PAUSED:{this.handleRemotePause();break}case chrome.cast.media.PlayerState.PLAYING:this.handleRemotePlay();break;case chrome.cast.media.PlayerState.BUFFERING:break;default:Vr(n)}}),t(Jt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),i=>{this.logRemoteEvent(i),this.handleRemoteVolumeChange({volume:i.value})}),t(Jt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),i=>{this.logRemoteEvent(i),this.handleRemoteVolumeChange({muted:i.value})});let r=ab(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,ZA(["init"])).pipe(eb(0));t(r,this.syncPlayback)}restoreSession(e){this.log({message:"restoreSession"});let{remotePlayer:t}=this.params.connection;if(e.playerState!==chrome.cast.media.PlayerState.IDLE){t.isPaused?(this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),x(this.params.desiredState.playbackState,"playing"));let r=this.params.output.isLive$.getValue();this.params.output.duration$.next(r?0:t.duration),this.params.output.position$.next(r?0:t.currentTime),this.params.desiredState.seekState.setState({state:"none"})}}prepare(){let e=this.params.format;this.log({message:`[prepare] format: ${e}`});let t=this.createMediaInfo(e),r=this.createLoadRequest(t);this.loadMedia(r)}handleRemotePause(){let e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)==="paused"||e==="playing")&&(this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused"))}handleRemotePlay(){let e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)==="playing"||e==="paused")&&(this.videoState.setState("playing"),x(this.params.desiredState.playbackState,"playing"))}handleRemoteReady(){var t;let e=this.videoState.getTransition();(e==null?void 0:e.to)==="ready"&&this.videoState.setState("ready"),((t=this.params.desiredState.playbackState.getTransition())==null?void 0:t.to)==="ready"&&x(this.params.desiredState.playbackState,"ready")}handleRemoteStop(){this.videoState.getState()!=="stopped"&&this.videoState.setState("stopped")}handleRemoteVolumeChange(e){var i,s;let t=this.params.output.volume$.getValue(),r={volume:(i=e.volume)!=null?i:t.volume,muted:(s=e.muted)!=null?s:t.muted};(r.volume!==t.volume||r.muted!==r.muted)&&this.params.output.volume$.next(r)}seek(e){this.params.output.willSeekEvent$.next();let{remotePlayer:t,remotePlayerController:r}=this.params.connection;t.currentTime=e,r.seek()}stop(){let{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){var l;let t=this.params.source,r,i,s;switch(e){case"MPEG":{let c=t[e];Kt(c);let d=rw(Object.keys(c));Kt(d);let h=c[d];Kt(h),r=h,i="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let c=t[e];Kt(c),r=c.url,i="application/x-mpegurl",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":{let c=t[e];Kt(c),r=c.url,i="application/dash+xml",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let c=t[e];Kt(c),r=c.url,i="application/dash+xml",s=chrome.cast.media.StreamType.LIVE;break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let c=t[e];Kt(c),r=se(c.url),i="application/x-mpegurl",s=chrome.cast.media.StreamType.LIVE;break}case"DASH_LIVE":case"WEB_RTC_LIVE":{let c="Unsupported format for Chromecast",d=new Error(c);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:tb.VIDEO_PIPELINE,message:c,thrown:d}),d}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return Vr(e)}let n=new chrome.cast.media.MediaInfo((l=this.params.meta.videoId)!=null?l:r,i);n.contentUrl=r,n.streamType=s,n.metadata=new chrome.cast.media.GenericMediaMetadata;let{title:o,subtitle:u}=this.params.meta;return rb(o)&&(n.metadata.title=o),rb(u)&&(n.metadata.subtitle=u),n}createLoadRequest(e){let t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;let r=this.params.desiredState.seekState.getState();return r.state==="applying"||r.state==="requested"?t.currentTime=this.params.output.isLive$.getValue()?0:r.position/1e3:t.currentTime=0,t}loadMedia(e){let t=this.params.connection.session.loadMedia(e),r=new Promise((i,s)=>{this.loadMediaTimeoutSubscription.add(tw(sb).subscribe(()=>s(`timeout(${sb})`)))});(0,nb.default)(Promise.race([t,r]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},i=>{let s=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${i}`;this.log({message:s}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:tb.VIDEO_PIPELINE,message:s,thrown:i})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};import{clearVideoElement as ub}from"@vkontakte/videoplayer-shared";import{clearVideoElement as nw}from"@vkontakte/videoplayer-shared";var ob=a=>{try{a.pause(),a.playbackRate=0,nw(a),a.remove()}catch(e){console.error(e)}};import{fromEvent as ow,Subscription as uw}from"@vkontakte/videoplayer-shared";var Eu=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)}},xu=window.WeakMap?new WeakMap:new Eu,Pu=window.WeakMap?new WeakMap:new Map,lw=(a,e=20)=>{let t=0;return ow(a,"ratechange").subscribe(r=>{t++,t>=e&&(a.currentTime=a.currentTime,t=0)})},be=(a,{audioVideoSyncRate:e})=>{let t=a.querySelector("video"),r=!!t;t?ub(t):(t=document.createElement("video"),a.appendChild(t)),xu.set(t,r);let i=new uw;return i.add(lw(t,e)),Pu.set(t,i),t.setAttribute("crossorigin","anonymous"),t.setAttribute("playsinline","playsinline"),t.controls=!1,t.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),t},ge=a=>{let e=Pu.get(a);e==null||e.unsubscribe(),Pu.delete(a);let t=xu.get(a);xu.delete(a),t?ub(a):ob(a)};import{assertNonNullable as $i,isNonNullable as it,isNullable as pw,fromEvent as _r,merge as lb,observableFrom as cb,filterChanged as db,map as Li,Subject as pb,Subscription as hw,ValueSubject as fw,ErrorCategory as mw}from"@vkontakte/videoplayer-shared";import{isNonNullable as Au,isNullable as cw,Subscription as dw}from"@vkontakte/videoplayer-shared";var Ls=(a,e,t,{equal:r=(n,o)=>n===o,changed$:i,onError:s}={})=>{let n=a.getState(),o=e(),u=cw(i),l=new dw;return i&&l.add(i.subscribe(c=>{let d=a.getState();r(c,d)&&a.setState(c)},s)),r(o,n)||(t(n),u&&a.setState(n)),l.add(a.stateChangeStarted$.subscribe(c=>{t(c.to),u&&a.setState(c.to)},s)),l},rt=(a,e,t)=>Ls(e,()=>a.loop,r=>{Au(r)&&(a.loop=r)},{onError:t}),Se=(a,e,t,r)=>Ls(e,()=>({muted:a.muted,volume:a.volume}),i=>{Au(i)&&(a.muted=i.muted,a.volume=i.volume)},{equal:(i,s)=>i===s||(i==null?void 0:i.muted)===(s==null?void 0:s.muted)&&(i==null?void 0:i.volume)===(s==null?void 0:s.volume),changed$:t,onError:r}),Be=(a,e,t,r)=>Ls(e,()=>a.playbackRate,i=>{Au(i)&&(a.playbackRate=i)},{changed$:t,onError:r}),At=Ls;var bw=a=>["__",a.language,a.label].join("|"),gw=(a,e)=>{if(a.id===e)return!0;let[t,r,i]=e.split("|");return a.language===r&&a.label===i},wu=class a{constructor(){this.available$=new pb;this.current$=new fw(void 0);this.error$=new pb;this.subscription=new hw;this.externalTracks=new Map;this.internalTracks=new Map}connect(e,t,r){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();let i=s=>{this.error$.next({id:"TextTracksManager",category:mw.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:s})};this.subscription.add(this.available$.subscribe(r.availableTextTracks$)),this.subscription.add(this.current$.subscribe(r.currentTextTrack$)),this.subscription.add(this.error$.subscribe(r.error$)),this.subscription.add(At(t.internalTextTracks,()=>Object.values(this.internalTracks),s=>{it(s)&&this.setInternal(s)},{equal:(s,n)=>it(s)&&it(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(Li(s=>s.filter(({type:n})=>n==="internal"))),onError:i})),this.subscription.add(At(t.externalTextTracks,()=>Object.values(this.externalTracks),s=>{it(s)&&this.setExternal(s)},{equal:(s,n)=>it(s)&&it(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(Li(s=>s.filter(({type:n})=>n==="external"))),onError:i})),this.subscription.add(At(t.currentTextTrack,()=>{if(this.video)return;let s=this.htmlTextTracksAsArray().find(({mode:n})=>n==="showing");return s&&this.htmlTextTrackToITextTrack(s).id},s=>this.select(s),{changed$:this.current$,onError:i})),this.subscription.add(At(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.activeCues)}))}subscribe(){$i(this.video);let{textTracks:e}=this.video;this.subscription.add(_r(e,"addtrack").subscribe(()=>{let r=this.current$.getValue();r&&this.select(r)})),this.subscription.add(lb(_r(e,"addtrack"),_r(e,"removetrack"),cb(["init"])).pipe(Li(()=>this.htmlTextTracksAsArray().map(r=>this.htmlTextTrackToITextTrack(r))),db((r,i)=>r.length===i.length&&r.every(({id:s},n)=>s===i[n].id))).subscribe(this.available$)),this.subscription.add(lb(_r(e,"change"),cb(["init"])).pipe(Li(()=>this.htmlTextTracksAsArray().find(({mode:r})=>r==="showing")),Li(r=>r&&this.htmlTextTrackToITextTrack(r).id),db()).subscribe(this.current$));let t=r=>{var i,s;return this.applyCueSettings((s=(i=r.target)==null?void 0:i.activeCues)!=null?s:null)};this.subscription.add(_r(e,"addtrack").subscribe(r=>{var s,n;(s=r.track)==null||s.addEventListener("cuechange",t);let i=o=>{var l,c,d,h,p;let u=(c=(l=o.target)==null?void 0:l.cues)!=null?c:null;u&&u.length&&(this.applyCueSettings((h=(d=o.target)==null?void 0:d.cues)!=null?h:null),(p=o.target)==null||p.removeEventListener("cuechange",i))};(n=r.track)==null||n.addEventListener("cuechange",i)})),this.subscription.add(_r(e,"removetrack").subscribe(r=>{var i;(i=r.track)==null||i.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;let t=this.cueSettings.getState();for(let r of Array.from(e)){let i=r;it(t.align)&&(i.align=t.align),it(t.position)&&(i.position=t.position),it(t.size)&&(i.size=t.size),it(t.line)&&(i.line=t.line)}}htmlTextTracksAsArray(e=!1){$i(this.video);let t=[...this.video.textTracks];return e?t:t.filter(a.isHealthyTrack)}htmlTextTrackToITextTrack(e){var o,u,l,c;let{language:t,label:r}=e,i=e.id?e.id:bw(e),s=this.externalTracks.has(i),n=(s?(o=this.externalTracks.get(i))==null?void 0:o.isAuto:(u=this.internalTracks.get(i))==null?void 0:u.isAuto)||i.includes("auto");return s?{id:i,type:"external",isAuto:n,language:t,label:r,url:(l=this.externalTracks.get(i))==null?void 0:l.url}:{id:i,type:"internal",isAuto:n,language:t,label:r,url:(c=this.internalTracks.get(i))==null?void 0:c.url}}static isHealthyTrack(e){return!(e.kind==="metadata"||e.groupId||e.id===""&&e.label===""&&e.language==="")}setExternal(e){this.internalTracks.size>0&&Array.from(this.internalTracks).forEach(([,t])=>this.detach(t)),e.filter(({id:t})=>!this.externalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.externalTracks).filter(([t])=>!e.find(r=>r.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){let t=[...this.externalTracks];e.filter(({id:r,language:i,isAuto:s})=>!this.internalTracks.has(r)&&!t.some(([,n])=>n.language===i&&n.isAuto===s)).forEach(r=>this.attach(r)),Array.from(this.internalTracks).filter(([r])=>!e.find(i=>i.id===r)).forEach(([,r])=>this.detach(r))}select(e){$i(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(pw(e)||!gw(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){$i(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){$i(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)}},Oe=wu;var dt=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 hb=a=>{let e=a;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e==null?void 0:e.parentNode;return e!=null?e:void 0},ku=a=>{let e=hb(a);return!!(e&&e.fullscreenElement&&e.fullscreenElement===a)},fb=a=>{let e=hb(a);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===a)};import{fromEvent as Ve,map as wt,merge as bb,filterChanged as vw,isNonNullable as gb,Subject as yw,filter as Sb,mapTo as vb,combine as Tw,once as Iw,ErrorCategory as Ew,ValueSubject as yb,clientChecker as xw}from"@vkontakte/videoplayer-shared";var Sw=3,mb=(a,e,t=Sw)=>{let r=0,i=0;for(let s=0;s<a.length;s++){let n=a.start(s),o=a.end(s);if(n<=e&&e<=o){if(r=n,i=o,!t)return{from:r,to:i};for(let u=s-1;u>=0;u--)a.end(u)+t>=r&&(r=a.start(u));for(let u=s+1;u<a.length;u++)a.start(u)-t<=i&&(i=a.end(u))}}return{from:r,to:i}};var ve=a=>{let e=T=>Ve(a,T).pipe(vb(void 0)),r=bb(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(T=>Ve(a,T))).pipe(wt(T=>T.type==="ended"?a.readyState<2:a.readyState<3),vw()),i=bb(Ve(a,"progress"),Ve(a,"timeupdate")).pipe(wt(()=>mb(a.buffered,a.currentTime))),s=xw.isSafari?Tw({play:e("play").pipe(Iw()),playing:e("playing")}).pipe(vb(void 0)):e("playing"),n=Ve(a,"volumechange").pipe(wt(()=>({muted:a.muted,volume:a.volume}))),o=Ve(a,"ratechange").pipe(wt(()=>a.playbackRate)),u=Ve(a,"error").pipe(Sb(()=>!!(a.error||a.played.length)),wt(()=>{var I;let T=a.error;return{id:T?`MediaError#${T.code}`:"HtmlVideoError",category:Ew.VIDEO_PIPELINE,message:T?T.message:"Error event from HTML video element",thrown:(I=a.error)!=null?I:void 0}})),l=Ve(a,"timeupdate").pipe(wt(()=>a.currentTime)),c=new yw,d=.3,h;l.subscribe(T=>{a.loop&&gb(h)&&gb(T)&&h>=a.duration-d&&T<=d&&c.next(h),h=T});let p=e("pause").pipe(Sb(()=>!a.error&&h!==a.duration)),f=Ve(a,"enterpictureinpicture"),b=Ve(a,"leavepictureinpicture"),g=new yb(fb(a));f.subscribe(()=>g.next(!0)),b.subscribe(()=>g.next(!1));let S=new yb(ku(a));return Ve(a,"fullscreenchange").pipe(wt(()=>ku(a))).subscribe(S),{playing$:s,pause$:p,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$:Ve(a,"durationchange").pipe(wt(()=>a.duration)),isBuffering$:r,currentBuffer$:i,volumeState$:n,playbackRateState$:o,inPiP$:g,inFullscreen$:S}};import{VideoQuality as kt}from"@vkontakte/videoplayer-shared";var Rt=a=>{switch(a){case"mobile":return kt.Q_144P;case"lowest":return kt.Q_240P;case"low":return kt.Q_360P;case"sd":case"medium":return kt.Q_480P;case"hd":case"high":return kt.Q_720P;case"fullhd":case"full":return kt.Q_1080P;case"quadhd":case"quad":return kt.Q_1440P;case"ultrahd":case"ultra":return kt.Q_2160P}};var Xt=je(Nr(),1);import{isNonNullable as te,isNullable as $u,now as Db,isHigher as Lu,isHigherOrEqual as $b,isInvariantQuality as Lb,isLower as Mb,isLowerOrEqual as Mu,videoSizeToQuality as Cw,assertNotEmptyArray as Bb,assertNonNullable as Dw}from"@vkontakte/videoplayer-shared";var Ru=!1,pt={},wb=a=>{Ru=a},kb=()=>{pt={}},Rb=a=>{a(pt)},Mi=(a,e)=>{var t;Ru&&(pt.meta=(t=pt.meta)!=null?t:{},pt.meta[a]=e)},ce=class{constructor(e){this.name=e}next(e){var r,i;if(!Ru)return;pt.series=(r=pt.series)!=null?r:{};let t=(i=pt.series[this.name])!=null?i:[];t.push([Date.now(),e]),pt.series[this.name]=t}};var Bw=new ce("best_bitrate"),Ob=(a,e,t)=>(e-t)*Math.pow(2,-10*a)+t;var Cu=a=>(e,t)=>a*(Number(e.bitrate)-Number(t.bitrate)),Ci=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=Db()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},Vb='Assertion "ABR Tracks is empty array" failed',Ms=(a,e,t,r)=>{var u;let i=[...e].sort(Cu(1)),s=[...t].sort(Cu(1)),n=s.filter(l=>te(l.bitrate)&&te(a.bitrate)?a.bitrate/l.bitrate>r:!0),o=(u=(0,Xt.default)(s,Math.round(s.length*i.indexOf(a)/(i.length+1))))!=null?u:(0,Xt.default)(s,-1);return o&&n.includes(o)?o:n.length?(0,Xt.default)(n,-1):(0,Xt.default)(s,0)},Cb=a=>"quality"in a,_b=(a,e,t,r)=>{var n;let i=te((n=r==null?void 0:r.last)==null?void 0:n.bitrate)&&te(t==null?void 0:t.bitrate)&&r.last.bitrate<t.bitrate?a.trackCooldownIncreaseQuality:a.trackCooldownDecreaseQuality,s=t&&r&&r.history[t.id]&&Db()-r.history[t.id]<=i&&(!r.last||t.id!==r.last.id);if(t!=null&&t.id&&r&&!s&&r.recordSelection(t),s&&(r!=null&&r.last)){let o=r.last;r==null||r.recordSwitch(o);let u=Cb(o)?"video":"audio",l=Cb(o)?o.quality:o.bitrate;return e({message:`
6
+ var kv=Object.create;var kn=Object.defineProperty,Rv=Object.defineProperties,$v=Object.getOwnPropertyDescriptor,Lv=Object.getOwnPropertyDescriptors,Mv=Object.getOwnPropertyNames,Wa=Object.getOwnPropertySymbols,Cv=Object.getPrototypeOf,Rn=Object.prototype.hasOwnProperty,dc=Object.prototype.propertyIsEnumerable;var Dv=(a,e)=>(e=Symbol[a])?e:Symbol.for("Symbol."+a);var et=Math.pow,cc=(a,e,t)=>e in a?kn(a,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):a[e]=t,A=(a,e)=>{for(var t in e||(e={}))Rn.call(e,t)&&cc(a,t,e[t]);if(Wa)for(var t of Wa(e))dc.call(e,t)&&cc(a,t,e[t]);return a},D=(a,e)=>Rv(a,Lv(e));var pc=(a,e)=>{var t={};for(var r in a)Rn.call(a,r)&&e.indexOf(r)<0&&(t[r]=a[r]);if(a!=null&&Wa)for(var r of Wa(a))e.indexOf(r)<0&&dc.call(a,r)&&(t[r]=a[r]);return t};var m=(a,e)=>()=>(e||a((e={exports:{}}).exports,e),e.exports);var Bv=(a,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Mv(e))!Rn.call(a,i)&&i!==t&&kn(a,i,{get:()=>e[i],enumerable:!(r=$v(e,i))||r.enumerable});return a};var Ge=(a,e,t)=>(t=a!=null?kv(Cv(a)):{},Bv(e||!a||!a.__esModule?kn(t,"default",{value:a,enumerable:!0}):t,a));var w=(a,e,t)=>new Promise((r,i)=>{var s=u=>{try{o(t.next(u))}catch(l){i(l)}},n=u=>{try{o(t.throw(u))}catch(l){i(l)}},o=u=>u.done?r(u.value):Promise.resolve(u.value).then(s,n);o((t=t.apply(a,e)).next())}),$n=function(a,e){this[0]=a,this[1]=e},Z=(a,e,t)=>{var r=(n,o,u,l)=>{try{var c=t[n](o),d=(o=c.value)instanceof $n,h=c.done;Promise.resolve(d?o[0]:o).then(p=>d?r(n==="return"?n:"next",o[1]?{done:p.done,value:p.value}:p,u,l):u({value:p,done:h})).catch(p=>r("throw",p,u,l))}catch(p){l(p)}},i=n=>s[n]=o=>new Promise((u,l)=>r(n,o,u,l)),s={};return t=t.apply(a,e),s[Dv("asyncIterator")]=()=>s,i("next"),i("throw"),i("return"),s};var Pe=m((VL,yc)=>{"use strict";yc.exports=function(a){try{return!!a()}catch(e){return!0}}});var ai=m((_L,Tc)=>{"use strict";var Hv=Pe();Tc.exports=!Hv(function(){var a=function(){}.bind();return typeof a!="function"||a.hasOwnProperty("prototype")})});var me=m((NL,xc)=>{"use strict";var Ic=ai(),Ec=Function.prototype,Bn=Ec.call,jv=Ic&&Ec.bind.bind(Bn,Bn);xc.exports=Ic?jv:function(a){return function(){return Bn.apply(a,arguments)}}});var Tr=m((FL,Ac)=>{"use strict";var Pc=me(),Gv=Pc({}.toString),Wv=Pc("".slice);Ac.exports=function(a){return Wv(Gv(a),8,-1)}});var kc=m((UL,wc)=>{"use strict";var Yv=me(),Qv=Pe(),zv=Tr(),On=Object,Kv=Yv("".split);wc.exports=Qv(function(){return!On("z").propertyIsEnumerable(0)})?function(a){return zv(a)==="String"?Kv(a,""):On(a)}:On});var Ir=m((qL,Rc)=>{"use strict";Rc.exports=function(a){return a==null}});var si=m((HL,$c)=>{"use strict";var Jv=Ir(),Xv=TypeError;$c.exports=function(a){if(Jv(a))throw new Xv("Can't call method on "+a);return a}});var Er=m((jL,Lc)=>{"use strict";var Zv=kc(),ey=si();Lc.exports=function(a){return Zv(ey(a))}});var Vn=m((GL,Mc)=>{"use strict";Mc.exports=function(){}});var Gt=m((WL,Cc)=>{"use strict";Cc.exports={}});var X=m((_n,Dc)=>{"use strict";var ni=function(a){return a&&a.Math===Math&&a};Dc.exports=ni(typeof globalThis=="object"&&globalThis)||ni(typeof window=="object"&&window)||ni(typeof self=="object"&&self)||ni(typeof global=="object"&&global)||ni(typeof _n=="object"&&_n)||function(){return this}()||Function("return this")()});var J=m((YL,Bc)=>{"use strict";var Nn=typeof document=="object"&&document.all;Bc.exports=typeof Nn=="undefined"&&Nn!==void 0?function(a){return typeof a=="function"||a===Nn}:function(a){return typeof a=="function"}});var _c=m((QL,Vc)=>{"use strict";var ty=X(),ry=J(),Oc=ty.WeakMap;Vc.exports=ry(Oc)&&/native code/.test(String(Oc))});var De=m((zL,Nc)=>{"use strict";var iy=J();Nc.exports=function(a){return typeof a=="object"?a!==null:iy(a)}});var Be=m((KL,Fc)=>{"use strict";var ay=Pe();Fc.exports=!ay(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var Ka=m((JL,qc)=>{"use strict";var sy=X(),Uc=De(),Fn=sy.document,ny=Uc(Fn)&&Uc(Fn.createElement);qc.exports=function(a){return ny?Fn.createElement(a):{}}});var Un=m((XL,Hc)=>{"use strict";var oy=Be(),uy=Pe(),ly=Ka();Hc.exports=!oy&&!uy(function(){return Object.defineProperty(ly("div"),"a",{get:function(){return 7}}).a!==7})});var qn=m((ZL,jc)=>{"use strict";var cy=Be(),dy=Pe();jc.exports=cy&&dy(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var tt=m((eM,Gc)=>{"use strict";var py=De(),hy=String,fy=TypeError;Gc.exports=function(a){if(py(a))return a;throw new fy(hy(a)+" is not an object")}});var Ae=m((tM,Wc)=>{"use strict";var my=ai(),Ja=Function.prototype.call;Wc.exports=my?Ja.bind(Ja):function(){return Ja.apply(Ja,arguments)}});var Xa=m((rM,Yc)=>{"use strict";Yc.exports={}});var ot=m((iM,zc)=>{"use strict";var Hn=Xa(),jn=X(),by=J(),Qc=function(a){return by(a)?a:void 0};zc.exports=function(a,e){return arguments.length<2?Qc(Hn[a])||Qc(jn[a]):Hn[a]&&Hn[a][e]||jn[a]&&jn[a][e]}});var oi=m((aM,Kc)=>{"use strict";var gy=me();Kc.exports=gy({}.isPrototypeOf)});var xr=m((sM,Zc)=>{"use strict";var Sy=X(),Jc=Sy.navigator,Xc=Jc&&Jc.userAgent;Zc.exports=Xc?String(Xc):""});var Wn=m((nM,sd)=>{"use strict";var ad=X(),Gn=xr(),ed=ad.process,td=ad.Deno,rd=ed&&ed.versions||td&&td.version,id=rd&&rd.v8,We,Za;id&&(We=id.split("."),Za=We[0]>0&&We[0]<4?1:+(We[0]+We[1]));!Za&&Gn&&(We=Gn.match(/Edge\/(\d+)/),(!We||We[1]>=74)&&(We=Gn.match(/Chrome\/(\d+)/),We&&(Za=+We[1])));sd.exports=Za});var Yn=m((oM,od)=>{"use strict";var nd=Wn(),vy=Pe(),yy=X(),Ty=yy.String;od.exports=!!Object.getOwnPropertySymbols&&!vy(function(){var a=Symbol("symbol detection");return!Ty(a)||!(Object(a)instanceof Symbol)||!Symbol.sham&&nd&&nd<41})});var Qn=m((uM,ud)=>{"use strict";var Iy=Yn();ud.exports=Iy&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var zn=m((lM,ld)=>{"use strict";var Ey=ot(),xy=J(),Py=oi(),Ay=Qn(),wy=Object;ld.exports=Ay?function(a){return typeof a=="symbol"}:function(a){var e=Ey("Symbol");return xy(e)&&Py(e.prototype,wy(a))}});var ui=m((cM,cd)=>{"use strict";var ky=String;cd.exports=function(a){try{return ky(a)}catch(e){return"Object"}}});var ut=m((dM,dd)=>{"use strict";var Ry=J(),$y=ui(),Ly=TypeError;dd.exports=function(a){if(Ry(a))return a;throw new Ly($y(a)+" is not a function")}});var li=m((pM,pd)=>{"use strict";var My=ut(),Cy=Ir();pd.exports=function(a,e){var t=a[e];return Cy(t)?void 0:My(t)}});var fd=m((hM,hd)=>{"use strict";var Kn=Ae(),Jn=J(),Xn=De(),Dy=TypeError;hd.exports=function(a,e){var t,r;if(e==="string"&&Jn(t=a.toString)&&!Xn(r=Kn(t,a))||Jn(t=a.valueOf)&&!Xn(r=Kn(t,a))||e!=="string"&&Jn(t=a.toString)&&!Xn(r=Kn(t,a)))return r;throw new Dy("Can't convert object to primitive value")}});var Ye=m((fM,md)=>{"use strict";md.exports=!0});var Sd=m((mM,gd)=>{"use strict";var bd=X(),By=Object.defineProperty;gd.exports=function(a,e){try{By(bd,a,{value:e,configurable:!0,writable:!0})}catch(t){bd[a]=e}return e}});var ci=m((bM,Td)=>{"use strict";var Oy=Ye(),Vy=X(),_y=Sd(),vd="__core-js_shared__",yd=Td.exports=Vy[vd]||_y(vd,{});(yd.versions||(yd.versions=[])).push({version:"3.38.0",mode:Oy?"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 Zn=m((gM,Ed)=>{"use strict";var Id=ci();Ed.exports=function(a,e){return Id[a]||(Id[a]=e||{})}});var di=m((SM,xd)=>{"use strict";var Ny=si(),Fy=Object;xd.exports=function(a){return Fy(Ny(a))}});var Qe=m((vM,Pd)=>{"use strict";var Uy=me(),qy=di(),Hy=Uy({}.hasOwnProperty);Pd.exports=Object.hasOwn||function(e,t){return Hy(qy(e),t)}});var eo=m((yM,Ad)=>{"use strict";var jy=me(),Gy=0,Wy=Math.random(),Yy=jy(1 .toString);Ad.exports=function(a){return"Symbol("+(a===void 0?"":a)+")_"+Yy(++Gy+Wy,36)}});var ce=m((TM,kd)=>{"use strict";var Qy=X(),zy=Zn(),wd=Qe(),Ky=eo(),Jy=Yn(),Xy=Qn(),Pr=Qy.Symbol,to=zy("wks"),Zy=Xy?Pr.for||Pr:Pr&&Pr.withoutSetter||Ky;kd.exports=function(a){return wd(to,a)||(to[a]=Jy&&wd(Pr,a)?Pr[a]:Zy("Symbol."+a)),to[a]}});var Md=m((IM,Ld)=>{"use strict";var eT=Ae(),Rd=De(),$d=zn(),tT=li(),rT=fd(),iT=ce(),aT=TypeError,sT=iT("toPrimitive");Ld.exports=function(a,e){if(!Rd(a)||$d(a))return a;var t=tT(a,sT),r;if(t){if(e===void 0&&(e="default"),r=eT(t,a,e),!Rd(r)||$d(r))return r;throw new aT("Can't convert object to primitive value")}return e===void 0&&(e="number"),rT(a,e)}});var ro=m((EM,Cd)=>{"use strict";var nT=Md(),oT=zn();Cd.exports=function(a){var e=nT(a,"string");return oT(e)?e:e+""}});var Wt=m(Bd=>{"use strict";var uT=Be(),lT=Un(),cT=qn(),es=tt(),Dd=ro(),dT=TypeError,io=Object.defineProperty,pT=Object.getOwnPropertyDescriptor,ao="enumerable",so="configurable",no="writable";Bd.f=uT?cT?function(e,t,r){if(es(e),t=Dd(t),es(r),typeof e=="function"&&t==="prototype"&&"value"in r&&no in r&&!r[no]){var i=pT(e,t);i&&i[no]&&(e[t]=r.value,r={configurable:so in r?r[so]:i[so],enumerable:ao in r?r[ao]:i[ao],writable:!1})}return io(e,t,r)}:io:function(e,t,r){if(es(e),t=Dd(t),es(r),lT)try{return io(e,t,r)}catch(i){}if("get"in r||"set"in r)throw new dT("Accessors not supported");return"value"in r&&(e[t]=r.value),e}});var pi=m((PM,Od)=>{"use strict";Od.exports=function(a,e){return{enumerable:!(a&1),configurable:!(a&2),writable:!(a&4),value:e}}});var Ar=m((AM,Vd)=>{"use strict";var hT=Be(),fT=Wt(),mT=pi();Vd.exports=hT?function(a,e,t){return fT.f(a,e,mT(1,t))}:function(a,e,t){return a[e]=t,a}});var ts=m((wM,Nd)=>{"use strict";var bT=Zn(),gT=eo(),_d=bT("keys");Nd.exports=function(a){return _d[a]||(_d[a]=gT(a))}});var rs=m((kM,Fd)=>{"use strict";Fd.exports={}});var co=m((RM,Hd)=>{"use strict";var ST=_c(),qd=X(),vT=De(),yT=Ar(),oo=Qe(),uo=ci(),TT=ts(),IT=rs(),Ud="Object already initialized",lo=qd.TypeError,ET=qd.WeakMap,is,hi,as,xT=function(a){return as(a)?hi(a):is(a,{})},PT=function(a){return function(e){var t;if(!vT(e)||(t=hi(e)).type!==a)throw new lo("Incompatible receiver, "+a+" required");return t}};ST||uo.state?(ze=uo.state||(uo.state=new ET),ze.get=ze.get,ze.has=ze.has,ze.set=ze.set,is=function(a,e){if(ze.has(a))throw new lo(Ud);return e.facade=a,ze.set(a,e),e},hi=function(a){return ze.get(a)||{}},as=function(a){return ze.has(a)}):(Yt=TT("state"),IT[Yt]=!0,is=function(a,e){if(oo(a,Yt))throw new lo(Ud);return e.facade=a,yT(a,Yt,e),e},hi=function(a){return oo(a,Yt)?a[Yt]:{}},as=function(a){return oo(a,Yt)});var ze,Yt;Hd.exports={set:is,get:hi,has:as,enforce:xT,getterFor:PT}});var po=m(($M,Yd)=>{"use strict";var AT=ai(),Wd=Function.prototype,jd=Wd.apply,Gd=Wd.call;Yd.exports=typeof Reflect=="object"&&Reflect.apply||(AT?Gd.bind(jd):function(){return Gd.apply(jd,arguments)})});var ho=m((LM,Qd)=>{"use strict";var wT=Tr(),kT=me();Qd.exports=function(a){if(wT(a)==="Function")return kT(a)}});var Xd=m(Jd=>{"use strict";var zd={}.propertyIsEnumerable,Kd=Object.getOwnPropertyDescriptor,RT=Kd&&!zd.call({1:2},1);Jd.f=RT?function(e){var t=Kd(this,e);return!!t&&t.enumerable}:zd});var tp=m(ep=>{"use strict";var $T=Be(),LT=Ae(),MT=Xd(),CT=pi(),DT=Er(),BT=ro(),OT=Qe(),VT=Un(),Zd=Object.getOwnPropertyDescriptor;ep.f=$T?Zd:function(e,t){if(e=DT(e),t=BT(t),VT)try{return Zd(e,t)}catch(r){}if(OT(e,t))return CT(!LT(MT.f,e,t),e[t])}});var fo=m((DM,rp)=>{"use strict";var _T=Pe(),NT=J(),FT=/#|\.prototype\./,fi=function(a,e){var t=qT[UT(a)];return t===jT?!0:t===HT?!1:NT(e)?_T(e):!!e},UT=fi.normalize=function(a){return String(a).replace(FT,".").toLowerCase()},qT=fi.data={},HT=fi.NATIVE="N",jT=fi.POLYFILL="P";rp.exports=fi});var mi=m((BM,ap)=>{"use strict";var ip=ho(),GT=ut(),WT=ai(),YT=ip(ip.bind);ap.exports=function(a,e){return GT(a),e===void 0?a:WT?YT(a,e):function(){return a.apply(e,arguments)}}});var Oe=m((OM,np)=>{"use strict";var bi=X(),QT=po(),zT=ho(),KT=J(),JT=tp().f,XT=fo(),wr=Xa(),ZT=mi(),kr=Ar(),sp=Qe();ci();var eI=function(a){var e=function(t,r,i){if(this instanceof e){switch(arguments.length){case 0:return new a;case 1:return new a(t);case 2:return new a(t,r)}return new a(t,r,i)}return QT(a,this,arguments)};return e.prototype=a.prototype,e};np.exports=function(a,e){var t=a.target,r=a.global,i=a.stat,s=a.proto,n=r?bi:i?bi[t]:bi[t]&&bi[t].prototype,o=r?wr:wr[t]||kr(wr,t,{})[t],u=o.prototype,l,c,d,h,p,f,b,g,T;for(h in e)l=XT(r?h:t+(i?".":"#")+h,a.forced),c=!l&&n&&sp(n,h),f=o[h],c&&(a.dontCallGetSet?(T=JT(n,h),b=T&&T.value):b=n[h]),p=c&&b?b:e[h],!(!l&&!s&&typeof f==typeof p)&&(a.bind&&c?g=ZT(p,bi):a.wrap&&c?g=eI(p):s&&KT(p)?g=zT(p):g=p,(a.sham||p&&p.sham||f&&f.sham)&&kr(g,"sham",!0),kr(o,h,g),s&&(d=t+"Prototype",sp(wr,d)||kr(wr,d,{}),kr(wr[d],h,p),a.real&&u&&(l||!u[h])&&kr(u,h,p)))}});var lp=m((VM,up)=>{"use strict";var mo=Be(),tI=Qe(),op=Function.prototype,rI=mo&&Object.getOwnPropertyDescriptor,bo=tI(op,"name"),iI=bo&&function(){}.name==="something",aI=bo&&(!mo||mo&&rI(op,"name").configurable);up.exports={EXISTS:bo,PROPER:iI,CONFIGURABLE:aI}});var dp=m((_M,cp)=>{"use strict";var sI=Math.ceil,nI=Math.floor;cp.exports=Math.trunc||function(e){var t=+e;return(t>0?nI:sI)(t)}});var ss=m((NM,pp)=>{"use strict";var oI=dp();pp.exports=function(a){var e=+a;return e!==e||e===0?0:oI(e)}});var fp=m((FM,hp)=>{"use strict";var uI=ss(),lI=Math.max,cI=Math.min;hp.exports=function(a,e){var t=uI(a);return t<0?lI(t+e,0):cI(t,e)}});var bp=m((UM,mp)=>{"use strict";var dI=ss(),pI=Math.min;mp.exports=function(a){var e=dI(a);return e>0?pI(e,9007199254740991):0}});var ns=m((qM,gp)=>{"use strict";var hI=bp();gp.exports=function(a){return hI(a.length)}});var yp=m((HM,vp)=>{"use strict";var fI=Er(),mI=fp(),bI=ns(),Sp=function(a){return function(e,t,r){var i=fI(e),s=bI(i);if(s===0)return!a&&-1;var n=mI(r,s),o;if(a&&t!==t){for(;s>n;)if(o=i[n++],o!==o)return!0}else for(;s>n;n++)if((a||n in i)&&i[n]===t)return a||n||0;return!a&&-1}};vp.exports={includes:Sp(!0),indexOf:Sp(!1)}});var Ep=m((jM,Ip)=>{"use strict";var gI=me(),go=Qe(),SI=Er(),vI=yp().indexOf,yI=rs(),Tp=gI([].push);Ip.exports=function(a,e){var t=SI(a),r=0,i=[],s;for(s in t)!go(yI,s)&&go(t,s)&&Tp(i,s);for(;e.length>r;)go(t,s=e[r++])&&(~vI(i,s)||Tp(i,s));return i}});var So=m((GM,xp)=>{"use strict";xp.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var Ap=m((WM,Pp)=>{"use strict";var TI=Ep(),II=So();Pp.exports=Object.keys||function(e){return TI(e,II)}});var kp=m(wp=>{"use strict";var EI=Be(),xI=qn(),PI=Wt(),AI=tt(),wI=Er(),kI=Ap();wp.f=EI&&!xI?Object.defineProperties:function(e,t){AI(e);for(var r=wI(t),i=kI(t),s=i.length,n=0,o;s>n;)PI.f(e,o=i[n++],r[o]);return e}});var vo=m((QM,Rp)=>{"use strict";var RI=ot();Rp.exports=RI("document","documentElement")});var Eo=m((zM,Op)=>{"use strict";var $I=tt(),LI=kp(),$p=So(),MI=rs(),CI=vo(),DI=Ka(),BI=ts(),Lp=">",Mp="<",To="prototype",Io="script",Dp=BI("IE_PROTO"),yo=function(){},Bp=function(a){return Mp+Io+Lp+a+Mp+"/"+Io+Lp},Cp=function(a){a.write(Bp("")),a.close();var e=a.parentWindow.Object;return a=null,e},OI=function(){var a=DI("iframe"),e="java"+Io+":",t;return a.style.display="none",CI.appendChild(a),a.src=String(e),t=a.contentWindow.document,t.open(),t.write(Bp("document.F=Object")),t.close(),t.F},os,us=function(){try{os=new ActiveXObject("htmlfile")}catch(e){}us=typeof document!="undefined"?document.domain&&os?Cp(os):OI():Cp(os);for(var a=$p.length;a--;)delete us[To][$p[a]];return us()};MI[Dp]=!0;Op.exports=Object.create||function(e,t){var r;return e!==null?(yo[To]=$I(e),r=new yo,yo[To]=null,r[Dp]=e):r=us(),t===void 0?r:LI.f(r,t)}});var _p=m((KM,Vp)=>{"use strict";var VI=Pe();Vp.exports=!VI(function(){function a(){}return a.prototype.constructor=null,Object.getPrototypeOf(new a)!==a.prototype})});var Po=m((JM,Fp)=>{"use strict";var _I=Qe(),NI=J(),FI=di(),UI=ts(),qI=_p(),Np=UI("IE_PROTO"),xo=Object,HI=xo.prototype;Fp.exports=qI?xo.getPrototypeOf:function(a){var e=FI(a);if(_I(e,Np))return e[Np];var t=e.constructor;return NI(t)&&e instanceof t?t.prototype:e instanceof xo?HI:null}});var Rr=m((XM,Up)=>{"use strict";var jI=Ar();Up.exports=function(a,e,t,r){return r&&r.enumerable?a[e]=t:jI(a,e,t),a}});var Ro=m((ZM,jp)=>{"use strict";var GI=Pe(),WI=J(),YI=De(),QI=Eo(),qp=Po(),zI=Rr(),KI=ce(),JI=Ye(),ko=KI("iterator"),Hp=!1,lt,Ao,wo;[].keys&&(wo=[].keys(),"next"in wo?(Ao=qp(qp(wo)),Ao!==Object.prototype&&(lt=Ao)):Hp=!0);var XI=!YI(lt)||GI(function(){var a={};return lt[ko].call(a)!==a});XI?lt={}:JI&&(lt=QI(lt));WI(lt[ko])||zI(lt,ko,function(){return this});jp.exports={IteratorPrototype:lt,BUGGY_SAFARI_ITERATORS:Hp}});var ls=m((eC,Wp)=>{"use strict";var ZI=ce(),eE=ZI("toStringTag"),Gp={};Gp[eE]="z";Wp.exports=String(Gp)==="[object z]"});var gi=m((tC,Yp)=>{"use strict";var tE=ls(),rE=J(),cs=Tr(),iE=ce(),aE=iE("toStringTag"),sE=Object,nE=cs(function(){return arguments}())==="Arguments",oE=function(a,e){try{return a[e]}catch(t){}};Yp.exports=tE?cs:function(a){var e,t,r;return a===void 0?"Undefined":a===null?"Null":typeof(t=oE(e=sE(a),aE))=="string"?t:nE?cs(e):(r=cs(e))==="Object"&&rE(e.callee)?"Arguments":r}});var zp=m((rC,Qp)=>{"use strict";var uE=ls(),lE=gi();Qp.exports=uE?{}.toString:function(){return"[object "+lE(this)+"]"}});var Si=m((iC,Jp)=>{"use strict";var cE=ls(),dE=Wt().f,pE=Ar(),hE=Qe(),fE=zp(),mE=ce(),Kp=mE("toStringTag");Jp.exports=function(a,e,t,r){var i=t?a:a&&a.prototype;i&&(hE(i,Kp)||dE(i,Kp,{configurable:!0,value:e}),r&&!cE&&pE(i,"toString",fE))}});var Zp=m((aC,Xp)=>{"use strict";var bE=Ro().IteratorPrototype,gE=Eo(),SE=pi(),vE=Si(),yE=Gt(),TE=function(){return this};Xp.exports=function(a,e,t,r){var i=e+" Iterator";return a.prototype=gE(bE,{next:SE(+!r,t)}),vE(a,i,!1,!0),yE[i]=TE,a}});var th=m((sC,eh)=>{"use strict";var IE=me(),EE=ut();eh.exports=function(a,e,t){try{return IE(EE(Object.getOwnPropertyDescriptor(a,e)[t]))}catch(r){}}});var ih=m((nC,rh)=>{"use strict";var xE=De();rh.exports=function(a){return xE(a)||a===null}});var sh=m((oC,ah)=>{"use strict";var PE=ih(),AE=String,wE=TypeError;ah.exports=function(a){if(PE(a))return a;throw new wE("Can't set "+AE(a)+" as a prototype")}});var $o=m((uC,nh)=>{"use strict";var kE=th(),RE=De(),$E=si(),LE=sh();nh.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var a=!1,e={},t;try{t=kE(Object.prototype,"__proto__","set"),t(e,[]),a=e instanceof Array}catch(r){}return function(i,s){return $E(i),LE(s),RE(i)&&(a?t(i,s):i.__proto__=s),i}}():void 0)});var gh=m((lC,bh)=>{"use strict";var ME=Oe(),CE=Ae(),ds=Ye(),fh=lp(),DE=J(),BE=Zp(),oh=Po(),uh=$o(),OE=Si(),VE=Ar(),Lo=Rr(),_E=ce(),lh=Gt(),mh=Ro(),NE=fh.PROPER,FE=fh.CONFIGURABLE,ch=mh.IteratorPrototype,ps=mh.BUGGY_SAFARI_ITERATORS,vi=_E("iterator"),dh="keys",yi="values",ph="entries",hh=function(){return this};bh.exports=function(a,e,t,r,i,s,n){BE(t,e,r);var o=function(T){if(T===i&&h)return h;if(!ps&&T&&T in c)return c[T];switch(T){case dh:return function(){return new t(this,T)};case yi:return function(){return new t(this,T)};case ph:return function(){return new t(this,T)}}return function(){return new t(this)}},u=e+" Iterator",l=!1,c=a.prototype,d=c[vi]||c["@@iterator"]||i&&c[i],h=!ps&&d||o(i),p=e==="Array"&&c.entries||d,f,b,g;if(p&&(f=oh(p.call(new a)),f!==Object.prototype&&f.next&&(!ds&&oh(f)!==ch&&(uh?uh(f,ch):DE(f[vi])||Lo(f,vi,hh)),OE(f,u,!0,!0),ds&&(lh[u]=hh))),NE&&i===yi&&d&&d.name!==yi&&(!ds&&FE?VE(c,"name",yi):(l=!0,h=function(){return CE(d,this)})),i)if(b={values:o(yi),keys:s?h:o(dh),entries:o(ph)},n)for(g in b)(ps||l||!(g in c))&&Lo(c,g,b[g]);else ME({target:e,proto:!0,forced:ps||l},b);return(!ds||n)&&c[vi]!==h&&Lo(c,vi,h,{name:i}),lh[e]=h,b}});var vh=m((cC,Sh)=>{"use strict";Sh.exports=function(a,e){return{value:a,done:e}}});var Co=m((dC,xh)=>{"use strict";var UE=Er(),Mo=Vn(),yh=Gt(),Ih=co(),qE=Wt().f,HE=gh(),hs=vh(),jE=Ye(),GE=Be(),Eh="Array Iterator",WE=Ih.set,YE=Ih.getterFor(Eh);xh.exports=HE(Array,"Array",function(a,e){WE(this,{type:Eh,target:UE(a),index:0,kind:e})},function(){var a=YE(this),e=a.target,t=a.index++;if(!e||t>=e.length)return a.target=void 0,hs(void 0,!0);switch(a.kind){case"keys":return hs(t,!1);case"values":return hs(e[t],!1)}return hs([t,e[t]],!1)},"values");var Th=yh.Arguments=yh.Array;Mo("keys");Mo("values");Mo("entries");if(!jE&&GE&&Th.name!=="values")try{qE(Th,"name",{value:"values"})}catch(a){}});var Ah=m((pC,Ph)=>{"use strict";var QE=ce(),zE=Gt(),KE=QE("iterator"),JE=Array.prototype;Ph.exports=function(a){return a!==void 0&&(zE.Array===a||JE[KE]===a)}});var Do=m((hC,kh)=>{"use strict";var XE=gi(),wh=li(),ZE=Ir(),ex=Gt(),tx=ce(),rx=tx("iterator");kh.exports=function(a){if(!ZE(a))return wh(a,rx)||wh(a,"@@iterator")||ex[XE(a)]}});var $h=m((fC,Rh)=>{"use strict";var ix=Ae(),ax=ut(),sx=tt(),nx=ui(),ox=Do(),ux=TypeError;Rh.exports=function(a,e){var t=arguments.length<2?ox(a):e;if(ax(t))return sx(ix(t,a));throw new ux(nx(a)+" is not iterable")}});var Ch=m((mC,Mh)=>{"use strict";var lx=Ae(),Lh=tt(),cx=li();Mh.exports=function(a,e,t){var r,i;Lh(a);try{if(r=cx(a,"return"),!r){if(e==="throw")throw t;return t}r=lx(r,a)}catch(s){i=!0,r=s}if(e==="throw")throw t;if(i)throw r;return Lh(r),t}});var ms=m((bC,Vh)=>{"use strict";var dx=mi(),px=Ae(),hx=tt(),fx=ui(),mx=Ah(),bx=ns(),Dh=oi(),gx=$h(),Sx=Do(),Bh=Ch(),vx=TypeError,fs=function(a,e){this.stopped=a,this.result=e},Oh=fs.prototype;Vh.exports=function(a,e,t){var r=t&&t.that,i=!!(t&&t.AS_ENTRIES),s=!!(t&&t.IS_RECORD),n=!!(t&&t.IS_ITERATOR),o=!!(t&&t.INTERRUPTED),u=dx(e,r),l,c,d,h,p,f,b,g=function(y){return l&&Bh(l,"normal",y),new fs(!0,y)},T=function(y){return i?(hx(y),o?u(y[0],y[1],g):u(y[0],y[1])):o?u(y,g):u(y)};if(s)l=a.iterator;else if(n)l=a;else{if(c=Sx(a),!c)throw new vx(fx(a)+" is not iterable");if(mx(c)){for(d=0,h=bx(a);h>d;d++)if(p=T(a[d]),p&&Dh(Oh,p))return p;return new fs(!1)}l=gx(a,c)}for(f=s?a.next:l.next;!(b=px(f,l)).done;){try{p=T(b.value)}catch(y){Bh(l,"throw",y)}if(typeof p=="object"&&p&&Dh(Oh,p))return p}return new fs(!1)}});var Nh=m((gC,_h)=>{"use strict";var yx=Be(),Tx=Wt(),Ix=pi();_h.exports=function(a,e,t){yx?Tx.f(a,e,Ix(0,t)):a[e]=t}});var Fh=m(()=>{"use strict";var Ex=Oe(),xx=ms(),Px=Nh();Ex({target:"Object",stat:!0},{fromEntries:function(e){var t={};return xx(e,function(r,i){Px(t,r,i)},{AS_ENTRIES:!0}),t}})});var qh=m((yC,Uh)=>{"use strict";Co();Fh();var Ax=Xa();Uh.exports=Ax.Object.fromEntries});var jh=m((TC,Hh)=>{"use strict";Hh.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 Wh=m(()=>{"use strict";Co();var wx=jh(),kx=X(),Rx=Si(),Gh=Gt();for(bs in wx)Rx(kx[bs],bs),Gh[bs]=Gh.Array;var bs});var Qh=m((xC,Yh)=>{"use strict";var $x=qh();Wh();Yh.exports=$x});var Bo=m((PC,zh)=>{"use strict";var Lx=Qh();zh.exports=Lx});var Kh=m(()=>{"use strict"});var Oo=m((kC,Jh)=>{"use strict";var Ti=X(),Mx=xr(),Cx=Tr(),gs=function(a){return Mx.slice(0,a.length)===a};Jh.exports=function(){return gs("Bun/")?"BUN":gs("Cloudflare-Workers")?"CLOUDFLARE":gs("Deno/")?"DENO":gs("Node.js/")?"NODE":Ti.Bun&&typeof Bun.version=="string"?"BUN":Ti.Deno&&typeof Deno.version=="object"?"DENO":Cx(Ti.process)==="process"?"NODE":Ti.window&&Ti.document?"BROWSER":"REST"}()});var Ss=m((RC,Xh)=>{"use strict";var Dx=Oo();Xh.exports=Dx==="NODE"});var ef=m(($C,Zh)=>{"use strict";var Bx=Wt();Zh.exports=function(a,e,t){return Bx.f(a,e,t)}});var af=m((LC,rf)=>{"use strict";var Ox=ot(),Vx=ef(),_x=ce(),Nx=Be(),tf=_x("species");rf.exports=function(a){var e=Ox(a);Nx&&e&&!e[tf]&&Vx(e,tf,{configurable:!0,get:function(){return this}})}});var nf=m((MC,sf)=>{"use strict";var Fx=oi(),Ux=TypeError;sf.exports=function(a,e){if(Fx(e,a))return a;throw new Ux("Incorrect invocation")}});var _o=m((CC,of)=>{"use strict";var qx=me(),Hx=J(),Vo=ci(),jx=qx(Function.toString);Hx(Vo.inspectSource)||(Vo.inspectSource=function(a){return jx(a)});of.exports=Vo.inspectSource});var hf=m((DC,pf)=>{"use strict";var Gx=me(),Wx=Pe(),uf=J(),Yx=gi(),Qx=ot(),zx=_o(),lf=function(){},cf=Qx("Reflect","construct"),No=/^\s*(?:class|function)\b/,Kx=Gx(No.exec),Jx=!No.test(lf),Ii=function(e){if(!uf(e))return!1;try{return cf(lf,[],e),!0}catch(t){return!1}},df=function(e){if(!uf(e))return!1;switch(Yx(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return Jx||!!Kx(No,zx(e))}catch(t){return!0}};df.sham=!0;pf.exports=!cf||Wx(function(){var a;return Ii(Ii.call)||!Ii(Object)||!Ii(function(){a=!0})||a})?df:Ii});var mf=m((BC,ff)=>{"use strict";var Xx=hf(),Zx=ui(),eP=TypeError;ff.exports=function(a){if(Xx(a))return a;throw new eP(Zx(a)+" is not a constructor")}});var Fo=m((OC,gf)=>{"use strict";var bf=tt(),tP=mf(),rP=Ir(),iP=ce(),aP=iP("species");gf.exports=function(a,e){var t=bf(a).constructor,r;return t===void 0||rP(r=bf(t)[aP])?e:tP(r)}});var vf=m((VC,Sf)=>{"use strict";var sP=me();Sf.exports=sP([].slice)});var Tf=m((_C,yf)=>{"use strict";var nP=TypeError;yf.exports=function(a,e){if(a<e)throw new nP("Not enough arguments");return a}});var Uo=m((NC,If)=>{"use strict";var oP=xr();If.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(oP)});var Ko=m((FC,Lf)=>{"use strict";var we=X(),uP=po(),lP=mi(),Ef=J(),cP=Qe(),$f=Pe(),xf=vo(),dP=vf(),Pf=Ka(),pP=Tf(),hP=Uo(),fP=Ss(),Yo=we.setImmediate,Qo=we.clearImmediate,mP=we.process,qo=we.Dispatch,bP=we.Function,Af=we.MessageChannel,gP=we.String,Ho=0,Ei={},wf="onreadystatechange",xi,Qt,jo,Go;$f(function(){xi=we.location});var zo=function(a){if(cP(Ei,a)){var e=Ei[a];delete Ei[a],e()}},Wo=function(a){return function(){zo(a)}},kf=function(a){zo(a.data)},Rf=function(a){we.postMessage(gP(a),xi.protocol+"//"+xi.host)};(!Yo||!Qo)&&(Yo=function(e){pP(arguments.length,1);var t=Ef(e)?e:bP(e),r=dP(arguments,1);return Ei[++Ho]=function(){uP(t,void 0,r)},Qt(Ho),Ho},Qo=function(e){delete Ei[e]},fP?Qt=function(a){mP.nextTick(Wo(a))}:qo&&qo.now?Qt=function(a){qo.now(Wo(a))}:Af&&!hP?(jo=new Af,Go=jo.port2,jo.port1.onmessage=kf,Qt=lP(Go.postMessage,Go)):we.addEventListener&&Ef(we.postMessage)&&!we.importScripts&&xi&&xi.protocol!=="file:"&&!$f(Rf)?(Qt=Rf,we.addEventListener("message",kf,!1)):wf in Pf("script")?Qt=function(a){xf.appendChild(Pf("script"))[wf]=function(){xf.removeChild(this),zo(a)}}:Qt=function(a){setTimeout(Wo(a),0)});Lf.exports={set:Yo,clear:Qo}});var Df=m((UC,Cf)=>{"use strict";var Mf=X(),SP=Be(),vP=Object.getOwnPropertyDescriptor;Cf.exports=function(a){if(!SP)return Mf[a];var e=vP(Mf,a);return e&&e.value}});var Jo=m((qC,Of)=>{"use strict";var Bf=function(){this.head=null,this.tail=null};Bf.prototype={add:function(a){var e={item:a,next:null},t=this.tail;t?t.next=e:this.head=e,this.tail=e},get:function(){var a=this.head;if(a){var e=this.head=a.next;return e===null&&(this.tail=null),a.item}}};Of.exports=Bf});var _f=m((HC,Vf)=>{"use strict";var yP=xr();Vf.exports=/ipad|iphone|ipod/i.test(yP)&&typeof Pebble!="undefined"});var Ff=m((jC,Nf)=>{"use strict";var TP=xr();Nf.exports=/web0s(?!.*chrome)/i.test(TP)});var Yf=m((GC,Wf)=>{"use strict";var Lr=X(),IP=Df(),Uf=mi(),Xo=Ko().set,EP=Jo(),xP=Uo(),PP=_f(),AP=Ff(),Zo=Ss(),qf=Lr.MutationObserver||Lr.WebKitMutationObserver,Hf=Lr.document,jf=Lr.process,vs=Lr.Promise,ru=IP("queueMicrotask"),$r,eu,tu,ys,Gf;ru||(Pi=new EP,Ai=function(){var a,e;for(Zo&&(a=jf.domain)&&a.exit();e=Pi.get();)try{e()}catch(t){throw Pi.head&&$r(),t}a&&a.enter()},!xP&&!Zo&&!AP&&qf&&Hf?(eu=!0,tu=Hf.createTextNode(""),new qf(Ai).observe(tu,{characterData:!0}),$r=function(){tu.data=eu=!eu}):!PP&&vs&&vs.resolve?(ys=vs.resolve(void 0),ys.constructor=vs,Gf=Uf(ys.then,ys),$r=function(){Gf(Ai)}):Zo?$r=function(){jf.nextTick(Ai)}:(Xo=Uf(Xo,Lr),$r=function(){Xo(Ai)}),ru=function(a){Pi.head||$r(),Pi.add(a)});var Pi,Ai;Wf.exports=ru});var zf=m((WC,Qf)=>{"use strict";Qf.exports=function(a,e){try{arguments.length===1?console.error(a):console.error(a,e)}catch(t){}}});var Ts=m((YC,Kf)=>{"use strict";Kf.exports=function(a){try{return{error:!1,value:a()}}catch(e){return{error:!0,value:e}}}});var zt=m((QC,Jf)=>{"use strict";var wP=X();Jf.exports=wP.Promise});var Mr=m((zC,tm)=>{"use strict";var kP=X(),wi=zt(),RP=J(),$P=fo(),LP=_o(),MP=ce(),Xf=Oo(),CP=Ye(),iu=Wn(),Zf=wi&&wi.prototype,DP=MP("species"),au=!1,em=RP(kP.PromiseRejectionEvent),BP=$P("Promise",function(){var a=LP(wi),e=a!==String(wi);if(!e&&iu===66||CP&&!(Zf.catch&&Zf.finally))return!0;if(!iu||iu<51||!/native code/.test(a)){var t=new wi(function(s){s(1)}),r=function(s){s(function(){},function(){})},i=t.constructor={};if(i[DP]=r,au=t.then(function(){})instanceof r,!au)return!0}return!e&&(Xf==="BROWSER"||Xf==="DENO")&&!em});tm.exports={CONSTRUCTOR:BP,REJECTION_EVENT:em,SUBCLASSING:au}});var Cr=m((KC,im)=>{"use strict";var rm=ut(),OP=TypeError,VP=function(a){var e,t;this.promise=new a(function(r,i){if(e!==void 0||t!==void 0)throw new OP("Bad Promise constructor");e=r,t=i}),this.resolve=rm(e),this.reject=rm(t)};im.exports.f=function(a){return new VP(a)}});var Im=m(()=>{"use strict";var _P=Oe(),NP=Ye(),Ps=Ss(),Pt=X(),Vr=Ae(),am=Rr(),sm=$o(),FP=Si(),UP=af(),qP=ut(),xs=J(),HP=De(),jP=nf(),GP=Fo(),cm=Ko().set,lu=Yf(),WP=zf(),YP=Ts(),QP=Jo(),dm=co(),As=zt(),cu=Mr(),pm=Cr(),ws="Promise",hm=cu.CONSTRUCTOR,zP=cu.REJECTION_EVENT,KP=cu.SUBCLASSING,su=dm.getterFor(ws),JP=dm.set,Dr=As&&As.prototype,Kt=As,Is=Dr,fm=Pt.TypeError,nu=Pt.document,du=Pt.process,ou=pm.f,XP=ou,ZP=!!(nu&&nu.createEvent&&Pt.dispatchEvent),mm="unhandledrejection",eA="rejectionhandled",nm=0,bm=1,tA=2,pu=1,gm=2,Es,om,rA,um,Sm=function(a){var e;return HP(a)&&xs(e=a.then)?e:!1},vm=function(a,e){var t=e.value,r=e.state===bm,i=r?a.ok:a.fail,s=a.resolve,n=a.reject,o=a.domain,u,l,c;try{i?(r||(e.rejection===gm&&aA(e),e.rejection=pu),i===!0?u=t:(o&&o.enter(),u=i(t),o&&(o.exit(),c=!0)),u===a.promise?n(new fm("Promise-chain cycle")):(l=Sm(u))?Vr(l,u,s,n):s(u)):n(t)}catch(d){o&&!c&&o.exit(),n(d)}},ym=function(a,e){a.notified||(a.notified=!0,lu(function(){for(var t=a.reactions,r;r=t.get();)vm(r,a);a.notified=!1,e&&!a.rejection&&iA(a)}))},Tm=function(a,e,t){var r,i;ZP?(r=nu.createEvent("Event"),r.promise=e,r.reason=t,r.initEvent(a,!1,!0),Pt.dispatchEvent(r)):r={promise:e,reason:t},!zP&&(i=Pt["on"+a])?i(r):a===mm&&WP("Unhandled promise rejection",t)},iA=function(a){Vr(cm,Pt,function(){var e=a.facade,t=a.value,r=lm(a),i;if(r&&(i=YP(function(){Ps?du.emit("unhandledRejection",t,e):Tm(mm,e,t)}),a.rejection=Ps||lm(a)?gm:pu,i.error))throw i.value})},lm=function(a){return a.rejection!==pu&&!a.parent},aA=function(a){Vr(cm,Pt,function(){var e=a.facade;Ps?du.emit("rejectionHandled",e):Tm(eA,e,a.value)})},Br=function(a,e,t){return function(r){a(e,r,t)}},Or=function(a,e,t){a.done||(a.done=!0,t&&(a=t),a.value=e,a.state=tA,ym(a,!0))},uu=function(a,e,t){if(!a.done){a.done=!0,t&&(a=t);try{if(a.facade===e)throw new fm("Promise can't be resolved itself");var r=Sm(e);r?lu(function(){var i={done:!1};try{Vr(r,e,Br(uu,i,a),Br(Or,i,a))}catch(s){Or(i,s,a)}}):(a.value=e,a.state=bm,ym(a,!1))}catch(i){Or({done:!1},i,a)}}};if(hm&&(Kt=function(e){jP(this,Is),qP(e),Vr(Es,this);var t=su(this);try{e(Br(uu,t),Br(Or,t))}catch(r){Or(t,r)}},Is=Kt.prototype,Es=function(e){JP(this,{type:ws,done:!1,notified:!1,parent:!1,reactions:new QP,rejection:!1,state:nm,value:void 0})},Es.prototype=am(Is,"then",function(e,t){var r=su(this),i=ou(GP(this,Kt));return r.parent=!0,i.ok=xs(e)?e:!0,i.fail=xs(t)&&t,i.domain=Ps?du.domain:void 0,r.state===nm?r.reactions.add(i):lu(function(){vm(i,r)}),i.promise}),om=function(){var a=new Es,e=su(a);this.promise=a,this.resolve=Br(uu,e),this.reject=Br(Or,e)},pm.f=ou=function(a){return a===Kt||a===rA?new om(a):XP(a)},!NP&&xs(As)&&Dr!==Object.prototype)){um=Dr.then,KP||am(Dr,"then",function(e,t){var r=this;return new Kt(function(i,s){Vr(um,r,i,s)}).then(e,t)},{unsafe:!0});try{delete Dr.constructor}catch(a){}sm&&sm(Dr,Is)}_P({global:!0,constructor:!0,wrap:!0,forced:hm},{Promise:Kt});FP(Kt,ws,!1,!0);UP(ws)});var wm=m((ZC,Am)=>{"use strict";var sA=ce(),xm=sA("iterator"),Pm=!1;try{Em=0,hu={next:function(){return{done:!!Em++}},return:function(){Pm=!0}},hu[xm]=function(){return this},Array.from(hu,function(){throw 2})}catch(a){}var Em,hu;Am.exports=function(a,e){try{if(!e&&!Pm)return!1}catch(i){return!1}var t=!1;try{var r={};r[xm]=function(){return{next:function(){return{done:t=!0}}}},a(r)}catch(i){}return t}});var fu=m((eD,km)=>{"use strict";var nA=zt(),oA=wm(),uA=Mr().CONSTRUCTOR;km.exports=uA||!oA(function(a){nA.all(a).then(void 0,function(){})})});var Rm=m(()=>{"use strict";var lA=Oe(),cA=Ae(),dA=ut(),pA=Cr(),hA=Ts(),fA=ms(),mA=fu();lA({target:"Promise",stat:!0,forced:mA},{all:function(e){var t=this,r=pA.f(t),i=r.resolve,s=r.reject,n=hA(function(){var o=dA(t.resolve),u=[],l=0,c=1;fA(e,function(d){var h=l++,p=!1;c++,cA(o,t,d).then(function(f){p||(p=!0,u[h]=f,--c||i(u))},s)}),--c||i(u)});return n.error&&s(n.value),r.promise}})});var Lm=m(()=>{"use strict";var bA=Oe(),gA=Ye(),SA=Mr().CONSTRUCTOR,bu=zt(),vA=ot(),yA=J(),TA=Rr(),$m=bu&&bu.prototype;bA({target:"Promise",proto:!0,forced:SA,real:!0},{catch:function(a){return this.then(void 0,a)}});!gA&&yA(bu)&&(mu=vA("Promise").prototype.catch,$m.catch!==mu&&TA($m,"catch",mu,{unsafe:!0}));var mu});var Mm=m(()=>{"use strict";var IA=Oe(),EA=Ae(),xA=ut(),PA=Cr(),AA=Ts(),wA=ms(),kA=fu();IA({target:"Promise",stat:!0,forced:kA},{race:function(e){var t=this,r=PA.f(t),i=r.reject,s=AA(function(){var n=xA(t.resolve);wA(e,function(o){EA(n,t,o).then(r.resolve,i)})});return s.error&&i(s.value),r.promise}})});var Cm=m(()=>{"use strict";var RA=Oe(),$A=Cr(),LA=Mr().CONSTRUCTOR;RA({target:"Promise",stat:!0,forced:LA},{reject:function(e){var t=$A.f(this),r=t.reject;return r(e),t.promise}})});var gu=m((lD,Dm)=>{"use strict";var MA=tt(),CA=De(),DA=Cr();Dm.exports=function(a,e){if(MA(a),CA(e)&&e.constructor===a)return e;var t=DA.f(a),r=t.resolve;return r(e),t.promise}});var Vm=m(()=>{"use strict";var BA=Oe(),OA=ot(),Bm=Ye(),VA=zt(),Om=Mr().CONSTRUCTOR,_A=gu(),NA=OA("Promise"),FA=Bm&&!Om;BA({target:"Promise",stat:!0,forced:Bm||Om},{resolve:function(e){return _A(FA&&this===NA?VA:this,e)}})});var _m=m(()=>{"use strict";Im();Rm();Lm();Mm();Cm();Vm()});var qm=m(()=>{"use strict";var UA=Oe(),qA=Ye(),ks=zt(),HA=Pe(),Fm=ot(),Um=J(),jA=Fo(),Nm=gu(),GA=Rr(),vu=ks&&ks.prototype,WA=!!ks&&HA(function(){vu.finally.call({then:function(){}},function(){})});UA({target:"Promise",proto:!0,real:!0,forced:WA},{finally:function(a){var e=jA(this,Fm("Promise")),t=Um(a);return this.then(t?function(r){return Nm(e,a()).then(function(){return r})}:a,t?function(r){return Nm(e,a()).then(function(){throw r})}:a)}});!qA&&Um(ks)&&(Su=Fm("Promise").prototype.finally,vu.finally!==Su&&GA(vu,"finally",Su,{unsafe:!0}));var Su});var Rs=m((bD,Hm)=>{"use strict";var YA=ot();Hm.exports=YA});var Gm=m((gD,jm)=>{"use strict";Kh();_m();qm();var QA=Rs();jm.exports=QA("Promise","finally")});var Ym=m((SD,Wm)=>{"use strict";var zA=Gm();Wm.exports=zA});var $s=m((vD,Qm)=>{"use strict";var KA=Ym();Qm.exports=KA});var vb=m(()=>{"use strict";var Pw=Oe(),Aw=di(),ww=ns(),kw=ss(),Rw=Vn();Pw({target:"Array",proto:!0},{at:function(e){var t=Aw(this),r=ww(t),i=kw(e),s=i>=0?i:r+i;return s<0||s>=r?void 0:t[s]}});Rw("at")});var Tb=m((k0,yb)=>{"use strict";vb();var $w=Rs();yb.exports=$w("Array","at")});var Eb=m((R0,Ib)=>{"use strict";var Lw=Tb();Ib.exports=Lw});var Fr=m(($0,xb)=>{"use strict";var Mw=Eb();xb.exports=Mw});var $g=m(()=>{"use strict"});var Lg=m(()=>{"use strict"});var Cg=m((U_,Mg)=>{"use strict";var Fk=De(),Uk=Tr(),qk=ce(),Hk=qk("match");Mg.exports=function(a){var e;return Fk(a)&&((e=a[Hk])!==void 0?!!e:Uk(a)==="RegExp")}});var Bg=m((q_,Dg)=>{"use strict";var jk=gi(),Gk=String;Dg.exports=function(a){if(jk(a)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return Gk(a)}});var Vg=m((H_,Og)=>{"use strict";var Wk=tt();Og.exports=function(){var a=Wk(this),e="";return a.hasIndices&&(e+="d"),a.global&&(e+="g"),a.ignoreCase&&(e+="i"),a.multiline&&(e+="m"),a.dotAll&&(e+="s"),a.unicode&&(e+="u"),a.unicodeSets&&(e+="v"),a.sticky&&(e+="y"),e}});var Fg=m((j_,Ng)=>{"use strict";var Yk=Ae(),Qk=Qe(),zk=oi(),Kk=Vg(),_g=RegExp.prototype;Ng.exports=function(a){var e=a.flags;return e===void 0&&!("flags"in _g)&&!Qk(a,"flags")&&zk(_g,a)?Yk(Kk,a):e}});var qg=m((G_,Ug)=>{"use strict";var zu=me(),Jk=di(),Xk=Math.floor,Yu=zu("".charAt),Zk=zu("".replace),Qu=zu("".slice),eR=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,tR=/\$([$&'`]|\d{1,2})/g;Ug.exports=function(a,e,t,r,i,s){var n=t+a.length,o=r.length,u=tR;return i!==void 0&&(i=Jk(i),u=eR),Zk(s,u,function(l,c){var d;switch(Yu(c,0)){case"$":return"$";case"&":return a;case"`":return Qu(e,0,t);case"'":return Qu(e,n);case"<":d=i[Qu(c,1,-1)];break;default:var h=+c;if(h===0)return l;if(h>o){var p=Xk(h/10);return p===0?l:p<=o?r[p-1]===void 0?Yu(c,1):r[p-1]+Yu(c,1):l}d=r[h-1]}return d===void 0?"":d})}});var Gg=m(()=>{"use strict";var rR=Oe(),iR=Ae(),Ju=me(),Hg=si(),aR=J(),sR=Ir(),nR=Cg(),Wr=Bg(),oR=li(),uR=Fg(),lR=qg(),cR=ce(),dR=Ye(),pR=cR("replace"),hR=TypeError,Ku=Ju("".indexOf),fR=Ju("".replace),jg=Ju("".slice),mR=Math.max;rR({target:"String",proto:!0},{replaceAll:function(e,t){var r=Hg(this),i,s,n,o,u,l,c,d,h,p,f=0,b="";if(!sR(e)){if(i=nR(e),i&&(s=Wr(Hg(uR(e))),!~Ku(s,"g")))throw new hR("`.replaceAll` does not allow non-global regexes");if(n=oR(e,pR),n)return iR(n,e,r,t);if(dR&&i)return fR(Wr(r),e,t)}for(o=Wr(r),u=Wr(e),l=aR(t),l||(t=Wr(t)),c=u.length,d=mR(1,c),h=Ku(o,u);h!==-1;)p=l?Wr(t(u,h,o)):lR(u,o,h,[],void 0,t),b+=jg(o,f,h)+p,f=h+c,h=h+d>o.length?-1:Ku(o,u,h+d);return f<o.length&&(b+=jg(o,f)),b}})});var Yg=m((Q_,Wg)=>{"use strict";$g();Lg();Gg();var bR=Rs();Wg.exports=bR("String","replaceAll")});var zg=m((z_,Qg)=>{"use strict";var gR=Yg();Qg.exports=gR});var Jg=m((K_,Kg)=>{"use strict";var SR=zg();Kg.exports=SR});var hc="2.0.116-dev.d1ccc575.0";var fe=(i=>(i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused",i))(fe||{}),xt=(S=>(S.MPEG="MPEG",S.DASH="DASH",S.DASH_SEP="DASH_SEP",S.DASH_SEP_VK="DASH_SEP",S.DASH_WEBM="DASH_WEBM",S.DASH_WEBM_AV1="DASH_WEBM_AV1",S.DASH_STREAMS="DASH_STREAMS",S.DASH_WEBM_VK="DASH_WEBM",S.DASH_ONDEMAND="DASH_ONDEMAND",S.DASH_ONDEMAND_VK="DASH_ONDEMAND",S.DASH_LIVE="DASH_LIVE",S.DASH_LIVE_CMAF="DASH_LIVE_CMAF",S.DASH_LIVE_WEBM="DASH_LIVE_WEBM",S.HLS="HLS",S.HLS_ONDEMAND="HLS_ONDEMAND",S.HLS_JS="HLS",S.HLS_LIVE="HLS_LIVE",S.HLS_LIVE_CMAF="HLS_LIVE_CMAF",S.WEB_RTC_LIVE="WEB_RTC_LIVE",S))(xt||{});var Ya=(i=>(i.NOT_AVAILABLE="NOT_AVAILABLE",i.AVAILABLE="AVAILABLE",i.CONNECTING="CONNECTING",i.CONNECTED="CONNECTED",i))(Ya||{}),Ln=(r=>(r.HTTP1="http1",r.HTTP2="http2",r.QUIC="quic",r))(Ln||{});var Mn=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(Mn||{});import{assertNever as vc,assertNonNullable as Ov,isNonNullable as Qa,ValueSubject as Cn,Subject as Vv,Subscription as _v,merge as Nv,observableFrom as Fv,fromEvent as mc,map as bc,tap as gc,filterChanged as Uv,isNullable as Dn,ErrorCategory as Sc}from"@vkontakte/videoplayer-shared";var fc=a=>new Promise((e,t)=>{let r=document.createElement("script");r.setAttribute("src",a),r.onload=()=>e,r.onerror=()=>t,document.body.appendChild(r)});var za=class{constructor(e){this.connection$=new Cn(void 0);this.castState$=new Cn("NOT_AVAILABLE");this.errorEvent$=new Vv;this.realCastState$=new Cn("NOT_AVAILABLE");this.subscription=new _v;var s;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastInitializer");let t="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${t}`}),e.isDisabled||!t)return;let r=Qa((s=window.chrome)==null?void 0:s.cast),i=!!window.__onGCastApiAvailable;r?this.initializeCastApi():(window.__onGCastApiAvailable=n=>{delete window.__onGCastApiAvailable,n&&this.initializeCastApi()},i||fc("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:Sc.NETWORK,message:"Script loading failed!"})))}connect(){var e;(e=cast.framework.CastContext.getInstance())==null||e.requestSession()}disconnect(){var e,t;(t=(e=cast.framework.CastContext.getInstance())==null?void 0:e.getCurrentSession())==null||t.endSession(!0)}stopMedia(){return new Promise((e,t)=>{var r,i,s;(s=(i=(r=cast.framework.CastContext.getInstance())==null?void 0:r.getCurrentSession())==null?void 0:i.getMediaSession())==null||s.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){Qa(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();Dn(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();Dn(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(mc(r,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(i=>{var s,n,o;switch(i.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=(o=(n=(s=r.getCurrentSession())==null?void 0:s.getMediaSession())==null?void 0:n.media)==null?void 0:o.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return vc(i.sessionState)}})).add(Nv(mc(r,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(gc(i=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(i)}`})}),bc(i=>i.castState)),Fv([r.getCastState()])).pipe(Uv(),bc(qv),gc(i=>{this.log({message:`realCastState$: ${i}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(i=>{var o,u;let s=i==="CONNECTED",n=Qa(this.connection$.getValue());if(s&&!n){let l=r.getCurrentSession();Ov(l);let c=l.getCastDevice(),d=(u=(o=l.getMediaSession())==null?void 0:o.media)==null?void 0:u.contentId;(Dn(d)||d===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:l,castDevice:c}))}else!s&&n&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(i==="CONNECTED"?Qa(this.connection$.getValue())?"CONNECTED":"AVAILABLE":i)}))}initializeCastApi(){var i;let e,t,r;try{e=cast.framework.CastContext.getInstance(),t=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,r=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch(s){return}try{e.setOptions({receiverApplicationId:(i=this.params.receiverApplicationId)!=null?i:t,autoJoinPolicy:r}),this.initListeners()}catch(s){this.errorEvent$.next({id:"ChromecastInitializer",category:Sc.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:s})}}},qv=a=>{switch(a){case cast.framework.CastState.NO_DEVICES_AVAILABLE:return"NOT_AVAILABLE";case cast.framework.CastState.NOT_CONNECTED:return"AVAILABLE";case cast.framework.CastState.CONNECTING:return"CONNECTING";case cast.framework.CastState.CONNECTED:return"CONNECTED";default:return vc(a)}};var XS=Ge(Bo(),1);var ab=Ge($s(),1);import{assertNever as zm}from"@vkontakte/videoplayer-shared";var ne=(a,e=0,t=0)=>{switch(t){case 0:return a.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case 1:{if(e===0)return a;let r=new URL(a);return r.searchParams.append("playback_shift",e.toFixed(0)),r.toString()}case 2:{let r=new URL(a);return!r.searchParams.get("offset_p")&&e===0?a:(r.searchParams.set("offset_p",e.toFixed(0)),r.toString())}default:zm(t)}return a},yu=(a,e)=>{var t;switch(e){case 0:return NaN;case 1:{let r=new URL(a);return Number(r.searchParams.get("playback_shift"))}case 2:{let r=new URL(a);return Number((t=r.searchParams.get("offset_p"))!=null?t:0)}default:zm(e)}};var x=(a,e,t=!1)=>{let r=a.getTransition();(t||!r||r.to===e)&&a.setState(e)};import{isNonNullable as JA,Subject as Ls,merge as Km}from"@vkontakte/videoplayer-shared";var C=class{constructor(e){this.transitionStarted$=new Ls;this.transitionEnded$=new Ls;this.transitionUpdated$=new Ls;this.forceChanged$=new Ls;this.stateChangeStarted$=Km(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=Km(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||JA(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 XA}from"@vkontakte/videoplayer-shared";var Jm=a=>{switch(a){case"MPEG":case"DASH":case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":case"HLS":case"HLS_ONDEMAND":return!1;case"DASH_LIVE":case"DASH_LIVE_CMAF":case"HLS_LIVE":case"HLS_LIVE_CMAF":case"DASH_LIVE_WEBM":case"WEB_RTC_LIVE":return!0;default:return XA(a)}};import{assertNever as _r,assertNonNullable as Jt,debounce as Xm,ErrorCategory as Zm,fromEvent as Xt,isNonNullable as eb,map as tb,merge as rb,observableFrom as ZA,Subject as ew,Subscription as Tu,timeout as tw,getHighestQuality as rw}from"@vkontakte/videoplayer-shared";var iw=5,aw=5,sw=500,ib=7e3,ki=class{constructor(e){this.subscription=new Tu;this.loadMediaTimeoutSubscription=new Tu;this.videoState=new C("stopped");this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),r=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${r}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(s)};`}),r==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.stop());return}if(!t){if((i==null?void 0:i.to)!=="paused"&&s.state==="requested"&&e!=="stopped"){this.seek(s.position/1e3);return}switch(r){case"ready":{switch(e){case"playing":case"paused":case"ready":break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:_r(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:_r(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:_r(e)}break}default:_r(r)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(Jm(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 Tu;this.subscription.add(e),this.subscription.add(rb(this.videoState.stateChangeStarted$.pipe(tb(i=>`stateChangeStarted$ ${JSON.stringify(i)}`)),this.videoState.stateChangeEnded$.pipe(tb(i=>`stateChangeEnded$ ${JSON.stringify(i)}`))).subscribe(i=>this.log({message:`[videoState] ${i}`})));let t=(i,s)=>this.subscription.add(i.subscribe(s));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{let i=new ew;e.add(i.pipe(Xm(sw)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add(Xt(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)>iw)&&i.next(o),s=o})),e.add(Xt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(Xt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),i=>{this.logRemoteEvent(i),i.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(Xt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),i=>{this.logRemoteEvent(i),i.value?this.handleRemotePause():this.handleRemotePlay()}),t(Xt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),i=>{this.logRemoteEvent(i);let{remotePlayer:s}=this.params.connection,n=i.value,o=this.params.output.isBuffering$.getValue(),u=n===chrome.cast.media.PlayerState.BUFFERING;switch(o!==u&&this.params.output.isBuffering$.next(u),n){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&s.duration-s.currentTime<aw&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),x(this.params.desiredState.playbackState,"stopped");break;case chrome.cast.media.PlayerState.PAUSED:{this.handleRemotePause();break}case chrome.cast.media.PlayerState.PLAYING:this.handleRemotePlay();break;case chrome.cast.media.PlayerState.BUFFERING:break;default:_r(n)}}),t(Xt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),i=>{this.logRemoteEvent(i),this.handleRemoteVolumeChange({volume:i.value})}),t(Xt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),i=>{this.logRemoteEvent(i),this.handleRemoteVolumeChange({muted:i.value})});let r=rb(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,ZA(["init"])).pipe(Xm(0));t(r,this.syncPlayback)}restoreSession(e){this.log({message:"restoreSession"});let{remotePlayer:t}=this.params.connection;if(e.playerState!==chrome.cast.media.PlayerState.IDLE){t.isPaused?(this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),x(this.params.desiredState.playbackState,"playing"));let r=this.params.output.isLive$.getValue();this.params.output.duration$.next(r?0:t.duration),this.params.output.position$.next(r?0:t.currentTime),this.params.desiredState.seekState.setState({state:"none"})}}prepare(){let e=this.params.format;this.log({message:`[prepare] format: ${e}`});let t=this.createMediaInfo(e),r=this.createLoadRequest(t);this.loadMedia(r)}handleRemotePause(){let e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)==="paused"||e==="playing")&&(this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused"))}handleRemotePlay(){let e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)==="playing"||e==="paused")&&(this.videoState.setState("playing"),x(this.params.desiredState.playbackState,"playing"))}handleRemoteReady(){var t;let e=this.videoState.getTransition();(e==null?void 0:e.to)==="ready"&&this.videoState.setState("ready"),((t=this.params.desiredState.playbackState.getTransition())==null?void 0:t.to)==="ready"&&x(this.params.desiredState.playbackState,"ready")}handleRemoteStop(){this.videoState.getState()!=="stopped"&&this.videoState.setState("stopped")}handleRemoteVolumeChange(e){var i,s;let t=this.params.output.volume$.getValue(),r={volume:(i=e.volume)!=null?i:t.volume,muted:(s=e.muted)!=null?s:t.muted};(r.volume!==t.volume||r.muted!==r.muted)&&this.params.output.volume$.next(r)}seek(e){this.params.output.willSeekEvent$.next();let{remotePlayer:t,remotePlayerController:r}=this.params.connection;t.currentTime=e,r.seek()}stop(){let{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){var l;let t=this.params.source,r,i,s;switch(e){case"MPEG":{let c=t[e];Jt(c);let d=rw(Object.keys(c));Jt(d);let h=c[d];Jt(h),r=h,i="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let c=t[e];Jt(c),r=c.url,i="application/x-mpegurl",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":{let c=t[e];Jt(c),r=c.url,i="application/dash+xml",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let c=t[e];Jt(c),r=c.url,i="application/dash+xml",s=chrome.cast.media.StreamType.LIVE;break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let c=t[e];Jt(c),r=ne(c.url),i="application/x-mpegurl",s=chrome.cast.media.StreamType.LIVE;break}case"DASH_LIVE":case"WEB_RTC_LIVE":{let c="Unsupported format for Chromecast",d=new Error(c);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:Zm.VIDEO_PIPELINE,message:c,thrown:d}),d}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return _r(e)}let n=new chrome.cast.media.MediaInfo((l=this.params.meta.videoId)!=null?l:r,i);n.contentUrl=r,n.streamType=s,n.metadata=new chrome.cast.media.GenericMediaMetadata;let{title:o,subtitle:u}=this.params.meta;return eb(o)&&(n.metadata.title=o),eb(u)&&(n.metadata.subtitle=u),n}createLoadRequest(e){let t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;let r=this.params.desiredState.seekState.getState();return r.state==="applying"||r.state==="requested"?t.currentTime=this.params.output.isLive$.getValue()?0:r.position/1e3:t.currentTime=0,t}loadMedia(e){let t=this.params.connection.session.loadMedia(e),r=new Promise((i,s)=>{this.loadMediaTimeoutSubscription.add(tw(ib).subscribe(()=>s(`timeout(${ib})`)))});(0,ab.default)(Promise.race([t,r]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},i=>{let s=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${i}`;this.log({message:s}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:Zm.VIDEO_PIPELINE,message:s,thrown:i})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};import{clearVideoElement as nb}from"@vkontakte/videoplayer-shared";import{clearVideoElement as nw}from"@vkontakte/videoplayer-shared";var sb=a=>{try{a.pause(),a.playbackRate=0,nw(a),a.remove()}catch(e){console.error(e)}};import{fromEvent as ow,Subscription as uw}from"@vkontakte/videoplayer-shared";var Iu=class{constructor(){this.attribute="data-pool-reused"}get(e){return e.hasAttribute(this.attribute)}set(e,t){e.toggleAttribute(this.attribute,t)}delete(e){e.removeAttribute(this.attribute)}},Eu=window.WeakMap?new WeakMap:new Iu,xu=window.WeakMap?new WeakMap:new Map,lw=(a,e=20)=>{let t=0;return ow(a,"ratechange").subscribe(r=>{t++,t>=e&&(a.currentTime=a.currentTime,t=0)})},be=(a,{audioVideoSyncRate:e})=>{let t=a.querySelector("video"),r=!!t;t?nb(t):(t=document.createElement("video"),a.appendChild(t)),Eu.set(t,r);let i=new uw;return i.add(lw(t,e)),xu.set(t,i),t.setAttribute("crossorigin","anonymous"),t.setAttribute("playsinline","playsinline"),t.controls=!1,t.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),t},ge=a=>{let e=xu.get(a);e==null||e.unsubscribe(),xu.delete(a);let t=Eu.get(a);Eu.delete(a),t?nb(a):sb(a)};import{assertNonNullable as Ri,isNonNullable as it,isNullable as pw,fromEvent as Nr,merge as ob,observableFrom as ub,filterChanged as lb,map as $i,Subject as cb,Subscription as hw,ValueSubject as fw,ErrorCategory as mw}from"@vkontakte/videoplayer-shared";import{isNonNullable as Pu,isNullable as cw,Subscription as dw}from"@vkontakte/videoplayer-shared";var Ms=(a,e,t,{equal:r=(n,o)=>n===o,changed$:i,onError:s}={})=>{let n=a.getState(),o=e(),u=cw(i),l=new dw;return i&&l.add(i.subscribe(c=>{let d=a.getState();r(c,d)&&a.setState(c)},s)),r(o,n)||(t(n),u&&a.setState(n)),l.add(a.stateChangeStarted$.subscribe(c=>{t(c.to),u&&a.setState(c.to)},s)),l},rt=(a,e,t)=>Ms(e,()=>a.loop,r=>{Pu(r)&&(a.loop=r)},{onError:t}),Se=(a,e,t,r)=>Ms(e,()=>({muted:a.muted,volume:a.volume}),i=>{Pu(i)&&(a.muted=i.muted,a.volume=i.volume)},{equal:(i,s)=>i===s||(i==null?void 0:i.muted)===(s==null?void 0:s.muted)&&(i==null?void 0:i.volume)===(s==null?void 0:s.volume),changed$:t,onError:r}),Ve=(a,e,t,r)=>Ms(e,()=>a.playbackRate,i=>{Pu(i)&&(a.playbackRate=i)},{changed$:t,onError:r}),At=Ms;var bw=a=>["__",a.language,a.label].join("|"),gw=(a,e)=>{if(a.id===e)return!0;let[t,r,i]=e.split("|");return a.language===r&&a.label===i},Au=class a{constructor(){this.available$=new cb;this.current$=new fw(void 0);this.error$=new cb;this.subscription=new hw;this.externalTracks=new Map;this.internalTracks=new Map}connect(e,t,r){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();let i=s=>{this.error$.next({id:"TextTracksManager",category:mw.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:s})};this.subscription.add(this.available$.subscribe(r.availableTextTracks$)),this.subscription.add(this.current$.subscribe(r.currentTextTrack$)),this.subscription.add(this.error$.subscribe(r.error$)),this.subscription.add(At(t.internalTextTracks,()=>Object.values(this.internalTracks),s=>{it(s)&&this.setInternal(s)},{equal:(s,n)=>it(s)&&it(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe($i(s=>s.filter(({type:n})=>n==="internal"))),onError:i})),this.subscription.add(At(t.externalTextTracks,()=>Object.values(this.externalTracks),s=>{it(s)&&this.setExternal(s)},{equal:(s,n)=>it(s)&&it(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe($i(s=>s.filter(({type:n})=>n==="external"))),onError:i})),this.subscription.add(At(t.currentTextTrack,()=>{if(this.video)return;let s=this.htmlTextTracksAsArray().find(({mode:n})=>n==="showing");return s&&this.htmlTextTrackToITextTrack(s).id},s=>this.select(s),{changed$:this.current$,onError:i})),this.subscription.add(At(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.activeCues)}))}subscribe(){Ri(this.video);let{textTracks:e}=this.video;this.subscription.add(Nr(e,"addtrack").subscribe(()=>{let r=this.current$.getValue();r&&this.select(r)})),this.subscription.add(ob(Nr(e,"addtrack"),Nr(e,"removetrack"),ub(["init"])).pipe($i(()=>this.htmlTextTracksAsArray().map(r=>this.htmlTextTrackToITextTrack(r))),lb((r,i)=>r.length===i.length&&r.every(({id:s},n)=>s===i[n].id))).subscribe(this.available$)),this.subscription.add(ob(Nr(e,"change"),ub(["init"])).pipe($i(()=>this.htmlTextTracksAsArray().find(({mode:r})=>r==="showing")),$i(r=>r&&this.htmlTextTrackToITextTrack(r).id),lb()).subscribe(this.current$));let t=r=>{var i,s;return this.applyCueSettings((s=(i=r.target)==null?void 0:i.activeCues)!=null?s:null)};this.subscription.add(Nr(e,"addtrack").subscribe(r=>{var s,n;(s=r.track)==null||s.addEventListener("cuechange",t);let i=o=>{var l,c,d,h,p;let u=(c=(l=o.target)==null?void 0:l.cues)!=null?c:null;u&&u.length&&(this.applyCueSettings((h=(d=o.target)==null?void 0:d.cues)!=null?h:null),(p=o.target)==null||p.removeEventListener("cuechange",i))};(n=r.track)==null||n.addEventListener("cuechange",i)})),this.subscription.add(Nr(e,"removetrack").subscribe(r=>{var i;(i=r.track)==null||i.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;let t=this.cueSettings.getState();for(let r of Array.from(e)){let i=r;it(t.align)&&(i.align=t.align),it(t.position)&&(i.position=t.position),it(t.size)&&(i.size=t.size),it(t.line)&&(i.line=t.line)}}htmlTextTracksAsArray(e=!1){Ri(this.video);let t=[...this.video.textTracks];return e?t:t.filter(a.isHealthyTrack)}htmlTextTrackToITextTrack(e){var o,u,l,c;let{language:t,label:r}=e,i=e.id?e.id:bw(e),s=this.externalTracks.has(i),n=(s?(o=this.externalTracks.get(i))==null?void 0:o.isAuto:(u=this.internalTracks.get(i))==null?void 0:u.isAuto)||i.includes("auto");return s?{id:i,type:"external",isAuto:n,language:t,label:r,url:(l=this.externalTracks.get(i))==null?void 0:l.url}:{id:i,type:"internal",isAuto:n,language:t,label:r,url:(c=this.internalTracks.get(i))==null?void 0:c.url}}static isHealthyTrack(e){return!(e.kind==="metadata"||e.groupId||e.id===""&&e.label===""&&e.language==="")}setExternal(e){this.internalTracks.size>0&&Array.from(this.internalTracks).forEach(([,t])=>this.detach(t)),e.filter(({id:t})=>!this.externalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.externalTracks).filter(([t])=>!e.find(r=>r.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){let t=[...this.externalTracks];e.filter(({id:r,language:i,isAuto:s})=>!this.internalTracks.has(r)&&!t.some(([,n])=>n.language===i&&n.isAuto===s)).forEach(r=>this.attach(r)),Array.from(this.internalTracks).filter(([r])=>!e.find(i=>i.id===r)).forEach(([,r])=>this.detach(r))}select(e){Ri(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(pw(e)||!gw(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){Ri(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){Ri(this.video);let t=Array.prototype.find.call(this.video.getElementsByTagName("track"),r=>r.getAttribute("id")===e.id);t&&this.video.removeChild(t),e.type==="external"?this.externalTracks.delete(e.id):e.type==="internal"&&this.internalTracks.delete(e.id)}},_e=Au;var dt=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 db=a=>{let e=a;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e==null?void 0:e.parentNode;return e!=null?e:void 0},wu=a=>{let e=db(a);return!!(e&&e.fullscreenElement&&e.fullscreenElement===a)},pb=a=>{let e=db(a);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===a)};import{fromEvent as Ne,map as wt,merge as fb,filterChanged as vw,isNonNullable as mb,Subject as yw,filter as bb,mapTo as gb,combine as Tw,once as Iw,ErrorCategory as Ew,ValueSubject as Sb,clientChecker as xw}from"@vkontakte/videoplayer-shared";var Sw=3,hb=(a,e,t=Sw)=>{let r=0,i=0;for(let s=0;s<a.length;s++){let n=a.start(s),o=a.end(s);if(n<=e&&e<=o){if(r=n,i=o,!t)return{from:r,to:i};for(let u=s-1;u>=0;u--)a.end(u)+t>=r&&(r=a.start(u));for(let u=s+1;u<a.length;u++)a.start(u)-t<=i&&(i=a.end(u))}}return{from:r,to:i}};var ve=a=>{let e=S=>Ne(a,S).pipe(gb(void 0)),r=fb(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(S=>Ne(a,S))).pipe(wt(S=>S.type==="ended"?a.readyState<2:a.readyState<3),vw()),i=fb(Ne(a,"progress"),Ne(a,"timeupdate")).pipe(wt(()=>hb(a.buffered,a.currentTime))),s=xw.isSafari?Tw({play:e("play").pipe(Iw()),playing:e("playing")}).pipe(gb(void 0)):e("playing"),n=Ne(a,"volumechange").pipe(wt(()=>({muted:a.muted,volume:a.volume}))),o=Ne(a,"ratechange").pipe(wt(()=>a.playbackRate)),u=Ne(a,"error").pipe(bb(()=>!!(a.error||a.played.length)),wt(()=>{var I;let S=a.error;return{id:S?`MediaError#${S.code}`:"HtmlVideoError",category:Ew.VIDEO_PIPELINE,message:S?S.message:"Error event from HTML video element",thrown:(I=a.error)!=null?I:void 0}})),l=Ne(a,"timeupdate").pipe(wt(()=>a.currentTime)),c=new yw,d=.3,h;l.subscribe(S=>{a.loop&&mb(h)&&mb(S)&&h>=a.duration-d&&S<=d&&c.next(h),h=S});let p=e("pause").pipe(bb(()=>!a.error&&h!==a.duration)),f=Ne(a,"enterpictureinpicture"),b=Ne(a,"leavepictureinpicture"),g=new Sb(pb(a));f.subscribe(()=>g.next(!0)),b.subscribe(()=>g.next(!1));let T=new Sb(wu(a));return Ne(a,"fullscreenchange").pipe(wt(()=>wu(a))).subscribe(T),{playing$:s,pause$:p,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$:Ne(a,"durationchange").pipe(wt(()=>a.duration)),isBuffering$:r,currentBuffer$:i,volumeState$:n,playbackRateState$:o,inPiP$:g,inFullscreen$:T}};import{VideoQuality as kt}from"@vkontakte/videoplayer-shared";var Rt=a=>{switch(a){case"mobile":return kt.Q_144P;case"lowest":return kt.Q_240P;case"low":return kt.Q_360P;case"sd":case"medium":return kt.Q_480P;case"hd":case"high":return kt.Q_720P;case"fullhd":case"full":return kt.Q_1080P;case"quadhd":case"quad":return kt.Q_1440P;case"ultrahd":case"ultra":return kt.Q_2160P}};var Zt=Ge(Fr(),1);import{isNonNullable as te,isNullable as Ru,now as Mb,isHigher as $u,isHigherOrEqual as kb,isInvariantQuality as Rb,isLower as $b,isLowerOrEqual as Lu,videoSizeToQuality as Cw,assertNotEmptyArray as Cb,assertNonNullable as Dw}from"@vkontakte/videoplayer-shared";var ku=!1,pt={},Pb=a=>{ku=a},Ab=()=>{pt={}},wb=a=>{a(pt)},Li=(a,e)=>{var t;ku&&(pt.meta=(t=pt.meta)!=null?t:{},pt.meta[a]=e)},de=class{constructor(e){this.name=e}next(e){var r,i;if(!ku)return;pt.series=(r=pt.series)!=null?r:{};let t=(i=pt.series[this.name])!=null?i:[];t.push([Date.now(),e]),pt.series[this.name]=t}};var Bw=new de("best_bitrate"),Db=(a,e,t)=>(e-t)*Math.pow(2,-10*a)+t;var Mu=a=>(e,t)=>a*(Number(e.bitrate)-Number(t.bitrate)),Mi=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=Mb()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},Bb='Assertion "ABR Tracks is empty array" failed',Cs=(a,e,t,r)=>{var u;let i=[...e].sort(Mu(1)),s=[...t].sort(Mu(1)),n=s.filter(l=>te(l.bitrate)&&te(a.bitrate)?a.bitrate/l.bitrate>r:!0),o=(u=(0,Zt.default)(s,Math.round(s.length*i.indexOf(a)/(i.length+1))))!=null?u:(0,Zt.default)(s,-1);return o&&n.includes(o)?o:n.length?(0,Zt.default)(n,-1):(0,Zt.default)(s,0)},Lb=a=>"quality"in a,Ob=(a,e,t,r)=>{var n;let i=te((n=r==null?void 0:r.last)==null?void 0:n.bitrate)&&te(t==null?void 0:t.bitrate)&&r.last.bitrate<t.bitrate?a.trackCooldownIncreaseQuality:a.trackCooldownDecreaseQuality,s=t&&r&&r.history[t.id]&&Mb()-r.history[t.id]<=i&&(!r.last||t.id!==r.last.id);if(t!=null&&t.id&&r&&!s&&r.recordSelection(t),s&&(r!=null&&r.last)){let o=r.last;r==null||r.recordSwitch(o);let u=Lb(o)?"video":"audio",l=Lb(o)?o.quality:o.bitrate;return e({message:`
7
7
  [last ${u} selected] ${l}
8
- `}),o}return r==null||r.recordSwitch(t),t},$t=(a,{container:e,throughput:t,tuning:r,limits:i,reserve:s=0,forwardBufferHealth:n,playbackRate:o,current:u,history:l,visible:c,droppedVideoMaxQualityLimit:d,abrLogger:h})=>{var _,w,U,L,W;Bb(a,Vb);let p=(_=window.devicePixelRatio)!=null?_:1,f=r.usePixelRatio?r.pixelRatioMultiplier*(p-1)+1:1,b=r.limitByContainer&&e&&e.width>0&&e.height>0&&{width:e.width*f*r.containerSizeFactor,height:e.height*f*r.containerSizeFactor},g=b&&Cw(b),S=r.considerPlaybackRate&&te(o)?o:1,y=a.filter(v=>!Lb(v.quality)).sort((v,$)=>Lu(v.quality,$.quality)?-1:1),T=(w=(0,Xt.default)(y,-1))==null?void 0:w.quality,I=(U=(0,Xt.default)(y,0))==null?void 0:U.quality,E=$u(i)||te(i.min)&&te(i.max)&&Mb(i.max,i.min)||te(i.min)&&I&&Lu(i.min,I)||te(i.max)&&T&&Mb(i.max,T),k=S*Ob(n!=null?n:.5,r.bitrateFactorAtEmptyBuffer,r.bitrateFactorAtFullBuffer),B={},V=y.filter(v=>{if(!(g?Mu(v.quality,g):!0))return B[v.quality]="FitsContainer",!1;if(!(te(t)&&isFinite(t)&&te(v.bitrate)?t-s>=v.bitrate*k:!0))return B[v.quality]="FitsThroughput",!1;if(r.lazyQualitySwitch&&te(r.minBufferToSwitchUp)&&u&&!Lb(u.quality)&&(n!=null?n:0)<r.minBufferToSwitchUp&&Lu(v.quality,u.quality))return B[v.quality]="Buffer",!1;if(!!d&&$b(v.quality,d))return B[v.quality]="DroppedFramesLimit",!1;let Ue=E||($u(i.max)||Mu(v.quality,i.max))&&($u(i.min)||$b(v.quality,i.min)),dr=te(c)&&!c?Mu(v.quality,r.backgroundVideoQualityLimit):!0;return!Ue||!dr?(B[v.quality]="FitsQualityLimits",!1):!0})[0];V&&V.bitrate&&Bw.next(V.bitrate);let M=(L=V!=null?V:y[Math.ceil((y.length-1)/2)])!=null?L:a[0];return M.quality!==((W=l==null?void 0:l.last)==null?void 0:W.quality)&&h({message:`
8
+ `}),o}return r==null||r.recordSwitch(t),t},$t=(a,{container:e,throughput:t,tuning:r,limits:i,reserve:s=0,forwardBufferHealth:n,playbackRate:o,current:u,history:l,visible:c,droppedVideoMaxQualityLimit:d,abrLogger:h})=>{var _,R,U,L,W;Cb(a,Bb);let p=(_=window.devicePixelRatio)!=null?_:1,f=r.usePixelRatio?r.pixelRatioMultiplier*(p-1)+1:1,b=r.limitByContainer&&e&&e.width>0&&e.height>0&&{width:e.width*f*r.containerSizeFactor,height:e.height*f*r.containerSizeFactor},g=b&&Cw(b),T=r.considerPlaybackRate&&te(o)?o:1,y=a.filter(v=>!Rb(v.quality)).sort((v,$)=>$u(v.quality,$.quality)?-1:1),S=(R=(0,Zt.default)(y,-1))==null?void 0:R.quality,I=(U=(0,Zt.default)(y,0))==null?void 0:U.quality,E=Ru(i)||te(i.min)&&te(i.max)&&$b(i.max,i.min)||te(i.min)&&I&&$u(i.min,I)||te(i.max)&&S&&$b(i.max,S),k=T*Db(n!=null?n:.5,r.bitrateFactorAtEmptyBuffer,r.bitrateFactorAtFullBuffer),B={},V=y.filter(v=>{if(!(g?Lu(v.quality,g):!0))return B[v.quality]="FitsContainer",!1;if(!(te(t)&&isFinite(t)&&te(v.bitrate)?t-s>=v.bitrate*k:!0))return B[v.quality]="FitsThroughput",!1;if(r.lazyQualitySwitch&&te(r.minBufferToSwitchUp)&&u&&!Rb(u.quality)&&(n!=null?n:0)<r.minBufferToSwitchUp&&$u(v.quality,u.quality))return B[v.quality]="Buffer",!1;if(!!d&&kb(v.quality,d))return B[v.quality]="DroppedFramesLimit",!1;let qe=E||(Ru(i.max)||Lu(v.quality,i.max))&&(Ru(i.min)||kb(v.quality,i.min)),pr=te(c)&&!c?Lu(v.quality,r.backgroundVideoQualityLimit):!0;return!qe||!pr?(B[v.quality]="FitsQualityLimits",!1):!0})[0];V&&V.bitrate&&Bw.next(V.bitrate);let M=(L=V!=null?V:y[Math.ceil((y.length-1)/2)])!=null?L:a[0];return M.quality!==((W=l==null?void 0:l.last)==null?void 0:W.quality)&&h({message:`
9
9
  [VIDEO TRACKS ABR]
10
10
  [available video tracks]
11
11
  ${a.map(v=>`{ id: ${v.id}, quality: ${v.quality}, bitrate: ${v.bitrate} }`).join(`
@@ -20,7 +20,7 @@ var kv=Object.create;var Rn=Object.defineProperty,Rv=Object.defineProperties,$v=
20
20
  throughput: ${t},
21
21
  reserve: ${s},
22
22
  playbackRate: ${o},
23
- playbackRateFactor: ${S},
23
+ playbackRateFactor: ${T},
24
24
  forwardBufferHealth: ${n},
25
25
  bitrateFactor: ${k},
26
26
  minBufferToSwitchUp: ${r.minBufferToSwitchUp},
@@ -35,14 +35,14 @@ var kv=Object.create;var Rn=Object.defineProperty,Rv=Object.defineProperties,$v=
35
35
 
36
36
  [best video track] ${V==null?void 0:V.quality}
37
37
  [selected video track] ${M==null?void 0:M.quality}
38
- `}),_b(r,h,M,l)},Nb=(a,e,t,{throughput:r,tuning:i,playbackRate:s,forwardBufferHealth:n,history:o,abrLogger:u})=>{var b;Bb(t,Vb);let l=i.considerPlaybackRate&&te(s)?s:1,c=[...t].sort(Cu(-1)),d=a.bitrate;Dw(d);let h=l*Ob(n!=null?n:.5,i.bitrateAudioFactorAtEmptyBuffer,i.bitrateAudioFactorAtFullBuffer),p,f=Ms(a,e,t,i.minVideoAudioRatio);return te(r)&&isFinite(r)&&(p=c.find(g=>te(g.bitrate)&&te(f==null?void 0:f.bitrate)?r-d>=g.bitrate*h&&g.bitrate>=f.bitrate:!1)),p||(p=f),(p==null?void 0:p.bitrate)!==((b=o==null?void 0:o.last)==null?void 0:b.bitrate)&&u({message:`
38
+ `}),Ob(r,h,M,l)},Vb=(a,e,t,{throughput:r,tuning:i,playbackRate:s,forwardBufferHealth:n,history:o,abrLogger:u})=>{var b;Cb(t,Bb);let l=i.considerPlaybackRate&&te(s)?s:1,c=[...t].sort(Mu(-1)),d=a.bitrate;Dw(d);let h=l*Db(n!=null?n:.5,i.bitrateAudioFactorAtEmptyBuffer,i.bitrateAudioFactorAtFullBuffer),p,f=Cs(a,e,t,i.minVideoAudioRatio);return te(r)&&isFinite(r)&&(p=c.find(g=>te(g.bitrate)&&te(f==null?void 0:f.bitrate)?r-d>=g.bitrate*h&&g.bitrate>=f.bitrate:!1)),p||(p=f),(p==null?void 0:p.bitrate)!==((b=o==null?void 0:o.last)==null?void 0:b.bitrate)&&u({message:`
39
39
  [AUDIO TRACKS ABR]
40
40
  [available audio tracks]
41
41
  ${t.map(g=>`{ id: ${g.id}, bitrate: ${g.bitrate} }`).join(`
42
42
  `)}
43
43
 
44
44
  [tuning]
45
- ${Object.entries(i!=null?i:{}).map(([g,S])=>`${g}: ${S}`).join(`
45
+ ${Object.entries(i!=null?i:{}).map(([g,T])=>`${g}: ${T}`).join(`
46
46
  `)}
47
47
 
48
48
  [limit params]
@@ -55,14 +55,14 @@ var kv=Object.create;var Rn=Object.defineProperty,Rv=Object.defineProperties,$v=
55
55
  minBufferToSwitchUp: ${i.minBufferToSwitchUp},
56
56
 
57
57
  [selected audio track] ${p==null?void 0:p.id}
58
- `}),p&&_b(i,u,p,o)};var re=a=>new URL(a).hostname;import{assertNever as Gb,assertNonNullable as Wb,combine as rk,debounce as ik,ErrorCategory as Yb,filter as Qb,filterChanged as ak,isNonNullable as _u,map as Vs,merge as zb,observableFrom as sk,once as nk,Subscription as ok,ValueSubject as Nu,videoQualityToHeight as uk,videoSizeToQuality as lk}from"@vkontakte/videoplayer-shared";var Fb=a=>{if(a instanceof DOMException&&["Failed to load because no supported source was found.","The element has no supported sources."].includes(a.message))throw a;return!(a instanceof DOMException&&(a.code===20||a.name==="AbortError"))},ye=(a,e)=>R(void 0,null,function*(){let t=a.muted;try{yield a.play()}catch(r){if(!Fb(r))return!1;if(e&&e(),t)return console.warn(r),!1;a.muted=!0;try{yield a.play()}catch(i){return Fb(i)&&(a.muted=!1,console.warn(i)),!1}}return!0});import{isNonNullable as Ds,isNullable as _w,assertNonNullable as Oi}from"@vkontakte/videoplayer-shared";import{isNonNullable as Ub,assertNonNullable as Cs,now as Ow}from"@vkontakte/videoplayer-shared";function ie(){return Ow()}function Du(a){return ie()-a}function Bu(a){let e=a.split("/"),t=e.slice(0,e.length-1).join("/"),r=/^([a-z]+:)?\/\//i,i=n=>r.test(n);return{resolve:(n,o,u=!1)=>{i(n)||(n.startsWith("/")||(n="/"+n),n=t+n);let l=n.indexOf("?")>-1?"&":"?";return u&&(n+=l+"lowLat=1",l="&"),o&&(n+=l+"_rnd="+Math.floor(999999999*Math.random())),n}}}function qb(a,e,t){let r=(...i)=>{t.apply(null,i),a.removeEventListener(e,r)};a.addEventListener(e,r)}function Fr(a,e,t,r){let i=window.XMLHttpRequest,s,n,o,u=!1,l=0,c,d,h=!1,p="arraybuffer",f=7e3,b=2e3,g=()=>{if(u)return;Cs(c);let w=Du(c),U;if(w<b){U=b-w,setTimeout(g,U);return}b*=2,b>f&&(b=f),n&&n.abort(),n=new i,k()},S=w=>(s=w,_),y=w=>(d=w,_),T=()=>(p="json",_),I=()=>{if(!u){if(--l>=0){g(),r&&r();return}u=!0,d&&d(),t&&t()}},E=w=>(h=w,_),k=()=>{c=ie(),n=new i,n.open("get",a);let w=0,U,L=0,W=()=>(Cs(c),Math.max(c,Math.max(U||0,L||0)));if(s&&n.addEventListener("progress",v=>{let $=ie();s.updateChunk&&v.loaded>w&&(s.updateChunk(W(),v.loaded-w),w=v.loaded,U=$)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>I())),n.addEventListener("load",()=>{if(u)return;Cs(n);let v=n.status;if(v>=200&&v<300){if(n.response.byteLength&&s){let $=n.response.byteLength-w;$&&s.updateChunk&&s.updateChunk(W(),$)}n.responseType==="json"&&!Object.values(n.response).length?I():(d&&d(),e(n.response))}else I()}),n.addEventListener("error",()=>{I()}),h){let v=()=>{Cs(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(L=ie(),n.removeEventListener("readystatechange",v))};n.addEventListener("readystatechange",v)}return n.responseType=p,n.send(),_},_={withBitrateReporting:S,withParallel:E,withJSONResponse:T,withRetryCount:w=>(l=w,_),withRetryInterval:(w,U)=>(Ub(w)&&(b=w),Ub(U)&&(f=U),_),withTimeout:w=>(o=w,_),withFinally:y,send:k,abort:()=>{n&&(n.abort(),n=void 0),u=!0,d&&d()}};return _}var Di=class{constructor(e){this.intervals=[];this.currentRate=0;this.logger=e}_updateRate(e){let t=.2;this.currentRate&&(e<this.currentRate*.1?t=.8:e<this.currentRate*.5?t=.5:e<this.currentRate*.7&&(t=.3)),e=Math.max(1,Math.min(e,100*1024*1024)),this.currentRate=this.currentRate?this.currentRate*(1-t)+e*t:e}_createInterval(e,t,r){return{start:e,end:t,bytes:r}}_doMergeIntervals(e,t){e.start=Math.min(t.start,e.start),e.end=Math.max(t.end,e.end),e.bytes+=t.bytes}_mergeIntervals(e,t){return e.start<=t.end&&t.start<=e.end?(this._doMergeIntervals(e,t),!0):!1}_flushIntervals(){if(!this.intervals.length)return!1;let e=this.intervals[0].start,t=this.intervals[this.intervals.length-1].end-500;if(t-e>2e3){let r=0,i=0;for(;this.intervals.length>0;){let s=this.intervals[0];if(s.end<=t)r+=s.end-s.start,i+=s.bytes,this.intervals.splice(0,1);else{if(s.start>=t)break;{let n=t-s.start,o=s.end-s.start;r+=n;let u=s.bytes*n/o;i+=u,s.start=t,s.bytes-=u}}}if(i>0&&r>0){let s=i*8/(r/1e3);return this._updateRate(s),this.logger(`rate updated, new=${Math.round(s/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(i)}/${Math.round(r)} interval=${Math.round(t-e)}`),!0}}return!1}_joinIntervals(){let e;do{e=!1;for(let t=0;t<this.intervals.length-1;++t)this._mergeIntervals(this.intervals[t],this.intervals[t+1])&&(this.intervals.splice(t+1,1),e=!0)}while(e)}addInterval(e,t,r){return this.intervals.push(this._createInterval(e,t,r)),this._joinIntervals(),this.intervals.length>100&&(this.logger(`too many intervals (${this.intervals.length}); will merge`,{type:"warn"}),this._doMergeIntervals(this.intervals[1],this.intervals[0]),this.intervals.splice(0,1)),this._flushIntervals()}getBitRate(){return this.currentRate}};var Bi=class{constructor(e,t,r,i,s){this.pendingQueue=[];this.activeRequests={};this.completeRequests={};this.averageSegmentDuration=2e3;this.lastPrefetchStart=0;this.throttleTimeout=null;this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=r,this.MAX_PARALLEL_REQUESTS=i,this.logger=s}limitCompleteCount(){let e;for(;(e=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){let t=e[Math.floor(Math.random()*e.length)];this.logger(`Dropping completed request for url ${t}`,{type:"warn"}),delete this.completeRequests[t]}}_sendRequest(e,t){let r=ie(),i=u=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=u,e._errorCB?e._errorCB(u):(this.limitCompleteCount(),this.completeRequests[t]=e)},s=u=>{e._complete=1,e._responseData=u,e._downloadTime=ie()-r,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(u,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},n=()=>{e._finallyCB&&e._finallyCB()},o=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=Fr(t,s,()=>i("error"),o),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally(n),this.activeRequests[t]=e,e._request.send(),this.lastPrefetchStart=ie()}_getParallelRequestCount(){return Math.min(this.MAX_PARALLEL_REQUESTS,this.averageSegmentDuration<3e3?3:2)}_getPrefetchDelay(){return Math.max(100,Math.min(5e3,this.averageSegmentDuration/3))}_canSendPending(){let e=this._getParallelRequestCount(),t=ie();if(Object.keys(this.activeRequests).length>=e)return!1;let r=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),r>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),r),!1):!0}_sendPending(){for(;this._canSendPending();){let e=this.pendingQueue.pop();if(e){if(this.activeRequests[e]||this.completeRequests[e])continue;this.logger(`Submitting pending request url=${e}`),this._sendRequest({},e)}else return}}_removeFromActive(e){delete this.completeRequests[e],delete this.activeRequests[e]}abortAll(){Object.values(this.activeRequests).forEach(e=>{e&&e._request&&e._request.abort()}),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,r,i){let s={};return s.send=()=>{let n=this.activeRequests[e]||this.completeRequests[e];if(n)n._cb=t,n._errorCB=r,n._retryCB=i,n._finallyCB=s._finallyCB,n._error||n._complete?(this._removeFromActive(e),setTimeout(()=>{n._complete?(this.logger(`Requested url already prefetched, url=${e}`),t(n._responseData,n._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${e}`),r(n._errorMsg)),s._finallyCB&&s._finallyCB()},0)):this.logger(`Attached to active request, url=${e}`);else{let o=this.pendingQueue.indexOf(e);o!==-1&&this.pendingQueue.splice(o,1),this.logger(`Request not prefetched, starting new request, url=${e}${o===-1?"":"; removed pending"}`),this._sendRequest(s,e)}},s._cb=t,s._errorCB=r,s._retryCB=i,s.abort=function(){s.request&&s.request.abort()},s.withFinally=n=>(s._finallyCB=n,s),s}prefetch(e){this.activeRequests[e]||this.completeRequests[e]?this.logger(`Request already active for url=${e}`):(this.logger(`Added to pending queue; url=${e}`),this.pendingQueue.unshift(e),this._sendPending())}optimizeForSegDuration(e){this.averageSegmentDuration=e}};import{Subject as Nw}from"@vkontakte/videoplayer-shared";var Bs=1e4,Ou=3;var Fw=6e4,Uw=10,qw=1,Hw=500,Vi=class{constructor(e){this.paused=!1;this.autoQuality=!0;this.maxAutoQuality=void 0;this.buffering=!0;this.destroyed=!1;this.videoPlayStarted=!1;this.lowLatency=!1;this.bitrate=0;this.manifest=[];this.sourceBuffer=0;this.bufferStates=[];this.sourceJitter=-1;this.params=e,this.soundProhibitedEvent$=new Nw,this.chunkRateEstimator=new Di(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=Bu(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setMaxAutoQuality(e){this.maxAutoQuality=e}switchByName(e){let t;for(let r=0;r<this.manifest.length;++r)if(t=this.manifest[r],t.name===e){this._switchToQuality(t);return}}catchUp(){this.rep&&this.rep.stop(),this.currentManifestEntry&&(this.paused=!1,this._initPlayerWith(this.currentManifestEntry),this._notifyBuffering(!0))}stop(){this.params.videoElement.pause(),this.rep&&(this.rep.stop(),this.rep=null)}pause(){this.paused=!0,this.params.videoElement.pause(),this.videoPlayStarted=!1,this._notifyBuffering(!1)}play(){this.paused=!1;let e=this.lowLatency&&this._getBufferSizeSec()>this.sourceJitter+5;this.rep&&!e?(this.bufferStates=[],this.videoPlayStarted=!1,this.shouldPlay()?this._playVideoElement():this._notifyBuffering(!0)):this.catchUp()}startPlay(e,t){this.autoQuality=t,this._initPlayerWith(e)}destroy(){this.destroyed=!0,this.rep&&(this.rep.stop(),this.rep=null),this.manifestRequest&&this.manifestRequest.abort(),this.manifestRefetchTimer&&(clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=void 0)}reinit(e){this.manifestUrl=e,this.urlResolver=Bu(e),this.catchUp()}_handleNetworkError(){this.params.logger("Fatal network error"),this.params.playerCallback({name:"error",type:"network"})}_retryCallback(){this.params.playerCallback({name:"retry"})}_getBufferSizeSec(){let e=this.params.videoElement,t=0,r=e.buffered.length;return r!==0&&(t=e.buffered.end(r-1)-Math.max(e.currentTime,e.buffered.start(0))),t}_notifyBuffering(e){this.destroyed||(this.params.logger(`buffering: ${e}`),this.params.playerCallback({name:"buffering",isBuffering:e}),this.buffering=e)}_initVideo(){let{videoElement:e,logger:t}=this.params;e.addEventListener("error",()=>{var i;!!e.error&&!this.destroyed&&(t(`Video element error: ${(i=e.error)==null?void 0:i.code}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{let r=this._getBufferSizeSec();!this.paused&&r<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(r+.1)*1e3)):this.buffering&&this.videoPlayStarted&&this._notifyBuffering(!1)}),e.addEventListener("playing",()=>{t("playing")}),e.addEventListener("stalled",()=>this._fixupStall()),e.addEventListener("waiting",()=>this._fixupStall())}_fixupStall(){let{logger:e,videoElement:t}=this.params,r=t.buffered.length,i;r!==0&&(i=t.buffered.start(r-1),t.currentTime<i&&(e("Fixup stall"),t.currentTime=i))}_selectQuality(e){let{videoElement:t}=this.params,r,i,s,n=t&&1.62*(window.devicePixelRatio||1)*t.offsetHeight||520;for(let o=0;o<this.manifest.length;++o)s=this.manifest[o],!(this.maxAutoQuality&&s.video.height>this.maxAutoQuality)&&(s.bitrate<e&&n>Math.min(s.video.height,s.video.width)?(!i||s.bitrate>i.bitrate)&&(i=s):(!r||r.bitrate>s.bitrate)&&(r=s));return i||r}shouldPlay(){if(this.paused)return!1;let t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||Ds(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){let{logger:r,videoElement:i,playerCallback:s}=this.params;this.mediaSource=new window.MediaSource,r("setting video src"),i.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.videoPlayStarted=!1,i.addEventListener("canplay",()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});let n=()=>{qb(i,"progress",()=>{i.buffered.length?(i.currentTime=i.buffered.start(0),s({name:"playing"})):n()})};n()}_initPlayerWith(e){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new Bi(Ou,Bs,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){let{logger:t,videoElement:r,playerCallback:i}=this.params,s=!1,n=null,o=null,u=null,l=null,c=!1,d=()=>{let I=s&&(!c||c===this.rep);return I||t("Not running!"),I},h=(I,E,k)=>{u&&u.abort(),u=Fr(this.urlResolver.resolve(I,!1),E,k,()=>this._retryCallback()).withTimeout(Bs).withBitrateReporting(this.bitrateSwitcher).withRetryCount(Ou).withFinally(()=>{u=null}).send()},p=(I,E,k)=>{Oi(this.filesFetcher),o==null||o.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(I,!1),E,k,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},f=I=>{let E=r.playbackRate;r.playbackRate!==I&&(t(`Playback rate switch: ${E}=>${I}`),r.playbackRate=I)},b=I=>{this.lowLatency=I,t(`lowLatency changed to ${I}`),g()},g=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)f(1);else{let I=this._getBufferSizeSec();if(this.bufferStates.length<5){f(1);return}let k=ie()-1e4,B=0;for(let V=0;V<this.bufferStates.length;V++){let M=this.bufferStates[V];I=Math.min(I,M.buf),M.ts<k&&B++}this.bufferStates.splice(0,B),t(`update playback rate; minBuffer=${I} drop=${B} jitter=${this.sourceJitter}`);let G=I-qw;this.sourceJitter>=0?G-=this.sourceJitter/2:this.sourceJitter-=1,G>3?f(1.15):G>1?f(1.1):G>.3?f(1.05):f(1)}},S=I=>{let E,k=()=>E&&E.start?E.start.length:0,B=v=>E.start[v]/1e3,G=v=>E.dur[v]/1e3,V=v=>E.fragIndex+v,M=(v,$)=>({chunkIdx:V(v),startTS:B(v),dur:G(v),discontinuity:$}),_=()=>{let v=0;if(E&&E.dur){let $=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,Q=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,N=$;this.sourceJitter>1&&(N+=this.sourceJitter-1);let oe=E.dur.length-1;for(;oe>=0&&(N-=E.dur[oe],!(N<=0));--oe);v=Math.min(oe,E.dur.length-1-Q),v=Math.max(v,0)}return M(v,!0)},w=v=>{let $=k();if(!($<=0)){if(Ds(v)){for(let Q=0;Q<$;Q++)if(B(Q)>v)return M(Q)}return _()}},U=v=>{let $=k(),Q=v?v.chunkIdx+1:0,N=Q-E.fragIndex;if(!($<=0)){if(!v||N<0||N-$>Uw)return t(`Resync: offset=${N} bChunks=${$} chunk=`+JSON.stringify(v)),_();if(!(N>=$))return M(Q-E.fragIndex,!1)}},L=(v,$,Q)=>{l&&l.abort(),l=Fr(this.urlResolver.resolve(v,!0,this.lowLatency),$,Q,()=>this._retryCallback()).withTimeout(Bs).withRetryCount(Ou).withFinally(()=>{l=null}).withJSONResponse().send()};return{seek:(v,$)=>{L(I,Q=>{if(!d())return;E=Q;let N=!!E.lowLatency;N!==this.lowLatency&&b(N);let oe=0;for(let Ue=0;Ue<E.dur.length;++Ue)oe+=E.dur[Ue];oe>0&&(Oi(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(oe/E.dur.length)),i({name:"index",zeroTime:E.zeroTime,shiftDuration:E.shiftDuration}),this.sourceJitter=E.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,E.jitter/1e3)):1,v(w($))},()=>this._handleNetworkError())},nextChunk:U}},y=()=>{s=!1,o&&o.abort(),u&&u.abort(),l&&l.abort(),Oi(this.filesFetcher),this.filesFetcher.abortAll()};return c={start:I=>{let{videoElement:E,logger:k}=this.params,B=S(e.jidxUrl),G,V,M,_,w=0,U,L,W,v=()=>{U&&(clearTimeout(U),U=void 0);let H=Math.max(Hw,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),he=w+H,xe=ie(),$e=Math.min(1e4,he-xe);w=xe;let gt=()=>{l||d()&&B.seek(()=>{d()&&(w=ie(),$(),v())})};$e>0?U=window.setTimeout(()=>{this.paused?v():gt()},$e):gt()},$=()=>{let H;for(;H=B.nextChunk(_);)_=H,dr(H);let he=B.nextChunk(M);if(he){if(M&&he.discontinuity){k("Detected discontinuity; restarting playback"),this.paused?v():(y(),this._initPlayerWith(e));return}Ue(he)}else v()},Q=(H,he)=>{if(!d()||!this.sourceBuffer)return;let xe,$e,gt,pr=St=>{window.setTimeout(()=>{d()&&Q(H,he)},St)};if(this.sourceBuffer.updating)k("Source buffer is updating; delaying appendBuffer"),pr(100);else{let St=ie(),Nt=E.currentTime;!this.paused&&E.buffered.length>1&&L===Nt&&St-W>500&&(k("Stall suspected; trying to fix"),this._fixupStall()),L!==Nt&&(L=Nt,W=St);let hr=this._getBufferSizeSec();if(hr>30)k(`Buffered ${hr} seconds; delaying appendBuffer`),pr(2e3);else try{this.sourceBuffer.appendBuffer(H),this.videoPlayStarted?(this.bufferStates.push({ts:St,buf:hr}),g(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),he&&he()}catch(Zr){if(Zr.name==="QuotaExceededError")k("QuotaExceededError; delaying appendBuffer"),gt=this.sourceBuffer.buffered.length,gt!==0&&(xe=this.sourceBuffer.buffered.start(0),$e=Nt,$e-xe>4&&this.sourceBuffer.remove(xe,$e-3)),pr(1e3);else throw Zr}}},N=()=>{V&&G&&(k([`Appending chunk, sz=${V.byteLength}:`,JSON.stringify(M)]),Q(V,function(){V=null,$()}))},oe=H=>e.fragUrlTemplate.replace("%%id%%",H.chunkIdx),Ue=H=>{d()&&p(oe(H),(he,xe)=>{if(d()){if(xe/=1e3,V=he,M=H,n=H.startTS,xe){let $e=Math.min(10,H.dur/xe);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*$e:$e}N()}},()=>this._handleNetworkError())},dr=H=>{d()&&(Oi(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(oe(H),!1)))},Xr=H=>{d()&&(e.cachedHeader=H,Q(H,()=>{G=!0,N()}))};s=!0,B.seek(H=>{if(d()){if(w=ie(),!H){v();return}_=H,!_w(I)||H.startTS>I?Ue(H):(M=H,$())}},I),e.cachedHeader?Xr(e.cachedHeader):h(e.headerUrl,Xr,()=>this._handleNetworkError())},stop:y,getTimestampSec:()=>n},c}_switchToQuality(e){let{logger:t,playerCallback:r}=this.params,i;e.bitrate!==this.bitrate&&(this.rep&&(i=this.rep.getTimestampSec(),Ds(i)&&(i+=.1),this.rep.stop()),this.currentManifestEntry=e,this.rep=this._representation(e),t(`switch to quality: codecs=${e.codecs}; headerUrl=${e.headerUrl}; bitrate=${e.bitrate}`),this.bitrate=e.bitrate,Oi(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(i),r({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return Ds(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,r=d=>{if(!this.autoQuality)return;let h,p,f;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&d<this.bitrate&&(p=this._getBufferSizeSec(),f=d/this.bitrate,p>10&&f>.8||p>15&&f>.5||p>20&&f>.3)){e(`Not switching: buffer=${Math.floor(p)}; bitrate=${this.bitrate}; newRate=${Math.floor(d)}`);return}h=this._selectQuality(d),h?this._switchToQuality(h):e(`Could not find quality by bitrate ${d}`)},s={updateChunk:(h,p)=>{let f=ie();if(this.chunkRateEstimator.addInterval(h,f,p)){let g=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:p,duration:f-h,speed:g}),!0}},get:()=>{let h=this.chunkRateEstimator.getBitRate();return h?h*.85:0}},n=-1/0,o,u=!0,l=()=>{let d=s.get();if(d&&o&&this.autoQuality){if(u&&d>o&&Du(n)<3e4)return;r(d)}u=this.autoQuality};return{updateChunk:(d,h)=>{let p=s.updateChunk(d,h);return p&&l(),p},notifySwitch:d=>{let h=ie();d<o&&(n=h),o=d}}}_fetchManifest(e,t,r){this.manifestRequest=Fr(this.urlResolver.resolve(e,!0),t,r,()=>this._retryCallback()).withJSONResponse().withTimeout(Bs).withRetryCount(this.params.config.manifestRetryMaxCount).withRetryInterval(this.params.config.manifestRetryInterval,this.params.config.manifestRetryMaxInterval).send().withFinally(()=>{this.manifestRequest=void 0})}_playVideoElement(){let{videoElement:e}=this.params;ye(e,()=>{this.soundProhibitedEvent$.next()}).then(t=>{t||(this.params.liveOffset.pause(),this.params.videoState.setState("paused"))})}_handleManifestUpdate(e){let{logger:t,playerCallback:r,videoElement:i}=this.params,s=n=>{let o=[];return n!=null&&n.length?(n.forEach((u,l)=>{u.video&&i.canPlayType(u.codecs).replace(/no/,"")&&window.MediaSource.isTypeSupported(u.codecs)&&(u.index=l,o.push(u))}),o.sort(function(u,l){return u.video&&l.video?l.video.height-u.video.height:l.bitrate-u.bitrate}),o):(r({name:"error",type:"empty_manifest"}),[])};this.manifest=s(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),r({name:"manifest",manifest:this.manifest})}_refetchManifest(e){this.destroyed||(this.manifestRefetchTimer&&clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=window.setTimeout(()=>{this._fetchManifest(e,t=>{this.destroyed||(this._handleManifestUpdate(t),this._refetchManifest(e))},()=>this._refetchManifest(e))},Fw))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};import{debounce as jw,filter as Hb,fromEvent as Gw,interval as Ww,isHigher as Yw,isInvariantQuality as Qw,isLower as zw,merge as Kw,Subject as jb,Subscription as Jw}from"@vkontakte/videoplayer-shared";var Vu=class{constructor(){this.onDroopedVideoFramesLimit$=new jb;this.subscription=new Jw;this.playing=!1;this.tracks=[];this.forceChecker$=new jb;this.isForceCheckCounter=0;this.prevTotalVideoFrames=0;this.prevDroppedVideoFrames=0;this.limitCounts={};this.handleChangeVideoQuality=()=>{let e=this.tracks.find(({size:t})=>(t==null?void 0:t.height)===this.video.videoHeight&&(t==null?void 0:t.width)===this.video.videoWidth);e&&!Qw(e.quality)&&this.onChangeQuality(e.quality)};this.checkDroppedFrames=()=>{var n;let{totalVideoFrames:e,droppedVideoFrames:t}=this.video.getVideoPlaybackQuality(),r=e-this.prevTotalVideoFrames,i=t-this.prevDroppedVideoFrames,s=1-(r-i)/r;!isNaN(s)&&s>0&&this.log({message:`[dropped]. current dropped percent: ${s}, limit: ${this.droppedFramesChecker.percentLimit}`}),!isNaN(s)&&s>=this.droppedFramesChecker.percentLimit&&Yw(this.currentQuality,this.droppedFramesChecker.minQualityBanLimit)&&(this.limitCounts[this.currentQuality]=((n=this.limitCounts[this.currentQuality])!=null?n:0)+1,this.maxQualityLimit=this.getMaxQualityLimit(this.currentQuality),this.currentTimer&&window.clearTimeout(this.currentTimer),this.currentTimer=window.setTimeout(()=>this.maxQualityLimit=this.getMaxQualityLimit(),this.droppedFramesChecker.qualityUpWaitingTime),this.onDroopedVideoFramesLimitTrigger()),this.savePrevFrameCounts(e,t)}}connect(e){this.log=e.logger.createComponentLog("DroppedFramesManager"),this.video=e.video,this.isAuto=e.isAuto,this.tracks=e.tracks,this.droppedFramesChecker=e.droppedFramesChecker,this.subscription.add(e.playing$.subscribe(()=>this.playing=!0)),this.subscription.add(e.pause$.subscribe(()=>this.playing=!1)),this.isEnabled&&this.subscribe()}destroy(){this.currentTimer&&window.clearTimeout(this.currentTimer),this.subscription.unsubscribe()}get droppedVideoMaxQualityLimit(){return this.maxQualityLimit}subscribe(){this.subscription.add(Gw(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=Ww(this.droppedFramesChecker.checkTime).pipe(Hb(()=>this.playing),Hb(()=>{let i=!!this.isForceCheckCounter;return i&&(this.isForceCheckCounter-=1),!i})),t=this.forceChecker$.pipe(jw(this.droppedFramesChecker.checkTime)),r=Kw(e,t);this.subscription.add(r.subscribe(this.checkDroppedFrames))}onChangeQuality(e){this.currentQuality=e;let{totalVideoFrames:t,droppedVideoFrames:r}=this.video.getVideoPlaybackQuality();this.savePrevFrameCounts(t,r),this.isForceCheckCounter=this.droppedFramesChecker.tickCountAfterQualityChange,this.forceChecker$.next()}onDroopedVideoFramesLimitTrigger(){this.isAuto.getState()&&(this.log({message:`[onDroopedVideoFramesLimit]. maxQualityLimit: ${this.maxQualityLimit}`}),this.onDroopedVideoFramesLimit$.next())}getMaxQualityLimit(e){var r,i;let t=(i=(r=Object.entries(this.limitCounts).filter(([,s])=>s>=this.droppedFramesChecker.countLimit).sort(([s],[n])=>zw(s,n)?-1:1))==null?void 0:r[0])==null?void 0:i[0];return e!=null?e:t}get isEnabled(){return this.droppedFramesChecker.enabled&&this.isDroppedFramesCheckerSupport}get isDroppedFramesCheckerSupport(){return!!this.video&&typeof this.video.getVideoPlaybackQuality=="function"}savePrevFrameCounts(e,t){this.prevTotalVideoFrames=e,this.prevDroppedVideoFrames=t}},Os=Vu;import{map as Xw,Observable as Zw}from"@vkontakte/videoplayer-shared";import{fromEvent as ek}from"@vkontakte/videoplayer-shared";var _i=()=>{var a;return!!((a=window.documentPictureInPicture)!=null&&a.window)||!!document.pictureInPictureElement};var tk=(a,e)=>new Zw(t=>{if(!window.IntersectionObserver)return;let r={root:null},i=new IntersectionObserver((n,o)=>{n.forEach(u=>t.next(u.isIntersecting||_i()))},A(A({},r),e));i.observe(a);let s=ek(document,"visibilitychange").pipe(Xw(n=>!document.hidden||_i())).subscribe(n=>t.next(n));return()=>{i.unobserve(a),s.unsubscribe}}),_e=tk;var ck=["paused","playing","ready"],dk=["paused","playing","ready"],Ni=class{constructor(e){this.subscription=new ok;this.videoState=new C("stopped");this.representations$=new Nu([]);this.textTracksManager=new Oe;this.droppedFramesManager=new Os;this.maxSeekBackTime$=new Nu(1/0);this.zeroTime$=new Nu(void 0);this.liveOffset=new dt;this._dashCb=e=>{var t,r,i,s;switch(e.name){case"buffering":{let n=e.isBuffering;this.params.output.isBuffering$.next(n);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${e.type}`,category:Yb.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{let n=e.manifest,o=[];for(let u of n){let l=(t=u.name)!=null?t:u.index.toString(10),c=(r=Rt(u.name))!=null?r:lk(u.video),d=u.bitrate/1e3,h=A({},u.video);if(!c)continue;let p={id:l,quality:c,bitrate:d,size:h};o.push({track:p,representation:u})}this.representations$.next(o),this.params.output.availableVideoTracks$.next(o.map(({track:u})=>u)),((i=this.videoState.getTransition())==null?void 0:i.to)==="manifest_ready"&&this.videoState.setState("manifest_ready");break}case"qualitySwitch":{let n=e.quality,o=(s=this.representations$.getValue().find(({representation:u})=>u===n))==null?void 0:s.track;this.params.output.hostname$.next(new URL(n.headerUrl,this.params.source.url).hostname),_u(o)&&this.params.output.currentVideoTrack$.next(o);break}case"bandwidth":{let{size:n,duration:o}=e;this.params.dependencies.throughputEstimator.addRawSpeed(n,o);break}case"index":{this.maxSeekBackTime$.next(e.shiftDuration||0),this.zeroTime$.next(e.zeroTime);break}}};this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),r=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${r}; seekState: ${JSON.stringify(s)};`}),r==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState("stopped"));return}if(t)return;let n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(dk.includes(e)&&(n||o)){this.prepare();return}if((i==null?void 0:i.to)!=="paused"&&s.state==="requested"&&ck.includes(e)){this.seek(s.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(se(this.params.source.url));return;case"manifest_ready":this.videoState.startTransitionTo("ready"),this.prepare();break;case"ready":if(r==="paused")this.videoState.setState("paused");else if(r==="playing"){this.videoState.startTransitionTo("playing");let u=i==null?void 0:i.from;u&&u==="ready"&&this.dash.catchUp(),this.dash.play()}return;case"playing":r==="paused"&&(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.dash.pause());return;case"paused":if(r==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.dash.play(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let u=this.liveOffset.getTotalOffset();u>=this.maxSeekBackTime$.getValue()&&(u=0,this.liveOffset.resetTo(u)),this.liveOffset.resume(),this.params.output.position$.next(-u/1e3),this.dash.reinit(se(this.params.source.url,u))}return;default:return Gb(e)}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=i=>{e.output.error$.next({id:"DashLiveProvider",category:Yb.WTF,message:"DashLiveProvider internal logic error",thrown:i})};zb(this.videoState.stateChangeStarted$.pipe(Vs(i=>({transition:i,type:"start"}))),this.videoState.stateChangeEnded$.pipe(Vs(i=>({transition:i,type:"end"})))).subscribe(({transition:i,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(i)}`})}),this.video=be(e.container,e.tuning),this.params.output.element$.next(this.video),this.dash=this.createLiveDashPlayer(),this.subscription.add(this.dash.soundProhibitedEvent$.subscribe(this.params.output.soundProhibitedEvent$)),this.params.output.duration$.next(1/0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(re(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);let r=ve(this.video);this.subscription.add(this.representations$.pipe(Vs(i=>i.map(({track:s})=>s)),Qb(i=>!!i.length),nk()).subscribe(i=>this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:r.playing$,pause$:r.pause$,tracks:i}))),this.subscription.add(r.canplay$.subscribe(()=>{var i;((i=this.videoState.getTransition())==null?void 0:i.to)==="ready"&&this.videoState.setState("ready")},t)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused")},t)).add(r.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.videoState.setState("playing")},t)).add(r.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(ak(),Vs(i=>-i/1e3)).subscribe(this.params.output.duration$)).add(rk({zeroTime:this.zeroTime$.pipe(Qb(_u)),position:r.timeUpdate$}).subscribe(({zeroTime:i,position:s})=>this.params.output.liveTime$.next(i+s*1e3),t)).add(rt(this.video,this.params.desiredState.isLooped,t)).add(Se(this.video,this.params.desiredState.volume,r.volumeState$,t)).add(r.volumeState$.subscribe(this.params.output.volume$,t)).add(Be(this.video,this.params.desiredState.playbackRate,r.playbackRateState$,t)).add(r.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(r.loadedMetadata$.subscribe(this.params.output.loadedMetadataEvent$)).add(r.playing$.subscribe(this.params.output.firstFrameEvent$)).add(r.canplay$.subscribe(this.params.output.canplay$)).add(r.inPiP$.subscribe(this.params.output.inPiP$)).add(r.inFullscreen$.subscribe(this.params.output.inFullscreen$)).add(_e(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:i}})=>{let s=i&&uk(i);this.dash.setMaxAutoQuality(s),this.params.output.autoVideoTrackLimits$.next({max:i})})).add(this.videoState.stateChangeEnded$.subscribe(i=>{var s;switch(i.to){case"stopped":this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState("stopped");break;case"manifest_ready":case"ready":((s=this.params.desiredState.playbackState.getTransition())==null?void 0:s.to)==="ready"&&this.params.desiredState.playbackState.setState("ready");break;case"paused":this.params.desiredState.playbackState.setState("paused");break;case"playing":this.params.desiredState.playbackState.setState("playing");break;default:return Gb(i.to)}},t)).add(zb(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,sk(["init"])).pipe(ik(0)).subscribe(this.syncPlayback,t))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.droppedFramesManager.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),ge(this.video)}createLiveDashPlayer(){let e=new Vi({videoElement:this.video,videoState:this.videoState,liveOffset:this.liveOffset,config:{maxParallelRequests:this.params.config.maxParallelRequests,minBuffer:this.params.tuning.live.minBuffer,minBufferSegments:this.params.tuning.live.minBufferSegments,lowLatencyMinBuffer:this.params.tuning.live.lowLatencyMinBuffer,lowLatencyMinBufferSegments:this.params.tuning.live.lowLatencyMinBufferSegments,isLiveCatchUpMode:this.params.tuning.live.isLiveCatchUpMode,manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},playerCallback:this._dashCb,logger:t=>{this.params.dependencies.logger.log({message:String(t),component:"LiveDashPlayer"})}});return e.pause(),e}prepare(){var l,c,d,h,p,f;let e=this.representations$.getValue(),t=(c=(l=this.params.desiredState.videoTrack.getTransition())==null?void 0:l.to)!=null?c:this.params.desiredState.videoTrack.getState(),r=(h=(d=this.params.desiredState.autoVideoTrackSwitching.getTransition())==null?void 0:d.to)!=null?h:this.params.desiredState.autoVideoTrackSwitching.getState(),i=!r&&_u(t)?t:$t(e.map(({track:b})=>b),{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},throughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),s=i==null?void 0:i.id,n=this.params.desiredState.videoTrack.getTransition(),o=(p=this.params.desiredState.videoTrack.getState())==null?void 0:p.id,u=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(i&&(n||s!==o)&&this.setVideoTrack(i),u&&this.setAutoQuality(r),n||u||s!==o){let b=(f=e.find(({track:g})=>g.id===s))==null?void 0:f.representation;Wb(b,"Representations missing"),this.dash.startPlay(b,r)}}setVideoTrack(e){var r;let t=(r=this.representations$.getValue().find(({track:i})=>i.id===e.id))==null?void 0:r.representation;Wb(t,`No such representation ${e.id}`),this.dash.switchByName(t.name),this.params.desiredState.videoTrack.setState(e)}setAutoQuality(e){this.dash.setAutoQualityEnabled(e),this.params.desiredState.autoVideoTrackSwitching.setState(e)}seek(e){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),r=this.videoState.getState(),i=t==="paused"&&r==="paused",s=-e,n=s<=this.maxSeekBackTime$.getValue()?s:0;this.params.output.position$.next(e/1e3),this.dash.reinit(se(this.params.source.url,n)),i&&this.dash.pause(),this.liveOffset.resetTo(n,i)}};var Kb=Ni;var at=(a,e)=>{let t=0;for(let r=0;r<a.length;r++){let i=a.start(r)*1e3,s=a.end(r)*1e3;i<=e&&e<=s&&(t=s)}return Math.max(t-e,0)};import{assertNever as UR,assertNonNullable as qR,debounce as HR,ErrorCategory as bl,filter as ES,filterChanged as gl,fromEvent as jR,isNonNullable as GR,map as xS,merge as ln,observableFrom as WR,observeElementSize as YR,once as PS,Subscription as QR,ValueSubject as zR}from"@vkontakte/videoplayer-shared";var _s=class{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,r){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:r})}removeEventListener(e,t){if(!(e in this.listeners))return;let r=this.listeners[e];for(let i=0,s=r.length;i<s;i++)if(r[i].callback===t){r.splice(i,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;let r=this.listeners[e.type].slice();for(let i=0,s=r.length;i<s;i++){let n=r[i];try{n.callback.call(this,e)}catch(o){Promise.resolve().then(()=>{throw o})}n.options&&n.options.once&&this.removeEventListener(e.type,n.callback)}return!e.defaultPrevented}},Ur=class extends _s{constructor(){super(),this.listeners||_s.call(this),Object.defineProperty(this,"aborted",{value:!1,writable:!0,configurable:!0}),Object.defineProperty(this,"onabort",{value:null,writable:!0,configurable:!0}),Object.defineProperty(this,"reason",{value:void 0,writable:!0,configurable:!0})}toString(){return"[object AbortSignal]"}dispatchEvent(e){e.type==="abort"&&(this.aborted=!0,typeof this.onabort=="function"&&this.onabort.call(this,e)),super.dispatchEvent(e)}},Fi=class{constructor(){Object.defineProperty(this,"signal",{value:new Ur,writable:!0,configurable:!0})}abort(e){let t;try{t=new Event("abort")}catch(i){typeof document!="undefined"?document.createEvent?(t=document.createEvent("Event"),t.initEvent("abort",!1,!1)):(t=document.createEventObject(),t.type="abort"):t={type:"abort",bubbles:!1,cancelable:!1}}let r=e;if(r===void 0)if(typeof document=="undefined")r=new Error("This operation was aborted"),r.name="AbortError";else try{r=new DOMException("signal is aborted without reason")}catch(i){r=new Error("This operation was aborted"),r.name="AbortError"}this.signal.reason=r,this.signal.dispatchEvent(t)}toString(){return"[object AbortController]"}};typeof Symbol!="undefined"&&Symbol.toStringTag&&(Fi.prototype[Symbol.toStringTag]="AbortController",Ur.prototype[Symbol.toStringTag]="AbortSignal");function Ns(a){return a.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof a.Request=="function"&&!a.Request.prototype.hasOwnProperty("signal")||!a.AbortController}function Fu(a){typeof a=="function"&&(a={fetch:a});let{fetch:e,Request:t=e.Request,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:i=!1}=a;if(!Ns({fetch:e,Request:t,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:i}))return{fetch:e,Request:s};let s=t;(s&&!s.prototype.hasOwnProperty("signal")||i)&&(s=function(l,c){let d;c&&c.signal&&(d=c.signal,delete c.signal);let h=new t(l,c);return d&&Object.defineProperty(h,"signal",{writable:!1,enumerable:!1,configurable:!0,value:d}),h},s.prototype=t.prototype);let n=e;return{fetch:(u,l)=>{let c=s&&s.prototype.isPrototypeOf(u)?u.signal:l?l.signal:void 0;if(c){let d;try{d=new DOMException("Aborted","AbortError")}catch(p){d=new Error("Aborted"),d.name="AbortError"}if(c.aborted)return Promise.reject(d);let h=new Promise((p,f)=>{c.addEventListener("abort",()=>f(d),{once:!0})});return l&&l.signal&&delete l.signal,Promise.race([h,n(u,l)])}return n(u,l)},Request:s}}var Ui=Ns({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),Jb=Ui?Fu({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,ht=Ui?Jb.fetch:window.fetch,eO=Ui?Jb.Request:window.Request,ze=Ui?Fi:window.AbortController,tO=Ui?Ur:window.AbortSignal;var Qs=je(Nr(),1);var ft=()=>window.ManagedMediaSource||window.MediaSource,Fs=()=>{var a,e;return!!(window.ManagedMediaSource&&((e=(a=window.ManagedSourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},Xb=()=>{var a,e;return!!(window.MediaSource&&window.MediaStreamTrack&&((e=(a=window.SourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},Zb=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;import{assertNever as Ks,clientChecker as zs}from"@vkontakte/videoplayer-shared";var Ne=document.createElement("video"),fk='video/mp4; codecs="avc1.42000a,mp4a.40.2"',mk='video/mp4; codecs="hev1.1.6.L93.B0"',cg='video/webm; codecs="vp09.00.10.08"',dg='video/webm; codecs="av01.0.00M.08"',bk='audio/mp4; codecs="mp4a.40.2"',gk='audio/webm; codecs="opus"',eg,tg,Zt={mms:Fs(),mse:Xb(),hls:!!((eg=Ne.canPlayType)!=null&&eg.call(Ne,"application/x-mpegurl")||(tg=Ne.canPlayType)!=null&&tg.call(Ne,"vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},rg,ig,Te={mp4:!!((rg=Ne.canPlayType)!=null&&rg.call(Ne,"video/mp4")),webm:!!((ig=Ne.canPlayType)!=null&&ig.call(Ne,"video/webm")),cmaf:!0},qs,ag,Hs,sg,js,ng,Gs,og,Ws,ug,Ys,lg,Ie={h264:!!((ag=(qs=ft())==null?void 0:qs.isTypeSupported)!=null&&ag.call(qs,fk)),h265:!!((sg=(Hs=ft())==null?void 0:Hs.isTypeSupported)!=null&&sg.call(Hs,mk)),vp9:!!((ng=(js=ft())==null?void 0:js.isTypeSupported)!=null&&ng.call(js,cg)),av1:!!((og=(Gs=ft())==null?void 0:Gs.isTypeSupported)!=null&&og.call(Gs,dg)),aac:!!((ug=(Ws=ft())==null?void 0:Ws.isTypeSupported)!=null&&ug.call(Ws,bk)),opus:!!((lg=(Ys=ft())==null?void 0:Ys.isTypeSupported)!=null&&lg.call(Ys,gk))},qr=(Ie.h264||Ie.h265)&&Ie.aac,er,Sk=()=>R(void 0,null,function*(){if(!window.navigator.mediaCapabilities)return;let a={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=yield Promise.all([window.navigator.mediaCapabilities.decodingInfo(D(A({},a),{video:D(A({},a.video),{contentType:dg})})),window.navigator.mediaCapabilities.decodingInfo(D(A({},a),{video:D(A({},a.video),{contentType:cg})}))]);er={DASH_WEBM_AV1:e,DASH_WEBM:t}});try{Sk()}catch(a){console.error(a)}var Hr=Zt.hls&&Te.mp4,pg=()=>Object.keys(Ie).filter(a=>Ie[a]),hg=(a,e=!1,t=!1)=>{let r=Zt.mse||Zt.mms&&t;return a.filter(i=>{switch(i){case"DASH_SEP":return r&&Te.mp4&&qr;case"DASH_WEBM":return r&&Te.webm&&Ie.vp9&&Ie.opus;case"DASH_WEBM_AV1":return r&&Te.webm&&Ie.av1&&Ie.opus;case"DASH_STREAMS":return r&&(Te.mp4&&qr||Te.webm&&(Ie.vp9||Ie.av1)&&(Ie.opus||Ie.aac));case"DASH_LIVE":return Zt.mse&&Te.mp4&&qr;case"DASH_LIVE_CMAF":return r&&Te.mp4&&qr&&Te.cmaf;case"DASH_ONDEMAND":return r&&Te.mp4&&qr;case"HLS":case"HLS_ONDEMAND":return Hr||e&&Zt.mse&&Te.mp4&&qr;case"HLS_LIVE":case"HLS_LIVE_CMAF":return Hr;case"MPEG":return Te.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return Zt.webrtc&&Zt.ws&&Ie.h264&&(Te.mp4||Te.webm);default:return Ks(i)}})},Us=a=>{let e="DASH_WEBM",t="DASH_WEBM_AV1";switch(a){case"vp9":return[e,t];case"av1":return[t,e];case"none":return[];case"smooth":return er?er[t].smooth?[t,e]:er[e].smooth?[e,t]:[t,e]:[e,t];case"power_efficient":return er?er[t].powerEfficient?[t,e]:er[e].powerEfficient?[e,t]:[t,e]:[e,t];default:Ks(a)}return[e,t]},fg=({webmCodec:a,androidPreferredFormat:e,preferMultiStream:t})=>{let r=[...t?["DASH_STREAMS"]:[],...Us(a),"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]],i=[...t?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]];if(zs.isAndroid)switch(e){case"mpeg":return["MPEG",...r,"HLS","HLS_ONDEMAND"];case"hls":return["HLS","HLS_ONDEMAND",...r,"MPEG"];case"dash":return[...r,"HLS","HLS_ONDEMAND","MPEG"];case"dash_any_mpeg":return[...i,"MPEG",...Us(a),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...Us(a),"MPEG",...i,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...Us(a),...i,"HLS","HLS_ONDEMAND"];default:Ks(e)}return Hr?[...r,"HLS","HLS_ONDEMAND","MPEG"]:[...r,"HLS","HLS_ONDEMAND","MPEG"]},mg=({androidPreferredFormat:a,preferCMAF:e,preferWebRTC:t})=>{let r=e?["DASH_LIVE_CMAF","DASH_LIVE"]:["DASH_LIVE","DASH_LIVE_CMAF"],i=e?["HLS_LIVE_CMAF","HLS_LIVE"]:["HLS_LIVE","HLS_LIVE_CMAF"],s=[...r,...i],n=[...i,...r],o,u=zs.isMac&&zs.isSafari;if(zs.isAndroid)switch(a){case"dash":case"dash_any_mpeg":case"dash_any_webm":case"dash_sep":{o=s;break}case"hls":case"mpeg":{o=n;break}default:Ks(a)}else Hr&&!u?o=n:u?o=e?["DASH_LIVE_CMAF","HLS_LIVE_CMAF","HLS_LIVE","DASH_LIVE"]:["HLS_LIVE","DASH_LIVE","DASH_LIVE_CMAF","HLS_LIVE_CMAF"]:o=s;return t?["WEB_RTC_LIVE",...o]:[...o,"WEB_RTC_LIVE"]},Uu=a=>a?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],bg=a=>{if(a.size===0)return;if(a.size===1){let t=a.values().next();return(0,Qs.default)(t.value.split("."),0)}for(let t of a){let r=(0,Qs.default)(t.split("."),0);if(r==="opus"||r==="vp09"||r==="av01")return r}let e=a.values().next();return(0,Qs.default)(e.value.split("."),0)};import{ErrorCategory as qi}from"@vkontakte/videoplayer-shared";var gg=a=>{if(!a)return{id:"EmptyResponse",category:qi.PARSER,message:"Empty response"};if(a.length<=2&&a.match(/^\d+$/))return{id:`UVError#${a}`,category:qi.NETWORK,message:`UV Error ${a}`};let e=a.trimStart().substring(0,100).toLowerCase();if(e.startsWith("<!doctype")||e.startsWith("<html>")||e.startsWith("<body>")||e.startsWith("<head>"))return{id:"UnexpectedHTML",category:qi.NETWORK,message:"Received unexpected HTML, possibly a ISP block"};if(e.startsWith("<?xml"))return new DOMParser().parseFromString(a,"text/xml").querySelector("parsererror")?{id:"InvalidXML",category:qi.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:qi.PARSER,message:"Response is valid XML, but parser failed"}};var Lt=(a,e)=>{for(let r=0;r<a.length;r++)if(a.start(r)-1e4<=e&&a.end(r)*1e3+10>e)return!0;return!1};import{abortable as pl,assertNonNullable as or,clientChecker as $R,combine as an,ErrorCategory as Dt,filter as hl,filterChanged as gS,flattenObject as Sa,fromEvent as ur,getTraceSubscriptionMethod as LR,interval as fl,isNonNullable as SS,map as ml,merge as lr,now as MR,Subject as vS,Subscription as yS,tap as CR,throttle as DR,ValueSubject as ne}from"@vkontakte/videoplayer-shared";var Yr=je(Nr(),1);var vk=(a,e={})=>{let r=e.timeout||1,i=performance.now();return window.setTimeout(()=>{a({get didTimeout(){return e.timeout?!1:performance.now()-i-1>r},timeRemaining(){return Math.max(0,1+(performance.now()-i))}})},1)},yk=a=>window.clearTimeout(a),Sg=a=>typeof a=="function"&&(a==null?void 0:a.toString().endsWith("{ [native code] }")),vg=!Sg(window.requestIdleCallback)||!Sg(window.cancelIdleCallback),qu=vg?vk:window.requestIdleCallback,bO=vg?yk:window.cancelIdleCallback;var cS=je(Rs(),1);import{assertNever as Tk,ErrorCategory as yg,clientChecker as Hu,Subject as Tg}from"@vkontakte/videoplayer-shared";var Ik=18,Ig=!1;try{Ig=Hu.isSafari&&!!Hu.macVersion&&Hu.macVersion<=Ik}catch(a){console.error(a)}var ju=class{constructor(e){this.bufferFull$=new Tg;this.error$=new Tg;this.queue=[];this.currentTask=null;this.destroyed=!1;this.completeTask=()=>{var e;try{if(this.currentTask){let t=(e=this.currentTask.signal)==null?void 0:e.aborted;this.currentTask.callback(!t),this.currentTask=null}this.queue.length&&this.pull()}catch(t){this.error$.next({id:"BufferTaskQueueUnknown",category:yg.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:t})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}append(e,t){return R(this,null,function*(){return t&&t.aborted?!1:new Promise(r=>{let i={operation:"append",data:e,signal:t,callback:r};this.queue.push(i),this.pull()})})}remove(e,t,r){return R(this,null,function*(){return r&&r.aborted?!1:new Promise(i=>{let s={operation:"remove",from:e,to:t,signal:r,callback:i};this.queue.unshift(s),this.pull()})})}abort(e){return R(this,null,function*(){return new Promise(t=>{let r;Ig&&e?r={operation:"safariAbort",init:e,callback:t}:r={operation:"abort",callback:t};for(let{callback:i}of this.queue)i(!1);r&&(this.queue=[r]),this.pull()})})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){var i;if(this.buffer.updating||this.currentTask||this.destroyed)return;let e=this.queue.shift();if(!e)return;if((i=e.signal)!=null&&i.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(s){s instanceof DOMException&&s.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):s instanceof DOMException&&s.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:yg.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:s}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){let{operation:t}=e;switch(t){case"append":this.buffer.appendBuffer(e.data);break;case"remove":this.buffer.remove(e.from/1e3,e.to/1e3);break;case"abort":this.buffer.abort();break;case"safariAbort":{this.buffer.abort(),this.buffer.appendBuffer(e.init);break}default:Tk(t)}}},Eg=ju;var Gu=a=>{let e=0;for(let t=0;t<a.length;t++)e+=a.end(t)-a.start(t);return e*1e3};import{abortable as ar,assertNonNullable as de,ErrorCategory as Mt,fromEvent as ol,getExponentialDelay as ul,isNonNullable as Js,isNullable as Fe,now as Xs,once as yR,Subject as TR,Subscription as IR,ValueSubject as da}from"@vkontakte/videoplayer-shared";var j=class{constructor(e,t){this.cursor=0;this.source=e,this.boxParser=t,this.children=[];let r=this.readUint32();this.type=this.readString(4),this.size32=r<=e.buffer.byteLength-e.byteOffset?r:NaN;let i=this.size32?this.size32-8:void 0,s=e.byteOffset+this.cursor;this.size64=0,this.usertype=0,this.content=new DataView(e.buffer,s,i),this.children=this.parseChildrenBoxes()}get id(){return this.type}get size(){return this.size32}parseChildrenBoxes(){return[]}scanForBoxes(e){return this.boxParser.parse(e)}readString(e,t="ascii"){let i=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,i}readUint8(){let e=this.source.getUint8(this.cursor);return this.cursor+=1,e}readUint16(){let e=this.source.getUint16(this.cursor);return this.cursor+=2,e}readUint32(){let e=this.source.getUint32(this.cursor);return this.cursor+=4,e}readUint64(){let e=this.source.getBigInt64(this.cursor);return this.cursor+=8,e}};var jr=class extends j{};var Hi=class extends j{};var ji=class extends j{constructor(e,t){super(e,t),this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let r=this.size-this.cursor;for(;r;){let i=this.readString(4);this.compatibleBrands.push(i),r-=4}}};var Gi=class extends j{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Wi=class extends j{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Yi=class extends j{constructor(e,t){super(e,t),this.data=this.content}};var X=class extends j{constructor(e,t){super(e,t);let r=this.readUint32();this.version=r>>>24,this.flags=r&16777215}};var tr=class extends X{get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e,t){super(e,t),this.segments=[],this.referenceId=this.readUint32(),this.timescale=this.readUint32(),this.earliestPresentationTime32=this.readUint32(),this.firstOffset32=this.readUint32(),this.earliestPresentationTime64=0,this.firstOffset64=0,this.referenceCount=this.readUint32()&65535;for(let r=0;r<this.referenceCount;r++){let i=this.readUint32(),s=i>>>31,n=i<<1>>>1,o=this.readUint32();i=this.readUint32();let u=i>>>28,l=i<<3>>>3;this.segments.push({referenceType:s,referencedSize:n,subsegmentDuration:o,SAPType:u,SAPDeltaTime:l})}}};var Qi=class extends j{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var zi=class extends j{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Ki=class extends X{constructor(e,t){switch(super(e,t),this.readUint8()){case 0:this.stereoMode=0;break;case 1:this.stereoMode=1;break;case 2:this.stereoMode=2;break;case 3:this.stereoMode=3;break;case 4:this.stereoMode=4;break}this.cursor+=1}};var Ji=class extends X{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var Xi=class extends X{constructor(e,t){super(e,t),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}};var Zi=class extends j{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ea=class extends X{constructor(e,t){super(e,t),this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.trackId=this.readUint32(),this.cursor+=4,this.duration=this.readUint32(),this.cursor+=8,this.layer=this.readUint16(),this.alternateGroup=this.readUint16(),this.cursor+=2,this.cursor+=2,this.matrix=[[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()]],this.width=this.readUint32(),this.height=this.readUint32()}};var ta=class extends j{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ra=class extends j{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ia=class extends X{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var aa=class extends j{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var sa=class extends X{constructor(e,t){super(e,t),this.trackId=this.readUint32(),this.flags&1&&(this.baseDataOffset=this.readUint64()),this.flags&2&&(this.sampleDescriptionIndex=this.readUint32()),this.flags&8&&(this.defaultSampleDuration=this.readUint32()),this.flags&16&&(this.defaultSampleSize=this.readUint32()),this.flags&32&&(this.defaultSampleFlags=this.readUint32())}};var na=class extends X{constructor(t,r){super(t,r);this.baseMediaDecodeTime32=0;this.baseMediaDecodeTime64=BigInt(0);this.version===1?this.baseMediaDecodeTime64=this.readUint64():this.baseMediaDecodeTime32=this.readUint32()}get baseMediaDecodeTime(){return this.version===1?this.baseMediaDecodeTime64:this.baseMediaDecodeTime32}};var oa=class extends X{constructor(t,r){super(t,r);this.sampleDuration=[];this.sampleSize=[];this.sampleFlags=[];this.sampleCompositionTimeOffset=[];this.optionalFields=0;this.sampleCount=this.readUint32(),this.flags&1&&(this.dataOffset=this.readUint32()),this.flags&4&&(this.firstSampleFlags=this.readUint32());for(let i=0;i<this.sampleCount;i++)this.flags&256&&this.sampleDuration.push(this.readUint32()),this.flags&512&&this.sampleSize.push(this.readUint32()),this.flags&1024&&this.sampleFlags.push(this.readUint32()),this.flags&2048&&this.sampleCompositionTimeOffset.push(this.readUint32())}};var xk={ftyp:ji,moov:Gi,moof:Wi,mdat:Yi,sidx:tr,trak:Qi,mdia:Zi,mfhd:ia,tkhd:ea,traf:aa,tfhd:sa,tfdt:na,trun:oa,minf:ta,sv3d:zi,st3d:Ki,prhd:Ji,proj:ra,equi:Xi,uuid:Hi,unknown:jr},rr=class a{constructor(e={}){this.options=A({offset:0},e)}parse(e){let t=[],r=this.options.offset;for(;r<e.byteLength;)try{let s=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+r+4,4)),n=this.createBox(s,new DataView(e.buffer,e.byteOffset+r));if(!n.size)break;t.push(n),r+=n.size}catch(i){break}return t}createBox(e,t){let r=xk[e];return r?new r(t,new a):new jr(t,new a)}};var Gr=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{var r,i,s;(s=(r=this.index)[i=t.type])!=null||(r[i]=[]),this.index[t.type].push(t),t.children.length>0&&this.indexBoxLevel(t.children)})}find(e){return this.index[e]&&this.index[e][0]?this.index[e][0]:null}findAll(e){return this.index[e]||[]}};var Ak=new TextDecoder("ascii"),wk=a=>Ak.decode(new DataView(a.buffer,a.byteOffset+4,4))==="ftyp",kk=a=>{let e=new tr(a,new rr),t=e.earliestPresentationTime/e.timescale*1e3,r=a.byteOffset+a.byteLength+e.firstOffset;return e.segments.map(s=>{if(s.referenceType!==0)throw new Error("Unsupported multilevel sidx");let n=s.subsegmentDuration/e.timescale*1e3,o={status:"none",time:{from:t,to:t+n},byte:{from:r,to:r+s.referencedSize-1}};return t+=n,r+=s.referencedSize,o})},Rk=(a,e)=>{let r=new rr().parse(a),i=new Gr(r),s=i.findAll("moof"),n=e?i.findAll("uuid"):i.findAll("mdat");if(!(n.length&&s.length))return null;let o=s[0],u=n[n.length-1],l=o.source.byteOffset,d=u.source.byteOffset-o.source.byteOffset+u.size;return new DataView(a.buffer,l,d)},$k=(a,e)=>{let r=new rr().parse(a),s=new Gr(r).findAll("traf"),n=s[s.length-1].children.find(d=>d.type==="tfhd"),o=s[s.length-1].children.find(d=>d.type==="tfdt"),u=s[s.length-1].children.find(d=>d.type==="trun"),l=0;return u.sampleDuration.length?l=u.sampleDuration.reduce((d,h)=>d+h,0):l=n.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+l)/e*1e3},Lk=a=>{let e={is3dVideo:!1,stereoMode:0,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}},r=new rr().parse(a),i=new Gr(r);if(i.find("sv3d")){e.is3dVideo=!0;let n=i.find("st3d");n&&(e.stereoMode=n.stereoMode);let o=i.find("prhd");o&&(e.projectionData.pose.yaw=o.poseYawDegrees,e.projectionData.pose.pitch=o.posePitchDegrees,e.projectionData.pose.roll=o.poseRollDegrees);let u=i.find("equi");u&&(e.projectionData.bounds.top=u.projectionBoundsTop,e.projectionData.bounds.right=u.projectionBoundsRight,e.projectionData.bounds.bottom=u.projectionBoundsBottom,e.projectionData.bounds.left=u.projectionBoundsLeft)}return e},xg={validateData:wk,parseInit:Lk,getIndexRange:()=>{},parseSegments:kk,parseFeedableSegmentChunk:Rk,getSegmentEndTime:$k};import{assertNonNullable as Yu,isNonNullable as kg,isNullable as Ck}from"@vkontakte/videoplayer-shared";import{assertNever as Mk}from"@vkontakte/videoplayer-shared";var Pg={440786851:{type:"master"},17030:{type:"uint"},17143:{type:"uint"},17138:{type:"uint"},17139:{type:"uint"},17026:{type:"string"},17031:{type:"uint"},17029:{type:"uint"},236:{type:"binary"},408125543:{type:"master"},290298740:{type:"master"},19899:{type:"master"},21419:{type:"binary"},21420:{type:"uint"},357149030:{type:"master"},2807729:{type:"uint"},17545:{type:"float"},374648427:{type:"master"},174:{type:"master"},224:{type:"master"},30320:{type:"master"},30321:{type:"uint"},30322:{type:"master"},272869232:{type:"master"},524531317:{type:"master"},231:{type:"uint"},22612:{type:"master"},22743:{type:"uint"},167:{type:"uint"},171:{type:"uint"},163:{type:"binary"},160:{type:"master"},175:{type:"binary"},423732329:{type:"master"},307544935:{type:"master"},475249515:{type:"master"},187:{type:"master"},179:{type:"uint"},183:{type:"master"},247:{type:"uint"},241:{type:"uint"},240:{type:"uint"},178:{type:"uint"},21368:{type:"uint"},234:{type:"uint"},219:{type:"master"},150:{type:"uint"}},Ag=a=>{let e=a.getUint8(0),t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);let r=ua(a,t),i=r in Pg,s=i?Pg[r].type:"binary",n=a.getUint8(t),o=0;n&128?o=1:n&64?o=2:n&32?o=3:n&16?o=4:n&8?o=5:n&4?o=6:n&2?o=7:n&1&&(o=8);let u=new DataView(a.buffer,a.byteOffset+t+1,o-1),l=n&255>>o,c=ua(u),d=l*et(2,(o-1)*8)+c,h=t+o,p;return h+d>a.byteLength?p=new DataView(a.buffer,a.byteOffset+h):p=new DataView(a.buffer,a.byteOffset+h,d),{tag:i?r:"0x"+r.toString(16).toUpperCase(),type:s,tagHeaderSize:h,tagSize:h+d,value:p,valueSize:d}},ua=(a,e=a.byteLength)=>{switch(e){case 1:return a.getUint8(0);case 2:return a.getUint16(0);case 3:return a.getUint8(0)*et(2,16)+a.getUint16(1);case 4:return a.getUint32(0);case 5:return a.getUint8(0)*et(2,32)+a.getUint32(1);case 6:return a.getUint16(0)*et(2,32)+a.getUint32(2);case 7:{let t=a.getUint8(0)*281474976710656+a.getUint16(1)*4294967296+a.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},Ke=(a,e)=>{switch(e){case"int":return a.getInt8(0);case"uint":return ua(a);case"float":return a.byteLength===4?a.getFloat32(0):a.getFloat64(0);case"string":return new TextDecoder("ascii").decode(a);case"utf8":return new TextDecoder("utf-8").decode(a);case"date":return new Date(Date.UTC(2001,0)+a.getInt8(0)).getTime();case"master":return a;case"binary":return a;default:Mk(e)}},ir=(a,e)=>{let t=0;for(;t<a.byteLength;){let r=new DataView(a.buffer,a.byteOffset+t),i=Ag(r);if(!e(i))return;i.type==="master"&&ir(i.value,e),t=i.value.byteOffset-a.byteOffset+i.valueSize}},wg=a=>{if(a.getUint32(0)!==440786851)return!1;let e,t,r,i=Ag(a);return ir(i.value,({tag:s,type:n,value:o})=>(s===17143?e=Ke(o,n):s===17026?t=Ke(o,n):s===17029&&(r=Ke(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(r===void 0||r<=2)};var Rg=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],Dk=[231,22612,22743,167,171,163,160,175],Bk=a=>{let e,t,r,i,s=!1,n=!1,o=!1,u,l,c=!1,d=0;return ir(a,({tag:h,type:p,value:f,valueSize:b})=>{if(h===21419){let g=Ke(f,p);l=ua(g)}else h!==21420&&(l=void 0);return h===408125543?(e=f.byteOffset,t=f.byteOffset+b):h===357149030?s=!0:h===290298740?n=!0:h===2807729?r=Ke(f,p):h===17545?i=Ke(f,p):h===21420&&l===475249515?u=Ke(f,p):h===374648427?ir(f,({tag:g,type:S,value:y})=>g===30321?(c=Ke(y,S)===1,!1):!0):s&&n&&Rg.includes(h)&&(o=!0),!o}),Yu(e,"Failed to parse webm Segment start"),Yu(t,"Failed to parse webm Segment end"),Yu(i,"Failed to parse webm Segment duration"),r=r!=null?r:1e6,{segmentStart:Math.round(e/1e9*r*1e3),segmentEnd:Math.round(t/1e9*r*1e3),timeScale:r,segmentDuration:Math.round(i/1e9*r*1e3),cuesSeekPosition:u,is3dVideo:c,stereoMode:d,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},Ok=a=>{if(Ck(a.cuesSeekPosition))return;let e=a.segmentStart+a.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},Vk=(a,e)=>{let t=!1,r=!1,i=o=>kg(o.time)&&kg(o.position),s=[],n;return ir(a,({tag:o,type:u,value:l})=>{switch(o){case 475249515:t=!0;break;case 187:n&&i(n)&&s.push(n),n={};break;case 179:n&&(n.time=Ke(l,u));break;case 183:break;case 241:n&&(n.position=Ke(l,u));break;default:t&&Rg.includes(o)&&(r=!0)}return!(t&&r)}),n&&i(n)&&s.push(n),s.map((o,u)=>{let{time:l,position:c}=o,d=s[u+1];return{status:"none",time:{from:l,to:d?d.time:e.segmentDuration},byte:{from:e.segmentStart+c,to:d?e.segmentStart+d.position-1:e.segmentEnd-1}}})},_k=a=>{let e=0,t=!1;try{ir(a,r=>r.tag===524531317?r.tagSize<=a.byteLength?(e=r.tagSize,!1):(e+=r.tagHeaderSize,!0):Dk.includes(r.tag)?(e+r.tagSize<=a.byteLength&&(e+=r.tagSize,t||(t=[163,160,175].includes(r.tag))),!0):!1)}catch(r){}return e>0&&e<=a.byteLength&&t?new DataView(a.buffer,a.byteOffset,e):null},$g={validateData:wg,parseInit:Bk,getIndexRange:Ok,parseSegments:Vk,parseFeedableSegmentChunk:_k};var la=a=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(a);if(e){let[,t,r]=e;if(t==="audio"||t==="video")switch(r){case"webm":return $g;case"mp4":return xg}}throw new ReferenceError(`Unsupported mime type ${a}`)};var el=je(Xg(),1),aS=je(Nr(),1);var Zu=a=>{let e=a.split("."),[t,...r]=e;if(!t)return!1;switch(t){case"av01":{let[i,s,n]=r;return!!(n&&parseInt(n,10)>8)}case"vp09":{let[i,s,n]=r;return!!(i&&parseInt(i,10)>=2&&n&&parseInt(n,10)>8)}case"avc1":{let i=r[0];if(!i||i.length!==6)return!1;let[s,n]=i.toUpperCase(),o=s+n;return["6E","7A","F4"].includes(o)}}return!1};import{isNonNullable as tS,isNullable as rS}from"@vkontakte/videoplayer-shared";var Zg=a=>{if(a.includes("/")){let e=a.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(a)};var eS=a=>{var e;try{let t=SR(),r=a.match(t),{groups:i}=r!=null?r:{};if(i){let s={};if(i.extensions){let u=i.extensions.toLowerCase().match(/(?:[0-9a-wy-z](?:-[a-z0-9]{2,8})+)/g);Array.from(u||[]).forEach(l=>{s[l[0]]=l.slice(2)})}let n=(e=i.variants)==null?void 0:e.split(/-/).filter(u=>u!==""),o={extlang:i.extlang,langtag:i.langtag,language:i.language,privateuse:i.privateuse||i.privateuse2,region:i.region,script:i.script,extensions:s,variants:n};return Object.keys(o).forEach(u=>{let l=o[u];(typeof l=="undefined"||l==="")&&delete o[u]}),o}return null}catch(t){return null}};function SR(){let a="(?<extlang>(?:[a-z]{3}(?:-[a-z]{3}){0,2}))",e="x(?:-[a-z0-9]{1,8})+",c=`^(?:(?<langtag>${`
58
+ `}),p&&Ob(i,u,p,o)};var re=a=>new URL(a).hostname;import{assertNever as Hb,assertNonNullable as jb,combine as rk,debounce as ik,ErrorCategory as Gb,filter as Wb,filterChanged as ak,isNonNullable as Vu,map as _s,merge as Yb,observableFrom as sk,once as nk,Subscription as ok,ValueSubject as _u,videoQualityToHeight as uk,videoSizeToQuality as lk}from"@vkontakte/videoplayer-shared";var _b=a=>{if(a instanceof DOMException&&["Failed to load because no supported source was found.","The element has no supported sources."].includes(a.message))throw a;return!(a instanceof DOMException&&(a.code===20||a.name==="AbortError"))},ye=(a,e)=>w(void 0,null,function*(){let t=a.muted;try{yield a.play()}catch(r){if(!_b(r))return!1;if(e&&e(),t)return console.warn(r),!1;a.muted=!0;try{yield a.play()}catch(i){return _b(i)&&(a.muted=!1,console.warn(i)),!1}}return!0});import{isNonNullable as Bs,isNullable as _w,assertNonNullable as Bi}from"@vkontakte/videoplayer-shared";import{isNonNullable as Nb,assertNonNullable as Ds,now as Ow}from"@vkontakte/videoplayer-shared";function ie(){return Ow()}function Cu(a){return ie()-a}function Du(a){let e=a.split("/"),t=e.slice(0,e.length-1).join("/"),r=/^([a-z]+:)?\/\//i,i=n=>r.test(n);return{resolve:(n,o,u=!1)=>{i(n)||(n.startsWith("/")||(n="/"+n),n=t+n);let l=n.indexOf("?")>-1?"&":"?";return u&&(n+=l+"lowLat=1",l="&"),o&&(n+=l+"_rnd="+Math.floor(999999999*Math.random())),n}}}function Fb(a,e,t){let r=(...i)=>{t.apply(null,i),a.removeEventListener(e,r)};a.addEventListener(e,r)}function Ur(a,e,t,r){let i=window.XMLHttpRequest,s,n,o,u=!1,l=0,c,d,h=!1,p="arraybuffer",f=7e3,b=2e3,g=()=>{if(u)return;Ds(c);let R=Cu(c),U;if(R<b){U=b-R,setTimeout(g,U);return}b*=2,b>f&&(b=f),n&&n.abort(),n=new i,k()},T=R=>(s=R,_),y=R=>(d=R,_),S=()=>(p="json",_),I=()=>{if(!u){if(--l>=0){g(),r&&r();return}u=!0,d&&d(),t&&t()}},E=R=>(h=R,_),k=()=>{c=ie(),n=new i,n.open("get",a);let R=0,U,L=0,W=()=>(Ds(c),Math.max(c,Math.max(U||0,L||0)));if(s&&n.addEventListener("progress",v=>{let $=ie();s.updateChunk&&v.loaded>R&&(s.updateChunk(W(),v.loaded-R),R=v.loaded,U=$)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>I())),n.addEventListener("load",()=>{if(u)return;Ds(n);let v=n.status;if(v>=200&&v<300){if(n.response.byteLength&&s){let $=n.response.byteLength-R;$&&s.updateChunk&&s.updateChunk(W(),$)}n.responseType==="json"&&!Object.values(n.response).length?I():(d&&d(),e(n.response))}else I()}),n.addEventListener("error",()=>{I()}),h){let v=()=>{Ds(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(L=ie(),n.removeEventListener("readystatechange",v))};n.addEventListener("readystatechange",v)}return n.responseType=p,n.send(),_},_={withBitrateReporting:T,withParallel:E,withJSONResponse:S,withRetryCount:R=>(l=R,_),withRetryInterval:(R,U)=>(Nb(R)&&(b=R),Nb(U)&&(f=U),_),withTimeout:R=>(o=R,_),withFinally:y,send:k,abort:()=>{n&&(n.abort(),n=void 0),u=!0,d&&d()}};return _}var Ci=class{constructor(e){this.intervals=[];this.currentRate=0;this.logger=e}_updateRate(e){let t=.2;this.currentRate&&(e<this.currentRate*.1?t=.8:e<this.currentRate*.5?t=.5:e<this.currentRate*.7&&(t=.3)),e=Math.max(1,Math.min(e,100*1024*1024)),this.currentRate=this.currentRate?this.currentRate*(1-t)+e*t:e}_createInterval(e,t,r){return{start:e,end:t,bytes:r}}_doMergeIntervals(e,t){e.start=Math.min(t.start,e.start),e.end=Math.max(t.end,e.end),e.bytes+=t.bytes}_mergeIntervals(e,t){return e.start<=t.end&&t.start<=e.end?(this._doMergeIntervals(e,t),!0):!1}_flushIntervals(){if(!this.intervals.length)return!1;let e=this.intervals[0].start,t=this.intervals[this.intervals.length-1].end-500;if(t-e>2e3){let r=0,i=0;for(;this.intervals.length>0;){let s=this.intervals[0];if(s.end<=t)r+=s.end-s.start,i+=s.bytes,this.intervals.splice(0,1);else{if(s.start>=t)break;{let n=t-s.start,o=s.end-s.start;r+=n;let u=s.bytes*n/o;i+=u,s.start=t,s.bytes-=u}}}if(i>0&&r>0){let s=i*8/(r/1e3);return this._updateRate(s),this.logger(`rate updated, new=${Math.round(s/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(i)}/${Math.round(r)} interval=${Math.round(t-e)}`),!0}}return!1}_joinIntervals(){let e;do{e=!1;for(let t=0;t<this.intervals.length-1;++t)this._mergeIntervals(this.intervals[t],this.intervals[t+1])&&(this.intervals.splice(t+1,1),e=!0)}while(e)}addInterval(e,t,r){return this.intervals.push(this._createInterval(e,t,r)),this._joinIntervals(),this.intervals.length>100&&(this.logger(`too many intervals (${this.intervals.length}); will merge`,{type:"warn"}),this._doMergeIntervals(this.intervals[1],this.intervals[0]),this.intervals.splice(0,1)),this._flushIntervals()}getBitRate(){return this.currentRate}};var Di=class{constructor(e,t,r,i,s){this.pendingQueue=[];this.activeRequests={};this.completeRequests={};this.averageSegmentDuration=2e3;this.lastPrefetchStart=0;this.throttleTimeout=null;this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=r,this.MAX_PARALLEL_REQUESTS=i,this.logger=s}limitCompleteCount(){let e;for(;(e=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){let t=e[Math.floor(Math.random()*e.length)];this.logger(`Dropping completed request for url ${t}`,{type:"warn"}),delete this.completeRequests[t]}}_sendRequest(e,t){let r=ie(),i=u=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=u,e._errorCB?e._errorCB(u):(this.limitCompleteCount(),this.completeRequests[t]=e)},s=u=>{e._complete=1,e._responseData=u,e._downloadTime=ie()-r,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(u,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},n=()=>{e._finallyCB&&e._finallyCB()},o=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=Ur(t,s,()=>i("error"),o),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally(n),this.activeRequests[t]=e,e._request.send(),this.lastPrefetchStart=ie()}_getParallelRequestCount(){return Math.min(this.MAX_PARALLEL_REQUESTS,this.averageSegmentDuration<3e3?3:2)}_getPrefetchDelay(){return Math.max(100,Math.min(5e3,this.averageSegmentDuration/3))}_canSendPending(){let e=this._getParallelRequestCount(),t=ie();if(Object.keys(this.activeRequests).length>=e)return!1;let r=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),r>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),r),!1):!0}_sendPending(){for(;this._canSendPending();){let e=this.pendingQueue.pop();if(e){if(this.activeRequests[e]||this.completeRequests[e])continue;this.logger(`Submitting pending request url=${e}`),this._sendRequest({},e)}else return}}_removeFromActive(e){delete this.completeRequests[e],delete this.activeRequests[e]}abortAll(){Object.values(this.activeRequests).forEach(e=>{e&&e._request&&e._request.abort()}),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,r,i){let s={};return s.send=()=>{let n=this.activeRequests[e]||this.completeRequests[e];if(n)n._cb=t,n._errorCB=r,n._retryCB=i,n._finallyCB=s._finallyCB,n._error||n._complete?(this._removeFromActive(e),setTimeout(()=>{n._complete?(this.logger(`Requested url already prefetched, url=${e}`),t(n._responseData,n._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${e}`),r(n._errorMsg)),s._finallyCB&&s._finallyCB()},0)):this.logger(`Attached to active request, url=${e}`);else{let o=this.pendingQueue.indexOf(e);o!==-1&&this.pendingQueue.splice(o,1),this.logger(`Request not prefetched, starting new request, url=${e}${o===-1?"":"; removed pending"}`),this._sendRequest(s,e)}},s._cb=t,s._errorCB=r,s._retryCB=i,s.abort=function(){s.request&&s.request.abort()},s.withFinally=n=>(s._finallyCB=n,s),s}prefetch(e){this.activeRequests[e]||this.completeRequests[e]?this.logger(`Request already active for url=${e}`):(this.logger(`Added to pending queue; url=${e}`),this.pendingQueue.unshift(e),this._sendPending())}optimizeForSegDuration(e){this.averageSegmentDuration=e}};import{Subject as Nw}from"@vkontakte/videoplayer-shared";var Os=1e4,Bu=3;var Fw=6e4,Uw=10,qw=1,Hw=500,Oi=class{constructor(e){this.paused=!1;this.autoQuality=!0;this.maxAutoQuality=void 0;this.buffering=!0;this.destroyed=!1;this.videoPlayStarted=!1;this.lowLatency=!1;this.bitrate=0;this.manifest=[];this.sourceBuffer=0;this.bufferStates=[];this.sourceJitter=-1;this.params=e,this.soundProhibitedEvent$=new Nw,this.chunkRateEstimator=new Ci(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=Du(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setMaxAutoQuality(e){this.maxAutoQuality=e}switchByName(e){let t;for(let r=0;r<this.manifest.length;++r)if(t=this.manifest[r],t.name===e){this._switchToQuality(t);return}}catchUp(){this.rep&&this.rep.stop(),this.currentManifestEntry&&(this.paused=!1,this._initPlayerWith(this.currentManifestEntry),this._notifyBuffering(!0))}stop(){this.params.videoElement.pause(),this.rep&&(this.rep.stop(),this.rep=null)}pause(){this.paused=!0,this.params.videoElement.pause(),this.videoPlayStarted=!1,this._notifyBuffering(!1)}play(){this.paused=!1;let e=this.lowLatency&&this._getBufferSizeSec()>this.sourceJitter+5;this.rep&&!e?(this.bufferStates=[],this.videoPlayStarted=!1,this.shouldPlay()?this._playVideoElement():this._notifyBuffering(!0)):this.catchUp()}startPlay(e,t){this.autoQuality=t,this._initPlayerWith(e)}destroy(){this.destroyed=!0,this.rep&&(this.rep.stop(),this.rep=null),this.manifestRequest&&this.manifestRequest.abort(),this.manifestRefetchTimer&&(clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=void 0)}reinit(e){this.manifestUrl=e,this.urlResolver=Du(e),this.catchUp()}_handleNetworkError(){this.params.logger("Fatal network error"),this.params.playerCallback({name:"error",type:"network"})}_retryCallback(){this.params.playerCallback({name:"retry"})}_getBufferSizeSec(){let e=this.params.videoElement,t=0,r=e.buffered.length;return r!==0&&(t=e.buffered.end(r-1)-Math.max(e.currentTime,e.buffered.start(0))),t}_notifyBuffering(e){this.destroyed||(this.params.logger(`buffering: ${e}`),this.params.playerCallback({name:"buffering",isBuffering:e}),this.buffering=e)}_initVideo(){let{videoElement:e,logger:t}=this.params;e.addEventListener("error",()=>{var i;!!e.error&&!this.destroyed&&(t(`Video element error: ${(i=e.error)==null?void 0:i.code}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{let r=this._getBufferSizeSec();!this.paused&&r<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(r+.1)*1e3)):this.buffering&&this.videoPlayStarted&&this._notifyBuffering(!1)}),e.addEventListener("playing",()=>{t("playing")}),e.addEventListener("stalled",()=>this._fixupStall()),e.addEventListener("waiting",()=>this._fixupStall())}_fixupStall(){let{logger:e,videoElement:t}=this.params,r=t.buffered.length,i;r!==0&&(i=t.buffered.start(r-1),t.currentTime<i&&(e("Fixup stall"),t.currentTime=i))}_selectQuality(e){let{videoElement:t}=this.params,r,i,s,n=t&&1.62*(window.devicePixelRatio||1)*t.offsetHeight||520;for(let o=0;o<this.manifest.length;++o)s=this.manifest[o],!(this.maxAutoQuality&&s.video.height>this.maxAutoQuality)&&(s.bitrate<e&&n>Math.min(s.video.height,s.video.width)?(!i||s.bitrate>i.bitrate)&&(i=s):(!r||r.bitrate>s.bitrate)&&(r=s));return i||r}shouldPlay(){if(this.paused)return!1;let t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||Bs(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){let{logger:r,videoElement:i,playerCallback:s}=this.params;this.mediaSource=new window.MediaSource,r("setting video src"),i.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.videoPlayStarted=!1,i.addEventListener("canplay",()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});let n=()=>{Fb(i,"progress",()=>{i.buffered.length?(i.currentTime=i.buffered.start(0),s({name:"playing"})):n()})};n()}_initPlayerWith(e){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new Di(Bu,Os,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){let{logger:t,videoElement:r,playerCallback:i}=this.params,s=!1,n=null,o=null,u=null,l=null,c=!1,d=()=>{let I=s&&(!c||c===this.rep);return I||t("Not running!"),I},h=(I,E,k)=>{u&&u.abort(),u=Ur(this.urlResolver.resolve(I,!1),E,k,()=>this._retryCallback()).withTimeout(Os).withBitrateReporting(this.bitrateSwitcher).withRetryCount(Bu).withFinally(()=>{u=null}).send()},p=(I,E,k)=>{Bi(this.filesFetcher),o==null||o.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(I,!1),E,k,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},f=I=>{let E=r.playbackRate;r.playbackRate!==I&&(t(`Playback rate switch: ${E}=>${I}`),r.playbackRate=I)},b=I=>{this.lowLatency=I,t(`lowLatency changed to ${I}`),g()},g=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)f(1);else{let I=this._getBufferSizeSec();if(this.bufferStates.length<5){f(1);return}let k=ie()-1e4,B=0;for(let V=0;V<this.bufferStates.length;V++){let M=this.bufferStates[V];I=Math.min(I,M.buf),M.ts<k&&B++}this.bufferStates.splice(0,B),t(`update playback rate; minBuffer=${I} drop=${B} jitter=${this.sourceJitter}`);let G=I-qw;this.sourceJitter>=0?G-=this.sourceJitter/2:this.sourceJitter-=1,G>3?f(1.15):G>1?f(1.1):G>.3?f(1.05):f(1)}},T=I=>{let E,k=()=>E&&E.start?E.start.length:0,B=v=>E.start[v]/1e3,G=v=>E.dur[v]/1e3,V=v=>E.fragIndex+v,M=(v,$)=>({chunkIdx:V(v),startTS:B(v),dur:G(v),discontinuity:$}),_=()=>{let v=0;if(E&&E.dur){let $=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,Q=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,N=$;this.sourceJitter>1&&(N+=this.sourceJitter-1);let ue=E.dur.length-1;for(;ue>=0&&(N-=E.dur[ue],!(N<=0));--ue);v=Math.min(ue,E.dur.length-1-Q),v=Math.max(v,0)}return M(v,!0)},R=v=>{let $=k();if(!($<=0)){if(Bs(v)){for(let Q=0;Q<$;Q++)if(B(Q)>v)return M(Q)}return _()}},U=v=>{let $=k(),Q=v?v.chunkIdx+1:0,N=Q-E.fragIndex;if(!($<=0)){if(!v||N<0||N-$>Uw)return t(`Resync: offset=${N} bChunks=${$} chunk=`+JSON.stringify(v)),_();if(!(N>=$))return M(Q-E.fragIndex,!1)}},L=(v,$,Q)=>{l&&l.abort(),l=Ur(this.urlResolver.resolve(v,!0,this.lowLatency),$,Q,()=>this._retryCallback()).withTimeout(Os).withRetryCount(Bu).withFinally(()=>{l=null}).withJSONResponse().send()};return{seek:(v,$)=>{L(I,Q=>{if(!d())return;E=Q;let N=!!E.lowLatency;N!==this.lowLatency&&b(N);let ue=0;for(let qe=0;qe<E.dur.length;++qe)ue+=E.dur[qe];ue>0&&(Bi(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(ue/E.dur.length)),i({name:"index",zeroTime:E.zeroTime,shiftDuration:E.shiftDuration}),this.sourceJitter=E.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,E.jitter/1e3)):1,v(R($))},()=>this._handleNetworkError())},nextChunk:U}},y=()=>{s=!1,o&&o.abort(),u&&u.abort(),l&&l.abort(),Bi(this.filesFetcher),this.filesFetcher.abortAll()};return c={start:I=>{let{videoElement:E,logger:k}=this.params,B=T(e.jidxUrl),G,V,M,_,R=0,U,L,W,v=()=>{U&&(clearTimeout(U),U=void 0);let H=Math.max(Hw,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),he=R+H,xe=ie(),Me=Math.min(1e4,he-xe);R=xe;let gt=()=>{l||d()&&B.seek(()=>{d()&&(R=ie(),$(),v())})};Me>0?U=window.setTimeout(()=>{this.paused?v():gt()},Me):gt()},$=()=>{let H;for(;H=B.nextChunk(_);)_=H,pr(H);let he=B.nextChunk(M);if(he){if(M&&he.discontinuity){k("Detected discontinuity; restarting playback"),this.paused?v():(y(),this._initPlayerWith(e));return}qe(he)}else v()},Q=(H,he)=>{if(!d()||!this.sourceBuffer)return;let xe,Me,gt,hr=St=>{window.setTimeout(()=>{d()&&Q(H,he)},St)};if(this.sourceBuffer.updating)k("Source buffer is updating; delaying appendBuffer"),hr(100);else{let St=ie(),Ft=E.currentTime;!this.paused&&E.buffered.length>1&&L===Ft&&St-W>500&&(k("Stall suspected; trying to fix"),this._fixupStall()),L!==Ft&&(L=Ft,W=St);let fr=this._getBufferSizeSec();if(fr>30)k(`Buffered ${fr} seconds; delaying appendBuffer`),hr(2e3);else try{this.sourceBuffer.appendBuffer(H),this.videoPlayStarted?(this.bufferStates.push({ts:St,buf:fr}),g(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),he&&he()}catch(Xr){if(Xr.name==="QuotaExceededError")k("QuotaExceededError; delaying appendBuffer"),gt=this.sourceBuffer.buffered.length,gt!==0&&(xe=this.sourceBuffer.buffered.start(0),Me=Ft,Me-xe>4&&this.sourceBuffer.remove(xe,Me-3)),hr(1e3);else throw Xr}}},N=()=>{V&&G&&(k([`Appending chunk, sz=${V.byteLength}:`,JSON.stringify(M)]),Q(V,function(){V=null,$()}))},ue=H=>e.fragUrlTemplate.replace("%%id%%",H.chunkIdx),qe=H=>{d()&&p(ue(H),(he,xe)=>{if(d()){if(xe/=1e3,V=he,M=H,n=H.startTS,xe){let Me=Math.min(10,H.dur/xe);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*Me:Me}N()}},()=>this._handleNetworkError())},pr=H=>{d()&&(Bi(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(ue(H),!1)))},Jr=H=>{d()&&(e.cachedHeader=H,Q(H,()=>{G=!0,N()}))};s=!0,B.seek(H=>{if(d()){if(R=ie(),!H){v();return}_=H,!_w(I)||H.startTS>I?qe(H):(M=H,$())}},I),e.cachedHeader?Jr(e.cachedHeader):h(e.headerUrl,Jr,()=>this._handleNetworkError())},stop:y,getTimestampSec:()=>n},c}_switchToQuality(e){let{logger:t,playerCallback:r}=this.params,i;e.bitrate!==this.bitrate&&(this.rep&&(i=this.rep.getTimestampSec(),Bs(i)&&(i+=.1),this.rep.stop()),this.currentManifestEntry=e,this.rep=this._representation(e),t(`switch to quality: codecs=${e.codecs}; headerUrl=${e.headerUrl}; bitrate=${e.bitrate}`),this.bitrate=e.bitrate,Bi(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(i),r({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return Bs(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,r=d=>{if(!this.autoQuality)return;let h,p,f;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&d<this.bitrate&&(p=this._getBufferSizeSec(),f=d/this.bitrate,p>10&&f>.8||p>15&&f>.5||p>20&&f>.3)){e(`Not switching: buffer=${Math.floor(p)}; bitrate=${this.bitrate}; newRate=${Math.floor(d)}`);return}h=this._selectQuality(d),h?this._switchToQuality(h):e(`Could not find quality by bitrate ${d}`)},s={updateChunk:(h,p)=>{let f=ie();if(this.chunkRateEstimator.addInterval(h,f,p)){let g=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:p,duration:f-h,speed:g}),!0}},get:()=>{let h=this.chunkRateEstimator.getBitRate();return h?h*.85:0}},n=-1/0,o,u=!0,l=()=>{let d=s.get();if(d&&o&&this.autoQuality){if(u&&d>o&&Cu(n)<3e4)return;r(d)}u=this.autoQuality};return{updateChunk:(d,h)=>{let p=s.updateChunk(d,h);return p&&l(),p},notifySwitch:d=>{let h=ie();d<o&&(n=h),o=d}}}_fetchManifest(e,t,r){this.manifestRequest=Ur(this.urlResolver.resolve(e,!0),t,r,()=>this._retryCallback()).withJSONResponse().withTimeout(Os).withRetryCount(this.params.config.manifestRetryMaxCount).withRetryInterval(this.params.config.manifestRetryInterval,this.params.config.manifestRetryMaxInterval).send().withFinally(()=>{this.manifestRequest=void 0})}_playVideoElement(){let{videoElement:e}=this.params;ye(e,()=>{this.soundProhibitedEvent$.next()}).then(t=>{t||(this.params.liveOffset.pause(),this.params.videoState.setState("paused"))})}_handleManifestUpdate(e){let{logger:t,playerCallback:r,videoElement:i}=this.params,s=n=>{let o=[];return n!=null&&n.length?(n.forEach((u,l)=>{u.video&&i.canPlayType(u.codecs).replace(/no/,"")&&window.MediaSource.isTypeSupported(u.codecs)&&(u.index=l,o.push(u))}),o.sort(function(u,l){return u.video&&l.video?l.video.height-u.video.height:l.bitrate-u.bitrate}),o):(r({name:"error",type:"empty_manifest"}),[])};this.manifest=s(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),r({name:"manifest",manifest:this.manifest})}_refetchManifest(e){this.destroyed||(this.manifestRefetchTimer&&clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=window.setTimeout(()=>{this._fetchManifest(e,t=>{this.destroyed||(this._handleManifestUpdate(t),this._refetchManifest(e))},()=>this._refetchManifest(e))},Fw))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};import{debounce as jw,filter as Ub,fromEvent as Gw,interval as Ww,isHigher as Yw,isInvariantQuality as Qw,isLower as zw,merge as Kw,Subject as qb,Subscription as Jw}from"@vkontakte/videoplayer-shared";var Ou=class{constructor(){this.onDroopedVideoFramesLimit$=new qb;this.subscription=new Jw;this.playing=!1;this.tracks=[];this.forceChecker$=new qb;this.isForceCheckCounter=0;this.prevTotalVideoFrames=0;this.prevDroppedVideoFrames=0;this.limitCounts={};this.handleChangeVideoQuality=()=>{let e=this.tracks.find(({size:t})=>(t==null?void 0:t.height)===this.video.videoHeight&&(t==null?void 0:t.width)===this.video.videoWidth);e&&!Qw(e.quality)&&this.onChangeQuality(e.quality)};this.checkDroppedFrames=()=>{var n;let{totalVideoFrames:e,droppedVideoFrames:t}=this.video.getVideoPlaybackQuality(),r=e-this.prevTotalVideoFrames,i=t-this.prevDroppedVideoFrames,s=1-(r-i)/r;!isNaN(s)&&s>0&&this.log({message:`[dropped]. current dropped percent: ${s}, limit: ${this.droppedFramesChecker.percentLimit}`}),!isNaN(s)&&s>=this.droppedFramesChecker.percentLimit&&Yw(this.currentQuality,this.droppedFramesChecker.minQualityBanLimit)&&(this.limitCounts[this.currentQuality]=((n=this.limitCounts[this.currentQuality])!=null?n:0)+1,this.maxQualityLimit=this.getMaxQualityLimit(this.currentQuality),this.currentTimer&&window.clearTimeout(this.currentTimer),this.currentTimer=window.setTimeout(()=>this.maxQualityLimit=this.getMaxQualityLimit(),this.droppedFramesChecker.qualityUpWaitingTime),this.onDroopedVideoFramesLimitTrigger()),this.savePrevFrameCounts(e,t)}}connect(e){this.log=e.logger.createComponentLog("DroppedFramesManager"),this.video=e.video,this.isAuto=e.isAuto,this.tracks=e.tracks,this.droppedFramesChecker=e.droppedFramesChecker,this.subscription.add(e.playing$.subscribe(()=>this.playing=!0)),this.subscription.add(e.pause$.subscribe(()=>this.playing=!1)),this.isEnabled&&this.subscribe()}destroy(){this.currentTimer&&window.clearTimeout(this.currentTimer),this.subscription.unsubscribe()}get droppedVideoMaxQualityLimit(){return this.maxQualityLimit}subscribe(){this.subscription.add(Gw(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=Ww(this.droppedFramesChecker.checkTime).pipe(Ub(()=>this.playing),Ub(()=>{let i=!!this.isForceCheckCounter;return i&&(this.isForceCheckCounter-=1),!i})),t=this.forceChecker$.pipe(jw(this.droppedFramesChecker.checkTime)),r=Kw(e,t);this.subscription.add(r.subscribe(this.checkDroppedFrames))}onChangeQuality(e){this.currentQuality=e;let{totalVideoFrames:t,droppedVideoFrames:r}=this.video.getVideoPlaybackQuality();this.savePrevFrameCounts(t,r),this.isForceCheckCounter=this.droppedFramesChecker.tickCountAfterQualityChange,this.forceChecker$.next()}onDroopedVideoFramesLimitTrigger(){this.isAuto.getState()&&(this.log({message:`[onDroopedVideoFramesLimit]. maxQualityLimit: ${this.maxQualityLimit}`}),this.onDroopedVideoFramesLimit$.next())}getMaxQualityLimit(e){var r,i;let t=(i=(r=Object.entries(this.limitCounts).filter(([,s])=>s>=this.droppedFramesChecker.countLimit).sort(([s],[n])=>zw(s,n)?-1:1))==null?void 0:r[0])==null?void 0:i[0];return e!=null?e:t}get isEnabled(){return this.droppedFramesChecker.enabled&&this.isDroppedFramesCheckerSupport}get isDroppedFramesCheckerSupport(){return!!this.video&&typeof this.video.getVideoPlaybackQuality=="function"}savePrevFrameCounts(e,t){this.prevTotalVideoFrames=e,this.prevDroppedVideoFrames=t}},Vs=Ou;import{map as Xw,Observable as Zw}from"@vkontakte/videoplayer-shared";import{fromEvent as ek}from"@vkontakte/videoplayer-shared";var Vi=()=>{var a;return!!((a=window.documentPictureInPicture)!=null&&a.window)||!!document.pictureInPictureElement};var tk=(a,e)=>new Zw(t=>{if(!window.IntersectionObserver)return;let r={root:null},i=new IntersectionObserver((n,o)=>{n.forEach(u=>t.next(u.isIntersecting||Vi()))},A(A({},r),e));i.observe(a);let s=ek(document,"visibilitychange").pipe(Xw(n=>!document.hidden||Vi())).subscribe(n=>t.next(n));return()=>{i.unobserve(a),s.unsubscribe}}),Fe=tk;var ck=["paused","playing","ready"],dk=["paused","playing","ready"],_i=class{constructor(e){this.subscription=new ok;this.videoState=new C("stopped");this.representations$=new _u([]);this.textTracksManager=new _e;this.droppedFramesManager=new Vs;this.maxSeekBackTime$=new _u(1/0);this.zeroTime$=new _u(void 0);this.liveOffset=new dt;this._dashCb=e=>{var t,r,i,s;switch(e.name){case"buffering":{let n=e.isBuffering;this.params.output.isBuffering$.next(n);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${e.type}`,category:Gb.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{let n=e.manifest,o=[];for(let u of n){let l=(t=u.name)!=null?t:u.index.toString(10),c=(r=Rt(u.name))!=null?r:lk(u.video),d=u.bitrate/1e3,h=A({},u.video);if(!c)continue;let p={id:l,quality:c,bitrate:d,size:h};o.push({track:p,representation:u})}this.representations$.next(o),this.params.output.availableVideoTracks$.next(o.map(({track:u})=>u)),((i=this.videoState.getTransition())==null?void 0:i.to)==="manifest_ready"&&this.videoState.setState("manifest_ready");break}case"qualitySwitch":{let n=e.quality,o=(s=this.representations$.getValue().find(({representation:u})=>u===n))==null?void 0:s.track;this.params.output.hostname$.next(new URL(n.headerUrl,this.params.source.url).hostname),Vu(o)&&this.params.output.currentVideoTrack$.next(o);break}case"bandwidth":{let{size:n,duration:o}=e;this.params.dependencies.throughputEstimator.addRawSpeed(n,o);break}case"index":{this.maxSeekBackTime$.next(e.shiftDuration||0),this.zeroTime$.next(e.zeroTime);break}}};this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),r=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${r}; seekState: ${JSON.stringify(s)};`}),r==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState("stopped"));return}if(t)return;let n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(dk.includes(e)&&(n||o)){this.prepare();return}if((i==null?void 0:i.to)!=="paused"&&s.state==="requested"&&ck.includes(e)){this.seek(s.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(ne(this.params.source.url));return;case"manifest_ready":this.videoState.startTransitionTo("ready"),this.prepare();break;case"ready":if(r==="paused")this.videoState.setState("paused");else if(r==="playing"){this.videoState.startTransitionTo("playing");let u=i==null?void 0:i.from;u&&u==="ready"&&this.dash.catchUp(),this.dash.play()}return;case"playing":r==="paused"&&(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.dash.pause());return;case"paused":if(r==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.dash.play(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let u=this.liveOffset.getTotalOffset();u>=this.maxSeekBackTime$.getValue()&&(u=0,this.liveOffset.resetTo(u)),this.liveOffset.resume(),this.params.output.position$.next(-u/1e3),this.dash.reinit(ne(this.params.source.url,u))}return;default:return Hb(e)}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=i=>{e.output.error$.next({id:"DashLiveProvider",category:Gb.WTF,message:"DashLiveProvider internal logic error",thrown:i})};Yb(this.videoState.stateChangeStarted$.pipe(_s(i=>({transition:i,type:"start"}))),this.videoState.stateChangeEnded$.pipe(_s(i=>({transition:i,type:"end"})))).subscribe(({transition:i,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(i)}`})}),this.video=be(e.container,e.tuning),this.params.output.element$.next(this.video),this.dash=this.createLiveDashPlayer(),this.subscription.add(this.dash.soundProhibitedEvent$.subscribe(this.params.output.soundProhibitedEvent$)),this.params.output.duration$.next(1/0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(re(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);let r=ve(this.video);this.subscription.add(this.representations$.pipe(_s(i=>i.map(({track:s})=>s)),Wb(i=>!!i.length),nk()).subscribe(i=>this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:r.playing$,pause$:r.pause$,tracks:i}))),this.subscription.add(r.canplay$.subscribe(()=>{var i;((i=this.videoState.getTransition())==null?void 0:i.to)==="ready"&&this.videoState.setState("ready")},t)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused")},t)).add(r.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.videoState.setState("playing")},t)).add(r.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(ak(),_s(i=>-i/1e3)).subscribe(this.params.output.duration$)).add(rk({zeroTime:this.zeroTime$.pipe(Wb(Vu)),position:r.timeUpdate$}).subscribe(({zeroTime:i,position:s})=>this.params.output.liveTime$.next(i+s*1e3),t)).add(rt(this.video,this.params.desiredState.isLooped,t)).add(Se(this.video,this.params.desiredState.volume,r.volumeState$,t)).add(r.volumeState$.subscribe(this.params.output.volume$,t)).add(Ve(this.video,this.params.desiredState.playbackRate,r.playbackRateState$,t)).add(r.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(r.loadedMetadata$.subscribe(this.params.output.loadedMetadataEvent$)).add(r.playing$.subscribe(this.params.output.firstFrameEvent$)).add(r.canplay$.subscribe(this.params.output.canplay$)).add(r.inPiP$.subscribe(this.params.output.inPiP$)).add(r.inFullscreen$.subscribe(this.params.output.inFullscreen$)).add(Fe(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:i}})=>{let s=i&&uk(i);this.dash.setMaxAutoQuality(s),this.params.output.autoVideoTrackLimits$.next({max:i})})).add(this.videoState.stateChangeEnded$.subscribe(i=>{var s;switch(i.to){case"stopped":this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState("stopped");break;case"manifest_ready":case"ready":((s=this.params.desiredState.playbackState.getTransition())==null?void 0:s.to)==="ready"&&this.params.desiredState.playbackState.setState("ready");break;case"paused":this.params.desiredState.playbackState.setState("paused");break;case"playing":this.params.desiredState.playbackState.setState("playing");break;default:return Hb(i.to)}},t)).add(Yb(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,sk(["init"])).pipe(ik(0)).subscribe(this.syncPlayback,t))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.droppedFramesManager.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),ge(this.video)}createLiveDashPlayer(){let e=new Oi({videoElement:this.video,videoState:this.videoState,liveOffset:this.liveOffset,config:{maxParallelRequests:this.params.config.maxParallelRequests,minBuffer:this.params.tuning.live.minBuffer,minBufferSegments:this.params.tuning.live.minBufferSegments,lowLatencyMinBuffer:this.params.tuning.live.lowLatencyMinBuffer,lowLatencyMinBufferSegments:this.params.tuning.live.lowLatencyMinBufferSegments,isLiveCatchUpMode:this.params.tuning.live.isLiveCatchUpMode,manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},playerCallback:this._dashCb,logger:t=>{this.params.dependencies.logger.log({message:String(t),component:"LiveDashPlayer"})}});return e.pause(),e}prepare(){var l,c,d,h,p,f;let e=this.representations$.getValue(),t=(c=(l=this.params.desiredState.videoTrack.getTransition())==null?void 0:l.to)!=null?c:this.params.desiredState.videoTrack.getState(),r=(h=(d=this.params.desiredState.autoVideoTrackSwitching.getTransition())==null?void 0:d.to)!=null?h:this.params.desiredState.autoVideoTrackSwitching.getState(),i=!r&&Vu(t)?t:$t(e.map(({track:b})=>b),{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},throughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),s=i==null?void 0:i.id,n=this.params.desiredState.videoTrack.getTransition(),o=(p=this.params.desiredState.videoTrack.getState())==null?void 0:p.id,u=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(i&&(n||s!==o)&&this.setVideoTrack(i),u&&this.setAutoQuality(r),n||u||s!==o){let b=(f=e.find(({track:g})=>g.id===s))==null?void 0:f.representation;jb(b,"Representations missing"),this.dash.startPlay(b,r)}}setVideoTrack(e){var r;let t=(r=this.representations$.getValue().find(({track:i})=>i.id===e.id))==null?void 0:r.representation;jb(t,`No such representation ${e.id}`),this.dash.switchByName(t.name),this.params.desiredState.videoTrack.setState(e)}setAutoQuality(e){this.dash.setAutoQualityEnabled(e),this.params.desiredState.autoVideoTrackSwitching.setState(e)}seek(e){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),r=this.videoState.getState(),i=t==="paused"&&r==="paused",s=-e,n=s<=this.maxSeekBackTime$.getValue()?s:0;this.params.output.position$.next(e/1e3),this.dash.reinit(ne(this.params.source.url,n)),i&&this.dash.pause(),this.liveOffset.resetTo(n,i)}};var Qb=_i;var at=(a,e)=>{let t=0;for(let r=0;r<a.length;r++){let i=a.start(r)*1e3,s=a.end(r)*1e3;i<=e&&e<=s&&(t=s)}return Math.max(t-e,0)};import{assertNever as qR,assertNonNullable as HR,debounce as jR,ErrorCategory as ml,filter as ES,filterChanged as bl,fromEvent as GR,isNonNullable as WR,map as xS,merge as ln,observableFrom as YR,observeElementSize as QR,once as PS,Subscription as zR,ValueSubject as KR}from"@vkontakte/videoplayer-shared";var Ns=class{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,r){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:r})}removeEventListener(e,t){if(!(e in this.listeners))return;let r=this.listeners[e];for(let i=0,s=r.length;i<s;i++)if(r[i].callback===t){r.splice(i,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;let r=this.listeners[e.type].slice();for(let i=0,s=r.length;i<s;i++){let n=r[i];try{n.callback.call(this,e)}catch(o){Promise.resolve().then(()=>{throw o})}n.options&&n.options.once&&this.removeEventListener(e.type,n.callback)}return!e.defaultPrevented}},qr=class extends Ns{constructor(){super(),this.listeners||Ns.call(this),Object.defineProperty(this,"aborted",{value:!1,writable:!0,configurable:!0}),Object.defineProperty(this,"onabort",{value:null,writable:!0,configurable:!0}),Object.defineProperty(this,"reason",{value:void 0,writable:!0,configurable:!0})}toString(){return"[object AbortSignal]"}dispatchEvent(e){e.type==="abort"&&(this.aborted=!0,typeof this.onabort=="function"&&this.onabort.call(this,e)),super.dispatchEvent(e)}},Ni=class{constructor(){Object.defineProperty(this,"signal",{value:new qr,writable:!0,configurable:!0})}abort(e){let t;try{t=new Event("abort")}catch(i){typeof document!="undefined"?document.createEvent?(t=document.createEvent("Event"),t.initEvent("abort",!1,!1)):(t=document.createEventObject(),t.type="abort"):t={type:"abort",bubbles:!1,cancelable:!1}}let r=e;if(r===void 0)if(typeof document=="undefined")r=new Error("This operation was aborted"),r.name="AbortError";else try{r=new DOMException("signal is aborted without reason")}catch(i){r=new Error("This operation was aborted"),r.name="AbortError"}this.signal.reason=r,this.signal.dispatchEvent(t)}toString(){return"[object AbortController]"}};typeof Symbol!="undefined"&&Symbol.toStringTag&&(Ni.prototype[Symbol.toStringTag]="AbortController",qr.prototype[Symbol.toStringTag]="AbortSignal");function Fs(a){return a.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof a.Request=="function"&&!a.Request.prototype.hasOwnProperty("signal")||!a.AbortController}function Nu(a){typeof a=="function"&&(a={fetch:a});let{fetch:e,Request:t=e.Request,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:i=!1}=a;if(!Fs({fetch:e,Request:t,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:i}))return{fetch:e,Request:s};let s=t;(s&&!s.prototype.hasOwnProperty("signal")||i)&&(s=function(l,c){let d;c&&c.signal&&(d=c.signal,delete c.signal);let h=new t(l,c);return d&&Object.defineProperty(h,"signal",{writable:!1,enumerable:!1,configurable:!0,value:d}),h},s.prototype=t.prototype);let n=e;return{fetch:(u,l)=>{let c=s&&s.prototype.isPrototypeOf(u)?u.signal:l?l.signal:void 0;if(c){let d;try{d=new DOMException("Aborted","AbortError")}catch(p){d=new Error("Aborted"),d.name="AbortError"}if(c.aborted)return Promise.reject(d);let h=new Promise((p,f)=>{c.addEventListener("abort",()=>f(d),{once:!0})});return l&&l.signal&&delete l.signal,Promise.race([h,n(u,l)])}return n(u,l)},Request:s}}var Fi=Fs({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),zb=Fi?Nu({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,ht=Fi?zb.fetch:window.fetch,rO=Fi?zb.Request:window.Request,ke=Fi?Ni:window.AbortController,iO=Fi?qr:window.AbortSignal;var zs=Ge(Fr(),1);var ft=()=>window.ManagedMediaSource||window.MediaSource,Us=()=>{var a,e;return!!(window.ManagedMediaSource&&((e=(a=window.ManagedSourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},Kb=()=>{var a,e;return!!(window.MediaSource&&window.MediaStreamTrack&&((e=(a=window.SourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},Jb=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;import{assertNever as Js,clientChecker as Ks}from"@vkontakte/videoplayer-shared";var Ue=document.createElement("video"),fk='video/mp4; codecs="avc1.42000a,mp4a.40.2"',mk='video/mp4; codecs="hev1.1.6.L93.B0"',ug='video/webm; codecs="vp09.00.10.08"',lg='video/webm; codecs="av01.0.00M.08"',bk='audio/mp4; codecs="mp4a.40.2"',gk='audio/webm; codecs="opus"',Xb,Zb,er={mms:Us(),mse:Kb(),hls:!!((Xb=Ue.canPlayType)!=null&&Xb.call(Ue,"application/x-mpegurl")||(Zb=Ue.canPlayType)!=null&&Zb.call(Ue,"vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},eg,tg,Te={mp4:!!((eg=Ue.canPlayType)!=null&&eg.call(Ue,"video/mp4")),webm:!!((tg=Ue.canPlayType)!=null&&tg.call(Ue,"video/webm")),cmaf:!0},Hs,rg,js,ig,Gs,ag,Ws,sg,Ys,ng,Qs,og,Ie={h264:!!((rg=(Hs=ft())==null?void 0:Hs.isTypeSupported)!=null&&rg.call(Hs,fk)),h265:!!((ig=(js=ft())==null?void 0:js.isTypeSupported)!=null&&ig.call(js,mk)),vp9:!!((ag=(Gs=ft())==null?void 0:Gs.isTypeSupported)!=null&&ag.call(Gs,ug)),av1:!!((sg=(Ws=ft())==null?void 0:Ws.isTypeSupported)!=null&&sg.call(Ws,lg)),aac:!!((ng=(Ys=ft())==null?void 0:Ys.isTypeSupported)!=null&&ng.call(Ys,bk)),opus:!!((og=(Qs=ft())==null?void 0:Qs.isTypeSupported)!=null&&og.call(Qs,gk))},Hr=(Ie.h264||Ie.h265)&&Ie.aac,tr,Sk=()=>w(void 0,null,function*(){if(!window.navigator.mediaCapabilities)return;let a={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=yield Promise.all([window.navigator.mediaCapabilities.decodingInfo(D(A({},a),{video:D(A({},a.video),{contentType:lg})})),window.navigator.mediaCapabilities.decodingInfo(D(A({},a),{video:D(A({},a.video),{contentType:ug})}))]);tr={DASH_WEBM_AV1:e,DASH_WEBM:t}});try{Sk()}catch(a){console.error(a)}var jr=er.hls&&Te.mp4,cg=()=>Object.keys(Ie).filter(a=>Ie[a]),dg=(a,e=!1,t=!1)=>{let r=er.mse||er.mms&&t;return a.filter(i=>{switch(i){case"DASH_SEP":return r&&Te.mp4&&Hr;case"DASH_WEBM":return r&&Te.webm&&Ie.vp9&&Ie.opus;case"DASH_WEBM_AV1":return r&&Te.webm&&Ie.av1&&Ie.opus;case"DASH_STREAMS":return r&&(Te.mp4&&Hr||Te.webm&&(Ie.vp9||Ie.av1)&&(Ie.opus||Ie.aac));case"DASH_LIVE":return er.mse&&Te.mp4&&Hr;case"DASH_LIVE_CMAF":return r&&Te.mp4&&Hr&&Te.cmaf;case"DASH_ONDEMAND":return r&&Te.mp4&&Hr;case"HLS":case"HLS_ONDEMAND":return jr||e&&er.mse&&Te.mp4&&Hr;case"HLS_LIVE":case"HLS_LIVE_CMAF":return jr;case"MPEG":return Te.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return er.webrtc&&er.ws&&Ie.h264&&(Te.mp4||Te.webm);default:return Js(i)}})},qs=a=>{let e="DASH_WEBM",t="DASH_WEBM_AV1";switch(a){case"vp9":return[e,t];case"av1":return[t,e];case"none":return[];case"smooth":return tr?tr[t].smooth?[t,e]:tr[e].smooth?[e,t]:[t,e]:[e,t];case"power_efficient":return tr?tr[t].powerEfficient?[t,e]:tr[e].powerEfficient?[e,t]:[t,e]:[e,t];default:Js(a)}return[e,t]},pg=({webmCodec:a,androidPreferredFormat:e,preferMultiStream:t})=>{let r=[...t?["DASH_STREAMS"]:[],...qs(a),"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]],i=[...t?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]];if(Ks.isAndroid)switch(e){case"mpeg":return["MPEG",...r,"HLS","HLS_ONDEMAND"];case"hls":return["HLS","HLS_ONDEMAND",...r,"MPEG"];case"dash":return[...r,"HLS","HLS_ONDEMAND","MPEG"];case"dash_any_mpeg":return[...i,"MPEG",...qs(a),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...qs(a),"MPEG",...i,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...qs(a),...i,"HLS","HLS_ONDEMAND"];default:Js(e)}return jr?[...r,"HLS","HLS_ONDEMAND","MPEG"]:[...r,"HLS","HLS_ONDEMAND","MPEG"]},hg=({androidPreferredFormat:a,preferCMAF:e,preferWebRTC:t})=>{let r=e?["DASH_LIVE_CMAF","DASH_LIVE"]:["DASH_LIVE","DASH_LIVE_CMAF"],i=e?["HLS_LIVE_CMAF","HLS_LIVE"]:["HLS_LIVE","HLS_LIVE_CMAF"],s=[...r,...i],n=[...i,...r],o,u=Ks.isMac&&Ks.isSafari;if(Ks.isAndroid)switch(a){case"dash":case"dash_any_mpeg":case"dash_any_webm":case"dash_sep":{o=s;break}case"hls":case"mpeg":{o=n;break}default:Js(a)}else jr&&!u?o=n:u?o=e?["DASH_LIVE_CMAF","HLS_LIVE_CMAF","HLS_LIVE","DASH_LIVE"]:["HLS_LIVE","DASH_LIVE","DASH_LIVE_CMAF","HLS_LIVE_CMAF"]:o=s;return t?["WEB_RTC_LIVE",...o]:[...o,"WEB_RTC_LIVE"]},Fu=a=>a?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],fg=a=>{if(a.size===0)return;if(a.size===1){let t=a.values().next();return(0,zs.default)(t.value.split("."),0)}for(let t of a){let r=(0,zs.default)(t.split("."),0);if(r==="opus"||r==="vp09"||r==="av01")return r}let e=a.values().next();return(0,zs.default)(e.value.split("."),0)};import{ErrorCategory as Ui}from"@vkontakte/videoplayer-shared";var mg=a=>{if(!a)return{id:"EmptyResponse",category:Ui.PARSER,message:"Empty response"};if(a.length<=2&&a.match(/^\d+$/))return{id:`UVError#${a}`,category:Ui.NETWORK,message:`UV Error ${a}`};let e=a.trimStart().substring(0,100).toLowerCase();if(e.startsWith("<!doctype")||e.startsWith("<html>")||e.startsWith("<body>")||e.startsWith("<head>"))return{id:"UnexpectedHTML",category:Ui.NETWORK,message:"Received unexpected HTML, possibly a ISP block"};if(e.startsWith("<?xml"))return new DOMParser().parseFromString(a,"text/xml").querySelector("parsererror")?{id:"InvalidXML",category:Ui.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:Ui.PARSER,message:"Response is valid XML, but parser failed"}};var Lt=(a,e,t=0)=>{for(let r=0;r<a.length;r++)if(a.start(r)*1e3-t<=e&&a.end(r)*1e3+t>e)return!0;return!1};import{abortable as dl,assertNonNullable as ur,clientChecker as LR,combine as an,ErrorCategory as Bt,filter as pl,filterChanged as gS,flattenObject as va,fromEvent as lr,getTraceSubscriptionMethod as MR,interval as hl,isNonNullable as SS,map as fl,merge as cr,now as CR,Subject as vS,Subscription as yS,tap as DR,throttle as BR,ValueSubject as oe}from"@vkontakte/videoplayer-shared";var Yr=Ge(Fr(),1);var vk=(a,e={})=>{let r=e.timeout||1,i=performance.now();return window.setTimeout(()=>{a({get didTimeout(){return e.timeout?!1:performance.now()-i-1>r},timeRemaining(){return Math.max(0,1+(performance.now()-i))}})},1)},yk=a=>window.clearTimeout(a),bg=a=>typeof a=="function"&&(a==null?void 0:a.toString().endsWith("{ [native code] }")),gg=!bg(window.requestIdleCallback)||!bg(window.cancelIdleCallback),Uu=gg?vk:window.requestIdleCallback,SO=gg?yk:window.cancelIdleCallback;var lS=Ge($s(),1);import{assertNever as Tk,ErrorCategory as Sg,clientChecker as qu,Subject as vg}from"@vkontakte/videoplayer-shared";var Ik=18,yg=!1;try{yg=qu.isSafari&&!!qu.macVersion&&qu.macVersion<=Ik}catch(a){console.error(a)}var Hu=class{constructor(e){this.bufferFull$=new vg;this.error$=new vg;this.queue=[];this.currentTask=null;this.destroyed=!1;this.completeTask=()=>{var e;try{if(this.currentTask){let t=(e=this.currentTask.signal)==null?void 0:e.aborted;this.currentTask.callback(!t),this.currentTask=null}this.queue.length&&this.pull()}catch(t){this.error$.next({id:"BufferTaskQueueUnknown",category:Sg.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:t})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}append(e,t){return w(this,null,function*(){return t&&t.aborted?!1:new Promise(r=>{let i={operation:"append",data:e,signal:t,callback:r};this.queue.push(i),this.pull()})})}remove(e,t,r){return w(this,null,function*(){return r&&r.aborted?!1:new Promise(i=>{let s={operation:"remove",from:e,to:t,signal:r,callback:i};this.queue.unshift(s),this.pull()})})}abort(e){return w(this,null,function*(){return new Promise(t=>{let r;yg&&e?r={operation:"safariAbort",init:e,callback:t}:r={operation:"abort",callback:t};for(let{callback:i}of this.queue)i(!1);r&&(this.queue=[r]),this.pull()})})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){var i;if(this.buffer.updating||this.currentTask||this.destroyed)return;let e=this.queue.shift();if(!e)return;if((i=e.signal)!=null&&i.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(s){s instanceof DOMException&&s.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):s instanceof DOMException&&s.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:Sg.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:s}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){let{operation:t}=e;switch(t){case"append":this.buffer.appendBuffer(e.data);break;case"remove":this.buffer.remove(e.from/1e3,e.to/1e3);break;case"abort":this.buffer.abort();break;case"safariAbort":{this.buffer.abort(),this.buffer.appendBuffer(e.init);break}default:Tk(t)}}},Tg=Hu;var ju=a=>{let e=0;for(let t=0;t<a.length;t++)e+=a.end(t)-a.start(t);return e*1e3};import{abortable as sr,assertNonNullable as ae,ErrorCategory as Ct,fromEvent as nl,getExponentialDelay as ol,isNonNullable as da,isNullable as $e,now as Xs,once as TR,Subject as IR,Subscription as ER,ValueSubject as pa}from"@vkontakte/videoplayer-shared";var j=class{constructor(e,t){this.cursor=0;this.source=e,this.boxParser=t,this.children=[];let r=this.readUint32();this.type=this.readString(4),this.size32=r<=e.buffer.byteLength-e.byteOffset?r:NaN;let i=this.size32?this.size32-8:void 0,s=e.byteOffset+this.cursor;this.size64=0,this.usertype=0,this.content=new DataView(e.buffer,s,i),this.children=this.parseChildrenBoxes()}get id(){return this.type}get size(){return this.size32}parseChildrenBoxes(){return[]}scanForBoxes(e){return this.boxParser.parse(e)}readString(e,t="ascii"){let i=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,i}readUint8(){let e=this.source.getUint8(this.cursor);return this.cursor+=1,e}readUint16(){let e=this.source.getUint16(this.cursor);return this.cursor+=2,e}readUint32(){let e=this.source.getUint32(this.cursor);return this.cursor+=4,e}readUint64(){let e=this.source.getBigInt64(this.cursor);return this.cursor+=8,e}};var Gr=class extends j{};var qi=class extends j{};var Hi=class extends j{constructor(e,t){super(e,t),this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let r=this.size-this.cursor;for(;r;){let i=this.readString(4);this.compatibleBrands.push(i),r-=4}}};var ji=class extends j{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var K=class extends j{constructor(e,t){super(e,t);let r=this.readUint32();this.version=r>>>24,this.flags=r&16777215}};var Gi=class extends K{constructor(e,t){super(e,t),this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.timescale=this.readUint32(),this.duration=this.readUint32(),this.rate=this.readUint32(),this.volume=this.readUint16()}};var Wi=class extends j{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Yi=class extends j{constructor(e,t){super(e,t),this.data=this.content}};var rr=class extends K{get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e,t){super(e,t),this.segments=[],this.referenceId=this.readUint32(),this.timescale=this.readUint32(),this.earliestPresentationTime32=this.readUint32(),this.firstOffset32=this.readUint32(),this.earliestPresentationTime64=0,this.firstOffset64=0,this.referenceCount=this.readUint32()&65535;for(let r=0;r<this.referenceCount;r++){let i=this.readUint32(),s=i>>>31,n=i<<1>>>1,o=this.readUint32();i=this.readUint32();let u=i>>>28,l=i<<3>>>3;this.segments.push({referenceType:s,referencedSize:n,subsegmentDuration:o,SAPType:u,SAPDeltaTime:l})}}};var Qi=class extends j{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var zi=class extends j{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Ki=class extends K{constructor(e,t){switch(super(e,t),this.readUint8()){case 0:this.stereoMode=0;break;case 1:this.stereoMode=1;break;case 2:this.stereoMode=2;break;case 3:this.stereoMode=3;break;case 4:this.stereoMode=4;break}this.cursor+=1}};var Ji=class extends K{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var Xi=class extends K{constructor(e,t){super(e,t),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}};var Zi=class extends j{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ea=class extends K{constructor(e,t){super(e,t),this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.trackId=this.readUint32(),this.cursor+=4,this.duration=this.readUint32(),this.cursor+=8,this.layer=this.readUint16(),this.alternateGroup=this.readUint16(),this.cursor+=2,this.cursor+=2,this.matrix=[[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()]],this.width=this.readUint32(),this.height=this.readUint32()}};var ta=class extends j{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ra=class extends j{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ia=class extends K{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var aa=class extends j{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var sa=class extends K{constructor(e,t){super(e,t),this.trackId=this.readUint32(),this.flags&1&&(this.baseDataOffset=this.readUint64()),this.flags&2&&(this.sampleDescriptionIndex=this.readUint32()),this.flags&8&&(this.defaultSampleDuration=this.readUint32()),this.flags&16&&(this.defaultSampleSize=this.readUint32()),this.flags&32&&(this.defaultSampleFlags=this.readUint32())}};var na=class extends K{constructor(t,r){super(t,r);this.baseMediaDecodeTime32=0;this.baseMediaDecodeTime64=BigInt(0);this.version===1?this.baseMediaDecodeTime64=this.readUint64():this.baseMediaDecodeTime32=this.readUint32()}get baseMediaDecodeTime(){return this.version===1?this.baseMediaDecodeTime64:this.baseMediaDecodeTime32}};var oa=class extends K{constructor(t,r){super(t,r);this.sampleDuration=[];this.sampleSize=[];this.sampleFlags=[];this.sampleCompositionTimeOffset=[];this.optionalFields=0;this.sampleCount=this.readUint32(),this.flags&1&&(this.dataOffset=this.readUint32()),this.flags&4&&(this.firstSampleFlags=this.readUint32());for(let i=0;i<this.sampleCount;i++)this.flags&256&&this.sampleDuration.push(this.readUint32()),this.flags&512&&this.sampleSize.push(this.readUint32()),this.flags&1024&&this.sampleFlags.push(this.readUint32()),this.flags&2048&&this.sampleCompositionTimeOffset.push(this.readUint32())}};var xk={ftyp:Hi,moov:ji,mvhd:Gi,moof:Wi,mdat:Yi,sidx:rr,trak:Qi,mdia:Zi,mfhd:ia,tkhd:ea,traf:aa,tfhd:sa,tfdt:na,trun:oa,minf:ta,sv3d:zi,st3d:Ki,prhd:Ji,proj:ra,equi:Xi,uuid:qi,unknown:Gr},Mt=class a{constructor(e={}){this.options=A({offset:0},e)}parse(e){let t=[],r=this.options.offset;for(;r<e.byteLength;)try{let s=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+r+4,4)),n=this.createBox(s,new DataView(e.buffer,e.byteOffset+r));if(!n.size)break;t.push(n),r+=n.size}catch(i){break}return t}createBox(e,t){let r=xk[e];return r?new r(t,new a):new Gr(t,new a)}};var ir=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{var r,i,s;(s=(r=this.index)[i=t.type])!=null||(r[i]=[]),this.index[t.type].push(t),t.children.length>0&&this.indexBoxLevel(t.children)})}find(e){return this.index[e]&&this.index[e][0]?this.index[e][0]:null}findAll(e){return this.index[e]||[]}};var Ak=new TextDecoder("ascii"),wk=a=>Ak.decode(new DataView(a.buffer,a.byteOffset+4,4))==="ftyp",kk=a=>{let e=new rr(a,new Mt),t=e.earliestPresentationTime/e.timescale*1e3,r=a.byteOffset+a.byteLength+e.firstOffset;return e.segments.map(s=>{if(s.referenceType!==0)throw new Error("Unsupported multilevel sidx");let n=s.subsegmentDuration/e.timescale*1e3,o={status:"none",time:{from:t,to:t+n},byte:{from:r,to:r+s.referencedSize-1}};return t+=n,r+=s.referencedSize,o})},Rk=(a,e)=>{let r=new Mt().parse(a),i=new ir(r),s=i.findAll("moof"),n=e?i.findAll("uuid"):i.findAll("mdat");if(!(n.length&&s.length))return null;let o=s[0],u=n[n.length-1],l=o.source.byteOffset,d=u.source.byteOffset-o.source.byteOffset+u.size;return new DataView(a.buffer,l,d)},$k=a=>{var i;let t=new Mt().parse(a);return(i=new ir(t).find("sidx"))==null?void 0:i.timescale},Lk=(a,e)=>{let r=new Mt().parse(a),s=new ir(r).findAll("traf"),n=s[s.length-1].children.find(d=>d.type==="tfhd"),o=s[s.length-1].children.find(d=>d.type==="tfdt"),u=s[s.length-1].children.find(d=>d.type==="trun"),l=0;return u.sampleDuration.length?l=u.sampleDuration.reduce((d,h)=>d+h,0):l=n.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+l)/e*1e3},Mk=a=>{let e={is3dVideo:!1,stereoMode:0,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}},r=new Mt().parse(a),i=new ir(r);if(i.find("sv3d")){e.is3dVideo=!0;let n=i.find("st3d");n&&(e.stereoMode=n.stereoMode);let o=i.find("prhd");o&&(e.projectionData.pose.yaw=o.poseYawDegrees,e.projectionData.pose.pitch=o.posePitchDegrees,e.projectionData.pose.roll=o.poseRollDegrees);let u=i.find("equi");u&&(e.projectionData.bounds.top=u.projectionBoundsTop,e.projectionData.bounds.right=u.projectionBoundsRight,e.projectionData.bounds.bottom=u.projectionBoundsBottom,e.projectionData.bounds.left=u.projectionBoundsLeft)}return e},Ig={validateData:wk,parseInit:Mk,getIndexRange:()=>{},parseSegments:kk,parseFeedableSegmentChunk:Rk,getChunkEndTime:Lk,getTimescaleFromIndex:$k};import{assertNonNullable as Wu,isNonNullable as Ag,isNullable as Dk}from"@vkontakte/videoplayer-shared";import{assertNever as Ck}from"@vkontakte/videoplayer-shared";var Eg={440786851:{type:"master"},17030:{type:"uint"},17143:{type:"uint"},17138:{type:"uint"},17139:{type:"uint"},17026:{type:"string"},17031:{type:"uint"},17029:{type:"uint"},236:{type:"binary"},408125543:{type:"master"},290298740:{type:"master"},19899:{type:"master"},21419:{type:"binary"},21420:{type:"uint"},357149030:{type:"master"},2807729:{type:"uint"},17545:{type:"float"},374648427:{type:"master"},174:{type:"master"},224:{type:"master"},30320:{type:"master"},30321:{type:"uint"},30322:{type:"master"},272869232:{type:"master"},524531317:{type:"master"},231:{type:"uint"},22612:{type:"master"},22743:{type:"uint"},167:{type:"uint"},171:{type:"uint"},163:{type:"binary"},160:{type:"master"},175:{type:"binary"},423732329:{type:"master"},307544935:{type:"master"},475249515:{type:"master"},187:{type:"master"},179:{type:"uint"},183:{type:"master"},247:{type:"uint"},241:{type:"uint"},240:{type:"uint"},178:{type:"uint"},21368:{type:"uint"},234:{type:"uint"},219:{type:"master"},150:{type:"uint"}},xg=a=>{let e=a.getUint8(0),t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);let r=ua(a,t),i=r in Eg,s=i?Eg[r].type:"binary",n=a.getUint8(t),o=0;n&128?o=1:n&64?o=2:n&32?o=3:n&16?o=4:n&8?o=5:n&4?o=6:n&2?o=7:n&1&&(o=8);let u=new DataView(a.buffer,a.byteOffset+t+1,o-1),l=n&255>>o,c=ua(u),d=l*et(2,(o-1)*8)+c,h=t+o,p;return h+d>a.byteLength?p=new DataView(a.buffer,a.byteOffset+h):p=new DataView(a.buffer,a.byteOffset+h,d),{tag:i?r:"0x"+r.toString(16).toUpperCase(),type:s,tagHeaderSize:h,tagSize:h+d,value:p,valueSize:d}},ua=(a,e=a.byteLength)=>{switch(e){case 1:return a.getUint8(0);case 2:return a.getUint16(0);case 3:return a.getUint8(0)*et(2,16)+a.getUint16(1);case 4:return a.getUint32(0);case 5:return a.getUint8(0)*et(2,32)+a.getUint32(1);case 6:return a.getUint16(0)*et(2,32)+a.getUint32(2);case 7:{let t=a.getUint8(0)*281474976710656+a.getUint16(1)*4294967296+a.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},Ke=(a,e)=>{switch(e){case"int":return a.getInt8(0);case"uint":return ua(a);case"float":return a.byteLength===4?a.getFloat32(0):a.getFloat64(0);case"string":return new TextDecoder("ascii").decode(a);case"utf8":return new TextDecoder("utf-8").decode(a);case"date":return new Date(Date.UTC(2001,0)+a.getInt8(0)).getTime();case"master":return a;case"binary":return a;default:Ck(e)}},ar=(a,e)=>{let t=0;for(;t<a.byteLength;){let r=new DataView(a.buffer,a.byteOffset+t),i=xg(r);if(!e(i))return;i.type==="master"&&ar(i.value,e),t=i.value.byteOffset-a.byteOffset+i.valueSize}},Pg=a=>{if(a.getUint32(0)!==440786851)return!1;let e,t,r,i=xg(a);return ar(i.value,({tag:s,type:n,value:o})=>(s===17143?e=Ke(o,n):s===17026?t=Ke(o,n):s===17029&&(r=Ke(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(r===void 0||r<=2)};var wg=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],Bk=[231,22612,22743,167,171,163,160,175],Ok=a=>{let e,t,r,i,s=!1,n=!1,o=!1,u,l,c=!1,d=0;return ar(a,({tag:h,type:p,value:f,valueSize:b})=>{if(h===21419){let g=Ke(f,p);l=ua(g)}else h!==21420&&(l=void 0);return h===408125543?(e=f.byteOffset,t=f.byteOffset+b):h===357149030?s=!0:h===290298740?n=!0:h===2807729?r=Ke(f,p):h===17545?i=Ke(f,p):h===21420&&l===475249515?u=Ke(f,p):h===374648427?ar(f,({tag:g,type:T,value:y})=>g===30321?(c=Ke(y,T)===1,!1):!0):s&&n&&wg.includes(h)&&(o=!0),!o}),Wu(e,"Failed to parse webm Segment start"),Wu(t,"Failed to parse webm Segment end"),Wu(i,"Failed to parse webm Segment duration"),r=r!=null?r:1e6,{segmentStart:Math.round(e/1e9*r*1e3),segmentEnd:Math.round(t/1e9*r*1e3),timeScale:r,segmentDuration:Math.round(i/1e9*r*1e3),cuesSeekPosition:u,is3dVideo:c,stereoMode:d,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},Vk=a=>{if(Dk(a.cuesSeekPosition))return;let e=a.segmentStart+a.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},_k=(a,e)=>{let t=!1,r=!1,i=o=>Ag(o.time)&&Ag(o.position),s=[],n;return ar(a,({tag:o,type:u,value:l})=>{switch(o){case 475249515:t=!0;break;case 187:n&&i(n)&&s.push(n),n={};break;case 179:n&&(n.time=Ke(l,u));break;case 183:break;case 241:n&&(n.position=Ke(l,u));break;default:t&&wg.includes(o)&&(r=!0)}return!(t&&r)}),n&&i(n)&&s.push(n),s.map((o,u)=>{let{time:l,position:c}=o,d=s[u+1];return{status:"none",time:{from:l,to:d?d.time:e.segmentDuration},byte:{from:e.segmentStart+c,to:d?e.segmentStart+d.position-1:e.segmentEnd-1}}})},Nk=a=>{let e=0,t=!1;try{ar(a,r=>r.tag===524531317?r.tagSize<=a.byteLength?(e=r.tagSize,!1):(e+=r.tagHeaderSize,!0):Bk.includes(r.tag)?(e+r.tagSize<=a.byteLength&&(e+=r.tagSize,t||(t=[163,160,175].includes(r.tag))),!0):!1)}catch(r){}return e>0&&e<=a.byteLength&&t?new DataView(a.buffer,a.byteOffset,e):null},kg={validateData:Pg,parseInit:Ok,getIndexRange:Vk,parseSegments:_k,parseFeedableSegmentChunk:Nk};var la=a=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(a);if(e){let[,t,r]=e;if(t==="audio"||t==="video")switch(r){case"webm":return kg;case"mp4":return Ig}}throw new ReferenceError(`Unsupported mime type ${a}`)},Rg=a=>"getChunkEndTime"in a;var Zu=Ge(Jg(),1),iS=Ge(Fr(),1);var Xu=a=>{let e=a.split("."),[t,...r]=e;if(!t)return!1;switch(t){case"av01":{let[i,s,n]=r;return!!(n&&parseInt(n,10)>8)}case"vp09":{let[i,s,n]=r;return!!(i&&parseInt(i,10)>=2&&n&&parseInt(n,10)>8)}case"avc1":{let i=r[0];if(!i||i.length!==6)return!1;let[s,n]=i.toUpperCase(),o=s+n;return["6E","7A","F4"].includes(o)}}return!1};import{isNonNullable as eS,isNullable as tS}from"@vkontakte/videoplayer-shared";var Xg=a=>{if(a.includes("/")){let e=a.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(a)};var Zg=a=>{var e;try{let t=vR(),r=a.match(t),{groups:i}=r!=null?r:{};if(i){let s={};if(i.extensions){let u=i.extensions.toLowerCase().match(/(?:[0-9a-wy-z](?:-[a-z0-9]{2,8})+)/g);Array.from(u||[]).forEach(l=>{s[l[0]]=l.slice(2)})}let n=(e=i.variants)==null?void 0:e.split(/-/).filter(u=>u!==""),o={extlang:i.extlang,langtag:i.langtag,language:i.language,privateuse:i.privateuse||i.privateuse2,region:i.region,script:i.script,extensions:s,variants:n};return Object.keys(o).forEach(u=>{let l=o[u];(typeof l=="undefined"||l==="")&&delete o[u]}),o}return null}catch(t){return null}};function vR(){let a="(?<extlang>(?:[a-z]{3}(?:-[a-z]{3}){0,2}))",e="x(?:-[a-z0-9]{1,8})+",c=`^(?:(?<langtag>${`
59
59
  (?<language>${`(?:[a-z]{2,3}(?:-${a})?|[a-z]{4}|[a-z]{5,8})`})
60
60
  (-(?<script>[a-z]{4}))?
61
61
  (-(?<region>(?:[a-z]{2}|[0-9]{3})))?
62
62
  (?<variants>(?:-(?:[a-z0-9]{5,8}|[0-9][a-z0-9]{3}))*)
63
63
  (?<extensions>(?:-[0-9a-wy-z](?:-[a-z0-9]{2,8})+)*)
64
64
  (?:-(?<privateuse>(?:${e})))?
65
- `})|(?<privateuse2>${e}))$`.replace(/[\s\t\n]/g,"");return new RegExp(c,"i")}var iS=a=>{if(!a.startsWith("P"))return;let e=(n,o)=>{let u=n?parseFloat(n.replace(",",".")):NaN;return(isNaN(u)?0:u)*o},r=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(a),i=(r==null?void 0:r[1])==="-"?-1:1,s={days:e(r==null?void 0:r[5],i),hours:e(r==null?void 0:r[6],i),minutes:e(r==null?void 0:r[7],i),seconds:e(r==null?void 0:r[8],i)};return s.days*24*60*60*1e3+s.hours*60*60*1e3+s.minutes*60*1e3+s.seconds*1e3},mt=(a,e)=>{let t=a;t=(0,el.default)(t,"$$","$");let r={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[i,s]of Object.entries(r)){let n=new RegExp(`\\$${i}(?:%0(\\d+)d)?\\$`,"g");t=(0,el.default)(t,n,(o,u)=>rS(s)?o:rS(u)?s:s.padStart(parseInt(u,10),"0"))}return t},sS=(a,e)=>{var E,k,B,G,V,M,_,w,U,L,W,v,$,Q,N,oe,Ue,dr,Xr,H,he,xe,$e,gt,pr,St,Nt,hr,Zr,Cl,Dl,Bl,Ol,Vl,_l,Nl,Fl,Ul,ql,Hl,jl,Gl,Wl,Yl,Ql,zl,Kl,Jl,Xl,Zl,ec,tc,rc,ic,ac,sc,nc,oc,uc,lc;let r=new DOMParser().parseFromString(a,"application/xml"),i={video:[],audio:[],text:[]},s=r.children[0],n=s.getElementsByTagName("Period")[0],o=Array.from(s.querySelectorAll("MPD > BaseURL").values()).map(ae=>{var Ma,vt;return(vt=(Ma=ae.textContent)==null?void 0:Ma.trim())!=null?vt:""}),u=(E=(0,aS.default)(o,0))!=null?E:"",l=n.children,c=s.getAttribute("type")==="dynamic",d=s.getAttribute("availabilityStartTime"),h=d?new Date(d).getTime():void 0,p,f=s.getAttribute("mediaPresentationDuration"),b=n.getAttribute("duration"),g=s.getElementsByTagName("vk:Attrs")[0],S=g==null?void 0:g.getElementsByTagName("vk:XPlaybackDuration")[0].textContent;if(f)p=iS(f);else if(b){let ae=iS(b);tS(ae)&&(p=ae)}else S&&(p=parseInt(S,10));let y=0,T=(B=(k=s.getAttribute("profiles"))==null?void 0:k.split(","))!=null?B:[];for(let ae of l){let Ma=(G=ae.getAttribute("id"))!=null?G:"id"+(y++).toString(10),vt=(V=ae.getAttribute("mimeType"))!=null?V:"",xn=(M=ae.getAttribute("codecs"))!=null?M:"",Pn=(_=ae.getAttribute("contentType"))!=null?_:vt==null?void 0:vt.split("/")[0],gv=(U=(w=ae.getAttribute("profiles"))==null?void 0:w.split(","))!=null?U:[],cc=(W=eS((L=ae.getAttribute("lang"))!=null?L:""))!=null?W:{},Sv=(Q=($=(v=ae.querySelector("Label"))==null?void 0:v.textContent)==null?void 0:$.trim())!=null?Q:void 0,vv=ae.querySelectorAll("Representation"),yv=ae.querySelector("SegmentTemplate"),Tv=(oe=(N=ae.querySelector("Role"))==null?void 0:N.getAttribute("value"))!=null?oe:void 0,ei=Pn,ee={id:Ma,language:cc.language,isDefault:Tv==="main",label:Sv,codecs:xn,hdr:ei==="video"&&Zu(xn),mime:vt,representations:[]};for(let z of vv){let Iv=(Ue=z.getAttribute("lang"))!=null?Ue:void 0,Ev=(dr=z.getAttribute("label"))!=null?dr:void 0,xv=(he=(H=(Xr=z.querySelector("BaseURL"))==null?void 0:Xr.textContent)==null?void 0:H.trim())!=null?he:"",Ca=new URL(xv||u,e).toString(),fr=(xe=z.getAttribute("mimeType"))!=null?xe:vt,Da=(gt=($e=z.getAttribute("codecs"))!=null?$e:xn)!=null?gt:"",Ba;if(Pn==="text"){let yt=z.getAttribute("id")||"",Oa=((pr=cc.privateuse)==null?void 0:pr.includes("x-auto"))||yt.includes("_auto"),Ft=z.querySelector("SegmentTemplate");if(Ft){let ti={representationId:(St=z.getAttribute("id"))!=null?St:void 0,bandwidth:(Nt=z.getAttribute("bandwidth"))!=null?Nt:void 0},Va=parseInt((hr=z.getAttribute("bandwidth"))!=null?hr:"",10)/1e3,_a=(Cl=parseInt((Zr=Ft.getAttribute("startNumber"))!=null?Zr:"",10))!=null?Cl:1,mr=parseInt((Dl=Ft.getAttribute("timescale"))!=null?Dl:"",10),An=(Bl=Ft.querySelectorAll("SegmentTimeline S"))!=null?Bl:[],br=Ft.getAttribute("media");if(!br)continue;let Na=[],Fa=0,Ua="",gr=0,ri=_a,ue=0;for(let qe of An){let Ut=parseInt((Ol=qe.getAttribute("d"))!=null?Ol:"",10),Le=parseInt((Vl=qe.getAttribute("r"))!=null?Vl:"",10)||0,Tt=parseInt((_l=qe.getAttribute("t"))!=null?_l:"",10);ue=Number.isFinite(Tt)?Tt:ue;let qt=Ut/mr*1e3,It=ue/mr*1e3;for(let Xe=0;Xe<Le+1;Xe++){let Et=mt(br,D(A({},ti),{segmentNumber:ri.toString(10),segmentTime:(ue+Xe*Ut).toString(10)})),Sr=(It!=null?It:0)+Xe*qt,ai=Sr+qt;ri++,Na.push({time:{from:Sr,to:ai},url:Et})}ue+=(Le+1)*Ut,Fa+=(Le+1)*qt}gr=ue/mr*1e3,Ua=mt(br,D(A({},ti),{segmentNumber:ri.toString(10),segmentTime:ue.toString(10)}));let ii={time:{from:gr,to:1/0},url:Ua},nt={type:"template",baseUrl:Ca,segmentTemplateUrl:br,initUrl:"",totalSegmentsDurationMs:Fa,segments:Na,nextSegmentBeyondManifest:ii,timescale:mr};Ba={id:yt,kind:"text",segmentReference:nt,profiles:[],duration:p,bitrate:Va,mime:"",codecs:"",width:0,height:0,isAuto:Oa}}else Ba={id:yt,isAuto:Oa,kind:"text",url:Ca}}else{let yt=(Fl=(Nl=z.getAttribute("contentType"))!=null?Nl:fr==null?void 0:fr.split("/")[0])!=null?Fl:Pn,Oa=(ql=(Ul=ae.getAttribute("profiles"))==null?void 0:Ul.split(","))!=null?ql:[],Ft=parseInt((Hl=z.getAttribute("width"))!=null?Hl:"",10),ti=parseInt((jl=z.getAttribute("height"))!=null?jl:"",10),Va=parseInt((Gl=z.getAttribute("bandwidth"))!=null?Gl:"",10)/1e3,_a=(Wl=z.getAttribute("frameRate"))!=null?Wl:"",mr=(Yl=z.getAttribute("quality"))!=null?Yl:void 0,An=_a?Zg(_a):void 0,br=(Ql=z.getAttribute("id"))!=null?Ql:"id"+(y++).toString(10),Na=yt==="video"?`${ti}p`:yt==="audio"?`${Va}Kbps`:Da,Fa=`${br}@${Na}`,Ua=[...T,...gv,...Oa],gr,ri=z.querySelector("SegmentBase"),ue=(zl=z.querySelector("SegmentTemplate"))!=null?zl:yv;if(ri){let nt=(Jl=(Kl=z.querySelector("SegmentBase Initialization"))==null?void 0:Kl.getAttribute("range"))!=null?Jl:"",[qe,Ut]=nt.split("-").map(Et=>parseInt(Et,10)),Le={from:qe,to:Ut},Tt=(Xl=z.querySelector("SegmentBase"))==null?void 0:Xl.getAttribute("indexRange"),[qt,It]=Tt?Tt.split("-").map(Et=>parseInt(Et,10)):[],Xe=Tt?{from:qt,to:It}:void 0;gr={type:"byteRange",url:Ca,initRange:Le,indexRange:Xe}}else if(ue){let nt={representationId:(Zl=z.getAttribute("id"))!=null?Zl:void 0,bandwidth:(ec=z.getAttribute("bandwidth"))!=null?ec:void 0},qe=parseInt((tc=ue.getAttribute("timescale"))!=null?tc:"",10),Ut=(rc=ue.getAttribute("initialization"))!=null?rc:"",Le=ue.getAttribute("media"),Tt=(ac=parseInt((ic=ue.getAttribute("startNumber"))!=null?ic:"",10))!=null?ac:1,qt=mt(Ut,nt);if(!Le)throw new ReferenceError("No media attribute in SegmentTemplate");let It=(sc=ue.querySelectorAll("SegmentTimeline S"))!=null?sc:[],Xe=[],Et=0,Sr="",ai=0;if(It.length){let qa=Tt,He=0;for(let vr of It){let Ze=parseInt((nc=vr.getAttribute("d"))!=null?nc:"",10),Ht=parseInt((oc=vr.getAttribute("r"))!=null?oc:"",10)||0,Ha=parseInt((uc=vr.getAttribute("t"))!=null?uc:"",10);He=Number.isFinite(Ha)?Ha:He;let wn=Ze/qe*1e3,kn=He/qe*1e3;for(let ja=0;ja<Ht+1;ja++){let Av=mt(Le,D(A({},nt),{segmentNumber:qa.toString(10),segmentTime:(He+ja*Ze).toString(10)})),dc=(kn!=null?kn:0)+ja*wn,wv=dc+wn;qa++,Xe.push({time:{from:dc,to:wv},url:Av})}He+=(Ht+1)*Ze,Et+=(Ht+1)*wn}ai=He/qe*1e3,Sr=mt(Le,D(A({},nt),{segmentNumber:qa.toString(10),segmentTime:He.toString(10)}))}else if(tS(p)){let He=parseInt((lc=ue.getAttribute("duration"))!=null?lc:"",10)/qe*1e3,vr=Math.ceil(p/He),Ze=0;for(let Ht=1;Ht<vr;Ht++){let Ha=mt(Le,D(A({},nt),{segmentNumber:Ht.toString(10),segmentTime:Ze.toString(10)}));Xe.push({time:{from:Ze,to:Ze+He},url:Ha}),Ze+=He}ai=Ze,Sr=mt(Le,D(A({},nt),{segmentNumber:vr.toString(10),segmentTime:Ze.toString(10)}))}let Pv={time:{from:ai,to:1/0},url:Sr};gr={type:"template",baseUrl:Ca,segmentTemplateUrl:Le,initUrl:qt,totalSegmentsDurationMs:Et,segments:Xe,nextSegmentBeyondManifest:Pv,timescale:qe}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!yt||!fr)continue;let ii={video:"video",audio:"audio",text:"text"}[yt];if(!ii)continue;ei||(ei=ii),Ba={id:Fa,kind:ii,segmentReference:gr,profiles:Ua,duration:p,bitrate:Va,mime:fr,codecs:Da,width:Ft,height:ti,fps:An,quality:mr}}ee.language||(ee.language=Iv),ee.label||(ee.label=Ev),ee.mime||(ee.mime=fr),ee.codecs||(ee.codecs=Da),ee.hdr||(ee.hdr=ei==="video"&&Zu(Da)),ee.representations.push(Ba)}ei&&i[ei].push(ee)}return{dynamic:c,liveAvailabilityStartTime:h,duration:p,streams:i,baseUrls:o}};var il=je(Nr(),1);import{videoSizeToQuality as vR}from"@vkontakte/videoplayer-shared";var nS=({id:a,width:e,height:t,bitrate:r,fps:i,quality:s})=>{var o;let n=(o=s?Rt(s):void 0)!=null?o:vR({width:e,height:t});return n&&{id:a,quality:n,bitrate:r,size:{width:e,height:t},fps:i}},oS=({id:a,bitrate:e})=>({id:a,bitrate:e}),uS=({language:a,label:e},{id:t,url:r,isAuto:i})=>({id:t,url:r,isAuto:i,type:"internal",language:a,label:e}),lS=({language:a,label:e,id:t,url:r,isAuto:i})=>({id:t,url:r,isAuto:i,type:"internal",language:a,label:e}),al=({id:a,language:e,label:t,codecs:r,isDefault:i})=>({id:a,language:e,label:t,codec:(0,il.default)(r.split("."),0),isDefault:i}),sl=({id:a,language:e,label:t,hdr:r,codecs:i})=>({id:a,language:e,hdr:r,label:t,codec:(0,il.default)(i.split("."),0)}),nl=a=>"url"in a,ke=a=>a.type==="template",ca=a=>a instanceof DOMException&&(a.name==="AbortError"||a.code===20);var pa=class{constructor(e,t,r,{fetcher:i,tuning:s,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentSegmentLength$=new da(0);this.onLastSegment$=new da(!1);this.fullyBuffered$=new da(!1);this.playingRepresentation$=new da(void 0);this.playingRepresentationInit$=new da(void 0);this.error$=new TR;this.gaps=[];this.subscription=new IR;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new ze;this.switchAbortController=new ze;this.destroyAbortController=new ze;this.bufferLimit=1/0;this.failedDownloads=0;this.baseUrls=[];this.baseUrlsIndex=0;this.isLive=!1;this.liveUpdateSegmentIndex=0;this.liveInitialAdditionalOffset=0;this.isSeekingLive=!1;this.index=0;this.lastDataObtainedTimestampMs=0;this.loadByteRangeSegmentsTimeoutId=0;this.startWith=ar(this.destroyAbortController.signal,function(e){return Z(this,null,function*(){let t=this.representations.get(e);de(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new Eg(this.sourceBuffer),this.subscription.add(ol(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let o,u=this.mediaSource.readyState;u!=="open"&&(o={id:`SegmentEjection_source_${u}`,category:Mt.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o!=null||(o={id:"SegmentEjection",category:Mt.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),this.error$.next(o)})),this.subscription.add(ol(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:Mt.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o)return;let u=Math.min(this.bufferLimit,Gu(this.sourceBuffer.buffered)*.8);this.bufferLimit=u;let l=at(this.sourceBuffer.buffered,o),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(o,n*2,l<c)})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(n=>this.error$.next(n))),yield this.loadInit(t,"high",!0);let r=this.initData.get(t.id),i=this.segments.get(t.id),s=this.parsedInitData.get(t.id);de(r,"No init buffer for starting representation"),de(i,"No segments for starting representation"),r instanceof ArrayBuffer&&(this.searchGaps(i,t),yield this.sourceBufferTaskQueue.append(r,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(s))})}.bind(this));this.switchToOld=ar(this.destroyAbortController.signal,function(e,t=!1){return Z(this,null,function*(){if(e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let r=this.representations.get(e);de(r,`No such representation ${e}`);let i=this.segments.get(e),s=this.initData.get(e);if(Fe(s)||Fe(i)?yield this.loadInit(r,"high",!1):s instanceof Promise&&(yield s),i=this.segments.get(e),de(i,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer))if(this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer(),this.maintain();else{let n=this.getCurrentPosition();Js(n)&&(this.isLive||(this.bufferLimit=1/0,yield new Ln(this.pruneBuffer(n,1/0,!0))),this.maintain(n)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}})}.bind(this));this.seekLive=ar(this.destroyAbortController.signal,function(e){return Z(this,null,function*(){var u,l;let t=(u=e==null?void 0:e.flatMap(c=>c.representations))!=null?u:[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let c of this.representations.keys()){let d=t.find(f=>f.id===c);d&&this.representations.set(c,d);let h=this.representations.get(c);if(!h||!ke(h.segmentReference))return;let p=this.getActualLiveStartingSegments(h.segmentReference);this.segments.set(h.id,p)}let r=(l=this.switchingToRepresentationId)!=null?l:this.downloadingRepresentationId,i=this.representations.get(r);de(i);let s=this.segments.get(r);de(s,"No segments for starting representation");let n=this.initData.get(r);if(de(n,"No init buffer for starting representation"),!(n instanceof ArrayBuffer))return;let o=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,this.abort(),o&&(yield this.sourceBufferTaskQueue.remove(o.from*1e3,o.to*1e3,this.destroyAbortController.signal)),this.searchGaps(s,i),yield this.sourceBufferTaskQueue.append(n,this.destroyAbortController.signal),this.isSeekingLive=!1})}.bind(this));var c;this.fetcher=i,this.tuning=s,this.compatibilityMode=u,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=o,this.isLive=!!(l!=null&&l.dynamic),this.baseUrls=(c=l==null?void 0:l.baseUrls)!=null?c:[],this.resetAccumulateBufferAfterStall(),this.startAccumulateBuffer(),this.initData=new Map(r.map(d=>[d.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(r.map(d=>[d.id,d])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}switchTo(e,t=!1){return this.tuning.useNewSwitchTo?this.switchToNew(e,t):this.switchToOld(e,t)}switchToNew(e,t=!1){e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new ze,ar(this.switchAbortController.signal,function(r,i=!1){return Z(this,null,function*(){this.switchingToRepresentationId=r;let s=this.representations.get(r);de(s,`No such representation ${r}`);let n=this.segments.get(r),o=this.initData.get(r);if(Fe(o)||Fe(n)?yield this.loadInit(s,"high",!1):o instanceof Promise&&(yield o),n=this.segments.get(r),de(n,"No segments for starting representation"),o=this.initData.get(r),!(!(o instanceof ArrayBuffer)||!this.sourceBuffer)){if(this.abort(),yield this.sourceBufferTaskQueue.append(o,this.downloadAbortController.signal),i)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=r,yield this.dropBuffer();else{let u=this.getCurrentPosition();Js(u)&&!this.isLive&&(this.bufferLimit=this.forwardBufferTarget,yield this.pruneBuffer(u,1/0,!0)),this.downloadingRepresentationId=r,this.switchingToRepresentationId=void 0}this.maintain()}})}.bind(this))(e,t))}abort(){for(let e of this.activeSegments)this.abortSegment(e.segment);this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new ze,this.abortBuffer()}maintain(e=this.getCurrentPosition()){var l,c;if(Fe(e)||Fe(this.downloadingRepresentationId)||Fe(this.playingRepresentationId)||Fe(this.sourceBuffer)||Js(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),r=this.segments.get(this.downloadingRepresentationId);if(de(t,`No such representation ${this.downloadingRepresentationId}`),!r)return;let i=r.find(d=>e>=d.time.from&&e<d.time.to);this.currentSegmentLength$.next(((l=i==null?void 0:i.time.to)!=null?l:0)-((c=i==null?void 0:i.time.from)!=null?c:0));let s=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){let h=at(this.sourceBuffer.buffered,e),p=i?i.time.to+100:-1/0;i&&i.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&h>=i.time.to-e+100&&(s=p)}if(isFinite(this.bufferLimit)&&Gu(this.sourceBuffer.buffered)>=this.bufferLimit){let d=at(this.sourceBuffer.buffered,e),h=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,d<h);return}let o=[];if(!this.activeSegments.size&&(o=this.selectForwardBufferSegments(r,t.segmentReference.type,s),o.length)){let d="auto";if(this.tuning.dash.useFetchPriorityHints&&i)if(o.includes(i))d="high";else{let h=(0,Yr.default)(o,0);h&&h.time.from-i.time.to>=this.forwardBufferTarget/2&&(d="low")}this.loadSegments(o,t,d)}(!this.preloadOnly&&!this.allInitsLoaded&&i&&i.status==="fed"&&!o.length&&at(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let u=(0,Yr.default)(r,-1);u&&u.status==="fed"&&(this.fullyBuffered$.next(!0),this.isLive||this.onLastSegment$.next(i===u))}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}searchGaps(e,t){this.gaps=[];let r=0,i=this.isLive?this.liveInitialAdditionalOffset:0;for(let s of e)Math.trunc(s.time.from-r)>0&&this.gaps.push({representation:t.id,from:r,to:s.time.from+i}),r=s.time.to;Js(t.duration)&&t.duration-r>0&&this.gaps.push({representation:t.id,from:r,to:t.duration})}getActualLiveStartingSegments(e){let t=e.segments,r=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,i=[],s=0,n=t.length-1;do i.unshift(t[n]),s+=t[n].time.to-t[n].time.from,n--;while(s<r&&n>=0);return this.liveInitialAdditionalOffset=s-r,this.isActiveLowLatency()?[i[0]]:i}getLiveSegmentsToLoadState(e){let t=e==null?void 0:e.streams[this.kind].flatMap(i=>i.representations).find(i=>i.id===this.downloadingRepresentationId);if(!t)return;let r=this.segments.get(t.id);if(r!=null&&r.length)return{from:r[0].time.from,to:r[r.length-1].time.to}}updateLive(e){var r,i,s,n;let t=(r=e==null?void 0:e.streams[this.kind].flatMap(o=>o.representations))!=null?r:[];for(let o of t){if(!o||!ke(o.segmentReference))return;let u=o.segmentReference.segments.map(h=>D(A({},h),{status:"none",size:void 0})),l=(i=this.segments.get(o.id))!=null?i:[],c=(n=(s=(0,Yr.default)(l,-1))==null?void 0:s.time.to)!=null?n:0,d=u==null?void 0:u.findIndex(h=>Math.floor(c)>=Math.floor(h.time.from)&&Math.floor(c)<=Math.floor(h.time.to));if(d===-1){this.liveUpdateSegmentIndex=0;let h=this.getActualLiveStartingSegments(o.segmentReference);this.segments.set(o.id,h)}else{let h=u.slice(d+1);this.segments.set(o.id,[...l,...h])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;de(e);let t=this.segments.get(e);if(t!=null&&t.length){let r=t[t.length-1];this.updateLowLatencyLiveIfNeeded(r)}}startAccumulateBuffer(){this.bufferAccumulation.enabled=!0}resetAccumulateBufferAfterStall(){this.bufferAccumulation={enabled:!1,targetBufferSizeMs:this.tuning.accumulationBufferStallSizeMs,accumulatedBufferSizeMs:0,accumulated:[]}}updateLowLatencyLiveIfNeeded(e){var t;for(let r of this.representations.values()){let i=r.segmentReference;if(!ke(i))return;let s=(t=this.segments.get(r.id))!=null?t:[],n=s.find(u=>Math.floor(u.time.from)===Math.floor(e.time.from));if(n&&!isFinite(n.time.to)&&(n.time.to=e.time.to),!!!s.find(u=>Math.floor(u.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let u=Math.round(e.time.to*i.timescale/1e3).toString(10),l=mt(i.segmentTemplateUrl,{segmentTime:u});s.push({status:"none",time:{from:e.time.to,to:1/0},url:l})}}}findSegmentStartTime(e){var s,n,o;let t=(n=(s=this.switchingToRepresentationId)!=null?s:this.downloadingRepresentationId)!=null?n:this.playingRepresentationId;if(!t)return;let r=this.segments.get(t);if(!r)return;let i=r.find(u=>u.time.from<=e&&u.time.to>=e);return(o=i==null?void 0:i.time.from)!=null?o:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){var e;if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),(e=this.sourceBufferTaskQueue)==null||e.destroy(),this.gapDetectionIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer){this.mediaSource.readyState==="open"&&this.abortBuffer();try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(t){if(!(t instanceof DOMException&&t.name==="NotFoundError"))throw t}}this.sourceBuffer=null,this.downloadAbortController.abort(),this.switchAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,r){return this.isLive?this.selectForwardBufferSegmentsLive(e,r):this.selectForwardBufferSegmentsRecord(e,t,r)}selectForwardBufferSegmentsLive(e,t){let r=e.findIndex(i=>t>=i.time.from&&t<i.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=r),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,r){let i=e.findIndex(({status:d,time:{from:h,to:p}},f)=>{let b=h<=r&&p>=r,g=h>r||b||f===0&&r===0,S=Math.min(this.forwardBufferTarget,this.bufferLimit),y=this.preloadOnly&&h<=r+S||p<=r+S;return(d==="none"||d==="partially_ejected"&&g&&y&&this.sourceBuffer&&!(Lt(this.sourceBuffer.buffered,h)&&Lt(this.sourceBuffer.buffered,p)))&&g&&y});if(i===-1)return[];if(t!=="byteRange")return e.slice(i,i+1);let s=e,n=0,o=0,u=[],l=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,c=this.preloadOnly?this.forwardBufferTarget:0;for(let d=i;d<s.length&&(n<=l||o<=c);d++){let h=s[d];if(n+=h.byte.to+1-h.byte.from,o+=h.time.to+1-h.time.from,h.status==="none"||h.status==="partially_ejected")u.push(h);else break}return u}loadSegments(e,t,r="auto"){return R(this,null,function*(){ke(t.segmentReference)?yield this.loadTemplateSegment(e[0],t,r):yield this.loadByteRangeSegments(e,t,r)})}loadTemplateSegment(e,t,r="auto"){return R(this,null,function*(){e.status="downloading";let i={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(i);let{range:s,url:n,signal:o,onProgress:u,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(yield ar(o,function(){return Z(this,null,function*(){let c=ul(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(d=>setTimeout(d,c))})}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let c=yield this.fetcher.fetch(n,{range:s,signal:o,onProgress:u,priority:r,isLowLatency:this.isActiveLowLatency()});if(this.lastDataObtainedTimestampMs=Xs(),!c)return;let d=new DataView(c);if(!isFinite(i.segment.time.to)){let h=t.segmentReference.timescale,p=la(t.mime);i.segment.time.to=p.getSegmentEndTime(d,h)}u&&i.feedingBytes&&l?yield Promise.all(l):yield this.sourceBufferTaskQueue.append(d,o),i.segment.status="downloaded",this.onSegmentFullyAppended(i,t.id),this.failedDownloads=0}catch(c){this.abortActiveSegments([e]),ca(c)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}})}updateRepresentationsBaseUrlIfNeeded(){if(!this.tuning.dash.enableBaseUrlSupport||!this.baseUrls.length||this.failedDownloads<=this.tuning.dash.maxSegmentRetryCount)return;this.baseUrlsIndex=(this.baseUrlsIndex+1)%this.baseUrls.length;let e=this.baseUrls[this.baseUrlsIndex];for(let t of this.representations.values())ke(t.segmentReference)?t.segmentReference.baseUrl=e:t.segmentReference.url=e}loadByteRangeSegments(e,t,r="auto"){return R(this,null,function*(){if(!e.length)return;for(let u of e)u.status="downloading",this.activeSegments.add({segment:u,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:i,url:s,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(yield ar(n,function(){return Z(this,null,function*(){let u=ul(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),ol(window,"online").pipe(yR()).subscribe(()=>{l(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{yield this.fetcher.fetch(s,{range:i,onProgress:o,signal:n,priority:r}),this.lastDataObtainedTimestampMs=Xs(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),ca(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}})}prepareByteRangeFetchSegmentParams(e,t){if(ke(t.segmentReference))throw new Error("Representation is not byte range type");let r=t.segmentReference.url,i={from:(0,Yr.default)(e,0).byte.from,to:(0,Yr.default)(e,-1).byte.to},{signal:s}=this.downloadAbortController;return{url:r,range:i,signal:s,onProgress:(o,u)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=Xs(),this.onSomeByteRangesDataLoaded({dataView:o,loaded:u,signal:s,onSegmentAppendFailed:()=>this.abort(),globalFrom:i?i.from:0,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:Mt.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!ke(t.segmentReference))throw new Error("Representation is not template type");let r=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&r.searchParams.set("low-latency","yes");let i=r.toString(),{signal:s}=this.downloadAbortController,n=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(l,c)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=Xs();let d=this.onSomeTemplateDataLoaded({dataView:l,loaded:c,signal:s,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(d)}catch(d){this.error$.next({id:"SegmentFeeding",category:Mt.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:d})}}:void 0;return{url:i,signal:s,onProgress:u,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)e.includes(t.segment)&&this.abortSegment(t.segment)}onSomeTemplateDataLoaded(n){return R(this,arguments,function*({dataView:e,representationId:t,loaded:r,onSegmentAppendFailed:i,signal:s}){if(!this.activeSegments.size)return;let o=this.representations.get(t);if(o)for(let u of this.activeSegments){let{segment:l}=u;if(u.representationId===t){if(s.aborted){i();continue}if(u.loadedBytes=r,u.loadedBytes>u.feedingBytes){let c=new DataView(e.buffer,e.byteOffset+u.feedingBytes,u.loadedBytes-u.feedingBytes),d=la(o.mime).parseFeedableSegmentChunk(c,this.isLive);d!=null&&d.byteLength&&(l.status="partially_fed",u.feedingBytes+=d.byteLength,yield this.sourceBufferTaskQueue.append(d),u.fedBytes+=d.byteLength)}}}})}onSomeByteRangesDataLoaded(o){return R(this,arguments,function*({dataView:e,representationId:t,globalFrom:r,loaded:i,signal:s,onSegmentAppendFailed:n}){if(!this.activeSegments.size)return;let u=this.representations.get(t);if(u)for(let l of this.activeSegments){let{segment:c}=l;if(l.representationId!==t)continue;if(s.aborted){n();continue}let d=c.byte.from-r,h=c.byte.to-r,p=h-d+1,f=d<i,b=h<=i;if(f){if(c.status==="downloading"&&b){c.status="downloaded";let g=new DataView(e.buffer,e.byteOffset+d,p);(yield this.sourceBufferTaskQueue.append(g,s))&&!s.aborted?this.onSegmentFullyAppended(l,t):n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(c.status==="downloading"||c.status==="partially_fed")&&(l.loadedBytes=Math.min(p,i-d),l.loadedBytes>l.feedingBytes)){let g=new DataView(e.buffer,e.byteOffset+d+l.feedingBytes,l.loadedBytes-l.feedingBytes),S=l.loadedBytes===p?g:la(u.mime).parseFeedableSegmentChunk(g);S!=null&&S.byteLength&&(c.status="partially_fed",l.feedingBytes+=S.byteLength,(yield this.sourceBufferTaskQueue.append(S,s))&&!s.aborted?(l.fedBytes+=S.byteLength,l.fedBytes===p&&this.onSegmentFullyAppended(l,t)):n())}}}})}onSegmentFullyAppended(e,t){var i;de(this.sourceBuffer),Lt(this.sourceBuffer.buffered,e.segment.time.from)&&Lt(this.sourceBuffer.buffered,e.segment.time.to)||this.error$.next({id:"SafariEmptyAppendBuffer",category:Mt.VIDEO_PIPELINE,message:"Safari stuck on empty result of adding segment to source buffer"}),this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status="fed",nl(e.segment)&&(e.segment.size=e.fedBytes);for(let s of this.representations.values())if(s.id!==t)for(let n of(i=this.segments.get(s.id))!=null?i:[])n.status==="fed"&&Math.round(n.time.from)===Math.round(e.segment.time.from)&&Math.round(n.time.to)===Math.round(e.segment.time.to)&&(n.status="none");de(this.sourceBuffer),this.updateLowLatencyLiveIfNeeded(e.segment),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment]),this.tuning.useNewPruneBufferStrategy&&this.pruneBuffer(this.getCurrentPosition(),1/0,!1)}abortSegment(e){e.status==="partially_fed"?e.status="partially_ejected":e.status!=="partially_ejected"&&(e.status="none");for(let t of this.activeSegments.values())if(t.segment===e){this.activeSegments.delete(t);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(let[i,s]of this.initData.entries()){let n=s instanceof Promise;t||(t=n),s===null&&(e=i)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let r=this.representations.get(e);r&&(this.initLoadIdleCallback=qu(()=>(0,cS.default)(this.loadInit(r,"low",!1),()=>this.initLoadIdleCallback=null)))}loadInit(e,t="auto",r=!1){return R(this,null,function*(){let i=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!r&&this.failedDownloads>0?ar(this.destroyAbortController.signal,function(){return Z(this,null,function*(){let o=ul(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))})}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,la(e.mime),i)).then(o=>R(this,null,function*(){if(!o)return;let{init:u,dataView:l,segments:c}=o,d=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,d);let h=c;this.isLive&&ke(e.segmentReference)&&(h=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,h),u&&this.parsedInitData.set(e.id,u)})).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),r&&this.error$.next({id:"LoadInits",category:Mt.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n})}dropBuffer(){return R(this,null,function*(){for(let e of this.segments.values())for(let t of e)t.status="none";yield this.pruneBuffer(0,1/0,!0)})}pruneBuffer(e,t,r=!1){return R(this,null,function*(){if(!this.sourceBuffer||!this.playingRepresentationId||Fe(e)||this.sourceBuffer.updating)return!1;let i=[],s=0,n=u=>{u.sort((c,d)=>c.from-d.from);let l=[u[0]];for(let c=1;c<u.length;c++){let{from:d,to:h}=u[c],p=l[l.length-1];p.to>=d?p.to=Math.max(p.to,h):l.push(u[c])}return l},o=u=>{var c;if(s>=t)return i;i.push(A({},u.time)),i=n(i);let l=nl(u)?(c=u.size)!=null?c:0:u.byte.to-u.byte.from;s+=l};for(let u of this.segments.values())for(let l of u){let c=l.time.to<=e-this.tuning.dash.bufferPruningSafeZone,d=l.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(c||d)&&l.status==="fed"&&o(l)}for(let u=0;u<this.sourceBuffer.buffered.length;u++){let l=this.sourceBuffer.buffered.start(u)*1e3,c=this.sourceBuffer.buffered.end(u)*1e3,d=0;for(let h of this.segments.values())for(let p of h)["none","partially_ejected"].includes(p.status)&&Math.round(p.time.from)<=Math.round(l)&&Math.round(p.time.to)>=Math.round(c)&&d++;if(d===this.segments.size){let h={time:{from:l,to:c},url:"",status:"none"};o(h)}}if(i.length&&r){let u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let l of this.segments.values())for(let c of l)c.time.from>=e+u&&c.status==="fed"&&o(c)}return i.length?(yield Promise.all(i.map(l=>this.sourceBufferTaskQueue.remove(l.from,l.to)))).reduce((l,c)=>l||c,!1):!1})}abortBuffer(){if(!this.sourceBuffer||this.mediaSource.readyState!=="open")return;let e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;this.sourceBufferTaskQueue.abort(t)}getDebugBufferState(){if(!(!this.sourceBuffer||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}getForwardBufferDuration(){let e=this.getCurrentPosition();return!this.sourceBuffer||!this.sourceBuffer.buffered.length||Fe(e)?0:at(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(this.sourceBuffer)for(let r of t){let i={representation:e,from:r.time.from,to:r.time.to};for(let s=0;s<this.sourceBuffer.buffered.length;s++){let n=this.sourceBuffer.buffered.start(s)*1e3,o=this.sourceBuffer.buffered.end(s)*1e3;if(!(o<=r.time.from||n>=r.time.to)){if(n<=r.time.from&&o>=r.time.to){i=void 0;break}o>r.time.from&&o<r.time.to&&(i.from=o),n<r.time.to&&n>r.time.from&&(i.to=n)}}i&&i.to-i.from>1&&!this.gaps.some(s=>i&&s.from===i.from&&s.to===i.to)&&this.gaps.push(i)}}detectGapsWhenIdle(e,t){if(!this.gapDetectionIdleCallback){de(this.sourceBuffer);for(let r=0;r<this.sourceBuffer.buffered.length;r++)this.gaps=this.gaps.filter(i=>this.sourceBuffer&&(Math.round(i.from)<Math.round(this.sourceBuffer.buffered.start(r)*1e3)||Math.round(i.to)>Math.round(this.sourceBuffer.buffered.end(r)*1e3)));this.gapDetectionIdleCallback=qu(()=>{try{this.detectGaps(e,t)}catch(r){this.error$.next({id:"GapDetection",category:Mt.WTF,message:"detectGaps threw",thrown:r})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if(Fe(this.sourceBuffer)||Fe(this.playingRepresentationId))return;let e=[];for(let r=0;r<this.sourceBuffer.buffered.length;r++){let i=Math.floor(this.sourceBuffer.buffered.start(r)*1e3),s=Math.ceil(this.sourceBuffer.buffered.end(r)*1e3);e.push({from:i,to:s})}let t=100;for(let r of this.segments.values())for(let i of r){let{status:s}=i;if(s!=="fed"&&s!=="partially_ejected")continue;let n=Math.floor(i.time.from),o=Math.ceil(i.time.to),u=e.some(c=>c.from-t<=n&&c.to+t>=o),l=e.filter(c=>n>=c.from&&n<c.to-t||o>c.from+t&&o<=c.to);u||(l.length===1?i.status="partially_ejected":this.gaps.some(c=>c.from===i.time.from||c.to===i.time.to)?i.status="partially_ejected":i.status="none")}}};var ha=a=>{let e=new URL(a);return e.searchParams.set("quic","1"),e.toString()};var dS=a=>{var s;let e=a.get("X-Delivery-Type"),t=a.get("X-Reused"),r=e===null?"http1":e!=null?e:void 0,i=t===null?void 0:(s={1:!0,0:!1}[t])!=null?s:void 0;return{type:r,reused:i}};import{abortable as fa,assertNever as pS,fromEvent as hS,merge as ER,now as ma,Subscription as xR,ValueSubject as ll,flattenObject as Qr}from"@vkontakte/videoplayer-shared";var Zs=class{constructor({throughputEstimator:e,requestQuic:t,tracer:r,compatibilityMode:i=!1}){this.lastConnectionType$=new ll(void 0);this.lastConnectionReused$=new ll(void 0);this.lastRequestFirstBytes$=new ll(void 0);this.abortAllController=new ze;this.subscription=new xR;this.fetchManifest=fa(this.abortAllController.signal,function(e){return Z(this,null,function*(){let t=this.tracer.createComponentTracer("FetchManifest"),r=e;this.requestQuic&&(r=ha(r));let i=yield ht(r,{signal:this.abortAllController.signal}).catch(ba);return i?(t.log("success",Qr({url:r,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(i.headers),i.text()):(t.error("error",Qr({url:r,message:"No data in request manifest"})),t.end(),null)})}.bind(this));this.fetch=fa(this.abortAllController.signal,function(l){return Z(this,arguments,function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:r,onProgress:i,priority:s="auto",signal:n,measureThroughput:o=!0,isLowLatency:u=!1}={}){var w,U;let c=e,d=new Headers,h=this.tracer.createComponentTracer("Fetch");if(r)switch(t){case 0:{d.append("Range",`bytes=${r.from}-${r.to}`);break}case 1:{let L=new URL(c,location.href);L.searchParams.append("bytes",`${r.from}-${r.to}`),c=L.toString();break}default:pS(t)}this.requestQuic&&(c=ha(c));let p=this.abortAllController.signal,f;if(n){let L=new ze;if(f=ER(hS(this.abortAllController.signal,"abort"),hS(n,"abort")).subscribe(()=>{try{L.abort()}catch(W){ba(W)}}),this.abortAllController.signal.aborted||n.aborted)try{L.abort()}catch(W){ba(W)}p=L.signal}let b=ma();h.log("startRequest",Qr({url:c,priority:s,rangeMethod:t,range:r,isLowLatency:u,requestStartedAt:b}));let g=yield ht(c,{priority:s,headers:d,signal:p}).catch(ba),S=ma();if(!g)return h.error("error",{message:"No response in request"}),h.end(),f==null||f.unsubscribe(),null;if((w=this.throughputEstimator)==null||w.addRawRtt(S-b),!g.ok||!g.body){f==null||f.unsubscribe();let L=`Fetch error ${g.status}: ${g.statusText}`;return h.error("error",{message:L}),h.end(),Promise.reject(new Error(`Fetch error ${g.status}: ${g.statusText}`))}if(this.onHeadersReceived(g.headers),!i&&!o){f==null||f.unsubscribe();let L=ma(),W={requestStartedAt:b,requestEndedAt:L,duration:L-b};return h.log("endRequest",Qr(W)),h.end(),g.arrayBuffer()}let[y,T]=g.body.tee(),I=y.getReader();o&&((U=this.throughputEstimator)==null||U.trackStream(T,u));let E=0,k=new Uint8Array(0),B=!1,G=L=>{f==null||f.unsubscribe(),B=!0,ba(L)},V=fa(p,function(v){return Z(this,arguments,function*({done:L,value:W}){if(E===0&&this.lastRequestFirstBytes$.next(ma()-b),p.aborted){f==null||f.unsubscribe();return}if(!L&&W){let $=new Uint8Array(k.length+W.length);$.set(k),$.set(W,k.length),k=$,E+=W.byteLength,i==null||i(new DataView(k.buffer),E),yield I==null?void 0:I.read().then(V,G)}})}.bind(this));yield I==null?void 0:I.read().then(V,G),f==null||f.unsubscribe();let M=ma(),_={failed:B,requestStartedAt:b,requestEndedAt:M,duration:M-b};return B?(h.error("endRequest",Qr(_)),h.end(),null):(h.log("endRequest",Qr(_)),h.end(),k.buffer)})}.bind(this));this.fetchByteRangeRepresentation=fa(this.abortAllController.signal,function(e,t,r){return Z(this,null,function*(){var S;if(e.type!=="byteRange")return null;let{from:i,to:s}=e.initRange,n=i,o=s,u=!1,l,c;e.indexRange&&(l=e.indexRange.from,c=e.indexRange.to,u=s+1===l,u&&(n=Math.min(l,i),o=Math.max(c,s))),n=Math.min(n,0);let d=yield this.fetch(e.url,{range:{from:n,to:o},priority:r,measureThroughput:!1});if(!d)return null;let h=new DataView(d,i-n,s-n+1);if(!t.validateData(h))throw new Error("Invalid media file");let p=t.parseInit(h),f=(S=e.indexRange)!=null?S:t.getIndexRange(p);if(!f)throw new ReferenceError("No way to load representation index");let b;if(u)b=new DataView(d,f.from-n,f.to-f.from+1);else{let y=yield this.fetch(e.url,{range:f,priority:r,measureThroughput:!1});if(!y)return null;b=new DataView(y)}let g=t.parseSegments(b,p,f);return{init:p,dataView:new DataView(d),segments:g}})}.bind(this));this.fetchTemplateRepresentation=fa(this.abortAllController.signal,function(e,t){return Z(this,null,function*(){if(e.type!=="template")return null;let r=new URL(e.initUrl,e.baseUrl).toString(),i=yield this.fetch(r,{priority:t,measureThroughput:!1});return i?{init:null,segments:e.segments.map(n=>D(A({},n),{status:"none",size:void 0})),dataView:new DataView(i)}:null})}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=i,this.tracer=r.createComponentTracer("Fetcher")}onHeadersReceived(e){let{type:t,reused:r}=dS(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(r)}fetchRepresentation(e,t,r="auto"){return R(this,null,function*(){var s,n;let{type:i}=e;switch(i){case"byteRange":return(s=yield this.fetchByteRangeRepresentation(e,t,r))!=null?s:null;case"template":return(n=yield this.fetchTemplateRepresentation(e,r))!=null?n:null;default:pS(i)}})}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}},ba=a=>{if(!ca(a))throw a};var sr=(a,e,t)=>t*e+(1-t)*a,cl=(a,e)=>a.reduce((t,r)=>t+r,0)/e,fS=(a,e,t,r)=>{let i=0,s=t,n=cl(a,e),o=e<r?e:r;for(let u=0;u<o;u++)a[s]>n?i++:i--,s=(a.length+s-1)%a.length;return Math.abs(i)===o};import{isNullable as PR,ValueSubject as mS}from"@vkontakte/videoplayer-shared";var Ct=class{constructor(e){this.prevReported=void 0;this.pastMeasures=[];this.takenMeasures=0;this.measuresCursor=0;var r;this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new mS(e.initial),this.debounced$=new mS(e.initial);let t=(r=e.label)!=null?r:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new ce(`raw_${t}`),this.smoothedSeries$=new ce(`smoothed_${t}`),this.reportedSeries$=new ce(`reported_${t}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,r=0;for(let o=0;o<this.pastMeasures.length;o++)this.pastMeasures[o]!==void 0&&(t+=et(this.pastMeasures[o]-this.smoothed,2),r++);this.takenMeasures=r,t/=r;let i=Math.sqrt(t),s=this.smoothed+this.params.deviationFactor*i,n=this.smoothed-this.params.deviationFactor*i;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(e),this.updateSmoothedValue(e),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),!(this.smoothed>s||this.smoothed<n)&&(PR(this.prevReported)||Math.abs(this.smoothed-this.prevReported)/this.prevReported>=this.params.changeThreshold)&&(this.prevReported=this.smoothed,this.debounced$.next(this.smoothed),this.reportedSeries$.next(this.smoothed))}};var en=class extends Ct{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=sr(this.slow,e,this.params.emaAlphaSlow),this.fast=sr(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var tn=class extends Ct{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=cl(this.pastMeasures,this.takenMeasures);this.emaSmoothed=sr(this.emaSmoothed,e,this.params.emaAlpha);let r=fS(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=r?this.emaSmoothed:t}};var rn=class extends Ct{constructor(t){super(t);this.furtherValues=[];this.currentTopExtremumValue=0;this.extremumInterval=t.extremumInterval}next(t){this.currentTopExtremumValue<=t?(this.currentTopExtremumValue=t,this.furtherValues=[]):this.furtherValues.length===this.extremumInterval?(super.next(this.currentTopExtremumValue),this.currentTopExtremumValue=t,this.furtherValues=[]):this.furtherValues.push(t)}updateSmoothedValue(t){this.smoothed=this.smoothed?sr(this.smoothed,t,this.params.emaAlpha):t}};var nr=class{static getSmoothedValue(e,t,r){return r.type==="TwoEma"?new en({initial:e,emaAlphaSlow:r.emaAlphaSlow,emaAlphaFast:r.emaAlphaFast,changeThreshold:r.changeThreshold,fastDirection:t,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"}):new tn({initial:e,emaAlpha:r.emaAlpha,basisTrendChangeCount:r.basisTrendChangeCount,changeThreshold:r.changeThreshold,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"})}static getLiveEstimatedDelaySmoothedValue(e,t){return new rn(A({initial:e,label:"liveEdgeDelay"},t))}};var dl=(a,e)=>{a&&a.playbackRate!==e&&(a.playbackRate=e)};import{isNullable as AR,ValueSubject as wR}from"@vkontakte/videoplayer-shared";var ga=class a{constructor(e,t){this.currentRepresentation$=new wR(null);this.maxRepresentations=4;this.representationsCursor=0;this.representations=[];this.currentSegment=null;this.getCurrentPosition=t.getCurrentPosition,this.processStreams(e)}updateLive(e){this.processStreams(e==null?void 0:e.streams.text)}seekLive(e){this.processStreams(e)}maintain(e=this.getCurrentPosition()){var t;if(!AR(e))for(let r of this.representations)for(let i of r){let s=i.segmentReference,n=s.segments.length,o=s.segments[0].time.from,u=s.segments[n-1].time.to;if(e<o||e>u)continue;let l=s.segments.find(c=>c.time.from<=e&&c.time.to>=e);!l||((t=this.currentSegment)==null?void 0:t.time.from)===l.time.from&&this.currentSegment.time.to===l.time.to||(this.currentSegment=l,this.currentRepresentation$.next(D(A({},i),{label:"Live Text",language:"ru",isAuto:!0,url:new URL(l.url,s.baseUrl).toString()})))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e!=null?e:[]){let r=a.filterRepresentations(t.representations);if(r){this.representations[this.representationsCursor]=r,this.representationsCursor=(this.representationsCursor+1)%this.maxRepresentations;break}}}static isSupported(e){return!!(e!=null&&e.some(t=>a.filterRepresentations(t.representations)))}static filterRepresentations(e){return e==null?void 0:e.filter(t=>t.kind==="text"&&"segmentReference"in t&&ke(t.segmentReference))}};var BR=["timeupdate","progress","play","seeked","stalled","waiting"],OR=["timeupdate","progress","loadeddata","playing","seeked"];var sn=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new yS;this.representationSubscription=new yS;this.state$=new C("none");this.currentVideoRepresentation$=new ne(void 0);this.currentVideoRepresentationInit$=new ne(void 0);this.currentAudioRepresentation$=new ne(void 0);this.currentVideoSegmentLength$=new ne(0);this.currentAudioSegmentLength$=new ne(0);this.error$=new vS;this.lastConnectionType$=new ne(void 0);this.lastConnectionReused$=new ne(void 0);this.lastRequestFirstBytes$=new ne(void 0);this.currentLiveTextRepresentation$=new ne(null);this.isLive$=new ne(!1);this.liveDuration$=new ne(0);this.liveAvailabilityStartTime$=new ne(void 0);this.bufferLength$=new ne(0);this.liveLoadBufferLength$=new ne(0);this.livePositionFromPlayer$=new ne(0);this.isActiveLowLatency$=new ne(!1);this.timeInWaiting=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.liveLastSeekOffset=0;this.forceEnded$=new vS;this.gapWatchdogActive=!1;this.destroyController=new ze;this.initManifest=pl(this.destroyController.signal,function(e,t,r){return Z(this,null,function*(){var i;this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=se(t,r,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),(i=this.manifest)!=null&&i.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:Dt.PARSER,message:"No playable video representations"})})}.bind(this));this.updateManifest=pl(this.destroyController.signal,function(){return Z(this,null,function*(){var n,o;this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(u=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:Dt.NETWORK,message:"Failed to load manifest",thrown:u})});if(!e)return null;let t=null;try{t=sS(e!=null?e:"",this.manifestUrlString)}catch(u){let l=(n=gg(e))!=null?n:{id:"ManifestParsing",category:Dt.PARSER,message:"Failed to parse MPD manifest",thrown:u};this.error$.next(l)}if(!t)return null;let r=(u,l,c)=>{var d,h,p,f;return!!((h=(d=this.element)==null?void 0:d.canPlayType)!=null&&h.call(d,l)&&((f=(p=ft())==null?void 0:p.isTypeSupported)!=null&&f.call(p,`${l}; codecs="${c}"`))||u==="text")};t.dynamic&&this.isLive$.getValue()!==t.dynamic&&(this.isLive$.next(t.dynamic),this.liveDuration$.getValue()!==t.duration&&this.liveDuration$.next(-1*((o=t.duration)!=null?o:0)/1e3),this.liveAvailabilityStartTime$.getValue()!==t.liveAvailabilityStartTime&&this.liveAvailabilityStartTime$.next(t.liveAvailabilityStartTime));let i={text:t.streams.text,video:[],audio:[]};for(let u of["video","audio"]){let c=t.streams[u].filter(({mime:p,codecs:f})=>r(u,p,f)),d=new Set(c.map(({codecs:p})=>p)),h=bg(d);if(h&&(i[u]=c.filter(({codecs:p})=>p.startsWith(h))),u==="video"){let p=this.tuning.preferHDR,f=i.video.some(g=>g.hdr),b=i.video.some(g=>!g.hdr);$R.isHDR&&p&&f?i.video=i.video.filter(g=>g.hdr):b&&(i.video=i.video.filter(g=>!g.hdr))}}let s=D(A({},t),{streams:i});return this.tracer.log("updateManifestEnd",Sa(s)),s})}.bind(this));this.initRepresentations=pl(this.destroyController.signal,function(e,t,r){return Z(this,null,function*(){var h;this.tracer.log("initRepresentationsStart",Sa({initialVideo:e,initialAudio:t,sourceHls:r})),or(this.manifest),or(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let i=p=>{this.representationSubscription.add(ur(p,"error").pipe(hl(f=>{var b;return!!((b=this.element)!=null&&b.played.length)})).subscribe(f=>{this.error$.next({id:"VideoSource",category:Dt.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:f})}))};this.source=this.tuning.useManagedMediaSource?Zb():new MediaSource;let s=document.createElement("source");if(i(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),this.tuning.useManagedMediaSource&&Fs())if(r){let p=document.createElement("source");i(p),p.type="application/x-mpegurl",p.src=r.url,this.element.appendChild(p)}else this.element.disableRemotePlayback=!0;this.isActiveLowLatency$.next(this.isLive$.getValue()&&this.tuning.dashCmafLive.lowLatency.isActive);let n={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLowLatency$.getValue(),manifest:this.manifest},o=this.manifest.streams.video.reduce((p,f)=>[...p,...f.representations],[]);if(this.videoBufferManager=new pa("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],SS(t)){let p=this.manifest.streams.audio.reduce((f,b)=>[...f,...b.representations],[]);this.audioBufferManager=new pa("audio",this.source,p,n),this.bufferManagers.push(this.audioBufferManager)}ga.isSupported(this.manifest.streams.text)&&!this.tuning.dashCmafLive.lowLatency.isActive&&(this.liveTextManager=new ga(this.manifest.streams.text,n)),this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$)),this.representationSubscription.add(fl(1e3).subscribe(p=>{var f;if((f=this.element)!=null&&f.paused){let b=Tu(this.manifestUrlString,2);this.manifestUrlString=se(this.manifestUrlString,b+1e3,2)}}));let u=()=>{var p;(p=this.stallWatchdogSubscription)==null||p.unsubscribe(),this.timeInWaiting=0};if(this.representationSubscription.add(lr(...OR.map(p=>ur(this.element,p))).pipe(ml(p=>this.element?at(this.element.buffered,this.element.currentTime*1e3):0),gS(),CR(p=>{p>this.tuning.dash.bufferEmptinessTolerance&&u()})).subscribe(this.bufferLength$)),this.representationSubscription.add(lr(ur(this.element,"ended"),this.forceEnded$).subscribe(()=>{u()})),this.isLive$.getValue()){this.representationSubscription.add(this.isActiveLowLatency$.pipe(gS()).subscribe(f=>dl(this.element,1))),this.representationSubscription.add(an({bufferLength:this.bufferLength$,isActiveLowLatency:this.isActiveLowLatency$}).pipe(hl(({bufferLength:f,isActiveLowLatency:b})=>b&&!!f)).subscribe(({bufferLength:f})=>this.liveEstimatedDelay.next(f))),this.representationSubscription.add(an({liveEstimatedDelay:this.liveEstimatedDelay.smoothed$,isActiveLowLatency:this.isActiveLowLatency$}).subscribe(({liveEstimatedDelay:f,isActiveLowLatency:b})=>{if(!b)return;let g=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,S=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,y=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,T=f-g,I=1;Math.abs(T)>S&&(I=1+Math.sign(T)*y),dl(this.element,I)})),this.representationSubscription.add(this.bufferLength$.subscribe(f=>{var g,S;let b=0;if(f){let y=((S=(g=this.element)==null?void 0:g.currentTime)!=null?S:0)*1e3;b=Math.min(...this.bufferManagers.map(I=>{var E,k;return(k=(E=I.getLiveSegmentsToLoadState(this.manifest))==null?void 0:E.to)!=null?k:y}))-y}this.liveLoadBufferLength$.getValue()!==b&&this.liveLoadBufferLength$.next(b)}));let p=0;this.representationSubscription.add(an({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(DR(1e3)).subscribe(g=>R(this,[g],function*({liveLoadBufferLength:f,bufferLength:b}){if(or(this.element),this.isUpdatingLive)return;let S=this.element.playbackRate,y=Tu(this.manifestUrlString,2),T=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,I=Math.min(T,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*S),E=this.tuning.dashCmafLive.normalizedActualBufferOffset*S,k=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*S,B=isFinite(f)?f:b,G=this.isActiveLowLatency$.getValue(),V=T<=this.tuning.live.activeLiveDelay&&y===0;this.isActiveLowLatency$.next(G&&V);let M="none";if(G?M="active_low_latency":this.tuning.dashCmafLive.lowLatency.isActive&&V?(this.isActiveLowLatency$.next(!0),this.bufferManagers.forEach(_=>_.proceedLowLatencyLive()),M="active_low_latency"):y!==0&&B<I?M="live_forward_buffering":B<I+k&&(M="live_with_target_offset"),isFinite(f)&&(p=f>p?f:p),M==="live_forward_buffering"||M==="live_with_target_offset"){let _=p-(I+E),w=this.normolizeLiveOffset(Math.trunc(y+_/S)),U=Math.abs(w-y),L;!f||U<=this.tuning.dashCmafLive.offsetCalculationError?L=y:w>0&&U>this.tuning.dashCmafLive.offsetCalculationError?L=w:L=0,this.manifestUrlString=se(this.manifestUrlString,L,2)}M!=="none"&&M!=="active_low_latency"&&(p=0,this.updateLive())})))}let l=lr(...this.bufferManagers.map(p=>p.fullyBuffered$)).pipe(ml(()=>this.bufferManagers.every(p=>p.fullyBuffered$.getValue()))),c=lr(...this.bufferManagers.map(p=>p.onLastSegment$)).pipe(ml(()=>this.bufferManagers.some(p=>p.onLastSegment$.getValue())));this.representationSubscription.add(lr(this.forceEnded$,an({allBuffersFull:l,someBufferEnded:c}).pipe(hl(({allBuffersFull:p,someBufferEnded:f})=>p&&f))).subscribe(()=>{var p;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(f=>!f.updating))try{(p=this.source)==null||p.endOfStream()}catch(f){this.error$.next({id:"EndOfStream",category:Dt.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:f})}})),this.representationSubscription.add(lr(...this.bufferManagers.map(p=>p.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.subscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.subscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&(this.representationSubscription.add(this.audioBufferManager.playingRepresentation$.subscribe(this.currentAudioRepresentation$)),this.subscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$))),this.liveTextManager&&this.subscription.add(this.liveTextManager.currentRepresentation$.subscribe(this.currentLiveTextRepresentation$)),this.source.readyState!=="open"&&(yield new Promise(p=>{var f;return(f=this.source)==null?void 0:f.addEventListener("sourceopen",p)}));let d=[(h=this.manifest.duration)!=null?h:0,...[...this.manifest.streams.audio,...this.manifest.streams.video].flatMap(p=>p.representations).flatMap(p=>{let f=[];return p.duration&&f.push(p.duration),ke(p.segmentReference)&&p.segmentReference.totalSegmentsDurationMs&&f.push(p.segmentReference.totalSegmentsDurationMs),f})];this.source.duration=Math.max(...d)/1e3,this.audioBufferManager&&SS(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState("representations_ready"),this.tracer.log("initRepresentationsEnd")})}.bind(this));this.tick=()=>{var t,r,i;if(!this.element||!this.videoBufferManager)return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),(t=this.audioBufferManager)==null||t.maintain(e),(r=this.liveTextManager)==null||r.maintain(e),(this.videoBufferManager.gaps.length||(i=this.audioBufferManager)!=null&&i.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=fl(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),s=>{this.error$.next({id:"GapWatchdog",category:Dt.WTF,message:"Error handling gaps",thrown:s})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name),this.fetcher=new Zs({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer}),this.liveEstimatedDelay=nr.getLiveEstimatedDelaySmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,A({},e.tuning.dashCmafLive.lowLatency.delayEstimator)),this.initTracerSubscription()}seekLive(e){return R(this,null,function*(){var r,i,s;or(this.element);let t=this.normolizeLiveOffset(e);this.isActiveLowLatency$.next(this.tuning.dashCmafLive.lowLatency.isActive&&t===0),this.liveLastSeekOffset=t,this.manifestUrlString=se(this.manifestUrlString,t,2),this.manifest=yield this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,yield(r=this.videoBufferManager)==null?void 0:r.seekLive(this.manifest.streams.video),yield(i=this.audioBufferManager)==null?void 0:i.seekLive(this.manifest.streams.audio),(s=this.liveTextManager)==null||s.seekLive(this.manifest.streams.text))})}initBuffer(){or(this.element),this.state$.setState("running"),this.subscription.add(lr(...BR.map(e=>ur(this.element,e)),ur(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:Dt.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(ur(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(ur(this.element,"waiting").subscribe(()=>{var t,r,i;this.element&&this.element.readyState===2&&!this.element.seeking&&Lt(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{var f,b,g,S,y,T,I,E,k,B;if(!this.element)return;this.timeInWaiting+=1e3;let s={timeInWaiting:this.timeInWaiting},n=MR(),o=100,u=(b=(f=this.videoBufferManager)==null?void 0:f.lastDataObtainedTimestamp)!=null?b:0,l=(S=(g=this.audioBufferManager)==null?void 0:g.lastDataObtainedTimestamp)!=null?S:0,c=(T=(y=this.videoBufferManager)==null?void 0:y.getForwardBufferDuration())!=null?T:0,d=(E=(I=this.audioBufferManager)==null?void 0:I.getForwardBufferDuration())!=null?E:0,h=c<o&&n-u>this.tuning.dash.crashOnStallTWithoutDataTimeout,p=this.audioBufferManager&&d<o&&n-l>this.tuning.dash.crashOnStallTWithoutDataTimeout;if((h||p)&&this.timeInWaiting>this.tuning.dash.crashOnStallTWithoutDataTimeout||this.timeInWaiting>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${this.timeInWaiting} ms`);if(this.isLive$.getValue()&&this.timeInWaiting%5e3===0)this.seekLive(this.liveLastSeekOffset),s.liveLastSeekOffset=this.liveLastSeekOffset;else{let G=this.element.currentTime*1e3;(k=this.videoBufferManager)==null||k.maintain(G),(B=this.audioBufferManager)==null||B.maintain(G),s.position=G}this.tracer.log("stallIntervalCallback",Sa(s))};(t=this.videoBufferManager)==null||t.startAccumulateBuffer(),(r=this.audioBufferManager)==null||r.startAccumulateBuffer(),(i=this.stallWatchdogSubscription)==null||i.unsubscribe(),this.stallWatchdogSubscription=fl(1e3).subscribe(e,s=>{this.error$.next({id:"StallWatchdogCallback",category:Dt.NETWORK,message:"Can't restore DASH after stall.",thrown:s})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}switchRepresentation(e,t,r=!1){return R(this,null,function*(){let i={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return i==null?void 0:i.switchTo(t,r)})}seek(e,t){var i,s,n,o,u,l;or(this.element),or(this.videoBufferManager);let r;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?r=e:r=Math.max((i=this.videoBufferManager.findSegmentStartTime(e))!=null?i:e,(n=(s=this.audioBufferManager)==null?void 0:s.findSegmentStartTime(e))!=null?n:e),Lt(this.element.buffered,r)||(this.videoBufferManager.abort(),(o=this.audioBufferManager)==null||o.abort()),this.videoBufferManager.startAccumulateBuffer(),this.videoBufferManager.maintain(r),(u=this.audioBufferManager)==null||u.startAccumulateBuffer(),(l=this.audioBufferManager)==null||l.maintain(r),this.element.currentTime=r/1e3,this.tracer.log("seek",Sa({requestedPosition:e,forcePrecise:t,position:r}))}stop(){var e,t,r;this.tracer.log("stop"),(e=this.element)==null||e.querySelectorAll("source").forEach(i=>i.remove()),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),(t=this.videoBufferManager)==null||t.destroy(),this.videoBufferManager=null,(r=this.audioBufferManager)==null||r.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getStreams(){var e;return(e=this.manifest)==null?void 0:e.streams}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){var e;this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),((e=this.source)==null?void 0:e.readyState)==="open"&&Array.from(this.source.sourceBuffers).every(t=>!t.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}initTracerSubscription(){let e=LR(this.tracer.error.bind(this.tracer));this.error$.subscribe(e("error"))}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}updateLive(){return R(this,null,function*(){var e,t;this.isUpdatingLive=!0,this.manifest=yield this.updateManifest(),this.manifest&&((e=this.bufferManagers)==null||e.forEach(r=>r.updateLive(this.manifest)),(t=this.liveTextManager)==null||t.updateLive(this.manifest)),this.isUpdatingLive=!1})}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.getDebugBufferState();if(!e)return;let t={isJumpGapAfterSeekLive:this.isJumpGapAfterSeekLive,isActiveLowLatency:this.isActiveLowLatency$.getValue(),initialCurrentTime:this.element.currentTime};this.isJumpGapAfterSeekLive&&!this.isActiveLowLatency$.getValue()&&this.element.currentTime>e.to&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let r=this.element.currentTime*1e3,i=[],s=this.element.readyState===1?this.tuning.endGapTolerance:0;for(let n of this.bufferManagers)for(let o of n.gaps)n.playingRepresentation$.getValue()===o.representation&&o.from-s<=r&&o.to+s>r&&(this.element.duration*1e3-o.to<this.tuning.endGapTolerance?i.push(1/0):i.push(o.to));if(i.length){let n=Math.max(...i)+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,n===1/0?this.forceEnded$.next():(this.element.currentTime=n/1e3,t=D(A({},t),{gapEnds:i,jumpTo:n,resultCurrentTime:this.element.currentTime}),this.tracer.log("jumpGap",Sa(t)))}}};var nn=class{constructor(e,t){this.fov=e,this.orientation=t}};var on=class{constructor(e,t){this.rotating=!1;this.fading=!1;this.lastTickTS=0;this.lastCameraTurnTS=0;this.fadeStartSpeed=null;this.fadeTime=0;this.camera=e,this.options=t,this.rotationSpeed={x:0,y:0,z:0},this.fadeCorrection=1/et(this.options.speedFadeTime/1e3,2)}turnCamera(e=0,t=0,r=0){this.pointCameraTo(this.camera.orientation.x+e,this.camera.orientation.y+t,this.camera.orientation.z+r)}pointCameraTo(e=0,t=0,r=0){t=this.limitCameraRotationY(t);let i=e-this.camera.orientation.x,s=t-this.camera.orientation.y,n=r-this.camera.orientation.z;this.camera.orientation.x=e,this.camera.orientation.y=t,this.camera.orientation.z=r,this.lastCameraTurn={x:i,y:s,z:n},this.lastCameraTurnTS=Date.now()}setRotationSpeed(e,t,r){this.rotationSpeed.x=e!=null?e:this.rotationSpeed.x,this.rotationSpeed.y=t!=null?t:this.rotationSpeed.y,this.rotationSpeed.z=r!=null?r:this.rotationSpeed.z}startRotation(){this.rotating=!0}stopRotation(e=!1){e?(this.setRotationSpeed(0,0,0),this.fadeStartSpeed=null):this.startFading(this.rotationSpeed.x,this.rotationSpeed.y,this.rotationSpeed.z),this.rotating=!1}onCameraRelease(){if(this.lastCameraTurn&&this.lastCameraTurnTS){let e=Date.now()-this.lastCameraTurnTS;if(e<this.options.speedFadeThreshold){let t=(1-e/this.options.speedFadeThreshold)*this.options.rotationSpeedCorrection;this.startFading(this.lastCameraTurn.x*t,this.lastCameraTurn.y*t,this.lastCameraTurn.z*t)}}}startFading(e,t,r){this.setRotationSpeed(e,t,r),this.fadeStartSpeed=A({},this.rotationSpeed),this.fading=!0}stopFading(){this.fadeStartSpeed=null,this.fading=!0,this.fadeTime=0}limitCameraRotationY(e){return Math.max(-this.options.maxYawAngle,Math.min(e,this.options.maxYawAngle))}tick(e){if(!this.lastTickTS){this.lastTickTS=e,this.lastCameraTurnTS=Date.now();return}let t=e-this.lastTickTS,r=t/1e3;if(this.rotating)this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*r,this.rotationSpeed.y*this.options.rotationSpeedCorrection*r,this.rotationSpeed.z*this.options.rotationSpeedCorrection*r);else if(this.fading&&this.fadeStartSpeed){let i=-this.fadeCorrection*et(this.fadeTime/1e3,2)+1;this.setRotationSpeed(this.fadeStartSpeed.x*i,this.fadeStartSpeed.y*i,this.fadeStartSpeed.z*i),i>0?this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*r,this.rotationSpeed.y*this.options.rotationSpeedCorrection*r,this.rotationSpeed.z*this.options.rotationSpeedCorrection*r):(this.stopRotation(!0),this.stopFading()),this.fadeTime=Math.min(this.fadeTime+t,this.options.speedFadeTime)}this.lastTickTS=e}};var TS=`attribute vec2 a_vertex;
65
+ `})|(?<privateuse2>${e}))$`.replace(/[\s\t\n]/g,"");return new RegExp(c,"i")}var rS=a=>{if(!a.startsWith("P"))return;let e=(n,o)=>{let u=n?parseFloat(n.replace(",",".")):NaN;return(isNaN(u)?0:u)*o},r=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(a),i=(r==null?void 0:r[1])==="-"?-1:1,s={days:e(r==null?void 0:r[5],i),hours:e(r==null?void 0:r[6],i),minutes:e(r==null?void 0:r[7],i),seconds:e(r==null?void 0:r[8],i)};return s.days*24*60*60*1e3+s.hours*60*60*1e3+s.minutes*60*1e3+s.seconds*1e3},mt=(a,e)=>{let t=a;t=(0,Zu.default)(t,"$$","$");let r={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[i,s]of Object.entries(r)){let n=new RegExp(`\\$${i}(?:%0(\\d+)d)?\\$`,"g");t=(0,Zu.default)(t,n,(o,u)=>tS(s)?o:tS(u)?s:s.padStart(parseInt(u,10),"0"))}return t},aS=(a,e)=>{var E,k,B,G,V,M,_,R,U,L,W,v,$,Q,N,ue,qe,pr,Jr,H,he,xe,Me,gt,hr,St,Ft,fr,Xr,Ll,Ml,Cl,Dl,Bl,Ol,Vl,_l,Nl,Fl,Ul,ql,Hl,jl,Gl,Wl,Yl,Ql,zl,Kl,Jl,Xl,Zl,ec,tc,rc,ic,ac,sc,nc,oc;let r=new DOMParser().parseFromString(a,"application/xml"),i={video:[],audio:[],text:[]},s=r.children[0],n=s.getElementsByTagName("Period")[0],o=Array.from(s.querySelectorAll("MPD > BaseURL").values()).map(se=>{var Ca,vt;return(vt=(Ca=se.textContent)==null?void 0:Ca.trim())!=null?vt:""}),u=(E=(0,iS.default)(o,0))!=null?E:"",l=n.children,c=s.getAttribute("type")==="dynamic",d=s.getAttribute("availabilityStartTime"),h=d?new Date(d).getTime():void 0,p,f=s.getAttribute("mediaPresentationDuration"),b=n.getAttribute("duration"),g=s.getElementsByTagName("vk:Attrs")[0],T=g==null?void 0:g.getElementsByTagName("vk:XPlaybackDuration")[0].textContent;if(f)p=rS(f);else if(b){let se=rS(b);eS(se)&&(p=se)}else T&&(p=parseInt(T,10));let y=0,S=(B=(k=s.getAttribute("profiles"))==null?void 0:k.split(","))!=null?B:[];for(let se of l){let Ca=(G=se.getAttribute("id"))!=null?G:"id"+(y++).toString(10),vt=(V=se.getAttribute("mimeType"))!=null?V:"",En=(M=se.getAttribute("codecs"))!=null?M:"",xn=(_=se.getAttribute("contentType"))!=null?_:vt==null?void 0:vt.split("/")[0],gv=(U=(R=se.getAttribute("profiles"))==null?void 0:R.split(","))!=null?U:[],uc=(W=Zg((L=se.getAttribute("lang"))!=null?L:""))!=null?W:{},Sv=(Q=($=(v=se.querySelector("Label"))==null?void 0:v.textContent)==null?void 0:$.trim())!=null?Q:void 0,vv=se.querySelectorAll("Representation"),yv=se.querySelector("SegmentTemplate"),Tv=(ue=(N=se.querySelector("Role"))==null?void 0:N.getAttribute("value"))!=null?ue:void 0,Zr=xn,ee={id:Ca,language:uc.language,isDefault:Tv==="main",label:Sv,codecs:En,hdr:Zr==="video"&&Xu(En),mime:vt,representations:[]};for(let z of vv){let Iv=(qe=z.getAttribute("lang"))!=null?qe:void 0,Ev=(pr=z.getAttribute("label"))!=null?pr:void 0,xv=(he=(H=(Jr=z.querySelector("BaseURL"))==null?void 0:Jr.textContent)==null?void 0:H.trim())!=null?he:"",Da=new URL(xv||u,e).toString(),mr=(xe=z.getAttribute("mimeType"))!=null?xe:vt,Ba=(gt=(Me=z.getAttribute("codecs"))!=null?Me:En)!=null?gt:"",Oa;if(xn==="text"){let yt=z.getAttribute("id")||"",Va=((hr=uc.privateuse)==null?void 0:hr.includes("x-auto"))||yt.includes("_auto"),Ut=z.querySelector("SegmentTemplate");if(Ut){let ei={representationId:(St=z.getAttribute("id"))!=null?St:void 0,bandwidth:(Ft=z.getAttribute("bandwidth"))!=null?Ft:void 0},_a=parseInt((fr=z.getAttribute("bandwidth"))!=null?fr:"",10)/1e3,Na=(Ll=parseInt((Xr=Ut.getAttribute("startNumber"))!=null?Xr:"",10))!=null?Ll:1,br=parseInt((Ml=Ut.getAttribute("timescale"))!=null?Ml:"",10),Pn=(Cl=Ut.querySelectorAll("SegmentTimeline S"))!=null?Cl:[],gr=Ut.getAttribute("media");if(!gr)continue;let Fa=[],Ua=0,qa="",Sr=0,ti=Na,le=0;for(let He of Pn){let qt=parseInt((Dl=He.getAttribute("d"))!=null?Dl:"",10),Ce=parseInt((Bl=He.getAttribute("r"))!=null?Bl:"",10)||0,Tt=parseInt((Ol=He.getAttribute("t"))!=null?Ol:"",10);le=Number.isFinite(Tt)?Tt:le;let Ht=qt/br*1e3,It=le/br*1e3;for(let Xe=0;Xe<Ce+1;Xe++){let Et=mt(gr,D(A({},ei),{segmentNumber:ti.toString(10),segmentTime:(le+Xe*qt).toString(10)})),vr=(It!=null?It:0)+Xe*Ht,ii=vr+Ht;ti++,Fa.push({time:{from:vr,to:ii},url:Et})}le+=(Ce+1)*qt,Ua+=(Ce+1)*Ht}Sr=le/br*1e3,qa=mt(gr,D(A({},ei),{segmentNumber:ti.toString(10),segmentTime:le.toString(10)}));let ri={time:{from:Sr,to:1/0},url:qa},nt={type:"template",baseUrl:Da,segmentTemplateUrl:gr,initUrl:"",totalSegmentsDurationMs:Ua,segments:Fa,nextSegmentBeyondManifest:ri,timescale:br};Oa={id:yt,kind:"text",segmentReference:nt,profiles:[],duration:p,bitrate:_a,mime:"",codecs:"",width:0,height:0,isAuto:Va}}else Oa={id:yt,isAuto:Va,kind:"text",url:Da}}else{let yt=(_l=(Vl=z.getAttribute("contentType"))!=null?Vl:mr==null?void 0:mr.split("/")[0])!=null?_l:xn,Va=(Fl=(Nl=se.getAttribute("profiles"))==null?void 0:Nl.split(","))!=null?Fl:[],Ut=parseInt((Ul=z.getAttribute("width"))!=null?Ul:"",10),ei=parseInt((ql=z.getAttribute("height"))!=null?ql:"",10),_a=parseInt((Hl=z.getAttribute("bandwidth"))!=null?Hl:"",10)/1e3,Na=(jl=z.getAttribute("frameRate"))!=null?jl:"",br=(Gl=z.getAttribute("quality"))!=null?Gl:void 0,Pn=Na?Xg(Na):void 0,gr=(Wl=z.getAttribute("id"))!=null?Wl:"id"+(y++).toString(10),Fa=yt==="video"?`${ei}p`:yt==="audio"?`${_a}Kbps`:Ba,Ua=`${gr}@${Fa}`,qa=[...S,...gv,...Va],Sr,ti=z.querySelector("SegmentBase"),le=(Yl=z.querySelector("SegmentTemplate"))!=null?Yl:yv;if(ti){let nt=(zl=(Ql=z.querySelector("SegmentBase Initialization"))==null?void 0:Ql.getAttribute("range"))!=null?zl:"",[He,qt]=nt.split("-").map(Et=>parseInt(Et,10)),Ce={from:He,to:qt},Tt=(Kl=z.querySelector("SegmentBase"))==null?void 0:Kl.getAttribute("indexRange"),[Ht,It]=Tt?Tt.split("-").map(Et=>parseInt(Et,10)):[],Xe=Tt?{from:Ht,to:It}:void 0;Sr={type:"byteRange",url:Da,initRange:Ce,indexRange:Xe}}else if(le){let nt={representationId:(Jl=z.getAttribute("id"))!=null?Jl:void 0,bandwidth:(Xl=z.getAttribute("bandwidth"))!=null?Xl:void 0},He=parseInt((Zl=le.getAttribute("timescale"))!=null?Zl:"",10),qt=(ec=le.getAttribute("initialization"))!=null?ec:"",Ce=le.getAttribute("media"),Tt=(rc=parseInt((tc=le.getAttribute("startNumber"))!=null?tc:"",10))!=null?rc:1,Ht=mt(qt,nt);if(!Ce)throw new ReferenceError("No media attribute in SegmentTemplate");let It=(ic=le.querySelectorAll("SegmentTimeline S"))!=null?ic:[],Xe=[],Et=0,vr="",ii=0;if(It.length){let Ha=Tt,je=0;for(let yr of It){let Ze=parseInt((ac=yr.getAttribute("d"))!=null?ac:"",10),jt=parseInt((sc=yr.getAttribute("r"))!=null?sc:"",10)||0,ja=parseInt((nc=yr.getAttribute("t"))!=null?nc:"",10);je=Number.isFinite(ja)?ja:je;let An=Ze/He*1e3,wn=je/He*1e3;for(let Ga=0;Ga<jt+1;Ga++){let Av=mt(Ce,D(A({},nt),{segmentNumber:Ha.toString(10),segmentTime:(je+Ga*Ze).toString(10)})),lc=(wn!=null?wn:0)+Ga*An,wv=lc+An;Ha++,Xe.push({time:{from:lc,to:wv},url:Av})}je+=(jt+1)*Ze,Et+=(jt+1)*An}ii=je/He*1e3,vr=mt(Ce,D(A({},nt),{segmentNumber:Ha.toString(10),segmentTime:je.toString(10)}))}else if(eS(p)){let je=parseInt((oc=le.getAttribute("duration"))!=null?oc:"",10)/He*1e3,yr=Math.ceil(p/je),Ze=0;for(let jt=1;jt<yr;jt++){let ja=mt(Ce,D(A({},nt),{segmentNumber:jt.toString(10),segmentTime:Ze.toString(10)}));Xe.push({time:{from:Ze,to:Ze+je},url:ja}),Ze+=je}ii=Ze,vr=mt(Ce,D(A({},nt),{segmentNumber:yr.toString(10),segmentTime:Ze.toString(10)}))}let Pv={time:{from:ii,to:1/0},url:vr};Sr={type:"template",baseUrl:Da,segmentTemplateUrl:Ce,initUrl:Ht,totalSegmentsDurationMs:Et,segments:Xe,nextSegmentBeyondManifest:Pv,timescale:He}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!yt||!mr)continue;let ri={video:"video",audio:"audio",text:"text"}[yt];if(!ri)continue;Zr||(Zr=ri),Oa={id:Ua,kind:ri,segmentReference:Sr,profiles:qa,duration:p,bitrate:_a,mime:mr,codecs:Ba,width:Ut,height:ei,fps:Pn,quality:br}}ee.language||(ee.language=Iv),ee.label||(ee.label=Ev),ee.mime||(ee.mime=mr),ee.codecs||(ee.codecs=Ba),ee.hdr||(ee.hdr=Zr==="video"&&Xu(Ba)),ee.representations.push(Oa)}Zr&&i[Zr].push(ee)}return{dynamic:c,liveAvailabilityStartTime:h,duration:p,streams:i,baseUrls:o}};var rl=Ge(Fr(),1);import{videoSizeToQuality as yR}from"@vkontakte/videoplayer-shared";var sS=({id:a,width:e,height:t,bitrate:r,fps:i,quality:s})=>{var o;let n=(o=s?Rt(s):void 0)!=null?o:yR({width:e,height:t});return n&&{id:a,quality:n,bitrate:r,size:{width:e,height:t},fps:i}},nS=({id:a,bitrate:e})=>({id:a,bitrate:e}),oS=({language:a,label:e},{id:t,url:r,isAuto:i})=>({id:t,url:r,isAuto:i,type:"internal",language:a,label:e}),uS=({language:a,label:e,id:t,url:r,isAuto:i})=>({id:t,url:r,isAuto:i,type:"internal",language:a,label:e}),il=({id:a,language:e,label:t,codecs:r,isDefault:i})=>({id:a,language:e,label:t,codec:(0,rl.default)(r.split("."),0),isDefault:i}),al=({id:a,language:e,label:t,hdr:r,codecs:i})=>({id:a,language:e,hdr:r,label:t,codec:(0,rl.default)(i.split("."),0)}),sl=a=>"url"in a,Re=a=>a.type==="template",ca=a=>a instanceof DOMException&&(a.name==="AbortError"||a.code===20);var ha=class{constructor(e,t,r,{fetcher:i,tuning:s,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentSegmentLength$=new pa(0);this.onLastSegment$=new pa(!1);this.fullyBuffered$=new pa(!1);this.playingRepresentation$=new pa(void 0);this.playingRepresentationInit$=new pa(void 0);this.error$=new IR;this.gaps=[];this.subscription=new ER;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new ke;this.switchAbortController=new ke;this.destroyAbortController=new ke;this.bufferLimit=1/0;this.failedDownloads=0;this.baseUrls=[];this.baseUrlsIndex=0;this.isLive=!1;this.liveUpdateSegmentIndex=0;this.liveInitialAdditionalOffset=0;this.isSeekingLive=!1;this.index=0;this.lastDataObtainedTimestampMs=0;this.loadByteRangeSegmentsTimeoutId=0;this.startWith=sr(this.destroyAbortController.signal,function(e){return Z(this,null,function*(){let t=this.representations.get(e);ae(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.resetAccumulateBufferAfterStall(),this.startAccumulateBuffer(),this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new Tg(this.sourceBuffer),this.subscription.add(nl(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let o,u=this.mediaSource.readyState;u!=="open"&&(o={id:`SegmentEjection_source_${u}`,category:Ct.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o!=null||(o={id:"SegmentEjection",category:Ct.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),this.error$.next(o)})),this.subscription.add(nl(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:Ct.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o)return;let u=Math.min(this.bufferLimit,ju(this.sourceBuffer.buffered)*.8);this.bufferLimit=u;let l=at(this.sourceBuffer.buffered,o),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(o,n*2,l<c)})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(n=>this.error$.next(n))),yield this.loadInit(t,"high",!0);let r=this.initData.get(t.id),i=this.segments.get(t.id),s=this.parsedInitData.get(t.id);ae(r,"No init buffer for starting representation"),ae(i,"No segments for starting representation"),r instanceof ArrayBuffer&&(this.searchGaps(i,t),yield this.sourceBufferTaskQueue.append(r,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(s))})}.bind(this));this.switchToOld=sr(this.destroyAbortController.signal,function(e,t=!1){return Z(this,null,function*(){if(e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let r=this.representations.get(e);ae(r,`No such representation ${e}`);let i=this.segments.get(e),s=this.initData.get(e);if($e(s)||$e(i)?yield this.loadInit(r,"high",!1):s instanceof Promise&&(yield s),i=this.segments.get(e),ae(i,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer))if(this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer(),this.maintain();else{let n=this.getCurrentPosition();da(n)&&(this.isLive||(this.bufferLimit=1/0,yield new $n(this.pruneBuffer(n,1/0,!0))),this.maintain(n)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}})}.bind(this));this.seekLive=sr(this.destroyAbortController.signal,function(e){return Z(this,null,function*(){var u,l;let t=(u=e==null?void 0:e.flatMap(c=>c.representations))!=null?u:[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let c of this.representations.keys()){let d=t.find(f=>f.id===c);d&&this.representations.set(c,d);let h=this.representations.get(c);if(!h||!Re(h.segmentReference))return;let p=this.getActualLiveStartingSegments(h.segmentReference);this.segments.set(h.id,p)}let r=(l=this.switchingToRepresentationId)!=null?l:this.downloadingRepresentationId,i=this.representations.get(r);ae(i);let s=this.segments.get(r);ae(s,"No segments for starting representation");let n=this.initData.get(r);if(ae(n,"No init buffer for starting representation"),!(n instanceof ArrayBuffer))return;let o=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,this.abort(),o&&(yield this.sourceBufferTaskQueue.remove(o.from*1e3,o.to*1e3,this.destroyAbortController.signal)),this.searchGaps(s,i),yield this.sourceBufferTaskQueue.append(n,this.destroyAbortController.signal),this.isSeekingLive=!1})}.bind(this));var c;this.fetcher=i,this.tuning=s,this.compatibilityMode=u,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=o,this.isLive=!!(l!=null&&l.dynamic),this.baseUrls=(c=l==null?void 0:l.baseUrls)!=null?c:[],this.initData=new Map(r.map(d=>[d.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(r.map(d=>[d.id,d])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}switchTo(e,t=!1){return this.tuning.useNewSwitchTo?this.switchToNew(e,t):this.switchToOld(e,t)}switchToNew(e,t=!1){e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new ke,sr(this.switchAbortController.signal,function(r,i=!1){return Z(this,null,function*(){this.switchingToRepresentationId=r;let s=this.representations.get(r);ae(s,`No such representation ${r}`);let n=this.segments.get(r),o=this.initData.get(r);if($e(o)||$e(n)?yield this.loadInit(s,"high",!1):o instanceof Promise&&(yield o),n=this.segments.get(r),ae(n,"No segments for starting representation"),o=this.initData.get(r),!(!(o instanceof ArrayBuffer)||!this.sourceBuffer)){if(this.abort(),yield this.sourceBufferTaskQueue.append(o,this.downloadAbortController.signal),i)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=r,yield this.dropBuffer();else{let u=this.getCurrentPosition();da(u)&&!this.isLive&&(this.bufferLimit=this.forwardBufferTarget,yield this.pruneBuffer(u,1/0,!0)),this.downloadingRepresentationId=r,this.switchingToRepresentationId=void 0}this.maintain()}})}.bind(this))(e,t))}abort(){for(let e of this.activeSegments)this.abortSegment(e.segment);this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new ke,this.abortBuffer()}maintain(e=this.getCurrentPosition()){var l,c;if($e(e)||$e(this.downloadingRepresentationId)||$e(this.playingRepresentationId)||$e(this.sourceBuffer)||da(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),r=this.segments.get(this.downloadingRepresentationId);if(ae(t,`No such representation ${this.downloadingRepresentationId}`),!r)return;let i=r.find(d=>e>=d.time.from&&e<d.time.to);this.currentSegmentLength$.next(((l=i==null?void 0:i.time.to)!=null?l:0)-((c=i==null?void 0:i.time.from)!=null?c:0));let s=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){let h=at(this.sourceBuffer.buffered,e),p=i?i.time.to+100:-1/0;i&&i.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&h>=i.time.to-e+100&&(s=p)}if(isFinite(this.bufferLimit)&&ju(this.sourceBuffer.buffered)>=this.bufferLimit){let d=at(this.sourceBuffer.buffered,e),h=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,d<h);return}let o=[];if(!this.activeSegments.size&&(o=this.selectForwardBufferSegments(r,t.segmentReference.type,s),o.length)){let d="auto";if(this.tuning.dash.useFetchPriorityHints&&i)if(o.includes(i))d="high";else{let h=(0,Yr.default)(o,0);h&&h.time.from-i.time.to>=this.forwardBufferTarget/2&&(d="low")}this.loadSegments(o,t,d)}(!this.preloadOnly&&!this.allInitsLoaded&&i&&i.status==="fed"&&!o.length&&at(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let u=(0,Yr.default)(r,-1);u&&u.status==="fed"&&(this.fullyBuffered$.next(!0),this.isLive||this.onLastSegment$.next(i===u))}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}searchGaps(e,t){this.gaps=[];let r=0,i=this.isLive?this.liveInitialAdditionalOffset:0;for(let s of e)Math.trunc(s.time.from-r)>0&&this.gaps.push({representation:t.id,from:r,to:s.time.from+i}),r=s.time.to;da(t.duration)&&t.duration-r>0&&this.gaps.push({representation:t.id,from:r,to:t.duration})}getActualLiveStartingSegments(e){let t=e.segments,r=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,i=[],s=0,n=t.length-1;do i.unshift(t[n]),s+=t[n].time.to-t[n].time.from,n--;while(s<r&&n>=0);return this.liveInitialAdditionalOffset=s-r,this.isActiveLowLatency()?[i[0]]:i}getLiveSegmentsToLoadState(e){let t=e==null?void 0:e.streams[this.kind].flatMap(i=>i.representations).find(i=>i.id===this.downloadingRepresentationId);if(!t)return;let r=this.segments.get(t.id);if(r!=null&&r.length)return{from:r[0].time.from,to:r[r.length-1].time.to}}updateLive(e){var r,i,s,n;let t=(r=e==null?void 0:e.streams[this.kind].flatMap(o=>o.representations))!=null?r:[];for(let o of t){if(!o||!Re(o.segmentReference))return;let u=o.segmentReference.segments.map(h=>D(A({},h),{status:"none",size:void 0})),l=(i=this.segments.get(o.id))!=null?i:[],c=(n=(s=(0,Yr.default)(l,-1))==null?void 0:s.time.to)!=null?n:0,d=u==null?void 0:u.findIndex(h=>Math.floor(c)>=Math.floor(h.time.from)&&Math.floor(c)<=Math.floor(h.time.to));if(d===-1){this.liveUpdateSegmentIndex=0;let h=this.getActualLiveStartingSegments(o.segmentReference);this.segments.set(o.id,h)}else{let h=u.slice(d+1);this.segments.set(o.id,[...l,...h])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;ae(e);let t=this.segments.get(e);if(t!=null&&t.length){let r=t[t.length-1];this.updateLowLatencyLiveIfNeeded(r)}}startAccumulateBuffer(){this.bufferAccumulation.enabled=!0}resetAccumulateBufferAfterStall(){var s;ae(this.playingRepresentationId);let e=(s=this.representations.get(this.playingRepresentationId))==null?void 0:s.duration;ae(e);let{shortVideoDuration:t,shortVideoBufferStallSizeMs:r,longVideoBufferStallSizeMs:i}=this.tuning.dash.accumulationBufferStallSize;this.bufferAccumulation={enabled:!1,targetBufferSizeMs:e<=t?r:i,accumulatedBufferSizeMs:0,accumulated:[]}}updateLowLatencyLiveIfNeeded(e){var t;for(let r of this.representations.values()){let i=r.segmentReference;if(!Re(i))return;let s=(t=this.segments.get(r.id))!=null?t:[],n=s.find(u=>Math.floor(u.time.from)===Math.floor(e.time.from));if(n&&!isFinite(n.time.to)&&(n.time.to=e.time.to),!!!s.find(u=>Math.floor(u.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let u=Math.round(e.time.to*i.timescale/1e3).toString(10),l=mt(i.segmentTemplateUrl,{segmentTime:u});s.push({status:"none",time:{from:e.time.to,to:1/0},url:l})}}}findSegmentStartTime(e){var s,n,o;let t=(n=(s=this.switchingToRepresentationId)!=null?s:this.downloadingRepresentationId)!=null?n:this.playingRepresentationId;if(!t)return;let r=this.segments.get(t);if(!r)return;let i=r.find(u=>u.time.from<=e&&u.time.to>=e);return(o=i==null?void 0:i.time.from)!=null?o:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){var e;if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),(e=this.sourceBufferTaskQueue)==null||e.destroy(),this.gapDetectionIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer){this.mediaSource.readyState==="open"&&this.abortBuffer();try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(t){if(!(t instanceof DOMException&&t.name==="NotFoundError"))throw t}}this.sourceBuffer=null,this.downloadAbortController.abort(),this.switchAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,r){return this.isLive?this.selectForwardBufferSegmentsLive(e,r):this.selectForwardBufferSegmentsRecord(e,t,r)}selectForwardBufferSegmentsLive(e,t){let r=e.findIndex(i=>t>=i.time.from&&t<i.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=r),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,r){let i=e.findIndex(({status:d,time:{from:h,to:p}},f)=>{let b=h<=r&&p>=r,g=h>r||b||f===0&&r===0,T=Math.min(this.forwardBufferTarget,this.bufferLimit),y=this.preloadOnly&&h<=r+T||p<=r+T;return(d==="none"||d==="partially_ejected"&&g&&y&&this.sourceBuffer&&!(Lt(this.sourceBuffer.buffered,h)&&Lt(this.sourceBuffer.buffered,p)))&&g&&y});if(i===-1)return[];if(t!=="byteRange")return e.slice(i,i+1);let s=e,n=0,o=0,u=[],l=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,c=this.preloadOnly?this.forwardBufferTarget:0;for(let d=i;d<s.length&&(n<=l||o<=c);d++){let h=s[d];if(n+=h.byte.to+1-h.byte.from,o+=h.time.to+1-h.time.from,h.status==="none"||h.status==="partially_ejected")u.push(h);else break}return u}loadSegments(e,t,r="auto"){return w(this,null,function*(){Re(t.segmentReference)?yield this.loadTemplateSegment(e[0],t,r):yield this.loadByteRangeSegments(e,t,r)})}loadTemplateSegment(e,t,r="auto"){return w(this,null,function*(){e.status="downloading";let i={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(i);let{range:s,url:n,signal:o,onProgress:u,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(yield sr(o,function(){return Z(this,null,function*(){let c=ol(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(d=>setTimeout(d,c))})}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let c=yield this.fetcher.fetch(n,{range:s,signal:o,onProgress:u,priority:r,isLowLatency:this.isActiveLowLatency()});if(this.lastDataObtainedTimestampMs=Xs(),!c)return;let d=new DataView(c);if(!isFinite(i.segment.time.to)){let h=t.segmentReference.timescale,p=la(t.mime);i.segment.time.to=p.getChunkEndTime(d,h)}u&&i.feedingBytes&&l?yield Promise.all(l):yield this.sourceBufferTaskQueue.append(d,o),i.segment.status="downloaded",this.onSegmentFullyAppended(i,t.id),this.failedDownloads=0}catch(c){this.abortActiveSegments([e]),ca(c)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}})}updateRepresentationsBaseUrlIfNeeded(){if(!this.tuning.dash.enableBaseUrlSupport||!this.baseUrls.length||this.failedDownloads<=this.tuning.dash.maxSegmentRetryCount)return;this.baseUrlsIndex=(this.baseUrlsIndex+1)%this.baseUrls.length;let e=this.baseUrls[this.baseUrlsIndex];for(let t of this.representations.values())Re(t.segmentReference)?t.segmentReference.baseUrl=e:t.segmentReference.url=e}loadByteRangeSegments(e,t,r="auto"){return w(this,null,function*(){if(!e.length)return;for(let u of e)u.status="downloading",this.activeSegments.add({segment:u,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:i,url:s,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(yield sr(n,function(){return Z(this,null,function*(){let u=ol(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),nl(window,"online").pipe(TR()).subscribe(()=>{l(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{yield this.fetcher.fetch(s,{range:i,onProgress:o,signal:n,priority:r}),this.lastDataObtainedTimestampMs=Xs(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),ca(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}})}prepareByteRangeFetchSegmentParams(e,t){if(Re(t.segmentReference))throw new Error("Representation is not byte range type");let r=t.segmentReference.url,i={from:(0,Yr.default)(e,0).byte.from,to:(0,Yr.default)(e,-1).byte.to},{signal:s}=this.downloadAbortController;return{url:r,range:i,signal:s,onProgress:(o,u)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=Xs(),this.onSomeByteRangesDataLoaded({dataView:o,loaded:u,signal:s,onSegmentAppendFailed:()=>this.abort(),globalFrom:i?i.from:0,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:Ct.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!Re(t.segmentReference))throw new Error("Representation is not template type");let r=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&r.searchParams.set("low-latency","yes");let i=r.toString(),{signal:s}=this.downloadAbortController,n=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(l,c)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=Xs();let d=this.onSomeTemplateDataLoaded({dataView:l,loaded:c,signal:s,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(d)}catch(d){this.error$.next({id:"SegmentFeeding",category:Ct.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:d})}}:void 0;return{url:i,signal:s,onProgress:u,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)e.includes(t.segment)&&this.abortSegment(t.segment)}onSomeTemplateDataLoaded(n){return w(this,arguments,function*({dataView:e,representationId:t,loaded:r,onSegmentAppendFailed:i,signal:s}){if(!this.activeSegments.size)return;let o=this.representations.get(t);if(o)for(let u of this.activeSegments){let{segment:l}=u;if(u.representationId===t){if(s.aborted){i();continue}if(u.loadedBytes=r,u.loadedBytes>u.feedingBytes){let c=new DataView(e.buffer,e.byteOffset+u.feedingBytes,u.loadedBytes-u.feedingBytes),d=la(o.mime).parseFeedableSegmentChunk(c,this.isLive);d!=null&&d.byteLength&&(l.status="partially_fed",u.feedingBytes+=d.byteLength,yield this.sourceBufferTaskQueue.append(d),u.fedBytes+=d.byteLength)}}}})}onSomeByteRangesDataLoaded(o){return w(this,arguments,function*({dataView:e,representationId:t,globalFrom:r,loaded:i,signal:s,onSegmentAppendFailed:n}){if(!this.activeSegments.size)return;let u=this.representations.get(t);if(u)for(let l of this.activeSegments){let{segment:c}=l;if(l.representationId!==t)continue;if(s.aborted){n();continue}let d=c.byte.from-r,h=c.byte.to-r,p=h-d+1,f=d<i,b=h<=i;if(!f)continue;let g=la(u.mime),T=this.tuning.dash.enableSubSegmentBufferFeeding&&(Rg(g)||this.bufferAccumulation.targetBufferSizeMs===0);if(c.status==="downloading"&&b){c.status="downloaded";let y=new DataView(e.buffer,e.byteOffset+d,p),S=this.getCurrentPosition();da(S)&&(this.bufferAccumulation.accumulatedBufferSizeMs=c.time.to-S,this.bufferAccumulation.accumulated.push({dataView:y,segmentProgress:l}),this.activeSegments.delete(l));let I=B=>w(this,[B],function*({dataView:E,segmentProgress:k}){(yield this.sourceBufferTaskQueue.append(E,s))&&!s.aborted?this.onSegmentFullyAppended(k,t):n()});this.bufferAccumulation.enabled&&this.bufferAccumulation.accumulatedBufferSizeMs>this.bufferAccumulation.targetBufferSizeMs?(this.bufferAccumulation.accumulated.forEach(I),this.resetAccumulateBufferAfterStall()):(!this.bufferAccumulation.enabled||!this.bufferAccumulation.targetBufferSizeMs||$e(S))&&(I({dataView:y,segmentProgress:l}),this.resetAccumulateBufferAfterStall())}else if(T&&(c.status==="downloading"||c.status==="partially_fed")&&(l.loadedBytes=Math.min(p,i-d),l.loadedBytes>l.feedingBytes)){let y=new DataView(e.buffer,e.byteOffset+d+l.feedingBytes,l.loadedBytes-l.feedingBytes),S=l.loadedBytes===p?y:g.parseFeedableSegmentChunk(y);S!=null&&S.byteLength&&(c.status="partially_fed",l.feedingBytes+=S.byteLength,(yield this.sourceBufferTaskQueue.append(S,s))&&!s.aborted?(l.fedBytes+=S.byteLength,l.fedBytes===p&&this.onSegmentFullyAppended(l,t)):n())}}})}onSegmentFullyAppended(e,t){var r;this.tuning.useSafariEndlessRequestBugfix&&(ae(this.sourceBuffer),Lt(this.sourceBuffer.buffered,e.segment.time.from,10)&&Lt(this.sourceBuffer.buffered,e.segment.time.to,10)||this.error$.next({id:"SafariEmptyAppendBuffer",category:Ct.VIDEO_PIPELINE,message:"Safari stuck on empty result of adding segment to source buffer"})),this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status="fed",sl(e.segment)&&(e.segment.size=e.fedBytes);for(let i of this.representations.values())if(i.id!==t)for(let s of(r=this.segments.get(i.id))!=null?r:[])s.status==="fed"&&Math.round(s.time.from)===Math.round(e.segment.time.from)&&Math.round(s.time.to)===Math.round(e.segment.time.to)&&(s.status="none");ae(this.sourceBuffer),this.updateLowLatencyLiveIfNeeded(e.segment),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment]),this.tuning.useNewPruneBufferStrategy&&this.pruneBuffer(this.getCurrentPosition(),1/0,!1)}abortSegment(e){e.status==="partially_fed"?e.status="partially_ejected":e.status!=="partially_ejected"&&(e.status="none");for(let t of this.activeSegments.values())if(t.segment===e){this.activeSegments.delete(t);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(let[i,s]of this.initData.entries()){let n=s instanceof Promise;t||(t=n),s===null&&(e=i)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let r=this.representations.get(e);r&&(this.initLoadIdleCallback=Uu(()=>(0,lS.default)(this.loadInit(r,"low",!1),()=>this.initLoadIdleCallback=null)))}loadInit(e,t="auto",r=!1){return w(this,null,function*(){let i=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!r&&this.failedDownloads>0?sr(this.destroyAbortController.signal,function(){return Z(this,null,function*(){let o=ol(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))})}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,la(e.mime),i)).then(o=>w(this,null,function*(){if(!o)return;let{init:u,dataView:l,segments:c}=o,d=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,d);let h=c;this.isLive&&Re(e.segmentReference)&&(h=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,h),u&&this.parsedInitData.set(e.id,u)})).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),r&&this.error$.next({id:"LoadInits",category:Ct.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n})}dropBuffer(){return w(this,null,function*(){for(let e of this.segments.values())for(let t of e)t.status="none";yield this.pruneBuffer(0,1/0,!0)})}pruneBuffer(e,t,r=!1){return w(this,null,function*(){if(!this.sourceBuffer||!this.playingRepresentationId||$e(e)||this.sourceBuffer.updating)return!1;let i=[],s=0,n=u=>{u.sort((c,d)=>c.from-d.from);let l=[u[0]];for(let c=1;c<u.length;c++){let{from:d,to:h}=u[c],p=l[l.length-1];p.to>=d?p.to=Math.max(p.to,h):l.push(u[c])}return l},o=u=>{var c;if(s>=t)return i;i.push(A({},u.time)),i=n(i);let l=sl(u)?(c=u.size)!=null?c:0:u.byte.to-u.byte.from;s+=l};for(let u of this.segments.values())for(let l of u){let c=l.time.to<=e-this.tuning.dash.bufferPruningSafeZone,d=l.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(c||d)&&l.status==="fed"&&o(l)}for(let u=0;u<this.sourceBuffer.buffered.length;u++){let l=this.sourceBuffer.buffered.start(u)*1e3,c=this.sourceBuffer.buffered.end(u)*1e3,d=0;for(let h of this.segments.values())for(let p of h)["none","partially_ejected"].includes(p.status)&&Math.round(p.time.from)<=Math.round(l)&&Math.round(p.time.to)>=Math.round(c)&&d++;if(d===this.segments.size){let h={time:{from:l,to:c},url:"",status:"none"};o(h)}}if(i.length&&r){let u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let l of this.segments.values())for(let c of l)c.time.from>=e+u&&c.status==="fed"&&o(c)}return i.length?(yield Promise.all(i.map(l=>this.sourceBufferTaskQueue.remove(l.from,l.to)))).reduce((l,c)=>l||c,!1):!1})}abortBuffer(){if(!this.sourceBuffer||this.mediaSource.readyState!=="open")return;let e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;this.sourceBufferTaskQueue.abort(t)}getDebugBufferState(){if(!(!this.sourceBuffer||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}getForwardBufferDuration(){let e=this.getCurrentPosition();return!this.sourceBuffer||!this.sourceBuffer.buffered.length||$e(e)?0:at(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(this.sourceBuffer)for(let r of t){let i={representation:e,from:r.time.from,to:r.time.to};for(let s=0;s<this.sourceBuffer.buffered.length;s++){let n=this.sourceBuffer.buffered.start(s)*1e3,o=this.sourceBuffer.buffered.end(s)*1e3;if(!(o<=r.time.from||n>=r.time.to)){if(n<=r.time.from&&o>=r.time.to){i=void 0;break}o>r.time.from&&o<r.time.to&&(i.from=o),n<r.time.to&&n>r.time.from&&(i.to=n)}}i&&i.to-i.from>1&&!this.gaps.some(s=>i&&s.from===i.from&&s.to===i.to)&&this.gaps.push(i)}}detectGapsWhenIdle(e,t){if(!this.gapDetectionIdleCallback){ae(this.sourceBuffer);for(let r=0;r<this.sourceBuffer.buffered.length;r++)this.gaps=this.gaps.filter(i=>this.sourceBuffer&&(Math.round(i.from)<Math.round(this.sourceBuffer.buffered.start(r)*1e3)||Math.round(i.to)>Math.round(this.sourceBuffer.buffered.end(r)*1e3)));this.gapDetectionIdleCallback=Uu(()=>{try{this.detectGaps(e,t)}catch(r){this.error$.next({id:"GapDetection",category:Ct.WTF,message:"detectGaps threw",thrown:r})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if($e(this.sourceBuffer)||$e(this.playingRepresentationId))return;let e=[];for(let r=0;r<this.sourceBuffer.buffered.length;r++){let i=Math.floor(this.sourceBuffer.buffered.start(r)*1e3),s=Math.ceil(this.sourceBuffer.buffered.end(r)*1e3);e.push({from:i,to:s})}let t=100;for(let r of this.segments.values())for(let i of r){let{status:s}=i;if(s!=="fed"&&s!=="partially_ejected")continue;let n=Math.floor(i.time.from),o=Math.ceil(i.time.to),u=e.some(c=>c.from-t<=n&&c.to+t>=o),l=e.filter(c=>n>=c.from&&n<c.to-t||o>c.from+t&&o<=c.to);u||(l.length===1?i.status="partially_ejected":this.gaps.some(c=>c.from===i.time.from||c.to===i.time.to)?i.status="partially_ejected":i.status="none")}}};var fa=a=>{let e=new URL(a);return e.searchParams.set("quic","1"),e.toString()};var cS=a=>{var s;let e=a.get("X-Delivery-Type"),t=a.get("X-Reused"),r=e===null?"http1":e!=null?e:void 0,i=t===null?void 0:(s={1:!0,0:!1}[t])!=null?s:void 0;return{type:r,reused:i}};import{abortable as ma,assertNever as pS,fromEvent as hS,merge as xR,now as ba,Subscription as PR,ValueSubject as ul,flattenObject as Qr}from"@vkontakte/videoplayer-shared";var dS=a=>{let e=new URL(a);return e.searchParams.set("enable-subtitles","yes"),e.toString()};var Zs=class{constructor({throughputEstimator:e,requestQuic:t,tracer:r,compatibilityMode:i=!1,useEnableSubtitlesParam:s=!1}){this.lastConnectionType$=new ul(void 0);this.lastConnectionReused$=new ul(void 0);this.lastRequestFirstBytes$=new ul(void 0);this.abortAllController=new ke;this.subscription=new PR;this.fetchManifest=ma(this.abortAllController.signal,function(e){return Z(this,null,function*(){let t=this.tracer.createComponentTracer("FetchManifest"),r=e;this.requestQuic&&(r=fa(r)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(r=dS(r));let i=yield ht(r,{signal:this.abortAllController.signal}).catch(ga);return i?(t.log("success",Qr({url:r,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(i.headers),i.text()):(t.error("error",Qr({url:r,message:"No data in request manifest"})),t.end(),null)})}.bind(this));this.fetch=ma(this.abortAllController.signal,function(l){return Z(this,arguments,function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:r,onProgress:i,priority:s="auto",signal:n,measureThroughput:o=!0,isLowLatency:u=!1}={}){var R,U;let c=e,d=new Headers,h=this.tracer.createComponentTracer("Fetch");if(r)switch(t){case 0:{d.append("Range",`bytes=${r.from}-${r.to}`);break}case 1:{let L=new URL(c,location.href);L.searchParams.append("bytes",`${r.from}-${r.to}`),c=L.toString();break}default:pS(t)}this.requestQuic&&(c=fa(c));let p=this.abortAllController.signal,f;if(n){let L=new ke;if(f=xR(hS(this.abortAllController.signal,"abort"),hS(n,"abort")).subscribe(()=>{try{L.abort()}catch(W){ga(W)}}),this.abortAllController.signal.aborted||n.aborted)try{L.abort()}catch(W){ga(W)}p=L.signal}let b=ba();h.log("startRequest",Qr({url:c,priority:s,rangeMethod:t,range:r,isLowLatency:u,requestStartedAt:b}));let g=yield ht(c,{priority:s,headers:d,signal:p}).catch(ga),T=ba();if(!g)return h.error("error",{message:"No response in request"}),h.end(),f==null||f.unsubscribe(),null;if((R=this.throughputEstimator)==null||R.addRawRtt(T-b),!g.ok||!g.body){f==null||f.unsubscribe();let L=`Fetch error ${g.status}: ${g.statusText}`;return h.error("error",{message:L}),h.end(),Promise.reject(new Error(`Fetch error ${g.status}: ${g.statusText}`))}if(this.onHeadersReceived(g.headers),!i&&!o){f==null||f.unsubscribe();let L=ba(),W={requestStartedAt:b,requestEndedAt:L,duration:L-b};return h.log("endRequest",Qr(W)),h.end(),g.arrayBuffer()}let[y,S]=g.body.tee(),I=y.getReader();o&&((U=this.throughputEstimator)==null||U.trackStream(S,u));let E=0,k=new Uint8Array(0),B=!1,G=L=>{f==null||f.unsubscribe(),B=!0,ga(L)},V=ma(p,function(v){return Z(this,arguments,function*({done:L,value:W}){if(E===0&&this.lastRequestFirstBytes$.next(ba()-b),p.aborted){f==null||f.unsubscribe();return}if(!L&&W){let $=new Uint8Array(k.length+W.length);$.set(k),$.set(W,k.length),k=$,E+=W.byteLength,i==null||i(new DataView(k.buffer),E),yield I==null?void 0:I.read().then(V,G)}})}.bind(this));yield I==null?void 0:I.read().then(V,G),f==null||f.unsubscribe();let M=ba(),_={failed:B,requestStartedAt:b,requestEndedAt:M,duration:M-b};return B?(h.error("endRequest",Qr(_)),h.end(),null):(h.log("endRequest",Qr(_)),h.end(),k.buffer)})}.bind(this));this.fetchByteRangeRepresentation=ma(this.abortAllController.signal,function(e,t,r){return Z(this,null,function*(){var T;if(e.type!=="byteRange")return null;let{from:i,to:s}=e.initRange,n=i,o=s,u=!1,l,c;e.indexRange&&(l=e.indexRange.from,c=e.indexRange.to,u=s+1===l,u&&(n=Math.min(l,i),o=Math.max(c,s))),n=Math.min(n,0);let d=yield this.fetch(e.url,{range:{from:n,to:o},priority:r,measureThroughput:!1});if(!d)return null;let h=new DataView(d,i-n,s-n+1);if(!t.validateData(h))throw new Error("Invalid media file");let p=t.parseInit(h),f=(T=e.indexRange)!=null?T:t.getIndexRange(p);if(!f)throw new ReferenceError("No way to load representation index");let b;if(u)b=new DataView(d,f.from-n,f.to-f.from+1);else{let y=yield this.fetch(e.url,{range:f,priority:r,measureThroughput:!1});if(!y)return null;b=new DataView(y)}let g=t.parseSegments(b,p,f);return{init:p,dataView:new DataView(d),segments:g}})}.bind(this));this.fetchTemplateRepresentation=ma(this.abortAllController.signal,function(e,t){return Z(this,null,function*(){if(e.type!=="template")return null;let r=new URL(e.initUrl,e.baseUrl).toString(),i=yield this.fetch(r,{priority:t,measureThroughput:!1});return i?{init:null,segments:e.segments.map(n=>D(A({},n),{status:"none",size:void 0})),dataView:new DataView(i)}:null})}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=i,this.tracer=r.createComponentTracer("Fetcher"),this.useEnableSubtitlesParam=s}onHeadersReceived(e){let{type:t,reused:r}=cS(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(r)}fetchRepresentation(e,t,r="auto"){return w(this,null,function*(){var s,n;let{type:i}=e;switch(i){case"byteRange":return(s=yield this.fetchByteRangeRepresentation(e,t,r))!=null?s:null;case"template":return(n=yield this.fetchTemplateRepresentation(e,r))!=null?n:null;default:pS(i)}})}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}},ga=a=>{if(!ca(a))throw a};var nr=(a,e,t)=>t*e+(1-t)*a,ll=(a,e)=>a.reduce((t,r)=>t+r,0)/e,fS=(a,e,t,r)=>{let i=0,s=t,n=ll(a,e),o=e<r?e:r;for(let u=0;u<o;u++)a[s]>n?i++:i--,s=(a.length+s-1)%a.length;return Math.abs(i)===o};import{isNullable as AR,ValueSubject as mS}from"@vkontakte/videoplayer-shared";var Dt=class{constructor(e){this.prevReported=void 0;this.pastMeasures=[];this.takenMeasures=0;this.measuresCursor=0;var r;this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new mS(e.initial),this.debounced$=new mS(e.initial);let t=(r=e.label)!=null?r:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new de(`raw_${t}`),this.smoothedSeries$=new de(`smoothed_${t}`),this.reportedSeries$=new de(`reported_${t}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,r=0;for(let o=0;o<this.pastMeasures.length;o++)this.pastMeasures[o]!==void 0&&(t+=et(this.pastMeasures[o]-this.smoothed,2),r++);this.takenMeasures=r,t/=r;let i=Math.sqrt(t),s=this.smoothed+this.params.deviationFactor*i,n=this.smoothed-this.params.deviationFactor*i;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(e),this.updateSmoothedValue(e),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),!(this.smoothed>s||this.smoothed<n)&&(AR(this.prevReported)||Math.abs(this.smoothed-this.prevReported)/this.prevReported>=this.params.changeThreshold)&&(this.prevReported=this.smoothed,this.debounced$.next(this.smoothed),this.reportedSeries$.next(this.smoothed))}};var en=class extends Dt{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=nr(this.slow,e,this.params.emaAlphaSlow),this.fast=nr(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var tn=class extends Dt{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=ll(this.pastMeasures,this.takenMeasures);this.emaSmoothed=nr(this.emaSmoothed,e,this.params.emaAlpha);let r=fS(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=r?this.emaSmoothed:t}};var rn=class extends Dt{constructor(t){super(t);this.furtherValues=[];this.currentTopExtremumValue=0;this.extremumInterval=t.extremumInterval}next(t){this.currentTopExtremumValue<=t?(this.currentTopExtremumValue=t,this.furtherValues=[]):this.furtherValues.length===this.extremumInterval?(super.next(this.currentTopExtremumValue),this.currentTopExtremumValue=t,this.furtherValues=[]):this.furtherValues.push(t)}updateSmoothedValue(t){this.smoothed=this.smoothed?nr(this.smoothed,t,this.params.emaAlpha):t}};var or=class{static getSmoothedValue(e,t,r){return r.type==="TwoEma"?new en({initial:e,emaAlphaSlow:r.emaAlphaSlow,emaAlphaFast:r.emaAlphaFast,changeThreshold:r.changeThreshold,fastDirection:t,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"}):new tn({initial:e,emaAlpha:r.emaAlpha,basisTrendChangeCount:r.basisTrendChangeCount,changeThreshold:r.changeThreshold,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"})}static getLiveEstimatedDelaySmoothedValue(e,t){return new rn(A({initial:e,label:"liveEdgeDelay"},t))}};var cl=(a,e)=>{a&&a.playbackRate!==e&&(a.playbackRate=e)};import{isNullable as wR,ValueSubject as kR}from"@vkontakte/videoplayer-shared";var Sa=class a{constructor(e,t){this.currentRepresentation$=new kR(null);this.maxRepresentations=4;this.representationsCursor=0;this.representations=[];this.currentSegment=null;this.getCurrentPosition=t.getCurrentPosition,this.processStreams(e)}updateLive(e){this.processStreams(e==null?void 0:e.streams.text)}seekLive(e){this.processStreams(e)}maintain(e=this.getCurrentPosition()){var t;if(!wR(e))for(let r of this.representations)for(let i of r){let s=i.segmentReference,n=s.segments.length,o=s.segments[0].time.from,u=s.segments[n-1].time.to;if(e<o||e>u)continue;let l=s.segments.find(c=>c.time.from<=e&&c.time.to>=e);!l||((t=this.currentSegment)==null?void 0:t.time.from)===l.time.from&&this.currentSegment.time.to===l.time.to||(this.currentSegment=l,this.currentRepresentation$.next(D(A({},i),{label:"Live Text",language:"ru",isAuto:!0,url:new URL(l.url,s.baseUrl).toString()})))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e!=null?e:[]){let r=a.filterRepresentations(t.representations);if(r){this.representations[this.representationsCursor]=r,this.representationsCursor=(this.representationsCursor+1)%this.maxRepresentations;break}}}static isSupported(e){return!!(e!=null&&e.some(t=>a.filterRepresentations(t.representations)))}static filterRepresentations(e){return e==null?void 0:e.filter(t=>t.kind==="text"&&"segmentReference"in t&&Re(t.segmentReference))}};var OR=["timeupdate","progress","play","seeked","stalled","waiting"],VR=["timeupdate","progress","loadeddata","playing","seeked"];var sn=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new yS;this.representationSubscription=new yS;this.state$=new C("none");this.currentVideoRepresentation$=new oe(void 0);this.currentVideoRepresentationInit$=new oe(void 0);this.currentAudioRepresentation$=new oe(void 0);this.currentVideoSegmentLength$=new oe(0);this.currentAudioSegmentLength$=new oe(0);this.error$=new vS;this.lastConnectionType$=new oe(void 0);this.lastConnectionReused$=new oe(void 0);this.lastRequestFirstBytes$=new oe(void 0);this.currentLiveTextRepresentation$=new oe(null);this.isLive$=new oe(!1);this.liveDuration$=new oe(0);this.liveAvailabilityStartTime$=new oe(void 0);this.bufferLength$=new oe(0);this.liveLoadBufferLength$=new oe(0);this.livePositionFromPlayer$=new oe(0);this.isActiveLowLatency$=new oe(!1);this.timeInWaiting=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.liveLastSeekOffset=0;this.forceEnded$=new vS;this.gapWatchdogActive=!1;this.destroyController=new ke;this.initManifest=dl(this.destroyController.signal,function(e,t,r){return Z(this,null,function*(){var i;this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=ne(t,r,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),(i=this.manifest)!=null&&i.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:Bt.PARSER,message:"No playable video representations"})})}.bind(this));this.updateManifest=dl(this.destroyController.signal,function(){return Z(this,null,function*(){var n,o;this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(u=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:Bt.NETWORK,message:"Failed to load manifest",thrown:u})});if(!e)return null;let t=null;try{t=aS(e!=null?e:"",this.manifestUrlString)}catch(u){let l=(n=mg(e))!=null?n:{id:"ManifestParsing",category:Bt.PARSER,message:"Failed to parse MPD manifest",thrown:u};this.error$.next(l)}if(!t)return null;let r=(u,l,c)=>{var d,h,p,f;return!!((h=(d=this.element)==null?void 0:d.canPlayType)!=null&&h.call(d,l)&&((f=(p=ft())==null?void 0:p.isTypeSupported)!=null&&f.call(p,`${l}; codecs="${c}"`))||u==="text")};t.dynamic&&this.isLive$.getValue()!==t.dynamic&&(this.isLive$.next(t.dynamic),this.liveDuration$.getValue()!==t.duration&&this.liveDuration$.next(-1*((o=t.duration)!=null?o:0)/1e3),this.liveAvailabilityStartTime$.getValue()!==t.liveAvailabilityStartTime&&this.liveAvailabilityStartTime$.next(t.liveAvailabilityStartTime));let i={text:t.streams.text,video:[],audio:[]};for(let u of["video","audio"]){let c=t.streams[u].filter(({mime:p,codecs:f})=>r(u,p,f)),d=new Set(c.map(({codecs:p})=>p)),h=fg(d);if(h&&(i[u]=c.filter(({codecs:p})=>p.startsWith(h))),u==="video"){let p=this.tuning.preferHDR,f=i.video.some(g=>g.hdr),b=i.video.some(g=>!g.hdr);LR.isHDR&&p&&f?i.video=i.video.filter(g=>g.hdr):b&&(i.video=i.video.filter(g=>!g.hdr))}}let s=D(A({},t),{streams:i});return this.tracer.log("updateManifestEnd",va(s)),s})}.bind(this));this.initRepresentations=dl(this.destroyController.signal,function(e,t,r){return Z(this,null,function*(){var h;this.tracer.log("initRepresentationsStart",va({initialVideo:e,initialAudio:t,sourceHls:r})),ur(this.manifest),ur(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let i=p=>{this.representationSubscription.add(lr(p,"error").pipe(pl(f=>{var b;return!!((b=this.element)!=null&&b.played.length)})).subscribe(f=>{this.error$.next({id:"VideoSource",category:Bt.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:f})}))};this.source=this.tuning.useManagedMediaSource?Jb():new MediaSource;let s=document.createElement("source");if(i(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),this.tuning.useManagedMediaSource&&Us())if(r){let p=document.createElement("source");i(p),p.type="application/x-mpegurl",p.src=r.url,this.element.appendChild(p)}else this.element.disableRemotePlayback=!0;this.isActiveLowLatency$.next(this.isLive$.getValue()&&this.tuning.dashCmafLive.lowLatency.isActive);let n={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLowLatency$.getValue(),manifest:this.manifest},o=this.manifest.streams.video.reduce((p,f)=>[...p,...f.representations],[]);if(this.videoBufferManager=new ha("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],SS(t)){let p=this.manifest.streams.audio.reduce((f,b)=>[...f,...b.representations],[]);this.audioBufferManager=new ha("audio",this.source,p,n),this.bufferManagers.push(this.audioBufferManager)}Sa.isSupported(this.manifest.streams.text)&&!this.tuning.dashCmafLive.lowLatency.isActive&&(this.liveTextManager=new Sa(this.manifest.streams.text,n)),this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$)),this.representationSubscription.add(hl(1e3).subscribe(p=>{var f;if((f=this.element)!=null&&f.paused){let b=yu(this.manifestUrlString,2);this.manifestUrlString=ne(this.manifestUrlString,b+1e3,2)}}));let u=()=>{var p;(p=this.stallWatchdogSubscription)==null||p.unsubscribe(),this.timeInWaiting=0};if(this.representationSubscription.add(cr(...VR.map(p=>lr(this.element,p))).pipe(fl(p=>this.element?at(this.element.buffered,this.element.currentTime*1e3):0),gS(),DR(p=>{p>this.tuning.dash.bufferEmptinessTolerance&&u()})).subscribe(this.bufferLength$)),this.representationSubscription.add(cr(lr(this.element,"ended"),this.forceEnded$).subscribe(()=>{u()})),this.isLive$.getValue()){this.representationSubscription.add(this.isActiveLowLatency$.pipe(gS()).subscribe(f=>cl(this.element,1))),this.representationSubscription.add(an({bufferLength:this.bufferLength$,isActiveLowLatency:this.isActiveLowLatency$}).pipe(pl(({bufferLength:f,isActiveLowLatency:b})=>b&&!!f)).subscribe(({bufferLength:f})=>this.liveEstimatedDelay.next(f))),this.representationSubscription.add(an({liveEstimatedDelay:this.liveEstimatedDelay.smoothed$,isActiveLowLatency:this.isActiveLowLatency$}).subscribe(({liveEstimatedDelay:f,isActiveLowLatency:b})=>{if(!b)return;let g=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,T=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,y=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,S=f-g,I=1;Math.abs(S)>T&&(I=1+Math.sign(S)*y),cl(this.element,I)})),this.representationSubscription.add(this.bufferLength$.subscribe(f=>{var g,T;let b=0;if(f){let y=((T=(g=this.element)==null?void 0:g.currentTime)!=null?T:0)*1e3;b=Math.min(...this.bufferManagers.map(I=>{var E,k;return(k=(E=I.getLiveSegmentsToLoadState(this.manifest))==null?void 0:E.to)!=null?k:y}))-y}this.liveLoadBufferLength$.getValue()!==b&&this.liveLoadBufferLength$.next(b)}));let p=0;this.representationSubscription.add(an({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(BR(1e3)).subscribe(g=>w(this,[g],function*({liveLoadBufferLength:f,bufferLength:b}){if(ur(this.element),this.isUpdatingLive)return;let T=this.element.playbackRate,y=yu(this.manifestUrlString,2),S=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,I=Math.min(S,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*T),E=this.tuning.dashCmafLive.normalizedActualBufferOffset*T,k=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*T,B=isFinite(f)?f:b,G=this.isActiveLowLatency$.getValue(),V=S<=this.tuning.live.activeLiveDelay&&y===0;this.isActiveLowLatency$.next(G&&V);let M="none";if(G?M="active_low_latency":this.tuning.dashCmafLive.lowLatency.isActive&&V?(this.isActiveLowLatency$.next(!0),this.bufferManagers.forEach(_=>_.proceedLowLatencyLive()),M="active_low_latency"):y!==0&&B<I?M="live_forward_buffering":B<I+k&&(M="live_with_target_offset"),isFinite(f)&&(p=f>p?f:p),M==="live_forward_buffering"||M==="live_with_target_offset"){let _=p-(I+E),R=this.normolizeLiveOffset(Math.trunc(y+_/T)),U=Math.abs(R-y),L;!f||U<=this.tuning.dashCmafLive.offsetCalculationError?L=y:R>0&&U>this.tuning.dashCmafLive.offsetCalculationError?L=R:L=0,this.manifestUrlString=ne(this.manifestUrlString,L,2)}M!=="none"&&M!=="active_low_latency"&&(p=0,this.updateLive())})))}let l=cr(...this.bufferManagers.map(p=>p.fullyBuffered$)).pipe(fl(()=>this.bufferManagers.every(p=>p.fullyBuffered$.getValue()))),c=cr(...this.bufferManagers.map(p=>p.onLastSegment$)).pipe(fl(()=>this.bufferManagers.some(p=>p.onLastSegment$.getValue())));this.representationSubscription.add(cr(this.forceEnded$,an({allBuffersFull:l,someBufferEnded:c}).pipe(pl(({allBuffersFull:p,someBufferEnded:f})=>p&&f))).subscribe(()=>{var p;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(f=>!f.updating))try{(p=this.source)==null||p.endOfStream()}catch(f){this.error$.next({id:"EndOfStream",category:Bt.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:f})}})),this.representationSubscription.add(cr(...this.bufferManagers.map(p=>p.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.subscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.subscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&(this.representationSubscription.add(this.audioBufferManager.playingRepresentation$.subscribe(this.currentAudioRepresentation$)),this.subscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$))),this.liveTextManager&&this.subscription.add(this.liveTextManager.currentRepresentation$.subscribe(this.currentLiveTextRepresentation$)),this.source.readyState!=="open"&&(yield new Promise(p=>{var f;return(f=this.source)==null?void 0:f.addEventListener("sourceopen",p)}));let d=[(h=this.manifest.duration)!=null?h:0,...[...this.manifest.streams.audio,...this.manifest.streams.video].flatMap(p=>p.representations).flatMap(p=>{let f=[];return p.duration&&f.push(p.duration),Re(p.segmentReference)&&p.segmentReference.totalSegmentsDurationMs&&f.push(p.segmentReference.totalSegmentsDurationMs),f})];this.source.duration=Math.max(...d)/1e3,this.audioBufferManager&&SS(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState("representations_ready"),this.tracer.log("initRepresentationsEnd")})}.bind(this));this.tick=()=>{var t,r,i;if(!this.element||!this.videoBufferManager)return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),(t=this.audioBufferManager)==null||t.maintain(e),(r=this.liveTextManager)==null||r.maintain(e),(this.videoBufferManager.gaps.length||(i=this.audioBufferManager)!=null&&i.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=hl(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),s=>{this.error$.next({id:"GapWatchdog",category:Bt.WTF,message:"Error handling gaps",thrown:s})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name),this.fetcher=new Zs({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer,useEnableSubtitlesParam:e.tuning.useEnableSubtitlesParam}),this.liveEstimatedDelay=or.getLiveEstimatedDelaySmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,A({},e.tuning.dashCmafLive.lowLatency.delayEstimator)),this.initTracerSubscription()}seekLive(e){return w(this,null,function*(){var r,i,s;ur(this.element);let t=this.normolizeLiveOffset(e);this.isActiveLowLatency$.next(this.tuning.dashCmafLive.lowLatency.isActive&&t===0),this.liveLastSeekOffset=t,this.manifestUrlString=ne(this.manifestUrlString,t,2),this.manifest=yield this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,yield(r=this.videoBufferManager)==null?void 0:r.seekLive(this.manifest.streams.video),yield(i=this.audioBufferManager)==null?void 0:i.seekLive(this.manifest.streams.audio),(s=this.liveTextManager)==null||s.seekLive(this.manifest.streams.text))})}initBuffer(){ur(this.element),this.state$.setState("running"),this.subscription.add(cr(...OR.map(e=>lr(this.element,e)),lr(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:Bt.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(lr(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(lr(this.element,"waiting").subscribe(()=>{var t,r,i;this.element&&this.element.readyState===2&&!this.element.seeking&&Lt(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{var f,b,g,T,y,S,I,E,k,B;if(!this.element)return;this.timeInWaiting+=1e3;let s={timeInWaiting:this.timeInWaiting},n=CR(),o=100,u=(b=(f=this.videoBufferManager)==null?void 0:f.lastDataObtainedTimestamp)!=null?b:0,l=(T=(g=this.audioBufferManager)==null?void 0:g.lastDataObtainedTimestamp)!=null?T:0,c=(S=(y=this.videoBufferManager)==null?void 0:y.getForwardBufferDuration())!=null?S:0,d=(E=(I=this.audioBufferManager)==null?void 0:I.getForwardBufferDuration())!=null?E:0,h=c<o&&n-u>this.tuning.dash.crashOnStallTWithoutDataTimeout,p=this.audioBufferManager&&d<o&&n-l>this.tuning.dash.crashOnStallTWithoutDataTimeout;if((h||p)&&this.timeInWaiting>this.tuning.dash.crashOnStallTWithoutDataTimeout||this.timeInWaiting>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${this.timeInWaiting} ms`);if(this.isLive$.getValue()&&this.timeInWaiting%5e3===0)this.seekLive(this.liveLastSeekOffset),s.liveLastSeekOffset=this.liveLastSeekOffset;else{let G=this.element.currentTime*1e3;(k=this.videoBufferManager)==null||k.maintain(G),(B=this.audioBufferManager)==null||B.maintain(G),s.position=G}this.tracer.log("stallIntervalCallback",va(s))};(t=this.videoBufferManager)==null||t.startAccumulateBuffer(),(r=this.audioBufferManager)==null||r.startAccumulateBuffer(),(i=this.stallWatchdogSubscription)==null||i.unsubscribe(),this.stallWatchdogSubscription=hl(1e3).subscribe(e,s=>{this.error$.next({id:"StallWatchdogCallback",category:Bt.NETWORK,message:"Can't restore DASH after stall.",thrown:s})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}switchRepresentation(e,t,r=!1){return w(this,null,function*(){let i={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return i==null?void 0:i.switchTo(t,r)})}seek(e,t){var i,s,n,o,u,l;ur(this.element),ur(this.videoBufferManager);let r;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?r=e:r=Math.max((i=this.videoBufferManager.findSegmentStartTime(e))!=null?i:e,(n=(s=this.audioBufferManager)==null?void 0:s.findSegmentStartTime(e))!=null?n:e),Lt(this.element.buffered,r)||(this.videoBufferManager.abort(),(o=this.audioBufferManager)==null||o.abort()),this.videoBufferManager.startAccumulateBuffer(),this.videoBufferManager.maintain(r),(u=this.audioBufferManager)==null||u.startAccumulateBuffer(),(l=this.audioBufferManager)==null||l.maintain(r),this.element.currentTime=r/1e3,this.tracer.log("seek",va({requestedPosition:e,forcePrecise:t,position:r}))}stop(){var e,t,r;this.tracer.log("stop"),(e=this.element)==null||e.querySelectorAll("source").forEach(i=>i.remove()),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),(t=this.videoBufferManager)==null||t.destroy(),this.videoBufferManager=null,(r=this.audioBufferManager)==null||r.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getStreams(){var e;return(e=this.manifest)==null?void 0:e.streams}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){var e;this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),((e=this.source)==null?void 0:e.readyState)==="open"&&Array.from(this.source.sourceBuffers).every(t=>!t.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}initTracerSubscription(){let e=MR(this.tracer.error.bind(this.tracer));this.error$.subscribe(e("error"))}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}updateLive(){return w(this,null,function*(){var e,t;this.isUpdatingLive=!0,this.manifest=yield this.updateManifest(),this.manifest&&((e=this.bufferManagers)==null||e.forEach(r=>r.updateLive(this.manifest)),(t=this.liveTextManager)==null||t.updateLive(this.manifest)),this.isUpdatingLive=!1})}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.getDebugBufferState();if(!e)return;let t={isJumpGapAfterSeekLive:this.isJumpGapAfterSeekLive,isActiveLowLatency:this.isActiveLowLatency$.getValue(),initialCurrentTime:this.element.currentTime};this.isJumpGapAfterSeekLive&&!this.isActiveLowLatency$.getValue()&&this.element.currentTime>e.to&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let r=this.element.currentTime*1e3,i=[],s=this.element.readyState===1?this.tuning.endGapTolerance:0;for(let n of this.bufferManagers)for(let o of n.gaps)n.playingRepresentation$.getValue()===o.representation&&o.from-s<=r&&o.to+s>r&&(this.element.duration*1e3-o.to<this.tuning.endGapTolerance?i.push(1/0):i.push(o.to));if(i.length){let n=Math.max(...i)+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,n===1/0?this.forceEnded$.next():(this.element.currentTime=n/1e3,t=D(A({},t),{gapEnds:i,jumpTo:n,resultCurrentTime:this.element.currentTime}),this.tracer.log("jumpGap",va(t)))}}};var nn=class{constructor(e,t){this.fov=e,this.orientation=t}};var on=class{constructor(e,t){this.rotating=!1;this.fading=!1;this.lastTickTS=0;this.lastCameraTurnTS=0;this.fadeStartSpeed=null;this.fadeTime=0;this.camera=e,this.options=t,this.rotationSpeed={x:0,y:0,z:0},this.fadeCorrection=1/et(this.options.speedFadeTime/1e3,2)}turnCamera(e=0,t=0,r=0){this.pointCameraTo(this.camera.orientation.x+e,this.camera.orientation.y+t,this.camera.orientation.z+r)}pointCameraTo(e=0,t=0,r=0){t=this.limitCameraRotationY(t);let i=e-this.camera.orientation.x,s=t-this.camera.orientation.y,n=r-this.camera.orientation.z;this.camera.orientation.x=e,this.camera.orientation.y=t,this.camera.orientation.z=r,this.lastCameraTurn={x:i,y:s,z:n},this.lastCameraTurnTS=Date.now()}setRotationSpeed(e,t,r){this.rotationSpeed.x=e!=null?e:this.rotationSpeed.x,this.rotationSpeed.y=t!=null?t:this.rotationSpeed.y,this.rotationSpeed.z=r!=null?r:this.rotationSpeed.z}startRotation(){this.rotating=!0}stopRotation(e=!1){e?(this.setRotationSpeed(0,0,0),this.fadeStartSpeed=null):this.startFading(this.rotationSpeed.x,this.rotationSpeed.y,this.rotationSpeed.z),this.rotating=!1}onCameraRelease(){if(this.lastCameraTurn&&this.lastCameraTurnTS){let e=Date.now()-this.lastCameraTurnTS;if(e<this.options.speedFadeThreshold){let t=(1-e/this.options.speedFadeThreshold)*this.options.rotationSpeedCorrection;this.startFading(this.lastCameraTurn.x*t,this.lastCameraTurn.y*t,this.lastCameraTurn.z*t)}}}startFading(e,t,r){this.setRotationSpeed(e,t,r),this.fadeStartSpeed=A({},this.rotationSpeed),this.fading=!0}stopFading(){this.fadeStartSpeed=null,this.fading=!0,this.fadeTime=0}limitCameraRotationY(e){return Math.max(-this.options.maxYawAngle,Math.min(e,this.options.maxYawAngle))}tick(e){if(!this.lastTickTS){this.lastTickTS=e,this.lastCameraTurnTS=Date.now();return}let t=e-this.lastTickTS,r=t/1e3;if(this.rotating)this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*r,this.rotationSpeed.y*this.options.rotationSpeedCorrection*r,this.rotationSpeed.z*this.options.rotationSpeedCorrection*r);else if(this.fading&&this.fadeStartSpeed){let i=-this.fadeCorrection*et(this.fadeTime/1e3,2)+1;this.setRotationSpeed(this.fadeStartSpeed.x*i,this.fadeStartSpeed.y*i,this.fadeStartSpeed.z*i),i>0?this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*r,this.rotationSpeed.y*this.options.rotationSpeedCorrection*r,this.rotationSpeed.z*this.options.rotationSpeedCorrection*r):(this.stopRotation(!0),this.stopFading()),this.fadeTime=Math.min(this.fadeTime+t,this.options.speedFadeTime)}this.lastTickTS=e}};var TS=`attribute vec2 a_vertex;
66
66
  attribute vec2 a_texel;
67
67
 
68
68
  varying vec2 v_texel;
@@ -116,5 +116,5 @@ void main(void) {
116
116
  // sample using new coordinates
117
117
  gl_FragColor = texture2D(u_texture, tc);
118
118
  }
119
- `;var un=class{constructor(e,t,r){this.videoInitialized=!1;this.active=!1;this.container=e,this.sourceVideoElement=t,this.params=r,this.canvas=this.createCanvas();let i=this.canvas.getContext("webgl");if(!i)throw new Error("Could not initialize WebGL context");this.gl=i,this.container.appendChild(this.canvas),this.camera=new nn(this.params.fov,this.params.orientation),this.cameraRotationManager=new on(this.camera,{rotationSpeed:this.params.rotationSpeed,maxYawAngle:this.params.maxYawAngle,rotationSpeedCorrection:this.params.rotationSpeedCorrection,degreeToPixelCorrection:this.params.degreeToPixelCorrection,speedFadeTime:this.params.speedFadeTime,speedFadeThreshold:this.params.speedFadeThreshold}),this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.textureMappingBuffer=this.createTextureMappingBuffer(),this.updateTextureMappingBuffer(),this.program=this.createProgram(),this.videoTexture=this.createTexture(),this.gl.useProgram(this.program),this.videoElementDataLoadedFn=this.onDataLoadedHandler.bind(this),this.renderFn=this.render.bind(this)}play(){this.active||(this.videoInitialized?this.doPlay():this.sourceVideoElement.readyState>=2?(this.videoInitialized=!0,this.doPlay()):this.sourceVideoElement.addEventListener("loadeddata",this.videoElementDataLoadedFn))}stop(){this.active=!1}startCameraManualRotation(e,t){this.cameraRotationManager.setRotationSpeed(e*this.params.rotationSpeed,t*this.params.rotationSpeed,0),this.cameraRotationManager.startRotation()}stopCameraManualRotation(e=!1){this.cameraRotationManager.stopRotation(e)}turnCamera(e,t){this.cameraRotationManager.turnCamera(e,t)}pointCameraTo(e,t){this.cameraRotationManager.pointCameraTo(e,t)}pixelToDegree(e){return{x:this.params.degreeToPixelCorrection*this.params.fov.x*-e.x/this.viewportWidth,y:this.params.degreeToPixelCorrection*this.params.fov.y*e.y/this.viewportHeight}}getCameraRotation(){return this.camera.orientation}holdCamera(){this.cameraRotationManager.stopRotation(!0)}releaseCamera(){this.cameraRotationManager.onCameraRelease()}destroy(){this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),this.stop(),this.canvas.remove()}setViewportSize(e,t){this.viewportWidth=e,this.viewportHeight=t,this.canvas.width=this.viewportWidth,this.canvas.height=this.viewportHeight,this.gl.viewport(0,0,this.canvas.width,this.canvas.height)}onDataLoadedHandler(){this.videoInitialized=!0,this.doPlay()}doPlay(){this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.active=!0,this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),requestAnimationFrame(this.renderFn)}render(e){this.cameraRotationManager.tick(e),this.updateTexture(),this.updateTextureMappingBuffer();let t=this.gl.getAttribLocation(this.program,"a_vertex"),r=this.gl.getAttribLocation(this.program,"a_texel"),i=this.gl.getUniformLocation(this.program,"u_texture"),s=this.gl.getUniformLocation(this.program,"u_focus");this.gl.enableVertexAttribArray(t),this.gl.enableVertexAttribArray(r),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.vertexBuffer),this.gl.vertexAttribPointer(t,2,this.gl.FLOAT,!1,0,0),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.vertexAttribPointer(r,2,this.gl.FLOAT,!1,0,0),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.uniform1i(i,0),this.gl.uniform2f(s,-this.camera.orientation.x,-this.camera.orientation.y),this.gl.drawArrays(this.gl.TRIANGLE_FAN,0,4),this.gl.bindTexture(this.gl.TEXTURE_2D,null),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),this.gl.disableVertexAttribArray(t),this.gl.disableVertexAttribArray(r),this.active&&requestAnimationFrame(this.renderFn)}createShader(e,t){let r=this.gl.createShader(t);if(!r)throw this.destroy(),new Error(`Could not create shader (${t})`);if(this.gl.shaderSource(r,e),this.gl.compileShader(r),!this.gl.getShaderParameter(r,this.gl.COMPILE_STATUS))throw this.destroy(),new Error("An error occurred while compiling the shader: "+this.gl.getShaderInfoLog(r));return r}createProgram(){let e=this.gl.createProgram();if(!e)throw this.destroy(),new Error("Could not create shader program");let t=this.createShader(TS,this.gl.VERTEX_SHADER),r=this.createShader(IS,this.gl.FRAGMENT_SHADER);if(this.gl.attachShader(e,t),this.gl.attachShader(e,r),this.gl.linkProgram(e),!this.gl.getProgramParameter(e,this.gl.LINK_STATUS))throw this.destroy(),new Error("Could not link shader program.");return e}createTexture(){let e=this.gl.createTexture();if(!e)throw this.destroy(),new Error("Could not create texture");return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.bindTexture(this.gl.TEXTURE_2D,null),e}updateTexture(){this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,!0),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.sourceVideoElement),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}createVertexBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create vertex buffer");let t=1,r=1,i=this.frameHeight/(this.frameWidth/this.viewportWidth);return i>this.viewportHeight?t=this.viewportHeight/i:r=i/this.viewportHeight,this.gl.bindBuffer(this.gl.ARRAY_BUFFER,e),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-t,-r,t,-r,t,r,-t,r]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),e}createTextureMappingBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create texture mapping buffer");return e}calculateTexturePosition(){let e=.5-this.camera.orientation.x/360,t=.5-this.camera.orientation.y/180,r=this.camera.fov.x/360/2,i=this.camera.fov.y/180/2,s=e-r,n=t-i,o=e+r,u=t-i,l=e+r,c=t+i,d=e-r,h=t+i;return[s,n,o,u,l,c,d,h]}updateTextureMappingBuffer(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([...this.calculateTexturePosition()]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}updateFrameSize(){this.frameWidth=this.sourceVideoElement.videoWidth,this.frameHeight=this.sourceVideoElement.videoHeight}createCanvas(){let e=document.createElement("canvas");return e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e}};var cr=class{constructor(e){this.subscription=new QR;this.videoState=new C("stopped");this.elementSize$=new zR(void 0);this.textTracksManager=new Oe;this.droppedFramesManager=new Os;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new Ci;this.audioTrackSwitchHistory=new Ci;this.syncPlayback=()=>{var n,o,u;let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),i=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(i.state==="requested"&&(r==null?void 0:r.to)!=="paused"&&e!=="stopped"&&t!=="stopped"){let l=(o=(n=this.liveOffset)==null?void 0:n.getTotalPausedTime())!=null?o:0;this.seek(i.position-l,i.forcePrecise)}if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.player.stop(),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),x(this.params.desiredState.playbackState,"stopped",!0));return}switch(e){case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();return;case"ready":t==="paused"?(this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="ready"&&x(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),(u=this.liveOffset)==null||u.pause(),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(r==null?void 0:r.to)==="playing"&&x(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.liveOffset?this.liveOffset.getTotalOffset()/1e3<Math.abs(this.params.output.duration$.getValue())?(this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(0,!1):this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&x(this.params.desiredState.playbackState,"paused");return;default:return UR(e)}}};this.init3DScene=e=>{var r,i,s;if(this.scene3D)return;this.scene3D=new un(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:((r=e.projectionData)==null?void 0:r.pose.yaw)||0,y:((i=e.projectionData)==null?void 0:i.pose.pitch)||0,z:((s=e.projectionData)==null?void 0:s.pose.roll)||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});let t=this.elementSize$.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};this.params=e,this.video=be(e.container,e.tuning),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(re(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.player=new sn({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode,tracer:this.tracer}),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params,r=ve(this.video),i=this.constructor.name,s=o=>{e.error$.next({id:i,category:bl.WTF,message:`${i} internal logic error`,thrown:o})};return{output:e,desiredState:t,observableVideo:r,genericErrorListener:s,connect:(o,u)=>this.subscription.add(o.subscribe(u,s))}}subscribe(){var l;let{output:e,desiredState:t,observableVideo:r,genericErrorListener:i,connect:s}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe(ES(c=>!!c.length),PS()).subscribe(c=>{this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:r.playing$,pause$:r.pause$,tracks:c})})),s(r.ended$,e.endedEvent$),s(r.looped$,e.loopedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentBuffer$),s(r.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),s(r.loadedMetadata$,e.loadedMetadataEvent$),s(this.player.error$,e.error$),s(this.player.lastConnectionType$,e.httpConnectionType$),s(this.player.lastConnectionReused$,e.httpConnectionReused$),s(this.player.isLive$,e.isLive$),s(this.player.lastRequestFirstBytes$.pipe(ES(GR),PS()),e.firstBytesEvent$),s(this.videoState.stateChangeEnded$.pipe(xS(c=>c.to)),this.params.output.playbackState$),this.subscription.add(r.seeked$.subscribe(e.seekedEvent$,i)),this.subscription.add(rt(this.video,t.isLooped,i)),this.subscription.add(Se(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Be(this.video,t.playbackRate,r.playbackRateState$,i)),s(YR(this.video),this.elementSize$),s(_e(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),x(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),x(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:c})=>{if(c==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let d=this.player.getStreams();if(qR(d,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let p=[];for(let f of d.audio){p.push(al(f));let b=[];for(let g of f.representations){let S=oS(g);b.push(S),this.audioTracksMap.set(S,{stream:f,representation:g})}this.audioStreamsMap.set(f,b)}this.params.output.availableAudioStreams$.next(p)}let h=[];for(let p of d.video){h.push(sl(p));let f=[];for(let b of p.representations){let g=nS(b);g&&(f.push(g),this.videoTracksMap.set(g,{stream:p,representation:b}))}this.videoStreamsMap.set(p,f)}if(this.params.output.availableVideoStreams$.next(h),this.textTracksManager)for(let p of d.text)for(let f of p.representations){let b=uS(p,f);this.textTracksMap.set(b,{stream:p,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())},i));let n=c=>e.error$.next({id:"RepresentationSwitch",category:bl.WTF,message:"Switching representations threw",thrown:c});this.subscription.add(ln(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$,jR(this.video,"progress")).subscribe(()=>{let c=this.player.state$.getState(),d=this.player.state$.getTransition();if(!["manifest_ready","running"].includes(c)||d)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let h=this.selectVideoAudioRepresentations();if(!h)return;let[p,f]=h,b=this.params.desiredState.autoVideoTrackLimits.getTransition();if(b&&this.params.output.autoVideoTrackLimits$.next(b.to),c==="manifest_ready")this.player.initRepresentations(p.id,f==null?void 0:f.id,this.params.sourceHls);else if(this.player.switchRepresentation("video",p.id).catch(n),f){let g=!!t.audioStream.getTransition();this.player.switchRepresentation("audio",f.id,g).catch(n)}},i)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:c})=>{this.scene3D&&c&&this.scene3D.pointCameraTo(c.x,c.y)})),this.subscription.add(this.elementSize$.subscribe(c=>{this.scene3D&&c&&this.scene3D.setViewportSize(c.width,c.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(gl()).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[h,{stream:p}]=d,f=this.params.desiredState.videoStream.getTransition();f&&f.to&&f.to.id===p.id&&this.params.desiredState.videoStream.setState(f.to),e.currentVideoTrack$.next(h),e.currentVideoStream$.next(sl(p))},i)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(gl()).subscribe(c=>{let d=[...this.audioTracksMap.entries()].find(([,{representation:b}])=>b.id===c);if(!d){e.currentAudioStream$.next(void 0);return}let[h,{stream:p}]=d,f=this.params.desiredState.audioStream.getTransition();f&&f.to&&f.to.id===p.id&&this.params.desiredState.audioStream.setState(f.to),e.currentAudioStream$.next(al(p))},i)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(c=>{var d,h;if(c!=null&&c.is3dVideo&&((d=this.params.tuning.spherical)!=null&&d.enabled))try{this.init3DScene(c),e.is3DVideo$.next(!0)}catch(p){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${p}`})}else this.destroy3DScene(),(h=this.params.tuning.spherical)!=null&&h.enabled&&e.is3DVideo$.next(!1)},i)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,i)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,i)),(l=this.textTracksManager)==null||l.connect(this.video,t,e);let o=t.playbackState.stateChangeStarted$.pipe(xS(({to:c})=>c==="ready"),gl());this.subscription.add(ln(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$).subscribe(()=>{let c=t.autoVideoTrackSwitching.getState(),h=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:c?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(h)})),this.subscription.add(ln(o,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let u=ln(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,WR(["init"])).pipe(HR(0));this.subscription.add(u.subscribe(this.syncPlayback,i))}selectVideoAudioRepresentations(){var k,B,G,V,M,_,w,U,L,W,v,$,Q;let{desiredState:e,output:t}=this.params,r=e.autoVideoTrackSwitching.getState(),i=(k=e.videoTrack.getState())==null?void 0:k.id,n=[...this.videoTracksMap.keys()].find(({id:N})=>N===i),o=t.currentVideoTrack$.getValue(),u=((V=(G=e.videoStream.getState())!=null?G:n&&((B=this.videoTracksMap.get(n))==null?void 0:B.stream))!=null?V:this.videoStreamsMap.size===1)?this.videoStreamsMap.keys().next().value:void 0;if(!u)return;let l=[...this.videoStreamsMap.keys()].find(({id:N})=>N===u.id),c=l&&this.videoStreamsMap.get(l);if(!c)return;let d=at(this.video.buffered,this.video.currentTime*1e3),h=r?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,p=Math.min(d/Math.min(h,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),f=(M=e.audioStream.getState())!=null?M:this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0,b=(_=[...this.audioStreamsMap.keys()].find(({id:N})=>N===(f==null?void 0:f.id)))!=null?_:this.audioStreamsMap.keys().next().value,g=0;if(b){if(n&&!r){let N=Ms(n,c,(w=this.audioStreamsMap.get(b))!=null?w:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);g=Math.max(g,(U=N==null?void 0:N.bitrate)!=null?U:-1/0)}if(o){let N=Ms(o,c,(L=this.audioStreamsMap.get(b))!=null?L:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);g=Math.max(g,(W=N==null?void 0:N.bitrate)!=null?W:-1/0)}}let S=$t(c,{container:this.elementSize$.getValue(),throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:g,forwardBufferHealth:p,current:o,visible:this.params.output.elementVisible$.getValue(),history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),y=r?S!=null?S:n:n!=null?n:S,T=b&&Nb(y,c,(v=this.audioStreamsMap.get(b))!=null?v:[],{throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:p,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),I=($=this.videoTracksMap.get(y))==null?void 0:$.representation,E=T&&((Q=this.audioTracksMap.get(T))==null?void 0:Q.representation);if(I&&E)return[I,E];if(I&&!E&&this.audioTracksMap.size===0)return[I,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){ye(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{var t;e||((t=this.liveOffset)==null||t.pause(),this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:bl.DOM,thrown:e}))}destroy(){var e;this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.destroy3DScene(),(e=this.textTracksManager)==null||e.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),ge(this.video),this.tracer.end()}};var ya=class extends cr{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 AS,interval as KR,map as JR}from"@vkontakte/videoplayer-shared";var Ta=class extends cr{constructor(e){super(e),this.liveOffset=new dt,this.textTracksManager=null}subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:r}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),r(t.timeUpdate$,e.liveBufferTime$),r(this.player.liveDuration$,e.duration$),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(AS({interval:KR(1e3),playbackRate:t.playbackRateState$}).subscribe(({playbackRate:i})=>{var s;if(this.videoState.getState()==="playing"){let n=e.position$.getValue()+(i-1);n<=0&&e.position$.next(n),(s=this.liveOffset)==null||s.resetTo(-n*1e3)}})).add(AS({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(JR(({liveBufferTime:i,liveAvailabilityStartTime:s})=>i&&s?i+s:void 0)).subscribe(e.liveTime$)).add(this.player.currentLiveTextRepresentation$.subscribe(i=>{if(i){let s=lS(i);this.params.output.availableTextTracks$.next([s])}}))}seek(e){this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),r=this.videoState.getState(),i=t==="paused"&&r==="paused",s=-e,n=Math.trunc(s/1e3<=Math.abs(this.params.output.duration$.getValue())?s:0);this.player.seekLive(n).then(()=>{var o;this.params.output.position$.next(e/1e3),(o=this.liveOffset)==null||o.resetTo(n,i)})}};var kS=je(Rs(),1);import{assertNever as Ia,assertNonNullable as wS,debounce as XR,ErrorCategory as cn,filter as ZR,isNonNullable as e$,isNullable as t$,map as dn,merge as r$,Observable as i$,observableFrom as a$,Subscription as s$,videoSizeToQuality as n$}from"@vkontakte/videoplayer-shared";var Je={};var zr=(a,e)=>new i$(t=>{let r=(i,s)=>t.next(s);return a.on(e,r),()=>a.off(e,r)}),Ea=class{constructor(e){this.subscription=new s$;this.videoState=new C("initializing");this.textTracksManager=new Oe;this.trackLevels=new Map;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),i=this.params.desiredState.seekState.getState();if(e!=="initializing")switch((r==null?void 0:r.to)!=="paused"&&i.state==="requested"&&this.seek(i.position),t){case"stopped":switch(e){case"stopped":break;case"ready":case"playing":case"paused":this.stop();break;default:Ia(e)}break;case"ready":switch(e){case"stopped":this.prepare();break;case"ready":case"playing":case"paused":break;default:Ia(e)}break;case"playing":switch(e){case"playing":break;case"stopped":this.prepare();break;case"ready":case"paused":this.playIfAllowed();break;default:Ia(e)}break;case"paused":switch(e){case"paused":break;case"stopped":this.prepare();break;case"ready":this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused");break;case"playing":this.pause();break;default:Ia(e)}break;default:Ia(t)}};this.video=be(e.container,e.tuning),this.params=e,this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(re(this.params.source.url)),this.loadHlsJs()}destroy(){var e,t;this.subscription.unsubscribe(),this.trackLevels.clear(),this.textTracksManager.destroy(),(e=this.hls)==null||e.detachMedia(),(t=this.hls)==null||t.destroy(),this.params.output.element$.next(void 0),ge(this.video)}loadHlsJs(){let e=!1,t=i=>{e||this.params.output.error$.next({id:i==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:cn.NETWORK,message:"Failed to load Hls.js",thrown:i}),e=!0},r=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);(0,kS.default)(import("hls.js").then(i=>{e||(Je.Hls=i.default,Je.Events=i.default.Events,this.init())},t),()=>{window.clearTimeout(r),e=!0})}init(){wS(Je.Hls,"hls.js not loaded"),this.hls=new Je.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState("stopped")}subscribe(){wS(Je.Events,"hls.js not loaded");let{desiredState:e,output:t}=this.params,r=l=>{t.error$.next({id:"HlsJsProvider",category:cn.WTF,message:"HlsJsProvider internal logic error",thrown:l})},i=ve(this.video),s=(l,c)=>this.subscription.add(l.subscribe(c,r));s(i.timeUpdate$,t.position$),s(i.durationChange$,t.duration$),s(i.ended$,t.endedEvent$),s(i.looped$,t.loopedEvent$),s(i.error$,t.error$),s(i.isBuffering$,t.isBuffering$),s(i.currentBuffer$,t.currentBuffer$),s(i.loadStart$,t.firstBytesEvent$),s(i.loadedMetadata$,t.loadedMetadataEvent$),s(i.playing$,t.firstFrameEvent$),s(i.canplay$,t.canplay$),s(i.seeked$,t.seekedEvent$),s(i.inPiP$,t.inPiP$),s(i.inFullscreen$,t.inFullscreen$),this.subscription.add(rt(this.video,e.isLooped,r)),this.subscription.add(Se(this.video,e.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(Be(this.video,e.playbackRate,i.playbackRateState$,r)),s(_e(this.video),t.elementVisible$),s(this.videoState.stateChangeEnded$.pipe(dn(l=>l.to)),this.params.output.playbackState$),this.subscription.add(zr(this.hls,Je.Events.ERROR).subscribe(l=>{var c;l.fatal&&t.error$.next({id:["HlsJsFatal",l.type,l.details].join("_"),category:cn.WTF,message:`HlsJs fatal ${l.type} ${l.details}, ${(c=l.err)==null?void 0:c.message} ${l.reason}`,thrown:l.error})})),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),x(e.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),x(e.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{var l;((l=this.videoState.getTransition())==null?void 0:l.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),s(zr(this.hls,Je.Events.MANIFEST_PARSED).pipe(dn(({levels:l})=>l.reduce((c,d)=>{var y,T;let h=d.name||d.height.toString(10),{width:p,height:f}=d,b=(T=Rt((y=d.attrs.QUALITY)!=null?y:""))!=null?T:n$({width:p,height:f});if(!b)return c;let g=d.attrs["FRAME-RATE"]?parseFloat(d.attrs["FRAME-RATE"]):void 0,S={id:h.toString(),quality:b,bitrate:d.bitrate/1e3,size:{width:p,height:f},fps:g};return this.trackLevels.set(h,{track:S,level:d}),c.push(S),c},[]))),t.availableVideoTracks$),s(zr(this.hls,Je.Events.MANIFEST_PARSED),l=>{if(l.subtitleTracks.length>0){let c=[];for(let d of l.subtitleTracks){let h=d.name,p=d.attrs.URI||"",f=d.lang;c.push({id:h,url:p,language:f,type:"internal"})}e.internalTextTracks.startTransitionTo(c)}}),s(zr(this.hls,Je.Events.LEVEL_LOADING).pipe(dn(({url:l})=>re(l))),t.hostname$),s(zr(this.hls,Je.Events.FRAG_CHANGED),l=>{var h,p,f,b;let{video:c,audio:d}=l.frag.elementaryStreams;t.currentVideoSegmentLength$.next((((h=c==null?void 0:c.endPTS)!=null?h:0)-((p=c==null?void 0:c.startPTS)!=null?p:0))*1e3),t.currentAudioSegmentLength$.next((((f=d==null?void 0:d.endPTS)!=null?f:0)-((b=d==null?void 0:d.startPTS)!=null?b:0))*1e3)}),this.subscription.add(At(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,l=>{this.hls.nextLevel=l?-1:this.hls.currentLevel,this.hls.loadLevel=l?-1:this.hls.loadLevel},{onError:r}));let n=l=>{var c;return(c=Array.from(this.trackLevels.values()).find(({level:d})=>d===l))==null?void 0:c.track},o=zr(this.hls,Je.Events.LEVEL_SWITCHED).pipe(dn(({level:l})=>n(this.hls.levels[l])));o.pipe(ZR(e$)).subscribe(t.currentVideoTrack$,r),this.subscription.add(At(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel]),l=>{var f;if(t$(l))return;let c=(f=this.trackLevels.get(l.id))==null?void 0:f.level;if(!c)return;let d=this.hls.levels.indexOf(c),h=this.hls.currentLevel,p=this.hls.levels[h];!p||c.bitrate>p.bitrate?this.hls.nextLevel=d:(this.hls.loadLevel=d,this.hls.loadLevel=d)},{changed$:o,onError:r})),s(i.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);let u=r$(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,a$(["init"])).pipe(XR(0));this.subscription.add(u.subscribe(this.syncPlayback,r))}prepare(){this.videoState.startTransitionTo("ready"),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}playIfAllowed(){return R(this,null,function*(){this.videoState.startTransitionTo("playing"),(yield ye(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:cn.DOM,thrown:t})))||(this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused",!0))})}pause(){this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}stop(){this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.hls.stopLoad(),this.hls.detachMedia(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState("stopped"),x(this.params.desiredState.playbackState,"stopped",!0)}};var RS="X-Playback-Duration",Sl=a=>R(void 0,null,function*(){var i;let e=yield ht(a),t=yield e.text(),r=(i=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t))==null?void 0:i[1];return r?parseInt(r,10):e.headers.has(RS)?parseInt(e.headers.get(RS),10):void 0});import{assertNever as p$,combine as h$,debounce as f$,ErrorCategory as hn,filter as m$,filterChanged as b$,isNonNullable as LS,isNullable as fn,map as MS,merge as g$,observableFrom as S$,Subscription as v$,ValueSubject as Tl,VideoQuality as y$}from"@vkontakte/videoplayer-shared";var yl=je(Oo(),1);import{videoSizeToQuality as o$,getExponentialDelay as u$}from"@vkontakte/videoplayer-shared";var l$=a=>{let e=null;if(a.QUALITY&&(e=Rt(a.QUALITY)),!e&&a.RESOLUTION){let[t,r]=a.RESOLUTION.split("x").map(i=>parseInt(i,10));e=o$({width:t,height:r})}return e!=null?e:null},c$=(a,e)=>{var s,n;let t=a.split(`
120
- `),r=[],i=[];for(let o=0;o<t.length;o++){let u=t[o],l=u.match(/^#EXT-X-STREAM-INF:(.+)/),c=u.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!l&&!c)){if(l){let d=(0,yl.default)(l[1].split(",").map(y=>y.split("="))),h=(s=d.QUALITY)!=null?s:`stream-${d.BANDWIDTH}`,p=l$(d),f;d.BANDWIDTH&&(f=parseInt(d.BANDWIDTH,10)/1e3||void 0),!f&&d["AVERAGE-BANDWIDTH"]&&(f=parseInt(d["AVERAGE-BANDWIDTH"],10)/1e3||void 0);let b=d["FRAME-RATE"]?parseFloat(d["FRAME-RATE"]):void 0,g;if(d.RESOLUTION){let[y,T]=d.RESOLUTION.split("x").map(I=>parseInt(I,10));y&&T&&(g={width:y,height:T})}let S=new URL(t[++o],e).toString();p&&r.push({id:h,quality:p,url:S,bandwidth:f,size:g,fps:b})}if(c){let d=(0,yl.default)(c[1].split(",").map(b=>b.split("=")).map(([b,g])=>[b,g.replace(/^"|"$/g,"")])),h=(n=d.URI)==null?void 0:n.replace(/playlist$/,"subtitles.vtt"),p=d.LANGUAGE,f=d.NAME;h&&p&&i.push({type:"internal",id:p,label:f,language:p,url:h,isAuto:!1})}}}if(!r.length)throw new Error("Empty manifest");return{qualityManifests:r,textTracks:i}},d$=a=>new Promise(e=>{setTimeout(()=>{e()},a)}),vl=0,$S=(r,...i)=>R(void 0,[r,...i],function*(a,e=a,t){let n=yield(yield ht(a)).text();vl+=1;try{let{qualityManifests:o,textTracks:u}=c$(n,e);return{qualityManifests:o,textTracks:u}}catch(o){if(vl<=t.manifestRetryMaxCount)return yield d$(u$(vl-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),$S(a,e,t)}return{qualityManifests:[],textTracks:[]}}),pn=$S;var xa=class{constructor(e){this.subscription=new v$;this.videoState=new C("stopped");this.textTracksManager=new Oe;this.manifests$=new Tl([]);this.liveOffset=new dt;this.manifestStartTime$=new Tl(void 0);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),r=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(r==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),x(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||n||o){let c=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(c),this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if((i==null?void 0:i.to)!=="paused"&&l.state==="requested"){this.videoState.startTransitionTo("ready"),this.seek(l.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(t){case"ready":r==="ready"?x(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),x(this.params.desiredState.playbackState,"paused")):r==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":r==="paused"?(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(i==null?void 0:i.to)==="playing"&&x(this.params.desiredState.playbackState,"playing");return;case"paused":if(r==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let c=this.liveOffset.getTotalOffset();c>=this.maxSeekBackTime$.getValue()&&(c=0,this.liveOffset.resetTo(c)),this.liveOffset.resume(),this.params.output.position$.next(-c/1e3),this.prepare()}else(i==null?void 0:i.to)==="paused"&&(x(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return p$(t)}};var t;this.params=e,this.video=be(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:y$.INVARIANT,url:this.params.source.url},pn(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:r})=>{r.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:hn.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),this.manifests$.next([this.masterManifest,...r])},r=>this.params.output.error$.next({id:"ExtractHlsQualities",category:hn.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:r})),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(re(this.params.source.url)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.maxSeekBackTime$=new Tl((t=e.source.maxSeekBackTime)!=null?t:1/0),this.subscribe()}selectManifest(){var u,l,c,d;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,r=e.getState(),i=t.getTransition(),s=(d=(c=(u=i==null?void 0:i.to)==null?void 0:u.id)!=null?c:(l=t.getState())==null?void 0:l.id)!=null?d:"master",n=this.manifests$.getValue();if(!n.length)return;let o=r?"master":s;return r&&!i&&t.startTransitionTo(this.masterManifest),n.find(h=>h.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"HlsLiveProvider",category:hn.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},i=ve(this.video),s=(o,u)=>this.subscription.add(o.subscribe(u,r));s(i.ended$,e.endedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(i.loadedMetadata$,e.firstBytesEvent$),s(i.loadedMetadata$,e.loadedMetadataEvent$),s(i.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),r)),this.subscription.add(Se(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Be(this.video,t.playbackRate,i.playbackRateState$,r)),s(_e(this.video),e.elementVisible$),this.textTracksManager.connect(this.video,t,e),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),x(t.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),x(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())==null?void 0:o.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.subscription.add(this.maxSeekBackTime$.pipe(b$(),MS(o=>-o/1e3)).subscribe(this.params.output.duration$,r)),this.subscription.add(i.loadedMetadata$.subscribe(()=>{let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&LS(l.to)){let d=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let h=this.manifests$.getValue().find(p=>p.id===d);h&&(this.params.output.currentVideoTrack$.next(h),this.params.output.hostname$.next(re(h.url)))}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o&&o.state==="requested"&&this.seek(o.position)},r)),this.subscription.add(i.loadedData$.subscribe(()=>{var u,l,c;let o=(c=(l=(u=this.video)==null?void 0:u.getStartDate)==null?void 0:l.call(u))==null?void 0:c.getTime();this.manifestStartTime$.next(o||void 0)},r)),this.subscription.add(h$({startTime:this.manifestStartTime$.pipe(m$(LS)),currentTime:i.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),r)),this.subscription.add(this.manifests$.pipe(MS(o=>o.map(({id:u,quality:l,size:c,bandwidth:d,fps:h})=>({id:u,quality:l,size:c,fps:h,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,r));let n=g$(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,S$(["init"])).pipe(f$(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),ge(this.video)}prepare(){var o,u;let e=this.selectManifest();if(fn(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),r=this.params.desiredState.autoVideoTrackLimits.getState(),i=new URL(e.url);if((t||r)&&e.id===this.masterManifest.id){let{max:l,min:c}=(u=(o=t==null?void 0:t.to)!=null?o:r)!=null?u:{};for(let[d,h]of[[l,"mq"],[c,"lq"]]){let p=String(parseFloat(d||""));h&&d&&i.searchParams.set(h,p)}}let s=this.params.format==="HLS_LIVE_CMAF"?2:0,n=se(i.toString(),this.liveOffset.getTotalOffset(),s);this.video.setAttribute("src",n),this.video.load(),Sl(n).then(l=>{var c;if(!fn(l))this.maxSeekBackTime$.next(l);else{let d=(c=this.params.source.maxSeekBackTime)!=null?c:this.maxSeekBackTime$.getValue();if(fn(d)||!isFinite(d))try{ht(n).then(h=>h.text()).then(h=>{var f;let p=(f=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(h))==null?void 0:f[1];if(p){let b=new URL(p,n).toString();Sl(b).then(g=>{fn(g)||this.maxSeekBackTime$.next(g)})}})}catch(h){}}})}playIfAllowed(){ye(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),x(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:hn.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,r=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(r),this.params.output.position$.next(-r/1e3),this.params.output.seekedEvent$.next()}};import{assertNever as T$,debounce as I$,ErrorCategory as Il,fromEvent as El,isNonNullable as E$,isNullable as x$,map as CS,merge as DS,observableFrom as BS,Subscription as P$,ValueSubject as A$,VideoQuality as w$,clientChecker as k$}from"@vkontakte/videoplayer-shared";var Pa=class{constructor(e){this.subscription=new P$;this.videoState=new C("stopped");this.textTracksManager=new Oe;this.manifests$=new A$([]);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),r=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(r==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),x(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||n||o){let c=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(c);let{currentTime:d}=this.video;this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:d*1e3,forcePrecise:!0});return}switch((i==null?void 0:i.to)!=="paused"&&l.state==="requested"&&this.seek(l.position),t){case"ready":r==="ready"?x(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused")):r==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":r==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(i==null?void 0:i.to)==="playing"&&x(this.params.desiredState.playbackState,"playing");return;case"paused":r==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&x(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return T$(t)}};this.params=e,this.video=be(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:w$.INVARIANT,url:this.params.source.url},this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(re(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),pn(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:Il.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){var u,l,c,d;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,r=e.getState(),i=t.getTransition(),s=(d=(c=(u=i==null?void 0:i.to)==null?void 0:u.id)!=null?c:(l=t.getState())==null?void 0:l.id)!=null?d:"master",n=this.manifests$.getValue();if(!n.length)return;let o=r?"master":s;return r&&!i&&t.startTransitionTo(this.masterManifest),n.find(h=>h.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"HlsProvider",category:Il.WTF,message:"HlsProvider internal logic error",thrown:o})},i=ve(this.video),s=(o,u)=>this.subscription.add(o.subscribe(u));if(s(i.timeUpdate$,e.position$),s(i.durationChange$,e.duration$),s(i.ended$,e.endedEvent$),s(i.looped$,e.loopedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(i.loadedMetadata$,e.firstBytesEvent$),s(i.loadedMetadata$,e.loadedMetadataEvent$),s(i.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.seeked$,e.seekedEvent$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe(CS(o=>o.to)),this.params.output.playbackState$),this.subscription.add(rt(this.video,t.isLooped,r)),this.subscription.add(Se(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Be(this.video,t.playbackRate,i.playbackRateState$,r)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),x(t.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),x(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())==null?void 0:o.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},r).add(i.loadedMetadata$.subscribe(()=>{var d;let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&E$(l.to)){let h=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let p=this.manifests$.getValue().find(f=>f.id===h);if(p){this.params.output.currentVideoTrack$.next(p),this.params.output.hostname$.next(re(p.url));let f=this.params.desiredState.playbackRate.getState(),b=(d=this.params.output.element$.getValue())==null?void 0:d.playbackRate;if(f!==b){let g=this.params.output.element$.getValue();g&&(this.params.desiredState.playbackRate.setState(f),g.playbackRate=f)}}}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o.state==="requested"&&this.seek(o.position)},r))),this.subscription.add(this.manifests$.pipe(CS(o=>o.map(({id:u,quality:l,size:c,bandwidth:d,fps:h})=>({id:u,quality:l,size:c,fps:h,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,r)),!k$.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add(DS(El(o,"addtrack"),El(o,"removetrack"),El(o,"change"),BS(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},r))}let n=DS(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,BS(["init"])).pipe(I$(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),ge(this.video)}prepare(){var s,n;let e=this.selectManifest();if(x$(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),r=this.params.desiredState.autoVideoTrackLimits.getState(),i=new URL(e.url);if((t||r)&&e.id===this.masterManifest.id){let{max:o,min:u}=(n=(s=t==null?void 0:t.to)!=null?s:r)!=null?n:{};for(let[l,c]of[[o,"mq"],[u,"lq"]]){let d=String(parseFloat(l||""));c&&l&&i.searchParams.set(c,d)}}this.video.setAttribute("src",i.toString()),this.video.load()}playIfAllowed(){ye(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Il.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};import{assertNever as R$,assertNonNullable as OS,debounce as $$,ErrorCategory as VS,isHigher as L$,isHigherOrEqual as M$,isInvariantQuality as _S,isLowerOrEqual as C$,isNonNullable as D$,merge as B$,observableFrom as O$,Subscription as V$,map as _$}from"@vkontakte/videoplayer-shared";var Aa=class{constructor(e){this.subscription=new V$;this.videoState=new C("stopped");this.trackUrls={};this.textTracksManager=new Oe;this.syncPlayback=()=>{var u,l,c;let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),x(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let s=this.params.desiredState.autoVideoTrackLimits.getTransition(),n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.seekState.getState();if(s&&e!=="ready"&&!n){this.handleQualityLimitTransition(s.to.max);return}if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(n){let{currentTime:d}=this.video;this.prepare(),o.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:d*1e3,forcePrecise:!0}),n.to&&((u=this.params.desiredState.autoVideoTrackLimits.getState())==null?void 0:u.max)!==((c=(l=this.trackUrls[n.to.id])==null?void 0:l.track)==null?void 0:c.quality)&&this.params.output.autoVideoTrackLimits$.next({max:void 0});return}switch((r==null?void 0:r.to)!=="paused"&&o.state==="requested"&&this.seek(o.position),e){case"ready":t==="ready"?x(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(r==null?void 0:r.to)==="playing"&&x(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&x(this.params.desiredState.playbackState,"paused");return;default:return R$(e)}};this.params=e,this.video=be(e.container,e.tuning),this.params.output.element$.next(this.video),Object.entries(this.params.source).reverse().forEach(([t,r],i)=>{let s=i.toString(10);this.trackUrls[s]={track:{quality:t,id:s},url:r}}),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next(Object.values(this.trackUrls).map(({track:t})=>t)),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.desiredState.autoVideoTrackSwitching.setState(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.subscribe()}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"MpegProvider",category:VS.WTF,message:"MpegProvider internal logic error",thrown:o})},i=ve(this.video),s=(o,u)=>this.subscription.add(o.subscribe(u,r));s(i.timeUpdate$,e.position$),s(i.durationChange$,e.duration$),s(i.ended$,e.endedEvent$),s(i.looped$,e.loopedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(i.loadedMetadata$,e.firstBytesEvent$),s(i.loadedMetadata$,e.loadedMetadataEvent$),s(i.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.seeked$,e.seekedEvent$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe(_$(o=>o.to)),this.params.output.playbackState$),this.subscription.add(rt(this.video,t.isLooped,r)),this.subscription.add(Se(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Be(this.video,t.playbackRate,i.playbackRateState$,r)),s(_e(this.video),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),x(t.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),x(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{var u,l;((u=this.videoState.getTransition())==null?void 0:u.to)==="ready"&&this.videoState.setState("ready");let o=this.params.desiredState.videoTrack.getTransition();if(o&&D$(o.to)){this.params.desiredState.videoTrack.setState(o.to),this.params.output.currentVideoTrack$.next(this.trackUrls[o.to.id].track);let c=this.params.desiredState.playbackRate.getState(),d=(l=this.params.output.element$.getValue())==null?void 0:l.playbackRate;if(c!==d){let h=this.params.output.element$.getValue();h&&(this.params.desiredState.playbackRate.setState(c),h.playbackRate=c)}}this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.textTracksManager.connect(this.video,t,e);let n=B$(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,O$(["init"])).pipe($$(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),ge(this.video)}prepare(){var r;let e=(r=this.params.desiredState.videoTrack.getState())==null?void 0:r.id;OS(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];OS(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=ha(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(re(t))}playIfAllowed(){ye(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:VS.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){var i,s,n,o;let t,r=e;if(e&&((i=this.params.output.currentVideoTrack$.getValue())==null?void 0:i.quality)!==e){let u=(s=Object.values(this.trackUrls).find(d=>!_S(d.track.quality)&&C$(d.track.quality,e)))==null?void 0:s.track,l=(n=this.params.desiredState.videoTrack.getState())==null?void 0:n.id,c=(o=this.trackUrls[l!=null?l:"0"])==null?void 0:o.track;if(u&&c&&M$(c.quality,u.quality)&&(t=u),!t){let d=Object.values(this.trackUrls).filter(p=>!_S(p.track.quality)&&L$(p.track.quality,e)),h=d.length;h&&(t=d[h-1].track)}t&&(r=t.quality)}else if(!e){let u=Object.values(this.trackUrls).map(l=>l.track);t=$t(u,{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},throughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:0,abrLogger:this.params.dependencies.abrLogger})}t&&(this.params.output.currentVideoTrack$.next(t),this.params.desiredState.videoTrack.startTransitionTo(t)),this.params.output.autoVideoTrackLimits$.next({max:r})}};import{assertNever as FS,debounce as q$,merge as US,observableFrom as H$,Subscription as j$,map as qS,ValueSubject as G$,ErrorCategory as Pl,VideoQuality as W$}from"@vkontakte/videoplayer-shared";import{ErrorCategory as N$}from"@vkontakte/videoplayer-shared";var NS=["stun:videostun.mycdn.me:80"],F$=1e3,U$=3,xl=()=>null,mn=class{constructor(e,t){this.ws=null;this.peerConnection=null;this.serverUrl="";this.streamKey="";this.stream=null;this.signalingType="JOIN";this.retryCount=0;this.externalStartCallback=xl;this.externalStopCallback=xl;this.externalErrorCallback=xl;this.options=this.normalizeOptions(t);let r=e.split("/");this.serverUrl=r.slice(0,r.length-1).join("/"),this.streamKey=r[r.length-1]}onStart(e){try{this.externalStartCallback=e}catch(t){this.handleSystemError(t)}}onStop(e){try{this.externalStopCallback=e}catch(t){this.handleSystemError(t)}}onError(e){try{this.externalErrorCallback=e}catch(t){this.handleSystemError(t)}}connect(){this.connectWS()}disconnect(){try{this.externalStopCallback(),this.closeConnections()}catch(e){this.handleSystemError(e)}}connectWS(){this.ws||(this.ws=new WebSocket(this.serverUrl),this.ws.onopen=this.onSocketOpen.bind(this),this.ws.onmessage=this.onSocketMessage.bind(this),this.ws.onclose=this.onSocketClose.bind(this),this.ws.onerror=this.onSocketError.bind(this))}onSocketOpen(){this.handleLogin()}onSocketClose(e){try{if(!this.ws)return;this.ws=null,e.code>1e3?(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():this.scheduleRetry()):this.externalStopCallback()}catch(t){this.handleRTCError(t)}}onSocketError(e){try{this.externalErrorCallback(new Error(e.toString()))}catch(t){this.handleRTCError(t)}}onSocketMessage(e){try{let t=this.parseMessage(e.data);switch(t.type){case"JOIN":case"CALL_JOIN":this.handleJoinMessage(t);break;case"UPDATE":this.handleUpdateMessage(t);break;case"STATUS":this.handleStatusMessage(t);break}}catch(t){this.handleRTCError(t)}}handleJoinMessage(e){switch(e.inviteType){case"ANSWER":this.handleAnswer(e.sdp);break;case"CANDIDATE":this.handleCandidate(e.candidate);break}}handleStatusMessage(e){switch(e.status){case"UNPUBLISHED":this.handleUnpublished();break}}handleUpdateMessage(e){return R(this,null,function*(){try{let t=yield this.createOffer();this.peerConnection&&(yield this.peerConnection.setLocalDescription(t)),this.handleAnswer(e.sdp)}catch(t){this.handleRTCError(t)}})}handleLogin(){return R(this,null,function*(){try{let e={iceServers:[{urls:NS}]};this.peerConnection=new RTCPeerConnection(e),this.peerConnection.ontrack=this.onPeerConnectionStream.bind(this),this.peerConnection.onicecandidate=this.onPeerConnectionIceCandidate.bind(this),this.peerConnection.oniceconnectionstatechange=this.onPeerConnectionIceConnectionStateChange.bind(this);let t=yield this.createOffer();yield this.peerConnection.setLocalDescription(t),this.send({type:this.signalingType,inviteType:"OFFER",streamKey:this.streamKey,sdp:t.sdp,callSupport:!1})}catch(e){this.handleRTCError(e)}})}handleAnswer(e){return R(this,null,function*(){try{this.peerConnection&&(yield this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e})))}catch(t){this.handleRTCError(t)}})}handleCandidate(e){return R(this,null,function*(){if(e)try{this.peerConnection&&(yield this.peerConnection.addIceCandidate(e))}catch(t){this.handleRTCError(t)}})}handleUnpublished(){try{this.closeConnections(),this.externalStopCallback()}catch(e){this.handleRTCError(e)}}handleSystemError(e){this.options.errorChanel&&this.options.errorChanel.next({id:"webrtc-provider-error",category:N$.WTF,message:e.message})}onPeerConnectionStream(e){return R(this,null,function*(){let t=e.streams[0];this.stream&&this.stream.id===t.id||(this.stream=t,this.externalStartCallback(this.stream))})}onPeerConnectionIceCandidate(e){e.candidate&&this.send({type:this.signalingType,inviteType:"CANDIDATE",candidate:e.candidate})}onPeerConnectionIceConnectionStateChange(){if(this.peerConnection){let e=this.peerConnection.iceConnectionState;["failed","closed"].indexOf(e)>-1&&(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():(this.closeConnections(),this.scheduleRetry()))}}createOffer(){return R(this,null,function*(){let e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");let t=yield this.peerConnection.createOffer(e),r=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(r))throw new Error("No h264 codec support error");return t})}handleRTCError(e){try{this.externalErrorCallback(e||new Error("RTC connection error"))}catch(t){this.handleSystemError(t)}}handleNetworkError(){try{this.externalErrorCallback(new Error("Network error"))}catch(e){this.handleSystemError(e)}}send(e){this.ws&&this.ws.send(JSON.stringify(e))}parseMessage(e){try{return JSON.parse(e)}catch(t){throw new Error("Can not parse socket message")}}closeConnections(){let e=this.ws;e&&(this.ws=null,e.close(1e3)),this.removePeerConnection()}removePeerConnection(){let e=this.peerConnection;e&&(this.peerConnection=null,e.close(),e.ontrack=null,e.onicecandidate=null,e.oniceconnectionstatechange=null,e=null)}scheduleRetry(){this.retryTimeout=setTimeout(this.connectWS.bind(this),F$)}normalizeOptions(e={}){let t={stunServerList:NS,maxRetryNumber:U$,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var wa=class{constructor(e){this.videoState=new C("stopped");this.maxSeekBackTime$=new G$(0);this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.pause(),this.video.srcObject=null,this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),x(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let s=this.params.desiredState.videoTrack.getTransition();if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s){this.prepare();return}switch(e){case"ready":t==="paused"?(this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(r==null?void 0:r.to)==="playing"&&x(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&x(this.params.desiredState.playbackState,"paused");return;default:return FS(e)}};this.subscription=new j$,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=be(e.container,e.tuning),this.liveStreamClient=new mn(this.params.source.url,{maxRetryNumber:this.params.tuning.webrtc.connectionRetryMaxNumber,errorChanel:this.params.output.error$}),this.liveStreamClient.onStart(this.onLiveStreamStart.bind(this)),this.liveStreamClient.onStop(this.onLiveStreamStop.bind(this)),this.liveStreamClient.onError(this.onLiveStreamError.bind(this)),this.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),ge(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,r=n=>{e.error$.next({id:"WebRTCLiveProvider",category:Pl.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};US(this.videoState.stateChangeStarted$.pipe(qS(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe(qS(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})});let i=ve(this.video),s=(n,o)=>this.subscription.add(n.subscribe(o,r));s(i.timeUpdate$,e.liveTime$),s(i.ended$,e.endedEvent$),s(i.looped$,e.loopedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(_e(this.video),this.params.output.elementVisible$),this.subscription.add(i.durationChange$.subscribe(n=>{e.duration$.next(n===1/0?0:n)})).add(i.canplay$.subscribe(()=>{var n;((n=this.videoState.getTransition())==null?void 0:n.to)==="ready"&&this.videoState.setState("ready")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused")},r)).add(i.playing$.subscribe(()=>{this.videoState.setState("playing")},r)).add(i.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(Se(this.video,t.volume,i.volumeState$,r)).add(i.volumeState$.subscribe(e.volume$,r)).add(this.videoState.stateChangeEnded$.subscribe(n=>{switch(n.to){case"stopped":e.position$.next(0),e.duration$.next(0),t.playbackState.setState("stopped");break;case"ready":break;case"paused":t.playbackState.setState("paused");break;case"playing":t.playbackState.setState("playing");break;default:return FS(n.to)}},r)).add(US(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,H$(["init"])).pipe(q$(0)).subscribe(this.syncPlayback.bind(this),r)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),r)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),r))}onLiveStreamStart(e){this.params.output.element$.next(this.video),this.params.output.duration$.next(0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(re(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.currentVideoTrack$.next({id:"webrtc",quality:W$.INVARIANT}),this.video.srcObject=e,x(this.params.desiredState.playbackState,"playing")}onLiveStreamStop(){this.videoState.startTransitionTo("stopped"),this.syncPlayback(),this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.params.output.endedEvent$.next()}onLiveStreamError(e){this.onLiveStreamStop(),this.params.output.error$.next({id:"WebRTC stream runtime error",category:Pl.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){ye(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Pl.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 $a,assertNonNullable as Bt,ErrorCategory as gn,filter as QS,isNonNullable as zS,isNullable as Z$,map as eL,merge as tL,once as rL,Subject as Ee,Subscription as KS,ValueSubject as O,flattenObject as JS}from"@vkontakte/videoplayer-shared";import{Observable as Y$,map as HS,Subscription as Q$,Subject as z$}from"@vkontakte/videoplayer-shared";var jS=a=>new Y$(e=>{let t=new Q$,r=a.desiredPlaybackState$.stateChangeStarted$.pipe(HS(({from:l,to:c})=>`${l}-${c}`)),i=a.desiredPlaybackState$.stateChangeEnded$,s=a.providerChanged$.pipe(HS(({type:l})=>l!==void 0)),n=new z$,o=0,u="unknown";return t.add(r.subscribe(l=>{o&&window.clearTimeout(o),u=l,o=window.setTimeout(()=>n.next(l),a.maxTransitionInterval)})),t.add(i.subscribe(()=>{window.clearTimeout(o),u="unknown",o=0})),t.add(s.subscribe(l=>{o&&(window.clearTimeout(o),o=0,l&&(o=window.setTimeout(()=>n.next(u),a.maxTransitionInterval)))})),t.add(n.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});import{ErrorCategory as GS,Subscription as K$,combine as J$,filter as WS,once as YS}from"@vkontakte/videoplayer-shared";var Ra=null,bn=null;function Al(){return Ra||(Ra=new(window.AudioContext||window.webkitAudioContext)),bn||(bn=new GainNode(Ra,{gain:1}),bn.connect(Ra.destination)),{audioCtx:Ra,gainNode:bn}}import{clientChecker as X$}from"@vkontakte/videoplayer-shared";var Kr=class Kr{constructor(e,t,r,i){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=r;this.volumeMultiplier=i;this.audioContextInit=!1;this.subscriptions=new K$;this.lastAudioContextResumeId=0;this.subscriptions.add(this.provider$.pipe(WS(s=>!!s.type),YS()).subscribe(({type:s})=>this.subscribe(s)))}subscribe(e){X$.isSafari&&e!=="MPEG"||this.subscriptions.add(J$({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe(WS(({playbackState:t,video:r,volume:{muted:i,volume:s}})=>t==="playing"&&!!r&&!i&&!!s),YS()).subscribe(({video:t})=>this.initAudioContextOnce(t)))}static isSupported(){return"AudioContext"in window&&"GainNode"in window&&"MediaElementAudioSourceNode"in window}initAudioContextOnce(e){let{volumeMultiplier:t}=this,{audioCtx:r,gainNode:i}=Al(),s=(Math.random()+1)*999999;this.lastAudioContextResumeId=s,r.resume().then(()=>{var n;if(s!==this.lastAudioContextResumeId)throw new Error(`AudioContext.resume() resolved after ${Kr.errorId} destroyed`);i.gain.value=t;try{new MediaElementAudioSourceNode(r,{mediaElement:e}).connect(i),this.audioContextInit=!0}catch(o){this.volumeMultiplierError$.next({id:Kr.errorId,category:GS.VIDEO_PIPELINE,message:(n=o==null?void 0:o.message)!=null?n:"initAudioContextOnce: (new MediaElementAudioSourceNode).connect() exception",thrown:o})}}).catch(n=>{var o;this.volumeMultiplierError$.next({id:Kr.errorId,category:GS.VIDEO_PIPELINE,message:(o=n==null?void 0:n.message)!=null?o:"initAudioContextOnce: AudioContext.resume() exception",thrown:n})})}destroy(){if(this.audioContextInit){let{gainNode:e}=Al();e.gain.value=1}this.subscriptions.unsubscribe(),this.lastAudioContextResumeId=0}};Kr.errorId="VolumeMultiplierManager";var Jr=Kr;var iL={chunkDuration:5e3,maxParallelRequests:5},La=class{constructor(e){this.current$=new O({type:void 0});this.providerError$=new Ee;this.noAvailableProvidersError$=new Ee;this.volumeMultiplierError$=new Ee;this.providerOutput={position$:new O(0),duration$:new O(1/0),volume$:new O({muted:!1,volume:1}),availableVideoStreams$:new O([]),currentVideoStream$:new O(void 0),availableVideoTracks$:new O([]),currentVideoTrack$:new O(void 0),availableAudioStreams$:new O([]),currentAudioStream$:new O(void 0),availableAudioTracks$:new O([]),currentVideoSegmentLength$:new O(0),currentAudioSegmentLength$:new O(0),isAudioAvailable$:new O(!0),autoVideoTrackLimitingAvailable$:new O(!1),autoVideoTrackLimits$:new O(void 0),currentBuffer$:new O(void 0),isBuffering$:new O(!0),error$:new Ee,warning$:new Ee,willSeekEvent$:new Ee,soundProhibitedEvent$:new Ee,seekedEvent$:new Ee,loopedEvent$:new Ee,endedEvent$:new Ee,firstBytesEvent$:new Ee,loadedMetadataEvent$:new Ee,firstFrameEvent$:new Ee,canplay$:new Ee,isLive$:new O(void 0),isLowLatency$:new O(!1),canChangePlaybackSpeed$:new O(!0),liveTime$:new O(void 0),liveBufferTime$:new O(void 0),availableTextTracks$:new O([]),currentTextTrack$:new O(void 0),hostname$:new O(void 0),httpConnectionType$:new O(void 0),httpConnectionReused$:new O(void 0),inPiP$:new O(!1),inFullscreen$:new O(!1),element$:new O(void 0),elementVisible$:new O(!0),availableSources$:new O(void 0),is3DVideo$:new O(!1),playbackState$:new O("")};this.subscription=new KS;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=hg([...mg(this.params.tuning),...fg(this.params.tuning)],this.params.tuning.useHlsJs,this.params.tuning.useManagedMediaSource).filter(l=>zS(e.sources[l])),{forceFormat:r,formatsToAvoid:i}=this.params.tuning,s=[];r?s=[r]:i.length?s=[...t.filter(l=>!i.includes(l)),...t.filter(l=>i.includes(l))]:s=t,this.log({message:`Selected formats: ${s.join(" > ")}`}),this.tracer.log("Selected formats",JS(s)),this.screenFormatsIterator=new ka(s);let n=[...Uu(!0),...Uu(!1)];this.chromecastFormatsIterator=new ka(n.filter(l=>zS(e.sources[l]))),this.providerOutput.availableSources$.next(e.sources);let{volumeMultiplier:o=1,tuning:{useVolumeMultiplier:u}}=this.params;u&&o!==1&&Jr.isSupported()&&(this.volumeMultiplierManager=new Jr(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(){var e;this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe(),(e=this.volumeMultiplierManager)==null||e.destroy(),this.volumeMultiplierManager=null,this.tracer.end()}initProvider(){let e=this.chooseDestination(),t=this.chooseFormat(e);if(Z$(t)){this.handleNoFormatsError(e);return}let r;try{r=this.createProvider(e,t)}catch(i){this.providerError$.next({id:"ProviderNotConstructed",category:gn.WTF,message:"Failed to create provider",thrown:i})}r?this.current$.next({type:t,provider:r,destination:e}):this.current$.next({type:void 0})}reinitProvider(){this.tracer.log("reinitProvider"),this.destroyProvider(),this.initProvider()}switchToNextProvider(e){this.tracer.log("switchToNextProvider",{destination:e}),this.destroyProvider(),this.failoverIndex=void 0,this.skipFormat(e),this.initProvider()}destroyProvider(){let e=this.current$.getValue().provider;if(!e)return;this.log({message:"destroyProvider"}),this.tracer.log("destroyProvider");let t=this.providerOutput.position$.getValue()*1e3,r=this.params.desiredState.seekState.getState(),i=r.state!=="none";if(this.params.desiredState.seekState.setState({state:"requested",position:i?r.position:t,forcePrecise:i?r.forcePrecise:!1}),e.scene3D){let n=e.scene3D.getCameraRotation();this.params.desiredState.cameraOrientation.setState({x:n.x,y:n.y})}e.destroy();let s=this.providerOutput.isBuffering$;s.getValue()||s.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),this.tracer.log("createProvider",{destination:e,format:t}),e){case"SCREEN":return this.createScreenProvider(t);case"CHROMECAST":return this.createChromecastProvider(t);default:return $a(e)}}createScreenProvider(e){let{sources:t,container:r,desiredState:i}=this.params,s=this.providerOutput,n={container:r,source:null,desiredState:i,output:s,dependencies:this.params.dependencies,tuning:this.params.tuning};switch(e){case"DASH_SEP":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_ONDEMAND":case"DASH_STREAMS":{let o=this.applyFailoverHost(t[e]),u=this.applyFailoverHost(t.HLS_ONDEMAND||t.HLS);return Bt(o),new ya(D(A({},n),{source:o,sourceHls:u}))}case"DASH_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return Bt(o),new Ta(D(A({},n),{source:o}))}case"HLS":case"HLS_ONDEMAND":{let o=this.applyFailoverHost(t[e]);return Bt(o),Hr||!this.params.tuning.useHlsJs?new Pa(D(A({},n),{source:o})):new Ea(D(A({},n),{source:o}))}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return Bt(o),new xa(D(A({},n),{source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e}))}case"MPEG":{let o=this.applyFailoverHost(t[e]);return Bt(o),new Aa(D(A({},n),{source:o}))}case"DASH_LIVE":{let o=this.applyFailoverHost(t[e]);return Bt(o),new Kb(D(A({},n),{source:o,config:D(A({},iL),{maxPausedTime:this.params.tuning.live.maxPausedTime})}))}case"WEB_RTC_LIVE":{let o=this.applyFailoverHost(t[e]);return Bt(o),new wa({container:r,source:o,desiredState:i,output:s,dependencies:this.params.dependencies,tuning:this.params.tuning})}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return $a(e)}}createChromecastProvider(e){let{sources:t,container:r,desiredState:i,meta:s}=this.params,n=this.providerOutput,o=this.params.dependencies.chromecastInitializer.connection$.getValue();return Bt(o),new Ri({connection:o,meta:s,container:r,source:t,format:e,desiredState:i,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?"CHROMECAST":"SCREEN"}chooseFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case"CHROMECAST":return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return $a(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return $a(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 $a(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;let t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;let r=i=>{let s=new URL(i);return s.host=t,s.toString()};if(e===void 0)return e;if("type"in e){if(e.type==="raw")return e;if(e.type==="url")return D(A({},e),{url:r(e.url)})}return(0,XS.default)(Object.entries(e).map(([i,s])=>[i,r(s)]))}initProviderErrorHandling(){let e=new KS,t=!1,r=0;return e.add(tL(this.providerOutput.error$.pipe(QS(i=>!this.params.tuning.ignoreAudioRendererError||!i.message||!/AUDIO_RENDERER_ERROR/ig.test(i.message))),jS({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(eL(i=>({id:`ProviderHangup:${i}`,category:gn.WTF,message:`A ${i} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;let i=this.params.desiredState.playbackState.transitionEnded$.pipe(QS(({to:s})=>s==="playing"),rL()).subscribe(()=>t=!0);e.add(i)})),e.add(this.providerError$.subscribe(i=>{let s=this.current$.getValue().destination,n={error:i,currentDestination:s};if(s==="CHROMECAST")this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider("SCREEN"),()=>this.params.dependencies.chromecastInitializer.disconnect());else{let o=i.category===gn.NETWORK,u=i.category===gn.FATAL,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=D(A({},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!=null?s:"SCREEN")}this.tracer.error("providerError",JS(n))})),e}};import{fromEvent as Sn,once as aL,combine as sL,Subscription as ZS,ValueSubject as wl,map as nL,filter as oL,isNonNullable as vn,now as Re,safeStorage as kl}from"@vkontakte/videoplayer-shared";var uL=5e3,ev="one_video_throughput",tv="one_video_rtt",bt=window.navigator.connection,rv=()=>{let a=bt==null?void 0:bt.downlink;if(vn(a)&&a!==10)return a*1e3},iv=()=>{let a=bt==null?void 0:bt.rtt;if(vn(a)&&a!==3e3)return a},av=(a,e,t)=>{let r=t*8,i=r/a;return r/(i+e)},Rl=class a{constructor(e){this.subscription=new ZS;this.concurrentDownloads=new Set;var i,s;this.tuningConfig=e;let t=a.load(ev)||(e.useBrowserEstimation?rv():void 0)||uL,r=(s=(i=a.load(tv))!=null?i:e.useBrowserEstimation?iv():void 0)!=null?s:0;if(this.throughput$=new wl(t),this.rtt$=new wl(r),this.rttAdjustedThroughput$=new wl(av(t,r,e.rttPenaltyRequestSize)),this.throughput=nr.getSmoothedValue(t,-1,e),this.rtt=nr.getSmoothedValue(r,1,e),e.useBrowserEstimation){let n=()=>{let u=rv();u&&this.throughput.next(u);let l=iv();vn(l)&&this.rtt.next(l)};bt&&"onchange"in bt&&this.subscription.add(Sn(bt,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{kl.set(ev,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{kl.set(tv,n.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(sL({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(nL(({throughput:n,rtt:o})=>av(n,o,e.rttPenaltyRequestSize)),oL(n=>{let o=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(n-o)/o>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,r=Re(),i=new ZS;switch(this.subscription.add(i),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:i.add(Sn(e,"progress").pipe(aL()).subscribe(s=>{t=s.loaded,r=Re()}));break;case 1:case 0:i.add(Sn(e,"loadstart").subscribe(()=>{t=0,r=Re()}));break}i.add(Sn(e,"loadend").subscribe(s=>{if(e.status===200){let n=s.loaded,o=Re(),u=n-t,l=o-r;this.addRawSpeed(u,l,1)}this.concurrentDownloads.delete(e),i.unsubscribe()}))}trackStream(e,t=!1){let r=e.getReader();if(!r){e.cancel("Could not get reader");return}let i=0,s=Re(),n=0,o=Re(),u=c=>{this.concurrentDownloads.delete(e),r.releaseLock(),e.cancel(`Throughput Estimator error: ${c}`).catch(()=>{})},l=h=>R(this,[h],function*({done:c,value:d}){if(c)!t&&this.addRawSpeed(i,Re()-s,1),this.concurrentDownloads.delete(e);else if(d){if(t){let p=Re();if(p-o>this.tuningConfig.lowLatency.continuesByteSequenceInterval||p-s>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let b=o-s;b&&this.addRawSpeed(n,b,1,t),n=d.byteLength,s=Re()}else n+=d.byteLength;o=Re()}else i+=d.byteLength,n+=d.byteLength,n>=this.tuningConfig.streamMinSampleSize&&Re()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,Re()-o,this.concurrentDownloads.size),n=0,o=Re());yield r==null?void 0:r.read().then(l,u)}});this.concurrentDownloads.add(e),r==null||r.read().then(l,u)}addRawSpeed(e,t,r=1,i=!1){if(a.sanityCheck(e,t,i)){let s=e*8/t;this.throughput.next(s*r)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,r=!1){let i=e*8/t;return!(!i||!isFinite(i)||i>1e6||i<30||r&&e<1e4||!r&&e<10*1024||!r&&t<=20)}static load(e){var r;let t=kl.get(e);if(vn(t))return(r=parseInt(t,10))!=null?r:void 0}},sv=Rl;import{fillWithDefault as lL,VideoQuality as nv}from"@vkontakte/videoplayer-shared";var ov={configName:["core"],throughputEstimator:{type:"EmaAndMa",emaAlphaSlow:.2,emaAlphaFast:.7,emaAlpha:.45,basisTrendChangeCount:10,changeThreshold:.05,useBrowserEstimation:!0,rttPenaltyRequestSize:1*1024*1024,streamMinSampleSize:10*1024,streamMinSampleTime:300,deviationDepth:20,deviationFactor:.5,lowLatency:{continuesByteSequenceInterval:50,maxLastEvaluationTimeout:300}},autoTrackSelection:{bitrateFactorAtEmptyBuffer:1.8,bitrateAudioFactorAtEmptyBuffer:10,bitrateFactorAtFullBuffer:1.2,bitrateAudioFactorAtFullBuffer:7,minVideoAudioRatio:5,minAvailableThroughputAudioRatio:5,usePixelRatio:!0,pixelRatioMultiplier:1,limitByContainer:!0,containerSizeFactor:1.5,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldownIncreaseQuality:3e3,trackCooldownDecreaseQuality:3e3,backgroundVideoQualityLimit:nv.Q_4320P,activeVideoAreaThreshold:.1},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:nv.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,enableBaseUrlSupport:!0,maxSegmentRetryCount:5},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:250,playbackCatchupSpeedup:.05,isActive:!1,delayEstimator:{emaAlpha:.45,changeThreshold:.05,deviationDepth:20,deviationFactor:.5,extremumInterval:5}}},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1,lowLatencyActiveLiveDelay:3e3,activeLiveDelay:5e3,maxPausedTime:5e3},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,forceFormat:void 0,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:void 0,useWebmBigRequest:!1,webmCodec:"vp9",androidPreferredFormat:"mpeg",preferCMAF:!1,preferWebRTC:!1,preferMultiStream:!1,preferHDR:!1,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,accumulationBufferStallSizeMs:0,requestQuick:!1,useHlsJs:!0,useNativeHLSTextTracks:!1,useManagedMediaSource:!1,useNewPruneBufferStrategy:!1,useNewSwitchTo:!1,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,manifestRetryInterval:300,manifestRetryMaxInterval:1e4,manifestRetryMaxCount:10,audioVideoSyncRate:20,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50},useVolumeMultiplier:!1,ignoreAudioRendererError:!1},uv=a=>{var e;return D(A({},lL(a,ov)),{configName:[...(e=a.configName)!=null?e:[],...ov.configName]})};import{assertNonNullable as yn,combine as Ot,ErrorCategory as Tn,filter as pe,filterChanged as q,fromEvent as Ll,isNonNullable as bL,isNullable as gL,Logger as SL,map as F,mapTo as pv,merge as Vt,now as In,once as st,Subject as Y,Subscription as hv,tap as fv,ValueSubject as P,isHigher as vL,isInvariantQuality as mv,flattenObject as _t,throttle as Ml,getTraceSubscriptionMethod as bv,Tracer as yL}from"@vkontakte/videoplayer-shared";import{merge as cL,map as dL,filter as lv,isNonNullable as pL}from"@vkontakte/videoplayer-shared";var $l=({seekState:a,position$:e})=>cL(a.stateChangeEnded$.pipe(dL(({to:t})=>{var r;return t.state==="none"?void 0:((r=t.position)!=null?r:NaN)/1e3}),lv(pL)),e.pipe(lv(()=>a.getState().state==="none")));import{assertNonNullable as hL}from"@vkontakte/videoplayer-shared";var cv=a=>{let e=typeof a.container=="string"?document.getElementById(a.container):a.container;return hL(e,`Wrong container or containerId {${a.container}}`),e};import{filter as fL,once as mL}from"@vkontakte/videoplayer-shared";var dv=(a,e,t,r)=>{a!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&(t==null?void 0:t.getValue().length)===0?t.pipe(fL(i=>i.length>0),mL()).subscribe(i=>{i.find(r)&&e.startTransitionTo(a)}):(a===void 0||t!=null&&t.getValue().find(r))&&e.startTransitionTo(a)};var En=class{constructor(e={configName:[]},t=yL.createRootTracer(!1)){this.subscription=new hv;this.logger=new SL;this.abrLogger=this.logger.createComponentLog("ABR");this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new P(!1);this.hasLiveOffsetByPausedTimer=0;this.desiredState={playbackState:new C("stopped"),seekState:new C({state:"none"}),volume:new C({volume:1,muted:!1}),videoTrack:new C(void 0),videoStream:new C(void 0),audioStream:new C(void 0),autoVideoTrackSwitching:new C(!0),autoVideoTrackLimits:new C({}),isLooped:new C(!1),playbackRate:new C(1),externalTextTracks:new C([]),internalTextTracks:new C([]),currentTextTrack:new C(void 0),textTrackCuesSettings:new C({}),cameraOrientation:new C({x:0,y:0})};this.info={playbackState$:new P("stopped"),position$:new P(0),duration$:new P(1/0),muted$:new P(!1),volume$:new P(1),availableVideoStreams$:new P([]),currentVideoStream$:new P(void 0),availableQualities$:new P([]),availableQualitiesFps$:new P({}),currentQuality$:new P(void 0),isAutoQualityEnabled$:new P(!0),autoQualityLimitingAvailable$:new P(!1),autoQualityLimits$:new P({}),availableAudioStreams$:new P([]),currentAudioStream$:new P(void 0),availableAudioTracks$:new P([]),isAudioAvailable$:new P(!0),currentPlaybackRate$:new P(1),currentBuffer$:new P({start:0,end:0}),isBuffering$:new P(!0),isStalled$:new P(!1),isEnded$:new P(!1),isLooped$:new P(!1),isLive$:new P(void 0),canChangePlaybackSpeed$:new P(void 0),atLiveEdge$:new P(void 0),atLiveDurationEdge$:new P(void 0),liveTime$:new P(void 0),liveBufferTime$:new P(void 0),currentFormat$:new P(void 0),availableTextTracks$:new P([]),currentTextTrack$:new P(void 0),throughputEstimation$:new P(void 0),rttEstimation$:new P(void 0),videoBitrate$:new P(void 0),hostname$:new P(void 0),httpConnectionType$:new P(void 0),httpConnectionReused$:new P(void 0),surface$:new P("none"),chromecastState$:new P("NOT_AVAILABLE"),chromecastDeviceName$:new P(void 0),intrinsicVideoSize$:new P(void 0),availableSources$:new P(void 0),is3DVideo$:new P(!1),currentVideoSegmentLength$:new P(0),currentAudioSegmentLength$:new P(0)};this.events={inited$:new Y,ready$:new Y,started$:new Y,playing$:new Y,paused$:new Y,stopped$:new Y,willStart$:new Y,willResume$:new Y,willPause$:new Y,willStop$:new Y,willDestruct$:new Y,watchCoverageRecord$:new Y,watchCoverageLive$:new Y,managedError$:new Y,fatalError$:new Y,ended$:new Y,looped$:new Y,seeked$:new Y,willSeek$:new Y,autoplaySoundProhibited$:new Y,firstBytes$:new Y,loadedMetadata$:new Y,firstFrame$:new Y,canplay$:new Y,log$:new Y};this.experimental={element$:new P(void 0),tuningConfigName$:new P([]),enableDebugTelemetry$:new P(!1),dumpTelemetry:Rb};if(this.initLogs(),this.tuning=uv(e),this.tracer=t,this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new Qa({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new sv(this.tuning.throughputEstimator),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(r,i,s)=>{let n=Reflect.get(r,i,s);return typeof n!="function"?n:(...o)=>{try{return n.apply(r,o)}catch(u){let l=o.map(h=>JSON.stringify(h,(p,f)=>{let b=typeof f;return["number","string","boolean"].includes(b)?f:f===null?null:`<${b}>`})),c=`Player.${String(i)}`,d=`Exception calling ${c} (${l.join(", ")})`;throw this.events.fatalError$.next({id:c,category:Tn.WTF,message:d,thrown:u}),u}}}})}initVideo(e){var s,n,o;this.config=e;let i=e,{container:t}=i,r=fc(i,["container"]);return this.tracer.log("initVideo",_t(r)),this.domContainer=cv(e),this.chromecastInitializer.contentId=(s=e.meta)==null?void 0:s.videoId,this.providerContainer=new La({sources:e.sources,meta:(n=e.meta)!=null?n:{},failoverHosts:(o=e.failoverHosts)!=null?o:[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,tracer:this.tracer,logger:this.logger,abrLogger:this.abrLogger},tuning:this.tuning,volumeMultiplier:e.volumeMultiplier}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.initTracerSubscription(),this.providerContainer.init(),this.setMuted(this.tuning.isAudioDisabled),this.initDebugTelemetry(),this.initWakeLock(),this}destroy(){var e;this.tracer.log("destroy"),window.clearTimeout(this.hasLiveOffsetByPausedTimer),this.events.willDestruct$.next(),this.stop(),(e=this.providerContainer)==null||e.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe(),this.tracer.end()}prepare(){let e=this.desiredState.playbackState;return this.tracer.log("prepare",{currentPlayBackState:e.getState()}),e.getState()==="stopped"&&e.startTransitionTo("ready"),this}play(){let e=()=>{let t=this.desiredState.playbackState;this.tracer.log("play",{currentPlayBackState:t.getState()}),t.getState()!=="playing"&&t.startTransitionTo("playing")};return document.hidden&&this.tuning.autoplayOnlyInActiveTab&&!_i()?(this.tracer.log("request play from hidden tab"),Ll(document,"visibilitychange").pipe(st()).subscribe(e)):e(),this}pause(){let e=this.desiredState.playbackState;return this.tracer.log("pause",{currentPlayBackState:e.getState()}),e.getState()!=="paused"&&e.startTransitionTo("paused"),this}stop(){let e=this.desiredState.playbackState;return this.tracer.log("stop",{currentPlayBackState:e.getState()}),e.getState()!=="stopped"&&e.startTransitionTo("stopped"),this}seekTime(e,t=!0){let r=this.info.duration$.getValue(),i=this.info.isLive$.getValue(),s=e;return e>=r&&!i&&(s=r-.1),this.tracer.log("seekTime",{duration:r,isLive:i,time:e,calculatedTime:s,forcePrecise:t}),this.events.willSeek$.next({from:this.getExactTime(),to:s}),this.desiredState.seekState.setState({state:"requested",position:s*1e3,forcePrecise:t}),this}seekPercent(e){let t=this.info.duration$.getValue();return this.tracer.log("seekPercent",{percent:e,duration:t}),isFinite(t)&&this.seekTime(Math.abs(t)*e,!1),this}setVolume(e){let t=this.tuning.isAudioDisabled||this.desiredState.volume.getState().muted;return this.tracer.log("setVolume",{volume:e,isAudioDisabled:this.tuning.isAudioDisabled,isDesiredStateMuted:this.desiredState.volume.getState().muted,chromecastState:this.chromecastInitializer.castState$.getValue(),muted:t}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setVolume(e):this.desiredState.volume.startTransitionTo({volume:e,muted:t}),this}setMuted(e){let t=this.tuning.isAudioDisabled||e;return this.tracer.log("setMuted",{isMuted:e,isAudioDisabled:this.tuning.isAudioDisabled,desiredStateVolume:this.desiredState.volume.getState().volume,chromecastState:this.chromecastInitializer.castState$.getValue(),muted:t}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setMuted(t):this.desiredState.volume.startTransitionTo({volume:this.desiredState.volume.getState().volume,muted:t}),this}setVideoStream(e){return this.desiredState.videoStream.startTransitionTo(e),this}setAudioStream(e){return this.desiredState.audioStream.startTransitionTo(e),this}setQuality(e){yn(this.providerContainer);let t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();return this.tracer.log("setQuality",{isDelayed:t.length===0,quality:e}),this.desiredState.videoTrack.getState()===void 0&&this.desiredState.videoTrack.getPrevState()===void 0&&t.length===0?this.providerContainer.providerOutput.availableVideoTracks$.pipe(pe(r=>r.length>0),st()).subscribe(r=>{this.setVideoTrackIdByQuality(r,e)}):t.length>0&&this.setVideoTrackIdByQuality(t,e),this}setAutoQuality(e){return this.tracer.log("setAutoQuality",{enable:e}),this.desiredState.autoVideoTrackSwitching.startTransitionTo(e),this}setAutoQualityLimits(e){return this.tracer.log("setAutoQualityLimits",_t(e)),this.desiredState.autoVideoTrackLimits.startTransitionTo(e),this}setPlaybackRate(e){var r;yn(this.providerContainer);let t=(r=this.providerContainer)==null?void 0:r.providerOutput.element$.getValue();return this.tracer.log("setPlaybackRate",{playbackRate:e,isVideoElementAvailable:!!t}),t&&(this.desiredState.playbackRate.setState(e),t.playbackRate=e),this}setExternalTextTracks(e){return e.length&&this.tracer.log("setExternalTextTracks",_t(e)),this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>A({type:"external"},t))),this}selectTextTrack(e){var t;return dv(e,this.desiredState.currentTextTrack,(t=this.providerContainer)==null?void 0:t.providerOutput.availableTextTracks$,r=>r.id===e),this.tracer.log("selectTextTrack",{textTrackId:e}),this}setTextTrackCueSettings(e){return this.tracer.log("setTextTrackCueSettings",A({},e)),this.desiredState.textTrackCuesSettings.startTransitionTo(e),this}setLooped(e){return this.tracer.log("setLooped",{isLooped:e}),this.desiredState.isLooped.startTransitionTo(e),this}toggleChromecast(){this.tracer.log("toggleChromecast"),this.chromecastInitializer.toggleConnection()}startCameraManualRotation(e,t){let r=this.getScene3D();return this.tracer.log("startCameraManualRotation",{isScene3DAvailable:!!r,mx:e,my:t}),r&&r.startCameraManualRotation(e,t),this}stopCameraManualRotation(e=!1){let t=this.getScene3D();return this.tracer.log("stopCameraManualRotation",{isScene3DAvailable:!!t,immediate:e}),t&&t.stopCameraManualRotation(e),this}moveCameraFocusPX(e,t){let r=this.getScene3D();if(this.tracer.log("moveCameraFocusPX",{isScene3DAvailable:!!r,dxpx:e,dypx:t}),r){let i=r.getCameraRotation(),s=r.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:i.x+s.x,y:i.y+s.y})}return this}holdCamera(){let e=this.getScene3D();return e&&e.holdCamera(),this}releaseCamera(){let e=this.getScene3D();return e&&e.releaseCamera(),this}getExactTime(){if(!this.providerContainer)return 0;let e=this.providerContainer.providerOutput.element$.getValue();if(gL(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),r=t.state==="none"?void 0:t.position;return bL(r)?r/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}getScene3D(){var t,r;let e=(t=this.providerContainer)==null?void 0:t.current$.getValue();if((r=e==null?void 0:e.provider)!=null&&r.scene3D)return e.provider.scene3D}setIntrinsicVideoSize(...e){let t={width:e.reduce((r,{width:i})=>r||i||0,0),height:e.reduce((r,{height:i})=>r||i||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add(Vt(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(F(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(F(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(F(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(F(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(F(e=>e.to)).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(pe(({from:e})=>e==="stopped"),st()).subscribe(()=>{this.initedAt=In(),this.events.inited$.next()})).add(this.desiredState.playbackState.stateChangeEnded$.subscribe(e=>{switch(e.to){case"ready":this.events.ready$.next();break;case"playing":this.isPlaybackStarted||this.events.started$.next(),this.isPlaybackStarted=!0,this.events.playing$.next();break;case"paused":this.events.paused$.next();break;case"stopped":this.events.stopped$.next()}})).add(this.desiredState.playbackState.stateChangeStarted$.subscribe(e=>{switch(e.to){case"paused":this.events.willPause$.next();break;case"playing":this.isPlaybackStarted?this.events.willResume$.next():this.events.willStart$.next();break;case"stopped":this.events.willStop$.next();break;default:}}))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();this.tracer.log("willSeekEvent",_t(n)),n.state==="requested"?this.desiredState.seekState.setState(D(A({},n),{state:"applying"})):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:Tn.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.soundProhibitedEvent$.pipe(st()).subscribe(this.events.autoplaySoundProhibited$)).add(e.providerOutput.seekedEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();this.tracer.log("seekedEvent",_t(n)),n.state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe(F(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(F(n=>n.destination),q()).subscribe(()=>this.isPlaybackStarted=!1)).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add(e.providerOutput.availableVideoTracks$.pipe(F(n=>n.map(({quality:o})=>o).sort((o,u)=>mv(o)?1:mv(u)?-1:vL(u,o)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(n=>{let o={};for(let u of n)u.fps&&(o[u.quality]=u.fps);this.info.availableQualitiesFps$.next(o)})).add(e.providerOutput.availableAudioStreams$.subscribe(this.info.availableAudioStreams$)).add(e.providerOutput.currentVideoStream$.subscribe(this.info.currentVideoStream$)).add(e.providerOutput.currentAudioStream$.subscribe(this.info.currentAudioStream$)).add(e.providerOutput.availableAudioTracks$.subscribe(this.info.availableAudioTracks$)).add(e.providerOutput.isAudioAvailable$.pipe(q()).subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{this.info.currentQuality$.next(n==null?void 0:n.quality),this.info.videoBitrate$.next(n==null?void 0:n.bitrate)})).add(e.providerOutput.currentVideoSegmentLength$.pipe(q((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.pipe(q((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe(q()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(q()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(q()).subscribe(this.info.httpConnectionReused$)).add(e.providerOutput.currentTextTrack$.subscribe(this.info.currentTextTrack$)).add(e.providerOutput.availableTextTracks$.subscribe(this.info.availableTextTracks$)).add(e.providerOutput.autoVideoTrackLimitingAvailable$.subscribe(this.info.autoQualityLimitingAvailable$)).add(e.providerOutput.autoVideoTrackLimits$.subscribe(n=>{this.desiredState.autoVideoTrackLimits.setState(n!=null?n:{})})).add(e.providerOutput.currentBuffer$.pipe(F(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(Ot({hasLiveOffsetByPaused:Vt(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(F(n=>n.to),q(),F(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(Ot({atLiveEdge:Ot({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:$l({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(F(({isLive:n,position:o,isLowLatency:u})=>{let l=this.getActiveLiveDelay(u);return n&&Math.abs(o)<l/1e3}),q(),fv(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(F(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add(Ot({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(F(({isLive:n,position:o,duration:u})=>n&&(Math.abs(u)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),q(),fv(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(F(n=>n.muted),q()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(F(n=>n.volume),q()).subscribe(this.info.volume$)).add($l({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(Vt(e.providerOutput.endedEvent$.pipe(pv(!0)),e.providerOutput.seekedEvent$.pipe(pv(!1))).pipe(q()).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(F(n=>({id:n?`No${n}`:"NoProviders",category:Tn.VIDEO_PIPELINE,message:n?`${n} was forced but failed or not available`:"No suitable providers or all providers failed"}))).subscribe(this.events.fatalError$)).add(e.providerOutput.element$.subscribe(this.experimental.element$)).add(e.providerOutput.firstBytesEvent$.pipe(st(),F(n=>n!=null?n:In()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe(st(),F(()=>In()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(st(),F(()=>In()-this.initedAt)).subscribe(this.events.canplay$)).add(this.throughputEstimator.throughput$.subscribe(this.info.throughputEstimation$)).add(this.throughputEstimator.rtt$.subscribe(this.info.rttEstimation$)).add(e.providerOutput.availableSources$.subscribe(this.info.availableSources$));let t=new P(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let r=new P(!0);this.subscription.add(e.current$.subscribe(()=>r.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(pe(({to:n})=>n==="playing"),st()).subscribe(()=>r.next(!1)));let i=0,s=Vt(e.providerOutput.isBuffering$,t,r).pipe(F(()=>{let n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||r.getValue();return n&&!o}),q());this.subscription.add(s.subscribe(n=>{n?i=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(i),this.info.isStalled$.next(!1))})),this.subscription.add(Vt(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{let n=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:n==null?void 0:n.videoWidth,height:n==null?void 0:n.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{var u,l;let o=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:(u=n==null?void 0:n.size)==null?void 0:u.width,height:(l=n==null?void 0:n.size)==null?void 0:l.height},{width:o==null?void 0:o.videoWidth,height:o==null?void 0:o.videoHeight})})).add(e.providerOutput.is3DVideo$.subscribe(this.info.is3DVideo$)),this.subscription.add(Vt(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(F(e=>e==null?void 0:e.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){let t=new hv;this.subscription.add(t),this.subscription.add(e.current$.pipe(q((r,i)=>r.provider===i.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(pe(r=>r.length>0),st()).subscribe(r=>{this.setStartingVideoTrack(r)}))}))}setStartingVideoTrack(e){var i;let t,r=(i=this.desiredState.videoTrack.getState())==null?void 0:i.quality;r&&(t=e.find(({quality:s})=>s===r),t||this.setAutoQuality(!0)),t||(t=$t(e,{container:this.domContainer.getBoundingClientRect(),throughput:this.throughputEstimator.throughput$.getValue(),tuning:this.tuning.autoTrackSelection,limits:this.desiredState.autoVideoTrackLimits.getState(),playbackRate:this.info.currentPlaybackRate$.getValue(),forwardBufferHealth:0,abrLogger:this.abrLogger})),this.desiredState.videoTrack.startTransitionTo(t),this.info.currentQuality$.next(t.quality),this.info.videoBitrate$.next(t.bitrate)}initLogs(){this.subscription.add(Vt(this.desiredState.videoTrack.stateChangeStarted$.pipe(F(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(F(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(F(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(F(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(F(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(F(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(F(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(F(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(F(e=>({component:"desiredState",message:`[${e.entity} change] ${e.type}: ${JSON.stringify(e.transition)}`}))).subscribe(this.logger.log)),this.subscription.add(this.logger.log$.subscribe(this.events.log$))}initDebugTelemetry(){var t;let e=(t=this.providerContainer)==null?void 0:t.providerOutput;yn(this.providerContainer),yn(e),kb(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(r=>wb(r)),this.providerContainer.current$.subscribe(({type:r})=>Mi("provider",r)),e.duration$.subscribe(r=>Mi("duration",r)),e.availableVideoTracks$.pipe(pe(r=>!!r.length),st()).subscribe(r=>Mi("tracks",r)),this.events.fatalError$.subscribe(new ce("fatalError")),this.events.managedError$.subscribe(new ce("managedError")),e.position$.subscribe(new ce("position")),e.currentVideoTrack$.pipe(F(r=>r==null?void 0:r.quality)).subscribe(new ce("quality")),this.info.currentBuffer$.subscribe(new ce("buffer")),e.isBuffering$.subscribe(new ce("isBuffering"))].forEach(r=>this.subscription.add(r)),Mi("codecs",pg())}initTracerSubscription(){let e=bv(this.tracer.log.bind(this.tracer)),t=bv(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(q()).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(Ot({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe(pe(({currentQuality:r,videoBitrate:i})=>!!r&&!!i),q((r,i)=>r.currentQuality===i.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe(pe(r=>r>0),q()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe(pe(r=>r>0),q()).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(Ot({currentBuffer:this.info.currentBuffer$.pipe(pe(r=>r.end>0),q((r,i)=>r.end===i.end&&r.start===i.start)),position:this.info.position$.pipe(q())}).pipe(Ml(1e3)).subscribe(e("currentBufferAndPosition"))).add(this.info.duration$.pipe(q()).subscribe(e("duration"))).add(this.info.isBuffering$.subscribe(e("isBuffering"))).add(this.info.isLive$.pipe(q()).subscribe(e("isLive"))).add(this.info.canChangePlaybackSpeed$.pipe(q()).subscribe(e("canChangePlaybackSpeed"))).add(Ot({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe(pe(({liveTime:r,liveBufferTime:i})=>!!r&&!!i),Ml(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe(q(),pe(r=>r===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe(q(),pe(r=>r===!0)).subscribe(e("atLiveDurationEdge"))).add(this.info.muted$.pipe(q()).subscribe(e("muted"))).add(this.info.volume$.pipe(q()).subscribe(e("volume"))).add(this.info.isEnded$.pipe(q(),pe(r=>r===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add(Ot({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe(pe(({throughputEstimation:r,rtt:i})=>!!r&&!!i),Ml(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe(q(),pe(r=>r===!0)).subscribe(e("is3DVideo"))).add(this.info.surface$.subscribe(e("surface"))).add(this.events.ended$.subscribe(e("ended"))).add(this.events.looped$.subscribe(e("looped"))).add(this.events.managedError$.subscribe(t("managedError"))).add(this.events.fatalError$.subscribe(t("fatalError"))).add(this.events.firstBytes$.subscribe(e("firstBytes"))).add(this.events.firstFrame$.subscribe(e("firstFrame"))).add(this.events.canplay$.subscribe(e("canplay")))}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e,t=()=>{e==null||e.release(),e=void 0},r=()=>R(this,null,function*(){t(),e=yield window.navigator.wakeLock.request("screen").catch(i=>{i instanceof DOMException&&i.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:Tn.DOM,message:String(i)})})});this.subscription.add(Vt(Ll(document,"visibilitychange"),Ll(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{let i=document.visibilityState==="visible",s=this.desiredState.playbackState.getState()==="playing",n=!!e&&!(e!=null&&e.released);i&&s?n||r():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){let r=e.find(i=>i.quality===t);this.tracer.log("setVideoTrackIdByQuality",_t({quality:t,availableTracks:_t(e),track:_t(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 GW,Observable as WW,Subject as YW,ValueSubject as QW,VideoQuality as zW}from"@vkontakte/videoplayer-shared";var KW=`@vkontakte/videoplayer-core@${mc}`;export{Wa as ChromecastState,Mn as HttpConnectionType,WW as Observable,fe as PlaybackState,En as Player,KW as SDK_VERSION,YW as Subject,GW as Subscription,Cn as Surface,mc as VERSION,QW as ValueSubject,xt as VideoFormat,zW as VideoQuality};
119
+ `;var un=class{constructor(e,t,r){this.videoInitialized=!1;this.active=!1;this.container=e,this.sourceVideoElement=t,this.params=r,this.canvas=this.createCanvas();let i=this.canvas.getContext("webgl");if(!i)throw new Error("Could not initialize WebGL context");this.gl=i,this.container.appendChild(this.canvas),this.camera=new nn(this.params.fov,this.params.orientation),this.cameraRotationManager=new on(this.camera,{rotationSpeed:this.params.rotationSpeed,maxYawAngle:this.params.maxYawAngle,rotationSpeedCorrection:this.params.rotationSpeedCorrection,degreeToPixelCorrection:this.params.degreeToPixelCorrection,speedFadeTime:this.params.speedFadeTime,speedFadeThreshold:this.params.speedFadeThreshold}),this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.textureMappingBuffer=this.createTextureMappingBuffer(),this.updateTextureMappingBuffer(),this.program=this.createProgram(),this.videoTexture=this.createTexture(),this.gl.useProgram(this.program),this.videoElementDataLoadedFn=this.onDataLoadedHandler.bind(this),this.renderFn=this.render.bind(this)}play(){this.active||(this.videoInitialized?this.doPlay():this.sourceVideoElement.readyState>=2?(this.videoInitialized=!0,this.doPlay()):this.sourceVideoElement.addEventListener("loadeddata",this.videoElementDataLoadedFn))}stop(){this.active=!1}startCameraManualRotation(e,t){this.cameraRotationManager.setRotationSpeed(e*this.params.rotationSpeed,t*this.params.rotationSpeed,0),this.cameraRotationManager.startRotation()}stopCameraManualRotation(e=!1){this.cameraRotationManager.stopRotation(e)}turnCamera(e,t){this.cameraRotationManager.turnCamera(e,t)}pointCameraTo(e,t){this.cameraRotationManager.pointCameraTo(e,t)}pixelToDegree(e){return{x:this.params.degreeToPixelCorrection*this.params.fov.x*-e.x/this.viewportWidth,y:this.params.degreeToPixelCorrection*this.params.fov.y*e.y/this.viewportHeight}}getCameraRotation(){return this.camera.orientation}holdCamera(){this.cameraRotationManager.stopRotation(!0)}releaseCamera(){this.cameraRotationManager.onCameraRelease()}destroy(){this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),this.stop(),this.canvas.remove()}setViewportSize(e,t){this.viewportWidth=e,this.viewportHeight=t,this.canvas.width=this.viewportWidth,this.canvas.height=this.viewportHeight,this.gl.viewport(0,0,this.canvas.width,this.canvas.height)}onDataLoadedHandler(){this.videoInitialized=!0,this.doPlay()}doPlay(){this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.active=!0,this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),requestAnimationFrame(this.renderFn)}render(e){this.cameraRotationManager.tick(e),this.updateTexture(),this.updateTextureMappingBuffer();let t=this.gl.getAttribLocation(this.program,"a_vertex"),r=this.gl.getAttribLocation(this.program,"a_texel"),i=this.gl.getUniformLocation(this.program,"u_texture"),s=this.gl.getUniformLocation(this.program,"u_focus");this.gl.enableVertexAttribArray(t),this.gl.enableVertexAttribArray(r),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.vertexBuffer),this.gl.vertexAttribPointer(t,2,this.gl.FLOAT,!1,0,0),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.vertexAttribPointer(r,2,this.gl.FLOAT,!1,0,0),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.uniform1i(i,0),this.gl.uniform2f(s,-this.camera.orientation.x,-this.camera.orientation.y),this.gl.drawArrays(this.gl.TRIANGLE_FAN,0,4),this.gl.bindTexture(this.gl.TEXTURE_2D,null),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),this.gl.disableVertexAttribArray(t),this.gl.disableVertexAttribArray(r),this.active&&requestAnimationFrame(this.renderFn)}createShader(e,t){let r=this.gl.createShader(t);if(!r)throw this.destroy(),new Error(`Could not create shader (${t})`);if(this.gl.shaderSource(r,e),this.gl.compileShader(r),!this.gl.getShaderParameter(r,this.gl.COMPILE_STATUS))throw this.destroy(),new Error("An error occurred while compiling the shader: "+this.gl.getShaderInfoLog(r));return r}createProgram(){let e=this.gl.createProgram();if(!e)throw this.destroy(),new Error("Could not create shader program");let t=this.createShader(TS,this.gl.VERTEX_SHADER),r=this.createShader(IS,this.gl.FRAGMENT_SHADER);if(this.gl.attachShader(e,t),this.gl.attachShader(e,r),this.gl.linkProgram(e),!this.gl.getProgramParameter(e,this.gl.LINK_STATUS))throw this.destroy(),new Error("Could not link shader program.");return e}createTexture(){let e=this.gl.createTexture();if(!e)throw this.destroy(),new Error("Could not create texture");return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.bindTexture(this.gl.TEXTURE_2D,null),e}updateTexture(){this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,!0),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.sourceVideoElement),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}createVertexBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create vertex buffer");let t=1,r=1,i=this.frameHeight/(this.frameWidth/this.viewportWidth);return i>this.viewportHeight?t=this.viewportHeight/i:r=i/this.viewportHeight,this.gl.bindBuffer(this.gl.ARRAY_BUFFER,e),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-t,-r,t,-r,t,r,-t,r]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),e}createTextureMappingBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create texture mapping buffer");return e}calculateTexturePosition(){let e=.5-this.camera.orientation.x/360,t=.5-this.camera.orientation.y/180,r=this.camera.fov.x/360/2,i=this.camera.fov.y/180/2,s=e-r,n=t-i,o=e+r,u=t-i,l=e+r,c=t+i,d=e-r,h=t+i;return[s,n,o,u,l,c,d,h]}updateTextureMappingBuffer(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([...this.calculateTexturePosition()]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}updateFrameSize(){this.frameWidth=this.sourceVideoElement.videoWidth,this.frameHeight=this.sourceVideoElement.videoHeight}createCanvas(){let e=document.createElement("canvas");return e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e}};var dr=class{constructor(e){this.subscription=new zR;this.videoState=new C("stopped");this.elementSize$=new KR(void 0);this.textTracksManager=new _e;this.droppedFramesManager=new Vs;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new Mi;this.audioTrackSwitchHistory=new Mi;this.syncPlayback=()=>{var n,o,u;let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),i=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(i.state==="requested"&&(r==null?void 0:r.to)!=="paused"&&e!=="stopped"&&t!=="stopped"){let l=(o=(n=this.liveOffset)==null?void 0:n.getTotalPausedTime())!=null?o:0;this.seek(i.position-l,i.forcePrecise)}if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.player.stop(),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),x(this.params.desiredState.playbackState,"stopped",!0));return}switch(e){case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();return;case"ready":t==="paused"?(this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="ready"&&x(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),(u=this.liveOffset)==null||u.pause(),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(r==null?void 0:r.to)==="playing"&&x(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.liveOffset?this.liveOffset.getTotalOffset()/1e3<Math.abs(this.params.output.duration$.getValue())?(this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(0,!1):this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&x(this.params.desiredState.playbackState,"paused");return;default:return qR(e)}}};this.init3DScene=e=>{var r,i,s;if(this.scene3D)return;this.scene3D=new un(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:((r=e.projectionData)==null?void 0:r.pose.yaw)||0,y:((i=e.projectionData)==null?void 0:i.pose.pitch)||0,z:((s=e.projectionData)==null?void 0:s.pose.roll)||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});let t=this.elementSize$.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};this.params=e,this.video=be(e.container,e.tuning),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(re(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.player=new sn({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode,tracer:this.tracer}),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params,r=ve(this.video),i=this.constructor.name,s=o=>{e.error$.next({id:i,category:ml.WTF,message:`${i} internal logic error`,thrown:o})};return{output:e,desiredState:t,observableVideo:r,genericErrorListener:s,connect:(o,u)=>this.subscription.add(o.subscribe(u,s))}}subscribe(){var l;let{output:e,desiredState:t,observableVideo:r,genericErrorListener:i,connect:s}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe(ES(c=>!!c.length),PS()).subscribe(c=>{this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:r.playing$,pause$:r.pause$,tracks:c})})),s(r.ended$,e.endedEvent$),s(r.looped$,e.loopedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentBuffer$),s(r.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),s(r.loadedMetadata$,e.loadedMetadataEvent$),s(this.player.error$,e.error$),s(this.player.lastConnectionType$,e.httpConnectionType$),s(this.player.lastConnectionReused$,e.httpConnectionReused$),s(this.player.isLive$,e.isLive$),s(this.player.lastRequestFirstBytes$.pipe(ES(WR),PS()),e.firstBytesEvent$),s(this.videoState.stateChangeEnded$.pipe(xS(c=>c.to)),this.params.output.playbackState$),this.subscription.add(r.seeked$.subscribe(e.seekedEvent$,i)),this.subscription.add(rt(this.video,t.isLooped,i)),this.subscription.add(Se(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Ve(this.video,t.playbackRate,r.playbackRateState$,i)),s(QR(this.video),this.elementSize$),s(Fe(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),x(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),x(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:c})=>{if(c==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let d=this.player.getStreams();if(HR(d,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let p=[];for(let f of d.audio){p.push(il(f));let b=[];for(let g of f.representations){let T=nS(g);b.push(T),this.audioTracksMap.set(T,{stream:f,representation:g})}this.audioStreamsMap.set(f,b)}this.params.output.availableAudioStreams$.next(p)}let h=[];for(let p of d.video){h.push(al(p));let f=[];for(let b of p.representations){let g=sS(b);g&&(f.push(g),this.videoTracksMap.set(g,{stream:p,representation:b}))}this.videoStreamsMap.set(p,f)}if(this.params.output.availableVideoStreams$.next(h),this.textTracksManager)for(let p of d.text)for(let f of p.representations){let b=oS(p,f);this.textTracksMap.set(b,{stream:p,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())},i));let n=c=>e.error$.next({id:"RepresentationSwitch",category:ml.WTF,message:"Switching representations threw",thrown:c});this.subscription.add(ln(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$,GR(this.video,"progress")).subscribe(()=>{let c=this.player.state$.getState(),d=this.player.state$.getTransition();if(!["manifest_ready","running"].includes(c)||d)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let h=this.selectVideoAudioRepresentations();if(!h)return;let[p,f]=h,b=this.params.desiredState.autoVideoTrackLimits.getTransition();if(b&&this.params.output.autoVideoTrackLimits$.next(b.to),c==="manifest_ready")this.player.initRepresentations(p.id,f==null?void 0:f.id,this.params.sourceHls);else if(this.player.switchRepresentation("video",p.id).catch(n),f){let g=!!t.audioStream.getTransition();this.player.switchRepresentation("audio",f.id,g).catch(n)}},i)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:c})=>{this.scene3D&&c&&this.scene3D.pointCameraTo(c.x,c.y)})),this.subscription.add(this.elementSize$.subscribe(c=>{this.scene3D&&c&&this.scene3D.setViewportSize(c.width,c.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(bl()).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[h,{stream:p}]=d,f=this.params.desiredState.videoStream.getTransition();f&&f.to&&f.to.id===p.id&&this.params.desiredState.videoStream.setState(f.to),e.currentVideoTrack$.next(h),e.currentVideoStream$.next(al(p))},i)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(bl()).subscribe(c=>{let d=[...this.audioTracksMap.entries()].find(([,{representation:b}])=>b.id===c);if(!d){e.currentAudioStream$.next(void 0);return}let[h,{stream:p}]=d,f=this.params.desiredState.audioStream.getTransition();f&&f.to&&f.to.id===p.id&&this.params.desiredState.audioStream.setState(f.to),e.currentAudioStream$.next(il(p))},i)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(c=>{var d,h;if(c!=null&&c.is3dVideo&&((d=this.params.tuning.spherical)!=null&&d.enabled))try{this.init3DScene(c),e.is3DVideo$.next(!0)}catch(p){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${p}`})}else this.destroy3DScene(),(h=this.params.tuning.spherical)!=null&&h.enabled&&e.is3DVideo$.next(!1)},i)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,i)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,i)),(l=this.textTracksManager)==null||l.connect(this.video,t,e);let o=t.playbackState.stateChangeStarted$.pipe(xS(({to:c})=>c==="ready"),bl());this.subscription.add(ln(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$).subscribe(()=>{let c=t.autoVideoTrackSwitching.getState(),h=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:c?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(h)})),this.subscription.add(ln(o,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let u=ln(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,YR(["init"])).pipe(jR(0));this.subscription.add(u.subscribe(this.syncPlayback,i))}selectVideoAudioRepresentations(){var k,B,G,V,M,_,R,U,L,W,v,$,Q;let{desiredState:e,output:t}=this.params,r=e.autoVideoTrackSwitching.getState(),i=(k=e.videoTrack.getState())==null?void 0:k.id,n=[...this.videoTracksMap.keys()].find(({id:N})=>N===i),o=t.currentVideoTrack$.getValue(),u=((V=(G=e.videoStream.getState())!=null?G:n&&((B=this.videoTracksMap.get(n))==null?void 0:B.stream))!=null?V:this.videoStreamsMap.size===1)?this.videoStreamsMap.keys().next().value:void 0;if(!u)return;let l=[...this.videoStreamsMap.keys()].find(({id:N})=>N===u.id),c=l&&this.videoStreamsMap.get(l);if(!c)return;let d=at(this.video.buffered,this.video.currentTime*1e3),h=r?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,p=Math.min(d/Math.min(h,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),f=(M=e.audioStream.getState())!=null?M:this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0,b=(_=[...this.audioStreamsMap.keys()].find(({id:N})=>N===(f==null?void 0:f.id)))!=null?_:this.audioStreamsMap.keys().next().value,g=0;if(b){if(n&&!r){let N=Cs(n,c,(R=this.audioStreamsMap.get(b))!=null?R:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);g=Math.max(g,(U=N==null?void 0:N.bitrate)!=null?U:-1/0)}if(o){let N=Cs(o,c,(L=this.audioStreamsMap.get(b))!=null?L:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);g=Math.max(g,(W=N==null?void 0:N.bitrate)!=null?W:-1/0)}}let T=$t(c,{container:this.elementSize$.getValue(),throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:g,forwardBufferHealth:p,current:o,visible:this.params.output.elementVisible$.getValue(),history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),y=r?T!=null?T:n:n!=null?n:T,S=b&&Vb(y,c,(v=this.audioStreamsMap.get(b))!=null?v:[],{throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:p,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),I=($=this.videoTracksMap.get(y))==null?void 0:$.representation,E=S&&((Q=this.audioTracksMap.get(S))==null?void 0:Q.representation);if(I&&E)return[I,E];if(I&&!E&&this.audioTracksMap.size===0)return[I,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){ye(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{var t;e||((t=this.liveOffset)==null||t.pause(),this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:ml.DOM,thrown:e}))}destroy(){var e;this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.destroy3DScene(),(e=this.textTracksManager)==null||e.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),ge(this.video),this.tracer.end()}};var Ta=class extends dr{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 AS,interval as JR,map as XR}from"@vkontakte/videoplayer-shared";var Ia=class extends dr{constructor(e){super(e),this.liveOffset=new dt,this.textTracksManager=null}subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:r}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),r(t.timeUpdate$,e.liveBufferTime$),r(this.player.liveDuration$,e.duration$),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(AS({interval:JR(1e3),playbackRate:t.playbackRateState$}).subscribe(({playbackRate:i})=>{var s;if(this.videoState.getState()==="playing"){let n=e.position$.getValue()+(i-1);n<=0&&e.position$.next(n),(s=this.liveOffset)==null||s.resetTo(-n*1e3)}})).add(AS({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(XR(({liveBufferTime:i,liveAvailabilityStartTime:s})=>i&&s?i+s:void 0)).subscribe(e.liveTime$)).add(this.player.currentLiveTextRepresentation$.subscribe(i=>{if(i){let s=uS(i);this.params.output.availableTextTracks$.next([s])}}))}seek(e){this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),r=this.videoState.getState(),i=t==="paused"&&r==="paused",s=-e,n=Math.trunc(s/1e3<=Math.abs(this.params.output.duration$.getValue())?s:0);this.player.seekLive(n).then(()=>{var o;this.params.output.position$.next(e/1e3),(o=this.liveOffset)==null||o.resetTo(n,i)})}};var kS=Ge($s(),1);import{assertNever as Ea,assertNonNullable as wS,debounce as ZR,ErrorCategory as cn,filter as e$,isNonNullable as t$,isNullable as r$,map as dn,merge as i$,Observable as a$,observableFrom as s$,Subscription as n$,videoSizeToQuality as o$}from"@vkontakte/videoplayer-shared";var Je={};var zr=(a,e)=>new a$(t=>{let r=(i,s)=>t.next(s);return a.on(e,r),()=>a.off(e,r)}),xa=class{constructor(e){this.subscription=new n$;this.videoState=new C("initializing");this.textTracksManager=new _e;this.trackLevels=new Map;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),i=this.params.desiredState.seekState.getState();if(e!=="initializing")switch((r==null?void 0:r.to)!=="paused"&&i.state==="requested"&&this.seek(i.position),t){case"stopped":switch(e){case"stopped":break;case"ready":case"playing":case"paused":this.stop();break;default:Ea(e)}break;case"ready":switch(e){case"stopped":this.prepare();break;case"ready":case"playing":case"paused":break;default:Ea(e)}break;case"playing":switch(e){case"playing":break;case"stopped":this.prepare();break;case"ready":case"paused":this.playIfAllowed();break;default:Ea(e)}break;case"paused":switch(e){case"paused":break;case"stopped":this.prepare();break;case"ready":this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused");break;case"playing":this.pause();break;default:Ea(e)}break;default:Ea(t)}};this.video=be(e.container,e.tuning),this.params=e,this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(re(this.params.source.url)),this.loadHlsJs()}destroy(){var e,t;this.subscription.unsubscribe(),this.trackLevels.clear(),this.textTracksManager.destroy(),(e=this.hls)==null||e.detachMedia(),(t=this.hls)==null||t.destroy(),this.params.output.element$.next(void 0),ge(this.video)}loadHlsJs(){let e=!1,t=i=>{e||this.params.output.error$.next({id:i==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:cn.NETWORK,message:"Failed to load Hls.js",thrown:i}),e=!0},r=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);(0,kS.default)(import("hls.js").then(i=>{e||(Je.Hls=i.default,Je.Events=i.default.Events,this.init())},t),()=>{window.clearTimeout(r),e=!0})}init(){wS(Je.Hls,"hls.js not loaded"),this.hls=new Je.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState("stopped")}subscribe(){wS(Je.Events,"hls.js not loaded");let{desiredState:e,output:t}=this.params,r=l=>{t.error$.next({id:"HlsJsProvider",category:cn.WTF,message:"HlsJsProvider internal logic error",thrown:l})},i=ve(this.video),s=(l,c)=>this.subscription.add(l.subscribe(c,r));s(i.timeUpdate$,t.position$),s(i.durationChange$,t.duration$),s(i.ended$,t.endedEvent$),s(i.looped$,t.loopedEvent$),s(i.error$,t.error$),s(i.isBuffering$,t.isBuffering$),s(i.currentBuffer$,t.currentBuffer$),s(i.loadStart$,t.firstBytesEvent$),s(i.loadedMetadata$,t.loadedMetadataEvent$),s(i.playing$,t.firstFrameEvent$),s(i.canplay$,t.canplay$),s(i.seeked$,t.seekedEvent$),s(i.inPiP$,t.inPiP$),s(i.inFullscreen$,t.inFullscreen$),this.subscription.add(rt(this.video,e.isLooped,r)),this.subscription.add(Se(this.video,e.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(Ve(this.video,e.playbackRate,i.playbackRateState$,r)),s(Fe(this.video),t.elementVisible$),s(this.videoState.stateChangeEnded$.pipe(dn(l=>l.to)),this.params.output.playbackState$),this.subscription.add(zr(this.hls,Je.Events.ERROR).subscribe(l=>{var c;l.fatal&&t.error$.next({id:["HlsJsFatal",l.type,l.details].join("_"),category:cn.WTF,message:`HlsJs fatal ${l.type} ${l.details}, ${(c=l.err)==null?void 0:c.message} ${l.reason}`,thrown:l.error})})),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),x(e.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),x(e.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{var l;((l=this.videoState.getTransition())==null?void 0:l.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),s(zr(this.hls,Je.Events.MANIFEST_PARSED).pipe(dn(({levels:l})=>l.reduce((c,d)=>{var y,S;let h=d.name||d.height.toString(10),{width:p,height:f}=d,b=(S=Rt((y=d.attrs.QUALITY)!=null?y:""))!=null?S:o$({width:p,height:f});if(!b)return c;let g=d.attrs["FRAME-RATE"]?parseFloat(d.attrs["FRAME-RATE"]):void 0,T={id:h.toString(),quality:b,bitrate:d.bitrate/1e3,size:{width:p,height:f},fps:g};return this.trackLevels.set(h,{track:T,level:d}),c.push(T),c},[]))),t.availableVideoTracks$),s(zr(this.hls,Je.Events.MANIFEST_PARSED),l=>{if(l.subtitleTracks.length>0){let c=[];for(let d of l.subtitleTracks){let h=d.name,p=d.attrs.URI||"",f=d.lang;c.push({id:h,url:p,language:f,type:"internal"})}e.internalTextTracks.startTransitionTo(c)}}),s(zr(this.hls,Je.Events.LEVEL_LOADING).pipe(dn(({url:l})=>re(l))),t.hostname$),s(zr(this.hls,Je.Events.FRAG_CHANGED),l=>{var h,p,f,b;let{video:c,audio:d}=l.frag.elementaryStreams;t.currentVideoSegmentLength$.next((((h=c==null?void 0:c.endPTS)!=null?h:0)-((p=c==null?void 0:c.startPTS)!=null?p:0))*1e3),t.currentAudioSegmentLength$.next((((f=d==null?void 0:d.endPTS)!=null?f:0)-((b=d==null?void 0:d.startPTS)!=null?b:0))*1e3)}),this.subscription.add(At(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,l=>{this.hls.nextLevel=l?-1:this.hls.currentLevel,this.hls.loadLevel=l?-1:this.hls.loadLevel},{onError:r}));let n=l=>{var c;return(c=Array.from(this.trackLevels.values()).find(({level:d})=>d===l))==null?void 0:c.track},o=zr(this.hls,Je.Events.LEVEL_SWITCHED).pipe(dn(({level:l})=>n(this.hls.levels[l])));o.pipe(e$(t$)).subscribe(t.currentVideoTrack$,r),this.subscription.add(At(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel]),l=>{var f;if(r$(l))return;let c=(f=this.trackLevels.get(l.id))==null?void 0:f.level;if(!c)return;let d=this.hls.levels.indexOf(c),h=this.hls.currentLevel,p=this.hls.levels[h];!p||c.bitrate>p.bitrate?this.hls.nextLevel=d:(this.hls.loadLevel=d,this.hls.loadLevel=d)},{changed$:o,onError:r})),s(i.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);let u=i$(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,s$(["init"])).pipe(ZR(0));this.subscription.add(u.subscribe(this.syncPlayback,r))}prepare(){this.videoState.startTransitionTo("ready"),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}playIfAllowed(){return w(this,null,function*(){this.videoState.startTransitionTo("playing"),(yield ye(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:cn.DOM,thrown:t})))||(this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused",!0))})}pause(){this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}stop(){this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.hls.stopLoad(),this.hls.detachMedia(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState("stopped"),x(this.params.desiredState.playbackState,"stopped",!0)}};var RS="X-Playback-Duration",gl=a=>w(void 0,null,function*(){var i;let e=yield ht(a),t=yield e.text(),r=(i=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t))==null?void 0:i[1];return r?parseInt(r,10):e.headers.has(RS)?parseInt(e.headers.get(RS),10):void 0});import{assertNever as h$,combine as f$,debounce as m$,ErrorCategory as hn,filter as b$,filterChanged as g$,isNonNullable as LS,isNullable as fn,map as MS,merge as S$,observableFrom as v$,Subscription as y$,ValueSubject as yl,VideoQuality as T$}from"@vkontakte/videoplayer-shared";var vl=Ge(Bo(),1);import{videoSizeToQuality as u$,getExponentialDelay as l$}from"@vkontakte/videoplayer-shared";var c$=a=>{let e=null;if(a.QUALITY&&(e=Rt(a.QUALITY)),!e&&a.RESOLUTION){let[t,r]=a.RESOLUTION.split("x").map(i=>parseInt(i,10));e=u$({width:t,height:r})}return e!=null?e:null},d$=(a,e)=>{var s,n;let t=a.split(`
120
+ `),r=[],i=[];for(let o=0;o<t.length;o++){let u=t[o],l=u.match(/^#EXT-X-STREAM-INF:(.+)/),c=u.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!l&&!c)){if(l){let d=(0,vl.default)(l[1].split(",").map(y=>y.split("="))),h=(s=d.QUALITY)!=null?s:`stream-${d.BANDWIDTH}`,p=c$(d),f;d.BANDWIDTH&&(f=parseInt(d.BANDWIDTH,10)/1e3||void 0),!f&&d["AVERAGE-BANDWIDTH"]&&(f=parseInt(d["AVERAGE-BANDWIDTH"],10)/1e3||void 0);let b=d["FRAME-RATE"]?parseFloat(d["FRAME-RATE"]):void 0,g;if(d.RESOLUTION){let[y,S]=d.RESOLUTION.split("x").map(I=>parseInt(I,10));y&&S&&(g={width:y,height:S})}let T=new URL(t[++o],e).toString();p&&r.push({id:h,quality:p,url:T,bandwidth:f,size:g,fps:b})}if(c){let d=(0,vl.default)(c[1].split(",").map(b=>b.split("=")).map(([b,g])=>[b,g.replace(/^"|"$/g,"")])),h=(n=d.URI)==null?void 0:n.replace(/playlist$/,"subtitles.vtt"),p=d.LANGUAGE,f=d.NAME;h&&p&&i.push({type:"internal",id:p,label:f,language:p,url:h,isAuto:!1})}}}if(!r.length)throw new Error("Empty manifest");return{qualityManifests:r,textTracks:i}},p$=a=>new Promise(e=>{setTimeout(()=>{e()},a)}),Sl=0,$S=(r,...i)=>w(void 0,[r,...i],function*(a,e=a,t){let n=yield(yield ht(a)).text();Sl+=1;try{let{qualityManifests:o,textTracks:u}=d$(n,e);return{qualityManifests:o,textTracks:u}}catch(o){if(Sl<=t.manifestRetryMaxCount)return yield p$(l$(Sl-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),$S(a,e,t)}return{qualityManifests:[],textTracks:[]}}),pn=$S;var Pa=class{constructor(e){this.subscription=new y$;this.videoState=new C("stopped");this.textTracksManager=new _e;this.manifests$=new yl([]);this.liveOffset=new dt;this.manifestStartTime$=new yl(void 0);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),r=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(r==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),x(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||n||o){let c=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(c),this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if((i==null?void 0:i.to)!=="paused"&&l.state==="requested"){this.videoState.startTransitionTo("ready"),this.seek(l.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(t){case"ready":r==="ready"?x(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),x(this.params.desiredState.playbackState,"paused")):r==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":r==="paused"?(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(i==null?void 0:i.to)==="playing"&&x(this.params.desiredState.playbackState,"playing");return;case"paused":if(r==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let c=this.liveOffset.getTotalOffset();c>=this.maxSeekBackTime$.getValue()&&(c=0,this.liveOffset.resetTo(c)),this.liveOffset.resume(),this.params.output.position$.next(-c/1e3),this.prepare()}else(i==null?void 0:i.to)==="paused"&&(x(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return h$(t)}};var t;this.params=e,this.video=be(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:T$.INVARIANT,url:this.params.source.url},pn(ne(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:r})=>{r.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:hn.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),this.manifests$.next([this.masterManifest,...r])},r=>this.params.output.error$.next({id:"ExtractHlsQualities",category:hn.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:r})),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(re(this.params.source.url)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.maxSeekBackTime$=new yl((t=e.source.maxSeekBackTime)!=null?t:1/0),this.subscribe()}selectManifest(){var u,l,c,d;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,r=e.getState(),i=t.getTransition(),s=(d=(c=(u=i==null?void 0:i.to)==null?void 0:u.id)!=null?c:(l=t.getState())==null?void 0:l.id)!=null?d:"master",n=this.manifests$.getValue();if(!n.length)return;let o=r?"master":s;return r&&!i&&t.startTransitionTo(this.masterManifest),n.find(h=>h.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"HlsLiveProvider",category:hn.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},i=ve(this.video),s=(o,u)=>this.subscription.add(o.subscribe(u,r));s(i.ended$,e.endedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(i.loadedMetadata$,e.firstBytesEvent$),s(i.loadedMetadata$,e.loadedMetadataEvent$),s(i.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),r)),this.subscription.add(Se(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Ve(this.video,t.playbackRate,i.playbackRateState$,r)),s(Fe(this.video),e.elementVisible$),this.textTracksManager.connect(this.video,t,e),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),x(t.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),x(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())==null?void 0:o.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.subscription.add(this.maxSeekBackTime$.pipe(g$(),MS(o=>-o/1e3)).subscribe(this.params.output.duration$,r)),this.subscription.add(i.loadedMetadata$.subscribe(()=>{let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&LS(l.to)){let d=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let h=this.manifests$.getValue().find(p=>p.id===d);h&&(this.params.output.currentVideoTrack$.next(h),this.params.output.hostname$.next(re(h.url)))}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o&&o.state==="requested"&&this.seek(o.position)},r)),this.subscription.add(i.loadedData$.subscribe(()=>{var u,l,c;let o=(c=(l=(u=this.video)==null?void 0:u.getStartDate)==null?void 0:l.call(u))==null?void 0:c.getTime();this.manifestStartTime$.next(o||void 0)},r)),this.subscription.add(f$({startTime:this.manifestStartTime$.pipe(b$(LS)),currentTime:i.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),r)),this.subscription.add(this.manifests$.pipe(MS(o=>o.map(({id:u,quality:l,size:c,bandwidth:d,fps:h})=>({id:u,quality:l,size:c,fps:h,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,r));let n=S$(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,v$(["init"])).pipe(m$(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),ge(this.video)}prepare(){var o,u;let e=this.selectManifest();if(fn(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),r=this.params.desiredState.autoVideoTrackLimits.getState(),i=new URL(e.url);if((t||r)&&e.id===this.masterManifest.id){let{max:l,min:c}=(u=(o=t==null?void 0:t.to)!=null?o:r)!=null?u:{};for(let[d,h]of[[l,"mq"],[c,"lq"]]){let p=String(parseFloat(d||""));h&&d&&i.searchParams.set(h,p)}}let s=this.params.format==="HLS_LIVE_CMAF"?2:0,n=ne(i.toString(),this.liveOffset.getTotalOffset(),s);this.video.setAttribute("src",n),this.video.load(),gl(n).then(l=>{var c;if(!fn(l))this.maxSeekBackTime$.next(l);else{let d=(c=this.params.source.maxSeekBackTime)!=null?c:this.maxSeekBackTime$.getValue();if(fn(d)||!isFinite(d))try{ht(n).then(h=>h.text()).then(h=>{var f;let p=(f=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(h))==null?void 0:f[1];if(p){let b=new URL(p,n).toString();gl(b).then(g=>{fn(g)||this.maxSeekBackTime$.next(g)})}})}catch(h){}}})}playIfAllowed(){ye(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),x(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:hn.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,r=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(r),this.params.output.position$.next(-r/1e3),this.params.output.seekedEvent$.next()}};import{assertNever as I$,debounce as E$,ErrorCategory as Tl,fromEvent as Il,isNonNullable as x$,isNullable as P$,map as CS,merge as DS,observableFrom as BS,Subscription as A$,ValueSubject as w$,VideoQuality as k$,clientChecker as R$}from"@vkontakte/videoplayer-shared";var Aa=class{constructor(e){this.subscription=new A$;this.videoState=new C("stopped");this.textTracksManager=new _e;this.manifests$=new w$([]);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),r=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(r==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),x(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||n||o){let c=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(c);let{currentTime:d}=this.video;this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:d*1e3,forcePrecise:!0});return}switch((i==null?void 0:i.to)!=="paused"&&l.state==="requested"&&this.seek(l.position),t){case"ready":r==="ready"?x(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused")):r==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":r==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(i==null?void 0:i.to)==="playing"&&x(this.params.desiredState.playbackState,"playing");return;case"paused":r==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&x(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return I$(t)}};this.params=e,this.video=be(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:k$.INVARIANT,url:this.params.source.url},this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(re(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),pn(ne(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:Tl.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){var u,l,c,d;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,r=e.getState(),i=t.getTransition(),s=(d=(c=(u=i==null?void 0:i.to)==null?void 0:u.id)!=null?c:(l=t.getState())==null?void 0:l.id)!=null?d:"master",n=this.manifests$.getValue();if(!n.length)return;let o=r?"master":s;return r&&!i&&t.startTransitionTo(this.masterManifest),n.find(h=>h.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"HlsProvider",category:Tl.WTF,message:"HlsProvider internal logic error",thrown:o})},i=ve(this.video),s=(o,u)=>this.subscription.add(o.subscribe(u));if(s(i.timeUpdate$,e.position$),s(i.durationChange$,e.duration$),s(i.ended$,e.endedEvent$),s(i.looped$,e.loopedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(i.loadedMetadata$,e.firstBytesEvent$),s(i.loadedMetadata$,e.loadedMetadataEvent$),s(i.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.seeked$,e.seekedEvent$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe(CS(o=>o.to)),this.params.output.playbackState$),this.subscription.add(rt(this.video,t.isLooped,r)),this.subscription.add(Se(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Ve(this.video,t.playbackRate,i.playbackRateState$,r)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),x(t.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),x(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())==null?void 0:o.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},r).add(i.loadedMetadata$.subscribe(()=>{var d;let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&x$(l.to)){let h=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let p=this.manifests$.getValue().find(f=>f.id===h);if(p){this.params.output.currentVideoTrack$.next(p),this.params.output.hostname$.next(re(p.url));let f=this.params.desiredState.playbackRate.getState(),b=(d=this.params.output.element$.getValue())==null?void 0:d.playbackRate;if(f!==b){let g=this.params.output.element$.getValue();g&&(this.params.desiredState.playbackRate.setState(f),g.playbackRate=f)}}}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o.state==="requested"&&this.seek(o.position)},r))),this.subscription.add(this.manifests$.pipe(CS(o=>o.map(({id:u,quality:l,size:c,bandwidth:d,fps:h})=>({id:u,quality:l,size:c,fps:h,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,r)),!R$.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add(DS(Il(o,"addtrack"),Il(o,"removetrack"),Il(o,"change"),BS(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},r))}let n=DS(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,BS(["init"])).pipe(E$(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),ge(this.video)}prepare(){var s,n;let e=this.selectManifest();if(P$(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),r=this.params.desiredState.autoVideoTrackLimits.getState(),i=new URL(e.url);if((t||r)&&e.id===this.masterManifest.id){let{max:o,min:u}=(n=(s=t==null?void 0:t.to)!=null?s:r)!=null?n:{};for(let[l,c]of[[o,"mq"],[u,"lq"]]){let d=String(parseFloat(l||""));c&&l&&i.searchParams.set(c,d)}}this.video.setAttribute("src",i.toString()),this.video.load()}playIfAllowed(){ye(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Tl.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};import{assertNever as $$,assertNonNullable as OS,debounce as L$,ErrorCategory as VS,isHigher as M$,isHigherOrEqual as C$,isInvariantQuality as _S,isLowerOrEqual as D$,isNonNullable as B$,merge as O$,observableFrom as V$,Subscription as _$,map as N$}from"@vkontakte/videoplayer-shared";var wa=class{constructor(e){this.subscription=new _$;this.videoState=new C("stopped");this.trackUrls={};this.textTracksManager=new _e;this.syncPlayback=()=>{var u,l,c;let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),x(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let s=this.params.desiredState.autoVideoTrackLimits.getTransition(),n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.seekState.getState();if(s&&e!=="ready"&&!n){this.handleQualityLimitTransition(s.to.max);return}if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(n){let{currentTime:d}=this.video;this.prepare(),o.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:d*1e3,forcePrecise:!0}),n.to&&((u=this.params.desiredState.autoVideoTrackLimits.getState())==null?void 0:u.max)!==((c=(l=this.trackUrls[n.to.id])==null?void 0:l.track)==null?void 0:c.quality)&&this.params.output.autoVideoTrackLimits$.next({max:void 0});return}switch((r==null?void 0:r.to)!=="paused"&&o.state==="requested"&&this.seek(o.position),e){case"ready":t==="ready"?x(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(r==null?void 0:r.to)==="playing"&&x(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&x(this.params.desiredState.playbackState,"paused");return;default:return $$(e)}};this.params=e,this.video=be(e.container,e.tuning),this.params.output.element$.next(this.video),Object.entries(this.params.source).reverse().forEach(([t,r],i)=>{let s=i.toString(10);this.trackUrls[s]={track:{quality:t,id:s},url:r}}),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next(Object.values(this.trackUrls).map(({track:t})=>t)),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.desiredState.autoVideoTrackSwitching.setState(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.subscribe()}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"MpegProvider",category:VS.WTF,message:"MpegProvider internal logic error",thrown:o})},i=ve(this.video),s=(o,u)=>this.subscription.add(o.subscribe(u,r));s(i.timeUpdate$,e.position$),s(i.durationChange$,e.duration$),s(i.ended$,e.endedEvent$),s(i.looped$,e.loopedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(i.loadedMetadata$,e.firstBytesEvent$),s(i.loadedMetadata$,e.loadedMetadataEvent$),s(i.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.seeked$,e.seekedEvent$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe(N$(o=>o.to)),this.params.output.playbackState$),this.subscription.add(rt(this.video,t.isLooped,r)),this.subscription.add(Se(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Ve(this.video,t.playbackRate,i.playbackRateState$,r)),s(Fe(this.video),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),x(t.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),x(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{var u,l;((u=this.videoState.getTransition())==null?void 0:u.to)==="ready"&&this.videoState.setState("ready");let o=this.params.desiredState.videoTrack.getTransition();if(o&&B$(o.to)){this.params.desiredState.videoTrack.setState(o.to),this.params.output.currentVideoTrack$.next(this.trackUrls[o.to.id].track);let c=this.params.desiredState.playbackRate.getState(),d=(l=this.params.output.element$.getValue())==null?void 0:l.playbackRate;if(c!==d){let h=this.params.output.element$.getValue();h&&(this.params.desiredState.playbackRate.setState(c),h.playbackRate=c)}}this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.textTracksManager.connect(this.video,t,e);let n=O$(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,V$(["init"])).pipe(L$(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),ge(this.video)}prepare(){var r;let e=(r=this.params.desiredState.videoTrack.getState())==null?void 0:r.id;OS(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];OS(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=fa(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(re(t))}playIfAllowed(){ye(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:VS.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){var i,s,n,o;let t,r=e;if(e&&((i=this.params.output.currentVideoTrack$.getValue())==null?void 0:i.quality)!==e){let u=(s=Object.values(this.trackUrls).find(d=>!_S(d.track.quality)&&D$(d.track.quality,e)))==null?void 0:s.track,l=(n=this.params.desiredState.videoTrack.getState())==null?void 0:n.id,c=(o=this.trackUrls[l!=null?l:"0"])==null?void 0:o.track;if(u&&c&&C$(c.quality,u.quality)&&(t=u),!t){let d=Object.values(this.trackUrls).filter(p=>!_S(p.track.quality)&&M$(p.track.quality,e)),h=d.length;h&&(t=d[h-1].track)}t&&(r=t.quality)}else if(!e){let u=Object.values(this.trackUrls).map(l=>l.track);t=$t(u,{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},throughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:0,abrLogger:this.params.dependencies.abrLogger})}t&&(this.params.output.currentVideoTrack$.next(t),this.params.desiredState.videoTrack.startTransitionTo(t)),this.params.output.autoVideoTrackLimits$.next({max:r})}};import{assertNever as FS,debounce as H$,merge as US,observableFrom as j$,Subscription as G$,map as qS,ValueSubject as W$,ErrorCategory as xl,VideoQuality as Y$}from"@vkontakte/videoplayer-shared";import{ErrorCategory as F$}from"@vkontakte/videoplayer-shared";var NS=["stun:videostun.mycdn.me:80"],U$=1e3,q$=3,El=()=>null,mn=class{constructor(e,t){this.ws=null;this.peerConnection=null;this.serverUrl="";this.streamKey="";this.stream=null;this.signalingType="JOIN";this.retryCount=0;this.externalStartCallback=El;this.externalStopCallback=El;this.externalErrorCallback=El;this.options=this.normalizeOptions(t);let r=e.split("/");this.serverUrl=r.slice(0,r.length-1).join("/"),this.streamKey=r[r.length-1]}onStart(e){try{this.externalStartCallback=e}catch(t){this.handleSystemError(t)}}onStop(e){try{this.externalStopCallback=e}catch(t){this.handleSystemError(t)}}onError(e){try{this.externalErrorCallback=e}catch(t){this.handleSystemError(t)}}connect(){this.connectWS()}disconnect(){try{this.externalStopCallback(),this.closeConnections()}catch(e){this.handleSystemError(e)}}connectWS(){this.ws||(this.ws=new WebSocket(this.serverUrl),this.ws.onopen=this.onSocketOpen.bind(this),this.ws.onmessage=this.onSocketMessage.bind(this),this.ws.onclose=this.onSocketClose.bind(this),this.ws.onerror=this.onSocketError.bind(this))}onSocketOpen(){this.handleLogin()}onSocketClose(e){try{if(!this.ws)return;this.ws=null,e.code>1e3?(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():this.scheduleRetry()):this.externalStopCallback()}catch(t){this.handleRTCError(t)}}onSocketError(e){try{this.externalErrorCallback(new Error(e.toString()))}catch(t){this.handleRTCError(t)}}onSocketMessage(e){try{let t=this.parseMessage(e.data);switch(t.type){case"JOIN":case"CALL_JOIN":this.handleJoinMessage(t);break;case"UPDATE":this.handleUpdateMessage(t);break;case"STATUS":this.handleStatusMessage(t);break}}catch(t){this.handleRTCError(t)}}handleJoinMessage(e){switch(e.inviteType){case"ANSWER":this.handleAnswer(e.sdp);break;case"CANDIDATE":this.handleCandidate(e.candidate);break}}handleStatusMessage(e){switch(e.status){case"UNPUBLISHED":this.handleUnpublished();break}}handleUpdateMessage(e){return w(this,null,function*(){try{let t=yield this.createOffer();this.peerConnection&&(yield this.peerConnection.setLocalDescription(t)),this.handleAnswer(e.sdp)}catch(t){this.handleRTCError(t)}})}handleLogin(){return w(this,null,function*(){try{let e={iceServers:[{urls:NS}]};this.peerConnection=new RTCPeerConnection(e),this.peerConnection.ontrack=this.onPeerConnectionStream.bind(this),this.peerConnection.onicecandidate=this.onPeerConnectionIceCandidate.bind(this),this.peerConnection.oniceconnectionstatechange=this.onPeerConnectionIceConnectionStateChange.bind(this);let t=yield this.createOffer();yield this.peerConnection.setLocalDescription(t),this.send({type:this.signalingType,inviteType:"OFFER",streamKey:this.streamKey,sdp:t.sdp,callSupport:!1})}catch(e){this.handleRTCError(e)}})}handleAnswer(e){return w(this,null,function*(){try{this.peerConnection&&(yield this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e})))}catch(t){this.handleRTCError(t)}})}handleCandidate(e){return w(this,null,function*(){if(e)try{this.peerConnection&&(yield this.peerConnection.addIceCandidate(e))}catch(t){this.handleRTCError(t)}})}handleUnpublished(){try{this.closeConnections(),this.externalStopCallback()}catch(e){this.handleRTCError(e)}}handleSystemError(e){this.options.errorChanel&&this.options.errorChanel.next({id:"webrtc-provider-error",category:F$.WTF,message:e.message})}onPeerConnectionStream(e){return w(this,null,function*(){let t=e.streams[0];this.stream&&this.stream.id===t.id||(this.stream=t,this.externalStartCallback(this.stream))})}onPeerConnectionIceCandidate(e){e.candidate&&this.send({type:this.signalingType,inviteType:"CANDIDATE",candidate:e.candidate})}onPeerConnectionIceConnectionStateChange(){if(this.peerConnection){let e=this.peerConnection.iceConnectionState;["failed","closed"].indexOf(e)>-1&&(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():(this.closeConnections(),this.scheduleRetry()))}}createOffer(){return w(this,null,function*(){let e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");let t=yield this.peerConnection.createOffer(e),r=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(r))throw new Error("No h264 codec support error");return t})}handleRTCError(e){try{this.externalErrorCallback(e||new Error("RTC connection error"))}catch(t){this.handleSystemError(t)}}handleNetworkError(){try{this.externalErrorCallback(new Error("Network error"))}catch(e){this.handleSystemError(e)}}send(e){this.ws&&this.ws.send(JSON.stringify(e))}parseMessage(e){try{return JSON.parse(e)}catch(t){throw new Error("Can not parse socket message")}}closeConnections(){let e=this.ws;e&&(this.ws=null,e.close(1e3)),this.removePeerConnection()}removePeerConnection(){let e=this.peerConnection;e&&(this.peerConnection=null,e.close(),e.ontrack=null,e.onicecandidate=null,e.oniceconnectionstatechange=null,e=null)}scheduleRetry(){this.retryTimeout=setTimeout(this.connectWS.bind(this),U$)}normalizeOptions(e={}){let t={stunServerList:NS,maxRetryNumber:q$,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var ka=class{constructor(e){this.videoState=new C("stopped");this.maxSeekBackTime$=new W$(0);this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.pause(),this.video.srcObject=null,this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),x(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let s=this.params.desiredState.videoTrack.getTransition();if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s){this.prepare();return}switch(e){case"ready":t==="paused"?(this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(r==null?void 0:r.to)==="playing"&&x(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&x(this.params.desiredState.playbackState,"paused");return;default:return FS(e)}};this.subscription=new G$,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=be(e.container,e.tuning),this.liveStreamClient=new mn(this.params.source.url,{maxRetryNumber:this.params.tuning.webrtc.connectionRetryMaxNumber,errorChanel:this.params.output.error$}),this.liveStreamClient.onStart(this.onLiveStreamStart.bind(this)),this.liveStreamClient.onStop(this.onLiveStreamStop.bind(this)),this.liveStreamClient.onError(this.onLiveStreamError.bind(this)),this.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),ge(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,r=n=>{e.error$.next({id:"WebRTCLiveProvider",category:xl.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};US(this.videoState.stateChangeStarted$.pipe(qS(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe(qS(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})});let i=ve(this.video),s=(n,o)=>this.subscription.add(n.subscribe(o,r));s(i.timeUpdate$,e.liveTime$),s(i.ended$,e.endedEvent$),s(i.looped$,e.loopedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(Fe(this.video),this.params.output.elementVisible$),this.subscription.add(i.durationChange$.subscribe(n=>{e.duration$.next(n===1/0?0:n)})).add(i.canplay$.subscribe(()=>{var n;((n=this.videoState.getTransition())==null?void 0:n.to)==="ready"&&this.videoState.setState("ready")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused")},r)).add(i.playing$.subscribe(()=>{this.videoState.setState("playing")},r)).add(i.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(Se(this.video,t.volume,i.volumeState$,r)).add(i.volumeState$.subscribe(e.volume$,r)).add(this.videoState.stateChangeEnded$.subscribe(n=>{switch(n.to){case"stopped":e.position$.next(0),e.duration$.next(0),t.playbackState.setState("stopped");break;case"ready":break;case"paused":t.playbackState.setState("paused");break;case"playing":t.playbackState.setState("playing");break;default:return FS(n.to)}},r)).add(US(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,j$(["init"])).pipe(H$(0)).subscribe(this.syncPlayback.bind(this),r)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),r)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),r))}onLiveStreamStart(e){this.params.output.element$.next(this.video),this.params.output.duration$.next(0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(re(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.currentVideoTrack$.next({id:"webrtc",quality:Y$.INVARIANT}),this.video.srcObject=e,x(this.params.desiredState.playbackState,"playing")}onLiveStreamStop(){this.videoState.startTransitionTo("stopped"),this.syncPlayback(),this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.params.output.endedEvent$.next()}onLiveStreamError(e){this.onLiveStreamStop(),this.params.output.error$.next({id:"WebRTC stream runtime error",category:xl.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){ye(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:xl.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var Ra=class{constructor(e){this.iterator=e[Symbol.iterator](),this.next()}next(){this.current=this.iterator.next()}getValue(){if(this.current.done)throw new Error("Iterable is completed");return this.current.value}isCompleted(){return!!this.current.done}};import{assertNever as La,assertNonNullable as Ot,ErrorCategory as bn,filter as QS,isNonNullable as zS,isNullable as tL,map as rL,merge as iL,once as aL,Subject as Ee,Subscription as KS,ValueSubject as O,flattenObject as JS}from"@vkontakte/videoplayer-shared";import{Observable as Q$,map as HS,Subscription as z$,Subject as K$}from"@vkontakte/videoplayer-shared";var jS=a=>new Q$(e=>{let t=new z$,r=a.desiredPlaybackState$.stateChangeStarted$.pipe(HS(({from:l,to:c})=>`${l}-${c}`)),i=a.desiredPlaybackState$.stateChangeEnded$,s=a.providerChanged$.pipe(HS(({type:l})=>l!==void 0)),n=new K$,o=0,u="unknown";return t.add(r.subscribe(l=>{o&&window.clearTimeout(o),u=l,o=window.setTimeout(()=>n.next(l),a.maxTransitionInterval)})),t.add(i.subscribe(()=>{window.clearTimeout(o),u="unknown",o=0})),t.add(s.subscribe(l=>{o&&(window.clearTimeout(o),o=0,l&&(o=window.setTimeout(()=>n.next(u),a.maxTransitionInterval)))})),t.add(n.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});import{ErrorCategory as J$,Subscription as X$,combine as Z$,filter as WS,once as YS}from"@vkontakte/videoplayer-shared";function GS(){return new(window.AudioContext||window.webkitAudioContext)}import{clientChecker as eL}from"@vkontakte/videoplayer-shared";var $a=class $a{constructor(e,t,r,i){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=r;this.volumeMultiplier=i;this.destroyController=new ke;this.subscriptions=new X$;this.audioContext=null;this.gainNode=null;this.mediaElementSource=null;this.subscriptions.add(this.provider$.pipe(WS(s=>!!s.type),YS()).subscribe(({type:s})=>this.subscribe(s)))}subscribe(e){eL.isSafari&&e!=="MPEG"||this.subscriptions.add(Z$({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe(WS(({playbackState:t,video:r,volume:{muted:i,volume:s}})=>t==="playing"&&!!r&&!i&&!!s),YS()).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}initAudioContextOnce(e){return w(this,null,function*(){let{volumeMultiplier:t}=this,r=GS();this.audioContext=r;let i=r.createGain();if(this.gainNode=i,i.gain.value=t,i.connect(r.destination),r.state==="suspended"&&(yield r.resume(),this.destroyController.signal.aborted))return!1;let s=r.createMediaElementSource(e);return this.mediaElementSource=s,s.connect(i),!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){var t;this.volumeMultiplierError$.next({id:$a.errorId,category:J$.VIDEO_PIPELINE,message:(t=e==null?void 0:e.message)!=null?t:`${$a.errorId} exception`,thrown:e})}};$a.errorId="VolumeMultiplierManager";var Kr=$a;var sL={chunkDuration:5e3,maxParallelRequests:5},Ma=class{constructor(e){this.current$=new O({type:void 0});this.providerError$=new Ee;this.noAvailableProvidersError$=new Ee;this.volumeMultiplierError$=new Ee;this.providerOutput={position$:new O(0),duration$:new O(1/0),volume$:new O({muted:!1,volume:1}),availableVideoStreams$:new O([]),currentVideoStream$:new O(void 0),availableVideoTracks$:new O([]),currentVideoTrack$:new O(void 0),availableAudioStreams$:new O([]),currentAudioStream$:new O(void 0),availableAudioTracks$:new O([]),currentVideoSegmentLength$:new O(0),currentAudioSegmentLength$:new O(0),isAudioAvailable$:new O(!0),autoVideoTrackLimitingAvailable$:new O(!1),autoVideoTrackLimits$:new O(void 0),currentBuffer$:new O(void 0),isBuffering$:new O(!0),error$:new Ee,warning$:new Ee,willSeekEvent$:new Ee,soundProhibitedEvent$:new Ee,seekedEvent$:new Ee,loopedEvent$:new Ee,endedEvent$:new Ee,firstBytesEvent$:new Ee,loadedMetadataEvent$:new Ee,firstFrameEvent$:new Ee,canplay$:new Ee,isLive$:new O(void 0),isLowLatency$:new O(!1),canChangePlaybackSpeed$:new O(!0),liveTime$:new O(void 0),liveBufferTime$:new O(void 0),availableTextTracks$:new O([]),currentTextTrack$:new O(void 0),hostname$:new O(void 0),httpConnectionType$:new O(void 0),httpConnectionReused$:new O(void 0),inPiP$:new O(!1),inFullscreen$:new O(!1),element$:new O(void 0),elementVisible$:new O(!0),availableSources$:new O(void 0),is3DVideo$:new O(!1),playbackState$:new O("")};this.subscription=new KS;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=dg([...hg(this.params.tuning),...pg(this.params.tuning)],this.params.tuning.useHlsJs,this.params.tuning.useManagedMediaSource).filter(l=>zS(e.sources[l])),{forceFormat:r,formatsToAvoid:i}=this.params.tuning,s=[];r?s=[r]:i.length?s=[...t.filter(l=>!i.includes(l)),...t.filter(l=>i.includes(l))]:s=t,this.log({message:`Selected formats: ${s.join(" > ")}`}),this.tracer.log("Selected formats",JS(s)),this.screenFormatsIterator=new Ra(s);let n=[...Fu(!0),...Fu(!1)];this.chromecastFormatsIterator=new Ra(n.filter(l=>zS(e.sources[l]))),this.providerOutput.availableSources$.next(e.sources);let{volumeMultiplier:o=1,tuning:{useVolumeMultiplier:u}}=this.params;u&&o!==1&&Kr.isSupported()&&(this.volumeMultiplierManager=new Kr(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(){var e;this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe(),(e=this.volumeMultiplierManager)==null||e.destroy(),this.volumeMultiplierManager=null,this.tracer.end()}initProvider(){let e=this.chooseDestination(),t=this.chooseFormat(e);if(tL(t)){this.handleNoFormatsError(e);return}let r;try{r=this.createProvider(e,t)}catch(i){this.providerError$.next({id:"ProviderNotConstructed",category:bn.WTF,message:"Failed to create provider",thrown:i})}r?this.current$.next({type:t,provider:r,destination:e}):this.current$.next({type:void 0})}reinitProvider(){this.tracer.log("reinitProvider"),this.destroyProvider(),this.initProvider()}switchToNextProvider(e){this.tracer.log("switchToNextProvider",{destination:e}),this.destroyProvider(),this.failoverIndex=void 0,this.skipFormat(e),this.initProvider()}destroyProvider(){let e=this.current$.getValue().provider;if(!e)return;this.log({message:"destroyProvider"}),this.tracer.log("destroyProvider");let t=this.providerOutput.position$.getValue()*1e3,r=this.params.desiredState.seekState.getState(),i=r.state!=="none";if(this.params.desiredState.seekState.setState({state:"requested",position:i?r.position:t,forcePrecise:i?r.forcePrecise:!1}),e.scene3D){let n=e.scene3D.getCameraRotation();this.params.desiredState.cameraOrientation.setState({x:n.x,y:n.y})}e.destroy();let s=this.providerOutput.isBuffering$;s.getValue()||s.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),this.tracer.log("createProvider",{destination:e,format:t}),e){case"SCREEN":return this.createScreenProvider(t);case"CHROMECAST":return this.createChromecastProvider(t);default:return La(e)}}createScreenProvider(e){let{sources:t,container:r,desiredState:i}=this.params,s=this.providerOutput,n={container:r,source:null,desiredState:i,output:s,dependencies:this.params.dependencies,tuning:this.params.tuning};switch(e){case"DASH_SEP":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_ONDEMAND":case"DASH_STREAMS":{let o=this.applyFailoverHost(t[e]),u=this.applyFailoverHost(t.HLS_ONDEMAND||t.HLS);return Ot(o),new Ta(D(A({},n),{source:o,sourceHls:u}))}case"DASH_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return Ot(o),new Ia(D(A({},n),{source:o}))}case"HLS":case"HLS_ONDEMAND":{let o=this.applyFailoverHost(t[e]);return Ot(o),jr||!this.params.tuning.useHlsJs?new Aa(D(A({},n),{source:o})):new xa(D(A({},n),{source:o}))}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return Ot(o),new Pa(D(A({},n),{source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e}))}case"MPEG":{let o=this.applyFailoverHost(t[e]);return Ot(o),new wa(D(A({},n),{source:o}))}case"DASH_LIVE":{let o=this.applyFailoverHost(t[e]);return Ot(o),new Qb(D(A({},n),{source:o,config:D(A({},sL),{maxPausedTime:this.params.tuning.live.maxPausedTime})}))}case"WEB_RTC_LIVE":{let o=this.applyFailoverHost(t[e]);return Ot(o),new ka({container:r,source:o,desiredState:i,output:s,dependencies:this.params.dependencies,tuning:this.params.tuning})}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return La(e)}}createChromecastProvider(e){let{sources:t,container:r,desiredState:i,meta:s}=this.params,n=this.providerOutput,o=this.params.dependencies.chromecastInitializer.connection$.getValue();return Ot(o),new ki({connection:o,meta:s,container:r,source:t,format:e,desiredState:i,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?"CHROMECAST":"SCREEN"}chooseFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case"CHROMECAST":return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return La(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return La(e)}}handleNoFormatsError(e){switch(e){case"SCREEN":this.noAvailableProvidersError$.next(this.params.tuning.forceFormat),this.current$.next({type:void 0});return;case"CHROMECAST":this.params.dependencies.chromecastInitializer.disconnect();return;default:return La(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;let t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;let r=i=>{let s=new URL(i);return s.host=t,s.toString()};if(e===void 0)return e;if("type"in e){if(e.type==="raw")return e;if(e.type==="url")return D(A({},e),{url:r(e.url)})}return(0,XS.default)(Object.entries(e).map(([i,s])=>[i,r(s)]))}initProviderErrorHandling(){let e=new KS,t=!1,r=0;return e.add(iL(this.providerOutput.error$.pipe(QS(i=>!this.params.tuning.ignoreAudioRendererError||!i.message||!/AUDIO_RENDERER_ERROR/ig.test(i.message))),jS({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(rL(i=>({id:`ProviderHangup:${i}`,category:bn.WTF,message:`A ${i} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;let i=this.params.desiredState.playbackState.transitionEnded$.pipe(QS(({to:s})=>s==="playing"),aL()).subscribe(()=>t=!0);e.add(i)})),e.add(this.providerError$.subscribe(i=>{let s=this.current$.getValue().destination,n={error:i,currentDestination:s};if(s==="CHROMECAST")this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider("SCREEN"),()=>this.params.dependencies.chromecastInitializer.disconnect());else{let o=i.category===bn.NETWORK,u=i.category===bn.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=D(A({},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!=null?s:"SCREEN")}this.tracer.error("providerError",JS(n))})),e}};import{fromEvent as gn,once as nL,combine as oL,Subscription as ZS,ValueSubject as Pl,map as uL,filter as lL,isNonNullable as Sn,now as Le,safeStorage as Al}from"@vkontakte/videoplayer-shared";var cL=5e3,ev="one_video_throughput",tv="one_video_rtt",bt=window.navigator.connection,rv=()=>{let a=bt==null?void 0:bt.downlink;if(Sn(a)&&a!==10)return a*1e3},iv=()=>{let a=bt==null?void 0:bt.rtt;if(Sn(a)&&a!==3e3)return a},av=(a,e,t)=>{let r=t*8,i=r/a;return r/(i+e)},wl=class a{constructor(e){this.subscription=new ZS;this.concurrentDownloads=new Set;var i,s;this.tuningConfig=e;let t=a.load(ev)||(e.useBrowserEstimation?rv():void 0)||cL,r=(s=(i=a.load(tv))!=null?i:e.useBrowserEstimation?iv():void 0)!=null?s:0;if(this.throughput$=new Pl(t),this.rtt$=new Pl(r),this.rttAdjustedThroughput$=new Pl(av(t,r,e.rttPenaltyRequestSize)),this.throughput=or.getSmoothedValue(t,-1,e),this.rtt=or.getSmoothedValue(r,1,e),e.useBrowserEstimation){let n=()=>{let u=rv();u&&this.throughput.next(u);let l=iv();Sn(l)&&this.rtt.next(l)};bt&&"onchange"in bt&&this.subscription.add(gn(bt,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{Al.set(ev,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{Al.set(tv,n.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(oL({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(uL(({throughput:n,rtt:o})=>av(n,o,e.rttPenaltyRequestSize)),lL(n=>{let o=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(n-o)/o>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,r=Le(),i=new ZS;switch(this.subscription.add(i),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:i.add(gn(e,"progress").pipe(nL()).subscribe(s=>{t=s.loaded,r=Le()}));break;case 1:case 0:i.add(gn(e,"loadstart").subscribe(()=>{t=0,r=Le()}));break}i.add(gn(e,"loadend").subscribe(s=>{if(e.status===200){let n=s.loaded,o=Le(),u=n-t,l=o-r;this.addRawSpeed(u,l,1)}this.concurrentDownloads.delete(e),i.unsubscribe()}))}trackStream(e,t=!1){let r=e.getReader();if(!r){e.cancel("Could not get reader");return}let i=0,s=Le(),n=0,o=Le(),u=c=>{this.concurrentDownloads.delete(e),r.releaseLock(),e.cancel(`Throughput Estimator error: ${c}`).catch(()=>{})},l=h=>w(this,[h],function*({done:c,value:d}){if(c)!t&&this.addRawSpeed(i,Le()-s,1),this.concurrentDownloads.delete(e);else if(d){if(t){let p=Le();if(p-o>this.tuningConfig.lowLatency.continuesByteSequenceInterval||p-s>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let b=o-s;b&&this.addRawSpeed(n,b,1,t),n=d.byteLength,s=Le()}else n+=d.byteLength;o=Le()}else i+=d.byteLength,n+=d.byteLength,n>=this.tuningConfig.streamMinSampleSize&&Le()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,Le()-o,this.concurrentDownloads.size),n=0,o=Le());yield r==null?void 0:r.read().then(l,u)}});this.concurrentDownloads.add(e),r==null||r.read().then(l,u)}addRawSpeed(e,t,r=1,i=!1){if(a.sanityCheck(e,t,i)){let s=e*8/t;this.throughput.next(s*r)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,r=!1){let i=e*8/t;return!(!i||!isFinite(i)||i>1e6||i<30||r&&e<1e4||!r&&e<10*1024||!r&&t<=20)}static load(e){var r;let t=Al.get(e);if(Sn(t))return(r=parseInt(t,10))!=null?r:void 0}},sv=wl;import{fillWithDefault as dL,VideoQuality as nv}from"@vkontakte/videoplayer-shared";var ov={configName:["core"],throughputEstimator:{type:"EmaAndMa",emaAlphaSlow:.2,emaAlphaFast:.7,emaAlpha:.45,basisTrendChangeCount:10,changeThreshold:.05,useBrowserEstimation:!0,rttPenaltyRequestSize:1*1024*1024,streamMinSampleSize:10*1024,streamMinSampleTime:300,deviationDepth:20,deviationFactor:.5,lowLatency:{continuesByteSequenceInterval:50,maxLastEvaluationTimeout:300}},autoTrackSelection:{bitrateFactorAtEmptyBuffer:1.8,bitrateAudioFactorAtEmptyBuffer:10,bitrateFactorAtFullBuffer:1.2,bitrateAudioFactorAtFullBuffer:7,minVideoAudioRatio:5,minAvailableThroughputAudioRatio:5,usePixelRatio:!0,pixelRatioMultiplier:1,limitByContainer:!0,containerSizeFactor:1.5,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldownIncreaseQuality:3e3,trackCooldownDecreaseQuality:3e3,backgroundVideoQualityLimit:nv.Q_4320P,activeVideoAreaThreshold:.1},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:nv.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,accumulationBufferStallSize:{shortVideoDuration:2*6e4,shortVideoBufferStallSizeMs:0,longVideoBufferStallSizeMs:0},enableBaseUrlSupport:!0,maxSegmentRetryCount:5},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:250,playbackCatchupSpeedup:.05,isActive:!1,delayEstimator:{emaAlpha:.45,changeThreshold:.05,deviationDepth:20,deviationFactor:.5,extremumInterval:5}}},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1,lowLatencyActiveLiveDelay:3e3,activeLiveDelay:5e3,maxPausedTime:5e3},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,forceFormat:void 0,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:void 0,useWebmBigRequest:!1,webmCodec:"vp9",androidPreferredFormat:"mpeg",preferCMAF:!1,preferWebRTC:!1,preferMultiStream:!1,preferHDR:!1,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useHlsJs:!0,useNativeHLSTextTracks:!1,useManagedMediaSource:!1,useNewPruneBufferStrategy:!1,useNewSwitchTo:!1,useSafariEndlessRequestBugfix:!1,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,manifestRetryInterval:300,manifestRetryMaxInterval:1e4,manifestRetryMaxCount:10,audioVideoSyncRate:20,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50},useVolumeMultiplier:!1,ignoreAudioRendererError:!1,useEnableSubtitlesParam:!1},uv=a=>{var e;return D(A({},dL(a,ov)),{configName:[...(e=a.configName)!=null?e:[],...ov.configName]})};import{assertNonNullable as vn,combine as Vt,ErrorCategory as yn,filter as pe,filterChanged as q,fromEvent as Rl,isNonNullable as SL,isNullable as vL,Logger as yL,map as F,mapTo as pv,merge as _t,now as Tn,once as st,Subject as Y,Subscription as hv,tap as fv,ValueSubject as P,isHigher as TL,isInvariantQuality as mv,flattenObject as Nt,throttle as $l,getTraceSubscriptionMethod as bv,Tracer as IL}from"@vkontakte/videoplayer-shared";import{merge as pL,map as hL,filter as lv,isNonNullable as fL}from"@vkontakte/videoplayer-shared";var kl=({seekState:a,position$:e})=>pL(a.stateChangeEnded$.pipe(hL(({to:t})=>{var r;return t.state==="none"?void 0:((r=t.position)!=null?r:NaN)/1e3}),lv(fL)),e.pipe(lv(()=>a.getState().state==="none")));import{assertNonNullable as mL}from"@vkontakte/videoplayer-shared";var cv=a=>{let e=typeof a.container=="string"?document.getElementById(a.container):a.container;return mL(e,`Wrong container or containerId {${a.container}}`),e};import{filter as bL,once as gL}from"@vkontakte/videoplayer-shared";var dv=(a,e,t,r)=>{a!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&(t==null?void 0:t.getValue().length)===0?t.pipe(bL(i=>i.length>0),gL()).subscribe(i=>{i.find(r)&&e.startTransitionTo(a)}):(a===void 0||t!=null&&t.getValue().find(r))&&e.startTransitionTo(a)};var In=class{constructor(e={configName:[]},t=IL.createRootTracer(!1)){this.subscription=new hv;this.logger=new yL;this.abrLogger=this.logger.createComponentLog("ABR");this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new P(!1);this.hasLiveOffsetByPausedTimer=0;this.desiredState={playbackState:new C("stopped"),seekState:new C({state:"none"}),volume:new C({volume:1,muted:!1}),videoTrack:new C(void 0),videoStream:new C(void 0),audioStream:new C(void 0),autoVideoTrackSwitching:new C(!0),autoVideoTrackLimits:new C({}),isLooped:new C(!1),playbackRate:new C(1),externalTextTracks:new C([]),internalTextTracks:new C([]),currentTextTrack:new C(void 0),textTrackCuesSettings:new C({}),cameraOrientation:new C({x:0,y:0})};this.info={playbackState$:new P("stopped"),position$:new P(0),duration$:new P(1/0),muted$:new P(!1),volume$:new P(1),availableVideoStreams$:new P([]),currentVideoStream$:new P(void 0),availableQualities$:new P([]),availableQualitiesFps$:new P({}),currentQuality$:new P(void 0),isAutoQualityEnabled$:new P(!0),autoQualityLimitingAvailable$:new P(!1),autoQualityLimits$:new P({}),availableAudioStreams$:new P([]),currentAudioStream$:new P(void 0),availableAudioTracks$:new P([]),isAudioAvailable$:new P(!0),currentPlaybackRate$:new P(1),currentBuffer$:new P({start:0,end:0}),isBuffering$:new P(!0),isStalled$:new P(!1),isEnded$:new P(!1),isLooped$:new P(!1),isLive$:new P(void 0),canChangePlaybackSpeed$:new P(void 0),atLiveEdge$:new P(void 0),atLiveDurationEdge$:new P(void 0),liveTime$:new P(void 0),liveBufferTime$:new P(void 0),currentFormat$:new P(void 0),availableTextTracks$:new P([]),currentTextTrack$:new P(void 0),throughputEstimation$:new P(void 0),rttEstimation$:new P(void 0),videoBitrate$:new P(void 0),hostname$:new P(void 0),httpConnectionType$:new P(void 0),httpConnectionReused$:new P(void 0),surface$:new P("none"),chromecastState$:new P("NOT_AVAILABLE"),chromecastDeviceName$:new P(void 0),intrinsicVideoSize$:new P(void 0),availableSources$:new P(void 0),is3DVideo$:new P(!1),currentVideoSegmentLength$:new P(0),currentAudioSegmentLength$:new P(0)};this.events={inited$:new Y,ready$:new Y,started$:new Y,playing$:new Y,paused$:new Y,stopped$:new Y,willStart$:new Y,willResume$:new Y,willPause$:new Y,willStop$:new Y,willDestruct$:new Y,watchCoverageRecord$:new Y,watchCoverageLive$:new Y,managedError$:new Y,fatalError$:new Y,ended$:new Y,looped$:new Y,seeked$:new Y,willSeek$:new Y,autoplaySoundProhibited$:new Y,firstBytes$:new Y,loadedMetadata$:new Y,firstFrame$:new Y,canplay$:new Y,log$:new Y};this.experimental={element$:new P(void 0),tuningConfigName$:new P([]),enableDebugTelemetry$:new P(!1),dumpTelemetry:wb};if(this.initLogs(),this.tuning=uv(e),this.tracer=t,this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new za({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new sv(this.tuning.throughputEstimator),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(r,i,s)=>{let n=Reflect.get(r,i,s);return typeof n!="function"?n:(...o)=>{try{return n.apply(r,o)}catch(u){let l=o.map(h=>JSON.stringify(h,(p,f)=>{let b=typeof f;return["number","string","boolean"].includes(b)?f:f===null?null:`<${b}>`})),c=`Player.${String(i)}`,d=`Exception calling ${c} (${l.join(", ")})`;throw this.events.fatalError$.next({id:c,category:yn.WTF,message:d,thrown:u}),u}}}})}initVideo(e){var s,n,o;this.config=e;let i=e,{container:t}=i,r=pc(i,["container"]);return this.tracer.log("initVideo",Nt(r)),this.domContainer=cv(e),this.chromecastInitializer.contentId=(s=e.meta)==null?void 0:s.videoId,this.providerContainer=new Ma({sources:e.sources,meta:(n=e.meta)!=null?n:{},failoverHosts:(o=e.failoverHosts)!=null?o:[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,tracer:this.tracer,logger:this.logger,abrLogger:this.abrLogger},tuning:this.tuning,volumeMultiplier:e.volumeMultiplier}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.initTracerSubscription(),this.providerContainer.init(),this.setMuted(this.tuning.isAudioDisabled),this.initDebugTelemetry(),this.initWakeLock(),this}destroy(){var e;this.tracer.log("destroy"),window.clearTimeout(this.hasLiveOffsetByPausedTimer),this.events.willDestruct$.next(),this.stop(),(e=this.providerContainer)==null||e.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe(),this.tracer.end()}prepare(){let e=this.desiredState.playbackState;return this.tracer.log("prepare",{currentPlayBackState:e.getState()}),e.getState()==="stopped"&&e.startTransitionTo("ready"),this}play(){let e=()=>{let t=this.desiredState.playbackState;this.tracer.log("play",{currentPlayBackState:t.getState()}),t.getState()!=="playing"&&t.startTransitionTo("playing")};return document.hidden&&this.tuning.autoplayOnlyInActiveTab&&!Vi()?(this.tracer.log("request play from hidden tab"),Rl(document,"visibilitychange").pipe(st()).subscribe(e)):e(),this}pause(){let e=this.desiredState.playbackState;return this.tracer.log("pause",{currentPlayBackState:e.getState()}),e.getState()!=="paused"&&e.startTransitionTo("paused"),this}stop(){let e=this.desiredState.playbackState;return this.tracer.log("stop",{currentPlayBackState:e.getState()}),e.getState()!=="stopped"&&e.startTransitionTo("stopped"),this}seekTime(e,t=!0){let r=this.info.duration$.getValue(),i=this.info.isLive$.getValue(),s=e;return e>=r&&!i&&(s=r-.1),this.tracer.log("seekTime",{duration:r,isLive:i,time:e,calculatedTime:s,forcePrecise:t}),this.events.willSeek$.next({from:this.getExactTime(),to:s}),this.desiredState.seekState.setState({state:"requested",position:s*1e3,forcePrecise:t}),this}seekPercent(e){let t=this.info.duration$.getValue();return this.tracer.log("seekPercent",{percent:e,duration:t}),isFinite(t)&&this.seekTime(Math.abs(t)*e,!1),this}setVolume(e){let t=this.tuning.isAudioDisabled||this.desiredState.volume.getState().muted;return this.tracer.log("setVolume",{volume:e,isAudioDisabled:this.tuning.isAudioDisabled,isDesiredStateMuted:this.desiredState.volume.getState().muted,chromecastState:this.chromecastInitializer.castState$.getValue(),muted:t}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setVolume(e):this.desiredState.volume.startTransitionTo({volume:e,muted:t}),this}setMuted(e){let t=this.tuning.isAudioDisabled||e;return this.tracer.log("setMuted",{isMuted:e,isAudioDisabled:this.tuning.isAudioDisabled,desiredStateVolume:this.desiredState.volume.getState().volume,chromecastState:this.chromecastInitializer.castState$.getValue(),muted:t}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setMuted(t):this.desiredState.volume.startTransitionTo({volume:this.desiredState.volume.getState().volume,muted:t}),this}setVideoStream(e){return this.desiredState.videoStream.startTransitionTo(e),this}setAudioStream(e){return this.desiredState.audioStream.startTransitionTo(e),this}setQuality(e){vn(this.providerContainer);let t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();return this.tracer.log("setQuality",{isDelayed:t.length===0,quality:e}),this.desiredState.videoTrack.getState()===void 0&&this.desiredState.videoTrack.getPrevState()===void 0&&t.length===0?this.providerContainer.providerOutput.availableVideoTracks$.pipe(pe(r=>r.length>0),st()).subscribe(r=>{this.setVideoTrackIdByQuality(r,e)}):t.length>0&&this.setVideoTrackIdByQuality(t,e),this}setAutoQuality(e){return this.tracer.log("setAutoQuality",{enable:e}),this.desiredState.autoVideoTrackSwitching.startTransitionTo(e),this}setAutoQualityLimits(e){return this.tracer.log("setAutoQualityLimits",Nt(e)),this.desiredState.autoVideoTrackLimits.startTransitionTo(e),this}setPlaybackRate(e){var r;vn(this.providerContainer);let t=(r=this.providerContainer)==null?void 0:r.providerOutput.element$.getValue();return this.tracer.log("setPlaybackRate",{playbackRate:e,isVideoElementAvailable:!!t}),t&&(this.desiredState.playbackRate.setState(e),t.playbackRate=e),this}setExternalTextTracks(e){return e.length&&this.tracer.log("setExternalTextTracks",Nt(e)),this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>A({type:"external"},t))),this}selectTextTrack(e){var t;return dv(e,this.desiredState.currentTextTrack,(t=this.providerContainer)==null?void 0:t.providerOutput.availableTextTracks$,r=>r.id===e),this.tracer.log("selectTextTrack",{textTrackId:e}),this}setTextTrackCueSettings(e){return this.tracer.log("setTextTrackCueSettings",A({},e)),this.desiredState.textTrackCuesSettings.startTransitionTo(e),this}setLooped(e){return this.tracer.log("setLooped",{isLooped:e}),this.desiredState.isLooped.startTransitionTo(e),this}toggleChromecast(){this.tracer.log("toggleChromecast"),this.chromecastInitializer.toggleConnection()}startCameraManualRotation(e,t){let r=this.getScene3D();return this.tracer.log("startCameraManualRotation",{isScene3DAvailable:!!r,mx:e,my:t}),r&&r.startCameraManualRotation(e,t),this}stopCameraManualRotation(e=!1){let t=this.getScene3D();return this.tracer.log("stopCameraManualRotation",{isScene3DAvailable:!!t,immediate:e}),t&&t.stopCameraManualRotation(e),this}moveCameraFocusPX(e,t){let r=this.getScene3D();if(this.tracer.log("moveCameraFocusPX",{isScene3DAvailable:!!r,dxpx:e,dypx:t}),r){let i=r.getCameraRotation(),s=r.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:i.x+s.x,y:i.y+s.y})}return this}holdCamera(){let e=this.getScene3D();return e&&e.holdCamera(),this}releaseCamera(){let e=this.getScene3D();return e&&e.releaseCamera(),this}getExactTime(){if(!this.providerContainer)return 0;let e=this.providerContainer.providerOutput.element$.getValue();if(vL(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),r=t.state==="none"?void 0:t.position;return SL(r)?r/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}getScene3D(){var t,r;let e=(t=this.providerContainer)==null?void 0:t.current$.getValue();if((r=e==null?void 0:e.provider)!=null&&r.scene3D)return e.provider.scene3D}setIntrinsicVideoSize(...e){let t={width:e.reduce((r,{width:i})=>r||i||0,0),height:e.reduce((r,{height:i})=>r||i||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add(_t(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(F(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(F(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(F(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(F(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(F(e=>e.to)).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(pe(({from:e})=>e==="stopped"),st()).subscribe(()=>{this.initedAt=Tn(),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",Nt(n)),n.state==="requested"?this.desiredState.seekState.setState(D(A({},n),{state:"applying"})):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:yn.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.soundProhibitedEvent$.pipe(st()).subscribe(this.events.autoplaySoundProhibited$)).add(e.providerOutput.seekedEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();this.tracer.log("seekedEvent",Nt(n)),n.state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe(F(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(F(n=>n.destination),q()).subscribe(()=>this.isPlaybackStarted=!1)).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add(e.providerOutput.availableVideoTracks$.pipe(F(n=>n.map(({quality:o})=>o).sort((o,u)=>mv(o)?1:mv(u)?-1:TL(u,o)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(n=>{let o={};for(let u of n)u.fps&&(o[u.quality]=u.fps);this.info.availableQualitiesFps$.next(o)})).add(e.providerOutput.availableAudioStreams$.subscribe(this.info.availableAudioStreams$)).add(e.providerOutput.currentVideoStream$.subscribe(this.info.currentVideoStream$)).add(e.providerOutput.currentAudioStream$.subscribe(this.info.currentAudioStream$)).add(e.providerOutput.availableAudioTracks$.subscribe(this.info.availableAudioTracks$)).add(e.providerOutput.isAudioAvailable$.pipe(q()).subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{this.info.currentQuality$.next(n==null?void 0:n.quality),this.info.videoBitrate$.next(n==null?void 0:n.bitrate)})).add(e.providerOutput.currentVideoSegmentLength$.pipe(q((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.pipe(q((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe(q()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(q()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(q()).subscribe(this.info.httpConnectionReused$)).add(e.providerOutput.currentTextTrack$.subscribe(this.info.currentTextTrack$)).add(e.providerOutput.availableTextTracks$.subscribe(this.info.availableTextTracks$)).add(e.providerOutput.autoVideoTrackLimitingAvailable$.subscribe(this.info.autoQualityLimitingAvailable$)).add(e.providerOutput.autoVideoTrackLimits$.subscribe(n=>{this.desiredState.autoVideoTrackLimits.setState(n!=null?n:{})})).add(e.providerOutput.currentBuffer$.pipe(F(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(Vt({hasLiveOffsetByPaused:_t(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(F(n=>n.to),q(),F(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(Vt({atLiveEdge:Vt({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:kl({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(F(({isLive:n,position:o,isLowLatency:u})=>{let l=this.getActiveLiveDelay(u);return n&&Math.abs(o)<l/1e3}),q(),fv(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(F(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add(Vt({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(F(({isLive:n,position:o,duration:u})=>n&&(Math.abs(u)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),q(),fv(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(F(n=>n.muted),q()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(F(n=>n.volume),q()).subscribe(this.info.volume$)).add(kl({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(_t(e.providerOutput.endedEvent$.pipe(pv(!0)),e.providerOutput.seekedEvent$.pipe(pv(!1))).pipe(q()).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(F(n=>({id:n?`No${n}`:"NoProviders",category:yn.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(st(),F(n=>n!=null?n:Tn()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe(st(),F(()=>Tn()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(st(),F(()=>Tn()-this.initedAt)).subscribe(this.events.canplay$)).add(this.throughputEstimator.throughput$.subscribe(this.info.throughputEstimation$)).add(this.throughputEstimator.rtt$.subscribe(this.info.rttEstimation$)).add(e.providerOutput.availableSources$.subscribe(this.info.availableSources$));let t=new P(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let r=new P(!0);this.subscription.add(e.current$.subscribe(()=>r.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(pe(({to:n})=>n==="playing"),st()).subscribe(()=>r.next(!1)));let i=0,s=_t(e.providerOutput.isBuffering$,t,r).pipe(F(()=>{let n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||r.getValue();return n&&!o}),q());this.subscription.add(s.subscribe(n=>{n?i=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(i),this.info.isStalled$.next(!1))})),this.subscription.add(_t(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{let n=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:n==null?void 0:n.videoWidth,height:n==null?void 0:n.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{var u,l;let o=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:(u=n==null?void 0:n.size)==null?void 0:u.width,height:(l=n==null?void 0:n.size)==null?void 0:l.height},{width:o==null?void 0:o.videoWidth,height:o==null?void 0:o.videoHeight})})).add(e.providerOutput.is3DVideo$.subscribe(this.info.is3DVideo$)),this.subscription.add(_t(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(F(e=>e==null?void 0:e.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){let t=new hv;this.subscription.add(t),this.subscription.add(e.current$.pipe(q((r,i)=>r.provider===i.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(pe(r=>r.length>0),st()).subscribe(r=>{this.setStartingVideoTrack(r)}))}))}setStartingVideoTrack(e){var i;let t,r=(i=this.desiredState.videoTrack.getState())==null?void 0:i.quality;r&&(t=e.find(({quality:s})=>s===r),t||this.setAutoQuality(!0)),t||(t=$t(e,{container:this.domContainer.getBoundingClientRect(),throughput:this.throughputEstimator.throughput$.getValue(),tuning:this.tuning.autoTrackSelection,limits:this.desiredState.autoVideoTrackLimits.getState(),playbackRate:this.info.currentPlaybackRate$.getValue(),forwardBufferHealth:0,abrLogger:this.abrLogger})),this.desiredState.videoTrack.startTransitionTo(t),this.info.currentQuality$.next(t.quality),this.info.videoBitrate$.next(t.bitrate)}initLogs(){this.subscription.add(_t(this.desiredState.videoTrack.stateChangeStarted$.pipe(F(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(F(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(F(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(F(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(F(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(F(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(F(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(F(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(F(e=>({component:"desiredState",message:`[${e.entity} change] ${e.type}: ${JSON.stringify(e.transition)}`}))).subscribe(this.logger.log)),this.subscription.add(this.logger.log$.subscribe(this.events.log$))}initDebugTelemetry(){var t;let e=(t=this.providerContainer)==null?void 0:t.providerOutput;vn(this.providerContainer),vn(e),Ab(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(r=>Pb(r)),this.providerContainer.current$.subscribe(({type:r})=>Li("provider",r)),e.duration$.subscribe(r=>Li("duration",r)),e.availableVideoTracks$.pipe(pe(r=>!!r.length),st()).subscribe(r=>Li("tracks",r)),this.events.fatalError$.subscribe(new de("fatalError")),this.events.managedError$.subscribe(new de("managedError")),e.position$.subscribe(new de("position")),e.currentVideoTrack$.pipe(F(r=>r==null?void 0:r.quality)).subscribe(new de("quality")),this.info.currentBuffer$.subscribe(new de("buffer")),e.isBuffering$.subscribe(new de("isBuffering"))].forEach(r=>this.subscription.add(r)),Li("codecs",cg())}initTracerSubscription(){let e=bv(this.tracer.log.bind(this.tracer)),t=bv(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(q()).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(Vt({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe(pe(({currentQuality:r,videoBitrate:i})=>!!r&&!!i),q((r,i)=>r.currentQuality===i.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe(pe(r=>r>0),q()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe(pe(r=>r>0),q()).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(Vt({currentBuffer:this.info.currentBuffer$.pipe(pe(r=>r.end>0),q((r,i)=>r.end===i.end&&r.start===i.start)),position:this.info.position$.pipe(q())}).pipe($l(1e3)).subscribe(e("currentBufferAndPosition"))).add(this.info.duration$.pipe(q()).subscribe(e("duration"))).add(this.info.isBuffering$.subscribe(e("isBuffering"))).add(this.info.isLive$.pipe(q()).subscribe(e("isLive"))).add(this.info.canChangePlaybackSpeed$.pipe(q()).subscribe(e("canChangePlaybackSpeed"))).add(Vt({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe(pe(({liveTime:r,liveBufferTime:i})=>!!r&&!!i),$l(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe(q(),pe(r=>r===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe(q(),pe(r=>r===!0)).subscribe(e("atLiveDurationEdge"))).add(this.info.muted$.pipe(q()).subscribe(e("muted"))).add(this.info.volume$.pipe(q()).subscribe(e("volume"))).add(this.info.isEnded$.pipe(q(),pe(r=>r===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add(Vt({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe(pe(({throughputEstimation:r,rtt:i})=>!!r&&!!i),$l(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe(q(),pe(r=>r===!0)).subscribe(e("is3DVideo"))).add(this.info.surface$.subscribe(e("surface"))).add(this.events.ended$.subscribe(e("ended"))).add(this.events.looped$.subscribe(e("looped"))).add(this.events.managedError$.subscribe(t("managedError"))).add(this.events.fatalError$.subscribe(t("fatalError"))).add(this.events.firstBytes$.subscribe(e("firstBytes"))).add(this.events.firstFrame$.subscribe(e("firstFrame"))).add(this.events.canplay$.subscribe(e("canplay")))}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e,t=()=>{e==null||e.release(),e=void 0},r=()=>w(this,null,function*(){t(),e=yield window.navigator.wakeLock.request("screen").catch(i=>{i instanceof DOMException&&i.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:yn.DOM,message:String(i)})})});this.subscription.add(_t(Rl(document,"visibilitychange"),Rl(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{let i=document.visibilityState==="visible",s=this.desiredState.playbackState.getState()==="playing",n=!!e&&!(e!=null&&e.released);i&&s?n||r():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){let r=e.find(i=>i.quality===t);this.tracer.log("setVideoTrackIdByQuality",Nt({quality:t,availableTracks:Nt(e),track:Nt(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 eY,Observable as tY,Subject as rY,ValueSubject as iY,VideoQuality as aY}from"@vkontakte/videoplayer-shared";var sY=`@vkontakte/videoplayer-core@${hc}`;export{Ya as ChromecastState,Ln as HttpConnectionType,tY as Observable,fe as PlaybackState,In as Player,sY as SDK_VERSION,rY as Subject,eY as Subscription,Mn as Surface,hc as VERSION,iY as ValueSubject,xt as VideoFormat,aY as VideoQuality};