@vkontakte/videoplayer-core 2.0.141-dev.752fa0a9.0 → 2.0.141-dev.95df362c.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/es2024.esm.js CHANGED
@@ -1,10 +1,10 @@
1
1
  /**
2
- * @vkontakte/videoplayer-core v2.0.141-dev.752fa0a9.0
3
- * Mon, 22 Sep 2025 10:07:10 GMT
2
+ * @vkontakte/videoplayer-core v2.0.141-dev.95df362c.0
3
+ * Tue, 23 Sep 2025 09:38:09 GMT
4
4
  * https://st.mycdn.me/static/vkontakte-videoplayer/2-0-141/doc/
5
5
  */
6
- var UI=Object.create;var qd=Object.defineProperty;var HI=Object.getOwnPropertyDescriptor;var jI=Object.getOwnPropertyNames;var QI=Object.getPrototypeOf,WI=Object.prototype.hasOwnProperty;var b=(a,e)=>()=>(e||a((e={exports:{}}).exports,e),e.exports);var GI=(a,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of jI(e))!WI.call(a,r)&&r!==t&&qd(a,r,{get:()=>e[r],enumerable:!(i=HI(e,r))||i.enumerable});return a};var B=(a,e,t)=>(t=a!=null?UI(QI(a)):{},GI(e||!a||!a.__esModule?qd(t,"default",{value:a,enumerable:!0}):t,a));var re=b((iu,Hd)=>{"use strict";var Nr=function(a){return a&&a.Math===Math&&a};Hd.exports=Nr(typeof globalThis=="object"&&globalThis)||Nr(typeof window=="object"&&window)||Nr(typeof self=="object"&&self)||Nr(typeof global=="object"&&global)||Nr(typeof iu=="object"&&iu)||function(){return this}()||Function("return this")()});var pe=b((t0,jd)=>{"use strict";jd.exports=function(a){try{return!!a()}catch{return!0}}});var qr=b((i0,Qd)=>{"use strict";var zI=pe();Qd.exports=!zI(function(){var a=function(){}.bind();return typeof a!="function"||a.hasOwnProperty("prototype")})});var ru=b((r0,Yd)=>{"use strict";var YI=qr(),zd=Function.prototype,Wd=zd.apply,Gd=zd.call;Yd.exports=typeof Reflect=="object"&&Reflect.apply||(YI?Gd.bind(Wd):function(){return Gd.apply(Wd,arguments)})});var he=b((a0,Jd)=>{"use strict";var Kd=qr(),Xd=Function.prototype,au=Xd.call,KI=Kd&&Xd.bind.bind(au,au);Jd.exports=Kd?KI:function(a){return function(){return au.apply(a,arguments)}}});var oi=b((s0,ep)=>{"use strict";var Zd=he(),XI=Zd({}.toString),JI=Zd("".slice);ep.exports=function(a){return JI(XI(a),8,-1)}});var su=b((n0,tp)=>{"use strict";var ZI=oi(),eE=he();tp.exports=function(a){if(ZI(a)==="Function")return eE(a)}});var ae=b((o0,ip)=>{"use strict";var nu=typeof document=="object"&&document.all;ip.exports=typeof nu>"u"&&nu!==void 0?function(a){return typeof a=="function"||a===nu}:function(a){return typeof a=="function"}});var Fe=b((u0,rp)=>{"use strict";var tE=pe();rp.exports=!tE(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var Ne=b((l0,ap)=>{"use strict";var iE=qr(),Ws=Function.prototype.call;ap.exports=iE?Ws.bind(Ws):function(){return Ws.apply(Ws,arguments)}});var ou=b(op=>{"use strict";var sp={}.propertyIsEnumerable,np=Object.getOwnPropertyDescriptor,rE=np&&!sp.call({1:2},1);op.f=rE?function(e){var t=np(this,e);return!!t&&t.enumerable}:sp});var Ur=b((d0,up)=>{"use strict";up.exports=function(a,e){return{enumerable:!(a&1),configurable:!(a&2),writable:!(a&4),value:e}}});var cp=b((p0,lp)=>{"use strict";var aE=he(),sE=pe(),nE=oi(),uu=Object,oE=aE("".split);lp.exports=sE(function(){return!uu("z").propertyIsEnumerable(0)})?function(a){return nE(a)==="String"?oE(a,""):uu(a)}:uu});var Hr=b((h0,dp)=>{"use strict";dp.exports=function(a){return a==null}});var Ft=b((f0,pp)=>{"use strict";var uE=Hr(),lE=TypeError;pp.exports=function(a){if(uE(a))throw new lE("Can't call method on "+a);return a}});var ui=b((m0,hp)=>{"use strict";var cE=cp(),dE=Ft();hp.exports=function(a){return cE(dE(a))}});var $e=b((b0,fp)=>{"use strict";var pE=ae();fp.exports=function(a){return typeof a=="object"?a!==null:pE(a)}});var li=b((g0,mp)=>{"use strict";mp.exports={}});var wt=b((S0,gp)=>{"use strict";var lu=li(),cu=re(),hE=ae(),bp=function(a){return hE(a)?a:void 0};gp.exports=function(a,e){return arguments.length<2?bp(lu[a])||bp(cu[a]):lu[a]&&lu[a][e]||cu[a]&&cu[a][e]}});var jr=b((v0,Sp)=>{"use strict";var fE=he();Sp.exports=fE({}.isPrototypeOf)});var ci=b((y0,Tp)=>{"use strict";var mE=re(),vp=mE.navigator,yp=vp&&vp.userAgent;Tp.exports=yp?String(yp):""});var pu=b((T0,Pp)=>{"use strict";var Ap=re(),du=ci(),Ip=Ap.process,Ep=Ap.Deno,xp=Ip&&Ip.versions||Ep&&Ep.version,wp=xp&&xp.v8,et,Gs;wp&&(et=wp.split("."),Gs=et[0]>0&&et[0]<4?1:+(et[0]+et[1]));!Gs&&du&&(et=du.match(/Edge\/(\d+)/),(!et||et[1]>=74)&&(et=du.match(/Chrome\/(\d+)/),et&&(Gs=+et[1])));Pp.exports=Gs});var hu=b((I0,Rp)=>{"use strict";var kp=pu(),bE=pe(),gE=re(),SE=gE.String;Rp.exports=!!Object.getOwnPropertySymbols&&!bE(function(){var a=Symbol("symbol detection");return!SE(a)||!(Object(a)instanceof Symbol)||!Symbol.sham&&kp&&kp<41})});var fu=b((E0,Lp)=>{"use strict";var vE=hu();Lp.exports=vE&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var mu=b((x0,$p)=>{"use strict";var yE=wt(),TE=ae(),IE=jr(),EE=fu(),xE=Object;$p.exports=EE?function(a){return typeof a=="symbol"}:function(a){var e=yE("Symbol");return TE(e)&&IE(e.prototype,xE(a))}});var Qr=b((w0,Mp)=>{"use strict";var wE=String;Mp.exports=function(a){try{return wE(a)}catch{return"Object"}}});var ht=b((A0,Dp)=>{"use strict";var AE=ae(),PE=Qr(),kE=TypeError;Dp.exports=function(a){if(AE(a))return a;throw new kE(PE(a)+" is not a function")}});var Wr=b((P0,Cp)=>{"use strict";var RE=ht(),LE=Hr();Cp.exports=function(a,e){var t=a[e];return LE(t)?void 0:RE(t)}});var Vp=b((k0,Bp)=>{"use strict";var bu=Ne(),gu=ae(),Su=$e(),$E=TypeError;Bp.exports=function(a,e){var t,i;if(e==="string"&&gu(t=a.toString)&&!Su(i=bu(t,a))||gu(t=a.valueOf)&&!Su(i=bu(t,a))||e!=="string"&&gu(t=a.toString)&&!Su(i=bu(t,a)))return i;throw new $E("Can't convert object to primitive value")}});var tt=b((R0,_p)=>{"use strict";_p.exports=!0});var Np=b((L0,Fp)=>{"use strict";var Op=re(),ME=Object.defineProperty;Fp.exports=function(a,e){try{ME(Op,a,{value:e,configurable:!0,writable:!0})}catch{Op[a]=e}return e}});var Gr=b(($0,Hp)=>{"use strict";var DE=tt(),CE=re(),BE=Np(),qp="__core-js_shared__",Up=Hp.exports=CE[qp]||BE(qp,{});(Up.versions||(Up.versions=[])).push({version:"3.43.0",mode:DE?"pure":"global",copyright:"\xA9 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 vu=b((M0,Qp)=>{"use strict";var jp=Gr();Qp.exports=function(a,e){return jp[a]||(jp[a]=e||{})}});var Ui=b((D0,Wp)=>{"use strict";var VE=Ft(),_E=Object;Wp.exports=function(a){return _E(VE(a))}});var it=b((C0,Gp)=>{"use strict";var OE=he(),FE=Ui(),NE=OE({}.hasOwnProperty);Gp.exports=Object.hasOwn||function(e,t){return NE(FE(e),t)}});var yu=b((B0,zp)=>{"use strict";var qE=he(),UE=0,HE=Math.random(),jE=qE(1.1.toString);zp.exports=function(a){return"Symbol("+(a===void 0?"":a)+")_"+jE(++UE+HE,36)}});var ge=b((V0,Kp)=>{"use strict";var QE=re(),WE=vu(),Yp=it(),GE=yu(),zE=hu(),YE=fu(),Hi=QE.Symbol,Tu=WE("wks"),KE=YE?Hi.for||Hi:Hi&&Hi.withoutSetter||GE;Kp.exports=function(a){return Yp(Tu,a)||(Tu[a]=zE&&Yp(Hi,a)?Hi[a]:KE("Symbol."+a)),Tu[a]}});var eh=b((_0,Zp)=>{"use strict";var XE=Ne(),Xp=$e(),Jp=mu(),JE=Wr(),ZE=Vp(),ex=ge(),tx=TypeError,ix=ex("toPrimitive");Zp.exports=function(a,e){if(!Xp(a)||Jp(a))return a;var t=JE(a,ix),i;if(t){if(e===void 0&&(e="default"),i=XE(t,a,e),!Xp(i)||Jp(i))return i;throw new tx("Can't convert object to primitive value")}return e===void 0&&(e="number"),ZE(a,e)}});var Iu=b((O0,th)=>{"use strict";var rx=eh(),ax=mu();th.exports=function(a){var e=rx(a,"string");return ax(e)?e:e+""}});var zs=b((F0,rh)=>{"use strict";var sx=re(),ih=$e(),Eu=sx.document,nx=ih(Eu)&&ih(Eu.createElement);rh.exports=function(a){return nx?Eu.createElement(a):{}}});var xu=b((N0,ah)=>{"use strict";var ox=Fe(),ux=pe(),lx=zs();ah.exports=!ox&&!ux(function(){return Object.defineProperty(lx("div"),"a",{get:function(){return 7}}).a!==7})});var oh=b(nh=>{"use strict";var cx=Fe(),dx=Ne(),px=ou(),hx=Ur(),fx=ui(),mx=Iu(),bx=it(),gx=xu(),sh=Object.getOwnPropertyDescriptor;nh.f=cx?sh:function(e,t){if(e=fx(e),t=mx(t),gx)try{return sh(e,t)}catch{}if(bx(e,t))return hx(!dx(px.f,e,t),e[t])}});var wu=b((U0,uh)=>{"use strict";var Sx=pe(),vx=ae(),yx=/#|\.prototype\./,zr=function(a,e){var t=Ix[Tx(a)];return t===xx?!0:t===Ex?!1:vx(e)?Sx(e):!!e},Tx=zr.normalize=function(a){return String(a).replace(yx,".").toLowerCase()},Ix=zr.data={},Ex=zr.NATIVE="N",xx=zr.POLYFILL="P";uh.exports=zr});var ji=b((H0,ch)=>{"use strict";var lh=su(),wx=ht(),Ax=qr(),Px=lh(lh.bind);ch.exports=function(a,e){return wx(a),e===void 0?a:Ax?Px(a,e):function(){return a.apply(e,arguments)}}});var Au=b((j0,dh)=>{"use strict";var kx=Fe(),Rx=pe();dh.exports=kx&&Rx(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var ft=b((Q0,ph)=>{"use strict";var Lx=$e(),$x=String,Mx=TypeError;ph.exports=function(a){if(Lx(a))return a;throw new Mx($x(a)+" is not an object")}});var di=b(fh=>{"use strict";var Dx=Fe(),Cx=xu(),Bx=Au(),Ys=ft(),hh=Iu(),Vx=TypeError,Pu=Object.defineProperty,_x=Object.getOwnPropertyDescriptor,ku="enumerable",Ru="configurable",Lu="writable";fh.f=Dx?Bx?function(e,t,i){if(Ys(e),t=hh(t),Ys(i),typeof e=="function"&&t==="prototype"&&"value"in i&&Lu in i&&!i[Lu]){var r=_x(e,t);r&&r[Lu]&&(e[t]=i.value,i={configurable:Ru in i?i[Ru]:r[Ru],enumerable:ku in i?i[ku]:r[ku],writable:!1})}return Pu(e,t,i)}:Pu:function(e,t,i){if(Ys(e),t=hh(t),Ys(i),Cx)try{return Pu(e,t,i)}catch{}if("get"in i||"set"in i)throw new Vx("Accessors not supported");return"value"in i&&(e[t]=i.value),e}});var Qi=b((G0,mh)=>{"use strict";var Ox=Fe(),Fx=di(),Nx=Ur();mh.exports=Ox?function(a,e,t){return Fx.f(a,e,Nx(1,t))}:function(a,e,t){return a[e]=t,a}});var oe=b((z0,gh)=>{"use strict";var Yr=re(),qx=ru(),Ux=su(),Hx=ae(),jx=oh().f,Qx=wu(),Wi=li(),Wx=ji(),Gi=Qi(),bh=it();Gr();var Gx=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 qx(a,this,arguments)};return e.prototype=a.prototype,e};gh.exports=function(a,e){var t=a.target,i=a.global,r=a.stat,s=a.proto,n=i?Yr:r?Yr[t]:Yr[t]&&Yr[t].prototype,u=i?Wi:Wi[t]||Gi(Wi,t,{})[t],o=u.prototype,l,p,d,c,h,f,m,g,S;for(c in e)l=Qx(i?c:t+(r?".":"#")+c,a.forced),p=!l&&n&&bh(n,c),f=u[c],p&&(a.dontCallGetSet?(S=jx(n,c),m=S&&S.value):m=n[c]),h=p&&m?m:e[c],!(!l&&!s&&typeof f==typeof h)&&(a.bind&&p?g=Wx(h,Yr):a.wrap&&p?g=Gx(h):s&&Hx(h)?g=Ux(h):g=h,(a.sham||h&&h.sham||f&&f.sham)&&Gi(g,"sham",!0),Gi(u,c,g),s&&(d=t+"Prototype",bh(Wi,d)||Gi(Wi,d,{}),Gi(Wi[d],c,h),a.real&&o&&(l||!o[c])&&Gi(o,c,h)))}});var Ks=b((Y0,vh)=>{"use strict";var zx=vu(),Yx=yu(),Sh=zx("keys");vh.exports=function(a){return Sh[a]||(Sh[a]=Yx(a))}});var Th=b((K0,yh)=>{"use strict";var Kx=pe();yh.exports=!Kx(function(){function a(){}return a.prototype.constructor=null,Object.getPrototypeOf(new a)!==a.prototype})});var Xs=b((X0,Eh)=>{"use strict";var Xx=it(),Jx=ae(),Zx=Ui(),ew=Ks(),tw=Th(),Ih=ew("IE_PROTO"),$u=Object,iw=$u.prototype;Eh.exports=tw?$u.getPrototypeOf:function(a){var e=Zx(a);if(Xx(e,Ih))return e[Ih];var t=e.constructor;return Jx(t)&&e instanceof t?t.prototype:e instanceof $u?iw:null}});var wh=b((J0,xh)=>{"use strict";var rw=Math.ceil,aw=Math.floor;xh.exports=Math.trunc||function(e){var t=+e;return(t>0?aw:rw)(t)}});var Kr=b((Z0,Ah)=>{"use strict";var sw=wh();Ah.exports=function(a){var e=+a;return e!==e||e===0?0:sw(e)}});var kh=b((e_,Ph)=>{"use strict";var nw=Kr(),ow=Math.max,uw=Math.min;Ph.exports=function(a,e){var t=nw(a);return t<0?ow(t+e,0):uw(t,e)}});var Mu=b((t_,Rh)=>{"use strict";var lw=Kr(),cw=Math.min;Rh.exports=function(a){var e=lw(a);return e>0?cw(e,9007199254740991):0}});var zi=b((i_,Lh)=>{"use strict";var dw=Mu();Lh.exports=function(a){return dw(a.length)}});var Du=b((r_,Mh)=>{"use strict";var pw=ui(),hw=kh(),fw=zi(),$h=function(a){return function(e,t,i){var r=pw(e),s=fw(r);if(s===0)return!a&&-1;var n=hw(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}};Mh.exports={includes:$h(!0),indexOf:$h(!1)}});var Js=b((a_,Dh)=>{"use strict";Dh.exports={}});var Vh=b((s_,Bh)=>{"use strict";var mw=he(),Cu=it(),bw=ui(),gw=Du().indexOf,Sw=Js(),Ch=mw([].push);Bh.exports=function(a,e){var t=bw(a),i=0,r=[],s;for(s in t)!Cu(Sw,s)&&Cu(t,s)&&Ch(r,s);for(;e.length>i;)Cu(t,s=e[i++])&&(~gw(r,s)||Ch(r,s));return r}});var Bu=b((n_,_h)=>{"use strict";_h.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var Vu=b((o_,Oh)=>{"use strict";var vw=Vh(),yw=Bu();Oh.exports=Object.keys||function(e){return vw(e,yw)}});var _u=b((u_,Hh)=>{"use strict";var Nh=Fe(),Tw=pe(),qh=he(),Iw=Xs(),Ew=Vu(),xw=ui(),ww=ou().f,Uh=qh(ww),Aw=qh([].push),Pw=Nh&&Tw(function(){var a=Object.create(null);return a[2]=2,!Uh(a,2)}),Fh=function(a){return function(e){for(var t=xw(e),i=Ew(t),r=Pw&&Iw(t)===null,s=i.length,n=0,u=[],o;s>n;)o=i[n++],(!Nh||(r?o in t:Uh(t,o)))&&Aw(u,a?[o,t[o]]:t[o]);return u}};Hh.exports={entries:Fh(!0),values:Fh(!1)}});var jh=b(()=>{"use strict";var kw=oe(),Rw=_u().values;kw({target:"Object",stat:!0},{values:function(e){return Rw(e)}})});var Wh=b((d_,Qh)=>{"use strict";jh();var Lw=li();Qh.exports=Lw.Object.values});var zh=b((p_,Gh)=>{"use strict";var $w=Wh();Gh.exports=$w});var pi=b((h_,Yh)=>{"use strict";var Mw=zh();Yh.exports=Mw});var Xr=b((f_,Kh)=>{"use strict";Kh.exports=function(){}});var Xh=b(()=>{"use strict";var Dw=oe(),Cw=Du().includes,Bw=pe(),Vw=Xr(),_w=Bw(function(){return!Array(1).includes()});Dw({target:"Array",proto:!0,forced:_w},{includes:function(e){return Cw(this,e,arguments.length>1?arguments[1]:void 0)}});Vw("includes")});var Nt=b((g_,Jh)=>{"use strict";var Ow=wt();Jh.exports=Ow});var ef=b((S_,Zh)=>{"use strict";Xh();var Fw=Nt();Zh.exports=Fw("Array","includes")});var rf=b((v_,tf)=>{"use strict";var Nw=ef();tf.exports=Nw});var Me=b((y_,af)=>{"use strict";var qw=rf();af.exports=qw});var df=b(()=>{"use strict";var Yw=oe(),Kw=_u().entries;Yw({target:"Object",stat:!0},{entries:function(e){return Kw(e)}})});var hf=b((C_,pf)=>{"use strict";df();var Xw=li();pf.exports=Xw.Object.entries});var mf=b((B_,ff)=>{"use strict";var Jw=hf();ff.exports=Jw});var Yi=b((V_,bf)=>{"use strict";var Zw=mf();bf.exports=Zw});var hi=b((__,gf)=>{"use strict";gf.exports={}});var yf=b((O_,vf)=>{"use strict";var eA=re(),tA=ae(),Sf=eA.WeakMap;vf.exports=tA(Sf)&&/native code/.test(String(Sf))});var Hu=b((F_,Ef)=>{"use strict";var iA=yf(),If=re(),rA=$e(),aA=Qi(),Nu=it(),qu=Gr(),sA=Ks(),nA=Js(),Tf="Object already initialized",Uu=If.TypeError,oA=If.WeakMap,tn,Jr,rn,uA=function(a){return rn(a)?Jr(a):tn(a,{})},lA=function(a){return function(e){var t;if(!rA(e)||(t=Jr(e)).type!==a)throw new Uu("Incompatible receiver, "+a+" required");return t}};iA||qu.state?(rt=qu.state||(qu.state=new oA),rt.get=rt.get,rt.has=rt.has,rt.set=rt.set,tn=function(a,e){if(rt.has(a))throw new Uu(Tf);return e.facade=a,rt.set(a,e),e},Jr=function(a){return rt.get(a)||{}},rn=function(a){return rt.has(a)}):(fi=sA("state"),nA[fi]=!0,tn=function(a,e){if(Nu(a,fi))throw new Uu(Tf);return e.facade=a,aA(a,fi,e),e},Jr=function(a){return Nu(a,fi)?a[fi]:{}},rn=function(a){return Nu(a,fi)});var rt,fi;Ef.exports={set:tn,get:Jr,has:rn,enforce:uA,getterFor:lA}});var Wu=b((N_,wf)=>{"use strict";var ju=Fe(),cA=it(),xf=Function.prototype,dA=ju&&Object.getOwnPropertyDescriptor,Qu=cA(xf,"name"),pA=Qu&&function(){}.name==="something",hA=Qu&&(!ju||ju&&dA(xf,"name").configurable);wf.exports={EXISTS:Qu,PROPER:pA,CONFIGURABLE:hA}});var Pf=b(Af=>{"use strict";var fA=Fe(),mA=Au(),bA=di(),gA=ft(),SA=ui(),vA=Vu();Af.f=fA&&!mA?Object.defineProperties:function(e,t){gA(e);for(var i=SA(t),r=vA(t),s=r.length,n=0,u;s>n;)bA.f(e,u=r[n++],i[u]);return e}});var Gu=b((U_,kf)=>{"use strict";var yA=wt();kf.exports=yA("document","documentElement")});var Xu=b((H_,Bf)=>{"use strict";var TA=ft(),IA=Pf(),Rf=Bu(),EA=Js(),xA=Gu(),wA=zs(),AA=Ks(),Lf=">",$f="<",Yu="prototype",Ku="script",Df=AA("IE_PROTO"),zu=function(){},Cf=function(a){return $f+Ku+Lf+a+$f+"/"+Ku+Lf},Mf=function(a){a.write(Cf("")),a.close();var e=a.parentWindow.Object;return a=null,e},PA=function(){var a=wA("iframe"),e="java"+Ku+":",t;return a.style.display="none",xA.appendChild(a),a.src=String(e),t=a.contentWindow.document,t.open(),t.write(Cf("document.F=Object")),t.close(),t.F},an,sn=function(){try{an=new ActiveXObject("htmlfile")}catch{}sn=typeof document<"u"?document.domain&&an?Mf(an):PA():Mf(an);for(var a=Rf.length;a--;)delete sn[Yu][Rf[a]];return sn()};EA[Df]=!0;Bf.exports=Object.create||function(e,t){var i;return e!==null?(zu[Yu]=TA(e),i=new zu,zu[Yu]=null,i[Df]=e):i=sn(),t===void 0?i:IA.f(i,t)}});var Ki=b((j_,Vf)=>{"use strict";var kA=Qi();Vf.exports=function(a,e,t,i){return i&&i.enumerable?a[e]=t:kA(a,e,t),a}});var tl=b((Q_,Ff)=>{"use strict";var RA=pe(),LA=ae(),$A=$e(),MA=Xu(),_f=Xs(),DA=Ki(),CA=ge(),BA=tt(),el=CA("iterator"),Of=!1,At,Ju,Zu;[].keys&&(Zu=[].keys(),"next"in Zu?(Ju=_f(_f(Zu)),Ju!==Object.prototype&&(At=Ju)):Of=!0);var VA=!$A(At)||RA(function(){var a={};return At[el].call(a)!==a});VA?At={}:BA&&(At=MA(At));LA(At[el])||DA(At,el,function(){return this});Ff.exports={IteratorPrototype:At,BUGGY_SAFARI_ITERATORS:Of}});var nn=b((W_,qf)=>{"use strict";var _A=ge(),OA=_A("toStringTag"),Nf={};Nf[OA]="z";qf.exports=String(Nf)==="[object z]"});var Zr=b((G_,Uf)=>{"use strict";var FA=nn(),NA=ae(),on=oi(),qA=ge(),UA=qA("toStringTag"),HA=Object,jA=on(function(){return arguments}())==="Arguments",QA=function(a,e){try{return a[e]}catch{}};Uf.exports=FA?on:function(a){var e,t,i;return a===void 0?"Undefined":a===null?"Null":typeof(t=QA(e=HA(a),UA))=="string"?t:jA?on(e):(i=on(e))==="Object"&&NA(e.callee)?"Arguments":i}});var jf=b((z_,Hf)=>{"use strict";var WA=nn(),GA=Zr();Hf.exports=WA?{}.toString:function(){return"[object "+GA(this)+"]"}});var ea=b((Y_,Wf)=>{"use strict";var zA=nn(),YA=di().f,KA=Qi(),XA=it(),JA=jf(),ZA=ge(),Qf=ZA("toStringTag");Wf.exports=function(a,e,t,i){var r=t?a:a&&a.prototype;r&&(XA(r,Qf)||YA(r,Qf,{configurable:!0,value:e}),i&&!zA&&KA(r,"toString",JA))}});var zf=b((K_,Gf)=>{"use strict";var eP=tl().IteratorPrototype,tP=Xu(),iP=Ur(),rP=ea(),aP=hi(),sP=function(){return this};Gf.exports=function(a,e,t,i){var r=e+" Iterator";return a.prototype=tP(eP,{next:iP(+!i,t)}),rP(a,r,!1,!0),aP[r]=sP,a}});var Kf=b((X_,Yf)=>{"use strict";var nP=he(),oP=ht();Yf.exports=function(a,e,t){try{return nP(oP(Object.getOwnPropertyDescriptor(a,e)[t]))}catch{}}});var Jf=b((J_,Xf)=>{"use strict";var uP=$e();Xf.exports=function(a){return uP(a)||a===null}});var em=b((Z_,Zf)=>{"use strict";var lP=Jf(),cP=String,dP=TypeError;Zf.exports=function(a){if(lP(a))return a;throw new dP("Can't set "+cP(a)+" as a prototype")}});var il=b((eO,tm)=>{"use strict";var pP=Kf(),hP=$e(),fP=Ft(),mP=em();tm.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var a=!1,e={},t;try{t=pP(Object.prototype,"__proto__","set"),t(e,[]),a=e instanceof Array}catch{}return function(r,s){return fP(r),mP(s),hP(r)&&(a?t(r,s):r.__proto__=s),r}}():void 0)});var pm=b((tO,dm)=>{"use strict";var bP=oe(),gP=Ne(),un=tt(),lm=Wu(),SP=ae(),vP=zf(),im=Xs(),rm=il(),yP=ea(),TP=Qi(),rl=Ki(),IP=ge(),am=hi(),cm=tl(),EP=lm.PROPER,xP=lm.CONFIGURABLE,sm=cm.IteratorPrototype,ln=cm.BUGGY_SAFARI_ITERATORS,ta=IP("iterator"),nm="keys",ia="values",om="entries",um=function(){return this};dm.exports=function(a,e,t,i,r,s,n){vP(t,e,i);var u=function(S){if(S===r&&c)return c;if(!ln&&S&&S in p)return p[S];switch(S){case nm:return function(){return new t(this,S)};case ia:return function(){return new t(this,S)};case om:return function(){return new t(this,S)}}return function(){return new t(this)}},o=e+" Iterator",l=!1,p=a.prototype,d=p[ta]||p["@@iterator"]||r&&p[r],c=!ln&&d||u(r),h=e==="Array"&&p.entries||d,f,m,g;if(h&&(f=im(h.call(new a)),f!==Object.prototype&&f.next&&(!un&&im(f)!==sm&&(rm?rm(f,sm):SP(f[ta])||rl(f,ta,um)),yP(f,o,!0,!0),un&&(am[o]=um))),EP&&r===ia&&d&&d.name!==ia&&(!un&&xP?TP(p,"name",ia):(l=!0,c=function(){return gP(d,this)})),r)if(m={values:u(ia),keys:s?c:u(nm),entries:u(om)},n)for(g in m)(ln||l||!(g in p))&&rl(p,g,m[g]);else bP({target:e,proto:!0,forced:ln||l},m);return(!un||n)&&p[ta]!==c&&rl(p,ta,c,{name:r}),am[e]=c,m}});var fm=b((iO,hm)=>{"use strict";hm.exports=function(a,e){return{value:a,done:e}}});var sl=b((rO,vm)=>{"use strict";var wP=ui(),al=Xr(),mm=hi(),gm=Hu(),AP=di().f,PP=pm(),cn=fm(),kP=tt(),RP=Fe(),Sm="Array Iterator",LP=gm.set,$P=gm.getterFor(Sm);vm.exports=PP(Array,"Array",function(a,e){LP(this,{type:Sm,target:wP(a),index:0,kind:e})},function(){var a=$P(this),e=a.target,t=a.index++;if(!e||t>=e.length)return a.target=null,cn(void 0,!0);switch(a.kind){case"keys":return cn(t,!1);case"values":return cn(e[t],!1)}return cn([t,e[t]],!1)},"values");var bm=mm.Arguments=mm.Array;al("keys");al("values");al("entries");if(!kP&&RP&&bm.name!=="values")try{AP(bm,"name",{value:"values"})}catch{}});var Tm=b((aO,ym)=>{"use strict";var MP=ge(),DP=hi(),CP=MP("iterator"),BP=Array.prototype;ym.exports=function(a){return a!==void 0&&(DP.Array===a||BP[CP]===a)}});var nl=b((sO,Em)=>{"use strict";var VP=Zr(),Im=Wr(),_P=Hr(),OP=hi(),FP=ge(),NP=FP("iterator");Em.exports=function(a){if(!_P(a))return Im(a,NP)||Im(a,"@@iterator")||OP[VP(a)]}});var wm=b((nO,xm)=>{"use strict";var qP=Ne(),UP=ht(),HP=ft(),jP=Qr(),QP=nl(),WP=TypeError;xm.exports=function(a,e){var t=arguments.length<2?QP(a):e;if(UP(t))return HP(qP(t,a));throw new WP(jP(a)+" is not iterable")}});var km=b((oO,Pm)=>{"use strict";var GP=Ne(),Am=ft(),zP=Wr();Pm.exports=function(a,e,t){var i,r;Am(a);try{if(i=zP(a,"return"),!i){if(e==="throw")throw t;return t}i=GP(i,a)}catch(s){r=!0,i=s}if(e==="throw")throw t;if(r)throw i;return Am(i),t}});var pn=b((uO,Mm)=>{"use strict";var YP=ji(),KP=Ne(),XP=ft(),JP=Qr(),ZP=Tm(),ek=zi(),Rm=jr(),tk=wm(),ik=nl(),Lm=km(),rk=TypeError,dn=function(a,e){this.stopped=a,this.result=e},$m=dn.prototype;Mm.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=YP(e,i),l,p,d,c,h,f,m,g=function(v){return l&&Lm(l,"normal"),new dn(!0,v)},S=function(v){return r?(XP(v),u?o(v[0],v[1],g):o(v[0],v[1])):u?o(v,g):o(v)};if(s)l=a.iterator;else if(n)l=a;else{if(p=ik(a),!p)throw new rk(JP(a)+" is not iterable");if(ZP(p)){for(d=0,c=ek(a);c>d;d++)if(h=S(a[d]),h&&Rm($m,h))return h;return new dn(!1)}l=tk(a,p)}for(f=s?a.next:l.next;!(m=KP(f,l)).done;){try{h=S(m.value)}catch(v){Lm(l,"throw",v)}if(typeof h=="object"&&h&&Rm($m,h))return h}return new dn(!1)}});var Cm=b((lO,Dm)=>{"use strict";var ak=Fe(),sk=di(),nk=Ur();Dm.exports=function(a,e,t){ak?sk.f(a,e,nk(0,t)):a[e]=t}});var Bm=b(()=>{"use strict";var ok=oe(),uk=pn(),lk=Cm();ok({target:"Object",stat:!0},{fromEntries:function(e){var t={};return uk(e,function(i,r){lk(t,i,r)},{AS_ENTRIES:!0}),t}})});var _m=b((pO,Vm)=>{"use strict";sl();Bm();var ck=li();Vm.exports=ck.Object.fromEntries});var Fm=b((hO,Om)=>{"use strict";Om.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 qm=b(()=>{"use strict";sl();var dk=Fm(),pk=re(),hk=ea(),Nm=hi();for(hn in dk)hk(pk[hn],hn),Nm[hn]=Nm.Array;var hn});var Hm=b((bO,Um)=>{"use strict";var fk=_m();qm();Um.exports=fk});var ol=b((gO,jm)=>{"use strict";var mk=Hm();jm.exports=mk});var Qm=b(()=>{"use strict"});var ul=b((yO,Wm)=>{"use strict";var ra=re(),bk=ci(),gk=oi(),fn=function(a){return bk.slice(0,a.length)===a};Wm.exports=function(){return fn("Bun/")?"BUN":fn("Cloudflare-Workers")?"CLOUDFLARE":fn("Deno/")?"DENO":fn("Node.js/")?"NODE":ra.Bun&&typeof Bun.version=="string"?"BUN":ra.Deno&&typeof Deno.version=="object"?"DENO":gk(ra.process)==="process"?"NODE":ra.window&&ra.document?"BROWSER":"REST"}()});var mn=b((TO,Gm)=>{"use strict";var Sk=ul();Gm.exports=Sk==="NODE"});var Ym=b((IO,zm)=>{"use strict";var vk=di();zm.exports=function(a,e,t){return vk.f(a,e,t)}});var Jm=b((EO,Xm)=>{"use strict";var yk=wt(),Tk=Ym(),Ik=ge(),Ek=Fe(),Km=Ik("species");Xm.exports=function(a){var e=yk(a);Ek&&e&&!e[Km]&&Tk(e,Km,{configurable:!0,get:function(){return this}})}});var eb=b((xO,Zm)=>{"use strict";var xk=jr(),wk=TypeError;Zm.exports=function(a,e){if(xk(e,a))return a;throw new wk("Incorrect invocation")}});var cl=b((wO,tb)=>{"use strict";var Ak=he(),Pk=ae(),ll=Gr(),kk=Ak(Function.toString);Pk(ll.inspectSource)||(ll.inspectSource=function(a){return kk(a)});tb.exports=ll.inspectSource});var pl=b((AO,nb)=>{"use strict";var Rk=he(),Lk=pe(),ib=ae(),$k=Zr(),Mk=wt(),Dk=cl(),rb=function(){},ab=Mk("Reflect","construct"),dl=/^\s*(?:class|function)\b/,Ck=Rk(dl.exec),Bk=!dl.test(rb),aa=function(e){if(!ib(e))return!1;try{return ab(rb,[],e),!0}catch{return!1}},sb=function(e){if(!ib(e))return!1;switch($k(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return Bk||!!Ck(dl,Dk(e))}catch{return!0}};sb.sham=!0;nb.exports=!ab||Lk(function(){var a;return aa(aa.call)||!aa(Object)||!aa(function(){a=!0})||a})?sb:aa});var ub=b((PO,ob)=>{"use strict";var Vk=pl(),_k=Qr(),Ok=TypeError;ob.exports=function(a){if(Vk(a))return a;throw new Ok(_k(a)+" is not a constructor")}});var hl=b((kO,cb)=>{"use strict";var lb=ft(),Fk=ub(),Nk=Hr(),qk=ge(),Uk=qk("species");cb.exports=function(a,e){var t=lb(a).constructor,i;return t===void 0||Nk(i=lb(t)[Uk])?e:Fk(i)}});var pb=b((RO,db)=>{"use strict";var Hk=he();db.exports=Hk([].slice)});var fb=b((LO,hb)=>{"use strict";var jk=TypeError;hb.exports=function(a,e){if(a<e)throw new jk("Not enough arguments");return a}});var fl=b(($O,mb)=>{"use strict";var Qk=ci();mb.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(Qk)});var El=b((MO,xb)=>{"use strict";var qe=re(),Wk=ru(),Gk=ji(),bb=ae(),zk=it(),Eb=pe(),gb=Gu(),Yk=pb(),Sb=zs(),Kk=fb(),Xk=fl(),Jk=mn(),yl=qe.setImmediate,Tl=qe.clearImmediate,Zk=qe.process,ml=qe.Dispatch,eR=qe.Function,vb=qe.MessageChannel,tR=qe.String,bl=0,sa={},yb="onreadystatechange",na,mi,gl,Sl;Eb(function(){na=qe.location});var Il=function(a){if(zk(sa,a)){var e=sa[a];delete sa[a],e()}},vl=function(a){return function(){Il(a)}},Tb=function(a){Il(a.data)},Ib=function(a){qe.postMessage(tR(a),na.protocol+"//"+na.host)};(!yl||!Tl)&&(yl=function(e){Kk(arguments.length,1);var t=bb(e)?e:eR(e),i=Yk(arguments,1);return sa[++bl]=function(){Wk(t,void 0,i)},mi(bl),bl},Tl=function(e){delete sa[e]},Jk?mi=function(a){Zk.nextTick(vl(a))}:ml&&ml.now?mi=function(a){ml.now(vl(a))}:vb&&!Xk?(gl=new vb,Sl=gl.port2,gl.port1.onmessage=Tb,mi=Gk(Sl.postMessage,Sl)):qe.addEventListener&&bb(qe.postMessage)&&!qe.importScripts&&na&&na.protocol!=="file:"&&!Eb(Ib)?(mi=Ib,qe.addEventListener("message",Tb,!1)):yb in Sb("script")?mi=function(a){gb.appendChild(Sb("script"))[yb]=function(){gb.removeChild(this),Il(a)}}:mi=function(a){setTimeout(vl(a),0)});xb.exports={set:yl,clear:Tl}});var Pb=b((DO,Ab)=>{"use strict";var wb=re(),iR=Fe(),rR=Object.getOwnPropertyDescriptor;Ab.exports=function(a){if(!iR)return wb[a];var e=rR(wb,a);return e&&e.value}});var xl=b((CO,Rb)=>{"use strict";var kb=function(){this.head=null,this.tail=null};kb.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}}};Rb.exports=kb});var $b=b((BO,Lb)=>{"use strict";var aR=ci();Lb.exports=/ipad|iphone|ipod/i.test(aR)&&typeof Pebble<"u"});var Db=b((VO,Mb)=>{"use strict";var sR=ci();Mb.exports=/web0s(?!.*chrome)/i.test(sR)});var Nb=b((_O,Fb)=>{"use strict";var Ji=re(),nR=Pb(),Cb=ji(),wl=El().set,oR=xl(),uR=fl(),lR=$b(),cR=Db(),Al=mn(),Bb=Ji.MutationObserver||Ji.WebKitMutationObserver,Vb=Ji.document,_b=Ji.process,bn=Ji.Promise,Rl=nR("queueMicrotask"),Xi,Pl,kl,gn,Ob;Rl||(oa=new oR,ua=function(){var a,e;for(Al&&(a=_b.domain)&&a.exit();e=oa.get();)try{e()}catch(t){throw oa.head&&Xi(),t}a&&a.enter()},!uR&&!Al&&!cR&&Bb&&Vb?(Pl=!0,kl=Vb.createTextNode(""),new Bb(ua).observe(kl,{characterData:!0}),Xi=function(){kl.data=Pl=!Pl}):!lR&&bn&&bn.resolve?(gn=bn.resolve(void 0),gn.constructor=bn,Ob=Cb(gn.then,gn),Xi=function(){Ob(ua)}):Al?Xi=function(){_b.nextTick(ua)}:(wl=Cb(wl,Ji),Xi=function(){wl(ua)}),Rl=function(a){oa.head||Xi(),oa.add(a)});var oa,ua;Fb.exports=Rl});var Ub=b((OO,qb)=>{"use strict";qb.exports=function(a,e){try{arguments.length===1?console.error(a):console.error(a,e)}catch{}}});var Sn=b((FO,Hb)=>{"use strict";Hb.exports=function(a){try{return{error:!1,value:a()}}catch(e){return{error:!0,value:e}}}});var bi=b((NO,jb)=>{"use strict";var dR=re();jb.exports=dR.Promise});var Zi=b((qO,zb)=>{"use strict";var pR=re(),la=bi(),hR=ae(),fR=wu(),mR=cl(),bR=ge(),Qb=ul(),gR=tt(),Ll=pu(),Wb=la&&la.prototype,SR=bR("species"),$l=!1,Gb=hR(pR.PromiseRejectionEvent),vR=fR("Promise",function(){var a=mR(la),e=a!==String(la);if(!e&&Ll===66||gR&&!(Wb.catch&&Wb.finally))return!0;if(!Ll||Ll<51||!/native code/.test(a)){var t=new la(function(s){s(1)}),i=function(s){s(function(){},function(){})},r=t.constructor={};if(r[SR]=i,$l=t.then(function(){})instanceof i,!$l)return!0}return!e&&(Qb==="BROWSER"||Qb==="DENO")&&!Gb});zb.exports={CONSTRUCTOR:vR,REJECTION_EVENT:Gb,SUBCLASSING:$l}});var er=b((UO,Kb)=>{"use strict";var Yb=ht(),yR=TypeError,TR=function(a){var e,t;this.promise=new a(function(i,r){if(e!==void 0||t!==void 0)throw new yR("Bad Promise constructor");e=i,t=r}),this.resolve=Yb(e),this.reject=Yb(t)};Kb.exports.f=function(a){return new TR(a)}});var bg=b(()=>{"use strict";var IR=oe(),ER=tt(),In=mn(),qt=re(),xR=li(),ar=Ne(),Xb=Ki(),Jb=il(),wR=ea(),AR=Jm(),PR=ht(),Tn=ae(),kR=$e(),RR=eb(),LR=hl(),rg=El().set,Vl=Nb(),$R=Ub(),MR=Sn(),DR=xl(),ag=Hu(),En=bi(),_l=Zi(),sg=er(),xn="Promise",ng=_l.CONSTRUCTOR,CR=_l.REJECTION_EVENT,BR=_l.SUBCLASSING,Ml=ag.getterFor(xn),VR=ag.set,tr=En&&En.prototype,gi=En,vn=tr,og=qt.TypeError,Dl=qt.document,Ol=qt.process,Cl=sg.f,_R=Cl,OR=!!(Dl&&Dl.createEvent&&qt.dispatchEvent),ug="unhandledrejection",FR="rejectionhandled",Zb=0,lg=1,NR=2,Fl=1,cg=2,yn,eg,dg,tg,pg=function(a){var e;return kR(a)&&Tn(e=a.then)?e:!1},hg=function(a,e){var t=e.value,i=e.state===lg,r=i?a.ok:a.fail,s=a.resolve,n=a.reject,u=a.domain,o,l,p;try{r?(i||(e.rejection===cg&&UR(e),e.rejection=Fl),r===!0?o=t:(u&&u.enter(),o=r(t),u&&(u.exit(),p=!0)),o===a.promise?n(new og("Promise-chain cycle")):(l=pg(o))?ar(l,o,s,n):s(o)):n(t)}catch(d){u&&!p&&u.exit(),n(d)}},fg=function(a,e){a.notified||(a.notified=!0,Vl(function(){for(var t=a.reactions,i;i=t.get();)hg(i,a);a.notified=!1,e&&!a.rejection&&qR(a)}))},mg=function(a,e,t){var i,r;OR?(i=Dl.createEvent("Event"),i.promise=e,i.reason=t,i.initEvent(a,!1,!0),qt.dispatchEvent(i)):i={promise:e,reason:t},!CR&&(r=qt["on"+a])?r(i):a===ug&&$R("Unhandled promise rejection",t)},qR=function(a){ar(rg,qt,function(){var e=a.facade,t=a.value,i=ig(a),r;if(i&&(r=MR(function(){In?Ol.emit("unhandledRejection",t,e):mg(ug,e,t)}),a.rejection=In||ig(a)?cg:Fl,r.error))throw r.value})},ig=function(a){return a.rejection!==Fl&&!a.parent},UR=function(a){ar(rg,qt,function(){var e=a.facade;In?Ol.emit("rejectionHandled",e):mg(FR,e,a.value)})},ir=function(a,e,t){return function(i){a(e,i,t)}},rr=function(a,e,t){a.done||(a.done=!0,t&&(a=t),a.value=e,a.state=NR,fg(a,!0))},Bl=function(a,e,t){if(!a.done){a.done=!0,t&&(a=t);try{if(a.facade===e)throw new og("Promise can't be resolved itself");var i=pg(e);i?Vl(function(){var r={done:!1};try{ar(i,e,ir(Bl,r,a),ir(rr,r,a))}catch(s){rr(r,s,a)}}):(a.value=e,a.state=lg,fg(a,!1))}catch(r){rr({done:!1},r,a)}}};if(ng&&(gi=function(e){RR(this,vn),PR(e),ar(yn,this);var t=Ml(this);try{e(ir(Bl,t),ir(rr,t))}catch(i){rr(t,i)}},vn=gi.prototype,yn=function(e){VR(this,{type:xn,done:!1,notified:!1,parent:!1,reactions:new DR,rejection:!1,state:Zb,value:null})},yn.prototype=Xb(vn,"then",function(e,t){var i=Ml(this),r=Cl(LR(this,gi));return i.parent=!0,r.ok=Tn(e)?e:!0,r.fail=Tn(t)&&t,r.domain=In?Ol.domain:void 0,i.state===Zb?i.reactions.add(r):Vl(function(){hg(r,i)}),r.promise}),eg=function(){var a=new yn,e=Ml(a);this.promise=a,this.resolve=ir(Bl,e),this.reject=ir(rr,e)},sg.f=Cl=function(a){return a===gi||a===dg?new eg(a):_R(a)},!ER&&Tn(En)&&tr!==Object.prototype)){tg=tr.then,BR||Xb(tr,"then",function(e,t){var i=this;return new gi(function(r,s){ar(tg,i,r,s)}).then(e,t)},{unsafe:!0});try{delete tr.constructor}catch{}Jb&&Jb(tr,vn)}IR({global:!0,constructor:!0,wrap:!0,forced:ng},{Promise:gi});dg=xR.Promise;wR(gi,xn,!1,!0);AR(xn)});var Tg=b((QO,yg)=>{"use strict";var HR=ge(),Sg=HR("iterator"),vg=!1;try{gg=0,Nl={next:function(){return{done:!!gg++}},return:function(){vg=!0}},Nl[Sg]=function(){return this},Array.from(Nl,function(){throw 2})}catch{}var gg,Nl;yg.exports=function(a,e){try{if(!e&&!vg)return!1}catch{return!1}var t=!1;try{var i={};i[Sg]=function(){return{next:function(){return{done:t=!0}}}},a(i)}catch{}return t}});var ql=b((WO,Ig)=>{"use strict";var jR=bi(),QR=Tg(),WR=Zi().CONSTRUCTOR;Ig.exports=WR||!QR(function(a){jR.all(a).then(void 0,function(){})})});var Eg=b(()=>{"use strict";var GR=oe(),zR=Ne(),YR=ht(),KR=er(),XR=Sn(),JR=pn(),ZR=ql();GR({target:"Promise",stat:!0,forced:ZR},{all:function(e){var t=this,i=KR.f(t),r=i.resolve,s=i.reject,n=XR(function(){var u=YR(t.resolve),o=[],l=0,p=1;JR(e,function(d){var c=l++,h=!1;p++,zR(u,t,d).then(function(f){h||(h=!0,o[c]=f,--p||r(o))},s)}),--p||r(o)});return n.error&&s(n.value),i.promise}})});var wg=b(()=>{"use strict";var eL=oe(),tL=tt(),iL=Zi().CONSTRUCTOR,Hl=bi(),rL=wt(),aL=ae(),sL=Ki(),xg=Hl&&Hl.prototype;eL({target:"Promise",proto:!0,forced:iL,real:!0},{catch:function(a){return this.then(void 0,a)}});!tL&&aL(Hl)&&(Ul=rL("Promise").prototype.catch,xg.catch!==Ul&&sL(xg,"catch",Ul,{unsafe:!0}));var Ul});var Ag=b(()=>{"use strict";var nL=oe(),oL=Ne(),uL=ht(),lL=er(),cL=Sn(),dL=pn(),pL=ql();nL({target:"Promise",stat:!0,forced:pL},{race:function(e){var t=this,i=lL.f(t),r=i.reject,s=cL(function(){var n=uL(t.resolve);dL(e,function(u){oL(n,t,u).then(i.resolve,r)})});return s.error&&r(s.value),i.promise}})});var Pg=b(()=>{"use strict";var hL=oe(),fL=er(),mL=Zi().CONSTRUCTOR;hL({target:"Promise",stat:!0,forced:mL},{reject:function(e){var t=fL.f(this),i=t.reject;return i(e),t.promise}})});var jl=b((tF,kg)=>{"use strict";var bL=ft(),gL=$e(),SL=er();kg.exports=function(a,e){if(bL(a),gL(e)&&e.constructor===a)return e;var t=SL.f(a),i=t.resolve;return i(e),t.promise}});var $g=b(()=>{"use strict";var vL=oe(),yL=wt(),Rg=tt(),TL=bi(),Lg=Zi().CONSTRUCTOR,IL=jl(),EL=yL("Promise"),xL=Rg&&!Lg;vL({target:"Promise",stat:!0,forced:Rg||Lg},{resolve:function(e){return IL(xL&&this===EL?TL:this,e)}})});var Mg=b(()=>{"use strict";bg();Eg();wg();Ag();Pg();$g()});var Vg=b(()=>{"use strict";var wL=oe(),AL=tt(),wn=bi(),PL=pe(),Cg=wt(),Bg=ae(),kL=hl(),Dg=jl(),RL=Ki(),Wl=wn&&wn.prototype,LL=!!wn&&PL(function(){Wl.finally.call({then:function(){}},function(){})});wL({target:"Promise",proto:!0,real:!0,forced:LL},{finally:function(a){var e=kL(this,Cg("Promise")),t=Bg(a);return this.then(t?function(i){return Dg(e,a()).then(function(){return i})}:a,t?function(i){return Dg(e,a()).then(function(){throw i})}:a)}});!AL&&Bg(wn)&&(Ql=Cg("Promise").prototype.finally,Wl.finally!==Ql&&RL(Wl,"finally",Ql,{unsafe:!0}));var Ql});var Og=b((uF,_g)=>{"use strict";Qm();Mg();Vg();var $L=Nt();_g.exports=$L("Promise","finally")});var Ng=b((lF,Fg)=>{"use strict";var ML=Og();Fg.exports=ML});var An=b((cF,qg)=>{"use strict";var DL=Ng();qg.exports=DL});var bS=b(()=>{"use strict";var m$=oe(),b$=Ui(),g$=zi(),S$=Kr(),v$=Xr();m$({target:"Array",proto:!0},{at:function(e){var t=b$(this),i=g$(t),r=S$(e),s=r>=0?r:i+r;return s<0||s>=i?void 0:t[s]}});v$("at")});var SS=b((tq,gS)=>{"use strict";bS();var y$=Nt();gS.exports=y$("Array","at")});var yS=b((iq,vS)=>{"use strict";var T$=SS();vS.exports=T$});var at=b((rq,TS)=>{"use strict";var I$=yS();TS.exports=I$});var bc=b((zU,rv)=>{"use strict";var iM=oi();rv.exports=Array.isArray||function(e){return iM(e)==="Array"}});var sv=b((YU,av)=>{"use strict";var rM=TypeError,aM=9007199254740991;av.exports=function(a){if(a>aM)throw rM("Maximum allowed index exceeded");return a}});var uv=b((KU,ov)=>{"use strict";var sM=bc(),nM=zi(),oM=sv(),uM=ji(),nv=function(a,e,t,i,r,s,n,u){for(var o=r,l=0,p=n?uM(n,u):!1,d,c;l<i;)l in t&&(d=p?p(t[l],l,e):t[l],s>0&&sM(d)?(c=nM(d),o=nv(a,e,d,c,o,s-1)-1):(oM(o+1),a[o]=d),o++),l++;return o};ov.exports=nv});var pv=b((XU,dv)=>{"use strict";var lv=bc(),lM=pl(),cM=$e(),dM=ge(),pM=dM("species"),cv=Array;dv.exports=function(a){var e;return lv(a)&&(e=a.constructor,lM(e)&&(e===cv||lv(e.prototype))?e=void 0:cM(e)&&(e=e[pM],e===null&&(e=void 0))),e===void 0?cv:e}});var fv=b((JU,hv)=>{"use strict";var hM=pv();hv.exports=function(a,e){return new(hM(a))(e===0?0:e)}});var mv=b(()=>{"use strict";var fM=oe(),mM=uv(),bM=ht(),gM=Ui(),SM=zi(),vM=fv();fM({target:"Array",proto:!0},{flatMap:function(e){var t=gM(this),i=SM(t),r;return bM(e),r=vM(t,0),r.length=mM(r,t,t,i,0,1,e,arguments.length>1?arguments[1]:void 0),r}})});var bv=b(()=>{"use strict";var yM=Xr();yM("flatMap")});var Sv=b((r1,gv)=>{"use strict";mv();bv();var TM=Nt();gv.exports=TM("Array","flatMap")});var yv=b((a1,vv)=>{"use strict";var IM=Sv();vv.exports=IM});var wa=b((s1,Tv)=>{"use strict";var EM=yv();Tv.exports=EM});var Aa=b((n1,Iv)=>{"use strict";var xM=Zr(),wM=String;Iv.exports=function(a){if(xM(a)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return wM(a)}});var gc=b((o1,Ev)=>{"use strict";Ev.exports=`
7
- \v\f\r \xA0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028\u2029\uFEFF`});var Av=b((u1,wv)=>{"use strict";var AM=he(),PM=Ft(),kM=Aa(),vc=gc(),xv=AM("".replace),RM=RegExp("^["+vc+"]+"),LM=RegExp("(^|[^"+vc+"])["+vc+"]+$"),Sc=function(a){return function(e){var t=kM(PM(e));return a&1&&(t=xv(t,RM,"")),a&2&&(t=xv(t,LM,"$1")),t}};wv.exports={start:Sc(1),end:Sc(2),trim:Sc(3)}});var Lv=b((l1,Rv)=>{"use strict";var $M=Wu().PROPER,MM=pe(),Pv=gc(),kv="\u200B\x85\u180E";Rv.exports=function(a){return MM(function(){return!!Pv[a]()||kv[a]()!==kv||$M&&Pv[a].name!==a})}});var yc=b((c1,$v)=>{"use strict";var DM=Av().start,CM=Lv();$v.exports=CM("trimStart")?function(){return DM(this)}:"".trimStart});var Dv=b(()=>{"use strict";var BM=oe(),Mv=yc();BM({target:"String",proto:!0,name:"trimStart",forced:"".trimLeft!==Mv},{trimLeft:Mv})});var Bv=b(()=>{"use strict";Dv();var VM=oe(),Cv=yc();VM({target:"String",proto:!0,name:"trimStart",forced:"".trimStart!==Cv},{trimStart:Cv})});var _v=b((m1,Vv)=>{"use strict";Bv();var _M=Nt();Vv.exports=_M("String","trimLeft")});var Fv=b((b1,Ov)=>{"use strict";var OM=_v();Ov.exports=OM});var qv=b((g1,Nv)=>{"use strict";var FM=Fv();Nv.exports=FM});var ry=b(()=>{"use strict"});var ay=b(()=>{"use strict"});var ny=b((rQ,sy)=>{"use strict";var lD=$e(),cD=oi(),dD=ge(),pD=dD("match");sy.exports=function(a){var e;return lD(a)&&((e=a[pD])!==void 0?!!e:cD(a)==="RegExp")}});var ly=b((aQ,uy)=>{"use strict";var hD=re(),fD=pe(),oy=hD.RegExp,mD=!fD(function(){var a=!0;try{oy(".","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(oy.prototype,"flags").get.call(e);return u!==i||t!==i});uy.exports={correct:mD}});var dy=b((sQ,cy)=>{"use strict";var bD=ft();cy.exports=function(){var a=bD(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 fy=b((nQ,hy)=>{"use strict";var gD=Ne(),SD=it(),vD=jr(),py=ly(),yD=dy(),TD=RegExp.prototype;hy.exports=py.correct?function(a){return a.flags}:function(a){return!py.correct&&vD(TD,a)&&!SD(a,"flags")?gD(yD,a):a.flags}});var by=b((oQ,my)=>{"use strict";var wc=he(),ID=Ui(),ED=Math.floor,Ec=wc("".charAt),xD=wc("".replace),xc=wc("".slice),wD=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,AD=/\$([$&'`]|\d{1,2})/g;my.exports=function(a,e,t,i,r,s){var n=t+a.length,u=i.length,o=AD;return r!==void 0&&(r=ID(r),o=wD),xD(s,o,function(l,p){var d;switch(Ec(p,0)){case"$":return"$";case"&":return a;case"`":return xc(e,0,t);case"'":return xc(e,n);case"<":d=r[xc(p,1,-1)];break;default:var c=+p;if(c===0)return l;if(c>u){var h=ED(c/10);return h===0?l:h<=u?i[h-1]===void 0?Ec(p,1):i[h-1]+Ec(p,1):l}d=i[c-1]}return d===void 0?"":d})}});var vy=b(()=>{"use strict";var PD=oe(),kD=Ne(),Pc=he(),gy=Ft(),RD=ae(),LD=$e(),$D=ny(),gr=Aa(),MD=Wr(),DD=fy(),CD=by(),BD=ge(),VD=tt(),_D=BD("replace"),OD=TypeError,Ac=Pc("".indexOf),FD=Pc("".replace),Sy=Pc("".slice),ND=Math.max;PD({target:"String",proto:!0},{replaceAll:function(e,t){var i=gy(this),r,s,n,u,o,l,p,d,c,h,f=0,m="";if(LD(e)){if(r=$D(e),r&&(s=gr(gy(DD(e))),!~Ac(s,"g")))throw new OD("`.replaceAll` does not allow non-global regexes");if(n=MD(e,_D),n)return kD(n,e,i,t);if(VD&&r)return FD(gr(i),e,t)}for(u=gr(i),o=gr(e),l=RD(t),l||(t=gr(t)),p=o.length,d=ND(1,p),c=Ac(u,o);c!==-1;)h=l?gr(t(o,c,u)):CD(o,u,c,[],void 0,t),m+=Sy(u,f,c)+h,f=c+p,c=c+d>u.length?-1:Ac(u,o,c+d);return f<u.length&&(m+=Sy(u,f)),m}})});var Ty=b((cQ,yy)=>{"use strict";ry();ay();vy();var qD=Nt();yy.exports=qD("String","replaceAll")});var Ey=b((dQ,Iy)=>{"use strict";var UD=Ty();Iy.exports=UD});var wy=b((pQ,xy)=>{"use strict";var HD=Ey();xy.exports=HD});var Py=b((hQ,Ay)=>{"use strict";var jD=Kr(),QD=Aa(),WD=Ft(),GD=RangeError;Ay.exports=function(e){var t=QD(WD(this)),i="",r=jD(e);if(r<0||r===1/0)throw new GD("Wrong number of repetitions");for(;r>0;(r>>>=1)&&(t+=t))r&1&&(i+=t);return i}});var My=b((fQ,$y)=>{"use strict";var Ly=he(),zD=Mu(),ky=Aa(),YD=Py(),KD=Ft(),XD=Ly(YD),JD=Ly("".slice),ZD=Math.ceil,Ry=function(a){return function(e,t,i){var r=ky(KD(e)),s=zD(t),n=r.length,u=i===void 0?" ":ky(i),o,l;return s<=n||u===""?r:(o=s-n,l=XD(u,ZD(o/u.length)),l.length>o&&(l=JD(l,0,o)),a?r+l:l+r)}};$y.exports={start:Ry(!1),end:Ry(!0)}});var Cy=b((mQ,Dy)=>{"use strict";var eC=ci();Dy.exports=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(eC)});var By=b(()=>{"use strict";var tC=oe(),iC=My().start,rC=Cy();tC({target:"String",proto:!0,forced:rC},{padStart:function(e){return iC(this,e,arguments.length>1?arguments[1]:void 0)}})});var _y=b((SQ,Vy)=>{"use strict";By();var aC=Nt();Vy.exports=aC("String","padStart")});var Fy=b((vQ,Oy)=>{"use strict";var sC=_y();Oy.exports=sC});var qy=b((yQ,Ny)=>{"use strict";var nC=Fy();Ny.exports=nC});var Ud="2.0.141-dev.752fa0a9.0";var Le=(r=>(r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused",r))(Le||{}),xt=(T=>(T.MPEG="MPEG",T.DASH="DASH",T.DASH_SEP="DASH_SEP",T.DASH_SEP_VK="DASH_SEP",T.DASH_WEBM="DASH_WEBM",T.DASH_WEBM_AV1="DASH_WEBM_AV1",T.DASH_STREAMS="DASH_STREAMS",T.DASH_WEBM_VK="DASH_WEBM",T.DASH_ONDEMAND="DASH_ONDEMAND",T.DASH_ONDEMAND_VK="DASH_ONDEMAND",T.DASH_LIVE="DASH_LIVE",T.DASH_LIVE_CMAF="DASH_LIVE_CMAF",T.DASH_LIVE_WEBM="DASH_LIVE_WEBM",T.HLS="HLS",T.HLS_ONDEMAND="HLS_ONDEMAND",T.HLS_JS="HLS",T.HLS_FMP4="HLS_FMP4",T.HLS_LIVE="HLS_LIVE",T.HLS_LIVE_CMAF="HLS_LIVE_CMAF",T.WEB_RTC_LIVE="WEB_RTC_LIVE",T))(xt||{});var js=(r=>(r.NOT_AVAILABLE="NOT_AVAILABLE",r.AVAILABLE="AVAILABLE",r.CONNECTING="CONNECTING",r.CONNECTED="CONNECTED",r))(js||{}),eu=(i=>(i.HTTP1="http1",i.HTTP2="http2",i.QUIC="quic",i))(eu||{});var tu=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(tu||{}),Qs=(i=>(i.TRAFFIC_SAVING="traffic_saving",i.HIGH_QUALITY="high_quality",i.UNKNOWN="unknown",i))(Qs||{});var Fd=B(pi(),1),_I=B(Me(),1);import{assertNever as cf,assertNonNullable as Uw,isNonNullable as Zs,ValueSubject as Ou,Subject as Hw,Subscription as jw,merge as Qw,observableFrom as Ww,fromEvent as nf,map as of,tap as uf,filterChanged as Gw,isNullable as Fu,ErrorCategory as lf}from"@vkontakte/videoplayer-shared/es2024";var sf=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 en=class{constructor(e){this.connection$=new Ou(void 0);this.castState$=new Ou("NOT_AVAILABLE");this.errorEvent$=new Hw;this.realCastState$=new Ou("NOT_AVAILABLE");this.subscription=new jw;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=Zs(window.chrome?.cast),r=!!window.__onGCastApiAvailable;i?this.initializeCastApi():(window.__onGCastApiAvailable=s=>{delete window.__onGCastApiAvailable,s&&!this.isDestroyed&&this.initializeCastApi()},r||sf("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:lf.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(){Zs(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();Fu(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();Fu(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(nf(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 cf(r.sessionState)}})).add(Qw(nf(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(uf(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),of(r=>r.castState)),Ww([i.getCastState()])).pipe(Gw(),of(zw),uf(r=>{this.log({message:`realCastState$: ${r}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{let s=r==="CONNECTED",n=Zs(this.connection$.getValue());if(s&&!n){let u=i.getCurrentSession();Uw(u);let o=u.getCastDevice(),l=u.getMediaSession()?.media?.contentId;(Fu(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"?Zs(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:lf.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:r})}}},zw=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 cf(a)}};var Ld=B(Me(),1),SI=B(Yi(),1),vI=B(ol(),1);var rS=B(An(),1);import{assertNever as Ug}from"@vkontakte/videoplayer-shared/es2024";var se=(a,e=0,t=0)=>{switch(t){case 0:return a.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case 1:{if(e===0)return a;let 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:Ug(t)}return a},Ut=(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:Ug(e)}};var P=(a,e,t=!1)=>{let i=a.getTransition();(t||!i||i.to===e)&&a.setState(e)};import{isNonNullable as CL,Subject as Pn,merge as Hg}from"@vkontakte/videoplayer-shared/es2024";var F=class{constructor(e){this.transitionStarted$=new Pn;this.transitionEnded$=new Pn;this.transitionUpdated$=new Pn;this.forceChanged$=new Pn;this.stateChangeStarted$=Hg(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=Hg(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||CL(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}};import{assertNever as Kg}from"@vkontakte/videoplayer-shared/es2024";var kn=class{constructor(){this._isMiuiBrowser=!1}get current(){return this._current}get isChrome(){return this.current==="Chrome"}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 jg=B(Me(),1);var ca=()=>/Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test(navigator.appVersion??navigator.userAgent)||navigator?.userAgentData?.mobile;var Rn=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,jg.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=ca()}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 Ln=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 Ue=()=>window.ManagedMediaSource||window.MediaSource,sr=()=>!!(window.ManagedMediaSource&&window.ManagedSourceBuffer?.prototype?.appendBuffer),Qg=()=>!!(window.MediaSource&&window.SourceBuffer?.prototype?.appendBuffer),$n=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;var BL=document.createElement("video"),VL='video/mp4; codecs="avc1.42000a,mp4a.40.2"',_L='video/mp4; codecs="hev1.1.6.L93.B0"',Wg='video/webm; codecs="vp09.00.10.08"',Gg='video/webm; codecs="av01.0.00M.08"',OL='audio/mp4; codecs="mp4a.40.2"',FL='audio/webm; codecs="opus"',zg,NL=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:Gg}}),window.navigator.mediaCapabilities.decodingInfo({...a,video:{...a.video,contentType:Wg}})]);zg={DASH_WEBM_AV1:e,DASH_WEBM:t}};NL().catch(a=>{console.log(BL),console.error(a)});var Mn=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 zg}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:Qg(),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=!!Ue()?.isTypeSupported?.(VL),t=!!Ue()?.isTypeSupported?.(_L),i=!!Ue()?.isTypeSupported?.(OL);this._codecs={h264:e,h265:t,vp9:!!Ue()?.isTypeSupported?.(Wg),av1:!!Ue()?.isTypeSupported?.(Gg),aac:i,opus:!!Ue()?.isTypeSupported?.(FL),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 Yg="audio/mpeg",Dn=class{supportMp3(){return this._codecs.mp3&&this._containers.mpeg}detect(){this._audio=document.createElement("audio");try{this._containers={mpeg:!!this._audio.canPlayType?.(Yg)},this._codecs={mp3:!!Ue()?.isTypeSupported?.(Yg)}}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}};import{ValueSubject as qL}from"@vkontakte/videoplayer-shared/es2024";var Gl=class{constructor(){this.isInited$=new qL(!1);this._displayChecker=new Ln,this._deviceChecker=new Rn(this._displayChecker),this._browserChecker=new kn,this._videoChecker=new Mn(this._deviceChecker,this._browserChecker),this._audioChecker=new Dn,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)}},C=new Gl;var zl=a=>{let{containers:e,protocols:t,codecs:i,nativeHlsSupported:r}=C.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 Kg(u)}})},Yl=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 Kg(a)}},UL=a=>{let t=Object.keys(a).filter(i=>!Yl(i));return zl(t).length>0};import{assertNever as nr,assertNonNullable as Si,debounce as Xg,ErrorCategory as Jg,fromEvent as vi,isNonNullable as Zg,map as eS,merge as tS,observableFrom as HL,Subject as jL,Subscription as Kl,timeout as QL,getHighestQuality as WL}from"@vkontakte/videoplayer-shared/es2024";var GL=5,zL=5,YL=500,iS=7e3,da=class{constructor(e){this.subscription=new Kl;this.loadMediaTimeoutSubscription=new Kl;this.videoState=new F("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:nr(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:nr(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:nr(e)}break}default:nr(i)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(Yl(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 Kl;this.subscription.add(e),this.subscription.add(tS(this.videoState.stateChangeStarted$.pipe(eS(r=>`stateChangeStarted$ ${JSON.stringify(r)}`)),this.videoState.stateChangeEnded$.pipe(eS(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 jL;e.add(r.pipe(Xg(YL)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add(vi(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)>GL)&&r.next(u),s=u})),e.add(vi(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(vi(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(vi(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemotePause():this.handleRemotePlay()}),t(vi(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<zL&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),P(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:nr(n)}}),t(vi(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t(vi(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({muted:r.value})});let i=tS(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,HL(["init"])).pipe(Xg(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"),P(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),P(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"),P(this.params.desiredState.playbackState,"paused"))}handleRemotePlay(){let e=this.videoState.getState();(this.videoState.getTransition()?.to==="playing"||e==="paused")&&(this.videoState.setState("playing"),P(this.params.desiredState.playbackState,"playing"))}handleRemoteReady(){this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.params.desiredState.playbackState.getTransition()?.to==="ready"&&P(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];Si(l);let p=WL(Object.keys(l));Si(p);let d=l[p];Si(d),i=d,r="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_FMP4":case"HLS_ONDEMAND":{let l=t[e];Si(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];Si(l),i=l.url,r="application/dash+xml",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let l=t[e];Si(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];Si(l),i=se(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:Jg.VIDEO_PIPELINE,message:l,thrown:p}),p}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return nr(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 Zg(u)&&(n.metadata.title=u),Zg(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(QL(iS).subscribe(()=>s(`timeout(${iS})`)))});(0,rS.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:Jg.VIDEO_PIPELINE,message:s,thrown:r})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var fc=B(Me(),1);import{clearVideoElement as sS}from"@vkontakte/videoplayer-shared/es2024";import{clearVideoElement as KL}from"@vkontakte/videoplayer-shared/es2024";var aS=a=>{try{a.pause(),a.playbackRate=0,KL(a),a.remove()}catch(e){console.error(e)}};import{fromEvent as XL,Subscription as JL}from"@vkontakte/videoplayer-shared/es2024";var Xl=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)}},Jl=window.WeakMap?new WeakMap:new Xl,Zl=window.WeakMap?new WeakMap:new Map,ZL=(a,e=20)=>{let t=0;return XL(a,"ratechange").subscribe(i=>{t++,t>=e&&(a.currentTime=a.currentTime,t=0)})},De=(a,{audioVideoSyncRate:e,disableYandexPiP:t})=>{let i=a.querySelector("video"),r=!!i;i?sS(i):(i=document.createElement("video"),a.appendChild(i)),Jl.set(i,r);let s=new JL;return s.add(ZL(i,e)),Zl.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},Ce=a=>{Zl.get(a)?.unsubscribe(),Zl.delete(a);let t=Jl.get(a);Jl.delete(a),t?sS(a):aS(a)};var tc=B(pi(),1);import{assertNonNullable as ha,isNonNullable as bt,isNullable as i$,fromEvent as or,merge as nS,observableFrom as oS,filterChanged as uS,map as fa,Subject as lS,Subscription as r$,ValueSubject as a$,ErrorCategory as s$}from"@vkontakte/videoplayer-shared/es2024";import{isNonNullable as ec,isNullable as e$,Subscription as t$}from"@vkontakte/videoplayer-shared/es2024";var Cn=(a,e,t,{equal:i=(n,u)=>n===u,changed$:r,onError:s}={})=>{let n=a.getState(),u=e(),o=e$(r),l=new t$;return r&&l.add(r.subscribe(p=>{let d=a.getState();i(p,d)&&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},mt=(a,e,t)=>Cn(e,()=>a.loop,i=>{ec(i)&&(a.loop=i)},{onError:t}),Be=(a,e,t,i)=>Cn(e,()=>({muted:a.muted,volume:a.volume}),r=>{ec(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}),ze=(a,e,t,i)=>Cn(e,()=>a.playbackRate,r=>{ec(r)&&(a.playbackRate=r)},{changed$:t,onError:i}),pa=Cn;var n$=a=>["__",a.language,a.label].join("|"),o$=(a,e)=>{if(a.id===e)return!0;let[t,i,r]=e.split("|");return a.language===i&&a.label===r},ic=class a{constructor(e){this.available$=new lS;this.current$=new a$(void 0);this.error$=new lS;this.subscription=new r$;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:s$.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(pa(t.internalTextTracks,()=>(0,tc.default)(this.internalTracks),s=>{bt(s)&&this.setInternal(s)},{equal:(s,n)=>bt(s)&&bt(n)&&s.length===n.length&&s.every(({id:u},o)=>u===n[o].id),changed$:this.available$.pipe(fa(s=>s.filter(({type:n})=>n==="internal"))),onError:r})),this.subscription.add(pa(t.externalTextTracks,()=>(0,tc.default)(this.externalTracks),s=>{bt(s)&&this.setExternal(s)},{equal:(s,n)=>bt(s)&&bt(n)&&s.length===n.length&&s.every(({id:u},o)=>u===n[o].id),changed$:this.available$.pipe(fa(s=>s.filter(({type:n})=>n==="external"))),onError:r})),this.subscription.add(pa(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(pa(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.activeCues)}))}subscribe(){ha(this.video);let{textTracks:e}=this.video;this.subscription.add(or(e,"addtrack").subscribe(()=>{let i=this.current$.getValue();i&&this.select(i)})),this.subscription.add(nS(or(e,"addtrack"),or(e,"removetrack"),oS(["init"])).pipe(fa(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),uS((i,r)=>i.length===r.length&&i.every(({id:s},n)=>s===r[n].id))).subscribe(this.available$)),this.subscription.add(nS(or(e,"change"),oS(["init"])).pipe(fa(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),fa(i=>i&&this.htmlTextTrackToITextTrack(i).id),uS()).subscribe(this.current$));let t=i=>this.applyCueSettings(i.target?.activeCues??null);this.subscription.add(or(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(or(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;bt(t.align)&&(r.align=t.align),bt(t.position)&&(r.position=t.position),bt(t.size)&&(r.size=t.size),bt(t.line)&&(r.line=t.line)}}htmlTextTracksAsArray(e=!1){ha(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:n$(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){ha(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(i$(e)||!o$(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){ha(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){ha(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)}},Ye=ic;var yi=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 cS=a=>{let e=a;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e?.parentNode;return e??void 0},rc=a=>{let e=cS(a);return!!(e&&e.fullscreenElement&&e.fullscreenElement===a)},dS=a=>{let e=cS(a);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===a)};import{fromEvent as Ee,map as gt,merge as Bn,filterChanged as hS,isNonNullable as fS,Subject as l$,filter as ac,mapTo as sc,combine as c$,once as d$,shareReplay as xe,throttle as p$,ErrorCategory as h$,ValueSubject as mS,Subscription as f$}from"@vkontakte/videoplayer-shared/es2024";var u$=3,pS=(a,e,t=u$)=>{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 Ve=a=>{let e=x=>Ee(a,x).pipe(sc(void 0),xe(1)),t=new f$,i=()=>t.unsubscribe(),r=Bn(Ee(a,"progress"),Ee(a,"timeupdate")).pipe(gt(()=>pS(a.buffered,a.currentTime)),xe(1)),s=C.browser.isSafari?c$({play:e("play").pipe(d$()),playing:e("playing")}).pipe(sc(void 0),xe(1)):e("playing"),n=Ee(a,"volumechange").pipe(gt(()=>({muted:a.muted,volume:a.volume})),xe(1)),u=Ee(a,"ratechange").pipe(gt(()=>a.playbackRate),xe(1)),o=Ee(a,"error").pipe(ac(()=>!!(a.error||a.played.length)),gt(()=>{let x=a.error;return{id:x?`MediaError#${x.code}`:"HtmlVideoError",category:h$.VIDEO_PIPELINE,message:x?x.message:"Error event from HTML video element",thrown:a.error??void 0}}),xe(1)),l=Ee(a,"timeupdate").pipe(gt(()=>a.currentTime),xe(1)),p=["waiting","seeking","seeked","timeupdate"],d=new l$,c=.3,h;t.add(Bn(...p.map(x=>Ee(a,x))).subscribe(x=>{let q=a.currentTime;a.loop&&fS(h)&&fS(q)&&h>=a.duration-c&&q<=c&&d.next(h),h=q}));let f=e("pause").pipe(ac(()=>!a.error&&h!==a.duration),xe(1)),m=Ee(a,"enterpictureinpicture").pipe(xe(1)),g=Ee(a,"leavepictureinpicture").pipe(xe(1)),S=new mS(dS(a));t.add(m.subscribe(()=>S.next(!0))),t.add(g.subscribe(()=>S.next(!1)));let v=new mS(rc(a)),I=Ee(a,"fullscreenchange").pipe(xe(1));t.add(I.pipe(gt(()=>rc(a))).subscribe(v));let T=.1,A=1e3,R=Ee(a,"timeupdate").pipe(gt(x=>a.duration-a.currentTime<T),hS(),xe(1)),L=Bn(R.pipe(ac(x=>!a.loop&&x)),Ee(a,"ended")).pipe(p$(A),sc(void 0),xe(1)),D=Bn(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(x=>Ee(a,x)),R.pipe(gt(x=>({type:x?"ended":"unknown"})))).pipe(gt(x=>C.browser.isFirefox&&x.type==="ended"?a.readyState<2:a.readyState<3),hS(),xe(1));return{playing$:s,pause$:f,canplay$:e("canplay"),ended$:L,looped$:d,error$:o,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:l,durationChange$:Ee(a,"durationchange").pipe(gt(()=>a.duration),xe(1)),isBuffering$:D,currentBuffer$:r,volumeState$:n,playbackRateState$:u,inPiP$:S,inFullscreen$:v,enterPip$:m,leavePip$:g,destroy:i}};import{VideoQuality as Ht}from"@vkontakte/videoplayer-shared/es2024";var jt=a=>{switch(a){case"mobile":return Ht.Q_144P;case"lowest":return Ht.Q_240P;case"low":return Ht.Q_360P;case"sd":case"medium":return Ht.Q_480P;case"hd":case"high":return Ht.Q_720P;case"fullhd":case"full":return Ht.Q_1080P;case"quadhd":case"quad":return Ht.Q_1440P;case"ultrahd":case"ultra":return Ht.Q_2160P}};var Ae=B(at(),1),oc=B(Me(),1),Ii=B(Yi(),1);import{isNonNullable as K,isNullable as Fn,now as MS,isHigher as Nn,isHigherOrEqual as Ti,isInvariantQuality as qn,isLowerOrEqual as lr,videoSizeToQuality as DS,assertNotEmptyArray as Un,assertNonNullable as CS}from"@vkontakte/videoplayer-shared/es2024";var nc=!1,kt={},IS=a=>{nc=a},ES=()=>{kt={}},xS=a=>{a(kt)},ma=(a,e)=>{nc&&(kt.meta=kt.meta??{},kt.meta[a]=e)},we=class{constructor(e){this.name=e}next(e){if(!nc)return;kt.series=kt.series??{};let t=kt.series[this.name]??[];t.push([Date.now(),e]),kt.series[this.name]=t}};import{isHigher as E$,isHigherOrEqual as lq,isLower as wS,isLowerOrEqual as cq,isNonNullable as Vn,isNullable as x$,videoHeightToQuality as _n}from"@vkontakte/videoplayer-shared/es2024";function AS(a,e,t){return!a.max&&a.min===e?"high_quality":!a.min&&a.max===t?"traffic_saving":"unknown"}function ur(a,e,t){return x$(a)||Vn(a.min)&&Vn(a.max)&&wS(a.max,a.min)||Vn(a.min)&&e&&E$(a.min,e)||Vn(a.max)&&t&&wS(a.max,t)}function PS({limits:a,highestAvailableHeight:e,lowestAvailableHeight:t}){return ur({max:a?.max?_n(a.max):void 0,min:a?.min?_n(a.min):void 0},e?_n(e):void 0,t?_n(t):void 0)}var BS=new we("best_bitrate"),Hn=(a,e,t)=>(e-t)*Math.pow(2,-10*a)+t;var cr=a=>(e,t)=>a*(Number(e.bitrate)-Number(t.bitrate)),Qt=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=MS()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},jn='Assertion "ABR Tracks is empty array" failed',On=new WeakMap,kS=new WeakMap,RS=new WeakMap,ba=(a,e,t,i)=>{let r=[...e].sort(cr(1)),s=[...t].sort(cr(1)),n=s.filter(o=>K(o.bitrate)&&K(a.bitrate)?a.bitrate/o.bitrate>i:!0),u=(0,Ae.default)(s,Math.round(s.length*r.indexOf(a)/(r.length+1)))??(0,Ae.default)(s,-1);return u&&(0,oc.default)(n,u)?u:n.length?(0,Ae.default)(n,-1):(0,Ae.default)(s,0)},ga=(a,e,t,i)=>{let r=On.get(e);r||(r=[...e].sort(cr(1)),On.set(e,r));let s=On.get(t);s||(s=[...t].sort(cr(1)),On.set(t,s));let n=RS.get(a);n||(n=s.filter(o=>K(o.bitrate)&&K(a.bitrate)?a.bitrate/o.bitrate>i:!0),RS.set(a,n));let u=(0,Ae.default)(s,Math.round(s.length*r.indexOf(a)/(r.length+1)))??(0,Ae.default)(s,-1);return u&&(0,oc.default)(n,u)?u:n.length?(0,Ae.default)(n,-1):(0,Ae.default)(s,0)},LS=a=>"quality"in a,Qn=(a,e,t,i)=>{let r=K(i?.last?.bitrate)&&K(t?.bitrate)&&i.last.bitrate<t.bitrate?a.trackCooldownIncreaseQuality:a.trackCooldownDecreaseQuality,s=t&&i&&i.history[t.id]&&MS()-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=LS(n)?"video":"audio",o=LS(n)?n.quality:n.bitrate;return e({message:`
6
+ var UI=Object.create;var qd=Object.defineProperty;var HI=Object.getOwnPropertyDescriptor;var jI=Object.getOwnPropertyNames;var QI=Object.getPrototypeOf,WI=Object.prototype.hasOwnProperty;var b=(a,e)=>()=>(e||a((e={exports:{}}).exports,e),e.exports);var GI=(a,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of jI(e))!WI.call(a,r)&&r!==t&&qd(a,r,{get:()=>e[r],enumerable:!(i=HI(e,r))||i.enumerable});return a};var B=(a,e,t)=>(t=a!=null?UI(QI(a)):{},GI(e||!a||!a.__esModule?qd(t,"default",{value:a,enumerable:!0}):t,a));var re=b((iu,Hd)=>{"use strict";var Nr=function(a){return a&&a.Math===Math&&a};Hd.exports=Nr(typeof globalThis=="object"&&globalThis)||Nr(typeof window=="object"&&window)||Nr(typeof self=="object"&&self)||Nr(typeof global=="object"&&global)||Nr(typeof iu=="object"&&iu)||function(){return this}()||Function("return this")()});var pe=b((tV,jd)=>{"use strict";jd.exports=function(a){try{return!!a()}catch{return!0}}});var qr=b((iV,Qd)=>{"use strict";var zI=pe();Qd.exports=!zI(function(){var a=function(){}.bind();return typeof a!="function"||a.hasOwnProperty("prototype")})});var ru=b((rV,Yd)=>{"use strict";var YI=qr(),zd=Function.prototype,Wd=zd.apply,Gd=zd.call;Yd.exports=typeof Reflect=="object"&&Reflect.apply||(YI?Gd.bind(Wd):function(){return Gd.apply(Wd,arguments)})});var he=b((aV,Jd)=>{"use strict";var Kd=qr(),Xd=Function.prototype,au=Xd.call,KI=Kd&&Xd.bind.bind(au,au);Jd.exports=Kd?KI:function(a){return function(){return au.apply(a,arguments)}}});var oi=b((sV,ep)=>{"use strict";var Zd=he(),XI=Zd({}.toString),JI=Zd("".slice);ep.exports=function(a){return JI(XI(a),8,-1)}});var su=b((nV,tp)=>{"use strict";var ZI=oi(),eE=he();tp.exports=function(a){if(ZI(a)==="Function")return eE(a)}});var ae=b((oV,ip)=>{"use strict";var nu=typeof document=="object"&&document.all;ip.exports=typeof nu>"u"&&nu!==void 0?function(a){return typeof a=="function"||a===nu}:function(a){return typeof a=="function"}});var Fe=b((uV,rp)=>{"use strict";var tE=pe();rp.exports=!tE(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var Ne=b((lV,ap)=>{"use strict";var iE=qr(),Ws=Function.prototype.call;ap.exports=iE?Ws.bind(Ws):function(){return Ws.apply(Ws,arguments)}});var ou=b(op=>{"use strict";var sp={}.propertyIsEnumerable,np=Object.getOwnPropertyDescriptor,rE=np&&!sp.call({1:2},1);op.f=rE?function(e){var t=np(this,e);return!!t&&t.enumerable}:sp});var Ur=b((dV,up)=>{"use strict";up.exports=function(a,e){return{enumerable:!(a&1),configurable:!(a&2),writable:!(a&4),value:e}}});var cp=b((pV,lp)=>{"use strict";var aE=he(),sE=pe(),nE=oi(),uu=Object,oE=aE("".split);lp.exports=sE(function(){return!uu("z").propertyIsEnumerable(0)})?function(a){return nE(a)==="String"?oE(a,""):uu(a)}:uu});var Hr=b((hV,dp)=>{"use strict";dp.exports=function(a){return a==null}});var Ft=b((fV,pp)=>{"use strict";var uE=Hr(),lE=TypeError;pp.exports=function(a){if(uE(a))throw new lE("Can't call method on "+a);return a}});var ui=b((mV,hp)=>{"use strict";var cE=cp(),dE=Ft();hp.exports=function(a){return cE(dE(a))}});var $e=b((bV,fp)=>{"use strict";var pE=ae();fp.exports=function(a){return typeof a=="object"?a!==null:pE(a)}});var li=b((gV,mp)=>{"use strict";mp.exports={}});var wt=b((SV,gp)=>{"use strict";var lu=li(),cu=re(),hE=ae(),bp=function(a){return hE(a)?a:void 0};gp.exports=function(a,e){return arguments.length<2?bp(lu[a])||bp(cu[a]):lu[a]&&lu[a][e]||cu[a]&&cu[a][e]}});var jr=b((vV,Sp)=>{"use strict";var fE=he();Sp.exports=fE({}.isPrototypeOf)});var ci=b((yV,Tp)=>{"use strict";var mE=re(),vp=mE.navigator,yp=vp&&vp.userAgent;Tp.exports=yp?String(yp):""});var pu=b((TV,Pp)=>{"use strict";var Ap=re(),du=ci(),Ip=Ap.process,Ep=Ap.Deno,xp=Ip&&Ip.versions||Ep&&Ep.version,wp=xp&&xp.v8,et,Gs;wp&&(et=wp.split("."),Gs=et[0]>0&&et[0]<4?1:+(et[0]+et[1]));!Gs&&du&&(et=du.match(/Edge\/(\d+)/),(!et||et[1]>=74)&&(et=du.match(/Chrome\/(\d+)/),et&&(Gs=+et[1])));Pp.exports=Gs});var hu=b((IV,Rp)=>{"use strict";var kp=pu(),bE=pe(),gE=re(),SE=gE.String;Rp.exports=!!Object.getOwnPropertySymbols&&!bE(function(){var a=Symbol("symbol detection");return!SE(a)||!(Object(a)instanceof Symbol)||!Symbol.sham&&kp&&kp<41})});var fu=b((EV,Lp)=>{"use strict";var vE=hu();Lp.exports=vE&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var mu=b((xV,$p)=>{"use strict";var yE=wt(),TE=ae(),IE=jr(),EE=fu(),xE=Object;$p.exports=EE?function(a){return typeof a=="symbol"}:function(a){var e=yE("Symbol");return TE(e)&&IE(e.prototype,xE(a))}});var Qr=b((wV,Mp)=>{"use strict";var wE=String;Mp.exports=function(a){try{return wE(a)}catch{return"Object"}}});var ht=b((AV,Dp)=>{"use strict";var AE=ae(),PE=Qr(),kE=TypeError;Dp.exports=function(a){if(AE(a))return a;throw new kE(PE(a)+" is not a function")}});var Wr=b((PV,Cp)=>{"use strict";var RE=ht(),LE=Hr();Cp.exports=function(a,e){var t=a[e];return LE(t)?void 0:RE(t)}});var Vp=b((kV,Bp)=>{"use strict";var bu=Ne(),gu=ae(),Su=$e(),$E=TypeError;Bp.exports=function(a,e){var t,i;if(e==="string"&&gu(t=a.toString)&&!Su(i=bu(t,a))||gu(t=a.valueOf)&&!Su(i=bu(t,a))||e!=="string"&&gu(t=a.toString)&&!Su(i=bu(t,a)))return i;throw new $E("Can't convert object to primitive value")}});var tt=b((RV,_p)=>{"use strict";_p.exports=!0});var Np=b((LV,Fp)=>{"use strict";var Op=re(),ME=Object.defineProperty;Fp.exports=function(a,e){try{ME(Op,a,{value:e,configurable:!0,writable:!0})}catch{Op[a]=e}return e}});var Gr=b(($V,Hp)=>{"use strict";var DE=tt(),CE=re(),BE=Np(),qp="__core-js_shared__",Up=Hp.exports=CE[qp]||BE(qp,{});(Up.versions||(Up.versions=[])).push({version:"3.43.0",mode:DE?"pure":"global",copyright:"\xA9 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 vu=b((MV,Qp)=>{"use strict";var jp=Gr();Qp.exports=function(a,e){return jp[a]||(jp[a]=e||{})}});var Ui=b((DV,Wp)=>{"use strict";var VE=Ft(),_E=Object;Wp.exports=function(a){return _E(VE(a))}});var it=b((CV,Gp)=>{"use strict";var OE=he(),FE=Ui(),NE=OE({}.hasOwnProperty);Gp.exports=Object.hasOwn||function(e,t){return NE(FE(e),t)}});var yu=b((BV,zp)=>{"use strict";var qE=he(),UE=0,HE=Math.random(),jE=qE(1.1.toString);zp.exports=function(a){return"Symbol("+(a===void 0?"":a)+")_"+jE(++UE+HE,36)}});var ge=b((VV,Kp)=>{"use strict";var QE=re(),WE=vu(),Yp=it(),GE=yu(),zE=hu(),YE=fu(),Hi=QE.Symbol,Tu=WE("wks"),KE=YE?Hi.for||Hi:Hi&&Hi.withoutSetter||GE;Kp.exports=function(a){return Yp(Tu,a)||(Tu[a]=zE&&Yp(Hi,a)?Hi[a]:KE("Symbol."+a)),Tu[a]}});var eh=b((_V,Zp)=>{"use strict";var XE=Ne(),Xp=$e(),Jp=mu(),JE=Wr(),ZE=Vp(),ex=ge(),tx=TypeError,ix=ex("toPrimitive");Zp.exports=function(a,e){if(!Xp(a)||Jp(a))return a;var t=JE(a,ix),i;if(t){if(e===void 0&&(e="default"),i=XE(t,a,e),!Xp(i)||Jp(i))return i;throw new tx("Can't convert object to primitive value")}return e===void 0&&(e="number"),ZE(a,e)}});var Iu=b((OV,th)=>{"use strict";var rx=eh(),ax=mu();th.exports=function(a){var e=rx(a,"string");return ax(e)?e:e+""}});var zs=b((FV,rh)=>{"use strict";var sx=re(),ih=$e(),Eu=sx.document,nx=ih(Eu)&&ih(Eu.createElement);rh.exports=function(a){return nx?Eu.createElement(a):{}}});var xu=b((NV,ah)=>{"use strict";var ox=Fe(),ux=pe(),lx=zs();ah.exports=!ox&&!ux(function(){return Object.defineProperty(lx("div"),"a",{get:function(){return 7}}).a!==7})});var oh=b(nh=>{"use strict";var cx=Fe(),dx=Ne(),px=ou(),hx=Ur(),fx=ui(),mx=Iu(),bx=it(),gx=xu(),sh=Object.getOwnPropertyDescriptor;nh.f=cx?sh:function(e,t){if(e=fx(e),t=mx(t),gx)try{return sh(e,t)}catch{}if(bx(e,t))return hx(!dx(px.f,e,t),e[t])}});var wu=b((UV,uh)=>{"use strict";var Sx=pe(),vx=ae(),yx=/#|\.prototype\./,zr=function(a,e){var t=Ix[Tx(a)];return t===xx?!0:t===Ex?!1:vx(e)?Sx(e):!!e},Tx=zr.normalize=function(a){return String(a).replace(yx,".").toLowerCase()},Ix=zr.data={},Ex=zr.NATIVE="N",xx=zr.POLYFILL="P";uh.exports=zr});var ji=b((HV,ch)=>{"use strict";var lh=su(),wx=ht(),Ax=qr(),Px=lh(lh.bind);ch.exports=function(a,e){return wx(a),e===void 0?a:Ax?Px(a,e):function(){return a.apply(e,arguments)}}});var Au=b((jV,dh)=>{"use strict";var kx=Fe(),Rx=pe();dh.exports=kx&&Rx(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var ft=b((QV,ph)=>{"use strict";var Lx=$e(),$x=String,Mx=TypeError;ph.exports=function(a){if(Lx(a))return a;throw new Mx($x(a)+" is not an object")}});var di=b(fh=>{"use strict";var Dx=Fe(),Cx=xu(),Bx=Au(),Ys=ft(),hh=Iu(),Vx=TypeError,Pu=Object.defineProperty,_x=Object.getOwnPropertyDescriptor,ku="enumerable",Ru="configurable",Lu="writable";fh.f=Dx?Bx?function(e,t,i){if(Ys(e),t=hh(t),Ys(i),typeof e=="function"&&t==="prototype"&&"value"in i&&Lu in i&&!i[Lu]){var r=_x(e,t);r&&r[Lu]&&(e[t]=i.value,i={configurable:Ru in i?i[Ru]:r[Ru],enumerable:ku in i?i[ku]:r[ku],writable:!1})}return Pu(e,t,i)}:Pu:function(e,t,i){if(Ys(e),t=hh(t),Ys(i),Cx)try{return Pu(e,t,i)}catch{}if("get"in i||"set"in i)throw new Vx("Accessors not supported");return"value"in i&&(e[t]=i.value),e}});var Qi=b((GV,mh)=>{"use strict";var Ox=Fe(),Fx=di(),Nx=Ur();mh.exports=Ox?function(a,e,t){return Fx.f(a,e,Nx(1,t))}:function(a,e,t){return a[e]=t,a}});var oe=b((zV,gh)=>{"use strict";var Yr=re(),qx=ru(),Ux=su(),Hx=ae(),jx=oh().f,Qx=wu(),Wi=li(),Wx=ji(),Gi=Qi(),bh=it();Gr();var Gx=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 qx(a,this,arguments)};return e.prototype=a.prototype,e};gh.exports=function(a,e){var t=a.target,i=a.global,r=a.stat,s=a.proto,n=i?Yr:r?Yr[t]:Yr[t]&&Yr[t].prototype,u=i?Wi:Wi[t]||Gi(Wi,t,{})[t],o=u.prototype,l,p,d,c,h,f,m,g,S;for(c in e)l=Qx(i?c:t+(r?".":"#")+c,a.forced),p=!l&&n&&bh(n,c),f=u[c],p&&(a.dontCallGetSet?(S=jx(n,c),m=S&&S.value):m=n[c]),h=p&&m?m:e[c],!(!l&&!s&&typeof f==typeof h)&&(a.bind&&p?g=Wx(h,Yr):a.wrap&&p?g=Gx(h):s&&Hx(h)?g=Ux(h):g=h,(a.sham||h&&h.sham||f&&f.sham)&&Gi(g,"sham",!0),Gi(u,c,g),s&&(d=t+"Prototype",bh(Wi,d)||Gi(Wi,d,{}),Gi(Wi[d],c,h),a.real&&o&&(l||!o[c])&&Gi(o,c,h)))}});var Ks=b((YV,vh)=>{"use strict";var zx=vu(),Yx=yu(),Sh=zx("keys");vh.exports=function(a){return Sh[a]||(Sh[a]=Yx(a))}});var Th=b((KV,yh)=>{"use strict";var Kx=pe();yh.exports=!Kx(function(){function a(){}return a.prototype.constructor=null,Object.getPrototypeOf(new a)!==a.prototype})});var Xs=b((XV,Eh)=>{"use strict";var Xx=it(),Jx=ae(),Zx=Ui(),ew=Ks(),tw=Th(),Ih=ew("IE_PROTO"),$u=Object,iw=$u.prototype;Eh.exports=tw?$u.getPrototypeOf:function(a){var e=Zx(a);if(Xx(e,Ih))return e[Ih];var t=e.constructor;return Jx(t)&&e instanceof t?t.prototype:e instanceof $u?iw:null}});var wh=b((JV,xh)=>{"use strict";var rw=Math.ceil,aw=Math.floor;xh.exports=Math.trunc||function(e){var t=+e;return(t>0?aw:rw)(t)}});var Kr=b((ZV,Ah)=>{"use strict";var sw=wh();Ah.exports=function(a){var e=+a;return e!==e||e===0?0:sw(e)}});var kh=b((e_,Ph)=>{"use strict";var nw=Kr(),ow=Math.max,uw=Math.min;Ph.exports=function(a,e){var t=nw(a);return t<0?ow(t+e,0):uw(t,e)}});var Mu=b((t_,Rh)=>{"use strict";var lw=Kr(),cw=Math.min;Rh.exports=function(a){var e=lw(a);return e>0?cw(e,9007199254740991):0}});var zi=b((i_,Lh)=>{"use strict";var dw=Mu();Lh.exports=function(a){return dw(a.length)}});var Du=b((r_,Mh)=>{"use strict";var pw=ui(),hw=kh(),fw=zi(),$h=function(a){return function(e,t,i){var r=pw(e),s=fw(r);if(s===0)return!a&&-1;var n=hw(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}};Mh.exports={includes:$h(!0),indexOf:$h(!1)}});var Js=b((a_,Dh)=>{"use strict";Dh.exports={}});var Vh=b((s_,Bh)=>{"use strict";var mw=he(),Cu=it(),bw=ui(),gw=Du().indexOf,Sw=Js(),Ch=mw([].push);Bh.exports=function(a,e){var t=bw(a),i=0,r=[],s;for(s in t)!Cu(Sw,s)&&Cu(t,s)&&Ch(r,s);for(;e.length>i;)Cu(t,s=e[i++])&&(~gw(r,s)||Ch(r,s));return r}});var Bu=b((n_,_h)=>{"use strict";_h.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var Vu=b((o_,Oh)=>{"use strict";var vw=Vh(),yw=Bu();Oh.exports=Object.keys||function(e){return vw(e,yw)}});var _u=b((u_,Hh)=>{"use strict";var Nh=Fe(),Tw=pe(),qh=he(),Iw=Xs(),Ew=Vu(),xw=ui(),ww=ou().f,Uh=qh(ww),Aw=qh([].push),Pw=Nh&&Tw(function(){var a=Object.create(null);return a[2]=2,!Uh(a,2)}),Fh=function(a){return function(e){for(var t=xw(e),i=Ew(t),r=Pw&&Iw(t)===null,s=i.length,n=0,u=[],o;s>n;)o=i[n++],(!Nh||(r?o in t:Uh(t,o)))&&Aw(u,a?[o,t[o]]:t[o]);return u}};Hh.exports={entries:Fh(!0),values:Fh(!1)}});var jh=b(()=>{"use strict";var kw=oe(),Rw=_u().values;kw({target:"Object",stat:!0},{values:function(e){return Rw(e)}})});var Wh=b((d_,Qh)=>{"use strict";jh();var Lw=li();Qh.exports=Lw.Object.values});var zh=b((p_,Gh)=>{"use strict";var $w=Wh();Gh.exports=$w});var pi=b((h_,Yh)=>{"use strict";var Mw=zh();Yh.exports=Mw});var Xr=b((f_,Kh)=>{"use strict";Kh.exports=function(){}});var Xh=b(()=>{"use strict";var Dw=oe(),Cw=Du().includes,Bw=pe(),Vw=Xr(),_w=Bw(function(){return!Array(1).includes()});Dw({target:"Array",proto:!0,forced:_w},{includes:function(e){return Cw(this,e,arguments.length>1?arguments[1]:void 0)}});Vw("includes")});var Nt=b((g_,Jh)=>{"use strict";var Ow=wt();Jh.exports=Ow});var ef=b((S_,Zh)=>{"use strict";Xh();var Fw=Nt();Zh.exports=Fw("Array","includes")});var rf=b((v_,tf)=>{"use strict";var Nw=ef();tf.exports=Nw});var Me=b((y_,af)=>{"use strict";var qw=rf();af.exports=qw});var df=b(()=>{"use strict";var Yw=oe(),Kw=_u().entries;Yw({target:"Object",stat:!0},{entries:function(e){return Kw(e)}})});var hf=b((C_,pf)=>{"use strict";df();var Xw=li();pf.exports=Xw.Object.entries});var mf=b((B_,ff)=>{"use strict";var Jw=hf();ff.exports=Jw});var Yi=b((V_,bf)=>{"use strict";var Zw=mf();bf.exports=Zw});var hi=b((__,gf)=>{"use strict";gf.exports={}});var yf=b((O_,vf)=>{"use strict";var eA=re(),tA=ae(),Sf=eA.WeakMap;vf.exports=tA(Sf)&&/native code/.test(String(Sf))});var Hu=b((F_,Ef)=>{"use strict";var iA=yf(),If=re(),rA=$e(),aA=Qi(),Nu=it(),qu=Gr(),sA=Ks(),nA=Js(),Tf="Object already initialized",Uu=If.TypeError,oA=If.WeakMap,tn,Jr,rn,uA=function(a){return rn(a)?Jr(a):tn(a,{})},lA=function(a){return function(e){var t;if(!rA(e)||(t=Jr(e)).type!==a)throw new Uu("Incompatible receiver, "+a+" required");return t}};iA||qu.state?(rt=qu.state||(qu.state=new oA),rt.get=rt.get,rt.has=rt.has,rt.set=rt.set,tn=function(a,e){if(rt.has(a))throw new Uu(Tf);return e.facade=a,rt.set(a,e),e},Jr=function(a){return rt.get(a)||{}},rn=function(a){return rt.has(a)}):(fi=sA("state"),nA[fi]=!0,tn=function(a,e){if(Nu(a,fi))throw new Uu(Tf);return e.facade=a,aA(a,fi,e),e},Jr=function(a){return Nu(a,fi)?a[fi]:{}},rn=function(a){return Nu(a,fi)});var rt,fi;Ef.exports={set:tn,get:Jr,has:rn,enforce:uA,getterFor:lA}});var Wu=b((N_,wf)=>{"use strict";var ju=Fe(),cA=it(),xf=Function.prototype,dA=ju&&Object.getOwnPropertyDescriptor,Qu=cA(xf,"name"),pA=Qu&&function(){}.name==="something",hA=Qu&&(!ju||ju&&dA(xf,"name").configurable);wf.exports={EXISTS:Qu,PROPER:pA,CONFIGURABLE:hA}});var Pf=b(Af=>{"use strict";var fA=Fe(),mA=Au(),bA=di(),gA=ft(),SA=ui(),vA=Vu();Af.f=fA&&!mA?Object.defineProperties:function(e,t){gA(e);for(var i=SA(t),r=vA(t),s=r.length,n=0,u;s>n;)bA.f(e,u=r[n++],i[u]);return e}});var Gu=b((U_,kf)=>{"use strict";var yA=wt();kf.exports=yA("document","documentElement")});var Xu=b((H_,Bf)=>{"use strict";var TA=ft(),IA=Pf(),Rf=Bu(),EA=Js(),xA=Gu(),wA=zs(),AA=Ks(),Lf=">",$f="<",Yu="prototype",Ku="script",Df=AA("IE_PROTO"),zu=function(){},Cf=function(a){return $f+Ku+Lf+a+$f+"/"+Ku+Lf},Mf=function(a){a.write(Cf("")),a.close();var e=a.parentWindow.Object;return a=null,e},PA=function(){var a=wA("iframe"),e="java"+Ku+":",t;return a.style.display="none",xA.appendChild(a),a.src=String(e),t=a.contentWindow.document,t.open(),t.write(Cf("document.F=Object")),t.close(),t.F},an,sn=function(){try{an=new ActiveXObject("htmlfile")}catch{}sn=typeof document<"u"?document.domain&&an?Mf(an):PA():Mf(an);for(var a=Rf.length;a--;)delete sn[Yu][Rf[a]];return sn()};EA[Df]=!0;Bf.exports=Object.create||function(e,t){var i;return e!==null?(zu[Yu]=TA(e),i=new zu,zu[Yu]=null,i[Df]=e):i=sn(),t===void 0?i:IA.f(i,t)}});var Ki=b((j_,Vf)=>{"use strict";var kA=Qi();Vf.exports=function(a,e,t,i){return i&&i.enumerable?a[e]=t:kA(a,e,t),a}});var tl=b((Q_,Ff)=>{"use strict";var RA=pe(),LA=ae(),$A=$e(),MA=Xu(),_f=Xs(),DA=Ki(),CA=ge(),BA=tt(),el=CA("iterator"),Of=!1,At,Ju,Zu;[].keys&&(Zu=[].keys(),"next"in Zu?(Ju=_f(_f(Zu)),Ju!==Object.prototype&&(At=Ju)):Of=!0);var VA=!$A(At)||RA(function(){var a={};return At[el].call(a)!==a});VA?At={}:BA&&(At=MA(At));LA(At[el])||DA(At,el,function(){return this});Ff.exports={IteratorPrototype:At,BUGGY_SAFARI_ITERATORS:Of}});var nn=b((W_,qf)=>{"use strict";var _A=ge(),OA=_A("toStringTag"),Nf={};Nf[OA]="z";qf.exports=String(Nf)==="[object z]"});var Zr=b((G_,Uf)=>{"use strict";var FA=nn(),NA=ae(),on=oi(),qA=ge(),UA=qA("toStringTag"),HA=Object,jA=on(function(){return arguments}())==="Arguments",QA=function(a,e){try{return a[e]}catch{}};Uf.exports=FA?on:function(a){var e,t,i;return a===void 0?"Undefined":a===null?"Null":typeof(t=QA(e=HA(a),UA))=="string"?t:jA?on(e):(i=on(e))==="Object"&&NA(e.callee)?"Arguments":i}});var jf=b((z_,Hf)=>{"use strict";var WA=nn(),GA=Zr();Hf.exports=WA?{}.toString:function(){return"[object "+GA(this)+"]"}});var ea=b((Y_,Wf)=>{"use strict";var zA=nn(),YA=di().f,KA=Qi(),XA=it(),JA=jf(),ZA=ge(),Qf=ZA("toStringTag");Wf.exports=function(a,e,t,i){var r=t?a:a&&a.prototype;r&&(XA(r,Qf)||YA(r,Qf,{configurable:!0,value:e}),i&&!zA&&KA(r,"toString",JA))}});var zf=b((K_,Gf)=>{"use strict";var eP=tl().IteratorPrototype,tP=Xu(),iP=Ur(),rP=ea(),aP=hi(),sP=function(){return this};Gf.exports=function(a,e,t,i){var r=e+" Iterator";return a.prototype=tP(eP,{next:iP(+!i,t)}),rP(a,r,!1,!0),aP[r]=sP,a}});var Kf=b((X_,Yf)=>{"use strict";var nP=he(),oP=ht();Yf.exports=function(a,e,t){try{return nP(oP(Object.getOwnPropertyDescriptor(a,e)[t]))}catch{}}});var Jf=b((J_,Xf)=>{"use strict";var uP=$e();Xf.exports=function(a){return uP(a)||a===null}});var em=b((Z_,Zf)=>{"use strict";var lP=Jf(),cP=String,dP=TypeError;Zf.exports=function(a){if(lP(a))return a;throw new dP("Can't set "+cP(a)+" as a prototype")}});var il=b((eO,tm)=>{"use strict";var pP=Kf(),hP=$e(),fP=Ft(),mP=em();tm.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var a=!1,e={},t;try{t=pP(Object.prototype,"__proto__","set"),t(e,[]),a=e instanceof Array}catch{}return function(r,s){return fP(r),mP(s),hP(r)&&(a?t(r,s):r.__proto__=s),r}}():void 0)});var pm=b((tO,dm)=>{"use strict";var bP=oe(),gP=Ne(),un=tt(),lm=Wu(),SP=ae(),vP=zf(),im=Xs(),rm=il(),yP=ea(),TP=Qi(),rl=Ki(),IP=ge(),am=hi(),cm=tl(),EP=lm.PROPER,xP=lm.CONFIGURABLE,sm=cm.IteratorPrototype,ln=cm.BUGGY_SAFARI_ITERATORS,ta=IP("iterator"),nm="keys",ia="values",om="entries",um=function(){return this};dm.exports=function(a,e,t,i,r,s,n){vP(t,e,i);var u=function(S){if(S===r&&c)return c;if(!ln&&S&&S in p)return p[S];switch(S){case nm:return function(){return new t(this,S)};case ia:return function(){return new t(this,S)};case om:return function(){return new t(this,S)}}return function(){return new t(this)}},o=e+" Iterator",l=!1,p=a.prototype,d=p[ta]||p["@@iterator"]||r&&p[r],c=!ln&&d||u(r),h=e==="Array"&&p.entries||d,f,m,g;if(h&&(f=im(h.call(new a)),f!==Object.prototype&&f.next&&(!un&&im(f)!==sm&&(rm?rm(f,sm):SP(f[ta])||rl(f,ta,um)),yP(f,o,!0,!0),un&&(am[o]=um))),EP&&r===ia&&d&&d.name!==ia&&(!un&&xP?TP(p,"name",ia):(l=!0,c=function(){return gP(d,this)})),r)if(m={values:u(ia),keys:s?c:u(nm),entries:u(om)},n)for(g in m)(ln||l||!(g in p))&&rl(p,g,m[g]);else bP({target:e,proto:!0,forced:ln||l},m);return(!un||n)&&p[ta]!==c&&rl(p,ta,c,{name:r}),am[e]=c,m}});var fm=b((iO,hm)=>{"use strict";hm.exports=function(a,e){return{value:a,done:e}}});var sl=b((rO,vm)=>{"use strict";var wP=ui(),al=Xr(),mm=hi(),gm=Hu(),AP=di().f,PP=pm(),cn=fm(),kP=tt(),RP=Fe(),Sm="Array Iterator",LP=gm.set,$P=gm.getterFor(Sm);vm.exports=PP(Array,"Array",function(a,e){LP(this,{type:Sm,target:wP(a),index:0,kind:e})},function(){var a=$P(this),e=a.target,t=a.index++;if(!e||t>=e.length)return a.target=null,cn(void 0,!0);switch(a.kind){case"keys":return cn(t,!1);case"values":return cn(e[t],!1)}return cn([t,e[t]],!1)},"values");var bm=mm.Arguments=mm.Array;al("keys");al("values");al("entries");if(!kP&&RP&&bm.name!=="values")try{AP(bm,"name",{value:"values"})}catch{}});var Tm=b((aO,ym)=>{"use strict";var MP=ge(),DP=hi(),CP=MP("iterator"),BP=Array.prototype;ym.exports=function(a){return a!==void 0&&(DP.Array===a||BP[CP]===a)}});var nl=b((sO,Em)=>{"use strict";var VP=Zr(),Im=Wr(),_P=Hr(),OP=hi(),FP=ge(),NP=FP("iterator");Em.exports=function(a){if(!_P(a))return Im(a,NP)||Im(a,"@@iterator")||OP[VP(a)]}});var wm=b((nO,xm)=>{"use strict";var qP=Ne(),UP=ht(),HP=ft(),jP=Qr(),QP=nl(),WP=TypeError;xm.exports=function(a,e){var t=arguments.length<2?QP(a):e;if(UP(t))return HP(qP(t,a));throw new WP(jP(a)+" is not iterable")}});var km=b((oO,Pm)=>{"use strict";var GP=Ne(),Am=ft(),zP=Wr();Pm.exports=function(a,e,t){var i,r;Am(a);try{if(i=zP(a,"return"),!i){if(e==="throw")throw t;return t}i=GP(i,a)}catch(s){r=!0,i=s}if(e==="throw")throw t;if(r)throw i;return Am(i),t}});var pn=b((uO,Mm)=>{"use strict";var YP=ji(),KP=Ne(),XP=ft(),JP=Qr(),ZP=Tm(),ek=zi(),Rm=jr(),tk=wm(),ik=nl(),Lm=km(),rk=TypeError,dn=function(a,e){this.stopped=a,this.result=e},$m=dn.prototype;Mm.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=YP(e,i),l,p,d,c,h,f,m,g=function(v){return l&&Lm(l,"normal"),new dn(!0,v)},S=function(v){return r?(XP(v),u?o(v[0],v[1],g):o(v[0],v[1])):u?o(v,g):o(v)};if(s)l=a.iterator;else if(n)l=a;else{if(p=ik(a),!p)throw new rk(JP(a)+" is not iterable");if(ZP(p)){for(d=0,c=ek(a);c>d;d++)if(h=S(a[d]),h&&Rm($m,h))return h;return new dn(!1)}l=tk(a,p)}for(f=s?a.next:l.next;!(m=KP(f,l)).done;){try{h=S(m.value)}catch(v){Lm(l,"throw",v)}if(typeof h=="object"&&h&&Rm($m,h))return h}return new dn(!1)}});var Cm=b((lO,Dm)=>{"use strict";var ak=Fe(),sk=di(),nk=Ur();Dm.exports=function(a,e,t){ak?sk.f(a,e,nk(0,t)):a[e]=t}});var Bm=b(()=>{"use strict";var ok=oe(),uk=pn(),lk=Cm();ok({target:"Object",stat:!0},{fromEntries:function(e){var t={};return uk(e,function(i,r){lk(t,i,r)},{AS_ENTRIES:!0}),t}})});var _m=b((pO,Vm)=>{"use strict";sl();Bm();var ck=li();Vm.exports=ck.Object.fromEntries});var Fm=b((hO,Om)=>{"use strict";Om.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 qm=b(()=>{"use strict";sl();var dk=Fm(),pk=re(),hk=ea(),Nm=hi();for(hn in dk)hk(pk[hn],hn),Nm[hn]=Nm.Array;var hn});var Hm=b((bO,Um)=>{"use strict";var fk=_m();qm();Um.exports=fk});var ol=b((gO,jm)=>{"use strict";var mk=Hm();jm.exports=mk});var Qm=b(()=>{"use strict"});var ul=b((yO,Wm)=>{"use strict";var ra=re(),bk=ci(),gk=oi(),fn=function(a){return bk.slice(0,a.length)===a};Wm.exports=function(){return fn("Bun/")?"BUN":fn("Cloudflare-Workers")?"CLOUDFLARE":fn("Deno/")?"DENO":fn("Node.js/")?"NODE":ra.Bun&&typeof Bun.version=="string"?"BUN":ra.Deno&&typeof Deno.version=="object"?"DENO":gk(ra.process)==="process"?"NODE":ra.window&&ra.document?"BROWSER":"REST"}()});var mn=b((TO,Gm)=>{"use strict";var Sk=ul();Gm.exports=Sk==="NODE"});var Ym=b((IO,zm)=>{"use strict";var vk=di();zm.exports=function(a,e,t){return vk.f(a,e,t)}});var Jm=b((EO,Xm)=>{"use strict";var yk=wt(),Tk=Ym(),Ik=ge(),Ek=Fe(),Km=Ik("species");Xm.exports=function(a){var e=yk(a);Ek&&e&&!e[Km]&&Tk(e,Km,{configurable:!0,get:function(){return this}})}});var eb=b((xO,Zm)=>{"use strict";var xk=jr(),wk=TypeError;Zm.exports=function(a,e){if(xk(e,a))return a;throw new wk("Incorrect invocation")}});var cl=b((wO,tb)=>{"use strict";var Ak=he(),Pk=ae(),ll=Gr(),kk=Ak(Function.toString);Pk(ll.inspectSource)||(ll.inspectSource=function(a){return kk(a)});tb.exports=ll.inspectSource});var pl=b((AO,nb)=>{"use strict";var Rk=he(),Lk=pe(),ib=ae(),$k=Zr(),Mk=wt(),Dk=cl(),rb=function(){},ab=Mk("Reflect","construct"),dl=/^\s*(?:class|function)\b/,Ck=Rk(dl.exec),Bk=!dl.test(rb),aa=function(e){if(!ib(e))return!1;try{return ab(rb,[],e),!0}catch{return!1}},sb=function(e){if(!ib(e))return!1;switch($k(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return Bk||!!Ck(dl,Dk(e))}catch{return!0}};sb.sham=!0;nb.exports=!ab||Lk(function(){var a;return aa(aa.call)||!aa(Object)||!aa(function(){a=!0})||a})?sb:aa});var ub=b((PO,ob)=>{"use strict";var Vk=pl(),_k=Qr(),Ok=TypeError;ob.exports=function(a){if(Vk(a))return a;throw new Ok(_k(a)+" is not a constructor")}});var hl=b((kO,cb)=>{"use strict";var lb=ft(),Fk=ub(),Nk=Hr(),qk=ge(),Uk=qk("species");cb.exports=function(a,e){var t=lb(a).constructor,i;return t===void 0||Nk(i=lb(t)[Uk])?e:Fk(i)}});var pb=b((RO,db)=>{"use strict";var Hk=he();db.exports=Hk([].slice)});var fb=b((LO,hb)=>{"use strict";var jk=TypeError;hb.exports=function(a,e){if(a<e)throw new jk("Not enough arguments");return a}});var fl=b(($O,mb)=>{"use strict";var Qk=ci();mb.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(Qk)});var El=b((MO,xb)=>{"use strict";var qe=re(),Wk=ru(),Gk=ji(),bb=ae(),zk=it(),Eb=pe(),gb=Gu(),Yk=pb(),Sb=zs(),Kk=fb(),Xk=fl(),Jk=mn(),yl=qe.setImmediate,Tl=qe.clearImmediate,Zk=qe.process,ml=qe.Dispatch,eR=qe.Function,vb=qe.MessageChannel,tR=qe.String,bl=0,sa={},yb="onreadystatechange",na,mi,gl,Sl;Eb(function(){na=qe.location});var Il=function(a){if(zk(sa,a)){var e=sa[a];delete sa[a],e()}},vl=function(a){return function(){Il(a)}},Tb=function(a){Il(a.data)},Ib=function(a){qe.postMessage(tR(a),na.protocol+"//"+na.host)};(!yl||!Tl)&&(yl=function(e){Kk(arguments.length,1);var t=bb(e)?e:eR(e),i=Yk(arguments,1);return sa[++bl]=function(){Wk(t,void 0,i)},mi(bl),bl},Tl=function(e){delete sa[e]},Jk?mi=function(a){Zk.nextTick(vl(a))}:ml&&ml.now?mi=function(a){ml.now(vl(a))}:vb&&!Xk?(gl=new vb,Sl=gl.port2,gl.port1.onmessage=Tb,mi=Gk(Sl.postMessage,Sl)):qe.addEventListener&&bb(qe.postMessage)&&!qe.importScripts&&na&&na.protocol!=="file:"&&!Eb(Ib)?(mi=Ib,qe.addEventListener("message",Tb,!1)):yb in Sb("script")?mi=function(a){gb.appendChild(Sb("script"))[yb]=function(){gb.removeChild(this),Il(a)}}:mi=function(a){setTimeout(vl(a),0)});xb.exports={set:yl,clear:Tl}});var Pb=b((DO,Ab)=>{"use strict";var wb=re(),iR=Fe(),rR=Object.getOwnPropertyDescriptor;Ab.exports=function(a){if(!iR)return wb[a];var e=rR(wb,a);return e&&e.value}});var xl=b((CO,Rb)=>{"use strict";var kb=function(){this.head=null,this.tail=null};kb.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}}};Rb.exports=kb});var $b=b((BO,Lb)=>{"use strict";var aR=ci();Lb.exports=/ipad|iphone|ipod/i.test(aR)&&typeof Pebble<"u"});var Db=b((VO,Mb)=>{"use strict";var sR=ci();Mb.exports=/web0s(?!.*chrome)/i.test(sR)});var Nb=b((_O,Fb)=>{"use strict";var Ji=re(),nR=Pb(),Cb=ji(),wl=El().set,oR=xl(),uR=fl(),lR=$b(),cR=Db(),Al=mn(),Bb=Ji.MutationObserver||Ji.WebKitMutationObserver,Vb=Ji.document,_b=Ji.process,bn=Ji.Promise,Rl=nR("queueMicrotask"),Xi,Pl,kl,gn,Ob;Rl||(oa=new oR,ua=function(){var a,e;for(Al&&(a=_b.domain)&&a.exit();e=oa.get();)try{e()}catch(t){throw oa.head&&Xi(),t}a&&a.enter()},!uR&&!Al&&!cR&&Bb&&Vb?(Pl=!0,kl=Vb.createTextNode(""),new Bb(ua).observe(kl,{characterData:!0}),Xi=function(){kl.data=Pl=!Pl}):!lR&&bn&&bn.resolve?(gn=bn.resolve(void 0),gn.constructor=bn,Ob=Cb(gn.then,gn),Xi=function(){Ob(ua)}):Al?Xi=function(){_b.nextTick(ua)}:(wl=Cb(wl,Ji),Xi=function(){wl(ua)}),Rl=function(a){oa.head||Xi(),oa.add(a)});var oa,ua;Fb.exports=Rl});var Ub=b((OO,qb)=>{"use strict";qb.exports=function(a,e){try{arguments.length===1?console.error(a):console.error(a,e)}catch{}}});var Sn=b((FO,Hb)=>{"use strict";Hb.exports=function(a){try{return{error:!1,value:a()}}catch(e){return{error:!0,value:e}}}});var bi=b((NO,jb)=>{"use strict";var dR=re();jb.exports=dR.Promise});var Zi=b((qO,zb)=>{"use strict";var pR=re(),la=bi(),hR=ae(),fR=wu(),mR=cl(),bR=ge(),Qb=ul(),gR=tt(),Ll=pu(),Wb=la&&la.prototype,SR=bR("species"),$l=!1,Gb=hR(pR.PromiseRejectionEvent),vR=fR("Promise",function(){var a=mR(la),e=a!==String(la);if(!e&&Ll===66||gR&&!(Wb.catch&&Wb.finally))return!0;if(!Ll||Ll<51||!/native code/.test(a)){var t=new la(function(s){s(1)}),i=function(s){s(function(){},function(){})},r=t.constructor={};if(r[SR]=i,$l=t.then(function(){})instanceof i,!$l)return!0}return!e&&(Qb==="BROWSER"||Qb==="DENO")&&!Gb});zb.exports={CONSTRUCTOR:vR,REJECTION_EVENT:Gb,SUBCLASSING:$l}});var er=b((UO,Kb)=>{"use strict";var Yb=ht(),yR=TypeError,TR=function(a){var e,t;this.promise=new a(function(i,r){if(e!==void 0||t!==void 0)throw new yR("Bad Promise constructor");e=i,t=r}),this.resolve=Yb(e),this.reject=Yb(t)};Kb.exports.f=function(a){return new TR(a)}});var bg=b(()=>{"use strict";var IR=oe(),ER=tt(),In=mn(),qt=re(),xR=li(),ar=Ne(),Xb=Ki(),Jb=il(),wR=ea(),AR=Jm(),PR=ht(),Tn=ae(),kR=$e(),RR=eb(),LR=hl(),rg=El().set,Vl=Nb(),$R=Ub(),MR=Sn(),DR=xl(),ag=Hu(),En=bi(),_l=Zi(),sg=er(),xn="Promise",ng=_l.CONSTRUCTOR,CR=_l.REJECTION_EVENT,BR=_l.SUBCLASSING,Ml=ag.getterFor(xn),VR=ag.set,tr=En&&En.prototype,gi=En,vn=tr,og=qt.TypeError,Dl=qt.document,Ol=qt.process,Cl=sg.f,_R=Cl,OR=!!(Dl&&Dl.createEvent&&qt.dispatchEvent),ug="unhandledrejection",FR="rejectionhandled",Zb=0,lg=1,NR=2,Fl=1,cg=2,yn,eg,dg,tg,pg=function(a){var e;return kR(a)&&Tn(e=a.then)?e:!1},hg=function(a,e){var t=e.value,i=e.state===lg,r=i?a.ok:a.fail,s=a.resolve,n=a.reject,u=a.domain,o,l,p;try{r?(i||(e.rejection===cg&&UR(e),e.rejection=Fl),r===!0?o=t:(u&&u.enter(),o=r(t),u&&(u.exit(),p=!0)),o===a.promise?n(new og("Promise-chain cycle")):(l=pg(o))?ar(l,o,s,n):s(o)):n(t)}catch(d){u&&!p&&u.exit(),n(d)}},fg=function(a,e){a.notified||(a.notified=!0,Vl(function(){for(var t=a.reactions,i;i=t.get();)hg(i,a);a.notified=!1,e&&!a.rejection&&qR(a)}))},mg=function(a,e,t){var i,r;OR?(i=Dl.createEvent("Event"),i.promise=e,i.reason=t,i.initEvent(a,!1,!0),qt.dispatchEvent(i)):i={promise:e,reason:t},!CR&&(r=qt["on"+a])?r(i):a===ug&&$R("Unhandled promise rejection",t)},qR=function(a){ar(rg,qt,function(){var e=a.facade,t=a.value,i=ig(a),r;if(i&&(r=MR(function(){In?Ol.emit("unhandledRejection",t,e):mg(ug,e,t)}),a.rejection=In||ig(a)?cg:Fl,r.error))throw r.value})},ig=function(a){return a.rejection!==Fl&&!a.parent},UR=function(a){ar(rg,qt,function(){var e=a.facade;In?Ol.emit("rejectionHandled",e):mg(FR,e,a.value)})},ir=function(a,e,t){return function(i){a(e,i,t)}},rr=function(a,e,t){a.done||(a.done=!0,t&&(a=t),a.value=e,a.state=NR,fg(a,!0))},Bl=function(a,e,t){if(!a.done){a.done=!0,t&&(a=t);try{if(a.facade===e)throw new og("Promise can't be resolved itself");var i=pg(e);i?Vl(function(){var r={done:!1};try{ar(i,e,ir(Bl,r,a),ir(rr,r,a))}catch(s){rr(r,s,a)}}):(a.value=e,a.state=lg,fg(a,!1))}catch(r){rr({done:!1},r,a)}}};if(ng&&(gi=function(e){RR(this,vn),PR(e),ar(yn,this);var t=Ml(this);try{e(ir(Bl,t),ir(rr,t))}catch(i){rr(t,i)}},vn=gi.prototype,yn=function(e){VR(this,{type:xn,done:!1,notified:!1,parent:!1,reactions:new DR,rejection:!1,state:Zb,value:null})},yn.prototype=Xb(vn,"then",function(e,t){var i=Ml(this),r=Cl(LR(this,gi));return i.parent=!0,r.ok=Tn(e)?e:!0,r.fail=Tn(t)&&t,r.domain=In?Ol.domain:void 0,i.state===Zb?i.reactions.add(r):Vl(function(){hg(r,i)}),r.promise}),eg=function(){var a=new yn,e=Ml(a);this.promise=a,this.resolve=ir(Bl,e),this.reject=ir(rr,e)},sg.f=Cl=function(a){return a===gi||a===dg?new eg(a):_R(a)},!ER&&Tn(En)&&tr!==Object.prototype)){tg=tr.then,BR||Xb(tr,"then",function(e,t){var i=this;return new gi(function(r,s){ar(tg,i,r,s)}).then(e,t)},{unsafe:!0});try{delete tr.constructor}catch{}Jb&&Jb(tr,vn)}IR({global:!0,constructor:!0,wrap:!0,forced:ng},{Promise:gi});dg=xR.Promise;wR(gi,xn,!1,!0);AR(xn)});var Tg=b((QO,yg)=>{"use strict";var HR=ge(),Sg=HR("iterator"),vg=!1;try{gg=0,Nl={next:function(){return{done:!!gg++}},return:function(){vg=!0}},Nl[Sg]=function(){return this},Array.from(Nl,function(){throw 2})}catch{}var gg,Nl;yg.exports=function(a,e){try{if(!e&&!vg)return!1}catch{return!1}var t=!1;try{var i={};i[Sg]=function(){return{next:function(){return{done:t=!0}}}},a(i)}catch{}return t}});var ql=b((WO,Ig)=>{"use strict";var jR=bi(),QR=Tg(),WR=Zi().CONSTRUCTOR;Ig.exports=WR||!QR(function(a){jR.all(a).then(void 0,function(){})})});var Eg=b(()=>{"use strict";var GR=oe(),zR=Ne(),YR=ht(),KR=er(),XR=Sn(),JR=pn(),ZR=ql();GR({target:"Promise",stat:!0,forced:ZR},{all:function(e){var t=this,i=KR.f(t),r=i.resolve,s=i.reject,n=XR(function(){var u=YR(t.resolve),o=[],l=0,p=1;JR(e,function(d){var c=l++,h=!1;p++,zR(u,t,d).then(function(f){h||(h=!0,o[c]=f,--p||r(o))},s)}),--p||r(o)});return n.error&&s(n.value),i.promise}})});var wg=b(()=>{"use strict";var eL=oe(),tL=tt(),iL=Zi().CONSTRUCTOR,Hl=bi(),rL=wt(),aL=ae(),sL=Ki(),xg=Hl&&Hl.prototype;eL({target:"Promise",proto:!0,forced:iL,real:!0},{catch:function(a){return this.then(void 0,a)}});!tL&&aL(Hl)&&(Ul=rL("Promise").prototype.catch,xg.catch!==Ul&&sL(xg,"catch",Ul,{unsafe:!0}));var Ul});var Ag=b(()=>{"use strict";var nL=oe(),oL=Ne(),uL=ht(),lL=er(),cL=Sn(),dL=pn(),pL=ql();nL({target:"Promise",stat:!0,forced:pL},{race:function(e){var t=this,i=lL.f(t),r=i.reject,s=cL(function(){var n=uL(t.resolve);dL(e,function(u){oL(n,t,u).then(i.resolve,r)})});return s.error&&r(s.value),i.promise}})});var Pg=b(()=>{"use strict";var hL=oe(),fL=er(),mL=Zi().CONSTRUCTOR;hL({target:"Promise",stat:!0,forced:mL},{reject:function(e){var t=fL.f(this),i=t.reject;return i(e),t.promise}})});var jl=b((tF,kg)=>{"use strict";var bL=ft(),gL=$e(),SL=er();kg.exports=function(a,e){if(bL(a),gL(e)&&e.constructor===a)return e;var t=SL.f(a),i=t.resolve;return i(e),t.promise}});var $g=b(()=>{"use strict";var vL=oe(),yL=wt(),Rg=tt(),TL=bi(),Lg=Zi().CONSTRUCTOR,IL=jl(),EL=yL("Promise"),xL=Rg&&!Lg;vL({target:"Promise",stat:!0,forced:Rg||Lg},{resolve:function(e){return IL(xL&&this===EL?TL:this,e)}})});var Mg=b(()=>{"use strict";bg();Eg();wg();Ag();Pg();$g()});var Vg=b(()=>{"use strict";var wL=oe(),AL=tt(),wn=bi(),PL=pe(),Cg=wt(),Bg=ae(),kL=hl(),Dg=jl(),RL=Ki(),Wl=wn&&wn.prototype,LL=!!wn&&PL(function(){Wl.finally.call({then:function(){}},function(){})});wL({target:"Promise",proto:!0,real:!0,forced:LL},{finally:function(a){var e=kL(this,Cg("Promise")),t=Bg(a);return this.then(t?function(i){return Dg(e,a()).then(function(){return i})}:a,t?function(i){return Dg(e,a()).then(function(){throw i})}:a)}});!AL&&Bg(wn)&&(Ql=Cg("Promise").prototype.finally,Wl.finally!==Ql&&RL(Wl,"finally",Ql,{unsafe:!0}));var Ql});var Og=b((uF,_g)=>{"use strict";Qm();Mg();Vg();var $L=Nt();_g.exports=$L("Promise","finally")});var Ng=b((lF,Fg)=>{"use strict";var ML=Og();Fg.exports=ML});var An=b((cF,qg)=>{"use strict";var DL=Ng();qg.exports=DL});var bS=b(()=>{"use strict";var m$=oe(),b$=Ui(),g$=zi(),S$=Kr(),v$=Xr();m$({target:"Array",proto:!0},{at:function(e){var t=b$(this),i=g$(t),r=S$(e),s=r>=0?r:i+r;return s<0||s>=i?void 0:t[s]}});v$("at")});var SS=b((tq,gS)=>{"use strict";bS();var y$=Nt();gS.exports=y$("Array","at")});var yS=b((iq,vS)=>{"use strict";var T$=SS();vS.exports=T$});var at=b((rq,TS)=>{"use strict";var I$=yS();TS.exports=I$});var bc=b((zU,rv)=>{"use strict";var iM=oi();rv.exports=Array.isArray||function(e){return iM(e)==="Array"}});var sv=b((YU,av)=>{"use strict";var rM=TypeError,aM=9007199254740991;av.exports=function(a){if(a>aM)throw rM("Maximum allowed index exceeded");return a}});var uv=b((KU,ov)=>{"use strict";var sM=bc(),nM=zi(),oM=sv(),uM=ji(),nv=function(a,e,t,i,r,s,n,u){for(var o=r,l=0,p=n?uM(n,u):!1,d,c;l<i;)l in t&&(d=p?p(t[l],l,e):t[l],s>0&&sM(d)?(c=nM(d),o=nv(a,e,d,c,o,s-1)-1):(oM(o+1),a[o]=d),o++),l++;return o};ov.exports=nv});var pv=b((XU,dv)=>{"use strict";var lv=bc(),lM=pl(),cM=$e(),dM=ge(),pM=dM("species"),cv=Array;dv.exports=function(a){var e;return lv(a)&&(e=a.constructor,lM(e)&&(e===cv||lv(e.prototype))?e=void 0:cM(e)&&(e=e[pM],e===null&&(e=void 0))),e===void 0?cv:e}});var fv=b((JU,hv)=>{"use strict";var hM=pv();hv.exports=function(a,e){return new(hM(a))(e===0?0:e)}});var mv=b(()=>{"use strict";var fM=oe(),mM=uv(),bM=ht(),gM=Ui(),SM=zi(),vM=fv();fM({target:"Array",proto:!0},{flatMap:function(e){var t=gM(this),i=SM(t),r;return bM(e),r=vM(t,0),r.length=mM(r,t,t,i,0,1,e,arguments.length>1?arguments[1]:void 0),r}})});var bv=b(()=>{"use strict";var yM=Xr();yM("flatMap")});var Sv=b((r1,gv)=>{"use strict";mv();bv();var TM=Nt();gv.exports=TM("Array","flatMap")});var yv=b((a1,vv)=>{"use strict";var IM=Sv();vv.exports=IM});var wa=b((s1,Tv)=>{"use strict";var EM=yv();Tv.exports=EM});var Aa=b((n1,Iv)=>{"use strict";var xM=Zr(),wM=String;Iv.exports=function(a){if(xM(a)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return wM(a)}});var gc=b((o1,Ev)=>{"use strict";Ev.exports=`
7
+ \v\f\r \xA0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028\u2029\uFEFF`});var Av=b((u1,wv)=>{"use strict";var AM=he(),PM=Ft(),kM=Aa(),vc=gc(),xv=AM("".replace),RM=RegExp("^["+vc+"]+"),LM=RegExp("(^|[^"+vc+"])["+vc+"]+$"),Sc=function(a){return function(e){var t=kM(PM(e));return a&1&&(t=xv(t,RM,"")),a&2&&(t=xv(t,LM,"$1")),t}};wv.exports={start:Sc(1),end:Sc(2),trim:Sc(3)}});var Lv=b((l1,Rv)=>{"use strict";var $M=Wu().PROPER,MM=pe(),Pv=gc(),kv="\u200B\x85\u180E";Rv.exports=function(a){return MM(function(){return!!Pv[a]()||kv[a]()!==kv||$M&&Pv[a].name!==a})}});var yc=b((c1,$v)=>{"use strict";var DM=Av().start,CM=Lv();$v.exports=CM("trimStart")?function(){return DM(this)}:"".trimStart});var Dv=b(()=>{"use strict";var BM=oe(),Mv=yc();BM({target:"String",proto:!0,name:"trimStart",forced:"".trimLeft!==Mv},{trimLeft:Mv})});var Bv=b(()=>{"use strict";Dv();var VM=oe(),Cv=yc();VM({target:"String",proto:!0,name:"trimStart",forced:"".trimStart!==Cv},{trimStart:Cv})});var _v=b((m1,Vv)=>{"use strict";Bv();var _M=Nt();Vv.exports=_M("String","trimLeft")});var Fv=b((b1,Ov)=>{"use strict";var OM=_v();Ov.exports=OM});var qv=b((g1,Nv)=>{"use strict";var FM=Fv();Nv.exports=FM});var ry=b(()=>{"use strict"});var ay=b(()=>{"use strict"});var ny=b((rQ,sy)=>{"use strict";var lD=$e(),cD=oi(),dD=ge(),pD=dD("match");sy.exports=function(a){var e;return lD(a)&&((e=a[pD])!==void 0?!!e:cD(a)==="RegExp")}});var ly=b((aQ,uy)=>{"use strict";var hD=re(),fD=pe(),oy=hD.RegExp,mD=!fD(function(){var a=!0;try{oy(".","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(oy.prototype,"flags").get.call(e);return u!==i||t!==i});uy.exports={correct:mD}});var dy=b((sQ,cy)=>{"use strict";var bD=ft();cy.exports=function(){var a=bD(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 fy=b((nQ,hy)=>{"use strict";var gD=Ne(),SD=it(),vD=jr(),py=ly(),yD=dy(),TD=RegExp.prototype;hy.exports=py.correct?function(a){return a.flags}:function(a){return!py.correct&&vD(TD,a)&&!SD(a,"flags")?gD(yD,a):a.flags}});var by=b((oQ,my)=>{"use strict";var wc=he(),ID=Ui(),ED=Math.floor,Ec=wc("".charAt),xD=wc("".replace),xc=wc("".slice),wD=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,AD=/\$([$&'`]|\d{1,2})/g;my.exports=function(a,e,t,i,r,s){var n=t+a.length,u=i.length,o=AD;return r!==void 0&&(r=ID(r),o=wD),xD(s,o,function(l,p){var d;switch(Ec(p,0)){case"$":return"$";case"&":return a;case"`":return xc(e,0,t);case"'":return xc(e,n);case"<":d=r[xc(p,1,-1)];break;default:var c=+p;if(c===0)return l;if(c>u){var h=ED(c/10);return h===0?l:h<=u?i[h-1]===void 0?Ec(p,1):i[h-1]+Ec(p,1):l}d=i[c-1]}return d===void 0?"":d})}});var vy=b(()=>{"use strict";var PD=oe(),kD=Ne(),Pc=he(),gy=Ft(),RD=ae(),LD=$e(),$D=ny(),gr=Aa(),MD=Wr(),DD=fy(),CD=by(),BD=ge(),VD=tt(),_D=BD("replace"),OD=TypeError,Ac=Pc("".indexOf),FD=Pc("".replace),Sy=Pc("".slice),ND=Math.max;PD({target:"String",proto:!0},{replaceAll:function(e,t){var i=gy(this),r,s,n,u,o,l,p,d,c,h,f=0,m="";if(LD(e)){if(r=$D(e),r&&(s=gr(gy(DD(e))),!~Ac(s,"g")))throw new OD("`.replaceAll` does not allow non-global regexes");if(n=MD(e,_D),n)return kD(n,e,i,t);if(VD&&r)return FD(gr(i),e,t)}for(u=gr(i),o=gr(e),l=RD(t),l||(t=gr(t)),p=o.length,d=ND(1,p),c=Ac(u,o);c!==-1;)h=l?gr(t(o,c,u)):CD(o,u,c,[],void 0,t),m+=Sy(u,f,c)+h,f=c+p,c=c+d>u.length?-1:Ac(u,o,c+d);return f<u.length&&(m+=Sy(u,f)),m}})});var Ty=b((cQ,yy)=>{"use strict";ry();ay();vy();var qD=Nt();yy.exports=qD("String","replaceAll")});var Ey=b((dQ,Iy)=>{"use strict";var UD=Ty();Iy.exports=UD});var wy=b((pQ,xy)=>{"use strict";var HD=Ey();xy.exports=HD});var Py=b((hQ,Ay)=>{"use strict";var jD=Kr(),QD=Aa(),WD=Ft(),GD=RangeError;Ay.exports=function(e){var t=QD(WD(this)),i="",r=jD(e);if(r<0||r===1/0)throw new GD("Wrong number of repetitions");for(;r>0;(r>>>=1)&&(t+=t))r&1&&(i+=t);return i}});var My=b((fQ,$y)=>{"use strict";var Ly=he(),zD=Mu(),ky=Aa(),YD=Py(),KD=Ft(),XD=Ly(YD),JD=Ly("".slice),ZD=Math.ceil,Ry=function(a){return function(e,t,i){var r=ky(KD(e)),s=zD(t),n=r.length,u=i===void 0?" ":ky(i),o,l;return s<=n||u===""?r:(o=s-n,l=XD(u,ZD(o/u.length)),l.length>o&&(l=JD(l,0,o)),a?r+l:l+r)}};$y.exports={start:Ry(!1),end:Ry(!0)}});var Cy=b((mQ,Dy)=>{"use strict";var eC=ci();Dy.exports=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(eC)});var By=b(()=>{"use strict";var tC=oe(),iC=My().start,rC=Cy();tC({target:"String",proto:!0,forced:rC},{padStart:function(e){return iC(this,e,arguments.length>1?arguments[1]:void 0)}})});var _y=b((SQ,Vy)=>{"use strict";By();var aC=Nt();Vy.exports=aC("String","padStart")});var Fy=b((vQ,Oy)=>{"use strict";var sC=_y();Oy.exports=sC});var qy=b((yQ,Ny)=>{"use strict";var nC=Fy();Ny.exports=nC});var Ud="2.0.141-dev.95df362c.0";var Le=(r=>(r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused",r))(Le||{}),xt=(T=>(T.MPEG="MPEG",T.DASH="DASH",T.DASH_SEP="DASH_SEP",T.DASH_SEP_VK="DASH_SEP",T.DASH_WEBM="DASH_WEBM",T.DASH_WEBM_AV1="DASH_WEBM_AV1",T.DASH_STREAMS="DASH_STREAMS",T.DASH_WEBM_VK="DASH_WEBM",T.DASH_ONDEMAND="DASH_ONDEMAND",T.DASH_ONDEMAND_VK="DASH_ONDEMAND",T.DASH_LIVE="DASH_LIVE",T.DASH_LIVE_CMAF="DASH_LIVE_CMAF",T.DASH_LIVE_WEBM="DASH_LIVE_WEBM",T.HLS="HLS",T.HLS_ONDEMAND="HLS_ONDEMAND",T.HLS_JS="HLS",T.HLS_FMP4="HLS_FMP4",T.HLS_LIVE="HLS_LIVE",T.HLS_LIVE_CMAF="HLS_LIVE_CMAF",T.WEB_RTC_LIVE="WEB_RTC_LIVE",T))(xt||{});var js=(r=>(r.NOT_AVAILABLE="NOT_AVAILABLE",r.AVAILABLE="AVAILABLE",r.CONNECTING="CONNECTING",r.CONNECTED="CONNECTED",r))(js||{}),eu=(i=>(i.HTTP1="http1",i.HTTP2="http2",i.QUIC="quic",i))(eu||{});var tu=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(tu||{}),Qs=(i=>(i.TRAFFIC_SAVING="traffic_saving",i.HIGH_QUALITY="high_quality",i.UNKNOWN="unknown",i))(Qs||{});var Fd=B(pi(),1),_I=B(Me(),1);import{assertNever as cf,assertNonNullable as Uw,isNonNullable as Zs,ValueSubject as Ou,Subject as Hw,Subscription as jw,merge as Qw,observableFrom as Ww,fromEvent as nf,map as of,tap as uf,filterChanged as Gw,isNullable as Fu,ErrorCategory as lf}from"@vkontakte/videoplayer-shared/es2024";var sf=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 en=class{constructor(e){this.connection$=new Ou(void 0);this.castState$=new Ou("NOT_AVAILABLE");this.errorEvent$=new Hw;this.realCastState$=new Ou("NOT_AVAILABLE");this.subscription=new jw;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=Zs(window.chrome?.cast),r=!!window.__onGCastApiAvailable;i?this.initializeCastApi():(window.__onGCastApiAvailable=s=>{delete window.__onGCastApiAvailable,s&&!this.isDestroyed&&this.initializeCastApi()},r||sf("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:lf.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(){Zs(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();Fu(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();Fu(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(nf(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 cf(r.sessionState)}})).add(Qw(nf(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(uf(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),of(r=>r.castState)),Ww([i.getCastState()])).pipe(Gw(),of(zw),uf(r=>{this.log({message:`realCastState$: ${r}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{let s=r==="CONNECTED",n=Zs(this.connection$.getValue());if(s&&!n){let u=i.getCurrentSession();Uw(u);let o=u.getCastDevice(),l=u.getMediaSession()?.media?.contentId;(Fu(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"?Zs(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:lf.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:r})}}},zw=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 cf(a)}};var Ld=B(Me(),1),SI=B(Yi(),1),vI=B(ol(),1);var rS=B(An(),1);import{assertNever as Ug}from"@vkontakte/videoplayer-shared/es2024";var se=(a,e=0,t=0)=>{switch(t){case 0:return a.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case 1:{if(e===0)return a;let 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:Ug(t)}return a},Ut=(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:Ug(e)}};var P=(a,e,t=!1)=>{let i=a.getTransition();(t||!i||i.to===e)&&a.setState(e)};import{isNonNullable as CL,Subject as Pn,merge as Hg}from"@vkontakte/videoplayer-shared/es2024";var F=class{constructor(e){this.transitionStarted$=new Pn;this.transitionEnded$=new Pn;this.transitionUpdated$=new Pn;this.forceChanged$=new Pn;this.stateChangeStarted$=Hg(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=Hg(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||CL(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}};import{assertNever as Kg}from"@vkontakte/videoplayer-shared/es2024";var kn=class{constructor(){this._isMiuiBrowser=!1}get current(){return this._current}get isChrome(){return this.current==="Chrome"}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 jg=B(Me(),1);var ca=()=>/Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test(navigator.appVersion??navigator.userAgent)||navigator?.userAgentData?.mobile;var Rn=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,jg.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=ca()}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 Ln=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 Ue=()=>window.ManagedMediaSource||window.MediaSource,sr=()=>!!(window.ManagedMediaSource&&window.ManagedSourceBuffer?.prototype?.appendBuffer),Qg=()=>!!(window.MediaSource&&window.SourceBuffer?.prototype?.appendBuffer),$n=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;var BL=document.createElement("video"),VL='video/mp4; codecs="avc1.42000a,mp4a.40.2"',_L='video/mp4; codecs="hev1.1.6.L93.B0"',Wg='video/webm; codecs="vp09.00.10.08"',Gg='video/webm; codecs="av01.0.00M.08"',OL='audio/mp4; codecs="mp4a.40.2"',FL='audio/webm; codecs="opus"',zg,NL=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:Gg}}),window.navigator.mediaCapabilities.decodingInfo({...a,video:{...a.video,contentType:Wg}})]);zg={DASH_WEBM_AV1:e,DASH_WEBM:t}};NL().catch(a=>{console.log(BL),console.error(a)});var Mn=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 zg}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:Qg(),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=!!Ue()?.isTypeSupported?.(VL),t=!!Ue()?.isTypeSupported?.(_L),i=!!Ue()?.isTypeSupported?.(OL);this._codecs={h264:e,h265:t,vp9:!!Ue()?.isTypeSupported?.(Wg),av1:!!Ue()?.isTypeSupported?.(Gg),aac:i,opus:!!Ue()?.isTypeSupported?.(FL),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 Yg="audio/mpeg",Dn=class{supportMp3(){return this._codecs.mp3&&this._containers.mpeg}detect(){this._audio=document.createElement("audio");try{this._containers={mpeg:!!this._audio.canPlayType?.(Yg)},this._codecs={mp3:!!Ue()?.isTypeSupported?.(Yg)}}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}};import{ValueSubject as qL}from"@vkontakte/videoplayer-shared/es2024";var Gl=class{constructor(){this.isInited$=new qL(!1);this._displayChecker=new Ln,this._deviceChecker=new Rn(this._displayChecker),this._browserChecker=new kn,this._videoChecker=new Mn(this._deviceChecker,this._browserChecker),this._audioChecker=new Dn,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)}},C=new Gl;var zl=a=>{let{containers:e,protocols:t,codecs:i,nativeHlsSupported:r}=C.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 Kg(u)}})},Yl=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 Kg(a)}},UL=a=>{let t=Object.keys(a).filter(i=>!Yl(i));return zl(t).length>0};import{assertNever as nr,assertNonNullable as Si,debounce as Xg,ErrorCategory as Jg,fromEvent as vi,isNonNullable as Zg,map as eS,merge as tS,observableFrom as HL,Subject as jL,Subscription as Kl,timeout as QL,getHighestQuality as WL}from"@vkontakte/videoplayer-shared/es2024";var GL=5,zL=5,YL=500,iS=7e3,da=class{constructor(e){this.subscription=new Kl;this.loadMediaTimeoutSubscription=new Kl;this.videoState=new F("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:nr(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:nr(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:nr(e)}break}default:nr(i)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(Yl(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 Kl;this.subscription.add(e),this.subscription.add(tS(this.videoState.stateChangeStarted$.pipe(eS(r=>`stateChangeStarted$ ${JSON.stringify(r)}`)),this.videoState.stateChangeEnded$.pipe(eS(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 jL;e.add(r.pipe(Xg(YL)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add(vi(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)>GL)&&r.next(u),s=u})),e.add(vi(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(vi(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(vi(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemotePause():this.handleRemotePlay()}),t(vi(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<zL&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),P(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:nr(n)}}),t(vi(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t(vi(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({muted:r.value})});let i=tS(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,HL(["init"])).pipe(Xg(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"),P(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),P(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"),P(this.params.desiredState.playbackState,"paused"))}handleRemotePlay(){let e=this.videoState.getState();(this.videoState.getTransition()?.to==="playing"||e==="paused")&&(this.videoState.setState("playing"),P(this.params.desiredState.playbackState,"playing"))}handleRemoteReady(){this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.params.desiredState.playbackState.getTransition()?.to==="ready"&&P(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];Si(l);let p=WL(Object.keys(l));Si(p);let d=l[p];Si(d),i=d,r="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_FMP4":case"HLS_ONDEMAND":{let l=t[e];Si(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];Si(l),i=l.url,r="application/dash+xml",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let l=t[e];Si(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];Si(l),i=se(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:Jg.VIDEO_PIPELINE,message:l,thrown:p}),p}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return nr(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 Zg(u)&&(n.metadata.title=u),Zg(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(QL(iS).subscribe(()=>s(`timeout(${iS})`)))});(0,rS.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:Jg.VIDEO_PIPELINE,message:s,thrown:r})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var fc=B(Me(),1);import{clearVideoElement as sS}from"@vkontakte/videoplayer-shared/es2024";import{clearVideoElement as KL}from"@vkontakte/videoplayer-shared/es2024";var aS=a=>{try{a.pause(),a.playbackRate=0,KL(a),a.remove()}catch(e){console.error(e)}};import{fromEvent as XL,Subscription as JL}from"@vkontakte/videoplayer-shared/es2024";var Xl=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)}},Jl=window.WeakMap?new WeakMap:new Xl,Zl=window.WeakMap?new WeakMap:new Map,ZL=(a,e=20)=>{let t=0;return XL(a,"ratechange").subscribe(i=>{t++,t>=e&&(a.currentTime=a.currentTime,t=0)})},De=(a,{audioVideoSyncRate:e,disableYandexPiP:t})=>{let i=a.querySelector("video"),r=!!i;i?sS(i):(i=document.createElement("video"),a.appendChild(i)),Jl.set(i,r);let s=new JL;return s.add(ZL(i,e)),Zl.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},Ce=a=>{Zl.get(a)?.unsubscribe(),Zl.delete(a);let t=Jl.get(a);Jl.delete(a),t?sS(a):aS(a)};var tc=B(pi(),1);import{assertNonNullable as ha,isNonNullable as bt,isNullable as i$,fromEvent as or,merge as nS,observableFrom as oS,filterChanged as uS,map as fa,Subject as lS,Subscription as r$,ValueSubject as a$,ErrorCategory as s$}from"@vkontakte/videoplayer-shared/es2024";import{isNonNullable as ec,isNullable as e$,Subscription as t$}from"@vkontakte/videoplayer-shared/es2024";var Cn=(a,e,t,{equal:i=(n,u)=>n===u,changed$:r,onError:s}={})=>{let n=a.getState(),u=e(),o=e$(r),l=new t$;return r&&l.add(r.subscribe(p=>{let d=a.getState();i(p,d)&&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},mt=(a,e,t)=>Cn(e,()=>a.loop,i=>{ec(i)&&(a.loop=i)},{onError:t}),Be=(a,e,t,i)=>Cn(e,()=>({muted:a.muted,volume:a.volume}),r=>{ec(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}),ze=(a,e,t,i)=>Cn(e,()=>a.playbackRate,r=>{ec(r)&&(a.playbackRate=r)},{changed$:t,onError:i}),pa=Cn;var n$=a=>["__",a.language,a.label].join("|"),o$=(a,e)=>{if(a.id===e)return!0;let[t,i,r]=e.split("|");return a.language===i&&a.label===r},ic=class a{constructor(e){this.available$=new lS;this.current$=new a$(void 0);this.error$=new lS;this.subscription=new r$;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:s$.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(pa(t.internalTextTracks,()=>(0,tc.default)(this.internalTracks),s=>{bt(s)&&this.setInternal(s)},{equal:(s,n)=>bt(s)&&bt(n)&&s.length===n.length&&s.every(({id:u},o)=>u===n[o].id),changed$:this.available$.pipe(fa(s=>s.filter(({type:n})=>n==="internal"))),onError:r})),this.subscription.add(pa(t.externalTextTracks,()=>(0,tc.default)(this.externalTracks),s=>{bt(s)&&this.setExternal(s)},{equal:(s,n)=>bt(s)&&bt(n)&&s.length===n.length&&s.every(({id:u},o)=>u===n[o].id),changed$:this.available$.pipe(fa(s=>s.filter(({type:n})=>n==="external"))),onError:r})),this.subscription.add(pa(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(pa(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.activeCues)}))}subscribe(){ha(this.video);let{textTracks:e}=this.video;this.subscription.add(or(e,"addtrack").subscribe(()=>{let i=this.current$.getValue();i&&this.select(i)})),this.subscription.add(nS(or(e,"addtrack"),or(e,"removetrack"),oS(["init"])).pipe(fa(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),uS((i,r)=>i.length===r.length&&i.every(({id:s},n)=>s===r[n].id))).subscribe(this.available$)),this.subscription.add(nS(or(e,"change"),oS(["init"])).pipe(fa(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),fa(i=>i&&this.htmlTextTrackToITextTrack(i).id),uS()).subscribe(this.current$));let t=i=>this.applyCueSettings(i.target?.activeCues??null);this.subscription.add(or(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(or(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;bt(t.align)&&(r.align=t.align),bt(t.position)&&(r.position=t.position),bt(t.size)&&(r.size=t.size),bt(t.line)&&(r.line=t.line)}}htmlTextTracksAsArray(e=!1){ha(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:n$(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){ha(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(i$(e)||!o$(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){ha(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){ha(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)}},Ye=ic;var yi=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 cS=a=>{let e=a;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e?.parentNode;return e??void 0},rc=a=>{let e=cS(a);return!!(e&&e.fullscreenElement&&e.fullscreenElement===a)},dS=a=>{let e=cS(a);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===a)};import{fromEvent as Ee,map as gt,merge as Bn,filterChanged as hS,isNonNullable as fS,Subject as l$,filter as ac,mapTo as sc,combine as c$,once as d$,shareReplay as xe,throttle as p$,ErrorCategory as h$,ValueSubject as mS,Subscription as f$}from"@vkontakte/videoplayer-shared/es2024";var u$=3,pS=(a,e,t=u$)=>{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 Ve=a=>{let e=x=>Ee(a,x).pipe(sc(void 0),xe(1)),t=new f$,i=()=>t.unsubscribe(),r=Bn(Ee(a,"progress"),Ee(a,"timeupdate")).pipe(gt(()=>pS(a.buffered,a.currentTime)),xe(1)),s=C.browser.isSafari?c$({play:e("play").pipe(d$()),playing:e("playing")}).pipe(sc(void 0),xe(1)):e("playing"),n=Ee(a,"volumechange").pipe(gt(()=>({muted:a.muted,volume:a.volume})),xe(1)),u=Ee(a,"ratechange").pipe(gt(()=>a.playbackRate),xe(1)),o=Ee(a,"error").pipe(ac(()=>!!(a.error||a.played.length)),gt(()=>{let x=a.error;return{id:x?`MediaError#${x.code}`:"HtmlVideoError",category:h$.VIDEO_PIPELINE,message:x?x.message:"Error event from HTML video element",thrown:a.error??void 0}}),xe(1)),l=Ee(a,"timeupdate").pipe(gt(()=>a.currentTime),xe(1)),p=["waiting","seeking","seeked","timeupdate"],d=new l$,c=.3,h;t.add(Bn(...p.map(x=>Ee(a,x))).subscribe(x=>{let q=a.currentTime;a.loop&&fS(h)&&fS(q)&&h>=a.duration-c&&q<=c&&d.next(h),h=q}));let f=e("pause").pipe(ac(()=>!a.error&&h!==a.duration),xe(1)),m=Ee(a,"enterpictureinpicture").pipe(xe(1)),g=Ee(a,"leavepictureinpicture").pipe(xe(1)),S=new mS(dS(a));t.add(m.subscribe(()=>S.next(!0))),t.add(g.subscribe(()=>S.next(!1)));let v=new mS(rc(a)),I=Ee(a,"fullscreenchange").pipe(xe(1));t.add(I.pipe(gt(()=>rc(a))).subscribe(v));let T=.1,A=1e3,R=Ee(a,"timeupdate").pipe(gt(x=>a.duration-a.currentTime<T),hS(),xe(1)),L=Bn(R.pipe(ac(x=>!a.loop&&x)),Ee(a,"ended")).pipe(p$(A),sc(void 0),xe(1)),D=Bn(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(x=>Ee(a,x)),R.pipe(gt(x=>({type:x?"ended":"unknown"})))).pipe(gt(x=>C.browser.isFirefox&&x.type==="ended"?a.readyState<2:a.readyState<3),hS(),xe(1));return{playing$:s,pause$:f,canplay$:e("canplay"),ended$:L,looped$:d,error$:o,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:l,durationChange$:Ee(a,"durationchange").pipe(gt(()=>a.duration),xe(1)),isBuffering$:D,currentBuffer$:r,volumeState$:n,playbackRateState$:u,inPiP$:S,inFullscreen$:v,enterPip$:m,leavePip$:g,destroy:i}};import{VideoQuality as Ht}from"@vkontakte/videoplayer-shared/es2024";var jt=a=>{switch(a){case"mobile":return Ht.Q_144P;case"lowest":return Ht.Q_240P;case"low":return Ht.Q_360P;case"sd":case"medium":return Ht.Q_480P;case"hd":case"high":return Ht.Q_720P;case"fullhd":case"full":return Ht.Q_1080P;case"quadhd":case"quad":return Ht.Q_1440P;case"ultrahd":case"ultra":return Ht.Q_2160P}};var Ae=B(at(),1),oc=B(Me(),1),Ii=B(Yi(),1);import{isNonNullable as K,isNullable as Fn,now as MS,isHigher as Nn,isHigherOrEqual as Ti,isInvariantQuality as qn,isLowerOrEqual as lr,videoSizeToQuality as DS,assertNotEmptyArray as Un,assertNonNullable as CS}from"@vkontakte/videoplayer-shared/es2024";var nc=!1,kt={},IS=a=>{nc=a},ES=()=>{kt={}},xS=a=>{a(kt)},ma=(a,e)=>{nc&&(kt.meta=kt.meta??{},kt.meta[a]=e)},we=class{constructor(e){this.name=e}next(e){if(!nc)return;kt.series=kt.series??{};let t=kt.series[this.name]??[];t.push([Date.now(),e]),kt.series[this.name]=t}};import{isHigher as E$,isHigherOrEqual as lq,isLower as wS,isLowerOrEqual as cq,isNonNullable as Vn,isNullable as x$,videoHeightToQuality as _n}from"@vkontakte/videoplayer-shared/es2024";function AS(a,e,t){return!a.max&&a.min===e?"high_quality":!a.min&&a.max===t?"traffic_saving":"unknown"}function ur(a,e,t){return x$(a)||Vn(a.min)&&Vn(a.max)&&wS(a.max,a.min)||Vn(a.min)&&e&&E$(a.min,e)||Vn(a.max)&&t&&wS(a.max,t)}function PS({limits:a,highestAvailableHeight:e,lowestAvailableHeight:t}){return ur({max:a?.max?_n(a.max):void 0,min:a?.min?_n(a.min):void 0},e?_n(e):void 0,t?_n(t):void 0)}var BS=new we("best_bitrate"),Hn=(a,e,t)=>(e-t)*Math.pow(2,-10*a)+t;var cr=a=>(e,t)=>a*(Number(e.bitrate)-Number(t.bitrate)),Qt=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=MS()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},jn='Assertion "ABR Tracks is empty array" failed',On=new WeakMap,kS=new WeakMap,RS=new WeakMap,ba=(a,e,t,i)=>{let r=[...e].sort(cr(1)),s=[...t].sort(cr(1)),n=s.filter(o=>K(o.bitrate)&&K(a.bitrate)?a.bitrate/o.bitrate>i:!0),u=(0,Ae.default)(s,Math.round(s.length*r.indexOf(a)/(r.length+1)))??(0,Ae.default)(s,-1);return u&&(0,oc.default)(n,u)?u:n.length?(0,Ae.default)(n,-1):(0,Ae.default)(s,0)},ga=(a,e,t,i)=>{let r=On.get(e);r||(r=[...e].sort(cr(1)),On.set(e,r));let s=On.get(t);s||(s=[...t].sort(cr(1)),On.set(t,s));let n=RS.get(a);n||(n=s.filter(o=>K(o.bitrate)&&K(a.bitrate)?a.bitrate/o.bitrate>i:!0),RS.set(a,n));let u=(0,Ae.default)(s,Math.round(s.length*r.indexOf(a)/(r.length+1)))??(0,Ae.default)(s,-1);return u&&(0,oc.default)(n,u)?u:n.length?(0,Ae.default)(n,-1):(0,Ae.default)(s,0)},LS=a=>"quality"in a,Qn=(a,e,t,i)=>{let r=K(i?.last?.bitrate)&&K(t?.bitrate)&&i.last.bitrate<t.bitrate?a.trackCooldownIncreaseQuality:a.trackCooldownDecreaseQuality,s=t&&i&&i.history[t.id]&&MS()-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=LS(n)?"video":"audio",o=LS(n)?n.quality:n.bitrate;return e({message:`
8
8
  [last ${u} selected] ${o}
9
9
  `}),n}return i?.recordSwitch(t),t},w$=(a,e)=>Math.log(e)/Math.log(a),VS=({tuning:a,container:e,limits:t,panelSize:i})=>{let r=a.containerSizeFactor;if(i)return{containerSizeLimit:i,containerSizeFactor:r};if(a.usePixelRatio&&C.display.pixelRatio){let s=C.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=w$(n,u*s+o)+l;Number.isFinite(p)&&(r*=p)}}return K(t?.min)&&Ti(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}},$S=new WeakMap,St=(a,{container:e,estimatedThroughput:t,tuning:i,limits:r,reserve:s=0,forwardBufferHealth:n,playbackRate:u,current:o,history:l,visible:p,droppedVideoMaxQualityLimit:d,stallsVideoMaxQualityLimit:c,stallsPredictedThroughput:h,abrLogger:f,panelSize:m})=>{Un(a,jn);let{containerSizeFactor:g,containerSizeLimit:S}=VS({container:e,tuning:i,limits:r,panelSize:m}),v=i.considerPlaybackRate&&K(u)?u:1,I=$S.get(a);I||(I=a.filter(y=>!qn(y.quality)).sort((y,E)=>Nn(y.quality,E.quality)?-1:1),$S.set(a,I));let T=(0,Ae.default)(I,-1)?.quality,A=(0,Ae.default)(I,0)?.quality,R=ur(r,A,T),L=v*Hn(n??.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),w={},D=null;for(let y of I){let E=!0;if(S)if(y.size)E=y.size.width<=S.width&&y.size.height<=S.height;else{let j=S&&DS(S);E=j?lr(y.quality,j):!0}if(!E){w[y.quality]="FitsContainer";continue}let z=h||t,M=K(z)&&isFinite(z)&&K(y.bitrate)?z-s>=y.bitrate*L:!0,H=r?.min===y.quality;if(!M&&!H){w[y.quality]="FitsThroughput";continue}if(i.lazyQualitySwitch&&K(i.minBufferToSwitchUp)&&o&&!qn(o.quality)&&(n??0)<i.minBufferToSwitchUp&&Nn(y.quality,o.quality)){w[y.quality]="Buffer";continue}if(!!d&&Ti(y.quality,d)&&!H){w[y.quality]="DroppedFramesLimit";continue}if(!!c&&Ti(y.quality,c)&&!H){w[y.quality]="StallsLimit";continue}let me=R||(Fn(r?.max)||lr(y.quality,r.max))&&(Fn(r?.min)||Ti(y.quality,r.min)),be=K(p)&&!p?lr(y.quality,i.backgroundVideoQualityLimit):!0;if(!me||!be){w[y.quality]="FitsQualityLimits";continue}D||(D=y)}D&&D.bitrate&&BS.next(D.bitrate);let x=D??(0,Ae.default)(I,-1)??a[0],q=l?.last,$=Qn(i,f,x,l);return K(l)&&$.quality!==q?.quality&&f({message:`
10
10
  [VIDEO TRACKS ABR]
@@ -177,4 +177,4 @@ void main(void) {
177
177
  }
178
178
  `;var Pr=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 Eo(this.params.fov,this.params.orientation),this.cameraRotationManager=new xo(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(pT,this.gl.VERTEX_SHADER),i=this.createShader(hT,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,d=e-i,c=t+r;return[s,n,u,o,l,p,d,c]}updateTextureMappingBuffer(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([...this.calculateTexturePosition()]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}updateFrameSize(){this.frameWidth=this.sourceVideoElement.videoWidth,this.frameHeight=this.sourceVideoElement.videoHeight}createCanvas(){let e=document.createElement("canvas");return e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e}};import{isNullable as CC,now as ls,once as BC,Subscription as VC,ValueSubject as Wc,isNonNullable as _C,safeStorage as Gc,filterChanged as OC}from"@vkontakte/videoplayer-shared/es2024";var wo="stalls_manager_metrics",zc="stalls_manager_abr_params",fT="stalls_manager_default_tuning_abr_params",Yc=class{constructor(){this.isSeeked$=new Wc(!1);this.isBuffering$=new Wc(!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 VC;this.severeStallOccurred$=new Wc(!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.resetStoredAbrParamsIfNeeded(),this.subscribe(e)}get videoMaxQualityLimit(){return this.maxQualityLimit}get predictedThroughput(){return this.predictedThroughputWithoutData}get abrTuningParams(){let e=this.tuning.enabled?this.getStoredData(zc):{};return{...this.abrParams,...e}}set lastVideoTrackSelected(e){this.lastUniqueVideoTrackSelected?.id!==e.id&&(this.lastUniqueVideoTrackSelected=e,this.lastUniqueVideoTrackSelectedTimestamp=ls(),this.currentStallsCount=0)}destroy(){window.clearTimeout(this.qualityRestrictionTimer),this.subscription.unsubscribe(),this.currentStallDuration$.getValue()!==0&&this.updateStallData();let e=(ls()-this.providerStartWatchingTimestamp-this.sumStallsDuration)/1e3,t=this.sumStallsDuration;this.addStallInfoToHistory(e,t),this.updateStoredAbrParams()}resetStoredAbrParamsIfNeeded(){let{bitrateFactorAtEmptyBuffer:e,bitrateFactorAtFullBuffer:t,containerSizeFactor:i}={...this.getStoredData(fT)},{bitrateFactorAtEmptyBuffer:r,bitrateFactorAtFullBuffer:s,containerSizeFactor:n}={...this.abrParams};this.tuning.enabled&&e===r&&t===s&&i===n||(this.removeStoredData(zc),this.setStoredData(fT,{bitrateFactorAtEmptyBuffer:r,bitrateFactorAtFullBuffer:s,containerSizeFactor:n}))}updateStoredAbrParams(){let e=[],t=this.getStoredData(wo,"[]");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(wo,[]),this.setStoredData(zc,r)}calculateOptimalAbrParams(e,t){let{targetStallsDurationPerTvt:i,deviationStallsDurationPerTvt:r,criticalStallsDurationPerTvt:s,abrAdjustingSpeed:n,significantTvt:u,stallsMetricsHistoryLength:o}=this.tuning,l=n*Math.min(t/(u*o),1),p=this.abrTuningParams;return e<i-r?p={bitrateFactorAtEmptyBuffer:Math.max(p.bitrateFactorAtEmptyBuffer-l,this.abrParams.minBitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.max(p.bitrateFactorAtFullBuffer-l,this.abrParams.minBitrateFactorAtFullBuffer),containerSizeFactor:Math.min(p.containerSizeFactor+l,this.abrParams.maxContainerSizeFactor)}:e>i+r&&(p={bitrateFactorAtEmptyBuffer:Math.min(p.bitrateFactorAtEmptyBuffer+l,this.abrParams.maxBitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.min(p.bitrateFactorAtFullBuffer+l,this.abrParams.maxBitrateFactorAtFullBuffer),containerSizeFactor:Math.max(p.containerSizeFactor-l,this.abrParams.minContainerSizeFactor)}),e>s&&(p={bitrateFactorAtEmptyBuffer:Math.max(p.bitrateFactorAtEmptyBuffer,this.abrParams.bitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.max(p.bitrateFactorAtFullBuffer,this.abrParams.bitrateFactorAtFullBuffer),containerSizeFactor:Math.min(p.containerSizeFactor,this.abrParams.containerSizeFactor)}),p}getStoredData(e,t="{}"){return JSON.parse(Gc.get(e)??t)}setStoredData(e,t){Gc.set(e,JSON.stringify(t))}removeStoredData(e){Gc.remove(e)}addStallInfoToHistory(e,t){if(e<this.tuning.minTvtToBeCounted||e>this.tuning.maxTvtToBeCounted||e*1e3<t)return;let i=this.getStoredData(wo,"[]"),r=t/e,s=i.length?$t(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(wo,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(BC()).subscribe(t=>this.providerStartWatchingTimestamp=ls())),this.subscription.add(this.currentStallDuration$.pipe(OC()).subscribe(t=>{let{stallDurationNoDataBeforeQualityDecrease:i,stallCountBeforeQualityDecrease:r,resetQualityRestrictionTimeout:s,ignoreStallsOnSeek:n}=this.tuning;if(CC(this.lastUniqueVideoTrackSelected)||n&&this.isSeeked$.getValue())return;let u=this.rtt$.getValue(),o=this.throughput$.getValue(),l=this.videoLastDataObtainedTimestamp$.getValue(),p=ls(),d=r&&this.currentStallsCount>=r,c=i&&p-this.lastUniqueVideoTrackSelectedTimestamp>=i+u&&p-l>=i+u&&t>=i;(d||c)&&(this.severeStallOccurred$.next(!0),window.clearTimeout(this.qualityRestrictionTimer),this.maxQualityLimit=this.lastUniqueVideoTrackSelected.quality,_C(this.lastUniqueVideoTrackSelected.bitrate)&&o>this.lastUniqueVideoTrackSelected.bitrate&&(this.predictedThroughputWithoutData=this.lastUniqueVideoTrackSelected.bitrate)),!t&&ls()-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}))}},Ao=Yc;import{combine as FC,map as NC,observeElementSize as qC,Subscription as UC,ValueSubject as Kc,noop as HC}from"@vkontakte/videoplayer-shared/es2024";var Po=class{constructor(){this.subscription=new UC;this.pipSize$=new Kc(void 0);this.videoSize$=new Kc(void 0);this.elementSize$=new Kc(void 0);this.pictureInPictureWindowRemoveEventListener=HC}connect({observableVideo:e,video:t}){let i=r=>{let s=r.target;this.pipSize$.next({width:s.width,height:s.height})};this.subscription.add(qC(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(FC({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe(NC(({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()}};import{filter as mT,map as jC,once as bT}from"@vkontakte/videoplayer-shared/es2024";var kr=({subscription:a,desiredState:e,videoElement$:t,observableVideo:i})=>{if(!C.browser.isSafari)return;let r=0,s=!1;a.add(e.volume.stateChangeStarted$.pipe(jC(()=>{let n=e.volume.getTransition(),u=t.getValue();return!u||!n?!1:!n.to.muted&&u.muted}),mT(n=>!!n),bT()).subscribe(()=>{r=performance.now(),s=!0})),a.add(i.playbackRateState$.pipe(mT(()=>s),bT()).subscribe(()=>{let n=t.getValue(),u=e.playbackRate.getState();n&&u!==n.playbackRate&&performance.now()-r<1e3&&(n.playbackRate=u)}))};var Ri=class{constructor(e){this.subscription=new JC;this.videoState=new F("stopped");this.observableVideo=null;this.droppedFramesManager=new pr;this.stallsManager=new Ao;this.elementSizeManager=new Po;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new Qt;this.audioTrackSwitchHistory=new Qt;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"),P(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"),P(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="ready"&&P(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"&&P(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&P(this.params.desiredState.playbackState,"paused");return;default:return WC(e)}}};this.init3DScene=e=>{if(this.scene3D)return;this.scene3D=new Pr(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 Ye(e.source.url),this.params=e,this.video=De(e.container,e.tuning),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Se(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 Io({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;XC(this.observableVideo)&&(this.observableVideo=Ve(this.video),this.subscription.add(()=>this.observableVideo?.destroy()));let i=this.constructor.name,r=n=>{e.error$.next({id:i,category:gT.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(Xc(d=>!!d.length),vT()).subscribe(d=>{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:d})}));let n=this.params.desiredState.seekState.stateChangeEnded$.pipe(ds(d=>d.to.state!=="none"),cs());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$}),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.lastConnectionType$,e.httpConnectionType$),s(this.player.lastConnectionReused$,e.httpConnectionReused$),s(this.player.isLive$,e.isLive$),s(this.player.lastRequestFirstBytes$.pipe(Xc(ST),vT()),e.firstBytesEvent$),s(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),s(this.videoState.stateChangeEnded$.pipe(ds(d=>d.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(mt(this.video,t.isLooped,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),kr({subscription:this.subscription,desiredState:t,videoElement$:this.params.output.element$,observableVideo:i}),this.subscription.add(Be(this.video,t.volume,i.volumeState$,r)),this.subscription.add(ze(this.video,t.playbackRate,i.playbackRateState$,r)),this.elementSizeManager.connect({video:this.video,observableVideo:i}),s(Ke(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),P(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),P(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"),P(t.playbackState,"paused")})),this.subscription.add(this.player.manifestRequested.subscribe(this.params.output.manifestRequested$)).add(this.player.manifestReceived.subscribe(this.params.output.manifestReceived$)).add(this.player.firstBytesRequested.subscribe(this.params.output.firstBytesRequested$)).add(this.player.firstBytesReceived.subscribe(this.params.output.firstBytesReceived$)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:d})=>{if(d==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let c=this.player.getStreams(),h=this.player.getCodecs();if(GC(c,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let m=[];for(let g of c.audio){m.push(Mc(g));let S=[];for(let v of g.representations){let I=Ky(v);S.push(I),this.audioTracksMap.set(I,{stream:g,representation:v})}this.audioStreamsMap.set(g,S)}this.params.output.availableAudioStreams$.next(m)}let f=[];for(let m of c.video){f.push(Dc(m));let g=[];for(let S of m.representations){let v=es({...S,streamId:m.id});v&&(g.push(v),this.videoTracksMap.set(v,{stream:m,representation:S}))}this.videoStreamsMap.set(m,g)}this.params.output.availableVideoStreams$.next(f);for(let m of c.text)for(let g of m.representations){let S=Xy(m,g);this.textTracksMap.set(S,{stream:m,representation:g})}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 d==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},r));let u=ps(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$,KC(this.video,"progress")).pipe(Xc(()=>this.videoTracksMap.size>0)),{abrThrottle:o}=this.params.tuning.dash;o&&(u=u.pipe(ZC(o))),this.subscription.add(u.subscribe(async()=>{let d=this.player.state$.getState(),c=this.player.state$.getTransition();if(d!=="manifest_ready"&&d!=="running"||c)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let h=this.selectVideoAudioRepresentations();if(!h)return;let[f,m]=h,g=[...this.videoTracksMap.keys()].find(v=>this.videoTracksMap.get(v)?.representation.id===f.id);ST(g)&&(this.stallsManager.lastVideoTrackSelected=g);let S=this.params.desiredState.autoVideoTrackLimits.getTransition();if(S&&this.params.output.autoVideoTrackLimits$.next(S.to),d==="manifest_ready")await this.player.initRepresentations(f.id,m?.id,this.params.sourceHls);else if(await this.player.switchRepresentation("video",f.id),m){let v=!!t.audioStream.getTransition();await this.player.switchRepresentation("audio",m.id,v)}},r)),this.subscription.add(zC({videoState:this.videoState.stateChangeEnded$,autoVideoTrackState:ps(ko([t.autoVideoTrackSwitching.getState()]),t.autoVideoTrackSwitching.stateChangeEnded$.pipe(ds(d=>d.to)))}).pipe(ds(({videoState:d,autoVideoTrackState:c})=>d.to!=="stopped"&&c),cs()).subscribe(d=>this.player.setSmartRepresentationSwitch(d))),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:d})=>{this.scene3D&&d&&this.scene3D.pointCameraTo(d.x,d.y)})),this.subscription.add(this.elementSizeManager.subscribe(d=>{this.scene3D&&d&&this.scene3D.setViewportSize(d.width,d.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(cs()).subscribe(d=>{let c=[...this.videoTracksMap.entries()].find(([,{representation:S}])=>S.id===d);if(!c){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[h,{stream:f}]=c,m=this.params.desiredState.videoStream.getTransition();m&&m.to&&m.to.id===f.id&&this.params.desiredState.videoStream.setState(m.to),e.currentVideoTrack$.next(h),e.currentVideoStream$.next(Dc(f));let g=this.player.calculateDurationFromSegments();g&&this.params.output.duration$.next(g/1e3)},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(cs()).subscribe(d=>{let c=[...this.audioTracksMap.entries()].find(([,{representation:g}])=>g.id===d);if(!c){e.currentAudioStream$.next(void 0);return}let[h,{stream:f}]=c,m=this.params.desiredState.audioStream.getTransition();m&&m.to&&m.to.id===f.id&&this.params.desiredState.audioStream.setState(m.to),e.currentAudioStream$.next(Mc(f))},r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(d=>{if(d?.is3dVideo&&this.params.tuning.spherical?.enabled)try{this.init3DScene(d),e.is3DVideo$.next(!0)}catch(c){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${c}`})}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(ds(({to:d})=>d==="ready"),cs());this.subscription.add(ps(l,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,ko(["init"])).subscribe(()=>{let d=t.autoVideoTrackSwitching.getState(),h=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:d?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(h)})),this.subscription.add(ps(l,this.player.state$.stateChangeEnded$,ko(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let p=ps(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,ko(["init"])).pipe(YC(0));this.subscription.add(p.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?ga:ba,t=this.params.tuning.useNewAutoSelectVideoTrack?zn:Gn,i=this.params.tuning.useNewAutoSelectVideoTrack?St:Wn,{desiredState:r,output:s}=this.params,n=r.autoVideoTrackSwitching.getState(),u=r.videoTrack.getState()?.id,o=[...this.videoTracksMap.keys()].find(({id:w})=>w===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 d=[...this.videoStreamsMap.keys()].find(({id:w})=>w===p.id),c=d&&this.videoStreamsMap.get(d);if(!c)return;let h=ve(this.video.buffered,this.video.currentTime*1e3),f;this.player.isActiveLive$.getValue()?f=this.player.isLowLatency$.getValue()?this.params.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.params.tuning.dashCmafLive.normalizedLiveMinBufferSize:this.player.isLive$.getValue()?f=this.params.tuning.dashCmafLive.normalizedTargetMinBufferSize:f=n?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;let m=(this.video.duration*1e3||1/0)-this.video.currentTime*1e3,g=Math.min(h/Math.min(f,m||1/0),1),S=r.audioStream.getState()??(this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0),v=[...this.audioStreamsMap.keys()].find(({id:w})=>w===S?.id)??this.audioStreamsMap.keys().next().value,I=0;if(v){if(o&&!n){let w=e(o,c,this.audioStreamsMap.get(v)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);I=Math.max(I,w?.bitrate??-1/0)}if(l){let w=e(l,c,this.audioStreamsMap.get(v)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);I=Math.max(I,w?.bitrate??-1/0)}}let T=o;(n||!T)&&(T=i(c,{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:I,forwardBufferHealth:g,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 A=v&&t(T,c,this.audioStreamsMap.get(v)??[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.stallsManager.abrTuningParams,forwardBufferHealth:g,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),R=this.videoTracksMap.get(T)?.representation,L=A&&this.audioTracksMap.get(A)?.representation;if(R&&L)return[R,L];if(R&&!L&&this.audioTracksMap.size===0)return[R,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){_e(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:gT.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),Ce(this.video),this.tracer.end()}};var hs=class extends Ri{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)}};import{combine as Jc,merge as yT,filter as TT,filterChanged as IT,isNullable as Zc,map as ET,ValueSubject as ed,isNonNullable as eB}from"@vkontakte/videoplayer-shared/es2024";var fs=class extends Ri{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 ed(1);n(r.playbackRateState$,u),this.params.tuning.dashCmafLive.catchupLiveForMutedInactiveTab&&this.subscription.add(i.elementVisible$.pipe(IT()).subscribe(o=>{let l=i.position$.getValue(),p=i.volume$.getValue(),d=!p.volume||p.muted;!o&&!l&&d?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(ET(o=>o.to)).subscribe(this.player.isLowLatency$)).add(Jc({liveBufferTime:i.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(ET(({liveBufferTime:o,liveAvailabilityStartTime:l})=>o&&l?o+l:void 0)).subscribe(i.liveTime$)).add(this.player.liveStreamStatus$.pipe(TT(o=>eB(o))).subscribe(o=>i.isLiveEnded$.next(o!=="active"&&i.position$.getValue()===0))).add(Jc({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:yT(r.playbackRateState$,new ed(1))}).pipe(TT(({liveStreamStatus:o,liveDuration:l})=>o==="active"&&!!l)).subscribe(({liveDuration:o,playbackRate:l})=>{let p=i.liveBufferTime$.getValue(),d=i.position$.getValue(),{playbackCatchupSpeedup:c}=this.params.tuning.dashCmafLive.lowLatency;d||l<1-c||this.video.paused||Zc(p)||(t=o-p)})).add(Jc({time:i.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:yT(r.playbackRateState$,new ed(1))}).pipe(IT((o,l)=>this.player.liveStreamStatus$.getValue()==="active"?o.liveDuration===l.liveDuration:o.time===l.time)).subscribe(({time:o,liveDuration:l,playbackRate:p})=>{let d=i.position$.getValue(),{playbackCatchupSpeedup:c}=this.params.tuning.dashCmafLive.lowLatency;if(!d&&!this.video.paused&&p>=1-c||Zc(o)||Zc(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=Jy(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)})}};import{assertNever as PB,assertNonNullable as kB,combine as RB,debounce as LB,ErrorCategory as NT,filter as bd,filterChanged as xs,fromEvent as $B,isNonNullable as qT,isNullable as MB,map as ws,merge as As,observableFrom as Fo,once as UT,Subscription as DB}from"@vkontakte/videoplayer-shared/es2024";var FT=B(Me(),1),fd=B(wa(),1);import{abortable as cd,assertNonNullable as $r,combine as Mr,ErrorCategory as ut,filter as Vo,filterChanged as Ts,flattenObject as Is,fromEvent as It,getTraceSubscriptionMethod as gB,interval as dd,isNonNullable as Es,isNullable as _T,map as Dr,merge as Ci,now as pd,Subject as ei,Subscription as hd,tap as SB,throttle as OT,ValueSubject as te}from"@vkontakte/videoplayer-shared/es2024";var Mo=B(Me(),1),Di=B(at(),1),Do=B(wa(),1);var DT=B(An(),1);import{assertNever as tB,ErrorCategory as xT,Subject as wT}from"@vkontakte/videoplayer-shared/es2024";var iB=18,AT=!1;try{AT=C.browser.isSafari&&!!C.browser.safariVersion&&C.browser.safariVersion<=iB}catch(a){console.error(a)}var td=class{constructor(e){this.bufferFull$=new wT;this.error$=new wT;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:xT.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)};AT&&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:xT.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:tB(t)}}},PT=td;import{abortable as Jt,assertNonNullable as ke,ErrorCategory as $i,fromEvent as nd,getExponentialDelay as od,isHigher as oB,isNonNullable as Zt,isNullable as ce,now as $o,once as uB,Subject as lB,Subscription as cB,ValueSubject as Mi}from"@vkontakte/videoplayer-shared/es2024";var id=B(at(),1);import{videoSizeToQuality as rB,throttleFn as aB}from"@vkontakte/videoplayer-shared/es2024";var ms=({id:a,width:e,height:t,bitrate:i,fps:r,quality:s,streamId:n})=>{let u=(s?jt(s):void 0)??rB({width:e,height:t});return u&&{id:a,quality:u,bitrate:i,size:{width:e,height:t},fps:r,streamId:n}},kT=({id:a,bitrate:e})=>({id:a,bitrate:e}),RT=({language:a,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:a,label:e}),LT=({language:a,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:a,label:e}),rd=({id:a,language:e,label:t,codecs:i,isDefault:r})=>({id:a,language:e,label:t,codec:(0,id.default)(i.split("."),0),isDefault:r}),ad=({id:a,language:e,label:t,hdr:i,codecs:r})=>({id:a,language:e,hdr:i,label:t,codec:(0,id.default)(r.split("."),0)}),sd=a=>"url"in a,je=a=>a.type==="template";var $T=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},MT=a=>{let e=!1,t=aB(()=>{e=!0},a);return()=>{try{return t(),e}finally{e=!1}}};import{fromEvent as sB,Subscription as nB}from"@vkontakte/videoplayer-shared/es2024";var Ro=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 Lo=class{constructor(e,t){this.lastUpdateTs=0;this.lastCallTs=0;this.prevRanges=[];this.subscription=new nB;this.mediaSource=e,this.sourceBuffer=t,this.subscription.add(sB(this.sourceBuffer,"updateend").subscribe(()=>this.updateend()))}updateend(){if(!V(this.mediaSource,this.sourceBuffer))return;let{prevRanges:e}=this,t=Ro(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 bs=class{constructor(e,t,i,{fetcher:r,tuning:s,getCurrentPosition:n,isActiveLowLatency:u,compatibilityMode:o=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new Mi(0);this.currentLowLatencySegmentLength$=new Mi(0);this.currentSegmentLength$=new Mi(0);this.onLastSegment$=new Mi(!1);this.fullyBuffered$=new Mi(!1);this.playingRepresentation$=new Mi(void 0);this.playingRepresentationInit$=new Mi(void 0);this.error$=new lB;this.gaps=[];this.subscription=new cB;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new X;this.switchAbortController=new X;this.destroyAbortController=new X;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=Jt(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);ke(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new PT(this.sourceBuffer),this.sourceBufferBufferedDiff=new Lo(this.mediaSource,this.sourceBuffer),this.subscription.add(nd(this.sourceBuffer,"updateend").subscribe(()=>{this.maintain()})),this.subscription.add(nd(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:$i.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let u=this.getCurrentPosition();if(!this.sourceBuffer||!u||!V(this.mediaSource,this.sourceBuffer))return;let o=Math.min(this.bufferLimit,mr(this.sourceBuffer.buffered)*.8);this.bufferLimit=o;let l=ve(this.sourceBuffer.buffered,u),p=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(u,n*2,l<p).catch(d=>{this.handleAsyncError(d,"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);ke(i,"No init buffer for starting representation"),ke(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=Jt(this.destroyAbortController.signal,async function*(e,t=!1){if(!V(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);ke(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if(ce(s)||ce(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),ke(r,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!V(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();Zt(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=Jt(this.destroyAbortController.signal,async function*(e,t=!1){if(!V(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);ke(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if(ce(s)||ce(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),ke(r,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!V(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();Zt(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=Jt(this.destroyAbortController.signal,async function*(e){let t=(0,Do.default)(e,o=>o.representations)??[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let o of this.representations.keys()){let l=t.find(c=>c.id===o);l&&this.representations.set(o,l);let p=this.representations.get(o);if(!p||!je(p.segmentReference))return;let d=this.getActualLiveStartingSegments(p.segmentReference);this.segments.set(p.id,d)}let i=this.switchingToRepresentationId??this.downloadingRepresentationId,r=this.representations.get(i);ke(r);let s=this.segments.get(i);ke(s,"No segments for starting representation");let n=this.initData.get(i);if(ke(n,"No init buffer for starting representation"),!(n instanceof ArrayBuffer))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){!V(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new X,Jt(this.switchAbortController.signal,async function*(i,r=!1){this.switchingToRepresentationId=i;let s=this.representations.get(i);ke(s,`No such representation ${i}`);let n=this.segments.get(i),u=this.initData.get(i);if(ce(u)||ce(n)?yield this.loadInit(s,"high",!1):u instanceof Promise&&(yield u),n=this.segments.get(i),ke(n,"No segments for starting representation"),u=this.initData.get(i),!(!(u instanceof ArrayBuffer)||!this.sourceBuffer||!V(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();Zt(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(){!ce(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 X,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(ce(e)||ce(this.downloadingRepresentationId)||ce(this.playingRepresentationId)||ce(this.sourceBuffer)||!V(this.mediaSource,this.sourceBuffer)||Zt(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(ke(t,`No such representation ${this.downloadingRepresentationId}`),ke(i,`No such representation ${this.playingRepresentationId}`),ce(r)||ce(s))return;let n=r.find(c=>e>=c.time.from&&e<c.time.to);Zt(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 c=this.getForwardBufferDuration(e),h=ms(i),f=ms(t),m=this.useSmartRepresentationSwitch&&this.tuning.dash.useNewRepresentationSwitch&&this.tuning.dash.useSmartRepresentationSwitch&&Zt(h)&&Zt(f)&&oB(h.quality,f.quality),g=this.useSmartRepresentationSwitch&&this.tuning.dash.useNewRepresentationSwitch&&this.tuning.dash.useDelayedRepresentationSwitch;if(m||g?u+=Math.min(c,this.tuning.dash.representationSwitchForwardBufferGap):n&&n.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&c>=n.time.to-e+o&&(u=n?n.time.to+o:-1/0),this.tuning.dash.useNewRepresentationSwitch){let v=[...this.segments.entries()].map(([I,T])=>{let A=T.find(R=>e>=R.time.from&&e<R.time.to);return{representationId:I,status:A?.status}}).find(I=>I.status==="fed")?.representationId;if(!v)return;this.playingRepresentationId=v,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId))}}if(isFinite(this.bufferLimit)&&mr(this.sourceBuffer.buffered)>=this.bufferLimit){let c=ve(this.sourceBuffer.buffered,e),h=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,c<h).catch(f=>{this.handleAsyncError(f,"pruneBuffer")});return}let p=null;if(!this.activeSegments.size&&(p=this.selectForwardBufferSegments(r,t.segmentReference.type,u),p?.length)){let c="auto";if(this.tuning.dash.useFetchPriorityHints&&n)if((0,Mo.default)(p,n))c="high";else{let h=(0,Di.default)(p,0);h&&h.time.from-n.time.to>=this.forwardBufferTarget/2&&(c="low")}this.loadSegments(p,t,c).catch(h=>{this.handleAsyncError(h,"loadSegments")})}(!this.preloadOnly&&!this.allInitsLoaded&&n&&n.status==="fed"&&!p?.length&&ve(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let d=(0,Di.default)(r,-1);!this.isLive&&d&&(this.fullyBuffered$.next(d.time.to-e-ve(this.sourceBuffer.buffered,e)<o),this.onLastSegment$.next(e-d.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;Zt(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=(0,Do.default)(e?.streams[this.kind],r=>r.representations).find(r=>r.id===this.downloadingRepresentationId);if(!t)return;let i=this.segments.get(t.id);if(i?.length)return{from:i[0].time.from,to:i[i.length-1].time.to}}updateLive(e){let t=(0,Do.default)(e?.streams[this.kind],i=>i.representations)??[];if(![...this.segments.values()].every(i=>!i.length))for(let i of t){if(!i||!je(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,Di.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;ke(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(!je(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=nt(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&&vt&&vt(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&vt&&vt(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:c,time:{from:h,to:f}},m)=>{let g=h<=i&&f>=i,S=h>i||g||m===0&&i===0,v=Math.min(this.forwardBufferTarget,this.bufferLimit),I=this.preloadOnly&&h<=i+v||r<v&&f-h>=v||f<=i+v;return(c==="none"||c==="partially_ejected"&&S&&I&&this.sourceBuffer&&V(this.mediaSource,this.sourceBuffer)&&!(ye(this.sourceBuffer.buffered,h)&&ye(this.sourceBuffer.buffered,f)))&&S&&I});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,d=this.preloadOnly?this.forwardBufferTarget:0;for(let c=s;c<n.length&&(u<=p||o<=d);c++){let h=n[c];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"){je(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 Jt(u,async function*(){let p=od(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(d=>setTimeout(d,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=$o(),!p)return;let d=new DataView(p),c=yt(t.mime);if(!isFinite(r.segment.time.to)){let m=t.segmentReference.timescale;r.segment.time.to=c.getChunkEndTime(d,m)}o&&r.feedingBytes&&l?await Promise.all(l):await this.sourceBufferTaskQueue.append(d,u);let{serverDataReceivedTimestamp:h,serverDataPreparedTime:f}=c.getServerLatencyTimestamps(d);h&&f&&this.currentLiveSegmentServerLatency$.next(f-h),r.segment.status="downloaded",this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(p){this.abortActiveSegments([e]),Tt(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())je(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 Jt(n,async function*(){let o=od(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,o),nd(window,"online").pipe(uB()).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=$o(),this.failedDownloads=0}catch(o){this.abortActiveSegments(e),Tt(o)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}prepareByteRangeFetchSegmentParams(e,t){if(je(t.segmentReference))throw new Error("Representation is not byte range type");let i=t.segmentReference.url,r={from:(0,Di.default)(e,0).byte.from,to:(0,Di.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=$o(),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:$i.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!je(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=$o();let d=this.onSomeTemplateDataLoaded({dataView:l,loaded:p,signal:s,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(d)}catch(d){this.error$.next({id:"SegmentFeeding",category:$i.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:d})}}:void 0;return{url:r,signal:s,onProgress:o,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)(0,Mo.default)(e,t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:r,signal:s}){if(!this.activeSegments.size||!V(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=yt(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||!V(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,d=l.byte.to-i,c=d-p+1,h=p<r,f=d<=r;if(h){if(l.status==="downloading"&&f){l.status="downloaded";let m=new DataView(e.buffer,e.byteOffset+p,c);await this.sourceBufferTaskQueue.append(m,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(c,r-p),o.loadedBytes>o.feedingBytes)){let m=new DataView(e.buffer,e.byteOffset+p+o.feedingBytes,o.loadedBytes-o.feedingBytes),g=o.loadedBytes===c?m:yt(u.mime).parseFeedableSegmentChunk(m);g?.byteLength&&(l.status="partially_fed",o.feedingBytes+=g.byteLength,await this.sourceBufferTaskQueue.append(g,s)&&!s.aborted?(o.fedBytes+=g.byteLength,o.fedBytes===c&&this.onSegmentFullyAppended(o,t)):await n())}}}}onSegmentFullyAppended(e,t){if(!(ce(this.sourceBuffer)||!V(this.mediaSource,this.sourceBuffer))){!this.isLive&&C.browser.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(ye(this.sourceBuffer.buffered,e.segment.time.from,100)&&ye(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:$i.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",sd(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=fr(()=>(0,DT.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?Jt(this.destroyAbortController.signal,async function*(){let u=od(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(o=>setTimeout(o,u))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,yt(e.mime),r)).then(u=>{if(!u)return;let{init:o,dataView:l,segments:p}=u,d=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,d);let c=p;this.isLive&&je(e.segmentReference)&&(c=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,c),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:$i.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||!V(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||ce(e))return!1;this.checkEjectedSegments();let r=[],s=0,n=u=>{if(s>=t)return;r.push({...u.time});let o=sd(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 d of this.segments.values())for(let c of d)(0,Mo.default)(["none","partially_ejected"],c.status)&&Math.round(c.time.from)<=Math.round(o)&&Math.round(c.time.to)>=Math.round(l)&&p++;if(p===this.segments.size){let d={time:{from:o,to:l},url:"",status:"none"};n(d)}}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=$T(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||!V(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||!V(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||!V(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||!V(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||ce(e)?0:ve(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!this.sourceBuffer||!V(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||!V(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=fr(()=>{try{this.detectGaps(e,t)}catch(r){this.error$.next({id:"GapDetection",category:$i.WTF,message:"detectGaps threw",thrown:r})}finally{this.gapDetectionIdleCallback=null}})}checkEjectedSegments(){if(ce(this.sourceBuffer)||!V(this.mediaSource,this.sourceBuffer)||ce(this.playingRepresentationId)||this.sourceBufferBufferedDiff&&!this.sourceBufferBufferedDiff.wasUpdated())return;let e=Ro(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 d=e[p],c=e[p+1];o||(o=d-t<=n&&c+t>=u),(n>=d&&n<c-t||u>d+t&&u<=c)&&(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:$i.VIDEO_PIPELINE,thrown:e,message:"Something went wrong"})}calculateDurationFromSegments(){if(!this.playingRepresentationId)return 0;let e=this.segments.get(this.playingRepresentationId);return(e?(0,Di.default)(e,-1)?.time.to:0)||0}};import{abortable as gs,assertNever as CT,fromEvent as BT,merge as dB,now as Ss,Subject as Rr,ValueSubject as ud,flattenObject as Lr,ErrorCategory as vs,SubscriptionRemovable as pB}from"@vkontakte/videoplayer-shared/es2024";var Bo=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:s=!1}){this.manifestRequested=new Rr;this.manifestReceived=new Rr;this.firstBytesRequested=new Rr;this.firstBytesReceived=new Rr;this.lastConnectionType$=new ud(void 0);this.lastConnectionReused$=new ud(void 0);this.lastRequestFirstBytes$=new ud(void 0);this.recoverableError$=new Rr;this.error$=new Rr;this.abortAllController=new X;this.subscription=new pB;this.fetchManifest=gs(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=Yt(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=uo(i)),this.manifestRequested.next();let r=yield this.doFetch(i,{signal:this.abortAllController.signal}).catch(Co);return r?(t.log("success",Lr({url:i,message:"Request successfully executed"})),t.end(),this.manifestReceived.next(),this.onHeadersReceived(r.headers),r.text()):(t.error("error",Lr({url:i,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=gs(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,d=new Headers,c=this.tracer.createComponentTracer("Fetch");if(i)switch(t){case 0:{d.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let y=new URL(p,location.href);y.searchParams.append("bytes",`${i.from}-${i.to}`),p=y.toString();break}default:CT(t)}this.requestQuic&&(p=Yt(p));let h=this.abortAllController.signal,f;if(n){let y=new X;if(f=dB(BT(this.abortAllController.signal,"abort"),BT(n,"abort")).subscribe(()=>{try{y.abort()}catch(E){Co(E)}}),this.subscription.add(f),this.abortAllController.signal.aborted||n.aborted)try{y.abort()}catch(E){Co(E)}h=y.signal}let m=0,g=Ss();c.log("startRequest",Lr({url:p,priority:s,rangeMethod:t,range:i,isLowLatency:o,requestStartedAt:g})),this.firstBytesRequested.next();let S=yield this.doFetch(p,{priority:s,headers:d,signal:h}),v=Ss();if(!S)return c.error("error",{message:"No response in request"}),c.end(),this.unsubscribeAbortSubscription(f),null;if(this.throughputEstimator?.addRawRtt(v-g),!S.ok||!S.body){this.unsubscribeAbortSubscription(f);let y=`Fetch error ${S.status}: ${S.statusText}`;return c.error("error",{message:y}),c.end(),Promise.reject(new Error(`Fetch error ${S.status}: ${S.statusText}`))}if(this.onHeadersReceived(S.headers),!r&&!u){this.unsubscribeAbortSubscription(f);let y=Ss(),E={requestStartedAt:g,requestEndedAt:y,duration:y-g};return c.log("endRequest",Lr(E)),c.end(),S.arrayBuffer()}let I=S.body;if(u){let y;[I,y]=S.body.tee(),this.throughputEstimator?.trackStream(y,o)}let T=I.getReader(),A,R=parseInt(S.headers.get("content-length")??"",10);Number.isFinite(R)&&(A=R),!A&&i&&(A=i.to-i.from+1);let L=A?new Uint8Array(A):new Uint8Array(0),w=!1,D=y=>{this.unsubscribeAbortSubscription(f),w=!0,Co(y)},x=gs(h,async function*({done:y,value:E}){if(m===0&&(this.lastRequestFirstBytes$.next(Ss()-g),this.firstBytesReceived.next()),h.aborted){this.unsubscribeAbortSubscription(f);return}if(!y&&E){if(l&&A)L.set(E,m),m+=E.byteLength;else{let z=new Uint8Array(L.length+E.length);z.set(L),z.set(E,L.length),L=z,m+=E.byteLength}r?.(new DataView(L.buffer),m),yield T?.read().then(x,D)}}.bind(this));yield T?.read().then(x,D),this.unsubscribeAbortSubscription(f);let q=Ss(),$={failed:w,requestStartedAt:g,requestEndedAt:q,duration:q-g};return w?(c.error("endRequest",Lr($)),c.end(),null):(c.log("endRequest",Lr($)),c.end(),L.buffer)}.bind(this));this.fetchByteRangeRepresentation=gs(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 d=yield this.fetch(e.url,{range:{from:n,to:u},priority:i,measureThroughput:!1});if(!d)return null;let c=new DataView(d,r-n,s-n+1);if(!t.validateData(c))throw new Error("Invalid media file");let h=t.parseInit(c),f=e.indexRange??t.getIndexRange(h);if(!f)throw new ReferenceError("No way to load representation index");let m;if(o)m=new DataView(d,f.from-n,f.to-f.from+1);else{let S=yield this.fetch(e.url,{range:f,priority:i,measureThroughput:!1});if(!S)return null;m=new DataView(S)}let g=t.parseSegments(m,h,f);return{init:h,dataView:new DataView(d),segments:g}}.bind(this));this.fetchTemplateRepresentation=gs(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}=oo(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:CT(r)}}destroy(){this.abortAllController.abort(),this.tracer.end(),this.subscription.unsubscribe()}async doFetch(e,t){let i=await Xe(e,t);if(i.ok)return i;let r=await i.text(),s=parseInt(r);if(!isNaN(s))switch(s){case 1:this.recoverableError$.next({id:"VideoDataLinkExpiredError",message:"Video data links have expired",category:vs.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:vs.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:vs.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:vs.FATAL});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${s})`,category:vs.FATAL})}}unsubscribeAbortSubscription(e){e&&(e.unsubscribe(),this.subscription.remove(e))}},Co=a=>{if(!Tt(a))throw a};import{isNullable as hB,ValueSubject as fB}from"@vkontakte/videoplayer-shared/es2024";var ys=class a{constructor(e,t){this.currentRepresentation$=new fB(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(!hB(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&&je(t.segmentReference))}};var vB=["progress","play","seeked","stalled","waiting"],yB=["timeupdate","progress","loadeddata","playing","seeked"];var _o=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.bufferManagers=[];this.subscription=new hd;this.representationSubscription=new hd;this.state$=new F("none");this.currentVideoRepresentation$=new te(void 0);this.currentVideoRepresentationInit$=new te(void 0);this.currentAudioRepresentation$=new te(void 0);this.currentVideoSegmentLength$=new te(0);this.currentAudioSegmentLength$=new te(0);this.error$=new ei;this.manifestRequested=new ei;this.manifestReceived=new ei;this.firstBytesRequested=new ei;this.firstBytesReceived=new ei;this.lastConnectionType$=new te(void 0);this.lastConnectionReused$=new te(void 0);this.lastRequestFirstBytes$=new te(void 0);this.currentLiveTextRepresentation$=new te(null);this.isLive$=new te(!1);this.isActiveLive$=new te(!1);this.isLowLatency$=new te(!1);this.liveDuration$=new te(0);this.liveSeekableDuration$=new te(0);this.liveAvailabilityStartTime$=new te(0);this.liveStreamStatus$=new te(void 0);this.bufferLength$=new te(0);this.liveLatency$=new te(void 0);this.liveLoadBufferLength$=new te(0);this.livePositionFromPlayer$=new te(0);this.currentStallDuration$=new te(0);this.videoLastDataObtainedTimestamp$=new te(0);this.fetcherRecoverableError$=new ei;this.fetcherError$=new ei;this.liveStreamEndTimestamp=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.forceEnded$=new ei;this.gapWatchdogActive=!1;this.destroyController=new X;this.initManifest=cd(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=se(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:ut.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=cd(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:ut.NETWORK,message:"Failed to load manifest",thrown:o})});if(!e)return null;let t=null;try{t=ro(e??"",this.manifestUrlString)}catch(o){let l=to(e)??{id:"ManifestParsing",category:ut.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)&&Ue()?.isTypeSupported?.(`${l}; codecs="${p}"`)||o==="text");if(t.live){this.isLive$.next(!!t.live);let{availabilityStartTime:o,latestSegmentPublishTime:l,streamIsUnpublished:p,streamIsAlive:d}=t.live,c=(t.duration??0)/1e3;this.liveSeekableDuration$.next(-1*c),this.liveDuration$.next((l-o)/1e3),this.liveAvailabilityStartTime$.next(t.live.availabilityStartTime);let h="active";d||(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:c,codecs:h})=>i(o,c,h));r[o]=p;let d;if(this.tuning.dash.codecsPrioritizeEnabled){let c=p.map(({codecs:h})=>h);o==="audio"&&(n=yo(c),d=n[0]),o==="video"&&(s=vo(c),this.forceVideoCodec&&(0,FT.default)(s,this.forceVideoCodec)?d=this.forceVideoCodec:d=s[0]),d&&(r[o]=p.filter(({codecs:h})=>Er(h)===d))}else{let c=new Set(p.map(({codecs:h})=>h));d=So(c),d&&(r[o]=p.filter(({codecs:h})=>h.startsWith(d)))}if(o==="video"){let c=this.tuning.preferHDR,h=r.video.some(m=>m.hdr),f=r.video.some(m=>!m.hdr);C.display.isHDR&&c&&h?r.video=r.video.filter(m=>m.hdr):f&&(r.video=r.video.filter(m=>!m.hdr))}}let u={...t,streams:r};return this.tuning.dash.codecsPrioritizeEnabled&&(u.codecs={video:s,audio:n}),this.tracer.log("updateManifestEnd",Is(u)),u}.bind(this));this.initRepresentations=cd(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initRepresentationsStart",Is({initialVideo:e,initialAudio:t,sourceHls:i})),$r(this.manifest),$r(this.element),this.representationSubscription.unsubscribe(),this.representationSubscription=new hd,this.state$.startTransitionTo("representations_ready");let r=c=>{this.representationSubscription.add(It(c,"error").pipe(Vo(h=>!!this.element?.played.length)).subscribe(h=>{this.error$.next({id:"VideoSource",category:ut.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:h})}))};this.source=$n();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,h)=>[...c,...h.representations],[]);if(this.videoBufferManager=new bs("video",this.source,u,n),this.bufferManagers=[this.videoBufferManager],Es(t)){let c=this.manifest.streams.audio.reduce((h,f)=>[...h,...f.representations],[]);this.audioBufferManager=new bs("audio",this.source,c,n),this.bufferManagers.push(this.audioBufferManager)}ys.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new ys(this.manifest.streams.text,n)),this.representationSubscription.add(this.fetcher.manifestRequested.subscribe(this.manifestRequested)),this.representationSubscription.add(this.fetcher.manifestReceived.subscribe(this.manifestReceived)),this.representationSubscription.add(this.fetcher.firstBytesRequested.subscribe(this.firstBytesRequested)),this.representationSubscription.add(this.fetcher.firstBytesReceived.subscribe(this.firstBytesReceived)),this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$));let o=()=>{this.stallWatchdogSubscription?.unsubscribe(),this.currentStallDuration$.next(0)};if(this.representationSubscription.add(Ci(...yB.map(c=>It(this.element,c))).pipe(Dr(c=>this.element?ve(this.element.buffered,this.element.currentTime*1e3):0),Ts(),SB(c=>{c>this.tuning.dash.bufferEmptinessTolerance&&o()})).subscribe(this.bufferLength$)),this.representationSubscription.add(Ci(It(this.element,"ended"),this.forceEnded$).subscribe(()=>{o()})),this.isLive$.getValue()){this.subscription.add(this.liveDuration$.pipe(Ts()).subscribe(h=>this.liveStreamEndTimestamp=pd())),this.subscription.add(It(this.element,"pause").subscribe(()=>{this.livePauseWatchdogSubscription=dd(1e3).subscribe(h=>{let f=Ut(this.manifestUrlString,2);this.manifestUrlString=se(this.manifestUrlString,f+1e3,2),this.liveStreamStatus$.getValue()==="active"&&this.updateManifest()}),this.subscription.add(this.livePauseWatchdogSubscription)})).add(It(this.element,"play").subscribe(h=>this.livePauseWatchdogSubscription?.unsubscribe())),this.representationSubscription.add(Mr({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(Dr(({isActiveLive:h,isLowLatency:f})=>h&&f),Ts()).subscribe(h=>{this.isManualDecreasePlaybackInLive()||Ir(this.element,1)})),this.representationSubscription.add(Mr({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(Vo(({bufferLength:h,isActiveLive:f,isLowLatency:m})=>f&&m&&!!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 f=this.liveSeekableDuration$.getValue()-h/1e3;this.liveSeekableDuration$.next(Math.max(f,-1*this.tuning.dashCmafLive.maxLiveDuration)),this.liveDuration$.next(this.liveDuration$.getValue()+h/1e3)})),this.representationSubscription.add(Mr({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe(Vo(({isLive:h})=>h),Ts((h,f)=>f.bufferLength<h.bufferLength),Dr(({rtt:h,bufferLength:f,segmentServerLatency:m})=>{let g=Ut(this.manifestUrlString,2);return(h/2+f+m+g)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add(Mr({liveBuffer:this.liveBuffer.smoothed$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).subscribe(({liveBuffer:h,isActiveLive:f,isLowLatency:m})=>{if(!m||!f)return;let g=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,S=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,v=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,I=h-g;if(this.isManualDecreasePlaybackInLive())return;let T=1;Math.abs(I)>S&&(T=1+Math.sign(I)*v),Ir(this.element,T)})),this.representationSubscription.add(this.bufferLength$.subscribe(h=>{let f=0;if(h){let m=(this.element?.currentTime??0)*1e3;f=Math.min(...this.bufferManagers.map(S=>S.getLiveSegmentsToLoadState(this.manifest)?.to??m))-m}this.liveLoadBufferLength$.getValue()!==f&&this.liveLoadBufferLength$.next(f)}));let c=0;this.representationSubscription.add(Mr({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(OT(1e3)).subscribe(async({liveLoadBufferLength:h,bufferLength:f})=>{if(!this.element||this.isUpdatingLive)return;let m=this.element.playbackRate,g=Ut(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,T=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*m,A=isFinite(h)?h:f,R=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),L=S<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next(L);let w="none";if(R?w="active_low_latency":this.isLowLatency$.getValue()&&L?(this.bufferManagers.forEach(D=>D.proceedLowLatencyLive()),w="active_low_latency"):g!==0&&A<v?w="live_forward_buffering":A<v+T&&(w="live_with_target_offset"),isFinite(h)&&(c=h>c?h:c),w==="live_forward_buffering"||w==="live_with_target_offset"){let D=c-(v+I),x=this.normolizeLiveOffset(Math.trunc(g+D/m)),q=Math.abs(x-g),$=0;!h||q<=this.tuning.dashCmafLive.offsetCalculationError?$=g:x>0&&q>this.tuning.dashCmafLive.offsetCalculationError&&($=x),this.manifestUrlString=se(this.manifestUrlString,$,2)}(w==="live_with_target_offset"||w==="live_forward_buffering")&&(c=0,await this.updateLive())},h=>{this.error$.next({id:"updateLive",category:ut.VIDEO_PIPELINE,thrown:h,message:"Failed to update live with subscription"})}))}let l=Ci(...this.bufferManagers.map(c=>c.fullyBuffered$)).pipe(Dr(()=>this.bufferManagers.every(c=>c.fullyBuffered$.getValue()))),p=Ci(...this.bufferManagers.map(c=>c.onLastSegment$)).pipe(Dr(()=>this.bufferManagers.some(c=>c.onLastSegment$.getValue()))),d=Mr({allBuffersFull:l,someBufferEnded:p}).pipe(Ts(),Dr(({allBuffersFull:c,someBufferEnded:h})=>c&&h),Vo(c=>c));if(this.representationSubscription.add(Ci(this.forceEnded$,d).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:ut.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:c})}})),this.representationSubscription.add(Ci(...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(h=>{c&&(this.timeoutSourceOpenId=setTimeout(()=>{if(this.source?.readyState==="open"){h();return}this.error$.next({id:"OpenOfStream",category:ut.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 c=[this.manifest.duration??0,...(0,fd.default)((0,fd.default)([...this.manifest.streams.audio,...this.manifest.streams.video],h=>h.representations),h=>{let f=[];return h.duration&&f.push(h.duration),je(h.segmentReference)&&h.segmentReference.totalSegmentsDurationMs&&f.push(h.segmentReference.totalSegmentsDurationMs),f})];this.source.duration=Math.max(...c)/1e3}this.audioBufferManager&&Es(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=dd(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),t=>{this.error$.next({id:"GapWatchdog",category:ut.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 Bo({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.liveBuffer=Mt.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){$r(this.element);let t=this.liveStreamStatus$.getValue()!=="active"?pd()-this.liveStreamEndTimestamp:0,i=this.normolizeLiveOffset(e+t);this.isActiveLive$.next(i===0),this.manifestUrlString=se(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(){$r(this.element),this.state$.setState("running");let e=It(this.element,"timeupdate");this.tuning.dash.timeupdateEventTickThrottle&&(e=e.pipe(OT(this.tuning.dash.timeupdateEventTickThrottle))),this.subscription.add(Ci(...vB.map(t=>It(this.element,t)),It(window,"online"),e).subscribe(()=>this.tick(),t=>{this.error$.next({id:"DashVKPlayer",category:ut.WTF,message:"Internal logic error",thrown:t})})),this.subscription.add(It(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(It(this.element,"waiting").subscribe(()=>{this.tuning.dash.useVideoElementWaitingCurrentTimeReassign&&this.element&&this.element.readyState===HTMLMediaElement.HAVE_CURRENT_DATA&&!this.element.seeking&&ye(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=pd(),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,d=l<n&&s-u>this.tuning.dash.crashOnStallTWithoutDataTimeout,c=this.audioBufferManager&&p<n&&s-o>this.tuning.dash.crashOnStallTWithoutDataTimeout;if((d||c)&&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(f=>{this.error$.next({id:"stallIntervalCallback",category:ut.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:f})}),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",Is(r))};this.stallWatchdogSubscription?.unsubscribe(),this.stallWatchdogSubscription=dd(50).subscribe(t,i=>{this.error$.next({id:"StallWatchdogCallback",category:ut.NETWORK,message:"Can't restore DASH after stall.",thrown:i})}),this.subscription.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){$r(this.element),$r(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),ye(this.element.buffered,i)||await Promise.all([this.videoBufferManager.abort(),this.audioBufferManager?.abort()]),!(_T(this.element)||_T(this.videoBufferManager))&&(this.videoBufferManager.maintain(i),this.audioBufferManager?.maintain(i),this.element.currentTime=i/1e3,this.tracer.log("seek",Is({requestedPosition:e,forcePrecise:t,position:i})))}warmUpMediaSourceIfNeeded(e=this.element?.currentTime){Es(this.element)&&Es(this.source)&&Es(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.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=gB(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",Is({isJumpGapAfterSeekLive:i,isActiveLowLatency:t,initialCurrentTime:r,jumpTo:o,resultCurrentTime:this.element.currentTime})))}}calculateDurationFromSegments(){return Math.max(this.videoBufferManager?.calculateDurationFromSegments()||0,this.audioBufferManager?.calculateDurationFromSegments()||0)}};import{combine as TB,map as IB,observeElementSize as EB,Subscription as xB,ValueSubject as md,noop as wB}from"@vkontakte/videoplayer-shared/es2024";var Oo=class{constructor(){this.subscription=new xB;this.pipSize$=new md(void 0);this.videoSize$=new md(void 0);this.elementSize$=new md(void 0);this.pictureInPictureWindowRemoveEventListener=wB}connect({observableVideo:e,video:t}){let i=r=>{let s=r.target;this.pipSize$.next({width:s.width,height:s.height})};this.subscription.add(EB(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(TB({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe(IB(({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 Bi=class{constructor(e){this.subscription=new DB;this.videoState=new F("stopped");this.observableVideo=null;this.droppedFramesManager=new pr;this.stallsManager=new Ao;this.elementSizeManager=new Oo;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new Qt;this.audioTrackSwitchHistory=new Qt;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"),P(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"),P(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="ready"&&P(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"&&P(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&P(this.params.desiredState.playbackState,"paused");return;default:return PB(e)}}};this.init3DScene=e=>{if(this.scene3D)return;this.scene3D=new Pr(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 Ye(e.source.url),this.params=e,this.video=De(e.container,e.tuning),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Se(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 _o({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;MB(this.observableVideo)&&(this.observableVideo=Ve(this.video),this.subscription.add(()=>this.observableVideo?.destroy()));let i=this.constructor.name,r=n=>{e.error$.next({id:i,category:NT.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(bd(d=>!!d.length),UT()).subscribe(d=>{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:d})}));let n=this.params.desiredState.seekState.stateChangeEnded$.pipe(ws(d=>d.to.state!=="none"),xs());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$}),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.lastConnectionType$,e.httpConnectionType$),s(this.player.lastConnectionReused$,e.httpConnectionReused$),s(this.player.isLive$,e.isLive$),s(this.player.lastRequestFirstBytes$.pipe(bd(qT),UT()),e.firstBytesEvent$),s(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),s(this.videoState.stateChangeEnded$.pipe(ws(d=>d.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(mt(this.video,t.isLooped,r)),this.subscription.add(Be(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(ze(this.video,t.playbackRate,i.playbackRateState$,r)),this.elementSizeManager.connect({video:this.video,observableVideo:i}),s(Ke(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),P(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),P(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"),P(t.playbackState,"paused")})),this.subscription.add(this.player.manifestRequested.subscribe(this.params.output.manifestRequested$)).add(this.player.manifestReceived.subscribe(this.params.output.manifestReceived$)).add(this.player.firstBytesRequested.subscribe(this.params.output.firstBytesRequested$)).add(this.player.firstBytesReceived.subscribe(this.params.output.firstBytesReceived$)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:d})=>{if(d==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let c=this.player.getStreams(),h=this.player.getCodecs();if(kB(c,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let m=[];for(let g of c.audio){m.push(rd(g));let S=[];for(let v of g.representations){let I=kT(v);S.push(I),this.audioTracksMap.set(I,{stream:g,representation:v})}this.audioStreamsMap.set(g,S)}this.params.output.availableAudioStreams$.next(m)}let f=[];for(let m of c.video){f.push(ad(m));let g=[];for(let S of m.representations){let v=ms({...S,streamId:m.id});v&&(g.push(v),this.videoTracksMap.set(v,{stream:m,representation:S}))}this.videoStreamsMap.set(m,g)}this.params.output.availableVideoStreams$.next(f);for(let m of c.text)for(let g of m.representations){let S=RT(m,g);this.textTracksMap.set(S,{stream:m,representation:g})}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 d==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},r));let{vktvAbrThrottle:u}=this.params.tuning.dash,o=u&&MT(u)||null;this.subscription.add(As(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$,$B(this.video,"progress")).pipe(bd(()=>this.videoTracksMap.size>0)).subscribe(async()=>{let d=this.player.state$.getState(),c=this.player.state$.getTransition();if(d!=="manifest_ready"&&d!=="running"||c||d==="running"&&o&&!o())return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState()),this.selectVideoAudioRepresentations();let{video:h,audio:f}=this.selectedRepresentations;if(!h)return;let m=Li(this.videoTracksMap.keys(),S=>this.videoTracksMap.get(S)?.representation.id===h.id);qT(m)&&(this.stallsManager.lastVideoTrackSelected=m);let g=this.params.desiredState.autoVideoTrackLimits.getTransition();if(g&&this.params.output.autoVideoTrackLimits$.next(g.to),d==="manifest_ready")await this.player.initRepresentations(h.id,f?.id,this.params.sourceHls);else if(await this.player.switchRepresentation("video",h.id),f){let S=!!t.audioStream.getTransition();await this.player.switchRepresentation("audio",f.id,S)}},r)),this.subscription.add(RB({videoState:this.videoState.stateChangeEnded$,autoVideoTrackState:As(Fo([t.autoVideoTrackSwitching.getState()]),t.autoVideoTrackSwitching.stateChangeEnded$.pipe(ws(d=>d.to)))}).pipe(ws(({videoState:d,autoVideoTrackState:c})=>d.to!=="stopped"&&c),xs()).subscribe(d=>this.player.setSmartRepresentationSwitch(d))),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:d})=>{this.scene3D&&d&&this.scene3D.pointCameraTo(d.x,d.y)})),this.subscription.add(this.elementSizeManager.subscribe(d=>{this.scene3D&&d&&this.scene3D.setViewportSize(d.width,d.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(xs()).subscribe(d=>{let c=Li(this.videoTracksMap.entries(),([,{representation:S}])=>S.id===d);if(!c){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[h,{stream:f}]=c,m=this.params.desiredState.videoStream.getTransition();m&&m.to&&m.to.id===f.id&&this.params.desiredState.videoStream.setState(m.to),e.currentVideoTrack$.next(h),e.currentVideoStream$.next(ad(f));let g=this.player.calculateDurationFromSegments();g&&this.params.output.duration$.next(g/1e3)},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(xs()).subscribe(d=>{let c=Li(this.audioTracksMap.entries(),([,{representation:g}])=>g.id===d);if(!c){e.currentAudioStream$.next(void 0);return}let[h,{stream:f}]=c,m=this.params.desiredState.audioStream.getTransition();m&&m.to&&m.to.id===f.id&&this.params.desiredState.audioStream.setState(m.to),e.currentAudioStream$.next(rd(f))},r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(d=>{if(d?.is3dVideo&&this.params.tuning.spherical?.enabled)try{this.init3DScene(d),e.is3DVideo$.next(!0)}catch(c){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${c}`})}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(ws(({to:d})=>d==="ready"),xs());this.subscription.add(As(l,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,Fo(["init"])).subscribe(()=>{let d=t.autoVideoTrackSwitching.getState(),h=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:d?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(h)})),this.subscription.add(As(l,this.player.state$.stateChangeEnded$,Fo(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let p=As(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Fo(["init"])).pipe(LB(0));this.subscription.add(p.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?ga:ba,t=this.params.tuning.useNewAutoSelectVideoTrack?zn:Gn,i=this.params.tuning.useNewAutoSelectVideoTrack?St:Wn,{desiredState:r,output:s}=this.params,n=r.autoVideoTrackSwitching.getState(),u=r.videoTrack.getState()?.id,o=Li(this.videoTracksMap.keys(),w=>w.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 d=Li(this.videoStreamsMap.keys(),w=>w.id===p.id),c=d&&this.videoStreamsMap.get(d);if(!c)return;let h=ve(this.video.buffered,this.video.currentTime*1e3),f;this.player.isActiveLive$.getValue()?f=this.player.isLowLatency$.getValue()?this.params.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.params.tuning.dashCmafLive.normalizedLiveMinBufferSize:this.player.isLive$.getValue()?f=this.params.tuning.dashCmafLive.normalizedTargetMinBufferSize:f=n?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;let m=(this.video.duration*1e3||1/0)-this.video.currentTime*1e3,g=Math.min(h/Math.min(f,m||1/0),1),S=r.audioStream.getState()??(this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0),v=S?.id&&Li(this.audioStreamsMap.keys(),w=>w.id===S.id)||this.audioStreamsMap.keys().next().value,I=0;if(v){if(o&&!n){let w=e(o,c,this.audioStreamsMap.get(v)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);I=Math.max(I,w?.bitrate??-1/0)}if(l){let w=e(l,c,this.audioStreamsMap.get(v)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);I=Math.max(I,w?.bitrate??-1/0)}}let T=o;(n||!T)&&(T=i(c,{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:I,forwardBufferHealth:g,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 A=v&&t(T,c,this.audioStreamsMap.get(v)??[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.stallsManager.abrTuningParams,forwardBufferHealth:g,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),R=this.videoTracksMap.get(T)?.representation,L=A&&this.audioTracksMap.get(A)?.representation;R&&L?(this.selectedRepresentations.video=R,this.selectedRepresentations.audio=L):R&&!L&&this.audioTracksMap.size===0&&(this.selectedRepresentations.video=R,this.selectedRepresentations.audio=null)}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){_e(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:NT.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),Ce(this.video),this.tracer.end()}};var Ps=class extends Bi{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)}};import{combine as gd,merge as HT,filter as jT,filterChanged as QT,isNullable as Sd,map as WT,ValueSubject as vd,isNonNullable as CB}from"@vkontakte/videoplayer-shared/es2024";var ks=class extends Bi{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 vd(1);n(r.playbackRateState$,u),this.params.tuning.dashCmafLive.catchupLiveForMutedInactiveTab&&this.subscription.add(i.elementVisible$.pipe(QT()).subscribe(o=>{let l=i.position$.getValue(),p=i.volume$.getValue(),d=!p.volume||p.muted;!o&&!l&&d?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(WT(o=>o.to)).subscribe(this.player.isLowLatency$)).add(gd({liveBufferTime:i.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(WT(({liveBufferTime:o,liveAvailabilityStartTime:l})=>o&&l?o+l:void 0)).subscribe(i.liveTime$)).add(this.player.liveStreamStatus$.pipe(jT(o=>CB(o))).subscribe(o=>i.isLiveEnded$.next(o!=="active"&&i.position$.getValue()===0))).add(gd({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:HT(r.playbackRateState$,new vd(1))}).pipe(jT(({liveStreamStatus:o,liveDuration:l})=>o==="active"&&!!l)).subscribe(({liveDuration:o,playbackRate:l})=>{let p=i.liveBufferTime$.getValue(),d=i.position$.getValue(),{playbackCatchupSpeedup:c}=this.params.tuning.dashCmafLive.lowLatency;d||l<1-c||this.video.paused||Sd(p)||(t=o-p)})).add(gd({time:i.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:HT(r.playbackRateState$,new vd(1))}).pipe(QT((o,l)=>this.player.liveStreamStatus$.getValue()==="active"?o.liveDuration===l.liveDuration:o.time===l.time)).subscribe(({time:o,liveDuration:l,playbackRate:p})=>{let d=i.position$.getValue(),{playbackCatchupSpeedup:c}=this.params.tuning.dashCmafLive.lowLatency;if(!d&&!this.video.paused&&p>=1-c||Sd(o)||Sd(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=LT(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 GT="X-Playback-Duration",yd=async a=>{let e=await Xe(a),t=await e.text(),i=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t)?.[1];return i?parseInt(i,10):e.headers.has(GT)?parseInt(e.headers.get(GT),10):void 0};import{assertNever as QB,combine as WB,debounce as GB,ErrorCategory as Uo,filter as zB,filterChanged as YB,isNonNullable as KT,isNullable as Ho,map as XT,merge as KB,observableFrom as XB,Subscription as JB,ValueSubject as Ed,VideoQuality as ZB}from"@vkontakte/videoplayer-shared/es2024";var Id=B(ol(),1);import{videoSizeToQuality as BB,getExponentialDelay as VB}from"@vkontakte/videoplayer-shared/es2024";var _B=a=>{let e=null;if(a.QUALITY&&(e=jt(a.QUALITY)),!e&&a.RESOLUTION){let[t,i]=a.RESOLUTION.split("x").map(r=>parseInt(r,10));e=BB({width:t,height:i})}return e??null},OB=(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,Id.default)(u[1].split(",").map(g=>g.split("="))),p=l.QUALITY??`stream-${l.BANDWIDTH}`,d=_B(l),c;l.BANDWIDTH&&(c=parseInt(l.BANDWIDTH,10)/1e3||void 0),!c&&l["AVERAGE-BANDWIDTH"]&&(c=parseInt(l["AVERAGE-BANDWIDTH"],10)/1e3||void 0);let h=l["FRAME-RATE"]?parseFloat(l["FRAME-RATE"]):void 0,f;if(l.RESOLUTION){let[g,S]=l.RESOLUTION.split("x").map(v=>parseInt(v,10));g&&S&&(f={width:g,height:S})}let m=new URL(t[++s],e).toString();d&&i.push({id:p,quality:d,url:m,bandwidth:c,size:f,fps:h})}if(o){let l=(0,Id.default)(o[1].split(",").map(h=>{let f=h.indexOf("=");return[h.substring(0,f),h.substring(f+1)]}).map(([h,f])=>[h,f.replace(/^"|"$/g,"")])),p=l.URI?.replace(/playlist$/,"subtitles.vtt"),d=l.LANGUAGE,c=l.NAME;p&&d&&r.push({type:"internal",id:d,label:c,language:d,url:p,isAuto:!1})}}}if(!i.length)throw new Error("Empty manifest");return{qualityManifests:i,textTracks:r}},FB=a=>new Promise(e=>{setTimeout(()=>{e()},a)}),Td=0,zT=async(a,e=a,t,i)=>{let s=await(await Xe(a,i)).text();Td+=1;try{let{qualityManifests:n,textTracks:u}=OB(s,e);return{qualityManifests:n,textTracks:u}}catch{if(Td<=t.manifestRetryMaxCount)return await FB(VB(Td-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),zT(a,e,t)}return{qualityManifests:[],textTracks:[]}},No=zT;import{isNonNullable as NB,Subscription as qB,throttle as UB,ValueSubject as YT,Subject as HB,ErrorCategory as jB}from"@vkontakte/videoplayer-shared/es2024";var qo=class{constructor(e,t,i,r,s){this.subscription=new qB;this.abortControllers={destroy:new X,nextManifest:null};this.prepareUrl=void 0;this.currentTextTrackData=null;this.availableTextTracks$=new YT(null);this.getCurrentTime$=new YT(null);this.error$=new HB;this.params={fetchManifestData:i,sourceUrl:r,downloadThreshold:s},this.subscription.add(e.pipe(UB(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 Xe(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 d=new Date(i.vkStartTime).valueOf(),c=new Date(i.programDateTime).valueOf();i.segmentStartTime=c-d}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(NB(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 X;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:jB.WTF,thrown:t,message:e})}};var Rs=class{constructor(e){this.subscription=new JB;this.videoState=new F("stopped");this.textTracksManager=null;this.liveTextManager=null;this.manifests$=new Ed([]);this.liveOffset=new yi;this.manifestStartTime$=new Ed(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"),P(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"?P(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),P(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"&&P(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"&&(P(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return QB(t)}};this.params=e,this.video=De(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:ZB.INVARIANT,url:this.params.source.url};let t=(i,r)=>No(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 qo(this.params.output.liveTime$,this.video,t,this.params.source.url,this.params.tuning.hlsLiveNewTextManagerDownloadThreshold):this.textTracksManager=new Ye(e.source.url),t(this.generateLiveUrl()).then(({qualityManifests:i,textTracks:r})=>{i.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:Uo.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:Uo.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(Se(this.params.source.url)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.maxSeekBackTime$=new Ed(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:Uo.WTF,message:"HlsLiveProvider internal logic error",thrown:u})},r=Ve(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(Be(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(ze(this.video,t.playbackRate,r.playbackRateState$,i)),s(Ke(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"),P(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),P(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(YB(),XT(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&&KT(l.to)){let d=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let c=this.manifests$.getValue().find(h=>h.id===d);c&&(this.params.output.currentVideoTrack$.next(c),this.params.output.hostname$.next(Se(c.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(WB({startTime:this.manifestStartTime$.pipe(zB(KT)),currentTime:r.timeUpdate$}).subscribe(({startTime:u,currentTime:o})=>this.params.output.liveTime$.next(u+o*1e3),i)),this.subscription.add(this.manifests$.pipe(XT(u=>u.map(({id:o,quality:l,size:p,bandwidth:d,fps:c})=>({id:o,quality:l,size:p,fps:c,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,i));let n=KB(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,XB(["init"])).pipe(GB(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),Ce(this.video)}prepare(){let e=this.selectManifest();if(Ho(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 d=String(parseFloat(l||""));p&&l&&r.searchParams.set(p,d)}}let s=this.params.format==="HLS_LIVE_CMAF"?2:0,n=se(r.toString(),this.liveOffset.getTotalOffset(),s);this.liveTextManager?.prepare(n),this.video.setAttribute("src",n),this.video.load(),yd(n).then(u=>{if(!Ho(u))this.maxSeekBackTime$.next(u);else{let o=this.params.source.maxSeekBackTime??this.maxSeekBackTime$.getValue();(Ho(o)||!isFinite(o))&&Xe(n).then(l=>l.text()).then(l=>{let p=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(l)?.[1];if(p){let d=new URL(p,n).toString();yd(d).then(c=>{Ho(c)||this.maxSeekBackTime$.next(c)})}}).catch(()=>{})}})}playIfAllowed(){_e(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),P(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Uo.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=se(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}};import{assertNever as eV,debounce as tV,ErrorCategory as xd,fromEvent as wd,isNonNullable as iV,isNullable as rV,map as JT,merge as ZT,observableFrom as eI,Subscription as aV,ValueSubject as tI,VideoQuality as sV}from"@vkontakte/videoplayer-shared/es2024";var Ls=class{constructor(e){this.subscription=new aV;this.videoState=new F("stopped");this.manifests$=new tI([]);this.unmuteAfterBrowserResetsHappened=new tI(!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"),P(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:d}=this.video;this.prepare(),u&&this.params.output.autoVideoTrackLimits$.next(u.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:d*1e3,forcePrecise:!0});return}switch(r?.to!=="paused"&&l.state==="requested"&&this.seek(l.position),t){case"ready":i==="ready"?P(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),P(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"&&P(this.params.desiredState.playbackState,"playing");return;case"paused":i==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):r?.to==="paused"&&P(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return eV(t)}};this.textTracksManager=new Ye(e.source.url),this.params=e,this.video=De(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:sV.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(Se(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.manifestRequested$.next(),No(se(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:t,textTracks:i})=>{this.params.output.manifestReceived$.next(),this.manifests$.next([this.masterManifest,...t]),this.params.tuning.useNativeHLSTextTracks||this.params.desiredState.internalTextTracks.startTransitionTo(i)},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:xd.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:xd.WTF,message:"HlsProvider internal logic error",thrown:u})},r=Ve(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(JT(u=>u.to)),this.params.output.playbackState$),this.subscription.add(mt(this.video,t.isLooped,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(ze(this.video,t.playbackRate,r.playbackRateState$,i)),kr({subscription:this.subscription,desiredState:t,videoElement$:this.params.output.element$,observableVideo:r}),this.subscription.add(Be(this.video,t.volume,r.volumeState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),P(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),P(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&&iV(l.to)){let h=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let f=this.manifests$.getValue().find(m=>m.id===h);f&&(this.params.output.currentVideoTrack$.next(f),this.params.output.hostname$.next(Se(f.url)))}let d=this.params.desiredState.playbackRate.getState(),c=this.params.output.element$.getValue()?.playbackRate;if(d!==c){let h=this.params.output.element$.getValue();h&&(this.params.desiredState.playbackRate.setState(d),h.playbackRate=d)}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"),P(t.playbackState,"paused")})),this.subscription.add(this.manifests$.pipe(JT(u=>u.map(({id:o,quality:l,size:p,bandwidth:d,fps:c})=>({id:o,quality:l,size:p,fps:c,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,i)),!C.device.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:u}=this.video;this.subscription.add(ZT(wd(u,"addtrack"),wd(u,"removetrack"),wd(u,"change"),eI(["init"])).subscribe(()=>{for(let o=0;o<u.length;o++)u[o].mode="hidden"},i))}let n=ZT(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,eI(["init"])).pipe(tV(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),Ce(this.video)}prepare(){let e=this.selectManifest();if(rV(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(){_e(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:xd.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};var aI=B(Yi(),1),Ad=B(pi(),1),sI=B(at(),1);import{assertNever as nV,assertNonNullable as iI,debounce as oV,ErrorCategory as rI,isHigherOrEqual as uV,isLowerOrEqual as lV,isNonNullable as cV,merge as dV,observableFrom as pV,Subscription as hV,map as fV}from"@vkontakte/videoplayer-shared/es2024";var $s=class{constructor(e){this.subscription=new hV;this.videoState=new F("stopped");this.trackUrls={};this.textTracksManager=new Ye;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"),P(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"?P(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),P(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"&&P(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&P(this.params.desiredState.playbackState,"paused");return;default:return nV(e)}};this.params=e,this.video=De(e.container,e.tuning),this.params.output.element$.next(this.video),(0,aI.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,Ad.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:rI.WTF,message:"MpegProvider internal logic error",thrown:u})},r=Ve(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(fV(u=>u.to)),this.params.output.playbackState$),this.subscription.add(mt(this.video,t.isLooped,i)),kr({subscription:this.subscription,desiredState:t,videoElement$:this.params.output.element$,observableVideo:r}),this.subscription.add(Be(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(ze(this.video,t.playbackRate,r.playbackRateState$,i)),s(Ke(this.video),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),P(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),P(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&&cV(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"),P(t.playbackState,"paused")})),this.textTracksManager.connect(this.video,t,e);let n=dV(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,pV(["init"])).pipe(oV(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),Ce(this.video)}prepare(){let e=this.params.desiredState.videoTrack.getState()?.id;iI(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];iI(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=Yt(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(Se(t))}playIfAllowed(){_e(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:rI.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=St(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,Ad.default)(this.trackUrls).map(l=>l.track);if(!r||!s||ur(e,n[0].quality,(0,sI.default)(n,-1)?.quality)){i();return}let u=e.max?lV(r,e.max):!0,o=e.min?uV(r,e.min):!0;u&&o||i(e)}};import{assertNever as oI,debounce as SV,merge as uI,observableFrom as vV,Subscription as yV,map as lI,ValueSubject as TV,ErrorCategory as kd,VideoQuality as IV}from"@vkontakte/videoplayer-shared/es2024";import{ErrorCategory as mV}from"@vkontakte/videoplayer-shared/es2024";var nI=["stun:videostun.mycdn.me:80"],bV=1e3,gV=3,Pd=()=>null,jo=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=Pd;this.externalStopCallback=Pd;this.externalErrorCallback=Pd;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:nI}]};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:mV.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),bV)}normalizeOptions(e={}){let t={stunServerList:nI,maxRetryNumber:gV,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var Ms=class{constructor(e){this.videoState=new F("stopped");this.maxSeekBackTime$=new TV(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"),P(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"),P(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"&&P(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&P(this.params.desiredState.playbackState,"paused");return;default:return oI(e)}};this.subscription=new yV,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=De(e.container,e.tuning),this.liveStreamClient=new jo(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),Ce(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,i=n=>{e.error$.next({id:"WebRTCLiveProvider",category:kd.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};this.subscription.add(uI(this.videoState.stateChangeStarted$.pipe(lI(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe(lI(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:u})=>{this.log({message:`[videoState change] ${u}: ${JSON.stringify(n)}`})}));let r=Ve(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(Ke(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(Be(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 oI(n.to)}},i)).add(uI(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,vV(["init"])).pipe(SV(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(Se(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:IV.INVARIANT}),this.video.srcObject=e,P(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:kd.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){_e(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:kd.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var Cr=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}};import{assertNever as Ds,assertNonNullable as ti,ErrorCategory as Qo,filter as mI,isNonNullable as bI,isNullable as RV,map as LV,merge as $V,once as MV,Subject as ne,Subscription as gI,ValueSubject as _,flattenObject as Rd}from"@vkontakte/videoplayer-shared/es2024";import{Observable as EV,map as cI,Subscription as xV,Subject as wV}from"@vkontakte/videoplayer-shared/es2024";var dI=a=>new EV(e=>{let t=new xV,i=a.desiredPlaybackState$.stateChangeStarted$.pipe(cI(({from:l,to:p})=>`${l}-${p}`)),r=a.desiredPlaybackState$.stateChangeEnded$,s=a.providerChanged$.pipe(cI(({type:l})=>l!==void 0)),n=new wV,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()}});import{ErrorCategory as AV,Subscription as PV,combine as kV,filter as hI,once as fI}from"@vkontakte/videoplayer-shared/es2024";function pI(){return new(window.AudioContext||window.webkitAudioContext)}var Br=class a{constructor(e,t,i,r){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=i;this.volumeMultiplier=r;this.destroyController=new X;this.subscriptions=new PV;this.audioContext=null;this.gainNode=null;this.mediaElementSource=null;this.subscriptions.add(this.provider$.pipe(hI(s=>!!s.type),fI()).subscribe(({type:s})=>this.subscribe(s)))}static{this.errorId="VolumeMultiplierManager"}subscribe(e){C.browser.isSafari&&e!=="MPEG"||this.subscriptions.add(kV({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe(hI(({playbackState:t,video:i,volume:{muted:r,volume:s}})=>t==="playing"&&!!i&&!r&&!!s),fI()).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=pI();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:AV.VIDEO_PIPELINE,message:e?.message??`${a.errorId} exception`,thrown:e})}};var DV={chunkDuration:5e3,maxParallelRequests:5},Cs=class{constructor(e){this.current$=new _({type:void 0});this.providerError$=new ne;this.noAvailableProvidersError$=new ne;this.volumeMultiplierError$=new ne;this.providerOutput={position$:new _(0),duration$:new _(1/0),volume$:new _({muted:!1,volume:1}),availableVideoStreams$:new _([]),currentVideoStream$:new _(void 0),availableVideoTracks$:new _([]),currentVideoTrack$:new _(void 0),availableVideoCodecs$:new _([]),availableAudioStreams$:new _([]),currentAudioStream$:new _(void 0),availableAudioTracks$:new _([]),availableAudioCodecs$:new _([]),currentVideoSegmentLength$:new _(0),currentAudioSegmentLength$:new _(0),isAudioAvailable$:new _(!0),autoVideoTrackLimitingAvailable$:new _(!1),autoVideoTrackLimits$:new _(void 0),currentBuffer$:new _(void 0),isBuffering$:new _(!0),error$:new ne,fetcherError$:new ne,fetcherRecoverableError$:new ne,warning$:new ne,willSeekEvent$:new ne,soundProhibitedEvent$:new ne,seekedEvent$:new ne,loopedEvent$:new ne,endedEvent$:new ne,manifestRequested$:new ne,manifestReceived$:new ne,firstBytesRequested$:new ne,firstBytesReceived$:new ne,firstBytesEvent$:new ne,loadedMetadataEvent$:new ne,firstFrameEvent$:new ne,canplay$:new ne,isLive$:new _(void 0),isLiveEnded$:new _(null),canPlayLiveTailBuffer$:new _(!1),isLowLatency$:new _(!1),canChangePlaybackSpeed$:new _(!0),liveTime$:new _(void 0),liveBufferTime$:new _(void 0),liveLatency$:new _(void 0),severeStallOccurred$:new ne,availableTextTracks$:new _([]),currentTextTrack$:new _(void 0),hostname$:new _(void 0),httpConnectionType$:new _(void 0),httpConnectionReused$:new _(void 0),inPiP$:new _(!1),inFullscreen$:new _(!1),element$:new _(void 0),elementVisible$:new _(!0),availableSources$:new _(void 0),is3DVideo$:new _(!1),playbackState$:new _(""),getCurrentTime$:new _(null)};this.subscription=new gI;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=zl([...nT(this.params.tuning),...sT(this.params.tuning)]).filter(l=>bI(e.sources[l])),{forceFormat:i,formatsToAvoid:r}=this.params.tuning,s=[];i?s=[i]:r.length?s=[...t.filter(l=>!(0,Ld.default)(r,l)),...t.filter(l=>(0,Ld.default)(r,l))]:s=t,this.log({message:`Selected formats: ${s.join(" > ")}`}),this.tracer.log("Selected formats",Rd(s)),this.screenFormatsIterator=new Cr(s);let n=[...Nc(!0),...Nc(!1)];this.chromecastFormatsIterator=new Cr(n.filter(l=>bI(e.sources[l]))),this.providerOutput.availableSources$.next(e.sources);let{volumeMultiplier:u=1,tuning:{useVolumeMultiplier:o}}=this.params;o&&u!==1&&Br.isSupported()&&(this.volumeMultiplierManager=new Br(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 Cr(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(RV(t)){this.handleNoFormatsError(e);return}let i;try{i=this.createProvider(e,t)}catch(r){this.providerError$.next({id:"ProviderNotConstructed",category:Qo.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 Ds(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 ti(o),this.params.tuning.useNewDashProvider?new Ps({...u,source:o,sourceHls:l,forceVideoCodec:this.videoCodecsIterator?.getValue()}):new hs({...u,source:o,sourceHls:l,forceVideoCodec:this.videoCodecsIterator?.getValue()})}case"DASH_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return ti(o),this.params.tuning.useNewDashProvider?new ks({...u,source:o}):new fs({...u,source:o})}case"HLS":case"HLS_ONDEMAND":case"HLS_FMP4":{let o=this.applyFailoverHost(t[e]);return ti(o),new Ls({...u,source:o})}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return ti(o),new Rs({...u,source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case"MPEG":{let o=this.applyFailoverHost(t[e]);return ti(o),new $s({...u,source:o})}case"DASH_LIVE":{let o=this.applyFailoverHost(t[e]);return ti(o),new ZS({...u,source:o,config:{...DV,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case"WEB_RTC_LIVE":{let o=this.applyFailoverHost(t[e]);return ti(o),new Ms({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 Ds(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 ti(u),new da({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 Ds(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return Ds(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 Ds(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,vI.default)((0,SI.default)(e).map(([r,s])=>[r,i(s)]))}initProviderErrorHandling(){let e=new gI,t=!1,i=0;return e.add($V(this.providerOutput.error$.pipe(mI(r=>!this.params.tuning.ignoreAudioRendererError||!r.message||!/AUDIO_RENDERER_ERROR/ig.test(r.message))),dI({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(LV(r=>({id:`ProviderHangup:${r}`,category:Qo.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(mI(({to:s})=>s==="playing"),MV()).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===Qo.NETWORK,o=r.category===Qo.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,d=this.videoCodecsIterator&&!this.videoCodecsIterator.isLast()&&this.params.tuning.dash.codecsPrioritizeEnabled,c=l&&!o&&(u&&t||!p);n={...n,isNetworkError:u,isFatalError:o,haveFailoverHost:l,tryFailover:c,canReinitProvider:p},p?(i++,this.reinitProvider()):c?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):d?this.switchToNextVideoCodec():(i=0,this.switchToNextProvider(s??"SCREEN"))}r.traceAsLog?this.tracer.log("providerInfo",Rd(n)):this.tracer.error("providerError",Rd(n))})),e}};import{fromEvent as Wo,once as CV,combine as BV,Subscription as yI,ValueSubject as $d,map as VV,filter as _V,isNonNullable as Go,now as Qe,safeStorage as Md}from"@vkontakte/videoplayer-shared/es2024";var OV=5e3,TI="one_video_throughput",II="one_video_rtt",Bs=window.navigator.connection,EI=()=>{let a=Bs?.downlink;if(Go(a)&&a!==10)return a*1e3},xI=()=>{let a=Bs?.rtt;if(Go(a)&&a!==3e3)return a},wI=(a,e,t)=>{let i=t*8,r=i/a;return i/(r+e)},Dd=class a{constructor(e){this.subscription=new yI;this.concurrentDownloads=new Set;this.tuningConfig=e;let t=a.load(TI)||(e.useBrowserEstimation?EI():void 0)||OV,i=a.load(II)??(e.useBrowserEstimation?xI():void 0)??0;if(this.throughput$=new $d(t),this.rtt$=new $d(i),this.rttAdjustedThroughput$=new $d(wI(t,i,e.rttPenaltyRequestSize)),this.throughput=Mt.getSmoothedValue(t,-1,e),this.rtt=Mt.getSmoothedValue(i,1,e),e.useBrowserEstimation){let r=()=>{let n=EI();n&&this.throughput.next(n);let u=xI();Go(u)&&this.rtt.next(u)};Bs&&"onchange"in Bs&&this.subscription.add(Wo(Bs,"change").subscribe(r)),r()}this.subscription.add(this.throughput.smoothed$.subscribe(r=>{Md.set(TI,r.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(r=>{Md.set(II,r.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(BV({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(VV(({throughput:r,rtt:s})=>wI(r,s,e.rttPenaltyRequestSize)),_V(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=Qe(),r=new yI;switch(this.subscription.add(r),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:r.add(Wo(e,"progress").pipe(CV()).subscribe(s=>{t=s.loaded,i=Qe()}));break;case 1:case 0:r.add(Wo(e,"loadstart").subscribe(()=>{t=0,i=Qe()}));break}r.add(Wo(e,"loadend").subscribe(s=>{if(e.status===200){let n=s.loaded,u=Qe(),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=Qe(),n=0,u=Qe(),o=p=>{this.concurrentDownloads.delete(e),i.releaseLock(),e.cancel(`Throughput Estimator error: ${p}`).catch(()=>{})},l=async({done:p,value:d})=>{if(p)!t&&this.addRawSpeed(r,Qe()-s,1),this.concurrentDownloads.delete(e);else if(d){if(t){let c=Qe();if(c-u>this.tuningConfig.lowLatency.continuesByteSequenceInterval||c-s>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let f=u-s;f&&this.addRawSpeed(n,f,1,t),n=d.byteLength,s=Qe()}else n+=d.byteLength;u=Qe()}else r+=d.byteLength,n+=d.byteLength,n>=this.tuningConfig.streamMinSampleSize&&Qe()-u>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,Qe()-u,this.concurrentDownloads.size),n=0,u=Qe());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=Md.get(e);if(Go(t))return parseInt(t,10)??void 0}},AI=Dd;import{fillWithDefault as FV,VideoQuality as zo}from"@vkontakte/videoplayer-shared/es2024";var PI={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:zo.Q_4320P,activeVideoAreaThreshold:.1,highQualityLimit:zo.Q_720P,trafficSavingLimit:zo.Q_480P},stallsManager:{enabled:!1,stallDurationNoDataBeforeQualityDecrease:500,stallDurationToBeCount:100,stallCountBeforeQualityDecrease:3,resetQualityRestrictionTimeout:1e4,ignoreStallsOnSeek:!0,stallsMetricsHistoryLength:5,maxPossibleStallDuration:3e4,minTvtToBeCounted:5,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:zo.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},dashCmafLive:{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},kI=a=>({...FV(a,PI),configName:[...a.configName??[],...PI.configName]});import{assertNonNullable as Bd,combine as Ct,ErrorCategory as Yo,filter as O,filterChanged as Y,fromEvent as Vd,isNonNullable as MI,isNullable as WV,Logger as GV,map as G,mapTo as DI,merge as ii,now as Ko,once as N,Subject as W,Subscription as CI,tap as _d,ValueSubject as k,isHigher as zV,isInvariantQuality as BI,flattenObject as ri,throttle as Od,getTraceSubscriptionMethod as VI,TracerFactory as YV,InternalsExposure as KV,getPlayerId as XV}from"@vkontakte/videoplayer-shared/es2024";import{merge as NV,map as qV,filter as RI,isNonNullable as UV}from"@vkontakte/videoplayer-shared/es2024";var Cd=({seekState:a,position$:e})=>NV(a.stateChangeEnded$.pipe(qV(({to:t})=>t.state==="none"?void 0:(t.position??NaN)/1e3),RI(UV)),e.pipe(RI(()=>a.getState().state==="none")));import{assertNonNullable as HV}from"@vkontakte/videoplayer-shared/es2024";var LI=a=>{let e=typeof a.container=="string"?document.getElementById(a.container):a.container;return HV(e,`Wrong container or containerId {${a.container}}`),e};import{filter as jV,once as QV}from"@vkontakte/videoplayer-shared/es2024";var $I=(a,e,t,i)=>{a!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&t?.getValue().length===0?t.pipe(jV(r=>r.length>0),QV()).subscribe(r=>{r.find(i)&&e.startTransitionTo(a)}):(a===void 0||t?.getValue().find(i))&&e.startTransitionTo(a)};var Xo=class{constructor(e={configName:[]},t=YV.createRootTracer(!1),i){this.subscription=new CI;this.logger=new GV;this.abrLogger=this.logger.createComponentLog("ABR");this.internalsExposure=null;this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new k(!1);this.hasLiveOffsetByPausedTimer=0;this.playerInitRequest=0;this.playerInited=new k(!1);this.wasSetStartedQuality=!1;this.desiredState={playbackState:new F("stopped"),seekState:new F({state:"none"}),volume:new F({volume:1,muted:!1}),videoTrack:new F(void 0),videoStream:new F(void 0),audioStream:new F(void 0),autoVideoTrackSwitching:new F(!0),autoVideoTrackLimits:new F({}),isLooped:new F(!1),isLowLatency:new F(!1),playbackRate:new F(1),externalTextTracks:new F([]),internalTextTracks:new F([]),currentTextTrack:new F(void 0),textTrackCuesSettings:new F({}),cameraOrientation:new F({x:0,y:0})};this.info={playbackState$:new k(void 0),position$:new k(0),duration$:new k(1/0),muted$:new k(!1),volume$:new k(1),availableVideoStreams$:new k([]),currentVideoStream$:new k(void 0),availableQualities$:new k([]),availableQualitiesFps$:new k({}),currentQuality$:new k(void 0),isAutoQualityEnabled$:new k(!0),autoQualityLimitingAvailable$:new k(!1),autoQualityLimits$:new k({}),predefinedQualityLimitType$:new k("unknown"),availableAudioStreams$:new k([]),currentAudioStream$:new k(void 0),availableAudioTracks$:new k([]),isAudioAvailable$:new k(!0),currentPlaybackRate$:new k(1),currentBuffer$:new k({start:0,end:0}),isBuffering$:new k(!0),isStalled$:new k(!1),isEnded$:new k(!1),isLooped$:new k(!1),isLive$:new k(void 0),isLiveEnded$:new k(null),canPlayLiveTailBuffer$:new k(!1),canChangePlaybackSpeed$:new k(void 0),atLiveEdge$:new k(void 0),atLiveDurationEdge$:new k(void 0),liveTime$:new k(void 0),liveBufferTime$:new k(void 0),liveLatency$:new k(void 0),currentFormat$:new k(void 0),availableTextTracks$:new k([]),currentTextTrack$:new k(void 0),throughputEstimation$:new k(void 0),rttEstimation$:new k(void 0),videoBitrate$:new k(void 0),hostname$:new k(void 0),httpConnectionType$:new k(void 0),httpConnectionReused$:new k(void 0),surface$:new k("none"),chromecastState$:new k("NOT_AVAILABLE"),chromecastDeviceName$:new k(void 0),intrinsicVideoSize$:new k(void 0),availableSources$:new k(void 0),is3DVideo$:new k(!1),currentVideoSegmentLength$:new k(0),currentAudioSegmentLength$:new k(0)};this.events={inited$:new W,ready$:new W,started$:new W,playing$:new W,paused$:new W,stopped$:new W,willReady$:new W,willStart$:new W,willResume$:new W,willPause$:new W,willStop$:new W,willDestruct$:new W,watchCoverageRecord$:new W,watchCoverageLive$:new W,managedError$:new W,fatalError$:new W,fetcherRecoverableError$:new W,ended$:new W,looped$:new W,seeked$:new W,willSeek$:new W,autoplaySoundProhibited$:new W,manifestRequested$:new W,manifestReceived$:new W,firstBytesRequested$:new W,firstBytesReceived$:new W,firstBytes$:new W,loadedMetadata$:new W,firstFrame$:new W,canplay$:new W,log$:new W,fetcherError$:new W,severeStallOccured$:new W};this.experimental={element$:new k(void 0),tuningConfigName$:new k([]),enableDebugTelemetry$:new k(!1),dumpTelemetry:xS,getCurrentTime$:new k(null)};if(this.initLogs(),this.tuning=kI(e),this.tracer=t,this.tuning.suppressExceptionsInObservables&&((0,Fd.default)(this.info).forEach(r=>r.setSuppressErrors(!0)),(0,Fd.default)(this.events).forEach(r=>r.setSuppressErrors(!0))),this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new en({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new AI(this.tuning.throughputEstimator),e.exposeInternalsToGlobal&&(this.internalsExposure=new KV("core",XV(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,(f,m)=>{let g=typeof m;return(0,_I.default)(["number","string","boolean"],g)?m:m===null?null:`<${g}>`})),d=`Player.${String(s)}`,c=`Exception calling ${d} (${p.join(", ")})`;throw this.events.fatalError$.next({id:d,category:Yo.WTF,message:c,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",ri(n)),this.domContainer=LI(e),this.chromecastInitializer.contentId=e.meta?.videoId,this.providerContainer=new Cs({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?C.isInited$.pipe(O(s=>!!s),N()).subscribe(()=>{console.log("Core SDK async start"),i()}):i()};return this.isNotActiveTabCase()?(this.tracer.log("request play from hidden tab"),Vd(document,"visibilitychange").pipe(N()).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()}prepare(){return this.subscription.add(this.playerInited.pipe(O(e=>!!e),N()).subscribe(()=>{let e=this.desiredState.playbackState;this.tracer.log("prepare",{currentPlayBackState:e.getState()}),e.getState()==="stopped"&&e.startTransitionTo("ready")})),this}play(){return this.subscription.add(this.playerInited.pipe(O(e=>!!e),N()).subscribe(()=>{let e=this.desiredState.playbackState;this.tracer.log("play",{currentPlayBackState:e.getState()}),e.getState()!=="playing"&&e.startTransitionTo("playing")})),this}pause(){return this.subscription.add(this.playerInited.pipe(O(e=>!!e),N()).subscribe(()=>{let e=this.desiredState.playbackState;this.tracer.log("pause",{currentPlayBackState:e.getState()}),e.getState()!=="paused"&&e.startTransitionTo("paused")})),this}stop(){return this.subscription.add(this.playerInited.pipe(O(e=>!!e),N()).subscribe(()=>{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.subscription.add(this.playerInited.pipe(O(i=>!!i),N()).subscribe(()=>{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.subscription.add(this.playerInited.pipe(O(t=>!!t),N()).subscribe(()=>{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.subscription.add(this.playerInited.pipe(O(i=>!!i),N()).subscribe(()=>{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.subscription.add(this.playerInited.pipe(O(i=>!!i),N()).subscribe(()=>{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.subscription.add(this.playerInited.pipe(O(t=>!!t),N()).subscribe(()=>{this.desiredState.videoStream.startTransitionTo(e)})),this}setAudioStream(e){return this.subscription.add(this.playerInited.pipe(O(t=>!!t),N()).subscribe(()=>{this.desiredState.audioStream.startTransitionTo(e)})),this}setQuality(e){return this.subscription.add(this.playerInited.pipe(O(t=>!!t),N()).subscribe(()=>{Bd(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(O(i=>i.length>0),N()).subscribe(i=>{this.setVideoTrackIdByQuality(i,e)}):this.explicitInitialQuality=e:t.length>0&&this.setVideoTrackIdByQuality(t,e)})),this}setAutoQuality(e){return this.subscription.add(this.playerInited.pipe(O(t=>!!t),N()).subscribe(()=>{this.tracer.log("setAutoQuality",{enable:e}),this.desiredState.autoVideoTrackSwitching.startTransitionTo(e)})),this}setAutoQualityLimits(e){return this.subscription.add(this.playerInited.pipe(O(t=>!!t),N()).subscribe(()=>{this.tracer.log("setAutoQualityLimits",ri(e)),this.desiredState.autoVideoTrackLimits.startTransitionTo(e)})),this}setPredefinedQualityLimits(e){return this.subscription.add(this.playerInited.pipe(O(t=>!!t),N()).subscribe(()=>{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.subscription.add(this.playerInited.pipe(O(t=>!!t),N()).subscribe(()=>{this.tracer.log("setPlaybackRate",{playbackRate:e}),this.desiredState.playbackRate.startTransitionTo(e)})),this}setExternalTextTracks(e){return this.subscription.add(this.playerInited.pipe(O(t=>!!t),N()).subscribe(()=>{e.length&&this.tracer.log("setExternalTextTracks",ri(e)),this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>({type:"external",...t})))})),this}selectTextTrack(e){return this.subscription.add(this.playerInited.pipe(O(t=>!!t),N()).subscribe(()=>{$I(e,this.desiredState.currentTextTrack,this.providerContainer?.providerOutput.availableTextTracks$,t=>t.id===e),this.tracer.log("selectTextTrack",{textTrackId:e})})),this}setTextTrackCueSettings(e){return this.subscription.add(this.playerInited.pipe(O(t=>!!t),N()).subscribe(()=>{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.subscription.add(this.playerInited.pipe(O(t=>!!t),N()).subscribe(()=>{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.subscription.add(this.playerInited.pipe(O(i=>!!i),N()).subscribe(()=>{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.subscription.add(this.playerInited.pipe(O(t=>!!t),N()).subscribe(()=>{let t=this.getScene3D();this.tracer.log("stopCameraManualRotation",{isScene3DAvailable:!!t,immediate:e}),t&&t.stopCameraManualRotation(e)})),this}moveCameraFocusPX(e,t){return this.subscription.add(this.playerInited.pipe(O(i=>!!i),N()).subscribe(()=>{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.subscription.add(this.playerInited.pipe(O(e=>e),N()).subscribe(()=>{let e=this.getScene3D();e&&e.holdCamera()})),this}releaseCamera(){return this.subscription.add(this.playerInited.pipe(O(e=>!!e),N()).subscribe(()=>{let e=this.getScene3D();e&&e.releaseCamera()})),this}getExactTime(){if(!this.providerContainer)return 0;let e=this.providerContainer.providerOutput.element$.getValue();if(WV(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),i=t.state==="none"?void 0:t.position;return MI(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(ii(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(G(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(G(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(G(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(G(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(G(e=>e.to)).subscribe(e=>{this.info.autoQualityLimits$.next(e);let{highQualityLimit:t,trafficSavingLimit:i}=this.tuning.autoTrackSelection;this.info.predefinedQualityLimitType$.next(AS(e,t,i))})),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(O(({from:e})=>e==="stopped"),N()).subscribe(()=>{this.initedAt=Ko(),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",ri(n)),n.state==="requested"?this.desiredState.seekState.setState({...n,state:"applying"}):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:Yo.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.soundProhibitedEvent$.pipe(N()).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",ri(n)),n.state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe(G(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(G(n=>n.destination),Y()).subscribe(()=>this.isPlaybackStarted=!1)).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add(Ct({availableVideoTracks:e.providerOutput.availableVideoTracks$,currentVideoStream:e.providerOutput.currentVideoStream$}).pipe(G(({availableVideoTracks:n,currentVideoStream:u})=>n.filter(o=>u?u.id===o.streamId:!0).map(({quality:o})=>o).sort((o,l)=>BI(o)?1:BI(l)?-1:zV(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(Y()).subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.pipe(O(n=>MI(n))).subscribe(n=>{this.info.currentQuality$.next(n?.quality),this.info.videoBitrate$.next(n?.bitrate)})).add(e.providerOutput.currentVideoSegmentLength$.pipe(Y((n,u)=>Math.round(n)===Math.round(u))).subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.pipe(Y((n,u)=>Math.round(n)===Math.round(u))).subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe(Y()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(Y()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(Y()).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(G(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(_d(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(Ct({hasLiveOffsetByPaused:ii(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(G(n=>n.to),Y(),G(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(Ct({atLiveEdge:Ct({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:Cd({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(G(({isLive:n,position:u,isLowLatency:o})=>{let l=this.getActiveLiveDelay(o);return n&&Math.abs(u)<l/1e3}),Y(),_d(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(G(({atLiveEdge:n,hasPausedTimeoutCase:u})=>n&&!u)).subscribe(this.info.atLiveEdge$)).add(Ct({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(G(({isLive:n,position:u,duration:o})=>n&&(Math.abs(o)-Math.abs(u))*1e3<this.tuning.live.activeLiveDelay),Y(),_d(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(G(n=>n.muted),Y()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(G(n=>n.volume),Y()).subscribe(this.info.volume$)).add(Cd({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(ii(e.providerOutput.endedEvent$.pipe(DI(!0)),e.providerOutput.seekedEvent$.pipe(DI(!1))).pipe(Y()).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(G(n=>({id:n?`No${n}`:"NoProviders",category:Yo.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(N()).subscribe(this.events.manifestRequested$)).add(e.providerOutput.manifestReceived$.pipe(N()).subscribe(this.events.manifestReceived$)).add(e.providerOutput.firstBytesRequested$.pipe(N()).subscribe(this.events.firstBytesRequested$)).add(e.providerOutput.firstBytesReceived$.pipe(N()).subscribe(this.events.firstBytesReceived$)).add(e.providerOutput.firstBytesEvent$.pipe(N(),G(n=>n??Ko()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe(N(),G(()=>Ko()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(N(),G(()=>Ko()-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 k(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let i=new k(!0);this.subscription.add(e.current$.subscribe(()=>i.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(O(({to:n})=>n==="playing"),N()).subscribe(()=>i.next(!1)));let r=0,s=ii(e.providerOutput.isBuffering$,t,i).pipe(G(()=>{let n=e.providerOutput.isBuffering$.getValue(),u=t.getValue()||i.getValue();return n&&!u}),Y());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(ii(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(ii(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(),d;p==="CONNECTED"?d="second_screen":o?l?n?d="pip":u?d="fullscreen":d="inline":d="invisible":d="none",this.info.surface$.getValue()!==d&&this.info.surface$.next(d)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(G(e=>e?.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){let t=new CI;this.subscription.add(t),this.subscription.add(e.current$.pipe(Y((i,r)=>i.provider===r.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(O(i=>i.length>0),N()).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=St(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(ii(this.desiredState.videoTrack.stateChangeStarted$.pipe(G(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(G(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(G(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(G(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(G(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(G(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(G(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(G(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(G(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;Bd(this.providerContainer),Bd(e),ES(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(t=>IS(t)),this.providerContainer.current$.subscribe(({type:t})=>ma("provider",t)),e.duration$.subscribe(t=>ma("duration",t)),e.availableVideoTracks$.pipe(O(t=>!!t.length),N()).subscribe(t=>ma("tracks",t)),this.events.fatalError$.subscribe(new we("fatalError")),this.events.managedError$.subscribe(new we("managedError")),e.position$.subscribe(new we("position")),e.currentVideoTrack$.pipe(G(t=>t?.quality)).subscribe(new we("quality")),this.info.currentBuffer$.subscribe(new we("buffer")),e.isBuffering$.subscribe(new we("isBuffering"))].forEach(t=>this.subscription.add(t)),ma("codecs",C.video.supportedCodecs)}initTracerSubscription(){let e=VI(this.tracer.log.bind(this.tracer)),t=VI(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(Y()).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(Ct({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe(O(({currentQuality:i,videoBitrate:r})=>!!i&&!!r),Y((i,r)=>i.currentQuality===r.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe(O(i=>i>0),Y()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe(O(i=>i>0),Y()).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(Ct({currentBuffer:this.info.currentBuffer$.pipe(O(i=>i.end>0),Y((i,r)=>i.end===r.end&&i.start===r.start)),position:this.info.position$.pipe(Y())}).pipe(Od(1e3)).subscribe(e("currentBufferAndPosition"))).add(this.info.duration$.pipe(Y()).subscribe(e("duration"))).add(this.info.isBuffering$.subscribe(e("isBuffering"))).add(this.info.isLive$.pipe(Y()).subscribe(e("isLive"))).add(this.info.canChangePlaybackSpeed$.pipe(Y()).subscribe(e("canChangePlaybackSpeed"))).add(Ct({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe(O(({liveTime:i,liveBufferTime:r})=>!!i&&!!r),Od(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe(Y(),O(i=>i===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe(Y(),O(i=>i===!0)).subscribe(e("atLiveDurationEdge"))).add(this.info.muted$.pipe(Y()).subscribe(e("muted"))).add(this.info.volume$.pipe(Y()).subscribe(e("volume"))).add(this.info.isEnded$.pipe(Y(),O(i=>i===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add(Ct({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe(O(({throughputEstimation:i,rtt:r})=>!!i&&!!r),Od(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe(Y(),O(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:Yo.DOM,message:String(r)})})};this.subscription.add(ii(Vd(document,"visibilitychange"),Vd(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",ri({quality:t,availableTracks:ri(e),track:ri(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&&!Ia()}};import{Subscription as L7,Observable as $7,Subject as M7,ValueSubject as D7,VideoQuality as C7}from"@vkontakte/videoplayer-shared/es2024";var B7=`@vkontakte/videoplayer-core@${Ud}`;export{js as ChromecastState,eu as HttpConnectionType,$7 as Observable,Le as PlaybackState,Xo as Player,Qs as PredefinedQualityLimits,B7 as SDK_VERSION,M7 as Subject,L7 as Subscription,tu as Surface,Ud as VERSION,D7 as ValueSubject,xt as VideoFormat,C7 as VideoQuality,UL as areValidLiveRecordSources,C as clientChecker,ca as isMobile};
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 d=new Date(i.vkStartTime).valueOf(),c=new Date(i.programDateTime).valueOf();i.segmentStartTime=c-d}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(NB(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 X;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:jB.WTF,thrown:t,message:e})}};var Rs=class{constructor(e){this.subscription=new JB;this.videoState=new F("stopped");this.textTracksManager=null;this.liveTextManager=null;this.manifests$=new Ed([]);this.liveOffset=new yi;this.manifestStartTime$=new Ed(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"),P(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"?P(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),P(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"&&P(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"&&(P(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return QB(t)}};this.params=e,this.video=De(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:ZB.INVARIANT,url:this.params.source.url};let t=(i,r)=>No(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 qo(this.params.output.liveTime$,this.video,t,this.params.source.url,this.params.tuning.hlsLiveNewTextManagerDownloadThreshold):this.textTracksManager=new Ye(e.source.url),t(this.generateLiveUrl()).then(({qualityManifests:i,textTracks:r})=>{i.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:Uo.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:Uo.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(Se(this.params.source.url)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.maxSeekBackTime$=new Ed(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:Uo.WTF,message:"HlsLiveProvider internal logic error",thrown:u})},r=Ve(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(Be(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(ze(this.video,t.playbackRate,r.playbackRateState$,i)),s(Ke(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"),P(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),P(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(YB(),XT(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&&KT(l.to)){let d=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let c=this.manifests$.getValue().find(h=>h.id===d);c&&(this.params.output.currentVideoTrack$.next(c),this.params.output.hostname$.next(Se(c.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(WB({startTime:this.manifestStartTime$.pipe(zB(KT)),currentTime:r.timeUpdate$}).subscribe(({startTime:u,currentTime:o})=>this.params.output.liveTime$.next(u+o*1e3),i)),this.subscription.add(this.manifests$.pipe(XT(u=>u.map(({id:o,quality:l,size:p,bandwidth:d,fps:c})=>({id:o,quality:l,size:p,fps:c,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,i));let n=KB(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,XB(["init"])).pipe(GB(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),Ce(this.video)}prepare(){let e=this.selectManifest();if(Ho(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 d=String(parseFloat(l||""));p&&l&&r.searchParams.set(p,d)}}let s=this.params.format==="HLS_LIVE_CMAF"?2:0,n=se(r.toString(),this.liveOffset.getTotalOffset(),s);this.liveTextManager?.prepare(n),this.video.setAttribute("src",n),this.video.load(),yd(n).then(u=>{if(!Ho(u))this.maxSeekBackTime$.next(u);else{let o=this.params.source.maxSeekBackTime??this.maxSeekBackTime$.getValue();(Ho(o)||!isFinite(o))&&Xe(n).then(l=>l.text()).then(l=>{let p=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(l)?.[1];if(p){let d=new URL(p,n).toString();yd(d).then(c=>{Ho(c)||this.maxSeekBackTime$.next(c)})}}).catch(()=>{})}})}playIfAllowed(){_e(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),P(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Uo.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=se(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}};import{assertNever as e0,debounce as t0,ErrorCategory as xd,fromEvent as wd,isNonNullable as i0,isNullable as r0,map as JT,merge as ZT,observableFrom as eI,Subscription as a0,ValueSubject as tI,VideoQuality as s0}from"@vkontakte/videoplayer-shared/es2024";var Ls=class{constructor(e){this.subscription=new a0;this.videoState=new F("stopped");this.manifests$=new tI([]);this.unmuteAfterBrowserResetsHappened=new tI(!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"),P(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:d}=this.video;this.prepare(),u&&this.params.output.autoVideoTrackLimits$.next(u.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:d*1e3,forcePrecise:!0});return}switch(r?.to!=="paused"&&l.state==="requested"&&this.seek(l.position),t){case"ready":i==="ready"?P(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),P(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"&&P(this.params.desiredState.playbackState,"playing");return;case"paused":i==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):r?.to==="paused"&&P(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return e0(t)}};this.textTracksManager=new Ye(e.source.url),this.params=e,this.video=De(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:s0.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(Se(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.manifestRequested$.next(),No(se(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:t,textTracks:i})=>{this.params.output.manifestReceived$.next(),this.manifests$.next([this.masterManifest,...t]),this.params.tuning.useNativeHLSTextTracks||this.params.desiredState.internalTextTracks.startTransitionTo(i)},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:xd.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:xd.WTF,message:"HlsProvider internal logic error",thrown:u})},r=Ve(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(JT(u=>u.to)),this.params.output.playbackState$),this.subscription.add(mt(this.video,t.isLooped,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(ze(this.video,t.playbackRate,r.playbackRateState$,i)),kr({subscription:this.subscription,desiredState:t,videoElement$:this.params.output.element$,observableVideo:r}),this.subscription.add(Be(this.video,t.volume,r.volumeState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),P(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),P(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&&i0(l.to)){let h=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let f=this.manifests$.getValue().find(m=>m.id===h);f&&(this.params.output.currentVideoTrack$.next(f),this.params.output.hostname$.next(Se(f.url)))}let d=this.params.desiredState.playbackRate.getState(),c=this.params.output.element$.getValue()?.playbackRate;if(d!==c){let h=this.params.output.element$.getValue();h&&(this.params.desiredState.playbackRate.setState(d),h.playbackRate=d)}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"),P(t.playbackState,"paused")})),this.subscription.add(this.manifests$.pipe(JT(u=>u.map(({id:o,quality:l,size:p,bandwidth:d,fps:c})=>({id:o,quality:l,size:p,fps:c,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,i)),!C.device.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:u}=this.video;this.subscription.add(ZT(wd(u,"addtrack"),wd(u,"removetrack"),wd(u,"change"),eI(["init"])).subscribe(()=>{for(let o=0;o<u.length;o++)u[o].mode="hidden"},i))}let n=ZT(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,eI(["init"])).pipe(t0(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),Ce(this.video)}prepare(){let e=this.selectManifest();if(r0(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(){_e(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:xd.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};var aI=B(Yi(),1),Ad=B(pi(),1),sI=B(at(),1);import{assertNever as n0,assertNonNullable as iI,debounce as o0,ErrorCategory as rI,isHigherOrEqual as u0,isLowerOrEqual as l0,isNonNullable as c0,merge as d0,observableFrom as p0,Subscription as h0,map as f0}from"@vkontakte/videoplayer-shared/es2024";var $s=class{constructor(e){this.subscription=new h0;this.videoState=new F("stopped");this.trackUrls={};this.textTracksManager=new Ye;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"),P(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"?P(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),P(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"&&P(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&P(this.params.desiredState.playbackState,"paused");return;default:return n0(e)}};this.params=e,this.video=De(e.container,e.tuning),this.params.output.element$.next(this.video),(0,aI.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,Ad.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:rI.WTF,message:"MpegProvider internal logic error",thrown:u})},r=Ve(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(f0(u=>u.to)),this.params.output.playbackState$),this.subscription.add(mt(this.video,t.isLooped,i)),kr({subscription:this.subscription,desiredState:t,videoElement$:this.params.output.element$,observableVideo:r}),this.subscription.add(Be(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(ze(this.video,t.playbackRate,r.playbackRateState$,i)),s(Ke(this.video),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),P(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),P(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&&c0(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"),P(t.playbackState,"paused")})),this.textTracksManager.connect(this.video,t,e);let n=d0(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,p0(["init"])).pipe(o0(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),Ce(this.video)}prepare(){let e=this.params.desiredState.videoTrack.getState()?.id;iI(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];iI(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=Yt(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(Se(t))}playIfAllowed(){_e(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:rI.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=St(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,Ad.default)(this.trackUrls).map(l=>l.track);if(!r||!s||ur(e,n[0].quality,(0,sI.default)(n,-1)?.quality)){i();return}let u=e.max?l0(r,e.max):!0,o=e.min?u0(r,e.min):!0;u&&o||i(e)}};import{assertNever as oI,debounce as S0,merge as uI,observableFrom as v0,Subscription as y0,map as lI,ValueSubject as T0,ErrorCategory as kd,VideoQuality as I0}from"@vkontakte/videoplayer-shared/es2024";import{ErrorCategory as m0}from"@vkontakte/videoplayer-shared/es2024";var nI=["stun:videostun.mycdn.me:80"],b0=1e3,g0=3,Pd=()=>null,jo=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=Pd;this.externalStopCallback=Pd;this.externalErrorCallback=Pd;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:nI}]};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:m0.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),b0)}normalizeOptions(e={}){let t={stunServerList:nI,maxRetryNumber:g0,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var Ms=class{constructor(e){this.videoState=new F("stopped");this.maxSeekBackTime$=new T0(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"),P(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"),P(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"&&P(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&P(this.params.desiredState.playbackState,"paused");return;default:return oI(e)}};this.subscription=new y0,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=De(e.container,e.tuning),this.liveStreamClient=new jo(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),Ce(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,i=n=>{e.error$.next({id:"WebRTCLiveProvider",category:kd.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};this.subscription.add(uI(this.videoState.stateChangeStarted$.pipe(lI(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe(lI(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:u})=>{this.log({message:`[videoState change] ${u}: ${JSON.stringify(n)}`})}));let r=Ve(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(Ke(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(Be(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 oI(n.to)}},i)).add(uI(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,v0(["init"])).pipe(S0(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(Se(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:I0.INVARIANT}),this.video.srcObject=e,P(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:kd.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){_e(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:kd.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var Cr=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}};import{assertNever as Ds,assertNonNullable as ti,ErrorCategory as Qo,filter as mI,isNonNullable as bI,isNullable as R0,map as L0,merge as $0,once as M0,Subject as ne,Subscription as gI,ValueSubject as _,flattenObject as Rd}from"@vkontakte/videoplayer-shared/es2024";import{Observable as E0,map as cI,Subscription as x0,Subject as w0}from"@vkontakte/videoplayer-shared/es2024";var dI=a=>new E0(e=>{let t=new x0,i=a.desiredPlaybackState$.stateChangeStarted$.pipe(cI(({from:l,to:p})=>`${l}-${p}`)),r=a.desiredPlaybackState$.stateChangeEnded$,s=a.providerChanged$.pipe(cI(({type:l})=>l!==void 0)),n=new w0,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()}});import{ErrorCategory as A0,Subscription as P0,combine as k0,filter as hI,once as fI}from"@vkontakte/videoplayer-shared/es2024";function pI(){return new(window.AudioContext||window.webkitAudioContext)}var Br=class a{constructor(e,t,i,r){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=i;this.volumeMultiplier=r;this.destroyController=new X;this.subscriptions=new P0;this.audioContext=null;this.gainNode=null;this.mediaElementSource=null;this.subscriptions.add(this.provider$.pipe(hI(s=>!!s.type),fI()).subscribe(({type:s})=>this.subscribe(s)))}static{this.errorId="VolumeMultiplierManager"}subscribe(e){C.browser.isSafari&&e!=="MPEG"||this.subscriptions.add(k0({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe(hI(({playbackState:t,video:i,volume:{muted:r,volume:s}})=>t==="playing"&&!!i&&!r&&!!s),fI()).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=pI();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:A0.VIDEO_PIPELINE,message:e?.message??`${a.errorId} exception`,thrown:e})}};var D0={chunkDuration:5e3,maxParallelRequests:5},Cs=class{constructor(e){this.current$=new _({type:void 0});this.providerError$=new ne;this.noAvailableProvidersError$=new ne;this.volumeMultiplierError$=new ne;this.providerOutput={position$:new _(0),duration$:new _(1/0),volume$:new _({muted:!1,volume:1}),availableVideoStreams$:new _([]),currentVideoStream$:new _(void 0),availableVideoTracks$:new _([]),currentVideoTrack$:new _(void 0),availableVideoCodecs$:new _([]),availableAudioStreams$:new _([]),currentAudioStream$:new _(void 0),availableAudioTracks$:new _([]),availableAudioCodecs$:new _([]),currentVideoSegmentLength$:new _(0),currentAudioSegmentLength$:new _(0),isAudioAvailable$:new _(!0),autoVideoTrackLimitingAvailable$:new _(!1),autoVideoTrackLimits$:new _(void 0),currentBuffer$:new _(void 0),isBuffering$:new _(!0),error$:new ne,fetcherError$:new ne,fetcherRecoverableError$:new ne,warning$:new ne,willSeekEvent$:new ne,soundProhibitedEvent$:new ne,seekedEvent$:new ne,loopedEvent$:new ne,endedEvent$:new ne,manifestRequested$:new ne,manifestReceived$:new ne,firstBytesRequested$:new ne,firstBytesReceived$:new ne,firstBytesEvent$:new ne,loadedMetadataEvent$:new ne,firstFrameEvent$:new ne,canplay$:new ne,isLive$:new _(void 0),isLiveEnded$:new _(null),canPlayLiveTailBuffer$:new _(!1),isLowLatency$:new _(!1),canChangePlaybackSpeed$:new _(!0),liveTime$:new _(void 0),liveBufferTime$:new _(void 0),liveLatency$:new _(void 0),severeStallOccurred$:new ne,availableTextTracks$:new _([]),currentTextTrack$:new _(void 0),hostname$:new _(void 0),httpConnectionType$:new _(void 0),httpConnectionReused$:new _(void 0),inPiP$:new _(!1),inFullscreen$:new _(!1),element$:new _(void 0),elementVisible$:new _(!0),availableSources$:new _(void 0),is3DVideo$:new _(!1),playbackState$:new _(""),getCurrentTime$:new _(null)};this.subscription=new gI;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=zl([...nT(this.params.tuning),...sT(this.params.tuning)]).filter(l=>bI(e.sources[l])),{forceFormat:i,formatsToAvoid:r}=this.params.tuning,s=[];i?s=[i]:r.length?s=[...t.filter(l=>!(0,Ld.default)(r,l)),...t.filter(l=>(0,Ld.default)(r,l))]:s=t,this.log({message:`Selected formats: ${s.join(" > ")}`}),this.tracer.log("Selected formats",Rd(s)),this.screenFormatsIterator=new Cr(s);let n=[...Nc(!0),...Nc(!1)];this.chromecastFormatsIterator=new Cr(n.filter(l=>bI(e.sources[l]))),this.providerOutput.availableSources$.next(e.sources);let{volumeMultiplier:u=1,tuning:{useVolumeMultiplier:o}}=this.params;o&&u!==1&&Br.isSupported()&&(this.volumeMultiplierManager=new Br(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 Cr(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(R0(t)){this.handleNoFormatsError(e);return}let i;try{i=this.createProvider(e,t)}catch(r){this.providerError$.next({id:"ProviderNotConstructed",category:Qo.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 Ds(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 ti(o),this.params.tuning.useNewDashProvider?new Ps({...u,source:o,sourceHls:l,forceVideoCodec:this.videoCodecsIterator?.getValue()}):new hs({...u,source:o,sourceHls:l,forceVideoCodec:this.videoCodecsIterator?.getValue()})}case"DASH_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return ti(o),this.params.tuning.useNewDashProvider?new ks({...u,source:o}):new fs({...u,source:o})}case"HLS":case"HLS_ONDEMAND":case"HLS_FMP4":{let o=this.applyFailoverHost(t[e]);return ti(o),new Ls({...u,source:o})}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return ti(o),new Rs({...u,source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case"MPEG":{let o=this.applyFailoverHost(t[e]);return ti(o),new $s({...u,source:o})}case"DASH_LIVE":{let o=this.applyFailoverHost(t[e]);return ti(o),new ZS({...u,source:o,config:{...D0,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case"WEB_RTC_LIVE":{let o=this.applyFailoverHost(t[e]);return ti(o),new Ms({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 Ds(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 ti(u),new da({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 Ds(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return Ds(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 Ds(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,vI.default)((0,SI.default)(e).map(([r,s])=>[r,i(s)]))}initProviderErrorHandling(){let e=new gI,t=!1,i=0;return e.add($0(this.providerOutput.error$.pipe(mI(r=>!this.params.tuning.ignoreAudioRendererError||!r.message||!/AUDIO_RENDERER_ERROR/ig.test(r.message))),dI({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(L0(r=>({id:`ProviderHangup:${r}`,category:Qo.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(mI(({to:s})=>s==="playing"),M0()).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===Qo.NETWORK,o=r.category===Qo.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,d=this.videoCodecsIterator&&!this.videoCodecsIterator.isLast()&&this.params.tuning.dash.codecsPrioritizeEnabled,c=l&&!o&&(u&&t||!p);n={...n,isNetworkError:u,isFatalError:o,haveFailoverHost:l,tryFailover:c,canReinitProvider:p},p?(i++,this.reinitProvider()):c?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):d?this.switchToNextVideoCodec():(i=0,this.switchToNextProvider(s??"SCREEN"))}r.traceAsLog?this.tracer.log("providerInfo",Rd(n)):this.tracer.error("providerError",Rd(n))})),e}};import{fromEvent as Wo,once as C0,combine as B0,Subscription as yI,ValueSubject as $d,map as V0,filter as _0,isNonNullable as Go,now as Qe,safeStorage as Md}from"@vkontakte/videoplayer-shared/es2024";var O0=5e3,TI="one_video_throughput",II="one_video_rtt",Bs=window.navigator.connection,EI=()=>{let a=Bs?.downlink;if(Go(a)&&a!==10)return a*1e3},xI=()=>{let a=Bs?.rtt;if(Go(a)&&a!==3e3)return a},wI=(a,e,t)=>{let i=t*8,r=i/a;return i/(r+e)},Dd=class a{constructor(e){this.subscription=new yI;this.concurrentDownloads=new Set;this.tuningConfig=e;let t=a.load(TI)||(e.useBrowserEstimation?EI():void 0)||O0,i=a.load(II)??(e.useBrowserEstimation?xI():void 0)??0;if(this.throughput$=new $d(t),this.rtt$=new $d(i),this.rttAdjustedThroughput$=new $d(wI(t,i,e.rttPenaltyRequestSize)),this.throughput=Mt.getSmoothedValue(t,-1,e),this.rtt=Mt.getSmoothedValue(i,1,e),e.useBrowserEstimation){let r=()=>{let n=EI();n&&this.throughput.next(n);let u=xI();Go(u)&&this.rtt.next(u)};Bs&&"onchange"in Bs&&this.subscription.add(Wo(Bs,"change").subscribe(r)),r()}this.subscription.add(this.throughput.smoothed$.subscribe(r=>{Md.set(TI,r.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(r=>{Md.set(II,r.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(B0({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(V0(({throughput:r,rtt:s})=>wI(r,s,e.rttPenaltyRequestSize)),_0(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=Qe(),r=new yI;switch(this.subscription.add(r),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:r.add(Wo(e,"progress").pipe(C0()).subscribe(s=>{t=s.loaded,i=Qe()}));break;case 1:case 0:r.add(Wo(e,"loadstart").subscribe(()=>{t=0,i=Qe()}));break}r.add(Wo(e,"loadend").subscribe(s=>{if(e.status===200){let n=s.loaded,u=Qe(),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=Qe(),n=0,u=Qe(),o=p=>{this.concurrentDownloads.delete(e),i.releaseLock(),e.cancel(`Throughput Estimator error: ${p}`).catch(()=>{})},l=async({done:p,value:d})=>{if(p)!t&&this.addRawSpeed(r,Qe()-s,1),this.concurrentDownloads.delete(e);else if(d){if(t){let c=Qe();if(c-u>this.tuningConfig.lowLatency.continuesByteSequenceInterval||c-s>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let f=u-s;f&&this.addRawSpeed(n,f,1,t),n=d.byteLength,s=Qe()}else n+=d.byteLength;u=Qe()}else r+=d.byteLength,n+=d.byteLength,n>=this.tuningConfig.streamMinSampleSize&&Qe()-u>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,Qe()-u,this.concurrentDownloads.size),n=0,u=Qe());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=Md.get(e);if(Go(t))return parseInt(t,10)??void 0}},AI=Dd;import{fillWithDefault as F0,VideoQuality as zo}from"@vkontakte/videoplayer-shared/es2024";var PI={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:zo.Q_4320P,activeVideoAreaThreshold:.1,highQualityLimit:zo.Q_720P,trafficSavingLimit:zo.Q_480P},stallsManager:{enabled:!1,stallDurationNoDataBeforeQualityDecrease:500,stallDurationToBeCount:100,stallCountBeforeQualityDecrease:3,resetQualityRestrictionTimeout:1e4,ignoreStallsOnSeek:!0,stallsMetricsHistoryLength:5,maxPossibleStallDuration:3e4,minTvtToBeCounted:5,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:zo.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},dashCmafLive:{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},kI=a=>({...F0(a,PI),configName:[...a.configName??[],...PI.configName]});import{assertNonNullable as Bd,combine as Ct,ErrorCategory as Yo,filter as O,filterChanged as Y,fromEvent as Vd,isNonNullable as MI,isNullable as W0,Logger as G0,map as G,mapTo as DI,merge as ii,now as Ko,once as N,Subject as W,Subscription as CI,tap as _d,ValueSubject as k,isHigher as z0,isInvariantQuality as BI,flattenObject as ri,throttle as Od,getTraceSubscriptionMethod as VI,TracerFactory as Y0,InternalsExposure as K0,getPlayerId as X0}from"@vkontakte/videoplayer-shared/es2024";import{merge as N0,map as q0,filter as RI,isNonNullable as U0}from"@vkontakte/videoplayer-shared/es2024";var Cd=({seekState:a,position$:e})=>N0(a.stateChangeEnded$.pipe(q0(({to:t})=>t.state==="none"?void 0:(t.position??NaN)/1e3),RI(U0)),e.pipe(RI(()=>a.getState().state==="none")));import{assertNonNullable as H0}from"@vkontakte/videoplayer-shared/es2024";var LI=a=>{let e=typeof a.container=="string"?document.getElementById(a.container):a.container;return H0(e,`Wrong container or containerId {${a.container}}`),e};import{filter as j0,once as Q0}from"@vkontakte/videoplayer-shared/es2024";var $I=(a,e,t,i)=>{a!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&t?.getValue().length===0?t.pipe(j0(r=>r.length>0),Q0()).subscribe(r=>{r.find(i)&&e.startTransitionTo(a)}):(a===void 0||t?.getValue().find(i))&&e.startTransitionTo(a)};var Xo=class{constructor(e={configName:[]},t=Y0.createRootTracer(!1),i){this.subscription=new CI;this.logger=new G0;this.abrLogger=this.logger.createComponentLog("ABR");this.internalsExposure=null;this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new k(!1);this.hasLiveOffsetByPausedTimer=0;this.playerInitRequest=0;this.playerInited=new k(!1);this.wasSetStartedQuality=!1;this.desiredState={playbackState:new F("stopped"),seekState:new F({state:"none"}),volume:new F({volume:1,muted:!1}),videoTrack:new F(void 0),videoStream:new F(void 0),audioStream:new F(void 0),autoVideoTrackSwitching:new F(!0),autoVideoTrackLimits:new F({}),isLooped:new F(!1),isLowLatency:new F(!1),playbackRate:new F(1),externalTextTracks:new F([]),internalTextTracks:new F([]),currentTextTrack:new F(void 0),textTrackCuesSettings:new F({}),cameraOrientation:new F({x:0,y:0})};this.info={playbackState$:new k(void 0),position$:new k(0),duration$:new k(1/0),muted$:new k(!1),volume$:new k(1),availableVideoStreams$:new k([]),currentVideoStream$:new k(void 0),availableQualities$:new k([]),availableQualitiesFps$:new k({}),currentQuality$:new k(void 0),isAutoQualityEnabled$:new k(!0),autoQualityLimitingAvailable$:new k(!1),autoQualityLimits$:new k({}),predefinedQualityLimitType$:new k("unknown"),availableAudioStreams$:new k([]),currentAudioStream$:new k(void 0),availableAudioTracks$:new k([]),isAudioAvailable$:new k(!0),currentPlaybackRate$:new k(1),currentBuffer$:new k({start:0,end:0}),isBuffering$:new k(!0),isStalled$:new k(!1),isEnded$:new k(!1),isLooped$:new k(!1),isLive$:new k(void 0),isLiveEnded$:new k(null),canPlayLiveTailBuffer$:new k(!1),canChangePlaybackSpeed$:new k(void 0),atLiveEdge$:new k(void 0),atLiveDurationEdge$:new k(void 0),liveTime$:new k(void 0),liveBufferTime$:new k(void 0),liveLatency$:new k(void 0),currentFormat$:new k(void 0),availableTextTracks$:new k([]),currentTextTrack$:new k(void 0),throughputEstimation$:new k(void 0),rttEstimation$:new k(void 0),videoBitrate$:new k(void 0),hostname$:new k(void 0),httpConnectionType$:new k(void 0),httpConnectionReused$:new k(void 0),surface$:new k("none"),chromecastState$:new k("NOT_AVAILABLE"),chromecastDeviceName$:new k(void 0),intrinsicVideoSize$:new k(void 0),availableSources$:new k(void 0),is3DVideo$:new k(!1),currentVideoSegmentLength$:new k(0),currentAudioSegmentLength$:new k(0)};this.events={inited$:new W,ready$:new W,started$:new W,playing$:new W,paused$:new W,stopped$:new W,willReady$:new W,willStart$:new W,willResume$:new W,willPause$:new W,willStop$:new W,willDestruct$:new W,watchCoverageRecord$:new W,watchCoverageLive$:new W,managedError$:new W,fatalError$:new W,fetcherRecoverableError$:new W,ended$:new W,looped$:new W,seeked$:new W,willSeek$:new W,autoplaySoundProhibited$:new W,manifestRequested$:new W,manifestReceived$:new W,firstBytesRequested$:new W,firstBytesReceived$:new W,firstBytes$:new W,loadedMetadata$:new W,firstFrame$:new W,canplay$:new W,log$:new W,fetcherError$:new W,severeStallOccured$:new W};this.experimental={element$:new k(void 0),tuningConfigName$:new k([]),enableDebugTelemetry$:new k(!1),dumpTelemetry:xS,getCurrentTime$:new k(null)};if(this.initLogs(),this.tuning=kI(e),this.tracer=t,this.tuning.suppressExceptionsInObservables&&((0,Fd.default)(this.info).forEach(r=>r.setSuppressErrors(!0)),(0,Fd.default)(this.events).forEach(r=>r.setSuppressErrors(!0))),this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new en({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new AI(this.tuning.throughputEstimator),e.exposeInternalsToGlobal&&(this.internalsExposure=new K0("core",X0(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,(f,m)=>{let g=typeof m;return(0,_I.default)(["number","string","boolean"],g)?m:m===null?null:`<${g}>`})),d=`Player.${String(s)}`,c=`Exception calling ${d} (${p.join(", ")})`;throw this.events.fatalError$.next({id:d,category:Yo.WTF,message:c,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",ri(n)),this.domContainer=LI(e),this.chromecastInitializer.contentId=e.meta?.videoId,this.providerContainer=new Cs({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?C.isInited$.pipe(O(s=>!!s),N()).subscribe(()=>{console.log("Core SDK async start"),i()}):i()};return this.isNotActiveTabCase()?(this.tracer.log("request play from hidden tab"),Vd(document,"visibilitychange").pipe(N()).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()}prepare(){return this.subscription.add(this.playerInited.pipe(O(e=>!!e),N()).subscribe(()=>{let e=this.desiredState.playbackState;this.tracer.log("prepare",{currentPlayBackState:e.getState()}),e.getState()==="stopped"&&e.startTransitionTo("ready")})),this}play(){return this.subscription.add(this.playerInited.pipe(O(e=>!!e),N()).subscribe(()=>{let e=this.desiredState.playbackState;this.tracer.log("play",{currentPlayBackState:e.getState()}),e.getState()!=="playing"&&e.startTransitionTo("playing")})),this}pause(){return this.subscription.add(this.playerInited.pipe(O(e=>!!e),N()).subscribe(()=>{let e=this.desiredState.playbackState;this.tracer.log("pause",{currentPlayBackState:e.getState()}),e.getState()!=="paused"&&e.startTransitionTo("paused")})),this}stop(){return this.subscription.add(this.playerInited.pipe(O(e=>!!e),N()).subscribe(()=>{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.subscription.add(this.playerInited.pipe(O(i=>!!i),N()).subscribe(()=>{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.subscription.add(this.playerInited.pipe(O(t=>!!t),N()).subscribe(()=>{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.subscription.add(this.playerInited.pipe(O(i=>!!i),N()).subscribe(()=>{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.subscription.add(this.playerInited.pipe(O(i=>!!i),N()).subscribe(()=>{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.subscription.add(this.playerInited.pipe(O(t=>!!t),N()).subscribe(()=>{this.desiredState.videoStream.startTransitionTo(e)})),this}setAudioStream(e){return this.subscription.add(this.playerInited.pipe(O(t=>!!t),N()).subscribe(()=>{this.desiredState.audioStream.startTransitionTo(e)})),this}setQuality(e){return this.subscription.add(this.playerInited.pipe(O(t=>!!t),N()).subscribe(()=>{Bd(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(O(i=>i.length>0),N()).subscribe(i=>{this.setVideoTrackIdByQuality(i,e)}):this.explicitInitialQuality=e:t.length>0&&this.setVideoTrackIdByQuality(t,e)})),this}setAutoQuality(e){return this.subscription.add(this.playerInited.pipe(O(t=>!!t),N()).subscribe(()=>{this.tracer.log("setAutoQuality",{enable:e}),this.desiredState.autoVideoTrackSwitching.startTransitionTo(e)})),this}setAutoQualityLimits(e){return this.subscription.add(this.playerInited.pipe(O(t=>!!t),N()).subscribe(()=>{this.tracer.log("setAutoQualityLimits",ri(e)),this.desiredState.autoVideoTrackLimits.startTransitionTo(e)})),this}setPredefinedQualityLimits(e){return this.subscription.add(this.playerInited.pipe(O(t=>!!t),N()).subscribe(()=>{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.subscription.add(this.playerInited.pipe(O(t=>!!t),N()).subscribe(()=>{this.tracer.log("setPlaybackRate",{playbackRate:e}),this.desiredState.playbackRate.startTransitionTo(e)})),this}setExternalTextTracks(e){return this.subscription.add(this.playerInited.pipe(O(t=>!!t),N()).subscribe(()=>{e.length&&this.tracer.log("setExternalTextTracks",ri(e)),this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>({type:"external",...t})))})),this}selectTextTrack(e){return this.subscription.add(this.playerInited.pipe(O(t=>!!t),N()).subscribe(()=>{$I(e,this.desiredState.currentTextTrack,this.providerContainer?.providerOutput.availableTextTracks$,t=>t.id===e),this.tracer.log("selectTextTrack",{textTrackId:e})})),this}setTextTrackCueSettings(e){return this.subscription.add(this.playerInited.pipe(O(t=>!!t),N()).subscribe(()=>{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.subscription.add(this.playerInited.pipe(O(t=>!!t),N()).subscribe(()=>{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.subscription.add(this.playerInited.pipe(O(i=>!!i),N()).subscribe(()=>{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.subscription.add(this.playerInited.pipe(O(t=>!!t),N()).subscribe(()=>{let t=this.getScene3D();this.tracer.log("stopCameraManualRotation",{isScene3DAvailable:!!t,immediate:e}),t&&t.stopCameraManualRotation(e)})),this}moveCameraFocusPX(e,t){return this.subscription.add(this.playerInited.pipe(O(i=>!!i),N()).subscribe(()=>{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.subscription.add(this.playerInited.pipe(O(e=>e),N()).subscribe(()=>{let e=this.getScene3D();e&&e.holdCamera()})),this}releaseCamera(){return this.subscription.add(this.playerInited.pipe(O(e=>!!e),N()).subscribe(()=>{let e=this.getScene3D();e&&e.releaseCamera()})),this}getExactTime(){if(!this.providerContainer)return 0;let e=this.providerContainer.providerOutput.element$.getValue();if(W0(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),i=t.state==="none"?void 0:t.position;return MI(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(ii(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(G(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(G(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(G(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(G(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(G(e=>e.to)).subscribe(e=>{this.info.autoQualityLimits$.next(e);let{highQualityLimit:t,trafficSavingLimit:i}=this.tuning.autoTrackSelection;this.info.predefinedQualityLimitType$.next(AS(e,t,i))})),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(O(({from:e})=>e==="stopped"),N()).subscribe(()=>{this.initedAt=Ko(),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",ri(n)),n.state==="requested"?this.desiredState.seekState.setState({...n,state:"applying"}):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:Yo.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.soundProhibitedEvent$.pipe(N()).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",ri(n)),n.state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe(G(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(G(n=>n.destination),Y()).subscribe(()=>this.isPlaybackStarted=!1)).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add(Ct({availableVideoTracks:e.providerOutput.availableVideoTracks$,currentVideoStream:e.providerOutput.currentVideoStream$}).pipe(G(({availableVideoTracks:n,currentVideoStream:u})=>n.filter(o=>u?u.id===o.streamId:!0).map(({quality:o})=>o).sort((o,l)=>BI(o)?1:BI(l)?-1:z0(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(Y()).subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.pipe(O(n=>MI(n))).subscribe(n=>{this.info.currentQuality$.next(n?.quality),this.info.videoBitrate$.next(n?.bitrate)})).add(e.providerOutput.currentVideoSegmentLength$.pipe(Y((n,u)=>Math.round(n)===Math.round(u))).subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.pipe(Y((n,u)=>Math.round(n)===Math.round(u))).subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe(Y()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(Y()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(Y()).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(G(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(_d(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(Ct({hasLiveOffsetByPaused:ii(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(G(n=>n.to),Y(),G(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(Ct({atLiveEdge:Ct({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:Cd({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(G(({isLive:n,position:u,isLowLatency:o})=>{let l=this.getActiveLiveDelay(o);return n&&Math.abs(u)<l/1e3}),Y(),_d(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(G(({atLiveEdge:n,hasPausedTimeoutCase:u})=>n&&!u)).subscribe(this.info.atLiveEdge$)).add(Ct({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(G(({isLive:n,position:u,duration:o})=>n&&(Math.abs(o)-Math.abs(u))*1e3<this.tuning.live.activeLiveDelay),Y(),_d(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(G(n=>n.muted),Y()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(G(n=>n.volume),Y()).subscribe(this.info.volume$)).add(Cd({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(ii(e.providerOutput.endedEvent$.pipe(DI(!0)),e.providerOutput.seekedEvent$.pipe(DI(!1))).pipe(Y()).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(G(n=>({id:n?`No${n}`:"NoProviders",category:Yo.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(N()).subscribe(this.events.manifestRequested$)).add(e.providerOutput.manifestReceived$.pipe(N()).subscribe(this.events.manifestReceived$)).add(e.providerOutput.firstBytesRequested$.pipe(N()).subscribe(this.events.firstBytesRequested$)).add(e.providerOutput.firstBytesReceived$.pipe(N()).subscribe(this.events.firstBytesReceived$)).add(e.providerOutput.firstBytesEvent$.pipe(N(),G(n=>n??Ko()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe(N(),G(()=>Ko()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(N(),G(()=>Ko()-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 k(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let i=new k(!0);this.subscription.add(e.current$.subscribe(()=>i.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(O(({to:n})=>n==="playing"),N()).subscribe(()=>i.next(!1)));let r=0,s=ii(e.providerOutput.isBuffering$,t,i).pipe(G(()=>{let n=e.providerOutput.isBuffering$.getValue(),u=t.getValue()||i.getValue();return n&&!u}),Y());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(ii(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(ii(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(),d;p==="CONNECTED"?d="second_screen":o?l?n?d="pip":u?d="fullscreen":d="inline":d="invisible":d="none",this.info.surface$.getValue()!==d&&this.info.surface$.next(d)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(G(e=>e?.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){let t=new CI;this.subscription.add(t),this.subscription.add(e.current$.pipe(Y((i,r)=>i.provider===r.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(O(i=>i.length>0),N()).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=St(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(ii(this.desiredState.videoTrack.stateChangeStarted$.pipe(G(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(G(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(G(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(G(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(G(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(G(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(G(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(G(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(G(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;Bd(this.providerContainer),Bd(e),ES(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(t=>IS(t)),this.providerContainer.current$.subscribe(({type:t})=>ma("provider",t)),e.duration$.subscribe(t=>ma("duration",t)),e.availableVideoTracks$.pipe(O(t=>!!t.length),N()).subscribe(t=>ma("tracks",t)),this.events.fatalError$.subscribe(new we("fatalError")),this.events.managedError$.subscribe(new we("managedError")),e.position$.subscribe(new we("position")),e.currentVideoTrack$.pipe(G(t=>t?.quality)).subscribe(new we("quality")),this.info.currentBuffer$.subscribe(new we("buffer")),e.isBuffering$.subscribe(new we("isBuffering"))].forEach(t=>this.subscription.add(t)),ma("codecs",C.video.supportedCodecs)}initTracerSubscription(){let e=VI(this.tracer.log.bind(this.tracer)),t=VI(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(Y()).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(Ct({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe(O(({currentQuality:i,videoBitrate:r})=>!!i&&!!r),Y((i,r)=>i.currentQuality===r.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe(O(i=>i>0),Y()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe(O(i=>i>0),Y()).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(Ct({currentBuffer:this.info.currentBuffer$.pipe(O(i=>i.end>0),Y((i,r)=>i.end===r.end&&i.start===r.start)),position:this.info.position$.pipe(Y())}).pipe(Od(1e3)).subscribe(e("currentBufferAndPosition"))).add(this.info.duration$.pipe(Y()).subscribe(e("duration"))).add(this.info.isBuffering$.subscribe(e("isBuffering"))).add(this.info.isLive$.pipe(Y()).subscribe(e("isLive"))).add(this.info.canChangePlaybackSpeed$.pipe(Y()).subscribe(e("canChangePlaybackSpeed"))).add(Ct({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe(O(({liveTime:i,liveBufferTime:r})=>!!i&&!!r),Od(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe(Y(),O(i=>i===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe(Y(),O(i=>i===!0)).subscribe(e("atLiveDurationEdge"))).add(this.info.muted$.pipe(Y()).subscribe(e("muted"))).add(this.info.volume$.pipe(Y()).subscribe(e("volume"))).add(this.info.isEnded$.pipe(Y(),O(i=>i===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add(Ct({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe(O(({throughputEstimation:i,rtt:r})=>!!i&&!!r),Od(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe(Y(),O(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:Yo.DOM,message:String(r)})})};this.subscription.add(ii(Vd(document,"visibilitychange"),Vd(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",ri({quality:t,availableTracks:ri(e),track:ri(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&&!Ia()}};import{Subscription as LX,Observable as $X,Subject as MX,ValueSubject as DX,VideoQuality as CX}from"@vkontakte/videoplayer-shared/es2024";var BX=`@vkontakte/videoplayer-core@${Ud}`;export{js as ChromecastState,eu as HttpConnectionType,$X as Observable,Le as PlaybackState,Xo as Player,Qs as PredefinedQualityLimits,BX as SDK_VERSION,MX as Subject,LX as Subscription,tu as Surface,Ud as VERSION,DX as ValueSubject,xt as VideoFormat,CX as VideoQuality,UL as areValidLiveRecordSources,C as clientChecker,ca as isMobile};