@vkontakte/videoplayer-core 2.0.145 → 2.0.146-dev.0b43ee9b.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/esnext.cjs.js CHANGED
@@ -1,19 +1,19 @@
1
1
  /**
2
- * @vkontakte/videoplayer-core v2.0.145
3
- * Thu, 06 Nov 2025 09:26:06 GMT
4
- * https://st.mycdn.me/static/vkontakte-videoplayer/2-0-145/doc/
2
+ * @vkontakte/videoplayer-core v2.0.146-dev.0b43ee9b.0
3
+ * Tue, 11 Nov 2025 17:54:43 GMT
4
+ * https://st.mycdn.me/static/vkontakte-videoplayer/2-0-146/doc/
5
5
  */
6
- "use strict";var Rv=Object.create;var hs=Object.defineProperty;var $v=Object.getOwnPropertyDescriptor;var Lv=Object.getOwnPropertyNames;var Mv=Object.getPrototypeOf,Dv=Object.prototype.hasOwnProperty;var g=(a,e)=>()=>(e||a((e={exports:{}}).exports,e),e.exports),Cv=(a,e)=>{for(var t in e)hs(a,t,{get:e[t],enumerable:!0})},ic=(a,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Lv(e))!Dv.call(a,r)&&r!==t&&hs(a,r,{get:()=>e[r],enumerable:!(i=$v(e,r))||i.enumerable});return a};var Q=(a,e,t)=>(t=a!=null?Rv(Mv(a)):{},ic(e||!a||!a.__esModule?hs(t,"default",{value:a,enumerable:!0}):t,a)),Bv=a=>ic(hs({},"__esModule",{value:!0}),a);var Se=g((ao,rc)=>{"use strict";var $r=function(a){return a&&a.Math===Math&&a};rc.exports=$r(typeof globalThis=="object"&&globalThis)||$r(typeof window=="object"&&window)||$r(typeof self=="object"&&self)||$r(typeof global=="object"&&global)||$r(typeof ao=="object"&&ao)||function(){return this}()||Function("return this")()});var we=g((w$,ac)=>{"use strict";ac.exports=function(a){try{return!!a()}catch{return!0}}});var Lr=g((k$,sc)=>{"use strict";var Vv=we();sc.exports=!Vv(function(){var a=function(){}.bind();return typeof a!="function"||a.hasOwnProperty("prototype")})});var so=g((A$,lc)=>{"use strict";var _v=Lr(),uc=Function.prototype,nc=uc.apply,oc=uc.call;lc.exports=typeof Reflect=="object"&&Reflect.apply||(_v?oc.bind(nc):function(){return oc.apply(nc,arguments)})});var ke=g((P$,pc)=>{"use strict";var cc=Lr(),dc=Function.prototype,no=dc.call,Ov=cc&&dc.bind.bind(no,no);pc.exports=cc?Ov:function(a){return function(){return no.apply(a,arguments)}}});var hi=g((R$,fc)=>{"use strict";var hc=ke(),Fv=hc({}.toString),Nv=hc("".slice);fc.exports=function(a){return Nv(Fv(a),8,-1)}});var oo=g(($$,mc)=>{"use strict";var qv=hi(),Uv=ke();mc.exports=function(a){if(qv(a)==="Function")return Uv(a)}});var ve=g((L$,bc)=>{"use strict";var uo=typeof document=="object"&&document.all;bc.exports=typeof uo>"u"&&uo!==void 0?function(a){return typeof a=="function"||a===uo}:function(a){return typeof a=="function"}});var Ke=g((M$,gc)=>{"use strict";var Hv=we();gc.exports=!Hv(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var Xe=g((D$,Sc)=>{"use strict";var jv=Lr(),bs=Function.prototype.call;Sc.exports=jv?bs.bind(bs):function(){return bs.apply(bs,arguments)}});var lo=g(Tc=>{"use strict";var vc={}.propertyIsEnumerable,yc=Object.getOwnPropertyDescriptor,Wv=yc&&!vc.call({1:2},1);Tc.f=Wv?function(e){var t=yc(this,e);return!!t&&t.enumerable}:vc});var Mr=g((B$,Ic)=>{"use strict";Ic.exports=function(a,e){return{enumerable:!(a&1),configurable:!(a&2),writable:!(a&4),value:e}}});var xc=g((V$,Ec)=>{"use strict";var Qv=ke(),Gv=we(),zv=hi(),co=Object,Yv=Qv("".split);Ec.exports=Gv(function(){return!co("z").propertyIsEnumerable(0)})?function(a){return zv(a)==="String"?Yv(a,""):co(a)}:co});var Dr=g((_$,wc)=>{"use strict";wc.exports=function(a){return a==null}});var Xt=g((O$,kc)=>{"use strict";var Kv=Dr(),Xv=TypeError;kc.exports=function(a){if(Kv(a))throw new Xv("Can't call method on "+a);return a}});var fi=g((F$,Ac)=>{"use strict";var Jv=xc(),Zv=Xt();Ac.exports=function(a){return Jv(Zv(a))}});var qe=g((N$,Pc)=>{"use strict";var ey=ve();Pc.exports=function(a){return typeof a=="object"?a!==null:ey(a)}});var mi=g((q$,Rc)=>{"use strict";Rc.exports={}});var Vt=g((U$,Lc)=>{"use strict";var po=mi(),ho=Se(),ty=ve(),$c=function(a){return ty(a)?a:void 0};Lc.exports=function(a,e){return arguments.length<2?$c(po[a])||$c(ho[a]):po[a]&&po[a][e]||ho[a]&&ho[a][e]}});var Cr=g((H$,Mc)=>{"use strict";var iy=ke();Mc.exports=iy({}.isPrototypeOf)});var bi=g((j$,Bc)=>{"use strict";var ry=Se(),Dc=ry.navigator,Cc=Dc&&Dc.userAgent;Bc.exports=Cc?String(Cc):""});var mo=g((W$,qc)=>{"use strict";var Nc=Se(),fo=bi(),Vc=Nc.process,_c=Nc.Deno,Oc=Vc&&Vc.versions||_c&&_c.version,Fc=Oc&&Oc.v8,ht,gs;Fc&&(ht=Fc.split("."),gs=ht[0]>0&&ht[0]<4?1:+(ht[0]+ht[1]));!gs&&fo&&(ht=fo.match(/Edge\/(\d+)/),(!ht||ht[1]>=74)&&(ht=fo.match(/Chrome\/(\d+)/),ht&&(gs=+ht[1])));qc.exports=gs});var bo=g((Q$,Hc)=>{"use strict";var Uc=mo(),ay=we(),sy=Se(),ny=sy.String;Hc.exports=!!Object.getOwnPropertySymbols&&!ay(function(){var a=Symbol("symbol detection");return!ny(a)||!(Object(a)instanceof Symbol)||!Symbol.sham&&Uc&&Uc<41})});var go=g((G$,jc)=>{"use strict";var oy=bo();jc.exports=oy&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var So=g((z$,Wc)=>{"use strict";var uy=Vt(),ly=ve(),cy=Cr(),dy=go(),py=Object;Wc.exports=dy?function(a){return typeof a=="symbol"}:function(a){var e=uy("Symbol");return ly(e)&&cy(e.prototype,py(a))}});var Br=g((Y$,Qc)=>{"use strict";var hy=String;Qc.exports=function(a){try{return hy(a)}catch{return"Object"}}});var wt=g((K$,Gc)=>{"use strict";var fy=ve(),my=Br(),by=TypeError;Gc.exports=function(a){if(fy(a))return a;throw new by(my(a)+" is not a function")}});var Vr=g((X$,zc)=>{"use strict";var gy=wt(),Sy=Dr();zc.exports=function(a,e){var t=a[e];return Sy(t)?void 0:gy(t)}});var Kc=g((J$,Yc)=>{"use strict";var vo=Xe(),yo=ve(),To=qe(),vy=TypeError;Yc.exports=function(a,e){var t,i;if(e==="string"&&yo(t=a.toString)&&!To(i=vo(t,a))||yo(t=a.valueOf)&&!To(i=vo(t,a))||e!=="string"&&yo(t=a.toString)&&!To(i=vo(t,a)))return i;throw new vy("Can't convert object to primitive value")}});var ft=g((Z$,Xc)=>{"use strict";Xc.exports=!0});var ed=g((eL,Zc)=>{"use strict";var Jc=Se(),yy=Object.defineProperty;Zc.exports=function(a,e){try{yy(Jc,a,{value:e,configurable:!0,writable:!0})}catch{Jc[a]=e}return e}});var _r=g((tL,rd)=>{"use strict";var Ty=ft(),Iy=Se(),Ey=ed(),td="__core-js_shared__",id=rd.exports=Iy[td]||Ey(td,{});(id.versions||(id.versions=[])).push({version:"3.43.0",mode:Ty?"pure":"global",copyright:"© 2014-2025 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.43.0/LICENSE",source:"https://github.com/zloirock/core-js"})});var Io=g((iL,sd)=>{"use strict";var ad=_r();sd.exports=function(a,e){return ad[a]||(ad[a]=e||{})}});var qi=g((rL,nd)=>{"use strict";var xy=Xt(),wy=Object;nd.exports=function(a){return wy(xy(a))}});var mt=g((aL,od)=>{"use strict";var ky=ke(),Ay=qi(),Py=ky({}.hasOwnProperty);od.exports=Object.hasOwn||function(e,t){return Py(Ay(e),t)}});var Eo=g((sL,ud)=>{"use strict";var Ry=ke(),$y=0,Ly=Math.random(),My=Ry(1.1.toString);ud.exports=function(a){return"Symbol("+(a===void 0?"":a)+")_"+My(++$y+Ly,36)}});var Le=g((nL,cd)=>{"use strict";var Dy=Se(),Cy=Io(),ld=mt(),By=Eo(),Vy=bo(),_y=go(),Ui=Dy.Symbol,xo=Cy("wks"),Oy=_y?Ui.for||Ui:Ui&&Ui.withoutSetter||By;cd.exports=function(a){return ld(xo,a)||(xo[a]=Vy&&ld(Ui,a)?Ui[a]:Oy("Symbol."+a)),xo[a]}});var fd=g((oL,hd)=>{"use strict";var Fy=Xe(),dd=qe(),pd=So(),Ny=Vr(),qy=Kc(),Uy=Le(),Hy=TypeError,jy=Uy("toPrimitive");hd.exports=function(a,e){if(!dd(a)||pd(a))return a;var t=Ny(a,jy),i;if(t){if(e===void 0&&(e="default"),i=Fy(t,a,e),!dd(i)||pd(i))return i;throw new Hy("Can't convert object to primitive value")}return e===void 0&&(e="number"),qy(a,e)}});var wo=g((uL,md)=>{"use strict";var Wy=fd(),Qy=So();md.exports=function(a){var e=Wy(a,"string");return Qy(e)?e:e+""}});var Ss=g((lL,gd)=>{"use strict";var Gy=Se(),bd=qe(),ko=Gy.document,zy=bd(ko)&&bd(ko.createElement);gd.exports=function(a){return zy?ko.createElement(a):{}}});var Ao=g((cL,Sd)=>{"use strict";var Yy=Ke(),Ky=we(),Xy=Ss();Sd.exports=!Yy&&!Ky(function(){return Object.defineProperty(Xy("div"),"a",{get:function(){return 7}}).a!==7})});var Td=g(yd=>{"use strict";var Jy=Ke(),Zy=Xe(),eT=lo(),tT=Mr(),iT=fi(),rT=wo(),aT=mt(),sT=Ao(),vd=Object.getOwnPropertyDescriptor;yd.f=Jy?vd:function(e,t){if(e=iT(e),t=rT(t),sT)try{return vd(e,t)}catch{}if(aT(e,t))return tT(!Zy(eT.f,e,t),e[t])}});var Po=g((pL,Id)=>{"use strict";var nT=we(),oT=ve(),uT=/#|\.prototype\./,Or=function(a,e){var t=cT[lT(a)];return t===pT?!0:t===dT?!1:oT(e)?nT(e):!!e},lT=Or.normalize=function(a){return String(a).replace(uT,".").toLowerCase()},cT=Or.data={},dT=Or.NATIVE="N",pT=Or.POLYFILL="P";Id.exports=Or});var Hi=g((hL,xd)=>{"use strict";var Ed=oo(),hT=wt(),fT=Lr(),mT=Ed(Ed.bind);xd.exports=function(a,e){return hT(a),e===void 0?a:fT?mT(a,e):function(){return a.apply(e,arguments)}}});var Ro=g((fL,wd)=>{"use strict";var bT=Ke(),gT=we();wd.exports=bT&&gT(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var kt=g((mL,kd)=>{"use strict";var ST=qe(),vT=String,yT=TypeError;kd.exports=function(a){if(ST(a))return a;throw new yT(vT(a)+" is not an object")}});var gi=g(Pd=>{"use strict";var TT=Ke(),IT=Ao(),ET=Ro(),vs=kt(),Ad=wo(),xT=TypeError,$o=Object.defineProperty,wT=Object.getOwnPropertyDescriptor,Lo="enumerable",Mo="configurable",Do="writable";Pd.f=TT?ET?function(e,t,i){if(vs(e),t=Ad(t),vs(i),typeof e=="function"&&t==="prototype"&&"value"in i&&Do in i&&!i[Do]){var r=wT(e,t);r&&r[Do]&&(e[t]=i.value,i={configurable:Mo in i?i[Mo]:r[Mo],enumerable:Lo in i?i[Lo]:r[Lo],writable:!1})}return $o(e,t,i)}:$o:function(e,t,i){if(vs(e),t=Ad(t),vs(i),IT)try{return $o(e,t,i)}catch{}if("get"in i||"set"in i)throw new xT("Accessors not supported");return"value"in i&&(e[t]=i.value),e}});var ji=g((gL,Rd)=>{"use strict";var kT=Ke(),AT=gi(),PT=Mr();Rd.exports=kT?function(a,e,t){return AT.f(a,e,PT(1,t))}:function(a,e,t){return a[e]=t,a}});var Te=g((SL,Ld)=>{"use strict";var Fr=Se(),RT=so(),$T=oo(),LT=ve(),MT=Td().f,DT=Po(),Wi=mi(),CT=Hi(),Qi=ji(),$d=mt();_r();var BT=function(a){var e=function(t,i,r){if(this instanceof e){switch(arguments.length){case 0:return new a;case 1:return new a(t);case 2:return new a(t,i)}return new a(t,i,r)}return RT(a,this,arguments)};return e.prototype=a.prototype,e};Ld.exports=function(a,e){var t=a.target,i=a.global,r=a.stat,s=a.proto,n=i?Fr:r?Fr[t]:Fr[t]&&Fr[t].prototype,u=i?Wi:Wi[t]||Qi(Wi,t,{})[t],o=u.prototype,l,p,c,d,h,m,b,S,v;for(d in e)l=DT(i?d:t+(r?".":"#")+d,a.forced),p=!l&&n&&$d(n,d),m=u[d],p&&(a.dontCallGetSet?(v=MT(n,d),b=v&&v.value):b=n[d]),h=p&&b?b:e[d],!(!l&&!s&&typeof m==typeof h)&&(a.bind&&p?S=CT(h,Fr):a.wrap&&p?S=BT(h):s&&LT(h)?S=$T(h):S=h,(a.sham||h&&h.sham||m&&m.sham)&&Qi(S,"sham",!0),Qi(u,d,S),s&&(c=t+"Prototype",$d(Wi,c)||Qi(Wi,c,{}),Qi(Wi[c],d,h),a.real&&o&&(l||!o[d])&&Qi(o,d,h)))}});var ys=g((vL,Dd)=>{"use strict";var VT=Io(),_T=Eo(),Md=VT("keys");Dd.exports=function(a){return Md[a]||(Md[a]=_T(a))}});var Bd=g((yL,Cd)=>{"use strict";var OT=we();Cd.exports=!OT(function(){function a(){}return a.prototype.constructor=null,Object.getPrototypeOf(new a)!==a.prototype})});var Ts=g((TL,_d)=>{"use strict";var FT=mt(),NT=ve(),qT=qi(),UT=ys(),HT=Bd(),Vd=UT("IE_PROTO"),Co=Object,jT=Co.prototype;_d.exports=HT?Co.getPrototypeOf:function(a){var e=qT(a);if(FT(e,Vd))return e[Vd];var t=e.constructor;return NT(t)&&e instanceof t?t.prototype:e instanceof Co?jT:null}});var Fd=g((IL,Od)=>{"use strict";var WT=Math.ceil,QT=Math.floor;Od.exports=Math.trunc||function(e){var t=+e;return(t>0?QT:WT)(t)}});var Nr=g((EL,Nd)=>{"use strict";var GT=Fd();Nd.exports=function(a){var e=+a;return e!==e||e===0?0:GT(e)}});var Ud=g((xL,qd)=>{"use strict";var zT=Nr(),YT=Math.max,KT=Math.min;qd.exports=function(a,e){var t=zT(a);return t<0?YT(t+e,0):KT(t,e)}});var Bo=g((wL,Hd)=>{"use strict";var XT=Nr(),JT=Math.min;Hd.exports=function(a){var e=XT(a);return e>0?JT(e,9007199254740991):0}});var Gi=g((kL,jd)=>{"use strict";var ZT=Bo();jd.exports=function(a){return ZT(a.length)}});var Vo=g((AL,Qd)=>{"use strict";var eI=fi(),tI=Ud(),iI=Gi(),Wd=function(a){return function(e,t,i){var r=eI(e),s=iI(r);if(s===0)return!a&&-1;var n=tI(i,s),u;if(a&&t!==t){for(;s>n;)if(u=r[n++],u!==u)return!0}else for(;s>n;n++)if((a||n in r)&&r[n]===t)return a||n||0;return!a&&-1}};Qd.exports={includes:Wd(!0),indexOf:Wd(!1)}});var Is=g((PL,Gd)=>{"use strict";Gd.exports={}});var Kd=g((RL,Yd)=>{"use strict";var rI=ke(),_o=mt(),aI=fi(),sI=Vo().indexOf,nI=Is(),zd=rI([].push);Yd.exports=function(a,e){var t=aI(a),i=0,r=[],s;for(s in t)!_o(nI,s)&&_o(t,s)&&zd(r,s);for(;e.length>i;)_o(t,s=e[i++])&&(~sI(r,s)||zd(r,s));return r}});var Oo=g(($L,Xd)=>{"use strict";Xd.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var Fo=g((LL,Jd)=>{"use strict";var oI=Kd(),uI=Oo();Jd.exports=Object.keys||function(e){return oI(e,uI)}});var No=g((ML,rp)=>{"use strict";var ep=Ke(),lI=we(),tp=ke(),cI=Ts(),dI=Fo(),pI=fi(),hI=lo().f,ip=tp(hI),fI=tp([].push),mI=ep&&lI(function(){var a=Object.create(null);return a[2]=2,!ip(a,2)}),Zd=function(a){return function(e){for(var t=pI(e),i=dI(t),r=mI&&cI(t)===null,s=i.length,n=0,u=[],o;s>n;)o=i[n++],(!ep||(r?o in t:ip(t,o)))&&fI(u,a?[o,t[o]]:t[o]);return u}};rp.exports={entries:Zd(!0),values:Zd(!1)}});var ap=g(()=>{"use strict";var bI=Te(),gI=No().values;bI({target:"Object",stat:!0},{values:function(e){return gI(e)}})});var np=g((BL,sp)=>{"use strict";ap();var SI=mi();sp.exports=SI.Object.values});var up=g((VL,op)=>{"use strict";var vI=np();op.exports=vI});var Si=g((_L,lp)=>{"use strict";var yI=up();lp.exports=yI});var qr=g((OL,cp)=>{"use strict";cp.exports=function(){}});var dp=g(()=>{"use strict";var TI=Te(),II=Vo().includes,EI=we(),xI=qr(),wI=EI(function(){return!Array(1).includes()});TI({target:"Array",proto:!0,forced:wI},{includes:function(e){return II(this,e,arguments.length>1?arguments[1]:void 0)}});xI("includes")});var Jt=g((qL,pp)=>{"use strict";var kI=Vt();pp.exports=kI});var fp=g((UL,hp)=>{"use strict";dp();var AI=Jt();hp.exports=AI("Array","includes")});var bp=g((HL,mp)=>{"use strict";var PI=fp();mp.exports=PI});var Oe=g((jL,gp)=>{"use strict";var RI=bp();gp.exports=RI});var vp=g(()=>{"use strict";var LI=Te(),MI=No().entries;LI({target:"Object",stat:!0},{entries:function(e){return MI(e)}})});var Tp=g((rM,yp)=>{"use strict";vp();var DI=mi();yp.exports=DI.Object.entries});var Ep=g((aM,Ip)=>{"use strict";var CI=Tp();Ip.exports=CI});var zi=g((sM,xp)=>{"use strict";var BI=Ep();xp.exports=BI});var vi=g((nM,wp)=>{"use strict";wp.exports={}});var Pp=g((oM,Ap)=>{"use strict";var VI=Se(),_I=ve(),kp=VI.WeakMap;Ap.exports=_I(kp)&&/native code/.test(String(kp))});var jo=g((uM,Lp)=>{"use strict";var OI=Pp(),$p=Se(),FI=qe(),NI=ji(),qo=mt(),Uo=_r(),qI=ys(),UI=Is(),Rp="Object already initialized",Ho=$p.TypeError,HI=$p.WeakMap,xs,Ur,ws,jI=function(a){return ws(a)?Ur(a):xs(a,{})},WI=function(a){return function(e){var t;if(!FI(e)||(t=Ur(e)).type!==a)throw new Ho("Incompatible receiver, "+a+" required");return t}};OI||Uo.state?(bt=Uo.state||(Uo.state=new HI),bt.get=bt.get,bt.has=bt.has,bt.set=bt.set,xs=function(a,e){if(bt.has(a))throw new Ho(Rp);return e.facade=a,bt.set(a,e),e},Ur=function(a){return bt.get(a)||{}},ws=function(a){return bt.has(a)}):(yi=qI("state"),UI[yi]=!0,xs=function(a,e){if(qo(a,yi))throw new Ho(Rp);return e.facade=a,NI(a,yi,e),e},Ur=function(a){return qo(a,yi)?a[yi]:{}},ws=function(a){return qo(a,yi)});var bt,yi;Lp.exports={set:xs,get:Ur,has:ws,enforce:jI,getterFor:WI}});var Go=g((lM,Dp)=>{"use strict";var Wo=Ke(),QI=mt(),Mp=Function.prototype,GI=Wo&&Object.getOwnPropertyDescriptor,Qo=QI(Mp,"name"),zI=Qo&&function(){}.name==="something",YI=Qo&&(!Wo||Wo&&GI(Mp,"name").configurable);Dp.exports={EXISTS:Qo,PROPER:zI,CONFIGURABLE:YI}});var Bp=g(Cp=>{"use strict";var KI=Ke(),XI=Ro(),JI=gi(),ZI=kt(),eE=fi(),tE=Fo();Cp.f=KI&&!XI?Object.defineProperties:function(e,t){ZI(e);for(var i=eE(t),r=tE(t),s=r.length,n=0,u;s>n;)JI.f(e,u=r[n++],i[u]);return e}});var zo=g((dM,Vp)=>{"use strict";var iE=Vt();Vp.exports=iE("document","documentElement")});var Jo=g((pM,Hp)=>{"use strict";var rE=kt(),aE=Bp(),_p=Oo(),sE=Is(),nE=zo(),oE=Ss(),uE=ys(),Op=">",Fp="<",Ko="prototype",Xo="script",qp=uE("IE_PROTO"),Yo=function(){},Up=function(a){return Fp+Xo+Op+a+Fp+"/"+Xo+Op},Np=function(a){a.write(Up("")),a.close();var e=a.parentWindow.Object;return a=null,e},lE=function(){var a=oE("iframe"),e="java"+Xo+":",t;return a.style.display="none",nE.appendChild(a),a.src=String(e),t=a.contentWindow.document,t.open(),t.write(Up("document.F=Object")),t.close(),t.F},ks,As=function(){try{ks=new ActiveXObject("htmlfile")}catch{}As=typeof document<"u"?document.domain&&ks?Np(ks):lE():Np(ks);for(var a=_p.length;a--;)delete As[Ko][_p[a]];return As()};sE[qp]=!0;Hp.exports=Object.create||function(e,t){var i;return e!==null?(Yo[Ko]=rE(e),i=new Yo,Yo[Ko]=null,i[qp]=e):i=As(),t===void 0?i:aE.f(i,t)}});var Yi=g((hM,jp)=>{"use strict";var cE=ji();jp.exports=function(a,e,t,i){return i&&i.enumerable?a[e]=t:cE(a,e,t),a}});var iu=g((fM,Gp)=>{"use strict";var dE=we(),pE=ve(),hE=qe(),fE=Jo(),Wp=Ts(),mE=Yi(),bE=Le(),gE=ft(),tu=bE("iterator"),Qp=!1,_t,Zo,eu;[].keys&&(eu=[].keys(),"next"in eu?(Zo=Wp(Wp(eu)),Zo!==Object.prototype&&(_t=Zo)):Qp=!0);var SE=!hE(_t)||dE(function(){var a={};return _t[tu].call(a)!==a});SE?_t={}:gE&&(_t=fE(_t));pE(_t[tu])||mE(_t,tu,function(){return this});Gp.exports={IteratorPrototype:_t,BUGGY_SAFARI_ITERATORS:Qp}});var Ps=g((mM,Yp)=>{"use strict";var vE=Le(),yE=vE("toStringTag"),zp={};zp[yE]="z";Yp.exports=String(zp)==="[object z]"});var Hr=g((bM,Kp)=>{"use strict";var TE=Ps(),IE=ve(),Rs=hi(),EE=Le(),xE=EE("toStringTag"),wE=Object,kE=Rs(function(){return arguments}())==="Arguments",AE=function(a,e){try{return a[e]}catch{}};Kp.exports=TE?Rs:function(a){var e,t,i;return a===void 0?"Undefined":a===null?"Null":typeof(t=AE(e=wE(a),xE))=="string"?t:kE?Rs(e):(i=Rs(e))==="Object"&&IE(e.callee)?"Arguments":i}});var Jp=g((gM,Xp)=>{"use strict";var PE=Ps(),RE=Hr();Xp.exports=PE?{}.toString:function(){return"[object "+RE(this)+"]"}});var jr=g((SM,eh)=>{"use strict";var $E=Ps(),LE=gi().f,ME=ji(),DE=mt(),CE=Jp(),BE=Le(),Zp=BE("toStringTag");eh.exports=function(a,e,t,i){var r=t?a:a&&a.prototype;r&&(DE(r,Zp)||LE(r,Zp,{configurable:!0,value:e}),i&&!$E&&ME(r,"toString",CE))}});var ih=g((vM,th)=>{"use strict";var VE=iu().IteratorPrototype,_E=Jo(),OE=Mr(),FE=jr(),NE=vi(),qE=function(){return this};th.exports=function(a,e,t,i){var r=e+" Iterator";return a.prototype=_E(VE,{next:OE(+!i,t)}),FE(a,r,!1,!0),NE[r]=qE,a}});var ah=g((yM,rh)=>{"use strict";var UE=ke(),HE=wt();rh.exports=function(a,e,t){try{return UE(HE(Object.getOwnPropertyDescriptor(a,e)[t]))}catch{}}});var nh=g((TM,sh)=>{"use strict";var jE=qe();sh.exports=function(a){return jE(a)||a===null}});var uh=g((IM,oh)=>{"use strict";var WE=nh(),QE=String,GE=TypeError;oh.exports=function(a){if(WE(a))return a;throw new GE("Can't set "+QE(a)+" as a prototype")}});var ru=g((EM,lh)=>{"use strict";var zE=ah(),YE=qe(),KE=Xt(),XE=uh();lh.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var a=!1,e={},t;try{t=zE(Object.prototype,"__proto__","set"),t(e,[]),a=e instanceof Array}catch{}return function(r,s){return KE(r),XE(s),YE(r)&&(a?t(r,s):r.__proto__=s),r}}():void 0)});var yh=g((xM,vh)=>{"use strict";var JE=Te(),ZE=Xe(),$s=ft(),gh=Go(),ex=ve(),tx=ih(),ch=Ts(),dh=ru(),ix=jr(),rx=ji(),au=Yi(),ax=Le(),ph=vi(),Sh=iu(),sx=gh.PROPER,nx=gh.CONFIGURABLE,hh=Sh.IteratorPrototype,Ls=Sh.BUGGY_SAFARI_ITERATORS,Wr=ax("iterator"),fh="keys",Qr="values",mh="entries",bh=function(){return this};vh.exports=function(a,e,t,i,r,s,n){tx(t,e,i);var u=function(v){if(v===r&&d)return d;if(!Ls&&v&&v in p)return p[v];switch(v){case fh:return function(){return new t(this,v)};case Qr:return function(){return new t(this,v)};case mh:return function(){return new t(this,v)}}return function(){return new t(this)}},o=e+" Iterator",l=!1,p=a.prototype,c=p[Wr]||p["@@iterator"]||r&&p[r],d=!Ls&&c||u(r),h=e==="Array"&&p.entries||c,m,b,S;if(h&&(m=ch(h.call(new a)),m!==Object.prototype&&m.next&&(!$s&&ch(m)!==hh&&(dh?dh(m,hh):ex(m[Wr])||au(m,Wr,bh)),ix(m,o,!0,!0),$s&&(ph[o]=bh))),sx&&r===Qr&&c&&c.name!==Qr&&(!$s&&nx?rx(p,"name",Qr):(l=!0,d=function(){return ZE(c,this)})),r)if(b={values:u(Qr),keys:s?d:u(fh),entries:u(mh)},n)for(S in b)(Ls||l||!(S in p))&&au(p,S,b[S]);else JE({target:e,proto:!0,forced:Ls||l},b);return(!$s||n)&&p[Wr]!==d&&au(p,Wr,d,{name:r}),ph[e]=d,b}});var Ih=g((wM,Th)=>{"use strict";Th.exports=function(a,e){return{value:a,done:e}}});var nu=g((kM,Ah)=>{"use strict";var ox=fi(),su=qr(),Eh=vi(),wh=jo(),ux=gi().f,lx=yh(),Ms=Ih(),cx=ft(),dx=Ke(),kh="Array Iterator",px=wh.set,hx=wh.getterFor(kh);Ah.exports=lx(Array,"Array",function(a,e){px(this,{type:kh,target:ox(a),index:0,kind:e})},function(){var a=hx(this),e=a.target,t=a.index++;if(!e||t>=e.length)return a.target=null,Ms(void 0,!0);switch(a.kind){case"keys":return Ms(t,!1);case"values":return Ms(e[t],!1)}return Ms([t,e[t]],!1)},"values");var xh=Eh.Arguments=Eh.Array;su("keys");su("values");su("entries");if(!cx&&dx&&xh.name!=="values")try{ux(xh,"name",{value:"values"})}catch{}});var Rh=g((AM,Ph)=>{"use strict";var fx=Le(),mx=vi(),bx=fx("iterator"),gx=Array.prototype;Ph.exports=function(a){return a!==void 0&&(mx.Array===a||gx[bx]===a)}});var ou=g((PM,Lh)=>{"use strict";var Sx=Hr(),$h=Vr(),vx=Dr(),yx=vi(),Tx=Le(),Ix=Tx("iterator");Lh.exports=function(a){if(!vx(a))return $h(a,Ix)||$h(a,"@@iterator")||yx[Sx(a)]}});var Dh=g((RM,Mh)=>{"use strict";var Ex=Xe(),xx=wt(),wx=kt(),kx=Br(),Ax=ou(),Px=TypeError;Mh.exports=function(a,e){var t=arguments.length<2?Ax(a):e;if(xx(t))return wx(Ex(t,a));throw new Px(kx(a)+" is not iterable")}});var Vh=g(($M,Bh)=>{"use strict";var Rx=Xe(),Ch=kt(),$x=Vr();Bh.exports=function(a,e,t){var i,r;Ch(a);try{if(i=$x(a,"return"),!i){if(e==="throw")throw t;return t}i=Rx(i,a)}catch(s){r=!0,i=s}if(e==="throw")throw t;if(r)throw i;return Ch(i),t}});var Cs=g((LM,Nh)=>{"use strict";var Lx=Hi(),Mx=Xe(),Dx=kt(),Cx=Br(),Bx=Rh(),Vx=Gi(),_h=Cr(),_x=Dh(),Ox=ou(),Oh=Vh(),Fx=TypeError,Ds=function(a,e){this.stopped=a,this.result=e},Fh=Ds.prototype;Nh.exports=function(a,e,t){var i=t&&t.that,r=!!(t&&t.AS_ENTRIES),s=!!(t&&t.IS_RECORD),n=!!(t&&t.IS_ITERATOR),u=!!(t&&t.INTERRUPTED),o=Lx(e,i),l,p,c,d,h,m,b,S=function(I){return l&&Oh(l,"normal"),new Ds(!0,I)},v=function(I){return r?(Dx(I),u?o(I[0],I[1],S):o(I[0],I[1])):u?o(I,S):o(I)};if(s)l=a.iterator;else if(n)l=a;else{if(p=Ox(a),!p)throw new Fx(Cx(a)+" is not iterable");if(Bx(p)){for(c=0,d=Vx(a);d>c;c++)if(h=v(a[c]),h&&_h(Fh,h))return h;return new Ds(!1)}l=_x(a,p)}for(m=s?a.next:l.next;!(b=Mx(m,l)).done;){try{h=v(b.value)}catch(I){Oh(l,"throw",I)}if(typeof h=="object"&&h&&_h(Fh,h))return h}return new Ds(!1)}});var Uh=g((MM,qh)=>{"use strict";var Nx=Ke(),qx=gi(),Ux=Mr();qh.exports=function(a,e,t){Nx?qx.f(a,e,Ux(0,t)):a[e]=t}});var Hh=g(()=>{"use strict";var Hx=Te(),jx=Cs(),Wx=Uh();Hx({target:"Object",stat:!0},{fromEntries:function(e){var t={};return jx(e,function(i,r){Wx(t,i,r)},{AS_ENTRIES:!0}),t}})});var Wh=g((BM,jh)=>{"use strict";nu();Hh();var Qx=mi();jh.exports=Qx.Object.fromEntries});var Gh=g((VM,Qh)=>{"use strict";Qh.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 Yh=g(()=>{"use strict";nu();var Gx=Gh(),zx=Se(),Yx=jr(),zh=vi();for(Bs in Gx)Yx(zx[Bs],Bs),zh[Bs]=zh.Array;var Bs});var Xh=g((FM,Kh)=>{"use strict";var Kx=Wh();Yh();Kh.exports=Kx});var uu=g((NM,Jh)=>{"use strict";var Xx=Xh();Jh.exports=Xx});var Zh=g(()=>{"use strict"});var lu=g((HM,ef)=>{"use strict";var Gr=Se(),Jx=bi(),Zx=hi(),Vs=function(a){return Jx.slice(0,a.length)===a};ef.exports=function(){return Vs("Bun/")?"BUN":Vs("Cloudflare-Workers")?"CLOUDFLARE":Vs("Deno/")?"DENO":Vs("Node.js/")?"NODE":Gr.Bun&&typeof Bun.version=="string"?"BUN":Gr.Deno&&typeof Deno.version=="object"?"DENO":Zx(Gr.process)==="process"?"NODE":Gr.window&&Gr.document?"BROWSER":"REST"}()});var _s=g((jM,tf)=>{"use strict";var ew=lu();tf.exports=ew==="NODE"});var af=g((WM,rf)=>{"use strict";var tw=gi();rf.exports=function(a,e,t){return tw.f(a,e,t)}});var of=g((QM,nf)=>{"use strict";var iw=Vt(),rw=af(),aw=Le(),sw=Ke(),sf=aw("species");nf.exports=function(a){var e=iw(a);sw&&e&&!e[sf]&&rw(e,sf,{configurable:!0,get:function(){return this}})}});var lf=g((GM,uf)=>{"use strict";var nw=Cr(),ow=TypeError;uf.exports=function(a,e){if(nw(e,a))return a;throw new ow("Incorrect invocation")}});var du=g((zM,cf)=>{"use strict";var uw=ke(),lw=ve(),cu=_r(),cw=uw(Function.toString);lw(cu.inspectSource)||(cu.inspectSource=function(a){return cw(a)});cf.exports=cu.inspectSource});var hu=g((YM,mf)=>{"use strict";var dw=ke(),pw=we(),df=ve(),hw=Hr(),fw=Vt(),mw=du(),pf=function(){},hf=fw("Reflect","construct"),pu=/^\s*(?:class|function)\b/,bw=dw(pu.exec),gw=!pu.test(pf),zr=function(e){if(!df(e))return!1;try{return hf(pf,[],e),!0}catch{return!1}},ff=function(e){if(!df(e))return!1;switch(hw(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return gw||!!bw(pu,mw(e))}catch{return!0}};ff.sham=!0;mf.exports=!hf||pw(function(){var a;return zr(zr.call)||!zr(Object)||!zr(function(){a=!0})||a})?ff:zr});var gf=g((KM,bf)=>{"use strict";var Sw=hu(),vw=Br(),yw=TypeError;bf.exports=function(a){if(Sw(a))return a;throw new yw(vw(a)+" is not a constructor")}});var fu=g((XM,vf)=>{"use strict";var Sf=kt(),Tw=gf(),Iw=Dr(),Ew=Le(),xw=Ew("species");vf.exports=function(a,e){var t=Sf(a).constructor,i;return t===void 0||Iw(i=Sf(t)[xw])?e:Tw(i)}});var Tf=g((JM,yf)=>{"use strict";var ww=ke();yf.exports=ww([].slice)});var Ef=g((ZM,If)=>{"use strict";var kw=TypeError;If.exports=function(a,e){if(a<e)throw new kw("Not enough arguments");return a}});var mu=g((eD,xf)=>{"use strict";var Aw=bi();xf.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(Aw)});var xu=g((tD,Df)=>{"use strict";var Je=Se(),Pw=so(),Rw=Hi(),wf=ve(),$w=mt(),Mf=we(),kf=zo(),Lw=Tf(),Af=Ss(),Mw=Ef(),Dw=mu(),Cw=_s(),Tu=Je.setImmediate,Iu=Je.clearImmediate,Bw=Je.process,bu=Je.Dispatch,Vw=Je.Function,Pf=Je.MessageChannel,_w=Je.String,gu=0,Yr={},Rf="onreadystatechange",Kr,Ti,Su,vu;Mf(function(){Kr=Je.location});var Eu=function(a){if($w(Yr,a)){var e=Yr[a];delete Yr[a],e()}},yu=function(a){return function(){Eu(a)}},$f=function(a){Eu(a.data)},Lf=function(a){Je.postMessage(_w(a),Kr.protocol+"//"+Kr.host)};(!Tu||!Iu)&&(Tu=function(e){Mw(arguments.length,1);var t=wf(e)?e:Vw(e),i=Lw(arguments,1);return Yr[++gu]=function(){Pw(t,void 0,i)},Ti(gu),gu},Iu=function(e){delete Yr[e]},Cw?Ti=function(a){Bw.nextTick(yu(a))}:bu&&bu.now?Ti=function(a){bu.now(yu(a))}:Pf&&!Dw?(Su=new Pf,vu=Su.port2,Su.port1.onmessage=$f,Ti=Rw(vu.postMessage,vu)):Je.addEventListener&&wf(Je.postMessage)&&!Je.importScripts&&Kr&&Kr.protocol!=="file:"&&!Mf(Lf)?(Ti=Lf,Je.addEventListener("message",$f,!1)):Rf in Af("script")?Ti=function(a){kf.appendChild(Af("script"))[Rf]=function(){kf.removeChild(this),Eu(a)}}:Ti=function(a){setTimeout(yu(a),0)});Df.exports={set:Tu,clear:Iu}});var Vf=g((iD,Bf)=>{"use strict";var Cf=Se(),Ow=Ke(),Fw=Object.getOwnPropertyDescriptor;Bf.exports=function(a){if(!Ow)return Cf[a];var e=Fw(Cf,a);return e&&e.value}});var wu=g((rD,Of)=>{"use strict";var _f=function(){this.head=null,this.tail=null};_f.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=_f});var Nf=g((aD,Ff)=>{"use strict";var Nw=bi();Ff.exports=/ipad|iphone|ipod/i.test(Nw)&&typeof Pebble<"u"});var Uf=g((sD,qf)=>{"use strict";var qw=bi();qf.exports=/web0s(?!.*chrome)/i.test(qw)});var Yf=g((nD,zf)=>{"use strict";var Xi=Se(),Uw=Vf(),Hf=Hi(),ku=xu().set,Hw=wu(),jw=mu(),Ww=Nf(),Qw=Uf(),Au=_s(),jf=Xi.MutationObserver||Xi.WebKitMutationObserver,Wf=Xi.document,Qf=Xi.process,Os=Xi.Promise,$u=Uw("queueMicrotask"),Ki,Pu,Ru,Fs,Gf;$u||(Xr=new Hw,Jr=function(){var a,e;for(Au&&(a=Qf.domain)&&a.exit();e=Xr.get();)try{e()}catch(t){throw Xr.head&&Ki(),t}a&&a.enter()},!jw&&!Au&&!Qw&&jf&&Wf?(Pu=!0,Ru=Wf.createTextNode(""),new jf(Jr).observe(Ru,{characterData:!0}),Ki=function(){Ru.data=Pu=!Pu}):!Ww&&Os&&Os.resolve?(Fs=Os.resolve(void 0),Fs.constructor=Os,Gf=Hf(Fs.then,Fs),Ki=function(){Gf(Jr)}):Au?Ki=function(){Qf.nextTick(Jr)}:(ku=Hf(ku,Xi),Ki=function(){ku(Jr)}),$u=function(a){Xr.head||Ki(),Xr.add(a)});var Xr,Jr;zf.exports=$u});var Xf=g((oD,Kf)=>{"use strict";Kf.exports=function(a,e){try{arguments.length===1?console.error(a):console.error(a,e)}catch{}}});var Ns=g((uD,Jf)=>{"use strict";Jf.exports=function(a){try{return{error:!1,value:a()}}catch(e){return{error:!0,value:e}}}});var Ii=g((lD,Zf)=>{"use strict";var Gw=Se();Zf.exports=Gw.Promise});var Ji=g((cD,rm)=>{"use strict";var zw=Se(),Zr=Ii(),Yw=ve(),Kw=Po(),Xw=du(),Jw=Le(),em=lu(),Zw=ft(),Lu=mo(),tm=Zr&&Zr.prototype,ek=Jw("species"),Mu=!1,im=Yw(zw.PromiseRejectionEvent),tk=Kw("Promise",function(){var a=Xw(Zr),e=a!==String(Zr);if(!e&&Lu===66||Zw&&!(tm.catch&&tm.finally))return!0;if(!Lu||Lu<51||!/native code/.test(a)){var t=new Zr(function(s){s(1)}),i=function(s){s(function(){},function(){})},r=t.constructor={};if(r[ek]=i,Mu=t.then(function(){})instanceof i,!Mu)return!0}return!e&&(em==="BROWSER"||em==="DENO")&&!im});rm.exports={CONSTRUCTOR:tk,REJECTION_EVENT:im,SUBCLASSING:Mu}});var Zi=g((dD,sm)=>{"use strict";var am=wt(),ik=TypeError,rk=function(a){var e,t;this.promise=new a(function(i,r){if(e!==void 0||t!==void 0)throw new ik("Bad Promise constructor");e=i,t=r}),this.resolve=am(e),this.reject=am(t)};sm.exports.f=function(a){return new rk(a)}});var wm=g(()=>{"use strict";var ak=Te(),sk=ft(),js=_s(),Zt=Se(),nk=mi(),rr=Xe(),nm=Yi(),om=ru(),ok=jr(),uk=of(),lk=wt(),Hs=ve(),ck=qe(),dk=lf(),pk=fu(),pm=xu().set,_u=Yf(),hk=Xf(),fk=Ns(),mk=wu(),hm=jo(),Ws=Ii(),Ou=Ji(),fm=Zi(),Qs="Promise",mm=Ou.CONSTRUCTOR,bk=Ou.REJECTION_EVENT,gk=Ou.SUBCLASSING,Du=hm.getterFor(Qs),Sk=hm.set,er=Ws&&Ws.prototype,Ei=Ws,qs=er,bm=Zt.TypeError,Cu=Zt.document,Fu=Zt.process,Bu=fm.f,vk=Bu,yk=!!(Cu&&Cu.createEvent&&Zt.dispatchEvent),gm="unhandledrejection",Tk="rejectionhandled",um=0,Sm=1,Ik=2,Nu=1,vm=2,Us,lm,ym,cm,Tm=function(a){var e;return ck(a)&&Hs(e=a.then)?e:!1},Im=function(a,e){var t=e.value,i=e.state===Sm,r=i?a.ok:a.fail,s=a.resolve,n=a.reject,u=a.domain,o,l,p;try{r?(i||(e.rejection===vm&&xk(e),e.rejection=Nu),r===!0?o=t:(u&&u.enter(),o=r(t),u&&(u.exit(),p=!0)),o===a.promise?n(new bm("Promise-chain cycle")):(l=Tm(o))?rr(l,o,s,n):s(o)):n(t)}catch(c){u&&!p&&u.exit(),n(c)}},Em=function(a,e){a.notified||(a.notified=!0,_u(function(){for(var t=a.reactions,i;i=t.get();)Im(i,a);a.notified=!1,e&&!a.rejection&&Ek(a)}))},xm=function(a,e,t){var i,r;yk?(i=Cu.createEvent("Event"),i.promise=e,i.reason=t,i.initEvent(a,!1,!0),Zt.dispatchEvent(i)):i={promise:e,reason:t},!bk&&(r=Zt["on"+a])?r(i):a===gm&&hk("Unhandled promise rejection",t)},Ek=function(a){rr(pm,Zt,function(){var e=a.facade,t=a.value,i=dm(a),r;if(i&&(r=fk(function(){js?Fu.emit("unhandledRejection",t,e):xm(gm,e,t)}),a.rejection=js||dm(a)?vm:Nu,r.error))throw r.value})},dm=function(a){return a.rejection!==Nu&&!a.parent},xk=function(a){rr(pm,Zt,function(){var e=a.facade;js?Fu.emit("rejectionHandled",e):xm(Tk,e,a.value)})},tr=function(a,e,t){return function(i){a(e,i,t)}},ir=function(a,e,t){a.done||(a.done=!0,t&&(a=t),a.value=e,a.state=Ik,Em(a,!0))},Vu=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 i=Tm(e);i?_u(function(){var r={done:!1};try{rr(i,e,tr(Vu,r,a),tr(ir,r,a))}catch(s){ir(r,s,a)}}):(a.value=e,a.state=Sm,Em(a,!1))}catch(r){ir({done:!1},r,a)}}};if(mm&&(Ei=function(e){dk(this,qs),lk(e),rr(Us,this);var t=Du(this);try{e(tr(Vu,t),tr(ir,t))}catch(i){ir(t,i)}},qs=Ei.prototype,Us=function(e){Sk(this,{type:Qs,done:!1,notified:!1,parent:!1,reactions:new mk,rejection:!1,state:um,value:null})},Us.prototype=nm(qs,"then",function(e,t){var i=Du(this),r=Bu(pk(this,Ei));return i.parent=!0,r.ok=Hs(e)?e:!0,r.fail=Hs(t)&&t,r.domain=js?Fu.domain:void 0,i.state===um?i.reactions.add(r):_u(function(){Im(r,i)}),r.promise}),lm=function(){var a=new Us,e=Du(a);this.promise=a,this.resolve=tr(Vu,e),this.reject=tr(ir,e)},fm.f=Bu=function(a){return a===Ei||a===ym?new lm(a):vk(a)},!sk&&Hs(Ws)&&er!==Object.prototype)){cm=er.then,gk||nm(er,"then",function(e,t){var i=this;return new Ei(function(r,s){rr(cm,i,r,s)}).then(e,t)},{unsafe:!0});try{delete er.constructor}catch{}om&&om(er,qs)}ak({global:!0,constructor:!0,wrap:!0,forced:mm},{Promise:Ei});ym=nk.Promise;ok(Ei,Qs,!1,!0);uk(Qs)});var $m=g((fD,Rm)=>{"use strict";var wk=Le(),Am=wk("iterator"),Pm=!1;try{km=0,qu={next:function(){return{done:!!km++}},return:function(){Pm=!0}},qu[Am]=function(){return this},Array.from(qu,function(){throw 2})}catch{}var km,qu;Rm.exports=function(a,e){try{if(!e&&!Pm)return!1}catch{return!1}var t=!1;try{var i={};i[Am]=function(){return{next:function(){return{done:t=!0}}}},a(i)}catch{}return t}});var Uu=g((mD,Lm)=>{"use strict";var kk=Ii(),Ak=$m(),Pk=Ji().CONSTRUCTOR;Lm.exports=Pk||!Ak(function(a){kk.all(a).then(void 0,function(){})})});var Mm=g(()=>{"use strict";var Rk=Te(),$k=Xe(),Lk=wt(),Mk=Zi(),Dk=Ns(),Ck=Cs(),Bk=Uu();Rk({target:"Promise",stat:!0,forced:Bk},{all:function(e){var t=this,i=Mk.f(t),r=i.resolve,s=i.reject,n=Dk(function(){var u=Lk(t.resolve),o=[],l=0,p=1;Ck(e,function(c){var d=l++,h=!1;p++,$k(u,t,c).then(function(m){h||(h=!0,o[d]=m,--p||r(o))},s)}),--p||r(o)});return n.error&&s(n.value),i.promise}})});var Cm=g(()=>{"use strict";var Vk=Te(),_k=ft(),Ok=Ji().CONSTRUCTOR,ju=Ii(),Fk=Vt(),Nk=ve(),qk=Yi(),Dm=ju&&ju.prototype;Vk({target:"Promise",proto:!0,forced:Ok,real:!0},{catch:function(a){return this.then(void 0,a)}});!_k&&Nk(ju)&&(Hu=Fk("Promise").prototype.catch,Dm.catch!==Hu&&qk(Dm,"catch",Hu,{unsafe:!0}));var Hu});var Bm=g(()=>{"use strict";var Uk=Te(),Hk=Xe(),jk=wt(),Wk=Zi(),Qk=Ns(),Gk=Cs(),zk=Uu();Uk({target:"Promise",stat:!0,forced:zk},{race:function(e){var t=this,i=Wk.f(t),r=i.reject,s=Qk(function(){var n=jk(t.resolve);Gk(e,function(u){Hk(n,t,u).then(i.resolve,r)})});return s.error&&r(s.value),i.promise}})});var Vm=g(()=>{"use strict";var Yk=Te(),Kk=Zi(),Xk=Ji().CONSTRUCTOR;Yk({target:"Promise",stat:!0,forced:Xk},{reject:function(e){var t=Kk.f(this),i=t.reject;return i(e),t.promise}})});var Wu=g((xD,_m)=>{"use strict";var Jk=kt(),Zk=qe(),eA=Zi();_m.exports=function(a,e){if(Jk(a),Zk(e)&&e.constructor===a)return e;var t=eA.f(a),i=t.resolve;return i(e),t.promise}});var Nm=g(()=>{"use strict";var tA=Te(),iA=Vt(),Om=ft(),rA=Ii(),Fm=Ji().CONSTRUCTOR,aA=Wu(),sA=iA("Promise"),nA=Om&&!Fm;tA({target:"Promise",stat:!0,forced:Om||Fm},{resolve:function(e){return aA(nA&&this===sA?rA:this,e)}})});var qm=g(()=>{"use strict";wm();Mm();Cm();Bm();Vm();Nm()});var Wm=g(()=>{"use strict";var oA=Te(),uA=ft(),Gs=Ii(),lA=we(),Hm=Vt(),jm=ve(),cA=fu(),Um=Wu(),dA=Yi(),Gu=Gs&&Gs.prototype,pA=!!Gs&&lA(function(){Gu.finally.call({then:function(){}},function(){})});oA({target:"Promise",proto:!0,real:!0,forced:pA},{finally:function(a){var e=cA(this,Hm("Promise")),t=jm(a);return this.then(t?function(i){return Um(e,a()).then(function(){return i})}:a,t?function(i){return Um(e,a()).then(function(){throw i})}:a)}});!uA&&jm(Gs)&&(Qu=Hm("Promise").prototype.finally,Gu.finally!==Qu&&dA(Gu,"finally",Qu,{unsafe:!0}));var Qu});var Gm=g((LD,Qm)=>{"use strict";Zh();qm();Wm();var hA=Jt();Qm.exports=hA("Promise","finally")});var Ym=g((MD,zm)=>{"use strict";var fA=Gm();zm.exports=fA});var zs=g((DD,Km)=>{"use strict";var mA=Ym();Km.exports=mA});var hb=g(()=>{"use strict";var RA=Te(),$A=qi(),LA=Gi(),MA=Nr(),DA=qr();RA({target:"Array",proto:!0},{at:function(e){var t=$A(this),i=LA(t),r=MA(e),s=r>=0?r:i+r;return s<0||s>=i?void 0:t[s]}});DA("at")});var mb=g((pB,fb)=>{"use strict";hb();var CA=Jt();fb.exports=CA("Array","at")});var gb=g((hB,bb)=>{"use strict";var BA=mb();bb.exports=BA});var gt=g((fB,Sb)=>{"use strict";var VA=gb();Sb.exports=VA});var fl=g((z0,Hb)=>{"use strict";var GA=hi();Hb.exports=Array.isArray||function(e){return GA(e)==="Array"}});var Wb=g((Y0,jb)=>{"use strict";var zA=TypeError,YA=9007199254740991;jb.exports=function(a){if(a>YA)throw zA("Maximum allowed index exceeded");return a}});var zb=g((K0,Gb)=>{"use strict";var KA=fl(),XA=Gi(),JA=Wb(),ZA=Hi(),Qb=function(a,e,t,i,r,s,n,u){for(var o=r,l=0,p=n?ZA(n,u):!1,c,d;l<i;)l in t&&(c=p?p(t[l],l,e):t[l],s>0&&KA(c)?(d=XA(c),o=Qb(a,e,c,d,o,s-1)-1):(JA(o+1),a[o]=c),o++),l++;return o};Gb.exports=Qb});var Jb=g((X0,Xb)=>{"use strict";var Yb=fl(),eP=hu(),tP=qe(),iP=Le(),rP=iP("species"),Kb=Array;Xb.exports=function(a){var e;return Yb(a)&&(e=a.constructor,eP(e)&&(e===Kb||Yb(e.prototype))?e=void 0:tP(e)&&(e=e[rP],e===null&&(e=void 0))),e===void 0?Kb:e}});var eg=g((J0,Zb)=>{"use strict";var aP=Jb();Zb.exports=function(a,e){return new(aP(a))(e===0?0:e)}});var tg=g(()=>{"use strict";var sP=Te(),nP=zb(),oP=wt(),uP=qi(),lP=Gi(),cP=eg();sP({target:"Array",proto:!0},{flatMap:function(e){var t=uP(this),i=lP(t),r;return oP(e),r=cP(t,0),r.length=nP(r,t,t,i,0,1,e,arguments.length>1?arguments[1]:void 0),r}})});var ig=g(()=>{"use strict";var dP=qr();dP("flatMap")});var ag=g((rV,rg)=>{"use strict";tg();ig();var pP=Jt();rg.exports=pP("Array","flatMap")});var ng=g((aV,sg)=>{"use strict";var hP=ag();sg.exports=hP});var da=g((sV,og)=>{"use strict";var fP=ng();og.exports=fP});var pa=g((nV,ug)=>{"use strict";var mP=Hr(),bP=String;ug.exports=function(a){if(mP(a)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return bP(a)}});var ml=g((oV,lg)=>{"use strict";lg.exports=`
7
- \v\f\r                 \u2028\u2029\uFEFF`});var pg=g((uV,dg)=>{"use strict";var gP=ke(),SP=Xt(),vP=pa(),gl=ml(),cg=gP("".replace),yP=RegExp("^["+gl+"]+"),TP=RegExp("(^|[^"+gl+"])["+gl+"]+$"),bl=function(a){return function(e){var t=vP(SP(e));return a&1&&(t=cg(t,yP,"")),a&2&&(t=cg(t,TP,"$1")),t}};dg.exports={start:bl(1),end:bl(2),trim:bl(3)}});var bg=g((lV,mg)=>{"use strict";var IP=Go().PROPER,EP=we(),hg=ml(),fg="​…᠎";mg.exports=function(a){return EP(function(){return!!hg[a]()||fg[a]()!==fg||IP&&hg[a].name!==a})}});var Sl=g((cV,gg)=>{"use strict";var xP=pg().start,wP=bg();gg.exports=wP("trimStart")?function(){return xP(this)}:"".trimStart});var vg=g(()=>{"use strict";var kP=Te(),Sg=Sl();kP({target:"String",proto:!0,name:"trimStart",forced:"".trimLeft!==Sg},{trimLeft:Sg})});var Tg=g(()=>{"use strict";vg();var AP=Te(),yg=Sl();AP({target:"String",proto:!0,name:"trimStart",forced:"".trimStart!==yg},{trimStart:yg})});var Eg=g((mV,Ig)=>{"use strict";Tg();var PP=Jt();Ig.exports=PP("String","trimLeft")});var wg=g((bV,xg)=>{"use strict";var RP=Eg();xg.exports=RP});var Ag=g((gV,kg)=>{"use strict";var $P=wg();kg.exports=$P});var Ug=g(()=>{"use strict"});var Hg=g(()=>{"use strict"});var Wg=g((JO,jg)=>{"use strict";var KP=qe(),XP=hi(),JP=Le(),ZP=JP("match");jg.exports=function(a){var e;return KP(a)&&((e=a[ZP])!==void 0?!!e:XP(a)==="RegExp")}});var zg=g((ZO,Gg)=>{"use strict";var eR=Se(),tR=we(),Qg=eR.RegExp,iR=!tR(function(){var a=!0;try{Qg(".","d")}catch{a=!1}var e={},t="",i=a?"dgimsy":"gimsy",r=function(o,l){Object.defineProperty(e,o,{get:function(){return t+=l,!0}})},s={dotAll:"s",global:"g",ignoreCase:"i",multiline:"m",sticky:"y"};a&&(s.hasIndices="d");for(var n in s)r(n,s[n]);var u=Object.getOwnPropertyDescriptor(Qg.prototype,"flags").get.call(e);return u!==i||t!==i});Gg.exports={correct:iR}});var Kg=g((eF,Yg)=>{"use strict";var rR=kt();Yg.exports=function(){var a=rR(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 Zg=g((tF,Jg)=>{"use strict";var aR=Xe(),sR=mt(),nR=Cr(),Xg=zg(),oR=Kg(),uR=RegExp.prototype;Jg.exports=Xg.correct?function(a){return a.flags}:function(a){return!Xg.correct&&nR(uR,a)&&!sR(a,"flags")?aR(oR,a):a.flags}});var tS=g((iF,eS)=>{"use strict";var Il=ke(),lR=qi(),cR=Math.floor,yl=Il("".charAt),dR=Il("".replace),Tl=Il("".slice),pR=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,hR=/\$([$&'`]|\d{1,2})/g;eS.exports=function(a,e,t,i,r,s){var n=t+a.length,u=i.length,o=hR;return r!==void 0&&(r=lR(r),o=pR),dR(s,o,function(l,p){var c;switch(yl(p,0)){case"$":return"$";case"&":return a;case"`":return Tl(e,0,t);case"'":return Tl(e,n);case"<":c=r[Tl(p,1,-1)];break;default:var d=+p;if(d===0)return l;if(d>u){var h=cR(d/10);return h===0?l:h<=u?i[h-1]===void 0?yl(p,1):i[h-1]+yl(p,1):l}c=i[d-1]}return c===void 0?"":c})}});var aS=g(()=>{"use strict";var fR=Te(),mR=Xe(),xl=ke(),iS=Xt(),bR=ve(),gR=qe(),SR=Wg(),mr=pa(),vR=Vr(),yR=Zg(),TR=tS(),IR=Le(),ER=ft(),xR=IR("replace"),wR=TypeError,El=xl("".indexOf),kR=xl("".replace),rS=xl("".slice),AR=Math.max;fR({target:"String",proto:!0},{replaceAll:function(e,t){var i=iS(this),r,s,n,u,o,l,p,c,d,h,m=0,b="";if(gR(e)){if(r=SR(e),r&&(s=mr(iS(yR(e))),!~El(s,"g")))throw new wR("`.replaceAll` does not allow non-global regexes");if(n=vR(e,xR),n)return mR(n,e,i,t);if(ER&&r)return kR(mr(i),e,t)}for(u=mr(i),o=mr(e),l=bR(t),l||(t=mr(t)),p=o.length,c=AR(1,p),d=El(u,o);d!==-1;)h=l?mr(t(o,d,u)):TR(o,u,d,[],void 0,t),b+=rS(u,m,d)+h,m=d+p,d=d+c>u.length?-1:El(u,o,d+c);return m<u.length&&(b+=rS(u,m)),b}})});var nS=g((sF,sS)=>{"use strict";Ug();Hg();aS();var PR=Jt();sS.exports=PR("String","replaceAll")});var uS=g((nF,oS)=>{"use strict";var RR=nS();oS.exports=RR});var cS=g((oF,lS)=>{"use strict";var $R=uS();lS.exports=$R});var pS=g((uF,dS)=>{"use strict";var LR=Nr(),MR=pa(),DR=Xt(),CR=RangeError;dS.exports=function(e){var t=MR(DR(this)),i="",r=LR(e);if(r<0||r===1/0)throw new CR("Wrong number of repetitions");for(;r>0;(r>>>=1)&&(t+=t))r&1&&(i+=t);return i}});var gS=g((lF,bS)=>{"use strict";var mS=ke(),BR=Bo(),hS=pa(),VR=pS(),_R=Xt(),OR=mS(VR),FR=mS("".slice),NR=Math.ceil,fS=function(a){return function(e,t,i){var r=hS(_R(e)),s=BR(t),n=r.length,u=i===void 0?" ":hS(i),o,l;return s<=n||u===""?r:(o=s-n,l=OR(u,NR(o/u.length)),l.length>o&&(l=FR(l,0,o)),a?r+l:l+r)}};bS.exports={start:fS(!1),end:fS(!0)}});var vS=g((cF,SS)=>{"use strict";var qR=bi();SS.exports=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(qR)});var yS=g(()=>{"use strict";var UR=Te(),HR=gS().start,jR=vS();UR({target:"String",proto:!0,forced:jR},{padStart:function(e){return HR(this,e,arguments.length>1?arguments[1]:void 0)}})});var IS=g((hF,TS)=>{"use strict";yS();var WR=Jt();TS.exports=WR("String","padStart")});var xS=g((fF,ES)=>{"use strict";var QR=IS();ES.exports=QR});var kS=g((mF,wS)=>{"use strict";var GR=xS();wS.exports=GR});var T$={};Cv(T$,{ChromecastState:()=>Pr,HttpConnectionType:()=>fs,Observable:()=>Ct.Observable,PlaybackState:()=>_e,Player:()=>as,PredefinedQualityLimits:()=>Rr,SDK_VERSION:()=>y$,Subject:()=>Ct.Subject,Subscription:()=>Ct.Subscription,Surface:()=>ms,VERSION:()=>ro,ValueSubject:()=>Ct.ValueSubject,VideoFormat:()=>xt,VideoQuality:()=>Ct.VideoQuality,areValidLiveRecordSources:()=>sb,clientChecker:()=>j,isMobile:()=>ar});module.exports=Bv(T$);var ro="2.0.145";var _e=(r=>(r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused",r))(_e||{}),xt=(x=>(x.MPEG="MPEG",x.DASH="DASH",x.DASH_SEP="DASH_SEP",x.DASH_SEP_VK="DASH_SEP",x.DASH_WEBM="DASH_WEBM",x.DASH_WEBM_AV1="DASH_WEBM_AV1",x.DASH_STREAMS="DASH_STREAMS",x.DASH_WEBM_VK="DASH_WEBM",x.DASH_ONDEMAND="DASH_ONDEMAND",x.DASH_ONDEMAND_VK="DASH_ONDEMAND",x.DASH_LIVE="DASH_LIVE",x.DASH_LIVE_CMAF="DASH_LIVE_CMAF",x.DASH_LIVE_WEBM="DASH_LIVE_WEBM",x.HLS="HLS",x.HLS_ONDEMAND="HLS_ONDEMAND",x.HLS_JS="HLS",x.HLS_FMP4="HLS_FMP4",x.HLS_LIVE="HLS_LIVE",x.HLS_LIVE_CMAF="HLS_LIVE_CMAF",x.WEB_RTC_LIVE="WEB_RTC_LIVE",x))(xt||{});var Pr=(r=>(r.NOT_AVAILABLE="NOT_AVAILABLE",r.AVAILABLE="AVAILABLE",r.CONNECTING="CONNECTING",r.CONNECTED="CONNECTED",r))(Pr||{}),fs=(i=>(i.HTTP1="http1",i.HTTP2="http2",i.QUIC="quic",i))(fs||{});var ms=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(ms||{}),Rr=(i=>(i.TRAFFIC_SAVING="traffic_saving",i.HIGH_QUALITY="high_quality",i.UNKNOWN="unknown",i))(Rr||{});var ec=Q(Si(),1),xv=Q(Oe(),1);var J=require("@vkontakte/videoplayer-shared");var Sp=a=>new Promise((e,t)=>{let i=document.createElement("script");i.setAttribute("src",a),i.onload=()=>e(),i.onerror=r=>t(r),document.body.appendChild(i)});var Es=class{constructor(e){this.connection$=new J.ValueSubject(void 0);this.castState$=new J.ValueSubject("NOT_AVAILABLE");this.errorEvent$=new J.Subject;this.realCastState$=new J.ValueSubject("NOT_AVAILABLE");this.subscription=new J.Subscription;this.isDestroyed=!1;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 i=(0,J.isNonNullable)(window.chrome?.cast),r=!!window.__onGCastApiAvailable;i?this.initializeCastApi():(window.__onGCastApiAvailable=s=>{delete window.__onGCastApiAvailable,s&&!this.isDestroyed&&this.initializeCastApi()},r||Sp("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:J.ErrorCategory.NETWORK,message:"Script loading failed!"})))}connect(){cast.framework.CastContext.getInstance()?.requestSession()}disconnect(){cast.framework.CastContext.getInstance()?.getCurrentSession()?.endSession(!0)}stopMedia(){return new Promise((e,t)=>{cast.framework.CastContext.getInstance()?.getCurrentSession()?.getMediaSession()?.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){(0,J.isNonNullable)(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();(0,J.isNullable)(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();(0,J.isNullable)(t)||e!==t.remotePlayer.isMuted&&t.remotePlayerController.muteOrUnmute()}destroy(){this.isDestroyed=!0,this.subscription.unsubscribe()}initListeners(){let e=new cast.framework.RemotePlayer,t=new cast.framework.RemotePlayerController(e),i=cast.framework.CastContext.getInstance();this.subscription.add((0,J.fromEvent)(i,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(r=>{switch(r.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=i.getCurrentSession()?.getMediaSession()?.media?.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return(0,J.assertNever)(r.sessionState)}})).add((0,J.merge)((0,J.fromEvent)(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe((0,J.tap)(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),(0,J.map)(r=>r.castState)),(0,J.observableFrom)([i.getCastState()])).pipe((0,J.filterChanged)(),(0,J.map)($I),(0,J.tap)(r=>{this.log({message:`realCastState$: ${r}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{let s=r==="CONNECTED",n=(0,J.isNonNullable)(this.connection$.getValue());if(s&&!n){let u=i.getCurrentSession();(0,J.assertNonNullable)(u);let o=u.getCastDevice(),l=u.getMediaSession()?.media?.contentId;((0,J.isNullable)(l)||l===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:u,castDevice:o}))}else!s&&n&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(r==="CONNECTED"?(0,J.isNonNullable)(this.connection$.getValue())?"CONNECTED":"AVAILABLE":r)}))}initializeCastApi(){let e,t,i;try{e=cast.framework.CastContext.getInstance(),t=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,i=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch{return}try{e.setOptions({receiverApplicationId:this.params.receiverApplicationId??t,autoJoinPolicy:i}),this.initListeners()}catch(r){this.errorEvent$.next({id:"ChromecastInitializer",category:J.ErrorCategory.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:r})}}},$I=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(0,J.assertNever)(a)}};var Xl=Q(Oe(),1),dv=Q(zi(),1),pv=Q(uu(),1);var ob=Q(zs(),1);var zu=require("@vkontakte/videoplayer-shared");var ye=(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 i=new URL(a);return i.searchParams.append("playback_shift",e.toFixed(0)),i.toString()}case 2:{let i=new URL(a);return!i.searchParams.get("offset_p")&&e===0?a:(i.searchParams.set("offset_p",e.toFixed(0)),i.toString())}default:(0,zu.assertNever)(t)}return a},ei=(a,e)=>{switch(e){case 0:return NaN;case 1:{let t=new URL(a);return Number(t.searchParams.get("playback_shift"))}case 2:{let t=new URL(a);return Number(t.searchParams.get("offset_p")??0)}default:(0,zu.assertNever)(e)}};var B=(a,e,t=!1)=>{let i=a.getTransition();(t||!i||i.to===e)&&a.setState(e)};var At=require("@vkontakte/videoplayer-shared"),Z=class{constructor(e){this.transitionStarted$=new At.Subject;this.transitionEnded$=new At.Subject;this.transitionUpdated$=new At.Subject;this.forceChanged$=new At.Subject;this.stateChangeStarted$=(0,At.merge)(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=(0,At.merge)(this.transitionEnded$,this.forceChanged$);this.state=e,this.prevState=void 0}setState(e){let t=this.transition,i=this.state;this.transition=void 0,this.prevState=i,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:i,to:e,canceledTransition:t})}startTransitionTo(e){let t=this.transition,i=this.state;i===e||(0,At.isNonNullable)(t)&&t.to===e||(this.prevState=i,this.state=e,t?(this.transition={from:t.from,to:e,canceledTransition:t},this.transitionUpdated$.next(this.transition)):(this.transition={from:i,to:e},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}getPrevState(){return this.prevState}};var Ku=require("@vkontakte/videoplayer-shared");var Xm=Q(Oe(),1);var Ys=class{constructor(){this._isMiuiBrowser=!1}get current(){return this._current}get isChrome(){return this.current==="Chrome"}get isChromiumBased(){return(0,Xm.default)(["Chrome","Chromium","Opera","Yandex","Edge","SamsungBrowser"],this.current)}get isFirefox(){return this.current==="Firefox"}get isSafari(){return this.current==="Safari"}get isOpera(){return this.current==="Opera"}get isEdge(){return this.current==="Edge"}get isYandex(){return this.current==="Yandex"}get isSamsungBrowser(){return this.current==="SamsungBrowser"}get currentVersion(){return this._current_version}get chromeVersion(){return this._chromeVersion}get firefoxVersion(){return this._firefoxVersion}get safariVersion(){return this._safariVersion}get operaVersion(){return this._operaVersion}get edgeVersion(){return this._edgeVersion}get yandexVersion(){return this._yandexVersion}get isMiuiBrowser(){return this._isMiuiBrowser}detect(){let{userAgent:e}=navigator;try{let t=/yabrowser/i.test(e)?"Yandex":void 0,i=/samsungbrowser/i.test(e)?"SamsungBrowser":void 0,r=/chrome|crios/i.test(e)?"Chrome":void 0,s=/chromium/i.test(e)?"Chromium":void 0,n=/firefox|fxios/i.test(e)?"Firefox":void 0,u=/webkit|safari|khtml/i.test(e)?"Safari":void 0,o=/opr\//i.test(e)?"Opera":void 0,l=/edg/i.test(e)?"Edge":void 0;this._isMiuiBrowser=/(XiaoMi)|(MiuiBrowser)/i.test(e),this._current=t||i||n||o||l||r||s||u||"Rest"}catch(t){console.error(t)}this.isChrome&&this.detectChromeVersion(),this.isFirefox&&this.detectFirefoxVersion(),this.isSafari&&this.detectSafariVersion(),this.isOpera&&this.detectOperaVersion(),this.isEdge&&this.detectEdgeVersion(),this.isYandex&&this.detectYandexVersion()}detectVersion(e){try{let{userAgent:t}=window.navigator,i=t.match(e);if(!i)return;let r=i[1],s=parseInt(r,10);if(!isNaN(s))return this._current_version=s,s}catch(t){console.error(t)}}detectChromeVersion(){this._chromeVersion=this.detectVersion(/Chrome\/(\d+\.\d+)/)}detectFirefoxVersion(){this._firefoxVersion=this.detectVersion(/Firefox\/(\d+\.\d+)/)}detectSafariVersion(){this._safariVersion=this.detectVersion(/Version\/(\d+)/)}detectOperaVersion(){this._operaVersion=this.detectVersion(/OPR\/(\d+\.\d+)/)}detectEdgeVersion(){this._edgeVersion=this.detectVersion(/Edg\/(\d+\.\d+)/)}detectYandexVersion(){this._yandexVersion=this.detectVersion(/YaBrowser\/(\d+\.\d+\.\d+)/)}};var Jm=Q(Oe(),1);var ar=()=>/Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test(navigator.appVersion??navigator.userAgent)||navigator?.userAgentData?.mobile;var Ks=class{constructor(e){this._highEntropyValues={};this._displayChecker=e}get current(){return this._current}get isIOS(){let e=["iPhone","iPad","iPod"];return this._highEntropyValues.platform==="iOS"||(0,Jm.default)(e,this.current)}get isMac(){return this._highEntropyValues.platform==="macOS"||this.current==="Mac"}get isApple(){return this.isIOS||this.isMac}get isIphoneOrOldIpad(){if(!this.isApple||!this._displayChecker.isTouch)return!1;let e=this.current==="iPad"||this._displayChecker.width>700,t=this._iosVersion;return!e||e&&!!t&&t<16}get isAndroid(){return this._highEntropyValues.platform==="Android"||this.current==="Android"}get isMobile(){return this._highEntropyValues.mobile||this._isMobile}get iOSVersion(){return this._iosVersion}detect(){let{userAgent:e}=navigator;try{this._isMobile=ar()}catch(t){console.error(t)}this.detectDevice(e),this.detectHighEntropyValues(),this.isIOS&&this.detectIOSVersion()}async detectHighEntropyValues(){let{userAgentData:e}=navigator;if(e?.getHighEntropyValues){let t=await e.getHighEntropyValues(["architecture","bitness","brands","mobile","platform","formFactor","model","platformVersion","wow64"]);this._highEntropyValues=t}}detectDevice(e){try{let t=/android/i.test(e)?"Android":void 0,i=/iphone/i.test(e)?"iPhone":void 0,r=/ipad/i.test(e)?"iPad":void 0,s=/ipod/i.test(e)?"iPod":void 0,n=/mac/i.test(e)?"Mac":void 0,u=/webOS|BlackBerry|IEMobile|Opera Mini/i.test(e)?"RestMobile":void 0;this._current=t||i||r||s||u||n||"Desktop"}catch(t){console.error(t)}}detectIOSVersion(){try{if(this._highEntropyValues.platformVersion){let s=this._highEntropyValues.platformVersion.split(".").slice(0,2).join("."),n=parseFloat(s);this._iosVersion=n;return}let{userAgent:e}=window.navigator,t=e.match(/OS (\d+(_\d+)?)/i);if(!t)return;let i=t[1].replace(/_/g,".");if(!i)return;let r=parseFloat(i);if(isNaN(r))return;this._iosVersion=r}catch(e){console.error(e)}}};var Xs=class{get isTouch(){return typeof this._maxTouchPoints=="number"?this._maxTouchPoints>1:"ontouchstart"in window}get maxTouchPoints(){return this._maxTouchPoints}get height(){return this._height}get width(){return this._width}get screenHeight(){return this._screenHeight}get screenWidth(){return this._screenWidth}get pixelRatio(){return this._pixelRatio}get isHDR(){return this._isHdr}get colorDepth(){return this._colorDepth}detect(){let{maxTouchPoints:e}=navigator;try{this._maxTouchPoints=e??0,this._isHdr=!!matchMedia("(dynamic-range: high)")?.matches,this._colorDepth=screen.colorDepth}catch(t){console.error(t)}try{this._pixelRatio=window.devicePixelRatio||1,this._height=screen.height,this._width=screen.width,this._height=screen.height,this._screenHeight=this._height*this._pixelRatio,this._screenWidth=this._width*this._pixelRatio}catch(t){console.error(t)}}};var Ze=()=>window.ManagedMediaSource||window.MediaSource,sr=()=>!!(window.ManagedMediaSource&&window.ManagedSourceBuffer?.prototype?.appendBuffer),Zm=()=>!!(window.MediaSource&&window.SourceBuffer?.prototype?.appendBuffer),Js=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;var bA=document.createElement("video"),gA='video/mp4; codecs="avc1.42000a,mp4a.40.2"',SA='video/mp4; codecs="hev1.1.6.L93.B0"',eb='video/webm; codecs="vp09.00.10.08"',tb='video/webm; codecs="av01.0.00M.08"',vA='audio/mp4; codecs="mp4a.40.2"',yA='audio/webm; codecs="opus"',ib,TA=async()=>{if(!window.navigator.mediaCapabilities)return;let a={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=await Promise.all([window.navigator.mediaCapabilities.decodingInfo({...a,video:{...a.video,contentType:tb}}),window.navigator.mediaCapabilities.decodingInfo({...a,video:{...a.video,contentType:eb}})]);ib={DASH_WEBM_AV1:e,DASH_WEBM:t}};TA().catch(a=>{console.log(bA),console.error(a)});var Zs=class{constructor(e,t){this._deviceChecker=e,this._browserChecker=t}get protocols(){return this._protocols}get containers(){return this._containers}get codecs(){return this._codecs}get webmDecodingInfo(){return ib}get supportedCodecs(){return Object.keys(this._codecs).filter(e=>this._codecs[e])}get nativeHlsSupported(){return this._nativeHlsSupported}detect(){this._video=document.createElement("video");try{this._protocols={mms:sr(),mse:Zm(),hls:!!(this._video.canPlayType?.("application/x-mpegurl")||this._video.canPlayType?.("vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},this._containers={mp4:!!this._video.canPlayType?.("video/mp4"),webm:!!this._video.canPlayType?.("video/webm"),cmaf:!0};let e=!!Ze()?.isTypeSupported?.(gA),t=!!Ze()?.isTypeSupported?.(SA),i=!!Ze()?.isTypeSupported?.(vA);this._codecs={h264:e,h265:t,vp9:!!Ze()?.isTypeSupported?.(eb),av1:!!Ze()?.isTypeSupported?.(tb),aac:i,opus:!!Ze()?.isTypeSupported?.(yA),mpeg:(e||t)&&i},this._nativeHlsSupported=this._protocols.hls&&this._containers.mp4}catch(e){console.error(e)}try{this.destroyVideoElement()}catch(e){console.error("Error destroying video element:",e)}}destroyVideoElement(){if(!this._video)return;if(this._video.pause(),this._video.currentTime=0,this._video.removeAttribute("src"),this._video.src="",this._video.load(),this._video.remove){this._video.remove(),this._video=null;return}this._video.parentNode&&this._video.parentNode.removeChild(this._video);let e=this._video.cloneNode(!1);this._video.parentNode?.replaceChild(e,this._video),this._video=null}};var rb="audio/mpeg",en=class{supportMp3(){return this._codecs.mp3&&this._containers.mpeg}detect(){this._audio=document.createElement("audio");try{this._containers={mpeg:!!this._audio.canPlayType?.(rb)},this._codecs={mp3:!!Ze()?.isTypeSupported?.(rb)}}catch(e){console.error(e)}try{this.destroyAudioElement()}catch(e){console.error("Error destroying audio element:",e)}}destroyAudioElement(){if(!this._audio)return;if(this._audio.pause(),this._audio.currentTime=0,this._audio.removeAttribute("src"),this._audio.src="",this._audio.load(),this._audio.remove){this._audio.remove(),this._audio=null;return}this._audio.parentNode&&this._audio.parentNode.removeChild(this._audio);let e=this._audio.cloneNode(!1);this._audio.parentNode?.replaceChild(e,this._audio),this._audio=null}};var ab=require("@vkontakte/videoplayer-shared"),Yu=class{constructor(){this.isInited$=new ab.ValueSubject(!1);this._displayChecker=new Xs,this._deviceChecker=new Ks(this._displayChecker),this._browserChecker=new Ys,this._videoChecker=new Zs(this._deviceChecker,this._browserChecker),this._audioChecker=new en,this.detect()}get display(){return this._displayChecker}get device(){return this._deviceChecker}get browser(){return this._browserChecker}get video(){return this._videoChecker}get audio(){return this._audioChecker}async detect(){this._displayChecker.detect(),this._deviceChecker.detect(),this._browserChecker.detect(),this._videoChecker.detect(),this._audioChecker.detect(),this.isInited$.next(!0)}},j=new Yu;var Xu=a=>{let{containers:e,protocols:t,codecs:i,nativeHlsSupported:r}=j.video,s=(i.h264||i.h265)&&i.aac,n=t.mse||t.mms;return a.filter(u=>{switch(u){case"DASH_SEP":return n&&e.mp4&&s;case"DASH_WEBM":return n&&e.webm&&i.vp9&&i.opus;case"DASH_WEBM_AV1":return n&&e.webm&&i.av1&&i.opus;case"DASH_STREAMS":return n&&(e.mp4&&s||e.webm&&(i.vp9||i.av1)&&(i.opus||i.aac));case"DASH_LIVE":return n&&e.mp4&&s;case"DASH_LIVE_CMAF":return n&&e.mp4&&s&&e.cmaf;case"DASH_ONDEMAND":return n&&e.mp4&&s;case"HLS":case"HLS_ONDEMAND":case"HLS_FMP4":case"HLS_LIVE":case"HLS_LIVE_CMAF":return r;case"MPEG":return e.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return t.webrtc&&t.ws&&i.h264&&(e.mp4||e.webm);default:return(0,Ku.assertNever)(u)}})},Ju=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_FMP4":case"HLS_ONDEMAND":return!1;case"DASH_LIVE":case"DASH_LIVE_CMAF":case"HLS_LIVE":case"HLS_LIVE_CMAF":case"DASH_LIVE_WEBM":case"WEB_RTC_LIVE":return!0;default:return(0,Ku.assertNever)(a)}},sb=a=>{let t=Object.keys(a).filter(i=>!Ju(i));return Xu(t).length>0};var q=require("@vkontakte/videoplayer-shared");var IA=5,EA=5,xA=500,nb=7e3,ea=class{constructor(e){this.subscription=new q.Subscription;this.loadMediaTimeoutSubscription=new q.Subscription;this.videoState=new Z("stopped");this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(s)};`}),i==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.stop());return}if(!t){if(r?.to!=="paused"&&s.state==="requested"&&e!=="stopped"){this.seek(s.position/1e3);return}switch(i){case"ready":{switch(e){case"playing":case"paused":case"ready":break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:(0,q.assertNever)(e)}break}case"playing":{switch(e){case"playing":break;case"paused":this.videoState.startTransitionTo("playing"),this.params.connection.remotePlayerController.playOrPause();break;case"ready":this.videoState.startTransitionTo("playing"),this.params.connection.remotePlayerController.playOrPause();break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:(0,q.assertNever)(e)}break}case"paused":{switch(e){case"playing":this.videoState.startTransitionTo("paused"),this.params.connection.remotePlayerController.playOrPause();break;case"paused":break;case"ready":this.videoState.startTransitionTo("paused"),this.videoState.setState("paused");break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:(0,q.assertNever)(e)}break}default:(0,q.assertNever)(i)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(Ju(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 q.Subscription;this.subscription.add(e),this.subscription.add((0,q.merge)(this.videoState.stateChangeStarted$.pipe((0,q.map)(r=>`stateChangeStarted$ ${JSON.stringify(r)}`)),this.videoState.stateChangeEnded$.pipe((0,q.map)(r=>`stateChangeEnded$ ${JSON.stringify(r)}`))).subscribe(r=>this.log({message:`[videoState] ${r}`})));let t=(r,s)=>this.subscription.add(r.subscribe(s));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{let r=new q.Subject;e.add(r.pipe((0,q.debounce)(xA)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add((0,q.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe(n=>{this.logRemoteEvent(n);let u=n.value;this.params.output.position$.next(u),(this.params.desiredState.seekState.getState().state==="applying"||Math.abs(u-s)>IA)&&r.next(u),s=u})),e.add((0,q.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t((0,q.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t((0,q.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemotePause():this.handleRemotePlay()}),t((0,q.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),r=>{this.logRemoteEvent(r);let{remotePlayer:s}=this.params.connection,n=r.value,u=this.params.output.isBuffering$.getValue(),o=n===chrome.cast.media.PlayerState.BUFFERING;switch(u!==o&&this.params.output.isBuffering$.next(o),n){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&s.duration-s.currentTime<EA&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),B(this.params.desiredState.playbackState,"stopped");break;case chrome.cast.media.PlayerState.PAUSED:{this.handleRemotePause();break}case chrome.cast.media.PlayerState.PLAYING:this.handleRemotePlay();break;case chrome.cast.media.PlayerState.BUFFERING:break;default:(0,q.assertNever)(n)}}),t((0,q.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t((0,q.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({muted:r.value})});let i=(0,q.merge)(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,q.observableFrom)(["init"])).pipe((0,q.debounce)(0));t(i,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"),B(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),B(this.params.desiredState.playbackState,"playing"));let i=this.params.output.isLive$.getValue();this.params.output.duration$.next(i?0:t.duration),this.params.output.position$.next(i?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),i=this.createLoadRequest(t);this.loadMedia(i)}handleRemotePause(){let e=this.videoState.getState();(this.videoState.getTransition()?.to==="paused"||e==="playing")&&(this.videoState.setState("paused"),B(this.params.desiredState.playbackState,"paused"))}handleRemotePlay(){let e=this.videoState.getState();(this.videoState.getTransition()?.to==="playing"||e==="paused")&&(this.videoState.setState("playing"),B(this.params.desiredState.playbackState,"playing"))}handleRemoteReady(){this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.params.desiredState.playbackState.getTransition()?.to==="ready"&&B(this.params.desiredState.playbackState,"ready")}handleRemoteStop(){this.videoState.getState()!=="stopped"&&this.videoState.setState("stopped")}handleRemoteVolumeChange(e){let t=this.params.output.volume$.getValue(),i={volume:e.volume??t.volume,muted:e.muted??t.muted};(i.volume!==t.volume||i.muted!==i.muted)&&this.params.output.volume$.next(i)}seek(e){this.params.output.willSeekEvent$.next();let{remotePlayer:t,remotePlayerController:i}=this.params.connection;t.currentTime=e,i.seek()}stop(){let{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){let t=this.params.source,i,r,s;switch(e){case"MPEG":{let l=t[e];(0,q.assertNonNullable)(l);let p=(0,q.getHighestQuality)(Object.keys(l));(0,q.assertNonNullable)(p);let c=l[p];(0,q.assertNonNullable)(c),i=c,r="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_FMP4":case"HLS_ONDEMAND":{let l=t[e];(0,q.assertNonNullable)(l),i=l.url,r="application/x-mpegurl",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":{let l=t[e];(0,q.assertNonNullable)(l),i=l.url,r="application/dash+xml",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let l=t[e];(0,q.assertNonNullable)(l),i=l.url,r="application/dash+xml",s=chrome.cast.media.StreamType.LIVE;break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let l=t[e];(0,q.assertNonNullable)(l),i=ye(l.url),r="application/x-mpegurl",s=chrome.cast.media.StreamType.LIVE;break}case"DASH_LIVE":case"WEB_RTC_LIVE":{let l="Unsupported format for Chromecast",p=new Error(l);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:q.ErrorCategory.VIDEO_PIPELINE,message:l,thrown:p}),p}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return(0,q.assertNever)(e)}let n=new chrome.cast.media.MediaInfo(this.params.meta.videoId??i,r);n.contentUrl=i,n.streamType=s,n.metadata=new chrome.cast.media.GenericMediaMetadata;let{title:u,subtitle:o}=this.params.meta;return(0,q.isNonNullable)(u)&&(n.metadata.title=u),(0,q.isNonNullable)(o)&&(n.metadata.subtitle=o),n}createLoadRequest(e){let t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;let i=this.params.desiredState.seekState.getState();return i.state==="applying"||i.state==="requested"?t.currentTime=this.params.output.isLive$.getValue()?0:i.position/1e3:t.currentTime=0,t}loadMedia(e){let t=this.params.connection.session.loadMedia(e),i=new Promise((r,s)=>{this.loadMediaTimeoutSubscription.add((0,q.timeout)(nb).subscribe(()=>s(`timeout(${nb})`)))});(0,ob.default)(Promise.race([t,i]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},r=>{let s=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${r}`;this.log({message:s}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:q.ErrorCategory.VIDEO_PIPELINE,message:s,thrown:r})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var pl=Q(Oe(),1);var il=require("@vkontakte/videoplayer-shared");var ub=require("@vkontakte/videoplayer-shared"),lb=a=>{try{a.pause(),a.playbackRate=0,(0,ub.clearVideoElement)(a),a.remove()}catch(e){console.error(e)}};var tn=require("@vkontakte/videoplayer-shared"),Zu=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)}},el=window.WeakMap?new WeakMap:new Zu,tl=window.WeakMap?new WeakMap:new Map,wA=(a,e=20)=>{let t=0;return(0,tn.fromEvent)(a,"ratechange").subscribe(i=>{t++,t>=e&&(a.currentTime=a.currentTime,t=0)})},Ue=(a,{audioVideoSyncRate:e,disableYandexPiP:t})=>{let i=a.querySelector("video"),r=!!i;i?(0,il.clearVideoElement)(i):(i=document.createElement("video"),a.appendChild(i)),el.set(i,r);let s=new tn.Subscription;return s.add(wA(i,e)),tl.set(i,s),i.setAttribute("crossorigin","anonymous"),i.setAttribute("playsinline","playsinline"),t&&i.setAttribute("x-yandex-pip","false"),i.controls=!1,i.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),i},He=a=>{tl.get(a)?.unsubscribe(),tl.delete(a);let t=el.get(a);el.delete(a),t?(0,il.clearVideoElement)(a):lb(a)};var rl=Q(Si(),1),U=require("@vkontakte/videoplayer-shared");var ti=require("@vkontakte/videoplayer-shared"),rn=(a,e,t,{equal:i=(n,u)=>n===u,changed$:r,onError:s}={})=>{let n=a.getState(),u=e(),o=(0,ti.isNullable)(r),l=new ti.Subscription;return r&&l.add(r.subscribe(p=>{let c=a.getState();i(p,c)&&a.setState(p)},s)),i(u,n)||(t(n),o&&a.setState(n)),l.add(a.stateChangeStarted$.subscribe(p=>{t(p.to),o&&a.setState(p.to)},s)),l},Pt=(a,e,t)=>rn(e,()=>a.loop,i=>{(0,ti.isNonNullable)(i)&&(a.loop=i)},{onError:t}),je=(a,e,t,i)=>rn(e,()=>({muted:a.muted,volume:a.volume}),r=>{(0,ti.isNonNullable)(r)&&(a.muted=r.muted,a.volume=r.volume)},{equal:(r,s)=>r===s||r?.muted===s?.muted&&r?.volume===s?.volume,changed$:t,onError:i}),nt=(a,e,t,i)=>rn(e,()=>a.playbackRate,r=>{(0,ti.isNonNullable)(r)&&(a.playbackRate=r)},{changed$:t,onError:i}),ta=rn;var kA=a=>["__",a.language,a.label].join("|"),AA=(a,e)=>{if(a.id===e)return!0;let[t,i,r]=e.split("|");return a.language===i&&a.label===r},al=class a{constructor(e){this.available$=new U.Subject;this.current$=new U.ValueSubject(void 0);this.error$=new U.Subject;this.subscription=new U.Subscription;this.externalTracks=new Map;this.internalTracks=new Map;this.baseURL=e}connect(e,t,i){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();let r=s=>{this.error$.next({id:"TextTracksManager",category:U.ErrorCategory.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:s})};this.subscription.add(this.available$.subscribe(i.availableTextTracks$)),this.subscription.add(this.current$.subscribe(i.currentTextTrack$)),this.subscription.add(this.error$.subscribe(i.error$)),this.subscription.add(ta(t.internalTextTracks,()=>(0,rl.default)(this.internalTracks),s=>{(0,U.isNonNullable)(s)&&this.setInternal(s)},{equal:(s,n)=>(0,U.isNonNullable)(s)&&(0,U.isNonNullable)(n)&&s.length===n.length&&s.every(({id:u},o)=>u===n[o].id),changed$:this.available$.pipe((0,U.map)(s=>s.filter(({type:n})=>n==="internal"))),onError:r})),this.subscription.add(ta(t.externalTextTracks,()=>(0,rl.default)(this.externalTracks),s=>{(0,U.isNonNullable)(s)&&this.setExternal(s)},{equal:(s,n)=>(0,U.isNonNullable)(s)&&(0,U.isNonNullable)(n)&&s.length===n.length&&s.every(({id:u},o)=>u===n[o].id),changed$:this.available$.pipe((0,U.map)(s=>s.filter(({type:n})=>n==="external"))),onError:r})),this.subscription.add(ta(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:r})),this.subscription.add(ta(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.activeCues)}))}subscribe(){(0,U.assertNonNullable)(this.video);let{textTracks:e}=this.video;this.subscription.add((0,U.fromEvent)(e,"addtrack").subscribe(()=>{let i=this.current$.getValue();i&&this.select(i)})),this.subscription.add((0,U.merge)((0,U.fromEvent)(e,"addtrack"),(0,U.fromEvent)(e,"removetrack"),(0,U.observableFrom)(["init"])).pipe((0,U.map)(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),(0,U.filterChanged)((i,r)=>i.length===r.length&&i.every(({id:s},n)=>s===r[n].id))).subscribe(this.available$)),this.subscription.add((0,U.merge)((0,U.fromEvent)(e,"change"),(0,U.observableFrom)(["init"])).pipe((0,U.map)(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),(0,U.map)(i=>i&&this.htmlTextTrackToITextTrack(i).id),(0,U.filterChanged)()).subscribe(this.current$));let t=i=>this.applyCueSettings(i.target?.activeCues??null);this.subscription.add((0,U.fromEvent)(e,"addtrack").subscribe(i=>{i.track?.addEventListener("cuechange",t);let r=s=>{let n=s.target?.cues??null;n&&n.length&&(this.applyCueSettings(s.target?.cues??null),s.target?.removeEventListener("cuechange",r))};i.track?.addEventListener("cuechange",r)})),this.subscription.add((0,U.fromEvent)(e,"removetrack").subscribe(i=>{i.track?.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;let t=this.cueSettings.getState();for(let i of Array.from(e)){let r=i;(0,U.isNonNullable)(t.align)&&(r.align=t.align),(0,U.isNonNullable)(t.position)&&(r.position=t.position),(0,U.isNonNullable)(t.size)&&(r.size=t.size),(0,U.isNonNullable)(t.line)&&(r.line=t.line)}}htmlTextTracksAsArray(e=!1){(0,U.assertNonNullable)(this.video);let t=[...this.video.textTracks];return e?t:t.filter(a.isHealthyTrack)}htmlTextTrackToITextTrack(e){let{language:t,label:i}=e,r=e.id?e.id:kA(e),s=this.externalTracks.has(r),n=(s?this.externalTracks.get(r)?.isAuto:this.internalTracks.get(r)?.isAuto)??r.includes("auto");return s?{id:r,type:"external",isAuto:n,language:t,label:i,url:this.externalTracks.get(r)?.url}:{id:r,type:"internal",isAuto:n,language:t,label:i,url:this.internalTracks.get(r)?.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(i=>i.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){let t=[...this.externalTracks];e.filter(({id:i,language:r,isAuto:s})=>!this.internalTracks.has(i)&&!t.some(([,n])=>n.language===r&&n.isAuto===s)).forEach(i=>this.attach(i)),Array.from(this.internalTracks).filter(([i])=>!e.find(r=>r.id===i)).forEach(([,i])=>this.detach(i))}select(e){(0,U.assertNonNullable)(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))((0,U.isNullable)(e)||!AA(t,e))&&(t.mode="disabled")}destroy(){if(this.subscription.unsubscribe(),this.video)for(let e of Array.from(this.video.getElementsByTagName("track"))){let t=e.getAttribute("id");t&&this.externalTracks.has(t)&&this.video.removeChild(e)}this.externalTracks.clear()}attach(e){(0,U.assertNonNullable)(this.video);let t=document.createElement("track");this.baseURL?t.setAttribute("src",new URL(e.url,this.baseURL).toString()):t.setAttribute("src",e.url),t.setAttribute("id",e.id),e.label&&t.setAttribute("label",e.label),e.language&&t.setAttribute("srclang",e.language),e.type==="external"?this.externalTracks.set(e.id,e):e.type==="internal"&&this.internalTracks.set(e.id,e),this.video.appendChild(t)}detach(e){(0,U.assertNonNullable)(this.video);let t=Array.prototype.find.call(this.video.getElementsByTagName("track"),i=>i.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)}},ot=al;var xi=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 cb=a=>{let e=a;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e?.parentNode;return e??void 0},sl=a=>{let e=cb(a);return!!(e&&e.fullscreenElement&&e.fullscreenElement===a)},db=a=>{let e=cb(a);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===a)};var $=require("@vkontakte/videoplayer-shared");var PA=3,pb=(a,e,t=PA)=>{let i=0,r=0;for(let s=0;s<a.length;s++){let n=a.start(s),u=a.end(s);if(n<=e&&e<=u){if(i=n,r=u,!t)return{from:i,to:r};for(let o=s-1;o>=0;o--)a.end(o)+t>=i&&(i=a.start(o));for(let o=s+1;o<a.length;o++)a.start(o)-t<=r&&(r=a.end(o))}}return{from:i,to:r}};var We=a=>{let e=L=>(0,$.fromEvent)(a,L).pipe((0,$.mapTo)(void 0),(0,$.shareReplay)(1)),t=new $.Subscription,i=()=>t.unsubscribe(),r=(0,$.merge)((0,$.fromEvent)(a,"progress"),(0,$.fromEvent)(a,"timeupdate")).pipe((0,$.map)(()=>pb(a.buffered,a.currentTime)),(0,$.shareReplay)(1)),s=j.browser.isSafari?(0,$.combine)({play:e("play").pipe((0,$.once)()),playing:e("playing")}).pipe((0,$.mapTo)(void 0),(0,$.shareReplay)(1)):e("playing"),n=(0,$.fromEvent)(a,"volumechange").pipe((0,$.map)(()=>({muted:a.muted,volume:a.volume})),(0,$.shareReplay)(1)),u=(0,$.fromEvent)(a,"ratechange").pipe((0,$.map)(()=>a.playbackRate),(0,$.shareReplay)(1)),o=(0,$.fromEvent)(a,"error").pipe((0,$.filter)(()=>!!(a.error||a.played.length)),(0,$.map)(()=>{let L=a.error;return{id:L?`MediaError#${L.code}`:"HtmlVideoError",category:$.ErrorCategory.VIDEO_PIPELINE,message:L?L.message:"Error event from HTML video element",thrown:a.error??void 0}}),(0,$.shareReplay)(1)),l=(0,$.fromEvent)(a,"timeupdate").pipe((0,$.map)(()=>a.currentTime),(0,$.shareReplay)(1)),p=["waiting","seeking","seeked","timeupdate"],c=new $.Subject,d=.3,h;t.add((0,$.merge)(...p.map(L=>(0,$.fromEvent)(a,L))).subscribe(L=>{let ee=a.currentTime;a.loop&&(0,$.isNonNullable)(h)&&(0,$.isNonNullable)(ee)&&h>=a.duration-d&&ee<=d&&c.next(h),h=ee}));let m=e("pause").pipe((0,$.filter)(()=>!a.error&&h!==a.duration),(0,$.shareReplay)(1)),b=(0,$.fromEvent)(a,"enterpictureinpicture").pipe((0,$.shareReplay)(1)),S=(0,$.fromEvent)(a,"leavepictureinpicture").pipe((0,$.shareReplay)(1)),v=new $.ValueSubject(db(a));t.add(b.subscribe(()=>v.next(!0))),t.add(S.subscribe(()=>v.next(!1)));let I=new $.ValueSubject(sl(a)),A=(0,$.fromEvent)(a,"fullscreenchange").pipe((0,$.shareReplay)(1));t.add(A.pipe((0,$.map)(()=>sl(a))).subscribe(I));let x=.1,C=1e3,V=(0,$.fromEvent)(a,"timeupdate").pipe((0,$.map)(L=>a.duration-a.currentTime<x),(0,$.filterChanged)(),(0,$.shareReplay)(1)),O=(0,$.merge)(V.pipe((0,$.filter)(L=>!a.loop&&L)),(0,$.fromEvent)(a,"ended")).pipe((0,$.throttle)(C),(0,$.mapTo)(void 0),(0,$.shareReplay)(1)),N=(0,$.merge)(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(L=>(0,$.fromEvent)(a,L)),V.pipe((0,$.map)(L=>({type:L?"ended":"unknown"})))).pipe((0,$.map)(L=>j.browser.isFirefox&&L.type==="ended"?a.readyState<2:a.readyState<3),(0,$.filterChanged)(),(0,$.shareReplay)(1));return{playing$:s,pause$:m,canplay$:e("canplay"),ended$:O,looped$:c,error$:o,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:l,durationChange$:(0,$.fromEvent)(a,"durationchange").pipe((0,$.map)(()=>a.duration),(0,$.shareReplay)(1)),isBuffering$:N,currentBuffer$:r,volumeState$:n,playbackRateState$:u,inPiP$:v,inFullscreen$:I,enterPip$:b,leavePip$:S,destroy:i}};var Ft=require("@vkontakte/videoplayer-shared"),ii=a=>{switch(a){case"mobile":return Ft.VideoQuality.Q_144P;case"lowest":return Ft.VideoQuality.Q_240P;case"low":return Ft.VideoQuality.Q_360P;case"sd":case"medium":return Ft.VideoQuality.Q_480P;case"hd":case"high":return Ft.VideoQuality.Q_720P;case"fullhd":case"full":return Ft.VideoQuality.Q_1080P;case"quadhd":case"quad":return Ft.VideoQuality.Q_1440P;case"ultrahd":case"ultra":return Ft.VideoQuality.Q_2160P}};var Ne=Q(gt(),1),ol=Q(Oe(),1),wi=Q(zi(),1),M=require("@vkontakte/videoplayer-shared");var nl=!1,Nt={},vb=a=>{nl=a},yb=()=>{Nt={}},Tb=a=>{a(Nt)},ia=(a,e)=>{nl&&(Nt.meta=Nt.meta??{},Nt.meta[a]=e)},Fe=class{constructor(e){this.name=e}next(e){if(!nl)return;Nt.series=Nt.series??{};let t=Nt.series[this.name]??[];t.push([Date.now(),e]),Nt.series[this.name]=t}};var Ie=require("@vkontakte/videoplayer-shared");function Ib(a,e,t){return!a.max&&a.min===e?"high_quality":!a.min&&a.max===t?"traffic_saving":"unknown"}function nr(a,e,t){return(0,Ie.isNullable)(a)||(0,Ie.isNonNullable)(a.min)&&(0,Ie.isNonNullable)(a.max)&&(0,Ie.isLower)(a.max,a.min)||(0,Ie.isNonNullable)(a.min)&&e&&(0,Ie.isHigher)(a.min,e)||(0,Ie.isNonNullable)(a.max)&&t&&(0,Ie.isLower)(a.max,t)}function Eb({limits:a,highestAvailableHeight:e,lowestAvailableHeight:t}){return nr({max:a?.max?(0,Ie.videoHeightToQuality)(a.max):void 0,min:a?.min?(0,Ie.videoHeightToQuality)(a.min):void 0},e?(0,Ie.videoHeightToQuality)(e):void 0,t?(0,Ie.videoHeightToQuality)(t):void 0)}var Pb=new Fe("best_bitrate"),sn=(a,e,t)=>(e-t)*Math.pow(2,-10*a)+t;var or=a=>(e,t)=>a*(Number(e.bitrate)-Number(t.bitrate)),ri=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=(0,M.now)()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},nn='Assertion "ABR Tracks is empty array" failed',an=new WeakMap,xb=new WeakMap,wb=new WeakMap,ra=(a,e,t,i)=>{let r=[...e].sort(or(1)),s=[...t].sort(or(1)),n=s.filter(o=>(0,M.isNonNullable)(o.bitrate)&&(0,M.isNonNullable)(a.bitrate)?a.bitrate/o.bitrate>i:!0),u=(0,Ne.default)(s,Math.round(s.length*r.indexOf(a)/(r.length+1)))??(0,Ne.default)(s,-1);return u&&(0,ol.default)(n,u)?u:n.length?(0,Ne.default)(n,-1):(0,Ne.default)(s,0)},aa=(a,e,t,i)=>{let r=an.get(e);r||(r=[...e].sort(or(1)),an.set(e,r));let s=an.get(t);s||(s=[...t].sort(or(1)),an.set(t,s));let n=wb.get(a);n||(n=s.filter(o=>(0,M.isNonNullable)(o.bitrate)&&(0,M.isNonNullable)(a.bitrate)?a.bitrate/o.bitrate>i:!0),wb.set(a,n));let u=(0,Ne.default)(s,Math.round(s.length*r.indexOf(a)/(r.length+1)))??(0,Ne.default)(s,-1);return u&&(0,ol.default)(n,u)?u:n.length?(0,Ne.default)(n,-1):(0,Ne.default)(s,0)},kb=a=>"quality"in a,on=(a,e,t,i)=>{let r=(0,M.isNonNullable)(i?.last?.bitrate)&&(0,M.isNonNullable)(t?.bitrate)&&i.last.bitrate<t.bitrate?a.trackCooldownIncreaseQuality:a.trackCooldownDecreaseQuality,s=t&&i&&i.history[t.id]&&(0,M.now)()-i.history[t.id]<=r&&(!i.last||t.id!==i.last.id);if(t?.id&&i&&!s&&i.recordSelection(t),s&&i?.last){let n=i.last;i?.recordSwitch(n);let u=kb(n)?"video":"audio",o=kb(n)?n.quality:n.bitrate;return e({message:`
6
+ "use strict";var Rv=Object.create;var hs=Object.defineProperty;var $v=Object.getOwnPropertyDescriptor;var Lv=Object.getOwnPropertyNames;var Mv=Object.getPrototypeOf,Dv=Object.prototype.hasOwnProperty;var g=(a,e)=>()=>(e||a((e={exports:{}}).exports,e),e.exports),Cv=(a,e)=>{for(var t in e)hs(a,t,{get:e[t],enumerable:!0})},ic=(a,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Lv(e))!Dv.call(a,r)&&r!==t&&hs(a,r,{get:()=>e[r],enumerable:!(i=$v(e,r))||i.enumerable});return a};var Q=(a,e,t)=>(t=a!=null?Rv(Mv(a)):{},ic(e||!a||!a.__esModule?hs(t,"default",{value:a,enumerable:!0}):t,a)),Bv=a=>ic(hs({},"__esModule",{value:!0}),a);var Se=g((ao,rc)=>{"use strict";var $r=function(a){return a&&a.Math===Math&&a};rc.exports=$r(typeof globalThis=="object"&&globalThis)||$r(typeof window=="object"&&window)||$r(typeof self=="object"&&self)||$r(typeof global=="object"&&global)||$r(typeof ao=="object"&&ao)||function(){return this}()||Function("return this")()});var we=g((w$,ac)=>{"use strict";ac.exports=function(a){try{return!!a()}catch{return!0}}});var Lr=g((A$,sc)=>{"use strict";var Vv=we();sc.exports=!Vv(function(){var a=function(){}.bind();return typeof a!="function"||a.hasOwnProperty("prototype")})});var so=g((P$,lc)=>{"use strict";var _v=Lr(),uc=Function.prototype,nc=uc.apply,oc=uc.call;lc.exports=typeof Reflect=="object"&&Reflect.apply||(_v?oc.bind(nc):function(){return oc.apply(nc,arguments)})});var Ae=g((k$,pc)=>{"use strict";var cc=Lr(),dc=Function.prototype,no=dc.call,Ov=cc&&dc.bind.bind(no,no);pc.exports=cc?Ov:function(a){return function(){return no.apply(a,arguments)}}});var hi=g((R$,fc)=>{"use strict";var hc=Ae(),Fv=hc({}.toString),Nv=hc("".slice);fc.exports=function(a){return Nv(Fv(a),8,-1)}});var oo=g(($$,mc)=>{"use strict";var qv=hi(),Uv=Ae();mc.exports=function(a){if(qv(a)==="Function")return Uv(a)}});var ve=g((L$,bc)=>{"use strict";var uo=typeof document=="object"&&document.all;bc.exports=typeof uo>"u"&&uo!==void 0?function(a){return typeof a=="function"||a===uo}:function(a){return typeof a=="function"}});var Ke=g((M$,gc)=>{"use strict";var Hv=we();gc.exports=!Hv(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var Xe=g((D$,Sc)=>{"use strict";var jv=Lr(),bs=Function.prototype.call;Sc.exports=jv?bs.bind(bs):function(){return bs.apply(bs,arguments)}});var lo=g(Tc=>{"use strict";var vc={}.propertyIsEnumerable,yc=Object.getOwnPropertyDescriptor,Wv=yc&&!vc.call({1:2},1);Tc.f=Wv?function(e){var t=yc(this,e);return!!t&&t.enumerable}:vc});var Mr=g((B$,Ic)=>{"use strict";Ic.exports=function(a,e){return{enumerable:!(a&1),configurable:!(a&2),writable:!(a&4),value:e}}});var xc=g((V$,Ec)=>{"use strict";var Qv=Ae(),Gv=we(),zv=hi(),co=Object,Yv=Qv("".split);Ec.exports=Gv(function(){return!co("z").propertyIsEnumerable(0)})?function(a){return zv(a)==="String"?Yv(a,""):co(a)}:co});var Dr=g((_$,wc)=>{"use strict";wc.exports=function(a){return a==null}});var Xt=g((O$,Ac)=>{"use strict";var Kv=Dr(),Xv=TypeError;Ac.exports=function(a){if(Kv(a))throw new Xv("Can't call method on "+a);return a}});var fi=g((F$,Pc)=>{"use strict";var Jv=xc(),Zv=Xt();Pc.exports=function(a){return Jv(Zv(a))}});var qe=g((N$,kc)=>{"use strict";var ey=ve();kc.exports=function(a){return typeof a=="object"?a!==null:ey(a)}});var mi=g((q$,Rc)=>{"use strict";Rc.exports={}});var Vt=g((U$,Lc)=>{"use strict";var po=mi(),ho=Se(),ty=ve(),$c=function(a){return ty(a)?a:void 0};Lc.exports=function(a,e){return arguments.length<2?$c(po[a])||$c(ho[a]):po[a]&&po[a][e]||ho[a]&&ho[a][e]}});var Cr=g((H$,Mc)=>{"use strict";var iy=Ae();Mc.exports=iy({}.isPrototypeOf)});var bi=g((j$,Bc)=>{"use strict";var ry=Se(),Dc=ry.navigator,Cc=Dc&&Dc.userAgent;Bc.exports=Cc?String(Cc):""});var mo=g((W$,qc)=>{"use strict";var Nc=Se(),fo=bi(),Vc=Nc.process,_c=Nc.Deno,Oc=Vc&&Vc.versions||_c&&_c.version,Fc=Oc&&Oc.v8,ht,gs;Fc&&(ht=Fc.split("."),gs=ht[0]>0&&ht[0]<4?1:+(ht[0]+ht[1]));!gs&&fo&&(ht=fo.match(/Edge\/(\d+)/),(!ht||ht[1]>=74)&&(ht=fo.match(/Chrome\/(\d+)/),ht&&(gs=+ht[1])));qc.exports=gs});var bo=g((Q$,Hc)=>{"use strict";var Uc=mo(),ay=we(),sy=Se(),ny=sy.String;Hc.exports=!!Object.getOwnPropertySymbols&&!ay(function(){var a=Symbol("symbol detection");return!ny(a)||!(Object(a)instanceof Symbol)||!Symbol.sham&&Uc&&Uc<41})});var go=g((G$,jc)=>{"use strict";var oy=bo();jc.exports=oy&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var So=g((z$,Wc)=>{"use strict";var uy=Vt(),ly=ve(),cy=Cr(),dy=go(),py=Object;Wc.exports=dy?function(a){return typeof a=="symbol"}:function(a){var e=uy("Symbol");return ly(e)&&cy(e.prototype,py(a))}});var Br=g((Y$,Qc)=>{"use strict";var hy=String;Qc.exports=function(a){try{return hy(a)}catch{return"Object"}}});var wt=g((K$,Gc)=>{"use strict";var fy=ve(),my=Br(),by=TypeError;Gc.exports=function(a){if(fy(a))return a;throw new by(my(a)+" is not a function")}});var Vr=g((X$,zc)=>{"use strict";var gy=wt(),Sy=Dr();zc.exports=function(a,e){var t=a[e];return Sy(t)?void 0:gy(t)}});var Kc=g((J$,Yc)=>{"use strict";var vo=Xe(),yo=ve(),To=qe(),vy=TypeError;Yc.exports=function(a,e){var t,i;if(e==="string"&&yo(t=a.toString)&&!To(i=vo(t,a))||yo(t=a.valueOf)&&!To(i=vo(t,a))||e!=="string"&&yo(t=a.toString)&&!To(i=vo(t,a)))return i;throw new vy("Can't convert object to primitive value")}});var ft=g((Z$,Xc)=>{"use strict";Xc.exports=!0});var ed=g((eL,Zc)=>{"use strict";var Jc=Se(),yy=Object.defineProperty;Zc.exports=function(a,e){try{yy(Jc,a,{value:e,configurable:!0,writable:!0})}catch{Jc[a]=e}return e}});var _r=g((tL,rd)=>{"use strict";var Ty=ft(),Iy=Se(),Ey=ed(),td="__core-js_shared__",id=rd.exports=Iy[td]||Ey(td,{});(id.versions||(id.versions=[])).push({version:"3.43.0",mode:Ty?"pure":"global",copyright:"© 2014-2025 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.43.0/LICENSE",source:"https://github.com/zloirock/core-js"})});var Io=g((iL,sd)=>{"use strict";var ad=_r();sd.exports=function(a,e){return ad[a]||(ad[a]=e||{})}});var qi=g((rL,nd)=>{"use strict";var xy=Xt(),wy=Object;nd.exports=function(a){return wy(xy(a))}});var mt=g((aL,od)=>{"use strict";var Ay=Ae(),Py=qi(),ky=Ay({}.hasOwnProperty);od.exports=Object.hasOwn||function(e,t){return ky(Py(e),t)}});var Eo=g((sL,ud)=>{"use strict";var Ry=Ae(),$y=0,Ly=Math.random(),My=Ry(1.1.toString);ud.exports=function(a){return"Symbol("+(a===void 0?"":a)+")_"+My(++$y+Ly,36)}});var Le=g((nL,cd)=>{"use strict";var Dy=Se(),Cy=Io(),ld=mt(),By=Eo(),Vy=bo(),_y=go(),Ui=Dy.Symbol,xo=Cy("wks"),Oy=_y?Ui.for||Ui:Ui&&Ui.withoutSetter||By;cd.exports=function(a){return ld(xo,a)||(xo[a]=Vy&&ld(Ui,a)?Ui[a]:Oy("Symbol."+a)),xo[a]}});var fd=g((oL,hd)=>{"use strict";var Fy=Xe(),dd=qe(),pd=So(),Ny=Vr(),qy=Kc(),Uy=Le(),Hy=TypeError,jy=Uy("toPrimitive");hd.exports=function(a,e){if(!dd(a)||pd(a))return a;var t=Ny(a,jy),i;if(t){if(e===void 0&&(e="default"),i=Fy(t,a,e),!dd(i)||pd(i))return i;throw new Hy("Can't convert object to primitive value")}return e===void 0&&(e="number"),qy(a,e)}});var wo=g((uL,md)=>{"use strict";var Wy=fd(),Qy=So();md.exports=function(a){var e=Wy(a,"string");return Qy(e)?e:e+""}});var Ss=g((lL,gd)=>{"use strict";var Gy=Se(),bd=qe(),Ao=Gy.document,zy=bd(Ao)&&bd(Ao.createElement);gd.exports=function(a){return zy?Ao.createElement(a):{}}});var Po=g((cL,Sd)=>{"use strict";var Yy=Ke(),Ky=we(),Xy=Ss();Sd.exports=!Yy&&!Ky(function(){return Object.defineProperty(Xy("div"),"a",{get:function(){return 7}}).a!==7})});var Td=g(yd=>{"use strict";var Jy=Ke(),Zy=Xe(),eT=lo(),tT=Mr(),iT=fi(),rT=wo(),aT=mt(),sT=Po(),vd=Object.getOwnPropertyDescriptor;yd.f=Jy?vd:function(e,t){if(e=iT(e),t=rT(t),sT)try{return vd(e,t)}catch{}if(aT(e,t))return tT(!Zy(eT.f,e,t),e[t])}});var ko=g((pL,Id)=>{"use strict";var nT=we(),oT=ve(),uT=/#|\.prototype\./,Or=function(a,e){var t=cT[lT(a)];return t===pT?!0:t===dT?!1:oT(e)?nT(e):!!e},lT=Or.normalize=function(a){return String(a).replace(uT,".").toLowerCase()},cT=Or.data={},dT=Or.NATIVE="N",pT=Or.POLYFILL="P";Id.exports=Or});var Hi=g((hL,xd)=>{"use strict";var Ed=oo(),hT=wt(),fT=Lr(),mT=Ed(Ed.bind);xd.exports=function(a,e){return hT(a),e===void 0?a:fT?mT(a,e):function(){return a.apply(e,arguments)}}});var Ro=g((fL,wd)=>{"use strict";var bT=Ke(),gT=we();wd.exports=bT&&gT(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var At=g((mL,Ad)=>{"use strict";var ST=qe(),vT=String,yT=TypeError;Ad.exports=function(a){if(ST(a))return a;throw new yT(vT(a)+" is not an object")}});var gi=g(kd=>{"use strict";var TT=Ke(),IT=Po(),ET=Ro(),vs=At(),Pd=wo(),xT=TypeError,$o=Object.defineProperty,wT=Object.getOwnPropertyDescriptor,Lo="enumerable",Mo="configurable",Do="writable";kd.f=TT?ET?function(e,t,i){if(vs(e),t=Pd(t),vs(i),typeof e=="function"&&t==="prototype"&&"value"in i&&Do in i&&!i[Do]){var r=wT(e,t);r&&r[Do]&&(e[t]=i.value,i={configurable:Mo in i?i[Mo]:r[Mo],enumerable:Lo in i?i[Lo]:r[Lo],writable:!1})}return $o(e,t,i)}:$o:function(e,t,i){if(vs(e),t=Pd(t),vs(i),IT)try{return $o(e,t,i)}catch{}if("get"in i||"set"in i)throw new xT("Accessors not supported");return"value"in i&&(e[t]=i.value),e}});var ji=g((gL,Rd)=>{"use strict";var AT=Ke(),PT=gi(),kT=Mr();Rd.exports=AT?function(a,e,t){return PT.f(a,e,kT(1,t))}:function(a,e,t){return a[e]=t,a}});var Te=g((SL,Ld)=>{"use strict";var Fr=Se(),RT=so(),$T=oo(),LT=ve(),MT=Td().f,DT=ko(),Wi=mi(),CT=Hi(),Qi=ji(),$d=mt();_r();var BT=function(a){var e=function(t,i,r){if(this instanceof e){switch(arguments.length){case 0:return new a;case 1:return new a(t);case 2:return new a(t,i)}return new a(t,i,r)}return RT(a,this,arguments)};return e.prototype=a.prototype,e};Ld.exports=function(a,e){var t=a.target,i=a.global,r=a.stat,s=a.proto,n=i?Fr:r?Fr[t]:Fr[t]&&Fr[t].prototype,u=i?Wi:Wi[t]||Qi(Wi,t,{})[t],o=u.prototype,l,p,c,d,h,m,b,S,v;for(d in e)l=DT(i?d:t+(r?".":"#")+d,a.forced),p=!l&&n&&$d(n,d),m=u[d],p&&(a.dontCallGetSet?(v=MT(n,d),b=v&&v.value):b=n[d]),h=p&&b?b:e[d],!(!l&&!s&&typeof m==typeof h)&&(a.bind&&p?S=CT(h,Fr):a.wrap&&p?S=BT(h):s&&LT(h)?S=$T(h):S=h,(a.sham||h&&h.sham||m&&m.sham)&&Qi(S,"sham",!0),Qi(u,d,S),s&&(c=t+"Prototype",$d(Wi,c)||Qi(Wi,c,{}),Qi(Wi[c],d,h),a.real&&o&&(l||!o[d])&&Qi(o,d,h)))}});var ys=g((vL,Dd)=>{"use strict";var VT=Io(),_T=Eo(),Md=VT("keys");Dd.exports=function(a){return Md[a]||(Md[a]=_T(a))}});var Bd=g((yL,Cd)=>{"use strict";var OT=we();Cd.exports=!OT(function(){function a(){}return a.prototype.constructor=null,Object.getPrototypeOf(new a)!==a.prototype})});var Ts=g((TL,_d)=>{"use strict";var FT=mt(),NT=ve(),qT=qi(),UT=ys(),HT=Bd(),Vd=UT("IE_PROTO"),Co=Object,jT=Co.prototype;_d.exports=HT?Co.getPrototypeOf:function(a){var e=qT(a);if(FT(e,Vd))return e[Vd];var t=e.constructor;return NT(t)&&e instanceof t?t.prototype:e instanceof Co?jT:null}});var Fd=g((IL,Od)=>{"use strict";var WT=Math.ceil,QT=Math.floor;Od.exports=Math.trunc||function(e){var t=+e;return(t>0?QT:WT)(t)}});var Nr=g((EL,Nd)=>{"use strict";var GT=Fd();Nd.exports=function(a){var e=+a;return e!==e||e===0?0:GT(e)}});var Ud=g((xL,qd)=>{"use strict";var zT=Nr(),YT=Math.max,KT=Math.min;qd.exports=function(a,e){var t=zT(a);return t<0?YT(t+e,0):KT(t,e)}});var Bo=g((wL,Hd)=>{"use strict";var XT=Nr(),JT=Math.min;Hd.exports=function(a){var e=XT(a);return e>0?JT(e,9007199254740991):0}});var Gi=g((AL,jd)=>{"use strict";var ZT=Bo();jd.exports=function(a){return ZT(a.length)}});var Vo=g((PL,Qd)=>{"use strict";var eI=fi(),tI=Ud(),iI=Gi(),Wd=function(a){return function(e,t,i){var r=eI(e),s=iI(r);if(s===0)return!a&&-1;var n=tI(i,s),u;if(a&&t!==t){for(;s>n;)if(u=r[n++],u!==u)return!0}else for(;s>n;n++)if((a||n in r)&&r[n]===t)return a||n||0;return!a&&-1}};Qd.exports={includes:Wd(!0),indexOf:Wd(!1)}});var Is=g((kL,Gd)=>{"use strict";Gd.exports={}});var Kd=g((RL,Yd)=>{"use strict";var rI=Ae(),_o=mt(),aI=fi(),sI=Vo().indexOf,nI=Is(),zd=rI([].push);Yd.exports=function(a,e){var t=aI(a),i=0,r=[],s;for(s in t)!_o(nI,s)&&_o(t,s)&&zd(r,s);for(;e.length>i;)_o(t,s=e[i++])&&(~sI(r,s)||zd(r,s));return r}});var Oo=g(($L,Xd)=>{"use strict";Xd.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var Fo=g((LL,Jd)=>{"use strict";var oI=Kd(),uI=Oo();Jd.exports=Object.keys||function(e){return oI(e,uI)}});var No=g((ML,rp)=>{"use strict";var ep=Ke(),lI=we(),tp=Ae(),cI=Ts(),dI=Fo(),pI=fi(),hI=lo().f,ip=tp(hI),fI=tp([].push),mI=ep&&lI(function(){var a=Object.create(null);return a[2]=2,!ip(a,2)}),Zd=function(a){return function(e){for(var t=pI(e),i=dI(t),r=mI&&cI(t)===null,s=i.length,n=0,u=[],o;s>n;)o=i[n++],(!ep||(r?o in t:ip(t,o)))&&fI(u,a?[o,t[o]]:t[o]);return u}};rp.exports={entries:Zd(!0),values:Zd(!1)}});var ap=g(()=>{"use strict";var bI=Te(),gI=No().values;bI({target:"Object",stat:!0},{values:function(e){return gI(e)}})});var np=g((BL,sp)=>{"use strict";ap();var SI=mi();sp.exports=SI.Object.values});var up=g((VL,op)=>{"use strict";var vI=np();op.exports=vI});var Si=g((_L,lp)=>{"use strict";var yI=up();lp.exports=yI});var qr=g((OL,cp)=>{"use strict";cp.exports=function(){}});var dp=g(()=>{"use strict";var TI=Te(),II=Vo().includes,EI=we(),xI=qr(),wI=EI(function(){return!Array(1).includes()});TI({target:"Array",proto:!0,forced:wI},{includes:function(e){return II(this,e,arguments.length>1?arguments[1]:void 0)}});xI("includes")});var Jt=g((qL,pp)=>{"use strict";var AI=Vt();pp.exports=AI});var fp=g((UL,hp)=>{"use strict";dp();var PI=Jt();hp.exports=PI("Array","includes")});var bp=g((HL,mp)=>{"use strict";var kI=fp();mp.exports=kI});var Oe=g((jL,gp)=>{"use strict";var RI=bp();gp.exports=RI});var vp=g(()=>{"use strict";var LI=Te(),MI=No().entries;LI({target:"Object",stat:!0},{entries:function(e){return MI(e)}})});var Tp=g((rM,yp)=>{"use strict";vp();var DI=mi();yp.exports=DI.Object.entries});var Ep=g((aM,Ip)=>{"use strict";var CI=Tp();Ip.exports=CI});var zi=g((sM,xp)=>{"use strict";var BI=Ep();xp.exports=BI});var vi=g((nM,wp)=>{"use strict";wp.exports={}});var kp=g((oM,Pp)=>{"use strict";var VI=Se(),_I=ve(),Ap=VI.WeakMap;Pp.exports=_I(Ap)&&/native code/.test(String(Ap))});var jo=g((uM,Lp)=>{"use strict";var OI=kp(),$p=Se(),FI=qe(),NI=ji(),qo=mt(),Uo=_r(),qI=ys(),UI=Is(),Rp="Object already initialized",Ho=$p.TypeError,HI=$p.WeakMap,xs,Ur,ws,jI=function(a){return ws(a)?Ur(a):xs(a,{})},WI=function(a){return function(e){var t;if(!FI(e)||(t=Ur(e)).type!==a)throw new Ho("Incompatible receiver, "+a+" required");return t}};OI||Uo.state?(bt=Uo.state||(Uo.state=new HI),bt.get=bt.get,bt.has=bt.has,bt.set=bt.set,xs=function(a,e){if(bt.has(a))throw new Ho(Rp);return e.facade=a,bt.set(a,e),e},Ur=function(a){return bt.get(a)||{}},ws=function(a){return bt.has(a)}):(yi=qI("state"),UI[yi]=!0,xs=function(a,e){if(qo(a,yi))throw new Ho(Rp);return e.facade=a,NI(a,yi,e),e},Ur=function(a){return qo(a,yi)?a[yi]:{}},ws=function(a){return qo(a,yi)});var bt,yi;Lp.exports={set:xs,get:Ur,has:ws,enforce:jI,getterFor:WI}});var Go=g((lM,Dp)=>{"use strict";var Wo=Ke(),QI=mt(),Mp=Function.prototype,GI=Wo&&Object.getOwnPropertyDescriptor,Qo=QI(Mp,"name"),zI=Qo&&function(){}.name==="something",YI=Qo&&(!Wo||Wo&&GI(Mp,"name").configurable);Dp.exports={EXISTS:Qo,PROPER:zI,CONFIGURABLE:YI}});var Bp=g(Cp=>{"use strict";var KI=Ke(),XI=Ro(),JI=gi(),ZI=At(),eE=fi(),tE=Fo();Cp.f=KI&&!XI?Object.defineProperties:function(e,t){ZI(e);for(var i=eE(t),r=tE(t),s=r.length,n=0,u;s>n;)JI.f(e,u=r[n++],i[u]);return e}});var zo=g((dM,Vp)=>{"use strict";var iE=Vt();Vp.exports=iE("document","documentElement")});var Jo=g((pM,Hp)=>{"use strict";var rE=At(),aE=Bp(),_p=Oo(),sE=Is(),nE=zo(),oE=Ss(),uE=ys(),Op=">",Fp="<",Ko="prototype",Xo="script",qp=uE("IE_PROTO"),Yo=function(){},Up=function(a){return Fp+Xo+Op+a+Fp+"/"+Xo+Op},Np=function(a){a.write(Up("")),a.close();var e=a.parentWindow.Object;return a=null,e},lE=function(){var a=oE("iframe"),e="java"+Xo+":",t;return a.style.display="none",nE.appendChild(a),a.src=String(e),t=a.contentWindow.document,t.open(),t.write(Up("document.F=Object")),t.close(),t.F},As,Ps=function(){try{As=new ActiveXObject("htmlfile")}catch{}Ps=typeof document<"u"?document.domain&&As?Np(As):lE():Np(As);for(var a=_p.length;a--;)delete Ps[Ko][_p[a]];return Ps()};sE[qp]=!0;Hp.exports=Object.create||function(e,t){var i;return e!==null?(Yo[Ko]=rE(e),i=new Yo,Yo[Ko]=null,i[qp]=e):i=Ps(),t===void 0?i:aE.f(i,t)}});var Yi=g((hM,jp)=>{"use strict";var cE=ji();jp.exports=function(a,e,t,i){return i&&i.enumerable?a[e]=t:cE(a,e,t),a}});var iu=g((fM,Gp)=>{"use strict";var dE=we(),pE=ve(),hE=qe(),fE=Jo(),Wp=Ts(),mE=Yi(),bE=Le(),gE=ft(),tu=bE("iterator"),Qp=!1,_t,Zo,eu;[].keys&&(eu=[].keys(),"next"in eu?(Zo=Wp(Wp(eu)),Zo!==Object.prototype&&(_t=Zo)):Qp=!0);var SE=!hE(_t)||dE(function(){var a={};return _t[tu].call(a)!==a});SE?_t={}:gE&&(_t=fE(_t));pE(_t[tu])||mE(_t,tu,function(){return this});Gp.exports={IteratorPrototype:_t,BUGGY_SAFARI_ITERATORS:Qp}});var ks=g((mM,Yp)=>{"use strict";var vE=Le(),yE=vE("toStringTag"),zp={};zp[yE]="z";Yp.exports=String(zp)==="[object z]"});var Hr=g((bM,Kp)=>{"use strict";var TE=ks(),IE=ve(),Rs=hi(),EE=Le(),xE=EE("toStringTag"),wE=Object,AE=Rs(function(){return arguments}())==="Arguments",PE=function(a,e){try{return a[e]}catch{}};Kp.exports=TE?Rs:function(a){var e,t,i;return a===void 0?"Undefined":a===null?"Null":typeof(t=PE(e=wE(a),xE))=="string"?t:AE?Rs(e):(i=Rs(e))==="Object"&&IE(e.callee)?"Arguments":i}});var Jp=g((gM,Xp)=>{"use strict";var kE=ks(),RE=Hr();Xp.exports=kE?{}.toString:function(){return"[object "+RE(this)+"]"}});var jr=g((SM,eh)=>{"use strict";var $E=ks(),LE=gi().f,ME=ji(),DE=mt(),CE=Jp(),BE=Le(),Zp=BE("toStringTag");eh.exports=function(a,e,t,i){var r=t?a:a&&a.prototype;r&&(DE(r,Zp)||LE(r,Zp,{configurable:!0,value:e}),i&&!$E&&ME(r,"toString",CE))}});var ih=g((vM,th)=>{"use strict";var VE=iu().IteratorPrototype,_E=Jo(),OE=Mr(),FE=jr(),NE=vi(),qE=function(){return this};th.exports=function(a,e,t,i){var r=e+" Iterator";return a.prototype=_E(VE,{next:OE(+!i,t)}),FE(a,r,!1,!0),NE[r]=qE,a}});var ah=g((yM,rh)=>{"use strict";var UE=Ae(),HE=wt();rh.exports=function(a,e,t){try{return UE(HE(Object.getOwnPropertyDescriptor(a,e)[t]))}catch{}}});var nh=g((TM,sh)=>{"use strict";var jE=qe();sh.exports=function(a){return jE(a)||a===null}});var uh=g((IM,oh)=>{"use strict";var WE=nh(),QE=String,GE=TypeError;oh.exports=function(a){if(WE(a))return a;throw new GE("Can't set "+QE(a)+" as a prototype")}});var ru=g((EM,lh)=>{"use strict";var zE=ah(),YE=qe(),KE=Xt(),XE=uh();lh.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var a=!1,e={},t;try{t=zE(Object.prototype,"__proto__","set"),t(e,[]),a=e instanceof Array}catch{}return function(r,s){return KE(r),XE(s),YE(r)&&(a?t(r,s):r.__proto__=s),r}}():void 0)});var yh=g((xM,vh)=>{"use strict";var JE=Te(),ZE=Xe(),$s=ft(),gh=Go(),ex=ve(),tx=ih(),ch=Ts(),dh=ru(),ix=jr(),rx=ji(),au=Yi(),ax=Le(),ph=vi(),Sh=iu(),sx=gh.PROPER,nx=gh.CONFIGURABLE,hh=Sh.IteratorPrototype,Ls=Sh.BUGGY_SAFARI_ITERATORS,Wr=ax("iterator"),fh="keys",Qr="values",mh="entries",bh=function(){return this};vh.exports=function(a,e,t,i,r,s,n){tx(t,e,i);var u=function(v){if(v===r&&d)return d;if(!Ls&&v&&v in p)return p[v];switch(v){case fh:return function(){return new t(this,v)};case Qr:return function(){return new t(this,v)};case mh:return function(){return new t(this,v)}}return function(){return new t(this)}},o=e+" Iterator",l=!1,p=a.prototype,c=p[Wr]||p["@@iterator"]||r&&p[r],d=!Ls&&c||u(r),h=e==="Array"&&p.entries||c,m,b,S;if(h&&(m=ch(h.call(new a)),m!==Object.prototype&&m.next&&(!$s&&ch(m)!==hh&&(dh?dh(m,hh):ex(m[Wr])||au(m,Wr,bh)),ix(m,o,!0,!0),$s&&(ph[o]=bh))),sx&&r===Qr&&c&&c.name!==Qr&&(!$s&&nx?rx(p,"name",Qr):(l=!0,d=function(){return ZE(c,this)})),r)if(b={values:u(Qr),keys:s?d:u(fh),entries:u(mh)},n)for(S in b)(Ls||l||!(S in p))&&au(p,S,b[S]);else JE({target:e,proto:!0,forced:Ls||l},b);return(!$s||n)&&p[Wr]!==d&&au(p,Wr,d,{name:r}),ph[e]=d,b}});var Ih=g((wM,Th)=>{"use strict";Th.exports=function(a,e){return{value:a,done:e}}});var nu=g((AM,Ph)=>{"use strict";var ox=fi(),su=qr(),Eh=vi(),wh=jo(),ux=gi().f,lx=yh(),Ms=Ih(),cx=ft(),dx=Ke(),Ah="Array Iterator",px=wh.set,hx=wh.getterFor(Ah);Ph.exports=lx(Array,"Array",function(a,e){px(this,{type:Ah,target:ox(a),index:0,kind:e})},function(){var a=hx(this),e=a.target,t=a.index++;if(!e||t>=e.length)return a.target=null,Ms(void 0,!0);switch(a.kind){case"keys":return Ms(t,!1);case"values":return Ms(e[t],!1)}return Ms([t,e[t]],!1)},"values");var xh=Eh.Arguments=Eh.Array;su("keys");su("values");su("entries");if(!cx&&dx&&xh.name!=="values")try{ux(xh,"name",{value:"values"})}catch{}});var Rh=g((PM,kh)=>{"use strict";var fx=Le(),mx=vi(),bx=fx("iterator"),gx=Array.prototype;kh.exports=function(a){return a!==void 0&&(mx.Array===a||gx[bx]===a)}});var ou=g((kM,Lh)=>{"use strict";var Sx=Hr(),$h=Vr(),vx=Dr(),yx=vi(),Tx=Le(),Ix=Tx("iterator");Lh.exports=function(a){if(!vx(a))return $h(a,Ix)||$h(a,"@@iterator")||yx[Sx(a)]}});var Dh=g((RM,Mh)=>{"use strict";var Ex=Xe(),xx=wt(),wx=At(),Ax=Br(),Px=ou(),kx=TypeError;Mh.exports=function(a,e){var t=arguments.length<2?Px(a):e;if(xx(t))return wx(Ex(t,a));throw new kx(Ax(a)+" is not iterable")}});var Vh=g(($M,Bh)=>{"use strict";var Rx=Xe(),Ch=At(),$x=Vr();Bh.exports=function(a,e,t){var i,r;Ch(a);try{if(i=$x(a,"return"),!i){if(e==="throw")throw t;return t}i=Rx(i,a)}catch(s){r=!0,i=s}if(e==="throw")throw t;if(r)throw i;return Ch(i),t}});var Cs=g((LM,Nh)=>{"use strict";var Lx=Hi(),Mx=Xe(),Dx=At(),Cx=Br(),Bx=Rh(),Vx=Gi(),_h=Cr(),_x=Dh(),Ox=ou(),Oh=Vh(),Fx=TypeError,Ds=function(a,e){this.stopped=a,this.result=e},Fh=Ds.prototype;Nh.exports=function(a,e,t){var i=t&&t.that,r=!!(t&&t.AS_ENTRIES),s=!!(t&&t.IS_RECORD),n=!!(t&&t.IS_ITERATOR),u=!!(t&&t.INTERRUPTED),o=Lx(e,i),l,p,c,d,h,m,b,S=function(I){return l&&Oh(l,"normal"),new Ds(!0,I)},v=function(I){return r?(Dx(I),u?o(I[0],I[1],S):o(I[0],I[1])):u?o(I,S):o(I)};if(s)l=a.iterator;else if(n)l=a;else{if(p=Ox(a),!p)throw new Fx(Cx(a)+" is not iterable");if(Bx(p)){for(c=0,d=Vx(a);d>c;c++)if(h=v(a[c]),h&&_h(Fh,h))return h;return new Ds(!1)}l=_x(a,p)}for(m=s?a.next:l.next;!(b=Mx(m,l)).done;){try{h=v(b.value)}catch(I){Oh(l,"throw",I)}if(typeof h=="object"&&h&&_h(Fh,h))return h}return new Ds(!1)}});var Uh=g((MM,qh)=>{"use strict";var Nx=Ke(),qx=gi(),Ux=Mr();qh.exports=function(a,e,t){Nx?qx.f(a,e,Ux(0,t)):a[e]=t}});var Hh=g(()=>{"use strict";var Hx=Te(),jx=Cs(),Wx=Uh();Hx({target:"Object",stat:!0},{fromEntries:function(e){var t={};return jx(e,function(i,r){Wx(t,i,r)},{AS_ENTRIES:!0}),t}})});var Wh=g((BM,jh)=>{"use strict";nu();Hh();var Qx=mi();jh.exports=Qx.Object.fromEntries});var Gh=g((VM,Qh)=>{"use strict";Qh.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 Yh=g(()=>{"use strict";nu();var Gx=Gh(),zx=Se(),Yx=jr(),zh=vi();for(Bs in Gx)Yx(zx[Bs],Bs),zh[Bs]=zh.Array;var Bs});var Xh=g((FM,Kh)=>{"use strict";var Kx=Wh();Yh();Kh.exports=Kx});var uu=g((NM,Jh)=>{"use strict";var Xx=Xh();Jh.exports=Xx});var Zh=g(()=>{"use strict"});var lu=g((HM,ef)=>{"use strict";var Gr=Se(),Jx=bi(),Zx=hi(),Vs=function(a){return Jx.slice(0,a.length)===a};ef.exports=function(){return Vs("Bun/")?"BUN":Vs("Cloudflare-Workers")?"CLOUDFLARE":Vs("Deno/")?"DENO":Vs("Node.js/")?"NODE":Gr.Bun&&typeof Bun.version=="string"?"BUN":Gr.Deno&&typeof Deno.version=="object"?"DENO":Zx(Gr.process)==="process"?"NODE":Gr.window&&Gr.document?"BROWSER":"REST"}()});var _s=g((jM,tf)=>{"use strict";var ew=lu();tf.exports=ew==="NODE"});var af=g((WM,rf)=>{"use strict";var tw=gi();rf.exports=function(a,e,t){return tw.f(a,e,t)}});var of=g((QM,nf)=>{"use strict";var iw=Vt(),rw=af(),aw=Le(),sw=Ke(),sf=aw("species");nf.exports=function(a){var e=iw(a);sw&&e&&!e[sf]&&rw(e,sf,{configurable:!0,get:function(){return this}})}});var lf=g((GM,uf)=>{"use strict";var nw=Cr(),ow=TypeError;uf.exports=function(a,e){if(nw(e,a))return a;throw new ow("Incorrect invocation")}});var du=g((zM,cf)=>{"use strict";var uw=Ae(),lw=ve(),cu=_r(),cw=uw(Function.toString);lw(cu.inspectSource)||(cu.inspectSource=function(a){return cw(a)});cf.exports=cu.inspectSource});var hu=g((YM,mf)=>{"use strict";var dw=Ae(),pw=we(),df=ve(),hw=Hr(),fw=Vt(),mw=du(),pf=function(){},hf=fw("Reflect","construct"),pu=/^\s*(?:class|function)\b/,bw=dw(pu.exec),gw=!pu.test(pf),zr=function(e){if(!df(e))return!1;try{return hf(pf,[],e),!0}catch{return!1}},ff=function(e){if(!df(e))return!1;switch(hw(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return gw||!!bw(pu,mw(e))}catch{return!0}};ff.sham=!0;mf.exports=!hf||pw(function(){var a;return zr(zr.call)||!zr(Object)||!zr(function(){a=!0})||a})?ff:zr});var gf=g((KM,bf)=>{"use strict";var Sw=hu(),vw=Br(),yw=TypeError;bf.exports=function(a){if(Sw(a))return a;throw new yw(vw(a)+" is not a constructor")}});var fu=g((XM,vf)=>{"use strict";var Sf=At(),Tw=gf(),Iw=Dr(),Ew=Le(),xw=Ew("species");vf.exports=function(a,e){var t=Sf(a).constructor,i;return t===void 0||Iw(i=Sf(t)[xw])?e:Tw(i)}});var Tf=g((JM,yf)=>{"use strict";var ww=Ae();yf.exports=ww([].slice)});var Ef=g((ZM,If)=>{"use strict";var Aw=TypeError;If.exports=function(a,e){if(a<e)throw new Aw("Not enough arguments");return a}});var mu=g((eD,xf)=>{"use strict";var Pw=bi();xf.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(Pw)});var xu=g((tD,Df)=>{"use strict";var Je=Se(),kw=so(),Rw=Hi(),wf=ve(),$w=mt(),Mf=we(),Af=zo(),Lw=Tf(),Pf=Ss(),Mw=Ef(),Dw=mu(),Cw=_s(),Tu=Je.setImmediate,Iu=Je.clearImmediate,Bw=Je.process,bu=Je.Dispatch,Vw=Je.Function,kf=Je.MessageChannel,_w=Je.String,gu=0,Yr={},Rf="onreadystatechange",Kr,Ti,Su,vu;Mf(function(){Kr=Je.location});var Eu=function(a){if($w(Yr,a)){var e=Yr[a];delete Yr[a],e()}},yu=function(a){return function(){Eu(a)}},$f=function(a){Eu(a.data)},Lf=function(a){Je.postMessage(_w(a),Kr.protocol+"//"+Kr.host)};(!Tu||!Iu)&&(Tu=function(e){Mw(arguments.length,1);var t=wf(e)?e:Vw(e),i=Lw(arguments,1);return Yr[++gu]=function(){kw(t,void 0,i)},Ti(gu),gu},Iu=function(e){delete Yr[e]},Cw?Ti=function(a){Bw.nextTick(yu(a))}:bu&&bu.now?Ti=function(a){bu.now(yu(a))}:kf&&!Dw?(Su=new kf,vu=Su.port2,Su.port1.onmessage=$f,Ti=Rw(vu.postMessage,vu)):Je.addEventListener&&wf(Je.postMessage)&&!Je.importScripts&&Kr&&Kr.protocol!=="file:"&&!Mf(Lf)?(Ti=Lf,Je.addEventListener("message",$f,!1)):Rf in Pf("script")?Ti=function(a){Af.appendChild(Pf("script"))[Rf]=function(){Af.removeChild(this),Eu(a)}}:Ti=function(a){setTimeout(yu(a),0)});Df.exports={set:Tu,clear:Iu}});var Vf=g((iD,Bf)=>{"use strict";var Cf=Se(),Ow=Ke(),Fw=Object.getOwnPropertyDescriptor;Bf.exports=function(a){if(!Ow)return Cf[a];var e=Fw(Cf,a);return e&&e.value}});var wu=g((rD,Of)=>{"use strict";var _f=function(){this.head=null,this.tail=null};_f.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=_f});var Nf=g((aD,Ff)=>{"use strict";var Nw=bi();Ff.exports=/ipad|iphone|ipod/i.test(Nw)&&typeof Pebble<"u"});var Uf=g((sD,qf)=>{"use strict";var qw=bi();qf.exports=/web0s(?!.*chrome)/i.test(qw)});var Yf=g((nD,zf)=>{"use strict";var Xi=Se(),Uw=Vf(),Hf=Hi(),Au=xu().set,Hw=wu(),jw=mu(),Ww=Nf(),Qw=Uf(),Pu=_s(),jf=Xi.MutationObserver||Xi.WebKitMutationObserver,Wf=Xi.document,Qf=Xi.process,Os=Xi.Promise,$u=Uw("queueMicrotask"),Ki,ku,Ru,Fs,Gf;$u||(Xr=new Hw,Jr=function(){var a,e;for(Pu&&(a=Qf.domain)&&a.exit();e=Xr.get();)try{e()}catch(t){throw Xr.head&&Ki(),t}a&&a.enter()},!jw&&!Pu&&!Qw&&jf&&Wf?(ku=!0,Ru=Wf.createTextNode(""),new jf(Jr).observe(Ru,{characterData:!0}),Ki=function(){Ru.data=ku=!ku}):!Ww&&Os&&Os.resolve?(Fs=Os.resolve(void 0),Fs.constructor=Os,Gf=Hf(Fs.then,Fs),Ki=function(){Gf(Jr)}):Pu?Ki=function(){Qf.nextTick(Jr)}:(Au=Hf(Au,Xi),Ki=function(){Au(Jr)}),$u=function(a){Xr.head||Ki(),Xr.add(a)});var Xr,Jr;zf.exports=$u});var Xf=g((oD,Kf)=>{"use strict";Kf.exports=function(a,e){try{arguments.length===1?console.error(a):console.error(a,e)}catch{}}});var Ns=g((uD,Jf)=>{"use strict";Jf.exports=function(a){try{return{error:!1,value:a()}}catch(e){return{error:!0,value:e}}}});var Ii=g((lD,Zf)=>{"use strict";var Gw=Se();Zf.exports=Gw.Promise});var Ji=g((cD,rm)=>{"use strict";var zw=Se(),Zr=Ii(),Yw=ve(),Kw=ko(),Xw=du(),Jw=Le(),em=lu(),Zw=ft(),Lu=mo(),tm=Zr&&Zr.prototype,eA=Jw("species"),Mu=!1,im=Yw(zw.PromiseRejectionEvent),tA=Kw("Promise",function(){var a=Xw(Zr),e=a!==String(Zr);if(!e&&Lu===66||Zw&&!(tm.catch&&tm.finally))return!0;if(!Lu||Lu<51||!/native code/.test(a)){var t=new Zr(function(s){s(1)}),i=function(s){s(function(){},function(){})},r=t.constructor={};if(r[eA]=i,Mu=t.then(function(){})instanceof i,!Mu)return!0}return!e&&(em==="BROWSER"||em==="DENO")&&!im});rm.exports={CONSTRUCTOR:tA,REJECTION_EVENT:im,SUBCLASSING:Mu}});var Zi=g((dD,sm)=>{"use strict";var am=wt(),iA=TypeError,rA=function(a){var e,t;this.promise=new a(function(i,r){if(e!==void 0||t!==void 0)throw new iA("Bad Promise constructor");e=i,t=r}),this.resolve=am(e),this.reject=am(t)};sm.exports.f=function(a){return new rA(a)}});var wm=g(()=>{"use strict";var aA=Te(),sA=ft(),js=_s(),Zt=Se(),nA=mi(),rr=Xe(),nm=Yi(),om=ru(),oA=jr(),uA=of(),lA=wt(),Hs=ve(),cA=qe(),dA=lf(),pA=fu(),pm=xu().set,_u=Yf(),hA=Xf(),fA=Ns(),mA=wu(),hm=jo(),Ws=Ii(),Ou=Ji(),fm=Zi(),Qs="Promise",mm=Ou.CONSTRUCTOR,bA=Ou.REJECTION_EVENT,gA=Ou.SUBCLASSING,Du=hm.getterFor(Qs),SA=hm.set,er=Ws&&Ws.prototype,Ei=Ws,qs=er,bm=Zt.TypeError,Cu=Zt.document,Fu=Zt.process,Bu=fm.f,vA=Bu,yA=!!(Cu&&Cu.createEvent&&Zt.dispatchEvent),gm="unhandledrejection",TA="rejectionhandled",um=0,Sm=1,IA=2,Nu=1,vm=2,Us,lm,ym,cm,Tm=function(a){var e;return cA(a)&&Hs(e=a.then)?e:!1},Im=function(a,e){var t=e.value,i=e.state===Sm,r=i?a.ok:a.fail,s=a.resolve,n=a.reject,u=a.domain,o,l,p;try{r?(i||(e.rejection===vm&&xA(e),e.rejection=Nu),r===!0?o=t:(u&&u.enter(),o=r(t),u&&(u.exit(),p=!0)),o===a.promise?n(new bm("Promise-chain cycle")):(l=Tm(o))?rr(l,o,s,n):s(o)):n(t)}catch(c){u&&!p&&u.exit(),n(c)}},Em=function(a,e){a.notified||(a.notified=!0,_u(function(){for(var t=a.reactions,i;i=t.get();)Im(i,a);a.notified=!1,e&&!a.rejection&&EA(a)}))},xm=function(a,e,t){var i,r;yA?(i=Cu.createEvent("Event"),i.promise=e,i.reason=t,i.initEvent(a,!1,!0),Zt.dispatchEvent(i)):i={promise:e,reason:t},!bA&&(r=Zt["on"+a])?r(i):a===gm&&hA("Unhandled promise rejection",t)},EA=function(a){rr(pm,Zt,function(){var e=a.facade,t=a.value,i=dm(a),r;if(i&&(r=fA(function(){js?Fu.emit("unhandledRejection",t,e):xm(gm,e,t)}),a.rejection=js||dm(a)?vm:Nu,r.error))throw r.value})},dm=function(a){return a.rejection!==Nu&&!a.parent},xA=function(a){rr(pm,Zt,function(){var e=a.facade;js?Fu.emit("rejectionHandled",e):xm(TA,e,a.value)})},tr=function(a,e,t){return function(i){a(e,i,t)}},ir=function(a,e,t){a.done||(a.done=!0,t&&(a=t),a.value=e,a.state=IA,Em(a,!0))},Vu=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 i=Tm(e);i?_u(function(){var r={done:!1};try{rr(i,e,tr(Vu,r,a),tr(ir,r,a))}catch(s){ir(r,s,a)}}):(a.value=e,a.state=Sm,Em(a,!1))}catch(r){ir({done:!1},r,a)}}};if(mm&&(Ei=function(e){dA(this,qs),lA(e),rr(Us,this);var t=Du(this);try{e(tr(Vu,t),tr(ir,t))}catch(i){ir(t,i)}},qs=Ei.prototype,Us=function(e){SA(this,{type:Qs,done:!1,notified:!1,parent:!1,reactions:new mA,rejection:!1,state:um,value:null})},Us.prototype=nm(qs,"then",function(e,t){var i=Du(this),r=Bu(pA(this,Ei));return i.parent=!0,r.ok=Hs(e)?e:!0,r.fail=Hs(t)&&t,r.domain=js?Fu.domain:void 0,i.state===um?i.reactions.add(r):_u(function(){Im(r,i)}),r.promise}),lm=function(){var a=new Us,e=Du(a);this.promise=a,this.resolve=tr(Vu,e),this.reject=tr(ir,e)},fm.f=Bu=function(a){return a===Ei||a===ym?new lm(a):vA(a)},!sA&&Hs(Ws)&&er!==Object.prototype)){cm=er.then,gA||nm(er,"then",function(e,t){var i=this;return new Ei(function(r,s){rr(cm,i,r,s)}).then(e,t)},{unsafe:!0});try{delete er.constructor}catch{}om&&om(er,qs)}aA({global:!0,constructor:!0,wrap:!0,forced:mm},{Promise:Ei});ym=nA.Promise;oA(Ei,Qs,!1,!0);uA(Qs)});var $m=g((fD,Rm)=>{"use strict";var wA=Le(),Pm=wA("iterator"),km=!1;try{Am=0,qu={next:function(){return{done:!!Am++}},return:function(){km=!0}},qu[Pm]=function(){return this},Array.from(qu,function(){throw 2})}catch{}var Am,qu;Rm.exports=function(a,e){try{if(!e&&!km)return!1}catch{return!1}var t=!1;try{var i={};i[Pm]=function(){return{next:function(){return{done:t=!0}}}},a(i)}catch{}return t}});var Uu=g((mD,Lm)=>{"use strict";var AA=Ii(),PA=$m(),kA=Ji().CONSTRUCTOR;Lm.exports=kA||!PA(function(a){AA.all(a).then(void 0,function(){})})});var Mm=g(()=>{"use strict";var RA=Te(),$A=Xe(),LA=wt(),MA=Zi(),DA=Ns(),CA=Cs(),BA=Uu();RA({target:"Promise",stat:!0,forced:BA},{all:function(e){var t=this,i=MA.f(t),r=i.resolve,s=i.reject,n=DA(function(){var u=LA(t.resolve),o=[],l=0,p=1;CA(e,function(c){var d=l++,h=!1;p++,$A(u,t,c).then(function(m){h||(h=!0,o[d]=m,--p||r(o))},s)}),--p||r(o)});return n.error&&s(n.value),i.promise}})});var Cm=g(()=>{"use strict";var VA=Te(),_A=ft(),OA=Ji().CONSTRUCTOR,ju=Ii(),FA=Vt(),NA=ve(),qA=Yi(),Dm=ju&&ju.prototype;VA({target:"Promise",proto:!0,forced:OA,real:!0},{catch:function(a){return this.then(void 0,a)}});!_A&&NA(ju)&&(Hu=FA("Promise").prototype.catch,Dm.catch!==Hu&&qA(Dm,"catch",Hu,{unsafe:!0}));var Hu});var Bm=g(()=>{"use strict";var UA=Te(),HA=Xe(),jA=wt(),WA=Zi(),QA=Ns(),GA=Cs(),zA=Uu();UA({target:"Promise",stat:!0,forced:zA},{race:function(e){var t=this,i=WA.f(t),r=i.reject,s=QA(function(){var n=jA(t.resolve);GA(e,function(u){HA(n,t,u).then(i.resolve,r)})});return s.error&&r(s.value),i.promise}})});var Vm=g(()=>{"use strict";var YA=Te(),KA=Zi(),XA=Ji().CONSTRUCTOR;YA({target:"Promise",stat:!0,forced:XA},{reject:function(e){var t=KA.f(this),i=t.reject;return i(e),t.promise}})});var Wu=g((xD,_m)=>{"use strict";var JA=At(),ZA=qe(),eP=Zi();_m.exports=function(a,e){if(JA(a),ZA(e)&&e.constructor===a)return e;var t=eP.f(a),i=t.resolve;return i(e),t.promise}});var Nm=g(()=>{"use strict";var tP=Te(),iP=Vt(),Om=ft(),rP=Ii(),Fm=Ji().CONSTRUCTOR,aP=Wu(),sP=iP("Promise"),nP=Om&&!Fm;tP({target:"Promise",stat:!0,forced:Om||Fm},{resolve:function(e){return aP(nP&&this===sP?rP:this,e)}})});var qm=g(()=>{"use strict";wm();Mm();Cm();Bm();Vm();Nm()});var Wm=g(()=>{"use strict";var oP=Te(),uP=ft(),Gs=Ii(),lP=we(),Hm=Vt(),jm=ve(),cP=fu(),Um=Wu(),dP=Yi(),Gu=Gs&&Gs.prototype,pP=!!Gs&&lP(function(){Gu.finally.call({then:function(){}},function(){})});oP({target:"Promise",proto:!0,real:!0,forced:pP},{finally:function(a){var e=cP(this,Hm("Promise")),t=jm(a);return this.then(t?function(i){return Um(e,a()).then(function(){return i})}:a,t?function(i){return Um(e,a()).then(function(){throw i})}:a)}});!uP&&jm(Gs)&&(Qu=Hm("Promise").prototype.finally,Gu.finally!==Qu&&dP(Gu,"finally",Qu,{unsafe:!0}));var Qu});var Gm=g((LD,Qm)=>{"use strict";Zh();qm();Wm();var hP=Jt();Qm.exports=hP("Promise","finally")});var Ym=g((MD,zm)=>{"use strict";var fP=Gm();zm.exports=fP});var zs=g((DD,Km)=>{"use strict";var mP=Ym();Km.exports=mP});var hb=g(()=>{"use strict";var RP=Te(),$P=qi(),LP=Gi(),MP=Nr(),DP=qr();RP({target:"Array",proto:!0},{at:function(e){var t=$P(this),i=LP(t),r=MP(e),s=r>=0?r:i+r;return s<0||s>=i?void 0:t[s]}});DP("at")});var mb=g((pB,fb)=>{"use strict";hb();var CP=Jt();fb.exports=CP("Array","at")});var gb=g((hB,bb)=>{"use strict";var BP=mb();bb.exports=BP});var gt=g((fB,Sb)=>{"use strict";var VP=gb();Sb.exports=VP});var fl=g((z0,Hb)=>{"use strict";var GP=hi();Hb.exports=Array.isArray||function(e){return GP(e)==="Array"}});var Wb=g((Y0,jb)=>{"use strict";var zP=TypeError,YP=9007199254740991;jb.exports=function(a){if(a>YP)throw zP("Maximum allowed index exceeded");return a}});var zb=g((K0,Gb)=>{"use strict";var KP=fl(),XP=Gi(),JP=Wb(),ZP=Hi(),Qb=function(a,e,t,i,r,s,n,u){for(var o=r,l=0,p=n?ZP(n,u):!1,c,d;l<i;)l in t&&(c=p?p(t[l],l,e):t[l],s>0&&KP(c)?(d=XP(c),o=Qb(a,e,c,d,o,s-1)-1):(JP(o+1),a[o]=c),o++),l++;return o};Gb.exports=Qb});var Jb=g((X0,Xb)=>{"use strict";var Yb=fl(),ek=hu(),tk=qe(),ik=Le(),rk=ik("species"),Kb=Array;Xb.exports=function(a){var e;return Yb(a)&&(e=a.constructor,ek(e)&&(e===Kb||Yb(e.prototype))?e=void 0:tk(e)&&(e=e[rk],e===null&&(e=void 0))),e===void 0?Kb:e}});var eg=g((J0,Zb)=>{"use strict";var ak=Jb();Zb.exports=function(a,e){return new(ak(a))(e===0?0:e)}});var tg=g(()=>{"use strict";var sk=Te(),nk=zb(),ok=wt(),uk=qi(),lk=Gi(),ck=eg();sk({target:"Array",proto:!0},{flatMap:function(e){var t=uk(this),i=lk(t),r;return ok(e),r=ck(t,0),r.length=nk(r,t,t,i,0,1,e,arguments.length>1?arguments[1]:void 0),r}})});var ig=g(()=>{"use strict";var dk=qr();dk("flatMap")});var ag=g((rV,rg)=>{"use strict";tg();ig();var pk=Jt();rg.exports=pk("Array","flatMap")});var ng=g((aV,sg)=>{"use strict";var hk=ag();sg.exports=hk});var da=g((sV,og)=>{"use strict";var fk=ng();og.exports=fk});var pa=g((nV,ug)=>{"use strict";var mk=Hr(),bk=String;ug.exports=function(a){if(mk(a)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return bk(a)}});var ml=g((oV,lg)=>{"use strict";lg.exports=`
7
+ \v\f\r                 \u2028\u2029\uFEFF`});var pg=g((uV,dg)=>{"use strict";var gk=Ae(),Sk=Xt(),vk=pa(),gl=ml(),cg=gk("".replace),yk=RegExp("^["+gl+"]+"),Tk=RegExp("(^|[^"+gl+"])["+gl+"]+$"),bl=function(a){return function(e){var t=vk(Sk(e));return a&1&&(t=cg(t,yk,"")),a&2&&(t=cg(t,Tk,"$1")),t}};dg.exports={start:bl(1),end:bl(2),trim:bl(3)}});var bg=g((lV,mg)=>{"use strict";var Ik=Go().PROPER,Ek=we(),hg=ml(),fg="​…᠎";mg.exports=function(a){return Ek(function(){return!!hg[a]()||fg[a]()!==fg||Ik&&hg[a].name!==a})}});var Sl=g((cV,gg)=>{"use strict";var xk=pg().start,wk=bg();gg.exports=wk("trimStart")?function(){return xk(this)}:"".trimStart});var vg=g(()=>{"use strict";var Ak=Te(),Sg=Sl();Ak({target:"String",proto:!0,name:"trimStart",forced:"".trimLeft!==Sg},{trimLeft:Sg})});var Tg=g(()=>{"use strict";vg();var Pk=Te(),yg=Sl();Pk({target:"String",proto:!0,name:"trimStart",forced:"".trimStart!==yg},{trimStart:yg})});var Eg=g((mV,Ig)=>{"use strict";Tg();var kk=Jt();Ig.exports=kk("String","trimLeft")});var wg=g((bV,xg)=>{"use strict";var Rk=Eg();xg.exports=Rk});var Pg=g((gV,Ag)=>{"use strict";var $k=wg();Ag.exports=$k});var Ug=g(()=>{"use strict"});var Hg=g(()=>{"use strict"});var Wg=g((JO,jg)=>{"use strict";var Kk=qe(),Xk=hi(),Jk=Le(),Zk=Jk("match");jg.exports=function(a){var e;return Kk(a)&&((e=a[Zk])!==void 0?!!e:Xk(a)==="RegExp")}});var zg=g((ZO,Gg)=>{"use strict";var eR=Se(),tR=we(),Qg=eR.RegExp,iR=!tR(function(){var a=!0;try{Qg(".","d")}catch{a=!1}var e={},t="",i=a?"dgimsy":"gimsy",r=function(o,l){Object.defineProperty(e,o,{get:function(){return t+=l,!0}})},s={dotAll:"s",global:"g",ignoreCase:"i",multiline:"m",sticky:"y"};a&&(s.hasIndices="d");for(var n in s)r(n,s[n]);var u=Object.getOwnPropertyDescriptor(Qg.prototype,"flags").get.call(e);return u!==i||t!==i});Gg.exports={correct:iR}});var Kg=g((eF,Yg)=>{"use strict";var rR=At();Yg.exports=function(){var a=rR(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 Zg=g((tF,Jg)=>{"use strict";var aR=Xe(),sR=mt(),nR=Cr(),Xg=zg(),oR=Kg(),uR=RegExp.prototype;Jg.exports=Xg.correct?function(a){return a.flags}:function(a){return!Xg.correct&&nR(uR,a)&&!sR(a,"flags")?aR(oR,a):a.flags}});var tS=g((iF,eS)=>{"use strict";var Il=Ae(),lR=qi(),cR=Math.floor,yl=Il("".charAt),dR=Il("".replace),Tl=Il("".slice),pR=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,hR=/\$([$&'`]|\d{1,2})/g;eS.exports=function(a,e,t,i,r,s){var n=t+a.length,u=i.length,o=hR;return r!==void 0&&(r=lR(r),o=pR),dR(s,o,function(l,p){var c;switch(yl(p,0)){case"$":return"$";case"&":return a;case"`":return Tl(e,0,t);case"'":return Tl(e,n);case"<":c=r[Tl(p,1,-1)];break;default:var d=+p;if(d===0)return l;if(d>u){var h=cR(d/10);return h===0?l:h<=u?i[h-1]===void 0?yl(p,1):i[h-1]+yl(p,1):l}c=i[d-1]}return c===void 0?"":c})}});var aS=g(()=>{"use strict";var fR=Te(),mR=Xe(),xl=Ae(),iS=Xt(),bR=ve(),gR=qe(),SR=Wg(),mr=pa(),vR=Vr(),yR=Zg(),TR=tS(),IR=Le(),ER=ft(),xR=IR("replace"),wR=TypeError,El=xl("".indexOf),AR=xl("".replace),rS=xl("".slice),PR=Math.max;fR({target:"String",proto:!0},{replaceAll:function(e,t){var i=iS(this),r,s,n,u,o,l,p,c,d,h,m=0,b="";if(gR(e)){if(r=SR(e),r&&(s=mr(iS(yR(e))),!~El(s,"g")))throw new wR("`.replaceAll` does not allow non-global regexes");if(n=vR(e,xR),n)return mR(n,e,i,t);if(ER&&r)return AR(mr(i),e,t)}for(u=mr(i),o=mr(e),l=bR(t),l||(t=mr(t)),p=o.length,c=PR(1,p),d=El(u,o);d!==-1;)h=l?mr(t(o,d,u)):TR(o,u,d,[],void 0,t),b+=rS(u,m,d)+h,m=d+p,d=d+c>u.length?-1:El(u,o,d+c);return m<u.length&&(b+=rS(u,m)),b}})});var nS=g((sF,sS)=>{"use strict";Ug();Hg();aS();var kR=Jt();sS.exports=kR("String","replaceAll")});var uS=g((nF,oS)=>{"use strict";var RR=nS();oS.exports=RR});var cS=g((oF,lS)=>{"use strict";var $R=uS();lS.exports=$R});var pS=g((uF,dS)=>{"use strict";var LR=Nr(),MR=pa(),DR=Xt(),CR=RangeError;dS.exports=function(e){var t=MR(DR(this)),i="",r=LR(e);if(r<0||r===1/0)throw new CR("Wrong number of repetitions");for(;r>0;(r>>>=1)&&(t+=t))r&1&&(i+=t);return i}});var gS=g((lF,bS)=>{"use strict";var mS=Ae(),BR=Bo(),hS=pa(),VR=pS(),_R=Xt(),OR=mS(VR),FR=mS("".slice),NR=Math.ceil,fS=function(a){return function(e,t,i){var r=hS(_R(e)),s=BR(t),n=r.length,u=i===void 0?" ":hS(i),o,l;return s<=n||u===""?r:(o=s-n,l=OR(u,NR(o/u.length)),l.length>o&&(l=FR(l,0,o)),a?r+l:l+r)}};bS.exports={start:fS(!1),end:fS(!0)}});var vS=g((cF,SS)=>{"use strict";var qR=bi();SS.exports=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(qR)});var yS=g(()=>{"use strict";var UR=Te(),HR=gS().start,jR=vS();UR({target:"String",proto:!0,forced:jR},{padStart:function(e){return HR(this,e,arguments.length>1?arguments[1]:void 0)}})});var IS=g((hF,TS)=>{"use strict";yS();var WR=Jt();TS.exports=WR("String","padStart")});var xS=g((fF,ES)=>{"use strict";var QR=IS();ES.exports=QR});var AS=g((mF,wS)=>{"use strict";var GR=xS();wS.exports=GR});var T$={};Cv(T$,{ChromecastState:()=>kr,HttpConnectionType:()=>fs,Observable:()=>Ct.Observable,PlaybackState:()=>_e,Player:()=>as,PredefinedQualityLimits:()=>Rr,SDK_VERSION:()=>y$,Subject:()=>Ct.Subject,Subscription:()=>Ct.Subscription,Surface:()=>ms,VERSION:()=>ro,ValueSubject:()=>Ct.ValueSubject,VideoFormat:()=>xt,VideoQuality:()=>Ct.VideoQuality,areValidLiveRecordSources:()=>sb,clientChecker:()=>j,isMobile:()=>ar});module.exports=Bv(T$);var ro="2.0.146-dev.0b43ee9b.0";var _e=(r=>(r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused",r))(_e||{}),xt=(x=>(x.MPEG="MPEG",x.DASH="DASH",x.DASH_SEP="DASH_SEP",x.DASH_SEP_VK="DASH_SEP",x.DASH_WEBM="DASH_WEBM",x.DASH_WEBM_AV1="DASH_WEBM_AV1",x.DASH_STREAMS="DASH_STREAMS",x.DASH_WEBM_VK="DASH_WEBM",x.DASH_ONDEMAND="DASH_ONDEMAND",x.DASH_ONDEMAND_VK="DASH_ONDEMAND",x.DASH_LIVE="DASH_LIVE",x.DASH_LIVE_CMAF="DASH_LIVE_CMAF",x.DASH_LIVE_WEBM="DASH_LIVE_WEBM",x.HLS="HLS",x.HLS_ONDEMAND="HLS_ONDEMAND",x.HLS_JS="HLS",x.HLS_FMP4="HLS_FMP4",x.HLS_LIVE="HLS_LIVE",x.HLS_LIVE_CMAF="HLS_LIVE_CMAF",x.WEB_RTC_LIVE="WEB_RTC_LIVE",x))(xt||{});var kr=(r=>(r.NOT_AVAILABLE="NOT_AVAILABLE",r.AVAILABLE="AVAILABLE",r.CONNECTING="CONNECTING",r.CONNECTED="CONNECTED",r))(kr||{}),fs=(i=>(i.HTTP1="http1",i.HTTP2="http2",i.QUIC="quic",i))(fs||{});var ms=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(ms||{}),Rr=(i=>(i.TRAFFIC_SAVING="traffic_saving",i.HIGH_QUALITY="high_quality",i.UNKNOWN="unknown",i))(Rr||{});var ec=Q(Si(),1),xv=Q(Oe(),1);var J=require("@vkontakte/videoplayer-shared");var Sp=a=>new Promise((e,t)=>{let i=document.createElement("script");i.setAttribute("src",a),i.onload=()=>e(),i.onerror=r=>t(r),document.body.appendChild(i)});var Es=class{constructor(e){this.connection$=new J.ValueSubject(void 0);this.castState$=new J.ValueSubject("NOT_AVAILABLE");this.errorEvent$=new J.Subject;this.realCastState$=new J.ValueSubject("NOT_AVAILABLE");this.subscription=new J.Subscription;this.isDestroyed=!1;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 i=(0,J.isNonNullable)(window.chrome?.cast),r=!!window.__onGCastApiAvailable;i?this.initializeCastApi():(window.__onGCastApiAvailable=s=>{delete window.__onGCastApiAvailable,s&&!this.isDestroyed&&this.initializeCastApi()},r||Sp("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:J.ErrorCategory.NETWORK,message:"Script loading failed!"})))}connect(){cast.framework.CastContext.getInstance()?.requestSession()}disconnect(){cast.framework.CastContext.getInstance()?.getCurrentSession()?.endSession(!0)}stopMedia(){return new Promise((e,t)=>{cast.framework.CastContext.getInstance()?.getCurrentSession()?.getMediaSession()?.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){(0,J.isNonNullable)(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();(0,J.isNullable)(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();(0,J.isNullable)(t)||e!==t.remotePlayer.isMuted&&t.remotePlayerController.muteOrUnmute()}destroy(){this.isDestroyed=!0,this.subscription.unsubscribe()}initListeners(){let e=new cast.framework.RemotePlayer,t=new cast.framework.RemotePlayerController(e),i=cast.framework.CastContext.getInstance();this.subscription.add((0,J.fromEvent)(i,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(r=>{switch(r.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=i.getCurrentSession()?.getMediaSession()?.media?.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return(0,J.assertNever)(r.sessionState)}})).add((0,J.merge)((0,J.fromEvent)(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe((0,J.tap)(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),(0,J.map)(r=>r.castState)),(0,J.observableFrom)([i.getCastState()])).pipe((0,J.filterChanged)(),(0,J.map)($I),(0,J.tap)(r=>{this.log({message:`realCastState$: ${r}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{let s=r==="CONNECTED",n=(0,J.isNonNullable)(this.connection$.getValue());if(s&&!n){let u=i.getCurrentSession();(0,J.assertNonNullable)(u);let o=u.getCastDevice(),l=u.getMediaSession()?.media?.contentId;((0,J.isNullable)(l)||l===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:u,castDevice:o}))}else!s&&n&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(r==="CONNECTED"?(0,J.isNonNullable)(this.connection$.getValue())?"CONNECTED":"AVAILABLE":r)}))}initializeCastApi(){let e,t,i;try{e=cast.framework.CastContext.getInstance(),t=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,i=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch{return}try{e.setOptions({receiverApplicationId:this.params.receiverApplicationId??t,autoJoinPolicy:i}),this.initListeners()}catch(r){this.errorEvent$.next({id:"ChromecastInitializer",category:J.ErrorCategory.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:r})}}},$I=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(0,J.assertNever)(a)}};var Xl=Q(Oe(),1),dv=Q(zi(),1),pv=Q(uu(),1);var ob=Q(zs(),1);var zu=require("@vkontakte/videoplayer-shared");var ye=(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 i=new URL(a);return i.searchParams.append("playback_shift",e.toFixed(0)),i.toString()}case 2:{let i=new URL(a);return!i.searchParams.get("offset_p")&&e===0?a:(i.searchParams.set("offset_p",e.toFixed(0)),i.toString())}default:(0,zu.assertNever)(t)}return a},ei=(a,e)=>{switch(e){case 0:return NaN;case 1:{let t=new URL(a);return Number(t.searchParams.get("playback_shift"))}case 2:{let t=new URL(a);return Number(t.searchParams.get("offset_p")??0)}default:(0,zu.assertNever)(e)}};var B=(a,e,t=!1)=>{let i=a.getTransition();(t||!i||i.to===e)&&a.setState(e)};var Pt=require("@vkontakte/videoplayer-shared"),Z=class{constructor(e){this.transitionStarted$=new Pt.Subject;this.transitionEnded$=new Pt.Subject;this.transitionUpdated$=new Pt.Subject;this.forceChanged$=new Pt.Subject;this.stateChangeStarted$=(0,Pt.merge)(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=(0,Pt.merge)(this.transitionEnded$,this.forceChanged$);this.state=e,this.prevState=void 0}setState(e){let t=this.transition,i=this.state;this.transition=void 0,this.prevState=i,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:i,to:e,canceledTransition:t})}startTransitionTo(e){let t=this.transition,i=this.state;i===e||(0,Pt.isNonNullable)(t)&&t.to===e||(this.prevState=i,this.state=e,t?(this.transition={from:t.from,to:e,canceledTransition:t},this.transitionUpdated$.next(this.transition)):(this.transition={from:i,to:e},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}getPrevState(){return this.prevState}};var Ku=require("@vkontakte/videoplayer-shared");var Xm=Q(Oe(),1);var Ys=class{constructor(){this._isMiuiBrowser=!1}get current(){return this._current}get isChrome(){return this.current==="Chrome"}get isChromiumBased(){return(0,Xm.default)(["Chrome","Chromium","Opera","Yandex","Edge","SamsungBrowser"],this.current)}get isFirefox(){return this.current==="Firefox"}get isSafari(){return this.current==="Safari"}get isOpera(){return this.current==="Opera"}get isEdge(){return this.current==="Edge"}get isYandex(){return this.current==="Yandex"}get isSamsungBrowser(){return this.current==="SamsungBrowser"}get currentVersion(){return this._current_version}get chromeVersion(){return this._chromeVersion}get firefoxVersion(){return this._firefoxVersion}get safariVersion(){return this._safariVersion}get operaVersion(){return this._operaVersion}get edgeVersion(){return this._edgeVersion}get yandexVersion(){return this._yandexVersion}get isMiuiBrowser(){return this._isMiuiBrowser}detect(){let{userAgent:e}=navigator;try{let t=/yabrowser/i.test(e)?"Yandex":void 0,i=/samsungbrowser/i.test(e)?"SamsungBrowser":void 0,r=/chrome|crios/i.test(e)?"Chrome":void 0,s=/chromium/i.test(e)?"Chromium":void 0,n=/firefox|fxios/i.test(e)?"Firefox":void 0,u=/webkit|safari|khtml/i.test(e)?"Safari":void 0,o=/opr\//i.test(e)?"Opera":void 0,l=/edg/i.test(e)?"Edge":void 0;this._isMiuiBrowser=/(XiaoMi)|(MiuiBrowser)/i.test(e),this._current=t||i||n||o||l||r||s||u||"Rest"}catch(t){console.error(t)}this.isChrome&&this.detectChromeVersion(),this.isFirefox&&this.detectFirefoxVersion(),this.isSafari&&this.detectSafariVersion(),this.isOpera&&this.detectOperaVersion(),this.isEdge&&this.detectEdgeVersion(),this.isYandex&&this.detectYandexVersion()}detectVersion(e){try{let{userAgent:t}=window.navigator,i=t.match(e);if(!i)return;let r=i[1],s=parseInt(r,10);if(!isNaN(s))return this._current_version=s,s}catch(t){console.error(t)}}detectChromeVersion(){this._chromeVersion=this.detectVersion(/Chrome\/(\d+\.\d+)/)}detectFirefoxVersion(){this._firefoxVersion=this.detectVersion(/Firefox\/(\d+\.\d+)/)}detectSafariVersion(){this._safariVersion=this.detectVersion(/Version\/(\d+)/)}detectOperaVersion(){this._operaVersion=this.detectVersion(/OPR\/(\d+\.\d+)/)}detectEdgeVersion(){this._edgeVersion=this.detectVersion(/Edg\/(\d+\.\d+)/)}detectYandexVersion(){this._yandexVersion=this.detectVersion(/YaBrowser\/(\d+\.\d+\.\d+)/)}};var Jm=Q(Oe(),1);var ar=()=>/Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test(navigator.appVersion??navigator.userAgent)||navigator?.userAgentData?.mobile;var Ks=class{constructor(e){this._highEntropyValues={};this._displayChecker=e}get current(){return this._current}get isIOS(){let e=["iPhone","iPad","iPod"];return this._highEntropyValues.platform==="iOS"||(0,Jm.default)(e,this.current)}get isMac(){return this._highEntropyValues.platform==="macOS"||this.current==="Mac"}get isApple(){return this.isIOS||this.isMac}get isIphoneOrOldIpad(){if(!this.isApple||!this._displayChecker.isTouch)return!1;let e=this.current==="iPad"||this._displayChecker.width>700,t=this._iosVersion;return!e||e&&!!t&&t<16}get isAndroid(){return this._highEntropyValues.platform==="Android"||this.current==="Android"}get isMobile(){return this._highEntropyValues.mobile||this._isMobile}get iOSVersion(){return this._iosVersion}detect(){let{userAgent:e}=navigator;try{this._isMobile=ar()}catch(t){console.error(t)}this.detectDevice(e),this.detectHighEntropyValues(),this.isIOS&&this.detectIOSVersion()}async detectHighEntropyValues(){let{userAgentData:e}=navigator;if(e?.getHighEntropyValues){let t=await e.getHighEntropyValues(["architecture","bitness","brands","mobile","platform","formFactor","model","platformVersion","wow64"]);this._highEntropyValues=t}}detectDevice(e){try{let t=/android/i.test(e)?"Android":void 0,i=/iphone/i.test(e)?"iPhone":void 0,r=/ipad/i.test(e)?"iPad":void 0,s=/ipod/i.test(e)?"iPod":void 0,n=/mac/i.test(e)?"Mac":void 0,u=/webOS|BlackBerry|IEMobile|Opera Mini/i.test(e)?"RestMobile":void 0;this._current=t||i||r||s||u||n||"Desktop"}catch(t){console.error(t)}}detectIOSVersion(){try{if(this._highEntropyValues.platformVersion){let s=this._highEntropyValues.platformVersion.split(".").slice(0,2).join("."),n=parseFloat(s);this._iosVersion=n;return}let{userAgent:e}=window.navigator,t=e.match(/OS (\d+(_\d+)?)/i);if(!t)return;let i=t[1].replace(/_/g,".");if(!i)return;let r=parseFloat(i);if(isNaN(r))return;this._iosVersion=r}catch(e){console.error(e)}}};var Xs=class{get isTouch(){return typeof this._maxTouchPoints=="number"?this._maxTouchPoints>1:"ontouchstart"in window}get maxTouchPoints(){return this._maxTouchPoints}get height(){return this._height}get width(){return this._width}get screenHeight(){return this._screenHeight}get screenWidth(){return this._screenWidth}get pixelRatio(){return this._pixelRatio}get isHDR(){return this._isHdr}get colorDepth(){return this._colorDepth}detect(){let{maxTouchPoints:e}=navigator;try{this._maxTouchPoints=e??0,this._isHdr=!!matchMedia("(dynamic-range: high)")?.matches,this._colorDepth=screen.colorDepth}catch(t){console.error(t)}try{this._pixelRatio=window.devicePixelRatio||1,this._height=screen.height,this._width=screen.width,this._height=screen.height,this._screenHeight=this._height*this._pixelRatio,this._screenWidth=this._width*this._pixelRatio}catch(t){console.error(t)}}};var Ze=()=>window.ManagedMediaSource||window.MediaSource,sr=()=>!!(window.ManagedMediaSource&&window.ManagedSourceBuffer?.prototype?.appendBuffer),Zm=()=>!!(window.MediaSource&&window.SourceBuffer?.prototype?.appendBuffer),Js=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;var bP=document.createElement("video"),gP='video/mp4; codecs="avc1.42000a,mp4a.40.2"',SP='video/mp4; codecs="hev1.1.6.L93.B0"',eb='video/webm; codecs="vp09.00.10.08"',tb='video/webm; codecs="av01.0.00M.08"',vP='audio/mp4; codecs="mp4a.40.2"',yP='audio/webm; codecs="opus"',ib,TP=async()=>{if(!window.navigator.mediaCapabilities)return;let a={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=await Promise.all([window.navigator.mediaCapabilities.decodingInfo({...a,video:{...a.video,contentType:tb}}),window.navigator.mediaCapabilities.decodingInfo({...a,video:{...a.video,contentType:eb}})]);ib={DASH_WEBM_AV1:e,DASH_WEBM:t}};TP().catch(a=>{console.log(bP),console.error(a)});var Zs=class{constructor(e,t){this._deviceChecker=e,this._browserChecker=t}get protocols(){return this._protocols}get containers(){return this._containers}get codecs(){return this._codecs}get webmDecodingInfo(){return ib}get supportedCodecs(){return Object.keys(this._codecs).filter(e=>this._codecs[e])}get nativeHlsSupported(){return this._nativeHlsSupported}detect(){this._video=document.createElement("video");try{this._protocols={mms:sr(),mse:Zm(),hls:!!(this._video.canPlayType?.("application/x-mpegurl")||this._video.canPlayType?.("vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},this._containers={mp4:!!this._video.canPlayType?.("video/mp4"),webm:!!this._video.canPlayType?.("video/webm"),cmaf:!0};let e=!!Ze()?.isTypeSupported?.(gP),t=!!Ze()?.isTypeSupported?.(SP),i=!!Ze()?.isTypeSupported?.(vP);this._codecs={h264:e,h265:t,vp9:!!Ze()?.isTypeSupported?.(eb),av1:!!Ze()?.isTypeSupported?.(tb),aac:i,opus:!!Ze()?.isTypeSupported?.(yP),mpeg:(e||t)&&i},this._nativeHlsSupported=this._protocols.hls&&this._containers.mp4}catch(e){console.error(e)}try{this.destroyVideoElement()}catch(e){console.error("Error destroying video element:",e)}}destroyVideoElement(){if(!this._video)return;if(this._video.pause(),this._video.currentTime=0,this._video.removeAttribute("src"),this._video.src="",this._video.load(),this._video.remove){this._video.remove(),this._video=null;return}this._video.parentNode&&this._video.parentNode.removeChild(this._video);let e=this._video.cloneNode(!1);this._video.parentNode?.replaceChild(e,this._video),this._video=null}};var rb="audio/mpeg",en=class{supportMp3(){return this._codecs.mp3&&this._containers.mpeg}detect(){this._audio=document.createElement("audio");try{this._containers={mpeg:!!this._audio.canPlayType?.(rb)},this._codecs={mp3:!!Ze()?.isTypeSupported?.(rb)}}catch(e){console.error(e)}try{this.destroyAudioElement()}catch(e){console.error("Error destroying audio element:",e)}}destroyAudioElement(){if(!this._audio)return;if(this._audio.pause(),this._audio.currentTime=0,this._audio.removeAttribute("src"),this._audio.src="",this._audio.load(),this._audio.remove){this._audio.remove(),this._audio=null;return}this._audio.parentNode&&this._audio.parentNode.removeChild(this._audio);let e=this._audio.cloneNode(!1);this._audio.parentNode?.replaceChild(e,this._audio),this._audio=null}};var ab=require("@vkontakte/videoplayer-shared"),Yu=class{constructor(){this.isInited$=new ab.ValueSubject(!1);this._displayChecker=new Xs,this._deviceChecker=new Ks(this._displayChecker),this._browserChecker=new Ys,this._videoChecker=new Zs(this._deviceChecker,this._browserChecker),this._audioChecker=new en,this.detect()}get display(){return this._displayChecker}get device(){return this._deviceChecker}get browser(){return this._browserChecker}get video(){return this._videoChecker}get audio(){return this._audioChecker}async detect(){this._displayChecker.detect(),this._deviceChecker.detect(),this._browserChecker.detect(),this._videoChecker.detect(),this._audioChecker.detect(),this.isInited$.next(!0)}},j=new Yu;var Xu=a=>{let{containers:e,protocols:t,codecs:i,nativeHlsSupported:r}=j.video,s=(i.h264||i.h265)&&i.aac,n=t.mse||t.mms;return a.filter(u=>{switch(u){case"DASH_SEP":return n&&e.mp4&&s;case"DASH_WEBM":return n&&e.webm&&i.vp9&&i.opus;case"DASH_WEBM_AV1":return n&&e.webm&&i.av1&&i.opus;case"DASH_STREAMS":return n&&(e.mp4&&s||e.webm&&(i.vp9||i.av1)&&(i.opus||i.aac));case"DASH_LIVE":return n&&e.mp4&&s;case"DASH_LIVE_CMAF":return n&&e.mp4&&s&&e.cmaf;case"DASH_ONDEMAND":return n&&e.mp4&&s;case"HLS":case"HLS_ONDEMAND":case"HLS_FMP4":case"HLS_LIVE":case"HLS_LIVE_CMAF":return r;case"MPEG":return e.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return t.webrtc&&t.ws&&i.h264&&(e.mp4||e.webm);default:return(0,Ku.assertNever)(u)}})},Ju=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_FMP4":case"HLS_ONDEMAND":return!1;case"DASH_LIVE":case"DASH_LIVE_CMAF":case"HLS_LIVE":case"HLS_LIVE_CMAF":case"DASH_LIVE_WEBM":case"WEB_RTC_LIVE":return!0;default:return(0,Ku.assertNever)(a)}},sb=a=>{let t=Object.keys(a).filter(i=>!Ju(i));return Xu(t).length>0};var q=require("@vkontakte/videoplayer-shared");var IP=5,EP=5,xP=500,nb=7e3,ea=class{constructor(e){this.subscription=new q.Subscription;this.loadMediaTimeoutSubscription=new q.Subscription;this.videoState=new Z("stopped");this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(s)};`}),i==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.stop());return}if(!t){if(r?.to!=="paused"&&s.state==="requested"&&e!=="stopped"){this.seek(s.position/1e3);return}switch(i){case"ready":{switch(e){case"playing":case"paused":case"ready":break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:(0,q.assertNever)(e)}break}case"playing":{switch(e){case"playing":break;case"paused":this.videoState.startTransitionTo("playing"),this.params.connection.remotePlayerController.playOrPause();break;case"ready":this.videoState.startTransitionTo("playing"),this.params.connection.remotePlayerController.playOrPause();break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:(0,q.assertNever)(e)}break}case"paused":{switch(e){case"playing":this.videoState.startTransitionTo("paused"),this.params.connection.remotePlayerController.playOrPause();break;case"paused":break;case"ready":this.videoState.startTransitionTo("paused"),this.videoState.setState("paused");break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:(0,q.assertNever)(e)}break}default:(0,q.assertNever)(i)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(Ju(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 q.Subscription;this.subscription.add(e),this.subscription.add((0,q.merge)(this.videoState.stateChangeStarted$.pipe((0,q.map)(r=>`stateChangeStarted$ ${JSON.stringify(r)}`)),this.videoState.stateChangeEnded$.pipe((0,q.map)(r=>`stateChangeEnded$ ${JSON.stringify(r)}`))).subscribe(r=>this.log({message:`[videoState] ${r}`})));let t=(r,s)=>this.subscription.add(r.subscribe(s));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{let r=new q.Subject;e.add(r.pipe((0,q.debounce)(xP)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add((0,q.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe(n=>{this.logRemoteEvent(n);let u=n.value;this.params.output.position$.next(u),(this.params.desiredState.seekState.getState().state==="applying"||Math.abs(u-s)>IP)&&r.next(u),s=u})),e.add((0,q.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t((0,q.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t((0,q.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemotePause():this.handleRemotePlay()}),t((0,q.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),r=>{this.logRemoteEvent(r);let{remotePlayer:s}=this.params.connection,n=r.value,u=this.params.output.isBuffering$.getValue(),o=n===chrome.cast.media.PlayerState.BUFFERING;switch(u!==o&&this.params.output.isBuffering$.next(o),n){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&s.duration-s.currentTime<EP&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),B(this.params.desiredState.playbackState,"stopped");break;case chrome.cast.media.PlayerState.PAUSED:{this.handleRemotePause();break}case chrome.cast.media.PlayerState.PLAYING:this.handleRemotePlay();break;case chrome.cast.media.PlayerState.BUFFERING:break;default:(0,q.assertNever)(n)}}),t((0,q.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t((0,q.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({muted:r.value})});let i=(0,q.merge)(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,q.observableFrom)(["init"])).pipe((0,q.debounce)(0));t(i,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"),B(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),B(this.params.desiredState.playbackState,"playing"));let i=this.params.output.isLive$.getValue();this.params.output.duration$.next(i?0:t.duration),this.params.output.position$.next(i?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),i=this.createLoadRequest(t);this.loadMedia(i)}handleRemotePause(){let e=this.videoState.getState();(this.videoState.getTransition()?.to==="paused"||e==="playing")&&(this.videoState.setState("paused"),B(this.params.desiredState.playbackState,"paused"))}handleRemotePlay(){let e=this.videoState.getState();(this.videoState.getTransition()?.to==="playing"||e==="paused")&&(this.videoState.setState("playing"),B(this.params.desiredState.playbackState,"playing"))}handleRemoteReady(){this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.params.desiredState.playbackState.getTransition()?.to==="ready"&&B(this.params.desiredState.playbackState,"ready")}handleRemoteStop(){this.videoState.getState()!=="stopped"&&this.videoState.setState("stopped")}handleRemoteVolumeChange(e){let t=this.params.output.volume$.getValue(),i={volume:e.volume??t.volume,muted:e.muted??t.muted};(i.volume!==t.volume||i.muted!==i.muted)&&this.params.output.volume$.next(i)}seek(e){this.params.output.willSeekEvent$.next();let{remotePlayer:t,remotePlayerController:i}=this.params.connection;t.currentTime=e,i.seek()}stop(){let{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){let t=this.params.source,i,r,s;switch(e){case"MPEG":{let l=t[e];(0,q.assertNonNullable)(l);let p=(0,q.getHighestQuality)(Object.keys(l));(0,q.assertNonNullable)(p);let c=l[p];(0,q.assertNonNullable)(c),i=c,r="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_FMP4":case"HLS_ONDEMAND":{let l=t[e];(0,q.assertNonNullable)(l),i=l.url,r="application/x-mpegurl",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":{let l=t[e];(0,q.assertNonNullable)(l),i=l.url,r="application/dash+xml",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let l=t[e];(0,q.assertNonNullable)(l),i=l.url,r="application/dash+xml",s=chrome.cast.media.StreamType.LIVE;break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let l=t[e];(0,q.assertNonNullable)(l),i=ye(l.url),r="application/x-mpegurl",s=chrome.cast.media.StreamType.LIVE;break}case"DASH_LIVE":case"WEB_RTC_LIVE":{let l="Unsupported format for Chromecast",p=new Error(l);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:q.ErrorCategory.VIDEO_PIPELINE,message:l,thrown:p}),p}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return(0,q.assertNever)(e)}let n=new chrome.cast.media.MediaInfo(this.params.meta.videoId??i,r);n.contentUrl=i,n.streamType=s,n.metadata=new chrome.cast.media.GenericMediaMetadata;let{title:u,subtitle:o}=this.params.meta;return(0,q.isNonNullable)(u)&&(n.metadata.title=u),(0,q.isNonNullable)(o)&&(n.metadata.subtitle=o),n}createLoadRequest(e){let t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;let i=this.params.desiredState.seekState.getState();return i.state==="applying"||i.state==="requested"?t.currentTime=this.params.output.isLive$.getValue()?0:i.position/1e3:t.currentTime=0,t}loadMedia(e){let t=this.params.connection.session.loadMedia(e),i=new Promise((r,s)=>{this.loadMediaTimeoutSubscription.add((0,q.timeout)(nb).subscribe(()=>s(`timeout(${nb})`)))});(0,ob.default)(Promise.race([t,i]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},r=>{let s=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${r}`;this.log({message:s}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:q.ErrorCategory.VIDEO_PIPELINE,message:s,thrown:r})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var pl=Q(Oe(),1);var il=require("@vkontakte/videoplayer-shared");var ub=require("@vkontakte/videoplayer-shared"),lb=a=>{try{a.pause(),a.playbackRate=0,(0,ub.clearVideoElement)(a),a.remove()}catch(e){console.error(e)}};var tn=require("@vkontakte/videoplayer-shared"),Zu=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)}},el=window.WeakMap?new WeakMap:new Zu,tl=window.WeakMap?new WeakMap:new Map,wP=(a,e=20)=>{let t=0;return(0,tn.fromEvent)(a,"ratechange").subscribe(i=>{t++,t>=e&&(a.currentTime=a.currentTime,t=0)})},Ue=(a,{audioVideoSyncRate:e,disableYandexPiP:t})=>{let i=a.querySelector("video"),r=!!i;i?(0,il.clearVideoElement)(i):(i=document.createElement("video"),a.appendChild(i)),el.set(i,r);let s=new tn.Subscription;return s.add(wP(i,e)),tl.set(i,s),i.setAttribute("crossorigin","anonymous"),i.setAttribute("playsinline","playsinline"),t&&i.setAttribute("x-yandex-pip","false"),i.controls=!1,i.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),i},He=a=>{tl.get(a)?.unsubscribe(),tl.delete(a);let t=el.get(a);el.delete(a),t?(0,il.clearVideoElement)(a):lb(a)};var rl=Q(Si(),1),U=require("@vkontakte/videoplayer-shared");var ti=require("@vkontakte/videoplayer-shared"),rn=(a,e,t,{equal:i=(n,u)=>n===u,changed$:r,onError:s}={})=>{let n=a.getState(),u=e(),o=(0,ti.isNullable)(r),l=new ti.Subscription;return r&&l.add(r.subscribe(p=>{let c=a.getState();i(p,c)&&a.setState(p)},s)),i(u,n)||(t(n),o&&a.setState(n)),l.add(a.stateChangeStarted$.subscribe(p=>{t(p.to),o&&a.setState(p.to)},s)),l},kt=(a,e,t)=>rn(e,()=>a.loop,i=>{(0,ti.isNonNullable)(i)&&(a.loop=i)},{onError:t}),je=(a,e,t,i)=>rn(e,()=>({muted:a.muted,volume:a.volume}),r=>{(0,ti.isNonNullable)(r)&&(a.muted=r.muted,a.volume=r.volume)},{equal:(r,s)=>r===s||r?.muted===s?.muted&&r?.volume===s?.volume,changed$:t,onError:i}),nt=(a,e,t,i)=>rn(e,()=>a.playbackRate,r=>{(0,ti.isNonNullable)(r)&&(a.playbackRate=r)},{changed$:t,onError:i}),ta=rn;var AP=a=>["__",a.language,a.label].join("|"),PP=(a,e)=>{if(a.id===e)return!0;let[t,i,r]=e.split("|");return a.language===i&&a.label===r},al=class a{constructor(e){this.available$=new U.Subject;this.current$=new U.ValueSubject(void 0);this.error$=new U.Subject;this.subscription=new U.Subscription;this.externalTracks=new Map;this.internalTracks=new Map;this.baseURL=e}connect(e,t,i){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();let r=s=>{this.error$.next({id:"TextTracksManager",category:U.ErrorCategory.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:s})};this.subscription.add(this.available$.subscribe(i.availableTextTracks$)),this.subscription.add(this.current$.subscribe(i.currentTextTrack$)),this.subscription.add(this.error$.subscribe(i.error$)),this.subscription.add(ta(t.internalTextTracks,()=>(0,rl.default)(this.internalTracks),s=>{(0,U.isNonNullable)(s)&&this.setInternal(s)},{equal:(s,n)=>(0,U.isNonNullable)(s)&&(0,U.isNonNullable)(n)&&s.length===n.length&&s.every(({id:u},o)=>u===n[o].id),changed$:this.available$.pipe((0,U.map)(s=>s.filter(({type:n})=>n==="internal"))),onError:r})),this.subscription.add(ta(t.externalTextTracks,()=>(0,rl.default)(this.externalTracks),s=>{(0,U.isNonNullable)(s)&&this.setExternal(s)},{equal:(s,n)=>(0,U.isNonNullable)(s)&&(0,U.isNonNullable)(n)&&s.length===n.length&&s.every(({id:u},o)=>u===n[o].id),changed$:this.available$.pipe((0,U.map)(s=>s.filter(({type:n})=>n==="external"))),onError:r})),this.subscription.add(ta(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:r})),this.subscription.add(ta(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.activeCues)}))}subscribe(){(0,U.assertNonNullable)(this.video);let{textTracks:e}=this.video;this.subscription.add((0,U.fromEvent)(e,"addtrack").subscribe(()=>{let i=this.current$.getValue();i&&this.select(i)})),this.subscription.add((0,U.merge)((0,U.fromEvent)(e,"addtrack"),(0,U.fromEvent)(e,"removetrack"),(0,U.observableFrom)(["init"])).pipe((0,U.map)(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),(0,U.filterChanged)((i,r)=>i.length===r.length&&i.every(({id:s},n)=>s===r[n].id))).subscribe(this.available$)),this.subscription.add((0,U.merge)((0,U.fromEvent)(e,"change"),(0,U.observableFrom)(["init"])).pipe((0,U.map)(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),(0,U.map)(i=>i&&this.htmlTextTrackToITextTrack(i).id),(0,U.filterChanged)()).subscribe(this.current$));let t=i=>this.applyCueSettings(i.target?.activeCues??null);this.subscription.add((0,U.fromEvent)(e,"addtrack").subscribe(i=>{i.track?.addEventListener("cuechange",t);let r=s=>{let n=s.target?.cues??null;n&&n.length&&(this.applyCueSettings(s.target?.cues??null),s.target?.removeEventListener("cuechange",r))};i.track?.addEventListener("cuechange",r)})),this.subscription.add((0,U.fromEvent)(e,"removetrack").subscribe(i=>{i.track?.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;let t=this.cueSettings.getState();for(let i of Array.from(e)){let r=i;(0,U.isNonNullable)(t.align)&&(r.align=t.align),(0,U.isNonNullable)(t.position)&&(r.position=t.position),(0,U.isNonNullable)(t.size)&&(r.size=t.size),(0,U.isNonNullable)(t.line)&&(r.line=t.line)}}htmlTextTracksAsArray(e=!1){(0,U.assertNonNullable)(this.video);let t=[...this.video.textTracks];return e?t:t.filter(a.isHealthyTrack)}htmlTextTrackToITextTrack(e){let{language:t,label:i}=e,r=e.id?e.id:AP(e),s=this.externalTracks.has(r),n=(s?this.externalTracks.get(r)?.isAuto:this.internalTracks.get(r)?.isAuto)??r.includes("auto");return s?{id:r,type:"external",isAuto:n,language:t,label:i,url:this.externalTracks.get(r)?.url}:{id:r,type:"internal",isAuto:n,language:t,label:i,url:this.internalTracks.get(r)?.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(i=>i.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){let t=[...this.externalTracks];e.filter(({id:i,language:r,isAuto:s})=>!this.internalTracks.has(i)&&!t.some(([,n])=>n.language===r&&n.isAuto===s)).forEach(i=>this.attach(i)),Array.from(this.internalTracks).filter(([i])=>!e.find(r=>r.id===i)).forEach(([,i])=>this.detach(i))}select(e){(0,U.assertNonNullable)(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))((0,U.isNullable)(e)||!PP(t,e))&&(t.mode="disabled")}destroy(){if(this.subscription.unsubscribe(),this.video)for(let e of Array.from(this.video.getElementsByTagName("track"))){let t=e.getAttribute("id");t&&this.externalTracks.has(t)&&this.video.removeChild(e)}this.externalTracks.clear()}attach(e){(0,U.assertNonNullable)(this.video);let t=document.createElement("track");this.baseURL?t.setAttribute("src",new URL(e.url,this.baseURL).toString()):t.setAttribute("src",e.url),t.setAttribute("id",e.id),e.label&&t.setAttribute("label",e.label),e.language&&t.setAttribute("srclang",e.language),e.type==="external"?this.externalTracks.set(e.id,e):e.type==="internal"&&this.internalTracks.set(e.id,e),this.video.appendChild(t)}detach(e){(0,U.assertNonNullable)(this.video);let t=Array.prototype.find.call(this.video.getElementsByTagName("track"),i=>i.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)}},ot=al;var xi=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 cb=a=>{let e=a;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e?.parentNode;return e??void 0},sl=a=>{let e=cb(a);return!!(e&&e.fullscreenElement&&e.fullscreenElement===a)},db=a=>{let e=cb(a);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===a)};var $=require("@vkontakte/videoplayer-shared");var kP=3,pb=(a,e,t=kP)=>{let i=0,r=0;for(let s=0;s<a.length;s++){let n=a.start(s),u=a.end(s);if(n<=e&&e<=u){if(i=n,r=u,!t)return{from:i,to:r};for(let o=s-1;o>=0;o--)a.end(o)+t>=i&&(i=a.start(o));for(let o=s+1;o<a.length;o++)a.start(o)-t<=r&&(r=a.end(o))}}return{from:i,to:r}};var We=a=>{let e=L=>(0,$.fromEvent)(a,L).pipe((0,$.mapTo)(void 0),(0,$.shareReplay)(1)),t=new $.Subscription,i=()=>t.unsubscribe(),r=(0,$.merge)((0,$.fromEvent)(a,"progress"),(0,$.fromEvent)(a,"timeupdate")).pipe((0,$.map)(()=>pb(a.buffered,a.currentTime)),(0,$.shareReplay)(1)),s=j.browser.isSafari?(0,$.combine)({play:e("play").pipe((0,$.once)()),playing:e("playing")}).pipe((0,$.mapTo)(void 0),(0,$.shareReplay)(1)):e("playing"),n=(0,$.fromEvent)(a,"volumechange").pipe((0,$.map)(()=>({muted:a.muted,volume:a.volume})),(0,$.shareReplay)(1)),u=(0,$.fromEvent)(a,"ratechange").pipe((0,$.map)(()=>a.playbackRate),(0,$.shareReplay)(1)),o=(0,$.fromEvent)(a,"error").pipe((0,$.filter)(()=>!!(a.error||a.played.length)),(0,$.map)(()=>{let L=a.error;return{id:L?`MediaError#${L.code}`:"HtmlVideoError",category:$.ErrorCategory.VIDEO_PIPELINE,message:L?L.message:"Error event from HTML video element",thrown:a.error??void 0}}),(0,$.shareReplay)(1)),l=(0,$.fromEvent)(a,"timeupdate").pipe((0,$.map)(()=>a.currentTime),(0,$.shareReplay)(1)),p=["waiting","seeking","seeked","timeupdate"],c=new $.Subject,d=.3,h;t.add((0,$.merge)(...p.map(L=>(0,$.fromEvent)(a,L))).subscribe(L=>{let ee=a.currentTime;a.loop&&(0,$.isNonNullable)(h)&&(0,$.isNonNullable)(ee)&&h>=a.duration-d&&ee<=d&&c.next(h),h=ee}));let m=e("pause").pipe((0,$.filter)(()=>!a.error&&h!==a.duration),(0,$.shareReplay)(1)),b=(0,$.fromEvent)(a,"enterpictureinpicture").pipe((0,$.shareReplay)(1)),S=(0,$.fromEvent)(a,"leavepictureinpicture").pipe((0,$.shareReplay)(1)),v=new $.ValueSubject(db(a));t.add(b.subscribe(()=>v.next(!0))),t.add(S.subscribe(()=>v.next(!1)));let I=new $.ValueSubject(sl(a)),P=(0,$.fromEvent)(a,"fullscreenchange").pipe((0,$.shareReplay)(1));t.add(P.pipe((0,$.map)(()=>sl(a))).subscribe(I));let x=.1,C=1e3,V=(0,$.fromEvent)(a,"timeupdate").pipe((0,$.map)(L=>a.duration-a.currentTime<x),(0,$.filterChanged)(),(0,$.shareReplay)(1)),O=(0,$.merge)(V.pipe((0,$.filter)(L=>!a.loop&&L)),(0,$.fromEvent)(a,"ended")).pipe((0,$.throttle)(C),(0,$.mapTo)(void 0),(0,$.shareReplay)(1)),N=(0,$.merge)(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(L=>(0,$.fromEvent)(a,L)),V.pipe((0,$.map)(L=>({type:L?"ended":"unknown"})))).pipe((0,$.map)(L=>j.browser.isFirefox&&L.type==="ended"?a.readyState<2:a.readyState<3),(0,$.filterChanged)(),(0,$.shareReplay)(1));return{playing$:s,pause$:m,canplay$:e("canplay"),ended$:O,looped$:c,error$:o,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:l,durationChange$:(0,$.fromEvent)(a,"durationchange").pipe((0,$.map)(()=>a.duration),(0,$.shareReplay)(1)),isBuffering$:N,currentBuffer$:r,volumeState$:n,playbackRateState$:u,inPiP$:v,inFullscreen$:I,enterPip$:b,leavePip$:S,destroy:i}};var Ft=require("@vkontakte/videoplayer-shared"),ii=a=>{switch(a){case"mobile":return Ft.VideoQuality.Q_144P;case"lowest":return Ft.VideoQuality.Q_240P;case"low":return Ft.VideoQuality.Q_360P;case"sd":case"medium":return Ft.VideoQuality.Q_480P;case"hd":case"high":return Ft.VideoQuality.Q_720P;case"fullhd":case"full":return Ft.VideoQuality.Q_1080P;case"quadhd":case"quad":return Ft.VideoQuality.Q_1440P;case"ultrahd":case"ultra":return Ft.VideoQuality.Q_2160P}};var Ne=Q(gt(),1),ol=Q(Oe(),1),wi=Q(zi(),1),M=require("@vkontakte/videoplayer-shared");var nl=!1,Nt={},vb=a=>{nl=a},yb=()=>{Nt={}},Tb=a=>{a(Nt)},ia=(a,e)=>{nl&&(Nt.meta=Nt.meta??{},Nt.meta[a]=e)},Fe=class{constructor(e){this.name=e}next(e){if(!nl)return;Nt.series=Nt.series??{};let t=Nt.series[this.name]??[];t.push([Date.now(),e]),Nt.series[this.name]=t}};var Ie=require("@vkontakte/videoplayer-shared");function Ib(a,e,t){return!a.max&&a.min===e?"high_quality":!a.min&&a.max===t?"traffic_saving":"unknown"}function nr(a,e,t){return(0,Ie.isNullable)(a)||(0,Ie.isNonNullable)(a.min)&&(0,Ie.isNonNullable)(a.max)&&(0,Ie.isLower)(a.max,a.min)||(0,Ie.isNonNullable)(a.min)&&e&&(0,Ie.isHigher)(a.min,e)||(0,Ie.isNonNullable)(a.max)&&t&&(0,Ie.isLower)(a.max,t)}function Eb({limits:a,highestAvailableHeight:e,lowestAvailableHeight:t}){return nr({max:a?.max?(0,Ie.videoHeightToQuality)(a.max):void 0,min:a?.min?(0,Ie.videoHeightToQuality)(a.min):void 0},e?(0,Ie.videoHeightToQuality)(e):void 0,t?(0,Ie.videoHeightToQuality)(t):void 0)}var kb=new Fe("best_bitrate"),sn=(a,e,t)=>(e-t)*Math.pow(2,-10*a)+t;var or=a=>(e,t)=>a*(Number(e.bitrate)-Number(t.bitrate)),ri=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=(0,M.now)()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},nn='Assertion "ABR Tracks is empty array" failed',an=new WeakMap,xb=new WeakMap,wb=new WeakMap,ra=(a,e,t,i)=>{let r=[...e].sort(or(1)),s=[...t].sort(or(1)),n=s.filter(o=>(0,M.isNonNullable)(o.bitrate)&&(0,M.isNonNullable)(a.bitrate)?a.bitrate/o.bitrate>i:!0),u=(0,Ne.default)(s,Math.round(s.length*r.indexOf(a)/(r.length+1)))??(0,Ne.default)(s,-1);return u&&(0,ol.default)(n,u)?u:n.length?(0,Ne.default)(n,-1):(0,Ne.default)(s,0)},aa=(a,e,t,i)=>{let r=an.get(e);r||(r=[...e].sort(or(1)),an.set(e,r));let s=an.get(t);s||(s=[...t].sort(or(1)),an.set(t,s));let n=wb.get(a);n||(n=s.filter(o=>(0,M.isNonNullable)(o.bitrate)&&(0,M.isNonNullable)(a.bitrate)?a.bitrate/o.bitrate>i:!0),wb.set(a,n));let u=(0,Ne.default)(s,Math.round(s.length*r.indexOf(a)/(r.length+1)))??(0,Ne.default)(s,-1);return u&&(0,ol.default)(n,u)?u:n.length?(0,Ne.default)(n,-1):(0,Ne.default)(s,0)},Ab=a=>"quality"in a,on=(a,e,t,i)=>{let r=(0,M.isNonNullable)(i?.last?.bitrate)&&(0,M.isNonNullable)(t?.bitrate)&&i.last.bitrate<t.bitrate?a.trackCooldownIncreaseQuality:a.trackCooldownDecreaseQuality,s=t&&i&&i.history[t.id]&&(0,M.now)()-i.history[t.id]<=r&&(!i.last||t.id!==i.last.id);if(t?.id&&i&&!s&&i.recordSelection(t),s&&i?.last){let n=i.last;i?.recordSwitch(n);let u=Ab(n)?"video":"audio",o=Ab(n)?n.quality:n.bitrate;return e({message:`
8
8
  [last ${u} selected] ${o}
9
- `}),n}return i?.recordSwitch(t),t},_A=(a,e)=>Math.log(e)/Math.log(a),Rb=({tuning:a,container:e,limits:t,panelSize:i})=>{let r=a.containerSizeFactor;if(i)return{containerSizeLimit:i,containerSizeFactor:r};if(a.usePixelRatio&&j.display.pixelRatio){let s=j.display.pixelRatio;if(a.pixelRatioMultiplier)r*=a.pixelRatioMultiplier*(s-1)+1;else{let n=a.pixelRatioLogBase,[u=0,o=0,l=0]=a.pixelRatioLogCoefficients,p=_A(n,u*s+o)+l;Number.isFinite(p)&&(r*=p)}}return(0,M.isNonNullable)(t?.min)&&(0,M.isHigherOrEqual)(t.min,a.highQualityLimit)&&(r*=2),{containerSizeLimit:a.limitByContainer&&e&&e.width>0&&e.height>0?{width:e.width*r,height:e.height*r}:void 0,containerSizeFactor:r}},Ab=new WeakMap,Rt=(a,{container:e,estimatedThroughput:t,tuning:i,limits:r,reserve:s=0,forwardBufferHealth:n,playbackRate:u,current:o,history:l,visible:p,droppedVideoMaxQualityLimit:c,stallsVideoMaxQualityLimit:d,stallsPredictedThroughput:h,abrLogger:m,panelSize:b})=>{(0,M.assertNotEmptyArray)(a,nn);let{containerSizeFactor:S,containerSizeLimit:v}=Rb({container:e,tuning:i,limits:r,panelSize:b}),I=i.considerPlaybackRate&&(0,M.isNonNullable)(u)?u:1,A=Ab.get(a);A||(A=a.filter(R=>!(0,M.isInvariantQuality)(R.quality)).sort((R,P)=>(0,M.isHigher)(R.quality,P.quality)?-1:1),Ab.set(a,A));let x=(0,Ne.default)(A,-1)?.quality,C=(0,Ne.default)(A,0)?.quality,V=nr(r,C,x),O=I*sn(n??.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),D={},N=null;for(let R of A){let P=!0;if(v)if(R.size)P=R.size.width<=v.width&&R.size.height<=v.height;else{let se=v&&(0,M.videoSizeToQuality)(v);P=se?(0,M.isLowerOrEqual)(R.quality,se):!0}if(!P){D[R.quality]="FitsContainer";continue}let te=h||t,_=(0,M.isNonNullable)(te)&&isFinite(te)&&(0,M.isNonNullable)(R.bitrate)?te-s>=R.bitrate*O:!0,ae=r?.min===R.quality;if(!_&&!ae){D[R.quality]="FitsThroughput";continue}if(i.lazyQualitySwitch&&(0,M.isNonNullable)(i.minBufferToSwitchUp)&&o&&!(0,M.isInvariantQuality)(o.quality)&&(n??0)<i.minBufferToSwitchUp&&(0,M.isHigher)(R.quality,o.quality)){D[R.quality]="Buffer";continue}if(!!c&&(0,M.isHigherOrEqual)(R.quality,c)&&!ae){D[R.quality]="DroppedFramesLimit";continue}if(!!d&&(0,M.isHigherOrEqual)(R.quality,d)&&!ae){D[R.quality]="StallsLimit";continue}let Pe=V||((0,M.isNullable)(r?.max)||(0,M.isLowerOrEqual)(R.quality,r.max))&&((0,M.isNullable)(r?.min)||(0,M.isHigherOrEqual)(R.quality,r.min)),Re=(0,M.isNonNullable)(p)&&!p?(0,M.isLowerOrEqual)(R.quality,i.backgroundVideoQualityLimit):!0;if(!Pe||!Re){D[R.quality]="FitsQualityLimits";continue}N||(N=R)}N&&N.bitrate&&Pb.next(N.bitrate);let L=N??(0,Ne.default)(A,-1)??a[0],ee=l?.last,W=on(i,m,L,l);return(0,M.isNonNullable)(l)&&W.quality!==ee?.quality&&m({message:`
9
+ `}),n}return i?.recordSwitch(t),t},_P=(a,e)=>Math.log(e)/Math.log(a),Rb=({tuning:a,container:e,limits:t,panelSize:i})=>{let r=a.containerSizeFactor;if(i)return{containerSizeLimit:i,containerSizeFactor:r};if(a.usePixelRatio&&j.display.pixelRatio){let s=j.display.pixelRatio;if(a.pixelRatioMultiplier)r*=a.pixelRatioMultiplier*(s-1)+1;else{let n=a.pixelRatioLogBase,[u=0,o=0,l=0]=a.pixelRatioLogCoefficients,p=_P(n,u*s+o)+l;Number.isFinite(p)&&(r*=p)}}return(0,M.isNonNullable)(t?.min)&&(0,M.isHigherOrEqual)(t.min,a.highQualityLimit)&&(r*=2),{containerSizeLimit:a.limitByContainer&&e&&e.width>0&&e.height>0?{width:e.width*r,height:e.height*r}:void 0,containerSizeFactor:r}},Pb=new WeakMap,Rt=(a,{container:e,estimatedThroughput:t,tuning:i,limits:r,reserve:s=0,forwardBufferHealth:n,playbackRate:u,current:o,history:l,visible:p,droppedVideoMaxQualityLimit:c,stallsVideoMaxQualityLimit:d,stallsPredictedThroughput:h,abrLogger:m,panelSize:b})=>{(0,M.assertNotEmptyArray)(a,nn);let{containerSizeFactor:S,containerSizeLimit:v}=Rb({container:e,tuning:i,limits:r,panelSize:b}),I=i.considerPlaybackRate&&(0,M.isNonNullable)(u)?u:1,P=Pb.get(a);P||(P=a.filter(R=>!(0,M.isInvariantQuality)(R.quality)).sort((R,k)=>(0,M.isHigher)(R.quality,k.quality)?-1:1),Pb.set(a,P));let x=(0,Ne.default)(P,-1)?.quality,C=(0,Ne.default)(P,0)?.quality,V=nr(r,C,x),O=I*sn(n??.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),D={},N=null;for(let R of P){let k=!0;if(v)if(R.size)k=R.size.width<=v.width&&R.size.height<=v.height;else{let se=v&&(0,M.videoSizeToQuality)(v);k=se?(0,M.isLowerOrEqual)(R.quality,se):!0}if(!k){D[R.quality]="FitsContainer";continue}let te=h||t,_=(0,M.isNonNullable)(te)&&isFinite(te)&&(0,M.isNonNullable)(R.bitrate)?te-s>=R.bitrate*O:!0,ae=r?.min===R.quality;if(!_&&!ae){D[R.quality]="FitsThroughput";continue}if(i.lazyQualitySwitch&&(0,M.isNonNullable)(i.minBufferToSwitchUp)&&o&&!(0,M.isInvariantQuality)(o.quality)&&(n??0)<i.minBufferToSwitchUp&&(0,M.isHigher)(R.quality,o.quality)){D[R.quality]="Buffer";continue}if(!!c&&(0,M.isHigherOrEqual)(R.quality,c)&&!ae){D[R.quality]="DroppedFramesLimit";continue}if(!!d&&(0,M.isHigherOrEqual)(R.quality,d)&&!ae){D[R.quality]="StallsLimit";continue}let ke=V||((0,M.isNullable)(r?.max)||(0,M.isLowerOrEqual)(R.quality,r.max))&&((0,M.isNullable)(r?.min)||(0,M.isHigherOrEqual)(R.quality,r.min)),Re=(0,M.isNonNullable)(p)&&!p?(0,M.isLowerOrEqual)(R.quality,i.backgroundVideoQualityLimit):!0;if(!ke||!Re){D[R.quality]="FitsQualityLimits";continue}N||(N=R)}N&&N.bitrate&&kb.next(N.bitrate);let L=N??(0,Ne.default)(P,-1)??a[0],ee=l?.last,W=on(i,m,L,l);return(0,M.isNonNullable)(l)&&W.quality!==ee?.quality&&m({message:`
10
10
  [VIDEO TRACKS ABR]
11
11
  [available video tracks]
12
12
  ${a.map(R=>`{ id: ${R.id}, quality: ${R.quality}, bitrate: ${R.bitrate}, size: ${R.size?.width}:${R.size?.height} }`).join(`
13
13
  `)}
14
14
 
15
15
  [tuning]
16
- ${(0,wi.default)(i??{}).map(([R,P])=>`${R}: ${P}`).join(`
16
+ ${(0,wi.default)(i??{}).map(([R,k])=>`${R}: ${k}`).join(`
17
17
  `)}
18
18
 
19
19
  [limit params]
@@ -34,19 +34,19 @@
34
34
  minQualityLimit: ${r?.min},
35
35
 
36
36
  [limited video tracks]
37
- ${(0,wi.default)(D).map(([R,P])=>`${R}: ${P}`).join(`
37
+ ${(0,wi.default)(D).map(([R,k])=>`${R}: ${k}`).join(`
38
38
  `)||"All tracks are available"}
39
39
 
40
40
  [best video track] ${N?.quality}
41
41
  [selected video track] ${W?.quality}
42
- `}),W},un=(a,{container:e,estimatedThroughput:t,tuning:i,limits:r,reserve:s=0,forwardBufferHealth:n,playbackRate:u,current:o,history:l,visible:p,droppedVideoMaxQualityLimit:c,stallsVideoMaxQualityLimit:d,stallsPredictedThroughput:h,abrLogger:m,panelSize:b})=>{(0,M.assertNotEmptyArray)(a,nn);let{containerSizeFactor:S,containerSizeLimit:v}=Rb({container:e,tuning:i,limits:r,panelSize:b}),I=i.considerPlaybackRate&&(0,M.isNonNullable)(u)?u:1,A=a.filter(P=>!(0,M.isInvariantQuality)(P.quality)).sort((P,te)=>(0,M.isHigher)(P.quality,te.quality)?-1:1),x=(0,Ne.default)(A,-1)?.quality,C=(0,Ne.default)(A,0)?.quality,V=nr(r,C,x),O=I*sn(n??.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),D={},L=A.filter(P=>{let te=!0;if(v)if(P.size)te=P.size.width<=v.width&&P.size.height<=v.height;else{let ie=v&&(0,M.videoSizeToQuality)(v);te=ie?(0,M.isLowerOrEqual)(P.quality,ie):!0}if(!te)return D[P.quality]="FitsContainer",!1;let _=h||t,ae=(0,M.isNonNullable)(_)&&isFinite(_)&&(0,M.isNonNullable)(P.bitrate)?_-s>=P.bitrate*O:!0,le=r?.min===P.quality;if(!ae&&!le)return D[P.quality]="FitsThroughput",!1;if(i.lazyQualitySwitch&&(0,M.isNonNullable)(i.minBufferToSwitchUp)&&o&&!(0,M.isInvariantQuality)(o.quality)&&(n??0)<i.minBufferToSwitchUp&&(0,M.isHigher)(P.quality,o.quality))return D[P.quality]="Buffer",!1;if(!!c&&(0,M.isHigherOrEqual)(P.quality,c)&&!le)return D[P.quality]="DroppedFramesLimit",!1;if(!!d&&(0,M.isHigherOrEqual)(P.quality,d)&&!le)return D[P.quality]="StallsLimit",!1;let Re=V||((0,M.isNullable)(r?.max)||(0,M.isLowerOrEqual)(P.quality,r.max))&&((0,M.isNullable)(r?.min)||(0,M.isHigherOrEqual)(P.quality,r.min)),se=(0,M.isNonNullable)(p)&&!p?(0,M.isLowerOrEqual)(P.quality,i.backgroundVideoQualityLimit):!0;return!Re||!se?(D[P.quality]="FitsQualityLimits",!1):!0})[0];L&&L.bitrate&&Pb.next(L.bitrate);let ee=L??(0,Ne.default)(A,-1)??a[0],W=l?.last,R=on(i,m,ee,l);return(0,M.isNonNullable)(l)&&R.quality!==W?.quality&&m({message:`
42
+ `}),W},un=(a,{container:e,estimatedThroughput:t,tuning:i,limits:r,reserve:s=0,forwardBufferHealth:n,playbackRate:u,current:o,history:l,visible:p,droppedVideoMaxQualityLimit:c,stallsVideoMaxQualityLimit:d,stallsPredictedThroughput:h,abrLogger:m,panelSize:b})=>{(0,M.assertNotEmptyArray)(a,nn);let{containerSizeFactor:S,containerSizeLimit:v}=Rb({container:e,tuning:i,limits:r,panelSize:b}),I=i.considerPlaybackRate&&(0,M.isNonNullable)(u)?u:1,P=a.filter(k=>!(0,M.isInvariantQuality)(k.quality)).sort((k,te)=>(0,M.isHigher)(k.quality,te.quality)?-1:1),x=(0,Ne.default)(P,-1)?.quality,C=(0,Ne.default)(P,0)?.quality,V=nr(r,C,x),O=I*sn(n??.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),D={},L=P.filter(k=>{let te=!0;if(v)if(k.size)te=k.size.width<=v.width&&k.size.height<=v.height;else{let ie=v&&(0,M.videoSizeToQuality)(v);te=ie?(0,M.isLowerOrEqual)(k.quality,ie):!0}if(!te)return D[k.quality]="FitsContainer",!1;let _=h||t,ae=(0,M.isNonNullable)(_)&&isFinite(_)&&(0,M.isNonNullable)(k.bitrate)?_-s>=k.bitrate*O:!0,le=r?.min===k.quality;if(!ae&&!le)return D[k.quality]="FitsThroughput",!1;if(i.lazyQualitySwitch&&(0,M.isNonNullable)(i.minBufferToSwitchUp)&&o&&!(0,M.isInvariantQuality)(o.quality)&&(n??0)<i.minBufferToSwitchUp&&(0,M.isHigher)(k.quality,o.quality))return D[k.quality]="Buffer",!1;if(!!c&&(0,M.isHigherOrEqual)(k.quality,c)&&!le)return D[k.quality]="DroppedFramesLimit",!1;if(!!d&&(0,M.isHigherOrEqual)(k.quality,d)&&!le)return D[k.quality]="StallsLimit",!1;let Re=V||((0,M.isNullable)(r?.max)||(0,M.isLowerOrEqual)(k.quality,r.max))&&((0,M.isNullable)(r?.min)||(0,M.isHigherOrEqual)(k.quality,r.min)),se=(0,M.isNonNullable)(p)&&!p?(0,M.isLowerOrEqual)(k.quality,i.backgroundVideoQualityLimit):!0;return!Re||!se?(D[k.quality]="FitsQualityLimits",!1):!0})[0];L&&L.bitrate&&kb.next(L.bitrate);let ee=L??(0,Ne.default)(P,-1)??a[0],W=l?.last,R=on(i,m,ee,l);return(0,M.isNonNullable)(l)&&R.quality!==W?.quality&&m({message:`
43
43
  [VIDEO TRACKS ABR]
44
44
  [available video tracks]
45
- ${a.map(P=>`{ id: ${P.id}, quality: ${P.quality}, bitrate: ${P.bitrate}, size: ${P.size?.width}:${P.size?.height} }`).join(`
45
+ ${a.map(k=>`{ id: ${k.id}, quality: ${k.quality}, bitrate: ${k.bitrate}, size: ${k.size?.width}:${k.size?.height} }`).join(`
46
46
  `)}
47
47
 
48
48
  [tuning]
49
- ${(0,wi.default)(i??{}).map(([P,te])=>`${P}: ${te}`).join(`
49
+ ${(0,wi.default)(i??{}).map(([k,te])=>`${k}: ${te}`).join(`
50
50
  `)}
51
51
 
52
52
  [limit params]
@@ -67,19 +67,19 @@
67
67
  minQualityLimit: ${r?.min},
68
68
 
69
69
  [limited video tracks]
70
- ${(0,wi.default)(D).map(([P,te])=>`${P}: ${te}`).join(`
70
+ ${(0,wi.default)(D).map(([k,te])=>`${k}: ${te}`).join(`
71
71
  `)||"All tracks are available"}
72
72
 
73
73
  [best video track] ${L?.quality}
74
74
  [selected video track] ${R?.quality}
75
- `}),R},ln=(a,e,t,{estimatedThroughput:i,tuning:r,playbackRate:s,forwardBufferHealth:n,history:u,abrLogger:o,stallsPredictedThroughput:l})=>{(0,M.assertNotEmptyArray)(t,nn);let p=r.considerPlaybackRate&&(0,M.isNonNullable)(s)?s:1,c=[...t].sort(or(-1)),d=a.bitrate;(0,M.assertNonNullable)(d);let h=p*sn(n??.5,r.bitrateAudioFactorAtEmptyBuffer,r.bitrateAudioFactorAtFullBuffer),m,b=ra(a,e,t,r.minVideoAudioRatio),S=l||i;(0,M.isNonNullable)(S)&&isFinite(S)&&(m=c.find(A=>(0,M.isNonNullable)(A.bitrate)&&(0,M.isNonNullable)(b?.bitrate)?S-d>=A.bitrate*h&&A.bitrate>=b.bitrate:!1)),m||(m=b);let v=u?.last,I=m&&on(r,o,m,u);return(0,M.isNonNullable)(u)&&I?.bitrate!==v?.bitrate&&o({message:`
75
+ `}),R},ln=(a,e,t,{estimatedThroughput:i,tuning:r,playbackRate:s,forwardBufferHealth:n,history:u,abrLogger:o,stallsPredictedThroughput:l})=>{(0,M.assertNotEmptyArray)(t,nn);let p=r.considerPlaybackRate&&(0,M.isNonNullable)(s)?s:1,c=[...t].sort(or(-1)),d=a.bitrate;(0,M.assertNonNullable)(d);let h=p*sn(n??.5,r.bitrateAudioFactorAtEmptyBuffer,r.bitrateAudioFactorAtFullBuffer),m,b=ra(a,e,t,r.minVideoAudioRatio),S=l||i;(0,M.isNonNullable)(S)&&isFinite(S)&&(m=c.find(P=>(0,M.isNonNullable)(P.bitrate)&&(0,M.isNonNullable)(b?.bitrate)?S-d>=P.bitrate*h&&P.bitrate>=b.bitrate:!1)),m||(m=b);let v=u?.last,I=m&&on(r,o,m,u);return(0,M.isNonNullable)(u)&&I?.bitrate!==v?.bitrate&&o({message:`
76
76
  [AUDIO TRACKS ABR]
77
77
  [available audio tracks]
78
- ${t.map(A=>`{ id: ${A.id}, bitrate: ${A.bitrate} }`).join(`
78
+ ${t.map(P=>`{ id: ${P.id}, bitrate: ${P.bitrate} }`).join(`
79
79
  `)}
80
80
 
81
81
  [tuning]
82
- ${(0,wi.default)(r??{}).map(([A,x])=>`${A}: ${x}`).join(`
82
+ ${(0,wi.default)(r??{}).map(([P,x])=>`${P}: ${x}`).join(`
83
83
  `)}
84
84
 
85
85
  [limit params]
@@ -93,14 +93,14 @@
93
93
  minBufferToSwitchUp: ${r.minBufferToSwitchUp},
94
94
 
95
95
  [selected audio track] ${I?.id}
96
- `}),I},cn=(a,e,t,{estimatedThroughput:i,tuning:r,playbackRate:s,forwardBufferHealth:n,history:u,abrLogger:o,stallsPredictedThroughput:l})=>{(0,M.assertNotEmptyArray)(t,nn);let p=r.considerPlaybackRate&&(0,M.isNonNullable)(s)?s:1,c=xb.get(t);c||(c=[...t].sort(or(-1)),xb.set(t,c));let d=a.bitrate;(0,M.assertNonNullable)(d);let h=p*sn(n??.5,r.bitrateAudioFactorAtEmptyBuffer,r.bitrateAudioFactorAtFullBuffer),m,b=aa(a,e,t,r.minVideoAudioRatio),S=l||i;(0,M.isNonNullable)(S)&&isFinite(S)&&(m=c.find(A=>(0,M.isNonNullable)(A.bitrate)&&(0,M.isNonNullable)(b?.bitrate)?S-d>=A.bitrate*h&&A.bitrate>=b.bitrate:!1)),m||(m=b);let v=u?.last,I=m&&on(r,o,m,u);return(0,M.isNonNullable)(u)&&I?.bitrate!==v?.bitrate&&o({message:`
96
+ `}),I},cn=(a,e,t,{estimatedThroughput:i,tuning:r,playbackRate:s,forwardBufferHealth:n,history:u,abrLogger:o,stallsPredictedThroughput:l})=>{(0,M.assertNotEmptyArray)(t,nn);let p=r.considerPlaybackRate&&(0,M.isNonNullable)(s)?s:1,c=xb.get(t);c||(c=[...t].sort(or(-1)),xb.set(t,c));let d=a.bitrate;(0,M.assertNonNullable)(d);let h=p*sn(n??.5,r.bitrateAudioFactorAtEmptyBuffer,r.bitrateAudioFactorAtFullBuffer),m,b=aa(a,e,t,r.minVideoAudioRatio),S=l||i;(0,M.isNonNullable)(S)&&isFinite(S)&&(m=c.find(P=>(0,M.isNonNullable)(P.bitrate)&&(0,M.isNonNullable)(b?.bitrate)?S-d>=P.bitrate*h&&P.bitrate>=b.bitrate:!1)),m||(m=b);let v=u?.last,I=m&&on(r,o,m,u);return(0,M.isNonNullable)(u)&&I?.bitrate!==v?.bitrate&&o({message:`
97
97
  [AUDIO TRACKS ABR]
98
98
  [available audio tracks]
99
- ${t.map(A=>`{ id: ${A.id}, bitrate: ${A.bitrate} }`).join(`
99
+ ${t.map(P=>`{ id: ${P.id}, bitrate: ${P.bitrate} }`).join(`
100
100
  `)}
101
101
 
102
102
  [tuning]
103
- ${(0,wi.default)(r??{}).map(([A,x])=>`${A}: ${x}`).join(`
103
+ ${(0,wi.default)(r??{}).map(([P,x])=>`${P}: ${x}`).join(`
104
104
  `)}
105
105
 
106
106
  [limit params]
@@ -114,14 +114,14 @@
114
114
  minBufferToSwitchUp: ${r.minBufferToSwitchUp},
115
115
 
116
116
  [selected audio track] ${I?.id}
117
- `}),I};var Me=a=>new URL(a).hostname;var Y=require("@vkontakte/videoplayer-shared");var Bb=Q(gt(),1);var Lb=Q(Oe(),1),$b=a=>{if(a instanceof DOMException&&(0,Lb.default)(["Failed to load because no supported source was found.","The element has no supported sources."],a.message))throw a;return!(a instanceof DOMException&&(a.code===20||a.name==="AbortError"))},Qe=async(a,e)=>{let t=a.muted;try{await a.play()}catch(i){if(!$b(i))return!1;if(e&&e(),t)return console.warn(i),!1;a.muted=!0;try{await a.play()}catch(r){return $b(r)&&(a.muted=!1,console.warn(r)),!1}}return!0};var et=require("@vkontakte/videoplayer-shared");var Mb=Q(Si(),1),$t=require("@vkontakte/videoplayer-shared");function Ae(){return(0,$t.now)()}function ul(a){return Ae()-a}function ll(a){let e=a.split("/"),t=e.slice(0,e.length-1).join("/"),i=/^([a-z]+:)?\/\//i,r=n=>i.test(n);return{resolve:(n,u,o=!1)=>{r(n)||(n.startsWith("/")||(n="/"+n),n=t+n);let l=n.indexOf("?")>-1?"&":"?";return o&&(n+=l+"lowLat=1",l="&"),u&&(n+=l+"_rnd="+Math.floor(999999999*Math.random())),n}}}function Db(a,e,t){let i=(...r)=>{t.apply(null,r),a.removeEventListener(e,i)};a.addEventListener(e,i)}function ur(a,e,t,i){let r=window.XMLHttpRequest,s,n,u,o=!1,l=0,p,c,d=!1,h="arraybuffer",m=7e3,b=2e3,S=()=>{if(o)return;(0,$t.assertNonNullable)(p);let W=ul(p),R;if(W<b){R=b-W,setTimeout(S,R);return}b*=2,b>m&&(b=m),n&&n.abort(),n=new r,V()},v=W=>(s=W,ee),I=W=>(c=W,ee),A=()=>(h="json",ee),x=()=>{if(!o){if(--l>=0){S(),i&&i();return}o=!0,c&&c(),t&&t()}},C=W=>(d=W,ee),V=()=>{p=Ae(),n=new r,n.open("get",a);let W=0,R,P=0,te=()=>((0,$t.assertNonNullable)(p),Math.max(p,Math.max(R||0,P||0)));if(s&&n.addEventListener("progress",_=>{let ae=Ae();s.updateChunk&&_.loaded>W&&(s.updateChunk(te(),_.loaded-W),W=_.loaded,R=ae)}),u&&(n.timeout=u,n.addEventListener("timeout",()=>x())),n.addEventListener("load",()=>{if(o)return;(0,$t.assertNonNullable)(n);let _=n.status;if(_>=200&&_<300){let{response:ae,responseType:le}=n,ge=ae?.byteLength;if(typeof ge=="number"&&s){let Ee=ge-W;Ee&&s.updateChunk&&s.updateChunk(te(),Ee)}le==="json"&&(!ae||!(0,Mb.default)(ae).length)?x():(c&&c(),e(ae))}else x()}),n.addEventListener("error",()=>{x()}),d){let _=()=>{(0,$t.assertNonNullable)(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(P=Ae(),n.removeEventListener("readystatechange",_))};n.addEventListener("readystatechange",_)}return n.responseType=h,n.send(),ee},ee={withBitrateReporting:v,withParallel:C,withJSONResponse:A,withRetryCount:W=>(l=W,ee),withRetryInterval:(W,R)=>((0,$t.isNonNullable)(W)&&(b=W),(0,$t.isNonNullable)(R)&&(m=R),ee),withTimeout:W=>(u=W,ee),withFinally:I,send:V,abort:()=>{n&&(n.abort(),n=void 0),o=!0,c&&c()}};return ee}var sa=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,i){return{start:e,end:t,bytes:i}}_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 i=0,r=0;for(;this.intervals.length>0;){let s=this.intervals[0];if(s.end<=t)i+=s.end-s.start,r+=s.bytes,this.intervals.splice(0,1);else{if(s.start>=t)break;{let n=t-s.start,u=s.end-s.start;i+=n;let o=s.bytes*n/u;r+=o,s.start=t,s.bytes-=o}}}if(r>0&&i>0){let s=r*8/(i/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(r)}/${Math.round(i)} 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,i){return this.intervals.push(this._createInterval(e,t,i)),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 Cb=Q(Si(),1);var na=class{constructor(e,t,i,r,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=i,this.MAX_PARALLEL_REQUESTS=r,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 i=Ae(),r=o=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=o,e._errorCB?e._errorCB(o):(this.limitCompleteCount(),this.completeRequests[t]=e)},s=o=>{e._complete=1,e._responseData=o,e._downloadTime=Ae()-i,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(o,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},n=()=>{e._finallyCB&&e._finallyCB()},u=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=ur(t,s,()=>r("error"),u),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=Ae()}_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=Ae();if(Object.keys(this.activeRequests).length>=e)return!1;let i=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),i>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),i),!1):!0}_sendPending(){for(;this._canSendPending();){let e=this.pendingQueue.pop();if(e){if(this.activeRequests[e]||this.completeRequests[e])continue;this.logger(`Submitting pending request url=${e}`),this._sendRequest({},e)}else return}}_removeFromActive(e){delete this.completeRequests[e],delete this.activeRequests[e]}abortAll(){(0,Cb.default)(this.activeRequests).forEach(e=>{e&&e._request&&e._request.abort()}),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,i,r){let s={};return s.send=()=>{let n=this.activeRequests[e]||this.completeRequests[e];if(n)n._cb=t,n._errorCB=i,n._retryCB=r,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}`),i(n._errorMsg)),s._finallyCB&&s._finallyCB()},0)):this.logger(`Attached to active request, url=${e}`);else{let u=this.pendingQueue.indexOf(e);u!==-1&&this.pendingQueue.splice(u,1),this.logger(`Request not prefetched, starting new request, url=${e}${u===-1?"":"; removed pending"}`),this._sendRequest(s,e)}},s._cb=t,s._errorCB=i,s._retryCB=r,s.abort=function(){s.request&&s.request.abort()},s.withFinally=n=>(s._finallyCB=n,s),s}prefetch(e){this.activeRequests[e]||this.completeRequests[e]?this.logger(`Request already active for url=${e}`):(this.logger(`Added to pending queue; url=${e}`),this.pendingQueue.unshift(e),this._sendPending())}optimizeForSegDuration(e){this.averageSegmentDuration=e}};var Vb=require("@vkontakte/videoplayer-shared");var dn=1e4,cl=3;var FA=6e4,NA=10,qA=1,UA=500,oa=class{constructor(e){this.paused=!1;this.autoQuality=!0;this.autoQualityLimits=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.waitingForFirstBufferAfterSrcChange=!1;this.params=e,this.soundProhibitedEvent$=new Vb.Subject,this.chunkRateEstimator=new sa(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=ll(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setAutoQualityLimits(e){this.autoQualityLimits=e}switchByName(e){let t;for(let i=0;i<this.manifest.length;++i)if(t=this.manifest[i],t.name===e){this._switchToQuality(t);return}}catchUp(){if(this.rep&&this.rep.stop(),this.currentManifestEntry){let e=this.params.playbackState.getState();this.paused=e==="paused",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=ll(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,i=e.buffered.length;return i!==0&&(t=e.buffered.end(i-1)-Math.max(e.currentTime,e.buffered.start(0))),t}_notifyBuffering(e){this.destroyed||(this.params.logger(`buffering: ${e}`),this.params.playerCallback({name:"buffering",isBuffering:e}),this.buffering=e)}_initVideo(){let{videoElement:e,logger:t}=this.params;e.addEventListener("error",()=>{!!e.error&&!this.destroyed&&(t(`Video element error: ${e.error?.code}, details: ${e.error?.message}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{let i=this._getBufferSizeSec();!this.paused&&i<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(i+.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,i=t.buffered.length,r;i!==0&&!this.waitingForFirstBufferAfterSrcChange&&(r=t.buffered.start(i-1),t.currentTime<r&&(e("Fixup stall"),t.currentTime=r))}_selectQuality(e){let{videoElement:t}=this.params,i,r,s,n=t&&1.62*(j.display.pixelRatio||1)*t.offsetHeight||520;for(let u=0;u<this.manifest.length;++u){s=this.manifest[u];let{max:o,min:l}=this.autoQualityLimits||{};!Eb({limits:this.autoQualityLimits,highestAvailableHeight:this.manifest[0].video.height,lowestAvailableHeight:(0,Bb.default)(this.manifest,-1).video.height})&&(o&&s.video.height>o||l&&s.video.height<l)||(s.bitrate<e&&n>Math.min(s.video.height,s.video.width)?(!r||s.bitrate>r.bitrate)&&(r=s):(!i||i.bitrate>s.bitrate)&&(i=s))}return r||i}shouldPlay(){if(this.paused)return!1;let t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||(0,et.isNonNullable)(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){let{logger:i,videoElement:r,playerCallback:s}=this.params;this.mediaSource=new window.MediaSource,i("setting video src"),r.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.videoPlayStarted=!1,r.addEventListener("canplay",()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});let n=()=>{Db(r,"progress",()=>{r.buffered.length?(r.currentTime=r.buffered.start(0),this.waitingForFirstBufferAfterSrcChange=!1,s({name:"playing"})):n()})};this.waitingForFirstBufferAfterSrcChange=!0,n()}_initPlayerWith(e){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new na(cl,dn,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){let{logger:t,videoElement:i,playerCallback:r}=this.params,s=!1,n=null,u=null,o=null,l=null,p=!1,c=()=>{let x=s&&(!p||p===this.rep);return x||t("Not running!"),x},d=(x,C,V)=>{o&&o.abort(),o=ur(this.urlResolver.resolve(x,!1),C,V,()=>this._retryCallback()).withTimeout(dn).withBitrateReporting(this.bitrateSwitcher).withRetryCount(cl).withFinally(()=>{o=null}).send()},h=(x,C,V)=>{(0,et.assertNonNullable)(this.filesFetcher),u?.abort(),u=this.filesFetcher.requestData(this.urlResolver.resolve(x,!1),C,V,()=>this._retryCallback()).withFinally(()=>{u=null}).send()},m=x=>{let C=i.playbackRate;i.playbackRate!==x&&(t(`Playback rate switch: ${C}=>${x}`),i.playbackRate=x)},b=x=>{this.lowLatency=x,t(`lowLatency changed to ${x}`),S()},S=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)m(1);else{let x=this._getBufferSizeSec();if(this.bufferStates.length<5){m(1);return}let V=Ae()-1e4,O=0;for(let N=0;N<this.bufferStates.length;N++){let L=this.bufferStates[N];x=Math.min(x,L.buf),L.ts<V&&O++}this.bufferStates.splice(0,O),t(`update playback rate; minBuffer=${x} drop=${O} jitter=${this.sourceJitter}`);let D=x-qA;this.sourceJitter>=0?D-=this.sourceJitter/2:this.sourceJitter-=1,D>3?m(1.15):D>1?m(1.1):D>.3?m(1.05):m(1)}},v=x=>{let C,V=()=>C&&C.start?C.start.length:0,O=_=>C.start[_]/1e3,D=_=>C.dur[_]/1e3,N=_=>C.fragIndex+_,L=(_,ae)=>({chunkIdx:N(_),startTS:O(_),dur:D(_),discontinuity:ae}),ee=()=>{let _=0;if(C&&C.dur){let ae=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,le=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,ge=ae;this.sourceJitter>1&&(ge+=this.sourceJitter-1);let Ee=C.dur.length-1;for(;Ee>=0&&(ge-=C.dur[Ee],!(ge<=0));--Ee);_=Math.min(Ee,C.dur.length-1-le),_=Math.max(_,0)}return L(_,!0)},W=_=>{let ae=V();if(!(ae<=0)){if((0,et.isNonNullable)(_)){for(let le=0;le<ae;le++)if(O(le)>_)return L(le)}return ee()}},R=_=>{let ae=V(),le=_?_.chunkIdx+1:0,ge=le-C.fragIndex;if(!(ae<=0)){if(!_||ge<0||ge-ae>NA)return t(`Resync: offset=${ge} bChunks=${ae} chunk=`+JSON.stringify(_)),ee();if(!(ge>=ae))return L(le-C.fragIndex,!1)}},P=(_,ae,le)=>{l&&l.abort(),l=ur(this.urlResolver.resolve(_,!0,this.lowLatency),ae,le,()=>this._retryCallback()).withTimeout(dn).withRetryCount(cl).withFinally(()=>{l=null}).withJSONResponse().send()};return{seek:(_,ae)=>{P(x,le=>{if(!c())return;C=le;let ge=!!C.lowLatency;ge!==this.lowLatency&&b(ge);let Ee=0;for(let Pe=0;Pe<C.dur.length;++Pe)Ee+=C.dur[Pe];Ee>0&&((0,et.assertNonNullable)(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(Ee/C.dur.length)),r({name:"index",zeroTime:C.zeroTime,shiftDuration:C.shiftDuration}),this.sourceJitter=C.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,C.jitter/1e3)):1,_(W(ae))},()=>this._handleNetworkError())},nextChunk:R}},I=()=>{s=!1,u&&u.abort(),o&&o.abort(),l&&l.abort(),(0,et.assertNonNullable)(this.filesFetcher),this.filesFetcher.abortAll()};return p={start:x=>{let{videoElement:C,logger:V}=this.params,O=v(e.jidxUrl),D,N,L,ee,W=0,R,P,te,_=()=>{R&&(clearTimeout(R),R=void 0);let ie=Math.max(UA,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),$e=W+ie,Be=Ae(),xe=Math.min(1e4,$e-Be);W=Be;let at=()=>{l||c()&&O.seek(()=>{c()&&(W=Ae(),ae(),_())})};xe>0?R=window.setTimeout(()=>{this.paused?_():at()},xe):at()},ae=()=>{let ie;for(;ie=O.nextChunk(ee);)ee=ie,Re(ie);let $e=O.nextChunk(L);if($e){if(L&&$e.discontinuity){V("Detected discontinuity; restarting playback"),this.paused?_():(I(),this._initPlayerWith(e));return}Pe($e)}else _()},le=(ie,$e)=>{if(!c()||!this.sourceBuffer)return;let Be,xe,at,Gt=yt=>{window.setTimeout(()=>{c()&&le(ie,$e)},yt)};if(this.sourceBuffer.updating)V("Source buffer is updating; delaying appendBuffer"),Gt(100);else{let yt=Ae(),Ye=C.currentTime;!this.paused&&C.buffered.length>1&&P===Ye&&yt-te>500&&(V("Stall suspected; trying to fix"),this._fixupStall()),P!==Ye&&(P=Ye,te=yt);let zt=this._getBufferSizeSec();if(zt>30)V(`Buffered ${zt} seconds; delaying appendBuffer`),Gt(2e3);else try{this.sourceBuffer.appendBuffer(ie),this.videoPlayStarted?(this.bufferStates.push({ts:yt,buf:zt}),S(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),$e&&$e()}catch(Tt){if(Tt.name==="QuotaExceededError")V("QuotaExceededError; delaying appendBuffer"),at=this.sourceBuffer.buffered.length,at!==0&&(Be=this.sourceBuffer.buffered.start(0),xe=Ye,xe-Be>4&&this.sourceBuffer.remove(Be,xe-3)),Gt(1e3);else throw Tt}}},ge=()=>{N&&D&&(V([`Appending chunk, sz=${N.byteLength}:`,JSON.stringify(L)]),le(N,function(){N=null,ae()}))},Ee=ie=>e.fragUrlTemplate.replace("%%id%%",ie.chunkIdx),Pe=ie=>{c()&&h(Ee(ie),($e,Be)=>{if(c()){if(Be/=1e3,N=$e,L=ie,n=ie.startTS,Be){let xe=Math.min(10,ie.dur/Be);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*xe:xe}ge()}},()=>this._handleNetworkError())},Re=ie=>{c()&&((0,et.assertNonNullable)(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(Ee(ie),!1)))},se=ie=>{c()&&(e.cachedHeader=ie,le(ie,()=>{D=!0,ge()}))};s=!0,O.seek(ie=>{if(c()){if(W=Ae(),!ie){_();return}ee=ie,!(0,et.isNullable)(x)||ie.startTS>x?Pe(ie):(L=ie,ae())}},x),e.cachedHeader?se(e.cachedHeader):d(e.headerUrl,se,()=>this._handleNetworkError())},stop:I,getTimestampSec:()=>n},p}_switchToQuality(e){let{logger:t,playerCallback:i}=this.params,r;e.bitrate!==this.bitrate&&(this.rep&&(r=this.rep.getTimestampSec(),(0,et.isNonNullable)(r)&&(r+=.1),this.rep.stop()),this.currentManifestEntry=e,this.rep=this._representation(e),t(`switch to quality: codecs=${e.codecs}; headerUrl=${e.headerUrl}; bitrate=${e.bitrate}`),this.bitrate=e.bitrate,(0,et.assertNonNullable)(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(r),i({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return(0,et.isNonNullable)(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,i=c=>{if(!this.autoQuality)return;let d,h,m;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&c<this.bitrate&&(h=this._getBufferSizeSec(),m=c/this.bitrate,h>10&&m>.8||h>15&&m>.5||h>20&&m>.3)){e(`Not switching: buffer=${Math.floor(h)}; bitrate=${this.bitrate}; newRate=${Math.floor(c)}`);return}d=this._selectQuality(c),d?this._switchToQuality(d):e(`Could not find quality by bitrate ${c}`)},s={updateChunk:(d,h)=>{let m=Ae();if(this.chunkRateEstimator.addInterval(d,m,h)){let S=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:h,duration:m-d,speed:S}),!0}},get:()=>{let d=this.chunkRateEstimator.getBitRate();return d?d*.85:0}},n=-1/0,u,o=!0,l=()=>{let c=s.get();if(c&&u&&this.autoQuality){if(o&&c>u&&ul(n)<3e4)return;i(c)}o=this.autoQuality};return{updateChunk:(c,d)=>{let h=s.updateChunk(c,d);return h&&l(),h},notifySwitch:c=>{let d=Ae();c<u&&(n=d),u=c}}}_fetchManifest(e,t,i){this.manifestRequest=ur(this.urlResolver.resolve(e,!0),t,i,()=>this._retryCallback()).withJSONResponse().withTimeout(dn).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;Qe(e,()=>{this.soundProhibitedEvent$.next()}).then(t=>{t||(this.params.liveOffset.pause(),this.params.videoState.setState("paused"))})}_handleManifestUpdate(e){let{logger:t,playerCallback:i,videoElement:r}=this.params,s=n=>{let u=[];return n?.length?(n.forEach((o,l)=>{o.video&&r.canPlayType(o.codecs).replace(/no/,"")&&window.MediaSource?.isTypeSupported?.(o.codecs)&&(o.index=l,u.push(o))}),u.sort(function(o,l){return o.video&&l.video?l.video.height-o.video.height:l.bitrate-o.bitrate}),u):(i({name:"error",type:"empty_manifest"}),[])};this.manifest=s(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),i({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))},FA))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};var _b=Q(zi(),1),be=require("@vkontakte/videoplayer-shared"),dl=class{constructor(){this.onDroopedVideoFramesLimit$=new be.Subject;this.subscription=new be.Subscription;this.playing=!1;this.tracks=[];this.forceChecker$=new be.Subject;this.isForceCheckCounter=0;this.prevTotalVideoFrames=0;this.prevDroppedVideoFrames=0;this.limitCounts={};this.handleChangeVideoQuality=()=>{let e=this.tracks.find(({size:t})=>t?.height===this.video.videoHeight&&t?.width===this.video.videoWidth);e&&!(0,be.isInvariantQuality)(e.quality)&&this.onChangeQuality(e.quality)};this.checkDroppedFrames=()=>{let{totalVideoFrames:e,droppedVideoFrames:t}=this.video.getVideoPlaybackQuality(),i=e-this.prevTotalVideoFrames,r=t-this.prevDroppedVideoFrames,s=1-(i-r)/i;!isNaN(s)&&s>0&&this.log({message:`[dropped]. current dropped percent: ${s}, limit: ${this.droppedFramesChecker.percentLimit}`}),!isNaN(s)&&s>=this.droppedFramesChecker.percentLimit&&(0,be.isHigher)(this.currentQuality,this.droppedFramesChecker.minQualityBanLimit)&&(this.limitCounts[this.currentQuality]=(this.limitCounts[this.currentQuality]??0)+1,this.maxQualityLimit=this.getMaxQualityLimit(this.currentQuality),this.currentTimer&&window.clearTimeout(this.currentTimer),this.currentTimer=window.setTimeout(()=>this.maxQualityLimit=this.getMaxQualityLimit(),this.droppedFramesChecker.qualityUpWaitingTime),this.onDroopedVideoFramesLimitTrigger()),this.savePrevFrameCounts(e,t)}}connect(e){this.log=e.logger.createComponentLog("DroppedFramesManager"),this.video=e.video,this.isAuto=e.isAuto,this.tracks=e.tracks,this.droppedFramesChecker=e.droppedFramesChecker,this.subscription.add(e.playing$.subscribe(()=>this.playing=!0)),this.subscription.add(e.pause$.subscribe(()=>this.playing=!1)),this.isEnabled&&this.subscribe()}destroy(){this.currentTimer&&window.clearTimeout(this.currentTimer),this.subscription.unsubscribe()}get droppedVideoMaxQualityLimit(){return this.maxQualityLimit}subscribe(){this.subscription.add((0,be.fromEvent)(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=(0,be.interval)(this.droppedFramesChecker.checkTime).pipe((0,be.filter)(()=>this.playing),(0,be.filter)(()=>{let r=!!this.isForceCheckCounter;return r&&(this.isForceCheckCounter-=1),!r})),t=this.forceChecker$.pipe((0,be.debounce)(this.droppedFramesChecker.checkTime)),i=(0,be.merge)(e,t);this.subscription.add(i.subscribe(this.checkDroppedFrames))}onChangeQuality(e){this.currentQuality=e;let{totalVideoFrames:t,droppedVideoFrames:i}=this.video.getVideoPlaybackQuality();this.savePrevFrameCounts(t,i),this.isForceCheckCounter=this.droppedFramesChecker.tickCountAfterQualityChange,this.forceChecker$.next()}onDroopedVideoFramesLimitTrigger(){this.isAuto.getState()&&(this.log({message:`[onDroopedVideoFramesLimit]. maxQualityLimit: ${this.maxQualityLimit}`}),this.onDroopedVideoFramesLimit$.next())}getMaxQualityLimit(e){let t=(0,_b.default)(this.limitCounts).filter(([,i])=>i>=this.droppedFramesChecker.countLimit).sort(([i],[r])=>(0,be.isLower)(i,r)?-1:1)?.[0]?.[0];return e??t}get isEnabled(){return this.droppedFramesChecker.enabled&&this.isDroppedFramesCheckerSupport}get isDroppedFramesCheckerSupport(){return!!this.video&&typeof this.video.getVideoPlaybackQuality=="function"}savePrevFrameCounts(e,t){this.prevTotalVideoFrames=e,this.prevDroppedVideoFrames=t}},lr=dl;var pn=require("@vkontakte/videoplayer-shared"),Ob=require("@vkontakte/videoplayer-shared");var ua=()=>!!window.documentPictureInPicture?.window||!!document.pictureInPictureElement;var HA=(a,e)=>new pn.Observable(t=>{if(!window.IntersectionObserver)return;let i={root:null},r=new IntersectionObserver((n,u)=>{n.forEach(o=>t.next(o.isIntersecting||ua()))},{...i,...e});r.observe(a);let s=(0,Ob.fromEvent)(document,"visibilitychange").pipe((0,pn.map)(n=>!document.hidden||ua())).subscribe(n=>t.next(n));return()=>{r.unobserve(a),s.unsubscribe()}}),ut=HA;var jA=["paused","playing","ready"],WA=["paused","playing","ready"],la=class{constructor(e){this.subscription=new Y.Subscription;this.videoState=new Z("stopped");this.representations$=new Y.ValueSubject([]);this.droppedFramesManager=new lr;this.maxSeekBackTime$=new Y.ValueSubject(1/0);this.zeroTime$=new Y.ValueSubject(void 0);this.liveOffset=new xi;this._dashCb=e=>{switch(e.name){case"buffering":{let t=e.isBuffering;this.params.output.isBuffering$.next(t);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${e.type}`,category:Y.ErrorCategory.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{let t=e.manifest,i=[];for(let r of t){let s=r.name??r.index.toString(10),n=ii(r.name)??(0,Y.videoSizeToQuality)(r.video),u=r.bitrate/1e3,o={...r.video};if(!n)continue;let l={id:s,quality:n,bitrate:u,size:o};i.push({track:l,representation:r})}this.representations$.next(i),this.params.output.availableVideoTracks$.next(i.map(({track:r})=>r)),this.videoState.getTransition()?.to==="manifest_ready"&&this.videoState.setState("manifest_ready");break}case"qualitySwitch":{let t=e.quality,i=this.representations$.getValue().find(({representation:r})=>r===t)?.track;this.params.output.hostname$.next(new URL(t.headerUrl,this.params.source.url).hostname),(0,Y.isNonNullable)(i)&&this.params.output.currentVideoTrack$.next(i);break}case"bandwidth":{let{size:t,duration:i}=e;this.params.dependencies.throughputEstimator.addRawSpeed(t,i);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(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; seekState: ${JSON.stringify(s)};`}),i==="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(),u=this.params.desiredState.autoVideoTrackSwitching.getTransition();if((0,pl.default)(WA,e)&&(n||u)){this.prepare();return}if(r?.to!=="paused"&&s.state==="requested"&&(0,pl.default)(jA,e)){this.seek(s.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(ye(this.params.source.url));return;case"manifest_ready":this.videoState.startTransitionTo("ready"),this.prepare();break;case"ready":if(i==="paused")this.videoState.setState("paused");else if(i==="playing"){this.videoState.startTransitionTo("playing");let o=r?.from;o&&o==="ready"&&this.dash.catchUp(),this.dash.play()}return;case"playing":i==="paused"&&(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.dash.pause());return;case"paused":if(i==="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 o=this.liveOffset.getTotalOffset();o>=this.maxSeekBackTime$.getValue()&&(o=0,this.liveOffset.resetTo(o)),this.liveOffset.resume(),this.params.output.position$.next(-o/1e3),this.dash.reinit(ye(this.params.source.url,o))}return;default:return(0,Y.assertNever)(e)}};this.textTracksManager=new ot(e.source.url),this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=r=>{e.output.error$.next({id:"DashLiveProvider",category:Y.ErrorCategory.WTF,message:"DashLiveProvider internal logic error",thrown:r})};this.subscription.add((0,Y.merge)(this.videoState.stateChangeStarted$.pipe((0,Y.map)(r=>({transition:r,type:"start"}))),this.videoState.stateChangeEnded$.pipe((0,Y.map)(r=>({transition:r,type:"end"})))).subscribe(({transition:r,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(r)}`})})),this.video=Ue(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(Me(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 i=We(this.video);this.subscription.add(()=>i.destroy()),this.subscription.add(this.representations$.pipe((0,Y.map)(r=>r.map(({track:s})=>s)),(0,Y.filter)(r=>!!r.length),(0,Y.once)()).subscribe(r=>this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks:r}))),this.subscription.add(i.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready")},t)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused")},t)).add(i.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.videoState.setState("playing")},t)).add(i.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe((0,Y.filterChanged)(),(0,Y.map)(r=>-r/1e3)).subscribe(this.params.output.duration$)).add((0,Y.combine)({zeroTime:this.zeroTime$.pipe((0,Y.filter)(Y.isNonNullable)),position:i.timeUpdate$}).subscribe(({zeroTime:r,position:s})=>this.params.output.liveTime$.next(r+s*1e3),t)).add(Pt(this.video,this.params.desiredState.isLooped,t)).add(je(this.video,this.params.desiredState.volume,i.volumeState$,t)).add(i.volumeState$.subscribe(this.params.output.volume$,t)).add(nt(this.video,this.params.desiredState.playbackRate,i.playbackRateState$,t)).add(i.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(i.loadedMetadata$.subscribe(this.params.output.loadedMetadataEvent$)).add(i.playing$.subscribe(this.params.output.firstFrameEvent$)).add(i.canplay$.subscribe(this.params.output.canplay$)).add(i.inPiP$.subscribe(this.params.output.inPiP$)).add(i.inFullscreen$.subscribe(this.params.output.inFullscreen$)).add(ut(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:r,min:s}})=>{this.dash.setAutoQualityLimits({max:r&&(0,Y.videoQualityToHeight)(r),min:s&&(0,Y.videoQualityToHeight)(s)}),this.params.output.autoVideoTrackLimits$.next({max:r,min:s})})).add(this.videoState.stateChangeEnded$.subscribe(r=>{switch(r.to){case"stopped":this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState("stopped");break;case"manifest_ready":case"ready":this.params.desiredState.playbackState.getTransition()?.to==="ready"&&this.params.desiredState.playbackState.setState("ready");break;case"paused":this.params.desiredState.playbackState.setState("paused");break;case"playing":this.params.desiredState.playbackState.setState("playing");break;default:return(0,Y.assertNever)(r.to)}},t)).add((0,Y.merge)(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,(0,Y.observableFrom)(["init"])).pipe((0,Y.debounce)(0)).subscribe(this.syncPlayback,t))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.droppedFramesManager.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),He(this.video)}createLiveDashPlayer(){let e=new oa({videoElement:this.video,videoState:this.videoState,playbackState:this.params.desiredState.playbackState,liveOffset:this.liveOffset,config:{maxParallelRequests:this.params.config.maxParallelRequests,minBuffer:this.params.tuning.live.minBuffer,minBufferSegments:this.params.tuning.live.minBufferSegments,lowLatencyMinBuffer:this.params.tuning.live.lowLatencyMinBuffer,lowLatencyMinBufferSegments:this.params.tuning.live.lowLatencyMinBufferSegments,isLiveCatchUpMode:this.params.tuning.live.isLiveCatchUpMode,manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},playerCallback:this._dashCb,logger:t=>{this.params.dependencies.logger.log({message:String(t),component:"LiveDashPlayer"})}});return e.pause(),e}prepare(){let e=this.representations$.getValue(),t=this.params.desiredState.videoTrack.getTransition()?.to??this.params.desiredState.videoTrack.getState(),i=this.params.desiredState.autoVideoTrackSwitching.getTransition()?.to??this.params.desiredState.autoVideoTrackSwitching.getState(),r=!i&&(0,Y.isNonNullable)(t)?t:Rt(e.map(({track:l})=>l),{container:this.video.getBoundingClientRect(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),s=r?.id,n=this.params.desiredState.videoTrack.getTransition(),u=this.params.desiredState.videoTrack.getState()?.id,o=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(r&&(n||s!==u)&&this.setVideoTrack(r),o&&this.setAutoQuality(i),n||o||s!==u){let l=e.find(({track:p})=>p.id===s)?.representation;(0,Y.assertNonNullable)(l,"Representations missing"),this.dash.startPlay(l,i)}}setVideoTrack(e){let t=this.representations$.getValue().find(({track:i})=>i.id===e.id)?.representation;(0,Y.assertNonNullable)(t,`No such representation ${e.id}`),this.dash.switchByName(t.name),this.params.desiredState.videoTrack.setState(e)}setAutoQuality(e){this.dash.setAutoQualityEnabled(e),this.params.desiredState.autoVideoTrackSwitching.setState(e)}seek(e){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),i=this.videoState.getState(),r=t==="paused"&&i==="paused",s=-e,n=s<=this.maxSeekBackTime$.getValue()?s:0;this.params.output.position$.next(e/1e3),this.dash.reinit(ye(this.params.source.url,n)),r&&this.dash.pause(),this.liveOffset.resetTo(n,r)}};var Fb=la;var De=(a,e)=>{let t=0;for(let i=0;i<a.length;i++){let r=a.start(i)*1e3,s=a.end(i)*1e3;r<=e&&e<=s&&(t=s)}return Math.max(t-e,0)};var F=require("@vkontakte/videoplayer-shared");var{NativeAbortSignal:C0,NativeAbortController:B0}=function(a){return{NativeAbortSignal:a.AbortSignal,NativeAbortController:a.AbortController}}(typeof self<"u"?self:global);function Nb(a){let e;try{e=new Event("abort")}catch{typeof document<"u"?document.createEvent?(e=document.createEvent("Event"),e.initEvent("abort",!1,!1)):(e=document.createEventObject(),e.type="abort"):e={type:"abort",bubbles:!1,cancelable:!1}}return e.reason=a,e}function qb(a){if(a===void 0)if(typeof document>"u")a=new Error("This operation was aborted"),a.name="AbortError";else try{a=new DOMException("signal is aborted without reason"),Object.defineProperty(a,"name",{value:"AbortError"})}catch{a=new Error("This operation was aborted"),a.name="AbortError"}return a}var hn=class{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,i){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:i})}removeEventListener(e,t){if(!(e in this.listeners))return;let i=this.listeners[e];for(let r=0,s=i.length;r<s;r++)if(i[r].callback===t){i.splice(r,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;let i=this.listeners[e.type].slice();for(let r=0,s=i.length;r<s;r++){let n=i[r];try{n.callback.call(this,e)}catch(u){Promise.resolve().then(()=>{throw u})}n.options&&n.options.once&&this.removeEventListener(e.type,n.callback)}return!e.defaultPrevented}},cr=class extends hn{constructor(){super(),this.listeners||hn.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)}throwIfAborted(){let{aborted:e,reason:t="Aborted"}=this;if(e)throw t}static timeout(e){let t=new ki;return setTimeout(()=>t.abort(new DOMException(`This signal is timeout in ${e}ms`,"TimeoutError")),e),t.signal}static any(e){let t=new ki;function i(){t.abort(this.reason),r()}function r(){for(let s of e)s.removeEventListener("abort",i)}for(let s of e)if(s.aborted){t.abort(s.reason);break}else s.addEventListener("abort",i);return t.signal}},ki=class{constructor(){Object.defineProperty(this,"signal",{value:new cr,writable:!0,configurable:!0})}abort(e){let t=qb(e),i=Nb(t);this.signal.reason=t,this.signal.dispatchEvent(i)}toString(){return"[object AbortController]"}};typeof Symbol<"u"&&Symbol.toStringTag&&(ki.prototype[Symbol.toStringTag]="AbortController",cr.prototype[Symbol.toStringTag]="AbortSignal");function fn(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 hl(a){typeof a=="function"&&(a={fetch:a});let{fetch:e,Request:t=e.Request,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r=!1}=a;if(!fn({fetch:e,Request:t,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r}))return{fetch:e,Request:s};let s=t;(s&&!s.prototype.hasOwnProperty("signal")||r)&&(s=function(l,p){let c;p&&p.signal&&(c=p.signal,delete p.signal);let d=new t(l,p);return c&&Object.defineProperty(d,"signal",{writable:!1,enumerable:!1,configurable:!0,value:c}),d},s.prototype=t.prototype);let n=e;return{fetch:(o,l)=>{let p=s&&s.prototype.isPrototypeOf(o)?o.signal:l?l.signal:void 0;if(p){let c;try{c=new DOMException("Aborted","AbortError")}catch{c=new Error("Aborted"),c.name="AbortError"}if(p.aborted)return Promise.reject(c);let d=new Promise((h,m)=>{p.addEventListener("abort",()=>m(c),{once:!0})});return l&&l.signal&&delete l.signal,Promise.race([d,n(o,l)])}return n(o,l)},Request:s}}var QA=()=>"fetch"in window,ca=QA()&&fn({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),Ub=ca?hl({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,lt=ca?Ub.fetch:window.fetch,W0=ca?Ub.Request:window.Request,ue=ca?ki:window.AbortController,Q0=ca?cr:window.AbortSignal;var HS=Q(Oe(),1),Vl=Q(da(),1);var Pg=Q(Ag(),1),dr=require("@vkontakte/videoplayer-shared"),mn=a=>{if(!a)return{id:"EmptyResponse",category:dr.ErrorCategory.PARSER,message:"Empty response"};if(a.length<=2&&a.match(/^\d+$/))return{id:`UVError#${a}`,category:dr.ErrorCategory.NETWORK,message:`UV Error ${a}`};let e=(0,Pg.default)(a).substring(0,100).toLowerCase();if(e.startsWith("<!doctype")||e.startsWith("<html>")||e.startsWith("<body>")||e.startsWith("<head>"))return{id:"UnexpectedHTML",category:dr.ErrorCategory.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:dr.ErrorCategory.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:dr.ErrorCategory.PARSER,message:"Response is valid XML, but parser failed"}};var Ce=(a,e,t=0)=>{for(let i=0;i<a.length;i++)if(a.start(i)*1e3-t<=e&&a.end(i)*1e3+t>e)return!0;return!1};var T=require("@vkontakte/videoplayer-shared");var Sn=Q(Oe(),1),Ri=Q(gt(),1),vn=Q(da(),1);var LP=(a,e={})=>{let i=e.timeout||1,r=performance.now();return window.setTimeout(()=>{a({get didTimeout(){return e.timeout?!1:performance.now()-r-1>i},timeRemaining(){return Math.max(0,1+(performance.now()-r))}})},1)},MP=a=>window.clearTimeout(a),Rg=a=>typeof a=="function"&&a?.toString().endsWith("{ [native code] }"),$g=!Rg(window.requestIdleCallback)||!Rg(window.cancelIdleCallback),pr=$g?LP:window.requestIdleCallback,Lt=$g?MP:window.cancelIdleCallback;var OS=Q(zs(),1);var ai=require("@vkontakte/videoplayer-shared");var DP=18,Lg=!1;try{Lg=j.browser.isSafari&&!!j.browser.safariVersion&&j.browser.safariVersion<=DP}catch(a){console.error(a)}var vl=class{constructor(e){this.bufferFull$=new ai.Subject;this.error$=new ai.Subject;this.queue=[];this.currentTask=null;this.destroyed=!1;this.abortRequested=!1;this.completeTask=()=>{try{if(this.currentTask){let e=this.currentTask.signal?.aborted;this.currentTask.callback(!e),this.currentTask=null}this.queue.length&&this.pull()}catch(e){this.error$.next({id:"BufferTaskQueueUnknown",category:ai.ErrorCategory.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:e})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(i=>{let r={operation:"append",data:e,signal:t,callback:i};this.queue.push(r),this.pull()})}async remove(e,t,i){return i&&i.aborted?!1:new Promise(r=>{let s={operation:"remove",from:e,to:t,signal:i,callback:r};this.queue.unshift(s),this.pull()})}async abort(e){return new Promise(t=>{let i,r=s=>{this.abortRequested=!1,t(s)};Lg&&e?i={operation:"safariAbort",init:e,callback:r}:i={operation:"abort",callback:r};for(let{callback:s}of this.queue)s(!1);this.abortRequested=!0,i&&(this.queue=[i]),this.pull()})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){if((this.buffer.updating||this.currentTask||this.destroyed)&&!this.abortRequested)return;let e=this.queue.shift();if(!e)return;if(e.signal?.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(r){r instanceof DOMException&&r.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):r instanceof DOMException&&r.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:ai.ErrorCategory.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:r}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){let{operation:t}=e;switch(t){case"append":this.buffer.appendBuffer(e.data);break;case"remove":this.buffer.remove(e.from/1e3,e.to/1e3);break;case"abort":this.buffer.abort();break;case"safariAbort":{this.buffer.abort(),this.buffer.appendBuffer(e.init);break}default:(0,ai.assertNever)(t)}}},Mg=vl;var hr=a=>{let e=0;for(let t=0;t<a.length;t++)e+=a.end(t)-a.start(t);return e*1e3};var w=require("@vkontakte/videoplayer-shared");var Cg=Q(gt(),1);var bn=a=>a.valid,ne=class{constructor(e,t){this.cursor=0;this.source=e,this.boxParser=t,this.children=[];let i=this.readUint32();this.type=this.readString(4),i===1&&(this.cursor+=8);let r=e.byteOffset+this.cursor,s;i===0?(this.size=void 0,this.valid=!1,s=void 0):i===1?(this.size=void 0,this.valid=!1,s=void 0):i>e.byteLength?(this.size=i,this.valid=!1,s=Math.min(i-this.cursor,e.byteLength-this.cursor)):(this.size=i,this.valid=!0,s=i-this.cursor),this.content=new DataView(e.buffer,r,s)}get id(){return this.type}scanForBoxes(e){return this.boxParser.parse(e)}readString(e,t="ascii"){let r=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,r}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 fr=class extends ne{};var Dg=require("@vkontakte/videoplayer-shared");var ha=class extends ne{constructor(e,t){if(super(e,t),!this.valid)return;let i=this.readString(16),r=new DataView(this.content.buffer,this.content.byteOffset+16,this.content.byteLength-16);this.userData=this.parseData(i,r)}parseData(e,t){switch(e){case"ondemandlivejson":{let i=new TextDecoder("ascii").decode(t),r=JSON.parse(i);return{received:r["t-in"],prepared:r["t-out"]}}default:(0,Dg.assertNever)(e)}}};var fa=class extends ne{constructor(e,t){if(super(e,t),!this.valid)return;this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let i=new DataView(this.content.buffer,this.content.byteOffset+8,this.content.byteLength-8);for(let r=0;r<i.byteLength;r+=4){let s=this.readString(4);this.compatibleBrands.push(s)}}};var ma=class extends ne{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var pe=class extends ne{constructor(e,t){if(super(e,t),!this.valid)return;let i=this.readUint32();this.version=i>>>24,this.flags=i&16777215,this.content=new DataView(this.content.buffer,this.content.byteOffset+4,this.content.byteLength-4)}};var ba=class extends pe{constructor(e,t){super(e,t),this.valid&&(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 ga=class extends ne{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Sa=class extends ne{constructor(e,t){super(e,t),this.data=this.content}};var Ai=class extends pe{get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e,t){if(super(e,t),!!this.valid){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 i=0;i<this.referenceCount;i++){let r=this.readUint32(),s=r>>>31,n=r<<1>>>1,u=this.readUint32();r=this.readUint32();let o=r>>>28,l=r<<3>>>3;this.segments.push({referenceType:s,referencedSize:n,subsegmentDuration:u,SAPType:o,SAPDeltaTime:l})}}}};var va=class extends ne{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ya=class extends ne{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ta=class extends pe{constructor(e,t){if(super(e,t),!this.valid)return;switch(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 Ia=class extends pe{constructor(e,t){super(e,t),this.valid&&(this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32())}};var Ea=class extends pe{constructor(e,t){super(e,t),this.valid&&(this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32())}};var xa=class extends ne{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var wa=class extends pe{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 ka=class extends ne{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Aa=class extends ne{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Pa=class extends pe{constructor(e,t){super(e,t),this.valid&&(this.sequenceNumber=this.readUint32())}};var Ra=class extends ne{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var $a=class extends pe{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 La=class extends pe{constructor(t,i){super(t,i);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 Ma=class extends pe{constructor(t,i){super(t,i);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 r=0;r<this.sampleCount;r++)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 Da=class extends ne{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ca=class extends pe{constructor(e,t){super(e,t),this.valid&&(this.entryCount=this.readUint32(),this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+4,this.content.byteLength-4)))}};var Ba=class extends ne{constructor(e,t){super(e,t),this.valid&&(this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+78,this.content.byteLength-78)))}};var BP={ftyp:fa,moov:ma,mvhd:ba,moof:ga,mdat:Sa,sidx:Ai,trak:va,mdia:xa,mfhd:Pa,tkhd:wa,traf:Ra,tfhd:$a,tfdt:La,trun:Ma,minf:ka,sv3d:ya,st3d:Ta,prhd:Ia,proj:Aa,equi:Ea,uuid:ha,stbl:Da,stsd:Ca,avc1:Ba,unknown:fr},qt=class a{constructor(e={}){this.options={offset:0,...e}}parse(e){let t=[],i=this.options.offset;for(;i<e.byteLength;){let s=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+i+4,4)),n;try{n=this.createBox(s,new DataView(e.buffer,e.byteOffset+i,e.byteLength-i))}catch(u){if(!(u instanceof RangeError))throw u}if(!n||!bn(n))break;t.push(n),i+=n.size}return t}createBox(e,t){let i=BP[e];return i?new i(t,new a):new fr(t,new a)}};var si=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{bn(t)&&(this.index[t.type]??=[],this.index[t.type].push(t),t.children.length>0&&this.indexBoxLevel(t.children))})}find(e){return this.index[e]&&this.index[e][0]?this.index[e][0]:null}findAll(e){return this.index[e]||[]}};var _P=new TextDecoder("ascii"),OP=a=>_P.decode(new DataView(a.buffer,a.byteOffset+4,4))==="ftyp",FP=a=>{let e=new Ai(a,new qt),t=e.earliestPresentationTime/e.timescale*1e3,i=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,u={status:"none",time:{from:t,to:t+n},byte:{from:i,to:i+s.referencedSize-1}};return t+=n,i+=s.referencedSize,u})},NP=(a,e)=>{let i=new qt().parse(a),r=new si(i),s=r.findAll("moof"),n=e?r.findAll("uuid"):r.findAll("mdat");if(!(n.length&&s.length))return null;let u=s[0],o=n[n.length-1],l=u.source.byteOffset,c=o.source.byteOffset-u.source.byteOffset+o.size;return new DataView(a.buffer,l,c)},qP=a=>{let t=new qt().parse(a),i=new si(t),r={},s=i.findAll("uuid"),n=(0,Cg.default)(s,-1);return n?{serverDataReceivedTimestamp:n.userData.received,serverDataPreparedTime:n.userData.received}:r},UP=a=>{let t=new qt().parse(a);return new si(t).find("sidx")?.timescale},HP=(a,e)=>{let i=new qt().parse(a),s=new si(i).findAll("traf"),n=s[s.length-1].children.find(c=>c.type==="tfhd"),u=s[s.length-1].children.find(c=>c.type==="tfdt"),o=s[s.length-1].children.find(c=>c.type==="trun"),l=0;return o.sampleDuration.length?l=o.sampleDuration.reduce((c,d)=>c+d,0):l=n.defaultSampleDuration*o.sampleCount,(Number(u.baseMediaDecodeTime)+l)/e*1e3},jP=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}}},i=new qt().parse(a),r=new si(i);if(r.find("sv3d")){e.is3dVideo=!0;let n=r.find("st3d");n&&(e.stereoMode=n.stereoMode);let u=r.find("prhd");u&&(e.projectionData.pose.yaw=u.poseYawDegrees,e.projectionData.pose.pitch=u.posePitchDegrees,e.projectionData.pose.roll=u.poseRollDegrees);let o=r.find("equi");o&&(e.projectionData.bounds.top=o.projectionBoundsTop,e.projectionData.bounds.right=o.projectionBoundsRight,e.projectionData.bounds.bottom=o.projectionBoundsBottom,e.projectionData.bounds.left=o.projectionBoundsLeft)}return e},Bg={validateData:OP,parseInit:jP,getIndexRange:()=>{},parseSegments:FP,parseFeedableSegmentChunk:NP,getChunkEndTime:HP,getServerLatencyTimestamps:qP,getTimescaleFromIndex:UP};var Oa=Q(Oe(),1),Ut=require("@vkontakte/videoplayer-shared");var _g=require("@vkontakte/videoplayer-shared");var Vg={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"}},Og=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 i=_a(a,t),r=i in Vg,s=r?Vg[i].type:"binary",n=a.getUint8(t),u=0;n&128?u=1:n&64?u=2:n&32?u=3:n&16?u=4:n&8?u=5:n&4?u=6:n&2?u=7:n&1&&(u=8);let o=new DataView(a.buffer,a.byteOffset+t+1,u-1),l=n&255>>u,p=_a(o),c=l*2**((u-1)*8)+p,d=t+u,h;return d+c>a.byteLength?h=new DataView(a.buffer,a.byteOffset+d):h=new DataView(a.buffer,a.byteOffset+d,c),{tag:r?i:"0x"+i.toString(16).toUpperCase(),type:s,tagHeaderSize:d,tagSize:d+c,value:h,valueSize:c}},_a=(a,e=a.byteLength)=>{switch(e){case 1:return a.getUint8(0);case 2:return a.getUint16(0);case 3:return a.getUint8(0)*2**16+a.getUint16(1);case 4:return a.getUint32(0);case 5:return a.getUint8(0)*2**32+a.getUint32(1);case 6:return a.getUint16(0)*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},St=(a,e)=>{switch(e){case"int":return a.getInt8(0);case"uint":return _a(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:(0,_g.assertNever)(e)}},Pi=(a,e)=>{let t=0;for(;t<a.byteLength;){let i=new DataView(a.buffer,a.byteOffset+t),r=Og(i);if(!e(r))return;r.type==="master"&&Pi(r.value,e),t=r.value.byteOffset-a.byteOffset+r.valueSize}},Fg=a=>{if(a.getUint32(0)!==440786851)return!1;let e,t,i,r=Og(a);return Pi(r.value,({tag:s,type:n,value:u})=>(s===17143?e=St(u,n):s===17026?t=St(u,n):s===17029&&(i=St(u,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)};var Ng=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],WP=[231,22612,22743,167,171,163,160,175],QP=a=>{let e,t,i,r,s=!1,n=!1,u=!1,o,l,p=!1,c=0;return Pi(a,({tag:d,type:h,value:m,valueSize:b})=>{if(d===21419){let S=St(m,h);l=_a(S)}else d!==21420&&(l=void 0);return d===408125543?(e=m.byteOffset,t=m.byteOffset+b):d===357149030?s=!0:d===290298740?n=!0:d===2807729?i=St(m,h):d===17545?r=St(m,h):d===21420&&l===475249515?o=St(m,h):d===374648427?Pi(m,({tag:S,type:v,value:I})=>S===30321?(p=St(I,v)===1,!1):!0):s&&n&&(0,Oa.default)(Ng,d)&&(u=!0),!u}),(0,Ut.assertNonNullable)(e,"Failed to parse webm Segment start"),(0,Ut.assertNonNullable)(t,"Failed to parse webm Segment end"),(0,Ut.assertNonNullable)(r,"Failed to parse webm Segment duration"),i=i??1e6,{segmentStart:Math.round(e/1e9*i*1e3),segmentEnd:Math.round(t/1e9*i*1e3),timeScale:i,segmentDuration:Math.round(r/1e9*i*1e3),cuesSeekPosition:o,is3dVideo:p,stereoMode:c,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},GP=a=>{if((0,Ut.isNullable)(a.cuesSeekPosition))return;let e=a.segmentStart+a.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},zP=(a,e)=>{let t=!1,i=!1,r=u=>(0,Ut.isNonNullable)(u.time)&&(0,Ut.isNonNullable)(u.position),s=[],n;return Pi(a,({tag:u,type:o,value:l})=>{switch(u){case 475249515:t=!0;break;case 187:n&&r(n)&&s.push(n),n={};break;case 179:n&&(n.time=St(l,o));break;case 183:break;case 241:n&&(n.position=St(l,o));break;default:t&&(0,Oa.default)(Ng,u)&&(i=!0)}return!(t&&i)}),n&&r(n)&&s.push(n),s.map((u,o)=>{let{time:l,position:p}=u,c=s[o+1];return{status:"none",time:{from:l,to:c?c.time:e.segmentDuration},byte:{from:e.segmentStart+p,to:c?e.segmentStart+c.position-1:e.segmentEnd-1}}})},YP=a=>{let e=0,t=!1;try{Pi(a,i=>i.tag===524531317?i.tagSize<=a.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):(0,Oa.default)(WP,i.tag)?(e+i.tagSize<=a.byteLength&&(e+=i.tagSize,t||=(0,Oa.default)([163,160,175],i.tag)),!0):!1)}catch{}return e>0&&e<=a.byteLength&&t?new DataView(a.buffer,a.byteOffset,e):null},qg={validateData:Fg,parseInit:QP,getIndexRange:GP,parseSegments:zP,parseFeedableSegmentChunk:YP};var Mt=a=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(a);if(e){let[,t,i]=e;if(t==="audio"||t==="video")switch(i){case"webm":return qg;case"mp4":return Bg}}throw new ReferenceError(`Unsupported mime type ${a}`)};var Dt=a=>a instanceof DOMException&&(a.name==="AbortError"||a.code===20);var kl=Q(cS(),1),LS=Q(zi(),1),MS=Q(kS(),1),DS=Q(gt(),1),Al=Q(Si(),1);var AS=Q(Oe(),1),wl=a=>{let e=a.split("."),[t,...i]=e;if(!t)return!1;switch(t){case"av01":{let[r,s,n]=i;return!!(n&&parseInt(n,10)>8)}case"vp09":{let[r,s,n]=i;return!!(r&&parseInt(r,10)>=2&&n&&parseInt(n,10)>8)}case"avc1":{let r=i[0];if(!r||r.length!==6)return!1;let[s,n]=r.toUpperCase(),u=s+n;return(0,AS.default)(["6E","7A","F4"],u)}}return!1};var Fa=require("@vkontakte/videoplayer-shared");var PS=a=>{if(a.includes("/")){let e=a.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(a)};var RS=a=>{try{let e=zR(),t=a.match(e),{groups:i}=t??{};if(i){let r={};if(i.extensions){let u=i.extensions.toLowerCase().match(/(?:[0-9a-wy-z](?:-[a-z0-9]{2,8})+)/g);Array.from(u||[]).forEach(o=>{r[o[0]]=o.slice(2)})}let s=i.variants?.split(/-/).filter(u=>u!==""),n={extlang:i.extlang,langtag:i.langtag,language:i.language,privateuse:i.privateuse||i.privateuse2,region:i.region,script:i.script,extensions:r,variants:s};return Object.keys(n).forEach(u=>{let o=n[u];(typeof o>"u"||o==="")&&delete n[u]}),n}return null}catch{return null}};function zR(){let a="(?<extlang>(?:[a-z]{3}(?:-[a-z]{3}){0,2}))",e="x(?:-[a-z0-9]{1,8})+",p=`^(?:(?<langtag>${`
117
+ `}),I};var Me=a=>new URL(a).hostname;var Y=require("@vkontakte/videoplayer-shared");var Bb=Q(gt(),1);var Lb=Q(Oe(),1),$b=a=>{if(a instanceof DOMException&&(0,Lb.default)(["Failed to load because no supported source was found.","The element has no supported sources."],a.message))throw a;return!(a instanceof DOMException&&(a.code===20||a.name==="AbortError"))},Qe=async(a,e)=>{let t=a.muted;try{await a.play()}catch(i){if(!$b(i))return!1;if(e&&e(),t)return console.warn(i),!1;a.muted=!0;try{await a.play()}catch(r){return $b(r)&&(a.muted=!1,console.warn(r)),!1}}return!0};var et=require("@vkontakte/videoplayer-shared");var Mb=Q(Si(),1),$t=require("@vkontakte/videoplayer-shared");function Pe(){return(0,$t.now)()}function ul(a){return Pe()-a}function ll(a){let e=a.split("/"),t=e.slice(0,e.length-1).join("/"),i=/^([a-z]+:)?\/\//i,r=n=>i.test(n);return{resolve:(n,u,o=!1)=>{r(n)||(n.startsWith("/")||(n="/"+n),n=t+n);let l=n.indexOf("?")>-1?"&":"?";return o&&(n+=l+"lowLat=1",l="&"),u&&(n+=l+"_rnd="+Math.floor(999999999*Math.random())),n}}}function Db(a,e,t){let i=(...r)=>{t.apply(null,r),a.removeEventListener(e,i)};a.addEventListener(e,i)}function ur(a,e,t,i){let r=window.XMLHttpRequest,s,n,u,o=!1,l=0,p,c,d=!1,h="arraybuffer",m=7e3,b=2e3,S=()=>{if(o)return;(0,$t.assertNonNullable)(p);let W=ul(p),R;if(W<b){R=b-W,setTimeout(S,R);return}b*=2,b>m&&(b=m),n&&n.abort(),n=new r,V()},v=W=>(s=W,ee),I=W=>(c=W,ee),P=()=>(h="json",ee),x=()=>{if(!o){if(--l>=0){S(),i&&i();return}o=!0,c&&c(),t&&t()}},C=W=>(d=W,ee),V=()=>{p=Pe(),n=new r,n.open("get",a);let W=0,R,k=0,te=()=>((0,$t.assertNonNullable)(p),Math.max(p,Math.max(R||0,k||0)));if(s&&n.addEventListener("progress",_=>{let ae=Pe();s.updateChunk&&_.loaded>W&&(s.updateChunk(te(),_.loaded-W),W=_.loaded,R=ae)}),u&&(n.timeout=u,n.addEventListener("timeout",()=>x())),n.addEventListener("load",()=>{if(o)return;(0,$t.assertNonNullable)(n);let _=n.status;if(_>=200&&_<300){let{response:ae,responseType:le}=n,ge=ae?.byteLength;if(typeof ge=="number"&&s){let Ee=ge-W;Ee&&s.updateChunk&&s.updateChunk(te(),Ee)}le==="json"&&(!ae||!(0,Mb.default)(ae).length)?x():(c&&c(),e(ae))}else x()}),n.addEventListener("error",()=>{x()}),d){let _=()=>{(0,$t.assertNonNullable)(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(k=Pe(),n.removeEventListener("readystatechange",_))};n.addEventListener("readystatechange",_)}return n.responseType=h,n.send(),ee},ee={withBitrateReporting:v,withParallel:C,withJSONResponse:P,withRetryCount:W=>(l=W,ee),withRetryInterval:(W,R)=>((0,$t.isNonNullable)(W)&&(b=W),(0,$t.isNonNullable)(R)&&(m=R),ee),withTimeout:W=>(u=W,ee),withFinally:I,send:V,abort:()=>{n&&(n.abort(),n=void 0),o=!0,c&&c()}};return ee}var sa=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,i){return{start:e,end:t,bytes:i}}_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 i=0,r=0;for(;this.intervals.length>0;){let s=this.intervals[0];if(s.end<=t)i+=s.end-s.start,r+=s.bytes,this.intervals.splice(0,1);else{if(s.start>=t)break;{let n=t-s.start,u=s.end-s.start;i+=n;let o=s.bytes*n/u;r+=o,s.start=t,s.bytes-=o}}}if(r>0&&i>0){let s=r*8/(i/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(r)}/${Math.round(i)} 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,i){return this.intervals.push(this._createInterval(e,t,i)),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 Cb=Q(Si(),1);var na=class{constructor(e,t,i,r,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=i,this.MAX_PARALLEL_REQUESTS=r,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 i=Pe(),r=o=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=o,e._errorCB?e._errorCB(o):(this.limitCompleteCount(),this.completeRequests[t]=e)},s=o=>{e._complete=1,e._responseData=o,e._downloadTime=Pe()-i,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(o,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},n=()=>{e._finallyCB&&e._finallyCB()},u=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=ur(t,s,()=>r("error"),u),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally(n),this.activeRequests[t]=e,e._request.send(),this.lastPrefetchStart=Pe()}_getParallelRequestCount(){return Math.min(this.MAX_PARALLEL_REQUESTS,this.averageSegmentDuration<3e3?3:2)}_getPrefetchDelay(){return Math.max(100,Math.min(5e3,this.averageSegmentDuration/3))}_canSendPending(){let e=this._getParallelRequestCount(),t=Pe();if(Object.keys(this.activeRequests).length>=e)return!1;let i=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),i>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),i),!1):!0}_sendPending(){for(;this._canSendPending();){let e=this.pendingQueue.pop();if(e){if(this.activeRequests[e]||this.completeRequests[e])continue;this.logger(`Submitting pending request url=${e}`),this._sendRequest({},e)}else return}}_removeFromActive(e){delete this.completeRequests[e],delete this.activeRequests[e]}abortAll(){(0,Cb.default)(this.activeRequests).forEach(e=>{e&&e._request&&e._request.abort()}),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,i,r){let s={};return s.send=()=>{let n=this.activeRequests[e]||this.completeRequests[e];if(n)n._cb=t,n._errorCB=i,n._retryCB=r,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}`),i(n._errorMsg)),s._finallyCB&&s._finallyCB()},0)):this.logger(`Attached to active request, url=${e}`);else{let u=this.pendingQueue.indexOf(e);u!==-1&&this.pendingQueue.splice(u,1),this.logger(`Request not prefetched, starting new request, url=${e}${u===-1?"":"; removed pending"}`),this._sendRequest(s,e)}},s._cb=t,s._errorCB=i,s._retryCB=r,s.abort=function(){s.request&&s.request.abort()},s.withFinally=n=>(s._finallyCB=n,s),s}prefetch(e){this.activeRequests[e]||this.completeRequests[e]?this.logger(`Request already active for url=${e}`):(this.logger(`Added to pending queue; url=${e}`),this.pendingQueue.unshift(e),this._sendPending())}optimizeForSegDuration(e){this.averageSegmentDuration=e}};var Vb=require("@vkontakte/videoplayer-shared");var dn=1e4,cl=3;var FP=6e4,NP=10,qP=1,UP=500,oa=class{constructor(e){this.paused=!1;this.autoQuality=!0;this.autoQualityLimits=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.waitingForFirstBufferAfterSrcChange=!1;this.params=e,this.soundProhibitedEvent$=new Vb.Subject,this.chunkRateEstimator=new sa(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=ll(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setAutoQualityLimits(e){this.autoQualityLimits=e}switchByName(e){let t;for(let i=0;i<this.manifest.length;++i)if(t=this.manifest[i],t.name===e){this._switchToQuality(t);return}}catchUp(){if(this.rep&&this.rep.stop(),this.currentManifestEntry){let e=this.params.playbackState.getState();this.paused=e==="paused",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=ll(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,i=e.buffered.length;return i!==0&&(t=e.buffered.end(i-1)-Math.max(e.currentTime,e.buffered.start(0))),t}_notifyBuffering(e){this.destroyed||(this.params.logger(`buffering: ${e}`),this.params.playerCallback({name:"buffering",isBuffering:e}),this.buffering=e)}_initVideo(){let{videoElement:e,logger:t}=this.params;e.addEventListener("error",()=>{!!e.error&&!this.destroyed&&(t(`Video element error: ${e.error?.code}, details: ${e.error?.message}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{let i=this._getBufferSizeSec();!this.paused&&i<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(i+.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,i=t.buffered.length,r;i!==0&&!this.waitingForFirstBufferAfterSrcChange&&(r=t.buffered.start(i-1),t.currentTime<r&&(e("Fixup stall"),t.currentTime=r))}_selectQuality(e){let{videoElement:t}=this.params,i,r,s,n=t&&1.62*(j.display.pixelRatio||1)*t.offsetHeight||520;for(let u=0;u<this.manifest.length;++u){s=this.manifest[u];let{max:o,min:l}=this.autoQualityLimits||{};!Eb({limits:this.autoQualityLimits,highestAvailableHeight:this.manifest[0].video.height,lowestAvailableHeight:(0,Bb.default)(this.manifest,-1).video.height})&&(o&&s.video.height>o||l&&s.video.height<l)||(s.bitrate<e&&n>Math.min(s.video.height,s.video.width)?(!r||s.bitrate>r.bitrate)&&(r=s):(!i||i.bitrate>s.bitrate)&&(i=s))}return r||i}shouldPlay(){if(this.paused)return!1;let t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||(0,et.isNonNullable)(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){let{logger:i,videoElement:r,playerCallback:s}=this.params;this.mediaSource=new window.MediaSource,i("setting video src"),r.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.videoPlayStarted=!1,r.addEventListener("canplay",()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});let n=()=>{Db(r,"progress",()=>{r.buffered.length?(r.currentTime=r.buffered.start(0),this.waitingForFirstBufferAfterSrcChange=!1,s({name:"playing"})):n()})};this.waitingForFirstBufferAfterSrcChange=!0,n()}_initPlayerWith(e){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new na(cl,dn,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){let{logger:t,videoElement:i,playerCallback:r}=this.params,s=!1,n=null,u=null,o=null,l=null,p=!1,c=()=>{let x=s&&(!p||p===this.rep);return x||t("Not running!"),x},d=(x,C,V)=>{o&&o.abort(),o=ur(this.urlResolver.resolve(x,!1),C,V,()=>this._retryCallback()).withTimeout(dn).withBitrateReporting(this.bitrateSwitcher).withRetryCount(cl).withFinally(()=>{o=null}).send()},h=(x,C,V)=>{(0,et.assertNonNullable)(this.filesFetcher),u?.abort(),u=this.filesFetcher.requestData(this.urlResolver.resolve(x,!1),C,V,()=>this._retryCallback()).withFinally(()=>{u=null}).send()},m=x=>{let C=i.playbackRate;i.playbackRate!==x&&(t(`Playback rate switch: ${C}=>${x}`),i.playbackRate=x)},b=x=>{this.lowLatency=x,t(`lowLatency changed to ${x}`),S()},S=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)m(1);else{let x=this._getBufferSizeSec();if(this.bufferStates.length<5){m(1);return}let V=Pe()-1e4,O=0;for(let N=0;N<this.bufferStates.length;N++){let L=this.bufferStates[N];x=Math.min(x,L.buf),L.ts<V&&O++}this.bufferStates.splice(0,O),t(`update playback rate; minBuffer=${x} drop=${O} jitter=${this.sourceJitter}`);let D=x-qP;this.sourceJitter>=0?D-=this.sourceJitter/2:this.sourceJitter-=1,D>3?m(1.15):D>1?m(1.1):D>.3?m(1.05):m(1)}},v=x=>{let C,V=()=>C&&C.start?C.start.length:0,O=_=>C.start[_]/1e3,D=_=>C.dur[_]/1e3,N=_=>C.fragIndex+_,L=(_,ae)=>({chunkIdx:N(_),startTS:O(_),dur:D(_),discontinuity:ae}),ee=()=>{let _=0;if(C&&C.dur){let ae=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,le=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,ge=ae;this.sourceJitter>1&&(ge+=this.sourceJitter-1);let Ee=C.dur.length-1;for(;Ee>=0&&(ge-=C.dur[Ee],!(ge<=0));--Ee);_=Math.min(Ee,C.dur.length-1-le),_=Math.max(_,0)}return L(_,!0)},W=_=>{let ae=V();if(!(ae<=0)){if((0,et.isNonNullable)(_)){for(let le=0;le<ae;le++)if(O(le)>_)return L(le)}return ee()}},R=_=>{let ae=V(),le=_?_.chunkIdx+1:0,ge=le-C.fragIndex;if(!(ae<=0)){if(!_||ge<0||ge-ae>NP)return t(`Resync: offset=${ge} bChunks=${ae} chunk=`+JSON.stringify(_)),ee();if(!(ge>=ae))return L(le-C.fragIndex,!1)}},k=(_,ae,le)=>{l&&l.abort(),l=ur(this.urlResolver.resolve(_,!0,this.lowLatency),ae,le,()=>this._retryCallback()).withTimeout(dn).withRetryCount(cl).withFinally(()=>{l=null}).withJSONResponse().send()};return{seek:(_,ae)=>{k(x,le=>{if(!c())return;C=le;let ge=!!C.lowLatency;ge!==this.lowLatency&&b(ge);let Ee=0;for(let ke=0;ke<C.dur.length;++ke)Ee+=C.dur[ke];Ee>0&&((0,et.assertNonNullable)(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(Ee/C.dur.length)),r({name:"index",zeroTime:C.zeroTime,shiftDuration:C.shiftDuration}),this.sourceJitter=C.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,C.jitter/1e3)):1,_(W(ae))},()=>this._handleNetworkError())},nextChunk:R}},I=()=>{s=!1,u&&u.abort(),o&&o.abort(),l&&l.abort(),(0,et.assertNonNullable)(this.filesFetcher),this.filesFetcher.abortAll()};return p={start:x=>{let{videoElement:C,logger:V}=this.params,O=v(e.jidxUrl),D,N,L,ee,W=0,R,k,te,_=()=>{R&&(clearTimeout(R),R=void 0);let ie=Math.max(UP,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),$e=W+ie,Be=Pe(),xe=Math.min(1e4,$e-Be);W=Be;let at=()=>{l||c()&&O.seek(()=>{c()&&(W=Pe(),ae(),_())})};xe>0?R=window.setTimeout(()=>{this.paused?_():at()},xe):at()},ae=()=>{let ie;for(;ie=O.nextChunk(ee);)ee=ie,Re(ie);let $e=O.nextChunk(L);if($e){if(L&&$e.discontinuity){V("Detected discontinuity; restarting playback"),this.paused?_():(I(),this._initPlayerWith(e));return}ke($e)}else _()},le=(ie,$e)=>{if(!c()||!this.sourceBuffer)return;let Be,xe,at,Gt=yt=>{window.setTimeout(()=>{c()&&le(ie,$e)},yt)};if(this.sourceBuffer.updating)V("Source buffer is updating; delaying appendBuffer"),Gt(100);else{let yt=Pe(),Ye=C.currentTime;!this.paused&&C.buffered.length>1&&k===Ye&&yt-te>500&&(V("Stall suspected; trying to fix"),this._fixupStall()),k!==Ye&&(k=Ye,te=yt);let zt=this._getBufferSizeSec();if(zt>30)V(`Buffered ${zt} seconds; delaying appendBuffer`),Gt(2e3);else try{this.sourceBuffer.appendBuffer(ie),this.videoPlayStarted?(this.bufferStates.push({ts:yt,buf:zt}),S(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),$e&&$e()}catch(Tt){if(Tt.name==="QuotaExceededError")V("QuotaExceededError; delaying appendBuffer"),at=this.sourceBuffer.buffered.length,at!==0&&(Be=this.sourceBuffer.buffered.start(0),xe=Ye,xe-Be>4&&this.sourceBuffer.remove(Be,xe-3)),Gt(1e3);else throw Tt}}},ge=()=>{N&&D&&(V([`Appending chunk, sz=${N.byteLength}:`,JSON.stringify(L)]),le(N,function(){N=null,ae()}))},Ee=ie=>e.fragUrlTemplate.replace("%%id%%",ie.chunkIdx),ke=ie=>{c()&&h(Ee(ie),($e,Be)=>{if(c()){if(Be/=1e3,N=$e,L=ie,n=ie.startTS,Be){let xe=Math.min(10,ie.dur/Be);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*xe:xe}ge()}},()=>this._handleNetworkError())},Re=ie=>{c()&&((0,et.assertNonNullable)(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(Ee(ie),!1)))},se=ie=>{c()&&(e.cachedHeader=ie,le(ie,()=>{D=!0,ge()}))};s=!0,O.seek(ie=>{if(c()){if(W=Pe(),!ie){_();return}ee=ie,!(0,et.isNullable)(x)||ie.startTS>x?ke(ie):(L=ie,ae())}},x),e.cachedHeader?se(e.cachedHeader):d(e.headerUrl,se,()=>this._handleNetworkError())},stop:I,getTimestampSec:()=>n},p}_switchToQuality(e){let{logger:t,playerCallback:i}=this.params,r;e.bitrate!==this.bitrate&&(this.rep&&(r=this.rep.getTimestampSec(),(0,et.isNonNullable)(r)&&(r+=.1),this.rep.stop()),this.currentManifestEntry=e,this.rep=this._representation(e),t(`switch to quality: codecs=${e.codecs}; headerUrl=${e.headerUrl}; bitrate=${e.bitrate}`),this.bitrate=e.bitrate,(0,et.assertNonNullable)(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(r),i({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return(0,et.isNonNullable)(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,i=c=>{if(!this.autoQuality)return;let d,h,m;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&c<this.bitrate&&(h=this._getBufferSizeSec(),m=c/this.bitrate,h>10&&m>.8||h>15&&m>.5||h>20&&m>.3)){e(`Not switching: buffer=${Math.floor(h)}; bitrate=${this.bitrate}; newRate=${Math.floor(c)}`);return}d=this._selectQuality(c),d?this._switchToQuality(d):e(`Could not find quality by bitrate ${c}`)},s={updateChunk:(d,h)=>{let m=Pe();if(this.chunkRateEstimator.addInterval(d,m,h)){let S=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:h,duration:m-d,speed:S}),!0}},get:()=>{let d=this.chunkRateEstimator.getBitRate();return d?d*.85:0}},n=-1/0,u,o=!0,l=()=>{let c=s.get();if(c&&u&&this.autoQuality){if(o&&c>u&&ul(n)<3e4)return;i(c)}o=this.autoQuality};return{updateChunk:(c,d)=>{let h=s.updateChunk(c,d);return h&&l(),h},notifySwitch:c=>{let d=Pe();c<u&&(n=d),u=c}}}_fetchManifest(e,t,i){this.manifestRequest=ur(this.urlResolver.resolve(e,!0),t,i,()=>this._retryCallback()).withJSONResponse().withTimeout(dn).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;Qe(e,()=>{this.soundProhibitedEvent$.next()}).then(t=>{t||(this.params.liveOffset.pause(),this.params.videoState.setState("paused"))})}_handleManifestUpdate(e){let{logger:t,playerCallback:i,videoElement:r}=this.params,s=n=>{let u=[];return n?.length?(n.forEach((o,l)=>{o.video&&r.canPlayType(o.codecs).replace(/no/,"")&&window.MediaSource?.isTypeSupported?.(o.codecs)&&(o.index=l,u.push(o))}),u.sort(function(o,l){return o.video&&l.video?l.video.height-o.video.height:l.bitrate-o.bitrate}),u):(i({name:"error",type:"empty_manifest"}),[])};this.manifest=s(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),i({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))},FP))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};var _b=Q(zi(),1),be=require("@vkontakte/videoplayer-shared"),dl=class{constructor(){this.onDroopedVideoFramesLimit$=new be.Subject;this.subscription=new be.Subscription;this.playing=!1;this.tracks=[];this.forceChecker$=new be.Subject;this.isForceCheckCounter=0;this.prevTotalVideoFrames=0;this.prevDroppedVideoFrames=0;this.limitCounts={};this.handleChangeVideoQuality=()=>{let e=this.tracks.find(({size:t})=>t?.height===this.video.videoHeight&&t?.width===this.video.videoWidth);e&&!(0,be.isInvariantQuality)(e.quality)&&this.onChangeQuality(e.quality)};this.checkDroppedFrames=()=>{let{totalVideoFrames:e,droppedVideoFrames:t}=this.video.getVideoPlaybackQuality(),i=e-this.prevTotalVideoFrames,r=t-this.prevDroppedVideoFrames,s=1-(i-r)/i;!isNaN(s)&&s>0&&this.log({message:`[dropped]. current dropped percent: ${s}, limit: ${this.droppedFramesChecker.percentLimit}`}),!isNaN(s)&&s>=this.droppedFramesChecker.percentLimit&&(0,be.isHigher)(this.currentQuality,this.droppedFramesChecker.minQualityBanLimit)&&(this.limitCounts[this.currentQuality]=(this.limitCounts[this.currentQuality]??0)+1,this.maxQualityLimit=this.getMaxQualityLimit(this.currentQuality),this.currentTimer&&window.clearTimeout(this.currentTimer),this.currentTimer=window.setTimeout(()=>this.maxQualityLimit=this.getMaxQualityLimit(),this.droppedFramesChecker.qualityUpWaitingTime),this.onDroopedVideoFramesLimitTrigger()),this.savePrevFrameCounts(e,t)}}connect(e){this.log=e.logger.createComponentLog("DroppedFramesManager"),this.video=e.video,this.isAuto=e.isAuto,this.tracks=e.tracks,this.droppedFramesChecker=e.droppedFramesChecker,this.subscription.add(e.playing$.subscribe(()=>this.playing=!0)),this.subscription.add(e.pause$.subscribe(()=>this.playing=!1)),this.isEnabled&&this.subscribe()}destroy(){this.currentTimer&&window.clearTimeout(this.currentTimer),this.subscription.unsubscribe()}get droppedVideoMaxQualityLimit(){return this.maxQualityLimit}subscribe(){this.subscription.add((0,be.fromEvent)(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=(0,be.interval)(this.droppedFramesChecker.checkTime).pipe((0,be.filter)(()=>this.playing),(0,be.filter)(()=>{let r=!!this.isForceCheckCounter;return r&&(this.isForceCheckCounter-=1),!r})),t=this.forceChecker$.pipe((0,be.debounce)(this.droppedFramesChecker.checkTime)),i=(0,be.merge)(e,t);this.subscription.add(i.subscribe(this.checkDroppedFrames))}onChangeQuality(e){this.currentQuality=e;let{totalVideoFrames:t,droppedVideoFrames:i}=this.video.getVideoPlaybackQuality();this.savePrevFrameCounts(t,i),this.isForceCheckCounter=this.droppedFramesChecker.tickCountAfterQualityChange,this.forceChecker$.next()}onDroopedVideoFramesLimitTrigger(){this.isAuto.getState()&&(this.log({message:`[onDroopedVideoFramesLimit]. maxQualityLimit: ${this.maxQualityLimit}`}),this.onDroopedVideoFramesLimit$.next())}getMaxQualityLimit(e){let t=(0,_b.default)(this.limitCounts).filter(([,i])=>i>=this.droppedFramesChecker.countLimit).sort(([i],[r])=>(0,be.isLower)(i,r)?-1:1)?.[0]?.[0];return e??t}get isEnabled(){return this.droppedFramesChecker.enabled&&this.isDroppedFramesCheckerSupport}get isDroppedFramesCheckerSupport(){return!!this.video&&typeof this.video.getVideoPlaybackQuality=="function"}savePrevFrameCounts(e,t){this.prevTotalVideoFrames=e,this.prevDroppedVideoFrames=t}},lr=dl;var pn=require("@vkontakte/videoplayer-shared"),Ob=require("@vkontakte/videoplayer-shared");var ua=()=>!!window.documentPictureInPicture?.window||!!document.pictureInPictureElement;var HP=(a,e)=>new pn.Observable(t=>{if(!window.IntersectionObserver)return;let i={root:null},r=new IntersectionObserver((n,u)=>{n.forEach(o=>t.next(o.isIntersecting||ua()))},{...i,...e});r.observe(a);let s=(0,Ob.fromEvent)(document,"visibilitychange").pipe((0,pn.map)(n=>!document.hidden||ua())).subscribe(n=>t.next(n));return()=>{r.unobserve(a),s.unsubscribe()}}),ut=HP;var jP=["paused","playing","ready"],WP=["paused","playing","ready"],la=class{constructor(e){this.subscription=new Y.Subscription;this.videoState=new Z("stopped");this.representations$=new Y.ValueSubject([]);this.droppedFramesManager=new lr;this.maxSeekBackTime$=new Y.ValueSubject(1/0);this.zeroTime$=new Y.ValueSubject(void 0);this.liveOffset=new xi;this._dashCb=e=>{switch(e.name){case"buffering":{let t=e.isBuffering;this.params.output.isBuffering$.next(t);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${e.type}`,category:Y.ErrorCategory.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{let t=e.manifest,i=[];for(let r of t){let s=r.name??r.index.toString(10),n=ii(r.name)??(0,Y.videoSizeToQuality)(r.video),u=r.bitrate/1e3,o={...r.video};if(!n)continue;let l={id:s,quality:n,bitrate:u,size:o};i.push({track:l,representation:r})}this.representations$.next(i),this.params.output.availableVideoTracks$.next(i.map(({track:r})=>r)),this.videoState.getTransition()?.to==="manifest_ready"&&this.videoState.setState("manifest_ready");break}case"qualitySwitch":{let t=e.quality,i=this.representations$.getValue().find(({representation:r})=>r===t)?.track;this.params.output.hostname$.next(new URL(t.headerUrl,this.params.source.url).hostname),(0,Y.isNonNullable)(i)&&this.params.output.currentVideoTrack$.next(i);break}case"bandwidth":{let{size:t,duration:i}=e;this.params.dependencies.throughputEstimator.addRawSpeed(t,i);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(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; seekState: ${JSON.stringify(s)};`}),i==="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(),u=this.params.desiredState.autoVideoTrackSwitching.getTransition();if((0,pl.default)(WP,e)&&(n||u)){this.prepare();return}if(r?.to!=="paused"&&s.state==="requested"&&(0,pl.default)(jP,e)){this.seek(s.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(ye(this.params.source.url));return;case"manifest_ready":this.videoState.startTransitionTo("ready"),this.prepare();break;case"ready":if(i==="paused")this.videoState.setState("paused");else if(i==="playing"){this.videoState.startTransitionTo("playing");let o=r?.from;o&&o==="ready"&&this.dash.catchUp(),this.dash.play()}return;case"playing":i==="paused"&&(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.dash.pause());return;case"paused":if(i==="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 o=this.liveOffset.getTotalOffset();o>=this.maxSeekBackTime$.getValue()&&(o=0,this.liveOffset.resetTo(o)),this.liveOffset.resume(),this.params.output.position$.next(-o/1e3),this.dash.reinit(ye(this.params.source.url,o))}return;default:return(0,Y.assertNever)(e)}};this.textTracksManager=new ot(e.source.url),this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=r=>{e.output.error$.next({id:"DashLiveProvider",category:Y.ErrorCategory.WTF,message:"DashLiveProvider internal logic error",thrown:r})};this.subscription.add((0,Y.merge)(this.videoState.stateChangeStarted$.pipe((0,Y.map)(r=>({transition:r,type:"start"}))),this.videoState.stateChangeEnded$.pipe((0,Y.map)(r=>({transition:r,type:"end"})))).subscribe(({transition:r,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(r)}`})})),this.video=Ue(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(Me(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 i=We(this.video);this.subscription.add(()=>i.destroy()),this.subscription.add(this.representations$.pipe((0,Y.map)(r=>r.map(({track:s})=>s)),(0,Y.filter)(r=>!!r.length),(0,Y.once)()).subscribe(r=>this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks:r}))),this.subscription.add(i.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready")},t)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused")},t)).add(i.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.videoState.setState("playing")},t)).add(i.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe((0,Y.filterChanged)(),(0,Y.map)(r=>-r/1e3)).subscribe(this.params.output.duration$)).add((0,Y.combine)({zeroTime:this.zeroTime$.pipe((0,Y.filter)(Y.isNonNullable)),position:i.timeUpdate$}).subscribe(({zeroTime:r,position:s})=>this.params.output.liveTime$.next(r+s*1e3),t)).add(kt(this.video,this.params.desiredState.isLooped,t)).add(je(this.video,this.params.desiredState.volume,i.volumeState$,t)).add(i.volumeState$.subscribe(this.params.output.volume$,t)).add(nt(this.video,this.params.desiredState.playbackRate,i.playbackRateState$,t)).add(i.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(i.loadedMetadata$.subscribe(this.params.output.loadedMetadataEvent$)).add(i.playing$.subscribe(this.params.output.firstFrameEvent$)).add(i.canplay$.subscribe(this.params.output.canplay$)).add(i.inPiP$.subscribe(this.params.output.inPiP$)).add(i.inFullscreen$.subscribe(this.params.output.inFullscreen$)).add(ut(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:r,min:s}})=>{this.dash.setAutoQualityLimits({max:r&&(0,Y.videoQualityToHeight)(r),min:s&&(0,Y.videoQualityToHeight)(s)}),this.params.output.autoVideoTrackLimits$.next({max:r,min:s})})).add(this.videoState.stateChangeEnded$.subscribe(r=>{switch(r.to){case"stopped":this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState("stopped");break;case"manifest_ready":case"ready":this.params.desiredState.playbackState.getTransition()?.to==="ready"&&this.params.desiredState.playbackState.setState("ready");break;case"paused":this.params.desiredState.playbackState.setState("paused");break;case"playing":this.params.desiredState.playbackState.setState("playing");break;default:return(0,Y.assertNever)(r.to)}},t)).add((0,Y.merge)(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,(0,Y.observableFrom)(["init"])).pipe((0,Y.debounce)(0)).subscribe(this.syncPlayback,t))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.droppedFramesManager.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),He(this.video)}createLiveDashPlayer(){let e=new oa({videoElement:this.video,videoState:this.videoState,playbackState:this.params.desiredState.playbackState,liveOffset:this.liveOffset,config:{maxParallelRequests:this.params.config.maxParallelRequests,minBuffer:this.params.tuning.live.minBuffer,minBufferSegments:this.params.tuning.live.minBufferSegments,lowLatencyMinBuffer:this.params.tuning.live.lowLatencyMinBuffer,lowLatencyMinBufferSegments:this.params.tuning.live.lowLatencyMinBufferSegments,isLiveCatchUpMode:this.params.tuning.live.isLiveCatchUpMode,manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},playerCallback:this._dashCb,logger:t=>{this.params.dependencies.logger.log({message:String(t),component:"LiveDashPlayer"})}});return e.pause(),e}prepare(){let e=this.representations$.getValue(),t=this.params.desiredState.videoTrack.getTransition()?.to??this.params.desiredState.videoTrack.getState(),i=this.params.desiredState.autoVideoTrackSwitching.getTransition()?.to??this.params.desiredState.autoVideoTrackSwitching.getState(),r=!i&&(0,Y.isNonNullable)(t)?t:Rt(e.map(({track:l})=>l),{container:this.video.getBoundingClientRect(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),s=r?.id,n=this.params.desiredState.videoTrack.getTransition(),u=this.params.desiredState.videoTrack.getState()?.id,o=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(r&&(n||s!==u)&&this.setVideoTrack(r),o&&this.setAutoQuality(i),n||o||s!==u){let l=e.find(({track:p})=>p.id===s)?.representation;(0,Y.assertNonNullable)(l,"Representations missing"),this.dash.startPlay(l,i)}}setVideoTrack(e){let t=this.representations$.getValue().find(({track:i})=>i.id===e.id)?.representation;(0,Y.assertNonNullable)(t,`No such representation ${e.id}`),this.dash.switchByName(t.name),this.params.desiredState.videoTrack.setState(e)}setAutoQuality(e){this.dash.setAutoQualityEnabled(e),this.params.desiredState.autoVideoTrackSwitching.setState(e)}seek(e){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),i=this.videoState.getState(),r=t==="paused"&&i==="paused",s=-e,n=s<=this.maxSeekBackTime$.getValue()?s:0;this.params.output.position$.next(e/1e3),this.dash.reinit(ye(this.params.source.url,n)),r&&this.dash.pause(),this.liveOffset.resetTo(n,r)}};var Fb=la;var De=(a,e)=>{let t=0;for(let i=0;i<a.length;i++){let r=a.start(i)*1e3,s=a.end(i)*1e3;r<=e&&e<=s&&(t=s)}return Math.max(t-e,0)};var F=require("@vkontakte/videoplayer-shared");var{NativeAbortSignal:C0,NativeAbortController:B0}=function(a){return{NativeAbortSignal:a.AbortSignal,NativeAbortController:a.AbortController}}(typeof self<"u"?self:global);function Nb(a){let e;try{e=new Event("abort")}catch{typeof document<"u"?document.createEvent?(e=document.createEvent("Event"),e.initEvent("abort",!1,!1)):(e=document.createEventObject(),e.type="abort"):e={type:"abort",bubbles:!1,cancelable:!1}}return e.reason=a,e}function qb(a){if(a===void 0)if(typeof document>"u")a=new Error("This operation was aborted"),a.name="AbortError";else try{a=new DOMException("signal is aborted without reason"),Object.defineProperty(a,"name",{value:"AbortError"})}catch{a=new Error("This operation was aborted"),a.name="AbortError"}return a}var hn=class{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,i){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:i})}removeEventListener(e,t){if(!(e in this.listeners))return;let i=this.listeners[e];for(let r=0,s=i.length;r<s;r++)if(i[r].callback===t){i.splice(r,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;let i=this.listeners[e.type].slice();for(let r=0,s=i.length;r<s;r++){let n=i[r];try{n.callback.call(this,e)}catch(u){Promise.resolve().then(()=>{throw u})}n.options&&n.options.once&&this.removeEventListener(e.type,n.callback)}return!e.defaultPrevented}},cr=class extends hn{constructor(){super(),this.listeners||hn.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)}throwIfAborted(){let{aborted:e,reason:t="Aborted"}=this;if(e)throw t}static timeout(e){let t=new Ai;return setTimeout(()=>t.abort(new DOMException(`This signal is timeout in ${e}ms`,"TimeoutError")),e),t.signal}static any(e){let t=new Ai;function i(){t.abort(this.reason),r()}function r(){for(let s of e)s.removeEventListener("abort",i)}for(let s of e)if(s.aborted){t.abort(s.reason);break}else s.addEventListener("abort",i);return t.signal}},Ai=class{constructor(){Object.defineProperty(this,"signal",{value:new cr,writable:!0,configurable:!0})}abort(e){let t=qb(e),i=Nb(t);this.signal.reason=t,this.signal.dispatchEvent(i)}toString(){return"[object AbortController]"}};typeof Symbol<"u"&&Symbol.toStringTag&&(Ai.prototype[Symbol.toStringTag]="AbortController",cr.prototype[Symbol.toStringTag]="AbortSignal");function fn(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 hl(a){typeof a=="function"&&(a={fetch:a});let{fetch:e,Request:t=e.Request,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r=!1}=a;if(!fn({fetch:e,Request:t,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r}))return{fetch:e,Request:s};let s=t;(s&&!s.prototype.hasOwnProperty("signal")||r)&&(s=function(l,p){let c;p&&p.signal&&(c=p.signal,delete p.signal);let d=new t(l,p);return c&&Object.defineProperty(d,"signal",{writable:!1,enumerable:!1,configurable:!0,value:c}),d},s.prototype=t.prototype);let n=e;return{fetch:(o,l)=>{let p=s&&s.prototype.isPrototypeOf(o)?o.signal:l?l.signal:void 0;if(p){let c;try{c=new DOMException("Aborted","AbortError")}catch{c=new Error("Aborted"),c.name="AbortError"}if(p.aborted)return Promise.reject(c);let d=new Promise((h,m)=>{p.addEventListener("abort",()=>m(c),{once:!0})});return l&&l.signal&&delete l.signal,Promise.race([d,n(o,l)])}return n(o,l)},Request:s}}var QP=()=>"fetch"in window,ca=QP()&&fn({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),Ub=ca?hl({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,lt=ca?Ub.fetch:window.fetch,W0=ca?Ub.Request:window.Request,ue=ca?Ai:window.AbortController,Q0=ca?cr:window.AbortSignal;var HS=Q(Oe(),1),Vl=Q(da(),1);var kg=Q(Pg(),1),dr=require("@vkontakte/videoplayer-shared"),mn=a=>{if(!a)return{id:"EmptyResponse",category:dr.ErrorCategory.PARSER,message:"Empty response"};if(a.length<=2&&a.match(/^\d+$/))return{id:`UVError#${a}`,category:dr.ErrorCategory.NETWORK,message:`UV Error ${a}`};let e=(0,kg.default)(a).substring(0,100).toLowerCase();if(e.startsWith("<!doctype")||e.startsWith("<html>")||e.startsWith("<body>")||e.startsWith("<head>"))return{id:"UnexpectedHTML",category:dr.ErrorCategory.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:dr.ErrorCategory.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:dr.ErrorCategory.PARSER,message:"Response is valid XML, but parser failed"}};var Ce=(a,e,t=0)=>{for(let i=0;i<a.length;i++)if(a.start(i)*1e3-t<=e&&a.end(i)*1e3+t>e)return!0;return!1};var T=require("@vkontakte/videoplayer-shared");var Sn=Q(Oe(),1),Ri=Q(gt(),1),vn=Q(da(),1);var Lk=(a,e={})=>{let i=e.timeout||1,r=performance.now();return window.setTimeout(()=>{a({get didTimeout(){return e.timeout?!1:performance.now()-r-1>i},timeRemaining(){return Math.max(0,1+(performance.now()-r))}})},1)},Mk=a=>window.clearTimeout(a),Rg=a=>typeof a=="function"&&a?.toString().endsWith("{ [native code] }"),$g=!Rg(window.requestIdleCallback)||!Rg(window.cancelIdleCallback),pr=$g?Lk:window.requestIdleCallback,Lt=$g?Mk:window.cancelIdleCallback;var OS=Q(zs(),1);var ai=require("@vkontakte/videoplayer-shared");var Dk=18,Lg=!1;try{Lg=j.browser.isSafari&&!!j.browser.safariVersion&&j.browser.safariVersion<=Dk}catch(a){console.error(a)}var vl=class{constructor(e){this.bufferFull$=new ai.Subject;this.error$=new ai.Subject;this.queue=[];this.currentTask=null;this.destroyed=!1;this.abortRequested=!1;this.completeTask=()=>{try{if(this.currentTask){let e=this.currentTask.signal?.aborted;this.currentTask.callback(!e),this.currentTask=null}this.queue.length&&this.pull()}catch(e){this.error$.next({id:"BufferTaskQueueUnknown",category:ai.ErrorCategory.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:e})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(i=>{let r={operation:"append",data:e,signal:t,callback:i};this.queue.push(r),this.pull()})}async remove(e,t,i){return i&&i.aborted?!1:new Promise(r=>{let s={operation:"remove",from:e,to:t,signal:i,callback:r};this.queue.unshift(s),this.pull()})}async abort(e){return new Promise(t=>{let i,r=s=>{this.abortRequested=!1,t(s)};Lg&&e?i={operation:"safariAbort",init:e,callback:r}:i={operation:"abort",callback:r};for(let{callback:s}of this.queue)s(!1);this.abortRequested=!0,i&&(this.queue=[i]),this.pull()})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){if((this.buffer.updating||this.currentTask||this.destroyed)&&!this.abortRequested)return;let e=this.queue.shift();if(!e)return;if(e.signal?.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(r){r instanceof DOMException&&r.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):r instanceof DOMException&&r.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:ai.ErrorCategory.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:r}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){let{operation:t}=e;switch(t){case"append":this.buffer.appendBuffer(e.data);break;case"remove":this.buffer.remove(e.from/1e3,e.to/1e3);break;case"abort":this.buffer.abort();break;case"safariAbort":{this.buffer.abort(),this.buffer.appendBuffer(e.init);break}default:(0,ai.assertNever)(t)}}},Mg=vl;var hr=a=>{let e=0;for(let t=0;t<a.length;t++)e+=a.end(t)-a.start(t);return e*1e3};var w=require("@vkontakte/videoplayer-shared");var Cg=Q(gt(),1);var bn=a=>a.valid,ne=class{constructor(e,t){this.cursor=0;this.source=e,this.boxParser=t,this.children=[];let i=this.readUint32();this.type=this.readString(4),i===1&&(this.cursor+=8);let r=e.byteOffset+this.cursor,s;i===0?(this.size=void 0,this.valid=!1,s=void 0):i===1?(this.size=void 0,this.valid=!1,s=void 0):i>e.byteLength?(this.size=i,this.valid=!1,s=Math.min(i-this.cursor,e.byteLength-this.cursor)):(this.size=i,this.valid=!0,s=i-this.cursor),this.content=new DataView(e.buffer,r,s)}get id(){return this.type}scanForBoxes(e){return this.boxParser.parse(e)}readString(e,t="ascii"){let r=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,r}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 fr=class extends ne{};var Dg=require("@vkontakte/videoplayer-shared");var ha=class extends ne{constructor(e,t){if(super(e,t),!this.valid)return;let i=this.readString(16),r=new DataView(this.content.buffer,this.content.byteOffset+16,this.content.byteLength-16);this.userData=this.parseData(i,r)}parseData(e,t){switch(e){case"ondemandlivejson":{let i=new TextDecoder("ascii").decode(t),r=JSON.parse(i);return{received:r["t-in"],prepared:r["t-out"]}}default:(0,Dg.assertNever)(e)}}};var fa=class extends ne{constructor(e,t){if(super(e,t),!this.valid)return;this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let i=new DataView(this.content.buffer,this.content.byteOffset+8,this.content.byteLength-8);for(let r=0;r<i.byteLength;r+=4){let s=this.readString(4);this.compatibleBrands.push(s)}}};var ma=class extends ne{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var pe=class extends ne{constructor(e,t){if(super(e,t),!this.valid)return;let i=this.readUint32();this.version=i>>>24,this.flags=i&16777215,this.content=new DataView(this.content.buffer,this.content.byteOffset+4,this.content.byteLength-4)}};var ba=class extends pe{constructor(e,t){super(e,t),this.valid&&(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 ga=class extends ne{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Sa=class extends ne{constructor(e,t){super(e,t),this.data=this.content}};var Pi=class extends pe{get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e,t){if(super(e,t),!!this.valid){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 i=0;i<this.referenceCount;i++){let r=this.readUint32(),s=r>>>31,n=r<<1>>>1,u=this.readUint32();r=this.readUint32();let o=r>>>28,l=r<<3>>>3;this.segments.push({referenceType:s,referencedSize:n,subsegmentDuration:u,SAPType:o,SAPDeltaTime:l})}}}};var va=class extends ne{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ya=class extends ne{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ta=class extends pe{constructor(e,t){if(super(e,t),!this.valid)return;switch(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 Ia=class extends pe{constructor(e,t){super(e,t),this.valid&&(this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32())}};var Ea=class extends pe{constructor(e,t){super(e,t),this.valid&&(this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32())}};var xa=class extends ne{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var wa=class extends pe{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 Aa=class extends ne{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Pa=class extends ne{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ka=class extends pe{constructor(e,t){super(e,t),this.valid&&(this.sequenceNumber=this.readUint32())}};var Ra=class extends ne{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var $a=class extends pe{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 La=class extends pe{constructor(t,i){super(t,i);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 Ma=class extends pe{constructor(t,i){super(t,i);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 r=0;r<this.sampleCount;r++)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 Da=class extends ne{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ca=class extends pe{constructor(e,t){super(e,t),this.valid&&(this.entryCount=this.readUint32(),this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+4,this.content.byteLength-4)))}};var Ba=class extends ne{constructor(e,t){super(e,t),this.valid&&(this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+78,this.content.byteLength-78)))}};var Bk={ftyp:fa,moov:ma,mvhd:ba,moof:ga,mdat:Sa,sidx:Pi,trak:va,mdia:xa,mfhd:ka,tkhd:wa,traf:Ra,tfhd:$a,tfdt:La,trun:Ma,minf:Aa,sv3d:ya,st3d:Ta,prhd:Ia,proj:Pa,equi:Ea,uuid:ha,stbl:Da,stsd:Ca,avc1:Ba,unknown:fr},qt=class a{constructor(e={}){this.options={offset:0,...e}}parse(e){let t=[],i=this.options.offset;for(;i<e.byteLength;){let s=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+i+4,4)),n;try{n=this.createBox(s,new DataView(e.buffer,e.byteOffset+i,e.byteLength-i))}catch(u){if(!(u instanceof RangeError))throw u}if(!n||!bn(n))break;t.push(n),i+=n.size}return t}createBox(e,t){let i=Bk[e];return i?new i(t,new a):new fr(t,new a)}};var si=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{bn(t)&&(this.index[t.type]??=[],this.index[t.type].push(t),t.children.length>0&&this.indexBoxLevel(t.children))})}find(e){return this.index[e]&&this.index[e][0]?this.index[e][0]:null}findAll(e){return this.index[e]||[]}};var _k=new TextDecoder("ascii"),Ok=a=>_k.decode(new DataView(a.buffer,a.byteOffset+4,4))==="ftyp",Fk=a=>{let e=new Pi(a,new qt),t=e.earliestPresentationTime/e.timescale*1e3,i=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,u={status:"none",time:{from:t,to:t+n},byte:{from:i,to:i+s.referencedSize-1}};return t+=n,i+=s.referencedSize,u})},Nk=(a,e)=>{let i=new qt().parse(a),r=new si(i),s=r.findAll("moof"),n=e?r.findAll("uuid"):r.findAll("mdat");if(!(n.length&&s.length))return null;let u=s[0],o=n[n.length-1],l=u.source.byteOffset,c=o.source.byteOffset-u.source.byteOffset+o.size;return new DataView(a.buffer,l,c)},qk=a=>{let t=new qt().parse(a),i=new si(t),r={},s=i.findAll("uuid"),n=(0,Cg.default)(s,-1);return n?{serverDataReceivedTimestamp:n.userData.received,serverDataPreparedTime:n.userData.received}:r},Uk=a=>{let t=new qt().parse(a);return new si(t).find("sidx")?.timescale},Hk=(a,e)=>{let i=new qt().parse(a),s=new si(i).findAll("traf"),n=s[s.length-1].children.find(c=>c.type==="tfhd"),u=s[s.length-1].children.find(c=>c.type==="tfdt"),o=s[s.length-1].children.find(c=>c.type==="trun"),l=0;return o.sampleDuration.length?l=o.sampleDuration.reduce((c,d)=>c+d,0):l=n.defaultSampleDuration*o.sampleCount,(Number(u.baseMediaDecodeTime)+l)/e*1e3},jk=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}}},i=new qt().parse(a),r=new si(i);if(r.find("sv3d")){e.is3dVideo=!0;let n=r.find("st3d");n&&(e.stereoMode=n.stereoMode);let u=r.find("prhd");u&&(e.projectionData.pose.yaw=u.poseYawDegrees,e.projectionData.pose.pitch=u.posePitchDegrees,e.projectionData.pose.roll=u.poseRollDegrees);let o=r.find("equi");o&&(e.projectionData.bounds.top=o.projectionBoundsTop,e.projectionData.bounds.right=o.projectionBoundsRight,e.projectionData.bounds.bottom=o.projectionBoundsBottom,e.projectionData.bounds.left=o.projectionBoundsLeft)}return e},Bg={validateData:Ok,parseInit:jk,getIndexRange:()=>{},parseSegments:Fk,parseFeedableSegmentChunk:Nk,getChunkEndTime:Hk,getServerLatencyTimestamps:qk,getTimescaleFromIndex:Uk};var Oa=Q(Oe(),1),Ut=require("@vkontakte/videoplayer-shared");var _g=require("@vkontakte/videoplayer-shared");var Vg={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"}},Og=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 i=_a(a,t),r=i in Vg,s=r?Vg[i].type:"binary",n=a.getUint8(t),u=0;n&128?u=1:n&64?u=2:n&32?u=3:n&16?u=4:n&8?u=5:n&4?u=6:n&2?u=7:n&1&&(u=8);let o=new DataView(a.buffer,a.byteOffset+t+1,u-1),l=n&255>>u,p=_a(o),c=l*2**((u-1)*8)+p,d=t+u,h;return d+c>a.byteLength?h=new DataView(a.buffer,a.byteOffset+d):h=new DataView(a.buffer,a.byteOffset+d,c),{tag:r?i:"0x"+i.toString(16).toUpperCase(),type:s,tagHeaderSize:d,tagSize:d+c,value:h,valueSize:c}},_a=(a,e=a.byteLength)=>{switch(e){case 1:return a.getUint8(0);case 2:return a.getUint16(0);case 3:return a.getUint8(0)*2**16+a.getUint16(1);case 4:return a.getUint32(0);case 5:return a.getUint8(0)*2**32+a.getUint32(1);case 6:return a.getUint16(0)*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},St=(a,e)=>{switch(e){case"int":return a.getInt8(0);case"uint":return _a(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:(0,_g.assertNever)(e)}},ki=(a,e)=>{let t=0;for(;t<a.byteLength;){let i=new DataView(a.buffer,a.byteOffset+t),r=Og(i);if(!e(r))return;r.type==="master"&&ki(r.value,e),t=r.value.byteOffset-a.byteOffset+r.valueSize}},Fg=a=>{if(a.getUint32(0)!==440786851)return!1;let e,t,i,r=Og(a);return ki(r.value,({tag:s,type:n,value:u})=>(s===17143?e=St(u,n):s===17026?t=St(u,n):s===17029&&(i=St(u,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)};var Ng=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],Wk=[231,22612,22743,167,171,163,160,175],Qk=a=>{let e,t,i,r,s=!1,n=!1,u=!1,o,l,p=!1,c=0;return ki(a,({tag:d,type:h,value:m,valueSize:b})=>{if(d===21419){let S=St(m,h);l=_a(S)}else d!==21420&&(l=void 0);return d===408125543?(e=m.byteOffset,t=m.byteOffset+b):d===357149030?s=!0:d===290298740?n=!0:d===2807729?i=St(m,h):d===17545?r=St(m,h):d===21420&&l===475249515?o=St(m,h):d===374648427?ki(m,({tag:S,type:v,value:I})=>S===30321?(p=St(I,v)===1,!1):!0):s&&n&&(0,Oa.default)(Ng,d)&&(u=!0),!u}),(0,Ut.assertNonNullable)(e,"Failed to parse webm Segment start"),(0,Ut.assertNonNullable)(t,"Failed to parse webm Segment end"),(0,Ut.assertNonNullable)(r,"Failed to parse webm Segment duration"),i=i??1e6,{segmentStart:Math.round(e/1e9*i*1e3),segmentEnd:Math.round(t/1e9*i*1e3),timeScale:i,segmentDuration:Math.round(r/1e9*i*1e3),cuesSeekPosition:o,is3dVideo:p,stereoMode:c,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},Gk=a=>{if((0,Ut.isNullable)(a.cuesSeekPosition))return;let e=a.segmentStart+a.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},zk=(a,e)=>{let t=!1,i=!1,r=u=>(0,Ut.isNonNullable)(u.time)&&(0,Ut.isNonNullable)(u.position),s=[],n;return ki(a,({tag:u,type:o,value:l})=>{switch(u){case 475249515:t=!0;break;case 187:n&&r(n)&&s.push(n),n={};break;case 179:n&&(n.time=St(l,o));break;case 183:break;case 241:n&&(n.position=St(l,o));break;default:t&&(0,Oa.default)(Ng,u)&&(i=!0)}return!(t&&i)}),n&&r(n)&&s.push(n),s.map((u,o)=>{let{time:l,position:p}=u,c=s[o+1];return{status:"none",time:{from:l,to:c?c.time:e.segmentDuration},byte:{from:e.segmentStart+p,to:c?e.segmentStart+c.position-1:e.segmentEnd-1}}})},Yk=a=>{let e=0,t=!1;try{ki(a,i=>i.tag===524531317?i.tagSize<=a.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):(0,Oa.default)(Wk,i.tag)?(e+i.tagSize<=a.byteLength&&(e+=i.tagSize,t||=(0,Oa.default)([163,160,175],i.tag)),!0):!1)}catch{}return e>0&&e<=a.byteLength&&t?new DataView(a.buffer,a.byteOffset,e):null},qg={validateData:Fg,parseInit:Qk,getIndexRange:Gk,parseSegments:zk,parseFeedableSegmentChunk:Yk};var Mt=a=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(a);if(e){let[,t,i]=e;if(t==="audio"||t==="video")switch(i){case"webm":return qg;case"mp4":return Bg}}throw new ReferenceError(`Unsupported mime type ${a}`)};var Dt=a=>a instanceof DOMException&&(a.name==="AbortError"||a.code===20);var Al=Q(cS(),1),LS=Q(zi(),1),MS=Q(AS(),1),DS=Q(gt(),1),Pl=Q(Si(),1);var PS=Q(Oe(),1),wl=a=>{let e=a.split("."),[t,...i]=e;if(!t)return!1;switch(t){case"av01":{let[r,s,n]=i;return!!(n&&parseInt(n,10)>8)}case"vp09":{let[r,s,n]=i;return!!(r&&parseInt(r,10)>=2&&n&&parseInt(n,10)>8)}case"avc1":{let r=i[0];if(!r||r.length!==6)return!1;let[s,n]=r.toUpperCase(),u=s+n;return(0,PS.default)(["6E","7A","F4"],u)}}return!1};var Fa=require("@vkontakte/videoplayer-shared");var kS=a=>{if(a.includes("/")){let e=a.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(a)};var RS=a=>{try{let e=zR(),t=a.match(e),{groups:i}=t??{};if(i){let r={};if(i.extensions){let u=i.extensions.toLowerCase().match(/(?:[0-9a-wy-z](?:-[a-z0-9]{2,8})+)/g);Array.from(u||[]).forEach(o=>{r[o[0]]=o.slice(2)})}let s=i.variants?.split(/-/).filter(u=>u!==""),n={extlang:i.extlang,langtag:i.langtag,language:i.language,privateuse:i.privateuse||i.privateuse2,region:i.region,script:i.script,extensions:r,variants:s};return Object.keys(n).forEach(u=>{let o=n[u];(typeof o>"u"||o==="")&&delete n[u]}),n}return null}catch{return null}};function zR(){let a="(?<extlang>(?:[a-z]{3}(?:-[a-z]{3}){0,2}))",e="x(?:-[a-z0-9]{1,8})+",p=`^(?:(?<langtag>${`
118
118
  (?<language>${`(?:[a-z]{2,3}(?:-${a})?|[a-z]{4}|[a-z]{5,8})`})
119
119
  (-(?<script>[a-z]{4}))?
120
120
  (-(?<region>(?:[a-z]{2}|[0-9]{3})))?
121
121
  (?<variants>(?:-(?:[a-z0-9]{5,8}|[0-9][a-z0-9]{3}))*)
122
122
  (?<extensions>(?:-[0-9a-wy-z](?:-[a-z0-9]{2,8})+)*)
123
123
  (?:-(?<privateuse>(?:${e})))?
124
- `})|(?<privateuse2>${e}))$`.replace(/[\s\t\n]/g,"");return new RegExp(p,"i")}var $S=a=>{if(!a?.startsWith("P"))return;let e=(n,u)=>{let o=n?parseFloat(n.replace(",",".")):NaN;return(isNaN(o)?0:o)*u},i=/^(-|\+)?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),r=i?.[1]==="-"?-1:1,s={days:e(i?.[5],r),hours:e(i?.[6],r),minutes:e(i?.[7],r),seconds:e(i?.[8],r)};return s.days*24*60*60*1e3+s.hours*60*60*1e3+s.minutes*60*1e3+s.seconds*1e3},vt=(a,e)=>{let t=a;t=(0,kl.default)(t,"$$","$");let i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[r,s]of(0,LS.default)(i)){let n=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=(0,kl.default)(t,n,(u,o)=>(0,Fa.isNullable)(s)?u:(0,Fa.isNullable)(o)?s:(0,MS.default)(s,parseInt(o,10),"0"))}return t},gn=(a,e)=>{let i=new DOMParser().parseFromString(a,"application/xml"),r={video:[],audio:[],text:[]},s=i.children[0],n=Array.from(s.querySelectorAll("MPD > BaseURL").values()).map(N=>N.textContent?.trim()??""),u=(0,DS.default)(n,0)??"",o=s.getAttribute("type")==="dynamic",l=s.getAttribute("availabilityStartTime"),p=s.getAttribute("publishTime"),c=s.getElementsByTagName("vk:Attrs")[0],d=c?.getElementsByTagName("vk:XLatestSegmentPublishTime")[0].textContent,h=c?.getElementsByTagName("vk:XStreamIsLive")[0].textContent,m=c?.getElementsByTagName("vk:XStreamIsUnpublished")[0].textContent,b=c?.getElementsByTagName("vk:XPlaybackDuration")[0].textContent,S;o&&(S={availabilityStartTime:l?new Date(l).getTime():0,publishTime:p?new Date(p).getTime():0,latestSegmentPublishTime:d?new Date(d).getTime():0,streamIsAlive:h==="yes",streamIsUnpublished:m==="yes"});let v,I=s.getAttribute("mediaPresentationDuration"),A=[...s.getElementsByTagName("Period")],x=A.reduce((N,L)=>({...N,[L.id]:L.children}),{}),C=A.reduce((N,L)=>({...N,[L.id]:L.getAttribute("duration")}),{});I?v=$S(I):(0,Al.default)(C).filter(N=>N).length&&!o?v=(0,Al.default)(C).reduce((N,L)=>N+($S(L)??0),0):b&&(v=parseInt(b,10));let V=0,O=s.getAttribute("profiles")?.split(",")??[];for(let N of A.map(L=>L.id))for(let L of x[N]){let ee=L.getAttribute("id")??"id"+(V++).toString(10),W=L.getAttribute("mimeType")??"",R=L.getAttribute("codecs")??"",P=L.getAttribute("contentType")??W?.split("/")[0],te=L.getAttribute("profiles")?.split(",")??[],_=RS(L.getAttribute("lang")??"")??{},ae=L.querySelector("Label")?.textContent?.trim()??void 0,le=L.querySelectorAll("Representation"),ge=L.querySelector("SegmentTemplate"),Ee=L.querySelector("Role")?.getAttribute("value")??void 0,Pe=P,Re={id:ee,language:_.language,isDefault:Ee==="main",label:ae,codecs:R,hdr:Pe==="video"&&wl(R),mime:W,representations:[]};for(let se of le){let ie=se.getAttribute("lang")??void 0,$e=ae??L.getAttribute("label")??se.getAttribute("label")??void 0,Be=se.querySelector("BaseURL")?.textContent?.trim()??"",xe=new URL(Be||u,e).toString(),at=se.getAttribute("mimeType")??W,Gt=se.getAttribute("codecs")??R??"",yt;if(P==="text"){let Ye=se.getAttribute("id")||"",zt=_.privateuse?.includes("x-auto")||Ye.includes("_auto"),Tt=se.querySelector("SegmentTemplate");if(Tt){let xr={representationId:se.getAttribute("id")??void 0,bandwidth:se.getAttribute("bandwidth")??void 0},ss=parseInt(se.getAttribute("bandwidth")??"",10)/1e3,ns=parseInt(Tt.getAttribute("startNumber")??"",10)??1,Bi=parseInt(Tt.getAttribute("timescale")??"",10),to=Tt.querySelectorAll("SegmentTimeline S")??[],Vi=Tt.getAttribute("media");if(!Vi)continue;let os=[],us=0,ls="",_i=0,wr=ns,Ve=0;for(let dt of to){let ci=parseInt(dt.getAttribute("d")??"",10),st=parseInt(dt.getAttribute("r")??"",10)||0,Yt=parseInt(dt.getAttribute("t")??"",10);Ve=Number.isFinite(Yt)?Yt:Ve;let di=ci/Bi*1e3,Oi=Ve/Bi*1e3;for(let It=0;It<st+1;It++){let Kt=vt(Vi,{...xr,segmentNumber:wr.toString(10),segmentTime:(Ve+It*ci).toString(10)}),Fi=(Oi??0)+It*di,Ar=Fi+di;wr++,os.push({time:{from:Fi,to:Ar},url:Kt})}Ve+=(st+1)*ci,us+=(st+1)*di}_i=Ve/Bi*1e3,ls=vt(Vi,{...xr,segmentNumber:wr.toString(10),segmentTime:Ve.toString(10)});let kr={time:{from:_i,to:1/0},url:ls},Bt={type:"template",baseUrl:xe,segmentTemplateUrl:Vi,initUrl:"",totalSegmentsDurationMs:us,segments:os,nextSegmentBeyondManifest:kr,timescale:Bi};yt={id:Ye,kind:"text",segmentReference:Bt,profiles:[],duration:v,bitrate:ss,mime:"",codecs:"",width:0,height:0,isAuto:zt}}else yt={id:Ye,isAuto:zt,kind:"text",url:xe}}else{let Ye=se.getAttribute("contentType")??at?.split("/")[0]??P,zt=L.getAttribute("profiles")?.split(",")??[],Tt=parseInt(se.getAttribute("width")??"",10),xr=parseInt(se.getAttribute("height")??"",10),ss=parseInt(se.getAttribute("bandwidth")??"",10)/1e3,ns=se.getAttribute("frameRate")??"",Bi=se.getAttribute("quality")??void 0,to=ns?PS(ns):void 0,Vi=se.getAttribute("id")??"id"+(V++).toString(10),os=Ye==="video"?`${xr}p`:Ye==="audio"?`${ss}Kbps`:Gt,us=`${Vi}@${os}`,ls=[...O,...te,...zt],_i,wr=se.querySelector("SegmentBase"),Ve=se.querySelector("SegmentTemplate")??ge;if(wr){let Bt=se.querySelector("SegmentBase Initialization")?.getAttribute("range")??"",[dt,ci]=Bt.split("-").map(Kt=>parseInt(Kt,10)),st={from:dt,to:ci},Yt=se.querySelector("SegmentBase")?.getAttribute("indexRange"),[di,Oi]=Yt?Yt.split("-").map(Kt=>parseInt(Kt,10)):[],It=Yt?{from:di,to:Oi}:void 0;_i={type:"byteRange",url:xe,initRange:st,indexRange:It}}else if(Ve){let Bt={representationId:se.getAttribute("id")??void 0,bandwidth:se.getAttribute("bandwidth")??void 0},dt=parseInt(Ve.getAttribute("timescale")??"",10),ci=Ve.getAttribute("initialization")??"",st=Ve.getAttribute("media"),Yt=parseInt(Ve.getAttribute("startNumber")??"",10)??1,di=vt(ci,Bt);if(!st)throw new ReferenceError("No media attribute in SegmentTemplate");let Oi=Ve.querySelectorAll("SegmentTimeline S")??[],It=[],Kt=0,Fi="",Ar=0;if(Oi.length){let cs=Yt,pt=0;for(let Ni of Oi){let Et=parseInt(Ni.getAttribute("d")??"",10),pi=parseInt(Ni.getAttribute("r")??"",10)||0,ds=parseInt(Ni.getAttribute("t")??"",10);pt=Number.isFinite(ds)?ds:pt;let io=Et/dt*1e3,kv=pt/dt*1e3;for(let ps=0;ps<pi+1;ps++){let Av=vt(st,{...Bt,segmentNumber:cs.toString(10),segmentTime:(pt+ps*Et).toString(10)}),tc=(kv??0)+ps*io,Pv=tc+io;cs++,It.push({time:{from:tc,to:Pv},url:Av})}pt+=(pi+1)*Et,Kt+=(pi+1)*io}Ar=pt/dt*1e3,Fi=vt(st,{...Bt,segmentNumber:cs.toString(10),segmentTime:pt.toString(10)})}else if((0,Fa.isNonNullable)(v)){let pt=parseInt(Ve.getAttribute("duration")??"",10)/dt*1e3,Ni=Math.ceil(v/pt),Et=0;for(let pi=1;pi<Ni;pi++){let ds=vt(st,{...Bt,segmentNumber:pi.toString(10),segmentTime:Et.toString(10)});It.push({time:{from:Et,to:Et+pt},url:ds}),Et+=pt}Ar=Et,Fi=vt(st,{...Bt,segmentNumber:Ni.toString(10),segmentTime:Et.toString(10)})}let wv={time:{from:Ar,to:1/0},url:Fi};_i={type:"template",baseUrl:xe,segmentTemplateUrl:st,initUrl:di,totalSegmentsDurationMs:Kt,segments:It,nextSegmentBeyondManifest:wv,timescale:dt}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!Ye||!at)continue;let kr={video:"video",audio:"audio",text:"text"}[Ye];if(!kr)continue;Pe||=kr,yt={id:us,kind:kr,segmentReference:_i,profiles:ls,duration:v,bitrate:ss,mime:at,codecs:Gt,width:Tt,height:xr,fps:to,quality:Bi}}Re.language||=ie,Re.label||=$e,Re.mime||=at,Re.codecs||=Gt,Re.hdr||=Pe==="video"&&wl(Gt),Re.representations.push(yt)}if(Pe){let se=r[Pe].find(ie=>ie.id===Re.id);if(se&&Re.representations.every(ie=>ie.segmentReference.type==="template"))for(let ie of se.representations){let $e=Re.representations.find(at=>at.id===ie.id);if(!$e)continue;let Be=$e.segmentReference,xe=ie.segmentReference;xe.segments.push(...Be.segments),xe.nextSegmentBeyondManifest=Be.nextSegmentBeyondManifest}else r[Pe].push(Re)}}return{duration:v,streams:r,baseUrls:n,live:S}};var Pl=Q(gt(),1);var CS=require("@vkontakte/videoplayer-shared"),Na=({id:a,width:e,height:t,bitrate:i,fps:r,quality:s,streamId:n})=>{let u=(s?ii(s):void 0)??(0,CS.videoSizeToQuality)({width:e,height:t});return u&&{id:a,quality:u,bitrate:i,size:{width:e,height:t},fps:r,streamId:n}},BS=({id:a,bitrate:e})=>({id:a,bitrate:e}),VS=({language:a,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:a,label:e}),_S=({language:a,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:a,label:e}),Rl=({id:a,language:e,label:t,codecs:i,isDefault:r})=>({id:a,language:e,label:t,codec:(0,Pl.default)(i.split("."),0),isDefault:r}),$l=({id:a,language:e,label:t,hdr:i,codecs:r})=>({id:a,language:e,hdr:i,label:t,codec:(0,Pl.default)(r.split("."),0)}),Ll=a=>"url"in a,tt=a=>a.type==="template";var Ml=require("@vkontakte/videoplayer-shared"),X=(a,e)=>(0,Ml.isNonNullable)(a)&&(0,Ml.isNonNullable)(e)&&a.readyState==="open"&&YR(a,e);function YR(a,e){for(let t=0;t<a.activeSourceBuffers.length;++t)if(a.activeSourceBuffers[t]===e)return!0;return!1}var qa=class{constructor(e,t,i,{fetcher:r,tuning:s,getCurrentPosition:n,isActiveLowLatency:u,compatibilityMode:o=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new w.ValueSubject(0);this.currentLowLatencySegmentLength$=new w.ValueSubject(0);this.currentSegmentLength$=new w.ValueSubject(0);this.onLastSegment$=new w.ValueSubject(!1);this.fullyBuffered$=new w.ValueSubject(!1);this.playingRepresentation$=new w.ValueSubject(void 0);this.playingRepresentationInit$=new w.ValueSubject(void 0);this.error$=new w.Subject;this.gaps=[];this.subscription=new w.Subscription;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new ue;this.switchAbortController=new ue;this.destroyAbortController=new ue;this.useSmartRepresentationSwitch=!1;this.bufferLimit=1/0;this.failedDownloads=0;this.baseUrls=[];this.baseUrlsIndex=0;this.isLive=!1;this.liveUpdateSegmentIndex=0;this.liveInitialAdditionalOffset=0;this.isSeekingLive=!1;this.index=0;this.lastDataObtainedTimestampMs=0;this.loadByteRangeSegmentsTimeoutId=0;this.startWith=(0,w.abortable)(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);(0,w.assertNonNullable)(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new Mg(this.sourceBuffer),this.subscription.add((0,w.fromEvent)(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let u,o=this.mediaSource.readyState;o!=="open"&&(u={id:`SegmentEjection_source_${o}`,category:w.ErrorCategory.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),u??={id:"SegmentEjection",category:w.ErrorCategory.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n},this.error$.next(u)})),this.subscription.add((0,w.fromEvent)(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:w.ErrorCategory.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let u=this.getCurrentPosition();if(!this.sourceBuffer||!u||!X(this.mediaSource,this.sourceBuffer))return;let o=Math.min(this.bufferLimit,hr(this.sourceBuffer.buffered)*.8);this.bufferLimit=o;let l=this.getForwardBufferDuration(u),p=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(u,n*2,l<p).catch(c=>{this.handleAsyncError(c,"pruneBuffer")})})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(n=>this.error$.next(n))),yield this.loadInit(t,"high",!0);let i=this.initData.get(t.id),r=this.segments.get(t.id),s=this.parsedInitData.get(t.id);(0,w.assertNonNullable)(i,"No init buffer for starting representation"),(0,w.assertNonNullable)(r,"No segments for starting representation"),i instanceof ArrayBuffer&&(this.searchGaps(r,t),yield this.sourceBufferTaskQueue.append(i,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(s))}.bind(this));this.switchTo=(0,w.abortable)(this.destroyAbortController.signal,async function*(e,t=!1){if(!X(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);(0,w.assertNonNullable)(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if((0,w.isNullable)(s)||(0,w.isNullable)(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),(0,w.assertNonNullable)(r,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!X(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer();else{let n=this.getCurrentPosition();(0,w.isNonNullable)(n)&&!this.isLive&&(this.bufferLimit=1/0,await this.pruneBuffer(n,1/0,!0)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}this.maintain()}}.bind(this));this.switchToOld=(0,w.abortable)(this.destroyAbortController.signal,async function*(e,t=!1){if(!X(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);(0,w.assertNonNullable)(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if((0,w.isNullable)(s)||(0,w.isNullable)(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),(0,w.assertNonNullable)(r,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!X(this.mediaSource,this.sourceBuffer)))if(yield this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer(),this.maintain();else{let n=this.getCurrentPosition();(0,w.isNonNullable)(n)&&(this.isLive||(this.bufferLimit=1/0,await this.pruneBuffer(n,1/0,!0)),this.maintain(n)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}}.bind(this));this.seekLive=(0,w.abortable)(this.destroyAbortController.signal,async function*(e){let t=(0,vn.default)(e,o=>o.representations);if(!this.downloadingRepresentationId||!t.length)return;this.isSeekingLive=!0;for(let o of this.representations.keys()){let l=t.find(d=>d.id===o);l&&this.representations.set(o,l);let p=this.representations.get(o);if(!p||!tt(p.segmentReference)){this.isSeekingLive=!1;return}let c=this.getActualLiveStartingSegments(p.segmentReference);this.segments.set(p.id,c)}let i=this.switchingToRepresentationId??this.downloadingRepresentationId,r=this.representations.get(i);(0,w.assertNonNullable)(r,`Representation not found by id ${i}`);let s=this.segments.get(i);(0,w.assertNonNullable)(s,"No segments for starting representation");let n=this.initData.get(i);if((0,w.assertNonNullable)(n,"No init buffer for starting representation"),!(n instanceof ArrayBuffer)){this.isSeekingLive=!1;return}let u=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,yield this.abort(),u&&(yield this.sourceBufferTaskQueue.remove(u.from*1e3,u.to*1e3,this.destroyAbortController.signal)),this.searchGaps(s,r),yield this.sourceBufferTaskQueue.append(n,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this));this.fetcher=r,this.tuning=s,this.compatibilityMode=o,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=u,this.isLive=!!l?.live,this.baseUrls=l?.baseUrls??[],this.initData=new Map(i.map(p=>[p.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(i.map(p=>[p.id,p])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}switchToWithPreviousAbort(e,t=!1){!X(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new ue,(0,w.abortable)(this.switchAbortController.signal,async function*(i,r=!1){this.switchingToRepresentationId=i;let s=this.representations.get(i);(0,w.assertNonNullable)(s,`No such representation ${i}`);let n=this.segments.get(i),u=this.initData.get(i);if((0,w.isNullable)(u)||(0,w.isNullable)(n)?yield this.loadInit(s,"high",!1):u instanceof Promise&&(yield u),n=this.segments.get(i),(0,w.assertNonNullable)(n,"No segments for starting representation"),u=this.initData.get(i),!(!(u instanceof ArrayBuffer)||!this.sourceBuffer||!X(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(u,this.downloadAbortController.signal),r)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=i,yield this.dropBuffer();else{let o=this.getCurrentPosition();(0,w.isNonNullable)(o)&&!this.isLive&&(this.bufferLimit=this.forwardBufferTarget,yield this.pruneBuffer(o,1/0,!0)),this.downloadingRepresentationId=i,this.switchingToRepresentationId=void 0}this.maintain()}}.bind(this))(e,t))}warmUpMediaSource(){!(0,w.isNullable)(this.sourceBuffer)&&!this.sourceBuffer.updating&&(this.sourceBuffer.mode="segments")}async abort(){for(let e of this.activeSegments)this.abortSegment(e.segment);return this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new ue,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if((0,w.isNullable)(e)||(0,w.isNullable)(this.downloadingRepresentationId)||(0,w.isNullable)(this.playingRepresentationId)||(0,w.isNullable)(this.sourceBuffer)||!X(this.mediaSource,this.sourceBuffer)||(0,w.isNonNullable)(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.representations.get(this.playingRepresentationId),r=this.segments.get(this.downloadingRepresentationId),s=this.segments.get(this.playingRepresentationId);if((0,w.assertNonNullable)(t,`No such representation ${this.downloadingRepresentationId}`),(0,w.assertNonNullable)(i,`No such representation ${this.playingRepresentationId}`),(0,w.isNullable)(r)||(0,w.isNullable)(s))return;let n=r.find(d=>e>=d.time.from&&e<d.time.to);(0,w.isNonNullable)(n)&&isFinite(n.time.from)&&isFinite(n.time.to)&&this.currentSegmentLength$.next(n?.time.to-n.time.from);let u=e,o=100;if(this.playingRepresentationId!==this.downloadingRepresentationId){let d=this.getForwardBufferDuration(e),h=Na(i),m=Na(t),b=this.useSmartRepresentationSwitch&&this.tuning.dash.useNewRepresentationSwitch&&this.tuning.dash.useSmartRepresentationSwitch&&(0,w.isNonNullable)(h)&&(0,w.isNonNullable)(m)&&(0,w.isHigher)(h.quality,m.quality),S=this.useSmartRepresentationSwitch&&this.tuning.dash.useNewRepresentationSwitch&&this.tuning.dash.useDelayedRepresentationSwitch;if(b||S?u+=Math.min(d,this.tuning.dash.representationSwitchForwardBufferGap):n&&n.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&d>=n.time.to-e+o&&(u=n?n.time.to+o:-1/0),this.tuning.dash.useNewRepresentationSwitch){let I=[...this.segments.entries()].map(([A,x])=>{let C=x.find(V=>e>=V.time.from&&e<V.time.to);return{representationId:A,status:C?.status}}).find(A=>A.status==="fed")?.representationId;I&&(this.playingRepresentationId=I,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)))}}if(isFinite(this.bufferLimit)&&hr(this.sourceBuffer.buffered)>=this.bufferLimit){let d=this.getForwardBufferDuration(e),h=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,d<h).catch(m=>{this.handleAsyncError(m,"pruneBuffer")});return}let p=[];if(!this.activeSegments.size&&(p=this.selectForwardBufferSegments(r,t.segmentReference.type,u),p.length)){let d="auto";if(this.tuning.dash.useFetchPriorityHints&&n)if((0,Sn.default)(p,n))d="high";else{let h=(0,Ri.default)(p,0);h&&h.time.from-n.time.to>=this.forwardBufferTarget/2&&(d="low")}this.loadSegments(p,t,d).catch(h=>{this.handleAsyncError(h,"loadSegments")})}(!this.preloadOnly&&!this.allInitsLoaded&&n&&n.status==="fed"&&!p.length&&this.getForwardBufferDuration(e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let c=(0,Ri.default)(r,-1);!this.isLive&&c&&(this.fullyBuffered$.next(c.time.to-e-this.getForwardBufferDuration(e)<o),this.onLastSegment$.next(e-c.time.from>0))}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}searchGaps(e,t){this.gaps=[];let i=0,r=this.isLive?this.liveInitialAdditionalOffset:0;for(let s of e)Math.trunc(s.time.from-i)>0&&this.gaps.push({representation:t.id,from:i,to:s.time.from+r,persistent:!0}),i=s.time.to;(0,w.isNonNullable)(t.duration)&&t.duration-i>0&&!this.isLive&&this.gaps.push({representation:t.id,from:i,to:t.duration,persistent:!0})}getActualLiveStartingSegments(e){let t=e.segments,i=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,r=[],s=0,n=t.length-1;do r.unshift(t[n]),s+=t[n].time.to-t[n].time.from,n--;while(s<i&&n>=0);return this.liveInitialAdditionalOffset=s-i,this.isActiveLowLatency()?[r[0]]:r}getLiveSegmentsToLoadState(e){let t=e?.streams[this.kind];if(!t)return;let i=(0,vn.default)(t,s=>s.representations).find(s=>s.id===this.downloadingRepresentationId);if(!i)return;let r=this.segments.get(i.id);if(r?.length)return{from:r[0].time.from,to:r[r.length-1].time.to}}updateLive(e){if(!e||[...this.segments.values()].every(i=>!i.length))return;let t=(0,vn.default)(e.streams[this.kind],i=>i.representations);for(let i of t){if(!i||!tt(i.segmentReference))return;let r=i.segmentReference.segments.map(l=>({...l,status:"none",size:void 0})),s=100,n=this.segments.get(i.id)??[],u=(0,Ri.default)(n,-1)?.time.to??0,o=r?.findIndex(l=>u>=l.time.from+s&&u<=l.time.to+s);if(o===-1){this.liveUpdateSegmentIndex=0;let l=this.getActualLiveStartingSegments(i.segmentReference);this.segments.set(i.id,l)}else{let l=r.slice(o+1);this.segments.set(i.id,[...n,...l])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;(0,w.assertNonNullable)(e);let t=this.segments.get(e);if(t?.length){let i=t[t.length-1];this.updateLowLatencyLiveIfNeeded(i)}}calculateDurationFromSegments(){if(!this.playingRepresentationId)return 0;let e=this.segments.get(this.playingRepresentationId);return(e?(0,Ri.default)(e,-1)?.time.to:0)||0}setSmartRepresentationSwitch(e){this.useSmartRepresentationSwitch=e}updateLowLatencyLiveIfNeeded(e){let t=0;for(let i of this.representations.values()){let r=i.segmentReference;if(!tt(r))return;let s=this.segments.get(i.id)??[],n=s.find(o=>Math.floor(o.time.from)===Math.floor(e.time.from));if(n&&!isFinite(n.time.to)&&(n.time.to=e.time.to,t=n.time.to-n.time.from),!!!s.find(o=>Math.floor(o.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let o=Math.round(e.time.to*r.timescale/1e3).toString(10),l=vt(r.segmentTemplateUrl,{segmentTime:o});s.push({status:"none",time:{from:e.time.to,to:1/0},url:l})}}this.currentLowLatencySegmentLength$.next(t)}findSegmentStartTime(e){let t=this.switchingToRepresentationId??this.downloadingRepresentationId??this.playingRepresentationId;if(!t)return;let i=this.segments.get(t);return i?i.find(s=>s.time.from<=e&&s.time.to>=e)?.time.from??void 0:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),this.sourceBufferTaskQueue?.destroy(),this.gapDetectionIdleCallback&&Lt&&Lt(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&Lt&&Lt(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer)try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(e){if(!(e instanceof DOMException&&e.name==="NotFoundError"))throw e}this.sourceBuffer=null,this.downloadAbortController.abort(),this.switchAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,i){return this.isLive?this.selectForwardBufferSegmentsLive(e,i):this.selectForwardBufferSegmentsRecord(e,t,i)}selectForwardBufferSegmentsLive(e,t){let i=e.findIndex(r=>t>=r.time.from&&t<r.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=i),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,i){let r=this.getForwardBufferDuration(i),s=e.findIndex(({status:d,time:{from:h,to:m}},b)=>{let S=h<=i&&m>=i,v=h>i||S||b===0&&i===0,I=Math.min(this.forwardBufferTarget,this.bufferLimit),A=this.preloadOnly&&h<=i+I||r<I&&m-h>=I||m<=i+I;return(d==="none"||d==="partially_ejected"&&v&&A&&this.sourceBuffer&&X(this.mediaSource,this.sourceBuffer)&&!(Ce(this.sourceBuffer.buffered,h)&&Ce(this.sourceBuffer.buffered,m)))&&v&&A});if(s===-1)return[];if(t!=="byteRange")return e.slice(s,s+1);let n=e,u=0,o=0,l=[],p=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,c=this.preloadOnly?this.forwardBufferTarget:0;for(let d=s;d<n.length&&(u<=p||o<=c);d++){let h=n[d];if(u+=h.byte.to+1-h.byte.from,o+=h.time.to+1-h.time.from,h.status==="none"||h.status==="partially_ejected")l.push(h);else break}return l}async loadSegments(e,t,i="auto"){tt(t.segmentReference)?await this.loadTemplateSegment(e[0],t,i):await this.loadByteRangeSegments(e,t,i)}async loadTemplateSegment(e,t,i="auto"){e.status="downloading";let r={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(r);let{range:s,url:n,signal:u,onProgress:o,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&u&&(await(0,w.abortable)(u,async function*(){let p=(0,w.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>setTimeout(c,p))}.bind(this))(),u.aborted&&this.abortActiveSegments([e]));try{let p=await this.fetcher.fetch(n,{range:s,signal:u,onProgress:o,priority:i,isLowLatency:this.isActiveLowLatency(),bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation});if(this.lastDataObtainedTimestampMs=(0,w.now)(),!p)return;let c=new DataView(p),d=Mt(t.mime);if(!isFinite(r.segment.time.to)){let b=t.segmentReference.timescale;r.segment.time.to=d.getChunkEndTime(c,b)}o&&r.feedingBytes&&l?await Promise.all(l):await this.sourceBufferTaskQueue.append(c,u);let{serverDataReceivedTimestamp:h,serverDataPreparedTime:m}=d.getServerLatencyTimestamps(c);h&&m&&this.currentLiveSegmentServerLatency$.next(m-h),r.segment.status="downloaded",this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(p){this.abortActiveSegments([e]),Dt(p)||(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())tt(t.segmentReference)?t.segmentReference.baseUrl=e:t.segmentReference.url=e}async loadByteRangeSegments(e,t,i="auto"){if(!e.length)return;for(let o of e)o.status="downloading",this.activeSegments.add({segment:o,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:r,url:s,signal:n,onProgress:u}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(await(0,w.abortable)(n,async function*(){let o=(0,w.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,o),(0,w.fromEvent)(window,"online").pipe((0,w.once)()).subscribe(()=>{l(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(s,{range:r,onProgress:u,signal:n,priority:i,bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation}),this.lastDataObtainedTimestampMs=(0,w.now)(),this.failedDownloads=0}catch(o){this.abortActiveSegments(e),Dt(o)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}prepareByteRangeFetchSegmentParams(e,t){if(tt(t.segmentReference))throw new Error("Representation is not byte range type");let i=t.segmentReference.url,r={from:(0,Ri.default)(e,0).byte.from,to:(0,Ri.default)(e,-1).byte.to},{signal:s}=this.downloadAbortController;return{url:i,range:r,signal:s,onProgress:async(u,o)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=(0,w.now)(),await this.onSomeByteRangesDataLoaded({dataView:u,loaded:o,signal:s,onSegmentAppendFailed:()=>this.abort(),globalFrom:r?r.from:0,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:w.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!tt(t.segmentReference))throw new Error("Representation is not template type");let i=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&i.searchParams.set("low-latency","yes");let r=i.toString(),{signal:s}=this.downloadAbortController,n=[],o=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(l,p)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=(0,w.now)();let c=this.onSomeTemplateDataLoaded({dataView:l,loaded:p,signal:s,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(c)}catch(c){this.error$.next({id:"SegmentFeeding",category:w.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:c})}}:void 0;return{url:r,signal:s,onProgress:o,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)(0,Sn.default)(e,t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:r,signal:s}){if(!this.activeSegments.size||!X(this.mediaSource,this.sourceBuffer))return;let n=this.representations.get(t);if(n)for(let u of this.activeSegments){let{segment:o}=u;if(u.representationId===t){if(s.aborted){r();continue}if(u.loadedBytes=i,u.loadedBytes>u.feedingBytes){let l=new DataView(e.buffer,e.byteOffset+u.feedingBytes,u.loadedBytes-u.feedingBytes),p=Mt(n.mime).parseFeedableSegmentChunk(l,this.isLive);p?.byteLength&&(o.status="partially_fed",u.feedingBytes+=p.byteLength,await this.sourceBufferTaskQueue.append(p),u.fedBytes+=p.byteLength)}}}}async onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:s,onSegmentAppendFailed:n}){if(!this.activeSegments.size||!X(this.mediaSource,this.sourceBuffer))return;let u=this.representations.get(t);if(u)for(let o of this.activeSegments){let{segment:l}=o;if(o.representationId!==t)continue;if(s.aborted){await n();continue}let p=l.byte.from-i,c=l.byte.to-i,d=c-p+1,h=p<r,m=c<=r;if(!h)continue;let b=Mt(u.mime);if(l.status==="downloading"&&m){l.status="downloaded";let S=new DataView(e.buffer,e.byteOffset+p,d);await this.sourceBufferTaskQueue.append(S,s)&&!s.aborted?this.onSegmentFullyAppended(o,t):await n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(l.status==="downloading"||l.status==="partially_fed")&&(o.loadedBytes=Math.min(d,r-p),o.loadedBytes>o.feedingBytes)){let S=new DataView(e.buffer,e.byteOffset+p+o.feedingBytes,o.loadedBytes-o.feedingBytes),v=o.loadedBytes===d?S:b.parseFeedableSegmentChunk(S);v?.byteLength&&(l.status="partially_fed",o.feedingBytes+=v.byteLength,await this.sourceBufferTaskQueue.append(v,s)&&!s.aborted?(o.fedBytes+=v.byteLength,o.fedBytes===d&&this.onSegmentFullyAppended(o,t)):await n())}}}onSegmentFullyAppended(e,t){if(!((0,w.isNullable)(this.sourceBuffer)||!X(this.mediaSource,this.sourceBuffer))){!this.isLive&&j.browser.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(Ce(this.sourceBuffer.buffered,e.segment.time.from,100)&&Ce(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:w.ErrorCategory.VIDEO_PIPELINE,message:"Browser stuck on empty result of adding segment to source buffer"})),this.tuning.dash.useNewRepresentationSwitch||(this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId))),e.segment.status="fed",Ll(e.segment)&&(e.segment.size=e.fedBytes);for(let i of this.representations.values())if(i.id!==t)for(let r of this.segments.get(i.id)??[])r.status==="fed"&&Math.round(r.time.from)===Math.round(e.segment.time.from)&&Math.round(r.time.to)===Math.round(e.segment.time.to)&&(r.status="none");this.updateLowLatencyLiveIfNeeded(e.segment),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment])}}abortSegment(e){e.status==="partially_fed"?e.status="partially_ejected":e.status!=="partially_ejected"&&(e.status="none");for(let t of this.activeSegments.values())if(t.segment===e){this.activeSegments.delete(t);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(let[r,s]of this.initData.entries()){let n=s instanceof Promise;t||=n,s===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let i=this.representations.get(e);i&&(this.initLoadIdleCallback=pr(()=>(0,OS.default)(this.loadInit(i,"low",!1),()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",i=!1){let r=this.tuning.dash.useFetchPriorityHints?t:"auto",s=!i&&this.tuning.dash.ignoreNetworkErrorsOnLoadInit,u=(!i&&this.failedDownloads>0?(0,w.abortable)(this.destroyAbortController.signal,async function*(){let o=(0,w.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>setTimeout(l,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,Mt(e.mime),{priority:r,ignoreNetworkErrors:s})).then(async o=>{if(!o)return;let{init:l,dataView:p,segments:c}=o,d=p.buffer.slice(p.byteOffset,p.byteOffset+p.byteLength);this.initData.set(e.id,d);let h=c;this.isLive&&tt(e.segmentReference)&&(h=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,h),l&&this.parsedInitData.set(e.id,l)}).then(()=>this.failedDownloads=0,o=>{s||this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:w.ErrorCategory.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,u),u}async dropBuffer(){for(let e of this.segments.values())for(let t of e)t.status="none";await this.pruneBuffer(0,1/0,!0)}async pruneBuffer(e,t,i=!1){if(!this.sourceBuffer||!X(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||(0,w.isNullable)(e))return!1;let r=[],s=0,n=o=>{o.sort((p,c)=>p.from-c.from);let l=[o[0]];for(let p=1;p<o.length;p++){let{from:c,to:d}=o[p],h=l[l.length-1];h.to>=c?h.to=Math.max(h.to,d):l.push(o[p])}return l},u=o=>{if(s>=t)return r;r.push({...o.time}),r=n(r);let l=Ll(o)?o.size??0:o.byte.to-o.byte.from;s+=l};for(let o of this.segments.values())for(let l of o){let p=l.time.to<=e-this.tuning.dash.bufferPruningSafeZone,c=l.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(p||c)&&l.status==="fed"&&u(l)}for(let o=0;o<this.sourceBuffer.buffered.length;o++){let l=this.sourceBuffer.buffered.start(o)*1e3,p=this.sourceBuffer.buffered.end(o)*1e3,c=0;for(let d of this.segments.values())for(let h of d)(0,Sn.default)(["none","partially_ejected"],h.status)&&Math.round(h.time.from)<=Math.round(l)&&Math.round(h.time.to)>=Math.round(p)&&c++;if(c===this.segments.size){let d={time:{from:l,to:p},url:"",status:"none"};u(d)}}if(r.length&&i){let o=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let l of this.segments.values())for(let p of l)p.time.from>=e+o&&p.status==="fed"&&u(p)}return r.length?(await Promise.all(r.map(l=>this.sourceBufferTaskQueue.remove(l.from,l.to)))).reduce((l,p)=>l||p,!1):!1}async abortBuffer(){if(!this.sourceBuffer||!X(this.mediaSource,this.sourceBuffer))return!1;let e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;return this.sourceBufferTaskQueue.abort(t)}getDebugBufferState(){if(!(!this.sourceBuffer||!X(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}getForwardBufferDuration(e=this.getCurrentPosition()){return!this.sourceBuffer||!X(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||(0,w.isNullable)(e)?0:De(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!(!this.sourceBuffer||!X(this.mediaSource,this.sourceBuffer)))for(let i of t){let r={representation:e,from:i.time.from,to:i.time.to,persistent:!1},{buffered:s}=this.sourceBuffer;for(let n=0;n<s.length;n++){let u=s.start(n)*1e3,o=s.end(n)*1e3;if(!(o<=i.time.from||u>=i.time.to)){if(u<=i.time.from&&o>=i.time.to){r=void 0;break}o>i.time.from&&o<i.time.to&&(r.from=o),u<i.time.to&&u>i.time.from&&(r.to=u)}}r&&r.to-r.from>1&&!this.gaps.some(n=>r&&n.from===r.from&&n.to===r.to)&&this.gaps.push(r)}}detectGapsWhenIdle(e,t){if(this.gapDetectionIdleCallback||!this.sourceBuffer||!X(this.mediaSource,this.sourceBuffer))return;let{buffered:i}=this.sourceBuffer,{usePersistentGaps:r}=this.tuning.dash;this.gaps=this.gaps.filter(s=>{if(r&&s.persistent)return!0;let n=Math.round(s.from),u=Math.round(s.to);for(let o=0;o<i.length;o++)if(n>=Math.round(i.start(o)*1e3)&&u<=Math.round(i.end(o)*1e3))return!1;return!0}),this.gapDetectionIdleCallback=pr(()=>{try{this.detectGaps(e,t)}catch(s){this.error$.next({id:"GapDetection",category:w.ErrorCategory.WTF,message:"detectGaps threw",thrown:s})}finally{this.gapDetectionIdleCallback=null}})}checkEjectedSegments(){if((0,w.isNullable)(this.sourceBuffer)||!X(this.mediaSource,this.sourceBuffer)||(0,w.isNullable)(this.playingRepresentationId))return;let e=[];for(let i=0;i<this.sourceBuffer.buffered.length;i++){let r=Math.floor(this.sourceBuffer.buffered.start(i)*1e3),s=Math.ceil(this.sourceBuffer.buffered.end(i)*1e3);e.push({from:r,to:s})}let t=100;for(let i of this.segments.values())for(let r of i){let{status:s}=r;if(s!=="fed"&&s!=="partially_ejected")continue;let n=Math.floor(r.time.from),u=Math.ceil(r.time.to),o=e.some(p=>p.from-t<=n&&p.to+t>=u),l=e.filter(p=>n>=p.from&&n<p.to-t||u>p.from+t&&u<=p.to);o||(l.length===1?r.status="partially_ejected":this.gaps.some(p=>p.from===r.time.from||p.to===r.time.to)?r.status="partially_ejected":r.status="none")}}handleAsyncError(e,t){this.error$.next({id:t,category:w.ErrorCategory.VIDEO_PIPELINE,thrown:e,message:"Something went wrong"})}};var ni=a=>{let e=new URL(a);return e.searchParams.set("quic","1"),e.toString()};var yn=a=>{let e=a.get("X-Delivery-Type"),t=a.get("X-Reused"),i=e===null?"http1":e??void 0,r=t===null?void 0:{1:!0,0:!1}[t]??void 0;return{type:i,reused:r}};var G=require("@vkontakte/videoplayer-shared");var Tn=a=>{let e=new URL(a);return e.searchParams.set("enable-subtitles","yes"),e.toString()};var En=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:s=!1}){this.manifestRequested$=new G.Subject;this.firstBytesManifest$=new G.Subject;this.manifestReceived$=new G.Subject;this.firstBytesRequested$=new G.Subject;this.firstBytesReceived$=new G.Subject;this.lastConnectionType$=new G.ValueSubject(void 0);this.lastConnectionReused$=new G.ValueSubject(void 0);this.lastRequestFirstBytes$=new G.ValueSubject(void 0);this.recoverableError$=new G.Subject;this.error$=new G.Subject;this.abortAllController=new ue;this.subscription=new G.SubscriptionRemovable;this.fetchManifest=(0,G.abortable)(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=ni(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=Tn(i)),this.manifestRequested$.next();let r=yield this.doFetch(i,{signal:this.abortAllController.signal},{type:"manifest"}).catch(In);return r?(t.log("success",(0,G.flattenObject)({url:i,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(r.headers),this.manifestReceived$.next(),r.text()):(t.error("error",(0,G.flattenObject)({url:i,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=(0,G.abortable)(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:i,onProgress:r,priority:s="auto",signal:n,measureThroughput:u=!0,isLowLatency:o=!1,bufferOptimisation:l=!1,ignoreNetworkErrors:p=!1}={}){let c=e,d=new Headers,h=this.tracer.createComponentTracer("Fetch");if(i)switch(t){case 0:{d.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let P=new URL(c,location.href);P.searchParams.append("bytes",`${i.from}-${i.to}`),c=P.toString();break}default:(0,G.assertNever)(t)}this.requestQuic&&(c=ni(c));let m=this.abortAllController.signal,b;if(n){let P=new ue;if(b=(0,G.merge)((0,G.fromEvent)(this.abortAllController.signal,"abort"),(0,G.fromEvent)(n,"abort")).subscribe(()=>{try{P.abort()}catch(te){In(te)}}),this.subscription.add(b),this.abortAllController.signal.aborted||n.aborted)try{P.abort()}catch(te){In(te)}m=P.signal}let S=0,v=(0,G.now)();h.log("startRequest",(0,G.flattenObject)({url:c,priority:s,rangeMethod:t,range:i,isLowLatency:o,requestStartedAt:v})),this.firstBytesRequested$.next();let I=yield this.doFetch(c,{priority:s,headers:d,signal:m},{ignoreNetworkErrors:p}),A=(0,G.now)();if(!I)return h.error("error",{message:"No response in request"}),h.end(),this.unsubscribeAbortSubscription(b),null;if(this.throughputEstimator?.addRawRtt(A-v),!I.ok||!I.body){this.unsubscribeAbortSubscription(b);let P=`Fetch error ${I.status}: ${I.statusText}`;return h.error("error",{message:P}),h.end(),Promise.reject(new Error(`Fetch error ${I.status}: ${I.statusText}`))}if(this.onHeadersReceived(I.headers),!r&&!u){this.unsubscribeAbortSubscription(b);let P=(0,G.now)(),te={requestStartedAt:v,requestEndedAt:P,duration:P-v};return h.log("endRequest",(0,G.flattenObject)(te)),h.end(),I.arrayBuffer()}let x=I.body;if(u){let P;[x,P]=I.body.tee(),this.throughputEstimator?.trackStream(P,o)}let C=x.getReader(),V,O=parseInt(I.headers.get("content-length")??"",10);Number.isFinite(O)&&(V=O),!V&&i&&(V=i.to-i.from+1);let D=V?new Uint8Array(V):new Uint8Array(0),N=!1,L=P=>{this.unsubscribeAbortSubscription(b),N=!0,In(P)},ee=(0,G.abortable)(m,async function*({done:P,value:te}){if(S===0&&(this.lastRequestFirstBytes$.next((0,G.now)()-v),this.firstBytesReceived$.next()),m.aborted){this.unsubscribeAbortSubscription(b);return}if(!P&&te){if(l&&V)D.set(te,S),S+=te.byteLength;else{let _=new Uint8Array(D.length+te.length);_.set(D),_.set(te,D.length),D=_,S+=te.byteLength}r?.(new DataView(D.buffer),S),yield C?.read().then(ee,L)}}.bind(this));yield C?.read().then(ee,L),this.unsubscribeAbortSubscription(b);let W=(0,G.now)(),R={failed:N,requestStartedAt:v,requestEndedAt:W,duration:W-v};return N?(h.error("endRequest",(0,G.flattenObject)(R)),h.end(),null):(h.log("endRequest",(0,G.flattenObject)(R)),h.end(),D.buffer)}.bind(this));this.fetchByteRangeRepresentation=(0,G.abortable)(this.abortAllController.signal,async function*(e,t,i){if(e.type!=="byteRange")return null;let{from:r,to:s}=e.initRange,n=r,u=s,o=!1,l,p;e.indexRange&&(l=e.indexRange.from,p=e.indexRange.to,o=s+1===l,o&&(n=Math.min(l,r),u=Math.max(p,s))),n=Math.min(n,0);let c=yield this.fetch(e.url,{range:{from:n,to:u},measureThroughput:!1,...i});if(!c)return null;let d=new DataView(c,r-n,s-n+1);if(!t.validateData(d))throw new Error("Invalid media file");let h=t.parseInit(d),m=e.indexRange??t.getIndexRange(h);if(!m)throw new ReferenceError("No way to load representation index");let b;if(o)b=new DataView(c,m.from-n,m.to-m.from+1);else{let v=yield this.fetch(e.url,{range:m,measureThroughput:!1});if(!v)return null;b=new DataView(v)}let S=t.parseSegments(b,h,m);return{init:h,dataView:new DataView(c),segments:S}}.bind(this));this.fetchTemplateRepresentation=(0,G.abortable)(this.abortAllController.signal,async function*(e,t){if(e.type!=="template")return null;let i=new URL(e.initUrl,e.baseUrl).toString(),r=yield this.fetch(i,{measureThroughput:!1,...t});return r?{init:null,segments:e.segments.map(n=>({...n,status:"none",size:void 0})),dataView:new DataView(r)}:null}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=r,this.tracer=i.createComponentTracer("Fetcher"),this.useEnableSubtitlesParam=s}onHeadersReceived(e){let{type:t,reused:i}=yn(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}async fetchRepresentation(e,t,i){let{type:r}=e;switch(r){case"byteRange":return await this.fetchByteRangeRepresentation(e,t,i)??null;case"template":return await this.fetchTemplateRepresentation(e,i)??null;default:(0,G.assertNever)(r)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}async doFetch(e,t,i){let r=await lt(e,t);if(r.ok)return i?.type==="manifest"&&this.firstBytesManifest$.next(),r;if(i?.ignoreNetworkErrors)return;let s=await r.text(),n=parseInt(s);if(!isNaN(n))switch(n){case 1:this.recoverableError$.next({id:"VideoDataLinkExpiredError",message:"Video data links have expired",category:G.ErrorCategory.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:G.ErrorCategory.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:G.ErrorCategory.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:G.ErrorCategory.FATAL});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${n})`,category:G.ErrorCategory.FATAL})}}unsubscribeAbortSubscription(e){e&&(e.unsubscribe(),this.subscription.remove(e))}},In=a=>{if(!Dt(a))throw a};var Ht=(a,e,t)=>t*e+(1-t)*a,Dl=(a,e)=>a.reduce((t,i)=>t+i,0)/e,FS=(a,e,t,i)=>{let r=0,s=t,n=Dl(a,e),u=e<i?e:i;for(let o=0;o<u;o++)a[s]>n?r++:r--,s=(a.length+s-1)%a.length;return Math.abs(r)===u};var Ua=require("@vkontakte/videoplayer-shared"),oi=class{constructor(e){this.prevReported=void 0;this.pastMeasures=[];this.takenMeasures=0;this.measuresCursor=0;this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new Ua.ValueSubject(e.initial),this.debounced$=new Ua.ValueSubject(e.initial);let t=e.label??"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new Fe(`raw_${t}`),this.smoothedSeries$=new Fe(`smoothed_${t}`),this.reportedSeries$=new Fe(`reported_${t}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,i=0;for(let u=0;u<this.pastMeasures.length;u++)this.pastMeasures[u]!==void 0&&(t+=(this.pastMeasures[u]-this.smoothed)**2,i++);this.takenMeasures=i,t/=i;let r=Math.sqrt(t),s=this.smoothed+this.params.deviationFactor*r,n=this.smoothed-this.params.deviationFactor*r;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(e),this.updateSmoothedValue(e),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),!(this.smoothed>s||this.smoothed<n)&&((0,Ua.isNullable)(this.prevReported)||Math.abs(this.smoothed-this.prevReported)/this.prevReported>=this.params.changeThreshold)&&(this.prevReported=this.smoothed,this.debounced$.next(this.smoothed),this.reportedSeries$.next(this.smoothed))}};var xn=class extends oi{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=Ht(this.slow,e,this.params.emaAlphaSlow),this.fast=Ht(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var wn=class extends oi{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=Dl(this.pastMeasures,this.takenMeasures);this.emaSmoothed=Ht(this.emaSmoothed,e,this.params.emaAlpha);let i=FS(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=i?this.emaSmoothed:t}};var kn=class extends oi{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?Ht(this.smoothed,t,this.params.emaAlpha):t}};var jt=class{static getSmoothedValue(e,t,i){return i.type==="TwoEma"?new xn({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new wn({initial:e,emaAlpha:i.emaAlpha,basisTrendChangeCount:i.basisTrendChangeCount,changeThreshold:i.changeThreshold,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"})}static getLiveBufferSmoothedValue(e,t){return new kn({initial:e,label:"liveEdgeDelay",...t})}};var Sr=(a,e)=>{a&&a.playbackRate!==e&&(a.playbackRate=e)};var An=require("@vkontakte/videoplayer-shared");var Ha=class a{constructor(e,t){this.currentRepresentation$=new An.ValueSubject(null);this.maxRepresentations=4;this.representationsCursor=0;this.representations=[];this.currentSegment=null;this.getCurrentPosition=t.getCurrentPosition,this.processStreams(e)}updateLive(e){this.processStreams(e?.streams.text)}seekLive(e){this.processStreams(e)}maintain(e=this.getCurrentPosition()){if(!(0,An.isNullable)(e))for(let t of this.representations)for(let i of t){let r=i.segmentReference,s=r.segments.length,n=r.segments[0].time.from,u=r.segments[s-1].time.to;if(e<n||e>u)continue;let o=r.segments.find(l=>l.time.from<=e&&l.time.to>=e);!o||this.currentSegment?.time.from===o.time.from&&this.currentSegment.time.to===o.time.to||(this.currentSegment=o,this.currentRepresentation$.next({...i,label:"Live Text",language:"ru",isAuto:!0,url:new URL(o.url,r.baseUrl).toString()}))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e??[]){let i=a.filterRepresentations(t.representations);if(i){this.representations[this.representationsCursor]=i,this.representationsCursor=(this.representationsCursor+1)%this.maxRepresentations;break}}}static isSupported(e){return!!e?.some(t=>a.filterRepresentations(t.representations))}static filterRepresentations(e){return e?.filter(t=>t.kind==="text"&&"segmentReference"in t&&tt(t.segmentReference))}};var Rn=Q(gt(),1),Cl=Q(Oe(),1),ja=require("@vkontakte/videoplayer-shared");var Pn=a=>{let{webmDecodingInfo:e}=j.video,t="DASH_WEBM",i="DASH_WEBM_AV1";switch(a){case"vp9":return[t,i];case"av1":return[i,t];case"none":return[];case"smooth":return e?e[i].smooth?[i,t]:e[t].smooth?[t,i]:[i,t]:[t,i];case"power_efficient":return e?e[i].powerEfficient?[i,t]:e[t].powerEfficient?[t,i]:[i,t]:[t,i];default:(0,ja.assertNever)(a)}},NS=({webmCodec:a,androidPreferredFormat:e,iosPreferredFormat:t,preferMultiStream:i})=>{let r=[...i?["DASH_STREAMS"]:[],...Pn(a),"DASH_SEP","DASH_ONDEMAND",...i?[]:["DASH_STREAMS"]],s=[...i?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...i?[]:["DASH_STREAMS"]];if(j.device.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[...s,"MPEG",...Pn(a),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...Pn(a),"MPEG",...s,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...Pn(a),...s,"HLS","HLS_ONDEMAND"];default:(0,ja.assertNever)(e)}if(j.video.nativeHlsSupported)switch(t){case"hls":return[...r,"HLS","HLS_FMP4","HLS_ONDEMAND","MPEG"];case"hls_fmp4":return[...r,"HLS_FMP4","HLS","HLS_ONDEMAND","MPEG"];default:(0,ja.assertNever)(t)}return[...r,"HLS","HLS_ONDEMAND","MPEG"]},qS=({androidPreferredFormat:a,preferCMAF:e,preferWebRTC:t})=>{let i=e?["DASH_LIVE_CMAF","DASH_LIVE"]:["DASH_LIVE","DASH_LIVE_CMAF"],r=e?["HLS_LIVE_CMAF","HLS_LIVE"]:["HLS_LIVE","HLS_LIVE_CMAF"],s=[...i,...r],n=[...r,...i],u,o=j.device.isMac&&j.browser.isSafari;if(j.device.isAndroid)switch(a){case"dash":case"dash_any_mpeg":case"dash_any_webm":case"dash_sep":{u=s;break}case"hls":case"mpeg":{u=n;break}default:(0,ja.assertNever)(a)}else j.video.nativeHlsSupported&&!o&&!j.browser.isChromiumBased?u=n:o?u=e?["DASH_LIVE_CMAF","HLS_LIVE_CMAF","HLS_LIVE","DASH_LIVE"]:["HLS_LIVE","DASH_LIVE","DASH_LIVE_CMAF","HLS_LIVE_CMAF"]:u=s;return t?["WEB_RTC_LIVE",...u]:[...u,"WEB_RTC_LIVE"]},Bl=a=>a?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],$n=a=>{if(a.size===0)return;if(a.size===1){let t=a.values().next();return(0,Rn.default)(t.value.split("."),0)}for(let t of a){let i=(0,Rn.default)(t.split("."),0);if(i==="opus"||i==="vp09"||i==="av01")return i}let e=a.values().next();return(0,Rn.default)(e.value.split("."),0)},Ln=a=>{let e=a.map(i=>vr(i)),{codecs:t}=j.video;return ZR().filter(i=>{if((0,Cl.default)(e,i))switch(i){case"av1":return t.av1;case"vp9":return t.vp9;case"avc1":return t.h264;case"hev1":return t.h265;default:return!1}else return!1})},Mn=a=>{let e=a.map(i=>vr(i)),{codecs:t}=j.video;return e$().filter(i=>{if((0,Cl.default)(e,i))switch(i){case"opus":return t.opus;case"mp4a":return t.aac;default:return!1}else return!1})},vr=a=>a.split(".")[0].replace("0",""),ZR=()=>["av1","vp9","hev1","avc1"],e$=()=>["opus","mp4a"];var i$=["timeupdate","progress","play","seeked","stalled","waiting"],r$=["timeupdate","progress","loadeddata","playing","seeked"];var Dn=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.bufferManagers=[];this.subscription=new T.Subscription;this.subscriptionRemovable=new T.SubscriptionRemovable;this.representationSubscription=new T.Subscription;this.state$=new Z("none");this.currentVideoRepresentation$=new T.ValueSubject(void 0);this.currentVideoRepresentationInit$=new T.ValueSubject(void 0);this.currentAudioRepresentation$=new T.ValueSubject(void 0);this.currentVideoSegmentLength$=new T.ValueSubject(0);this.currentAudioSegmentLength$=new T.ValueSubject(0);this.error$=new T.Subject;this.manifestRequested$=new T.Subject;this.firstBytesManifest$=new T.Subject;this.manifestReceived$=new T.Subject;this.firstBytesRequested$=new T.Subject;this.firstBytesReceived$=new T.Subject;this.lastConnectionType$=new T.ValueSubject(void 0);this.lastConnectionReused$=new T.ValueSubject(void 0);this.lastRequestFirstBytes$=new T.ValueSubject(void 0);this.currentLiveTextRepresentation$=new T.ValueSubject(null);this.isLive$=new T.ValueSubject(!1);this.isActiveLive$=new T.ValueSubject(!1);this.isLowLatency$=new T.ValueSubject(!1);this.liveDuration$=new T.ValueSubject(0);this.liveSeekableDuration$=new T.ValueSubject(0);this.liveAvailabilityStartTime$=new T.ValueSubject(0);this.liveStreamStatus$=new T.ValueSubject(void 0);this.bufferLength$=new T.ValueSubject(0);this.liveLatency$=new T.ValueSubject(void 0);this.liveLoadBufferLength$=new T.ValueSubject(0);this.livePositionFromPlayer$=new T.ValueSubject(0);this.currentStallDuration$=new T.ValueSubject(0);this.videoLastDataObtainedTimestamp$=new T.ValueSubject(0);this.fetcherRecoverableError$=new T.Subject;this.fetcherError$=new T.Subject;this.liveStreamEndTimestamp=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.forceEnded$=new T.Subject;this.gapWatchdogActive=!1;this.liveWasInterrupted=!1;this.destroyController=new ue;this.initManifest=(0,T.abortable)(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=ye(t,i,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),this.manifest?.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:T.ErrorCategory.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=(0,T.abortable)(this.destroyController.signal,async function*(){this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(o=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:T.ErrorCategory.NETWORK,message:"Failed to load manifest",thrown:o})});if(!e)return null;let t=null;try{t=gn(e??"",this.manifestUrlString)}catch(o){let l=mn(e)??{id:"ManifestParsing",category:T.ErrorCategory.PARSER,message:"Failed to parse MPD manifest",thrown:o};this.error$.next(l)}if(!t)return null;let i=(o,l,p)=>!!(this.element?.canPlayType?.(l)&&Ze()?.isTypeSupported?.(`${l}; codecs="${p}"`)||o==="text");if(t.live){this.isLive$.next(!0);let{availabilityStartTime:o,latestSegmentPublishTime:l,streamIsUnpublished:p,streamIsAlive:c}=t.live,d=(t.duration??0)/1e3;this.liveSeekableDuration$.next(-1*d),this.liveDuration$.next((l-o)/1e3),this.liveAvailabilityStartTime$.next(t.live.availabilityStartTime);let h="active";if(c||(h=p?"unpublished":"unexpectedly_down"),this.liveStreamStatus$.next(h),c&&this.liveWasInterrupted){this.liveWasInterrupted=!1,this.stopStallWatchdogSubscription();let m=this.normalizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);this.seekLive(m).catch(b=>{this.error$.next({id:"updateManifest",category:T.ErrorCategory.VIDEO_PIPELINE,message:"seekLive after stream restore failed",thrown:b})})}}let r={text:t.streams.text,video:[],audio:[]},s,n;for(let o of["video","audio"]){let p=t.streams[o].filter(({mime:d,codecs:h})=>i(o,d,h));r[o]=p;let c;if(this.tuning.dash.codecsPrioritizeEnabled){let d=p.map(({codecs:h})=>h);o==="audio"&&(n=Mn(d),c=n[0]),o==="video"&&(s=Ln(d),this.forceVideoCodec&&(0,HS.default)(s,this.forceVideoCodec)?c=this.forceVideoCodec:c=s[0]),c&&(r[o]=p.filter(({codecs:h})=>vr(h)===c))}else{let d=new Set(p.map(({codecs:h})=>h));c=$n(d),c&&(r[o]=p.filter(({codecs:h})=>h.startsWith(c)))}if(o==="video"){let d=this.tuning.preferHDR,h=r.video.some(b=>b.hdr),m=r.video.some(b=>!b.hdr);j.display.isHDR&&d&&h?r.video=r.video.filter(b=>b.hdr):m&&(r.video=r.video.filter(b=>!b.hdr))}}let u={...t,streams:r};return this.tuning.dash.codecsPrioritizeEnabled&&(u.codecs={video:s,audio:n}),this.tracer.log("updateManifestEnd",(0,T.flattenObject)(u)),u}.bind(this));this.initRepresentations=(0,T.abortable)(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initRepresentationsStart",(0,T.flattenObject)({initialVideo:e,initialAudio:t,sourceHls:i})),(0,T.assertNonNullable)(this.manifest),(0,T.assertNonNullable)(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let r=c=>{this.representationSubscription.add((0,T.fromEvent)(c,"error").pipe((0,T.filter)(d=>!!this.element?.played.length)).subscribe(d=>{this.error$.next({id:"VideoSource",category:T.ErrorCategory.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:d})}))};this.source=Js();let s=document.createElement("source");if(r(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),sr())if(i){let c=document.createElement("source");r(c),c.type="application/x-mpegurl",c.src=i.url,this.element.appendChild(c)}else this.element.disableRemotePlayback=!0;this.isActiveLive$.next(this.isLive$.getValue());let n={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),manifest:this.manifest},u=this.manifest.streams.video.reduce((c,d)=>[...c,...d.representations],[]);if(this.videoBufferManager=new qa("video",this.source,u,n),this.bufferManagers=[this.videoBufferManager],(0,T.isNonNullable)(t)){let c=this.manifest.streams.audio.reduce((d,h)=>[...d,...h.representations],[]);this.audioBufferManager=new qa("audio",this.source,c,n),this.bufferManagers.push(this.audioBufferManager)}if(Ha.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new Ha(this.manifest.streams.text,n)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$)),this.representationSubscription.add((0,T.merge)(...r$.map(c=>(0,T.fromEvent)(this.element,c))).pipe((0,T.map)(c=>this.element?De(this.element.buffered,this.element.currentTime*1e3):0),(0,T.filterChanged)(),(0,T.tap)(c=>{c>this.tuning.dash.bufferEmptinessTolerance&&this.stopStallWatchdogSubscription()})).subscribe(this.bufferLength$)),this.representationSubscription.add((0,T.merge)((0,T.fromEvent)(this.element,"ended"),this.forceEnded$).subscribe(()=>{this.stopStallWatchdogSubscription()})),this.isLive$.getValue()){this.subscription.add(this.liveDuration$.pipe((0,T.filterChanged)()).subscribe(d=>this.liveStreamEndTimestamp=(0,T.now)())),this.subscription.add((0,T.fromEvent)(this.element,"pause").subscribe(()=>{let{liveUpdateInterval:d}=this.tuning.dash;this.livePauseWatchdogSubscription=(0,T.interval)(d).subscribe(h=>{let m=ei(this.manifestUrlString,2);this.manifestUrlString=ye(this.manifestUrlString,m+d,2),this.liveStreamStatus$.getValue()==="active"&&this.updateManifest()}),this.subscription.add(this.livePauseWatchdogSubscription)})).add((0,T.fromEvent)(this.element,"play").subscribe(d=>this.livePauseWatchdogSubscription?.unsubscribe())),this.representationSubscription.add((0,T.combine)({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe((0,T.map)(({isActiveLive:d,isLowLatency:h})=>d&&h),(0,T.filterChanged)()).subscribe(d=>{this.isManualDecreasePlaybackInLive()||Sr(this.element,1)})),this.representationSubscription.add((0,T.combine)({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe((0,T.filter)(({bufferLength:d,isActiveLive:h,isLowLatency:m})=>h&&m&&!!d)).subscribe(({bufferLength:d})=>this.liveBuffer.next(d))),this.representationSubscription.add(this.videoBufferManager.currentLowLatencySegmentLength$.subscribe(d=>{if(!this.isActiveLive$.getValue()&&!this.isLowLatency$.getValue()&&!d)return;let h=this.liveSeekableDuration$.getValue()-d/1e3;this.liveSeekableDuration$.next(Math.max(h,-1*this.tuning.dashCmafLive.maxLiveDuration)),this.liveDuration$.next(this.liveDuration$.getValue()+d/1e3)})),this.representationSubscription.add((0,T.combine)({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe((0,T.filter)(({isLive:d})=>d),(0,T.filterChanged)((d,h)=>h.bufferLength<d.bufferLength),(0,T.map)(({rtt:d,bufferLength:h,segmentServerLatency:m})=>{let b=ei(this.manifestUrlString,2);return(d/2+h+m+b)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add((0,T.combine)({liveBuffer:this.liveBuffer.smoothed$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).subscribe(({liveBuffer:d,isActiveLive:h,isLowLatency:m})=>{if(!m||!h)return;let b=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,S=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,v=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,I=d-b;if(this.isManualDecreasePlaybackInLive())return;let A=1;Math.abs(I)>S&&(A=1+Math.sign(I)*v),Sr(this.element,A)})),this.representationSubscription.add(this.bufferLength$.subscribe(d=>{let h=0;if(d){let m=(this.element?.currentTime??0)*1e3;h=Math.min(...this.bufferManagers.map(S=>S.getLiveSegmentsToLoadState(this.manifest)?.to??m))-m}this.liveLoadBufferLength$.getValue()!==h&&this.liveLoadBufferLength$.next(h)}));let c=0;this.representationSubscription.add((0,T.combine)({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe((0,T.throttle)(this.tuning.dash.liveUpdateInterval)).subscribe(async({liveLoadBufferLength:d,bufferLength:h})=>{if(!this.element||this.isUpdatingLive)return;let m=this.element.playbackRate,b=ei(this.manifestUrlString,2),S=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,v=Math.min(S,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*m),I=this.tuning.dashCmafLive.normalizedActualBufferOffset*m,A=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*m,x=isFinite(d)?d:h,C=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),V=S<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next(V);let O="none";if(C?O="active_low_latency":this.isLowLatency$.getValue()&&V?(this.bufferManagers.forEach(D=>D.proceedLowLatencyLive()),O="active_low_latency"):b!==0&&x<v?O="live_forward_buffering":x<v+A&&(O="live_with_target_offset"),isFinite(d)&&(c=d>c?d:c),O==="live_forward_buffering"||O==="live_with_target_offset"){let D=c-(v+I),N=this.normalizeLiveOffset(Math.trunc(b+D/m)),L=Math.abs(N-b),ee=0;!d||L<=this.tuning.dashCmafLive.offsetCalculationError?ee=b:N>0&&L>this.tuning.dashCmafLive.offsetCalculationError&&(ee=N),this.manifestUrlString=ye(this.manifestUrlString,ee,2)}(O==="live_with_target_offset"||O==="live_forward_buffering")&&(c=0,await this.updateLive())},d=>{this.error$.next({id:"updateLive",category:T.ErrorCategory.VIDEO_PIPELINE,thrown:d,message:"Failed to update live with subscription"})}))}let o=(0,T.merge)(...this.bufferManagers.map(c=>c.fullyBuffered$)).pipe((0,T.map)(()=>this.bufferManagers.every(c=>c.fullyBuffered$.getValue()))),l=(0,T.merge)(...this.bufferManagers.map(c=>c.onLastSegment$)).pipe((0,T.map)(()=>this.bufferManagers.some(c=>c.onLastSegment$.getValue()))),p=(0,T.combine)({allBuffersFull:o,someBufferEnded:l}).pipe((0,T.filterChanged)(),(0,T.map)(({allBuffersFull:c,someBufferEnded:d})=>c&&d),(0,T.filter)(c=>c));if(this.representationSubscription.add((0,T.merge)(this.forceEnded$,p).subscribe(()=>{if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(c=>!c.updating))try{this.source?.endOfStream()}catch(c){this.error$.next({id:"EndOfStream",category:T.ErrorCategory.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:c})}})),this.representationSubscription.add((0,T.merge)(...this.bufferManagers.map(c=>c.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.representationSubscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&(this.representationSubscription.add(this.audioBufferManager.playingRepresentation$.subscribe(this.currentAudioRepresentation$)),this.representationSubscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$))),this.liveTextManager&&this.representationSubscription.add(this.liveTextManager.currentRepresentation$.subscribe(this.currentLiveTextRepresentation$)),this.source.readyState!=="open"){let c=this.tuning.dash.sourceOpenTimeout>=0;yield new Promise(d=>{c&&(this.timeoutSourceOpenId=setTimeout(()=>{if(this.source?.readyState==="open"){d();return}this.error$.next({id:"OpenOfStream",category:T.ErrorCategory.VIDEO_PIPELINE,message:"Failed to open MediaSource",thrown:new Error("Timeout reject when wait sourceopen event"),traceAsLog:!0})},this.tuning.dash.sourceOpenTimeout)),this.source?.addEventListener("sourceopen",()=>{this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),d()},{once:!0})})}if(!this.isLive$.getValue()){let c=[this.manifest.duration??0,...(0,Vl.default)((0,Vl.default)([...this.manifest.streams.audio,...this.manifest.streams.video],d=>d.representations),d=>{let h=[];return d.duration&&h.push(d.duration),tt(d.segmentReference)&&d.segmentReference.totalSegmentsDurationMs&&h.push(d.segmentReference.totalSegmentsDurationMs),h})];this.source.duration=Math.max(...c)/1e3}this.audioBufferManager&&(0,T.isNonNullable)(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState("representations_ready"),this.tracer.log("initRepresentationsEnd")}.bind(this));this.tick=()=>{if(!this.element||!this.videoBufferManager||this.source?.readyState!=="open")return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),this.audioBufferManager?.maintain(e),this.liveTextManager?.maintain(e),(this.videoBufferManager.gaps.length||this.audioBufferManager?.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=(0,T.interval)(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),t=>{this.error$.next({id:"GapWatchdog",category:T.ErrorCategory.WTF,message:"Error handling gaps",thrown:t})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name),this.forceVideoCodec=e.forceVideoCodec,this.fetcher=new En({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer,useEnableSubtitlesParam:e.tuning.useEnableSubtitlesParam}),this.subscription.add(this.fetcher.recoverableError$.subscribe(this.fetcherRecoverableError$)),this.subscription.add(this.fetcher.error$.subscribe(this.fetcherError$)),this.subscription.add(this.fetcher.manifestRequested$.subscribe(this.manifestRequested$)),this.subscription.add(this.fetcher.firstBytesManifest$.subscribe(this.firstBytesManifest$)),this.subscription.add(this.fetcher.manifestReceived$.subscribe(this.manifestReceived$)),this.subscription.add(this.fetcher.firstBytesRequested$.subscribe(this.firstBytesRequested$)),this.subscription.add(this.fetcher.firstBytesReceived$.subscribe(this.firstBytesReceived$)),this.subscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.subscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.liveBuffer=jt.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.bufferEstimator}),this.initTracerSubscription()}setSmartRepresentationSwitch(e){this.bufferManagers.forEach(t=>t.setSmartRepresentationSwitch(e))}async seekLive(e){(0,T.assertNonNullable)(this.element),this.updateManifestUrlWithTimeOffset(e),this.manifest=await this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,await this.updateLiveBuffersFromManifest(this.manifest))}updateManifestUrlWithTimeOffset(e){let t=this.liveStreamStatus$.getValue()!=="active"?(0,T.now)()-this.liveStreamEndTimestamp:0,i=this.normalizeLiveOffset(e+t);this.isActiveLive$.next(i===0),this.manifestUrlString=ye(this.manifestUrlString,i,2)}async updateLiveBuffersFromManifest(e){await this.videoBufferManager?.seekLive(e.streams.video),await this.audioBufferManager?.seekLive(e.streams.audio),this.liveTextManager?.seekLive(e.streams.text)}stopStallWatchdogSubscription(){this.stallWatchdogSubscription?.unsubscribe(),this.currentStallDuration$.next(0)}initBuffer(){(0,T.assertNonNullable)(this.element),this.state$.setState("running"),this.subscription.add((0,T.merge)(...i$.map(e=>(0,T.fromEvent)(this.element,e)),(0,T.fromEvent)(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:T.ErrorCategory.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add((0,T.fromEvent)(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add((0,T.fromEvent)(this.element,"waiting").subscribe(()=>{this.tuning.dash.useVideoElementWaitingCurrentTimeReassign&&this.element&&this.element.readyState===2&&!this.element.seeking&&Ce(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{let{keepSilentStallWatchdogWhenNotActive:t}=this.tuning.dashCmafLive,{crashOnStallTimeout:i,crashOnStallTWithoutDataTimeout:r,liveStallReinitInterval:s,stallWatchdogInterval:n}=this.tuning.dash,u=this.isLive$.getValue(),l=this.liveStreamStatus$.getValue()==="active";if(!this.element||this.source?.readyState!=="open")return;let p=this.currentStallDuration$.getValue();p+=n,this.currentStallDuration$.next(p);let c={timeInWaiting:p},d=(0,T.now)(),h=100,m=this.videoBufferManager?.lastDataObtainedTimestamp??0;this.videoLastDataObtainedTimestamp$.next(m);let b=this.audioBufferManager?.lastDataObtainedTimestamp??0,S=this.videoBufferManager?.getForwardBufferDuration()??0,v=this.audioBufferManager?.getForwardBufferDuration()??0,I=S<h&&d-m>r,A=this.audioBufferManager&&v<h&&d-b>r;if((!t||l)&&((I||A)&&p>r||p>=i))throw new Error(`Stall timeout exceeded: ${p} ms`);if(u&&p%s===0){let x=this.normalizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);!l&&t?(this.liveWasInterrupted=!0,this.updateManifestUrlWithTimeOffset(x),this.updateManifest()):this.seekLive(x).catch(C=>{this.error$.next({id:"stallIntervalCallback",category:T.ErrorCategory.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:C})}),c.liveLastOffset=x}else{let x=this.element.currentTime*1e3;this.videoBufferManager?.maintain(x),this.audioBufferManager?.maintain(x),c.position=x}this.tracer.log("stallIntervalCallback",(0,T.flattenObject)(c))};this.stallWatchdogSubscription&&(this.stallWatchdogSubscription.unsubscribe(),this.subscriptionRemovable.remove(this.stallWatchdogSubscription)),this.stallWatchdogSubscription=(0,T.interval)(this.tuning.dash.stallWatchdogInterval).subscribe(e,t=>{this.error$.next({id:"StallWatchdogCallback",category:T.ErrorCategory.NETWORK,message:"Can't restore DASH after stall.",thrown:t})}),this.subscriptionRemovable.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t,i=!1){let r={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return this.tuning.useNewSwitchTo?this.currentStallDuration$.getValue()>0?r?.switchToWithPreviousAbort(t,i):r?.switchTo(t,i):r?.switchToOld(t,i)}async seek(e,t){(0,T.assertNonNullable)(this.element),(0,T.assertNonNullable)(this.videoBufferManager);let i;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?i=e:i=Math.max(this.videoBufferManager.findSegmentStartTime(e)??e,this.audioBufferManager?.findSegmentStartTime(e)??e),this.warmUpMediaSourceIfNeeded(i),Ce(this.element.buffered,i)||await Promise.all([this.videoBufferManager.abort(),this.audioBufferManager?.abort()]),!((0,T.isNullable)(this.element)||(0,T.isNullable)(this.videoBufferManager))&&(this.videoBufferManager.maintain(i),this.audioBufferManager?.maintain(i),this.element.currentTime=i/1e3,this.tracer.log("seek",(0,T.flattenObject)({requestedPosition:e,forcePrecise:t,position:i})))}warmUpMediaSourceIfNeeded(e=this.element?.currentTime){(0,T.isNonNullable)(this.element)&&(0,T.isNonNullable)(this.source)&&(0,T.isNonNullable)(e)&&this.source?.readyState==="ended"&&this.element.duration*1e3-e>this.tuning.dash.seekBiasInTheEnd&&this.bufferManagers.forEach(t=>t.warmUpMediaSource())}get isStreamEnded(){return this.source?.readyState==="ended"}stop(){this.tracer.log("stop"),this.element?.querySelectorAll("source").forEach(e=>{URL.revokeObjectURL(e.src),e.remove()}),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),this.videoBufferManager?.destroy(),this.videoBufferManager=null,this.audioBufferManager?.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getStreams(){return this.manifest?.streams}getCodecs(){return this.manifest?.codecs}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){this.subscription.unsubscribe(),this.subscriptionRemovable.unsubscribe(),this.representationSubscription.unsubscribe(),this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),this.source?.readyState==="open"&&Array.from(this.source.sourceBuffers).every(e=>!e.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}initTracerSubscription(){let e=(0,T.getTraceSubscriptionMethod)(this.tracer.error.bind(this.tracer));this.subscription.add(this.error$.subscribe(e("error")))}isManualDecreasePlaybackInLive(){if(!this.element||!this.isLive$.getValue())return!1;let e=1-this.element.playbackRate;return Number(e.toFixed(2))>Number(this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup.toFixed(2))}normalizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}async updateLive(){this.isUpdatingLive=!0,this.manifest=await this.updateManifest(),this.manifest&&(this.bufferManagers.forEach(e=>e.updateLive(this.manifest)),this.liveTextManager?.updateLive(this.manifest)),this.isUpdatingLive=!1}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.getDebugBufferState();if(!e)return;let t=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),i={isJumpGapAfterSeekLive:this.isJumpGapAfterSeekLive,isActiveLowLatency:t,initialCurrentTime:this.element.currentTime},{usePersistentGaps:r}=this.tuning.dash;this.isJumpGapAfterSeekLive&&!t&&this.element.currentTime>e.to&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let s=this.element.currentTime*1e3,n=[],u=this.element.readyState===1?this.tuning.endGapTolerance:0;for(let o of this.bufferManagers)for(let l of o.gaps)(r&&l.persistent||o.playingRepresentation$.getValue()===l.representation)&&l.from-u<=s&&l.to+u>s&&(this.element.duration*1e3-l.to<this.tuning.endGapTolerance?n.push(1/0):n.push(l.to));if(n.length){let o=Math.max(...n)+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,o===1/0?this.forceEnded$.next():(this.element.currentTime=o/1e3,i={...i,gapEnds:n,jumpTo:o,resultCurrentTime:this.element.currentTime},this.tracer.log("jumpGap",(0,T.flattenObject)(i)))}}calculateDurationFromSegments(){return Math.max(this.videoBufferManager?.calculateDurationFromSegments()||0,this.audioBufferManager?.calculateDurationFromSegments()||0)}};var Cn=class{constructor(e,t){this.fov=e,this.orientation=t}};var Bn=class{constructor(e,t){this.rotating=!1;this.fading=!1;this.lastTickTS=0;this.lastCameraTurnTS=0;this.fadeStartSpeed=null;this.fadeTime=0;this.camera=e,this.options=t,this.rotationSpeed={x:0,y:0,z:0},this.fadeCorrection=1/(this.options.speedFadeTime/1e3)**2}turnCamera(e=0,t=0,i=0){this.pointCameraTo(this.camera.orientation.x+e,this.camera.orientation.y+t,this.camera.orientation.z+i)}pointCameraTo(e=0,t=0,i=0){t=this.limitCameraRotationY(t);let r=e-this.camera.orientation.x,s=t-this.camera.orientation.y,n=i-this.camera.orientation.z;this.camera.orientation.x=e,this.camera.orientation.y=t,this.camera.orientation.z=i,this.lastCameraTurn={x:r,y:s,z:n},this.lastCameraTurnTS=Date.now()}setRotationSpeed(e,t,i){this.rotationSpeed.x=e??this.rotationSpeed.x,this.rotationSpeed.y=t??this.rotationSpeed.y,this.rotationSpeed.z=i??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,i){this.setRotationSpeed(e,t,i),this.fadeStartSpeed={...this.rotationSpeed},this.fading=!0}stopFading(){this.fadeStartSpeed=null,this.fading=!0,this.fadeTime=0}limitCameraRotationY(e){return Math.max(-this.options.maxYawAngle,Math.min(e,this.options.maxYawAngle))}tick(e){if(!this.lastTickTS){this.lastTickTS=e,this.lastCameraTurnTS=Date.now();return}let t=e-this.lastTickTS,i=t/1e3;if(this.rotating)this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*i,this.rotationSpeed.y*this.options.rotationSpeedCorrection*i,this.rotationSpeed.z*this.options.rotationSpeedCorrection*i);else if(this.fading&&this.fadeStartSpeed){let r=-this.fadeCorrection*(this.fadeTime/1e3)**2+1;this.setRotationSpeed(this.fadeStartSpeed.x*r,this.fadeStartSpeed.y*r,this.fadeStartSpeed.z*r),r>0?this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*i,this.rotationSpeed.y*this.options.rotationSpeedCorrection*i,this.rotationSpeed.z*this.options.rotationSpeedCorrection*i):(this.stopRotation(!0),this.stopFading()),this.fadeTime=Math.min(this.fadeTime+t,this.options.speedFadeTime)}this.lastTickTS=e}};var jS=`attribute vec2 a_vertex;
124
+ `})|(?<privateuse2>${e}))$`.replace(/[\s\t\n]/g,"");return new RegExp(p,"i")}var $S=a=>{if(!a?.startsWith("P"))return;let e=(n,u)=>{let o=n?parseFloat(n.replace(",",".")):NaN;return(isNaN(o)?0:o)*u},i=/^(-|\+)?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),r=i?.[1]==="-"?-1:1,s={days:e(i?.[5],r),hours:e(i?.[6],r),minutes:e(i?.[7],r),seconds:e(i?.[8],r)};return s.days*24*60*60*1e3+s.hours*60*60*1e3+s.minutes*60*1e3+s.seconds*1e3},vt=(a,e)=>{let t=a;t=(0,Al.default)(t,"$$","$");let i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[r,s]of(0,LS.default)(i)){let n=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=(0,Al.default)(t,n,(u,o)=>(0,Fa.isNullable)(s)?u:(0,Fa.isNullable)(o)?s:(0,MS.default)(s,parseInt(o,10),"0"))}return t},gn=(a,e)=>{let i=new DOMParser().parseFromString(a,"application/xml"),r={video:[],audio:[],text:[]},s=i.children[0],n=Array.from(s.querySelectorAll("MPD > BaseURL").values()).map(N=>N.textContent?.trim()??""),u=(0,DS.default)(n,0)??"",o=s.getAttribute("type")==="dynamic",l=s.getAttribute("availabilityStartTime"),p=s.getAttribute("publishTime"),c=s.getElementsByTagName("vk:Attrs")[0],d=c?.getElementsByTagName("vk:XLatestSegmentPublishTime")[0].textContent,h=c?.getElementsByTagName("vk:XStreamIsLive")[0].textContent,m=c?.getElementsByTagName("vk:XStreamIsUnpublished")[0].textContent,b=c?.getElementsByTagName("vk:XPlaybackDuration")[0].textContent,S;o&&(S={availabilityStartTime:l?new Date(l).getTime():0,publishTime:p?new Date(p).getTime():0,latestSegmentPublishTime:d?new Date(d).getTime():0,streamIsAlive:h==="yes",streamIsUnpublished:m==="yes"});let v,I=s.getAttribute("mediaPresentationDuration"),P=[...s.getElementsByTagName("Period")],x=P.reduce((N,L)=>({...N,[L.id]:L.children}),{}),C=P.reduce((N,L)=>({...N,[L.id]:L.getAttribute("duration")}),{});I?v=$S(I):(0,Pl.default)(C).filter(N=>N).length&&!o?v=(0,Pl.default)(C).reduce((N,L)=>N+($S(L)??0),0):b&&(v=parseInt(b,10));let V=0,O=s.getAttribute("profiles")?.split(",")??[];for(let N of P.map(L=>L.id))for(let L of x[N]){let ee=L.getAttribute("id")??"id"+(V++).toString(10),W=L.getAttribute("mimeType")??"",R=L.getAttribute("codecs")??"",k=L.getAttribute("contentType")??W?.split("/")[0],te=L.getAttribute("profiles")?.split(",")??[],_=RS(L.getAttribute("lang")??"")??{},ae=L.querySelector("Label")?.textContent?.trim()??void 0,le=L.querySelectorAll("Representation"),ge=L.querySelector("SegmentTemplate"),Ee=L.querySelector("Role")?.getAttribute("value")??void 0,ke=k,Re={id:ee,language:_.language,isDefault:Ee==="main",label:ae,codecs:R,hdr:ke==="video"&&wl(R),mime:W,representations:[]};for(let se of le){let ie=se.getAttribute("lang")??void 0,$e=ae??L.getAttribute("label")??se.getAttribute("label")??void 0,Be=se.querySelector("BaseURL")?.textContent?.trim()??"",xe=new URL(Be||u,e).toString(),at=se.getAttribute("mimeType")??W,Gt=se.getAttribute("codecs")??R??"",yt;if(k==="text"){let Ye=se.getAttribute("id")||"",zt=_.privateuse?.includes("x-auto")||Ye.includes("_auto"),Tt=se.querySelector("SegmentTemplate");if(Tt){let xr={representationId:se.getAttribute("id")??void 0,bandwidth:se.getAttribute("bandwidth")??void 0},ss=parseInt(se.getAttribute("bandwidth")??"",10)/1e3,ns=parseInt(Tt.getAttribute("startNumber")??"",10)??1,Bi=parseInt(Tt.getAttribute("timescale")??"",10),to=Tt.querySelectorAll("SegmentTimeline S")??[],Vi=Tt.getAttribute("media");if(!Vi)continue;let os=[],us=0,ls="",_i=0,wr=ns,Ve=0;for(let dt of to){let ci=parseInt(dt.getAttribute("d")??"",10),st=parseInt(dt.getAttribute("r")??"",10)||0,Yt=parseInt(dt.getAttribute("t")??"",10);Ve=Number.isFinite(Yt)?Yt:Ve;let di=ci/Bi*1e3,Oi=Ve/Bi*1e3;for(let It=0;It<st+1;It++){let Kt=vt(Vi,{...xr,segmentNumber:wr.toString(10),segmentTime:(Ve+It*ci).toString(10)}),Fi=(Oi??0)+It*di,Pr=Fi+di;wr++,os.push({time:{from:Fi,to:Pr},url:Kt})}Ve+=(st+1)*ci,us+=(st+1)*di}_i=Ve/Bi*1e3,ls=vt(Vi,{...xr,segmentNumber:wr.toString(10),segmentTime:Ve.toString(10)});let Ar={time:{from:_i,to:1/0},url:ls},Bt={type:"template",baseUrl:xe,segmentTemplateUrl:Vi,initUrl:"",totalSegmentsDurationMs:us,segments:os,nextSegmentBeyondManifest:Ar,timescale:Bi};yt={id:Ye,kind:"text",segmentReference:Bt,profiles:[],duration:v,bitrate:ss,mime:"",codecs:"",width:0,height:0,isAuto:zt}}else yt={id:Ye,isAuto:zt,kind:"text",url:xe}}else{let Ye=se.getAttribute("contentType")??at?.split("/")[0]??k,zt=L.getAttribute("profiles")?.split(",")??[],Tt=parseInt(se.getAttribute("width")??"",10),xr=parseInt(se.getAttribute("height")??"",10),ss=parseInt(se.getAttribute("bandwidth")??"",10)/1e3,ns=se.getAttribute("frameRate")??"",Bi=se.getAttribute("quality")??void 0,to=ns?kS(ns):void 0,Vi=se.getAttribute("id")??"id"+(V++).toString(10),os=Ye==="video"?`${xr}p`:Ye==="audio"?`${ss}Kbps`:Gt,us=`${Vi}@${os}`,ls=[...O,...te,...zt],_i,wr=se.querySelector("SegmentBase"),Ve=se.querySelector("SegmentTemplate")??ge;if(wr){let Bt=se.querySelector("SegmentBase Initialization")?.getAttribute("range")??"",[dt,ci]=Bt.split("-").map(Kt=>parseInt(Kt,10)),st={from:dt,to:ci},Yt=se.querySelector("SegmentBase")?.getAttribute("indexRange"),[di,Oi]=Yt?Yt.split("-").map(Kt=>parseInt(Kt,10)):[],It=Yt?{from:di,to:Oi}:void 0;_i={type:"byteRange",url:xe,initRange:st,indexRange:It}}else if(Ve){let Bt={representationId:se.getAttribute("id")??void 0,bandwidth:se.getAttribute("bandwidth")??void 0},dt=parseInt(Ve.getAttribute("timescale")??"",10),ci=Ve.getAttribute("initialization")??"",st=Ve.getAttribute("media"),Yt=parseInt(Ve.getAttribute("startNumber")??"",10)??1,di=vt(ci,Bt);if(!st)throw new ReferenceError("No media attribute in SegmentTemplate");let Oi=Ve.querySelectorAll("SegmentTimeline S")??[],It=[],Kt=0,Fi="",Pr=0;if(Oi.length){let cs=Yt,pt=0;for(let Ni of Oi){let Et=parseInt(Ni.getAttribute("d")??"",10),pi=parseInt(Ni.getAttribute("r")??"",10)||0,ds=parseInt(Ni.getAttribute("t")??"",10);pt=Number.isFinite(ds)?ds:pt;let io=Et/dt*1e3,Av=pt/dt*1e3;for(let ps=0;ps<pi+1;ps++){let Pv=vt(st,{...Bt,segmentNumber:cs.toString(10),segmentTime:(pt+ps*Et).toString(10)}),tc=(Av??0)+ps*io,kv=tc+io;cs++,It.push({time:{from:tc,to:kv},url:Pv})}pt+=(pi+1)*Et,Kt+=(pi+1)*io}Pr=pt/dt*1e3,Fi=vt(st,{...Bt,segmentNumber:cs.toString(10),segmentTime:pt.toString(10)})}else if((0,Fa.isNonNullable)(v)){let pt=parseInt(Ve.getAttribute("duration")??"",10)/dt*1e3,Ni=Math.ceil(v/pt),Et=0;for(let pi=1;pi<Ni;pi++){let ds=vt(st,{...Bt,segmentNumber:pi.toString(10),segmentTime:Et.toString(10)});It.push({time:{from:Et,to:Et+pt},url:ds}),Et+=pt}Pr=Et,Fi=vt(st,{...Bt,segmentNumber:Ni.toString(10),segmentTime:Et.toString(10)})}let wv={time:{from:Pr,to:1/0},url:Fi};_i={type:"template",baseUrl:xe,segmentTemplateUrl:st,initUrl:di,totalSegmentsDurationMs:Kt,segments:It,nextSegmentBeyondManifest:wv,timescale:dt}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!Ye||!at)continue;let Ar={video:"video",audio:"audio",text:"text"}[Ye];if(!Ar)continue;ke||=Ar,yt={id:us,kind:Ar,segmentReference:_i,profiles:ls,duration:v,bitrate:ss,mime:at,codecs:Gt,width:Tt,height:xr,fps:to,quality:Bi}}Re.language||=ie,Re.label||=$e,Re.mime||=at,Re.codecs||=Gt,Re.hdr||=ke==="video"&&wl(Gt),Re.representations.push(yt)}if(ke){let se=r[ke].find(ie=>ie.id===Re.id);if(se&&Re.representations.every(ie=>ie.segmentReference.type==="template"))for(let ie of se.representations){let $e=Re.representations.find(at=>at.id===ie.id);if(!$e)continue;let Be=$e.segmentReference,xe=ie.segmentReference;xe.segments.push(...Be.segments),xe.nextSegmentBeyondManifest=Be.nextSegmentBeyondManifest}else r[ke].push(Re)}}return{duration:v,streams:r,baseUrls:n,live:S}};var kl=Q(gt(),1);var CS=require("@vkontakte/videoplayer-shared"),Na=({id:a,width:e,height:t,bitrate:i,fps:r,quality:s,streamId:n})=>{let u=(s?ii(s):void 0)??(0,CS.videoSizeToQuality)({width:e,height:t});return u&&{id:a,quality:u,bitrate:i,size:{width:e,height:t},fps:r,streamId:n}},BS=({id:a,bitrate:e})=>({id:a,bitrate:e}),VS=({language:a,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:a,label:e}),_S=({language:a,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:a,label:e}),Rl=({id:a,language:e,label:t,codecs:i,isDefault:r})=>({id:a,language:e,label:t,codec:(0,kl.default)(i.split("."),0),isDefault:r}),$l=({id:a,language:e,label:t,hdr:i,codecs:r})=>({id:a,language:e,hdr:i,label:t,codec:(0,kl.default)(r.split("."),0)}),Ll=a=>"url"in a,tt=a=>a.type==="template";var Ml=require("@vkontakte/videoplayer-shared"),X=(a,e)=>(0,Ml.isNonNullable)(a)&&(0,Ml.isNonNullable)(e)&&a.readyState==="open"&&YR(a,e);function YR(a,e){for(let t=0;t<a.activeSourceBuffers.length;++t)if(a.activeSourceBuffers[t]===e)return!0;return!1}var qa=class{constructor(e,t,i,{fetcher:r,tuning:s,getCurrentPosition:n,isActiveLowLatency:u,compatibilityMode:o=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new w.ValueSubject(0);this.currentLowLatencySegmentLength$=new w.ValueSubject(0);this.currentSegmentLength$=new w.ValueSubject(0);this.onLastSegment$=new w.ValueSubject(!1);this.fullyBuffered$=new w.ValueSubject(!1);this.playingRepresentation$=new w.ValueSubject(void 0);this.playingRepresentationInit$=new w.ValueSubject(void 0);this.error$=new w.Subject;this.gaps=[];this.subscription=new w.Subscription;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new ue;this.switchAbortController=new ue;this.destroyAbortController=new ue;this.useSmartRepresentationSwitch=!1;this.bufferLimit=1/0;this.failedDownloads=0;this.baseUrls=[];this.baseUrlsIndex=0;this.isLive=!1;this.liveUpdateSegmentIndex=0;this.liveInitialAdditionalOffset=0;this.isSeekingLive=!1;this.index=0;this.lastDataObtainedTimestampMs=0;this.loadByteRangeSegmentsTimeoutId=0;this.startWith=(0,w.abortable)(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);(0,w.assertNonNullable)(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new Mg(this.sourceBuffer),this.subscription.add((0,w.fromEvent)(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let u,o=this.mediaSource.readyState;o!=="open"&&(u={id:`SegmentEjection_source_${o}`,category:w.ErrorCategory.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),u??={id:"SegmentEjection",category:w.ErrorCategory.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n},this.error$.next(u)})),this.subscription.add((0,w.fromEvent)(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:w.ErrorCategory.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let u=this.getCurrentPosition();if(!this.sourceBuffer||!u||!X(this.mediaSource,this.sourceBuffer))return;let o=Math.min(this.bufferLimit,hr(this.sourceBuffer.buffered)*.8);this.bufferLimit=o;let l=this.getForwardBufferDuration(u),p=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(u,n*2,l<p).catch(c=>{this.handleAsyncError(c,"pruneBuffer")})})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(n=>this.error$.next(n))),yield this.loadInit(t,"high",!0);let i=this.initData.get(t.id),r=this.segments.get(t.id),s=this.parsedInitData.get(t.id);(0,w.assertNonNullable)(i,"No init buffer for starting representation"),(0,w.assertNonNullable)(r,"No segments for starting representation"),i instanceof ArrayBuffer&&(this.searchGaps(r,t),yield this.sourceBufferTaskQueue.append(i,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(s))}.bind(this));this.switchTo=(0,w.abortable)(this.destroyAbortController.signal,async function*(e,t=!1){if(!X(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);(0,w.assertNonNullable)(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if((0,w.isNullable)(s)||(0,w.isNullable)(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),(0,w.assertNonNullable)(r,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!X(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer();else{let n=this.getCurrentPosition();(0,w.isNonNullable)(n)&&!this.isLive&&(this.bufferLimit=1/0,await this.pruneBuffer(n,1/0,!0)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}this.maintain()}}.bind(this));this.switchToOld=(0,w.abortable)(this.destroyAbortController.signal,async function*(e,t=!1){if(!X(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);(0,w.assertNonNullable)(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if((0,w.isNullable)(s)||(0,w.isNullable)(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),(0,w.assertNonNullable)(r,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!X(this.mediaSource,this.sourceBuffer)))if(yield this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer(),this.maintain();else{let n=this.getCurrentPosition();(0,w.isNonNullable)(n)&&(this.isLive||(this.bufferLimit=1/0,await this.pruneBuffer(n,1/0,!0)),this.maintain(n)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}}.bind(this));this.seekLive=(0,w.abortable)(this.destroyAbortController.signal,async function*(e){let t=(0,vn.default)(e,o=>o.representations);if(!this.downloadingRepresentationId||!t.length)return;this.isSeekingLive=!0;for(let o of this.representations.keys()){let l=t.find(d=>d.id===o);l&&this.representations.set(o,l);let p=this.representations.get(o);if(!p||!tt(p.segmentReference)){this.isSeekingLive=!1;return}let c=this.getActualLiveStartingSegments(p.segmentReference);this.segments.set(p.id,c)}let i=this.switchingToRepresentationId??this.downloadingRepresentationId,r=this.representations.get(i);(0,w.assertNonNullable)(r,`Representation not found by id ${i}`);let s=this.segments.get(i);(0,w.assertNonNullable)(s,"No segments for starting representation");let n=this.initData.get(i);if((0,w.assertNonNullable)(n,"No init buffer for starting representation"),!(n instanceof ArrayBuffer)){this.isSeekingLive=!1;return}let u=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,yield this.abort(),u&&(yield this.sourceBufferTaskQueue.remove(u.from*1e3,u.to*1e3,this.destroyAbortController.signal)),this.searchGaps(s,r),yield this.sourceBufferTaskQueue.append(n,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this));this.fetcher=r,this.tuning=s,this.compatibilityMode=o,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=u,this.isLive=!!l?.live,this.baseUrls=l?.baseUrls??[],this.initData=new Map(i.map(p=>[p.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(i.map(p=>[p.id,p])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}switchToWithPreviousAbort(e,t=!1){!X(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new ue,(0,w.abortable)(this.switchAbortController.signal,async function*(i,r=!1){this.switchingToRepresentationId=i;let s=this.representations.get(i);(0,w.assertNonNullable)(s,`No such representation ${i}`);let n=this.segments.get(i),u=this.initData.get(i);if((0,w.isNullable)(u)||(0,w.isNullable)(n)?yield this.loadInit(s,"high",!1):u instanceof Promise&&(yield u),n=this.segments.get(i),(0,w.assertNonNullable)(n,"No segments for starting representation"),u=this.initData.get(i),!(!(u instanceof ArrayBuffer)||!this.sourceBuffer||!X(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(u,this.downloadAbortController.signal),r)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=i,yield this.dropBuffer();else{let o=this.getCurrentPosition();(0,w.isNonNullable)(o)&&!this.isLive&&(this.bufferLimit=this.forwardBufferTarget,yield this.pruneBuffer(o,1/0,!0)),this.downloadingRepresentationId=i,this.switchingToRepresentationId=void 0}this.maintain()}}.bind(this))(e,t))}warmUpMediaSource(){!(0,w.isNullable)(this.sourceBuffer)&&!this.sourceBuffer.updating&&(this.sourceBuffer.mode="segments")}async abort(){for(let e of this.activeSegments)this.abortSegment(e.segment);return this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new ue,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if((0,w.isNullable)(e)||(0,w.isNullable)(this.downloadingRepresentationId)||(0,w.isNullable)(this.playingRepresentationId)||(0,w.isNullable)(this.sourceBuffer)||!X(this.mediaSource,this.sourceBuffer)||(0,w.isNonNullable)(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.representations.get(this.playingRepresentationId),r=this.segments.get(this.downloadingRepresentationId),s=this.segments.get(this.playingRepresentationId);if((0,w.assertNonNullable)(t,`No such representation ${this.downloadingRepresentationId}`),(0,w.assertNonNullable)(i,`No such representation ${this.playingRepresentationId}`),(0,w.isNullable)(r)||(0,w.isNullable)(s))return;let n=r.find(d=>e>=d.time.from&&e<d.time.to);(0,w.isNonNullable)(n)&&isFinite(n.time.from)&&isFinite(n.time.to)&&this.currentSegmentLength$.next(n?.time.to-n.time.from);let u=e,o=100;if(this.playingRepresentationId!==this.downloadingRepresentationId){let d=this.getForwardBufferDuration(e),h=Na(i),m=Na(t),b=this.useSmartRepresentationSwitch&&this.tuning.dash.useNewRepresentationSwitch&&this.tuning.dash.useSmartRepresentationSwitch&&(0,w.isNonNullable)(h)&&(0,w.isNonNullable)(m)&&(0,w.isHigher)(h.quality,m.quality),S=this.useSmartRepresentationSwitch&&this.tuning.dash.useNewRepresentationSwitch&&this.tuning.dash.useDelayedRepresentationSwitch;if(b||S?u+=Math.min(d,this.tuning.dash.representationSwitchForwardBufferGap):n&&n.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&d>=n.time.to-e+o&&(u=n?n.time.to+o:-1/0),this.tuning.dash.useNewRepresentationSwitch){let I=[...this.segments.entries()].map(([P,x])=>{let C=x.find(V=>e>=V.time.from&&e<V.time.to);return{representationId:P,status:C?.status}}).find(P=>P.status==="fed")?.representationId;I&&(this.playingRepresentationId=I,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)))}}if(isFinite(this.bufferLimit)&&hr(this.sourceBuffer.buffered)>=this.bufferLimit){let d=this.getForwardBufferDuration(e),h=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,d<h).catch(m=>{this.handleAsyncError(m,"pruneBuffer")});return}let p=[];if(!this.activeSegments.size&&(p=this.selectForwardBufferSegments(r,t.segmentReference.type,u),p.length)){let d="auto";if(this.tuning.dash.useFetchPriorityHints&&n)if((0,Sn.default)(p,n))d="high";else{let h=(0,Ri.default)(p,0);h&&h.time.from-n.time.to>=this.forwardBufferTarget/2&&(d="low")}this.loadSegments(p,t,d).catch(h=>{this.handleAsyncError(h,"loadSegments")})}(!this.preloadOnly&&!this.allInitsLoaded&&n&&n.status==="fed"&&!p.length&&this.getForwardBufferDuration(e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let c=(0,Ri.default)(r,-1);!this.isLive&&c&&(this.fullyBuffered$.next(c.time.to-e-this.getForwardBufferDuration(e)<o),this.onLastSegment$.next(e-c.time.from>0))}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}searchGaps(e,t){this.gaps=[];let i=0,r=this.isLive?this.liveInitialAdditionalOffset:0;for(let s of e)Math.trunc(s.time.from-i)>0&&this.gaps.push({representation:t.id,from:i,to:s.time.from+r,persistent:!0}),i=s.time.to;(0,w.isNonNullable)(t.duration)&&t.duration-i>0&&!this.isLive&&this.gaps.push({representation:t.id,from:i,to:t.duration,persistent:!0})}getActualLiveStartingSegments(e){let t=e.segments,i=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,r=[],s=0,n=t.length-1;do r.unshift(t[n]),s+=t[n].time.to-t[n].time.from,n--;while(s<i&&n>=0);return this.liveInitialAdditionalOffset=s-i,this.isActiveLowLatency()?[r[0]]:r}getLiveSegmentsToLoadState(e){let t=e?.streams[this.kind];if(!t)return;let i=(0,vn.default)(t,s=>s.representations).find(s=>s.id===this.downloadingRepresentationId);if(!i)return;let r=this.segments.get(i.id);if(r?.length)return{from:r[0].time.from,to:r[r.length-1].time.to}}updateLive(e){if(!e||[...this.segments.values()].every(i=>!i.length))return;let t=(0,vn.default)(e.streams[this.kind],i=>i.representations);for(let i of t){if(!i||!tt(i.segmentReference))return;let r=i.segmentReference.segments.map(l=>({...l,status:"none",size:void 0})),s=100,n=this.segments.get(i.id)??[],u=(0,Ri.default)(n,-1)?.time.to??0,o=r?.findIndex(l=>u>=l.time.from+s&&u<=l.time.to+s);if(o===-1){this.liveUpdateSegmentIndex=0;let l=this.getActualLiveStartingSegments(i.segmentReference);this.segments.set(i.id,l)}else{let l=r.slice(o+1);this.segments.set(i.id,[...n,...l])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;(0,w.assertNonNullable)(e);let t=this.segments.get(e);if(t?.length){let i=t[t.length-1];this.updateLowLatencyLiveIfNeeded(i)}}calculateDurationFromSegments(){if(!this.playingRepresentationId)return 0;let e=this.segments.get(this.playingRepresentationId);return(e?(0,Ri.default)(e,-1)?.time.to:0)||0}setSmartRepresentationSwitch(e){this.useSmartRepresentationSwitch=e}updateLowLatencyLiveIfNeeded(e){let t=0;for(let i of this.representations.values()){let r=i.segmentReference;if(!tt(r))return;let s=this.segments.get(i.id)??[],n=s.find(o=>Math.floor(o.time.from)===Math.floor(e.time.from));if(n&&!isFinite(n.time.to)&&(n.time.to=e.time.to,t=n.time.to-n.time.from),!!!s.find(o=>Math.floor(o.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let o=Math.round(e.time.to*r.timescale/1e3).toString(10),l=vt(r.segmentTemplateUrl,{segmentTime:o});s.push({status:"none",time:{from:e.time.to,to:1/0},url:l})}}this.currentLowLatencySegmentLength$.next(t)}findSegmentStartTime(e){let t=this.switchingToRepresentationId??this.downloadingRepresentationId??this.playingRepresentationId;if(!t)return;let i=this.segments.get(t);return i?i.find(s=>s.time.from<=e&&s.time.to>=e)?.time.from??void 0:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),this.sourceBufferTaskQueue?.destroy(),this.gapDetectionIdleCallback&&Lt&&Lt(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&Lt&&Lt(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer)try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(e){if(!(e instanceof DOMException&&e.name==="NotFoundError"))throw e}this.sourceBuffer=null,this.downloadAbortController.abort(),this.switchAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,i){return this.isLive?this.selectForwardBufferSegmentsLive(e,i):this.selectForwardBufferSegmentsRecord(e,t,i)}selectForwardBufferSegmentsLive(e,t){let i=e.findIndex(r=>t>=r.time.from&&t<r.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=i),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,i){let r=this.getForwardBufferDuration(i),s=e.findIndex(({status:d,time:{from:h,to:m}},b)=>{let S=h<=i&&m>=i,v=h>i||S||b===0&&i===0,I=Math.min(this.forwardBufferTarget,this.bufferLimit),P=this.preloadOnly&&h<=i+I||r<I&&m-h>=I||m<=i+I;return(d==="none"||d==="partially_ejected"&&v&&P&&this.sourceBuffer&&X(this.mediaSource,this.sourceBuffer)&&!(Ce(this.sourceBuffer.buffered,h)&&Ce(this.sourceBuffer.buffered,m)))&&v&&P});if(s===-1)return[];if(t!=="byteRange")return e.slice(s,s+1);let n=e,u=0,o=0,l=[],p=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,c=this.preloadOnly?this.forwardBufferTarget:0;for(let d=s;d<n.length&&(u<=p||o<=c);d++){let h=n[d];if(u+=h.byte.to+1-h.byte.from,o+=h.time.to+1-h.time.from,h.status==="none"||h.status==="partially_ejected")l.push(h);else break}return l}async loadSegments(e,t,i="auto"){tt(t.segmentReference)?await this.loadTemplateSegment(e[0],t,i):await this.loadByteRangeSegments(e,t,i)}async loadTemplateSegment(e,t,i="auto"){e.status="downloading";let r={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(r);let{range:s,url:n,signal:u,onProgress:o,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&u&&(await(0,w.abortable)(u,async function*(){let p=(0,w.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>setTimeout(c,p))}.bind(this))(),u.aborted&&this.abortActiveSegments([e]));try{let p=await this.fetcher.fetch(n,{range:s,signal:u,onProgress:o,priority:i,isLowLatency:this.isActiveLowLatency(),bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation});if(this.lastDataObtainedTimestampMs=(0,w.now)(),!p)return;let c=new DataView(p),d=Mt(t.mime);if(!isFinite(r.segment.time.to)){let b=t.segmentReference.timescale;r.segment.time.to=d.getChunkEndTime(c,b)}o&&r.feedingBytes&&l?await Promise.all(l):await this.sourceBufferTaskQueue.append(c,u);let{serverDataReceivedTimestamp:h,serverDataPreparedTime:m}=d.getServerLatencyTimestamps(c);h&&m&&this.currentLiveSegmentServerLatency$.next(m-h),r.segment.status="downloaded",this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(p){this.abortActiveSegments([e]),Dt(p)||(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())tt(t.segmentReference)?t.segmentReference.baseUrl=e:t.segmentReference.url=e}async loadByteRangeSegments(e,t,i="auto"){if(!e.length)return;for(let o of e)o.status="downloading",this.activeSegments.add({segment:o,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:r,url:s,signal:n,onProgress:u}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(await(0,w.abortable)(n,async function*(){let o=(0,w.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,o),(0,w.fromEvent)(window,"online").pipe((0,w.once)()).subscribe(()=>{l(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(s,{range:r,onProgress:u,signal:n,priority:i,bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation}),this.lastDataObtainedTimestampMs=(0,w.now)(),this.failedDownloads=0}catch(o){this.abortActiveSegments(e),Dt(o)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}prepareByteRangeFetchSegmentParams(e,t){if(tt(t.segmentReference))throw new Error("Representation is not byte range type");let i=t.segmentReference.url,r={from:(0,Ri.default)(e,0).byte.from,to:(0,Ri.default)(e,-1).byte.to},{signal:s}=this.downloadAbortController;return{url:i,range:r,signal:s,onProgress:async(u,o)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=(0,w.now)(),await this.onSomeByteRangesDataLoaded({dataView:u,loaded:o,signal:s,onSegmentAppendFailed:()=>this.abort(),globalFrom:r?r.from:0,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:w.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!tt(t.segmentReference))throw new Error("Representation is not template type");let i=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&i.searchParams.set("low-latency","yes");let r=i.toString(),{signal:s}=this.downloadAbortController,n=[],o=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(l,p)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=(0,w.now)();let c=this.onSomeTemplateDataLoaded({dataView:l,loaded:p,signal:s,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(c)}catch(c){this.error$.next({id:"SegmentFeeding",category:w.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:c})}}:void 0;return{url:r,signal:s,onProgress:o,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)(0,Sn.default)(e,t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:r,signal:s}){if(!this.activeSegments.size||!X(this.mediaSource,this.sourceBuffer))return;let n=this.representations.get(t);if(n)for(let u of this.activeSegments){let{segment:o}=u;if(u.representationId===t){if(s.aborted){r();continue}if(u.loadedBytes=i,u.loadedBytes>u.feedingBytes){let l=new DataView(e.buffer,e.byteOffset+u.feedingBytes,u.loadedBytes-u.feedingBytes),p=Mt(n.mime).parseFeedableSegmentChunk(l,this.isLive);p?.byteLength&&(o.status="partially_fed",u.feedingBytes+=p.byteLength,await this.sourceBufferTaskQueue.append(p),u.fedBytes+=p.byteLength)}}}}async onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:s,onSegmentAppendFailed:n}){if(!this.activeSegments.size||!X(this.mediaSource,this.sourceBuffer))return;let u=this.representations.get(t);if(u)for(let o of this.activeSegments){let{segment:l}=o;if(o.representationId!==t)continue;if(s.aborted){await n();continue}let p=l.byte.from-i,c=l.byte.to-i,d=c-p+1,h=p<r,m=c<=r;if(!h)continue;let b=Mt(u.mime);if(l.status==="downloading"&&m){l.status="downloaded";let S=new DataView(e.buffer,e.byteOffset+p,d);await this.sourceBufferTaskQueue.append(S,s)&&!s.aborted?this.onSegmentFullyAppended(o,t):await n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(l.status==="downloading"||l.status==="partially_fed")&&(o.loadedBytes=Math.min(d,r-p),o.loadedBytes>o.feedingBytes)){let S=new DataView(e.buffer,e.byteOffset+p+o.feedingBytes,o.loadedBytes-o.feedingBytes),v=o.loadedBytes===d?S:b.parseFeedableSegmentChunk(S);v?.byteLength&&(l.status="partially_fed",o.feedingBytes+=v.byteLength,await this.sourceBufferTaskQueue.append(v,s)&&!s.aborted?(o.fedBytes+=v.byteLength,o.fedBytes===d&&this.onSegmentFullyAppended(o,t)):await n())}}}onSegmentFullyAppended(e,t){if(!((0,w.isNullable)(this.sourceBuffer)||!X(this.mediaSource,this.sourceBuffer))){!this.isLive&&j.browser.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(Ce(this.sourceBuffer.buffered,e.segment.time.from,100)&&Ce(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:w.ErrorCategory.VIDEO_PIPELINE,message:"Browser stuck on empty result of adding segment to source buffer"})),this.tuning.dash.useNewRepresentationSwitch||(this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId))),e.segment.status="fed",Ll(e.segment)&&(e.segment.size=e.fedBytes);for(let i of this.representations.values())if(i.id!==t)for(let r of this.segments.get(i.id)??[])r.status==="fed"&&Math.round(r.time.from)===Math.round(e.segment.time.from)&&Math.round(r.time.to)===Math.round(e.segment.time.to)&&(r.status="none");this.updateLowLatencyLiveIfNeeded(e.segment),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment])}}abortSegment(e){e.status==="partially_fed"?e.status="partially_ejected":e.status!=="partially_ejected"&&(e.status="none");for(let t of this.activeSegments.values())if(t.segment===e){this.activeSegments.delete(t);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(let[r,s]of this.initData.entries()){let n=s instanceof Promise;t||=n,s===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let i=this.representations.get(e);i&&(this.initLoadIdleCallback=pr(()=>(0,OS.default)(this.loadInit(i,"low",!1),()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",i=!1){let r=this.tuning.dash.useFetchPriorityHints?t:"auto",s=!i&&this.tuning.dash.ignoreNetworkErrorsOnLoadInit,u=(!i&&this.failedDownloads>0?(0,w.abortable)(this.destroyAbortController.signal,async function*(){let o=(0,w.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>setTimeout(l,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,Mt(e.mime),{priority:r,ignoreNetworkErrors:s})).then(async o=>{if(!o)return;let{init:l,dataView:p,segments:c}=o,d=p.buffer.slice(p.byteOffset,p.byteOffset+p.byteLength);this.initData.set(e.id,d);let h=c;this.isLive&&tt(e.segmentReference)&&(h=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,h),l&&this.parsedInitData.set(e.id,l)}).then(()=>this.failedDownloads=0,o=>{s||this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:w.ErrorCategory.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,u),u}async dropBuffer(){for(let e of this.segments.values())for(let t of e)t.status="none";await this.pruneBuffer(0,1/0,!0)}async pruneBuffer(e,t,i=!1){if(!this.sourceBuffer||!X(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||(0,w.isNullable)(e))return!1;let r=[],s=0,n=o=>{o.sort((p,c)=>p.from-c.from);let l=[o[0]];for(let p=1;p<o.length;p++){let{from:c,to:d}=o[p],h=l[l.length-1];h.to>=c?h.to=Math.max(h.to,d):l.push(o[p])}return l},u=o=>{if(s>=t)return r;r.push({...o.time}),r=n(r);let l=Ll(o)?o.size??0:o.byte.to-o.byte.from;s+=l};for(let o of this.segments.values())for(let l of o){let p=l.time.to<=e-this.tuning.dash.bufferPruningSafeZone,c=l.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(p||c)&&l.status==="fed"&&u(l)}for(let o=0;o<this.sourceBuffer.buffered.length;o++){let l=this.sourceBuffer.buffered.start(o)*1e3,p=this.sourceBuffer.buffered.end(o)*1e3,c=0;for(let d of this.segments.values())for(let h of d)(0,Sn.default)(["none","partially_ejected"],h.status)&&Math.round(h.time.from)<=Math.round(l)&&Math.round(h.time.to)>=Math.round(p)&&c++;if(c===this.segments.size){let d={time:{from:l,to:p},url:"",status:"none"};u(d)}}if(r.length&&i){let o=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let l of this.segments.values())for(let p of l)p.time.from>=e+o&&p.status==="fed"&&u(p)}return r.length?(await Promise.all(r.map(l=>this.sourceBufferTaskQueue.remove(l.from,l.to)))).reduce((l,p)=>l||p,!1):!1}async abortBuffer(){if(!this.sourceBuffer||!X(this.mediaSource,this.sourceBuffer))return!1;let e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;return this.sourceBufferTaskQueue.abort(t)}getDebugBufferState(){if(!(!this.sourceBuffer||!X(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}getForwardBufferDuration(e=this.getCurrentPosition()){return!this.sourceBuffer||!X(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||(0,w.isNullable)(e)?0:De(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!(!this.sourceBuffer||!X(this.mediaSource,this.sourceBuffer)))for(let i of t){let r={representation:e,from:i.time.from,to:i.time.to,persistent:!1},{buffered:s}=this.sourceBuffer;for(let n=0;n<s.length;n++){let u=s.start(n)*1e3,o=s.end(n)*1e3;if(!(o<=i.time.from||u>=i.time.to)){if(u<=i.time.from&&o>=i.time.to){r=void 0;break}o>i.time.from&&o<i.time.to&&(r.from=o),u<i.time.to&&u>i.time.from&&(r.to=u)}}r&&r.to-r.from>1&&!this.gaps.some(n=>r&&n.from===r.from&&n.to===r.to)&&this.gaps.push(r)}}detectGapsWhenIdle(e,t){if(this.gapDetectionIdleCallback||!this.sourceBuffer||!X(this.mediaSource,this.sourceBuffer))return;let{buffered:i}=this.sourceBuffer,{usePersistentGaps:r}=this.tuning.dash;this.gaps=this.gaps.filter(s=>{if(r&&s.persistent)return!0;let n=Math.round(s.from),u=Math.round(s.to);for(let o=0;o<i.length;o++)if(n>=Math.round(i.start(o)*1e3)&&u<=Math.round(i.end(o)*1e3))return!1;return!0}),this.gapDetectionIdleCallback=pr(()=>{try{this.detectGaps(e,t)}catch(s){this.error$.next({id:"GapDetection",category:w.ErrorCategory.WTF,message:"detectGaps threw",thrown:s})}finally{this.gapDetectionIdleCallback=null}})}checkEjectedSegments(){if((0,w.isNullable)(this.sourceBuffer)||!X(this.mediaSource,this.sourceBuffer)||(0,w.isNullable)(this.playingRepresentationId))return;let e=[];for(let i=0;i<this.sourceBuffer.buffered.length;i++){let r=Math.floor(this.sourceBuffer.buffered.start(i)*1e3),s=Math.ceil(this.sourceBuffer.buffered.end(i)*1e3);e.push({from:r,to:s})}let t=100;for(let i of this.segments.values())for(let r of i){let{status:s}=r;if(s!=="fed"&&s!=="partially_ejected")continue;let n=Math.floor(r.time.from),u=Math.ceil(r.time.to),o=e.some(p=>p.from-t<=n&&p.to+t>=u),l=e.filter(p=>n>=p.from&&n<p.to-t||u>p.from+t&&u<=p.to);o||(l.length===1?r.status="partially_ejected":this.gaps.some(p=>p.from===r.time.from||p.to===r.time.to)?r.status="partially_ejected":r.status="none")}}handleAsyncError(e,t){this.error$.next({id:t,category:w.ErrorCategory.VIDEO_PIPELINE,thrown:e,message:"Something went wrong"})}};var ni=a=>{let e=new URL(a);return e.searchParams.set("quic","1"),e.toString()};var yn=a=>{let e=a.get("X-Delivery-Type"),t=a.get("X-Reused"),i=e===null?"http1":e??void 0,r=t===null?void 0:{1:!0,0:!1}[t]??void 0;return{type:i,reused:r}};var G=require("@vkontakte/videoplayer-shared");var Tn=a=>{let e=new URL(a);return e.searchParams.set("enable-subtitles","yes"),e.toString()};var En=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:s=!1}){this.manifestRequested$=new G.Subject;this.firstBytesManifest$=new G.Subject;this.manifestReceived$=new G.Subject;this.firstBytesRequested$=new G.Subject;this.firstBytesReceived$=new G.Subject;this.lastConnectionType$=new G.ValueSubject(void 0);this.lastConnectionReused$=new G.ValueSubject(void 0);this.lastRequestFirstBytes$=new G.ValueSubject(void 0);this.recoverableError$=new G.Subject;this.error$=new G.Subject;this.abortAllController=new ue;this.subscription=new G.SubscriptionRemovable;this.fetchManifest=(0,G.abortable)(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=ni(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=Tn(i)),this.manifestRequested$.next();let r=yield this.doFetch(i,{signal:this.abortAllController.signal},{type:"manifest"}).catch(In);return r?(t.log("success",(0,G.flattenObject)({url:i,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(r.headers),this.manifestReceived$.next(),r.text()):(t.error("error",(0,G.flattenObject)({url:i,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=(0,G.abortable)(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:i,onProgress:r,priority:s="auto",signal:n,measureThroughput:u=!0,isLowLatency:o=!1,bufferOptimisation:l=!1,ignoreNetworkErrors:p=!1}={}){let c=e,d=new Headers,h=this.tracer.createComponentTracer("Fetch");if(i)switch(t){case 0:{d.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let k=new URL(c,location.href);k.searchParams.append("bytes",`${i.from}-${i.to}`),c=k.toString();break}default:(0,G.assertNever)(t)}this.requestQuic&&(c=ni(c));let m=this.abortAllController.signal,b;if(n){let k=new ue;if(b=(0,G.merge)((0,G.fromEvent)(this.abortAllController.signal,"abort"),(0,G.fromEvent)(n,"abort")).subscribe(()=>{try{k.abort()}catch(te){In(te)}}),this.subscription.add(b),this.abortAllController.signal.aborted||n.aborted)try{k.abort()}catch(te){In(te)}m=k.signal}let S=0,v=(0,G.now)();h.log("startRequest",(0,G.flattenObject)({url:c,priority:s,rangeMethod:t,range:i,isLowLatency:o,requestStartedAt:v})),this.firstBytesRequested$.next();let I=yield this.doFetch(c,{priority:s,headers:d,signal:m},{ignoreNetworkErrors:p}),P=(0,G.now)();if(!I)return h.error("error",{message:"No response in request"}),h.end(),this.unsubscribeAbortSubscription(b),null;if(this.throughputEstimator?.addRawRtt(P-v),!I.ok||!I.body){this.unsubscribeAbortSubscription(b);let k=`Fetch error ${I.status}: ${I.statusText}`;return h.error("error",{message:k}),h.end(),Promise.reject(new Error(`Fetch error ${I.status}: ${I.statusText}`))}if(this.onHeadersReceived(I.headers),!r&&!u){this.unsubscribeAbortSubscription(b);let k=(0,G.now)(),te={requestStartedAt:v,requestEndedAt:k,duration:k-v};return h.log("endRequest",(0,G.flattenObject)(te)),h.end(),I.arrayBuffer()}let x=I.body;if(u){let k;[x,k]=I.body.tee(),this.throughputEstimator?.trackStream(k,o)}let C=x.getReader(),V,O=parseInt(I.headers.get("content-length")??"",10);Number.isFinite(O)&&(V=O),!V&&i&&(V=i.to-i.from+1);let D=V?new Uint8Array(V):new Uint8Array(0),N=!1,L=k=>{this.unsubscribeAbortSubscription(b),N=!0,In(k)},ee=(0,G.abortable)(m,async function*({done:k,value:te}){if(S===0&&(this.lastRequestFirstBytes$.next((0,G.now)()-v),this.firstBytesReceived$.next()),m.aborted){this.unsubscribeAbortSubscription(b);return}if(!k&&te){if(l&&V)D.set(te,S),S+=te.byteLength;else{let _=new Uint8Array(D.length+te.length);_.set(D),_.set(te,D.length),D=_,S+=te.byteLength}r?.(new DataView(D.buffer),S),yield C?.read().then(ee,L)}}.bind(this));yield C?.read().then(ee,L),this.unsubscribeAbortSubscription(b);let W=(0,G.now)(),R={failed:N,requestStartedAt:v,requestEndedAt:W,duration:W-v};return N?(h.error("endRequest",(0,G.flattenObject)(R)),h.end(),null):(h.log("endRequest",(0,G.flattenObject)(R)),h.end(),D.buffer)}.bind(this));this.fetchByteRangeRepresentation=(0,G.abortable)(this.abortAllController.signal,async function*(e,t,i){if(e.type!=="byteRange")return null;let{from:r,to:s}=e.initRange,n=r,u=s,o=!1,l,p;e.indexRange&&(l=e.indexRange.from,p=e.indexRange.to,o=s+1===l,o&&(n=Math.min(l,r),u=Math.max(p,s))),n=Math.min(n,0);let c=yield this.fetch(e.url,{range:{from:n,to:u},measureThroughput:!1,...i});if(!c)return null;let d=new DataView(c,r-n,s-n+1);if(!t.validateData(d))throw new Error("Invalid media file");let h=t.parseInit(d),m=e.indexRange??t.getIndexRange(h);if(!m)throw new ReferenceError("No way to load representation index");let b;if(o)b=new DataView(c,m.from-n,m.to-m.from+1);else{let v=yield this.fetch(e.url,{range:m,measureThroughput:!1});if(!v)return null;b=new DataView(v)}let S=t.parseSegments(b,h,m);return{init:h,dataView:new DataView(c),segments:S}}.bind(this));this.fetchTemplateRepresentation=(0,G.abortable)(this.abortAllController.signal,async function*(e,t){if(e.type!=="template")return null;let i=new URL(e.initUrl,e.baseUrl).toString(),r=yield this.fetch(i,{measureThroughput:!1,...t});return r?{init:null,segments:e.segments.map(n=>({...n,status:"none",size:void 0})),dataView:new DataView(r)}:null}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=r,this.tracer=i.createComponentTracer("Fetcher"),this.useEnableSubtitlesParam=s}onHeadersReceived(e){let{type:t,reused:i}=yn(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}async fetchRepresentation(e,t,i){let{type:r}=e;switch(r){case"byteRange":return await this.fetchByteRangeRepresentation(e,t,i)??null;case"template":return await this.fetchTemplateRepresentation(e,i)??null;default:(0,G.assertNever)(r)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}async doFetch(e,t,i){let r=await lt(e,t);if(r.ok)return i?.type==="manifest"&&this.firstBytesManifest$.next(),r;if(i?.ignoreNetworkErrors)return;let s=await r.text(),n=parseInt(s);if(!isNaN(n))switch(n){case 1:this.recoverableError$.next({id:"VideoDataLinkExpiredError",message:"Video data links have expired",category:G.ErrorCategory.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:G.ErrorCategory.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:G.ErrorCategory.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:G.ErrorCategory.FATAL});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${n})`,category:G.ErrorCategory.FATAL})}}unsubscribeAbortSubscription(e){e&&(e.unsubscribe(),this.subscription.remove(e))}},In=a=>{if(!Dt(a))throw a};var Ht=(a,e,t)=>t*e+(1-t)*a,Dl=(a,e)=>a.reduce((t,i)=>t+i,0)/e,FS=(a,e,t,i)=>{let r=0,s=t,n=Dl(a,e),u=e<i?e:i;for(let o=0;o<u;o++)a[s]>n?r++:r--,s=(a.length+s-1)%a.length;return Math.abs(r)===u};var Ua=require("@vkontakte/videoplayer-shared"),oi=class{constructor(e){this.prevReported=void 0;this.pastMeasures=[];this.takenMeasures=0;this.measuresCursor=0;this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new Ua.ValueSubject(e.initial),this.debounced$=new Ua.ValueSubject(e.initial);let t=e.label??"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new Fe(`raw_${t}`),this.smoothedSeries$=new Fe(`smoothed_${t}`),this.reportedSeries$=new Fe(`reported_${t}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,i=0;for(let u=0;u<this.pastMeasures.length;u++)this.pastMeasures[u]!==void 0&&(t+=(this.pastMeasures[u]-this.smoothed)**2,i++);this.takenMeasures=i,t/=i;let r=Math.sqrt(t),s=this.smoothed+this.params.deviationFactor*r,n=this.smoothed-this.params.deviationFactor*r;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(e),this.updateSmoothedValue(e),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),!(this.smoothed>s||this.smoothed<n)&&((0,Ua.isNullable)(this.prevReported)||Math.abs(this.smoothed-this.prevReported)/this.prevReported>=this.params.changeThreshold)&&(this.prevReported=this.smoothed,this.debounced$.next(this.smoothed),this.reportedSeries$.next(this.smoothed))}};var xn=class extends oi{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=Ht(this.slow,e,this.params.emaAlphaSlow),this.fast=Ht(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var wn=class extends oi{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=Dl(this.pastMeasures,this.takenMeasures);this.emaSmoothed=Ht(this.emaSmoothed,e,this.params.emaAlpha);let i=FS(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=i?this.emaSmoothed:t}};var An=class extends oi{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?Ht(this.smoothed,t,this.params.emaAlpha):t}};var jt=class{static getSmoothedValue(e,t,i){return i.type==="TwoEma"?new xn({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new wn({initial:e,emaAlpha:i.emaAlpha,basisTrendChangeCount:i.basisTrendChangeCount,changeThreshold:i.changeThreshold,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"})}static getLiveBufferSmoothedValue(e,t){return new An({initial:e,label:"liveEdgeDelay",...t})}};var Sr=(a,e)=>{a&&a.playbackRate!==e&&(a.playbackRate=e)};var Pn=require("@vkontakte/videoplayer-shared");var Ha=class a{constructor(e,t){this.currentRepresentation$=new Pn.ValueSubject(null);this.maxRepresentations=4;this.representationsCursor=0;this.representations=[];this.currentSegment=null;this.getCurrentPosition=t.getCurrentPosition,this.processStreams(e)}updateLive(e){this.processStreams(e?.streams.text)}seekLive(e){this.processStreams(e)}maintain(e=this.getCurrentPosition()){if(!(0,Pn.isNullable)(e))for(let t of this.representations)for(let i of t){let r=i.segmentReference,s=r.segments.length,n=r.segments[0].time.from,u=r.segments[s-1].time.to;if(e<n||e>u)continue;let o=r.segments.find(l=>l.time.from<=e&&l.time.to>=e);!o||this.currentSegment?.time.from===o.time.from&&this.currentSegment.time.to===o.time.to||(this.currentSegment=o,this.currentRepresentation$.next({...i,label:"Live Text",language:"ru",isAuto:!0,url:new URL(o.url,r.baseUrl).toString()}))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e??[]){let i=a.filterRepresentations(t.representations);if(i){this.representations[this.representationsCursor]=i,this.representationsCursor=(this.representationsCursor+1)%this.maxRepresentations;break}}}static isSupported(e){return!!e?.some(t=>a.filterRepresentations(t.representations))}static filterRepresentations(e){return e?.filter(t=>t.kind==="text"&&"segmentReference"in t&&tt(t.segmentReference))}};var Rn=Q(gt(),1),Cl=Q(Oe(),1),ja=require("@vkontakte/videoplayer-shared");var kn=a=>{let{webmDecodingInfo:e}=j.video,t="DASH_WEBM",i="DASH_WEBM_AV1";switch(a){case"vp9":return[t,i];case"av1":return[i,t];case"none":return[];case"smooth":return e?e[i].smooth?[i,t]:e[t].smooth?[t,i]:[i,t]:[t,i];case"power_efficient":return e?e[i].powerEfficient?[i,t]:e[t].powerEfficient?[t,i]:[i,t]:[t,i];default:(0,ja.assertNever)(a)}},NS=({webmCodec:a,androidPreferredFormat:e,iosPreferredFormat:t,preferMultiStream:i})=>{let r=[...i?["DASH_STREAMS"]:[],...kn(a),"DASH_SEP","DASH_ONDEMAND",...i?[]:["DASH_STREAMS"]],s=[...i?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...i?[]:["DASH_STREAMS"]];if(j.device.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[...s,"MPEG",...kn(a),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...kn(a),"MPEG",...s,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...kn(a),...s,"HLS","HLS_ONDEMAND"];default:(0,ja.assertNever)(e)}if(j.video.nativeHlsSupported)switch(t){case"hls":return[...r,"HLS","HLS_FMP4","HLS_ONDEMAND","MPEG"];case"hls_fmp4":return[...r,"HLS_FMP4","HLS","HLS_ONDEMAND","MPEG"];default:(0,ja.assertNever)(t)}return[...r,"HLS","HLS_ONDEMAND","MPEG"]},qS=({androidPreferredFormat:a,preferCMAF:e,preferWebRTC:t})=>{let i=e?["DASH_LIVE_CMAF","DASH_LIVE"]:["DASH_LIVE","DASH_LIVE_CMAF"],r=e?["HLS_LIVE_CMAF","HLS_LIVE"]:["HLS_LIVE","HLS_LIVE_CMAF"],s=[...i,...r],n=[...r,...i],u,o=j.device.isMac&&j.browser.isSafari;if(j.device.isAndroid)switch(a){case"dash":case"dash_any_mpeg":case"dash_any_webm":case"dash_sep":{u=s;break}case"hls":case"mpeg":{u=n;break}default:(0,ja.assertNever)(a)}else j.video.nativeHlsSupported&&!o&&!j.browser.isChromiumBased?u=n:o?u=e?["DASH_LIVE_CMAF","HLS_LIVE_CMAF","HLS_LIVE","DASH_LIVE"]:["HLS_LIVE","DASH_LIVE","DASH_LIVE_CMAF","HLS_LIVE_CMAF"]:u=s;return t?["WEB_RTC_LIVE",...u]:[...u,"WEB_RTC_LIVE"]},Bl=a=>a?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],$n=a=>{if(a.size===0)return;if(a.size===1){let t=a.values().next();return(0,Rn.default)(t.value.split("."),0)}for(let t of a){let i=(0,Rn.default)(t.split("."),0);if(i==="opus"||i==="vp09"||i==="av01")return i}let e=a.values().next();return(0,Rn.default)(e.value.split("."),0)},Ln=a=>{let e=a.map(i=>vr(i)),{codecs:t}=j.video;return ZR().filter(i=>{if((0,Cl.default)(e,i))switch(i){case"av1":return t.av1;case"vp9":return t.vp9;case"avc1":return t.h264;case"hev1":return t.h265;default:return!1}else return!1})},Mn=a=>{let e=a.map(i=>vr(i)),{codecs:t}=j.video;return e$().filter(i=>{if((0,Cl.default)(e,i))switch(i){case"opus":return t.opus;case"mp4a":return t.aac;default:return!1}else return!1})},vr=a=>a.split(".")[0].replace("0",""),ZR=()=>["av1","vp9","hev1","avc1"],e$=()=>["opus","mp4a"];var i$=["timeupdate","progress","play","seeked","stalled","waiting"],r$=["timeupdate","progress","loadeddata","playing","seeked"];var Dn=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.bufferManagers=[];this.subscription=new T.Subscription;this.subscriptionRemovable=new T.SubscriptionRemovable;this.representationSubscription=new T.Subscription;this.state$=new Z("none");this.currentVideoRepresentation$=new T.ValueSubject(void 0);this.currentVideoRepresentationInit$=new T.ValueSubject(void 0);this.currentAudioRepresentation$=new T.ValueSubject(void 0);this.currentVideoSegmentLength$=new T.ValueSubject(0);this.currentAudioSegmentLength$=new T.ValueSubject(0);this.error$=new T.Subject;this.manifestRequested$=new T.Subject;this.firstBytesManifest$=new T.Subject;this.manifestReceived$=new T.Subject;this.firstBytesRequested$=new T.Subject;this.firstBytesReceived$=new T.Subject;this.lastConnectionType$=new T.ValueSubject(void 0);this.lastConnectionReused$=new T.ValueSubject(void 0);this.lastRequestFirstBytes$=new T.ValueSubject(void 0);this.currentLiveTextRepresentation$=new T.ValueSubject(null);this.isLive$=new T.ValueSubject(!1);this.isActiveLive$=new T.ValueSubject(!1);this.isLowLatency$=new T.ValueSubject(!1);this.liveDuration$=new T.ValueSubject(0);this.liveSeekableDuration$=new T.ValueSubject(0);this.liveAvailabilityStartTime$=new T.ValueSubject(0);this.liveStreamStatus$=new T.ValueSubject(void 0);this.bufferLength$=new T.ValueSubject(0);this.liveLatency$=new T.ValueSubject(void 0);this.liveLoadBufferLength$=new T.ValueSubject(0);this.livePositionFromPlayer$=new T.ValueSubject(0);this.currentStallDuration$=new T.ValueSubject(0);this.videoLastDataObtainedTimestamp$=new T.ValueSubject(0);this.fetcherRecoverableError$=new T.Subject;this.fetcherError$=new T.Subject;this.liveStreamEndTimestamp=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.forceEnded$=new T.Subject;this.gapWatchdogActive=!1;this.liveWasInterrupted=!1;this.destroyController=new ue;this.initManifest=(0,T.abortable)(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=ye(t,i,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),this.manifest?.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:T.ErrorCategory.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=(0,T.abortable)(this.destroyController.signal,async function*(){this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(o=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:T.ErrorCategory.NETWORK,message:"Failed to load manifest",thrown:o})});if(!e)return null;let t=null;try{t=gn(e??"",this.manifestUrlString)}catch(o){let l=mn(e)??{id:"ManifestParsing",category:T.ErrorCategory.PARSER,message:"Failed to parse MPD manifest",thrown:o};this.error$.next(l)}if(!t)return null;let i=(o,l,p)=>!!(this.element?.canPlayType?.(l)&&Ze()?.isTypeSupported?.(`${l}; codecs="${p}"`)||o==="text");if(t.live){this.isLive$.next(!0);let{availabilityStartTime:o,latestSegmentPublishTime:l,streamIsUnpublished:p,streamIsAlive:c}=t.live,d=(t.duration??0)/1e3;this.liveSeekableDuration$.next(-1*d),this.liveDuration$.next((l-o)/1e3),this.liveAvailabilityStartTime$.next(t.live.availabilityStartTime);let h="active";if(c||(h=p?"unpublished":"unexpectedly_down"),this.liveStreamStatus$.next(h),c&&this.liveWasInterrupted){this.liveWasInterrupted=!1,this.stopStallWatchdogSubscription();let m=this.normalizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);this.seekLive(m).catch(b=>{this.error$.next({id:"updateManifest",category:T.ErrorCategory.VIDEO_PIPELINE,message:"seekLive after stream restore failed",thrown:b})})}}let r={text:t.streams.text,video:[],audio:[]},s,n;for(let o of["video","audio"]){let p=t.streams[o].filter(({mime:d,codecs:h})=>i(o,d,h));r[o]=p;let c;if(this.tuning.dash.codecsPrioritizeEnabled){let d=p.map(({codecs:h})=>h);o==="audio"&&(n=Mn(d),c=n[0]),o==="video"&&(s=Ln(d),this.forceVideoCodec&&(0,HS.default)(s,this.forceVideoCodec)?c=this.forceVideoCodec:c=s[0]),c&&(r[o]=p.filter(({codecs:h})=>vr(h)===c))}else{let d=new Set(p.map(({codecs:h})=>h));c=$n(d),c&&(r[o]=p.filter(({codecs:h})=>h.startsWith(c)))}if(o==="video"){let d=this.tuning.preferHDR,h=r.video.some(b=>b.hdr),m=r.video.some(b=>!b.hdr);j.display.isHDR&&d&&h?r.video=r.video.filter(b=>b.hdr):m&&(r.video=r.video.filter(b=>!b.hdr))}}let u={...t,streams:r};return this.tuning.dash.codecsPrioritizeEnabled&&(u.codecs={video:s,audio:n}),this.tracer.log("updateManifestEnd",(0,T.flattenObject)(u)),u}.bind(this));this.initRepresentations=(0,T.abortable)(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initRepresentationsStart",(0,T.flattenObject)({initialVideo:e,initialAudio:t,sourceHls:i})),(0,T.assertNonNullable)(this.manifest),(0,T.assertNonNullable)(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let r=c=>{this.representationSubscription.add((0,T.fromEvent)(c,"error").pipe((0,T.filter)(d=>!!this.element?.played.length)).subscribe(d=>{this.error$.next({id:"VideoSource",category:T.ErrorCategory.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:d})}))};this.source=Js();let s=document.createElement("source");if(r(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),sr())if(i){let c=document.createElement("source");r(c),c.type="application/x-mpegurl",c.src=i.url,this.element.appendChild(c)}else this.element.disableRemotePlayback=!0;this.isActiveLive$.next(this.isLive$.getValue());let n={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),manifest:this.manifest},u=this.manifest.streams.video.reduce((c,d)=>[...c,...d.representations],[]);if(this.videoBufferManager=new qa("video",this.source,u,n),this.bufferManagers=[this.videoBufferManager],(0,T.isNonNullable)(t)){let c=this.manifest.streams.audio.reduce((d,h)=>[...d,...h.representations],[]);this.audioBufferManager=new qa("audio",this.source,c,n),this.bufferManagers.push(this.audioBufferManager)}if(Ha.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new Ha(this.manifest.streams.text,n)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$)),this.representationSubscription.add((0,T.merge)(...r$.map(c=>(0,T.fromEvent)(this.element,c))).pipe((0,T.map)(c=>this.element?De(this.element.buffered,this.element.currentTime*1e3):0),(0,T.filterChanged)(),(0,T.tap)(c=>{c>this.tuning.dash.bufferEmptinessTolerance&&this.stopStallWatchdogSubscription()})).subscribe(this.bufferLength$)),this.representationSubscription.add((0,T.merge)((0,T.fromEvent)(this.element,"ended"),this.forceEnded$).subscribe(()=>{this.stopStallWatchdogSubscription()})),this.isLive$.getValue()){this.subscription.add(this.liveDuration$.pipe((0,T.filterChanged)()).subscribe(d=>this.liveStreamEndTimestamp=(0,T.now)())),this.subscription.add((0,T.fromEvent)(this.element,"pause").subscribe(()=>{let{liveUpdateInterval:d}=this.tuning.dash;this.livePauseWatchdogSubscription=(0,T.interval)(d).subscribe(h=>{let m=ei(this.manifestUrlString,2);this.manifestUrlString=ye(this.manifestUrlString,m+d,2),this.liveStreamStatus$.getValue()==="active"&&this.updateManifest()}),this.subscription.add(this.livePauseWatchdogSubscription)})).add((0,T.fromEvent)(this.element,"play").subscribe(d=>this.livePauseWatchdogSubscription?.unsubscribe())),this.representationSubscription.add((0,T.combine)({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe((0,T.map)(({isActiveLive:d,isLowLatency:h})=>d&&h),(0,T.filterChanged)()).subscribe(d=>{this.isManualDecreasePlaybackInLive()||Sr(this.element,1)})),this.representationSubscription.add((0,T.combine)({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe((0,T.filter)(({bufferLength:d,isActiveLive:h,isLowLatency:m})=>h&&m&&!!d)).subscribe(({bufferLength:d})=>this.liveBuffer.next(d))),this.representationSubscription.add(this.videoBufferManager.currentLowLatencySegmentLength$.subscribe(d=>{if(!this.isActiveLive$.getValue()&&!this.isLowLatency$.getValue()&&!d)return;let h=this.liveSeekableDuration$.getValue()-d/1e3;this.liveSeekableDuration$.next(Math.max(h,-1*this.tuning.dashCmafLive.maxLiveDuration)),this.liveDuration$.next(this.liveDuration$.getValue()+d/1e3)})),this.representationSubscription.add((0,T.combine)({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe((0,T.filter)(({isLive:d})=>d),(0,T.filterChanged)((d,h)=>h.bufferLength<d.bufferLength),(0,T.map)(({rtt:d,bufferLength:h,segmentServerLatency:m})=>{let b=ei(this.manifestUrlString,2);return(d/2+h+m+b)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add((0,T.combine)({liveBuffer:this.liveBuffer.smoothed$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).subscribe(({liveBuffer:d,isActiveLive:h,isLowLatency:m})=>{if(!m||!h)return;let b=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,S=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,v=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,I=d-b;if(this.isManualDecreasePlaybackInLive())return;let P=1;Math.abs(I)>S&&(P=1+Math.sign(I)*v),Sr(this.element,P)})),this.representationSubscription.add(this.bufferLength$.subscribe(d=>{let h=0;if(d){let m=(this.element?.currentTime??0)*1e3;h=Math.min(...this.bufferManagers.map(S=>S.getLiveSegmentsToLoadState(this.manifest)?.to??m))-m}this.liveLoadBufferLength$.getValue()!==h&&this.liveLoadBufferLength$.next(h)}));let c=0;this.representationSubscription.add((0,T.combine)({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe((0,T.throttle)(this.tuning.dash.liveUpdateInterval)).subscribe(async({liveLoadBufferLength:d,bufferLength:h})=>{if(!this.element||this.isUpdatingLive)return;let m=this.element.playbackRate,b=ei(this.manifestUrlString,2),S=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,v=Math.min(S,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*m),I=this.tuning.dashCmafLive.normalizedActualBufferOffset*m,P=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*m,x=isFinite(d)?d:h,C=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),V=S<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next(V);let O="none";if(C?O="active_low_latency":this.isLowLatency$.getValue()&&V?(this.bufferManagers.forEach(D=>D.proceedLowLatencyLive()),O="active_low_latency"):b!==0&&x<v?O="live_forward_buffering":x<v+P&&(O="live_with_target_offset"),isFinite(d)&&(c=d>c?d:c),O==="live_forward_buffering"||O==="live_with_target_offset"){let D=c-(v+I),N=this.normalizeLiveOffset(Math.trunc(b+D/m)),L=Math.abs(N-b),ee=0;!d||L<=this.tuning.dashCmafLive.offsetCalculationError?ee=b:N>0&&L>this.tuning.dashCmafLive.offsetCalculationError&&(ee=N),this.manifestUrlString=ye(this.manifestUrlString,ee,2)}(O==="live_with_target_offset"||O==="live_forward_buffering")&&(c=0,await this.updateLive())},d=>{this.error$.next({id:"updateLive",category:T.ErrorCategory.VIDEO_PIPELINE,thrown:d,message:"Failed to update live with subscription"})}))}let o=(0,T.merge)(...this.bufferManagers.map(c=>c.fullyBuffered$)).pipe((0,T.map)(()=>this.bufferManagers.every(c=>c.fullyBuffered$.getValue()))),l=(0,T.merge)(...this.bufferManagers.map(c=>c.onLastSegment$)).pipe((0,T.map)(()=>this.bufferManagers.some(c=>c.onLastSegment$.getValue()))),p=(0,T.combine)({allBuffersFull:o,someBufferEnded:l}).pipe((0,T.filterChanged)(),(0,T.map)(({allBuffersFull:c,someBufferEnded:d})=>c&&d),(0,T.filter)(c=>c));if(this.representationSubscription.add((0,T.merge)(this.forceEnded$,p).subscribe(()=>{if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(c=>!c.updating))try{this.source?.endOfStream()}catch(c){this.error$.next({id:"EndOfStream",category:T.ErrorCategory.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:c})}})),this.representationSubscription.add((0,T.merge)(...this.bufferManagers.map(c=>c.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.representationSubscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&(this.representationSubscription.add(this.audioBufferManager.playingRepresentation$.subscribe(this.currentAudioRepresentation$)),this.representationSubscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$))),this.liveTextManager&&this.representationSubscription.add(this.liveTextManager.currentRepresentation$.subscribe(this.currentLiveTextRepresentation$)),this.source.readyState!=="open"){let c=this.tuning.dash.sourceOpenTimeout>=0;yield new Promise(d=>{c&&(this.timeoutSourceOpenId=setTimeout(()=>{if(this.source?.readyState==="open"){d();return}this.error$.next({id:"OpenOfStream",category:T.ErrorCategory.VIDEO_PIPELINE,message:"Failed to open MediaSource",thrown:new Error("Timeout reject when wait sourceopen event"),traceAsLog:!0})},this.tuning.dash.sourceOpenTimeout)),this.source?.addEventListener("sourceopen",()=>{this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),d()},{once:!0})})}if(!this.isLive$.getValue()){let c=[this.manifest.duration??0,...(0,Vl.default)((0,Vl.default)([...this.manifest.streams.audio,...this.manifest.streams.video],d=>d.representations),d=>{let h=[];return d.duration&&h.push(d.duration),tt(d.segmentReference)&&d.segmentReference.totalSegmentsDurationMs&&h.push(d.segmentReference.totalSegmentsDurationMs),h})];this.source.duration=Math.max(...c)/1e3}this.audioBufferManager&&(0,T.isNonNullable)(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState("representations_ready"),this.tracer.log("initRepresentationsEnd")}.bind(this));this.tick=()=>{if(!this.element||!this.videoBufferManager||this.source?.readyState!=="open")return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),this.audioBufferManager?.maintain(e),this.liveTextManager?.maintain(e),(this.videoBufferManager.gaps.length||this.audioBufferManager?.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=(0,T.interval)(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),t=>{this.error$.next({id:"GapWatchdog",category:T.ErrorCategory.WTF,message:"Error handling gaps",thrown:t})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name),this.forceVideoCodec=e.forceVideoCodec,this.fetcher=new En({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer,useEnableSubtitlesParam:e.tuning.useEnableSubtitlesParam}),this.subscription.add(this.fetcher.recoverableError$.subscribe(this.fetcherRecoverableError$)),this.subscription.add(this.fetcher.error$.subscribe(this.fetcherError$)),this.subscription.add(this.fetcher.manifestRequested$.subscribe(this.manifestRequested$)),this.subscription.add(this.fetcher.firstBytesManifest$.subscribe(this.firstBytesManifest$)),this.subscription.add(this.fetcher.manifestReceived$.subscribe(this.manifestReceived$)),this.subscription.add(this.fetcher.firstBytesRequested$.subscribe(this.firstBytesRequested$)),this.subscription.add(this.fetcher.firstBytesReceived$.subscribe(this.firstBytesReceived$)),this.subscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.subscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.liveBuffer=jt.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.bufferEstimator}),this.initTracerSubscription()}setSmartRepresentationSwitch(e){this.bufferManagers.forEach(t=>t.setSmartRepresentationSwitch(e))}async seekLive(e){(0,T.assertNonNullable)(this.element),this.updateManifestUrlWithTimeOffset(e),this.manifest=await this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,await this.updateLiveBuffersFromManifest(this.manifest))}updateManifestUrlWithTimeOffset(e){let t=this.liveStreamStatus$.getValue()!=="active"?(0,T.now)()-this.liveStreamEndTimestamp:0,i=this.normalizeLiveOffset(e+t);this.isActiveLive$.next(i===0),this.manifestUrlString=ye(this.manifestUrlString,i,2)}async updateLiveBuffersFromManifest(e){await this.videoBufferManager?.seekLive(e.streams.video),await this.audioBufferManager?.seekLive(e.streams.audio),this.liveTextManager?.seekLive(e.streams.text)}stopStallWatchdogSubscription(){this.stallWatchdogSubscription?.unsubscribe(),this.currentStallDuration$.next(0)}initBuffer(){(0,T.assertNonNullable)(this.element),this.state$.setState("running"),this.subscription.add((0,T.merge)(...i$.map(e=>(0,T.fromEvent)(this.element,e)),(0,T.fromEvent)(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:T.ErrorCategory.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add((0,T.fromEvent)(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add((0,T.fromEvent)(this.element,"waiting").subscribe(()=>{this.tuning.dash.useVideoElementWaitingCurrentTimeReassign&&this.element&&this.element.readyState===2&&!this.element.seeking&&Ce(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{let{keepSilentStallWatchdogWhenNotActive:t}=this.tuning.dashCmafLive,{crashOnStallTimeout:i,crashOnStallTWithoutDataTimeout:r,liveStallReinitInterval:s,stallWatchdogInterval:n}=this.tuning.dash,u=this.isLive$.getValue(),l=this.liveStreamStatus$.getValue()==="active";if(!this.element||this.source?.readyState!=="open")return;let p=this.currentStallDuration$.getValue();p+=n,this.currentStallDuration$.next(p);let c={timeInWaiting:p},d=(0,T.now)(),h=100,m=this.videoBufferManager?.lastDataObtainedTimestamp??0;this.videoLastDataObtainedTimestamp$.next(m);let b=this.audioBufferManager?.lastDataObtainedTimestamp??0,S=this.videoBufferManager?.getForwardBufferDuration()??0,v=this.audioBufferManager?.getForwardBufferDuration()??0,I=S<h&&d-m>r,P=this.audioBufferManager&&v<h&&d-b>r;if((!t||l)&&((I||P)&&p>r||p>=i))throw new Error(`Stall timeout exceeded: ${p} ms`);if(u&&p%s===0){let x=this.normalizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);!l&&t?(this.liveWasInterrupted=!0,this.updateManifestUrlWithTimeOffset(x),this.updateManifest()):this.seekLive(x).catch(C=>{this.error$.next({id:"stallIntervalCallback",category:T.ErrorCategory.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:C})}),c.liveLastOffset=x}else{let x=this.element.currentTime*1e3;this.videoBufferManager?.maintain(x),this.audioBufferManager?.maintain(x),c.position=x}this.tracer.log("stallIntervalCallback",(0,T.flattenObject)(c))};this.stallWatchdogSubscription&&(this.stallWatchdogSubscription.unsubscribe(),this.subscriptionRemovable.remove(this.stallWatchdogSubscription)),this.stallWatchdogSubscription=(0,T.interval)(this.tuning.dash.stallWatchdogInterval).subscribe(e,t=>{this.error$.next({id:"StallWatchdogCallback",category:T.ErrorCategory.NETWORK,message:"Can't restore DASH after stall.",thrown:t})}),this.subscriptionRemovable.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t,i=!1){let r={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return this.tuning.useNewSwitchTo?this.currentStallDuration$.getValue()>0?r?.switchToWithPreviousAbort(t,i):r?.switchTo(t,i):r?.switchToOld(t,i)}async seek(e,t){(0,T.assertNonNullable)(this.element),(0,T.assertNonNullable)(this.videoBufferManager);let i;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?i=e:i=Math.max(this.videoBufferManager.findSegmentStartTime(e)??e,this.audioBufferManager?.findSegmentStartTime(e)??e),this.warmUpMediaSourceIfNeeded(i),Ce(this.element.buffered,i)||await Promise.all([this.videoBufferManager.abort(),this.audioBufferManager?.abort()]),!((0,T.isNullable)(this.element)||(0,T.isNullable)(this.videoBufferManager))&&(this.videoBufferManager.maintain(i),this.audioBufferManager?.maintain(i),this.element.currentTime=i/1e3,this.tracer.log("seek",(0,T.flattenObject)({requestedPosition:e,forcePrecise:t,position:i})))}warmUpMediaSourceIfNeeded(e=this.element?.currentTime){(0,T.isNonNullable)(this.element)&&(0,T.isNonNullable)(this.source)&&(0,T.isNonNullable)(e)&&this.source?.readyState==="ended"&&this.element.duration*1e3-e>this.tuning.dash.seekBiasInTheEnd&&this.bufferManagers.forEach(t=>t.warmUpMediaSource())}get isStreamEnded(){return this.source?.readyState==="ended"}stop(){this.tracer.log("stop"),this.element?.querySelectorAll("source").forEach(e=>{URL.revokeObjectURL(e.src),e.remove()}),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),this.videoBufferManager?.destroy(),this.videoBufferManager=null,this.audioBufferManager?.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getStreams(){return this.manifest?.streams}getCodecs(){return this.manifest?.codecs}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){this.subscription.unsubscribe(),this.subscriptionRemovable.unsubscribe(),this.representationSubscription.unsubscribe(),this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),this.source?.readyState==="open"&&Array.from(this.source.sourceBuffers).every(e=>!e.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}initTracerSubscription(){let e=(0,T.getTraceSubscriptionMethod)(this.tracer.error.bind(this.tracer));this.subscription.add(this.error$.subscribe(e("error")))}isManualDecreasePlaybackInLive(){if(!this.element||!this.isLive$.getValue())return!1;let e=1-this.element.playbackRate;return Number(e.toFixed(2))>Number(this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup.toFixed(2))}normalizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}async updateLive(){this.isUpdatingLive=!0,this.manifest=await this.updateManifest(),this.manifest&&(this.bufferManagers.forEach(e=>e.updateLive(this.manifest)),this.liveTextManager?.updateLive(this.manifest)),this.isUpdatingLive=!1}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.getDebugBufferState();if(!e)return;let t=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),i={isJumpGapAfterSeekLive:this.isJumpGapAfterSeekLive,isActiveLowLatency:t,initialCurrentTime:this.element.currentTime},{usePersistentGaps:r}=this.tuning.dash;this.isJumpGapAfterSeekLive&&!t&&this.element.currentTime>e.to&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let s=this.element.currentTime*1e3,n=[],u=this.element.readyState===1?this.tuning.endGapTolerance:0;for(let o of this.bufferManagers)for(let l of o.gaps)(r&&l.persistent||o.playingRepresentation$.getValue()===l.representation)&&l.from-u<=s&&l.to+u>s&&(this.element.duration*1e3-l.to<this.tuning.endGapTolerance?n.push(1/0):n.push(l.to));if(n.length){let o=Math.max(...n)+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,o===1/0?this.forceEnded$.next():(this.element.currentTime=o/1e3,i={...i,gapEnds:n,jumpTo:o,resultCurrentTime:this.element.currentTime},this.tracer.log("jumpGap",(0,T.flattenObject)(i)))}}calculateDurationFromSegments(){return Math.max(this.videoBufferManager?.calculateDurationFromSegments()||0,this.audioBufferManager?.calculateDurationFromSegments()||0)}};var Cn=class{constructor(e,t){this.fov=e,this.orientation=t}};var Bn=class{constructor(e,t){this.rotating=!1;this.fading=!1;this.lastTickTS=0;this.lastCameraTurnTS=0;this.fadeStartSpeed=null;this.fadeTime=0;this.camera=e,this.options=t,this.rotationSpeed={x:0,y:0,z:0},this.fadeCorrection=1/(this.options.speedFadeTime/1e3)**2}turnCamera(e=0,t=0,i=0){this.pointCameraTo(this.camera.orientation.x+e,this.camera.orientation.y+t,this.camera.orientation.z+i)}pointCameraTo(e=0,t=0,i=0){t=this.limitCameraRotationY(t);let r=e-this.camera.orientation.x,s=t-this.camera.orientation.y,n=i-this.camera.orientation.z;this.camera.orientation.x=e,this.camera.orientation.y=t,this.camera.orientation.z=i,this.lastCameraTurn={x:r,y:s,z:n},this.lastCameraTurnTS=Date.now()}setRotationSpeed(e,t,i){this.rotationSpeed.x=e??this.rotationSpeed.x,this.rotationSpeed.y=t??this.rotationSpeed.y,this.rotationSpeed.z=i??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,i){this.setRotationSpeed(e,t,i),this.fadeStartSpeed={...this.rotationSpeed},this.fading=!0}stopFading(){this.fadeStartSpeed=null,this.fading=!0,this.fadeTime=0}limitCameraRotationY(e){return Math.max(-this.options.maxYawAngle,Math.min(e,this.options.maxYawAngle))}tick(e){if(!this.lastTickTS){this.lastTickTS=e,this.lastCameraTurnTS=Date.now();return}let t=e-this.lastTickTS,i=t/1e3;if(this.rotating)this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*i,this.rotationSpeed.y*this.options.rotationSpeedCorrection*i,this.rotationSpeed.z*this.options.rotationSpeedCorrection*i);else if(this.fading&&this.fadeStartSpeed){let r=-this.fadeCorrection*(this.fadeTime/1e3)**2+1;this.setRotationSpeed(this.fadeStartSpeed.x*r,this.fadeStartSpeed.y*r,this.fadeStartSpeed.z*r),r>0?this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*i,this.rotationSpeed.y*this.options.rotationSpeedCorrection*i,this.rotationSpeed.z*this.options.rotationSpeedCorrection*i):(this.stopRotation(!0),this.stopFading()),this.fadeTime=Math.min(this.fadeTime+t,this.options.speedFadeTime)}this.lastTickTS=e}};var jS=`attribute vec2 a_vertex;
125
125
  attribute vec2 a_texel;
126
126
 
127
127
  varying vec2 v_texel;
@@ -175,6 +175,6 @@ void main(void) {
175
175
  // sample using new coordinates
176
176
  gl_FragColor = texture2D(u_texture, tc);
177
177
  }
178
- `;var yr=class{constructor(e,t,i){this.videoInitialized=!1;this.active=!1;this.container=e,this.sourceVideoElement=t,this.params=i,this.canvas=this.createCanvas();let r=this.canvas.getContext("webgl");if(!r)throw new Error("Could not initialize WebGL context");this.gl=r,this.container.appendChild(this.canvas),this.camera=new Cn(this.params.fov,this.params.orientation),this.cameraRotationManager=new Bn(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"),i=this.gl.getAttribLocation(this.program,"a_texel"),r=this.gl.getUniformLocation(this.program,"u_texture"),s=this.gl.getUniformLocation(this.program,"u_focus");this.gl.enableVertexAttribArray(t),this.gl.enableVertexAttribArray(i),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(i,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(r,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(i),this.active&&requestAnimationFrame(this.renderFn)}createShader(e,t){let i=this.gl.createShader(t);if(!i)throw this.destroy(),new Error(`Could not create shader (${t})`);if(this.gl.shaderSource(i,e),this.gl.compileShader(i),!this.gl.getShaderParameter(i,this.gl.COMPILE_STATUS))throw this.destroy(),new Error("An error occurred while compiling the shader: "+this.gl.getShaderInfoLog(i));return i}createProgram(){let e=this.gl.createProgram();if(!e)throw this.destroy(),new Error("Could not create shader program");let t=this.createShader(jS,this.gl.VERTEX_SHADER),i=this.createShader(WS,this.gl.FRAGMENT_SHADER);if(this.gl.attachShader(e,t),this.gl.attachShader(e,i),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,i=1,r=this.frameHeight/(this.frameWidth/this.viewportWidth);return r>this.viewportHeight?t=this.viewportHeight/r:i=r/this.viewportHeight,this.gl.bindBuffer(this.gl.ARRAY_BUFFER,e),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-t,-i,t,-i,t,i,-t,i]),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,i=this.camera.fov.x/360/2,r=this.camera.fov.y/180/2,s=e-i,n=t-r,u=e+i,o=t-r,l=e+i,p=t+r,c=e-i,d=t+r;return[s,n,u,o,l,p,c,d]}updateTextureMappingBuffer(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([...this.calculateTexturePosition()]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}updateFrameSize(){this.frameWidth=this.sourceVideoElement.videoWidth,this.frameHeight=this.sourceVideoElement.videoHeight}createCanvas(){let e=document.createElement("canvas");return e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e}};var he=require("@vkontakte/videoplayer-shared");var Vn="stalls_manager_metrics",_l="stalls_manager_abr_params",QS="stalls_manager_default_tuning_abr_params",Ol=class{constructor(){this.isSeeked$=new he.ValueSubject(!1);this.isBuffering$=new he.ValueSubject(!1);this.maxQualityLimit=void 0;this.currentStallsCount=0;this.sumStallsDuration=0;this.lastStallDuration=0;this.providerStartWatchingTimestamp=0;this.lastUniqueVideoTrackSelectedTimestamp=0;this.predictedThroughputWithoutData=0;this.subscription=new he.Subscription;this.severeStallOccurred$=new he.ValueSubject(!1)}init(e){this.currentStallDuration$=e.currentStallDuration$,this.videoLastDataObtainedTimestamp$=e.videoLastDataObtainedTimestamp$,this.throughput$=e.throughput$,this.rtt$=e.rtt$,this.tuning=e.tuning,this.abrParams=e.abrParams,this.duration=e.duration,this.resetStoredAbrParamsIfNeeded(),this.subscribe(e)}get videoMaxQualityLimit(){return this.maxQualityLimit}get predictedThroughput(){return this.predictedThroughputWithoutData}get abrTuningParams(){let t=(this.tuning.ignoreDynamicAbrForShortVideo?this.tuning.enabled&&this.duration>this.tuning.minTvtToBeCounted:this.tuning.enabled)?this.getStoredData(_l):{};return{...this.abrParams,...t}}set lastVideoTrackSelected(e){this.lastUniqueVideoTrackSelected?.id!==e.id&&(this.lastUniqueVideoTrackSelected=e,this.lastUniqueVideoTrackSelectedTimestamp=(0,he.now)(),this.currentStallsCount=0)}destroy(){window.clearTimeout(this.qualityRestrictionTimer),this.subscription.unsubscribe(),this.currentStallDuration$.getValue()!==0&&this.updateStallData();let e=((0,he.now)()-this.providerStartWatchingTimestamp-this.sumStallsDuration)/1e3,t=this.sumStallsDuration;this.addStallInfoToHistory(e,t),this.updateStoredAbrParams()}resetStoredAbrParamsIfNeeded(){let{bitrateFactorAtEmptyBuffer:e,bitrateFactorAtFullBuffer:t,containerSizeFactor:i}={...this.getStoredData(QS)},{bitrateFactorAtEmptyBuffer:r,bitrateFactorAtFullBuffer:s,containerSizeFactor:n}={...this.abrParams};this.tuning.enabled&&e===r&&t===s&&i===n||(this.removeStoredData(_l),this.setStoredData(QS,{bitrateFactorAtEmptyBuffer:r,bitrateFactorAtFullBuffer:s,containerSizeFactor:n}))}updateStoredAbrParams(){let e=[],t=this.getStoredData(Vn,"[]");if(!this.tuning.enabled||t.length<this.tuning.stallsMetricsHistoryLength)return;let i=t.reduce((s,n)=>s+n.tvt,0);if(this.tuning.useTotalStallsDurationPerTvt){let n=t.reduce((u,o)=>u+o.stallsDuration,0)/i;e.push(this.calculateOptimalAbrParams(n,i))}if(this.tuning.useAverageStallsDurationPerTvt){let s=t.reduce((n,u)=>n+u.stallsDurationPerTvt,0)/t.length;e.push(this.calculateOptimalAbrParams(s,i))}this.tuning.useEmaStallsDurationPerTvt&&e.push(this.calculateOptimalAbrParams(t[t.length-1].stallsDurationPerTvtSmoothed,i));let r={bitrateFactorAtEmptyBuffer:Math.max(...e.map(s=>s.bitrateFactorAtEmptyBuffer)),bitrateFactorAtFullBuffer:Math.max(...e.map(s=>s.bitrateFactorAtFullBuffer)),containerSizeFactor:Math.min(...e.map(s=>s.containerSizeFactor))};this.setStoredData(Vn,[]),this.setStoredData(_l,r)}calculateOptimalAbrParams(e,t){let{targetStallsDurationPerTvt:i,deviationStallsDurationPerTvt:r,criticalStallsDurationPerTvt:s,abrAdjustingSpeed:n,significantTvt:u}=this.tuning,o=n*Math.min(t/u,1),l=this.abrTuningParams;return e<i-r?l={bitrateFactorAtEmptyBuffer:Math.max(l.bitrateFactorAtEmptyBuffer-o,this.abrParams.minBitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.max(l.bitrateFactorAtFullBuffer-o,this.abrParams.minBitrateFactorAtFullBuffer),containerSizeFactor:Math.min(l.containerSizeFactor+o,this.abrParams.maxContainerSizeFactor)}:e>i+r&&(l={bitrateFactorAtEmptyBuffer:Math.min(l.bitrateFactorAtEmptyBuffer+o,this.abrParams.maxBitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.min(l.bitrateFactorAtFullBuffer+o,this.abrParams.maxBitrateFactorAtFullBuffer),containerSizeFactor:Math.max(l.containerSizeFactor-o,this.abrParams.minContainerSizeFactor)}),e>s&&(l={bitrateFactorAtEmptyBuffer:Math.max(l.bitrateFactorAtEmptyBuffer,this.abrParams.bitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.max(l.bitrateFactorAtFullBuffer,this.abrParams.bitrateFactorAtFullBuffer),containerSizeFactor:Math.min(l.containerSizeFactor,this.abrParams.containerSizeFactor)}),l}getStoredData(e,t="{}"){return JSON.parse(he.safeStorage.get(e)??t)}setStoredData(e,t){he.safeStorage.set(e,JSON.stringify(t))}removeStoredData(e){he.safeStorage.remove(e)}addStallInfoToHistory(e,t){if(e<this.tuning.minTvtToBeCounted||e>this.tuning.maxTvtToBeCounted||e*1e3<t)return;let i=this.getStoredData(Vn,"[]"),r=t/e,s=i.length?Ht(i[i.length-1].stallsDurationPerTvtSmoothed,t/e,this.tuning.emaAlpha):r,n={tvt:e,stallsDuration:t,stallsDurationPerTvt:r,stallsDurationPerTvtSmoothed:s};i.push(n),i.length>this.tuning.stallsMetricsHistoryLength&&i.shift(),this.setStoredData(Vn,i)}updateStallData(){this.providerStartWatchingTimestamp&&!this.isSeeked$.getValue()&&(this.sumStallsDuration+=Math.min(this.lastStallDuration,this.tuning.maxPossibleStallDuration),this.currentStallsCount++)}subscribe(e){this.subscription.add(e.isSeeked$.subscribe(this.isSeeked$)),this.subscription.add(e.isBuffering$.subscribe(this.isBuffering$)),this.subscription.add(e.looped$.subscribe(t=>this.currentStallsCount=0)),this.subscription.add(e.playing$.pipe((0,he.once)()).subscribe(t=>this.providerStartWatchingTimestamp=(0,he.now)())),this.subscription.add(this.currentStallDuration$.pipe((0,he.filterChanged)()).subscribe(t=>{let{stallDurationNoDataBeforeQualityDecrease:i,stallCountBeforeQualityDecrease:r,resetQualityRestrictionTimeout:s,ignoreStallsOnSeek:n}=this.tuning;if((0,he.isNullable)(this.lastUniqueVideoTrackSelected)||n&&this.isSeeked$.getValue())return;let u=this.rtt$.getValue(),o=this.throughput$.getValue(),l=this.videoLastDataObtainedTimestamp$.getValue(),p=(0,he.now)(),c=r&&this.currentStallsCount>=r,d=i&&p-this.lastUniqueVideoTrackSelectedTimestamp>=i+u&&p-l>=i+u&&t>=i;(c||d)&&(this.severeStallOccurred$.next(!0),window.clearTimeout(this.qualityRestrictionTimer),this.maxQualityLimit=this.lastUniqueVideoTrackSelected.quality,(0,he.isNonNullable)(this.lastUniqueVideoTrackSelected.bitrate)&&o>this.lastUniqueVideoTrackSelected.bitrate&&(this.predictedThroughputWithoutData=this.lastUniqueVideoTrackSelected.bitrate)),!t&&(0,he.now)()-this.providerStartWatchingTimestamp>this.lastStallDuration&&(this.updateStallData(),this.severeStallOccurred$.next(!1),window.clearTimeout(this.qualityRestrictionTimer),this.qualityRestrictionTimer=window.setTimeout(()=>{this.maxQualityLimit=void 0,this.predictedThroughputWithoutData=0},s)),this.lastStallDuration=t}))}},_n=Ol;var Ge=require("@vkontakte/videoplayer-shared"),On=class{constructor(){this.subscription=new Ge.Subscription;this.pipSize$=new Ge.ValueSubject(void 0);this.videoSize$=new Ge.ValueSubject(void 0);this.elementSize$=new Ge.ValueSubject(void 0);this.pictureInPictureWindowRemoveEventListener=Ge.noop}connect({observableVideo:e,video:t}){let i=r=>{let s=r.target;this.pipSize$.next({width:s.width,height:s.height})};this.subscription.add((0,Ge.observeElementSize)(t).subscribe(this.videoSize$)).add(e.enterPip$.subscribe(({pictureInPictureWindow:r})=>{this.pipSize$.next({width:r.width,height:r.height}),r.addEventListener("resize",i),this.pictureInPictureWindowRemoveEventListener=()=>{r.removeEventListener("resize",i)}})).add(e.leavePip$.subscribe(()=>{this.pictureInPictureWindowRemoveEventListener()})).add((0,Ge.combine)({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe((0,Ge.map)(({videoSize:r,inPip:s,pipSize:n})=>s?n:r)).subscribe(this.elementSize$))}getValue(){return this.elementSize$.getValue()}subscribe(e,t){return this.elementSize$.subscribe(e,t)}getObservable(){return this.elementSize$}destroy(){this.pictureInPictureWindowRemoveEventListener(),this.subscription.unsubscribe()}};var ui=require("@vkontakte/videoplayer-shared");var Tr=({subscription:a,desiredState:e,videoElement$:t,observableVideo:i})=>{if(!j.browser.isSafari)return;let r=0,s=!1;a.add(e.volume.stateChangeStarted$.pipe((0,ui.map)(()=>{let n=e.volume.getTransition(),u=t.getValue();return!u||!n?!1:!n.to.muted&&u.muted}),(0,ui.filter)(n=>!!n),(0,ui.once)()).subscribe(()=>{r=performance.now(),s=!0})),a.add(i.playbackRateState$.pipe((0,ui.filter)(()=>s),(0,ui.once)()).subscribe(()=>{let n=t.getValue(),u=e.playbackRate.getState();n&&u!==n.playbackRate&&performance.now()-r<1e3&&(n.playbackRate=u)}))};var $i=class{constructor(e){this.subscription=new F.Subscription;this.videoState=new Z("stopped");this.observableVideo=null;this.droppedFramesManager=new lr;this.stallsManager=new _n;this.elementSizeManager=new On;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new ri;this.audioTrackSwitchHistory=new ri;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(r.state==="requested"&&i?.to!=="paused"&&e!=="stopped"&&t!=="stopped"&&this.seek(r.position,r.forcePrecise),t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.player.stop(),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"),B(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"),B(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="ready"&&B(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):t==="playing"&&this.video.paused?this.playIfAllowed():i?.to==="playing"&&B(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&B(this.params.desiredState.playbackState,"paused");return;default:return(0,F.assertNever)(e)}}};this.init3DScene=e=>{if(this.scene3D)return;this.scene3D=new yr(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:e.projectionData?.pose.yaw||0,y:e.projectionData?.pose.pitch||0,z:e.projectionData?.pose.roll||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});let t=this.elementSizeManager.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};this.textTracksManager=new ot(e.source.url),this.params=e,this.video=Ue(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(Me(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 Dn({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode,tracer:this.tracer,forceVideoCodec:this.params.forceVideoCodec}),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params;(0,F.isNullable)(this.observableVideo)&&(this.observableVideo=We(this.video),this.subscription.add(()=>this.observableVideo?.destroy()));let i=this.constructor.name,r=n=>{e.error$.next({id:i,category:F.ErrorCategory.WTF,message:`${i} internal logic error`,thrown:n})},s=(n,u)=>this.subscription.add(n.subscribe(u,r));return{output:e,desiredState:t,observableVideo:this.observableVideo,genericErrorListener:r,connect:s}}subscribe(){let{output:e,desiredState:t,observableVideo:i,genericErrorListener:r,connect:s}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe((0,F.filter)(c=>!!c.length),(0,F.once)()).subscribe(c=>{this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks:c})}));let n=this.params.desiredState.seekState.stateChangeEnded$.pipe((0,F.map)(c=>c.to.state!=="none"),(0,F.filterChanged)());this.stallsManager.init({isSeeked$:n,currentStallDuration$:this.player.currentStallDuration$,videoLastDataObtainedTimestamp$:this.player.videoLastDataObtainedTimestamp$,throughput$:this.params.dependencies.throughputEstimator.throughput$,rtt$:this.params.dependencies.throughputEstimator.rtt$,tuning:this.params.tuning.stallsManager,abrParams:this.params.tuning.autoTrackSelection,isBuffering$:i.isBuffering$,looped$:i.looped$,playing$:i.playing$,duration:this.video.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.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),s(i.loadedMetadata$,e.loadedMetadataEvent$),s(this.player.error$,e.error$),s(this.player.fetcherRecoverableError$,e.fetcherRecoverableError$),s(this.player.fetcherError$,e.fetcherError$),s(this.player.manifestRequested$,e.manifestRequested$),s(this.player.firstBytesManifest$,e.firstBytesManifest$),s(this.player.manifestReceived$,e.manifestReceived$),s(this.player.firstBytesRequested$,e.firstBytesRequested$),s(this.player.firstBytesReceived$,e.firstBytesReceived$),s(this.player.lastConnectionType$,e.httpConnectionType$),s(this.player.lastConnectionReused$,e.httpConnectionReused$),s(this.player.isLive$,e.isLive$),s(this.player.lastRequestFirstBytes$.pipe((0,F.filter)(F.isNonNullable),(0,F.once)()),e.firstBytesEvent$),s(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),s(this.videoState.stateChangeEnded$.pipe((0,F.map)(c=>c.to)),this.params.output.playbackState$),this.subscription.add(i.looped$.subscribe(()=>this.player.warmUpMediaSourceIfNeeded(),r)),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(Pt(this.video,t.isLooped,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),Tr({subscription:this.subscription,desiredState:t,videoElement$:this.params.output.element$,observableVideo:i}),this.subscription.add(je(this.video,t.volume,i.volumeState$,r)),this.subscription.add(nt(this.video,t.playbackRate,i.playbackRateState$,r)),this.elementSizeManager.connect({video:this.video,observableVideo:i}),s(ut(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),B(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),B(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.params.tuning.changePlaybackStateToPausedWhenEnded&&this.subscription.add(i.ended$.subscribe(()=>{this.videoState.setState("paused"),B(t.playbackState,"paused")})),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(),h=this.player.getCodecs();if((0,F.assertNonNullable)(d,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let b=[];for(let S of d.audio){b.push(Rl(S));let v=[];for(let I of S.representations){let A=BS(I);v.push(A),this.audioTracksMap.set(A,{stream:S,representation:I})}this.audioStreamsMap.set(S,v)}this.params.output.availableAudioStreams$.next(b)}let m=[];for(let b of d.video){m.push($l(b));let S=[];for(let v of b.representations){let I=Na({...v,streamId:b.id});I&&(S.push(I),this.videoTracksMap.set(I,{stream:b,representation:v}))}this.videoStreamsMap.set(b,S)}this.params.output.availableVideoStreams$.next(m);for(let b of d.text)for(let S of b.representations){let v=VS(b,S);this.textTracksMap.set(v,{stream:b,representation:S})}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),h?.video&&this.params.output.availableVideoCodecs$.next(h.video),h?.audio&&this.params.output.availableAudioCodecs$.next(h.audio),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())},r));let u=(0,F.merge)(this.player.currentStallDuration$,this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,this.elementSizeManager.getObservable(),this.params.output.elementVisible$,this.droppedFramesManager.onDroopedVideoFramesLimit$,(0,F.fromEvent)(this.video,"progress")).pipe((0,F.filter)(()=>this.videoTracksMap.size>0)),{abrThrottle:o}=this.params.tuning.dash;o&&(u=u.pipe((0,F.throttle)(o))),this.subscription.add(u.subscribe(async()=>{let c=this.player.state$.getState(),d=this.player.state$.getTransition();if(c!=="manifest_ready"&&c!=="running"||d)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let h=this.selectVideoAudioRepresentations();if(!h)return;let[m,b]=h,S=[...this.videoTracksMap.keys()].find(I=>this.videoTracksMap.get(I)?.representation.id===m.id);(0,F.isNonNullable)(S)&&(this.stallsManager.lastVideoTrackSelected=S);let v=this.params.desiredState.autoVideoTrackLimits.getTransition();if(v&&this.params.output.autoVideoTrackLimits$.next(v.to),c==="manifest_ready")await this.player.initRepresentations(m.id,b?.id,this.params.sourceHls);else if(await this.player.switchRepresentation("video",m.id),b){let I=!!t.audioStream.getTransition();await this.player.switchRepresentation("audio",b.id,I)}},r)),this.subscription.add((0,F.combine)({videoState:this.videoState.stateChangeEnded$,autoVideoTrackState:(0,F.merge)((0,F.observableFrom)([t.autoVideoTrackSwitching.getState()]),t.autoVideoTrackSwitching.stateChangeEnded$.pipe((0,F.map)(c=>c.to)))}).pipe((0,F.map)(({videoState:c,autoVideoTrackState:d})=>c.to!=="stopped"&&d),(0,F.filterChanged)()).subscribe(c=>this.player.setSmartRepresentationSwitch(c))),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:c})=>{this.scene3D&&c&&this.scene3D.pointCameraTo(c.x,c.y)})),this.subscription.add(this.elementSizeManager.subscribe(c=>{this.scene3D&&c&&this.scene3D.setViewportSize(c.width,c.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe((0,F.filterChanged)()).subscribe(c=>{let d=[...this.videoTracksMap.entries()].find(([,{representation:v}])=>v.id===c);if(!d){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[h,{stream:m}]=d,b=this.params.desiredState.videoStream.getTransition();b&&b.to&&b.to.id===m.id&&this.params.desiredState.videoStream.setState(b.to),e.currentVideoTrack$.next(h),e.currentVideoStream$.next($l(m));let S=this.player.calculateDurationFromSegments();S&&this.params.output.duration$.next(S/1e3)},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe((0,F.filterChanged)()).subscribe(c=>{let d=[...this.audioTracksMap.entries()].find(([,{representation:S}])=>S.id===c);if(!d){e.currentAudioStream$.next(void 0);return}let[h,{stream:m}]=d,b=this.params.desiredState.audioStream.getTransition();b&&b.to&&b.to.id===m.id&&this.params.desiredState.audioStream.setState(b.to),e.currentAudioStream$.next(Rl(m))},r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(c=>{if(c?.is3dVideo&&this.params.tuning.spherical?.enabled)try{this.init3DScene(c),e.is3DVideo$.next(!0)}catch(d){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${d}`})}else this.destroy3DScene(),this.params.tuning.spherical?.enabled&&e.is3DVideo$.next(!1)},r)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,r)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,r)),this.textTracksManager.connect(this.video,t,e);let l=t.playbackState.stateChangeStarted$.pipe((0,F.map)(({to:c})=>c==="ready"),(0,F.filterChanged)());this.subscription.add((0,F.merge)(l,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,(0,F.observableFrom)(["init"])).subscribe(()=>{let c=t.autoVideoTrackSwitching.getState(),h=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:c?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(h)})),this.subscription.add((0,F.merge)(l,this.player.state$.stateChangeEnded$,(0,F.observableFrom)(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let p=(0,F.merge)(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,F.observableFrom)(["init"])).pipe((0,F.debounce)(0));this.subscription.add(p.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?aa:ra,t=this.params.tuning.useNewAutoSelectVideoTrack?cn:ln,i=this.params.tuning.useNewAutoSelectVideoTrack?Rt:un,{desiredState:r,output:s}=this.params,n=r.autoVideoTrackSwitching.getState(),u=r.videoTrack.getState()?.id,o=[...this.videoTracksMap.keys()].find(({id:D})=>D===u),l=s.currentVideoTrack$.getValue(),p=r.videoStream.getState()??(o&&this.videoTracksMap.get(o)?.stream)??this.videoStreamsMap.size===1?this.videoStreamsMap.keys().next().value:void 0;if(!p)return;let c=[...this.videoStreamsMap.keys()].find(({id:D})=>D===p.id),d=c&&this.videoStreamsMap.get(c);if(!d)return;let h=De(this.video.buffered,this.video.currentTime*1e3),m;this.player.isActiveLive$.getValue()?m=this.player.isLowLatency$.getValue()?this.params.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.params.tuning.dashCmafLive.normalizedLiveMinBufferSize:this.player.isLive$.getValue()?m=this.params.tuning.dashCmafLive.normalizedTargetMinBufferSize:m=n?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;let b=(this.video.duration*1e3||1/0)-this.video.currentTime*1e3,S=Math.min(h/Math.min(m,b||1/0),1),v=r.audioStream.getState()??(this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0),I=[...this.audioStreamsMap.keys()].find(({id:D})=>D===v?.id)??this.audioStreamsMap.keys().next().value,A=0;if(I){if(o&&!n){let D=e(o,d,this.audioStreamsMap.get(I)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);A=Math.max(A,D?.bitrate??-1/0)}if(l){let D=e(l,d,this.audioStreamsMap.get(I)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);A=Math.max(A,D?.bitrate??-1/0)}}let x=o;(n||!x)&&(x=i(d,{container:this.elementSizeManager.getValue(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.stallsManager.abrTuningParams,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:A,forwardBufferHealth:S,current:l,visible:this.params.output.elementVisible$.getValue(),history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,stallsVideoMaxQualityLimit:this.stallsManager.videoMaxQualityLimit,stallsPredictedThroughput:this.stallsManager.predictedThroughput,abrLogger:this.params.dependencies.abrLogger}));let C=I&&t(x,d,this.audioStreamsMap.get(I)??[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.stallsManager.abrTuningParams,forwardBufferHealth:S,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),V=this.videoTracksMap.get(x)?.representation,O=C&&this.audioTracksMap.get(C)?.representation;if(V&&O)return[V,O];if(V&&!O&&this.audioTracksMap.size===0)return[V,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){Qe(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),B(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:F.ErrorCategory.DOM,thrown:e}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.stallsManager.destroy(),this.elementSizeManager.destroy(),this.destroy3DScene(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),this.params.output.currentVideoStream$.next(void 0),He(this.video),this.tracer.end()}};var Wa=class extends $i{subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();i(t.timeUpdate$,e.position$),i(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}};var ce=require("@vkontakte/videoplayer-shared");var Qa=class extends $i{constructor(e){super(e),this.textTracksManager.destroy()}subscribe(){super.subscribe();let e=!1,t=-1,{output:i,observableVideo:r,desiredState:s,connect:n}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canPlayLiveTailBuffer$.next(!0),n(r.timeUpdate$,i.liveBufferTime$),n(this.player.liveSeekableDuration$,i.duration$),n(this.player.liveLatency$,i.liveLatency$);let u=new ce.ValueSubject(1);n(r.playbackRateState$,u),this.params.tuning.dashCmafLive.catchupLiveForMutedInactiveTab&&this.subscription.add(i.elementVisible$.pipe((0,ce.filterChanged)()).subscribe(o=>{let l=i.position$.getValue(),p=i.volume$.getValue(),c=!p.volume||p.muted;!o&&!l&&c?e=!0:o&&e&&(this.seek(0),e=!1)})),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(s.isLowLatency.stateChangeEnded$.pipe((0,ce.map)(o=>o.to)).subscribe(this.player.isLowLatency$)).add((0,ce.combine)({liveBufferTime:i.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe((0,ce.map)(({liveBufferTime:o,liveAvailabilityStartTime:l})=>o&&l?o+l:void 0)).subscribe(i.liveTime$)).add((0,ce.combine)({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:(0,ce.merge)(r.playbackRateState$,new ce.ValueSubject(1))}).pipe((0,ce.filter)(({liveStreamStatus:o,liveDuration:l})=>o==="active"&&!!l)).subscribe(({liveDuration:o,playbackRate:l})=>{let p=i.liveBufferTime$.getValue(),c=i.position$.getValue(),{playbackCatchupSpeedup:d}=this.params.tuning.dashCmafLive.lowLatency;c||l<1-d||this.video.paused||(0,ce.isNullable)(p)||(t=o-p)})).add((0,ce.combine)({time:i.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:(0,ce.merge)(r.playbackRateState$,new ce.ValueSubject(1))}).pipe((0,ce.filterChanged)((o,l)=>this.player.liveStreamStatus$.getValue()==="active"?o.liveDuration===l.liveDuration:o.time===l.time)).subscribe(({time:o,liveDuration:l,playbackRate:p})=>{let c=i.position$.getValue(),{playbackCatchupSpeedup:d}=this.params.tuning.dashCmafLive.lowLatency;if(!c&&!this.video.paused&&p>=1-d||(0,ce.isNullable)(o)||(0,ce.isNullable)(l))return;let h=-1*(l-o-t);i.position$.next(Math.min(h,0))})).add(this.player.currentLiveTextRepresentation$.subscribe(o=>{if(o){let l=_S(o);this.params.output.availableTextTracks$.next([l])}})),this.params.tuning.dashCmafLive.externalStopControl||this.subscription.add(this.player.liveStreamStatus$.pipe((0,ce.filter)(o=>(0,ce.isNonNullable)(o))).subscribe(o=>i.isLiveEnded$.next(o==="unpublished"&&i.position$.getValue()===0)))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,i=Math.trunc(t/1e3<=Math.abs(this.params.output.duration$.getValue())?t:0);this.player.seekLive(i).then(()=>{this.params.output.position$.next(e/1e3)})}};var H=require("@vkontakte/videoplayer-shared");var iv=Q(Oe(),1),Wl=Q(da(),1);var y=require("@vkontakte/videoplayer-shared");var Hn=Q(Oe(),1),Mi=Q(gt(),1),jn=Q(da(),1);var ev=Q(zs(),1);var li=require("@vkontakte/videoplayer-shared");var o$=18,GS=!1;try{GS=j.browser.isSafari&&!!j.browser.safariVersion&&j.browser.safariVersion<=o$}catch(a){console.error(a)}var Fl=class{constructor(e){this.bufferFull$=new li.Subject;this.error$=new li.Subject;this.queue=[];this.currentTask=null;this.destroyed=!1;this.abortRequested=!1;this.completeTask=()=>{try{if(this.currentTask){let e=this.currentTask.signal?.aborted;this.currentTask.callback(!e),this.currentTask=null}this.queue.length&&this.pull()}catch(e){this.error$.next({id:"BufferTaskQueueUnknown",category:li.ErrorCategory.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:e})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(i=>{let r={operation:"append",data:e,signal:t,callback:i};this.queue.push(r),this.pull()})}async remove(e,t,i){return i&&i.aborted?!1:new Promise(r=>{let s={operation:"remove",from:e,to:t,signal:i,callback:r};this.queue.unshift(s),this.pull()})}async abort(e){return new Promise(t=>{let i,r=s=>{this.abortRequested=!1,t(s)};GS&&e?i={operation:"safariAbort",init:e,callback:r}:i={operation:"abort",callback:r};for(let{callback:s}of this.queue)s(!1);this.abortRequested=!0,i&&(this.queue=[i]),this.pull()})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){if((this.buffer.updating||this.currentTask||this.destroyed)&&!this.abortRequested)return;let e=this.queue.shift();if(!e)return;if(e.signal?.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(r){r instanceof DOMException&&r.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):r instanceof DOMException&&r.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:li.ErrorCategory.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:r}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){let{operation:t}=e;switch(t){case"append":this.buffer.appendBuffer(e.data);break;case"remove":this.buffer.remove(e.from/1e3,e.to/1e3);break;case"abort":this.buffer.abort();break;case"safariAbort":{this.buffer.abort(),this.buffer.appendBuffer(e.init);break}default:(0,li.assertNever)(t)}}},zS=Fl;var k=require("@vkontakte/videoplayer-shared");var Nl=Q(gt(),1);var Fn=require("@vkontakte/videoplayer-shared"),Ga=({id:a,width:e,height:t,bitrate:i,fps:r,quality:s,streamId:n})=>{let u=(s?ii(s):void 0)??(0,Fn.videoSizeToQuality)({width:e,height:t});return u&&{id:a,quality:u,bitrate:i,size:{width:e,height:t},fps:r,streamId:n}},YS=({id:a,bitrate:e})=>({id:a,bitrate:e}),KS=({language:a,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:a,label:e}),XS=({language:a,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:a,label:e}),ql=({id:a,language:e,label:t,codecs:i,isDefault:r})=>({id:a,language:e,label:t,codec:(0,Nl.default)(i.split("."),0),isDefault:r}),Ul=({id:a,language:e,label:t,hdr:i,codecs:r})=>({id:a,language:e,hdr:i,label:t,codec:(0,Nl.default)(r.split("."),0)}),Hl=a=>"url"in a,it=a=>a.type==="template";var JS=a=>{a.sort((t,i)=>t.from-i.from);let e=[a[0]];for(let t=1;t<a.length;t++){let{from:i,to:r}=a[t],s=e[e.length-1];s.to>=i?s.to=Math.max(s.to,r):e.push(a[t])}return e},Li=(a,e)=>{for(let t of a)if(e(t))return t;return null},ZS=a=>{let e=!1,t=(0,Fn.throttleFn)(()=>{e=!0},a);return()=>{try{return t(),e}finally{e=!1}}};var Un=require("@vkontakte/videoplayer-shared");var Nn=a=>{let e=[];for(let t=0;t<a.length;t++){let i=Math.floor(a.start(t)*1e3),r=Math.ceil(a.end(t)*1e3);e.push(i,r)}return e};var qn=class{constructor(e,t){this.lastUpdateTs=0;this.lastCallTs=0;this.prevRanges=[];this.subscription=new Un.Subscription;this.mediaSource=e,this.sourceBuffer=t,this.subscription.add((0,Un.fromEvent)(this.sourceBuffer,"updateend").subscribe(()=>this.updateend()))}updateend(){if(!X(this.mediaSource,this.sourceBuffer))return;let{prevRanges:e}=this,t=Nn(this.sourceBuffer.buffered);this.prevRanges=t,this.isRangesRemoved(e,t)&&(this.lastUpdateTs=Date.now())}isRangesRemoved(e,t){if(e.length!==t.length)return!0;for(let i=0;i<e.length;i+=2){let r=e[i],s=e[i+1],n=t[i],u=t[i+1];if(n>r||u<s)return!0}return!1}wasUpdated(){let{lastCallTs:e,lastUpdateTs:t}=this;return this.lastCallTs=Date.now(),e<=t}destroy(){this.subscription.unsubscribe()}};var za=class{constructor(e,t,i,{fetcher:r,tuning:s,getCurrentPosition:n,isActiveLowLatency:u,compatibilityMode:o=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new k.ValueSubject(0);this.currentLowLatencySegmentLength$=new k.ValueSubject(0);this.currentSegmentLength$=new k.ValueSubject(0);this.onLastSegment$=new k.ValueSubject(!1);this.fullyBuffered$=new k.ValueSubject(!1);this.playingRepresentation$=new k.ValueSubject(void 0);this.playingRepresentationInit$=new k.ValueSubject(void 0);this.error$=new k.Subject;this.gaps=[];this.subscription=new k.Subscription;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new ue;this.switchAbortController=new ue;this.destroyAbortController=new ue;this.useSmartRepresentationSwitch=!1;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.sourceBufferBufferedDiff=null;this.startWith=(0,k.abortable)(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);(0,k.assertNonNullable)(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new zS(this.sourceBuffer),this.sourceBufferBufferedDiff=new qn(this.mediaSource,this.sourceBuffer),this.subscription.add((0,k.fromEvent)(this.sourceBuffer,"updateend").subscribe(()=>{this.maintain()})),this.subscription.add((0,k.fromEvent)(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:k.ErrorCategory.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let u=this.getCurrentPosition();if(!this.sourceBuffer||!u||!X(this.mediaSource,this.sourceBuffer))return;let o=Math.min(this.bufferLimit,hr(this.sourceBuffer.buffered)*.8);this.bufferLimit=o;let l=De(this.sourceBuffer.buffered,u),p=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(u,n*2,l<p).catch(c=>{this.handleAsyncError(c,"pruneBuffer")})})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(n=>this.error$.next(n))),yield this.loadInit(t,"high",!0);let i=this.initData.get(t.id),r=this.segments.get(t.id),s=this.parsedInitData.get(t.id);(0,k.assertNonNullable)(i,"No init buffer for starting representation"),(0,k.assertNonNullable)(r,"No segments for starting representation"),i instanceof ArrayBuffer&&(this.searchGaps(r,t),yield this.sourceBufferTaskQueue.append(i,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(s))}.bind(this));this.switchTo=(0,k.abortable)(this.destroyAbortController.signal,async function*(e,t=!1){if(!X(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);(0,k.assertNonNullable)(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if((0,k.isNullable)(s)||(0,k.isNullable)(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),(0,k.assertNonNullable)(r,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!X(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer();else{let n=this.getCurrentPosition();(0,k.isNonNullable)(n)&&!this.isLive&&(this.bufferLimit=1/0,await this.pruneBuffer(n,1/0,!0)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}this.maintain()}}.bind(this));this.switchToOld=(0,k.abortable)(this.destroyAbortController.signal,async function*(e,t=!1){if(!X(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);(0,k.assertNonNullable)(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if((0,k.isNullable)(s)||(0,k.isNullable)(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),(0,k.assertNonNullable)(r,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!X(this.mediaSource,this.sourceBuffer)))if(yield this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer(),this.maintain();else{let n=this.getCurrentPosition();(0,k.isNonNullable)(n)&&(this.isLive||(this.bufferLimit=1/0,await this.pruneBuffer(n,1/0,!0)),this.maintain(n)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}}.bind(this));this.seekLive=(0,k.abortable)(this.destroyAbortController.signal,async function*(e){let t=(0,jn.default)(e,o=>o.representations);if(!this.downloadingRepresentationId||!t.length)return;this.isSeekingLive=!0;for(let o of this.representations.keys()){let l=t.find(d=>d.id===o);l&&this.representations.set(o,l);let p=this.representations.get(o);if(!p||!it(p.segmentReference)){this.isSeekingLive=!1;return}let c=this.getActualLiveStartingSegments(p.segmentReference);this.segments.set(p.id,c)}let i=this.switchingToRepresentationId??this.downloadingRepresentationId,r=this.representations.get(i);(0,k.assertNonNullable)(r,`Representation not found by id ${i}`);let s=this.segments.get(i);(0,k.assertNonNullable)(s,"No segments for starting representation");let n=this.initData.get(i);if((0,k.assertNonNullable)(n,"No init buffer for starting representation"),!(n instanceof ArrayBuffer)){this.isSeekingLive=!1;return}let u=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,yield this.abort(),u&&(yield this.sourceBufferTaskQueue.remove(u.from*1e3,u.to*1e3,this.destroyAbortController.signal)),this.searchGaps(s,r),yield this.sourceBufferTaskQueue.append(n,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this));this.fetcher=r,this.tuning=s,this.compatibilityMode=o,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=u,this.isLive=!!l?.live,this.baseUrls=l?.baseUrls??[],this.initData=new Map(i.map(p=>[p.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(i.map(p=>[p.id,p])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}switchToWithPreviousAbort(e,t=!1){!X(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new ue,(0,k.abortable)(this.switchAbortController.signal,async function*(i,r=!1){this.switchingToRepresentationId=i;let s=this.representations.get(i);(0,k.assertNonNullable)(s,`No such representation ${i}`);let n=this.segments.get(i),u=this.initData.get(i);if((0,k.isNullable)(u)||(0,k.isNullable)(n)?yield this.loadInit(s,"high",!1):u instanceof Promise&&(yield u),n=this.segments.get(i),(0,k.assertNonNullable)(n,"No segments for starting representation"),u=this.initData.get(i),!(!(u instanceof ArrayBuffer)||!this.sourceBuffer||!X(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(u,this.downloadAbortController.signal),r)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=i,yield this.dropBuffer();else{let o=this.getCurrentPosition();(0,k.isNonNullable)(o)&&!this.isLive&&(this.bufferLimit=this.forwardBufferTarget,yield this.pruneBuffer(o,1/0,!0)),this.downloadingRepresentationId=i,this.switchingToRepresentationId=void 0}this.maintain()}}.bind(this))(e,t))}warmUpMediaSource(){!(0,k.isNullable)(this.sourceBuffer)&&!this.sourceBuffer.updating&&(this.sourceBuffer.mode="segments")}async abort(){for(let e of this.activeSegments)this.abortSegment(e.segment);return this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new ue,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if((0,k.isNullable)(e)||(0,k.isNullable)(this.downloadingRepresentationId)||(0,k.isNullable)(this.playingRepresentationId)||(0,k.isNullable)(this.sourceBuffer)||!X(this.mediaSource,this.sourceBuffer)||(0,k.isNonNullable)(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.representations.get(this.playingRepresentationId),r=this.segments.get(this.downloadingRepresentationId),s=this.segments.get(this.playingRepresentationId);if((0,k.assertNonNullable)(t,`No such representation ${this.downloadingRepresentationId}`),(0,k.assertNonNullable)(i,`No such representation ${this.playingRepresentationId}`),(0,k.isNullable)(r)||(0,k.isNullable)(s))return;let n=r.find(d=>e>=d.time.from&&e<d.time.to);(0,k.isNonNullable)(n)&&isFinite(n.time.from)&&isFinite(n.time.to)&&this.currentSegmentLength$.next(n?.time.to-n.time.from);let u=e,o=100;if(this.playingRepresentationId!==this.downloadingRepresentationId){let d=this.getForwardBufferDuration(e),h=Ga(i),m=Ga(t),b=this.useSmartRepresentationSwitch&&this.tuning.dash.useNewRepresentationSwitch&&this.tuning.dash.useSmartRepresentationSwitch&&(0,k.isNonNullable)(h)&&(0,k.isNonNullable)(m)&&(0,k.isHigher)(h.quality,m.quality),S=this.useSmartRepresentationSwitch&&this.tuning.dash.useNewRepresentationSwitch&&this.tuning.dash.useDelayedRepresentationSwitch;if(b||S?u+=Math.min(d,this.tuning.dash.representationSwitchForwardBufferGap):n&&n.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&d>=n.time.to-e+o&&(u=n?n.time.to+o:-1/0),this.tuning.dash.useNewRepresentationSwitch){let I=[...this.segments.entries()].map(([A,x])=>{let C=x.find(V=>e>=V.time.from&&e<V.time.to);return{representationId:A,status:C?.status}}).find(A=>A.status==="fed")?.representationId;I&&(this.playingRepresentationId=I,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)))}}if(isFinite(this.bufferLimit)&&hr(this.sourceBuffer.buffered)>=this.bufferLimit){let d=De(this.sourceBuffer.buffered,e),h=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,d<h).catch(m=>{this.handleAsyncError(m,"pruneBuffer")});return}let p=null;if(!this.activeSegments.size&&(p=this.selectForwardBufferSegments(r,t.segmentReference.type,u),p?.length)){let d="auto";if(this.tuning.dash.useFetchPriorityHints&&n)if((0,Hn.default)(p,n))d="high";else{let h=(0,Mi.default)(p,0);h&&h.time.from-n.time.to>=this.forwardBufferTarget/2&&(d="low")}this.loadSegments(p,t,d).catch(h=>{this.handleAsyncError(h,"loadSegments")})}(!this.preloadOnly&&!this.allInitsLoaded&&n&&n.status==="fed"&&!p?.length&&De(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let c=(0,Mi.default)(r,-1);!this.isLive&&c&&(this.fullyBuffered$.next(c.time.to-e-De(this.sourceBuffer.buffered,e)<o),this.onLastSegment$.next(e-c.time.from>0))}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}searchGaps(e,t){this.gaps=[];let i=0,r=this.isLive?this.liveInitialAdditionalOffset:0;for(let s of e)Math.trunc(s.time.from-i)>0&&this.gaps.push({representation:t.id,from:i,to:s.time.from+r,persistent:!0}),i=s.time.to;(0,k.isNonNullable)(t.duration)&&t.duration-i>0&&!this.isLive&&this.gaps.push({representation:t.id,from:i,to:t.duration,persistent:!0})}getActualLiveStartingSegments(e){let t=e.segments,i=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,r=[],s=0,n=t.length-1;do r.unshift(t[n]),s+=t[n].time.to-t[n].time.from,n--;while(s<i&&n>=0);return this.liveInitialAdditionalOffset=s-i,this.isActiveLowLatency()?[r[0]]:r}getLiveSegmentsToLoadState(e){let t=e?.streams[this.kind];if(!t)return;let i=(0,jn.default)(t,s=>s.representations).find(s=>s.id===this.downloadingRepresentationId);if(!i)return;let r=this.segments.get(i.id);if(r?.length)return{from:r[0].time.from,to:r[r.length-1].time.to}}updateLive(e){if(!e||[...this.segments.values()].every(i=>!i.length))return;let t=(0,jn.default)(e.streams[this.kind],i=>i.representations)??[];for(let i of t){if(!i||!it(i.segmentReference))return;let r=i.segmentReference.segments.map(l=>({...l,status:"none",size:void 0})),s=100,n=this.segments.get(i.id)??[],u=(0,Mi.default)(n,-1)?.time.to??0,o=r?.findIndex(l=>u>=l.time.from+s&&u<=l.time.to+s);if(o===-1){this.liveUpdateSegmentIndex=0;let l=this.getActualLiveStartingSegments(i.segmentReference);this.segments.set(i.id,l)}else{let l=r.slice(o+1);this.segments.set(i.id,[...n,...l])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;(0,k.assertNonNullable)(e);let t=this.segments.get(e);if(t?.length){let i=t[t.length-1];this.updateLowLatencyLiveIfNeeded(i)}}setSmartRepresentationSwitch(e){this.useSmartRepresentationSwitch=e}updateLowLatencyLiveIfNeeded(e){let t=0;for(let i of this.representations.values()){let r=i.segmentReference;if(!it(r))return;let s=this.segments.get(i.id);if(!s)continue;let n=s.find(o=>Math.floor(o.time.from)===Math.floor(e.time.from));if(n&&!isFinite(n.time.to)&&(n.time.to=e.time.to,t=n.time.to-n.time.from),!!!s.find(o=>Math.floor(o.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let o=Math.round(e.time.to*r.timescale/1e3).toString(10),l=vt(r.segmentTemplateUrl,{segmentTime:o});s.push({status:"none",time:{from:e.time.to,to:1/0},url:l})}}this.currentLowLatencySegmentLength$.next(t)}findSegmentStartTime(e){let t=this.switchingToRepresentationId??this.downloadingRepresentationId??this.playingRepresentationId;if(!t)return;let i=this.segments.get(t);return i?i.find(s=>s.time.from<=e&&s.time.to>=e)?.time.from??void 0:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),this.sourceBufferTaskQueue?.destroy(),this.sourceBufferBufferedDiff?.destroy(),this.gapDetectionIdleCallback&&Lt&&Lt(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&Lt&&Lt(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer)try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(e){if(!(e instanceof DOMException&&e.name==="NotFoundError"))throw e}this.sourceBuffer=null,this.downloadAbortController.abort(),this.switchAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,i){return this.checkEjectedSegments(),this.isLive?this.selectForwardBufferSegmentsLive(e,i):this.selectForwardBufferSegmentsRecord(e,t,i)}selectForwardBufferSegmentsLive(e,t){if(this.playingRepresentationId!==this.downloadingRepresentationId){let i=e.findIndex(r=>t>=r.time.from&&t<r.time.to);this.liveUpdateSegmentIndex=i}return this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):null}selectForwardBufferSegmentsRecord(e,t,i){let r=this.getForwardBufferDuration(i),s=e.findIndex(({status:d,time:{from:h,to:m}},b)=>{let S=h<=i&&m>=i,v=h>i||S||b===0&&i===0,I=Math.min(this.forwardBufferTarget,this.bufferLimit),A=this.preloadOnly&&h<=i+I||r<I&&m-h>=I||m<=i+I;return(d==="none"||d==="partially_ejected"&&v&&A&&this.sourceBuffer&&X(this.mediaSource,this.sourceBuffer)&&!(Ce(this.sourceBuffer.buffered,h)&&Ce(this.sourceBuffer.buffered,m)))&&v&&A});if(s===-1)return null;if(t!=="byteRange")return e.slice(s,s+1);let n=e,u=0,o=0,l=[],p=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,c=this.preloadOnly?this.forwardBufferTarget:0;for(let d=s;d<n.length&&(u<=p||o<=c);d++){let h=n[d];if(u+=h.byte.to+1-h.byte.from,o+=h.time.to+1-h.time.from,h.status==="none"||h.status==="partially_ejected")l.push(h);else break}return l}async loadSegments(e,t,i="auto"){it(t.segmentReference)?await this.loadTemplateSegment(e[0],t,i):await this.loadByteRangeSegments(e,t,i)}async loadTemplateSegment(e,t,i="auto"){e.status="downloading";let r={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(r);let{range:s,url:n,signal:u,onProgress:o,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&u&&(await(0,k.abortable)(u,async function*(){let p=(0,k.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>setTimeout(c,p))}.bind(this))(),u.aborted&&this.abortActiveSegments([e]));try{let p=await this.fetcher.fetch(n,{range:s,signal:u,onProgress:o,priority:i,isLowLatency:this.isActiveLowLatency(),bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation});if(this.lastDataObtainedTimestampMs=(0,k.now)(),!p)return;let c=new DataView(p),d=Mt(t.mime);if(!isFinite(r.segment.time.to)){let b=t.segmentReference.timescale;r.segment.time.to=d.getChunkEndTime(c,b)}o&&r.feedingBytes&&l?await Promise.all(l):await this.sourceBufferTaskQueue.append(c,u);let{serverDataReceivedTimestamp:h,serverDataPreparedTime:m}=d.getServerLatencyTimestamps(c);h&&m&&this.currentLiveSegmentServerLatency$.next(m-h),r.segment.status="downloaded",this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(p){this.abortActiveSegments([e]),Dt(p)||(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())it(t.segmentReference)?t.segmentReference.baseUrl=e:t.segmentReference.url=e}async loadByteRangeSegments(e,t,i="auto"){if(!e.length)return;for(let o of e)o.status="downloading",this.activeSegments.add({segment:o,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:r,url:s,signal:n,onProgress:u}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(await(0,k.abortable)(n,async function*(){let o=(0,k.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,o),(0,k.fromEvent)(window,"online").pipe((0,k.once)()).subscribe(()=>{l(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(s,{range:r,onProgress:u,signal:n,priority:i,bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation}),this.lastDataObtainedTimestampMs=(0,k.now)(),this.failedDownloads=0}catch(o){this.abortActiveSegments(e),Dt(o)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}prepareByteRangeFetchSegmentParams(e,t){if(it(t.segmentReference))throw new Error("Representation is not byte range type");let i=t.segmentReference.url,r={from:(0,Mi.default)(e,0).byte.from,to:(0,Mi.default)(e,-1).byte.to},{signal:s}=this.downloadAbortController;return{url:i,range:r,signal:s,onProgress:async(u,o)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=(0,k.now)(),await this.onSomeByteRangesDataLoaded({dataView:u,loaded:o,signal:s,onSegmentAppendFailed:()=>this.abort(),globalFrom:r?r.from:0,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:k.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!it(t.segmentReference))throw new Error("Representation is not template type");let i=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&i.searchParams.set("low-latency","yes");let r=i.toString(),{signal:s}=this.downloadAbortController,n=[],o=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(l,p)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=(0,k.now)();let c=this.onSomeTemplateDataLoaded({dataView:l,loaded:p,signal:s,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(c)}catch(c){this.error$.next({id:"SegmentFeeding",category:k.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:c})}}:void 0;return{url:r,signal:s,onProgress:o,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)(0,Hn.default)(e,t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:r,signal:s}){if(!this.activeSegments.size||!X(this.mediaSource,this.sourceBuffer))return;let n=this.representations.get(t);if(n)for(let u of this.activeSegments){let{segment:o}=u;if(u.representationId===t){if(s.aborted){r();continue}if(u.loadedBytes=i,u.loadedBytes>u.feedingBytes){let l=new DataView(e.buffer,e.byteOffset+u.feedingBytes,u.loadedBytes-u.feedingBytes),p=Mt(n.mime).parseFeedableSegmentChunk(l,this.isLive);p?.byteLength&&(o.status="partially_fed",u.feedingBytes+=p.byteLength,await this.sourceBufferTaskQueue.append(p),u.fedBytes+=p.byteLength)}}}}async onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:s,onSegmentAppendFailed:n}){if(!this.activeSegments.size||!X(this.mediaSource,this.sourceBuffer))return;let u=this.representations.get(t);if(u)for(let o of this.activeSegments){if(o.representationId!==t)continue;if(s.aborted){await n();continue}let{segment:l}=o,p=l.byte.from-i,c=l.byte.to-i,d=c-p+1,h=p<r,m=c<=r;if(h){if(l.status==="downloading"&&m){l.status="downloaded";let b=new DataView(e.buffer,e.byteOffset+p,d);await this.sourceBufferTaskQueue.append(b,s)&&!s.aborted?this.onSegmentFullyAppended(o,t):await n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(l.status==="downloading"||l.status==="partially_fed")&&(o.loadedBytes=Math.min(d,r-p),o.loadedBytes>o.feedingBytes)){let b=new DataView(e.buffer,e.byteOffset+p+o.feedingBytes,o.loadedBytes-o.feedingBytes),S=o.loadedBytes===d?b:Mt(u.mime).parseFeedableSegmentChunk(b);S?.byteLength&&(l.status="partially_fed",o.feedingBytes+=S.byteLength,await this.sourceBufferTaskQueue.append(S,s)&&!s.aborted?(o.fedBytes+=S.byteLength,o.fedBytes===d&&this.onSegmentFullyAppended(o,t)):await n())}}}}onSegmentFullyAppended(e,t){if(!((0,k.isNullable)(this.sourceBuffer)||!X(this.mediaSource,this.sourceBuffer))){!this.isLive&&j.browser.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(Ce(this.sourceBuffer.buffered,e.segment.time.from,100)&&Ce(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:k.ErrorCategory.VIDEO_PIPELINE,message:"Browser 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",Hl(e.segment)&&(e.segment.size=e.fedBytes);for(let i of this.representations.values()){if(i.id===t)continue;let r=this.segments.get(i.id);if(r)for(let s of 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")}this.isActiveLowLatency()&&this.updateLowLatencyLiveIfNeeded(e.segment),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,e.segment)}}abortSegment(e){e.status==="partially_fed"?e.status="partially_ejected":e.status!=="partially_ejected"&&(e.status="none");for(let t of this.activeSegments.values())if(t.segment===e){this.activeSegments.delete(t);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(let[r,s]of this.initData.entries()){let n=s instanceof Promise;t||=n,s===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let i=this.representations.get(e);i&&(this.initLoadIdleCallback=pr(()=>(0,ev.default)(this.loadInit(i,"low",!1),()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",i=!1){let r=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!i&&this.failedDownloads>0?(0,k.abortable)(this.destroyAbortController.signal,async function*(){let u=(0,k.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(o=>setTimeout(o,u))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,Mt(e.mime),r)).then(u=>{if(!u)return;let{init:o,dataView:l,segments:p}=u,c=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,c);let d=p;this.isLive&&it(e.segmentReference)&&(d=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,d),o&&this.parsedInitData.set(e.id,o)}).then(()=>this.failedDownloads=0,u=>{this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:k.ErrorCategory.WTF,message:"loadInit threw",thrown:u})});return this.initData.set(e.id,n),n}async dropBuffer(){for(let e of this.segments.values())for(let t of e)t.status="none";await this.pruneBuffer(0,1/0,!0)}async pruneBuffer(e,t,i=!1){if(!this.sourceBuffer||!X(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||(0,k.isNullable)(e))return!1;this.checkEjectedSegments();let r=[],s=0,n=u=>{if(s>=t)return;r.push({...u.time});let o=Hl(u)?u.size??0:u.byte.to-u.byte.from;s+=o};for(let u of this.segments.values())for(let o of u){let l=o.time.to<=e-this.tuning.dash.bufferPruningSafeZone,p=o.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(l||p)&&o.status==="fed"&&n(o)}for(let u=0;u<this.sourceBuffer.buffered.length;u++){let o=this.sourceBuffer.buffered.start(u)*1e3,l=this.sourceBuffer.buffered.end(u)*1e3,p=0;for(let c of this.segments.values())for(let d of c)(0,Hn.default)(["none","partially_ejected"],d.status)&&Math.round(d.time.from)<=Math.round(o)&&Math.round(d.time.to)>=Math.round(l)&&p++;if(p===this.segments.size){let c={time:{from:o,to:l},url:"",status:"none"};n(c)}}if(r.length&&i){let u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let o of this.segments.values())for(let l of o)l.time.from>=e+u&&l.status==="fed"&&n(l)}return r.length?(r=JS(r),(await Promise.all(r.map(o=>this.sourceBufferTaskQueue.remove(o.from,o.to)))).reduce((o,l)=>o||l,!1)):!1}async abortBuffer(){if(!this.sourceBuffer||!X(this.mediaSource,this.sourceBuffer))return!1;let e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;return this.sourceBufferTaskQueue.abort(t)}getDebugBufferState(){if(!(!this.sourceBuffer||!X(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}getBufferedTo(){return!this.sourceBuffer||!X(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length?null:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}getForwardBufferDuration(e=this.getCurrentPosition()){return!this.sourceBuffer||!X(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||(0,k.isNullable)(e)?0:De(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!this.sourceBuffer||!X(this.mediaSource,this.sourceBuffer))return;let{buffered:i}=this.sourceBuffer,r={representation:e,from:t.time.from,to:t.time.to,persistent:!1};for(let s=0;s<i.length;s++){let n=i.start(s)*1e3,u=i.end(s)*1e3;if(!(u<=t.time.from||n>=t.time.to)){if(n<=t.time.from&&u>=t.time.to){r=void 0;break}u>t.time.from&&u<t.time.to&&(r.from=u),n<t.time.to&&n>t.time.from&&(r.to=n)}}r&&r.to-r.from>1&&!this.gaps.some(s=>r&&s.from===r.from&&s.to===r.to)&&this.gaps.push(r)}detectGapsWhenIdle(e,t){if(this.gapDetectionIdleCallback||!this.sourceBuffer||!X(this.mediaSource,this.sourceBuffer))return;let{buffered:i}=this.sourceBuffer;this.gaps=this.gaps.filter(r=>{if(r.persistent)return!0;let s=Math.round(r.from),n=Math.round(r.to);for(let u=0;u<i.length;u++)if(s>=Math.round(i.start(u)*1e3)&&n<=Math.round(i.end(u)*1e3))return!1;return!0}),this.gapDetectionIdleCallback=pr(()=>{try{this.detectGaps(e,t)}catch(r){this.error$.next({id:"GapDetection",category:k.ErrorCategory.WTF,message:"detectGaps threw",thrown:r})}finally{this.gapDetectionIdleCallback=null}})}checkEjectedSegments(){if((0,k.isNullable)(this.sourceBuffer)||!X(this.mediaSource,this.sourceBuffer)||(0,k.isNullable)(this.playingRepresentationId)||this.sourceBufferBufferedDiff&&!this.sourceBufferBufferedDiff.wasUpdated())return;let e=Nn(this.sourceBuffer.buffered),t=100;for(let i of this.segments.values())for(let r of i){let{status:s}=r;if(s!=="fed"&&s!=="partially_ejected")continue;let n=Math.floor(r.time.from),u=Math.ceil(r.time.to),o=!1,l=0;for(let p=0;p<e.length;p+=2){let c=e[p],d=e[p+1];o||(o=c-t<=n&&d+t>=u),(n>=c&&n<d-t||u>c+t&&u<=d)&&(l+=1)}o||(l===1?r.status="partially_ejected":this.gaps.some(p=>p.from===r.time.from||p.to===r.time.to)?r.status="partially_ejected":r.status="none")}}handleAsyncError(e,t){this.error$.next({id:t,category:k.ErrorCategory.VIDEO_PIPELINE,thrown:e,message:"Something went wrong"})}calculateDurationFromSegments(){if(!this.playingRepresentationId)return 0;let e=this.segments.get(this.playingRepresentationId);return(e?(0,Mi.default)(e,-1)?.time.to:0)||0}};var z=require("@vkontakte/videoplayer-shared");var Qn=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:s=!1}){this.manifestRequested$=new z.Subject;this.firstBytesManifest$=new z.Subject;this.manifestReceived$=new z.Subject;this.firstBytesRequested$=new z.Subject;this.firstBytesReceived$=new z.Subject;this.lastConnectionType$=new z.ValueSubject(void 0);this.lastConnectionReused$=new z.ValueSubject(void 0);this.lastRequestFirstBytes$=new z.ValueSubject(void 0);this.recoverableError$=new z.Subject;this.error$=new z.Subject;this.abortAllController=new ue;this.subscription=new z.SubscriptionRemovable;this.fetchManifest=(0,z.abortable)(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=ni(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=Tn(i)),this.manifestRequested$.next();let r=yield this.doFetch(i,{signal:this.abortAllController.signal},"manifest").catch(Wn);return r?(t.log("success",(0,z.flattenObject)({url:i,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(r.headers),this.manifestReceived$.next(),r.text()):(t.error("error",(0,z.flattenObject)({url:i,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=(0,z.abortable)(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:i,onProgress:r,priority:s="auto",signal:n,measureThroughput:u=!0,isLowLatency:o=!1,bufferOptimisation:l=!1}={}){let p=e,c=new Headers,d=this.tracer.createComponentTracer("Fetch");if(i)switch(t){case 0:{c.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let R=new URL(p,location.href);R.searchParams.append("bytes",`${i.from}-${i.to}`),p=R.toString();break}default:(0,z.assertNever)(t)}this.requestQuic&&(p=ni(p));let h=this.abortAllController.signal,m;if(n){let R=new ue;if(m=(0,z.merge)((0,z.fromEvent)(this.abortAllController.signal,"abort"),(0,z.fromEvent)(n,"abort")).subscribe(()=>{try{R.abort()}catch(P){Wn(P)}}),this.subscription.add(m),this.abortAllController.signal.aborted||n.aborted)try{R.abort()}catch(P){Wn(P)}h=R.signal}let b=0,S=(0,z.now)();d.log("startRequest",(0,z.flattenObject)({url:p,priority:s,rangeMethod:t,range:i,isLowLatency:o,requestStartedAt:S})),this.firstBytesRequested$.next();let v=yield this.doFetch(p,{priority:s,headers:c,signal:h}),I=(0,z.now)();if(!v)return d.error("error",{message:"No response in request"}),d.end(),this.unsubscribeAbortSubscription(m),null;if(this.throughputEstimator?.addRawRtt(I-S),!v.ok||!v.body){this.unsubscribeAbortSubscription(m);let R=`Fetch error ${v.status}: ${v.statusText}`;return d.error("error",{message:R}),d.end(),Promise.reject(new Error(`Fetch error ${v.status}: ${v.statusText}`))}if(this.onHeadersReceived(v.headers),!r&&!u){this.unsubscribeAbortSubscription(m);let R=(0,z.now)(),P={requestStartedAt:S,requestEndedAt:R,duration:R-S};return d.log("endRequest",(0,z.flattenObject)(P)),d.end(),v.arrayBuffer()}let A=v.body;if(u){let R;[A,R]=v.body.tee(),this.throughputEstimator?.trackStream(R,o)}let x=A.getReader(),C,V=parseInt(v.headers.get("content-length")??"",10);Number.isFinite(V)&&(C=V),!C&&i&&(C=i.to-i.from+1);let O=C?new Uint8Array(C):new Uint8Array(0),D=!1,N=R=>{this.unsubscribeAbortSubscription(m),D=!0,Wn(R)},L=(0,z.abortable)(h,async function*({done:R,value:P}){if(b===0&&(this.lastRequestFirstBytes$.next((0,z.now)()-S),this.firstBytesReceived$.next()),h.aborted){this.unsubscribeAbortSubscription(m);return}if(!R&&P){if(l&&C)O.set(P,b),b+=P.byteLength;else{let te=new Uint8Array(O.length+P.length);te.set(O),te.set(P,O.length),O=te,b+=P.byteLength}r?.(new DataView(O.buffer),b),yield x?.read().then(L,N)}}.bind(this));yield x?.read().then(L,N),this.unsubscribeAbortSubscription(m);let ee=(0,z.now)(),W={failed:D,requestStartedAt:S,requestEndedAt:ee,duration:ee-S};return D?(d.error("endRequest",(0,z.flattenObject)(W)),d.end(),null):(d.log("endRequest",(0,z.flattenObject)(W)),d.end(),O.buffer)}.bind(this));this.fetchByteRangeRepresentation=(0,z.abortable)(this.abortAllController.signal,async function*(e,t,i){if(e.type!=="byteRange")return null;let{from:r,to:s}=e.initRange,n=r,u=s,o=!1,l,p;e.indexRange&&(l=e.indexRange.from,p=e.indexRange.to,o=s+1===l,o&&(n=Math.min(l,r),u=Math.max(p,s))),n=Math.min(n,0);let c=yield this.fetch(e.url,{range:{from:n,to:u},priority:i,measureThroughput:!1});if(!c)return null;let d=new DataView(c,r-n,s-n+1);if(!t.validateData(d))throw new Error("Invalid media file");let h=t.parseInit(d),m=e.indexRange??t.getIndexRange(h);if(!m)throw new ReferenceError("No way to load representation index");let b;if(o)b=new DataView(c,m.from-n,m.to-m.from+1);else{let v=yield this.fetch(e.url,{range:m,priority:i,measureThroughput:!1});if(!v)return null;b=new DataView(v)}let S=t.parseSegments(b,h,m);return{init:h,dataView:new DataView(c),segments:S}}.bind(this));this.fetchTemplateRepresentation=(0,z.abortable)(this.abortAllController.signal,async function*(e,t){if(e.type!=="template")return null;let i=new URL(e.initUrl,e.baseUrl).toString(),r=yield this.fetch(i,{priority:t,measureThroughput:!1});return r?{init:null,segments:e.segments.map(n=>({...n,status:"none",size:void 0})),dataView:new DataView(r)}:null}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=r,this.tracer=i.createComponentTracer("Fetcher"),this.useEnableSubtitlesParam=s}onHeadersReceived(e){let{type:t,reused:i}=yn(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}async fetchRepresentation(e,t,i="auto"){let{type:r}=e;switch(r){case"byteRange":return await this.fetchByteRangeRepresentation(e,t,i)??null;case"template":return await this.fetchTemplateRepresentation(e,i)??null;default:(0,z.assertNever)(r)}}destroy(){this.abortAllController.abort(),this.tracer.end(),this.subscription.unsubscribe()}async doFetch(e,t,i){let r=await lt(e,t);if(r.ok)return i==="manifest"&&this.firstBytesManifest$.next(),r;let s=await r.text(),n=parseInt(s);if(!isNaN(n))switch(n){case 1:this.recoverableError$.next({id:"VideoDataLinkExpiredError",message:"Video data links have expired",category:z.ErrorCategory.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:z.ErrorCategory.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:z.ErrorCategory.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:z.ErrorCategory.FATAL});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${n})`,category:z.ErrorCategory.FATAL})}}unsubscribeAbortSubscription(e){e&&(e.unsubscribe(),this.subscription.remove(e))}},Wn=a=>{if(!Dt(a))throw a};var Gn=require("@vkontakte/videoplayer-shared");var Ya=class a{constructor(e,t){this.currentRepresentation$=new Gn.ValueSubject(null);this.maxRepresentations=4;this.representationsCursor=0;this.representations=[];this.currentSegment=null;this.getCurrentPosition=t.getCurrentPosition,this.processStreams(e)}updateLive(e){this.processStreams(e?.streams.text)}seekLive(e){this.processStreams(e)}maintain(e=this.getCurrentPosition()){if(!(0,Gn.isNullable)(e))for(let t of this.representations)for(let i of t){let r=i.segmentReference,s=r.segments.length,n=r.segments[0].time.from,u=r.segments[s-1].time.to;if(e<n||e>u)continue;let o=r.segments.find(l=>l.time.from<=e&&l.time.to>=e);!o||this.currentSegment?.time.from===o.time.from&&this.currentSegment.time.to===o.time.to||(this.currentSegment=o,this.currentRepresentation$.next({...i,label:"Live Text",language:"ru",isAuto:!0,url:new URL(o.url,r.baseUrl).toString()}))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e??[]){let i=a.filterRepresentations(t.representations);if(i){this.representations[this.representationsCursor]=i,this.representationsCursor=(this.representationsCursor+1)%this.maxRepresentations;break}}}static isSupported(e){return!!e?.some(t=>a.filterRepresentations(t.representations))}static filterRepresentations(e){return e?.filter(t=>t.kind==="text"&&"segmentReference"in t&&it(t.segmentReference))}};var c$=["progress","play","seeked","stalled","waiting"],d$=["timeupdate","progress","loadeddata","playing","seeked"];var zn=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.bufferManagers=[];this.subscription=new y.Subscription;this.subscriptionRemovable=new y.SubscriptionRemovable;this.representationSubscription=new y.Subscription;this.state$=new Z("none");this.currentVideoRepresentation$=new y.ValueSubject(void 0);this.currentVideoRepresentationInit$=new y.ValueSubject(void 0);this.currentAudioRepresentation$=new y.ValueSubject(void 0);this.currentVideoSegmentLength$=new y.ValueSubject(0);this.currentAudioSegmentLength$=new y.ValueSubject(0);this.error$=new y.Subject;this.manifestRequested$=new y.Subject;this.firstBytesManifest$=new y.Subject;this.manifestReceived$=new y.Subject;this.firstBytesRequested$=new y.Subject;this.firstBytesReceived$=new y.Subject;this.lastConnectionType$=new y.ValueSubject(void 0);this.lastConnectionReused$=new y.ValueSubject(void 0);this.lastRequestFirstBytes$=new y.ValueSubject(void 0);this.currentLiveTextRepresentation$=new y.ValueSubject(null);this.isLive$=new y.ValueSubject(!1);this.isActiveLive$=new y.ValueSubject(!1);this.isLowLatency$=new y.ValueSubject(!1);this.liveDuration$=new y.ValueSubject(0);this.liveSeekableDuration$=new y.ValueSubject(0);this.liveAvailabilityStartTime$=new y.ValueSubject(0);this.liveStreamStatus$=new y.ValueSubject(void 0);this.bufferLength$=new y.ValueSubject(0);this.liveLatency$=new y.ValueSubject(void 0);this.liveLoadBufferLength$=new y.ValueSubject(0);this.livePositionFromPlayer$=new y.ValueSubject(0);this.currentStallDuration$=new y.ValueSubject(0);this.videoLastDataObtainedTimestamp$=new y.ValueSubject(0);this.fetcherRecoverableError$=new y.Subject;this.fetcherError$=new y.Subject;this.liveStreamEndTimestamp=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.forceEnded$=new y.Subject;this.gapWatchdogActive=!1;this.destroyController=new ue;this.initManifest=(0,y.abortable)(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=ye(t,i,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),this.manifest?.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:y.ErrorCategory.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=(0,y.abortable)(this.destroyController.signal,async function*(){this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(o=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:y.ErrorCategory.NETWORK,message:"Failed to load manifest",thrown:o})});if(!e)return null;let t=null;try{t=gn(e??"",this.manifestUrlString)}catch(o){let l=mn(e)??{id:"ManifestParsing",category:y.ErrorCategory.PARSER,message:"Failed to parse MPD manifest",thrown:o};this.error$.next(l)}if(!t)return null;let i=(o,l,p)=>!!(this.element?.canPlayType?.(l)&&Ze()?.isTypeSupported?.(`${l}; codecs="${p}"`)||o==="text");if(t.live){this.isLive$.next(!!t.live);let{availabilityStartTime:o,latestSegmentPublishTime:l,streamIsUnpublished:p,streamIsAlive:c}=t.live,d=(t.duration??0)/1e3;this.liveSeekableDuration$.next(-1*d),this.liveDuration$.next((l-o)/1e3),this.liveAvailabilityStartTime$.next(t.live.availabilityStartTime);let h="active";c||(h=p?"unpublished":"unexpectedly_down"),this.liveStreamStatus$.next(h)}let r={text:t.streams.text,video:[],audio:[]},s,n;for(let o of["video","audio"]){let p=t.streams[o].filter(({mime:d,codecs:h})=>i(o,d,h));r[o]=p;let c;if(this.tuning.dash.codecsPrioritizeEnabled){let d=p.map(({codecs:h})=>h);o==="audio"&&(n=Mn(d),c=n[0]),o==="video"&&(s=Ln(d),this.forceVideoCodec&&(0,iv.default)(s,this.forceVideoCodec)?c=this.forceVideoCodec:c=s[0]),c&&(r[o]=p.filter(({codecs:h})=>vr(h)===c))}else{let d=new Set(p.map(({codecs:h})=>h));c=$n(d),c&&(r[o]=p.filter(({codecs:h})=>h.startsWith(c)))}if(o==="video"){let d=this.tuning.preferHDR,h=r.video.some(b=>b.hdr),m=r.video.some(b=>!b.hdr);j.display.isHDR&&d&&h?r.video=r.video.filter(b=>b.hdr):m&&(r.video=r.video.filter(b=>!b.hdr))}}let u={...t,streams:r};return this.tuning.dash.codecsPrioritizeEnabled&&(u.codecs={video:s,audio:n}),this.tracer.log("updateManifestEnd",(0,y.flattenObject)(u)),u}.bind(this));this.initRepresentations=(0,y.abortable)(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initRepresentationsStart",(0,y.flattenObject)({initialVideo:e,initialAudio:t,sourceHls:i})),(0,y.assertNonNullable)(this.manifest),(0,y.assertNonNullable)(this.element),this.representationSubscription.unsubscribe(),this.representationSubscription=new y.Subscription,this.state$.startTransitionTo("representations_ready");let r=d=>{this.representationSubscription.add((0,y.fromEvent)(d,"error").pipe((0,y.filter)(h=>!!this.element?.played.length)).subscribe(h=>{this.error$.next({id:"VideoSource",category:y.ErrorCategory.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:h})}))};this.source=Js();let s=document.createElement("source");if(r(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),sr())if(i){let d=document.createElement("source");r(d),d.type="application/x-mpegurl",d.src=i.url,this.element.appendChild(d)}else this.element.disableRemotePlayback=!0;this.isActiveLive$.next(this.isLive$.getValue());let n={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),manifest:this.manifest},u=this.manifest.streams.video.reduce((d,h)=>[...d,...h.representations],[]);if(this.videoBufferManager=new za("video",this.source,u,n),this.bufferManagers=[this.videoBufferManager],(0,y.isNonNullable)(t)){let d=this.manifest.streams.audio.reduce((h,m)=>[...h,...m.representations],[]);this.audioBufferManager=new za("audio",this.source,d,n),this.bufferManagers.push(this.audioBufferManager)}Ya.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new Ya(this.manifest.streams.text,n)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$));let o=()=>{this.stallWatchdogSubscription?.unsubscribe(),this.currentStallDuration$.next(0)};if(this.representationSubscription.add((0,y.merge)(...d$.map(d=>(0,y.fromEvent)(this.element,d))).pipe((0,y.map)(d=>this.element?De(this.element.buffered,this.element.currentTime*1e3):0),(0,y.filterChanged)(),(0,y.tap)(d=>{d>this.tuning.dash.bufferEmptinessTolerance&&o()})).subscribe(this.bufferLength$)),this.representationSubscription.add((0,y.merge)((0,y.fromEvent)(this.element,"ended"),this.forceEnded$).subscribe(()=>{o()})),this.isLive$.getValue()){this.subscription.add(this.liveDuration$.pipe((0,y.filterChanged)()).subscribe(h=>this.liveStreamEndTimestamp=(0,y.now)())),this.subscription.add((0,y.fromEvent)(this.element,"pause").subscribe(()=>{this.livePauseWatchdogSubscription=(0,y.interval)(1e3).subscribe(h=>{let m=ei(this.manifestUrlString,2);this.manifestUrlString=ye(this.manifestUrlString,m+1e3,2),this.liveStreamStatus$.getValue()==="active"&&this.updateManifest()}),this.subscription.add(this.livePauseWatchdogSubscription)})).add((0,y.fromEvent)(this.element,"play").subscribe(h=>this.livePauseWatchdogSubscription?.unsubscribe())),this.representationSubscription.add((0,y.combine)({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe((0,y.map)(({isActiveLive:h,isLowLatency:m})=>h&&m),(0,y.filterChanged)()).subscribe(h=>{this.isManualDecreasePlaybackInLive()||Sr(this.element,1)})),this.representationSubscription.add((0,y.combine)({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe((0,y.filter)(({bufferLength:h,isActiveLive:m,isLowLatency:b})=>m&&b&&!!h)).subscribe(({bufferLength:h})=>this.liveBuffer.next(h))),this.representationSubscription.add(this.videoBufferManager.currentLowLatencySegmentLength$.subscribe(h=>{if(!this.isActiveLive$.getValue()&&!this.isLowLatency$.getValue()&&!h)return;let m=this.liveSeekableDuration$.getValue()-h/1e3;this.liveSeekableDuration$.next(Math.max(m,-1*this.tuning.dashCmafLive.maxLiveDuration)),this.liveDuration$.next(this.liveDuration$.getValue()+h/1e3)})),this.representationSubscription.add((0,y.combine)({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe((0,y.filter)(({isLive:h})=>h),(0,y.filterChanged)((h,m)=>m.bufferLength<h.bufferLength),(0,y.map)(({rtt:h,bufferLength:m,segmentServerLatency:b})=>{let S=ei(this.manifestUrlString,2);return(h/2+m+b+S)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add((0,y.combine)({liveBuffer:this.liveBuffer.smoothed$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).subscribe(({liveBuffer:h,isActiveLive:m,isLowLatency:b})=>{if(!b||!m)return;let S=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,v=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,I=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,A=h-S;if(this.isManualDecreasePlaybackInLive())return;let x=1;Math.abs(A)>v&&(x=1+Math.sign(A)*I),Sr(this.element,x)})),this.representationSubscription.add(this.bufferLength$.subscribe(h=>{let m=0;if(h){let b=(this.element?.currentTime??0)*1e3;m=Math.min(...this.bufferManagers.map(v=>v.getLiveSegmentsToLoadState(this.manifest)?.to??b))-b}this.liveLoadBufferLength$.getValue()!==m&&this.liveLoadBufferLength$.next(m)}));let d=0;this.representationSubscription.add((0,y.combine)({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe((0,y.throttle)(1e3)).subscribe(async({liveLoadBufferLength:h,bufferLength:m})=>{if(!this.element||this.isUpdatingLive)return;let b=this.element.playbackRate,S=ei(this.manifestUrlString,2),v=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,I=Math.min(v,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*b),A=this.tuning.dashCmafLive.normalizedActualBufferOffset*b,x=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*b,C=isFinite(h)?h:m,V=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),O=v<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next(O);let D="none";if(V?D="active_low_latency":this.isLowLatency$.getValue()&&O?(this.bufferManagers.forEach(N=>N.proceedLowLatencyLive()),D="active_low_latency"):S!==0&&C<I?D="live_forward_buffering":C<I+x&&(D="live_with_target_offset"),isFinite(h)&&(d=h>d?h:d),D==="live_forward_buffering"||D==="live_with_target_offset"){let N=d-(I+A),L=this.normolizeLiveOffset(Math.trunc(S+N/b)),ee=Math.abs(L-S),W=0;!h||ee<=this.tuning.dashCmafLive.offsetCalculationError?W=S:L>0&&ee>this.tuning.dashCmafLive.offsetCalculationError&&(W=L),this.manifestUrlString=ye(this.manifestUrlString,W,2)}(D==="live_with_target_offset"||D==="live_forward_buffering")&&(d=0,await this.updateLive())},h=>{this.error$.next({id:"updateLive",category:y.ErrorCategory.VIDEO_PIPELINE,thrown:h,message:"Failed to update live with subscription"})}))}let l=(0,y.merge)(...this.bufferManagers.map(d=>d.fullyBuffered$)).pipe((0,y.map)(()=>this.bufferManagers.every(d=>d.fullyBuffered$.getValue()))),p=(0,y.merge)(...this.bufferManagers.map(d=>d.onLastSegment$)).pipe((0,y.map)(()=>this.bufferManagers.some(d=>d.onLastSegment$.getValue()))),c=(0,y.combine)({allBuffersFull:l,someBufferEnded:p}).pipe((0,y.filterChanged)(),(0,y.map)(({allBuffersFull:d,someBufferEnded:h})=>d&&h),(0,y.filter)(d=>d));if(this.representationSubscription.add((0,y.merge)(this.forceEnded$,c).subscribe(()=>{if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(d=>!d.updating))try{this.source?.endOfStream()}catch(d){this.error$.next({id:"EndOfStream",category:y.ErrorCategory.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:d})}})),this.representationSubscription.add((0,y.merge)(...this.bufferManagers.map(d=>d.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.representationSubscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&(this.representationSubscription.add(this.audioBufferManager.playingRepresentation$.subscribe(this.currentAudioRepresentation$)),this.representationSubscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$))),this.liveTextManager&&this.representationSubscription.add(this.liveTextManager.currentRepresentation$.subscribe(this.currentLiveTextRepresentation$)),this.source.readyState!=="open"){let d=this.tuning.dash.sourceOpenTimeout>=0;yield new Promise(h=>{d&&(this.timeoutSourceOpenId=setTimeout(()=>{if(this.source?.readyState==="open"){h();return}this.error$.next({id:"OpenOfStream",category:y.ErrorCategory.VIDEO_PIPELINE,message:"Failed to open MediaSource",thrown:new Error("Timeout reject when wait sourceopen event"),traceAsLog:!0})},this.tuning.dash.sourceOpenTimeout)),this.source?.addEventListener("sourceopen",()=>{this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),h()},{once:!0})})}if(!this.isLive$.getValue()){let d=[this.manifest.duration??0,...(0,Wl.default)((0,Wl.default)([...this.manifest.streams.audio,...this.manifest.streams.video],h=>h.representations),h=>{let m=[];return h.duration&&m.push(h.duration),it(h.segmentReference)&&h.segmentReference.totalSegmentsDurationMs&&m.push(h.segmentReference.totalSegmentsDurationMs),m})];this.source.duration=Math.max(...d)/1e3}this.audioBufferManager&&(0,y.isNonNullable)(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState("representations_ready"),this.tracer.log("initRepresentationsEnd")}.bind(this));this.tick=()=>{if(!this.element||!this.videoBufferManager||this.source?.readyState!=="open")return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),this.audioBufferManager?.maintain(e),this.liveTextManager?.maintain(e),(this.videoBufferManager.gaps.length||this.audioBufferManager?.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=(0,y.interval)(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),t=>{this.error$.next({id:"GapWatchdog",category:y.ErrorCategory.WTF,message:"Error handling gaps",thrown:t})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name),this.forceVideoCodec=e.forceVideoCodec,this.fetcher=new Qn({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer,useEnableSubtitlesParam:e.tuning.useEnableSubtitlesParam}),this.subscription.add(this.fetcher.recoverableError$.subscribe(this.fetcherRecoverableError$)),this.subscription.add(this.fetcher.error$.subscribe(this.fetcherError$)),this.subscription.add(this.fetcher.manifestRequested$.subscribe(this.manifestRequested$)),this.subscription.add(this.fetcher.firstBytesManifest$.subscribe(this.firstBytesManifest$)),this.subscription.add(this.fetcher.manifestReceived$.subscribe(this.manifestReceived$)),this.subscription.add(this.fetcher.firstBytesRequested$.subscribe(this.firstBytesRequested$)),this.subscription.add(this.fetcher.firstBytesReceived$.subscribe(this.firstBytesReceived$)),this.subscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.subscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.liveBuffer=jt.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.bufferEstimator}),this.initTracerSubscription()}setSmartRepresentationSwitch(e){this.bufferManagers.forEach(t=>t.setSmartRepresentationSwitch(e))}async seekLive(e){(0,y.assertNonNullable)(this.element);let t=this.liveStreamStatus$.getValue()!=="active"?(0,y.now)()-this.liveStreamEndTimestamp:0,i=this.normolizeLiveOffset(e+t);this.isActiveLive$.next(i===0),this.manifestUrlString=ye(this.manifestUrlString,i,2),this.manifest=await this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,await this.videoBufferManager?.seekLive(this.manifest.streams.video),await this.audioBufferManager?.seekLive(this.manifest.streams.audio),this.liveTextManager?.seekLive(this.manifest.streams.text))}initBuffer(){(0,y.assertNonNullable)(this.element),this.state$.setState("running");let e=(0,y.fromEvent)(this.element,"timeupdate");this.tuning.dash.timeupdateEventTickThrottle&&(e=e.pipe((0,y.throttle)(this.tuning.dash.timeupdateEventTickThrottle))),this.subscription.add((0,y.merge)(...c$.map(t=>(0,y.fromEvent)(this.element,t)),(0,y.fromEvent)(window,"online"),e).subscribe(()=>this.tick(),t=>{this.error$.next({id:"DashVKPlayer",category:y.ErrorCategory.WTF,message:"Internal logic error",thrown:t})})),this.subscription.add((0,y.fromEvent)(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===HTMLMediaElement.HAVE_CURRENT_DATA&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add((0,y.fromEvent)(this.element,"waiting").subscribe(()=>{this.tuning.dash.useVideoElementWaitingCurrentTimeReassign&&this.element&&this.element.readyState===HTMLMediaElement.HAVE_CURRENT_DATA&&!this.element.seeking&&Ce(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let t=()=>{if(!this.element||this.source?.readyState!=="open")return;let i=this.currentStallDuration$.getValue();i+=50,this.currentStallDuration$.next(i);let r={timeInWaiting:i},s=(0,y.now)(),n=100,u=this.videoBufferManager?.lastDataObtainedTimestamp??0;this.videoLastDataObtainedTimestamp$.next(u);let o=this.audioBufferManager?.lastDataObtainedTimestamp??0,l=this.videoBufferManager?.getForwardBufferDuration()??0,p=this.audioBufferManager?.getForwardBufferDuration()??0,c=l<n&&s-u>this.tuning.dash.crashOnStallTWithoutDataTimeout,d=this.audioBufferManager&&p<n&&s-o>this.tuning.dash.crashOnStallTWithoutDataTimeout;if((c||d)&&i>this.tuning.dash.crashOnStallTWithoutDataTimeout||i>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${i} ms`);if(this.isLive$.getValue()&&i%2e3===0){let h=this.normolizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);this.seekLive(h).catch(m=>{this.error$.next({id:"stallIntervalCallback",category:y.ErrorCategory.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:m})}),r.liveLastOffset=h}else{let h=this.element.currentTime*1e3;this.videoBufferManager?.maintain(h),this.audioBufferManager?.maintain(h),r.position=h}this.tracer.log("stallIntervalCallback",(0,y.flattenObject)(r))};this.stallWatchdogSubscription&&(this.stallWatchdogSubscription.unsubscribe(),this.subscriptionRemovable.remove(this.stallWatchdogSubscription)),this.stallWatchdogSubscription=(0,y.interval)(50).subscribe(t,i=>{this.error$.next({id:"StallWatchdogCallback",category:y.ErrorCategory.NETWORK,message:"Can't restore DASH after stall.",thrown:i})}),this.subscriptionRemovable.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t,i=!1){let r={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return this.tuning.useNewSwitchTo?this.currentStallDuration$.getValue()>0?r?.switchToWithPreviousAbort(t,i):r?.switchTo(t,i):r?.switchToOld(t,i)}async seek(e,t){(0,y.assertNonNullable)(this.element),(0,y.assertNonNullable)(this.videoBufferManager);let i;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?i=e:i=Math.max(this.videoBufferManager.findSegmentStartTime(e)??e,this.audioBufferManager?.findSegmentStartTime(e)??e),this.warmUpMediaSourceIfNeeded(i),Ce(this.element.buffered,i)||await Promise.all([this.videoBufferManager.abort(),this.audioBufferManager?.abort()]),!((0,y.isNullable)(this.element)||(0,y.isNullable)(this.videoBufferManager))&&(this.videoBufferManager.maintain(i),this.audioBufferManager?.maintain(i),this.element.currentTime=i/1e3,this.tracer.log("seek",(0,y.flattenObject)({requestedPosition:e,forcePrecise:t,position:i})))}warmUpMediaSourceIfNeeded(e=this.element?.currentTime){(0,y.isNonNullable)(this.element)&&(0,y.isNonNullable)(this.source)&&(0,y.isNonNullable)(e)&&this.source?.readyState==="ended"&&this.element.duration*1e3-e>this.tuning.dash.seekBiasInTheEnd&&this.bufferManagers.forEach(t=>t.warmUpMediaSource())}get isStreamEnded(){return this.source?.readyState==="ended"}stop(){this.tracer.log("stop"),this.element?.querySelectorAll("source").forEach(e=>{URL.revokeObjectURL(e.src),e.remove()}),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),this.videoBufferManager?.destroy(),this.videoBufferManager=null,this.audioBufferManager?.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getStreams(){return this.manifest?.streams}getCodecs(){return this.manifest?.codecs}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){this.subscription.unsubscribe(),this.subscriptionRemovable.unsubscribe(),this.representationSubscription.unsubscribe(),this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),this.source?.readyState==="open"&&Array.from(this.source.sourceBuffers).every(e=>!e.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}initTracerSubscription(){let e=(0,y.getTraceSubscriptionMethod)(this.tracer.error.bind(this.tracer));this.subscription.add(this.error$.subscribe(e("error")))}isManualDecreasePlaybackInLive(){return!this.element||!this.isLive$.getValue()?!1:1-this.element.playbackRate>this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}async updateLive(){this.isUpdatingLive=!0,this.manifest=await this.updateManifest(),this.manifest&&(this.bufferManagers.forEach(e=>e.updateLive(this.manifest)),this.liveTextManager?.updateLive(this.manifest)),this.isUpdatingLive=!1}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.getBufferedTo();if(e===null)return;let t=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),i=this.isJumpGapAfterSeekLive,r=this.element.currentTime;this.isJumpGapAfterSeekLive&&!t&&this.element.currentTime>e&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let s=this.element.currentTime*1e3,n=null,u=this.element.readyState===HTMLMediaElement.HAVE_METADATA?this.tuning.endGapTolerance:0;for(let o of this.bufferManagers)for(let l of o.gaps)(l.persistent||o.playingRepresentation$.getValue()===l.representation)&&l.from-u<=s&&l.to+u>s&&(this.element.duration*1e3-l.to<this.tuning.endGapTolerance?n=1/0:(n===null||l.to>n)&&(n=l.to));if(n!==null){let o=n+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,o===1/0?this.forceEnded$.next():(this.element.currentTime=o/1e3,this.tracer.log("jumpGap",(0,y.flattenObject)({isJumpGapAfterSeekLive:i,isActiveLowLatency:t,initialCurrentTime:r,jumpTo:o,resultCurrentTime:this.element.currentTime})))}}calculateDurationFromSegments(){return Math.max(this.videoBufferManager?.calculateDurationFromSegments()||0,this.audioBufferManager?.calculateDurationFromSegments()||0)}};var ze=require("@vkontakte/videoplayer-shared"),Yn=class{constructor(){this.subscription=new ze.Subscription;this.pipSize$=new ze.ValueSubject(void 0);this.videoSize$=new ze.ValueSubject(void 0);this.elementSize$=new ze.ValueSubject(void 0);this.pictureInPictureWindowRemoveEventListener=ze.noop}connect({observableVideo:e,video:t}){let i=r=>{let s=r.target;this.pipSize$.next({width:s.width,height:s.height})};this.subscription.add((0,ze.observeElementSize)(t).subscribe(this.videoSize$)).add(e.enterPip$.subscribe(({pictureInPictureWindow:r})=>{this.pipSize$.next({width:r.width,height:r.height}),r.addEventListener("resize",i),this.pictureInPictureWindowRemoveEventListener=()=>{r.removeEventListener("resize",i)}})).add(e.leavePip$.subscribe(()=>{this.pictureInPictureWindowRemoveEventListener()})).add((0,ze.combine)({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe((0,ze.map)(({videoSize:r,inPip:s,pipSize:n})=>s?n:r)).subscribe(this.elementSize$))}getValue(){return this.elementSize$.getValue()}subscribe(e,t){return this.elementSize$.subscribe(e,t)}getObservable(){return this.elementSize$}destroy(){this.pictureInPictureWindowRemoveEventListener(),this.subscription.unsubscribe()}};var Di=class{constructor(e){this.subscription=new H.Subscription;this.videoState=new Z("stopped");this.observableVideo=null;this.droppedFramesManager=new lr;this.stallsManager=new _n;this.elementSizeManager=new Yn;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new ri;this.audioTrackSwitchHistory=new ri;this.selectedRepresentations={audio:null,video:null};this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(r.state==="requested"&&i?.to!=="paused"&&e!=="stopped"&&t!=="stopped"&&this.seek(r.position,r.forcePrecise),t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.player.stop(),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"),B(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"),B(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="ready"&&B(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):t==="playing"&&this.video.paused?this.playIfAllowed():i?.to==="playing"&&B(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&B(this.params.desiredState.playbackState,"paused");return;default:return(0,H.assertNever)(e)}}};this.init3DScene=e=>{if(this.scene3D)return;this.scene3D=new yr(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:e.projectionData?.pose.yaw||0,y:e.projectionData?.pose.pitch||0,z:e.projectionData?.pose.roll||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});let t=this.elementSizeManager.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};this.textTracksManager=new ot(e.source.url),this.params=e,this.video=Ue(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(Me(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 zn({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode,tracer:this.tracer,forceVideoCodec:this.params.forceVideoCodec}),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params;(0,H.isNullable)(this.observableVideo)&&(this.observableVideo=We(this.video),this.subscription.add(()=>this.observableVideo?.destroy()));let i=this.constructor.name,r=n=>{e.error$.next({id:i,category:H.ErrorCategory.WTF,message:`${i} internal logic error`,thrown:n})},s=(n,u)=>this.subscription.add(n.subscribe(u,r));return{output:e,desiredState:t,observableVideo:this.observableVideo,genericErrorListener:r,connect:s}}subscribe(){let{output:e,desiredState:t,observableVideo:i,genericErrorListener:r,connect:s}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe((0,H.filter)(c=>!!c.length),(0,H.once)()).subscribe(c=>{this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks:c})}));let n=this.params.desiredState.seekState.stateChangeEnded$.pipe((0,H.map)(c=>c.to.state!=="none"),(0,H.filterChanged)());this.stallsManager.init({isSeeked$:n,currentStallDuration$:this.player.currentStallDuration$,videoLastDataObtainedTimestamp$:this.player.videoLastDataObtainedTimestamp$,throughput$:this.params.dependencies.throughputEstimator.throughput$,rtt$:this.params.dependencies.throughputEstimator.rtt$,tuning:this.params.tuning.stallsManager,abrParams:this.params.tuning.autoTrackSelection,isBuffering$:i.isBuffering$,looped$:i.looped$,playing$:i.playing$,duration:this.video.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.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),s(i.loadedMetadata$,e.loadedMetadataEvent$),s(this.player.error$,e.error$),s(this.player.fetcherRecoverableError$,e.fetcherRecoverableError$),s(this.player.fetcherError$,e.fetcherError$),s(this.player.manifestRequested$,e.manifestRequested$),s(this.player.firstBytesManifest$,e.firstBytesManifest$),s(this.player.manifestReceived$,e.manifestReceived$),s(this.player.firstBytesRequested$,e.firstBytesRequested$),s(this.player.firstBytesReceived$,e.firstBytesReceived$),s(this.player.lastConnectionType$,e.httpConnectionType$),s(this.player.lastConnectionReused$,e.httpConnectionReused$),s(this.player.isLive$,e.isLive$),s(this.player.lastRequestFirstBytes$.pipe((0,H.filter)(H.isNonNullable),(0,H.once)()),e.firstBytesEvent$),s(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),s(this.videoState.stateChangeEnded$.pipe((0,H.map)(c=>c.to)),this.params.output.playbackState$),this.subscription.add(i.looped$.subscribe(()=>this.player.warmUpMediaSourceIfNeeded(),r)),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(Pt(this.video,t.isLooped,r)),this.subscription.add(je(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(nt(this.video,t.playbackRate,i.playbackRateState$,r)),this.elementSizeManager.connect({video:this.video,observableVideo:i}),s(ut(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),B(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),B(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.params.tuning.changePlaybackStateToPausedWhenEnded&&this.subscription.add(i.ended$.subscribe(()=>{this.videoState.setState("paused"),B(t.playbackState,"paused")})),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(),h=this.player.getCodecs();if((0,H.assertNonNullable)(d,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let b=[];for(let S of d.audio){b.push(ql(S));let v=[];for(let I of S.representations){let A=YS(I);v.push(A),this.audioTracksMap.set(A,{stream:S,representation:I})}this.audioStreamsMap.set(S,v)}this.params.output.availableAudioStreams$.next(b)}let m=[];for(let b of d.video){m.push(Ul(b));let S=[];for(let v of b.representations){let I=Ga({...v,streamId:b.id});I&&(S.push(I),this.videoTracksMap.set(I,{stream:b,representation:v}))}this.videoStreamsMap.set(b,S)}this.params.output.availableVideoStreams$.next(m);for(let b of d.text)for(let S of b.representations){let v=KS(b,S);this.textTracksMap.set(v,{stream:b,representation:S})}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),h?.video&&this.params.output.availableVideoCodecs$.next(h.video),h?.audio&&this.params.output.availableAudioCodecs$.next(h.audio),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())},r));let{vktvAbrThrottle:u}=this.params.tuning.dash,o=u&&ZS(u)||null;this.subscription.add((0,H.merge)(this.player.currentStallDuration$,this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,this.elementSizeManager.getObservable(),this.params.output.elementVisible$,this.droppedFramesManager.onDroopedVideoFramesLimit$,(0,H.fromEvent)(this.video,"progress")).pipe((0,H.filter)(()=>this.videoTracksMap.size>0)).subscribe(async()=>{let c=this.player.state$.getState(),d=this.player.state$.getTransition();if(c!=="manifest_ready"&&c!=="running"||d||c==="running"&&o&&!o())return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState()),this.selectVideoAudioRepresentations();let{video:h,audio:m}=this.selectedRepresentations;if(!h)return;let b=Li(this.videoTracksMap.keys(),v=>this.videoTracksMap.get(v)?.representation.id===h.id);(0,H.isNonNullable)(b)&&(this.stallsManager.lastVideoTrackSelected=b);let S=this.params.desiredState.autoVideoTrackLimits.getTransition();if(S&&this.params.output.autoVideoTrackLimits$.next(S.to),c==="manifest_ready")await this.player.initRepresentations(h.id,m?.id,this.params.sourceHls);else if(await this.player.switchRepresentation("video",h.id),m){let v=!!t.audioStream.getTransition();await this.player.switchRepresentation("audio",m.id,v)}},r)),this.subscription.add((0,H.combine)({videoState:this.videoState.stateChangeEnded$,autoVideoTrackState:(0,H.merge)((0,H.observableFrom)([t.autoVideoTrackSwitching.getState()]),t.autoVideoTrackSwitching.stateChangeEnded$.pipe((0,H.map)(c=>c.to)))}).pipe((0,H.map)(({videoState:c,autoVideoTrackState:d})=>c.to!=="stopped"&&d),(0,H.filterChanged)()).subscribe(c=>this.player.setSmartRepresentationSwitch(c))),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:c})=>{this.scene3D&&c&&this.scene3D.pointCameraTo(c.x,c.y)})),this.subscription.add(this.elementSizeManager.subscribe(c=>{this.scene3D&&c&&this.scene3D.setViewportSize(c.width,c.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe((0,H.filterChanged)()).subscribe(c=>{let d=Li(this.videoTracksMap.entries(),([,{representation:v}])=>v.id===c);if(!d){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[h,{stream:m}]=d,b=this.params.desiredState.videoStream.getTransition();b&&b.to&&b.to.id===m.id&&this.params.desiredState.videoStream.setState(b.to),e.currentVideoTrack$.next(h),e.currentVideoStream$.next(Ul(m));let S=this.player.calculateDurationFromSegments();S&&this.params.output.duration$.next(S/1e3)},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe((0,H.filterChanged)()).subscribe(c=>{let d=Li(this.audioTracksMap.entries(),([,{representation:S}])=>S.id===c);if(!d){e.currentAudioStream$.next(void 0);return}let[h,{stream:m}]=d,b=this.params.desiredState.audioStream.getTransition();b&&b.to&&b.to.id===m.id&&this.params.desiredState.audioStream.setState(b.to),e.currentAudioStream$.next(ql(m))},r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(c=>{if(c?.is3dVideo&&this.params.tuning.spherical?.enabled)try{this.init3DScene(c),e.is3DVideo$.next(!0)}catch(d){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${d}`})}else this.destroy3DScene(),this.params.tuning.spherical?.enabled&&e.is3DVideo$.next(!1)},r)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,r)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,r)),this.textTracksManager.connect(this.video,t,e);let l=t.playbackState.stateChangeStarted$.pipe((0,H.map)(({to:c})=>c==="ready"),(0,H.filterChanged)());this.subscription.add((0,H.merge)(l,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,(0,H.observableFrom)(["init"])).subscribe(()=>{let c=t.autoVideoTrackSwitching.getState(),h=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:c?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(h)})),this.subscription.add((0,H.merge)(l,this.player.state$.stateChangeEnded$,(0,H.observableFrom)(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let p=(0,H.merge)(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,H.observableFrom)(["init"])).pipe((0,H.debounce)(0));this.subscription.add(p.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?aa:ra,t=this.params.tuning.useNewAutoSelectVideoTrack?cn:ln,i=this.params.tuning.useNewAutoSelectVideoTrack?Rt:un,{desiredState:r,output:s}=this.params,n=r.autoVideoTrackSwitching.getState(),u=r.videoTrack.getState()?.id,o=Li(this.videoTracksMap.keys(),D=>D.id===u),l=s.currentVideoTrack$.getValue(),p=r.videoStream.getState()??(o&&this.videoTracksMap.get(o)?.stream)??this.videoStreamsMap.size===1?this.videoStreamsMap.keys().next().value:void 0;if(!p)return;let c=Li(this.videoStreamsMap.keys(),D=>D.id===p.id),d=c&&this.videoStreamsMap.get(c);if(!d)return;let h=De(this.video.buffered,this.video.currentTime*1e3),m;this.player.isActiveLive$.getValue()?m=this.player.isLowLatency$.getValue()?this.params.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.params.tuning.dashCmafLive.normalizedLiveMinBufferSize:this.player.isLive$.getValue()?m=this.params.tuning.dashCmafLive.normalizedTargetMinBufferSize:m=n?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;let b=(this.video.duration*1e3||1/0)-this.video.currentTime*1e3,S=Math.min(h/Math.min(m,b||1/0),1),v=r.audioStream.getState()??(this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0),I=v?.id&&Li(this.audioStreamsMap.keys(),D=>D.id===v.id)||this.audioStreamsMap.keys().next().value,A=0;if(I){if(o&&!n){let D=e(o,d,this.audioStreamsMap.get(I)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);A=Math.max(A,D?.bitrate??-1/0)}if(l){let D=e(l,d,this.audioStreamsMap.get(I)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);A=Math.max(A,D?.bitrate??-1/0)}}let x=o;(n||!x)&&(x=i(d,{container:this.elementSizeManager.getValue(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.stallsManager.abrTuningParams,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:A,forwardBufferHealth:S,current:l,visible:this.params.output.elementVisible$.getValue(),history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,stallsVideoMaxQualityLimit:this.stallsManager.videoMaxQualityLimit,stallsPredictedThroughput:this.stallsManager.predictedThroughput,abrLogger:this.params.dependencies.abrLogger}));let C=I&&t(x,d,this.audioStreamsMap.get(I)??[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.stallsManager.abrTuningParams,forwardBufferHealth:S,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),V=this.videoTracksMap.get(x)?.representation,O=C&&this.audioTracksMap.get(C)?.representation;V&&O?(this.selectedRepresentations.video=V,this.selectedRepresentations.audio=O):V&&!O&&this.audioTracksMap.size===0&&(this.selectedRepresentations.video=V,this.selectedRepresentations.audio=null)}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){Qe(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),B(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:H.ErrorCategory.DOM,thrown:e}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.stallsManager.destroy(),this.elementSizeManager.destroy(),this.destroy3DScene(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),this.params.output.currentVideoStream$.next(void 0),He(this.video),this.tracer.end()}};var Ka=class extends Di{subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();i(t.timeUpdate$,e.position$),i(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}};var de=require("@vkontakte/videoplayer-shared");var Xa=class extends Di{constructor(e){super(e),this.textTracksManager.destroy()}subscribe(){super.subscribe();let e=!1,t=-1,{output:i,observableVideo:r,desiredState:s,connect:n}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canPlayLiveTailBuffer$.next(!0),n(r.timeUpdate$,i.liveBufferTime$),n(this.player.liveSeekableDuration$,i.duration$),n(this.player.liveLatency$,i.liveLatency$);let u=new de.ValueSubject(1);n(r.playbackRateState$,u),this.params.tuning.dashCmafLive.catchupLiveForMutedInactiveTab&&this.subscription.add(i.elementVisible$.pipe((0,de.filterChanged)()).subscribe(o=>{let l=i.position$.getValue(),p=i.volume$.getValue(),c=!p.volume||p.muted;!o&&!l&&c?e=!0:o&&e&&(this.seek(0),e=!1)})),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(s.isLowLatency.stateChangeEnded$.pipe((0,de.map)(o=>o.to)).subscribe(this.player.isLowLatency$)).add((0,de.combine)({liveBufferTime:i.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe((0,de.map)(({liveBufferTime:o,liveAvailabilityStartTime:l})=>o&&l?o+l:void 0)).subscribe(i.liveTime$)).add(this.player.liveStreamStatus$.pipe((0,de.filter)(o=>(0,de.isNonNullable)(o))).subscribe(o=>i.isLiveEnded$.next(o!=="active"&&i.position$.getValue()===0))).add((0,de.combine)({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:(0,de.merge)(r.playbackRateState$,new de.ValueSubject(1))}).pipe((0,de.filter)(({liveStreamStatus:o,liveDuration:l})=>o==="active"&&!!l)).subscribe(({liveDuration:o,playbackRate:l})=>{let p=i.liveBufferTime$.getValue(),c=i.position$.getValue(),{playbackCatchupSpeedup:d}=this.params.tuning.dashCmafLive.lowLatency;c||l<1-d||this.video.paused||(0,de.isNullable)(p)||(t=o-p)})).add((0,de.combine)({time:i.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:(0,de.merge)(r.playbackRateState$,new de.ValueSubject(1))}).pipe((0,de.filterChanged)((o,l)=>this.player.liveStreamStatus$.getValue()==="active"?o.liveDuration===l.liveDuration:o.time===l.time)).subscribe(({time:o,liveDuration:l,playbackRate:p})=>{let c=i.position$.getValue(),{playbackCatchupSpeedup:d}=this.params.tuning.dashCmafLive.lowLatency;if(!c&&!this.video.paused&&p>=1-d||(0,de.isNullable)(o)||(0,de.isNullable)(l))return;let h=-1*(l-o-t);i.position$.next(Math.min(h,0))})).add(this.player.currentLiveTextRepresentation$.subscribe(o=>{if(o){let l=XS(o);this.params.output.availableTextTracks$.next([l])}}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,i=Math.trunc(t/1e3<=Math.abs(this.params.output.duration$.getValue())?t:0);this.player.seekLive(i).then(()=>{this.params.output.position$.next(e/1e3)})}};var rv="X-Playback-Duration",Ql=async a=>{let e=await lt(a),t=await e.text(),i=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t)?.[1];return i?parseInt(i,10):e.headers.has(rv)?parseInt(e.headers.get(rv),10):void 0};var re=require("@vkontakte/videoplayer-shared");var zl=Q(uu(),1);var Kn=require("@vkontakte/videoplayer-shared");var h$=a=>{let e=null;if(a.QUALITY&&(e=ii(a.QUALITY)),!e&&a.RESOLUTION){let[t,i]=a.RESOLUTION.split("x").map(r=>parseInt(r,10));e=(0,Kn.videoSizeToQuality)({width:t,height:i})}return e??null},f$=(a,e)=>{let t=a.split(`
178
+ `;var yr=class{constructor(e,t,i){this.videoInitialized=!1;this.active=!1;this.container=e,this.sourceVideoElement=t,this.params=i,this.canvas=this.createCanvas();let r=this.canvas.getContext("webgl");if(!r)throw new Error("Could not initialize WebGL context");this.gl=r,this.container.appendChild(this.canvas),this.camera=new Cn(this.params.fov,this.params.orientation),this.cameraRotationManager=new Bn(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"),i=this.gl.getAttribLocation(this.program,"a_texel"),r=this.gl.getUniformLocation(this.program,"u_texture"),s=this.gl.getUniformLocation(this.program,"u_focus");this.gl.enableVertexAttribArray(t),this.gl.enableVertexAttribArray(i),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(i,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(r,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(i),this.active&&requestAnimationFrame(this.renderFn)}createShader(e,t){let i=this.gl.createShader(t);if(!i)throw this.destroy(),new Error(`Could not create shader (${t})`);if(this.gl.shaderSource(i,e),this.gl.compileShader(i),!this.gl.getShaderParameter(i,this.gl.COMPILE_STATUS))throw this.destroy(),new Error("An error occurred while compiling the shader: "+this.gl.getShaderInfoLog(i));return i}createProgram(){let e=this.gl.createProgram();if(!e)throw this.destroy(),new Error("Could not create shader program");let t=this.createShader(jS,this.gl.VERTEX_SHADER),i=this.createShader(WS,this.gl.FRAGMENT_SHADER);if(this.gl.attachShader(e,t),this.gl.attachShader(e,i),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,i=1,r=this.frameHeight/(this.frameWidth/this.viewportWidth);return r>this.viewportHeight?t=this.viewportHeight/r:i=r/this.viewportHeight,this.gl.bindBuffer(this.gl.ARRAY_BUFFER,e),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-t,-i,t,-i,t,i,-t,i]),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,i=this.camera.fov.x/360/2,r=this.camera.fov.y/180/2,s=e-i,n=t-r,u=e+i,o=t-r,l=e+i,p=t+r,c=e-i,d=t+r;return[s,n,u,o,l,p,c,d]}updateTextureMappingBuffer(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([...this.calculateTexturePosition()]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}updateFrameSize(){this.frameWidth=this.sourceVideoElement.videoWidth,this.frameHeight=this.sourceVideoElement.videoHeight}createCanvas(){let e=document.createElement("canvas");return e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e}};var he=require("@vkontakte/videoplayer-shared");var Vn="stalls_manager_metrics",_l="stalls_manager_abr_params",QS="stalls_manager_default_tuning_abr_params",Ol=class{constructor(){this.isSeeked$=new he.ValueSubject(!1);this.isBuffering$=new he.ValueSubject(!1);this.maxQualityLimit=void 0;this.currentStallsCount=0;this.sumStallsDuration=0;this.lastStallDuration=0;this.providerStartWatchingTimestamp=0;this.lastUniqueVideoTrackSelectedTimestamp=0;this.predictedThroughputWithoutData=0;this.subscription=new he.Subscription;this.severeStallOccurred$=new he.ValueSubject(!1)}init(e){this.currentStallDuration$=e.currentStallDuration$,this.videoLastDataObtainedTimestamp$=e.videoLastDataObtainedTimestamp$,this.throughput$=e.throughput$,this.rtt$=e.rtt$,this.tuning=e.tuning,this.abrParams=e.abrParams,this.duration=e.duration,this.resetStoredAbrParamsIfNeeded(),this.subscribe(e)}get videoMaxQualityLimit(){return this.maxQualityLimit}get predictedThroughput(){return this.predictedThroughputWithoutData}get abrTuningParams(){let t=(this.tuning.ignoreDynamicAbrForShortVideo?this.tuning.enabled&&this.duration>this.tuning.minTvtToBeCounted:this.tuning.enabled)?this.getStoredData(_l):{};return{...this.abrParams,...t}}set lastVideoTrackSelected(e){this.lastUniqueVideoTrackSelected?.id!==e.id&&(this.lastUniqueVideoTrackSelected=e,this.lastUniqueVideoTrackSelectedTimestamp=(0,he.now)(),this.currentStallsCount=0)}destroy(){window.clearTimeout(this.qualityRestrictionTimer),this.subscription.unsubscribe(),this.currentStallDuration$.getValue()!==0&&this.updateStallData();let e=((0,he.now)()-this.providerStartWatchingTimestamp-this.sumStallsDuration)/1e3,t=this.sumStallsDuration;this.addStallInfoToHistory(e,t),this.updateStoredAbrParams()}resetStoredAbrParamsIfNeeded(){let{bitrateFactorAtEmptyBuffer:e,bitrateFactorAtFullBuffer:t,containerSizeFactor:i}={...this.getStoredData(QS)},{bitrateFactorAtEmptyBuffer:r,bitrateFactorAtFullBuffer:s,containerSizeFactor:n}={...this.abrParams};this.tuning.enabled&&e===r&&t===s&&i===n||(this.removeStoredData(_l),this.setStoredData(QS,{bitrateFactorAtEmptyBuffer:r,bitrateFactorAtFullBuffer:s,containerSizeFactor:n}))}updateStoredAbrParams(){let e=[],t=this.getStoredData(Vn,"[]");if(!this.tuning.enabled||t.length<this.tuning.stallsMetricsHistoryLength)return;let i=t.reduce((s,n)=>s+n.tvt,0);if(this.tuning.useTotalStallsDurationPerTvt){let n=t.reduce((u,o)=>u+o.stallsDuration,0)/i;e.push(this.calculateOptimalAbrParams(n,i))}if(this.tuning.useAverageStallsDurationPerTvt){let s=t.reduce((n,u)=>n+u.stallsDurationPerTvt,0)/t.length;e.push(this.calculateOptimalAbrParams(s,i))}this.tuning.useEmaStallsDurationPerTvt&&e.push(this.calculateOptimalAbrParams(t[t.length-1].stallsDurationPerTvtSmoothed,i));let r={bitrateFactorAtEmptyBuffer:Math.max(...e.map(s=>s.bitrateFactorAtEmptyBuffer)),bitrateFactorAtFullBuffer:Math.max(...e.map(s=>s.bitrateFactorAtFullBuffer)),containerSizeFactor:Math.min(...e.map(s=>s.containerSizeFactor))};this.setStoredData(Vn,[]),this.setStoredData(_l,r)}calculateOptimalAbrParams(e,t){let{targetStallsDurationPerTvt:i,deviationStallsDurationPerTvt:r,criticalStallsDurationPerTvt:s,abrAdjustingSpeed:n,significantTvt:u}=this.tuning,o=n*Math.min(t/u,1),l=this.abrTuningParams;return e<i-r?l={bitrateFactorAtEmptyBuffer:Math.max(l.bitrateFactorAtEmptyBuffer-o,this.abrParams.minBitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.max(l.bitrateFactorAtFullBuffer-o,this.abrParams.minBitrateFactorAtFullBuffer),containerSizeFactor:Math.min(l.containerSizeFactor+o,this.abrParams.maxContainerSizeFactor)}:e>i+r&&(l={bitrateFactorAtEmptyBuffer:Math.min(l.bitrateFactorAtEmptyBuffer+o,this.abrParams.maxBitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.min(l.bitrateFactorAtFullBuffer+o,this.abrParams.maxBitrateFactorAtFullBuffer),containerSizeFactor:Math.max(l.containerSizeFactor-o,this.abrParams.minContainerSizeFactor)}),e>s&&(l={bitrateFactorAtEmptyBuffer:Math.max(l.bitrateFactorAtEmptyBuffer,this.abrParams.bitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.max(l.bitrateFactorAtFullBuffer,this.abrParams.bitrateFactorAtFullBuffer),containerSizeFactor:Math.min(l.containerSizeFactor,this.abrParams.containerSizeFactor)}),l}getStoredData(e,t="{}"){return JSON.parse(he.safeStorage.get(e)??t)}setStoredData(e,t){he.safeStorage.set(e,JSON.stringify(t))}removeStoredData(e){he.safeStorage.remove(e)}addStallInfoToHistory(e,t){if(e<this.tuning.minTvtToBeCounted||e>this.tuning.maxTvtToBeCounted||e*1e3<t)return;let i=this.getStoredData(Vn,"[]"),r=t/e,s=i.length?Ht(i[i.length-1].stallsDurationPerTvtSmoothed,t/e,this.tuning.emaAlpha):r,n={tvt:e,stallsDuration:t,stallsDurationPerTvt:r,stallsDurationPerTvtSmoothed:s};i.push(n),i.length>this.tuning.stallsMetricsHistoryLength&&i.shift(),this.setStoredData(Vn,i)}updateStallData(){this.providerStartWatchingTimestamp&&!this.isSeeked$.getValue()&&(this.sumStallsDuration+=Math.min(this.lastStallDuration,this.tuning.maxPossibleStallDuration),this.currentStallsCount++)}subscribe(e){this.subscription.add(e.isSeeked$.subscribe(this.isSeeked$)),this.subscription.add(e.isBuffering$.subscribe(this.isBuffering$)),this.subscription.add(e.looped$.subscribe(t=>this.currentStallsCount=0)),this.subscription.add(e.playing$.pipe((0,he.once)()).subscribe(t=>this.providerStartWatchingTimestamp=(0,he.now)())),this.subscription.add(this.currentStallDuration$.pipe((0,he.filterChanged)()).subscribe(t=>{let{stallDurationNoDataBeforeQualityDecrease:i,stallCountBeforeQualityDecrease:r,resetQualityRestrictionTimeout:s,ignoreStallsOnSeek:n}=this.tuning;if((0,he.isNullable)(this.lastUniqueVideoTrackSelected)||n&&this.isSeeked$.getValue())return;let u=this.rtt$.getValue(),o=this.throughput$.getValue(),l=this.videoLastDataObtainedTimestamp$.getValue(),p=(0,he.now)(),c=r&&this.currentStallsCount>=r,d=i&&p-this.lastUniqueVideoTrackSelectedTimestamp>=i+u&&p-l>=i+u&&t>=i;(c||d)&&(this.severeStallOccurred$.next(!0),window.clearTimeout(this.qualityRestrictionTimer),this.maxQualityLimit=this.lastUniqueVideoTrackSelected.quality,(0,he.isNonNullable)(this.lastUniqueVideoTrackSelected.bitrate)&&o>this.lastUniqueVideoTrackSelected.bitrate&&(this.predictedThroughputWithoutData=this.lastUniqueVideoTrackSelected.bitrate)),!t&&(0,he.now)()-this.providerStartWatchingTimestamp>this.lastStallDuration&&(this.updateStallData(),this.severeStallOccurred$.next(!1),window.clearTimeout(this.qualityRestrictionTimer),this.qualityRestrictionTimer=window.setTimeout(()=>{this.maxQualityLimit=void 0,this.predictedThroughputWithoutData=0},s)),this.lastStallDuration=t}))}},_n=Ol;var Ge=require("@vkontakte/videoplayer-shared"),On=class{constructor(){this.subscription=new Ge.Subscription;this.pipSize$=new Ge.ValueSubject(void 0);this.videoSize$=new Ge.ValueSubject(void 0);this.elementSize$=new Ge.ValueSubject(void 0);this.pictureInPictureWindowRemoveEventListener=Ge.noop}connect({observableVideo:e,video:t}){let i=r=>{let s=r.target;this.pipSize$.next({width:s.width,height:s.height})};this.subscription.add((0,Ge.observeElementSize)(t).subscribe(this.videoSize$)).add(e.enterPip$.subscribe(({pictureInPictureWindow:r})=>{this.pipSize$.next({width:r.width,height:r.height}),r.addEventListener("resize",i),this.pictureInPictureWindowRemoveEventListener=()=>{r.removeEventListener("resize",i)}})).add(e.leavePip$.subscribe(()=>{this.pictureInPictureWindowRemoveEventListener()})).add((0,Ge.combine)({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe((0,Ge.map)(({videoSize:r,inPip:s,pipSize:n})=>s?n:r)).subscribe(this.elementSize$))}getValue(){return this.elementSize$.getValue()}subscribe(e,t){return this.elementSize$.subscribe(e,t)}getObservable(){return this.elementSize$}destroy(){this.pictureInPictureWindowRemoveEventListener(),this.subscription.unsubscribe()}};var ui=require("@vkontakte/videoplayer-shared");var Tr=({subscription:a,desiredState:e,videoElement$:t,observableVideo:i})=>{if(!j.browser.isSafari)return;let r=0,s=!1;a.add(e.volume.stateChangeStarted$.pipe((0,ui.map)(()=>{let n=e.volume.getTransition(),u=t.getValue();return!u||!n?!1:!n.to.muted&&u.muted}),(0,ui.filter)(n=>!!n),(0,ui.once)()).subscribe(()=>{r=performance.now(),s=!0})),a.add(i.playbackRateState$.pipe((0,ui.filter)(()=>s),(0,ui.once)()).subscribe(()=>{let n=t.getValue(),u=e.playbackRate.getState();n&&u!==n.playbackRate&&performance.now()-r<1e3&&(n.playbackRate=u)}))};var $i=class{constructor(e){this.subscription=new F.Subscription;this.videoState=new Z("stopped");this.observableVideo=null;this.droppedFramesManager=new lr;this.stallsManager=new _n;this.elementSizeManager=new On;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new ri;this.audioTrackSwitchHistory=new ri;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(r.state==="requested"&&i?.to!=="paused"&&e!=="stopped"&&t!=="stopped"&&this.seek(r.position,r.forcePrecise),t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.player.stop(),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"),B(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"),B(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="ready"&&B(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):t==="playing"&&this.video.paused?this.playIfAllowed():i?.to==="playing"&&B(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&B(this.params.desiredState.playbackState,"paused");return;default:return(0,F.assertNever)(e)}}};this.init3DScene=e=>{if(this.scene3D)return;this.scene3D=new yr(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:e.projectionData?.pose.yaw||0,y:e.projectionData?.pose.pitch||0,z:e.projectionData?.pose.roll||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});let t=this.elementSizeManager.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};this.textTracksManager=new ot(e.source.url),this.params=e,this.video=Ue(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(Me(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 Dn({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode,tracer:this.tracer,forceVideoCodec:this.params.forceVideoCodec}),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params;(0,F.isNullable)(this.observableVideo)&&(this.observableVideo=We(this.video),this.subscription.add(()=>this.observableVideo?.destroy()));let i=this.constructor.name,r=n=>{e.error$.next({id:i,category:F.ErrorCategory.WTF,message:`${i} internal logic error`,thrown:n})},s=(n,u)=>this.subscription.add(n.subscribe(u,r));return{output:e,desiredState:t,observableVideo:this.observableVideo,genericErrorListener:r,connect:s}}subscribe(){let{output:e,desiredState:t,observableVideo:i,genericErrorListener:r,connect:s}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe((0,F.filter)(c=>!!c.length),(0,F.once)()).subscribe(c=>{this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks:c})}));let n=this.params.desiredState.seekState.stateChangeEnded$.pipe((0,F.map)(c=>c.to.state!=="none"),(0,F.filterChanged)());this.stallsManager.init({isSeeked$:n,currentStallDuration$:this.player.currentStallDuration$,videoLastDataObtainedTimestamp$:this.player.videoLastDataObtainedTimestamp$,throughput$:this.params.dependencies.throughputEstimator.throughput$,rtt$:this.params.dependencies.throughputEstimator.rtt$,tuning:this.params.tuning.stallsManager,abrParams:this.params.tuning.autoTrackSelection,isBuffering$:i.isBuffering$,looped$:i.looped$,playing$:i.playing$,duration:this.video.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.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),s(i.loadedMetadata$,e.loadedMetadataEvent$),s(this.player.error$,e.error$),s(this.player.fetcherRecoverableError$,e.fetcherRecoverableError$),s(this.player.fetcherError$,e.fetcherError$),s(this.player.manifestRequested$,e.manifestRequested$),s(this.player.firstBytesManifest$,e.firstBytesManifest$),s(this.player.manifestReceived$,e.manifestReceived$),s(this.player.firstBytesRequested$,e.firstBytesRequested$),s(this.player.firstBytesReceived$,e.firstBytesReceived$),s(this.player.lastConnectionType$,e.httpConnectionType$),s(this.player.lastConnectionReused$,e.httpConnectionReused$),s(this.player.isLive$,e.isLive$),s(this.player.lastRequestFirstBytes$.pipe((0,F.filter)(F.isNonNullable),(0,F.once)()),e.firstBytesEvent$),s(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),s(this.videoState.stateChangeEnded$.pipe((0,F.map)(c=>c.to)),this.params.output.playbackState$),this.subscription.add(i.looped$.subscribe(()=>this.player.warmUpMediaSourceIfNeeded(),r)),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(kt(this.video,t.isLooped,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),Tr({subscription:this.subscription,desiredState:t,videoElement$:this.params.output.element$,observableVideo:i}),this.subscription.add(je(this.video,t.volume,i.volumeState$,r)),this.subscription.add(nt(this.video,t.playbackRate,i.playbackRateState$,r)),this.elementSizeManager.connect({video:this.video,observableVideo:i}),s(ut(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),B(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),B(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.params.tuning.changePlaybackStateToPausedWhenEnded&&this.subscription.add(i.ended$.subscribe(()=>{this.videoState.setState("paused"),B(t.playbackState,"paused")})),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(),h=this.player.getCodecs();if((0,F.assertNonNullable)(d,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let b=[];for(let S of d.audio){b.push(Rl(S));let v=[];for(let I of S.representations){let P=BS(I);v.push(P),this.audioTracksMap.set(P,{stream:S,representation:I})}this.audioStreamsMap.set(S,v)}this.params.output.availableAudioStreams$.next(b)}let m=[];for(let b of d.video){m.push($l(b));let S=[];for(let v of b.representations){let I=Na({...v,streamId:b.id});I&&(S.push(I),this.videoTracksMap.set(I,{stream:b,representation:v}))}this.videoStreamsMap.set(b,S)}this.params.output.availableVideoStreams$.next(m);for(let b of d.text)for(let S of b.representations){let v=VS(b,S);this.textTracksMap.set(v,{stream:b,representation:S})}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),h?.video&&this.params.output.availableVideoCodecs$.next(h.video),h?.audio&&this.params.output.availableAudioCodecs$.next(h.audio),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())},r));let u=(0,F.merge)(this.player.currentStallDuration$,this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,this.elementSizeManager.getObservable(),this.params.output.elementVisible$,this.droppedFramesManager.onDroopedVideoFramesLimit$,(0,F.fromEvent)(this.video,"progress")).pipe((0,F.filter)(()=>this.videoTracksMap.size>0)),{abrThrottle:o}=this.params.tuning.dash;o&&(u=u.pipe((0,F.throttle)(o))),this.subscription.add(u.subscribe(async()=>{let c=this.player.state$.getState(),d=this.player.state$.getTransition();if(c!=="manifest_ready"&&c!=="running"||d)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let h=this.selectVideoAudioRepresentations();if(!h)return;let[m,b]=h,S=[...this.videoTracksMap.keys()].find(I=>this.videoTracksMap.get(I)?.representation.id===m.id);(0,F.isNonNullable)(S)&&(this.stallsManager.lastVideoTrackSelected=S);let v=this.params.desiredState.autoVideoTrackLimits.getTransition();if(v&&this.params.output.autoVideoTrackLimits$.next(v.to),c==="manifest_ready")await this.player.initRepresentations(m.id,b?.id,this.params.sourceHls);else if(await this.player.switchRepresentation("video",m.id),b){let I=!!t.audioStream.getTransition();await this.player.switchRepresentation("audio",b.id,I)}},r)),this.subscription.add((0,F.combine)({videoState:this.videoState.stateChangeEnded$,autoVideoTrackState:(0,F.merge)((0,F.observableFrom)([t.autoVideoTrackSwitching.getState()]),t.autoVideoTrackSwitching.stateChangeEnded$.pipe((0,F.map)(c=>c.to)))}).pipe((0,F.map)(({videoState:c,autoVideoTrackState:d})=>c.to!=="stopped"&&d),(0,F.filterChanged)()).subscribe(c=>this.player.setSmartRepresentationSwitch(c))),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:c})=>{this.scene3D&&c&&this.scene3D.pointCameraTo(c.x,c.y)})),this.subscription.add(this.elementSizeManager.subscribe(c=>{this.scene3D&&c&&this.scene3D.setViewportSize(c.width,c.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe((0,F.filterChanged)()).subscribe(c=>{let d=[...this.videoTracksMap.entries()].find(([,{representation:v}])=>v.id===c);if(!d){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[h,{stream:m}]=d,b=this.params.desiredState.videoStream.getTransition();b&&b.to&&b.to.id===m.id&&this.params.desiredState.videoStream.setState(b.to),e.currentVideoTrack$.next(h),e.currentVideoStream$.next($l(m));let S=this.player.calculateDurationFromSegments();S&&this.params.output.duration$.next(S/1e3)},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe((0,F.filterChanged)()).subscribe(c=>{let d=[...this.audioTracksMap.entries()].find(([,{representation:S}])=>S.id===c);if(!d){e.currentAudioStream$.next(void 0);return}let[h,{stream:m}]=d,b=this.params.desiredState.audioStream.getTransition();b&&b.to&&b.to.id===m.id&&this.params.desiredState.audioStream.setState(b.to),e.currentAudioStream$.next(Rl(m))},r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(c=>{if(c?.is3dVideo&&this.params.tuning.spherical?.enabled)try{this.init3DScene(c),e.is3DVideo$.next(!0)}catch(d){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${d}`})}else this.destroy3DScene(),this.params.tuning.spherical?.enabled&&e.is3DVideo$.next(!1)},r)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,r)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,r)),this.textTracksManager.connect(this.video,t,e);let l=t.playbackState.stateChangeStarted$.pipe((0,F.map)(({to:c})=>c==="ready"),(0,F.filterChanged)());this.subscription.add((0,F.merge)(l,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,(0,F.observableFrom)(["init"])).subscribe(()=>{let c=t.autoVideoTrackSwitching.getState(),h=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:c?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(h)})),this.subscription.add((0,F.merge)(l,this.player.state$.stateChangeEnded$,(0,F.observableFrom)(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let p=(0,F.merge)(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,F.observableFrom)(["init"])).pipe((0,F.debounce)(0));this.subscription.add(p.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?aa:ra,t=this.params.tuning.useNewAutoSelectVideoTrack?cn:ln,i=this.params.tuning.useNewAutoSelectVideoTrack?Rt:un,{desiredState:r,output:s}=this.params,n=r.autoVideoTrackSwitching.getState(),u=r.videoTrack.getState()?.id,o=[...this.videoTracksMap.keys()].find(({id:D})=>D===u),l=s.currentVideoTrack$.getValue(),p=r.videoStream.getState()??(o&&this.videoTracksMap.get(o)?.stream)??this.videoStreamsMap.size===1?this.videoStreamsMap.keys().next().value:void 0;if(!p)return;let c=[...this.videoStreamsMap.keys()].find(({id:D})=>D===p.id),d=c&&this.videoStreamsMap.get(c);if(!d)return;let h=De(this.video.buffered,this.video.currentTime*1e3),m;this.player.isActiveLive$.getValue()?m=this.player.isLowLatency$.getValue()?this.params.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.params.tuning.dashCmafLive.normalizedLiveMinBufferSize:this.player.isLive$.getValue()?m=this.params.tuning.dashCmafLive.normalizedTargetMinBufferSize:m=n?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;let b=(this.video.duration*1e3||1/0)-this.video.currentTime*1e3,S=Math.min(h/Math.min(m,b||1/0),1),v=r.audioStream.getState()??(this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0),I=[...this.audioStreamsMap.keys()].find(({id:D})=>D===v?.id)??this.audioStreamsMap.keys().next().value,P=0;if(I){if(o&&!n){let D=e(o,d,this.audioStreamsMap.get(I)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);P=Math.max(P,D?.bitrate??-1/0)}if(l){let D=e(l,d,this.audioStreamsMap.get(I)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);P=Math.max(P,D?.bitrate??-1/0)}}let x=o;(n||!x)&&(x=i(d,{container:this.elementSizeManager.getValue(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.stallsManager.abrTuningParams,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:P,forwardBufferHealth:S,current:l,visible:this.params.output.elementVisible$.getValue(),history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,stallsVideoMaxQualityLimit:this.stallsManager.videoMaxQualityLimit,stallsPredictedThroughput:this.stallsManager.predictedThroughput,abrLogger:this.params.dependencies.abrLogger}));let C=I&&t(x,d,this.audioStreamsMap.get(I)??[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.stallsManager.abrTuningParams,forwardBufferHealth:S,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),V=this.videoTracksMap.get(x)?.representation,O=C&&this.audioTracksMap.get(C)?.representation;if(V&&O)return[V,O];if(V&&!O&&this.audioTracksMap.size===0)return[V,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){Qe(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),B(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:F.ErrorCategory.DOM,thrown:e}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.stallsManager.destroy(),this.elementSizeManager.destroy(),this.destroy3DScene(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),this.params.output.currentVideoStream$.next(void 0),He(this.video),this.tracer.end()}};var Wa=class extends $i{subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();i(t.timeUpdate$,e.position$),i(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}};var ce=require("@vkontakte/videoplayer-shared");var Qa=class extends $i{constructor(e){super(e),this.textTracksManager.destroy()}subscribe(){super.subscribe();let e=!1,t=-1,{output:i,observableVideo:r,desiredState:s,connect:n}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canPlayLiveTailBuffer$.next(!0),n(r.timeUpdate$,i.liveBufferTime$),n(this.player.liveSeekableDuration$,i.duration$),n(this.player.liveLatency$,i.liveLatency$);let u=new ce.ValueSubject(1);n(r.playbackRateState$,u),this.params.tuning.dashCmafLive.catchupLiveForMutedInactiveTab&&this.subscription.add(i.elementVisible$.pipe((0,ce.filterChanged)()).subscribe(o=>{let l=i.position$.getValue(),p=i.volume$.getValue(),c=!p.volume||p.muted;!o&&!l&&c?e=!0:o&&e&&(this.seek(0),e=!1)})),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(s.isLowLatency.stateChangeEnded$.pipe((0,ce.map)(o=>o.to)).subscribe(this.player.isLowLatency$)).add((0,ce.combine)({liveBufferTime:i.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe((0,ce.map)(({liveBufferTime:o,liveAvailabilityStartTime:l})=>o&&l?o+l:void 0)).subscribe(i.liveTime$)).add((0,ce.combine)({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:(0,ce.merge)(r.playbackRateState$,new ce.ValueSubject(1))}).pipe((0,ce.filter)(({liveStreamStatus:o,liveDuration:l})=>o==="active"&&!!l)).subscribe(({liveDuration:o,playbackRate:l})=>{let p=i.liveBufferTime$.getValue(),c=i.position$.getValue(),{playbackCatchupSpeedup:d}=this.params.tuning.dashCmafLive.lowLatency;c||l<1-d||this.video.paused||(0,ce.isNullable)(p)||(t=o-p)})).add((0,ce.combine)({time:i.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:(0,ce.merge)(r.playbackRateState$,new ce.ValueSubject(1))}).pipe((0,ce.filterChanged)((o,l)=>this.player.liveStreamStatus$.getValue()==="active"?o.liveDuration===l.liveDuration:o.time===l.time)).subscribe(({time:o,liveDuration:l,playbackRate:p})=>{let c=i.position$.getValue(),{playbackCatchupSpeedup:d}=this.params.tuning.dashCmafLive.lowLatency;if(!c&&!this.video.paused&&p>=1-d||(0,ce.isNullable)(o)||(0,ce.isNullable)(l))return;let h=-1*(l-o-t);i.position$.next(Math.min(h,0))})).add(this.player.currentLiveTextRepresentation$.subscribe(o=>{if(o){let l=_S(o);this.params.output.availableTextTracks$.next([l])}})),this.params.tuning.dashCmafLive.externalStopControl||this.subscription.add(this.player.liveStreamStatus$.pipe((0,ce.filter)(o=>(0,ce.isNonNullable)(o))).subscribe(o=>i.isLiveEnded$.next(o==="unpublished"&&i.position$.getValue()===0)))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,i=Math.trunc(t/1e3<=Math.abs(this.params.output.duration$.getValue())?t:0);this.player.seekLive(i).then(()=>{this.params.output.position$.next(e/1e3)})}};var H=require("@vkontakte/videoplayer-shared");var iv=Q(Oe(),1),Wl=Q(da(),1);var y=require("@vkontakte/videoplayer-shared");var Hn=Q(Oe(),1),Mi=Q(gt(),1),jn=Q(da(),1);var ev=Q(zs(),1);var li=require("@vkontakte/videoplayer-shared");var o$=18,GS=!1;try{GS=j.browser.isSafari&&!!j.browser.safariVersion&&j.browser.safariVersion<=o$}catch(a){console.error(a)}var Fl=class{constructor(e){this.bufferFull$=new li.Subject;this.error$=new li.Subject;this.queue=[];this.currentTask=null;this.destroyed=!1;this.abortRequested=!1;this.completeTask=()=>{try{if(this.currentTask){let e=this.currentTask.signal?.aborted;this.currentTask.callback(!e),this.currentTask=null}this.queue.length&&this.pull()}catch(e){this.error$.next({id:"BufferTaskQueueUnknown",category:li.ErrorCategory.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:e})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(i=>{let r={operation:"append",data:e,signal:t,callback:i};this.queue.push(r),this.pull()})}async remove(e,t,i){return i&&i.aborted?!1:new Promise(r=>{let s={operation:"remove",from:e,to:t,signal:i,callback:r};this.queue.unshift(s),this.pull()})}async abort(e){return new Promise(t=>{let i,r=s=>{this.abortRequested=!1,t(s)};GS&&e?i={operation:"safariAbort",init:e,callback:r}:i={operation:"abort",callback:r};for(let{callback:s}of this.queue)s(!1);this.abortRequested=!0,i&&(this.queue=[i]),this.pull()})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){if((this.buffer.updating||this.currentTask||this.destroyed)&&!this.abortRequested)return;let e=this.queue.shift();if(!e)return;if(e.signal?.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(r){r instanceof DOMException&&r.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):r instanceof DOMException&&r.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:li.ErrorCategory.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:r}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){let{operation:t}=e;switch(t){case"append":this.buffer.appendBuffer(e.data);break;case"remove":this.buffer.remove(e.from/1e3,e.to/1e3);break;case"abort":this.buffer.abort();break;case"safariAbort":{this.buffer.abort(),this.buffer.appendBuffer(e.init);break}default:(0,li.assertNever)(t)}}},zS=Fl;var A=require("@vkontakte/videoplayer-shared");var Nl=Q(gt(),1);var Fn=require("@vkontakte/videoplayer-shared"),Ga=({id:a,width:e,height:t,bitrate:i,fps:r,quality:s,streamId:n})=>{let u=(s?ii(s):void 0)??(0,Fn.videoSizeToQuality)({width:e,height:t});return u&&{id:a,quality:u,bitrate:i,size:{width:e,height:t},fps:r,streamId:n}},YS=({id:a,bitrate:e})=>({id:a,bitrate:e}),KS=({language:a,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:a,label:e}),XS=({language:a,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:a,label:e}),ql=({id:a,language:e,label:t,codecs:i,isDefault:r})=>({id:a,language:e,label:t,codec:(0,Nl.default)(i.split("."),0),isDefault:r}),Ul=({id:a,language:e,label:t,hdr:i,codecs:r})=>({id:a,language:e,hdr:i,label:t,codec:(0,Nl.default)(r.split("."),0)}),Hl=a=>"url"in a,it=a=>a.type==="template";var JS=a=>{a.sort((t,i)=>t.from-i.from);let e=[a[0]];for(let t=1;t<a.length;t++){let{from:i,to:r}=a[t],s=e[e.length-1];s.to>=i?s.to=Math.max(s.to,r):e.push(a[t])}return e},Li=(a,e)=>{for(let t of a)if(e(t))return t;return null},ZS=a=>{let e=!1,t=(0,Fn.throttleFn)(()=>{e=!0},a);return()=>{try{return t(),e}finally{e=!1}}};var Un=require("@vkontakte/videoplayer-shared");var Nn=a=>{let e=[];for(let t=0;t<a.length;t++){let i=Math.floor(a.start(t)*1e3),r=Math.ceil(a.end(t)*1e3);e.push(i,r)}return e};var qn=class{constructor(e,t){this.lastUpdateTs=0;this.lastCallTs=0;this.prevRanges=[];this.subscription=new Un.Subscription;this.mediaSource=e,this.sourceBuffer=t,this.subscription.add((0,Un.fromEvent)(this.sourceBuffer,"updateend").subscribe(()=>this.updateend()))}updateend(){if(!X(this.mediaSource,this.sourceBuffer))return;let{prevRanges:e}=this,t=Nn(this.sourceBuffer.buffered);this.prevRanges=t,this.isRangesRemoved(e,t)&&(this.lastUpdateTs=Date.now())}isRangesRemoved(e,t){if(e.length!==t.length)return!0;for(let i=0;i<e.length;i+=2){let r=e[i],s=e[i+1],n=t[i],u=t[i+1];if(n>r||u<s)return!0}return!1}wasUpdated(){let{lastCallTs:e,lastUpdateTs:t}=this;return this.lastCallTs=Date.now(),e<=t}destroy(){this.subscription.unsubscribe()}};var za=class{constructor(e,t,i,{fetcher:r,tuning:s,getCurrentPosition:n,isActiveLowLatency:u,compatibilityMode:o=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new A.ValueSubject(0);this.currentLowLatencySegmentLength$=new A.ValueSubject(0);this.currentSegmentLength$=new A.ValueSubject(0);this.onLastSegment$=new A.ValueSubject(!1);this.fullyBuffered$=new A.ValueSubject(!1);this.playingRepresentation$=new A.ValueSubject(void 0);this.playingRepresentationInit$=new A.ValueSubject(void 0);this.error$=new A.Subject;this.gaps=[];this.subscription=new A.Subscription;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new ue;this.switchAbortController=new ue;this.destroyAbortController=new ue;this.useSmartRepresentationSwitch=!1;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.sourceBufferBufferedDiff=null;this.startWith=(0,A.abortable)(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);(0,A.assertNonNullable)(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new zS(this.sourceBuffer),this.sourceBufferBufferedDiff=new qn(this.mediaSource,this.sourceBuffer),this.subscription.add((0,A.fromEvent)(this.sourceBuffer,"updateend").subscribe(()=>{this.maintain()})),this.subscription.add((0,A.fromEvent)(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:A.ErrorCategory.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let u=this.getCurrentPosition();if(!this.sourceBuffer||!u||!X(this.mediaSource,this.sourceBuffer))return;let o=Math.min(this.bufferLimit,hr(this.sourceBuffer.buffered)*.8);this.bufferLimit=o;let l=De(this.sourceBuffer.buffered,u),p=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(u,n*2,l<p).catch(c=>{this.handleAsyncError(c,"pruneBuffer")})})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(n=>this.error$.next(n))),yield this.loadInit(t,"high",!0);let i=this.initData.get(t.id),r=this.segments.get(t.id),s=this.parsedInitData.get(t.id);(0,A.assertNonNullable)(i,"No init buffer for starting representation"),(0,A.assertNonNullable)(r,"No segments for starting representation"),i instanceof ArrayBuffer&&(this.searchGaps(r,t),yield this.sourceBufferTaskQueue.append(i,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(s))}.bind(this));this.switchTo=(0,A.abortable)(this.destroyAbortController.signal,async function*(e,t=!1){if(!X(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);(0,A.assertNonNullable)(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if((0,A.isNullable)(s)||(0,A.isNullable)(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),(0,A.assertNonNullable)(r,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!X(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer();else{let n=this.getCurrentPosition();(0,A.isNonNullable)(n)&&!this.isLive&&(this.bufferLimit=1/0,await this.pruneBuffer(n,1/0,!0)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}this.maintain()}}.bind(this));this.switchToOld=(0,A.abortable)(this.destroyAbortController.signal,async function*(e,t=!1){if(!X(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);(0,A.assertNonNullable)(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if((0,A.isNullable)(s)||(0,A.isNullable)(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),(0,A.assertNonNullable)(r,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!X(this.mediaSource,this.sourceBuffer)))if(yield this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer(),this.maintain();else{let n=this.getCurrentPosition();(0,A.isNonNullable)(n)&&(this.isLive||(this.bufferLimit=1/0,await this.pruneBuffer(n,1/0,!0)),this.maintain(n)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}}.bind(this));this.seekLive=(0,A.abortable)(this.destroyAbortController.signal,async function*(e){let t=(0,jn.default)(e,o=>o.representations);if(!this.downloadingRepresentationId||!t.length)return;this.isSeekingLive=!0;for(let o of this.representations.keys()){let l=t.find(d=>d.id===o);l&&this.representations.set(o,l);let p=this.representations.get(o);if(!p||!it(p.segmentReference)){this.isSeekingLive=!1;return}let c=this.getActualLiveStartingSegments(p.segmentReference);this.segments.set(p.id,c)}let i=this.switchingToRepresentationId??this.downloadingRepresentationId,r=this.representations.get(i);(0,A.assertNonNullable)(r,`Representation not found by id ${i}`);let s=this.segments.get(i);(0,A.assertNonNullable)(s,"No segments for starting representation");let n=this.initData.get(i);if((0,A.assertNonNullable)(n,"No init buffer for starting representation"),!(n instanceof ArrayBuffer)){this.isSeekingLive=!1;return}let u=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,yield this.abort(),u&&(yield this.sourceBufferTaskQueue.remove(u.from*1e3,u.to*1e3,this.destroyAbortController.signal)),this.searchGaps(s,r),yield this.sourceBufferTaskQueue.append(n,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this));this.fetcher=r,this.tuning=s,this.compatibilityMode=o,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=u,this.isLive=!!l?.live,this.baseUrls=l?.baseUrls??[],this.initData=new Map(i.map(p=>[p.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(i.map(p=>[p.id,p])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}switchToWithPreviousAbort(e,t=!1){!X(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new ue,(0,A.abortable)(this.switchAbortController.signal,async function*(i,r=!1){this.switchingToRepresentationId=i;let s=this.representations.get(i);(0,A.assertNonNullable)(s,`No such representation ${i}`);let n=this.segments.get(i),u=this.initData.get(i);if((0,A.isNullable)(u)||(0,A.isNullable)(n)?yield this.loadInit(s,"high",!1):u instanceof Promise&&(yield u),n=this.segments.get(i),(0,A.assertNonNullable)(n,"No segments for starting representation"),u=this.initData.get(i),!(!(u instanceof ArrayBuffer)||!this.sourceBuffer||!X(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(u,this.downloadAbortController.signal),r)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=i,yield this.dropBuffer();else{let o=this.getCurrentPosition();(0,A.isNonNullable)(o)&&!this.isLive&&(this.bufferLimit=this.forwardBufferTarget,yield this.pruneBuffer(o,1/0,!0)),this.downloadingRepresentationId=i,this.switchingToRepresentationId=void 0}this.maintain()}}.bind(this))(e,t))}warmUpMediaSource(){!(0,A.isNullable)(this.sourceBuffer)&&!this.sourceBuffer.updating&&(this.sourceBuffer.mode="segments")}async abort(){for(let e of this.activeSegments)this.abortSegment(e.segment);return this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new ue,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if((0,A.isNullable)(e)||(0,A.isNullable)(this.downloadingRepresentationId)||(0,A.isNullable)(this.playingRepresentationId)||(0,A.isNullable)(this.sourceBuffer)||!X(this.mediaSource,this.sourceBuffer)||(0,A.isNonNullable)(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.representations.get(this.playingRepresentationId),r=this.segments.get(this.downloadingRepresentationId),s=this.segments.get(this.playingRepresentationId);if((0,A.assertNonNullable)(t,`No such representation ${this.downloadingRepresentationId}`),(0,A.assertNonNullable)(i,`No such representation ${this.playingRepresentationId}`),(0,A.isNullable)(r)||(0,A.isNullable)(s))return;let n=r.find(d=>e>=d.time.from&&e<d.time.to);(0,A.isNonNullable)(n)&&isFinite(n.time.from)&&isFinite(n.time.to)&&this.currentSegmentLength$.next(n?.time.to-n.time.from);let u=e,o=100;if(this.playingRepresentationId!==this.downloadingRepresentationId){let d=this.getForwardBufferDuration(e),h=Ga(i),m=Ga(t),b=this.useSmartRepresentationSwitch&&this.tuning.dash.useNewRepresentationSwitch&&this.tuning.dash.useSmartRepresentationSwitch&&(0,A.isNonNullable)(h)&&(0,A.isNonNullable)(m)&&(0,A.isHigher)(h.quality,m.quality),S=this.useSmartRepresentationSwitch&&this.tuning.dash.useNewRepresentationSwitch&&this.tuning.dash.useDelayedRepresentationSwitch;if(b||S?u+=Math.min(d,this.tuning.dash.representationSwitchForwardBufferGap):n&&n.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&d>=n.time.to-e+o&&(u=n?n.time.to+o:-1/0),this.tuning.dash.useNewRepresentationSwitch){let I=[...this.segments.entries()].map(([P,x])=>{let C=x.find(V=>e>=V.time.from&&e<V.time.to);return{representationId:P,status:C?.status}}).find(P=>P.status==="fed")?.representationId;I&&(this.playingRepresentationId=I,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)))}}if(isFinite(this.bufferLimit)&&hr(this.sourceBuffer.buffered)>=this.bufferLimit){let d=De(this.sourceBuffer.buffered,e),h=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,d<h).catch(m=>{this.handleAsyncError(m,"pruneBuffer")});return}let p=null;if(!this.activeSegments.size&&(p=this.selectForwardBufferSegments(r,t.segmentReference.type,u),p?.length)){let d="auto";if(this.tuning.dash.useFetchPriorityHints&&n)if((0,Hn.default)(p,n))d="high";else{let h=(0,Mi.default)(p,0);h&&h.time.from-n.time.to>=this.forwardBufferTarget/2&&(d="low")}this.loadSegments(p,t,d).catch(h=>{this.handleAsyncError(h,"loadSegments")})}(!this.preloadOnly&&!this.allInitsLoaded&&n&&n.status==="fed"&&!p?.length&&De(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let c=(0,Mi.default)(r,-1);!this.isLive&&c&&(this.fullyBuffered$.next(c.time.to-e-De(this.sourceBuffer.buffered,e)<o),this.onLastSegment$.next(e-c.time.from>0))}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}searchGaps(e,t){this.gaps=[];let i=0,r=this.isLive?this.liveInitialAdditionalOffset:0;for(let s of e)Math.trunc(s.time.from-i)>0&&this.gaps.push({representation:t.id,from:i,to:s.time.from+r,persistent:!0}),i=s.time.to;(0,A.isNonNullable)(t.duration)&&t.duration-i>0&&!this.isLive&&this.gaps.push({representation:t.id,from:i,to:t.duration,persistent:!0})}getActualLiveStartingSegments(e){let t=e.segments,i=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,r=[],s=0,n=t.length-1;do r.unshift(t[n]),s+=t[n].time.to-t[n].time.from,n--;while(s<i&&n>=0);return this.liveInitialAdditionalOffset=s-i,this.isActiveLowLatency()?[r[0]]:r}getLiveSegmentsToLoadState(e){let t=e?.streams[this.kind];if(!t)return;let i=(0,jn.default)(t,s=>s.representations).find(s=>s.id===this.downloadingRepresentationId);if(!i)return;let r=this.segments.get(i.id);if(r?.length)return{from:r[0].time.from,to:r[r.length-1].time.to}}updateLive(e){if(!e||[...this.segments.values()].every(i=>!i.length))return;let t=(0,jn.default)(e.streams[this.kind],i=>i.representations)??[];for(let i of t){if(!i||!it(i.segmentReference))return;let r=i.segmentReference.segments.map(l=>({...l,status:"none",size:void 0})),s=100,n=this.segments.get(i.id)??[],u=(0,Mi.default)(n,-1)?.time.to??0,o=r?.findIndex(l=>u>=l.time.from+s&&u<=l.time.to+s);if(o===-1){this.liveUpdateSegmentIndex=0;let l=this.getActualLiveStartingSegments(i.segmentReference);this.segments.set(i.id,l)}else{let l=r.slice(o+1);this.segments.set(i.id,[...n,...l])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;(0,A.assertNonNullable)(e);let t=this.segments.get(e);if(t?.length){let i=t[t.length-1];this.updateLowLatencyLiveIfNeeded(i)}}setSmartRepresentationSwitch(e){this.useSmartRepresentationSwitch=e}updateLowLatencyLiveIfNeeded(e){let t=0;for(let i of this.representations.values()){let r=i.segmentReference;if(!it(r))return;let s=this.segments.get(i.id);if(!s)continue;let n=s.find(o=>Math.floor(o.time.from)===Math.floor(e.time.from));if(n&&!isFinite(n.time.to)&&(n.time.to=e.time.to,t=n.time.to-n.time.from),!!!s.find(o=>Math.floor(o.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let o=Math.round(e.time.to*r.timescale/1e3).toString(10),l=vt(r.segmentTemplateUrl,{segmentTime:o});s.push({status:"none",time:{from:e.time.to,to:1/0},url:l})}}this.currentLowLatencySegmentLength$.next(t)}findSegmentStartTime(e){let t=this.switchingToRepresentationId??this.downloadingRepresentationId??this.playingRepresentationId;if(!t)return;let i=this.segments.get(t);return i?i.find(s=>s.time.from<=e&&s.time.to>=e)?.time.from??void 0:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),this.sourceBufferTaskQueue?.destroy(),this.sourceBufferBufferedDiff?.destroy(),this.gapDetectionIdleCallback&&Lt&&Lt(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&Lt&&Lt(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer)try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(e){if(!(e instanceof DOMException&&e.name==="NotFoundError"))throw e}this.sourceBuffer=null,this.downloadAbortController.abort(),this.switchAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,i){return this.checkEjectedSegments(),this.isLive?this.selectForwardBufferSegmentsLive(e,i):this.selectForwardBufferSegmentsRecord(e,t,i)}selectForwardBufferSegmentsLive(e,t){if(this.playingRepresentationId!==this.downloadingRepresentationId){let i=e.findIndex(r=>t>=r.time.from&&t<r.time.to);this.liveUpdateSegmentIndex=i}return this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):null}selectForwardBufferSegmentsRecord(e,t,i){let r=this.getForwardBufferDuration(i),s=e.findIndex(({status:d,time:{from:h,to:m}},b)=>{let S=h<=i&&m>=i,v=h>i||S||b===0&&i===0,I=Math.min(this.forwardBufferTarget,this.bufferLimit),P=this.preloadOnly&&h<=i+I||r<I&&m-h>=I||m<=i+I;return(d==="none"||d==="partially_ejected"&&v&&P&&this.sourceBuffer&&X(this.mediaSource,this.sourceBuffer)&&!(Ce(this.sourceBuffer.buffered,h)&&Ce(this.sourceBuffer.buffered,m)))&&v&&P});if(s===-1)return null;if(t!=="byteRange")return e.slice(s,s+1);let n=e,u=0,o=0,l=[],p=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,c=this.preloadOnly?this.forwardBufferTarget:0;for(let d=s;d<n.length&&(u<=p||o<=c);d++){let h=n[d];if(u+=h.byte.to+1-h.byte.from,o+=h.time.to+1-h.time.from,h.status==="none"||h.status==="partially_ejected")l.push(h);else break}return l}async loadSegments(e,t,i="auto"){it(t.segmentReference)?await this.loadTemplateSegment(e[0],t,i):await this.loadByteRangeSegments(e,t,i)}async loadTemplateSegment(e,t,i="auto"){e.status="downloading";let r={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(r);let{range:s,url:n,signal:u,onProgress:o,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&u&&(await(0,A.abortable)(u,async function*(){let p=(0,A.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>setTimeout(c,p))}.bind(this))(),u.aborted&&this.abortActiveSegments([e]));try{let p=await this.fetcher.fetch(n,{range:s,signal:u,onProgress:o,priority:i,isLowLatency:this.isActiveLowLatency(),bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation});if(this.lastDataObtainedTimestampMs=(0,A.now)(),!p)return;let c=new DataView(p),d=Mt(t.mime);if(!isFinite(r.segment.time.to)){let b=t.segmentReference.timescale;r.segment.time.to=d.getChunkEndTime(c,b)}o&&r.feedingBytes&&l?await Promise.all(l):await this.sourceBufferTaskQueue.append(c,u);let{serverDataReceivedTimestamp:h,serverDataPreparedTime:m}=d.getServerLatencyTimestamps(c);h&&m&&this.currentLiveSegmentServerLatency$.next(m-h),r.segment.status="downloaded",this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(p){this.abortActiveSegments([e]),Dt(p)||(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())it(t.segmentReference)?t.segmentReference.baseUrl=e:t.segmentReference.url=e}async loadByteRangeSegments(e,t,i="auto"){if(!e.length)return;for(let o of e)o.status="downloading",this.activeSegments.add({segment:o,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:r,url:s,signal:n,onProgress:u}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(await(0,A.abortable)(n,async function*(){let o=(0,A.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,o),(0,A.fromEvent)(window,"online").pipe((0,A.once)()).subscribe(()=>{l(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(s,{range:r,onProgress:u,signal:n,priority:i,bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation}),this.lastDataObtainedTimestampMs=(0,A.now)(),this.failedDownloads=0}catch(o){this.abortActiveSegments(e),Dt(o)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}prepareByteRangeFetchSegmentParams(e,t){if(it(t.segmentReference))throw new Error("Representation is not byte range type");let i=t.segmentReference.url,r={from:(0,Mi.default)(e,0).byte.from,to:(0,Mi.default)(e,-1).byte.to},{signal:s}=this.downloadAbortController;return{url:i,range:r,signal:s,onProgress:async(u,o)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=(0,A.now)(),await this.onSomeByteRangesDataLoaded({dataView:u,loaded:o,signal:s,onSegmentAppendFailed:()=>this.abort(),globalFrom:r?r.from:0,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:A.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!it(t.segmentReference))throw new Error("Representation is not template type");let i=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&i.searchParams.set("low-latency","yes");let r=i.toString(),{signal:s}=this.downloadAbortController,n=[],o=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(l,p)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=(0,A.now)();let c=this.onSomeTemplateDataLoaded({dataView:l,loaded:p,signal:s,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(c)}catch(c){this.error$.next({id:"SegmentFeeding",category:A.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:c})}}:void 0;return{url:r,signal:s,onProgress:o,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)(0,Hn.default)(e,t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:r,signal:s}){if(!this.activeSegments.size||!X(this.mediaSource,this.sourceBuffer))return;let n=this.representations.get(t);if(n)for(let u of this.activeSegments){let{segment:o}=u;if(u.representationId===t){if(s.aborted){r();continue}if(u.loadedBytes=i,u.loadedBytes>u.feedingBytes){let l=new DataView(e.buffer,e.byteOffset+u.feedingBytes,u.loadedBytes-u.feedingBytes),p=Mt(n.mime).parseFeedableSegmentChunk(l,this.isLive);p?.byteLength&&(o.status="partially_fed",u.feedingBytes+=p.byteLength,await this.sourceBufferTaskQueue.append(p),u.fedBytes+=p.byteLength)}}}}async onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:s,onSegmentAppendFailed:n}){if(!this.activeSegments.size||!X(this.mediaSource,this.sourceBuffer))return;let u=this.representations.get(t);if(u)for(let o of this.activeSegments){if(o.representationId!==t)continue;if(s.aborted){await n();continue}let{segment:l}=o,p=l.byte.from-i,c=l.byte.to-i,d=c-p+1,h=p<r,m=c<=r;if(h){if(l.status==="downloading"&&m){l.status="downloaded";let b=new DataView(e.buffer,e.byteOffset+p,d);await this.sourceBufferTaskQueue.append(b,s)&&!s.aborted?this.onSegmentFullyAppended(o,t):await n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(l.status==="downloading"||l.status==="partially_fed")&&(o.loadedBytes=Math.min(d,r-p),o.loadedBytes>o.feedingBytes)){let b=new DataView(e.buffer,e.byteOffset+p+o.feedingBytes,o.loadedBytes-o.feedingBytes),S=o.loadedBytes===d?b:Mt(u.mime).parseFeedableSegmentChunk(b);S?.byteLength&&(l.status="partially_fed",o.feedingBytes+=S.byteLength,await this.sourceBufferTaskQueue.append(S,s)&&!s.aborted?(o.fedBytes+=S.byteLength,o.fedBytes===d&&this.onSegmentFullyAppended(o,t)):await n())}}}}onSegmentFullyAppended(e,t){if(!((0,A.isNullable)(this.sourceBuffer)||!X(this.mediaSource,this.sourceBuffer))){!this.isLive&&j.browser.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(Ce(this.sourceBuffer.buffered,e.segment.time.from,100)&&Ce(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:A.ErrorCategory.VIDEO_PIPELINE,message:"Browser 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",Hl(e.segment)&&(e.segment.size=e.fedBytes);for(let i of this.representations.values()){if(i.id===t)continue;let r=this.segments.get(i.id);if(r)for(let s of 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")}this.isActiveLowLatency()&&this.updateLowLatencyLiveIfNeeded(e.segment),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,e.segment)}}abortSegment(e){e.status==="partially_fed"?e.status="partially_ejected":e.status!=="partially_ejected"&&(e.status="none");for(let t of this.activeSegments.values())if(t.segment===e){this.activeSegments.delete(t);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(let[r,s]of this.initData.entries()){let n=s instanceof Promise;t||=n,s===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let i=this.representations.get(e);i&&(this.initLoadIdleCallback=pr(()=>(0,ev.default)(this.loadInit(i,"low",!1),()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",i=!1){let r=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!i&&this.failedDownloads>0?(0,A.abortable)(this.destroyAbortController.signal,async function*(){let u=(0,A.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(o=>setTimeout(o,u))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,Mt(e.mime),r)).then(u=>{if(!u)return;let{init:o,dataView:l,segments:p}=u,c=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,c);let d=p;this.isLive&&it(e.segmentReference)&&(d=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,d),o&&this.parsedInitData.set(e.id,o)}).then(()=>this.failedDownloads=0,u=>{this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:A.ErrorCategory.WTF,message:"loadInit threw",thrown:u})});return this.initData.set(e.id,n),n}async dropBuffer(){for(let e of this.segments.values())for(let t of e)t.status="none";await this.pruneBuffer(0,1/0,!0)}async pruneBuffer(e,t,i=!1){if(!this.sourceBuffer||!X(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||(0,A.isNullable)(e))return!1;this.checkEjectedSegments();let r=[],s=0,n=u=>{if(s>=t)return;r.push({...u.time});let o=Hl(u)?u.size??0:u.byte.to-u.byte.from;s+=o};for(let u of this.segments.values())for(let o of u){let l=o.time.to<=e-this.tuning.dash.bufferPruningSafeZone,p=o.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(l||p)&&o.status==="fed"&&n(o)}for(let u=0;u<this.sourceBuffer.buffered.length;u++){let o=this.sourceBuffer.buffered.start(u)*1e3,l=this.sourceBuffer.buffered.end(u)*1e3,p=0;for(let c of this.segments.values())for(let d of c)(0,Hn.default)(["none","partially_ejected"],d.status)&&Math.round(d.time.from)<=Math.round(o)&&Math.round(d.time.to)>=Math.round(l)&&p++;if(p===this.segments.size){let c={time:{from:o,to:l},url:"",status:"none"};n(c)}}if(r.length&&i){let u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let o of this.segments.values())for(let l of o)l.time.from>=e+u&&l.status==="fed"&&n(l)}return r.length?(r=JS(r),(await Promise.all(r.map(o=>this.sourceBufferTaskQueue.remove(o.from,o.to)))).reduce((o,l)=>o||l,!1)):!1}async abortBuffer(){if(!this.sourceBuffer||!X(this.mediaSource,this.sourceBuffer))return!1;let e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;return this.sourceBufferTaskQueue.abort(t)}getDebugBufferState(){if(!(!this.sourceBuffer||!X(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}getBufferedTo(){return!this.sourceBuffer||!X(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length?null:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}getForwardBufferDuration(e=this.getCurrentPosition()){return!this.sourceBuffer||!X(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||(0,A.isNullable)(e)?0:De(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!this.sourceBuffer||!X(this.mediaSource,this.sourceBuffer))return;let{buffered:i}=this.sourceBuffer,r={representation:e,from:t.time.from,to:t.time.to,persistent:!1};for(let s=0;s<i.length;s++){let n=i.start(s)*1e3,u=i.end(s)*1e3;if(!(u<=t.time.from||n>=t.time.to)){if(n<=t.time.from&&u>=t.time.to){r=void 0;break}u>t.time.from&&u<t.time.to&&(r.from=u),n<t.time.to&&n>t.time.from&&(r.to=n)}}r&&r.to-r.from>1&&!this.gaps.some(s=>r&&s.from===r.from&&s.to===r.to)&&this.gaps.push(r)}detectGapsWhenIdle(e,t){if(this.gapDetectionIdleCallback||!this.sourceBuffer||!X(this.mediaSource,this.sourceBuffer))return;let{buffered:i}=this.sourceBuffer;this.gaps=this.gaps.filter(r=>{if(r.persistent)return!0;let s=Math.round(r.from),n=Math.round(r.to);for(let u=0;u<i.length;u++)if(s>=Math.round(i.start(u)*1e3)&&n<=Math.round(i.end(u)*1e3))return!1;return!0}),this.gapDetectionIdleCallback=pr(()=>{try{this.detectGaps(e,t)}catch(r){this.error$.next({id:"GapDetection",category:A.ErrorCategory.WTF,message:"detectGaps threw",thrown:r})}finally{this.gapDetectionIdleCallback=null}})}checkEjectedSegments(){if((0,A.isNullable)(this.sourceBuffer)||!X(this.mediaSource,this.sourceBuffer)||(0,A.isNullable)(this.playingRepresentationId)||this.sourceBufferBufferedDiff&&!this.sourceBufferBufferedDiff.wasUpdated())return;let e=Nn(this.sourceBuffer.buffered),t=100;for(let i of this.segments.values())for(let r of i){let{status:s}=r;if(s!=="fed"&&s!=="partially_ejected")continue;let n=Math.floor(r.time.from),u=Math.ceil(r.time.to),o=!1,l=0;for(let p=0;p<e.length;p+=2){let c=e[p],d=e[p+1];o||(o=c-t<=n&&d+t>=u),(n>=c&&n<d-t||u>c+t&&u<=d)&&(l+=1)}o||(l===1?r.status="partially_ejected":this.gaps.some(p=>p.from===r.time.from||p.to===r.time.to)?r.status="partially_ejected":r.status="none")}}handleAsyncError(e,t){this.error$.next({id:t,category:A.ErrorCategory.VIDEO_PIPELINE,thrown:e,message:"Something went wrong"})}calculateDurationFromSegments(){if(!this.playingRepresentationId)return 0;let e=this.segments.get(this.playingRepresentationId);return(e?(0,Mi.default)(e,-1)?.time.to:0)||0}};var z=require("@vkontakte/videoplayer-shared");var Qn=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:s=!1}){this.manifestRequested$=new z.Subject;this.firstBytesManifest$=new z.Subject;this.manifestReceived$=new z.Subject;this.firstBytesRequested$=new z.Subject;this.firstBytesReceived$=new z.Subject;this.lastConnectionType$=new z.ValueSubject(void 0);this.lastConnectionReused$=new z.ValueSubject(void 0);this.lastRequestFirstBytes$=new z.ValueSubject(void 0);this.recoverableError$=new z.Subject;this.error$=new z.Subject;this.abortAllController=new ue;this.subscription=new z.SubscriptionRemovable;this.fetchManifest=(0,z.abortable)(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=ni(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=Tn(i)),this.manifestRequested$.next();let r=yield this.doFetch(i,{signal:this.abortAllController.signal},"manifest").catch(Wn);return r?(t.log("success",(0,z.flattenObject)({url:i,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(r.headers),this.manifestReceived$.next(),r.text()):(t.error("error",(0,z.flattenObject)({url:i,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=(0,z.abortable)(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:i,onProgress:r,priority:s="auto",signal:n,measureThroughput:u=!0,isLowLatency:o=!1,bufferOptimisation:l=!1}={}){let p=e,c=new Headers,d=this.tracer.createComponentTracer("Fetch");if(i)switch(t){case 0:{c.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let R=new URL(p,location.href);R.searchParams.append("bytes",`${i.from}-${i.to}`),p=R.toString();break}default:(0,z.assertNever)(t)}this.requestQuic&&(p=ni(p));let h=this.abortAllController.signal,m;if(n){let R=new ue;if(m=(0,z.merge)((0,z.fromEvent)(this.abortAllController.signal,"abort"),(0,z.fromEvent)(n,"abort")).subscribe(()=>{try{R.abort()}catch(k){Wn(k)}}),this.subscription.add(m),this.abortAllController.signal.aborted||n.aborted)try{R.abort()}catch(k){Wn(k)}h=R.signal}let b=0,S=(0,z.now)();d.log("startRequest",(0,z.flattenObject)({url:p,priority:s,rangeMethod:t,range:i,isLowLatency:o,requestStartedAt:S})),this.firstBytesRequested$.next();let v=yield this.doFetch(p,{priority:s,headers:c,signal:h}),I=(0,z.now)();if(!v)return d.error("error",{message:"No response in request"}),d.end(),this.unsubscribeAbortSubscription(m),null;if(this.throughputEstimator?.addRawRtt(I-S),!v.ok||!v.body){this.unsubscribeAbortSubscription(m);let R=`Fetch error ${v.status}: ${v.statusText}`;return d.error("error",{message:R}),d.end(),Promise.reject(new Error(`Fetch error ${v.status}: ${v.statusText}`))}if(this.onHeadersReceived(v.headers),!r&&!u){this.unsubscribeAbortSubscription(m);let R=(0,z.now)(),k={requestStartedAt:S,requestEndedAt:R,duration:R-S};return d.log("endRequest",(0,z.flattenObject)(k)),d.end(),v.arrayBuffer()}let P=v.body;if(u){let R;[P,R]=v.body.tee(),this.throughputEstimator?.trackStream(R,o)}let x=P.getReader(),C,V=parseInt(v.headers.get("content-length")??"",10);Number.isFinite(V)&&(C=V),!C&&i&&(C=i.to-i.from+1);let O=C?new Uint8Array(C):new Uint8Array(0),D=!1,N=R=>{this.unsubscribeAbortSubscription(m),D=!0,Wn(R)},L=(0,z.abortable)(h,async function*({done:R,value:k}){if(b===0&&(this.lastRequestFirstBytes$.next((0,z.now)()-S),this.firstBytesReceived$.next()),h.aborted){this.unsubscribeAbortSubscription(m);return}if(!R&&k){if(l&&C)O.set(k,b),b+=k.byteLength;else{let te=new Uint8Array(O.length+k.length);te.set(O),te.set(k,O.length),O=te,b+=k.byteLength}r?.(new DataView(O.buffer),b),yield x?.read().then(L,N)}}.bind(this));yield x?.read().then(L,N),this.unsubscribeAbortSubscription(m);let ee=(0,z.now)(),W={failed:D,requestStartedAt:S,requestEndedAt:ee,duration:ee-S};return D?(d.error("endRequest",(0,z.flattenObject)(W)),d.end(),null):(d.log("endRequest",(0,z.flattenObject)(W)),d.end(),O.buffer)}.bind(this));this.fetchByteRangeRepresentation=(0,z.abortable)(this.abortAllController.signal,async function*(e,t,i){if(e.type!=="byteRange")return null;let{from:r,to:s}=e.initRange,n=r,u=s,o=!1,l,p;e.indexRange&&(l=e.indexRange.from,p=e.indexRange.to,o=s+1===l,o&&(n=Math.min(l,r),u=Math.max(p,s))),n=Math.min(n,0);let c=yield this.fetch(e.url,{range:{from:n,to:u},priority:i,measureThroughput:!1});if(!c)return null;let d=new DataView(c,r-n,s-n+1);if(!t.validateData(d))throw new Error("Invalid media file");let h=t.parseInit(d),m=e.indexRange??t.getIndexRange(h);if(!m)throw new ReferenceError("No way to load representation index");let b;if(o)b=new DataView(c,m.from-n,m.to-m.from+1);else{let v=yield this.fetch(e.url,{range:m,priority:i,measureThroughput:!1});if(!v)return null;b=new DataView(v)}let S=t.parseSegments(b,h,m);return{init:h,dataView:new DataView(c),segments:S}}.bind(this));this.fetchTemplateRepresentation=(0,z.abortable)(this.abortAllController.signal,async function*(e,t){if(e.type!=="template")return null;let i=new URL(e.initUrl,e.baseUrl).toString(),r=yield this.fetch(i,{priority:t,measureThroughput:!1});return r?{init:null,segments:e.segments.map(n=>({...n,status:"none",size:void 0})),dataView:new DataView(r)}:null}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=r,this.tracer=i.createComponentTracer("Fetcher"),this.useEnableSubtitlesParam=s}onHeadersReceived(e){let{type:t,reused:i}=yn(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}async fetchRepresentation(e,t,i="auto"){let{type:r}=e;switch(r){case"byteRange":return await this.fetchByteRangeRepresentation(e,t,i)??null;case"template":return await this.fetchTemplateRepresentation(e,i)??null;default:(0,z.assertNever)(r)}}destroy(){this.abortAllController.abort(),this.tracer.end(),this.subscription.unsubscribe()}async doFetch(e,t,i){let r=await lt(e,t);if(r.ok)return i==="manifest"&&this.firstBytesManifest$.next(),r;let s=await r.text(),n=parseInt(s);if(!isNaN(n))switch(n){case 1:this.recoverableError$.next({id:"VideoDataLinkExpiredError",message:"Video data links have expired",category:z.ErrorCategory.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:z.ErrorCategory.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:z.ErrorCategory.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:z.ErrorCategory.FATAL});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${n})`,category:z.ErrorCategory.FATAL})}}unsubscribeAbortSubscription(e){e&&(e.unsubscribe(),this.subscription.remove(e))}},Wn=a=>{if(!Dt(a))throw a};var Gn=require("@vkontakte/videoplayer-shared");var Ya=class a{constructor(e,t){this.currentRepresentation$=new Gn.ValueSubject(null);this.maxRepresentations=4;this.representationsCursor=0;this.representations=[];this.currentSegment=null;this.getCurrentPosition=t.getCurrentPosition,this.processStreams(e)}updateLive(e){this.processStreams(e?.streams.text)}seekLive(e){this.processStreams(e)}maintain(e=this.getCurrentPosition()){if(!(0,Gn.isNullable)(e))for(let t of this.representations)for(let i of t){let r=i.segmentReference,s=r.segments.length,n=r.segments[0].time.from,u=r.segments[s-1].time.to;if(e<n||e>u)continue;let o=r.segments.find(l=>l.time.from<=e&&l.time.to>=e);!o||this.currentSegment?.time.from===o.time.from&&this.currentSegment.time.to===o.time.to||(this.currentSegment=o,this.currentRepresentation$.next({...i,label:"Live Text",language:"ru",isAuto:!0,url:new URL(o.url,r.baseUrl).toString()}))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e??[]){let i=a.filterRepresentations(t.representations);if(i){this.representations[this.representationsCursor]=i,this.representationsCursor=(this.representationsCursor+1)%this.maxRepresentations;break}}}static isSupported(e){return!!e?.some(t=>a.filterRepresentations(t.representations))}static filterRepresentations(e){return e?.filter(t=>t.kind==="text"&&"segmentReference"in t&&it(t.segmentReference))}};var c$=["progress","play","seeked","stalled","waiting"],d$=["timeupdate","progress","loadeddata","playing","seeked"];var zn=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.bufferManagers=[];this.subscription=new y.Subscription;this.subscriptionRemovable=new y.SubscriptionRemovable;this.representationSubscription=new y.Subscription;this.state$=new Z("none");this.currentVideoRepresentation$=new y.ValueSubject(void 0);this.currentVideoRepresentationInit$=new y.ValueSubject(void 0);this.currentAudioRepresentation$=new y.ValueSubject(void 0);this.currentVideoSegmentLength$=new y.ValueSubject(0);this.currentAudioSegmentLength$=new y.ValueSubject(0);this.error$=new y.Subject;this.manifestRequested$=new y.Subject;this.firstBytesManifest$=new y.Subject;this.manifestReceived$=new y.Subject;this.firstBytesRequested$=new y.Subject;this.firstBytesReceived$=new y.Subject;this.lastConnectionType$=new y.ValueSubject(void 0);this.lastConnectionReused$=new y.ValueSubject(void 0);this.lastRequestFirstBytes$=new y.ValueSubject(void 0);this.currentLiveTextRepresentation$=new y.ValueSubject(null);this.isLive$=new y.ValueSubject(!1);this.isActiveLive$=new y.ValueSubject(!1);this.isLowLatency$=new y.ValueSubject(!1);this.liveDuration$=new y.ValueSubject(0);this.liveSeekableDuration$=new y.ValueSubject(0);this.liveAvailabilityStartTime$=new y.ValueSubject(0);this.liveStreamStatus$=new y.ValueSubject(void 0);this.bufferLength$=new y.ValueSubject(0);this.liveLatency$=new y.ValueSubject(void 0);this.liveLoadBufferLength$=new y.ValueSubject(0);this.livePositionFromPlayer$=new y.ValueSubject(0);this.currentStallDuration$=new y.ValueSubject(0);this.videoLastDataObtainedTimestamp$=new y.ValueSubject(0);this.fetcherRecoverableError$=new y.Subject;this.fetcherError$=new y.Subject;this.liveStreamEndTimestamp=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.forceEnded$=new y.Subject;this.gapWatchdogActive=!1;this.destroyController=new ue;this.initManifest=(0,y.abortable)(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=ye(t,i,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),this.manifest?.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:y.ErrorCategory.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=(0,y.abortable)(this.destroyController.signal,async function*(){this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(o=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:y.ErrorCategory.NETWORK,message:"Failed to load manifest",thrown:o})});if(!e)return null;let t=null;try{t=gn(e??"",this.manifestUrlString)}catch(o){let l=mn(e)??{id:"ManifestParsing",category:y.ErrorCategory.PARSER,message:"Failed to parse MPD manifest",thrown:o};this.error$.next(l)}if(!t)return null;let i=(o,l,p)=>!!(this.element?.canPlayType?.(l)&&Ze()?.isTypeSupported?.(`${l}; codecs="${p}"`)||o==="text");if(t.live){this.isLive$.next(!!t.live);let{availabilityStartTime:o,latestSegmentPublishTime:l,streamIsUnpublished:p,streamIsAlive:c}=t.live,d=(t.duration??0)/1e3;this.liveSeekableDuration$.next(-1*d),this.liveDuration$.next((l-o)/1e3),this.liveAvailabilityStartTime$.next(t.live.availabilityStartTime);let h="active";c||(h=p?"unpublished":"unexpectedly_down"),this.liveStreamStatus$.next(h)}let r={text:t.streams.text,video:[],audio:[]},s,n;for(let o of["video","audio"]){let p=t.streams[o].filter(({mime:d,codecs:h})=>i(o,d,h));r[o]=p;let c;if(this.tuning.dash.codecsPrioritizeEnabled){let d=p.map(({codecs:h})=>h);o==="audio"&&(n=Mn(d),c=n[0]),o==="video"&&(s=Ln(d),this.forceVideoCodec&&(0,iv.default)(s,this.forceVideoCodec)?c=this.forceVideoCodec:c=s[0]),c&&(r[o]=p.filter(({codecs:h})=>vr(h)===c))}else{let d=new Set(p.map(({codecs:h})=>h));c=$n(d),c&&(r[o]=p.filter(({codecs:h})=>h.startsWith(c)))}if(o==="video"){let d=this.tuning.preferHDR,h=r.video.some(b=>b.hdr),m=r.video.some(b=>!b.hdr);j.display.isHDR&&d&&h?r.video=r.video.filter(b=>b.hdr):m&&(r.video=r.video.filter(b=>!b.hdr))}}let u={...t,streams:r};return this.tuning.dash.codecsPrioritizeEnabled&&(u.codecs={video:s,audio:n}),this.tracer.log("updateManifestEnd",(0,y.flattenObject)(u)),u}.bind(this));this.initRepresentations=(0,y.abortable)(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initRepresentationsStart",(0,y.flattenObject)({initialVideo:e,initialAudio:t,sourceHls:i})),(0,y.assertNonNullable)(this.manifest),(0,y.assertNonNullable)(this.element),this.representationSubscription.unsubscribe(),this.representationSubscription=new y.Subscription,this.state$.startTransitionTo("representations_ready");let r=d=>{this.representationSubscription.add((0,y.fromEvent)(d,"error").pipe((0,y.filter)(h=>!!this.element?.played.length)).subscribe(h=>{this.error$.next({id:"VideoSource",category:y.ErrorCategory.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:h})}))};this.source=Js();let s=document.createElement("source");if(r(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),sr())if(i){let d=document.createElement("source");r(d),d.type="application/x-mpegurl",d.src=i.url,this.element.appendChild(d)}else this.element.disableRemotePlayback=!0;this.isActiveLive$.next(this.isLive$.getValue());let n={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),manifest:this.manifest},u=this.manifest.streams.video.reduce((d,h)=>[...d,...h.representations],[]);if(this.videoBufferManager=new za("video",this.source,u,n),this.bufferManagers=[this.videoBufferManager],(0,y.isNonNullable)(t)){let d=this.manifest.streams.audio.reduce((h,m)=>[...h,...m.representations],[]);this.audioBufferManager=new za("audio",this.source,d,n),this.bufferManagers.push(this.audioBufferManager)}Ya.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new Ya(this.manifest.streams.text,n)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$));let o=()=>{this.stallWatchdogSubscription?.unsubscribe(),this.currentStallDuration$.next(0)};if(this.representationSubscription.add((0,y.merge)(...d$.map(d=>(0,y.fromEvent)(this.element,d))).pipe((0,y.map)(d=>this.element?De(this.element.buffered,this.element.currentTime*1e3):0),(0,y.filterChanged)(),(0,y.tap)(d=>{d>this.tuning.dash.bufferEmptinessTolerance&&o()})).subscribe(this.bufferLength$)),this.representationSubscription.add((0,y.merge)((0,y.fromEvent)(this.element,"ended"),this.forceEnded$).subscribe(()=>{o()})),this.isLive$.getValue()){this.subscription.add(this.liveDuration$.pipe((0,y.filterChanged)()).subscribe(h=>this.liveStreamEndTimestamp=(0,y.now)())),this.subscription.add((0,y.fromEvent)(this.element,"pause").subscribe(()=>{this.livePauseWatchdogSubscription=(0,y.interval)(1e3).subscribe(h=>{let m=ei(this.manifestUrlString,2);this.manifestUrlString=ye(this.manifestUrlString,m+1e3,2),this.liveStreamStatus$.getValue()==="active"&&this.updateManifest()}),this.subscription.add(this.livePauseWatchdogSubscription)})).add((0,y.fromEvent)(this.element,"play").subscribe(h=>this.livePauseWatchdogSubscription?.unsubscribe())),this.representationSubscription.add((0,y.combine)({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe((0,y.map)(({isActiveLive:h,isLowLatency:m})=>h&&m),(0,y.filterChanged)()).subscribe(h=>{this.isManualDecreasePlaybackInLive()||Sr(this.element,1)})),this.representationSubscription.add((0,y.combine)({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe((0,y.filter)(({bufferLength:h,isActiveLive:m,isLowLatency:b})=>m&&b&&!!h)).subscribe(({bufferLength:h})=>this.liveBuffer.next(h))),this.representationSubscription.add(this.videoBufferManager.currentLowLatencySegmentLength$.subscribe(h=>{if(!this.isActiveLive$.getValue()&&!this.isLowLatency$.getValue()&&!h)return;let m=this.liveSeekableDuration$.getValue()-h/1e3;this.liveSeekableDuration$.next(Math.max(m,-1*this.tuning.dashCmafLive.maxLiveDuration)),this.liveDuration$.next(this.liveDuration$.getValue()+h/1e3)})),this.representationSubscription.add((0,y.combine)({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe((0,y.filter)(({isLive:h})=>h),(0,y.filterChanged)((h,m)=>m.bufferLength<h.bufferLength),(0,y.map)(({rtt:h,bufferLength:m,segmentServerLatency:b})=>{let S=ei(this.manifestUrlString,2);return(h/2+m+b+S)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add((0,y.combine)({liveBuffer:this.liveBuffer.smoothed$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).subscribe(({liveBuffer:h,isActiveLive:m,isLowLatency:b})=>{if(!b||!m)return;let S=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,v=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,I=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,P=h-S;if(this.isManualDecreasePlaybackInLive())return;let x=1;Math.abs(P)>v&&(x=1+Math.sign(P)*I),Sr(this.element,x)})),this.representationSubscription.add(this.bufferLength$.subscribe(h=>{let m=0;if(h){let b=(this.element?.currentTime??0)*1e3;m=Math.min(...this.bufferManagers.map(v=>v.getLiveSegmentsToLoadState(this.manifest)?.to??b))-b}this.liveLoadBufferLength$.getValue()!==m&&this.liveLoadBufferLength$.next(m)}));let d=0;this.representationSubscription.add((0,y.combine)({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe((0,y.throttle)(1e3)).subscribe(async({liveLoadBufferLength:h,bufferLength:m})=>{if(!this.element||this.isUpdatingLive)return;let b=this.element.playbackRate,S=ei(this.manifestUrlString,2),v=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,I=Math.min(v,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*b),P=this.tuning.dashCmafLive.normalizedActualBufferOffset*b,x=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*b,C=isFinite(h)?h:m,V=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),O=v<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next(O);let D="none";if(V?D="active_low_latency":this.isLowLatency$.getValue()&&O?(this.bufferManagers.forEach(N=>N.proceedLowLatencyLive()),D="active_low_latency"):S!==0&&C<I?D="live_forward_buffering":C<I+x&&(D="live_with_target_offset"),isFinite(h)&&(d=h>d?h:d),D==="live_forward_buffering"||D==="live_with_target_offset"){let N=d-(I+P),L=this.normolizeLiveOffset(Math.trunc(S+N/b)),ee=Math.abs(L-S),W=0;!h||ee<=this.tuning.dashCmafLive.offsetCalculationError?W=S:L>0&&ee>this.tuning.dashCmafLive.offsetCalculationError&&(W=L),this.manifestUrlString=ye(this.manifestUrlString,W,2)}(D==="live_with_target_offset"||D==="live_forward_buffering")&&(d=0,await this.updateLive())},h=>{this.error$.next({id:"updateLive",category:y.ErrorCategory.VIDEO_PIPELINE,thrown:h,message:"Failed to update live with subscription"})}))}let l=(0,y.merge)(...this.bufferManagers.map(d=>d.fullyBuffered$)).pipe((0,y.map)(()=>this.bufferManagers.every(d=>d.fullyBuffered$.getValue()))),p=(0,y.merge)(...this.bufferManagers.map(d=>d.onLastSegment$)).pipe((0,y.map)(()=>this.bufferManagers.some(d=>d.onLastSegment$.getValue()))),c=(0,y.combine)({allBuffersFull:l,someBufferEnded:p}).pipe((0,y.filterChanged)(),(0,y.map)(({allBuffersFull:d,someBufferEnded:h})=>d&&h),(0,y.filter)(d=>d));if(this.representationSubscription.add((0,y.merge)(this.forceEnded$,c).subscribe(()=>{if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(d=>!d.updating))try{this.source?.endOfStream()}catch(d){this.error$.next({id:"EndOfStream",category:y.ErrorCategory.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:d})}})),this.representationSubscription.add((0,y.merge)(...this.bufferManagers.map(d=>d.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.representationSubscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&(this.representationSubscription.add(this.audioBufferManager.playingRepresentation$.subscribe(this.currentAudioRepresentation$)),this.representationSubscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$))),this.liveTextManager&&this.representationSubscription.add(this.liveTextManager.currentRepresentation$.subscribe(this.currentLiveTextRepresentation$)),this.source.readyState!=="open"){let d=this.tuning.dash.sourceOpenTimeout>=0;yield new Promise(h=>{d&&(this.timeoutSourceOpenId=setTimeout(()=>{if(this.source?.readyState==="open"){h();return}this.error$.next({id:"OpenOfStream",category:y.ErrorCategory.VIDEO_PIPELINE,message:"Failed to open MediaSource",thrown:new Error("Timeout reject when wait sourceopen event"),traceAsLog:!0})},this.tuning.dash.sourceOpenTimeout)),this.source?.addEventListener("sourceopen",()=>{this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),h()},{once:!0})})}if(!this.isLive$.getValue()){let d=[this.manifest.duration??0,...(0,Wl.default)((0,Wl.default)([...this.manifest.streams.audio,...this.manifest.streams.video],h=>h.representations),h=>{let m=[];return h.duration&&m.push(h.duration),it(h.segmentReference)&&h.segmentReference.totalSegmentsDurationMs&&m.push(h.segmentReference.totalSegmentsDurationMs),m})];this.source.duration=Math.max(...d)/1e3}this.audioBufferManager&&(0,y.isNonNullable)(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState("representations_ready"),this.tracer.log("initRepresentationsEnd")}.bind(this));this.tick=()=>{if(!this.element||!this.videoBufferManager||this.source?.readyState!=="open")return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),this.audioBufferManager?.maintain(e),this.liveTextManager?.maintain(e),(this.videoBufferManager.gaps.length||this.audioBufferManager?.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=(0,y.interval)(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),t=>{this.error$.next({id:"GapWatchdog",category:y.ErrorCategory.WTF,message:"Error handling gaps",thrown:t})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name),this.forceVideoCodec=e.forceVideoCodec,this.fetcher=new Qn({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer,useEnableSubtitlesParam:e.tuning.useEnableSubtitlesParam}),this.subscription.add(this.fetcher.recoverableError$.subscribe(this.fetcherRecoverableError$)),this.subscription.add(this.fetcher.error$.subscribe(this.fetcherError$)),this.subscription.add(this.fetcher.manifestRequested$.subscribe(this.manifestRequested$)),this.subscription.add(this.fetcher.firstBytesManifest$.subscribe(this.firstBytesManifest$)),this.subscription.add(this.fetcher.manifestReceived$.subscribe(this.manifestReceived$)),this.subscription.add(this.fetcher.firstBytesRequested$.subscribe(this.firstBytesRequested$)),this.subscription.add(this.fetcher.firstBytesReceived$.subscribe(this.firstBytesReceived$)),this.subscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.subscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.liveBuffer=jt.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.bufferEstimator}),this.initTracerSubscription()}setSmartRepresentationSwitch(e){this.bufferManagers.forEach(t=>t.setSmartRepresentationSwitch(e))}async seekLive(e){(0,y.assertNonNullable)(this.element);let t=this.liveStreamStatus$.getValue()!=="active"?(0,y.now)()-this.liveStreamEndTimestamp:0,i=this.normolizeLiveOffset(e+t);this.isActiveLive$.next(i===0),this.manifestUrlString=ye(this.manifestUrlString,i,2),this.manifest=await this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,await this.videoBufferManager?.seekLive(this.manifest.streams.video),await this.audioBufferManager?.seekLive(this.manifest.streams.audio),this.liveTextManager?.seekLive(this.manifest.streams.text))}initBuffer(){(0,y.assertNonNullable)(this.element),this.state$.setState("running");let e=(0,y.fromEvent)(this.element,"timeupdate");this.tuning.dash.timeupdateEventTickThrottle&&(e=e.pipe((0,y.throttle)(this.tuning.dash.timeupdateEventTickThrottle))),this.subscription.add((0,y.merge)(...c$.map(t=>(0,y.fromEvent)(this.element,t)),(0,y.fromEvent)(window,"online"),e).subscribe(()=>this.tick(),t=>{this.error$.next({id:"DashVKPlayer",category:y.ErrorCategory.WTF,message:"Internal logic error",thrown:t})})),this.subscription.add((0,y.fromEvent)(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===HTMLMediaElement.HAVE_CURRENT_DATA&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add((0,y.fromEvent)(this.element,"waiting").subscribe(()=>{this.tuning.dash.useVideoElementWaitingCurrentTimeReassign&&this.element&&this.element.readyState===HTMLMediaElement.HAVE_CURRENT_DATA&&!this.element.seeking&&Ce(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let t=()=>{if(!this.element||this.source?.readyState!=="open")return;let i=this.currentStallDuration$.getValue();i+=50,this.currentStallDuration$.next(i);let r={timeInWaiting:i},s=(0,y.now)(),n=100,u=this.videoBufferManager?.lastDataObtainedTimestamp??0;this.videoLastDataObtainedTimestamp$.next(u);let o=this.audioBufferManager?.lastDataObtainedTimestamp??0,l=this.videoBufferManager?.getForwardBufferDuration()??0,p=this.audioBufferManager?.getForwardBufferDuration()??0,c=l<n&&s-u>this.tuning.dash.crashOnStallTWithoutDataTimeout,d=this.audioBufferManager&&p<n&&s-o>this.tuning.dash.crashOnStallTWithoutDataTimeout;if((c||d)&&i>this.tuning.dash.crashOnStallTWithoutDataTimeout||i>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${i} ms`);if(this.isLive$.getValue()&&i%2e3===0){let h=this.normolizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);this.seekLive(h).catch(m=>{this.error$.next({id:"stallIntervalCallback",category:y.ErrorCategory.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:m})}),r.liveLastOffset=h}else{let h=this.element.currentTime*1e3;this.videoBufferManager?.maintain(h),this.audioBufferManager?.maintain(h),r.position=h}this.tracer.log("stallIntervalCallback",(0,y.flattenObject)(r))};this.stallWatchdogSubscription&&(this.stallWatchdogSubscription.unsubscribe(),this.subscriptionRemovable.remove(this.stallWatchdogSubscription)),this.stallWatchdogSubscription=(0,y.interval)(50).subscribe(t,i=>{this.error$.next({id:"StallWatchdogCallback",category:y.ErrorCategory.NETWORK,message:"Can't restore DASH after stall.",thrown:i})}),this.subscriptionRemovable.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t,i=!1){let r={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return this.tuning.useNewSwitchTo?this.currentStallDuration$.getValue()>0?r?.switchToWithPreviousAbort(t,i):r?.switchTo(t,i):r?.switchToOld(t,i)}async seek(e,t){(0,y.assertNonNullable)(this.element),(0,y.assertNonNullable)(this.videoBufferManager);let i;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?i=e:i=Math.max(this.videoBufferManager.findSegmentStartTime(e)??e,this.audioBufferManager?.findSegmentStartTime(e)??e),this.warmUpMediaSourceIfNeeded(i),Ce(this.element.buffered,i)||await Promise.all([this.videoBufferManager.abort(),this.audioBufferManager?.abort()]),!((0,y.isNullable)(this.element)||(0,y.isNullable)(this.videoBufferManager))&&(this.videoBufferManager.maintain(i),this.audioBufferManager?.maintain(i),this.element.currentTime=i/1e3,this.tracer.log("seek",(0,y.flattenObject)({requestedPosition:e,forcePrecise:t,position:i})))}warmUpMediaSourceIfNeeded(e=this.element?.currentTime){(0,y.isNonNullable)(this.element)&&(0,y.isNonNullable)(this.source)&&(0,y.isNonNullable)(e)&&this.source?.readyState==="ended"&&this.element.duration*1e3-e>this.tuning.dash.seekBiasInTheEnd&&this.bufferManagers.forEach(t=>t.warmUpMediaSource())}get isStreamEnded(){return this.source?.readyState==="ended"}stop(){this.tracer.log("stop"),this.element?.querySelectorAll("source").forEach(e=>{URL.revokeObjectURL(e.src),e.remove()}),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),this.videoBufferManager?.destroy(),this.videoBufferManager=null,this.audioBufferManager?.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getStreams(){return this.manifest?.streams}getCodecs(){return this.manifest?.codecs}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){this.subscription.unsubscribe(),this.subscriptionRemovable.unsubscribe(),this.representationSubscription.unsubscribe(),this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),this.source?.readyState==="open"&&Array.from(this.source.sourceBuffers).every(e=>!e.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}initTracerSubscription(){let e=(0,y.getTraceSubscriptionMethod)(this.tracer.error.bind(this.tracer));this.subscription.add(this.error$.subscribe(e("error")))}isManualDecreasePlaybackInLive(){return!this.element||!this.isLive$.getValue()?!1:1-this.element.playbackRate>this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}async updateLive(){this.isUpdatingLive=!0,this.manifest=await this.updateManifest(),this.manifest&&(this.bufferManagers.forEach(e=>e.updateLive(this.manifest)),this.liveTextManager?.updateLive(this.manifest)),this.isUpdatingLive=!1}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.getBufferedTo();if(e===null)return;let t=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),i=this.isJumpGapAfterSeekLive,r=this.element.currentTime;this.isJumpGapAfterSeekLive&&!t&&this.element.currentTime>e&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let s=this.element.currentTime*1e3,n=null,u=this.element.readyState===HTMLMediaElement.HAVE_METADATA?this.tuning.endGapTolerance:0;for(let o of this.bufferManagers)for(let l of o.gaps)(l.persistent||o.playingRepresentation$.getValue()===l.representation)&&l.from-u<=s&&l.to+u>s&&(this.element.duration*1e3-l.to<this.tuning.endGapTolerance?n=1/0:(n===null||l.to>n)&&(n=l.to));if(n!==null){let o=n+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,o===1/0?this.forceEnded$.next():(this.element.currentTime=o/1e3,this.tracer.log("jumpGap",(0,y.flattenObject)({isJumpGapAfterSeekLive:i,isActiveLowLatency:t,initialCurrentTime:r,jumpTo:o,resultCurrentTime:this.element.currentTime})))}}calculateDurationFromSegments(){return Math.max(this.videoBufferManager?.calculateDurationFromSegments()||0,this.audioBufferManager?.calculateDurationFromSegments()||0)}};var ze=require("@vkontakte/videoplayer-shared"),Yn=class{constructor(){this.subscription=new ze.Subscription;this.pipSize$=new ze.ValueSubject(void 0);this.videoSize$=new ze.ValueSubject(void 0);this.elementSize$=new ze.ValueSubject(void 0);this.pictureInPictureWindowRemoveEventListener=ze.noop}connect({observableVideo:e,video:t}){let i=r=>{let s=r.target;this.pipSize$.next({width:s.width,height:s.height})};this.subscription.add((0,ze.observeElementSize)(t).subscribe(this.videoSize$)).add(e.enterPip$.subscribe(({pictureInPictureWindow:r})=>{this.pipSize$.next({width:r.width,height:r.height}),r.addEventListener("resize",i),this.pictureInPictureWindowRemoveEventListener=()=>{r.removeEventListener("resize",i)}})).add(e.leavePip$.subscribe(()=>{this.pictureInPictureWindowRemoveEventListener()})).add((0,ze.combine)({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe((0,ze.map)(({videoSize:r,inPip:s,pipSize:n})=>s?n:r)).subscribe(this.elementSize$))}getValue(){return this.elementSize$.getValue()}subscribe(e,t){return this.elementSize$.subscribe(e,t)}getObservable(){return this.elementSize$}destroy(){this.pictureInPictureWindowRemoveEventListener(),this.subscription.unsubscribe()}};var Di=class{constructor(e){this.subscription=new H.Subscription;this.videoState=new Z("stopped");this.observableVideo=null;this.droppedFramesManager=new lr;this.stallsManager=new _n;this.elementSizeManager=new Yn;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new ri;this.audioTrackSwitchHistory=new ri;this.selectedRepresentations={audio:null,video:null};this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(r.state==="requested"&&i?.to!=="paused"&&e!=="stopped"&&t!=="stopped"&&this.seek(r.position,r.forcePrecise),t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.player.stop(),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"),B(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"),B(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="ready"&&B(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):t==="playing"&&this.video.paused?this.playIfAllowed():i?.to==="playing"&&B(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&B(this.params.desiredState.playbackState,"paused");return;default:return(0,H.assertNever)(e)}}};this.init3DScene=e=>{if(this.scene3D)return;this.scene3D=new yr(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:e.projectionData?.pose.yaw||0,y:e.projectionData?.pose.pitch||0,z:e.projectionData?.pose.roll||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});let t=this.elementSizeManager.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};this.textTracksManager=new ot(e.source.url),this.params=e,this.video=Ue(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(Me(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 zn({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode,tracer:this.tracer,forceVideoCodec:this.params.forceVideoCodec}),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params;(0,H.isNullable)(this.observableVideo)&&(this.observableVideo=We(this.video),this.subscription.add(()=>this.observableVideo?.destroy()));let i=this.constructor.name,r=n=>{e.error$.next({id:i,category:H.ErrorCategory.WTF,message:`${i} internal logic error`,thrown:n})},s=(n,u)=>this.subscription.add(n.subscribe(u,r));return{output:e,desiredState:t,observableVideo:this.observableVideo,genericErrorListener:r,connect:s}}subscribe(){let{output:e,desiredState:t,observableVideo:i,genericErrorListener:r,connect:s}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe((0,H.filter)(c=>!!c.length),(0,H.once)()).subscribe(c=>{this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks:c})}));let n=this.params.desiredState.seekState.stateChangeEnded$.pipe((0,H.map)(c=>c.to.state!=="none"),(0,H.filterChanged)());this.stallsManager.init({isSeeked$:n,currentStallDuration$:this.player.currentStallDuration$,videoLastDataObtainedTimestamp$:this.player.videoLastDataObtainedTimestamp$,throughput$:this.params.dependencies.throughputEstimator.throughput$,rtt$:this.params.dependencies.throughputEstimator.rtt$,tuning:this.params.tuning.stallsManager,abrParams:this.params.tuning.autoTrackSelection,isBuffering$:i.isBuffering$,looped$:i.looped$,playing$:i.playing$,duration:this.video.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.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),s(i.loadedMetadata$,e.loadedMetadataEvent$),s(this.player.error$,e.error$),s(this.player.fetcherRecoverableError$,e.fetcherRecoverableError$),s(this.player.fetcherError$,e.fetcherError$),s(this.player.manifestRequested$,e.manifestRequested$),s(this.player.firstBytesManifest$,e.firstBytesManifest$),s(this.player.manifestReceived$,e.manifestReceived$),s(this.player.firstBytesRequested$,e.firstBytesRequested$),s(this.player.firstBytesReceived$,e.firstBytesReceived$),s(this.player.lastConnectionType$,e.httpConnectionType$),s(this.player.lastConnectionReused$,e.httpConnectionReused$),s(this.player.isLive$,e.isLive$),s(this.player.lastRequestFirstBytes$.pipe((0,H.filter)(H.isNonNullable),(0,H.once)()),e.firstBytesEvent$),s(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),s(this.videoState.stateChangeEnded$.pipe((0,H.map)(c=>c.to)),this.params.output.playbackState$),this.subscription.add(i.looped$.subscribe(()=>this.player.warmUpMediaSourceIfNeeded(),r)),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(kt(this.video,t.isLooped,r)),this.subscription.add(je(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(nt(this.video,t.playbackRate,i.playbackRateState$,r)),this.elementSizeManager.connect({video:this.video,observableVideo:i}),s(ut(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),B(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),B(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.params.tuning.changePlaybackStateToPausedWhenEnded&&this.subscription.add(i.ended$.subscribe(()=>{this.videoState.setState("paused"),B(t.playbackState,"paused")})),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(),h=this.player.getCodecs();if((0,H.assertNonNullable)(d,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let b=[];for(let S of d.audio){b.push(ql(S));let v=[];for(let I of S.representations){let P=YS(I);v.push(P),this.audioTracksMap.set(P,{stream:S,representation:I})}this.audioStreamsMap.set(S,v)}this.params.output.availableAudioStreams$.next(b)}let m=[];for(let b of d.video){m.push(Ul(b));let S=[];for(let v of b.representations){let I=Ga({...v,streamId:b.id});I&&(S.push(I),this.videoTracksMap.set(I,{stream:b,representation:v}))}this.videoStreamsMap.set(b,S)}this.params.output.availableVideoStreams$.next(m);for(let b of d.text)for(let S of b.representations){let v=KS(b,S);this.textTracksMap.set(v,{stream:b,representation:S})}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),h?.video&&this.params.output.availableVideoCodecs$.next(h.video),h?.audio&&this.params.output.availableAudioCodecs$.next(h.audio),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())},r));let{vktvAbrThrottle:u}=this.params.tuning.dash,o=u&&ZS(u)||null;this.subscription.add((0,H.merge)(this.player.currentStallDuration$,this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,this.elementSizeManager.getObservable(),this.params.output.elementVisible$,this.droppedFramesManager.onDroopedVideoFramesLimit$,(0,H.fromEvent)(this.video,"progress")).pipe((0,H.filter)(()=>this.videoTracksMap.size>0)).subscribe(async()=>{let c=this.player.state$.getState(),d=this.player.state$.getTransition();if(c!=="manifest_ready"&&c!=="running"||d||c==="running"&&o&&!o())return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState()),this.selectVideoAudioRepresentations();let{video:h,audio:m}=this.selectedRepresentations;if(!h)return;let b=Li(this.videoTracksMap.keys(),v=>this.videoTracksMap.get(v)?.representation.id===h.id);(0,H.isNonNullable)(b)&&(this.stallsManager.lastVideoTrackSelected=b);let S=this.params.desiredState.autoVideoTrackLimits.getTransition();if(S&&this.params.output.autoVideoTrackLimits$.next(S.to),c==="manifest_ready")await this.player.initRepresentations(h.id,m?.id,this.params.sourceHls);else if(await this.player.switchRepresentation("video",h.id),m){let v=!!t.audioStream.getTransition();await this.player.switchRepresentation("audio",m.id,v)}},r)),this.subscription.add((0,H.combine)({videoState:this.videoState.stateChangeEnded$,autoVideoTrackState:(0,H.merge)((0,H.observableFrom)([t.autoVideoTrackSwitching.getState()]),t.autoVideoTrackSwitching.stateChangeEnded$.pipe((0,H.map)(c=>c.to)))}).pipe((0,H.map)(({videoState:c,autoVideoTrackState:d})=>c.to!=="stopped"&&d),(0,H.filterChanged)()).subscribe(c=>this.player.setSmartRepresentationSwitch(c))),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:c})=>{this.scene3D&&c&&this.scene3D.pointCameraTo(c.x,c.y)})),this.subscription.add(this.elementSizeManager.subscribe(c=>{this.scene3D&&c&&this.scene3D.setViewportSize(c.width,c.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe((0,H.filterChanged)()).subscribe(c=>{let d=Li(this.videoTracksMap.entries(),([,{representation:v}])=>v.id===c);if(!d){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[h,{stream:m}]=d,b=this.params.desiredState.videoStream.getTransition();b&&b.to&&b.to.id===m.id&&this.params.desiredState.videoStream.setState(b.to),e.currentVideoTrack$.next(h),e.currentVideoStream$.next(Ul(m));let S=this.player.calculateDurationFromSegments();S&&this.params.output.duration$.next(S/1e3)},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe((0,H.filterChanged)()).subscribe(c=>{let d=Li(this.audioTracksMap.entries(),([,{representation:S}])=>S.id===c);if(!d){e.currentAudioStream$.next(void 0);return}let[h,{stream:m}]=d,b=this.params.desiredState.audioStream.getTransition();b&&b.to&&b.to.id===m.id&&this.params.desiredState.audioStream.setState(b.to),e.currentAudioStream$.next(ql(m))},r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(c=>{if(c?.is3dVideo&&this.params.tuning.spherical?.enabled)try{this.init3DScene(c),e.is3DVideo$.next(!0)}catch(d){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${d}`})}else this.destroy3DScene(),this.params.tuning.spherical?.enabled&&e.is3DVideo$.next(!1)},r)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,r)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,r)),this.textTracksManager.connect(this.video,t,e);let l=t.playbackState.stateChangeStarted$.pipe((0,H.map)(({to:c})=>c==="ready"),(0,H.filterChanged)());this.subscription.add((0,H.merge)(l,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,(0,H.observableFrom)(["init"])).subscribe(()=>{let c=t.autoVideoTrackSwitching.getState(),h=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:c?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(h)})),this.subscription.add((0,H.merge)(l,this.player.state$.stateChangeEnded$,(0,H.observableFrom)(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let p=(0,H.merge)(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,H.observableFrom)(["init"])).pipe((0,H.debounce)(0));this.subscription.add(p.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?aa:ra,t=this.params.tuning.useNewAutoSelectVideoTrack?cn:ln,i=this.params.tuning.useNewAutoSelectVideoTrack?Rt:un,{desiredState:r,output:s}=this.params,n=r.autoVideoTrackSwitching.getState(),u=r.videoTrack.getState()?.id,o=Li(this.videoTracksMap.keys(),D=>D.id===u),l=s.currentVideoTrack$.getValue(),p=r.videoStream.getState()??(o&&this.videoTracksMap.get(o)?.stream)??this.videoStreamsMap.size===1?this.videoStreamsMap.keys().next().value:void 0;if(!p)return;let c=Li(this.videoStreamsMap.keys(),D=>D.id===p.id),d=c&&this.videoStreamsMap.get(c);if(!d)return;let h=De(this.video.buffered,this.video.currentTime*1e3),m;this.player.isActiveLive$.getValue()?m=this.player.isLowLatency$.getValue()?this.params.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.params.tuning.dashCmafLive.normalizedLiveMinBufferSize:this.player.isLive$.getValue()?m=this.params.tuning.dashCmafLive.normalizedTargetMinBufferSize:m=n?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;let b=(this.video.duration*1e3||1/0)-this.video.currentTime*1e3,S=Math.min(h/Math.min(m,b||1/0),1),v=r.audioStream.getState()??(this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0),I=v?.id&&Li(this.audioStreamsMap.keys(),D=>D.id===v.id)||this.audioStreamsMap.keys().next().value,P=0;if(I){if(o&&!n){let D=e(o,d,this.audioStreamsMap.get(I)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);P=Math.max(P,D?.bitrate??-1/0)}if(l){let D=e(l,d,this.audioStreamsMap.get(I)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);P=Math.max(P,D?.bitrate??-1/0)}}let x=o;(n||!x)&&(x=i(d,{container:this.elementSizeManager.getValue(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.stallsManager.abrTuningParams,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:P,forwardBufferHealth:S,current:l,visible:this.params.output.elementVisible$.getValue(),history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,stallsVideoMaxQualityLimit:this.stallsManager.videoMaxQualityLimit,stallsPredictedThroughput:this.stallsManager.predictedThroughput,abrLogger:this.params.dependencies.abrLogger}));let C=I&&t(x,d,this.audioStreamsMap.get(I)??[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.stallsManager.abrTuningParams,forwardBufferHealth:S,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),V=this.videoTracksMap.get(x)?.representation,O=C&&this.audioTracksMap.get(C)?.representation;V&&O?(this.selectedRepresentations.video=V,this.selectedRepresentations.audio=O):V&&!O&&this.audioTracksMap.size===0&&(this.selectedRepresentations.video=V,this.selectedRepresentations.audio=null)}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){Qe(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),B(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:H.ErrorCategory.DOM,thrown:e}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.stallsManager.destroy(),this.elementSizeManager.destroy(),this.destroy3DScene(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),this.params.output.currentVideoStream$.next(void 0),He(this.video),this.tracer.end()}};var Ka=class extends Di{subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();i(t.timeUpdate$,e.position$),i(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}};var de=require("@vkontakte/videoplayer-shared");var Xa=class extends Di{constructor(e){super(e),this.textTracksManager.destroy()}subscribe(){super.subscribe();let e=!1,t=-1,{output:i,observableVideo:r,desiredState:s,connect:n}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canPlayLiveTailBuffer$.next(!0),n(r.timeUpdate$,i.liveBufferTime$),n(this.player.liveSeekableDuration$,i.duration$),n(this.player.liveLatency$,i.liveLatency$);let u=new de.ValueSubject(1);n(r.playbackRateState$,u),this.params.tuning.dashCmafLive.catchupLiveForMutedInactiveTab&&this.subscription.add(i.elementVisible$.pipe((0,de.filterChanged)()).subscribe(o=>{let l=i.position$.getValue(),p=i.volume$.getValue(),c=!p.volume||p.muted;!o&&!l&&c?e=!0:o&&e&&(this.seek(0),e=!1)})),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(s.isLowLatency.stateChangeEnded$.pipe((0,de.map)(o=>o.to)).subscribe(this.player.isLowLatency$)).add((0,de.combine)({liveBufferTime:i.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe((0,de.map)(({liveBufferTime:o,liveAvailabilityStartTime:l})=>o&&l?o+l:void 0)).subscribe(i.liveTime$)).add(this.player.liveStreamStatus$.pipe((0,de.filter)(o=>(0,de.isNonNullable)(o))).subscribe(o=>i.isLiveEnded$.next(o!=="active"&&i.position$.getValue()===0))).add((0,de.combine)({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:(0,de.merge)(r.playbackRateState$,new de.ValueSubject(1))}).pipe((0,de.filter)(({liveStreamStatus:o,liveDuration:l})=>o==="active"&&!!l)).subscribe(({liveDuration:o,playbackRate:l})=>{let p=i.liveBufferTime$.getValue(),c=i.position$.getValue(),{playbackCatchupSpeedup:d}=this.params.tuning.dashCmafLive.lowLatency;c||l<1-d||this.video.paused||(0,de.isNullable)(p)||(t=o-p)})).add((0,de.combine)({time:i.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:(0,de.merge)(r.playbackRateState$,new de.ValueSubject(1))}).pipe((0,de.filterChanged)((o,l)=>this.player.liveStreamStatus$.getValue()==="active"?o.liveDuration===l.liveDuration:o.time===l.time)).subscribe(({time:o,liveDuration:l,playbackRate:p})=>{let c=i.position$.getValue(),{playbackCatchupSpeedup:d}=this.params.tuning.dashCmafLive.lowLatency;if(!c&&!this.video.paused&&p>=1-d||(0,de.isNullable)(o)||(0,de.isNullable)(l))return;let h=-1*(l-o-t);i.position$.next(Math.min(h,0))})).add(this.player.currentLiveTextRepresentation$.subscribe(o=>{if(o){let l=XS(o);this.params.output.availableTextTracks$.next([l])}}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,i=Math.trunc(t/1e3<=Math.abs(this.params.output.duration$.getValue())?t:0);this.player.seekLive(i).then(()=>{this.params.output.position$.next(e/1e3)})}};var rv="X-Playback-Duration",Ql=async a=>{let e=await lt(a),t=await e.text(),i=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t)?.[1];return i?parseInt(i,10):e.headers.has(rv)?parseInt(e.headers.get(rv),10):void 0};var re=require("@vkontakte/videoplayer-shared");var zl=Q(uu(),1);var Kn=require("@vkontakte/videoplayer-shared");var h$=a=>{let e=null;if(a.QUALITY&&(e=ii(a.QUALITY)),!e&&a.RESOLUTION){let[t,i]=a.RESOLUTION.split("x").map(r=>parseInt(r,10));e=(0,Kn.videoSizeToQuality)({width:t,height:i})}return e??null},f$=(a,e)=>{let t=a.split(`
179
179
  `),i=[],r=[];for(let s=0;s<t.length;s++){let n=t[s],u=n.match(/^#EXT-X-STREAM-INF:(.+)/),o=n.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!u&&!o)){if(u){let l=(0,zl.default)(u[1].split(",").map(S=>S.split("="))),p=l.QUALITY??`stream-${l.BANDWIDTH}`,c=h$(l),d;l.BANDWIDTH&&(d=parseInt(l.BANDWIDTH,10)/1e3||void 0),!d&&l["AVERAGE-BANDWIDTH"]&&(d=parseInt(l["AVERAGE-BANDWIDTH"],10)/1e3||void 0);let h=l["FRAME-RATE"]?parseFloat(l["FRAME-RATE"]):void 0,m;if(l.RESOLUTION){let[S,v]=l.RESOLUTION.split("x").map(I=>parseInt(I,10));S&&v&&(m={width:S,height:v})}let b=new URL(t[++s],e).toString();c&&i.push({id:p,quality:c,url:b,bandwidth:d,size:m,fps:h})}if(o){let l=(0,zl.default)(o[1].split(",").map(h=>{let m=h.indexOf("=");return[h.substring(0,m),h.substring(m+1)]}).map(([h,m])=>[h,m.replace(/^"|"$/g,"")])),p=l.URI?.replace(/playlist$/,"subtitles.vtt"),c=l.LANGUAGE,d=l.NAME;p&&c&&r.push({type:"internal",id:c,label:d,language:c,url:p,isAuto:!1})}}}if(!i.length)throw new Error("Empty manifest");return{qualityManifests:i,textTracks:r}},m$=a=>new Promise(e=>{setTimeout(()=>{e()},a)}),Gl=0,av=async(a,e=a,t,i)=>{let s=await(await lt(a,i)).text();Gl+=1;try{let{qualityManifests:n,textTracks:u}=f$(s,e);return{qualityManifests:n,textTracks:u}}catch{if(Gl<=t.manifestRetryMaxCount)return await m$((0,Kn.getExponentialDelay)(Gl-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),av(a,e,t)}return{qualityManifests:[],textTracks:[]}},Xn=av;var rt=require("@vkontakte/videoplayer-shared");var Jn=class{constructor(e,t,i,r,s){this.subscription=new rt.Subscription;this.abortControllers={destroy:new ue,nextManifest:null};this.prepareUrl=void 0;this.currentTextTrackData=null;this.availableTextTracks$=new rt.ValueSubject(null);this.getCurrentTime$=new rt.ValueSubject(null);this.error$=new rt.Subject;this.params={fetchManifestData:i,sourceUrl:r,downloadThreshold:s},this.subscription.add(e.pipe((0,rt.throttle)(1e3)).subscribe(n=>{this.processLiveTime(n)})),this.getCurrentTime$.next(()=>this.currentTextTrackData?this.currentTextTrackData.playlist.segmentStartTime/1e3+t.currentTime:0)}destroy(){this.subscription.unsubscribe(),this.abortControllers.destroy.abort()}async prepare(e){try{let t=new URL(e);t.searchParams.set("enable-subtitles","yes"),this.prepareUrl=t.toString();let{textTracks:i}=await this.fetchManifestData();await this.processTextTracks(i,this.params.sourceUrl)}catch(t){this.error("prepare",t)}}async processTextTracks(e,t){try{let i=await this.parseTextTracks(e,t);i&&(this.currentTextTrackData=i)}catch(i){this.error("processTextTracks",i)}}async parseTextTracks(e,t){for(let i of e){let r=new URL(i.url,t).toString(),n=await(await lt(r,{signal:this.abortControllers.destroy.signal})).text(),u=this.parsePlaylist(n,r);return{textTrack:i,playlist:u}}}parsePlaylist(e,t){let i={mediaSequence:0,programDateTime:"",segments:[],targetDuration:0,vkPlaybackDuration:0,segmentStartTime:0,vkStartTime:""},r=e.split(`
180
- `),s=0;for(let n=0;n<r.length;++n){let u=r[n];switch(!0){case u.startsWith("#EXTINF:"):{let o=r[++n],l=new URL(o,t).toString(),p=Number(this.extractPlaylistRowValue("#EXTINF:",u))*1e3;if(i.segments.push({time:{from:s,to:s+p},url:l}),s=s+p,!i.segmentStartTime){let c=new Date(i.vkStartTime).valueOf(),d=new Date(i.programDateTime).valueOf();i.segmentStartTime=d-c}break}case u.startsWith("#EXT-X-TARGETDURATION:"):i.targetDuration=Number(this.extractPlaylistRowValue("#EXT-X-TARGETDURATION:",u));break;case u.startsWith("#EXT-X-MEDIA-SEQUENCE:"):i.mediaSequence=Number(this.extractPlaylistRowValue("#EXT-X-MEDIA-SEQUENCE:",u));break;case u.startsWith("#EXT-X-VK-PLAYBACK-DURATION:"):i.vkPlaybackDuration=Number(this.extractPlaylistRowValue("#EXT-X-VK-PLAYBACK-DURATION:",u));break;case u.startsWith("#EXT-X-PROGRAM-DATE-TIME:"):{let o=this.extractPlaylistRowValue("#EXT-X-PROGRAM-DATE-TIME:",u);i.programDateTime=o;let l=new Date(o);l.setMilliseconds(0),s=l.valueOf();break}case u.startsWith("#EXT-X-VK-START-TIME:"):i.vkStartTime=this.extractPlaylistRowValue("#EXT-X-VK-START-TIME:",u);break}}return i}extractPlaylistRowValue(e,t){switch(e){case"#EXTINF:":return t.substring(e.length,t.length-1);default:return t.substring(e.length)}}processLiveTime(e){if((0,rt.isNonNullable)(e)&&this.currentTextTrackData){let{segments:t}=this.currentTextTrackData.playlist,{from:i}=t[0].time,{to:r}=t[t.length-1].time;if(e<i||e>r)return;r-e<this.params.downloadThreshold&&this.fetchNextManifestData();for(let n of t)if(n.time.from<=e&&n.time.to>=e){this.availableTextTracks$.next([{...this.currentTextTrackData.textTrack,url:n.url,isAuto:!0}]);break}}}async fetchNextManifestData(){try{if(this.abortControllers.nextManifest)return;this.abortControllers.nextManifest=new ue;let{textTracks:e}=await this.fetchManifestData(),t=await this.parseTextTracks(e,this.params.sourceUrl);this.currentTextTrackData&&t&&(this.currentTextTrackData.playlist.segments=t.playlist.segments)}catch(e){this.error("fetchNextManifestData",e)}finally{this.abortControllers.nextManifest=null}}async fetchManifestData(){let e=this.prepareUrl??this.params.sourceUrl;return await this.params.fetchManifestData(e,{signal:this.abortControllers.destroy.signal})}error(e,t){this.error$.next({id:"[LiveTextManager][HLS_LIVE_CMAF]",category:rt.ErrorCategory.WTF,thrown:t,message:e})}};var Ja=class{constructor(e){this.subscription=new re.Subscription;this.videoState=new Z("stopped");this.textTracksManager=null;this.liveTextManager=null;this.manifests$=new re.ValueSubject([]);this.liveOffset=new xi;this.manifestStartTime$=new re.ValueSubject(void 0);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),u=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i==="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"),B(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||u){let p=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(p),this.prepare(),u&&this.params.output.autoVideoTrackLimits$.next(u.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if(r?.to!=="paused"&&l.state==="requested"){this.videoState.startTransitionTo("ready"),this.seek(l.position&&l.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(t){case"ready":i==="ready"?B(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),B(this.params.desiredState.playbackState,"paused")):i==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":i==="paused"?(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.video.paused?this.videoState.setState("paused"):this.video.pause()):r?.to==="playing"&&B(this.params.desiredState.playbackState,"playing");return;case"paused":if(i==="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 p=this.liveOffset.getTotalOffset();p>=this.maxSeekBackTime$.getValue()&&(p=0,this.liveOffset.resetTo(p)),this.liveOffset.resume(),this.params.output.position$.next(-p/1e3),this.prepare()}else r?.to==="paused"&&(B(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return(0,re.assertNever)(t)}};this.params=e,this.video=Ue(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:re.VideoQuality.INVARIANT,url:this.params.source.url};let t=(i,r)=>Xn(i,this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},r);this.params.tuning.useHlsLiveNewTextManager?this.liveTextManager=new Jn(this.params.output.liveTime$,this.video,t,this.params.source.url,this.params.tuning.hlsLiveNewTextManagerDownloadThreshold):this.textTracksManager=new ot(e.source.url),t(this.generateLiveUrl()).then(({qualityManifests:i,textTracks:r})=>{i.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:re.ErrorCategory.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),this.liveTextManager?.processTextTracks(r,this.params.source.url),this.manifests$.next([this.masterManifest,...i])}).catch(i=>{this.params.output.error$.next({id:"ExtractHlsQualities",category:re.ErrorCategory.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:i})}),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(Me(this.params.source.url)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.maxSeekBackTime$=new re.ValueSubject(e.source.maxSeekBackTime??1/0),this.subscribe()}selectManifest(){let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),r=t.getTransition(),s=r?.to?.id??t.getState()?.id??"master",n=this.manifests$.getValue();if(!n.length)return;let u=i?"master":s;return i&&!r&&t.startTransitionTo(this.masterManifest),n.find(o=>o.id===u)}subscribe(){let{output:e,desiredState:t}=this.params,i=u=>{e.error$.next({id:"HlsLiveProvider",category:re.ErrorCategory.WTF,message:"HlsLiveProvider internal logic error",thrown:u})},r=We(this.video);this.subscription.add(()=>r.destroy());let s=(u,o)=>this.subscription.add(u.subscribe(o,i));s(r.ended$,e.endedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentBuffer$),s(r.loadedMetadata$,e.firstBytesEvent$),s(r.loadedMetadata$,e.loadedMetadataEvent$),s(r.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(je(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(nt(this.video,t.playbackRate,r.playbackRateState$,i)),s(ut(this.video),e.elementVisible$),this.liveTextManager?(s(this.liveTextManager.getCurrentTime$,this.params.output.getCurrentTime$),s(this.liveTextManager.error$,this.params.output.error$)):this.textTracksManager&&this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),B(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),B(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.liveTextManager&&this.subscription.add(this.liveTextManager.availableTextTracks$.subscribe(u=>{u&&this.params.output.availableTextTracks$.next(u)})),this.subscription.add(this.maxSeekBackTime$.pipe((0,re.filterChanged)(),(0,re.map)(u=>-u/1e3)).subscribe(this.params.output.duration$,i)),this.subscription.add(r.loadedMetadata$.subscribe(()=>{let u=this.params.desiredState.seekState.getState(),o=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),p=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&(0,re.isNonNullable)(l.to)){let c=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let d=this.manifests$.getValue().find(h=>h.id===c);d&&(this.params.output.currentVideoTrack$.next(d),this.params.output.hostname$.next(Me(d.url)))}p&&this.params.desiredState.autoVideoTrackSwitching.setState(p.to),o&&o.from==="changing_manifest"&&this.videoState.setState(o.to),u&&u.state==="requested"&&this.seek(u.position)},i)),this.subscription.add(r.loadedData$.subscribe(()=>{let u=this.video?.getStartDate?.()?.getTime();this.manifestStartTime$.next(u||void 0)},i)),this.subscription.add((0,re.combine)({startTime:this.manifestStartTime$.pipe((0,re.filter)(re.isNonNullable)),currentTime:r.timeUpdate$}).subscribe(({startTime:u,currentTime:o})=>this.params.output.liveTime$.next(u+o*1e3),i)),this.subscription.add(this.manifests$.pipe((0,re.map)(u=>u.map(({id:o,quality:l,size:p,bandwidth:c,fps:d})=>({id:o,quality:l,size:p,fps:d,bitrate:c})))).subscribe(this.params.output.availableVideoTracks$,i));let n=(0,re.merge)(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,(0,re.observableFrom)(["init"])).pipe((0,re.debounce)(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager?.destroy(),this.liveTextManager?.destroy(),this.params.output.element$.next(void 0),He(this.video)}prepare(){let e=this.selectManifest();if((0,re.isNullable)(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),r=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){let{max:u,min:o}=t?.to??i??{};for(let[l,p]of[[u,"mq"],[o,"lq"]]){let c=String(parseFloat(l||""));p&&l&&r.searchParams.set(p,c)}}let s=this.params.format==="HLS_LIVE_CMAF"?2:0,n=ye(r.toString(),this.liveOffset.getTotalOffset(),s);this.liveTextManager?.prepare(n),this.video.setAttribute("src",n),this.video.load(),Ql(n).then(u=>{if(!(0,re.isNullable)(u))this.maxSeekBackTime$.next(u);else{let o=this.params.source.maxSeekBackTime??this.maxSeekBackTime$.getValue();((0,re.isNullable)(o)||!isFinite(o))&&lt(n).then(l=>l.text()).then(l=>{let p=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(l)?.[1];if(p){let c=new URL(p,n).toString();Ql(c).then(d=>{(0,re.isNullable)(d)||this.maxSeekBackTime$.next(d)})}}).catch(()=>{})}})}playIfAllowed(){Qe(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),B(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:re.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,i=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(i),this.params.output.position$.next(-i/1e3),this.params.output.seekedEvent$.next()}generateLiveUrl(){let e=ye(this.params.source.url);if(this.params.tuning.useHlsLiveNewTextManager){let t=new URL(e);t.searchParams.set("enable-subtitles","yes"),e=t.toString()}return e}};var oe=require("@vkontakte/videoplayer-shared");var Za=class{constructor(e){this.subscription=new oe.Subscription;this.videoState=new Z("stopped");this.manifests$=new oe.ValueSubject([]);this.unmuteAfterBrowserResetsHappened=new oe.ValueSubject(!1);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),u=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i==="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"),B(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||u){let p=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(p);let{currentTime:c}=this.video;this.prepare(),u&&this.params.output.autoVideoTrackLimits$.next(u.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:c*1e3,forcePrecise:!0});return}switch(r?.to!=="paused"&&l.state==="requested"&&this.seek(l.position),t){case"ready":i==="ready"?B(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),B(this.params.desiredState.playbackState,"paused")):i==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":i==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):r?.to==="playing"&&B(this.params.desiredState.playbackState,"playing");return;case"paused":i==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):r?.to==="paused"&&B(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return(0,oe.assertNever)(t)}};this.textTracksManager=new ot(e.source.url),this.params=e,this.video=Ue(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:oe.VideoQuality.INVARIANT,url:this.params.source.url},this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Me(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.manifestRequested$.next(),Xn(ye(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:i})=>{this.params.output.firstBytesManifest$.next(),this.manifests$.next([this.masterManifest,...t]),this.params.output.manifestReceived$.next(),this.params.tuning.useNativeHLSTextTracks||this.params.desiredState.internalTextTracks.startTransitionTo(i)},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:oe.ErrorCategory.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),r=t.getTransition(),s=r?.to?.id??t.getState()?.id??"master",n=this.manifests$.getValue();if(!n.length)return;let u=i?"master":s;return i&&(!r||!r.from)&&t.startTransitionTo(this.masterManifest),n.find(o=>o.id===u)}subscribe(){let{output:e,desiredState:t}=this.params,i=u=>{e.error$.next({id:"HlsProvider",category:oe.ErrorCategory.WTF,message:"HlsProvider internal logic error",thrown:u})},r=We(this.video);this.subscription.add(()=>r.destroy());let s=(u,o)=>this.subscription.add(u.subscribe(o));if(s(r.timeUpdate$,e.position$),s(r.durationChange$,e.duration$),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.loadedMetadata$,e.firstBytesEvent$),s(r.loadedMetadata$,e.loadedMetadataEvent$),s(r.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.seeked$,e.seekedEvent$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe((0,oe.map)(u=>u.to)),this.params.output.playbackState$),this.subscription.add(Pt(this.video,t.isLooped,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(nt(this.video,t.playbackRate,r.playbackRateState$,i)),Tr({subscription:this.subscription,desiredState:t,videoElement$:this.params.output.element$,observableVideo:r}),this.subscription.add(je(this.video,t.volume,r.volumeState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),B(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),B(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i).add(r.loadedMetadata$.subscribe(()=>{let u=this.params.desiredState.seekState.getState(),o=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),p=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&(0,oe.isNonNullable)(l.to)){let h=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let m=this.manifests$.getValue().find(b=>b.id===h);m&&(this.params.output.currentVideoTrack$.next(m),this.params.output.hostname$.next(Me(m.url)))}let c=this.params.desiredState.playbackRate.getState(),d=this.params.output.element$.getValue()?.playbackRate;if(c!==d){let h=this.params.output.element$.getValue();h&&(this.params.desiredState.playbackRate.setState(c),h.playbackRate=c)}p&&this.params.desiredState.autoVideoTrackSwitching.setState(p.to),o&&o.from==="changing_manifest"&&this.videoState.setState(o.to),u.state==="requested"&&this.seek(u.position)},i))),this.params.tuning.changePlaybackStateToPausedWhenEnded&&this.subscription.add(r.ended$.subscribe(()=>{this.videoState.setState("paused"),B(t.playbackState,"paused")})),this.subscription.add(this.manifests$.pipe((0,oe.map)(u=>u.map(({id:o,quality:l,size:p,bandwidth:c,fps:d})=>({id:o,quality:l,size:p,fps:d,bitrate:c})))).subscribe(this.params.output.availableVideoTracks$,i)),!j.device.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:u}=this.video;this.subscription.add((0,oe.merge)((0,oe.fromEvent)(u,"addtrack"),(0,oe.fromEvent)(u,"removetrack"),(0,oe.fromEvent)(u,"change"),(0,oe.observableFrom)(["init"])).subscribe(()=>{for(let o=0;o<u.length;o++)u[o].mode="hidden"},i))}let n=(0,oe.merge)(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,(0,oe.observableFrom)(["init"])).pipe((0,oe.debounce)(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),He(this.video)}prepare(){let e=this.selectManifest();if((0,oe.isNullable)(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),r=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){let{max:s,min:n}=t?.to??i??{};for(let[u,o]of[[s,"mq"],[n,"lq"]]){let l=String(parseFloat(u||""));o&&u&&r.searchParams.set(o,l)}}this.video.setAttribute("src",r.toString()),this.video.load()}playIfAllowed(){Qe(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),B(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:oe.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};var sv=Q(zi(),1),Yl=Q(Si(),1),nv=Q(gt(),1);var fe=require("@vkontakte/videoplayer-shared");var es=class{constructor(e){this.subscription=new fe.Subscription;this.videoState=new Z("stopped");this.trackUrls={};this.textTracksManager=new ot;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=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"),B(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(),u=this.params.desiredState.seekState.getState();if(s&&e!=="ready"&&!n){this.handleQualityLimitTransition(s.to);return}if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(n){let{currentTime:o}=this.video;this.prepare(),u.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:o*1e3,forcePrecise:!0});return}switch(i?.to!=="paused"&&u.state==="requested"&&this.seek(u.position),e){case"ready":t==="ready"?B(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),B(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()):i?.to==="playing"&&B(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&B(this.params.desiredState.playbackState,"paused");return;default:return(0,fe.assertNever)(e)}};this.params=e,this.video=Ue(e.container,e.tuning),this.params.output.element$.next(this.video),(0,sv.default)(this.params.source).reverse().forEach(([t,i],r)=>{let s=r.toString(10);this.trackUrls[s]={track:{quality:t,id:s},url:i}}),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next((0,Yl.default)(this.trackUrls).map(({track:t})=>t)),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.desiredState.autoVideoTrackSwitching.setState(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.subscribe()}subscribe(){let{output:e,desiredState:t}=this.params,i=u=>{e.error$.next({id:"MpegProvider",category:fe.ErrorCategory.WTF,message:"MpegProvider internal logic error",thrown:u})},r=We(this.video);this.subscription.add(()=>r.destroy());let s=(u,o)=>this.subscription.add(u.subscribe(o,i));s(r.timeUpdate$,e.position$),s(r.durationChange$,e.duration$),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.loadedMetadata$,e.firstBytesEvent$),s(r.loadedMetadata$,e.loadedMetadataEvent$),s(r.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.seeked$,e.seekedEvent$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe((0,fe.map)(u=>u.to)),this.params.output.playbackState$),this.subscription.add(Pt(this.video,t.isLooped,i)),Tr({subscription:this.subscription,desiredState:t,videoElement$:this.params.output.element$,observableVideo:r}),this.subscription.add(je(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(nt(this.video,t.playbackRate,r.playbackRateState$,i)),s(ut(this.video),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),B(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),B(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready");let u=this.params.desiredState.videoTrack.getTransition();if(u&&(0,fe.isNonNullable)(u.to)){this.params.desiredState.videoTrack.setState(u.to),this.params.output.currentVideoTrack$.next(this.trackUrls[u.to.id].track);let o=this.params.desiredState.playbackRate.getState(),l=this.params.output.element$.getValue()?.playbackRate;if(o!==l){let p=this.params.output.element$.getValue();p&&(this.params.desiredState.playbackRate.setState(o),p.playbackRate=o)}}this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.params.tuning.changePlaybackStateToPausedWhenEnded&&this.subscription.add(r.ended$.subscribe(()=>{this.videoState.setState("paused"),B(t.playbackState,"paused")})),this.textTracksManager.connect(this.video,t,e);let n=(0,fe.merge)(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,(0,fe.observableFrom)(["init"])).pipe((0,fe.debounce)(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.params.output.element$.next(void 0),He(this.video)}prepare(){let e=this.params.desiredState.videoTrack.getState()?.id;(0,fe.assertNonNullable)(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];(0,fe.assertNonNullable)(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=ni(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(Me(t))}playIfAllowed(){Qe(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),B(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:fe.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){this.params.output.autoVideoTrackLimits$.next(e);let t=l=>{this.params.output.currentVideoTrack$.next(l),this.params.desiredState.videoTrack.startTransitionTo(l)},i=l=>{let p=Rt(n,{container:this.video.getBoundingClientRect(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:0,limits:l,abrLogger:this.params.dependencies.abrLogger});t(p)},r=this.params.output.currentVideoTrack$.getValue()?.quality,s=!!(e.max||e.min),n=(0,Yl.default)(this.trackUrls).map(l=>l.track);if(!r||!s||nr(e,n[0].quality,(0,nv.default)(n,-1)?.quality)){i();return}let u=e.max?(0,fe.isLowerOrEqual)(r,e.max):!0,o=e.min?(0,fe.isHigherOrEqual)(r,e.min):!0;u&&o||i(e)}};var me=require("@vkontakte/videoplayer-shared");var uv=require("@vkontakte/videoplayer-shared"),ov=["stun:videostun.mycdn.me:80"],b$=1e3,g$=3,Kl=()=>null,Zn=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=Kl;this.externalStopCallback=Kl;this.externalErrorCallback=Kl;this.options=this.normalizeOptions(t);let i=e.split("/");this.serverUrl=i.slice(0,i.length-1).join("/"),this.streamKey=i[i.length-1]}onStart(e){try{this.externalStartCallback=e}catch(t){this.handleSystemError(t)}}onStop(e){try{this.externalStopCallback=e}catch(t){this.handleSystemError(t)}}onError(e){try{this.externalErrorCallback=e}catch(t){this.handleSystemError(t)}}connect(){this.connectWS()}disconnect(){try{this.externalStopCallback(),this.closeConnections()}catch(e){this.handleSystemError(e)}}connectWS(){this.ws||(this.ws=new WebSocket(this.serverUrl),this.ws.onopen=this.onSocketOpen.bind(this),this.ws.onmessage=this.onSocketMessage.bind(this),this.ws.onclose=this.onSocketClose.bind(this),this.ws.onerror=this.onSocketError.bind(this))}onSocketOpen(){this.handleLogin()}onSocketClose(e){try{if(!this.ws)return;this.ws=null,e.code>1e3?(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():this.scheduleRetry()):this.externalStopCallback()}catch(t){this.handleRTCError(t)}}onSocketError(e){try{this.externalErrorCallback(new Error(e.toString()))}catch(t){this.handleRTCError(t)}}onSocketMessage(e){try{let t=this.parseMessage(e.data);switch(t.type){case"JOIN":case"CALL_JOIN":this.handleJoinMessage(t);break;case"UPDATE":this.handleUpdateMessage(t);break;case"STATUS":this.handleStatusMessage(t);break}}catch(t){this.handleRTCError(t)}}handleJoinMessage(e){switch(e.inviteType){case"ANSWER":this.handleAnswer(e.sdp);break;case"CANDIDATE":this.handleCandidate(e.candidate);break}}handleStatusMessage(e){switch(e.status){case"UNPUBLISHED":this.handleUnpublished();break}}async handleUpdateMessage(e){try{let t=await this.createOffer();this.peerConnection&&await this.peerConnection.setLocalDescription(t),this.handleAnswer(e.sdp)}catch(t){this.handleRTCError(t)}}async handleLogin(){try{let e={iceServers:[{urls:ov}]};this.peerConnection=new RTCPeerConnection(e),this.peerConnection.ontrack=this.onPeerConnectionStream.bind(this),this.peerConnection.onicecandidate=this.onPeerConnectionIceCandidate.bind(this),this.peerConnection.oniceconnectionstatechange=this.onPeerConnectionIceConnectionStateChange.bind(this);let t=await this.createOffer();await this.peerConnection.setLocalDescription(t),this.send({type:this.signalingType,inviteType:"OFFER",streamKey:this.streamKey,sdp:t.sdp,callSupport:!1})}catch(e){this.handleRTCError(e)}}async handleAnswer(e){try{this.peerConnection&&await this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e}))}catch(t){this.handleRTCError(t)}}async handleCandidate(e){if(e)try{this.peerConnection&&await this.peerConnection.addIceCandidate(e)}catch(t){this.handleRTCError(t)}}handleUnpublished(){try{this.closeConnections(),this.externalStopCallback()}catch(e){this.handleRTCError(e)}}handleSystemError(e){this.options.errorChanel&&this.options.errorChanel.next({id:"webrtc-provider-error",category:uv.ErrorCategory.WTF,message:e.message})}async onPeerConnectionStream(e){let t=e.streams[0];this.stream&&this.stream.id===t.id||(this.stream=t,this.externalStartCallback(this.stream))}onPeerConnectionIceCandidate(e){e.candidate&&this.send({type:this.signalingType,inviteType:"CANDIDATE",candidate:e.candidate})}onPeerConnectionIceConnectionStateChange(){if(this.peerConnection){let e=this.peerConnection.iceConnectionState;["failed","closed"].indexOf(e)>-1&&(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():(this.closeConnections(),this.scheduleRetry()))}}async createOffer(){let e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");let t=await this.peerConnection.createOffer(e),i=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(i))throw new Error("No h264 codec support error");return t}handleRTCError(e){try{this.externalErrorCallback(e||new Error("RTC connection error"))}catch(t){this.handleSystemError(t)}}handleNetworkError(){try{this.externalErrorCallback(new Error("Network error"))}catch(e){this.handleSystemError(e)}}send(e){this.ws&&this.ws.send(JSON.stringify(e))}parseMessage(e){try{return JSON.parse(e)}catch{throw new Error("Can not parse socket message")}}closeConnections(){let e=this.ws;e&&(this.ws=null,e.close(1e3)),this.removePeerConnection()}removePeerConnection(){let e=this.peerConnection;e&&(this.peerConnection=null,e.close(),e.ontrack=null,e.onicecandidate=null,e.oniceconnectionstatechange=null,e=null)}scheduleRetry(){this.retryTimeout=setTimeout(this.connectWS.bind(this),b$)}normalizeOptions(e={}){let t={stunServerList:ov,maxRetryNumber:g$,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var ts=class{constructor(e){this.videoState=new Z("stopped");this.maxSeekBackTime$=new me.ValueSubject(0);this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=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"),B(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"),B(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()):i?.to==="playing"&&B(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&B(this.params.desiredState.playbackState,"paused");return;default:return(0,me.assertNever)(e)}};this.subscription=new me.Subscription,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=Ue(e.container,e.tuning),this.liveStreamClient=new Zn(this.params.source.url,{maxRetryNumber:this.params.tuning.webrtc.connectionRetryMaxNumber,errorChanel:this.params.output.error$}),this.liveStreamClient.onStart(this.onLiveStreamStart.bind(this)),this.liveStreamClient.onStop(this.onLiveStreamStop.bind(this)),this.liveStreamClient.onError(this.onLiveStreamError.bind(this)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.subscribe()}destroy(){this.subscription.unsubscribe(),this.liveStreamClient.disconnect(),this.params.output.element$.next(void 0),He(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,i=n=>{e.error$.next({id:"WebRTCLiveProvider",category:me.ErrorCategory.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};this.subscription.add((0,me.merge)(this.videoState.stateChangeStarted$.pipe((0,me.map)(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe((0,me.map)(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:u})=>{this.log({message:`[videoState change] ${u}: ${JSON.stringify(n)}`})}));let r=We(this.video);this.subscription.add(()=>r.destroy());let s=(n,u)=>this.subscription.add(n.subscribe(u,i));s(r.timeUpdate$,e.liveTime$),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(ut(this.video),this.params.output.elementVisible$),this.subscription.add(r.durationChange$.subscribe(n=>{e.duration$.next(n===1/0?0:n)})).add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused")},i)).add(r.playing$.subscribe(()=>{this.videoState.setState("playing")},i)).add(r.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(je(this.video,t.volume,r.volumeState$,i)).add(r.volumeState$.subscribe(e.volume$,i)).add(this.videoState.stateChangeEnded$.subscribe(n=>{switch(n.to){case"stopped":e.position$.next(0),e.duration$.next(0),t.playbackState.setState("stopped");break;case"ready":break;case"paused":t.playbackState.setState("paused");break;case"playing":t.playbackState.setState("playing");break;default:return(0,me.assertNever)(n.to)}},i)).add((0,me.merge)(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,(0,me.observableFrom)(["init"])).pipe((0,me.debounce)(0)).subscribe(this.syncPlayback.bind(this),i)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),i))}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(Me(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:me.VideoQuality.INVARIANT}),this.video.srcObject=e,B(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:me.ErrorCategory.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){Qe(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),B(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:me.ErrorCategory.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var Ir=class{constructor(e){this.length=e.length,this.iterator=e[Symbol.iterator](),this.next()}next(){this.current=this.iterator.next(),this.index=this.index===void 0?0:this.index+1}getValue(){if(this.current.done)throw new Error("Iterable is completed");return this.current.value}isCompleted(){return!!this.current.done}isLast(){return this.index===this.length-1}};var E=require("@vkontakte/videoplayer-shared");var Wt=require("@vkontakte/videoplayer-shared"),lv=a=>new Wt.Observable(e=>{let t=new Wt.Subscription,i=a.desiredPlaybackState$.stateChangeStarted$.pipe((0,Wt.map)(({from:l,to:p})=>`${l}-${p}`)),r=a.desiredPlaybackState$.stateChangeEnded$,s=a.providerChanged$.pipe((0,Wt.map)(({type:l})=>l!==void 0)),n=new Wt.Subject,u=0,o="unknown";return t.add(i.subscribe(l=>{u&&window.clearTimeout(u),o=l,u=window.setTimeout(()=>n.next(l),a.maxTransitionInterval)})),t.add(r.subscribe(()=>{window.clearTimeout(u),o="unknown",u=0})),t.add(s.subscribe(l=>{u&&(window.clearTimeout(u),u=0,l&&(u=window.setTimeout(()=>n.next(o),a.maxTransitionInterval)))})),t.add(n.subscribe(e)),()=>{window.clearTimeout(u),t.unsubscribe()}});var ct=require("@vkontakte/videoplayer-shared");function cv(){return new(window.AudioContext||window.webkitAudioContext)}var Er=class a{constructor(e,t,i,r){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=i;this.volumeMultiplier=r;this.destroyController=new ue;this.subscriptions=new ct.Subscription;this.audioContext=null;this.gainNode=null;this.mediaElementSource=null;this.subscriptions.add(this.provider$.pipe((0,ct.filter)(s=>!!s.type),(0,ct.once)()).subscribe(({type:s})=>this.subscribe(s)))}static{this.errorId="VolumeMultiplierManager"}subscribe(e){j.browser.isSafari&&e!=="MPEG"||this.subscriptions.add((0,ct.combine)({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe((0,ct.filter)(({playbackState:t,video:i,volume:{muted:r,volume:s}})=>t==="playing"&&!!i&&!r&&!!s),(0,ct.once)()).subscribe(({video:t})=>{this.initAudioContextOnce(t).then(i=>{i||this.destroy()}).catch(i=>{this.handleError(i),this.destroy()})}))}static isSupported(){return"AudioContext"in window&&"GainNode"in window&&"MediaElementAudioSourceNode"in window}async initAudioContextOnce(e){let{volumeMultiplier:t}=this,i=cv();this.audioContext=i;let r=i.createGain();if(this.gainNode=r,r.gain.value=t,r.connect(i.destination),i.state==="suspended"&&(await i.resume(),this.destroyController.signal.aborted))return!1;let s=i.createMediaElementSource(e);return this.mediaElementSource=s,s.connect(r),!0}cleanup(){this.mediaElementSource&&(this.mediaElementSource.disconnect(),this.mediaElementSource=null),this.gainNode&&(this.gainNode.disconnect(),this.gainNode=null),this.audioContext&&(this.audioContext.state!=="closed"&&this.audioContext.close(),this.audioContext=null)}destroy(){this.destroyController.abort(),this.subscriptions.unsubscribe(),this.cleanup()}handleError(e){this.volumeMultiplierError$.next({id:a.errorId,category:ct.ErrorCategory.VIDEO_PIPELINE,message:e?.message??`${a.errorId} exception`,thrown:e})}};var S$={chunkDuration:5e3,maxParallelRequests:5},is=class{constructor(e){this.current$=new E.ValueSubject({type:void 0});this.providerError$=new E.Subject;this.noAvailableProvidersError$=new E.Subject;this.volumeMultiplierError$=new E.Subject;this.providerOutput={position$:new E.ValueSubject(0),duration$:new E.ValueSubject(1/0),volume$:new E.ValueSubject({muted:!1,volume:1}),availableVideoStreams$:new E.ValueSubject([]),currentVideoStream$:new E.ValueSubject(void 0),availableVideoTracks$:new E.ValueSubject([]),currentVideoTrack$:new E.ValueSubject(void 0),availableVideoCodecs$:new E.ValueSubject([]),availableAudioStreams$:new E.ValueSubject([]),currentAudioStream$:new E.ValueSubject(void 0),availableAudioTracks$:new E.ValueSubject([]),availableAudioCodecs$:new E.ValueSubject([]),currentVideoSegmentLength$:new E.ValueSubject(0),currentAudioSegmentLength$:new E.ValueSubject(0),isAudioAvailable$:new E.ValueSubject(!0),autoVideoTrackLimitingAvailable$:new E.ValueSubject(!1),autoVideoTrackLimits$:new E.ValueSubject(void 0),currentBuffer$:new E.ValueSubject(void 0),isBuffering$:new E.ValueSubject(!0),error$:new E.Subject,fetcherError$:new E.Subject,fetcherRecoverableError$:new E.Subject,warning$:new E.Subject,willSeekEvent$:new E.Subject,soundProhibitedEvent$:new E.Subject,seekedEvent$:new E.Subject,loopedEvent$:new E.Subject,endedEvent$:new E.Subject,manifestRequested$:new E.Subject,firstBytesManifest$:new E.Subject,manifestReceived$:new E.Subject,firstBytesRequested$:new E.Subject,firstBytesReceived$:new E.Subject,firstBytesEvent$:new E.Subject,loadedMetadataEvent$:new E.Subject,firstFrameEvent$:new E.Subject,canplay$:new E.Subject,isLive$:new E.ValueSubject(void 0),isLiveEnded$:new E.ValueSubject(null),canPlayLiveTailBuffer$:new E.ValueSubject(!1),isLowLatency$:new E.ValueSubject(!1),canChangePlaybackSpeed$:new E.ValueSubject(!0),liveTime$:new E.ValueSubject(void 0),liveBufferTime$:new E.ValueSubject(void 0),liveLatency$:new E.ValueSubject(void 0),severeStallOccurred$:new E.Subject,availableTextTracks$:new E.ValueSubject([]),currentTextTrack$:new E.ValueSubject(void 0),hostname$:new E.ValueSubject(void 0),httpConnectionType$:new E.ValueSubject(void 0),httpConnectionReused$:new E.ValueSubject(void 0),inPiP$:new E.ValueSubject(!1),inFullscreen$:new E.ValueSubject(!1),element$:new E.ValueSubject(void 0),elementVisible$:new E.ValueSubject(!0),availableSources$:new E.ValueSubject(void 0),is3DVideo$:new E.ValueSubject(!1),playbackState$:new E.ValueSubject(""),getCurrentTime$:new E.ValueSubject(null)};this.subscription=new E.Subscription;this.volumeMultiplierManager=null;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer"),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name);let t=Xu([...qS(this.params.tuning),...NS(this.params.tuning)]).filter(l=>(0,E.isNonNullable)(e.sources[l])),{forceFormat:i,formatsToAvoid:r}=this.params.tuning,s=[];i?s=[i]:r.length?s=[...t.filter(l=>!(0,Xl.default)(r,l)),...t.filter(l=>(0,Xl.default)(r,l))]:s=t,this.log({message:`Selected formats: ${s.join(" > ")}`}),this.tracer.log("Selected formats",(0,E.flattenObject)(s)),this.screenFormatsIterator=new Ir(s);let n=[...Bl(!0),...Bl(!1)];this.chromecastFormatsIterator=new Ir(n.filter(l=>(0,E.isNonNullable)(e.sources[l]))),this.providerOutput.availableSources$.next(e.sources);let{volumeMultiplier:u=1,tuning:{useVolumeMultiplier:o}}=this.params;o&&u!==1&&Er.isSupported()&&(this.volumeMultiplierManager=new Er(this.providerOutput,this.current$,this.volumeMultiplierError$,u))}init(){this.subscription.add(this.initProviderErrorHandling()).add(this.params.dependencies.chromecastInitializer.connection$.subscribe(()=>{this.reinitProvider()})).add(this.providerOutput.availableVideoCodecs$.subscribe(e=>{!this.videoCodecsIterator&&e.length>1&&(this.videoCodecsIterator=new Ir(e))}))}destroy(){this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe(),this.volumeMultiplierManager?.destroy(),this.volumeMultiplierManager=null,this.tracer.end()}initProvider(){let e=this.chooseDestination(),t=this.chooseFormat(e);if((0,E.isNullable)(t)){this.handleNoFormatsError(e);return}let i;try{i=this.createProvider(e,t)}catch(r){this.providerError$.next({id:"ProviderNotConstructed",category:E.ErrorCategory.WTF,message:"Failed to create provider",thrown:r})}i?this.current$.next({type:t,provider:i,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()}switchToNextVideoCodec(){this.params.tuning.dash.codecsPrioritizeEnabled&&!this.videoCodecsIterator.isLast()&&(this.tracer.log("switchToNextVideoCodec"),this.destroyProvider(),this.videoCodecsIterator.next(),this.initProvider())}destroyProvider(){let e=this.current$.getValue().provider;if(!e)return;this.log({message:"destroyProvider"}),this.tracer.log("destroyProvider"),e.destroy();let t=this.providerOutput.position$.getValue()*1e3,i=this.params.desiredState.seekState.getState(),r=i.state!=="none";if(this.params.desiredState.seekState.setState({state:"requested",position:r?i.position:t,forcePrecise:r?i.forcePrecise:!1}),e.scene3D){let n=e.scene3D.getCameraRotation();this.params.desiredState.cameraOrientation.setState({x:n.x,y:n.y})}let s=this.providerOutput.isBuffering$;s.getValue()||s.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),this.tracer.log("createProvider",{destination:e,format:t}),e){case"SCREEN":return this.createScreenProvider(t);case"CHROMECAST":return this.createChromecastProvider(t);default:return(0,E.assertNever)(e)}}createScreenProvider(e){let{sources:t,container:i,desiredState:r,panelSize:s}=this.params,n=this.providerOutput,u={container:i,source:null,desiredState:r,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning,panelSize:s};switch(e){case"DASH_SEP":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_ONDEMAND":case"DASH_STREAMS":{let o=this.applyFailoverHost(t[e]),l=this.applyFailoverHost(t.HLS_ONDEMAND||t.HLS);return(0,E.assertNonNullable)(o),this.params.tuning.useNewDashProvider?new Ka({...u,source:o,sourceHls:l,forceVideoCodec:this.videoCodecsIterator?.getValue()}):new Wa({...u,source:o,sourceHls:l,forceVideoCodec:this.videoCodecsIterator?.getValue()})}case"DASH_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return(0,E.assertNonNullable)(o),this.params.tuning.useNewDashProvider?new Xa({...u,source:o}):new Qa({...u,source:o})}case"HLS":case"HLS_ONDEMAND":case"HLS_FMP4":{let o=this.applyFailoverHost(t[e]);return(0,E.assertNonNullable)(o),new Za({...u,source:o})}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return(0,E.assertNonNullable)(o),new Ja({...u,source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case"MPEG":{let o=this.applyFailoverHost(t[e]);return(0,E.assertNonNullable)(o),new es({...u,source:o})}case"DASH_LIVE":{let o=this.applyFailoverHost(t[e]);return(0,E.assertNonNullable)(o),new Fb({...u,source:o,config:{...S$,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case"WEB_RTC_LIVE":{let o=this.applyFailoverHost(t[e]);return(0,E.assertNonNullable)(o),new ts({container:i,source:o,desiredState:r,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return(0,E.assertNever)(e)}}createChromecastProvider(e){let{sources:t,container:i,desiredState:r,meta:s}=this.params,n=this.providerOutput,u=this.params.dependencies.chromecastInitializer.connection$.getValue();return(0,E.assertNonNullable)(u),new ea({connection:u,meta:s,container:i,source:t,format:e,desiredState:r,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?"CHROMECAST":"SCREEN"}chooseFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case"CHROMECAST":return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return(0,E.assertNever)(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return(0,E.assertNever)(e)}}handleNoFormatsError(e){switch(e){case"SCREEN":this.noAvailableProvidersError$.next(this.params.tuning.forceFormat),this.current$.next({type:void 0});return;case"CHROMECAST":this.params.dependencies.chromecastInitializer.disconnect();return;default:return(0,E.assertNever)(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;let t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;let i=r=>{let s=new URL(r);return s.host=t,s.toString()};if(e===void 0)return e;if("type"in e){if(e.type==="raw")return e;if(e.type==="url")return{...e,url:i(e.url)}}return(0,pv.default)((0,dv.default)(e).map(([r,s])=>[r,i(s)]))}initProviderErrorHandling(){let e=new E.Subscription,t=!1,i=0;return e.add((0,E.merge)(this.providerOutput.error$.pipe((0,E.filter)(r=>!this.params.tuning.ignoreAudioRendererError||!r.message||!/AUDIO_RENDERER_ERROR/ig.test(r.message))),lv({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe((0,E.map)(r=>({id:`ProviderHangup:${r}`,category:E.ErrorCategory.WTF,message:`A ${r} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.providerOutput.fetcherError$.subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;let r=this.params.desiredState.playbackState.transitionEnded$.pipe((0,E.filter)(({to:s})=>s==="playing"),(0,E.once)()).subscribe(()=>t=!0);e.add(r)})),e.add(this.providerError$.subscribe(r=>{let s=this.current$.getValue().destination,n={error:r,currentDestination:s};if(s==="CHROMECAST")this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider("SCREEN"),()=>this.params.dependencies.chromecastInitializer.disconnect());else{let u=r.category===E.ErrorCategory.NETWORK,o=r.category===E.ErrorCategory.FATAL,l=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),p=i<this.params.tuning.providerErrorLimit&&!o,c=this.videoCodecsIterator&&!this.videoCodecsIterator.isLast()&&this.params.tuning.dash.codecsPrioritizeEnabled,d=l&&!o&&(u&&t||!p);n={...n,isNetworkError:u,isFatalError:o,haveFailoverHost:l,tryFailover:d,canReinitProvider:p},p?(i++,this.reinitProvider()):d?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):c?this.switchToNextVideoCodec():(i=0,this.switchToNextProvider(s??"SCREEN"))}r.traceAsLog?this.tracer.log("providerInfo",(0,E.flattenObject)(n)):this.tracer.error("providerError",(0,E.flattenObject)(n))})),e}};var K=require("@vkontakte/videoplayer-shared");var v$=5e3,hv="one_video_throughput",fv="one_video_rtt",rs=window.navigator.connection,mv=()=>{let a=rs?.downlink;if((0,K.isNonNullable)(a)&&a!==10)return a*1e3},bv=()=>{let a=rs?.rtt;if((0,K.isNonNullable)(a)&&a!==3e3)return a},gv=(a,e,t)=>{let i=t*8,r=i/a;return i/(r+e)},Jl=class a{constructor(e){this.subscription=new K.Subscription;this.concurrentDownloads=new Set;this.tuningConfig=e;let t=a.load(hv)||(e.useBrowserEstimation?mv():void 0)||v$,i=a.load(fv)??(e.useBrowserEstimation?bv():void 0)??0;if(this.throughput$=new K.ValueSubject(t),this.rtt$=new K.ValueSubject(i),this.rttAdjustedThroughput$=new K.ValueSubject(gv(t,i,e.rttPenaltyRequestSize)),this.throughput=jt.getSmoothedValue(t,-1,e),this.rtt=jt.getSmoothedValue(i,1,e),e.useBrowserEstimation){let r=()=>{let n=mv();n&&this.throughput.next(n);let u=bv();(0,K.isNonNullable)(u)&&this.rtt.next(u)};rs&&"onchange"in rs&&this.subscription.add((0,K.fromEvent)(rs,"change").subscribe(r)),r()}this.subscription.add(this.throughput.smoothed$.subscribe(r=>{K.safeStorage.set(hv,r.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(r=>{K.safeStorage.set(fv,r.toFixed(0))})),this.subscription.add(this.throughput.debounced$.pipe((0,K.map)(r=>Math.round(r))).subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add((0,K.combine)({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe((0,K.map)(({throughput:r,rtt:s})=>gv(r,s,e.rttPenaltyRequestSize)),(0,K.filter)(r=>{let s=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(r-s)/s>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,i=(0,K.now)(),r=new K.Subscription;switch(this.subscription.add(r),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:r.add((0,K.fromEvent)(e,"progress").pipe((0,K.once)()).subscribe(s=>{t=s.loaded,i=(0,K.now)()}));break;case 1:case 0:r.add((0,K.fromEvent)(e,"loadstart").subscribe(()=>{t=0,i=(0,K.now)()}));break}r.add((0,K.fromEvent)(e,"loadend").subscribe(s=>{if(e.status===200){let n=s.loaded,u=(0,K.now)(),o=n-t,l=u-i;this.addRawSpeed(o,l,1)}this.concurrentDownloads.delete(e),r.unsubscribe()}))}trackStream(e,t=!1){let i=e.getReader();if(!i){e.cancel("Could not get reader");return}let r=0,s=(0,K.now)(),n=0,u=(0,K.now)(),o=p=>{this.concurrentDownloads.delete(e),i.releaseLock(),e.cancel(`Throughput Estimator error: ${p}`).catch(()=>{})},l=async({done:p,value:c})=>{if(p)!t&&this.addRawSpeed(r,(0,K.now)()-s,1),this.concurrentDownloads.delete(e);else if(c){if(t){let d=(0,K.now)();if(d-u>this.tuningConfig.lowLatency.continuesByteSequenceInterval||d-s>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let m=u-s;m&&this.addRawSpeed(n,m,1,t),n=c.byteLength,s=(0,K.now)()}else n+=c.byteLength;u=(0,K.now)()}else r+=c.byteLength,n+=c.byteLength,n>=this.tuningConfig.streamMinSampleSize&&(0,K.now)()-u>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,(0,K.now)()-u,this.concurrentDownloads.size),n=0,u=(0,K.now)());await i?.read().then(l,o)}};this.concurrentDownloads.add(e),i?.read().then(l,o)}addRawSpeed(e,t,i=1,r=!1){if(a.sanityCheck(e,t,r)){let s=e*8/t;this.throughput.next(s*i)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,i=!1){let r=e*8/t;return!(!r||!isFinite(r)||r>1e6||r<30||i&&e<1e4||!i&&e<10*1024||!i&&t<=20)}static load(e){let t=K.safeStorage.get(e);if((0,K.isNonNullable)(t))return parseInt(t,10)??void 0}},Sv=Jl;var Ci=require("@vkontakte/videoplayer-shared"),vv={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:{maxBitrateFactorAtEmptyBuffer:4,bitrateFactorAtEmptyBuffer:2.8,minBitrateFactorAtEmptyBuffer:1.5,bitrateAudioFactorAtEmptyBuffer:10,maxBitrateFactorAtFullBuffer:3,bitrateFactorAtFullBuffer:2,minBitrateFactorAtFullBuffer:1,bitrateAudioFactorAtFullBuffer:7,minVideoAudioRatio:5,minAvailableThroughputAudioRatio:5,usePixelRatio:!0,pixelRatioMultiplier:void 0,pixelRatioLogBase:3,pixelRatioLogCoefficients:[1,0,1],limitByContainer:!0,maxContainerSizeFactor:2,containerSizeFactor:1.3,minContainerSizeFactor:1,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldownIncreaseQuality:15e3,trackCooldownDecreaseQuality:3e3,backgroundVideoQualityLimit:Ci.VideoQuality.Q_4320P,activeVideoAreaThreshold:.1,highQualityLimit:Ci.VideoQuality.Q_720P,trafficSavingLimit:Ci.VideoQuality.Q_480P},stallsManager:{enabled:!0,ignoreDynamicAbrForShortVideo:!1,stallDurationNoDataBeforeQualityDecrease:500,stallDurationToBeCount:100,stallCountBeforeQualityDecrease:3,resetQualityRestrictionTimeout:1e4,ignoreStallsOnSeek:!0,stallsMetricsHistoryLength:20,maxPossibleStallDuration:3e4,minTvtToBeCounted:120,maxTvtToBeCounted:10800,significantTvt:600,targetStallsDurationPerTvt:1,deviationStallsDurationPerTvt:.5,criticalStallsDurationPerTvt:6,abrAdjustingSpeed:.1,emaAlpha:.6,useTotalStallsDurationPerTvt:!0,useAverageStallsDurationPerTvt:!0,useEmaStallsDurationPerTvt:!0},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:Ci.VideoQuality.Q_480P},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,seekBiasInTheEnd:2e3,maxSegmentDurationLeftToSelectNextSegment:3e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:15e3,crashOnStallTimeout:25e3,crashOnStallTWithoutDataTimeout:5e3,enableSubSegmentBufferFeeding:!0,bufferEmptinessTolerance:100,useNewRepresentationSwitch:!1,useDelayedRepresentationSwitch:!1,useSmartRepresentationSwitch:!1,useFetchPriorityHints:!0,enableBaseUrlSupport:!0,maxSegmentRetryCount:5,sourceOpenTimeout:1e3,vktvAbrThrottle:0,timeupdateEventTickThrottle:300,fetcherBufferOptimisation:!0,codecsPrioritizeEnabled:!1,usePersistentGaps:!1,abrThrottle:0,useVideoElementWaitingCurrentTimeReassign:!0,stallWatchdogInterval:100,liveUpdateInterval:1e3,liveStallReinitInterval:3e3,ignoreNetworkErrorsOnLoadInit:!1},dashCmafLive:{externalStopControl:!1,keepSilentStallWatchdogWhenNotActive:!1,maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,maxLiveDuration:7200,catchupLiveForMutedInactiveTab:!0,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:250,playbackCatchupSpeedup:.05,isActiveOnDefault:!1,bufferEstimator:{emaAlpha:.45,changeThreshold:.05,deviationDepth:20,deviationFactor:.5,extremumInterval:5}}},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1,lowLatencyActiveLiveDelay:3e3,activeLiveDelay:5e3,maxPausedTime:5e3},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,forceFormat:void 0,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:"07A4434E",useWebmBigRequest:!1,webmCodec:"vp9",androidPreferredFormat:"dash",iosPreferredFormat:"hls",preferCMAF:!1,preferWebRTC:!1,preferMultiStream:!1,preferHDR:!1,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,seekNearDurationBias:1,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useHlsJs:!1,useNativeHLSTextTracks:!1,useNewSwitchTo:!1,useNewDashProvider:!1,useNewAutoSelectVideoTrack:!1,useSafariEndlessRequestBugfix:!0,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,manifestRetryInterval:300,manifestRetryMaxInterval:1e4,manifestRetryMaxCount:10,audioVideoSyncRate:20,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50},useVolumeMultiplier:!1,ignoreAudioRendererError:!1,useEnableSubtitlesParam:!1,useHlsLiveNewTextManager:!1,exposeInternalsToGlobal:!1,hlsLiveNewTextManagerDownloadThreshold:4e3,disableYandexPiP:!1,asyncResolveClientChecker:!1,autostartOnlyIfVisible:!1,changePlaybackStateToPausedWhenEnded:!1,suppressExceptionsInObservables:!0},yv=a=>({...(0,Ci.fillWithDefault)(a,vv),configName:[...a.configName??[],...vv.configName]});var f=require("@vkontakte/videoplayer-shared");var Qt=require("@vkontakte/videoplayer-shared"),Zl=({seekState:a,position$:e})=>(0,Qt.merge)(a.stateChangeEnded$.pipe((0,Qt.map)(({to:t})=>t.state==="none"?void 0:(t.position??NaN)/1e3),(0,Qt.filter)(Qt.isNonNullable)),e.pipe((0,Qt.filter)(()=>a.getState().state==="none")));var Tv=require("@vkontakte/videoplayer-shared"),Iv=a=>{let e=typeof a.container=="string"?document.getElementById(a.container):a.container;return(0,Tv.assertNonNullable)(e,`Wrong container or containerId {${a.container}}`),e};var eo=require("@vkontakte/videoplayer-shared"),Ev=(a,e,t,i)=>{a!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&t?.getValue().length===0?t.pipe((0,eo.filter)(r=>r.length>0),(0,eo.once)()).subscribe(r=>{r.find(i)&&e.startTransitionTo(a)}):(a===void 0||t?.getValue().find(i))&&e.startTransitionTo(a)};var as=class{constructor(e={configName:[]},t=f.TracerFactory.createRootTracer(!1),i){this.subscription=new f.Subscription;this.logger=new f.Logger;this.abrLogger=this.logger.createComponentLog("ABR");this.internalsExposure=null;this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new f.ValueSubject(!1);this.hasLiveOffsetByPausedTimer=0;this.playerInitRequest=0;this.playerInited=new f.ValueSubject(!1);this.wasSetStartedQuality=!1;this.desiredState={playbackState:new Z("stopped"),seekState:new Z({state:"none"}),volume:new Z({volume:1,muted:!1}),videoTrack:new Z(void 0),videoStream:new Z(void 0),audioStream:new Z(void 0),autoVideoTrackSwitching:new Z(!0),autoVideoTrackLimits:new Z({}),isLooped:new Z(!1),isLowLatency:new Z(!1),playbackRate:new Z(1),externalTextTracks:new Z([]),internalTextTracks:new Z([]),currentTextTrack:new Z(void 0),textTrackCuesSettings:new Z({}),cameraOrientation:new Z({x:0,y:0})};this.info={playbackState$:new f.ValueSubject(void 0),position$:new f.ValueSubject(0),duration$:new f.ValueSubject(1/0),muted$:new f.ValueSubject(!1),volume$:new f.ValueSubject(1),availableVideoStreams$:new f.ValueSubject([]),currentVideoStream$:new f.ValueSubject(void 0),availableQualities$:new f.ValueSubject([]),availableQualitiesFps$:new f.ValueSubject({}),currentQuality$:new f.ValueSubject(void 0),isAutoQualityEnabled$:new f.ValueSubject(!0),autoQualityLimitingAvailable$:new f.ValueSubject(!1),autoQualityLimits$:new f.ValueSubject({}),predefinedQualityLimitType$:new f.ValueSubject("unknown"),availableAudioStreams$:new f.ValueSubject([]),currentAudioStream$:new f.ValueSubject(void 0),availableAudioTracks$:new f.ValueSubject([]),isAudioAvailable$:new f.ValueSubject(!0),currentPlaybackRate$:new f.ValueSubject(1),currentBuffer$:new f.ValueSubject({start:0,end:0}),isBuffering$:new f.ValueSubject(!0),isStalled$:new f.ValueSubject(!1),isEnded$:new f.ValueSubject(!1),isLooped$:new f.ValueSubject(!1),isLive$:new f.ValueSubject(void 0),isLiveEnded$:new f.ValueSubject(null),canPlayLiveTailBuffer$:new f.ValueSubject(!1),canChangePlaybackSpeed$:new f.ValueSubject(void 0),atLiveEdge$:new f.ValueSubject(void 0),atLiveDurationEdge$:new f.ValueSubject(void 0),liveTime$:new f.ValueSubject(void 0),liveBufferTime$:new f.ValueSubject(void 0),liveLatency$:new f.ValueSubject(void 0),currentFormat$:new f.ValueSubject(void 0),availableTextTracks$:new f.ValueSubject([]),currentTextTrack$:new f.ValueSubject(void 0),throughputEstimation$:new f.ValueSubject(void 0),rttEstimation$:new f.ValueSubject(void 0),videoBitrate$:new f.ValueSubject(void 0),hostname$:new f.ValueSubject(void 0),httpConnectionType$:new f.ValueSubject(void 0),httpConnectionReused$:new f.ValueSubject(void 0),surface$:new f.ValueSubject("none"),chromecastState$:new f.ValueSubject("NOT_AVAILABLE"),chromecastDeviceName$:new f.ValueSubject(void 0),intrinsicVideoSize$:new f.ValueSubject(void 0),availableSources$:new f.ValueSubject(void 0),is3DVideo$:new f.ValueSubject(!1),currentVideoSegmentLength$:new f.ValueSubject(0),currentAudioSegmentLength$:new f.ValueSubject(0)};this.events={inited$:new f.Subject,ready$:new f.Subject,started$:new f.Subject,playing$:new f.Subject,paused$:new f.Subject,stopped$:new f.Subject,willReady$:new f.Subject,willStart$:new f.Subject,willResume$:new f.Subject,willPause$:new f.Subject,willStop$:new f.Subject,willDestruct$:new f.Subject,watchCoverageRecord$:new f.Subject,watchCoverageLive$:new f.Subject,managedError$:new f.Subject,fatalError$:new f.Subject,fetcherRecoverableError$:new f.Subject,ended$:new f.Subject,looped$:new f.Subject,seeked$:new f.Subject,willSeek$:new f.Subject,autoplaySoundProhibited$:new f.Subject,manifestRequested$:new f.Subject,firstBytesManifest$:new f.Subject,manifestReceived$:new f.Subject,firstBytesRequested$:new f.Subject,firstBytesReceived$:new f.Subject,firstBytes$:new f.Subject,loadedMetadata$:new f.Subject,firstFrame$:new f.Subject,canplay$:new f.Subject,log$:new f.Subject,fetcherError$:new f.Subject,severeStallOccured$:new f.Subject};this.experimental={element$:new f.ValueSubject(void 0),tuningConfigName$:new f.ValueSubject([]),enableDebugTelemetry$:new f.ValueSubject(!1),dumpTelemetry:Tb,getCurrentTime$:new f.ValueSubject(null)};if(this.initLogs(),this.tuning=yv(e),this.tracer=t,this.tuning.suppressExceptionsInObservables&&((0,ec.default)(this.info).forEach(r=>r.setSuppressErrors(!0)),(0,ec.default)(this.events).forEach(r=>r.setSuppressErrors(!0))),this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new Es({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new Sv(this.tuning.throughputEstimator),e.exposeInternalsToGlobal&&(this.internalsExposure=new f.InternalsExposure("core",(0,f.getPlayerId)(i?.playerId)),this.internalsExposure.expose({player:this})),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(r,s,n)=>{let u=Reflect.get(r,s,n);return typeof u!="function"?u:(...o)=>{try{return u.apply(r,o)}catch(l){let p=o.map(h=>JSON.stringify(h,(m,b)=>{let S=typeof b;return(0,xv.default)(["number","string","boolean"],S)?b:b===null?null:`<${S}>`})),c=`Player.${String(s)}`,d=`Exception calling ${c} (${p.join(", ")})`;throw this.events.fatalError$.next({id:c,category:f.ErrorCategory.WTF,message:d,thrown:l}),l}}}})}initVideo(e){this.config=e,this.internalsExposure?.expose({config:e,logger:this.logger,tuning:this.tuning}),this.setMuted(this.tuning.isAudioDisabled);let t=()=>{let{container:s,...n}=e;this.tracer.log("initVideo",(0,f.flattenObject)(n)),this.domContainer=Iv(e),this.chromecastInitializer.contentId=e.meta?.videoId,this.providerContainer=new is({sources:e.sources,meta:e.meta??{},failoverHosts:e.failoverHosts??[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,tracer:this.tracer,logger:this.logger,abrLogger:this.abrLogger},tuning:this.tuning,volumeMultiplier:e.volumeMultiplier,panelSize:e.panelSize}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.initTracerSubscription(),this.providerContainer.init(),this.setLiveLowLatency(this.tuning.dashCmafLive.lowLatency.isActiveOnDefault),this.initDebugTelemetry(),this.initWakeLock(),this.playerInited.next(!0)},i=()=>{this.tuning.autostartOnlyIfVisible&&window.requestAnimationFrame?this.playerInitRequest=window.requestAnimationFrame(()=>t()):t()},r=()=>{this.tuning.asyncResolveClientChecker?j.isInited$.pipe((0,f.filter)(s=>!!s),(0,f.once)()).subscribe(()=>{console.log("Core SDK async start"),i()}):i()};return this.isNotActiveTabCase()?(this.tracer.log("request play from hidden tab"),(0,f.fromEvent)(document,"visibilitychange").pipe((0,f.once)()).subscribe(r)):r(),this}destroy(){this.tracer.log("destroy"),window.clearTimeout(this.hasLiveOffsetByPausedTimer),this.playerInitRequest&&window.cancelAnimationFrame(this.playerInitRequest),this.events.willDestruct$.next(),this.stop(),this.providerContainer?.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe(),this.tracer.end(),this.internalsExposure?.destroy()}waitInit(e){this.playerInited.getValue()?e():this.subscription.add(this.playerInited.pipe((0,f.filter)(t=>!!t),(0,f.once)()).subscribe(e))}prepare(){return this.waitInit(()=>{let e=this.desiredState.playbackState;this.tracer.log("prepare",{currentPlayBackState:e.getState()}),e.getState()==="stopped"&&e.startTransitionTo("ready")}),this}play(){return this.waitInit(()=>{let e=this.desiredState.playbackState;this.tracer.log("play",{currentPlayBackState:e.getState()}),e.getState()!=="playing"&&e.startTransitionTo("playing")}),this}pause(){return this.waitInit(()=>{let e=this.desiredState.playbackState;this.tracer.log("pause",{currentPlayBackState:e.getState()}),e.getState()!=="paused"&&e.startTransitionTo("paused")}),this}stop(){return this.waitInit(()=>{let e=this.desiredState.playbackState;this.tracer.log("stop",{currentPlayBackState:e.getState()}),e.getState()!=="stopped"&&e.startTransitionTo("stopped")}),this}seekTime(e,t=!0){return this.waitInit(()=>{let i=this.info.duration$.getValue(),r=this.info.isLive$.getValue(),s=e;e>=i&&!r&&(s=i-this.tuning.seekNearDurationBias),this.tracer.log("seekTime",{duration:i,isLive:r,time:e,calculatedTime:s,forcePrecise:t}),Number.isFinite(s)&&(this.events.willSeek$.next({from:this.getExactTime(),to:s}),this.desiredState.seekState.setState({state:"requested",position:s*1e3,forcePrecise:t}))}),this}seekPercent(e){return this.waitInit(()=>{let t=this.info.duration$.getValue();this.tracer.log("seekPercent",{percent:e,duration:t}),isFinite(t)&&this.seekTime(Math.abs(t)*e,!1)}),this}setVolume(e,t){return this.waitInit(()=>{let i=this.desiredState.volume,s=i.getTransition()?.to.muted??this.info.muted$.getValue(),n=t??(this.tuning.isAudioDisabled||s);this.tracer.log("setVolume",{volume:e,isAudioDisabled:this.tuning.isAudioDisabled,chromecastState:this.chromecastInitializer.castState$.getValue(),muted:n}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setVolume(e):i.startTransitionTo({volume:e,muted:n})}),this}setMuted(e,t=!1){return this.waitInit(()=>{let i=this.desiredState.volume,r=this.tuning.isAudioDisabled&&!t||e,n=i.getTransition()?.to.volume??this.info.volume$.getValue();this.tracer.log("setMuted",{isMuted:e,nextMuted:r,volume:n,isAudioDisabled:this.tuning.isAudioDisabled,chromecastState:this.chromecastInitializer.castState$.getValue()}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setMuted(r):i.startTransitionTo({volume:n,muted:r})}),this}setVideoStream(e){return this.waitInit(()=>{this.desiredState.videoStream.startTransitionTo(e)}),this}setAudioStream(e){return this.waitInit(()=>{this.desiredState.audioStream.startTransitionTo(e)}),this}setQuality(e){return this.waitInit(()=>{(0,f.assertNonNullable)(this.providerContainer);let t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();this.tracer.log("setQuality",{isDelayed:t.length===0,quality:e}),this.desiredState.videoTrack.getState()===void 0&&this.desiredState.videoTrack.getPrevState()===void 0&&t.length===0?this.wasSetStartedQuality?this.providerContainer.providerOutput.availableVideoTracks$.pipe((0,f.filter)(i=>i.length>0),(0,f.once)()).subscribe(i=>{this.setVideoTrackIdByQuality(i,e)}):this.explicitInitialQuality=e:t.length>0&&this.setVideoTrackIdByQuality(t,e)}),this}setAutoQuality(e){return this.waitInit(()=>{this.tracer.log("setAutoQuality",{enable:e}),this.desiredState.autoVideoTrackSwitching.startTransitionTo(e)}),this}setAutoQualityLimits(e){return this.waitInit(()=>{this.tracer.log("setAutoQualityLimits",(0,f.flattenObject)(e)),this.desiredState.autoVideoTrackLimits.startTransitionTo(e)}),this}setPredefinedQualityLimits(e){return this.waitInit(()=>{if(this.info.predefinedQualityLimitType$.getValue()===e)return this;let{highQualityLimit:t,trafficSavingLimit:i}=this.tuning.autoTrackSelection,r;switch(e){case"high_quality":r={min:t,max:void 0};break;case"traffic_saving":r={max:i,min:void 0};break;default:r={max:void 0,min:void 0}}this.setAutoQualityLimits(r)}),this}setPlaybackRate(e){return this.waitInit(()=>{this.tracer.log("setPlaybackRate",{playbackRate:e}),this.desiredState.playbackRate.startTransitionTo(e)}),this}setExternalTextTracks(e){return this.waitInit(()=>{e.length&&this.tracer.log("setExternalTextTracks",(0,f.flattenObject)(e)),this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>({type:"external",...t})))}),this}selectTextTrack(e){return this.waitInit(()=>{Ev(e,this.desiredState.currentTextTrack,this.providerContainer?.providerOutput.availableTextTracks$,t=>t.id===e),this.tracer.log("selectTextTrack",{textTrackId:e})}),this}setTextTrackCueSettings(e){return this.waitInit(()=>{this.tracer.log("setTextTrackCueSettings",{...e}),this.desiredState.textTrackCuesSettings.startTransitionTo(e)}),this}setLiveLowLatency(e){let t=this.info.isLive$.getValue(),i=this.desiredState.isLowLatency.getState();return!t||i===e?this:(this.tracer.log("live switch to low latency "+e),this.desiredState.isLowLatency.setState(e),this.seekTime(0))}setLooped(e){return this.waitInit(()=>{this.tracer.log("setLooped",{isLooped:e}),this.desiredState.isLooped.startTransitionTo(e)}),this}toggleChromecast(){this.tracer.log("toggleChromecast"),this.chromecastInitializer.toggleConnection()}startCameraManualRotation(e,t){return this.waitInit(()=>{let i=this.getScene3D();this.tracer.log("startCameraManualRotation",{isScene3DAvailable:!!i,mx:e,my:t}),i&&i.startCameraManualRotation(e,t)}),this}stopCameraManualRotation(e=!1){return this.waitInit(()=>{let t=this.getScene3D();this.tracer.log("stopCameraManualRotation",{isScene3DAvailable:!!t,immediate:e}),t&&t.stopCameraManualRotation(e)}),this}moveCameraFocusPX(e,t){return this.waitInit(()=>{let i=this.getScene3D();if(this.tracer.log("moveCameraFocusPX",{isScene3DAvailable:!!i,dxpx:e,dypx:t}),i){let r=i.getCameraRotation(),s=i.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:r.x+s.x,y:r.y+s.y})}}),this}holdCamera(){return this.waitInit(()=>{let e=this.getScene3D();e&&e.holdCamera()}),this}releaseCamera(){return this.waitInit(()=>{let e=this.getScene3D();e&&e.releaseCamera()}),this}getExactTime(){if(!this.providerContainer)return 0;let e=this.providerContainer.providerOutput.element$.getValue();if((0,f.isNullable)(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),i=t.state==="none"?void 0:t.position;return(0,f.isNonNullable)(i)?i/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}getScene3D(){let e=this.providerContainer?.current$.getValue();if(e?.provider?.scene3D)return e.provider.scene3D}setIntrinsicVideoSize(...e){let t={width:e.reduce((i,{width:r})=>i||r||0,0),height:e.reduce((i,{height:r})=>i||r||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add((0,f.merge)(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe((0,f.map)(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe((0,f.map)(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe((0,f.map)(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe((0,f.map)(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe((0,f.map)(e=>e.to)).subscribe(e=>{this.info.autoQualityLimits$.next(e);let{highQualityLimit:t,trafficSavingLimit:i}=this.tuning.autoTrackSelection;this.info.predefinedQualityLimitType$.next(Ib(e,t,i))})),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe((0,f.filter)(({from:e})=>e==="stopped"),(0,f.once)()).subscribe(()=>{this.initedAt=(0,f.now)(),this.events.inited$.next()})).add(this.desiredState.playbackState.stateChangeEnded$.subscribe(e=>{switch(e.to){case"ready":this.events.ready$.next();break;case"playing":this.isPlaybackStarted||this.events.started$.next(),this.isPlaybackStarted=!0,this.events.playing$.next();break;case"paused":this.events.paused$.next();break;case"stopped":this.events.stopped$.next()}})).add(this.desiredState.playbackState.stateChangeStarted$.subscribe(e=>{switch(e.to){case"ready":this.events.willReady$.next();break;case"paused":this.events.willPause$.next();break;case"playing":this.isPlaybackStarted?this.events.willResume$.next():this.events.willStart$.next();break;case"stopped":this.events.willStop$.next();break;default:}}))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();this.tracer.log("willSeekEvent",(0,f.flattenObject)(n)),n.state==="requested"?this.desiredState.seekState.setState({...n,state:"applying"}):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:f.ErrorCategory.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.soundProhibitedEvent$.pipe((0,f.once)()).subscribe(this.events.autoplaySoundProhibited$)).add(e.providerOutput.severeStallOccurred$.subscribe(this.events.severeStallOccured$)).add(e.providerOutput.seekedEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();this.tracer.log("seekedEvent",(0,f.flattenObject)(n)),n.state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe((0,f.map)(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe((0,f.map)(n=>n.destination),(0,f.filterChanged)()).subscribe(()=>this.isPlaybackStarted=!1)).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add((0,f.combine)({availableVideoTracks:e.providerOutput.availableVideoTracks$,currentVideoStream:e.providerOutput.currentVideoStream$}).pipe((0,f.map)(({availableVideoTracks:n,currentVideoStream:u})=>n.filter(o=>u?u.id===o.streamId:!0).map(({quality:o})=>o).sort((o,l)=>(0,f.isInvariantQuality)(o)?1:(0,f.isInvariantQuality)(l)?-1:(0,f.isHigher)(l,o)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(n=>{let u={};for(let o of n)o.fps&&(u[o.quality]=o.fps);this.info.availableQualitiesFps$.next(u)})).add(e.providerOutput.availableAudioStreams$.subscribe(this.info.availableAudioStreams$)).add(e.providerOutput.currentVideoStream$.subscribe(this.info.currentVideoStream$)).add(e.providerOutput.currentAudioStream$.subscribe(this.info.currentAudioStream$)).add(e.providerOutput.availableAudioTracks$.subscribe(this.info.availableAudioTracks$)).add(e.providerOutput.isAudioAvailable$.pipe((0,f.filterChanged)()).subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.pipe((0,f.filter)(n=>(0,f.isNonNullable)(n))).subscribe(n=>{this.info.currentQuality$.next(n?.quality),this.info.videoBitrate$.next(n?.bitrate)})).add(e.providerOutput.currentVideoSegmentLength$.pipe((0,f.filterChanged)((n,u)=>Math.round(n)===Math.round(u))).subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.pipe((0,f.filterChanged)((n,u)=>Math.round(n)===Math.round(u))).subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe((0,f.filterChanged)()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe((0,f.filterChanged)()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe((0,f.filterChanged)()).subscribe(this.info.httpConnectionReused$)).add(e.providerOutput.currentTextTrack$.subscribe(this.info.currentTextTrack$)).add(e.providerOutput.availableTextTracks$.subscribe(this.info.availableTextTracks$)).add(e.providerOutput.autoVideoTrackLimitingAvailable$.subscribe(this.info.autoQualityLimitingAvailable$)).add(e.providerOutput.autoVideoTrackLimits$.subscribe(n=>{this.desiredState.autoVideoTrackLimits.setState(n??{})})).add(e.providerOutput.currentBuffer$.pipe((0,f.map)(n=>n?{start:n.from,end:n.to}:{start:0,end:0})).subscribe(this.info.currentBuffer$)).add(e.providerOutput.duration$.subscribe(this.info.duration$)).add(e.providerOutput.isBuffering$.subscribe(this.info.isBuffering$)).add(e.providerOutput.isLive$.subscribe(this.info.isLive$)).add(e.providerOutput.isLiveEnded$.pipe((0,f.tap)(n=>n&&this.stop())).subscribe(this.info.isLiveEnded$)).add(e.providerOutput.canPlayLiveTailBuffer$.subscribe(this.info.canPlayLiveTailBuffer$)).add(e.providerOutput.canChangePlaybackSpeed$.subscribe(this.info.canChangePlaybackSpeed$)).add(e.providerOutput.liveTime$.subscribe(this.info.liveTime$)).add(e.providerOutput.liveBufferTime$.subscribe(this.info.liveBufferTime$)).add(e.providerOutput.liveLatency$.subscribe(this.info.liveLatency$)).add((0,f.combine)({hasLiveOffsetByPaused:(0,f.merge)(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe((0,f.map)(n=>n.to),(0,f.filterChanged)(),(0,f.map)(n=>n==="paused")),isLowLatency:e.providerOutput.isLowLatency$}).subscribe(({hasLiveOffsetByPaused:n,isLowLatency:u})=>{if(window.clearTimeout(this.hasLiveOffsetByPausedTimer),n){this.hasLiveOffsetByPausedTimer=window.setTimeout(()=>{this.hasLiveOffsetByPaused.next(!0)},this.getActiveLiveDelay(u));return}this.hasLiveOffsetByPaused.next(!1)})).add((0,f.combine)({atLiveEdge:(0,f.combine)({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:Zl({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe((0,f.map)(({isLive:n,position:u,isLowLatency:o})=>{let l=this.getActiveLiveDelay(o);return n&&Math.abs(u)<l/1e3}),(0,f.filterChanged)(),(0,f.tap)(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe((0,f.map)(({atLiveEdge:n,hasPausedTimeoutCase:u})=>n&&!u)).subscribe(this.info.atLiveEdge$)).add((0,f.combine)({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe((0,f.map)(({isLive:n,position:u,duration:o})=>n&&(Math.abs(o)-Math.abs(u))*1e3<this.tuning.live.activeLiveDelay),(0,f.filterChanged)(),(0,f.tap)(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe((0,f.map)(n=>n.muted),(0,f.filterChanged)()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe((0,f.map)(n=>n.volume),(0,f.filterChanged)()).subscribe(this.info.volume$)).add(Zl({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(e.providerOutput.seekedEvent$.subscribe(()=>{this.info.isEnded$.getValue()&&this.tuning.changePlaybackStateToPausedWhenEnded&&this.play()})).add((0,f.merge)(e.providerOutput.endedEvent$.pipe((0,f.mapTo)(!0)),e.providerOutput.seekedEvent$.pipe((0,f.mapTo)(!1))).pipe((0,f.filterChanged)()).subscribe(this.info.isEnded$)).add(e.providerOutput.endedEvent$.subscribe(this.events.ended$)).add(e.providerOutput.loopedEvent$.subscribe(this.events.looped$)).add(e.providerError$.subscribe(this.events.managedError$)).add(e.providerOutput.fetcherRecoverableError$.subscribe(this.events.fetcherRecoverableError$)).add(e.providerOutput.fetcherError$.subscribe(this.events.fatalError$)).add(e.volumeMultiplierError$.subscribe(this.events.managedError$)).add(e.noAvailableProvidersError$.pipe((0,f.map)(n=>({id:n?`No${n}`:"NoProviders",category:f.ErrorCategory.VIDEO_PIPELINE,message:n?`${n} was forced but failed or not available`:"No suitable providers or all providers failed"}))).subscribe(this.events.fatalError$)).add(e.providerOutput.element$.subscribe(this.experimental.element$)).add(e.providerOutput.getCurrentTime$.subscribe(this.experimental.getCurrentTime$)).add(e.providerOutput.manifestRequested$.pipe((0,f.once)()).subscribe(this.events.manifestRequested$)).add(e.providerOutput.firstBytesManifest$.pipe((0,f.once)()).subscribe(this.events.firstBytesManifest$)).add(e.providerOutput.manifestReceived$.pipe((0,f.once)()).subscribe(this.events.manifestReceived$)).add(e.providerOutput.firstBytesRequested$.pipe((0,f.once)()).subscribe(this.events.firstBytesRequested$)).add(e.providerOutput.firstBytesReceived$.pipe((0,f.once)()).subscribe(this.events.firstBytesReceived$)).add(e.providerOutput.firstBytesEvent$.pipe((0,f.once)(),(0,f.map)(n=>n??(0,f.now)()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe((0,f.once)(),(0,f.map)(()=>(0,f.now)()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe((0,f.once)(),(0,f.map)(()=>(0,f.now)()-this.initedAt)).subscribe(this.events.canplay$)).add(this.throughputEstimator.throughput$.subscribe(this.info.throughputEstimation$)).add(this.throughputEstimator.rtt$.subscribe(this.info.rttEstimation$)).add(e.providerOutput.availableSources$.subscribe(this.info.availableSources$));let t=new f.ValueSubject(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let i=new f.ValueSubject(!0);this.subscription.add(e.current$.subscribe(()=>i.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe((0,f.filter)(({to:n})=>n==="playing"),(0,f.once)()).subscribe(()=>i.next(!1)));let r=0,s=(0,f.merge)(e.providerOutput.isBuffering$,t,i).pipe((0,f.map)(()=>{let n=e.providerOutput.isBuffering$.getValue(),u=t.getValue()||i.getValue();return n&&!u}),(0,f.filterChanged)());this.subscription.add(s.subscribe(n=>{n?r=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(r),this.info.isStalled$.next(!1))})),this.subscription.add((0,f.merge)(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{let n=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:n?.videoWidth,height:n?.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{let u=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:n?.size?.width,height:n?.size?.height},{width:u?.videoWidth,height:u?.videoHeight})})).add(e.providerOutput.is3DVideo$.subscribe(this.info.is3DVideo$)),this.subscription.add((0,f.merge)(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,e.providerOutput.elementVisible$,this.chromecastInitializer.castState$).subscribe(()=>{let n=e.providerOutput.inPiP$.getValue(),u=e.providerOutput.inFullscreen$.getValue(),o=e.providerOutput.element$.getValue(),l=e.providerOutput.elementVisible$.getValue(),p=this.chromecastInitializer.castState$.getValue(),c;p==="CONNECTED"?c="second_screen":o?l?n?c="pip":u?c="fullscreen":c="inline":c="invisible":c="none",this.info.surface$.getValue()!==c&&this.info.surface$.next(c)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe((0,f.map)(e=>e?.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){let t=new f.Subscription;this.subscription.add(t),this.subscription.add(e.current$.pipe((0,f.filterChanged)((i,r)=>i.provider===r.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe((0,f.filter)(i=>i.length>0),(0,f.once)()).subscribe(i=>{this.setStartingVideoTrack(i)}))}))}setStartingVideoTrack(e){let t;this.wasSetStartedQuality=!0;let i=this.explicitInitialQuality??this.info.currentQuality$.getValue();i&&(t=e.find(({quality:r})=>r===i),t||this.setAutoQuality(!0)),t||(t=Rt(e,{container:this.domContainer.getBoundingClientRect(),panelSize:this.config.panelSize,estimatedThroughput:this.throughputEstimator.throughput$.getValue(),tuning:this.tuning.autoTrackSelection,limits:this.desiredState.autoVideoTrackLimits.getState(),playbackRate:this.info.currentPlaybackRate$.getValue(),forwardBufferHealth:0,abrLogger:this.abrLogger})),this.desiredState.videoTrack.startTransitionTo(t),this.info.currentQuality$.next(t.quality),this.info.videoBitrate$.next(t.bitrate)}initLogs(){this.subscription.add((0,f.merge)(this.desiredState.videoTrack.stateChangeStarted$.pipe((0,f.map)(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe((0,f.map)(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe((0,f.map)(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe((0,f.map)(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe((0,f.map)(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe((0,f.map)(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe((0,f.map)(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe((0,f.map)(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe((0,f.map)(e=>({component:"desiredState",message:`[${e.entity} change] ${e.type}: ${JSON.stringify(e.transition)}`}))).subscribe(this.logger.log)),this.subscription.add(this.logger.log$.subscribe(this.events.log$))}initDebugTelemetry(){let e=this.providerContainer?.providerOutput;(0,f.assertNonNullable)(this.providerContainer),(0,f.assertNonNullable)(e),yb(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(t=>vb(t)),this.providerContainer.current$.subscribe(({type:t})=>ia("provider",t)),e.duration$.subscribe(t=>ia("duration",t)),e.availableVideoTracks$.pipe((0,f.filter)(t=>!!t.length),(0,f.once)()).subscribe(t=>ia("tracks",t)),this.events.fatalError$.subscribe(new Fe("fatalError")),this.events.managedError$.subscribe(new Fe("managedError")),e.position$.subscribe(new Fe("position")),e.currentVideoTrack$.pipe((0,f.map)(t=>t?.quality)).subscribe(new Fe("quality")),this.info.currentBuffer$.subscribe(new Fe("buffer")),e.isBuffering$.subscribe(new Fe("isBuffering"))].forEach(t=>this.subscription.add(t)),ia("codecs",j.video.supportedCodecs)}initTracerSubscription(){let e=(0,f.getTraceSubscriptionMethod)(this.tracer.log.bind(this.tracer)),t=(0,f.getTraceSubscriptionMethod)(this.tracer.error.bind(this.tracer));this.subscription.add(this.info.playbackState$.subscribe(e("playbackState"))).add(this.info.isLooped$.subscribe(e("isLooped"))).add(this.info.currentPlaybackRate$.pipe((0,f.filterChanged)()).subscribe(e("currentPlaybackRate"))).add(this.info.isAutoQualityEnabled$.subscribe(e("isAutoQualityEnabled"))).add(this.info.autoQualityLimits$.subscribe(e("autoQualityLimits"))).add(this.info.currentFormat$.subscribe(e("currentFormat"))).add(this.info.availableQualities$.subscribe(e("availableQualities"))).add(this.info.availableQualitiesFps$.subscribe(e("availableQualitiesFps"))).add(this.info.availableAudioTracks$.subscribe(e("availableAudioTracks"))).add(this.info.isAudioAvailable$.subscribe(e("isAudioAvailable"))).add((0,f.combine)({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe((0,f.filter)(({currentQuality:i,videoBitrate:r})=>!!i&&!!r),(0,f.filterChanged)((i,r)=>i.currentQuality===r.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe((0,f.filter)(i=>i>0),(0,f.filterChanged)()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe((0,f.filter)(i=>i>0),(0,f.filterChanged)()).subscribe(e("currentAudioSegmentLength"))).add(this.info.hostname$.subscribe(e("hostname"))).add(this.info.currentTextTrack$.subscribe(e("currentTextTrack"))).add(this.info.availableTextTracks$.subscribe(e("availableTextTracks"))).add(this.info.autoQualityLimitingAvailable$.subscribe(e("autoQualityLimitingAvailable"))).add((0,f.combine)({currentBuffer:this.info.currentBuffer$.pipe((0,f.filter)(i=>i.end>0),(0,f.filterChanged)((i,r)=>i.end===r.end&&i.start===r.start)),position:this.info.position$.pipe((0,f.filterChanged)())}).pipe((0,f.throttle)(1e3)).subscribe(e("currentBufferAndPosition"))).add(this.info.duration$.pipe((0,f.filterChanged)()).subscribe(e("duration"))).add(this.info.isBuffering$.subscribe(e("isBuffering"))).add(this.info.isLive$.pipe((0,f.filterChanged)()).subscribe(e("isLive"))).add(this.info.canChangePlaybackSpeed$.pipe((0,f.filterChanged)()).subscribe(e("canChangePlaybackSpeed"))).add((0,f.combine)({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe((0,f.filter)(({liveTime:i,liveBufferTime:r})=>!!i&&!!r),(0,f.throttle)(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe((0,f.filterChanged)(),(0,f.filter)(i=>i===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe((0,f.filterChanged)(),(0,f.filter)(i=>i===!0)).subscribe(e("atLiveDurationEdge"))).add(this.info.muted$.pipe((0,f.filterChanged)()).subscribe(e("muted"))).add(this.info.volume$.pipe((0,f.filterChanged)()).subscribe(e("volume"))).add(this.info.isEnded$.pipe((0,f.filterChanged)(),(0,f.filter)(i=>i===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add((0,f.combine)({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe((0,f.filter)(({throughputEstimation:i,rtt:r})=>!!i&&!!r),(0,f.throttle)(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe((0,f.filterChanged)(),(0,f.filter)(i=>i===!0)).subscribe(e("is3DVideo"))).add(this.info.surface$.subscribe(e("surface"))).add(this.events.ended$.subscribe(e("ended"))).add(this.events.looped$.subscribe(e("looped"))).add(this.events.managedError$.subscribe(t("managedError"))).add(this.events.fatalError$.subscribe(t("fatalError"))).add(this.events.firstBytes$.subscribe(e("firstBytes"))).add(this.events.firstFrame$.subscribe(e("firstFrame"))).add(this.events.canplay$.subscribe(e("canplay")))}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e,t=()=>{e?.release(),e=void 0},i=async()=>{t(),e=await window.navigator.wakeLock.request("screen").catch(r=>{r instanceof DOMException&&r.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:f.ErrorCategory.DOM,message:String(r)})})};this.subscription.add((0,f.merge)((0,f.fromEvent)(document,"visibilitychange"),(0,f.fromEvent)(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{let r=document.visibilityState==="visible",s=this.desiredState.playbackState.getState()==="playing",n=!!e&&!e?.released;r&&s?n||i():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){let i=e.find(r=>r.quality===t);this.tracer.log("setVideoTrackIdByQuality",(0,f.flattenObject)({quality:t,availableTracks:(0,f.flattenObject)(e),track:(0,f.flattenObject)(i),isAutoQuality:!i})),i?this.desiredState.videoTrack.startTransitionTo(i):this.setAutoQuality(!0)}getActiveLiveDelay(e=!1){return e?this.tuning.live.lowLatencyActiveLiveDelay:this.tuning.live.activeLiveDelay}isNotActiveTabCase(){return document.hidden&&this.tuning.autoplayOnlyInActiveTab&&!ua()}};var Ct=require("@vkontakte/videoplayer-shared"),y$=`@vkontakte/videoplayer-core@${ro}`;
180
+ `),s=0;for(let n=0;n<r.length;++n){let u=r[n];switch(!0){case u.startsWith("#EXTINF:"):{let o=r[++n],l=new URL(o,t).toString(),p=Number(this.extractPlaylistRowValue("#EXTINF:",u))*1e3;if(i.segments.push({time:{from:s,to:s+p},url:l}),s=s+p,!i.segmentStartTime){let c=new Date(i.vkStartTime).valueOf(),d=new Date(i.programDateTime).valueOf();i.segmentStartTime=d-c}break}case u.startsWith("#EXT-X-TARGETDURATION:"):i.targetDuration=Number(this.extractPlaylistRowValue("#EXT-X-TARGETDURATION:",u));break;case u.startsWith("#EXT-X-MEDIA-SEQUENCE:"):i.mediaSequence=Number(this.extractPlaylistRowValue("#EXT-X-MEDIA-SEQUENCE:",u));break;case u.startsWith("#EXT-X-VK-PLAYBACK-DURATION:"):i.vkPlaybackDuration=Number(this.extractPlaylistRowValue("#EXT-X-VK-PLAYBACK-DURATION:",u));break;case u.startsWith("#EXT-X-PROGRAM-DATE-TIME:"):{let o=this.extractPlaylistRowValue("#EXT-X-PROGRAM-DATE-TIME:",u);i.programDateTime=o;let l=new Date(o);l.setMilliseconds(0),s=l.valueOf();break}case u.startsWith("#EXT-X-VK-START-TIME:"):i.vkStartTime=this.extractPlaylistRowValue("#EXT-X-VK-START-TIME:",u);break}}return i}extractPlaylistRowValue(e,t){switch(e){case"#EXTINF:":return t.substring(e.length,t.length-1);default:return t.substring(e.length)}}processLiveTime(e){if((0,rt.isNonNullable)(e)&&this.currentTextTrackData){let{segments:t}=this.currentTextTrackData.playlist,{from:i}=t[0].time,{to:r}=t[t.length-1].time;if(e<i||e>r)return;r-e<this.params.downloadThreshold&&this.fetchNextManifestData();for(let n of t)if(n.time.from<=e&&n.time.to>=e){this.availableTextTracks$.next([{...this.currentTextTrackData.textTrack,url:n.url,isAuto:!0}]);break}}}async fetchNextManifestData(){try{if(this.abortControllers.nextManifest)return;this.abortControllers.nextManifest=new ue;let{textTracks:e}=await this.fetchManifestData(),t=await this.parseTextTracks(e,this.params.sourceUrl);this.currentTextTrackData&&t&&(this.currentTextTrackData.playlist.segments=t.playlist.segments)}catch(e){this.error("fetchNextManifestData",e)}finally{this.abortControllers.nextManifest=null}}async fetchManifestData(){let e=this.prepareUrl??this.params.sourceUrl;return await this.params.fetchManifestData(e,{signal:this.abortControllers.destroy.signal})}error(e,t){this.error$.next({id:"[LiveTextManager][HLS_LIVE_CMAF]",category:rt.ErrorCategory.WTF,thrown:t,message:e})}};var Ja=class{constructor(e){this.subscription=new re.Subscription;this.videoState=new Z("stopped");this.textTracksManager=null;this.liveTextManager=null;this.manifests$=new re.ValueSubject([]);this.liveOffset=new xi;this.manifestStartTime$=new re.ValueSubject(void 0);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),u=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i==="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"),B(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||u){let p=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(p),this.prepare(),u&&this.params.output.autoVideoTrackLimits$.next(u.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if(r?.to!=="paused"&&l.state==="requested"){this.videoState.startTransitionTo("ready"),this.seek(l.position&&l.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(t){case"ready":i==="ready"?B(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),B(this.params.desiredState.playbackState,"paused")):i==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":i==="paused"?(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.video.paused?this.videoState.setState("paused"):this.video.pause()):r?.to==="playing"&&B(this.params.desiredState.playbackState,"playing");return;case"paused":if(i==="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 p=this.liveOffset.getTotalOffset();p>=this.maxSeekBackTime$.getValue()&&(p=0,this.liveOffset.resetTo(p)),this.liveOffset.resume(),this.params.output.position$.next(-p/1e3),this.prepare()}else r?.to==="paused"&&(B(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return(0,re.assertNever)(t)}};this.params=e,this.video=Ue(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:re.VideoQuality.INVARIANT,url:this.params.source.url};let t=(i,r)=>Xn(i,this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},r);this.params.tuning.useHlsLiveNewTextManager?this.liveTextManager=new Jn(this.params.output.liveTime$,this.video,t,this.params.source.url,this.params.tuning.hlsLiveNewTextManagerDownloadThreshold):this.textTracksManager=new ot(e.source.url),t(this.generateLiveUrl()).then(({qualityManifests:i,textTracks:r})=>{i.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:re.ErrorCategory.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),this.liveTextManager?.processTextTracks(r,this.params.source.url),this.manifests$.next([this.masterManifest,...i])}).catch(i=>{this.params.output.error$.next({id:"ExtractHlsQualities",category:re.ErrorCategory.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:i})}),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(Me(this.params.source.url)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.maxSeekBackTime$=new re.ValueSubject(e.source.maxSeekBackTime??1/0),this.subscribe()}selectManifest(){let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),r=t.getTransition(),s=r?.to?.id??t.getState()?.id??"master",n=this.manifests$.getValue();if(!n.length)return;let u=i?"master":s;return i&&!r&&t.startTransitionTo(this.masterManifest),n.find(o=>o.id===u)}subscribe(){let{output:e,desiredState:t}=this.params,i=u=>{e.error$.next({id:"HlsLiveProvider",category:re.ErrorCategory.WTF,message:"HlsLiveProvider internal logic error",thrown:u})},r=We(this.video);this.subscription.add(()=>r.destroy());let s=(u,o)=>this.subscription.add(u.subscribe(o,i));s(r.ended$,e.endedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentBuffer$),s(r.loadedMetadata$,e.firstBytesEvent$),s(r.loadedMetadata$,e.loadedMetadataEvent$),s(r.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(je(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(nt(this.video,t.playbackRate,r.playbackRateState$,i)),s(ut(this.video),e.elementVisible$),this.liveTextManager?(s(this.liveTextManager.getCurrentTime$,this.params.output.getCurrentTime$),s(this.liveTextManager.error$,this.params.output.error$)):this.textTracksManager&&this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),B(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),B(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.liveTextManager&&this.subscription.add(this.liveTextManager.availableTextTracks$.subscribe(u=>{u&&this.params.output.availableTextTracks$.next(u)})),this.subscription.add(this.maxSeekBackTime$.pipe((0,re.filterChanged)(),(0,re.map)(u=>-u/1e3)).subscribe(this.params.output.duration$,i)),this.subscription.add(r.loadedMetadata$.subscribe(()=>{let u=this.params.desiredState.seekState.getState(),o=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),p=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&(0,re.isNonNullable)(l.to)){let c=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let d=this.manifests$.getValue().find(h=>h.id===c);d&&(this.params.output.currentVideoTrack$.next(d),this.params.output.hostname$.next(Me(d.url)))}p&&this.params.desiredState.autoVideoTrackSwitching.setState(p.to),o&&o.from==="changing_manifest"&&this.videoState.setState(o.to),u&&u.state==="requested"&&this.seek(u.position)},i)),this.subscription.add(r.loadedData$.subscribe(()=>{let u=this.video?.getStartDate?.()?.getTime();this.manifestStartTime$.next(u||void 0)},i)),this.subscription.add((0,re.combine)({startTime:this.manifestStartTime$.pipe((0,re.filter)(re.isNonNullable)),currentTime:r.timeUpdate$}).subscribe(({startTime:u,currentTime:o})=>this.params.output.liveTime$.next(u+o*1e3),i)),this.subscription.add(this.manifests$.pipe((0,re.map)(u=>u.map(({id:o,quality:l,size:p,bandwidth:c,fps:d})=>({id:o,quality:l,size:p,fps:d,bitrate:c})))).subscribe(this.params.output.availableVideoTracks$,i));let n=(0,re.merge)(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,(0,re.observableFrom)(["init"])).pipe((0,re.debounce)(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager?.destroy(),this.liveTextManager?.destroy(),this.params.output.element$.next(void 0),He(this.video)}prepare(){let e=this.selectManifest();if((0,re.isNullable)(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),r=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){let{max:u,min:o}=t?.to??i??{};for(let[l,p]of[[u,"mq"],[o,"lq"]]){let c=String(parseFloat(l||""));p&&l&&r.searchParams.set(p,c)}}let s=this.params.format==="HLS_LIVE_CMAF"?2:0,n=ye(r.toString(),this.liveOffset.getTotalOffset(),s);this.liveTextManager?.prepare(n),this.video.setAttribute("src",n),this.video.load(),Ql(n).then(u=>{if(!(0,re.isNullable)(u))this.maxSeekBackTime$.next(u);else{let o=this.params.source.maxSeekBackTime??this.maxSeekBackTime$.getValue();((0,re.isNullable)(o)||!isFinite(o))&&lt(n).then(l=>l.text()).then(l=>{let p=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(l)?.[1];if(p){let c=new URL(p,n).toString();Ql(c).then(d=>{(0,re.isNullable)(d)||this.maxSeekBackTime$.next(d)})}}).catch(()=>{})}})}playIfAllowed(){Qe(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),B(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:re.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,i=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(i),this.params.output.position$.next(-i/1e3),this.params.output.seekedEvent$.next()}generateLiveUrl(){let e=ye(this.params.source.url);if(this.params.tuning.useHlsLiveNewTextManager){let t=new URL(e);t.searchParams.set("enable-subtitles","yes"),e=t.toString()}return e}};var oe=require("@vkontakte/videoplayer-shared");var Za=class{constructor(e){this.subscription=new oe.Subscription;this.videoState=new Z("stopped");this.manifests$=new oe.ValueSubject([]);this.unmuteAfterBrowserResetsHappened=new oe.ValueSubject(!1);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),u=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i==="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"),B(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||u){let p=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(p);let{currentTime:c}=this.video;this.prepare(),u&&this.params.output.autoVideoTrackLimits$.next(u.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:c*1e3,forcePrecise:!0});return}switch(r?.to!=="paused"&&l.state==="requested"&&this.seek(l.position),t){case"ready":i==="ready"?B(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),B(this.params.desiredState.playbackState,"paused")):i==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":i==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):r?.to==="playing"&&B(this.params.desiredState.playbackState,"playing");return;case"paused":i==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):r?.to==="paused"&&B(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return(0,oe.assertNever)(t)}};this.textTracksManager=new ot(e.source.url),this.params=e,this.video=Ue(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:oe.VideoQuality.INVARIANT,url:this.params.source.url},this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Me(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.manifestRequested$.next(),Xn(ye(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:i})=>{this.params.output.firstBytesManifest$.next(),this.manifests$.next([this.masterManifest,...t]),this.params.output.manifestReceived$.next(),this.params.tuning.useNativeHLSTextTracks||this.params.desiredState.internalTextTracks.startTransitionTo(i)},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:oe.ErrorCategory.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),r=t.getTransition(),s=r?.to?.id??t.getState()?.id??"master",n=this.manifests$.getValue();if(!n.length)return;let u=i?"master":s;return i&&(!r||!r.from)&&t.startTransitionTo(this.masterManifest),n.find(o=>o.id===u)}subscribe(){let{output:e,desiredState:t}=this.params,i=u=>{e.error$.next({id:"HlsProvider",category:oe.ErrorCategory.WTF,message:"HlsProvider internal logic error",thrown:u})},r=We(this.video);this.subscription.add(()=>r.destroy());let s=(u,o)=>this.subscription.add(u.subscribe(o));if(s(r.timeUpdate$,e.position$),s(r.durationChange$,e.duration$),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.loadedMetadata$,e.firstBytesEvent$),s(r.loadedMetadata$,e.loadedMetadataEvent$),s(r.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.seeked$,e.seekedEvent$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe((0,oe.map)(u=>u.to)),this.params.output.playbackState$),this.subscription.add(kt(this.video,t.isLooped,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(nt(this.video,t.playbackRate,r.playbackRateState$,i)),Tr({subscription:this.subscription,desiredState:t,videoElement$:this.params.output.element$,observableVideo:r}),this.subscription.add(je(this.video,t.volume,r.volumeState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),B(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),B(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i).add(r.loadedMetadata$.subscribe(()=>{let u=this.params.desiredState.seekState.getState(),o=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),p=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&(0,oe.isNonNullable)(l.to)){let h=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let m=this.manifests$.getValue().find(b=>b.id===h);m&&(this.params.output.currentVideoTrack$.next(m),this.params.output.hostname$.next(Me(m.url)))}let c=this.params.desiredState.playbackRate.getState(),d=this.params.output.element$.getValue()?.playbackRate;if(c!==d){let h=this.params.output.element$.getValue();h&&(this.params.desiredState.playbackRate.setState(c),h.playbackRate=c)}p&&this.params.desiredState.autoVideoTrackSwitching.setState(p.to),o&&o.from==="changing_manifest"&&this.videoState.setState(o.to),u.state==="requested"&&this.seek(u.position)},i))),this.params.tuning.changePlaybackStateToPausedWhenEnded&&this.subscription.add(r.ended$.subscribe(()=>{this.videoState.setState("paused"),B(t.playbackState,"paused")})),this.subscription.add(this.manifests$.pipe((0,oe.map)(u=>u.map(({id:o,quality:l,size:p,bandwidth:c,fps:d})=>({id:o,quality:l,size:p,fps:d,bitrate:c})))).subscribe(this.params.output.availableVideoTracks$,i)),!j.device.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:u}=this.video;this.subscription.add((0,oe.merge)((0,oe.fromEvent)(u,"addtrack"),(0,oe.fromEvent)(u,"removetrack"),(0,oe.fromEvent)(u,"change"),(0,oe.observableFrom)(["init"])).subscribe(()=>{for(let o=0;o<u.length;o++)u[o].mode="hidden"},i))}let n=(0,oe.merge)(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,(0,oe.observableFrom)(["init"])).pipe((0,oe.debounce)(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),He(this.video)}prepare(){let e=this.selectManifest();if((0,oe.isNullable)(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),r=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){let{max:s,min:n}=t?.to??i??{};for(let[u,o]of[[s,"mq"],[n,"lq"]]){let l=String(parseFloat(u||""));o&&u&&r.searchParams.set(o,l)}}this.video.setAttribute("src",r.toString()),this.video.load()}playIfAllowed(){Qe(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),B(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:oe.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};var sv=Q(zi(),1),Yl=Q(Si(),1),nv=Q(gt(),1);var fe=require("@vkontakte/videoplayer-shared");var es=class{constructor(e){this.subscription=new fe.Subscription;this.videoState=new Z("stopped");this.trackUrls={};this.textTracksManager=new ot;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=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"),B(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(),u=this.params.desiredState.seekState.getState();if(s&&e!=="ready"&&!n){this.handleQualityLimitTransition(s.to);return}if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(n){let{currentTime:o}=this.video;this.prepare(),u.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:o*1e3,forcePrecise:!0});return}switch(i?.to!=="paused"&&u.state==="requested"&&this.seek(u.position),e){case"ready":t==="ready"?B(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),B(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()):i?.to==="playing"&&B(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&B(this.params.desiredState.playbackState,"paused");return;default:return(0,fe.assertNever)(e)}};this.params=e,this.video=Ue(e.container,e.tuning),this.params.output.element$.next(this.video),(0,sv.default)(this.params.source).reverse().forEach(([t,i],r)=>{let s=r.toString(10);this.trackUrls[s]={track:{quality:t,id:s},url:i}}),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next((0,Yl.default)(this.trackUrls).map(({track:t})=>t)),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.desiredState.autoVideoTrackSwitching.setState(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.subscribe()}subscribe(){let{output:e,desiredState:t}=this.params,i=u=>{e.error$.next({id:"MpegProvider",category:fe.ErrorCategory.WTF,message:"MpegProvider internal logic error",thrown:u})},r=We(this.video);this.subscription.add(()=>r.destroy());let s=(u,o)=>this.subscription.add(u.subscribe(o,i));s(r.timeUpdate$,e.position$),s(r.durationChange$,e.duration$),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.loadedMetadata$,e.firstBytesEvent$),s(r.loadedMetadata$,e.loadedMetadataEvent$),s(r.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.seeked$,e.seekedEvent$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe((0,fe.map)(u=>u.to)),this.params.output.playbackState$),this.subscription.add(kt(this.video,t.isLooped,i)),Tr({subscription:this.subscription,desiredState:t,videoElement$:this.params.output.element$,observableVideo:r}),this.subscription.add(je(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(nt(this.video,t.playbackRate,r.playbackRateState$,i)),s(ut(this.video),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),B(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),B(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready");let u=this.params.desiredState.videoTrack.getTransition();if(u&&(0,fe.isNonNullable)(u.to)){this.params.desiredState.videoTrack.setState(u.to),this.params.output.currentVideoTrack$.next(this.trackUrls[u.to.id].track);let o=this.params.desiredState.playbackRate.getState(),l=this.params.output.element$.getValue()?.playbackRate;if(o!==l){let p=this.params.output.element$.getValue();p&&(this.params.desiredState.playbackRate.setState(o),p.playbackRate=o)}}this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.params.tuning.changePlaybackStateToPausedWhenEnded&&this.subscription.add(r.ended$.subscribe(()=>{this.videoState.setState("paused"),B(t.playbackState,"paused")})),this.textTracksManager.connect(this.video,t,e);let n=(0,fe.merge)(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,(0,fe.observableFrom)(["init"])).pipe((0,fe.debounce)(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.params.output.element$.next(void 0),He(this.video)}prepare(){let e=this.params.desiredState.videoTrack.getState()?.id;(0,fe.assertNonNullable)(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];(0,fe.assertNonNullable)(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=ni(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(Me(t))}playIfAllowed(){Qe(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),B(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:fe.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){this.params.output.autoVideoTrackLimits$.next(e);let t=l=>{this.params.output.currentVideoTrack$.next(l),this.params.desiredState.videoTrack.startTransitionTo(l)},i=l=>{let p=Rt(n,{container:this.video.getBoundingClientRect(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:0,limits:l,abrLogger:this.params.dependencies.abrLogger});t(p)},r=this.params.output.currentVideoTrack$.getValue()?.quality,s=!!(e.max||e.min),n=(0,Yl.default)(this.trackUrls).map(l=>l.track);if(!r||!s||nr(e,n[0].quality,(0,nv.default)(n,-1)?.quality)){i();return}let u=e.max?(0,fe.isLowerOrEqual)(r,e.max):!0,o=e.min?(0,fe.isHigherOrEqual)(r,e.min):!0;u&&o||i(e)}};var me=require("@vkontakte/videoplayer-shared");var uv=require("@vkontakte/videoplayer-shared"),ov=["stun:videostun.mycdn.me:80"],b$=1e3,g$=3,Kl=()=>null,Zn=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=Kl;this.externalStopCallback=Kl;this.externalErrorCallback=Kl;this.options=this.normalizeOptions(t);let i=e.split("/");this.serverUrl=i.slice(0,i.length-1).join("/"),this.streamKey=i[i.length-1]}onStart(e){try{this.externalStartCallback=e}catch(t){this.handleSystemError(t)}}onStop(e){try{this.externalStopCallback=e}catch(t){this.handleSystemError(t)}}onError(e){try{this.externalErrorCallback=e}catch(t){this.handleSystemError(t)}}connect(){this.connectWS()}disconnect(){try{this.externalStopCallback(),this.closeConnections()}catch(e){this.handleSystemError(e)}}connectWS(){this.ws||(this.ws=new WebSocket(this.serverUrl),this.ws.onopen=this.onSocketOpen.bind(this),this.ws.onmessage=this.onSocketMessage.bind(this),this.ws.onclose=this.onSocketClose.bind(this),this.ws.onerror=this.onSocketError.bind(this))}onSocketOpen(){this.handleLogin()}onSocketClose(e){try{if(!this.ws)return;this.ws=null,e.code>1e3?(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():this.scheduleRetry()):this.externalStopCallback()}catch(t){this.handleRTCError(t)}}onSocketError(e){try{this.externalErrorCallback(new Error(e.toString()))}catch(t){this.handleRTCError(t)}}onSocketMessage(e){try{let t=this.parseMessage(e.data);switch(t.type){case"JOIN":case"CALL_JOIN":this.handleJoinMessage(t);break;case"UPDATE":this.handleUpdateMessage(t);break;case"STATUS":this.handleStatusMessage(t);break}}catch(t){this.handleRTCError(t)}}handleJoinMessage(e){switch(e.inviteType){case"ANSWER":this.handleAnswer(e.sdp);break;case"CANDIDATE":this.handleCandidate(e.candidate);break}}handleStatusMessage(e){switch(e.status){case"UNPUBLISHED":this.handleUnpublished();break}}async handleUpdateMessage(e){try{let t=await this.createOffer();this.peerConnection&&await this.peerConnection.setLocalDescription(t),this.handleAnswer(e.sdp)}catch(t){this.handleRTCError(t)}}async handleLogin(){try{let e={iceServers:[{urls:ov}]};this.peerConnection=new RTCPeerConnection(e),this.peerConnection.ontrack=this.onPeerConnectionStream.bind(this),this.peerConnection.onicecandidate=this.onPeerConnectionIceCandidate.bind(this),this.peerConnection.oniceconnectionstatechange=this.onPeerConnectionIceConnectionStateChange.bind(this);let t=await this.createOffer();await this.peerConnection.setLocalDescription(t),this.send({type:this.signalingType,inviteType:"OFFER",streamKey:this.streamKey,sdp:t.sdp,callSupport:!1})}catch(e){this.handleRTCError(e)}}async handleAnswer(e){try{this.peerConnection&&await this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e}))}catch(t){this.handleRTCError(t)}}async handleCandidate(e){if(e)try{this.peerConnection&&await this.peerConnection.addIceCandidate(e)}catch(t){this.handleRTCError(t)}}handleUnpublished(){try{this.closeConnections(),this.externalStopCallback()}catch(e){this.handleRTCError(e)}}handleSystemError(e){this.options.errorChanel&&this.options.errorChanel.next({id:"webrtc-provider-error",category:uv.ErrorCategory.WTF,message:e.message})}async onPeerConnectionStream(e){let t=e.streams[0];this.stream&&this.stream.id===t.id||(this.stream=t,this.externalStartCallback(this.stream))}onPeerConnectionIceCandidate(e){e.candidate&&this.send({type:this.signalingType,inviteType:"CANDIDATE",candidate:e.candidate})}onPeerConnectionIceConnectionStateChange(){if(this.peerConnection){let e=this.peerConnection.iceConnectionState;["failed","closed"].indexOf(e)>-1&&(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():(this.closeConnections(),this.scheduleRetry()))}}async createOffer(){let e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");let t=await this.peerConnection.createOffer(e),i=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(i))throw new Error("No h264 codec support error");return t}handleRTCError(e){try{this.externalErrorCallback(e||new Error("RTC connection error"))}catch(t){this.handleSystemError(t)}}handleNetworkError(){try{this.externalErrorCallback(new Error("Network error"))}catch(e){this.handleSystemError(e)}}send(e){this.ws&&this.ws.send(JSON.stringify(e))}parseMessage(e){try{return JSON.parse(e)}catch{throw new Error("Can not parse socket message")}}closeConnections(){let e=this.ws;e&&(this.ws=null,e.close(1e3)),this.removePeerConnection()}removePeerConnection(){let e=this.peerConnection;e&&(this.peerConnection=null,e.close(),e.ontrack=null,e.onicecandidate=null,e.oniceconnectionstatechange=null,e=null)}scheduleRetry(){this.retryTimeout=setTimeout(this.connectWS.bind(this),b$)}normalizeOptions(e={}){let t={stunServerList:ov,maxRetryNumber:g$,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var ts=class{constructor(e){this.videoState=new Z("stopped");this.maxSeekBackTime$=new me.ValueSubject(0);this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=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"),B(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"),B(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()):i?.to==="playing"&&B(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&B(this.params.desiredState.playbackState,"paused");return;default:return(0,me.assertNever)(e)}};this.subscription=new me.Subscription,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=Ue(e.container,e.tuning),this.liveStreamClient=new Zn(this.params.source.url,{maxRetryNumber:this.params.tuning.webrtc.connectionRetryMaxNumber,errorChanel:this.params.output.error$}),this.liveStreamClient.onStart(this.onLiveStreamStart.bind(this)),this.liveStreamClient.onStop(this.onLiveStreamStop.bind(this)),this.liveStreamClient.onError(this.onLiveStreamError.bind(this)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.subscribe()}destroy(){this.subscription.unsubscribe(),this.liveStreamClient.disconnect(),this.params.output.element$.next(void 0),He(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,i=n=>{e.error$.next({id:"WebRTCLiveProvider",category:me.ErrorCategory.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};this.subscription.add((0,me.merge)(this.videoState.stateChangeStarted$.pipe((0,me.map)(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe((0,me.map)(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:u})=>{this.log({message:`[videoState change] ${u}: ${JSON.stringify(n)}`})}));let r=We(this.video);this.subscription.add(()=>r.destroy());let s=(n,u)=>this.subscription.add(n.subscribe(u,i));s(r.timeUpdate$,e.liveTime$),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(ut(this.video),this.params.output.elementVisible$),this.subscription.add(r.durationChange$.subscribe(n=>{e.duration$.next(n===1/0?0:n)})).add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused")},i)).add(r.playing$.subscribe(()=>{this.videoState.setState("playing")},i)).add(r.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(je(this.video,t.volume,r.volumeState$,i)).add(r.volumeState$.subscribe(e.volume$,i)).add(this.videoState.stateChangeEnded$.subscribe(n=>{switch(n.to){case"stopped":e.position$.next(0),e.duration$.next(0),t.playbackState.setState("stopped");break;case"ready":break;case"paused":t.playbackState.setState("paused");break;case"playing":t.playbackState.setState("playing");break;default:return(0,me.assertNever)(n.to)}},i)).add((0,me.merge)(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,(0,me.observableFrom)(["init"])).pipe((0,me.debounce)(0)).subscribe(this.syncPlayback.bind(this),i)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),i))}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(Me(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:me.VideoQuality.INVARIANT}),this.video.srcObject=e,B(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:me.ErrorCategory.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){Qe(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),B(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:me.ErrorCategory.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var Ir=class{constructor(e){this.length=e.length,this.iterator=e[Symbol.iterator](),this.next()}next(){this.current=this.iterator.next(),this.index=this.index===void 0?0:this.index+1}getValue(){if(this.current.done)throw new Error("Iterable is completed");return this.current.value}isCompleted(){return!!this.current.done}isLast(){return this.index===this.length-1}};var E=require("@vkontakte/videoplayer-shared");var Wt=require("@vkontakte/videoplayer-shared"),lv=a=>new Wt.Observable(e=>{let t=new Wt.Subscription,i=a.desiredPlaybackState$.stateChangeStarted$.pipe((0,Wt.map)(({from:l,to:p})=>`${l}-${p}`)),r=a.desiredPlaybackState$.stateChangeEnded$,s=a.providerChanged$.pipe((0,Wt.map)(({type:l})=>l!==void 0)),n=new Wt.Subject,u=0,o="unknown";return t.add(i.subscribe(l=>{u&&window.clearTimeout(u),o=l,u=window.setTimeout(()=>n.next(l),a.maxTransitionInterval)})),t.add(r.subscribe(()=>{window.clearTimeout(u),o="unknown",u=0})),t.add(s.subscribe(l=>{u&&(window.clearTimeout(u),u=0,l&&(u=window.setTimeout(()=>n.next(o),a.maxTransitionInterval)))})),t.add(n.subscribe(e)),()=>{window.clearTimeout(u),t.unsubscribe()}});var ct=require("@vkontakte/videoplayer-shared");function cv(){return new(window.AudioContext||window.webkitAudioContext)}var Er=class a{constructor(e,t,i,r){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=i;this.volumeMultiplier=r;this.destroyController=new ue;this.subscriptions=new ct.Subscription;this.audioContext=null;this.gainNode=null;this.mediaElementSource=null;this.subscriptions.add(this.provider$.pipe((0,ct.filter)(s=>!!s.type),(0,ct.once)()).subscribe(({type:s})=>this.subscribe(s)))}static{this.errorId="VolumeMultiplierManager"}subscribe(e){j.browser.isSafari&&e!=="MPEG"||this.subscriptions.add((0,ct.combine)({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe((0,ct.filter)(({playbackState:t,video:i,volume:{muted:r,volume:s}})=>t==="playing"&&!!i&&!r&&!!s),(0,ct.once)()).subscribe(({video:t})=>{this.initAudioContextOnce(t).then(i=>{i||this.destroy()}).catch(i=>{this.handleError(i),this.destroy()})}))}static isSupported(){return"AudioContext"in window&&"GainNode"in window&&"MediaElementAudioSourceNode"in window}async initAudioContextOnce(e){let{volumeMultiplier:t}=this,i=cv();this.audioContext=i;let r=i.createGain();if(this.gainNode=r,r.gain.value=t,r.connect(i.destination),i.state==="suspended"&&(await i.resume(),this.destroyController.signal.aborted))return!1;let s=i.createMediaElementSource(e);return this.mediaElementSource=s,s.connect(r),!0}cleanup(){this.mediaElementSource&&(this.mediaElementSource.disconnect(),this.mediaElementSource=null),this.gainNode&&(this.gainNode.disconnect(),this.gainNode=null),this.audioContext&&(this.audioContext.state!=="closed"&&this.audioContext.close(),this.audioContext=null)}destroy(){this.destroyController.abort(),this.subscriptions.unsubscribe(),this.cleanup()}handleError(e){this.volumeMultiplierError$.next({id:a.errorId,category:ct.ErrorCategory.VIDEO_PIPELINE,message:e?.message??`${a.errorId} exception`,thrown:e})}};var S$={chunkDuration:5e3,maxParallelRequests:5},is=class{constructor(e){this.current$=new E.ValueSubject({type:void 0});this.providerError$=new E.Subject;this.noAvailableProvidersError$=new E.Subject;this.volumeMultiplierError$=new E.Subject;this.providerOutput={position$:new E.ValueSubject(0),duration$:new E.ValueSubject(1/0),volume$:new E.ValueSubject({muted:!1,volume:1}),availableVideoStreams$:new E.ValueSubject([]),currentVideoStream$:new E.ValueSubject(void 0),availableVideoTracks$:new E.ValueSubject([]),currentVideoTrack$:new E.ValueSubject(void 0),availableVideoCodecs$:new E.ValueSubject([]),availableAudioStreams$:new E.ValueSubject([]),currentAudioStream$:new E.ValueSubject(void 0),availableAudioTracks$:new E.ValueSubject([]),availableAudioCodecs$:new E.ValueSubject([]),currentVideoSegmentLength$:new E.ValueSubject(0),currentAudioSegmentLength$:new E.ValueSubject(0),isAudioAvailable$:new E.ValueSubject(!0),autoVideoTrackLimitingAvailable$:new E.ValueSubject(!1),autoVideoTrackLimits$:new E.ValueSubject(void 0),currentBuffer$:new E.ValueSubject(void 0),isBuffering$:new E.ValueSubject(!0),error$:new E.Subject,fetcherError$:new E.Subject,fetcherRecoverableError$:new E.Subject,warning$:new E.Subject,willSeekEvent$:new E.Subject,soundProhibitedEvent$:new E.Subject,seekedEvent$:new E.Subject,loopedEvent$:new E.Subject,endedEvent$:new E.Subject,manifestRequested$:new E.Subject,firstBytesManifest$:new E.Subject,manifestReceived$:new E.Subject,firstBytesRequested$:new E.Subject,firstBytesReceived$:new E.Subject,firstBytesEvent$:new E.Subject,loadedMetadataEvent$:new E.Subject,firstFrameEvent$:new E.Subject,canplay$:new E.Subject,isLive$:new E.ValueSubject(void 0),isLiveEnded$:new E.ValueSubject(null),canPlayLiveTailBuffer$:new E.ValueSubject(!1),isLowLatency$:new E.ValueSubject(!1),canChangePlaybackSpeed$:new E.ValueSubject(!0),liveTime$:new E.ValueSubject(void 0),liveBufferTime$:new E.ValueSubject(void 0),liveLatency$:new E.ValueSubject(void 0),severeStallOccurred$:new E.Subject,availableTextTracks$:new E.ValueSubject([]),currentTextTrack$:new E.ValueSubject(void 0),hostname$:new E.ValueSubject(void 0),httpConnectionType$:new E.ValueSubject(void 0),httpConnectionReused$:new E.ValueSubject(void 0),inPiP$:new E.ValueSubject(!1),inFullscreen$:new E.ValueSubject(!1),element$:new E.ValueSubject(void 0),elementVisible$:new E.ValueSubject(!0),availableSources$:new E.ValueSubject(void 0),is3DVideo$:new E.ValueSubject(!1),playbackState$:new E.ValueSubject(""),getCurrentTime$:new E.ValueSubject(null)};this.subscription=new E.Subscription;this.volumeMultiplierManager=null;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer"),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name);let t=Xu([...qS(this.params.tuning),...NS(this.params.tuning)]).filter(l=>(0,E.isNonNullable)(e.sources[l])),{forceFormat:i,formatsToAvoid:r}=this.params.tuning,s=[];i?s=[i]:r.length?s=[...t.filter(l=>!(0,Xl.default)(r,l)),...t.filter(l=>(0,Xl.default)(r,l))]:s=t,this.log({message:`Selected formats: ${s.join(" > ")}`}),this.tracer.log("Selected formats",(0,E.flattenObject)(s)),this.screenFormatsIterator=new Ir(s);let n=[...Bl(!0),...Bl(!1)];this.chromecastFormatsIterator=new Ir(n.filter(l=>(0,E.isNonNullable)(e.sources[l]))),this.providerOutput.availableSources$.next(e.sources);let{volumeMultiplier:u=1,tuning:{useVolumeMultiplier:o}}=this.params;o&&u!==1&&Er.isSupported()&&(this.volumeMultiplierManager=new Er(this.providerOutput,this.current$,this.volumeMultiplierError$,u))}init(){this.subscription.add(this.initProviderErrorHandling()).add(this.params.dependencies.chromecastInitializer.connection$.subscribe(()=>{this.reinitProvider()})).add(this.providerOutput.availableVideoCodecs$.subscribe(e=>{!this.videoCodecsIterator&&e.length>1&&(this.videoCodecsIterator=new Ir(e))}))}destroy(){this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe(),this.volumeMultiplierManager?.destroy(),this.volumeMultiplierManager=null,this.tracer.end()}initProvider(){let e=this.chooseDestination(),t=this.chooseFormat(e);if((0,E.isNullable)(t)){this.handleNoFormatsError(e);return}let i;try{i=this.createProvider(e,t)}catch(r){this.providerError$.next({id:"ProviderNotConstructed",category:E.ErrorCategory.WTF,message:"Failed to create provider",thrown:r})}i?this.current$.next({type:t,provider:i,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()}switchToNextVideoCodec(){this.params.tuning.dash.codecsPrioritizeEnabled&&!this.videoCodecsIterator.isLast()&&(this.tracer.log("switchToNextVideoCodec"),this.destroyProvider(),this.videoCodecsIterator.next(),this.initProvider())}destroyProvider(){let e=this.current$.getValue().provider;if(!e)return;this.log({message:"destroyProvider"}),this.tracer.log("destroyProvider"),e.destroy();let t=this.providerOutput.position$.getValue()*1e3,i=this.params.desiredState.seekState.getState(),r=i.state!=="none";if(this.params.desiredState.seekState.setState({state:"requested",position:r?i.position:t,forcePrecise:r?i.forcePrecise:!1}),e.scene3D){let n=e.scene3D.getCameraRotation();this.params.desiredState.cameraOrientation.setState({x:n.x,y:n.y})}let s=this.providerOutput.isBuffering$;s.getValue()||s.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),this.tracer.log("createProvider",{destination:e,format:t}),e){case"SCREEN":return this.createScreenProvider(t);case"CHROMECAST":return this.createChromecastProvider(t);default:return(0,E.assertNever)(e)}}createScreenProvider(e){let{sources:t,container:i,desiredState:r,panelSize:s}=this.params,n=this.providerOutput,u={container:i,source:null,desiredState:r,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning,panelSize:s};switch(e){case"DASH_SEP":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_ONDEMAND":case"DASH_STREAMS":{let o=this.applyFailoverHost(t[e]),l=this.applyFailoverHost(t.HLS_ONDEMAND||t.HLS);return(0,E.assertNonNullable)(o),this.params.tuning.useNewDashProvider?new Ka({...u,source:o,sourceHls:l,forceVideoCodec:this.videoCodecsIterator?.getValue()}):new Wa({...u,source:o,sourceHls:l,forceVideoCodec:this.videoCodecsIterator?.getValue()})}case"DASH_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return(0,E.assertNonNullable)(o),this.params.tuning.useNewDashProvider?new Xa({...u,source:o}):new Qa({...u,source:o})}case"HLS":case"HLS_ONDEMAND":case"HLS_FMP4":{let o=this.applyFailoverHost(t[e]);return(0,E.assertNonNullable)(o),new Za({...u,source:o})}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return(0,E.assertNonNullable)(o),new Ja({...u,source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case"MPEG":{let o=this.applyFailoverHost(t[e]);return(0,E.assertNonNullable)(o),new es({...u,source:o})}case"DASH_LIVE":{let o=this.applyFailoverHost(t[e]);return(0,E.assertNonNullable)(o),new Fb({...u,source:o,config:{...S$,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case"WEB_RTC_LIVE":{let o=this.applyFailoverHost(t[e]);return(0,E.assertNonNullable)(o),new ts({container:i,source:o,desiredState:r,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return(0,E.assertNever)(e)}}createChromecastProvider(e){let{sources:t,container:i,desiredState:r,meta:s}=this.params,n=this.providerOutput,u=this.params.dependencies.chromecastInitializer.connection$.getValue();return(0,E.assertNonNullable)(u),new ea({connection:u,meta:s,container:i,source:t,format:e,desiredState:r,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?"CHROMECAST":"SCREEN"}chooseFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case"CHROMECAST":return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return(0,E.assertNever)(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return(0,E.assertNever)(e)}}handleNoFormatsError(e){switch(e){case"SCREEN":this.noAvailableProvidersError$.next(this.params.tuning.forceFormat),this.current$.next({type:void 0});return;case"CHROMECAST":this.params.dependencies.chromecastInitializer.disconnect();return;default:return(0,E.assertNever)(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;let t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;let i=r=>{let s=new URL(r);return s.host=t,s.toString()};if(e===void 0)return e;if("type"in e){if(e.type==="raw")return e;if(e.type==="url")return{...e,url:i(e.url)}}return(0,pv.default)((0,dv.default)(e).map(([r,s])=>[r,i(s)]))}initProviderErrorHandling(){let e=new E.Subscription,t=!1,i=0;return e.add((0,E.merge)(this.providerOutput.error$.pipe((0,E.filter)(r=>!this.params.tuning.ignoreAudioRendererError||!r.message||!/AUDIO_RENDERER_ERROR/ig.test(r.message))),lv({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe((0,E.map)(r=>({id:`ProviderHangup:${r}`,category:E.ErrorCategory.WTF,message:`A ${r} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.providerOutput.fetcherError$.subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;let r=this.params.desiredState.playbackState.transitionEnded$.pipe((0,E.filter)(({to:s})=>s==="playing"),(0,E.once)()).subscribe(()=>t=!0);e.add(r)})),e.add(this.providerError$.subscribe(r=>{let s=this.current$.getValue().destination,n={error:r,currentDestination:s};if(s==="CHROMECAST")this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider("SCREEN"),()=>this.params.dependencies.chromecastInitializer.disconnect());else{let u=r.category===E.ErrorCategory.NETWORK,o=r.category===E.ErrorCategory.FATAL,l=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),p=i<this.params.tuning.providerErrorLimit&&!o,c=this.videoCodecsIterator&&!this.videoCodecsIterator.isLast()&&this.params.tuning.dash.codecsPrioritizeEnabled,d=l&&!o&&(u&&t||!p);n={...n,isNetworkError:u,isFatalError:o,haveFailoverHost:l,tryFailover:d,canReinitProvider:p},p?(i++,this.reinitProvider()):d?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):c?this.switchToNextVideoCodec():(i=0,this.switchToNextProvider(s??"SCREEN"))}r.traceAsLog?this.tracer.log("providerInfo",(0,E.flattenObject)(n)):this.tracer.error("providerError",(0,E.flattenObject)(n))})),e}};var K=require("@vkontakte/videoplayer-shared");var v$=5e3,hv="one_video_throughput",fv="one_video_rtt",rs=window.navigator.connection,mv=()=>{let a=rs?.downlink;if((0,K.isNonNullable)(a)&&a!==10)return a*1e3},bv=()=>{let a=rs?.rtt;if((0,K.isNonNullable)(a)&&a!==3e3)return a},gv=(a,e,t)=>{let i=t*8,r=i/a;return i/(r+e)},Jl=class a{constructor(e){this.subscription=new K.Subscription;this.concurrentDownloads=new Set;this.tuningConfig=e;let t=a.load(hv)||(e.useBrowserEstimation?mv():void 0)||v$,i=a.load(fv)??(e.useBrowserEstimation?bv():void 0)??0;if(this.throughput$=new K.ValueSubject(t),this.rtt$=new K.ValueSubject(i),this.rttAdjustedThroughput$=new K.ValueSubject(gv(t,i,e.rttPenaltyRequestSize)),this.throughput=jt.getSmoothedValue(t,-1,e),this.rtt=jt.getSmoothedValue(i,1,e),e.useBrowserEstimation){let r=()=>{let n=mv();n&&this.throughput.next(n);let u=bv();(0,K.isNonNullable)(u)&&this.rtt.next(u)};rs&&"onchange"in rs&&this.subscription.add((0,K.fromEvent)(rs,"change").subscribe(r)),r()}this.subscription.add(this.throughput.smoothed$.subscribe(r=>{K.safeStorage.set(hv,r.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(r=>{K.safeStorage.set(fv,r.toFixed(0))})),this.subscription.add(this.throughput.debounced$.pipe((0,K.map)(r=>Math.round(r))).subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add((0,K.combine)({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe((0,K.map)(({throughput:r,rtt:s})=>gv(r,s,e.rttPenaltyRequestSize)),(0,K.filter)(r=>{let s=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(r-s)/s>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,i=(0,K.now)(),r=new K.Subscription;switch(this.subscription.add(r),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:r.add((0,K.fromEvent)(e,"progress").pipe((0,K.once)()).subscribe(s=>{t=s.loaded,i=(0,K.now)()}));break;case 1:case 0:r.add((0,K.fromEvent)(e,"loadstart").subscribe(()=>{t=0,i=(0,K.now)()}));break}r.add((0,K.fromEvent)(e,"loadend").subscribe(s=>{if(e.status===200){let n=s.loaded,u=(0,K.now)(),o=n-t,l=u-i;this.addRawSpeed(o,l,1)}this.concurrentDownloads.delete(e),r.unsubscribe()}))}trackStream(e,t=!1){let i=e.getReader();if(!i){e.cancel("Could not get reader");return}let r=0,s=(0,K.now)(),n=0,u=(0,K.now)(),o=p=>{this.concurrentDownloads.delete(e),i.releaseLock(),e.cancel(`Throughput Estimator error: ${p}`).catch(()=>{})},l=async({done:p,value:c})=>{if(p)!t&&this.addRawSpeed(r,(0,K.now)()-s,1),this.concurrentDownloads.delete(e);else if(c){if(t){let d=(0,K.now)();if(d-u>this.tuningConfig.lowLatency.continuesByteSequenceInterval||d-s>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let m=u-s;m&&this.addRawSpeed(n,m,1,t),n=c.byteLength,s=(0,K.now)()}else n+=c.byteLength;u=(0,K.now)()}else r+=c.byteLength,n+=c.byteLength,n>=this.tuningConfig.streamMinSampleSize&&(0,K.now)()-u>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,(0,K.now)()-u,this.concurrentDownloads.size),n=0,u=(0,K.now)());await i?.read().then(l,o)}};this.concurrentDownloads.add(e),i?.read().then(l,o)}addRawSpeed(e,t,i=1,r=!1){if(a.sanityCheck(e,t,r)){let s=e*8/t;this.throughput.next(s*i)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,i=!1){let r=e*8/t;return!(!r||!isFinite(r)||r>1e6||r<30||i&&e<1e4||!i&&e<10*1024||!i&&t<=20)}static load(e){let t=K.safeStorage.get(e);if((0,K.isNonNullable)(t))return parseInt(t,10)??void 0}},Sv=Jl;var Ci=require("@vkontakte/videoplayer-shared"),vv={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:{maxBitrateFactorAtEmptyBuffer:4,bitrateFactorAtEmptyBuffer:2.8,minBitrateFactorAtEmptyBuffer:1.5,bitrateAudioFactorAtEmptyBuffer:10,maxBitrateFactorAtFullBuffer:3,bitrateFactorAtFullBuffer:2,minBitrateFactorAtFullBuffer:1,bitrateAudioFactorAtFullBuffer:7,minVideoAudioRatio:5,minAvailableThroughputAudioRatio:5,usePixelRatio:!0,pixelRatioMultiplier:void 0,pixelRatioLogBase:3,pixelRatioLogCoefficients:[1,0,1],limitByContainer:!0,maxContainerSizeFactor:2,containerSizeFactor:1.3,minContainerSizeFactor:1,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldownIncreaseQuality:15e3,trackCooldownDecreaseQuality:3e3,backgroundVideoQualityLimit:Ci.VideoQuality.Q_4320P,activeVideoAreaThreshold:.1,highQualityLimit:Ci.VideoQuality.Q_720P,trafficSavingLimit:Ci.VideoQuality.Q_480P},stallsManager:{enabled:!0,ignoreDynamicAbrForShortVideo:!1,stallDurationNoDataBeforeQualityDecrease:500,stallDurationToBeCount:100,stallCountBeforeQualityDecrease:3,resetQualityRestrictionTimeout:1e4,ignoreStallsOnSeek:!0,stallsMetricsHistoryLength:20,maxPossibleStallDuration:3e4,minTvtToBeCounted:120,maxTvtToBeCounted:10800,significantTvt:600,targetStallsDurationPerTvt:1,deviationStallsDurationPerTvt:.5,criticalStallsDurationPerTvt:6,abrAdjustingSpeed:.1,emaAlpha:.6,useTotalStallsDurationPerTvt:!0,useAverageStallsDurationPerTvt:!0,useEmaStallsDurationPerTvt:!0},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:Ci.VideoQuality.Q_480P},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,seekBiasInTheEnd:2e3,maxSegmentDurationLeftToSelectNextSegment:3e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:15e3,crashOnStallTimeout:25e3,crashOnStallTWithoutDataTimeout:5e3,enableSubSegmentBufferFeeding:!0,bufferEmptinessTolerance:100,useNewRepresentationSwitch:!1,useDelayedRepresentationSwitch:!1,useSmartRepresentationSwitch:!1,useFetchPriorityHints:!0,enableBaseUrlSupport:!0,maxSegmentRetryCount:5,sourceOpenTimeout:1e3,vktvAbrThrottle:0,timeupdateEventTickThrottle:300,fetcherBufferOptimisation:!0,codecsPrioritizeEnabled:!1,usePersistentGaps:!1,abrThrottle:0,useVideoElementWaitingCurrentTimeReassign:!0,stallWatchdogInterval:100,liveUpdateInterval:1e3,liveStallReinitInterval:3e3,ignoreNetworkErrorsOnLoadInit:!1},dashCmafLive:{externalStopControl:!1,keepSilentStallWatchdogWhenNotActive:!1,maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,maxLiveDuration:7200,catchupLiveForMutedInactiveTab:!0,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:250,playbackCatchupSpeedup:.05,isActiveOnDefault:!1,bufferEstimator:{emaAlpha:.45,changeThreshold:.05,deviationDepth:20,deviationFactor:.5,extremumInterval:5}}},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1,lowLatencyActiveLiveDelay:3e3,activeLiveDelay:5e3,maxPausedTime:5e3},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,forceFormat:void 0,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:"07A4434E",useWebmBigRequest:!1,webmCodec:"vp9",androidPreferredFormat:"dash",iosPreferredFormat:"hls",preferCMAF:!1,preferWebRTC:!1,preferMultiStream:!1,preferHDR:!1,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,seekNearDurationBias:1,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useHlsJs:!1,useNativeHLSTextTracks:!1,useNewSwitchTo:!1,useNewDashProvider:!1,useNewAutoSelectVideoTrack:!1,useSafariEndlessRequestBugfix:!0,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,manifestRetryInterval:300,manifestRetryMaxInterval:1e4,manifestRetryMaxCount:10,audioVideoSyncRate:20,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50},useVolumeMultiplier:!1,ignoreAudioRendererError:!1,useEnableSubtitlesParam:!1,useHlsLiveNewTextManager:!1,exposeInternalsToGlobal:!1,hlsLiveNewTextManagerDownloadThreshold:4e3,disableYandexPiP:!1,asyncResolveClientChecker:!1,autostartOnlyIfVisible:!1,changePlaybackStateToPausedWhenEnded:!1,suppressExceptionsInObservables:!0},yv=a=>({...(0,Ci.fillWithDefault)(a,vv),configName:[...a.configName??[],...vv.configName]});var f=require("@vkontakte/videoplayer-shared");var Qt=require("@vkontakte/videoplayer-shared"),Zl=({seekState:a,position$:e})=>(0,Qt.merge)(a.stateChangeEnded$.pipe((0,Qt.map)(({to:t})=>t.state==="none"?void 0:(t.position??NaN)/1e3),(0,Qt.filter)(Qt.isNonNullable)),e.pipe((0,Qt.filter)(()=>a.getState().state==="none")));var Tv=require("@vkontakte/videoplayer-shared"),Iv=a=>{let e=typeof a.container=="string"?document.getElementById(a.container):a.container;return(0,Tv.assertNonNullable)(e,`Wrong container or containerId {${a.container}}`),e};var eo=require("@vkontakte/videoplayer-shared"),Ev=(a,e,t,i)=>{a!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&t?.getValue().length===0?t.pipe((0,eo.filter)(r=>r.length>0),(0,eo.once)()).subscribe(r=>{r.find(i)&&e.startTransitionTo(a)}):(a===void 0||t?.getValue().find(i))&&e.startTransitionTo(a)};var as=class{constructor(e={configName:[]},t=f.TracerFactory.createRootTracer(!1),i){this.subscription=new f.Subscription;this.logger=new f.Logger;this.abrLogger=this.logger.createComponentLog("ABR");this.internalsExposure=null;this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new f.ValueSubject(!1);this.hasLiveOffsetByPausedTimer=0;this.playerInitRequest=0;this.playerInited=new f.ValueSubject(!1);this.wasSetStartedQuality=!1;this.desiredState={playbackState:new Z("stopped"),seekState:new Z({state:"none"}),volume:new Z({volume:1,muted:!1}),videoTrack:new Z(void 0),videoStream:new Z(void 0),audioStream:new Z(void 0),autoVideoTrackSwitching:new Z(!0),autoVideoTrackLimits:new Z({}),isLooped:new Z(!1),isLowLatency:new Z(!1),playbackRate:new Z(1),externalTextTracks:new Z([]),internalTextTracks:new Z([]),currentTextTrack:new Z(void 0),textTrackCuesSettings:new Z({}),cameraOrientation:new Z({x:0,y:0})};this.info={playbackState$:new f.ValueSubject(void 0),position$:new f.ValueSubject(0),duration$:new f.ValueSubject(1/0),muted$:new f.ValueSubject(!1),volume$:new f.ValueSubject(1),availableVideoStreams$:new f.ValueSubject([]),currentVideoStream$:new f.ValueSubject(void 0),availableQualities$:new f.ValueSubject([]),availableQualitiesFps$:new f.ValueSubject({}),currentQuality$:new f.ValueSubject(void 0),isAutoQualityEnabled$:new f.ValueSubject(!0),autoQualityLimitingAvailable$:new f.ValueSubject(!1),autoQualityLimits$:new f.ValueSubject({}),predefinedQualityLimitType$:new f.ValueSubject("unknown"),availableAudioStreams$:new f.ValueSubject([]),currentAudioStream$:new f.ValueSubject(void 0),availableAudioTracks$:new f.ValueSubject([]),isAudioAvailable$:new f.ValueSubject(!0),currentPlaybackRate$:new f.ValueSubject(1),currentBuffer$:new f.ValueSubject({start:0,end:0}),isBuffering$:new f.ValueSubject(!0),isStalled$:new f.ValueSubject(!1),isEnded$:new f.ValueSubject(!1),isLooped$:new f.ValueSubject(!1),isLive$:new f.ValueSubject(void 0),isLiveEnded$:new f.ValueSubject(null),canPlayLiveTailBuffer$:new f.ValueSubject(!1),canChangePlaybackSpeed$:new f.ValueSubject(void 0),atLiveEdge$:new f.ValueSubject(void 0),atLiveDurationEdge$:new f.ValueSubject(void 0),liveTime$:new f.ValueSubject(void 0),liveBufferTime$:new f.ValueSubject(void 0),liveLatency$:new f.ValueSubject(void 0),currentFormat$:new f.ValueSubject(void 0),availableTextTracks$:new f.ValueSubject([]),currentTextTrack$:new f.ValueSubject(void 0),throughputEstimation$:new f.ValueSubject(void 0),rttEstimation$:new f.ValueSubject(void 0),videoBitrate$:new f.ValueSubject(void 0),hostname$:new f.ValueSubject(void 0),httpConnectionType$:new f.ValueSubject(void 0),httpConnectionReused$:new f.ValueSubject(void 0),surface$:new f.ValueSubject("none"),chromecastState$:new f.ValueSubject("NOT_AVAILABLE"),chromecastDeviceName$:new f.ValueSubject(void 0),intrinsicVideoSize$:new f.ValueSubject(void 0),availableSources$:new f.ValueSubject(void 0),is3DVideo$:new f.ValueSubject(!1),currentVideoSegmentLength$:new f.ValueSubject(0),currentAudioSegmentLength$:new f.ValueSubject(0)};this.events={inited$:new f.Subject,ready$:new f.Subject,started$:new f.Subject,playing$:new f.Subject,paused$:new f.Subject,stopped$:new f.Subject,willReady$:new f.Subject,willStart$:new f.Subject,willResume$:new f.Subject,willPause$:new f.Subject,willStop$:new f.Subject,willDestruct$:new f.Subject,watchCoverageRecord$:new f.Subject,watchCoverageLive$:new f.Subject,managedError$:new f.Subject,fatalError$:new f.Subject,fetcherRecoverableError$:new f.Subject,ended$:new f.Subject,looped$:new f.Subject,seeked$:new f.Subject,willSeek$:new f.Subject,autoplaySoundProhibited$:new f.Subject,manifestRequested$:new f.Subject,firstBytesManifest$:new f.Subject,manifestReceived$:new f.Subject,firstBytesRequested$:new f.Subject,firstBytesReceived$:new f.Subject,firstBytes$:new f.Subject,loadedMetadata$:new f.Subject,firstFrame$:new f.Subject,canplay$:new f.Subject,log$:new f.Subject,fetcherError$:new f.Subject,severeStallOccured$:new f.Subject};this.experimental={element$:new f.ValueSubject(void 0),tuningConfigName$:new f.ValueSubject([]),enableDebugTelemetry$:new f.ValueSubject(!1),dumpTelemetry:Tb,getCurrentTime$:new f.ValueSubject(null)};if(this.initLogs(),this.tuning=yv(e),this.tracer=t,this.tuning.suppressExceptionsInObservables&&((0,ec.default)(this.info).forEach(r=>r.setSuppressErrors(!0)),(0,ec.default)(this.events).forEach(r=>r.setSuppressErrors(!0))),this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new Es({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new Sv(this.tuning.throughputEstimator),e.exposeInternalsToGlobal&&(this.internalsExposure=new f.InternalsExposure("core",(0,f.getPlayerId)(i?.playerId)),this.internalsExposure.expose({player:this})),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(r,s,n)=>{let u=Reflect.get(r,s,n);return typeof u!="function"?u:(...o)=>{try{return u.apply(r,o)}catch(l){let p=o.map(h=>JSON.stringify(h,(m,b)=>{let S=typeof b;return(0,xv.default)(["number","string","boolean"],S)?b:b===null?null:`<${S}>`})),c=`Player.${String(s)}`,d=`Exception calling ${c} (${p.join(", ")})`;throw this.events.fatalError$.next({id:c,category:f.ErrorCategory.WTF,message:d,thrown:l}),l}}}})}initVideo(e){this.config=e,this.internalsExposure?.expose({config:e,logger:this.logger,tuning:this.tuning}),this.setMuted(this.tuning.isAudioDisabled);let t=()=>{let{container:s,...n}=e;this.tracer.log("initVideo",(0,f.flattenObject)(n)),this.domContainer=Iv(e),this.chromecastInitializer.contentId=e.meta?.videoId,this.providerContainer=new is({sources:e.sources,meta:e.meta??{},failoverHosts:e.failoverHosts??[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,tracer:this.tracer,logger:this.logger,abrLogger:this.abrLogger},tuning:this.tuning,volumeMultiplier:e.volumeMultiplier,panelSize:e.panelSize}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.initTracerSubscription(),this.providerContainer.init(),this.setLiveLowLatency(this.tuning.dashCmafLive.lowLatency.isActiveOnDefault),this.initDebugTelemetry(),this.initWakeLock(),this.playerInited.next(!0)},i=()=>{this.tuning.autostartOnlyIfVisible&&window.requestAnimationFrame?this.playerInitRequest=window.requestAnimationFrame(()=>t()):t()},r=()=>{this.tuning.asyncResolveClientChecker?j.isInited$.pipe((0,f.filter)(s=>!!s),(0,f.once)()).subscribe(()=>{console.log("Core SDK async start"),i()}):i()};return this.isNotActiveTabCase()?(this.tracer.log("request play from hidden tab"),(0,f.fromEvent)(document,"visibilitychange").pipe((0,f.once)()).subscribe(r)):r(),this}destroy(){this.tracer.log("destroy"),window.clearTimeout(this.hasLiveOffsetByPausedTimer),this.playerInitRequest&&window.cancelAnimationFrame(this.playerInitRequest),this.events.willDestruct$.next(),this.stop(),this.providerContainer?.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe(),this.tracer.end(),this.internalsExposure?.destroy()}waitInit(e){this.playerInited.getValue()?e():this.subscription.add(this.playerInited.pipe((0,f.filter)(t=>!!t),(0,f.once)()).subscribe(e))}prepare(){return this.waitInit(()=>{let e=this.desiredState.playbackState;this.tracer.log("prepare",{currentPlayBackState:e.getState()}),e.getState()==="stopped"&&e.startTransitionTo("ready")}),this}play(){return this.waitInit(()=>{let e=this.desiredState.playbackState;this.tracer.log("play",{currentPlayBackState:e.getState()}),e.getState()!=="playing"&&e.startTransitionTo("playing")}),this}pause(){return this.waitInit(()=>{let e=this.desiredState.playbackState;this.tracer.log("pause",{currentPlayBackState:e.getState()}),e.getState()!=="paused"&&e.startTransitionTo("paused")}),this}stop(){return this.waitInit(()=>{let e=this.desiredState.playbackState;this.tracer.log("stop",{currentPlayBackState:e.getState()}),e.getState()!=="stopped"&&e.startTransitionTo("stopped")}),this}seekTime(e,t=!0){return this.waitInit(()=>{let i=this.info.duration$.getValue(),r=this.info.isLive$.getValue(),s=e;e>=i&&!r&&(s=i-this.tuning.seekNearDurationBias),this.tracer.log("seekTime",{duration:i,isLive:r,time:e,calculatedTime:s,forcePrecise:t}),Number.isFinite(s)&&(this.events.willSeek$.next({from:this.getExactTime(),to:s}),this.desiredState.seekState.setState({state:"requested",position:s*1e3,forcePrecise:t}))}),this}seekPercent(e){return this.waitInit(()=>{let t=this.info.duration$.getValue();this.tracer.log("seekPercent",{percent:e,duration:t}),isFinite(t)&&this.seekTime(Math.abs(t)*e,!1)}),this}setVolume(e,t){return this.waitInit(()=>{let i=this.desiredState.volume,s=i.getTransition()?.to.muted??this.info.muted$.getValue(),n=t??(this.tuning.isAudioDisabled||s);this.tracer.log("setVolume",{volume:e,isAudioDisabled:this.tuning.isAudioDisabled,chromecastState:this.chromecastInitializer.castState$.getValue(),muted:n}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setVolume(e):i.startTransitionTo({volume:e,muted:n})}),this}setMuted(e,t=!1){return this.waitInit(()=>{let i=this.desiredState.volume,r=this.tuning.isAudioDisabled&&!t||e,n=i.getTransition()?.to.volume??this.info.volume$.getValue();this.tracer.log("setMuted",{isMuted:e,nextMuted:r,volume:n,isAudioDisabled:this.tuning.isAudioDisabled,chromecastState:this.chromecastInitializer.castState$.getValue()}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setMuted(r):i.startTransitionTo({volume:n,muted:r})}),this}setVideoStream(e){return this.waitInit(()=>{this.desiredState.videoStream.startTransitionTo(e)}),this}setAudioStream(e){return this.waitInit(()=>{this.desiredState.audioStream.startTransitionTo(e)}),this}setQuality(e){return this.waitInit(()=>{(0,f.assertNonNullable)(this.providerContainer);let t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();this.tracer.log("setQuality",{isDelayed:t.length===0,quality:e}),this.desiredState.videoTrack.getState()===void 0&&this.desiredState.videoTrack.getPrevState()===void 0&&t.length===0?this.wasSetStartedQuality?this.providerContainer.providerOutput.availableVideoTracks$.pipe((0,f.filter)(i=>i.length>0),(0,f.once)()).subscribe(i=>{this.setVideoTrackIdByQuality(i,e)}):this.explicitInitialQuality=e:t.length>0&&this.setVideoTrackIdByQuality(t,e)}),this}setAutoQuality(e){return this.waitInit(()=>{this.tracer.log("setAutoQuality",{enable:e}),this.desiredState.autoVideoTrackSwitching.startTransitionTo(e)}),this}setAutoQualityLimits(e){return this.waitInit(()=>{this.tracer.log("setAutoQualityLimits",(0,f.flattenObject)(e)),this.desiredState.autoVideoTrackLimits.startTransitionTo(e)}),this}setPredefinedQualityLimits(e){return this.waitInit(()=>{if(this.info.predefinedQualityLimitType$.getValue()===e)return this;let{highQualityLimit:t,trafficSavingLimit:i}=this.tuning.autoTrackSelection,r;switch(e){case"high_quality":r={min:t,max:void 0};break;case"traffic_saving":r={max:i,min:void 0};break;default:r={max:void 0,min:void 0}}this.setAutoQualityLimits(r)}),this}setPlaybackRate(e){return this.waitInit(()=>{this.tracer.log("setPlaybackRate",{playbackRate:e}),this.desiredState.playbackRate.startTransitionTo(e)}),this}setExternalTextTracks(e){return this.waitInit(()=>{e.length&&this.tracer.log("setExternalTextTracks",(0,f.flattenObject)(e)),this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>({type:"external",...t})))}),this}selectTextTrack(e){return this.waitInit(()=>{Ev(e,this.desiredState.currentTextTrack,this.providerContainer?.providerOutput.availableTextTracks$,t=>t.id===e),this.tracer.log("selectTextTrack",{textTrackId:e})}),this}setTextTrackCueSettings(e){return this.waitInit(()=>{this.tracer.log("setTextTrackCueSettings",{...e}),this.desiredState.textTrackCuesSettings.startTransitionTo(e)}),this}setLiveLowLatency(e){let t=this.info.isLive$.getValue(),i=this.desiredState.isLowLatency.getState();return!t||i===e?this:(this.tracer.log("live switch to low latency "+e),this.desiredState.isLowLatency.setState(e),this.seekTime(0))}setLooped(e){return this.waitInit(()=>{this.tracer.log("setLooped",{isLooped:e}),this.desiredState.isLooped.startTransitionTo(e)}),this}toggleChromecast(){this.tracer.log("toggleChromecast"),this.chromecastInitializer.toggleConnection()}startCameraManualRotation(e,t){return this.waitInit(()=>{let i=this.getScene3D();this.tracer.log("startCameraManualRotation",{isScene3DAvailable:!!i,mx:e,my:t}),i&&i.startCameraManualRotation(e,t)}),this}stopCameraManualRotation(e=!1){return this.waitInit(()=>{let t=this.getScene3D();this.tracer.log("stopCameraManualRotation",{isScene3DAvailable:!!t,immediate:e}),t&&t.stopCameraManualRotation(e)}),this}moveCameraFocusPX(e,t){return this.waitInit(()=>{let i=this.getScene3D();if(this.tracer.log("moveCameraFocusPX",{isScene3DAvailable:!!i,dxpx:e,dypx:t}),i){let r=i.getCameraRotation(),s=i.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:r.x+s.x,y:r.y+s.y})}}),this}holdCamera(){return this.waitInit(()=>{let e=this.getScene3D();e&&e.holdCamera()}),this}releaseCamera(){return this.waitInit(()=>{let e=this.getScene3D();e&&e.releaseCamera()}),this}getExactTime(){if(!this.providerContainer)return 0;let e=this.providerContainer.providerOutput.element$.getValue();if((0,f.isNullable)(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),i=t.state==="none"?void 0:t.position;return(0,f.isNonNullable)(i)?i/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}getScene3D(){let e=this.providerContainer?.current$.getValue();if(e?.provider?.scene3D)return e.provider.scene3D}setIntrinsicVideoSize(...e){let t={width:e.reduce((i,{width:r})=>i||r||0,0),height:e.reduce((i,{height:r})=>i||r||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add((0,f.merge)(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe((0,f.map)(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe((0,f.map)(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe((0,f.map)(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe((0,f.map)(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe((0,f.map)(e=>e.to)).subscribe(e=>{this.info.autoQualityLimits$.next(e);let{highQualityLimit:t,trafficSavingLimit:i}=this.tuning.autoTrackSelection;this.info.predefinedQualityLimitType$.next(Ib(e,t,i))})),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe((0,f.filter)(({from:e})=>e==="stopped"),(0,f.once)()).subscribe(()=>{this.initedAt=(0,f.now)(),this.events.inited$.next()})).add(this.desiredState.playbackState.stateChangeEnded$.subscribe(e=>{switch(e.to){case"ready":this.events.ready$.next();break;case"playing":this.isPlaybackStarted||this.events.started$.next(),this.isPlaybackStarted=!0,this.events.playing$.next();break;case"paused":this.events.paused$.next();break;case"stopped":this.events.stopped$.next()}})).add(this.desiredState.playbackState.stateChangeStarted$.subscribe(e=>{switch(e.to){case"ready":this.events.willReady$.next();break;case"paused":this.events.willPause$.next();break;case"playing":this.isPlaybackStarted?this.events.willResume$.next():this.events.willStart$.next();break;case"stopped":this.events.willStop$.next();break;default:}}))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();this.tracer.log("willSeekEvent",(0,f.flattenObject)(n)),n.state==="requested"?this.desiredState.seekState.setState({...n,state:"applying"}):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:f.ErrorCategory.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.soundProhibitedEvent$.pipe((0,f.once)()).subscribe(this.events.autoplaySoundProhibited$)).add(e.providerOutput.severeStallOccurred$.subscribe(this.events.severeStallOccured$)).add(e.providerOutput.seekedEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();this.tracer.log("seekedEvent",(0,f.flattenObject)(n)),n.state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe((0,f.map)(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe((0,f.map)(n=>n.destination),(0,f.filterChanged)()).subscribe(()=>this.isPlaybackStarted=!1)).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add((0,f.combine)({availableVideoTracks:e.providerOutput.availableVideoTracks$,currentVideoStream:e.providerOutput.currentVideoStream$}).pipe((0,f.map)(({availableVideoTracks:n,currentVideoStream:u})=>n.filter(o=>u?u.id===o.streamId:!0).map(({quality:o})=>o).sort((o,l)=>(0,f.isInvariantQuality)(o)?1:(0,f.isInvariantQuality)(l)?-1:(0,f.isHigher)(l,o)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(n=>{let u={};for(let o of n)o.fps&&(u[o.quality]=o.fps);this.info.availableQualitiesFps$.next(u)})).add(e.providerOutput.availableAudioStreams$.subscribe(this.info.availableAudioStreams$)).add(e.providerOutput.currentVideoStream$.subscribe(this.info.currentVideoStream$)).add(e.providerOutput.currentAudioStream$.subscribe(this.info.currentAudioStream$)).add(e.providerOutput.availableAudioTracks$.subscribe(this.info.availableAudioTracks$)).add(e.providerOutput.isAudioAvailable$.pipe((0,f.filterChanged)()).subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.pipe((0,f.filter)(n=>(0,f.isNonNullable)(n))).subscribe(n=>{this.info.currentQuality$.next(n?.quality),this.info.videoBitrate$.next(n?.bitrate)})).add(e.providerOutput.currentVideoSegmentLength$.pipe((0,f.filterChanged)((n,u)=>Math.round(n)===Math.round(u))).subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.pipe((0,f.filterChanged)((n,u)=>Math.round(n)===Math.round(u))).subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe((0,f.filterChanged)()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe((0,f.filterChanged)()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe((0,f.filterChanged)()).subscribe(this.info.httpConnectionReused$)).add(e.providerOutput.currentTextTrack$.subscribe(this.info.currentTextTrack$)).add(e.providerOutput.availableTextTracks$.subscribe(this.info.availableTextTracks$)).add(e.providerOutput.autoVideoTrackLimitingAvailable$.subscribe(this.info.autoQualityLimitingAvailable$)).add(e.providerOutput.autoVideoTrackLimits$.subscribe(n=>{this.desiredState.autoVideoTrackLimits.setState(n??{})})).add(e.providerOutput.currentBuffer$.pipe((0,f.map)(n=>n?{start:n.from,end:n.to}:{start:0,end:0})).subscribe(this.info.currentBuffer$)).add(e.providerOutput.duration$.subscribe(this.info.duration$)).add(e.providerOutput.isBuffering$.subscribe(this.info.isBuffering$)).add(e.providerOutput.isLive$.subscribe(this.info.isLive$)).add(e.providerOutput.isLiveEnded$.pipe((0,f.tap)(n=>n&&this.stop())).subscribe(this.info.isLiveEnded$)).add(e.providerOutput.canPlayLiveTailBuffer$.subscribe(this.info.canPlayLiveTailBuffer$)).add(e.providerOutput.canChangePlaybackSpeed$.subscribe(this.info.canChangePlaybackSpeed$)).add(e.providerOutput.liveTime$.subscribe(this.info.liveTime$)).add(e.providerOutput.liveBufferTime$.subscribe(this.info.liveBufferTime$)).add(e.providerOutput.liveLatency$.subscribe(this.info.liveLatency$)).add((0,f.combine)({hasLiveOffsetByPaused:(0,f.merge)(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe((0,f.map)(n=>n.to),(0,f.filterChanged)(),(0,f.map)(n=>n==="paused")),isLowLatency:e.providerOutput.isLowLatency$}).subscribe(({hasLiveOffsetByPaused:n,isLowLatency:u})=>{if(window.clearTimeout(this.hasLiveOffsetByPausedTimer),n){this.hasLiveOffsetByPausedTimer=window.setTimeout(()=>{this.hasLiveOffsetByPaused.next(!0)},this.getActiveLiveDelay(u));return}this.hasLiveOffsetByPaused.next(!1)})).add((0,f.combine)({atLiveEdge:(0,f.combine)({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:Zl({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe((0,f.map)(({isLive:n,position:u,isLowLatency:o})=>{let l=this.getActiveLiveDelay(o);return n&&Math.abs(u)<l/1e3}),(0,f.filterChanged)(),(0,f.tap)(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe((0,f.map)(({atLiveEdge:n,hasPausedTimeoutCase:u})=>n&&!u)).subscribe(this.info.atLiveEdge$)).add((0,f.combine)({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe((0,f.map)(({isLive:n,position:u,duration:o})=>n&&(Math.abs(o)-Math.abs(u))*1e3<this.tuning.live.activeLiveDelay),(0,f.filterChanged)(),(0,f.tap)(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe((0,f.map)(n=>n.muted),(0,f.filterChanged)()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe((0,f.map)(n=>n.volume),(0,f.filterChanged)()).subscribe(this.info.volume$)).add(Zl({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(e.providerOutput.seekedEvent$.subscribe(()=>{this.info.isEnded$.getValue()&&this.tuning.changePlaybackStateToPausedWhenEnded&&this.play()})).add((0,f.merge)(e.providerOutput.endedEvent$.pipe((0,f.mapTo)(!0)),e.providerOutput.seekedEvent$.pipe((0,f.mapTo)(!1))).pipe((0,f.filterChanged)()).subscribe(this.info.isEnded$)).add(e.providerOutput.endedEvent$.subscribe(this.events.ended$)).add(e.providerOutput.loopedEvent$.subscribe(this.events.looped$)).add(e.providerError$.subscribe(this.events.managedError$)).add(e.providerOutput.fetcherRecoverableError$.subscribe(this.events.fetcherRecoverableError$)).add(e.providerOutput.fetcherError$.subscribe(this.events.fatalError$)).add(e.volumeMultiplierError$.subscribe(this.events.managedError$)).add(e.noAvailableProvidersError$.pipe((0,f.map)(n=>({id:n?`No${n}`:"NoProviders",category:f.ErrorCategory.VIDEO_PIPELINE,message:n?`${n} was forced but failed or not available`:"No suitable providers or all providers failed"}))).subscribe(this.events.fatalError$)).add(e.providerOutput.element$.subscribe(this.experimental.element$)).add(e.providerOutput.getCurrentTime$.subscribe(this.experimental.getCurrentTime$)).add(e.providerOutput.manifestRequested$.pipe((0,f.once)()).subscribe(this.events.manifestRequested$)).add(e.providerOutput.firstBytesManifest$.pipe((0,f.once)()).subscribe(this.events.firstBytesManifest$)).add(e.providerOutput.manifestReceived$.pipe((0,f.once)()).subscribe(this.events.manifestReceived$)).add(e.providerOutput.firstBytesRequested$.pipe((0,f.once)()).subscribe(this.events.firstBytesRequested$)).add(e.providerOutput.firstBytesReceived$.pipe((0,f.once)()).subscribe(this.events.firstBytesReceived$)).add(e.providerOutput.firstBytesEvent$.pipe((0,f.once)(),(0,f.map)(n=>n??(0,f.now)()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe((0,f.once)(),(0,f.map)(()=>(0,f.now)()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe((0,f.once)(),(0,f.map)(()=>(0,f.now)()-this.initedAt)).subscribe(this.events.canplay$)).add(this.throughputEstimator.throughput$.subscribe(this.info.throughputEstimation$)).add(this.throughputEstimator.rtt$.subscribe(this.info.rttEstimation$)).add(e.providerOutput.availableSources$.subscribe(this.info.availableSources$));let t=new f.ValueSubject(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let i=new f.ValueSubject(!0);this.subscription.add(e.current$.subscribe(()=>i.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe((0,f.filter)(({to:n})=>n==="playing"),(0,f.once)()).subscribe(()=>i.next(!1)));let r=0,s=(0,f.merge)(e.providerOutput.isBuffering$,t,i).pipe((0,f.map)(()=>{let n=e.providerOutput.isBuffering$.getValue(),u=t.getValue()||i.getValue();return n&&!u}),(0,f.filterChanged)());this.subscription.add(s.subscribe(n=>{n?r=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(r),this.info.isStalled$.next(!1))})),this.subscription.add((0,f.merge)(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{let n=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:n?.videoWidth,height:n?.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{let u=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:n?.size?.width,height:n?.size?.height},{width:u?.videoWidth,height:u?.videoHeight})})).add(e.providerOutput.is3DVideo$.subscribe(this.info.is3DVideo$)),this.subscription.add((0,f.merge)(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,e.providerOutput.elementVisible$,this.chromecastInitializer.castState$).subscribe(()=>{let n=e.providerOutput.inPiP$.getValue(),u=e.providerOutput.inFullscreen$.getValue(),o=e.providerOutput.element$.getValue(),l=e.providerOutput.elementVisible$.getValue(),p=this.chromecastInitializer.castState$.getValue(),c;p==="CONNECTED"?c="second_screen":o?l?n?c="pip":u?c="fullscreen":c="inline":c="invisible":c="none",this.info.surface$.getValue()!==c&&this.info.surface$.next(c)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe((0,f.map)(e=>e?.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){let t=new f.Subscription;this.subscription.add(t),this.subscription.add(e.current$.pipe((0,f.filterChanged)((i,r)=>i.provider===r.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe((0,f.filter)(i=>i.length>0),(0,f.once)()).subscribe(i=>{this.setStartingVideoTrack(i)}))}))}setStartingVideoTrack(e){let t;this.wasSetStartedQuality=!0;let i=this.explicitInitialQuality??this.info.currentQuality$.getValue();i&&(t=e.find(({quality:r})=>r===i),t||this.setAutoQuality(!0)),t||(t=Rt(e,{container:this.domContainer.getBoundingClientRect(),panelSize:this.config.panelSize,estimatedThroughput:this.throughputEstimator.throughput$.getValue(),tuning:this.tuning.autoTrackSelection,limits:this.desiredState.autoVideoTrackLimits.getState(),playbackRate:this.info.currentPlaybackRate$.getValue(),forwardBufferHealth:0,abrLogger:this.abrLogger})),this.desiredState.videoTrack.startTransitionTo(t),this.info.currentQuality$.next(t.quality),this.info.videoBitrate$.next(t.bitrate)}initLogs(){this.subscription.add((0,f.merge)(this.desiredState.videoTrack.stateChangeStarted$.pipe((0,f.map)(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe((0,f.map)(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe((0,f.map)(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe((0,f.map)(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe((0,f.map)(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe((0,f.map)(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe((0,f.map)(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe((0,f.map)(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe((0,f.map)(e=>({component:"desiredState",message:`[${e.entity} change] ${e.type}: ${JSON.stringify(e.transition)}`}))).subscribe(this.logger.log)),this.subscription.add(this.logger.log$.subscribe(this.events.log$))}initDebugTelemetry(){let e=this.providerContainer?.providerOutput;(0,f.assertNonNullable)(this.providerContainer),(0,f.assertNonNullable)(e),yb(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(t=>vb(t)),this.providerContainer.current$.subscribe(({type:t})=>ia("provider",t)),e.duration$.subscribe(t=>ia("duration",t)),e.availableVideoTracks$.pipe((0,f.filter)(t=>!!t.length),(0,f.once)()).subscribe(t=>ia("tracks",t)),this.events.fatalError$.subscribe(new Fe("fatalError")),this.events.managedError$.subscribe(new Fe("managedError")),e.position$.subscribe(new Fe("position")),e.currentVideoTrack$.pipe((0,f.map)(t=>t?.quality)).subscribe(new Fe("quality")),this.info.currentBuffer$.subscribe(new Fe("buffer")),e.isBuffering$.subscribe(new Fe("isBuffering"))].forEach(t=>this.subscription.add(t)),ia("codecs",j.video.supportedCodecs)}initTracerSubscription(){let e=(0,f.getTraceSubscriptionMethod)(this.tracer.log.bind(this.tracer)),t=(0,f.getTraceSubscriptionMethod)(this.tracer.error.bind(this.tracer));this.subscription.add(this.info.playbackState$.subscribe(e("playbackState"))).add(this.info.isLooped$.subscribe(e("isLooped"))).add(this.info.currentPlaybackRate$.pipe((0,f.filterChanged)()).subscribe(e("currentPlaybackRate"))).add(this.info.isAutoQualityEnabled$.subscribe(e("isAutoQualityEnabled"))).add(this.info.autoQualityLimits$.subscribe(e("autoQualityLimits"))).add(this.info.currentFormat$.subscribe(e("currentFormat"))).add(this.info.availableQualities$.subscribe(e("availableQualities"))).add(this.info.availableQualitiesFps$.subscribe(e("availableQualitiesFps"))).add(this.info.availableAudioTracks$.subscribe(e("availableAudioTracks"))).add(this.info.isAudioAvailable$.subscribe(e("isAudioAvailable"))).add((0,f.combine)({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe((0,f.filter)(({currentQuality:i,videoBitrate:r})=>!!i&&!!r),(0,f.filterChanged)((i,r)=>i.currentQuality===r.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe((0,f.filter)(i=>i>0),(0,f.filterChanged)()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe((0,f.filter)(i=>i>0),(0,f.filterChanged)()).subscribe(e("currentAudioSegmentLength"))).add(this.info.hostname$.subscribe(e("hostname"))).add(this.info.currentTextTrack$.subscribe(e("currentTextTrack"))).add(this.info.availableTextTracks$.subscribe(e("availableTextTracks"))).add(this.info.autoQualityLimitingAvailable$.subscribe(e("autoQualityLimitingAvailable"))).add((0,f.combine)({currentBuffer:this.info.currentBuffer$.pipe((0,f.filter)(i=>i.end>0),(0,f.filterChanged)((i,r)=>i.end===r.end&&i.start===r.start)),position:this.info.position$.pipe((0,f.filterChanged)())}).pipe((0,f.throttle)(1e3)).subscribe(e("currentBufferAndPosition"))).add(this.info.duration$.pipe((0,f.filterChanged)()).subscribe(e("duration"))).add(this.info.isBuffering$.subscribe(e("isBuffering"))).add(this.info.isLive$.pipe((0,f.filterChanged)()).subscribe(e("isLive"))).add(this.info.canChangePlaybackSpeed$.pipe((0,f.filterChanged)()).subscribe(e("canChangePlaybackSpeed"))).add((0,f.combine)({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe((0,f.filter)(({liveTime:i,liveBufferTime:r})=>!!i&&!!r),(0,f.throttle)(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe((0,f.filterChanged)(),(0,f.filter)(i=>i===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe((0,f.filterChanged)(),(0,f.filter)(i=>i===!0)).subscribe(e("atLiveDurationEdge"))).add(this.info.muted$.pipe((0,f.filterChanged)()).subscribe(e("muted"))).add(this.info.volume$.pipe((0,f.filterChanged)()).subscribe(e("volume"))).add(this.info.isEnded$.pipe((0,f.filterChanged)(),(0,f.filter)(i=>i===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add((0,f.combine)({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe((0,f.filter)(({throughputEstimation:i,rtt:r})=>!!i&&!!r),(0,f.throttle)(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe((0,f.filterChanged)(),(0,f.filter)(i=>i===!0)).subscribe(e("is3DVideo"))).add(this.info.surface$.subscribe(e("surface"))).add(this.events.ended$.subscribe(e("ended"))).add(this.events.looped$.subscribe(e("looped"))).add(this.events.managedError$.subscribe(t("managedError"))).add(this.events.fatalError$.subscribe(t("fatalError"))).add(this.events.firstBytes$.subscribe(e("firstBytes"))).add(this.events.firstFrame$.subscribe(e("firstFrame"))).add(this.events.canplay$.subscribe(e("canplay")))}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e,t=()=>{e?.release(),e=void 0},i=async()=>{t(),e=await window.navigator.wakeLock.request("screen").catch(r=>{r instanceof DOMException&&r.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:f.ErrorCategory.DOM,message:String(r)})})};this.subscription.add((0,f.merge)((0,f.fromEvent)(document,"visibilitychange"),(0,f.fromEvent)(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{let r=document.visibilityState==="visible",s=this.desiredState.playbackState.getState()==="playing",n=!!e&&!e?.released;r&&s?n||i():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){let i=e.find(r=>r.quality===t);this.tracer.log("setVideoTrackIdByQuality",(0,f.flattenObject)({quality:t,availableTracks:(0,f.flattenObject)(e),track:(0,f.flattenObject)(i),isAutoQuality:!i})),i?this.desiredState.videoTrack.startTransitionTo(i):this.setAutoQuality(!0)}getActiveLiveDelay(e=!1){return e?this.tuning.live.lowLatencyActiveLiveDelay:this.tuning.live.activeLiveDelay}isNotActiveTabCase(){return document.hidden&&this.tuning.autoplayOnlyInActiveTab&&!ua()}};var Ct=require("@vkontakte/videoplayer-shared"),y$=`@vkontakte/videoplayer-core@${ro}`;