@vkontakte/videoplayer-core 2.0.140-dev.4c27f703.0 → 2.0.140-dev.7b3cdcf7.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,127 +1,127 @@
1
1
  /**
2
- * @vkontakte/videoplayer-core v2.0.140-dev.4c27f703.0
3
- * Tue, 02 Sep 2025 09:42:02 GMT
2
+ * @vkontakte/videoplayer-core v2.0.140-dev.7b3cdcf7.0
3
+ * Tue, 09 Sep 2025 14:28:38 GMT
4
4
  * https://st.mycdn.me/static/vkontakte-videoplayer/2-0-140/doc/
5
5
  */
6
- var NI=Object.create;var Nd=Object.defineProperty;var qI=Object.getOwnPropertyDescriptor;var UI=Object.getOwnPropertyNames;var HI=Object.getPrototypeOf,jI=Object.prototype.hasOwnProperty;var m=(a,e)=>()=>(e||a((e={exports:{}}).exports,e),e.exports);var QI=(a,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of UI(e))!jI.call(a,r)&&r!==t&&Nd(a,r,{get:()=>e[r],enumerable:!(i=qI(e,r))||i.enumerable});return a};var C=(a,e,t)=>(t=a!=null?NI(HI(a)):{},QI(e||!a||!a.__esModule?Nd(t,"default",{value:a,enumerable:!0}):t,a));var re=m((Xo,Ud)=>{"use strict";var Fr=function(a){return a&&a.Math===Math&&a};Ud.exports=Fr(typeof globalThis=="object"&&globalThis)||Fr(typeof window=="object"&&window)||Fr(typeof self=="object"&&self)||Fr(typeof global=="object"&&global)||Fr(typeof Xo=="object"&&Xo)||function(){return this}()||Function("return this")()});var ce=m((G0,Hd)=>{"use strict";Hd.exports=function(a){try{return!!a()}catch{return!0}}});var Nr=m((z0,jd)=>{"use strict";var WI=ce();jd.exports=!WI(function(){var a=function(){}.bind();return typeof a!="function"||a.hasOwnProperty("prototype")})});var Jo=m((Y0,zd)=>{"use strict";var GI=Nr(),Gd=Function.prototype,Qd=Gd.apply,Wd=Gd.call;zd.exports=typeof Reflect=="object"&&Reflect.apply||(GI?Wd.bind(Qd):function(){return Wd.apply(Qd,arguments)})});var de=m((K0,Xd)=>{"use strict";var Yd=Nr(),Kd=Function.prototype,Zo=Kd.call,zI=Yd&&Kd.bind.bind(Zo,Zo);Xd.exports=Yd?zI:function(a){return function(){return Zo.apply(a,arguments)}}});var si=m((X0,Zd)=>{"use strict";var Jd=de(),YI=Jd({}.toString),KI=Jd("".slice);Zd.exports=function(a){return KI(YI(a),8,-1)}});var eu=m((J0,ep)=>{"use strict";var XI=si(),JI=de();ep.exports=function(a){if(XI(a)==="Function")return JI(a)}});var ae=m((Z0,tp)=>{"use strict";var tu=typeof document=="object"&&document.all;tp.exports=typeof tu>"u"&&tu!==void 0?function(a){return typeof a=="function"||a===tu}:function(a){return typeof a=="function"}});var Fe=m((eV,ip)=>{"use strict";var ZI=ce();ip.exports=!ZI(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var Ne=m((tV,rp)=>{"use strict";var eE=Nr(),_s=Function.prototype.call;rp.exports=eE?_s.bind(_s):function(){return _s.apply(_s,arguments)}});var iu=m(np=>{"use strict";var ap={}.propertyIsEnumerable,sp=Object.getOwnPropertyDescriptor,tE=sp&&!ap.call({1:2},1);np.f=tE?function(e){var t=sp(this,e);return!!t&&t.enumerable}:ap});var qr=m((rV,op)=>{"use strict";op.exports=function(a,e){return{enumerable:!(a&1),configurable:!(a&2),writable:!(a&4),value:e}}});var lp=m((aV,up)=>{"use strict";var iE=de(),rE=ce(),aE=si(),ru=Object,sE=iE("".split);up.exports=rE(function(){return!ru("z").propertyIsEnumerable(0)})?function(a){return aE(a)==="String"?sE(a,""):ru(a)}:ru});var Ur=m((sV,cp)=>{"use strict";cp.exports=function(a){return a==null}});var Ft=m((nV,dp)=>{"use strict";var nE=Ur(),oE=TypeError;dp.exports=function(a){if(nE(a))throw new oE("Can't call method on "+a);return a}});var ni=m((oV,pp)=>{"use strict";var uE=lp(),lE=Ft();pp.exports=function(a){return uE(lE(a))}});var Le=m((uV,hp)=>{"use strict";var cE=ae();hp.exports=function(a){return typeof a=="object"?a!==null:cE(a)}});var oi=m((lV,fp)=>{"use strict";fp.exports={}});var wt=m((cV,bp)=>{"use strict";var au=oi(),su=re(),dE=ae(),mp=function(a){return dE(a)?a:void 0};bp.exports=function(a,e){return arguments.length<2?mp(au[a])||mp(su[a]):au[a]&&au[a][e]||su[a]&&su[a][e]}});var Hr=m((dV,gp)=>{"use strict";var pE=de();gp.exports=pE({}.isPrototypeOf)});var ui=m((pV,yp)=>{"use strict";var hE=re(),Sp=hE.navigator,vp=Sp&&Sp.userAgent;yp.exports=vp?String(vp):""});var ou=m((hV,Ap)=>{"use strict";var wp=re(),nu=ui(),Tp=wp.process,Ip=wp.Deno,Ep=Tp&&Tp.versions||Ip&&Ip.version,xp=Ep&&Ep.v8,et,Os;xp&&(et=xp.split("."),Os=et[0]>0&&et[0]<4?1:+(et[0]+et[1]));!Os&&nu&&(et=nu.match(/Edge\/(\d+)/),(!et||et[1]>=74)&&(et=nu.match(/Chrome\/(\d+)/),et&&(Os=+et[1])));Ap.exports=Os});var uu=m((fV,kp)=>{"use strict";var Pp=ou(),fE=ce(),mE=re(),bE=mE.String;kp.exports=!!Object.getOwnPropertySymbols&&!fE(function(){var a=Symbol("symbol detection");return!bE(a)||!(Object(a)instanceof Symbol)||!Symbol.sham&&Pp&&Pp<41})});var lu=m((mV,Rp)=>{"use strict";var gE=uu();Rp.exports=gE&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var cu=m((bV,Lp)=>{"use strict";var SE=wt(),vE=ae(),yE=Hr(),TE=lu(),IE=Object;Lp.exports=TE?function(a){return typeof a=="symbol"}:function(a){var e=SE("Symbol");return vE(e)&&yE(e.prototype,IE(a))}});var jr=m((gV,$p)=>{"use strict";var EE=String;$p.exports=function(a){try{return EE(a)}catch{return"Object"}}});var ht=m((SV,Mp)=>{"use strict";var xE=ae(),wE=jr(),AE=TypeError;Mp.exports=function(a){if(xE(a))return a;throw new AE(wE(a)+" is not a function")}});var Qr=m((vV,Dp)=>{"use strict";var PE=ht(),kE=Ur();Dp.exports=function(a,e){var t=a[e];return kE(t)?void 0:PE(t)}});var Bp=m((yV,Cp)=>{"use strict";var du=Ne(),pu=ae(),hu=Le(),RE=TypeError;Cp.exports=function(a,e){var t,i;if(e==="string"&&pu(t=a.toString)&&!hu(i=du(t,a))||pu(t=a.valueOf)&&!hu(i=du(t,a))||e!=="string"&&pu(t=a.toString)&&!hu(i=du(t,a)))return i;throw new RE("Can't convert object to primitive value")}});var tt=m((TV,Vp)=>{"use strict";Vp.exports=!0});var Fp=m((IV,Op)=>{"use strict";var _p=re(),LE=Object.defineProperty;Op.exports=function(a,e){try{LE(_p,a,{value:e,configurable:!0,writable:!0})}catch{_p[a]=e}return e}});var Wr=m((EV,Up)=>{"use strict";var $E=tt(),ME=re(),DE=Fp(),Np="__core-js_shared__",qp=Up.exports=ME[Np]||DE(Np,{});(qp.versions||(qp.versions=[])).push({version:"3.43.0",mode:$E?"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 fu=m((xV,jp)=>{"use strict";var Hp=Wr();jp.exports=function(a,e){return Hp[a]||(Hp[a]=e||{})}});var Fi=m((wV,Qp)=>{"use strict";var CE=Ft(),BE=Object;Qp.exports=function(a){return BE(CE(a))}});var it=m((AV,Wp)=>{"use strict";var VE=de(),_E=Fi(),OE=VE({}.hasOwnProperty);Wp.exports=Object.hasOwn||function(e,t){return OE(_E(e),t)}});var mu=m((PV,Gp)=>{"use strict";var FE=de(),NE=0,qE=Math.random(),UE=FE(1.1.toString);Gp.exports=function(a){return"Symbol("+(a===void 0?"":a)+")_"+UE(++NE+qE,36)}});var be=m((kV,Yp)=>{"use strict";var HE=re(),jE=fu(),zp=it(),QE=mu(),WE=uu(),GE=lu(),Ni=HE.Symbol,bu=jE("wks"),zE=GE?Ni.for||Ni:Ni&&Ni.withoutSetter||QE;Yp.exports=function(a){return zp(bu,a)||(bu[a]=WE&&zp(Ni,a)?Ni[a]:zE("Symbol."+a)),bu[a]}});var Zp=m((RV,Jp)=>{"use strict";var YE=Ne(),Kp=Le(),Xp=cu(),KE=Qr(),XE=Bp(),JE=be(),ZE=TypeError,ex=JE("toPrimitive");Jp.exports=function(a,e){if(!Kp(a)||Xp(a))return a;var t=KE(a,ex),i;if(t){if(e===void 0&&(e="default"),i=YE(t,a,e),!Kp(i)||Xp(i))return i;throw new ZE("Can't convert object to primitive value")}return e===void 0&&(e="number"),XE(a,e)}});var gu=m((LV,eh)=>{"use strict";var tx=Zp(),ix=cu();eh.exports=function(a){var e=tx(a,"string");return ix(e)?e:e+""}});var Fs=m(($V,ih)=>{"use strict";var rx=re(),th=Le(),Su=rx.document,ax=th(Su)&&th(Su.createElement);ih.exports=function(a){return ax?Su.createElement(a):{}}});var vu=m((MV,rh)=>{"use strict";var sx=Fe(),nx=ce(),ox=Fs();rh.exports=!sx&&!nx(function(){return Object.defineProperty(ox("div"),"a",{get:function(){return 7}}).a!==7})});var nh=m(sh=>{"use strict";var ux=Fe(),lx=Ne(),cx=iu(),dx=qr(),px=ni(),hx=gu(),fx=it(),mx=vu(),ah=Object.getOwnPropertyDescriptor;sh.f=ux?ah:function(e,t){if(e=px(e),t=hx(t),mx)try{return ah(e,t)}catch{}if(fx(e,t))return dx(!lx(cx.f,e,t),e[t])}});var yu=m((CV,oh)=>{"use strict";var bx=ce(),gx=ae(),Sx=/#|\.prototype\./,Gr=function(a,e){var t=yx[vx(a)];return t===Ix?!0:t===Tx?!1:gx(e)?bx(e):!!e},vx=Gr.normalize=function(a){return String(a).replace(Sx,".").toLowerCase()},yx=Gr.data={},Tx=Gr.NATIVE="N",Ix=Gr.POLYFILL="P";oh.exports=Gr});var qi=m((BV,lh)=>{"use strict";var uh=eu(),Ex=ht(),xx=Nr(),wx=uh(uh.bind);lh.exports=function(a,e){return Ex(a),e===void 0?a:xx?wx(a,e):function(){return a.apply(e,arguments)}}});var Tu=m((VV,ch)=>{"use strict";var Ax=Fe(),Px=ce();ch.exports=Ax&&Px(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var ft=m((_V,dh)=>{"use strict";var kx=Le(),Rx=String,Lx=TypeError;dh.exports=function(a){if(kx(a))return a;throw new Lx(Rx(a)+" is not an object")}});var li=m(hh=>{"use strict";var $x=Fe(),Mx=vu(),Dx=Tu(),Ns=ft(),ph=gu(),Cx=TypeError,Iu=Object.defineProperty,Bx=Object.getOwnPropertyDescriptor,Eu="enumerable",xu="configurable",wu="writable";hh.f=$x?Dx?function(e,t,i){if(Ns(e),t=ph(t),Ns(i),typeof e=="function"&&t==="prototype"&&"value"in i&&wu in i&&!i[wu]){var r=Bx(e,t);r&&r[wu]&&(e[t]=i.value,i={configurable:xu in i?i[xu]:r[xu],enumerable:Eu in i?i[Eu]:r[Eu],writable:!1})}return Iu(e,t,i)}:Iu:function(e,t,i){if(Ns(e),t=ph(t),Ns(i),Mx)try{return Iu(e,t,i)}catch{}if("get"in i||"set"in i)throw new Cx("Accessors not supported");return"value"in i&&(e[t]=i.value),e}});var Ui=m((FV,fh)=>{"use strict";var Vx=Fe(),_x=li(),Ox=qr();fh.exports=Vx?function(a,e,t){return _x.f(a,e,Ox(1,t))}:function(a,e,t){return a[e]=t,a}});var oe=m((NV,bh)=>{"use strict";var zr=re(),Fx=Jo(),Nx=eu(),qx=ae(),Ux=nh().f,Hx=yu(),Hi=oi(),jx=qi(),ji=Ui(),mh=it();Wr();var Qx=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 Fx(a,this,arguments)};return e.prototype=a.prototype,e};bh.exports=function(a,e){var t=a.target,i=a.global,r=a.stat,s=a.proto,n=i?zr:r?zr[t]:zr[t]&&zr[t].prototype,u=i?Hi:Hi[t]||ji(Hi,t,{})[t],o=u.prototype,l,c,p,d,h,f,b,S,g;for(d in e)l=Hx(i?d:t+(r?".":"#")+d,a.forced),c=!l&&n&&mh(n,d),f=u[d],c&&(a.dontCallGetSet?(g=Ux(n,d),b=g&&g.value):b=n[d]),h=c&&b?b:e[d],!(!l&&!s&&typeof f==typeof h)&&(a.bind&&c?S=jx(h,zr):a.wrap&&c?S=Qx(h):s&&qx(h)?S=Nx(h):S=h,(a.sham||h&&h.sham||f&&f.sham)&&ji(S,"sham",!0),ji(u,d,S),s&&(p=t+"Prototype",mh(Hi,p)||ji(Hi,p,{}),ji(Hi[p],d,h),a.real&&o&&(l||!o[d])&&ji(o,d,h)))}});var qs=m((qV,Sh)=>{"use strict";var Wx=fu(),Gx=mu(),gh=Wx("keys");Sh.exports=function(a){return gh[a]||(gh[a]=Gx(a))}});var yh=m((UV,vh)=>{"use strict";var zx=ce();vh.exports=!zx(function(){function a(){}return a.prototype.constructor=null,Object.getPrototypeOf(new a)!==a.prototype})});var Us=m((HV,Ih)=>{"use strict";var Yx=it(),Kx=ae(),Xx=Fi(),Jx=qs(),Zx=yh(),Th=Jx("IE_PROTO"),Au=Object,ew=Au.prototype;Ih.exports=Zx?Au.getPrototypeOf:function(a){var e=Xx(a);if(Yx(e,Th))return e[Th];var t=e.constructor;return Kx(t)&&e instanceof t?t.prototype:e instanceof Au?ew:null}});var xh=m((jV,Eh)=>{"use strict";var tw=Math.ceil,iw=Math.floor;Eh.exports=Math.trunc||function(e){var t=+e;return(t>0?iw:tw)(t)}});var Yr=m((QV,wh)=>{"use strict";var rw=xh();wh.exports=function(a){var e=+a;return e!==e||e===0?0:rw(e)}});var Ph=m((WV,Ah)=>{"use strict";var aw=Yr(),sw=Math.max,nw=Math.min;Ah.exports=function(a,e){var t=aw(a);return t<0?sw(t+e,0):nw(t,e)}});var Pu=m((GV,kh)=>{"use strict";var ow=Yr(),uw=Math.min;kh.exports=function(a){var e=ow(a);return e>0?uw(e,9007199254740991):0}});var Qi=m((zV,Rh)=>{"use strict";var lw=Pu();Rh.exports=function(a){return lw(a.length)}});var ku=m((YV,$h)=>{"use strict";var cw=ni(),dw=Ph(),pw=Qi(),Lh=function(a){return function(e,t,i){var r=cw(e),s=pw(r);if(s===0)return!a&&-1;var n=dw(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}};$h.exports={includes:Lh(!0),indexOf:Lh(!1)}});var Hs=m((KV,Mh)=>{"use strict";Mh.exports={}});var Bh=m((XV,Ch)=>{"use strict";var hw=de(),Ru=it(),fw=ni(),mw=ku().indexOf,bw=Hs(),Dh=hw([].push);Ch.exports=function(a,e){var t=fw(a),i=0,r=[],s;for(s in t)!Ru(bw,s)&&Ru(t,s)&&Dh(r,s);for(;e.length>i;)Ru(t,s=e[i++])&&(~mw(r,s)||Dh(r,s));return r}});var Lu=m((JV,Vh)=>{"use strict";Vh.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var $u=m((ZV,_h)=>{"use strict";var gw=Bh(),Sw=Lu();_h.exports=Object.keys||function(e){return gw(e,Sw)}});var Mu=m((e_,Uh)=>{"use strict";var Fh=Fe(),vw=ce(),Nh=de(),yw=Us(),Tw=$u(),Iw=ni(),Ew=iu().f,qh=Nh(Ew),xw=Nh([].push),ww=Fh&&vw(function(){var a=Object.create(null);return a[2]=2,!qh(a,2)}),Oh=function(a){return function(e){for(var t=Iw(e),i=Tw(t),r=ww&&yw(t)===null,s=i.length,n=0,u=[],o;s>n;)o=i[n++],(!Fh||(r?o in t:qh(t,o)))&&xw(u,a?[o,t[o]]:t[o]);return u}};Uh.exports={entries:Oh(!0),values:Oh(!1)}});var Hh=m(()=>{"use strict";var Aw=oe(),Pw=Mu().values;Aw({target:"Object",stat:!0},{values:function(e){return Pw(e)}})});var Qh=m((r_,jh)=>{"use strict";Hh();var kw=oi();jh.exports=kw.Object.values});var Gh=m((a_,Wh)=>{"use strict";var Rw=Qh();Wh.exports=Rw});var ci=m((s_,zh)=>{"use strict";var Lw=Gh();zh.exports=Lw});var Kr=m((n_,Yh)=>{"use strict";Yh.exports=function(){}});var Kh=m(()=>{"use strict";var $w=oe(),Mw=ku().includes,Dw=ce(),Cw=Kr(),Bw=Dw(function(){return!Array(1).includes()});$w({target:"Array",proto:!0,forced:Bw},{includes:function(e){return Mw(this,e,arguments.length>1?arguments[1]:void 0)}});Cw("includes")});var Nt=m((l_,Xh)=>{"use strict";var Vw=wt();Xh.exports=Vw});var Zh=m((c_,Jh)=>{"use strict";Kh();var _w=Nt();Jh.exports=_w("Array","includes")});var tf=m((d_,ef)=>{"use strict";var Ow=Zh();ef.exports=Ow});var Ee=m((p_,rf)=>{"use strict";var Fw=tf();rf.exports=Fw});var cf=m(()=>{"use strict";var Gw=oe(),zw=Mu().entries;Gw({target:"Object",stat:!0},{entries:function(e){return zw(e)}})});var pf=m((A_,df)=>{"use strict";cf();var Yw=oi();df.exports=Yw.Object.entries});var ff=m((P_,hf)=>{"use strict";var Kw=pf();hf.exports=Kw});var Wi=m((k_,mf)=>{"use strict";var Xw=ff();mf.exports=Xw});var di=m((R_,bf)=>{"use strict";bf.exports={}});var vf=m((L_,Sf)=>{"use strict";var Jw=re(),Zw=ae(),gf=Jw.WeakMap;Sf.exports=Zw(gf)&&/native code/.test(String(gf))});var Ou=m(($_,If)=>{"use strict";var eA=vf(),Tf=re(),tA=Le(),iA=Ui(),Bu=it(),Vu=Wr(),rA=qs(),aA=Hs(),yf="Object already initialized",_u=Tf.TypeError,sA=Tf.WeakMap,Ws,Xr,Gs,nA=function(a){return Gs(a)?Xr(a):Ws(a,{})},oA=function(a){return function(e){var t;if(!tA(e)||(t=Xr(e)).type!==a)throw new _u("Incompatible receiver, "+a+" required");return t}};eA||Vu.state?(rt=Vu.state||(Vu.state=new sA),rt.get=rt.get,rt.has=rt.has,rt.set=rt.set,Ws=function(a,e){if(rt.has(a))throw new _u(yf);return e.facade=a,rt.set(a,e),e},Xr=function(a){return rt.get(a)||{}},Gs=function(a){return rt.has(a)}):(pi=rA("state"),aA[pi]=!0,Ws=function(a,e){if(Bu(a,pi))throw new _u(yf);return e.facade=a,iA(a,pi,e),e},Xr=function(a){return Bu(a,pi)?a[pi]:{}},Gs=function(a){return Bu(a,pi)});var rt,pi;If.exports={set:Ws,get:Xr,has:Gs,enforce:nA,getterFor:oA}});var qu=m((M_,xf)=>{"use strict";var Fu=Fe(),uA=it(),Ef=Function.prototype,lA=Fu&&Object.getOwnPropertyDescriptor,Nu=uA(Ef,"name"),cA=Nu&&function(){}.name==="something",dA=Nu&&(!Fu||Fu&&lA(Ef,"name").configurable);xf.exports={EXISTS:Nu,PROPER:cA,CONFIGURABLE:dA}});var Af=m(wf=>{"use strict";var pA=Fe(),hA=Tu(),fA=li(),mA=ft(),bA=ni(),gA=$u();wf.f=pA&&!hA?Object.defineProperties:function(e,t){mA(e);for(var i=bA(t),r=gA(t),s=r.length,n=0,u;s>n;)fA.f(e,u=r[n++],i[u]);return e}});var Uu=m((C_,Pf)=>{"use strict";var SA=wt();Pf.exports=SA("document","documentElement")});var Wu=m((B_,Cf)=>{"use strict";var vA=ft(),yA=Af(),kf=Lu(),TA=Hs(),IA=Uu(),EA=Fs(),xA=qs(),Rf=">",Lf="<",ju="prototype",Qu="script",Mf=xA("IE_PROTO"),Hu=function(){},Df=function(a){return Lf+Qu+Rf+a+Lf+"/"+Qu+Rf},$f=function(a){a.write(Df("")),a.close();var e=a.parentWindow.Object;return a=null,e},wA=function(){var a=EA("iframe"),e="java"+Qu+":",t;return a.style.display="none",IA.appendChild(a),a.src=String(e),t=a.contentWindow.document,t.open(),t.write(Df("document.F=Object")),t.close(),t.F},zs,Ys=function(){try{zs=new ActiveXObject("htmlfile")}catch{}Ys=typeof document<"u"?document.domain&&zs?$f(zs):wA():$f(zs);for(var a=kf.length;a--;)delete Ys[ju][kf[a]];return Ys()};TA[Mf]=!0;Cf.exports=Object.create||function(e,t){var i;return e!==null?(Hu[ju]=vA(e),i=new Hu,Hu[ju]=null,i[Mf]=e):i=Ys(),t===void 0?i:yA.f(i,t)}});var Gi=m((V_,Bf)=>{"use strict";var AA=Ui();Bf.exports=function(a,e,t,i){return i&&i.enumerable?a[e]=t:AA(a,e,t),a}});var Ku=m((__,Of)=>{"use strict";var PA=ce(),kA=ae(),RA=Le(),LA=Wu(),Vf=Us(),$A=Gi(),MA=be(),DA=tt(),Yu=MA("iterator"),_f=!1,At,Gu,zu;[].keys&&(zu=[].keys(),"next"in zu?(Gu=Vf(Vf(zu)),Gu!==Object.prototype&&(At=Gu)):_f=!0);var CA=!RA(At)||PA(function(){var a={};return At[Yu].call(a)!==a});CA?At={}:DA&&(At=LA(At));kA(At[Yu])||$A(At,Yu,function(){return this});Of.exports={IteratorPrototype:At,BUGGY_SAFARI_ITERATORS:_f}});var Ks=m((O_,Nf)=>{"use strict";var BA=be(),VA=BA("toStringTag"),Ff={};Ff[VA]="z";Nf.exports=String(Ff)==="[object z]"});var Jr=m((F_,qf)=>{"use strict";var _A=Ks(),OA=ae(),Xs=si(),FA=be(),NA=FA("toStringTag"),qA=Object,UA=Xs(function(){return arguments}())==="Arguments",HA=function(a,e){try{return a[e]}catch{}};qf.exports=_A?Xs:function(a){var e,t,i;return a===void 0?"Undefined":a===null?"Null":typeof(t=HA(e=qA(a),NA))=="string"?t:UA?Xs(e):(i=Xs(e))==="Object"&&OA(e.callee)?"Arguments":i}});var Hf=m((N_,Uf)=>{"use strict";var jA=Ks(),QA=Jr();Uf.exports=jA?{}.toString:function(){return"[object "+QA(this)+"]"}});var Zr=m((q_,Qf)=>{"use strict";var WA=Ks(),GA=li().f,zA=Ui(),YA=it(),KA=Hf(),XA=be(),jf=XA("toStringTag");Qf.exports=function(a,e,t,i){var r=t?a:a&&a.prototype;r&&(YA(r,jf)||GA(r,jf,{configurable:!0,value:e}),i&&!WA&&zA(r,"toString",KA))}});var Gf=m((U_,Wf)=>{"use strict";var JA=Ku().IteratorPrototype,ZA=Wu(),eP=qr(),tP=Zr(),iP=di(),rP=function(){return this};Wf.exports=function(a,e,t,i){var r=e+" Iterator";return a.prototype=ZA(JA,{next:eP(+!i,t)}),tP(a,r,!1,!0),iP[r]=rP,a}});var Yf=m((H_,zf)=>{"use strict";var aP=de(),sP=ht();zf.exports=function(a,e,t){try{return aP(sP(Object.getOwnPropertyDescriptor(a,e)[t]))}catch{}}});var Xf=m((j_,Kf)=>{"use strict";var nP=Le();Kf.exports=function(a){return nP(a)||a===null}});var Zf=m((Q_,Jf)=>{"use strict";var oP=Xf(),uP=String,lP=TypeError;Jf.exports=function(a){if(oP(a))return a;throw new lP("Can't set "+uP(a)+" as a prototype")}});var Xu=m((W_,em)=>{"use strict";var cP=Yf(),dP=Le(),pP=Ft(),hP=Zf();em.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var a=!1,e={},t;try{t=cP(Object.prototype,"__proto__","set"),t(e,[]),a=e instanceof Array}catch{}return function(r,s){return pP(r),hP(s),dP(r)&&(a?t(r,s):r.__proto__=s),r}}():void 0)});var dm=m((G_,cm)=>{"use strict";var fP=oe(),mP=Ne(),Js=tt(),um=qu(),bP=ae(),gP=Gf(),tm=Us(),im=Xu(),SP=Zr(),vP=Ui(),Ju=Gi(),yP=be(),rm=di(),lm=Ku(),TP=um.PROPER,IP=um.CONFIGURABLE,am=lm.IteratorPrototype,Zs=lm.BUGGY_SAFARI_ITERATORS,ea=yP("iterator"),sm="keys",ta="values",nm="entries",om=function(){return this};cm.exports=function(a,e,t,i,r,s,n){gP(t,e,i);var u=function(g){if(g===r&&d)return d;if(!Zs&&g&&g in c)return c[g];switch(g){case sm:return function(){return new t(this,g)};case ta:return function(){return new t(this,g)};case nm:return function(){return new t(this,g)}}return function(){return new t(this)}},o=e+" Iterator",l=!1,c=a.prototype,p=c[ea]||c["@@iterator"]||r&&c[r],d=!Zs&&p||u(r),h=e==="Array"&&c.entries||p,f,b,S;if(h&&(f=tm(h.call(new a)),f!==Object.prototype&&f.next&&(!Js&&tm(f)!==am&&(im?im(f,am):bP(f[ea])||Ju(f,ea,om)),SP(f,o,!0,!0),Js&&(rm[o]=om))),TP&&r===ta&&p&&p.name!==ta&&(!Js&&IP?vP(c,"name",ta):(l=!0,d=function(){return mP(p,this)})),r)if(b={values:u(ta),keys:s?d:u(sm),entries:u(nm)},n)for(S in b)(Zs||l||!(S in c))&&Ju(c,S,b[S]);else fP({target:e,proto:!0,forced:Zs||l},b);return(!Js||n)&&c[ea]!==d&&Ju(c,ea,d,{name:r}),rm[e]=d,b}});var hm=m((z_,pm)=>{"use strict";pm.exports=function(a,e){return{value:a,done:e}}});var el=m((Y_,Sm)=>{"use strict";var EP=ni(),Zu=Kr(),fm=di(),bm=Ou(),xP=li().f,wP=dm(),en=hm(),AP=tt(),PP=Fe(),gm="Array Iterator",kP=bm.set,RP=bm.getterFor(gm);Sm.exports=wP(Array,"Array",function(a,e){kP(this,{type:gm,target:EP(a),index:0,kind:e})},function(){var a=RP(this),e=a.target,t=a.index++;if(!e||t>=e.length)return a.target=null,en(void 0,!0);switch(a.kind){case"keys":return en(t,!1);case"values":return en(e[t],!1)}return en([t,e[t]],!1)},"values");var mm=fm.Arguments=fm.Array;Zu("keys");Zu("values");Zu("entries");if(!AP&&PP&&mm.name!=="values")try{xP(mm,"name",{value:"values"})}catch{}});var ym=m((K_,vm)=>{"use strict";var LP=be(),$P=di(),MP=LP("iterator"),DP=Array.prototype;vm.exports=function(a){return a!==void 0&&($P.Array===a||DP[MP]===a)}});var tl=m((X_,Im)=>{"use strict";var CP=Jr(),Tm=Qr(),BP=Ur(),VP=di(),_P=be(),OP=_P("iterator");Im.exports=function(a){if(!BP(a))return Tm(a,OP)||Tm(a,"@@iterator")||VP[CP(a)]}});var xm=m((J_,Em)=>{"use strict";var FP=Ne(),NP=ht(),qP=ft(),UP=jr(),HP=tl(),jP=TypeError;Em.exports=function(a,e){var t=arguments.length<2?HP(a):e;if(NP(t))return qP(FP(t,a));throw new jP(UP(a)+" is not iterable")}});var Pm=m((Z_,Am)=>{"use strict";var QP=Ne(),wm=ft(),WP=Qr();Am.exports=function(a,e,t){var i,r;wm(a);try{if(i=WP(a,"return"),!i){if(e==="throw")throw t;return t}i=QP(i,a)}catch(s){r=!0,i=s}if(e==="throw")throw t;if(r)throw i;return wm(i),t}});var rn=m((eO,$m)=>{"use strict";var GP=qi(),zP=Ne(),YP=ft(),KP=jr(),XP=ym(),JP=Qi(),km=Hr(),ZP=xm(),ek=tl(),Rm=Pm(),tk=TypeError,tn=function(a,e){this.stopped=a,this.result=e},Lm=tn.prototype;$m.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=GP(e,i),l,c,p,d,h,f,b,S=function(I){return l&&Rm(l,"normal"),new tn(!0,I)},g=function(I){return r?(YP(I),u?o(I[0],I[1],S):o(I[0],I[1])):u?o(I,S):o(I)};if(s)l=a.iterator;else if(n)l=a;else{if(c=ek(a),!c)throw new tk(KP(a)+" is not iterable");if(XP(c)){for(p=0,d=JP(a);d>p;p++)if(h=g(a[p]),h&&km(Lm,h))return h;return new tn(!1)}l=ZP(a,c)}for(f=s?a.next:l.next;!(b=zP(f,l)).done;){try{h=g(b.value)}catch(I){Rm(l,"throw",I)}if(typeof h=="object"&&h&&km(Lm,h))return h}return new tn(!1)}});var Dm=m((tO,Mm)=>{"use strict";var ik=Fe(),rk=li(),ak=qr();Mm.exports=function(a,e,t){ik?rk.f(a,e,ak(0,t)):a[e]=t}});var Cm=m(()=>{"use strict";var sk=oe(),nk=rn(),ok=Dm();sk({target:"Object",stat:!0},{fromEntries:function(e){var t={};return nk(e,function(i,r){ok(t,i,r)},{AS_ENTRIES:!0}),t}})});var Vm=m((aO,Bm)=>{"use strict";el();Cm();var uk=oi();Bm.exports=uk.Object.fromEntries});var Om=m((sO,_m)=>{"use strict";_m.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 Nm=m(()=>{"use strict";el();var lk=Om(),ck=re(),dk=Zr(),Fm=di();for(an in lk)dk(ck[an],an),Fm[an]=Fm.Array;var an});var Um=m((uO,qm)=>{"use strict";var pk=Vm();Nm();qm.exports=pk});var il=m((lO,Hm)=>{"use strict";var hk=Um();Hm.exports=hk});var jm=m(()=>{"use strict"});var rl=m((pO,Qm)=>{"use strict";var ia=re(),fk=ui(),mk=si(),sn=function(a){return fk.slice(0,a.length)===a};Qm.exports=function(){return sn("Bun/")?"BUN":sn("Cloudflare-Workers")?"CLOUDFLARE":sn("Deno/")?"DENO":sn("Node.js/")?"NODE":ia.Bun&&typeof Bun.version=="string"?"BUN":ia.Deno&&typeof Deno.version=="object"?"DENO":mk(ia.process)==="process"?"NODE":ia.window&&ia.document?"BROWSER":"REST"}()});var nn=m((hO,Wm)=>{"use strict";var bk=rl();Wm.exports=bk==="NODE"});var zm=m((fO,Gm)=>{"use strict";var gk=li();Gm.exports=function(a,e,t){return gk.f(a,e,t)}});var Xm=m((mO,Km)=>{"use strict";var Sk=wt(),vk=zm(),yk=be(),Tk=Fe(),Ym=yk("species");Km.exports=function(a){var e=Sk(a);Tk&&e&&!e[Ym]&&vk(e,Ym,{configurable:!0,get:function(){return this}})}});var Zm=m((bO,Jm)=>{"use strict";var Ik=Hr(),Ek=TypeError;Jm.exports=function(a,e){if(Ik(e,a))return a;throw new Ek("Incorrect invocation")}});var sl=m((gO,eb)=>{"use strict";var xk=de(),wk=ae(),al=Wr(),Ak=xk(Function.toString);wk(al.inspectSource)||(al.inspectSource=function(a){return Ak(a)});eb.exports=al.inspectSource});var ol=m((SO,sb)=>{"use strict";var Pk=de(),kk=ce(),tb=ae(),Rk=Jr(),Lk=wt(),$k=sl(),ib=function(){},rb=Lk("Reflect","construct"),nl=/^\s*(?:class|function)\b/,Mk=Pk(nl.exec),Dk=!nl.test(ib),ra=function(e){if(!tb(e))return!1;try{return rb(ib,[],e),!0}catch{return!1}},ab=function(e){if(!tb(e))return!1;switch(Rk(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return Dk||!!Mk(nl,$k(e))}catch{return!0}};ab.sham=!0;sb.exports=!rb||kk(function(){var a;return ra(ra.call)||!ra(Object)||!ra(function(){a=!0})||a})?ab:ra});var ob=m((vO,nb)=>{"use strict";var Ck=ol(),Bk=jr(),Vk=TypeError;nb.exports=function(a){if(Ck(a))return a;throw new Vk(Bk(a)+" is not a constructor")}});var ul=m((yO,lb)=>{"use strict";var ub=ft(),_k=ob(),Ok=Ur(),Fk=be(),Nk=Fk("species");lb.exports=function(a,e){var t=ub(a).constructor,i;return t===void 0||Ok(i=ub(t)[Nk])?e:_k(i)}});var db=m((TO,cb)=>{"use strict";var qk=de();cb.exports=qk([].slice)});var hb=m((IO,pb)=>{"use strict";var Uk=TypeError;pb.exports=function(a,e){if(a<e)throw new Uk("Not enough arguments");return a}});var ll=m((EO,fb)=>{"use strict";var Hk=ui();fb.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(Hk)});var Sl=m((xO,Eb)=>{"use strict";var qe=re(),jk=Jo(),Qk=qi(),mb=ae(),Wk=it(),Ib=ce(),bb=Uu(),Gk=db(),gb=Fs(),zk=hb(),Yk=ll(),Kk=nn(),ml=qe.setImmediate,bl=qe.clearImmediate,Xk=qe.process,cl=qe.Dispatch,Jk=qe.Function,Sb=qe.MessageChannel,Zk=qe.String,dl=0,aa={},vb="onreadystatechange",sa,hi,pl,hl;Ib(function(){sa=qe.location});var gl=function(a){if(Wk(aa,a)){var e=aa[a];delete aa[a],e()}},fl=function(a){return function(){gl(a)}},yb=function(a){gl(a.data)},Tb=function(a){qe.postMessage(Zk(a),sa.protocol+"//"+sa.host)};(!ml||!bl)&&(ml=function(e){zk(arguments.length,1);var t=mb(e)?e:Jk(e),i=Gk(arguments,1);return aa[++dl]=function(){jk(t,void 0,i)},hi(dl),dl},bl=function(e){delete aa[e]},Kk?hi=function(a){Xk.nextTick(fl(a))}:cl&&cl.now?hi=function(a){cl.now(fl(a))}:Sb&&!Yk?(pl=new Sb,hl=pl.port2,pl.port1.onmessage=yb,hi=Qk(hl.postMessage,hl)):qe.addEventListener&&mb(qe.postMessage)&&!qe.importScripts&&sa&&sa.protocol!=="file:"&&!Ib(Tb)?(hi=Tb,qe.addEventListener("message",yb,!1)):vb in gb("script")?hi=function(a){bb.appendChild(gb("script"))[vb]=function(){bb.removeChild(this),gl(a)}}:hi=function(a){setTimeout(fl(a),0)});Eb.exports={set:ml,clear:bl}});var Ab=m((wO,wb)=>{"use strict";var xb=re(),eR=Fe(),tR=Object.getOwnPropertyDescriptor;wb.exports=function(a){if(!eR)return xb[a];var e=tR(xb,a);return e&&e.value}});var vl=m((AO,kb)=>{"use strict";var Pb=function(){this.head=null,this.tail=null};Pb.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}}};kb.exports=Pb});var Lb=m((PO,Rb)=>{"use strict";var iR=ui();Rb.exports=/ipad|iphone|ipod/i.test(iR)&&typeof Pebble<"u"});var Mb=m((kO,$b)=>{"use strict";var rR=ui();$b.exports=/web0s(?!.*chrome)/i.test(rR)});var Fb=m((RO,Ob)=>{"use strict";var Yi=re(),aR=Ab(),Db=qi(),yl=Sl().set,sR=vl(),nR=ll(),oR=Lb(),uR=Mb(),Tl=nn(),Cb=Yi.MutationObserver||Yi.WebKitMutationObserver,Bb=Yi.document,Vb=Yi.process,on=Yi.Promise,xl=aR("queueMicrotask"),zi,Il,El,un,_b;xl||(na=new sR,oa=function(){var a,e;for(Tl&&(a=Vb.domain)&&a.exit();e=na.get();)try{e()}catch(t){throw na.head&&zi(),t}a&&a.enter()},!nR&&!Tl&&!uR&&Cb&&Bb?(Il=!0,El=Bb.createTextNode(""),new Cb(oa).observe(El,{characterData:!0}),zi=function(){El.data=Il=!Il}):!oR&&on&&on.resolve?(un=on.resolve(void 0),un.constructor=on,_b=Db(un.then,un),zi=function(){_b(oa)}):Tl?zi=function(){Vb.nextTick(oa)}:(yl=Db(yl,Yi),zi=function(){yl(oa)}),xl=function(a){na.head||zi(),na.add(a)});var na,oa;Ob.exports=xl});var qb=m((LO,Nb)=>{"use strict";Nb.exports=function(a,e){try{arguments.length===1?console.error(a):console.error(a,e)}catch{}}});var ln=m(($O,Ub)=>{"use strict";Ub.exports=function(a){try{return{error:!1,value:a()}}catch(e){return{error:!0,value:e}}}});var fi=m((MO,Hb)=>{"use strict";var lR=re();Hb.exports=lR.Promise});var Ki=m((DO,Gb)=>{"use strict";var cR=re(),ua=fi(),dR=ae(),pR=yu(),hR=sl(),fR=be(),jb=rl(),mR=tt(),wl=ou(),Qb=ua&&ua.prototype,bR=fR("species"),Al=!1,Wb=dR(cR.PromiseRejectionEvent),gR=pR("Promise",function(){var a=hR(ua),e=a!==String(ua);if(!e&&wl===66||mR&&!(Qb.catch&&Qb.finally))return!0;if(!wl||wl<51||!/native code/.test(a)){var t=new ua(function(s){s(1)}),i=function(s){s(function(){},function(){})},r=t.constructor={};if(r[bR]=i,Al=t.then(function(){})instanceof i,!Al)return!0}return!e&&(jb==="BROWSER"||jb==="DENO")&&!Wb});Gb.exports={CONSTRUCTOR:gR,REJECTION_EVENT:Wb,SUBCLASSING:Al}});var Xi=m((CO,Yb)=>{"use strict";var zb=ht(),SR=TypeError,vR=function(a){var e,t;this.promise=new a(function(i,r){if(e!==void 0||t!==void 0)throw new SR("Bad Promise constructor");e=i,t=r}),this.resolve=zb(e),this.reject=zb(t)};Yb.exports.f=function(a){return new vR(a)}});var mg=m(()=>{"use strict";var yR=oe(),TR=tt(),hn=nn(),qt=re(),IR=oi(),tr=Ne(),Kb=Gi(),Xb=Xu(),ER=Zr(),xR=Xm(),wR=ht(),pn=ae(),AR=Le(),PR=Zm(),kR=ul(),ig=Sl().set,$l=Fb(),RR=qb(),LR=ln(),$R=vl(),rg=Ou(),fn=fi(),Ml=Ki(),ag=Xi(),mn="Promise",sg=Ml.CONSTRUCTOR,MR=Ml.REJECTION_EVENT,DR=Ml.SUBCLASSING,Pl=rg.getterFor(mn),CR=rg.set,Ji=fn&&fn.prototype,mi=fn,cn=Ji,ng=qt.TypeError,kl=qt.document,Dl=qt.process,Rl=ag.f,BR=Rl,VR=!!(kl&&kl.createEvent&&qt.dispatchEvent),og="unhandledrejection",_R="rejectionhandled",Jb=0,ug=1,OR=2,Cl=1,lg=2,dn,Zb,cg,eg,dg=function(a){var e;return AR(a)&&pn(e=a.then)?e:!1},pg=function(a,e){var t=e.value,i=e.state===ug,r=i?a.ok:a.fail,s=a.resolve,n=a.reject,u=a.domain,o,l,c;try{r?(i||(e.rejection===lg&&NR(e),e.rejection=Cl),r===!0?o=t:(u&&u.enter(),o=r(t),u&&(u.exit(),c=!0)),o===a.promise?n(new ng("Promise-chain cycle")):(l=dg(o))?tr(l,o,s,n):s(o)):n(t)}catch(p){u&&!c&&u.exit(),n(p)}},hg=function(a,e){a.notified||(a.notified=!0,$l(function(){for(var t=a.reactions,i;i=t.get();)pg(i,a);a.notified=!1,e&&!a.rejection&&FR(a)}))},fg=function(a,e,t){var i,r;VR?(i=kl.createEvent("Event"),i.promise=e,i.reason=t,i.initEvent(a,!1,!0),qt.dispatchEvent(i)):i={promise:e,reason:t},!MR&&(r=qt["on"+a])?r(i):a===og&&RR("Unhandled promise rejection",t)},FR=function(a){tr(ig,qt,function(){var e=a.facade,t=a.value,i=tg(a),r;if(i&&(r=LR(function(){hn?Dl.emit("unhandledRejection",t,e):fg(og,e,t)}),a.rejection=hn||tg(a)?lg:Cl,r.error))throw r.value})},tg=function(a){return a.rejection!==Cl&&!a.parent},NR=function(a){tr(ig,qt,function(){var e=a.facade;hn?Dl.emit("rejectionHandled",e):fg(_R,e,a.value)})},Zi=function(a,e,t){return function(i){a(e,i,t)}},er=function(a,e,t){a.done||(a.done=!0,t&&(a=t),a.value=e,a.state=OR,hg(a,!0))},Ll=function(a,e,t){if(!a.done){a.done=!0,t&&(a=t);try{if(a.facade===e)throw new ng("Promise can't be resolved itself");var i=dg(e);i?$l(function(){var r={done:!1};try{tr(i,e,Zi(Ll,r,a),Zi(er,r,a))}catch(s){er(r,s,a)}}):(a.value=e,a.state=ug,hg(a,!1))}catch(r){er({done:!1},r,a)}}};if(sg&&(mi=function(e){PR(this,cn),wR(e),tr(dn,this);var t=Pl(this);try{e(Zi(Ll,t),Zi(er,t))}catch(i){er(t,i)}},cn=mi.prototype,dn=function(e){CR(this,{type:mn,done:!1,notified:!1,parent:!1,reactions:new $R,rejection:!1,state:Jb,value:null})},dn.prototype=Kb(cn,"then",function(e,t){var i=Pl(this),r=Rl(kR(this,mi));return i.parent=!0,r.ok=pn(e)?e:!0,r.fail=pn(t)&&t,r.domain=hn?Dl.domain:void 0,i.state===Jb?i.reactions.add(r):$l(function(){pg(r,i)}),r.promise}),Zb=function(){var a=new dn,e=Pl(a);this.promise=a,this.resolve=Zi(Ll,e),this.reject=Zi(er,e)},ag.f=Rl=function(a){return a===mi||a===cg?new Zb(a):BR(a)},!TR&&pn(fn)&&Ji!==Object.prototype)){eg=Ji.then,DR||Kb(Ji,"then",function(e,t){var i=this;return new mi(function(r,s){tr(eg,i,r,s)}).then(e,t)},{unsafe:!0});try{delete Ji.constructor}catch{}Xb&&Xb(Ji,cn)}yR({global:!0,constructor:!0,wrap:!0,forced:sg},{Promise:mi});cg=IR.Promise;ER(mi,mn,!1,!0);xR(mn)});var yg=m((_O,vg)=>{"use strict";var qR=be(),gg=qR("iterator"),Sg=!1;try{bg=0,Bl={next:function(){return{done:!!bg++}},return:function(){Sg=!0}},Bl[gg]=function(){return this},Array.from(Bl,function(){throw 2})}catch{}var bg,Bl;vg.exports=function(a,e){try{if(!e&&!Sg)return!1}catch{return!1}var t=!1;try{var i={};i[gg]=function(){return{next:function(){return{done:t=!0}}}},a(i)}catch{}return t}});var Vl=m((OO,Tg)=>{"use strict";var UR=fi(),HR=yg(),jR=Ki().CONSTRUCTOR;Tg.exports=jR||!HR(function(a){UR.all(a).then(void 0,function(){})})});var Ig=m(()=>{"use strict";var QR=oe(),WR=Ne(),GR=ht(),zR=Xi(),YR=ln(),KR=rn(),XR=Vl();QR({target:"Promise",stat:!0,forced:XR},{all:function(e){var t=this,i=zR.f(t),r=i.resolve,s=i.reject,n=YR(function(){var u=GR(t.resolve),o=[],l=0,c=1;KR(e,function(p){var d=l++,h=!1;c++,WR(u,t,p).then(function(f){h||(h=!0,o[d]=f,--c||r(o))},s)}),--c||r(o)});return n.error&&s(n.value),i.promise}})});var xg=m(()=>{"use strict";var JR=oe(),ZR=tt(),eL=Ki().CONSTRUCTOR,Ol=fi(),tL=wt(),iL=ae(),rL=Gi(),Eg=Ol&&Ol.prototype;JR({target:"Promise",proto:!0,forced:eL,real:!0},{catch:function(a){return this.then(void 0,a)}});!ZR&&iL(Ol)&&(_l=tL("Promise").prototype.catch,Eg.catch!==_l&&rL(Eg,"catch",_l,{unsafe:!0}));var _l});var wg=m(()=>{"use strict";var aL=oe(),sL=Ne(),nL=ht(),oL=Xi(),uL=ln(),lL=rn(),cL=Vl();aL({target:"Promise",stat:!0,forced:cL},{race:function(e){var t=this,i=oL.f(t),r=i.reject,s=uL(function(){var n=nL(t.resolve);lL(e,function(u){sL(n,t,u).then(i.resolve,r)})});return s.error&&r(s.value),i.promise}})});var Ag=m(()=>{"use strict";var dL=oe(),pL=Xi(),hL=Ki().CONSTRUCTOR;dL({target:"Promise",stat:!0,forced:hL},{reject:function(e){var t=pL.f(this),i=t.reject;return i(e),t.promise}})});var Fl=m((GO,Pg)=>{"use strict";var fL=ft(),mL=Le(),bL=Xi();Pg.exports=function(a,e){if(fL(a),mL(e)&&e.constructor===a)return e;var t=bL.f(a),i=t.resolve;return i(e),t.promise}});var Lg=m(()=>{"use strict";var gL=oe(),SL=wt(),kg=tt(),vL=fi(),Rg=Ki().CONSTRUCTOR,yL=Fl(),TL=SL("Promise"),IL=kg&&!Rg;gL({target:"Promise",stat:!0,forced:kg||Rg},{resolve:function(e){return yL(IL&&this===TL?vL:this,e)}})});var $g=m(()=>{"use strict";mg();Ig();xg();wg();Ag();Lg()});var Bg=m(()=>{"use strict";var EL=oe(),xL=tt(),bn=fi(),wL=ce(),Dg=wt(),Cg=ae(),AL=ul(),Mg=Fl(),PL=Gi(),ql=bn&&bn.prototype,kL=!!bn&&wL(function(){ql.finally.call({then:function(){}},function(){})});EL({target:"Promise",proto:!0,real:!0,forced:kL},{finally:function(a){var e=AL(this,Dg("Promise")),t=Cg(a);return this.then(t?function(i){return Mg(e,a()).then(function(){return i})}:a,t?function(i){return Mg(e,a()).then(function(){throw i})}:a)}});!xL&&Cg(bn)&&(Nl=Dg("Promise").prototype.finally,ql.finally!==Nl&&PL(ql,"finally",Nl,{unsafe:!0}));var Nl});var _g=m((eF,Vg)=>{"use strict";jm();$g();Bg();var RL=Nt();Vg.exports=RL("Promise","finally")});var Fg=m((tF,Og)=>{"use strict";var LL=_g();Og.exports=LL});var gn=m((iF,Ng)=>{"use strict";var $L=Fg();Ng.exports=$L});var mS=m(()=>{"use strict";var h$=oe(),f$=Fi(),m$=Qi(),b$=Yr(),g$=Kr();h$({target:"Array",proto:!0},{at:function(e){var t=f$(this),i=m$(t),r=b$(e),s=r>=0?r:i+r;return s<0||s>=i?void 0:t[s]}});g$("at")});var gS=m((GN,bS)=>{"use strict";mS();var S$=Nt();bS.exports=S$("Array","at")});var vS=m((zN,SS)=>{"use strict";var v$=gS();SS.exports=v$});var at=m((YN,yS)=>{"use strict";var y$=vS();yS.exports=y$});var pc=m((NU,tv)=>{"use strict";var eM=si();tv.exports=Array.isArray||function(e){return eM(e)==="Array"}});var rv=m((qU,iv)=>{"use strict";var tM=TypeError,iM=9007199254740991;iv.exports=function(a){if(a>iM)throw tM("Maximum allowed index exceeded");return a}});var nv=m((UU,sv)=>{"use strict";var rM=pc(),aM=Qi(),sM=rv(),nM=qi(),av=function(a,e,t,i,r,s,n,u){for(var o=r,l=0,c=n?nM(n,u):!1,p,d;l<i;)l in t&&(p=c?c(t[l],l,e):t[l],s>0&&rM(p)?(d=aM(p),o=av(a,e,p,d,o,s-1)-1):(sM(o+1),a[o]=p),o++),l++;return o};sv.exports=av});var cv=m((HU,lv)=>{"use strict";var ov=pc(),oM=ol(),uM=Le(),lM=be(),cM=lM("species"),uv=Array;lv.exports=function(a){var e;return ov(a)&&(e=a.constructor,oM(e)&&(e===uv||ov(e.prototype))?e=void 0:uM(e)&&(e=e[cM],e===null&&(e=void 0))),e===void 0?uv:e}});var pv=m((jU,dv)=>{"use strict";var dM=cv();dv.exports=function(a,e){return new(dM(a))(e===0?0:e)}});var hv=m(()=>{"use strict";var pM=oe(),hM=nv(),fM=ht(),mM=Fi(),bM=Qi(),gM=pv();pM({target:"Array",proto:!0},{flatMap:function(e){var t=mM(this),i=bM(t),r;return fM(e),r=gM(t,0),r.length=hM(r,t,t,i,0,1,e,arguments.length>1?arguments[1]:void 0),r}})});var fv=m(()=>{"use strict";var SM=Kr();SM("flatMap")});var bv=m((YU,mv)=>{"use strict";hv();fv();var vM=Nt();mv.exports=vM("Array","flatMap")});var Sv=m((KU,gv)=>{"use strict";var yM=bv();gv.exports=yM});var xa=m((XU,vv)=>{"use strict";var TM=Sv();vv.exports=TM});var wa=m((JU,yv)=>{"use strict";var IM=Jr(),EM=String;yv.exports=function(a){if(IM(a)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return EM(a)}});var hc=m((ZU,Tv)=>{"use strict";Tv.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 xv=m((e1,Ev)=>{"use strict";var xM=de(),wM=Ft(),AM=wa(),mc=hc(),Iv=xM("".replace),PM=RegExp("^["+mc+"]+"),kM=RegExp("(^|[^"+mc+"])["+mc+"]+$"),fc=function(a){return function(e){var t=AM(wM(e));return a&1&&(t=Iv(t,PM,"")),a&2&&(t=Iv(t,kM,"$1")),t}};Ev.exports={start:fc(1),end:fc(2),trim:fc(3)}});var kv=m((t1,Pv)=>{"use strict";var RM=qu().PROPER,LM=ce(),wv=hc(),Av="\u200B\x85\u180E";Pv.exports=function(a){return LM(function(){return!!wv[a]()||Av[a]()!==Av||RM&&wv[a].name!==a})}});var bc=m((i1,Rv)=>{"use strict";var $M=xv().start,MM=kv();Rv.exports=MM("trimStart")?function(){return $M(this)}:"".trimStart});var $v=m(()=>{"use strict";var DM=oe(),Lv=bc();DM({target:"String",proto:!0,name:"trimStart",forced:"".trimLeft!==Lv},{trimLeft:Lv})});var Dv=m(()=>{"use strict";$v();var CM=oe(),Mv=bc();CM({target:"String",proto:!0,name:"trimStart",forced:"".trimStart!==Mv},{trimStart:Mv})});var Bv=m((o1,Cv)=>{"use strict";Dv();var BM=Nt();Cv.exports=BM("String","trimLeft")});var _v=m((u1,Vv)=>{"use strict";var VM=Bv();Vv.exports=VM});var Fv=m((l1,Ov)=>{"use strict";var _M=_v();Ov.exports=_M});var ty=m(()=>{"use strict"});var iy=m(()=>{"use strict"});var ay=m((Yj,ry)=>{"use strict";var oD=Le(),uD=si(),lD=be(),cD=lD("match");ry.exports=function(a){var e;return oD(a)&&((e=a[cD])!==void 0?!!e:uD(a)==="RegExp")}});var oy=m((Kj,ny)=>{"use strict";var dD=re(),pD=ce(),sy=dD.RegExp,hD=!pD(function(){var a=!0;try{sy(".","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(sy.prototype,"flags").get.call(e);return u!==i||t!==i});ny.exports={correct:hD}});var ly=m((Xj,uy)=>{"use strict";var fD=ft();uy.exports=function(){var a=fD(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 py=m((Jj,dy)=>{"use strict";var mD=Ne(),bD=it(),gD=Hr(),cy=oy(),SD=ly(),vD=RegExp.prototype;dy.exports=cy.correct?function(a){return a.flags}:function(a){return!cy.correct&&gD(vD,a)&&!bD(a,"flags")?mD(SD,a):a.flags}});var fy=m((Zj,hy)=>{"use strict";var Tc=de(),yD=Fi(),TD=Math.floor,vc=Tc("".charAt),ID=Tc("".replace),yc=Tc("".slice),ED=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,xD=/\$([$&'`]|\d{1,2})/g;hy.exports=function(a,e,t,i,r,s){var n=t+a.length,u=i.length,o=xD;return r!==void 0&&(r=yD(r),o=ED),ID(s,o,function(l,c){var p;switch(vc(c,0)){case"$":return"$";case"&":return a;case"`":return yc(e,0,t);case"'":return yc(e,n);case"<":p=r[yc(c,1,-1)];break;default:var d=+c;if(d===0)return l;if(d>u){var h=TD(d/10);return h===0?l:h<=u?i[h-1]===void 0?vc(c,1):i[h-1]+vc(c,1):l}p=i[d-1]}return p===void 0?"":p})}});var gy=m(()=>{"use strict";var wD=oe(),AD=Ne(),Ec=de(),my=Ft(),PD=ae(),kD=Le(),RD=ay(),mr=wa(),LD=Qr(),$D=py(),MD=fy(),DD=be(),CD=tt(),BD=DD("replace"),VD=TypeError,Ic=Ec("".indexOf),_D=Ec("".replace),by=Ec("".slice),OD=Math.max;wD({target:"String",proto:!0},{replaceAll:function(e,t){var i=my(this),r,s,n,u,o,l,c,p,d,h,f=0,b="";if(kD(e)){if(r=RD(e),r&&(s=mr(my($D(e))),!~Ic(s,"g")))throw new VD("`.replaceAll` does not allow non-global regexes");if(n=LD(e,BD),n)return AD(n,e,i,t);if(CD&&r)return _D(mr(i),e,t)}for(u=mr(i),o=mr(e),l=PD(t),l||(t=mr(t)),c=o.length,p=OD(1,c),d=Ic(u,o);d!==-1;)h=l?mr(t(o,d,u)):MD(o,u,d,[],void 0,t),b+=by(u,f,d)+h,f=d+c,d=d+p>u.length?-1:Ic(u,o,d+p);return f<u.length&&(b+=by(u,f)),b}})});var vy=m((iQ,Sy)=>{"use strict";ty();iy();gy();var FD=Nt();Sy.exports=FD("String","replaceAll")});var Ty=m((rQ,yy)=>{"use strict";var ND=vy();yy.exports=ND});var Ey=m((aQ,Iy)=>{"use strict";var qD=Ty();Iy.exports=qD});var wy=m((sQ,xy)=>{"use strict";var UD=Yr(),HD=wa(),jD=Ft(),QD=RangeError;xy.exports=function(e){var t=HD(jD(this)),i="",r=UD(e);if(r<0||r===1/0)throw new QD("Wrong number of repetitions");for(;r>0;(r>>>=1)&&(t+=t))r&1&&(i+=t);return i}});var Ly=m((nQ,Ry)=>{"use strict";var ky=de(),WD=Pu(),Ay=wa(),GD=wy(),zD=Ft(),YD=ky(GD),KD=ky("".slice),XD=Math.ceil,Py=function(a){return function(e,t,i){var r=Ay(zD(e)),s=WD(t),n=r.length,u=i===void 0?" ":Ay(i),o,l;return s<=n||u===""?r:(o=s-n,l=YD(u,XD(o/u.length)),l.length>o&&(l=KD(l,0,o)),a?r+l:l+r)}};Ry.exports={start:Py(!1),end:Py(!0)}});var My=m((oQ,$y)=>{"use strict";var JD=ui();$y.exports=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(JD)});var Dy=m(()=>{"use strict";var ZD=oe(),eC=Ly().start,tC=My();ZD({target:"String",proto:!0,forced:tC},{padStart:function(e){return eC(this,e,arguments.length>1?arguments[1]:void 0)}})});var By=m((cQ,Cy)=>{"use strict";Dy();var iC=Nt();Cy.exports=iC("String","padStart")});var _y=m((dQ,Vy)=>{"use strict";var rC=By();Vy.exports=rC});var Fy=m((pQ,Oy)=>{"use strict";var aC=_y();Oy.exports=aC});var qd="2.0.140-dev.4c27f703.0";var Re=(r=>(r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused",r))(Re||{}),xt=(y=>(y.MPEG="MPEG",y.DASH="DASH",y.DASH_SEP="DASH_SEP",y.DASH_SEP_VK="DASH_SEP",y.DASH_WEBM="DASH_WEBM",y.DASH_WEBM_AV1="DASH_WEBM_AV1",y.DASH_STREAMS="DASH_STREAMS",y.DASH_WEBM_VK="DASH_WEBM",y.DASH_ONDEMAND="DASH_ONDEMAND",y.DASH_ONDEMAND_VK="DASH_ONDEMAND",y.DASH_LIVE="DASH_LIVE",y.DASH_LIVE_CMAF="DASH_LIVE_CMAF",y.DASH_LIVE_WEBM="DASH_LIVE_WEBM",y.HLS="HLS",y.HLS_ONDEMAND="HLS_ONDEMAND",y.HLS_JS="HLS",y.HLS_FMP4="HLS_FMP4",y.HLS_LIVE="HLS_LIVE",y.HLS_LIVE_CMAF="HLS_LIVE_CMAF",y.WEB_RTC_LIVE="WEB_RTC_LIVE",y))(xt||{});var Bs=(r=>(r.NOT_AVAILABLE="NOT_AVAILABLE",r.AVAILABLE="AVAILABLE",r.CONNECTING="CONNECTING",r.CONNECTED="CONNECTED",r))(Bs||{}),Yo=(i=>(i.HTTP1="http1",i.HTTP2="http2",i.QUIC="quic",i))(Yo||{});var Ko=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(Ko||{}),Vs=(i=>(i.TRAFFIC_SAVING="traffic_saving",i.HIGH_QUALITY="high_quality",i.UNKNOWN="unknown",i))(Vs||{});var Od=C(ci(),1),BI=C(Ee(),1);import{assertNever as lf,assertNonNullable as Nw,isNonNullable as js,ValueSubject as Du,Subject as qw,Subscription as Uw,merge as Hw,observableFrom as jw,fromEvent as sf,map as nf,tap as of,filterChanged as Qw,isNullable as Cu,ErrorCategory as uf}from"@vkontakte/videoplayer-shared/es2024";var af=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 Qs=class{constructor(e){this.connection$=new Du(void 0);this.castState$=new Du("NOT_AVAILABLE");this.errorEvent$=new qw;this.realCastState$=new Du("NOT_AVAILABLE");this.subscription=new Uw;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=js(window.chrome?.cast),r=!!window.__onGCastApiAvailable;i?this.initializeCastApi():(window.__onGCastApiAvailable=s=>{delete window.__onGCastApiAvailable,s&&!this.isDestroyed&&this.initializeCastApi()},r||af("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:uf.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(){js(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();Cu(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();Cu(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(sf(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 lf(r.sessionState)}})).add(Hw(sf(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(of(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),nf(r=>r.castState)),jw([i.getCastState()])).pipe(Qw(),nf(Ww),of(r=>{this.log({message:`realCastState$: ${r}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{let s=r==="CONNECTED",n=js(this.connection$.getValue());if(s&&!n){let u=i.getCurrentSession();Nw(u);let o=u.getCastDevice(),l=u.getMediaSession()?.media?.contentId;(Cu(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"?js(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:uf.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:r})}}},Ww=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 lf(a)}};var Ld=C(Ee(),1),bI=C(Wi(),1),gI=C(il(),1);var iS=C(gn(),1);import{assertNever as qg}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:qg(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:qg(e)}};var P=(a,e,t=!1)=>{let i=a.getTransition();(t||!i||i.to===e)&&a.setState(e)};import{isNonNullable as ML,Subject as Sn,merge as Ug}from"@vkontakte/videoplayer-shared/es2024";var F=class{constructor(e){this.transitionStarted$=new Sn;this.transitionEnded$=new Sn;this.transitionUpdated$=new Sn;this.forceChanged$=new Sn;this.stateChangeStarted$=Ug(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=Ug(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||ML(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 Yg}from"@vkontakte/videoplayer-shared/es2024";var vn=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 Hg=C(Ee(),1);var la=()=>/Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test(navigator.appVersion??navigator.userAgent)||navigator?.userAgentData?.mobile;var yn=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,Hg.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=la()}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 Tn=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,ir=()=>!!(window.ManagedMediaSource&&window.ManagedSourceBuffer?.prototype?.appendBuffer),jg=()=>!!(window.MediaSource&&window.SourceBuffer?.prototype?.appendBuffer),In=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;var DL=document.createElement("video"),CL='video/mp4; codecs="avc1.42000a,mp4a.40.2"',BL='video/mp4; codecs="hev1.1.6.L93.B0"',Qg='video/webm; codecs="vp09.00.10.08"',Wg='video/webm; codecs="av01.0.00M.08"',VL='audio/mp4; codecs="mp4a.40.2"',_L='audio/webm; codecs="opus"',Gg,OL=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:Wg}}),window.navigator.mediaCapabilities.decodingInfo({...a,video:{...a.video,contentType:Qg}})]);Gg={DASH_WEBM_AV1:e,DASH_WEBM:t}};OL().catch(a=>{console.log(DL),console.error(a)});var En=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 Gg}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:ir(),mse:jg(),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?.(CL),t=!!Ue()?.isTypeSupported?.(BL),i=!!Ue()?.isTypeSupported?.(VL);this._codecs={h264:e,h265:t,vp9:!!Ue()?.isTypeSupported?.(Qg),av1:!!Ue()?.isTypeSupported?.(Wg),aac:i,opus:!!Ue()?.isTypeSupported?.(_L),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 zg="audio/mpeg",xn=class{supportMp3(){return this._codecs.mp3&&this._containers.mpeg}detect(){this._audio=document.createElement("audio");try{this._containers={mpeg:!!this._audio.canPlayType?.(zg)},this._codecs={mp3:!!Ue()?.isTypeSupported?.(zg)}}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 FL}from"@vkontakte/videoplayer-shared/es2024";var Ul=class{constructor(){this.isInited$=new FL(!1);this._displayChecker=new Tn,this._deviceChecker=new yn(this._displayChecker),this._browserChecker=new vn,this._videoChecker=new En(this._deviceChecker,this._browserChecker),this._audioChecker=new xn,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)}},B=new Ul;var Hl=a=>{let{containers:e,protocols:t,codecs:i,nativeHlsSupported:r}=B.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 Yg(u)}})},jl=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 Yg(a)}},NL=a=>{let t=Object.keys(a).filter(i=>!jl(i));return Hl(t).length>0};import{assertNever as rr,assertNonNullable as bi,debounce as Kg,ErrorCategory as Xg,fromEvent as gi,isNonNullable as Jg,map as Zg,merge as eS,observableFrom as qL,Subject as UL,Subscription as Ql,timeout as HL,getHighestQuality as jL}from"@vkontakte/videoplayer-shared/es2024";var QL=5,WL=5,GL=500,tS=7e3,ca=class{constructor(e){this.subscription=new Ql;this.loadMediaTimeoutSubscription=new Ql;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:rr(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:rr(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:rr(e)}break}default:rr(i)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(jl(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 Ql;this.subscription.add(e),this.subscription.add(eS(this.videoState.stateChangeStarted$.pipe(Zg(r=>`stateChangeStarted$ ${JSON.stringify(r)}`)),this.videoState.stateChangeEnded$.pipe(Zg(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 UL;e.add(r.pipe(Kg(GL)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add(gi(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)>QL)&&r.next(u),s=u})),e.add(gi(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(gi(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(gi(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemotePause():this.handleRemotePlay()}),t(gi(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<WL&&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:rr(n)}}),t(gi(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t(gi(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({muted:r.value})});let i=eS(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,qL(["init"])).pipe(Kg(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];bi(l);let c=jL(Object.keys(l));bi(c);let p=l[c];bi(p),i=p,r="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_FMP4":case"HLS_ONDEMAND":{let l=t[e];bi(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];bi(l),i=l.url,r="application/dash+xml",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let l=t[e];bi(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];bi(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",c=new Error(l);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:Xg.VIDEO_PIPELINE,message:l,thrown:c}),c}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return rr(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 Jg(u)&&(n.metadata.title=u),Jg(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(HL(tS).subscribe(()=>s(`timeout(${tS})`)))});(0,iS.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:Xg.VIDEO_PIPELINE,message:s,thrown:r})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var cc=C(Ee(),1);import{clearVideoElement as aS}from"@vkontakte/videoplayer-shared/es2024";import{clearVideoElement as zL}from"@vkontakte/videoplayer-shared/es2024";var rS=a=>{try{a.pause(),a.playbackRate=0,zL(a),a.remove()}catch(e){console.error(e)}};import{fromEvent as YL,Subscription as KL}from"@vkontakte/videoplayer-shared/es2024";var Wl=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)}},Gl=window.WeakMap?new WeakMap:new Wl,zl=window.WeakMap?new WeakMap:new Map,XL=(a,e=20)=>{let t=0;return YL(a,"ratechange").subscribe(i=>{t++,t>=e&&(a.currentTime=a.currentTime,t=0)})},$e=(a,{audioVideoSyncRate:e,disableYandexPiP:t})=>{let i=a.querySelector("video"),r=!!i;i?aS(i):(i=document.createElement("video"),a.appendChild(i)),Gl.set(i,r);let s=new KL;return s.add(XL(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},Me=a=>{zl.get(a)?.unsubscribe(),zl.delete(a);let t=Gl.get(a);Gl.delete(a),t?aS(a):rS(a)};var Kl=C(ci(),1);import{assertNonNullable as pa,isNonNullable as bt,isNullable as e$,fromEvent as ar,merge as sS,observableFrom as nS,filterChanged as oS,map as ha,Subject as uS,Subscription as t$,ValueSubject as i$,ErrorCategory as r$}from"@vkontakte/videoplayer-shared/es2024";import{isNonNullable as Yl,isNullable as JL,Subscription as ZL}from"@vkontakte/videoplayer-shared/es2024";var wn=(a,e,t,{equal:i=(n,u)=>n===u,changed$:r,onError:s}={})=>{let n=a.getState(),u=e(),o=JL(r),l=new ZL;return r&&l.add(r.subscribe(c=>{let p=a.getState();i(c,p)&&a.setState(c)},s)),i(u,n)||(t(n),o&&a.setState(n)),l.add(a.stateChangeStarted$.subscribe(c=>{t(c.to),o&&a.setState(c.to)},s)),l},mt=(a,e,t)=>wn(e,()=>a.loop,i=>{Yl(i)&&(a.loop=i)},{onError:t}),De=(a,e,t,i)=>wn(e,()=>({muted:a.muted,volume:a.volume}),r=>{Yl(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)=>wn(e,()=>a.playbackRate,r=>{Yl(r)&&(a.playbackRate=r)},{changed$:t,onError:i}),da=wn;var a$=a=>["__",a.language,a.label].join("|"),s$=(a,e)=>{if(a.id===e)return!0;let[t,i,r]=e.split("|");return a.language===i&&a.label===r},Xl=class a{constructor(e){this.available$=new uS;this.current$=new i$(void 0);this.error$=new uS;this.subscription=new t$;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:r$.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(da(t.internalTextTracks,()=>(0,Kl.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(ha(s=>s.filter(({type:n})=>n==="internal"))),onError:r})),this.subscription.add(da(t.externalTextTracks,()=>(0,Kl.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(ha(s=>s.filter(({type:n})=>n==="external"))),onError:r})),this.subscription.add(da(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(da(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.activeCues)}))}subscribe(){pa(this.video);let{textTracks:e}=this.video;this.subscription.add(ar(e,"addtrack").subscribe(()=>{let i=this.current$.getValue();i&&this.select(i)})),this.subscription.add(sS(ar(e,"addtrack"),ar(e,"removetrack"),nS(["init"])).pipe(ha(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),oS((i,r)=>i.length===r.length&&i.every(({id:s},n)=>s===r[n].id))).subscribe(this.available$)),this.subscription.add(sS(ar(e,"change"),nS(["init"])).pipe(ha(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),ha(i=>i&&this.htmlTextTrackToITextTrack(i).id),oS()).subscribe(this.current$));let t=i=>this.applyCueSettings(i.target?.activeCues??null);this.subscription.add(ar(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(ar(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){pa(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:a$(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){pa(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(e$(e)||!s$(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){pa(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){pa(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=Xl;var Si=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 lS=a=>{let e=a;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e?.parentNode;return e??void 0},Jl=a=>{let e=lS(a);return!!(e&&e.fullscreenElement&&e.fullscreenElement===a)},cS=a=>{let e=lS(a);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===a)};import{fromEvent as xe,map as gt,merge as An,filterChanged as pS,isNonNullable as hS,Subject as o$,filter as Zl,mapTo as ec,combine as u$,once as l$,shareReplay as we,throttle as c$,ErrorCategory as d$,ValueSubject as fS,Subscription as p$}from"@vkontakte/videoplayer-shared/es2024";var n$=3,dS=(a,e,t=n$)=>{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 Ce=a=>{let e=T=>xe(a,T).pipe(ec(void 0),we(1)),t=new p$,i=()=>t.unsubscribe(),r=An(xe(a,"progress"),xe(a,"timeupdate")).pipe(gt(()=>dS(a.buffered,a.currentTime)),we(1)),s=B.browser.isSafari?u$({play:e("play").pipe(l$()),playing:e("playing")}).pipe(ec(void 0),we(1)):e("playing"),n=xe(a,"volumechange").pipe(gt(()=>({muted:a.muted,volume:a.volume})),we(1)),u=xe(a,"ratechange").pipe(gt(()=>a.playbackRate),we(1)),o=xe(a,"error").pipe(Zl(()=>!!(a.error||a.played.length)),gt(()=>{let T=a.error;return{id:T?`MediaError#${T.code}`:"HtmlVideoError",category:d$.VIDEO_PIPELINE,message:T?T.message:"Error event from HTML video element",thrown:a.error??void 0}}),we(1)),l=xe(a,"timeupdate").pipe(gt(()=>a.currentTime),we(1)),c=["waiting","seeking","seeked","timeupdate"],p=new o$,d=.3,h;t.add(An(...c.map(T=>xe(a,T))).subscribe(T=>{let q=a.currentTime;a.loop&&hS(h)&&hS(q)&&h>=a.duration-d&&q<=d&&p.next(h),h=q}));let f=e("pause").pipe(Zl(()=>!a.error&&h!==a.duration),we(1)),b=xe(a,"enterpictureinpicture").pipe(we(1)),S=xe(a,"leavepictureinpicture").pipe(we(1)),g=new fS(cS(a));t.add(b.subscribe(()=>g.next(!0))),t.add(S.subscribe(()=>g.next(!1)));let I=new fS(Jl(a)),x=xe(a,"fullscreenchange").pipe(we(1));t.add(x.pipe(gt(()=>Jl(a))).subscribe(I));let y=.1,w=1e3,D=xe(a,"timeupdate").pipe(gt(T=>a.duration-a.currentTime<y),pS(),we(1)),L=An(D.pipe(Zl(T=>!a.loop&&T)),xe(a,"ended")).pipe(c$(w),ec(void 0),we(1)),R=An(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(T=>xe(a,T)),D.pipe(gt(T=>({type:T?"ended":"unknown"})))).pipe(gt(T=>B.browser.isFirefox&&T.type==="ended"?a.readyState<2:a.readyState<3),pS(),we(1));return{playing$:s,pause$:f,canplay$:e("canplay"),ended$:L,looped$:p,error$:o,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:l,durationChange$:xe(a,"durationchange").pipe(gt(()=>a.duration),we(1)),isBuffering$:R,currentBuffer$:r,volumeState$:n,playbackRateState$:u,inPiP$:g,inFullscreen$:I,enterPip$:b,leavePip$:S,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 Pe=C(at(),1),rc=C(Ee(),1),vi=C(Wi(),1);import{isNonNullable as K,isNullable as $n,now as LS,isHigher as Mn,isHigherOrEqual as nr,isInvariantQuality as Dn,isLowerOrEqual as or,videoSizeToQuality as $S,assertNotEmptyArray as Cn,assertNonNullable as MS}from"@vkontakte/videoplayer-shared/es2024";var tc=!1,kt={},TS=a=>{tc=a},IS=()=>{kt={}},ES=a=>{a(kt)},fa=(a,e)=>{tc&&(kt.meta=kt.meta??{},kt.meta[a]=e)},Ae=class{constructor(e){this.name=e}next(e){if(!tc)return;kt.series=kt.series??{};let t=kt.series[this.name]??[];t.push([Date.now(),e]),kt.series[this.name]=t}};import{isHigher as T$,isHigherOrEqual as tq,isLower as xS,isLowerOrEqual as iq,isNonNullable as Pn,isNullable as I$,videoHeightToQuality as kn}from"@vkontakte/videoplayer-shared/es2024";function ic(a,e,t){return!a.max&&a.min===e?"high_quality":!a.min&&a.max===t?"traffic_saving":"unknown"}function Rn(a,e,t){return!!a&&ic(a,e,t)==="high_quality"}function sr(a,e,t){return I$(a)||Pn(a.min)&&Pn(a.max)&&xS(a.max,a.min)||Pn(a.min)&&e&&T$(a.min,e)||Pn(a.max)&&t&&xS(a.max,t)}function wS({limits:a,highestAvailableHeight:e,lowestAvailableHeight:t}){return sr({max:a?.max?kn(a.max):void 0,min:a?.min?kn(a.min):void 0},e?kn(e):void 0,t?kn(t):void 0)}var DS=new Ae("best_bitrate"),Bn=(a,e,t)=>(e-t)*Math.pow(2,-10*a)+t;var ur=a=>(e,t)=>a*(Number(e.bitrate)-Number(t.bitrate)),Qt=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=LS()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},Vn='Assertion "ABR Tracks is empty array" failed',Ln=new WeakMap,AS=new WeakMap,PS=new WeakMap,ma=(a,e,t,i)=>{let r=[...e].sort(ur(1)),s=[...t].sort(ur(1)),n=s.filter(o=>K(o.bitrate)&&K(a.bitrate)?a.bitrate/o.bitrate>i:!0),u=(0,Pe.default)(s,Math.round(s.length*r.indexOf(a)/(r.length+1)))??(0,Pe.default)(s,-1);return u&&(0,rc.default)(n,u)?u:n.length?(0,Pe.default)(n,-1):(0,Pe.default)(s,0)},ba=(a,e,t,i)=>{let r=Ln.get(e);r||(r=[...e].sort(ur(1)),Ln.set(e,r));let s=Ln.get(t);s||(s=[...t].sort(ur(1)),Ln.set(t,s));let n=PS.get(a);n||(n=s.filter(o=>K(o.bitrate)&&K(a.bitrate)?a.bitrate/o.bitrate>i:!0),PS.set(a,n));let u=(0,Pe.default)(s,Math.round(s.length*r.indexOf(a)/(r.length+1)))??(0,Pe.default)(s,-1);return u&&(0,rc.default)(n,u)?u:n.length?(0,Pe.default)(n,-1):(0,Pe.default)(s,0)},kS=a=>"quality"in a,_n=(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]&&LS()-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=kS(n)?"video":"audio",o=kS(n)?n.quality:n.bitrate;return e({message:`
6
+ var qI=Object.create;var Ud=Object.defineProperty;var UI=Object.getOwnPropertyDescriptor;var HI=Object.getOwnPropertyNames;var jI=Object.getPrototypeOf,QI=Object.prototype.hasOwnProperty;var b=(a,e)=>()=>(e||a((e={exports:{}}).exports,e),e.exports);var WI=(a,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of HI(e))!QI.call(a,r)&&r!==t&&Ud(a,r,{get:()=>e[r],enumerable:!(i=UI(e,r))||i.enumerable});return a};var C=(a,e,t)=>(t=a!=null?qI(jI(a)):{},WI(e||!a||!a.__esModule?Ud(t,"default",{value:a,enumerable:!0}):t,a));var re=b((ru,jd)=>{"use strict";var Nr=function(a){return a&&a.Math===Math&&a};jd.exports=Nr(typeof globalThis=="object"&&globalThis)||Nr(typeof window=="object"&&window)||Nr(typeof self=="object"&&self)||Nr(typeof global=="object"&&global)||Nr(typeof ru=="object"&&ru)||function(){return this}()||Function("return this")()});var pe=b((eV,Qd)=>{"use strict";Qd.exports=function(a){try{return!!a()}catch{return!0}}});var qr=b((tV,Wd)=>{"use strict";var GI=pe();Wd.exports=!GI(function(){var a=function(){}.bind();return typeof a!="function"||a.hasOwnProperty("prototype")})});var au=b((iV,Kd)=>{"use strict";var zI=qr(),Yd=Function.prototype,Gd=Yd.apply,zd=Yd.call;Kd.exports=typeof Reflect=="object"&&Reflect.apply||(zI?zd.bind(Gd):function(){return zd.apply(Gd,arguments)})});var he=b((rV,Zd)=>{"use strict";var Xd=qr(),Jd=Function.prototype,su=Jd.call,YI=Xd&&Jd.bind.bind(su,su);Zd.exports=Xd?YI:function(a){return function(){return su.apply(a,arguments)}}});var oi=b((aV,tp)=>{"use strict";var ep=he(),KI=ep({}.toString),XI=ep("".slice);tp.exports=function(a){return XI(KI(a),8,-1)}});var nu=b((sV,ip)=>{"use strict";var JI=oi(),ZI=he();ip.exports=function(a){if(JI(a)==="Function")return ZI(a)}});var ae=b((nV,rp)=>{"use strict";var ou=typeof document=="object"&&document.all;rp.exports=typeof ou>"u"&&ou!==void 0?function(a){return typeof a=="function"||a===ou}:function(a){return typeof a=="function"}});var Fe=b((oV,ap)=>{"use strict";var eE=pe();ap.exports=!eE(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var Ne=b((uV,sp)=>{"use strict";var tE=qr(),Ws=Function.prototype.call;sp.exports=tE?Ws.bind(Ws):function(){return Ws.apply(Ws,arguments)}});var uu=b(up=>{"use strict";var np={}.propertyIsEnumerable,op=Object.getOwnPropertyDescriptor,iE=op&&!np.call({1:2},1);up.f=iE?function(e){var t=op(this,e);return!!t&&t.enumerable}:np});var Ur=b((cV,lp)=>{"use strict";lp.exports=function(a,e){return{enumerable:!(a&1),configurable:!(a&2),writable:!(a&4),value:e}}});var dp=b((dV,cp)=>{"use strict";var rE=he(),aE=pe(),sE=oi(),lu=Object,nE=rE("".split);cp.exports=aE(function(){return!lu("z").propertyIsEnumerable(0)})?function(a){return sE(a)==="String"?nE(a,""):lu(a)}:lu});var Hr=b((pV,pp)=>{"use strict";pp.exports=function(a){return a==null}});var Ft=b((hV,hp)=>{"use strict";var oE=Hr(),uE=TypeError;hp.exports=function(a){if(oE(a))throw new uE("Can't call method on "+a);return a}});var ui=b((fV,fp)=>{"use strict";var lE=dp(),cE=Ft();fp.exports=function(a){return lE(cE(a))}});var Me=b((mV,mp)=>{"use strict";var dE=ae();mp.exports=function(a){return typeof a=="object"?a!==null:dE(a)}});var li=b((bV,bp)=>{"use strict";bp.exports={}});var wt=b((gV,Sp)=>{"use strict";var cu=li(),du=re(),pE=ae(),gp=function(a){return pE(a)?a:void 0};Sp.exports=function(a,e){return arguments.length<2?gp(cu[a])||gp(du[a]):cu[a]&&cu[a][e]||du[a]&&du[a][e]}});var jr=b((SV,vp)=>{"use strict";var hE=he();vp.exports=hE({}.isPrototypeOf)});var ci=b((vV,Ip)=>{"use strict";var fE=re(),yp=fE.navigator,Tp=yp&&yp.userAgent;Ip.exports=Tp?String(Tp):""});var hu=b((yV,Rp)=>{"use strict";var Pp=re(),pu=ci(),Ep=Pp.process,xp=Pp.Deno,wp=Ep&&Ep.versions||xp&&xp.version,Ap=wp&&wp.v8,et,Gs;Ap&&(et=Ap.split("."),Gs=et[0]>0&&et[0]<4?1:+(et[0]+et[1]));!Gs&&pu&&(et=pu.match(/Edge\/(\d+)/),(!et||et[1]>=74)&&(et=pu.match(/Chrome\/(\d+)/),et&&(Gs=+et[1])));Rp.exports=Gs});var fu=b((TV,Lp)=>{"use strict";var kp=hu(),mE=pe(),bE=re(),gE=bE.String;Lp.exports=!!Object.getOwnPropertySymbols&&!mE(function(){var a=Symbol("symbol detection");return!gE(a)||!(Object(a)instanceof Symbol)||!Symbol.sham&&kp&&kp<41})});var mu=b((IV,$p)=>{"use strict";var SE=fu();$p.exports=SE&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var bu=b((EV,Mp)=>{"use strict";var vE=wt(),yE=ae(),TE=jr(),IE=mu(),EE=Object;Mp.exports=IE?function(a){return typeof a=="symbol"}:function(a){var e=vE("Symbol");return yE(e)&&TE(e.prototype,EE(a))}});var Qr=b((xV,Dp)=>{"use strict";var xE=String;Dp.exports=function(a){try{return xE(a)}catch{return"Object"}}});var ht=b((wV,Cp)=>{"use strict";var wE=ae(),AE=Qr(),PE=TypeError;Cp.exports=function(a){if(wE(a))return a;throw new PE(AE(a)+" is not a function")}});var Wr=b((AV,Bp)=>{"use strict";var RE=ht(),kE=Hr();Bp.exports=function(a,e){var t=a[e];return kE(t)?void 0:RE(t)}});var _p=b((PV,Vp)=>{"use strict";var gu=Ne(),Su=ae(),vu=Me(),LE=TypeError;Vp.exports=function(a,e){var t,i;if(e==="string"&&Su(t=a.toString)&&!vu(i=gu(t,a))||Su(t=a.valueOf)&&!vu(i=gu(t,a))||e!=="string"&&Su(t=a.toString)&&!vu(i=gu(t,a)))return i;throw new LE("Can't convert object to primitive value")}});var tt=b((RV,Op)=>{"use strict";Op.exports=!0});var qp=b((kV,Np)=>{"use strict";var Fp=re(),$E=Object.defineProperty;Np.exports=function(a,e){try{$E(Fp,a,{value:e,configurable:!0,writable:!0})}catch{Fp[a]=e}return e}});var Gr=b((LV,jp)=>{"use strict";var ME=tt(),DE=re(),CE=qp(),Up="__core-js_shared__",Hp=jp.exports=DE[Up]||CE(Up,{});(Hp.versions||(Hp.versions=[])).push({version:"3.43.0",mode:ME?"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 yu=b(($V,Wp)=>{"use strict";var Qp=Gr();Wp.exports=function(a,e){return Qp[a]||(Qp[a]=e||{})}});var Ui=b((MV,Gp)=>{"use strict";var BE=Ft(),VE=Object;Gp.exports=function(a){return VE(BE(a))}});var it=b((DV,zp)=>{"use strict";var _E=he(),OE=Ui(),FE=_E({}.hasOwnProperty);zp.exports=Object.hasOwn||function(e,t){return FE(OE(e),t)}});var Tu=b((CV,Yp)=>{"use strict";var NE=he(),qE=0,UE=Math.random(),HE=NE(1.1.toString);Yp.exports=function(a){return"Symbol("+(a===void 0?"":a)+")_"+HE(++qE+UE,36)}});var ge=b((BV,Xp)=>{"use strict";var jE=re(),QE=yu(),Kp=it(),WE=Tu(),GE=fu(),zE=mu(),Hi=jE.Symbol,Iu=QE("wks"),YE=zE?Hi.for||Hi:Hi&&Hi.withoutSetter||WE;Xp.exports=function(a){return Kp(Iu,a)||(Iu[a]=GE&&Kp(Hi,a)?Hi[a]:YE("Symbol."+a)),Iu[a]}});var th=b((VV,eh)=>{"use strict";var KE=Ne(),Jp=Me(),Zp=bu(),XE=Wr(),JE=_p(),ZE=ge(),ex=TypeError,tx=ZE("toPrimitive");eh.exports=function(a,e){if(!Jp(a)||Zp(a))return a;var t=XE(a,tx),i;if(t){if(e===void 0&&(e="default"),i=KE(t,a,e),!Jp(i)||Zp(i))return i;throw new ex("Can't convert object to primitive value")}return e===void 0&&(e="number"),JE(a,e)}});var Eu=b((_V,ih)=>{"use strict";var ix=th(),rx=bu();ih.exports=function(a){var e=ix(a,"string");return rx(e)?e:e+""}});var zs=b((OV,ah)=>{"use strict";var ax=re(),rh=Me(),xu=ax.document,sx=rh(xu)&&rh(xu.createElement);ah.exports=function(a){return sx?xu.createElement(a):{}}});var wu=b((FV,sh)=>{"use strict";var nx=Fe(),ox=pe(),ux=zs();sh.exports=!nx&&!ox(function(){return Object.defineProperty(ux("div"),"a",{get:function(){return 7}}).a!==7})});var uh=b(oh=>{"use strict";var lx=Fe(),cx=Ne(),dx=uu(),px=Ur(),hx=ui(),fx=Eu(),mx=it(),bx=wu(),nh=Object.getOwnPropertyDescriptor;oh.f=lx?nh:function(e,t){if(e=hx(e),t=fx(t),bx)try{return nh(e,t)}catch{}if(mx(e,t))return px(!cx(dx.f,e,t),e[t])}});var Au=b((qV,lh)=>{"use strict";var gx=pe(),Sx=ae(),vx=/#|\.prototype\./,zr=function(a,e){var t=Tx[yx(a)];return t===Ex?!0:t===Ix?!1:Sx(e)?gx(e):!!e},yx=zr.normalize=function(a){return String(a).replace(vx,".").toLowerCase()},Tx=zr.data={},Ix=zr.NATIVE="N",Ex=zr.POLYFILL="P";lh.exports=zr});var ji=b((UV,dh)=>{"use strict";var ch=nu(),xx=ht(),wx=qr(),Ax=ch(ch.bind);dh.exports=function(a,e){return xx(a),e===void 0?a:wx?Ax(a,e):function(){return a.apply(e,arguments)}}});var Pu=b((HV,ph)=>{"use strict";var Px=Fe(),Rx=pe();ph.exports=Px&&Rx(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var ft=b((jV,hh)=>{"use strict";var kx=Me(),Lx=String,$x=TypeError;hh.exports=function(a){if(kx(a))return a;throw new $x(Lx(a)+" is not an object")}});var di=b(mh=>{"use strict";var Mx=Fe(),Dx=wu(),Cx=Pu(),Ys=ft(),fh=Eu(),Bx=TypeError,Ru=Object.defineProperty,Vx=Object.getOwnPropertyDescriptor,ku="enumerable",Lu="configurable",$u="writable";mh.f=Mx?Cx?function(e,t,i){if(Ys(e),t=fh(t),Ys(i),typeof e=="function"&&t==="prototype"&&"value"in i&&$u in i&&!i[$u]){var r=Vx(e,t);r&&r[$u]&&(e[t]=i.value,i={configurable:Lu in i?i[Lu]:r[Lu],enumerable:ku in i?i[ku]:r[ku],writable:!1})}return Ru(e,t,i)}:Ru:function(e,t,i){if(Ys(e),t=fh(t),Ys(i),Dx)try{return Ru(e,t,i)}catch{}if("get"in i||"set"in i)throw new Bx("Accessors not supported");return"value"in i&&(e[t]=i.value),e}});var Qi=b((WV,bh)=>{"use strict";var _x=Fe(),Ox=di(),Fx=Ur();bh.exports=_x?function(a,e,t){return Ox.f(a,e,Fx(1,t))}:function(a,e,t){return a[e]=t,a}});var oe=b((GV,Sh)=>{"use strict";var Yr=re(),Nx=au(),qx=nu(),Ux=ae(),Hx=uh().f,jx=Au(),Wi=li(),Qx=ji(),Gi=Qi(),gh=it();Gr();var Wx=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 Nx(a,this,arguments)};return e.prototype=a.prototype,e};Sh.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=jx(i?c:t+(r?".":"#")+c,a.forced),p=!l&&n&&gh(n,c),f=u[c],p&&(a.dontCallGetSet?(S=Hx(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=Qx(h,Yr):a.wrap&&p?g=Wx(h):s&&Ux(h)?g=qx(h):g=h,(a.sham||h&&h.sham||f&&f.sham)&&Gi(g,"sham",!0),Gi(u,c,g),s&&(d=t+"Prototype",gh(Wi,d)||Gi(Wi,d,{}),Gi(Wi[d],c,h),a.real&&o&&(l||!o[c])&&Gi(o,c,h)))}});var Ks=b((zV,yh)=>{"use strict";var Gx=yu(),zx=Tu(),vh=Gx("keys");yh.exports=function(a){return vh[a]||(vh[a]=zx(a))}});var Ih=b((YV,Th)=>{"use strict";var Yx=pe();Th.exports=!Yx(function(){function a(){}return a.prototype.constructor=null,Object.getPrototypeOf(new a)!==a.prototype})});var Xs=b((KV,xh)=>{"use strict";var Kx=it(),Xx=ae(),Jx=Ui(),Zx=Ks(),ew=Ih(),Eh=Zx("IE_PROTO"),Mu=Object,tw=Mu.prototype;xh.exports=ew?Mu.getPrototypeOf:function(a){var e=Jx(a);if(Kx(e,Eh))return e[Eh];var t=e.constructor;return Xx(t)&&e instanceof t?t.prototype:e instanceof Mu?tw:null}});var Ah=b((XV,wh)=>{"use strict";var iw=Math.ceil,rw=Math.floor;wh.exports=Math.trunc||function(e){var t=+e;return(t>0?rw:iw)(t)}});var Kr=b((JV,Ph)=>{"use strict";var aw=Ah();Ph.exports=function(a){var e=+a;return e!==e||e===0?0:aw(e)}});var kh=b((ZV,Rh)=>{"use strict";var sw=Kr(),nw=Math.max,ow=Math.min;Rh.exports=function(a,e){var t=sw(a);return t<0?nw(t+e,0):ow(t,e)}});var Du=b((e_,Lh)=>{"use strict";var uw=Kr(),lw=Math.min;Lh.exports=function(a){var e=uw(a);return e>0?lw(e,9007199254740991):0}});var zi=b((t_,$h)=>{"use strict";var cw=Du();$h.exports=function(a){return cw(a.length)}});var Cu=b((i_,Dh)=>{"use strict";var dw=ui(),pw=kh(),hw=zi(),Mh=function(a){return function(e,t,i){var r=dw(e),s=hw(r);if(s===0)return!a&&-1;var n=pw(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}};Dh.exports={includes:Mh(!0),indexOf:Mh(!1)}});var Js=b((r_,Ch)=>{"use strict";Ch.exports={}});var _h=b((a_,Vh)=>{"use strict";var fw=he(),Bu=it(),mw=ui(),bw=Cu().indexOf,gw=Js(),Bh=fw([].push);Vh.exports=function(a,e){var t=mw(a),i=0,r=[],s;for(s in t)!Bu(gw,s)&&Bu(t,s)&&Bh(r,s);for(;e.length>i;)Bu(t,s=e[i++])&&(~bw(r,s)||Bh(r,s));return r}});var Vu=b((s_,Oh)=>{"use strict";Oh.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var _u=b((n_,Fh)=>{"use strict";var Sw=_h(),vw=Vu();Fh.exports=Object.keys||function(e){return Sw(e,vw)}});var Ou=b((o_,jh)=>{"use strict";var qh=Fe(),yw=pe(),Uh=he(),Tw=Xs(),Iw=_u(),Ew=ui(),xw=uu().f,Hh=Uh(xw),ww=Uh([].push),Aw=qh&&yw(function(){var a=Object.create(null);return a[2]=2,!Hh(a,2)}),Nh=function(a){return function(e){for(var t=Ew(e),i=Iw(t),r=Aw&&Tw(t)===null,s=i.length,n=0,u=[],o;s>n;)o=i[n++],(!qh||(r?o in t:Hh(t,o)))&&ww(u,a?[o,t[o]]:t[o]);return u}};jh.exports={entries:Nh(!0),values:Nh(!1)}});var Qh=b(()=>{"use strict";var Pw=oe(),Rw=Ou().values;Pw({target:"Object",stat:!0},{values:function(e){return Rw(e)}})});var Gh=b((c_,Wh)=>{"use strict";Qh();var kw=li();Wh.exports=kw.Object.values});var Yh=b((d_,zh)=>{"use strict";var Lw=Gh();zh.exports=Lw});var pi=b((p_,Kh)=>{"use strict";var $w=Yh();Kh.exports=$w});var Xr=b((h_,Xh)=>{"use strict";Xh.exports=function(){}});var Jh=b(()=>{"use strict";var Mw=oe(),Dw=Cu().includes,Cw=pe(),Bw=Xr(),Vw=Cw(function(){return!Array(1).includes()});Mw({target:"Array",proto:!0,forced:Vw},{includes:function(e){return Dw(this,e,arguments.length>1?arguments[1]:void 0)}});Bw("includes")});var Nt=b((b_,Zh)=>{"use strict";var _w=wt();Zh.exports=_w});var tf=b((g_,ef)=>{"use strict";Jh();var Ow=Nt();ef.exports=Ow("Array","includes")});var af=b((S_,rf)=>{"use strict";var Fw=tf();rf.exports=Fw});var De=b((v_,sf)=>{"use strict";var Nw=af();sf.exports=Nw});var pf=b(()=>{"use strict";var zw=oe(),Yw=Ou().entries;zw({target:"Object",stat:!0},{entries:function(e){return Yw(e)}})});var ff=b((D_,hf)=>{"use strict";pf();var Kw=li();hf.exports=Kw.Object.entries});var bf=b((C_,mf)=>{"use strict";var Xw=ff();mf.exports=Xw});var Yi=b((B_,gf)=>{"use strict";var Jw=bf();gf.exports=Jw});var hi=b((V_,Sf)=>{"use strict";Sf.exports={}});var Tf=b((__,yf)=>{"use strict";var Zw=re(),eA=ae(),vf=Zw.WeakMap;yf.exports=eA(vf)&&/native code/.test(String(vf))});var ju=b((O_,xf)=>{"use strict";var tA=Tf(),Ef=re(),iA=Me(),rA=Qi(),qu=it(),Uu=Gr(),aA=Ks(),sA=Js(),If="Object already initialized",Hu=Ef.TypeError,nA=Ef.WeakMap,tn,Jr,rn,oA=function(a){return rn(a)?Jr(a):tn(a,{})},uA=function(a){return function(e){var t;if(!iA(e)||(t=Jr(e)).type!==a)throw new Hu("Incompatible receiver, "+a+" required");return t}};tA||Uu.state?(rt=Uu.state||(Uu.state=new nA),rt.get=rt.get,rt.has=rt.has,rt.set=rt.set,tn=function(a,e){if(rt.has(a))throw new Hu(If);return e.facade=a,rt.set(a,e),e},Jr=function(a){return rt.get(a)||{}},rn=function(a){return rt.has(a)}):(fi=aA("state"),sA[fi]=!0,tn=function(a,e){if(qu(a,fi))throw new Hu(If);return e.facade=a,rA(a,fi,e),e},Jr=function(a){return qu(a,fi)?a[fi]:{}},rn=function(a){return qu(a,fi)});var rt,fi;xf.exports={set:tn,get:Jr,has:rn,enforce:oA,getterFor:uA}});var Gu=b((F_,Af)=>{"use strict";var Qu=Fe(),lA=it(),wf=Function.prototype,cA=Qu&&Object.getOwnPropertyDescriptor,Wu=lA(wf,"name"),dA=Wu&&function(){}.name==="something",pA=Wu&&(!Qu||Qu&&cA(wf,"name").configurable);Af.exports={EXISTS:Wu,PROPER:dA,CONFIGURABLE:pA}});var Rf=b(Pf=>{"use strict";var hA=Fe(),fA=Pu(),mA=di(),bA=ft(),gA=ui(),SA=_u();Pf.f=hA&&!fA?Object.defineProperties:function(e,t){bA(e);for(var i=gA(t),r=SA(t),s=r.length,n=0,u;s>n;)mA.f(e,u=r[n++],i[u]);return e}});var zu=b((q_,kf)=>{"use strict";var vA=wt();kf.exports=vA("document","documentElement")});var Ju=b((U_,Vf)=>{"use strict";var yA=ft(),TA=Rf(),Lf=Vu(),IA=Js(),EA=zu(),xA=zs(),wA=Ks(),$f=">",Mf="<",Ku="prototype",Xu="script",Cf=wA("IE_PROTO"),Yu=function(){},Bf=function(a){return Mf+Xu+$f+a+Mf+"/"+Xu+$f},Df=function(a){a.write(Bf("")),a.close();var e=a.parentWindow.Object;return a=null,e},AA=function(){var a=xA("iframe"),e="java"+Xu+":",t;return a.style.display="none",EA.appendChild(a),a.src=String(e),t=a.contentWindow.document,t.open(),t.write(Bf("document.F=Object")),t.close(),t.F},an,sn=function(){try{an=new ActiveXObject("htmlfile")}catch{}sn=typeof document<"u"?document.domain&&an?Df(an):AA():Df(an);for(var a=Lf.length;a--;)delete sn[Ku][Lf[a]];return sn()};IA[Cf]=!0;Vf.exports=Object.create||function(e,t){var i;return e!==null?(Yu[Ku]=yA(e),i=new Yu,Yu[Ku]=null,i[Cf]=e):i=sn(),t===void 0?i:TA.f(i,t)}});var Ki=b((H_,_f)=>{"use strict";var PA=Qi();_f.exports=function(a,e,t,i){return i&&i.enumerable?a[e]=t:PA(a,e,t),a}});var il=b((j_,Nf)=>{"use strict";var RA=pe(),kA=ae(),LA=Me(),$A=Ju(),Of=Xs(),MA=Ki(),DA=ge(),CA=tt(),tl=DA("iterator"),Ff=!1,At,Zu,el;[].keys&&(el=[].keys(),"next"in el?(Zu=Of(Of(el)),Zu!==Object.prototype&&(At=Zu)):Ff=!0);var BA=!LA(At)||RA(function(){var a={};return At[tl].call(a)!==a});BA?At={}:CA&&(At=$A(At));kA(At[tl])||MA(At,tl,function(){return this});Nf.exports={IteratorPrototype:At,BUGGY_SAFARI_ITERATORS:Ff}});var nn=b((Q_,Uf)=>{"use strict";var VA=ge(),_A=VA("toStringTag"),qf={};qf[_A]="z";Uf.exports=String(qf)==="[object z]"});var Zr=b((W_,Hf)=>{"use strict";var OA=nn(),FA=ae(),on=oi(),NA=ge(),qA=NA("toStringTag"),UA=Object,HA=on(function(){return arguments}())==="Arguments",jA=function(a,e){try{return a[e]}catch{}};Hf.exports=OA?on:function(a){var e,t,i;return a===void 0?"Undefined":a===null?"Null":typeof(t=jA(e=UA(a),qA))=="string"?t:HA?on(e):(i=on(e))==="Object"&&FA(e.callee)?"Arguments":i}});var Qf=b((G_,jf)=>{"use strict";var QA=nn(),WA=Zr();jf.exports=QA?{}.toString:function(){return"[object "+WA(this)+"]"}});var ea=b((z_,Gf)=>{"use strict";var GA=nn(),zA=di().f,YA=Qi(),KA=it(),XA=Qf(),JA=ge(),Wf=JA("toStringTag");Gf.exports=function(a,e,t,i){var r=t?a:a&&a.prototype;r&&(KA(r,Wf)||zA(r,Wf,{configurable:!0,value:e}),i&&!GA&&YA(r,"toString",XA))}});var Yf=b((Y_,zf)=>{"use strict";var ZA=il().IteratorPrototype,eP=Ju(),tP=Ur(),iP=ea(),rP=hi(),aP=function(){return this};zf.exports=function(a,e,t,i){var r=e+" Iterator";return a.prototype=eP(ZA,{next:tP(+!i,t)}),iP(a,r,!1,!0),rP[r]=aP,a}});var Xf=b((K_,Kf)=>{"use strict";var sP=he(),nP=ht();Kf.exports=function(a,e,t){try{return sP(nP(Object.getOwnPropertyDescriptor(a,e)[t]))}catch{}}});var Zf=b((X_,Jf)=>{"use strict";var oP=Me();Jf.exports=function(a){return oP(a)||a===null}});var tm=b((J_,em)=>{"use strict";var uP=Zf(),lP=String,cP=TypeError;em.exports=function(a){if(uP(a))return a;throw new cP("Can't set "+lP(a)+" as a prototype")}});var rl=b((Z_,im)=>{"use strict";var dP=Xf(),pP=Me(),hP=Ft(),fP=tm();im.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var a=!1,e={},t;try{t=dP(Object.prototype,"__proto__","set"),t(e,[]),a=e instanceof Array}catch{}return function(r,s){return hP(r),fP(s),pP(r)&&(a?t(r,s):r.__proto__=s),r}}():void 0)});var hm=b((eO,pm)=>{"use strict";var mP=oe(),bP=Ne(),un=tt(),cm=Gu(),gP=ae(),SP=Yf(),rm=Xs(),am=rl(),vP=ea(),yP=Qi(),al=Ki(),TP=ge(),sm=hi(),dm=il(),IP=cm.PROPER,EP=cm.CONFIGURABLE,nm=dm.IteratorPrototype,ln=dm.BUGGY_SAFARI_ITERATORS,ta=TP("iterator"),om="keys",ia="values",um="entries",lm=function(){return this};pm.exports=function(a,e,t,i,r,s,n){SP(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 om:return function(){return new t(this,S)};case ia:return function(){return new t(this,S)};case um: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=rm(h.call(new a)),f!==Object.prototype&&f.next&&(!un&&rm(f)!==nm&&(am?am(f,nm):gP(f[ta])||al(f,ta,lm)),vP(f,o,!0,!0),un&&(sm[o]=lm))),IP&&r===ia&&d&&d.name!==ia&&(!un&&EP?yP(p,"name",ia):(l=!0,c=function(){return bP(d,this)})),r)if(m={values:u(ia),keys:s?c:u(om),entries:u(um)},n)for(g in m)(ln||l||!(g in p))&&al(p,g,m[g]);else mP({target:e,proto:!0,forced:ln||l},m);return(!un||n)&&p[ta]!==c&&al(p,ta,c,{name:r}),sm[e]=c,m}});var mm=b((tO,fm)=>{"use strict";fm.exports=function(a,e){return{value:a,done:e}}});var nl=b((iO,ym)=>{"use strict";var xP=ui(),sl=Xr(),bm=hi(),Sm=ju(),wP=di().f,AP=hm(),cn=mm(),PP=tt(),RP=Fe(),vm="Array Iterator",kP=Sm.set,LP=Sm.getterFor(vm);ym.exports=AP(Array,"Array",function(a,e){kP(this,{type:vm,target:xP(a),index:0,kind:e})},function(){var a=LP(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 gm=bm.Arguments=bm.Array;sl("keys");sl("values");sl("entries");if(!PP&&RP&&gm.name!=="values")try{wP(gm,"name",{value:"values"})}catch{}});var Im=b((rO,Tm)=>{"use strict";var $P=ge(),MP=hi(),DP=$P("iterator"),CP=Array.prototype;Tm.exports=function(a){return a!==void 0&&(MP.Array===a||CP[DP]===a)}});var ol=b((aO,xm)=>{"use strict";var BP=Zr(),Em=Wr(),VP=Hr(),_P=hi(),OP=ge(),FP=OP("iterator");xm.exports=function(a){if(!VP(a))return Em(a,FP)||Em(a,"@@iterator")||_P[BP(a)]}});var Am=b((sO,wm)=>{"use strict";var NP=Ne(),qP=ht(),UP=ft(),HP=Qr(),jP=ol(),QP=TypeError;wm.exports=function(a,e){var t=arguments.length<2?jP(a):e;if(qP(t))return UP(NP(t,a));throw new QP(HP(a)+" is not iterable")}});var km=b((nO,Rm)=>{"use strict";var WP=Ne(),Pm=ft(),GP=Wr();Rm.exports=function(a,e,t){var i,r;Pm(a);try{if(i=GP(a,"return"),!i){if(e==="throw")throw t;return t}i=WP(i,a)}catch(s){r=!0,i=s}if(e==="throw")throw t;if(r)throw i;return Pm(i),t}});var pn=b((oO,Dm)=>{"use strict";var zP=ji(),YP=Ne(),KP=ft(),XP=Qr(),JP=Im(),ZP=zi(),Lm=jr(),eR=Am(),tR=ol(),$m=km(),iR=TypeError,dn=function(a,e){this.stopped=a,this.result=e},Mm=dn.prototype;Dm.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=zP(e,i),l,p,d,c,h,f,m,g=function(v){return l&&$m(l,"normal"),new dn(!0,v)},S=function(v){return r?(KP(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=tR(a),!p)throw new iR(XP(a)+" is not iterable");if(JP(p)){for(d=0,c=ZP(a);c>d;d++)if(h=S(a[d]),h&&Lm(Mm,h))return h;return new dn(!1)}l=eR(a,p)}for(f=s?a.next:l.next;!(m=YP(f,l)).done;){try{h=S(m.value)}catch(v){$m(l,"throw",v)}if(typeof h=="object"&&h&&Lm(Mm,h))return h}return new dn(!1)}});var Bm=b((uO,Cm)=>{"use strict";var rR=Fe(),aR=di(),sR=Ur();Cm.exports=function(a,e,t){rR?aR.f(a,e,sR(0,t)):a[e]=t}});var Vm=b(()=>{"use strict";var nR=oe(),oR=pn(),uR=Bm();nR({target:"Object",stat:!0},{fromEntries:function(e){var t={};return oR(e,function(i,r){uR(t,i,r)},{AS_ENTRIES:!0}),t}})});var Om=b((dO,_m)=>{"use strict";nl();Vm();var lR=li();_m.exports=lR.Object.fromEntries});var Nm=b((pO,Fm)=>{"use strict";Fm.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 Um=b(()=>{"use strict";nl();var cR=Nm(),dR=re(),pR=ea(),qm=hi();for(hn in cR)pR(dR[hn],hn),qm[hn]=qm.Array;var hn});var jm=b((mO,Hm)=>{"use strict";var hR=Om();Um();Hm.exports=hR});var ul=b((bO,Qm)=>{"use strict";var fR=jm();Qm.exports=fR});var Wm=b(()=>{"use strict"});var ll=b((vO,Gm)=>{"use strict";var ra=re(),mR=ci(),bR=oi(),fn=function(a){return mR.slice(0,a.length)===a};Gm.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":bR(ra.process)==="process"?"NODE":ra.window&&ra.document?"BROWSER":"REST"}()});var mn=b((yO,zm)=>{"use strict";var gR=ll();zm.exports=gR==="NODE"});var Km=b((TO,Ym)=>{"use strict";var SR=di();Ym.exports=function(a,e,t){return SR.f(a,e,t)}});var Zm=b((IO,Jm)=>{"use strict";var vR=wt(),yR=Km(),TR=ge(),IR=Fe(),Xm=TR("species");Jm.exports=function(a){var e=vR(a);IR&&e&&!e[Xm]&&yR(e,Xm,{configurable:!0,get:function(){return this}})}});var tb=b((EO,eb)=>{"use strict";var ER=jr(),xR=TypeError;eb.exports=function(a,e){if(ER(e,a))return a;throw new xR("Incorrect invocation")}});var dl=b((xO,ib)=>{"use strict";var wR=he(),AR=ae(),cl=Gr(),PR=wR(Function.toString);AR(cl.inspectSource)||(cl.inspectSource=function(a){return PR(a)});ib.exports=cl.inspectSource});var hl=b((wO,ob)=>{"use strict";var RR=he(),kR=pe(),rb=ae(),LR=Zr(),$R=wt(),MR=dl(),ab=function(){},sb=$R("Reflect","construct"),pl=/^\s*(?:class|function)\b/,DR=RR(pl.exec),CR=!pl.test(ab),aa=function(e){if(!rb(e))return!1;try{return sb(ab,[],e),!0}catch{return!1}},nb=function(e){if(!rb(e))return!1;switch(LR(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return CR||!!DR(pl,MR(e))}catch{return!0}};nb.sham=!0;ob.exports=!sb||kR(function(){var a;return aa(aa.call)||!aa(Object)||!aa(function(){a=!0})||a})?nb:aa});var lb=b((AO,ub)=>{"use strict";var BR=hl(),VR=Qr(),_R=TypeError;ub.exports=function(a){if(BR(a))return a;throw new _R(VR(a)+" is not a constructor")}});var fl=b((PO,db)=>{"use strict";var cb=ft(),OR=lb(),FR=Hr(),NR=ge(),qR=NR("species");db.exports=function(a,e){var t=cb(a).constructor,i;return t===void 0||FR(i=cb(t)[qR])?e:OR(i)}});var hb=b((RO,pb)=>{"use strict";var UR=he();pb.exports=UR([].slice)});var mb=b((kO,fb)=>{"use strict";var HR=TypeError;fb.exports=function(a,e){if(a<e)throw new HR("Not enough arguments");return a}});var ml=b((LO,bb)=>{"use strict";var jR=ci();bb.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(jR)});var xl=b(($O,wb)=>{"use strict";var qe=re(),QR=au(),WR=ji(),gb=ae(),GR=it(),xb=pe(),Sb=zu(),zR=hb(),vb=zs(),YR=mb(),KR=ml(),XR=mn(),Tl=qe.setImmediate,Il=qe.clearImmediate,JR=qe.process,bl=qe.Dispatch,ZR=qe.Function,yb=qe.MessageChannel,ek=qe.String,gl=0,sa={},Tb="onreadystatechange",na,mi,Sl,vl;xb(function(){na=qe.location});var El=function(a){if(GR(sa,a)){var e=sa[a];delete sa[a],e()}},yl=function(a){return function(){El(a)}},Ib=function(a){El(a.data)},Eb=function(a){qe.postMessage(ek(a),na.protocol+"//"+na.host)};(!Tl||!Il)&&(Tl=function(e){YR(arguments.length,1);var t=gb(e)?e:ZR(e),i=zR(arguments,1);return sa[++gl]=function(){QR(t,void 0,i)},mi(gl),gl},Il=function(e){delete sa[e]},XR?mi=function(a){JR.nextTick(yl(a))}:bl&&bl.now?mi=function(a){bl.now(yl(a))}:yb&&!KR?(Sl=new yb,vl=Sl.port2,Sl.port1.onmessage=Ib,mi=WR(vl.postMessage,vl)):qe.addEventListener&&gb(qe.postMessage)&&!qe.importScripts&&na&&na.protocol!=="file:"&&!xb(Eb)?(mi=Eb,qe.addEventListener("message",Ib,!1)):Tb in vb("script")?mi=function(a){Sb.appendChild(vb("script"))[Tb]=function(){Sb.removeChild(this),El(a)}}:mi=function(a){setTimeout(yl(a),0)});wb.exports={set:Tl,clear:Il}});var Rb=b((MO,Pb)=>{"use strict";var Ab=re(),tk=Fe(),ik=Object.getOwnPropertyDescriptor;Pb.exports=function(a){if(!tk)return Ab[a];var e=ik(Ab,a);return e&&e.value}});var wl=b((DO,Lb)=>{"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}}};Lb.exports=kb});var Mb=b((CO,$b)=>{"use strict";var rk=ci();$b.exports=/ipad|iphone|ipod/i.test(rk)&&typeof Pebble<"u"});var Cb=b((BO,Db)=>{"use strict";var ak=ci();Db.exports=/web0s(?!.*chrome)/i.test(ak)});var qb=b((VO,Nb)=>{"use strict";var Ji=re(),sk=Rb(),Bb=ji(),Al=xl().set,nk=wl(),ok=ml(),uk=Mb(),lk=Cb(),Pl=mn(),Vb=Ji.MutationObserver||Ji.WebKitMutationObserver,_b=Ji.document,Ob=Ji.process,bn=Ji.Promise,Ll=sk("queueMicrotask"),Xi,Rl,kl,gn,Fb;Ll||(oa=new nk,ua=function(){var a,e;for(Pl&&(a=Ob.domain)&&a.exit();e=oa.get();)try{e()}catch(t){throw oa.head&&Xi(),t}a&&a.enter()},!ok&&!Pl&&!lk&&Vb&&_b?(Rl=!0,kl=_b.createTextNode(""),new Vb(ua).observe(kl,{characterData:!0}),Xi=function(){kl.data=Rl=!Rl}):!uk&&bn&&bn.resolve?(gn=bn.resolve(void 0),gn.constructor=bn,Fb=Bb(gn.then,gn),Xi=function(){Fb(ua)}):Pl?Xi=function(){Ob.nextTick(ua)}:(Al=Bb(Al,Ji),Xi=function(){Al(ua)}),Ll=function(a){oa.head||Xi(),oa.add(a)});var oa,ua;Nb.exports=Ll});var Hb=b((_O,Ub)=>{"use strict";Ub.exports=function(a,e){try{arguments.length===1?console.error(a):console.error(a,e)}catch{}}});var Sn=b((OO,jb)=>{"use strict";jb.exports=function(a){try{return{error:!1,value:a()}}catch(e){return{error:!0,value:e}}}});var bi=b((FO,Qb)=>{"use strict";var ck=re();Qb.exports=ck.Promise});var Zi=b((NO,Yb)=>{"use strict";var dk=re(),la=bi(),pk=ae(),hk=Au(),fk=dl(),mk=ge(),Wb=ll(),bk=tt(),$l=hu(),Gb=la&&la.prototype,gk=mk("species"),Ml=!1,zb=pk(dk.PromiseRejectionEvent),Sk=hk("Promise",function(){var a=fk(la),e=a!==String(la);if(!e&&$l===66||bk&&!(Gb.catch&&Gb.finally))return!0;if(!$l||$l<51||!/native code/.test(a)){var t=new la(function(s){s(1)}),i=function(s){s(function(){},function(){})},r=t.constructor={};if(r[gk]=i,Ml=t.then(function(){})instanceof i,!Ml)return!0}return!e&&(Wb==="BROWSER"||Wb==="DENO")&&!zb});Yb.exports={CONSTRUCTOR:Sk,REJECTION_EVENT:zb,SUBCLASSING:Ml}});var er=b((qO,Xb)=>{"use strict";var Kb=ht(),vk=TypeError,yk=function(a){var e,t;this.promise=new a(function(i,r){if(e!==void 0||t!==void 0)throw new vk("Bad Promise constructor");e=i,t=r}),this.resolve=Kb(e),this.reject=Kb(t)};Xb.exports.f=function(a){return new yk(a)}});var gg=b(()=>{"use strict";var Tk=oe(),Ik=tt(),In=mn(),qt=re(),Ek=li(),ar=Ne(),Jb=Ki(),Zb=rl(),xk=ea(),wk=Zm(),Ak=ht(),Tn=ae(),Pk=Me(),Rk=tb(),kk=fl(),ag=xl().set,_l=qb(),Lk=Hb(),$k=Sn(),Mk=wl(),sg=ju(),En=bi(),Ol=Zi(),ng=er(),xn="Promise",og=Ol.CONSTRUCTOR,Dk=Ol.REJECTION_EVENT,Ck=Ol.SUBCLASSING,Dl=sg.getterFor(xn),Bk=sg.set,tr=En&&En.prototype,gi=En,vn=tr,ug=qt.TypeError,Cl=qt.document,Fl=qt.process,Bl=ng.f,Vk=Bl,_k=!!(Cl&&Cl.createEvent&&qt.dispatchEvent),lg="unhandledrejection",Ok="rejectionhandled",eg=0,cg=1,Fk=2,Nl=1,dg=2,yn,tg,pg,ig,hg=function(a){var e;return Pk(a)&&Tn(e=a.then)?e:!1},fg=function(a,e){var t=e.value,i=e.state===cg,r=i?a.ok:a.fail,s=a.resolve,n=a.reject,u=a.domain,o,l,p;try{r?(i||(e.rejection===dg&&qk(e),e.rejection=Nl),r===!0?o=t:(u&&u.enter(),o=r(t),u&&(u.exit(),p=!0)),o===a.promise?n(new ug("Promise-chain cycle")):(l=hg(o))?ar(l,o,s,n):s(o)):n(t)}catch(d){u&&!p&&u.exit(),n(d)}},mg=function(a,e){a.notified||(a.notified=!0,_l(function(){for(var t=a.reactions,i;i=t.get();)fg(i,a);a.notified=!1,e&&!a.rejection&&Nk(a)}))},bg=function(a,e,t){var i,r;_k?(i=Cl.createEvent("Event"),i.promise=e,i.reason=t,i.initEvent(a,!1,!0),qt.dispatchEvent(i)):i={promise:e,reason:t},!Dk&&(r=qt["on"+a])?r(i):a===lg&&Lk("Unhandled promise rejection",t)},Nk=function(a){ar(ag,qt,function(){var e=a.facade,t=a.value,i=rg(a),r;if(i&&(r=$k(function(){In?Fl.emit("unhandledRejection",t,e):bg(lg,e,t)}),a.rejection=In||rg(a)?dg:Nl,r.error))throw r.value})},rg=function(a){return a.rejection!==Nl&&!a.parent},qk=function(a){ar(ag,qt,function(){var e=a.facade;In?Fl.emit("rejectionHandled",e):bg(Ok,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=Fk,mg(a,!0))},Vl=function(a,e,t){if(!a.done){a.done=!0,t&&(a=t);try{if(a.facade===e)throw new ug("Promise can't be resolved itself");var i=hg(e);i?_l(function(){var r={done:!1};try{ar(i,e,ir(Vl,r,a),ir(rr,r,a))}catch(s){rr(r,s,a)}}):(a.value=e,a.state=cg,mg(a,!1))}catch(r){rr({done:!1},r,a)}}};if(og&&(gi=function(e){Rk(this,vn),Ak(e),ar(yn,this);var t=Dl(this);try{e(ir(Vl,t),ir(rr,t))}catch(i){rr(t,i)}},vn=gi.prototype,yn=function(e){Bk(this,{type:xn,done:!1,notified:!1,parent:!1,reactions:new Mk,rejection:!1,state:eg,value:null})},yn.prototype=Jb(vn,"then",function(e,t){var i=Dl(this),r=Bl(kk(this,gi));return i.parent=!0,r.ok=Tn(e)?e:!0,r.fail=Tn(t)&&t,r.domain=In?Fl.domain:void 0,i.state===eg?i.reactions.add(r):_l(function(){fg(r,i)}),r.promise}),tg=function(){var a=new yn,e=Dl(a);this.promise=a,this.resolve=ir(Vl,e),this.reject=ir(rr,e)},ng.f=Bl=function(a){return a===gi||a===pg?new tg(a):Vk(a)},!Ik&&Tn(En)&&tr!==Object.prototype)){ig=tr.then,Ck||Jb(tr,"then",function(e,t){var i=this;return new gi(function(r,s){ar(ig,i,r,s)}).then(e,t)},{unsafe:!0});try{delete tr.constructor}catch{}Zb&&Zb(tr,vn)}Tk({global:!0,constructor:!0,wrap:!0,forced:og},{Promise:gi});pg=Ek.Promise;xk(gi,xn,!1,!0);wk(xn)});var Ig=b((jO,Tg)=>{"use strict";var Uk=ge(),vg=Uk("iterator"),yg=!1;try{Sg=0,ql={next:function(){return{done:!!Sg++}},return:function(){yg=!0}},ql[vg]=function(){return this},Array.from(ql,function(){throw 2})}catch{}var Sg,ql;Tg.exports=function(a,e){try{if(!e&&!yg)return!1}catch{return!1}var t=!1;try{var i={};i[vg]=function(){return{next:function(){return{done:t=!0}}}},a(i)}catch{}return t}});var Ul=b((QO,Eg)=>{"use strict";var Hk=bi(),jk=Ig(),Qk=Zi().CONSTRUCTOR;Eg.exports=Qk||!jk(function(a){Hk.all(a).then(void 0,function(){})})});var xg=b(()=>{"use strict";var Wk=oe(),Gk=Ne(),zk=ht(),Yk=er(),Kk=Sn(),Xk=pn(),Jk=Ul();Wk({target:"Promise",stat:!0,forced:Jk},{all:function(e){var t=this,i=Yk.f(t),r=i.resolve,s=i.reject,n=Kk(function(){var u=zk(t.resolve),o=[],l=0,p=1;Xk(e,function(d){var c=l++,h=!1;p++,Gk(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 Ag=b(()=>{"use strict";var Zk=oe(),eL=tt(),tL=Zi().CONSTRUCTOR,jl=bi(),iL=wt(),rL=ae(),aL=Ki(),wg=jl&&jl.prototype;Zk({target:"Promise",proto:!0,forced:tL,real:!0},{catch:function(a){return this.then(void 0,a)}});!eL&&rL(jl)&&(Hl=iL("Promise").prototype.catch,wg.catch!==Hl&&aL(wg,"catch",Hl,{unsafe:!0}));var Hl});var Pg=b(()=>{"use strict";var sL=oe(),nL=Ne(),oL=ht(),uL=er(),lL=Sn(),cL=pn(),dL=Ul();sL({target:"Promise",stat:!0,forced:dL},{race:function(e){var t=this,i=uL.f(t),r=i.reject,s=lL(function(){var n=oL(t.resolve);cL(e,function(u){nL(n,t,u).then(i.resolve,r)})});return s.error&&r(s.value),i.promise}})});var Rg=b(()=>{"use strict";var pL=oe(),hL=er(),fL=Zi().CONSTRUCTOR;pL({target:"Promise",stat:!0,forced:fL},{reject:function(e){var t=hL.f(this),i=t.reject;return i(e),t.promise}})});var Ql=b((eF,kg)=>{"use strict";var mL=ft(),bL=Me(),gL=er();kg.exports=function(a,e){if(mL(a),bL(e)&&e.constructor===a)return e;var t=gL.f(a),i=t.resolve;return i(e),t.promise}});var Mg=b(()=>{"use strict";var SL=oe(),vL=wt(),Lg=tt(),yL=bi(),$g=Zi().CONSTRUCTOR,TL=Ql(),IL=vL("Promise"),EL=Lg&&!$g;SL({target:"Promise",stat:!0,forced:Lg||$g},{resolve:function(e){return TL(EL&&this===IL?yL:this,e)}})});var Dg=b(()=>{"use strict";gg();xg();Ag();Pg();Rg();Mg()});var _g=b(()=>{"use strict";var xL=oe(),wL=tt(),wn=bi(),AL=pe(),Bg=wt(),Vg=ae(),PL=fl(),Cg=Ql(),RL=Ki(),Gl=wn&&wn.prototype,kL=!!wn&&AL(function(){Gl.finally.call({then:function(){}},function(){})});xL({target:"Promise",proto:!0,real:!0,forced:kL},{finally:function(a){var e=PL(this,Bg("Promise")),t=Vg(a);return this.then(t?function(i){return Cg(e,a()).then(function(){return i})}:a,t?function(i){return Cg(e,a()).then(function(){throw i})}:a)}});!wL&&Vg(wn)&&(Wl=Bg("Promise").prototype.finally,Gl.finally!==Wl&&RL(Gl,"finally",Wl,{unsafe:!0}));var Wl});var Fg=b((oF,Og)=>{"use strict";Wm();Dg();_g();var LL=Nt();Og.exports=LL("Promise","finally")});var qg=b((uF,Ng)=>{"use strict";var $L=Fg();Ng.exports=$L});var An=b((lF,Ug)=>{"use strict";var ML=qg();Ug.exports=ML});var gS=b(()=>{"use strict";var f$=oe(),m$=Ui(),b$=zi(),g$=Kr(),S$=Xr();f$({target:"Array",proto:!0},{at:function(e){var t=m$(this),i=b$(t),r=g$(e),s=r>=0?r:i+r;return s<0||s>=i?void 0:t[s]}});S$("at")});var vS=b((eq,SS)=>{"use strict";gS();var v$=Nt();SS.exports=v$("Array","at")});var TS=b((tq,yS)=>{"use strict";var y$=vS();yS.exports=y$});var at=b((iq,IS)=>{"use strict";var T$=TS();IS.exports=T$});var gc=b((GU,av)=>{"use strict";var tM=oi();av.exports=Array.isArray||function(e){return tM(e)==="Array"}});var nv=b((zU,sv)=>{"use strict";var iM=TypeError,rM=9007199254740991;sv.exports=function(a){if(a>rM)throw iM("Maximum allowed index exceeded");return a}});var lv=b((YU,uv)=>{"use strict";var aM=gc(),sM=zi(),nM=nv(),oM=ji(),ov=function(a,e,t,i,r,s,n,u){for(var o=r,l=0,p=n?oM(n,u):!1,d,c;l<i;)l in t&&(d=p?p(t[l],l,e):t[l],s>0&&aM(d)?(c=sM(d),o=ov(a,e,d,c,o,s-1)-1):(nM(o+1),a[o]=d),o++),l++;return o};uv.exports=ov});var hv=b((KU,pv)=>{"use strict";var cv=gc(),uM=hl(),lM=Me(),cM=ge(),dM=cM("species"),dv=Array;pv.exports=function(a){var e;return cv(a)&&(e=a.constructor,uM(e)&&(e===dv||cv(e.prototype))?e=void 0:lM(e)&&(e=e[dM],e===null&&(e=void 0))),e===void 0?dv:e}});var mv=b((XU,fv)=>{"use strict";var pM=hv();fv.exports=function(a,e){return new(pM(a))(e===0?0:e)}});var bv=b(()=>{"use strict";var hM=oe(),fM=lv(),mM=ht(),bM=Ui(),gM=zi(),SM=mv();hM({target:"Array",proto:!0},{flatMap:function(e){var t=bM(this),i=gM(t),r;return mM(e),r=SM(t,0),r.length=fM(r,t,t,i,0,1,e,arguments.length>1?arguments[1]:void 0),r}})});var gv=b(()=>{"use strict";var vM=Xr();vM("flatMap")});var vv=b((i1,Sv)=>{"use strict";bv();gv();var yM=Nt();Sv.exports=yM("Array","flatMap")});var Tv=b((r1,yv)=>{"use strict";var TM=vv();yv.exports=TM});var wa=b((a1,Iv)=>{"use strict";var IM=Tv();Iv.exports=IM});var Aa=b((s1,Ev)=>{"use strict";var EM=Zr(),xM=String;Ev.exports=function(a){if(EM(a)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return xM(a)}});var Sc=b((n1,xv)=>{"use strict";xv.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 Pv=b((o1,Av)=>{"use strict";var wM=he(),AM=Ft(),PM=Aa(),yc=Sc(),wv=wM("".replace),RM=RegExp("^["+yc+"]+"),kM=RegExp("(^|[^"+yc+"])["+yc+"]+$"),vc=function(a){return function(e){var t=PM(AM(e));return a&1&&(t=wv(t,RM,"")),a&2&&(t=wv(t,kM,"$1")),t}};Av.exports={start:vc(1),end:vc(2),trim:vc(3)}});var $v=b((u1,Lv)=>{"use strict";var LM=Gu().PROPER,$M=pe(),Rv=Sc(),kv="\u200B\x85\u180E";Lv.exports=function(a){return $M(function(){return!!Rv[a]()||kv[a]()!==kv||LM&&Rv[a].name!==a})}});var Tc=b((l1,Mv)=>{"use strict";var MM=Pv().start,DM=$v();Mv.exports=DM("trimStart")?function(){return MM(this)}:"".trimStart});var Cv=b(()=>{"use strict";var CM=oe(),Dv=Tc();CM({target:"String",proto:!0,name:"trimStart",forced:"".trimLeft!==Dv},{trimLeft:Dv})});var Vv=b(()=>{"use strict";Cv();var BM=oe(),Bv=Tc();BM({target:"String",proto:!0,name:"trimStart",forced:"".trimStart!==Bv},{trimStart:Bv})});var Ov=b((f1,_v)=>{"use strict";Vv();var VM=Nt();_v.exports=VM("String","trimLeft")});var Nv=b((m1,Fv)=>{"use strict";var _M=Ov();Fv.exports=_M});var Uv=b((b1,qv)=>{"use strict";var OM=Nv();qv.exports=OM});var ay=b(()=>{"use strict"});var sy=b(()=>{"use strict"});var oy=b((iQ,ny)=>{"use strict";var uD=Me(),lD=oi(),cD=ge(),dD=cD("match");ny.exports=function(a){var e;return uD(a)&&((e=a[dD])!==void 0?!!e:lD(a)==="RegExp")}});var cy=b((rQ,ly)=>{"use strict";var pD=re(),hD=pe(),uy=pD.RegExp,fD=!hD(function(){var a=!0;try{uy(".","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(uy.prototype,"flags").get.call(e);return u!==i||t!==i});ly.exports={correct:fD}});var py=b((aQ,dy)=>{"use strict";var mD=ft();dy.exports=function(){var a=mD(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 my=b((sQ,fy)=>{"use strict";var bD=Ne(),gD=it(),SD=jr(),hy=cy(),vD=py(),yD=RegExp.prototype;fy.exports=hy.correct?function(a){return a.flags}:function(a){return!hy.correct&&SD(yD,a)&&!gD(a,"flags")?bD(vD,a):a.flags}});var gy=b((nQ,by)=>{"use strict";var Ac=he(),TD=Ui(),ID=Math.floor,xc=Ac("".charAt),ED=Ac("".replace),wc=Ac("".slice),xD=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,wD=/\$([$&'`]|\d{1,2})/g;by.exports=function(a,e,t,i,r,s){var n=t+a.length,u=i.length,o=wD;return r!==void 0&&(r=TD(r),o=xD),ED(s,o,function(l,p){var d;switch(xc(p,0)){case"$":return"$";case"&":return a;case"`":return wc(e,0,t);case"'":return wc(e,n);case"<":d=r[wc(p,1,-1)];break;default:var c=+p;if(c===0)return l;if(c>u){var h=ID(c/10);return h===0?l:h<=u?i[h-1]===void 0?xc(p,1):i[h-1]+xc(p,1):l}d=i[c-1]}return d===void 0?"":d})}});var yy=b(()=>{"use strict";var AD=oe(),PD=Ne(),Rc=he(),Sy=Ft(),RD=ae(),kD=Me(),LD=oy(),gr=Aa(),$D=Wr(),MD=my(),DD=gy(),CD=ge(),BD=tt(),VD=CD("replace"),_D=TypeError,Pc=Rc("".indexOf),OD=Rc("".replace),vy=Rc("".slice),FD=Math.max;AD({target:"String",proto:!0},{replaceAll:function(e,t){var i=Sy(this),r,s,n,u,o,l,p,d,c,h,f=0,m="";if(kD(e)){if(r=LD(e),r&&(s=gr(Sy(MD(e))),!~Pc(s,"g")))throw new _D("`.replaceAll` does not allow non-global regexes");if(n=$D(e,VD),n)return PD(n,e,i,t);if(BD&&r)return OD(gr(i),e,t)}for(u=gr(i),o=gr(e),l=RD(t),l||(t=gr(t)),p=o.length,d=FD(1,p),c=Pc(u,o);c!==-1;)h=l?gr(t(o,c,u)):DD(o,u,c,[],void 0,t),m+=vy(u,f,c)+h,f=c+p,c=c+d>u.length?-1:Pc(u,o,c+d);return f<u.length&&(m+=vy(u,f)),m}})});var Iy=b((lQ,Ty)=>{"use strict";ay();sy();yy();var ND=Nt();Ty.exports=ND("String","replaceAll")});var xy=b((cQ,Ey)=>{"use strict";var qD=Iy();Ey.exports=qD});var Ay=b((dQ,wy)=>{"use strict";var UD=xy();wy.exports=UD});var Ry=b((pQ,Py)=>{"use strict";var HD=Kr(),jD=Aa(),QD=Ft(),WD=RangeError;Py.exports=function(e){var t=jD(QD(this)),i="",r=HD(e);if(r<0||r===1/0)throw new WD("Wrong number of repetitions");for(;r>0;(r>>>=1)&&(t+=t))r&1&&(i+=t);return i}});var Dy=b((hQ,My)=>{"use strict";var $y=he(),GD=Du(),ky=Aa(),zD=Ry(),YD=Ft(),KD=$y(zD),XD=$y("".slice),JD=Math.ceil,Ly=function(a){return function(e,t,i){var r=ky(YD(e)),s=GD(t),n=r.length,u=i===void 0?" ":ky(i),o,l;return s<=n||u===""?r:(o=s-n,l=KD(u,JD(o/u.length)),l.length>o&&(l=XD(l,0,o)),a?r+l:l+r)}};My.exports={start:Ly(!1),end:Ly(!0)}});var By=b((fQ,Cy)=>{"use strict";var ZD=ci();Cy.exports=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(ZD)});var Vy=b(()=>{"use strict";var eC=oe(),tC=Dy().start,iC=By();eC({target:"String",proto:!0,forced:iC},{padStart:function(e){return tC(this,e,arguments.length>1?arguments[1]:void 0)}})});var Oy=b((gQ,_y)=>{"use strict";Vy();var rC=Nt();_y.exports=rC("String","padStart")});var Ny=b((SQ,Fy)=>{"use strict";var aC=Oy();Fy.exports=aC});var Uy=b((vQ,qy)=>{"use strict";var sC=Ny();qy.exports=sC});var Hd="2.0.140-dev.7b3cdcf7.0";var $e=(r=>(r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused",r))($e||{}),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||{}),tu=(i=>(i.HTTP1="http1",i.HTTP2="http2",i.QUIC="quic",i))(tu||{});var iu=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(iu||{}),Qs=(i=>(i.TRAFFIC_SAVING="traffic_saving",i.HIGH_QUALITY="high_quality",i.UNKNOWN="unknown",i))(Qs||{});var Nd=C(pi(),1),VI=C(De(),1);import{assertNever as df,assertNonNullable as qw,isNonNullable as Zs,ValueSubject as Fu,Subject as Uw,Subscription as Hw,merge as jw,observableFrom as Qw,fromEvent as of,map as uf,tap as lf,filterChanged as Ww,isNullable as Nu,ErrorCategory as cf}from"@vkontakte/videoplayer-shared/es2024";var nf=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 Fu(void 0);this.castState$=new Fu("NOT_AVAILABLE");this.errorEvent$=new Uw;this.realCastState$=new Fu("NOT_AVAILABLE");this.subscription=new Hw;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||nf("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:cf.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();Nu(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();Nu(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(of(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 df(r.sessionState)}})).add(jw(of(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(lf(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),uf(r=>r.castState)),Qw([i.getCastState()])).pipe(Ww(),uf(Gw),lf(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();qw(u);let o=u.getCastDevice(),l=u.getMediaSession()?.media?.contentId;(Nu(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:cf.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:r})}}},Gw=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 df(a)}};var $d=C(De(),1),gI=C(Yi(),1),SI=C(ul(),1);var aS=C(An(),1);import{assertNever as Hg}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:Hg(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:Hg(e)}};var P=(a,e,t=!1)=>{let i=a.getTransition();(t||!i||i.to===e)&&a.setState(e)};import{isNonNullable as DL,Subject as Pn,merge as jg}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$=jg(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=jg(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||DL(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 Xg}from"@vkontakte/videoplayer-shared/es2024";var Rn=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 Qg=C(De(),1);var ca=()=>/Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test(navigator.appVersion??navigator.userAgent)||navigator?.userAgentData?.mobile;var kn=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,Qg.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),Wg=()=>!!(window.MediaSource&&window.SourceBuffer?.prototype?.appendBuffer),$n=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;var CL=document.createElement("video"),BL='video/mp4; codecs="avc1.42000a,mp4a.40.2"',VL='video/mp4; codecs="hev1.1.6.L93.B0"',Gg='video/webm; codecs="vp09.00.10.08"',zg='video/webm; codecs="av01.0.00M.08"',_L='audio/mp4; codecs="mp4a.40.2"',OL='audio/webm; codecs="opus"',Yg,FL=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:zg}}),window.navigator.mediaCapabilities.decodingInfo({...a,video:{...a.video,contentType:Gg}})]);Yg={DASH_WEBM_AV1:e,DASH_WEBM:t}};FL().catch(a=>{console.log(CL),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 Yg}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:Wg(),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?.(BL),t=!!Ue()?.isTypeSupported?.(VL),i=!!Ue()?.isTypeSupported?.(_L);this._codecs={h264:e,h265:t,vp9:!!Ue()?.isTypeSupported?.(Gg),av1:!!Ue()?.isTypeSupported?.(zg),aac:i,opus:!!Ue()?.isTypeSupported?.(OL),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 Kg="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?.(Kg)},this._codecs={mp3:!!Ue()?.isTypeSupported?.(Kg)}}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 NL}from"@vkontakte/videoplayer-shared/es2024";var zl=class{constructor(){this.isInited$=new NL(!1);this._displayChecker=new Ln,this._deviceChecker=new kn(this._displayChecker),this._browserChecker=new Rn,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)}},B=new zl;var Yl=a=>{let{containers:e,protocols:t,codecs:i,nativeHlsSupported:r}=B.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 Xg(u)}})},Kl=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 Xg(a)}},qL=a=>{let t=Object.keys(a).filter(i=>!Kl(i));return Yl(t).length>0};import{assertNever as nr,assertNonNullable as Si,debounce as Jg,ErrorCategory as Zg,fromEvent as vi,isNonNullable as eS,map as tS,merge as iS,observableFrom as UL,Subject as HL,Subscription as Xl,timeout as jL,getHighestQuality as QL}from"@vkontakte/videoplayer-shared/es2024";var WL=5,GL=5,zL=500,rS=7e3,da=class{constructor(e){this.subscription=new Xl;this.loadMediaTimeoutSubscription=new Xl;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(Kl(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 Xl;this.subscription.add(e),this.subscription.add(iS(this.videoState.stateChangeStarted$.pipe(tS(r=>`stateChangeStarted$ ${JSON.stringify(r)}`)),this.videoState.stateChangeEnded$.pipe(tS(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 HL;e.add(r.pipe(Jg(zL)).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)>WL)&&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<GL&&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=iS(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,UL(["init"])).pipe(Jg(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=QL(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:Zg.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 eS(u)&&(n.metadata.title=u),eS(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(jL(rS).subscribe(()=>s(`timeout(${rS})`)))});(0,aS.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:Zg.VIDEO_PIPELINE,message:s,thrown:r})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var mc=C(De(),1);import{clearVideoElement as nS}from"@vkontakte/videoplayer-shared/es2024";import{clearVideoElement as YL}from"@vkontakte/videoplayer-shared/es2024";var sS=a=>{try{a.pause(),a.playbackRate=0,YL(a),a.remove()}catch(e){console.error(e)}};import{fromEvent as KL,Subscription as XL}from"@vkontakte/videoplayer-shared/es2024";var Jl=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)}},Zl=window.WeakMap?new WeakMap:new Jl,ec=window.WeakMap?new WeakMap:new Map,JL=(a,e=20)=>{let t=0;return KL(a,"ratechange").subscribe(i=>{t++,t>=e&&(a.currentTime=a.currentTime,t=0)})},Ce=(a,{audioVideoSyncRate:e,disableYandexPiP:t})=>{let i=a.querySelector("video"),r=!!i;i?nS(i):(i=document.createElement("video"),a.appendChild(i)),Zl.set(i,r);let s=new XL;return s.add(JL(i,e)),ec.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},Be=a=>{ec.get(a)?.unsubscribe(),ec.delete(a);let t=Zl.get(a);Zl.delete(a),t?nS(a):sS(a)};var ic=C(pi(),1);import{assertNonNullable as ha,isNonNullable as bt,isNullable as t$,fromEvent as or,merge as oS,observableFrom as uS,filterChanged as lS,map as fa,Subject as cS,Subscription as i$,ValueSubject as r$,ErrorCategory as a$}from"@vkontakte/videoplayer-shared/es2024";import{isNonNullable as tc,isNullable as ZL,Subscription as e$}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=ZL(r),l=new e$;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=>{tc(i)&&(a.loop=i)},{onError:t}),Ee=(a,e,t,i)=>Cn(e,()=>({muted:a.muted,volume:a.volume}),r=>{tc(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=>{tc(r)&&(a.playbackRate=r)},{changed$:t,onError:i}),pa=Cn;var s$=a=>["__",a.language,a.label].join("|"),n$=(a,e)=>{if(a.id===e)return!0;let[t,i,r]=e.split("|");return a.language===i&&a.label===r},rc=class a{constructor(e){this.available$=new cS;this.current$=new r$(void 0);this.error$=new cS;this.subscription=new i$;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:a$.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,ic.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,ic.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(oS(or(e,"addtrack"),or(e,"removetrack"),uS(["init"])).pipe(fa(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),lS((i,r)=>i.length===r.length&&i.every(({id:s},n)=>s===r[n].id))).subscribe(this.available$)),this.subscription.add(oS(or(e,"change"),uS(["init"])).pipe(fa(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),fa(i=>i&&this.htmlTextTrackToITextTrack(i).id),lS()).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:s$(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))(t$(e)||!n$(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=rc;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 dS=a=>{let e=a;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e?.parentNode;return e??void 0},ac=a=>{let e=dS(a);return!!(e&&e.fullscreenElement&&e.fullscreenElement===a)},pS=a=>{let e=dS(a);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===a)};import{fromEvent as xe,map as gt,merge as Bn,filterChanged as fS,isNonNullable as mS,Subject as u$,filter as sc,mapTo as nc,combine as l$,once as c$,shareReplay as we,throttle as d$,ErrorCategory as p$,ValueSubject as bS,Subscription as h$}from"@vkontakte/videoplayer-shared/es2024";var o$=3,hS=(a,e,t=o$)=>{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=>xe(a,x).pipe(nc(void 0),we(1)),t=new h$,i=()=>t.unsubscribe(),r=Bn(xe(a,"progress"),xe(a,"timeupdate")).pipe(gt(()=>hS(a.buffered,a.currentTime)),we(1)),s=B.browser.isSafari?l$({play:e("play").pipe(c$()),playing:e("playing")}).pipe(nc(void 0),we(1)):e("playing"),n=xe(a,"volumechange").pipe(gt(()=>({muted:a.muted,volume:a.volume})),we(1)),u=xe(a,"ratechange").pipe(gt(()=>a.playbackRate),we(1)),o=xe(a,"error").pipe(sc(()=>!!(a.error||a.played.length)),gt(()=>{let x=a.error;return{id:x?`MediaError#${x.code}`:"HtmlVideoError",category:p$.VIDEO_PIPELINE,message:x?x.message:"Error event from HTML video element",thrown:a.error??void 0}}),we(1)),l=xe(a,"timeupdate").pipe(gt(()=>a.currentTime),we(1)),p=["waiting","seeking","seeked","timeupdate"],d=new u$,c=.3,h;t.add(Bn(...p.map(x=>xe(a,x))).subscribe(x=>{let q=a.currentTime;a.loop&&mS(h)&&mS(q)&&h>=a.duration-c&&q<=c&&d.next(h),h=q}));let f=e("pause").pipe(sc(()=>!a.error&&h!==a.duration),we(1)),m=xe(a,"enterpictureinpicture").pipe(we(1)),g=xe(a,"leavepictureinpicture").pipe(we(1)),S=new bS(pS(a));t.add(m.subscribe(()=>S.next(!0))),t.add(g.subscribe(()=>S.next(!1)));let v=new bS(ac(a)),I=xe(a,"fullscreenchange").pipe(we(1));t.add(I.pipe(gt(()=>ac(a))).subscribe(v));let T=.1,A=1e3,k=xe(a,"timeupdate").pipe(gt(x=>a.duration-a.currentTime<T),fS(),we(1)),L=Bn(k.pipe(sc(x=>!a.loop&&x)),xe(a,"ended")).pipe(d$(A),nc(void 0),we(1)),D=Bn(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(x=>xe(a,x)),k.pipe(gt(x=>({type:x?"ended":"unknown"})))).pipe(gt(x=>B.browser.isFirefox&&x.type==="ended"?a.readyState<2:a.readyState<3),fS(),we(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$:xe(a,"durationchange").pipe(gt(()=>a.duration),we(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 Pe=C(at(),1),uc=C(De(),1),Ii=C(Yi(),1);import{isNonNullable as K,isNullable as Fn,now as DS,isHigher as Nn,isHigherOrEqual as Ti,isInvariantQuality as qn,isLowerOrEqual as lr,videoSizeToQuality as CS,assertNotEmptyArray as Un,assertNonNullable as BS}from"@vkontakte/videoplayer-shared/es2024";var oc=!1,Rt={},ES=a=>{oc=a},xS=()=>{Rt={}},wS=a=>{a(Rt)},ma=(a,e)=>{oc&&(Rt.meta=Rt.meta??{},Rt.meta[a]=e)},Ae=class{constructor(e){this.name=e}next(e){if(!oc)return;Rt.series=Rt.series??{};let t=Rt.series[this.name]??[];t.push([Date.now(),e]),Rt.series[this.name]=t}};import{isHigher as I$,isHigherOrEqual as uq,isLower as AS,isLowerOrEqual as lq,isNonNullable as Vn,isNullable as E$,videoHeightToQuality as _n}from"@vkontakte/videoplayer-shared/es2024";function PS(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 E$(a)||Vn(a.min)&&Vn(a.max)&&AS(a.max,a.min)||Vn(a.min)&&e&&I$(a.min,e)||Vn(a.max)&&t&&AS(a.max,t)}function RS({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 VS=new Ae("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]=DS()}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,LS=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,Pe.default)(s,Math.round(s.length*r.indexOf(a)/(r.length+1)))??(0,Pe.default)(s,-1);return u&&(0,uc.default)(n,u)?u:n.length?(0,Pe.default)(n,-1):(0,Pe.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=LS.get(a);n||(n=s.filter(o=>K(o.bitrate)&&K(a.bitrate)?a.bitrate/o.bitrate>i:!0),LS.set(a,n));let u=(0,Pe.default)(s,Math.round(s.length*r.indexOf(a)/(r.length+1)))??(0,Pe.default)(s,-1);return u&&(0,uc.default)(n,u)?u:n.length?(0,Pe.default)(n,-1):(0,Pe.default)(s,0)},$S=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]&&DS()-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=$S(n)?"video":"audio",o=$S(n)?n.quality:n.bitrate;return e({message:`
8
8
  [last ${u} selected] ${o}
9
- `}),n}return i?.recordSwitch(t),t},E$=(a,e)=>Math.log(e)/Math.log(a),CS=({tuning:a,container:e,limits:t,panelSize:i})=>{let r=a.containerSizeFactor;if(i)return{containerSizeLimit:i,containerSizeFactor:r};if(a.usePixelRatio&&B.display.pixelRatio){let s=B.display.pixelRatio;if(a.pixelRatioMultiplier)r*=a.pixelRatioMultiplier*(s-1)+1;else{let n=a.pixelRatioLogBase,[u=0,o=0,l=0]=a.pixelRatioLogCoefficients,c=E$(n,u*s+o)+l;Number.isFinite(c)&&(r*=c)}}return Rn(t,a.highQualityLimit,a.trafficSavingLimit)&&(r*=2),{containerSizeLimit:a.limitByContainer&&e&&e.width>0&&e.height>0?{width:e.width*r,height:e.height*r}:void 0,containerSizeFactor:r}},RS=new WeakMap,St=(a,{container:e,estimatedThroughput:t,tuning:i,limits:r,reserve:s=0,forwardBufferHealth:n,playbackRate:u,current:o,history:l,visible:c,droppedVideoMaxQualityLimit:p,stallsVideoMaxQualityLimit:d,stallsPredictedThroughput:h,abrLogger:f,panelSize:b})=>{Cn(a,Vn);let{containerSizeFactor:S,containerSizeLimit:g}=CS({container:e,tuning:i,limits:r,panelSize:b}),I=i.considerPlaybackRate&&K(u)?u:1,x=RS.get(a);x||(x=a.filter(v=>!Dn(v.quality)).sort((v,E)=>Mn(v.quality,E.quality)?-1:1),RS.set(a,x));let y=(0,Pe.default)(x,-1)?.quality,w=(0,Pe.default)(x,0)?.quality,D=sr(r,w,y),L=I*Bn(n??.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),A={},R=null;for(let v of x){let E=!0;if(g)if(v.size)E=v.size.width<=g.width&&v.size.height<=g.height;else{let j=g&&$S(g);E=j?or(v.quality,j):!0}if(!E){A[v.quality]="FitsContainer";continue}let z=h||t,M=K(z)&&isFinite(z)&&K(v.bitrate)?z-s>=v.bitrate*L:!0,H=Rn(r,i.highQualityLimit,i.trafficSavingLimit)&&r?.min===v.quality;if(!M&&!H){A[v.quality]="FitsThroughput";continue}if(i.lazyQualitySwitch&&K(i.minBufferToSwitchUp)&&o&&!Dn(o.quality)&&(n??0)<i.minBufferToSwitchUp&&Mn(v.quality,o.quality)){A[v.quality]="Buffer";continue}if(!!p&&nr(v.quality,p)&&!H){A[v.quality]="DroppedFramesLimit";continue}if(!!d&&nr(v.quality,d)&&!H){A[v.quality]="StallsLimit";continue}let fe=D||($n(r?.max)||or(v.quality,r.max))&&($n(r?.min)||nr(v.quality,r.min)),me=K(c)&&!c?or(v.quality,i.backgroundVideoQualityLimit):!0;if(!fe||!me){A[v.quality]="FitsQualityLimits";continue}R||(R=v)}R&&R.bitrate&&DS.next(R.bitrate);let T=R??(0,Pe.default)(x,-1)??a[0],q=l?.last,$=_n(i,f,T,l);return K(l)&&$.quality!==q?.quality&&f({message:`
9
+ `}),n}return i?.recordSwitch(t),t},x$=(a,e)=>Math.log(e)/Math.log(a),_S=({tuning:a,container:e,limits:t,panelSize:i})=>{let r=a.containerSizeFactor;if(i)return{containerSizeLimit:i,containerSizeFactor:r};if(a.usePixelRatio&&B.display.pixelRatio){let s=B.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=x$(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}},MS=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}=_S({container:e,tuning:i,limits:r,panelSize:m}),v=i.considerPlaybackRate&&K(u)?u:1,I=MS.get(a);I||(I=a.filter(y=>!qn(y.quality)).sort((y,E)=>Nn(y.quality,E.quality)?-1:1),MS.set(a,I));let T=(0,Pe.default)(I,-1)?.quality,A=(0,Pe.default)(I,0)?.quality,k=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&&CS(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=k||(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&&VS.next(D.bitrate);let x=D??(0,Pe.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]
11
11
  [available video tracks]
12
- ${a.map(v=>`{ id: ${v.id}, quality: ${v.quality}, bitrate: ${v.bitrate}, size: ${v.size?.width}:${v.size?.height} }`).join(`
12
+ ${a.map(y=>`{ id: ${y.id}, quality: ${y.quality}, bitrate: ${y.bitrate}, size: ${y.size?.width}:${y.size?.height} }`).join(`
13
13
  `)}
14
14
 
15
15
  [tuning]
16
- ${(0,vi.default)(i??{}).map(([v,E])=>`${v}: ${E}`).join(`
16
+ ${(0,Ii.default)(i??{}).map(([y,E])=>`${y}: ${E}`).join(`
17
17
  `)}
18
18
 
19
19
  [limit params]
20
- containerSizeFactor: ${S},
21
- containerSizeLimit: ${g?.width??0} x ${g?.height??0},
20
+ containerSizeFactor: ${g},
21
+ containerSizeLimit: ${S?.width??0} x ${S?.height??0},
22
22
  estimatedThroughput: ${t},
23
23
  stallsPredictedThroughput: ${h},
24
24
  reserve: ${s},
25
25
  playbackRate: ${u},
26
- playbackRateFactor: ${I},
26
+ playbackRateFactor: ${v},
27
27
  forwardBufferHealth: ${n},
28
28
  bitrateFactor: ${L},
29
29
  minBufferToSwitchUp: ${i.minBufferToSwitchUp},
30
- droppedVideoMaxQualityLimit: ${p},
31
- stallsVideoMaxQualityLimit: ${d},
32
- limitsAreInvalid: ${D},
30
+ droppedVideoMaxQualityLimit: ${d},
31
+ stallsVideoMaxQualityLimit: ${c},
32
+ limitsAreInvalid: ${k},
33
33
  maxQualityLimit: ${r?.max},
34
34
  minQualityLimit: ${r?.min},
35
35
 
36
36
  [limited video tracks]
37
- ${(0,vi.default)(A).map(([v,E])=>`${v}: ${E}`).join(`
37
+ ${(0,Ii.default)(w).map(([y,E])=>`${y}: ${E}`).join(`
38
38
  `)||"All tracks are available"}
39
39
 
40
- [best video track] ${R?.quality}
40
+ [best video track] ${D?.quality}
41
41
  [selected video track] ${$?.quality}
42
- `}),$},On=(a,{container:e,estimatedThroughput:t,tuning:i,limits:r,reserve:s=0,forwardBufferHealth:n,playbackRate:u,current:o,history:l,visible:c,droppedVideoMaxQualityLimit:p,stallsVideoMaxQualityLimit:d,stallsPredictedThroughput:h,abrLogger:f,panelSize:b})=>{Cn(a,Vn);let{containerSizeFactor:S,containerSizeLimit:g}=CS({container:e,tuning:i,limits:r,panelSize:b}),I=i.considerPlaybackRate&&K(u)?u:1,x=a.filter(E=>!Dn(E.quality)).sort((E,z)=>Mn(E.quality,z.quality)?-1:1),y=(0,Pe.default)(x,-1)?.quality,w=(0,Pe.default)(x,0)?.quality,D=sr(r,w,y),L=I*Bn(n??.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),A={},T=x.filter(E=>{let z=!0;if(g)if(E.size)z=E.size.width<=g.width&&E.size.height<=g.height;else{let U=g&&$S(g);z=U?or(E.quality,U):!0}if(!z)return A[E.quality]="FitsContainer",!1;let M=h||t,H=K(M)&&isFinite(M)&&K(E.bitrate)?M-s>=E.bitrate*L:!0,J=Rn(r,i.highQualityLimit,i.trafficSavingLimit)&&r?.min===E.quality;if(!H&&!J)return A[E.quality]="FitsThroughput",!1;if(i.lazyQualitySwitch&&K(i.minBufferToSwitchUp)&&o&&!Dn(o.quality)&&(n??0)<i.minBufferToSwitchUp&&Mn(E.quality,o.quality))return A[E.quality]="Buffer",!1;if(!!p&&nr(E.quality,p)&&!J)return A[E.quality]="DroppedFramesLimit",!1;if(!!d&&nr(E.quality,d)&&!J)return A[E.quality]="StallsLimit",!1;let me=D||($n(r?.max)||or(E.quality,r.max))&&($n(r?.min)||nr(E.quality,r.min)),j=K(c)&&!c?or(E.quality,i.backgroundVideoQualityLimit):!0;return!me||!j?(A[E.quality]="FitsQualityLimits",!1):!0})[0];T&&T.bitrate&&DS.next(T.bitrate);let q=T??(0,Pe.default)(x,-1)??a[0],$=l?.last,v=_n(i,f,q,l);return K(l)&&v.quality!==$?.quality&&f({message:`
42
+ `}),$},Wn=(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}=_S({container:e,tuning:i,limits:r,panelSize:m}),v=i.considerPlaybackRate&&K(u)?u:1,I=a.filter(E=>!qn(E.quality)).sort((E,z)=>Nn(E.quality,z.quality)?-1:1),T=(0,Pe.default)(I,-1)?.quality,A=(0,Pe.default)(I,0)?.quality,k=ur(r,A,T),L=v*Hn(n??.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),w={},x=I.filter(E=>{let z=!0;if(S)if(E.size)z=E.size.width<=S.width&&E.size.height<=S.height;else{let U=S&&CS(S);z=U?lr(E.quality,U):!0}if(!z)return w[E.quality]="FitsContainer",!1;let M=h||t,H=K(M)&&isFinite(M)&&K(E.bitrate)?M-s>=E.bitrate*L:!0,J=r?.min===E.quality;if(!H&&!J)return w[E.quality]="FitsThroughput",!1;if(i.lazyQualitySwitch&&K(i.minBufferToSwitchUp)&&o&&!qn(o.quality)&&(n??0)<i.minBufferToSwitchUp&&Nn(E.quality,o.quality))return w[E.quality]="Buffer",!1;if(!!d&&Ti(E.quality,d)&&!J)return w[E.quality]="DroppedFramesLimit",!1;if(!!c&&Ti(E.quality,c)&&!J)return w[E.quality]="StallsLimit",!1;let be=k||(Fn(r?.max)||lr(E.quality,r.max))&&(Fn(r?.min)||Ti(E.quality,r.min)),j=K(p)&&!p?lr(E.quality,i.backgroundVideoQualityLimit):!0;return!be||!j?(w[E.quality]="FitsQualityLimits",!1):!0})[0];x&&x.bitrate&&VS.next(x.bitrate);let q=x??(0,Pe.default)(I,-1)??a[0],$=l?.last,y=Qn(i,f,q,l);return K(l)&&y.quality!==$?.quality&&f({message:`
43
43
  [VIDEO TRACKS ABR]
44
44
  [available video tracks]
45
45
  ${a.map(E=>`{ id: ${E.id}, quality: ${E.quality}, bitrate: ${E.bitrate}, size: ${E.size?.width}:${E.size?.height} }`).join(`
46
46
  `)}
47
47
 
48
48
  [tuning]
49
- ${(0,vi.default)(i??{}).map(([E,z])=>`${E}: ${z}`).join(`
49
+ ${(0,Ii.default)(i??{}).map(([E,z])=>`${E}: ${z}`).join(`
50
50
  `)}
51
51
 
52
52
  [limit params]
53
- containerSizeFactor: ${S},
54
- containerSizeLimit: ${g?.width??0} x ${g?.height??0},
53
+ containerSizeFactor: ${g},
54
+ containerSizeLimit: ${S?.width??0} x ${S?.height??0},
55
55
  estimatedThroughput: ${t},
56
56
  stallsPredictedThroughput: ${h},
57
57
  reserve: ${s},
58
58
  playbackRate: ${u},
59
- playbackRateFactor: ${I},
59
+ playbackRateFactor: ${v},
60
60
  forwardBufferHealth: ${n},
61
61
  bitrateFactor: ${L},
62
62
  minBufferToSwitchUp: ${i.minBufferToSwitchUp},
63
- droppedVideoMaxQualityLimit: ${p},
64
- stallsVideoMaxQualityLimit: ${d},
65
- limitsAreInvalid: ${D},
63
+ droppedVideoMaxQualityLimit: ${d},
64
+ stallsVideoMaxQualityLimit: ${c},
65
+ limitsAreInvalid: ${k},
66
66
  maxQualityLimit: ${r?.max},
67
67
  minQualityLimit: ${r?.min},
68
68
 
69
69
  [limited video tracks]
70
- ${(0,vi.default)(A).map(([E,z])=>`${E}: ${z}`).join(`
70
+ ${(0,Ii.default)(w).map(([E,z])=>`${E}: ${z}`).join(`
71
71
  `)||"All tracks are available"}
72
72
 
73
- [best video track] ${T?.quality}
74
- [selected video track] ${v?.quality}
75
- `}),v},Fn=(a,e,t,{estimatedThroughput:i,tuning:r,playbackRate:s,forwardBufferHealth:n,history:u,abrLogger:o,stallsPredictedThroughput:l})=>{Cn(t,Vn);let c=r.considerPlaybackRate&&K(s)?s:1,p=[...t].sort(ur(-1)),d=a.bitrate;MS(d);let h=c*Bn(n??.5,r.bitrateAudioFactorAtEmptyBuffer,r.bitrateAudioFactorAtFullBuffer),f,b=ma(a,e,t,r.minVideoAudioRatio),S=l||i;K(S)&&isFinite(S)&&(f=p.find(x=>K(x.bitrate)&&K(b?.bitrate)?S-d>=x.bitrate*h&&x.bitrate>=b.bitrate:!1)),f||(f=b);let g=u?.last,I=f&&_n(r,o,f,u);return K(u)&&I?.bitrate!==g?.bitrate&&o({message:`
73
+ [best video track] ${x?.quality}
74
+ [selected video track] ${y?.quality}
75
+ `}),y},Gn=(a,e,t,{estimatedThroughput:i,tuning:r,playbackRate:s,forwardBufferHealth:n,history:u,abrLogger:o,stallsPredictedThroughput:l})=>{Un(t,jn);let p=r.considerPlaybackRate&&K(s)?s:1,d=[...t].sort(cr(-1)),c=a.bitrate;BS(c);let h=p*Hn(n??.5,r.bitrateAudioFactorAtEmptyBuffer,r.bitrateAudioFactorAtFullBuffer),f,m=ba(a,e,t,r.minVideoAudioRatio),g=l||i;K(g)&&isFinite(g)&&(f=d.find(I=>K(I.bitrate)&&K(m?.bitrate)?g-c>=I.bitrate*h&&I.bitrate>=m.bitrate:!1)),f||(f=m);let S=u?.last,v=f&&Qn(r,o,f,u);return K(u)&&v?.bitrate!==S?.bitrate&&o({message:`
76
76
  [AUDIO TRACKS ABR]
77
77
  [available audio tracks]
78
- ${t.map(x=>`{ id: ${x.id}, bitrate: ${x.bitrate} }`).join(`
78
+ ${t.map(I=>`{ id: ${I.id}, bitrate: ${I.bitrate} }`).join(`
79
79
  `)}
80
80
 
81
81
  [tuning]
82
- ${(0,vi.default)(r??{}).map(([x,y])=>`${x}: ${y}`).join(`
82
+ ${(0,Ii.default)(r??{}).map(([I,T])=>`${I}: ${T}`).join(`
83
83
  `)}
84
84
 
85
85
  [limit params]
86
86
  estimatedThroughput: ${i},
87
87
  stallsPredictedThroughput: ${l},
88
- reserve: ${d},
88
+ reserve: ${c},
89
89
  playbackRate: ${s},
90
- playbackRateFactor: ${c},
90
+ playbackRateFactor: ${p},
91
91
  forwardBufferHealth: ${n},
92
92
  bitrateFactor: ${h},
93
93
  minBufferToSwitchUp: ${r.minBufferToSwitchUp},
94
94
 
95
- [selected audio track] ${I?.id}
96
- `}),I},Nn=(a,e,t,{estimatedThroughput:i,tuning:r,playbackRate:s,forwardBufferHealth:n,history:u,abrLogger:o,stallsPredictedThroughput:l})=>{Cn(t,Vn);let c=r.considerPlaybackRate&&K(s)?s:1,p=AS.get(t);p||(p=[...t].sort(ur(-1)),AS.set(t,p));let d=a.bitrate;MS(d);let h=c*Bn(n??.5,r.bitrateAudioFactorAtEmptyBuffer,r.bitrateAudioFactorAtFullBuffer),f,b=ba(a,e,t,r.minVideoAudioRatio),S=l||i;K(S)&&isFinite(S)&&(f=p.find(x=>K(x.bitrate)&&K(b?.bitrate)?S-d>=x.bitrate*h&&x.bitrate>=b.bitrate:!1)),f||(f=b);let g=u?.last,I=f&&_n(r,o,f,u);return K(u)&&I?.bitrate!==g?.bitrate&&o({message:`
95
+ [selected audio track] ${v?.id}
96
+ `}),v},zn=(a,e,t,{estimatedThroughput:i,tuning:r,playbackRate:s,forwardBufferHealth:n,history:u,abrLogger:o,stallsPredictedThroughput:l})=>{Un(t,jn);let p=r.considerPlaybackRate&&K(s)?s:1,d=kS.get(t);d||(d=[...t].sort(cr(-1)),kS.set(t,d));let c=a.bitrate;BS(c);let h=p*Hn(n??.5,r.bitrateAudioFactorAtEmptyBuffer,r.bitrateAudioFactorAtFullBuffer),f,m=ga(a,e,t,r.minVideoAudioRatio),g=l||i;K(g)&&isFinite(g)&&(f=d.find(I=>K(I.bitrate)&&K(m?.bitrate)?g-c>=I.bitrate*h&&I.bitrate>=m.bitrate:!1)),f||(f=m);let S=u?.last,v=f&&Qn(r,o,f,u);return K(u)&&v?.bitrate!==S?.bitrate&&o({message:`
97
97
  [AUDIO TRACKS ABR]
98
98
  [available audio tracks]
99
- ${t.map(x=>`{ id: ${x.id}, bitrate: ${x.bitrate} }`).join(`
99
+ ${t.map(I=>`{ id: ${I.id}, bitrate: ${I.bitrate} }`).join(`
100
100
  `)}
101
101
 
102
102
  [tuning]
103
- ${(0,vi.default)(r??{}).map(([x,y])=>`${x}: ${y}`).join(`
103
+ ${(0,Ii.default)(r??{}).map(([I,T])=>`${I}: ${T}`).join(`
104
104
  `)}
105
105
 
106
106
  [limit params]
107
107
  estimatedThroughput: ${i},
108
108
  stallsPredictedThroughput: ${l},
109
- reserve: ${d},
109
+ reserve: ${c},
110
110
  playbackRate: ${s},
111
- playbackRateFactor: ${c},
111
+ playbackRateFactor: ${p},
112
112
  forwardBufferHealth: ${n},
113
113
  bitrateFactor: ${h},
114
114
  minBufferToSwitchUp: ${r.minBufferToSwitchUp},
115
115
 
116
- [selected audio track] ${I?.id}
117
- `}),I};var ge=a=>new URL(a).hostname;import{assertNever as QS,assertNonNullable as WS,combine as j$,debounce as Q$,ErrorCategory as GS,filter as zS,filterChanged as W$,isNonNullable as uc,map as jn,merge as YS,observableFrom as G$,once as z$,Subscription as Y$,ValueSubject as lc,videoQualityToHeight as KS,videoSizeToQuality as K$}from"@vkontakte/videoplayer-shared/es2024";var qS=C(at(),1);var VS=C(Ee(),1),BS=a=>{if(a instanceof DOMException&&(0,VS.default)(["Failed to load because no supported source was found.","The element has no supported sources."],a.message))throw a;return!(a instanceof DOMException&&(a.code===20||a.name==="AbortError"))},Be=async(a,e)=>{let t=a.muted;try{await a.play()}catch(i){if(!BS(i))return!1;if(e&&e(),t)return console.warn(i),!1;a.muted=!0;try{await a.play()}catch(r){return BS(r)&&(a.muted=!1,console.warn(r)),!1}}return!0};import{isNonNullable as Un,isNullable as A$,assertNonNullable as va}from"@vkontakte/videoplayer-shared/es2024";var OS=C(ci(),1);import{isNonNullable as _S,assertNonNullable as qn,now as x$}from"@vkontakte/videoplayer-shared/es2024";function pe(){return x$()}function ac(a){return pe()-a}function sc(a){let e=a.split("/"),t=e.slice(0,e.length-1).join("/"),i=/^([a-z]+:)?\/\//i,r=n=>i.test(n);return{resolve:(n,u,o=!1)=>{r(n)||(n.startsWith("/")||(n="/"+n),n=t+n);let l=n.indexOf("?")>-1?"&":"?";return o&&(n+=l+"lowLat=1",l="&"),u&&(n+=l+"_rnd="+Math.floor(999999999*Math.random())),n}}}function FS(a,e,t){let i=(...r)=>{t.apply(null,r),a.removeEventListener(e,i)};a.addEventListener(e,i)}function lr(a,e,t,i){let r=window.XMLHttpRequest,s,n,u,o=!1,l=0,c,p,d=!1,h="arraybuffer",f=7e3,b=2e3,S=()=>{if(o)return;qn(c);let $=ac(c),v;if($<b){v=b-$,setTimeout(S,v);return}b*=2,b>f&&(b=f),n&&n.abort(),n=new r,D()},g=$=>(s=$,q),I=$=>(p=$,q),x=()=>(h="json",q),y=()=>{if(!o){if(--l>=0){S(),i&&i();return}o=!0,p&&p(),t&&t()}},w=$=>(d=$,q),D=()=>{c=pe(),n=new r,n.open("get",a);let $=0,v,E=0,z=()=>(qn(c),Math.max(c,Math.max(v||0,E||0)));if(s&&n.addEventListener("progress",M=>{let H=pe();s.updateChunk&&M.loaded>$&&(s.updateChunk(z(),M.loaded-$),$=M.loaded,v=H)}),u&&(n.timeout=u,n.addEventListener("timeout",()=>y())),n.addEventListener("load",()=>{if(o)return;qn(n);let M=n.status;if(M>=200&&M<300){let{response:H,responseType:J}=n,ie=H?.byteLength;if(typeof ie=="number"&&s){let ue=ie-$;ue&&s.updateChunk&&s.updateChunk(z(),ue)}J==="json"&&(!H||!(0,OS.default)(H).length)?y():(p&&p(),e(H))}else y()}),n.addEventListener("error",()=>{y()}),d){let M=()=>{qn(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(E=pe(),n.removeEventListener("readystatechange",M))};n.addEventListener("readystatechange",M)}return n.responseType=h,n.send(),q},q={withBitrateReporting:g,withParallel:w,withJSONResponse:x,withRetryCount:$=>(l=$,q),withRetryInterval:($,v)=>(_S($)&&(b=$),_S(v)&&(f=v),q),withTimeout:$=>(u=$,q),withFinally:I,send:D,abort:()=>{n&&(n.abort(),n=void 0),o=!0,p&&p()}};return q}var ga=class{constructor(e){this.intervals=[];this.currentRate=0;this.logger=e}_updateRate(e){let t=.2;this.currentRate&&(e<this.currentRate*.1?t=.8:e<this.currentRate*.5?t=.5:e<this.currentRate*.7&&(t=.3)),e=Math.max(1,Math.min(e,100*1024*1024)),this.currentRate=this.currentRate?this.currentRate*(1-t)+e*t:e}_createInterval(e,t,i){return{start:e,end:t,bytes:i}}_doMergeIntervals(e,t){e.start=Math.min(t.start,e.start),e.end=Math.max(t.end,e.end),e.bytes+=t.bytes}_mergeIntervals(e,t){return e.start<=t.end&&t.start<=e.end?(this._doMergeIntervals(e,t),!0):!1}_flushIntervals(){if(!this.intervals.length)return!1;let e=this.intervals[0].start,t=this.intervals[this.intervals.length-1].end-500;if(t-e>2e3){let i=0,r=0;for(;this.intervals.length>0;){let s=this.intervals[0];if(s.end<=t)i+=s.end-s.start,r+=s.bytes,this.intervals.splice(0,1);else{if(s.start>=t)break;{let n=t-s.start,u=s.end-s.start;i+=n;let o=s.bytes*n/u;r+=o,s.start=t,s.bytes-=o}}}if(r>0&&i>0){let s=r*8/(i/1e3);return this._updateRate(s),this.logger(`rate updated, new=${Math.round(s/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(r)}/${Math.round(i)} interval=${Math.round(t-e)}`),!0}}return!1}_joinIntervals(){let e;do{e=!1;for(let t=0;t<this.intervals.length-1;++t)this._mergeIntervals(this.intervals[t],this.intervals[t+1])&&(this.intervals.splice(t+1,1),e=!0)}while(e)}addInterval(e,t,i){return this.intervals.push(this._createInterval(e,t,i)),this._joinIntervals(),this.intervals.length>100&&(this.logger(`too many intervals (${this.intervals.length}); will merge`,{type:"warn"}),this._doMergeIntervals(this.intervals[1],this.intervals[0]),this.intervals.splice(0,1)),this._flushIntervals()}getBitRate(){return this.currentRate}};var NS=C(ci(),1);var Sa=class{constructor(e,t,i,r,s){this.pendingQueue=[];this.activeRequests={};this.completeRequests={};this.averageSegmentDuration=2e3;this.lastPrefetchStart=0;this.throttleTimeout=null;this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=i,this.MAX_PARALLEL_REQUESTS=r,this.logger=s}limitCompleteCount(){let e;for(;(e=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){let t=e[Math.floor(Math.random()*e.length)];this.logger(`Dropping completed request for url ${t}`,{type:"warn"}),delete this.completeRequests[t]}}_sendRequest(e,t){let i=pe(),r=o=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=o,e._errorCB?e._errorCB(o):(this.limitCompleteCount(),this.completeRequests[t]=e)},s=o=>{e._complete=1,e._responseData=o,e._downloadTime=pe()-i,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(o,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},n=()=>{e._finallyCB&&e._finallyCB()},u=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=lr(t,s,()=>r("error"),u),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally(n),this.activeRequests[t]=e,e._request.send(),this.lastPrefetchStart=pe()}_getParallelRequestCount(){return Math.min(this.MAX_PARALLEL_REQUESTS,this.averageSegmentDuration<3e3?3:2)}_getPrefetchDelay(){return Math.max(100,Math.min(5e3,this.averageSegmentDuration/3))}_canSendPending(){let e=this._getParallelRequestCount(),t=pe();if(Object.keys(this.activeRequests).length>=e)return!1;let i=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),i>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),i),!1):!0}_sendPending(){for(;this._canSendPending();){let e=this.pendingQueue.pop();if(e){if(this.activeRequests[e]||this.completeRequests[e])continue;this.logger(`Submitting pending request url=${e}`),this._sendRequest({},e)}else return}}_removeFromActive(e){delete this.completeRequests[e],delete this.activeRequests[e]}abortAll(){(0,NS.default)(this.activeRequests).forEach(e=>{e&&e._request&&e._request.abort()}),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,i,r){let s={};return s.send=()=>{let n=this.activeRequests[e]||this.completeRequests[e];if(n)n._cb=t,n._errorCB=i,n._retryCB=r,n._finallyCB=s._finallyCB,n._error||n._complete?(this._removeFromActive(e),setTimeout(()=>{n._complete?(this.logger(`Requested url already prefetched, url=${e}`),t(n._responseData,n._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${e}`),i(n._errorMsg)),s._finallyCB&&s._finallyCB()},0)):this.logger(`Attached to active request, url=${e}`);else{let u=this.pendingQueue.indexOf(e);u!==-1&&this.pendingQueue.splice(u,1),this.logger(`Request not prefetched, starting new request, url=${e}${u===-1?"":"; removed pending"}`),this._sendRequest(s,e)}},s._cb=t,s._errorCB=i,s._retryCB=r,s.abort=function(){s.request&&s.request.abort()},s.withFinally=n=>(s._finallyCB=n,s),s}prefetch(e){this.activeRequests[e]||this.completeRequests[e]?this.logger(`Request already active for url=${e}`):(this.logger(`Added to pending queue; url=${e}`),this.pendingQueue.unshift(e),this._sendPending())}optimizeForSegDuration(e){this.averageSegmentDuration=e}};import{Subject as P$}from"@vkontakte/videoplayer-shared/es2024";var Hn=1e4,nc=3;var k$=6e4,R$=10,L$=1,$$=500,ya=class{constructor(e){this.paused=!1;this.autoQuality=!0;this.autoQualityLimits=void 0;this.buffering=!0;this.destroyed=!1;this.videoPlayStarted=!1;this.lowLatency=!1;this.bitrate=0;this.manifest=[];this.sourceBuffer=0;this.bufferStates=[];this.sourceJitter=-1;this.waitingForFirstBufferAfterSrcChange=!1;this.params=e,this.soundProhibitedEvent$=new P$,this.chunkRateEstimator=new ga(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=sc(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setAutoQualityLimits(e){this.autoQualityLimits=e}switchByName(e){let t;for(let i=0;i<this.manifest.length;++i)if(t=this.manifest[i],t.name===e){this._switchToQuality(t);return}}catchUp(){if(this.rep&&this.rep.stop(),this.currentManifestEntry){let e=this.params.playbackState.getState();this.paused=e==="paused",this._initPlayerWith(this.currentManifestEntry),this._notifyBuffering(!0)}}stop(){this.params.videoElement.pause(),this.rep&&(this.rep.stop(),this.rep=null)}pause(){this.paused=!0,this.params.videoElement.pause(),this.videoPlayStarted=!1,this._notifyBuffering(!1)}play(){this.paused=!1;let e=this.lowLatency&&this._getBufferSizeSec()>this.sourceJitter+5;this.rep&&!e?(this.bufferStates=[],this.videoPlayStarted=!1,this.shouldPlay()?this._playVideoElement():this._notifyBuffering(!0)):this.catchUp()}startPlay(e,t){this.autoQuality=t,this._initPlayerWith(e)}destroy(){this.destroyed=!0,this.rep&&(this.rep.stop(),this.rep=null),this.manifestRequest&&this.manifestRequest.abort(),this.manifestRefetchTimer&&(clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=void 0)}reinit(e){this.manifestUrl=e,this.urlResolver=sc(e),this.catchUp()}_handleNetworkError(){this.params.logger("Fatal network error"),this.params.playerCallback({name:"error",type:"network"})}_retryCallback(){this.params.playerCallback({name:"retry"})}_getBufferSizeSec(){let e=this.params.videoElement,t=0,i=e.buffered.length;return i!==0&&(t=e.buffered.end(i-1)-Math.max(e.currentTime,e.buffered.start(0))),t}_notifyBuffering(e){this.destroyed||(this.params.logger(`buffering: ${e}`),this.params.playerCallback({name:"buffering",isBuffering:e}),this.buffering=e)}_initVideo(){let{videoElement:e,logger:t}=this.params;e.addEventListener("error",()=>{!!e.error&&!this.destroyed&&(t(`Video element error: ${e.error?.code}, details: ${e.error?.message}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{let i=this._getBufferSizeSec();!this.paused&&i<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(i+.1)*1e3)):this.buffering&&this.videoPlayStarted&&this._notifyBuffering(!1)}),e.addEventListener("playing",()=>{t("playing")}),e.addEventListener("stalled",()=>this._fixupStall()),e.addEventListener("waiting",()=>this._fixupStall())}_fixupStall(){let{logger:e,videoElement:t}=this.params,i=t.buffered.length,r;i!==0&&!this.waitingForFirstBufferAfterSrcChange&&(r=t.buffered.start(i-1),t.currentTime<r&&(e("Fixup stall"),t.currentTime=r))}_selectQuality(e){let{videoElement:t}=this.params,i,r,s,n=t&&1.62*(B.display.pixelRatio||1)*t.offsetHeight||520;for(let u=0;u<this.manifest.length;++u){s=this.manifest[u];let{max:o,min:l}=this.autoQualityLimits||{};!wS({limits:this.autoQualityLimits,highestAvailableHeight:this.manifest[0].video.height,lowestAvailableHeight:(0,qS.default)(this.manifest,-1).video.height})&&(o&&s.video.height>o||l&&s.video.height<l)||(s.bitrate<e&&n>Math.min(s.video.height,s.video.width)?(!r||s.bitrate>r.bitrate)&&(r=s):(!i||i.bitrate>s.bitrate)&&(i=s))}return r||i}shouldPlay(){if(this.paused)return!1;let t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||Un(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){let{logger:i,videoElement:r,playerCallback:s}=this.params;this.mediaSource=new window.MediaSource,i("setting video src"),r.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.videoPlayStarted=!1,r.addEventListener("canplay",()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});let n=()=>{FS(r,"progress",()=>{r.buffered.length?(r.currentTime=r.buffered.start(0),this.waitingForFirstBufferAfterSrcChange=!1,s({name:"playing"})):n()})};this.waitingForFirstBufferAfterSrcChange=!0,n()}_initPlayerWith(e){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new Sa(nc,Hn,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){let{logger:t,videoElement:i,playerCallback:r}=this.params,s=!1,n=null,u=null,o=null,l=null,c=!1,p=()=>{let y=s&&(!c||c===this.rep);return y||t("Not running!"),y},d=(y,w,D)=>{o&&o.abort(),o=lr(this.urlResolver.resolve(y,!1),w,D,()=>this._retryCallback()).withTimeout(Hn).withBitrateReporting(this.bitrateSwitcher).withRetryCount(nc).withFinally(()=>{o=null}).send()},h=(y,w,D)=>{va(this.filesFetcher),u?.abort(),u=this.filesFetcher.requestData(this.urlResolver.resolve(y,!1),w,D,()=>this._retryCallback()).withFinally(()=>{u=null}).send()},f=y=>{let w=i.playbackRate;i.playbackRate!==y&&(t(`Playback rate switch: ${w}=>${y}`),i.playbackRate=y)},b=y=>{this.lowLatency=y,t(`lowLatency changed to ${y}`),S()},S=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)f(1);else{let y=this._getBufferSizeSec();if(this.bufferStates.length<5){f(1);return}let D=pe()-1e4,L=0;for(let R=0;R<this.bufferStates.length;R++){let T=this.bufferStates[R];y=Math.min(y,T.buf),T.ts<D&&L++}this.bufferStates.splice(0,L),t(`update playback rate; minBuffer=${y} drop=${L} jitter=${this.sourceJitter}`);let A=y-L$;this.sourceJitter>=0?A-=this.sourceJitter/2:this.sourceJitter-=1,A>3?f(1.15):A>1?f(1.1):A>.3?f(1.05):f(1)}},g=y=>{let w,D=()=>w&&w.start?w.start.length:0,L=M=>w.start[M]/1e3,A=M=>w.dur[M]/1e3,R=M=>w.fragIndex+M,T=(M,H)=>({chunkIdx:R(M),startTS:L(M),dur:A(M),discontinuity:H}),q=()=>{let M=0;if(w&&w.dur){let H=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,J=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,ie=H;this.sourceJitter>1&&(ie+=this.sourceJitter-1);let ue=w.dur.length-1;for(;ue>=0&&(ie-=w.dur[ue],!(ie<=0));--ue);M=Math.min(ue,w.dur.length-1-J),M=Math.max(M,0)}return T(M,!0)},$=M=>{let H=D();if(!(H<=0)){if(Un(M)){for(let J=0;J<H;J++)if(L(J)>M)return T(J)}return q()}},v=M=>{let H=D(),J=M?M.chunkIdx+1:0,ie=J-w.fragIndex;if(!(H<=0)){if(!M||ie<0||ie-H>R$)return t(`Resync: offset=${ie} bChunks=${H} chunk=`+JSON.stringify(M)),q();if(!(ie>=H))return T(J-w.fragIndex,!1)}},E=(M,H,J)=>{l&&l.abort(),l=lr(this.urlResolver.resolve(M,!0,this.lowLatency),H,J,()=>this._retryCallback()).withTimeout(Hn).withRetryCount(nc).withFinally(()=>{l=null}).withJSONResponse().send()};return{seek:(M,H)=>{E(y,J=>{if(!p())return;w=J;let ie=!!w.lowLatency;ie!==this.lowLatency&&b(ie);let ue=0;for(let fe=0;fe<w.dur.length;++fe)ue+=w.dur[fe];ue>0&&(va(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(ue/w.dur.length)),r({name:"index",zeroTime:w.zeroTime,shiftDuration:w.shiftDuration}),this.sourceJitter=w.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,w.jitter/1e3)):1,M($(H))},()=>this._handleNetworkError())},nextChunk:v}},I=()=>{s=!1,u&&u.abort(),o&&o.abort(),l&&l.abort(),va(this.filesFetcher),this.filesFetcher.abortAll()};return c={start:y=>{let{videoElement:w,logger:D}=this.params,L=g(e.jidxUrl),A,R,T,q,$=0,v,E,z,M=()=>{v&&(clearTimeout(v),v=void 0);let U=Math.max($$,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),ke=$+U,Te=pe(),le=Math.min(1e4,ke-Te);$=Te;let We=()=>{l||p()&&L.seek(()=>{p()&&($=pe(),H(),M())})};le>0?v=window.setTimeout(()=>{this.paused?M():We()},le):We()},H=()=>{let U;for(;U=L.nextChunk(q);)q=U,me(U);let ke=L.nextChunk(T);if(ke){if(T&&ke.discontinuity){D("Detected discontinuity; restarting playback"),this.paused?M():(I(),this._initPlayerWith(e));return}fe(ke)}else M()},J=(U,ke)=>{if(!p()||!this.sourceBuffer)return;let Te,le,We,Bt=lt=>{window.setTimeout(()=>{p()&&J(U,ke)},lt)};if(this.sourceBuffer.updating)D("Source buffer is updating; delaying appendBuffer"),Bt(100);else{let lt=pe(),Oe=w.currentTime;!this.paused&&w.buffered.length>1&&E===Oe&&lt-z>500&&(D("Stall suspected; trying to fix"),this._fixupStall()),E!==Oe&&(E=Oe,z=lt);let Vt=this._getBufferSizeSec();if(Vt>30)D(`Buffered ${Vt} seconds; delaying appendBuffer`),Bt(2e3);else try{this.sourceBuffer.appendBuffer(U),this.videoPlayStarted?(this.bufferStates.push({ts:lt,buf:Vt}),S(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),ke&&ke()}catch(ct){if(ct.name==="QuotaExceededError")D("QuotaExceededError; delaying appendBuffer"),We=this.sourceBuffer.buffered.length,We!==0&&(Te=this.sourceBuffer.buffered.start(0),le=Oe,le-Te>4&&this.sourceBuffer.remove(Te,le-3)),Bt(1e3);else throw ct}}},ie=()=>{R&&A&&(D([`Appending chunk, sz=${R.byteLength}:`,JSON.stringify(T)]),J(R,function(){R=null,H()}))},ue=U=>e.fragUrlTemplate.replace("%%id%%",U.chunkIdx),fe=U=>{p()&&h(ue(U),(ke,Te)=>{if(p()){if(Te/=1e3,R=ke,T=U,n=U.startTS,Te){let le=Math.min(10,U.dur/Te);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*le:le}ie()}},()=>this._handleNetworkError())},me=U=>{p()&&(va(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(ue(U),!1)))},j=U=>{p()&&(e.cachedHeader=U,J(U,()=>{A=!0,ie()}))};s=!0,L.seek(U=>{if(p()){if($=pe(),!U){M();return}q=U,!A$(y)||U.startTS>y?fe(U):(T=U,H())}},y),e.cachedHeader?j(e.cachedHeader):d(e.headerUrl,j,()=>this._handleNetworkError())},stop:I,getTimestampSec:()=>n},c}_switchToQuality(e){let{logger:t,playerCallback:i}=this.params,r;e.bitrate!==this.bitrate&&(this.rep&&(r=this.rep.getTimestampSec(),Un(r)&&(r+=.1),this.rep.stop()),this.currentManifestEntry=e,this.rep=this._representation(e),t(`switch to quality: codecs=${e.codecs}; headerUrl=${e.headerUrl}; bitrate=${e.bitrate}`),this.bitrate=e.bitrate,va(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(r),i({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return Un(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,i=p=>{if(!this.autoQuality)return;let d,h,f;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&p<this.bitrate&&(h=this._getBufferSizeSec(),f=p/this.bitrate,h>10&&f>.8||h>15&&f>.5||h>20&&f>.3)){e(`Not switching: buffer=${Math.floor(h)}; bitrate=${this.bitrate}; newRate=${Math.floor(p)}`);return}d=this._selectQuality(p),d?this._switchToQuality(d):e(`Could not find quality by bitrate ${p}`)},s={updateChunk:(d,h)=>{let f=pe();if(this.chunkRateEstimator.addInterval(d,f,h)){let S=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:h,duration:f-d,speed:S}),!0}},get:()=>{let d=this.chunkRateEstimator.getBitRate();return d?d*.85:0}},n=-1/0,u,o=!0,l=()=>{let p=s.get();if(p&&u&&this.autoQuality){if(o&&p>u&&ac(n)<3e4)return;i(p)}o=this.autoQuality};return{updateChunk:(p,d)=>{let h=s.updateChunk(p,d);return h&&l(),h},notifySwitch:p=>{let d=pe();p<u&&(n=d),u=p}}}_fetchManifest(e,t,i){this.manifestRequest=lr(this.urlResolver.resolve(e,!0),t,i,()=>this._retryCallback()).withJSONResponse().withTimeout(Hn).withRetryCount(this.params.config.manifestRetryMaxCount).withRetryInterval(this.params.config.manifestRetryInterval,this.params.config.manifestRetryMaxInterval).send().withFinally(()=>{this.manifestRequest=void 0})}_playVideoElement(){let{videoElement:e}=this.params;Be(e,()=>{this.soundProhibitedEvent$.next()}).then(t=>{t||(this.params.liveOffset.pause(),this.params.videoState.setState("paused"))})}_handleManifestUpdate(e){let{logger:t,playerCallback:i,videoElement:r}=this.params,s=n=>{let u=[];return n?.length?(n.forEach((o,l)=>{o.video&&r.canPlayType(o.codecs).replace(/no/,"")&&window.MediaSource?.isTypeSupported?.(o.codecs)&&(o.index=l,u.push(o))}),u.sort(function(o,l){return o.video&&l.video?l.video.height-o.video.height:l.bitrate-o.bitrate}),u):(i({name:"error",type:"empty_manifest"}),[])};this.manifest=s(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),i({name:"manifest",manifest:this.manifest})}_refetchManifest(e){this.destroyed||(this.manifestRefetchTimer&&clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=window.setTimeout(()=>{this._fetchManifest(e,t=>{this.destroyed||(this._handleManifestUpdate(t),this._refetchManifest(e))},()=>this._refetchManifest(e))},k$))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};var jS=C(Wi(),1);import{debounce as M$,filter as US,fromEvent as D$,interval as C$,isHigher as B$,isInvariantQuality as V$,isLower as _$,merge as O$,Subject as HS,Subscription as F$}from"@vkontakte/videoplayer-shared/es2024";var oc=class{constructor(){this.onDroopedVideoFramesLimit$=new HS;this.subscription=new F$;this.playing=!1;this.tracks=[];this.forceChecker$=new HS;this.isForceCheckCounter=0;this.prevTotalVideoFrames=0;this.prevDroppedVideoFrames=0;this.limitCounts={};this.handleChangeVideoQuality=()=>{let e=this.tracks.find(({size:t})=>t?.height===this.video.videoHeight&&t?.width===this.video.videoWidth);e&&!V$(e.quality)&&this.onChangeQuality(e.quality)};this.checkDroppedFrames=()=>{let{totalVideoFrames:e,droppedVideoFrames:t}=this.video.getVideoPlaybackQuality(),i=e-this.prevTotalVideoFrames,r=t-this.prevDroppedVideoFrames,s=1-(i-r)/i;!isNaN(s)&&s>0&&this.log({message:`[dropped]. current dropped percent: ${s}, limit: ${this.droppedFramesChecker.percentLimit}`}),!isNaN(s)&&s>=this.droppedFramesChecker.percentLimit&&B$(this.currentQuality,this.droppedFramesChecker.minQualityBanLimit)&&(this.limitCounts[this.currentQuality]=(this.limitCounts[this.currentQuality]??0)+1,this.maxQualityLimit=this.getMaxQualityLimit(this.currentQuality),this.currentTimer&&window.clearTimeout(this.currentTimer),this.currentTimer=window.setTimeout(()=>this.maxQualityLimit=this.getMaxQualityLimit(),this.droppedFramesChecker.qualityUpWaitingTime),this.onDroopedVideoFramesLimitTrigger()),this.savePrevFrameCounts(e,t)}}connect(e){this.log=e.logger.createComponentLog("DroppedFramesManager"),this.video=e.video,this.isAuto=e.isAuto,this.tracks=e.tracks,this.droppedFramesChecker=e.droppedFramesChecker,this.subscription.add(e.playing$.subscribe(()=>this.playing=!0)),this.subscription.add(e.pause$.subscribe(()=>this.playing=!1)),this.isEnabled&&this.subscribe()}destroy(){this.currentTimer&&window.clearTimeout(this.currentTimer),this.subscription.unsubscribe()}get droppedVideoMaxQualityLimit(){return this.maxQualityLimit}subscribe(){this.subscription.add(D$(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=C$(this.droppedFramesChecker.checkTime).pipe(US(()=>this.playing),US(()=>{let r=!!this.isForceCheckCounter;return r&&(this.isForceCheckCounter-=1),!r})),t=this.forceChecker$.pipe(M$(this.droppedFramesChecker.checkTime)),i=O$(e,t);this.subscription.add(i.subscribe(this.checkDroppedFrames))}onChangeQuality(e){this.currentQuality=e;let{totalVideoFrames:t,droppedVideoFrames:i}=this.video.getVideoPlaybackQuality();this.savePrevFrameCounts(t,i),this.isForceCheckCounter=this.droppedFramesChecker.tickCountAfterQualityChange,this.forceChecker$.next()}onDroopedVideoFramesLimitTrigger(){this.isAuto.getState()&&(this.log({message:`[onDroopedVideoFramesLimit]. maxQualityLimit: ${this.maxQualityLimit}`}),this.onDroopedVideoFramesLimit$.next())}getMaxQualityLimit(e){let t=(0,jS.default)(this.limitCounts).filter(([,i])=>i>=this.droppedFramesChecker.countLimit).sort(([i],[r])=>_$(i,r)?-1:1)?.[0]?.[0];return e??t}get isEnabled(){return this.droppedFramesChecker.enabled&&this.isDroppedFramesCheckerSupport}get isDroppedFramesCheckerSupport(){return!!this.video&&typeof this.video.getVideoPlaybackQuality=="function"}savePrevFrameCounts(e,t){this.prevTotalVideoFrames=e,this.prevDroppedVideoFrames=t}},cr=oc;import{map as N$,Observable as q$}from"@vkontakte/videoplayer-shared/es2024";import{fromEvent as U$}from"@vkontakte/videoplayer-shared/es2024";var Ta=()=>!!window.documentPictureInPicture?.window||!!document.pictureInPictureElement;var H$=(a,e)=>new q$(t=>{if(!window.IntersectionObserver)return;let i={root:null},r=new IntersectionObserver((n,u)=>{n.forEach(o=>t.next(o.isIntersecting||Ta()))},{...i,...e});r.observe(a);let s=U$(document,"visibilitychange").pipe(N$(n=>!document.hidden||Ta())).subscribe(n=>t.next(n));return()=>{r.unobserve(a),s.unsubscribe()}}),Ke=H$;var X$=["paused","playing","ready"],J$=["paused","playing","ready"],Ia=class{constructor(e){this.subscription=new Y$;this.videoState=new F("stopped");this.representations$=new lc([]);this.droppedFramesManager=new cr;this.maxSeekBackTime$=new lc(1/0);this.zeroTime$=new lc(void 0);this.liveOffset=new Si;this._dashCb=e=>{switch(e.name){case"buffering":{let t=e.isBuffering;this.params.output.isBuffering$.next(t);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${e.type}`,category:GS.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{let t=e.manifest,i=[];for(let r of t){let s=r.name??r.index.toString(10),n=jt(r.name)??K$(r.video),u=r.bitrate/1e3,o={...r.video};if(!n)continue;let l={id:s,quality:n,bitrate:u,size:o};i.push({track:l,representation:r})}this.representations$.next(i),this.params.output.availableVideoTracks$.next(i.map(({track:r})=>r)),this.videoState.getTransition()?.to==="manifest_ready"&&this.videoState.setState("manifest_ready");break}case"qualitySwitch":{let t=e.quality,i=this.representations$.getValue().find(({representation:r})=>r===t)?.track;this.params.output.hostname$.next(new URL(t.headerUrl,this.params.source.url).hostname),uc(i)&&this.params.output.currentVideoTrack$.next(i);break}case"bandwidth":{let{size:t,duration:i}=e;this.params.dependencies.throughputEstimator.addRawSpeed(t,i);break}case"index":{this.maxSeekBackTime$.next(e.shiftDuration||0),this.zeroTime$.next(e.zeroTime);break}}};this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; seekState: ${JSON.stringify(s)};`}),i==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState("stopped"));return}if(t)return;let n=this.params.desiredState.videoTrack.getTransition(),u=this.params.desiredState.autoVideoTrackSwitching.getTransition();if((0,cc.default)(J$,e)&&(n||u)){this.prepare();return}if(r?.to!=="paused"&&s.state==="requested"&&(0,cc.default)(X$,e)){this.seek(s.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(se(this.params.source.url));return;case"manifest_ready":this.videoState.startTransitionTo("ready"),this.prepare();break;case"ready":if(i==="paused")this.videoState.setState("paused");else if(i==="playing"){this.videoState.startTransitionTo("playing");let o=r?.from;o&&o==="ready"&&this.dash.catchUp(),this.dash.play()}return;case"playing":i==="paused"&&(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.dash.pause());return;case"paused":if(i==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.dash.play(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let o=this.liveOffset.getTotalOffset();o>=this.maxSeekBackTime$.getValue()&&(o=0,this.liveOffset.resetTo(o)),this.liveOffset.resume(),this.params.output.position$.next(-o/1e3),this.dash.reinit(se(this.params.source.url,o))}return;default:return QS(e)}};this.textTracksManager=new Ye(e.source.url),this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=r=>{e.output.error$.next({id:"DashLiveProvider",category:GS.WTF,message:"DashLiveProvider internal logic error",thrown:r})};this.subscription.add(YS(this.videoState.stateChangeStarted$.pipe(jn(r=>({transition:r,type:"start"}))),this.videoState.stateChangeEnded$.pipe(jn(r=>({transition:r,type:"end"})))).subscribe(({transition:r,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(r)}`})})),this.video=$e(e.container,e.tuning),this.params.output.element$.next(this.video),this.dash=this.createLiveDashPlayer(),this.subscription.add(this.dash.soundProhibitedEvent$.subscribe(this.params.output.soundProhibitedEvent$)),this.params.output.duration$.next(1/0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(ge(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);let i=Ce(this.video);this.subscription.add(()=>i.destroy()),this.subscription.add(this.representations$.pipe(jn(r=>r.map(({track:s})=>s)),zS(r=>!!r.length),z$()).subscribe(r=>this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks:r}))),this.subscription.add(i.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready")},t)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused")},t)).add(i.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.videoState.setState("playing")},t)).add(i.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(W$(),jn(r=>-r/1e3)).subscribe(this.params.output.duration$)).add(j$({zeroTime:this.zeroTime$.pipe(zS(uc)),position:i.timeUpdate$}).subscribe(({zeroTime:r,position:s})=>this.params.output.liveTime$.next(r+s*1e3),t)).add(mt(this.video,this.params.desiredState.isLooped,t)).add(De(this.video,this.params.desiredState.volume,i.volumeState$,t)).add(i.volumeState$.subscribe(this.params.output.volume$,t)).add(ze(this.video,this.params.desiredState.playbackRate,i.playbackRateState$,t)).add(i.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(i.loadedMetadata$.subscribe(this.params.output.loadedMetadataEvent$)).add(i.playing$.subscribe(this.params.output.firstFrameEvent$)).add(i.canplay$.subscribe(this.params.output.canplay$)).add(i.inPiP$.subscribe(this.params.output.inPiP$)).add(i.inFullscreen$.subscribe(this.params.output.inFullscreen$)).add(Ke(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:r,min:s}})=>{this.dash.setAutoQualityLimits({max:r&&KS(r),min:s&&KS(s)}),this.params.output.autoVideoTrackLimits$.next({max:r,min:s})})).add(this.videoState.stateChangeEnded$.subscribe(r=>{switch(r.to){case"stopped":this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState("stopped");break;case"manifest_ready":case"ready":this.params.desiredState.playbackState.getTransition()?.to==="ready"&&this.params.desiredState.playbackState.setState("ready");break;case"paused":this.params.desiredState.playbackState.setState("paused");break;case"playing":this.params.desiredState.playbackState.setState("playing");break;default:return QS(r.to)}},t)).add(YS(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,G$(["init"])).pipe(Q$(0)).subscribe(this.syncPlayback,t))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.droppedFramesManager.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),Me(this.video)}createLiveDashPlayer(){let e=new ya({videoElement:this.video,videoState:this.videoState,playbackState:this.params.desiredState.playbackState,liveOffset:this.liveOffset,config:{maxParallelRequests:this.params.config.maxParallelRequests,minBuffer:this.params.tuning.live.minBuffer,minBufferSegments:this.params.tuning.live.minBufferSegments,lowLatencyMinBuffer:this.params.tuning.live.lowLatencyMinBuffer,lowLatencyMinBufferSegments:this.params.tuning.live.lowLatencyMinBufferSegments,isLiveCatchUpMode:this.params.tuning.live.isLiveCatchUpMode,manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},playerCallback:this._dashCb,logger:t=>{this.params.dependencies.logger.log({message:String(t),component:"LiveDashPlayer"})}});return e.pause(),e}prepare(){let e=this.representations$.getValue(),t=this.params.desiredState.videoTrack.getTransition()?.to??this.params.desiredState.videoTrack.getState(),i=this.params.desiredState.autoVideoTrackSwitching.getTransition()?.to??this.params.desiredState.autoVideoTrackSwitching.getState(),r=!i&&uc(t)?t:St(e.map(({track:l})=>l),{container:this.video.getBoundingClientRect(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),s=r?.id,n=this.params.desiredState.videoTrack.getTransition(),u=this.params.desiredState.videoTrack.getState()?.id,o=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(r&&(n||s!==u)&&this.setVideoTrack(r),o&&this.setAutoQuality(i),n||o||s!==u){let l=e.find(({track:c})=>c.id===s)?.representation;WS(l,"Representations missing"),this.dash.startPlay(l,i)}}setVideoTrack(e){let t=this.representations$.getValue().find(({track:i})=>i.id===e.id)?.representation;WS(t,`No such representation ${e.id}`),this.dash.switchByName(t.name),this.params.desiredState.videoTrack.setState(e)}setAutoQuality(e){this.dash.setAutoQualityEnabled(e),this.params.desiredState.autoVideoTrackSwitching.setState(e)}seek(e){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),i=this.videoState.getState(),r=t==="paused"&&i==="paused",s=-e,n=s<=this.maxSeekBackTime$.getValue()?s:0;this.params.output.position$.next(e/1e3),this.dash.reinit(se(this.params.source.url,n)),r&&this.dash.pause(),this.liveOffset.resetTo(n,r)}};var XS=Ia;var gT=C(Ee(),1);var he=(a,e)=>{let t=0;for(let i=0;i<a.length;i++){let r=a.start(i)*1e3,s=a.end(i)*1e3;r<=e&&e<=s&&(t=s)}return Math.max(t-e,0)};import{assertNever as UC,assertNonNullable as HC,debounce as jC,ErrorCategory as fT,filter as Gc,filterChanged as yo,fromEvent as QC,isNonNullable as mT,isNullable as WC,map as zc,merge as To,observableFrom as Yc,once as bT,Subscription as GC}from"@vkontakte/videoplayer-shared/es2024";var{NativeAbortSignal:AU,NativeAbortController:PU}=function(a){return{NativeAbortSignal:a.AbortSignal,NativeAbortController:a.AbortController}}(typeof self<"u"?self:global);function JS(a){let e;try{e=new Event("abort")}catch{typeof document<"u"?document.createEvent?(e=document.createEvent("Event"),e.initEvent("abort",!1,!1)):(e=document.createEventObject(),e.type="abort"):e={type:"abort",bubbles:!1,cancelable:!1}}return e.reason=a,e}function ZS(a){if(a===void 0)if(typeof document>"u")a=new Error("This operation was aborted"),a.name="AbortError";else try{a=new DOMException("signal is aborted without reason"),Object.defineProperty(a,"name",{value:"AbortError"})}catch{a=new Error("This operation was aborted"),a.name="AbortError"}return a}var Qn=class{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,i){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:i})}removeEventListener(e,t){if(!(e in this.listeners))return;let i=this.listeners[e];for(let r=0,s=i.length;r<s;r++)if(i[r].callback===t){i.splice(r,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;let i=this.listeners[e.type].slice();for(let r=0,s=i.length;r<s;r++){let n=i[r];try{n.callback.call(this,e)}catch(u){Promise.resolve().then(()=>{throw u})}n.options&&n.options.once&&this.removeEventListener(e.type,n.callback)}return!e.defaultPrevented}},dr=class extends Qn{constructor(){super(),this.listeners||Qn.call(this),Object.defineProperty(this,"aborted",{value:!1,writable:!0,configurable:!0}),Object.defineProperty(this,"onabort",{value:null,writable:!0,configurable:!0}),Object.defineProperty(this,"reason",{value:void 0,writable:!0,configurable:!0})}toString(){return"[object AbortSignal]"}dispatchEvent(e){e.type==="abort"&&(this.aborted=!0,typeof this.onabort=="function"&&this.onabort.call(this,e)),super.dispatchEvent(e)}throwIfAborted(){let{aborted:e,reason:t="Aborted"}=this;if(e)throw t}static timeout(e){let t=new yi;return setTimeout(()=>t.abort(new DOMException(`This signal is timeout in ${e}ms`,"TimeoutError")),e),t.signal}static any(e){let t=new yi;function i(){t.abort(this.reason),r()}function r(){for(let s of e)s.removeEventListener("abort",i)}for(let s of e)if(s.aborted){t.abort(s.reason);break}else s.addEventListener("abort",i);return t.signal}},yi=class{constructor(){Object.defineProperty(this,"signal",{value:new dr,writable:!0,configurable:!0})}abort(e){let t=ZS(e),i=JS(t);this.signal.reason=t,this.signal.dispatchEvent(i)}toString(){return"[object AbortController]"}};typeof Symbol<"u"&&Symbol.toStringTag&&(yi.prototype[Symbol.toStringTag]="AbortController",dr.prototype[Symbol.toStringTag]="AbortSignal");function Wn(a){return a.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof a.Request=="function"&&!a.Request.prototype.hasOwnProperty("signal")||!a.AbortController}function dc(a){typeof a=="function"&&(a={fetch:a});let{fetch:e,Request:t=e.Request,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r=!1}=a;if(!Wn({fetch:e,Request:t,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r}))return{fetch:e,Request:s};let s=t;(s&&!s.prototype.hasOwnProperty("signal")||r)&&(s=function(l,c){let p;c&&c.signal&&(p=c.signal,delete c.signal);let d=new t(l,c);return p&&Object.defineProperty(d,"signal",{writable:!1,enumerable:!1,configurable:!0,value:p}),d},s.prototype=t.prototype);let n=e;return{fetch:(o,l)=>{let c=s&&s.prototype.isPrototypeOf(o)?o.signal:l?l.signal:void 0;if(c){let p;try{p=new DOMException("Aborted","AbortError")}catch{p=new Error("Aborted"),p.name="AbortError"}if(c.aborted)return Promise.reject(p);let d=new Promise((h,f)=>{c.addEventListener("abort",()=>f(p),{once:!0})});return l&&l.signal&&delete l.signal,Promise.race([d,n(o,l)])}return n(o,l)},Request:s}}var Z$=()=>"fetch"in window,Ea=Z$()&&Wn({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),ev=Ea?dc({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,Xe=Ea?ev.fetch:window.fetch,_U=Ea?ev.Request:window.Request,X=Ea?yi:window.AbortController,OU=Ea?dr:window.AbortSignal;var cT=C(Ee(),1),qc=C(xa(),1);var Nv=C(Fv(),1);import{ErrorCategory as Aa}from"@vkontakte/videoplayer-shared/es2024";var Gn=a=>{if(!a)return{id:"EmptyResponse",category:Aa.PARSER,message:"Empty response"};if(a.length<=2&&a.match(/^\d+$/))return{id:`UVError#${a}`,category:Aa.NETWORK,message:`UV Error ${a}`};let e=(0,Nv.default)(a).substring(0,100).toLowerCase();if(e.startsWith("<!doctype")||e.startsWith("<html>")||e.startsWith("<body>")||e.startsWith("<head>"))return{id:"UnexpectedHTML",category:Aa.NETWORK,message:"Received unexpected HTML, possibly a ISP block"};if(e.startsWith("<?xml"))return new DOMParser().parseFromString(a,"text/xml").querySelector("parsererror")?{id:"InvalidXML",category:Aa.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:Aa.PARSER,message:"Response is valid XML, but parser failed"}};var Se=(a,e,t=0)=>{for(let i=0;i<a.length;i++)if(a.start(i)*1e3-t<=e&&a.end(i)*1e3+t>e)return!0;return!1};import{abortable as Oc,assertNonNullable as Er,combine as xr,ErrorCategory as ot,filter as ho,filterChanged as as,flattenObject as ss,fromEvent as Dt,getTraceSubscriptionMethod as xC,interval as Fc,isNonNullable as ns,isNullable as oT,map as wr,merge as wi,now as Nc,Subject as Kt,Subscription as uT,tap as wC,throttle as AC,ValueSubject as ee}from"@vkontakte/videoplayer-shared/es2024";var Xn=C(Ee(),1),xi=C(at(),1),Jn=C(xa(),1);var OM=(a,e={})=>{let i=e.timeout||1,r=performance.now();return window.setTimeout(()=>{a({get didTimeout(){return e.timeout?!1:performance.now()-r-1>i},timeRemaining(){return Math.max(0,1+(performance.now()-r))}})},1)},FM=a=>window.clearTimeout(a),qv=a=>typeof a=="function"&&a?.toString().endsWith("{ [native code] }"),Uv=!qv(window.requestIdleCallback)||!qv(window.cancelIdleCallback),pr=Uv?OM:window.requestIdleCallback,vt=Uv?FM:window.cancelIdleCallback;var Zy=C(gn(),1);import{assertNever as NM,ErrorCategory as Hv,Subject as jv}from"@vkontakte/videoplayer-shared/es2024";var qM=18,Qv=!1;try{Qv=B.browser.isSafari&&!!B.browser.safariVersion&&B.browser.safariVersion<=qM}catch(a){console.error(a)}var gc=class{constructor(e){this.bufferFull$=new jv;this.error$=new jv;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:Hv.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)};Qv&&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:Hv.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:NM(t)}}},Wv=gc;var hr=a=>{let e=0;for(let t=0;t<a.length;t++)e+=a.end(t)-a.start(t);return e*1e3};import{abortable as Gt,assertNonNullable as Ve,ErrorCategory as Lt,fromEvent as $c,getExponentialDelay as Mc,isNonNullable as Sr,isNullable as ve,now as Kn,once as lC,Subject as cC,Subscription as dC,ValueSubject as Ei}from"@vkontakte/videoplayer-shared/es2024";var Gv=C(at(),1);var zn=a=>a.valid,Q=class{constructor(e,t){this.cursor=0;this.source=e,this.boxParser=t,this.children=[];let i=this.readUint32();this.type=this.readString(4),i===1&&(this.cursor+=8);let r=e.byteOffset+this.cursor,s;i===0?(this.size=void 0,this.valid=!1,s=void 0):i===1?(this.size=void 0,this.valid=!1,s=void 0):i>e.byteLength?(this.size=i,this.valid=!1,s=Math.min(i-this.cursor,e.byteLength-this.cursor)):(this.size=i,this.valid=!0,s=i-this.cursor),this.content=new DataView(e.buffer,r,s)}get id(){return this.type}scanForBoxes(e){return this.boxParser.parse(e)}readString(e,t="ascii"){let r=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,r}readUint8(){let e=this.source.getUint8(this.cursor);return this.cursor+=1,e}readUint16(){let e=this.source.getUint16(this.cursor);return this.cursor+=2,e}readUint32(){let e=this.source.getUint32(this.cursor);return this.cursor+=4,e}readUint64(){let e=this.source.getBigInt64(this.cursor);return this.cursor+=8,e}};var fr=class extends Q{};import{assertNever as UM}from"@vkontakte/videoplayer-shared/es2024";var Pa=class extends Q{constructor(e,t){if(super(e,t),!this.valid)return;let i=this.readString(16),r=new DataView(this.content.buffer,this.content.byteOffset+16,this.content.byteLength-16);this.userData=this.parseData(i,r)}parseData(e,t){switch(e){case"ondemandlivejson":{let i=new TextDecoder("ascii").decode(t),r=JSON.parse(i);return{received:r["t-in"],prepared:r["t-out"]}}default:UM(e)}}};var ka=class extends Q{constructor(e,t){if(super(e,t),!this.valid)return;this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let i=new DataView(this.content.buffer,this.content.byteOffset+8,this.content.byteLength-8);for(let r=0;r<i.byteLength;r+=4){let s=this.readString(4);this.compatibleBrands.push(s)}}};var Ra=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Z=class extends Q{constructor(e,t){if(super(e,t),!this.valid)return;let i=this.readUint32();this.version=i>>>24,this.flags=i&16777215,this.content=new DataView(this.content.buffer,this.content.byteOffset+4,this.content.byteLength-4)}};var La=class extends Z{constructor(e,t){super(e,t),this.valid&&(this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.timescale=this.readUint32(),this.duration=this.readUint32(),this.rate=this.readUint32(),this.volume=this.readUint16())}};var $a=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ma=class extends Q{constructor(e,t){super(e,t),this.data=this.content}};var Ti=class extends Z{get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e,t){if(super(e,t),!!this.valid){this.segments=[],this.referenceId=this.readUint32(),this.timescale=this.readUint32(),this.earliestPresentationTime32=this.readUint32(),this.firstOffset32=this.readUint32(),this.earliestPresentationTime64=0,this.firstOffset64=0,this.referenceCount=this.readUint32()&65535;for(let i=0;i<this.referenceCount;i++){let r=this.readUint32(),s=r>>>31,n=r<<1>>>1,u=this.readUint32();r=this.readUint32();let o=r>>>28,l=r<<3>>>3;this.segments.push({referenceType:s,referencedSize:n,subsegmentDuration:u,SAPType:o,SAPDeltaTime:l})}}}};var Da=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ca=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ba=class extends Z{constructor(e,t){if(super(e,t),!this.valid)return;switch(this.readUint8()){case 0:this.stereoMode=0;break;case 1:this.stereoMode=1;break;case 2:this.stereoMode=2;break;case 3:this.stereoMode=3;break;case 4:this.stereoMode=4;break}this.cursor+=1}};var Va=class extends Z{constructor(e,t){super(e,t),this.valid&&(this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32())}};var _a=class extends Z{constructor(e,t){super(e,t),this.valid&&(this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32())}};var Oa=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Fa=class extends Z{constructor(e,t){super(e,t),this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.trackId=this.readUint32(),this.cursor+=4,this.duration=this.readUint32(),this.cursor+=8,this.layer=this.readUint16(),this.alternateGroup=this.readUint16(),this.cursor+=2,this.cursor+=2,this.matrix=[[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()]],this.width=this.readUint32(),this.height=this.readUint32()}};var Na=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var qa=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ua=class extends Z{constructor(e,t){super(e,t),this.valid&&(this.sequenceNumber=this.readUint32())}};var Ha=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ja=class extends Z{constructor(e,t){super(e,t),this.trackId=this.readUint32(),this.flags&1&&(this.baseDataOffset=this.readUint64()),this.flags&2&&(this.sampleDescriptionIndex=this.readUint32()),this.flags&8&&(this.defaultSampleDuration=this.readUint32()),this.flags&16&&(this.defaultSampleSize=this.readUint32()),this.flags&32&&(this.defaultSampleFlags=this.readUint32())}};var Qa=class extends Z{constructor(t,i){super(t,i);this.baseMediaDecodeTime32=0;this.baseMediaDecodeTime64=BigInt(0);this.version===1?this.baseMediaDecodeTime64=this.readUint64():this.baseMediaDecodeTime32=this.readUint32()}get baseMediaDecodeTime(){return this.version===1?this.baseMediaDecodeTime64:this.baseMediaDecodeTime32}};var Wa=class extends Z{constructor(t,i){super(t,i);this.sampleDuration=[];this.sampleSize=[];this.sampleFlags=[];this.sampleCompositionTimeOffset=[];this.optionalFields=0;this.sampleCount=this.readUint32(),this.flags&1&&(this.dataOffset=this.readUint32()),this.flags&4&&(this.firstSampleFlags=this.readUint32());for(let r=0;r<this.sampleCount;r++)this.flags&256&&this.sampleDuration.push(this.readUint32()),this.flags&512&&this.sampleSize.push(this.readUint32()),this.flags&1024&&this.sampleFlags.push(this.readUint32()),this.flags&2048&&this.sampleCompositionTimeOffset.push(this.readUint32())}};var Ga=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var za=class extends Z{constructor(e,t){super(e,t),this.valid&&(this.entryCount=this.readUint32(),this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+4,this.content.byteLength-4)))}};var Ya=class extends Q{constructor(e,t){super(e,t),this.valid&&(this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+78,this.content.byteLength-78)))}};var jM={ftyp:ka,moov:Ra,mvhd:La,moof:$a,mdat:Ma,sidx:Ti,trak:Da,mdia:Oa,mfhd:Ua,tkhd:Fa,traf:Ha,tfhd:ja,tfdt:Qa,trun:Wa,minf:Na,sv3d:Ca,st3d:Ba,prhd:Va,proj:qa,equi:_a,uuid:Pa,stbl:Ga,stsd:za,avc1:Ya,unknown:fr},Rt=class a{constructor(e={}){this.options={offset:0,...e}}parse(e){let t=[],i=this.options.offset;for(;i<e.byteLength;){let s=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+i+4,4)),n;try{n=this.createBox(s,new DataView(e.buffer,e.byteOffset+i,e.byteLength-i))}catch(u){if(!(u instanceof RangeError))throw u}if(!n||!zn(n))break;t.push(n),i+=n.size}return t}createBox(e,t){let i=jM[e];return i?new i(t,new a):new fr(t,new a)}};var Wt=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{zn(t)&&(this.index[t.type]??=[],this.index[t.type].push(t),t.children.length>0&&this.indexBoxLevel(t.children))})}find(e){return this.index[e]&&this.index[e][0]?this.index[e][0]:null}findAll(e){return this.index[e]||[]}};var WM=new TextDecoder("ascii"),GM=a=>WM.decode(new DataView(a.buffer,a.byteOffset+4,4))==="ftyp",zM=a=>{let e=new Ti(a,new Rt),t=e.earliestPresentationTime/e.timescale*1e3,i=a.byteOffset+a.byteLength+e.firstOffset;return e.segments.map(s=>{if(s.referenceType!==0)throw new Error("Unsupported multilevel sidx");let n=s.subsegmentDuration/e.timescale*1e3,u={status:"none",time:{from:t,to:t+n},byte:{from:i,to:i+s.referencedSize-1}};return t+=n,i+=s.referencedSize,u})},YM=(a,e)=>{let i=new Rt().parse(a),r=new Wt(i),s=r.findAll("moof"),n=e?r.findAll("uuid"):r.findAll("mdat");if(!(n.length&&s.length))return null;let u=s[0],o=n[n.length-1],l=u.source.byteOffset,p=o.source.byteOffset-u.source.byteOffset+o.size;return new DataView(a.buffer,l,p)},KM=a=>{let t=new Rt().parse(a),i=new Wt(t),r={},s=i.findAll("uuid"),n=(0,Gv.default)(s,-1);return n?{serverDataReceivedTimestamp:n.userData.received,serverDataPreparedTime:n.userData.received}:r},XM=a=>{let t=new Rt().parse(a);return new Wt(t).find("sidx")?.timescale},JM=(a,e)=>{let i=new Rt().parse(a),s=new Wt(i).findAll("traf"),n=s[s.length-1].children.find(p=>p.type==="tfhd"),u=s[s.length-1].children.find(p=>p.type==="tfdt"),o=s[s.length-1].children.find(p=>p.type==="trun"),l=0;return o.sampleDuration.length?l=o.sampleDuration.reduce((p,d)=>p+d,0):l=n.defaultSampleDuration*o.sampleCount,(Number(u.baseMediaDecodeTime)+l)/e*1e3},ZM=a=>{let e={is3dVideo:!1,stereoMode:0,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}},i=new Rt().parse(a),r=new Wt(i);if(r.find("sv3d")){e.is3dVideo=!0;let n=r.find("st3d");n&&(e.stereoMode=n.stereoMode);let u=r.find("prhd");u&&(e.projectionData.pose.yaw=u.poseYawDegrees,e.projectionData.pose.pitch=u.posePitchDegrees,e.projectionData.pose.roll=u.poseRollDegrees);let o=r.find("equi");o&&(e.projectionData.bounds.top=o.projectionBoundsTop,e.projectionData.bounds.right=o.projectionBoundsRight,e.projectionData.bounds.bottom=o.projectionBoundsBottom,e.projectionData.bounds.left=o.projectionBoundsLeft)}return e},zv={validateData:GM,parseInit:ZM,getIndexRange:()=>{},parseSegments:zM,parseFeedableSegmentChunk:YM,getChunkEndTime:JM,getServerLatencyTimestamps:KM,getTimescaleFromIndex:XM};var Ja=C(Ee(),1);import{assertNonNullable as Sc,isNonNullable as Jv,isNullable as tD}from"@vkontakte/videoplayer-shared/es2024";import{assertNever as eD}from"@vkontakte/videoplayer-shared/es2024";var Yv={440786851:{type:"master"},17030:{type:"uint"},17143:{type:"uint"},17138:{type:"uint"},17139:{type:"uint"},17026:{type:"string"},17031:{type:"uint"},17029:{type:"uint"},236:{type:"binary"},408125543:{type:"master"},290298740:{type:"master"},19899:{type:"master"},21419:{type:"binary"},21420:{type:"uint"},357149030:{type:"master"},2807729:{type:"uint"},17545:{type:"float"},374648427:{type:"master"},174:{type:"master"},224:{type:"master"},30320:{type:"master"},30321:{type:"uint"},30322:{type:"master"},272869232:{type:"master"},524531317:{type:"master"},231:{type:"uint"},22612:{type:"master"},22743:{type:"uint"},167:{type:"uint"},171:{type:"uint"},163:{type:"binary"},160:{type:"master"},175:{type:"binary"},423732329:{type:"master"},307544935:{type:"master"},475249515:{type:"master"},187:{type:"master"},179:{type:"uint"},183:{type:"master"},247:{type:"uint"},241:{type:"uint"},240:{type:"uint"},178:{type:"uint"},21368:{type:"uint"},234:{type:"uint"},219:{type:"master"},150:{type:"uint"}},Kv=a=>{let e=a.getUint8(0),t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);let i=Xa(a,t),r=i in Yv,s=r?Yv[i].type:"binary",n=a.getUint8(t),u=0;n&128?u=1:n&64?u=2:n&32?u=3:n&16?u=4:n&8?u=5:n&4?u=6:n&2?u=7:n&1&&(u=8);let o=new DataView(a.buffer,a.byteOffset+t+1,u-1),l=n&255>>u,c=Xa(o),p=l*2**((u-1)*8)+c,d=t+u,h;return d+p>a.byteLength?h=new DataView(a.buffer,a.byteOffset+d):h=new DataView(a.buffer,a.byteOffset+d,p),{tag:r?i:"0x"+i.toString(16).toUpperCase(),type:s,tagHeaderSize:d,tagSize:d+p,value:h,valueSize:p}},Xa=(a,e=a.byteLength)=>{switch(e){case 1:return a.getUint8(0);case 2:return a.getUint16(0);case 3:return a.getUint8(0)*2**16+a.getUint16(1);case 4:return a.getUint32(0);case 5:return a.getUint8(0)*2**32+a.getUint32(1);case 6:return a.getUint16(0)*2**32+a.getUint32(2);case 7:{let t=a.getUint8(0)*281474976710656+a.getUint16(1)*4294967296+a.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},st=(a,e)=>{switch(e){case"int":return a.getInt8(0);case"uint":return Xa(a);case"float":return a.byteLength===4?a.getFloat32(0):a.getFloat64(0);case"string":return new TextDecoder("ascii").decode(a);case"utf8":return new TextDecoder("utf-8").decode(a);case"date":return new Date(Date.UTC(2001,0)+a.getInt8(0)).getTime();case"master":return a;case"binary":return a;default:eD(e)}},Ii=(a,e)=>{let t=0;for(;t<a.byteLength;){let i=new DataView(a.buffer,a.byteOffset+t),r=Kv(i);if(!e(r))return;r.type==="master"&&Ii(r.value,e),t=r.value.byteOffset-a.byteOffset+r.valueSize}},Xv=a=>{if(a.getUint32(0)!==440786851)return!1;let e,t,i,r=Kv(a);return Ii(r.value,({tag:s,type:n,value:u})=>(s===17143?e=st(u,n):s===17026?t=st(u,n):s===17029&&(i=st(u,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)};var Zv=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],iD=[231,22612,22743,167,171,163,160,175],rD=a=>{let e,t,i,r,s=!1,n=!1,u=!1,o,l,c=!1,p=0;return Ii(a,({tag:d,type:h,value:f,valueSize:b})=>{if(d===21419){let S=st(f,h);l=Xa(S)}else d!==21420&&(l=void 0);return d===408125543?(e=f.byteOffset,t=f.byteOffset+b):d===357149030?s=!0:d===290298740?n=!0:d===2807729?i=st(f,h):d===17545?r=st(f,h):d===21420&&l===475249515?o=st(f,h):d===374648427?Ii(f,({tag:S,type:g,value:I})=>S===30321?(c=st(I,g)===1,!1):!0):s&&n&&(0,Ja.default)(Zv,d)&&(u=!0),!u}),Sc(e,"Failed to parse webm Segment start"),Sc(t,"Failed to parse webm Segment end"),Sc(r,"Failed to parse webm Segment duration"),i=i??1e6,{segmentStart:Math.round(e/1e9*i*1e3),segmentEnd:Math.round(t/1e9*i*1e3),timeScale:i,segmentDuration:Math.round(r/1e9*i*1e3),cuesSeekPosition:o,is3dVideo:c,stereoMode:p,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},aD=a=>{if(tD(a.cuesSeekPosition))return;let e=a.segmentStart+a.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},sD=(a,e)=>{let t=!1,i=!1,r=u=>Jv(u.time)&&Jv(u.position),s=[],n;return Ii(a,({tag:u,type:o,value:l})=>{switch(u){case 475249515:t=!0;break;case 187:n&&r(n)&&s.push(n),n={};break;case 179:n&&(n.time=st(l,o));break;case 183:break;case 241:n&&(n.position=st(l,o));break;default:t&&(0,Ja.default)(Zv,u)&&(i=!0)}return!(t&&i)}),n&&r(n)&&s.push(n),s.map((u,o)=>{let{time:l,position:c}=u,p=s[o+1];return{status:"none",time:{from:l,to:p?p.time:e.segmentDuration},byte:{from:e.segmentStart+c,to:p?e.segmentStart+p.position-1:e.segmentEnd-1}}})},nD=a=>{let e=0,t=!1;try{Ii(a,i=>i.tag===524531317?i.tagSize<=a.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):(0,Ja.default)(iD,i.tag)?(e+i.tagSize<=a.byteLength&&(e+=i.tagSize,t||=(0,Ja.default)([163,160,175],i.tag)),!0):!1)}catch{}return e>0&&e<=a.byteLength&&t?new DataView(a.buffer,a.byteOffset,e):null},ey={validateData:Xv,parseInit:rD,getIndexRange:aD,parseSegments:sD,parseFeedableSegmentChunk:nD};var yt=a=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(a);if(e){let[,t,i]=e;if(t==="audio"||t==="video")switch(i){case"webm":return ey;case"mp4":return zv}}throw new ReferenceError(`Unsupported mime type ${a}`)};var Tt=a=>a instanceof DOMException&&(a.name==="AbortError"||a.code===20);var wc=C(Ey(),1),Qy=C(Wi(),1),Wy=C(Fy(),1),Gy=C(at(),1),Ac=C(ci(),1);var Ny=C(Ee(),1),xc=a=>{let e=a.split("."),[t,...i]=e;if(!t)return!1;switch(t){case"av01":{let[r,s,n]=i;return!!(n&&parseInt(n,10)>8)}case"vp09":{let[r,s,n]=i;return!!(r&&parseInt(r,10)>=2&&n&&parseInt(n,10)>8)}case"avc1":{let r=i[0];if(!r||r.length!==6)return!1;let[s,n]=r.toUpperCase(),u=s+n;return(0,Ny.default)(["6E","7A","F4"],u)}}return!1};import{isNonNullable as nC,isNullable as Hy}from"@vkontakte/videoplayer-shared/es2024";var qy=a=>{if(a.includes("/")){let e=a.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(a)};var Uy=a=>{try{let e=sC(),t=a.match(e),{groups:i}=t??{};if(i){let r={};if(i.extensions){let u=i.extensions.toLowerCase().match(/(?:[0-9a-wy-z](?:-[a-z0-9]{2,8})+)/g);Array.from(u||[]).forEach(o=>{r[o[0]]=o.slice(2)})}let s=i.variants?.split(/-/).filter(u=>u!==""),n={extlang:i.extlang,langtag:i.langtag,language:i.language,privateuse:i.privateuse||i.privateuse2,region:i.region,script:i.script,extensions:r,variants:s};return Object.keys(n).forEach(u=>{let o=n[u];(typeof o>"u"||o==="")&&delete n[u]}),n}return null}catch{return null}};function sC(){let a="(?<extlang>(?:[a-z]{3}(?:-[a-z]{3}){0,2}))",e="x(?:-[a-z0-9]{1,8})+",c=`^(?:(?<langtag>${`
116
+ [selected audio track] ${v?.id}
117
+ `}),v};var Se=a=>new URL(a).hostname;import{assertNever as zS,assertNonNullable as YS,combine as Q$,debounce as W$,ErrorCategory as KS,filter as XS,filterChanged as G$,isNonNullable as hc,map as Jn,merge as JS,observableFrom as z$,once as Y$,Subscription as K$,ValueSubject as fc,videoQualityToHeight as ZS,videoSizeToQuality as X$}from"@vkontakte/videoplayer-shared/es2024";var jS=C(at(),1);var FS=C(De(),1),OS=a=>{if(a instanceof DOMException&&(0,FS.default)(["Failed to load because no supported source was found.","The element has no supported sources."],a.message))throw a;return!(a instanceof DOMException&&(a.code===20||a.name==="AbortError"))},_e=async(a,e)=>{let t=a.muted;try{await a.play()}catch(i){if(!OS(i))return!1;if(e&&e(),t)return console.warn(i),!1;a.muted=!0;try{await a.play()}catch(r){return OS(r)&&(a.muted=!1,console.warn(r)),!1}}return!0};import{isNonNullable as Kn,isNullable as P$,assertNonNullable as ya}from"@vkontakte/videoplayer-shared/es2024";var qS=C(pi(),1);import{isNonNullable as NS,assertNonNullable as Yn,now as w$}from"@vkontakte/videoplayer-shared/es2024";function fe(){return w$()}function lc(a){return fe()-a}function cc(a){let e=a.split("/"),t=e.slice(0,e.length-1).join("/"),i=/^([a-z]+:)?\/\//i,r=n=>i.test(n);return{resolve:(n,u,o=!1)=>{r(n)||(n.startsWith("/")||(n="/"+n),n=t+n);let l=n.indexOf("?")>-1?"&":"?";return o&&(n+=l+"lowLat=1",l="&"),u&&(n+=l+"_rnd="+Math.floor(999999999*Math.random())),n}}}function US(a,e,t){let i=(...r)=>{t.apply(null,r),a.removeEventListener(e,i)};a.addEventListener(e,i)}function dr(a,e,t,i){let r=window.XMLHttpRequest,s,n,u,o=!1,l=0,p,d,c=!1,h="arraybuffer",f=7e3,m=2e3,g=()=>{if(o)return;Yn(p);let $=lc(p),y;if($<m){y=m-$,setTimeout(g,y);return}m*=2,m>f&&(m=f),n&&n.abort(),n=new r,k()},S=$=>(s=$,q),v=$=>(d=$,q),I=()=>(h="json",q),T=()=>{if(!o){if(--l>=0){g(),i&&i();return}o=!0,d&&d(),t&&t()}},A=$=>(c=$,q),k=()=>{p=fe(),n=new r,n.open("get",a);let $=0,y,E=0,z=()=>(Yn(p),Math.max(p,Math.max(y||0,E||0)));if(s&&n.addEventListener("progress",M=>{let H=fe();s.updateChunk&&M.loaded>$&&(s.updateChunk(z(),M.loaded-$),$=M.loaded,y=H)}),u&&(n.timeout=u,n.addEventListener("timeout",()=>T())),n.addEventListener("load",()=>{if(o)return;Yn(n);let M=n.status;if(M>=200&&M<300){let{response:H,responseType:J}=n,ie=H?.byteLength;if(typeof ie=="number"&&s){let ue=ie-$;ue&&s.updateChunk&&s.updateChunk(z(),ue)}J==="json"&&(!H||!(0,qS.default)(H).length)?T():(d&&d(),e(H))}else T()}),n.addEventListener("error",()=>{T()}),c){let M=()=>{Yn(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(E=fe(),n.removeEventListener("readystatechange",M))};n.addEventListener("readystatechange",M)}return n.responseType=h,n.send(),q},q={withBitrateReporting:S,withParallel:A,withJSONResponse:I,withRetryCount:$=>(l=$,q),withRetryInterval:($,y)=>(NS($)&&(m=$),NS(y)&&(f=y),q),withTimeout:$=>(u=$,q),withFinally:v,send:k,abort:()=>{n&&(n.abort(),n=void 0),o=!0,d&&d()}};return q}var Sa=class{constructor(e){this.intervals=[];this.currentRate=0;this.logger=e}_updateRate(e){let t=.2;this.currentRate&&(e<this.currentRate*.1?t=.8:e<this.currentRate*.5?t=.5:e<this.currentRate*.7&&(t=.3)),e=Math.max(1,Math.min(e,100*1024*1024)),this.currentRate=this.currentRate?this.currentRate*(1-t)+e*t:e}_createInterval(e,t,i){return{start:e,end:t,bytes:i}}_doMergeIntervals(e,t){e.start=Math.min(t.start,e.start),e.end=Math.max(t.end,e.end),e.bytes+=t.bytes}_mergeIntervals(e,t){return e.start<=t.end&&t.start<=e.end?(this._doMergeIntervals(e,t),!0):!1}_flushIntervals(){if(!this.intervals.length)return!1;let e=this.intervals[0].start,t=this.intervals[this.intervals.length-1].end-500;if(t-e>2e3){let i=0,r=0;for(;this.intervals.length>0;){let s=this.intervals[0];if(s.end<=t)i+=s.end-s.start,r+=s.bytes,this.intervals.splice(0,1);else{if(s.start>=t)break;{let n=t-s.start,u=s.end-s.start;i+=n;let o=s.bytes*n/u;r+=o,s.start=t,s.bytes-=o}}}if(r>0&&i>0){let s=r*8/(i/1e3);return this._updateRate(s),this.logger(`rate updated, new=${Math.round(s/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(r)}/${Math.round(i)} interval=${Math.round(t-e)}`),!0}}return!1}_joinIntervals(){let e;do{e=!1;for(let t=0;t<this.intervals.length-1;++t)this._mergeIntervals(this.intervals[t],this.intervals[t+1])&&(this.intervals.splice(t+1,1),e=!0)}while(e)}addInterval(e,t,i){return this.intervals.push(this._createInterval(e,t,i)),this._joinIntervals(),this.intervals.length>100&&(this.logger(`too many intervals (${this.intervals.length}); will merge`,{type:"warn"}),this._doMergeIntervals(this.intervals[1],this.intervals[0]),this.intervals.splice(0,1)),this._flushIntervals()}getBitRate(){return this.currentRate}};var HS=C(pi(),1);var va=class{constructor(e,t,i,r,s){this.pendingQueue=[];this.activeRequests={};this.completeRequests={};this.averageSegmentDuration=2e3;this.lastPrefetchStart=0;this.throttleTimeout=null;this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=i,this.MAX_PARALLEL_REQUESTS=r,this.logger=s}limitCompleteCount(){let e;for(;(e=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){let t=e[Math.floor(Math.random()*e.length)];this.logger(`Dropping completed request for url ${t}`,{type:"warn"}),delete this.completeRequests[t]}}_sendRequest(e,t){let i=fe(),r=o=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=o,e._errorCB?e._errorCB(o):(this.limitCompleteCount(),this.completeRequests[t]=e)},s=o=>{e._complete=1,e._responseData=o,e._downloadTime=fe()-i,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(o,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},n=()=>{e._finallyCB&&e._finallyCB()},u=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=dr(t,s,()=>r("error"),u),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally(n),this.activeRequests[t]=e,e._request.send(),this.lastPrefetchStart=fe()}_getParallelRequestCount(){return Math.min(this.MAX_PARALLEL_REQUESTS,this.averageSegmentDuration<3e3?3:2)}_getPrefetchDelay(){return Math.max(100,Math.min(5e3,this.averageSegmentDuration/3))}_canSendPending(){let e=this._getParallelRequestCount(),t=fe();if(Object.keys(this.activeRequests).length>=e)return!1;let i=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),i>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),i),!1):!0}_sendPending(){for(;this._canSendPending();){let e=this.pendingQueue.pop();if(e){if(this.activeRequests[e]||this.completeRequests[e])continue;this.logger(`Submitting pending request url=${e}`),this._sendRequest({},e)}else return}}_removeFromActive(e){delete this.completeRequests[e],delete this.activeRequests[e]}abortAll(){(0,HS.default)(this.activeRequests).forEach(e=>{e&&e._request&&e._request.abort()}),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,i,r){let s={};return s.send=()=>{let n=this.activeRequests[e]||this.completeRequests[e];if(n)n._cb=t,n._errorCB=i,n._retryCB=r,n._finallyCB=s._finallyCB,n._error||n._complete?(this._removeFromActive(e),setTimeout(()=>{n._complete?(this.logger(`Requested url already prefetched, url=${e}`),t(n._responseData,n._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${e}`),i(n._errorMsg)),s._finallyCB&&s._finallyCB()},0)):this.logger(`Attached to active request, url=${e}`);else{let u=this.pendingQueue.indexOf(e);u!==-1&&this.pendingQueue.splice(u,1),this.logger(`Request not prefetched, starting new request, url=${e}${u===-1?"":"; removed pending"}`),this._sendRequest(s,e)}},s._cb=t,s._errorCB=i,s._retryCB=r,s.abort=function(){s.request&&s.request.abort()},s.withFinally=n=>(s._finallyCB=n,s),s}prefetch(e){this.activeRequests[e]||this.completeRequests[e]?this.logger(`Request already active for url=${e}`):(this.logger(`Added to pending queue; url=${e}`),this.pendingQueue.unshift(e),this._sendPending())}optimizeForSegDuration(e){this.averageSegmentDuration=e}};import{Subject as R$}from"@vkontakte/videoplayer-shared/es2024";var Xn=1e4,dc=3;var k$=6e4,L$=10,$$=1,M$=500,Ta=class{constructor(e){this.paused=!1;this.autoQuality=!0;this.autoQualityLimits=void 0;this.buffering=!0;this.destroyed=!1;this.videoPlayStarted=!1;this.lowLatency=!1;this.bitrate=0;this.manifest=[];this.sourceBuffer=0;this.bufferStates=[];this.sourceJitter=-1;this.waitingForFirstBufferAfterSrcChange=!1;this.params=e,this.soundProhibitedEvent$=new R$,this.chunkRateEstimator=new Sa(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=cc(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setAutoQualityLimits(e){this.autoQualityLimits=e}switchByName(e){let t;for(let i=0;i<this.manifest.length;++i)if(t=this.manifest[i],t.name===e){this._switchToQuality(t);return}}catchUp(){if(this.rep&&this.rep.stop(),this.currentManifestEntry){let e=this.params.playbackState.getState();this.paused=e==="paused",this._initPlayerWith(this.currentManifestEntry),this._notifyBuffering(!0)}}stop(){this.params.videoElement.pause(),this.rep&&(this.rep.stop(),this.rep=null)}pause(){this.paused=!0,this.params.videoElement.pause(),this.videoPlayStarted=!1,this._notifyBuffering(!1)}play(){this.paused=!1;let e=this.lowLatency&&this._getBufferSizeSec()>this.sourceJitter+5;this.rep&&!e?(this.bufferStates=[],this.videoPlayStarted=!1,this.shouldPlay()?this._playVideoElement():this._notifyBuffering(!0)):this.catchUp()}startPlay(e,t){this.autoQuality=t,this._initPlayerWith(e)}destroy(){this.destroyed=!0,this.rep&&(this.rep.stop(),this.rep=null),this.manifestRequest&&this.manifestRequest.abort(),this.manifestRefetchTimer&&(clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=void 0)}reinit(e){this.manifestUrl=e,this.urlResolver=cc(e),this.catchUp()}_handleNetworkError(){this.params.logger("Fatal network error"),this.params.playerCallback({name:"error",type:"network"})}_retryCallback(){this.params.playerCallback({name:"retry"})}_getBufferSizeSec(){let e=this.params.videoElement,t=0,i=e.buffered.length;return i!==0&&(t=e.buffered.end(i-1)-Math.max(e.currentTime,e.buffered.start(0))),t}_notifyBuffering(e){this.destroyed||(this.params.logger(`buffering: ${e}`),this.params.playerCallback({name:"buffering",isBuffering:e}),this.buffering=e)}_initVideo(){let{videoElement:e,logger:t}=this.params;e.addEventListener("error",()=>{!!e.error&&!this.destroyed&&(t(`Video element error: ${e.error?.code}, details: ${e.error?.message}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{let i=this._getBufferSizeSec();!this.paused&&i<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(i+.1)*1e3)):this.buffering&&this.videoPlayStarted&&this._notifyBuffering(!1)}),e.addEventListener("playing",()=>{t("playing")}),e.addEventListener("stalled",()=>this._fixupStall()),e.addEventListener("waiting",()=>this._fixupStall())}_fixupStall(){let{logger:e,videoElement:t}=this.params,i=t.buffered.length,r;i!==0&&!this.waitingForFirstBufferAfterSrcChange&&(r=t.buffered.start(i-1),t.currentTime<r&&(e("Fixup stall"),t.currentTime=r))}_selectQuality(e){let{videoElement:t}=this.params,i,r,s,n=t&&1.62*(B.display.pixelRatio||1)*t.offsetHeight||520;for(let u=0;u<this.manifest.length;++u){s=this.manifest[u];let{max:o,min:l}=this.autoQualityLimits||{};!RS({limits:this.autoQualityLimits,highestAvailableHeight:this.manifest[0].video.height,lowestAvailableHeight:(0,jS.default)(this.manifest,-1).video.height})&&(o&&s.video.height>o||l&&s.video.height<l)||(s.bitrate<e&&n>Math.min(s.video.height,s.video.width)?(!r||s.bitrate>r.bitrate)&&(r=s):(!i||i.bitrate>s.bitrate)&&(i=s))}return r||i}shouldPlay(){if(this.paused)return!1;let t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||Kn(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){let{logger:i,videoElement:r,playerCallback:s}=this.params;this.mediaSource=new window.MediaSource,i("setting video src"),r.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.videoPlayStarted=!1,r.addEventListener("canplay",()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});let n=()=>{US(r,"progress",()=>{r.buffered.length?(r.currentTime=r.buffered.start(0),this.waitingForFirstBufferAfterSrcChange=!1,s({name:"playing"})):n()})};this.waitingForFirstBufferAfterSrcChange=!0,n()}_initPlayerWith(e){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new va(dc,Xn,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){let{logger:t,videoElement:i,playerCallback:r}=this.params,s=!1,n=null,u=null,o=null,l=null,p=!1,d=()=>{let T=s&&(!p||p===this.rep);return T||t("Not running!"),T},c=(T,A,k)=>{o&&o.abort(),o=dr(this.urlResolver.resolve(T,!1),A,k,()=>this._retryCallback()).withTimeout(Xn).withBitrateReporting(this.bitrateSwitcher).withRetryCount(dc).withFinally(()=>{o=null}).send()},h=(T,A,k)=>{ya(this.filesFetcher),u?.abort(),u=this.filesFetcher.requestData(this.urlResolver.resolve(T,!1),A,k,()=>this._retryCallback()).withFinally(()=>{u=null}).send()},f=T=>{let A=i.playbackRate;i.playbackRate!==T&&(t(`Playback rate switch: ${A}=>${T}`),i.playbackRate=T)},m=T=>{this.lowLatency=T,t(`lowLatency changed to ${T}`),g()},g=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)f(1);else{let T=this._getBufferSizeSec();if(this.bufferStates.length<5){f(1);return}let k=fe()-1e4,L=0;for(let D=0;D<this.bufferStates.length;D++){let x=this.bufferStates[D];T=Math.min(T,x.buf),x.ts<k&&L++}this.bufferStates.splice(0,L),t(`update playback rate; minBuffer=${T} drop=${L} jitter=${this.sourceJitter}`);let w=T-$$;this.sourceJitter>=0?w-=this.sourceJitter/2:this.sourceJitter-=1,w>3?f(1.15):w>1?f(1.1):w>.3?f(1.05):f(1)}},S=T=>{let A,k=()=>A&&A.start?A.start.length:0,L=M=>A.start[M]/1e3,w=M=>A.dur[M]/1e3,D=M=>A.fragIndex+M,x=(M,H)=>({chunkIdx:D(M),startTS:L(M),dur:w(M),discontinuity:H}),q=()=>{let M=0;if(A&&A.dur){let H=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,J=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,ie=H;this.sourceJitter>1&&(ie+=this.sourceJitter-1);let ue=A.dur.length-1;for(;ue>=0&&(ie-=A.dur[ue],!(ie<=0));--ue);M=Math.min(ue,A.dur.length-1-J),M=Math.max(M,0)}return x(M,!0)},$=M=>{let H=k();if(!(H<=0)){if(Kn(M)){for(let J=0;J<H;J++)if(L(J)>M)return x(J)}return q()}},y=M=>{let H=k(),J=M?M.chunkIdx+1:0,ie=J-A.fragIndex;if(!(H<=0)){if(!M||ie<0||ie-H>L$)return t(`Resync: offset=${ie} bChunks=${H} chunk=`+JSON.stringify(M)),q();if(!(ie>=H))return x(J-A.fragIndex,!1)}},E=(M,H,J)=>{l&&l.abort(),l=dr(this.urlResolver.resolve(M,!0,this.lowLatency),H,J,()=>this._retryCallback()).withTimeout(Xn).withRetryCount(dc).withFinally(()=>{l=null}).withJSONResponse().send()};return{seek:(M,H)=>{E(T,J=>{if(!d())return;A=J;let ie=!!A.lowLatency;ie!==this.lowLatency&&m(ie);let ue=0;for(let me=0;me<A.dur.length;++me)ue+=A.dur[me];ue>0&&(ya(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(ue/A.dur.length)),r({name:"index",zeroTime:A.zeroTime,shiftDuration:A.shiftDuration}),this.sourceJitter=A.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,A.jitter/1e3)):1,M($(H))},()=>this._handleNetworkError())},nextChunk:y}},v=()=>{s=!1,u&&u.abort(),o&&o.abort(),l&&l.abort(),ya(this.filesFetcher),this.filesFetcher.abortAll()};return p={start:T=>{let{videoElement:A,logger:k}=this.params,L=S(e.jidxUrl),w,D,x,q,$=0,y,E,z,M=()=>{y&&(clearTimeout(y),y=void 0);let U=Math.max(M$,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),Le=$+U,Te=fe(),de=Math.min(1e4,Le-Te);$=Te;let We=()=>{l||d()&&L.seek(()=>{d()&&($=fe(),H(),M())})};de>0?y=window.setTimeout(()=>{this.paused?M():We()},de):We()},H=()=>{let U;for(;U=L.nextChunk(q);)q=U,be(U);let Le=L.nextChunk(x);if(Le){if(x&&Le.discontinuity){k("Detected discontinuity; restarting playback"),this.paused?M():(v(),this._initPlayerWith(e));return}me(Le)}else M()},J=(U,Le)=>{if(!d()||!this.sourceBuffer)return;let Te,de,We,Bt=lt=>{window.setTimeout(()=>{d()&&J(U,Le)},lt)};if(this.sourceBuffer.updating)k("Source buffer is updating; delaying appendBuffer"),Bt(100);else{let lt=fe(),Oe=A.currentTime;!this.paused&&A.buffered.length>1&&E===Oe&&lt-z>500&&(k("Stall suspected; trying to fix"),this._fixupStall()),E!==Oe&&(E=Oe,z=lt);let Vt=this._getBufferSizeSec();if(Vt>30)k(`Buffered ${Vt} seconds; delaying appendBuffer`),Bt(2e3);else try{this.sourceBuffer.appendBuffer(U),this.videoPlayStarted?(this.bufferStates.push({ts:lt,buf:Vt}),g(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),Le&&Le()}catch(ct){if(ct.name==="QuotaExceededError")k("QuotaExceededError; delaying appendBuffer"),We=this.sourceBuffer.buffered.length,We!==0&&(Te=this.sourceBuffer.buffered.start(0),de=Oe,de-Te>4&&this.sourceBuffer.remove(Te,de-3)),Bt(1e3);else throw ct}}},ie=()=>{D&&w&&(k([`Appending chunk, sz=${D.byteLength}:`,JSON.stringify(x)]),J(D,function(){D=null,H()}))},ue=U=>e.fragUrlTemplate.replace("%%id%%",U.chunkIdx),me=U=>{d()&&h(ue(U),(Le,Te)=>{if(d()){if(Te/=1e3,D=Le,x=U,n=U.startTS,Te){let de=Math.min(10,U.dur/Te);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*de:de}ie()}},()=>this._handleNetworkError())},be=U=>{d()&&(ya(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(ue(U),!1)))},j=U=>{d()&&(e.cachedHeader=U,J(U,()=>{w=!0,ie()}))};s=!0,L.seek(U=>{if(d()){if($=fe(),!U){M();return}q=U,!P$(T)||U.startTS>T?me(U):(x=U,H())}},T),e.cachedHeader?j(e.cachedHeader):c(e.headerUrl,j,()=>this._handleNetworkError())},stop:v,getTimestampSec:()=>n},p}_switchToQuality(e){let{logger:t,playerCallback:i}=this.params,r;e.bitrate!==this.bitrate&&(this.rep&&(r=this.rep.getTimestampSec(),Kn(r)&&(r+=.1),this.rep.stop()),this.currentManifestEntry=e,this.rep=this._representation(e),t(`switch to quality: codecs=${e.codecs}; headerUrl=${e.headerUrl}; bitrate=${e.bitrate}`),this.bitrate=e.bitrate,ya(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(r),i({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return Kn(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,i=d=>{if(!this.autoQuality)return;let c,h,f;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&d<this.bitrate&&(h=this._getBufferSizeSec(),f=d/this.bitrate,h>10&&f>.8||h>15&&f>.5||h>20&&f>.3)){e(`Not switching: buffer=${Math.floor(h)}; bitrate=${this.bitrate}; newRate=${Math.floor(d)}`);return}c=this._selectQuality(d),c?this._switchToQuality(c):e(`Could not find quality by bitrate ${d}`)},s={updateChunk:(c,h)=>{let f=fe();if(this.chunkRateEstimator.addInterval(c,f,h)){let g=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:h,duration:f-c,speed:g}),!0}},get:()=>{let c=this.chunkRateEstimator.getBitRate();return c?c*.85:0}},n=-1/0,u,o=!0,l=()=>{let d=s.get();if(d&&u&&this.autoQuality){if(o&&d>u&&lc(n)<3e4)return;i(d)}o=this.autoQuality};return{updateChunk:(d,c)=>{let h=s.updateChunk(d,c);return h&&l(),h},notifySwitch:d=>{let c=fe();d<u&&(n=c),u=d}}}_fetchManifest(e,t,i){this.manifestRequest=dr(this.urlResolver.resolve(e,!0),t,i,()=>this._retryCallback()).withJSONResponse().withTimeout(Xn).withRetryCount(this.params.config.manifestRetryMaxCount).withRetryInterval(this.params.config.manifestRetryInterval,this.params.config.manifestRetryMaxInterval).send().withFinally(()=>{this.manifestRequest=void 0})}_playVideoElement(){let{videoElement:e}=this.params;_e(e,()=>{this.soundProhibitedEvent$.next()}).then(t=>{t||(this.params.liveOffset.pause(),this.params.videoState.setState("paused"))})}_handleManifestUpdate(e){let{logger:t,playerCallback:i,videoElement:r}=this.params,s=n=>{let u=[];return n?.length?(n.forEach((o,l)=>{o.video&&r.canPlayType(o.codecs).replace(/no/,"")&&window.MediaSource?.isTypeSupported?.(o.codecs)&&(o.index=l,u.push(o))}),u.sort(function(o,l){return o.video&&l.video?l.video.height-o.video.height:l.bitrate-o.bitrate}),u):(i({name:"error",type:"empty_manifest"}),[])};this.manifest=s(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),i({name:"manifest",manifest:this.manifest})}_refetchManifest(e){this.destroyed||(this.manifestRefetchTimer&&clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=window.setTimeout(()=>{this._fetchManifest(e,t=>{this.destroyed||(this._handleManifestUpdate(t),this._refetchManifest(e))},()=>this._refetchManifest(e))},k$))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};var GS=C(Yi(),1);import{debounce as D$,filter as QS,fromEvent as C$,interval as B$,isHigher as V$,isInvariantQuality as _$,isLower as O$,merge as F$,Subject as WS,Subscription as N$}from"@vkontakte/videoplayer-shared/es2024";var pc=class{constructor(){this.onDroopedVideoFramesLimit$=new WS;this.subscription=new N$;this.playing=!1;this.tracks=[];this.forceChecker$=new WS;this.isForceCheckCounter=0;this.prevTotalVideoFrames=0;this.prevDroppedVideoFrames=0;this.limitCounts={};this.handleChangeVideoQuality=()=>{let e=this.tracks.find(({size:t})=>t?.height===this.video.videoHeight&&t?.width===this.video.videoWidth);e&&!_$(e.quality)&&this.onChangeQuality(e.quality)};this.checkDroppedFrames=()=>{let{totalVideoFrames:e,droppedVideoFrames:t}=this.video.getVideoPlaybackQuality(),i=e-this.prevTotalVideoFrames,r=t-this.prevDroppedVideoFrames,s=1-(i-r)/i;!isNaN(s)&&s>0&&this.log({message:`[dropped]. current dropped percent: ${s}, limit: ${this.droppedFramesChecker.percentLimit}`}),!isNaN(s)&&s>=this.droppedFramesChecker.percentLimit&&V$(this.currentQuality,this.droppedFramesChecker.minQualityBanLimit)&&(this.limitCounts[this.currentQuality]=(this.limitCounts[this.currentQuality]??0)+1,this.maxQualityLimit=this.getMaxQualityLimit(this.currentQuality),this.currentTimer&&window.clearTimeout(this.currentTimer),this.currentTimer=window.setTimeout(()=>this.maxQualityLimit=this.getMaxQualityLimit(),this.droppedFramesChecker.qualityUpWaitingTime),this.onDroopedVideoFramesLimitTrigger()),this.savePrevFrameCounts(e,t)}}connect(e){this.log=e.logger.createComponentLog("DroppedFramesManager"),this.video=e.video,this.isAuto=e.isAuto,this.tracks=e.tracks,this.droppedFramesChecker=e.droppedFramesChecker,this.subscription.add(e.playing$.subscribe(()=>this.playing=!0)),this.subscription.add(e.pause$.subscribe(()=>this.playing=!1)),this.isEnabled&&this.subscribe()}destroy(){this.currentTimer&&window.clearTimeout(this.currentTimer),this.subscription.unsubscribe()}get droppedVideoMaxQualityLimit(){return this.maxQualityLimit}subscribe(){this.subscription.add(C$(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=B$(this.droppedFramesChecker.checkTime).pipe(QS(()=>this.playing),QS(()=>{let r=!!this.isForceCheckCounter;return r&&(this.isForceCheckCounter-=1),!r})),t=this.forceChecker$.pipe(D$(this.droppedFramesChecker.checkTime)),i=F$(e,t);this.subscription.add(i.subscribe(this.checkDroppedFrames))}onChangeQuality(e){this.currentQuality=e;let{totalVideoFrames:t,droppedVideoFrames:i}=this.video.getVideoPlaybackQuality();this.savePrevFrameCounts(t,i),this.isForceCheckCounter=this.droppedFramesChecker.tickCountAfterQualityChange,this.forceChecker$.next()}onDroopedVideoFramesLimitTrigger(){this.isAuto.getState()&&(this.log({message:`[onDroopedVideoFramesLimit]. maxQualityLimit: ${this.maxQualityLimit}`}),this.onDroopedVideoFramesLimit$.next())}getMaxQualityLimit(e){let t=(0,GS.default)(this.limitCounts).filter(([,i])=>i>=this.droppedFramesChecker.countLimit).sort(([i],[r])=>O$(i,r)?-1:1)?.[0]?.[0];return e??t}get isEnabled(){return this.droppedFramesChecker.enabled&&this.isDroppedFramesCheckerSupport}get isDroppedFramesCheckerSupport(){return!!this.video&&typeof this.video.getVideoPlaybackQuality=="function"}savePrevFrameCounts(e,t){this.prevTotalVideoFrames=e,this.prevDroppedVideoFrames=t}},pr=pc;import{map as q$,Observable as U$}from"@vkontakte/videoplayer-shared/es2024";import{fromEvent as H$}from"@vkontakte/videoplayer-shared/es2024";var Ia=()=>!!window.documentPictureInPicture?.window||!!document.pictureInPictureElement;var j$=(a,e)=>new U$(t=>{if(!window.IntersectionObserver)return;let i={root:null},r=new IntersectionObserver((n,u)=>{n.forEach(o=>t.next(o.isIntersecting||Ia()))},{...i,...e});r.observe(a);let s=H$(document,"visibilitychange").pipe(q$(n=>!document.hidden||Ia())).subscribe(n=>t.next(n));return()=>{r.unobserve(a),s.unsubscribe()}}),Ke=j$;var J$=["paused","playing","ready"],Z$=["paused","playing","ready"],Ea=class{constructor(e){this.subscription=new K$;this.videoState=new F("stopped");this.representations$=new fc([]);this.droppedFramesManager=new pr;this.maxSeekBackTime$=new fc(1/0);this.zeroTime$=new fc(void 0);this.liveOffset=new yi;this._dashCb=e=>{switch(e.name){case"buffering":{let t=e.isBuffering;this.params.output.isBuffering$.next(t);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${e.type}`,category:KS.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{let t=e.manifest,i=[];for(let r of t){let s=r.name??r.index.toString(10),n=jt(r.name)??X$(r.video),u=r.bitrate/1e3,o={...r.video};if(!n)continue;let l={id:s,quality:n,bitrate:u,size:o};i.push({track:l,representation:r})}this.representations$.next(i),this.params.output.availableVideoTracks$.next(i.map(({track:r})=>r)),this.videoState.getTransition()?.to==="manifest_ready"&&this.videoState.setState("manifest_ready");break}case"qualitySwitch":{let t=e.quality,i=this.representations$.getValue().find(({representation:r})=>r===t)?.track;this.params.output.hostname$.next(new URL(t.headerUrl,this.params.source.url).hostname),hc(i)&&this.params.output.currentVideoTrack$.next(i);break}case"bandwidth":{let{size:t,duration:i}=e;this.params.dependencies.throughputEstimator.addRawSpeed(t,i);break}case"index":{this.maxSeekBackTime$.next(e.shiftDuration||0),this.zeroTime$.next(e.zeroTime);break}}};this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; seekState: ${JSON.stringify(s)};`}),i==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState("stopped"));return}if(t)return;let n=this.params.desiredState.videoTrack.getTransition(),u=this.params.desiredState.autoVideoTrackSwitching.getTransition();if((0,mc.default)(Z$,e)&&(n||u)){this.prepare();return}if(r?.to!=="paused"&&s.state==="requested"&&(0,mc.default)(J$,e)){this.seek(s.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(se(this.params.source.url));return;case"manifest_ready":this.videoState.startTransitionTo("ready"),this.prepare();break;case"ready":if(i==="paused")this.videoState.setState("paused");else if(i==="playing"){this.videoState.startTransitionTo("playing");let o=r?.from;o&&o==="ready"&&this.dash.catchUp(),this.dash.play()}return;case"playing":i==="paused"&&(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.dash.pause());return;case"paused":if(i==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.dash.play(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let o=this.liveOffset.getTotalOffset();o>=this.maxSeekBackTime$.getValue()&&(o=0,this.liveOffset.resetTo(o)),this.liveOffset.resume(),this.params.output.position$.next(-o/1e3),this.dash.reinit(se(this.params.source.url,o))}return;default:return zS(e)}};this.textTracksManager=new Ye(e.source.url),this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=r=>{e.output.error$.next({id:"DashLiveProvider",category:KS.WTF,message:"DashLiveProvider internal logic error",thrown:r})};this.subscription.add(JS(this.videoState.stateChangeStarted$.pipe(Jn(r=>({transition:r,type:"start"}))),this.videoState.stateChangeEnded$.pipe(Jn(r=>({transition:r,type:"end"})))).subscribe(({transition:r,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(r)}`})})),this.video=Ce(e.container,e.tuning),this.params.output.element$.next(this.video),this.dash=this.createLiveDashPlayer(),this.subscription.add(this.dash.soundProhibitedEvent$.subscribe(this.params.output.soundProhibitedEvent$)),this.params.output.duration$.next(1/0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(Se(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);let i=Ve(this.video);this.subscription.add(()=>i.destroy()),this.subscription.add(this.representations$.pipe(Jn(r=>r.map(({track:s})=>s)),XS(r=>!!r.length),Y$()).subscribe(r=>this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks:r}))),this.subscription.add(i.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready")},t)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused")},t)).add(i.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.videoState.setState("playing")},t)).add(i.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(G$(),Jn(r=>-r/1e3)).subscribe(this.params.output.duration$)).add(Q$({zeroTime:this.zeroTime$.pipe(XS(hc)),position:i.timeUpdate$}).subscribe(({zeroTime:r,position:s})=>this.params.output.liveTime$.next(r+s*1e3),t)).add(mt(this.video,this.params.desiredState.isLooped,t)).add(Ee(this.video,this.params.desiredState.volume,i.volumeState$,t)).add(i.volumeState$.subscribe(this.params.output.volume$,t)).add(ze(this.video,this.params.desiredState.playbackRate,i.playbackRateState$,t)).add(i.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(i.loadedMetadata$.subscribe(this.params.output.loadedMetadataEvent$)).add(i.playing$.subscribe(this.params.output.firstFrameEvent$)).add(i.canplay$.subscribe(this.params.output.canplay$)).add(i.inPiP$.subscribe(this.params.output.inPiP$)).add(i.inFullscreen$.subscribe(this.params.output.inFullscreen$)).add(Ke(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:r,min:s}})=>{this.dash.setAutoQualityLimits({max:r&&ZS(r),min:s&&ZS(s)}),this.params.output.autoVideoTrackLimits$.next({max:r,min:s})})).add(this.videoState.stateChangeEnded$.subscribe(r=>{switch(r.to){case"stopped":this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState("stopped");break;case"manifest_ready":case"ready":this.params.desiredState.playbackState.getTransition()?.to==="ready"&&this.params.desiredState.playbackState.setState("ready");break;case"paused":this.params.desiredState.playbackState.setState("paused");break;case"playing":this.params.desiredState.playbackState.setState("playing");break;default:return zS(r.to)}},t)).add(JS(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,z$(["init"])).pipe(W$(0)).subscribe(this.syncPlayback,t))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.droppedFramesManager.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),Be(this.video)}createLiveDashPlayer(){let e=new Ta({videoElement:this.video,videoState:this.videoState,playbackState:this.params.desiredState.playbackState,liveOffset:this.liveOffset,config:{maxParallelRequests:this.params.config.maxParallelRequests,minBuffer:this.params.tuning.live.minBuffer,minBufferSegments:this.params.tuning.live.minBufferSegments,lowLatencyMinBuffer:this.params.tuning.live.lowLatencyMinBuffer,lowLatencyMinBufferSegments:this.params.tuning.live.lowLatencyMinBufferSegments,isLiveCatchUpMode:this.params.tuning.live.isLiveCatchUpMode,manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},playerCallback:this._dashCb,logger:t=>{this.params.dependencies.logger.log({message:String(t),component:"LiveDashPlayer"})}});return e.pause(),e}prepare(){let e=this.representations$.getValue(),t=this.params.desiredState.videoTrack.getTransition()?.to??this.params.desiredState.videoTrack.getState(),i=this.params.desiredState.autoVideoTrackSwitching.getTransition()?.to??this.params.desiredState.autoVideoTrackSwitching.getState(),r=!i&&hc(t)?t:St(e.map(({track:l})=>l),{container:this.video.getBoundingClientRect(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),s=r?.id,n=this.params.desiredState.videoTrack.getTransition(),u=this.params.desiredState.videoTrack.getState()?.id,o=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(r&&(n||s!==u)&&this.setVideoTrack(r),o&&this.setAutoQuality(i),n||o||s!==u){let l=e.find(({track:p})=>p.id===s)?.representation;YS(l,"Representations missing"),this.dash.startPlay(l,i)}}setVideoTrack(e){let t=this.representations$.getValue().find(({track:i})=>i.id===e.id)?.representation;YS(t,`No such representation ${e.id}`),this.dash.switchByName(t.name),this.params.desiredState.videoTrack.setState(e)}setAutoQuality(e){this.dash.setAutoQualityEnabled(e),this.params.desiredState.autoVideoTrackSwitching.setState(e)}seek(e){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),i=this.videoState.getState(),r=t==="paused"&&i==="paused",s=-e,n=s<=this.maxSeekBackTime$.getValue()?s:0;this.params.output.position$.next(e/1e3),this.dash.reinit(se(this.params.source.url,n)),r&&this.dash.pause(),this.liveOffset.resetTo(n,r)}};var ev=Ea;var ve=(a,e)=>{let t=0;for(let i=0;i<a.length;i++){let r=a.start(i)*1e3,s=a.end(i)*1e3;r<=e&&e<=s&&(t=s)}return Math.max(t-e,0)};import{assertNever as jC,assertNonNullable as QC,combine as WC,debounce as GC,ErrorCategory as bT,filter as cs,filterChanged as ds,fromEvent as zC,isNonNullable as gT,isNullable as YC,map as Rr,merge as ps,observableFrom as Ro,once as ko,Subscription as KC,throttle as XC,ValueSubject as JC}from"@vkontakte/videoplayer-shared/es2024";var{NativeAbortSignal:DU,NativeAbortController:CU}=function(a){return{NativeAbortSignal:a.AbortSignal,NativeAbortController:a.AbortController}}(typeof self<"u"?self:global);function tv(a){let e;try{e=new Event("abort")}catch{typeof document<"u"?document.createEvent?(e=document.createEvent("Event"),e.initEvent("abort",!1,!1)):(e=document.createEventObject(),e.type="abort"):e={type:"abort",bubbles:!1,cancelable:!1}}return e.reason=a,e}function iv(a){if(a===void 0)if(typeof document>"u")a=new Error("This operation was aborted"),a.name="AbortError";else try{a=new DOMException("signal is aborted without reason"),Object.defineProperty(a,"name",{value:"AbortError"})}catch{a=new Error("This operation was aborted"),a.name="AbortError"}return a}var Zn=class{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,i){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:i})}removeEventListener(e,t){if(!(e in this.listeners))return;let i=this.listeners[e];for(let r=0,s=i.length;r<s;r++)if(i[r].callback===t){i.splice(r,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;let i=this.listeners[e.type].slice();for(let r=0,s=i.length;r<s;r++){let n=i[r];try{n.callback.call(this,e)}catch(u){Promise.resolve().then(()=>{throw u})}n.options&&n.options.once&&this.removeEventListener(e.type,n.callback)}return!e.defaultPrevented}},hr=class extends Zn{constructor(){super(),this.listeners||Zn.call(this),Object.defineProperty(this,"aborted",{value:!1,writable:!0,configurable:!0}),Object.defineProperty(this,"onabort",{value:null,writable:!0,configurable:!0}),Object.defineProperty(this,"reason",{value:void 0,writable:!0,configurable:!0})}toString(){return"[object AbortSignal]"}dispatchEvent(e){e.type==="abort"&&(this.aborted=!0,typeof this.onabort=="function"&&this.onabort.call(this,e)),super.dispatchEvent(e)}throwIfAborted(){let{aborted:e,reason:t="Aborted"}=this;if(e)throw t}static timeout(e){let t=new Ei;return setTimeout(()=>t.abort(new DOMException(`This signal is timeout in ${e}ms`,"TimeoutError")),e),t.signal}static any(e){let t=new Ei;function i(){t.abort(this.reason),r()}function r(){for(let s of e)s.removeEventListener("abort",i)}for(let s of e)if(s.aborted){t.abort(s.reason);break}else s.addEventListener("abort",i);return t.signal}},Ei=class{constructor(){Object.defineProperty(this,"signal",{value:new hr,writable:!0,configurable:!0})}abort(e){let t=iv(e),i=tv(t);this.signal.reason=t,this.signal.dispatchEvent(i)}toString(){return"[object AbortController]"}};typeof Symbol<"u"&&Symbol.toStringTag&&(Ei.prototype[Symbol.toStringTag]="AbortController",hr.prototype[Symbol.toStringTag]="AbortSignal");function eo(a){return a.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof a.Request=="function"&&!a.Request.prototype.hasOwnProperty("signal")||!a.AbortController}function bc(a){typeof a=="function"&&(a={fetch:a});let{fetch:e,Request:t=e.Request,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r=!1}=a;if(!eo({fetch:e,Request:t,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r}))return{fetch:e,Request:s};let s=t;(s&&!s.prototype.hasOwnProperty("signal")||r)&&(s=function(l,p){let d;p&&p.signal&&(d=p.signal,delete p.signal);let c=new t(l,p);return d&&Object.defineProperty(c,"signal",{writable:!1,enumerable:!1,configurable:!0,value:d}),c},s.prototype=t.prototype);let n=e;return{fetch:(o,l)=>{let p=s&&s.prototype.isPrototypeOf(o)?o.signal:l?l.signal:void 0;if(p){let d;try{d=new DOMException("Aborted","AbortError")}catch{d=new Error("Aborted"),d.name="AbortError"}if(p.aborted)return Promise.reject(d);let c=new Promise((h,f)=>{p.addEventListener("abort",()=>f(d),{once:!0})});return l&&l.signal&&delete l.signal,Promise.race([c,n(o,l)])}return n(o,l)},Request:s}}var eM=()=>"fetch"in window,xa=eM()&&eo({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),rv=xa?bc({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,Xe=xa?rv.fetch:window.fetch,jU=xa?rv.Request:window.Request,X=xa?Ei:window.AbortController,QU=xa?hr:window.AbortSignal;var pT=C(De(),1),Wc=C(wa(),1);var Hv=C(Uv(),1);import{ErrorCategory as Pa}from"@vkontakte/videoplayer-shared/es2024";var to=a=>{if(!a)return{id:"EmptyResponse",category:Pa.PARSER,message:"Empty response"};if(a.length<=2&&a.match(/^\d+$/))return{id:`UVError#${a}`,category:Pa.NETWORK,message:`UV Error ${a}`};let e=(0,Hv.default)(a).substring(0,100).toLowerCase();if(e.startsWith("<!doctype")||e.startsWith("<html>")||e.startsWith("<body>")||e.startsWith("<head>"))return{id:"UnexpectedHTML",category:Pa.NETWORK,message:"Received unexpected HTML, possibly a ISP block"};if(e.startsWith("<?xml"))return new DOMParser().parseFromString(a,"text/xml").querySelector("parsererror")?{id:"InvalidXML",category:Pa.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:Pa.PARSER,message:"Response is valid XML, but parser failed"}};var ye=(a,e,t=0)=>{for(let i=0;i<a.length;i++)if(a.start(i)*1e3-t<=e&&a.end(i)*1e3+t>e)return!0;return!1};import{abortable as Hc,assertNonNullable as xr,combine as wr,ErrorCategory as ot,filter as To,filterChanged as ns,flattenObject as os,fromEvent as Dt,getTraceSubscriptionMethod as AC,interval as jc,isNonNullable as us,isNullable as lT,map as Ar,merge as Ri,now as Qc,Subject as Xt,Subscription as cT,tap as PC,throttle as RC,ValueSubject as ee}from"@vkontakte/videoplayer-shared/es2024";var so=C(De(),1),Pi=C(at(),1),no=C(wa(),1);var FM=(a,e={})=>{let i=e.timeout||1,r=performance.now();return window.setTimeout(()=>{a({get didTimeout(){return e.timeout?!1:performance.now()-r-1>i},timeRemaining(){return Math.max(0,1+(performance.now()-r))}})},1)},NM=a=>window.clearTimeout(a),jv=a=>typeof a=="function"&&a?.toString().endsWith("{ [native code] }"),Qv=!jv(window.requestIdleCallback)||!jv(window.cancelIdleCallback),fr=Qv?FM:window.requestIdleCallback,vt=Qv?NM:window.cancelIdleCallback;var tT=C(An(),1);import{assertNever as qM,ErrorCategory as Wv,Subject as Gv}from"@vkontakte/videoplayer-shared/es2024";var UM=18,zv=!1;try{zv=B.browser.isSafari&&!!B.browser.safariVersion&&B.browser.safariVersion<=UM}catch(a){console.error(a)}var Ic=class{constructor(e){this.bufferFull$=new Gv;this.error$=new Gv;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:Wv.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)};zv&&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:Wv.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:qM(t)}}},Yv=Ic;var mr=a=>{let e=0;for(let t=0;t<a.length;t++)e+=a.end(t)-a.start(t);return e*1e3};import{abortable as Gt,assertNonNullable as Re,ErrorCategory as Lt,fromEvent as Vc,getExponentialDelay as _c,isHigher as cC,isNonNullable as zt,isNullable as le,now as ao,once as dC,Subject as pC,Subscription as hC,ValueSubject as Ai}from"@vkontakte/videoplayer-shared/es2024";var Kv=C(at(),1);var io=a=>a.valid,Q=class{constructor(e,t){this.cursor=0;this.source=e,this.boxParser=t,this.children=[];let i=this.readUint32();this.type=this.readString(4),i===1&&(this.cursor+=8);let r=e.byteOffset+this.cursor,s;i===0?(this.size=void 0,this.valid=!1,s=void 0):i===1?(this.size=void 0,this.valid=!1,s=void 0):i>e.byteLength?(this.size=i,this.valid=!1,s=Math.min(i-this.cursor,e.byteLength-this.cursor)):(this.size=i,this.valid=!0,s=i-this.cursor),this.content=new DataView(e.buffer,r,s)}get id(){return this.type}scanForBoxes(e){return this.boxParser.parse(e)}readString(e,t="ascii"){let r=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,r}readUint8(){let e=this.source.getUint8(this.cursor);return this.cursor+=1,e}readUint16(){let e=this.source.getUint16(this.cursor);return this.cursor+=2,e}readUint32(){let e=this.source.getUint32(this.cursor);return this.cursor+=4,e}readUint64(){let e=this.source.getBigInt64(this.cursor);return this.cursor+=8,e}};var br=class extends Q{};import{assertNever as HM}from"@vkontakte/videoplayer-shared/es2024";var Ra=class extends Q{constructor(e,t){if(super(e,t),!this.valid)return;let i=this.readString(16),r=new DataView(this.content.buffer,this.content.byteOffset+16,this.content.byteLength-16);this.userData=this.parseData(i,r)}parseData(e,t){switch(e){case"ondemandlivejson":{let i=new TextDecoder("ascii").decode(t),r=JSON.parse(i);return{received:r["t-in"],prepared:r["t-out"]}}default:HM(e)}}};var ka=class extends Q{constructor(e,t){if(super(e,t),!this.valid)return;this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let i=new DataView(this.content.buffer,this.content.byteOffset+8,this.content.byteLength-8);for(let r=0;r<i.byteLength;r+=4){let s=this.readString(4);this.compatibleBrands.push(s)}}};var La=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Z=class extends Q{constructor(e,t){if(super(e,t),!this.valid)return;let i=this.readUint32();this.version=i>>>24,this.flags=i&16777215,this.content=new DataView(this.content.buffer,this.content.byteOffset+4,this.content.byteLength-4)}};var $a=class extends Z{constructor(e,t){super(e,t),this.valid&&(this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.timescale=this.readUint32(),this.duration=this.readUint32(),this.rate=this.readUint32(),this.volume=this.readUint16())}};var Ma=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Da=class extends Q{constructor(e,t){super(e,t),this.data=this.content}};var xi=class extends Z{get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e,t){if(super(e,t),!!this.valid){this.segments=[],this.referenceId=this.readUint32(),this.timescale=this.readUint32(),this.earliestPresentationTime32=this.readUint32(),this.firstOffset32=this.readUint32(),this.earliestPresentationTime64=0,this.firstOffset64=0,this.referenceCount=this.readUint32()&65535;for(let i=0;i<this.referenceCount;i++){let r=this.readUint32(),s=r>>>31,n=r<<1>>>1,u=this.readUint32();r=this.readUint32();let o=r>>>28,l=r<<3>>>3;this.segments.push({referenceType:s,referencedSize:n,subsegmentDuration:u,SAPType:o,SAPDeltaTime:l})}}}};var Ca=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ba=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Va=class extends Z{constructor(e,t){if(super(e,t),!this.valid)return;switch(this.readUint8()){case 0:this.stereoMode=0;break;case 1:this.stereoMode=1;break;case 2:this.stereoMode=2;break;case 3:this.stereoMode=3;break;case 4:this.stereoMode=4;break}this.cursor+=1}};var _a=class extends Z{constructor(e,t){super(e,t),this.valid&&(this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32())}};var Oa=class extends Z{constructor(e,t){super(e,t),this.valid&&(this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32())}};var Fa=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Na=class extends Z{constructor(e,t){super(e,t),this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.trackId=this.readUint32(),this.cursor+=4,this.duration=this.readUint32(),this.cursor+=8,this.layer=this.readUint16(),this.alternateGroup=this.readUint16(),this.cursor+=2,this.cursor+=2,this.matrix=[[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()]],this.width=this.readUint32(),this.height=this.readUint32()}};var qa=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ua=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ha=class extends Z{constructor(e,t){super(e,t),this.valid&&(this.sequenceNumber=this.readUint32())}};var ja=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Qa=class extends Z{constructor(e,t){super(e,t),this.trackId=this.readUint32(),this.flags&1&&(this.baseDataOffset=this.readUint64()),this.flags&2&&(this.sampleDescriptionIndex=this.readUint32()),this.flags&8&&(this.defaultSampleDuration=this.readUint32()),this.flags&16&&(this.defaultSampleSize=this.readUint32()),this.flags&32&&(this.defaultSampleFlags=this.readUint32())}};var Wa=class extends Z{constructor(t,i){super(t,i);this.baseMediaDecodeTime32=0;this.baseMediaDecodeTime64=BigInt(0);this.version===1?this.baseMediaDecodeTime64=this.readUint64():this.baseMediaDecodeTime32=this.readUint32()}get baseMediaDecodeTime(){return this.version===1?this.baseMediaDecodeTime64:this.baseMediaDecodeTime32}};var Ga=class extends Z{constructor(t,i){super(t,i);this.sampleDuration=[];this.sampleSize=[];this.sampleFlags=[];this.sampleCompositionTimeOffset=[];this.optionalFields=0;this.sampleCount=this.readUint32(),this.flags&1&&(this.dataOffset=this.readUint32()),this.flags&4&&(this.firstSampleFlags=this.readUint32());for(let r=0;r<this.sampleCount;r++)this.flags&256&&this.sampleDuration.push(this.readUint32()),this.flags&512&&this.sampleSize.push(this.readUint32()),this.flags&1024&&this.sampleFlags.push(this.readUint32()),this.flags&2048&&this.sampleCompositionTimeOffset.push(this.readUint32())}};var za=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ya=class extends Z{constructor(e,t){super(e,t),this.valid&&(this.entryCount=this.readUint32(),this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+4,this.content.byteLength-4)))}};var Ka=class extends Q{constructor(e,t){super(e,t),this.valid&&(this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+78,this.content.byteLength-78)))}};var QM={ftyp:ka,moov:La,mvhd:$a,moof:Ma,mdat:Da,sidx:xi,trak:Ca,mdia:Fa,mfhd:Ha,tkhd:Na,traf:ja,tfhd:Qa,tfdt:Wa,trun:Ga,minf:qa,sv3d:Ba,st3d:Va,prhd:_a,proj:Ua,equi:Oa,uuid:Ra,stbl:za,stsd:Ya,avc1:Ka,unknown:br},kt=class a{constructor(e={}){this.options={offset:0,...e}}parse(e){let t=[],i=this.options.offset;for(;i<e.byteLength;){let s=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+i+4,4)),n;try{n=this.createBox(s,new DataView(e.buffer,e.byteOffset+i,e.byteLength-i))}catch(u){if(!(u instanceof RangeError))throw u}if(!n||!io(n))break;t.push(n),i+=n.size}return t}createBox(e,t){let i=QM[e];return i?new i(t,new a):new br(t,new a)}};var Wt=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{io(t)&&(this.index[t.type]??=[],this.index[t.type].push(t),t.children.length>0&&this.indexBoxLevel(t.children))})}find(e){return this.index[e]&&this.index[e][0]?this.index[e][0]:null}findAll(e){return this.index[e]||[]}};var GM=new TextDecoder("ascii"),zM=a=>GM.decode(new DataView(a.buffer,a.byteOffset+4,4))==="ftyp",YM=a=>{let e=new xi(a,new kt),t=e.earliestPresentationTime/e.timescale*1e3,i=a.byteOffset+a.byteLength+e.firstOffset;return e.segments.map(s=>{if(s.referenceType!==0)throw new Error("Unsupported multilevel sidx");let n=s.subsegmentDuration/e.timescale*1e3,u={status:"none",time:{from:t,to:t+n},byte:{from:i,to:i+s.referencedSize-1}};return t+=n,i+=s.referencedSize,u})},KM=(a,e)=>{let i=new kt().parse(a),r=new Wt(i),s=r.findAll("moof"),n=e?r.findAll("uuid"):r.findAll("mdat");if(!(n.length&&s.length))return null;let u=s[0],o=n[n.length-1],l=u.source.byteOffset,d=o.source.byteOffset-u.source.byteOffset+o.size;return new DataView(a.buffer,l,d)},XM=a=>{let t=new kt().parse(a),i=new Wt(t),r={},s=i.findAll("uuid"),n=(0,Kv.default)(s,-1);return n?{serverDataReceivedTimestamp:n.userData.received,serverDataPreparedTime:n.userData.received}:r},JM=a=>{let t=new kt().parse(a);return new Wt(t).find("sidx")?.timescale},ZM=(a,e)=>{let i=new kt().parse(a),s=new Wt(i).findAll("traf"),n=s[s.length-1].children.find(d=>d.type==="tfhd"),u=s[s.length-1].children.find(d=>d.type==="tfdt"),o=s[s.length-1].children.find(d=>d.type==="trun"),l=0;return o.sampleDuration.length?l=o.sampleDuration.reduce((d,c)=>d+c,0):l=n.defaultSampleDuration*o.sampleCount,(Number(u.baseMediaDecodeTime)+l)/e*1e3},eD=a=>{let e={is3dVideo:!1,stereoMode:0,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}},i=new kt().parse(a),r=new Wt(i);if(r.find("sv3d")){e.is3dVideo=!0;let n=r.find("st3d");n&&(e.stereoMode=n.stereoMode);let u=r.find("prhd");u&&(e.projectionData.pose.yaw=u.poseYawDegrees,e.projectionData.pose.pitch=u.posePitchDegrees,e.projectionData.pose.roll=u.poseRollDegrees);let o=r.find("equi");o&&(e.projectionData.bounds.top=o.projectionBoundsTop,e.projectionData.bounds.right=o.projectionBoundsRight,e.projectionData.bounds.bottom=o.projectionBoundsBottom,e.projectionData.bounds.left=o.projectionBoundsLeft)}return e},Xv={validateData:zM,parseInit:eD,getIndexRange:()=>{},parseSegments:YM,parseFeedableSegmentChunk:KM,getChunkEndTime:ZM,getServerLatencyTimestamps:XM,getTimescaleFromIndex:JM};var Za=C(De(),1);import{assertNonNullable as Ec,isNonNullable as ty,isNullable as iD}from"@vkontakte/videoplayer-shared/es2024";import{assertNever as tD}from"@vkontakte/videoplayer-shared/es2024";var Jv={440786851:{type:"master"},17030:{type:"uint"},17143:{type:"uint"},17138:{type:"uint"},17139:{type:"uint"},17026:{type:"string"},17031:{type:"uint"},17029:{type:"uint"},236:{type:"binary"},408125543:{type:"master"},290298740:{type:"master"},19899:{type:"master"},21419:{type:"binary"},21420:{type:"uint"},357149030:{type:"master"},2807729:{type:"uint"},17545:{type:"float"},374648427:{type:"master"},174:{type:"master"},224:{type:"master"},30320:{type:"master"},30321:{type:"uint"},30322:{type:"master"},272869232:{type:"master"},524531317:{type:"master"},231:{type:"uint"},22612:{type:"master"},22743:{type:"uint"},167:{type:"uint"},171:{type:"uint"},163:{type:"binary"},160:{type:"master"},175:{type:"binary"},423732329:{type:"master"},307544935:{type:"master"},475249515:{type:"master"},187:{type:"master"},179:{type:"uint"},183:{type:"master"},247:{type:"uint"},241:{type:"uint"},240:{type:"uint"},178:{type:"uint"},21368:{type:"uint"},234:{type:"uint"},219:{type:"master"},150:{type:"uint"}},Zv=a=>{let e=a.getUint8(0),t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);let i=Ja(a,t),r=i in Jv,s=r?Jv[i].type:"binary",n=a.getUint8(t),u=0;n&128?u=1:n&64?u=2:n&32?u=3:n&16?u=4:n&8?u=5:n&4?u=6:n&2?u=7:n&1&&(u=8);let o=new DataView(a.buffer,a.byteOffset+t+1,u-1),l=n&255>>u,p=Ja(o),d=l*2**((u-1)*8)+p,c=t+u,h;return c+d>a.byteLength?h=new DataView(a.buffer,a.byteOffset+c):h=new DataView(a.buffer,a.byteOffset+c,d),{tag:r?i:"0x"+i.toString(16).toUpperCase(),type:s,tagHeaderSize:c,tagSize:c+d,value:h,valueSize:d}},Ja=(a,e=a.byteLength)=>{switch(e){case 1:return a.getUint8(0);case 2:return a.getUint16(0);case 3:return a.getUint8(0)*2**16+a.getUint16(1);case 4:return a.getUint32(0);case 5:return a.getUint8(0)*2**32+a.getUint32(1);case 6:return a.getUint16(0)*2**32+a.getUint32(2);case 7:{let t=a.getUint8(0)*281474976710656+a.getUint16(1)*4294967296+a.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},st=(a,e)=>{switch(e){case"int":return a.getInt8(0);case"uint":return Ja(a);case"float":return a.byteLength===4?a.getFloat32(0):a.getFloat64(0);case"string":return new TextDecoder("ascii").decode(a);case"utf8":return new TextDecoder("utf-8").decode(a);case"date":return new Date(Date.UTC(2001,0)+a.getInt8(0)).getTime();case"master":return a;case"binary":return a;default:tD(e)}},wi=(a,e)=>{let t=0;for(;t<a.byteLength;){let i=new DataView(a.buffer,a.byteOffset+t),r=Zv(i);if(!e(r))return;r.type==="master"&&wi(r.value,e),t=r.value.byteOffset-a.byteOffset+r.valueSize}},ey=a=>{if(a.getUint32(0)!==440786851)return!1;let e,t,i,r=Zv(a);return wi(r.value,({tag:s,type:n,value:u})=>(s===17143?e=st(u,n):s===17026?t=st(u,n):s===17029&&(i=st(u,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)};var iy=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],rD=[231,22612,22743,167,171,163,160,175],aD=a=>{let e,t,i,r,s=!1,n=!1,u=!1,o,l,p=!1,d=0;return wi(a,({tag:c,type:h,value:f,valueSize:m})=>{if(c===21419){let g=st(f,h);l=Ja(g)}else c!==21420&&(l=void 0);return c===408125543?(e=f.byteOffset,t=f.byteOffset+m):c===357149030?s=!0:c===290298740?n=!0:c===2807729?i=st(f,h):c===17545?r=st(f,h):c===21420&&l===475249515?o=st(f,h):c===374648427?wi(f,({tag:g,type:S,value:v})=>g===30321?(p=st(v,S)===1,!1):!0):s&&n&&(0,Za.default)(iy,c)&&(u=!0),!u}),Ec(e,"Failed to parse webm Segment start"),Ec(t,"Failed to parse webm Segment end"),Ec(r,"Failed to parse webm Segment duration"),i=i??1e6,{segmentStart:Math.round(e/1e9*i*1e3),segmentEnd:Math.round(t/1e9*i*1e3),timeScale:i,segmentDuration:Math.round(r/1e9*i*1e3),cuesSeekPosition:o,is3dVideo:p,stereoMode:d,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},sD=a=>{if(iD(a.cuesSeekPosition))return;let e=a.segmentStart+a.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},nD=(a,e)=>{let t=!1,i=!1,r=u=>ty(u.time)&&ty(u.position),s=[],n;return wi(a,({tag:u,type:o,value:l})=>{switch(u){case 475249515:t=!0;break;case 187:n&&r(n)&&s.push(n),n={};break;case 179:n&&(n.time=st(l,o));break;case 183:break;case 241:n&&(n.position=st(l,o));break;default:t&&(0,Za.default)(iy,u)&&(i=!0)}return!(t&&i)}),n&&r(n)&&s.push(n),s.map((u,o)=>{let{time:l,position:p}=u,d=s[o+1];return{status:"none",time:{from:l,to:d?d.time:e.segmentDuration},byte:{from:e.segmentStart+p,to:d?e.segmentStart+d.position-1:e.segmentEnd-1}}})},oD=a=>{let e=0,t=!1;try{wi(a,i=>i.tag===524531317?i.tagSize<=a.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):(0,Za.default)(rD,i.tag)?(e+i.tagSize<=a.byteLength&&(e+=i.tagSize,t||=(0,Za.default)([163,160,175],i.tag)),!0):!1)}catch{}return e>0&&e<=a.byteLength&&t?new DataView(a.buffer,a.byteOffset,e):null},ry={validateData:ey,parseInit:aD,getIndexRange:sD,parseSegments:nD,parseFeedableSegmentChunk:oD};var yt=a=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(a);if(e){let[,t,i]=e;if(t==="audio"||t==="video")switch(i){case"webm":return ry;case"mp4":return Xv}}throw new ReferenceError(`Unsupported mime type ${a}`)};var Tt=a=>a instanceof DOMException&&(a.name==="AbortError"||a.code===20);var Lc=C(Ay(),1),zy=C(Yi(),1),Yy=C(Uy(),1),Ky=C(at(),1),$c=C(pi(),1);var Hy=C(De(),1),kc=a=>{let e=a.split("."),[t,...i]=e;if(!t)return!1;switch(t){case"av01":{let[r,s,n]=i;return!!(n&&parseInt(n,10)>8)}case"vp09":{let[r,s,n]=i;return!!(r&&parseInt(r,10)>=2&&n&&parseInt(n,10)>8)}case"avc1":{let r=i[0];if(!r||r.length!==6)return!1;let[s,n]=r.toUpperCase(),u=s+n;return(0,Hy.default)(["6E","7A","F4"],u)}}return!1};import{isNonNullable as oC,isNullable as Wy}from"@vkontakte/videoplayer-shared/es2024";var jy=a=>{if(a.includes("/")){let e=a.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(a)};var Qy=a=>{try{let e=nC(),t=a.match(e),{groups:i}=t??{};if(i){let r={};if(i.extensions){let u=i.extensions.toLowerCase().match(/(?:[0-9a-wy-z](?:-[a-z0-9]{2,8})+)/g);Array.from(u||[]).forEach(o=>{r[o[0]]=o.slice(2)})}let s=i.variants?.split(/-/).filter(u=>u!==""),n={extlang:i.extlang,langtag:i.langtag,language:i.language,privateuse:i.privateuse||i.privateuse2,region:i.region,script:i.script,extensions:r,variants:s};return Object.keys(n).forEach(u=>{let o=n[u];(typeof o>"u"||o==="")&&delete n[u]}),n}return null}catch{return null}};function nC(){let a="(?<extlang>(?:[a-z]{3}(?:-[a-z]{3}){0,2}))",e="x(?:-[a-z0-9]{1,8})+",p=`^(?:(?<langtag>${`
118
118
  (?<language>${`(?:[a-z]{2,3}(?:-${a})?|[a-z]{4}|[a-z]{5,8})`})
119
119
  (-(?<script>[a-z]{4}))?
120
120
  (-(?<region>(?:[a-z]{2}|[0-9]{3})))?
121
121
  (?<variants>(?:-(?:[a-z0-9]{5,8}|[0-9][a-z0-9]{3}))*)
122
122
  (?<extensions>(?:-[0-9a-wy-z](?:-[a-z0-9]{2,8})+)*)
123
123
  (?:-(?<privateuse>(?:${e})))?
124
- `})|(?<privateuse2>${e}))$`.replace(/[\s\t\n]/g,"");return new RegExp(c,"i")}var jy=a=>{if(!a?.startsWith("P"))return;let e=(n,u)=>{let o=n?parseFloat(n.replace(",",".")):NaN;return(isNaN(o)?0:o)*u},i=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(a),r=i?.[1]==="-"?-1:1,s={days:e(i?.[5],r),hours:e(i?.[6],r),minutes:e(i?.[7],r),seconds:e(i?.[8],r)};return s.days*24*60*60*1e3+s.hours*60*60*1e3+s.minutes*60*1e3+s.seconds*1e3},nt=(a,e)=>{let t=a;t=(0,wc.default)(t,"$$","$");let i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[r,s]of(0,Qy.default)(i)){let n=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=(0,wc.default)(t,n,(u,o)=>Hy(s)?u:Hy(o)?s:(0,Wy.default)(s,parseInt(o,10),"0"))}return t},Yn=(a,e)=>{let i=new DOMParser().parseFromString(a,"application/xml"),r={video:[],audio:[],text:[]},s=i.children[0],n=Array.from(s.querySelectorAll("MPD > BaseURL").values()).map(R=>R.textContent?.trim()??""),u=(0,Gy.default)(n,0)??"",o=s.getAttribute("type")==="dynamic",l=s.getAttribute("availabilityStartTime"),c=s.getAttribute("publishTime"),p=s.getElementsByTagName("vk:Attrs")[0],d=p?.getElementsByTagName("vk:XLatestSegmentPublishTime")[0].textContent,h=p?.getElementsByTagName("vk:XStreamIsLive")[0].textContent,f=p?.getElementsByTagName("vk:XStreamIsUnpublished")[0].textContent,b=p?.getElementsByTagName("vk:XPlaybackDuration")[0].textContent,S;o&&(S={availabilityStartTime:l?new Date(l).getTime():0,publishTime:c?new Date(c).getTime():0,latestSegmentPublishTime:d?new Date(d).getTime():0,streamIsAlive:h==="yes",streamIsUnpublished:f==="yes"});let g,I=s.getAttribute("mediaPresentationDuration"),x=[...s.getElementsByTagName("Period")],y=x.reduce((R,T)=>({...R,[T.id]:T.children}),{}),w=x.reduce((R,T)=>({...R,[T.id]:T.getAttribute("duration")}),{});I?g=jy(I):(0,Ac.default)(w).filter(R=>R).length&&!o?g=(0,Ac.default)(w).reduce((R,T)=>R+(jy(T)??0),0):b&&(g=parseInt(b,10));let D=0,L=s.getAttribute("profiles")?.split(",")??[];for(let R of x.map(T=>T.id))for(let T of y[R]){let q=T.getAttribute("id")??"id"+(D++).toString(10),$=T.getAttribute("mimeType")??"",v=T.getAttribute("codecs")??"",E=T.getAttribute("contentType")??$?.split("/")[0],z=T.getAttribute("profiles")?.split(",")??[],M=Uy(T.getAttribute("lang")??"")??{},H=T.querySelector("Label")?.textContent?.trim()??void 0,J=T.querySelectorAll("Representation"),ie=T.querySelector("SegmentTemplate"),ue=T.querySelector("Role")?.getAttribute("value")??void 0,fe=E,me={id:q,language:M.language,isDefault:ue==="main",label:H,codecs:v,hdr:fe==="video"&&xc(v),mime:$,representations:[]};for(let j of J){let U=j.getAttribute("lang")??void 0,ke=H??T.getAttribute("label")??j.getAttribute("label")??void 0,Te=j.querySelector("BaseURL")?.textContent?.trim()??"",le=new URL(Te||u,e).toString(),We=j.getAttribute("mimeType")??$,Bt=j.getAttribute("codecs")??v??"",lt;if(E==="text"){let Oe=j.getAttribute("id")||"",Vt=M.privateuse?.includes("x-auto")||Oe.includes("_auto"),ct=j.querySelector("SegmentTemplate");if(ct){let Br={representationId:j.getAttribute("id")??void 0,bandwidth:j.getAttribute("bandwidth")??void 0},Ps=parseInt(j.getAttribute("bandwidth")??"",10)/1e3,ks=parseInt(ct.getAttribute("startNumber")??"",10)??1,Di=parseInt(ct.getAttribute("timescale")??"",10),Go=ct.querySelectorAll("SegmentTimeline S")??[],Ci=ct.getAttribute("media");if(!Ci)continue;let Rs=[],Ls=0,$s="",Bi=0,Vr=ks,Ie=0;for(let Je of Go){let ii=parseInt(Je.getAttribute("d")??"",10),Ge=parseInt(Je.getAttribute("r")??"",10)||0,_t=parseInt(Je.getAttribute("t")??"",10);Ie=Number.isFinite(_t)?_t:Ie;let ri=ii/Di*1e3,Vi=Ie/Di*1e3;for(let dt=0;dt<Ge+1;dt++){let Ot=nt(Ci,{...Br,segmentNumber:Vr.toString(10),segmentTime:(Ie+dt*ii).toString(10)}),_i=(Vi??0)+dt*ri,Or=_i+ri;Vr++,Rs.push({time:{from:_i,to:Or},url:Ot})}Ie+=(Ge+1)*ii,Ls+=(Ge+1)*ri}Bi=Ie/Di*1e3,$s=nt(Ci,{...Br,segmentNumber:Vr.toString(10),segmentTime:Ie.toString(10)});let _r={time:{from:Bi,to:1/0},url:$s},Et={type:"template",baseUrl:le,segmentTemplateUrl:Ci,initUrl:"",totalSegmentsDurationMs:Ls,segments:Rs,nextSegmentBeyondManifest:_r,timescale:Di};lt={id:Oe,kind:"text",segmentReference:Et,profiles:[],duration:g,bitrate:Ps,mime:"",codecs:"",width:0,height:0,isAuto:Vt}}else lt={id:Oe,isAuto:Vt,kind:"text",url:le}}else{let Oe=j.getAttribute("contentType")??We?.split("/")[0]??E,Vt=T.getAttribute("profiles")?.split(",")??[],ct=parseInt(j.getAttribute("width")??"",10),Br=parseInt(j.getAttribute("height")??"",10),Ps=parseInt(j.getAttribute("bandwidth")??"",10)/1e3,ks=j.getAttribute("frameRate")??"",Di=j.getAttribute("quality")??void 0,Go=ks?qy(ks):void 0,Ci=j.getAttribute("id")??"id"+(D++).toString(10),Rs=Oe==="video"?`${Br}p`:Oe==="audio"?`${Ps}Kbps`:Bt,Ls=`${Ci}@${Rs}`,$s=[...L,...z,...Vt],Bi,Vr=j.querySelector("SegmentBase"),Ie=j.querySelector("SegmentTemplate")??ie;if(Vr){let Et=j.querySelector("SegmentBase Initialization")?.getAttribute("range")??"",[Je,ii]=Et.split("-").map(Ot=>parseInt(Ot,10)),Ge={from:Je,to:ii},_t=j.querySelector("SegmentBase")?.getAttribute("indexRange"),[ri,Vi]=_t?_t.split("-").map(Ot=>parseInt(Ot,10)):[],dt=_t?{from:ri,to:Vi}:void 0;Bi={type:"byteRange",url:le,initRange:Ge,indexRange:dt}}else if(Ie){let Et={representationId:j.getAttribute("id")??void 0,bandwidth:j.getAttribute("bandwidth")??void 0},Je=parseInt(Ie.getAttribute("timescale")??"",10),ii=Ie.getAttribute("initialization")??"",Ge=Ie.getAttribute("media"),_t=parseInt(Ie.getAttribute("startNumber")??"",10)??1,ri=nt(ii,Et);if(!Ge)throw new ReferenceError("No media attribute in SegmentTemplate");let Vi=Ie.querySelectorAll("SegmentTimeline S")??[],dt=[],Ot=0,_i="",Or=0;if(Vi.length){let Ms=_t,Ze=0;for(let Oi of Vi){let pt=parseInt(Oi.getAttribute("d")??"",10),ai=parseInt(Oi.getAttribute("r")??"",10)||0,Ds=parseInt(Oi.getAttribute("t")??"",10);Ze=Number.isFinite(Ds)?Ds:Ze;let zo=pt/Je*1e3,_I=Ze/Je*1e3;for(let Cs=0;Cs<ai+1;Cs++){let OI=nt(Ge,{...Et,segmentNumber:Ms.toString(10),segmentTime:(Ze+Cs*pt).toString(10)}),Fd=(_I??0)+Cs*zo,FI=Fd+zo;Ms++,dt.push({time:{from:Fd,to:FI},url:OI})}Ze+=(ai+1)*pt,Ot+=(ai+1)*zo}Or=Ze/Je*1e3,_i=nt(Ge,{...Et,segmentNumber:Ms.toString(10),segmentTime:Ze.toString(10)})}else if(nC(g)){let Ze=parseInt(Ie.getAttribute("duration")??"",10)/Je*1e3,Oi=Math.ceil(g/Ze),pt=0;for(let ai=1;ai<Oi;ai++){let Ds=nt(Ge,{...Et,segmentNumber:ai.toString(10),segmentTime:pt.toString(10)});dt.push({time:{from:pt,to:pt+Ze},url:Ds}),pt+=Ze}Or=pt,_i=nt(Ge,{...Et,segmentNumber:Oi.toString(10),segmentTime:pt.toString(10)})}let VI={time:{from:Or,to:1/0},url:_i};Bi={type:"template",baseUrl:le,segmentTemplateUrl:Ge,initUrl:ri,totalSegmentsDurationMs:Ot,segments:dt,nextSegmentBeyondManifest:VI,timescale:Je}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!Oe||!We)continue;let _r={video:"video",audio:"audio",text:"text"}[Oe];if(!_r)continue;fe||=_r,lt={id:Ls,kind:_r,segmentReference:Bi,profiles:$s,duration:g,bitrate:Ps,mime:We,codecs:Bt,width:ct,height:Br,fps:Go,quality:Di}}me.language||=U,me.label||=ke,me.mime||=We,me.codecs||=Bt,me.hdr||=fe==="video"&&xc(Bt),me.representations.push(lt)}if(fe){let j=r[fe].find(U=>U.id===me.id);if(j&&me.representations.every(U=>U.segmentReference.type==="template"))for(let U of j.representations){let Te=me.representations.find(We=>We.id===U.id)?.segmentReference,le=U.segmentReference;le.segments.push(...Te.segments),le.nextSegmentBeyondManifest=Te.nextSegmentBeyondManifest}else r[fe].push(me)}}return{duration:g,streams:r,baseUrls:n,live:S}};var Pc=C(at(),1);import{videoSizeToQuality as oC}from"@vkontakte/videoplayer-shared/es2024";var zy=({id:a,width:e,height:t,bitrate:i,fps:r,quality:s,streamId:n})=>{let u=(s?jt(s):void 0)??oC({width:e,height:t});return u&&{id:a,quality:u,bitrate:i,size:{width:e,height:t},fps:r,streamId:n}},Yy=({id:a,bitrate:e})=>({id:a,bitrate:e}),Ky=({language:a,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:a,label:e}),Xy=({language:a,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:a,label:e}),kc=({id:a,language:e,label:t,codecs:i,isDefault:r})=>({id:a,language:e,label:t,codec:(0,Pc.default)(i.split("."),0),isDefault:r}),Rc=({id:a,language:e,label:t,hdr:i,codecs:r})=>({id:a,language:e,hdr:i,label:t,codec:(0,Pc.default)(r.split("."),0)}),Lc=a=>"url"in a,He=a=>a.type==="template";import{isNonNullable as Jy}from"@vkontakte/videoplayer-shared/es2024";var V=(a,e)=>Jy(a)&&Jy(e)&&a.readyState==="open"&&uC(a,e);function uC(a,e){for(let t=0;t<a.activeSourceBuffers.length;++t)if(a.activeSourceBuffers[t]===e)return!0;return!1}var Za=class{constructor(e,t,i,{fetcher:r,tuning:s,getCurrentPosition:n,isActiveLowLatency:u,compatibilityMode:o=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new Ei(0);this.currentLowLatencySegmentLength$=new Ei(0);this.currentSegmentLength$=new Ei(0);this.onLastSegment$=new Ei(!1);this.fullyBuffered$=new Ei(!1);this.playingRepresentation$=new Ei(void 0);this.playingRepresentationInit$=new Ei(void 0);this.error$=new cC;this.gaps=[];this.subscription=new dC;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new X;this.switchAbortController=new X;this.destroyAbortController=new X;this.bufferLimit=1/0;this.failedDownloads=0;this.baseUrls=[];this.baseUrlsIndex=0;this.isLive=!1;this.liveUpdateSegmentIndex=0;this.liveInitialAdditionalOffset=0;this.isSeekingLive=!1;this.index=0;this.lastDataObtainedTimestampMs=0;this.loadByteRangeSegmentsTimeoutId=0;this.startWith=Gt(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);Ve(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new Wv(this.sourceBuffer),this.subscription.add($c(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let u,o=this.mediaSource.readyState;o!=="open"&&(u={id:`SegmentEjection_source_${o}`,category:Lt.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),u??={id:"SegmentEjection",category:Lt.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n},this.error$.next(u)})),this.subscription.add($c(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:Lt.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,hr(this.sourceBuffer.buffered)*.8);this.bufferLimit=o;let l=this.getForwardBufferDuration(u),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(u,n*2,l<c).catch(p=>{this.handleAsyncError(p,"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);Ve(i,"No init buffer for starting representation"),Ve(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=Gt(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);Ve(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if(ve(s)||ve(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),Ve(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();Sr(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=Gt(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);Ve(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if(ve(s)||ve(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),Ve(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();Sr(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=Gt(this.destroyAbortController.signal,async function*(e){let t=(0,Jn.default)(e,o=>o.representations)??[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let o of this.representations.keys()){let l=t.find(d=>d.id===o);l&&this.representations.set(o,l);let c=this.representations.get(o);if(!c||!He(c.segmentReference))return;let p=this.getActualLiveStartingSegments(c.segmentReference);this.segments.set(c.id,p)}let i=this.switchingToRepresentationId??this.downloadingRepresentationId,r=this.representations.get(i);Ve(r);let s=this.segments.get(i);Ve(s,"No segments for starting representation");let n=this.initData.get(i);if(Ve(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(c=>[c.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(i.map(c=>[c.id,c])),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,Gt(this.switchAbortController.signal,async function*(i,r=!1){this.switchingToRepresentationId=i;let s=this.representations.get(i);Ve(s,`No such representation ${i}`);let n=this.segments.get(i),u=this.initData.get(i);if(ve(u)||ve(n)?yield this.loadInit(s,"high",!1):u instanceof Promise&&(yield u),n=this.segments.get(i),Ve(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();Sr(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(){!ve(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(ve(e)||ve(this.downloadingRepresentationId)||ve(this.playingRepresentationId)||ve(this.sourceBuffer)||!V(this.mediaSource,this.sourceBuffer)||Sr(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if(Ve(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;let r=i.find(c=>e>=c.time.from&&e<c.time.to);Sr(r)&&isFinite(r.time.from)&&isFinite(r.time.to)&&this.currentSegmentLength$.next(r?.time.to-r.time.from);let s=e,n=100;if(this.playingRepresentationId!==this.downloadingRepresentationId){let c=this.getForwardBufferDuration(e),p=r?r.time.to+n:-1/0;r&&r.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&c>=r.time.to-e+n&&(s=p)}if(isFinite(this.bufferLimit)&&hr(this.sourceBuffer.buffered)>=this.bufferLimit){let c=this.getForwardBufferDuration(e),p=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,c<p).catch(d=>{this.handleAsyncError(d,"pruneBuffer")});return}let o=[];if(!this.activeSegments.size&&(o=this.selectForwardBufferSegments(i,t.segmentReference.type,s),o.length)){let c="auto";if(this.tuning.dash.useFetchPriorityHints&&r)if((0,Xn.default)(o,r))c="high";else{let p=(0,xi.default)(o,0);p&&p.time.from-r.time.to>=this.forwardBufferTarget/2&&(c="low")}this.loadSegments(o,t,c).catch(p=>{this.handleAsyncError(p,"loadSegments")})}(!this.preloadOnly&&!this.allInitsLoaded&&r&&r.status==="fed"&&!o.length&&this.getForwardBufferDuration(e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let l=(0,xi.default)(i,-1);!this.isLive&&l&&(this.fullyBuffered$.next(l.time.to-e-this.getForwardBufferDuration(e)<n),this.onLastSegment$.next(e-l.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}),i=s.time.to;Sr(t.duration)&&t.duration-i>0&&!this.isLive&&this.gaps.push({representation:t.id,from:i,to:t.duration})}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,Jn.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,Jn.default)(e?.streams[this.kind],i=>i.representations)??[];if(![...this.segments.values()].every(i=>!i.length))for(let i of t){if(!i||!He(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,xi.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;Ve(e);let t=this.segments.get(e);if(t?.length){let i=t[t.length-1];this.updateLowLatencyLiveIfNeeded(i)}}calculateDurationFromSegments(){if(!this.playingRepresentationId)return 0;let e=this.segments.get(this.playingRepresentationId);return(e?(0,xi.default)(e,-1)?.time.to:0)||0}updateLowLatencyLiveIfNeeded(e){let t=0;for(let i of this.representations.values()){let r=i.segmentReference;if(!He(r))return;let s=this.segments.get(i.id)??[],n=s.find(o=>Math.floor(o.time.from)===Math.floor(e.time.from));if(n&&!isFinite(n.time.to)&&(n.time.to=e.time.to,t=n.time.to-n.time.from),!!!s.find(o=>Math.floor(o.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let o=Math.round(e.time.to*r.timescale/1e3).toString(10),l=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.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.isLive?this.selectForwardBufferSegmentsLive(e,i):this.selectForwardBufferSegmentsRecord(e,t,i)}selectForwardBufferSegmentsLive(e,t){let i=e.findIndex(r=>t>=r.time.from&&t<r.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=i),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,i){let r=this.getForwardBufferDuration(i),s=e.findIndex(({status:d,time:{from:h,to:f}},b)=>{let S=h<=i&&f>=i,g=h>i||S||b===0&&i===0,I=Math.min(this.forwardBufferTarget,this.bufferLimit),x=this.preloadOnly&&h<=i+I||r<I&&f-h>=I||f<=i+I;return(d==="none"||d==="partially_ejected"&&g&&x&&this.sourceBuffer&&V(this.mediaSource,this.sourceBuffer)&&!(Se(this.sourceBuffer.buffered,h)&&Se(this.sourceBuffer.buffered,f)))&&g&&x});if(s===-1)return[];if(t!=="byteRange")return e.slice(s,s+1);let n=e,u=0,o=0,l=[],c=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,p=this.preloadOnly?this.forwardBufferTarget:0;for(let d=s;d<n.length&&(u<=c||o<=p);d++){let h=n[d];if(u+=h.byte.to+1-h.byte.from,o+=h.time.to+1-h.time.from,h.status==="none"||h.status==="partially_ejected")l.push(h);else break}return l}async loadSegments(e,t,i="auto"){He(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 Gt(u,async function*(){let c=Mc(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(p=>setTimeout(p,c))}.bind(this))(),u.aborted&&this.abortActiveSegments([e]));try{let c=await this.fetcher.fetch(n,{range:s,signal:u,onProgress:o,priority:i,isLowLatency:this.isActiveLowLatency(),bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation});if(this.lastDataObtainedTimestampMs=Kn(),!c)return;let p=new DataView(c),d=yt(t.mime);if(!isFinite(r.segment.time.to)){let b=t.segmentReference.timescale;r.segment.time.to=d.getChunkEndTime(p,b)}o&&r.feedingBytes&&l?await Promise.all(l):await this.sourceBufferTaskQueue.append(p,u);let{serverDataReceivedTimestamp:h,serverDataPreparedTime:f}=d.getServerLatencyTimestamps(p);h&&f&&this.currentLiveSegmentServerLatency$.next(f-h),r.segment.status="downloaded",this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(c){this.abortActiveSegments([e]),Tt(c)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}updateRepresentationsBaseUrlIfNeeded(){if(!this.tuning.dash.enableBaseUrlSupport||!this.baseUrls.length||this.failedDownloads<=this.tuning.dash.maxSegmentRetryCount)return;this.baseUrlsIndex=(this.baseUrlsIndex+1)%this.baseUrls.length;let e=this.baseUrls[this.baseUrlsIndex];for(let t of this.representations.values())He(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 Gt(n,async function*(){let o=Mc(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,o),$c(window,"online").pipe(lC()).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=Kn(),this.failedDownloads=0}catch(o){this.abortActiveSegments(e),Tt(o)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}prepareByteRangeFetchSegmentParams(e,t){if(He(t.segmentReference))throw new Error("Representation is not byte range type");let i=t.segmentReference.url,r={from:(0,xi.default)(e,0).byte.from,to:(0,xi.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=Kn(),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:Lt.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!He(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,c)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=Kn();let p=this.onSomeTemplateDataLoaded({dataView:l,loaded:c,signal:s,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(p)}catch(p){this.error$.next({id:"SegmentFeeding",category:Lt.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:p})}}:void 0;return{url:r,signal:s,onProgress:o,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)(0,Xn.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),c=yt(n.mime).parseFeedableSegmentChunk(l,this.isLive);c?.byteLength&&(o.status="partially_fed",u.feedingBytes+=c.byteLength,await this.sourceBufferTaskQueue.append(c),u.fedBytes+=c.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){let{segment:l}=o;if(o.representationId!==t)continue;if(s.aborted){await n();continue}let c=l.byte.from-i,p=l.byte.to-i,d=p-c+1,h=c<r,f=p<=r;if(!h)continue;let b=yt(u.mime);if(l.status==="downloading"&&f){l.status="downloaded";let S=new DataView(e.buffer,e.byteOffset+c,d);await this.sourceBufferTaskQueue.append(S,s)&&!s.aborted?this.onSegmentFullyAppended(o,t):await n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(l.status==="downloading"||l.status==="partially_fed")&&(o.loadedBytes=Math.min(d,r-c),o.loadedBytes>o.feedingBytes)){let S=new DataView(e.buffer,e.byteOffset+c+o.feedingBytes,o.loadedBytes-o.feedingBytes),g=o.loadedBytes===d?S:b.parseFeedableSegmentChunk(S);g?.byteLength&&(l.status="partially_fed",o.feedingBytes+=g.byteLength,await this.sourceBufferTaskQueue.append(g,s)&&!s.aborted?(o.fedBytes+=g.byteLength,o.fedBytes===d&&this.onSegmentFullyAppended(o,t)):await n())}}}onSegmentFullyAppended(e,t){if(!(ve(this.sourceBuffer)||!V(this.mediaSource,this.sourceBuffer))){!this.isLive&&B.browser.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(Se(this.sourceBuffer.buffered,e.segment.time.from,100)&&Se(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:Lt.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",Lc(e.segment)&&(e.segment.size=e.fedBytes);for(let i of this.representations.values())if(i.id!==t)for(let r of this.segments.get(i.id)??[])r.status==="fed"&&Math.round(r.time.from)===Math.round(e.segment.time.from)&&Math.round(r.time.to)===Math.round(e.segment.time.to)&&(r.status="none");this.updateLowLatencyLiveIfNeeded(e.segment),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment])}}abortSegment(e){e.status==="partially_fed"?e.status="partially_ejected":e.status!=="partially_ejected"&&(e.status="none");for(let t of this.activeSegments.values())if(t.segment===e){this.activeSegments.delete(t);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(let[r,s]of this.initData.entries()){let n=s instanceof Promise;t||=n,s===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let i=this.representations.get(e);i&&(this.initLoadIdleCallback=pr(()=>(0,Zy.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?Gt(this.destroyAbortController.signal,async function*(){let u=Mc(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(async u=>{if(!u)return;let{init:o,dataView:l,segments:c}=u,p=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,p);let d=c;this.isLive&&He(e.segmentReference)&&(d=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,d),o&&this.parsedInitData.set(e.id,o)}).then(()=>this.failedDownloads=0,u=>{this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:Lt.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||ve(e))return!1;let r=[],s=0,n=o=>{o.sort((c,p)=>c.from-p.from);let l=[o[0]];for(let c=1;c<o.length;c++){let{from:p,to:d}=o[c],h=l[l.length-1];h.to>=p?h.to=Math.max(h.to,d):l.push(o[c])}return l},u=o=>{if(s>=t)return r;r.push({...o.time}),r=n(r);let l=Lc(o)?o.size??0:o.byte.to-o.byte.from;s+=l};for(let o of this.segments.values())for(let l of o){let c=l.time.to<=e-this.tuning.dash.bufferPruningSafeZone,p=l.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(c||p)&&l.status==="fed"&&u(l)}for(let o=0;o<this.sourceBuffer.buffered.length;o++){let l=this.sourceBuffer.buffered.start(o)*1e3,c=this.sourceBuffer.buffered.end(o)*1e3,p=0;for(let d of this.segments.values())for(let h of d)(0,Xn.default)(["none","partially_ejected"],h.status)&&Math.round(h.time.from)<=Math.round(l)&&Math.round(h.time.to)>=Math.round(c)&&p++;if(p===this.segments.size){let d={time:{from:l,to:c},url:"",status:"none"};u(d)}}if(r.length&&i){let o=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let l of this.segments.values())for(let c of l)c.time.from>=e+o&&c.status==="fed"&&u(c)}return r.length?(await Promise.all(r.map(l=>this.sourceBufferTaskQueue.remove(l.from,l.to)))).reduce((l,c)=>l||c,!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)}}getForwardBufferDuration(e=this.getCurrentPosition()){return!this.sourceBuffer||!V(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||ve(e)?0:he(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!(!this.sourceBuffer||!V(this.mediaSource,this.sourceBuffer))){if(this.tuning.useRefactoredSearchGap)for(let i=0;i<this.sourceBuffer.buffered.length;i++)this.gaps=this.gaps.filter(r=>this.sourceBuffer&&(Math.round(r.from)<Math.round(this.sourceBuffer.buffered.start(i)*1e3)||Math.round(r.to)>Math.round(this.sourceBuffer.buffered.end(i)*1e3)));for(let i of t){let r={representation:e,from:i.time.from,to:i.time.to};for(let s=0;s<this.sourceBuffer.buffered.length;s++){let n=this.sourceBuffer.buffered.start(s)*1e3,u=this.sourceBuffer.buffered.end(s)*1e3;if(!(u<=i.time.from||n>=i.time.to)){if(n<=i.time.from&&u>=i.time.to){r=void 0;break}u>i.time.from&&u<i.time.to&&(r.from=u),n<i.time.to&&n>i.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))){if(!this.tuning.useRefactoredSearchGap)for(let i=0;i<this.sourceBuffer.buffered.length;i++)this.gaps=this.gaps.filter(r=>this.sourceBuffer&&(Math.round(r.from)<Math.round(this.sourceBuffer.buffered.start(i)*1e3)||Math.round(r.to)>Math.round(this.sourceBuffer.buffered.end(i)*1e3)));this.gapDetectionIdleCallback=pr(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:Lt.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if(ve(this.sourceBuffer)||!V(this.mediaSource,this.sourceBuffer)||ve(this.playingRepresentationId))return;let e=[];for(let i=0;i<this.sourceBuffer.buffered.length;i++){let r=Math.floor(this.sourceBuffer.buffered.start(i)*1e3),s=Math.ceil(this.sourceBuffer.buffered.end(i)*1e3);e.push({from:r,to:s})}let t=100;for(let i of this.segments.values())for(let r of i){let{status:s}=r;if(s!=="fed"&&s!=="partially_ejected")continue;let n=Math.floor(r.time.from),u=Math.ceil(r.time.to),o=e.some(c=>c.from-t<=n&&c.to+t>=u),l=e.filter(c=>n>=c.from&&n<c.to-t||u>c.from+t&&u<=c.to);o||(l.length===1?r.status="partially_ejected":this.gaps.some(c=>c.from===r.time.from||c.to===r.time.to)?r.status="partially_ejected":r.status="none")}}handleAsyncError(e,t){this.error$.next({id:t,category:Lt.VIDEO_PIPELINE,thrown:e,message:"Something went wrong"})}};var zt=a=>{let e=new URL(a);return e.searchParams.set("quic","1"),e.toString()};var Zn=a=>{let e=a.get("X-Delivery-Type"),t=a.get("X-Reused"),i=e===null?"http1":e??void 0,r=t===null?void 0:{1:!0,0:!1}[t]??void 0;return{type:i,reused:r}};import{abortable as es,assertNever as eT,fromEvent as tT,merge as pC,now as ts,Subject as vr,ValueSubject as Dc,flattenObject as yr,ErrorCategory as is,SubscriptionRemovable as hC}from"@vkontakte/videoplayer-shared/es2024";var eo=a=>{let e=new URL(a);return e.searchParams.set("enable-subtitles","yes"),e.toString()};var io=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:s=!1}){this.manifestRequested=new vr;this.manifestReceived=new vr;this.firstBytesRequested=new vr;this.firstBytesReceived=new vr;this.lastConnectionType$=new Dc(void 0);this.lastConnectionReused$=new Dc(void 0);this.lastRequestFirstBytes$=new Dc(void 0);this.recoverableError$=new vr;this.error$=new vr;this.abortAllController=new X;this.subscription=new hC;this.fetchManifest=es(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=zt(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=eo(i)),this.manifestRequested.next();let r=yield this.doFetch(i,{signal:this.abortAllController.signal}).catch(to);return r?(t.log("success",yr({url:i,message:"Request successfully executed"})),t.end(),this.manifestReceived.next(),this.onHeadersReceived(r.headers),r.text()):(t.error("error",yr({url:i,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=es(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 c=e,p=new Headers,d=this.tracer.createComponentTracer("Fetch");if(i)switch(t){case 0:{p.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let v=new URL(c,location.href);v.searchParams.append("bytes",`${i.from}-${i.to}`),c=v.toString();break}default:eT(t)}this.requestQuic&&(c=zt(c));let h=this.abortAllController.signal,f;if(n){let v=new X;if(f=pC(tT(this.abortAllController.signal,"abort"),tT(n,"abort")).subscribe(()=>{try{v.abort()}catch(E){to(E)}}),this.subscription.add(f),this.abortAllController.signal.aborted||n.aborted)try{v.abort()}catch(E){to(E)}h=v.signal}let b=0,S=ts();d.log("startRequest",yr({url:c,priority:s,rangeMethod:t,range:i,isLowLatency:o,requestStartedAt:S})),this.firstBytesRequested.next();let g=yield this.doFetch(c,{priority:s,headers:p,signal:h}),I=ts();if(!g)return d.error("error",{message:"No response in request"}),d.end(),this.unsubscribeAbortSubscription(f),null;if(this.throughputEstimator?.addRawRtt(I-S),!g.ok||!g.body){this.unsubscribeAbortSubscription(f);let v=`Fetch error ${g.status}: ${g.statusText}`;return d.error("error",{message:v}),d.end(),Promise.reject(new Error(`Fetch error ${g.status}: ${g.statusText}`))}if(this.onHeadersReceived(g.headers),!r&&!u){this.unsubscribeAbortSubscription(f);let v=ts(),E={requestStartedAt:S,requestEndedAt:v,duration:v-S};return d.log("endRequest",yr(E)),d.end(),g.arrayBuffer()}let x=g.body;if(u){let v;[x,v]=g.body.tee(),this.throughputEstimator?.trackStream(v,o)}let y=x.getReader(),w,D=parseInt(g.headers.get("content-length")??"",10);Number.isFinite(D)&&(w=D),!w&&i&&(w=i.to-i.from+1);let L=w?new Uint8Array(w):new Uint8Array(0),A=!1,R=v=>{this.unsubscribeAbortSubscription(f),A=!0,to(v)},T=es(h,async function*({done:v,value:E}){if(b===0&&(this.lastRequestFirstBytes$.next(ts()-S),this.firstBytesReceived.next()),h.aborted){this.unsubscribeAbortSubscription(f);return}if(!v&&E){if(l&&w)L.set(E,b),b+=E.byteLength;else{let z=new Uint8Array(L.length+E.length);z.set(L),z.set(E,L.length),L=z,b+=E.byteLength}r?.(new DataView(L.buffer),b),yield y?.read().then(T,R)}}.bind(this));yield y?.read().then(T,R),this.unsubscribeAbortSubscription(f);let q=ts(),$={failed:A,requestStartedAt:S,requestEndedAt:q,duration:q-S};return A?(d.error("endRequest",yr($)),d.end(),null):(d.log("endRequest",yr($)),d.end(),L.buffer)}.bind(this));this.fetchByteRangeRepresentation=es(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,c;e.indexRange&&(l=e.indexRange.from,c=e.indexRange.to,o=s+1===l,o&&(n=Math.min(l,r),u=Math.max(c,s))),n=Math.min(n,0);let p=yield this.fetch(e.url,{range:{from:n,to:u},priority:i,measureThroughput:!1});if(!p)return null;let d=new DataView(p,r-n,s-n+1);if(!t.validateData(d))throw new Error("Invalid media file");let h=t.parseInit(d),f=e.indexRange??t.getIndexRange(h);if(!f)throw new ReferenceError("No way to load representation index");let b;if(o)b=new DataView(p,f.from-n,f.to-f.from+1);else{let g=yield this.fetch(e.url,{range:f,priority:i,measureThroughput:!1});if(!g)return null;b=new DataView(g)}let S=t.parseSegments(b,h,f);return{init:h,dataView:new DataView(p),segments:S}}.bind(this));this.fetchTemplateRepresentation=es(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}=Zn(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:eT(r)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}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:is.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:is.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:is.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:is.FATAL});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${s})`,category:is.FATAL})}}unsubscribeAbortSubscription(e){e&&(e.unsubscribe(),this.subscription.remove(e))}},to=a=>{if(!Tt(a))throw a};var $t=(a,e,t)=>t*e+(1-t)*a,Cc=(a,e)=>a.reduce((t,i)=>t+i,0)/e,iT=(a,e,t,i)=>{let r=0,s=t,n=Cc(a,e),u=e<i?e:i;for(let o=0;o<u;o++)a[s]>n?r++:r--,s=(a.length+s-1)%a.length;return Math.abs(r)===u};import{isNullable as fC,ValueSubject as rT}from"@vkontakte/videoplayer-shared/es2024";var Yt=class{constructor(e){this.prevReported=void 0;this.pastMeasures=[];this.takenMeasures=0;this.measuresCursor=0;this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new rT(e.initial),this.debounced$=new rT(e.initial);let t=e.label??"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new Ae(`raw_${t}`),this.smoothedSeries$=new Ae(`smoothed_${t}`),this.reportedSeries$=new Ae(`reported_${t}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,i=0;for(let u=0;u<this.pastMeasures.length;u++)this.pastMeasures[u]!==void 0&&(t+=(this.pastMeasures[u]-this.smoothed)**2,i++);this.takenMeasures=i,t/=i;let r=Math.sqrt(t),s=this.smoothed+this.params.deviationFactor*r,n=this.smoothed-this.params.deviationFactor*r;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(e),this.updateSmoothedValue(e),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),!(this.smoothed>s||this.smoothed<n)&&(fC(this.prevReported)||Math.abs(this.smoothed-this.prevReported)/this.prevReported>=this.params.changeThreshold)&&(this.prevReported=this.smoothed,this.debounced$.next(this.smoothed),this.reportedSeries$.next(this.smoothed))}};var ro=class extends Yt{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=$t(this.slow,e,this.params.emaAlphaSlow),this.fast=$t(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var ao=class extends Yt{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=Cc(this.pastMeasures,this.takenMeasures);this.emaSmoothed=$t(this.emaSmoothed,e,this.params.emaAlpha);let i=iT(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=i?this.emaSmoothed:t}};var so=class extends Yt{constructor(t){super(t);this.furtherValues=[];this.currentTopExtremumValue=0;this.extremumInterval=t.extremumInterval}next(t){this.currentTopExtremumValue<=t?(this.currentTopExtremumValue=t,this.furtherValues=[]):this.furtherValues.length===this.extremumInterval?(super.next(this.currentTopExtremumValue),this.currentTopExtremumValue=t,this.furtherValues=[]):this.furtherValues.push(t)}updateSmoothedValue(t){this.smoothed=this.smoothed?$t(this.smoothed,t,this.params.emaAlpha):t}};var Mt=class{static getSmoothedValue(e,t,i){return i.type==="TwoEma"?new ro({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new ao({initial:e,emaAlpha:i.emaAlpha,basisTrendChangeCount:i.basisTrendChangeCount,changeThreshold:i.changeThreshold,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"})}static getLiveBufferSmoothedValue(e,t){return new so({initial:e,label:"liveEdgeDelay",...t})}};var Tr=(a,e)=>{a&&a.playbackRate!==e&&(a.playbackRate=e)};import{isNullable as mC,ValueSubject as bC}from"@vkontakte/videoplayer-shared/es2024";var rs=class a{constructor(e,t){this.currentRepresentation$=new bC(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(!mC(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&&He(t.segmentReference))}};var oo=C(at(),1),Bc=C(Ee(),1);import{assertNever as uo}from"@vkontakte/videoplayer-shared/es2024";var no=a=>{let{webmDecodingInfo:e}=B.video,t="DASH_WEBM",i="DASH_WEBM_AV1";switch(a){case"vp9":return[t,i];case"av1":return[i,t];case"none":return[];case"smooth":return e?e[i].smooth?[i,t]:e[t].smooth?[t,i]:[i,t]:[t,i];case"power_efficient":return e?e[i].powerEfficient?[i,t]:e[t].powerEfficient?[t,i]:[i,t]:[t,i];default:uo(a)}return[t,i]},aT=({webmCodec:a,androidPreferredFormat:e,iosPreferredFormat:t,preferMultiStream:i})=>{let r=[...i?["DASH_STREAMS"]:[],...no(a),"DASH_SEP","DASH_ONDEMAND",...i?[]:["DASH_STREAMS"]],s=[...i?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...i?[]:["DASH_STREAMS"]];if(B.device.isAndroid)switch(e){case"mpeg":return["MPEG",...r,"HLS","HLS_ONDEMAND"];case"hls":return["HLS","HLS_ONDEMAND",...r,"MPEG"];case"dash":return[...r,"HLS","HLS_ONDEMAND","MPEG"];case"dash_any_mpeg":return[...s,"MPEG",...no(a),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...no(a),"MPEG",...s,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...no(a),...s,"HLS","HLS_ONDEMAND"];default:uo(e)}if(B.video.nativeHlsSupported)switch(t){case"hls":return[...r,"HLS","HLS_FMP4","HLS_ONDEMAND","MPEG"];case"hls_fmp4":return[...r,"HLS_FMP4","HLS","HLS_ONDEMAND","MPEG"];default:uo(t)}return[...r,"HLS","HLS_ONDEMAND","MPEG"]},sT=({androidPreferredFormat:a,preferCMAF:e,preferWebRTC:t})=>{let i=e?["DASH_LIVE_CMAF","DASH_LIVE"]:["DASH_LIVE","DASH_LIVE_CMAF"],r=e?["HLS_LIVE_CMAF","HLS_LIVE"]:["HLS_LIVE","HLS_LIVE_CMAF"],s=[...i,...r],n=[...r,...i],u,o=B.device.isMac&&B.browser.isSafari;if(B.device.isAndroid)switch(a){case"dash":case"dash_any_mpeg":case"dash_any_webm":case"dash_sep":{u=s;break}case"hls":case"mpeg":{u=n;break}default:uo(a)}else B.video.nativeHlsSupported&&!o?u=n:o?u=e?["DASH_LIVE_CMAF","HLS_LIVE_CMAF","HLS_LIVE","DASH_LIVE"]:["HLS_LIVE","DASH_LIVE","DASH_LIVE_CMAF","HLS_LIVE_CMAF"]:u=s;return t?["WEB_RTC_LIVE",...u]:[...u,"WEB_RTC_LIVE"]},Vc=a=>a?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],lo=a=>{if(a.size===0)return;if(a.size===1){let t=a.values().next();return(0,oo.default)(t.value.split("."),0)}for(let t of a){let i=(0,oo.default)(t.split("."),0);if(i==="opus"||i==="vp09"||i==="av01")return i}let e=a.values().next();return(0,oo.default)(e.value.split("."),0)},co=a=>{let e=a.map(i=>Ir(i)),{codecs:t}=B.video;return yC().filter(i=>{if((0,Bc.default)(e,i))switch(i){case"av1":return t.av1;case"vp9":return t.vp9;case"avc1":return t.h264;case"hev1":return t.h265;default:return!1}else return!1})},po=a=>{let e=a.map(i=>Ir(i)),{codecs:t}=B.video;return TC().filter(i=>{if((0,Bc.default)(e,i))switch(i){case"opus":return t.opus;case"mp4a":return t.aac;default:return!1}else return!1})},Ir=a=>a.split(".")[0].replace("0",""),yC=()=>["av1","vp9","hev1","avc1"],TC=()=>["opus","mp4a"];var PC=["timeupdate","progress","play","seeked","stalled","waiting"],kC=["timeupdate","progress","loadeddata","playing","seeked"];var fo=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.bufferManagers=[];this.subscription=new uT;this.representationSubscription=new uT;this.state$=new F("none");this.currentVideoRepresentation$=new ee(void 0);this.currentVideoRepresentationInit$=new ee(void 0);this.currentAudioRepresentation$=new ee(void 0);this.currentVideoSegmentLength$=new ee(0);this.currentAudioSegmentLength$=new ee(0);this.error$=new Kt;this.manifestRequested=new Kt;this.manifestReceived=new Kt;this.firstBytesRequested=new Kt;this.firstBytesReceived=new Kt;this.lastConnectionType$=new ee(void 0);this.lastConnectionReused$=new ee(void 0);this.lastRequestFirstBytes$=new ee(void 0);this.currentLiveTextRepresentation$=new ee(null);this.isLive$=new ee(!1);this.isActiveLive$=new ee(!1);this.isLowLatency$=new ee(!1);this.liveDuration$=new ee(0);this.liveSeekableDuration$=new ee(0);this.liveAvailabilityStartTime$=new ee(0);this.liveStreamStatus$=new ee(void 0);this.bufferLength$=new ee(0);this.liveLatency$=new ee(void 0);this.liveLoadBufferLength$=new ee(0);this.livePositionFromPlayer$=new ee(0);this.currentStallDuration$=new ee(0);this.videoLastDataObtainedTimestamp$=new ee(0);this.fetcherRecoverableError$=new Kt;this.fetcherError$=new Kt;this.liveStreamEndTimestamp=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.forceEnded$=new Kt;this.gapWatchdogActive=!1;this.destroyController=new X;this.initManifest=Oc(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:ot.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=Oc(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:ot.NETWORK,message:"Failed to load manifest",thrown:o})});if(!e)return null;let t=null;try{t=Yn(e??"",this.manifestUrlString)}catch(o){let l=Gn(e)??{id:"ManifestParsing",category:ot.PARSER,message:"Failed to parse MPD manifest",thrown:o};this.error$.next(l)}if(!t)return null;let i=(o,l,c)=>!!(this.element?.canPlayType?.(l)&&Ue()?.isTypeSupported?.(`${l}; codecs="${c}"`)||o==="text");if(t.live){this.isLive$.next(!!t.live);let{availabilityStartTime:o,latestSegmentPublishTime:l,streamIsUnpublished:c,streamIsAlive:p}=t.live,d=(t.duration??0)/1e3;this.liveSeekableDuration$.next(-1*d),this.liveDuration$.next((l-o)/1e3),this.liveAvailabilityStartTime$.next(t.live.availabilityStartTime);let h="active";p||(h=c?"unpublished":"unexpectedly_down"),this.liveStreamStatus$.next(h)}let r={text:t.streams.text,video:[],audio:[]},s,n;for(let o of["video","audio"]){let c=t.streams[o].filter(({mime:d,codecs:h})=>i(o,d,h));r[o]=c;let p;if(this.tuning.dash.codecsPrioritizeEnabled){let d=c.map(({codecs:h})=>h);o==="audio"&&(n=po(d),p=n[0]),o==="video"&&(s=co(d),this.forceVideoCodec&&(0,cT.default)(s,this.forceVideoCodec)?p=this.forceVideoCodec:p=s[0]),p&&(r[o]=c.filter(({codecs:h})=>Ir(h)===p))}else{let d=new Set(c.map(({codecs:h})=>h));p=lo(d),p&&(r[o]=c.filter(({codecs:h})=>h.startsWith(p)))}if(o==="video"){let d=this.tuning.preferHDR,h=r.video.some(b=>b.hdr),f=r.video.some(b=>!b.hdr);B.display.isHDR&&d&&h?r.video=r.video.filter(b=>b.hdr):f&&(r.video=r.video.filter(b=>!b.hdr))}}let u={...t,streams:r};return this.tuning.dash.codecsPrioritizeEnabled&&(u.codecs={video:s,audio:n}),this.tracer.log("updateManifestEnd",ss(u)),u}.bind(this));this.initRepresentations=Oc(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initRepresentationsStart",ss({initialVideo:e,initialAudio:t,sourceHls:i})),Er(this.manifest),Er(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let r=d=>{this.representationSubscription.add(Dt(d,"error").pipe(ho(h=>!!this.element?.played.length)).subscribe(h=>{this.error$.next({id:"VideoSource",category:ot.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:h})}))};this.source=In();let s=document.createElement("source");if(r(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),ir())if(i){let d=document.createElement("source");r(d),d.type="application/x-mpegurl",d.src=i.url,this.element.appendChild(d)}else this.element.disableRemotePlayback=!0;this.isActiveLive$.next(this.isLive$.getValue());let n={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),manifest:this.manifest},u=this.manifest.streams.video.reduce((d,h)=>[...d,...h.representations],[]);if(this.videoBufferManager=new Za("video",this.source,u,n),this.bufferManagers=[this.videoBufferManager],ns(t)){let d=this.manifest.streams.audio.reduce((h,f)=>[...h,...f.representations],[]);this.audioBufferManager=new Za("audio",this.source,d,n),this.bufferManagers.push(this.audioBufferManager)}rs.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new rs(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(wi(...kC.map(d=>Dt(this.element,d))).pipe(wr(d=>this.element?he(this.element.buffered,this.element.currentTime*1e3):0),as(),wC(d=>{d>this.tuning.dash.bufferEmptinessTolerance&&o()})).subscribe(this.bufferLength$)),this.representationSubscription.add(wi(Dt(this.element,"ended"),this.forceEnded$).subscribe(()=>{o()})),this.isLive$.getValue()){this.subscription.add(this.liveDuration$.pipe(as()).subscribe(h=>this.liveStreamEndTimestamp=Nc())),this.subscription.add(Dt(this.element,"pause").subscribe(()=>{this.livePauseWatchdogSubscription=Fc(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(Dt(this.element,"play").subscribe(h=>this.livePauseWatchdogSubscription?.unsubscribe())),this.representationSubscription.add(xr({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(wr(({isActiveLive:h,isLowLatency:f})=>h&&f),as()).subscribe(h=>{this.isManualDecreasePlaybackInLive()||Tr(this.element,1)})),this.representationSubscription.add(xr({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(ho(({bufferLength:h,isActiveLive:f,isLowLatency:b})=>f&&b&&!!h)).subscribe(({bufferLength:h})=>this.liveBuffer.next(h))),this.representationSubscription.add(this.videoBufferManager.currentLowLatencySegmentLength$.subscribe(h=>{if(!this.isActiveLive$.getValue()&&!this.isLowLatency$.getValue()&&!h)return;let 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(xr({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe(ho(({isLive:h})=>h),as((h,f)=>f.bufferLength<h.bufferLength),wr(({rtt:h,bufferLength:f,segmentServerLatency:b})=>{let S=Ut(this.manifestUrlString,2);return(h/2+f+b+S)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add(xr({liveBuffer:this.liveBuffer.smoothed$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).subscribe(({liveBuffer:h,isActiveLive:f,isLowLatency:b})=>{if(!b||!f)return;let S=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,g=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,I=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,x=h-S;if(this.isManualDecreasePlaybackInLive())return;let y=1;Math.abs(x)>g&&(y=1+Math.sign(x)*I),Tr(this.element,y)})),this.representationSubscription.add(this.bufferLength$.subscribe(h=>{let f=0;if(h){let b=(this.element?.currentTime??0)*1e3;f=Math.min(...this.bufferManagers.map(g=>g.getLiveSegmentsToLoadState(this.manifest)?.to??b))-b}this.liveLoadBufferLength$.getValue()!==f&&this.liveLoadBufferLength$.next(f)}));let d=0;this.representationSubscription.add(xr({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(AC(1e3)).subscribe(async({liveLoadBufferLength:h,bufferLength:f})=>{if(!this.element||this.isUpdatingLive)return;let b=this.element.playbackRate,S=Ut(this.manifestUrlString,2),g=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,I=Math.min(g,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*b),x=this.tuning.dashCmafLive.normalizedActualBufferOffset*b,y=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*b,w=isFinite(h)?h:f,D=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),L=g<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next(L);let A="none";if(D?A="active_low_latency":this.isLowLatency$.getValue()&&L?(this.bufferManagers.forEach(R=>R.proceedLowLatencyLive()),A="active_low_latency"):S!==0&&w<I?A="live_forward_buffering":w<I+y&&(A="live_with_target_offset"),isFinite(h)&&(d=h>d?h:d),A==="live_forward_buffering"||A==="live_with_target_offset"){let R=d-(I+x),T=this.normolizeLiveOffset(Math.trunc(S+R/b)),q=Math.abs(T-S),$=0;!h||q<=this.tuning.dashCmafLive.offsetCalculationError?$=S:T>0&&q>this.tuning.dashCmafLive.offsetCalculationError&&($=T),this.manifestUrlString=se(this.manifestUrlString,$,2)}(A==="live_with_target_offset"||A==="live_forward_buffering")&&(d=0,await this.updateLive())},h=>{this.error$.next({id:"updateLive",category:ot.VIDEO_PIPELINE,thrown:h,message:"Failed to update live with subscription"})}))}let l=wi(...this.bufferManagers.map(d=>d.fullyBuffered$)).pipe(wr(()=>this.bufferManagers.every(d=>d.fullyBuffered$.getValue()))),c=wi(...this.bufferManagers.map(d=>d.onLastSegment$)).pipe(wr(()=>this.bufferManagers.some(d=>d.onLastSegment$.getValue()))),p=xr({allBuffersFull:l,someBufferEnded:c}).pipe(as(),wr(({allBuffersFull:d,someBufferEnded:h})=>d&&h),ho(d=>d));if(this.representationSubscription.add(wi(this.forceEnded$,p).subscribe(()=>{if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(d=>!d.updating))try{this.source?.endOfStream()}catch(d){this.error$.next({id:"EndOfStream",category:ot.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:d})}})),this.representationSubscription.add(wi(...this.bufferManagers.map(d=>d.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.representationSubscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&(this.representationSubscription.add(this.audioBufferManager.playingRepresentation$.subscribe(this.currentAudioRepresentation$)),this.representationSubscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$))),this.liveTextManager&&this.representationSubscription.add(this.liveTextManager.currentRepresentation$.subscribe(this.currentLiveTextRepresentation$)),this.source.readyState!=="open"){let d=this.tuning.dash.sourceOpenTimeout>=0;yield new Promise(h=>{d&&(this.timeoutSourceOpenId=setTimeout(()=>{if(this.source?.readyState==="open"){h();return}this.error$.next({id:"OpenOfStream",category:ot.VIDEO_PIPELINE,message:"Failed to open MediaSource",thrown:new Error("Timeout reject when wait sourceopen event"),traceAsLog:!0})},this.tuning.dash.sourceOpenTimeout)),this.source?.addEventListener("sourceopen",()=>{this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),h()},{once:!0})})}if(!this.isLive$.getValue()){let d=[this.manifest.duration??0,...(0,qc.default)((0,qc.default)([...this.manifest.streams.audio,...this.manifest.streams.video],h=>h.representations),h=>{let f=[];return h.duration&&f.push(h.duration),He(h.segmentReference)&&h.segmentReference.totalSegmentsDurationMs&&f.push(h.segmentReference.totalSegmentsDurationMs),f})];this.source.duration=Math.max(...d)/1e3}this.audioBufferManager&&ns(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=Fc(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),t=>{this.error$.next({id:"GapWatchdog",category:ot.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 io({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()}async seekLive(e){Er(this.element);let t=this.liveStreamStatus$.getValue()!=="active"?Nc()-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(){Er(this.element),this.state$.setState("running"),this.subscription.add(wi(...PC.map(e=>Dt(this.element,e)),Dt(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:ot.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(Dt(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(Dt(this.element,"waiting").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&Se(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{if(!this.element||this.source?.readyState!=="open")return;let t=this.currentStallDuration$.getValue();t+=50,this.currentStallDuration$.next(t);let i={timeInWaiting:t},r=Nc(),s=100,n=this.videoBufferManager?.lastDataObtainedTimestamp??0;this.videoLastDataObtainedTimestamp$.next(n);let u=this.audioBufferManager?.lastDataObtainedTimestamp??0,o=this.videoBufferManager?.getForwardBufferDuration()??0,l=this.audioBufferManager?.getForwardBufferDuration()??0,c=o<s&&r-n>this.tuning.dash.crashOnStallTWithoutDataTimeout,p=this.audioBufferManager&&l<s&&r-u>this.tuning.dash.crashOnStallTWithoutDataTimeout;if((c||p)&&t>this.tuning.dash.crashOnStallTWithoutDataTimeout||t>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${t} ms`);if(this.isLive$.getValue()&&t%2e3===0){let d=this.normolizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);this.seekLive(d).catch(h=>{this.error$.next({id:"stallIntervalCallback",category:ot.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:h})}),i.liveLastOffset=d}else{let d=this.element.currentTime*1e3;this.videoBufferManager?.maintain(d),this.audioBufferManager?.maintain(d),i.position=d}this.tracer.log("stallIntervalCallback",ss(i))};this.stallWatchdogSubscription?.unsubscribe(),this.stallWatchdogSubscription=Fc(50).subscribe(e,t=>{this.error$.next({id:"StallWatchdogCallback",category:ot.NETWORK,message:"Can't restore DASH after stall.",thrown:t})}),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){Er(this.element),Er(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),Se(this.element.buffered,i)||await Promise.all([this.videoBufferManager.abort(),this.audioBufferManager?.abort()]),!(oT(this.element)||oT(this.videoBufferManager))&&(this.videoBufferManager.maintain(i),this.audioBufferManager?.maintain(i),this.element.currentTime=i/1e3,this.tracer.log("seek",ss({requestedPosition:e,forcePrecise:t,position:i})))}warmUpMediaSourceIfNeeded(e=this.element?.currentTime){ns(this.element)&&ns(this.source)&&ns(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=xC(this.tracer.error.bind(this.tracer));this.subscription.add(this.error$.subscribe(e("error")))}isManualDecreasePlaybackInLive(){if(!this.element||!this.isLive$.getValue())return!1;let e=1-this.element.playbackRate;return Number(e.toFixed(2))>Number(this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup.toFixed(2))}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}async updateLive(){this.isUpdatingLive=!0,this.manifest=await this.updateManifest(),this.manifest&&(this.bufferManagers.forEach(e=>e.updateLive(this.manifest)),this.liveTextManager?.updateLive(this.manifest)),this.isUpdatingLive=!1}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.getDebugBufferState();if(!e)return;let t=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),i={isJumpGapAfterSeekLive:this.isJumpGapAfterSeekLive,isActiveLowLatency:t,initialCurrentTime:this.element.currentTime};this.isJumpGapAfterSeekLive&&!t&&this.element.currentTime>e.to&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let r=this.element.currentTime*1e3,s=[],n=this.element.readyState===1?this.tuning.endGapTolerance:0;for(let u of this.bufferManagers)for(let o of u.gaps)u.playingRepresentation$.getValue()===o.representation&&o.from-n<=r&&o.to+n>r&&(this.element.duration*1e3-o.to<this.tuning.endGapTolerance?s.push(1/0):s.push(o.to));if(s.length){let u=Math.max(...s)+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,u===1/0?this.forceEnded$.next():(this.element.currentTime=u/1e3,i={...i,gapEnds:s,jumpTo:u,resultCurrentTime:this.element.currentTime},this.tracer.log("jumpGap",ss(i)))}}calculateDurationFromSegments(){return Math.max(this.videoBufferManager?.calculateDurationFromSegments()||0,this.audioBufferManager?.calculateDurationFromSegments()||0)}};var mo=class{constructor(e,t){this.fov=e,this.orientation=t}};var bo=class{constructor(e,t){this.rotating=!1;this.fading=!1;this.lastTickTS=0;this.lastCameraTurnTS=0;this.fadeStartSpeed=null;this.fadeTime=0;this.camera=e,this.options=t,this.rotationSpeed={x:0,y:0,z:0},this.fadeCorrection=1/(this.options.speedFadeTime/1e3)**2}turnCamera(e=0,t=0,i=0){this.pointCameraTo(this.camera.orientation.x+e,this.camera.orientation.y+t,this.camera.orientation.z+i)}pointCameraTo(e=0,t=0,i=0){t=this.limitCameraRotationY(t);let r=e-this.camera.orientation.x,s=t-this.camera.orientation.y,n=i-this.camera.orientation.z;this.camera.orientation.x=e,this.camera.orientation.y=t,this.camera.orientation.z=i,this.lastCameraTurn={x:r,y:s,z:n},this.lastCameraTurnTS=Date.now()}setRotationSpeed(e,t,i){this.rotationSpeed.x=e??this.rotationSpeed.x,this.rotationSpeed.y=t??this.rotationSpeed.y,this.rotationSpeed.z=i??this.rotationSpeed.z}startRotation(){this.rotating=!0}stopRotation(e=!1){e?(this.setRotationSpeed(0,0,0),this.fadeStartSpeed=null):this.startFading(this.rotationSpeed.x,this.rotationSpeed.y,this.rotationSpeed.z),this.rotating=!1}onCameraRelease(){if(this.lastCameraTurn&&this.lastCameraTurnTS){let e=Date.now()-this.lastCameraTurnTS;if(e<this.options.speedFadeThreshold){let t=(1-e/this.options.speedFadeThreshold)*this.options.rotationSpeedCorrection;this.startFading(this.lastCameraTurn.x*t,this.lastCameraTurn.y*t,this.lastCameraTurn.z*t)}}}startFading(e,t,i){this.setRotationSpeed(e,t,i),this.fadeStartSpeed={...this.rotationSpeed},this.fading=!0}stopFading(){this.fadeStartSpeed=null,this.fading=!0,this.fadeTime=0}limitCameraRotationY(e){return Math.max(-this.options.maxYawAngle,Math.min(e,this.options.maxYawAngle))}tick(e){if(!this.lastTickTS){this.lastTickTS=e,this.lastCameraTurnTS=Date.now();return}let t=e-this.lastTickTS,i=t/1e3;if(this.rotating)this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*i,this.rotationSpeed.y*this.options.rotationSpeedCorrection*i,this.rotationSpeed.z*this.options.rotationSpeedCorrection*i);else if(this.fading&&this.fadeStartSpeed){let r=-this.fadeCorrection*(this.fadeTime/1e3)**2+1;this.setRotationSpeed(this.fadeStartSpeed.x*r,this.fadeStartSpeed.y*r,this.fadeStartSpeed.z*r),r>0?this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*i,this.rotationSpeed.y*this.options.rotationSpeedCorrection*i,this.rotationSpeed.z*this.options.rotationSpeedCorrection*i):(this.stopRotation(!0),this.stopFading()),this.fadeTime=Math.min(this.fadeTime+t,this.options.speedFadeTime)}this.lastTickTS=e}};var dT=`attribute vec2 a_vertex;
124
+ `})|(?<privateuse2>${e}))$`.replace(/[\s\t\n]/g,"");return new RegExp(p,"i")}var Gy=a=>{if(!a?.startsWith("P"))return;let e=(n,u)=>{let o=n?parseFloat(n.replace(",",".")):NaN;return(isNaN(o)?0:o)*u},i=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(a),r=i?.[1]==="-"?-1:1,s={days:e(i?.[5],r),hours:e(i?.[6],r),minutes:e(i?.[7],r),seconds:e(i?.[8],r)};return s.days*24*60*60*1e3+s.hours*60*60*1e3+s.minutes*60*1e3+s.seconds*1e3},nt=(a,e)=>{let t=a;t=(0,Lc.default)(t,"$$","$");let i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[r,s]of(0,zy.default)(i)){let n=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=(0,Lc.default)(t,n,(u,o)=>Wy(s)?u:Wy(o)?s:(0,Yy.default)(s,parseInt(o,10),"0"))}return t},ro=(a,e)=>{let i=new DOMParser().parseFromString(a,"application/xml"),r={video:[],audio:[],text:[]},s=i.children[0],n=Array.from(s.querySelectorAll("MPD > BaseURL").values()).map(D=>D.textContent?.trim()??""),u=(0,Ky.default)(n,0)??"",o=s.getAttribute("type")==="dynamic",l=s.getAttribute("availabilityStartTime"),p=s.getAttribute("publishTime"),d=s.getElementsByTagName("vk:Attrs")[0],c=d?.getElementsByTagName("vk:XLatestSegmentPublishTime")[0].textContent,h=d?.getElementsByTagName("vk:XStreamIsLive")[0].textContent,f=d?.getElementsByTagName("vk:XStreamIsUnpublished")[0].textContent,m=d?.getElementsByTagName("vk:XPlaybackDuration")[0].textContent,g;o&&(g={availabilityStartTime:l?new Date(l).getTime():0,publishTime:p?new Date(p).getTime():0,latestSegmentPublishTime:c?new Date(c).getTime():0,streamIsAlive:h==="yes",streamIsUnpublished:f==="yes"});let S,v=s.getAttribute("mediaPresentationDuration"),I=[...s.getElementsByTagName("Period")],T=I.reduce((D,x)=>({...D,[x.id]:x.children}),{}),A=I.reduce((D,x)=>({...D,[x.id]:x.getAttribute("duration")}),{});v?S=Gy(v):(0,$c.default)(A).filter(D=>D).length&&!o?S=(0,$c.default)(A).reduce((D,x)=>D+(Gy(x)??0),0):m&&(S=parseInt(m,10));let k=0,L=s.getAttribute("profiles")?.split(",")??[];for(let D of I.map(x=>x.id))for(let x of T[D]){let q=x.getAttribute("id")??"id"+(k++).toString(10),$=x.getAttribute("mimeType")??"",y=x.getAttribute("codecs")??"",E=x.getAttribute("contentType")??$?.split("/")[0],z=x.getAttribute("profiles")?.split(",")??[],M=Qy(x.getAttribute("lang")??"")??{},H=x.querySelector("Label")?.textContent?.trim()??void 0,J=x.querySelectorAll("Representation"),ie=x.querySelector("SegmentTemplate"),ue=x.querySelector("Role")?.getAttribute("value")??void 0,me=E,be={id:q,language:M.language,isDefault:ue==="main",label:H,codecs:y,hdr:me==="video"&&kc(y),mime:$,representations:[]};for(let j of J){let U=j.getAttribute("lang")??void 0,Le=H??x.getAttribute("label")??j.getAttribute("label")??void 0,Te=j.querySelector("BaseURL")?.textContent?.trim()??"",de=new URL(Te||u,e).toString(),We=j.getAttribute("mimeType")??$,Bt=j.getAttribute("codecs")??y??"",lt;if(E==="text"){let Oe=j.getAttribute("id")||"",Vt=M.privateuse?.includes("x-auto")||Oe.includes("_auto"),ct=j.querySelector("SegmentTemplate");if(ct){let Vr={representationId:j.getAttribute("id")??void 0,bandwidth:j.getAttribute("bandwidth")??void 0},Vs=parseInt(j.getAttribute("bandwidth")??"",10)/1e3,_s=parseInt(ct.getAttribute("startNumber")??"",10)??1,Vi=parseInt(ct.getAttribute("timescale")??"",10),Zo=ct.querySelectorAll("SegmentTimeline S")??[],_i=ct.getAttribute("media");if(!_i)continue;let Os=[],Fs=0,Ns="",Oi=0,_r=_s,Ie=0;for(let Je of Zo){let ai=parseInt(Je.getAttribute("d")??"",10),Ge=parseInt(Je.getAttribute("r")??"",10)||0,_t=parseInt(Je.getAttribute("t")??"",10);Ie=Number.isFinite(_t)?_t:Ie;let si=ai/Vi*1e3,Fi=Ie/Vi*1e3;for(let dt=0;dt<Ge+1;dt++){let Ot=nt(_i,{...Vr,segmentNumber:_r.toString(10),segmentTime:(Ie+dt*ai).toString(10)}),Ni=(Fi??0)+dt*si,Fr=Ni+si;_r++,Os.push({time:{from:Ni,to:Fr},url:Ot})}Ie+=(Ge+1)*ai,Fs+=(Ge+1)*si}Oi=Ie/Vi*1e3,Ns=nt(_i,{...Vr,segmentNumber:_r.toString(10),segmentTime:Ie.toString(10)});let Or={time:{from:Oi,to:1/0},url:Ns},Et={type:"template",baseUrl:de,segmentTemplateUrl:_i,initUrl:"",totalSegmentsDurationMs:Fs,segments:Os,nextSegmentBeyondManifest:Or,timescale:Vi};lt={id:Oe,kind:"text",segmentReference:Et,profiles:[],duration:S,bitrate:Vs,mime:"",codecs:"",width:0,height:0,isAuto:Vt}}else lt={id:Oe,isAuto:Vt,kind:"text",url:de}}else{let Oe=j.getAttribute("contentType")??We?.split("/")[0]??E,Vt=x.getAttribute("profiles")?.split(",")??[],ct=parseInt(j.getAttribute("width")??"",10),Vr=parseInt(j.getAttribute("height")??"",10),Vs=parseInt(j.getAttribute("bandwidth")??"",10)/1e3,_s=j.getAttribute("frameRate")??"",Vi=j.getAttribute("quality")??void 0,Zo=_s?jy(_s):void 0,_i=j.getAttribute("id")??"id"+(k++).toString(10),Os=Oe==="video"?`${Vr}p`:Oe==="audio"?`${Vs}Kbps`:Bt,Fs=`${_i}@${Os}`,Ns=[...L,...z,...Vt],Oi,_r=j.querySelector("SegmentBase"),Ie=j.querySelector("SegmentTemplate")??ie;if(_r){let Et=j.querySelector("SegmentBase Initialization")?.getAttribute("range")??"",[Je,ai]=Et.split("-").map(Ot=>parseInt(Ot,10)),Ge={from:Je,to:ai},_t=j.querySelector("SegmentBase")?.getAttribute("indexRange"),[si,Fi]=_t?_t.split("-").map(Ot=>parseInt(Ot,10)):[],dt=_t?{from:si,to:Fi}:void 0;Oi={type:"byteRange",url:de,initRange:Ge,indexRange:dt}}else if(Ie){let Et={representationId:j.getAttribute("id")??void 0,bandwidth:j.getAttribute("bandwidth")??void 0},Je=parseInt(Ie.getAttribute("timescale")??"",10),ai=Ie.getAttribute("initialization")??"",Ge=Ie.getAttribute("media"),_t=parseInt(Ie.getAttribute("startNumber")??"",10)??1,si=nt(ai,Et);if(!Ge)throw new ReferenceError("No media attribute in SegmentTemplate");let Fi=Ie.querySelectorAll("SegmentTimeline S")??[],dt=[],Ot=0,Ni="",Fr=0;if(Fi.length){let qs=_t,Ze=0;for(let qi of Fi){let pt=parseInt(qi.getAttribute("d")??"",10),ni=parseInt(qi.getAttribute("r")??"",10)||0,Us=parseInt(qi.getAttribute("t")??"",10);Ze=Number.isFinite(Us)?Us:Ze;let eu=pt/Je*1e3,OI=Ze/Je*1e3;for(let Hs=0;Hs<ni+1;Hs++){let FI=nt(Ge,{...Et,segmentNumber:qs.toString(10),segmentTime:(Ze+Hs*pt).toString(10)}),qd=(OI??0)+Hs*eu,NI=qd+eu;qs++,dt.push({time:{from:qd,to:NI},url:FI})}Ze+=(ni+1)*pt,Ot+=(ni+1)*eu}Fr=Ze/Je*1e3,Ni=nt(Ge,{...Et,segmentNumber:qs.toString(10),segmentTime:Ze.toString(10)})}else if(oC(S)){let Ze=parseInt(Ie.getAttribute("duration")??"",10)/Je*1e3,qi=Math.ceil(S/Ze),pt=0;for(let ni=1;ni<qi;ni++){let Us=nt(Ge,{...Et,segmentNumber:ni.toString(10),segmentTime:pt.toString(10)});dt.push({time:{from:pt,to:pt+Ze},url:Us}),pt+=Ze}Fr=pt,Ni=nt(Ge,{...Et,segmentNumber:qi.toString(10),segmentTime:pt.toString(10)})}let _I={time:{from:Fr,to:1/0},url:Ni};Oi={type:"template",baseUrl:de,segmentTemplateUrl:Ge,initUrl:si,totalSegmentsDurationMs:Ot,segments:dt,nextSegmentBeyondManifest:_I,timescale:Je}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!Oe||!We)continue;let Or={video:"video",audio:"audio",text:"text"}[Oe];if(!Or)continue;me||=Or,lt={id:Fs,kind:Or,segmentReference:Oi,profiles:Ns,duration:S,bitrate:Vs,mime:We,codecs:Bt,width:ct,height:Vr,fps:Zo,quality:Vi}}be.language||=U,be.label||=Le,be.mime||=We,be.codecs||=Bt,be.hdr||=me==="video"&&kc(Bt),be.representations.push(lt)}if(me){let j=r[me].find(U=>U.id===be.id);if(j&&be.representations.every(U=>U.segmentReference.type==="template"))for(let U of j.representations){let Te=be.representations.find(We=>We.id===U.id)?.segmentReference,de=U.segmentReference;de.segments.push(...Te.segments),de.nextSegmentBeyondManifest=Te.nextSegmentBeyondManifest}else r[me].push(be)}}return{duration:S,streams:r,baseUrls:n,live:g}};var Mc=C(at(),1);import{videoSizeToQuality as uC}from"@vkontakte/videoplayer-shared/es2024";var es=({id:a,width:e,height:t,bitrate:i,fps:r,quality:s,streamId:n})=>{let u=(s?jt(s):void 0)??uC({width:e,height:t});return u&&{id:a,quality:u,bitrate:i,size:{width:e,height:t},fps:r,streamId:n}},Xy=({id:a,bitrate:e})=>({id:a,bitrate:e}),Jy=({language:a,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:a,label:e}),Zy=({language:a,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:a,label:e}),Dc=({id:a,language:e,label:t,codecs:i,isDefault:r})=>({id:a,language:e,label:t,codec:(0,Mc.default)(i.split("."),0),isDefault:r}),Cc=({id:a,language:e,label:t,hdr:i,codecs:r})=>({id:a,language:e,hdr:i,label:t,codec:(0,Mc.default)(r.split("."),0)}),Bc=a=>"url"in a,He=a=>a.type==="template";import{isNonNullable as eT}from"@vkontakte/videoplayer-shared/es2024";var V=(a,e)=>eT(a)&&eT(e)&&a.readyState==="open"&&lC(a,e);function lC(a,e){for(let t=0;t<a.activeSourceBuffers.length;++t)if(a.activeSourceBuffers[t]===e)return!0;return!1}var ts=class{constructor(e,t,i,{fetcher:r,tuning:s,getCurrentPosition:n,isActiveLowLatency:u,compatibilityMode:o=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new Ai(0);this.currentLowLatencySegmentLength$=new Ai(0);this.currentSegmentLength$=new Ai(0);this.onLastSegment$=new Ai(!1);this.fullyBuffered$=new Ai(!1);this.playingRepresentation$=new Ai(void 0);this.playingRepresentationInit$=new Ai(void 0);this.error$=new pC;this.gaps=[];this.subscription=new hC;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.startWith=Gt(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);Re(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new Yv(this.sourceBuffer),this.subscription.add(Vc(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let u,o=this.mediaSource.readyState;o!=="open"&&(u={id:`SegmentEjection_source_${o}`,category:Lt.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),u??={id:"SegmentEjection",category:Lt.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n},this.error$.next(u)})),this.subscription.add(Vc(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:Lt.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=this.getForwardBufferDuration(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);Re(i,"No init buffer for starting representation"),Re(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=Gt(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);Re(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if(le(s)||le(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),Re(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=Gt(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);Re(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if(le(s)||le(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),Re(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=Gt(this.destroyAbortController.signal,async function*(e){let t=(0,no.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||!He(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);Re(r);let s=this.segments.get(i);Re(s,"No segments for starting representation");let n=this.initData.get(i);if(Re(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,Gt(this.switchAbortController.signal,async function*(i,r=!1){this.switchingToRepresentationId=i;let s=this.representations.get(i);Re(s,`No such representation ${i}`);let n=this.segments.get(i),u=this.initData.get(i);if(le(u)||le(n)?yield this.loadInit(s,"high",!1):u instanceof Promise&&(yield u),n=this.segments.get(i),Re(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(){!le(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(le(e)||le(this.downloadingRepresentationId)||le(this.playingRepresentationId)||le(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(Re(t,`No such representation ${this.downloadingRepresentationId}`),Re(i,`No such representation ${this.playingRepresentationId}`),le(r)||le(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=es(i),f=es(t),m=this.useSmartRepresentationSwitch&&this.tuning.dash.useNewRepresentationSwitch&&this.tuning.dash.useSmartRepresentationSwitch&&zt(h)&&zt(f)&&cC(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(k=>e>=k.time.from&&e<k.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=this.getForwardBufferDuration(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=[];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,so.default)(p,n))c="high";else{let h=(0,Pi.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&&this.getForwardBufferDuration(e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let d=(0,Pi.default)(r,-1);!this.isLive&&d&&(this.fullyBuffered$.next(d.time.to-e-this.getForwardBufferDuration(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,no.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,no.default)(e?.streams[this.kind],i=>i.representations)??[];if(![...this.segments.values()].every(i=>!i.length))for(let i of t){if(!i||!He(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,Pi.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;Re(e);let t=this.segments.get(e);if(t?.length){let i=t[t.length-1];this.updateLowLatencyLiveIfNeeded(i)}}calculateDurationFromSegments(){if(!this.playingRepresentationId)return 0;let e=this.segments.get(this.playingRepresentationId);return(e?(0,Pi.default)(e,-1)?.time.to:0)||0}setSmartRepresentationSwitch(e){this.useSmartRepresentationSwitch=e}updateLowLatencyLiveIfNeeded(e){let t=0;for(let i of this.representations.values()){let r=i.segmentReference;if(!He(r))return;let s=this.segments.get(i.id)??[],n=s.find(o=>Math.floor(o.time.from)===Math.floor(e.time.from));if(n&&!isFinite(n.time.to)&&(n.time.to=e.time.to,t=n.time.to-n.time.from),!!!s.find(o=>Math.floor(o.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let o=Math.round(e.time.to*r.timescale/1e3).toString(10),l=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.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.isLive?this.selectForwardBufferSegmentsLive(e,i):this.selectForwardBufferSegmentsRecord(e,t,i)}selectForwardBufferSegmentsLive(e,t){let i=e.findIndex(r=>t>=r.time.from&&t<r.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=i),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,i){let r=this.getForwardBufferDuration(i),s=e.findIndex(({status: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[];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"){He(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 Gt(u,async function*(){let p=_c(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=ao(),!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())He(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 Gt(n,async function*(){let o=_c(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,o),Vc(window,"online").pipe(dC()).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=ao(),this.failedDownloads=0}catch(o){this.abortActiveSegments(e),Tt(o)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}prepareByteRangeFetchSegmentParams(e,t){if(He(t.segmentReference))throw new Error("Representation is not byte range type");let i=t.segmentReference.url,r={from:(0,Pi.default)(e,0).byte.from,to:(0,Pi.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=ao(),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:Lt.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!He(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=ao();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:Lt.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,so.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){let{segment:l}=o;if(o.representationId!==t)continue;if(s.aborted){await n();continue}let p=l.byte.from-i,d=l.byte.to-i,c=d-p+1,h=p<r,f=d<=r;if(!h)continue;let m=yt(u.mime);if(l.status==="downloading"&&f){l.status="downloaded";let g=new DataView(e.buffer,e.byteOffset+p,c);await this.sourceBufferTaskQueue.append(g,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 g=new DataView(e.buffer,e.byteOffset+p+o.feedingBytes,o.loadedBytes-o.feedingBytes),S=o.loadedBytes===c?g:m.parseFeedableSegmentChunk(g);S?.byteLength&&(l.status="partially_fed",o.feedingBytes+=S.byteLength,await this.sourceBufferTaskQueue.append(S,s)&&!s.aborted?(o.fedBytes+=S.byteLength,o.fedBytes===c&&this.onSegmentFullyAppended(o,t)):await n())}}}onSegmentFullyAppended(e,t){if(!(le(this.sourceBuffer)||!V(this.mediaSource,this.sourceBuffer))){!this.isLive&&B.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:Lt.VIDEO_PIPELINE,message:"Browser stuck on empty result of adding segment to source buffer"})),this.tuning.dash.useNewRepresentationSwitch||(this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId))),e.segment.status="fed",Bc(e.segment)&&(e.segment.size=e.fedBytes);for(let i of this.representations.values())if(i.id!==t)for(let r of this.segments.get(i.id)??[])r.status==="fed"&&Math.round(r.time.from)===Math.round(e.segment.time.from)&&Math.round(r.time.to)===Math.round(e.segment.time.to)&&(r.status="none");this.updateLowLatencyLiveIfNeeded(e.segment),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment])}}abortSegment(e){e.status==="partially_fed"?e.status="partially_ejected":e.status!=="partially_ejected"&&(e.status="none");for(let t of this.activeSegments.values())if(t.segment===e){this.activeSegments.delete(t);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(let[r,s]of this.initData.entries()){let n=s instanceof Promise;t||=n,s===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let i=this.representations.get(e);i&&(this.initLoadIdleCallback=fr(()=>(0,tT.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?Gt(this.destroyAbortController.signal,async function*(){let u=_c(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(async 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&&He(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:Lt.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||le(e))return!1;let r=[],s=0,n=o=>{o.sort((p,d)=>p.from-d.from);let l=[o[0]];for(let p=1;p<o.length;p++){let{from:d,to:c}=o[p],h=l[l.length-1];h.to>=d?h.to=Math.max(h.to,c):l.push(o[p])}return l},u=o=>{if(s>=t)return r;r.push({...o.time}),r=n(r);let l=Bc(o)?o.size??0:o.byte.to-o.byte.from;s+=l};for(let o of this.segments.values())for(let l of o){let p=l.time.to<=e-this.tuning.dash.bufferPruningSafeZone,d=l.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(p||d)&&l.status==="fed"&&u(l)}for(let o=0;o<this.sourceBuffer.buffered.length;o++){let l=this.sourceBuffer.buffered.start(o)*1e3,p=this.sourceBuffer.buffered.end(o)*1e3,d=0;for(let c of this.segments.values())for(let h of c)(0,so.default)(["none","partially_ejected"],h.status)&&Math.round(h.time.from)<=Math.round(l)&&Math.round(h.time.to)>=Math.round(p)&&d++;if(d===this.segments.size){let c={time:{from:l,to:p},url:"",status:"none"};u(c)}}if(r.length&&i){let o=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let l of this.segments.values())for(let p of l)p.time.from>=e+o&&p.status==="fed"&&u(p)}return r.length?(await Promise.all(r.map(l=>this.sourceBufferTaskQueue.remove(l.from,l.to)))).reduce((l,p)=>l||p,!1):!1}async abortBuffer(){if(!this.sourceBuffer||!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)}}getForwardBufferDuration(e=this.getCurrentPosition()){return!this.sourceBuffer||!V(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||le(e)?0:ve(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!(!this.sourceBuffer||!V(this.mediaSource,this.sourceBuffer)))for(let i of t){let r={representation:e,from:i.time.from,to:i.time.to,persistent:!1},{buffered:s}=this.sourceBuffer;for(let n=0;n<s.length;n++){let u=s.start(n)*1e3,o=s.end(n)*1e3;if(!(o<=i.time.from||u>=i.time.to)){if(u<=i.time.from&&o>=i.time.to){r=void 0;break}o>i.time.from&&o<i.time.to&&(r.from=o),u<i.time.to&&u>i.time.from&&(r.to=u)}}r&&r.to-r.from>1&&!this.gaps.some(n=>r&&n.from===r.from&&n.to===r.to)&&this.gaps.push(r)}}detectGapsWhenIdle(e,t){if(this.gapDetectionIdleCallback||!this.sourceBuffer||!V(this.mediaSource,this.sourceBuffer))return;let{buffered:i}=this.sourceBuffer,{usePersistentGaps:r}=this.tuning.dash;this.gaps=this.gaps.filter(s=>{if(r&&s.persistent)return!0;let n=Math.round(s.from),u=Math.round(s.to);for(let o=0;o<i.length;o++)if(n>=Math.round(i.start(o)*1e3)&&u<=Math.round(i.end(o)*1e3))return!1;return!0}),this.gapDetectionIdleCallback=fr(()=>{try{this.detectGaps(e,t)}catch(s){this.error$.next({id:"GapDetection",category:Lt.WTF,message:"detectGaps threw",thrown:s})}finally{this.gapDetectionIdleCallback=null}})}checkEjectedSegments(){if(le(this.sourceBuffer)||!V(this.mediaSource,this.sourceBuffer)||le(this.playingRepresentationId))return;let e=[];for(let i=0;i<this.sourceBuffer.buffered.length;i++){let r=Math.floor(this.sourceBuffer.buffered.start(i)*1e3),s=Math.ceil(this.sourceBuffer.buffered.end(i)*1e3);e.push({from:r,to:s})}let t=100;for(let i of this.segments.values())for(let r of i){let{status:s}=r;if(s!=="fed"&&s!=="partially_ejected")continue;let n=Math.floor(r.time.from),u=Math.ceil(r.time.to),o=e.some(p=>p.from-t<=n&&p.to+t>=u),l=e.filter(p=>n>=p.from&&n<p.to-t||u>p.from+t&&u<=p.to);o||(l.length===1?r.status="partially_ejected":this.gaps.some(p=>p.from===r.time.from||p.to===r.time.to)?r.status="partially_ejected":r.status="none")}}handleAsyncError(e,t){this.error$.next({id:t,category:Lt.VIDEO_PIPELINE,thrown:e,message:"Something went wrong"})}};var Yt=a=>{let e=new URL(a);return e.searchParams.set("quic","1"),e.toString()};var oo=a=>{let e=a.get("X-Delivery-Type"),t=a.get("X-Reused"),i=e===null?"http1":e??void 0,r=t===null?void 0:{1:!0,0:!1}[t]??void 0;return{type:i,reused:r}};import{abortable as is,assertNever as iT,fromEvent as rT,merge as fC,now as rs,Subject as yr,ValueSubject as Oc,flattenObject as Tr,ErrorCategory as as,SubscriptionRemovable as mC}from"@vkontakte/videoplayer-shared/es2024";var uo=a=>{let e=new URL(a);return e.searchParams.set("enable-subtitles","yes"),e.toString()};var co=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:s=!1}){this.manifestRequested=new yr;this.manifestReceived=new yr;this.firstBytesRequested=new yr;this.firstBytesReceived=new yr;this.lastConnectionType$=new Oc(void 0);this.lastConnectionReused$=new Oc(void 0);this.lastRequestFirstBytes$=new Oc(void 0);this.recoverableError$=new yr;this.error$=new yr;this.abortAllController=new X;this.subscription=new mC;this.fetchManifest=is(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(lo);return r?(t.log("success",Tr({url:i,message:"Request successfully executed"})),t.end(),this.manifestReceived.next(),this.onHeadersReceived(r.headers),r.text()):(t.error("error",Tr({url:i,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=is(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:iT(t)}this.requestQuic&&(p=Yt(p));let h=this.abortAllController.signal,f;if(n){let y=new X;if(f=fC(rT(this.abortAllController.signal,"abort"),rT(n,"abort")).subscribe(()=>{try{y.abort()}catch(E){lo(E)}}),this.subscription.add(f),this.abortAllController.signal.aborted||n.aborted)try{y.abort()}catch(E){lo(E)}h=y.signal}let m=0,g=rs();c.log("startRequest",Tr({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=rs();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=rs(),E={requestStartedAt:g,requestEndedAt:y,duration:y-g};return c.log("endRequest",Tr(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,k=parseInt(S.headers.get("content-length")??"",10);Number.isFinite(k)&&(A=k),!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,lo(y)},x=is(h,async function*({done:y,value:E}){if(m===0&&(this.lastRequestFirstBytes$.next(rs()-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=rs(),$={failed:w,requestStartedAt:g,requestEndedAt:q,duration:q-g};return w?(c.error("endRequest",Tr($)),c.end(),null):(c.log("endRequest",Tr($)),c.end(),L.buffer)}.bind(this));this.fetchByteRangeRepresentation=is(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=is(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:iT(r)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}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:as.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:as.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:as.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:as.FATAL});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${s})`,category:as.FATAL})}}unsubscribeAbortSubscription(e){e&&(e.unsubscribe(),this.subscription.remove(e))}},lo=a=>{if(!Tt(a))throw a};var $t=(a,e,t)=>t*e+(1-t)*a,Fc=(a,e)=>a.reduce((t,i)=>t+i,0)/e,aT=(a,e,t,i)=>{let r=0,s=t,n=Fc(a,e),u=e<i?e:i;for(let o=0;o<u;o++)a[s]>n?r++:r--,s=(a.length+s-1)%a.length;return Math.abs(r)===u};import{isNullable as bC,ValueSubject as sT}from"@vkontakte/videoplayer-shared/es2024";var Kt=class{constructor(e){this.prevReported=void 0;this.pastMeasures=[];this.takenMeasures=0;this.measuresCursor=0;this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new sT(e.initial),this.debounced$=new sT(e.initial);let t=e.label??"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new Ae(`raw_${t}`),this.smoothedSeries$=new Ae(`smoothed_${t}`),this.reportedSeries$=new Ae(`reported_${t}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,i=0;for(let u=0;u<this.pastMeasures.length;u++)this.pastMeasures[u]!==void 0&&(t+=(this.pastMeasures[u]-this.smoothed)**2,i++);this.takenMeasures=i,t/=i;let r=Math.sqrt(t),s=this.smoothed+this.params.deviationFactor*r,n=this.smoothed-this.params.deviationFactor*r;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(e),this.updateSmoothedValue(e),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),!(this.smoothed>s||this.smoothed<n)&&(bC(this.prevReported)||Math.abs(this.smoothed-this.prevReported)/this.prevReported>=this.params.changeThreshold)&&(this.prevReported=this.smoothed,this.debounced$.next(this.smoothed),this.reportedSeries$.next(this.smoothed))}};var po=class extends Kt{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=$t(this.slow,e,this.params.emaAlphaSlow),this.fast=$t(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var ho=class extends Kt{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=Fc(this.pastMeasures,this.takenMeasures);this.emaSmoothed=$t(this.emaSmoothed,e,this.params.emaAlpha);let i=aT(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=i?this.emaSmoothed:t}};var fo=class extends Kt{constructor(t){super(t);this.furtherValues=[];this.currentTopExtremumValue=0;this.extremumInterval=t.extremumInterval}next(t){this.currentTopExtremumValue<=t?(this.currentTopExtremumValue=t,this.furtherValues=[]):this.furtherValues.length===this.extremumInterval?(super.next(this.currentTopExtremumValue),this.currentTopExtremumValue=t,this.furtherValues=[]):this.furtherValues.push(t)}updateSmoothedValue(t){this.smoothed=this.smoothed?$t(this.smoothed,t,this.params.emaAlpha):t}};var Mt=class{static getSmoothedValue(e,t,i){return i.type==="TwoEma"?new po({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new ho({initial:e,emaAlpha:i.emaAlpha,basisTrendChangeCount:i.basisTrendChangeCount,changeThreshold:i.changeThreshold,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"})}static getLiveBufferSmoothedValue(e,t){return new fo({initial:e,label:"liveEdgeDelay",...t})}};var Ir=(a,e)=>{a&&a.playbackRate!==e&&(a.playbackRate=e)};import{isNullable as gC,ValueSubject as SC}from"@vkontakte/videoplayer-shared/es2024";var ss=class a{constructor(e,t){this.currentRepresentation$=new SC(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(!gC(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&&He(t.segmentReference))}};var bo=C(at(),1),Nc=C(De(),1);import{assertNever as go}from"@vkontakte/videoplayer-shared/es2024";var mo=a=>{let{webmDecodingInfo:e}=B.video,t="DASH_WEBM",i="DASH_WEBM_AV1";switch(a){case"vp9":return[t,i];case"av1":return[i,t];case"none":return[];case"smooth":return e?e[i].smooth?[i,t]:e[t].smooth?[t,i]:[i,t]:[t,i];case"power_efficient":return e?e[i].powerEfficient?[i,t]:e[t].powerEfficient?[t,i]:[i,t]:[t,i];default:go(a)}return[t,i]},nT=({webmCodec:a,androidPreferredFormat:e,iosPreferredFormat:t,preferMultiStream:i})=>{let r=[...i?["DASH_STREAMS"]:[],...mo(a),"DASH_SEP","DASH_ONDEMAND",...i?[]:["DASH_STREAMS"]],s=[...i?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...i?[]:["DASH_STREAMS"]];if(B.device.isAndroid)switch(e){case"mpeg":return["MPEG",...r,"HLS","HLS_ONDEMAND"];case"hls":return["HLS","HLS_ONDEMAND",...r,"MPEG"];case"dash":return[...r,"HLS","HLS_ONDEMAND","MPEG"];case"dash_any_mpeg":return[...s,"MPEG",...mo(a),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...mo(a),"MPEG",...s,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...mo(a),...s,"HLS","HLS_ONDEMAND"];default:go(e)}if(B.video.nativeHlsSupported)switch(t){case"hls":return[...r,"HLS","HLS_FMP4","HLS_ONDEMAND","MPEG"];case"hls_fmp4":return[...r,"HLS_FMP4","HLS","HLS_ONDEMAND","MPEG"];default:go(t)}return[...r,"HLS","HLS_ONDEMAND","MPEG"]},oT=({androidPreferredFormat:a,preferCMAF:e,preferWebRTC:t})=>{let i=e?["DASH_LIVE_CMAF","DASH_LIVE"]:["DASH_LIVE","DASH_LIVE_CMAF"],r=e?["HLS_LIVE_CMAF","HLS_LIVE"]:["HLS_LIVE","HLS_LIVE_CMAF"],s=[...i,...r],n=[...r,...i],u,o=B.device.isMac&&B.browser.isSafari;if(B.device.isAndroid)switch(a){case"dash":case"dash_any_mpeg":case"dash_any_webm":case"dash_sep":{u=s;break}case"hls":case"mpeg":{u=n;break}default:go(a)}else B.video.nativeHlsSupported&&!o?u=n:o?u=e?["DASH_LIVE_CMAF","HLS_LIVE_CMAF","HLS_LIVE","DASH_LIVE"]:["HLS_LIVE","DASH_LIVE","DASH_LIVE_CMAF","HLS_LIVE_CMAF"]:u=s;return t?["WEB_RTC_LIVE",...u]:[...u,"WEB_RTC_LIVE"]},qc=a=>a?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],So=a=>{if(a.size===0)return;if(a.size===1){let t=a.values().next();return(0,bo.default)(t.value.split("."),0)}for(let t of a){let i=(0,bo.default)(t.split("."),0);if(i==="opus"||i==="vp09"||i==="av01")return i}let e=a.values().next();return(0,bo.default)(e.value.split("."),0)},vo=a=>{let e=a.map(i=>Er(i)),{codecs:t}=B.video;return IC().filter(i=>{if((0,Nc.default)(e,i))switch(i){case"av1":return t.av1;case"vp9":return t.vp9;case"avc1":return t.h264;case"hev1":return t.h265;default:return!1}else return!1})},yo=a=>{let e=a.map(i=>Er(i)),{codecs:t}=B.video;return EC().filter(i=>{if((0,Nc.default)(e,i))switch(i){case"opus":return t.opus;case"mp4a":return t.aac;default:return!1}else return!1})},Er=a=>a.split(".")[0].replace("0",""),IC=()=>["av1","vp9","hev1","avc1"],EC=()=>["opus","mp4a"];var kC=["timeupdate","progress","play","seeked","stalled","waiting"],LC=["timeupdate","progress","loadeddata","playing","seeked"];var Io=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.bufferManagers=[];this.subscription=new cT;this.representationSubscription=new cT;this.state$=new F("none");this.currentVideoRepresentation$=new ee(void 0);this.currentVideoRepresentationInit$=new ee(void 0);this.currentAudioRepresentation$=new ee(void 0);this.currentVideoSegmentLength$=new ee(0);this.currentAudioSegmentLength$=new ee(0);this.error$=new Xt;this.manifestRequested=new Xt;this.manifestReceived=new Xt;this.firstBytesRequested=new Xt;this.firstBytesReceived=new Xt;this.lastConnectionType$=new ee(void 0);this.lastConnectionReused$=new ee(void 0);this.lastRequestFirstBytes$=new ee(void 0);this.currentLiveTextRepresentation$=new ee(null);this.isLive$=new ee(!1);this.isActiveLive$=new ee(!1);this.isLowLatency$=new ee(!1);this.liveDuration$=new ee(0);this.liveSeekableDuration$=new ee(0);this.liveAvailabilityStartTime$=new ee(0);this.liveStreamStatus$=new ee(void 0);this.bufferLength$=new ee(0);this.liveLatency$=new ee(void 0);this.liveLoadBufferLength$=new ee(0);this.livePositionFromPlayer$=new ee(0);this.currentStallDuration$=new ee(0);this.videoLastDataObtainedTimestamp$=new ee(0);this.fetcherRecoverableError$=new Xt;this.fetcherError$=new Xt;this.liveStreamEndTimestamp=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.forceEnded$=new Xt;this.gapWatchdogActive=!1;this.destroyController=new X;this.initManifest=Hc(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:ot.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=Hc(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:ot.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:ot.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,pT.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);B.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",os(u)),u}.bind(this));this.initRepresentations=Hc(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initRepresentationsStart",os({initialVideo:e,initialAudio:t,sourceHls:i})),xr(this.manifest),xr(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let r=c=>{this.representationSubscription.add(Dt(c,"error").pipe(To(h=>!!this.element?.played.length)).subscribe(h=>{this.error$.next({id:"VideoSource",category:ot.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 ts("video",this.source,u,n),this.bufferManagers=[this.videoBufferManager],us(t)){let c=this.manifest.streams.audio.reduce((h,f)=>[...h,...f.representations],[]);this.audioBufferManager=new ts("audio",this.source,c,n),this.bufferManagers.push(this.audioBufferManager)}ss.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new ss(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(Ri(...LC.map(c=>Dt(this.element,c))).pipe(Ar(c=>this.element?ve(this.element.buffered,this.element.currentTime*1e3):0),ns(),PC(c=>{c>this.tuning.dash.bufferEmptinessTolerance&&o()})).subscribe(this.bufferLength$)),this.representationSubscription.add(Ri(Dt(this.element,"ended"),this.forceEnded$).subscribe(()=>{o()})),this.isLive$.getValue()){this.subscription.add(this.liveDuration$.pipe(ns()).subscribe(h=>this.liveStreamEndTimestamp=Qc())),this.subscription.add(Dt(this.element,"pause").subscribe(()=>{this.livePauseWatchdogSubscription=jc(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(Dt(this.element,"play").subscribe(h=>this.livePauseWatchdogSubscription?.unsubscribe())),this.representationSubscription.add(wr({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(Ar(({isActiveLive:h,isLowLatency:f})=>h&&f),ns()).subscribe(h=>{this.isManualDecreasePlaybackInLive()||Ir(this.element,1)})),this.representationSubscription.add(wr({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(To(({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(wr({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe(To(({isLive:h})=>h),ns((h,f)=>f.bufferLength<h.bufferLength),Ar(({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(wr({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(wr({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(RC(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,k=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),L=S<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next(L);let w="none";if(k?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:ot.VIDEO_PIPELINE,thrown:h,message:"Failed to update live with subscription"})}))}let l=Ri(...this.bufferManagers.map(c=>c.fullyBuffered$)).pipe(Ar(()=>this.bufferManagers.every(c=>c.fullyBuffered$.getValue()))),p=Ri(...this.bufferManagers.map(c=>c.onLastSegment$)).pipe(Ar(()=>this.bufferManagers.some(c=>c.onLastSegment$.getValue()))),d=wr({allBuffersFull:l,someBufferEnded:p}).pipe(ns(),Ar(({allBuffersFull:c,someBufferEnded:h})=>c&&h),To(c=>c));if(this.representationSubscription.add(Ri(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:ot.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:c})}})),this.representationSubscription.add(Ri(...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:ot.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,Wc.default)((0,Wc.default)([...this.manifest.streams.audio,...this.manifest.streams.video],h=>h.representations),h=>{let f=[];return h.duration&&f.push(h.duration),He(h.segmentReference)&&h.segmentReference.totalSegmentsDurationMs&&f.push(h.segmentReference.totalSegmentsDurationMs),f})];this.source.duration=Math.max(...c)/1e3}this.audioBufferManager&&us(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=jc(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),t=>{this.error$.next({id:"GapWatchdog",category:ot.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 co({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){xr(this.element);let t=this.liveStreamStatus$.getValue()!=="active"?Qc()-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(){xr(this.element),this.state$.setState("running"),this.subscription.add(Ri(...kC.map(e=>Dt(this.element,e)),Dt(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:ot.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(Dt(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(Dt(this.element,"waiting").subscribe(()=>{this.tuning.dash.useVideoElementWaitingCurrentTimeReassign&&this.element&&this.element.readyState===2&&!this.element.seeking&&ye(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{if(!this.element||this.source?.readyState!=="open")return;let t=this.currentStallDuration$.getValue();t+=50,this.currentStallDuration$.next(t);let i={timeInWaiting:t},r=Qc(),s=100,n=this.videoBufferManager?.lastDataObtainedTimestamp??0;this.videoLastDataObtainedTimestamp$.next(n);let u=this.audioBufferManager?.lastDataObtainedTimestamp??0,o=this.videoBufferManager?.getForwardBufferDuration()??0,l=this.audioBufferManager?.getForwardBufferDuration()??0,p=o<s&&r-n>this.tuning.dash.crashOnStallTWithoutDataTimeout,d=this.audioBufferManager&&l<s&&r-u>this.tuning.dash.crashOnStallTWithoutDataTimeout;if((p||d)&&t>this.tuning.dash.crashOnStallTWithoutDataTimeout||t>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${t} ms`);if(this.isLive$.getValue()&&t%2e3===0){let c=this.normolizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);this.seekLive(c).catch(h=>{this.error$.next({id:"stallIntervalCallback",category:ot.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:h})}),i.liveLastOffset=c}else{let c=this.element.currentTime*1e3;this.videoBufferManager?.maintain(c),this.audioBufferManager?.maintain(c),i.position=c}this.tracer.log("stallIntervalCallback",os(i))};this.stallWatchdogSubscription?.unsubscribe(),this.stallWatchdogSubscription=jc(50).subscribe(e,t=>{this.error$.next({id:"StallWatchdogCallback",category:ot.NETWORK,message:"Can't restore DASH after stall.",thrown:t})}),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){xr(this.element),xr(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()]),!(lT(this.element)||lT(this.videoBufferManager))&&(this.videoBufferManager.maintain(i),this.audioBufferManager?.maintain(i),this.element.currentTime=i/1e3,this.tracer.log("seek",os({requestedPosition:e,forcePrecise:t,position:i})))}warmUpMediaSourceIfNeeded(e=this.element?.currentTime){us(this.element)&&us(this.source)&&us(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=AC(this.tracer.error.bind(this.tracer));this.subscription.add(this.error$.subscribe(e("error")))}isManualDecreasePlaybackInLive(){if(!this.element||!this.isLive$.getValue())return!1;let e=1-this.element.playbackRate;return Number(e.toFixed(2))>Number(this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup.toFixed(2))}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}async updateLive(){this.isUpdatingLive=!0,this.manifest=await this.updateManifest(),this.manifest&&(this.bufferManagers.forEach(e=>e.updateLive(this.manifest)),this.liveTextManager?.updateLive(this.manifest)),this.isUpdatingLive=!1}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.getDebugBufferState();if(!e)return;let t=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),i={isJumpGapAfterSeekLive:this.isJumpGapAfterSeekLive,isActiveLowLatency:t,initialCurrentTime:this.element.currentTime},{usePersistentGaps:r}=this.tuning.dash;this.isJumpGapAfterSeekLive&&!t&&this.element.currentTime>e.to&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let s=this.element.currentTime*1e3,n=[],u=this.element.readyState===1?this.tuning.endGapTolerance:0;for(let o of this.bufferManagers)for(let l of o.gaps)(r&&l.persistent||o.playingRepresentation$.getValue()===l.representation)&&l.from-u<=s&&l.to+u>s&&(this.element.duration*1e3-l.to<this.tuning.endGapTolerance?n.push(1/0):n.push(l.to));if(n.length){let o=Math.max(...n)+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,o===1/0?this.forceEnded$.next():(this.element.currentTime=o/1e3,i={...i,gapEnds:n,jumpTo:o,resultCurrentTime:this.element.currentTime},this.tracer.log("jumpGap",os(i)))}}calculateDurationFromSegments(){return Math.max(this.videoBufferManager?.calculateDurationFromSegments()||0,this.audioBufferManager?.calculateDurationFromSegments()||0)}};var Eo=class{constructor(e,t){this.fov=e,this.orientation=t}};var xo=class{constructor(e,t){this.rotating=!1;this.fading=!1;this.lastTickTS=0;this.lastCameraTurnTS=0;this.fadeStartSpeed=null;this.fadeTime=0;this.camera=e,this.options=t,this.rotationSpeed={x:0,y:0,z:0},this.fadeCorrection=1/(this.options.speedFadeTime/1e3)**2}turnCamera(e=0,t=0,i=0){this.pointCameraTo(this.camera.orientation.x+e,this.camera.orientation.y+t,this.camera.orientation.z+i)}pointCameraTo(e=0,t=0,i=0){t=this.limitCameraRotationY(t);let r=e-this.camera.orientation.x,s=t-this.camera.orientation.y,n=i-this.camera.orientation.z;this.camera.orientation.x=e,this.camera.orientation.y=t,this.camera.orientation.z=i,this.lastCameraTurn={x:r,y:s,z:n},this.lastCameraTurnTS=Date.now()}setRotationSpeed(e,t,i){this.rotationSpeed.x=e??this.rotationSpeed.x,this.rotationSpeed.y=t??this.rotationSpeed.y,this.rotationSpeed.z=i??this.rotationSpeed.z}startRotation(){this.rotating=!0}stopRotation(e=!1){e?(this.setRotationSpeed(0,0,0),this.fadeStartSpeed=null):this.startFading(this.rotationSpeed.x,this.rotationSpeed.y,this.rotationSpeed.z),this.rotating=!1}onCameraRelease(){if(this.lastCameraTurn&&this.lastCameraTurnTS){let e=Date.now()-this.lastCameraTurnTS;if(e<this.options.speedFadeThreshold){let t=(1-e/this.options.speedFadeThreshold)*this.options.rotationSpeedCorrection;this.startFading(this.lastCameraTurn.x*t,this.lastCameraTurn.y*t,this.lastCameraTurn.z*t)}}}startFading(e,t,i){this.setRotationSpeed(e,t,i),this.fadeStartSpeed={...this.rotationSpeed},this.fading=!0}stopFading(){this.fadeStartSpeed=null,this.fading=!0,this.fadeTime=0}limitCameraRotationY(e){return Math.max(-this.options.maxYawAngle,Math.min(e,this.options.maxYawAngle))}tick(e){if(!this.lastTickTS){this.lastTickTS=e,this.lastCameraTurnTS=Date.now();return}let t=e-this.lastTickTS,i=t/1e3;if(this.rotating)this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*i,this.rotationSpeed.y*this.options.rotationSpeedCorrection*i,this.rotationSpeed.z*this.options.rotationSpeedCorrection*i);else if(this.fading&&this.fadeStartSpeed){let r=-this.fadeCorrection*(this.fadeTime/1e3)**2+1;this.setRotationSpeed(this.fadeStartSpeed.x*r,this.fadeStartSpeed.y*r,this.fadeStartSpeed.z*r),r>0?this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*i,this.rotationSpeed.y*this.options.rotationSpeedCorrection*i,this.rotationSpeed.z*this.options.rotationSpeedCorrection*i):(this.stopRotation(!0),this.stopFading()),this.fadeTime=Math.min(this.fadeTime+t,this.options.speedFadeTime)}this.lastTickTS=e}};var hT=`attribute vec2 a_vertex;
125
125
  attribute vec2 a_texel;
126
126
 
127
127
  varying vec2 v_texel;
@@ -132,7 +132,7 @@ void main(void) {
132
132
  // save texel vector to pass to fragment shader
133
133
  v_texel = a_texel;
134
134
  }
135
- `;var pT=`#ifdef GL_ES
135
+ `;var fT=`#ifdef GL_ES
136
136
  precision highp float;
137
137
  precision highp int;
138
138
  #else
@@ -175,6 +175,6 @@ void main(void) {
175
175
  // sample using new coordinates
176
176
  gl_FragColor = texture2D(u_texture, tc);
177
177
  }
178
- `;var Ar=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 mo(this.params.fov,this.params.orientation),this.cameraRotationManager=new bo(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(dT,this.gl.VERTEX_SHADER),i=this.createShader(pT,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,c=t+r,p=e-i,d=t+r;return[s,n,u,o,l,c,p,d]}updateTextureMappingBuffer(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([...this.calculateTexturePosition()]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}updateFrameSize(){this.frameWidth=this.sourceVideoElement.videoWidth,this.frameHeight=this.sourceVideoElement.videoHeight}createCanvas(){let e=document.createElement("canvas");return e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e}};import{isNullable as $C,now as os,once as MC,Subscription as DC,ValueSubject as Uc,isNonNullable as CC,safeStorage as Hc,filterChanged as BC}from"@vkontakte/videoplayer-shared/es2024";var go="stalls_manager_metrics",jc="stalls_manager_abr_params",hT="stalls_manager_default_tuning_abr_params",Qc=class{constructor(){this.isSeeked$=new Uc(!1);this.isBuffering$=new Uc(!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 DC;this.severeStallOccurred$=new Uc(!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(jc):{};return{...this.abrParams,...e}}set lastVideoTrackSelected(e){this.lastUniqueVideoTrackSelected?.id!==e.id&&(this.lastUniqueVideoTrackSelected=e,this.lastUniqueVideoTrackSelectedTimestamp=os(),this.currentStallsCount=0)}destroy(){window.clearTimeout(this.qualityRestrictionTimer),this.subscription.unsubscribe(),this.currentStallDuration$.getValue()!==0&&this.updateStallData();let e=(os()-this.providerStartWatchingTimestamp-this.sumStallsDuration)/1e3,t=this.sumStallsDuration;this.addStallInfoToHistory(e,t),this.updateStoredAbrParams()}resetStoredAbrParamsIfNeeded(){let{bitrateFactorAtEmptyBuffer:e,bitrateFactorAtFullBuffer:t,containerSizeFactor:i}={...this.getStoredData(hT)},{bitrateFactorAtEmptyBuffer:r,bitrateFactorAtFullBuffer:s,containerSizeFactor:n}={...this.abrParams};this.tuning.enabled&&e===r&&t===s&&i===n||(this.removeStoredData(jc),this.setStoredData(hT,{bitrateFactorAtEmptyBuffer:r,bitrateFactorAtFullBuffer:s,containerSizeFactor:n}))}updateStoredAbrParams(){let e=[],t=this.getStoredData(go,"[]");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(go,[]),this.setStoredData(jc,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),c=this.abrTuningParams;return e<i-r?c={bitrateFactorAtEmptyBuffer:Math.max(c.bitrateFactorAtEmptyBuffer-l,this.abrParams.minBitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.max(c.bitrateFactorAtFullBuffer-l,this.abrParams.minBitrateFactorAtFullBuffer),containerSizeFactor:Math.min(c.containerSizeFactor+l,this.abrParams.maxContainerSizeFactor)}:e>i+r&&(c={bitrateFactorAtEmptyBuffer:Math.min(c.bitrateFactorAtEmptyBuffer+l,this.abrParams.maxBitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.min(c.bitrateFactorAtFullBuffer+l,this.abrParams.maxBitrateFactorAtFullBuffer),containerSizeFactor:Math.max(c.containerSizeFactor-l,this.abrParams.minContainerSizeFactor)}),e>s&&(c={bitrateFactorAtEmptyBuffer:Math.max(c.bitrateFactorAtEmptyBuffer,this.abrParams.bitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.max(c.bitrateFactorAtFullBuffer,this.abrParams.bitrateFactorAtFullBuffer),containerSizeFactor:Math.min(c.containerSizeFactor,this.abrParams.containerSizeFactor)}),c}getStoredData(e,t="{}"){return JSON.parse(Hc.get(e)??t)}setStoredData(e,t){Hc.set(e,JSON.stringify(t))}removeStoredData(e){Hc.remove(e)}addStallInfoToHistory(e,t){if(e<this.tuning.minTvtToBeCounted||e>this.tuning.maxTvtToBeCounted||e*1e3<t)return;let i=this.getStoredData(go,"[]"),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(go,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(MC()).subscribe(t=>this.providerStartWatchingTimestamp=os())),this.subscription.add(this.currentStallDuration$.pipe(BC()).subscribe(t=>{let{stallDurationNoDataBeforeQualityDecrease:i,stallCountBeforeQualityDecrease:r,resetQualityRestrictionTimeout:s,ignoreStallsOnSeek:n}=this.tuning;if($C(this.lastUniqueVideoTrackSelected)||n&&this.isSeeked$.getValue())return;let u=this.rtt$.getValue(),o=this.throughput$.getValue(),l=this.videoLastDataObtainedTimestamp$.getValue(),c=os(),p=r&&this.currentStallsCount>=r,d=i&&c-this.lastUniqueVideoTrackSelectedTimestamp>=i+u&&c-l>=i+u&&t>=i;(p||d)&&(this.severeStallOccurred$.next(!0),window.clearTimeout(this.qualityRestrictionTimer),this.maxQualityLimit=this.lastUniqueVideoTrackSelected.quality,CC(this.lastUniqueVideoTrackSelected.bitrate)&&o>this.lastUniqueVideoTrackSelected.bitrate&&(this.predictedThroughputWithoutData=this.lastUniqueVideoTrackSelected.bitrate)),!t&&os()-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}))}},So=Qc;import{combine as VC,map as _C,observeElementSize as OC,Subscription as FC,ValueSubject as Wc,noop as NC}from"@vkontakte/videoplayer-shared/es2024";var vo=class{constructor(){this.subscription=new FC;this.pipSize$=new Wc(void 0);this.videoSize$=new Wc(void 0);this.elementSize$=new Wc(void 0);this.pictureInPictureWindowRemoveEventListener=NC}connect({observableVideo:e,video:t}){let i=r=>{let s=r.target;this.pipSize$.next({width:s.width,height:s.height})};this.subscription.add(OC(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(VC({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe(_C(({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 Ai=class{constructor(e){this.subscription=new GC;this.videoState=new F("stopped");this.observableVideo=null;this.droppedFramesManager=new cr;this.stallsManager=new So;this.elementSizeManager=new vo;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 UC(e)}}};this.init3DScene=e=>{if(this.scene3D)return;this.scene3D=new Ar(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=$e(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(ge(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 fo({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;WC(this.observableVideo)&&(this.observableVideo=Ce(this.video),this.subscription.add(()=>this.observableVideo?.destroy()));let i=this.constructor.name,r=n=>{e.error$.next({id:i,category:fT.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(Gc(l=>!!l.length),bT()).subscribe(l=>{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:l})}));let n=this.params.desiredState.seekState.stateChangeEnded$.pipe(zc(l=>l.to.state!=="none"),yo());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(Gc(mT),bT()),e.firstBytesEvent$),s(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),s(this.videoState.stateChangeEnded$.pipe(zc(l=>l.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(De(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:l})=>{if(l==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let c=this.player.getStreams(),p=this.player.getCodecs();if(HC(c,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let h=[];for(let f of c.audio){h.push(kc(f));let b=[];for(let S of f.representations){let g=Yy(S);b.push(g),this.audioTracksMap.set(g,{stream:f,representation:S})}this.audioStreamsMap.set(f,b)}this.params.output.availableAudioStreams$.next(h)}let d=[];for(let h of c.video){d.push(Rc(h));let f=[];for(let b of h.representations){let S=zy({...b,streamId:h.id});S&&(f.push(S),this.videoTracksMap.set(S,{stream:h,representation:b}))}this.videoStreamsMap.set(h,f)}this.params.output.availableVideoStreams$.next(d);for(let h of c.text)for(let f of h.representations){let b=Ky(h,f);this.textTracksMap.set(b,{stream:h,representation:f})}this.params.output.availableVideoTracks$.next(Array.from(this.videoTracksMap.keys())),this.params.output.availableAudioTracks$.next(Array.from(this.audioTracksMap.keys())),this.params.output.isAudioAvailable$.next(!!this.audioTracksMap.size),p?.video&&this.params.output.availableVideoCodecs$.next(p.video),p?.audio&&this.params.output.availableAudioCodecs$.next(p.audio),this.audioTracksMap.size&&this.textTracksMap.size&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else l==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},r)),this.subscription.add(To(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$,QC(this.video,"progress")).pipe(Gc(()=>this.videoTracksMap.size>0)).subscribe(async()=>{let l=this.player.state$.getState(),c=this.player.state$.getTransition();if(!(0,gT.default)(["manifest_ready","running"],l)||c)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let p=this.selectVideoAudioRepresentations();if(!p)return;let[d,h]=p,f=[...this.videoTracksMap.keys()].find(S=>this.videoTracksMap.get(S)?.representation.id===d.id);mT(f)&&(this.stallsManager.lastVideoTrackSelected=f);let b=this.params.desiredState.autoVideoTrackLimits.getTransition();if(b&&this.params.output.autoVideoTrackLimits$.next(b.to),l==="manifest_ready")await this.player.initRepresentations(d.id,h?.id,this.params.sourceHls);else if(await this.player.switchRepresentation("video",d.id),h){let S=!!t.audioStream.getTransition();await this.player.switchRepresentation("audio",h.id,S)}},r)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:l})=>{this.scene3D&&l&&this.scene3D.pointCameraTo(l.x,l.y)})),this.subscription.add(this.elementSizeManager.subscribe(l=>{this.scene3D&&l&&this.scene3D.setViewportSize(l.width,l.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(yo()).subscribe(l=>{let c=[...this.videoTracksMap.entries()].find(([,{representation:b}])=>b.id===l);if(!c){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[p,{stream:d}]=c,h=this.params.desiredState.videoStream.getTransition();h&&h.to&&h.to.id===d.id&&this.params.desiredState.videoStream.setState(h.to),e.currentVideoTrack$.next(p),e.currentVideoStream$.next(Rc(d));let f=this.player.calculateDurationFromSegments();f&&this.params.output.duration$.next(f/1e3)},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(yo()).subscribe(l=>{let c=[...this.audioTracksMap.entries()].find(([,{representation:f}])=>f.id===l);if(!c){e.currentAudioStream$.next(void 0);return}let[p,{stream:d}]=c,h=this.params.desiredState.audioStream.getTransition();h&&h.to&&h.to.id===d.id&&this.params.desiredState.audioStream.setState(h.to),e.currentAudioStream$.next(kc(d))},r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(l=>{if(l?.is3dVideo&&this.params.tuning.spherical?.enabled)try{this.init3DScene(l),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 u=t.playbackState.stateChangeStarted$.pipe(zc(({to:l})=>l==="ready"),yo());this.subscription.add(To(u,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,Yc(["init"])).subscribe(()=>{let l=t.autoVideoTrackSwitching.getState(),p=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:l?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(p)})),this.subscription.add(To(u,this.player.state$.stateChangeEnded$,Yc(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let o=To(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Yc(["init"])).pipe(jC(0));this.subscription.add(o.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?ba:ma,t=this.params.tuning.useNewAutoSelectVideoTrack?Nn:Fn,i=this.params.tuning.useNewAutoSelectVideoTrack?St:On,{desiredState:r,output:s}=this.params,n=r.autoVideoTrackSwitching.getState(),u=r.videoTrack.getState()?.id,l=[...this.videoTracksMap.keys()].find(({id:T})=>T===u),c=s.currentVideoTrack$.getValue(),p=r.videoStream.getState()??(l&&this.videoTracksMap.get(l)?.stream)??this.videoStreamsMap.size===1?this.videoStreamsMap.keys().next().value:void 0;if(!p)return;let d=[...this.videoStreamsMap.keys()].find(({id:T})=>T===p.id),h=d&&this.videoStreamsMap.get(d);if(!h)return;let f=he(this.video.buffered,this.video.currentTime*1e3),b;this.player.isActiveLive$.getValue()?b=this.player.isLowLatency$.getValue()?this.params.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.params.tuning.dashCmafLive.normalizedLiveMinBufferSize:this.player.isLive$.getValue()?b=this.params.tuning.dashCmafLive.normalizedTargetMinBufferSize:b=n?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;let S=(this.video.duration*1e3||1/0)-this.video.currentTime*1e3,g=Math.min(f/Math.min(b,S||1/0),1),I=r.audioStream.getState()??(this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0),x=[...this.audioStreamsMap.keys()].find(({id:T})=>T===I?.id)??this.audioStreamsMap.keys().next().value,y=0;if(x){if(l&&!n){let T=e(l,h,this.audioStreamsMap.get(x)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);y=Math.max(y,T?.bitrate??-1/0)}if(c){let T=e(c,h,this.audioStreamsMap.get(x)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);y=Math.max(y,T?.bitrate??-1/0)}}let w=i(h,{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:y,forwardBufferHealth:g,current:c,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}),D=n?w??l:l??w,L=x&&t(D,h,this.audioStreamsMap.get(x)??[],{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}),A=this.videoTracksMap.get(D)?.representation,R=L&&this.audioTracksMap.get(L)?.representation;if(A&&R)return[A,R];if(A&&!R&&this.audioTracksMap.size===0)return[A,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){Be(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.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:fT.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),Me(this.video),this.tracer.end()}};var us=class extends Ai{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 Kc,merge as ST,filter as vT,filterChanged as yT,isNullable as Xc,map as TT,ValueSubject as Jc,isNonNullable as zC}from"@vkontakte/videoplayer-shared/es2024";var ls=class extends Ai{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 Jc(1);n(r.playbackRateState$,u),this.params.tuning.dashCmafLive.catchupLiveForMutedInactiveTab&&this.subscription.add(i.elementVisible$.pipe(yT()).subscribe(o=>{let l=i.position$.getValue(),c=i.volume$.getValue(),p=!c.volume||c.muted;!o&&!l&&p?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(TT(o=>o.to)).subscribe(this.player.isLowLatency$)).add(Kc({liveBufferTime:i.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(TT(({liveBufferTime:o,liveAvailabilityStartTime:l})=>o&&l?o+l:void 0)).subscribe(i.liveTime$)).add(this.player.liveStreamStatus$.pipe(vT(o=>zC(o))).subscribe(o=>i.isLiveEnded$.next(o!=="active"&&i.position$.getValue()===0))).add(Kc({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:ST(r.playbackRateState$,new Jc(1))}).pipe(vT(({liveStreamStatus:o,liveDuration:l})=>o==="active"&&!!l)).subscribe(({liveDuration:o,playbackRate:l})=>{let c=i.liveBufferTime$.getValue(),p=i.position$.getValue(),{playbackCatchupSpeedup:d}=this.params.tuning.dashCmafLive.lowLatency;p||l<1-d||this.video.paused||Xc(c)||(t=o-c)})).add(Kc({time:i.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:ST(r.playbackRateState$,new Jc(1))}).pipe(yT((o,l)=>this.player.liveStreamStatus$.getValue()==="active"?o.liveDuration===l.liveDuration:o.time===l.time)).subscribe(({time:o,liveDuration:l,playbackRate:c})=>{let p=i.position$.getValue(),{playbackCatchupSpeedup:d}=this.params.tuning.dashCmafLive.lowLatency;if(!p&&!this.video.paused&&c>=1-d||Xc(o)||Xc(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=Xy(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 yB,assertNonNullable as TB,debounce as IB,ErrorCategory as FT,filter as fd,filterChanged as Mo,fromEvent as EB,isNonNullable as NT,isNullable as xB,map as md,merge as Do,observableFrom as bd,once as qT,Subscription as wB}from"@vkontakte/videoplayer-shared/es2024";var OT=C(Ee(),1),pd=C(xa(),1);import{abortable as ud,assertNonNullable as Lr,combine as $r,ErrorCategory as ut,filter as Ro,filterChanged as ms,flattenObject as bs,fromEvent as It,getTraceSubscriptionMethod as cB,interval as ld,isNonNullable as gs,isNullable as VT,map as Mr,merge as $i,now as cd,Subject as Jt,Subscription as dd,tap as dB,throttle as _T,ValueSubject as te}from"@vkontakte/videoplayer-shared/es2024";var wo=C(Ee(),1),Li=C(at(),1),Ao=C(xa(),1);var MT=C(gn(),1);import{assertNever as YC,ErrorCategory as IT,Subject as ET}from"@vkontakte/videoplayer-shared/es2024";var KC=18,xT=!1;try{xT=B.browser.isSafari&&!!B.browser.safariVersion&&B.browser.safariVersion<=KC}catch(a){console.error(a)}var Zc=class{constructor(e){this.bufferFull$=new ET;this.error$=new ET;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:IT.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)};xT&&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:IT.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:YC(t)}}},wT=Zc;import{abortable as Xt,assertNonNullable as _e,ErrorCategory as ki,fromEvent as ad,getExponentialDelay as sd,isNonNullable as Pr,isNullable as ye,now as xo,once as tB,Subject as iB,Subscription as rB,ValueSubject as Ri}from"@vkontakte/videoplayer-shared/es2024";var ed=C(at(),1);import{videoSizeToQuality as XC,throttleFn as JC}from"@vkontakte/videoplayer-shared/es2024";var AT=({id:a,width:e,height:t,bitrate:i,fps:r,quality:s,streamId:n})=>{let u=(s?jt(s):void 0)??XC({width:e,height:t});return u&&{id:a,quality:u,bitrate:i,size:{width:e,height:t},fps:r,streamId:n}},PT=({id:a,bitrate:e})=>({id:a,bitrate:e}),kT=({language:a,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:a,label:e}),RT=({language:a,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:a,label:e}),td=({id:a,language:e,label:t,codecs:i,isDefault:r})=>({id:a,language:e,label:t,codec:(0,ed.default)(i.split("."),0),isDefault:r}),id=({id:a,language:e,label:t,hdr:i,codecs:r})=>({id:a,language:e,hdr:i,label:t,codec:(0,ed.default)(r.split("."),0)}),rd=a=>"url"in a,je=a=>a.type==="template";var LT=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},Pi=(a,e)=>{for(let t of a)if(e(t))return t;return null},$T=a=>{let e=!1,t=JC(()=>{e=!0},a);return()=>{try{return t(),e}finally{e=!1}}};import{fromEvent as ZC,Subscription as eB}from"@vkontakte/videoplayer-shared/es2024";var Io=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 Eo=class{constructor(e,t){this.lastUpdateTs=0;this.lastCallTs=0;this.prevRanges=[];this.subscription=new eB;this.mediaSource=e,this.sourceBuffer=t,this.subscription.add(ZC(this.sourceBuffer,"updateend").subscribe(()=>this.updateend()))}updateend(){if(!V(this.mediaSource,this.sourceBuffer))return;let{prevRanges:e}=this,t=Io(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 cs=class{constructor(e,t,i,{fetcher:r,tuning:s,getCurrentPosition:n,isActiveLowLatency:u,compatibilityMode:o=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new Ri(0);this.currentLowLatencySegmentLength$=new Ri(0);this.currentSegmentLength$=new Ri(0);this.onLastSegment$=new Ri(!1);this.fullyBuffered$=new Ri(!1);this.playingRepresentation$=new Ri(void 0);this.playingRepresentationInit$=new Ri(void 0);this.error$=new iB;this.gaps=[];this.subscription=new rB;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new X;this.switchAbortController=new X;this.destroyAbortController=new X;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=Xt(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);_e(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new wT(this.sourceBuffer),this.sourceBufferBufferedDiff=new Eo(this.mediaSource,this.sourceBuffer),this.subscription.add(ad(this.sourceBuffer,"updateend").subscribe(()=>{this.maintain()})),this.subscription.add(ad(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:ki.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,hr(this.sourceBuffer.buffered)*.8);this.bufferLimit=o;let l=he(this.sourceBuffer.buffered,u),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(u,n*2,l<c).catch(p=>{this.handleAsyncError(p,"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);_e(i,"No init buffer for starting representation"),_e(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=Xt(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);_e(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if(ye(s)||ye(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),_e(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();Pr(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=Xt(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);_e(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if(ye(s)||ye(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),_e(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();Pr(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=Xt(this.destroyAbortController.signal,async function*(e){let t=(0,Ao.default)(e,o=>o.representations)??[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let o of this.representations.keys()){let l=t.find(d=>d.id===o);l&&this.representations.set(o,l);let c=this.representations.get(o);if(!c||!je(c.segmentReference))return;let p=this.getActualLiveStartingSegments(c.segmentReference);this.segments.set(c.id,p)}let i=this.switchingToRepresentationId??this.downloadingRepresentationId,r=this.representations.get(i);_e(r);let s=this.segments.get(i);_e(s,"No segments for starting representation");let n=this.initData.get(i);if(_e(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(c=>[c.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(i.map(c=>[c.id,c])),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,Xt(this.switchAbortController.signal,async function*(i,r=!1){this.switchingToRepresentationId=i;let s=this.representations.get(i);_e(s,`No such representation ${i}`);let n=this.segments.get(i),u=this.initData.get(i);if(ye(u)||ye(n)?yield this.loadInit(s,"high",!1):u instanceof Promise&&(yield u),n=this.segments.get(i),_e(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();Pr(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(){!ye(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(ye(e)||ye(this.downloadingRepresentationId)||ye(this.playingRepresentationId)||ye(this.sourceBuffer)||!V(this.mediaSource,this.sourceBuffer)||Pr(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if(_e(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;let r=i.find(c=>e>=c.time.from&&e<c.time.to);Pr(r)&&isFinite(r.time.from)&&isFinite(r.time.to)&&this.currentSegmentLength$.next(r?.time.to-r.time.from);let s=e,n=100;if(this.playingRepresentationId!==this.downloadingRepresentationId){let c=he(this.sourceBuffer.buffered,e),p=r?r.time.to+n:-1/0;r&&r.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&c>=r.time.to-e+n&&(s=p)}if(isFinite(this.bufferLimit)&&hr(this.sourceBuffer.buffered)>=this.bufferLimit){let c=he(this.sourceBuffer.buffered,e),p=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,c<p).catch(d=>{this.handleAsyncError(d,"pruneBuffer")});return}let o=null;if(!this.activeSegments.size&&(o=this.selectForwardBufferSegments(i,t.segmentReference.type,s),o?.length)){let c="auto";if(this.tuning.dash.useFetchPriorityHints&&r)if((0,wo.default)(o,r))c="high";else{let p=(0,Li.default)(o,0);p&&p.time.from-r.time.to>=this.forwardBufferTarget/2&&(c="low")}this.loadSegments(o,t,c).catch(p=>{this.handleAsyncError(p,"loadSegments")})}(!this.preloadOnly&&!this.allInitsLoaded&&r&&r.status==="fed"&&!o?.length&&he(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let l=(0,Li.default)(i,-1);!this.isLive&&l&&(this.fullyBuffered$.next(l.time.to-e-he(this.sourceBuffer.buffered,e)<n),this.onLastSegment$.next(e-l.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;Pr(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,Ao.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,Ao.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,Li.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;_e(e);let t=this.segments.get(e);if(t?.length){let i=t[t.length-1];this.updateLowLatencyLiveIfNeeded(i)}}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:d,time:{from:h,to:f}},b)=>{let S=h<=i&&f>=i,g=h>i||S||b===0&&i===0,I=Math.min(this.forwardBufferTarget,this.bufferLimit),x=this.preloadOnly&&h<=i+I||r<I&&f-h>=I||f<=i+I;return(d==="none"||d==="partially_ejected"&&g&&x&&this.sourceBuffer&&V(this.mediaSource,this.sourceBuffer)&&!(Se(this.sourceBuffer.buffered,h)&&Se(this.sourceBuffer.buffered,f)))&&g&&x});if(s===-1)return null;if(t!=="byteRange")return e.slice(s,s+1);let n=e,u=0,o=0,l=[],c=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,p=this.preloadOnly?this.forwardBufferTarget:0;for(let d=s;d<n.length&&(u<=c||o<=p);d++){let h=n[d];if(u+=h.byte.to+1-h.byte.from,o+=h.time.to+1-h.time.from,h.status==="none"||h.status==="partially_ejected")l.push(h);else break}return l}async loadSegments(e,t,i="auto"){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 Xt(u,async function*(){let c=sd(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(p=>setTimeout(p,c))}.bind(this))(),u.aborted&&this.abortActiveSegments([e]));try{let c=await this.fetcher.fetch(n,{range:s,signal:u,onProgress:o,priority:i,isLowLatency:this.isActiveLowLatency(),bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation});if(this.lastDataObtainedTimestampMs=xo(),!c)return;let p=new DataView(c),d=yt(t.mime);if(!isFinite(r.segment.time.to)){let b=t.segmentReference.timescale;r.segment.time.to=d.getChunkEndTime(p,b)}o&&r.feedingBytes&&l?await Promise.all(l):await this.sourceBufferTaskQueue.append(p,u);let{serverDataReceivedTimestamp:h,serverDataPreparedTime:f}=d.getServerLatencyTimestamps(p);h&&f&&this.currentLiveSegmentServerLatency$.next(f-h),r.segment.status="downloaded",this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(c){this.abortActiveSegments([e]),Tt(c)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}updateRepresentationsBaseUrlIfNeeded(){if(!this.tuning.dash.enableBaseUrlSupport||!this.baseUrls.length||this.failedDownloads<=this.tuning.dash.maxSegmentRetryCount)return;this.baseUrlsIndex=(this.baseUrlsIndex+1)%this.baseUrls.length;let e=this.baseUrls[this.baseUrlsIndex];for(let t of this.representations.values())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 Xt(n,async function*(){let o=sd(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,o),ad(window,"online").pipe(tB()).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=xo(),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,Li.default)(e,0).byte.from,to:(0,Li.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=xo(),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:ki.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,c)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=xo();let p=this.onSomeTemplateDataLoaded({dataView:l,loaded:c,signal:s,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(p)}catch(p){this.error$.next({id:"SegmentFeeding",category:ki.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:p})}}:void 0;return{url:r,signal:s,onProgress:o,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)(0,wo.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),c=yt(n.mime).parseFeedableSegmentChunk(l,this.isLive);c?.byteLength&&(o.status="partially_fed",u.feedingBytes+=c.byteLength,await this.sourceBufferTaskQueue.append(c),u.fedBytes+=c.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,c=l.byte.from-i,p=l.byte.to-i,d=p-c+1,h=c<r,f=p<=r;if(h){if(l.status==="downloading"&&f){l.status="downloaded";let b=new DataView(e.buffer,e.byteOffset+c,d);await this.sourceBufferTaskQueue.append(b,s)&&!s.aborted?this.onSegmentFullyAppended(o,t):await n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(l.status==="downloading"||l.status==="partially_fed")&&(o.loadedBytes=Math.min(d,r-c),o.loadedBytes>o.feedingBytes)){let b=new DataView(e.buffer,e.byteOffset+c+o.feedingBytes,o.loadedBytes-o.feedingBytes),S=o.loadedBytes===d?b:yt(u.mime).parseFeedableSegmentChunk(b);S?.byteLength&&(l.status="partially_fed",o.feedingBytes+=S.byteLength,await this.sourceBufferTaskQueue.append(S,s)&&!s.aborted?(o.fedBytes+=S.byteLength,o.fedBytes===d&&this.onSegmentFullyAppended(o,t)):await n())}}}}onSegmentFullyAppended(e,t){if(!(ye(this.sourceBuffer)||!V(this.mediaSource,this.sourceBuffer))){!this.isLive&&B.browser.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(Se(this.sourceBuffer.buffered,e.segment.time.from,100)&&Se(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:ki.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",rd(e.segment)&&(e.segment.size=e.fedBytes);for(let i of this.representations.values()){if(i.id===t)continue;let r=this.segments.get(i.id);if(r)for(let s of r)s.status==="fed"&&Math.round(s.time.from)===Math.round(e.segment.time.from)&&Math.round(s.time.to)===Math.round(e.segment.time.to)&&(s.status="none")}this.isActiveLowLatency()&&this.updateLowLatencyLiveIfNeeded(e.segment),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,e.segment)}}abortSegment(e){e.status==="partially_fed"?e.status="partially_ejected":e.status!=="partially_ejected"&&(e.status="none");for(let t of this.activeSegments.values())if(t.segment===e){this.activeSegments.delete(t);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(let[r,s]of this.initData.entries()){let n=s instanceof Promise;t||=n,s===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let i=this.representations.get(e);i&&(this.initLoadIdleCallback=pr(()=>(0,MT.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?Xt(this.destroyAbortController.signal,async function*(){let u=sd(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:c}=u,p=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,p);let d=c;this.isLive&&je(e.segmentReference)&&(d=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,d),o&&this.parsedInitData.set(e.id,o)}).then(()=>this.failedDownloads=0,u=>{this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:ki.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||ye(e))return!1;this.checkEjectedSegments();let r=[],s=0,n=u=>{if(s>=t)return;r.push({...u.time});let o=rd(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,c=o.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(l||c)&&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,c=0;for(let p of this.segments.values())for(let d of p)(0,wo.default)(["none","partially_ejected"],d.status)&&Math.round(d.time.from)<=Math.round(o)&&Math.round(d.time.to)>=Math.round(l)&&c++;if(c===this.segments.size){let p={time:{from:o,to:l},url:"",status:"none"};n(p)}}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=LT(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||ye(e)?0:he(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!this.sourceBuffer||!V(this.mediaSource,this.sourceBuffer))return;let{buffered:i}=this.sourceBuffer;this.tuning.useRefactoredSearchGap&&(this.gaps=this.gaps.filter(s=>{if(s.persistent)return!0;let n=Math.round(s.from),u=Math.round(s.to);for(let o=0;o<i.length;o++)if(n>=Math.round(i.start(o)*1e3)&&u<=Math.round(i.end(o)*1e3))return!1;return!0}));let 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))){if(!this.tuning.useRefactoredSearchGap)for(let i=0;i<this.sourceBuffer.buffered.length;i++)this.gaps=this.gaps.filter(r=>r.persistent||this.sourceBuffer&&(Math.round(r.from)<Math.round(this.sourceBuffer.buffered.start(i)*1e3)||Math.round(r.to)>Math.round(this.sourceBuffer.buffered.end(i)*1e3)));this.gapDetectionIdleCallback=pr(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:ki.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if(ye(this.sourceBuffer)||!V(this.mediaSource,this.sourceBuffer)||ye(this.playingRepresentationId)||this.sourceBufferBufferedDiff&&!this.sourceBufferBufferedDiff.wasUpdated())return;let e=Io(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 c=0;c<e.length;c+=2){let p=e[c],d=e[c+1];o||(o=p-t<=n&&d+t>=u),(n>=p&&n<d-t||u>p+t&&u<=d)&&(l+=1)}o||(l===1?r.status="partially_ejected":this.gaps.some(c=>c.from===r.time.from||c.to===r.time.to)?r.status="partially_ejected":r.status="none")}}handleAsyncError(e,t){this.error$.next({id:t,category:ki.VIDEO_PIPELINE,thrown:e,message:"Something went wrong"})}calculateDurationFromSegments(){if(!this.playingRepresentationId)return 0;let e=this.segments.get(this.playingRepresentationId);return(e?(0,Li.default)(e,-1)?.time.to:0)||0}};import{abortable as ds,assertNever as DT,fromEvent as CT,merge as aB,now as ps,Subject as kr,ValueSubject as nd,flattenObject as Rr,ErrorCategory as hs,SubscriptionRemovable as sB}from"@vkontakte/videoplayer-shared/es2024";var ko=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:s=!1}){this.manifestRequested=new kr;this.manifestReceived=new kr;this.firstBytesRequested=new kr;this.firstBytesReceived=new kr;this.lastConnectionType$=new nd(void 0);this.lastConnectionReused$=new nd(void 0);this.lastRequestFirstBytes$=new nd(void 0);this.recoverableError$=new kr;this.error$=new kr;this.abortAllController=new X;this.subscription=new sB;this.fetchManifest=ds(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=zt(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=eo(i)),this.manifestRequested.next();let r=yield this.doFetch(i,{signal:this.abortAllController.signal}).catch(Po);return r?(t.log("success",Rr({url:i,message:"Request successfully executed"})),t.end(),this.manifestReceived.next(),this.onHeadersReceived(r.headers),r.text()):(t.error("error",Rr({url:i,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=ds(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 c=e,p=new Headers,d=this.tracer.createComponentTracer("Fetch");if(i)switch(t){case 0:{p.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let v=new URL(c,location.href);v.searchParams.append("bytes",`${i.from}-${i.to}`),c=v.toString();break}default:DT(t)}this.requestQuic&&(c=zt(c));let h=this.abortAllController.signal,f;if(n){let v=new X;if(f=aB(CT(this.abortAllController.signal,"abort"),CT(n,"abort")).subscribe(()=>{try{v.abort()}catch(E){Po(E)}}),this.subscription.add(f),this.abortAllController.signal.aborted||n.aborted)try{v.abort()}catch(E){Po(E)}h=v.signal}let b=0,S=ps();d.log("startRequest",Rr({url:c,priority:s,rangeMethod:t,range:i,isLowLatency:o,requestStartedAt:S})),this.firstBytesRequested.next();let g=yield this.doFetch(c,{priority:s,headers:p,signal:h}),I=ps();if(!g)return d.error("error",{message:"No response in request"}),d.end(),this.unsubscribeAbortSubscription(f),null;if(this.throughputEstimator?.addRawRtt(I-S),!g.ok||!g.body){this.unsubscribeAbortSubscription(f);let v=`Fetch error ${g.status}: ${g.statusText}`;return d.error("error",{message:v}),d.end(),Promise.reject(new Error(`Fetch error ${g.status}: ${g.statusText}`))}if(this.onHeadersReceived(g.headers),!r&&!u){this.unsubscribeAbortSubscription(f);let v=ps(),E={requestStartedAt:S,requestEndedAt:v,duration:v-S};return d.log("endRequest",Rr(E)),d.end(),g.arrayBuffer()}let x=g.body;if(u){let v;[x,v]=g.body.tee(),this.throughputEstimator?.trackStream(v,o)}let y=x.getReader(),w,D=parseInt(g.headers.get("content-length")??"",10);Number.isFinite(D)&&(w=D),!w&&i&&(w=i.to-i.from+1);let L=w?new Uint8Array(w):new Uint8Array(0),A=!1,R=v=>{this.unsubscribeAbortSubscription(f),A=!0,Po(v)},T=ds(h,async function*({done:v,value:E}){if(b===0&&(this.lastRequestFirstBytes$.next(ps()-S),this.firstBytesReceived.next()),h.aborted){this.unsubscribeAbortSubscription(f);return}if(!v&&E){if(l&&w)L.set(E,b),b+=E.byteLength;else{let z=new Uint8Array(L.length+E.length);z.set(L),z.set(E,L.length),L=z,b+=E.byteLength}r?.(new DataView(L.buffer),b),yield y?.read().then(T,R)}}.bind(this));yield y?.read().then(T,R),this.unsubscribeAbortSubscription(f);let q=ps(),$={failed:A,requestStartedAt:S,requestEndedAt:q,duration:q-S};return A?(d.error("endRequest",Rr($)),d.end(),null):(d.log("endRequest",Rr($)),d.end(),L.buffer)}.bind(this));this.fetchByteRangeRepresentation=ds(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,c;e.indexRange&&(l=e.indexRange.from,c=e.indexRange.to,o=s+1===l,o&&(n=Math.min(l,r),u=Math.max(c,s))),n=Math.min(n,0);let p=yield this.fetch(e.url,{range:{from:n,to:u},priority:i,measureThroughput:!1});if(!p)return null;let d=new DataView(p,r-n,s-n+1);if(!t.validateData(d))throw new Error("Invalid media file");let h=t.parseInit(d),f=e.indexRange??t.getIndexRange(h);if(!f)throw new ReferenceError("No way to load representation index");let b;if(o)b=new DataView(p,f.from-n,f.to-f.from+1);else{let g=yield this.fetch(e.url,{range:f,priority:i,measureThroughput:!1});if(!g)return null;b=new DataView(g)}let S=t.parseSegments(b,h,f);return{init:h,dataView:new DataView(p),segments:S}}.bind(this));this.fetchTemplateRepresentation=ds(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}=Zn(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:DT(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:hs.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:hs.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:hs.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:hs.FATAL});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${s})`,category:hs.FATAL})}}unsubscribeAbortSubscription(e){e&&(e.unsubscribe(),this.subscription.remove(e))}},Po=a=>{if(!Tt(a))throw a};import{isNullable as nB,ValueSubject as oB}from"@vkontakte/videoplayer-shared/es2024";var fs=class a{constructor(e,t){this.currentRepresentation$=new oB(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(!nB(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 pB=["progress","play","seeked","stalled","waiting"],hB=["timeupdate","progress","loadeddata","playing","seeked"];var Lo=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.bufferManagers=[];this.subscription=new dd;this.representationSubscription=new dd;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 Jt;this.manifestRequested=new Jt;this.manifestReceived=new Jt;this.firstBytesRequested=new Jt;this.firstBytesReceived=new Jt;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 Jt;this.fetcherError$=new Jt;this.liveStreamEndTimestamp=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.forceEnded$=new Jt;this.gapWatchdogActive=!1;this.destroyController=new X;this.initManifest=ud(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=ud(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=Yn(e??"",this.manifestUrlString)}catch(o){let l=Gn(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,c)=>!!(this.element?.canPlayType?.(l)&&Ue()?.isTypeSupported?.(`${l}; codecs="${c}"`)||o==="text");if(t.live){this.isLive$.next(!!t.live);let{availabilityStartTime:o,latestSegmentPublishTime:l,streamIsUnpublished:c,streamIsAlive:p}=t.live,d=(t.duration??0)/1e3;this.liveSeekableDuration$.next(-1*d),this.liveDuration$.next((l-o)/1e3),this.liveAvailabilityStartTime$.next(t.live.availabilityStartTime);let h="active";p||(h=c?"unpublished":"unexpectedly_down"),this.liveStreamStatus$.next(h)}let r={text:t.streams.text,video:[],audio:[]},s,n;for(let o of["video","audio"]){let c=t.streams[o].filter(({mime:d,codecs:h})=>i(o,d,h));r[o]=c;let p;if(this.tuning.dash.codecsPrioritizeEnabled){let d=c.map(({codecs:h})=>h);o==="audio"&&(n=po(d),p=n[0]),o==="video"&&(s=co(d),this.forceVideoCodec&&(0,OT.default)(s,this.forceVideoCodec)?p=this.forceVideoCodec:p=s[0]),p&&(r[o]=c.filter(({codecs:h})=>Ir(h)===p))}else{let d=new Set(c.map(({codecs:h})=>h));p=lo(d),p&&(r[o]=c.filter(({codecs:h})=>h.startsWith(p)))}if(o==="video"){let d=this.tuning.preferHDR,h=r.video.some(b=>b.hdr),f=r.video.some(b=>!b.hdr);B.display.isHDR&&d&&h?r.video=r.video.filter(b=>b.hdr):f&&(r.video=r.video.filter(b=>!b.hdr))}}let u={...t,streams:r};return this.tuning.dash.codecsPrioritizeEnabled&&(u.codecs={video:s,audio:n}),this.tracer.log("updateManifestEnd",bs(u)),u}.bind(this));this.initRepresentations=ud(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initRepresentationsStart",bs({initialVideo:e,initialAudio:t,sourceHls:i})),Lr(this.manifest),Lr(this.element),this.representationSubscription.unsubscribe(),this.representationSubscription=new dd,this.state$.startTransitionTo("representations_ready");let r=d=>{this.representationSubscription.add(It(d,"error").pipe(Ro(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=In();let s=document.createElement("source");if(r(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),ir())if(i){let d=document.createElement("source");r(d),d.type="application/x-mpegurl",d.src=i.url,this.element.appendChild(d)}else this.element.disableRemotePlayback=!0;this.isActiveLive$.next(this.isLive$.getValue());let n={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),manifest:this.manifest},u=this.manifest.streams.video.reduce((d,h)=>[...d,...h.representations],[]);if(this.videoBufferManager=new cs("video",this.source,u,n),this.bufferManagers=[this.videoBufferManager],gs(t)){let d=this.manifest.streams.audio.reduce((h,f)=>[...h,...f.representations],[]);this.audioBufferManager=new cs("audio",this.source,d,n),this.bufferManagers.push(this.audioBufferManager)}fs.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new fs(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($i(...hB.map(d=>It(this.element,d))).pipe(Mr(d=>this.element?he(this.element.buffered,this.element.currentTime*1e3):0),ms(),dB(d=>{d>this.tuning.dash.bufferEmptinessTolerance&&o()})).subscribe(this.bufferLength$)),this.representationSubscription.add($i(It(this.element,"ended"),this.forceEnded$).subscribe(()=>{o()})),this.isLive$.getValue()){this.subscription.add(this.liveDuration$.pipe(ms()).subscribe(h=>this.liveStreamEndTimestamp=cd())),this.subscription.add(It(this.element,"pause").subscribe(()=>{this.livePauseWatchdogSubscription=ld(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($r({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(Mr(({isActiveLive:h,isLowLatency:f})=>h&&f),ms()).subscribe(h=>{this.isManualDecreasePlaybackInLive()||Tr(this.element,1)})),this.representationSubscription.add($r({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(Ro(({bufferLength:h,isActiveLive:f,isLowLatency:b})=>f&&b&&!!h)).subscribe(({bufferLength:h})=>this.liveBuffer.next(h))),this.representationSubscription.add(this.videoBufferManager.currentLowLatencySegmentLength$.subscribe(h=>{if(!this.isActiveLive$.getValue()&&!this.isLowLatency$.getValue()&&!h)return;let 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($r({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe(Ro(({isLive:h})=>h),ms((h,f)=>f.bufferLength<h.bufferLength),Mr(({rtt:h,bufferLength:f,segmentServerLatency:b})=>{let S=Ut(this.manifestUrlString,2);return(h/2+f+b+S)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add($r({liveBuffer:this.liveBuffer.smoothed$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).subscribe(({liveBuffer:h,isActiveLive:f,isLowLatency:b})=>{if(!b||!f)return;let S=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,g=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,I=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,x=h-S;if(this.isManualDecreasePlaybackInLive())return;let y=1;Math.abs(x)>g&&(y=1+Math.sign(x)*I),Tr(this.element,y)})),this.representationSubscription.add(this.bufferLength$.subscribe(h=>{let f=0;if(h){let b=(this.element?.currentTime??0)*1e3;f=Math.min(...this.bufferManagers.map(g=>g.getLiveSegmentsToLoadState(this.manifest)?.to??b))-b}this.liveLoadBufferLength$.getValue()!==f&&this.liveLoadBufferLength$.next(f)}));let d=0;this.representationSubscription.add($r({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(_T(1e3)).subscribe(async({liveLoadBufferLength:h,bufferLength:f})=>{if(!this.element||this.isUpdatingLive)return;let b=this.element.playbackRate,S=Ut(this.manifestUrlString,2),g=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,I=Math.min(g,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*b),x=this.tuning.dashCmafLive.normalizedActualBufferOffset*b,y=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*b,w=isFinite(h)?h:f,D=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),L=g<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next(L);let A="none";if(D?A="active_low_latency":this.isLowLatency$.getValue()&&L?(this.bufferManagers.forEach(R=>R.proceedLowLatencyLive()),A="active_low_latency"):S!==0&&w<I?A="live_forward_buffering":w<I+y&&(A="live_with_target_offset"),isFinite(h)&&(d=h>d?h:d),A==="live_forward_buffering"||A==="live_with_target_offset"){let R=d-(I+x),T=this.normolizeLiveOffset(Math.trunc(S+R/b)),q=Math.abs(T-S),$=0;!h||q<=this.tuning.dashCmafLive.offsetCalculationError?$=S:T>0&&q>this.tuning.dashCmafLive.offsetCalculationError&&($=T),this.manifestUrlString=se(this.manifestUrlString,$,2)}(A==="live_with_target_offset"||A==="live_forward_buffering")&&(d=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=$i(...this.bufferManagers.map(d=>d.fullyBuffered$)).pipe(Mr(()=>this.bufferManagers.every(d=>d.fullyBuffered$.getValue()))),c=$i(...this.bufferManagers.map(d=>d.onLastSegment$)).pipe(Mr(()=>this.bufferManagers.some(d=>d.onLastSegment$.getValue()))),p=$r({allBuffersFull:l,someBufferEnded:c}).pipe(ms(),Mr(({allBuffersFull:d,someBufferEnded:h})=>d&&h),Ro(d=>d));if(this.representationSubscription.add($i(this.forceEnded$,p).subscribe(()=>{if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(d=>!d.updating))try{this.source?.endOfStream()}catch(d){this.error$.next({id:"EndOfStream",category:ut.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:d})}})),this.representationSubscription.add($i(...this.bufferManagers.map(d=>d.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.representationSubscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&(this.representationSubscription.add(this.audioBufferManager.playingRepresentation$.subscribe(this.currentAudioRepresentation$)),this.representationSubscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$))),this.liveTextManager&&this.representationSubscription.add(this.liveTextManager.currentRepresentation$.subscribe(this.currentLiveTextRepresentation$)),this.source.readyState!=="open"){let d=this.tuning.dash.sourceOpenTimeout>=0;yield new Promise(h=>{d&&(this.timeoutSourceOpenId=setTimeout(()=>{if(this.source?.readyState==="open"){h();return}this.error$.next({id:"OpenOfStream",category: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 d=[this.manifest.duration??0,...(0,pd.default)((0,pd.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(...d)/1e3}this.audioBufferManager&&gs(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=ld(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 ko({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()}async seekLive(e){Lr(this.element);let t=this.liveStreamStatus$.getValue()!=="active"?cd()-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(){Lr(this.element),this.state$.setState("running");let e=It(this.element,"timeupdate");this.tuning.dash.timeupdateEventTickThrottle&&(e=e.pipe(_T(this.tuning.dash.timeupdateEventTickThrottle))),this.subscription.add($i(...pB.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.element&&this.element.readyState===HTMLMediaElement.HAVE_CURRENT_DATA&&!this.element.seeking&&Se(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=cd(),n=100,u=this.videoBufferManager?.lastDataObtainedTimestamp??0;this.videoLastDataObtainedTimestamp$.next(u);let o=this.audioBufferManager?.lastDataObtainedTimestamp??0,l=this.videoBufferManager?.getForwardBufferDuration()??0,c=this.audioBufferManager?.getForwardBufferDuration()??0,p=l<n&&s-u>this.tuning.dash.crashOnStallTWithoutDataTimeout,d=this.audioBufferManager&&c<n&&s-o>this.tuning.dash.crashOnStallTWithoutDataTimeout;if((p||d)&&i>this.tuning.dash.crashOnStallTWithoutDataTimeout||i>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${i} ms`);if(this.isLive$.getValue()&&i%2e3===0){let h=this.normolizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);this.seekLive(h).catch(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",bs(r))};this.stallWatchdogSubscription?.unsubscribe(),this.stallWatchdogSubscription=ld(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){Lr(this.element),Lr(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),Se(this.element.buffered,i)||await Promise.all([this.videoBufferManager.abort(),this.audioBufferManager?.abort()]),!(VT(this.element)||VT(this.videoBufferManager))&&(this.videoBufferManager.maintain(i),this.audioBufferManager?.maintain(i),this.element.currentTime=i/1e3,this.tracer.log("seek",bs({requestedPosition:e,forcePrecise:t,position:i})))}warmUpMediaSourceIfNeeded(e=this.element?.currentTime){gs(this.element)&&gs(this.source)&&gs(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=cB(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",bs({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 fB,map as mB,observeElementSize as bB,Subscription as gB,ValueSubject as hd,noop as SB}from"@vkontakte/videoplayer-shared/es2024";var $o=class{constructor(){this.subscription=new gB;this.pipSize$=new hd(void 0);this.videoSize$=new hd(void 0);this.elementSize$=new hd(void 0);this.pictureInPictureWindowRemoveEventListener=SB}connect({observableVideo:e,video:t}){let i=r=>{let s=r.target;this.pipSize$.next({width:s.width,height:s.height})};this.subscription.add(bB(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(fB({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe(mB(({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 Mi=class{constructor(e){this.subscription=new wB;this.videoState=new F("stopped");this.observableVideo=null;this.droppedFramesManager=new cr;this.stallsManager=new So;this.elementSizeManager=new $o;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 yB(e)}}};this.init3DScene=e=>{if(this.scene3D)return;this.scene3D=new Ar(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=$e(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(ge(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 Lo({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;xB(this.observableVideo)&&(this.observableVideo=Ce(this.video),this.subscription.add(()=>this.observableVideo?.destroy()));let i=this.constructor.name,r=n=>{e.error$.next({id:i,category:FT.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(fd(p=>!!p.length),qT()).subscribe(p=>{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:p})}));let n=this.params.desiredState.seekState.stateChangeEnded$.pipe(md(p=>p.to.state!=="none"),Mo());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(fd(NT),qT()),e.firstBytesEvent$),s(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),s(this.videoState.stateChangeEnded$.pipe(md(p=>p.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(De(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:p})=>{if(p==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let d=this.player.getStreams(),h=this.player.getCodecs();if(TB(d,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let b=[];for(let S of d.audio){b.push(td(S));let g=[];for(let I of S.representations){let x=PT(I);g.push(x),this.audioTracksMap.set(x,{stream:S,representation:I})}this.audioStreamsMap.set(S,g)}this.params.output.availableAudioStreams$.next(b)}let f=[];for(let b of d.video){f.push(id(b));let S=[];for(let g of b.representations){let I=AT({...g,streamId:b.id});I&&(S.push(I),this.videoTracksMap.set(I,{stream:b,representation:g}))}this.videoStreamsMap.set(b,S)}this.params.output.availableVideoStreams$.next(f);for(let b of d.text)for(let S of b.representations){let g=kT(b,S);this.textTracksMap.set(g,{stream:b,representation:S})}this.params.output.availableVideoTracks$.next(Array.from(this.videoTracksMap.keys())),this.params.output.availableAudioTracks$.next(Array.from(this.audioTracksMap.keys())),this.params.output.isAudioAvailable$.next(!!this.audioTracksMap.size),h?.video&&this.params.output.availableVideoCodecs$.next(h.video),h?.audio&&this.params.output.availableAudioCodecs$.next(h.audio),this.audioTracksMap.size&&this.textTracksMap.size&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else p==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},r));let{vktvAbrThrottle:u}=this.params.tuning.dash,o=u&&$T(u)||null;this.subscription.add(Do(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$,EB(this.video,"progress")).pipe(fd(()=>this.videoTracksMap.size>0)).subscribe(async()=>{let p=this.player.state$.getState(),d=this.player.state$.getTransition();if(p!=="manifest_ready"&&p!=="running"||d||p==="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 b=Pi(this.videoTracksMap.keys(),g=>this.videoTracksMap.get(g)?.representation.id===h.id);NT(b)&&(this.stallsManager.lastVideoTrackSelected=b);let S=this.params.desiredState.autoVideoTrackLimits.getTransition();if(S&&this.params.output.autoVideoTrackLimits$.next(S.to),p==="manifest_ready")await this.player.initRepresentations(h.id,f?.id,this.params.sourceHls);else if(await this.player.switchRepresentation("video",h.id),f){let g=!!t.audioStream.getTransition();await this.player.switchRepresentation("audio",f.id,g)}},r)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:p})=>{this.scene3D&&p&&this.scene3D.pointCameraTo(p.x,p.y)})),this.subscription.add(this.elementSizeManager.subscribe(p=>{this.scene3D&&p&&this.scene3D.setViewportSize(p.width,p.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(Mo()).subscribe(p=>{let d=Pi(this.videoTracksMap.entries(),([,{representation:g}])=>g.id===p);if(!d){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[h,{stream:f}]=d,b=this.params.desiredState.videoStream.getTransition();b&&b.to&&b.to.id===f.id&&this.params.desiredState.videoStream.setState(b.to),e.currentVideoTrack$.next(h),e.currentVideoStream$.next(id(f));let S=this.player.calculateDurationFromSegments();S&&this.params.output.duration$.next(S/1e3)},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(Mo()).subscribe(p=>{let d=Pi(this.audioTracksMap.entries(),([,{representation:S}])=>S.id===p);if(!d){e.currentAudioStream$.next(void 0);return}let[h,{stream:f}]=d,b=this.params.desiredState.audioStream.getTransition();b&&b.to&&b.to.id===f.id&&this.params.desiredState.audioStream.setState(b.to),e.currentAudioStream$.next(td(f))},r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(p=>{if(p?.is3dVideo&&this.params.tuning.spherical?.enabled)try{this.init3DScene(p),e.is3DVideo$.next(!0)}catch(d){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${d}`})}else this.destroy3DScene(),this.params.tuning.spherical?.enabled&&e.is3DVideo$.next(!1)},r)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,r)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,r)),this.textTracksManager.connect(this.video,t,e);let l=t.playbackState.stateChangeStarted$.pipe(md(({to:p})=>p==="ready"),Mo());this.subscription.add(Do(l,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,bd(["init"])).subscribe(()=>{let p=t.autoVideoTrackSwitching.getState(),h=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:p?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(h)})),this.subscription.add(Do(l,this.player.state$.stateChangeEnded$,bd(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let c=Do(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,bd(["init"])).pipe(IB(0));this.subscription.add(c.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?ba:ma,t=this.params.tuning.useNewAutoSelectVideoTrack?Nn:Fn,i=this.params.tuning.useNewAutoSelectVideoTrack?St:On,{desiredState:r,output:s}=this.params,n=r.autoVideoTrackSwitching.getState(),u=r.videoTrack.getState()?.id,o=Pi(this.videoTracksMap.keys(),A=>A.id===u),l=s.currentVideoTrack$.getValue(),c=r.videoStream.getState()??(o&&this.videoTracksMap.get(o)?.stream)??this.videoStreamsMap.size===1?this.videoStreamsMap.keys().next().value:void 0;if(!c)return;let p=Pi(this.videoStreamsMap.keys(),A=>A.id===c.id),d=p&&this.videoStreamsMap.get(p);if(!d)return;let h=he(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 b=(this.video.duration*1e3||1/0)-this.video.currentTime*1e3,S=Math.min(h/Math.min(f,b||1/0),1),g=r.audioStream.getState()??(this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0),I=g?.id&&Pi(this.audioStreamsMap.keys(),A=>A.id===g.id)||this.audioStreamsMap.keys().next().value,x=0;if(I){if(o&&!n){let A=e(o,d,this.audioStreamsMap.get(I)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);x=Math.max(x,A?.bitrate??-1/0)}if(l){let A=e(l,d,this.audioStreamsMap.get(I)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);x=Math.max(x,A?.bitrate??-1/0)}}let y=o;(n||!y)&&(y=i(d,{container:this.elementSizeManager.getValue(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.stallsManager.abrTuningParams,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:x,forwardBufferHealth:S,current:l,visible:this.params.output.elementVisible$.getValue(),history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,stallsVideoMaxQualityLimit:this.stallsManager.videoMaxQualityLimit,stallsPredictedThroughput:this.stallsManager.predictedThroughput,abrLogger:this.params.dependencies.abrLogger}));let w=I&&t(y,d,this.audioStreamsMap.get(I)??[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.stallsManager.abrTuningParams,forwardBufferHealth:S,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),D=this.videoTracksMap.get(y)?.representation,L=w&&this.audioTracksMap.get(w)?.representation;D&&L?(this.selectedRepresentations.video=D,this.selectedRepresentations.audio=L):D&&!L&&this.audioTracksMap.size===0&&(this.selectedRepresentations.video=D,this.selectedRepresentations.audio=null)}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){Be(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.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:FT.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),Me(this.video),this.tracer.end()}};var Ss=class extends Mi{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 UT,filter as HT,filterChanged as jT,isNullable as Sd,map as QT,ValueSubject as vd,isNonNullable as AB}from"@vkontakte/videoplayer-shared/es2024";var vs=class extends Mi{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(jT()).subscribe(o=>{let l=i.position$.getValue(),c=i.volume$.getValue(),p=!c.volume||c.muted;!o&&!l&&p?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(QT(o=>o.to)).subscribe(this.player.isLowLatency$)).add(gd({liveBufferTime:i.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(QT(({liveBufferTime:o,liveAvailabilityStartTime:l})=>o&&l?o+l:void 0)).subscribe(i.liveTime$)).add(this.player.liveStreamStatus$.pipe(HT(o=>AB(o))).subscribe(o=>i.isLiveEnded$.next(o!=="active"&&i.position$.getValue()===0))).add(gd({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:UT(r.playbackRateState$,new vd(1))}).pipe(HT(({liveStreamStatus:o,liveDuration:l})=>o==="active"&&!!l)).subscribe(({liveDuration:o,playbackRate:l})=>{let c=i.liveBufferTime$.getValue(),p=i.position$.getValue(),{playbackCatchupSpeedup:d}=this.params.tuning.dashCmafLive.lowLatency;p||l<1-d||this.video.paused||Sd(c)||(t=o-c)})).add(gd({time:i.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:UT(r.playbackRateState$,new vd(1))}).pipe(jT((o,l)=>this.player.liveStreamStatus$.getValue()==="active"?o.liveDuration===l.liveDuration:o.time===l.time)).subscribe(({time:o,liveDuration:l,playbackRate:c})=>{let p=i.position$.getValue(),{playbackCatchupSpeedup:d}=this.params.tuning.dashCmafLive.lowLatency;if(!p&&!this.video.paused&&c>=1-d||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=RT(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 WT="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(WT)?parseInt(e.headers.get(WT),10):void 0};import{assertNever as _B,combine as OB,debounce as FB,ErrorCategory as Vo,filter as NB,filterChanged as qB,isNonNullable as YT,isNullable as _o,map as KT,merge as UB,observableFrom as HB,Subscription as jB,ValueSubject as Ed,VideoQuality as QB}from"@vkontakte/videoplayer-shared/es2024";var Id=C(il(),1);import{videoSizeToQuality as PB,getExponentialDelay as kB}from"@vkontakte/videoplayer-shared/es2024";var RB=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=PB({width:t,height:i})}return e??null},LB=(a,e)=>{let t=a.split(`
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(S=>S.split("="))),c=l.QUALITY??`stream-${l.BANDWIDTH}`,p=RB(l),d;l.BANDWIDTH&&(d=parseInt(l.BANDWIDTH,10)/1e3||void 0),!d&&l["AVERAGE-BANDWIDTH"]&&(d=parseInt(l["AVERAGE-BANDWIDTH"],10)/1e3||void 0);let h=l["FRAME-RATE"]?parseFloat(l["FRAME-RATE"]):void 0,f;if(l.RESOLUTION){let[S,g]=l.RESOLUTION.split("x").map(I=>parseInt(I,10));S&&g&&(f={width:S,height:g})}let b=new URL(t[++s],e).toString();p&&i.push({id:c,quality:p,url:b,bandwidth:d,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,"")])),c=l.URI?.replace(/playlist$/,"subtitles.vtt"),p=l.LANGUAGE,d=l.NAME;c&&p&&r.push({type:"internal",id:p,label:d,language:p,url:c,isAuto:!1})}}}if(!i.length)throw new Error("Empty manifest");return{qualityManifests:i,textTracks:r}},$B=a=>new Promise(e=>{setTimeout(()=>{e()},a)}),Td=0,GT=async(a,e=a,t,i)=>{let s=await(await Xe(a,i)).text();Td+=1;try{let{qualityManifests:n,textTracks:u}=LB(s,e);return{qualityManifests:n,textTracks:u}}catch{if(Td<=t.manifestRetryMaxCount)return await $B(kB(Td-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),GT(a,e,t)}return{qualityManifests:[],textTracks:[]}},Co=GT;import{isNonNullable as MB,Subscription as DB,throttle as CB,ValueSubject as zT,Subject as BB,ErrorCategory as VB}from"@vkontakte/videoplayer-shared/es2024";var Bo=class{constructor(e,t,i,r,s){this.subscription=new DB;this.abortControllers={destroy:new X,nextManifest:null};this.prepareUrl=void 0;this.currentTextTrackData=null;this.availableTextTracks$=new zT(null);this.getCurrentTime$=new zT(null);this.error$=new BB;this.params={fetchManifestData:i,sourceUrl:r,downloadThreshold:s},this.subscription.add(e.pipe(CB(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(),c=Number(this.extractPlaylistRowValue("#EXTINF:",u))*1e3;if(i.segments.push({time:{from:s,to:s+c},url:l}),s=s+c,!i.segmentStartTime){let p=new Date(i.vkStartTime).valueOf(),d=new Date(i.programDateTime).valueOf();i.segmentStartTime=d-p}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(MB(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:VB.WTF,thrown:t,message:e})}};var ys=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 Si;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 c=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(c),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 c=this.liveOffset.getTotalOffset();c>=this.maxSeekBackTime$.getValue()&&(c=0,this.liveOffset.resetTo(c)),this.liveOffset.resume(),this.params.output.position$.next(-c/1e3),this.prepare()}else r?.to==="paused"&&(P(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return _B(t)}};this.params=e,this.video=$e(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:QB.INVARIANT,url:this.params.source.url};let t=(i,r)=>Co(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 Bo(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:Vo.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:Vo.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(ge(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:Vo.WTF,message:"HlsLiveProvider internal logic error",thrown:u})},r=Ce(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(De(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(qB(),KT(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(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&YT(l.to)){let p=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let d=this.manifests$.getValue().find(h=>h.id===p);d&&(this.params.output.currentVideoTrack$.next(d),this.params.output.hostname$.next(ge(d.url)))}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.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(OB({startTime:this.manifestStartTime$.pipe(NB(YT)),currentTime:r.timeUpdate$}).subscribe(({startTime:u,currentTime:o})=>this.params.output.liveTime$.next(u+o*1e3),i)),this.subscription.add(this.manifests$.pipe(KT(u=>u.map(({id:o,quality:l,size:c,bandwidth:p,fps:d})=>({id:o,quality:l,size:c,fps:d,bitrate:p})))).subscribe(this.params.output.availableVideoTracks$,i));let n=UB(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,HB(["init"])).pipe(FB(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),Me(this.video)}prepare(){let e=this.selectManifest();if(_o(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,c]of[[u,"mq"],[o,"lq"]]){let p=String(parseFloat(l||""));c&&l&&r.searchParams.set(c,p)}}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(!_o(u))this.maxSeekBackTime$.next(u);else{let o=this.params.source.maxSeekBackTime??this.maxSeekBackTime$.getValue();(_o(o)||!isFinite(o))&&Xe(n).then(l=>l.text()).then(l=>{let c=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(l)?.[1];if(c){let p=new URL(c,n).toString();yd(p).then(d=>{_o(d)||this.maxSeekBackTime$.next(d)})}}).catch(()=>{})}})}playIfAllowed(){Be(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:Vo.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 WB,debounce as GB,ErrorCategory as xd,fromEvent as wd,isNonNullable as zB,isNullable as YB,map as XT,merge as JT,observableFrom as ZT,Subscription as KB,ValueSubject as XB,VideoQuality as JB}from"@vkontakte/videoplayer-shared/es2024";var Ts=class{constructor(e){this.subscription=new KB;this.videoState=new F("stopped");this.manifests$=new XB([]);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 c=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(c);let{currentTime:p}=this.video;this.prepare(),u&&this.params.output.autoVideoTrackLimits$.next(u.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:p*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 WB(t)}};this.textTracksManager=new Ye(e.source.url),this.params=e,this.video=$e(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:JB.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(ge(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.manifestRequested$.next(),Co(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=Ce(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(XT(u=>u.to)),this.params.output.playbackState$),this.subscription.add(mt(this.video,t.isLooped,i)),this.subscription.add(De(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)),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(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&zB(l.to)){let h=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let f=this.manifests$.getValue().find(b=>b.id===h);f&&(this.params.output.currentVideoTrack$.next(f),this.params.output.hostname$.next(ge(f.url)))}let p=this.params.desiredState.playbackRate.getState(),d=this.params.output.element$.getValue()?.playbackRate;if(p!==d){let h=this.params.output.element$.getValue();h&&(this.params.desiredState.playbackRate.setState(p),h.playbackRate=p)}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.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(XT(u=>u.map(({id:o,quality:l,size:c,bandwidth:p,fps:d})=>({id:o,quality:l,size:c,fps:d,bitrate:p})))).subscribe(this.params.output.availableVideoTracks$,i)),!B.device.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:u}=this.video;this.subscription.add(JT(wd(u,"addtrack"),wd(u,"removetrack"),wd(u,"change"),ZT(["init"])).subscribe(()=>{for(let o=0;o<u.length;o++)u[o].mode="hidden"},i))}let n=JT(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,ZT(["init"])).pipe(GB(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),Me(this.video)}prepare(){let e=this.selectManifest();if(YB(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(){Be(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 iI=C(Wi(),1),Ad=C(ci(),1),rI=C(at(),1);import{assertNever as ZB,assertNonNullable as eI,debounce as e0,ErrorCategory as tI,isHigherOrEqual as t0,isLowerOrEqual as i0,isNonNullable as r0,merge as a0,observableFrom as s0,Subscription as n0,map as o0}from"@vkontakte/videoplayer-shared/es2024";var Is=class{constructor(e){this.subscription=new n0;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 ZB(e)}};this.params=e,this.video=$e(e.container,e.tuning),this.params.output.element$.next(this.video),(0,iI.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:tI.WTF,message:"MpegProvider internal logic error",thrown:u})},r=Ce(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(o0(u=>u.to)),this.params.output.playbackState$),this.subscription.add(mt(this.video,t.isLooped,i)),this.subscription.add(De(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&&r0(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 c=this.params.output.element$.getValue();c&&(this.params.desiredState.playbackRate.setState(o),c.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=a0(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,s0(["init"])).pipe(e0(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),Me(this.video)}prepare(){let e=this.params.desiredState.videoTrack.getState()?.id;eI(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];eI(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=zt(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(ge(t))}playIfAllowed(){Be(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:tI.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 c=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(c)},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||sr(e,n[0].quality,(0,rI.default)(n,-1)?.quality)){i();return}let u=e.max?i0(r,e.max):!0,o=e.min?t0(r,e.min):!0;u&&o||i(e)}};import{assertNever as sI,debounce as d0,merge as nI,observableFrom as p0,Subscription as h0,map as oI,ValueSubject as f0,ErrorCategory as kd,VideoQuality as m0}from"@vkontakte/videoplayer-shared/es2024";import{ErrorCategory as u0}from"@vkontakte/videoplayer-shared/es2024";var aI=["stun:videostun.mycdn.me:80"],l0=1e3,c0=3,Pd=()=>null,Oo=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:aI}]};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:u0.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),l0)}normalizeOptions(e={}){let t={stunServerList:aI,maxRetryNumber:c0,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var Es=class{constructor(e){this.videoState=new F("stopped");this.maxSeekBackTime$=new f0(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 sI(e)}};this.subscription=new h0,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=$e(e.container,e.tuning),this.liveStreamClient=new Oo(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),Me(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(nI(this.videoState.stateChangeStarted$.pipe(oI(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe(oI(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:u})=>{this.log({message:`[videoState change] ${u}: ${JSON.stringify(n)}`})}));let r=Ce(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(De(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 sI(n.to)}},i)).add(nI(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,p0(["init"])).pipe(d0(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(ge(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:m0.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(){Be(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 Dr=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 xs,assertNonNullable as Zt,ErrorCategory as Fo,filter as hI,isNonNullable as fI,isNullable as I0,map as E0,merge as x0,once as w0,Subject as ne,Subscription as mI,ValueSubject as _,flattenObject as Rd}from"@vkontakte/videoplayer-shared/es2024";import{Observable as b0,map as uI,Subscription as g0,Subject as S0}from"@vkontakte/videoplayer-shared/es2024";var lI=a=>new b0(e=>{let t=new g0,i=a.desiredPlaybackState$.stateChangeStarted$.pipe(uI(({from:l,to:c})=>`${l}-${c}`)),r=a.desiredPlaybackState$.stateChangeEnded$,s=a.providerChanged$.pipe(uI(({type:l})=>l!==void 0)),n=new S0,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 v0,Subscription as y0,combine as T0,filter as dI,once as pI}from"@vkontakte/videoplayer-shared/es2024";function cI(){return new(window.AudioContext||window.webkitAudioContext)}var Cr=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 y0;this.audioContext=null;this.gainNode=null;this.mediaElementSource=null;this.subscriptions.add(this.provider$.pipe(dI(s=>!!s.type),pI()).subscribe(({type:s})=>this.subscribe(s)))}static{this.errorId="VolumeMultiplierManager"}subscribe(e){B.browser.isSafari&&e!=="MPEG"||this.subscriptions.add(T0({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe(dI(({playbackState:t,video:i,volume:{muted:r,volume:s}})=>t==="playing"&&!!i&&!r&&!!s),pI()).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=cI();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:v0.VIDEO_PIPELINE,message:e?.message??`${a.errorId} exception`,thrown:e})}};var A0={chunkDuration:5e3,maxParallelRequests:5},ws=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 mI;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=Hl([...sT(this.params.tuning),...aT(this.params.tuning)]).filter(l=>fI(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 Dr(s);let n=[...Vc(!0),...Vc(!1)];this.chromecastFormatsIterator=new Dr(n.filter(l=>fI(e.sources[l]))),this.providerOutput.availableSources$.next(e.sources);let{volumeMultiplier:u=1,tuning:{useVolumeMultiplier:o}}=this.params;o&&u!==1&&Cr.isSupported()&&(this.volumeMultiplierManager=new Cr(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 Dr(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(I0(t)){this.handleNoFormatsError(e);return}let i;try{i=this.createProvider(e,t)}catch(r){this.providerError$.next({id:"ProviderNotConstructed",category:Fo.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 xs(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 Zt(o),this.params.tuning.useNewDashProvider?new Ss({...u,source:o,sourceHls:l,forceVideoCodec:this.videoCodecsIterator?.getValue()}):new us({...u,source:o,sourceHls:l,forceVideoCodec:this.videoCodecsIterator?.getValue()})}case"DASH_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return Zt(o),this.params.tuning.useNewDashProvider?new vs({...u,source:o}):new ls({...u,source:o})}case"HLS":case"HLS_ONDEMAND":case"HLS_FMP4":{let o=this.applyFailoverHost(t[e]);return Zt(o),new Ts({...u,source:o})}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return Zt(o),new ys({...u,source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case"MPEG":{let o=this.applyFailoverHost(t[e]);return Zt(o),new Is({...u,source:o})}case"DASH_LIVE":{let o=this.applyFailoverHost(t[e]);return Zt(o),new XS({...u,source:o,config:{...A0,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case"WEB_RTC_LIVE":{let o=this.applyFailoverHost(t[e]);return Zt(o),new Es({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 xs(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 Zt(u),new ca({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 xs(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return xs(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 xs(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,gI.default)((0,bI.default)(e).map(([r,s])=>[r,i(s)]))}initProviderErrorHandling(){let e=new mI,t=!1,i=0;return e.add(x0(this.providerOutput.error$.pipe(hI(r=>!this.params.tuning.ignoreAudioRendererError||!r.message||!/AUDIO_RENDERER_ERROR/ig.test(r.message))),lI({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(E0(r=>({id:`ProviderHangup:${r}`,category:Fo.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(hI(({to:s})=>s==="playing"),w0()).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===Fo.NETWORK,o=r.category===Fo.FATAL,l=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),c=i<this.params.tuning.providerErrorLimit&&!o,p=this.videoCodecsIterator&&!this.videoCodecsIterator.isLast()&&this.params.tuning.dash.codecsPrioritizeEnabled,d=l&&!o&&(u&&t||!c);n={...n,isNetworkError:u,isFatalError:o,haveFailoverHost:l,tryFailover:d,canReinitProvider:c},c?(i++,this.reinitProvider()):d?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):p?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 No,once as P0,combine as k0,Subscription as SI,ValueSubject as $d,map as R0,filter as L0,isNonNullable as qo,now as Qe,safeStorage as Md}from"@vkontakte/videoplayer-shared/es2024";var $0=5e3,vI="one_video_throughput",yI="one_video_rtt",As=window.navigator.connection,TI=()=>{let a=As?.downlink;if(qo(a)&&a!==10)return a*1e3},II=()=>{let a=As?.rtt;if(qo(a)&&a!==3e3)return a},EI=(a,e,t)=>{let i=t*8,r=i/a;return i/(r+e)},Dd=class a{constructor(e){this.subscription=new SI;this.concurrentDownloads=new Set;this.tuningConfig=e;let t=a.load(vI)||(e.useBrowserEstimation?TI():void 0)||$0,i=a.load(yI)??(e.useBrowserEstimation?II():void 0)??0;if(this.throughput$=new $d(t),this.rtt$=new $d(i),this.rttAdjustedThroughput$=new $d(EI(t,i,e.rttPenaltyRequestSize)),this.throughput=Mt.getSmoothedValue(t,-1,e),this.rtt=Mt.getSmoothedValue(i,1,e),e.useBrowserEstimation){let r=()=>{let n=TI();n&&this.throughput.next(n);let u=II();qo(u)&&this.rtt.next(u)};As&&"onchange"in As&&this.subscription.add(No(As,"change").subscribe(r)),r()}this.subscription.add(this.throughput.smoothed$.subscribe(r=>{Md.set(vI,r.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(r=>{Md.set(yI,r.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(k0({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(R0(({throughput:r,rtt:s})=>EI(r,s,e.rttPenaltyRequestSize)),L0(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 SI;switch(this.subscription.add(r),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:r.add(No(e,"progress").pipe(P0()).subscribe(s=>{t=s.loaded,i=Qe()}));break;case 1:case 0:r.add(No(e,"loadstart").subscribe(()=>{t=0,i=Qe()}));break}r.add(No(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=c=>{this.concurrentDownloads.delete(e),i.releaseLock(),e.cancel(`Throughput Estimator error: ${c}`).catch(()=>{})},l=async({done:c,value:p})=>{if(c)!t&&this.addRawSpeed(r,Qe()-s,1),this.concurrentDownloads.delete(e);else if(p){if(t){let d=Qe();if(d-u>this.tuningConfig.lowLatency.continuesByteSequenceInterval||d-s>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let f=u-s;f&&this.addRawSpeed(n,f,1,t),n=p.byteLength,s=Qe()}else n+=p.byteLength;u=Qe()}else r+=p.byteLength,n+=p.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(qo(t))return parseInt(t,10)??void 0}},xI=Dd;import{fillWithDefault as M0,VideoQuality as Uo}from"@vkontakte/videoplayer-shared/es2024";var wI={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:Uo.Q_4320P,activeVideoAreaThreshold:.1,highQualityLimit:Uo.Q_720P,trafficSavingLimit:Uo.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:Uo.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:3e3,crashOnStallTimeout:25e3,crashOnStallTWithoutDataTimeout:5e3,enableSubSegmentBufferFeeding:!0,bufferEmptinessTolerance:100,useFetchPriorityHints:!0,enableBaseUrlSupport:!0,maxSegmentRetryCount:5,sourceOpenTimeout:1e3,vktvAbrThrottle:0,timeupdateEventTickThrottle:300,fetcherBufferOptimisation:!0,codecsPrioritizeEnabled:!1},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,useRefactoredSearchGap:!1,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,manifestRetryInterval:300,manifestRetryMaxInterval:1e4,manifestRetryMaxCount:10,audioVideoSyncRate:20,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50},useVolumeMultiplier:!1,ignoreAudioRendererError:!1,useEnableSubtitlesParam:!1,useHlsLiveNewTextManager:!1,exposeInternalsToGlobal:!1,hlsLiveNewTextManagerDownloadThreshold:4e3,disableYandexPiP:!1,asyncResolveClientChecker:!1,autostartOnlyIfVisible:!1,changePlaybackStateToPausedWhenEnded:!1,suppressExceptionsInObservables:!0},AI=a=>({...M0(a,wI),configName:[...a.configName??[],...wI.configName]});import{assertNonNullable as Ho,combine as Ct,ErrorCategory as jo,filter as O,filterChanged as Y,fromEvent as Bd,isNonNullable as LI,isNullable as F0,Logger as N0,map as G,mapTo as $I,merge as ei,now as Qo,once as N,Subject as W,Subscription as MI,tap as Vd,ValueSubject as k,isHigher as q0,isInvariantQuality as DI,flattenObject as ti,throttle as _d,getTraceSubscriptionMethod as CI,TracerFactory as U0,InternalsExposure as H0}from"@vkontakte/videoplayer-shared/es2024";import{merge as D0,map as C0,filter as PI,isNonNullable as B0}from"@vkontakte/videoplayer-shared/es2024";var Cd=({seekState:a,position$:e})=>D0(a.stateChangeEnded$.pipe(C0(({to:t})=>t.state==="none"?void 0:(t.position??NaN)/1e3),PI(B0)),e.pipe(PI(()=>a.getState().state==="none")));import{assertNonNullable as V0}from"@vkontakte/videoplayer-shared/es2024";var kI=a=>{let e=typeof a.container=="string"?document.getElementById(a.container):a.container;return V0(e,`Wrong container or containerId {${a.container}}`),e};import{filter as _0,once as O0}from"@vkontakte/videoplayer-shared/es2024";var RI=(a,e,t,i)=>{a!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&t?.getValue().length===0?t.pipe(_0(r=>r.length>0),O0()).subscribe(r=>{r.find(i)&&e.startTransitionTo(a)}):(a===void 0||t?.getValue().find(i))&&e.startTransitionTo(a)};var Wo=class{constructor(e={configName:[]},t=U0.createRootTracer(!1)){this.subscription=new MI;this.logger=new N0;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:ES,getCurrentTime$:new k(null)};if(this.initLogs(),this.tuning=AI(e),this.tracer=t,this.tuning.suppressExceptionsInObservables&&((0,Od.default)(this.info).forEach(i=>i.setSuppressErrors(!0)),(0,Od.default)(this.events).forEach(i=>i.setSuppressErrors(!0))),this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new Qs({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new xI(this.tuning.throughputEstimator),e.exposeInternalsToGlobal&&(this.internalsExposure=new H0("CORE"),this.internalsExposure.expose({player:this})),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(i,r,s)=>{let n=Reflect.get(i,r,s);return typeof n!="function"?n:(...u)=>{try{return n.apply(i,u)}catch(o){let l=u.map(d=>JSON.stringify(d,(h,f)=>{let b=typeof f;return(0,BI.default)(["number","string","boolean"],b)?f:f===null?null:`<${b}>`})),c=`Player.${String(r)}`,p=`Exception calling ${c} (${l.join(", ")})`;throw this.events.fatalError$.next({id:c,category:jo.WTF,message:p,thrown:o}),o}}}})}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",ti(n)),this.domContainer=kI(e),this.chromecastInitializer.contentId=e.meta?.videoId,this.providerContainer=new ws({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?B.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"),Bd(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(()=>{Ho(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",ti(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(()=>{Ho(this.providerContainer);let t=this.providerContainer?.providerOutput.element$.getValue();this.tracer.log("setPlaybackRate",{playbackRate:e,isVideoElementAvailable:!!t}),t&&(this.desiredState.playbackRate.setState(e),t.playbackRate=e)})),this}setExternalTextTracks(e){return this.subscription.add(this.playerInited.pipe(O(t=>!!t),N()).subscribe(()=>{e.length&&this.tracer.log("setExternalTextTracks",ti(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(()=>{RI(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(F0(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),i=t.state==="none"?void 0:t.position;return LI(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(ei(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(ic(e,t,i))})),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(O(({from:e})=>e==="stopped"),N()).subscribe(()=>{this.initedAt=Qo(),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",ti(n)),n.state==="requested"?this.desiredState.seekState.setState({...n,state:"applying"}):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:jo.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",ti(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)=>DI(o)?1:DI(l)?-1:q0(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=>LI(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(Vd(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:ei(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(),Vd(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(),Vd(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(ei(e.providerOutput.endedEvent$.pipe($I(!0)),e.providerOutput.seekedEvent$.pipe($I(!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:jo.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??Qo()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe(N(),G(()=>Qo()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(N(),G(()=>Qo()-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=ei(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(ei(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(ei(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(),c=this.chromecastInitializer.castState$.getValue(),p;c==="CONNECTED"?p="second_screen":o?l?n?p="pip":u?p="fullscreen":p="inline":p="invisible":p="none",this.info.surface$.getValue()!==p&&this.info.surface$.next(p)}))}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 MI;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(ei(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;Ho(this.providerContainer),Ho(e),IS(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(t=>TS(t)),this.providerContainer.current$.subscribe(({type:t})=>fa("provider",t)),e.duration$.subscribe(t=>fa("duration",t)),e.availableVideoTracks$.pipe(O(t=>!!t.length),N()).subscribe(t=>fa("tracks",t)),this.events.fatalError$.subscribe(new Ae("fatalError")),this.events.managedError$.subscribe(new Ae("managedError")),e.position$.subscribe(new Ae("position")),e.currentVideoTrack$.pipe(G(t=>t?.quality)).subscribe(new Ae("quality")),this.info.currentBuffer$.subscribe(new Ae("buffer")),e.isBuffering$.subscribe(new Ae("isBuffering"))].forEach(t=>this.subscription.add(t)),fa("codecs",B.video.supportedCodecs)}initTracerSubscription(){let e=CI(this.tracer.log.bind(this.tracer)),t=CI(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(_d(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),_d(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),_d(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:jo.DOM,message:String(r)})})};this.subscription.add(ei(Bd(document,"visibilitychange"),Bd(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",ti({quality:t,availableTracks:ti(e),track:ti(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&&!Ta()}};import{Subscription as pX,Observable as hX,Subject as fX,ValueSubject as mX,VideoQuality as bX}from"@vkontakte/videoplayer-shared/es2024";var gX=`@vkontakte/videoplayer-core@${qd}`;export{Bs as ChromecastState,Yo as HttpConnectionType,hX as Observable,Re as PlaybackState,Wo as Player,Vs as PredefinedQualityLimits,gX as SDK_VERSION,fX as Subject,pX as Subscription,Ko as Surface,qd as VERSION,mX as ValueSubject,xt as VideoFormat,bX as VideoQuality,NL as areValidLiveRecordSources,B as clientChecker,la as isMobile};
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(hT,this.gl.VERTEX_SHADER),i=this.createShader(fT,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 DC,now as ls,once as CC,Subscription as BC,ValueSubject as Gc,isNonNullable as VC,safeStorage as zc,filterChanged as _C}from"@vkontakte/videoplayer-shared/es2024";var wo="stalls_manager_metrics",Yc="stalls_manager_abr_params",mT="stalls_manager_default_tuning_abr_params",Kc=class{constructor(){this.isSeeked$=new Gc(!1);this.isBuffering$=new Gc(!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 BC;this.severeStallOccurred$=new Gc(!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(Yc):{};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(mT)},{bitrateFactorAtEmptyBuffer:r,bitrateFactorAtFullBuffer:s,containerSizeFactor:n}={...this.abrParams};this.tuning.enabled&&e===r&&t===s&&i===n||(this.removeStoredData(Yc),this.setStoredData(mT,{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(Yc,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(zc.get(e)??t)}setStoredData(e,t){zc.set(e,JSON.stringify(t))}removeStoredData(e){zc.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(CC()).subscribe(t=>this.providerStartWatchingTimestamp=ls())),this.subscription.add(this.currentStallDuration$.pipe(_C()).subscribe(t=>{let{stallDurationNoDataBeforeQualityDecrease:i,stallCountBeforeQualityDecrease:r,resetQualityRestrictionTimeout:s,ignoreStallsOnSeek:n}=this.tuning;if(DC(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,VC(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=Kc;import{combine as OC,map as FC,observeElementSize as NC,Subscription as qC,ValueSubject as Xc,noop as UC}from"@vkontakte/videoplayer-shared/es2024";var Po=class{constructor(){this.subscription=new qC;this.pipSize$=new Xc(void 0);this.videoSize$=new Xc(void 0);this.elementSize$=new Xc(void 0);this.pictureInPictureWindowRemoveEventListener=UC}connect({observableVideo:e,video:t}){let i=r=>{let s=r.target;this.pipSize$.next({width:s.width,height:s.height})};this.subscription.add(NC(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(OC({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe(FC(({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 ki=class{constructor(e){this.subscription=new KC;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.unmuteAfterBrowserResetsHappened=new JC(!1);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 jC(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=Ce(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;YC(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:bT.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(cs(d=>!!d.length),ko()).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(Rr(d=>d.to.state!=="none"),ds());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(cs(gT),ko()),e.firstBytesEvent$),s(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),s(this.videoState.stateChangeEnded$.pipe(Rr(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(Ee(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(t.volume.stateChangeStarted$.pipe(Rr(()=>{let d=t.volume.getTransition(),c=this.params.output.element$.getValue();return!c||!d?!1:!d.to.muted&&c.muted}),cs(d=>!!d),ko()).subscribe(()=>{this.unmuteAfterBrowserResetsHappened.next(!0)})),this.subscription.add(Ee(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.playbackRateState$.pipe(cs(()=>this.unmuteAfterBrowserResetsHappened.getValue()),ko()).subscribe(()=>{let d=this.params.output.element$.getValue(),c=t.playbackRate.getState();d&&c!==d.playbackRate&&(d.playbackRate=c)})),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(QC(c,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let m=[];for(let g of c.audio){m.push(Dc(g));let S=[];for(let v of g.representations){let I=Xy(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(Cc(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=Jy(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$,zC(this.video,"progress")).pipe(cs(()=>this.videoTracksMap.size>0)),{abrThrottle:o}=this.params.tuning.dash;o&&(u=u.pipe(XC(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);gT(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(WC({videoState:this.videoState.stateChangeEnded$,autoVideoTrackState:ps(Ro([t.autoVideoTrackSwitching.getState()]),t.autoVideoTrackSwitching.stateChangeEnded$.pipe(Rr(d=>d.to)))}).pipe(Rr(({videoState:d,autoVideoTrackState:c})=>d.to!=="stopped"&&c),ds()).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(ds()).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(Cc(f));let g=this.player.calculateDurationFromSegments();g&&this.params.output.duration$.next(g/1e3)},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(ds()).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(Dc(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(Rr(({to:d})=>d==="ready"),ds());this.subscription.add(ps(l,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,Ro(["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$,Ro(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let p=ps(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Ro(["init"])).pipe(GC(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}),k=this.videoTracksMap.get(T)?.representation,L=A&&this.audioTracksMap.get(A)?.representation;if(k&&L)return[k,L];if(k&&!L&&this.audioTracksMap.size===0)return[k,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:bT.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),Be(this.video),this.tracer.end()}};var hs=class extends ki{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 ST,filter as vT,filterChanged as yT,isNullable as Zc,map as TT,ValueSubject as ed,isNonNullable as ZC}from"@vkontakte/videoplayer-shared/es2024";var fs=class extends ki{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(yT()).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(TT(o=>o.to)).subscribe(this.player.isLowLatency$)).add(Jc({liveBufferTime:i.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(TT(({liveBufferTime:o,liveAvailabilityStartTime:l})=>o&&l?o+l:void 0)).subscribe(i.liveTime$)).add(this.player.liveStreamStatus$.pipe(vT(o=>ZC(o))).subscribe(o=>i.isLiveEnded$.next(o!=="active"&&i.position$.getValue()===0))).add(Jc({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:ST(r.playbackRateState$,new ed(1))}).pipe(vT(({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:ST(r.playbackRateState$,new ed(1))}).pipe(yT((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=Zy(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 AB,assertNonNullable as PB,combine as RB,debounce as kB,ErrorCategory as OT,filter as bd,filterChanged as xs,fromEvent as LB,isNonNullable as FT,isNullable as $B,map as ws,merge as As,observableFrom as No,once as NT,Subscription as MB}from"@vkontakte/videoplayer-shared/es2024";var _T=C(De(),1),fd=C(wa(),1);import{abortable as cd,assertNonNullable as $r,combine as Mr,ErrorCategory as ut,filter as _o,filterChanged as Ts,flattenObject as Is,fromEvent as It,getTraceSubscriptionMethod as bB,interval as dd,isNonNullable as Es,isNullable as BT,map as Dr,merge as Ci,now as pd,Subject as ei,Subscription as hd,tap as gB,throttle as VT,ValueSubject as te}from"@vkontakte/videoplayer-shared/es2024";var Do=C(De(),1),Di=C(at(),1),Co=C(wa(),1);var $T=C(An(),1);import{assertNever as eB,ErrorCategory as IT,Subject as ET}from"@vkontakte/videoplayer-shared/es2024";var tB=18,xT=!1;try{xT=B.browser.isSafari&&!!B.browser.safariVersion&&B.browser.safariVersion<=tB}catch(a){console.error(a)}var td=class{constructor(e){this.bufferFull$=new ET;this.error$=new ET;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:IT.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)};xT&&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:IT.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:eB(t)}}},wT=td;import{abortable as Jt,assertNonNullable as ke,ErrorCategory as $i,fromEvent as nd,getExponentialDelay as od,isHigher as nB,isNonNullable as Zt,isNullable as ce,now as Mo,once as oB,Subject as uB,Subscription as lB,ValueSubject as Mi}from"@vkontakte/videoplayer-shared/es2024";var id=C(at(),1);import{videoSizeToQuality as iB,throttleFn as rB}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)??iB({width:e,height:t});return u&&{id:a,quality:u,bitrate:i,size:{width:e,height:t},fps:r,streamId:n}},AT=({id:a,bitrate:e})=>({id:a,bitrate:e}),PT=({language:a,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:a,label:e}),RT=({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 kT=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},LT=a=>{let e=!1,t=rB(()=>{e=!0},a);return()=>{try{return t(),e}finally{e=!1}}};import{fromEvent as aB,Subscription as sB}from"@vkontakte/videoplayer-shared/es2024";var Lo=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 $o=class{constructor(e,t){this.lastUpdateTs=0;this.lastCallTs=0;this.prevRanges=[];this.subscription=new sB;this.mediaSource=e,this.sourceBuffer=t,this.subscription.add(aB(this.sourceBuffer,"updateend").subscribe(()=>this.updateend()))}updateend(){if(!V(this.mediaSource,this.sourceBuffer))return;let{prevRanges:e}=this,t=Lo(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 uB;this.gaps=[];this.subscription=new lB;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 wT(this.sourceBuffer),this.sourceBufferBufferedDiff=new $o(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,Co.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)&&nB(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(k=>e>=k.time.from&&e<k.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,Do.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,Co.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,Co.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=Mo(),!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(oB()).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=Mo(),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=Mo(),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=Mo();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,Do.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&&B.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,$T.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,Do.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=kT(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=Lo(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 MT,fromEvent as DT,merge as cB,now as Ss,Subject as kr,ValueSubject as ud,flattenObject as Lr,ErrorCategory as vs,SubscriptionRemovable as dB}from"@vkontakte/videoplayer-shared/es2024";var Vo=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:s=!1}){this.manifestRequested=new kr;this.manifestReceived=new kr;this.firstBytesRequested=new kr;this.firstBytesReceived=new kr;this.lastConnectionType$=new ud(void 0);this.lastConnectionReused$=new ud(void 0);this.lastRequestFirstBytes$=new ud(void 0);this.recoverableError$=new kr;this.error$=new kr;this.abortAllController=new X;this.subscription=new dB;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(Bo);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:MT(t)}this.requestQuic&&(p=Yt(p));let h=this.abortAllController.signal,f;if(n){let y=new X;if(f=cB(DT(this.abortAllController.signal,"abort"),DT(n,"abort")).subscribe(()=>{try{y.abort()}catch(E){Bo(E)}}),this.subscription.add(f),this.abortAllController.signal.aborted||n.aborted)try{y.abort()}catch(E){Bo(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,k=parseInt(S.headers.get("content-length")??"",10);Number.isFinite(k)&&(A=k),!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,Bo(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:MT(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))}},Bo=a=>{if(!Tt(a))throw a};import{isNullable as pB,ValueSubject as hB}from"@vkontakte/videoplayer-shared/es2024";var ys=class a{constructor(e,t){this.currentRepresentation$=new hB(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(!pB(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 SB=["progress","play","seeked","stalled","waiting"],vB=["timeupdate","progress","loadeddata","playing","seeked"];var Oo=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,_T.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);B.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(_o(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(...vB.map(c=>It(this.element,c))).pipe(Dr(c=>this.element?ve(this.element.buffered,this.element.currentTime*1e3):0),Ts(),gB(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(_o(({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(_o(({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(VT(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,k=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),L=S<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next(L);let w="none";if(k?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),_o(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 Vo({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(VT(this.tuning.dash.timeupdateEventTickThrottle))),this.subscription.add(Ci(...SB.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()]),!(BT(this.element)||BT(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=bB(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 yB,map as TB,observeElementSize as IB,Subscription as EB,ValueSubject as md,noop as xB}from"@vkontakte/videoplayer-shared/es2024";var Fo=class{constructor(){this.subscription=new EB;this.pipSize$=new md(void 0);this.videoSize$=new md(void 0);this.elementSize$=new md(void 0);this.pictureInPictureWindowRemoveEventListener=xB}connect({observableVideo:e,video:t}){let i=r=>{let s=r.target;this.pipSize$.next({width:s.width,height:s.height})};this.subscription.add(IB(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(yB({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe(TB(({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 MB;this.videoState=new F("stopped");this.observableVideo=null;this.droppedFramesManager=new pr;this.stallsManager=new Ao;this.elementSizeManager=new Fo;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 AB(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=Ce(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 Oo({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;$B(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:OT.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),NT()).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(FT),NT()),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(Ee(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(PB(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=AT(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=PT(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&&LT(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$,LB(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);FT(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(No([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$,No(["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$,No(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let p=As(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,No(["init"])).pipe(kB(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}),k=this.videoTracksMap.get(T)?.representation,L=A&&this.audioTracksMap.get(A)?.representation;k&&L?(this.selectedRepresentations.video=k,this.selectedRepresentations.audio=L):k&&!L&&this.audioTracksMap.size===0&&(this.selectedRepresentations.video=k,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:OT.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),Be(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 qT,filter as UT,filterChanged as HT,isNullable as Sd,map as jT,ValueSubject as vd,isNonNullable as DB}from"@vkontakte/videoplayer-shared/es2024";var Rs=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(HT()).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(jT(o=>o.to)).subscribe(this.player.isLowLatency$)).add(gd({liveBufferTime:i.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(jT(({liveBufferTime:o,liveAvailabilityStartTime:l})=>o&&l?o+l:void 0)).subscribe(i.liveTime$)).add(this.player.liveStreamStatus$.pipe(UT(o=>DB(o))).subscribe(o=>i.isLiveEnded$.next(o!=="active"&&i.position$.getValue()===0))).add(gd({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:qT(r.playbackRateState$,new vd(1))}).pipe(UT(({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:qT(r.playbackRateState$,new vd(1))}).pipe(HT((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=RT(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 QT="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(QT)?parseInt(e.headers.get(QT),10):void 0};import{assertNever as jB,combine as QB,debounce as WB,ErrorCategory as Ho,filter as GB,filterChanged as zB,isNonNullable as zT,isNullable as jo,map as YT,merge as YB,observableFrom as KB,Subscription as XB,ValueSubject as Ed,VideoQuality as JB}from"@vkontakte/videoplayer-shared/es2024";var Id=C(ul(),1);import{videoSizeToQuality as CB,getExponentialDelay as BB}from"@vkontakte/videoplayer-shared/es2024";var VB=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=CB({width:t,height:i})}return e??null},_B=(a,e)=>{let t=a.split(`
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=VB(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}},OB=a=>new Promise(e=>{setTimeout(()=>{e()},a)}),Td=0,WT=async(a,e=a,t,i)=>{let s=await(await Xe(a,i)).text();Td+=1;try{let{qualityManifests:n,textTracks:u}=_B(s,e);return{qualityManifests:n,textTracks:u}}catch{if(Td<=t.manifestRetryMaxCount)return await OB(BB(Td-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),WT(a,e,t)}return{qualityManifests:[],textTracks:[]}},qo=WT;import{isNonNullable as FB,Subscription as NB,throttle as qB,ValueSubject as GT,Subject as UB,ErrorCategory as HB}from"@vkontakte/videoplayer-shared/es2024";var Uo=class{constructor(e,t,i,r,s){this.subscription=new NB;this.abortControllers={destroy:new X,nextManifest:null};this.prepareUrl=void 0;this.currentTextTrackData=null;this.availableTextTracks$=new GT(null);this.getCurrentTime$=new GT(null);this.error$=new UB;this.params={fetchManifestData:i,sourceUrl:r,downloadThreshold:s},this.subscription.add(e.pipe(qB(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(FB(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:HB.WTF,thrown:t,message:e})}};var ks=class{constructor(e){this.subscription=new XB;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 jB(t)}};this.params=e,this.video=Ce(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:JB.INVARIANT,url:this.params.source.url};let t=(i,r)=>qo(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 Uo(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:Ho.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:Ho.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:Ho.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(Ee(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(zB(),YT(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&&zT(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(QB({startTime:this.manifestStartTime$.pipe(GB(zT)),currentTime:r.timeUpdate$}).subscribe(({startTime:u,currentTime:o})=>this.params.output.liveTime$.next(u+o*1e3),i)),this.subscription.add(this.manifests$.pipe(YT(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=YB(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,KB(["init"])).pipe(WB(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),Be(this.video)}prepare(){let e=this.selectManifest();if(jo(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(!jo(u))this.maxSeekBackTime$.next(u);else{let o=this.params.source.maxSeekBackTime??this.maxSeekBackTime$.getValue();(jo(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=>{jo(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:Ho.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 ZB,debounce as e0,ErrorCategory as xd,filter as KT,fromEvent as wd,isNonNullable as t0,isNullable as i0,map as Ad,merge as XT,observableFrom as JT,once as ZT,Subscription as r0,ValueSubject as eI,VideoQuality as a0}from"@vkontakte/videoplayer-shared/es2024";var Ls=class{constructor(e){this.subscription=new r0;this.videoState=new F("stopped");this.manifests$=new eI([]);this.unmuteAfterBrowserResetsHappened=new eI(!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 ZB(t)}};this.textTracksManager=new Ye(e.source.url),this.params=e,this.video=Ce(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:a0.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(),qo(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(Ad(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)),this.subscription.add(t.volume.stateChangeStarted$.pipe(Ad(()=>{let u=t.volume.getTransition(),o=this.params.output.element$.getValue();return!o||!u?!1:!u.to.muted&&o.muted}),KT(u=>!!u),ZT()).subscribe(()=>{this.unmuteAfterBrowserResetsHappened.next(!0)})),this.subscription.add(Ee(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.playbackRateState$.pipe(KT(()=>this.unmuteAfterBrowserResetsHappened.getValue()),ZT()).subscribe(()=>{let u=this.params.output.element$.getValue(),o=t.playbackRate.getState();u&&o!==u.playbackRate&&(u.playbackRate=o)})),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&&t0(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(Ad(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)),!B.device.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:u}=this.video;this.subscription.add(XT(wd(u,"addtrack"),wd(u,"removetrack"),wd(u,"change"),JT(["init"])).subscribe(()=>{for(let o=0;o<u.length;o++)u[o].mode="hidden"},i))}let n=XT(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,JT(["init"])).pipe(e0(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),Be(this.video)}prepare(){let e=this.selectManifest();if(i0(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 rI=C(Yi(),1),Pd=C(pi(),1),aI=C(at(),1);import{assertNever as s0,assertNonNullable as tI,debounce as n0,ErrorCategory as iI,isHigherOrEqual as o0,isLowerOrEqual as u0,isNonNullable as l0,merge as c0,observableFrom as d0,Subscription as p0,map as h0}from"@vkontakte/videoplayer-shared/es2024";var $s=class{constructor(e){this.subscription=new p0;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 s0(e)}};this.params=e,this.video=Ce(e.container,e.tuning),this.params.output.element$.next(this.video),(0,rI.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,Pd.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:iI.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(h0(u=>u.to)),this.params.output.playbackState$),this.subscription.add(mt(this.video,t.isLooped,i)),this.subscription.add(Ee(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&&l0(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=c0(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,d0(["init"])).pipe(n0(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),Be(this.video)}prepare(){let e=this.params.desiredState.videoTrack.getState()?.id;tI(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];tI(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:iI.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,Pd.default)(this.trackUrls).map(l=>l.track);if(!r||!s||ur(e,n[0].quality,(0,aI.default)(n,-1)?.quality)){i();return}let u=e.max?u0(r,e.max):!0,o=e.min?o0(r,e.min):!0;u&&o||i(e)}};import{assertNever as nI,debounce as g0,merge as oI,observableFrom as S0,Subscription as v0,map as uI,ValueSubject as y0,ErrorCategory as kd,VideoQuality as T0}from"@vkontakte/videoplayer-shared/es2024";import{ErrorCategory as f0}from"@vkontakte/videoplayer-shared/es2024";var sI=["stun:videostun.mycdn.me:80"],m0=1e3,b0=3,Rd=()=>null,Qo=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=Rd;this.externalStopCallback=Rd;this.externalErrorCallback=Rd;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:sI}]};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:f0.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),m0)}normalizeOptions(e={}){let t={stunServerList:sI,maxRetryNumber:b0,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 y0(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 nI(e)}};this.subscription=new v0,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=Ce(e.container,e.tuning),this.liveStreamClient=new Qo(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),Be(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(oI(this.videoState.stateChangeStarted$.pipe(uI(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe(uI(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(Ee(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 nI(n.to)}},i)).add(oI(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,S0(["init"])).pipe(g0(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:T0.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 Wo,filter as fI,isNonNullable as mI,isNullable as R0,map as k0,merge as L0,once as $0,Subject as ne,Subscription as bI,ValueSubject as _,flattenObject as Ld}from"@vkontakte/videoplayer-shared/es2024";import{Observable as I0,map as lI,Subscription as E0,Subject as x0}from"@vkontakte/videoplayer-shared/es2024";var cI=a=>new I0(e=>{let t=new E0,i=a.desiredPlaybackState$.stateChangeStarted$.pipe(lI(({from:l,to:p})=>`${l}-${p}`)),r=a.desiredPlaybackState$.stateChangeEnded$,s=a.providerChanged$.pipe(lI(({type:l})=>l!==void 0)),n=new x0,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 w0,Subscription as A0,combine as P0,filter as pI,once as hI}from"@vkontakte/videoplayer-shared/es2024";function dI(){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 A0;this.audioContext=null;this.gainNode=null;this.mediaElementSource=null;this.subscriptions.add(this.provider$.pipe(pI(s=>!!s.type),hI()).subscribe(({type:s})=>this.subscribe(s)))}static{this.errorId="VolumeMultiplierManager"}subscribe(e){B.browser.isSafari&&e!=="MPEG"||this.subscriptions.add(P0({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe(pI(({playbackState:t,video:i,volume:{muted:r,volume:s}})=>t==="playing"&&!!i&&!r&&!!s),hI()).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=dI();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:w0.VIDEO_PIPELINE,message:e?.message??`${a.errorId} exception`,thrown:e})}};var M0={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 bI;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=Yl([...oT(this.params.tuning),...nT(this.params.tuning)]).filter(l=>mI(e.sources[l])),{forceFormat:i,formatsToAvoid:r}=this.params.tuning,s=[];i?s=[i]:r.length?s=[...t.filter(l=>!(0,$d.default)(r,l)),...t.filter(l=>(0,$d.default)(r,l))]:s=t,this.log({message:`Selected formats: ${s.join(" > ")}`}),this.tracer.log("Selected formats",Ld(s)),this.screenFormatsIterator=new Cr(s);let n=[...qc(!0),...qc(!1)];this.chromecastFormatsIterator=new Cr(n.filter(l=>mI(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:Wo.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 Rs({...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 ks({...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 ev({...u,source:o,config:{...M0,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,SI.default)((0,gI.default)(e).map(([r,s])=>[r,i(s)]))}initProviderErrorHandling(){let e=new bI,t=!1,i=0;return e.add(L0(this.providerOutput.error$.pipe(fI(r=>!this.params.tuning.ignoreAudioRendererError||!r.message||!/AUDIO_RENDERER_ERROR/ig.test(r.message))),cI({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(k0(r=>({id:`ProviderHangup:${r}`,category:Wo.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(fI(({to:s})=>s==="playing"),$0()).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===Wo.NETWORK,o=r.category===Wo.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",Ld(n)):this.tracer.error("providerError",Ld(n))})),e}};import{fromEvent as Go,once as D0,combine as C0,Subscription as vI,ValueSubject as Md,map as B0,filter as V0,isNonNullable as zo,now as Qe,safeStorage as Dd}from"@vkontakte/videoplayer-shared/es2024";var _0=5e3,yI="one_video_throughput",TI="one_video_rtt",Bs=window.navigator.connection,II=()=>{let a=Bs?.downlink;if(zo(a)&&a!==10)return a*1e3},EI=()=>{let a=Bs?.rtt;if(zo(a)&&a!==3e3)return a},xI=(a,e,t)=>{let i=t*8,r=i/a;return i/(r+e)},Cd=class a{constructor(e){this.subscription=new vI;this.concurrentDownloads=new Set;this.tuningConfig=e;let t=a.load(yI)||(e.useBrowserEstimation?II():void 0)||_0,i=a.load(TI)??(e.useBrowserEstimation?EI():void 0)??0;if(this.throughput$=new Md(t),this.rtt$=new Md(i),this.rttAdjustedThroughput$=new Md(xI(t,i,e.rttPenaltyRequestSize)),this.throughput=Mt.getSmoothedValue(t,-1,e),this.rtt=Mt.getSmoothedValue(i,1,e),e.useBrowserEstimation){let r=()=>{let n=II();n&&this.throughput.next(n);let u=EI();zo(u)&&this.rtt.next(u)};Bs&&"onchange"in Bs&&this.subscription.add(Go(Bs,"change").subscribe(r)),r()}this.subscription.add(this.throughput.smoothed$.subscribe(r=>{Dd.set(yI,r.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(r=>{Dd.set(TI,r.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(C0({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(B0(({throughput:r,rtt:s})=>xI(r,s,e.rttPenaltyRequestSize)),V0(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 vI;switch(this.subscription.add(r),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:r.add(Go(e,"progress").pipe(D0()).subscribe(s=>{t=s.loaded,i=Qe()}));break;case 1:case 0:r.add(Go(e,"loadstart").subscribe(()=>{t=0,i=Qe()}));break}r.add(Go(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=Dd.get(e);if(zo(t))return parseInt(t,10)??void 0}},wI=Cd;import{fillWithDefault as O0,VideoQuality as Yo}from"@vkontakte/videoplayer-shared/es2024";var AI={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:Yo.Q_4320P,activeVideoAreaThreshold:.1,highQualityLimit:Yo.Q_720P,trafficSavingLimit:Yo.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:Yo.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},PI=a=>({...O0(a,AI),configName:[...a.configName??[],...AI.configName]});import{assertNonNullable as Vd,combine as Ct,ErrorCategory as Ko,filter as O,filterChanged as Y,fromEvent as _d,isNonNullable as $I,isNullable as Q0,Logger as W0,map as G,mapTo as MI,merge as ii,now as Xo,once as N,Subject as W,Subscription as DI,tap as Od,ValueSubject as R,isHigher as G0,isInvariantQuality as CI,flattenObject as ri,throttle as Fd,getTraceSubscriptionMethod as BI,TracerFactory as z0,InternalsExposure as Y0,getPlayerId as K0}from"@vkontakte/videoplayer-shared/es2024";import{merge as F0,map as N0,filter as RI,isNonNullable as q0}from"@vkontakte/videoplayer-shared/es2024";var Bd=({seekState:a,position$:e})=>F0(a.stateChangeEnded$.pipe(N0(({to:t})=>t.state==="none"?void 0:(t.position??NaN)/1e3),RI(q0)),e.pipe(RI(()=>a.getState().state==="none")));import{assertNonNullable as U0}from"@vkontakte/videoplayer-shared/es2024";var kI=a=>{let e=typeof a.container=="string"?document.getElementById(a.container):a.container;return U0(e,`Wrong container or containerId {${a.container}}`),e};import{filter as H0,once as j0}from"@vkontakte/videoplayer-shared/es2024";var LI=(a,e,t,i)=>{a!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&t?.getValue().length===0?t.pipe(H0(r=>r.length>0),j0()).subscribe(r=>{r.find(i)&&e.startTransitionTo(a)}):(a===void 0||t?.getValue().find(i))&&e.startTransitionTo(a)};var Jo=class{constructor(e={configName:[]},t=z0.createRootTracer(!1),i){this.subscription=new DI;this.logger=new W0;this.abrLogger=this.logger.createComponentLog("ABR");this.internalsExposure=null;this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new R(!1);this.hasLiveOffsetByPausedTimer=0;this.playerInitRequest=0;this.playerInited=new R(!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 R(void 0),position$:new R(0),duration$:new R(1/0),muted$:new R(!1),volume$:new R(1),availableVideoStreams$:new R([]),currentVideoStream$:new R(void 0),availableQualities$:new R([]),availableQualitiesFps$:new R({}),currentQuality$:new R(void 0),isAutoQualityEnabled$:new R(!0),autoQualityLimitingAvailable$:new R(!1),autoQualityLimits$:new R({}),predefinedQualityLimitType$:new R("unknown"),availableAudioStreams$:new R([]),currentAudioStream$:new R(void 0),availableAudioTracks$:new R([]),isAudioAvailable$:new R(!0),currentPlaybackRate$:new R(1),currentBuffer$:new R({start:0,end:0}),isBuffering$:new R(!0),isStalled$:new R(!1),isEnded$:new R(!1),isLooped$:new R(!1),isLive$:new R(void 0),isLiveEnded$:new R(null),canPlayLiveTailBuffer$:new R(!1),canChangePlaybackSpeed$:new R(void 0),atLiveEdge$:new R(void 0),atLiveDurationEdge$:new R(void 0),liveTime$:new R(void 0),liveBufferTime$:new R(void 0),liveLatency$:new R(void 0),currentFormat$:new R(void 0),availableTextTracks$:new R([]),currentTextTrack$:new R(void 0),throughputEstimation$:new R(void 0),rttEstimation$:new R(void 0),videoBitrate$:new R(void 0),hostname$:new R(void 0),httpConnectionType$:new R(void 0),httpConnectionReused$:new R(void 0),surface$:new R("none"),chromecastState$:new R("NOT_AVAILABLE"),chromecastDeviceName$:new R(void 0),intrinsicVideoSize$:new R(void 0),availableSources$:new R(void 0),is3DVideo$:new R(!1),currentVideoSegmentLength$:new R(0),currentAudioSegmentLength$:new R(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 R(void 0),tuningConfigName$:new R([]),enableDebugTelemetry$:new R(!1),dumpTelemetry:wS,getCurrentTime$:new R(null)};if(this.initLogs(),this.tuning=PI(e),this.tracer=t,this.tuning.suppressExceptionsInObservables&&((0,Nd.default)(this.info).forEach(r=>r.setSuppressErrors(!0)),(0,Nd.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 wI(this.tuning.throughputEstimator),e.exposeInternalsToGlobal&&(this.internalsExposure=new Y0("core",K0(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,VI.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:Ko.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=kI(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?B.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"),_d(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(()=>{Vd(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.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(()=>{LI(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(Q0(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),i=t.state==="none"?void 0:t.position;return $I(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(PS(e,t,i))})),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(O(({from:e})=>e==="stopped"),N()).subscribe(()=>{this.initedAt=Xo(),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:Ko.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)=>CI(o)?1:CI(l)?-1:G0(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=>$I(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(Od(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:Bd({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(),Od(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(),Od(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(Bd({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(ii(e.providerOutput.endedEvent$.pipe(MI(!0)),e.providerOutput.seekedEvent$.pipe(MI(!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:Ko.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??Xo()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe(N(),G(()=>Xo()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(N(),G(()=>Xo()-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 R(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let i=new R(!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 DI;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;Vd(this.providerContainer),Vd(e),xS(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(t=>ES(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 Ae("fatalError")),this.events.managedError$.subscribe(new Ae("managedError")),e.position$.subscribe(new Ae("position")),e.currentVideoTrack$.pipe(G(t=>t?.quality)).subscribe(new Ae("quality")),this.info.currentBuffer$.subscribe(new Ae("buffer")),e.isBuffering$.subscribe(new Ae("isBuffering"))].forEach(t=>this.subscription.add(t)),ma("codecs",B.video.supportedCodecs)}initTracerSubscription(){let e=BI(this.tracer.log.bind(this.tracer)),t=BI(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(Fd(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),Fd(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),Fd(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:Ko.DOM,message:String(r)})})};this.subscription.add(ii(_d(document,"visibilitychange"),_d(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 TX,Observable as IX,Subject as EX,ValueSubject as xX,VideoQuality as wX}from"@vkontakte/videoplayer-shared/es2024";var AX=`@vkontakte/videoplayer-core@${Hd}`;export{js as ChromecastState,tu as HttpConnectionType,IX as Observable,$e as PlaybackState,Jo as Player,Qs as PredefinedQualityLimits,AX as SDK_VERSION,EX as Subject,TX as Subscription,iu as Surface,Hd as VERSION,xX as ValueSubject,xt as VideoFormat,wX as VideoQuality,qL as areValidLiveRecordSources,B as clientChecker,ca as isMobile};