@vkontakte/videoplayer-core 2.0.136-dev.65dd5a4b.0 → 2.0.136-dev.969962ab.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/esnext.esm.js CHANGED
@@ -1,12 +1,12 @@
1
1
  /**
2
- * @vkontakte/videoplayer-core v2.0.136-dev.65dd5a4b.0
3
- * Wed, 09 Jul 2025 08:27:14 GMT
2
+ * @vkontakte/videoplayer-core v2.0.136-dev.969962ab.0
3
+ * Wed, 09 Jul 2025 08:01:59 GMT
4
4
  * https://st.mycdn.me/static/vkontakte-videoplayer/2-0-136/doc/
5
5
  */
6
- var TI=Object.create;var Rd=Object.defineProperty;var II=Object.getOwnPropertyDescriptor;var EI=Object.getOwnPropertyNames;var xI=Object.getPrototypeOf,wI=Object.prototype.hasOwnProperty;var m=(a,e)=>()=>(e||a((e={exports:{}}).exports,e),e.exports);var AI=(a,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of EI(e))!wI.call(a,r)&&r!==t&&Rd(a,r,{get:()=>e[r],enumerable:!(i=II(e,r))||i.enumerable});return a};var V=(a,e,t)=>(t=a!=null?TI(xI(a)):{},AI(e||!a||!a.__esModule?Rd(t,"default",{value:a,enumerable:!0}):t,a));var se=m((jo,$d)=>{"use strict";var Mr=function(a){return a&&a.Math===Math&&a};$d.exports=Mr(typeof globalThis=="object"&&globalThis)||Mr(typeof window=="object"&&window)||Mr(typeof self=="object"&&self)||Mr(typeof global=="object"&&global)||Mr(typeof jo=="object"&&jo)||function(){return this}()||Function("return this")()});var me=m((E0,Md)=>{"use strict";Md.exports=function(a){try{return!!a()}catch{return!0}}});var Dr=m((x0,Dd)=>{"use strict";var kI=me();Dd.exports=!kI(function(){var a=function(){}.bind();return typeof a!="function"||a.hasOwnProperty("prototype")})});var Qo=m((w0,_d)=>{"use strict";var PI=Dr(),Vd=Function.prototype,Cd=Vd.apply,Bd=Vd.call;_d.exports=typeof Reflect=="object"&&Reflect.apply||(PI?Bd.bind(Cd):function(){return Bd.apply(Cd,arguments)})});var le=m((A0,Nd)=>{"use strict";var Od=Dr(),Fd=Function.prototype,Go=Fd.call,RI=Od&&Fd.bind.bind(Go,Go);Nd.exports=Od?RI:function(a){return function(){return Go.apply(a,arguments)}}});var ii=m((k0,qd)=>{"use strict";var Ud=le(),LI=Ud({}.toString),$I=Ud("".slice);qd.exports=function(a){return $I(LI(a),8,-1)}});var Wo=m((P0,Hd)=>{"use strict";var MI=ii(),DI=le();Hd.exports=function(a){if(MI(a)==="Function")return DI(a)}});var re=m((R0,jd)=>{"use strict";var zo=typeof document=="object"&&document.all;jd.exports=typeof zo>"u"&&zo!==void 0?function(a){return typeof a=="function"||a===zo}:function(a){return typeof a=="function"}});var Ve=m((L0,Qd)=>{"use strict";var CI=me();Qd.exports=!CI(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var _e=m(($0,Gd)=>{"use strict";var BI=Dr(),$s=Function.prototype.call;Gd.exports=BI?$s.bind($s):function(){return $s.apply($s,arguments)}});var Yo=m(Yd=>{"use strict";var Wd={}.propertyIsEnumerable,zd=Object.getOwnPropertyDescriptor,VI=zd&&!Wd.call({1:2},1);Yd.f=VI?function(e){var t=zd(this,e);return!!t&&t.enumerable}:Wd});var Cr=m((D0,Kd)=>{"use strict";Kd.exports=function(a,e){return{enumerable:!(a&1),configurable:!(a&2),writable:!(a&4),value:e}}});var Jd=m((C0,Xd)=>{"use strict";var _I=le(),OI=me(),FI=ii(),Ko=Object,NI=_I("".split);Xd.exports=OI(function(){return!Ko("z").propertyIsEnumerable(0)})?function(a){return FI(a)==="String"?NI(a,""):Ko(a)}:Ko});var Di=m((B0,Zd)=>{"use strict";Zd.exports=function(a){return a==null}});var Ot=m((V0,ep)=>{"use strict";var UI=Di(),qI=TypeError;ep.exports=function(a){if(UI(a))throw new qI("Can't call method on "+a);return a}});var ri=m((_0,tp)=>{"use strict";var HI=Jd(),jI=Ot();tp.exports=function(a){return HI(jI(a))}});var Oe=m((O0,ip)=>{"use strict";var QI=re();ip.exports=function(a){return typeof a=="object"?a!==null:QI(a)}});var Ci=m((F0,rp)=>{"use strict";rp.exports={}});var xt=m((N0,sp)=>{"use strict";var Xo=Ci(),Jo=se(),GI=re(),ap=function(a){return GI(a)?a:void 0};sp.exports=function(a,e){return arguments.length<2?ap(Xo[a])||ap(Jo[a]):Xo[a]&&Xo[a][e]||Jo[a]&&Jo[a][e]}});var Br=m((U0,np)=>{"use strict";var WI=le();np.exports=WI({}.isPrototypeOf)});var ai=m((q0,lp)=>{"use strict";var zI=se(),op=zI.navigator,up=op&&op.userAgent;lp.exports=up?String(up):""});var eu=m((H0,mp)=>{"use strict";var fp=se(),Zo=ai(),cp=fp.process,dp=fp.Deno,pp=cp&&cp.versions||dp&&dp.version,hp=pp&&pp.v8,Ze,Ms;hp&&(Ze=hp.split("."),Ms=Ze[0]>0&&Ze[0]<4?1:+(Ze[0]+Ze[1]));!Ms&&Zo&&(Ze=Zo.match(/Edge\/(\d+)/),(!Ze||Ze[1]>=74)&&(Ze=Zo.match(/Chrome\/(\d+)/),Ze&&(Ms=+Ze[1])));mp.exports=Ms});var tu=m((j0,gp)=>{"use strict";var bp=eu(),YI=me(),KI=se(),XI=KI.String;gp.exports=!!Object.getOwnPropertySymbols&&!YI(function(){var a=Symbol("symbol detection");return!XI(a)||!(Object(a)instanceof Symbol)||!Symbol.sham&&bp&&bp<41})});var iu=m((Q0,Sp)=>{"use strict";var JI=tu();Sp.exports=JI&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var ru=m((G0,vp)=>{"use strict";var ZI=xt(),eE=re(),tE=Br(),iE=iu(),rE=Object;vp.exports=iE?function(a){return typeof a=="symbol"}:function(a){var e=ZI("Symbol");return eE(e)&&tE(e.prototype,rE(a))}});var Vr=m((W0,yp)=>{"use strict";var aE=String;yp.exports=function(a){try{return aE(a)}catch{return"Object"}}});var dt=m((z0,Tp)=>{"use strict";var sE=re(),nE=Vr(),oE=TypeError;Tp.exports=function(a){if(sE(a))return a;throw new oE(nE(a)+" is not a function")}});var _r=m((Y0,Ip)=>{"use strict";var uE=dt(),lE=Di();Ip.exports=function(a,e){var t=a[e];return lE(t)?void 0:uE(t)}});var xp=m((K0,Ep)=>{"use strict";var au=_e(),su=re(),nu=Oe(),cE=TypeError;Ep.exports=function(a,e){var t,i;if(e==="string"&&su(t=a.toString)&&!nu(i=au(t,a))||su(t=a.valueOf)&&!nu(i=au(t,a))||e!=="string"&&su(t=a.toString)&&!nu(i=au(t,a)))return i;throw new cE("Can't convert object to primitive value")}});var et=m((X0,wp)=>{"use strict";wp.exports=!0});var Pp=m((J0,kp)=>{"use strict";var Ap=se(),dE=Object.defineProperty;kp.exports=function(a,e){try{dE(Ap,a,{value:e,configurable:!0,writable:!0})}catch{Ap[a]=e}return e}});var Or=m((Z0,$p)=>{"use strict";var pE=et(),hE=se(),fE=Pp(),Rp="__core-js_shared__",Lp=$p.exports=hE[Rp]||fE(Rp,{});(Lp.versions||(Lp.versions=[])).push({version:"3.38.0",mode:pE?"pure":"global",copyright:"\xA9 2014-2024 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.38.0/LICENSE",source:"https://github.com/zloirock/core-js"})});var ou=m((eV,Dp)=>{"use strict";var Mp=Or();Dp.exports=function(a,e){return Mp[a]||(Mp[a]=e||{})}});var Bi=m((tV,Cp)=>{"use strict";var mE=Ot(),bE=Object;Cp.exports=function(a){return bE(mE(a))}});var tt=m((iV,Bp)=>{"use strict";var gE=le(),SE=Bi(),vE=gE({}.hasOwnProperty);Bp.exports=Object.hasOwn||function(e,t){return vE(SE(e),t)}});var uu=m((rV,Vp)=>{"use strict";var yE=le(),TE=0,IE=Math.random(),EE=yE(1 .toString);Vp.exports=function(a){return"Symbol("+(a===void 0?"":a)+")_"+EE(++TE+IE,36)}});var be=m((aV,Op)=>{"use strict";var xE=se(),wE=ou(),_p=tt(),AE=uu(),kE=tu(),PE=iu(),Vi=xE.Symbol,lu=wE("wks"),RE=PE?Vi.for||Vi:Vi&&Vi.withoutSetter||AE;Op.exports=function(a){return _p(lu,a)||(lu[a]=kE&&_p(Vi,a)?Vi[a]:RE("Symbol."+a)),lu[a]}});var qp=m((sV,Up)=>{"use strict";var LE=_e(),Fp=Oe(),Np=ru(),$E=_r(),ME=xp(),DE=be(),CE=TypeError,BE=DE("toPrimitive");Up.exports=function(a,e){if(!Fp(a)||Np(a))return a;var t=$E(a,BE),i;if(t){if(e===void 0&&(e="default"),i=LE(t,a,e),!Fp(i)||Np(i))return i;throw new CE("Can't convert object to primitive value")}return e===void 0&&(e="number"),ME(a,e)}});var cu=m((nV,Hp)=>{"use strict";var VE=qp(),_E=ru();Hp.exports=function(a){var e=VE(a,"string");return _E(e)?e:e+""}});var Ds=m((oV,Qp)=>{"use strict";var OE=se(),jp=Oe(),du=OE.document,FE=jp(du)&&jp(du.createElement);Qp.exports=function(a){return FE?du.createElement(a):{}}});var pu=m((uV,Gp)=>{"use strict";var NE=Ve(),UE=me(),qE=Ds();Gp.exports=!NE&&!UE(function(){return Object.defineProperty(qE("div"),"a",{get:function(){return 7}}).a!==7})});var Yp=m(zp=>{"use strict";var HE=Ve(),jE=_e(),QE=Yo(),GE=Cr(),WE=ri(),zE=cu(),YE=tt(),KE=pu(),Wp=Object.getOwnPropertyDescriptor;zp.f=HE?Wp:function(e,t){if(e=WE(e),t=zE(t),KE)try{return Wp(e,t)}catch{}if(YE(e,t))return GE(!jE(QE.f,e,t),e[t])}});var hu=m((cV,Kp)=>{"use strict";var XE=me(),JE=re(),ZE=/#|\.prototype\./,Fr=function(a,e){var t=tx[ex(a)];return t===rx?!0:t===ix?!1:JE(e)?XE(e):!!e},ex=Fr.normalize=function(a){return String(a).replace(ZE,".").toLowerCase()},tx=Fr.data={},ix=Fr.NATIVE="N",rx=Fr.POLYFILL="P";Kp.exports=Fr});var _i=m((dV,Jp)=>{"use strict";var Xp=Wo(),ax=dt(),sx=Dr(),nx=Xp(Xp.bind);Jp.exports=function(a,e){return ax(a),e===void 0?a:sx?nx(a,e):function(){return a.apply(e,arguments)}}});var fu=m((pV,Zp)=>{"use strict";var ox=Ve(),ux=me();Zp.exports=ox&&ux(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var pt=m((hV,eh)=>{"use strict";var lx=Oe(),cx=String,dx=TypeError;eh.exports=function(a){if(lx(a))return a;throw new dx(cx(a)+" is not an object")}});var si=m(ih=>{"use strict";var px=Ve(),hx=pu(),fx=fu(),Cs=pt(),th=cu(),mx=TypeError,mu=Object.defineProperty,bx=Object.getOwnPropertyDescriptor,bu="enumerable",gu="configurable",Su="writable";ih.f=px?fx?function(e,t,i){if(Cs(e),t=th(t),Cs(i),typeof e=="function"&&t==="prototype"&&"value"in i&&Su in i&&!i[Su]){var r=bx(e,t);r&&r[Su]&&(e[t]=i.value,i={configurable:gu in i?i[gu]:r[gu],enumerable:bu in i?i[bu]:r[bu],writable:!1})}return mu(e,t,i)}:mu:function(e,t,i){if(Cs(e),t=th(t),Cs(i),hx)try{return mu(e,t,i)}catch{}if("get"in i||"set"in i)throw new mx("Accessors not supported");return"value"in i&&(e[t]=i.value),e}});var Oi=m((mV,rh)=>{"use strict";var gx=Ve(),Sx=si(),vx=Cr();rh.exports=gx?function(a,e,t){return Sx.f(a,e,vx(1,t))}:function(a,e,t){return a[e]=t,a}});var ne=m((bV,sh)=>{"use strict";var Nr=se(),yx=Qo(),Tx=Wo(),Ix=re(),Ex=Yp().f,xx=hu(),Fi=Ci(),wx=_i(),Ni=Oi(),ah=tt();Or();var Ax=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 yx(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?Nr:r?Nr[t]:Nr[t]&&Nr[t].prototype,o=i?Fi:Fi[t]||Ni(Fi,t,{})[t],u=o.prototype,l,c,d,p,h,f,b,g,S;for(p in e)l=xx(i?p:t+(r?".":"#")+p,a.forced),c=!l&&n&&ah(n,p),f=o[p],c&&(a.dontCallGetSet?(S=Ex(n,p),b=S&&S.value):b=n[p]),h=c&&b?b:e[p],!(!l&&!s&&typeof f==typeof h)&&(a.bind&&c?g=wx(h,Nr):a.wrap&&c?g=Ax(h):s&&Ix(h)?g=Tx(h):g=h,(a.sham||h&&h.sham||f&&f.sham)&&Ni(g,"sham",!0),Ni(o,p,g),s&&(d=t+"Prototype",ah(Fi,d)||Ni(Fi,d,{}),Ni(Fi[d],p,h),a.real&&u&&(l||!u[p])&&Ni(u,p,h)))}});var oh=m((gV,nh)=>{"use strict";var kx=Math.ceil,Px=Math.floor;nh.exports=Math.trunc||function(e){var t=+e;return(t>0?Px:kx)(t)}});var Ur=m((SV,uh)=>{"use strict";var Rx=oh();uh.exports=function(a){var e=+a;return e!==e||e===0?0:Rx(e)}});var ch=m((vV,lh)=>{"use strict";var Lx=Ur(),$x=Math.max,Mx=Math.min;lh.exports=function(a,e){var t=Lx(a);return t<0?$x(t+e,0):Mx(t,e)}});var vu=m((yV,dh)=>{"use strict";var Dx=Ur(),Cx=Math.min;dh.exports=function(a){var e=Dx(a);return e>0?Cx(e,9007199254740991):0}});var Ui=m((TV,ph)=>{"use strict";var Bx=vu();ph.exports=function(a){return Bx(a.length)}});var yu=m((IV,fh)=>{"use strict";var Vx=ri(),_x=ch(),Ox=Ui(),hh=function(a){return function(e,t,i){var r=Vx(e),s=Ox(r);if(s===0)return!a&&-1;var n=_x(i,s),o;if(a&&t!==t){for(;s>n;)if(o=r[n++],o!==o)return!0}else for(;s>n;n++)if((a||n in r)&&r[n]===t)return a||n||0;return!a&&-1}};fh.exports={includes:hh(!0),indexOf:hh(!1)}});var qr=m((EV,mh)=>{"use strict";mh.exports=function(){}});var bh=m(()=>{"use strict";var Fx=ne(),Nx=yu().includes,Ux=me(),qx=qr(),Hx=Ux(function(){return!Array(1).includes()});Fx({target:"Array",proto:!0,forced:Hx},{includes:function(e){return Nx(this,e,arguments.length>1?arguments[1]:void 0)}});qx("includes")});var Ft=m((AV,gh)=>{"use strict";var jx=xt();gh.exports=jx});var vh=m((kV,Sh)=>{"use strict";bh();var Qx=Ft();Sh.exports=Qx("Array","includes")});var Th=m((PV,yh)=>{"use strict";var Gx=vh();yh.exports=Gx});var Ge=m((RV,Ih)=>{"use strict";var Wx=Th();Ih.exports=Wx});var _s=m((UV,Lh)=>{"use strict";var tw=ou(),iw=uu(),Rh=tw("keys");Lh.exports=function(a){return Rh[a]||(Rh[a]=iw(a))}});var Mh=m((qV,$h)=>{"use strict";var rw=me();$h.exports=!rw(function(){function a(){}return a.prototype.constructor=null,Object.getPrototypeOf(new a)!==a.prototype})});var Os=m((HV,Ch)=>{"use strict";var aw=tt(),sw=re(),nw=Bi(),ow=_s(),uw=Mh(),Dh=ow("IE_PROTO"),Eu=Object,lw=Eu.prototype;Ch.exports=uw?Eu.getPrototypeOf:function(a){var e=nw(a);if(aw(e,Dh))return e[Dh];var t=e.constructor;return sw(t)&&e instanceof t?t.prototype:e instanceof Eu?lw:null}});var Fs=m((jV,Bh)=>{"use strict";Bh.exports={}});var Oh=m((QV,_h)=>{"use strict";var cw=le(),xu=tt(),dw=ri(),pw=yu().indexOf,hw=Fs(),Vh=cw([].push);_h.exports=function(a,e){var t=dw(a),i=0,r=[],s;for(s in t)!xu(hw,s)&&xu(t,s)&&Vh(r,s);for(;e.length>i;)xu(t,s=e[i++])&&(~pw(r,s)||Vh(r,s));return r}});var wu=m((GV,Fh)=>{"use strict";Fh.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var Au=m((WV,Nh)=>{"use strict";var fw=Oh(),mw=wu();Nh.exports=Object.keys||function(e){return fw(e,mw)}});var ku=m((zV,Qh)=>{"use strict";var qh=Ve(),bw=me(),Hh=le(),gw=Os(),Sw=Au(),vw=ri(),yw=Yo().f,jh=Hh(yw),Tw=Hh([].push),Iw=qh&&bw(function(){var a=Object.create(null);return a[2]=2,!jh(a,2)}),Uh=function(a){return function(e){for(var t=vw(e),i=Sw(t),r=Iw&&gw(t)===null,s=i.length,n=0,o=[],u;s>n;)u=i[n++],(!qh||(r?u in t:jh(t,u)))&&Tw(o,a?[u,t[u]]:t[u]);return o}};Qh.exports={entries:Uh(!0),values:Uh(!1)}});var Gh=m(()=>{"use strict";var Ew=ne(),xw=ku().entries;Ew({target:"Object",stat:!0},{entries:function(e){return xw(e)}})});var zh=m((XV,Wh)=>{"use strict";Gh();var ww=Ci();Wh.exports=ww.Object.entries});var Kh=m((JV,Yh)=>{"use strict";var Aw=zh();Yh.exports=Aw});var qi=m((ZV,Xh)=>{"use strict";var kw=Kh();Xh.exports=kw});var ni=m((e_,Jh)=>{"use strict";Jh.exports={}});var tf=m((t_,ef)=>{"use strict";var Pw=se(),Rw=re(),Zh=Pw.WeakMap;ef.exports=Rw(Zh)&&/native code/.test(String(Zh))});var $u=m((i_,sf)=>{"use strict";var Lw=tf(),af=se(),$w=Oe(),Mw=Oi(),Pu=tt(),Ru=Or(),Dw=_s(),Cw=Fs(),rf="Object already initialized",Lu=af.TypeError,Bw=af.WeakMap,Ns,Hr,Us,Vw=function(a){return Us(a)?Hr(a):Ns(a,{})},_w=function(a){return function(e){var t;if(!$w(e)||(t=Hr(e)).type!==a)throw new Lu("Incompatible receiver, "+a+" required");return t}};Lw||Ru.state?(it=Ru.state||(Ru.state=new Bw),it.get=it.get,it.has=it.has,it.set=it.set,Ns=function(a,e){if(it.has(a))throw new Lu(rf);return e.facade=a,it.set(a,e),e},Hr=function(a){return it.get(a)||{}},Us=function(a){return it.has(a)}):(oi=Dw("state"),Cw[oi]=!0,Ns=function(a,e){if(Pu(a,oi))throw new Lu(rf);return e.facade=a,Mw(a,oi,e),e},Hr=function(a){return Pu(a,oi)?a[oi]:{}},Us=function(a){return Pu(a,oi)});var it,oi;sf.exports={set:Ns,get:Hr,has:Us,enforce:Vw,getterFor:_w}});var Cu=m((r_,of)=>{"use strict";var Mu=Ve(),Ow=tt(),nf=Function.prototype,Fw=Mu&&Object.getOwnPropertyDescriptor,Du=Ow(nf,"name"),Nw=Du&&function(){}.name==="something",Uw=Du&&(!Mu||Mu&&Fw(nf,"name").configurable);of.exports={EXISTS:Du,PROPER:Nw,CONFIGURABLE:Uw}});var lf=m(uf=>{"use strict";var qw=Ve(),Hw=fu(),jw=si(),Qw=pt(),Gw=ri(),Ww=Au();uf.f=qw&&!Hw?Object.defineProperties:function(e,t){Qw(e);for(var i=Gw(t),r=Ww(t),s=r.length,n=0,o;s>n;)jw.f(e,o=r[n++],i[o]);return e}});var Bu=m((s_,cf)=>{"use strict";var zw=xt();cf.exports=zw("document","documentElement")});var Fu=m((n_,gf)=>{"use strict";var Yw=pt(),Kw=lf(),df=wu(),Xw=Fs(),Jw=Bu(),Zw=Ds(),eA=_s(),pf=">",hf="<",_u="prototype",Ou="script",mf=eA("IE_PROTO"),Vu=function(){},bf=function(a){return hf+Ou+pf+a+hf+"/"+Ou+pf},ff=function(a){a.write(bf("")),a.close();var e=a.parentWindow.Object;return a=null,e},tA=function(){var a=Zw("iframe"),e="java"+Ou+":",t;return a.style.display="none",Jw.appendChild(a),a.src=String(e),t=a.contentWindow.document,t.open(),t.write(bf("document.F=Object")),t.close(),t.F},qs,Hs=function(){try{qs=new ActiveXObject("htmlfile")}catch{}Hs=typeof document<"u"?document.domain&&qs?ff(qs):tA():ff(qs);for(var a=df.length;a--;)delete Hs[_u][df[a]];return Hs()};Xw[mf]=!0;gf.exports=Object.create||function(e,t){var i;return e!==null?(Vu[_u]=Yw(e),i=new Vu,Vu[_u]=null,i[mf]=e):i=Hs(),t===void 0?i:Kw.f(i,t)}});var Hi=m((o_,Sf)=>{"use strict";var iA=Oi();Sf.exports=function(a,e,t,i){return i&&i.enumerable?a[e]=t:iA(a,e,t),a}});var Hu=m((u_,Tf)=>{"use strict";var rA=me(),aA=re(),sA=Oe(),nA=Fu(),vf=Os(),oA=Hi(),uA=be(),lA=et(),qu=uA("iterator"),yf=!1,wt,Nu,Uu;[].keys&&(Uu=[].keys(),"next"in Uu?(Nu=vf(vf(Uu)),Nu!==Object.prototype&&(wt=Nu)):yf=!0);var cA=!sA(wt)||rA(function(){var a={};return wt[qu].call(a)!==a});cA?wt={}:lA&&(wt=nA(wt));aA(wt[qu])||oA(wt,qu,function(){return this});Tf.exports={IteratorPrototype:wt,BUGGY_SAFARI_ITERATORS:yf}});var js=m((l_,Ef)=>{"use strict";var dA=be(),pA=dA("toStringTag"),If={};If[pA]="z";Ef.exports=String(If)==="[object z]"});var jr=m((c_,xf)=>{"use strict";var hA=js(),fA=re(),Qs=ii(),mA=be(),bA=mA("toStringTag"),gA=Object,SA=Qs(function(){return arguments}())==="Arguments",vA=function(a,e){try{return a[e]}catch{}};xf.exports=hA?Qs:function(a){var e,t,i;return a===void 0?"Undefined":a===null?"Null":typeof(t=vA(e=gA(a),bA))=="string"?t:SA?Qs(e):(i=Qs(e))==="Object"&&fA(e.callee)?"Arguments":i}});var Af=m((d_,wf)=>{"use strict";var yA=js(),TA=jr();wf.exports=yA?{}.toString:function(){return"[object "+TA(this)+"]"}});var Qr=m((p_,Pf)=>{"use strict";var IA=js(),EA=si().f,xA=Oi(),wA=tt(),AA=Af(),kA=be(),kf=kA("toStringTag");Pf.exports=function(a,e,t,i){var r=t?a:a&&a.prototype;r&&(wA(r,kf)||EA(r,kf,{configurable:!0,value:e}),i&&!IA&&xA(r,"toString",AA))}});var Lf=m((h_,Rf)=>{"use strict";var PA=Hu().IteratorPrototype,RA=Fu(),LA=Cr(),$A=Qr(),MA=ni(),DA=function(){return this};Rf.exports=function(a,e,t,i){var r=e+" Iterator";return a.prototype=RA(PA,{next:LA(+!i,t)}),$A(a,r,!1,!0),MA[r]=DA,a}});var Mf=m((f_,$f)=>{"use strict";var CA=le(),BA=dt();$f.exports=function(a,e,t){try{return CA(BA(Object.getOwnPropertyDescriptor(a,e)[t]))}catch{}}});var Cf=m((m_,Df)=>{"use strict";var VA=Oe();Df.exports=function(a){return VA(a)||a===null}});var Vf=m((b_,Bf)=>{"use strict";var _A=Cf(),OA=String,FA=TypeError;Bf.exports=function(a){if(_A(a))return a;throw new FA("Can't set "+OA(a)+" as a prototype")}});var ju=m((g_,_f)=>{"use strict";var NA=Mf(),UA=Oe(),qA=Ot(),HA=Vf();_f.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var a=!1,e={},t;try{t=NA(Object.prototype,"__proto__","set"),t(e,[]),a=e instanceof Array}catch{}return function(r,s){return qA(r),HA(s),UA(r)&&(a?t(r,s):r.__proto__=s),r}}():void 0)});var zf=m((S_,Wf)=>{"use strict";var jA=ne(),QA=_e(),Gs=et(),Qf=Cu(),GA=re(),WA=Lf(),Of=Os(),Ff=ju(),zA=Qr(),YA=Oi(),Qu=Hi(),KA=be(),Nf=ni(),Gf=Hu(),XA=Qf.PROPER,JA=Qf.CONFIGURABLE,Uf=Gf.IteratorPrototype,Ws=Gf.BUGGY_SAFARI_ITERATORS,Gr=KA("iterator"),qf="keys",Wr="values",Hf="entries",jf=function(){return this};Wf.exports=function(a,e,t,i,r,s,n){WA(t,e,i);var o=function(S){if(S===r&&p)return p;if(!Ws&&S&&S in c)return c[S];switch(S){case qf:return function(){return new t(this,S)};case Wr:return function(){return new t(this,S)};case Hf:return function(){return new t(this,S)}}return function(){return new t(this)}},u=e+" Iterator",l=!1,c=a.prototype,d=c[Gr]||c["@@iterator"]||r&&c[r],p=!Ws&&d||o(r),h=e==="Array"&&c.entries||d,f,b,g;if(h&&(f=Of(h.call(new a)),f!==Object.prototype&&f.next&&(!Gs&&Of(f)!==Uf&&(Ff?Ff(f,Uf):GA(f[Gr])||Qu(f,Gr,jf)),zA(f,u,!0,!0),Gs&&(Nf[u]=jf))),XA&&r===Wr&&d&&d.name!==Wr&&(!Gs&&JA?YA(c,"name",Wr):(l=!0,p=function(){return QA(d,this)})),r)if(b={values:o(Wr),keys:s?p:o(qf),entries:o(Hf)},n)for(g in b)(Ws||l||!(g in c))&&Qu(c,g,b[g]);else jA({target:e,proto:!0,forced:Ws||l},b);return(!Gs||n)&&c[Gr]!==p&&Qu(c,Gr,p,{name:r}),Nf[e]=p,b}});var Kf=m((v_,Yf)=>{"use strict";Yf.exports=function(a,e){return{value:a,done:e}}});var Wu=m((y_,tm)=>{"use strict";var ZA=ri(),Gu=qr(),Xf=ni(),Zf=$u(),ek=si().f,tk=zf(),zs=Kf(),ik=et(),rk=Ve(),em="Array Iterator",ak=Zf.set,sk=Zf.getterFor(em);tm.exports=tk(Array,"Array",function(a,e){ak(this,{type:em,target:ZA(a),index:0,kind:e})},function(){var a=sk(this),e=a.target,t=a.index++;if(!e||t>=e.length)return a.target=void 0,zs(void 0,!0);switch(a.kind){case"keys":return zs(t,!1);case"values":return zs(e[t],!1)}return zs([t,e[t]],!1)},"values");var Jf=Xf.Arguments=Xf.Array;Gu("keys");Gu("values");Gu("entries");if(!ik&&rk&&Jf.name!=="values")try{ek(Jf,"name",{value:"values"})}catch{}});var rm=m((T_,im)=>{"use strict";var nk=be(),ok=ni(),uk=nk("iterator"),lk=Array.prototype;im.exports=function(a){return a!==void 0&&(ok.Array===a||lk[uk]===a)}});var zu=m((I_,sm)=>{"use strict";var ck=jr(),am=_r(),dk=Di(),pk=ni(),hk=be(),fk=hk("iterator");sm.exports=function(a){if(!dk(a))return am(a,fk)||am(a,"@@iterator")||pk[ck(a)]}});var om=m((E_,nm)=>{"use strict";var mk=_e(),bk=dt(),gk=pt(),Sk=Vr(),vk=zu(),yk=TypeError;nm.exports=function(a,e){var t=arguments.length<2?vk(a):e;if(bk(t))return gk(mk(t,a));throw new yk(Sk(a)+" is not iterable")}});var cm=m((x_,lm)=>{"use strict";var Tk=_e(),um=pt(),Ik=_r();lm.exports=function(a,e,t){var i,r;um(a);try{if(i=Ik(a,"return"),!i){if(e==="throw")throw t;return t}i=Tk(i,a)}catch(s){r=!0,i=s}if(e==="throw")throw t;if(r)throw i;return um(i),t}});var Ks=m((w_,fm)=>{"use strict";var Ek=_i(),xk=_e(),wk=pt(),Ak=Vr(),kk=rm(),Pk=Ui(),dm=Br(),Rk=om(),Lk=zu(),pm=cm(),$k=TypeError,Ys=function(a,e){this.stopped=a,this.result=e},hm=Ys.prototype;fm.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),o=!!(t&&t.INTERRUPTED),u=Ek(e,i),l,c,d,p,h,f,b,g=function(T){return l&&pm(l,"normal",T),new Ys(!0,T)},S=function(T){return r?(wk(T),o?u(T[0],T[1],g):u(T[0],T[1])):o?u(T,g):u(T)};if(s)l=a.iterator;else if(n)l=a;else{if(c=Lk(a),!c)throw new $k(Ak(a)+" is not iterable");if(kk(c)){for(d=0,p=Pk(a);p>d;d++)if(h=S(a[d]),h&&dm(hm,h))return h;return new Ys(!1)}l=Rk(a,c)}for(f=s?a.next:l.next;!(b=xk(f,l)).done;){try{h=S(b.value)}catch(T){pm(l,"throw",T)}if(typeof h=="object"&&h&&dm(hm,h))return h}return new Ys(!1)}});var bm=m((A_,mm)=>{"use strict";var Mk=Ve(),Dk=si(),Ck=Cr();mm.exports=function(a,e,t){Mk?Dk.f(a,e,Ck(0,t)):a[e]=t}});var gm=m(()=>{"use strict";var Bk=ne(),Vk=Ks(),_k=bm();Bk({target:"Object",stat:!0},{fromEntries:function(e){var t={};return Vk(e,function(i,r){_k(t,i,r)},{AS_ENTRIES:!0}),t}})});var vm=m((R_,Sm)=>{"use strict";Wu();gm();var Ok=Ci();Sm.exports=Ok.Object.fromEntries});var Tm=m((L_,ym)=>{"use strict";ym.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 Em=m(()=>{"use strict";Wu();var Fk=Tm(),Nk=se(),Uk=Qr(),Im=ni();for(Xs in Fk)Uk(Nk[Xs],Xs),Im[Xs]=Im.Array;var Xs});var wm=m((D_,xm)=>{"use strict";var qk=vm();Em();xm.exports=qk});var Yu=m((C_,Am)=>{"use strict";var Hk=wm();Am.exports=Hk});var km=m(()=>{"use strict"});var Ku=m((__,Pm)=>{"use strict";var zr=se(),jk=ai(),Qk=ii(),Js=function(a){return jk.slice(0,a.length)===a};Pm.exports=function(){return Js("Bun/")?"BUN":Js("Cloudflare-Workers")?"CLOUDFLARE":Js("Deno/")?"DENO":Js("Node.js/")?"NODE":zr.Bun&&typeof Bun.version=="string"?"BUN":zr.Deno&&typeof Deno.version=="object"?"DENO":Qk(zr.process)==="process"?"NODE":zr.window&&zr.document?"BROWSER":"REST"}()});var Zs=m((O_,Rm)=>{"use strict";var Gk=Ku();Rm.exports=Gk==="NODE"});var $m=m((F_,Lm)=>{"use strict";var Wk=si();Lm.exports=function(a,e,t){return Wk.f(a,e,t)}});var Cm=m((N_,Dm)=>{"use strict";var zk=xt(),Yk=$m(),Kk=be(),Xk=Ve(),Mm=Kk("species");Dm.exports=function(a){var e=zk(a);Xk&&e&&!e[Mm]&&Yk(e,Mm,{configurable:!0,get:function(){return this}})}});var Vm=m((U_,Bm)=>{"use strict";var Jk=Br(),Zk=TypeError;Bm.exports=function(a,e){if(Jk(e,a))return a;throw new Zk("Incorrect invocation")}});var Ju=m((q_,_m)=>{"use strict";var eP=le(),tP=re(),Xu=Or(),iP=eP(Function.toString);tP(Xu.inspectSource)||(Xu.inspectSource=function(a){return iP(a)});_m.exports=Xu.inspectSource});var el=m((H_,qm)=>{"use strict";var rP=le(),aP=me(),Om=re(),sP=jr(),nP=xt(),oP=Ju(),Fm=function(){},Nm=nP("Reflect","construct"),Zu=/^\s*(?:class|function)\b/,uP=rP(Zu.exec),lP=!Zu.test(Fm),Yr=function(e){if(!Om(e))return!1;try{return Nm(Fm,[],e),!0}catch{return!1}},Um=function(e){if(!Om(e))return!1;switch(sP(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return lP||!!uP(Zu,oP(e))}catch{return!0}};Um.sham=!0;qm.exports=!Nm||aP(function(){var a;return Yr(Yr.call)||!Yr(Object)||!Yr(function(){a=!0})||a})?Um:Yr});var jm=m((j_,Hm)=>{"use strict";var cP=el(),dP=Vr(),pP=TypeError;Hm.exports=function(a){if(cP(a))return a;throw new pP(dP(a)+" is not a constructor")}});var tl=m((Q_,Gm)=>{"use strict";var Qm=pt(),hP=jm(),fP=Di(),mP=be(),bP=mP("species");Gm.exports=function(a,e){var t=Qm(a).constructor,i;return t===void 0||fP(i=Qm(t)[bP])?e:hP(i)}});var zm=m((G_,Wm)=>{"use strict";var gP=le();Wm.exports=gP([].slice)});var Km=m((W_,Ym)=>{"use strict";var SP=TypeError;Ym.exports=function(a,e){if(a<e)throw new SP("Not enough arguments");return a}});var il=m((z_,Xm)=>{"use strict";var vP=ai();Xm.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(vP)});var dl=m((Y_,nb)=>{"use strict";var Fe=se(),yP=Qo(),TP=_i(),Jm=re(),IP=tt(),sb=me(),Zm=Bu(),EP=zm(),eb=Ds(),xP=Km(),wP=il(),AP=Zs(),ul=Fe.setImmediate,ll=Fe.clearImmediate,kP=Fe.process,rl=Fe.Dispatch,PP=Fe.Function,tb=Fe.MessageChannel,RP=Fe.String,al=0,Kr={},ib="onreadystatechange",Xr,ui,sl,nl;sb(function(){Xr=Fe.location});var cl=function(a){if(IP(Kr,a)){var e=Kr[a];delete Kr[a],e()}},ol=function(a){return function(){cl(a)}},rb=function(a){cl(a.data)},ab=function(a){Fe.postMessage(RP(a),Xr.protocol+"//"+Xr.host)};(!ul||!ll)&&(ul=function(e){xP(arguments.length,1);var t=Jm(e)?e:PP(e),i=EP(arguments,1);return Kr[++al]=function(){yP(t,void 0,i)},ui(al),al},ll=function(e){delete Kr[e]},AP?ui=function(a){kP.nextTick(ol(a))}:rl&&rl.now?ui=function(a){rl.now(ol(a))}:tb&&!wP?(sl=new tb,nl=sl.port2,sl.port1.onmessage=rb,ui=TP(nl.postMessage,nl)):Fe.addEventListener&&Jm(Fe.postMessage)&&!Fe.importScripts&&Xr&&Xr.protocol!=="file:"&&!sb(ab)?(ui=ab,Fe.addEventListener("message",rb,!1)):ib in eb("script")?ui=function(a){Zm.appendChild(eb("script"))[ib]=function(){Zm.removeChild(this),cl(a)}}:ui=function(a){setTimeout(ol(a),0)});nb.exports={set:ul,clear:ll}});var lb=m((K_,ub)=>{"use strict";var ob=se(),LP=Ve(),$P=Object.getOwnPropertyDescriptor;ub.exports=function(a){if(!LP)return ob[a];var e=$P(ob,a);return e&&e.value}});var pl=m((X_,db)=>{"use strict";var cb=function(){this.head=null,this.tail=null};cb.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}}};db.exports=cb});var hb=m((J_,pb)=>{"use strict";var MP=ai();pb.exports=/ipad|iphone|ipod/i.test(MP)&&typeof Pebble<"u"});var mb=m((Z_,fb)=>{"use strict";var DP=ai();fb.exports=/web0s(?!.*chrome)/i.test(DP)});var Ib=m((eO,Tb)=>{"use strict";var Qi=se(),CP=lb(),bb=_i(),hl=dl().set,BP=pl(),VP=il(),_P=hb(),OP=mb(),fl=Zs(),gb=Qi.MutationObserver||Qi.WebKitMutationObserver,Sb=Qi.document,vb=Qi.process,en=Qi.Promise,gl=CP("queueMicrotask"),ji,ml,bl,tn,yb;gl||(Jr=new BP,Zr=function(){var a,e;for(fl&&(a=vb.domain)&&a.exit();e=Jr.get();)try{e()}catch(t){throw Jr.head&&ji(),t}a&&a.enter()},!VP&&!fl&&!OP&&gb&&Sb?(ml=!0,bl=Sb.createTextNode(""),new gb(Zr).observe(bl,{characterData:!0}),ji=function(){bl.data=ml=!ml}):!_P&&en&&en.resolve?(tn=en.resolve(void 0),tn.constructor=en,yb=bb(tn.then,tn),ji=function(){yb(Zr)}):fl?ji=function(){vb.nextTick(Zr)}:(hl=bb(hl,Qi),ji=function(){hl(Zr)}),gl=function(a){Jr.head||ji(),Jr.add(a)});var Jr,Zr;Tb.exports=gl});var xb=m((tO,Eb)=>{"use strict";Eb.exports=function(a,e){try{arguments.length===1?console.error(a):console.error(a,e)}catch{}}});var rn=m((iO,wb)=>{"use strict";wb.exports=function(a){try{return{error:!1,value:a()}}catch(e){return{error:!0,value:e}}}});var li=m((rO,Ab)=>{"use strict";var FP=se();Ab.exports=FP.Promise});var Gi=m((aO,Lb)=>{"use strict";var NP=se(),ea=li(),UP=re(),qP=hu(),HP=Ju(),jP=be(),kb=Ku(),QP=et(),Sl=eu(),Pb=ea&&ea.prototype,GP=jP("species"),vl=!1,Rb=UP(NP.PromiseRejectionEvent),WP=qP("Promise",function(){var a=HP(ea),e=a!==String(ea);if(!e&&Sl===66||QP&&!(Pb.catch&&Pb.finally))return!0;if(!Sl||Sl<51||!/native code/.test(a)){var t=new ea(function(s){s(1)}),i=function(s){s(function(){},function(){})},r=t.constructor={};if(r[GP]=i,vl=t.then(function(){})instanceof i,!vl)return!0}return!e&&(kb==="BROWSER"||kb==="DENO")&&!Rb});Lb.exports={CONSTRUCTOR:WP,REJECTION_EVENT:Rb,SUBCLASSING:vl}});var Wi=m((sO,Mb)=>{"use strict";var $b=dt(),zP=TypeError,YP=function(a){var e,t;this.promise=new a(function(i,r){if(e!==void 0||t!==void 0)throw new zP("Bad Promise constructor");e=i,t=r}),this.resolve=$b(e),this.reject=$b(t)};Mb.exports.f=function(a){return new YP(a)}});var Xb=m(()=>{"use strict";var KP=ne(),XP=et(),on=Zs(),Nt=se(),Xi=_e(),Db=Hi(),Cb=ju(),JP=Qr(),ZP=Cm(),eR=dt(),nn=re(),tR=Oe(),iR=Vm(),rR=tl(),Fb=dl().set,xl=Ib(),aR=xb(),sR=rn(),nR=pl(),Nb=$u(),un=li(),wl=Gi(),Ub=Wi(),ln="Promise",qb=wl.CONSTRUCTOR,oR=wl.REJECTION_EVENT,uR=wl.SUBCLASSING,yl=Nb.getterFor(ln),lR=Nb.set,zi=un&&un.prototype,ci=un,an=zi,Hb=Nt.TypeError,Tl=Nt.document,Al=Nt.process,Il=Ub.f,cR=Il,dR=!!(Tl&&Tl.createEvent&&Nt.dispatchEvent),jb="unhandledrejection",pR="rejectionhandled",Bb=0,Qb=1,hR=2,kl=1,Gb=2,sn,Vb,fR,_b,Wb=function(a){var e;return tR(a)&&nn(e=a.then)?e:!1},zb=function(a,e){var t=e.value,i=e.state===Qb,r=i?a.ok:a.fail,s=a.resolve,n=a.reject,o=a.domain,u,l,c;try{r?(i||(e.rejection===Gb&&bR(e),e.rejection=kl),r===!0?u=t:(o&&o.enter(),u=r(t),o&&(o.exit(),c=!0)),u===a.promise?n(new Hb("Promise-chain cycle")):(l=Wb(u))?Xi(l,u,s,n):s(u)):n(t)}catch(d){o&&!c&&o.exit(),n(d)}},Yb=function(a,e){a.notified||(a.notified=!0,xl(function(){for(var t=a.reactions,i;i=t.get();)zb(i,a);a.notified=!1,e&&!a.rejection&&mR(a)}))},Kb=function(a,e,t){var i,r;dR?(i=Tl.createEvent("Event"),i.promise=e,i.reason=t,i.initEvent(a,!1,!0),Nt.dispatchEvent(i)):i={promise:e,reason:t},!oR&&(r=Nt["on"+a])?r(i):a===jb&&aR("Unhandled promise rejection",t)},mR=function(a){Xi(Fb,Nt,function(){var e=a.facade,t=a.value,i=Ob(a),r;if(i&&(r=sR(function(){on?Al.emit("unhandledRejection",t,e):Kb(jb,e,t)}),a.rejection=on||Ob(a)?Gb:kl,r.error))throw r.value})},Ob=function(a){return a.rejection!==kl&&!a.parent},bR=function(a){Xi(Fb,Nt,function(){var e=a.facade;on?Al.emit("rejectionHandled",e):Kb(pR,e,a.value)})},Yi=function(a,e,t){return function(i){a(e,i,t)}},Ki=function(a,e,t){a.done||(a.done=!0,t&&(a=t),a.value=e,a.state=hR,Yb(a,!0))},El=function(a,e,t){if(!a.done){a.done=!0,t&&(a=t);try{if(a.facade===e)throw new Hb("Promise can't be resolved itself");var i=Wb(e);i?xl(function(){var r={done:!1};try{Xi(i,e,Yi(El,r,a),Yi(Ki,r,a))}catch(s){Ki(r,s,a)}}):(a.value=e,a.state=Qb,Yb(a,!1))}catch(r){Ki({done:!1},r,a)}}};if(qb&&(ci=function(e){iR(this,an),eR(e),Xi(sn,this);var t=yl(this);try{e(Yi(El,t),Yi(Ki,t))}catch(i){Ki(t,i)}},an=ci.prototype,sn=function(e){lR(this,{type:ln,done:!1,notified:!1,parent:!1,reactions:new nR,rejection:!1,state:Bb,value:void 0})},sn.prototype=Db(an,"then",function(e,t){var i=yl(this),r=Il(rR(this,ci));return i.parent=!0,r.ok=nn(e)?e:!0,r.fail=nn(t)&&t,r.domain=on?Al.domain:void 0,i.state===Bb?i.reactions.add(r):xl(function(){zb(r,i)}),r.promise}),Vb=function(){var a=new sn,e=yl(a);this.promise=a,this.resolve=Yi(El,e),this.reject=Yi(Ki,e)},Ub.f=Il=function(a){return a===ci||a===fR?new Vb(a):cR(a)},!XP&&nn(un)&&zi!==Object.prototype)){_b=zi.then,uR||Db(zi,"then",function(e,t){var i=this;return new ci(function(r,s){Xi(_b,i,r,s)}).then(e,t)},{unsafe:!0});try{delete zi.constructor}catch{}Cb&&Cb(zi,an)}KP({global:!0,constructor:!0,wrap:!0,forced:qb},{Promise:ci});JP(ci,ln,!1,!0);ZP(ln)});var ig=m((uO,tg)=>{"use strict";var gR=be(),Zb=gR("iterator"),eg=!1;try{Jb=0,Pl={next:function(){return{done:!!Jb++}},return:function(){eg=!0}},Pl[Zb]=function(){return this},Array.from(Pl,function(){throw 2})}catch{}var Jb,Pl;tg.exports=function(a,e){try{if(!e&&!eg)return!1}catch{return!1}var t=!1;try{var i={};i[Zb]=function(){return{next:function(){return{done:t=!0}}}},a(i)}catch{}return t}});var Rl=m((lO,rg)=>{"use strict";var SR=li(),vR=ig(),yR=Gi().CONSTRUCTOR;rg.exports=yR||!vR(function(a){SR.all(a).then(void 0,function(){})})});var ag=m(()=>{"use strict";var TR=ne(),IR=_e(),ER=dt(),xR=Wi(),wR=rn(),AR=Ks(),kR=Rl();TR({target:"Promise",stat:!0,forced:kR},{all:function(e){var t=this,i=xR.f(t),r=i.resolve,s=i.reject,n=wR(function(){var o=ER(t.resolve),u=[],l=0,c=1;AR(e,function(d){var p=l++,h=!1;c++,IR(o,t,d).then(function(f){h||(h=!0,u[p]=f,--c||r(u))},s)}),--c||r(u)});return n.error&&s(n.value),i.promise}})});var ng=m(()=>{"use strict";var PR=ne(),RR=et(),LR=Gi().CONSTRUCTOR,$l=li(),$R=xt(),MR=re(),DR=Hi(),sg=$l&&$l.prototype;PR({target:"Promise",proto:!0,forced:LR,real:!0},{catch:function(a){return this.then(void 0,a)}});!RR&&MR($l)&&(Ll=$R("Promise").prototype.catch,sg.catch!==Ll&&DR(sg,"catch",Ll,{unsafe:!0}));var Ll});var og=m(()=>{"use strict";var CR=ne(),BR=_e(),VR=dt(),_R=Wi(),OR=rn(),FR=Ks(),NR=Rl();CR({target:"Promise",stat:!0,forced:NR},{race:function(e){var t=this,i=_R.f(t),r=i.reject,s=OR(function(){var n=VR(t.resolve);FR(e,function(o){BR(n,t,o).then(i.resolve,r)})});return s.error&&r(s.value),i.promise}})});var ug=m(()=>{"use strict";var UR=ne(),qR=Wi(),HR=Gi().CONSTRUCTOR;UR({target:"Promise",stat:!0,forced:HR},{reject:function(e){var t=qR.f(this),i=t.reject;return i(e),t.promise}})});var Ml=m((SO,lg)=>{"use strict";var jR=pt(),QR=Oe(),GR=Wi();lg.exports=function(a,e){if(jR(a),QR(e)&&e.constructor===a)return e;var t=GR.f(a),i=t.resolve;return i(e),t.promise}});var pg=m(()=>{"use strict";var WR=ne(),zR=xt(),cg=et(),YR=li(),dg=Gi().CONSTRUCTOR,KR=Ml(),XR=zR("Promise"),JR=cg&&!dg;WR({target:"Promise",stat:!0,forced:cg||dg},{resolve:function(e){return KR(JR&&this===XR?YR:this,e)}})});var hg=m(()=>{"use strict";Xb();ag();ng();og();ug();pg()});var gg=m(()=>{"use strict";var ZR=ne(),eL=et(),cn=li(),tL=me(),mg=xt(),bg=re(),iL=tl(),fg=Ml(),rL=Hi(),Cl=cn&&cn.prototype,aL=!!cn&&tL(function(){Cl.finally.call({then:function(){}},function(){})});ZR({target:"Promise",proto:!0,real:!0,forced:aL},{finally:function(a){var e=iL(this,mg("Promise")),t=bg(a);return this.then(t?function(i){return fg(e,a()).then(function(){return i})}:a,t?function(i){return fg(e,a()).then(function(){throw i})}:a)}});!eL&&bg(cn)&&(Dl=mg("Promise").prototype.finally,Cl.finally!==Dl&&rL(Cl,"finally",Dl,{unsafe:!0}));var Dl});var vg=m((wO,Sg)=>{"use strict";km();hg();gg();var sL=Ft();Sg.exports=sL("Promise","finally")});var Tg=m((AO,yg)=>{"use strict";var nL=vg();yg.exports=nL});var dn=m((kO,Ig)=>{"use strict";var oL=Tg();Ig.exports=oL});var Bg=m(()=>{"use strict";var IL=ne(),EL=ku().values;IL({target:"Object",stat:!0},{values:function(e){return EL(e)}})});var _g=m((dF,Vg)=>{"use strict";Bg();var xL=Ci();Vg.exports=xL.Object.values});var Fg=m((pF,Og)=>{"use strict";var wL=_g();Og.exports=wL});var Zi=m((hF,Ng)=>{"use strict";var AL=Fg();Ng.exports=AL});var rS=m(()=>{"use strict";var YL=ne(),KL=Bi(),XL=Ui(),JL=Ur(),ZL=qr();YL({target:"Array",proto:!0},{at:function(e){var t=KL(this),i=XL(t),r=JL(e),s=r>=0?r:i+r;return s<0||s>=i?void 0:t[s]}});ZL("at")});var sS=m((IN,aS)=>{"use strict";rS();var e$=Ft();aS.exports=e$("Array","at")});var oS=m((EN,nS)=>{"use strict";var t$=sS();nS.exports=t$});var bt=m((xN,uS)=>{"use strict";var i$=oS();uS.exports=i$});var rc=m((dq,US)=>{"use strict";var V$=ii();US.exports=Array.isArray||function(e){return V$(e)==="Array"}});var HS=m((pq,qS)=>{"use strict";var _$=TypeError,O$=9007199254740991;qS.exports=function(a){if(a>O$)throw _$("Maximum allowed index exceeded");return a}});var GS=m((hq,QS)=>{"use strict";var F$=rc(),N$=Ui(),U$=HS(),q$=_i(),jS=function(a,e,t,i,r,s,n,o){for(var u=r,l=0,c=n?q$(n,o):!1,d,p;l<i;)l in t&&(d=c?c(t[l],l,e):t[l],s>0&&F$(d)?(p=N$(d),u=jS(a,e,d,p,u,s-1)-1):(U$(u+1),a[u]=d),u++),l++;return u};QS.exports=jS});var KS=m((fq,YS)=>{"use strict";var WS=rc(),H$=el(),j$=Oe(),Q$=be(),G$=Q$("species"),zS=Array;YS.exports=function(a){var e;return WS(a)&&(e=a.constructor,H$(e)&&(e===zS||WS(e.prototype))?e=void 0:j$(e)&&(e=e[G$],e===null&&(e=void 0))),e===void 0?zS:e}});var JS=m((mq,XS)=>{"use strict";var W$=KS();XS.exports=function(a,e){return new(W$(a))(e===0?0:e)}});var ZS=m(()=>{"use strict";var z$=ne(),Y$=GS(),K$=dt(),X$=Bi(),J$=Ui(),Z$=JS();z$({target:"Array",proto:!0},{flatMap:function(e){var t=X$(this),i=J$(t),r;return K$(e),r=Z$(t,0),r.length=Y$(r,t,t,i,0,1,e,arguments.length>1?arguments[1]:void 0),r}})});var ev=m(()=>{"use strict";var eM=qr();eM("flatMap")});var iv=m((yq,tv)=>{"use strict";ZS();ev();var tM=Ft();tv.exports=tM("Array","flatMap")});var av=m((Tq,rv)=>{"use strict";var iM=iv();rv.exports=iM});var ga=m((Iq,sv)=>{"use strict";var rM=av();sv.exports=rM});var Sa=m((Eq,nv)=>{"use strict";var aM=jr(),sM=String;nv.exports=function(a){if(aM(a)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return sM(a)}});var ac=m((xq,ov)=>{"use strict";ov.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 cv=m((wq,lv)=>{"use strict";var nM=le(),oM=Ot(),uM=Sa(),nc=ac(),uv=nM("".replace),lM=RegExp("^["+nc+"]+"),cM=RegExp("(^|[^"+nc+"])["+nc+"]+$"),sc=function(a){return function(e){var t=uM(oM(e));return a&1&&(t=uv(t,lM,"")),a&2&&(t=uv(t,cM,"$1")),t}};lv.exports={start:sc(1),end:sc(2),trim:sc(3)}});var fv=m((Aq,hv)=>{"use strict";var dM=Cu().PROPER,pM=me(),dv=ac(),pv="\u200B\x85\u180E";hv.exports=function(a){return pM(function(){return!!dv[a]()||pv[a]()!==pv||dM&&dv[a].name!==a})}});var oc=m((kq,mv)=>{"use strict";var hM=cv().start,fM=fv();mv.exports=fM("trimStart")?function(){return hM(this)}:"".trimStart});var gv=m(()=>{"use strict";var mM=ne(),bv=oc();mM({target:"String",proto:!0,name:"trimStart",forced:"".trimLeft!==bv},{trimLeft:bv})});var vv=m(()=>{"use strict";gv();var bM=ne(),Sv=oc();bM({target:"String",proto:!0,name:"trimStart",forced:"".trimStart!==Sv},{trimStart:Sv})});var Tv=m((Mq,yv)=>{"use strict";vv();var gM=Ft();yv.exports=gM("String","trimLeft")});var Ev=m((Dq,Iv)=>{"use strict";var SM=Tv();Iv.exports=SM});var wv=m((Cq,xv)=>{"use strict";var vM=Ev();xv.exports=vM});var Nv=m(()=>{"use strict"});var Uv=m(()=>{"use strict"});var Hv=m((mj,qv)=>{"use strict";var qM=Oe(),HM=ii(),jM=be(),QM=jM("match");qv.exports=function(a){var e;return qM(a)&&((e=a[QM])!==void 0?!!e:HM(a)==="RegExp")}});var Qv=m((bj,jv)=>{"use strict";var GM=pt();jv.exports=function(){var a=GM(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 zv=m((gj,Wv)=>{"use strict";var WM=_e(),zM=tt(),YM=Br(),KM=Qv(),Gv=RegExp.prototype;Wv.exports=function(a){var e=a.flags;return e===void 0&&!("flags"in Gv)&&!zM(a,"flags")&&YM(Gv,a)?WM(KM,a):e}});var Kv=m((Sj,Yv)=>{"use strict";var pc=le(),XM=Bi(),JM=Math.floor,cc=pc("".charAt),ZM=pc("".replace),dc=pc("".slice),eD=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,tD=/\$([$&'`]|\d{1,2})/g;Yv.exports=function(a,e,t,i,r,s){var n=t+a.length,o=i.length,u=tD;return r!==void 0&&(r=XM(r),u=eD),ZM(s,u,function(l,c){var d;switch(cc(c,0)){case"$":return"$";case"&":return a;case"`":return dc(e,0,t);case"'":return dc(e,n);case"<":d=r[dc(c,1,-1)];break;default:var p=+c;if(p===0)return l;if(p>o){var h=JM(p/10);return h===0?l:h<=o?i[h-1]===void 0?cc(c,1):i[h-1]+cc(c,1):l}d=i[p-1]}return d===void 0?"":d})}});var Zv=m(()=>{"use strict";var iD=ne(),rD=_e(),fc=le(),Xv=Ot(),aD=re(),sD=Di(),nD=Hv(),pr=Sa(),oD=_r(),uD=zv(),lD=Kv(),cD=be(),dD=et(),pD=cD("replace"),hD=TypeError,hc=fc("".indexOf),fD=fc("".replace),Jv=fc("".slice),mD=Math.max;iD({target:"String",proto:!0},{replaceAll:function(e,t){var i=Xv(this),r,s,n,o,u,l,c,d,p,h,f=0,b="";if(!sD(e)){if(r=nD(e),r&&(s=pr(Xv(uD(e))),!~hc(s,"g")))throw new hD("`.replaceAll` does not allow non-global regexes");if(n=oD(e,pD),n)return rD(n,e,i,t);if(dD&&r)return fD(pr(i),e,t)}for(o=pr(i),u=pr(e),l=aD(t),l||(t=pr(t)),c=u.length,d=mD(1,c),p=hc(o,u);p!==-1;)h=l?pr(t(u,p,o)):lD(u,o,p,[],void 0,t),b+=Jv(o,f,p)+h,f=p+c,p=p+d>o.length?-1:hc(o,u,p+d);return f<o.length&&(b+=Jv(o,f)),b}})});var ty=m((Tj,ey)=>{"use strict";Nv();Uv();Zv();var bD=Ft();ey.exports=bD("String","replaceAll")});var ry=m((Ij,iy)=>{"use strict";var gD=ty();iy.exports=gD});var sy=m((Ej,ay)=>{"use strict";var SD=ry();ay.exports=SD});var oy=m((xj,ny)=>{"use strict";var vD=Ur(),yD=Sa(),TD=Ot(),ID=RangeError;ny.exports=function(e){var t=yD(TD(this)),i="",r=vD(e);if(r<0||r===1/0)throw new ID("Wrong number of repetitions");for(;r>0;(r>>>=1)&&(t+=t))r&1&&(i+=t);return i}});var py=m((wj,dy)=>{"use strict";var cy=le(),ED=vu(),uy=Sa(),xD=oy(),wD=Ot(),AD=cy(xD),kD=cy("".slice),PD=Math.ceil,ly=function(a){return function(e,t,i){var r=uy(wD(e)),s=ED(t),n=r.length,o=i===void 0?" ":uy(i),u,l;return s<=n||o===""?r:(u=s-n,l=AD(o,PD(u/o.length)),l.length>u&&(l=kD(l,0,u)),a?r+l:l+r)}};dy.exports={start:ly(!1),end:ly(!0)}});var fy=m((Aj,hy)=>{"use strict";var RD=ai();hy.exports=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(RD)});var my=m(()=>{"use strict";var LD=ne(),$D=py().start,MD=fy();LD({target:"String",proto:!0,forced:MD},{padStart:function(e){return $D(this,e,arguments.length>1?arguments[1]:void 0)}})});var gy=m((Rj,by)=>{"use strict";my();var DD=Ft();by.exports=DD("String","padStart")});var vy=m((Lj,Sy)=>{"use strict";var CD=gy();Sy.exports=CD});var Ty=m(($j,yy)=>{"use strict";var BD=vy();yy.exports=BD});var Ld="2.0.136-dev.65dd5a4b.0";var ke=(r=>(r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused",r))(ke||{}),Et=(v=>(v.MPEG="MPEG",v.DASH="DASH",v.DASH_SEP="DASH_SEP",v.DASH_SEP_VK="DASH_SEP",v.DASH_WEBM="DASH_WEBM",v.DASH_WEBM_AV1="DASH_WEBM_AV1",v.DASH_STREAMS="DASH_STREAMS",v.DASH_WEBM_VK="DASH_WEBM",v.DASH_ONDEMAND="DASH_ONDEMAND",v.DASH_ONDEMAND_VK="DASH_ONDEMAND",v.DASH_LIVE="DASH_LIVE",v.DASH_LIVE_CMAF="DASH_LIVE_CMAF",v.DASH_LIVE_WEBM="DASH_LIVE_WEBM",v.HLS="HLS",v.HLS_ONDEMAND="HLS_ONDEMAND",v.HLS_JS="HLS",v.HLS_LIVE="HLS_LIVE",v.HLS_LIVE_CMAF="HLS_LIVE_CMAF",v.WEB_RTC_LIVE="WEB_RTC_LIVE",v))(Et||{});var Rs=(r=>(r.NOT_AVAILABLE="NOT_AVAILABLE",r.AVAILABLE="AVAILABLE",r.CONNECTING="CONNECTING",r.CONNECTED="CONNECTED",r))(Rs||{}),qo=(i=>(i.HTTP1="http1",i.HTTP2="http2",i.QUIC="quic",i))(qo||{});var Ho=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(Ho||{}),Ls=(i=>(i.TRAFFIC_SAVING="traffic_saving",i.HIGH_QUALITY="high_quality",i.UNKNOWN="unknown",i))(Ls||{});var bI=V(Ge(),1);import{assertNever as Ph,assertNonNullable as zx,isNonNullable as Bs,ValueSubject as Tu,Subject as Yx,Subscription as Kx,merge as Xx,observableFrom as Jx,fromEvent as xh,map as wh,tap as Ah,filterChanged as Zx,isNullable as Iu,ErrorCategory as kh}from"@vkontakte/videoplayer-shared";var Eh=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 Vs=class{constructor(e){this.connection$=new Tu(void 0);this.castState$=new Tu("NOT_AVAILABLE");this.errorEvent$=new Yx;this.realCastState$=new Tu("NOT_AVAILABLE");this.subscription=new Kx;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=Bs(window.chrome?.cast),r=!!window.__onGCastApiAvailable;i?this.initializeCastApi():(window.__onGCastApiAvailable=s=>{delete window.__onGCastApiAvailable,s&&!this.isDestroyed&&this.initializeCastApi()},r||Eh("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:kh.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(){Bs(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();Iu(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();Iu(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(xh(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 Ph(r.sessionState)}})).add(Xx(xh(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(Ah(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),wh(r=>r.castState)),Jx([i.getCastState()])).pipe(Zx(),wh(ew),Ah(r=>{this.log({message:`realCastState$: ${r}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{let s=r==="CONNECTED",n=Bs(this.connection$.getValue());if(s&&!n){let o=i.getCurrentSession();zx(o);let u=o.getCastDevice(),l=o.getMediaSession()?.media?.contentId;(Iu(l)||l===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:o,castDevice:u}))}else!s&&n&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(r==="CONNECTED"?Bs(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:kh.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:r})}}},ew=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 Ph(a)}};var yd=V(Ge(),1),XT=V(qi(),1),JT=V(Yu(),1);var Mg=V(dn(),1);import{assertNever as Eg}from"@vkontakte/videoplayer-shared";var ae=(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:Eg(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:Eg(e)}};var P=(a,e,t=!1)=>{let i=a.getTransition();(t||!i||i.to===e)&&a.setState(e)};import{isNonNullable as uL,Subject as pn,merge as xg}from"@vkontakte/videoplayer-shared";var F=class{constructor(e){this.transitionStarted$=new pn;this.transitionEnded$=new pn;this.transitionUpdated$=new pn;this.forceChanged$=new pn;this.stateChangeStarted$=xg(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=xg(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||uL(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 lL}from"@vkontakte/videoplayer-shared";var wg=a=>{switch(a){case"MPEG":case"DASH":case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":case"HLS":case"HLS_ONDEMAND":return!1;case"DASH_LIVE":case"DASH_LIVE_CMAF":case"HLS_LIVE":case"HLS_LIVE_CMAF":case"DASH_LIVE_WEBM":case"WEB_RTC_LIVE":return!0;default:return lL(a)}},cL=a=>!!(a.DASH_ONDEMAND||a.HLS_ONDEMAND);import{assertNever as Ji,assertNonNullable as di,debounce as Ag,ErrorCategory as kg,fromEvent as pi,isNonNullable as Pg,map as Rg,merge as Lg,observableFrom as dL,Subject as pL,Subscription as Bl,timeout as hL,getHighestQuality as fL}from"@vkontakte/videoplayer-shared";var mL=5,bL=5,gL=500,$g=7e3,ta=class{constructor(e){this.subscription=new Bl;this.loadMediaTimeoutSubscription=new Bl;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:Ji(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:Ji(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:Ji(e)}break}default:Ji(i)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(wg(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 Bl;this.subscription.add(e),this.subscription.add(Lg(this.videoState.stateChangeStarted$.pipe(Rg(r=>`stateChangeStarted$ ${JSON.stringify(r)}`)),this.videoState.stateChangeEnded$.pipe(Rg(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 pL;e.add(r.pipe(Ag(gL)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add(pi(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe(n=>{this.logRemoteEvent(n);let o=n.value;this.params.output.position$.next(o),(this.params.desiredState.seekState.getState().state==="applying"||Math.abs(o-s)>mL)&&r.next(o),s=o})),e.add(pi(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(pi(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(pi(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemotePause():this.handleRemotePlay()}),t(pi(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),r=>{this.logRemoteEvent(r);let{remotePlayer:s}=this.params.connection,n=r.value,o=this.params.output.isBuffering$.getValue(),u=n===chrome.cast.media.PlayerState.BUFFERING;switch(o!==u&&this.params.output.isBuffering$.next(u),n){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&s.duration-s.currentTime<bL&&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:Ji(n)}}),t(pi(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t(pi(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({muted:r.value})});let i=Lg(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,dL(["init"])).pipe(Ag(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];di(l);let c=fL(Object.keys(l));di(c);let d=l[c];di(d),i=d,r="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let l=t[e];di(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];di(l),i=l.url,r="application/dash+xml",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let l=t[e];di(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];di(l),i=ae(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:kg.VIDEO_PIPELINE,message:l,thrown:c}),c}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return Ji(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:o,subtitle:u}=this.params.meta;return Pg(o)&&(n.metadata.title=o),Pg(u)&&(n.metadata.subtitle=u),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($g).subscribe(()=>s(`timeout(${$g})`)))});(0,Mg.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:kg.VIDEO_PIPELINE,message:s,thrown:r})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var tc=V(Ge(),1);import{clearVideoElement as Cg}from"@vkontakte/videoplayer-shared";import{clearVideoElement as SL}from"@vkontakte/videoplayer-shared";var Dg=a=>{try{a.pause(),a.playbackRate=0,SL(a),a.remove()}catch(e){console.error(e)}};import{fromEvent as vL,Subscription as yL}from"@vkontakte/videoplayer-shared";var Vl=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)}},_l=window.WeakMap?new WeakMap:new Vl,Ol=window.WeakMap?new WeakMap:new Map,TL=(a,e=20)=>{let t=0;return vL(a,"ratechange").subscribe(i=>{t++,t>=e&&(a.currentTime=a.currentTime,t=0)})},Pe=(a,{audioVideoSyncRate:e,disableYandexPiP:t})=>{let i=a.querySelector("video"),r=!!i;i?Cg(i):(i=document.createElement("video"),a.appendChild(i)),_l.set(i,r);let s=new yL;return s.add(TL(i,e)),Ol.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},Re=a=>{Ol.get(a)?.unsubscribe(),Ol.delete(a);let t=_l.get(a);_l.delete(a),t?Cg(a):Dg(a)};var Nl=V(Zi(),1);import{assertNonNullable as ra,isNonNullable as ft,isNullable as RL,fromEvent as er,merge as Ug,observableFrom as qg,filterChanged as Hg,map as aa,Subject as jg,Subscription as LL,ValueSubject as $L,ErrorCategory as ML}from"@vkontakte/videoplayer-shared";import{isNonNullable as Fl,isNullable as kL,Subscription as PL}from"@vkontakte/videoplayer-shared";var hn=(a,e,t,{equal:i=(n,o)=>n===o,changed$:r,onError:s}={})=>{let n=a.getState(),o=e(),u=kL(r),l=new PL;return r&&l.add(r.subscribe(c=>{let d=a.getState();i(c,d)&&a.setState(c)},s)),i(o,n)||(t(n),u&&a.setState(n)),l.add(a.stateChangeStarted$.subscribe(c=>{t(c.to),u&&a.setState(c.to)},s)),l},ht=(a,e,t)=>hn(e,()=>a.loop,i=>{Fl(i)&&(a.loop=i)},{onError:t}),Le=(a,e,t,i)=>hn(e,()=>({muted:a.muted,volume:a.volume}),r=>{Fl(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}),We=(a,e,t,i)=>hn(e,()=>a.playbackRate,r=>{Fl(r)&&(a.playbackRate=r)},{changed$:t,onError:i}),ia=hn;var DL=a=>["__",a.language,a.label].join("|"),CL=(a,e)=>{if(a.id===e)return!0;let[t,i,r]=e.split("|");return a.language===i&&a.label===r},Ul=class a{constructor(e){this.available$=new jg;this.current$=new $L(void 0);this.error$=new jg;this.subscription=new LL;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:ML.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(ia(t.internalTextTracks,()=>(0,Nl.default)(this.internalTracks),s=>{ft(s)&&this.setInternal(s)},{equal:(s,n)=>ft(s)&&ft(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(aa(s=>s.filter(({type:n})=>n==="internal"))),onError:r})),this.subscription.add(ia(t.externalTextTracks,()=>(0,Nl.default)(this.externalTracks),s=>{ft(s)&&this.setExternal(s)},{equal:(s,n)=>ft(s)&&ft(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(aa(s=>s.filter(({type:n})=>n==="external"))),onError:r})),this.subscription.add(ia(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(ia(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.activeCues)}))}subscribe(){ra(this.video);let{textTracks:e}=this.video;this.subscription.add(er(e,"addtrack").subscribe(()=>{let i=this.current$.getValue();i&&this.select(i)})),this.subscription.add(Ug(er(e,"addtrack"),er(e,"removetrack"),qg(["init"])).pipe(aa(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),Hg((i,r)=>i.length===r.length&&i.every(({id:s},n)=>s===r[n].id))).subscribe(this.available$)),this.subscription.add(Ug(er(e,"change"),qg(["init"])).pipe(aa(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),aa(i=>i&&this.htmlTextTrackToITextTrack(i).id),Hg()).subscribe(this.current$));let t=i=>this.applyCueSettings(i.target?.activeCues??null);this.subscription.add(er(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(er(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;ft(t.align)&&(r.align=t.align),ft(t.position)&&(r.position=t.position),ft(t.size)&&(r.size=t.size),ft(t.line)&&(r.line=t.line)}}htmlTextTracksAsArray(e=!1){ra(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:DL(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){ra(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(RL(e)||!CL(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){ra(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){ra(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)}},ze=Ul;var hi=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 Qg=a=>{let e=a;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e?.parentNode;return e??void 0},ql=a=>{let e=Qg(a);return!!(e&&e.fullscreenElement&&e.fullscreenElement===a)},Gg=a=>{let e=Qg(a);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===a)};import{fromEvent as Ee,map as mt,merge as yn,filterChanged as eS,isNonNullable as tS,Subject as HL,filter as jl,mapTo as Ql,combine as jL,once as QL,throttle as GL,ErrorCategory as WL,ValueSubject as iS,Subscription as zL}from"@vkontakte/videoplayer-shared";var BL=3,Wg=(a,e,t=BL)=>{let i=0,r=0;for(let s=0;s<a.length;s++){let n=a.start(s),o=a.end(s);if(n<=e&&e<=o){if(i=n,r=o,!t)return{from:i,to:r};for(let u=s-1;u>=0;u--)a.end(u)+t>=i&&(i=a.start(u));for(let u=s+1;u<a.length;u++)a.start(u)-t<=r&&(r=a.end(u))}}return{from:i,to:r}};var fn=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,o=/webkit|safari|khtml/i.test(e)?"Safari":void 0,u=/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||u||l||r||s||o||"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 zg=V(Ge(),1);var sa=()=>/Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test(navigator.appVersion??navigator.userAgent)||navigator?.userAgentData?.mobile;var mn=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,zg.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=sa()}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,o=/webOS|BlackBerry|IEMobile|Opera Mini/i.test(e)?"RestMobile":void 0;this._current=t||i||r||s||o||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 bn=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 Ne=()=>window.ManagedMediaSource||window.MediaSource,tr=()=>!!(window.ManagedMediaSource&&window.ManagedSourceBuffer?.prototype?.appendBuffer),Yg=()=>!!(window.MediaSource&&window.SourceBuffer?.prototype?.appendBuffer),gn=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;var VL=document.createElement("video"),_L='video/mp4; codecs="avc1.42000a,mp4a.40.2"',OL='video/mp4; codecs="hev1.1.6.L93.B0"',Kg='video/webm; codecs="vp09.00.10.08"',Xg='video/webm; codecs="av01.0.00M.08"',FL='audio/mp4; codecs="mp4a.40.2"',NL='audio/webm; codecs="opus"',Jg,UL=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:Xg}}),window.navigator.mediaCapabilities.decodingInfo({...a,video:{...a.video,contentType:Kg}})]);Jg={DASH_WEBM_AV1:e,DASH_WEBM:t}};UL().catch(a=>{console.log(VL),console.error(a)});var Sn=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 Jg}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:tr(),mse:Yg(),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=!!Ne()?.isTypeSupported?.(_L),t=!!Ne()?.isTypeSupported?.(OL),i=!!Ne()?.isTypeSupported?.(FL);this._codecs={h264:e,h265:t,vp9:!!Ne()?.isTypeSupported?.(Kg),av1:!!Ne()?.isTypeSupported?.(Xg),aac:i,opus:!!Ne()?.isTypeSupported?.(NL),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",vn=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:!!Ne()?.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 qL}from"@vkontakte/videoplayer-shared";var Hl=class{constructor(){this.isInited$=new qL(!1);this._displayChecker=new bn,this._deviceChecker=new mn(this._displayChecker),this._browserChecker=new fn,this._videoChecker=new Sn(this._deviceChecker,this._browserChecker),this._audioChecker=new vn,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)}},_=new Hl;var $e=a=>{let e=y=>Ee(a,y).pipe(Ql(void 0)),t=new zL,i=()=>t.unsubscribe(),r=yn(Ee(a,"progress"),Ee(a,"timeupdate")).pipe(mt(()=>Wg(a.buffered,a.currentTime))),s=_.browser.isSafari?jL({play:e("play").pipe(QL()),playing:e("playing")}).pipe(Ql(void 0)):e("playing"),n=Ee(a,"volumechange").pipe(mt(()=>({muted:a.muted,volume:a.volume}))),o=Ee(a,"ratechange").pipe(mt(()=>a.playbackRate)),u=Ee(a,"error").pipe(jl(()=>!!(a.error||a.played.length)),mt(()=>{let y=a.error;return{id:y?`MediaError#${y.code}`:"HtmlVideoError",category:WL.VIDEO_PIPELINE,message:y?y.message:"Error event from HTML video element",thrown:a.error??void 0}})),l=Ee(a,"timeupdate").pipe(mt(()=>a.currentTime)),c=["waiting","seeking","seeked","timeupdate"],d=new HL,p=.3,h;t.add(yn(...c.map(y=>Ee(a,y))).subscribe(y=>{let M=a.currentTime;a.loop&&tS(h)&&tS(M)&&h>=a.duration-p&&M<=p&&d.next(h),h=M}));let f=e("pause").pipe(jl(()=>!a.error&&h!==a.duration)),b=Ee(a,"enterpictureinpicture"),g=Ee(a,"leavepictureinpicture"),S=new iS(Gg(a));t.add(b.subscribe(()=>S.next(!0))),t.add(g.subscribe(()=>S.next(!1)));let T=new iS(ql(a)),v=Ee(a,"fullscreenchange");t.add(v.pipe(mt(()=>ql(a))).subscribe(T));let x=.1,w=1e3,L=Ee(a,"timeupdate").pipe(mt(y=>a.duration-a.currentTime<x),eS()),B=yn(L.pipe(jl(y=>!a.loop&&y)),Ee(a,"ended")).pipe(GL(w),Ql(void 0)),$=yn(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(y=>Ee(a,y)),L.pipe(mt(y=>({type:y?"ended":"unknown"})))).pipe(mt(y=>_.browser.isFirefox&&y.type==="ended"?a.readyState<2:a.readyState<3),eS());return{playing$:s,pause$:f,canplay$:e("canplay"),ended$:B,looped$:d,error$:u,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:l,durationChange$:Ee(a,"durationchange").pipe(mt(()=>a.duration)),isBuffering$:$,currentBuffer$:r,volumeState$:n,playbackRateState$:o,inPiP$:S,inFullscreen$:T,enterPip$:b,leavePip$:g,destroy:i}};import{VideoQuality as qt}from"@vkontakte/videoplayer-shared";var Ht=a=>{switch(a){case"mobile":return qt.Q_144P;case"lowest":return qt.Q_240P;case"low":return qt.Q_360P;case"sd":case"medium":return qt.Q_480P;case"hd":case"high":return qt.Q_720P;case"fullhd":case"full":return qt.Q_1080P;case"quadhd":case"quad":return qt.Q_1440P;case"ultrahd":case"ultra":return qt.Q_2160P}};var we=V(bt(),1),zl=V(Ge(),1),fi=V(qi(),1);import{isNonNullable as Y,isNullable as wn,now as SS,isHigher as An,isHigherOrEqual as rr,isInvariantQuality as kn,isLowerOrEqual as ar,videoSizeToQuality as vS,assertNotEmptyArray as Pn,assertNonNullable as yS}from"@vkontakte/videoplayer-shared";var Gl=!1,kt={},lS=a=>{Gl=a},cS=()=>{kt={}},dS=a=>{a(kt)},na=(a,e)=>{Gl&&(kt.meta=kt.meta??{},kt.meta[a]=e)},xe=class{constructor(e){this.name=e}next(e){if(!Gl)return;kt.series=kt.series??{};let t=kt.series[this.name]??[];t.push([Date.now(),e]),kt.series[this.name]=t}};import{isHigher as r$,isHigherOrEqual as LN,isLower as pS,isLowerOrEqual as $N,isNonNullable as Tn,isNullable as a$,videoHeightToQuality as In}from"@vkontakte/videoplayer-shared";function Wl(a,e,t){return!a.max&&a.min===e?"high_quality":!a.min&&a.max===t?"traffic_saving":"unknown"}function En(a,e,t){return!!a&&Wl(a,e,t)==="high_quality"}function ir(a,e,t){return a$(a)||Tn(a.min)&&Tn(a.max)&&pS(a.max,a.min)||Tn(a.min)&&e&&r$(a.min,e)||Tn(a.max)&&t&&pS(a.max,t)}function hS({limits:a,highestAvailableHeight:e,lowestAvailableHeight:t}){return ir({max:a?.max?In(a.max):void 0,min:a?.min?In(a.min):void 0},e?In(e):void 0,t?In(t):void 0)}var TS=new xe("best_bitrate"),Rn=(a,e,t)=>(e-t)*Math.pow(2,-10*a)+t;var sr=a=>(e,t)=>a*(Number(e.bitrate)-Number(t.bitrate)),jt=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=SS()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},Ln='Assertion "ABR Tracks is empty array" failed',xn=new WeakMap,fS=new WeakMap,mS=new WeakMap,oa=(a,e,t,i)=>{let r=[...e].sort(sr(1)),s=[...t].sort(sr(1)),n=s.filter(u=>Y(u.bitrate)&&Y(a.bitrate)?a.bitrate/u.bitrate>i:!0),o=(0,we.default)(s,Math.round(s.length*r.indexOf(a)/(r.length+1)))??(0,we.default)(s,-1);return o&&(0,zl.default)(n,o)?o:n.length?(0,we.default)(n,-1):(0,we.default)(s,0)},ua=(a,e,t,i)=>{let r=xn.get(e);r||(r=[...e].sort(sr(1)),xn.set(e,r));let s=xn.get(t);s||(s=[...t].sort(sr(1)),xn.set(t,s));let n=mS.get(a);n||(n=s.filter(u=>Y(u.bitrate)&&Y(a.bitrate)?a.bitrate/u.bitrate>i:!0),mS.set(a,n));let o=(0,we.default)(s,Math.round(s.length*r.indexOf(a)/(r.length+1)))??(0,we.default)(s,-1);return o&&(0,zl.default)(n,o)?o:n.length?(0,we.default)(n,-1):(0,we.default)(s,0)},bS=a=>"quality"in a,$n=(a,e,t,i)=>{let r=Y(i?.last?.bitrate)&&Y(t?.bitrate)&&i.last.bitrate<t.bitrate?a.trackCooldownIncreaseQuality:a.trackCooldownDecreaseQuality,s=t&&i&&i.history[t.id]&&SS()-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 o=bS(n)?"video":"audio",u=bS(n)?n.quality:n.bitrate;return e({message:`
6
+ var TI=Object.create;var Rd=Object.defineProperty;var II=Object.getOwnPropertyDescriptor;var EI=Object.getOwnPropertyNames;var xI=Object.getPrototypeOf,wI=Object.prototype.hasOwnProperty;var m=(a,e)=>()=>(e||a((e={exports:{}}).exports,e),e.exports);var AI=(a,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of EI(e))!wI.call(a,r)&&r!==t&&Rd(a,r,{get:()=>e[r],enumerable:!(i=II(e,r))||i.enumerable});return a};var V=(a,e,t)=>(t=a!=null?TI(xI(a)):{},AI(e||!a||!a.__esModule?Rd(t,"default",{value:a,enumerable:!0}):t,a));var se=m((Ho,$d)=>{"use strict";var Mr=function(a){return a&&a.Math===Math&&a};$d.exports=Mr(typeof globalThis=="object"&&globalThis)||Mr(typeof window=="object"&&window)||Mr(typeof self=="object"&&self)||Mr(typeof global=="object"&&global)||Mr(typeof Ho=="object"&&Ho)||function(){return this}()||Function("return this")()});var me=m((I0,Md)=>{"use strict";Md.exports=function(a){try{return!!a()}catch{return!0}}});var Dr=m((E0,Dd)=>{"use strict";var kI=me();Dd.exports=!kI(function(){var a=function(){}.bind();return typeof a!="function"||a.hasOwnProperty("prototype")})});var Qo=m((x0,_d)=>{"use strict";var PI=Dr(),Vd=Function.prototype,Cd=Vd.apply,Bd=Vd.call;_d.exports=typeof Reflect=="object"&&Reflect.apply||(PI?Bd.bind(Cd):function(){return Bd.apply(Cd,arguments)})});var le=m((w0,Nd)=>{"use strict";var Od=Dr(),Fd=Function.prototype,Go=Fd.call,RI=Od&&Fd.bind.bind(Go,Go);Nd.exports=Od?RI:function(a){return function(){return Go.apply(a,arguments)}}});var ii=m((A0,qd)=>{"use strict";var Ud=le(),LI=Ud({}.toString),$I=Ud("".slice);qd.exports=function(a){return $I(LI(a),8,-1)}});var Wo=m((k0,jd)=>{"use strict";var MI=ii(),DI=le();jd.exports=function(a){if(MI(a)==="Function")return DI(a)}});var re=m((P0,Hd)=>{"use strict";var zo=typeof document=="object"&&document.all;Hd.exports=typeof zo>"u"&&zo!==void 0?function(a){return typeof a=="function"||a===zo}:function(a){return typeof a=="function"}});var Ve=m((R0,Qd)=>{"use strict";var CI=me();Qd.exports=!CI(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var _e=m((L0,Gd)=>{"use strict";var BI=Dr(),$s=Function.prototype.call;Gd.exports=BI?$s.bind($s):function(){return $s.apply($s,arguments)}});var Yo=m(Yd=>{"use strict";var Wd={}.propertyIsEnumerable,zd=Object.getOwnPropertyDescriptor,VI=zd&&!Wd.call({1:2},1);Yd.f=VI?function(e){var t=zd(this,e);return!!t&&t.enumerable}:Wd});var Cr=m((M0,Kd)=>{"use strict";Kd.exports=function(a,e){return{enumerable:!(a&1),configurable:!(a&2),writable:!(a&4),value:e}}});var Jd=m((D0,Xd)=>{"use strict";var _I=le(),OI=me(),FI=ii(),Ko=Object,NI=_I("".split);Xd.exports=OI(function(){return!Ko("z").propertyIsEnumerable(0)})?function(a){return FI(a)==="String"?NI(a,""):Ko(a)}:Ko});var Di=m((C0,Zd)=>{"use strict";Zd.exports=function(a){return a==null}});var Ot=m((B0,ep)=>{"use strict";var UI=Di(),qI=TypeError;ep.exports=function(a){if(UI(a))throw new qI("Can't call method on "+a);return a}});var ri=m((V0,tp)=>{"use strict";var jI=Jd(),HI=Ot();tp.exports=function(a){return jI(HI(a))}});var Oe=m((_0,ip)=>{"use strict";var QI=re();ip.exports=function(a){return typeof a=="object"?a!==null:QI(a)}});var Ci=m((O0,rp)=>{"use strict";rp.exports={}});var xt=m((F0,sp)=>{"use strict";var Xo=Ci(),Jo=se(),GI=re(),ap=function(a){return GI(a)?a:void 0};sp.exports=function(a,e){return arguments.length<2?ap(Xo[a])||ap(Jo[a]):Xo[a]&&Xo[a][e]||Jo[a]&&Jo[a][e]}});var Br=m((N0,np)=>{"use strict";var WI=le();np.exports=WI({}.isPrototypeOf)});var ai=m((U0,lp)=>{"use strict";var zI=se(),op=zI.navigator,up=op&&op.userAgent;lp.exports=up?String(up):""});var eu=m((q0,mp)=>{"use strict";var fp=se(),Zo=ai(),cp=fp.process,dp=fp.Deno,pp=cp&&cp.versions||dp&&dp.version,hp=pp&&pp.v8,Ze,Ms;hp&&(Ze=hp.split("."),Ms=Ze[0]>0&&Ze[0]<4?1:+(Ze[0]+Ze[1]));!Ms&&Zo&&(Ze=Zo.match(/Edge\/(\d+)/),(!Ze||Ze[1]>=74)&&(Ze=Zo.match(/Chrome\/(\d+)/),Ze&&(Ms=+Ze[1])));mp.exports=Ms});var tu=m((j0,gp)=>{"use strict";var bp=eu(),YI=me(),KI=se(),XI=KI.String;gp.exports=!!Object.getOwnPropertySymbols&&!YI(function(){var a=Symbol("symbol detection");return!XI(a)||!(Object(a)instanceof Symbol)||!Symbol.sham&&bp&&bp<41})});var iu=m((H0,Sp)=>{"use strict";var JI=tu();Sp.exports=JI&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var ru=m((Q0,vp)=>{"use strict";var ZI=xt(),eE=re(),tE=Br(),iE=iu(),rE=Object;vp.exports=iE?function(a){return typeof a=="symbol"}:function(a){var e=ZI("Symbol");return eE(e)&&tE(e.prototype,rE(a))}});var Vr=m((G0,yp)=>{"use strict";var aE=String;yp.exports=function(a){try{return aE(a)}catch{return"Object"}}});var dt=m((W0,Tp)=>{"use strict";var sE=re(),nE=Vr(),oE=TypeError;Tp.exports=function(a){if(sE(a))return a;throw new oE(nE(a)+" is not a function")}});var _r=m((z0,Ip)=>{"use strict";var uE=dt(),lE=Di();Ip.exports=function(a,e){var t=a[e];return lE(t)?void 0:uE(t)}});var xp=m((Y0,Ep)=>{"use strict";var au=_e(),su=re(),nu=Oe(),cE=TypeError;Ep.exports=function(a,e){var t,i;if(e==="string"&&su(t=a.toString)&&!nu(i=au(t,a))||su(t=a.valueOf)&&!nu(i=au(t,a))||e!=="string"&&su(t=a.toString)&&!nu(i=au(t,a)))return i;throw new cE("Can't convert object to primitive value")}});var et=m((K0,wp)=>{"use strict";wp.exports=!0});var Pp=m((X0,kp)=>{"use strict";var Ap=se(),dE=Object.defineProperty;kp.exports=function(a,e){try{dE(Ap,a,{value:e,configurable:!0,writable:!0})}catch{Ap[a]=e}return e}});var Or=m((J0,$p)=>{"use strict";var pE=et(),hE=se(),fE=Pp(),Rp="__core-js_shared__",Lp=$p.exports=hE[Rp]||fE(Rp,{});(Lp.versions||(Lp.versions=[])).push({version:"3.38.0",mode:pE?"pure":"global",copyright:"\xA9 2014-2024 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.38.0/LICENSE",source:"https://github.com/zloirock/core-js"})});var ou=m((Z0,Dp)=>{"use strict";var Mp=Or();Dp.exports=function(a,e){return Mp[a]||(Mp[a]=e||{})}});var Bi=m((eV,Cp)=>{"use strict";var mE=Ot(),bE=Object;Cp.exports=function(a){return bE(mE(a))}});var tt=m((tV,Bp)=>{"use strict";var gE=le(),SE=Bi(),vE=gE({}.hasOwnProperty);Bp.exports=Object.hasOwn||function(e,t){return vE(SE(e),t)}});var uu=m((iV,Vp)=>{"use strict";var yE=le(),TE=0,IE=Math.random(),EE=yE(1 .toString);Vp.exports=function(a){return"Symbol("+(a===void 0?"":a)+")_"+EE(++TE+IE,36)}});var be=m((rV,Op)=>{"use strict";var xE=se(),wE=ou(),_p=tt(),AE=uu(),kE=tu(),PE=iu(),Vi=xE.Symbol,lu=wE("wks"),RE=PE?Vi.for||Vi:Vi&&Vi.withoutSetter||AE;Op.exports=function(a){return _p(lu,a)||(lu[a]=kE&&_p(Vi,a)?Vi[a]:RE("Symbol."+a)),lu[a]}});var qp=m((aV,Up)=>{"use strict";var LE=_e(),Fp=Oe(),Np=ru(),$E=_r(),ME=xp(),DE=be(),CE=TypeError,BE=DE("toPrimitive");Up.exports=function(a,e){if(!Fp(a)||Np(a))return a;var t=$E(a,BE),i;if(t){if(e===void 0&&(e="default"),i=LE(t,a,e),!Fp(i)||Np(i))return i;throw new CE("Can't convert object to primitive value")}return e===void 0&&(e="number"),ME(a,e)}});var cu=m((sV,jp)=>{"use strict";var VE=qp(),_E=ru();jp.exports=function(a){var e=VE(a,"string");return _E(e)?e:e+""}});var Ds=m((nV,Qp)=>{"use strict";var OE=se(),Hp=Oe(),du=OE.document,FE=Hp(du)&&Hp(du.createElement);Qp.exports=function(a){return FE?du.createElement(a):{}}});var pu=m((oV,Gp)=>{"use strict";var NE=Ve(),UE=me(),qE=Ds();Gp.exports=!NE&&!UE(function(){return Object.defineProperty(qE("div"),"a",{get:function(){return 7}}).a!==7})});var Yp=m(zp=>{"use strict";var jE=Ve(),HE=_e(),QE=Yo(),GE=Cr(),WE=ri(),zE=cu(),YE=tt(),KE=pu(),Wp=Object.getOwnPropertyDescriptor;zp.f=jE?Wp:function(e,t){if(e=WE(e),t=zE(t),KE)try{return Wp(e,t)}catch{}if(YE(e,t))return GE(!HE(QE.f,e,t),e[t])}});var hu=m((lV,Kp)=>{"use strict";var XE=me(),JE=re(),ZE=/#|\.prototype\./,Fr=function(a,e){var t=tx[ex(a)];return t===rx?!0:t===ix?!1:JE(e)?XE(e):!!e},ex=Fr.normalize=function(a){return String(a).replace(ZE,".").toLowerCase()},tx=Fr.data={},ix=Fr.NATIVE="N",rx=Fr.POLYFILL="P";Kp.exports=Fr});var _i=m((cV,Jp)=>{"use strict";var Xp=Wo(),ax=dt(),sx=Dr(),nx=Xp(Xp.bind);Jp.exports=function(a,e){return ax(a),e===void 0?a:sx?nx(a,e):function(){return a.apply(e,arguments)}}});var fu=m((dV,Zp)=>{"use strict";var ox=Ve(),ux=me();Zp.exports=ox&&ux(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var pt=m((pV,eh)=>{"use strict";var lx=Oe(),cx=String,dx=TypeError;eh.exports=function(a){if(lx(a))return a;throw new dx(cx(a)+" is not an object")}});var si=m(ih=>{"use strict";var px=Ve(),hx=pu(),fx=fu(),Cs=pt(),th=cu(),mx=TypeError,mu=Object.defineProperty,bx=Object.getOwnPropertyDescriptor,bu="enumerable",gu="configurable",Su="writable";ih.f=px?fx?function(e,t,i){if(Cs(e),t=th(t),Cs(i),typeof e=="function"&&t==="prototype"&&"value"in i&&Su in i&&!i[Su]){var r=bx(e,t);r&&r[Su]&&(e[t]=i.value,i={configurable:gu in i?i[gu]:r[gu],enumerable:bu in i?i[bu]:r[bu],writable:!1})}return mu(e,t,i)}:mu:function(e,t,i){if(Cs(e),t=th(t),Cs(i),hx)try{return mu(e,t,i)}catch{}if("get"in i||"set"in i)throw new mx("Accessors not supported");return"value"in i&&(e[t]=i.value),e}});var Oi=m((fV,rh)=>{"use strict";var gx=Ve(),Sx=si(),vx=Cr();rh.exports=gx?function(a,e,t){return Sx.f(a,e,vx(1,t))}:function(a,e,t){return a[e]=t,a}});var ne=m((mV,sh)=>{"use strict";var Nr=se(),yx=Qo(),Tx=Wo(),Ix=re(),Ex=Yp().f,xx=hu(),Fi=Ci(),wx=_i(),Ni=Oi(),ah=tt();Or();var Ax=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 yx(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?Nr:r?Nr[t]:Nr[t]&&Nr[t].prototype,o=i?Fi:Fi[t]||Ni(Fi,t,{})[t],u=o.prototype,l,c,d,p,h,f,b,g,S;for(p in e)l=xx(i?p:t+(r?".":"#")+p,a.forced),c=!l&&n&&ah(n,p),f=o[p],c&&(a.dontCallGetSet?(S=Ex(n,p),b=S&&S.value):b=n[p]),h=c&&b?b:e[p],!(!l&&!s&&typeof f==typeof h)&&(a.bind&&c?g=wx(h,Nr):a.wrap&&c?g=Ax(h):s&&Ix(h)?g=Tx(h):g=h,(a.sham||h&&h.sham||f&&f.sham)&&Ni(g,"sham",!0),Ni(o,p,g),s&&(d=t+"Prototype",ah(Fi,d)||Ni(Fi,d,{}),Ni(Fi[d],p,h),a.real&&u&&(l||!u[p])&&Ni(u,p,h)))}});var oh=m((bV,nh)=>{"use strict";var kx=Math.ceil,Px=Math.floor;nh.exports=Math.trunc||function(e){var t=+e;return(t>0?Px:kx)(t)}});var Ur=m((gV,uh)=>{"use strict";var Rx=oh();uh.exports=function(a){var e=+a;return e!==e||e===0?0:Rx(e)}});var ch=m((SV,lh)=>{"use strict";var Lx=Ur(),$x=Math.max,Mx=Math.min;lh.exports=function(a,e){var t=Lx(a);return t<0?$x(t+e,0):Mx(t,e)}});var vu=m((vV,dh)=>{"use strict";var Dx=Ur(),Cx=Math.min;dh.exports=function(a){var e=Dx(a);return e>0?Cx(e,9007199254740991):0}});var Ui=m((yV,ph)=>{"use strict";var Bx=vu();ph.exports=function(a){return Bx(a.length)}});var yu=m((TV,fh)=>{"use strict";var Vx=ri(),_x=ch(),Ox=Ui(),hh=function(a){return function(e,t,i){var r=Vx(e),s=Ox(r);if(s===0)return!a&&-1;var n=_x(i,s),o;if(a&&t!==t){for(;s>n;)if(o=r[n++],o!==o)return!0}else for(;s>n;n++)if((a||n in r)&&r[n]===t)return a||n||0;return!a&&-1}};fh.exports={includes:hh(!0),indexOf:hh(!1)}});var qr=m((IV,mh)=>{"use strict";mh.exports=function(){}});var bh=m(()=>{"use strict";var Fx=ne(),Nx=yu().includes,Ux=me(),qx=qr(),jx=Ux(function(){return!Array(1).includes()});Fx({target:"Array",proto:!0,forced:jx},{includes:function(e){return Nx(this,e,arguments.length>1?arguments[1]:void 0)}});qx("includes")});var Ft=m((wV,gh)=>{"use strict";var Hx=xt();gh.exports=Hx});var vh=m((AV,Sh)=>{"use strict";bh();var Qx=Ft();Sh.exports=Qx("Array","includes")});var Th=m((kV,yh)=>{"use strict";var Gx=vh();yh.exports=Gx});var Ge=m((PV,Ih)=>{"use strict";var Wx=Th();Ih.exports=Wx});var _s=m((NV,Lh)=>{"use strict";var tw=ou(),iw=uu(),Rh=tw("keys");Lh.exports=function(a){return Rh[a]||(Rh[a]=iw(a))}});var Mh=m((UV,$h)=>{"use strict";var rw=me();$h.exports=!rw(function(){function a(){}return a.prototype.constructor=null,Object.getPrototypeOf(new a)!==a.prototype})});var Os=m((qV,Ch)=>{"use strict";var aw=tt(),sw=re(),nw=Bi(),ow=_s(),uw=Mh(),Dh=ow("IE_PROTO"),Eu=Object,lw=Eu.prototype;Ch.exports=uw?Eu.getPrototypeOf:function(a){var e=nw(a);if(aw(e,Dh))return e[Dh];var t=e.constructor;return sw(t)&&e instanceof t?t.prototype:e instanceof Eu?lw:null}});var Fs=m((jV,Bh)=>{"use strict";Bh.exports={}});var Oh=m((HV,_h)=>{"use strict";var cw=le(),xu=tt(),dw=ri(),pw=yu().indexOf,hw=Fs(),Vh=cw([].push);_h.exports=function(a,e){var t=dw(a),i=0,r=[],s;for(s in t)!xu(hw,s)&&xu(t,s)&&Vh(r,s);for(;e.length>i;)xu(t,s=e[i++])&&(~pw(r,s)||Vh(r,s));return r}});var wu=m((QV,Fh)=>{"use strict";Fh.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var Au=m((GV,Nh)=>{"use strict";var fw=Oh(),mw=wu();Nh.exports=Object.keys||function(e){return fw(e,mw)}});var ku=m((WV,Qh)=>{"use strict";var qh=Ve(),bw=me(),jh=le(),gw=Os(),Sw=Au(),vw=ri(),yw=Yo().f,Hh=jh(yw),Tw=jh([].push),Iw=qh&&bw(function(){var a=Object.create(null);return a[2]=2,!Hh(a,2)}),Uh=function(a){return function(e){for(var t=vw(e),i=Sw(t),r=Iw&&gw(t)===null,s=i.length,n=0,o=[],u;s>n;)u=i[n++],(!qh||(r?u in t:Hh(t,u)))&&Tw(o,a?[u,t[u]]:t[u]);return o}};Qh.exports={entries:Uh(!0),values:Uh(!1)}});var Gh=m(()=>{"use strict";var Ew=ne(),xw=ku().entries;Ew({target:"Object",stat:!0},{entries:function(e){return xw(e)}})});var zh=m((KV,Wh)=>{"use strict";Gh();var ww=Ci();Wh.exports=ww.Object.entries});var Kh=m((XV,Yh)=>{"use strict";var Aw=zh();Yh.exports=Aw});var qi=m((JV,Xh)=>{"use strict";var kw=Kh();Xh.exports=kw});var ni=m((ZV,Jh)=>{"use strict";Jh.exports={}});var tf=m((e_,ef)=>{"use strict";var Pw=se(),Rw=re(),Zh=Pw.WeakMap;ef.exports=Rw(Zh)&&/native code/.test(String(Zh))});var $u=m((t_,sf)=>{"use strict";var Lw=tf(),af=se(),$w=Oe(),Mw=Oi(),Pu=tt(),Ru=Or(),Dw=_s(),Cw=Fs(),rf="Object already initialized",Lu=af.TypeError,Bw=af.WeakMap,Ns,jr,Us,Vw=function(a){return Us(a)?jr(a):Ns(a,{})},_w=function(a){return function(e){var t;if(!$w(e)||(t=jr(e)).type!==a)throw new Lu("Incompatible receiver, "+a+" required");return t}};Lw||Ru.state?(it=Ru.state||(Ru.state=new Bw),it.get=it.get,it.has=it.has,it.set=it.set,Ns=function(a,e){if(it.has(a))throw new Lu(rf);return e.facade=a,it.set(a,e),e},jr=function(a){return it.get(a)||{}},Us=function(a){return it.has(a)}):(oi=Dw("state"),Cw[oi]=!0,Ns=function(a,e){if(Pu(a,oi))throw new Lu(rf);return e.facade=a,Mw(a,oi,e),e},jr=function(a){return Pu(a,oi)?a[oi]:{}},Us=function(a){return Pu(a,oi)});var it,oi;sf.exports={set:Ns,get:jr,has:Us,enforce:Vw,getterFor:_w}});var Cu=m((i_,of)=>{"use strict";var Mu=Ve(),Ow=tt(),nf=Function.prototype,Fw=Mu&&Object.getOwnPropertyDescriptor,Du=Ow(nf,"name"),Nw=Du&&function(){}.name==="something",Uw=Du&&(!Mu||Mu&&Fw(nf,"name").configurable);of.exports={EXISTS:Du,PROPER:Nw,CONFIGURABLE:Uw}});var lf=m(uf=>{"use strict";var qw=Ve(),jw=fu(),Hw=si(),Qw=pt(),Gw=ri(),Ww=Au();uf.f=qw&&!jw?Object.defineProperties:function(e,t){Qw(e);for(var i=Gw(t),r=Ww(t),s=r.length,n=0,o;s>n;)Hw.f(e,o=r[n++],i[o]);return e}});var Bu=m((a_,cf)=>{"use strict";var zw=xt();cf.exports=zw("document","documentElement")});var Fu=m((s_,gf)=>{"use strict";var Yw=pt(),Kw=lf(),df=wu(),Xw=Fs(),Jw=Bu(),Zw=Ds(),eA=_s(),pf=">",hf="<",_u="prototype",Ou="script",mf=eA("IE_PROTO"),Vu=function(){},bf=function(a){return hf+Ou+pf+a+hf+"/"+Ou+pf},ff=function(a){a.write(bf("")),a.close();var e=a.parentWindow.Object;return a=null,e},tA=function(){var a=Zw("iframe"),e="java"+Ou+":",t;return a.style.display="none",Jw.appendChild(a),a.src=String(e),t=a.contentWindow.document,t.open(),t.write(bf("document.F=Object")),t.close(),t.F},qs,js=function(){try{qs=new ActiveXObject("htmlfile")}catch{}js=typeof document<"u"?document.domain&&qs?ff(qs):tA():ff(qs);for(var a=df.length;a--;)delete js[_u][df[a]];return js()};Xw[mf]=!0;gf.exports=Object.create||function(e,t){var i;return e!==null?(Vu[_u]=Yw(e),i=new Vu,Vu[_u]=null,i[mf]=e):i=js(),t===void 0?i:Kw.f(i,t)}});var ji=m((n_,Sf)=>{"use strict";var iA=Oi();Sf.exports=function(a,e,t,i){return i&&i.enumerable?a[e]=t:iA(a,e,t),a}});var ju=m((o_,Tf)=>{"use strict";var rA=me(),aA=re(),sA=Oe(),nA=Fu(),vf=Os(),oA=ji(),uA=be(),lA=et(),qu=uA("iterator"),yf=!1,wt,Nu,Uu;[].keys&&(Uu=[].keys(),"next"in Uu?(Nu=vf(vf(Uu)),Nu!==Object.prototype&&(wt=Nu)):yf=!0);var cA=!sA(wt)||rA(function(){var a={};return wt[qu].call(a)!==a});cA?wt={}:lA&&(wt=nA(wt));aA(wt[qu])||oA(wt,qu,function(){return this});Tf.exports={IteratorPrototype:wt,BUGGY_SAFARI_ITERATORS:yf}});var Hs=m((u_,Ef)=>{"use strict";var dA=be(),pA=dA("toStringTag"),If={};If[pA]="z";Ef.exports=String(If)==="[object z]"});var Hr=m((l_,xf)=>{"use strict";var hA=Hs(),fA=re(),Qs=ii(),mA=be(),bA=mA("toStringTag"),gA=Object,SA=Qs(function(){return arguments}())==="Arguments",vA=function(a,e){try{return a[e]}catch{}};xf.exports=hA?Qs:function(a){var e,t,i;return a===void 0?"Undefined":a===null?"Null":typeof(t=vA(e=gA(a),bA))=="string"?t:SA?Qs(e):(i=Qs(e))==="Object"&&fA(e.callee)?"Arguments":i}});var Af=m((c_,wf)=>{"use strict";var yA=Hs(),TA=Hr();wf.exports=yA?{}.toString:function(){return"[object "+TA(this)+"]"}});var Qr=m((d_,Pf)=>{"use strict";var IA=Hs(),EA=si().f,xA=Oi(),wA=tt(),AA=Af(),kA=be(),kf=kA("toStringTag");Pf.exports=function(a,e,t,i){var r=t?a:a&&a.prototype;r&&(wA(r,kf)||EA(r,kf,{configurable:!0,value:e}),i&&!IA&&xA(r,"toString",AA))}});var Lf=m((p_,Rf)=>{"use strict";var PA=ju().IteratorPrototype,RA=Fu(),LA=Cr(),$A=Qr(),MA=ni(),DA=function(){return this};Rf.exports=function(a,e,t,i){var r=e+" Iterator";return a.prototype=RA(PA,{next:LA(+!i,t)}),$A(a,r,!1,!0),MA[r]=DA,a}});var Mf=m((h_,$f)=>{"use strict";var CA=le(),BA=dt();$f.exports=function(a,e,t){try{return CA(BA(Object.getOwnPropertyDescriptor(a,e)[t]))}catch{}}});var Cf=m((f_,Df)=>{"use strict";var VA=Oe();Df.exports=function(a){return VA(a)||a===null}});var Vf=m((m_,Bf)=>{"use strict";var _A=Cf(),OA=String,FA=TypeError;Bf.exports=function(a){if(_A(a))return a;throw new FA("Can't set "+OA(a)+" as a prototype")}});var Hu=m((b_,_f)=>{"use strict";var NA=Mf(),UA=Oe(),qA=Ot(),jA=Vf();_f.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var a=!1,e={},t;try{t=NA(Object.prototype,"__proto__","set"),t(e,[]),a=e instanceof Array}catch{}return function(r,s){return qA(r),jA(s),UA(r)&&(a?t(r,s):r.__proto__=s),r}}():void 0)});var zf=m((g_,Wf)=>{"use strict";var HA=ne(),QA=_e(),Gs=et(),Qf=Cu(),GA=re(),WA=Lf(),Of=Os(),Ff=Hu(),zA=Qr(),YA=Oi(),Qu=ji(),KA=be(),Nf=ni(),Gf=ju(),XA=Qf.PROPER,JA=Qf.CONFIGURABLE,Uf=Gf.IteratorPrototype,Ws=Gf.BUGGY_SAFARI_ITERATORS,Gr=KA("iterator"),qf="keys",Wr="values",jf="entries",Hf=function(){return this};Wf.exports=function(a,e,t,i,r,s,n){WA(t,e,i);var o=function(S){if(S===r&&p)return p;if(!Ws&&S&&S in c)return c[S];switch(S){case qf:return function(){return new t(this,S)};case Wr:return function(){return new t(this,S)};case jf:return function(){return new t(this,S)}}return function(){return new t(this)}},u=e+" Iterator",l=!1,c=a.prototype,d=c[Gr]||c["@@iterator"]||r&&c[r],p=!Ws&&d||o(r),h=e==="Array"&&c.entries||d,f,b,g;if(h&&(f=Of(h.call(new a)),f!==Object.prototype&&f.next&&(!Gs&&Of(f)!==Uf&&(Ff?Ff(f,Uf):GA(f[Gr])||Qu(f,Gr,Hf)),zA(f,u,!0,!0),Gs&&(Nf[u]=Hf))),XA&&r===Wr&&d&&d.name!==Wr&&(!Gs&&JA?YA(c,"name",Wr):(l=!0,p=function(){return QA(d,this)})),r)if(b={values:o(Wr),keys:s?p:o(qf),entries:o(jf)},n)for(g in b)(Ws||l||!(g in c))&&Qu(c,g,b[g]);else HA({target:e,proto:!0,forced:Ws||l},b);return(!Gs||n)&&c[Gr]!==p&&Qu(c,Gr,p,{name:r}),Nf[e]=p,b}});var Kf=m((S_,Yf)=>{"use strict";Yf.exports=function(a,e){return{value:a,done:e}}});var Wu=m((v_,tm)=>{"use strict";var ZA=ri(),Gu=qr(),Xf=ni(),Zf=$u(),ek=si().f,tk=zf(),zs=Kf(),ik=et(),rk=Ve(),em="Array Iterator",ak=Zf.set,sk=Zf.getterFor(em);tm.exports=tk(Array,"Array",function(a,e){ak(this,{type:em,target:ZA(a),index:0,kind:e})},function(){var a=sk(this),e=a.target,t=a.index++;if(!e||t>=e.length)return a.target=void 0,zs(void 0,!0);switch(a.kind){case"keys":return zs(t,!1);case"values":return zs(e[t],!1)}return zs([t,e[t]],!1)},"values");var Jf=Xf.Arguments=Xf.Array;Gu("keys");Gu("values");Gu("entries");if(!ik&&rk&&Jf.name!=="values")try{ek(Jf,"name",{value:"values"})}catch{}});var rm=m((y_,im)=>{"use strict";var nk=be(),ok=ni(),uk=nk("iterator"),lk=Array.prototype;im.exports=function(a){return a!==void 0&&(ok.Array===a||lk[uk]===a)}});var zu=m((T_,sm)=>{"use strict";var ck=Hr(),am=_r(),dk=Di(),pk=ni(),hk=be(),fk=hk("iterator");sm.exports=function(a){if(!dk(a))return am(a,fk)||am(a,"@@iterator")||pk[ck(a)]}});var om=m((I_,nm)=>{"use strict";var mk=_e(),bk=dt(),gk=pt(),Sk=Vr(),vk=zu(),yk=TypeError;nm.exports=function(a,e){var t=arguments.length<2?vk(a):e;if(bk(t))return gk(mk(t,a));throw new yk(Sk(a)+" is not iterable")}});var cm=m((E_,lm)=>{"use strict";var Tk=_e(),um=pt(),Ik=_r();lm.exports=function(a,e,t){var i,r;um(a);try{if(i=Ik(a,"return"),!i){if(e==="throw")throw t;return t}i=Tk(i,a)}catch(s){r=!0,i=s}if(e==="throw")throw t;if(r)throw i;return um(i),t}});var Ks=m((x_,fm)=>{"use strict";var Ek=_i(),xk=_e(),wk=pt(),Ak=Vr(),kk=rm(),Pk=Ui(),dm=Br(),Rk=om(),Lk=zu(),pm=cm(),$k=TypeError,Ys=function(a,e){this.stopped=a,this.result=e},hm=Ys.prototype;fm.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),o=!!(t&&t.INTERRUPTED),u=Ek(e,i),l,c,d,p,h,f,b,g=function(T){return l&&pm(l,"normal",T),new Ys(!0,T)},S=function(T){return r?(wk(T),o?u(T[0],T[1],g):u(T[0],T[1])):o?u(T,g):u(T)};if(s)l=a.iterator;else if(n)l=a;else{if(c=Lk(a),!c)throw new $k(Ak(a)+" is not iterable");if(kk(c)){for(d=0,p=Pk(a);p>d;d++)if(h=S(a[d]),h&&dm(hm,h))return h;return new Ys(!1)}l=Rk(a,c)}for(f=s?a.next:l.next;!(b=xk(f,l)).done;){try{h=S(b.value)}catch(T){pm(l,"throw",T)}if(typeof h=="object"&&h&&dm(hm,h))return h}return new Ys(!1)}});var bm=m((w_,mm)=>{"use strict";var Mk=Ve(),Dk=si(),Ck=Cr();mm.exports=function(a,e,t){Mk?Dk.f(a,e,Ck(0,t)):a[e]=t}});var gm=m(()=>{"use strict";var Bk=ne(),Vk=Ks(),_k=bm();Bk({target:"Object",stat:!0},{fromEntries:function(e){var t={};return Vk(e,function(i,r){_k(t,i,r)},{AS_ENTRIES:!0}),t}})});var vm=m((P_,Sm)=>{"use strict";Wu();gm();var Ok=Ci();Sm.exports=Ok.Object.fromEntries});var Tm=m((R_,ym)=>{"use strict";ym.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 Em=m(()=>{"use strict";Wu();var Fk=Tm(),Nk=se(),Uk=Qr(),Im=ni();for(Xs in Fk)Uk(Nk[Xs],Xs),Im[Xs]=Im.Array;var Xs});var wm=m((M_,xm)=>{"use strict";var qk=vm();Em();xm.exports=qk});var Yu=m((D_,Am)=>{"use strict";var jk=wm();Am.exports=jk});var km=m(()=>{"use strict"});var Ku=m((V_,Pm)=>{"use strict";var zr=se(),Hk=ai(),Qk=ii(),Js=function(a){return Hk.slice(0,a.length)===a};Pm.exports=function(){return Js("Bun/")?"BUN":Js("Cloudflare-Workers")?"CLOUDFLARE":Js("Deno/")?"DENO":Js("Node.js/")?"NODE":zr.Bun&&typeof Bun.version=="string"?"BUN":zr.Deno&&typeof Deno.version=="object"?"DENO":Qk(zr.process)==="process"?"NODE":zr.window&&zr.document?"BROWSER":"REST"}()});var Zs=m((__,Rm)=>{"use strict";var Gk=Ku();Rm.exports=Gk==="NODE"});var $m=m((O_,Lm)=>{"use strict";var Wk=si();Lm.exports=function(a,e,t){return Wk.f(a,e,t)}});var Cm=m((F_,Dm)=>{"use strict";var zk=xt(),Yk=$m(),Kk=be(),Xk=Ve(),Mm=Kk("species");Dm.exports=function(a){var e=zk(a);Xk&&e&&!e[Mm]&&Yk(e,Mm,{configurable:!0,get:function(){return this}})}});var Vm=m((N_,Bm)=>{"use strict";var Jk=Br(),Zk=TypeError;Bm.exports=function(a,e){if(Jk(e,a))return a;throw new Zk("Incorrect invocation")}});var Ju=m((U_,_m)=>{"use strict";var eP=le(),tP=re(),Xu=Or(),iP=eP(Function.toString);tP(Xu.inspectSource)||(Xu.inspectSource=function(a){return iP(a)});_m.exports=Xu.inspectSource});var el=m((q_,qm)=>{"use strict";var rP=le(),aP=me(),Om=re(),sP=Hr(),nP=xt(),oP=Ju(),Fm=function(){},Nm=nP("Reflect","construct"),Zu=/^\s*(?:class|function)\b/,uP=rP(Zu.exec),lP=!Zu.test(Fm),Yr=function(e){if(!Om(e))return!1;try{return Nm(Fm,[],e),!0}catch{return!1}},Um=function(e){if(!Om(e))return!1;switch(sP(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return lP||!!uP(Zu,oP(e))}catch{return!0}};Um.sham=!0;qm.exports=!Nm||aP(function(){var a;return Yr(Yr.call)||!Yr(Object)||!Yr(function(){a=!0})||a})?Um:Yr});var Hm=m((j_,jm)=>{"use strict";var cP=el(),dP=Vr(),pP=TypeError;jm.exports=function(a){if(cP(a))return a;throw new pP(dP(a)+" is not a constructor")}});var tl=m((H_,Gm)=>{"use strict";var Qm=pt(),hP=Hm(),fP=Di(),mP=be(),bP=mP("species");Gm.exports=function(a,e){var t=Qm(a).constructor,i;return t===void 0||fP(i=Qm(t)[bP])?e:hP(i)}});var zm=m((Q_,Wm)=>{"use strict";var gP=le();Wm.exports=gP([].slice)});var Km=m((G_,Ym)=>{"use strict";var SP=TypeError;Ym.exports=function(a,e){if(a<e)throw new SP("Not enough arguments");return a}});var il=m((W_,Xm)=>{"use strict";var vP=ai();Xm.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(vP)});var dl=m((z_,nb)=>{"use strict";var Fe=se(),yP=Qo(),TP=_i(),Jm=re(),IP=tt(),sb=me(),Zm=Bu(),EP=zm(),eb=Ds(),xP=Km(),wP=il(),AP=Zs(),ul=Fe.setImmediate,ll=Fe.clearImmediate,kP=Fe.process,rl=Fe.Dispatch,PP=Fe.Function,tb=Fe.MessageChannel,RP=Fe.String,al=0,Kr={},ib="onreadystatechange",Xr,ui,sl,nl;sb(function(){Xr=Fe.location});var cl=function(a){if(IP(Kr,a)){var e=Kr[a];delete Kr[a],e()}},ol=function(a){return function(){cl(a)}},rb=function(a){cl(a.data)},ab=function(a){Fe.postMessage(RP(a),Xr.protocol+"//"+Xr.host)};(!ul||!ll)&&(ul=function(e){xP(arguments.length,1);var t=Jm(e)?e:PP(e),i=EP(arguments,1);return Kr[++al]=function(){yP(t,void 0,i)},ui(al),al},ll=function(e){delete Kr[e]},AP?ui=function(a){kP.nextTick(ol(a))}:rl&&rl.now?ui=function(a){rl.now(ol(a))}:tb&&!wP?(sl=new tb,nl=sl.port2,sl.port1.onmessage=rb,ui=TP(nl.postMessage,nl)):Fe.addEventListener&&Jm(Fe.postMessage)&&!Fe.importScripts&&Xr&&Xr.protocol!=="file:"&&!sb(ab)?(ui=ab,Fe.addEventListener("message",rb,!1)):ib in eb("script")?ui=function(a){Zm.appendChild(eb("script"))[ib]=function(){Zm.removeChild(this),cl(a)}}:ui=function(a){setTimeout(ol(a),0)});nb.exports={set:ul,clear:ll}});var lb=m((Y_,ub)=>{"use strict";var ob=se(),LP=Ve(),$P=Object.getOwnPropertyDescriptor;ub.exports=function(a){if(!LP)return ob[a];var e=$P(ob,a);return e&&e.value}});var pl=m((K_,db)=>{"use strict";var cb=function(){this.head=null,this.tail=null};cb.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}}};db.exports=cb});var hb=m((X_,pb)=>{"use strict";var MP=ai();pb.exports=/ipad|iphone|ipod/i.test(MP)&&typeof Pebble<"u"});var mb=m((J_,fb)=>{"use strict";var DP=ai();fb.exports=/web0s(?!.*chrome)/i.test(DP)});var Ib=m((Z_,Tb)=>{"use strict";var Qi=se(),CP=lb(),bb=_i(),hl=dl().set,BP=pl(),VP=il(),_P=hb(),OP=mb(),fl=Zs(),gb=Qi.MutationObserver||Qi.WebKitMutationObserver,Sb=Qi.document,vb=Qi.process,en=Qi.Promise,gl=CP("queueMicrotask"),Hi,ml,bl,tn,yb;gl||(Jr=new BP,Zr=function(){var a,e;for(fl&&(a=vb.domain)&&a.exit();e=Jr.get();)try{e()}catch(t){throw Jr.head&&Hi(),t}a&&a.enter()},!VP&&!fl&&!OP&&gb&&Sb?(ml=!0,bl=Sb.createTextNode(""),new gb(Zr).observe(bl,{characterData:!0}),Hi=function(){bl.data=ml=!ml}):!_P&&en&&en.resolve?(tn=en.resolve(void 0),tn.constructor=en,yb=bb(tn.then,tn),Hi=function(){yb(Zr)}):fl?Hi=function(){vb.nextTick(Zr)}:(hl=bb(hl,Qi),Hi=function(){hl(Zr)}),gl=function(a){Jr.head||Hi(),Jr.add(a)});var Jr,Zr;Tb.exports=gl});var xb=m((eO,Eb)=>{"use strict";Eb.exports=function(a,e){try{arguments.length===1?console.error(a):console.error(a,e)}catch{}}});var rn=m((tO,wb)=>{"use strict";wb.exports=function(a){try{return{error:!1,value:a()}}catch(e){return{error:!0,value:e}}}});var li=m((iO,Ab)=>{"use strict";var FP=se();Ab.exports=FP.Promise});var Gi=m((rO,Lb)=>{"use strict";var NP=se(),ea=li(),UP=re(),qP=hu(),jP=Ju(),HP=be(),kb=Ku(),QP=et(),Sl=eu(),Pb=ea&&ea.prototype,GP=HP("species"),vl=!1,Rb=UP(NP.PromiseRejectionEvent),WP=qP("Promise",function(){var a=jP(ea),e=a!==String(ea);if(!e&&Sl===66||QP&&!(Pb.catch&&Pb.finally))return!0;if(!Sl||Sl<51||!/native code/.test(a)){var t=new ea(function(s){s(1)}),i=function(s){s(function(){},function(){})},r=t.constructor={};if(r[GP]=i,vl=t.then(function(){})instanceof i,!vl)return!0}return!e&&(kb==="BROWSER"||kb==="DENO")&&!Rb});Lb.exports={CONSTRUCTOR:WP,REJECTION_EVENT:Rb,SUBCLASSING:vl}});var Wi=m((aO,Mb)=>{"use strict";var $b=dt(),zP=TypeError,YP=function(a){var e,t;this.promise=new a(function(i,r){if(e!==void 0||t!==void 0)throw new zP("Bad Promise constructor");e=i,t=r}),this.resolve=$b(e),this.reject=$b(t)};Mb.exports.f=function(a){return new YP(a)}});var Xb=m(()=>{"use strict";var KP=ne(),XP=et(),on=Zs(),Nt=se(),Xi=_e(),Db=ji(),Cb=Hu(),JP=Qr(),ZP=Cm(),eR=dt(),nn=re(),tR=Oe(),iR=Vm(),rR=tl(),Fb=dl().set,xl=Ib(),aR=xb(),sR=rn(),nR=pl(),Nb=$u(),un=li(),wl=Gi(),Ub=Wi(),ln="Promise",qb=wl.CONSTRUCTOR,oR=wl.REJECTION_EVENT,uR=wl.SUBCLASSING,yl=Nb.getterFor(ln),lR=Nb.set,zi=un&&un.prototype,ci=un,an=zi,jb=Nt.TypeError,Tl=Nt.document,Al=Nt.process,Il=Ub.f,cR=Il,dR=!!(Tl&&Tl.createEvent&&Nt.dispatchEvent),Hb="unhandledrejection",pR="rejectionhandled",Bb=0,Qb=1,hR=2,kl=1,Gb=2,sn,Vb,fR,_b,Wb=function(a){var e;return tR(a)&&nn(e=a.then)?e:!1},zb=function(a,e){var t=e.value,i=e.state===Qb,r=i?a.ok:a.fail,s=a.resolve,n=a.reject,o=a.domain,u,l,c;try{r?(i||(e.rejection===Gb&&bR(e),e.rejection=kl),r===!0?u=t:(o&&o.enter(),u=r(t),o&&(o.exit(),c=!0)),u===a.promise?n(new jb("Promise-chain cycle")):(l=Wb(u))?Xi(l,u,s,n):s(u)):n(t)}catch(d){o&&!c&&o.exit(),n(d)}},Yb=function(a,e){a.notified||(a.notified=!0,xl(function(){for(var t=a.reactions,i;i=t.get();)zb(i,a);a.notified=!1,e&&!a.rejection&&mR(a)}))},Kb=function(a,e,t){var i,r;dR?(i=Tl.createEvent("Event"),i.promise=e,i.reason=t,i.initEvent(a,!1,!0),Nt.dispatchEvent(i)):i={promise:e,reason:t},!oR&&(r=Nt["on"+a])?r(i):a===Hb&&aR("Unhandled promise rejection",t)},mR=function(a){Xi(Fb,Nt,function(){var e=a.facade,t=a.value,i=Ob(a),r;if(i&&(r=sR(function(){on?Al.emit("unhandledRejection",t,e):Kb(Hb,e,t)}),a.rejection=on||Ob(a)?Gb:kl,r.error))throw r.value})},Ob=function(a){return a.rejection!==kl&&!a.parent},bR=function(a){Xi(Fb,Nt,function(){var e=a.facade;on?Al.emit("rejectionHandled",e):Kb(pR,e,a.value)})},Yi=function(a,e,t){return function(i){a(e,i,t)}},Ki=function(a,e,t){a.done||(a.done=!0,t&&(a=t),a.value=e,a.state=hR,Yb(a,!0))},El=function(a,e,t){if(!a.done){a.done=!0,t&&(a=t);try{if(a.facade===e)throw new jb("Promise can't be resolved itself");var i=Wb(e);i?xl(function(){var r={done:!1};try{Xi(i,e,Yi(El,r,a),Yi(Ki,r,a))}catch(s){Ki(r,s,a)}}):(a.value=e,a.state=Qb,Yb(a,!1))}catch(r){Ki({done:!1},r,a)}}};if(qb&&(ci=function(e){iR(this,an),eR(e),Xi(sn,this);var t=yl(this);try{e(Yi(El,t),Yi(Ki,t))}catch(i){Ki(t,i)}},an=ci.prototype,sn=function(e){lR(this,{type:ln,done:!1,notified:!1,parent:!1,reactions:new nR,rejection:!1,state:Bb,value:void 0})},sn.prototype=Db(an,"then",function(e,t){var i=yl(this),r=Il(rR(this,ci));return i.parent=!0,r.ok=nn(e)?e:!0,r.fail=nn(t)&&t,r.domain=on?Al.domain:void 0,i.state===Bb?i.reactions.add(r):xl(function(){zb(r,i)}),r.promise}),Vb=function(){var a=new sn,e=yl(a);this.promise=a,this.resolve=Yi(El,e),this.reject=Yi(Ki,e)},Ub.f=Il=function(a){return a===ci||a===fR?new Vb(a):cR(a)},!XP&&nn(un)&&zi!==Object.prototype)){_b=zi.then,uR||Db(zi,"then",function(e,t){var i=this;return new ci(function(r,s){Xi(_b,i,r,s)}).then(e,t)},{unsafe:!0});try{delete zi.constructor}catch{}Cb&&Cb(zi,an)}KP({global:!0,constructor:!0,wrap:!0,forced:qb},{Promise:ci});JP(ci,ln,!1,!0);ZP(ln)});var ig=m((oO,tg)=>{"use strict";var gR=be(),Zb=gR("iterator"),eg=!1;try{Jb=0,Pl={next:function(){return{done:!!Jb++}},return:function(){eg=!0}},Pl[Zb]=function(){return this},Array.from(Pl,function(){throw 2})}catch{}var Jb,Pl;tg.exports=function(a,e){try{if(!e&&!eg)return!1}catch{return!1}var t=!1;try{var i={};i[Zb]=function(){return{next:function(){return{done:t=!0}}}},a(i)}catch{}return t}});var Rl=m((uO,rg)=>{"use strict";var SR=li(),vR=ig(),yR=Gi().CONSTRUCTOR;rg.exports=yR||!vR(function(a){SR.all(a).then(void 0,function(){})})});var ag=m(()=>{"use strict";var TR=ne(),IR=_e(),ER=dt(),xR=Wi(),wR=rn(),AR=Ks(),kR=Rl();TR({target:"Promise",stat:!0,forced:kR},{all:function(e){var t=this,i=xR.f(t),r=i.resolve,s=i.reject,n=wR(function(){var o=ER(t.resolve),u=[],l=0,c=1;AR(e,function(d){var p=l++,h=!1;c++,IR(o,t,d).then(function(f){h||(h=!0,u[p]=f,--c||r(u))},s)}),--c||r(u)});return n.error&&s(n.value),i.promise}})});var ng=m(()=>{"use strict";var PR=ne(),RR=et(),LR=Gi().CONSTRUCTOR,$l=li(),$R=xt(),MR=re(),DR=ji(),sg=$l&&$l.prototype;PR({target:"Promise",proto:!0,forced:LR,real:!0},{catch:function(a){return this.then(void 0,a)}});!RR&&MR($l)&&(Ll=$R("Promise").prototype.catch,sg.catch!==Ll&&DR(sg,"catch",Ll,{unsafe:!0}));var Ll});var og=m(()=>{"use strict";var CR=ne(),BR=_e(),VR=dt(),_R=Wi(),OR=rn(),FR=Ks(),NR=Rl();CR({target:"Promise",stat:!0,forced:NR},{race:function(e){var t=this,i=_R.f(t),r=i.reject,s=OR(function(){var n=VR(t.resolve);FR(e,function(o){BR(n,t,o).then(i.resolve,r)})});return s.error&&r(s.value),i.promise}})});var ug=m(()=>{"use strict";var UR=ne(),qR=Wi(),jR=Gi().CONSTRUCTOR;UR({target:"Promise",stat:!0,forced:jR},{reject:function(e){var t=qR.f(this),i=t.reject;return i(e),t.promise}})});var Ml=m((gO,lg)=>{"use strict";var HR=pt(),QR=Oe(),GR=Wi();lg.exports=function(a,e){if(HR(a),QR(e)&&e.constructor===a)return e;var t=GR.f(a),i=t.resolve;return i(e),t.promise}});var pg=m(()=>{"use strict";var WR=ne(),zR=xt(),cg=et(),YR=li(),dg=Gi().CONSTRUCTOR,KR=Ml(),XR=zR("Promise"),JR=cg&&!dg;WR({target:"Promise",stat:!0,forced:cg||dg},{resolve:function(e){return KR(JR&&this===XR?YR:this,e)}})});var hg=m(()=>{"use strict";Xb();ag();ng();og();ug();pg()});var gg=m(()=>{"use strict";var ZR=ne(),eL=et(),cn=li(),tL=me(),mg=xt(),bg=re(),iL=tl(),fg=Ml(),rL=ji(),Cl=cn&&cn.prototype,aL=!!cn&&tL(function(){Cl.finally.call({then:function(){}},function(){})});ZR({target:"Promise",proto:!0,real:!0,forced:aL},{finally:function(a){var e=iL(this,mg("Promise")),t=bg(a);return this.then(t?function(i){return fg(e,a()).then(function(){return i})}:a,t?function(i){return fg(e,a()).then(function(){throw i})}:a)}});!eL&&bg(cn)&&(Dl=mg("Promise").prototype.finally,Cl.finally!==Dl&&rL(Cl,"finally",Dl,{unsafe:!0}));var Dl});var vg=m((xO,Sg)=>{"use strict";km();hg();gg();var sL=Ft();Sg.exports=sL("Promise","finally")});var Tg=m((wO,yg)=>{"use strict";var nL=vg();yg.exports=nL});var dn=m((AO,Ig)=>{"use strict";var oL=Tg();Ig.exports=oL});var Bg=m(()=>{"use strict";var TL=ne(),IL=ku().values;TL({target:"Object",stat:!0},{values:function(e){return IL(e)}})});var _g=m((cF,Vg)=>{"use strict";Bg();var EL=Ci();Vg.exports=EL.Object.values});var Fg=m((dF,Og)=>{"use strict";var xL=_g();Og.exports=xL});var Zi=m((pF,Ng)=>{"use strict";var wL=Fg();Ng.exports=wL});var rS=m(()=>{"use strict";var zL=ne(),YL=Bi(),KL=Ui(),XL=Ur(),JL=qr();zL({target:"Array",proto:!0},{at:function(e){var t=YL(this),i=KL(t),r=XL(e),s=r>=0?r:i+r;return s<0||s>=i?void 0:t[s]}});JL("at")});var sS=m((TN,aS)=>{"use strict";rS();var ZL=Ft();aS.exports=ZL("Array","at")});var oS=m((IN,nS)=>{"use strict";var e$=sS();nS.exports=e$});var bt=m((EN,uS)=>{"use strict";var t$=oS();uS.exports=t$});var rc=m((cq,US)=>{"use strict";var B$=ii();US.exports=Array.isArray||function(e){return B$(e)==="Array"}});var jS=m((dq,qS)=>{"use strict";var V$=TypeError,_$=9007199254740991;qS.exports=function(a){if(a>_$)throw V$("Maximum allowed index exceeded");return a}});var GS=m((pq,QS)=>{"use strict";var O$=rc(),F$=Ui(),N$=jS(),U$=_i(),HS=function(a,e,t,i,r,s,n,o){for(var u=r,l=0,c=n?U$(n,o):!1,d,p;l<i;)l in t&&(d=c?c(t[l],l,e):t[l],s>0&&O$(d)?(p=F$(d),u=HS(a,e,d,p,u,s-1)-1):(N$(u+1),a[u]=d),u++),l++;return u};QS.exports=HS});var KS=m((hq,YS)=>{"use strict";var WS=rc(),q$=el(),j$=Oe(),H$=be(),Q$=H$("species"),zS=Array;YS.exports=function(a){var e;return WS(a)&&(e=a.constructor,q$(e)&&(e===zS||WS(e.prototype))?e=void 0:j$(e)&&(e=e[Q$],e===null&&(e=void 0))),e===void 0?zS:e}});var JS=m((fq,XS)=>{"use strict";var G$=KS();XS.exports=function(a,e){return new(G$(a))(e===0?0:e)}});var ZS=m(()=>{"use strict";var W$=ne(),z$=GS(),Y$=dt(),K$=Bi(),X$=Ui(),J$=JS();W$({target:"Array",proto:!0},{flatMap:function(e){var t=K$(this),i=X$(t),r;return Y$(e),r=J$(t,0),r.length=z$(r,t,t,i,0,1,e,arguments.length>1?arguments[1]:void 0),r}})});var ev=m(()=>{"use strict";var Z$=qr();Z$("flatMap")});var iv=m((vq,tv)=>{"use strict";ZS();ev();var eM=Ft();tv.exports=eM("Array","flatMap")});var av=m((yq,rv)=>{"use strict";var tM=iv();rv.exports=tM});var ga=m((Tq,sv)=>{"use strict";var iM=av();sv.exports=iM});var Sa=m((Iq,nv)=>{"use strict";var rM=Hr(),aM=String;nv.exports=function(a){if(rM(a)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return aM(a)}});var ac=m((Eq,ov)=>{"use strict";ov.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 cv=m((xq,lv)=>{"use strict";var sM=le(),nM=Ot(),oM=Sa(),nc=ac(),uv=sM("".replace),uM=RegExp("^["+nc+"]+"),lM=RegExp("(^|[^"+nc+"])["+nc+"]+$"),sc=function(a){return function(e){var t=oM(nM(e));return a&1&&(t=uv(t,uM,"")),a&2&&(t=uv(t,lM,"$1")),t}};lv.exports={start:sc(1),end:sc(2),trim:sc(3)}});var fv=m((wq,hv)=>{"use strict";var cM=Cu().PROPER,dM=me(),dv=ac(),pv="\u200B\x85\u180E";hv.exports=function(a){return dM(function(){return!!dv[a]()||pv[a]()!==pv||cM&&dv[a].name!==a})}});var oc=m((Aq,mv)=>{"use strict";var pM=cv().start,hM=fv();mv.exports=hM("trimStart")?function(){return pM(this)}:"".trimStart});var gv=m(()=>{"use strict";var fM=ne(),bv=oc();fM({target:"String",proto:!0,name:"trimStart",forced:"".trimLeft!==bv},{trimLeft:bv})});var vv=m(()=>{"use strict";gv();var mM=ne(),Sv=oc();mM({target:"String",proto:!0,name:"trimStart",forced:"".trimStart!==Sv},{trimStart:Sv})});var Tv=m(($q,yv)=>{"use strict";vv();var bM=Ft();yv.exports=bM("String","trimLeft")});var Ev=m((Mq,Iv)=>{"use strict";var gM=Tv();Iv.exports=gM});var wv=m((Dq,xv)=>{"use strict";var SM=Ev();xv.exports=SM});var Nv=m(()=>{"use strict"});var Uv=m(()=>{"use strict"});var jv=m((fH,qv)=>{"use strict";var UM=Oe(),qM=ii(),jM=be(),HM=jM("match");qv.exports=function(a){var e;return UM(a)&&((e=a[HM])!==void 0?!!e:qM(a)==="RegExp")}});var Qv=m((mH,Hv)=>{"use strict";var QM=pt();Hv.exports=function(){var a=QM(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 zv=m((bH,Wv)=>{"use strict";var GM=_e(),WM=tt(),zM=Br(),YM=Qv(),Gv=RegExp.prototype;Wv.exports=function(a){var e=a.flags;return e===void 0&&!("flags"in Gv)&&!WM(a,"flags")&&zM(Gv,a)?GM(YM,a):e}});var Kv=m((gH,Yv)=>{"use strict";var pc=le(),KM=Bi(),XM=Math.floor,cc=pc("".charAt),JM=pc("".replace),dc=pc("".slice),ZM=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,eD=/\$([$&'`]|\d{1,2})/g;Yv.exports=function(a,e,t,i,r,s){var n=t+a.length,o=i.length,u=eD;return r!==void 0&&(r=KM(r),u=ZM),JM(s,u,function(l,c){var d;switch(cc(c,0)){case"$":return"$";case"&":return a;case"`":return dc(e,0,t);case"'":return dc(e,n);case"<":d=r[dc(c,1,-1)];break;default:var p=+c;if(p===0)return l;if(p>o){var h=XM(p/10);return h===0?l:h<=o?i[h-1]===void 0?cc(c,1):i[h-1]+cc(c,1):l}d=i[p-1]}return d===void 0?"":d})}});var Zv=m(()=>{"use strict";var tD=ne(),iD=_e(),fc=le(),Xv=Ot(),rD=re(),aD=Di(),sD=jv(),pr=Sa(),nD=_r(),oD=zv(),uD=Kv(),lD=be(),cD=et(),dD=lD("replace"),pD=TypeError,hc=fc("".indexOf),hD=fc("".replace),Jv=fc("".slice),fD=Math.max;tD({target:"String",proto:!0},{replaceAll:function(e,t){var i=Xv(this),r,s,n,o,u,l,c,d,p,h,f=0,b="";if(!aD(e)){if(r=sD(e),r&&(s=pr(Xv(oD(e))),!~hc(s,"g")))throw new pD("`.replaceAll` does not allow non-global regexes");if(n=nD(e,dD),n)return iD(n,e,i,t);if(cD&&r)return hD(pr(i),e,t)}for(o=pr(i),u=pr(e),l=rD(t),l||(t=pr(t)),c=u.length,d=fD(1,c),p=hc(o,u);p!==-1;)h=l?pr(t(u,p,o)):uD(u,o,p,[],void 0,t),b+=Jv(o,f,p)+h,f=p+c,p=p+d>o.length?-1:hc(o,u,p+d);return f<o.length&&(b+=Jv(o,f)),b}})});var ty=m((yH,ey)=>{"use strict";Nv();Uv();Zv();var mD=Ft();ey.exports=mD("String","replaceAll")});var ry=m((TH,iy)=>{"use strict";var bD=ty();iy.exports=bD});var sy=m((IH,ay)=>{"use strict";var gD=ry();ay.exports=gD});var oy=m((EH,ny)=>{"use strict";var SD=Ur(),vD=Sa(),yD=Ot(),TD=RangeError;ny.exports=function(e){var t=vD(yD(this)),i="",r=SD(e);if(r<0||r===1/0)throw new TD("Wrong number of repetitions");for(;r>0;(r>>>=1)&&(t+=t))r&1&&(i+=t);return i}});var py=m((xH,dy)=>{"use strict";var cy=le(),ID=vu(),uy=Sa(),ED=oy(),xD=Ot(),wD=cy(ED),AD=cy("".slice),kD=Math.ceil,ly=function(a){return function(e,t,i){var r=uy(xD(e)),s=ID(t),n=r.length,o=i===void 0?" ":uy(i),u,l;return s<=n||o===""?r:(u=s-n,l=wD(o,kD(u/o.length)),l.length>u&&(l=AD(l,0,u)),a?r+l:l+r)}};dy.exports={start:ly(!1),end:ly(!0)}});var fy=m((wH,hy)=>{"use strict";var PD=ai();hy.exports=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(PD)});var my=m(()=>{"use strict";var RD=ne(),LD=py().start,$D=fy();RD({target:"String",proto:!0,forced:$D},{padStart:function(e){return LD(this,e,arguments.length>1?arguments[1]:void 0)}})});var gy=m((PH,by)=>{"use strict";my();var MD=Ft();by.exports=MD("String","padStart")});var vy=m((RH,Sy)=>{"use strict";var DD=gy();Sy.exports=DD});var Ty=m((LH,yy)=>{"use strict";var CD=vy();yy.exports=CD});var Ld="2.0.136-dev.969962ab.0";var ke=(r=>(r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused",r))(ke||{}),Et=(v=>(v.MPEG="MPEG",v.DASH="DASH",v.DASH_SEP="DASH_SEP",v.DASH_SEP_VK="DASH_SEP",v.DASH_WEBM="DASH_WEBM",v.DASH_WEBM_AV1="DASH_WEBM_AV1",v.DASH_STREAMS="DASH_STREAMS",v.DASH_WEBM_VK="DASH_WEBM",v.DASH_ONDEMAND="DASH_ONDEMAND",v.DASH_ONDEMAND_VK="DASH_ONDEMAND",v.DASH_LIVE="DASH_LIVE",v.DASH_LIVE_CMAF="DASH_LIVE_CMAF",v.DASH_LIVE_WEBM="DASH_LIVE_WEBM",v.HLS="HLS",v.HLS_ONDEMAND="HLS_ONDEMAND",v.HLS_JS="HLS",v.HLS_LIVE="HLS_LIVE",v.HLS_LIVE_CMAF="HLS_LIVE_CMAF",v.WEB_RTC_LIVE="WEB_RTC_LIVE",v))(Et||{});var Rs=(r=>(r.NOT_AVAILABLE="NOT_AVAILABLE",r.AVAILABLE="AVAILABLE",r.CONNECTING="CONNECTING",r.CONNECTED="CONNECTED",r))(Rs||{}),qo=(i=>(i.HTTP1="http1",i.HTTP2="http2",i.QUIC="quic",i))(qo||{});var jo=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(jo||{}),Ls=(i=>(i.TRAFFIC_SAVING="traffic_saving",i.HIGH_QUALITY="high_quality",i.UNKNOWN="unknown",i))(Ls||{});var bI=V(Ge(),1);import{assertNever as Ph,assertNonNullable as zx,isNonNullable as Bs,ValueSubject as Tu,Subject as Yx,Subscription as Kx,merge as Xx,observableFrom as Jx,fromEvent as xh,map as wh,tap as Ah,filterChanged as Zx,isNullable as Iu,ErrorCategory as kh}from"@vkontakte/videoplayer-shared";var Eh=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 Vs=class{constructor(e){this.connection$=new Tu(void 0);this.castState$=new Tu("NOT_AVAILABLE");this.errorEvent$=new Yx;this.realCastState$=new Tu("NOT_AVAILABLE");this.subscription=new Kx;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=Bs(window.chrome?.cast),r=!!window.__onGCastApiAvailable;i?this.initializeCastApi():(window.__onGCastApiAvailable=s=>{delete window.__onGCastApiAvailable,s&&!this.isDestroyed&&this.initializeCastApi()},r||Eh("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:kh.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(){Bs(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();Iu(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();Iu(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(xh(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 Ph(r.sessionState)}})).add(Xx(xh(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(Ah(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),wh(r=>r.castState)),Jx([i.getCastState()])).pipe(Zx(),wh(ew),Ah(r=>{this.log({message:`realCastState$: ${r}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{let s=r==="CONNECTED",n=Bs(this.connection$.getValue());if(s&&!n){let o=i.getCurrentSession();zx(o);let u=o.getCastDevice(),l=o.getMediaSession()?.media?.contentId;(Iu(l)||l===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:o,castDevice:u}))}else!s&&n&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(r==="CONNECTED"?Bs(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:kh.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:r})}}},ew=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 Ph(a)}};var yd=V(Ge(),1),XT=V(qi(),1),JT=V(Yu(),1);var Mg=V(dn(),1);import{assertNever as Eg}from"@vkontakte/videoplayer-shared";var ae=(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:Eg(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:Eg(e)}};var P=(a,e,t=!1)=>{let i=a.getTransition();(t||!i||i.to===e)&&a.setState(e)};import{isNonNullable as uL,Subject as pn,merge as xg}from"@vkontakte/videoplayer-shared";var F=class{constructor(e){this.transitionStarted$=new pn;this.transitionEnded$=new pn;this.transitionUpdated$=new pn;this.forceChanged$=new pn;this.stateChangeStarted$=xg(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=xg(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||uL(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 lL}from"@vkontakte/videoplayer-shared";var wg=a=>{switch(a){case"MPEG":case"DASH":case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":case"HLS":case"HLS_ONDEMAND":return!1;case"DASH_LIVE":case"DASH_LIVE_CMAF":case"HLS_LIVE":case"HLS_LIVE_CMAF":case"DASH_LIVE_WEBM":case"WEB_RTC_LIVE":return!0;default:return lL(a)}};import{assertNever as Ji,assertNonNullable as di,debounce as Ag,ErrorCategory as kg,fromEvent as pi,isNonNullable as Pg,map as Rg,merge as Lg,observableFrom as cL,Subject as dL,Subscription as Bl,timeout as pL,getHighestQuality as hL}from"@vkontakte/videoplayer-shared";var fL=5,mL=5,bL=500,$g=7e3,ta=class{constructor(e){this.subscription=new Bl;this.loadMediaTimeoutSubscription=new Bl;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:Ji(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:Ji(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:Ji(e)}break}default:Ji(i)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(wg(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 Bl;this.subscription.add(e),this.subscription.add(Lg(this.videoState.stateChangeStarted$.pipe(Rg(r=>`stateChangeStarted$ ${JSON.stringify(r)}`)),this.videoState.stateChangeEnded$.pipe(Rg(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 dL;e.add(r.pipe(Ag(bL)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add(pi(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe(n=>{this.logRemoteEvent(n);let o=n.value;this.params.output.position$.next(o),(this.params.desiredState.seekState.getState().state==="applying"||Math.abs(o-s)>fL)&&r.next(o),s=o})),e.add(pi(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(pi(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(pi(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemotePause():this.handleRemotePlay()}),t(pi(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),r=>{this.logRemoteEvent(r);let{remotePlayer:s}=this.params.connection,n=r.value,o=this.params.output.isBuffering$.getValue(),u=n===chrome.cast.media.PlayerState.BUFFERING;switch(o!==u&&this.params.output.isBuffering$.next(u),n){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&s.duration-s.currentTime<mL&&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:Ji(n)}}),t(pi(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t(pi(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({muted:r.value})});let i=Lg(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,cL(["init"])).pipe(Ag(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];di(l);let c=hL(Object.keys(l));di(c);let d=l[c];di(d),i=d,r="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let l=t[e];di(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];di(l),i=l.url,r="application/dash+xml",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let l=t[e];di(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];di(l),i=ae(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:kg.VIDEO_PIPELINE,message:l,thrown:c}),c}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return Ji(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:o,subtitle:u}=this.params.meta;return Pg(o)&&(n.metadata.title=o),Pg(u)&&(n.metadata.subtitle=u),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(pL($g).subscribe(()=>s(`timeout(${$g})`)))});(0,Mg.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:kg.VIDEO_PIPELINE,message:s,thrown:r})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var tc=V(Ge(),1);import{clearVideoElement as Cg}from"@vkontakte/videoplayer-shared";import{clearVideoElement as gL}from"@vkontakte/videoplayer-shared";var Dg=a=>{try{a.pause(),a.playbackRate=0,gL(a),a.remove()}catch(e){console.error(e)}};import{fromEvent as SL,Subscription as vL}from"@vkontakte/videoplayer-shared";var Vl=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)}},_l=window.WeakMap?new WeakMap:new Vl,Ol=window.WeakMap?new WeakMap:new Map,yL=(a,e=20)=>{let t=0;return SL(a,"ratechange").subscribe(i=>{t++,t>=e&&(a.currentTime=a.currentTime,t=0)})},Pe=(a,{audioVideoSyncRate:e,disableYandexPiP:t})=>{let i=a.querySelector("video"),r=!!i;i?Cg(i):(i=document.createElement("video"),a.appendChild(i)),_l.set(i,r);let s=new vL;return s.add(yL(i,e)),Ol.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},Re=a=>{Ol.get(a)?.unsubscribe(),Ol.delete(a);let t=_l.get(a);_l.delete(a),t?Cg(a):Dg(a)};var Nl=V(Zi(),1);import{assertNonNullable as ra,isNonNullable as ft,isNullable as PL,fromEvent as er,merge as Ug,observableFrom as qg,filterChanged as jg,map as aa,Subject as Hg,Subscription as RL,ValueSubject as LL,ErrorCategory as $L}from"@vkontakte/videoplayer-shared";import{isNonNullable as Fl,isNullable as AL,Subscription as kL}from"@vkontakte/videoplayer-shared";var hn=(a,e,t,{equal:i=(n,o)=>n===o,changed$:r,onError:s}={})=>{let n=a.getState(),o=e(),u=AL(r),l=new kL;return r&&l.add(r.subscribe(c=>{let d=a.getState();i(c,d)&&a.setState(c)},s)),i(o,n)||(t(n),u&&a.setState(n)),l.add(a.stateChangeStarted$.subscribe(c=>{t(c.to),u&&a.setState(c.to)},s)),l},ht=(a,e,t)=>hn(e,()=>a.loop,i=>{Fl(i)&&(a.loop=i)},{onError:t}),Le=(a,e,t,i)=>hn(e,()=>({muted:a.muted,volume:a.volume}),r=>{Fl(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}),We=(a,e,t,i)=>hn(e,()=>a.playbackRate,r=>{Fl(r)&&(a.playbackRate=r)},{changed$:t,onError:i}),ia=hn;var ML=a=>["__",a.language,a.label].join("|"),DL=(a,e)=>{if(a.id===e)return!0;let[t,i,r]=e.split("|");return a.language===i&&a.label===r},Ul=class a{constructor(e){this.available$=new Hg;this.current$=new LL(void 0);this.error$=new Hg;this.subscription=new RL;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:$L.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(ia(t.internalTextTracks,()=>(0,Nl.default)(this.internalTracks),s=>{ft(s)&&this.setInternal(s)},{equal:(s,n)=>ft(s)&&ft(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(aa(s=>s.filter(({type:n})=>n==="internal"))),onError:r})),this.subscription.add(ia(t.externalTextTracks,()=>(0,Nl.default)(this.externalTracks),s=>{ft(s)&&this.setExternal(s)},{equal:(s,n)=>ft(s)&&ft(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(aa(s=>s.filter(({type:n})=>n==="external"))),onError:r})),this.subscription.add(ia(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(ia(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.activeCues)}))}subscribe(){ra(this.video);let{textTracks:e}=this.video;this.subscription.add(er(e,"addtrack").subscribe(()=>{let i=this.current$.getValue();i&&this.select(i)})),this.subscription.add(Ug(er(e,"addtrack"),er(e,"removetrack"),qg(["init"])).pipe(aa(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),jg((i,r)=>i.length===r.length&&i.every(({id:s},n)=>s===r[n].id))).subscribe(this.available$)),this.subscription.add(Ug(er(e,"change"),qg(["init"])).pipe(aa(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),aa(i=>i&&this.htmlTextTrackToITextTrack(i).id),jg()).subscribe(this.current$));let t=i=>this.applyCueSettings(i.target?.activeCues??null);this.subscription.add(er(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(er(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;ft(t.align)&&(r.align=t.align),ft(t.position)&&(r.position=t.position),ft(t.size)&&(r.size=t.size),ft(t.line)&&(r.line=t.line)}}htmlTextTracksAsArray(e=!1){ra(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:ML(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){ra(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(PL(e)||!DL(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){ra(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){ra(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)}},ze=Ul;var hi=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 Qg=a=>{let e=a;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e?.parentNode;return e??void 0},ql=a=>{let e=Qg(a);return!!(e&&e.fullscreenElement&&e.fullscreenElement===a)},Gg=a=>{let e=Qg(a);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===a)};import{fromEvent as Ee,map as mt,merge as yn,filterChanged as eS,isNonNullable as tS,Subject as qL,filter as Hl,mapTo as Ql,combine as jL,once as HL,throttle as QL,ErrorCategory as GL,ValueSubject as iS,Subscription as WL}from"@vkontakte/videoplayer-shared";var CL=3,Wg=(a,e,t=CL)=>{let i=0,r=0;for(let s=0;s<a.length;s++){let n=a.start(s),o=a.end(s);if(n<=e&&e<=o){if(i=n,r=o,!t)return{from:i,to:r};for(let u=s-1;u>=0;u--)a.end(u)+t>=i&&(i=a.start(u));for(let u=s+1;u<a.length;u++)a.start(u)-t<=r&&(r=a.end(u))}}return{from:i,to:r}};var fn=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,o=/webkit|safari|khtml/i.test(e)?"Safari":void 0,u=/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||u||l||r||s||o||"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 zg=V(Ge(),1);var sa=()=>/Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test(navigator.appVersion??navigator.userAgent)||navigator?.userAgentData?.mobile;var mn=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,zg.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=sa()}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,o=/webOS|BlackBerry|IEMobile|Opera Mini/i.test(e)?"RestMobile":void 0;this._current=t||i||r||s||o||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 bn=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 Ne=()=>window.ManagedMediaSource||window.MediaSource,tr=()=>!!(window.ManagedMediaSource&&window.ManagedSourceBuffer?.prototype?.appendBuffer),Yg=()=>!!(window.MediaSource&&window.SourceBuffer?.prototype?.appendBuffer),gn=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;var BL=document.createElement("video"),VL='video/mp4; codecs="avc1.42000a,mp4a.40.2"',_L='video/mp4; codecs="hev1.1.6.L93.B0"',Kg='video/webm; codecs="vp09.00.10.08"',Xg='video/webm; codecs="av01.0.00M.08"',OL='audio/mp4; codecs="mp4a.40.2"',FL='audio/webm; codecs="opus"',Jg,NL=async()=>{if(!window.navigator.mediaCapabilities)return;let a={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=await Promise.all([window.navigator.mediaCapabilities.decodingInfo({...a,video:{...a.video,contentType:Xg}}),window.navigator.mediaCapabilities.decodingInfo({...a,video:{...a.video,contentType:Kg}})]);Jg={DASH_WEBM_AV1:e,DASH_WEBM:t}};NL().catch(a=>{console.log(BL),console.error(a)});var Sn=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 Jg}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:tr(),mse:Yg(),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=!!Ne()?.isTypeSupported?.(VL),t=!!Ne()?.isTypeSupported?.(_L),i=!!Ne()?.isTypeSupported?.(OL);this._codecs={h264:e,h265:t,vp9:!!Ne()?.isTypeSupported?.(Kg),av1:!!Ne()?.isTypeSupported?.(Xg),aac:i,opus:!!Ne()?.isTypeSupported?.(FL),mpeg:(e||t)&&i},this._nativeHlsSupported=this._protocols.hls&&this._containers.mp4}catch(e){console.error(e)}try{this.destroyVideoElement()}catch(e){console.error("Error destroying video element:",e)}}destroyVideoElement(){if(!this._video)return;if(this._video.pause(),this._video.currentTime=0,this._video.removeAttribute("src"),this._video.src="",this._video.load(),this._video.remove){this._video.remove(),this._video=null;return}this._video.parentNode&&this._video.parentNode.removeChild(this._video);let e=this._video.cloneNode(!1);this._video.parentNode?.replaceChild(e,this._video),this._video=null}};var Zg="audio/mpeg",vn=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:!!Ne()?.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 UL}from"@vkontakte/videoplayer-shared";var jl=class{constructor(){this.isInited$=new UL(!1);this._displayChecker=new bn,this._deviceChecker=new mn(this._displayChecker),this._browserChecker=new fn,this._videoChecker=new Sn(this._deviceChecker,this._browserChecker),this._audioChecker=new vn,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)}},_=new jl;var $e=a=>{let e=y=>Ee(a,y).pipe(Ql(void 0)),t=new WL,i=()=>t.unsubscribe(),r=yn(Ee(a,"progress"),Ee(a,"timeupdate")).pipe(mt(()=>Wg(a.buffered,a.currentTime))),s=_.browser.isSafari?jL({play:e("play").pipe(HL()),playing:e("playing")}).pipe(Ql(void 0)):e("playing"),n=Ee(a,"volumechange").pipe(mt(()=>({muted:a.muted,volume:a.volume}))),o=Ee(a,"ratechange").pipe(mt(()=>a.playbackRate)),u=Ee(a,"error").pipe(Hl(()=>!!(a.error||a.played.length)),mt(()=>{let y=a.error;return{id:y?`MediaError#${y.code}`:"HtmlVideoError",category:GL.VIDEO_PIPELINE,message:y?y.message:"Error event from HTML video element",thrown:a.error??void 0}})),l=Ee(a,"timeupdate").pipe(mt(()=>a.currentTime)),c=["waiting","seeking","seeked","timeupdate"],d=new qL,p=.3,h;t.add(yn(...c.map(y=>Ee(a,y))).subscribe(y=>{let M=a.currentTime;a.loop&&tS(h)&&tS(M)&&h>=a.duration-p&&M<=p&&d.next(h),h=M}));let f=e("pause").pipe(Hl(()=>!a.error&&h!==a.duration)),b=Ee(a,"enterpictureinpicture"),g=Ee(a,"leavepictureinpicture"),S=new iS(Gg(a));t.add(b.subscribe(()=>S.next(!0))),t.add(g.subscribe(()=>S.next(!1)));let T=new iS(ql(a)),v=Ee(a,"fullscreenchange");t.add(v.pipe(mt(()=>ql(a))).subscribe(T));let x=.1,w=1e3,L=Ee(a,"timeupdate").pipe(mt(y=>a.duration-a.currentTime<x),eS()),B=yn(L.pipe(Hl(y=>!a.loop&&y)),Ee(a,"ended")).pipe(QL(w),Ql(void 0)),$=yn(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(y=>Ee(a,y)),L.pipe(mt(y=>({type:y?"ended":"unknown"})))).pipe(mt(y=>_.browser.isFirefox&&y.type==="ended"?a.readyState<2:a.readyState<3),eS());return{playing$:s,pause$:f,canplay$:e("canplay"),ended$:B,looped$:d,error$:u,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:l,durationChange$:Ee(a,"durationchange").pipe(mt(()=>a.duration)),isBuffering$:$,currentBuffer$:r,volumeState$:n,playbackRateState$:o,inPiP$:S,inFullscreen$:T,enterPip$:b,leavePip$:g,destroy:i}};import{VideoQuality as qt}from"@vkontakte/videoplayer-shared";var jt=a=>{switch(a){case"mobile":return qt.Q_144P;case"lowest":return qt.Q_240P;case"low":return qt.Q_360P;case"sd":case"medium":return qt.Q_480P;case"hd":case"high":return qt.Q_720P;case"fullhd":case"full":return qt.Q_1080P;case"quadhd":case"quad":return qt.Q_1440P;case"ultrahd":case"ultra":return qt.Q_2160P}};var we=V(bt(),1),zl=V(Ge(),1),fi=V(qi(),1);import{isNonNullable as Y,isNullable as wn,now as SS,isHigher as An,isHigherOrEqual as rr,isInvariantQuality as kn,isLowerOrEqual as ar,videoSizeToQuality as vS,assertNotEmptyArray as Pn,assertNonNullable as yS}from"@vkontakte/videoplayer-shared";var Gl=!1,kt={},lS=a=>{Gl=a},cS=()=>{kt={}},dS=a=>{a(kt)},na=(a,e)=>{Gl&&(kt.meta=kt.meta??{},kt.meta[a]=e)},xe=class{constructor(e){this.name=e}next(e){if(!Gl)return;kt.series=kt.series??{};let t=kt.series[this.name]??[];t.push([Date.now(),e]),kt.series[this.name]=t}};import{isHigher as i$,isHigherOrEqual as RN,isLower as pS,isLowerOrEqual as LN,isNonNullable as Tn,isNullable as r$,videoHeightToQuality as In}from"@vkontakte/videoplayer-shared";function Wl(a,e,t){return!a.max&&a.min===e?"high_quality":!a.min&&a.max===t?"traffic_saving":"unknown"}function En(a,e,t){return!!a&&Wl(a,e,t)==="high_quality"}function ir(a,e,t){return r$(a)||Tn(a.min)&&Tn(a.max)&&pS(a.max,a.min)||Tn(a.min)&&e&&i$(a.min,e)||Tn(a.max)&&t&&pS(a.max,t)}function hS({limits:a,highestAvailableHeight:e,lowestAvailableHeight:t}){return ir({max:a?.max?In(a.max):void 0,min:a?.min?In(a.min):void 0},e?In(e):void 0,t?In(t):void 0)}var TS=new xe("best_bitrate"),Rn=(a,e,t)=>(e-t)*Math.pow(2,-10*a)+t;var sr=a=>(e,t)=>a*(Number(e.bitrate)-Number(t.bitrate)),Ht=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=SS()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},Ln='Assertion "ABR Tracks is empty array" failed',xn=new WeakMap,fS=new WeakMap,mS=new WeakMap,oa=(a,e,t,i)=>{let r=[...e].sort(sr(1)),s=[...t].sort(sr(1)),n=s.filter(u=>Y(u.bitrate)&&Y(a.bitrate)?a.bitrate/u.bitrate>i:!0),o=(0,we.default)(s,Math.round(s.length*r.indexOf(a)/(r.length+1)))??(0,we.default)(s,-1);return o&&(0,zl.default)(n,o)?o:n.length?(0,we.default)(n,-1):(0,we.default)(s,0)},ua=(a,e,t,i)=>{let r=xn.get(e);r||(r=[...e].sort(sr(1)),xn.set(e,r));let s=xn.get(t);s||(s=[...t].sort(sr(1)),xn.set(t,s));let n=mS.get(a);n||(n=s.filter(u=>Y(u.bitrate)&&Y(a.bitrate)?a.bitrate/u.bitrate>i:!0),mS.set(a,n));let o=(0,we.default)(s,Math.round(s.length*r.indexOf(a)/(r.length+1)))??(0,we.default)(s,-1);return o&&(0,zl.default)(n,o)?o:n.length?(0,we.default)(n,-1):(0,we.default)(s,0)},bS=a=>"quality"in a,$n=(a,e,t,i)=>{let r=Y(i?.last?.bitrate)&&Y(t?.bitrate)&&i.last.bitrate<t.bitrate?a.trackCooldownIncreaseQuality:a.trackCooldownDecreaseQuality,s=t&&i&&i.history[t.id]&&SS()-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 o=bS(n)?"video":"audio",u=bS(n)?n.quality:n.bitrate;return e({message:`
8
8
  [last ${o} selected] ${u}
9
- `}),n}return i?.recordSwitch(t),t},s$=(a,e)=>Math.log(e)/Math.log(a),IS=({tuning:a,container:e,limits:t,panelSize:i})=>{let r=a.containerSizeFactor;if(i)return{containerSizeLimit:i,containerSizeFactor:r};if(a.usePixelRatio&&_.display.pixelRatio){let s=_.display.pixelRatio;if(a.pixelRatioMultiplier)r*=a.pixelRatioMultiplier*(s-1)+1;else{let n=a.pixelRatioLogBase,[o=0,u=0,l=0]=a.pixelRatioLogCoefficients,c=s$(n,o*s+u)+l;Number.isFinite(c)&&(r*=c)}}return En(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}},gS=new WeakMap,gt=(a,{container:e,estimatedThroughput:t,tuning:i,limits:r,reserve:s=0,forwardBufferHealth:n,playbackRate:o,current:u,history:l,visible:c,droppedVideoMaxQualityLimit:d,stallsVideoMaxQualityLimit:p,stallsPredictedThroughput:h,abrLogger:f,panelSize:b})=>{Pn(a,Ln);let{containerSizeFactor:g,containerSizeLimit:S}=IS({container:e,tuning:i,limits:r,panelSize:b}),T=i.considerPlaybackRate&&Y(o)?o:1,v=gS.get(a);v||(v=a.filter(E=>!kn(E.quality)).sort((E,k)=>An(E.quality,k.quality)?-1:1),gS.set(a,v));let x=(0,we.default)(v,-1)?.quality,w=(0,we.default)(v,0)?.quality,L=ir(r,w,x),B=T*Rn(n??.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),A={},$=null;for(let E of v){let k=!0;if(S)if(E.size)k=E.size.width<=S.width&&E.size.height<=S.height;else{let j=S&&vS(S);k=j?ar(E.quality,j):!0}if(!k){A[E.quality]="FitsContainer";continue}let Z=h||t,D=Y(Z)&&isFinite(Z)&&Y(E.bitrate)?Z-s>=E.bitrate*B:!0,q=En(r,i.highQualityLimit,i.trafficSavingLimit)&&r?.min===E.quality;if(!D&&!q){A[E.quality]="FitsThroughput";continue}if(i.lazyQualitySwitch&&Y(i.minBufferToSwitchUp)&&u&&!kn(u.quality)&&(n??0)<i.minBufferToSwitchUp&&An(E.quality,u.quality)){A[E.quality]="Buffer";continue}if(!!d&&rr(E.quality,d)&&!q){A[E.quality]="DroppedFramesLimit";continue}if(!!p&&rr(E.quality,p)&&!q){A[E.quality]="StallsLimit";continue}let he=L||(wn(r?.max)||ar(E.quality,r.max))&&(wn(r?.min)||rr(E.quality,r.min)),fe=Y(c)&&!c?ar(E.quality,i.backgroundVideoQualityLimit):!0;if(!he||!fe){A[E.quality]="FitsQualityLimits";continue}$||($=E)}$&&$.bitrate&&TS.next($.bitrate);let y=$??(0,we.default)(v,-1)??a[0],M=l?.last,I=$n(i,f,y,l);return Y(l)&&I.quality!==M?.quality&&f({message:`
9
+ `}),n}return i?.recordSwitch(t),t},a$=(a,e)=>Math.log(e)/Math.log(a),IS=({tuning:a,container:e,limits:t,panelSize:i})=>{let r=a.containerSizeFactor;if(i)return{containerSizeLimit:i,containerSizeFactor:r};if(a.usePixelRatio&&_.display.pixelRatio){let s=_.display.pixelRatio;if(a.pixelRatioMultiplier)r*=a.pixelRatioMultiplier*(s-1)+1;else{let n=a.pixelRatioLogBase,[o=0,u=0,l=0]=a.pixelRatioLogCoefficients,c=a$(n,o*s+u)+l;Number.isFinite(c)&&(r*=c)}}return En(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}},gS=new WeakMap,gt=(a,{container:e,estimatedThroughput:t,tuning:i,limits:r,reserve:s=0,forwardBufferHealth:n,playbackRate:o,current:u,history:l,visible:c,droppedVideoMaxQualityLimit:d,stallsVideoMaxQualityLimit:p,stallsPredictedThroughput:h,abrLogger:f,panelSize:b})=>{Pn(a,Ln);let{containerSizeFactor:g,containerSizeLimit:S}=IS({container:e,tuning:i,limits:r,panelSize:b}),T=i.considerPlaybackRate&&Y(o)?o:1,v=gS.get(a);v||(v=a.filter(E=>!kn(E.quality)).sort((E,k)=>An(E.quality,k.quality)?-1:1),gS.set(a,v));let x=(0,we.default)(v,-1)?.quality,w=(0,we.default)(v,0)?.quality,L=ir(r,w,x),B=T*Rn(n??.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),A={},$=null;for(let E of v){let k=!0;if(S)if(E.size)k=E.size.width<=S.width&&E.size.height<=S.height;else{let H=S&&vS(S);k=H?ar(E.quality,H):!0}if(!k){A[E.quality]="FitsContainer";continue}let Z=h||t,D=Y(Z)&&isFinite(Z)&&Y(E.bitrate)?Z-s>=E.bitrate*B:!0,q=En(r,i.highQualityLimit,i.trafficSavingLimit)&&r?.min===E.quality;if(!D&&!q){A[E.quality]="FitsThroughput";continue}if(i.lazyQualitySwitch&&Y(i.minBufferToSwitchUp)&&u&&!kn(u.quality)&&(n??0)<i.minBufferToSwitchUp&&An(E.quality,u.quality)){A[E.quality]="Buffer";continue}if(!!d&&rr(E.quality,d)&&!q){A[E.quality]="DroppedFramesLimit";continue}if(!!p&&rr(E.quality,p)&&!q){A[E.quality]="StallsLimit";continue}let he=L||(wn(r?.max)||ar(E.quality,r.max))&&(wn(r?.min)||rr(E.quality,r.min)),fe=Y(c)&&!c?ar(E.quality,i.backgroundVideoQualityLimit):!0;if(!he||!fe){A[E.quality]="FitsQualityLimits";continue}$||($=E)}$&&$.bitrate&&TS.next($.bitrate);let y=$??(0,we.default)(v,-1)??a[0],M=l?.last,I=$n(i,f,y,l);return Y(l)&&I.quality!==M?.quality&&f({message:`
10
10
  [VIDEO TRACKS ABR]
11
11
  [available video tracks]
12
12
  ${a.map(E=>`{ id: ${E.id}, quality: ${E.quality}, bitrate: ${E.bitrate}, size: ${E.size?.width}:${E.size?.height} }`).join(`
@@ -39,7 +39,7 @@ var TI=Object.create;var Rd=Object.defineProperty;var II=Object.getOwnPropertyDe
39
39
 
40
40
  [best video track] ${$?.quality}
41
41
  [selected video track] ${I?.quality}
42
- `}),I},Mn=(a,{container:e,estimatedThroughput:t,tuning:i,limits:r,reserve:s=0,forwardBufferHealth:n,playbackRate:o,current:u,history:l,visible:c,droppedVideoMaxQualityLimit:d,stallsVideoMaxQualityLimit:p,stallsPredictedThroughput:h,abrLogger:f,panelSize:b})=>{Pn(a,Ln);let{containerSizeFactor:g,containerSizeLimit:S}=IS({container:e,tuning:i,limits:r,panelSize:b}),T=i.considerPlaybackRate&&Y(o)?o:1,v=a.filter(k=>!kn(k.quality)).sort((k,Z)=>An(k.quality,Z.quality)?-1:1),x=(0,we.default)(v,-1)?.quality,w=(0,we.default)(v,0)?.quality,L=ir(r,w,x),B=T*Rn(n??.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),A={},y=v.filter(k=>{let Z=!0;if(S)if(k.size)Z=k.size.width<=S.width&&k.size.height<=S.height;else{let N=S&&vS(S);Z=N?ar(k.quality,N):!0}if(!Z)return A[k.quality]="FitsContainer",!1;let D=h||t,q=Y(D)&&isFinite(D)&&Y(k.bitrate)?D-s>=k.bitrate*B:!0,X=En(r,i.highQualityLimit,i.trafficSavingLimit)&&r?.min===k.quality;if(!q&&!X)return A[k.quality]="FitsThroughput",!1;if(i.lazyQualitySwitch&&Y(i.minBufferToSwitchUp)&&u&&!kn(u.quality)&&(n??0)<i.minBufferToSwitchUp&&An(k.quality,u.quality))return A[k.quality]="Buffer",!1;if(!!d&&rr(k.quality,d)&&!X)return A[k.quality]="DroppedFramesLimit",!1;if(!!p&&rr(k.quality,p)&&!X)return A[k.quality]="StallsLimit",!1;let fe=L||(wn(r?.max)||ar(k.quality,r.max))&&(wn(r?.min)||rr(k.quality,r.min)),j=Y(c)&&!c?ar(k.quality,i.backgroundVideoQualityLimit):!0;return!fe||!j?(A[k.quality]="FitsQualityLimits",!1):!0})[0];y&&y.bitrate&&TS.next(y.bitrate);let M=y??(0,we.default)(v,-1)??a[0],I=l?.last,E=$n(i,f,M,l);return Y(l)&&E.quality!==I?.quality&&f({message:`
42
+ `}),I},Mn=(a,{container:e,estimatedThroughput:t,tuning:i,limits:r,reserve:s=0,forwardBufferHealth:n,playbackRate:o,current:u,history:l,visible:c,droppedVideoMaxQualityLimit:d,stallsVideoMaxQualityLimit:p,stallsPredictedThroughput:h,abrLogger:f,panelSize:b})=>{Pn(a,Ln);let{containerSizeFactor:g,containerSizeLimit:S}=IS({container:e,tuning:i,limits:r,panelSize:b}),T=i.considerPlaybackRate&&Y(o)?o:1,v=a.filter(k=>!kn(k.quality)).sort((k,Z)=>An(k.quality,Z.quality)?-1:1),x=(0,we.default)(v,-1)?.quality,w=(0,we.default)(v,0)?.quality,L=ir(r,w,x),B=T*Rn(n??.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),A={},y=v.filter(k=>{let Z=!0;if(S)if(k.size)Z=k.size.width<=S.width&&k.size.height<=S.height;else{let N=S&&vS(S);Z=N?ar(k.quality,N):!0}if(!Z)return A[k.quality]="FitsContainer",!1;let D=h||t,q=Y(D)&&isFinite(D)&&Y(k.bitrate)?D-s>=k.bitrate*B:!0,X=En(r,i.highQualityLimit,i.trafficSavingLimit)&&r?.min===k.quality;if(!q&&!X)return A[k.quality]="FitsThroughput",!1;if(i.lazyQualitySwitch&&Y(i.minBufferToSwitchUp)&&u&&!kn(u.quality)&&(n??0)<i.minBufferToSwitchUp&&An(k.quality,u.quality))return A[k.quality]="Buffer",!1;if(!!d&&rr(k.quality,d)&&!X)return A[k.quality]="DroppedFramesLimit",!1;if(!!p&&rr(k.quality,p)&&!X)return A[k.quality]="StallsLimit",!1;let fe=L||(wn(r?.max)||ar(k.quality,r.max))&&(wn(r?.min)||rr(k.quality,r.min)),H=Y(c)&&!c?ar(k.quality,i.backgroundVideoQualityLimit):!0;return!fe||!H?(A[k.quality]="FitsQualityLimits",!1):!0})[0];y&&y.bitrate&&TS.next(y.bitrate);let M=y??(0,we.default)(v,-1)??a[0],I=l?.last,E=$n(i,f,M,l);return Y(l)&&E.quality!==I?.quality&&f({message:`
43
43
  [VIDEO TRACKS ABR]
44
44
  [available video tracks]
45
45
  ${a.map(k=>`{ id: ${k.id}, quality: ${k.quality}, bitrate: ${k.bitrate}, size: ${k.size?.width}:${k.size?.height} }`).join(`
@@ -114,14 +114,14 @@ var TI=Object.create;var Rd=Object.defineProperty;var II=Object.getOwnPropertyDe
114
114
  minBufferToSwitchUp: ${r.minBufferToSwitchUp},
115
115
 
116
116
  [selected audio track] ${T?.id}
117
- `}),T};var ge=a=>new URL(a).hostname;import{assertNever as DS,assertNonNullable as CS,combine as A$,debounce as k$,ErrorCategory as BS,filter as VS,filterChanged as P$,isNonNullable as Zl,map as On,merge as _S,observableFrom as R$,once as L$,Subscription as $$,ValueSubject as ec,videoQualityToHeight as OS,videoSizeToQuality as M$}from"@vkontakte/videoplayer-shared";var RS=V(bt(),1);var xS=V(Ge(),1),ES=a=>{if(a instanceof DOMException&&(0,xS.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"))},Me=async(a,e)=>{let t=a.muted;try{await a.play()}catch(i){if(!ES(i))return!1;if(e&&e(),t)return console.warn(i),!1;a.muted=!0;try{await a.play()}catch(r){return ES(r)&&(a.muted=!1,console.warn(r)),!1}}return!0};import{isNonNullable as Vn,isNullable as u$,assertNonNullable as da}from"@vkontakte/videoplayer-shared";var AS=V(Zi(),1);import{isNonNullable as wS,assertNonNullable as Bn,now as n$}from"@vkontakte/videoplayer-shared";function ce(){return n$()}function Yl(a){return ce()-a}function Kl(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,o,u=!1)=>{r(n)||(n.startsWith("/")||(n="/"+n),n=t+n);let l=n.indexOf("?")>-1?"&":"?";return u&&(n+=l+"lowLat=1",l="&"),o&&(n+=l+"_rnd="+Math.floor(999999999*Math.random())),n}}}function kS(a,e,t){let i=(...r)=>{t.apply(null,r),a.removeEventListener(e,i)};a.addEventListener(e,i)}function nr(a,e,t,i){let r=window.XMLHttpRequest,s,n,o,u=!1,l=0,c,d,p=!1,h="arraybuffer",f=7e3,b=2e3,g=()=>{if(u)return;Bn(c);let I=Yl(c),E;if(I<b){E=b-I,setTimeout(g,E);return}b*=2,b>f&&(b=f),n&&n.abort(),n=new r,L()},S=I=>(s=I,M),T=I=>(d=I,M),v=()=>(h="json",M),x=()=>{if(!u){if(--l>=0){g(),i&&i();return}u=!0,d&&d(),t&&t()}},w=I=>(p=I,M),L=()=>{c=ce(),n=new r,n.open("get",a);let I=0,E,k=0,Z=()=>(Bn(c),Math.max(c,Math.max(E||0,k||0)));if(s&&n.addEventListener("progress",D=>{let q=ce();s.updateChunk&&D.loaded>I&&(s.updateChunk(Z(),D.loaded-I),I=D.loaded,E=q)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>x())),n.addEventListener("load",()=>{if(u)return;Bn(n);let D=n.status;if(D>=200&&D<300){let{response:q,responseType:X}=n,ie=q?.byteLength;if(typeof ie=="number"&&s){let oe=ie-I;oe&&s.updateChunk&&s.updateChunk(Z(),oe)}X==="json"&&(!q||!(0,AS.default)(q).length)?x():(d&&d(),e(q))}else x()}),n.addEventListener("error",()=>{x()}),p){let D=()=>{Bn(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(k=ce(),n.removeEventListener("readystatechange",D))};n.addEventListener("readystatechange",D)}return n.responseType=h,n.send(),M},M={withBitrateReporting:S,withParallel:w,withJSONResponse:v,withRetryCount:I=>(l=I,M),withRetryInterval:(I,E)=>(wS(I)&&(b=I),wS(E)&&(f=E),M),withTimeout:I=>(o=I,M),withFinally:T,send:L,abort:()=>{n&&(n.abort(),n=void 0),u=!0,d&&d()}};return M}var la=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,o=s.end-s.start;i+=n;let u=s.bytes*n/o;r+=u,s.start=t,s.bytes-=u}}}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 PS=V(Zi(),1);var ca=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=ce(),r=u=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=u,e._errorCB?e._errorCB(u):(this.limitCompleteCount(),this.completeRequests[t]=e)},s=u=>{e._complete=1,e._responseData=u,e._downloadTime=ce()-i,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(u,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},n=()=>{e._finallyCB&&e._finallyCB()},o=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=nr(t,s,()=>r("error"),o),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally(n),this.activeRequests[t]=e,e._request.send(),this.lastPrefetchStart=ce()}_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=ce();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,PS.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 o=this.pendingQueue.indexOf(e);o!==-1&&this.pendingQueue.splice(o,1),this.logger(`Request not prefetched, starting new request, url=${e}${o===-1?"":"; removed pending"}`),this._sendRequest(s,e)}},s._cb=t,s._errorCB=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 l$}from"@vkontakte/videoplayer-shared";var _n=1e4,Xl=3;var c$=6e4,d$=10,p$=1,h$=500,pa=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 l$,this.chunkRateEstimator=new la(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=Kl(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=Kl(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*(_.display.pixelRatio||1)*t.offsetHeight||520;for(let o=0;o<this.manifest.length;++o){s=this.manifest[o];let{max:u,min:l}=this.autoQualityLimits||{};!hS({limits:this.autoQualityLimits,highestAvailableHeight:this.manifest[0].video.height,lowestAvailableHeight:(0,RS.default)(this.manifest,-1).video.height})&&(u&&s.video.height>u||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||Vn(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=()=>{kS(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 ca(Xl,_n,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,o=null,u=null,l=null,c=!1,d=()=>{let x=s&&(!c||c===this.rep);return x||t("Not running!"),x},p=(x,w,L)=>{u&&u.abort(),u=nr(this.urlResolver.resolve(x,!1),w,L,()=>this._retryCallback()).withTimeout(_n).withBitrateReporting(this.bitrateSwitcher).withRetryCount(Xl).withFinally(()=>{u=null}).send()},h=(x,w,L)=>{da(this.filesFetcher),o?.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(x,!1),w,L,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},f=x=>{let w=i.playbackRate;i.playbackRate!==x&&(t(`Playback rate switch: ${w}=>${x}`),i.playbackRate=x)},b=x=>{this.lowLatency=x,t(`lowLatency changed to ${x}`),g()},g=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)f(1);else{let x=this._getBufferSizeSec();if(this.bufferStates.length<5){f(1);return}let L=ce()-1e4,B=0;for(let $=0;$<this.bufferStates.length;$++){let y=this.bufferStates[$];x=Math.min(x,y.buf),y.ts<L&&B++}this.bufferStates.splice(0,B),t(`update playback rate; minBuffer=${x} drop=${B} jitter=${this.sourceJitter}`);let A=x-p$;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)}},S=x=>{let w,L=()=>w&&w.start?w.start.length:0,B=D=>w.start[D]/1e3,A=D=>w.dur[D]/1e3,$=D=>w.fragIndex+D,y=(D,q)=>({chunkIdx:$(D),startTS:B(D),dur:A(D),discontinuity:q}),M=()=>{let D=0;if(w&&w.dur){let q=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,X=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,ie=q;this.sourceJitter>1&&(ie+=this.sourceJitter-1);let oe=w.dur.length-1;for(;oe>=0&&(ie-=w.dur[oe],!(ie<=0));--oe);D=Math.min(oe,w.dur.length-1-X),D=Math.max(D,0)}return y(D,!0)},I=D=>{let q=L();if(!(q<=0)){if(Vn(D)){for(let X=0;X<q;X++)if(B(X)>D)return y(X)}return M()}},E=D=>{let q=L(),X=D?D.chunkIdx+1:0,ie=X-w.fragIndex;if(!(q<=0)){if(!D||ie<0||ie-q>d$)return t(`Resync: offset=${ie} bChunks=${q} chunk=`+JSON.stringify(D)),M();if(!(ie>=q))return y(X-w.fragIndex,!1)}},k=(D,q,X)=>{l&&l.abort(),l=nr(this.urlResolver.resolve(D,!0,this.lowLatency),q,X,()=>this._retryCallback()).withTimeout(_n).withRetryCount(Xl).withFinally(()=>{l=null}).withJSONResponse().send()};return{seek:(D,q)=>{k(x,X=>{if(!d())return;w=X;let ie=!!w.lowLatency;ie!==this.lowLatency&&b(ie);let oe=0;for(let he=0;he<w.dur.length;++he)oe+=w.dur[he];oe>0&&(da(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(oe/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,D(I(q))},()=>this._handleNetworkError())},nextChunk:E}},T=()=>{s=!1,o&&o.abort(),u&&u.abort(),l&&l.abort(),da(this.filesFetcher),this.filesFetcher.abortAll()};return c={start:x=>{let{videoElement:w,logger:L}=this.params,B=S(e.jidxUrl),A,$,y,M,I=0,E,k,Z,D=()=>{E&&(clearTimeout(E),E=void 0);let N=Math.max(h$,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),Ae=I+N,Te=ce(),ue=Math.min(1e4,Ae-Te);I=Te;let je=()=>{l||d()&&B.seek(()=>{d()&&(I=ce(),q(),D())})};ue>0?E=window.setTimeout(()=>{this.paused?D():je()},ue):je()},q=()=>{let N;for(;N=B.nextChunk(M);)M=N,fe(N);let Ae=B.nextChunk(y);if(Ae){if(y&&Ae.discontinuity){L("Detected discontinuity; restarting playback"),this.paused?D():(T(),this._initPlayerWith(e));return}he(Ae)}else D()},X=(N,Ae)=>{if(!d()||!this.sourceBuffer)return;let Te,ue,je,Ct=ot=>{window.setTimeout(()=>{d()&&X(N,Ae)},ot)};if(this.sourceBuffer.updating)L("Source buffer is updating; delaying appendBuffer"),Ct(100);else{let ot=ce(),Be=w.currentTime;!this.paused&&w.buffered.length>1&&k===Be&&ot-Z>500&&(L("Stall suspected; trying to fix"),this._fixupStall()),k!==Be&&(k=Be,Z=ot);let Bt=this._getBufferSizeSec();if(Bt>30)L(`Buffered ${Bt} seconds; delaying appendBuffer`),Ct(2e3);else try{this.sourceBuffer.appendBuffer(N),this.videoPlayStarted?(this.bufferStates.push({ts:ot,buf:Bt}),g(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),Ae&&Ae()}catch(ut){if(ut.name==="QuotaExceededError")L("QuotaExceededError; delaying appendBuffer"),je=this.sourceBuffer.buffered.length,je!==0&&(Te=this.sourceBuffer.buffered.start(0),ue=Be,ue-Te>4&&this.sourceBuffer.remove(Te,ue-3)),Ct(1e3);else throw ut}}},ie=()=>{$&&A&&(L([`Appending chunk, sz=${$.byteLength}:`,JSON.stringify(y)]),X($,function(){$=null,q()}))},oe=N=>e.fragUrlTemplate.replace("%%id%%",N.chunkIdx),he=N=>{d()&&h(oe(N),(Ae,Te)=>{if(d()){if(Te/=1e3,$=Ae,y=N,n=N.startTS,Te){let ue=Math.min(10,N.dur/Te);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*ue:ue}ie()}},()=>this._handleNetworkError())},fe=N=>{d()&&(da(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(oe(N),!1)))},j=N=>{d()&&(e.cachedHeader=N,X(N,()=>{A=!0,ie()}))};s=!0,B.seek(N=>{if(d()){if(I=ce(),!N){D();return}M=N,!u$(x)||N.startTS>x?he(N):(y=N,q())}},x),e.cachedHeader?j(e.cachedHeader):p(e.headerUrl,j,()=>this._handleNetworkError())},stop:T,getTimestampSec:()=>n},c}_switchToQuality(e){let{logger:t,playerCallback:i}=this.params,r;e.bitrate!==this.bitrate&&(this.rep&&(r=this.rep.getTimestampSec(),Vn(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,da(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(r),i({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return Vn(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,i=d=>{if(!this.autoQuality)return;let p,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}p=this._selectQuality(d),p?this._switchToQuality(p):e(`Could not find quality by bitrate ${d}`)},s={updateChunk:(p,h)=>{let f=ce();if(this.chunkRateEstimator.addInterval(p,f,h)){let g=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:h,duration:f-p,speed:g}),!0}},get:()=>{let p=this.chunkRateEstimator.getBitRate();return p?p*.85:0}},n=-1/0,o,u=!0,l=()=>{let d=s.get();if(d&&o&&this.autoQuality){if(u&&d>o&&Yl(n)<3e4)return;i(d)}u=this.autoQuality};return{updateChunk:(d,p)=>{let h=s.updateChunk(d,p);return h&&l(),h},notifySwitch:d=>{let p=ce();d<o&&(n=p),o=d}}}_fetchManifest(e,t,i){this.manifestRequest=nr(this.urlResolver.resolve(e,!0),t,i,()=>this._retryCallback()).withJSONResponse().withTimeout(_n).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;Me(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 o=[];return n?.length?(n.forEach((u,l)=>{u.video&&r.canPlayType(u.codecs).replace(/no/,"")&&window.MediaSource?.isTypeSupported?.(u.codecs)&&(u.index=l,o.push(u))}),o.sort(function(u,l){return u.video&&l.video?l.video.height-u.video.height:l.bitrate-u.bitrate}),o):(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))},c$))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};var MS=V(qi(),1);import{debounce as f$,filter as LS,fromEvent as m$,interval as b$,isHigher as g$,isInvariantQuality as S$,isLower as v$,merge as y$,Subject as $S,Subscription as T$}from"@vkontakte/videoplayer-shared";var Jl=class{constructor(){this.onDroopedVideoFramesLimit$=new $S;this.subscription=new T$;this.playing=!1;this.tracks=[];this.forceChecker$=new $S;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&&!S$(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&&g$(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(m$(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=b$(this.droppedFramesChecker.checkTime).pipe(LS(()=>this.playing),LS(()=>{let r=!!this.isForceCheckCounter;return r&&(this.isForceCheckCounter-=1),!r})),t=this.forceChecker$.pipe(f$(this.droppedFramesChecker.checkTime)),i=y$(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,MS.default)(this.limitCounts).filter(([,i])=>i>=this.droppedFramesChecker.countLimit).sort(([i],[r])=>v$(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}},or=Jl;import{map as I$,Observable as E$}from"@vkontakte/videoplayer-shared";import{fromEvent as x$}from"@vkontakte/videoplayer-shared";var ha=()=>!!window.documentPictureInPicture?.window||!!document.pictureInPictureElement;var w$=(a,e)=>new E$(t=>{if(!window.IntersectionObserver)return;let i={root:null},r=new IntersectionObserver((n,o)=>{n.forEach(u=>t.next(u.isIntersecting||ha()))},{...i,...e});r.observe(a);let s=x$(document,"visibilitychange").pipe(I$(n=>!document.hidden||ha())).subscribe(n=>t.next(n));return()=>{r.unobserve(a),s.unsubscribe()}}),Ye=w$;var D$=["paused","playing","ready"],C$=["paused","playing","ready"],fa=class{constructor(e){this.subscription=new $$;this.videoState=new F("stopped");this.representations$=new ec([]);this.droppedFramesManager=new or;this.maxSeekBackTime$=new ec(1/0);this.zeroTime$=new ec(void 0);this.liveOffset=new hi;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:BS.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=Ht(r.name)??M$(r.video),o=r.bitrate/1e3,u={...r.video};if(!n)continue;let l={id:s,quality:n,bitrate:o,size:u};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),Zl(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(),o=this.params.desiredState.autoVideoTrackSwitching.getTransition();if((0,tc.default)(C$,e)&&(n||o)){this.prepare();return}if(r?.to!=="paused"&&s.state==="requested"&&(0,tc.default)(D$,e)){this.seek(s.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(ae(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 u=r?.from;u&&u==="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 u=this.liveOffset.getTotalOffset();u>=this.maxSeekBackTime$.getValue()&&(u=0,this.liveOffset.resetTo(u)),this.liveOffset.resume(),this.params.output.position$.next(-u/1e3),this.dash.reinit(ae(this.params.source.url,u))}return;default:return DS(e)}};this.textTracksManager=new ze(e.source.url),this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=r=>{e.output.error$.next({id:"DashLiveProvider",category:BS.WTF,message:"DashLiveProvider internal logic error",thrown:r})};this.subscription.add(_S(this.videoState.stateChangeStarted$.pipe(On(r=>({transition:r,type:"start"}))),this.videoState.stateChangeEnded$.pipe(On(r=>({transition:r,type:"end"})))).subscribe(({transition:r,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(r)}`})})),this.video=Pe(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=$e(this.video);this.subscription.add(()=>i.destroy()),this.subscription.add(this.representations$.pipe(On(r=>r.map(({track:s})=>s)),VS(r=>!!r.length),L$()).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(P$(),On(r=>-r/1e3)).subscribe(this.params.output.duration$)).add(A$({zeroTime:this.zeroTime$.pipe(VS(Zl)),position:i.timeUpdate$}).subscribe(({zeroTime:r,position:s})=>this.params.output.liveTime$.next(r+s*1e3),t)).add(ht(this.video,this.params.desiredState.isLooped,t)).add(Le(this.video,this.params.desiredState.volume,i.volumeState$,t)).add(i.volumeState$.subscribe(this.params.output.volume$,t)).add(We(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(Ye(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:r,min:s}})=>{this.dash.setAutoQualityLimits({max:r&&OS(r),min:s&&OS(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 DS(r.to)}},t)).add(_S(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,R$(["init"])).pipe(k$(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),Re(this.video)}createLiveDashPlayer(){let e=new pa({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&&Zl(t)?t:gt(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(),o=this.params.desiredState.videoTrack.getState()?.id,u=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(r&&(n||s!==o)&&this.setVideoTrack(r),u&&this.setAutoQuality(i),n||u||s!==o){let l=e.find(({track:c})=>c.id===s)?.representation;CS(l,"Representations missing"),this.dash.startPlay(l,i)}}setVideoTrack(e){let t=this.representations$.getValue().find(({track:i})=>i.id===e.id)?.representation;CS(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(ae(this.params.source.url,n)),r&&this.dash.pause(),this.liveOffset.resetTo(n,r)}};var FS=fa;var eT=V(Ge(),1);var de=(a,e)=>{let t=0;for(let i=0;i<a.length;i++){let r=a.start(i)*1e3,s=a.end(i)*1e3;r<=e&&e<=s&&(t=s)}return Math.max(t-e,0)};import{assertNever as bC,assertNonNullable as gC,debounce as SC,ErrorCategory as Xy,filter as _c,filterChanged as po,fromEvent as vC,isNonNullable as Jy,isNullable as yC,map as Oc,merge as ho,observableFrom as Fc,once as Zy,Subscription as TC}from"@vkontakte/videoplayer-shared";var Fn=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(o){Promise.resolve().then(()=>{throw o})}n.options&&n.options.once&&this.removeEventListener(e.type,n.callback)}return!e.defaultPrevented}},ur=class extends Fn{constructor(){super(),this.listeners||Fn.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)}},ma=class{constructor(){Object.defineProperty(this,"signal",{value:new ur,writable:!0,configurable:!0})}abort(e){let t;try{t=new Event("abort")}catch{typeof document<"u"?document.createEvent?(t=document.createEvent("Event"),t.initEvent("abort",!1,!1)):(t=document.createEventObject(),t.type="abort"):t={type:"abort",bubbles:!1,cancelable:!1}}let i=e;if(i===void 0)if(typeof document>"u")i=new Error("This operation was aborted"),i.name="AbortError";else try{i=new DOMException("signal is aborted without reason")}catch{i=new Error("This operation was aborted"),i.name="AbortError"}this.signal.reason=i,this.signal.dispatchEvent(t)}toString(){return"[object AbortController]"}};typeof Symbol<"u"&&Symbol.toStringTag&&(ma.prototype[Symbol.toStringTag]="AbortController",ur.prototype[Symbol.toStringTag]="AbortSignal");function Nn(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 ic(a){typeof a=="function"&&(a={fetch:a});let{fetch:e,Request:t=e.Request,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r=!1}=a;if(!Nn({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 d;c&&c.signal&&(d=c.signal,delete c.signal);let p=new t(l,c);return d&&Object.defineProperty(p,"signal",{writable:!1,enumerable:!1,configurable:!0,value:d}),p},s.prototype=t.prototype);let n=e;return{fetch:(u,l)=>{let c=s&&s.prototype.isPrototypeOf(u)?u.signal:l?l.signal:void 0;if(c){let d;try{d=new DOMException("Aborted","AbortError")}catch{d=new Error("Aborted"),d.name="AbortError"}if(c.aborted)return Promise.reject(d);let p=new Promise((h,f)=>{c.addEventListener("abort",()=>f(d),{once:!0})});return l&&l.signal&&delete l.signal,Promise.race([p,n(u,l)])}return n(u,l)},Request:s}}var B$=()=>"fetch"in window,ba=B$()&&Nn({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),NS=ba?ic({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,Ke=ba?NS.fetch:window.fetch,uq=ba?NS.Request:window.Request,K=ba?ma:window.AbortController,lq=ba?ur:window.AbortSignal;var $c=V(ga(),1);var Av=V(wv(),1);import{ErrorCategory as va}from"@vkontakte/videoplayer-shared";var Un=a=>{if(!a)return{id:"EmptyResponse",category:va.PARSER,message:"Empty response"};if(a.length<=2&&a.match(/^\d+$/))return{id:`UVError#${a}`,category:va.NETWORK,message:`UV Error ${a}`};let e=(0,Av.default)(a).substring(0,100).toLowerCase();if(e.startsWith("<!doctype")||e.startsWith("<html>")||e.startsWith("<body>")||e.startsWith("<head>"))return{id:"UnexpectedHTML",category:va.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:va.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:va.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 Pc,assertNonNullable as Sr,combine as vr,ErrorCategory as st,filter as ro,filterChanged as Xa,flattenObject as Ja,fromEvent as Mt,getTraceSubscriptionMethod as JD,interval as Rc,isNonNullable as Za,isNullable as Qy,map as yr,merge as vi,now as Lc,Subject as ao,Subscription as Gy,tap as ZD,throttle as eC,ValueSubject as ee}from"@vkontakte/videoplayer-shared";var jn=V(Ge(),1),Si=V(bt(),1),Qn=V(ga(),1);var yM=(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)},TM=a=>window.clearTimeout(a),kv=a=>typeof a=="function"&&a?.toString().endsWith("{ [native code] }"),Pv=!kv(window.requestIdleCallback)||!kv(window.cancelIdleCallback),lr=Pv?yM:window.requestIdleCallback,St=Pv?TM:window.cancelIdleCallback;var By=V(dn(),1);import{assertNever as IM,ErrorCategory as Rv,Subject as Lv}from"@vkontakte/videoplayer-shared";var EM=18,$v=!1;try{$v=_.browser.isSafari&&!!_.browser.safariVersion&&_.browser.safariVersion<=EM}catch(a){console.error(a)}var uc=class{constructor(e){this.bufferFull$=new Lv;this.error$=new Lv;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:Rv.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)};$v&&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:Rv.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:IM(t)}}},Mv=uc;var cr=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 De,ErrorCategory as Rt,fromEvent as Ic,getExponentialDelay as Ec,isNonNullable as mr,isNullable as ve,now as Hn,once as ND,Subject as UD,Subscription as qD,ValueSubject as gi}from"@vkontakte/videoplayer-shared";var 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),this.size32=i<=e.buffer.byteLength-e.byteOffset?i:NaN;let r=this.size32?this.size32-8:void 0,s=e.byteOffset+this.cursor;this.size64=0,this.usertype=0,this.content=new DataView(e.buffer,s,r)}get id(){return this.type}get size(){return this.size32}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 dr=class extends Q{};var ya=class extends Q{constructor(t,i){super(t,i);this.ondemandPrefix="ondemandlivejson";this.ondemandDataReceivedKey="t-in";this.ondemandDataPreparedKey="t-out";let r=this.content.byteOffset,s=r+this.content.byteLength,n=new TextDecoder("ascii").decode(this.content.buffer.slice(r,s)).split(this.ondemandPrefix)[1],o=JSON.parse(n);this.serverDataReceivedTimestamp=o[this.ondemandDataReceivedKey],this.serverDataPreparedTime=o[this.ondemandDataPreparedKey]}};var Ta=class extends Q{constructor(e,t){super(e,t),this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let i=this.size-this.cursor;for(;i;){let r=this.readString(4);this.compatibleBrands.push(r),i-=4}}};var Ia=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var J=class extends Q{constructor(e,t){super(e,t);let i=this.readUint32();this.version=i>>>24,this.flags=i&16777215}};var Ea=class extends J{constructor(e,t){super(e,t),this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.timescale=this.readUint32(),this.duration=this.readUint32(),this.rate=this.readUint32(),this.volume=this.readUint16()}};var xa=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var wa=class extends Q{constructor(e,t){super(e,t),this.data=this.content}};var mi=class extends J{get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e,t){super(e,t),this.segments=[],this.referenceId=this.readUint32(),this.timescale=this.readUint32(),this.earliestPresentationTime32=this.readUint32(),this.firstOffset32=this.readUint32(),this.earliestPresentationTime64=0,this.firstOffset64=0,this.referenceCount=this.readUint32()&65535;for(let i=0;i<this.referenceCount;i++){let r=this.readUint32(),s=r>>>31,n=r<<1>>>1,o=this.readUint32();r=this.readUint32();let u=r>>>28,l=r<<3>>>3;this.segments.push({referenceType:s,referencedSize:n,subsegmentDuration:o,SAPType:u,SAPDeltaTime:l})}}};var Aa=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ka=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Pa=class extends J{constructor(e,t){switch(super(e,t),this.readUint8()){case 0:this.stereoMode=0;break;case 1:this.stereoMode=1;break;case 2:this.stereoMode=2;break;case 3:this.stereoMode=3;break;case 4:this.stereoMode=4;break}this.cursor+=1}};var Ra=class extends J{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var La=class extends J{constructor(e,t){super(e,t),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}};var $a=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ma=class extends J{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 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 J{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var Va=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var _a=class extends J{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 Oa=class extends J{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 Fa=class extends J{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 Na=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ua=class extends J{constructor(e,t){super(e,t),this.entryCount=this.readUint32(),this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+8,this.content.byteLength-8))}};var qa=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+78,this.content.byteLength-78))}};var wM={ftyp:Ta,moov:Ia,mvhd:Ea,moof:xa,mdat:wa,sidx:mi,trak:Aa,mdia:$a,mfhd:Ba,tkhd:Ma,traf:Va,tfhd:_a,tfdt:Oa,trun:Fa,minf:Da,sv3d:ka,st3d:Pa,prhd:Ra,proj:Ca,equi:La,uuid:ya,stbl:Na,stsd:Ua,avc1:qa,unknown:dr},Pt=class a{constructor(e={}){this.options={offset:0,...e}}parse(e){let t=[],i=this.options.offset;for(;i<e.byteLength;)try{let s=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+i+4,4)),n=this.createBox(s,new DataView(e.buffer,e.byteOffset+i));if(!n.size)break;t.push(n),i+=n.size}catch{break}return t}createBox(e,t){let i=wM[e];return i?new i(t,new a):new dr(t,new a)}};var Qt=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(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 kM=new TextDecoder("ascii"),PM=a=>kM.decode(new DataView(a.buffer,a.byteOffset+4,4))==="ftyp",RM=a=>{let e=new mi(a,new Pt),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,o={status:"none",time:{from:t,to:t+n},byte:{from:i,to:i+s.referencedSize-1}};return t+=n,i+=s.referencedSize,o})},LM=(a,e)=>{let i=new Pt().parse(a),r=new Qt(i),s=r.findAll("moof"),n=e?r.findAll("uuid"):r.findAll("mdat");if(!(n.length&&s.length))return null;let o=s[0],u=n[n.length-1],l=o.source.byteOffset,d=u.source.byteOffset-o.source.byteOffset+u.size;return new DataView(a.buffer,l,d)},$M=a=>{let t=new Pt().parse(a),i=new Qt(t),r={},s=i.findAll("uuid");return s.length?s[s.length-1]:r},MM=a=>{let t=new Pt().parse(a);return new Qt(t).find("sidx")?.timescale},DM=(a,e)=>{let i=new Pt().parse(a),s=new Qt(i).findAll("traf"),n=s[s.length-1].children.find(d=>d.type==="tfhd"),o=s[s.length-1].children.find(d=>d.type==="tfdt"),u=s[s.length-1].children.find(d=>d.type==="trun"),l=0;return u.sampleDuration.length?l=u.sampleDuration.reduce((d,p)=>d+p,0):l=n.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+l)/e*1e3},CM=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 Pt().parse(a),r=new Qt(i);if(r.find("sv3d")){e.is3dVideo=!0;let n=r.find("st3d");n&&(e.stereoMode=n.stereoMode);let o=r.find("prhd");o&&(e.projectionData.pose.yaw=o.poseYawDegrees,e.projectionData.pose.pitch=o.posePitchDegrees,e.projectionData.pose.roll=o.poseRollDegrees);let u=r.find("equi");u&&(e.projectionData.bounds.top=u.projectionBoundsTop,e.projectionData.bounds.right=u.projectionBoundsRight,e.projectionData.bounds.bottom=u.projectionBoundsBottom,e.projectionData.bounds.left=u.projectionBoundsLeft)}return e},Dv={validateData:PM,parseInit:CM,getIndexRange:()=>{},parseSegments:RM,parseFeedableSegmentChunk:LM,getChunkEndTime:DM,getServerLatencyTimestamps:$M,getTimescaleFromIndex:MM};var Qa=V(Ge(),1);import{assertNonNullable as lc,isNonNullable as _v,isNullable as VM}from"@vkontakte/videoplayer-shared";import{assertNever as BM}from"@vkontakte/videoplayer-shared";var Cv={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"}},Bv=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 Cv,s=r?Cv[i].type:"binary",n=a.getUint8(t),o=0;n&128?o=1:n&64?o=2:n&32?o=3:n&16?o=4:n&8?o=5:n&4?o=6:n&2?o=7:n&1&&(o=8);let u=new DataView(a.buffer,a.byteOffset+t+1,o-1),l=n&255>>o,c=ja(u),d=l*2**((o-1)*8)+c,p=t+o,h;return p+d>a.byteLength?h=new DataView(a.buffer,a.byteOffset+p):h=new DataView(a.buffer,a.byteOffset+p,d),{tag:r?i:"0x"+i.toString(16).toUpperCase(),type:s,tagHeaderSize:p,tagSize:p+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},rt=(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:BM(e)}},bi=(a,e)=>{let t=0;for(;t<a.byteLength;){let i=new DataView(a.buffer,a.byteOffset+t),r=Bv(i);if(!e(r))return;r.type==="master"&&bi(r.value,e),t=r.value.byteOffset-a.byteOffset+r.valueSize}},Vv=a=>{if(a.getUint32(0)!==440786851)return!1;let e,t,i,r=Bv(a);return bi(r.value,({tag:s,type:n,value:o})=>(s===17143?e=rt(o,n):s===17026?t=rt(o,n):s===17029&&(i=rt(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)};var Ov=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],_M=[231,22612,22743,167,171,163,160,175],OM=a=>{let e,t,i,r,s=!1,n=!1,o=!1,u,l,c=!1,d=0;return bi(a,({tag:p,type:h,value:f,valueSize:b})=>{if(p===21419){let g=rt(f,h);l=ja(g)}else p!==21420&&(l=void 0);return p===408125543?(e=f.byteOffset,t=f.byteOffset+b):p===357149030?s=!0:p===290298740?n=!0:p===2807729?i=rt(f,h):p===17545?r=rt(f,h):p===21420&&l===475249515?u=rt(f,h):p===374648427?bi(f,({tag:g,type:S,value:T})=>g===30321?(c=rt(T,S)===1,!1):!0):s&&n&&(0,Qa.default)(Ov,p)&&(o=!0),!o}),lc(e,"Failed to parse webm Segment start"),lc(t,"Failed to parse webm Segment end"),lc(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:u,is3dVideo:c,stereoMode:d,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},FM=a=>{if(VM(a.cuesSeekPosition))return;let e=a.segmentStart+a.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},NM=(a,e)=>{let t=!1,i=!1,r=o=>_v(o.time)&&_v(o.position),s=[],n;return bi(a,({tag:o,type:u,value:l})=>{switch(o){case 475249515:t=!0;break;case 187:n&&r(n)&&s.push(n),n={};break;case 179:n&&(n.time=rt(l,u));break;case 183:break;case 241:n&&(n.position=rt(l,u));break;default:t&&(0,Qa.default)(Ov,o)&&(i=!0)}return!(t&&i)}),n&&r(n)&&s.push(n),s.map((o,u)=>{let{time:l,position:c}=o,d=s[u+1];return{status:"none",time:{from:l,to:d?d.time:e.segmentDuration},byte:{from:e.segmentStart+c,to:d?e.segmentStart+d.position-1:e.segmentEnd-1}}})},UM=a=>{let e=0,t=!1;try{bi(a,i=>i.tag===524531317?i.tagSize<=a.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):(0,Qa.default)(_M,i.tag)?(e+i.tagSize<=a.byteLength&&(e+=i.tagSize,t||=(0,Qa.default)([163,160,175],i.tag)),!0):!1)}catch{}return e>0&&e<=a.byteLength&&t?new DataView(a.buffer,a.byteOffset,e):null},Fv={validateData:Vv,parseInit:OM,getIndexRange:FM,parseSegments:NM,parseFeedableSegmentChunk:UM};var vt=a=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(a);if(e){let[,t,i]=e;if(t==="audio"||t==="video")switch(i){case"webm":return Fv;case"mp4":return Dv}}throw new ReferenceError(`Unsupported mime type ${a}`)};var yt=a=>a instanceof DOMException&&(a.name==="AbortError"||a.code===20);var bc=V(sy(),1),ky=V(qi(),1),Py=V(Ty(),1),Ry=V(bt(),1),gc=V(Zi(),1);var Iy=V(Ge(),1),mc=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(),o=s+n;return(0,Iy.default)(["6E","7A","F4"],o)}}return!1};import{isNonNullable as _D,isNullable as wy}from"@vkontakte/videoplayer-shared";var Ey=a=>{if(a.includes("/")){let e=a.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(a)};var xy=a=>{try{let e=VD(),t=a.match(e),{groups:i}=t??{};if(i){let r={};if(i.extensions){let o=i.extensions.toLowerCase().match(/(?:[0-9a-wy-z](?:-[a-z0-9]{2,8})+)/g);Array.from(o||[]).forEach(u=>{r[u[0]]=u.slice(2)})}let s=i.variants?.split(/-/).filter(o=>o!==""),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(o=>{let u=n[o];(typeof u>"u"||u==="")&&delete n[o]}),n}return null}catch{return null}};function VD(){let a="(?<extlang>(?:[a-z]{3}(?:-[a-z]{3}){0,2}))",e="x(?:-[a-z0-9]{1,8})+",c=`^(?:(?<langtag>${`
117
+ `}),T};var ge=a=>new URL(a).hostname;import{assertNever as DS,assertNonNullable as CS,combine as w$,debounce as A$,ErrorCategory as BS,filter as VS,filterChanged as k$,isNonNullable as Zl,map as On,merge as _S,observableFrom as P$,once as R$,Subscription as L$,ValueSubject as ec,videoQualityToHeight as OS,videoSizeToQuality as $$}from"@vkontakte/videoplayer-shared";var RS=V(bt(),1);var xS=V(Ge(),1),ES=a=>{if(a instanceof DOMException&&(0,xS.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"))},Me=async(a,e)=>{let t=a.muted;try{await a.play()}catch(i){if(!ES(i))return!1;if(e&&e(),t)return console.warn(i),!1;a.muted=!0;try{await a.play()}catch(r){return ES(r)&&(a.muted=!1,console.warn(r)),!1}}return!0};import{isNonNullable as Vn,isNullable as o$,assertNonNullable as da}from"@vkontakte/videoplayer-shared";var AS=V(Zi(),1);import{isNonNullable as wS,assertNonNullable as Bn,now as s$}from"@vkontakte/videoplayer-shared";function ce(){return s$()}function Yl(a){return ce()-a}function Kl(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,o,u=!1)=>{r(n)||(n.startsWith("/")||(n="/"+n),n=t+n);let l=n.indexOf("?")>-1?"&":"?";return u&&(n+=l+"lowLat=1",l="&"),o&&(n+=l+"_rnd="+Math.floor(999999999*Math.random())),n}}}function kS(a,e,t){let i=(...r)=>{t.apply(null,r),a.removeEventListener(e,i)};a.addEventListener(e,i)}function nr(a,e,t,i){let r=window.XMLHttpRequest,s,n,o,u=!1,l=0,c,d,p=!1,h="arraybuffer",f=7e3,b=2e3,g=()=>{if(u)return;Bn(c);let I=Yl(c),E;if(I<b){E=b-I,setTimeout(g,E);return}b*=2,b>f&&(b=f),n&&n.abort(),n=new r,L()},S=I=>(s=I,M),T=I=>(d=I,M),v=()=>(h="json",M),x=()=>{if(!u){if(--l>=0){g(),i&&i();return}u=!0,d&&d(),t&&t()}},w=I=>(p=I,M),L=()=>{c=ce(),n=new r,n.open("get",a);let I=0,E,k=0,Z=()=>(Bn(c),Math.max(c,Math.max(E||0,k||0)));if(s&&n.addEventListener("progress",D=>{let q=ce();s.updateChunk&&D.loaded>I&&(s.updateChunk(Z(),D.loaded-I),I=D.loaded,E=q)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>x())),n.addEventListener("load",()=>{if(u)return;Bn(n);let D=n.status;if(D>=200&&D<300){let{response:q,responseType:X}=n,ie=q?.byteLength;if(typeof ie=="number"&&s){let oe=ie-I;oe&&s.updateChunk&&s.updateChunk(Z(),oe)}X==="json"&&(!q||!(0,AS.default)(q).length)?x():(d&&d(),e(q))}else x()}),n.addEventListener("error",()=>{x()}),p){let D=()=>{Bn(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(k=ce(),n.removeEventListener("readystatechange",D))};n.addEventListener("readystatechange",D)}return n.responseType=h,n.send(),M},M={withBitrateReporting:S,withParallel:w,withJSONResponse:v,withRetryCount:I=>(l=I,M),withRetryInterval:(I,E)=>(wS(I)&&(b=I),wS(E)&&(f=E),M),withTimeout:I=>(o=I,M),withFinally:T,send:L,abort:()=>{n&&(n.abort(),n=void 0),u=!0,d&&d()}};return M}var la=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,o=s.end-s.start;i+=n;let u=s.bytes*n/o;r+=u,s.start=t,s.bytes-=u}}}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 PS=V(Zi(),1);var ca=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=ce(),r=u=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=u,e._errorCB?e._errorCB(u):(this.limitCompleteCount(),this.completeRequests[t]=e)},s=u=>{e._complete=1,e._responseData=u,e._downloadTime=ce()-i,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(u,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},n=()=>{e._finallyCB&&e._finallyCB()},o=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=nr(t,s,()=>r("error"),o),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally(n),this.activeRequests[t]=e,e._request.send(),this.lastPrefetchStart=ce()}_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=ce();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,PS.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 o=this.pendingQueue.indexOf(e);o!==-1&&this.pendingQueue.splice(o,1),this.logger(`Request not prefetched, starting new request, url=${e}${o===-1?"":"; removed pending"}`),this._sendRequest(s,e)}},s._cb=t,s._errorCB=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 u$}from"@vkontakte/videoplayer-shared";var _n=1e4,Xl=3;var l$=6e4,c$=10,d$=1,p$=500,pa=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 u$,this.chunkRateEstimator=new la(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=Kl(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=Kl(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*(_.display.pixelRatio||1)*t.offsetHeight||520;for(let o=0;o<this.manifest.length;++o){s=this.manifest[o];let{max:u,min:l}=this.autoQualityLimits||{};!hS({limits:this.autoQualityLimits,highestAvailableHeight:this.manifest[0].video.height,lowestAvailableHeight:(0,RS.default)(this.manifest,-1).video.height})&&(u&&s.video.height>u||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||Vn(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=()=>{kS(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 ca(Xl,_n,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,o=null,u=null,l=null,c=!1,d=()=>{let x=s&&(!c||c===this.rep);return x||t("Not running!"),x},p=(x,w,L)=>{u&&u.abort(),u=nr(this.urlResolver.resolve(x,!1),w,L,()=>this._retryCallback()).withTimeout(_n).withBitrateReporting(this.bitrateSwitcher).withRetryCount(Xl).withFinally(()=>{u=null}).send()},h=(x,w,L)=>{da(this.filesFetcher),o?.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(x,!1),w,L,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},f=x=>{let w=i.playbackRate;i.playbackRate!==x&&(t(`Playback rate switch: ${w}=>${x}`),i.playbackRate=x)},b=x=>{this.lowLatency=x,t(`lowLatency changed to ${x}`),g()},g=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)f(1);else{let x=this._getBufferSizeSec();if(this.bufferStates.length<5){f(1);return}let L=ce()-1e4,B=0;for(let $=0;$<this.bufferStates.length;$++){let y=this.bufferStates[$];x=Math.min(x,y.buf),y.ts<L&&B++}this.bufferStates.splice(0,B),t(`update playback rate; minBuffer=${x} drop=${B} jitter=${this.sourceJitter}`);let A=x-d$;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)}},S=x=>{let w,L=()=>w&&w.start?w.start.length:0,B=D=>w.start[D]/1e3,A=D=>w.dur[D]/1e3,$=D=>w.fragIndex+D,y=(D,q)=>({chunkIdx:$(D),startTS:B(D),dur:A(D),discontinuity:q}),M=()=>{let D=0;if(w&&w.dur){let q=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,X=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,ie=q;this.sourceJitter>1&&(ie+=this.sourceJitter-1);let oe=w.dur.length-1;for(;oe>=0&&(ie-=w.dur[oe],!(ie<=0));--oe);D=Math.min(oe,w.dur.length-1-X),D=Math.max(D,0)}return y(D,!0)},I=D=>{let q=L();if(!(q<=0)){if(Vn(D)){for(let X=0;X<q;X++)if(B(X)>D)return y(X)}return M()}},E=D=>{let q=L(),X=D?D.chunkIdx+1:0,ie=X-w.fragIndex;if(!(q<=0)){if(!D||ie<0||ie-q>c$)return t(`Resync: offset=${ie} bChunks=${q} chunk=`+JSON.stringify(D)),M();if(!(ie>=q))return y(X-w.fragIndex,!1)}},k=(D,q,X)=>{l&&l.abort(),l=nr(this.urlResolver.resolve(D,!0,this.lowLatency),q,X,()=>this._retryCallback()).withTimeout(_n).withRetryCount(Xl).withFinally(()=>{l=null}).withJSONResponse().send()};return{seek:(D,q)=>{k(x,X=>{if(!d())return;w=X;let ie=!!w.lowLatency;ie!==this.lowLatency&&b(ie);let oe=0;for(let he=0;he<w.dur.length;++he)oe+=w.dur[he];oe>0&&(da(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(oe/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,D(I(q))},()=>this._handleNetworkError())},nextChunk:E}},T=()=>{s=!1,o&&o.abort(),u&&u.abort(),l&&l.abort(),da(this.filesFetcher),this.filesFetcher.abortAll()};return c={start:x=>{let{videoElement:w,logger:L}=this.params,B=S(e.jidxUrl),A,$,y,M,I=0,E,k,Z,D=()=>{E&&(clearTimeout(E),E=void 0);let N=Math.max(p$,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),Ae=I+N,Te=ce(),ue=Math.min(1e4,Ae-Te);I=Te;let He=()=>{l||d()&&B.seek(()=>{d()&&(I=ce(),q(),D())})};ue>0?E=window.setTimeout(()=>{this.paused?D():He()},ue):He()},q=()=>{let N;for(;N=B.nextChunk(M);)M=N,fe(N);let Ae=B.nextChunk(y);if(Ae){if(y&&Ae.discontinuity){L("Detected discontinuity; restarting playback"),this.paused?D():(T(),this._initPlayerWith(e));return}he(Ae)}else D()},X=(N,Ae)=>{if(!d()||!this.sourceBuffer)return;let Te,ue,He,Ct=ot=>{window.setTimeout(()=>{d()&&X(N,Ae)},ot)};if(this.sourceBuffer.updating)L("Source buffer is updating; delaying appendBuffer"),Ct(100);else{let ot=ce(),Be=w.currentTime;!this.paused&&w.buffered.length>1&&k===Be&&ot-Z>500&&(L("Stall suspected; trying to fix"),this._fixupStall()),k!==Be&&(k=Be,Z=ot);let Bt=this._getBufferSizeSec();if(Bt>30)L(`Buffered ${Bt} seconds; delaying appendBuffer`),Ct(2e3);else try{this.sourceBuffer.appendBuffer(N),this.videoPlayStarted?(this.bufferStates.push({ts:ot,buf:Bt}),g(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),Ae&&Ae()}catch(ut){if(ut.name==="QuotaExceededError")L("QuotaExceededError; delaying appendBuffer"),He=this.sourceBuffer.buffered.length,He!==0&&(Te=this.sourceBuffer.buffered.start(0),ue=Be,ue-Te>4&&this.sourceBuffer.remove(Te,ue-3)),Ct(1e3);else throw ut}}},ie=()=>{$&&A&&(L([`Appending chunk, sz=${$.byteLength}:`,JSON.stringify(y)]),X($,function(){$=null,q()}))},oe=N=>e.fragUrlTemplate.replace("%%id%%",N.chunkIdx),he=N=>{d()&&h(oe(N),(Ae,Te)=>{if(d()){if(Te/=1e3,$=Ae,y=N,n=N.startTS,Te){let ue=Math.min(10,N.dur/Te);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*ue:ue}ie()}},()=>this._handleNetworkError())},fe=N=>{d()&&(da(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(oe(N),!1)))},H=N=>{d()&&(e.cachedHeader=N,X(N,()=>{A=!0,ie()}))};s=!0,B.seek(N=>{if(d()){if(I=ce(),!N){D();return}M=N,!o$(x)||N.startTS>x?he(N):(y=N,q())}},x),e.cachedHeader?H(e.cachedHeader):p(e.headerUrl,H,()=>this._handleNetworkError())},stop:T,getTimestampSec:()=>n},c}_switchToQuality(e){let{logger:t,playerCallback:i}=this.params,r;e.bitrate!==this.bitrate&&(this.rep&&(r=this.rep.getTimestampSec(),Vn(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,da(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(r),i({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return Vn(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,i=d=>{if(!this.autoQuality)return;let p,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}p=this._selectQuality(d),p?this._switchToQuality(p):e(`Could not find quality by bitrate ${d}`)},s={updateChunk:(p,h)=>{let f=ce();if(this.chunkRateEstimator.addInterval(p,f,h)){let g=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:h,duration:f-p,speed:g}),!0}},get:()=>{let p=this.chunkRateEstimator.getBitRate();return p?p*.85:0}},n=-1/0,o,u=!0,l=()=>{let d=s.get();if(d&&o&&this.autoQuality){if(u&&d>o&&Yl(n)<3e4)return;i(d)}u=this.autoQuality};return{updateChunk:(d,p)=>{let h=s.updateChunk(d,p);return h&&l(),h},notifySwitch:d=>{let p=ce();d<o&&(n=p),o=d}}}_fetchManifest(e,t,i){this.manifestRequest=nr(this.urlResolver.resolve(e,!0),t,i,()=>this._retryCallback()).withJSONResponse().withTimeout(_n).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;Me(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 o=[];return n?.length?(n.forEach((u,l)=>{u.video&&r.canPlayType(u.codecs).replace(/no/,"")&&window.MediaSource?.isTypeSupported?.(u.codecs)&&(u.index=l,o.push(u))}),o.sort(function(u,l){return u.video&&l.video?l.video.height-u.video.height:l.bitrate-u.bitrate}),o):(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))},l$))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};var MS=V(qi(),1);import{debounce as h$,filter as LS,fromEvent as f$,interval as m$,isHigher as b$,isInvariantQuality as g$,isLower as S$,merge as v$,Subject as $S,Subscription as y$}from"@vkontakte/videoplayer-shared";var Jl=class{constructor(){this.onDroopedVideoFramesLimit$=new $S;this.subscription=new y$;this.playing=!1;this.tracks=[];this.forceChecker$=new $S;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&&!g$(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(f$(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=m$(this.droppedFramesChecker.checkTime).pipe(LS(()=>this.playing),LS(()=>{let r=!!this.isForceCheckCounter;return r&&(this.isForceCheckCounter-=1),!r})),t=this.forceChecker$.pipe(h$(this.droppedFramesChecker.checkTime)),i=v$(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,MS.default)(this.limitCounts).filter(([,i])=>i>=this.droppedFramesChecker.countLimit).sort(([i],[r])=>S$(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}},or=Jl;import{map as T$,Observable as I$}from"@vkontakte/videoplayer-shared";import{fromEvent as E$}from"@vkontakte/videoplayer-shared";var ha=()=>!!window.documentPictureInPicture?.window||!!document.pictureInPictureElement;var x$=(a,e)=>new I$(t=>{if(!window.IntersectionObserver)return;let i={root:null},r=new IntersectionObserver((n,o)=>{n.forEach(u=>t.next(u.isIntersecting||ha()))},{...i,...e});r.observe(a);let s=E$(document,"visibilitychange").pipe(T$(n=>!document.hidden||ha())).subscribe(n=>t.next(n));return()=>{r.unobserve(a),s.unsubscribe()}}),Ye=x$;var M$=["paused","playing","ready"],D$=["paused","playing","ready"],fa=class{constructor(e){this.subscription=new L$;this.videoState=new F("stopped");this.representations$=new ec([]);this.droppedFramesManager=new or;this.maxSeekBackTime$=new ec(1/0);this.zeroTime$=new ec(void 0);this.liveOffset=new hi;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:BS.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)??$$(r.video),o=r.bitrate/1e3,u={...r.video};if(!n)continue;let l={id:s,quality:n,bitrate:o,size:u};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),Zl(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(),o=this.params.desiredState.autoVideoTrackSwitching.getTransition();if((0,tc.default)(D$,e)&&(n||o)){this.prepare();return}if(r?.to!=="paused"&&s.state==="requested"&&(0,tc.default)(M$,e)){this.seek(s.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(ae(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 u=r?.from;u&&u==="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 u=this.liveOffset.getTotalOffset();u>=this.maxSeekBackTime$.getValue()&&(u=0,this.liveOffset.resetTo(u)),this.liveOffset.resume(),this.params.output.position$.next(-u/1e3),this.dash.reinit(ae(this.params.source.url,u))}return;default:return DS(e)}};this.textTracksManager=new ze(e.source.url),this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=r=>{e.output.error$.next({id:"DashLiveProvider",category:BS.WTF,message:"DashLiveProvider internal logic error",thrown:r})};this.subscription.add(_S(this.videoState.stateChangeStarted$.pipe(On(r=>({transition:r,type:"start"}))),this.videoState.stateChangeEnded$.pipe(On(r=>({transition:r,type:"end"})))).subscribe(({transition:r,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(r)}`})})),this.video=Pe(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=$e(this.video);this.subscription.add(()=>i.destroy()),this.subscription.add(this.representations$.pipe(On(r=>r.map(({track:s})=>s)),VS(r=>!!r.length),R$()).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(k$(),On(r=>-r/1e3)).subscribe(this.params.output.duration$)).add(w$({zeroTime:this.zeroTime$.pipe(VS(Zl)),position:i.timeUpdate$}).subscribe(({zeroTime:r,position:s})=>this.params.output.liveTime$.next(r+s*1e3),t)).add(ht(this.video,this.params.desiredState.isLooped,t)).add(Le(this.video,this.params.desiredState.volume,i.volumeState$,t)).add(i.volumeState$.subscribe(this.params.output.volume$,t)).add(We(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(Ye(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:r,min:s}})=>{this.dash.setAutoQualityLimits({max:r&&OS(r),min:s&&OS(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 DS(r.to)}},t)).add(_S(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,P$(["init"])).pipe(A$(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),Re(this.video)}createLiveDashPlayer(){let e=new pa({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&&Zl(t)?t:gt(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(),o=this.params.desiredState.videoTrack.getState()?.id,u=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(r&&(n||s!==o)&&this.setVideoTrack(r),u&&this.setAutoQuality(i),n||u||s!==o){let l=e.find(({track:c})=>c.id===s)?.representation;CS(l,"Representations missing"),this.dash.startPlay(l,i)}}setVideoTrack(e){let t=this.representations$.getValue().find(({track:i})=>i.id===e.id)?.representation;CS(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(ae(this.params.source.url,n)),r&&this.dash.pause(),this.liveOffset.resetTo(n,r)}};var FS=fa;var eT=V(Ge(),1);var de=(a,e)=>{let t=0;for(let i=0;i<a.length;i++){let r=a.start(i)*1e3,s=a.end(i)*1e3;r<=e&&e<=s&&(t=s)}return Math.max(t-e,0)};import{assertNever as mC,assertNonNullable as bC,debounce as gC,ErrorCategory as Xy,filter as _c,filterChanged as po,fromEvent as SC,isNonNullable as Jy,isNullable as vC,map as Oc,merge as ho,observableFrom as Fc,once as Zy,Subscription as yC}from"@vkontakte/videoplayer-shared";var Fn=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(o){Promise.resolve().then(()=>{throw o})}n.options&&n.options.once&&this.removeEventListener(e.type,n.callback)}return!e.defaultPrevented}},ur=class extends Fn{constructor(){super(),this.listeners||Fn.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)}},ma=class{constructor(){Object.defineProperty(this,"signal",{value:new ur,writable:!0,configurable:!0})}abort(e){let t;try{t=new Event("abort")}catch{typeof document<"u"?document.createEvent?(t=document.createEvent("Event"),t.initEvent("abort",!1,!1)):(t=document.createEventObject(),t.type="abort"):t={type:"abort",bubbles:!1,cancelable:!1}}let i=e;if(i===void 0)if(typeof document>"u")i=new Error("This operation was aborted"),i.name="AbortError";else try{i=new DOMException("signal is aborted without reason")}catch{i=new Error("This operation was aborted"),i.name="AbortError"}this.signal.reason=i,this.signal.dispatchEvent(t)}toString(){return"[object AbortController]"}};typeof Symbol<"u"&&Symbol.toStringTag&&(ma.prototype[Symbol.toStringTag]="AbortController",ur.prototype[Symbol.toStringTag]="AbortSignal");function Nn(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 ic(a){typeof a=="function"&&(a={fetch:a});let{fetch:e,Request:t=e.Request,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r=!1}=a;if(!Nn({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 d;c&&c.signal&&(d=c.signal,delete c.signal);let p=new t(l,c);return d&&Object.defineProperty(p,"signal",{writable:!1,enumerable:!1,configurable:!0,value:d}),p},s.prototype=t.prototype);let n=e;return{fetch:(u,l)=>{let c=s&&s.prototype.isPrototypeOf(u)?u.signal:l?l.signal:void 0;if(c){let d;try{d=new DOMException("Aborted","AbortError")}catch{d=new Error("Aborted"),d.name="AbortError"}if(c.aborted)return Promise.reject(d);let p=new Promise((h,f)=>{c.addEventListener("abort",()=>f(d),{once:!0})});return l&&l.signal&&delete l.signal,Promise.race([p,n(u,l)])}return n(u,l)},Request:s}}var C$=()=>"fetch"in window,ba=C$()&&Nn({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),NS=ba?ic({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,Ke=ba?NS.fetch:window.fetch,oq=ba?NS.Request:window.Request,K=ba?ma:window.AbortController,uq=ba?ur:window.AbortSignal;var $c=V(ga(),1);var Av=V(wv(),1);import{ErrorCategory as va}from"@vkontakte/videoplayer-shared";var Un=a=>{if(!a)return{id:"EmptyResponse",category:va.PARSER,message:"Empty response"};if(a.length<=2&&a.match(/^\d+$/))return{id:`UVError#${a}`,category:va.NETWORK,message:`UV Error ${a}`};let e=(0,Av.default)(a).substring(0,100).toLowerCase();if(e.startsWith("<!doctype")||e.startsWith("<html>")||e.startsWith("<body>")||e.startsWith("<head>"))return{id:"UnexpectedHTML",category:va.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:va.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:va.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 Pc,assertNonNullable as Sr,combine as vr,ErrorCategory as st,filter as ro,filterChanged as Xa,flattenObject as Ja,fromEvent as Mt,getTraceSubscriptionMethod as XD,interval as Rc,isNonNullable as Za,isNullable as Qy,map as yr,merge as vi,now as Lc,Subject as ao,Subscription as Gy,tap as JD,throttle as ZD,ValueSubject as ee}from"@vkontakte/videoplayer-shared";var Hn=V(Ge(),1),Si=V(bt(),1),Qn=V(ga(),1);var vM=(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)},yM=a=>window.clearTimeout(a),kv=a=>typeof a=="function"&&a?.toString().endsWith("{ [native code] }"),Pv=!kv(window.requestIdleCallback)||!kv(window.cancelIdleCallback),lr=Pv?vM:window.requestIdleCallback,St=Pv?yM:window.cancelIdleCallback;var By=V(dn(),1);import{assertNever as TM,ErrorCategory as Rv,Subject as Lv}from"@vkontakte/videoplayer-shared";var IM=18,$v=!1;try{$v=_.browser.isSafari&&!!_.browser.safariVersion&&_.browser.safariVersion<=IM}catch(a){console.error(a)}var uc=class{constructor(e){this.bufferFull$=new Lv;this.error$=new Lv;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:Rv.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)};$v&&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:Rv.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:TM(t)}}},Mv=uc;var cr=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 De,ErrorCategory as Rt,fromEvent as Ic,getExponentialDelay as Ec,isNonNullable as mr,isNullable as ve,now as jn,once as FD,Subject as ND,Subscription as UD,ValueSubject as gi}from"@vkontakte/videoplayer-shared";var 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),this.size32=i<=e.buffer.byteLength-e.byteOffset?i:NaN;let r=this.size32?this.size32-8:void 0,s=e.byteOffset+this.cursor;this.size64=0,this.usertype=0,this.content=new DataView(e.buffer,s,r)}get id(){return this.type}get size(){return this.size32}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 dr=class extends Q{};var ya=class extends Q{constructor(t,i){super(t,i);this.ondemandPrefix="ondemandlivejson";this.ondemandDataReceivedKey="t-in";this.ondemandDataPreparedKey="t-out";let r=this.content.byteOffset,s=r+this.content.byteLength,n=new TextDecoder("ascii").decode(this.content.buffer.slice(r,s)).split(this.ondemandPrefix)[1],o=JSON.parse(n);this.serverDataReceivedTimestamp=o[this.ondemandDataReceivedKey],this.serverDataPreparedTime=o[this.ondemandDataPreparedKey]}};var Ta=class extends Q{constructor(e,t){super(e,t),this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let i=this.size-this.cursor;for(;i;){let r=this.readString(4);this.compatibleBrands.push(r),i-=4}}};var Ia=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var J=class extends Q{constructor(e,t){super(e,t);let i=this.readUint32();this.version=i>>>24,this.flags=i&16777215}};var Ea=class extends J{constructor(e,t){super(e,t),this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.timescale=this.readUint32(),this.duration=this.readUint32(),this.rate=this.readUint32(),this.volume=this.readUint16()}};var xa=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var wa=class extends Q{constructor(e,t){super(e,t),this.data=this.content}};var mi=class extends J{get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e,t){super(e,t),this.segments=[],this.referenceId=this.readUint32(),this.timescale=this.readUint32(),this.earliestPresentationTime32=this.readUint32(),this.firstOffset32=this.readUint32(),this.earliestPresentationTime64=0,this.firstOffset64=0,this.referenceCount=this.readUint32()&65535;for(let i=0;i<this.referenceCount;i++){let r=this.readUint32(),s=r>>>31,n=r<<1>>>1,o=this.readUint32();r=this.readUint32();let u=r>>>28,l=r<<3>>>3;this.segments.push({referenceType:s,referencedSize:n,subsegmentDuration:o,SAPType:u,SAPDeltaTime:l})}}};var Aa=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ka=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Pa=class extends J{constructor(e,t){switch(super(e,t),this.readUint8()){case 0:this.stereoMode=0;break;case 1:this.stereoMode=1;break;case 2:this.stereoMode=2;break;case 3:this.stereoMode=3;break;case 4:this.stereoMode=4;break}this.cursor+=1}};var Ra=class extends J{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var La=class extends J{constructor(e,t){super(e,t),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}};var $a=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ma=class extends J{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 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 J{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var Va=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var _a=class extends J{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 Oa=class extends J{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 Fa=class extends J{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 Na=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ua=class extends J{constructor(e,t){super(e,t),this.entryCount=this.readUint32(),this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+8,this.content.byteLength-8))}};var qa=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+78,this.content.byteLength-78))}};var xM={ftyp:Ta,moov:Ia,mvhd:Ea,moof:xa,mdat:wa,sidx:mi,trak:Aa,mdia:$a,mfhd:Ba,tkhd:Ma,traf:Va,tfhd:_a,tfdt:Oa,trun:Fa,minf:Da,sv3d:ka,st3d:Pa,prhd:Ra,proj:Ca,equi:La,uuid:ya,stbl:Na,stsd:Ua,avc1:qa,unknown:dr},Pt=class a{constructor(e={}){this.options={offset:0,...e}}parse(e){let t=[],i=this.options.offset;for(;i<e.byteLength;)try{let s=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+i+4,4)),n=this.createBox(s,new DataView(e.buffer,e.byteOffset+i));if(!n.size)break;t.push(n),i+=n.size}catch{break}return t}createBox(e,t){let i=xM[e];return i?new i(t,new a):new dr(t,new a)}};var Qt=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(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 AM=new TextDecoder("ascii"),kM=a=>AM.decode(new DataView(a.buffer,a.byteOffset+4,4))==="ftyp",PM=a=>{let e=new mi(a,new Pt),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,o={status:"none",time:{from:t,to:t+n},byte:{from:i,to:i+s.referencedSize-1}};return t+=n,i+=s.referencedSize,o})},RM=(a,e)=>{let i=new Pt().parse(a),r=new Qt(i),s=r.findAll("moof"),n=e?r.findAll("uuid"):r.findAll("mdat");if(!(n.length&&s.length))return null;let o=s[0],u=n[n.length-1],l=o.source.byteOffset,d=u.source.byteOffset-o.source.byteOffset+u.size;return new DataView(a.buffer,l,d)},LM=a=>{let t=new Pt().parse(a),i=new Qt(t),r={},s=i.findAll("uuid");return s.length?s[s.length-1]:r},$M=a=>{let t=new Pt().parse(a);return new Qt(t).find("sidx")?.timescale},MM=(a,e)=>{let i=new Pt().parse(a),s=new Qt(i).findAll("traf"),n=s[s.length-1].children.find(d=>d.type==="tfhd"),o=s[s.length-1].children.find(d=>d.type==="tfdt"),u=s[s.length-1].children.find(d=>d.type==="trun"),l=0;return u.sampleDuration.length?l=u.sampleDuration.reduce((d,p)=>d+p,0):l=n.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+l)/e*1e3},DM=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 Pt().parse(a),r=new Qt(i);if(r.find("sv3d")){e.is3dVideo=!0;let n=r.find("st3d");n&&(e.stereoMode=n.stereoMode);let o=r.find("prhd");o&&(e.projectionData.pose.yaw=o.poseYawDegrees,e.projectionData.pose.pitch=o.posePitchDegrees,e.projectionData.pose.roll=o.poseRollDegrees);let u=r.find("equi");u&&(e.projectionData.bounds.top=u.projectionBoundsTop,e.projectionData.bounds.right=u.projectionBoundsRight,e.projectionData.bounds.bottom=u.projectionBoundsBottom,e.projectionData.bounds.left=u.projectionBoundsLeft)}return e},Dv={validateData:kM,parseInit:DM,getIndexRange:()=>{},parseSegments:PM,parseFeedableSegmentChunk:RM,getChunkEndTime:MM,getServerLatencyTimestamps:LM,getTimescaleFromIndex:$M};var Qa=V(Ge(),1);import{assertNonNullable as lc,isNonNullable as _v,isNullable as BM}from"@vkontakte/videoplayer-shared";import{assertNever as CM}from"@vkontakte/videoplayer-shared";var Cv={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"}},Bv=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=Ha(a,t),r=i in Cv,s=r?Cv[i].type:"binary",n=a.getUint8(t),o=0;n&128?o=1:n&64?o=2:n&32?o=3:n&16?o=4:n&8?o=5:n&4?o=6:n&2?o=7:n&1&&(o=8);let u=new DataView(a.buffer,a.byteOffset+t+1,o-1),l=n&255>>o,c=Ha(u),d=l*2**((o-1)*8)+c,p=t+o,h;return p+d>a.byteLength?h=new DataView(a.buffer,a.byteOffset+p):h=new DataView(a.buffer,a.byteOffset+p,d),{tag:r?i:"0x"+i.toString(16).toUpperCase(),type:s,tagHeaderSize:p,tagSize:p+d,value:h,valueSize:d}},Ha=(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},rt=(a,e)=>{switch(e){case"int":return a.getInt8(0);case"uint":return Ha(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:CM(e)}},bi=(a,e)=>{let t=0;for(;t<a.byteLength;){let i=new DataView(a.buffer,a.byteOffset+t),r=Bv(i);if(!e(r))return;r.type==="master"&&bi(r.value,e),t=r.value.byteOffset-a.byteOffset+r.valueSize}},Vv=a=>{if(a.getUint32(0)!==440786851)return!1;let e,t,i,r=Bv(a);return bi(r.value,({tag:s,type:n,value:o})=>(s===17143?e=rt(o,n):s===17026?t=rt(o,n):s===17029&&(i=rt(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)};var Ov=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],VM=[231,22612,22743,167,171,163,160,175],_M=a=>{let e,t,i,r,s=!1,n=!1,o=!1,u,l,c=!1,d=0;return bi(a,({tag:p,type:h,value:f,valueSize:b})=>{if(p===21419){let g=rt(f,h);l=Ha(g)}else p!==21420&&(l=void 0);return p===408125543?(e=f.byteOffset,t=f.byteOffset+b):p===357149030?s=!0:p===290298740?n=!0:p===2807729?i=rt(f,h):p===17545?r=rt(f,h):p===21420&&l===475249515?u=rt(f,h):p===374648427?bi(f,({tag:g,type:S,value:T})=>g===30321?(c=rt(T,S)===1,!1):!0):s&&n&&(0,Qa.default)(Ov,p)&&(o=!0),!o}),lc(e,"Failed to parse webm Segment start"),lc(t,"Failed to parse webm Segment end"),lc(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:u,is3dVideo:c,stereoMode:d,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},OM=a=>{if(BM(a.cuesSeekPosition))return;let e=a.segmentStart+a.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},FM=(a,e)=>{let t=!1,i=!1,r=o=>_v(o.time)&&_v(o.position),s=[],n;return bi(a,({tag:o,type:u,value:l})=>{switch(o){case 475249515:t=!0;break;case 187:n&&r(n)&&s.push(n),n={};break;case 179:n&&(n.time=rt(l,u));break;case 183:break;case 241:n&&(n.position=rt(l,u));break;default:t&&(0,Qa.default)(Ov,o)&&(i=!0)}return!(t&&i)}),n&&r(n)&&s.push(n),s.map((o,u)=>{let{time:l,position:c}=o,d=s[u+1];return{status:"none",time:{from:l,to:d?d.time:e.segmentDuration},byte:{from:e.segmentStart+c,to:d?e.segmentStart+d.position-1:e.segmentEnd-1}}})},NM=a=>{let e=0,t=!1;try{bi(a,i=>i.tag===524531317?i.tagSize<=a.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):(0,Qa.default)(VM,i.tag)?(e+i.tagSize<=a.byteLength&&(e+=i.tagSize,t||=(0,Qa.default)([163,160,175],i.tag)),!0):!1)}catch{}return e>0&&e<=a.byteLength&&t?new DataView(a.buffer,a.byteOffset,e):null},Fv={validateData:Vv,parseInit:_M,getIndexRange:OM,parseSegments:FM,parseFeedableSegmentChunk:NM};var vt=a=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(a);if(e){let[,t,i]=e;if(t==="audio"||t==="video")switch(i){case"webm":return Fv;case"mp4":return Dv}}throw new ReferenceError(`Unsupported mime type ${a}`)};var yt=a=>a instanceof DOMException&&(a.name==="AbortError"||a.code===20);var bc=V(sy(),1),ky=V(qi(),1),Py=V(Ty(),1),Ry=V(bt(),1),gc=V(Zi(),1);var Iy=V(Ge(),1),mc=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(),o=s+n;return(0,Iy.default)(["6E","7A","F4"],o)}}return!1};import{isNonNullable as VD,isNullable as wy}from"@vkontakte/videoplayer-shared";var Ey=a=>{if(a.includes("/")){let e=a.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(a)};var xy=a=>{try{let e=BD(),t=a.match(e),{groups:i}=t??{};if(i){let r={};if(i.extensions){let o=i.extensions.toLowerCase().match(/(?:[0-9a-wy-z](?:-[a-z0-9]{2,8})+)/g);Array.from(o||[]).forEach(u=>{r[u[0]]=u.slice(2)})}let s=i.variants?.split(/-/).filter(o=>o!==""),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(o=>{let u=n[o];(typeof u>"u"||u==="")&&delete n[o]}),n}return null}catch{return null}};function BD(){let a="(?<extlang>(?:[a-z]{3}(?:-[a-z]{3}){0,2}))",e="x(?:-[a-z0-9]{1,8})+",c=`^(?:(?<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 Ay=a=>{if(!a?.startsWith("P"))return;let e=(n,o)=>{let u=n?parseFloat(n.replace(",",".")):NaN;return(isNaN(u)?0:u)*o},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},at=(a,e)=>{let t=a;t=(0,bc.default)(t,"$$","$");let i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[r,s]of(0,ky.default)(i)){let n=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=(0,bc.default)(t,n,(o,u)=>wy(s)?o:wy(u)?s:(0,Py.default)(s,parseInt(u,10),"0"))}return t},qn=(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($=>$.textContent?.trim()??""),o=(0,Ry.default)(n,0)??"",u=s.getAttribute("type")==="dynamic",l=s.getAttribute("availabilityStartTime"),c=s.getAttribute("publishTime"),d=s.getElementsByTagName("vk:Attrs")[0],p=d?.getElementsByTagName("vk:XLatestSegmentPublishTime")[0].textContent,h=d?.getElementsByTagName("vk:XStreamIsLive")[0].textContent,f=d?.getElementsByTagName("vk:XStreamIsUnpublished")[0].textContent,b=d?.getElementsByTagName("vk:XPlaybackDuration")[0].textContent,g;u&&(g={availabilityStartTime:l?new Date(l).getTime():0,publishTime:c?new Date(c).getTime():0,latestSegmentPublishTime:p?new Date(p).getTime():0,streamIsAlive:h==="yes",streamIsUnpublished:f==="yes"});let S,T=s.getAttribute("mediaPresentationDuration"),v=[...s.getElementsByTagName("Period")],x=v.reduce(($,y)=>({...$,[y.id]:y.children}),{}),w=v.reduce(($,y)=>({...$,[y.id]:y.getAttribute("duration")}),{});T?S=Ay(T):(0,gc.default)(w).filter($=>$).length&&!u?S=(0,gc.default)(w).reduce(($,y)=>$+(Ay(y)??0),0):b&&(S=parseInt(b,10));let L=0,B=s.getAttribute("profiles")?.split(",")??[];for(let $ of v.map(y=>y.id))for(let y of x[$]){let M=y.getAttribute("id")??"id"+(L++).toString(10),I=y.getAttribute("mimeType")??"",E=y.getAttribute("codecs")??"",k=y.getAttribute("contentType")??I?.split("/")[0],Z=y.getAttribute("profiles")?.split(",")??[],D=xy(y.getAttribute("lang")??"")??{},q=y.querySelector("Label")?.textContent?.trim()??void 0,X=y.querySelectorAll("Representation"),ie=y.querySelector("SegmentTemplate"),oe=y.querySelector("Role")?.getAttribute("value")??void 0,he=k,fe={id:M,language:D.language,isDefault:oe==="main",label:q,codecs:E,hdr:he==="video"&&mc(E),mime:I,representations:[]};for(let j of X){let N=j.getAttribute("lang")??void 0,Ae=q??y.getAttribute("label")??j.getAttribute("label")??void 0,Te=j.querySelector("BaseURL")?.textContent?.trim()??"",ue=new URL(Te||o,e).toString(),je=j.getAttribute("mimeType")??I,Ct=j.getAttribute("codecs")??E??"",ot;if(k==="text"){let Be=j.getAttribute("id")||"",Bt=D.privateuse?.includes("x-auto")||Be.includes("_auto"),ut=j.querySelector("SegmentTemplate");if(ut){let Pr={representationId:j.getAttribute("id")??void 0,bandwidth:j.getAttribute("bandwidth")??void 0},Ts=parseInt(j.getAttribute("bandwidth")??"",10)/1e3,Is=parseInt(ut.getAttribute("startNumber")??"",10)??1,ki=parseInt(ut.getAttribute("timescale")??"",10),No=ut.querySelectorAll("SegmentTimeline S")??[],Pi=ut.getAttribute("media");if(!Pi)continue;let Es=[],xs=0,ws="",Ri=0,Rr=Is,Ie=0;for(let Xe of No){let Zt=parseInt(Xe.getAttribute("d")??"",10),Qe=parseInt(Xe.getAttribute("r")??"",10)||0,Vt=parseInt(Xe.getAttribute("t")??"",10);Ie=Number.isFinite(Vt)?Vt:Ie;let ei=Zt/ki*1e3,Li=Ie/ki*1e3;for(let lt=0;lt<Qe+1;lt++){let _t=at(Pi,{...Pr,segmentNumber:Rr.toString(10),segmentTime:(Ie+lt*Zt).toString(10)}),$i=(Li??0)+lt*ei,$r=$i+ei;Rr++,Es.push({time:{from:$i,to:$r},url:_t})}Ie+=(Qe+1)*Zt,xs+=(Qe+1)*ei}Ri=Ie/ki*1e3,ws=at(Pi,{...Pr,segmentNumber:Rr.toString(10),segmentTime:Ie.toString(10)});let Lr={time:{from:Ri,to:1/0},url:ws},It={type:"template",baseUrl:ue,segmentTemplateUrl:Pi,initUrl:"",totalSegmentsDurationMs:xs,segments:Es,nextSegmentBeyondManifest:Lr,timescale:ki};ot={id:Be,kind:"text",segmentReference:It,profiles:[],duration:S,bitrate:Ts,mime:"",codecs:"",width:0,height:0,isAuto:Bt}}else ot={id:Be,isAuto:Bt,kind:"text",url:ue}}else{let Be=j.getAttribute("contentType")??je?.split("/")[0]??k,Bt=y.getAttribute("profiles")?.split(",")??[],ut=parseInt(j.getAttribute("width")??"",10),Pr=parseInt(j.getAttribute("height")??"",10),Ts=parseInt(j.getAttribute("bandwidth")??"",10)/1e3,Is=j.getAttribute("frameRate")??"",ki=j.getAttribute("quality")??void 0,No=Is?Ey(Is):void 0,Pi=j.getAttribute("id")??"id"+(L++).toString(10),Es=Be==="video"?`${Pr}p`:Be==="audio"?`${Ts}Kbps`:Ct,xs=`${Pi}@${Es}`,ws=[...B,...Z,...Bt],Ri,Rr=j.querySelector("SegmentBase"),Ie=j.querySelector("SegmentTemplate")??ie;if(Rr){let It=j.querySelector("SegmentBase Initialization")?.getAttribute("range")??"",[Xe,Zt]=It.split("-").map(_t=>parseInt(_t,10)),Qe={from:Xe,to:Zt},Vt=j.querySelector("SegmentBase")?.getAttribute("indexRange"),[ei,Li]=Vt?Vt.split("-").map(_t=>parseInt(_t,10)):[],lt=Vt?{from:ei,to:Li}:void 0;Ri={type:"byteRange",url:ue,initRange:Qe,indexRange:lt}}else if(Ie){let It={representationId:j.getAttribute("id")??void 0,bandwidth:j.getAttribute("bandwidth")??void 0},Xe=parseInt(Ie.getAttribute("timescale")??"",10),Zt=Ie.getAttribute("initialization")??"",Qe=Ie.getAttribute("media"),Vt=parseInt(Ie.getAttribute("startNumber")??"",10)??1,ei=at(Zt,It);if(!Qe)throw new ReferenceError("No media attribute in SegmentTemplate");let Li=Ie.querySelectorAll("SegmentTimeline S")??[],lt=[],_t=0,$i="",$r=0;if(Li.length){let As=Vt,Je=0;for(let Mi of Li){let ct=parseInt(Mi.getAttribute("d")??"",10),ti=parseInt(Mi.getAttribute("r")??"",10)||0,ks=parseInt(Mi.getAttribute("t")??"",10);Je=Number.isFinite(ks)?ks:Je;let Uo=ct/Xe*1e3,SI=Je/Xe*1e3;for(let Ps=0;Ps<ti+1;Ps++){let vI=at(Qe,{...It,segmentNumber:As.toString(10),segmentTime:(Je+Ps*ct).toString(10)}),Pd=(SI??0)+Ps*Uo,yI=Pd+Uo;As++,lt.push({time:{from:Pd,to:yI},url:vI})}Je+=(ti+1)*ct,_t+=(ti+1)*Uo}$r=Je/Xe*1e3,$i=at(Qe,{...It,segmentNumber:As.toString(10),segmentTime:Je.toString(10)})}else if(_D(S)){let Je=parseInt(Ie.getAttribute("duration")??"",10)/Xe*1e3,Mi=Math.ceil(S/Je),ct=0;for(let ti=1;ti<Mi;ti++){let ks=at(Qe,{...It,segmentNumber:ti.toString(10),segmentTime:ct.toString(10)});lt.push({time:{from:ct,to:ct+Je},url:ks}),ct+=Je}$r=ct,$i=at(Qe,{...It,segmentNumber:Mi.toString(10),segmentTime:ct.toString(10)})}let gI={time:{from:$r,to:1/0},url:$i};Ri={type:"template",baseUrl:ue,segmentTemplateUrl:Qe,initUrl:ei,totalSegmentsDurationMs:_t,segments:lt,nextSegmentBeyondManifest:gI,timescale:Xe}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!Be||!je)continue;let Lr={video:"video",audio:"audio",text:"text"}[Be];if(!Lr)continue;he||=Lr,ot={id:xs,kind:Lr,segmentReference:Ri,profiles:ws,duration:S,bitrate:Ts,mime:je,codecs:Ct,width:ut,height:Pr,fps:No,quality:ki}}fe.language||=N,fe.label||=Ae,fe.mime||=je,fe.codecs||=Ct,fe.hdr||=he==="video"&&mc(Ct),fe.representations.push(ot)}if(he){let j=r[he].find(N=>N.id===fe.id);if(j&&fe.representations.every(N=>N.segmentReference.type==="template"))for(let N of j.representations){let Te=fe.representations.find(je=>je.id===N.id)?.segmentReference,ue=N.segmentReference;ue.segments.push(...Te.segments),ue.nextSegmentBeyondManifest=Te.nextSegmentBeyondManifest}else r[he].push(fe)}}return{duration:S,streams:r,baseUrls:n,live:g}};var Sc=V(bt(),1);import{videoSizeToQuality as OD}from"@vkontakte/videoplayer-shared";var Ly=({id:a,width:e,height:t,bitrate:i,fps:r,quality:s,streamId:n})=>{let o=(s?Ht(s):void 0)??OD({width:e,height:t});return o&&{id:a,quality:o,bitrate:i,size:{width:e,height:t},fps:r,streamId:n}},$y=({id:a,bitrate:e})=>({id:a,bitrate:e}),My=({language:a,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:a,label:e}),Dy=({language:a,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:a,label:e}),vc=({id:a,language:e,label:t,codecs:i,isDefault:r})=>({id:a,language:e,label:t,codec:(0,Sc.default)(i.split("."),0),isDefault:r}),yc=({id:a,language:e,label:t,hdr:i,codecs:r})=>({id:a,language:e,hdr:i,label:t,codec:(0,Sc.default)(r.split("."),0)}),Tc=a=>"url"in a,Ue=a=>a.type==="template";import{isNonNullable as Cy}from"@vkontakte/videoplayer-shared";var C=(a,e)=>Cy(a)&&Cy(e)&&a.readyState==="open"&&FD(a,e);function FD(a,e){for(let t=0;t<a.activeSourceBuffers.length;++t)if(a.activeSourceBuffers[t]===e)return!0;return!1}var Ga=class{constructor(e,t,i,{fetcher:r,tuning:s,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new gi(0);this.currentLowLatencySegmentLength$=new gi(0);this.currentSegmentLength$=new gi(0);this.onLastSegment$=new gi(!1);this.fullyBuffered$=new gi(!1);this.playingRepresentation$=new gi(void 0);this.playingRepresentationInit$=new gi(void 0);this.error$=new UD;this.gaps=[];this.subscription=new qD;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new K;this.switchAbortController=new K;this.destroyAbortController=new K;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);De(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new Mv(this.sourceBuffer),this.subscription.add(Ic(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let o,u=this.mediaSource.readyState;u!=="open"&&(o={id:`SegmentEjection_source_${u}`,category:Rt.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o??={id:"SegmentEjection",category:Rt.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n},this.error$.next(o)})),this.subscription.add(Ic(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:Rt.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o||!C(this.mediaSource,this.sourceBuffer))return;let u=Math.min(this.bufferLimit,cr(this.sourceBuffer.buffered)*.8);this.bufferLimit=u;let l=this.getForwardBufferDuration(o),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(o,n*2,l<c).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);De(i,"No init buffer for starting representation"),De(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(!C(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);De(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),De(r,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!C(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();mr(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(!C(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);De(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),De(r,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!C(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();mr(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,Qn.default)(e,u=>u.representations)??[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let u of this.representations.keys()){let l=t.find(p=>p.id===u);l&&this.representations.set(u,l);let c=this.representations.get(u);if(!c||!Ue(c.segmentReference))return;let d=this.getActualLiveStartingSegments(c.segmentReference);this.segments.set(c.id,d)}let i=this.switchingToRepresentationId??this.downloadingRepresentationId,r=this.representations.get(i);De(r);let s=this.segments.get(i);De(s,"No segments for starting representation");let n=this.initData.get(i);if(De(n,"No init buffer for starting representation"),!(n instanceof ArrayBuffer))return;let o=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,yield this.abort(),o&&(yield this.sourceBufferTaskQueue.remove(o.from*1e3,o.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=u,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=o,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){!C(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new K,Gt(this.switchAbortController.signal,async function*(i,r=!1){this.switchingToRepresentationId=i;let s=this.representations.get(i);De(s,`No such representation ${i}`);let n=this.segments.get(i),o=this.initData.get(i);if(ve(o)||ve(n)?yield this.loadInit(s,"high",!1):o instanceof Promise&&(yield o),n=this.segments.get(i),De(n,"No segments for starting representation"),o=this.initData.get(i),!(!(o instanceof ArrayBuffer)||!this.sourceBuffer||!C(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(o,this.downloadAbortController.signal),r)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=i,yield this.dropBuffer();else{let u=this.getCurrentPosition();mr(u)&&!this.isLive&&(this.bufferLimit=this.forwardBufferTarget,yield this.pruneBuffer(u,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 K,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(ve(e)||ve(this.downloadingRepresentationId)||ve(this.playingRepresentationId)||ve(this.sourceBuffer)||!C(this.mediaSource,this.sourceBuffer)||mr(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if(De(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;let r=i.find(c=>e>=c.time.from&&e<c.time.to);mr(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),d=r?r.time.to+n:-1/0;r&&r.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&c>=r.time.to-e+n&&(s=d)}if(isFinite(this.bufferLimit)&&cr(this.sourceBuffer.buffered)>=this.bufferLimit){let c=this.getForwardBufferDuration(e),d=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,c<d).catch(p=>{this.handleAsyncError(p,"pruneBuffer")});return}let u=[];if(!this.activeSegments.size&&(u=this.selectForwardBufferSegments(i,t.segmentReference.type,s),u.length)){let c="auto";if(this.tuning.dash.useFetchPriorityHints&&r)if((0,jn.default)(u,r))c="high";else{let d=(0,Si.default)(u,0);d&&d.time.from-r.time.to>=this.forwardBufferTarget/2&&(c="low")}this.loadSegments(u,t,c).catch(d=>{this.handleAsyncError(d,"loadSegments")})}(!this.preloadOnly&&!this.allInitsLoaded&&r&&r.status==="fed"&&!u.length&&this.getForwardBufferDuration(e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let l=(0,Si.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;mr(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,Qn.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,Qn.default)(e?.streams[this.kind],i=>i.representations)??[];if(![...this.segments.values()].every(i=>!i.length))for(let i of t){if(!i||!Ue(i.segmentReference))return;let r=i.segmentReference.segments.map(l=>({...l,status:"none",size:void 0})),s=100,n=this.segments.get(i.id)??[],o=(0,Si.default)(n,-1)?.time.to??0,u=r?.findIndex(l=>o>=l.time.from+s&&o<=l.time.to+s);if(u===-1){this.liveUpdateSegmentIndex=0;let l=this.getActualLiveStartingSegments(i.segmentReference);this.segments.set(i.id,l)}else{let l=r.slice(u+1);this.segments.set(i.id,[...n,...l])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;De(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(0,Si.default)(e,-1)?.time.to||0}updateLowLatencyLiveIfNeeded(e){let t=0;for(let i of this.representations.values()){let r=i.segmentReference;if(!Ue(r))return;let s=this.segments.get(i.id)??[],n=s.find(u=>Math.floor(u.time.from)===Math.floor(e.time.from));if(n&&!isFinite(n.time.to)&&(n.time.to=e.time.to,t=n.time.to-n.time.from),!!!s.find(u=>Math.floor(u.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let u=Math.round(e.time.to*r.timescale/1e3).toString(10),l=at(r.segmentTemplateUrl,{segmentTime:u});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&&St&&St(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&St&&St(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:p,time:{from:h,to:f}},b)=>{let g=h<=i&&f>=i,S=h>i||g||b===0&&i===0,T=Math.min(this.forwardBufferTarget,this.bufferLimit),v=this.preloadOnly&&h<=i+T||r<T&&f-h>=T||f<=i+T;return(p==="none"||p==="partially_ejected"&&S&&v&&this.sourceBuffer&&C(this.mediaSource,this.sourceBuffer)&&!(Se(this.sourceBuffer.buffered,h)&&Se(this.sourceBuffer.buffered,f)))&&S&&v});if(s===-1)return[];if(t!=="byteRange")return e.slice(s,s+1);let n=e,o=0,u=0,l=[],c=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,d=this.preloadOnly?this.forwardBufferTarget:0;for(let p=s;p<n.length&&(o<=c||u<=d);p++){let h=n[p];if(o+=h.byte.to+1-h.byte.from,u+=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"){Ue(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:o,onProgress:u,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(await Gt(o,async function*(){let c=Ec(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(d=>setTimeout(d,c))}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let c=await this.fetcher.fetch(n,{range:s,signal:o,onProgress:u,priority:i,isLowLatency:this.isActiveLowLatency()});if(this.lastDataObtainedTimestampMs=Hn(),!c)return;let d=new DataView(c),p=vt(t.mime);if(!isFinite(r.segment.time.to)){let b=t.segmentReference.timescale;r.segment.time.to=p.getChunkEndTime(d,b)}u&&r.feedingBytes&&l?await Promise.all(l):await this.sourceBufferTaskQueue.append(d,o);let{serverDataReceivedTimestamp:h,serverDataPreparedTime:f}=p.getServerLatencyTimestamps(d);h&&f&&this.currentLiveSegmentServerLatency$.next(f-h),r.segment.status="downloaded",this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(c){this.abortActiveSegments([e]),yt(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())Ue(t.segmentReference)?t.segmentReference.baseUrl=e:t.segmentReference.url=e}async loadByteRangeSegments(e,t,i="auto"){if(!e.length)return;for(let u of e)u.status="downloading",this.activeSegments.add({segment:u,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:r,url:s,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(await Gt(n,async function*(){let u=Ec(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),Ic(window,"online").pipe(ND()).subscribe(()=>{l(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(s,{range:r,onProgress:o,signal:n,priority:i}),this.lastDataObtainedTimestampMs=Hn(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),yt(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}prepareByteRangeFetchSegmentParams(e,t){if(Ue(t.segmentReference))throw new Error("Representation is not byte range type");let i=t.segmentReference.url,r={from:(0,Si.default)(e,0).byte.from,to:(0,Si.default)(e,-1).byte.to},{signal:s}=this.downloadAbortController;return{url:i,range:r,signal:s,onProgress:async(o,u)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=Hn(),await this.onSomeByteRangesDataLoaded({dataView:o,loaded:u,signal:s,onSegmentAppendFailed:()=>this.abort(),globalFrom:r?r.from:0,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:Rt.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!Ue(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=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(l,c)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=Hn();let d=this.onSomeTemplateDataLoaded({dataView:l,loaded:c,signal:s,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(d)}catch(d){this.error$.next({id:"SegmentFeeding",category:Rt.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:d})}}:void 0;return{url:r,signal:s,onProgress:u,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)(0,jn.default)(e,t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:r,signal:s}){if(!this.activeSegments.size||!C(this.mediaSource,this.sourceBuffer))return;let n=this.representations.get(t);if(n)for(let o of this.activeSegments){let{segment:u}=o;if(o.representationId===t){if(s.aborted){r();continue}if(o.loadedBytes=i,o.loadedBytes>o.feedingBytes){let l=new DataView(e.buffer,e.byteOffset+o.feedingBytes,o.loadedBytes-o.feedingBytes),c=vt(n.mime).parseFeedableSegmentChunk(l,this.isLive);c?.byteLength&&(u.status="partially_fed",o.feedingBytes+=c.byteLength,await this.sourceBufferTaskQueue.append(c),o.fedBytes+=c.byteLength)}}}}async onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:s,onSegmentAppendFailed:n}){if(!this.activeSegments.size||!C(this.mediaSource,this.sourceBuffer))return;let o=this.representations.get(t);if(o)for(let u of this.activeSegments){let{segment:l}=u;if(u.representationId!==t)continue;if(s.aborted){await n();continue}let c=l.byte.from-i,d=l.byte.to-i,p=d-c+1,h=c<r,f=d<=r;if(!h)continue;let b=vt(o.mime);if(l.status==="downloading"&&f){l.status="downloaded";let g=new DataView(e.buffer,e.byteOffset+c,p);await this.sourceBufferTaskQueue.append(g,s)&&!s.aborted?this.onSegmentFullyAppended(u,t):await n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(l.status==="downloading"||l.status==="partially_fed")&&(u.loadedBytes=Math.min(p,r-c),u.loadedBytes>u.feedingBytes)){let g=new DataView(e.buffer,e.byteOffset+c+u.feedingBytes,u.loadedBytes-u.feedingBytes),S=u.loadedBytes===p?g:b.parseFeedableSegmentChunk(g);S?.byteLength&&(l.status="partially_fed",u.feedingBytes+=S.byteLength,await this.sourceBufferTaskQueue.append(S,s)&&!s.aborted?(u.fedBytes+=S.byteLength,u.fedBytes===p&&this.onSegmentFullyAppended(u,t)):await n())}}}onSegmentFullyAppended(e,t){if(!(ve(this.sourceBuffer)||!C(this.mediaSource,this.sourceBuffer))){!this.isLive&&_.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:Rt.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",Tc(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=lr(()=>(0,By.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 o=Ec(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,vt(e.mime),r)).then(async o=>{if(!o)return;let{init:u,dataView:l,segments:c}=o,d=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,d);let p=c;this.isLive&&Ue(e.segmentReference)&&(p=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,p),u&&this.parsedInitData.set(e.id,u)}).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:Rt.WTF,message:"loadInit threw",thrown:o})});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||!C(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||ve(e))return!1;let r=[],s=0,n=u=>{u.sort((c,d)=>c.from-d.from);let l=[u[0]];for(let c=1;c<u.length;c++){let{from:d,to:p}=u[c],h=l[l.length-1];h.to>=d?h.to=Math.max(h.to,p):l.push(u[c])}return l},o=u=>{if(s>=t)return r;r.push({...u.time}),r=n(r);let l=Tc(u)?u.size??0:u.byte.to-u.byte.from;s+=l};for(let u of this.segments.values())for(let l of u){let c=l.time.to<=e-this.tuning.dash.bufferPruningSafeZone,d=l.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(c||d)&&l.status==="fed"&&o(l)}for(let u=0;u<this.sourceBuffer.buffered.length;u++){let l=this.sourceBuffer.buffered.start(u)*1e3,c=this.sourceBuffer.buffered.end(u)*1e3,d=0;for(let p of this.segments.values())for(let h of p)(0,jn.default)(["none","partially_ejected"],h.status)&&Math.round(h.time.from)<=Math.round(l)&&Math.round(h.time.to)>=Math.round(c)&&d++;if(d===this.segments.size){let p={time:{from:l,to:c},url:"",status:"none"};o(p)}}if(r.length&&i){let u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let l of this.segments.values())for(let c of l)c.time.from>=e+u&&c.status==="fed"&&o(c)}return 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||!C(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||!C(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||!C(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||ve(e)?0:de(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!(!this.sourceBuffer||!C(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,o=this.sourceBuffer.buffered.end(s)*1e3;if(!(o<=i.time.from||n>=i.time.to)){if(n<=i.time.from&&o>=i.time.to){r=void 0;break}o>i.time.from&&o<i.time.to&&(r.from=o),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||!C(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=lr(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:Rt.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if(ve(this.sourceBuffer)||!C(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),o=Math.ceil(r.time.to),u=e.some(c=>c.from-t<=n&&c.to+t>=o),l=e.filter(c=>n>=c.from&&n<c.to-t||o>c.from+t&&o<=c.to);u||(l.length===1?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:Rt.VIDEO_PIPELINE,thrown:e,message:"Something went wrong"})}};var Wt=a=>{let e=new URL(a);return e.searchParams.set("quic","1"),e.toString()};var Gn=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 Wa,assertNever as Vy,fromEvent as _y,merge as HD,now as za,Subscription as jD,Subject as Oy,ValueSubject as xc,flattenObject as br,ErrorCategory as Ya}from"@vkontakte/videoplayer-shared";var Wn=a=>{let e=new URL(a);return e.searchParams.set("enable-subtitles","yes"),e.toString()};var Yn=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:s=!1}){this.lastConnectionType$=new xc(void 0);this.lastConnectionReused$=new xc(void 0);this.lastRequestFirstBytes$=new xc(void 0);this.recoverableError$=new Oy;this.error$=new Oy;this.abortAllController=new K;this.subscription=new jD;this.fetchManifest=Wa(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=Wt(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=Wn(i));let r=yield this.doFetch(i,{signal:this.abortAllController.signal}).catch(zn);return r?(t.log("success",br({url:i,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(r.headers),r.text()):(t.error("error",br({url:i,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=Wa(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:i,onProgress:r,priority:s="auto",signal:n,measureThroughput:o=!0,isLowLatency:u=!1}={}){let l=e,c=new Headers,d=this.tracer.createComponentTracer("Fetch");if(i)switch(t){case 0:{c.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let M=new URL(l,location.href);M.searchParams.append("bytes",`${i.from}-${i.to}`),l=M.toString();break}default:Vy(t)}this.requestQuic&&(l=Wt(l));let p=this.abortAllController.signal,h;if(n){let M=new K;if(h=HD(_y(this.abortAllController.signal,"abort"),_y(n,"abort")).subscribe(()=>{try{M.abort()}catch(I){zn(I)}}),this.subscription.add(h),this.abortAllController.signal.aborted||n.aborted)try{M.abort()}catch(I){zn(I)}p=M.signal}let f=za();d.log("startRequest",br({url:l,priority:s,rangeMethod:t,range:i,isLowLatency:u,requestStartedAt:f}));let b=yield this.doFetch(l,{priority:s,headers:c,signal:p}),g=za();if(!b)return d.error("error",{message:"No response in request"}),d.end(),h?.unsubscribe(),null;if(this.throughputEstimator?.addRawRtt(g-f),!b.ok||!b.body){h?.unsubscribe();let M=`Fetch error ${b.status}: ${b.statusText}`;return d.error("error",{message:M}),d.end(),Promise.reject(new Error(`Fetch error ${b.status}: ${b.statusText}`))}if(this.onHeadersReceived(b.headers),!r&&!o){h?.unsubscribe();let M=za(),I={requestStartedAt:f,requestEndedAt:M,duration:M-f};return d.log("endRequest",br(I)),d.end(),b.arrayBuffer()}let[S,T]=b.body.tee(),v=S.getReader();o&&this.throughputEstimator?.trackStream(T,u);let x=0,w=new Uint8Array(0),L=!1,B=M=>{h?.unsubscribe(),L=!0,zn(M)},A=Wa(p,async function*({done:M,value:I}){if(x===0&&this.lastRequestFirstBytes$.next(za()-f),p.aborted){h?.unsubscribe();return}if(!M&&I){let E=new Uint8Array(w.length+I.length);E.set(w),E.set(I,w.length),w=E,x+=I.byteLength,r?.(new DataView(w.buffer),x),yield v?.read().then(A,B)}}.bind(this));yield v?.read().then(A,B),h?.unsubscribe();let $=za(),y={failed:L,requestStartedAt:f,requestEndedAt:$,duration:$-f};return L?(d.error("endRequest",br(y)),d.end(),null):(d.log("endRequest",br(y)),d.end(),w.buffer)}.bind(this));this.fetchByteRangeRepresentation=Wa(this.abortAllController.signal,async function*(e,t,i){if(e.type!=="byteRange")return null;let{from:r,to:s}=e.initRange,n=r,o=s,u=!1,l,c;e.indexRange&&(l=e.indexRange.from,c=e.indexRange.to,u=s+1===l,u&&(n=Math.min(l,r),o=Math.max(c,s))),n=Math.min(n,0);let d=yield this.fetch(e.url,{range:{from:n,to:o},priority:i,measureThroughput:!1});if(!d)return null;let p=new DataView(d,r-n,s-n+1);if(!t.validateData(p))throw new Error("Invalid media file");let h=t.parseInit(p),f=e.indexRange??t.getIndexRange(h);if(!f)throw new ReferenceError("No way to load representation index");let b;if(u)b=new DataView(d,f.from-n,f.to-f.from+1);else{let S=yield this.fetch(e.url,{range:f,priority:i,measureThroughput:!1});if(!S)return null;b=new DataView(S)}let g=t.parseSegments(b,h,f);return{init:h,dataView:new DataView(d),segments:g}}.bind(this));this.fetchTemplateRepresentation=Wa(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}=Gn(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:Vy(r)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}async doFetch(e,t){let i=await Ke(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:Ya.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:Ya.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:Ya.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:Ya.FATAL});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${s})`,category:Ya.FATAL})}}},zn=a=>{if(!yt(a))throw a};var Lt=(a,e,t)=>t*e+(1-t)*a,wc=(a,e)=>a.reduce((t,i)=>t+i,0)/e,Fy=(a,e,t,i)=>{let r=0,s=t,n=wc(a,e),o=e<i?e:i;for(let u=0;u<o;u++)a[s]>n?r++:r--,s=(a.length+s-1)%a.length;return Math.abs(r)===o};import{isNullable as QD,ValueSubject as Ny}from"@vkontakte/videoplayer-shared";var zt=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 Ny(e.initial),this.debounced$=new Ny(e.initial);let t=e.label??"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new xe(`raw_${t}`),this.smoothedSeries$=new xe(`smoothed_${t}`),this.reportedSeries$=new xe(`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 o=0;o<this.pastMeasures.length;o++)this.pastMeasures[o]!==void 0&&(t+=(this.pastMeasures[o]-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)&&(QD(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 Kn=class extends zt{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=Lt(this.slow,e,this.params.emaAlphaSlow),this.fast=Lt(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var Xn=class extends zt{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=wc(this.pastMeasures,this.takenMeasures);this.emaSmoothed=Lt(this.emaSmoothed,e,this.params.emaAlpha);let i=Fy(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=i?this.emaSmoothed:t}};var Jn=class extends zt{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?Lt(this.smoothed,t,this.params.emaAlpha):t}};var $t=class{static getSmoothedValue(e,t,i){return i.type==="TwoEma"?new Kn({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new Xn({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 Jn({initial:e,label:"liveEdgeDelay",...t})}};var gr=(a,e)=>{a&&a.playbackRate!==e&&(a.playbackRate=e)};import{isNullable as GD,ValueSubject as WD}from"@vkontakte/videoplayer-shared";var Ka=class a{constructor(e,t){this.currentRepresentation$=new WD(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(!GD(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,o=r.segments[s-1].time.to;if(e<n||e>o)continue;let u=r.segments.find(l=>l.time.from<=e&&l.time.to>=e);!u||this.currentSegment?.time.from===u.time.from&&this.currentSegment.time.to===u.time.to||(this.currentSegment=u,this.currentRepresentation$.next({...i,label:"Live Text",language:"ru",isAuto:!0,url:new URL(u.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&&Ue(t.segmentReference))}};var eo=V(bt(),1);import{assertNever as to}from"@vkontakte/videoplayer-shared";var Uy=(a,{useManagedMediaSource:e,useOldMSEDetection:t})=>{let{containers:i,protocols:r,codecs:s,nativeHlsSupported:n}=_.video,o=(s.h264||s.h265)&&s.aac,u=r.mse&&(!t||!!window.MediaStreamTrack)||r.mms&&e;return a.filter(l=>{switch(l){case"DASH_SEP":return u&&i.mp4&&o;case"DASH_WEBM":return u&&i.webm&&s.vp9&&s.opus;case"DASH_WEBM_AV1":return u&&i.webm&&s.av1&&s.opus;case"DASH_STREAMS":return u&&(i.mp4&&o||i.webm&&(s.vp9||s.av1)&&(s.opus||s.aac));case"DASH_LIVE":return u&&i.mp4&&o;case"DASH_LIVE_CMAF":return u&&i.mp4&&o&&i.cmaf;case"DASH_ONDEMAND":return u&&i.mp4&&o;case"HLS":case"HLS_ONDEMAND":case"HLS_LIVE":case"HLS_LIVE_CMAF":return n;case"MPEG":return i.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return r.webrtc&&r.ws&&s.h264&&(i.mp4||i.webm);default:return to(l)}})},Zn=a=>{let{webmDecodingInfo:e}=_.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:to(a)}return[t,i]},qy=({webmCodec:a,androidPreferredFormat:e,preferMultiStream:t})=>{let i=[...t?["DASH_STREAMS"]:[],...Zn(a),"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]],r=[...t?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]];if(_.device.isAndroid)switch(e){case"mpeg":return["MPEG",...i,"HLS","HLS_ONDEMAND"];case"hls":return["HLS","HLS_ONDEMAND",...i,"MPEG"];case"dash":return[...i,"HLS","HLS_ONDEMAND","MPEG"];case"dash_any_mpeg":return[...r,"MPEG",...Zn(a),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...Zn(a),"MPEG",...r,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...Zn(a),...r,"HLS","HLS_ONDEMAND"];default:to(e)}return _.video.nativeHlsSupported?[...i,"HLS","HLS_ONDEMAND","MPEG"]:[...i,"HLS","HLS_ONDEMAND","MPEG"]},Hy=({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],o,u=_.device.isMac&&_.browser.isSafari;if(_.device.isAndroid)switch(a){case"dash":case"dash_any_mpeg":case"dash_any_webm":case"dash_sep":{o=s;break}case"hls":case"mpeg":{o=n;break}default:to(a)}else _.video.nativeHlsSupported&&!u?o=n:u?o=e?["DASH_LIVE_CMAF","HLS_LIVE_CMAF","HLS_LIVE","DASH_LIVE"]:["HLS_LIVE","DASH_LIVE","DASH_LIVE_CMAF","HLS_LIVE_CMAF"]:o=s;return t?["WEB_RTC_LIVE",...o]:[...o,"WEB_RTC_LIVE"]},Ac=a=>a?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],io=a=>{if(a.size===0)return;if(a.size===1){let t=a.values().next();return(0,eo.default)(t.value.split("."),0)}for(let t of a){let i=(0,eo.default)(t.split("."),0);if(i==="opus"||i==="vp09"||i==="av01")return i}let e=a.values().next();return(0,eo.default)(e.value.split("."),0)};var tC=["timeupdate","progress","play","seeked","stalled","waiting"],iC=["timeupdate","progress","loadeddata","playing","seeked"];var so=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new Gy;this.representationSubscription=new Gy;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 ao;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 ao;this.fetcherError$=new ao;this.liveStreamEndTimestamp=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.forceEnded$=new ao;this.gapWatchdogActive=!1;this.destroyController=new K;this.initManifest=Pc(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=ae(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:st.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=Pc(this.destroyController.signal,async function*(){this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(n=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:st.NETWORK,message:"Failed to load manifest",thrown:n})});if(!e)return null;let t=null;try{t=qn(e??"",this.manifestUrlString)}catch(n){let o=Un(e)??{id:"ManifestParsing",category:st.PARSER,message:"Failed to parse MPD manifest",thrown:n};this.error$.next(o)}if(!t)return null;let i=(n,o,u)=>!!(this.element?.canPlayType?.(o)&&Ne()?.isTypeSupported?.(`${o}; codecs="${u}"`)||n==="text");if(t.live){this.isLive$.next(!!t.live);let{availabilityStartTime:n,latestSegmentPublishTime:o,streamIsUnpublished:u,streamIsAlive:l}=t.live,c=(t.duration??0)/1e3;this.liveSeekableDuration$.next(-1*c),this.liveDuration$.next((o-n)/1e3),this.liveAvailabilityStartTime$.next(t.live.availabilityStartTime);let d="active";l||(d=u?"unpublished":"unexpectedly_down"),this.liveStreamStatus$.next(d)}let r={text:t.streams.text,video:[],audio:[]};for(let n of["video","audio"]){let u=t.streams[n].filter(({mime:d,codecs:p})=>i(n,d,p)),l=new Set(u.map(({codecs:d})=>d)),c=io(l);if(c&&(r[n]=u.filter(({codecs:d})=>d.startsWith(c))),n==="video"){let d=this.tuning.preferHDR,p=r.video.some(f=>f.hdr),h=r.video.some(f=>!f.hdr);_.display.isHDR&&d&&p?r.video=r.video.filter(f=>f.hdr):h&&(r.video=r.video.filter(f=>!f.hdr))}}let s={...t,streams:r};return this.tracer.log("updateManifestEnd",Ja(s)),s}.bind(this));this.initRepresentations=Pc(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initRepresentationsStart",Ja({initialVideo:e,initialAudio:t,sourceHls:i})),Sr(this.manifest),Sr(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let r=p=>{this.representationSubscription.add(Mt(p,"error").pipe(ro(h=>!!this.element?.played.length)).subscribe(h=>{this.error$.next({id:"VideoSource",category:st.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:h})}))};this.source=this.tuning.useManagedMediaSource?gn():new MediaSource;let s=document.createElement("source");if(r(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),this.tuning.useManagedMediaSource&&tr())if(i){let p=document.createElement("source");r(p),p.type="application/x-mpegurl",p.src=i.url,this.element.appendChild(p)}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},o=this.manifest.streams.video.reduce((p,h)=>[...p,...h.representations],[]);if(this.videoBufferManager=new Ga("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],Za(t)){let p=this.manifest.streams.audio.reduce((h,f)=>[...h,...f.representations],[]);this.audioBufferManager=new Ga("audio",this.source,p,n),this.bufferManagers.push(this.audioBufferManager)}Ka.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new Ka(this.manifest.streams.text,n)),this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$));let u=()=>{this.stallWatchdogSubscription?.unsubscribe(),this.currentStallDuration$.next(0)};if(this.representationSubscription.add(vi(...iC.map(p=>Mt(this.element,p))).pipe(yr(p=>this.element?de(this.element.buffered,this.element.currentTime*1e3):0),Xa(),ZD(p=>{p>this.tuning.dash.bufferEmptinessTolerance&&u()})).subscribe(this.bufferLength$)),this.representationSubscription.add(vi(Mt(this.element,"ended"),this.forceEnded$).subscribe(()=>{u()})),this.isLive$.getValue()){this.subscription.add(this.liveDuration$.pipe(Xa()).subscribe(h=>this.liveStreamEndTimestamp=Lc())),this.subscription.add(Mt(this.element,"pause").subscribe(()=>{this.livePauseWatchdogSubscription=Rc(1e3).subscribe(h=>{let f=Ut(this.manifestUrlString,2);this.manifestUrlString=ae(this.manifestUrlString,f+1e3,2),this.liveStreamStatus$.getValue()==="active"&&this.updateManifest()}),this.subscription.add(this.livePauseWatchdogSubscription)})).add(Mt(this.element,"play").subscribe(h=>this.livePauseWatchdogSubscription?.unsubscribe())),this.representationSubscription.add(vr({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(yr(({isActiveLive:h,isLowLatency:f})=>h&&f),Xa()).subscribe(h=>{this.isManualDecreasePlaybackInLive()||gr(this.element,1)})),this.representationSubscription.add(vr({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(vr({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe(ro(({isLive:h})=>h),Xa((h,f)=>f.bufferLength<h.bufferLength),yr(({rtt:h,bufferLength:f,segmentServerLatency:b})=>{let g=Ut(this.manifestUrlString,2);return(h/2+f+b+g)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add(vr({liveBuffer:this.liveBuffer.smoothed$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).subscribe(({liveBuffer:h,isActiveLive:f,isLowLatency:b})=>{if(!b||!f)return;let g=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,S=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,T=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,v=h-g;if(this.isManualDecreasePlaybackInLive())return;let x=1;Math.abs(v)>S&&(x=1+Math.sign(v)*T),gr(this.element,x)})),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(S=>S.getLiveSegmentsToLoadState(this.manifest)?.to??b))-b}this.liveLoadBufferLength$.getValue()!==f&&this.liveLoadBufferLength$.next(f)}));let p=0;this.representationSubscription.add(vr({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(eC(1e3)).subscribe(async({liveLoadBufferLength:h,bufferLength:f})=>{if(!this.element||this.isUpdatingLive)return;let b=this.element.playbackRate,g=Ut(this.manifestUrlString,2),S=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,T=Math.min(S,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*b),v=this.tuning.dashCmafLive.normalizedActualBufferOffset*b,x=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*b,w=isFinite(h)?h:f,L=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),B=S<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next(B);let A="none";if(L?A="active_low_latency":this.isLowLatency$.getValue()&&B?(this.bufferManagers.forEach($=>$.proceedLowLatencyLive()),A="active_low_latency"):g!==0&&w<T?A="live_forward_buffering":w<T+x&&(A="live_with_target_offset"),isFinite(h)&&(p=h>p?h:p),A==="live_forward_buffering"||A==="live_with_target_offset"){let $=p-(T+v),y=this.normolizeLiveOffset(Math.trunc(g+$/b)),M=Math.abs(y-g),I=0;!h||M<=this.tuning.dashCmafLive.offsetCalculationError?I=g:y>0&&M>this.tuning.dashCmafLive.offsetCalculationError&&(I=y),this.manifestUrlString=ae(this.manifestUrlString,I,2)}(A==="live_with_target_offset"||A==="live_forward_buffering")&&(p=0,await this.updateLive())},h=>{this.error$.next({id:"updateLive",category:st.VIDEO_PIPELINE,thrown:h,message:"Failed to update live with subscription"})}))}let l=vi(...this.bufferManagers.map(p=>p.fullyBuffered$)).pipe(yr(()=>this.bufferManagers.every(p=>p.fullyBuffered$.getValue()))),c=vi(...this.bufferManagers.map(p=>p.onLastSegment$)).pipe(yr(()=>this.bufferManagers.some(p=>p.onLastSegment$.getValue()))),d=vr({allBuffersFull:l,someBufferEnded:c}).pipe(Xa(),yr(({allBuffersFull:p,someBufferEnded:h})=>p&&h),ro(p=>p));if(this.representationSubscription.add(vi(this.forceEnded$,d).subscribe(()=>{if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(p=>!p.updating))try{this.source?.endOfStream()}catch(p){this.error$.next({id:"EndOfStream",category:st.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:p})}})),this.representationSubscription.add(vi(...this.bufferManagers.map(p=>p.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 p=this.tuning.dash.sourceOpenTimeout>=0;yield new Promise(h=>{p&&(this.timeoutSourceOpenId=setTimeout(()=>{if(this.source?.readyState==="open"){h();return}this.error$.next({id:"OpenOfStream",category:st.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 p=[this.manifest.duration??0,...(0,$c.default)((0,$c.default)([...this.manifest.streams.audio,...this.manifest.streams.video],h=>h.representations),h=>{let f=[];return h.duration&&f.push(h.duration),Ue(h.segmentReference)&&h.segmentReference.totalSegmentsDurationMs&&f.push(h.segmentReference.totalSegmentsDurationMs),f})];this.source.duration=Math.max(...p)/1e3}this.audioBufferManager&&Za(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=Rc(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),t=>{this.error$.next({id:"GapWatchdog",category:st.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.fetcher=new Yn({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=$t.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.bufferEstimator}),this.initTracerSubscription()}async seekLive(e){Sr(this.element);let t=this.liveStreamStatus$.getValue()!=="active"?Lc()-this.liveStreamEndTimestamp:0,i=this.normolizeLiveOffset(e+t);this.isActiveLive$.next(i===0),this.manifestUrlString=ae(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(){Sr(this.element),this.state$.setState("running"),this.subscription.add(vi(...tC.map(e=>Mt(this.element,e)),Mt(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:st.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(Mt(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(Mt(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=Lc(),s=100,n=this.videoBufferManager?.lastDataObtainedTimestamp??0;this.videoLastDataObtainedTimestamp$.next(n);let o=this.audioBufferManager?.lastDataObtainedTimestamp??0,u=this.videoBufferManager?.getForwardBufferDuration()??0,l=this.audioBufferManager?.getForwardBufferDuration()??0,c=u<s&&r-n>this.tuning.dash.crashOnStallTWithoutDataTimeout,d=this.audioBufferManager&&l<s&&r-o>this.tuning.dash.crashOnStallTWithoutDataTimeout;if((c||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 p=this.normolizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);this.seekLive(p).catch(h=>{this.error$.next({id:"stallIntervalCallback",category:st.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:h})}),i.liveLastOffset=p}else{let p=this.element.currentTime*1e3;this.videoBufferManager?.maintain(p),this.audioBufferManager?.maintain(p),i.position=p}this.tracer.log("stallIntervalCallback",Ja(i))};this.stallWatchdogSubscription?.unsubscribe(),this.stallWatchdogSubscription=Rc(50).subscribe(e,t=>{this.error$.next({id:"StallWatchdogCallback",category:st.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){Sr(this.element),Sr(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()]),!(Qy(this.element)||Qy(this.videoBufferManager))&&(this.videoBufferManager.maintain(i),this.audioBufferManager?.maintain(i),this.element.currentTime=i/1e3,this.tracer.log("seek",Ja({requestedPosition:e,forcePrecise:t,position:i})))}warmUpMediaSourceIfNeeded(e=this.element?.currentTime){Za(this.element)&&Za(this.source)&&Za(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}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=JD(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 o of this.bufferManagers)for(let u of o.gaps)o.playingRepresentation$.getValue()===u.representation&&u.from-n<=r&&u.to+n>r&&(this.element.duration*1e3-u.to<this.tuning.endGapTolerance?s.push(1/0):s.push(u.to));if(s.length){let o=Math.max(...s)+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,o===1/0?this.forceEnded$.next():(this.element.currentTime=o/1e3,i={...i,gapEnds:s,jumpTo:o,resultCurrentTime:this.element.currentTime},this.tracer.log("jumpGap",Ja(i)))}}calculateDurationFromSegments(){return Math.max(this.videoBufferManager?.calculateDurationFromSegments()||0,this.audioBufferManager?.calculateDurationFromSegments()||0)}};var no=class{constructor(e,t){this.fov=e,this.orientation=t}};var oo=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 zy=`attribute vec2 a_vertex;
124
+ `})|(?<privateuse2>${e}))$`.replace(/[\s\t\n]/g,"");return new RegExp(c,"i")}var Ay=a=>{if(!a?.startsWith("P"))return;let e=(n,o)=>{let u=n?parseFloat(n.replace(",",".")):NaN;return(isNaN(u)?0:u)*o},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},at=(a,e)=>{let t=a;t=(0,bc.default)(t,"$$","$");let i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[r,s]of(0,ky.default)(i)){let n=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=(0,bc.default)(t,n,(o,u)=>wy(s)?o:wy(u)?s:(0,Py.default)(s,parseInt(u,10),"0"))}return t},qn=(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($=>$.textContent?.trim()??""),o=(0,Ry.default)(n,0)??"",u=s.getAttribute("type")==="dynamic",l=s.getAttribute("availabilityStartTime"),c=s.getAttribute("publishTime"),d=s.getElementsByTagName("vk:Attrs")[0],p=d?.getElementsByTagName("vk:XLatestSegmentPublishTime")[0].textContent,h=d?.getElementsByTagName("vk:XStreamIsLive")[0].textContent,f=d?.getElementsByTagName("vk:XStreamIsUnpublished")[0].textContent,b=d?.getElementsByTagName("vk:XPlaybackDuration")[0].textContent,g;u&&(g={availabilityStartTime:l?new Date(l).getTime():0,publishTime:c?new Date(c).getTime():0,latestSegmentPublishTime:p?new Date(p).getTime():0,streamIsAlive:h==="yes",streamIsUnpublished:f==="yes"});let S,T=s.getAttribute("mediaPresentationDuration"),v=[...s.getElementsByTagName("Period")],x=v.reduce(($,y)=>({...$,[y.id]:y.children}),{}),w=v.reduce(($,y)=>({...$,[y.id]:y.getAttribute("duration")}),{});T?S=Ay(T):(0,gc.default)(w).filter($=>$).length&&!u?S=(0,gc.default)(w).reduce(($,y)=>$+(Ay(y)??0),0):b&&(S=parseInt(b,10));let L=0,B=s.getAttribute("profiles")?.split(",")??[];for(let $ of v.map(y=>y.id))for(let y of x[$]){let M=y.getAttribute("id")??"id"+(L++).toString(10),I=y.getAttribute("mimeType")??"",E=y.getAttribute("codecs")??"",k=y.getAttribute("contentType")??I?.split("/")[0],Z=y.getAttribute("profiles")?.split(",")??[],D=xy(y.getAttribute("lang")??"")??{},q=y.querySelector("Label")?.textContent?.trim()??void 0,X=y.querySelectorAll("Representation"),ie=y.querySelector("SegmentTemplate"),oe=y.querySelector("Role")?.getAttribute("value")??void 0,he=k,fe={id:M,language:D.language,isDefault:oe==="main",label:q,codecs:E,hdr:he==="video"&&mc(E),mime:I,representations:[]};for(let H of X){let N=H.getAttribute("lang")??void 0,Ae=q??y.getAttribute("label")??H.getAttribute("label")??void 0,Te=H.querySelector("BaseURL")?.textContent?.trim()??"",ue=new URL(Te||o,e).toString(),He=H.getAttribute("mimeType")??I,Ct=H.getAttribute("codecs")??E??"",ot;if(k==="text"){let Be=H.getAttribute("id")||"",Bt=D.privateuse?.includes("x-auto")||Be.includes("_auto"),ut=H.querySelector("SegmentTemplate");if(ut){let Pr={representationId:H.getAttribute("id")??void 0,bandwidth:H.getAttribute("bandwidth")??void 0},Ts=parseInt(H.getAttribute("bandwidth")??"",10)/1e3,Is=parseInt(ut.getAttribute("startNumber")??"",10)??1,ki=parseInt(ut.getAttribute("timescale")??"",10),No=ut.querySelectorAll("SegmentTimeline S")??[],Pi=ut.getAttribute("media");if(!Pi)continue;let Es=[],xs=0,ws="",Ri=0,Rr=Is,Ie=0;for(let Xe of No){let Zt=parseInt(Xe.getAttribute("d")??"",10),Qe=parseInt(Xe.getAttribute("r")??"",10)||0,Vt=parseInt(Xe.getAttribute("t")??"",10);Ie=Number.isFinite(Vt)?Vt:Ie;let ei=Zt/ki*1e3,Li=Ie/ki*1e3;for(let lt=0;lt<Qe+1;lt++){let _t=at(Pi,{...Pr,segmentNumber:Rr.toString(10),segmentTime:(Ie+lt*Zt).toString(10)}),$i=(Li??0)+lt*ei,$r=$i+ei;Rr++,Es.push({time:{from:$i,to:$r},url:_t})}Ie+=(Qe+1)*Zt,xs+=(Qe+1)*ei}Ri=Ie/ki*1e3,ws=at(Pi,{...Pr,segmentNumber:Rr.toString(10),segmentTime:Ie.toString(10)});let Lr={time:{from:Ri,to:1/0},url:ws},It={type:"template",baseUrl:ue,segmentTemplateUrl:Pi,initUrl:"",totalSegmentsDurationMs:xs,segments:Es,nextSegmentBeyondManifest:Lr,timescale:ki};ot={id:Be,kind:"text",segmentReference:It,profiles:[],duration:S,bitrate:Ts,mime:"",codecs:"",width:0,height:0,isAuto:Bt}}else ot={id:Be,isAuto:Bt,kind:"text",url:ue}}else{let Be=H.getAttribute("contentType")??He?.split("/")[0]??k,Bt=y.getAttribute("profiles")?.split(",")??[],ut=parseInt(H.getAttribute("width")??"",10),Pr=parseInt(H.getAttribute("height")??"",10),Ts=parseInt(H.getAttribute("bandwidth")??"",10)/1e3,Is=H.getAttribute("frameRate")??"",ki=H.getAttribute("quality")??void 0,No=Is?Ey(Is):void 0,Pi=H.getAttribute("id")??"id"+(L++).toString(10),Es=Be==="video"?`${Pr}p`:Be==="audio"?`${Ts}Kbps`:Ct,xs=`${Pi}@${Es}`,ws=[...B,...Z,...Bt],Ri,Rr=H.querySelector("SegmentBase"),Ie=H.querySelector("SegmentTemplate")??ie;if(Rr){let It=H.querySelector("SegmentBase Initialization")?.getAttribute("range")??"",[Xe,Zt]=It.split("-").map(_t=>parseInt(_t,10)),Qe={from:Xe,to:Zt},Vt=H.querySelector("SegmentBase")?.getAttribute("indexRange"),[ei,Li]=Vt?Vt.split("-").map(_t=>parseInt(_t,10)):[],lt=Vt?{from:ei,to:Li}:void 0;Ri={type:"byteRange",url:ue,initRange:Qe,indexRange:lt}}else if(Ie){let It={representationId:H.getAttribute("id")??void 0,bandwidth:H.getAttribute("bandwidth")??void 0},Xe=parseInt(Ie.getAttribute("timescale")??"",10),Zt=Ie.getAttribute("initialization")??"",Qe=Ie.getAttribute("media"),Vt=parseInt(Ie.getAttribute("startNumber")??"",10)??1,ei=at(Zt,It);if(!Qe)throw new ReferenceError("No media attribute in SegmentTemplate");let Li=Ie.querySelectorAll("SegmentTimeline S")??[],lt=[],_t=0,$i="",$r=0;if(Li.length){let As=Vt,Je=0;for(let Mi of Li){let ct=parseInt(Mi.getAttribute("d")??"",10),ti=parseInt(Mi.getAttribute("r")??"",10)||0,ks=parseInt(Mi.getAttribute("t")??"",10);Je=Number.isFinite(ks)?ks:Je;let Uo=ct/Xe*1e3,SI=Je/Xe*1e3;for(let Ps=0;Ps<ti+1;Ps++){let vI=at(Qe,{...It,segmentNumber:As.toString(10),segmentTime:(Je+Ps*ct).toString(10)}),Pd=(SI??0)+Ps*Uo,yI=Pd+Uo;As++,lt.push({time:{from:Pd,to:yI},url:vI})}Je+=(ti+1)*ct,_t+=(ti+1)*Uo}$r=Je/Xe*1e3,$i=at(Qe,{...It,segmentNumber:As.toString(10),segmentTime:Je.toString(10)})}else if(VD(S)){let Je=parseInt(Ie.getAttribute("duration")??"",10)/Xe*1e3,Mi=Math.ceil(S/Je),ct=0;for(let ti=1;ti<Mi;ti++){let ks=at(Qe,{...It,segmentNumber:ti.toString(10),segmentTime:ct.toString(10)});lt.push({time:{from:ct,to:ct+Je},url:ks}),ct+=Je}$r=ct,$i=at(Qe,{...It,segmentNumber:Mi.toString(10),segmentTime:ct.toString(10)})}let gI={time:{from:$r,to:1/0},url:$i};Ri={type:"template",baseUrl:ue,segmentTemplateUrl:Qe,initUrl:ei,totalSegmentsDurationMs:_t,segments:lt,nextSegmentBeyondManifest:gI,timescale:Xe}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!Be||!He)continue;let Lr={video:"video",audio:"audio",text:"text"}[Be];if(!Lr)continue;he||=Lr,ot={id:xs,kind:Lr,segmentReference:Ri,profiles:ws,duration:S,bitrate:Ts,mime:He,codecs:Ct,width:ut,height:Pr,fps:No,quality:ki}}fe.language||=N,fe.label||=Ae,fe.mime||=He,fe.codecs||=Ct,fe.hdr||=he==="video"&&mc(Ct),fe.representations.push(ot)}if(he){let H=r[he].find(N=>N.id===fe.id);if(H&&fe.representations.every(N=>N.segmentReference.type==="template"))for(let N of H.representations){let Te=fe.representations.find(He=>He.id===N.id)?.segmentReference,ue=N.segmentReference;ue.segments.push(...Te.segments),ue.nextSegmentBeyondManifest=Te.nextSegmentBeyondManifest}else r[he].push(fe)}}return{duration:S,streams:r,baseUrls:n,live:g}};var Sc=V(bt(),1);import{videoSizeToQuality as _D}from"@vkontakte/videoplayer-shared";var Ly=({id:a,width:e,height:t,bitrate:i,fps:r,quality:s,streamId:n})=>{let o=(s?jt(s):void 0)??_D({width:e,height:t});return o&&{id:a,quality:o,bitrate:i,size:{width:e,height:t},fps:r,streamId:n}},$y=({id:a,bitrate:e})=>({id:a,bitrate:e}),My=({language:a,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:a,label:e}),Dy=({language:a,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:a,label:e}),vc=({id:a,language:e,label:t,codecs:i,isDefault:r})=>({id:a,language:e,label:t,codec:(0,Sc.default)(i.split("."),0),isDefault:r}),yc=({id:a,language:e,label:t,hdr:i,codecs:r})=>({id:a,language:e,hdr:i,label:t,codec:(0,Sc.default)(r.split("."),0)}),Tc=a=>"url"in a,Ue=a=>a.type==="template";import{isNonNullable as Cy}from"@vkontakte/videoplayer-shared";var C=(a,e)=>Cy(a)&&Cy(e)&&a.readyState==="open"&&OD(a,e);function OD(a,e){for(let t=0;t<a.activeSourceBuffers.length;++t)if(a.activeSourceBuffers[t]===e)return!0;return!1}var Ga=class{constructor(e,t,i,{fetcher:r,tuning:s,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new gi(0);this.currentLowLatencySegmentLength$=new gi(0);this.currentSegmentLength$=new gi(0);this.onLastSegment$=new gi(!1);this.fullyBuffered$=new gi(!1);this.playingRepresentation$=new gi(void 0);this.playingRepresentationInit$=new gi(void 0);this.error$=new ND;this.gaps=[];this.subscription=new UD;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new K;this.switchAbortController=new K;this.destroyAbortController=new K;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);De(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new Mv(this.sourceBuffer),this.subscription.add(Ic(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let o,u=this.mediaSource.readyState;u!=="open"&&(o={id:`SegmentEjection_source_${u}`,category:Rt.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o??={id:"SegmentEjection",category:Rt.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n},this.error$.next(o)})),this.subscription.add(Ic(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:Rt.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o||!C(this.mediaSource,this.sourceBuffer))return;let u=Math.min(this.bufferLimit,cr(this.sourceBuffer.buffered)*.8);this.bufferLimit=u;let l=this.getForwardBufferDuration(o),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(o,n*2,l<c).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);De(i,"No init buffer for starting representation"),De(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(!C(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);De(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),De(r,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!C(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();mr(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(!C(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);De(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),De(r,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!C(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();mr(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,Qn.default)(e,u=>u.representations)??[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let u of this.representations.keys()){let l=t.find(p=>p.id===u);l&&this.representations.set(u,l);let c=this.representations.get(u);if(!c||!Ue(c.segmentReference))return;let d=this.getActualLiveStartingSegments(c.segmentReference);this.segments.set(c.id,d)}let i=this.switchingToRepresentationId??this.downloadingRepresentationId,r=this.representations.get(i);De(r);let s=this.segments.get(i);De(s,"No segments for starting representation");let n=this.initData.get(i);if(De(n,"No init buffer for starting representation"),!(n instanceof ArrayBuffer))return;let o=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,yield this.abort(),o&&(yield this.sourceBufferTaskQueue.remove(o.from*1e3,o.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=u,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=o,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){!C(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new K,Gt(this.switchAbortController.signal,async function*(i,r=!1){this.switchingToRepresentationId=i;let s=this.representations.get(i);De(s,`No such representation ${i}`);let n=this.segments.get(i),o=this.initData.get(i);if(ve(o)||ve(n)?yield this.loadInit(s,"high",!1):o instanceof Promise&&(yield o),n=this.segments.get(i),De(n,"No segments for starting representation"),o=this.initData.get(i),!(!(o instanceof ArrayBuffer)||!this.sourceBuffer||!C(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(o,this.downloadAbortController.signal),r)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=i,yield this.dropBuffer();else{let u=this.getCurrentPosition();mr(u)&&!this.isLive&&(this.bufferLimit=this.forwardBufferTarget,yield this.pruneBuffer(u,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 K,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(ve(e)||ve(this.downloadingRepresentationId)||ve(this.playingRepresentationId)||ve(this.sourceBuffer)||!C(this.mediaSource,this.sourceBuffer)||mr(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if(De(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;let r=i.find(c=>e>=c.time.from&&e<c.time.to);mr(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),d=r?r.time.to+n:-1/0;r&&r.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&c>=r.time.to-e+n&&(s=d)}if(isFinite(this.bufferLimit)&&cr(this.sourceBuffer.buffered)>=this.bufferLimit){let c=this.getForwardBufferDuration(e),d=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,c<d).catch(p=>{this.handleAsyncError(p,"pruneBuffer")});return}let u=[];if(!this.activeSegments.size&&(u=this.selectForwardBufferSegments(i,t.segmentReference.type,s),u.length)){let c="auto";if(this.tuning.dash.useFetchPriorityHints&&r)if((0,Hn.default)(u,r))c="high";else{let d=(0,Si.default)(u,0);d&&d.time.from-r.time.to>=this.forwardBufferTarget/2&&(c="low")}this.loadSegments(u,t,c).catch(d=>{this.handleAsyncError(d,"loadSegments")})}(!this.preloadOnly&&!this.allInitsLoaded&&r&&r.status==="fed"&&!u.length&&this.getForwardBufferDuration(e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let l=(0,Si.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;mr(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,Qn.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,Qn.default)(e?.streams[this.kind],i=>i.representations)??[];if(![...this.segments.values()].every(i=>!i.length))for(let i of t){if(!i||!Ue(i.segmentReference))return;let r=i.segmentReference.segments.map(l=>({...l,status:"none",size:void 0})),s=100,n=this.segments.get(i.id)??[],o=(0,Si.default)(n,-1)?.time.to??0,u=r?.findIndex(l=>o>=l.time.from+s&&o<=l.time.to+s);if(u===-1){this.liveUpdateSegmentIndex=0;let l=this.getActualLiveStartingSegments(i.segmentReference);this.segments.set(i.id,l)}else{let l=r.slice(u+1);this.segments.set(i.id,[...n,...l])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;De(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,Si.default)(e,-1)?.time.to:0)||0}updateLowLatencyLiveIfNeeded(e){let t=0;for(let i of this.representations.values()){let r=i.segmentReference;if(!Ue(r))return;let s=this.segments.get(i.id)??[],n=s.find(u=>Math.floor(u.time.from)===Math.floor(e.time.from));if(n&&!isFinite(n.time.to)&&(n.time.to=e.time.to,t=n.time.to-n.time.from),!!!s.find(u=>Math.floor(u.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let u=Math.round(e.time.to*r.timescale/1e3).toString(10),l=at(r.segmentTemplateUrl,{segmentTime:u});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&&St&&St(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&St&&St(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:p,time:{from:h,to:f}},b)=>{let g=h<=i&&f>=i,S=h>i||g||b===0&&i===0,T=Math.min(this.forwardBufferTarget,this.bufferLimit),v=this.preloadOnly&&h<=i+T||r<T&&f-h>=T||f<=i+T;return(p==="none"||p==="partially_ejected"&&S&&v&&this.sourceBuffer&&C(this.mediaSource,this.sourceBuffer)&&!(Se(this.sourceBuffer.buffered,h)&&Se(this.sourceBuffer.buffered,f)))&&S&&v});if(s===-1)return[];if(t!=="byteRange")return e.slice(s,s+1);let n=e,o=0,u=0,l=[],c=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,d=this.preloadOnly?this.forwardBufferTarget:0;for(let p=s;p<n.length&&(o<=c||u<=d);p++){let h=n[p];if(o+=h.byte.to+1-h.byte.from,u+=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"){Ue(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:o,onProgress:u,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(await Gt(o,async function*(){let c=Ec(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(d=>setTimeout(d,c))}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let c=await this.fetcher.fetch(n,{range:s,signal:o,onProgress:u,priority:i,isLowLatency:this.isActiveLowLatency()});if(this.lastDataObtainedTimestampMs=jn(),!c)return;let d=new DataView(c),p=vt(t.mime);if(!isFinite(r.segment.time.to)){let b=t.segmentReference.timescale;r.segment.time.to=p.getChunkEndTime(d,b)}u&&r.feedingBytes&&l?await Promise.all(l):await this.sourceBufferTaskQueue.append(d,o);let{serverDataReceivedTimestamp:h,serverDataPreparedTime:f}=p.getServerLatencyTimestamps(d);h&&f&&this.currentLiveSegmentServerLatency$.next(f-h),r.segment.status="downloaded",this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(c){this.abortActiveSegments([e]),yt(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())Ue(t.segmentReference)?t.segmentReference.baseUrl=e:t.segmentReference.url=e}async loadByteRangeSegments(e,t,i="auto"){if(!e.length)return;for(let u of e)u.status="downloading",this.activeSegments.add({segment:u,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:r,url:s,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(await Gt(n,async function*(){let u=Ec(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),Ic(window,"online").pipe(FD()).subscribe(()=>{l(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(s,{range:r,onProgress:o,signal:n,priority:i}),this.lastDataObtainedTimestampMs=jn(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),yt(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}prepareByteRangeFetchSegmentParams(e,t){if(Ue(t.segmentReference))throw new Error("Representation is not byte range type");let i=t.segmentReference.url,r={from:(0,Si.default)(e,0).byte.from,to:(0,Si.default)(e,-1).byte.to},{signal:s}=this.downloadAbortController;return{url:i,range:r,signal:s,onProgress:async(o,u)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=jn(),await this.onSomeByteRangesDataLoaded({dataView:o,loaded:u,signal:s,onSegmentAppendFailed:()=>this.abort(),globalFrom:r?r.from:0,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:Rt.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!Ue(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=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(l,c)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=jn();let d=this.onSomeTemplateDataLoaded({dataView:l,loaded:c,signal:s,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(d)}catch(d){this.error$.next({id:"SegmentFeeding",category:Rt.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:d})}}:void 0;return{url:r,signal:s,onProgress:u,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)(0,Hn.default)(e,t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:r,signal:s}){if(!this.activeSegments.size||!C(this.mediaSource,this.sourceBuffer))return;let n=this.representations.get(t);if(n)for(let o of this.activeSegments){let{segment:u}=o;if(o.representationId===t){if(s.aborted){r();continue}if(o.loadedBytes=i,o.loadedBytes>o.feedingBytes){let l=new DataView(e.buffer,e.byteOffset+o.feedingBytes,o.loadedBytes-o.feedingBytes),c=vt(n.mime).parseFeedableSegmentChunk(l,this.isLive);c?.byteLength&&(u.status="partially_fed",o.feedingBytes+=c.byteLength,await this.sourceBufferTaskQueue.append(c),o.fedBytes+=c.byteLength)}}}}async onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:s,onSegmentAppendFailed:n}){if(!this.activeSegments.size||!C(this.mediaSource,this.sourceBuffer))return;let o=this.representations.get(t);if(o)for(let u of this.activeSegments){let{segment:l}=u;if(u.representationId!==t)continue;if(s.aborted){await n();continue}let c=l.byte.from-i,d=l.byte.to-i,p=d-c+1,h=c<r,f=d<=r;if(!h)continue;let b=vt(o.mime);if(l.status==="downloading"&&f){l.status="downloaded";let g=new DataView(e.buffer,e.byteOffset+c,p);await this.sourceBufferTaskQueue.append(g,s)&&!s.aborted?this.onSegmentFullyAppended(u,t):await n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(l.status==="downloading"||l.status==="partially_fed")&&(u.loadedBytes=Math.min(p,r-c),u.loadedBytes>u.feedingBytes)){let g=new DataView(e.buffer,e.byteOffset+c+u.feedingBytes,u.loadedBytes-u.feedingBytes),S=u.loadedBytes===p?g:b.parseFeedableSegmentChunk(g);S?.byteLength&&(l.status="partially_fed",u.feedingBytes+=S.byteLength,await this.sourceBufferTaskQueue.append(S,s)&&!s.aborted?(u.fedBytes+=S.byteLength,u.fedBytes===p&&this.onSegmentFullyAppended(u,t)):await n())}}}onSegmentFullyAppended(e,t){if(!(ve(this.sourceBuffer)||!C(this.mediaSource,this.sourceBuffer))){!this.isLive&&_.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:Rt.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",Tc(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=lr(()=>(0,By.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 o=Ec(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,vt(e.mime),r)).then(async o=>{if(!o)return;let{init:u,dataView:l,segments:c}=o,d=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,d);let p=c;this.isLive&&Ue(e.segmentReference)&&(p=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,p),u&&this.parsedInitData.set(e.id,u)}).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:Rt.WTF,message:"loadInit threw",thrown:o})});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||!C(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||ve(e))return!1;let r=[],s=0,n=u=>{u.sort((c,d)=>c.from-d.from);let l=[u[0]];for(let c=1;c<u.length;c++){let{from:d,to:p}=u[c],h=l[l.length-1];h.to>=d?h.to=Math.max(h.to,p):l.push(u[c])}return l},o=u=>{if(s>=t)return r;r.push({...u.time}),r=n(r);let l=Tc(u)?u.size??0:u.byte.to-u.byte.from;s+=l};for(let u of this.segments.values())for(let l of u){let c=l.time.to<=e-this.tuning.dash.bufferPruningSafeZone,d=l.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(c||d)&&l.status==="fed"&&o(l)}for(let u=0;u<this.sourceBuffer.buffered.length;u++){let l=this.sourceBuffer.buffered.start(u)*1e3,c=this.sourceBuffer.buffered.end(u)*1e3,d=0;for(let p of this.segments.values())for(let h of p)(0,Hn.default)(["none","partially_ejected"],h.status)&&Math.round(h.time.from)<=Math.round(l)&&Math.round(h.time.to)>=Math.round(c)&&d++;if(d===this.segments.size){let p={time:{from:l,to:c},url:"",status:"none"};o(p)}}if(r.length&&i){let u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let l of this.segments.values())for(let c of l)c.time.from>=e+u&&c.status==="fed"&&o(c)}return 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||!C(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||!C(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||!C(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||ve(e)?0:de(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!(!this.sourceBuffer||!C(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,o=this.sourceBuffer.buffered.end(s)*1e3;if(!(o<=i.time.from||n>=i.time.to)){if(n<=i.time.from&&o>=i.time.to){r=void 0;break}o>i.time.from&&o<i.time.to&&(r.from=o),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||!C(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=lr(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:Rt.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if(ve(this.sourceBuffer)||!C(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),o=Math.ceil(r.time.to),u=e.some(c=>c.from-t<=n&&c.to+t>=o),l=e.filter(c=>n>=c.from&&n<c.to-t||o>c.from+t&&o<=c.to);u||(l.length===1?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:Rt.VIDEO_PIPELINE,thrown:e,message:"Something went wrong"})}};var Wt=a=>{let e=new URL(a);return e.searchParams.set("quic","1"),e.toString()};var Gn=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 Wa,assertNever as Vy,fromEvent as _y,merge as qD,now as za,Subscription as jD,Subject as Oy,ValueSubject as xc,flattenObject as br,ErrorCategory as Ya}from"@vkontakte/videoplayer-shared";var Wn=a=>{let e=new URL(a);return e.searchParams.set("enable-subtitles","yes"),e.toString()};var Yn=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:s=!1}){this.lastConnectionType$=new xc(void 0);this.lastConnectionReused$=new xc(void 0);this.lastRequestFirstBytes$=new xc(void 0);this.recoverableError$=new Oy;this.error$=new Oy;this.abortAllController=new K;this.subscription=new jD;this.fetchManifest=Wa(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=Wt(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=Wn(i));let r=yield this.doFetch(i,{signal:this.abortAllController.signal}).catch(zn);return r?(t.log("success",br({url:i,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(r.headers),r.text()):(t.error("error",br({url:i,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=Wa(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:i,onProgress:r,priority:s="auto",signal:n,measureThroughput:o=!0,isLowLatency:u=!1}={}){let l=e,c=new Headers,d=this.tracer.createComponentTracer("Fetch");if(i)switch(t){case 0:{c.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let M=new URL(l,location.href);M.searchParams.append("bytes",`${i.from}-${i.to}`),l=M.toString();break}default:Vy(t)}this.requestQuic&&(l=Wt(l));let p=this.abortAllController.signal,h;if(n){let M=new K;if(h=qD(_y(this.abortAllController.signal,"abort"),_y(n,"abort")).subscribe(()=>{try{M.abort()}catch(I){zn(I)}}),this.subscription.add(h),this.abortAllController.signal.aborted||n.aborted)try{M.abort()}catch(I){zn(I)}p=M.signal}let f=za();d.log("startRequest",br({url:l,priority:s,rangeMethod:t,range:i,isLowLatency:u,requestStartedAt:f}));let b=yield this.doFetch(l,{priority:s,headers:c,signal:p}),g=za();if(!b)return d.error("error",{message:"No response in request"}),d.end(),h?.unsubscribe(),null;if(this.throughputEstimator?.addRawRtt(g-f),!b.ok||!b.body){h?.unsubscribe();let M=`Fetch error ${b.status}: ${b.statusText}`;return d.error("error",{message:M}),d.end(),Promise.reject(new Error(`Fetch error ${b.status}: ${b.statusText}`))}if(this.onHeadersReceived(b.headers),!r&&!o){h?.unsubscribe();let M=za(),I={requestStartedAt:f,requestEndedAt:M,duration:M-f};return d.log("endRequest",br(I)),d.end(),b.arrayBuffer()}let[S,T]=b.body.tee(),v=S.getReader();o&&this.throughputEstimator?.trackStream(T,u);let x=0,w=new Uint8Array(0),L=!1,B=M=>{h?.unsubscribe(),L=!0,zn(M)},A=Wa(p,async function*({done:M,value:I}){if(x===0&&this.lastRequestFirstBytes$.next(za()-f),p.aborted){h?.unsubscribe();return}if(!M&&I){let E=new Uint8Array(w.length+I.length);E.set(w),E.set(I,w.length),w=E,x+=I.byteLength,r?.(new DataView(w.buffer),x),yield v?.read().then(A,B)}}.bind(this));yield v?.read().then(A,B),h?.unsubscribe();let $=za(),y={failed:L,requestStartedAt:f,requestEndedAt:$,duration:$-f};return L?(d.error("endRequest",br(y)),d.end(),null):(d.log("endRequest",br(y)),d.end(),w.buffer)}.bind(this));this.fetchByteRangeRepresentation=Wa(this.abortAllController.signal,async function*(e,t,i){if(e.type!=="byteRange")return null;let{from:r,to:s}=e.initRange,n=r,o=s,u=!1,l,c;e.indexRange&&(l=e.indexRange.from,c=e.indexRange.to,u=s+1===l,u&&(n=Math.min(l,r),o=Math.max(c,s))),n=Math.min(n,0);let d=yield this.fetch(e.url,{range:{from:n,to:o},priority:i,measureThroughput:!1});if(!d)return null;let p=new DataView(d,r-n,s-n+1);if(!t.validateData(p))throw new Error("Invalid media file");let h=t.parseInit(p),f=e.indexRange??t.getIndexRange(h);if(!f)throw new ReferenceError("No way to load representation index");let b;if(u)b=new DataView(d,f.from-n,f.to-f.from+1);else{let S=yield this.fetch(e.url,{range:f,priority:i,measureThroughput:!1});if(!S)return null;b=new DataView(S)}let g=t.parseSegments(b,h,f);return{init:h,dataView:new DataView(d),segments:g}}.bind(this));this.fetchTemplateRepresentation=Wa(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}=Gn(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:Vy(r)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}async doFetch(e,t){let i=await Ke(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:Ya.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:Ya.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:Ya.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:Ya.FATAL});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${s})`,category:Ya.FATAL})}}},zn=a=>{if(!yt(a))throw a};var Lt=(a,e,t)=>t*e+(1-t)*a,wc=(a,e)=>a.reduce((t,i)=>t+i,0)/e,Fy=(a,e,t,i)=>{let r=0,s=t,n=wc(a,e),o=e<i?e:i;for(let u=0;u<o;u++)a[s]>n?r++:r--,s=(a.length+s-1)%a.length;return Math.abs(r)===o};import{isNullable as HD,ValueSubject as Ny}from"@vkontakte/videoplayer-shared";var zt=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 Ny(e.initial),this.debounced$=new Ny(e.initial);let t=e.label??"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new xe(`raw_${t}`),this.smoothedSeries$=new xe(`smoothed_${t}`),this.reportedSeries$=new xe(`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 o=0;o<this.pastMeasures.length;o++)this.pastMeasures[o]!==void 0&&(t+=(this.pastMeasures[o]-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)&&(HD(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 Kn=class extends zt{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=Lt(this.slow,e,this.params.emaAlphaSlow),this.fast=Lt(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var Xn=class extends zt{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=wc(this.pastMeasures,this.takenMeasures);this.emaSmoothed=Lt(this.emaSmoothed,e,this.params.emaAlpha);let i=Fy(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=i?this.emaSmoothed:t}};var Jn=class extends zt{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?Lt(this.smoothed,t,this.params.emaAlpha):t}};var $t=class{static getSmoothedValue(e,t,i){return i.type==="TwoEma"?new Kn({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new Xn({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 Jn({initial:e,label:"liveEdgeDelay",...t})}};var gr=(a,e)=>{a&&a.playbackRate!==e&&(a.playbackRate=e)};import{isNullable as QD,ValueSubject as GD}from"@vkontakte/videoplayer-shared";var Ka=class a{constructor(e,t){this.currentRepresentation$=new GD(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(!QD(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,o=r.segments[s-1].time.to;if(e<n||e>o)continue;let u=r.segments.find(l=>l.time.from<=e&&l.time.to>=e);!u||this.currentSegment?.time.from===u.time.from&&this.currentSegment.time.to===u.time.to||(this.currentSegment=u,this.currentRepresentation$.next({...i,label:"Live Text",language:"ru",isAuto:!0,url:new URL(u.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&&Ue(t.segmentReference))}};var eo=V(bt(),1);import{assertNever as to}from"@vkontakte/videoplayer-shared";var Uy=(a,{useManagedMediaSource:e,useOldMSEDetection:t})=>{let{containers:i,protocols:r,codecs:s,nativeHlsSupported:n}=_.video,o=(s.h264||s.h265)&&s.aac,u=r.mse&&(!t||!!window.MediaStreamTrack)||r.mms&&e;return a.filter(l=>{switch(l){case"DASH_SEP":return u&&i.mp4&&o;case"DASH_WEBM":return u&&i.webm&&s.vp9&&s.opus;case"DASH_WEBM_AV1":return u&&i.webm&&s.av1&&s.opus;case"DASH_STREAMS":return u&&(i.mp4&&o||i.webm&&(s.vp9||s.av1)&&(s.opus||s.aac));case"DASH_LIVE":return u&&i.mp4&&o;case"DASH_LIVE_CMAF":return u&&i.mp4&&o&&i.cmaf;case"DASH_ONDEMAND":return u&&i.mp4&&o;case"HLS":case"HLS_ONDEMAND":case"HLS_LIVE":case"HLS_LIVE_CMAF":return n;case"MPEG":return i.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return r.webrtc&&r.ws&&s.h264&&(i.mp4||i.webm);default:return to(l)}})},Zn=a=>{let{webmDecodingInfo:e}=_.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:to(a)}return[t,i]},qy=({webmCodec:a,androidPreferredFormat:e,preferMultiStream:t})=>{let i=[...t?["DASH_STREAMS"]:[],...Zn(a),"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]],r=[...t?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]];if(_.device.isAndroid)switch(e){case"mpeg":return["MPEG",...i,"HLS","HLS_ONDEMAND"];case"hls":return["HLS","HLS_ONDEMAND",...i,"MPEG"];case"dash":return[...i,"HLS","HLS_ONDEMAND","MPEG"];case"dash_any_mpeg":return[...r,"MPEG",...Zn(a),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...Zn(a),"MPEG",...r,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...Zn(a),...r,"HLS","HLS_ONDEMAND"];default:to(e)}return _.video.nativeHlsSupported?[...i,"HLS","HLS_ONDEMAND","MPEG"]:[...i,"HLS","HLS_ONDEMAND","MPEG"]},jy=({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],o,u=_.device.isMac&&_.browser.isSafari;if(_.device.isAndroid)switch(a){case"dash":case"dash_any_mpeg":case"dash_any_webm":case"dash_sep":{o=s;break}case"hls":case"mpeg":{o=n;break}default:to(a)}else _.video.nativeHlsSupported&&!u?o=n:u?o=e?["DASH_LIVE_CMAF","HLS_LIVE_CMAF","HLS_LIVE","DASH_LIVE"]:["HLS_LIVE","DASH_LIVE","DASH_LIVE_CMAF","HLS_LIVE_CMAF"]:o=s;return t?["WEB_RTC_LIVE",...o]:[...o,"WEB_RTC_LIVE"]},Ac=a=>a?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],io=a=>{if(a.size===0)return;if(a.size===1){let t=a.values().next();return(0,eo.default)(t.value.split("."),0)}for(let t of a){let i=(0,eo.default)(t.split("."),0);if(i==="opus"||i==="vp09"||i==="av01")return i}let e=a.values().next();return(0,eo.default)(e.value.split("."),0)};var eC=["timeupdate","progress","play","seeked","stalled","waiting"],tC=["timeupdate","progress","loadeddata","playing","seeked"];var so=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new Gy;this.representationSubscription=new Gy;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 ao;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 ao;this.fetcherError$=new ao;this.liveStreamEndTimestamp=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.forceEnded$=new ao;this.gapWatchdogActive=!1;this.destroyController=new K;this.initManifest=Pc(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=ae(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:st.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=Pc(this.destroyController.signal,async function*(){this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(n=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:st.NETWORK,message:"Failed to load manifest",thrown:n})});if(!e)return null;let t=null;try{t=qn(e??"",this.manifestUrlString)}catch(n){let o=Un(e)??{id:"ManifestParsing",category:st.PARSER,message:"Failed to parse MPD manifest",thrown:n};this.error$.next(o)}if(!t)return null;let i=(n,o,u)=>!!(this.element?.canPlayType?.(o)&&Ne()?.isTypeSupported?.(`${o}; codecs="${u}"`)||n==="text");if(t.live){this.isLive$.next(!!t.live);let{availabilityStartTime:n,latestSegmentPublishTime:o,streamIsUnpublished:u,streamIsAlive:l}=t.live,c=(t.duration??0)/1e3;this.liveSeekableDuration$.next(-1*c),this.liveDuration$.next((o-n)/1e3),this.liveAvailabilityStartTime$.next(t.live.availabilityStartTime);let d="active";l||(d=u?"unpublished":"unexpectedly_down"),this.liveStreamStatus$.next(d)}let r={text:t.streams.text,video:[],audio:[]};for(let n of["video","audio"]){let u=t.streams[n].filter(({mime:d,codecs:p})=>i(n,d,p)),l=new Set(u.map(({codecs:d})=>d)),c=io(l);if(c&&(r[n]=u.filter(({codecs:d})=>d.startsWith(c))),n==="video"){let d=this.tuning.preferHDR,p=r.video.some(f=>f.hdr),h=r.video.some(f=>!f.hdr);_.display.isHDR&&d&&p?r.video=r.video.filter(f=>f.hdr):h&&(r.video=r.video.filter(f=>!f.hdr))}}let s={...t,streams:r};return this.tracer.log("updateManifestEnd",Ja(s)),s}.bind(this));this.initRepresentations=Pc(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initRepresentationsStart",Ja({initialVideo:e,initialAudio:t,sourceHls:i})),Sr(this.manifest),Sr(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let r=p=>{this.representationSubscription.add(Mt(p,"error").pipe(ro(h=>!!this.element?.played.length)).subscribe(h=>{this.error$.next({id:"VideoSource",category:st.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:h})}))};this.source=this.tuning.useManagedMediaSource?gn():new MediaSource;let s=document.createElement("source");if(r(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),this.tuning.useManagedMediaSource&&tr())if(i){let p=document.createElement("source");r(p),p.type="application/x-mpegurl",p.src=i.url,this.element.appendChild(p)}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},o=this.manifest.streams.video.reduce((p,h)=>[...p,...h.representations],[]);if(this.videoBufferManager=new Ga("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],Za(t)){let p=this.manifest.streams.audio.reduce((h,f)=>[...h,...f.representations],[]);this.audioBufferManager=new Ga("audio",this.source,p,n),this.bufferManagers.push(this.audioBufferManager)}Ka.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new Ka(this.manifest.streams.text,n)),this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$));let u=()=>{this.stallWatchdogSubscription?.unsubscribe(),this.currentStallDuration$.next(0)};if(this.representationSubscription.add(vi(...tC.map(p=>Mt(this.element,p))).pipe(yr(p=>this.element?de(this.element.buffered,this.element.currentTime*1e3):0),Xa(),JD(p=>{p>this.tuning.dash.bufferEmptinessTolerance&&u()})).subscribe(this.bufferLength$)),this.representationSubscription.add(vi(Mt(this.element,"ended"),this.forceEnded$).subscribe(()=>{u()})),this.isLive$.getValue()){this.subscription.add(this.liveDuration$.pipe(Xa()).subscribe(h=>this.liveStreamEndTimestamp=Lc())),this.subscription.add(Mt(this.element,"pause").subscribe(()=>{this.livePauseWatchdogSubscription=Rc(1e3).subscribe(h=>{let f=Ut(this.manifestUrlString,2);this.manifestUrlString=ae(this.manifestUrlString,f+1e3,2),this.liveStreamStatus$.getValue()==="active"&&this.updateManifest()}),this.subscription.add(this.livePauseWatchdogSubscription)})).add(Mt(this.element,"play").subscribe(h=>this.livePauseWatchdogSubscription?.unsubscribe())),this.representationSubscription.add(vr({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(yr(({isActiveLive:h,isLowLatency:f})=>h&&f),Xa()).subscribe(h=>{this.isManualDecreasePlaybackInLive()||gr(this.element,1)})),this.representationSubscription.add(vr({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(vr({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe(ro(({isLive:h})=>h),Xa((h,f)=>f.bufferLength<h.bufferLength),yr(({rtt:h,bufferLength:f,segmentServerLatency:b})=>{let g=Ut(this.manifestUrlString,2);return(h/2+f+b+g)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add(vr({liveBuffer:this.liveBuffer.smoothed$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).subscribe(({liveBuffer:h,isActiveLive:f,isLowLatency:b})=>{if(!b||!f)return;let g=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,S=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,T=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,v=h-g;if(this.isManualDecreasePlaybackInLive())return;let x=1;Math.abs(v)>S&&(x=1+Math.sign(v)*T),gr(this.element,x)})),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(S=>S.getLiveSegmentsToLoadState(this.manifest)?.to??b))-b}this.liveLoadBufferLength$.getValue()!==f&&this.liveLoadBufferLength$.next(f)}));let p=0;this.representationSubscription.add(vr({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(ZD(1e3)).subscribe(async({liveLoadBufferLength:h,bufferLength:f})=>{if(!this.element||this.isUpdatingLive)return;let b=this.element.playbackRate,g=Ut(this.manifestUrlString,2),S=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,T=Math.min(S,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*b),v=this.tuning.dashCmafLive.normalizedActualBufferOffset*b,x=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*b,w=isFinite(h)?h:f,L=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),B=S<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next(B);let A="none";if(L?A="active_low_latency":this.isLowLatency$.getValue()&&B?(this.bufferManagers.forEach($=>$.proceedLowLatencyLive()),A="active_low_latency"):g!==0&&w<T?A="live_forward_buffering":w<T+x&&(A="live_with_target_offset"),isFinite(h)&&(p=h>p?h:p),A==="live_forward_buffering"||A==="live_with_target_offset"){let $=p-(T+v),y=this.normolizeLiveOffset(Math.trunc(g+$/b)),M=Math.abs(y-g),I=0;!h||M<=this.tuning.dashCmafLive.offsetCalculationError?I=g:y>0&&M>this.tuning.dashCmafLive.offsetCalculationError&&(I=y),this.manifestUrlString=ae(this.manifestUrlString,I,2)}(A==="live_with_target_offset"||A==="live_forward_buffering")&&(p=0,await this.updateLive())},h=>{this.error$.next({id:"updateLive",category:st.VIDEO_PIPELINE,thrown:h,message:"Failed to update live with subscription"})}))}let l=vi(...this.bufferManagers.map(p=>p.fullyBuffered$)).pipe(yr(()=>this.bufferManagers.every(p=>p.fullyBuffered$.getValue()))),c=vi(...this.bufferManagers.map(p=>p.onLastSegment$)).pipe(yr(()=>this.bufferManagers.some(p=>p.onLastSegment$.getValue()))),d=vr({allBuffersFull:l,someBufferEnded:c}).pipe(Xa(),yr(({allBuffersFull:p,someBufferEnded:h})=>p&&h),ro(p=>p));if(this.representationSubscription.add(vi(this.forceEnded$,d).subscribe(()=>{if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(p=>!p.updating))try{this.source?.endOfStream()}catch(p){this.error$.next({id:"EndOfStream",category:st.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:p})}})),this.representationSubscription.add(vi(...this.bufferManagers.map(p=>p.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 p=this.tuning.dash.sourceOpenTimeout>=0;yield new Promise(h=>{p&&(this.timeoutSourceOpenId=setTimeout(()=>{if(this.source?.readyState==="open"){h();return}this.error$.next({id:"OpenOfStream",category:st.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 p=[this.manifest.duration??0,...(0,$c.default)((0,$c.default)([...this.manifest.streams.audio,...this.manifest.streams.video],h=>h.representations),h=>{let f=[];return h.duration&&f.push(h.duration),Ue(h.segmentReference)&&h.segmentReference.totalSegmentsDurationMs&&f.push(h.segmentReference.totalSegmentsDurationMs),f})];this.source.duration=Math.max(...p)/1e3}this.audioBufferManager&&Za(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=Rc(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),t=>{this.error$.next({id:"GapWatchdog",category:st.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.fetcher=new Yn({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=$t.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.bufferEstimator}),this.initTracerSubscription()}async seekLive(e){Sr(this.element);let t=this.liveStreamStatus$.getValue()!=="active"?Lc()-this.liveStreamEndTimestamp:0,i=this.normolizeLiveOffset(e+t);this.isActiveLive$.next(i===0),this.manifestUrlString=ae(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(){Sr(this.element),this.state$.setState("running"),this.subscription.add(vi(...eC.map(e=>Mt(this.element,e)),Mt(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:st.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(Mt(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(Mt(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=Lc(),s=100,n=this.videoBufferManager?.lastDataObtainedTimestamp??0;this.videoLastDataObtainedTimestamp$.next(n);let o=this.audioBufferManager?.lastDataObtainedTimestamp??0,u=this.videoBufferManager?.getForwardBufferDuration()??0,l=this.audioBufferManager?.getForwardBufferDuration()??0,c=u<s&&r-n>this.tuning.dash.crashOnStallTWithoutDataTimeout,d=this.audioBufferManager&&l<s&&r-o>this.tuning.dash.crashOnStallTWithoutDataTimeout;if((c||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 p=this.normolizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);this.seekLive(p).catch(h=>{this.error$.next({id:"stallIntervalCallback",category:st.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:h})}),i.liveLastOffset=p}else{let p=this.element.currentTime*1e3;this.videoBufferManager?.maintain(p),this.audioBufferManager?.maintain(p),i.position=p}this.tracer.log("stallIntervalCallback",Ja(i))};this.stallWatchdogSubscription?.unsubscribe(),this.stallWatchdogSubscription=Rc(50).subscribe(e,t=>{this.error$.next({id:"StallWatchdogCallback",category:st.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){Sr(this.element),Sr(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()]),!(Qy(this.element)||Qy(this.videoBufferManager))&&(this.videoBufferManager.maintain(i),this.audioBufferManager?.maintain(i),this.element.currentTime=i/1e3,this.tracer.log("seek",Ja({requestedPosition:e,forcePrecise:t,position:i})))}warmUpMediaSourceIfNeeded(e=this.element?.currentTime){Za(this.element)&&Za(this.source)&&Za(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}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=XD(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 o of this.bufferManagers)for(let u of o.gaps)o.playingRepresentation$.getValue()===u.representation&&u.from-n<=r&&u.to+n>r&&(this.element.duration*1e3-u.to<this.tuning.endGapTolerance?s.push(1/0):s.push(u.to));if(s.length){let o=Math.max(...s)+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,o===1/0?this.forceEnded$.next():(this.element.currentTime=o/1e3,i={...i,gapEnds:s,jumpTo:o,resultCurrentTime:this.element.currentTime},this.tracer.log("jumpGap",Ja(i)))}}calculateDurationFromSegments(){return Math.max(this.videoBufferManager?.calculateDurationFromSegments()||0,this.audioBufferManager?.calculateDurationFromSegments()||0)}};var no=class{constructor(e,t){this.fov=e,this.orientation=t}};var oo=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 zy=`attribute vec2 a_vertex;
125
125
  attribute vec2 a_texel;
126
126
 
127
127
  varying vec2 v_texel;
@@ -175,6 +175,6 @@ void main(void) {
175
175
  // sample using new coordinates
176
176
  gl_FragColor = texture2D(u_texture, tc);
177
177
  }
178
- `;var Tr=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 no(this.params.fov,this.params.orientation),this.cameraRotationManager=new oo(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(zy,this.gl.VERTEX_SHADER),i=this.createShader(Yy,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,o=e+i,u=t-r,l=e+i,c=t+r,d=e-i,p=t+r;return[s,n,o,u,l,c,d,p]}updateTextureMappingBuffer(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([...this.calculateTexturePosition()]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}updateFrameSize(){this.frameWidth=this.sourceVideoElement.videoWidth,this.frameHeight=this.sourceVideoElement.videoHeight}createCanvas(){let e=document.createElement("canvas");return e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e}};import{isNullable as sC,now as es,once as nC,Subscription as oC,ValueSubject as Mc,isNonNullable as uC,safeStorage as Dc,filterChanged as lC}from"@vkontakte/videoplayer-shared";var uo="stalls_manager_metrics",Cc="stalls_manager_abr_params",Ky="stalls_manager_default_tuning_abr_params",Bc=class{constructor(){this.isSeeked$=new Mc(!1);this.isBuffering$=new Mc(!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 oC;this.severeStallOccurred$=new Mc(!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(Cc):{};return{...this.abrParams,...e}}set lastVideoTrackSelected(e){this.lastUniqueVideoTrackSelected?.id!==e.id&&(this.lastUniqueVideoTrackSelected=e,this.lastUniqueVideoTrackSelectedTimestamp=es(),this.currentStallsCount=0)}destroy(){window.clearTimeout(this.qualityRestrictionTimer),this.subscription.unsubscribe(),this.currentStallDuration$.getValue()!==0&&this.updateStallData();let e=(es()-this.providerStartWatchingTimestamp-this.sumStallsDuration)/1e3,t=this.sumStallsDuration;this.addStallInfoToHistory(e,t),this.updateStoredAbrParams()}resetStoredAbrParamsIfNeeded(){let{bitrateFactorAtEmptyBuffer:e,bitrateFactorAtFullBuffer:t,containerSizeFactor:i}={...this.getStoredData(Ky)},{bitrateFactorAtEmptyBuffer:r,bitrateFactorAtFullBuffer:s,containerSizeFactor:n}={...this.abrParams};this.tuning.enabled&&e===r&&t===s&&i===n||(this.removeStoredData(Cc),this.setStoredData(Ky,{bitrateFactorAtEmptyBuffer:r,bitrateFactorAtFullBuffer:s,containerSizeFactor:n}))}updateStoredAbrParams(){let e=[],t=this.getStoredData(uo,"[]");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((o,u)=>o+u.stallsDuration,0)/i;e.push(this.calculateOptimalAbrParams(n,i))}if(this.tuning.useAverageStallsDurationPerTvt){let s=t.reduce((n,o)=>n+o.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(uo,[]),this.setStoredData(Cc,r)}calculateOptimalAbrParams(e,t){let{targetStallsDurationPerTvt:i,deviationStallsDurationPerTvt:r,criticalStallsDurationPerTvt:s,abrAdjustingSpeed:n,significantTvt:o,stallsMetricsHistoryLength:u}=this.tuning,l=n*Math.min(t/(o*u),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(Dc.get(e)??t)}setStoredData(e,t){Dc.set(e,JSON.stringify(t))}removeStoredData(e){Dc.remove(e)}addStallInfoToHistory(e,t){if(e<this.tuning.minTvtToBeCounted||e>this.tuning.maxTvtToBeCounted||e*1e3<t)return;let i=this.getStoredData(uo,"[]"),r=t/e,s=i.length?Lt(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(uo,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(nC()).subscribe(t=>this.providerStartWatchingTimestamp=es())),this.subscription.add(this.currentStallDuration$.pipe(lC()).subscribe(t=>{let{stallDurationNoDataBeforeQualityDecrease:i,stallCountBeforeQualityDecrease:r,resetQualityRestrictionTimeout:s,ignoreStallsOnSeek:n}=this.tuning;if(sC(this.lastUniqueVideoTrackSelected)||n&&this.isSeeked$.getValue())return;let o=this.rtt$.getValue(),u=this.throughput$.getValue(),l=this.videoLastDataObtainedTimestamp$.getValue(),c=es(),d=r&&this.currentStallsCount>=r,p=i&&c-this.lastUniqueVideoTrackSelectedTimestamp>=i+o&&c-l>=i+o&&t>=i;(d||p)&&(this.severeStallOccurred$.next(!0),window.clearTimeout(this.qualityRestrictionTimer),this.maxQualityLimit=this.lastUniqueVideoTrackSelected.quality,uC(this.lastUniqueVideoTrackSelected.bitrate)&&u>this.lastUniqueVideoTrackSelected.bitrate&&(this.predictedThroughputWithoutData=this.lastUniqueVideoTrackSelected.bitrate)),!t&&es()-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}))}},lo=Bc;import{combine as cC,map as dC,observeElementSize as pC,Subscription as hC,ValueSubject as Vc,noop as fC}from"@vkontakte/videoplayer-shared";var co=class{constructor(){this.subscription=new hC;this.pipSize$=new Vc(void 0);this.videoSize$=new Vc(void 0);this.elementSize$=new Vc(void 0);this.pictureInPictureWindowRemoveEventListener=fC}connect({observableVideo:e,video:t}){let i=r=>{let s=r.target;this.pipSize$.next({width:s.width,height:s.height})};this.subscription.add(pC(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(cC({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe(dC(({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 yi=class{constructor(e){this.subscription=new TC;this.videoState=new F("stopped");this.observableVideo=null;this.droppedFramesManager=new or;this.stallsManager=new lo;this.elementSizeManager=new co;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new jt;this.audioTrackSwitchHistory=new jt;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 bC(e)}}};this.init3DScene=e=>{if(this.scene3D)return;this.scene3D=new Tr(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 ze(e.source.url),this.params=e,this.video=Pe(e.container,e.tuning),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(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 so({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode,tracer:this.tracer}),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params;yC(this.observableVideo)&&(this.observableVideo=$e(this.video),this.subscription.add(()=>this.observableVideo?.destroy()));let i=this.constructor.name,r=n=>{e.error$.next({id:i,category:Xy.WTF,message:`${i} internal logic error`,thrown:n})},s=(n,o)=>this.subscription.add(n.subscribe(o,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(_c(l=>!!l.length),Zy()).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(Oc(l=>l.to.state!=="none"),po());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(_c(Jy),Zy()),e.firstBytesEvent$),s(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),s(this.videoState.stateChangeEnded$.pipe(Oc(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(ht(this.video,t.isLooped,r)),this.subscription.add(Le(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(We(this.video,t.playbackRate,i.playbackRateState$,r)),this.elementSizeManager.connect({video:this.video,observableVideo:i}),s(Ye(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.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();if(gC(c,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let p=[];for(let h of c.audio){p.push(vc(h));let f=[];for(let b of h.representations){let g=$y(b);f.push(g),this.audioTracksMap.set(g,{stream:h,representation:b})}this.audioStreamsMap.set(h,f)}this.params.output.availableAudioStreams$.next(p)}let d=[];for(let p of c.video){d.push(yc(p));let h=[];for(let f of p.representations){let b=Ly({...f,streamId:p.id});b&&(h.push(b),this.videoTracksMap.set(b,{stream:p,representation:f}))}this.videoStreamsMap.set(p,h)}this.params.output.availableVideoStreams$.next(d);for(let p of c.text)for(let h of p.representations){let f=My(p,h);this.textTracksMap.set(f,{stream:p,representation:h})}this.params.output.availableVideoTracks$.next(Array.from(this.videoTracksMap.keys())),this.params.output.availableAudioTracks$.next(Array.from(this.audioTracksMap.keys())),this.params.output.isAudioAvailable$.next(!!this.audioTracksMap.size),this.audioTracksMap.size&&this.textTracksMap.size&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else l==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},r)),this.subscription.add(ho(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$,vC(this.video,"progress")).pipe(_c(()=>this.videoTracksMap.size>0)).subscribe(async()=>{let l=this.player.state$.getState(),c=this.player.state$.getTransition();if(!(0,eT.default)(["manifest_ready","running"],l)||c)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let d=this.selectVideoAudioRepresentations();if(!d)return;let[p,h]=d,f=[...this.videoTracksMap.keys()].find(g=>this.videoTracksMap.get(g)?.representation.id===p.id);Jy(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(p.id,h?.id,this.params.sourceHls);else if(await this.player.switchRepresentation("video",p.id),h){let g=!!t.audioStream.getTransition();await this.player.switchRepresentation("audio",h.id,g)}},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(po()).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[d,{stream:p}]=c,h=this.params.desiredState.videoStream.getTransition();h&&h.to&&h.to.id===p.id&&this.params.desiredState.videoStream.setState(h.to),e.currentVideoTrack$.next(d),e.currentVideoStream$.next(yc(p));let f=this.player.calculateDurationFromSegments();f&&this.params.output.duration$.next(f/1e3)},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(po()).subscribe(l=>{let c=[...this.audioTracksMap.entries()].find(([,{representation:f}])=>f.id===l);if(!c){e.currentAudioStream$.next(void 0);return}let[d,{stream:p}]=c,h=this.params.desiredState.audioStream.getTransition();h&&h.to&&h.to.id===p.id&&this.params.desiredState.audioStream.setState(h.to),e.currentAudioStream$.next(vc(p))},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 o=t.playbackState.stateChangeStarted$.pipe(Oc(({to:l})=>l==="ready"),po());this.subscription.add(ho(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,Fc(["init"])).subscribe(()=>{let l=t.autoVideoTrackSwitching.getState(),d=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:l?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(d)})),this.subscription.add(ho(o,this.player.state$.stateChangeEnded$,Fc(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let u=ho(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Fc(["init"])).pipe(SC(0));this.subscription.add(u.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?ua:oa,t=this.params.tuning.useNewAutoSelectVideoTrack?Cn:Dn,i=this.params.tuning.useNewAutoSelectVideoTrack?gt:Mn,{desiredState:r,output:s}=this.params,n=r.autoVideoTrackSwitching.getState(),o=r.videoTrack.getState()?.id,l=[...this.videoTracksMap.keys()].find(({id:y})=>y===o),c=s.currentVideoTrack$.getValue(),d=r.videoStream.getState()??(l&&this.videoTracksMap.get(l)?.stream)??this.videoStreamsMap.size===1?this.videoStreamsMap.keys().next().value:void 0;if(!d)return;let p=[...this.videoStreamsMap.keys()].find(({id:y})=>y===d.id),h=p&&this.videoStreamsMap.get(p);if(!h)return;let f=de(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 g=(this.video.duration*1e3||1/0)-this.video.currentTime*1e3,S=Math.min(f/Math.min(b,g||1/0),1),T=r.audioStream.getState()??(this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0),v=[...this.audioStreamsMap.keys()].find(({id:y})=>y===T?.id)??this.audioStreamsMap.keys().next().value,x=0;if(v){if(l&&!n){let y=e(l,h,this.audioStreamsMap.get(v)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);x=Math.max(x,y?.bitrate??-1/0)}if(c){let y=e(c,h,this.audioStreamsMap.get(v)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);x=Math.max(x,y?.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:x,forwardBufferHealth:S,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}),L=n?w??l:l??w,B=v&&t(L,h,this.audioStreamsMap.get(v)??[],{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}),A=this.videoTracksMap.get(L)?.representation,$=B&&this.audioTracksMap.get(B)?.representation;if(A&&$)return[A,$];if(A&&!$&&this.audioTracksMap.size===0)return[A,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){Me(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:Xy.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),Re(this.video),this.tracer.end()}};var ts=class extends yi{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 Nc,merge as tT,filter as iT,filterChanged as IC,isNullable as Uc,map as rT,ValueSubject as qc,isNonNullable as EC}from"@vkontakte/videoplayer-shared";var is=class extends yi{constructor(e){super(e),this.textTracksManager.destroy()}subscribe(){super.subscribe();let e=-1,{output:t,observableVideo:i,desiredState:r,connect:s}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),s(i.timeUpdate$,t.liveBufferTime$),s(this.player.liveSeekableDuration$,t.duration$),s(this.player.liveLatency$,t.liveLatency$);let n=new qc(1);s(i.playbackRateState$,n),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(r.isLowLatency.stateChangeEnded$.pipe(rT(o=>o.to)).subscribe(this.player.isLowLatency$)).add(Nc({liveBufferTime:t.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(rT(({liveBufferTime:o,liveAvailabilityStartTime:u})=>o&&u?o+u:void 0)).subscribe(t.liveTime$)).add(this.player.liveStreamStatus$.pipe(iT(o=>EC(o))).subscribe(o=>t.isLiveEnded$.next(o!=="active"&&t.position$.getValue()===0))).add(Nc({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:tT(i.playbackRateState$,new qc(1))}).pipe(iT(({liveStreamStatus:o,liveDuration:u})=>o==="active"&&!!u)).subscribe(({liveDuration:o,playbackRate:u})=>{let l=t.liveBufferTime$.getValue(),c=t.position$.getValue(),{playbackCatchupSpeedup:d}=this.params.tuning.dashCmafLive.lowLatency;c||u<1-d||this.video.paused||Uc(l)||(e=o-l)})).add(Nc({time:t.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:tT(i.playbackRateState$,new qc(1))}).pipe(IC((o,u)=>this.player.liveStreamStatus$.getValue()==="active"?o.liveDuration===u.liveDuration:o.time===u.time)).subscribe(({time:o,liveDuration:u,playbackRate:l})=>{let c=t.position$.getValue(),{playbackCatchupSpeedup:d}=this.params.tuning.dashCmafLive.lowLatency;if(!c&&!this.video.paused&&l>=1-d||Uc(o)||Uc(u))return;let p=-1*(u-o-e);t.position$.next(Math.min(p,0))})).add(this.player.currentLiveTextRepresentation$.subscribe(o=>{if(o){let u=Dy(o);this.params.output.availableTextTracks$.next([u])}}))}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 YC,assertNonNullable as KC,debounce as XC,ErrorCategory as TT,filter as ad,filterChanged as wo,fromEvent as JC,isNonNullable as IT,isNullable as ZC,map as sd,merge as Ao,observableFrom as nd,once as ET,Subscription as eB}from"@vkontakte/videoplayer-shared";var id=V(ga(),1);import{abortable as Jc,assertNonNullable as xr,combine as wr,ErrorCategory as nt,filter as To,filterChanged as us,flattenObject as ls,fromEvent as Tt,getTraceSubscriptionMethod as FC,interval as Zc,isNonNullable as cs,isNullable as vT,map as Ar,merge as wi,now as ed,Subject as Io,Subscription as td,tap as NC,throttle as yT,ValueSubject as te}from"@vkontakte/videoplayer-shared";var go=V(Ge(),1),xi=V(bt(),1),So=V(ga(),1);var fT=V(dn(),1);import{assertNever as xC,ErrorCategory as aT,Subject as sT}from"@vkontakte/videoplayer-shared";var wC=18,nT=!1;try{nT=_.browser.isSafari&&!!_.browser.safariVersion&&_.browser.safariVersion<=wC}catch(a){console.error(a)}var Hc=class{constructor(e){this.bufferFull$=new sT;this.error$=new sT;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:aT.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)};nT&&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:aT.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:xC(t)}}},oT=Hc;import{abortable as Yt,assertNonNullable as Ce,ErrorCategory as Ii,fromEvent as zc,getExponentialDelay as Yc,isNonNullable as Ir,isNullable as ye,now as bo,once as LC,Subject as $C,Subscription as MC,ValueSubject as Ei}from"@vkontakte/videoplayer-shared";var jc=V(bt(),1);import{videoSizeToQuality as AC,throttleFn as kC}from"@vkontakte/videoplayer-shared";var uT=({id:a,width:e,height:t,bitrate:i,fps:r,quality:s,streamId:n})=>{let o=(s?Ht(s):void 0)??AC({width:e,height:t});return o&&{id:a,quality:o,bitrate:i,size:{width:e,height:t},fps:r,streamId:n}},lT=({id:a,bitrate:e})=>({id:a,bitrate:e}),cT=({language:a,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:a,label:e}),dT=({language:a,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:a,label:e}),Qc=({id:a,language:e,label:t,codecs:i,isDefault:r})=>({id:a,language:e,label:t,codec:(0,jc.default)(i.split("."),0),isDefault:r}),Gc=({id:a,language:e,label:t,hdr:i,codecs:r})=>({id:a,language:e,hdr:i,label:t,codec:(0,jc.default)(r.split("."),0)}),Wc=a=>"url"in a,qe=a=>a.type==="template";var pT=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},Ti=(a,e)=>{for(let t of a)if(e(t))return t;return null},hT=a=>{let e=!1,t=kC(()=>{e=!0},a);return()=>{try{return t(),e}finally{e=!1}}};import{fromEvent as PC,Subscription as RC}from"@vkontakte/videoplayer-shared";var fo=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 mo=class{constructor(e,t){this.lastUpdateTs=0;this.lastCallTs=0;this.prevRanges=[];this.subscription=new RC;this.mediaSource=e,this.sourceBuffer=t,this.subscription.add(PC(this.sourceBuffer,"updateend").subscribe(()=>this.updateend()))}updateend(){if(!C(this.mediaSource,this.sourceBuffer))return;let{prevRanges:e}=this,t=fo(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],o=t[i+1];if(n>r||o<s)return!0}return!1}wasUpdated(){let{lastCallTs:e,lastUpdateTs:t}=this;return this.lastCallTs=Date.now(),e<=t}destroy(){this.subscription.unsubscribe()}};var rs=class{constructor(e,t,i,{fetcher:r,tuning:s,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!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 $C;this.gaps=[];this.subscription=new MC;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new K;this.switchAbortController=new K;this.destroyAbortController=new K;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=Yt(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);Ce(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new oT(this.sourceBuffer),this.sourceBufferBufferedDiff=new mo(this.mediaSource,this.sourceBuffer),this.subscription.add(zc(this.sourceBuffer,"updateend").subscribe(()=>{this.maintain()})),this.subscription.add(zc(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:Ii.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o||!C(this.mediaSource,this.sourceBuffer))return;let u=Math.min(this.bufferLimit,cr(this.sourceBuffer.buffered)*.8);this.bufferLimit=u;let l=de(this.sourceBuffer.buffered,o),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(o,n*2,l<c).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);Ce(i,"No init buffer for starting representation"),Ce(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=Yt(this.destroyAbortController.signal,async function*(e,t=!1){if(!C(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);Ce(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),Ce(r,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!C(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();Ir(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=Yt(this.destroyAbortController.signal,async function*(e,t=!1){if(!C(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);Ce(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),Ce(r,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!C(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();Ir(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=Yt(this.destroyAbortController.signal,async function*(e){let t=(0,So.default)(e,u=>u.representations)??[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let u of this.representations.keys()){let l=t.find(p=>p.id===u);l&&this.representations.set(u,l);let c=this.representations.get(u);if(!c||!qe(c.segmentReference))return;let d=this.getActualLiveStartingSegments(c.segmentReference);this.segments.set(c.id,d)}let i=this.switchingToRepresentationId??this.downloadingRepresentationId,r=this.representations.get(i);Ce(r);let s=this.segments.get(i);Ce(s,"No segments for starting representation");let n=this.initData.get(i);if(Ce(n,"No init buffer for starting representation"),!(n instanceof ArrayBuffer))return;let o=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,yield this.abort(),o&&(yield this.sourceBufferTaskQueue.remove(o.from*1e3,o.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=u,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=o,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){!C(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new K,Yt(this.switchAbortController.signal,async function*(i,r=!1){this.switchingToRepresentationId=i;let s=this.representations.get(i);Ce(s,`No such representation ${i}`);let n=this.segments.get(i),o=this.initData.get(i);if(ye(o)||ye(n)?yield this.loadInit(s,"high",!1):o instanceof Promise&&(yield o),n=this.segments.get(i),Ce(n,"No segments for starting representation"),o=this.initData.get(i),!(!(o instanceof ArrayBuffer)||!this.sourceBuffer||!C(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(o,this.downloadAbortController.signal),r)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=i,yield this.dropBuffer();else{let u=this.getCurrentPosition();Ir(u)&&!this.isLive&&(this.bufferLimit=this.forwardBufferTarget,yield this.pruneBuffer(u,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 K,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(ye(e)||ye(this.downloadingRepresentationId)||ye(this.playingRepresentationId)||ye(this.sourceBuffer)||!C(this.mediaSource,this.sourceBuffer)||Ir(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if(Ce(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;let r=i.find(c=>e>=c.time.from&&e<c.time.to);Ir(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=de(this.sourceBuffer.buffered,e),d=r?r.time.to+n:-1/0;r&&r.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&c>=r.time.to-e+n&&(s=d)}if(isFinite(this.bufferLimit)&&cr(this.sourceBuffer.buffered)>=this.bufferLimit){let c=de(this.sourceBuffer.buffered,e),d=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,c<d).catch(p=>{this.handleAsyncError(p,"pruneBuffer")});return}let u=null;if(!this.activeSegments.size&&(u=this.selectForwardBufferSegments(i,t.segmentReference.type,s),u?.length)){let c="auto";if(this.tuning.dash.useFetchPriorityHints&&r)if((0,go.default)(u,r))c="high";else{let d=(0,xi.default)(u,0);d&&d.time.from-r.time.to>=this.forwardBufferTarget/2&&(c="low")}this.loadSegments(u,t,c).catch(d=>{this.handleAsyncError(d,"loadSegments")})}(!this.preloadOnly&&!this.allInitsLoaded&&r&&r.status==="fed"&&!u?.length&&de(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let l=(0,xi.default)(i,-1);!this.isLive&&l&&(this.fullyBuffered$.next(l.time.to-e-de(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;Ir(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,So.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,So.default)(e?.streams[this.kind],i=>i.representations)??[];if(![...this.segments.values()].every(i=>!i.length))for(let i of t){if(!i||!qe(i.segmentReference))return;let r=i.segmentReference.segments.map(l=>({...l,status:"none",size:void 0})),s=100,n=this.segments.get(i.id)??[],o=(0,xi.default)(n,-1)?.time.to??0,u=r?.findIndex(l=>o>=l.time.from+s&&o<=l.time.to+s);if(u===-1){this.liveUpdateSegmentIndex=0;let l=this.getActualLiveStartingSegments(i.segmentReference);this.segments.set(i.id,l)}else{let l=r.slice(u+1);this.segments.set(i.id,[...n,...l])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;Ce(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(!qe(r))return;let s=this.segments.get(i.id);if(!s)continue;let n=s.find(u=>Math.floor(u.time.from)===Math.floor(e.time.from));if(n&&!isFinite(n.time.to)&&(n.time.to=e.time.to,t=n.time.to-n.time.from),!!!s.find(u=>Math.floor(u.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let u=Math.round(e.time.to*r.timescale/1e3).toString(10),l=at(r.segmentTemplateUrl,{segmentTime:u});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&&St&&St(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&St&&St(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:p,time:{from:h,to:f}},b)=>{let g=h<=i&&f>=i,S=h>i||g||b===0&&i===0,T=Math.min(this.forwardBufferTarget,this.bufferLimit),v=this.preloadOnly&&h<=i+T||r<T&&f-h>=T||f<=i+T;return(p==="none"||p==="partially_ejected"&&S&&v&&this.sourceBuffer&&C(this.mediaSource,this.sourceBuffer)&&!(Se(this.sourceBuffer.buffered,h)&&Se(this.sourceBuffer.buffered,f)))&&S&&v});if(s===-1)return null;if(t!=="byteRange")return e.slice(s,s+1);let n=e,o=0,u=0,l=[],c=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,d=this.preloadOnly?this.forwardBufferTarget:0;for(let p=s;p<n.length&&(o<=c||u<=d);p++){let h=n[p];if(o+=h.byte.to+1-h.byte.from,u+=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"){qe(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:o,onProgress:u,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(await Yt(o,async function*(){let c=Yc(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(d=>setTimeout(d,c))}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let c=await this.fetcher.fetch(n,{range:s,signal:o,onProgress:u,priority:i,isLowLatency:this.isActiveLowLatency()});if(this.lastDataObtainedTimestampMs=bo(),!c)return;let d=new DataView(c),p=vt(t.mime);if(!isFinite(r.segment.time.to)){let b=t.segmentReference.timescale;r.segment.time.to=p.getChunkEndTime(d,b)}u&&r.feedingBytes&&l?await Promise.all(l):await this.sourceBufferTaskQueue.append(d,o);let{serverDataReceivedTimestamp:h,serverDataPreparedTime:f}=p.getServerLatencyTimestamps(d);h&&f&&this.currentLiveSegmentServerLatency$.next(f-h),r.segment.status="downloaded",this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(c){this.abortActiveSegments([e]),yt(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())qe(t.segmentReference)?t.segmentReference.baseUrl=e:t.segmentReference.url=e}async loadByteRangeSegments(e,t,i="auto"){if(!e.length)return;for(let u of e)u.status="downloading",this.activeSegments.add({segment:u,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:r,url:s,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(await Yt(n,async function*(){let u=Yc(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),zc(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:o,signal:n,priority:i}),this.lastDataObtainedTimestampMs=bo(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),yt(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}prepareByteRangeFetchSegmentParams(e,t){if(qe(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(o,u)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=bo(),await this.onSomeByteRangesDataLoaded({dataView:o,loaded:u,signal:s,onSegmentAppendFailed:()=>this.abort(),globalFrom:r?r.from:0,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:Ii.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!qe(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=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(l,c)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=bo();let d=this.onSomeTemplateDataLoaded({dataView:l,loaded:c,signal:s,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(d)}catch(d){this.error$.next({id:"SegmentFeeding",category:Ii.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:d})}}:void 0;return{url:r,signal:s,onProgress:u,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)(0,go.default)(e,t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:r,signal:s}){if(!this.activeSegments.size||!C(this.mediaSource,this.sourceBuffer))return;let n=this.representations.get(t);if(n)for(let o of this.activeSegments){let{segment:u}=o;if(o.representationId===t){if(s.aborted){r();continue}if(o.loadedBytes=i,o.loadedBytes>o.feedingBytes){let l=new DataView(e.buffer,e.byteOffset+o.feedingBytes,o.loadedBytes-o.feedingBytes),c=vt(n.mime).parseFeedableSegmentChunk(l,this.isLive);c?.byteLength&&(u.status="partially_fed",o.feedingBytes+=c.byteLength,await this.sourceBufferTaskQueue.append(c),o.fedBytes+=c.byteLength)}}}}async onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:s,onSegmentAppendFailed:n}){if(!this.activeSegments.size||!C(this.mediaSource,this.sourceBuffer))return;let o=this.representations.get(t);if(o)for(let u of this.activeSegments){if(u.representationId!==t)continue;if(s.aborted){await n();continue}let{segment:l}=u,c=l.byte.from-i,d=l.byte.to-i,p=d-c+1,h=c<r,f=d<=r;if(h){if(l.status==="downloading"&&f){l.status="downloaded";let b=new DataView(e.buffer,e.byteOffset+c,p);await this.sourceBufferTaskQueue.append(b,s)&&!s.aborted?this.onSegmentFullyAppended(u,t):await n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(l.status==="downloading"||l.status==="partially_fed")&&(u.loadedBytes=Math.min(p,r-c),u.loadedBytes>u.feedingBytes)){let b=new DataView(e.buffer,e.byteOffset+c+u.feedingBytes,u.loadedBytes-u.feedingBytes),g=u.loadedBytes===p?b:vt(o.mime).parseFeedableSegmentChunk(b);g?.byteLength&&(l.status="partially_fed",u.feedingBytes+=g.byteLength,await this.sourceBufferTaskQueue.append(g,s)&&!s.aborted?(u.fedBytes+=g.byteLength,u.fedBytes===p&&this.onSegmentFullyAppended(u,t)):await n())}}}}onSegmentFullyAppended(e,t){if(!(ye(this.sourceBuffer)||!C(this.mediaSource,this.sourceBuffer))){!this.isLive&&_.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:Ii.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",Wc(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=lr(()=>(0,fT.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?Yt(this.destroyAbortController.signal,async function*(){let o=Yc(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,vt(e.mime),r)).then(o=>{if(!o)return;let{init:u,dataView:l,segments:c}=o,d=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,d);let p=c;this.isLive&&qe(e.segmentReference)&&(p=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,p),u&&this.parsedInitData.set(e.id,u)}).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:Ii.WTF,message:"loadInit threw",thrown:o})});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||!C(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||ye(e))return!1;this.checkEjectedSegments();let r=[],s=0,n=o=>{if(s>=t)return;r.push({...o.time});let u=Wc(o)?o.size??0:o.byte.to-o.byte.from;s+=u};for(let o of this.segments.values())for(let u of o){let l=u.time.to<=e-this.tuning.dash.bufferPruningSafeZone,c=u.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(l||c)&&u.status==="fed"&&n(u)}for(let o=0;o<this.sourceBuffer.buffered.length;o++){let u=this.sourceBuffer.buffered.start(o)*1e3,l=this.sourceBuffer.buffered.end(o)*1e3,c=0;for(let d of this.segments.values())for(let p of d)(0,go.default)(["none","partially_ejected"],p.status)&&Math.round(p.time.from)<=Math.round(u)&&Math.round(p.time.to)>=Math.round(l)&&c++;if(c===this.segments.size){let d={time:{from:u,to:l},url:"",status:"none"};n(d)}}if(r.length&&i){let o=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let u of this.segments.values())for(let l of u)l.time.from>=e+o&&l.status==="fed"&&n(l)}return r.length?(r=pT(r),(await Promise.all(r.map(u=>this.sourceBufferTaskQueue.remove(u.from,u.to)))).reduce((u,l)=>u||l,!1)):!1}async abortBuffer(){if(!this.sourceBuffer||!C(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||!C(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||!C(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||!C(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||ye(e)?0:de(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!this.sourceBuffer||!C(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),o=Math.round(s.to);for(let u=0;u<i.length;u++)if(n>=Math.round(i.start(u)*1e3)&&o<=Math.round(i.end(u)*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,o=i.end(s)*1e3;if(!(o<=t.time.from||n>=t.time.to)){if(n<=t.time.from&&o>=t.time.to){r=void 0;break}o>t.time.from&&o<t.time.to&&(r.from=o),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||!C(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=lr(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:Ii.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if(ye(this.sourceBuffer)||!C(this.mediaSource,this.sourceBuffer)||ye(this.playingRepresentationId)||this.sourceBufferBufferedDiff&&!this.sourceBufferBufferedDiff.wasUpdated())return;let e=fo(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),o=Math.ceil(r.time.to),u=!1,l=0;for(let c=0;c<e.length;c+=2){let d=e[c],p=e[c+1];u||(u=d-t<=n&&p+t>=o),(n>=d&&n<p-t||o>d+t&&o<=p)&&(l+=1)}u||(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:Ii.VIDEO_PIPELINE,thrown:e,message:"Something went wrong"})}calculateDurationFromSegments(){if(!this.playingRepresentationId)return 0;let e=this.segments.get(this.playingRepresentationId);return(0,xi.default)(e,-1)?.time.to||0}};import{abortable as as,assertNever as mT,fromEvent as bT,merge as DC,now as ss,Subject as gT,ValueSubject as Kc,flattenObject as Er,ErrorCategory as ns,SubscriptionRemovable as CC}from"@vkontakte/videoplayer-shared";var yo=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:s=!1}){this.lastConnectionType$=new Kc(void 0);this.lastConnectionReused$=new Kc(void 0);this.lastRequestFirstBytes$=new Kc(void 0);this.recoverableError$=new gT;this.error$=new gT;this.abortAllController=new K;this.subscription=new CC;this.fetchManifest=as(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=Wt(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=Wn(i));let r=yield this.doFetch(i,{signal:this.abortAllController.signal}).catch(vo);return r?(t.log("success",Er({url:i,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(r.headers),r.text()):(t.error("error",Er({url:i,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=as(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:i,onProgress:r,priority:s="auto",signal:n,measureThroughput:o=!0,isLowLatency:u=!1}={}){let l=e,c=new Headers,d=this.tracer.createComponentTracer("Fetch");if(i)switch(t){case 0:{c.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let I=new URL(l,location.href);I.searchParams.append("bytes",`${i.from}-${i.to}`),l=I.toString();break}default:mT(t)}this.requestQuic&&(l=Wt(l));let p=this.abortAllController.signal,h;if(n){let I=new K;if(h=DC(bT(this.abortAllController.signal,"abort"),bT(n,"abort")).subscribe(()=>{try{I.abort()}catch(E){vo(E)}}),this.subscription.add(h),this.abortAllController.signal.aborted||n.aborted)try{I.abort()}catch(E){vo(E)}p=I.signal}let f=ss();d.log("startRequest",Er({url:l,priority:s,rangeMethod:t,range:i,isLowLatency:u,requestStartedAt:f}));let b=yield this.doFetch(l,{priority:s,headers:c,signal:p}),g=ss();if(!b)return d.error("error",{message:"No response in request"}),d.end(),this.unsubscribeAbortSubscription(h),null;if(this.throughputEstimator?.addRawRtt(g-f),!b.ok||!b.body){this.unsubscribeAbortSubscription(h);let I=`Fetch error ${b.status}: ${b.statusText}`;return d.error("error",{message:I}),d.end(),Promise.reject(new Error(`Fetch error ${b.status}: ${b.statusText}`))}if(this.onHeadersReceived(b.headers),!r&&!o){this.unsubscribeAbortSubscription(h);let I=ss(),E={requestStartedAt:f,requestEndedAt:I,duration:I-f};return d.log("endRequest",Er(E)),d.end(),b.arrayBuffer()}let S=b.body;if(o){let I;[S,I]=b.body.tee(),this.throughputEstimator?.trackStream(I,u)}let T=S.getReader(),v,x=parseInt(b.headers.get("content-length")??"",10);Number.isFinite(x)&&(v=x),!v&&i&&(v=i.to-i.from+1);let w=0,L=v?new Uint8Array(v):new Uint8Array(0),B=!1,A=I=>{this.unsubscribeAbortSubscription(h),B=!0,vo(I)},$=as(p,async function*({done:I,value:E}){if(w===0&&this.lastRequestFirstBytes$.next(ss()-f),p.aborted){this.unsubscribeAbortSubscription(h);return}if(!I&&E){if(v)L.set(E,w),w+=E.byteLength;else{let k=new Uint8Array(L.length+E.length);k.set(L),k.set(E,L.length),L=k,w+=E.byteLength}r?.(new DataView(L.buffer),w),yield T?.read().then($,A)}}.bind(this));yield T?.read().then($,A),this.unsubscribeAbortSubscription(h);let y=ss(),M={failed:B,requestStartedAt:f,requestEndedAt:y,duration:y-f};return B?(d.error("endRequest",Er(M)),d.end(),null):(d.log("endRequest",Er(M)),d.end(),L.buffer)}.bind(this));this.fetchByteRangeRepresentation=as(this.abortAllController.signal,async function*(e,t,i){if(e.type!=="byteRange")return null;let{from:r,to:s}=e.initRange,n=r,o=s,u=!1,l,c;e.indexRange&&(l=e.indexRange.from,c=e.indexRange.to,u=s+1===l,u&&(n=Math.min(l,r),o=Math.max(c,s))),n=Math.min(n,0);let d=yield this.fetch(e.url,{range:{from:n,to:o},priority:i,measureThroughput:!1});if(!d)return null;let p=new DataView(d,r-n,s-n+1);if(!t.validateData(p))throw new Error("Invalid media file");let h=t.parseInit(p),f=e.indexRange??t.getIndexRange(h);if(!f)throw new ReferenceError("No way to load representation index");let b;if(u)b=new DataView(d,f.from-n,f.to-f.from+1);else{let S=yield this.fetch(e.url,{range:f,priority:i,measureThroughput:!1});if(!S)return null;b=new DataView(S)}let g=t.parseSegments(b,h,f);return{init:h,dataView:new DataView(d),segments:g}}.bind(this));this.fetchTemplateRepresentation=as(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}=Gn(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 Ke(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:ns.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:ns.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:ns.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:ns.FATAL});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${s})`,category:ns.FATAL})}}unsubscribeAbortSubscription(e){e&&(e.unsubscribe(),this.subscription.remove(e))}},vo=a=>{if(!yt(a))throw a};import{isNullable as BC,ValueSubject as VC}from"@vkontakte/videoplayer-shared";var os=class a{constructor(e,t){this.currentRepresentation$=new VC(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(!BC(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,o=r.segments[s-1].time.to;if(e<n||e>o)continue;let u=r.segments.find(l=>l.time.from<=e&&l.time.to>=e);!u||this.currentSegment?.time.from===u.time.from&&this.currentSegment.time.to===u.time.to||(this.currentSegment=u,this.currentRepresentation$.next({...i,label:"Live Text",language:"ru",isAuto:!0,url:new URL(u.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&&qe(t.segmentReference))}};var UC=["progress","play","seeked","stalled","waiting"],qC=["timeupdate","progress","loadeddata","playing","seeked"];var Eo=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new td;this.representationSubscription=new td;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 Io;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 Io;this.fetcherError$=new Io;this.liveStreamEndTimestamp=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.forceEnded$=new Io;this.gapWatchdogActive=!1;this.destroyController=new K;this.initManifest=Jc(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=ae(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:nt.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=Jc(this.destroyController.signal,async function*(){this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(n=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:nt.NETWORK,message:"Failed to load manifest",thrown:n})});if(!e)return null;let t=null;try{t=qn(e??"",this.manifestUrlString)}catch(n){let o=Un(e)??{id:"ManifestParsing",category:nt.PARSER,message:"Failed to parse MPD manifest",thrown:n};this.error$.next(o)}if(!t)return null;let i=(n,o,u)=>!!(this.element?.canPlayType?.(o)&&Ne()?.isTypeSupported?.(`${o}; codecs="${u}"`)||n==="text");if(t.live){this.isLive$.next(!!t.live);let{availabilityStartTime:n,latestSegmentPublishTime:o,streamIsUnpublished:u,streamIsAlive:l}=t.live,c=(t.duration??0)/1e3;this.liveSeekableDuration$.next(-1*c),this.liveDuration$.next((o-n)/1e3),this.liveAvailabilityStartTime$.next(t.live.availabilityStartTime);let d="active";l||(d=u?"unpublished":"unexpectedly_down"),this.liveStreamStatus$.next(d)}let r={text:t.streams.text,video:[],audio:[]};for(let n of["video","audio"]){let u=t.streams[n].filter(({mime:d,codecs:p})=>i(n,d,p)),l=new Set(u.map(({codecs:d})=>d)),c=io(l);if(c&&(r[n]=u.filter(({codecs:d})=>d.startsWith(c))),n==="video"){let d=this.tuning.preferHDR,p=r.video.some(f=>f.hdr),h=r.video.some(f=>!f.hdr);_.display.isHDR&&d&&p?r.video=r.video.filter(f=>f.hdr):h&&(r.video=r.video.filter(f=>!f.hdr))}}let s={...t,streams:r};return this.tracer.log("updateManifestEnd",ls(s)),s}.bind(this));this.initRepresentations=Jc(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initRepresentationsStart",ls({initialVideo:e,initialAudio:t,sourceHls:i})),xr(this.manifest),xr(this.element),this.representationSubscription.unsubscribe(),this.representationSubscription=new td,this.state$.startTransitionTo("representations_ready");let r=p=>{this.representationSubscription.add(Tt(p,"error").pipe(To(h=>!!this.element?.played.length)).subscribe(h=>{this.error$.next({id:"VideoSource",category:nt.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:h})}))};this.source=this.tuning.useManagedMediaSource?gn():new MediaSource;let s=document.createElement("source");if(r(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),this.tuning.useManagedMediaSource&&tr())if(i){let p=document.createElement("source");r(p),p.type="application/x-mpegurl",p.src=i.url,this.element.appendChild(p)}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},o=this.manifest.streams.video.reduce((p,h)=>[...p,...h.representations],[]);if(this.videoBufferManager=new rs("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],cs(t)){let p=this.manifest.streams.audio.reduce((h,f)=>[...h,...f.representations],[]);this.audioBufferManager=new rs("audio",this.source,p,n),this.bufferManagers.push(this.audioBufferManager)}os.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new os(this.manifest.streams.text,n)),this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$));let u=()=>{this.stallWatchdogSubscription?.unsubscribe(),this.currentStallDuration$.next(0)};if(this.representationSubscription.add(wi(...qC.map(p=>Tt(this.element,p))).pipe(Ar(p=>this.element?de(this.element.buffered,this.element.currentTime*1e3):0),us(),NC(p=>{p>this.tuning.dash.bufferEmptinessTolerance&&u()})).subscribe(this.bufferLength$)),this.representationSubscription.add(wi(Tt(this.element,"ended"),this.forceEnded$).subscribe(()=>{u()})),this.isLive$.getValue()){this.subscription.add(this.liveDuration$.pipe(us()).subscribe(h=>this.liveStreamEndTimestamp=ed())),this.subscription.add(Tt(this.element,"pause").subscribe(()=>{this.livePauseWatchdogSubscription=Zc(1e3).subscribe(h=>{let f=Ut(this.manifestUrlString,2);this.manifestUrlString=ae(this.manifestUrlString,f+1e3,2),this.liveStreamStatus$.getValue()==="active"&&this.updateManifest()}),this.subscription.add(this.livePauseWatchdogSubscription)})).add(Tt(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),us()).subscribe(h=>{this.isManualDecreasePlaybackInLive()||gr(this.element,1)})),this.representationSubscription.add(wr({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(To(({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(wr({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe(To(({isLive:h})=>h),us((h,f)=>f.bufferLength<h.bufferLength),Ar(({rtt:h,bufferLength:f,segmentServerLatency:b})=>{let g=Ut(this.manifestUrlString,2);return(h/2+f+b+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:b})=>{if(!b||!f)return;let g=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,S=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,T=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,v=h-g;if(this.isManualDecreasePlaybackInLive())return;let x=1;Math.abs(v)>S&&(x=1+Math.sign(v)*T),gr(this.element,x)})),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(S=>S.getLiveSegmentsToLoadState(this.manifest)?.to??b))-b}this.liveLoadBufferLength$.getValue()!==f&&this.liveLoadBufferLength$.next(f)}));let p=0;this.representationSubscription.add(wr({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(yT(1e3)).subscribe(async({liveLoadBufferLength:h,bufferLength:f})=>{if(!this.element||this.isUpdatingLive)return;let b=this.element.playbackRate,g=Ut(this.manifestUrlString,2),S=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,T=Math.min(S,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*b),v=this.tuning.dashCmafLive.normalizedActualBufferOffset*b,x=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*b,w=isFinite(h)?h:f,L=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),B=S<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next(B);let A="none";if(L?A="active_low_latency":this.isLowLatency$.getValue()&&B?(this.bufferManagers.forEach($=>$.proceedLowLatencyLive()),A="active_low_latency"):g!==0&&w<T?A="live_forward_buffering":w<T+x&&(A="live_with_target_offset"),isFinite(h)&&(p=h>p?h:p),A==="live_forward_buffering"||A==="live_with_target_offset"){let $=p-(T+v),y=this.normolizeLiveOffset(Math.trunc(g+$/b)),M=Math.abs(y-g),I=0;!h||M<=this.tuning.dashCmafLive.offsetCalculationError?I=g:y>0&&M>this.tuning.dashCmafLive.offsetCalculationError&&(I=y),this.manifestUrlString=ae(this.manifestUrlString,I,2)}(A==="live_with_target_offset"||A==="live_forward_buffering")&&(p=0,await this.updateLive())},h=>{this.error$.next({id:"updateLive",category:nt.VIDEO_PIPELINE,thrown:h,message:"Failed to update live with subscription"})}))}let l=wi(...this.bufferManagers.map(p=>p.fullyBuffered$)).pipe(Ar(()=>this.bufferManagers.every(p=>p.fullyBuffered$.getValue()))),c=wi(...this.bufferManagers.map(p=>p.onLastSegment$)).pipe(Ar(()=>this.bufferManagers.some(p=>p.onLastSegment$.getValue()))),d=wr({allBuffersFull:l,someBufferEnded:c}).pipe(us(),Ar(({allBuffersFull:p,someBufferEnded:h})=>p&&h),To(p=>p));if(this.representationSubscription.add(wi(this.forceEnded$,d).subscribe(()=>{if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(p=>!p.updating))try{this.source?.endOfStream()}catch(p){this.error$.next({id:"EndOfStream",category:nt.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:p})}})),this.representationSubscription.add(wi(...this.bufferManagers.map(p=>p.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 p=this.tuning.dash.sourceOpenTimeout>=0;yield new Promise(h=>{p&&(this.timeoutSourceOpenId=setTimeout(()=>{if(this.source?.readyState==="open"){h();return}this.error$.next({id:"OpenOfStream",category:nt.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 p=[this.manifest.duration??0,...(0,id.default)((0,id.default)([...this.manifest.streams.audio,...this.manifest.streams.video],h=>h.representations),h=>{let f=[];return h.duration&&f.push(h.duration),qe(h.segmentReference)&&h.segmentReference.totalSegmentsDurationMs&&f.push(h.segmentReference.totalSegmentsDurationMs),f})];this.source.duration=Math.max(...p)/1e3}this.audioBufferManager&&cs(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=Zc(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),t=>{this.error$.next({id:"GapWatchdog",category:nt.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.fetcher=new yo({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=$t.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.bufferEstimator}),this.initTracerSubscription()}async seekLive(e){xr(this.element);let t=this.liveStreamStatus$.getValue()!=="active"?ed()-this.liveStreamEndTimestamp:0,i=this.normolizeLiveOffset(e+t);this.isActiveLive$.next(i===0),this.manifestUrlString=ae(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");let e=Tt(this.element,"timeupdate");this.tuning.dash.timeupdateEventTickThrottle&&(e=e.pipe(yT(this.tuning.dash.timeupdateEventTickThrottle))),this.subscription.add(wi(...UC.map(t=>Tt(this.element,t)),Tt(window,"online"),e).subscribe(()=>this.tick(),t=>{this.error$.next({id:"DashVKPlayer",category:nt.WTF,message:"Internal logic error",thrown:t})})),this.subscription.add(Tt(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(Tt(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=ed(),n=100,o=this.videoBufferManager?.lastDataObtainedTimestamp??0;this.videoLastDataObtainedTimestamp$.next(o);let u=this.audioBufferManager?.lastDataObtainedTimestamp??0,l=this.videoBufferManager?.getForwardBufferDuration()??0,c=this.audioBufferManager?.getForwardBufferDuration()??0,d=l<n&&s-o>this.tuning.dash.crashOnStallTWithoutDataTimeout,p=this.audioBufferManager&&c<n&&s-u>this.tuning.dash.crashOnStallTWithoutDataTimeout;if((d||p)&&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:nt.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",ls(r))};this.stallWatchdogSubscription?.unsubscribe(),this.stallWatchdogSubscription=Zc(50).subscribe(t,i=>{this.error$.next({id:"StallWatchdogCallback",category:nt.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){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),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",ls({requestedPosition:e,forcePrecise:t,position:i})))}warmUpMediaSourceIfNeeded(e=this.element?.currentTime){cs(this.element)&&cs(this.source)&&cs(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}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=FC(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,o=this.element.readyState===HTMLMediaElement.HAVE_METADATA?this.tuning.endGapTolerance:0;for(let u of this.bufferManagers)for(let l of u.gaps)(l.persistent||u.playingRepresentation$.getValue()===l.representation)&&l.from-o<=s&&l.to+o>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 u=n+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,u===1/0?this.forceEnded$.next():(this.element.currentTime=u/1e3,this.tracer.log("jumpGap",ls({isJumpGapAfterSeekLive:i,isActiveLowLatency:t,initialCurrentTime:r,jumpTo:u,resultCurrentTime:this.element.currentTime})))}}calculateDurationFromSegments(){return Math.max(this.videoBufferManager?.calculateDurationFromSegments()||0,this.audioBufferManager?.calculateDurationFromSegments()||0)}};import{combine as HC,map as jC,observeElementSize as QC,Subscription as GC,ValueSubject as rd,noop as WC}from"@vkontakte/videoplayer-shared";var xo=class{constructor(){this.subscription=new GC;this.pipSize$=new rd(void 0);this.videoSize$=new rd(void 0);this.elementSize$=new rd(void 0);this.pictureInPictureWindowRemoveEventListener=WC}connect({observableVideo:e,video:t}){let i=r=>{let s=r.target;this.pipSize$.next({width:s.width,height:s.height})};this.subscription.add(QC(t).subscribe(this.videoSize$)).add(e.enterPip$.subscribe(({pictureInPictureWindow:r})=>{this.pipSize$.next({width:r.width,height:r.height}),r.addEventListener("resize",i),this.pictureInPictureWindowRemoveEventListener=()=>{r.removeEventListener("resize",i)}})).add(e.leavePip$.subscribe(()=>{this.pictureInPictureWindowRemoveEventListener()})).add(HC({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe(jC(({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 eB;this.videoState=new F("stopped");this.observableVideo=null;this.droppedFramesManager=new or;this.stallsManager=new lo;this.elementSizeManager=new xo;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new jt;this.audioTrackSwitchHistory=new jt;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 YC(e)}}};this.init3DScene=e=>{if(this.scene3D)return;this.scene3D=new Tr(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 ze(e.source.url),this.params=e,this.video=Pe(e.container,e.tuning),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(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 Eo({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode,tracer:this.tracer}),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params;ZC(this.observableVideo)&&(this.observableVideo=$e(this.video),this.subscription.add(()=>this.observableVideo?.destroy()));let i=this.constructor.name,r=n=>{e.error$.next({id:i,category:TT.WTF,message:`${i} internal logic error`,thrown:n})},s=(n,o)=>this.subscription.add(n.subscribe(o,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(ad(d=>!!d.length),ET()).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(sd(d=>d.to.state!=="none"),wo());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(ad(IT),ET()),e.firstBytesEvent$),s(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),s(this.videoState.stateChangeEnded$.pipe(sd(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(ht(this.video,t.isLooped,r)),this.subscription.add(Le(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(We(this.video,t.playbackRate,i.playbackRateState$,r)),this.elementSizeManager.connect({video:this.video,observableVideo:i}),s(Ye(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.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 p=this.player.getStreams();if(KC(p,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let f=[];for(let b of p.audio){f.push(Qc(b));let g=[];for(let S of b.representations){let T=lT(S);g.push(T),this.audioTracksMap.set(T,{stream:b,representation:S})}this.audioStreamsMap.set(b,g)}this.params.output.availableAudioStreams$.next(f)}let h=[];for(let f of p.video){h.push(Gc(f));let b=[];for(let g of f.representations){let S=uT({...g,streamId:f.id});S&&(b.push(S),this.videoTracksMap.set(S,{stream:f,representation:g}))}this.videoStreamsMap.set(f,b)}this.params.output.availableVideoStreams$.next(h);for(let f of p.text)for(let b of f.representations){let g=cT(f,b);this.textTracksMap.set(g,{stream:f,representation:b})}this.params.output.availableVideoTracks$.next(Array.from(this.videoTracksMap.keys())),this.params.output.availableAudioTracks$.next(Array.from(this.audioTracksMap.keys())),this.params.output.isAudioAvailable$.next(!!this.audioTracksMap.size),this.audioTracksMap.size&&this.textTracksMap.size&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else d==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},r));let{vktvAbrThrottle:o}=this.params.tuning.dash,u=o&&hT(o)||null;this.subscription.add(Ao(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$,JC(this.video,"progress")).pipe(ad(()=>this.videoTracksMap.size>0)).subscribe(async()=>{let d=this.player.state$.getState(),p=this.player.state$.getTransition();if(d!=="manifest_ready"&&d!=="running"||p||d==="running"&&u&&!u())return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState()),this.selectVideoAudioRepresentations();let{video:h,audio:f}=this.selectedRepresentations;if(!h)return;let b=Ti(this.videoTracksMap.keys(),S=>this.videoTracksMap.get(S)?.representation.id===h.id);IT(b)&&(this.stallsManager.lastVideoTrackSelected=b);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(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(wo()).subscribe(d=>{let p=Ti(this.videoTracksMap.entries(),([,{representation:S}])=>S.id===d);if(!p){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[h,{stream:f}]=p,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(Gc(f));let g=this.player.calculateDurationFromSegments();g&&this.params.output.duration$.next(g/1e3)},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(wo()).subscribe(d=>{let p=Ti(this.audioTracksMap.entries(),([,{representation:g}])=>g.id===d);if(!p){e.currentAudioStream$.next(void 0);return}let[h,{stream:f}]=p,b=this.params.desiredState.audioStream.getTransition();b&&b.to&&b.to.id===f.id&&this.params.desiredState.audioStream.setState(b.to),e.currentAudioStream$.next(Qc(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(p){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${p}`})}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(sd(({to:d})=>d==="ready"),wo());this.subscription.add(Ao(l,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,nd(["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(Ao(l,this.player.state$.stateChangeEnded$,nd(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let c=Ao(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,nd(["init"])).pipe(XC(0));this.subscription.add(c.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?ua:oa,t=this.params.tuning.useNewAutoSelectVideoTrack?Cn:Dn,i=this.params.tuning.useNewAutoSelectVideoTrack?gt:Mn,{desiredState:r,output:s}=this.params,n=r.autoVideoTrackSwitching.getState(),o=r.videoTrack.getState()?.id,u=Ti(this.videoTracksMap.keys(),A=>A.id===o),l=s.currentVideoTrack$.getValue(),c=r.videoStream.getState()??(u&&this.videoTracksMap.get(u)?.stream)??this.videoStreamsMap.size===1?this.videoStreamsMap.keys().next().value:void 0;if(!c)return;let d=Ti(this.videoStreamsMap.keys(),A=>A.id===c.id),p=d&&this.videoStreamsMap.get(d);if(!p)return;let h=de(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,g=Math.min(h/Math.min(f,b||1/0),1),S=r.audioStream.getState()??(this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0),T=S?.id&&Ti(this.audioStreamsMap.keys(),A=>A.id===S.id)||this.audioStreamsMap.keys().next().value,v=0;if(T){if(u&&!n){let A=e(u,p,this.audioStreamsMap.get(T)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);v=Math.max(v,A?.bitrate??-1/0)}if(l){let A=e(l,p,this.audioStreamsMap.get(T)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);v=Math.max(v,A?.bitrate??-1/0)}}let x=u;(n||!x)&&(x=i(p,{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:v,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 w=T&&t(x,p,this.audioStreamsMap.get(T)??[],{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}),L=this.videoTracksMap.get(x)?.representation,B=w&&this.audioTracksMap.get(w)?.representation;L&&B?(this.selectedRepresentations.video=L,this.selectedRepresentations.audio=B):L&&!B&&this.audioTracksMap.size===0&&(this.selectedRepresentations.video=L,this.selectedRepresentations.audio=null)}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){Me(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:TT.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),Re(this.video),this.tracer.end()}};var ds=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 od,merge as xT,filter as wT,filterChanged as tB,isNullable as ud,map as AT,ValueSubject as ld,isNonNullable as iB}from"@vkontakte/videoplayer-shared";var ps=class extends Ai{constructor(e){super(e),this.textTracksManager.destroy()}subscribe(){super.subscribe();let e=-1,{output:t,observableVideo:i,desiredState:r,connect:s}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),s(i.timeUpdate$,t.liveBufferTime$),s(this.player.liveSeekableDuration$,t.duration$),s(this.player.liveLatency$,t.liveLatency$);let n=new ld(1);s(i.playbackRateState$,n),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(r.isLowLatency.stateChangeEnded$.pipe(AT(o=>o.to)).subscribe(this.player.isLowLatency$)).add(od({liveBufferTime:t.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(AT(({liveBufferTime:o,liveAvailabilityStartTime:u})=>o&&u?o+u:void 0)).subscribe(t.liveTime$)).add(this.player.liveStreamStatus$.pipe(wT(o=>iB(o))).subscribe(o=>t.isLiveEnded$.next(o!=="active"&&t.position$.getValue()===0))).add(od({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:xT(i.playbackRateState$,new ld(1))}).pipe(wT(({liveStreamStatus:o,liveDuration:u})=>o==="active"&&!!u)).subscribe(({liveDuration:o,playbackRate:u})=>{let l=t.liveBufferTime$.getValue(),c=t.position$.getValue(),{playbackCatchupSpeedup:d}=this.params.tuning.dashCmafLive.lowLatency;c||u<1-d||this.video.paused||ud(l)||(e=o-l)})).add(od({time:t.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:xT(i.playbackRateState$,new ld(1))}).pipe(tB((o,u)=>this.player.liveStreamStatus$.getValue()==="active"?o.liveDuration===u.liveDuration:o.time===u.time)).subscribe(({time:o,liveDuration:u,playbackRate:l})=>{let c=t.position$.getValue(),{playbackCatchupSpeedup:d}=this.params.tuning.dashCmafLive.lowLatency;if(!c&&!this.video.paused&&l>=1-d||ud(o)||ud(u))return;let p=-1*(u-o-e);t.position$.next(Math.min(p,0))})).add(this.player.currentLiveTextRepresentation$.subscribe(o=>{if(o){let u=dT(o);this.params.output.availableTextTracks$.next([u])}}))}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 kT="X-Playback-Duration",cd=async a=>{let e=await Ke(a),t=await e.text(),i=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t)?.[1];return i?parseInt(i,10):e.headers.has(kT)?parseInt(e.headers.get(kT),10):void 0};import{assertNever as hB,combine as fB,debounce as mB,ErrorCategory as Ro,filter as bB,filterChanged as gB,isNonNullable as LT,isNullable as Lo,map as $T,merge as SB,observableFrom as vB,Subscription as yB,ValueSubject as hd,VideoQuality as TB}from"@vkontakte/videoplayer-shared";var pd=V(Yu(),1);import{videoSizeToQuality as rB,getExponentialDelay as aB}from"@vkontakte/videoplayer-shared";var sB=a=>{let e=null;if(a.QUALITY&&(e=Ht(a.QUALITY)),!e&&a.RESOLUTION){let[t,i]=a.RESOLUTION.split("x").map(r=>parseInt(r,10));e=rB({width:t,height:i})}return e??null},nB=(a,e)=>{let t=a.split(`
179
- `),i=[],r=[];for(let s=0;s<t.length;s++){let n=t[s],o=n.match(/^#EXT-X-STREAM-INF:(.+)/),u=n.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!o&&!u)){if(o){let l=(0,pd.default)(o[1].split(",").map(g=>g.split("="))),c=l.QUALITY??`stream-${l.BANDWIDTH}`,d=sB(l),p;l.BANDWIDTH&&(p=parseInt(l.BANDWIDTH,10)/1e3||void 0),!p&&l["AVERAGE-BANDWIDTH"]&&(p=parseInt(l["AVERAGE-BANDWIDTH"],10)/1e3||void 0);let h=l["FRAME-RATE"]?parseFloat(l["FRAME-RATE"]):void 0,f;if(l.RESOLUTION){let[g,S]=l.RESOLUTION.split("x").map(T=>parseInt(T,10));g&&S&&(f={width:g,height:S})}let b=new URL(t[++s],e).toString();d&&i.push({id:c,quality:d,url:b,bandwidth:p,size:f,fps:h})}if(u){let l=(0,pd.default)(u[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"),d=l.LANGUAGE,p=l.NAME;c&&d&&r.push({type:"internal",id:d,label:p,language:d,url:c,isAuto:!1})}}}if(!i.length)throw new Error("Empty manifest");return{qualityManifests:i,textTracks:r}},oB=a=>new Promise(e=>{setTimeout(()=>{e()},a)}),dd=0,PT=async(a,e=a,t,i)=>{let s=await(await Ke(a,i)).text();dd+=1;try{let{qualityManifests:n,textTracks:o}=nB(s,e);return{qualityManifests:n,textTracks:o}}catch{if(dd<=t.manifestRetryMaxCount)return await oB(aB(dd-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),PT(a,e,t)}return{qualityManifests:[],textTracks:[]}},ko=PT;import{isNonNullable as uB,Subscription as lB,throttle as cB,ValueSubject as RT,Subject as dB,ErrorCategory as pB}from"@vkontakte/videoplayer-shared";var Po=class{constructor(e,t,i,r,s){this.subscription=new lB;this.abortControllers={destroy:new K,nextManifest:null};this.prepareUrl=void 0;this.currentTextTrackData=null;this.availableTextTracks$=new RT(null);this.getCurrentTime$=new RT(null);this.error$=new dB;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 Ke(r,{signal:this.abortControllers.destroy.signal})).text(),o=this.parsePlaylist(n,r);return{textTrack:i,playlist:o}}}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 o=r[n];switch(!0){case o.startsWith("#EXTINF:"):{let u=r[++n],l=new URL(u,t).toString(),c=Number(this.extractPlaylistRowValue("#EXTINF:",o))*1e3;if(i.segments.push({time:{from:s,to:s+c},url:l}),s=s+c,!i.segmentStartTime){let d=new Date(i.vkStartTime).valueOf(),p=new Date(i.programDateTime).valueOf();i.segmentStartTime=p-d}break}case o.startsWith("#EXT-X-TARGETDURATION:"):i.targetDuration=Number(this.extractPlaylistRowValue("#EXT-X-TARGETDURATION:",o));break;case o.startsWith("#EXT-X-MEDIA-SEQUENCE:"):i.mediaSequence=Number(this.extractPlaylistRowValue("#EXT-X-MEDIA-SEQUENCE:",o));break;case o.startsWith("#EXT-X-VK-PLAYBACK-DURATION:"):i.vkPlaybackDuration=Number(this.extractPlaylistRowValue("#EXT-X-VK-PLAYBACK-DURATION:",o));break;case o.startsWith("#EXT-X-PROGRAM-DATE-TIME:"):{let u=this.extractPlaylistRowValue("#EXT-X-PROGRAM-DATE-TIME:",o);i.programDateTime=u;let l=new Date(u);l.setMilliseconds(0),s=l.valueOf();break}case o.startsWith("#EXT-X-VK-START-TIME:"):i.vkStartTime=this.extractPlaylistRowValue("#EXT-X-VK-START-TIME:",o);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(uB(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 K;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:pB.WTF,thrown:t,message:e})}};var hs=class{constructor(e){this.subscription=new yB;this.videoState=new F("stopped");this.textTracksManager=null;this.liveTextManager=null;this.manifests$=new hd([]);this.liveOffset=new hi;this.manifestStartTime$=new hd(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(),o=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||o){let c=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(c),this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if(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 hB(t)}};this.params=e,this.video=Pe(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:TB.INVARIANT,url:this.params.source.url};let t=(i,r)=>ko(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 Po(this.params.output.liveTime$,this.video,t,this.params.source.url,this.params.tuning.hlsLiveNewTextManagerDownloadThreshold):this.textTracksManager=new ze(e.source.url),t(this.generateLiveUrl()).then(({qualityManifests:i,textTracks:r})=>{i.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:Ro.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:Ro.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 hd(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 o=i?"master":s;return i&&!r&&t.startTransitionTo(this.masterManifest),n.find(u=>u.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsLiveProvider",category:Ro.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},r=$e(this.video);this.subscription.add(()=>r.destroy());let s=(o,u)=>this.subscription.add(o.subscribe(u,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(Le(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(We(this.video,t.playbackRate,r.playbackRateState$,i)),s(Ye(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(o=>{o&&this.params.output.availableTextTracks$.next(o)})),this.subscription.add(this.maxSeekBackTime$.pipe(gB(),$T(o=>-o/1e3)).subscribe(this.params.output.duration$,i)),this.subscription.add(r.loadedMetadata$.subscribe(()=>{let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&LT(l.to)){let d=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let p=this.manifests$.getValue().find(h=>h.id===d);p&&(this.params.output.currentVideoTrack$.next(p),this.params.output.hostname$.next(ge(p.url)))}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o&&o.state==="requested"&&this.seek(o.position)},i)),this.subscription.add(r.loadedData$.subscribe(()=>{let o=this.video?.getStartDate?.()?.getTime();this.manifestStartTime$.next(o||void 0)},i)),this.subscription.add(fB({startTime:this.manifestStartTime$.pipe(bB(LT)),currentTime:r.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),i)),this.subscription.add(this.manifests$.pipe($T(o=>o.map(({id:u,quality:l,size:c,bandwidth:d,fps:p})=>({id:u,quality:l,size:c,fps:p,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,i));let n=SB(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,vB(["init"])).pipe(mB(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),Re(this.video)}prepare(){let e=this.selectManifest();if(Lo(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:o,min:u}=t?.to??i??{};for(let[l,c]of[[o,"mq"],[u,"lq"]]){let d=String(parseFloat(l||""));c&&l&&r.searchParams.set(c,d)}}let s=this.params.format==="HLS_LIVE_CMAF"?2:0,n=ae(r.toString(),this.liveOffset.getTotalOffset(),s);this.liveTextManager?.prepare(n),this.video.setAttribute("src",n),this.video.load(),cd(n).then(o=>{if(!Lo(o))this.maxSeekBackTime$.next(o);else{let u=this.params.source.maxSeekBackTime??this.maxSeekBackTime$.getValue();(Lo(u)||!isFinite(u))&&Ke(n).then(l=>l.text()).then(l=>{let c=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(l)?.[1];if(c){let d=new URL(c,n).toString();cd(d).then(p=>{Lo(p)||this.maxSeekBackTime$.next(p)})}}).catch(()=>{})}})}playIfAllowed(){Me(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:Ro.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=ae(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 IB,debounce as EB,ErrorCategory as fd,fromEvent as md,isNonNullable as xB,isNullable as wB,map as MT,merge as DT,observableFrom as CT,Subscription as AB,ValueSubject as kB,VideoQuality as PB}from"@vkontakte/videoplayer-shared";var fs=class{constructor(e){this.subscription=new AB;this.videoState=new F("stopped");this.manifests$=new kB([]);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(),o=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||o){let c=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(c);let{currentTime:d}=this.video;this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:d*1e3,forcePrecise:!0});return}switch(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 IB(t)}};this.textTracksManager=new ze(e.source.url),this.params=e,this.video=Pe(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:PB.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),ko(ae(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.manifests$.next([this.masterManifest,...t]),this.params.tuning.useNativeHLSTextTracks||this.params.desiredState.internalTextTracks.startTransitionTo(i)},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:fd.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 o=i?"master":s;return i&&(!r||!r.from)&&t.startTransitionTo(this.masterManifest),n.find(u=>u.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsProvider",category:fd.WTF,message:"HlsProvider internal logic error",thrown:o})},r=$e(this.video);this.subscription.add(()=>r.destroy());let s=(o,u)=>this.subscription.add(o.subscribe(u));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(MT(o=>o.to)),this.params.output.playbackState$),this.subscription.add(ht(this.video,t.isLooped,i)),this.subscription.add(Le(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(We(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 o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&xB(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 d=this.params.desiredState.playbackRate.getState(),p=this.params.output.element$.getValue()?.playbackRate;if(d!==p){let h=this.params.output.element$.getValue();h&&(this.params.desiredState.playbackRate.setState(d),h.playbackRate=d)}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o.state==="requested"&&this.seek(o.position)},i))),this.subscription.add(this.manifests$.pipe(MT(o=>o.map(({id:u,quality:l,size:c,bandwidth:d,fps:p})=>({id:u,quality:l,size:c,fps:p,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,i)),!_.device.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add(DT(md(o,"addtrack"),md(o,"removetrack"),md(o,"change"),CT(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},i))}let n=DT(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,CT(["init"])).pipe(EB(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),Re(this.video)}prepare(){let e=this.selectManifest();if(wB(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[o,u]of[[s,"mq"],[n,"lq"]]){let l=String(parseFloat(o||""));u&&o&&r.searchParams.set(u,l)}}this.video.setAttribute("src",r.toString()),this.video.load()}playIfAllowed(){Me(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:fd.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};var _T=V(qi(),1),bd=V(Zi(),1),OT=V(bt(),1);import{assertNever as RB,assertNonNullable as BT,debounce as LB,ErrorCategory as VT,isHigherOrEqual as $B,isLowerOrEqual as MB,isNonNullable as DB,merge as CB,observableFrom as BB,Subscription as VB,map as _B}from"@vkontakte/videoplayer-shared";var ms=class{constructor(e){this.subscription=new VB;this.videoState=new F("stopped");this.trackUrls={};this.textTracksManager=new ze;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(),o=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:u}=this.video;this.prepare(),o.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:u*1e3,forcePrecise:!0});return}switch(i?.to!=="paused"&&o.state==="requested"&&this.seek(o.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 RB(e)}};this.params=e,this.video=Pe(e.container,e.tuning),this.params.output.element$.next(this.video),(0,_T.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,bd.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=o=>{e.error$.next({id:"MpegProvider",category:VT.WTF,message:"MpegProvider internal logic error",thrown:o})},r=$e(this.video);this.subscription.add(()=>r.destroy());let s=(o,u)=>this.subscription.add(o.subscribe(u,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(_B(o=>o.to)),this.params.output.playbackState$),this.subscription.add(ht(this.video,t.isLooped,i)),this.subscription.add(Le(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(We(this.video,t.playbackRate,r.playbackRateState$,i)),s(Ye(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 o=this.params.desiredState.videoTrack.getTransition();if(o&&DB(o.to)){this.params.desiredState.videoTrack.setState(o.to),this.params.output.currentVideoTrack$.next(this.trackUrls[o.to.id].track);let u=this.params.desiredState.playbackRate.getState(),l=this.params.output.element$.getValue()?.playbackRate;if(u!==l){let c=this.params.output.element$.getValue();c&&(this.params.desiredState.playbackRate.setState(u),c.playbackRate=u)}}this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.textTracksManager.connect(this.video,t,e);let n=CB(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,BB(["init"])).pipe(LB(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),Re(this.video)}prepare(){let e=this.params.desiredState.videoTrack.getState()?.id;BT(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];BT(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=Wt(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(ge(t))}playIfAllowed(){Me(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:VT.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=gt(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,bd.default)(this.trackUrls).map(l=>l.track);if(!r||!s||ir(e,n[0].quality,(0,OT.default)(n,-1)?.quality)){i();return}let o=e.max?MB(r,e.max):!0,u=e.min?$B(r,e.min):!0;o&&u||i(e)}};import{assertNever as NT,debounce as UB,merge as UT,observableFrom as qB,Subscription as HB,map as qT,ValueSubject as jB,ErrorCategory as Sd,VideoQuality as QB}from"@vkontakte/videoplayer-shared";import{ErrorCategory as OB}from"@vkontakte/videoplayer-shared";var FT=["stun:videostun.mycdn.me:80"],FB=1e3,NB=3,gd=()=>null,$o=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=gd;this.externalStopCallback=gd;this.externalErrorCallback=gd;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:FT}]};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:OB.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),FB)}normalizeOptions(e={}){let t={stunServerList:FT,maxRetryNumber:NB,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var bs=class{constructor(e){this.videoState=new F("stopped");this.maxSeekBackTime$=new jB(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 NT(e)}};this.subscription=new HB,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=Pe(e.container,e.tuning),this.liveStreamClient=new $o(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),Re(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,i=n=>{e.error$.next({id:"WebRTCLiveProvider",category:Sd.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};this.subscription.add(UT(this.videoState.stateChangeStarted$.pipe(qT(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe(qT(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})}));let r=$e(this.video);this.subscription.add(()=>r.destroy());let s=(n,o)=>this.subscription.add(n.subscribe(o,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(Ye(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(Le(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 NT(n.to)}},i)).add(UT(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,qB(["init"])).pipe(UB(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:QB.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:Sd.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){Me(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:Sd.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var gs=class{constructor(e){this.iterator=e[Symbol.iterator](),this.next()}next(){this.current=this.iterator.next()}getValue(){if(this.current.done)throw new Error("Iterable is completed");return this.current.value}isCompleted(){return!!this.current.done}};import{assertNever as Ss,assertNonNullable as Kt,ErrorCategory as Mo,filter as zT,isNonNullable as YT,isNullable as JB,map as ZB,merge as e0,once as t0,Subject as pe,Subscription as KT,ValueSubject as U,flattenObject as vd}from"@vkontakte/videoplayer-shared";import{Observable as GB,map as HT,Subscription as WB,Subject as zB}from"@vkontakte/videoplayer-shared";var jT=a=>new GB(e=>{let t=new WB,i=a.desiredPlaybackState$.stateChangeStarted$.pipe(HT(({from:l,to:c})=>`${l}-${c}`)),r=a.desiredPlaybackState$.stateChangeEnded$,s=a.providerChanged$.pipe(HT(({type:l})=>l!==void 0)),n=new zB,o=0,u="unknown";return t.add(i.subscribe(l=>{o&&window.clearTimeout(o),u=l,o=window.setTimeout(()=>n.next(l),a.maxTransitionInterval)})),t.add(r.subscribe(()=>{window.clearTimeout(o),u="unknown",o=0})),t.add(s.subscribe(l=>{o&&(window.clearTimeout(o),o=0,l&&(o=window.setTimeout(()=>n.next(u),a.maxTransitionInterval)))})),t.add(n.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});import{ErrorCategory as YB,Subscription as KB,combine as XB,filter as GT,once as WT}from"@vkontakte/videoplayer-shared";function QT(){return new(window.AudioContext||window.webkitAudioContext)}var kr=class a{constructor(e,t,i,r){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=i;this.volumeMultiplier=r;this.destroyController=new K;this.subscriptions=new KB;this.audioContext=null;this.gainNode=null;this.mediaElementSource=null;this.subscriptions.add(this.provider$.pipe(GT(s=>!!s.type),WT()).subscribe(({type:s})=>this.subscribe(s)))}static{this.errorId="VolumeMultiplierManager"}subscribe(e){_.browser.isSafari&&e!=="MPEG"||this.subscriptions.add(XB({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe(GT(({playbackState:t,video:i,volume:{muted:r,volume:s}})=>t==="playing"&&!!i&&!r&&!!s),WT()).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=QT();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:YB.VIDEO_PIPELINE,message:e?.message??`${a.errorId} exception`,thrown:e})}};var i0={chunkDuration:5e3,maxParallelRequests:5},vs=class{constructor(e){this.current$=new U({type:void 0});this.providerError$=new pe;this.noAvailableProvidersError$=new pe;this.volumeMultiplierError$=new pe;this.providerOutput={position$:new U(0),duration$:new U(1/0),volume$:new U({muted:!1,volume:1}),availableVideoStreams$:new U([]),currentVideoStream$:new U(void 0),availableVideoTracks$:new U([]),currentVideoTrack$:new U(void 0),availableAudioStreams$:new U([]),currentAudioStream$:new U(void 0),availableAudioTracks$:new U([]),currentVideoSegmentLength$:new U(0),currentAudioSegmentLength$:new U(0),isAudioAvailable$:new U(!0),autoVideoTrackLimitingAvailable$:new U(!1),autoVideoTrackLimits$:new U(void 0),currentBuffer$:new U(void 0),isBuffering$:new U(!0),error$:new pe,fetcherError$:new pe,fetcherRecoverableError$:new pe,warning$:new pe,willSeekEvent$:new pe,soundProhibitedEvent$:new pe,seekedEvent$:new pe,loopedEvent$:new pe,endedEvent$:new pe,firstBytesEvent$:new pe,loadedMetadataEvent$:new pe,firstFrameEvent$:new pe,canplay$:new pe,isLive$:new U(void 0),isLiveEnded$:new U(null),isLowLatency$:new U(!1),canChangePlaybackSpeed$:new U(!0),liveTime$:new U(void 0),liveBufferTime$:new U(void 0),liveLatency$:new U(void 0),severeStallOccurred$:new pe,availableTextTracks$:new U([]),currentTextTrack$:new U(void 0),hostname$:new U(void 0),httpConnectionType$:new U(void 0),httpConnectionReused$:new U(void 0),inPiP$:new U(!1),inFullscreen$:new U(!1),element$:new U(void 0),elementVisible$:new U(!0),availableSources$:new U(void 0),is3DVideo$:new U(!1),playbackState$:new U(""),getCurrentTime$:new U(null)};this.subscription=new KT;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=Uy([...Hy(this.params.tuning),...qy(this.params.tuning)],this.params.tuning).filter(l=>YT(e.sources[l])),{forceFormat:i,formatsToAvoid:r}=this.params.tuning,s=[];i?s=[i]:r.length?s=[...t.filter(l=>!(0,yd.default)(r,l)),...t.filter(l=>(0,yd.default)(r,l))]:s=t,this.log({message:`Selected formats: ${s.join(" > ")}`}),this.tracer.log("Selected formats",vd(s)),this.screenFormatsIterator=new gs(s);let n=[...Ac(!0),...Ac(!1)];this.chromecastFormatsIterator=new gs(n.filter(l=>YT(e.sources[l]))),this.providerOutput.availableSources$.next(e.sources);let{volumeMultiplier:o=1,tuning:{useVolumeMultiplier:u}}=this.params;u&&o!==1&&kr.isSupported()&&(this.volumeMultiplierManager=new kr(this.providerOutput,this.current$,this.volumeMultiplierError$,o))}init(){this.subscription.add(this.initProviderErrorHandling()),this.subscription.add(this.params.dependencies.chromecastInitializer.connection$.subscribe(()=>{this.reinitProvider()}))}destroy(){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(JB(t)){this.handleNoFormatsError(e);return}let i;try{i=this.createProvider(e,t)}catch(r){this.providerError$.next({id:"ProviderNotConstructed",category:Mo.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()}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 Ss(e)}}createScreenProvider(e){let{sources:t,container:i,desiredState:r,panelSize:s}=this.params,n=this.providerOutput,o={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 u=this.applyFailoverHost(t[e]),l=this.applyFailoverHost(t.HLS_ONDEMAND||t.HLS);return Kt(u),this.params.tuning.useNewDashProvider?new ds({...o,source:u,sourceHls:l}):new ts({...o,source:u,sourceHls:l})}case"DASH_LIVE_CMAF":{let u=this.applyFailoverHost(t[e]);return Kt(u),this.params.tuning.useNewDashProvider?new ps({...o,source:u}):new is({...o,source:u})}case"HLS":case"HLS_ONDEMAND":{let u=this.applyFailoverHost(t[e]);return Kt(u),new fs({...o,source:u})}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let u=this.applyFailoverHost(t[e]);return Kt(u),new hs({...o,source:u,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case"MPEG":{let u=this.applyFailoverHost(t[e]);return Kt(u),new ms({...o,source:u})}case"DASH_LIVE":{let u=this.applyFailoverHost(t[e]);return Kt(u),new FS({...o,source:u,config:{...i0,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case"WEB_RTC_LIVE":{let u=this.applyFailoverHost(t[e]);return Kt(u),new bs({container:i,source:u,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 Ss(e)}}createChromecastProvider(e){let{sources:t,container:i,desiredState:r,meta:s}=this.params,n=this.providerOutput,o=this.params.dependencies.chromecastInitializer.connection$.getValue();return Kt(o),new ta({connection:o,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 Ss(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return Ss(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 Ss(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,JT.default)((0,XT.default)(e).map(([r,s])=>[r,i(s)]))}initProviderErrorHandling(){let e=new KT,t=!1,i=0;return e.add(e0(this.providerOutput.error$.pipe(zT(r=>!this.params.tuning.ignoreAudioRendererError||!r.message||!/AUDIO_RENDERER_ERROR/ig.test(r.message))),jT({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(ZB(r=>({id:`ProviderHangup:${r}`,category:Mo.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(zT(({to:s})=>s==="playing"),t0()).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 o=r.category===Mo.NETWORK,u=r.category===Mo.FATAL,l=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),c=i<this.params.tuning.providerErrorLimit&&!u,d=l&&!u&&(o&&t||!c);n={...n,isNetworkError:o,isFatalError:u,haveFailoverHost:l,tryFailover:d,canReinitProvider:c},c?(i++,this.reinitProvider()):d?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):(i=0,this.switchToNextProvider(s??"SCREEN"))}r.traceAsLog?this.tracer.log("providerInfo",vd(n)):this.tracer.error("providerError",vd(n))})),e}};import{fromEvent as Do,once as r0,combine as a0,Subscription as ZT,ValueSubject as Td,map as s0,filter as n0,isNonNullable as Co,now as He,safeStorage as Id}from"@vkontakte/videoplayer-shared";var o0=5e3,eI="one_video_throughput",tI="one_video_rtt",ys=window.navigator.connection,iI=()=>{let a=ys?.downlink;if(Co(a)&&a!==10)return a*1e3},rI=()=>{let a=ys?.rtt;if(Co(a)&&a!==3e3)return a},aI=(a,e,t)=>{let i=t*8,r=i/a;return i/(r+e)},Ed=class a{constructor(e){this.subscription=new ZT;this.concurrentDownloads=new Set;this.tuningConfig=e;let t=a.load(eI)||(e.useBrowserEstimation?iI():void 0)||o0,i=a.load(tI)??(e.useBrowserEstimation?rI():void 0)??0;if(this.throughput$=new Td(t),this.rtt$=new Td(i),this.rttAdjustedThroughput$=new Td(aI(t,i,e.rttPenaltyRequestSize)),this.throughput=$t.getSmoothedValue(t,-1,e),this.rtt=$t.getSmoothedValue(i,1,e),e.useBrowserEstimation){let r=()=>{let n=iI();n&&this.throughput.next(n);let o=rI();Co(o)&&this.rtt.next(o)};ys&&"onchange"in ys&&this.subscription.add(Do(ys,"change").subscribe(r)),r()}this.subscription.add(this.throughput.smoothed$.subscribe(r=>{Id.set(eI,r.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(r=>{Id.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(a0({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(s0(({throughput:r,rtt:s})=>aI(r,s,e.rttPenaltyRequestSize)),n0(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=He(),r=new ZT;switch(this.subscription.add(r),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:r.add(Do(e,"progress").pipe(r0()).subscribe(s=>{t=s.loaded,i=He()}));break;case 1:case 0:r.add(Do(e,"loadstart").subscribe(()=>{t=0,i=He()}));break}r.add(Do(e,"loadend").subscribe(s=>{if(e.status===200){let n=s.loaded,o=He(),u=n-t,l=o-i;this.addRawSpeed(u,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=He(),n=0,o=He(),u=c=>{this.concurrentDownloads.delete(e),i.releaseLock(),e.cancel(`Throughput Estimator error: ${c}`).catch(()=>{})},l=async({done:c,value:d})=>{if(c)!t&&this.addRawSpeed(r,He()-s,1),this.concurrentDownloads.delete(e);else if(d){if(t){let p=He();if(p-o>this.tuningConfig.lowLatency.continuesByteSequenceInterval||p-s>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let f=o-s;f&&this.addRawSpeed(n,f,1,t),n=d.byteLength,s=He()}else n+=d.byteLength;o=He()}else r+=d.byteLength,n+=d.byteLength,n>=this.tuningConfig.streamMinSampleSize&&He()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,He()-o,this.concurrentDownloads.size),n=0,o=He());await i?.read().then(l,u)}};this.concurrentDownloads.add(e),i?.read().then(l,u)}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=Id.get(e);if(Co(t))return parseInt(t,10)??void 0}},sI=Ed;import{fillWithDefault as u0,VideoQuality as Bo}from"@vkontakte/videoplayer-shared";var nI={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:Bo.Q_4320P,activeVideoAreaThreshold:.1,highQualityLimit:Bo.Q_720P,trafficSavingLimit:Bo.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:Bo.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},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,maxLiveDuration:7200,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:250,playbackCatchupSpeedup:.05,isActiveOnDefault:!1,bufferEstimator:{emaAlpha:.45,changeThreshold:.05,deviationDepth:20,deviationFactor:.5,extremumInterval:5}}},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1,lowLatencyActiveLiveDelay:3e3,activeLiveDelay:5e3,maxPausedTime:5e3},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,forceFormat:void 0,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:"07A4434E",useWebmBigRequest:!1,webmCodec:"vp9",androidPreferredFormat:"dash",preferCMAF:!1,preferWebRTC:!1,preferMultiStream:!1,preferHDR:!1,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,seekNearDurationBias:1,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useHlsJs:!1,useNativeHLSTextTracks:!1,useManagedMediaSource:!0,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,useOldMSEDetection:!1,useHlsLiveNewTextManager:!1,exposeInternalsToGlobal:!1,hlsLiveNewTextManagerDownloadThreshold:4e3,disableYandexPiP:!1,asyncResolveClientChecker:!1,autostartOnlyIfVisible:!1},oI=a=>({...u0(a,nI),configName:[...a.configName??[],...nI.configName]});import{assertNonNullable as Vo,combine as Dt,ErrorCategory as _o,filter as O,filterChanged as W,fromEvent as wd,isNonNullable as dI,isNullable as m0,Logger as b0,map as G,mapTo as pI,merge as Xt,now as Oo,once as H,Subject as z,Subscription as hI,tap as Ad,ValueSubject as R,isHigher as g0,isInvariantQuality as fI,flattenObject as Jt,throttle as kd,getTraceSubscriptionMethod as mI,TracerFactory as S0,InternalsExposure as v0}from"@vkontakte/videoplayer-shared";import{merge as l0,map as c0,filter as uI,isNonNullable as d0}from"@vkontakte/videoplayer-shared";var xd=({seekState:a,position$:e})=>l0(a.stateChangeEnded$.pipe(c0(({to:t})=>t.state==="none"?void 0:(t.position??NaN)/1e3),uI(d0)),e.pipe(uI(()=>a.getState().state==="none")));import{assertNonNullable as p0}from"@vkontakte/videoplayer-shared";var lI=a=>{let e=typeof a.container=="string"?document.getElementById(a.container):a.container;return p0(e,`Wrong container or containerId {${a.container}}`),e};import{filter as h0,once as f0}from"@vkontakte/videoplayer-shared";var cI=(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),f0()).subscribe(r=>{r.find(i)&&e.startTransitionTo(a)}):(a===void 0||t?.getValue().find(i))&&e.startTransitionTo(a)};var Fo=class{constructor(e={configName:[]},t=S0.createRootTracer(!1)){this.subscription=new hI;this.logger=new b0;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),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 z,ready$:new z,started$:new z,playing$:new z,paused$:new z,stopped$:new z,willReady$:new z,willStart$:new z,willResume$:new z,willPause$:new z,willStop$:new z,willDestruct$:new z,watchCoverageRecord$:new z,watchCoverageLive$:new z,managedError$:new z,fatalError$:new z,fetcherRecoverableError$:new z,ended$:new z,looped$:new z,seeked$:new z,willSeek$:new z,autoplaySoundProhibited$:new z,firstBytes$:new z,loadedMetadata$:new z,firstFrame$:new z,canplay$:new z,log$:new z,fetcherError$:new z,severeStallOccured$:new z};this.experimental={element$:new R(void 0),tuningConfigName$:new R([]),enableDebugTelemetry$:new R(!1),dumpTelemetry:dS,getCurrentTime$:new R(null)};if(this.initLogs(),this.tuning=oI(e),this.tracer=t,this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new Vs({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new sI(this.tuning.throughputEstimator),e.exposeInternalsToGlobal&&(this.internalsExposure=new v0("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:(...o)=>{try{return n.apply(i,o)}catch(u){let l=o.map(p=>JSON.stringify(p,(h,f)=>{let b=typeof f;return(0,bI.default)(["number","string","boolean"],b)?f:f===null?null:`<${b}>`})),c=`Player.${String(r)}`,d=`Exception calling ${c} (${l.join(", ")})`;throw this.events.fatalError$.next({id:c,category:_o.WTF,message:d,thrown:u}),u}}}})}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",Jt(n)),this.domContainer=lI(e),this.chromecastInitializer.contentId=e.meta?.videoId,this.providerContainer=new vs({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?_.isInited$.pipe(O(s=>!!s),H()).subscribe(()=>{console.log("Core SDK async start"),i()}):i()};return this.isNotActiveTabCase()?(this.tracer.log("request play from hidden tab"),wd(document,"visibilitychange").pipe(H()).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),H()).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),H()).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),H()).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),H()).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),H()).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),H()).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),H()).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),H()).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),H()).subscribe(()=>{this.desiredState.videoStream.startTransitionTo(e)})),this}setAudioStream(e){return this.subscription.add(this.playerInited.pipe(O(t=>!!t),H()).subscribe(()=>{this.desiredState.audioStream.startTransitionTo(e)})),this}setQuality(e){return this.subscription.add(this.playerInited.pipe(O(t=>!!t),H()).subscribe(()=>{Vo(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),H()).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),H()).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),H()).subscribe(()=>{this.tracer.log("setAutoQualityLimits",Jt(e)),this.desiredState.autoVideoTrackLimits.startTransitionTo(e)})),this}setPredefinedQualityLimits(e){return this.subscription.add(this.playerInited.pipe(O(t=>!!t),H()).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),H()).subscribe(()=>{Vo(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),H()).subscribe(()=>{e.length&&this.tracer.log("setExternalTextTracks",Jt(e)),this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>({type:"external",...t})))})),this}selectTextTrack(e){return this.subscription.add(this.playerInited.pipe(O(t=>!!t),H()).subscribe(()=>{cI(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),H()).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),H()).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),H()).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),H()).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),H()).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),H()).subscribe(()=>{let e=this.getScene3D();e&&e.holdCamera()})),this}releaseCamera(){return this.subscription.add(this.playerInited.pipe(O(e=>!!e),H()).subscribe(()=>{let e=this.getScene3D();e&&e.releaseCamera()})),this}getExactTime(){if(!this.providerContainer)return 0;let e=this.providerContainer.providerOutput.element$.getValue();if(m0(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),i=t.state==="none"?void 0:t.position;return dI(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(Xt(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(Wl(e,t,i))})),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(O(({from:e})=>e==="stopped"),H()).subscribe(()=>{this.initedAt=Oo(),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",Jt(n)),n.state==="requested"?this.desiredState.seekState.setState({...n,state:"applying"}):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:_o.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.soundProhibitedEvent$.pipe(H()).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",Jt(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),W()).subscribe(()=>this.isPlaybackStarted=!1)).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add(Dt({availableVideoTracks:e.providerOutput.availableVideoTracks$,currentVideoStream:e.providerOutput.currentVideoStream$}).pipe(G(({availableVideoTracks:n,currentVideoStream:o})=>n.filter(u=>o?o.id===u.streamId:!0).map(({quality:u})=>u).sort((u,l)=>fI(u)?1:fI(l)?-1:g0(l,u)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(n=>{let o={};for(let u of n)u.fps&&(o[u.quality]=u.fps);this.info.availableQualitiesFps$.next(o)})).add(e.providerOutput.availableAudioStreams$.subscribe(this.info.availableAudioStreams$)).add(e.providerOutput.currentVideoStream$.subscribe(this.info.currentVideoStream$)).add(e.providerOutput.currentAudioStream$.subscribe(this.info.currentAudioStream$)).add(e.providerOutput.availableAudioTracks$.subscribe(this.info.availableAudioTracks$)).add(e.providerOutput.isAudioAvailable$.pipe(W()).subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.pipe(O(n=>dI(n))).subscribe(n=>{this.info.currentQuality$.next(n?.quality),this.info.videoBitrate$.next(n?.bitrate)})).add(e.providerOutput.currentVideoSegmentLength$.pipe(W((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.pipe(W((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe(W()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(W()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(W()).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(Ad(n=>n&&this.stop())).subscribe(this.info.isLiveEnded$)).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(Dt({hasLiveOffsetByPaused:Xt(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(G(n=>n.to),W(),G(n=>n==="paused")),isLowLatency:e.providerOutput.isLowLatency$}).subscribe(({hasLiveOffsetByPaused:n,isLowLatency:o})=>{if(window.clearTimeout(this.hasLiveOffsetByPausedTimer),n){this.hasLiveOffsetByPausedTimer=window.setTimeout(()=>{this.hasLiveOffsetByPaused.next(!0)},this.getActiveLiveDelay(o));return}this.hasLiveOffsetByPaused.next(!1)})).add(Dt({atLiveEdge:Dt({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:xd({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(G(({isLive:n,position:o,isLowLatency:u})=>{let l=this.getActiveLiveDelay(u);return n&&Math.abs(o)<l/1e3}),W(),Ad(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(G(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add(Dt({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(G(({isLive:n,position:o,duration:u})=>n&&(Math.abs(u)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),W(),Ad(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(G(n=>n.muted),W()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(G(n=>n.volume),W()).subscribe(this.info.volume$)).add(xd({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(Xt(e.providerOutput.endedEvent$.pipe(pI(!0)),e.providerOutput.seekedEvent$.pipe(pI(!1))).pipe(W()).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:_o.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.firstBytesEvent$.pipe(H(),G(n=>n??Oo()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe(H(),G(()=>Oo()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(H(),G(()=>Oo()-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"),H()).subscribe(()=>i.next(!1)));let r=0,s=Xt(e.providerOutput.isBuffering$,t,i).pipe(G(()=>{let n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||i.getValue();return n&&!o}),W());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(Xt(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{let n=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:n?.videoWidth,height:n?.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{let o=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:n?.size?.width,height:n?.size?.height},{width:o?.videoWidth,height:o?.videoHeight})})).add(e.providerOutput.is3DVideo$.subscribe(this.info.is3DVideo$)),this.subscription.add(Xt(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,e.providerOutput.elementVisible$,this.chromecastInitializer.castState$).subscribe(()=>{let n=e.providerOutput.inPiP$.getValue(),o=e.providerOutput.inFullscreen$.getValue(),u=e.providerOutput.element$.getValue(),l=e.providerOutput.elementVisible$.getValue(),c=this.chromecastInitializer.castState$.getValue(),d;c==="CONNECTED"?d="second_screen":u?l?n?d="pip":o?d="fullscreen":d="inline":d="invisible":d="none",this.info.surface$.getValue()!==d&&this.info.surface$.next(d)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(G(e=>e?.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){let t=new hI;this.subscription.add(t),this.subscription.add(e.current$.pipe(W((i,r)=>i.provider===r.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(O(i=>i.length>0),H()).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=gt(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(Xt(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;Vo(this.providerContainer),Vo(e),cS(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(t=>lS(t)),this.providerContainer.current$.subscribe(({type:t})=>na("provider",t)),e.duration$.subscribe(t=>na("duration",t)),e.availableVideoTracks$.pipe(O(t=>!!t.length),H()).subscribe(t=>na("tracks",t)),this.events.fatalError$.subscribe(new xe("fatalError")),this.events.managedError$.subscribe(new xe("managedError")),e.position$.subscribe(new xe("position")),e.currentVideoTrack$.pipe(G(t=>t?.quality)).subscribe(new xe("quality")),this.info.currentBuffer$.subscribe(new xe("buffer")),e.isBuffering$.subscribe(new xe("isBuffering"))].forEach(t=>this.subscription.add(t)),na("codecs",_.video.supportedCodecs)}initTracerSubscription(){let e=mI(this.tracer.log.bind(this.tracer)),t=mI(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(W()).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(Dt({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe(O(({currentQuality:i,videoBitrate:r})=>!!i&&!!r),W((i,r)=>i.currentQuality===r.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe(O(i=>i>0),W()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe(O(i=>i>0),W()).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(Dt({currentBuffer:this.info.currentBuffer$.pipe(O(i=>i.end>0),W((i,r)=>i.end===r.end&&i.start===r.start)),position:this.info.position$.pipe(W())}).pipe(kd(1e3)).subscribe(e("currentBufferAndPosition"))).add(this.info.duration$.pipe(W()).subscribe(e("duration"))).add(this.info.isBuffering$.subscribe(e("isBuffering"))).add(this.info.isLive$.pipe(W()).subscribe(e("isLive"))).add(this.info.canChangePlaybackSpeed$.pipe(W()).subscribe(e("canChangePlaybackSpeed"))).add(Dt({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe(O(({liveTime:i,liveBufferTime:r})=>!!i&&!!r),kd(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe(W(),O(i=>i===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe(W(),O(i=>i===!0)).subscribe(e("atLiveDurationEdge"))).add(this.info.muted$.pipe(W()).subscribe(e("muted"))).add(this.info.volume$.pipe(W()).subscribe(e("volume"))).add(this.info.isEnded$.pipe(W(),O(i=>i===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add(Dt({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe(O(({throughputEstimation:i,rtt:r})=>!!i&&!!r),kd(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe(W(),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:_o.DOM,message:String(r)})})};this.subscription.add(Xt(wd(document,"visibilitychange"),wd(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",Jt({quality:t,availableTracks:Jt(e),track:Jt(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&&!ha()}};import{Subscription as vX,Observable as yX,Subject as TX,ValueSubject as IX,VideoQuality as EX}from"@vkontakte/videoplayer-shared";var xX=`@vkontakte/videoplayer-core@${Ld}`;export{Rs as ChromecastState,qo as HttpConnectionType,yX as Observable,ke as PlaybackState,Fo as Player,Ls as PredefinedQualityLimits,xX as SDK_VERSION,TX as Subject,vX as Subscription,Ho as Surface,Ld as VERSION,IX as ValueSubject,Et as VideoFormat,EX as VideoQuality,cL as areValidLiveRecordSources,_ as clientChecker,sa as isMobile};
178
+ `;var Tr=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 no(this.params.fov,this.params.orientation),this.cameraRotationManager=new oo(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(zy,this.gl.VERTEX_SHADER),i=this.createShader(Yy,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,o=e+i,u=t-r,l=e+i,c=t+r,d=e-i,p=t+r;return[s,n,o,u,l,c,d,p]}updateTextureMappingBuffer(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([...this.calculateTexturePosition()]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}updateFrameSize(){this.frameWidth=this.sourceVideoElement.videoWidth,this.frameHeight=this.sourceVideoElement.videoHeight}createCanvas(){let e=document.createElement("canvas");return e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e}};import{isNullable as aC,now as es,once as sC,Subscription as nC,ValueSubject as Mc,isNonNullable as oC,safeStorage as Dc,filterChanged as uC}from"@vkontakte/videoplayer-shared";var uo="stalls_manager_metrics",Cc="stalls_manager_abr_params",Ky="stalls_manager_default_tuning_abr_params",Bc=class{constructor(){this.isSeeked$=new Mc(!1);this.isBuffering$=new Mc(!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 nC;this.severeStallOccurred$=new Mc(!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(Cc):{};return{...this.abrParams,...e}}set lastVideoTrackSelected(e){this.lastUniqueVideoTrackSelected?.id!==e.id&&(this.lastUniqueVideoTrackSelected=e,this.lastUniqueVideoTrackSelectedTimestamp=es(),this.currentStallsCount=0)}destroy(){window.clearTimeout(this.qualityRestrictionTimer),this.subscription.unsubscribe(),this.currentStallDuration$.getValue()!==0&&this.updateStallData();let e=(es()-this.providerStartWatchingTimestamp-this.sumStallsDuration)/1e3,t=this.sumStallsDuration;this.addStallInfoToHistory(e,t),this.updateStoredAbrParams()}resetStoredAbrParamsIfNeeded(){let{bitrateFactorAtEmptyBuffer:e,bitrateFactorAtFullBuffer:t,containerSizeFactor:i}={...this.getStoredData(Ky)},{bitrateFactorAtEmptyBuffer:r,bitrateFactorAtFullBuffer:s,containerSizeFactor:n}={...this.abrParams};this.tuning.enabled&&e===r&&t===s&&i===n||(this.removeStoredData(Cc),this.setStoredData(Ky,{bitrateFactorAtEmptyBuffer:r,bitrateFactorAtFullBuffer:s,containerSizeFactor:n}))}updateStoredAbrParams(){let e=[],t=this.getStoredData(uo,"[]");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((o,u)=>o+u.stallsDuration,0)/i;e.push(this.calculateOptimalAbrParams(n,i))}if(this.tuning.useAverageStallsDurationPerTvt){let s=t.reduce((n,o)=>n+o.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(uo,[]),this.setStoredData(Cc,r)}calculateOptimalAbrParams(e,t){let{targetStallsDurationPerTvt:i,deviationStallsDurationPerTvt:r,criticalStallsDurationPerTvt:s,abrAdjustingSpeed:n,significantTvt:o,stallsMetricsHistoryLength:u}=this.tuning,l=n*Math.min(t/(o*u),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(Dc.get(e)??t)}setStoredData(e,t){Dc.set(e,JSON.stringify(t))}removeStoredData(e){Dc.remove(e)}addStallInfoToHistory(e,t){if(e<this.tuning.minTvtToBeCounted||e>this.tuning.maxTvtToBeCounted||e*1e3<t)return;let i=this.getStoredData(uo,"[]"),r=t/e,s=i.length?Lt(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(uo,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(sC()).subscribe(t=>this.providerStartWatchingTimestamp=es())),this.subscription.add(this.currentStallDuration$.pipe(uC()).subscribe(t=>{let{stallDurationNoDataBeforeQualityDecrease:i,stallCountBeforeQualityDecrease:r,resetQualityRestrictionTimeout:s,ignoreStallsOnSeek:n}=this.tuning;if(aC(this.lastUniqueVideoTrackSelected)||n&&this.isSeeked$.getValue())return;let o=this.rtt$.getValue(),u=this.throughput$.getValue(),l=this.videoLastDataObtainedTimestamp$.getValue(),c=es(),d=r&&this.currentStallsCount>=r,p=i&&c-this.lastUniqueVideoTrackSelectedTimestamp>=i+o&&c-l>=i+o&&t>=i;(d||p)&&(this.severeStallOccurred$.next(!0),window.clearTimeout(this.qualityRestrictionTimer),this.maxQualityLimit=this.lastUniqueVideoTrackSelected.quality,oC(this.lastUniqueVideoTrackSelected.bitrate)&&u>this.lastUniqueVideoTrackSelected.bitrate&&(this.predictedThroughputWithoutData=this.lastUniqueVideoTrackSelected.bitrate)),!t&&es()-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}))}},lo=Bc;import{combine as lC,map as cC,observeElementSize as dC,Subscription as pC,ValueSubject as Vc,noop as hC}from"@vkontakte/videoplayer-shared";var co=class{constructor(){this.subscription=new pC;this.pipSize$=new Vc(void 0);this.videoSize$=new Vc(void 0);this.elementSize$=new Vc(void 0);this.pictureInPictureWindowRemoveEventListener=hC}connect({observableVideo:e,video:t}){let i=r=>{let s=r.target;this.pipSize$.next({width:s.width,height:s.height})};this.subscription.add(dC(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(lC({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe(cC(({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 yi=class{constructor(e){this.subscription=new yC;this.videoState=new F("stopped");this.observableVideo=null;this.droppedFramesManager=new or;this.stallsManager=new lo;this.elementSizeManager=new co;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new Ht;this.audioTrackSwitchHistory=new Ht;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 mC(e)}}};this.init3DScene=e=>{if(this.scene3D)return;this.scene3D=new Tr(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 ze(e.source.url),this.params=e,this.video=Pe(e.container,e.tuning),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(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 so({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode,tracer:this.tracer}),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params;vC(this.observableVideo)&&(this.observableVideo=$e(this.video),this.subscription.add(()=>this.observableVideo?.destroy()));let i=this.constructor.name,r=n=>{e.error$.next({id:i,category:Xy.WTF,message:`${i} internal logic error`,thrown:n})},s=(n,o)=>this.subscription.add(n.subscribe(o,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(_c(l=>!!l.length),Zy()).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(Oc(l=>l.to.state!=="none"),po());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(_c(Jy),Zy()),e.firstBytesEvent$),s(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),s(this.videoState.stateChangeEnded$.pipe(Oc(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(ht(this.video,t.isLooped,r)),this.subscription.add(Le(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(We(this.video,t.playbackRate,i.playbackRateState$,r)),this.elementSizeManager.connect({video:this.video,observableVideo:i}),s(Ye(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.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();if(bC(c,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let p=[];for(let h of c.audio){p.push(vc(h));let f=[];for(let b of h.representations){let g=$y(b);f.push(g),this.audioTracksMap.set(g,{stream:h,representation:b})}this.audioStreamsMap.set(h,f)}this.params.output.availableAudioStreams$.next(p)}let d=[];for(let p of c.video){d.push(yc(p));let h=[];for(let f of p.representations){let b=Ly({...f,streamId:p.id});b&&(h.push(b),this.videoTracksMap.set(b,{stream:p,representation:f}))}this.videoStreamsMap.set(p,h)}this.params.output.availableVideoStreams$.next(d);for(let p of c.text)for(let h of p.representations){let f=My(p,h);this.textTracksMap.set(f,{stream:p,representation:h})}this.params.output.availableVideoTracks$.next(Array.from(this.videoTracksMap.keys())),this.params.output.availableAudioTracks$.next(Array.from(this.audioTracksMap.keys())),this.params.output.isAudioAvailable$.next(!!this.audioTracksMap.size),this.audioTracksMap.size&&this.textTracksMap.size&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else l==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},r)),this.subscription.add(ho(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$,SC(this.video,"progress")).pipe(_c(()=>this.videoTracksMap.size>0)).subscribe(async()=>{let l=this.player.state$.getState(),c=this.player.state$.getTransition();if(!(0,eT.default)(["manifest_ready","running"],l)||c)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let d=this.selectVideoAudioRepresentations();if(!d)return;let[p,h]=d,f=[...this.videoTracksMap.keys()].find(g=>this.videoTracksMap.get(g)?.representation.id===p.id);Jy(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(p.id,h?.id,this.params.sourceHls);else if(await this.player.switchRepresentation("video",p.id),h){let g=!!t.audioStream.getTransition();await this.player.switchRepresentation("audio",h.id,g)}},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(po()).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[d,{stream:p}]=c,h=this.params.desiredState.videoStream.getTransition();h&&h.to&&h.to.id===p.id&&this.params.desiredState.videoStream.setState(h.to),e.currentVideoTrack$.next(d),e.currentVideoStream$.next(yc(p));let f=this.player.calculateDurationFromSegments();f&&this.params.output.duration$.next(f/1e3)},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(po()).subscribe(l=>{let c=[...this.audioTracksMap.entries()].find(([,{representation:f}])=>f.id===l);if(!c){e.currentAudioStream$.next(void 0);return}let[d,{stream:p}]=c,h=this.params.desiredState.audioStream.getTransition();h&&h.to&&h.to.id===p.id&&this.params.desiredState.audioStream.setState(h.to),e.currentAudioStream$.next(vc(p))},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 o=t.playbackState.stateChangeStarted$.pipe(Oc(({to:l})=>l==="ready"),po());this.subscription.add(ho(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,Fc(["init"])).subscribe(()=>{let l=t.autoVideoTrackSwitching.getState(),d=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:l?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(d)})),this.subscription.add(ho(o,this.player.state$.stateChangeEnded$,Fc(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let u=ho(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Fc(["init"])).pipe(gC(0));this.subscription.add(u.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?ua:oa,t=this.params.tuning.useNewAutoSelectVideoTrack?Cn:Dn,i=this.params.tuning.useNewAutoSelectVideoTrack?gt:Mn,{desiredState:r,output:s}=this.params,n=r.autoVideoTrackSwitching.getState(),o=r.videoTrack.getState()?.id,l=[...this.videoTracksMap.keys()].find(({id:y})=>y===o),c=s.currentVideoTrack$.getValue(),d=r.videoStream.getState()??(l&&this.videoTracksMap.get(l)?.stream)??this.videoStreamsMap.size===1?this.videoStreamsMap.keys().next().value:void 0;if(!d)return;let p=[...this.videoStreamsMap.keys()].find(({id:y})=>y===d.id),h=p&&this.videoStreamsMap.get(p);if(!h)return;let f=de(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 g=(this.video.duration*1e3||1/0)-this.video.currentTime*1e3,S=Math.min(f/Math.min(b,g||1/0),1),T=r.audioStream.getState()??(this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0),v=[...this.audioStreamsMap.keys()].find(({id:y})=>y===T?.id)??this.audioStreamsMap.keys().next().value,x=0;if(v){if(l&&!n){let y=e(l,h,this.audioStreamsMap.get(v)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);x=Math.max(x,y?.bitrate??-1/0)}if(c){let y=e(c,h,this.audioStreamsMap.get(v)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);x=Math.max(x,y?.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:x,forwardBufferHealth:S,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}),L=n?w??l:l??w,B=v&&t(L,h,this.audioStreamsMap.get(v)??[],{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}),A=this.videoTracksMap.get(L)?.representation,$=B&&this.audioTracksMap.get(B)?.representation;if(A&&$)return[A,$];if(A&&!$&&this.audioTracksMap.size===0)return[A,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){Me(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:Xy.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),Re(this.video),this.tracer.end()}};var ts=class extends yi{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 Nc,merge as tT,filter as iT,filterChanged as TC,isNullable as Uc,map as rT,ValueSubject as qc,isNonNullable as IC}from"@vkontakte/videoplayer-shared";var is=class extends yi{constructor(e){super(e),this.textTracksManager.destroy()}subscribe(){super.subscribe();let e=-1,{output:t,observableVideo:i,desiredState:r,connect:s}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),s(i.timeUpdate$,t.liveBufferTime$),s(this.player.liveSeekableDuration$,t.duration$),s(this.player.liveLatency$,t.liveLatency$);let n=new qc(1);s(i.playbackRateState$,n),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(r.isLowLatency.stateChangeEnded$.pipe(rT(o=>o.to)).subscribe(this.player.isLowLatency$)).add(Nc({liveBufferTime:t.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(rT(({liveBufferTime:o,liveAvailabilityStartTime:u})=>o&&u?o+u:void 0)).subscribe(t.liveTime$)).add(this.player.liveStreamStatus$.pipe(iT(o=>IC(o))).subscribe(o=>t.isLiveEnded$.next(o!=="active"&&t.position$.getValue()===0))).add(Nc({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:tT(i.playbackRateState$,new qc(1))}).pipe(iT(({liveStreamStatus:o,liveDuration:u})=>o==="active"&&!!u)).subscribe(({liveDuration:o,playbackRate:u})=>{let l=t.liveBufferTime$.getValue(),c=t.position$.getValue(),{playbackCatchupSpeedup:d}=this.params.tuning.dashCmafLive.lowLatency;c||u<1-d||this.video.paused||Uc(l)||(e=o-l)})).add(Nc({time:t.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:tT(i.playbackRateState$,new qc(1))}).pipe(TC((o,u)=>this.player.liveStreamStatus$.getValue()==="active"?o.liveDuration===u.liveDuration:o.time===u.time)).subscribe(({time:o,liveDuration:u,playbackRate:l})=>{let c=t.position$.getValue(),{playbackCatchupSpeedup:d}=this.params.tuning.dashCmafLive.lowLatency;if(!c&&!this.video.paused&&l>=1-d||Uc(o)||Uc(u))return;let p=-1*(u-o-e);t.position$.next(Math.min(p,0))})).add(this.player.currentLiveTextRepresentation$.subscribe(o=>{if(o){let u=Dy(o);this.params.output.availableTextTracks$.next([u])}}))}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 zC,assertNonNullable as YC,debounce as KC,ErrorCategory as TT,filter as ad,filterChanged as wo,fromEvent as XC,isNonNullable as IT,isNullable as JC,map as sd,merge as Ao,observableFrom as nd,once as ET,Subscription as ZC}from"@vkontakte/videoplayer-shared";var id=V(ga(),1);import{abortable as Jc,assertNonNullable as xr,combine as wr,ErrorCategory as nt,filter as To,filterChanged as us,flattenObject as ls,fromEvent as Tt,getTraceSubscriptionMethod as OC,interval as Zc,isNonNullable as cs,isNullable as vT,map as Ar,merge as wi,now as ed,Subject as Io,Subscription as td,tap as FC,throttle as yT,ValueSubject as te}from"@vkontakte/videoplayer-shared";var go=V(Ge(),1),xi=V(bt(),1),So=V(ga(),1);var fT=V(dn(),1);import{assertNever as EC,ErrorCategory as aT,Subject as sT}from"@vkontakte/videoplayer-shared";var xC=18,nT=!1;try{nT=_.browser.isSafari&&!!_.browser.safariVersion&&_.browser.safariVersion<=xC}catch(a){console.error(a)}var jc=class{constructor(e){this.bufferFull$=new sT;this.error$=new sT;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:aT.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)};nT&&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:aT.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:EC(t)}}},oT=jc;import{abortable as Yt,assertNonNullable as Ce,ErrorCategory as Ii,fromEvent as zc,getExponentialDelay as Yc,isNonNullable as Ir,isNullable as ye,now as bo,once as RC,Subject as LC,Subscription as $C,ValueSubject as Ei}from"@vkontakte/videoplayer-shared";var Hc=V(bt(),1);import{videoSizeToQuality as wC,throttleFn as AC}from"@vkontakte/videoplayer-shared";var uT=({id:a,width:e,height:t,bitrate:i,fps:r,quality:s,streamId:n})=>{let o=(s?jt(s):void 0)??wC({width:e,height:t});return o&&{id:a,quality:o,bitrate:i,size:{width:e,height:t},fps:r,streamId:n}},lT=({id:a,bitrate:e})=>({id:a,bitrate:e}),cT=({language:a,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:a,label:e}),dT=({language:a,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:a,label:e}),Qc=({id:a,language:e,label:t,codecs:i,isDefault:r})=>({id:a,language:e,label:t,codec:(0,Hc.default)(i.split("."),0),isDefault:r}),Gc=({id:a,language:e,label:t,hdr:i,codecs:r})=>({id:a,language:e,hdr:i,label:t,codec:(0,Hc.default)(r.split("."),0)}),Wc=a=>"url"in a,qe=a=>a.type==="template";var pT=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},Ti=(a,e)=>{for(let t of a)if(e(t))return t;return null},hT=a=>{let e=!1,t=AC(()=>{e=!0},a);return()=>{try{return t(),e}finally{e=!1}}};import{fromEvent as kC,Subscription as PC}from"@vkontakte/videoplayer-shared";var fo=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 mo=class{constructor(e,t){this.lastUpdateTs=0;this.lastCallTs=0;this.prevRanges=[];this.subscription=new PC;this.mediaSource=e,this.sourceBuffer=t,this.subscription.add(kC(this.sourceBuffer,"updateend").subscribe(()=>this.updateend()))}updateend(){if(!C(this.mediaSource,this.sourceBuffer))return;let{prevRanges:e}=this,t=fo(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],o=t[i+1];if(n>r||o<s)return!0}return!1}wasUpdated(){let{lastCallTs:e,lastUpdateTs:t}=this;return this.lastCallTs=Date.now(),e<=t}destroy(){this.subscription.unsubscribe()}};var rs=class{constructor(e,t,i,{fetcher:r,tuning:s,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!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 LC;this.gaps=[];this.subscription=new $C;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new K;this.switchAbortController=new K;this.destroyAbortController=new K;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=Yt(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);Ce(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new oT(this.sourceBuffer),this.sourceBufferBufferedDiff=new mo(this.mediaSource,this.sourceBuffer),this.subscription.add(zc(this.sourceBuffer,"updateend").subscribe(()=>{this.maintain()})),this.subscription.add(zc(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:Ii.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o||!C(this.mediaSource,this.sourceBuffer))return;let u=Math.min(this.bufferLimit,cr(this.sourceBuffer.buffered)*.8);this.bufferLimit=u;let l=de(this.sourceBuffer.buffered,o),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(o,n*2,l<c).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);Ce(i,"No init buffer for starting representation"),Ce(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=Yt(this.destroyAbortController.signal,async function*(e,t=!1){if(!C(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);Ce(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),Ce(r,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!C(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();Ir(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=Yt(this.destroyAbortController.signal,async function*(e,t=!1){if(!C(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);Ce(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),Ce(r,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!C(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();Ir(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=Yt(this.destroyAbortController.signal,async function*(e){let t=(0,So.default)(e,u=>u.representations)??[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let u of this.representations.keys()){let l=t.find(p=>p.id===u);l&&this.representations.set(u,l);let c=this.representations.get(u);if(!c||!qe(c.segmentReference))return;let d=this.getActualLiveStartingSegments(c.segmentReference);this.segments.set(c.id,d)}let i=this.switchingToRepresentationId??this.downloadingRepresentationId,r=this.representations.get(i);Ce(r);let s=this.segments.get(i);Ce(s,"No segments for starting representation");let n=this.initData.get(i);if(Ce(n,"No init buffer for starting representation"),!(n instanceof ArrayBuffer))return;let o=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,yield this.abort(),o&&(yield this.sourceBufferTaskQueue.remove(o.from*1e3,o.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=u,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=o,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){!C(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new K,Yt(this.switchAbortController.signal,async function*(i,r=!1){this.switchingToRepresentationId=i;let s=this.representations.get(i);Ce(s,`No such representation ${i}`);let n=this.segments.get(i),o=this.initData.get(i);if(ye(o)||ye(n)?yield this.loadInit(s,"high",!1):o instanceof Promise&&(yield o),n=this.segments.get(i),Ce(n,"No segments for starting representation"),o=this.initData.get(i),!(!(o instanceof ArrayBuffer)||!this.sourceBuffer||!C(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(o,this.downloadAbortController.signal),r)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=i,yield this.dropBuffer();else{let u=this.getCurrentPosition();Ir(u)&&!this.isLive&&(this.bufferLimit=this.forwardBufferTarget,yield this.pruneBuffer(u,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 K,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(ye(e)||ye(this.downloadingRepresentationId)||ye(this.playingRepresentationId)||ye(this.sourceBuffer)||!C(this.mediaSource,this.sourceBuffer)||Ir(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if(Ce(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;let r=i.find(c=>e>=c.time.from&&e<c.time.to);Ir(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=de(this.sourceBuffer.buffered,e),d=r?r.time.to+n:-1/0;r&&r.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&c>=r.time.to-e+n&&(s=d)}if(isFinite(this.bufferLimit)&&cr(this.sourceBuffer.buffered)>=this.bufferLimit){let c=de(this.sourceBuffer.buffered,e),d=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,c<d).catch(p=>{this.handleAsyncError(p,"pruneBuffer")});return}let u=null;if(!this.activeSegments.size&&(u=this.selectForwardBufferSegments(i,t.segmentReference.type,s),u?.length)){let c="auto";if(this.tuning.dash.useFetchPriorityHints&&r)if((0,go.default)(u,r))c="high";else{let d=(0,xi.default)(u,0);d&&d.time.from-r.time.to>=this.forwardBufferTarget/2&&(c="low")}this.loadSegments(u,t,c).catch(d=>{this.handleAsyncError(d,"loadSegments")})}(!this.preloadOnly&&!this.allInitsLoaded&&r&&r.status==="fed"&&!u?.length&&de(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let l=(0,xi.default)(i,-1);!this.isLive&&l&&(this.fullyBuffered$.next(l.time.to-e-de(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;Ir(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,So.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,So.default)(e?.streams[this.kind],i=>i.representations)??[];if(![...this.segments.values()].every(i=>!i.length))for(let i of t){if(!i||!qe(i.segmentReference))return;let r=i.segmentReference.segments.map(l=>({...l,status:"none",size:void 0})),s=100,n=this.segments.get(i.id)??[],o=(0,xi.default)(n,-1)?.time.to??0,u=r?.findIndex(l=>o>=l.time.from+s&&o<=l.time.to+s);if(u===-1){this.liveUpdateSegmentIndex=0;let l=this.getActualLiveStartingSegments(i.segmentReference);this.segments.set(i.id,l)}else{let l=r.slice(u+1);this.segments.set(i.id,[...n,...l])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;Ce(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(!qe(r))return;let s=this.segments.get(i.id);if(!s)continue;let n=s.find(u=>Math.floor(u.time.from)===Math.floor(e.time.from));if(n&&!isFinite(n.time.to)&&(n.time.to=e.time.to,t=n.time.to-n.time.from),!!!s.find(u=>Math.floor(u.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let u=Math.round(e.time.to*r.timescale/1e3).toString(10),l=at(r.segmentTemplateUrl,{segmentTime:u});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&&St&&St(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&St&&St(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:p,time:{from:h,to:f}},b)=>{let g=h<=i&&f>=i,S=h>i||g||b===0&&i===0,T=Math.min(this.forwardBufferTarget,this.bufferLimit),v=this.preloadOnly&&h<=i+T||r<T&&f-h>=T||f<=i+T;return(p==="none"||p==="partially_ejected"&&S&&v&&this.sourceBuffer&&C(this.mediaSource,this.sourceBuffer)&&!(Se(this.sourceBuffer.buffered,h)&&Se(this.sourceBuffer.buffered,f)))&&S&&v});if(s===-1)return null;if(t!=="byteRange")return e.slice(s,s+1);let n=e,o=0,u=0,l=[],c=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,d=this.preloadOnly?this.forwardBufferTarget:0;for(let p=s;p<n.length&&(o<=c||u<=d);p++){let h=n[p];if(o+=h.byte.to+1-h.byte.from,u+=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"){qe(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:o,onProgress:u,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(await Yt(o,async function*(){let c=Yc(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(d=>setTimeout(d,c))}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let c=await this.fetcher.fetch(n,{range:s,signal:o,onProgress:u,priority:i,isLowLatency:this.isActiveLowLatency()});if(this.lastDataObtainedTimestampMs=bo(),!c)return;let d=new DataView(c),p=vt(t.mime);if(!isFinite(r.segment.time.to)){let b=t.segmentReference.timescale;r.segment.time.to=p.getChunkEndTime(d,b)}u&&r.feedingBytes&&l?await Promise.all(l):await this.sourceBufferTaskQueue.append(d,o);let{serverDataReceivedTimestamp:h,serverDataPreparedTime:f}=p.getServerLatencyTimestamps(d);h&&f&&this.currentLiveSegmentServerLatency$.next(f-h),r.segment.status="downloaded",this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(c){this.abortActiveSegments([e]),yt(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())qe(t.segmentReference)?t.segmentReference.baseUrl=e:t.segmentReference.url=e}async loadByteRangeSegments(e,t,i="auto"){if(!e.length)return;for(let u of e)u.status="downloading",this.activeSegments.add({segment:u,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:r,url:s,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(await Yt(n,async function*(){let u=Yc(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),zc(window,"online").pipe(RC()).subscribe(()=>{l(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(s,{range:r,onProgress:o,signal:n,priority:i}),this.lastDataObtainedTimestampMs=bo(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),yt(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}prepareByteRangeFetchSegmentParams(e,t){if(qe(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(o,u)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=bo(),await this.onSomeByteRangesDataLoaded({dataView:o,loaded:u,signal:s,onSegmentAppendFailed:()=>this.abort(),globalFrom:r?r.from:0,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:Ii.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!qe(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=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(l,c)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=bo();let d=this.onSomeTemplateDataLoaded({dataView:l,loaded:c,signal:s,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(d)}catch(d){this.error$.next({id:"SegmentFeeding",category:Ii.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:d})}}:void 0;return{url:r,signal:s,onProgress:u,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)(0,go.default)(e,t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:r,signal:s}){if(!this.activeSegments.size||!C(this.mediaSource,this.sourceBuffer))return;let n=this.representations.get(t);if(n)for(let o of this.activeSegments){let{segment:u}=o;if(o.representationId===t){if(s.aborted){r();continue}if(o.loadedBytes=i,o.loadedBytes>o.feedingBytes){let l=new DataView(e.buffer,e.byteOffset+o.feedingBytes,o.loadedBytes-o.feedingBytes),c=vt(n.mime).parseFeedableSegmentChunk(l,this.isLive);c?.byteLength&&(u.status="partially_fed",o.feedingBytes+=c.byteLength,await this.sourceBufferTaskQueue.append(c),o.fedBytes+=c.byteLength)}}}}async onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:s,onSegmentAppendFailed:n}){if(!this.activeSegments.size||!C(this.mediaSource,this.sourceBuffer))return;let o=this.representations.get(t);if(o)for(let u of this.activeSegments){if(u.representationId!==t)continue;if(s.aborted){await n();continue}let{segment:l}=u,c=l.byte.from-i,d=l.byte.to-i,p=d-c+1,h=c<r,f=d<=r;if(h){if(l.status==="downloading"&&f){l.status="downloaded";let b=new DataView(e.buffer,e.byteOffset+c,p);await this.sourceBufferTaskQueue.append(b,s)&&!s.aborted?this.onSegmentFullyAppended(u,t):await n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(l.status==="downloading"||l.status==="partially_fed")&&(u.loadedBytes=Math.min(p,r-c),u.loadedBytes>u.feedingBytes)){let b=new DataView(e.buffer,e.byteOffset+c+u.feedingBytes,u.loadedBytes-u.feedingBytes),g=u.loadedBytes===p?b:vt(o.mime).parseFeedableSegmentChunk(b);g?.byteLength&&(l.status="partially_fed",u.feedingBytes+=g.byteLength,await this.sourceBufferTaskQueue.append(g,s)&&!s.aborted?(u.fedBytes+=g.byteLength,u.fedBytes===p&&this.onSegmentFullyAppended(u,t)):await n())}}}}onSegmentFullyAppended(e,t){if(!(ye(this.sourceBuffer)||!C(this.mediaSource,this.sourceBuffer))){!this.isLive&&_.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:Ii.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",Wc(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=lr(()=>(0,fT.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?Yt(this.destroyAbortController.signal,async function*(){let o=Yc(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,vt(e.mime),r)).then(o=>{if(!o)return;let{init:u,dataView:l,segments:c}=o,d=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,d);let p=c;this.isLive&&qe(e.segmentReference)&&(p=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,p),u&&this.parsedInitData.set(e.id,u)}).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:Ii.WTF,message:"loadInit threw",thrown:o})});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||!C(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||ye(e))return!1;this.checkEjectedSegments();let r=[],s=0,n=o=>{if(s>=t)return;r.push({...o.time});let u=Wc(o)?o.size??0:o.byte.to-o.byte.from;s+=u};for(let o of this.segments.values())for(let u of o){let l=u.time.to<=e-this.tuning.dash.bufferPruningSafeZone,c=u.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(l||c)&&u.status==="fed"&&n(u)}for(let o=0;o<this.sourceBuffer.buffered.length;o++){let u=this.sourceBuffer.buffered.start(o)*1e3,l=this.sourceBuffer.buffered.end(o)*1e3,c=0;for(let d of this.segments.values())for(let p of d)(0,go.default)(["none","partially_ejected"],p.status)&&Math.round(p.time.from)<=Math.round(u)&&Math.round(p.time.to)>=Math.round(l)&&c++;if(c===this.segments.size){let d={time:{from:u,to:l},url:"",status:"none"};n(d)}}if(r.length&&i){let o=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let u of this.segments.values())for(let l of u)l.time.from>=e+o&&l.status==="fed"&&n(l)}return r.length?(r=pT(r),(await Promise.all(r.map(u=>this.sourceBufferTaskQueue.remove(u.from,u.to)))).reduce((u,l)=>u||l,!1)):!1}async abortBuffer(){if(!this.sourceBuffer||!C(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||!C(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||!C(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||!C(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||ye(e)?0:de(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!this.sourceBuffer||!C(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),o=Math.round(s.to);for(let u=0;u<i.length;u++)if(n>=Math.round(i.start(u)*1e3)&&o<=Math.round(i.end(u)*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,o=i.end(s)*1e3;if(!(o<=t.time.from||n>=t.time.to)){if(n<=t.time.from&&o>=t.time.to){r=void 0;break}o>t.time.from&&o<t.time.to&&(r.from=o),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||!C(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=lr(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:Ii.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if(ye(this.sourceBuffer)||!C(this.mediaSource,this.sourceBuffer)||ye(this.playingRepresentationId)||this.sourceBufferBufferedDiff&&!this.sourceBufferBufferedDiff.wasUpdated())return;let e=fo(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),o=Math.ceil(r.time.to),u=!1,l=0;for(let c=0;c<e.length;c+=2){let d=e[c],p=e[c+1];u||(u=d-t<=n&&p+t>=o),(n>=d&&n<p-t||o>d+t&&o<=p)&&(l+=1)}u||(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:Ii.VIDEO_PIPELINE,thrown:e,message:"Something went wrong"})}calculateDurationFromSegments(){if(!this.playingRepresentationId)return 0;let e=this.segments.get(this.playingRepresentationId);return(e?(0,xi.default)(e,-1)?.time.to:0)||0}};import{abortable as as,assertNever as mT,fromEvent as bT,merge as MC,now as ss,Subject as gT,ValueSubject as Kc,flattenObject as Er,ErrorCategory as ns,SubscriptionRemovable as DC}from"@vkontakte/videoplayer-shared";var yo=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:s=!1}){this.lastConnectionType$=new Kc(void 0);this.lastConnectionReused$=new Kc(void 0);this.lastRequestFirstBytes$=new Kc(void 0);this.recoverableError$=new gT;this.error$=new gT;this.abortAllController=new K;this.subscription=new DC;this.fetchManifest=as(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=Wt(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=Wn(i));let r=yield this.doFetch(i,{signal:this.abortAllController.signal}).catch(vo);return r?(t.log("success",Er({url:i,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(r.headers),r.text()):(t.error("error",Er({url:i,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=as(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:i,onProgress:r,priority:s="auto",signal:n,measureThroughput:o=!0,isLowLatency:u=!1}={}){let l=e,c=new Headers,d=this.tracer.createComponentTracer("Fetch");if(i)switch(t){case 0:{c.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let I=new URL(l,location.href);I.searchParams.append("bytes",`${i.from}-${i.to}`),l=I.toString();break}default:mT(t)}this.requestQuic&&(l=Wt(l));let p=this.abortAllController.signal,h;if(n){let I=new K;if(h=MC(bT(this.abortAllController.signal,"abort"),bT(n,"abort")).subscribe(()=>{try{I.abort()}catch(E){vo(E)}}),this.subscription.add(h),this.abortAllController.signal.aborted||n.aborted)try{I.abort()}catch(E){vo(E)}p=I.signal}let f=ss();d.log("startRequest",Er({url:l,priority:s,rangeMethod:t,range:i,isLowLatency:u,requestStartedAt:f}));let b=yield this.doFetch(l,{priority:s,headers:c,signal:p}),g=ss();if(!b)return d.error("error",{message:"No response in request"}),d.end(),this.unsubscribeAbortSubscription(h),null;if(this.throughputEstimator?.addRawRtt(g-f),!b.ok||!b.body){this.unsubscribeAbortSubscription(h);let I=`Fetch error ${b.status}: ${b.statusText}`;return d.error("error",{message:I}),d.end(),Promise.reject(new Error(`Fetch error ${b.status}: ${b.statusText}`))}if(this.onHeadersReceived(b.headers),!r&&!o){this.unsubscribeAbortSubscription(h);let I=ss(),E={requestStartedAt:f,requestEndedAt:I,duration:I-f};return d.log("endRequest",Er(E)),d.end(),b.arrayBuffer()}let S=b.body;if(o){let I;[S,I]=b.body.tee(),this.throughputEstimator?.trackStream(I,u)}let T=S.getReader(),v,x=parseInt(b.headers.get("content-length")??"",10);Number.isFinite(x)&&(v=x),!v&&i&&(v=i.to-i.from+1);let w=0,L=v?new Uint8Array(v):new Uint8Array(0),B=!1,A=I=>{this.unsubscribeAbortSubscription(h),B=!0,vo(I)},$=as(p,async function*({done:I,value:E}){if(w===0&&this.lastRequestFirstBytes$.next(ss()-f),p.aborted){this.unsubscribeAbortSubscription(h);return}if(!I&&E){if(v)L.set(E,w),w+=E.byteLength;else{let k=new Uint8Array(L.length+E.length);k.set(L),k.set(E,L.length),L=k,w+=E.byteLength}r?.(new DataView(L.buffer),w),yield T?.read().then($,A)}}.bind(this));yield T?.read().then($,A),this.unsubscribeAbortSubscription(h);let y=ss(),M={failed:B,requestStartedAt:f,requestEndedAt:y,duration:y-f};return B?(d.error("endRequest",Er(M)),d.end(),null):(d.log("endRequest",Er(M)),d.end(),L.buffer)}.bind(this));this.fetchByteRangeRepresentation=as(this.abortAllController.signal,async function*(e,t,i){if(e.type!=="byteRange")return null;let{from:r,to:s}=e.initRange,n=r,o=s,u=!1,l,c;e.indexRange&&(l=e.indexRange.from,c=e.indexRange.to,u=s+1===l,u&&(n=Math.min(l,r),o=Math.max(c,s))),n=Math.min(n,0);let d=yield this.fetch(e.url,{range:{from:n,to:o},priority:i,measureThroughput:!1});if(!d)return null;let p=new DataView(d,r-n,s-n+1);if(!t.validateData(p))throw new Error("Invalid media file");let h=t.parseInit(p),f=e.indexRange??t.getIndexRange(h);if(!f)throw new ReferenceError("No way to load representation index");let b;if(u)b=new DataView(d,f.from-n,f.to-f.from+1);else{let S=yield this.fetch(e.url,{range:f,priority:i,measureThroughput:!1});if(!S)return null;b=new DataView(S)}let g=t.parseSegments(b,h,f);return{init:h,dataView:new DataView(d),segments:g}}.bind(this));this.fetchTemplateRepresentation=as(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}=Gn(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 Ke(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:ns.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:ns.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:ns.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:ns.FATAL});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${s})`,category:ns.FATAL})}}unsubscribeAbortSubscription(e){e&&(e.unsubscribe(),this.subscription.remove(e))}},vo=a=>{if(!yt(a))throw a};import{isNullable as CC,ValueSubject as BC}from"@vkontakte/videoplayer-shared";var os=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(!CC(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,o=r.segments[s-1].time.to;if(e<n||e>o)continue;let u=r.segments.find(l=>l.time.from<=e&&l.time.to>=e);!u||this.currentSegment?.time.from===u.time.from&&this.currentSegment.time.to===u.time.to||(this.currentSegment=u,this.currentRepresentation$.next({...i,label:"Live Text",language:"ru",isAuto:!0,url:new URL(u.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&&qe(t.segmentReference))}};var NC=["progress","play","seeked","stalled","waiting"],UC=["timeupdate","progress","loadeddata","playing","seeked"];var Eo=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new td;this.representationSubscription=new td;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 Io;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 Io;this.fetcherError$=new Io;this.liveStreamEndTimestamp=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.forceEnded$=new Io;this.gapWatchdogActive=!1;this.destroyController=new K;this.initManifest=Jc(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=ae(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:nt.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=Jc(this.destroyController.signal,async function*(){this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(n=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:nt.NETWORK,message:"Failed to load manifest",thrown:n})});if(!e)return null;let t=null;try{t=qn(e??"",this.manifestUrlString)}catch(n){let o=Un(e)??{id:"ManifestParsing",category:nt.PARSER,message:"Failed to parse MPD manifest",thrown:n};this.error$.next(o)}if(!t)return null;let i=(n,o,u)=>!!(this.element?.canPlayType?.(o)&&Ne()?.isTypeSupported?.(`${o}; codecs="${u}"`)||n==="text");if(t.live){this.isLive$.next(!!t.live);let{availabilityStartTime:n,latestSegmentPublishTime:o,streamIsUnpublished:u,streamIsAlive:l}=t.live,c=(t.duration??0)/1e3;this.liveSeekableDuration$.next(-1*c),this.liveDuration$.next((o-n)/1e3),this.liveAvailabilityStartTime$.next(t.live.availabilityStartTime);let d="active";l||(d=u?"unpublished":"unexpectedly_down"),this.liveStreamStatus$.next(d)}let r={text:t.streams.text,video:[],audio:[]};for(let n of["video","audio"]){let u=t.streams[n].filter(({mime:d,codecs:p})=>i(n,d,p)),l=new Set(u.map(({codecs:d})=>d)),c=io(l);if(c&&(r[n]=u.filter(({codecs:d})=>d.startsWith(c))),n==="video"){let d=this.tuning.preferHDR,p=r.video.some(f=>f.hdr),h=r.video.some(f=>!f.hdr);_.display.isHDR&&d&&p?r.video=r.video.filter(f=>f.hdr):h&&(r.video=r.video.filter(f=>!f.hdr))}}let s={...t,streams:r};return this.tracer.log("updateManifestEnd",ls(s)),s}.bind(this));this.initRepresentations=Jc(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initRepresentationsStart",ls({initialVideo:e,initialAudio:t,sourceHls:i})),xr(this.manifest),xr(this.element),this.representationSubscription.unsubscribe(),this.representationSubscription=new td,this.state$.startTransitionTo("representations_ready");let r=p=>{this.representationSubscription.add(Tt(p,"error").pipe(To(h=>!!this.element?.played.length)).subscribe(h=>{this.error$.next({id:"VideoSource",category:nt.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:h})}))};this.source=this.tuning.useManagedMediaSource?gn():new MediaSource;let s=document.createElement("source");if(r(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),this.tuning.useManagedMediaSource&&tr())if(i){let p=document.createElement("source");r(p),p.type="application/x-mpegurl",p.src=i.url,this.element.appendChild(p)}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},o=this.manifest.streams.video.reduce((p,h)=>[...p,...h.representations],[]);if(this.videoBufferManager=new rs("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],cs(t)){let p=this.manifest.streams.audio.reduce((h,f)=>[...h,...f.representations],[]);this.audioBufferManager=new rs("audio",this.source,p,n),this.bufferManagers.push(this.audioBufferManager)}os.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new os(this.manifest.streams.text,n)),this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$));let u=()=>{this.stallWatchdogSubscription?.unsubscribe(),this.currentStallDuration$.next(0)};if(this.representationSubscription.add(wi(...UC.map(p=>Tt(this.element,p))).pipe(Ar(p=>this.element?de(this.element.buffered,this.element.currentTime*1e3):0),us(),FC(p=>{p>this.tuning.dash.bufferEmptinessTolerance&&u()})).subscribe(this.bufferLength$)),this.representationSubscription.add(wi(Tt(this.element,"ended"),this.forceEnded$).subscribe(()=>{u()})),this.isLive$.getValue()){this.subscription.add(this.liveDuration$.pipe(us()).subscribe(h=>this.liveStreamEndTimestamp=ed())),this.subscription.add(Tt(this.element,"pause").subscribe(()=>{this.livePauseWatchdogSubscription=Zc(1e3).subscribe(h=>{let f=Ut(this.manifestUrlString,2);this.manifestUrlString=ae(this.manifestUrlString,f+1e3,2),this.liveStreamStatus$.getValue()==="active"&&this.updateManifest()}),this.subscription.add(this.livePauseWatchdogSubscription)})).add(Tt(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),us()).subscribe(h=>{this.isManualDecreasePlaybackInLive()||gr(this.element,1)})),this.representationSubscription.add(wr({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(To(({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(wr({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe(To(({isLive:h})=>h),us((h,f)=>f.bufferLength<h.bufferLength),Ar(({rtt:h,bufferLength:f,segmentServerLatency:b})=>{let g=Ut(this.manifestUrlString,2);return(h/2+f+b+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:b})=>{if(!b||!f)return;let g=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,S=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,T=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,v=h-g;if(this.isManualDecreasePlaybackInLive())return;let x=1;Math.abs(v)>S&&(x=1+Math.sign(v)*T),gr(this.element,x)})),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(S=>S.getLiveSegmentsToLoadState(this.manifest)?.to??b))-b}this.liveLoadBufferLength$.getValue()!==f&&this.liveLoadBufferLength$.next(f)}));let p=0;this.representationSubscription.add(wr({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(yT(1e3)).subscribe(async({liveLoadBufferLength:h,bufferLength:f})=>{if(!this.element||this.isUpdatingLive)return;let b=this.element.playbackRate,g=Ut(this.manifestUrlString,2),S=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,T=Math.min(S,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*b),v=this.tuning.dashCmafLive.normalizedActualBufferOffset*b,x=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*b,w=isFinite(h)?h:f,L=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),B=S<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next(B);let A="none";if(L?A="active_low_latency":this.isLowLatency$.getValue()&&B?(this.bufferManagers.forEach($=>$.proceedLowLatencyLive()),A="active_low_latency"):g!==0&&w<T?A="live_forward_buffering":w<T+x&&(A="live_with_target_offset"),isFinite(h)&&(p=h>p?h:p),A==="live_forward_buffering"||A==="live_with_target_offset"){let $=p-(T+v),y=this.normolizeLiveOffset(Math.trunc(g+$/b)),M=Math.abs(y-g),I=0;!h||M<=this.tuning.dashCmafLive.offsetCalculationError?I=g:y>0&&M>this.tuning.dashCmafLive.offsetCalculationError&&(I=y),this.manifestUrlString=ae(this.manifestUrlString,I,2)}(A==="live_with_target_offset"||A==="live_forward_buffering")&&(p=0,await this.updateLive())},h=>{this.error$.next({id:"updateLive",category:nt.VIDEO_PIPELINE,thrown:h,message:"Failed to update live with subscription"})}))}let l=wi(...this.bufferManagers.map(p=>p.fullyBuffered$)).pipe(Ar(()=>this.bufferManagers.every(p=>p.fullyBuffered$.getValue()))),c=wi(...this.bufferManagers.map(p=>p.onLastSegment$)).pipe(Ar(()=>this.bufferManagers.some(p=>p.onLastSegment$.getValue()))),d=wr({allBuffersFull:l,someBufferEnded:c}).pipe(us(),Ar(({allBuffersFull:p,someBufferEnded:h})=>p&&h),To(p=>p));if(this.representationSubscription.add(wi(this.forceEnded$,d).subscribe(()=>{if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(p=>!p.updating))try{this.source?.endOfStream()}catch(p){this.error$.next({id:"EndOfStream",category:nt.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:p})}})),this.representationSubscription.add(wi(...this.bufferManagers.map(p=>p.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 p=this.tuning.dash.sourceOpenTimeout>=0;yield new Promise(h=>{p&&(this.timeoutSourceOpenId=setTimeout(()=>{if(this.source?.readyState==="open"){h();return}this.error$.next({id:"OpenOfStream",category:nt.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 p=[this.manifest.duration??0,...(0,id.default)((0,id.default)([...this.manifest.streams.audio,...this.manifest.streams.video],h=>h.representations),h=>{let f=[];return h.duration&&f.push(h.duration),qe(h.segmentReference)&&h.segmentReference.totalSegmentsDurationMs&&f.push(h.segmentReference.totalSegmentsDurationMs),f})];this.source.duration=Math.max(...p)/1e3}this.audioBufferManager&&cs(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=Zc(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),t=>{this.error$.next({id:"GapWatchdog",category:nt.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.fetcher=new yo({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=$t.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.bufferEstimator}),this.initTracerSubscription()}async seekLive(e){xr(this.element);let t=this.liveStreamStatus$.getValue()!=="active"?ed()-this.liveStreamEndTimestamp:0,i=this.normolizeLiveOffset(e+t);this.isActiveLive$.next(i===0),this.manifestUrlString=ae(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");let e=Tt(this.element,"timeupdate");this.tuning.dash.timeupdateEventTickThrottle&&(e=e.pipe(yT(this.tuning.dash.timeupdateEventTickThrottle))),this.subscription.add(wi(...NC.map(t=>Tt(this.element,t)),Tt(window,"online"),e).subscribe(()=>this.tick(),t=>{this.error$.next({id:"DashVKPlayer",category:nt.WTF,message:"Internal logic error",thrown:t})})),this.subscription.add(Tt(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(Tt(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=ed(),n=100,o=this.videoBufferManager?.lastDataObtainedTimestamp??0;this.videoLastDataObtainedTimestamp$.next(o);let u=this.audioBufferManager?.lastDataObtainedTimestamp??0,l=this.videoBufferManager?.getForwardBufferDuration()??0,c=this.audioBufferManager?.getForwardBufferDuration()??0,d=l<n&&s-o>this.tuning.dash.crashOnStallTWithoutDataTimeout,p=this.audioBufferManager&&c<n&&s-u>this.tuning.dash.crashOnStallTWithoutDataTimeout;if((d||p)&&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:nt.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",ls(r))};this.stallWatchdogSubscription?.unsubscribe(),this.stallWatchdogSubscription=Zc(50).subscribe(t,i=>{this.error$.next({id:"StallWatchdogCallback",category:nt.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){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),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",ls({requestedPosition:e,forcePrecise:t,position:i})))}warmUpMediaSourceIfNeeded(e=this.element?.currentTime){cs(this.element)&&cs(this.source)&&cs(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}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=OC(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,o=this.element.readyState===HTMLMediaElement.HAVE_METADATA?this.tuning.endGapTolerance:0;for(let u of this.bufferManagers)for(let l of u.gaps)(l.persistent||u.playingRepresentation$.getValue()===l.representation)&&l.from-o<=s&&l.to+o>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 u=n+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,u===1/0?this.forceEnded$.next():(this.element.currentTime=u/1e3,this.tracer.log("jumpGap",ls({isJumpGapAfterSeekLive:i,isActiveLowLatency:t,initialCurrentTime:r,jumpTo:u,resultCurrentTime:this.element.currentTime})))}}calculateDurationFromSegments(){return Math.max(this.videoBufferManager?.calculateDurationFromSegments()||0,this.audioBufferManager?.calculateDurationFromSegments()||0)}};import{combine as qC,map as jC,observeElementSize as HC,Subscription as QC,ValueSubject as rd,noop as GC}from"@vkontakte/videoplayer-shared";var xo=class{constructor(){this.subscription=new QC;this.pipSize$=new rd(void 0);this.videoSize$=new rd(void 0);this.elementSize$=new rd(void 0);this.pictureInPictureWindowRemoveEventListener=GC}connect({observableVideo:e,video:t}){let i=r=>{let s=r.target;this.pipSize$.next({width:s.width,height:s.height})};this.subscription.add(HC(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(qC({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe(jC(({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 ZC;this.videoState=new F("stopped");this.observableVideo=null;this.droppedFramesManager=new or;this.stallsManager=new lo;this.elementSizeManager=new xo;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new Ht;this.audioTrackSwitchHistory=new Ht;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 zC(e)}}};this.init3DScene=e=>{if(this.scene3D)return;this.scene3D=new Tr(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 ze(e.source.url),this.params=e,this.video=Pe(e.container,e.tuning),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(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 Eo({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode,tracer:this.tracer}),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params;JC(this.observableVideo)&&(this.observableVideo=$e(this.video),this.subscription.add(()=>this.observableVideo?.destroy()));let i=this.constructor.name,r=n=>{e.error$.next({id:i,category:TT.WTF,message:`${i} internal logic error`,thrown:n})},s=(n,o)=>this.subscription.add(n.subscribe(o,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(ad(d=>!!d.length),ET()).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(sd(d=>d.to.state!=="none"),wo());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(ad(IT),ET()),e.firstBytesEvent$),s(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),s(this.videoState.stateChangeEnded$.pipe(sd(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(ht(this.video,t.isLooped,r)),this.subscription.add(Le(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(We(this.video,t.playbackRate,i.playbackRateState$,r)),this.elementSizeManager.connect({video:this.video,observableVideo:i}),s(Ye(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.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 p=this.player.getStreams();if(YC(p,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let f=[];for(let b of p.audio){f.push(Qc(b));let g=[];for(let S of b.representations){let T=lT(S);g.push(T),this.audioTracksMap.set(T,{stream:b,representation:S})}this.audioStreamsMap.set(b,g)}this.params.output.availableAudioStreams$.next(f)}let h=[];for(let f of p.video){h.push(Gc(f));let b=[];for(let g of f.representations){let S=uT({...g,streamId:f.id});S&&(b.push(S),this.videoTracksMap.set(S,{stream:f,representation:g}))}this.videoStreamsMap.set(f,b)}this.params.output.availableVideoStreams$.next(h);for(let f of p.text)for(let b of f.representations){let g=cT(f,b);this.textTracksMap.set(g,{stream:f,representation:b})}this.params.output.availableVideoTracks$.next(Array.from(this.videoTracksMap.keys())),this.params.output.availableAudioTracks$.next(Array.from(this.audioTracksMap.keys())),this.params.output.isAudioAvailable$.next(!!this.audioTracksMap.size),this.audioTracksMap.size&&this.textTracksMap.size&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else d==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},r));let{vktvAbrThrottle:o}=this.params.tuning.dash,u=o&&hT(o)||null;this.subscription.add(Ao(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$,XC(this.video,"progress")).pipe(ad(()=>this.videoTracksMap.size>0)).subscribe(async()=>{let d=this.player.state$.getState(),p=this.player.state$.getTransition();if(d!=="manifest_ready"&&d!=="running"||p||d==="running"&&u&&!u())return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState()),this.selectVideoAudioRepresentations();let{video:h,audio:f}=this.selectedRepresentations;if(!h)return;let b=Ti(this.videoTracksMap.keys(),S=>this.videoTracksMap.get(S)?.representation.id===h.id);IT(b)&&(this.stallsManager.lastVideoTrackSelected=b);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(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(wo()).subscribe(d=>{let p=Ti(this.videoTracksMap.entries(),([,{representation:S}])=>S.id===d);if(!p){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[h,{stream:f}]=p,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(Gc(f));let g=this.player.calculateDurationFromSegments();g&&this.params.output.duration$.next(g/1e3)},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(wo()).subscribe(d=>{let p=Ti(this.audioTracksMap.entries(),([,{representation:g}])=>g.id===d);if(!p){e.currentAudioStream$.next(void 0);return}let[h,{stream:f}]=p,b=this.params.desiredState.audioStream.getTransition();b&&b.to&&b.to.id===f.id&&this.params.desiredState.audioStream.setState(b.to),e.currentAudioStream$.next(Qc(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(p){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${p}`})}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(sd(({to:d})=>d==="ready"),wo());this.subscription.add(Ao(l,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,nd(["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(Ao(l,this.player.state$.stateChangeEnded$,nd(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let c=Ao(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,nd(["init"])).pipe(KC(0));this.subscription.add(c.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?ua:oa,t=this.params.tuning.useNewAutoSelectVideoTrack?Cn:Dn,i=this.params.tuning.useNewAutoSelectVideoTrack?gt:Mn,{desiredState:r,output:s}=this.params,n=r.autoVideoTrackSwitching.getState(),o=r.videoTrack.getState()?.id,u=Ti(this.videoTracksMap.keys(),A=>A.id===o),l=s.currentVideoTrack$.getValue(),c=r.videoStream.getState()??(u&&this.videoTracksMap.get(u)?.stream)??this.videoStreamsMap.size===1?this.videoStreamsMap.keys().next().value:void 0;if(!c)return;let d=Ti(this.videoStreamsMap.keys(),A=>A.id===c.id),p=d&&this.videoStreamsMap.get(d);if(!p)return;let h=de(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,g=Math.min(h/Math.min(f,b||1/0),1),S=r.audioStream.getState()??(this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0),T=S?.id&&Ti(this.audioStreamsMap.keys(),A=>A.id===S.id)||this.audioStreamsMap.keys().next().value,v=0;if(T){if(u&&!n){let A=e(u,p,this.audioStreamsMap.get(T)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);v=Math.max(v,A?.bitrate??-1/0)}if(l){let A=e(l,p,this.audioStreamsMap.get(T)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);v=Math.max(v,A?.bitrate??-1/0)}}let x=u;(n||!x)&&(x=i(p,{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:v,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 w=T&&t(x,p,this.audioStreamsMap.get(T)??[],{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}),L=this.videoTracksMap.get(x)?.representation,B=w&&this.audioTracksMap.get(w)?.representation;L&&B?(this.selectedRepresentations.video=L,this.selectedRepresentations.audio=B):L&&!B&&this.audioTracksMap.size===0&&(this.selectedRepresentations.video=L,this.selectedRepresentations.audio=null)}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){Me(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:TT.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),Re(this.video),this.tracer.end()}};var ds=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 od,merge as xT,filter as wT,filterChanged as eB,isNullable as ud,map as AT,ValueSubject as ld,isNonNullable as tB}from"@vkontakte/videoplayer-shared";var ps=class extends Ai{constructor(e){super(e),this.textTracksManager.destroy()}subscribe(){super.subscribe();let e=-1,{output:t,observableVideo:i,desiredState:r,connect:s}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),s(i.timeUpdate$,t.liveBufferTime$),s(this.player.liveSeekableDuration$,t.duration$),s(this.player.liveLatency$,t.liveLatency$);let n=new ld(1);s(i.playbackRateState$,n),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(r.isLowLatency.stateChangeEnded$.pipe(AT(o=>o.to)).subscribe(this.player.isLowLatency$)).add(od({liveBufferTime:t.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(AT(({liveBufferTime:o,liveAvailabilityStartTime:u})=>o&&u?o+u:void 0)).subscribe(t.liveTime$)).add(this.player.liveStreamStatus$.pipe(wT(o=>tB(o))).subscribe(o=>t.isLiveEnded$.next(o!=="active"&&t.position$.getValue()===0))).add(od({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:xT(i.playbackRateState$,new ld(1))}).pipe(wT(({liveStreamStatus:o,liveDuration:u})=>o==="active"&&!!u)).subscribe(({liveDuration:o,playbackRate:u})=>{let l=t.liveBufferTime$.getValue(),c=t.position$.getValue(),{playbackCatchupSpeedup:d}=this.params.tuning.dashCmafLive.lowLatency;c||u<1-d||this.video.paused||ud(l)||(e=o-l)})).add(od({time:t.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:xT(i.playbackRateState$,new ld(1))}).pipe(eB((o,u)=>this.player.liveStreamStatus$.getValue()==="active"?o.liveDuration===u.liveDuration:o.time===u.time)).subscribe(({time:o,liveDuration:u,playbackRate:l})=>{let c=t.position$.getValue(),{playbackCatchupSpeedup:d}=this.params.tuning.dashCmafLive.lowLatency;if(!c&&!this.video.paused&&l>=1-d||ud(o)||ud(u))return;let p=-1*(u-o-e);t.position$.next(Math.min(p,0))})).add(this.player.currentLiveTextRepresentation$.subscribe(o=>{if(o){let u=dT(o);this.params.output.availableTextTracks$.next([u])}}))}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 kT="X-Playback-Duration",cd=async a=>{let e=await Ke(a),t=await e.text(),i=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t)?.[1];return i?parseInt(i,10):e.headers.has(kT)?parseInt(e.headers.get(kT),10):void 0};import{assertNever as pB,combine as hB,debounce as fB,ErrorCategory as Ro,filter as mB,filterChanged as bB,isNonNullable as LT,isNullable as Lo,map as $T,merge as gB,observableFrom as SB,Subscription as vB,ValueSubject as hd,VideoQuality as yB}from"@vkontakte/videoplayer-shared";var pd=V(Yu(),1);import{videoSizeToQuality as iB,getExponentialDelay as rB}from"@vkontakte/videoplayer-shared";var aB=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=iB({width:t,height:i})}return e??null},sB=(a,e)=>{let t=a.split(`
179
+ `),i=[],r=[];for(let s=0;s<t.length;s++){let n=t[s],o=n.match(/^#EXT-X-STREAM-INF:(.+)/),u=n.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!o&&!u)){if(o){let l=(0,pd.default)(o[1].split(",").map(g=>g.split("="))),c=l.QUALITY??`stream-${l.BANDWIDTH}`,d=aB(l),p;l.BANDWIDTH&&(p=parseInt(l.BANDWIDTH,10)/1e3||void 0),!p&&l["AVERAGE-BANDWIDTH"]&&(p=parseInt(l["AVERAGE-BANDWIDTH"],10)/1e3||void 0);let h=l["FRAME-RATE"]?parseFloat(l["FRAME-RATE"]):void 0,f;if(l.RESOLUTION){let[g,S]=l.RESOLUTION.split("x").map(T=>parseInt(T,10));g&&S&&(f={width:g,height:S})}let b=new URL(t[++s],e).toString();d&&i.push({id:c,quality:d,url:b,bandwidth:p,size:f,fps:h})}if(u){let l=(0,pd.default)(u[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"),d=l.LANGUAGE,p=l.NAME;c&&d&&r.push({type:"internal",id:d,label:p,language:d,url:c,isAuto:!1})}}}if(!i.length)throw new Error("Empty manifest");return{qualityManifests:i,textTracks:r}},nB=a=>new Promise(e=>{setTimeout(()=>{e()},a)}),dd=0,PT=async(a,e=a,t,i)=>{let s=await(await Ke(a,i)).text();dd+=1;try{let{qualityManifests:n,textTracks:o}=sB(s,e);return{qualityManifests:n,textTracks:o}}catch{if(dd<=t.manifestRetryMaxCount)return await nB(rB(dd-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),PT(a,e,t)}return{qualityManifests:[],textTracks:[]}},ko=PT;import{isNonNullable as oB,Subscription as uB,throttle as lB,ValueSubject as RT,Subject as cB,ErrorCategory as dB}from"@vkontakte/videoplayer-shared";var Po=class{constructor(e,t,i,r,s){this.subscription=new uB;this.abortControllers={destroy:new K,nextManifest:null};this.prepareUrl=void 0;this.currentTextTrackData=null;this.availableTextTracks$=new RT(null);this.getCurrentTime$=new RT(null);this.error$=new cB;this.params={fetchManifestData:i,sourceUrl:r,downloadThreshold:s},this.subscription.add(e.pipe(lB(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 Ke(r,{signal:this.abortControllers.destroy.signal})).text(),o=this.parsePlaylist(n,r);return{textTrack:i,playlist:o}}}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 o=r[n];switch(!0){case o.startsWith("#EXTINF:"):{let u=r[++n],l=new URL(u,t).toString(),c=Number(this.extractPlaylistRowValue("#EXTINF:",o))*1e3;if(i.segments.push({time:{from:s,to:s+c},url:l}),s=s+c,!i.segmentStartTime){let d=new Date(i.vkStartTime).valueOf(),p=new Date(i.programDateTime).valueOf();i.segmentStartTime=p-d}break}case o.startsWith("#EXT-X-TARGETDURATION:"):i.targetDuration=Number(this.extractPlaylistRowValue("#EXT-X-TARGETDURATION:",o));break;case o.startsWith("#EXT-X-MEDIA-SEQUENCE:"):i.mediaSequence=Number(this.extractPlaylistRowValue("#EXT-X-MEDIA-SEQUENCE:",o));break;case o.startsWith("#EXT-X-VK-PLAYBACK-DURATION:"):i.vkPlaybackDuration=Number(this.extractPlaylistRowValue("#EXT-X-VK-PLAYBACK-DURATION:",o));break;case o.startsWith("#EXT-X-PROGRAM-DATE-TIME:"):{let u=this.extractPlaylistRowValue("#EXT-X-PROGRAM-DATE-TIME:",o);i.programDateTime=u;let l=new Date(u);l.setMilliseconds(0),s=l.valueOf();break}case o.startsWith("#EXT-X-VK-START-TIME:"):i.vkStartTime=this.extractPlaylistRowValue("#EXT-X-VK-START-TIME:",o);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(oB(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 K;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:dB.WTF,thrown:t,message:e})}};var hs=class{constructor(e){this.subscription=new vB;this.videoState=new F("stopped");this.textTracksManager=null;this.liveTextManager=null;this.manifests$=new hd([]);this.liveOffset=new hi;this.manifestStartTime$=new hd(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(),o=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||o){let c=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(c),this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if(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 pB(t)}};this.params=e,this.video=Pe(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:yB.INVARIANT,url:this.params.source.url};let t=(i,r)=>ko(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 Po(this.params.output.liveTime$,this.video,t,this.params.source.url,this.params.tuning.hlsLiveNewTextManagerDownloadThreshold):this.textTracksManager=new ze(e.source.url),t(this.generateLiveUrl()).then(({qualityManifests:i,textTracks:r})=>{i.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:Ro.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:Ro.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 hd(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 o=i?"master":s;return i&&!r&&t.startTransitionTo(this.masterManifest),n.find(u=>u.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsLiveProvider",category:Ro.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},r=$e(this.video);this.subscription.add(()=>r.destroy());let s=(o,u)=>this.subscription.add(o.subscribe(u,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(Le(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(We(this.video,t.playbackRate,r.playbackRateState$,i)),s(Ye(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(o=>{o&&this.params.output.availableTextTracks$.next(o)})),this.subscription.add(this.maxSeekBackTime$.pipe(bB(),$T(o=>-o/1e3)).subscribe(this.params.output.duration$,i)),this.subscription.add(r.loadedMetadata$.subscribe(()=>{let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&LT(l.to)){let d=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let p=this.manifests$.getValue().find(h=>h.id===d);p&&(this.params.output.currentVideoTrack$.next(p),this.params.output.hostname$.next(ge(p.url)))}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o&&o.state==="requested"&&this.seek(o.position)},i)),this.subscription.add(r.loadedData$.subscribe(()=>{let o=this.video?.getStartDate?.()?.getTime();this.manifestStartTime$.next(o||void 0)},i)),this.subscription.add(hB({startTime:this.manifestStartTime$.pipe(mB(LT)),currentTime:r.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),i)),this.subscription.add(this.manifests$.pipe($T(o=>o.map(({id:u,quality:l,size:c,bandwidth:d,fps:p})=>({id:u,quality:l,size:c,fps:p,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,i));let n=gB(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,SB(["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),Re(this.video)}prepare(){let e=this.selectManifest();if(Lo(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:o,min:u}=t?.to??i??{};for(let[l,c]of[[o,"mq"],[u,"lq"]]){let d=String(parseFloat(l||""));c&&l&&r.searchParams.set(c,d)}}let s=this.params.format==="HLS_LIVE_CMAF"?2:0,n=ae(r.toString(),this.liveOffset.getTotalOffset(),s);this.liveTextManager?.prepare(n),this.video.setAttribute("src",n),this.video.load(),cd(n).then(o=>{if(!Lo(o))this.maxSeekBackTime$.next(o);else{let u=this.params.source.maxSeekBackTime??this.maxSeekBackTime$.getValue();(Lo(u)||!isFinite(u))&&Ke(n).then(l=>l.text()).then(l=>{let c=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(l)?.[1];if(c){let d=new URL(c,n).toString();cd(d).then(p=>{Lo(p)||this.maxSeekBackTime$.next(p)})}}).catch(()=>{})}})}playIfAllowed(){Me(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:Ro.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=ae(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 TB,debounce as IB,ErrorCategory as fd,fromEvent as md,isNonNullable as EB,isNullable as xB,map as MT,merge as DT,observableFrom as CT,Subscription as wB,ValueSubject as AB,VideoQuality as kB}from"@vkontakte/videoplayer-shared";var fs=class{constructor(e){this.subscription=new wB;this.videoState=new F("stopped");this.manifests$=new AB([]);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(),o=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||o){let c=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(c);let{currentTime:d}=this.video;this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:d*1e3,forcePrecise:!0});return}switch(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 TB(t)}};this.textTracksManager=new ze(e.source.url),this.params=e,this.video=Pe(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:kB.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),ko(ae(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.manifests$.next([this.masterManifest,...t]),this.params.tuning.useNativeHLSTextTracks||this.params.desiredState.internalTextTracks.startTransitionTo(i)},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:fd.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 o=i?"master":s;return i&&(!r||!r.from)&&t.startTransitionTo(this.masterManifest),n.find(u=>u.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsProvider",category:fd.WTF,message:"HlsProvider internal logic error",thrown:o})},r=$e(this.video);this.subscription.add(()=>r.destroy());let s=(o,u)=>this.subscription.add(o.subscribe(u));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(MT(o=>o.to)),this.params.output.playbackState$),this.subscription.add(ht(this.video,t.isLooped,i)),this.subscription.add(Le(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(We(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 o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&EB(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 d=this.params.desiredState.playbackRate.getState(),p=this.params.output.element$.getValue()?.playbackRate;if(d!==p){let h=this.params.output.element$.getValue();h&&(this.params.desiredState.playbackRate.setState(d),h.playbackRate=d)}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o.state==="requested"&&this.seek(o.position)},i))),this.subscription.add(this.manifests$.pipe(MT(o=>o.map(({id:u,quality:l,size:c,bandwidth:d,fps:p})=>({id:u,quality:l,size:c,fps:p,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,i)),!_.device.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add(DT(md(o,"addtrack"),md(o,"removetrack"),md(o,"change"),CT(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},i))}let n=DT(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,CT(["init"])).pipe(IB(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),Re(this.video)}prepare(){let e=this.selectManifest();if(xB(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[o,u]of[[s,"mq"],[n,"lq"]]){let l=String(parseFloat(o||""));u&&o&&r.searchParams.set(u,l)}}this.video.setAttribute("src",r.toString()),this.video.load()}playIfAllowed(){Me(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:fd.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};var _T=V(qi(),1),bd=V(Zi(),1),OT=V(bt(),1);import{assertNever as PB,assertNonNullable as BT,debounce as RB,ErrorCategory as VT,isHigherOrEqual as LB,isLowerOrEqual as $B,isNonNullable as MB,merge as DB,observableFrom as CB,Subscription as BB,map as VB}from"@vkontakte/videoplayer-shared";var ms=class{constructor(e){this.subscription=new BB;this.videoState=new F("stopped");this.trackUrls={};this.textTracksManager=new ze;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(),o=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:u}=this.video;this.prepare(),o.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:u*1e3,forcePrecise:!0});return}switch(i?.to!=="paused"&&o.state==="requested"&&this.seek(o.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 PB(e)}};this.params=e,this.video=Pe(e.container,e.tuning),this.params.output.element$.next(this.video),(0,_T.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,bd.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=o=>{e.error$.next({id:"MpegProvider",category:VT.WTF,message:"MpegProvider internal logic error",thrown:o})},r=$e(this.video);this.subscription.add(()=>r.destroy());let s=(o,u)=>this.subscription.add(o.subscribe(u,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(VB(o=>o.to)),this.params.output.playbackState$),this.subscription.add(ht(this.video,t.isLooped,i)),this.subscription.add(Le(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(We(this.video,t.playbackRate,r.playbackRateState$,i)),s(Ye(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 o=this.params.desiredState.videoTrack.getTransition();if(o&&MB(o.to)){this.params.desiredState.videoTrack.setState(o.to),this.params.output.currentVideoTrack$.next(this.trackUrls[o.to.id].track);let u=this.params.desiredState.playbackRate.getState(),l=this.params.output.element$.getValue()?.playbackRate;if(u!==l){let c=this.params.output.element$.getValue();c&&(this.params.desiredState.playbackRate.setState(u),c.playbackRate=u)}}this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.textTracksManager.connect(this.video,t,e);let n=DB(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,CB(["init"])).pipe(RB(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),Re(this.video)}prepare(){let e=this.params.desiredState.videoTrack.getState()?.id;BT(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];BT(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=Wt(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(ge(t))}playIfAllowed(){Me(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:VT.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=gt(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,bd.default)(this.trackUrls).map(l=>l.track);if(!r||!s||ir(e,n[0].quality,(0,OT.default)(n,-1)?.quality)){i();return}let o=e.max?$B(r,e.max):!0,u=e.min?LB(r,e.min):!0;o&&u||i(e)}};import{assertNever as NT,debounce as NB,merge as UT,observableFrom as UB,Subscription as qB,map as qT,ValueSubject as jB,ErrorCategory as Sd,VideoQuality as HB}from"@vkontakte/videoplayer-shared";import{ErrorCategory as _B}from"@vkontakte/videoplayer-shared";var FT=["stun:videostun.mycdn.me:80"],OB=1e3,FB=3,gd=()=>null,$o=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=gd;this.externalStopCallback=gd;this.externalErrorCallback=gd;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:FT}]};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:_B.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),OB)}normalizeOptions(e={}){let t={stunServerList:FT,maxRetryNumber:FB,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var bs=class{constructor(e){this.videoState=new F("stopped");this.maxSeekBackTime$=new jB(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 NT(e)}};this.subscription=new qB,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=Pe(e.container,e.tuning),this.liveStreamClient=new $o(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),Re(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,i=n=>{e.error$.next({id:"WebRTCLiveProvider",category:Sd.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};this.subscription.add(UT(this.videoState.stateChangeStarted$.pipe(qT(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe(qT(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})}));let r=$e(this.video);this.subscription.add(()=>r.destroy());let s=(n,o)=>this.subscription.add(n.subscribe(o,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(Ye(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(Le(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 NT(n.to)}},i)).add(UT(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,UB(["init"])).pipe(NB(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:HB.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:Sd.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){Me(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:Sd.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var gs=class{constructor(e){this.iterator=e[Symbol.iterator](),this.next()}next(){this.current=this.iterator.next()}getValue(){if(this.current.done)throw new Error("Iterable is completed");return this.current.value}isCompleted(){return!!this.current.done}};import{assertNever as Ss,assertNonNullable as Kt,ErrorCategory as Mo,filter as zT,isNonNullable as YT,isNullable as XB,map as JB,merge as ZB,once as e0,Subject as pe,Subscription as KT,ValueSubject as U,flattenObject as vd}from"@vkontakte/videoplayer-shared";import{Observable as QB,map as jT,Subscription as GB,Subject as WB}from"@vkontakte/videoplayer-shared";var HT=a=>new QB(e=>{let t=new GB,i=a.desiredPlaybackState$.stateChangeStarted$.pipe(jT(({from:l,to:c})=>`${l}-${c}`)),r=a.desiredPlaybackState$.stateChangeEnded$,s=a.providerChanged$.pipe(jT(({type:l})=>l!==void 0)),n=new WB,o=0,u="unknown";return t.add(i.subscribe(l=>{o&&window.clearTimeout(o),u=l,o=window.setTimeout(()=>n.next(l),a.maxTransitionInterval)})),t.add(r.subscribe(()=>{window.clearTimeout(o),u="unknown",o=0})),t.add(s.subscribe(l=>{o&&(window.clearTimeout(o),o=0,l&&(o=window.setTimeout(()=>n.next(u),a.maxTransitionInterval)))})),t.add(n.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});import{ErrorCategory as zB,Subscription as YB,combine as KB,filter as GT,once as WT}from"@vkontakte/videoplayer-shared";function QT(){return new(window.AudioContext||window.webkitAudioContext)}var kr=class a{constructor(e,t,i,r){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=i;this.volumeMultiplier=r;this.destroyController=new K;this.subscriptions=new YB;this.audioContext=null;this.gainNode=null;this.mediaElementSource=null;this.subscriptions.add(this.provider$.pipe(GT(s=>!!s.type),WT()).subscribe(({type:s})=>this.subscribe(s)))}static{this.errorId="VolumeMultiplierManager"}subscribe(e){_.browser.isSafari&&e!=="MPEG"||this.subscriptions.add(KB({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe(GT(({playbackState:t,video:i,volume:{muted:r,volume:s}})=>t==="playing"&&!!i&&!r&&!!s),WT()).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=QT();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:zB.VIDEO_PIPELINE,message:e?.message??`${a.errorId} exception`,thrown:e})}};var t0={chunkDuration:5e3,maxParallelRequests:5},vs=class{constructor(e){this.current$=new U({type:void 0});this.providerError$=new pe;this.noAvailableProvidersError$=new pe;this.volumeMultiplierError$=new pe;this.providerOutput={position$:new U(0),duration$:new U(1/0),volume$:new U({muted:!1,volume:1}),availableVideoStreams$:new U([]),currentVideoStream$:new U(void 0),availableVideoTracks$:new U([]),currentVideoTrack$:new U(void 0),availableAudioStreams$:new U([]),currentAudioStream$:new U(void 0),availableAudioTracks$:new U([]),currentVideoSegmentLength$:new U(0),currentAudioSegmentLength$:new U(0),isAudioAvailable$:new U(!0),autoVideoTrackLimitingAvailable$:new U(!1),autoVideoTrackLimits$:new U(void 0),currentBuffer$:new U(void 0),isBuffering$:new U(!0),error$:new pe,fetcherError$:new pe,fetcherRecoverableError$:new pe,warning$:new pe,willSeekEvent$:new pe,soundProhibitedEvent$:new pe,seekedEvent$:new pe,loopedEvent$:new pe,endedEvent$:new pe,firstBytesEvent$:new pe,loadedMetadataEvent$:new pe,firstFrameEvent$:new pe,canplay$:new pe,isLive$:new U(void 0),isLiveEnded$:new U(null),isLowLatency$:new U(!1),canChangePlaybackSpeed$:new U(!0),liveTime$:new U(void 0),liveBufferTime$:new U(void 0),liveLatency$:new U(void 0),severeStallOccurred$:new pe,availableTextTracks$:new U([]),currentTextTrack$:new U(void 0),hostname$:new U(void 0),httpConnectionType$:new U(void 0),httpConnectionReused$:new U(void 0),inPiP$:new U(!1),inFullscreen$:new U(!1),element$:new U(void 0),elementVisible$:new U(!0),availableSources$:new U(void 0),is3DVideo$:new U(!1),playbackState$:new U(""),getCurrentTime$:new U(null)};this.subscription=new KT;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=Uy([...jy(this.params.tuning),...qy(this.params.tuning)],this.params.tuning).filter(l=>YT(e.sources[l])),{forceFormat:i,formatsToAvoid:r}=this.params.tuning,s=[];i?s=[i]:r.length?s=[...t.filter(l=>!(0,yd.default)(r,l)),...t.filter(l=>(0,yd.default)(r,l))]:s=t,this.log({message:`Selected formats: ${s.join(" > ")}`}),this.tracer.log("Selected formats",vd(s)),this.screenFormatsIterator=new gs(s);let n=[...Ac(!0),...Ac(!1)];this.chromecastFormatsIterator=new gs(n.filter(l=>YT(e.sources[l]))),this.providerOutput.availableSources$.next(e.sources);let{volumeMultiplier:o=1,tuning:{useVolumeMultiplier:u}}=this.params;u&&o!==1&&kr.isSupported()&&(this.volumeMultiplierManager=new kr(this.providerOutput,this.current$,this.volumeMultiplierError$,o))}init(){this.subscription.add(this.initProviderErrorHandling()),this.subscription.add(this.params.dependencies.chromecastInitializer.connection$.subscribe(()=>{this.reinitProvider()}))}destroy(){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(XB(t)){this.handleNoFormatsError(e);return}let i;try{i=this.createProvider(e,t)}catch(r){this.providerError$.next({id:"ProviderNotConstructed",category:Mo.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()}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 Ss(e)}}createScreenProvider(e){let{sources:t,container:i,desiredState:r,panelSize:s}=this.params,n=this.providerOutput,o={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 u=this.applyFailoverHost(t[e]),l=this.applyFailoverHost(t.HLS_ONDEMAND||t.HLS);return Kt(u),this.params.tuning.useNewDashProvider?new ds({...o,source:u,sourceHls:l}):new ts({...o,source:u,sourceHls:l})}case"DASH_LIVE_CMAF":{let u=this.applyFailoverHost(t[e]);return Kt(u),this.params.tuning.useNewDashProvider?new ps({...o,source:u}):new is({...o,source:u})}case"HLS":case"HLS_ONDEMAND":{let u=this.applyFailoverHost(t[e]);return Kt(u),new fs({...o,source:u})}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let u=this.applyFailoverHost(t[e]);return Kt(u),new hs({...o,source:u,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case"MPEG":{let u=this.applyFailoverHost(t[e]);return Kt(u),new ms({...o,source:u})}case"DASH_LIVE":{let u=this.applyFailoverHost(t[e]);return Kt(u),new FS({...o,source:u,config:{...t0,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case"WEB_RTC_LIVE":{let u=this.applyFailoverHost(t[e]);return Kt(u),new bs({container:i,source:u,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 Ss(e)}}createChromecastProvider(e){let{sources:t,container:i,desiredState:r,meta:s}=this.params,n=this.providerOutput,o=this.params.dependencies.chromecastInitializer.connection$.getValue();return Kt(o),new ta({connection:o,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 Ss(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return Ss(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 Ss(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,JT.default)((0,XT.default)(e).map(([r,s])=>[r,i(s)]))}initProviderErrorHandling(){let e=new KT,t=!1,i=0;return e.add(ZB(this.providerOutput.error$.pipe(zT(r=>!this.params.tuning.ignoreAudioRendererError||!r.message||!/AUDIO_RENDERER_ERROR/ig.test(r.message))),HT({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(JB(r=>({id:`ProviderHangup:${r}`,category:Mo.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(zT(({to:s})=>s==="playing"),e0()).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 o=r.category===Mo.NETWORK,u=r.category===Mo.FATAL,l=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),c=i<this.params.tuning.providerErrorLimit&&!u,d=l&&!u&&(o&&t||!c);n={...n,isNetworkError:o,isFatalError:u,haveFailoverHost:l,tryFailover:d,canReinitProvider:c},c?(i++,this.reinitProvider()):d?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):(i=0,this.switchToNextProvider(s??"SCREEN"))}r.traceAsLog?this.tracer.log("providerInfo",vd(n)):this.tracer.error("providerError",vd(n))})),e}};import{fromEvent as Do,once as i0,combine as r0,Subscription as ZT,ValueSubject as Td,map as a0,filter as s0,isNonNullable as Co,now as je,safeStorage as Id}from"@vkontakte/videoplayer-shared";var n0=5e3,eI="one_video_throughput",tI="one_video_rtt",ys=window.navigator.connection,iI=()=>{let a=ys?.downlink;if(Co(a)&&a!==10)return a*1e3},rI=()=>{let a=ys?.rtt;if(Co(a)&&a!==3e3)return a},aI=(a,e,t)=>{let i=t*8,r=i/a;return i/(r+e)},Ed=class a{constructor(e){this.subscription=new ZT;this.concurrentDownloads=new Set;this.tuningConfig=e;let t=a.load(eI)||(e.useBrowserEstimation?iI():void 0)||n0,i=a.load(tI)??(e.useBrowserEstimation?rI():void 0)??0;if(this.throughput$=new Td(t),this.rtt$=new Td(i),this.rttAdjustedThroughput$=new Td(aI(t,i,e.rttPenaltyRequestSize)),this.throughput=$t.getSmoothedValue(t,-1,e),this.rtt=$t.getSmoothedValue(i,1,e),e.useBrowserEstimation){let r=()=>{let n=iI();n&&this.throughput.next(n);let o=rI();Co(o)&&this.rtt.next(o)};ys&&"onchange"in ys&&this.subscription.add(Do(ys,"change").subscribe(r)),r()}this.subscription.add(this.throughput.smoothed$.subscribe(r=>{Id.set(eI,r.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(r=>{Id.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(r0({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(a0(({throughput:r,rtt:s})=>aI(r,s,e.rttPenaltyRequestSize)),s0(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=je(),r=new ZT;switch(this.subscription.add(r),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:r.add(Do(e,"progress").pipe(i0()).subscribe(s=>{t=s.loaded,i=je()}));break;case 1:case 0:r.add(Do(e,"loadstart").subscribe(()=>{t=0,i=je()}));break}r.add(Do(e,"loadend").subscribe(s=>{if(e.status===200){let n=s.loaded,o=je(),u=n-t,l=o-i;this.addRawSpeed(u,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=je(),n=0,o=je(),u=c=>{this.concurrentDownloads.delete(e),i.releaseLock(),e.cancel(`Throughput Estimator error: ${c}`).catch(()=>{})},l=async({done:c,value:d})=>{if(c)!t&&this.addRawSpeed(r,je()-s,1),this.concurrentDownloads.delete(e);else if(d){if(t){let p=je();if(p-o>this.tuningConfig.lowLatency.continuesByteSequenceInterval||p-s>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let f=o-s;f&&this.addRawSpeed(n,f,1,t),n=d.byteLength,s=je()}else n+=d.byteLength;o=je()}else r+=d.byteLength,n+=d.byteLength,n>=this.tuningConfig.streamMinSampleSize&&je()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,je()-o,this.concurrentDownloads.size),n=0,o=je());await i?.read().then(l,u)}};this.concurrentDownloads.add(e),i?.read().then(l,u)}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=Id.get(e);if(Co(t))return parseInt(t,10)??void 0}},sI=Ed;import{fillWithDefault as o0,VideoQuality as Bo}from"@vkontakte/videoplayer-shared";var nI={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:Bo.Q_4320P,activeVideoAreaThreshold:.1,highQualityLimit:Bo.Q_720P,trafficSavingLimit:Bo.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:Bo.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},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,maxLiveDuration:7200,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:250,playbackCatchupSpeedup:.05,isActiveOnDefault:!1,bufferEstimator:{emaAlpha:.45,changeThreshold:.05,deviationDepth:20,deviationFactor:.5,extremumInterval:5}}},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1,lowLatencyActiveLiveDelay:3e3,activeLiveDelay:5e3,maxPausedTime:5e3},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,forceFormat:void 0,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:"07A4434E",useWebmBigRequest:!1,webmCodec:"vp9",androidPreferredFormat:"dash",preferCMAF:!1,preferWebRTC:!1,preferMultiStream:!1,preferHDR:!1,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,seekNearDurationBias:1,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useHlsJs:!1,useNativeHLSTextTracks:!1,useManagedMediaSource:!0,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,useOldMSEDetection:!1,useHlsLiveNewTextManager:!1,exposeInternalsToGlobal:!1,hlsLiveNewTextManagerDownloadThreshold:4e3,disableYandexPiP:!1,asyncResolveClientChecker:!1,autostartOnlyIfVisible:!1},oI=a=>({...o0(a,nI),configName:[...a.configName??[],...nI.configName]});import{assertNonNullable as Vo,combine as Dt,ErrorCategory as _o,filter as O,filterChanged as W,fromEvent as wd,isNonNullable as dI,isNullable as f0,Logger as m0,map as G,mapTo as pI,merge as Xt,now as Oo,once as j,Subject as z,Subscription as hI,tap as Ad,ValueSubject as R,isHigher as b0,isInvariantQuality as fI,flattenObject as Jt,throttle as kd,getTraceSubscriptionMethod as mI,TracerFactory as g0,InternalsExposure as S0}from"@vkontakte/videoplayer-shared";import{merge as u0,map as l0,filter as uI,isNonNullable as c0}from"@vkontakte/videoplayer-shared";var xd=({seekState:a,position$:e})=>u0(a.stateChangeEnded$.pipe(l0(({to:t})=>t.state==="none"?void 0:(t.position??NaN)/1e3),uI(c0)),e.pipe(uI(()=>a.getState().state==="none")));import{assertNonNullable as d0}from"@vkontakte/videoplayer-shared";var lI=a=>{let e=typeof a.container=="string"?document.getElementById(a.container):a.container;return d0(e,`Wrong container or containerId {${a.container}}`),e};import{filter as p0,once as h0}from"@vkontakte/videoplayer-shared";var cI=(a,e,t,i)=>{a!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&t?.getValue().length===0?t.pipe(p0(r=>r.length>0),h0()).subscribe(r=>{r.find(i)&&e.startTransitionTo(a)}):(a===void 0||t?.getValue().find(i))&&e.startTransitionTo(a)};var Fo=class{constructor(e={configName:[]},t=g0.createRootTracer(!1)){this.subscription=new hI;this.logger=new m0;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),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 z,ready$:new z,started$:new z,playing$:new z,paused$:new z,stopped$:new z,willReady$:new z,willStart$:new z,willResume$:new z,willPause$:new z,willStop$:new z,willDestruct$:new z,watchCoverageRecord$:new z,watchCoverageLive$:new z,managedError$:new z,fatalError$:new z,fetcherRecoverableError$:new z,ended$:new z,looped$:new z,seeked$:new z,willSeek$:new z,autoplaySoundProhibited$:new z,firstBytes$:new z,loadedMetadata$:new z,firstFrame$:new z,canplay$:new z,log$:new z,fetcherError$:new z,severeStallOccured$:new z};this.experimental={element$:new R(void 0),tuningConfigName$:new R([]),enableDebugTelemetry$:new R(!1),dumpTelemetry:dS,getCurrentTime$:new R(null)};if(this.initLogs(),this.tuning=oI(e),this.tracer=t,this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new Vs({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new sI(this.tuning.throughputEstimator),e.exposeInternalsToGlobal&&(this.internalsExposure=new S0("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:(...o)=>{try{return n.apply(i,o)}catch(u){let l=o.map(p=>JSON.stringify(p,(h,f)=>{let b=typeof f;return(0,bI.default)(["number","string","boolean"],b)?f:f===null?null:`<${b}>`})),c=`Player.${String(r)}`,d=`Exception calling ${c} (${l.join(", ")})`;throw this.events.fatalError$.next({id:c,category:_o.WTF,message:d,thrown:u}),u}}}})}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",Jt(n)),this.domContainer=lI(e),this.chromecastInitializer.contentId=e.meta?.videoId,this.providerContainer=new vs({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?_.isInited$.pipe(O(s=>!!s),j()).subscribe(()=>{console.log("Core SDK async start"),i()}):i()};return this.isNotActiveTabCase()?(this.tracer.log("request play from hidden tab"),wd(document,"visibilitychange").pipe(j()).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),j()).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),j()).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),j()).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),j()).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),j()).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),j()).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),j()).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),j()).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),j()).subscribe(()=>{this.desiredState.videoStream.startTransitionTo(e)})),this}setAudioStream(e){return this.subscription.add(this.playerInited.pipe(O(t=>!!t),j()).subscribe(()=>{this.desiredState.audioStream.startTransitionTo(e)})),this}setQuality(e){return this.subscription.add(this.playerInited.pipe(O(t=>!!t),j()).subscribe(()=>{Vo(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),j()).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),j()).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),j()).subscribe(()=>{this.tracer.log("setAutoQualityLimits",Jt(e)),this.desiredState.autoVideoTrackLimits.startTransitionTo(e)})),this}setPredefinedQualityLimits(e){return this.subscription.add(this.playerInited.pipe(O(t=>!!t),j()).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),j()).subscribe(()=>{Vo(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),j()).subscribe(()=>{e.length&&this.tracer.log("setExternalTextTracks",Jt(e)),this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>({type:"external",...t})))})),this}selectTextTrack(e){return this.subscription.add(this.playerInited.pipe(O(t=>!!t),j()).subscribe(()=>{cI(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),j()).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),j()).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),j()).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),j()).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),j()).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),j()).subscribe(()=>{let e=this.getScene3D();e&&e.holdCamera()})),this}releaseCamera(){return this.subscription.add(this.playerInited.pipe(O(e=>!!e),j()).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 dI(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(Xt(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(Wl(e,t,i))})),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(O(({from:e})=>e==="stopped"),j()).subscribe(()=>{this.initedAt=Oo(),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",Jt(n)),n.state==="requested"?this.desiredState.seekState.setState({...n,state:"applying"}):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:_o.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.soundProhibitedEvent$.pipe(j()).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",Jt(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),W()).subscribe(()=>this.isPlaybackStarted=!1)).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add(Dt({availableVideoTracks:e.providerOutput.availableVideoTracks$,currentVideoStream:e.providerOutput.currentVideoStream$}).pipe(G(({availableVideoTracks:n,currentVideoStream:o})=>n.filter(u=>o?o.id===u.streamId:!0).map(({quality:u})=>u).sort((u,l)=>fI(u)?1:fI(l)?-1:b0(l,u)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(n=>{let o={};for(let u of n)u.fps&&(o[u.quality]=u.fps);this.info.availableQualitiesFps$.next(o)})).add(e.providerOutput.availableAudioStreams$.subscribe(this.info.availableAudioStreams$)).add(e.providerOutput.currentVideoStream$.subscribe(this.info.currentVideoStream$)).add(e.providerOutput.currentAudioStream$.subscribe(this.info.currentAudioStream$)).add(e.providerOutput.availableAudioTracks$.subscribe(this.info.availableAudioTracks$)).add(e.providerOutput.isAudioAvailable$.pipe(W()).subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.pipe(O(n=>dI(n))).subscribe(n=>{this.info.currentQuality$.next(n?.quality),this.info.videoBitrate$.next(n?.bitrate)})).add(e.providerOutput.currentVideoSegmentLength$.pipe(W((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.pipe(W((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe(W()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(W()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(W()).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(Ad(n=>n&&this.stop())).subscribe(this.info.isLiveEnded$)).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(Dt({hasLiveOffsetByPaused:Xt(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(G(n=>n.to),W(),G(n=>n==="paused")),isLowLatency:e.providerOutput.isLowLatency$}).subscribe(({hasLiveOffsetByPaused:n,isLowLatency:o})=>{if(window.clearTimeout(this.hasLiveOffsetByPausedTimer),n){this.hasLiveOffsetByPausedTimer=window.setTimeout(()=>{this.hasLiveOffsetByPaused.next(!0)},this.getActiveLiveDelay(o));return}this.hasLiveOffsetByPaused.next(!1)})).add(Dt({atLiveEdge:Dt({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:xd({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(G(({isLive:n,position:o,isLowLatency:u})=>{let l=this.getActiveLiveDelay(u);return n&&Math.abs(o)<l/1e3}),W(),Ad(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(G(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add(Dt({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(G(({isLive:n,position:o,duration:u})=>n&&(Math.abs(u)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),W(),Ad(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(G(n=>n.muted),W()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(G(n=>n.volume),W()).subscribe(this.info.volume$)).add(xd({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(Xt(e.providerOutput.endedEvent$.pipe(pI(!0)),e.providerOutput.seekedEvent$.pipe(pI(!1))).pipe(W()).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:_o.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.firstBytesEvent$.pipe(j(),G(n=>n??Oo()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe(j(),G(()=>Oo()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(j(),G(()=>Oo()-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"),j()).subscribe(()=>i.next(!1)));let r=0,s=Xt(e.providerOutput.isBuffering$,t,i).pipe(G(()=>{let n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||i.getValue();return n&&!o}),W());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(Xt(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{let n=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:n?.videoWidth,height:n?.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{let o=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:n?.size?.width,height:n?.size?.height},{width:o?.videoWidth,height:o?.videoHeight})})).add(e.providerOutput.is3DVideo$.subscribe(this.info.is3DVideo$)),this.subscription.add(Xt(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,e.providerOutput.elementVisible$,this.chromecastInitializer.castState$).subscribe(()=>{let n=e.providerOutput.inPiP$.getValue(),o=e.providerOutput.inFullscreen$.getValue(),u=e.providerOutput.element$.getValue(),l=e.providerOutput.elementVisible$.getValue(),c=this.chromecastInitializer.castState$.getValue(),d;c==="CONNECTED"?d="second_screen":u?l?n?d="pip":o?d="fullscreen":d="inline":d="invisible":d="none",this.info.surface$.getValue()!==d&&this.info.surface$.next(d)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(G(e=>e?.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){let t=new hI;this.subscription.add(t),this.subscription.add(e.current$.pipe(W((i,r)=>i.provider===r.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(O(i=>i.length>0),j()).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=gt(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(Xt(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;Vo(this.providerContainer),Vo(e),cS(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(t=>lS(t)),this.providerContainer.current$.subscribe(({type:t})=>na("provider",t)),e.duration$.subscribe(t=>na("duration",t)),e.availableVideoTracks$.pipe(O(t=>!!t.length),j()).subscribe(t=>na("tracks",t)),this.events.fatalError$.subscribe(new xe("fatalError")),this.events.managedError$.subscribe(new xe("managedError")),e.position$.subscribe(new xe("position")),e.currentVideoTrack$.pipe(G(t=>t?.quality)).subscribe(new xe("quality")),this.info.currentBuffer$.subscribe(new xe("buffer")),e.isBuffering$.subscribe(new xe("isBuffering"))].forEach(t=>this.subscription.add(t)),na("codecs",_.video.supportedCodecs)}initTracerSubscription(){let e=mI(this.tracer.log.bind(this.tracer)),t=mI(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(W()).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(Dt({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe(O(({currentQuality:i,videoBitrate:r})=>!!i&&!!r),W((i,r)=>i.currentQuality===r.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe(O(i=>i>0),W()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe(O(i=>i>0),W()).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(Dt({currentBuffer:this.info.currentBuffer$.pipe(O(i=>i.end>0),W((i,r)=>i.end===r.end&&i.start===r.start)),position:this.info.position$.pipe(W())}).pipe(kd(1e3)).subscribe(e("currentBufferAndPosition"))).add(this.info.duration$.pipe(W()).subscribe(e("duration"))).add(this.info.isBuffering$.subscribe(e("isBuffering"))).add(this.info.isLive$.pipe(W()).subscribe(e("isLive"))).add(this.info.canChangePlaybackSpeed$.pipe(W()).subscribe(e("canChangePlaybackSpeed"))).add(Dt({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe(O(({liveTime:i,liveBufferTime:r})=>!!i&&!!r),kd(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe(W(),O(i=>i===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe(W(),O(i=>i===!0)).subscribe(e("atLiveDurationEdge"))).add(this.info.muted$.pipe(W()).subscribe(e("muted"))).add(this.info.volume$.pipe(W()).subscribe(e("volume"))).add(this.info.isEnded$.pipe(W(),O(i=>i===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add(Dt({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe(O(({throughputEstimation:i,rtt:r})=>!!i&&!!r),kd(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe(W(),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:_o.DOM,message:String(r)})})};this.subscription.add(Xt(wd(document,"visibilitychange"),wd(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",Jt({quality:t,availableTracks:Jt(e),track:Jt(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&&!ha()}};import{Subscription as SX,Observable as vX,Subject as yX,ValueSubject as TX,VideoQuality as IX}from"@vkontakte/videoplayer-shared";var EX=`@vkontakte/videoplayer-core@${Ld}`;export{Rs as ChromecastState,qo as HttpConnectionType,vX as Observable,ke as PlaybackState,Fo as Player,Ls as PredefinedQualityLimits,EX as SDK_VERSION,yX as Subject,SX as Subscription,jo as Surface,Ld as VERSION,TX as ValueSubject,Et as VideoFormat,IX as VideoQuality,_ as clientChecker,sa as isMobile};