@vkontakte/videoplayer-core 2.0.138-dev.2ccb74c0.0 → 2.0.138-dev.b9cfb5f8.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/es2018.esm.js CHANGED
@@ -1,85 +1,85 @@
1
1
  /**
2
- * @vkontakte/videoplayer-core v2.0.138-dev.2ccb74c0.0
3
- * Mon, 18 Aug 2025 18:48:09 GMT
2
+ * @vkontakte/videoplayer-core v2.0.138-dev.b9cfb5f8.0
3
+ * Thu, 21 Aug 2025 11:00:22 GMT
4
4
  * https://st.mycdn.me/static/vkontakte-videoplayer/2-0-138/doc/
5
5
  */
6
- var GE=Object.create;var jp=Object.defineProperty;var zE=Object.getOwnPropertyDescriptor;var YE=Object.getOwnPropertyNames;var KE=Object.getPrototypeOf,XE=Object.prototype.hasOwnProperty;var g=(a,e)=>()=>(e||a((e={exports:{}}).exports,e),e.exports);var JE=(a,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of YE(e))!XE.call(a,r)&&r!==t&&jp(a,r,{get:()=>e[r],enumerable:!(i=zE(e,r))||i.enumerable});return a};var O=(a,e,t)=>(t=a!=null?GE(KE(a)):{},JE(e||!a||!a.__esModule?jp(t,"default",{value:a,enumerable:!0}):t,a));var oe=g((Su,Wp)=>{"use strict";var Zr=function(a){return a&&a.Math===Math&&a};Wp.exports=Zr(typeof globalThis=="object"&&globalThis)||Zr(typeof window=="object"&&window)||Zr(typeof self=="object"&&self)||Zr(typeof global=="object"&&global)||Zr(typeof Su=="object"&&Su)||function(){return this}()||Function("return this")()});var he=g((e_,Gp)=>{"use strict";Gp.exports=function(a){try{return!!a()}catch(e){return!0}}});var ea=g((t_,zp)=>{"use strict";var ZE=he();zp.exports=!ZE(function(){var a=function(){}.bind();return typeof a!="function"||a.hasOwnProperty("prototype")})});var yu=g((i_,Jp)=>{"use strict";var ex=ea(),Xp=Function.prototype,Yp=Xp.apply,Kp=Xp.call;Jp.exports=typeof Reflect=="object"&&Reflect.apply||(ex?Kp.bind(Yp):function(){return Kp.apply(Yp,arguments)})});var fe=g((r_,th)=>{"use strict";var Zp=ea(),eh=Function.prototype,Tu=eh.call,tx=Zp&&eh.bind.bind(Tu,Tu);th.exports=Zp?tx:function(a){return function(){return Tu.apply(a,arguments)}}});var mi=g((a_,rh)=>{"use strict";var ih=fe(),ix=ih({}.toString),rx=ih("".slice);rh.exports=function(a){return rx(ix(a),8,-1)}});var Iu=g((s_,ah)=>{"use strict";var ax=mi(),sx=fe();ah.exports=function(a){if(ax(a)==="Function")return sx(a)}});var ue=g((n_,sh)=>{"use strict";var Eu=typeof document=="object"&&document.all;sh.exports=typeof Eu=="undefined"&&Eu!==void 0?function(a){return typeof a=="function"||a===Eu}:function(a){return typeof a=="function"}});var Ue=g((o_,nh)=>{"use strict";var nx=he();nh.exports=!nx(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var He=g((u_,oh)=>{"use strict";var ox=ea(),rn=Function.prototype.call;oh.exports=ox?rn.bind(rn):function(){return rn.apply(rn,arguments)}});var xu=g(ch=>{"use strict";var uh={}.propertyIsEnumerable,lh=Object.getOwnPropertyDescriptor,ux=lh&&!uh.call({1:2},1);ch.f=ux?function(e){var t=lh(this,e);return!!t&&t.enumerable}:uh});var ta=g((c_,dh)=>{"use strict";dh.exports=function(a,e){return{enumerable:!(a&1),configurable:!(a&2),writable:!(a&4),value:e}}});var hh=g((d_,ph)=>{"use strict";var lx=fe(),cx=he(),dx=mi(),wu=Object,px=lx("".split);ph.exports=cx(function(){return!wu("z").propertyIsEnumerable(0)})?function(a){return dx(a)==="String"?px(a,""):wu(a)}:wu});var ia=g((p_,fh)=>{"use strict";fh.exports=function(a){return a==null}});var Qt=g((h_,mh)=>{"use strict";var hx=ia(),fx=TypeError;mh.exports=function(a){if(hx(a))throw new fx("Can't call method on "+a);return a}});var bi=g((f_,bh)=>{"use strict";var mx=hh(),bx=Qt();bh.exports=function(a){return mx(bx(a))}});var Me=g((m_,gh)=>{"use strict";var gx=ue();gh.exports=function(a){return typeof a=="object"?a!==null:gx(a)}});var gi=g((b_,vh)=>{"use strict";vh.exports={}});var Pt=g((g_,yh)=>{"use strict";var Au=gi(),Pu=oe(),vx=ue(),Sh=function(a){return vx(a)?a:void 0};yh.exports=function(a,e){return arguments.length<2?Sh(Au[a])||Sh(Pu[a]):Au[a]&&Au[a][e]||Pu[a]&&Pu[a][e]}});var ra=g((v_,Th)=>{"use strict";var Sx=fe();Th.exports=Sx({}.isPrototypeOf)});var vi=g((S_,xh)=>{"use strict";var yx=oe(),Ih=yx.navigator,Eh=Ih&&Ih.userAgent;xh.exports=Eh?String(Eh):""});var ku=g((y_,Lh)=>{"use strict";var kh=oe(),Ru=vi(),wh=kh.process,Ah=kh.Deno,Ph=wh&&wh.versions||Ah&&Ah.version,Rh=Ph&&Ph.v8,rt,an;Rh&&(rt=Rh.split("."),an=rt[0]>0&&rt[0]<4?1:+(rt[0]+rt[1]));!an&&Ru&&(rt=Ru.match(/Edge\/(\d+)/),(!rt||rt[1]>=74)&&(rt=Ru.match(/Chrome\/(\d+)/),rt&&(an=+rt[1])));Lh.exports=an});var Lu=g((T_,Mh)=>{"use strict";var $h=ku(),Tx=he(),Ix=oe(),Ex=Ix.String;Mh.exports=!!Object.getOwnPropertySymbols&&!Tx(function(){var a=Symbol("symbol detection");return!Ex(a)||!(Object(a)instanceof Symbol)||!Symbol.sham&&$h&&$h<41})});var $u=g((I_,Dh)=>{"use strict";var xx=Lu();Dh.exports=xx&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var Mu=g((E_,Ch)=>{"use strict";var wx=Pt(),Ax=ue(),Px=ra(),Rx=$u(),kx=Object;Ch.exports=Rx?function(a){return typeof a=="symbol"}:function(a){var e=wx("Symbol");return Ax(e)&&Px(e.prototype,kx(a))}});var aa=g((x_,Bh)=>{"use strict";var Lx=String;Bh.exports=function(a){try{return Lx(a)}catch(e){return"Object"}}});var ft=g((w_,Vh)=>{"use strict";var $x=ue(),Mx=aa(),Dx=TypeError;Vh.exports=function(a){if($x(a))return a;throw new Dx(Mx(a)+" is not a function")}});var sa=g((A_,_h)=>{"use strict";var Cx=ft(),Bx=ia();_h.exports=function(a,e){var t=a[e];return Bx(t)?void 0:Cx(t)}});var Fh=g((P_,Oh)=>{"use strict";var Du=He(),Cu=ue(),Bu=Me(),Vx=TypeError;Oh.exports=function(a,e){var t,i;if(e==="string"&&Cu(t=a.toString)&&!Bu(i=Du(t,a))||Cu(t=a.valueOf)&&!Bu(i=Du(t,a))||e!=="string"&&Cu(t=a.toString)&&!Bu(i=Du(t,a)))return i;throw new Vx("Can't convert object to primitive value")}});var at=g((R_,Nh)=>{"use strict";Nh.exports=!0});var Hh=g((k_,Uh)=>{"use strict";var qh=oe(),_x=Object.defineProperty;Uh.exports=function(a,e){try{_x(qh,a,{value:e,configurable:!0,writable:!0})}catch(t){qh[a]=e}return e}});var na=g((L_,Wh)=>{"use strict";var Ox=at(),Fx=oe(),Nx=Hh(),jh="__core-js_shared__",Qh=Wh.exports=Fx[jh]||Nx(jh,{});(Qh.versions||(Qh.versions=[])).push({version:"3.43.0",mode:Ox?"pure":"global",copyright:"\xA9 2014-2025 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.43.0/LICENSE",source:"https://github.com/zloirock/core-js"})});var Vu=g(($_,zh)=>{"use strict";var Gh=na();zh.exports=function(a,e){return Gh[a]||(Gh[a]=e||{})}});var Yi=g((M_,Yh)=>{"use strict";var qx=Qt(),Ux=Object;Yh.exports=function(a){return Ux(qx(a))}});var st=g((D_,Kh)=>{"use strict";var Hx=fe(),jx=Yi(),Qx=Hx({}.hasOwnProperty);Kh.exports=Object.hasOwn||function(e,t){return Qx(jx(e),t)}});var _u=g((C_,Xh)=>{"use strict";var Wx=fe(),Gx=0,zx=Math.random(),Yx=Wx(1.1.toString);Xh.exports=function(a){return"Symbol("+(a===void 0?"":a)+")_"+Yx(++Gx+zx,36)}});var ye=g((B_,Zh)=>{"use strict";var Kx=oe(),Xx=Vu(),Jh=st(),Jx=_u(),Zx=Lu(),ew=$u(),Ki=Kx.Symbol,Ou=Xx("wks"),tw=ew?Ki.for||Ki:Ki&&Ki.withoutSetter||Jx;Zh.exports=function(a){return Jh(Ou,a)||(Ou[a]=Zx&&Jh(Ki,a)?Ki[a]:tw("Symbol."+a)),Ou[a]}});var af=g((V_,rf)=>{"use strict";var iw=He(),ef=Me(),tf=Mu(),rw=sa(),aw=Fh(),sw=ye(),nw=TypeError,ow=sw("toPrimitive");rf.exports=function(a,e){if(!ef(a)||tf(a))return a;var t=rw(a,ow),i;if(t){if(e===void 0&&(e="default"),i=iw(t,a,e),!ef(i)||tf(i))return i;throw new nw("Can't convert object to primitive value")}return e===void 0&&(e="number"),aw(a,e)}});var Fu=g((__,sf)=>{"use strict";var uw=af(),lw=Mu();sf.exports=function(a){var e=uw(a,"string");return lw(e)?e:e+""}});var sn=g((O_,of)=>{"use strict";var cw=oe(),nf=Me(),Nu=cw.document,dw=nf(Nu)&&nf(Nu.createElement);of.exports=function(a){return dw?Nu.createElement(a):{}}});var qu=g((F_,uf)=>{"use strict";var pw=Ue(),hw=he(),fw=sn();uf.exports=!pw&&!hw(function(){return Object.defineProperty(fw("div"),"a",{get:function(){return 7}}).a!==7})});var df=g(cf=>{"use strict";var mw=Ue(),bw=He(),gw=xu(),vw=ta(),Sw=bi(),yw=Fu(),Tw=st(),Iw=qu(),lf=Object.getOwnPropertyDescriptor;cf.f=mw?lf:function(e,t){if(e=Sw(e),t=yw(t),Iw)try{return lf(e,t)}catch(i){}if(Tw(e,t))return vw(!bw(gw.f,e,t),e[t])}});var Uu=g((q_,pf)=>{"use strict";var Ew=he(),xw=ue(),ww=/#|\.prototype\./,oa=function(a,e){var t=Pw[Aw(a)];return t===kw?!0:t===Rw?!1:xw(e)?Ew(e):!!e},Aw=oa.normalize=function(a){return String(a).replace(ww,".").toLowerCase()},Pw=oa.data={},Rw=oa.NATIVE="N",kw=oa.POLYFILL="P";pf.exports=oa});var Xi=g((U_,ff)=>{"use strict";var hf=Iu(),Lw=ft(),$w=ea(),Mw=hf(hf.bind);ff.exports=function(a,e){return Lw(a),e===void 0?a:$w?Mw(a,e):function(){return a.apply(e,arguments)}}});var Hu=g((H_,mf)=>{"use strict";var Dw=Ue(),Cw=he();mf.exports=Dw&&Cw(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var mt=g((j_,bf)=>{"use strict";var Bw=Me(),Vw=String,_w=TypeError;bf.exports=function(a){if(Bw(a))return a;throw new _w(Vw(a)+" is not an object")}});var Si=g(vf=>{"use strict";var Ow=Ue(),Fw=qu(),Nw=Hu(),nn=mt(),gf=Fu(),qw=TypeError,ju=Object.defineProperty,Uw=Object.getOwnPropertyDescriptor,Qu="enumerable",Wu="configurable",Gu="writable";vf.f=Ow?Nw?function(e,t,i){if(nn(e),t=gf(t),nn(i),typeof e=="function"&&t==="prototype"&&"value"in i&&Gu in i&&!i[Gu]){var r=Uw(e,t);r&&r[Gu]&&(e[t]=i.value,i={configurable:Wu in i?i[Wu]:r[Wu],enumerable:Qu in i?i[Qu]:r[Qu],writable:!1})}return ju(e,t,i)}:ju:function(e,t,i){if(nn(e),t=gf(t),nn(i),Fw)try{return ju(e,t,i)}catch(r){}if("get"in i||"set"in i)throw new qw("Accessors not supported");return"value"in i&&(e[t]=i.value),e}});var Ji=g((W_,Sf)=>{"use strict";var Hw=Ue(),jw=Si(),Qw=ta();Sf.exports=Hw?function(a,e,t){return jw.f(a,e,Qw(1,t))}:function(a,e,t){return a[e]=t,a}});var pe=g((G_,Tf)=>{"use strict";var ua=oe(),Ww=yu(),Gw=Iu(),zw=ue(),Yw=df().f,Kw=Uu(),Zi=gi(),Xw=Xi(),er=Ji(),yf=st();na();var Jw=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 Ww(a,this,arguments)};return e.prototype=a.prototype,e};Tf.exports=function(a,e){var t=a.target,i=a.global,r=a.stat,s=a.proto,n=i?ua:r?ua[t]:ua[t]&&ua[t].prototype,o=i?Zi:Zi[t]||er(Zi,t,{})[t],u=o.prototype,l,c,d,f,p,h,m,v,b;for(f in e)l=Kw(i?f:t+(r?".":"#")+f,a.forced),c=!l&&n&&yf(n,f),h=o[f],c&&(a.dontCallGetSet?(b=Yw(n,f),m=b&&b.value):m=n[f]),p=c&&m?m:e[f],!(!l&&!s&&typeof h==typeof p)&&(a.bind&&c?v=Xw(p,ua):a.wrap&&c?v=Jw(p):s&&zw(p)?v=Gw(p):v=p,(a.sham||p&&p.sham||h&&h.sham)&&er(v,"sham",!0),er(o,f,v),s&&(d=t+"Prototype",yf(Zi,d)||er(Zi,d,{}),er(Zi[d],f,p),a.real&&u&&(l||!u[f])&&er(u,f,p)))}});var Ef=g((z_,If)=>{"use strict";var Zw=Math.ceil,eA=Math.floor;If.exports=Math.trunc||function(e){var t=+e;return(t>0?eA:Zw)(t)}});var la=g((Y_,xf)=>{"use strict";var tA=Ef();xf.exports=function(a){var e=+a;return e!==e||e===0?0:tA(e)}});var Af=g((K_,wf)=>{"use strict";var iA=la(),rA=Math.max,aA=Math.min;wf.exports=function(a,e){var t=iA(a);return t<0?rA(t+e,0):aA(t,e)}});var zu=g((X_,Pf)=>{"use strict";var sA=la(),nA=Math.min;Pf.exports=function(a){var e=sA(a);return e>0?nA(e,9007199254740991):0}});var tr=g((J_,Rf)=>{"use strict";var oA=zu();Rf.exports=function(a){return oA(a.length)}});var Yu=g((Z_,Lf)=>{"use strict";var uA=bi(),lA=Af(),cA=tr(),kf=function(a){return function(e,t,i){var r=uA(e),s=cA(r);if(s===0)return!a&&-1;var n=lA(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}};Lf.exports={includes:kf(!0),indexOf:kf(!1)}});var ca=g((eO,$f)=>{"use strict";$f.exports=function(){}});var Mf=g(()=>{"use strict";var dA=pe(),pA=Yu().includes,hA=he(),fA=ca(),mA=hA(function(){return!Array(1).includes()});dA({target:"Array",proto:!0,forced:mA},{includes:function(e){return pA(this,e,arguments.length>1?arguments[1]:void 0)}});fA("includes")});var Wt=g((rO,Df)=>{"use strict";var bA=Pt();Df.exports=bA});var Bf=g((aO,Cf)=>{"use strict";Mf();var gA=Wt();Cf.exports=gA("Array","includes")});var _f=g((sO,Vf)=>{"use strict";var vA=Bf();Vf.exports=vA});var Ae=g((nO,Of)=>{"use strict";var SA=_f();Of.exports=SA});var ln=g((vO,Wf)=>{"use strict";var PA=Vu(),RA=_u(),Qf=PA("keys");Wf.exports=function(a){return Qf[a]||(Qf[a]=RA(a))}});var zf=g((SO,Gf)=>{"use strict";var kA=he();Gf.exports=!kA(function(){function a(){}return a.prototype.constructor=null,Object.getPrototypeOf(new a)!==a.prototype})});var cn=g((yO,Kf)=>{"use strict";var LA=st(),$A=ue(),MA=Yi(),DA=ln(),CA=zf(),Yf=DA("IE_PROTO"),Ju=Object,BA=Ju.prototype;Kf.exports=CA?Ju.getPrototypeOf:function(a){var e=MA(a);if(LA(e,Yf))return e[Yf];var t=e.constructor;return $A(t)&&e instanceof t?t.prototype:e instanceof Ju?BA:null}});var dn=g((TO,Xf)=>{"use strict";Xf.exports={}});var em=g((IO,Zf)=>{"use strict";var VA=fe(),Zu=st(),_A=bi(),OA=Yu().indexOf,FA=dn(),Jf=VA([].push);Zf.exports=function(a,e){var t=_A(a),i=0,r=[],s;for(s in t)!Zu(FA,s)&&Zu(t,s)&&Jf(r,s);for(;e.length>i;)Zu(t,s=e[i++])&&(~OA(r,s)||Jf(r,s));return r}});var el=g((EO,tm)=>{"use strict";tm.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var tl=g((xO,im)=>{"use strict";var NA=em(),qA=el();im.exports=Object.keys||function(e){return NA(e,qA)}});var il=g((wO,om)=>{"use strict";var am=Ue(),UA=he(),sm=fe(),HA=cn(),jA=tl(),QA=bi(),WA=xu().f,nm=sm(WA),GA=sm([].push),zA=am&&UA(function(){var a=Object.create(null);return a[2]=2,!nm(a,2)}),rm=function(a){return function(e){for(var t=QA(e),i=jA(t),r=zA&&HA(t)===null,s=i.length,n=0,o=[],u;s>n;)u=i[n++],(!am||(r?u in t:nm(t,u)))&&GA(o,a?[u,t[u]]:t[u]);return o}};om.exports={entries:rm(!0),values:rm(!1)}});var um=g(()=>{"use strict";var YA=pe(),KA=il().entries;YA({target:"Object",stat:!0},{entries:function(e){return KA(e)}})});var cm=g((RO,lm)=>{"use strict";um();var XA=gi();lm.exports=XA.Object.entries});var pm=g((kO,dm)=>{"use strict";var JA=cm();dm.exports=JA});var ir=g((LO,hm)=>{"use strict";var ZA=pm();hm.exports=ZA});var yi=g(($O,fm)=>{"use strict";fm.exports={}});var gm=g((MO,bm)=>{"use strict";var eP=oe(),tP=ue(),mm=eP.WeakMap;bm.exports=tP(mm)&&/native code/.test(String(mm))});var nl=g((DO,ym)=>{"use strict";var iP=gm(),Sm=oe(),rP=Me(),aP=Ji(),rl=st(),al=na(),sP=ln(),nP=dn(),vm="Object already initialized",sl=Sm.TypeError,oP=Sm.WeakMap,pn,da,hn,uP=function(a){return hn(a)?da(a):pn(a,{})},lP=function(a){return function(e){var t;if(!rP(e)||(t=da(e)).type!==a)throw new sl("Incompatible receiver, "+a+" required");return t}};iP||al.state?(nt=al.state||(al.state=new oP),nt.get=nt.get,nt.has=nt.has,nt.set=nt.set,pn=function(a,e){if(nt.has(a))throw new sl(vm);return e.facade=a,nt.set(a,e),e},da=function(a){return nt.get(a)||{}},hn=function(a){return nt.has(a)}):(Ti=sP("state"),nP[Ti]=!0,pn=function(a,e){if(rl(a,Ti))throw new sl(vm);return e.facade=a,aP(a,Ti,e),e},da=function(a){return rl(a,Ti)?a[Ti]:{}},hn=function(a){return rl(a,Ti)});var nt,Ti;ym.exports={set:pn,get:da,has:hn,enforce:uP,getterFor:lP}});var ll=g((CO,Im)=>{"use strict";var ol=Ue(),cP=st(),Tm=Function.prototype,dP=ol&&Object.getOwnPropertyDescriptor,ul=cP(Tm,"name"),pP=ul&&function(){}.name==="something",hP=ul&&(!ol||ol&&dP(Tm,"name").configurable);Im.exports={EXISTS:ul,PROPER:pP,CONFIGURABLE:hP}});var xm=g(Em=>{"use strict";var fP=Ue(),mP=Hu(),bP=Si(),gP=mt(),vP=bi(),SP=tl();Em.f=fP&&!mP?Object.defineProperties:function(e,t){gP(e);for(var i=vP(t),r=SP(t),s=r.length,n=0,o;s>n;)bP.f(e,o=r[n++],i[o]);return e}});var cl=g((VO,wm)=>{"use strict";var yP=Pt();wm.exports=yP("document","documentElement")});var fl=g((_O,Mm)=>{"use strict";var TP=mt(),IP=xm(),Am=el(),EP=dn(),xP=cl(),wP=sn(),AP=ln(),Pm=">",Rm="<",pl="prototype",hl="script",Lm=AP("IE_PROTO"),dl=function(){},$m=function(a){return Rm+hl+Pm+a+Rm+"/"+hl+Pm},km=function(a){a.write($m("")),a.close();var e=a.parentWindow.Object;return a=null,e},PP=function(){var a=wP("iframe"),e="java"+hl+":",t;return a.style.display="none",xP.appendChild(a),a.src=String(e),t=a.contentWindow.document,t.open(),t.write($m("document.F=Object")),t.close(),t.F},fn,mn=function(){try{fn=new ActiveXObject("htmlfile")}catch(e){}mn=typeof document!="undefined"?document.domain&&fn?km(fn):PP():km(fn);for(var a=Am.length;a--;)delete mn[pl][Am[a]];return mn()};EP[Lm]=!0;Mm.exports=Object.create||function(e,t){var i;return e!==null?(dl[pl]=TP(e),i=new dl,dl[pl]=null,i[Lm]=e):i=mn(),t===void 0?i:IP.f(i,t)}});var rr=g((OO,Dm)=>{"use strict";var RP=Ji();Dm.exports=function(a,e,t,i){return i&&i.enumerable?a[e]=t:RP(a,e,t),a}});var vl=g((FO,Vm)=>{"use strict";var kP=he(),LP=ue(),$P=Me(),MP=fl(),Cm=cn(),DP=rr(),CP=ye(),BP=at(),gl=CP("iterator"),Bm=!1,Rt,ml,bl;[].keys&&(bl=[].keys(),"next"in bl?(ml=Cm(Cm(bl)),ml!==Object.prototype&&(Rt=ml)):Bm=!0);var VP=!$P(Rt)||kP(function(){var a={};return Rt[gl].call(a)!==a});VP?Rt={}:BP&&(Rt=MP(Rt));LP(Rt[gl])||DP(Rt,gl,function(){return this});Vm.exports={IteratorPrototype:Rt,BUGGY_SAFARI_ITERATORS:Bm}});var bn=g((NO,Om)=>{"use strict";var _P=ye(),OP=_P("toStringTag"),_m={};_m[OP]="z";Om.exports=String(_m)==="[object z]"});var pa=g((qO,Fm)=>{"use strict";var FP=bn(),NP=ue(),gn=mi(),qP=ye(),UP=qP("toStringTag"),HP=Object,jP=gn(function(){return arguments}())==="Arguments",QP=function(a,e){try{return a[e]}catch(t){}};Fm.exports=FP?gn:function(a){var e,t,i;return a===void 0?"Undefined":a===null?"Null":typeof(t=QP(e=HP(a),UP))=="string"?t:jP?gn(e):(i=gn(e))==="Object"&&NP(e.callee)?"Arguments":i}});var qm=g((UO,Nm)=>{"use strict";var WP=bn(),GP=pa();Nm.exports=WP?{}.toString:function(){return"[object "+GP(this)+"]"}});var ha=g((HO,Hm)=>{"use strict";var zP=bn(),YP=Si().f,KP=Ji(),XP=st(),JP=qm(),ZP=ye(),Um=ZP("toStringTag");Hm.exports=function(a,e,t,i){var r=t?a:a&&a.prototype;r&&(XP(r,Um)||YP(r,Um,{configurable:!0,value:e}),i&&!zP&&KP(r,"toString",JP))}});var Qm=g((jO,jm)=>{"use strict";var eR=vl().IteratorPrototype,tR=fl(),iR=ta(),rR=ha(),aR=yi(),sR=function(){return this};jm.exports=function(a,e,t,i){var r=e+" Iterator";return a.prototype=tR(eR,{next:iR(+!i,t)}),rR(a,r,!1,!0),aR[r]=sR,a}});var Gm=g((QO,Wm)=>{"use strict";var nR=fe(),oR=ft();Wm.exports=function(a,e,t){try{return nR(oR(Object.getOwnPropertyDescriptor(a,e)[t]))}catch(i){}}});var Ym=g((WO,zm)=>{"use strict";var uR=Me();zm.exports=function(a){return uR(a)||a===null}});var Xm=g((GO,Km)=>{"use strict";var lR=Ym(),cR=String,dR=TypeError;Km.exports=function(a){if(lR(a))return a;throw new dR("Can't set "+cR(a)+" as a prototype")}});var Sl=g((zO,Jm)=>{"use strict";var pR=Gm(),hR=Me(),fR=Qt(),mR=Xm();Jm.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var a=!1,e={},t;try{t=pR(Object.prototype,"__proto__","set"),t(e,[]),a=e instanceof Array}catch(i){}return function(r,s){return fR(r),mR(s),hR(r)&&(a?t(r,s):r.__proto__=s),r}}():void 0)});var lb=g((YO,ub)=>{"use strict";var bR=pe(),gR=He(),vn=at(),nb=ll(),vR=ue(),SR=Qm(),Zm=cn(),eb=Sl(),yR=ha(),TR=Ji(),yl=rr(),IR=ye(),tb=yi(),ob=vl(),ER=nb.PROPER,xR=nb.CONFIGURABLE,ib=ob.IteratorPrototype,Sn=ob.BUGGY_SAFARI_ITERATORS,fa=IR("iterator"),rb="keys",ma="values",ab="entries",sb=function(){return this};ub.exports=function(a,e,t,i,r,s,n){SR(t,e,i);var o=function(b){if(b===r&&f)return f;if(!Sn&&b&&b in c)return c[b];switch(b){case rb:return function(){return new t(this,b)};case ma:return function(){return new t(this,b)};case ab:return function(){return new t(this,b)}}return function(){return new t(this)}},u=e+" Iterator",l=!1,c=a.prototype,d=c[fa]||c["@@iterator"]||r&&c[r],f=!Sn&&d||o(r),p=e==="Array"&&c.entries||d,h,m,v;if(p&&(h=Zm(p.call(new a)),h!==Object.prototype&&h.next&&(!vn&&Zm(h)!==ib&&(eb?eb(h,ib):vR(h[fa])||yl(h,fa,sb)),yR(h,u,!0,!0),vn&&(tb[u]=sb))),ER&&r===ma&&d&&d.name!==ma&&(!vn&&xR?TR(c,"name",ma):(l=!0,f=function(){return gR(d,this)})),r)if(m={values:o(ma),keys:s?f:o(rb),entries:o(ab)},n)for(v in m)(Sn||l||!(v in c))&&yl(c,v,m[v]);else bR({target:e,proto:!0,forced:Sn||l},m);return(!vn||n)&&c[fa]!==f&&yl(c,fa,f,{name:r}),tb[e]=f,m}});var db=g((KO,cb)=>{"use strict";cb.exports=function(a,e){return{value:a,done:e}}});var Il=g((XO,bb)=>{"use strict";var wR=bi(),Tl=ca(),pb=yi(),fb=nl(),AR=Si().f,PR=lb(),yn=db(),RR=at(),kR=Ue(),mb="Array Iterator",LR=fb.set,$R=fb.getterFor(mb);bb.exports=PR(Array,"Array",function(a,e){LR(this,{type:mb,target:wR(a),index:0,kind:e})},function(){var a=$R(this),e=a.target,t=a.index++;if(!e||t>=e.length)return a.target=null,yn(void 0,!0);switch(a.kind){case"keys":return yn(t,!1);case"values":return yn(e[t],!1)}return yn([t,e[t]],!1)},"values");var hb=pb.Arguments=pb.Array;Tl("keys");Tl("values");Tl("entries");if(!RR&&kR&&hb.name!=="values")try{AR(hb,"name",{value:"values"})}catch(a){}});var vb=g((JO,gb)=>{"use strict";var MR=ye(),DR=yi(),CR=MR("iterator"),BR=Array.prototype;gb.exports=function(a){return a!==void 0&&(DR.Array===a||BR[CR]===a)}});var El=g((ZO,yb)=>{"use strict";var VR=pa(),Sb=sa(),_R=ia(),OR=yi(),FR=ye(),NR=FR("iterator");yb.exports=function(a){if(!_R(a))return Sb(a,NR)||Sb(a,"@@iterator")||OR[VR(a)]}});var Ib=g((eF,Tb)=>{"use strict";var qR=He(),UR=ft(),HR=mt(),jR=aa(),QR=El(),WR=TypeError;Tb.exports=function(a,e){var t=arguments.length<2?QR(a):e;if(UR(t))return HR(qR(t,a));throw new WR(jR(a)+" is not iterable")}});var wb=g((tF,xb)=>{"use strict";var GR=He(),Eb=mt(),zR=sa();xb.exports=function(a,e,t){var i,r;Eb(a);try{if(i=zR(a,"return"),!i){if(e==="throw")throw t;return t}i=GR(i,a)}catch(s){r=!0,i=s}if(e==="throw")throw t;if(r)throw i;return Eb(i),t}});var In=g((iF,kb)=>{"use strict";var YR=Xi(),KR=He(),XR=mt(),JR=aa(),ZR=vb(),ek=tr(),Ab=ra(),tk=Ib(),ik=El(),Pb=wb(),rk=TypeError,Tn=function(a,e){this.stopped=a,this.result=e},Rb=Tn.prototype;kb.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=YR(e,i),l,c,d,f,p,h,m,v=function(S){return l&&Pb(l,"normal"),new Tn(!0,S)},b=function(S){return r?(XR(S),o?u(S[0],S[1],v):u(S[0],S[1])):o?u(S,v):u(S)};if(s)l=a.iterator;else if(n)l=a;else{if(c=ik(a),!c)throw new rk(JR(a)+" is not iterable");if(ZR(c)){for(d=0,f=ek(a);f>d;d++)if(p=b(a[d]),p&&Ab(Rb,p))return p;return new Tn(!1)}l=tk(a,c)}for(h=s?a.next:l.next;!(m=KR(h,l)).done;){try{p=b(m.value)}catch(S){Pb(l,"throw",S)}if(typeof p=="object"&&p&&Ab(Rb,p))return p}return new Tn(!1)}});var $b=g((rF,Lb)=>{"use strict";var ak=Ue(),sk=Si(),nk=ta();Lb.exports=function(a,e,t){ak?sk.f(a,e,nk(0,t)):a[e]=t}});var Mb=g(()=>{"use strict";var ok=pe(),uk=In(),lk=$b();ok({target:"Object",stat:!0},{fromEntries:function(e){var t={};return uk(e,function(i,r){lk(t,i,r)},{AS_ENTRIES:!0}),t}})});var Cb=g((nF,Db)=>{"use strict";Il();Mb();var ck=gi();Db.exports=ck.Object.fromEntries});var Vb=g((oF,Bb)=>{"use strict";Bb.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 Ob=g(()=>{"use strict";Il();var dk=Vb(),pk=oe(),hk=ha(),_b=yi();for(En in dk)hk(pk[En],En),_b[En]=_b.Array;var En});var Nb=g((cF,Fb)=>{"use strict";var fk=Cb();Ob();Fb.exports=fk});var xl=g((dF,qb)=>{"use strict";var mk=Nb();qb.exports=mk});var Ub=g(()=>{"use strict"});var wl=g((fF,Hb)=>{"use strict";var ba=oe(),bk=vi(),gk=mi(),xn=function(a){return bk.slice(0,a.length)===a};Hb.exports=function(){return xn("Bun/")?"BUN":xn("Cloudflare-Workers")?"CLOUDFLARE":xn("Deno/")?"DENO":xn("Node.js/")?"NODE":ba.Bun&&typeof Bun.version=="string"?"BUN":ba.Deno&&typeof Deno.version=="object"?"DENO":gk(ba.process)==="process"?"NODE":ba.window&&ba.document?"BROWSER":"REST"}()});var wn=g((mF,jb)=>{"use strict";var vk=wl();jb.exports=vk==="NODE"});var Wb=g((bF,Qb)=>{"use strict";var Sk=Si();Qb.exports=function(a,e,t){return Sk.f(a,e,t)}});var Yb=g((gF,zb)=>{"use strict";var yk=Pt(),Tk=Wb(),Ik=ye(),Ek=Ue(),Gb=Ik("species");zb.exports=function(a){var e=yk(a);Ek&&e&&!e[Gb]&&Tk(e,Gb,{configurable:!0,get:function(){return this}})}});var Xb=g((vF,Kb)=>{"use strict";var xk=ra(),wk=TypeError;Kb.exports=function(a,e){if(xk(e,a))return a;throw new wk("Incorrect invocation")}});var Pl=g((SF,Jb)=>{"use strict";var Ak=fe(),Pk=ue(),Al=na(),Rk=Ak(Function.toString);Pk(Al.inspectSource)||(Al.inspectSource=function(a){return Rk(a)});Jb.exports=Al.inspectSource});var kl=g((yF,rg)=>{"use strict";var kk=fe(),Lk=he(),Zb=ue(),$k=pa(),Mk=Pt(),Dk=Pl(),eg=function(){},tg=Mk("Reflect","construct"),Rl=/^\s*(?:class|function)\b/,Ck=kk(Rl.exec),Bk=!Rl.test(eg),ga=function(e){if(!Zb(e))return!1;try{return tg(eg,[],e),!0}catch(t){return!1}},ig=function(e){if(!Zb(e))return!1;switch($k(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return Bk||!!Ck(Rl,Dk(e))}catch(t){return!0}};ig.sham=!0;rg.exports=!tg||Lk(function(){var a;return ga(ga.call)||!ga(Object)||!ga(function(){a=!0})||a})?ig:ga});var sg=g((TF,ag)=>{"use strict";var Vk=kl(),_k=aa(),Ok=TypeError;ag.exports=function(a){if(Vk(a))return a;throw new Ok(_k(a)+" is not a constructor")}});var Ll=g((IF,og)=>{"use strict";var ng=mt(),Fk=sg(),Nk=ia(),qk=ye(),Uk=qk("species");og.exports=function(a,e){var t=ng(a).constructor,i;return t===void 0||Nk(i=ng(t)[Uk])?e:Fk(i)}});var lg=g((EF,ug)=>{"use strict";var Hk=fe();ug.exports=Hk([].slice)});var dg=g((xF,cg)=>{"use strict";var jk=TypeError;cg.exports=function(a,e){if(a<e)throw new jk("Not enough arguments");return a}});var $l=g((wF,pg)=>{"use strict";var Qk=vi();pg.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(Qk)});var Nl=g((AF,Tg)=>{"use strict";var je=oe(),Wk=yu(),Gk=Xi(),hg=ue(),zk=st(),yg=he(),fg=cl(),Yk=lg(),mg=sn(),Kk=dg(),Xk=$l(),Jk=wn(),_l=je.setImmediate,Ol=je.clearImmediate,Zk=je.process,Ml=je.Dispatch,eL=je.Function,bg=je.MessageChannel,tL=je.String,Dl=0,va={},gg="onreadystatechange",Sa,Ii,Cl,Bl;yg(function(){Sa=je.location});var Fl=function(a){if(zk(va,a)){var e=va[a];delete va[a],e()}},Vl=function(a){return function(){Fl(a)}},vg=function(a){Fl(a.data)},Sg=function(a){je.postMessage(tL(a),Sa.protocol+"//"+Sa.host)};(!_l||!Ol)&&(_l=function(e){Kk(arguments.length,1);var t=hg(e)?e:eL(e),i=Yk(arguments,1);return va[++Dl]=function(){Wk(t,void 0,i)},Ii(Dl),Dl},Ol=function(e){delete va[e]},Jk?Ii=function(a){Zk.nextTick(Vl(a))}:Ml&&Ml.now?Ii=function(a){Ml.now(Vl(a))}:bg&&!Xk?(Cl=new bg,Bl=Cl.port2,Cl.port1.onmessage=vg,Ii=Gk(Bl.postMessage,Bl)):je.addEventListener&&hg(je.postMessage)&&!je.importScripts&&Sa&&Sa.protocol!=="file:"&&!yg(Sg)?(Ii=Sg,je.addEventListener("message",vg,!1)):gg in mg("script")?Ii=function(a){fg.appendChild(mg("script"))[gg]=function(){fg.removeChild(this),Fl(a)}}:Ii=function(a){setTimeout(Vl(a),0)});Tg.exports={set:_l,clear:Ol}});var xg=g((PF,Eg)=>{"use strict";var Ig=oe(),iL=Ue(),rL=Object.getOwnPropertyDescriptor;Eg.exports=function(a){if(!iL)return Ig[a];var e=rL(Ig,a);return e&&e.value}});var ql=g((RF,Ag)=>{"use strict";var wg=function(){this.head=null,this.tail=null};wg.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}}};Ag.exports=wg});var Rg=g((kF,Pg)=>{"use strict";var aL=vi();Pg.exports=/ipad|iphone|ipod/i.test(aL)&&typeof Pebble!="undefined"});var Lg=g((LF,kg)=>{"use strict";var sL=vi();kg.exports=/web0s(?!.*chrome)/i.test(sL)});var _g=g(($F,Vg)=>{"use strict";var sr=oe(),nL=xg(),$g=Xi(),Ul=Nl().set,oL=ql(),uL=$l(),lL=Rg(),cL=Lg(),Hl=wn(),Mg=sr.MutationObserver||sr.WebKitMutationObserver,Dg=sr.document,Cg=sr.process,An=sr.Promise,Wl=nL("queueMicrotask"),ar,jl,Ql,Pn,Bg;Wl||(ya=new oL,Ta=function(){var a,e;for(Hl&&(a=Cg.domain)&&a.exit();e=ya.get();)try{e()}catch(t){throw ya.head&&ar(),t}a&&a.enter()},!uL&&!Hl&&!cL&&Mg&&Dg?(jl=!0,Ql=Dg.createTextNode(""),new Mg(Ta).observe(Ql,{characterData:!0}),ar=function(){Ql.data=jl=!jl}):!lL&&An&&An.resolve?(Pn=An.resolve(void 0),Pn.constructor=An,Bg=$g(Pn.then,Pn),ar=function(){Bg(Ta)}):Hl?ar=function(){Cg.nextTick(Ta)}:(Ul=$g(Ul,sr),ar=function(){Ul(Ta)}),Wl=function(a){ya.head||ar(),ya.add(a)});var ya,Ta;Vg.exports=Wl});var Fg=g((MF,Og)=>{"use strict";Og.exports=function(a,e){try{arguments.length===1?console.error(a):console.error(a,e)}catch(t){}}});var Rn=g((DF,Ng)=>{"use strict";Ng.exports=function(a){try{return{error:!1,value:a()}}catch(e){return{error:!0,value:e}}}});var Ei=g((CF,qg)=>{"use strict";var dL=oe();qg.exports=dL.Promise});var nr=g((BF,Qg)=>{"use strict";var pL=oe(),Ia=Ei(),hL=ue(),fL=Uu(),mL=Pl(),bL=ye(),Ug=wl(),gL=at(),Gl=ku(),Hg=Ia&&Ia.prototype,vL=bL("species"),zl=!1,jg=hL(pL.PromiseRejectionEvent),SL=fL("Promise",function(){var a=mL(Ia),e=a!==String(Ia);if(!e&&Gl===66||gL&&!(Hg.catch&&Hg.finally))return!0;if(!Gl||Gl<51||!/native code/.test(a)){var t=new Ia(function(s){s(1)}),i=function(s){s(function(){},function(){})},r=t.constructor={};if(r[vL]=i,zl=t.then(function(){})instanceof i,!zl)return!0}return!e&&(Ug==="BROWSER"||Ug==="DENO")&&!jg});Qg.exports={CONSTRUCTOR:SL,REJECTION_EVENT:jg,SUBCLASSING:zl}});var or=g((VF,Gg)=>{"use strict";var Wg=ft(),yL=TypeError,TL=function(a){var e,t;this.promise=new a(function(i,r){if(e!==void 0||t!==void 0)throw new yL("Bad Promise constructor");e=i,t=r}),this.resolve=Wg(e),this.reject=Wg(t)};Gg.exports.f=function(a){return new TL(a)}});var hv=g(()=>{"use strict";var IL=pe(),EL=at(),Mn=wn(),Gt=oe(),xL=gi(),dr=He(),zg=rr(),Yg=Sl(),wL=ha(),AL=Yb(),PL=ft(),$n=ue(),RL=Me(),kL=Xb(),LL=Ll(),ev=Nl().set,Zl=_g(),$L=Fg(),ML=Rn(),DL=ql(),tv=nl(),Dn=Ei(),ec=nr(),iv=or(),Cn="Promise",rv=ec.CONSTRUCTOR,CL=ec.REJECTION_EVENT,BL=ec.SUBCLASSING,Yl=tv.getterFor(Cn),VL=tv.set,ur=Dn&&Dn.prototype,xi=Dn,kn=ur,av=Gt.TypeError,Kl=Gt.document,tc=Gt.process,Xl=iv.f,_L=Xl,OL=!!(Kl&&Kl.createEvent&&Gt.dispatchEvent),sv="unhandledrejection",FL="rejectionhandled",Kg=0,nv=1,NL=2,ic=1,ov=2,Ln,Xg,uv,Jg,lv=function(a){var e;return RL(a)&&$n(e=a.then)?e:!1},cv=function(a,e){var t=e.value,i=e.state===nv,r=i?a.ok:a.fail,s=a.resolve,n=a.reject,o=a.domain,u,l,c;try{r?(i||(e.rejection===ov&&UL(e),e.rejection=ic),r===!0?u=t:(o&&o.enter(),u=r(t),o&&(o.exit(),c=!0)),u===a.promise?n(new av("Promise-chain cycle")):(l=lv(u))?dr(l,u,s,n):s(u)):n(t)}catch(d){o&&!c&&o.exit(),n(d)}},dv=function(a,e){a.notified||(a.notified=!0,Zl(function(){for(var t=a.reactions,i;i=t.get();)cv(i,a);a.notified=!1,e&&!a.rejection&&qL(a)}))},pv=function(a,e,t){var i,r;OL?(i=Kl.createEvent("Event"),i.promise=e,i.reason=t,i.initEvent(a,!1,!0),Gt.dispatchEvent(i)):i={promise:e,reason:t},!CL&&(r=Gt["on"+a])?r(i):a===sv&&$L("Unhandled promise rejection",t)},qL=function(a){dr(ev,Gt,function(){var e=a.facade,t=a.value,i=Zg(a),r;if(i&&(r=ML(function(){Mn?tc.emit("unhandledRejection",t,e):pv(sv,e,t)}),a.rejection=Mn||Zg(a)?ov:ic,r.error))throw r.value})},Zg=function(a){return a.rejection!==ic&&!a.parent},UL=function(a){dr(ev,Gt,function(){var e=a.facade;Mn?tc.emit("rejectionHandled",e):pv(FL,e,a.value)})},lr=function(a,e,t){return function(i){a(e,i,t)}},cr=function(a,e,t){a.done||(a.done=!0,t&&(a=t),a.value=e,a.state=NL,dv(a,!0))},Jl=function(a,e,t){if(!a.done){a.done=!0,t&&(a=t);try{if(a.facade===e)throw new av("Promise can't be resolved itself");var i=lv(e);i?Zl(function(){var r={done:!1};try{dr(i,e,lr(Jl,r,a),lr(cr,r,a))}catch(s){cr(r,s,a)}}):(a.value=e,a.state=nv,dv(a,!1))}catch(r){cr({done:!1},r,a)}}};if(rv&&(xi=function(e){kL(this,kn),PL(e),dr(Ln,this);var t=Yl(this);try{e(lr(Jl,t),lr(cr,t))}catch(i){cr(t,i)}},kn=xi.prototype,Ln=function(e){VL(this,{type:Cn,done:!1,notified:!1,parent:!1,reactions:new DL,rejection:!1,state:Kg,value:null})},Ln.prototype=zg(kn,"then",function(e,t){var i=Yl(this),r=Xl(LL(this,xi));return i.parent=!0,r.ok=$n(e)?e:!0,r.fail=$n(t)&&t,r.domain=Mn?tc.domain:void 0,i.state===Kg?i.reactions.add(r):Zl(function(){cv(r,i)}),r.promise}),Xg=function(){var a=new Ln,e=Yl(a);this.promise=a,this.resolve=lr(Jl,e),this.reject=lr(cr,e)},iv.f=Xl=function(a){return a===xi||a===uv?new Xg(a):_L(a)},!EL&&$n(Dn)&&ur!==Object.prototype)){Jg=ur.then,BL||zg(ur,"then",function(e,t){var i=this;return new xi(function(r,s){dr(Jg,i,r,s)}).then(e,t)},{unsafe:!0});try{delete ur.constructor}catch(a){}Yg&&Yg(ur,kn)}IL({global:!0,constructor:!0,wrap:!0,forced:rv},{Promise:xi});uv=xL.Promise;wL(xi,Cn,!1,!0);AL(Cn)});var vv=g((FF,gv)=>{"use strict";var HL=ye(),mv=HL("iterator"),bv=!1;try{fv=0,rc={next:function(){return{done:!!fv++}},return:function(){bv=!0}},rc[mv]=function(){return this},Array.from(rc,function(){throw 2})}catch(a){}var fv,rc;gv.exports=function(a,e){try{if(!e&&!bv)return!1}catch(r){return!1}var t=!1;try{var i={};i[mv]=function(){return{next:function(){return{done:t=!0}}}},a(i)}catch(r){}return t}});var ac=g((NF,Sv)=>{"use strict";var jL=Ei(),QL=vv(),WL=nr().CONSTRUCTOR;Sv.exports=WL||!QL(function(a){jL.all(a).then(void 0,function(){})})});var yv=g(()=>{"use strict";var GL=pe(),zL=He(),YL=ft(),KL=or(),XL=Rn(),JL=In(),ZL=ac();GL({target:"Promise",stat:!0,forced:ZL},{all:function(e){var t=this,i=KL.f(t),r=i.resolve,s=i.reject,n=XL(function(){var o=YL(t.resolve),u=[],l=0,c=1;JL(e,function(d){var f=l++,p=!1;c++,zL(o,t,d).then(function(h){p||(p=!0,u[f]=h,--c||r(u))},s)}),--c||r(u)});return n.error&&s(n.value),i.promise}})});var Iv=g(()=>{"use strict";var e$=pe(),t$=at(),i$=nr().CONSTRUCTOR,nc=Ei(),r$=Pt(),a$=ue(),s$=rr(),Tv=nc&&nc.prototype;e$({target:"Promise",proto:!0,forced:i$,real:!0},{catch:function(a){return this.then(void 0,a)}});!t$&&a$(nc)&&(sc=r$("Promise").prototype.catch,Tv.catch!==sc&&s$(Tv,"catch",sc,{unsafe:!0}));var sc});var Ev=g(()=>{"use strict";var n$=pe(),o$=He(),u$=ft(),l$=or(),c$=Rn(),d$=In(),p$=ac();n$({target:"Promise",stat:!0,forced:p$},{race:function(e){var t=this,i=l$.f(t),r=i.reject,s=c$(function(){var n=u$(t.resolve);d$(e,function(o){o$(n,t,o).then(i.resolve,r)})});return s.error&&r(s.value),i.promise}})});var xv=g(()=>{"use strict";var h$=pe(),f$=or(),m$=nr().CONSTRUCTOR;h$({target:"Promise",stat:!0,forced:m$},{reject:function(e){var t=f$.f(this),i=t.reject;return i(e),t.promise}})});var oc=g((YF,wv)=>{"use strict";var b$=mt(),g$=Me(),v$=or();wv.exports=function(a,e){if(b$(a),g$(e)&&e.constructor===a)return e;var t=v$.f(a),i=t.resolve;return i(e),t.promise}});var Rv=g(()=>{"use strict";var S$=pe(),y$=Pt(),Av=at(),T$=Ei(),Pv=nr().CONSTRUCTOR,I$=oc(),E$=y$("Promise"),x$=Av&&!Pv;S$({target:"Promise",stat:!0,forced:Av||Pv},{resolve:function(e){return I$(x$&&this===E$?T$:this,e)}})});var kv=g(()=>{"use strict";hv();yv();Iv();Ev();xv();Rv()});var Dv=g(()=>{"use strict";var w$=pe(),A$=at(),Bn=Ei(),P$=he(),$v=Pt(),Mv=ue(),R$=Ll(),Lv=oc(),k$=rr(),lc=Bn&&Bn.prototype,L$=!!Bn&&P$(function(){lc.finally.call({then:function(){}},function(){})});w$({target:"Promise",proto:!0,real:!0,forced:L$},{finally:function(a){var e=R$(this,$v("Promise")),t=Mv(a);return this.then(t?function(i){return Lv(e,a()).then(function(){return i})}:a,t?function(i){return Lv(e,a()).then(function(){throw i})}:a)}});!A$&&Mv(Bn)&&(uc=$v("Promise").prototype.finally,lc.finally!==uc&&k$(lc,"finally",uc,{unsafe:!0}));var uc});var Bv=g((iN,Cv)=>{"use strict";Ub();kv();Dv();var $$=Wt();Cv.exports=$$("Promise","finally")});var _v=g((rN,Vv)=>{"use strict";var M$=Bv();Vv.exports=M$});var Vn=g((aN,Ov)=>{"use strict";var D$=_v();Ov.exports=D$});var rS=g(()=>{"use strict";var eM=pe(),tM=il().values;eM({target:"Object",stat:!0},{values:function(e){return tM(e)}})});var sS=g((Iq,aS)=>{"use strict";rS();var iM=gi();aS.exports=iM.Object.values});var oS=g((Eq,nS)=>{"use strict";var rM=sS();nS.exports=rM});var fr=g((xq,uS)=>{"use strict";var aM=oS();uS.exports=aM});var SS=g(()=>{"use strict";var yM=pe(),TM=Yi(),IM=tr(),EM=la(),xM=ca();yM({target:"Array",proto:!0},{at:function(e){var t=TM(this),i=IM(t),r=EM(e),s=r>=0?r:i+r;return s<0||s>=i?void 0:t[s]}});xM("at")});var TS=g((eU,yS)=>{"use strict";SS();var wM=Wt();yS.exports=wM("Array","at")});var ES=g((tU,IS)=>{"use strict";var AM=TS();IS.exports=AM});var ot=g((iU,xS)=>{"use strict";var PM=ES();xS.exports=PM});var Cc=g((G1,sy)=>{"use strict";var oD=mi();sy.exports=Array.isArray||function(e){return oD(e)==="Array"}});var oy=g((z1,ny)=>{"use strict";var uD=TypeError,lD=9007199254740991;ny.exports=function(a){if(a>lD)throw uD("Maximum allowed index exceeded");return a}});var cy=g((Y1,ly)=>{"use strict";var cD=Cc(),dD=tr(),pD=oy(),hD=Xi(),uy=function(a,e,t,i,r,s,n,o){for(var u=r,l=0,c=n?hD(n,o):!1,d,f;l<i;)l in t&&(d=c?c(t[l],l,e):t[l],s>0&&cD(d)?(f=dD(d),u=uy(a,e,d,f,u,s-1)-1):(pD(u+1),a[u]=d),u++),l++;return u};ly.exports=uy});var fy=g((K1,hy)=>{"use strict";var dy=Cc(),fD=kl(),mD=Me(),bD=ye(),gD=bD("species"),py=Array;hy.exports=function(a){var e;return dy(a)&&(e=a.constructor,fD(e)&&(e===py||dy(e.prototype))?e=void 0:mD(e)&&(e=e[gD],e===null&&(e=void 0))),e===void 0?py:e}});var by=g((X1,my)=>{"use strict";var vD=fy();my.exports=function(a,e){return new(vD(a))(e===0?0:e)}});var gy=g(()=>{"use strict";var SD=pe(),yD=cy(),TD=ft(),ID=Yi(),ED=tr(),xD=by();SD({target:"Array",proto:!0},{flatMap:function(e){var t=ID(this),i=ED(t),r;return TD(e),r=xD(t,0),r.length=yD(r,t,t,i,0,1,e,arguments.length>1?arguments[1]:void 0),r}})});var vy=g(()=>{"use strict";var wD=ca();wD("flatMap")});var yy=g((iH,Sy)=>{"use strict";gy();vy();var AD=Wt();Sy.exports=AD("Array","flatMap")});var Iy=g((rH,Ty)=>{"use strict";var PD=yy();Ty.exports=PD});var Oa=g((aH,Ey)=>{"use strict";var RD=Iy();Ey.exports=RD});var Fa=g((sH,xy)=>{"use strict";var kD=pa(),LD=String;xy.exports=function(a){if(kD(a)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return LD(a)}});var Bc=g((nH,wy)=>{"use strict";wy.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 Ry=g((oH,Py)=>{"use strict";var $D=fe(),MD=Qt(),DD=Fa(),_c=Bc(),Ay=$D("".replace),CD=RegExp("^["+_c+"]+"),BD=RegExp("(^|[^"+_c+"])["+_c+"]+$"),Vc=function(a){return function(e){var t=DD(MD(e));return a&1&&(t=Ay(t,CD,"")),a&2&&(t=Ay(t,BD,"$1")),t}};Py.exports={start:Vc(1),end:Vc(2),trim:Vc(3)}});var My=g((uH,$y)=>{"use strict";var VD=ll().PROPER,_D=he(),ky=Bc(),Ly="\u200B\x85\u180E";$y.exports=function(a){return _D(function(){return!!ky[a]()||Ly[a]()!==Ly||VD&&ky[a].name!==a})}});var Oc=g((lH,Dy)=>{"use strict";var OD=Ry().start,FD=My();Dy.exports=FD("trimStart")?function(){return OD(this)}:"".trimStart});var By=g(()=>{"use strict";var ND=pe(),Cy=Oc();ND({target:"String",proto:!0,name:"trimStart",forced:"".trimLeft!==Cy},{trimLeft:Cy})});var _y=g(()=>{"use strict";By();var qD=pe(),Vy=Oc();qD({target:"String",proto:!0,name:"trimStart",forced:"".trimStart!==Vy},{trimStart:Vy})});var Fy=g((fH,Oy)=>{"use strict";_y();var UD=Wt();Oy.exports=UD("String","trimLeft")});var qy=g((mH,Ny)=>{"use strict";var HD=Fy();Ny.exports=HD});var Hy=g((bH,Uy)=>{"use strict";var jD=qy();Uy.exports=jD});var sT=g(()=>{"use strict"});var nT=g(()=>{"use strict"});var uT=g((iW,oT)=>{"use strict";var fC=Me(),mC=mi(),bC=ye(),gC=bC("match");oT.exports=function(a){var e;return fC(a)&&((e=a[gC])!==void 0?!!e:mC(a)==="RegExp")}});var dT=g((rW,cT)=>{"use strict";var vC=oe(),SC=he(),lT=vC.RegExp,yC=!SC(function(){var a=!0;try{lT(".","d")}catch(u){a=!1}var e={},t="",i=a?"dgimsy":"gimsy",r=function(u,l){Object.defineProperty(e,u,{get:function(){return t+=l,!0}})},s={dotAll:"s",global:"g",ignoreCase:"i",multiline:"m",sticky:"y"};a&&(s.hasIndices="d");for(var n in s)r(n,s[n]);var o=Object.getOwnPropertyDescriptor(lT.prototype,"flags").get.call(e);return o!==i||t!==i});cT.exports={correct:yC}});var hT=g((aW,pT)=>{"use strict";var TC=mt();pT.exports=function(){var a=TC(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 bT=g((sW,mT)=>{"use strict";var IC=He(),EC=st(),xC=ra(),fT=dT(),wC=hT(),AC=RegExp.prototype;mT.exports=fT.correct?function(a){return a.flags}:function(a){return!fT.correct&&xC(AC,a)&&!EC(a,"flags")?IC(wC,a):a.flags}});var vT=g((nW,gT)=>{"use strict";var Hc=fe(),PC=Yi(),RC=Math.floor,qc=Hc("".charAt),kC=Hc("".replace),Uc=Hc("".slice),LC=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,$C=/\$([$&'`]|\d{1,2})/g;gT.exports=function(a,e,t,i,r,s){var n=t+a.length,o=i.length,u=$C;return r!==void 0&&(r=PC(r),u=LC),kC(s,u,function(l,c){var d;switch(qc(c,0)){case"$":return"$";case"&":return a;case"`":return Uc(e,0,t);case"'":return Uc(e,n);case"<":d=r[Uc(c,1,-1)];break;default:var f=+c;if(f===0)return l;if(f>o){var p=RC(f/10);return p===0?l:p<=o?i[p-1]===void 0?qc(c,1):i[p-1]+qc(c,1):l}d=i[f-1]}return d===void 0?"":d})}});var TT=g(()=>{"use strict";var MC=pe(),DC=He(),Qc=fe(),ST=Qt(),CC=ue(),BC=Me(),VC=uT(),Ar=Fa(),_C=sa(),OC=bT(),FC=vT(),NC=ye(),qC=at(),UC=NC("replace"),HC=TypeError,jc=Qc("".indexOf),jC=Qc("".replace),yT=Qc("".slice),QC=Math.max;MC({target:"String",proto:!0},{replaceAll:function(e,t){var i=ST(this),r,s,n,o,u,l,c,d,f,p,h=0,m="";if(BC(e)){if(r=VC(e),r&&(s=Ar(ST(OC(e))),!~jc(s,"g")))throw new HC("`.replaceAll` does not allow non-global regexes");if(n=_C(e,UC),n)return DC(n,e,i,t);if(qC&&r)return jC(Ar(i),e,t)}for(o=Ar(i),u=Ar(e),l=CC(t),l||(t=Ar(t)),c=u.length,d=QC(1,c),f=jc(o,u);f!==-1;)p=l?Ar(t(u,f,o)):FC(u,o,f,[],void 0,t),m+=yT(o,h,f)+p,h=f+c,f=f+d>o.length?-1:jc(o,u,f+d);return h<o.length&&(m+=yT(o,h)),m}})});var ET=g((lW,IT)=>{"use strict";sT();nT();TT();var WC=Wt();IT.exports=WC("String","replaceAll")});var wT=g((cW,xT)=>{"use strict";var GC=ET();xT.exports=GC});var PT=g((dW,AT)=>{"use strict";var zC=wT();AT.exports=zC});var kT=g((pW,RT)=>{"use strict";var YC=la(),KC=Fa(),XC=Qt(),JC=RangeError;RT.exports=function(e){var t=KC(XC(this)),i="",r=YC(e);if(r<0||r===1/0)throw new JC("Wrong number of repetitions");for(;r>0;(r>>>=1)&&(t+=t))r&1&&(i+=t);return i}});var CT=g((hW,DT)=>{"use strict";var MT=fe(),ZC=zu(),LT=Fa(),eB=kT(),tB=Qt(),iB=MT(eB),rB=MT("".slice),aB=Math.ceil,$T=function(a){return function(e,t,i){var r=LT(tB(e)),s=ZC(t),n=r.length,o=i===void 0?" ":LT(i),u,l;return s<=n||o===""?r:(u=s-n,l=iB(o,aB(u/o.length)),l.length>u&&(l=rB(l,0,u)),a?r+l:l+r)}};DT.exports={start:$T(!1),end:$T(!0)}});var VT=g((fW,BT)=>{"use strict";var sB=vi();BT.exports=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(sB)});var _T=g(()=>{"use strict";var nB=pe(),oB=CT().start,uB=VT();nB({target:"String",proto:!0,forced:uB},{padStart:function(e){return oB(this,e,arguments.length>1?arguments[1]:void 0)}})});var FT=g((gW,OT)=>{"use strict";_T();var lB=Wt();OT.exports=lB("String","padStart")});var qT=g((vW,NT)=>{"use strict";var cB=FT();NT.exports=cB});var HT=g((SW,UT)=>{"use strict";var dB=qT();UT.exports=dB});var Qp="2.0.138-dev.2ccb74c0.0";var $e=(r=>(r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused",r))($e||{}),At=(y=>(y.MPEG="MPEG",y.DASH="DASH",y.DASH_SEP="DASH_SEP",y.DASH_SEP_VK="DASH_SEP",y.DASH_WEBM="DASH_WEBM",y.DASH_WEBM_AV1="DASH_WEBM_AV1",y.DASH_STREAMS="DASH_STREAMS",y.DASH_WEBM_VK="DASH_WEBM",y.DASH_ONDEMAND="DASH_ONDEMAND",y.DASH_ONDEMAND_VK="DASH_ONDEMAND",y.DASH_LIVE="DASH_LIVE",y.DASH_LIVE_CMAF="DASH_LIVE_CMAF",y.DASH_LIVE_WEBM="DASH_LIVE_WEBM",y.HLS="HLS",y.HLS_ONDEMAND="HLS_ONDEMAND",y.HLS_JS="HLS",y.HLS_FMP4="HLS_FMP4",y.HLS_LIVE="HLS_LIVE",y.HLS_LIVE_CMAF="HLS_LIVE_CMAF",y.WEB_RTC_LIVE="WEB_RTC_LIVE",y))(At||{});var en=(r=>(r.NOT_AVAILABLE="NOT_AVAILABLE",r.AVAILABLE="AVAILABLE",r.CONNECTING="CONNECTING",r.CONNECTED="CONNECTED",r))(en||{}),gu=(i=>(i.HTTP1="http1",i.HTTP2="http2",i.QUIC="quic",i))(gu||{});var vu=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(vu||{}),tn=(i=>(i.TRAFFIC_SAVING="traffic_saving",i.HIGH_QUALITY="high_quality",i.UNKNOWN="unknown",i))(tn||{});var FE=O(Ae(),1);import{assertNever as jf,assertNonNullable as yA,isNonNullable as on,ValueSubject as Ku,Subject as TA,Subscription as IA,merge as EA,observableFrom as xA,fromEvent as Nf,map as qf,tap as Uf,filterChanged as wA,isNullable as Xu,ErrorCategory as Hf}from"@vkontakte/videoplayer-shared/es2018";var Ff=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 un=class{constructor(e){this.connection$=new Ku(void 0);this.castState$=new Ku("NOT_AVAILABLE");this.errorEvent$=new TA;this.realCastState$=new Ku("NOT_AVAILABLE");this.subscription=new IA;this.isDestroyed=!1;var s;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastInitializer");let t="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${t}`}),e.isDisabled||!t)return;let i=on((s=window.chrome)==null?void 0:s.cast),r=!!window.__onGCastApiAvailable;i?this.initializeCastApi():(window.__onGCastApiAvailable=n=>{delete window.__onGCastApiAvailable,n&&!this.isDestroyed&&this.initializeCastApi()},r||Ff("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:Hf.NETWORK,message:"Script loading failed!"})))}connect(){var e;(e=cast.framework.CastContext.getInstance())==null||e.requestSession()}disconnect(){var e,t;(t=(e=cast.framework.CastContext.getInstance())==null?void 0:e.getCurrentSession())==null||t.endSession(!0)}stopMedia(){return new Promise((e,t)=>{var i,r,s;(s=(r=(i=cast.framework.CastContext.getInstance())==null?void 0:i.getCurrentSession())==null?void 0:r.getMediaSession())==null||s.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){on(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();Xu(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();Xu(t)||e!==t.remotePlayer.isMuted&&t.remotePlayerController.muteOrUnmute()}destroy(){this.isDestroyed=!0,this.subscription.unsubscribe()}initListeners(){let e=new cast.framework.RemotePlayer,t=new cast.framework.RemotePlayerController(e),i=cast.framework.CastContext.getInstance();this.subscription.add(Nf(i,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(r=>{var s,n,o;switch(r.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=(o=(n=(s=i.getCurrentSession())==null?void 0:s.getMediaSession())==null?void 0:n.media)==null?void 0:o.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return jf(r.sessionState)}})).add(EA(Nf(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(Uf(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),qf(r=>r.castState)),xA([i.getCastState()])).pipe(wA(),qf(AA),Uf(r=>{this.log({message:`realCastState$: ${r}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{var o,u;let s=r==="CONNECTED",n=on(this.connection$.getValue());if(s&&!n){let l=i.getCurrentSession();yA(l);let c=l.getCastDevice(),d=(u=(o=l.getMediaSession())==null?void 0:o.media)==null?void 0:u.contentId;(Xu(d)||d===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:l,castDevice:c}))}else!s&&n&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(r==="CONNECTED"?on(this.connection$.getValue())?"CONNECTED":"AVAILABLE":r)}))}initializeCastApi(){var r;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(s){return}try{e.setOptions({receiverApplicationId:(r=this.params.receiverApplicationId)!=null?r:t,autoJoinPolicy:i}),this.initListeners()}catch(s){this.errorEvent$.next({id:"ChromecastInitializer",category:Hf.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:s})}}},AA=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 jf(a)}};var Jd=O(Ae(),1),yE=O(ir(),1),TE=O(xl(),1);var eS=O(Vn(),1);import{assertNever as Fv}from"@vkontakte/videoplayer-shared/es2018";var le=(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:Fv(t)}return a},zt=(a,e)=>{var t;switch(e){case 0:return NaN;case 1:{let i=new URL(a);return Number(i.searchParams.get("playback_shift"))}case 2:{let i=new URL(a);return Number((t=i.searchParams.get("offset_p"))!=null?t:0)}default:Fv(e)}};var L=(a,e,t=!1)=>{let i=a.getTransition();(t||!i||i.to===e)&&a.setState(e)};import{isNonNullable as C$,Subject as _n,merge as Nv}from"@vkontakte/videoplayer-shared/es2018";var H=class{constructor(e){this.transitionStarted$=new _n;this.transitionEnded$=new _n;this.transitionUpdated$=new _n;this.forceChanged$=new _n;this.stateChangeStarted$=Nv(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=Nv(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||C$(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 Gv}from"@vkontakte/videoplayer-shared/es2018";var On=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 qv=O(Ae(),1);var Ea=()=>{var a,e;return/Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test((a=navigator.appVersion)!=null?a:navigator.userAgent)||((e=navigator==null?void 0:navigator.userAgentData)==null?void 0:e.mobile)};var Fn=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,qv.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=Ea()}catch(t){console.error(t)}this.detectDevice(e),this.detectHighEntropyValues(),this.isIOS&&this.detectIOSVersion()}async detectHighEntropyValues(){let{userAgentData:e}=navigator;if(e!=null&&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 Nn=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(){var t;let{maxTouchPoints:e}=navigator;try{this._maxTouchPoints=e!=null?e:0,this._isHdr=!!((t=matchMedia("(dynamic-range: high)"))!=null&&t.matches),this._colorDepth=screen.colorDepth}catch(i){console.error(i)}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(i){console.error(i)}}};var Qe=()=>window.ManagedMediaSource||window.MediaSource,pr=()=>{var a,e;return!!(window.ManagedMediaSource&&((e=(a=window.ManagedSourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},Uv=()=>{var a,e;return!!(window.MediaSource&&((e=(a=window.SourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},qn=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;var B$=document.createElement("video"),V$='video/mp4; codecs="avc1.42000a,mp4a.40.2"',_$='video/mp4; codecs="hev1.1.6.L93.B0"',Hv='video/webm; codecs="vp09.00.10.08"',jv='video/webm; codecs="av01.0.00M.08"',O$='audio/mp4; codecs="mp4a.40.2"',F$='audio/webm; codecs="opus"',Qv,N$=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:jv}}),window.navigator.mediaCapabilities.decodingInfo({...a,video:{...a.video,contentType:Hv}})]);Qv={DASH_WEBM_AV1:e,DASH_WEBM:t}};N$().catch(a=>{console.log(B$),console.error(a)});var Un=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 Qv}get supportedCodecs(){return Object.keys(this._codecs).filter(e=>this._codecs[e])}get nativeHlsSupported(){return this._nativeHlsSupported}detect(){var e,t,i,r,s,n,o,u,l,c,d,f,p,h,m,v,b,S,T,y;this._video=document.createElement("video");try{this._protocols={mms:pr(),mse:Uv(),hls:!!((t=(e=this._video).canPlayType)!=null&&t.call(e,"application/x-mpegurl")||(r=(i=this._video).canPlayType)!=null&&r.call(i,"vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},this._containers={mp4:!!((n=(s=this._video).canPlayType)!=null&&n.call(s,"video/mp4")),webm:!!((u=(o=this._video).canPlayType)!=null&&u.call(o,"video/webm")),cmaf:!0};let E=!!((c=(l=Qe())==null?void 0:l.isTypeSupported)!=null&&c.call(l,V$)),k=!!((f=(d=Qe())==null?void 0:d.isTypeSupported)!=null&&f.call(d,_$)),M=!!((h=(p=Qe())==null?void 0:p.isTypeSupported)!=null&&h.call(p,O$));this._codecs={h264:E,h265:k,vp9:!!((v=(m=Qe())==null?void 0:m.isTypeSupported)!=null&&v.call(m,Hv)),av1:!!((S=(b=Qe())==null?void 0:b.isTypeSupported)!=null&&S.call(b,jv)),aac:M,opus:!!((y=(T=Qe())==null?void 0:T.isTypeSupported)!=null&&y.call(T,F$)),mpeg:(E||k)&&M},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(){var t;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);(t=this._video.parentNode)==null||t.replaceChild(e,this._video),this._video=null}};var Wv="audio/mpeg",Hn=class{supportMp3(){return this._codecs.mp3&&this._containers.mpeg}detect(){var e,t,i,r;this._audio=document.createElement("audio");try{this._containers={mpeg:!!((t=(e=this._audio).canPlayType)!=null&&t.call(e,Wv))},this._codecs={mp3:!!((r=(i=Qe())==null?void 0:i.isTypeSupported)!=null&&r.call(i,Wv))}}catch(s){console.error(s)}try{this.destroyAudioElement()}catch(s){console.error("Error destroying audio element:",s)}}destroyAudioElement(){var t;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);(t=this._audio.parentNode)==null||t.replaceChild(e,this._audio),this._audio=null}};import{ValueSubject as q$}from"@vkontakte/videoplayer-shared/es2018";var cc=class{constructor(){this.isInited$=new q$(!1);this._displayChecker=new Nn,this._deviceChecker=new Fn(this._displayChecker),this._browserChecker=new On,this._videoChecker=new Un(this._deviceChecker,this._browserChecker),this._audioChecker=new Hn,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)}},F=new cc;var dc=a=>{let{containers:e,protocols:t,codecs:i,nativeHlsSupported:r}=F.video,s=(i.h264||i.h265)&&i.aac,n=t.mse||t.mms;return a.filter(o=>{switch(o){case"DASH_SEP":return n&&e.mp4&&s;case"DASH_WEBM":return n&&e.webm&&i.vp9&&i.opus;case"DASH_WEBM_AV1":return n&&e.webm&&i.av1&&i.opus;case"DASH_STREAMS":return n&&(e.mp4&&s||e.webm&&(i.vp9||i.av1)&&(i.opus||i.aac));case"DASH_LIVE":return n&&e.mp4&&s;case"DASH_LIVE_CMAF":return n&&e.mp4&&s&&e.cmaf;case"DASH_ONDEMAND":return n&&e.mp4&&s;case"HLS":case"HLS_ONDEMAND":case"HLS_FMP4":case"HLS_LIVE":case"HLS_LIVE_CMAF":return r;case"MPEG":return e.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return t.webrtc&&t.ws&&i.h264&&(e.mp4||e.webm);default:return Gv(o)}})},pc=a=>{switch(a){case"MPEG":case"DASH":case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":case"HLS":case"HLS_FMP4":case"HLS_ONDEMAND":return!1;case"DASH_LIVE":case"DASH_LIVE_CMAF":case"HLS_LIVE":case"HLS_LIVE_CMAF":case"DASH_LIVE_WEBM":case"WEB_RTC_LIVE":return!0;default:return Gv(a)}},U$=a=>{let t=Object.keys(a).filter(i=>!pc(i));return dc(t).length>0};import{assertNever as hr,assertNonNullable as wi,debounce as zv,ErrorCategory as Yv,fromEvent as Ai,isNonNullable as Kv,map as Xv,merge as Jv,observableFrom as H$,Subject as j$,Subscription as hc,timeout as Q$,getHighestQuality as W$}from"@vkontakte/videoplayer-shared/es2018";var G$=5,z$=5,Y$=500,Zv=7e3,xa=class{constructor(e){this.subscription=new hc;this.loadMediaTimeoutSubscription=new hc;this.videoState=new H("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==null?void 0: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:hr(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:hr(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:hr(e)}break}default:hr(i)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(pc(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 hc;this.subscription.add(e),this.subscription.add(Jv(this.videoState.stateChangeStarted$.pipe(Xv(r=>`stateChangeStarted$ ${JSON.stringify(r)}`)),this.videoState.stateChangeEnded$.pipe(Xv(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 j$;e.add(r.pipe(zv(Y$)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add(Ai(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)>G$)&&r.next(o),s=o})),e.add(Ai(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(Ai(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(Ai(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemotePause():this.handleRemotePlay()}),t(Ai(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<z$&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),L(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:hr(n)}}),t(Ai(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t(Ai(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({muted:r.value})});let i=Jv(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,H$(["init"])).pipe(zv(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"),L(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),L(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(),t=this.videoState.getTransition();((t==null?void 0:t.to)==="paused"||e==="playing")&&(this.videoState.setState("paused"),L(this.params.desiredState.playbackState,"paused"))}handleRemotePlay(){let e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)==="playing"||e==="paused")&&(this.videoState.setState("playing"),L(this.params.desiredState.playbackState,"playing"))}handleRemoteReady(){var t;let e=this.videoState.getTransition();(e==null?void 0:e.to)==="ready"&&this.videoState.setState("ready"),((t=this.params.desiredState.playbackState.getTransition())==null?void 0:t.to)==="ready"&&L(this.params.desiredState.playbackState,"ready")}handleRemoteStop(){this.videoState.getState()!=="stopped"&&this.videoState.setState("stopped")}handleRemoteVolumeChange(e){var r,s;let t=this.params.output.volume$.getValue(),i={volume:(r=e.volume)!=null?r:t.volume,muted:(s=e.muted)!=null?s: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){var l;let t=this.params.source,i,r,s;switch(e){case"MPEG":{let c=t[e];wi(c);let d=W$(Object.keys(c));wi(d);let f=c[d];wi(f),i=f,r="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_FMP4":case"HLS_ONDEMAND":{let c=t[e];wi(c),i=c.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 c=t[e];wi(c),i=c.url,r="application/dash+xml",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let c=t[e];wi(c),i=c.url,r="application/dash+xml",s=chrome.cast.media.StreamType.LIVE;break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let c=t[e];wi(c),i=le(c.url),r="application/x-mpegurl",s=chrome.cast.media.StreamType.LIVE;break}case"DASH_LIVE":case"WEB_RTC_LIVE":{let c="Unsupported format for Chromecast",d=new Error(c);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:Yv.VIDEO_PIPELINE,message:c,thrown:d}),d}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return hr(e)}let n=new chrome.cast.media.MediaInfo((l=this.params.meta.videoId)!=null?l:i,r);n.contentUrl=i,n.streamType=s,n.metadata=new chrome.cast.media.GenericMediaMetadata;let{title:o,subtitle:u}=this.params.meta;return Kv(o)&&(n.metadata.title=o),Kv(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(Q$(Zv).subscribe(()=>s(`timeout(${Zv})`)))});(0,eS.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:Yv.VIDEO_PIPELINE,message:s,thrown:r})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var Mc=O(Ae(),1);import{clearVideoElement as iS}from"@vkontakte/videoplayer-shared/es2018";import{clearVideoElement as K$}from"@vkontakte/videoplayer-shared/es2018";var tS=a=>{try{a.pause(),a.playbackRate=0,K$(a),a.remove()}catch(e){console.error(e)}};import{fromEvent as X$,Subscription as J$}from"@vkontakte/videoplayer-shared/es2018";var fc=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)}},mc=window.WeakMap?new WeakMap:new fc,bc=window.WeakMap?new WeakMap:new Map,Z$=(a,e=20)=>{let t=0;return X$(a,"ratechange").subscribe(i=>{t++,t>=e&&(a.currentTime=a.currentTime,t=0)})},De=(a,{audioVideoSyncRate:e,disableYandexPiP:t})=>{let i=a.querySelector("video"),r=!!i;i?iS(i):(i=document.createElement("video"),a.appendChild(i)),mc.set(i,r);let s=new J$;return s.add(Z$(i,e)),bc.set(i,s),i.setAttribute("crossorigin","anonymous"),i.setAttribute("playsinline","playsinline"),t&&i.setAttribute("x-yandex-pip","false"),i.controls=!1,i.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),i},Ce=a=>{let e=bc.get(a);e==null||e.unsubscribe(),bc.delete(a);let t=mc.get(a);mc.delete(a),t?iS(a):tS(a)};var vc=O(fr(),1);import{assertNonNullable as Aa,isNonNullable as gt,isNullable as oM,fromEvent as mr,merge as lS,observableFrom as cS,filterChanged as dS,map as Pa,Subject as pS,Subscription as uM,ValueSubject as lM,ErrorCategory as cM}from"@vkontakte/videoplayer-shared/es2018";import{isNonNullable as gc,isNullable as sM,Subscription as nM}from"@vkontakte/videoplayer-shared/es2018";var jn=(a,e,t,{equal:i=(n,o)=>n===o,changed$:r,onError:s}={})=>{let n=a.getState(),o=e(),u=sM(r),l=new nM;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},bt=(a,e,t)=>jn(e,()=>a.loop,i=>{gc(i)&&(a.loop=i)},{onError:t}),Be=(a,e,t,i)=>jn(e,()=>({muted:a.muted,volume:a.volume}),r=>{gc(r)&&(a.muted=r.muted,a.volume=r.volume)},{equal:(r,s)=>r===s||(r==null?void 0:r.muted)===(s==null?void 0:s.muted)&&(r==null?void 0:r.volume)===(s==null?void 0:s.volume),changed$:t,onError:i}),Ke=(a,e,t,i)=>jn(e,()=>a.playbackRate,r=>{gc(r)&&(a.playbackRate=r)},{changed$:t,onError:i}),wa=jn;var dM=a=>["__",a.language,a.label].join("|"),pM=(a,e)=>{if(a.id===e)return!0;let[t,i,r]=e.split("|");return a.language===i&&a.label===r},Sc=class a{constructor(e){this.available$=new pS;this.current$=new lM(void 0);this.error$=new pS;this.subscription=new uM;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:cM.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(wa(t.internalTextTracks,()=>(0,vc.default)(this.internalTracks),s=>{gt(s)&&this.setInternal(s)},{equal:(s,n)=>gt(s)&&gt(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(Pa(s=>s.filter(({type:n})=>n==="internal"))),onError:r})),this.subscription.add(wa(t.externalTextTracks,()=>(0,vc.default)(this.externalTracks),s=>{gt(s)&&this.setExternal(s)},{equal:(s,n)=>gt(s)&&gt(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(Pa(s=>s.filter(({type:n})=>n==="external"))),onError:r})),this.subscription.add(wa(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(wa(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.activeCues)}))}subscribe(){Aa(this.video);let{textTracks:e}=this.video;this.subscription.add(mr(e,"addtrack").subscribe(()=>{let i=this.current$.getValue();i&&this.select(i)})),this.subscription.add(lS(mr(e,"addtrack"),mr(e,"removetrack"),cS(["init"])).pipe(Pa(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),dS((i,r)=>i.length===r.length&&i.every(({id:s},n)=>s===r[n].id))).subscribe(this.available$)),this.subscription.add(lS(mr(e,"change"),cS(["init"])).pipe(Pa(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),Pa(i=>i&&this.htmlTextTrackToITextTrack(i).id),dS()).subscribe(this.current$));let t=i=>{var r,s;return this.applyCueSettings((s=(r=i.target)==null?void 0:r.activeCues)!=null?s:null)};this.subscription.add(mr(e,"addtrack").subscribe(i=>{var s,n;(s=i.track)==null||s.addEventListener("cuechange",t);let r=o=>{var l,c,d,f,p;let u=(c=(l=o.target)==null?void 0:l.cues)!=null?c:null;u&&u.length&&(this.applyCueSettings((f=(d=o.target)==null?void 0:d.cues)!=null?f:null),(p=o.target)==null||p.removeEventListener("cuechange",r))};(n=i.track)==null||n.addEventListener("cuechange",r)})),this.subscription.add(mr(e,"removetrack").subscribe(i=>{var r;(r=i.track)==null||r.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;gt(t.align)&&(r.align=t.align),gt(t.position)&&(r.position=t.position),gt(t.size)&&(r.size=t.size),gt(t.line)&&(r.line=t.line)}}htmlTextTracksAsArray(e=!1){Aa(this.video);let t=[...this.video.textTracks];return e?t:t.filter(a.isHealthyTrack)}htmlTextTrackToITextTrack(e){var o,u,l,c,d;let{language:t,label:i}=e,r=e.id?e.id:dM(e),s=this.externalTracks.has(r),n=(l=s?(o=this.externalTracks.get(r))==null?void 0:o.isAuto:(u=this.internalTracks.get(r))==null?void 0:u.isAuto)!=null?l:r.includes("auto");return s?{id:r,type:"external",isAuto:n,language:t,label:i,url:(c=this.externalTracks.get(r))==null?void 0:c.url}:{id:r,type:"internal",isAuto:n,language:t,label:i,url:(d=this.internalTracks.get(r))==null?void 0:d.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){Aa(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(oM(e)||!pM(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){Aa(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){Aa(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)}},Xe=Sc;var Pi=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 hS=a=>{let e=a;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e==null?void 0:e.parentNode;return e!=null?e:void 0},yc=a=>{let e=hS(a);return!!(e&&e.fullscreenElement&&e.fullscreenElement===a)},fS=a=>{let e=hS(a);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===a)};import{fromEvent as Pe,map as vt,merge as Qn,filterChanged as bS,isNonNullable as gS,Subject as fM,filter as Tc,mapTo as Ic,combine as mM,once as bM,shareReplay as Re,throttle as gM,ErrorCategory as vM,ValueSubject as vS,Subscription as SM}from"@vkontakte/videoplayer-shared/es2018";var hM=3,mS=(a,e,t=hM)=>{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 Ve=a=>{let e=P=>Pe(a,P).pipe(Ic(void 0),Re(1)),t=new SM,i=()=>t.unsubscribe(),r=Qn(Pe(a,"progress"),Pe(a,"timeupdate")).pipe(vt(()=>mS(a.buffered,a.currentTime)),Re(1)),s=F.browser.isSafari?mM({play:e("play").pipe(bM()),playing:e("playing")}).pipe(Ic(void 0),Re(1)):e("playing"),n=Pe(a,"volumechange").pipe(vt(()=>({muted:a.muted,volume:a.volume})),Re(1)),o=Pe(a,"ratechange").pipe(vt(()=>a.playbackRate),Re(1)),u=Pe(a,"error").pipe(Tc(()=>!!(a.error||a.played.length)),vt(()=>{var V;let P=a.error;return{id:P?`MediaError#${P.code}`:"HtmlVideoError",category:vM.VIDEO_PIPELINE,message:P?P.message:"Error event from HTML video element",thrown:(V=a.error)!=null?V:void 0}}),Re(1)),l=Pe(a,"timeupdate").pipe(vt(()=>a.currentTime),Re(1)),c=["waiting","seeking","seeked","timeupdate"],d=new fM,f=.3,p;t.add(Qn(...c.map(P=>Pe(a,P))).subscribe(P=>{let V=a.currentTime;a.loop&&gS(p)&&gS(V)&&p>=a.duration-f&&V<=f&&d.next(p),p=V}));let h=e("pause").pipe(Tc(()=>!a.error&&p!==a.duration),Re(1)),m=Pe(a,"enterpictureinpicture").pipe(Re(1)),v=Pe(a,"leavepictureinpicture").pipe(Re(1)),b=new vS(fS(a));t.add(m.subscribe(()=>b.next(!0))),t.add(v.subscribe(()=>b.next(!1)));let S=new vS(yc(a)),T=Pe(a,"fullscreenchange").pipe(Re(1));t.add(T.pipe(vt(()=>yc(a))).subscribe(S));let y=.1,E=1e3,k=Pe(a,"timeupdate").pipe(vt(P=>a.duration-a.currentTime<y),bS(),Re(1)),M=Qn(k.pipe(Tc(P=>!a.loop&&P)),Pe(a,"ended")).pipe(gM(E),Ic(void 0),Re(1)),A=Qn(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(P=>Pe(a,P)),k.pipe(vt(P=>({type:P?"ended":"unknown"})))).pipe(vt(P=>F.browser.isFirefox&&P.type==="ended"?a.readyState<2:a.readyState<3),bS(),Re(1));return{playing$:s,pause$:h,canplay$:e("canplay"),ended$:M,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$:Pe(a,"durationchange").pipe(vt(()=>a.duration),Re(1)),isBuffering$:A,currentBuffer$:r,volumeState$:n,playbackRateState$:o,inPiP$:b,inFullscreen$:S,enterPip$:m,leavePip$:v,destroy:i}};import{VideoQuality as Yt}from"@vkontakte/videoplayer-shared/es2018";var Kt=a=>{switch(a){case"mobile":return Yt.Q_144P;case"lowest":return Yt.Q_240P;case"low":return Yt.Q_360P;case"sd":case"medium":return Yt.Q_480P;case"hd":case"high":return Yt.Q_720P;case"fullhd":case"full":return Yt.Q_1080P;case"quadhd":case"quad":return Yt.Q_1440P;case"ultrahd":case"ultra":return Yt.Q_2160P}};var Le=O(ot(),1),wc=O(Ae(),1),Ri=O(ir(),1);import{isNonNullable as X,isNullable as Kn,now as CS,isHigher as Xn,isHigherOrEqual as gr,isInvariantQuality as Jn,isLowerOrEqual as vr,videoSizeToQuality as BS,assertNotEmptyArray as Zn,assertNonNullable as VS}from"@vkontakte/videoplayer-shared/es2018";var Ec=!1,Lt={},wS=a=>{Ec=a},AS=()=>{Lt={}},PS=a=>{a(Lt)},Ra=(a,e)=>{var t;Ec&&(Lt.meta=(t=Lt.meta)!=null?t:{},Lt.meta[a]=e)},ke=class{constructor(e){this.name=e}next(e){var i,r;if(!Ec)return;Lt.series=(i=Lt.series)!=null?i:{};let t=(r=Lt.series[this.name])!=null?r:[];t.push([Date.now(),e]),Lt.series[this.name]=t}};import{isHigher as RM,isHigherOrEqual as uU,isLower as RS,isLowerOrEqual as lU,isNonNullable as Wn,isNullable as kM,videoHeightToQuality as Gn}from"@vkontakte/videoplayer-shared/es2018";function xc(a,e,t){return!a.max&&a.min===e?"high_quality":!a.min&&a.max===t?"traffic_saving":"unknown"}function zn(a,e,t){return!!a&&xc(a,e,t)==="high_quality"}function br(a,e,t){return kM(a)||Wn(a.min)&&Wn(a.max)&&RS(a.max,a.min)||Wn(a.min)&&e&&RM(a.min,e)||Wn(a.max)&&t&&RS(a.max,t)}function kS({limits:a,highestAvailableHeight:e,lowestAvailableHeight:t}){return br({max:a!=null&&a.max?Gn(a.max):void 0,min:a!=null&&a.min?Gn(a.min):void 0},e?Gn(e):void 0,t?Gn(t):void 0)}var _S=new ke("best_bitrate"),eo=(a,e,t)=>(e-t)*Math.pow(2,-10*a)+t;var Sr=a=>(e,t)=>a*(Number(e.bitrate)-Number(t.bitrate)),Xt=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=CS()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},to='Assertion "ABR Tracks is empty array" failed',Yn=new WeakMap,LS=new WeakMap,$S=new WeakMap,ka=(a,e,t,i)=>{var u;let r=[...e].sort(Sr(1)),s=[...t].sort(Sr(1)),n=s.filter(l=>X(l.bitrate)&&X(a.bitrate)?a.bitrate/l.bitrate>i:!0),o=(u=(0,Le.default)(s,Math.round(s.length*r.indexOf(a)/(r.length+1))))!=null?u:(0,Le.default)(s,-1);return o&&(0,wc.default)(n,o)?o:n.length?(0,Le.default)(n,-1):(0,Le.default)(s,0)},La=(a,e,t,i)=>{var u;let r=Yn.get(e);r||(r=[...e].sort(Sr(1)),Yn.set(e,r));let s=Yn.get(t);s||(s=[...t].sort(Sr(1)),Yn.set(t,s));let n=$S.get(a);n||(n=s.filter(l=>X(l.bitrate)&&X(a.bitrate)?a.bitrate/l.bitrate>i:!0),$S.set(a,n));let o=(u=(0,Le.default)(s,Math.round(s.length*r.indexOf(a)/(r.length+1))))!=null?u:(0,Le.default)(s,-1);return o&&(0,wc.default)(n,o)?o:n.length?(0,Le.default)(n,-1):(0,Le.default)(s,0)},MS=a=>"quality"in a,io=(a,e,t,i)=>{var n;let r=X((n=i==null?void 0:i.last)==null?void 0:n.bitrate)&&X(t==null?void 0:t.bitrate)&&i.last.bitrate<t.bitrate?a.trackCooldownIncreaseQuality:a.trackCooldownDecreaseQuality,s=t&&i&&i.history[t.id]&&CS()-i.history[t.id]<=r&&(!i.last||t.id!==i.last.id);if(t!=null&&t.id&&i&&!s&&i.recordSelection(t),s&&(i!=null&&i.last)){let o=i.last;i==null||i.recordSwitch(o);let u=MS(o)?"video":"audio",l=MS(o)?o.quality:o.bitrate;return e({message:`
6
+ var WE=Object.create;var Gp=Object.defineProperty;var zE=Object.getOwnPropertyDescriptor;var YE=Object.getOwnPropertyNames;var KE=Object.getPrototypeOf,XE=Object.prototype.hasOwnProperty;var g=(a,e)=>()=>(e||a((e={exports:{}}).exports,e),e.exports);var JE=(a,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of YE(e))!XE.call(a,r)&&r!==t&&Gp(a,r,{get:()=>e[r],enumerable:!(i=zE(e,r))||i.enumerable});return a};var O=(a,e,t)=>(t=a!=null?WE(KE(a)):{},JE(e||!a||!a.__esModule?Gp(t,"default",{value:a,enumerable:!0}):t,a));var oe=g((wu,zp)=>{"use strict";var Zr=function(a){return a&&a.Math===Math&&a};zp.exports=Zr(typeof globalThis=="object"&&globalThis)||Zr(typeof window=="object"&&window)||Zr(typeof self=="object"&&self)||Zr(typeof global=="object"&&global)||Zr(typeof wu=="object"&&wu)||function(){return this}()||Function("return this")()});var me=g((a_,Yp)=>{"use strict";Yp.exports=function(a){try{return!!a()}catch(e){return!0}}});var ea=g((s_,Kp)=>{"use strict";var ZE=me();Kp.exports=!ZE(function(){var a=function(){}.bind();return typeof a!="function"||a.hasOwnProperty("prototype")})});var Au=g((n_,eh)=>{"use strict";var ex=ea(),Zp=Function.prototype,Xp=Zp.apply,Jp=Zp.call;eh.exports=typeof Reflect=="object"&&Reflect.apply||(ex?Jp.bind(Xp):function(){return Jp.apply(Xp,arguments)})});var be=g((o_,rh)=>{"use strict";var th=ea(),ih=Function.prototype,Ru=ih.call,tx=th&&ih.bind.bind(Ru,Ru);rh.exports=th?tx:function(a){return function(){return Ru.apply(a,arguments)}}});var gi=g((u_,sh)=>{"use strict";var ah=be(),ix=ah({}.toString),rx=ah("".slice);sh.exports=function(a){return rx(ix(a),8,-1)}});var Pu=g((l_,nh)=>{"use strict";var ax=gi(),sx=be();nh.exports=function(a){if(ax(a)==="Function")return sx(a)}});var ue=g((c_,oh)=>{"use strict";var ku=typeof document=="object"&&document.all;oh.exports=typeof ku=="undefined"&&ku!==void 0?function(a){return typeof a=="function"||a===ku}:function(a){return typeof a=="function"}});var Ue=g((d_,uh)=>{"use strict";var nx=me();uh.exports=!nx(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var je=g((p_,lh)=>{"use strict";var ox=ea(),dn=Function.prototype.call;lh.exports=ox?dn.bind(dn):function(){return dn.apply(dn,arguments)}});var Lu=g(ph=>{"use strict";var ch={}.propertyIsEnumerable,dh=Object.getOwnPropertyDescriptor,ux=dh&&!ch.call({1:2},1);ph.f=ux?function(e){var t=dh(this,e);return!!t&&t.enumerable}:ch});var ta=g((f_,hh)=>{"use strict";hh.exports=function(a,e){return{enumerable:!(a&1),configurable:!(a&2),writable:!(a&4),value:e}}});var mh=g((m_,fh)=>{"use strict";var lx=be(),cx=me(),dx=gi(),$u=Object,px=lx("".split);fh.exports=cx(function(){return!$u("z").propertyIsEnumerable(0)})?function(a){return dx(a)==="String"?px(a,""):$u(a)}:$u});var ia=g((b_,bh)=>{"use strict";bh.exports=function(a){return a==null}});var Qt=g((g_,gh)=>{"use strict";var hx=ia(),fx=TypeError;gh.exports=function(a){if(hx(a))throw new fx("Can't call method on "+a);return a}});var Si=g((S_,Sh)=>{"use strict";var mx=mh(),bx=Qt();Sh.exports=function(a){return mx(bx(a))}});var Ce=g((v_,vh)=>{"use strict";var gx=ue();vh.exports=function(a){return typeof a=="object"?a!==null:gx(a)}});var vi=g((y_,yh)=>{"use strict";yh.exports={}});var Rt=g((T_,Ih)=>{"use strict";var Mu=vi(),Du=oe(),Sx=ue(),Th=function(a){return Sx(a)?a:void 0};Ih.exports=function(a,e){return arguments.length<2?Th(Mu[a])||Th(Du[a]):Mu[a]&&Mu[a][e]||Du[a]&&Du[a][e]}});var ra=g((I_,Eh)=>{"use strict";var vx=be();Eh.exports=vx({}.isPrototypeOf)});var yi=g((E_,Ah)=>{"use strict";var yx=oe(),xh=yx.navigator,wh=xh&&xh.userAgent;Ah.exports=wh?String(wh):""});var Bu=g((x_,Mh)=>{"use strict";var $h=oe(),Cu=yi(),Rh=$h.process,Ph=$h.Deno,kh=Rh&&Rh.versions||Ph&&Ph.version,Lh=kh&&kh.v8,rt,pn;Lh&&(rt=Lh.split("."),pn=rt[0]>0&&rt[0]<4?1:+(rt[0]+rt[1]));!pn&&Cu&&(rt=Cu.match(/Edge\/(\d+)/),(!rt||rt[1]>=74)&&(rt=Cu.match(/Chrome\/(\d+)/),rt&&(pn=+rt[1])));Mh.exports=pn});var Vu=g((w_,Ch)=>{"use strict";var Dh=Bu(),Tx=me(),Ix=oe(),Ex=Ix.String;Ch.exports=!!Object.getOwnPropertySymbols&&!Tx(function(){var a=Symbol("symbol detection");return!Ex(a)||!(Object(a)instanceof Symbol)||!Symbol.sham&&Dh&&Dh<41})});var _u=g((A_,Bh)=>{"use strict";var xx=Vu();Bh.exports=xx&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var Ou=g((R_,Vh)=>{"use strict";var wx=Rt(),Ax=ue(),Rx=ra(),Px=_u(),kx=Object;Vh.exports=Px?function(a){return typeof a=="symbol"}:function(a){var e=wx("Symbol");return Ax(e)&&Rx(e.prototype,kx(a))}});var aa=g((P_,_h)=>{"use strict";var Lx=String;_h.exports=function(a){try{return Lx(a)}catch(e){return"Object"}}});var ft=g((k_,Oh)=>{"use strict";var $x=ue(),Mx=aa(),Dx=TypeError;Oh.exports=function(a){if($x(a))return a;throw new Dx(Mx(a)+" is not a function")}});var sa=g((L_,Fh)=>{"use strict";var Cx=ft(),Bx=ia();Fh.exports=function(a,e){var t=a[e];return Bx(t)?void 0:Cx(t)}});var qh=g(($_,Nh)=>{"use strict";var Fu=je(),Nu=ue(),qu=Ce(),Vx=TypeError;Nh.exports=function(a,e){var t,i;if(e==="string"&&Nu(t=a.toString)&&!qu(i=Fu(t,a))||Nu(t=a.valueOf)&&!qu(i=Fu(t,a))||e!=="string"&&Nu(t=a.toString)&&!qu(i=Fu(t,a)))return i;throw new Vx("Can't convert object to primitive value")}});var at=g((M_,Uh)=>{"use strict";Uh.exports=!0});var Qh=g((D_,Hh)=>{"use strict";var jh=oe(),_x=Object.defineProperty;Hh.exports=function(a,e){try{_x(jh,a,{value:e,configurable:!0,writable:!0})}catch(t){jh[a]=e}return e}});var na=g((C_,zh)=>{"use strict";var Ox=at(),Fx=oe(),Nx=Qh(),Gh="__core-js_shared__",Wh=zh.exports=Fx[Gh]||Nx(Gh,{});(Wh.versions||(Wh.versions=[])).push({version:"3.43.0",mode:Ox?"pure":"global",copyright:"\xA9 2014-2025 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.43.0/LICENSE",source:"https://github.com/zloirock/core-js"})});var Uu=g((B_,Kh)=>{"use strict";var Yh=na();Kh.exports=function(a,e){return Yh[a]||(Yh[a]=e||{})}});var Xi=g((V_,Xh)=>{"use strict";var qx=Qt(),Ux=Object;Xh.exports=function(a){return Ux(qx(a))}});var st=g((__,Jh)=>{"use strict";var jx=be(),Hx=Xi(),Qx=jx({}.hasOwnProperty);Jh.exports=Object.hasOwn||function(e,t){return Qx(Hx(e),t)}});var ju=g((O_,Zh)=>{"use strict";var Gx=be(),Wx=0,zx=Math.random(),Yx=Gx(1.1.toString);Zh.exports=function(a){return"Symbol("+(a===void 0?"":a)+")_"+Yx(++Wx+zx,36)}});var Te=g((F_,tf)=>{"use strict";var Kx=oe(),Xx=Uu(),ef=st(),Jx=ju(),Zx=Vu(),ew=_u(),Ji=Kx.Symbol,Hu=Xx("wks"),tw=ew?Ji.for||Ji:Ji&&Ji.withoutSetter||Jx;tf.exports=function(a){return ef(Hu,a)||(Hu[a]=Zx&&ef(Ji,a)?Ji[a]:tw("Symbol."+a)),Hu[a]}});var nf=g((N_,sf)=>{"use strict";var iw=je(),rf=Ce(),af=Ou(),rw=sa(),aw=qh(),sw=Te(),nw=TypeError,ow=sw("toPrimitive");sf.exports=function(a,e){if(!rf(a)||af(a))return a;var t=rw(a,ow),i;if(t){if(e===void 0&&(e="default"),i=iw(t,a,e),!rf(i)||af(i))return i;throw new nw("Can't convert object to primitive value")}return e===void 0&&(e="number"),aw(a,e)}});var Qu=g((q_,of)=>{"use strict";var uw=nf(),lw=Ou();of.exports=function(a){var e=uw(a,"string");return lw(e)?e:e+""}});var hn=g((U_,lf)=>{"use strict";var cw=oe(),uf=Ce(),Gu=cw.document,dw=uf(Gu)&&uf(Gu.createElement);lf.exports=function(a){return dw?Gu.createElement(a):{}}});var Wu=g((j_,cf)=>{"use strict";var pw=Ue(),hw=me(),fw=hn();cf.exports=!pw&&!hw(function(){return Object.defineProperty(fw("div"),"a",{get:function(){return 7}}).a!==7})});var hf=g(pf=>{"use strict";var mw=Ue(),bw=je(),gw=Lu(),Sw=ta(),vw=Si(),yw=Qu(),Tw=st(),Iw=Wu(),df=Object.getOwnPropertyDescriptor;pf.f=mw?df:function(e,t){if(e=vw(e),t=yw(t),Iw)try{return df(e,t)}catch(i){}if(Tw(e,t))return Sw(!bw(gw.f,e,t),e[t])}});var zu=g((Q_,ff)=>{"use strict";var Ew=me(),xw=ue(),ww=/#|\.prototype\./,oa=function(a,e){var t=Rw[Aw(a)];return t===kw?!0:t===Pw?!1:xw(e)?Ew(e):!!e},Aw=oa.normalize=function(a){return String(a).replace(ww,".").toLowerCase()},Rw=oa.data={},Pw=oa.NATIVE="N",kw=oa.POLYFILL="P";ff.exports=oa});var Zi=g((G_,bf)=>{"use strict";var mf=Pu(),Lw=ft(),$w=ea(),Mw=mf(mf.bind);bf.exports=function(a,e){return Lw(a),e===void 0?a:$w?Mw(a,e):function(){return a.apply(e,arguments)}}});var Yu=g((W_,gf)=>{"use strict";var Dw=Ue(),Cw=me();gf.exports=Dw&&Cw(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var mt=g((z_,Sf)=>{"use strict";var Bw=Ce(),Vw=String,_w=TypeError;Sf.exports=function(a){if(Bw(a))return a;throw new _w(Vw(a)+" is not an object")}});var Ti=g(yf=>{"use strict";var Ow=Ue(),Fw=Wu(),Nw=Yu(),fn=mt(),vf=Qu(),qw=TypeError,Ku=Object.defineProperty,Uw=Object.getOwnPropertyDescriptor,Xu="enumerable",Ju="configurable",Zu="writable";yf.f=Ow?Nw?function(e,t,i){if(fn(e),t=vf(t),fn(i),typeof e=="function"&&t==="prototype"&&"value"in i&&Zu in i&&!i[Zu]){var r=Uw(e,t);r&&r[Zu]&&(e[t]=i.value,i={configurable:Ju in i?i[Ju]:r[Ju],enumerable:Xu in i?i[Xu]:r[Xu],writable:!1})}return Ku(e,t,i)}:Ku:function(e,t,i){if(fn(e),t=vf(t),fn(i),Fw)try{return Ku(e,t,i)}catch(r){}if("get"in i||"set"in i)throw new qw("Accessors not supported");return"value"in i&&(e[t]=i.value),e}});var er=g((K_,Tf)=>{"use strict";var jw=Ue(),Hw=Ti(),Qw=ta();Tf.exports=jw?function(a,e,t){return Hw.f(a,e,Qw(1,t))}:function(a,e,t){return a[e]=t,a}});var pe=g((X_,Ef)=>{"use strict";var ua=oe(),Gw=Au(),Ww=Pu(),zw=ue(),Yw=hf().f,Kw=zu(),tr=vi(),Xw=Zi(),ir=er(),If=st();na();var Jw=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 Gw(a,this,arguments)};return e.prototype=a.prototype,e};Ef.exports=function(a,e){var t=a.target,i=a.global,r=a.stat,s=a.proto,n=i?ua:r?ua[t]:ua[t]&&ua[t].prototype,o=i?tr:tr[t]||ir(tr,t,{})[t],u=o.prototype,l,c,d,f,p,h,m,S,b;for(f in e)l=Kw(i?f:t+(r?".":"#")+f,a.forced),c=!l&&n&&If(n,f),h=o[f],c&&(a.dontCallGetSet?(b=Yw(n,f),m=b&&b.value):m=n[f]),p=c&&m?m:e[f],!(!l&&!s&&typeof h==typeof p)&&(a.bind&&c?S=Xw(p,ua):a.wrap&&c?S=Jw(p):s&&zw(p)?S=Ww(p):S=p,(a.sham||p&&p.sham||h&&h.sham)&&ir(S,"sham",!0),ir(o,f,S),s&&(d=t+"Prototype",If(tr,d)||ir(tr,d,{}),ir(tr[d],f,p),a.real&&u&&(l||!u[f])&&ir(u,f,p)))}});var wf=g((J_,xf)=>{"use strict";var Zw=Math.ceil,eA=Math.floor;xf.exports=Math.trunc||function(e){var t=+e;return(t>0?eA:Zw)(t)}});var la=g((Z_,Af)=>{"use strict";var tA=wf();Af.exports=function(a){var e=+a;return e!==e||e===0?0:tA(e)}});var Pf=g((eO,Rf)=>{"use strict";var iA=la(),rA=Math.max,aA=Math.min;Rf.exports=function(a,e){var t=iA(a);return t<0?rA(t+e,0):aA(t,e)}});var el=g((tO,kf)=>{"use strict";var sA=la(),nA=Math.min;kf.exports=function(a){var e=sA(a);return e>0?nA(e,9007199254740991):0}});var rr=g((iO,Lf)=>{"use strict";var oA=el();Lf.exports=function(a){return oA(a.length)}});var tl=g((rO,Mf)=>{"use strict";var uA=Si(),lA=Pf(),cA=rr(),$f=function(a){return function(e,t,i){var r=uA(e),s=cA(r);if(s===0)return!a&&-1;var n=lA(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}};Mf.exports={includes:$f(!0),indexOf:$f(!1)}});var ca=g((aO,Df)=>{"use strict";Df.exports=function(){}});var Cf=g(()=>{"use strict";var dA=pe(),pA=tl().includes,hA=me(),fA=ca(),mA=hA(function(){return!Array(1).includes()});dA({target:"Array",proto:!0,forced:mA},{includes:function(e){return pA(this,e,arguments.length>1?arguments[1]:void 0)}});fA("includes")});var Gt=g((oO,Bf)=>{"use strict";var bA=Rt();Bf.exports=bA});var _f=g((uO,Vf)=>{"use strict";Cf();var gA=Gt();Vf.exports=gA("Array","includes")});var Ff=g((lO,Of)=>{"use strict";var SA=_f();Of.exports=SA});var Ae=g((cO,Nf)=>{"use strict";var vA=Ff();Nf.exports=vA});var gn=g((IO,zf)=>{"use strict";var RA=Uu(),PA=ju(),Wf=RA("keys");zf.exports=function(a){return Wf[a]||(Wf[a]=PA(a))}});var Kf=g((EO,Yf)=>{"use strict";var kA=me();Yf.exports=!kA(function(){function a(){}return a.prototype.constructor=null,Object.getPrototypeOf(new a)!==a.prototype})});var Sn=g((xO,Jf)=>{"use strict";var LA=st(),$A=ue(),MA=Xi(),DA=gn(),CA=Kf(),Xf=DA("IE_PROTO"),al=Object,BA=al.prototype;Jf.exports=CA?al.getPrototypeOf:function(a){var e=MA(a);if(LA(e,Xf))return e[Xf];var t=e.constructor;return $A(t)&&e instanceof t?t.prototype:e instanceof al?BA:null}});var vn=g((wO,Zf)=>{"use strict";Zf.exports={}});var im=g((AO,tm)=>{"use strict";var VA=be(),sl=st(),_A=Si(),OA=tl().indexOf,FA=vn(),em=VA([].push);tm.exports=function(a,e){var t=_A(a),i=0,r=[],s;for(s in t)!sl(FA,s)&&sl(t,s)&&em(r,s);for(;e.length>i;)sl(t,s=e[i++])&&(~OA(r,s)||em(r,s));return r}});var nl=g((RO,rm)=>{"use strict";rm.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var ol=g((PO,am)=>{"use strict";var NA=im(),qA=nl();am.exports=Object.keys||function(e){return NA(e,qA)}});var ul=g((kO,lm)=>{"use strict";var nm=Ue(),UA=me(),om=be(),jA=Sn(),HA=ol(),QA=Si(),GA=Lu().f,um=om(GA),WA=om([].push),zA=nm&&UA(function(){var a=Object.create(null);return a[2]=2,!um(a,2)}),sm=function(a){return function(e){for(var t=QA(e),i=HA(t),r=zA&&jA(t)===null,s=i.length,n=0,o=[],u;s>n;)u=i[n++],(!nm||(r?u in t:um(t,u)))&&WA(o,a?[u,t[u]]:t[u]);return o}};lm.exports={entries:sm(!0),values:sm(!1)}});var cm=g(()=>{"use strict";var YA=pe(),KA=ul().entries;YA({target:"Object",stat:!0},{entries:function(e){return KA(e)}})});var pm=g((MO,dm)=>{"use strict";cm();var XA=vi();dm.exports=XA.Object.entries});var fm=g((DO,hm)=>{"use strict";var JA=pm();hm.exports=JA});var ar=g((CO,mm)=>{"use strict";var ZA=fm();mm.exports=ZA});var Ii=g((BO,bm)=>{"use strict";bm.exports={}});var vm=g((VO,Sm)=>{"use strict";var eR=oe(),tR=ue(),gm=eR.WeakMap;Sm.exports=tR(gm)&&/native code/.test(String(gm))});var pl=g((_O,Im)=>{"use strict";var iR=vm(),Tm=oe(),rR=Ce(),aR=er(),ll=st(),cl=na(),sR=gn(),nR=vn(),ym="Object already initialized",dl=Tm.TypeError,oR=Tm.WeakMap,yn,da,Tn,uR=function(a){return Tn(a)?da(a):yn(a,{})},lR=function(a){return function(e){var t;if(!rR(e)||(t=da(e)).type!==a)throw new dl("Incompatible receiver, "+a+" required");return t}};iR||cl.state?(nt=cl.state||(cl.state=new oR),nt.get=nt.get,nt.has=nt.has,nt.set=nt.set,yn=function(a,e){if(nt.has(a))throw new dl(ym);return e.facade=a,nt.set(a,e),e},da=function(a){return nt.get(a)||{}},Tn=function(a){return nt.has(a)}):(Ei=sR("state"),nR[Ei]=!0,yn=function(a,e){if(ll(a,Ei))throw new dl(ym);return e.facade=a,aR(a,Ei,e),e},da=function(a){return ll(a,Ei)?a[Ei]:{}},Tn=function(a){return ll(a,Ei)});var nt,Ei;Im.exports={set:yn,get:da,has:Tn,enforce:uR,getterFor:lR}});var ml=g((OO,xm)=>{"use strict";var hl=Ue(),cR=st(),Em=Function.prototype,dR=hl&&Object.getOwnPropertyDescriptor,fl=cR(Em,"name"),pR=fl&&function(){}.name==="something",hR=fl&&(!hl||hl&&dR(Em,"name").configurable);xm.exports={EXISTS:fl,PROPER:pR,CONFIGURABLE:hR}});var Am=g(wm=>{"use strict";var fR=Ue(),mR=Yu(),bR=Ti(),gR=mt(),SR=Si(),vR=ol();wm.f=fR&&!mR?Object.defineProperties:function(e,t){gR(e);for(var i=SR(t),r=vR(t),s=r.length,n=0,o;s>n;)bR.f(e,o=r[n++],i[o]);return e}});var bl=g((NO,Rm)=>{"use strict";var yR=Rt();Rm.exports=yR("document","documentElement")});var yl=g((qO,Cm)=>{"use strict";var TR=mt(),IR=Am(),Pm=nl(),ER=vn(),xR=bl(),wR=hn(),AR=gn(),km=">",Lm="<",Sl="prototype",vl="script",Mm=AR("IE_PROTO"),gl=function(){},Dm=function(a){return Lm+vl+km+a+Lm+"/"+vl+km},$m=function(a){a.write(Dm("")),a.close();var e=a.parentWindow.Object;return a=null,e},RR=function(){var a=wR("iframe"),e="java"+vl+":",t;return a.style.display="none",xR.appendChild(a),a.src=String(e),t=a.contentWindow.document,t.open(),t.write(Dm("document.F=Object")),t.close(),t.F},In,En=function(){try{In=new ActiveXObject("htmlfile")}catch(e){}En=typeof document!="undefined"?document.domain&&In?$m(In):RR():$m(In);for(var a=Pm.length;a--;)delete En[Sl][Pm[a]];return En()};ER[Mm]=!0;Cm.exports=Object.create||function(e,t){var i;return e!==null?(gl[Sl]=TR(e),i=new gl,gl[Sl]=null,i[Mm]=e):i=En(),t===void 0?i:IR.f(i,t)}});var sr=g((UO,Bm)=>{"use strict";var PR=er();Bm.exports=function(a,e,t,i){return i&&i.enumerable?a[e]=t:PR(a,e,t),a}});var xl=g((jO,Om)=>{"use strict";var kR=me(),LR=ue(),$R=Ce(),MR=yl(),Vm=Sn(),DR=sr(),CR=Te(),BR=at(),El=CR("iterator"),_m=!1,Pt,Tl,Il;[].keys&&(Il=[].keys(),"next"in Il?(Tl=Vm(Vm(Il)),Tl!==Object.prototype&&(Pt=Tl)):_m=!0);var VR=!$R(Pt)||kR(function(){var a={};return Pt[El].call(a)!==a});VR?Pt={}:BR&&(Pt=MR(Pt));LR(Pt[El])||DR(Pt,El,function(){return this});Om.exports={IteratorPrototype:Pt,BUGGY_SAFARI_ITERATORS:_m}});var xn=g((HO,Nm)=>{"use strict";var _R=Te(),OR=_R("toStringTag"),Fm={};Fm[OR]="z";Nm.exports=String(Fm)==="[object z]"});var pa=g((QO,qm)=>{"use strict";var FR=xn(),NR=ue(),wn=gi(),qR=Te(),UR=qR("toStringTag"),jR=Object,HR=wn(function(){return arguments}())==="Arguments",QR=function(a,e){try{return a[e]}catch(t){}};qm.exports=FR?wn:function(a){var e,t,i;return a===void 0?"Undefined":a===null?"Null":typeof(t=QR(e=jR(a),UR))=="string"?t:HR?wn(e):(i=wn(e))==="Object"&&NR(e.callee)?"Arguments":i}});var jm=g((GO,Um)=>{"use strict";var GR=xn(),WR=pa();Um.exports=GR?{}.toString:function(){return"[object "+WR(this)+"]"}});var ha=g((WO,Qm)=>{"use strict";var zR=xn(),YR=Ti().f,KR=er(),XR=st(),JR=jm(),ZR=Te(),Hm=ZR("toStringTag");Qm.exports=function(a,e,t,i){var r=t?a:a&&a.prototype;r&&(XR(r,Hm)||YR(r,Hm,{configurable:!0,value:e}),i&&!zR&&KR(r,"toString",JR))}});var Wm=g((zO,Gm)=>{"use strict";var eP=xl().IteratorPrototype,tP=yl(),iP=ta(),rP=ha(),aP=Ii(),sP=function(){return this};Gm.exports=function(a,e,t,i){var r=e+" Iterator";return a.prototype=tP(eP,{next:iP(+!i,t)}),rP(a,r,!1,!0),aP[r]=sP,a}});var Ym=g((YO,zm)=>{"use strict";var nP=be(),oP=ft();zm.exports=function(a,e,t){try{return nP(oP(Object.getOwnPropertyDescriptor(a,e)[t]))}catch(i){}}});var Xm=g((KO,Km)=>{"use strict";var uP=Ce();Km.exports=function(a){return uP(a)||a===null}});var Zm=g((XO,Jm)=>{"use strict";var lP=Xm(),cP=String,dP=TypeError;Jm.exports=function(a){if(lP(a))return a;throw new dP("Can't set "+cP(a)+" as a prototype")}});var wl=g((JO,eb)=>{"use strict";var pP=Ym(),hP=Ce(),fP=Qt(),mP=Zm();eb.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var a=!1,e={},t;try{t=pP(Object.prototype,"__proto__","set"),t(e,[]),a=e instanceof Array}catch(i){}return function(r,s){return fP(r),mP(s),hP(r)&&(a?t(r,s):r.__proto__=s),r}}():void 0)});var db=g((ZO,cb)=>{"use strict";var bP=pe(),gP=je(),An=at(),ub=ml(),SP=ue(),vP=Wm(),tb=Sn(),ib=wl(),yP=ha(),TP=er(),Al=sr(),IP=Te(),rb=Ii(),lb=xl(),EP=ub.PROPER,xP=ub.CONFIGURABLE,ab=lb.IteratorPrototype,Rn=lb.BUGGY_SAFARI_ITERATORS,fa=IP("iterator"),sb="keys",ma="values",nb="entries",ob=function(){return this};cb.exports=function(a,e,t,i,r,s,n){vP(t,e,i);var o=function(b){if(b===r&&f)return f;if(!Rn&&b&&b in c)return c[b];switch(b){case sb:return function(){return new t(this,b)};case ma:return function(){return new t(this,b)};case nb:return function(){return new t(this,b)}}return function(){return new t(this)}},u=e+" Iterator",l=!1,c=a.prototype,d=c[fa]||c["@@iterator"]||r&&c[r],f=!Rn&&d||o(r),p=e==="Array"&&c.entries||d,h,m,S;if(p&&(h=tb(p.call(new a)),h!==Object.prototype&&h.next&&(!An&&tb(h)!==ab&&(ib?ib(h,ab):SP(h[fa])||Al(h,fa,ob)),yP(h,u,!0,!0),An&&(rb[u]=ob))),EP&&r===ma&&d&&d.name!==ma&&(!An&&xP?TP(c,"name",ma):(l=!0,f=function(){return gP(d,this)})),r)if(m={values:o(ma),keys:s?f:o(sb),entries:o(nb)},n)for(S in m)(Rn||l||!(S in c))&&Al(c,S,m[S]);else bP({target:e,proto:!0,forced:Rn||l},m);return(!An||n)&&c[fa]!==f&&Al(c,fa,f,{name:r}),rb[e]=f,m}});var hb=g((eF,pb)=>{"use strict";pb.exports=function(a,e){return{value:a,done:e}}});var Pl=g((tF,Sb)=>{"use strict";var wP=Si(),Rl=ca(),fb=Ii(),bb=pl(),AP=Ti().f,RP=db(),Pn=hb(),PP=at(),kP=Ue(),gb="Array Iterator",LP=bb.set,$P=bb.getterFor(gb);Sb.exports=RP(Array,"Array",function(a,e){LP(this,{type:gb,target:wP(a),index:0,kind:e})},function(){var a=$P(this),e=a.target,t=a.index++;if(!e||t>=e.length)return a.target=null,Pn(void 0,!0);switch(a.kind){case"keys":return Pn(t,!1);case"values":return Pn(e[t],!1)}return Pn([t,e[t]],!1)},"values");var mb=fb.Arguments=fb.Array;Rl("keys");Rl("values");Rl("entries");if(!PP&&kP&&mb.name!=="values")try{AP(mb,"name",{value:"values"})}catch(a){}});var yb=g((iF,vb)=>{"use strict";var MP=Te(),DP=Ii(),CP=MP("iterator"),BP=Array.prototype;vb.exports=function(a){return a!==void 0&&(DP.Array===a||BP[CP]===a)}});var kl=g((rF,Ib)=>{"use strict";var VP=pa(),Tb=sa(),_P=ia(),OP=Ii(),FP=Te(),NP=FP("iterator");Ib.exports=function(a){if(!_P(a))return Tb(a,NP)||Tb(a,"@@iterator")||OP[VP(a)]}});var xb=g((aF,Eb)=>{"use strict";var qP=je(),UP=ft(),jP=mt(),HP=aa(),QP=kl(),GP=TypeError;Eb.exports=function(a,e){var t=arguments.length<2?QP(a):e;if(UP(t))return jP(qP(t,a));throw new GP(HP(a)+" is not iterable")}});var Rb=g((sF,Ab)=>{"use strict";var WP=je(),wb=mt(),zP=sa();Ab.exports=function(a,e,t){var i,r;wb(a);try{if(i=zP(a,"return"),!i){if(e==="throw")throw t;return t}i=WP(i,a)}catch(s){r=!0,i=s}if(e==="throw")throw t;if(r)throw i;return wb(i),t}});var Ln=g((nF,$b)=>{"use strict";var YP=Zi(),KP=je(),XP=mt(),JP=aa(),ZP=yb(),ek=rr(),Pb=ra(),tk=xb(),ik=kl(),kb=Rb(),rk=TypeError,kn=function(a,e){this.stopped=a,this.result=e},Lb=kn.prototype;$b.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=YP(e,i),l,c,d,f,p,h,m,S=function(v){return l&&kb(l,"normal"),new kn(!0,v)},b=function(v){return r?(XP(v),o?u(v[0],v[1],S):u(v[0],v[1])):o?u(v,S):u(v)};if(s)l=a.iterator;else if(n)l=a;else{if(c=ik(a),!c)throw new rk(JP(a)+" is not iterable");if(ZP(c)){for(d=0,f=ek(a);f>d;d++)if(p=b(a[d]),p&&Pb(Lb,p))return p;return new kn(!1)}l=tk(a,c)}for(h=s?a.next:l.next;!(m=KP(h,l)).done;){try{p=b(m.value)}catch(v){kb(l,"throw",v)}if(typeof p=="object"&&p&&Pb(Lb,p))return p}return new kn(!1)}});var Db=g((oF,Mb)=>{"use strict";var ak=Ue(),sk=Ti(),nk=ta();Mb.exports=function(a,e,t){ak?sk.f(a,e,nk(0,t)):a[e]=t}});var Cb=g(()=>{"use strict";var ok=pe(),uk=Ln(),lk=Db();ok({target:"Object",stat:!0},{fromEntries:function(e){var t={};return uk(e,function(i,r){lk(t,i,r)},{AS_ENTRIES:!0}),t}})});var Vb=g((cF,Bb)=>{"use strict";Pl();Cb();var ck=vi();Bb.exports=ck.Object.fromEntries});var Ob=g((dF,_b)=>{"use strict";_b.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 Nb=g(()=>{"use strict";Pl();var dk=Ob(),pk=oe(),hk=ha(),Fb=Ii();for($n in dk)hk(pk[$n],$n),Fb[$n]=Fb.Array;var $n});var Ub=g((fF,qb)=>{"use strict";var fk=Vb();Nb();qb.exports=fk});var Ll=g((mF,jb)=>{"use strict";var mk=Ub();jb.exports=mk});var Hb=g(()=>{"use strict"});var $l=g((SF,Qb)=>{"use strict";var ba=oe(),bk=yi(),gk=gi(),Mn=function(a){return bk.slice(0,a.length)===a};Qb.exports=function(){return Mn("Bun/")?"BUN":Mn("Cloudflare-Workers")?"CLOUDFLARE":Mn("Deno/")?"DENO":Mn("Node.js/")?"NODE":ba.Bun&&typeof Bun.version=="string"?"BUN":ba.Deno&&typeof Deno.version=="object"?"DENO":gk(ba.process)==="process"?"NODE":ba.window&&ba.document?"BROWSER":"REST"}()});var Dn=g((vF,Gb)=>{"use strict";var Sk=$l();Gb.exports=Sk==="NODE"});var zb=g((yF,Wb)=>{"use strict";var vk=Ti();Wb.exports=function(a,e,t){return vk.f(a,e,t)}});var Xb=g((TF,Kb)=>{"use strict";var yk=Rt(),Tk=zb(),Ik=Te(),Ek=Ue(),Yb=Ik("species");Kb.exports=function(a){var e=yk(a);Ek&&e&&!e[Yb]&&Tk(e,Yb,{configurable:!0,get:function(){return this}})}});var Zb=g((IF,Jb)=>{"use strict";var xk=ra(),wk=TypeError;Jb.exports=function(a,e){if(xk(e,a))return a;throw new wk("Incorrect invocation")}});var Dl=g((EF,eg)=>{"use strict";var Ak=be(),Rk=ue(),Ml=na(),Pk=Ak(Function.toString);Rk(Ml.inspectSource)||(Ml.inspectSource=function(a){return Pk(a)});eg.exports=Ml.inspectSource});var Bl=g((xF,sg)=>{"use strict";var kk=be(),Lk=me(),tg=ue(),$k=pa(),Mk=Rt(),Dk=Dl(),ig=function(){},rg=Mk("Reflect","construct"),Cl=/^\s*(?:class|function)\b/,Ck=kk(Cl.exec),Bk=!Cl.test(ig),ga=function(e){if(!tg(e))return!1;try{return rg(ig,[],e),!0}catch(t){return!1}},ag=function(e){if(!tg(e))return!1;switch($k(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return Bk||!!Ck(Cl,Dk(e))}catch(t){return!0}};ag.sham=!0;sg.exports=!rg||Lk(function(){var a;return ga(ga.call)||!ga(Object)||!ga(function(){a=!0})||a})?ag:ga});var og=g((wF,ng)=>{"use strict";var Vk=Bl(),_k=aa(),Ok=TypeError;ng.exports=function(a){if(Vk(a))return a;throw new Ok(_k(a)+" is not a constructor")}});var Vl=g((AF,lg)=>{"use strict";var ug=mt(),Fk=og(),Nk=ia(),qk=Te(),Uk=qk("species");lg.exports=function(a,e){var t=ug(a).constructor,i;return t===void 0||Nk(i=ug(t)[Uk])?e:Fk(i)}});var dg=g((RF,cg)=>{"use strict";var jk=be();cg.exports=jk([].slice)});var hg=g((PF,pg)=>{"use strict";var Hk=TypeError;pg.exports=function(a,e){if(a<e)throw new Hk("Not enough arguments");return a}});var _l=g((kF,fg)=>{"use strict";var Qk=yi();fg.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(Qk)});var Gl=g((LF,Eg)=>{"use strict";var He=oe(),Gk=Au(),Wk=Zi(),mg=ue(),zk=st(),Ig=me(),bg=bl(),Yk=dg(),gg=hn(),Kk=hg(),Xk=_l(),Jk=Dn(),jl=He.setImmediate,Hl=He.clearImmediate,Zk=He.process,Ol=He.Dispatch,eL=He.Function,Sg=He.MessageChannel,tL=He.String,Fl=0,Sa={},vg="onreadystatechange",va,xi,Nl,ql;Ig(function(){va=He.location});var Ql=function(a){if(zk(Sa,a)){var e=Sa[a];delete Sa[a],e()}},Ul=function(a){return function(){Ql(a)}},yg=function(a){Ql(a.data)},Tg=function(a){He.postMessage(tL(a),va.protocol+"//"+va.host)};(!jl||!Hl)&&(jl=function(e){Kk(arguments.length,1);var t=mg(e)?e:eL(e),i=Yk(arguments,1);return Sa[++Fl]=function(){Gk(t,void 0,i)},xi(Fl),Fl},Hl=function(e){delete Sa[e]},Jk?xi=function(a){Zk.nextTick(Ul(a))}:Ol&&Ol.now?xi=function(a){Ol.now(Ul(a))}:Sg&&!Xk?(Nl=new Sg,ql=Nl.port2,Nl.port1.onmessage=yg,xi=Wk(ql.postMessage,ql)):He.addEventListener&&mg(He.postMessage)&&!He.importScripts&&va&&va.protocol!=="file:"&&!Ig(Tg)?(xi=Tg,He.addEventListener("message",yg,!1)):vg in gg("script")?xi=function(a){bg.appendChild(gg("script"))[vg]=function(){bg.removeChild(this),Ql(a)}}:xi=function(a){setTimeout(Ul(a),0)});Eg.exports={set:jl,clear:Hl}});var Ag=g(($F,wg)=>{"use strict";var xg=oe(),iL=Ue(),rL=Object.getOwnPropertyDescriptor;wg.exports=function(a){if(!iL)return xg[a];var e=rL(xg,a);return e&&e.value}});var Wl=g((MF,Pg)=>{"use strict";var Rg=function(){this.head=null,this.tail=null};Rg.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}}};Pg.exports=Rg});var Lg=g((DF,kg)=>{"use strict";var aL=yi();kg.exports=/ipad|iphone|ipod/i.test(aL)&&typeof Pebble!="undefined"});var Mg=g((CF,$g)=>{"use strict";var sL=yi();$g.exports=/web0s(?!.*chrome)/i.test(sL)});var Fg=g((BF,Og)=>{"use strict";var or=oe(),nL=Ag(),Dg=Zi(),zl=Gl().set,oL=Wl(),uL=_l(),lL=Lg(),cL=Mg(),Yl=Dn(),Cg=or.MutationObserver||or.WebKitMutationObserver,Bg=or.document,Vg=or.process,Cn=or.Promise,Jl=nL("queueMicrotask"),nr,Kl,Xl,Bn,_g;Jl||(ya=new oL,Ta=function(){var a,e;for(Yl&&(a=Vg.domain)&&a.exit();e=ya.get();)try{e()}catch(t){throw ya.head&&nr(),t}a&&a.enter()},!uL&&!Yl&&!cL&&Cg&&Bg?(Kl=!0,Xl=Bg.createTextNode(""),new Cg(Ta).observe(Xl,{characterData:!0}),nr=function(){Xl.data=Kl=!Kl}):!lL&&Cn&&Cn.resolve?(Bn=Cn.resolve(void 0),Bn.constructor=Cn,_g=Dg(Bn.then,Bn),nr=function(){_g(Ta)}):Yl?nr=function(){Vg.nextTick(Ta)}:(zl=Dg(zl,or),nr=function(){zl(Ta)}),Jl=function(a){ya.head||nr(),ya.add(a)});var ya,Ta;Og.exports=Jl});var qg=g((VF,Ng)=>{"use strict";Ng.exports=function(a,e){try{arguments.length===1?console.error(a):console.error(a,e)}catch(t){}}});var Vn=g((_F,Ug)=>{"use strict";Ug.exports=function(a){try{return{error:!1,value:a()}}catch(e){return{error:!0,value:e}}}});var wi=g((OF,jg)=>{"use strict";var dL=oe();jg.exports=dL.Promise});var ur=g((FF,Wg)=>{"use strict";var pL=oe(),Ia=wi(),hL=ue(),fL=zu(),mL=Dl(),bL=Te(),Hg=$l(),gL=at(),Zl=Bu(),Qg=Ia&&Ia.prototype,SL=bL("species"),ec=!1,Gg=hL(pL.PromiseRejectionEvent),vL=fL("Promise",function(){var a=mL(Ia),e=a!==String(Ia);if(!e&&Zl===66||gL&&!(Qg.catch&&Qg.finally))return!0;if(!Zl||Zl<51||!/native code/.test(a)){var t=new Ia(function(s){s(1)}),i=function(s){s(function(){},function(){})},r=t.constructor={};if(r[SL]=i,ec=t.then(function(){})instanceof i,!ec)return!0}return!e&&(Hg==="BROWSER"||Hg==="DENO")&&!Gg});Wg.exports={CONSTRUCTOR:vL,REJECTION_EVENT:Gg,SUBCLASSING:ec}});var lr=g((NF,Yg)=>{"use strict";var zg=ft(),yL=TypeError,TL=function(a){var e,t;this.promise=new a(function(i,r){if(e!==void 0||t!==void 0)throw new yL("Bad Promise constructor");e=i,t=r}),this.resolve=zg(e),this.reject=zg(t)};Yg.exports.f=function(a){return new TL(a)}});var mS=g(()=>{"use strict";var IL=pe(),EL=at(),Nn=Dn(),Wt=oe(),xL=vi(),hr=je(),Kg=sr(),Xg=wl(),wL=ha(),AL=Xb(),RL=ft(),Fn=ue(),PL=Ce(),kL=Zb(),LL=Vl(),iS=Gl().set,sc=Fg(),$L=qg(),ML=Vn(),DL=Wl(),rS=pl(),qn=wi(),nc=ur(),aS=lr(),Un="Promise",sS=nc.CONSTRUCTOR,CL=nc.REJECTION_EVENT,BL=nc.SUBCLASSING,tc=rS.getterFor(Un),VL=rS.set,cr=qn&&qn.prototype,Ai=qn,_n=cr,nS=Wt.TypeError,ic=Wt.document,oc=Wt.process,rc=aS.f,_L=rc,OL=!!(ic&&ic.createEvent&&Wt.dispatchEvent),oS="unhandledrejection",FL="rejectionhandled",Jg=0,uS=1,NL=2,uc=1,lS=2,On,Zg,cS,eS,dS=function(a){var e;return PL(a)&&Fn(e=a.then)?e:!1},pS=function(a,e){var t=e.value,i=e.state===uS,r=i?a.ok:a.fail,s=a.resolve,n=a.reject,o=a.domain,u,l,c;try{r?(i||(e.rejection===lS&&UL(e),e.rejection=uc),r===!0?u=t:(o&&o.enter(),u=r(t),o&&(o.exit(),c=!0)),u===a.promise?n(new nS("Promise-chain cycle")):(l=dS(u))?hr(l,u,s,n):s(u)):n(t)}catch(d){o&&!c&&o.exit(),n(d)}},hS=function(a,e){a.notified||(a.notified=!0,sc(function(){for(var t=a.reactions,i;i=t.get();)pS(i,a);a.notified=!1,e&&!a.rejection&&qL(a)}))},fS=function(a,e,t){var i,r;OL?(i=ic.createEvent("Event"),i.promise=e,i.reason=t,i.initEvent(a,!1,!0),Wt.dispatchEvent(i)):i={promise:e,reason:t},!CL&&(r=Wt["on"+a])?r(i):a===oS&&$L("Unhandled promise rejection",t)},qL=function(a){hr(iS,Wt,function(){var e=a.facade,t=a.value,i=tS(a),r;if(i&&(r=ML(function(){Nn?oc.emit("unhandledRejection",t,e):fS(oS,e,t)}),a.rejection=Nn||tS(a)?lS:uc,r.error))throw r.value})},tS=function(a){return a.rejection!==uc&&!a.parent},UL=function(a){hr(iS,Wt,function(){var e=a.facade;Nn?oc.emit("rejectionHandled",e):fS(FL,e,a.value)})},dr=function(a,e,t){return function(i){a(e,i,t)}},pr=function(a,e,t){a.done||(a.done=!0,t&&(a=t),a.value=e,a.state=NL,hS(a,!0))},ac=function(a,e,t){if(!a.done){a.done=!0,t&&(a=t);try{if(a.facade===e)throw new nS("Promise can't be resolved itself");var i=dS(e);i?sc(function(){var r={done:!1};try{hr(i,e,dr(ac,r,a),dr(pr,r,a))}catch(s){pr(r,s,a)}}):(a.value=e,a.state=uS,hS(a,!1))}catch(r){pr({done:!1},r,a)}}};if(sS&&(Ai=function(e){kL(this,_n),RL(e),hr(On,this);var t=tc(this);try{e(dr(ac,t),dr(pr,t))}catch(i){pr(t,i)}},_n=Ai.prototype,On=function(e){VL(this,{type:Un,done:!1,notified:!1,parent:!1,reactions:new DL,rejection:!1,state:Jg,value:null})},On.prototype=Kg(_n,"then",function(e,t){var i=tc(this),r=rc(LL(this,Ai));return i.parent=!0,r.ok=Fn(e)?e:!0,r.fail=Fn(t)&&t,r.domain=Nn?oc.domain:void 0,i.state===Jg?i.reactions.add(r):sc(function(){pS(r,i)}),r.promise}),Zg=function(){var a=new On,e=tc(a);this.promise=a,this.resolve=dr(ac,e),this.reject=dr(pr,e)},aS.f=rc=function(a){return a===Ai||a===cS?new Zg(a):_L(a)},!EL&&Fn(qn)&&cr!==Object.prototype)){eS=cr.then,BL||Kg(cr,"then",function(e,t){var i=this;return new Ai(function(r,s){hr(eS,i,r,s)}).then(e,t)},{unsafe:!0});try{delete cr.constructor}catch(a){}Xg&&Xg(cr,_n)}IL({global:!0,constructor:!0,wrap:!0,forced:sS},{Promise:Ai});cS=xL.Promise;wL(Ai,Un,!1,!0);AL(Un)});var yS=g((jF,vS)=>{"use strict";var jL=Te(),gS=jL("iterator"),SS=!1;try{bS=0,lc={next:function(){return{done:!!bS++}},return:function(){SS=!0}},lc[gS]=function(){return this},Array.from(lc,function(){throw 2})}catch(a){}var bS,lc;vS.exports=function(a,e){try{if(!e&&!SS)return!1}catch(r){return!1}var t=!1;try{var i={};i[gS]=function(){return{next:function(){return{done:t=!0}}}},a(i)}catch(r){}return t}});var cc=g((HF,TS)=>{"use strict";var HL=wi(),QL=yS(),GL=ur().CONSTRUCTOR;TS.exports=GL||!QL(function(a){HL.all(a).then(void 0,function(){})})});var IS=g(()=>{"use strict";var WL=pe(),zL=je(),YL=ft(),KL=lr(),XL=Vn(),JL=Ln(),ZL=cc();WL({target:"Promise",stat:!0,forced:ZL},{all:function(e){var t=this,i=KL.f(t),r=i.resolve,s=i.reject,n=XL(function(){var o=YL(t.resolve),u=[],l=0,c=1;JL(e,function(d){var f=l++,p=!1;c++,zL(o,t,d).then(function(h){p||(p=!0,u[f]=h,--c||r(u))},s)}),--c||r(u)});return n.error&&s(n.value),i.promise}})});var xS=g(()=>{"use strict";var e$=pe(),t$=at(),i$=ur().CONSTRUCTOR,pc=wi(),r$=Rt(),a$=ue(),s$=sr(),ES=pc&&pc.prototype;e$({target:"Promise",proto:!0,forced:i$,real:!0},{catch:function(a){return this.then(void 0,a)}});!t$&&a$(pc)&&(dc=r$("Promise").prototype.catch,ES.catch!==dc&&s$(ES,"catch",dc,{unsafe:!0}));var dc});var wS=g(()=>{"use strict";var n$=pe(),o$=je(),u$=ft(),l$=lr(),c$=Vn(),d$=Ln(),p$=cc();n$({target:"Promise",stat:!0,forced:p$},{race:function(e){var t=this,i=l$.f(t),r=i.reject,s=c$(function(){var n=u$(t.resolve);d$(e,function(o){o$(n,t,o).then(i.resolve,r)})});return s.error&&r(s.value),i.promise}})});var AS=g(()=>{"use strict";var h$=pe(),f$=lr(),m$=ur().CONSTRUCTOR;h$({target:"Promise",stat:!0,forced:m$},{reject:function(e){var t=f$.f(this),i=t.reject;return i(e),t.promise}})});var hc=g((ZF,RS)=>{"use strict";var b$=mt(),g$=Ce(),S$=lr();RS.exports=function(a,e){if(b$(a),g$(e)&&e.constructor===a)return e;var t=S$.f(a),i=t.resolve;return i(e),t.promise}});var LS=g(()=>{"use strict";var v$=pe(),y$=Rt(),PS=at(),T$=wi(),kS=ur().CONSTRUCTOR,I$=hc(),E$=y$("Promise"),x$=PS&&!kS;v$({target:"Promise",stat:!0,forced:PS||kS},{resolve:function(e){return I$(x$&&this===E$?T$:this,e)}})});var $S=g(()=>{"use strict";mS();IS();xS();wS();AS();LS()});var BS=g(()=>{"use strict";var w$=pe(),A$=at(),jn=wi(),R$=me(),DS=Rt(),CS=ue(),P$=Vl(),MS=hc(),k$=sr(),mc=jn&&jn.prototype,L$=!!jn&&R$(function(){mc.finally.call({then:function(){}},function(){})});w$({target:"Promise",proto:!0,real:!0,forced:L$},{finally:function(a){var e=P$(this,DS("Promise")),t=CS(a);return this.then(t?function(i){return MS(e,a()).then(function(){return i})}:a,t?function(i){return MS(e,a()).then(function(){throw i})}:a)}});!A$&&CS(jn)&&(fc=DS("Promise").prototype.finally,mc.finally!==fc&&k$(mc,"finally",fc,{unsafe:!0}));var fc});var _S=g((nN,VS)=>{"use strict";Hb();$S();BS();var $$=Gt();VS.exports=$$("Promise","finally")});var FS=g((oN,OS)=>{"use strict";var M$=_S();OS.exports=M$});var Hn=g((uN,NS)=>{"use strict";var D$=FS();NS.exports=D$});var sv=g(()=>{"use strict";var eM=pe(),tM=ul().values;eM({target:"Object",stat:!0},{values:function(e){return tM(e)}})});var ov=g((Aq,nv)=>{"use strict";sv();var iM=vi();nv.exports=iM.Object.values});var lv=g((Rq,uv)=>{"use strict";var rM=ov();uv.exports=rM});var br=g((Pq,cv)=>{"use strict";var aM=lv();cv.exports=aM});var Tv=g(()=>{"use strict";var yM=pe(),TM=Xi(),IM=rr(),EM=la(),xM=ca();yM({target:"Array",proto:!0},{at:function(e){var t=TM(this),i=IM(t),r=EM(e),s=r>=0?r:i+r;return s<0||s>=i?void 0:t[s]}});xM("at")});var Ev=g((aU,Iv)=>{"use strict";Tv();var wM=Gt();Iv.exports=wM("Array","at")});var wv=g((sU,xv)=>{"use strict";var AM=Ev();xv.exports=AM});var ot=g((nU,Av)=>{"use strict";var RM=wv();Av.exports=RM});var Nc=g((X1,oy)=>{"use strict";var oD=gi();oy.exports=Array.isArray||function(e){return oD(e)==="Array"}});var ly=g((J1,uy)=>{"use strict";var uD=TypeError,lD=9007199254740991;uy.exports=function(a){if(a>lD)throw uD("Maximum allowed index exceeded");return a}});var py=g((Z1,dy)=>{"use strict";var cD=Nc(),dD=rr(),pD=ly(),hD=Zi(),cy=function(a,e,t,i,r,s,n,o){for(var u=r,l=0,c=n?hD(n,o):!1,d,f;l<i;)l in t&&(d=c?c(t[l],l,e):t[l],s>0&&cD(d)?(f=dD(d),u=cy(a,e,d,f,u,s-1)-1):(pD(u+1),a[u]=d),u++),l++;return u};dy.exports=cy});var by=g((ej,my)=>{"use strict";var hy=Nc(),fD=Bl(),mD=Ce(),bD=Te(),gD=bD("species"),fy=Array;my.exports=function(a){var e;return hy(a)&&(e=a.constructor,fD(e)&&(e===fy||hy(e.prototype))?e=void 0:mD(e)&&(e=e[gD],e===null&&(e=void 0))),e===void 0?fy:e}});var Sy=g((tj,gy)=>{"use strict";var SD=by();gy.exports=function(a,e){return new(SD(a))(e===0?0:e)}});var vy=g(()=>{"use strict";var vD=pe(),yD=py(),TD=ft(),ID=Xi(),ED=rr(),xD=Sy();vD({target:"Array",proto:!0},{flatMap:function(e){var t=ID(this),i=ED(t),r;return TD(e),r=xD(t,0),r.length=yD(r,t,t,i,0,1,e,arguments.length>1?arguments[1]:void 0),r}})});var yy=g(()=>{"use strict";var wD=ca();wD("flatMap")});var Iy=g((nj,Ty)=>{"use strict";vy();yy();var AD=Gt();Ty.exports=AD("Array","flatMap")});var xy=g((oj,Ey)=>{"use strict";var RD=Iy();Ey.exports=RD});var Oa=g((uj,wy)=>{"use strict";var PD=xy();wy.exports=PD});var Fa=g((lj,Ay)=>{"use strict";var kD=pa(),LD=String;Ay.exports=function(a){if(kD(a)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return LD(a)}});var qc=g((cj,Ry)=>{"use strict";Ry.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 Ly=g((dj,ky)=>{"use strict";var $D=be(),MD=Qt(),DD=Fa(),jc=qc(),Py=$D("".replace),CD=RegExp("^["+jc+"]+"),BD=RegExp("(^|[^"+jc+"])["+jc+"]+$"),Uc=function(a){return function(e){var t=DD(MD(e));return a&1&&(t=Py(t,CD,"")),a&2&&(t=Py(t,BD,"$1")),t}};ky.exports={start:Uc(1),end:Uc(2),trim:Uc(3)}});var Cy=g((pj,Dy)=>{"use strict";var VD=ml().PROPER,_D=me(),$y=qc(),My="\u200B\x85\u180E";Dy.exports=function(a){return _D(function(){return!!$y[a]()||My[a]()!==My||VD&&$y[a].name!==a})}});var Hc=g((hj,By)=>{"use strict";var OD=Ly().start,FD=Cy();By.exports=FD("trimStart")?function(){return OD(this)}:"".trimStart});var _y=g(()=>{"use strict";var ND=pe(),Vy=Hc();ND({target:"String",proto:!0,name:"trimStart",forced:"".trimLeft!==Vy},{trimLeft:Vy})});var Fy=g(()=>{"use strict";_y();var qD=pe(),Oy=Hc();qD({target:"String",proto:!0,name:"trimStart",forced:"".trimStart!==Oy},{trimStart:Oy})});var qy=g((Sj,Ny)=>{"use strict";Fy();var UD=Gt();Ny.exports=UD("String","trimLeft")});var jy=g((vj,Uy)=>{"use strict";var jD=qy();Uy.exports=jD});var Qy=g((yj,Hy)=>{"use strict";var HD=jy();Hy.exports=HD});var oT=g(()=>{"use strict"});var uT=g(()=>{"use strict"});var cT=g((nG,lT)=>{"use strict";var fC=Ce(),mC=gi(),bC=Te(),gC=bC("match");lT.exports=function(a){var e;return fC(a)&&((e=a[gC])!==void 0?!!e:mC(a)==="RegExp")}});var hT=g((oG,pT)=>{"use strict";var SC=oe(),vC=me(),dT=SC.RegExp,yC=!vC(function(){var a=!0;try{dT(".","d")}catch(u){a=!1}var e={},t="",i=a?"dgimsy":"gimsy",r=function(u,l){Object.defineProperty(e,u,{get:function(){return t+=l,!0}})},s={dotAll:"s",global:"g",ignoreCase:"i",multiline:"m",sticky:"y"};a&&(s.hasIndices="d");for(var n in s)r(n,s[n]);var o=Object.getOwnPropertyDescriptor(dT.prototype,"flags").get.call(e);return o!==i||t!==i});pT.exports={correct:yC}});var mT=g((uG,fT)=>{"use strict";var TC=mt();fT.exports=function(){var a=TC(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 ST=g((lG,gT)=>{"use strict";var IC=je(),EC=st(),xC=ra(),bT=hT(),wC=mT(),AC=RegExp.prototype;gT.exports=bT.correct?function(a){return a.flags}:function(a){return!bT.correct&&xC(AC,a)&&!EC(a,"flags")?IC(wC,a):a.flags}});var yT=g((cG,vT)=>{"use strict";var Yc=be(),RC=Xi(),PC=Math.floor,Wc=Yc("".charAt),kC=Yc("".replace),zc=Yc("".slice),LC=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,$C=/\$([$&'`]|\d{1,2})/g;vT.exports=function(a,e,t,i,r,s){var n=t+a.length,o=i.length,u=$C;return r!==void 0&&(r=RC(r),u=LC),kC(s,u,function(l,c){var d;switch(Wc(c,0)){case"$":return"$";case"&":return a;case"`":return zc(e,0,t);case"'":return zc(e,n);case"<":d=r[zc(c,1,-1)];break;default:var f=+c;if(f===0)return l;if(f>o){var p=PC(f/10);return p===0?l:p<=o?i[p-1]===void 0?Wc(c,1):i[p-1]+Wc(c,1):l}d=i[f-1]}return d===void 0?"":d})}});var ET=g(()=>{"use strict";var MC=pe(),DC=je(),Xc=be(),TT=Qt(),CC=ue(),BC=Ce(),VC=cT(),Pr=Fa(),_C=sa(),OC=ST(),FC=yT(),NC=Te(),qC=at(),UC=NC("replace"),jC=TypeError,Kc=Xc("".indexOf),HC=Xc("".replace),IT=Xc("".slice),QC=Math.max;MC({target:"String",proto:!0},{replaceAll:function(e,t){var i=TT(this),r,s,n,o,u,l,c,d,f,p,h=0,m="";if(BC(e)){if(r=VC(e),r&&(s=Pr(TT(OC(e))),!~Kc(s,"g")))throw new jC("`.replaceAll` does not allow non-global regexes");if(n=_C(e,UC),n)return DC(n,e,i,t);if(qC&&r)return HC(Pr(i),e,t)}for(o=Pr(i),u=Pr(e),l=CC(t),l||(t=Pr(t)),c=u.length,d=QC(1,c),f=Kc(o,u);f!==-1;)p=l?Pr(t(u,f,o)):FC(u,o,f,[],void 0,t),m+=IT(o,h,f)+p,h=f+c,f=f+d>o.length?-1:Kc(o,u,f+d);return h<o.length&&(m+=IT(o,h)),m}})});var wT=g((hG,xT)=>{"use strict";oT();uT();ET();var GC=Gt();xT.exports=GC("String","replaceAll")});var RT=g((fG,AT)=>{"use strict";var WC=wT();AT.exports=WC});var kT=g((mG,PT)=>{"use strict";var zC=RT();PT.exports=zC});var $T=g((bG,LT)=>{"use strict";var YC=la(),KC=Fa(),XC=Qt(),JC=RangeError;LT.exports=function(e){var t=KC(XC(this)),i="",r=YC(e);if(r<0||r===1/0)throw new JC("Wrong number of repetitions");for(;r>0;(r>>>=1)&&(t+=t))r&1&&(i+=t);return i}});var VT=g((gG,BT)=>{"use strict";var CT=be(),ZC=el(),MT=Fa(),eB=$T(),tB=Qt(),iB=CT(eB),rB=CT("".slice),aB=Math.ceil,DT=function(a){return function(e,t,i){var r=MT(tB(e)),s=ZC(t),n=r.length,o=i===void 0?" ":MT(i),u,l;return s<=n||o===""?r:(u=s-n,l=iB(o,aB(u/o.length)),l.length>u&&(l=rB(l,0,u)),a?r+l:l+r)}};BT.exports={start:DT(!1),end:DT(!0)}});var OT=g((SG,_T)=>{"use strict";var sB=yi();_T.exports=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(sB)});var FT=g(()=>{"use strict";var nB=pe(),oB=VT().start,uB=OT();nB({target:"String",proto:!0,forced:uB},{padStart:function(e){return oB(this,e,arguments.length>1?arguments[1]:void 0)}})});var qT=g((TG,NT)=>{"use strict";FT();var lB=Gt();NT.exports=lB("String","padStart")});var jT=g((IG,UT)=>{"use strict";var cB=qT();UT.exports=cB});var QT=g((EG,HT)=>{"use strict";var dB=jT();HT.exports=dB});var Wp="2.0.138-dev.b9cfb5f8.0";var De=(r=>(r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused",r))(De||{}),At=(y=>(y.MPEG="MPEG",y.DASH="DASH",y.DASH_SEP="DASH_SEP",y.DASH_SEP_VK="DASH_SEP",y.DASH_WEBM="DASH_WEBM",y.DASH_WEBM_AV1="DASH_WEBM_AV1",y.DASH_STREAMS="DASH_STREAMS",y.DASH_WEBM_VK="DASH_WEBM",y.DASH_ONDEMAND="DASH_ONDEMAND",y.DASH_ONDEMAND_VK="DASH_ONDEMAND",y.DASH_LIVE="DASH_LIVE",y.DASH_LIVE_CMAF="DASH_LIVE_CMAF",y.DASH_LIVE_WEBM="DASH_LIVE_WEBM",y.HLS="HLS",y.HLS_ONDEMAND="HLS_ONDEMAND",y.HLS_JS="HLS",y.HLS_FMP4="HLS_FMP4",y.HLS_LIVE="HLS_LIVE",y.HLS_LIVE_CMAF="HLS_LIVE_CMAF",y.WEB_RTC_LIVE="WEB_RTC_LIVE",y))(At||{});var ln=(r=>(r.NOT_AVAILABLE="NOT_AVAILABLE",r.AVAILABLE="AVAILABLE",r.CONNECTING="CONNECTING",r.CONNECTED="CONNECTED",r))(ln||{}),Eu=(i=>(i.HTTP1="http1",i.HTTP2="http2",i.QUIC="quic",i))(Eu||{});var xu=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(xu||{}),cn=(i=>(i.TRAFFIC_SAVING="traffic_saving",i.HIGH_QUALITY="high_quality",i.UNKNOWN="unknown",i))(cn||{});var FE=O(Ae(),1);import{assertNever as Gf,assertNonNullable as yA,isNonNullable as mn,ValueSubject as il,Subject as TA,Subscription as IA,merge as EA,observableFrom as xA,fromEvent as Uf,map as jf,tap as Hf,filterChanged as wA,isNullable as rl,ErrorCategory as Qf}from"@vkontakte/videoplayer-shared/es2018";var qf=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 bn=class{constructor(e){this.connection$=new il(void 0);this.castState$=new il("NOT_AVAILABLE");this.errorEvent$=new TA;this.realCastState$=new il("NOT_AVAILABLE");this.subscription=new IA;this.isDestroyed=!1;var s;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastInitializer");let t="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${t}`}),e.isDisabled||!t)return;let i=mn((s=window.chrome)==null?void 0:s.cast),r=!!window.__onGCastApiAvailable;i?this.initializeCastApi():(window.__onGCastApiAvailable=n=>{delete window.__onGCastApiAvailable,n&&!this.isDestroyed&&this.initializeCastApi()},r||qf("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:Qf.NETWORK,message:"Script loading failed!"})))}connect(){var e;(e=cast.framework.CastContext.getInstance())==null||e.requestSession()}disconnect(){var e,t;(t=(e=cast.framework.CastContext.getInstance())==null?void 0:e.getCurrentSession())==null||t.endSession(!0)}stopMedia(){return new Promise((e,t)=>{var i,r,s;(s=(r=(i=cast.framework.CastContext.getInstance())==null?void 0:i.getCurrentSession())==null?void 0:r.getMediaSession())==null||s.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){mn(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();rl(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();rl(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(Uf(i,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(r=>{var s,n,o;switch(r.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=(o=(n=(s=i.getCurrentSession())==null?void 0:s.getMediaSession())==null?void 0:n.media)==null?void 0:o.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return Gf(r.sessionState)}})).add(EA(Uf(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(Hf(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),jf(r=>r.castState)),xA([i.getCastState()])).pipe(wA(),jf(AA),Hf(r=>{this.log({message:`realCastState$: ${r}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{var o,u;let s=r==="CONNECTED",n=mn(this.connection$.getValue());if(s&&!n){let l=i.getCurrentSession();yA(l);let c=l.getCastDevice(),d=(u=(o=l.getMediaSession())==null?void 0:o.media)==null?void 0:u.contentId;(rl(d)||d===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:l,castDevice:c}))}else!s&&n&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(r==="CONNECTED"?mn(this.connection$.getValue())?"CONNECTED":"AVAILABLE":r)}))}initializeCastApi(){var r;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(s){return}try{e.setOptions({receiverApplicationId:(r=this.params.receiverApplicationId)!=null?r:t,autoJoinPolicy:i}),this.initListeners()}catch(s){this.errorEvent$.next({id:"ChromecastInitializer",category:Qf.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:s})}}},AA=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 Gf(a)}};var ep=O(Ae(),1),yE=O(ar(),1),TE=O(Ll(),1);var iv=O(Hn(),1);import{assertNever as qS}from"@vkontakte/videoplayer-shared/es2018";var le=(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:qS(t)}return a},zt=(a,e)=>{var t;switch(e){case 0:return NaN;case 1:{let i=new URL(a);return Number(i.searchParams.get("playback_shift"))}case 2:{let i=new URL(a);return Number((t=i.searchParams.get("offset_p"))!=null?t:0)}default:qS(e)}};var $=(a,e,t=!1)=>{let i=a.getTransition();(t||!i||i.to===e)&&a.setState(e)};import{isNonNullable as C$,Subject as Qn,merge as US}from"@vkontakte/videoplayer-shared/es2018";var j=class{constructor(e){this.transitionStarted$=new Qn;this.transitionEnded$=new Qn;this.transitionUpdated$=new Qn;this.forceChanged$=new Qn;this.stateChangeStarted$=US(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=US(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||C$(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 YS}from"@vkontakte/videoplayer-shared/es2018";var Gn=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 jS=O(Ae(),1);var Ea=()=>{var a,e;return/Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test((a=navigator.appVersion)!=null?a:navigator.userAgent)||((e=navigator==null?void 0:navigator.userAgentData)==null?void 0:e.mobile)};var Wn=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,jS.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=Ea()}catch(t){console.error(t)}this.detectDevice(e),this.detectHighEntropyValues(),this.isIOS&&this.detectIOSVersion()}async detectHighEntropyValues(){let{userAgentData:e}=navigator;if(e!=null&&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 zn=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(){var t;let{maxTouchPoints:e}=navigator;try{this._maxTouchPoints=e!=null?e:0,this._isHdr=!!((t=matchMedia("(dynamic-range: high)"))!=null&&t.matches),this._colorDepth=screen.colorDepth}catch(i){console.error(i)}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(i){console.error(i)}}};var Qe=()=>window.ManagedMediaSource||window.MediaSource,fr=()=>{var a,e;return!!(window.ManagedMediaSource&&((e=(a=window.ManagedSourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},HS=()=>{var a,e;return!!(window.MediaSource&&((e=(a=window.SourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},Yn=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;var B$=document.createElement("video"),V$='video/mp4; codecs="avc1.42000a,mp4a.40.2"',_$='video/mp4; codecs="hev1.1.6.L93.B0"',QS='video/webm; codecs="vp09.00.10.08"',GS='video/webm; codecs="av01.0.00M.08"',O$='audio/mp4; codecs="mp4a.40.2"',F$='audio/webm; codecs="opus"',WS,N$=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:GS}}),window.navigator.mediaCapabilities.decodingInfo({...a,video:{...a.video,contentType:QS}})]);WS={DASH_WEBM_AV1:e,DASH_WEBM:t}};N$().catch(a=>{console.log(B$),console.error(a)});var Kn=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 WS}get supportedCodecs(){return Object.keys(this._codecs).filter(e=>this._codecs[e])}get nativeHlsSupported(){return this._nativeHlsSupported}detect(){var e,t,i,r,s,n,o,u,l,c,d,f,p,h,m,S,b,v,T,y;this._video=document.createElement("video");try{this._protocols={mms:fr(),mse:HS(),hls:!!((t=(e=this._video).canPlayType)!=null&&t.call(e,"application/x-mpegurl")||(r=(i=this._video).canPlayType)!=null&&r.call(i,"vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},this._containers={mp4:!!((n=(s=this._video).canPlayType)!=null&&n.call(s,"video/mp4")),webm:!!((u=(o=this._video).canPlayType)!=null&&u.call(o,"video/webm")),cmaf:!0};let I=!!((c=(l=Qe())==null?void 0:l.isTypeSupported)!=null&&c.call(l,V$)),w=!!((f=(d=Qe())==null?void 0:d.isTypeSupported)!=null&&f.call(d,_$)),L=!!((h=(p=Qe())==null?void 0:p.isTypeSupported)!=null&&h.call(p,O$));this._codecs={h264:I,h265:w,vp9:!!((S=(m=Qe())==null?void 0:m.isTypeSupported)!=null&&S.call(m,QS)),av1:!!((v=(b=Qe())==null?void 0:b.isTypeSupported)!=null&&v.call(b,GS)),aac:L,opus:!!((y=(T=Qe())==null?void 0:T.isTypeSupported)!=null&&y.call(T,F$)),mpeg:(I||w)&&L},this._nativeHlsSupported=this._protocols.hls&&this._containers.mp4}catch(I){console.error(I)}try{this.destroyVideoElement()}catch(I){console.error("Error destroying video element:",I)}}destroyVideoElement(){var t;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);(t=this._video.parentNode)==null||t.replaceChild(e,this._video),this._video=null}};var zS="audio/mpeg",Xn=class{supportMp3(){return this._codecs.mp3&&this._containers.mpeg}detect(){var e,t,i,r;this._audio=document.createElement("audio");try{this._containers={mpeg:!!((t=(e=this._audio).canPlayType)!=null&&t.call(e,zS))},this._codecs={mp3:!!((r=(i=Qe())==null?void 0:i.isTypeSupported)!=null&&r.call(i,zS))}}catch(s){console.error(s)}try{this.destroyAudioElement()}catch(s){console.error("Error destroying audio element:",s)}}destroyAudioElement(){var t;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);(t=this._audio.parentNode)==null||t.replaceChild(e,this._audio),this._audio=null}};import{ValueSubject as q$}from"@vkontakte/videoplayer-shared/es2018";var bc=class{constructor(){this.isInited$=new q$(!1);this._displayChecker=new zn,this._deviceChecker=new Wn(this._displayChecker),this._browserChecker=new Gn,this._videoChecker=new Kn(this._deviceChecker,this._browserChecker),this._audioChecker=new Xn,this.detect()}get display(){return this._displayChecker}get device(){return this._deviceChecker}get browser(){return this._browserChecker}get video(){return this._videoChecker}get audio(){return this._audioChecker}async detect(){this._displayChecker.detect(),this._deviceChecker.detect(),this._browserChecker.detect(),this._videoChecker.detect(),this._audioChecker.detect(),this.isInited$.next(!0)}},F=new bc;var gc=a=>{let{containers:e,protocols:t,codecs:i,nativeHlsSupported:r}=F.video,s=(i.h264||i.h265)&&i.aac,n=t.mse||t.mms;return a.filter(o=>{switch(o){case"DASH_SEP":return n&&e.mp4&&s;case"DASH_WEBM":return n&&e.webm&&i.vp9&&i.opus;case"DASH_WEBM_AV1":return n&&e.webm&&i.av1&&i.opus;case"DASH_STREAMS":return n&&(e.mp4&&s||e.webm&&(i.vp9||i.av1)&&(i.opus||i.aac));case"DASH_LIVE":return n&&e.mp4&&s;case"DASH_LIVE_CMAF":return n&&e.mp4&&s&&e.cmaf;case"DASH_ONDEMAND":return n&&e.mp4&&s;case"HLS":case"HLS_ONDEMAND":case"HLS_FMP4":case"HLS_LIVE":case"HLS_LIVE_CMAF":return r;case"MPEG":return e.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return t.webrtc&&t.ws&&i.h264&&(e.mp4||e.webm);default:return YS(o)}})},Sc=a=>{switch(a){case"MPEG":case"DASH":case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":case"HLS":case"HLS_FMP4":case"HLS_ONDEMAND":return!1;case"DASH_LIVE":case"DASH_LIVE_CMAF":case"HLS_LIVE":case"HLS_LIVE_CMAF":case"DASH_LIVE_WEBM":case"WEB_RTC_LIVE":return!0;default:return YS(a)}},U$=a=>{let t=Object.keys(a).filter(i=>!Sc(i));return gc(t).length>0};import{assertNever as mr,assertNonNullable as Ri,debounce as KS,ErrorCategory as XS,fromEvent as Pi,isNonNullable as JS,map as ZS,merge as ev,observableFrom as j$,Subject as H$,Subscription as vc,timeout as Q$,getHighestQuality as G$}from"@vkontakte/videoplayer-shared/es2018";var W$=5,z$=5,Y$=500,tv=7e3,xa=class{constructor(e){this.subscription=new vc;this.loadMediaTimeoutSubscription=new vc;this.videoState=new j("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==null?void 0: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:mr(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:mr(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:mr(e)}break}default:mr(i)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(Sc(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 vc;this.subscription.add(e),this.subscription.add(ev(this.videoState.stateChangeStarted$.pipe(ZS(r=>`stateChangeStarted$ ${JSON.stringify(r)}`)),this.videoState.stateChangeEnded$.pipe(ZS(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 H$;e.add(r.pipe(KS(Y$)).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)>W$)&&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<z$&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),$(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:mr(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=ev(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,j$(["init"])).pipe(KS(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"),$(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),$(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(),t=this.videoState.getTransition();((t==null?void 0:t.to)==="paused"||e==="playing")&&(this.videoState.setState("paused"),$(this.params.desiredState.playbackState,"paused"))}handleRemotePlay(){let e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)==="playing"||e==="paused")&&(this.videoState.setState("playing"),$(this.params.desiredState.playbackState,"playing"))}handleRemoteReady(){var t;let e=this.videoState.getTransition();(e==null?void 0:e.to)==="ready"&&this.videoState.setState("ready"),((t=this.params.desiredState.playbackState.getTransition())==null?void 0:t.to)==="ready"&&$(this.params.desiredState.playbackState,"ready")}handleRemoteStop(){this.videoState.getState()!=="stopped"&&this.videoState.setState("stopped")}handleRemoteVolumeChange(e){var r,s;let t=this.params.output.volume$.getValue(),i={volume:(r=e.volume)!=null?r:t.volume,muted:(s=e.muted)!=null?s: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){var l;let t=this.params.source,i,r,s;switch(e){case"MPEG":{let c=t[e];Ri(c);let d=G$(Object.keys(c));Ri(d);let f=c[d];Ri(f),i=f,r="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_FMP4":case"HLS_ONDEMAND":{let c=t[e];Ri(c),i=c.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 c=t[e];Ri(c),i=c.url,r="application/dash+xml",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let c=t[e];Ri(c),i=c.url,r="application/dash+xml",s=chrome.cast.media.StreamType.LIVE;break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let c=t[e];Ri(c),i=le(c.url),r="application/x-mpegurl",s=chrome.cast.media.StreamType.LIVE;break}case"DASH_LIVE":case"WEB_RTC_LIVE":{let c="Unsupported format for Chromecast",d=new Error(c);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:XS.VIDEO_PIPELINE,message:c,thrown:d}),d}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return mr(e)}let n=new chrome.cast.media.MediaInfo((l=this.params.meta.videoId)!=null?l:i,r);n.contentUrl=i,n.streamType=s,n.metadata=new chrome.cast.media.GenericMediaMetadata;let{title:o,subtitle:u}=this.params.meta;return JS(o)&&(n.metadata.title=o),JS(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(Q$(tv).subscribe(()=>s(`timeout(${tv})`)))});(0,iv.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:XS.VIDEO_PIPELINE,message:s,thrown:r})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var Oc=O(Ae(),1);import{clearVideoElement as av}from"@vkontakte/videoplayer-shared/es2018";import{clearVideoElement as K$}from"@vkontakte/videoplayer-shared/es2018";var rv=a=>{try{a.pause(),a.playbackRate=0,K$(a),a.remove()}catch(e){console.error(e)}};import{fromEvent as X$,Subscription as J$}from"@vkontakte/videoplayer-shared/es2018";var yc=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)}},Tc=window.WeakMap?new WeakMap:new yc,Ic=window.WeakMap?new WeakMap:new Map,Z$=(a,e=20)=>{let t=0;return X$(a,"ratechange").subscribe(i=>{t++,t>=e&&(a.currentTime=a.currentTime,t=0)})},Be=(a,{audioVideoSyncRate:e,disableYandexPiP:t})=>{let i=a.querySelector("video"),r=!!i;i?av(i):(i=document.createElement("video"),a.appendChild(i)),Tc.set(i,r);let s=new J$;return s.add(Z$(i,e)),Ic.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},Ve=a=>{let e=Ic.get(a);e==null||e.unsubscribe(),Ic.delete(a);let t=Tc.get(a);Tc.delete(a),t?av(a):rv(a)};var xc=O(br(),1);import{assertNonNullable as Aa,isNonNullable as gt,isNullable as oM,fromEvent as gr,merge as dv,observableFrom as pv,filterChanged as hv,map as Ra,Subject as fv,Subscription as uM,ValueSubject as lM,ErrorCategory as cM}from"@vkontakte/videoplayer-shared/es2018";import{isNonNullable as Ec,isNullable as sM,Subscription as nM}from"@vkontakte/videoplayer-shared/es2018";var Jn=(a,e,t,{equal:i=(n,o)=>n===o,changed$:r,onError:s}={})=>{let n=a.getState(),o=e(),u=sM(r),l=new nM;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},bt=(a,e,t)=>Jn(e,()=>a.loop,i=>{Ec(i)&&(a.loop=i)},{onError:t}),_e=(a,e,t,i)=>Jn(e,()=>({muted:a.muted,volume:a.volume}),r=>{Ec(r)&&(a.muted=r.muted,a.volume=r.volume)},{equal:(r,s)=>r===s||(r==null?void 0:r.muted)===(s==null?void 0:s.muted)&&(r==null?void 0:r.volume)===(s==null?void 0:s.volume),changed$:t,onError:i}),Ke=(a,e,t,i)=>Jn(e,()=>a.playbackRate,r=>{Ec(r)&&(a.playbackRate=r)},{changed$:t,onError:i}),wa=Jn;var dM=a=>["__",a.language,a.label].join("|"),pM=(a,e)=>{if(a.id===e)return!0;let[t,i,r]=e.split("|");return a.language===i&&a.label===r},wc=class a{constructor(e){this.available$=new fv;this.current$=new lM(void 0);this.error$=new fv;this.subscription=new uM;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:cM.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(wa(t.internalTextTracks,()=>(0,xc.default)(this.internalTracks),s=>{gt(s)&&this.setInternal(s)},{equal:(s,n)=>gt(s)&&gt(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(Ra(s=>s.filter(({type:n})=>n==="internal"))),onError:r})),this.subscription.add(wa(t.externalTextTracks,()=>(0,xc.default)(this.externalTracks),s=>{gt(s)&&this.setExternal(s)},{equal:(s,n)=>gt(s)&&gt(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(Ra(s=>s.filter(({type:n})=>n==="external"))),onError:r})),this.subscription.add(wa(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(wa(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.activeCues)}))}subscribe(){Aa(this.video);let{textTracks:e}=this.video;this.subscription.add(gr(e,"addtrack").subscribe(()=>{let i=this.current$.getValue();i&&this.select(i)})),this.subscription.add(dv(gr(e,"addtrack"),gr(e,"removetrack"),pv(["init"])).pipe(Ra(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),hv((i,r)=>i.length===r.length&&i.every(({id:s},n)=>s===r[n].id))).subscribe(this.available$)),this.subscription.add(dv(gr(e,"change"),pv(["init"])).pipe(Ra(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),Ra(i=>i&&this.htmlTextTrackToITextTrack(i).id),hv()).subscribe(this.current$));let t=i=>{var r,s;return this.applyCueSettings((s=(r=i.target)==null?void 0:r.activeCues)!=null?s:null)};this.subscription.add(gr(e,"addtrack").subscribe(i=>{var s,n;(s=i.track)==null||s.addEventListener("cuechange",t);let r=o=>{var l,c,d,f,p;let u=(c=(l=o.target)==null?void 0:l.cues)!=null?c:null;u&&u.length&&(this.applyCueSettings((f=(d=o.target)==null?void 0:d.cues)!=null?f:null),(p=o.target)==null||p.removeEventListener("cuechange",r))};(n=i.track)==null||n.addEventListener("cuechange",r)})),this.subscription.add(gr(e,"removetrack").subscribe(i=>{var r;(r=i.track)==null||r.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;gt(t.align)&&(r.align=t.align),gt(t.position)&&(r.position=t.position),gt(t.size)&&(r.size=t.size),gt(t.line)&&(r.line=t.line)}}htmlTextTracksAsArray(e=!1){Aa(this.video);let t=[...this.video.textTracks];return e?t:t.filter(a.isHealthyTrack)}htmlTextTrackToITextTrack(e){var o,u,l,c,d;let{language:t,label:i}=e,r=e.id?e.id:dM(e),s=this.externalTracks.has(r),n=(l=s?(o=this.externalTracks.get(r))==null?void 0:o.isAuto:(u=this.internalTracks.get(r))==null?void 0:u.isAuto)!=null?l:r.includes("auto");return s?{id:r,type:"external",isAuto:n,language:t,label:i,url:(c=this.externalTracks.get(r))==null?void 0:c.url}:{id:r,type:"internal",isAuto:n,language:t,label:i,url:(d=this.internalTracks.get(r))==null?void 0:d.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){Aa(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(oM(e)||!pM(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){Aa(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){Aa(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)}},Xe=wc;var ki=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 mv=a=>{let e=a;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e==null?void 0:e.parentNode;return e!=null?e:void 0},Ac=a=>{let e=mv(a);return!!(e&&e.fullscreenElement&&e.fullscreenElement===a)},bv=a=>{let e=mv(a);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===a)};import{fromEvent as Re,map as St,merge as Zn,filterChanged as Sv,isNonNullable as vv,Subject as fM,filter as Rc,mapTo as Pc,combine as mM,once as bM,shareReplay as Pe,throttle as gM,ErrorCategory as SM,ValueSubject as yv,Subscription as vM}from"@vkontakte/videoplayer-shared/es2018";var hM=3,gv=(a,e,t=hM)=>{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 Oe=a=>{let e=P=>Re(a,P).pipe(Pc(void 0),Pe(1)),t=new vM,i=()=>t.unsubscribe(),r=Zn(Re(a,"progress"),Re(a,"timeupdate")).pipe(St(()=>gv(a.buffered,a.currentTime)),Pe(1)),s=F.browser.isSafari?mM({play:e("play").pipe(bM()),playing:e("playing")}).pipe(Pc(void 0),Pe(1)):e("playing"),n=Re(a,"volumechange").pipe(St(()=>({muted:a.muted,volume:a.volume})),Pe(1)),o=Re(a,"ratechange").pipe(St(()=>a.playbackRate),Pe(1)),u=Re(a,"error").pipe(Rc(()=>!!(a.error||a.played.length)),St(()=>{var V;let P=a.error;return{id:P?`MediaError#${P.code}`:"HtmlVideoError",category:SM.VIDEO_PIPELINE,message:P?P.message:"Error event from HTML video element",thrown:(V=a.error)!=null?V:void 0}}),Pe(1)),l=Re(a,"timeupdate").pipe(St(()=>a.currentTime),Pe(1)),c=["waiting","seeking","seeked","timeupdate"],d=new fM,f=.3,p;t.add(Zn(...c.map(P=>Re(a,P))).subscribe(P=>{let V=a.currentTime;a.loop&&vv(p)&&vv(V)&&p>=a.duration-f&&V<=f&&d.next(p),p=V}));let h=e("pause").pipe(Rc(()=>!a.error&&p!==a.duration),Pe(1)),m=Re(a,"enterpictureinpicture").pipe(Pe(1)),S=Re(a,"leavepictureinpicture").pipe(Pe(1)),b=new yv(bv(a));t.add(m.subscribe(()=>b.next(!0))),t.add(S.subscribe(()=>b.next(!1)));let v=new yv(Ac(a)),T=Re(a,"fullscreenchange").pipe(Pe(1));t.add(T.pipe(St(()=>Ac(a))).subscribe(v));let y=.1,I=1e3,w=Re(a,"timeupdate").pipe(St(P=>a.duration-a.currentTime<y),Sv(),Pe(1)),L=Zn(w.pipe(Rc(P=>!a.loop&&P)),Re(a,"ended")).pipe(gM(I),Pc(void 0),Pe(1)),R=Zn(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(P=>Re(a,P)),w.pipe(St(P=>({type:P?"ended":"unknown"})))).pipe(St(P=>F.browser.isFirefox&&P.type==="ended"?a.readyState<2:a.readyState<3),Sv(),Pe(1));return{playing$:s,pause$:h,canplay$:e("canplay"),ended$:L,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$:Re(a,"durationchange").pipe(St(()=>a.duration),Pe(1)),isBuffering$:R,currentBuffer$:r,volumeState$:n,playbackRateState$:o,inPiP$:b,inFullscreen$:v,enterPip$:m,leavePip$:S,destroy:i}};import{VideoQuality as Yt}from"@vkontakte/videoplayer-shared/es2018";var Kt=a=>{switch(a){case"mobile":return Yt.Q_144P;case"lowest":return Yt.Q_240P;case"low":return Yt.Q_360P;case"sd":case"medium":return Yt.Q_480P;case"hd":case"high":return Yt.Q_720P;case"fullhd":case"full":return Yt.Q_1080P;case"quadhd":case"quad":return Yt.Q_1440P;case"ultrahd":case"ultra":return Yt.Q_2160P}};var Le=O(ot(),1),$c=O(Ae(),1),Li=O(ar(),1);import{isNonNullable as X,isNullable as ao,now as Vv,isHigher as so,isHigherOrEqual as vr,isInvariantQuality as no,isLowerOrEqual as yr,videoSizeToQuality as _v,assertNotEmptyArray as oo,assertNonNullable as Ov}from"@vkontakte/videoplayer-shared/es2018";var kc=!1,Lt={},Rv=a=>{kc=a},Pv=()=>{Lt={}},kv=a=>{a(Lt)},Pa=(a,e)=>{var t;kc&&(Lt.meta=(t=Lt.meta)!=null?t:{},Lt.meta[a]=e)},ke=class{constructor(e){this.name=e}next(e){var i,r;if(!kc)return;Lt.series=(i=Lt.series)!=null?i:{};let t=(r=Lt.series[this.name])!=null?r:[];t.push([Date.now(),e]),Lt.series[this.name]=t}};import{isHigher as PM,isHigherOrEqual as pU,isLower as Lv,isLowerOrEqual as hU,isNonNullable as eo,isNullable as kM,videoHeightToQuality as to}from"@vkontakte/videoplayer-shared/es2018";function Lc(a,e,t){return!a.max&&a.min===e?"high_quality":!a.min&&a.max===t?"traffic_saving":"unknown"}function io(a,e,t){return!!a&&Lc(a,e,t)==="high_quality"}function Sr(a,e,t){return kM(a)||eo(a.min)&&eo(a.max)&&Lv(a.max,a.min)||eo(a.min)&&e&&PM(a.min,e)||eo(a.max)&&t&&Lv(a.max,t)}function $v({limits:a,highestAvailableHeight:e,lowestAvailableHeight:t}){return Sr({max:a!=null&&a.max?to(a.max):void 0,min:a!=null&&a.min?to(a.min):void 0},e?to(e):void 0,t?to(t):void 0)}var Fv=new ke("best_bitrate"),uo=(a,e,t)=>(e-t)*Math.pow(2,-10*a)+t;var Tr=a=>(e,t)=>a*(Number(e.bitrate)-Number(t.bitrate)),Xt=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=Vv()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},lo='Assertion "ABR Tracks is empty array" failed',ro=new WeakMap,Mv=new WeakMap,Dv=new WeakMap,ka=(a,e,t,i)=>{var u;let r=[...e].sort(Tr(1)),s=[...t].sort(Tr(1)),n=s.filter(l=>X(l.bitrate)&&X(a.bitrate)?a.bitrate/l.bitrate>i:!0),o=(u=(0,Le.default)(s,Math.round(s.length*r.indexOf(a)/(r.length+1))))!=null?u:(0,Le.default)(s,-1);return o&&(0,$c.default)(n,o)?o:n.length?(0,Le.default)(n,-1):(0,Le.default)(s,0)},La=(a,e,t,i)=>{var u;let r=ro.get(e);r||(r=[...e].sort(Tr(1)),ro.set(e,r));let s=ro.get(t);s||(s=[...t].sort(Tr(1)),ro.set(t,s));let n=Dv.get(a);n||(n=s.filter(l=>X(l.bitrate)&&X(a.bitrate)?a.bitrate/l.bitrate>i:!0),Dv.set(a,n));let o=(u=(0,Le.default)(s,Math.round(s.length*r.indexOf(a)/(r.length+1))))!=null?u:(0,Le.default)(s,-1);return o&&(0,$c.default)(n,o)?o:n.length?(0,Le.default)(n,-1):(0,Le.default)(s,0)},Cv=a=>"quality"in a,co=(a,e,t,i)=>{var n;let r=X((n=i==null?void 0:i.last)==null?void 0:n.bitrate)&&X(t==null?void 0:t.bitrate)&&i.last.bitrate<t.bitrate?a.trackCooldownIncreaseQuality:a.trackCooldownDecreaseQuality,s=t&&i&&i.history[t.id]&&Vv()-i.history[t.id]<=r&&(!i.last||t.id!==i.last.id);if(t!=null&&t.id&&i&&!s&&i.recordSelection(t),s&&(i!=null&&i.last)){let o=i.last;i==null||i.recordSwitch(o);let u=Cv(o)?"video":"audio",l=Cv(o)?o.quality:o.bitrate;return e({message:`
8
8
  [last ${u} selected] ${l}
9
- `}),o}return i==null||i.recordSwitch(t),t},LM=(a,e)=>Math.log(e)/Math.log(a),OS=({tuning:a,container:e,limits:t,panelSize:i})=>{let r=a.containerSizeFactor;if(i)return{containerSizeLimit:i,containerSizeFactor:r};if(a.usePixelRatio&&F.display.pixelRatio){let s=F.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=LM(n,o*s+u)+l;Number.isFinite(c)&&(r*=c)}}return zn(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}},DS=new WeakMap,St=(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:f,stallsPredictedThroughput:p,abrLogger:h,panelSize:m})=>{var _,K,J,I,R;Zn(a,to);let{containerSizeFactor:v,containerSizeLimit:b}=OS({container:e,tuning:i,limits:r,panelSize:m}),S=i.considerPlaybackRate&&X(o)?o:1,T=DS.get(a);T||(T=a.filter(x=>!Jn(x.quality)).sort((x,w)=>Xn(x.quality,w.quality)?-1:1),DS.set(a,T));let y=(_=(0,Le.default)(T,-1))==null?void 0:_.quality,E=(K=(0,Le.default)(T,0))==null?void 0:K.quality,k=br(r,E,y),M=S*eo(n!=null?n:.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),$={},A=null;for(let x of T){let w=!0;if(b)if(x.size)w=x.size.width<=b.width&&x.size.height<=b.height;else{let qe=b&&BS(b);w=qe?vr(x.quality,qe):!0}if(!w){$[x.quality]="FitsContainer";continue}let B=p||t,ne=X(B)&&isFinite(B)&&X(x.bitrate)?B-s>=x.bitrate*M:!0,Ne=zn(r,i.highQualityLimit,i.trafficSavingLimit)&&(r==null?void 0:r.min)===x.quality;if(!ne&&!Ne){$[x.quality]="FitsThroughput";continue}if(i.lazyQualitySwitch&&X(i.minBufferToSwitchUp)&&u&&!Jn(u.quality)&&(n!=null?n:0)<i.minBufferToSwitchUp&&Xn(x.quality,u.quality)){$[x.quality]="Buffer";continue}if(!!d&&gr(x.quality,d)&&!Ne){$[x.quality]="DroppedFramesLimit";continue}if(!!f&&gr(x.quality,f)&&!Ne){$[x.quality]="StallsLimit";continue}let ve=k||(Kn(r==null?void 0:r.max)||vr(x.quality,r.max))&&(Kn(r==null?void 0:r.min)||gr(x.quality,r.min)),Se=X(c)&&!c?vr(x.quality,i.backgroundVideoQualityLimit):!0;if(!ve||!Se){$[x.quality]="FitsQualityLimits";continue}A||(A=x)}A&&A.bitrate&&_S.next(A.bitrate);let P=(J=A!=null?A:(0,Le.default)(T,-1))!=null?J:a[0],V=l==null?void 0:l.last,D=io(i,h,P,l);return X(l)&&D.quality!==(V==null?void 0:V.quality)&&h({message:`
9
+ `}),o}return i==null||i.recordSwitch(t),t},LM=(a,e)=>Math.log(e)/Math.log(a),Nv=({tuning:a,container:e,limits:t,panelSize:i})=>{let r=a.containerSizeFactor;if(i)return{containerSizeLimit:i,containerSizeFactor:r};if(a.usePixelRatio&&F.display.pixelRatio){let s=F.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=LM(n,o*s+u)+l;Number.isFinite(c)&&(r*=c)}}return io(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}},Bv=new WeakMap,vt=(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:f,stallsPredictedThroughput:p,abrLogger:h,panelSize:m})=>{var _,K,J,E,k;oo(a,lo);let{containerSizeFactor:S,containerSizeLimit:b}=Nv({container:e,tuning:i,limits:r,panelSize:m}),v=i.considerPlaybackRate&&X(o)?o:1,T=Bv.get(a);T||(T=a.filter(x=>!no(x.quality)).sort((x,A)=>so(x.quality,A.quality)?-1:1),Bv.set(a,T));let y=(_=(0,Le.default)(T,-1))==null?void 0:_.quality,I=(K=(0,Le.default)(T,0))==null?void 0:K.quality,w=Sr(r,I,y),L=v*uo(n!=null?n:.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),M={},R=null;for(let x of T){let A=!0;if(b)if(x.size)A=x.size.width<=b.width&&x.size.height<=b.height;else{let qe=b&&_v(b);A=qe?yr(x.quality,qe):!0}if(!A){M[x.quality]="FitsContainer";continue}let B=p||t,ne=X(B)&&isFinite(B)&&X(x.bitrate)?B-s>=x.bitrate*L:!0,Ne=io(r,i.highQualityLimit,i.trafficSavingLimit)&&(r==null?void 0:r.min)===x.quality;if(!ne&&!Ne){M[x.quality]="FitsThroughput";continue}if(i.lazyQualitySwitch&&X(i.minBufferToSwitchUp)&&u&&!no(u.quality)&&(n!=null?n:0)<i.minBufferToSwitchUp&&so(x.quality,u.quality)){M[x.quality]="Buffer";continue}if(!!d&&vr(x.quality,d)&&!Ne){M[x.quality]="DroppedFramesLimit";continue}if(!!f&&vr(x.quality,f)&&!Ne){M[x.quality]="StallsLimit";continue}let ve=w||(ao(r==null?void 0:r.max)||yr(x.quality,r.max))&&(ao(r==null?void 0:r.min)||vr(x.quality,r.min)),ye=X(c)&&!c?yr(x.quality,i.backgroundVideoQualityLimit):!0;if(!ve||!ye){M[x.quality]="FitsQualityLimits";continue}R||(R=x)}R&&R.bitrate&&Fv.next(R.bitrate);let P=(J=R!=null?R:(0,Le.default)(T,-1))!=null?J:a[0],V=l==null?void 0:l.last,D=co(i,h,P,l);return X(l)&&D.quality!==(V==null?void 0:V.quality)&&h({message:`
10
10
  [VIDEO TRACKS ABR]
11
11
  [available video tracks]
12
- ${a.map(x=>{var w,B;return`{ id: ${x.id}, quality: ${x.quality}, bitrate: ${x.bitrate}, size: ${(w=x.size)==null?void 0:w.width}:${(B=x.size)==null?void 0:B.height} }`}).join(`
12
+ ${a.map(x=>{var A,B;return`{ id: ${x.id}, quality: ${x.quality}, bitrate: ${x.bitrate}, size: ${(A=x.size)==null?void 0:A.width}:${(B=x.size)==null?void 0:B.height} }`}).join(`
13
13
  `)}
14
14
 
15
15
  [tuning]
16
- ${(0,Ri.default)(i!=null?i:{}).map(([x,w])=>`${x}: ${w}`).join(`
16
+ ${(0,Li.default)(i!=null?i:{}).map(([x,A])=>`${x}: ${A}`).join(`
17
17
  `)}
18
18
 
19
19
  [limit params]
20
- containerSizeFactor: ${v},
21
- containerSizeLimit: ${(I=b==null?void 0:b.width)!=null?I:0} x ${(R=b==null?void 0:b.height)!=null?R:0},
20
+ containerSizeFactor: ${S},
21
+ containerSizeLimit: ${(E=b==null?void 0:b.width)!=null?E:0} x ${(k=b==null?void 0:b.height)!=null?k:0},
22
22
  estimatedThroughput: ${t},
23
23
  stallsPredictedThroughput: ${p},
24
24
  reserve: ${s},
25
25
  playbackRate: ${o},
26
- playbackRateFactor: ${S},
26
+ playbackRateFactor: ${v},
27
27
  forwardBufferHealth: ${n},
28
- bitrateFactor: ${M},
28
+ bitrateFactor: ${L},
29
29
  minBufferToSwitchUp: ${i.minBufferToSwitchUp},
30
30
  droppedVideoMaxQualityLimit: ${d},
31
31
  stallsVideoMaxQualityLimit: ${f},
32
- limitsAreInvalid: ${k},
32
+ limitsAreInvalid: ${w},
33
33
  maxQualityLimit: ${r==null?void 0:r.max},
34
34
  minQualityLimit: ${r==null?void 0:r.min},
35
35
 
36
36
  [limited video tracks]
37
- ${(0,Ri.default)($).map(([x,w])=>`${x}: ${w}`).join(`
37
+ ${(0,Li.default)(M).map(([x,A])=>`${x}: ${A}`).join(`
38
38
  `)||"All tracks are available"}
39
39
 
40
- [best video track] ${A==null?void 0:A.quality}
40
+ [best video track] ${R==null?void 0:R.quality}
41
41
  [selected video track] ${D==null?void 0:D.quality}
42
- `}),D},ro=(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:f,stallsPredictedThroughput:p,abrLogger:h,panelSize:m})=>{var K,J,I,R,x;Zn(a,to);let{containerSizeFactor:v,containerSizeLimit:b}=OS({container:e,tuning:i,limits:r,panelSize:m}),S=i.considerPlaybackRate&&X(o)?o:1,T=a.filter(w=>!Jn(w.quality)).sort((w,B)=>Xn(w.quality,B.quality)?-1:1),y=(K=(0,Le.default)(T,-1))==null?void 0:K.quality,E=(J=(0,Le.default)(T,0))==null?void 0:J.quality,k=br(r,E,y),M=S*eo(n!=null?n:.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),$={},P=T.filter(w=>{let B=!0;if(b)if(w.size)B=w.size.width<=b.width&&w.size.height<=b.height;else{let xt=b&&BS(b);B=xt?vr(w.quality,xt):!0}if(!B)return $[w.quality]="FitsContainer",!1;let ne=p||t,Ne=X(ne)&&isFinite(ne)&&X(w.bitrate)?ne-s>=w.bitrate*M:!0,ie=zn(r,i.highQualityLimit,i.trafficSavingLimit)&&(r==null?void 0:r.min)===w.quality;if(!Ne&&!ie)return $[w.quality]="FitsThroughput",!1;if(i.lazyQualitySwitch&&X(i.minBufferToSwitchUp)&&u&&!Jn(u.quality)&&(n!=null?n:0)<i.minBufferToSwitchUp&&Xn(w.quality,u.quality))return $[w.quality]="Buffer",!1;if(!!d&&gr(w.quality,d)&&!ie)return $[w.quality]="DroppedFramesLimit",!1;if(!!f&&gr(w.quality,f)&&!ie)return $[w.quality]="StallsLimit",!1;let Se=k||(Kn(r==null?void 0:r.max)||vr(w.quality,r.max))&&(Kn(r==null?void 0:r.min)||gr(w.quality,r.min)),qe=X(c)&&!c?vr(w.quality,i.backgroundVideoQualityLimit):!0;return!Se||!qe?($[w.quality]="FitsQualityLimits",!1):!0})[0];P&&P.bitrate&&_S.next(P.bitrate);let V=(I=P!=null?P:(0,Le.default)(T,-1))!=null?I:a[0],D=l==null?void 0:l.last,_=io(i,h,V,l);return X(l)&&_.quality!==(D==null?void 0:D.quality)&&h({message:`
42
+ `}),D},po=(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:f,stallsPredictedThroughput:p,abrLogger:h,panelSize:m})=>{var K,J,E,k,x;oo(a,lo);let{containerSizeFactor:S,containerSizeLimit:b}=Nv({container:e,tuning:i,limits:r,panelSize:m}),v=i.considerPlaybackRate&&X(o)?o:1,T=a.filter(A=>!no(A.quality)).sort((A,B)=>so(A.quality,B.quality)?-1:1),y=(K=(0,Le.default)(T,-1))==null?void 0:K.quality,I=(J=(0,Le.default)(T,0))==null?void 0:J.quality,w=Sr(r,I,y),L=v*uo(n!=null?n:.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),M={},P=T.filter(A=>{let B=!0;if(b)if(A.size)B=A.size.width<=b.width&&A.size.height<=b.height;else{let xt=b&&_v(b);B=xt?yr(A.quality,xt):!0}if(!B)return M[A.quality]="FitsContainer",!1;let ne=p||t,Ne=X(ne)&&isFinite(ne)&&X(A.bitrate)?ne-s>=A.bitrate*L:!0,ie=io(r,i.highQualityLimit,i.trafficSavingLimit)&&(r==null?void 0:r.min)===A.quality;if(!Ne&&!ie)return M[A.quality]="FitsThroughput",!1;if(i.lazyQualitySwitch&&X(i.minBufferToSwitchUp)&&u&&!no(u.quality)&&(n!=null?n:0)<i.minBufferToSwitchUp&&so(A.quality,u.quality))return M[A.quality]="Buffer",!1;if(!!d&&vr(A.quality,d)&&!ie)return M[A.quality]="DroppedFramesLimit",!1;if(!!f&&vr(A.quality,f)&&!ie)return M[A.quality]="StallsLimit",!1;let ye=w||(ao(r==null?void 0:r.max)||yr(A.quality,r.max))&&(ao(r==null?void 0:r.min)||vr(A.quality,r.min)),qe=X(c)&&!c?yr(A.quality,i.backgroundVideoQualityLimit):!0;return!ye||!qe?(M[A.quality]="FitsQualityLimits",!1):!0})[0];P&&P.bitrate&&Fv.next(P.bitrate);let V=(E=P!=null?P:(0,Le.default)(T,-1))!=null?E:a[0],D=l==null?void 0:l.last,_=co(i,h,V,l);return X(l)&&_.quality!==(D==null?void 0:D.quality)&&h({message:`
43
43
  [VIDEO TRACKS ABR]
44
44
  [available video tracks]
45
- ${a.map(w=>{var B,ne;return`{ id: ${w.id}, quality: ${w.quality}, bitrate: ${w.bitrate}, size: ${(B=w.size)==null?void 0:B.width}:${(ne=w.size)==null?void 0:ne.height} }`}).join(`
45
+ ${a.map(A=>{var B,ne;return`{ id: ${A.id}, quality: ${A.quality}, bitrate: ${A.bitrate}, size: ${(B=A.size)==null?void 0:B.width}:${(ne=A.size)==null?void 0:ne.height} }`}).join(`
46
46
  `)}
47
47
 
48
48
  [tuning]
49
- ${(0,Ri.default)(i!=null?i:{}).map(([w,B])=>`${w}: ${B}`).join(`
49
+ ${(0,Li.default)(i!=null?i:{}).map(([A,B])=>`${A}: ${B}`).join(`
50
50
  `)}
51
51
 
52
52
  [limit params]
53
- containerSizeFactor: ${v},
54
- containerSizeLimit: ${(R=b==null?void 0:b.width)!=null?R:0} x ${(x=b==null?void 0:b.height)!=null?x:0},
53
+ containerSizeFactor: ${S},
54
+ containerSizeLimit: ${(k=b==null?void 0:b.width)!=null?k:0} x ${(x=b==null?void 0:b.height)!=null?x:0},
55
55
  estimatedThroughput: ${t},
56
56
  stallsPredictedThroughput: ${p},
57
57
  reserve: ${s},
58
58
  playbackRate: ${o},
59
- playbackRateFactor: ${S},
59
+ playbackRateFactor: ${v},
60
60
  forwardBufferHealth: ${n},
61
- bitrateFactor: ${M},
61
+ bitrateFactor: ${L},
62
62
  minBufferToSwitchUp: ${i.minBufferToSwitchUp},
63
63
  droppedVideoMaxQualityLimit: ${d},
64
64
  stallsVideoMaxQualityLimit: ${f},
65
- limitsAreInvalid: ${k},
65
+ limitsAreInvalid: ${w},
66
66
  maxQualityLimit: ${r==null?void 0:r.max},
67
67
  minQualityLimit: ${r==null?void 0:r.min},
68
68
 
69
69
  [limited video tracks]
70
- ${(0,Ri.default)($).map(([w,B])=>`${w}: ${B}`).join(`
70
+ ${(0,Li.default)(M).map(([A,B])=>`${A}: ${B}`).join(`
71
71
  `)||"All tracks are available"}
72
72
 
73
73
  [best video track] ${P==null?void 0:P.quality}
74
74
  [selected video track] ${_==null?void 0:_.quality}
75
- `}),_},ao=(a,e,t,{estimatedThroughput:i,tuning:r,playbackRate:s,forwardBufferHealth:n,history:o,abrLogger:u,stallsPredictedThroughput:l})=>{Zn(t,to);let c=r.considerPlaybackRate&&X(s)?s:1,d=[...t].sort(Sr(-1)),f=a.bitrate;VS(f);let p=c*eo(n!=null?n:.5,r.bitrateAudioFactorAtEmptyBuffer,r.bitrateAudioFactorAtFullBuffer),h,m=ka(a,e,t,r.minVideoAudioRatio),v=l||i;X(v)&&isFinite(v)&&(h=d.find(T=>X(T.bitrate)&&X(m==null?void 0:m.bitrate)?v-f>=T.bitrate*p&&T.bitrate>=m.bitrate:!1)),h||(h=m);let b=o==null?void 0:o.last,S=h&&io(r,u,h,o);return X(o)&&(S==null?void 0:S.bitrate)!==(b==null?void 0:b.bitrate)&&u({message:`
75
+ `}),_},ho=(a,e,t,{estimatedThroughput:i,tuning:r,playbackRate:s,forwardBufferHealth:n,history:o,abrLogger:u,stallsPredictedThroughput:l})=>{oo(t,lo);let c=r.considerPlaybackRate&&X(s)?s:1,d=[...t].sort(Tr(-1)),f=a.bitrate;Ov(f);let p=c*uo(n!=null?n:.5,r.bitrateAudioFactorAtEmptyBuffer,r.bitrateAudioFactorAtFullBuffer),h,m=ka(a,e,t,r.minVideoAudioRatio),S=l||i;X(S)&&isFinite(S)&&(h=d.find(T=>X(T.bitrate)&&X(m==null?void 0:m.bitrate)?S-f>=T.bitrate*p&&T.bitrate>=m.bitrate:!1)),h||(h=m);let b=o==null?void 0:o.last,v=h&&co(r,u,h,o);return X(o)&&(v==null?void 0:v.bitrate)!==(b==null?void 0:b.bitrate)&&u({message:`
76
76
  [AUDIO TRACKS ABR]
77
77
  [available audio tracks]
78
78
  ${t.map(T=>`{ id: ${T.id}, bitrate: ${T.bitrate} }`).join(`
79
79
  `)}
80
80
 
81
81
  [tuning]
82
- ${(0,Ri.default)(r!=null?r:{}).map(([T,y])=>`${T}: ${y}`).join(`
82
+ ${(0,Li.default)(r!=null?r:{}).map(([T,y])=>`${T}: ${y}`).join(`
83
83
  `)}
84
84
 
85
85
  [limit params]
@@ -92,15 +92,15 @@ var GE=Object.create;var jp=Object.defineProperty;var zE=Object.getOwnPropertyDe
92
92
  bitrateFactor: ${p},
93
93
  minBufferToSwitchUp: ${r.minBufferToSwitchUp},
94
94
 
95
- [selected audio track] ${S==null?void 0:S.id}
96
- `}),S},so=(a,e,t,{estimatedThroughput:i,tuning:r,playbackRate:s,forwardBufferHealth:n,history:o,abrLogger:u,stallsPredictedThroughput:l})=>{Zn(t,to);let c=r.considerPlaybackRate&&X(s)?s:1,d=LS.get(t);d||(d=[...t].sort(Sr(-1)),LS.set(t,d));let f=a.bitrate;VS(f);let p=c*eo(n!=null?n:.5,r.bitrateAudioFactorAtEmptyBuffer,r.bitrateAudioFactorAtFullBuffer),h,m=La(a,e,t,r.minVideoAudioRatio),v=l||i;X(v)&&isFinite(v)&&(h=d.find(T=>X(T.bitrate)&&X(m==null?void 0:m.bitrate)?v-f>=T.bitrate*p&&T.bitrate>=m.bitrate:!1)),h||(h=m);let b=o==null?void 0:o.last,S=h&&io(r,u,h,o);return X(o)&&(S==null?void 0:S.bitrate)!==(b==null?void 0:b.bitrate)&&u({message:`
95
+ [selected audio track] ${v==null?void 0:v.id}
96
+ `}),v},fo=(a,e,t,{estimatedThroughput:i,tuning:r,playbackRate:s,forwardBufferHealth:n,history:o,abrLogger:u,stallsPredictedThroughput:l})=>{oo(t,lo);let c=r.considerPlaybackRate&&X(s)?s:1,d=Mv.get(t);d||(d=[...t].sort(Tr(-1)),Mv.set(t,d));let f=a.bitrate;Ov(f);let p=c*uo(n!=null?n:.5,r.bitrateAudioFactorAtEmptyBuffer,r.bitrateAudioFactorAtFullBuffer),h,m=La(a,e,t,r.minVideoAudioRatio),S=l||i;X(S)&&isFinite(S)&&(h=d.find(T=>X(T.bitrate)&&X(m==null?void 0:m.bitrate)?S-f>=T.bitrate*p&&T.bitrate>=m.bitrate:!1)),h||(h=m);let b=o==null?void 0:o.last,v=h&&co(r,u,h,o);return X(o)&&(v==null?void 0:v.bitrate)!==(b==null?void 0:b.bitrate)&&u({message:`
97
97
  [AUDIO TRACKS ABR]
98
98
  [available audio tracks]
99
99
  ${t.map(T=>`{ id: ${T.id}, bitrate: ${T.bitrate} }`).join(`
100
100
  `)}
101
101
 
102
102
  [tuning]
103
- ${(0,Ri.default)(r!=null?r:{}).map(([T,y])=>`${T}: ${y}`).join(`
103
+ ${(0,Li.default)(r!=null?r:{}).map(([T,y])=>`${T}: ${y}`).join(`
104
104
  `)}
105
105
 
106
106
  [limit params]
@@ -113,15 +113,15 @@ var GE=Object.create;var jp=Object.defineProperty;var zE=Object.getOwnPropertyDe
113
113
  bitrateFactor: ${p},
114
114
  minBufferToSwitchUp: ${r.minBufferToSwitchUp},
115
115
 
116
- [selected audio track] ${S==null?void 0:S.id}
117
- `}),S};var Te=a=>new URL(a).hostname;import{assertNever as YS,assertNonNullable as KS,combine as XM,debounce as JM,ErrorCategory as XS,filter as JS,filterChanged as ZM,isNonNullable as Lc,map as lo,merge as ZS,observableFrom as eD,once as tD,Subscription as iD,ValueSubject as $c,videoQualityToHeight as ey,videoSizeToQuality as rD}from"@vkontakte/videoplayer-shared/es2018";var QS=O(ot(),1);var NS=O(Ae(),1),FS=a=>{if(a instanceof DOMException&&(0,NS.default)(["Failed to load because no supported source was found.","The element has no supported sources."],a.message))throw a;return!(a instanceof DOMException&&(a.code===20||a.name==="AbortError"))},_e=async(a,e)=>{let t=a.muted;try{await a.play()}catch(i){if(!FS(i))return!1;if(e&&e(),t)return console.warn(i),!1;a.muted=!0;try{await a.play()}catch(r){return FS(r)&&(a.muted=!1,console.warn(r)),!1}}return!0};import{isNonNullable as oo,isNullable as DM,assertNonNullable as Da}from"@vkontakte/videoplayer-shared/es2018";var US=O(fr(),1);import{isNonNullable as qS,assertNonNullable as no,now as $M}from"@vkontakte/videoplayer-shared/es2018";function me(){return $M()}function Ac(a){return me()-a}function Pc(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 HS(a,e,t){let i=(...r)=>{t.apply(null,r),a.removeEventListener(e,i)};a.addEventListener(e,i)}function yr(a,e,t,i){let r=window.XMLHttpRequest,s,n,o,u=!1,l=0,c,d,f=!1,p="arraybuffer",h=7e3,m=2e3,v=()=>{if(u)return;no(c);let D=Ac(c),_;if(D<m){_=m-D,setTimeout(v,_);return}m*=2,m>h&&(m=h),n&&n.abort(),n=new r,k()},b=D=>(s=D,V),S=D=>(d=D,V),T=()=>(p="json",V),y=()=>{if(!u){if(--l>=0){v(),i&&i();return}u=!0,d&&d(),t&&t()}},E=D=>(f=D,V),k=()=>{c=me(),n=new r,n.open("get",a);let D=0,_,K=0,J=()=>(no(c),Math.max(c,Math.max(_||0,K||0)));if(s&&n.addEventListener("progress",I=>{let R=me();s.updateChunk&&I.loaded>D&&(s.updateChunk(J(),I.loaded-D),D=I.loaded,_=R)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>y())),n.addEventListener("load",()=>{if(u)return;no(n);let I=n.status;if(I>=200&&I<300){let{response:R,responseType:x}=n,w=R==null?void 0:R.byteLength;if(typeof w=="number"&&s){let B=w-D;B&&s.updateChunk&&s.updateChunk(J(),B)}x==="json"&&(!R||!(0,US.default)(R).length)?y():(d&&d(),e(R))}else y()}),n.addEventListener("error",()=>{y()}),f){let I=()=>{no(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(K=me(),n.removeEventListener("readystatechange",I))};n.addEventListener("readystatechange",I)}return n.responseType=p,n.send(),V},V={withBitrateReporting:b,withParallel:E,withJSONResponse:T,withRetryCount:D=>(l=D,V),withRetryInterval:(D,_)=>(qS(D)&&(m=D),qS(_)&&(h=_),V),withTimeout:D=>(o=D,V),withFinally:S,send:k,abort:()=>{n&&(n.abort(),n=void 0),u=!0,d&&d()}};return V}var $a=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 jS=O(fr(),1);var Ma=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=me(),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=me()-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=yr(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=me()}_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=me();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,jS.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 CM}from"@vkontakte/videoplayer-shared/es2018";var uo=1e4,Rc=3;var BM=6e4,VM=10,_M=1,OM=500,Ca=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 CM,this.chunkRateEstimator=new $a(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=Pc(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=Pc(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",()=>{var r,s;!!e.error&&!this.destroyed&&(t(`Video element error: ${(r=e.error)==null?void 0:r.code}, details: ${(s=e.error)==null?void 0:s.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*(F.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||{};!kS({limits:this.autoQualityLimits,highestAvailableHeight:this.manifest[0].video.height,lowestAvailableHeight:(0,QS.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||oo(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=()=>{HS(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 Ma(Rc,uo,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 y=s&&(!c||c===this.rep);return y||t("Not running!"),y},f=(y,E,k)=>{u&&u.abort(),u=yr(this.urlResolver.resolve(y,!1),E,k,()=>this._retryCallback()).withTimeout(uo).withBitrateReporting(this.bitrateSwitcher).withRetryCount(Rc).withFinally(()=>{u=null}).send()},p=(y,E,k)=>{Da(this.filesFetcher),o==null||o.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(y,!1),E,k,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},h=y=>{let E=i.playbackRate;i.playbackRate!==y&&(t(`Playback rate switch: ${E}=>${y}`),i.playbackRate=y)},m=y=>{this.lowLatency=y,t(`lowLatency changed to ${y}`),v()},v=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)h(1);else{let y=this._getBufferSizeSec();if(this.bufferStates.length<5){h(1);return}let k=me()-1e4,M=0;for(let A=0;A<this.bufferStates.length;A++){let P=this.bufferStates[A];y=Math.min(y,P.buf),P.ts<k&&M++}this.bufferStates.splice(0,M),t(`update playback rate; minBuffer=${y} drop=${M} jitter=${this.sourceJitter}`);let $=y-_M;this.sourceJitter>=0?$-=this.sourceJitter/2:this.sourceJitter-=1,$>3?h(1.15):$>1?h(1.1):$>.3?h(1.05):h(1)}},b=y=>{let E,k=()=>E&&E.start?E.start.length:0,M=I=>E.start[I]/1e3,$=I=>E.dur[I]/1e3,A=I=>E.fragIndex+I,P=(I,R)=>({chunkIdx:A(I),startTS:M(I),dur:$(I),discontinuity:R}),V=()=>{let I=0;if(E&&E.dur){let R=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,x=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,w=R;this.sourceJitter>1&&(w+=this.sourceJitter-1);let B=E.dur.length-1;for(;B>=0&&(w-=E.dur[B],!(w<=0));--B);I=Math.min(B,E.dur.length-1-x),I=Math.max(I,0)}return P(I,!0)},D=I=>{let R=k();if(!(R<=0)){if(oo(I)){for(let x=0;x<R;x++)if(M(x)>I)return P(x)}return V()}},_=I=>{let R=k(),x=I?I.chunkIdx+1:0,w=x-E.fragIndex;if(!(R<=0)){if(!I||w<0||w-R>VM)return t(`Resync: offset=${w} bChunks=${R} chunk=`+JSON.stringify(I)),V();if(!(w>=R))return P(x-E.fragIndex,!1)}},K=(I,R,x)=>{l&&l.abort(),l=yr(this.urlResolver.resolve(I,!0,this.lowLatency),R,x,()=>this._retryCallback()).withTimeout(uo).withRetryCount(Rc).withFinally(()=>{l=null}).withJSONResponse().send()};return{seek:(I,R)=>{K(y,x=>{if(!d())return;E=x;let w=!!E.lowLatency;w!==this.lowLatency&&m(w);let B=0;for(let ne=0;ne<E.dur.length;++ne)B+=E.dur[ne];B>0&&(Da(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(B/E.dur.length)),r({name:"index",zeroTime:E.zeroTime,shiftDuration:E.shiftDuration}),this.sourceJitter=E.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,E.jitter/1e3)):1,I(D(R))},()=>this._handleNetworkError())},nextChunk:_}},S=()=>{s=!1,o&&o.abort(),u&&u.abort(),l&&l.abort(),Da(this.filesFetcher),this.filesFetcher.abortAll()};return c={start:y=>{let{videoElement:E,logger:k}=this.params,M=b(e.jidxUrl),$,A,P,V,D=0,_,K,J,I=()=>{_&&(clearTimeout(_),_=void 0);let z=Math.max(OM,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),ge=D+z,ve=me(),Se=Math.min(1e4,ge-ve);D=ve;let qe=()=>{l||d()&&M.seek(()=>{d()&&(D=me(),R(),I())})};Se>0?_=window.setTimeout(()=>{this.paused?I():qe()},Se):qe()},R=()=>{let z;for(;z=M.nextChunk(V);)V=z,Ne(z);let ge=M.nextChunk(P);if(ge){if(P&&ge.discontinuity){k("Detected discontinuity; restarting playback"),this.paused?I():(S(),this._initPlayerWith(e));return}ne(ge)}else I()},x=(z,ge)=>{if(!d()||!this.sourceBuffer)return;let ve,Se,qe,xt=Ot=>{window.setTimeout(()=>{d()&&x(z,ge)},Ot)};if(this.sourceBuffer.updating)k("Source buffer is updating; delaying appendBuffer"),xt(100);else{let Ot=me(),ui=E.currentTime;!this.paused&&E.buffered.length>1&&K===ui&&Ot-J>500&&(k("Stall suspected; trying to fix"),this._fixupStall()),K!==ui&&(K=ui,J=Ot);let Ui=this._getBufferSizeSec();if(Ui>30)k(`Buffered ${Ui} seconds; delaying appendBuffer`),xt(2e3);else try{this.sourceBuffer.appendBuffer(z),this.videoPlayStarted?(this.bufferStates.push({ts:Ot,buf:Ui}),v(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),ge&&ge()}catch(Wr){if(Wr.name==="QuotaExceededError")k("QuotaExceededError; delaying appendBuffer"),qe=this.sourceBuffer.buffered.length,qe!==0&&(ve=this.sourceBuffer.buffered.start(0),Se=ui,Se-ve>4&&this.sourceBuffer.remove(ve,Se-3)),xt(1e3);else throw Wr}}},w=()=>{A&&$&&(k([`Appending chunk, sz=${A.byteLength}:`,JSON.stringify(P)]),x(A,function(){A=null,R()}))},B=z=>e.fragUrlTemplate.replace("%%id%%",z.chunkIdx),ne=z=>{d()&&p(B(z),(ge,ve)=>{if(d()){if(ve/=1e3,A=ge,P=z,n=z.startTS,ve){let Se=Math.min(10,z.dur/ve);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*Se:Se}w()}},()=>this._handleNetworkError())},Ne=z=>{d()&&(Da(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(B(z),!1)))},ie=z=>{d()&&(e.cachedHeader=z,x(z,()=>{$=!0,w()}))};s=!0,M.seek(z=>{if(d()){if(D=me(),!z){I();return}V=z,!DM(y)||z.startTS>y?ne(z):(P=z,R())}},y),e.cachedHeader?ie(e.cachedHeader):f(e.headerUrl,ie,()=>this._handleNetworkError())},stop:S,getTimestampSec:()=>n},c}_switchToQuality(e){let{logger:t,playerCallback:i}=this.params,r;e.bitrate!==this.bitrate&&(this.rep&&(r=this.rep.getTimestampSec(),oo(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 oo(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,i=d=>{if(!this.autoQuality)return;let f,p,h;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&d<this.bitrate&&(p=this._getBufferSizeSec(),h=d/this.bitrate,p>10&&h>.8||p>15&&h>.5||p>20&&h>.3)){e(`Not switching: buffer=${Math.floor(p)}; bitrate=${this.bitrate}; newRate=${Math.floor(d)}`);return}f=this._selectQuality(d),f?this._switchToQuality(f):e(`Could not find quality by bitrate ${d}`)},s={updateChunk:(f,p)=>{let h=me();if(this.chunkRateEstimator.addInterval(f,h,p)){let v=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:p,duration:h-f,speed:v}),!0}},get:()=>{let f=this.chunkRateEstimator.getBitRate();return f?f*.85:0}},n=-1/0,o,u=!0,l=()=>{let d=s.get();if(d&&o&&this.autoQuality){if(u&&d>o&&Ac(n)<3e4)return;i(d)}u=this.autoQuality};return{updateChunk:(d,f)=>{let p=s.updateChunk(d,f);return p&&l(),p},notifySwitch:d=>{let f=me();d<o&&(n=f),o=d}}}_fetchManifest(e,t,i){this.manifestRequest=yr(this.urlResolver.resolve(e,!0),t,i,()=>this._retryCallback()).withJSONResponse().withTimeout(uo).withRetryCount(this.params.config.manifestRetryMaxCount).withRetryInterval(this.params.config.manifestRetryInterval,this.params.config.manifestRetryMaxInterval).send().withFinally(()=>{this.manifestRequest=void 0})}_playVideoElement(){let{videoElement:e}=this.params;_e(e,()=>{this.soundProhibitedEvent$.next()}).then(t=>{t||(this.params.liveOffset.pause(),this.params.videoState.setState("paused"))})}_handleManifestUpdate(e){let{logger:t,playerCallback:i,videoElement:r}=this.params,s=n=>{let o=[];return n!=null&&n.length?(n.forEach((u,l)=>{var c,d;u.video&&r.canPlayType(u.codecs).replace(/no/,"")&&((d=(c=window.MediaSource)==null?void 0:c.isTypeSupported)!=null&&d.call(c,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))},BM))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};var zS=O(ir(),1);import{debounce as FM,filter as WS,fromEvent as NM,interval as qM,isHigher as UM,isInvariantQuality as HM,isLower as jM,merge as QM,Subject as GS,Subscription as WM}from"@vkontakte/videoplayer-shared/es2018";var kc=class{constructor(){this.onDroopedVideoFramesLimit$=new GS;this.subscription=new WM;this.playing=!1;this.tracks=[];this.forceChecker$=new GS;this.isForceCheckCounter=0;this.prevTotalVideoFrames=0;this.prevDroppedVideoFrames=0;this.limitCounts={};this.handleChangeVideoQuality=()=>{let e=this.tracks.find(({size:t})=>(t==null?void 0:t.height)===this.video.videoHeight&&(t==null?void 0:t.width)===this.video.videoWidth);e&&!HM(e.quality)&&this.onChangeQuality(e.quality)};this.checkDroppedFrames=()=>{var n;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&&UM(this.currentQuality,this.droppedFramesChecker.minQualityBanLimit)&&(this.limitCounts[this.currentQuality]=((n=this.limitCounts[this.currentQuality])!=null?n:0)+1,this.maxQualityLimit=this.getMaxQualityLimit(this.currentQuality),this.currentTimer&&window.clearTimeout(this.currentTimer),this.currentTimer=window.setTimeout(()=>this.maxQualityLimit=this.getMaxQualityLimit(),this.droppedFramesChecker.qualityUpWaitingTime),this.onDroopedVideoFramesLimitTrigger()),this.savePrevFrameCounts(e,t)}}connect(e){this.log=e.logger.createComponentLog("DroppedFramesManager"),this.video=e.video,this.isAuto=e.isAuto,this.tracks=e.tracks,this.droppedFramesChecker=e.droppedFramesChecker,this.subscription.add(e.playing$.subscribe(()=>this.playing=!0)),this.subscription.add(e.pause$.subscribe(()=>this.playing=!1)),this.isEnabled&&this.subscribe()}destroy(){this.currentTimer&&window.clearTimeout(this.currentTimer),this.subscription.unsubscribe()}get droppedVideoMaxQualityLimit(){return this.maxQualityLimit}subscribe(){this.subscription.add(NM(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=qM(this.droppedFramesChecker.checkTime).pipe(WS(()=>this.playing),WS(()=>{let r=!!this.isForceCheckCounter;return r&&(this.isForceCheckCounter-=1),!r})),t=this.forceChecker$.pipe(FM(this.droppedFramesChecker.checkTime)),i=QM(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){var i,r;let t=(r=(i=(0,zS.default)(this.limitCounts).filter(([,s])=>s>=this.droppedFramesChecker.countLimit).sort(([s],[n])=>jM(s,n)?-1:1))==null?void 0:i[0])==null?void 0:r[0];return e!=null?e:t}get isEnabled(){return this.droppedFramesChecker.enabled&&this.isDroppedFramesCheckerSupport}get isDroppedFramesCheckerSupport(){return!!this.video&&typeof this.video.getVideoPlaybackQuality=="function"}savePrevFrameCounts(e,t){this.prevTotalVideoFrames=e,this.prevDroppedVideoFrames=t}},Tr=kc;import{map as GM,Observable as zM}from"@vkontakte/videoplayer-shared/es2018";import{fromEvent as YM}from"@vkontakte/videoplayer-shared/es2018";var Ba=()=>{var a;return!!((a=window.documentPictureInPicture)!=null&&a.window)||!!document.pictureInPictureElement};var KM=(a,e)=>new zM(t=>{if(!window.IntersectionObserver)return;let i={root:null},r=new IntersectionObserver((n,o)=>{n.forEach(u=>t.next(u.isIntersecting||Ba()))},{...i,...e});r.observe(a);let s=YM(document,"visibilitychange").pipe(GM(n=>!document.hidden||Ba())).subscribe(n=>t.next(n));return()=>{r.unobserve(a),s.unsubscribe()}}),Je=KM;var aD=["paused","playing","ready"],sD=["paused","playing","ready"],Va=class{constructor(e){this.subscription=new iD;this.videoState=new H("stopped");this.representations$=new $c([]);this.droppedFramesManager=new Tr;this.maxSeekBackTime$=new $c(1/0);this.zeroTime$=new $c(void 0);this.liveOffset=new Pi;this._dashCb=e=>{var t,i,r,s;switch(e.name){case"buffering":{let n=e.isBuffering;this.params.output.isBuffering$.next(n);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${e.type}`,category:XS.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{let n=e.manifest,o=[];for(let u of n){let l=(t=u.name)!=null?t:u.index.toString(10),c=(i=Kt(u.name))!=null?i:rD(u.video),d=u.bitrate/1e3,f={...u.video};if(!c)continue;let p={id:l,quality:c,bitrate:d,size:f};o.push({track:p,representation:u})}this.representations$.next(o),this.params.output.availableVideoTracks$.next(o.map(({track:u})=>u)),((r=this.videoState.getTransition())==null?void 0:r.to)==="manifest_ready"&&this.videoState.setState("manifest_ready");break}case"qualitySwitch":{let n=e.quality,o=(s=this.representations$.getValue().find(({representation:u})=>u===n))==null?void 0:s.track;this.params.output.hostname$.next(new URL(n.headerUrl,this.params.source.url).hostname),Lc(o)&&this.params.output.currentVideoTrack$.next(o);break}case"bandwidth":{let{size:n,duration:o}=e;this.params.dependencies.throughputEstimator.addRawSpeed(n,o);break}case"index":{this.maxSeekBackTime$.next(e.shiftDuration||0),this.zeroTime$.next(e.zeroTime);break}}};this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),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,Mc.default)(sD,e)&&(n||o)){this.prepare();return}if((r==null?void 0:r.to)!=="paused"&&s.state==="requested"&&(0,Mc.default)(aD,e)){this.seek(s.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(le(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==null?void 0: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(le(this.params.source.url,u))}return;default:return YS(e)}};this.textTracksManager=new Xe(e.source.url),this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=r=>{e.output.error$.next({id:"DashLiveProvider",category:XS.WTF,message:"DashLiveProvider internal logic error",thrown:r})};this.subscription.add(ZS(this.videoState.stateChangeStarted$.pipe(lo(r=>({transition:r,type:"start"}))),this.videoState.stateChangeEnded$.pipe(lo(r=>({transition:r,type:"end"})))).subscribe(({transition:r,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(r)}`})})),this.video=De(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(Te(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);let i=Ve(this.video);this.subscription.add(()=>i.destroy()),this.subscription.add(this.representations$.pipe(lo(r=>r.map(({track:s})=>s)),JS(r=>!!r.length),tD()).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(()=>{var r;((r=this.videoState.getTransition())==null?void 0:r.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(ZM(),lo(r=>-r/1e3)).subscribe(this.params.output.duration$)).add(XM({zeroTime:this.zeroTime$.pipe(JS(Lc)),position:i.timeUpdate$}).subscribe(({zeroTime:r,position:s})=>this.params.output.liveTime$.next(r+s*1e3),t)).add(bt(this.video,this.params.desiredState.isLooped,t)).add(Be(this.video,this.params.desiredState.volume,i.volumeState$,t)).add(i.volumeState$.subscribe(this.params.output.volume$,t)).add(Ke(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(Je(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:r,min:s}})=>{this.dash.setAutoQualityLimits({max:r&&ey(r),min:s&&ey(s)}),this.params.output.autoVideoTrackLimits$.next({max:r,min:s})})).add(this.videoState.stateChangeEnded$.subscribe(r=>{var s;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":((s=this.params.desiredState.playbackState.getTransition())==null?void 0:s.to)==="ready"&&this.params.desiredState.playbackState.setState("ready");break;case"paused":this.params.desiredState.playbackState.setState("paused");break;case"playing":this.params.desiredState.playbackState.setState("playing");break;default:return YS(r.to)}},t)).add(ZS(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,eD(["init"])).pipe(JM(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),Ce(this.video)}createLiveDashPlayer(){let e=new Ca({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(){var l,c,d,f,p,h;let e=this.representations$.getValue(),t=(c=(l=this.params.desiredState.videoTrack.getTransition())==null?void 0:l.to)!=null?c:this.params.desiredState.videoTrack.getState(),i=(f=(d=this.params.desiredState.autoVideoTrackSwitching.getTransition())==null?void 0:d.to)!=null?f:this.params.desiredState.autoVideoTrackSwitching.getState(),r=!i&&Lc(t)?t:St(e.map(({track:m})=>m),{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==null?void 0:r.id,n=this.params.desiredState.videoTrack.getTransition(),o=(p=this.params.desiredState.videoTrack.getState())==null?void 0:p.id,u=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(r&&(n||s!==o)&&this.setVideoTrack(r),u&&this.setAutoQuality(i),n||u||s!==o){let m=(h=e.find(({track:v})=>v.id===s))==null?void 0:h.representation;KS(m,"Representations missing"),this.dash.startPlay(m,i)}}setVideoTrack(e){var i;let t=(i=this.representations$.getValue().find(({track:r})=>r.id===e.id))==null?void 0:i.representation;KS(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(le(this.params.source.url,n)),r&&this.dash.pause(),this.liveOffset.resetTo(n,r)}};var ty=Va;var TI=O(Ae(),1);var be=(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 YB,assertNonNullable as KB,debounce as XB,ErrorCategory as vI,filter as md,filterChanged as Fo,fromEvent as JB,isNonNullable as SI,isNullable as ZB,map as bd,merge as No,observableFrom as gd,once as yI,Subscription as e0}from"@vkontakte/videoplayer-shared/es2018";var{NativeAbortSignal:D1,NativeAbortController:C1}=function(a){return{NativeAbortSignal:a.AbortSignal,NativeAbortController:a.AbortController}}(typeof self!="undefined"?self:global);function iy(a){let e;try{e=new Event("abort")}catch(t){typeof document!="undefined"?document.createEvent?(e=document.createEvent("Event"),e.initEvent("abort",!1,!1)):(e=document.createEventObject(),e.type="abort"):e={type:"abort",bubbles:!1,cancelable:!1}}return e.reason=a,e}function ry(a){if(a===void 0)if(typeof document=="undefined")a=new Error("This operation was aborted"),a.name="AbortError";else try{a=new DOMException("signal is aborted without reason"),Object.defineProperty(a,"name",{value:"AbortError"})}catch(e){a=new Error("This operation was aborted"),a.name="AbortError"}return a}var co=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}},Ir=class extends co{constructor(){super(),this.listeners||co.call(this),Object.defineProperty(this,"aborted",{value:!1,writable:!0,configurable:!0}),Object.defineProperty(this,"onabort",{value:null,writable:!0,configurable:!0}),Object.defineProperty(this,"reason",{value:void 0,writable:!0,configurable:!0})}toString(){return"[object AbortSignal]"}dispatchEvent(e){e.type==="abort"&&(this.aborted=!0,typeof this.onabort=="function"&&this.onabort.call(this,e)),super.dispatchEvent(e)}throwIfAborted(){let{aborted:e,reason:t="Aborted"}=this;if(e)throw t}static timeout(e){let t=new ki;return setTimeout(()=>t.abort(new DOMException(`This signal is timeout in ${e}ms`,"TimeoutError")),e),t.signal}static any(e){let t=new ki;function i(){t.abort(this.reason),r()}function r(){for(let s of e)s.removeEventListener("abort",i)}for(let s of e)if(s.aborted){t.abort(s.reason);break}else s.addEventListener("abort",i);return t.signal}},ki=class{constructor(){Object.defineProperty(this,"signal",{value:new Ir,writable:!0,configurable:!0})}abort(e){let t=ry(e),i=iy(t);this.signal.reason=t,this.signal.dispatchEvent(i)}toString(){return"[object AbortController]"}};typeof Symbol!="undefined"&&Symbol.toStringTag&&(ki.prototype[Symbol.toStringTag]="AbortController",Ir.prototype[Symbol.toStringTag]="AbortSignal");function po(a){return a.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof a.Request=="function"&&!a.Request.prototype.hasOwnProperty("signal")||!a.AbortController}function Dc(a){typeof a=="function"&&(a={fetch:a});let{fetch:e,Request:t=e.Request,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r=!1}=a;if(!po({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 f=new t(l,c);return d&&Object.defineProperty(f,"signal",{writable:!1,enumerable:!1,configurable:!0,value:d}),f},s.prototype=t.prototype);let n=e;return{fetch:(u,l)=>{let c=s&&s.prototype.isPrototypeOf(u)?u.signal:l?l.signal:void 0;if(c){let d;try{d=new DOMException("Aborted","AbortError")}catch(p){d=new Error("Aborted"),d.name="AbortError"}if(c.aborted)return Promise.reject(d);let f=new Promise((p,h)=>{c.addEventListener("abort",()=>h(d),{once:!0})});return l&&l.signal&&delete l.signal,Promise.race([f,n(u,l)])}return n(u,l)},Request:s}}var nD=()=>"fetch"in window,_a=nD()&&po({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),ay=_a?Dc({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,Ze=_a?ay.fetch:window.fetch,j1=_a?ay.Request:window.Request,Z=_a?ki:window.AbortController,Q1=_a?Ir:window.AbortSignal;var fI=O(Ae(),1),ld=O(Oa(),1);var jy=O(Hy(),1);import{ErrorCategory as Na}from"@vkontakte/videoplayer-shared/es2018";var ho=a=>{if(!a)return{id:"EmptyResponse",category:Na.PARSER,message:"Empty response"};if(a.length<=2&&a.match(/^\d+$/))return{id:`UVError#${a}`,category:Na.NETWORK,message:`UV Error ${a}`};let e=(0,jy.default)(a).substring(0,100).toLowerCase();if(e.startsWith("<!doctype")||e.startsWith("<html>")||e.startsWith("<body>")||e.startsWith("<head>"))return{id:"UnexpectedHTML",category:Na.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:Na.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:Na.PARSER,message:"Response is valid XML, but parser failed"}};var Ie=(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 nd,assertNonNullable as Cr,combine as Br,ErrorCategory as ct,filter as Mo,filterChanged as vs,flattenObject as Ss,fromEvent as Bt,getTraceSubscriptionMethod as $B,interval as od,isNonNullable as ys,isNullable as dI,map as Vr,merge as Ci,now as ud,Subject as ii,Subscription as pI,tap as MB,throttle as DB,ValueSubject as ae}from"@vkontakte/videoplayer-shared/es2018";var go=O(Ae(),1),Di=O(ot(),1),vo=O(Oa(),1);var QD=(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)},WD=a=>window.clearTimeout(a),Qy=a=>typeof a=="function"&&(a==null?void 0:a.toString().endsWith("{ [native code] }")),Wy=!Qy(window.requestIdleCallback)||!Qy(window.cancelIdleCallback),Er=Wy?QD:window.requestIdleCallback,yt=Wy?WD:window.cancelIdleCallback;var rI=O(Vn(),1);import{assertNever as GD,ErrorCategory as Gy,Subject as zy}from"@vkontakte/videoplayer-shared/es2018";var zD=18,Yy=!1;try{Yy=F.browser.isSafari&&!!F.browser.safariVersion&&F.browser.safariVersion<=zD}catch(a){console.error(a)}var Fc=class{constructor(e){this.bufferFull$=new zy;this.error$=new zy;this.queue=[];this.currentTask=null;this.destroyed=!1;this.abortRequested=!1;this.completeTask=()=>{var e;try{if(this.currentTask){let t=(e=this.currentTask.signal)==null?void 0:e.aborted;this.currentTask.callback(!t),this.currentTask=null}this.queue.length&&this.pull()}catch(t){this.error$.next({id:"BufferTaskQueueUnknown",category:Gy.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:t})}};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)};Yy&&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(){var r;if((this.buffer.updating||this.currentTask||this.destroyed)&&!this.abortRequested)return;let e=this.queue.shift();if(!e)return;if((r=e.signal)!=null&&r.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(s){s instanceof DOMException&&s.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):s instanceof DOMException&&s.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:Gy.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:s}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){let{operation:t}=e;switch(t){case"append":this.buffer.appendBuffer(e.data);break;case"remove":this.buffer.remove(e.from/1e3,e.to/1e3);break;case"abort":this.buffer.abort();break;case"safariAbort":{this.buffer.abort(),this.buffer.appendBuffer(e.init);break}default:GD(t)}}},Ky=Fc;var xr=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 Zt,assertNonNullable as Oe,ErrorCategory as Mt,fromEvent as Zc,getExponentialDelay as ed,isNonNullable as kr,isNullable as Ee,now as bo,once as bB,Subject as gB,Subscription as vB,ValueSubject as Mi}from"@vkontakte/videoplayer-shared/es2018";var Xy=O(ot(),1);var fo=a=>a.valid,Q=class{constructor(e,t){this.cursor=0;this.source=e,this.boxParser=t,this.children=[];let i=this.readUint32();this.type=this.readString(4),i===1&&(this.cursor+=8);let r=e.byteOffset+this.cursor,s;i===0?(this.size=void 0,this.valid=!1,s=void 0):i===1?(this.size=void 0,this.valid=!1,s=void 0):i>e.byteLength?(this.size=i,this.valid=!1,s=Math.min(i-this.cursor,e.byteLength-this.cursor)):(this.size=i,this.valid=!0,s=i-this.cursor),this.content=new DataView(e.buffer,r,s)}get id(){return this.type}scanForBoxes(e){return this.boxParser.parse(e)}readString(e,t="ascii"){let r=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,r}readUint8(){let e=this.source.getUint8(this.cursor);return this.cursor+=1,e}readUint16(){let e=this.source.getUint16(this.cursor);return this.cursor+=2,e}readUint32(){let e=this.source.getUint32(this.cursor);return this.cursor+=4,e}readUint64(){let e=this.source.getBigInt64(this.cursor);return this.cursor+=8,e}};var wr=class extends Q{};import{assertNever as YD}from"@vkontakte/videoplayer-shared/es2018";var qa=class extends Q{constructor(e,t){if(super(e,t),!this.valid)return;let i=this.readString(16),r=new DataView(this.content.buffer,this.content.byteOffset+16,this.content.byteLength-16);this.userData=this.parseData(i,r)}parseData(e,t){switch(e){case"ondemandlivejson":{let i=new TextDecoder("ascii").decode(t),r=JSON.parse(i);return{received:r["t-in"],prepared:r["t-out"]}}default:YD(e)}}};var Ua=class extends Q{constructor(e,t){if(super(e,t),!this.valid)return;this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let i=new DataView(this.content.buffer,this.content.byteOffset+8,this.content.byteLength-8);for(let r=0;r<i.byteLength;r+=4){let s=this.readString(4);this.compatibleBrands.push(s)}}};var Ha=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var re=class extends Q{constructor(e,t){if(super(e,t),!this.valid)return;let i=this.readUint32();this.version=i>>>24,this.flags=i&16777215,this.content=new DataView(this.content.buffer,this.content.byteOffset+4,this.content.byteLength-4)}};var ja=class extends re{constructor(e,t){super(e,t),this.valid&&(this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.timescale=this.readUint32(),this.duration=this.readUint32(),this.rate=this.readUint32(),this.volume=this.readUint16())}};var Qa=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 Li=class extends re{get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e,t){if(super(e,t),!!this.valid){this.segments=[],this.referenceId=this.readUint32(),this.timescale=this.readUint32(),this.earliestPresentationTime32=this.readUint32(),this.firstOffset32=this.readUint32(),this.earliestPresentationTime64=0,this.firstOffset64=0,this.referenceCount=this.readUint32()&65535;for(let i=0;i<this.referenceCount;i++){let r=this.readUint32(),s=r>>>31,n=r<<1>>>1,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 Ga=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var za=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ya=class extends re{constructor(e,t){if(super(e,t),!this.valid)return;switch(this.readUint8()){case 0:this.stereoMode=0;break;case 1:this.stereoMode=1;break;case 2:this.stereoMode=2;break;case 3:this.stereoMode=3;break;case 4:this.stereoMode=4;break}this.cursor+=1}};var Ka=class extends re{constructor(e,t){super(e,t),this.valid&&(this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32())}};var Xa=class extends re{constructor(e,t){super(e,t),this.valid&&(this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32())}};var Ja=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Za=class extends re{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 es=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ts=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var is=class extends re{constructor(e,t){super(e,t),this.valid&&(this.sequenceNumber=this.readUint32())}};var rs=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var as=class extends re{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 ss=class extends re{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 ns=class extends re{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 os=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var us=class extends re{constructor(e,t){super(e,t),this.valid&&(this.entryCount=this.readUint32(),this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+4,this.content.byteLength-4)))}};var ls=class extends Q{constructor(e,t){super(e,t),this.valid&&(this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+78,this.content.byteLength-78)))}};var XD={ftyp:Ua,moov:Ha,mvhd:ja,moof:Qa,mdat:Wa,sidx:Li,trak:Ga,mdia:Ja,mfhd:is,tkhd:Za,traf:rs,tfhd:as,tfdt:ss,trun:ns,minf:es,sv3d:za,st3d:Ya,prhd:Ka,proj:ts,equi:Xa,uuid:qa,stbl:os,stsd:us,avc1:ls,unknown:wr},$t=class a{constructor(e={}){this.options={offset:0,...e}}parse(e){let t=[],i=this.options.offset;for(;i<e.byteLength;){let s=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+i+4,4)),n;try{n=this.createBox(s,new DataView(e.buffer,e.byteOffset+i,e.byteLength-i))}catch(o){if(!(o instanceof RangeError))throw o}if(!n||!fo(n))break;t.push(n),i+=n.size}return t}createBox(e,t){let i=XD[e];return i?new i(t,new a):new wr(t,new a)}};var Jt=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{var i,r,s;fo(t)&&((s=(i=this.index)[r=t.type])!=null||(i[r]=[]),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 ZD=new TextDecoder("ascii"),eC=a=>ZD.decode(new DataView(a.buffer,a.byteOffset+4,4))==="ftyp",tC=a=>{let e=new Li(a,new $t),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})},iC=(a,e)=>{let i=new $t().parse(a),r=new Jt(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)},rC=a=>{let t=new $t().parse(a),i=new Jt(t),r={},s=i.findAll("uuid"),n=(0,Xy.default)(s,-1);return n?{serverDataReceivedTimestamp:n.userData.received,serverDataPreparedTime:n.userData.received}:r},aC=a=>{var r;let t=new $t().parse(a);return(r=new Jt(t).find("sidx"))==null?void 0:r.timescale},sC=(a,e)=>{let i=new $t().parse(a),s=new Jt(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,f)=>d+f,0):l=n.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+l)/e*1e3},nC=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 $t().parse(a),r=new Jt(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},Jy={validateData:eC,parseInit:nC,getIndexRange:()=>{},parseSegments:tC,parseFeedableSegmentChunk:iC,getChunkEndTime:sC,getServerLatencyTimestamps:rC,getTimescaleFromIndex:aC};var ps=O(Ae(),1);import{assertNonNullable as Nc,isNonNullable as iT,isNullable as uC}from"@vkontakte/videoplayer-shared/es2018";import{assertNever as oC}from"@vkontakte/videoplayer-shared/es2018";var Zy={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"}},eT=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=ds(a,t),r=i in Zy,s=r?Zy[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=ds(u),d=l*2**((o-1)*8)+c,f=t+o,p;return f+d>a.byteLength?p=new DataView(a.buffer,a.byteOffset+f):p=new DataView(a.buffer,a.byteOffset+f,d),{tag:r?i:"0x"+i.toString(16).toUpperCase(),type:s,tagHeaderSize:f,tagSize:f+d,value:p,valueSize:d}},ds=(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},ut=(a,e)=>{switch(e){case"int":return a.getInt8(0);case"uint":return ds(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:oC(e)}},$i=(a,e)=>{let t=0;for(;t<a.byteLength;){let i=new DataView(a.buffer,a.byteOffset+t),r=eT(i);if(!e(r))return;r.type==="master"&&$i(r.value,e),t=r.value.byteOffset-a.byteOffset+r.valueSize}},tT=a=>{if(a.getUint32(0)!==440786851)return!1;let e,t,i,r=eT(a);return $i(r.value,({tag:s,type:n,value:o})=>(s===17143?e=ut(o,n):s===17026?t=ut(o,n):s===17029&&(i=ut(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)};var rT=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],lC=[231,22612,22743,167,171,163,160,175],cC=a=>{let e,t,i,r,s=!1,n=!1,o=!1,u,l,c=!1,d=0;return $i(a,({tag:f,type:p,value:h,valueSize:m})=>{if(f===21419){let v=ut(h,p);l=ds(v)}else f!==21420&&(l=void 0);return f===408125543?(e=h.byteOffset,t=h.byteOffset+m):f===357149030?s=!0:f===290298740?n=!0:f===2807729?i=ut(h,p):f===17545?r=ut(h,p):f===21420&&l===475249515?u=ut(h,p):f===374648427?$i(h,({tag:v,type:b,value:S})=>v===30321?(c=ut(S,b)===1,!1):!0):s&&n&&(0,ps.default)(rT,f)&&(o=!0),!o}),Nc(e,"Failed to parse webm Segment start"),Nc(t,"Failed to parse webm Segment end"),Nc(r,"Failed to parse webm Segment duration"),i=i!=null?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}}}},dC=a=>{if(uC(a.cuesSeekPosition))return;let e=a.segmentStart+a.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},pC=(a,e)=>{let t=!1,i=!1,r=o=>iT(o.time)&&iT(o.position),s=[],n;return $i(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=ut(l,u));break;case 183:break;case 241:n&&(n.position=ut(l,u));break;default:t&&(0,ps.default)(rT,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}}})},hC=a=>{let e=0,t=!1;try{$i(a,i=>i.tag===524531317?i.tagSize<=a.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):(0,ps.default)(lC,i.tag)?(e+i.tagSize<=a.byteLength&&(e+=i.tagSize,t||(t=(0,ps.default)([163,160,175],i.tag))),!0):!1)}catch(i){}return e>0&&e<=a.byteLength&&t?new DataView(a.buffer,a.byteOffset,e):null},aT={validateData:tT,parseInit:cC,getIndexRange:dC,parseSegments:pC,parseFeedableSegmentChunk:hC};var Tt=a=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(a);if(e){let[,t,i]=e;if(t==="audio"||t==="video")switch(i){case"webm":return aT;case"mp4":return Jy}}throw new ReferenceError(`Unsupported mime type ${a}`)};var It=a=>a instanceof DOMException&&(a.name==="AbortError"||a.code===20);var Gc=O(PT(),1),YT=O(ir(),1),KT=O(HT(),1),XT=O(ot(),1),zc=O(fr(),1);var jT=O(Ae(),1),Wc=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,jT.default)(["6E","7A","F4"],o)}}return!1};import{isNonNullable as hB,isNullable as GT}from"@vkontakte/videoplayer-shared/es2018";var QT=a=>{if(a.includes("/")){let e=a.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(a)};var WT=a=>{var e;try{let t=pB(),i=a.match(t),{groups:r}=i!=null?i:{};if(r){let s={};if(r.extensions){let u=r.extensions.toLowerCase().match(/(?:[0-9a-wy-z](?:-[a-z0-9]{2,8})+)/g);Array.from(u||[]).forEach(l=>{s[l[0]]=l.slice(2)})}let n=(e=r.variants)==null?void 0:e.split(/-/).filter(u=>u!==""),o={extlang:r.extlang,langtag:r.langtag,language:r.language,privateuse:r.privateuse||r.privateuse2,region:r.region,script:r.script,extensions:s,variants:n};return Object.keys(o).forEach(u=>{let l=o[u];(typeof l=="undefined"||l==="")&&delete o[u]}),o}return null}catch(t){return null}};function pB(){let a="(?<extlang>(?:[a-z]{3}(?:-[a-z]{3}){0,2}))",e="x(?:-[a-z0-9]{1,8})+",c=`^(?:(?<langtag>${`
116
+ [selected audio track] ${v==null?void 0:v.id}
117
+ `}),v};var Ie=a=>new URL(a).hostname;import{assertNever as Xv,assertNonNullable as Jv,combine as XM,debounce as JM,ErrorCategory as Zv,filter as ey,filterChanged as ZM,isNonNullable as Vc,map as So,merge as ty,observableFrom as eD,once as tD,Subscription as iD,ValueSubject as _c,videoQualityToHeight as iy,videoSizeToQuality as rD}from"@vkontakte/videoplayer-shared/es2018";var Wv=O(ot(),1);var Uv=O(Ae(),1),qv=a=>{if(a instanceof DOMException&&(0,Uv.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"))},Fe=async(a,e)=>{let t=a.muted;try{await a.play()}catch(i){if(!qv(i))return!1;if(e&&e(),t)return console.warn(i),!1;a.muted=!0;try{await a.play()}catch(r){return qv(r)&&(a.muted=!1,console.warn(r)),!1}}return!0};import{isNonNullable as bo,isNullable as DM,assertNonNullable as Da}from"@vkontakte/videoplayer-shared/es2018";var Hv=O(br(),1);import{isNonNullable as jv,assertNonNullable as mo,now as $M}from"@vkontakte/videoplayer-shared/es2018";function ge(){return $M()}function Mc(a){return ge()-a}function Dc(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 Qv(a,e,t){let i=(...r)=>{t.apply(null,r),a.removeEventListener(e,i)};a.addEventListener(e,i)}function Ir(a,e,t,i){let r=window.XMLHttpRequest,s,n,o,u=!1,l=0,c,d,f=!1,p="arraybuffer",h=7e3,m=2e3,S=()=>{if(u)return;mo(c);let D=Mc(c),_;if(D<m){_=m-D,setTimeout(S,_);return}m*=2,m>h&&(m=h),n&&n.abort(),n=new r,w()},b=D=>(s=D,V),v=D=>(d=D,V),T=()=>(p="json",V),y=()=>{if(!u){if(--l>=0){S(),i&&i();return}u=!0,d&&d(),t&&t()}},I=D=>(f=D,V),w=()=>{c=ge(),n=new r,n.open("get",a);let D=0,_,K=0,J=()=>(mo(c),Math.max(c,Math.max(_||0,K||0)));if(s&&n.addEventListener("progress",E=>{let k=ge();s.updateChunk&&E.loaded>D&&(s.updateChunk(J(),E.loaded-D),D=E.loaded,_=k)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>y())),n.addEventListener("load",()=>{if(u)return;mo(n);let E=n.status;if(E>=200&&E<300){let{response:k,responseType:x}=n,A=k==null?void 0:k.byteLength;if(typeof A=="number"&&s){let B=A-D;B&&s.updateChunk&&s.updateChunk(J(),B)}x==="json"&&(!k||!(0,Hv.default)(k).length)?y():(d&&d(),e(k))}else y()}),n.addEventListener("error",()=>{y()}),f){let E=()=>{mo(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(K=ge(),n.removeEventListener("readystatechange",E))};n.addEventListener("readystatechange",E)}return n.responseType=p,n.send(),V},V={withBitrateReporting:b,withParallel:I,withJSONResponse:T,withRetryCount:D=>(l=D,V),withRetryInterval:(D,_)=>(jv(D)&&(m=D),jv(_)&&(h=_),V),withTimeout:D=>(o=D,V),withFinally:v,send:w,abort:()=>{n&&(n.abort(),n=void 0),u=!0,d&&d()}};return V}var $a=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 Gv=O(br(),1);var Ma=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=ge(),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=ge()-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=Ir(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=ge()}_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=ge();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,Gv.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 CM}from"@vkontakte/videoplayer-shared/es2018";var go=1e4,Cc=3;var BM=6e4,VM=10,_M=1,OM=500,Ca=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 CM,this.chunkRateEstimator=new $a(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=Dc(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=Dc(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",()=>{var r,s;!!e.error&&!this.destroyed&&(t(`Video element error: ${(r=e.error)==null?void 0:r.code}, details: ${(s=e.error)==null?void 0:s.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*(F.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||{};!$v({limits:this.autoQualityLimits,highestAvailableHeight:this.manifest[0].video.height,lowestAvailableHeight:(0,Wv.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||bo(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=()=>{Qv(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 Ma(Cc,go,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 y=s&&(!c||c===this.rep);return y||t("Not running!"),y},f=(y,I,w)=>{u&&u.abort(),u=Ir(this.urlResolver.resolve(y,!1),I,w,()=>this._retryCallback()).withTimeout(go).withBitrateReporting(this.bitrateSwitcher).withRetryCount(Cc).withFinally(()=>{u=null}).send()},p=(y,I,w)=>{Da(this.filesFetcher),o==null||o.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(y,!1),I,w,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},h=y=>{let I=i.playbackRate;i.playbackRate!==y&&(t(`Playback rate switch: ${I}=>${y}`),i.playbackRate=y)},m=y=>{this.lowLatency=y,t(`lowLatency changed to ${y}`),S()},S=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)h(1);else{let y=this._getBufferSizeSec();if(this.bufferStates.length<5){h(1);return}let w=ge()-1e4,L=0;for(let R=0;R<this.bufferStates.length;R++){let P=this.bufferStates[R];y=Math.min(y,P.buf),P.ts<w&&L++}this.bufferStates.splice(0,L),t(`update playback rate; minBuffer=${y} drop=${L} jitter=${this.sourceJitter}`);let M=y-_M;this.sourceJitter>=0?M-=this.sourceJitter/2:this.sourceJitter-=1,M>3?h(1.15):M>1?h(1.1):M>.3?h(1.05):h(1)}},b=y=>{let I,w=()=>I&&I.start?I.start.length:0,L=E=>I.start[E]/1e3,M=E=>I.dur[E]/1e3,R=E=>I.fragIndex+E,P=(E,k)=>({chunkIdx:R(E),startTS:L(E),dur:M(E),discontinuity:k}),V=()=>{let E=0;if(I&&I.dur){let k=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,x=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,A=k;this.sourceJitter>1&&(A+=this.sourceJitter-1);let B=I.dur.length-1;for(;B>=0&&(A-=I.dur[B],!(A<=0));--B);E=Math.min(B,I.dur.length-1-x),E=Math.max(E,0)}return P(E,!0)},D=E=>{let k=w();if(!(k<=0)){if(bo(E)){for(let x=0;x<k;x++)if(L(x)>E)return P(x)}return V()}},_=E=>{let k=w(),x=E?E.chunkIdx+1:0,A=x-I.fragIndex;if(!(k<=0)){if(!E||A<0||A-k>VM)return t(`Resync: offset=${A} bChunks=${k} chunk=`+JSON.stringify(E)),V();if(!(A>=k))return P(x-I.fragIndex,!1)}},K=(E,k,x)=>{l&&l.abort(),l=Ir(this.urlResolver.resolve(E,!0,this.lowLatency),k,x,()=>this._retryCallback()).withTimeout(go).withRetryCount(Cc).withFinally(()=>{l=null}).withJSONResponse().send()};return{seek:(E,k)=>{K(y,x=>{if(!d())return;I=x;let A=!!I.lowLatency;A!==this.lowLatency&&m(A);let B=0;for(let ne=0;ne<I.dur.length;++ne)B+=I.dur[ne];B>0&&(Da(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(B/I.dur.length)),r({name:"index",zeroTime:I.zeroTime,shiftDuration:I.shiftDuration}),this.sourceJitter=I.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,I.jitter/1e3)):1,E(D(k))},()=>this._handleNetworkError())},nextChunk:_}},v=()=>{s=!1,o&&o.abort(),u&&u.abort(),l&&l.abort(),Da(this.filesFetcher),this.filesFetcher.abortAll()};return c={start:y=>{let{videoElement:I,logger:w}=this.params,L=b(e.jidxUrl),M,R,P,V,D=0,_,K,J,E=()=>{_&&(clearTimeout(_),_=void 0);let z=Math.max(OM,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),Se=D+z,ve=ge(),ye=Math.min(1e4,Se-ve);D=ve;let qe=()=>{l||d()&&L.seek(()=>{d()&&(D=ge(),k(),E())})};ye>0?_=window.setTimeout(()=>{this.paused?E():qe()},ye):qe()},k=()=>{let z;for(;z=L.nextChunk(V);)V=z,Ne(z);let Se=L.nextChunk(P);if(Se){if(P&&Se.discontinuity){w("Detected discontinuity; restarting playback"),this.paused?E():(v(),this._initPlayerWith(e));return}ne(Se)}else E()},x=(z,Se)=>{if(!d()||!this.sourceBuffer)return;let ve,ye,qe,xt=Ot=>{window.setTimeout(()=>{d()&&x(z,Se)},Ot)};if(this.sourceBuffer.updating)w("Source buffer is updating; delaying appendBuffer"),xt(100);else{let Ot=ge(),ci=I.currentTime;!this.paused&&I.buffered.length>1&&K===ci&&Ot-J>500&&(w("Stall suspected; trying to fix"),this._fixupStall()),K!==ci&&(K=ci,J=Ot);let Hi=this._getBufferSizeSec();if(Hi>30)w(`Buffered ${Hi} seconds; delaying appendBuffer`),xt(2e3);else try{this.sourceBuffer.appendBuffer(z),this.videoPlayStarted?(this.bufferStates.push({ts:Ot,buf:Hi}),S(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),Se&&Se()}catch(Gr){if(Gr.name==="QuotaExceededError")w("QuotaExceededError; delaying appendBuffer"),qe=this.sourceBuffer.buffered.length,qe!==0&&(ve=this.sourceBuffer.buffered.start(0),ye=ci,ye-ve>4&&this.sourceBuffer.remove(ve,ye-3)),xt(1e3);else throw Gr}}},A=()=>{R&&M&&(w([`Appending chunk, sz=${R.byteLength}:`,JSON.stringify(P)]),x(R,function(){R=null,k()}))},B=z=>e.fragUrlTemplate.replace("%%id%%",z.chunkIdx),ne=z=>{d()&&p(B(z),(Se,ve)=>{if(d()){if(ve/=1e3,R=Se,P=z,n=z.startTS,ve){let ye=Math.min(10,z.dur/ve);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*ye:ye}A()}},()=>this._handleNetworkError())},Ne=z=>{d()&&(Da(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(B(z),!1)))},ie=z=>{d()&&(e.cachedHeader=z,x(z,()=>{M=!0,A()}))};s=!0,L.seek(z=>{if(d()){if(D=ge(),!z){E();return}V=z,!DM(y)||z.startTS>y?ne(z):(P=z,k())}},y),e.cachedHeader?ie(e.cachedHeader):f(e.headerUrl,ie,()=>this._handleNetworkError())},stop:v,getTimestampSec:()=>n},c}_switchToQuality(e){let{logger:t,playerCallback:i}=this.params,r;e.bitrate!==this.bitrate&&(this.rep&&(r=this.rep.getTimestampSec(),bo(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 bo(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,i=d=>{if(!this.autoQuality)return;let f,p,h;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&d<this.bitrate&&(p=this._getBufferSizeSec(),h=d/this.bitrate,p>10&&h>.8||p>15&&h>.5||p>20&&h>.3)){e(`Not switching: buffer=${Math.floor(p)}; bitrate=${this.bitrate}; newRate=${Math.floor(d)}`);return}f=this._selectQuality(d),f?this._switchToQuality(f):e(`Could not find quality by bitrate ${d}`)},s={updateChunk:(f,p)=>{let h=ge();if(this.chunkRateEstimator.addInterval(f,h,p)){let S=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:p,duration:h-f,speed:S}),!0}},get:()=>{let f=this.chunkRateEstimator.getBitRate();return f?f*.85:0}},n=-1/0,o,u=!0,l=()=>{let d=s.get();if(d&&o&&this.autoQuality){if(u&&d>o&&Mc(n)<3e4)return;i(d)}u=this.autoQuality};return{updateChunk:(d,f)=>{let p=s.updateChunk(d,f);return p&&l(),p},notifySwitch:d=>{let f=ge();d<o&&(n=f),o=d}}}_fetchManifest(e,t,i){this.manifestRequest=Ir(this.urlResolver.resolve(e,!0),t,i,()=>this._retryCallback()).withJSONResponse().withTimeout(go).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;Fe(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!=null&&n.length?(n.forEach((u,l)=>{var c,d;u.video&&r.canPlayType(u.codecs).replace(/no/,"")&&((d=(c=window.MediaSource)==null?void 0:c.isTypeSupported)!=null&&d.call(c,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))},BM))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};var Kv=O(ar(),1);import{debounce as FM,filter as zv,fromEvent as NM,interval as qM,isHigher as UM,isInvariantQuality as jM,isLower as HM,merge as QM,Subject as Yv,Subscription as GM}from"@vkontakte/videoplayer-shared/es2018";var Bc=class{constructor(){this.onDroopedVideoFramesLimit$=new Yv;this.subscription=new GM;this.playing=!1;this.tracks=[];this.forceChecker$=new Yv;this.isForceCheckCounter=0;this.prevTotalVideoFrames=0;this.prevDroppedVideoFrames=0;this.limitCounts={};this.handleChangeVideoQuality=()=>{let e=this.tracks.find(({size:t})=>(t==null?void 0:t.height)===this.video.videoHeight&&(t==null?void 0:t.width)===this.video.videoWidth);e&&!jM(e.quality)&&this.onChangeQuality(e.quality)};this.checkDroppedFrames=()=>{var n;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&&UM(this.currentQuality,this.droppedFramesChecker.minQualityBanLimit)&&(this.limitCounts[this.currentQuality]=((n=this.limitCounts[this.currentQuality])!=null?n:0)+1,this.maxQualityLimit=this.getMaxQualityLimit(this.currentQuality),this.currentTimer&&window.clearTimeout(this.currentTimer),this.currentTimer=window.setTimeout(()=>this.maxQualityLimit=this.getMaxQualityLimit(),this.droppedFramesChecker.qualityUpWaitingTime),this.onDroopedVideoFramesLimitTrigger()),this.savePrevFrameCounts(e,t)}}connect(e){this.log=e.logger.createComponentLog("DroppedFramesManager"),this.video=e.video,this.isAuto=e.isAuto,this.tracks=e.tracks,this.droppedFramesChecker=e.droppedFramesChecker,this.subscription.add(e.playing$.subscribe(()=>this.playing=!0)),this.subscription.add(e.pause$.subscribe(()=>this.playing=!1)),this.isEnabled&&this.subscribe()}destroy(){this.currentTimer&&window.clearTimeout(this.currentTimer),this.subscription.unsubscribe()}get droppedVideoMaxQualityLimit(){return this.maxQualityLimit}subscribe(){this.subscription.add(NM(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=qM(this.droppedFramesChecker.checkTime).pipe(zv(()=>this.playing),zv(()=>{let r=!!this.isForceCheckCounter;return r&&(this.isForceCheckCounter-=1),!r})),t=this.forceChecker$.pipe(FM(this.droppedFramesChecker.checkTime)),i=QM(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){var i,r;let t=(r=(i=(0,Kv.default)(this.limitCounts).filter(([,s])=>s>=this.droppedFramesChecker.countLimit).sort(([s],[n])=>HM(s,n)?-1:1))==null?void 0:i[0])==null?void 0:r[0];return e!=null?e:t}get isEnabled(){return this.droppedFramesChecker.enabled&&this.isDroppedFramesCheckerSupport}get isDroppedFramesCheckerSupport(){return!!this.video&&typeof this.video.getVideoPlaybackQuality=="function"}savePrevFrameCounts(e,t){this.prevTotalVideoFrames=e,this.prevDroppedVideoFrames=t}},Er=Bc;import{map as WM,Observable as zM}from"@vkontakte/videoplayer-shared/es2018";import{fromEvent as YM}from"@vkontakte/videoplayer-shared/es2018";var Ba=()=>{var a;return!!((a=window.documentPictureInPicture)!=null&&a.window)||!!document.pictureInPictureElement};var KM=(a,e)=>new zM(t=>{if(!window.IntersectionObserver)return;let i={root:null},r=new IntersectionObserver((n,o)=>{n.forEach(u=>t.next(u.isIntersecting||Ba()))},{...i,...e});r.observe(a);let s=YM(document,"visibilitychange").pipe(WM(n=>!document.hidden||Ba())).subscribe(n=>t.next(n));return()=>{r.unobserve(a),s.unsubscribe()}}),Je=KM;var aD=["paused","playing","ready"],sD=["paused","playing","ready"],Va=class{constructor(e){this.subscription=new iD;this.videoState=new j("stopped");this.representations$=new _c([]);this.droppedFramesManager=new Er;this.maxSeekBackTime$=new _c(1/0);this.zeroTime$=new _c(void 0);this.liveOffset=new ki;this._dashCb=e=>{var t,i,r,s;switch(e.name){case"buffering":{let n=e.isBuffering;this.params.output.isBuffering$.next(n);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${e.type}`,category:Zv.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{let n=e.manifest,o=[];for(let u of n){let l=(t=u.name)!=null?t:u.index.toString(10),c=(i=Kt(u.name))!=null?i:rD(u.video),d=u.bitrate/1e3,f={...u.video};if(!c)continue;let p={id:l,quality:c,bitrate:d,size:f};o.push({track:p,representation:u})}this.representations$.next(o),this.params.output.availableVideoTracks$.next(o.map(({track:u})=>u)),((r=this.videoState.getTransition())==null?void 0:r.to)==="manifest_ready"&&this.videoState.setState("manifest_ready");break}case"qualitySwitch":{let n=e.quality,o=(s=this.representations$.getValue().find(({representation:u})=>u===n))==null?void 0:s.track;this.params.output.hostname$.next(new URL(n.headerUrl,this.params.source.url).hostname),Vc(o)&&this.params.output.currentVideoTrack$.next(o);break}case"bandwidth":{let{size:n,duration:o}=e;this.params.dependencies.throughputEstimator.addRawSpeed(n,o);break}case"index":{this.maxSeekBackTime$.next(e.shiftDuration||0),this.zeroTime$.next(e.zeroTime);break}}};this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),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,Oc.default)(sD,e)&&(n||o)){this.prepare();return}if((r==null?void 0:r.to)!=="paused"&&s.state==="requested"&&(0,Oc.default)(aD,e)){this.seek(s.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(le(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==null?void 0: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(le(this.params.source.url,u))}return;default:return Xv(e)}};this.textTracksManager=new Xe(e.source.url),this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=r=>{e.output.error$.next({id:"DashLiveProvider",category:Zv.WTF,message:"DashLiveProvider internal logic error",thrown:r})};this.subscription.add(ty(this.videoState.stateChangeStarted$.pipe(So(r=>({transition:r,type:"start"}))),this.videoState.stateChangeEnded$.pipe(So(r=>({transition:r,type:"end"})))).subscribe(({transition:r,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(r)}`})})),this.video=Be(e.container,e.tuning),this.params.output.element$.next(this.video),this.dash=this.createLiveDashPlayer(),this.subscription.add(this.dash.soundProhibitedEvent$.subscribe(this.params.output.soundProhibitedEvent$)),this.params.output.duration$.next(1/0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(Ie(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=Oe(this.video);this.subscription.add(()=>i.destroy()),this.subscription.add(this.representations$.pipe(So(r=>r.map(({track:s})=>s)),ey(r=>!!r.length),tD()).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(()=>{var r;((r=this.videoState.getTransition())==null?void 0:r.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(ZM(),So(r=>-r/1e3)).subscribe(this.params.output.duration$)).add(XM({zeroTime:this.zeroTime$.pipe(ey(Vc)),position:i.timeUpdate$}).subscribe(({zeroTime:r,position:s})=>this.params.output.liveTime$.next(r+s*1e3),t)).add(bt(this.video,this.params.desiredState.isLooped,t)).add(_e(this.video,this.params.desiredState.volume,i.volumeState$,t)).add(i.volumeState$.subscribe(this.params.output.volume$,t)).add(Ke(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(Je(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:r,min:s}})=>{this.dash.setAutoQualityLimits({max:r&&iy(r),min:s&&iy(s)}),this.params.output.autoVideoTrackLimits$.next({max:r,min:s})})).add(this.videoState.stateChangeEnded$.subscribe(r=>{var s;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":((s=this.params.desiredState.playbackState.getTransition())==null?void 0:s.to)==="ready"&&this.params.desiredState.playbackState.setState("ready");break;case"paused":this.params.desiredState.playbackState.setState("paused");break;case"playing":this.params.desiredState.playbackState.setState("playing");break;default:return Xv(r.to)}},t)).add(ty(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,eD(["init"])).pipe(JM(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),Ve(this.video)}createLiveDashPlayer(){let e=new Ca({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(){var l,c,d,f,p,h;let e=this.representations$.getValue(),t=(c=(l=this.params.desiredState.videoTrack.getTransition())==null?void 0:l.to)!=null?c:this.params.desiredState.videoTrack.getState(),i=(f=(d=this.params.desiredState.autoVideoTrackSwitching.getTransition())==null?void 0:d.to)!=null?f:this.params.desiredState.autoVideoTrackSwitching.getState(),r=!i&&Vc(t)?t:vt(e.map(({track:m})=>m),{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==null?void 0:r.id,n=this.params.desiredState.videoTrack.getTransition(),o=(p=this.params.desiredState.videoTrack.getState())==null?void 0:p.id,u=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(r&&(n||s!==o)&&this.setVideoTrack(r),u&&this.setAutoQuality(i),n||u||s!==o){let m=(h=e.find(({track:S})=>S.id===s))==null?void 0:h.representation;Jv(m,"Representations missing"),this.dash.startPlay(m,i)}}setVideoTrack(e){var i;let t=(i=this.representations$.getValue().find(({track:r})=>r.id===e.id))==null?void 0:i.representation;Jv(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(le(this.params.source.url,n)),r&&this.dash.pause(),this.liveOffset.resetTo(n,r)}};var ry=Va;var II=O(Ae(),1);var Ee=(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 KB,assertNonNullable as XB,combine as JB,debounce as ZB,ErrorCategory as vI,filter as Td,filterChanged as Es,fromEvent as e0,isNonNullable as yI,isNullable as t0,map as xs,merge as ws,observableFrom as Wo,once as TI,Subscription as i0}from"@vkontakte/videoplayer-shared/es2018";var{NativeAbortSignal:_1,NativeAbortController:O1}=function(a){return{NativeAbortSignal:a.AbortSignal,NativeAbortController:a.AbortController}}(typeof self!="undefined"?self:global);function ay(a){let e;try{e=new Event("abort")}catch(t){typeof document!="undefined"?document.createEvent?(e=document.createEvent("Event"),e.initEvent("abort",!1,!1)):(e=document.createEventObject(),e.type="abort"):e={type:"abort",bubbles:!1,cancelable:!1}}return e.reason=a,e}function sy(a){if(a===void 0)if(typeof document=="undefined")a=new Error("This operation was aborted"),a.name="AbortError";else try{a=new DOMException("signal is aborted without reason"),Object.defineProperty(a,"name",{value:"AbortError"})}catch(e){a=new Error("This operation was aborted"),a.name="AbortError"}return a}var vo=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}},xr=class extends vo{constructor(){super(),this.listeners||vo.call(this),Object.defineProperty(this,"aborted",{value:!1,writable:!0,configurable:!0}),Object.defineProperty(this,"onabort",{value:null,writable:!0,configurable:!0}),Object.defineProperty(this,"reason",{value:void 0,writable:!0,configurable:!0})}toString(){return"[object AbortSignal]"}dispatchEvent(e){e.type==="abort"&&(this.aborted=!0,typeof this.onabort=="function"&&this.onabort.call(this,e)),super.dispatchEvent(e)}throwIfAborted(){let{aborted:e,reason:t="Aborted"}=this;if(e)throw t}static timeout(e){let t=new $i;return setTimeout(()=>t.abort(new DOMException(`This signal is timeout in ${e}ms`,"TimeoutError")),e),t.signal}static any(e){let t=new $i;function i(){t.abort(this.reason),r()}function r(){for(let s of e)s.removeEventListener("abort",i)}for(let s of e)if(s.aborted){t.abort(s.reason);break}else s.addEventListener("abort",i);return t.signal}},$i=class{constructor(){Object.defineProperty(this,"signal",{value:new xr,writable:!0,configurable:!0})}abort(e){let t=sy(e),i=ay(t);this.signal.reason=t,this.signal.dispatchEvent(i)}toString(){return"[object AbortController]"}};typeof Symbol!="undefined"&&Symbol.toStringTag&&($i.prototype[Symbol.toStringTag]="AbortController",xr.prototype[Symbol.toStringTag]="AbortSignal");function yo(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 Fc(a){typeof a=="function"&&(a={fetch:a});let{fetch:e,Request:t=e.Request,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r=!1}=a;if(!yo({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 f=new t(l,c);return d&&Object.defineProperty(f,"signal",{writable:!1,enumerable:!1,configurable:!0,value:d}),f},s.prototype=t.prototype);let n=e;return{fetch:(u,l)=>{let c=s&&s.prototype.isPrototypeOf(u)?u.signal:l?l.signal:void 0;if(c){let d;try{d=new DOMException("Aborted","AbortError")}catch(p){d=new Error("Aborted"),d.name="AbortError"}if(c.aborted)return Promise.reject(d);let f=new Promise((p,h)=>{c.addEventListener("abort",()=>h(d),{once:!0})});return l&&l.signal&&delete l.signal,Promise.race([f,n(u,l)])}return n(u,l)},Request:s}}var nD=()=>"fetch"in window,_a=nD()&&yo({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),ny=_a?Fc({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,Ze=_a?ny.fetch:window.fetch,z1=_a?ny.Request:window.Request,Z=_a?$i:window.AbortController,Y1=_a?xr:window.AbortSignal;var mI=O(Ae(),1),md=O(Oa(),1);var Gy=O(Qy(),1);import{ErrorCategory as Na}from"@vkontakte/videoplayer-shared/es2018";var To=a=>{if(!a)return{id:"EmptyResponse",category:Na.PARSER,message:"Empty response"};if(a.length<=2&&a.match(/^\d+$/))return{id:`UVError#${a}`,category:Na.NETWORK,message:`UV Error ${a}`};let e=(0,Gy.default)(a).substring(0,100).toLowerCase();if(e.startsWith("<!doctype")||e.startsWith("<html>")||e.startsWith("<body>")||e.startsWith("<head>"))return{id:"UnexpectedHTML",category:Na.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:Na.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:Na.PARSER,message:"Response is valid XML, but parser failed"}};var xe=(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 pd,assertNonNullable as Br,combine as Vr,ErrorCategory as ct,filter as No,filterChanged as vs,flattenObject as ys,fromEvent as Bt,getTraceSubscriptionMethod as MB,interval as hd,isNonNullable as Ts,isNullable as pI,map as _r,merge as Vi,now as fd,Subject as ri,Subscription as hI,tap as DB,throttle as CB,ValueSubject as ae}from"@vkontakte/videoplayer-shared/es2018";var wo=O(Ae(),1),Bi=O(ot(),1),Ao=O(Oa(),1);var QD=(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)},GD=a=>window.clearTimeout(a),Wy=a=>typeof a=="function"&&(a==null?void 0:a.toString().endsWith("{ [native code] }")),zy=!Wy(window.requestIdleCallback)||!Wy(window.cancelIdleCallback),wr=zy?QD:window.requestIdleCallback,yt=zy?GD:window.cancelIdleCallback;var aI=O(Hn(),1);import{assertNever as WD,ErrorCategory as Yy,Subject as Ky}from"@vkontakte/videoplayer-shared/es2018";var zD=18,Xy=!1;try{Xy=F.browser.isSafari&&!!F.browser.safariVersion&&F.browser.safariVersion<=zD}catch(a){console.error(a)}var Qc=class{constructor(e){this.bufferFull$=new Ky;this.error$=new Ky;this.queue=[];this.currentTask=null;this.destroyed=!1;this.abortRequested=!1;this.completeTask=()=>{var e;try{if(this.currentTask){let t=(e=this.currentTask.signal)==null?void 0:e.aborted;this.currentTask.callback(!t),this.currentTask=null}this.queue.length&&this.pull()}catch(t){this.error$.next({id:"BufferTaskQueueUnknown",category:Yy.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:t})}};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)};Xy&&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(){var r;if((this.buffer.updating||this.currentTask||this.destroyed)&&!this.abortRequested)return;let e=this.queue.shift();if(!e)return;if((r=e.signal)!=null&&r.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(s){s instanceof DOMException&&s.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):s instanceof DOMException&&s.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:Yy.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:s}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){let{operation:t}=e;switch(t){case"append":this.buffer.appendBuffer(e.data);break;case"remove":this.buffer.remove(e.from/1e3,e.to/1e3);break;case"abort":this.buffer.abort();break;case"safariAbort":{this.buffer.abort(),this.buffer.appendBuffer(e.init);break}default:WD(t)}}},Jy=Qc;var Ar=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 Zt,assertNonNullable as $e,ErrorCategory as Mt,fromEvent as sd,getExponentialDelay as nd,isHigher as bB,isNonNullable as ei,isNullable as he,now as xo,once as gB,Subject as SB,Subscription as vB,ValueSubject as Ci}from"@vkontakte/videoplayer-shared/es2018";var Zy=O(ot(),1);var Io=a=>a.valid,Q=class{constructor(e,t){this.cursor=0;this.source=e,this.boxParser=t,this.children=[];let i=this.readUint32();this.type=this.readString(4),i===1&&(this.cursor+=8);let r=e.byteOffset+this.cursor,s;i===0?(this.size=void 0,this.valid=!1,s=void 0):i===1?(this.size=void 0,this.valid=!1,s=void 0):i>e.byteLength?(this.size=i,this.valid=!1,s=Math.min(i-this.cursor,e.byteLength-this.cursor)):(this.size=i,this.valid=!0,s=i-this.cursor),this.content=new DataView(e.buffer,r,s)}get id(){return this.type}scanForBoxes(e){return this.boxParser.parse(e)}readString(e,t="ascii"){let r=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,r}readUint8(){let e=this.source.getUint8(this.cursor);return this.cursor+=1,e}readUint16(){let e=this.source.getUint16(this.cursor);return this.cursor+=2,e}readUint32(){let e=this.source.getUint32(this.cursor);return this.cursor+=4,e}readUint64(){let e=this.source.getBigInt64(this.cursor);return this.cursor+=8,e}};var Rr=class extends Q{};import{assertNever as YD}from"@vkontakte/videoplayer-shared/es2018";var qa=class extends Q{constructor(e,t){if(super(e,t),!this.valid)return;let i=this.readString(16),r=new DataView(this.content.buffer,this.content.byteOffset+16,this.content.byteLength-16);this.userData=this.parseData(i,r)}parseData(e,t){switch(e){case"ondemandlivejson":{let i=new TextDecoder("ascii").decode(t),r=JSON.parse(i);return{received:r["t-in"],prepared:r["t-out"]}}default:YD(e)}}};var Ua=class extends Q{constructor(e,t){if(super(e,t),!this.valid)return;this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let i=new DataView(this.content.buffer,this.content.byteOffset+8,this.content.byteLength-8);for(let r=0;r<i.byteLength;r+=4){let s=this.readString(4);this.compatibleBrands.push(s)}}};var ja=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var re=class extends Q{constructor(e,t){if(super(e,t),!this.valid)return;let i=this.readUint32();this.version=i>>>24,this.flags=i&16777215,this.content=new DataView(this.content.buffer,this.content.byteOffset+4,this.content.byteLength-4)}};var Ha=class extends re{constructor(e,t){super(e,t),this.valid&&(this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.timescale=this.readUint32(),this.duration=this.readUint32(),this.rate=this.readUint32(),this.volume=this.readUint16())}};var Qa=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ga=class extends Q{constructor(e,t){super(e,t),this.data=this.content}};var Mi=class extends re{get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e,t){if(super(e,t),!!this.valid){this.segments=[],this.referenceId=this.readUint32(),this.timescale=this.readUint32(),this.earliestPresentationTime32=this.readUint32(),this.firstOffset32=this.readUint32(),this.earliestPresentationTime64=0,this.firstOffset64=0,this.referenceCount=this.readUint32()&65535;for(let i=0;i<this.referenceCount;i++){let r=this.readUint32(),s=r>>>31,n=r<<1>>>1,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 Wa=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var za=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ya=class extends re{constructor(e,t){if(super(e,t),!this.valid)return;switch(this.readUint8()){case 0:this.stereoMode=0;break;case 1:this.stereoMode=1;break;case 2:this.stereoMode=2;break;case 3:this.stereoMode=3;break;case 4:this.stereoMode=4;break}this.cursor+=1}};var Ka=class extends re{constructor(e,t){super(e,t),this.valid&&(this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32())}};var Xa=class extends re{constructor(e,t){super(e,t),this.valid&&(this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32())}};var Ja=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Za=class extends re{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 es=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ts=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var is=class extends re{constructor(e,t){super(e,t),this.valid&&(this.sequenceNumber=this.readUint32())}};var rs=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var as=class extends re{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 ss=class extends re{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 ns=class extends re{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 os=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var us=class extends re{constructor(e,t){super(e,t),this.valid&&(this.entryCount=this.readUint32(),this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+4,this.content.byteLength-4)))}};var ls=class extends Q{constructor(e,t){super(e,t),this.valid&&(this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+78,this.content.byteLength-78)))}};var XD={ftyp:Ua,moov:ja,mvhd:Ha,moof:Qa,mdat:Ga,sidx:Mi,trak:Wa,mdia:Ja,mfhd:is,tkhd:Za,traf:rs,tfhd:as,tfdt:ss,trun:ns,minf:es,sv3d:za,st3d:Ya,prhd:Ka,proj:ts,equi:Xa,uuid:qa,stbl:os,stsd:us,avc1:ls,unknown:Rr},$t=class a{constructor(e={}){this.options={offset:0,...e}}parse(e){let t=[],i=this.options.offset;for(;i<e.byteLength;){let s=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+i+4,4)),n;try{n=this.createBox(s,new DataView(e.buffer,e.byteOffset+i,e.byteLength-i))}catch(o){if(!(o instanceof RangeError))throw o}if(!n||!Io(n))break;t.push(n),i+=n.size}return t}createBox(e,t){let i=XD[e];return i?new i(t,new a):new Rr(t,new a)}};var Jt=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{var i,r,s;Io(t)&&((s=(i=this.index)[r=t.type])!=null||(i[r]=[]),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 ZD=new TextDecoder("ascii"),eC=a=>ZD.decode(new DataView(a.buffer,a.byteOffset+4,4))==="ftyp",tC=a=>{let e=new Mi(a,new $t),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})},iC=(a,e)=>{let i=new $t().parse(a),r=new Jt(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)},rC=a=>{let t=new $t().parse(a),i=new Jt(t),r={},s=i.findAll("uuid"),n=(0,Zy.default)(s,-1);return n?{serverDataReceivedTimestamp:n.userData.received,serverDataPreparedTime:n.userData.received}:r},aC=a=>{var r;let t=new $t().parse(a);return(r=new Jt(t).find("sidx"))==null?void 0:r.timescale},sC=(a,e)=>{let i=new $t().parse(a),s=new Jt(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,f)=>d+f,0):l=n.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+l)/e*1e3},nC=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 $t().parse(a),r=new Jt(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},eT={validateData:eC,parseInit:nC,getIndexRange:()=>{},parseSegments:tC,parseFeedableSegmentChunk:iC,getChunkEndTime:sC,getServerLatencyTimestamps:rC,getTimescaleFromIndex:aC};var ps=O(Ae(),1);import{assertNonNullable as Gc,isNonNullable as aT,isNullable as uC}from"@vkontakte/videoplayer-shared/es2018";import{assertNever as oC}from"@vkontakte/videoplayer-shared/es2018";var tT={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"}},iT=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=ds(a,t),r=i in tT,s=r?tT[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=ds(u),d=l*2**((o-1)*8)+c,f=t+o,p;return f+d>a.byteLength?p=new DataView(a.buffer,a.byteOffset+f):p=new DataView(a.buffer,a.byteOffset+f,d),{tag:r?i:"0x"+i.toString(16).toUpperCase(),type:s,tagHeaderSize:f,tagSize:f+d,value:p,valueSize:d}},ds=(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},ut=(a,e)=>{switch(e){case"int":return a.getInt8(0);case"uint":return ds(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:oC(e)}},Di=(a,e)=>{let t=0;for(;t<a.byteLength;){let i=new DataView(a.buffer,a.byteOffset+t),r=iT(i);if(!e(r))return;r.type==="master"&&Di(r.value,e),t=r.value.byteOffset-a.byteOffset+r.valueSize}},rT=a=>{if(a.getUint32(0)!==440786851)return!1;let e,t,i,r=iT(a);return Di(r.value,({tag:s,type:n,value:o})=>(s===17143?e=ut(o,n):s===17026?t=ut(o,n):s===17029&&(i=ut(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)};var sT=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],lC=[231,22612,22743,167,171,163,160,175],cC=a=>{let e,t,i,r,s=!1,n=!1,o=!1,u,l,c=!1,d=0;return Di(a,({tag:f,type:p,value:h,valueSize:m})=>{if(f===21419){let S=ut(h,p);l=ds(S)}else f!==21420&&(l=void 0);return f===408125543?(e=h.byteOffset,t=h.byteOffset+m):f===357149030?s=!0:f===290298740?n=!0:f===2807729?i=ut(h,p):f===17545?r=ut(h,p):f===21420&&l===475249515?u=ut(h,p):f===374648427?Di(h,({tag:S,type:b,value:v})=>S===30321?(c=ut(v,b)===1,!1):!0):s&&n&&(0,ps.default)(sT,f)&&(o=!0),!o}),Gc(e,"Failed to parse webm Segment start"),Gc(t,"Failed to parse webm Segment end"),Gc(r,"Failed to parse webm Segment duration"),i=i!=null?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}}}},dC=a=>{if(uC(a.cuesSeekPosition))return;let e=a.segmentStart+a.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},pC=(a,e)=>{let t=!1,i=!1,r=o=>aT(o.time)&&aT(o.position),s=[],n;return Di(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=ut(l,u));break;case 183:break;case 241:n&&(n.position=ut(l,u));break;default:t&&(0,ps.default)(sT,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}}})},hC=a=>{let e=0,t=!1;try{Di(a,i=>i.tag===524531317?i.tagSize<=a.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):(0,ps.default)(lC,i.tag)?(e+i.tagSize<=a.byteLength&&(e+=i.tagSize,t||(t=(0,ps.default)([163,160,175],i.tag))),!0):!1)}catch(i){}return e>0&&e<=a.byteLength&&t?new DataView(a.buffer,a.byteOffset,e):null},nT={validateData:rT,parseInit:cC,getIndexRange:dC,parseSegments:pC,parseFeedableSegmentChunk:hC};var Tt=a=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(a);if(e){let[,t,i]=e;if(t==="audio"||t==="video")switch(i){case"webm":return nT;case"mp4":return eT}}throw new ReferenceError(`Unsupported mime type ${a}`)};var It=a=>a instanceof DOMException&&(a.name==="AbortError"||a.code===20);var Zc=O(kT(),1),XT=O(ar(),1),JT=O(QT(),1),ZT=O(ot(),1),ed=O(br(),1);var GT=O(Ae(),1),Jc=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,GT.default)(["6E","7A","F4"],o)}}return!1};import{isNonNullable as hB,isNullable as YT}from"@vkontakte/videoplayer-shared/es2018";var WT=a=>{if(a.includes("/")){let e=a.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(a)};var zT=a=>{var e;try{let t=pB(),i=a.match(t),{groups:r}=i!=null?i:{};if(r){let s={};if(r.extensions){let u=r.extensions.toLowerCase().match(/(?:[0-9a-wy-z](?:-[a-z0-9]{2,8})+)/g);Array.from(u||[]).forEach(l=>{s[l[0]]=l.slice(2)})}let n=(e=r.variants)==null?void 0:e.split(/-/).filter(u=>u!==""),o={extlang:r.extlang,langtag:r.langtag,language:r.language,privateuse:r.privateuse||r.privateuse2,region:r.region,script:r.script,extensions:s,variants:n};return Object.keys(o).forEach(u=>{let l=o[u];(typeof l=="undefined"||l==="")&&delete o[u]}),o}return null}catch(t){return null}};function pB(){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 zT=a=>{if(!(a!=null&&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==null?void 0:i[1])==="-"?-1:1,s={days:e(i==null?void 0:i[5],r),hours:e(i==null?void 0:i[6],r),minutes:e(i==null?void 0:i[7],r),seconds:e(i==null?void 0:i[8],r)};return s.days*24*60*60*1e3+s.hours*60*60*1e3+s.minutes*60*1e3+s.seconds*1e3},lt=(a,e)=>{let t=a;t=(0,Gc.default)(t,"$$","$");let i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[r,s]of(0,YT.default)(i)){let n=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=(0,Gc.default)(t,n,(o,u)=>GT(s)?o:GT(u)?s:(0,KT.default)(s,parseInt(u,10),"0"))}return t},mo=(a,e)=>{var A,P,V,D,_,K,J,I,R,x,w,B,ne,Ne,ie,z,ge,ve,Se,qe,xt,Ot,ui,Ui,Wr,np,op,up,lp,cp,dp,pp,hp,fp,mp,bp,gp,vp,Sp,yp,Tp,Ip,Ep,xp,wp,Ap,Pp,Rp,kp,Lp,$p,Mp,Dp,Cp,Bp,Vp,_p,Op,Fp,Np,qp;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(et=>{var te,li;return(li=(te=et.textContent)==null?void 0:te.trim())!=null?li:""}),o=(A=(0,XT.default)(n,0))!=null?A:"",u=s.getAttribute("type")==="dynamic",l=s.getAttribute("availabilityStartTime"),c=s.getAttribute("publishTime"),d=s.getElementsByTagName("vk:Attrs")[0],f=d==null?void 0:d.getElementsByTagName("vk:XLatestSegmentPublishTime")[0].textContent,p=d==null?void 0:d.getElementsByTagName("vk:XStreamIsLive")[0].textContent,h=d==null?void 0:d.getElementsByTagName("vk:XStreamIsUnpublished")[0].textContent,m=d==null?void 0:d.getElementsByTagName("vk:XPlaybackDuration")[0].textContent,v;u&&(v={availabilityStartTime:l?new Date(l).getTime():0,publishTime:c?new Date(c).getTime():0,latestSegmentPublishTime:f?new Date(f).getTime():0,streamIsAlive:p==="yes",streamIsUnpublished:h==="yes"});let b,S=s.getAttribute("mediaPresentationDuration"),T=[...s.getElementsByTagName("Period")],y=T.reduce((et,te)=>({...et,[te.id]:te.children}),{}),E=T.reduce((et,te)=>({...et,[te.id]:te.getAttribute("duration")}),{});S?b=zT(S):(0,zc.default)(E).filter(et=>et).length&&!u?b=(0,zc.default)(E).reduce((et,te)=>{var li;return et+((li=zT(te))!=null?li:0)},0):m&&(b=parseInt(m,10));let k=0,M=(V=(P=s.getAttribute("profiles"))==null?void 0:P.split(","))!=null?V:[];for(let et of T.map(te=>te.id))for(let te of y[et]){let li=(D=te.getAttribute("id"))!=null?D:"id"+(k++).toString(10),Gr=(_=te.getAttribute("mimeType"))!=null?_:"",pu=(K=te.getAttribute("codecs"))!=null?K:"",hu=(J=te.getAttribute("contentType"))!=null?J:Gr==null?void 0:Gr.split("/")[0],NE=(R=(I=te.getAttribute("profiles"))==null?void 0:I.split(","))!=null?R:[],Up=(w=WT((x=te.getAttribute("lang"))!=null?x:""))!=null?w:{},qs=(Ne=(ne=(B=te.querySelector("Label"))==null?void 0:B.textContent)==null?void 0:ne.trim())!=null?Ne:void 0,qE=te.querySelectorAll("Representation"),UE=te.querySelector("SegmentTemplate"),HE=(z=(ie=te.querySelector("Role"))==null?void 0:ie.getAttribute("value"))!=null?z:void 0,Hi=hu,de={id:li,language:Up.language,isDefault:HE==="main",label:qs,codecs:pu,hdr:Hi==="video"&&Wc(pu),mime:Gr,representations:[]};for(let ee of qE){let Ft=(ge=ee.getAttribute("lang"))!=null?ge:void 0,zr=(Se=(ve=qs!=null?qs:te.getAttribute("label"))!=null?ve:ee.getAttribute("label"))!=null?Se:void 0,Us=(Ot=(xt=(qe=ee.querySelector("BaseURL"))==null?void 0:qe.textContent)==null?void 0:xt.trim())!=null?Ot:"",ci=new URL(Us||o,e).toString(),Nt=(ui=ee.getAttribute("mimeType"))!=null?ui:Gr,Hs=(Wr=(Ui=ee.getAttribute("codecs"))!=null?Ui:pu)!=null?Wr:"",js;if(hu==="text"){let qt=ee.getAttribute("id")||"",Qs=((np=Up.privateuse)==null?void 0:np.includes("x-auto"))||qt.includes("_auto"),di=ee.querySelector("SegmentTemplate");if(di){let Yr={representationId:(op=ee.getAttribute("id"))!=null?op:void 0,bandwidth:(up=ee.getAttribute("bandwidth"))!=null?up:void 0},Ws=parseInt((lp=ee.getAttribute("bandwidth"))!=null?lp:"",10)/1e3,Gs=(dp=parseInt((cp=di.getAttribute("startNumber"))!=null?cp:"",10))!=null?dp:1,ji=parseInt((pp=di.getAttribute("timescale"))!=null?pp:"",10),fu=(hp=di.querySelectorAll("SegmentTimeline S"))!=null?hp:[],Qi=di.getAttribute("media");if(!Qi)continue;let zs=[],Ys=0,Ks="",Wi=0,Kr=Gs,we=0;for(let tt of fu){let pi=parseInt((fp=tt.getAttribute("d"))!=null?fp:"",10),Ye=parseInt((mp=tt.getAttribute("r"))!=null?mp:"",10)||0,Ut=parseInt((bp=tt.getAttribute("t"))!=null?bp:"",10);we=Number.isFinite(Ut)?Ut:we;let hi=pi/ji*1e3,Ht=we/ji*1e3;for(let pt=0;pt<Ye+1;pt++){let jt=lt(Qi,{...Yr,segmentNumber:Kr.toString(10),segmentTime:(we+pt*pi).toString(10)}),Gi=(Ht!=null?Ht:0)+pt*hi,Jr=Gi+hi;Kr++,zs.push({time:{from:Gi,to:Jr},url:jt})}we+=(Ye+1)*pi,Ys+=(Ye+1)*hi}Wi=we/ji*1e3,Ks=lt(Qi,{...Yr,segmentNumber:Kr.toString(10),segmentTime:we.toString(10)});let Xr={time:{from:Wi,to:1/0},url:Ks},wt={type:"template",baseUrl:ci,segmentTemplateUrl:Qi,initUrl:"",totalSegmentsDurationMs:Ys,segments:zs,nextSegmentBeyondManifest:Xr,timescale:ji};js={id:qt,kind:"text",segmentReference:wt,profiles:[],duration:b,bitrate:Ws,mime:"",codecs:"",width:0,height:0,isAuto:Qs}}else js={id:qt,isAuto:Qs,kind:"text",url:ci}}else{let qt=(vp=(gp=ee.getAttribute("contentType"))!=null?gp:Nt==null?void 0:Nt.split("/")[0])!=null?vp:hu,Qs=(yp=(Sp=te.getAttribute("profiles"))==null?void 0:Sp.split(","))!=null?yp:[],di=parseInt((Tp=ee.getAttribute("width"))!=null?Tp:"",10),Yr=parseInt((Ip=ee.getAttribute("height"))!=null?Ip:"",10),Ws=parseInt((Ep=ee.getAttribute("bandwidth"))!=null?Ep:"",10)/1e3,Gs=(xp=ee.getAttribute("frameRate"))!=null?xp:"",ji=(wp=ee.getAttribute("quality"))!=null?wp:void 0,fu=Gs?QT(Gs):void 0,Qi=(Ap=ee.getAttribute("id"))!=null?Ap:"id"+(k++).toString(10),zs=qt==="video"?`${Yr}p`:qt==="audio"?`${Ws}Kbps`:Hs,Ys=`${Qi}@${zs}`,Ks=[...M,...NE,...Qs],Wi,Kr=ee.querySelector("SegmentBase"),we=(Pp=ee.querySelector("SegmentTemplate"))!=null?Pp:UE;if(Kr){let wt=(kp=(Rp=ee.querySelector("SegmentBase Initialization"))==null?void 0:Rp.getAttribute("range"))!=null?kp:"",[tt,pi]=wt.split("-").map(jt=>parseInt(jt,10)),Ye={from:tt,to:pi},Ut=(Lp=ee.querySelector("SegmentBase"))==null?void 0:Lp.getAttribute("indexRange"),[hi,Ht]=Ut?Ut.split("-").map(jt=>parseInt(jt,10)):[],pt=Ut?{from:hi,to:Ht}:void 0;Wi={type:"byteRange",url:ci,initRange:Ye,indexRange:pt}}else if(we){let wt={representationId:($p=ee.getAttribute("id"))!=null?$p:void 0,bandwidth:(Mp=ee.getAttribute("bandwidth"))!=null?Mp:void 0},tt=parseInt((Dp=we.getAttribute("timescale"))!=null?Dp:"",10),pi=(Cp=we.getAttribute("initialization"))!=null?Cp:"",Ye=we.getAttribute("media"),Ut=(Vp=parseInt((Bp=we.getAttribute("startNumber"))!=null?Bp:"",10))!=null?Vp:1,hi=lt(pi,wt);if(!Ye)throw new ReferenceError("No media attribute in SegmentTemplate");let Ht=(_p=we.querySelectorAll("SegmentTimeline S"))!=null?_p:[],pt=[],jt=0,Gi="",Jr=0;if(Ht.length){let Xs=Ut,it=0;for(let zi of Ht){let ht=parseInt((Op=zi.getAttribute("d"))!=null?Op:"",10),fi=parseInt((Fp=zi.getAttribute("r"))!=null?Fp:"",10)||0,Js=parseInt((Np=zi.getAttribute("t"))!=null?Np:"",10);it=Number.isFinite(Js)?Js:it;let mu=ht/tt*1e3,bu=it/tt*1e3;for(let Zs=0;Zs<fi+1;Zs++){let QE=lt(Ye,{...wt,segmentNumber:Xs.toString(10),segmentTime:(it+Zs*ht).toString(10)}),Hp=(bu!=null?bu:0)+Zs*mu,WE=Hp+mu;Xs++,pt.push({time:{from:Hp,to:WE},url:QE})}it+=(fi+1)*ht,jt+=(fi+1)*mu}Jr=it/tt*1e3,Gi=lt(Ye,{...wt,segmentNumber:Xs.toString(10),segmentTime:it.toString(10)})}else if(hB(b)){let it=parseInt((qp=we.getAttribute("duration"))!=null?qp:"",10)/tt*1e3,zi=Math.ceil(b/it),ht=0;for(let fi=1;fi<zi;fi++){let Js=lt(Ye,{...wt,segmentNumber:fi.toString(10),segmentTime:ht.toString(10)});pt.push({time:{from:ht,to:ht+it},url:Js}),ht+=it}Jr=ht,Gi=lt(Ye,{...wt,segmentNumber:zi.toString(10),segmentTime:ht.toString(10)})}let jE={time:{from:Jr,to:1/0},url:Gi};Wi={type:"template",baseUrl:ci,segmentTemplateUrl:Ye,initUrl:hi,totalSegmentsDurationMs:jt,segments:pt,nextSegmentBeyondManifest:jE,timescale:tt}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!qt||!Nt)continue;let Xr={video:"video",audio:"audio",text:"text"}[qt];if(!Xr)continue;Hi||(Hi=Xr),js={id:Ys,kind:Xr,segmentReference:Wi,profiles:Ks,duration:b,bitrate:Ws,mime:Nt,codecs:Hs,width:di,height:Yr,fps:fu,quality:ji}}de.language||(de.language=Ft),de.label||(de.label=zr),de.mime||(de.mime=Nt),de.codecs||(de.codecs=Hs),de.hdr||(de.hdr=Hi==="video"&&Wc(Hs)),de.representations.push(js)}if(Hi){let ee=r[Hi].find(Ft=>Ft.id===de.id);if(ee&&de.representations.every(Ft=>Ft.segmentReference.type==="template"))for(let Ft of ee.representations){let zr=de.representations.find(Nt=>Nt.id===Ft.id),Us=zr==null?void 0:zr.segmentReference,ci=Ft.segmentReference;ci.segments.push(...Us.segments),ci.nextSegmentBeyondManifest=Us.nextSegmentBeyondManifest}else r[Hi].push(de)}}return{duration:b,streams:r,baseUrls:n,live:v}};var Yc=O(ot(),1);import{videoSizeToQuality as fB}from"@vkontakte/videoplayer-shared/es2018";var JT=({id:a,width:e,height:t,bitrate:i,fps:r,quality:s,streamId:n})=>{var u;let o=(u=s?Kt(s):void 0)!=null?u:fB({width:e,height:t});return o&&{id:a,quality:o,bitrate:i,size:{width:e,height:t},fps:r,streamId:n}},ZT=({id:a,bitrate:e})=>({id:a,bitrate:e}),eI=({language:a,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:a,label:e}),tI=({language:a,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:a,label:e}),Kc=({id:a,language:e,label:t,codecs:i,isDefault:r})=>({id:a,language:e,label:t,codec:(0,Yc.default)(i.split("."),0),isDefault:r}),Xc=({id:a,language:e,label:t,hdr:i,codecs:r})=>({id:a,language:e,hdr:i,label:t,codec:(0,Yc.default)(r.split("."),0)}),Jc=a=>"url"in a,We=a=>a.type==="template";import{isNonNullable as iI}from"@vkontakte/videoplayer-shared/es2018";var N=(a,e)=>iI(a)&&iI(e)&&a.readyState==="open"&&mB(a,e);function mB(a,e){for(let t=0;t<a.activeSourceBuffers.length;++t)if(a.activeSourceBuffers[t]===e)return!0;return!1}var hs=class{constructor(e,t,i,{fetcher:r,tuning:s,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new Mi(0);this.currentLowLatencySegmentLength$=new Mi(0);this.currentSegmentLength$=new Mi(0);this.onLastSegment$=new Mi(!1);this.fullyBuffered$=new Mi(!1);this.playingRepresentation$=new Mi(void 0);this.playingRepresentationInit$=new Mi(void 0);this.error$=new gB;this.gaps=[];this.subscription=new vB;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new Z;this.switchAbortController=new Z;this.destroyAbortController=new Z;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=Zt(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);Oe(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new Ky(this.sourceBuffer),this.subscription.add(Zc(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let o,u=this.mediaSource.readyState;u!=="open"&&(o={id:`SegmentEjection_source_${u}`,category:Mt.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o!=null||(o={id:"SegmentEjection",category:Mt.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),this.error$.next(o)})),this.subscription.add(Zc(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:Mt.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o||!N(this.mediaSource,this.sourceBuffer))return;let u=Math.min(this.bufferLimit,xr(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);Oe(i,"No init buffer for starting representation"),Oe(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=Zt(this.destroyAbortController.signal,async function*(e,t=!1){if(!N(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);Oe(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if(Ee(s)||Ee(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),Oe(r,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!N(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();kr(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=Zt(this.destroyAbortController.signal,async function*(e,t=!1){if(!N(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);Oe(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if(Ee(s)||Ee(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),Oe(r,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!N(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();kr(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=Zt(this.destroyAbortController.signal,async function*(e){var u,l;let t=(u=(0,vo.default)(e,c=>c.representations))!=null?u:[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let c of this.representations.keys()){let d=t.find(h=>h.id===c);d&&this.representations.set(c,d);let f=this.representations.get(c);if(!f||!We(f.segmentReference))return;let p=this.getActualLiveStartingSegments(f.segmentReference);this.segments.set(f.id,p)}let i=(l=this.switchingToRepresentationId)!=null?l:this.downloadingRepresentationId,r=this.representations.get(i);Oe(r);let s=this.segments.get(i);Oe(s,"No segments for starting representation");let n=this.initData.get(i);if(Oe(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));var c;this.fetcher=r,this.tuning=s,this.compatibilityMode=u,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=o,this.isLive=!!(l!=null&&l.live),this.baseUrls=(c=l==null?void 0:l.baseUrls)!=null?c:[],this.initData=new Map(i.map(d=>[d.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(i.map(d=>[d.id,d])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}switchToWithPreviousAbort(e,t=!1){!N(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new Z,Zt(this.switchAbortController.signal,async function*(i,r=!1){this.switchingToRepresentationId=i;let s=this.representations.get(i);Oe(s,`No such representation ${i}`);let n=this.segments.get(i),o=this.initData.get(i);if(Ee(o)||Ee(n)?yield this.loadInit(s,"high",!1):o instanceof Promise&&(yield o),n=this.segments.get(i),Oe(n,"No segments for starting representation"),o=this.initData.get(i),!(!(o instanceof ArrayBuffer)||!this.sourceBuffer||!N(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();kr(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(){!Ee(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 Z,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(Ee(e)||Ee(this.downloadingRepresentationId)||Ee(this.playingRepresentationId)||Ee(this.sourceBuffer)||!N(this.mediaSource,this.sourceBuffer)||kr(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if(Oe(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;let r=i.find(c=>e>=c.time.from&&e<c.time.to);kr(r)&&isFinite(r.time.from)&&isFinite(r.time.to)&&this.currentSegmentLength$.next((r==null?void 0: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)&&xr(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(f=>{this.handleAsyncError(f,"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,go.default)(u,r))c="high";else{let d=(0,Di.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,Di.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;kr(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,vo.default)(e==null?void 0: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!=null&&i.length)return{from:i[0].time.from,to:i[i.length-1].time.to}}updateLive(e){var i,r,s,n;let t=(i=(0,vo.default)(e==null?void 0:e.streams[this.kind],o=>o.representations))!=null?i:[];if(![...this.segments.values()].every(o=>!o.length))for(let o of t){if(!o||!We(o.segmentReference))return;let u=o.segmentReference.segments.map(p=>({...p,status:"none",size:void 0})),l=100,c=(r=this.segments.get(o.id))!=null?r:[],d=(n=(s=(0,Di.default)(c,-1))==null?void 0:s.time.to)!=null?n:0,f=u==null?void 0:u.findIndex(p=>d>=p.time.from+l&&d<=p.time.to+l);if(f===-1){this.liveUpdateSegmentIndex=0;let p=this.getActualLiveStartingSegments(o.segmentReference);this.segments.set(o.id,p)}else{let p=u.slice(f+1);this.segments.set(o.id,[...c,...p])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;Oe(e);let t=this.segments.get(e);if(t!=null&&t.length){let i=t[t.length-1];this.updateLowLatencyLiveIfNeeded(i)}}calculateDurationFromSegments(){var t;if(!this.playingRepresentationId)return 0;let e=this.segments.get(this.playingRepresentationId);return(e?(t=(0,Di.default)(e,-1))==null?void 0:t.time.to:0)||0}updateLowLatencyLiveIfNeeded(e){var i;let t=0;for(let r of this.representations.values()){let s=r.segmentReference;if(!We(s))return;let n=(i=this.segments.get(r.id))!=null?i:[],o=n.find(l=>Math.floor(l.time.from)===Math.floor(e.time.from));if(o&&!isFinite(o.time.to)&&(o.time.to=e.time.to,t=o.time.to-o.time.from),!!!n.find(l=>Math.floor(l.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let l=Math.round(e.time.to*s.timescale/1e3).toString(10),c=lt(s.segmentTemplateUrl,{segmentTime:l});n.push({status:"none",time:{from:e.time.to,to:1/0},url:c})}}this.currentLowLatencySegmentLength$.next(t)}findSegmentStartTime(e){var s,n,o;let t=(n=(s=this.switchingToRepresentationId)!=null?s:this.downloadingRepresentationId)!=null?n:this.playingRepresentationId;if(!t)return;let i=this.segments.get(t);if(!i)return;let r=i.find(u=>u.time.from<=e&&u.time.to>=e);return(o=r==null?void 0:r.time.from)!=null?o:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){var e;if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),(e=this.sourceBufferTaskQueue)==null||e.destroy(),this.gapDetectionIdleCallback&&yt&&yt(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&yt&&yt(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer)try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(t){if(!(t instanceof DOMException&&t.name==="NotFoundError"))throw t}this.sourceBuffer=null,this.downloadAbortController.abort(),this.switchAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,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:f,time:{from:p,to:h}},m)=>{let v=p<=i&&h>=i,b=p>i||v||m===0&&i===0,S=Math.min(this.forwardBufferTarget,this.bufferLimit),T=this.preloadOnly&&p<=i+S||r<S&&h-p>=S||h<=i+S;return(f==="none"||f==="partially_ejected"&&b&&T&&this.sourceBuffer&&N(this.mediaSource,this.sourceBuffer)&&!(Ie(this.sourceBuffer.buffered,p)&&Ie(this.sourceBuffer.buffered,h)))&&b&&T});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 f=s;f<n.length&&(o<=c||u<=d);f++){let p=n[f];if(o+=p.byte.to+1-p.byte.from,u+=p.time.to+1-p.time.from,p.status==="none"||p.status==="partially_ejected")l.push(p);else break}return l}async loadSegments(e,t,i="auto"){We(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 Zt(o,async function*(){let c=ed(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(),bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation});if(this.lastDataObtainedTimestampMs=bo(),!c)return;let d=new DataView(c),f=Tt(t.mime);if(!isFinite(r.segment.time.to)){let m=t.segmentReference.timescale;r.segment.time.to=f.getChunkEndTime(d,m)}u&&r.feedingBytes&&l?await Promise.all(l):await this.sourceBufferTaskQueue.append(d,o);let{serverDataReceivedTimestamp:p,serverDataPreparedTime:h}=f.getServerLatencyTimestamps(d);p&&h&&this.currentLiveSegmentServerLatency$.next(h-p),r.segment.status="downloaded",this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(c){this.abortActiveSegments([e]),It(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())We(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 Zt(n,async function*(){let u=ed(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),Zc(window,"online").pipe(bB()).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,bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation}),this.lastDataObtainedTimestampMs=bo(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),It(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}prepareByteRangeFetchSegmentParams(e,t){if(We(t.segmentReference))throw new Error("Representation is not byte range type");let i=t.segmentReference.url,r={from:(0,Di.default)(e,0).byte.from,to:(0,Di.default)(e,-1).byte.to},{signal:s}=this.downloadAbortController;return{url:i,range:r,signal:s,onProgress:async(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:Mt.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!We(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:Mt.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||!N(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=Tt(n.mime).parseFeedableSegmentChunk(l,this.isLive);c!=null&&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||!N(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,f=d-c+1,p=c<r,h=d<=r;if(!p)continue;let m=Tt(o.mime);if(l.status==="downloading"&&h){l.status="downloaded";let v=new DataView(e.buffer,e.byteOffset+c,f);await this.sourceBufferTaskQueue.append(v,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(f,r-c),u.loadedBytes>u.feedingBytes)){let v=new DataView(e.buffer,e.byteOffset+c+u.feedingBytes,u.loadedBytes-u.feedingBytes),b=u.loadedBytes===f?v:m.parseFeedableSegmentChunk(v);b!=null&&b.byteLength&&(l.status="partially_fed",u.feedingBytes+=b.byteLength,await this.sourceBufferTaskQueue.append(b,s)&&!s.aborted?(u.fedBytes+=b.byteLength,u.fedBytes===f&&this.onSegmentFullyAppended(u,t)):await n())}}}onSegmentFullyAppended(e,t){var i;if(!(Ee(this.sourceBuffer)||!N(this.mediaSource,this.sourceBuffer))){!this.isLive&&F.browser.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(Ie(this.sourceBuffer.buffered,e.segment.time.from,100)&&Ie(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:Mt.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",Jc(e.segment)&&(e.segment.size=e.fedBytes);for(let r of this.representations.values())if(r.id!==t)for(let s of(i=this.segments.get(r.id))!=null?i:[])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.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||(t=n),s===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let i=this.representations.get(e);i&&(this.initLoadIdleCallback=Er(()=>(0,rI.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?Zt(this.destroyAbortController.signal,async function*(){let o=ed(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,Tt(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 f=c;this.isLive&&We(e.segmentReference)&&(f=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,f),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:Mt.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||!N(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||Ee(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:f}=u[c],p=l[l.length-1];p.to>=d?p.to=Math.max(p.to,f):l.push(u[c])}return l},o=u=>{var c;if(s>=t)return r;r.push({...u.time}),r=n(r);let l=Jc(u)?(c=u.size)!=null?c:0:u.byte.to-u.byte.from;s+=l};for(let u of this.segments.values())for(let l of u){let c=l.time.to<=e-this.tuning.dash.bufferPruningSafeZone,d=l.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(c||d)&&l.status==="fed"&&o(l)}for(let u=0;u<this.sourceBuffer.buffered.length;u++){let l=this.sourceBuffer.buffered.start(u)*1e3,c=this.sourceBuffer.buffered.end(u)*1e3,d=0;for(let f of this.segments.values())for(let p of f)(0,go.default)(["none","partially_ejected"],p.status)&&Math.round(p.time.from)<=Math.round(l)&&Math.round(p.time.to)>=Math.round(c)&&d++;if(d===this.segments.size){let f={time:{from:l,to:c},url:"",status:"none"};o(f)}}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||!N(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||!N(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||!N(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||Ee(e)?0:be(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!(!this.sourceBuffer||!N(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||!N(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=Er(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:Mt.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if(Ee(this.sourceBuffer)||!N(this.mediaSource,this.sourceBuffer)||Ee(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:Mt.VIDEO_PIPELINE,thrown:e,message:"Something went wrong"})}};var ei=a=>{let e=new URL(a);return e.searchParams.set("quic","1"),e.toString()};var So=a=>{var s;let e=a.get("X-Delivery-Type"),t=a.get("X-Reused"),i=e===null?"http1":e!=null?e:void 0,r=t===null?void 0:(s={1:!0,0:!1}[t])!=null?s:void 0;return{type:i,reused:r}};import{abortable as fs,assertNever as aI,fromEvent as sI,merge as SB,now as ms,Subscription as yB,Subject as Lr,ValueSubject as td,flattenObject as $r,ErrorCategory as bs}from"@vkontakte/videoplayer-shared/es2018";var yo=a=>{let e=new URL(a);return e.searchParams.set("enable-subtitles","yes"),e.toString()};var Io=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:s=!1}){this.manifestRequested=new Lr;this.manifestReceived=new Lr;this.firstBytesRequested=new Lr;this.firstBytesReceived=new Lr;this.lastConnectionType$=new td(void 0);this.lastConnectionReused$=new td(void 0);this.lastRequestFirstBytes$=new td(void 0);this.recoverableError$=new Lr;this.error$=new Lr;this.abortAllController=new Z;this.subscription=new yB;this.fetchManifest=fs(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=ei(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=yo(i)),this.manifestRequested.next();let r=yield this.doFetch(i,{signal:this.abortAllController.signal}).catch(To);return r?(t.log("success",$r({url:i,message:"Request successfully executed"})),t.end(),this.manifestReceived.next(),this.onHeadersReceived(r.headers),r.text()):(t.error("error",$r({url:i,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=fs(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,bufferOptimisation:l=!1}={}){var _,K,J;let c=e,d=new Headers,f=this.tracer.createComponentTracer("Fetch");if(i)switch(t){case 0:{d.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let I=new URL(c,location.href);I.searchParams.append("bytes",`${i.from}-${i.to}`),c=I.toString();break}default:aI(t)}this.requestQuic&&(c=ei(c));let p=this.abortAllController.signal,h;if(n){let I=new Z;if(h=SB(sI(this.abortAllController.signal,"abort"),sI(n,"abort")).subscribe(()=>{try{I.abort()}catch(R){To(R)}}),this.subscription.add(h),this.abortAllController.signal.aborted||n.aborted)try{I.abort()}catch(R){To(R)}p=I.signal}let m=0,v=ms();f.log("startRequest",$r({url:c,priority:s,rangeMethod:t,range:i,isLowLatency:u,requestStartedAt:v})),this.firstBytesRequested.next();let b=yield this.doFetch(c,{priority:s,headers:d,signal:p}),S=ms();if(!b)return f.error("error",{message:"No response in request"}),f.end(),h==null||h.unsubscribe(),null;if((_=this.throughputEstimator)==null||_.addRawRtt(S-v),!b.ok||!b.body){h==null||h.unsubscribe();let I=`Fetch error ${b.status}: ${b.statusText}`;return f.error("error",{message:I}),f.end(),Promise.reject(new Error(`Fetch error ${b.status}: ${b.statusText}`))}if(this.onHeadersReceived(b.headers),!r&&!o){h==null||h.unsubscribe();let I=ms(),R={requestStartedAt:v,requestEndedAt:I,duration:I-v};return f.log("endRequest",$r(R)),f.end(),b.arrayBuffer()}let T=b.body;if(o){let I;[T,I]=b.body.tee(),(K=this.throughputEstimator)==null||K.trackStream(I,u)}let y=T.getReader(),E,k=parseInt((J=b.headers.get("content-length"))!=null?J:"",10);Number.isFinite(k)&&(E=k),!E&&i&&(E=i.to-i.from+1);let M=E?new Uint8Array(E):new Uint8Array(0),$=!1,A=I=>{h==null||h.unsubscribe(),$=!0,To(I)},P=fs(p,async function*({done:I,value:R}){if(m===0&&(this.lastRequestFirstBytes$.next(ms()-v),this.firstBytesReceived.next()),p.aborted){h==null||h.unsubscribe();return}if(!I&&R){if(l&&E)M.set(R,m),m+=R.byteLength;else{let x=new Uint8Array(M.length+R.length);x.set(M),x.set(R,M.length),M=x,m+=R.byteLength}r==null||r(new DataView(M.buffer),m),yield y==null?void 0:y.read().then(P,A)}}.bind(this));yield y==null?void 0:y.read().then(P,A),h==null||h.unsubscribe();let V=ms(),D={failed:$,requestStartedAt:v,requestEndedAt:V,duration:V-v};return $?(f.error("endRequest",$r(D)),f.end(),null):(f.log("endRequest",$r(D)),f.end(),M.buffer)}.bind(this));this.fetchByteRangeRepresentation=fs(this.abortAllController.signal,async function*(e,t,i){var b;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 f=new DataView(d,r-n,s-n+1);if(!t.validateData(f))throw new Error("Invalid media file");let p=t.parseInit(f),h=(b=e.indexRange)!=null?b:t.getIndexRange(p);if(!h)throw new ReferenceError("No way to load representation index");let m;if(u)m=new DataView(d,h.from-n,h.to-h.from+1);else{let S=yield this.fetch(e.url,{range:h,priority:i,measureThroughput:!1});if(!S)return null;m=new DataView(S)}let v=t.parseSegments(m,p,h);return{init:p,dataView:new DataView(d),segments:v}}.bind(this));this.fetchTemplateRepresentation=fs(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}=So(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}async fetchRepresentation(e,t,i="auto"){var s,n;let{type:r}=e;switch(r){case"byteRange":return(s=await this.fetchByteRangeRepresentation(e,t,i))!=null?s:null;case"template":return(n=await this.fetchTemplateRepresentation(e,i))!=null?n:null;default:aI(r)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}async doFetch(e,t){let i=await Ze(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:bs.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:bs.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:bs.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:bs.FATAL});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${s})`,category:bs.FATAL})}}},To=a=>{if(!It(a))throw a};var Dt=(a,e,t)=>t*e+(1-t)*a,id=(a,e)=>a.reduce((t,i)=>t+i,0)/e,nI=(a,e,t,i)=>{let r=0,s=t,n=id(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 TB,ValueSubject as oI}from"@vkontakte/videoplayer-shared/es2018";var ti=class{constructor(e){this.prevReported=void 0;this.pastMeasures=[];this.takenMeasures=0;this.measuresCursor=0;var i;this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new oI(e.initial),this.debounced$=new oI(e.initial);let t=(i=e.label)!=null?i:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new ke(`raw_${t}`),this.smoothedSeries$=new ke(`smoothed_${t}`),this.reportedSeries$=new ke(`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)&&(TB(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 Eo=class extends ti{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=Dt(this.slow,e,this.params.emaAlphaSlow),this.fast=Dt(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var xo=class extends ti{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=id(this.pastMeasures,this.takenMeasures);this.emaSmoothed=Dt(this.emaSmoothed,e,this.params.emaAlpha);let i=nI(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=i?this.emaSmoothed:t}};var wo=class extends ti{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?Dt(this.smoothed,t,this.params.emaAlpha):t}};var Ct=class{static getSmoothedValue(e,t,i){return i.type==="TwoEma"?new Eo({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new xo({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 wo({initial:e,label:"liveEdgeDelay",...t})}};var Mr=(a,e)=>{a&&a.playbackRate!==e&&(a.playbackRate=e)};import{isNullable as IB,ValueSubject as EB}from"@vkontakte/videoplayer-shared/es2018";var gs=class a{constructor(e,t){this.currentRepresentation$=new EB(null);this.maxRepresentations=4;this.representationsCursor=0;this.representations=[];this.currentSegment=null;this.getCurrentPosition=t.getCurrentPosition,this.processStreams(e)}updateLive(e){this.processStreams(e==null?void 0:e.streams.text)}seekLive(e){this.processStreams(e)}maintain(e=this.getCurrentPosition()){var t;if(!IB(e))for(let i of this.representations)for(let r of i){let s=r.segmentReference,n=s.segments.length,o=s.segments[0].time.from,u=s.segments[n-1].time.to;if(e<o||e>u)continue;let l=s.segments.find(c=>c.time.from<=e&&c.time.to>=e);!l||((t=this.currentSegment)==null?void 0:t.time.from)===l.time.from&&this.currentSegment.time.to===l.time.to||(this.currentSegment=l,this.currentRepresentation$.next({...r,label:"Live Text",language:"ru",isAuto:!0,url:new URL(l.url,s.baseUrl).toString()}))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e!=null?e:[]){let 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!=null&&e.some(t=>a.filterRepresentations(t.representations)))}static filterRepresentations(e){return e==null?void 0:e.filter(t=>t.kind==="text"&&"segmentReference"in t&&We(t.segmentReference))}};var Po=O(ot(),1),rd=O(Ae(),1);import{assertNever as Ro}from"@vkontakte/videoplayer-shared/es2018";var Ao=a=>{let{webmDecodingInfo:e}=F.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:Ro(a)}return[t,i]},uI=({webmCodec:a,androidPreferredFormat:e,iosPreferredFormat:t,preferMultiStream:i})=>{let r=[...i?["DASH_STREAMS"]:[],...Ao(a),"DASH_SEP","DASH_ONDEMAND",...i?[]:["DASH_STREAMS"]],s=[...i?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...i?[]:["DASH_STREAMS"]];if(F.device.isAndroid)switch(e){case"mpeg":return["MPEG",...r,"HLS","HLS_ONDEMAND"];case"hls":return["HLS","HLS_ONDEMAND",...r,"MPEG"];case"dash":return[...r,"HLS","HLS_ONDEMAND","MPEG"];case"dash_any_mpeg":return[...s,"MPEG",...Ao(a),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...Ao(a),"MPEG",...s,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...Ao(a),...s,"HLS","HLS_ONDEMAND"];default:Ro(e)}if(F.video.nativeHlsSupported)switch(t){case"hls":return[...r,"HLS","HLS_FMP4","HLS_ONDEMAND","MPEG"];case"hls_fmp4":return[...r,"HLS_FMP4","HLS","HLS_ONDEMAND","MPEG"];default:Ro(t)}return[...r,"HLS","HLS_ONDEMAND","MPEG"]},lI=({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=F.device.isMac&&F.browser.isSafari;if(F.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:Ro(a)}else F.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"]},ad=a=>a?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],ko=a=>{if(a.size===0)return;if(a.size===1){let t=a.values().next();return(0,Po.default)(t.value.split("."),0)}for(let t of a){let i=(0,Po.default)(t.split("."),0);if(i==="opus"||i==="vp09"||i==="av01")return i}let e=a.values().next();return(0,Po.default)(e.value.split("."),0)},Lo=a=>{let e=a.map(i=>Dr(i)),{codecs:t}=F.video;return PB().filter(i=>{if((0,rd.default)(e,i))switch(i){case"av1":return t.av1;case"vp9":return t.vp9;case"avc1":return t.h264;case"hev1":return t.h265;default:return!1}else return!1})},$o=a=>{let e=a.map(i=>Dr(i)),{codecs:t}=F.video;return RB().filter(i=>{if((0,rd.default)(e,i))switch(i){case"opus":return t.opus;case"mp4a":return t.aac;default:return!1}else return!1})},Dr=a=>a.split(".")[0].replace("0",""),PB=()=>["av1","vp9","hev1","avc1"],RB=()=>["opus","mp4a"];var CB=["timeupdate","progress","play","seeked","stalled","waiting"],BB=["timeupdate","progress","loadeddata","playing","seeked"];var Do=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.bufferManagers=[];this.subscription=new pI;this.representationSubscription=new pI;this.state$=new H("none");this.currentVideoRepresentation$=new ae(void 0);this.currentVideoRepresentationInit$=new ae(void 0);this.currentAudioRepresentation$=new ae(void 0);this.currentVideoSegmentLength$=new ae(0);this.currentAudioSegmentLength$=new ae(0);this.error$=new ii;this.manifestRequested=new ii;this.manifestReceived=new ii;this.firstBytesRequested=new ii;this.firstBytesReceived=new ii;this.lastConnectionType$=new ae(void 0);this.lastConnectionReused$=new ae(void 0);this.lastRequestFirstBytes$=new ae(void 0);this.currentLiveTextRepresentation$=new ae(null);this.isLive$=new ae(!1);this.isActiveLive$=new ae(!1);this.isLowLatency$=new ae(!1);this.liveDuration$=new ae(0);this.liveSeekableDuration$=new ae(0);this.liveAvailabilityStartTime$=new ae(0);this.liveStreamStatus$=new ae(void 0);this.bufferLength$=new ae(0);this.liveLatency$=new ae(void 0);this.liveLoadBufferLength$=new ae(0);this.livePositionFromPlayer$=new ae(0);this.currentStallDuration$=new ae(0);this.videoLastDataObtainedTimestamp$=new ae(0);this.fetcherRecoverableError$=new ii;this.fetcherError$=new ii;this.liveStreamEndTimestamp=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.forceEnded$=new ii;this.gapWatchdogActive=!1;this.destroyController=new Z;this.initManifest=nd(this.destroyController.signal,async function*(e,t,i){var r;this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=le(t,i,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),(r=this.manifest)!=null&&r.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:ct.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=nd(this.destroyController.signal,async function*(){var u,l;this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(c=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:ct.NETWORK,message:"Failed to load manifest",thrown:c})});if(!e)return null;let t=null;try{t=mo(e!=null?e:"",this.manifestUrlString)}catch(c){let d=(u=ho(e))!=null?u:{id:"ManifestParsing",category:ct.PARSER,message:"Failed to parse MPD manifest",thrown:c};this.error$.next(d)}if(!t)return null;let i=(c,d,f)=>{var p,h,m,v;return!!((h=(p=this.element)==null?void 0:p.canPlayType)!=null&&h.call(p,d)&&((v=(m=Qe())==null?void 0:m.isTypeSupported)!=null&&v.call(m,`${d}; codecs="${f}"`))||c==="text")};if(t.live){this.isLive$.next(!!t.live);let{availabilityStartTime:c,latestSegmentPublishTime:d,streamIsUnpublished:f,streamIsAlive:p}=t.live,h=((l=t.duration)!=null?l:0)/1e3;this.liveSeekableDuration$.next(-1*h),this.liveDuration$.next((d-c)/1e3),this.liveAvailabilityStartTime$.next(t.live.availabilityStartTime);let m="active";p||(m=f?"unpublished":"unexpectedly_down"),this.liveStreamStatus$.next(m)}let r={text:t.streams.text,video:[],audio:[]},s,n;for(let c of["video","audio"]){let f=t.streams[c].filter(({mime:h,codecs:m})=>i(c,h,m));r[c]=f;let p;if(this.tuning.dash.codecsPrioritizeEnabled){let h=f.map(({codecs:m})=>m);c==="audio"&&(n=$o(h),p=n[0]),c==="video"&&(s=Lo(h),this.forceVideoCodec&&(0,fI.default)(s,this.forceVideoCodec)?p=this.forceVideoCodec:p=s[0]),p&&(r[c]=f.filter(({codecs:m})=>Dr(m)===p))}else{let h=new Set(f.map(({codecs:m})=>m));p=ko(h),p&&(r[c]=f.filter(({codecs:m})=>m.startsWith(p)))}if(c==="video"){let h=this.tuning.preferHDR,m=r.video.some(b=>b.hdr),v=r.video.some(b=>!b.hdr);F.display.isHDR&&h&&m?r.video=r.video.filter(b=>b.hdr):v&&(r.video=r.video.filter(b=>!b.hdr))}}let o={...t,streams:r};return this.tuning.dash.codecsPrioritizeEnabled&&(o.codecs={video:s,audio:n}),this.tracer.log("updateManifestEnd",Ss(o)),o}.bind(this));this.initRepresentations=nd(this.destroyController.signal,async function*(e,t,i){var f;this.tracer.log("initRepresentationsStart",Ss({initialVideo:e,initialAudio:t,sourceHls:i})),Cr(this.manifest),Cr(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let r=p=>{this.representationSubscription.add(Bt(p,"error").pipe(Mo(h=>{var m;return!!((m=this.element)!=null&&m.played.length)})).subscribe(h=>{this.error$.next({id:"VideoSource",category:ct.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:h})}))};this.source=qn();let s=document.createElement("source");if(r(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),pr())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 hs("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],ys(t)){let p=this.manifest.streams.audio.reduce((h,m)=>[...h,...m.representations],[]);this.audioBufferManager=new hs("audio",this.source,p,n),this.bufferManagers.push(this.audioBufferManager)}gs.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new gs(this.manifest.streams.text,n)),this.representationSubscription.add(this.fetcher.manifestRequested.subscribe(this.manifestRequested)),this.representationSubscription.add(this.fetcher.manifestReceived.subscribe(this.manifestReceived)),this.representationSubscription.add(this.fetcher.firstBytesRequested.subscribe(this.firstBytesRequested)),this.representationSubscription.add(this.fetcher.firstBytesReceived.subscribe(this.firstBytesReceived)),this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$));let u=()=>{var p;(p=this.stallWatchdogSubscription)==null||p.unsubscribe(),this.currentStallDuration$.next(0)};if(this.representationSubscription.add(Ci(...BB.map(p=>Bt(this.element,p))).pipe(Vr(p=>this.element?be(this.element.buffered,this.element.currentTime*1e3):0),vs(),MB(p=>{p>this.tuning.dash.bufferEmptinessTolerance&&u()})).subscribe(this.bufferLength$)),this.representationSubscription.add(Ci(Bt(this.element,"ended"),this.forceEnded$).subscribe(()=>{u()})),this.isLive$.getValue()){this.subscription.add(this.liveDuration$.pipe(vs()).subscribe(h=>this.liveStreamEndTimestamp=ud())),this.subscription.add(Bt(this.element,"pause").subscribe(()=>{this.livePauseWatchdogSubscription=od(1e3).subscribe(h=>{let m=zt(this.manifestUrlString,2);this.manifestUrlString=le(this.manifestUrlString,m+1e3,2),this.liveStreamStatus$.getValue()==="active"&&this.updateManifest()}),this.subscription.add(this.livePauseWatchdogSubscription)})).add(Bt(this.element,"play").subscribe(h=>{var m;return(m=this.livePauseWatchdogSubscription)==null?void 0:m.unsubscribe()})),this.representationSubscription.add(Br({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(Vr(({isActiveLive:h,isLowLatency:m})=>h&&m),vs()).subscribe(h=>{this.isManualDecreasePlaybackInLive()||Mr(this.element,1)})),this.representationSubscription.add(Br({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(Mo(({bufferLength:h,isActiveLive:m,isLowLatency:v})=>m&&v&&!!h)).subscribe(({bufferLength:h})=>this.liveBuffer.next(h))),this.representationSubscription.add(this.videoBufferManager.currentLowLatencySegmentLength$.subscribe(h=>{if(!this.isActiveLive$.getValue()&&!this.isLowLatency$.getValue()&&!h)return;let m=this.liveSeekableDuration$.getValue()-h/1e3;this.liveSeekableDuration$.next(Math.max(m,-1*this.tuning.dashCmafLive.maxLiveDuration)),this.liveDuration$.next(this.liveDuration$.getValue()+h/1e3)})),this.representationSubscription.add(Br({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe(Mo(({isLive:h})=>h),vs((h,m)=>m.bufferLength<h.bufferLength),Vr(({rtt:h,bufferLength:m,segmentServerLatency:v})=>{let b=zt(this.manifestUrlString,2);return(h/2+m+v+b)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add(Br({liveBuffer:this.liveBuffer.smoothed$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).subscribe(({liveBuffer:h,isActiveLive:m,isLowLatency:v})=>{if(!v||!m)return;let b=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,S=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,T=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,y=h-b;if(this.isManualDecreasePlaybackInLive())return;let E=1;Math.abs(y)>S&&(E=1+Math.sign(y)*T),Mr(this.element,E)})),this.representationSubscription.add(this.bufferLength$.subscribe(h=>{var v,b;let m=0;if(h){let S=((b=(v=this.element)==null?void 0:v.currentTime)!=null?b:0)*1e3;m=Math.min(...this.bufferManagers.map(y=>{var E,k;return(k=(E=y.getLiveSegmentsToLoadState(this.manifest))==null?void 0:E.to)!=null?k:S}))-S}this.liveLoadBufferLength$.getValue()!==m&&this.liveLoadBufferLength$.next(m)}));let p=0;this.representationSubscription.add(Br({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(DB(1e3)).subscribe(async({liveLoadBufferLength:h,bufferLength:m})=>{if(!this.element||this.isUpdatingLive)return;let v=this.element.playbackRate,b=zt(this.manifestUrlString,2),S=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,T=Math.min(S,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*v),y=this.tuning.dashCmafLive.normalizedActualBufferOffset*v,E=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*v,k=isFinite(h)?h:m,M=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),$=S<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next($);let A="none";if(M?A="active_low_latency":this.isLowLatency$.getValue()&&$?(this.bufferManagers.forEach(P=>P.proceedLowLatencyLive()),A="active_low_latency"):b!==0&&k<T?A="live_forward_buffering":k<T+E&&(A="live_with_target_offset"),isFinite(h)&&(p=h>p?h:p),A==="live_forward_buffering"||A==="live_with_target_offset"){let P=p-(T+y),V=this.normolizeLiveOffset(Math.trunc(b+P/v)),D=Math.abs(V-b),_=0;!h||D<=this.tuning.dashCmafLive.offsetCalculationError?_=b:V>0&&D>this.tuning.dashCmafLive.offsetCalculationError&&(_=V),this.manifestUrlString=le(this.manifestUrlString,_,2)}(A==="live_with_target_offset"||A==="live_forward_buffering")&&(p=0,await this.updateLive())},h=>{this.error$.next({id:"updateLive",category:ct.VIDEO_PIPELINE,thrown:h,message:"Failed to update live with subscription"})}))}let l=Ci(...this.bufferManagers.map(p=>p.fullyBuffered$)).pipe(Vr(()=>this.bufferManagers.every(p=>p.fullyBuffered$.getValue()))),c=Ci(...this.bufferManagers.map(p=>p.onLastSegment$)).pipe(Vr(()=>this.bufferManagers.some(p=>p.onLastSegment$.getValue()))),d=Br({allBuffersFull:l,someBufferEnded:c}).pipe(vs(),Vr(({allBuffersFull:p,someBufferEnded:h})=>p&&h),Mo(p=>p));if(this.representationSubscription.add(Ci(this.forceEnded$,d).subscribe(()=>{var p;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(h=>!h.updating))try{(p=this.source)==null||p.endOfStream()}catch(h){this.error$.next({id:"EndOfStream",category:ct.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:h})}})),this.representationSubscription.add(Ci(...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=>{var m;p&&(this.timeoutSourceOpenId=setTimeout(()=>{var v;if(((v=this.source)==null?void 0:v.readyState)==="open"){h();return}this.error$.next({id:"OpenOfStream",category:ct.VIDEO_PIPELINE,message:"Failed to open MediaSource",thrown:new Error("Timeout reject when wait sourceopen event"),traceAsLog:!0})},this.tuning.dash.sourceOpenTimeout)),(m=this.source)==null||m.addEventListener("sourceopen",()=>{this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),h()},{once:!0})})}if(!this.isLive$.getValue()){let p=[(f=this.manifest.duration)!=null?f:0,...(0,ld.default)((0,ld.default)([...this.manifest.streams.audio,...this.manifest.streams.video],h=>h.representations),h=>{let m=[];return h.duration&&m.push(h.duration),We(h.segmentReference)&&h.segmentReference.totalSegmentsDurationMs&&m.push(h.segmentReference.totalSegmentsDurationMs),m})];this.source.duration=Math.max(...p)/1e3}this.audioBufferManager&&ys(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState("representations_ready"),this.tracer.log("initRepresentationsEnd")}.bind(this));this.tick=()=>{var t,i,r,s;if(!this.element||!this.videoBufferManager||((t=this.source)==null?void 0:t.readyState)!=="open")return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),(i=this.audioBufferManager)==null||i.maintain(e),(r=this.liveTextManager)==null||r.maintain(e),(this.videoBufferManager.gaps.length||(s=this.audioBufferManager)!=null&&s.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=od(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),n=>{this.error$.next({id:"GapWatchdog",category:ct.WTF,message:"Error handling gaps",thrown:n})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name),this.forceVideoCodec=e.forceVideoCodec,this.fetcher=new Io({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer,useEnableSubtitlesParam:e.tuning.useEnableSubtitlesParam}),this.subscription.add(this.fetcher.recoverableError$.subscribe(this.fetcherRecoverableError$)),this.subscription.add(this.fetcher.error$.subscribe(this.fetcherError$)),this.liveBuffer=Ct.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.bufferEstimator}),this.initTracerSubscription()}async seekLive(e){var r,s,n;Cr(this.element);let t=this.liveStreamStatus$.getValue()!=="active"?ud()-this.liveStreamEndTimestamp:0,i=this.normolizeLiveOffset(e+t);this.isActiveLive$.next(i===0),this.manifestUrlString=le(this.manifestUrlString,i,2),this.manifest=await this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,await((r=this.videoBufferManager)==null?void 0:r.seekLive(this.manifest.streams.video)),await((s=this.audioBufferManager)==null?void 0:s.seekLive(this.manifest.streams.audio)),(n=this.liveTextManager)==null||n.seekLive(this.manifest.streams.text))}initBuffer(){Cr(this.element),this.state$.setState("running"),this.subscription.add(Ci(...CB.map(e=>Bt(this.element,e)),Bt(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:ct.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(Bt(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(Bt(this.element,"waiting").subscribe(()=>{var t;this.element&&this.element.readyState===2&&!this.element.seeking&&Ie(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{var p,h,m,v,b,S,T,y,E,k,M;if(!this.element||((p=this.source)==null?void 0:p.readyState)!=="open")return;let i=this.currentStallDuration$.getValue();i+=50,this.currentStallDuration$.next(i);let r={timeInWaiting:i},s=ud(),n=100,o=(m=(h=this.videoBufferManager)==null?void 0:h.lastDataObtainedTimestamp)!=null?m:0;this.videoLastDataObtainedTimestamp$.next(o);let u=(b=(v=this.audioBufferManager)==null?void 0:v.lastDataObtainedTimestamp)!=null?b:0,l=(T=(S=this.videoBufferManager)==null?void 0:S.getForwardBufferDuration())!=null?T:0,c=(E=(y=this.audioBufferManager)==null?void 0:y.getForwardBufferDuration())!=null?E:0,d=l<n&&s-o>this.tuning.dash.crashOnStallTWithoutDataTimeout,f=this.audioBufferManager&&c<n&&s-u>this.tuning.dash.crashOnStallTWithoutDataTimeout;if((d||f)&&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 $=this.normolizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);this.seekLive($).catch(A=>{this.error$.next({id:"stallIntervalCallback",category:ct.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:A})}),r.liveLastOffset=$}else{let $=this.element.currentTime*1e3;(k=this.videoBufferManager)==null||k.maintain($),(M=this.audioBufferManager)==null||M.maintain($),r.position=$}this.tracer.log("stallIntervalCallback",Ss(r))};(t=this.stallWatchdogSubscription)==null||t.unsubscribe(),this.stallWatchdogSubscription=od(50).subscribe(e,i=>{this.error$.next({id:"StallWatchdogCallback",category:ct.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==null?void 0:r.switchToWithPreviousAbort(t,i):r==null?void 0:r.switchTo(t,i):r==null?void 0:r.switchToOld(t,i)}async seek(e,t){var r,s,n,o,u;Cr(this.element),Cr(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((r=this.videoBufferManager.findSegmentStartTime(e))!=null?r:e,(n=(s=this.audioBufferManager)==null?void 0:s.findSegmentStartTime(e))!=null?n:e),this.warmUpMediaSourceIfNeeded(i),Ie(this.element.buffered,i)||await Promise.all([this.videoBufferManager.abort(),(o=this.audioBufferManager)==null?void 0:o.abort()]),!(dI(this.element)||dI(this.videoBufferManager))&&(this.videoBufferManager.maintain(i),(u=this.audioBufferManager)==null||u.maintain(i),this.element.currentTime=i/1e3,this.tracer.log("seek",Ss({requestedPosition:e,forcePrecise:t,position:i})))}warmUpMediaSourceIfNeeded(e=(t=>(t=this.element)==null?void 0:t.currentTime)()){var i;ys(this.element)&&ys(this.source)&&ys(e)&&((i=this.source)==null?void 0:i.readyState)==="ended"&&this.element.duration*1e3-e>this.tuning.dash.seekBiasInTheEnd&&this.bufferManagers.forEach(r=>r.warmUpMediaSource())}get isStreamEnded(){var e;return((e=this.source)==null?void 0:e.readyState)==="ended"}stop(){var e,t,i;this.tracer.log("stop"),(e=this.element)==null||e.querySelectorAll("source").forEach(r=>{URL.revokeObjectURL(r.src),r.remove()}),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),(t=this.videoBufferManager)==null||t.destroy(),this.videoBufferManager=null,(i=this.audioBufferManager)==null||i.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getStreams(){var e;return(e=this.manifest)==null?void 0:e.streams}getCodecs(){var e;return(e=this.manifest)==null?void 0:e.codecs}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){var e;this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),((e=this.source)==null?void 0:e.readyState)==="open"&&Array.from(this.source.sourceBuffers).every(t=>!t.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}initTracerSubscription(){let e=$B(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(){var e;this.isUpdatingLive=!0,this.manifest=await this.updateManifest(),this.manifest&&(this.bufferManagers.forEach(t=>t.updateLive(this.manifest)),(e=this.liveTextManager)==null||e.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",Ss(i)))}}calculateDurationFromSegments(){var e,t;return Math.max(((e=this.videoBufferManager)==null?void 0:e.calculateDurationFromSegments())||0,((t=this.audioBufferManager)==null?void 0:t.calculateDurationFromSegments())||0)}};var Co=class{constructor(e,t){this.fov=e,this.orientation=t}};var Bo=class{constructor(e,t){this.rotating=!1;this.fading=!1;this.lastTickTS=0;this.lastCameraTurnTS=0;this.fadeStartSpeed=null;this.fadeTime=0;this.camera=e,this.options=t,this.rotationSpeed={x:0,y:0,z:0},this.fadeCorrection=1/(this.options.speedFadeTime/1e3)**2}turnCamera(e=0,t=0,i=0){this.pointCameraTo(this.camera.orientation.x+e,this.camera.orientation.y+t,this.camera.orientation.z+i)}pointCameraTo(e=0,t=0,i=0){t=this.limitCameraRotationY(t);let r=e-this.camera.orientation.x,s=t-this.camera.orientation.y,n=i-this.camera.orientation.z;this.camera.orientation.x=e,this.camera.orientation.y=t,this.camera.orientation.z=i,this.lastCameraTurn={x:r,y:s,z:n},this.lastCameraTurnTS=Date.now()}setRotationSpeed(e,t,i){this.rotationSpeed.x=e!=null?e:this.rotationSpeed.x,this.rotationSpeed.y=t!=null?t:this.rotationSpeed.y,this.rotationSpeed.z=i!=null?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 mI=`attribute vec2 a_vertex;
124
+ `})|(?<privateuse2>${e}))$`.replace(/[\s\t\n]/g,"");return new RegExp(c,"i")}var KT=a=>{if(!(a!=null&&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==null?void 0:i[1])==="-"?-1:1,s={days:e(i==null?void 0:i[5],r),hours:e(i==null?void 0:i[6],r),minutes:e(i==null?void 0:i[7],r),seconds:e(i==null?void 0:i[8],r)};return s.days*24*60*60*1e3+s.hours*60*60*1e3+s.minutes*60*1e3+s.seconds*1e3},lt=(a,e)=>{let t=a;t=(0,Zc.default)(t,"$$","$");let i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[r,s]of(0,XT.default)(i)){let n=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=(0,Zc.default)(t,n,(o,u)=>YT(s)?o:YT(u)?s:(0,JT.default)(s,parseInt(u,10),"0"))}return t},Eo=(a,e)=>{var R,P,V,D,_,K,J,E,k,x,A,B,ne,Ne,ie,z,Se,ve,ye,qe,xt,Ot,ci,Hi,Gr,up,lp,cp,dp,pp,hp,fp,mp,bp,gp,Sp,vp,yp,Tp,Ip,Ep,xp,wp,Ap,Rp,Pp,kp,Lp,$p,Mp,Dp,Cp,Bp,Vp,_p,Op,Fp,Np,qp,Up,jp;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(et=>{var te,di;return(di=(te=et.textContent)==null?void 0:te.trim())!=null?di:""}),o=(R=(0,ZT.default)(n,0))!=null?R:"",u=s.getAttribute("type")==="dynamic",l=s.getAttribute("availabilityStartTime"),c=s.getAttribute("publishTime"),d=s.getElementsByTagName("vk:Attrs")[0],f=d==null?void 0:d.getElementsByTagName("vk:XLatestSegmentPublishTime")[0].textContent,p=d==null?void 0:d.getElementsByTagName("vk:XStreamIsLive")[0].textContent,h=d==null?void 0:d.getElementsByTagName("vk:XStreamIsUnpublished")[0].textContent,m=d==null?void 0:d.getElementsByTagName("vk:XPlaybackDuration")[0].textContent,S;u&&(S={availabilityStartTime:l?new Date(l).getTime():0,publishTime:c?new Date(c).getTime():0,latestSegmentPublishTime:f?new Date(f).getTime():0,streamIsAlive:p==="yes",streamIsUnpublished:h==="yes"});let b,v=s.getAttribute("mediaPresentationDuration"),T=[...s.getElementsByTagName("Period")],y=T.reduce((et,te)=>({...et,[te.id]:te.children}),{}),I=T.reduce((et,te)=>({...et,[te.id]:te.getAttribute("duration")}),{});v?b=KT(v):(0,ed.default)(I).filter(et=>et).length&&!u?b=(0,ed.default)(I).reduce((et,te)=>{var di;return et+((di=KT(te))!=null?di:0)},0):m&&(b=parseInt(m,10));let w=0,L=(V=(P=s.getAttribute("profiles"))==null?void 0:P.split(","))!=null?V:[];for(let et of T.map(te=>te.id))for(let te of y[et]){let di=(D=te.getAttribute("id"))!=null?D:"id"+(w++).toString(10),Wr=(_=te.getAttribute("mimeType"))!=null?_:"",Su=(K=te.getAttribute("codecs"))!=null?K:"",vu=(J=te.getAttribute("contentType"))!=null?J:Wr==null?void 0:Wr.split("/")[0],NE=(k=(E=te.getAttribute("profiles"))==null?void 0:E.split(","))!=null?k:[],Hp=(A=zT((x=te.getAttribute("lang"))!=null?x:""))!=null?A:{},Ys=(Ne=(ne=(B=te.querySelector("Label"))==null?void 0:B.textContent)==null?void 0:ne.trim())!=null?Ne:void 0,qE=te.querySelectorAll("Representation"),UE=te.querySelector("SegmentTemplate"),jE=(z=(ie=te.querySelector("Role"))==null?void 0:ie.getAttribute("value"))!=null?z:void 0,Qi=vu,de={id:di,language:Hp.language,isDefault:jE==="main",label:Ys,codecs:Su,hdr:Qi==="video"&&Jc(Su),mime:Wr,representations:[]};for(let ee of qE){let Ft=(Se=ee.getAttribute("lang"))!=null?Se:void 0,zr=(ye=(ve=Ys!=null?Ys:te.getAttribute("label"))!=null?ve:ee.getAttribute("label"))!=null?ye:void 0,Ks=(Ot=(xt=(qe=ee.querySelector("BaseURL"))==null?void 0:qe.textContent)==null?void 0:xt.trim())!=null?Ot:"",pi=new URL(Ks||o,e).toString(),Nt=(ci=ee.getAttribute("mimeType"))!=null?ci:Wr,Xs=(Gr=(Hi=ee.getAttribute("codecs"))!=null?Hi:Su)!=null?Gr:"",Js;if(vu==="text"){let qt=ee.getAttribute("id")||"",Zs=((up=Hp.privateuse)==null?void 0:up.includes("x-auto"))||qt.includes("_auto"),hi=ee.querySelector("SegmentTemplate");if(hi){let Yr={representationId:(lp=ee.getAttribute("id"))!=null?lp:void 0,bandwidth:(cp=ee.getAttribute("bandwidth"))!=null?cp:void 0},en=parseInt((dp=ee.getAttribute("bandwidth"))!=null?dp:"",10)/1e3,tn=(hp=parseInt((pp=hi.getAttribute("startNumber"))!=null?pp:"",10))!=null?hp:1,Gi=parseInt((fp=hi.getAttribute("timescale"))!=null?fp:"",10),yu=(mp=hi.querySelectorAll("SegmentTimeline S"))!=null?mp:[],Wi=hi.getAttribute("media");if(!Wi)continue;let rn=[],an=0,sn="",zi=0,Kr=tn,we=0;for(let tt of yu){let fi=parseInt((bp=tt.getAttribute("d"))!=null?bp:"",10),Ye=parseInt((gp=tt.getAttribute("r"))!=null?gp:"",10)||0,Ut=parseInt((Sp=tt.getAttribute("t"))!=null?Sp:"",10);we=Number.isFinite(Ut)?Ut:we;let mi=fi/Gi*1e3,jt=we/Gi*1e3;for(let pt=0;pt<Ye+1;pt++){let Ht=lt(Wi,{...Yr,segmentNumber:Kr.toString(10),segmentTime:(we+pt*fi).toString(10)}),Yi=(jt!=null?jt:0)+pt*mi,Jr=Yi+mi;Kr++,rn.push({time:{from:Yi,to:Jr},url:Ht})}we+=(Ye+1)*fi,an+=(Ye+1)*mi}zi=we/Gi*1e3,sn=lt(Wi,{...Yr,segmentNumber:Kr.toString(10),segmentTime:we.toString(10)});let Xr={time:{from:zi,to:1/0},url:sn},wt={type:"template",baseUrl:pi,segmentTemplateUrl:Wi,initUrl:"",totalSegmentsDurationMs:an,segments:rn,nextSegmentBeyondManifest:Xr,timescale:Gi};Js={id:qt,kind:"text",segmentReference:wt,profiles:[],duration:b,bitrate:en,mime:"",codecs:"",width:0,height:0,isAuto:Zs}}else Js={id:qt,isAuto:Zs,kind:"text",url:pi}}else{let qt=(yp=(vp=ee.getAttribute("contentType"))!=null?vp:Nt==null?void 0:Nt.split("/")[0])!=null?yp:vu,Zs=(Ip=(Tp=te.getAttribute("profiles"))==null?void 0:Tp.split(","))!=null?Ip:[],hi=parseInt((Ep=ee.getAttribute("width"))!=null?Ep:"",10),Yr=parseInt((xp=ee.getAttribute("height"))!=null?xp:"",10),en=parseInt((wp=ee.getAttribute("bandwidth"))!=null?wp:"",10)/1e3,tn=(Ap=ee.getAttribute("frameRate"))!=null?Ap:"",Gi=(Rp=ee.getAttribute("quality"))!=null?Rp:void 0,yu=tn?WT(tn):void 0,Wi=(Pp=ee.getAttribute("id"))!=null?Pp:"id"+(w++).toString(10),rn=qt==="video"?`${Yr}p`:qt==="audio"?`${en}Kbps`:Xs,an=`${Wi}@${rn}`,sn=[...L,...NE,...Zs],zi,Kr=ee.querySelector("SegmentBase"),we=(kp=ee.querySelector("SegmentTemplate"))!=null?kp:UE;if(Kr){let wt=($p=(Lp=ee.querySelector("SegmentBase Initialization"))==null?void 0:Lp.getAttribute("range"))!=null?$p:"",[tt,fi]=wt.split("-").map(Ht=>parseInt(Ht,10)),Ye={from:tt,to:fi},Ut=(Mp=ee.querySelector("SegmentBase"))==null?void 0:Mp.getAttribute("indexRange"),[mi,jt]=Ut?Ut.split("-").map(Ht=>parseInt(Ht,10)):[],pt=Ut?{from:mi,to:jt}:void 0;zi={type:"byteRange",url:pi,initRange:Ye,indexRange:pt}}else if(we){let wt={representationId:(Dp=ee.getAttribute("id"))!=null?Dp:void 0,bandwidth:(Cp=ee.getAttribute("bandwidth"))!=null?Cp:void 0},tt=parseInt((Bp=we.getAttribute("timescale"))!=null?Bp:"",10),fi=(Vp=we.getAttribute("initialization"))!=null?Vp:"",Ye=we.getAttribute("media"),Ut=(Op=parseInt((_p=we.getAttribute("startNumber"))!=null?_p:"",10))!=null?Op:1,mi=lt(fi,wt);if(!Ye)throw new ReferenceError("No media attribute in SegmentTemplate");let jt=(Fp=we.querySelectorAll("SegmentTimeline S"))!=null?Fp:[],pt=[],Ht=0,Yi="",Jr=0;if(jt.length){let nn=Ut,it=0;for(let Ki of jt){let ht=parseInt((Np=Ki.getAttribute("d"))!=null?Np:"",10),bi=parseInt((qp=Ki.getAttribute("r"))!=null?qp:"",10)||0,on=parseInt((Up=Ki.getAttribute("t"))!=null?Up:"",10);it=Number.isFinite(on)?on:it;let Tu=ht/tt*1e3,Iu=it/tt*1e3;for(let un=0;un<bi+1;un++){let QE=lt(Ye,{...wt,segmentNumber:nn.toString(10),segmentTime:(it+un*ht).toString(10)}),Qp=(Iu!=null?Iu:0)+un*Tu,GE=Qp+Tu;nn++,pt.push({time:{from:Qp,to:GE},url:QE})}it+=(bi+1)*ht,Ht+=(bi+1)*Tu}Jr=it/tt*1e3,Yi=lt(Ye,{...wt,segmentNumber:nn.toString(10),segmentTime:it.toString(10)})}else if(hB(b)){let it=parseInt((jp=we.getAttribute("duration"))!=null?jp:"",10)/tt*1e3,Ki=Math.ceil(b/it),ht=0;for(let bi=1;bi<Ki;bi++){let on=lt(Ye,{...wt,segmentNumber:bi.toString(10),segmentTime:ht.toString(10)});pt.push({time:{from:ht,to:ht+it},url:on}),ht+=it}Jr=ht,Yi=lt(Ye,{...wt,segmentNumber:Ki.toString(10),segmentTime:ht.toString(10)})}let HE={time:{from:Jr,to:1/0},url:Yi};zi={type:"template",baseUrl:pi,segmentTemplateUrl:Ye,initUrl:mi,totalSegmentsDurationMs:Ht,segments:pt,nextSegmentBeyondManifest:HE,timescale:tt}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!qt||!Nt)continue;let Xr={video:"video",audio:"audio",text:"text"}[qt];if(!Xr)continue;Qi||(Qi=Xr),Js={id:an,kind:Xr,segmentReference:zi,profiles:sn,duration:b,bitrate:en,mime:Nt,codecs:Xs,width:hi,height:Yr,fps:yu,quality:Gi}}de.language||(de.language=Ft),de.label||(de.label=zr),de.mime||(de.mime=Nt),de.codecs||(de.codecs=Xs),de.hdr||(de.hdr=Qi==="video"&&Jc(Xs)),de.representations.push(Js)}if(Qi){let ee=r[Qi].find(Ft=>Ft.id===de.id);if(ee&&de.representations.every(Ft=>Ft.segmentReference.type==="template"))for(let Ft of ee.representations){let zr=de.representations.find(Nt=>Nt.id===Ft.id),Ks=zr==null?void 0:zr.segmentReference,pi=Ft.segmentReference;pi.segments.push(...Ks.segments),pi.nextSegmentBeyondManifest=Ks.nextSegmentBeyondManifest}else r[Qi].push(de)}}return{duration:b,streams:r,baseUrls:n,live:S}};var td=O(ot(),1);import{videoSizeToQuality as fB}from"@vkontakte/videoplayer-shared/es2018";var hs=({id:a,width:e,height:t,bitrate:i,fps:r,quality:s,streamId:n})=>{var u;let o=(u=s?Kt(s):void 0)!=null?u:fB({width:e,height:t});return o&&{id:a,quality:o,bitrate:i,size:{width:e,height:t},fps:r,streamId:n}},eI=({id:a,bitrate:e})=>({id:a,bitrate:e}),tI=({language:a,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:a,label:e}),iI=({language:a,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:a,label:e}),id=({id:a,language:e,label:t,codecs:i,isDefault:r})=>({id:a,language:e,label:t,codec:(0,td.default)(i.split("."),0),isDefault:r}),rd=({id:a,language:e,label:t,hdr:i,codecs:r})=>({id:a,language:e,hdr:i,label:t,codec:(0,td.default)(r.split("."),0)}),ad=a=>"url"in a,Ge=a=>a.type==="template";import{isNonNullable as rI}from"@vkontakte/videoplayer-shared/es2018";var N=(a,e)=>rI(a)&&rI(e)&&a.readyState==="open"&&mB(a,e);function mB(a,e){for(let t=0;t<a.activeSourceBuffers.length;++t)if(a.activeSourceBuffers[t]===e)return!0;return!1}var fs=class{constructor(e,t,i,{fetcher:r,tuning:s,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new Ci(0);this.currentLowLatencySegmentLength$=new Ci(0);this.currentSegmentLength$=new Ci(0);this.onLastSegment$=new Ci(!1);this.fullyBuffered$=new Ci(!1);this.playingRepresentation$=new Ci(void 0);this.playingRepresentationInit$=new Ci(void 0);this.error$=new SB;this.gaps=[];this.subscription=new vB;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new Z;this.switchAbortController=new Z;this.destroyAbortController=new Z;this.useSmartRepresentationSwitch=!1;this.bufferLimit=1/0;this.failedDownloads=0;this.baseUrls=[];this.baseUrlsIndex=0;this.isLive=!1;this.liveUpdateSegmentIndex=0;this.liveInitialAdditionalOffset=0;this.isSeekingLive=!1;this.index=0;this.lastDataObtainedTimestampMs=0;this.loadByteRangeSegmentsTimeoutId=0;this.startWith=Zt(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);$e(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new Jy(this.sourceBuffer),this.subscription.add(sd(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let o,u=this.mediaSource.readyState;u!=="open"&&(o={id:`SegmentEjection_source_${u}`,category:Mt.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o!=null||(o={id:"SegmentEjection",category:Mt.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),this.error$.next(o)})),this.subscription.add(sd(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:Mt.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o||!N(this.mediaSource,this.sourceBuffer))return;let u=Math.min(this.bufferLimit,Ar(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);$e(i,"No init buffer for starting representation"),$e(r,"No segments for starting representation"),i instanceof ArrayBuffer&&(this.searchGaps(r,t),yield this.sourceBufferTaskQueue.append(i,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(s))}.bind(this));this.switchTo=Zt(this.destroyAbortController.signal,async function*(e,t=!1){if(!N(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);$e(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if(he(s)||he(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),$e(r,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!N(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();ei(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=Zt(this.destroyAbortController.signal,async function*(e,t=!1){if(!N(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);$e(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if(he(s)||he(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),$e(r,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!N(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();ei(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=Zt(this.destroyAbortController.signal,async function*(e){var u,l;let t=(u=(0,Ao.default)(e,c=>c.representations))!=null?u:[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let c of this.representations.keys()){let d=t.find(h=>h.id===c);d&&this.representations.set(c,d);let f=this.representations.get(c);if(!f||!Ge(f.segmentReference))return;let p=this.getActualLiveStartingSegments(f.segmentReference);this.segments.set(f.id,p)}let i=(l=this.switchingToRepresentationId)!=null?l:this.downloadingRepresentationId,r=this.representations.get(i);$e(r);let s=this.segments.get(i);$e(s,"No segments for starting representation");let n=this.initData.get(i);if($e(n,"No init buffer for starting representation"),!(n instanceof ArrayBuffer))return;let 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));var c;this.fetcher=r,this.tuning=s,this.compatibilityMode=u,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=o,this.isLive=!!(l!=null&&l.live),this.baseUrls=(c=l==null?void 0:l.baseUrls)!=null?c:[],this.initData=new Map(i.map(d=>[d.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(i.map(d=>[d.id,d])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}switchToWithPreviousAbort(e,t=!1){!N(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new Z,Zt(this.switchAbortController.signal,async function*(i,r=!1){this.switchingToRepresentationId=i;let s=this.representations.get(i);$e(s,`No such representation ${i}`);let n=this.segments.get(i),o=this.initData.get(i);if(he(o)||he(n)?yield this.loadInit(s,"high",!1):o instanceof Promise&&(yield o),n=this.segments.get(i),$e(n,"No segments for starting representation"),o=this.initData.get(i),!(!(o instanceof ArrayBuffer)||!this.sourceBuffer||!N(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();ei(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(){!he(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 Z,this.abortBuffer()}maintain(e=this.getCurrentPosition()){var f;if(he(e)||he(this.downloadingRepresentationId)||he(this.playingRepresentationId)||he(this.sourceBuffer)||!N(this.mediaSource,this.sourceBuffer)||ei(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.representations.get(this.playingRepresentationId),r=this.segments.get(this.downloadingRepresentationId),s=this.segments.get(this.playingRepresentationId);if($e(t,`No such representation ${this.downloadingRepresentationId}`),$e(i,`No such representation ${this.playingRepresentationId}`),he(r)||he(s))return;let n=r.find(p=>e>=p.time.from&&e<p.time.to);ei(n)&&isFinite(n.time.from)&&isFinite(n.time.to)&&this.currentSegmentLength$.next((n==null?void 0:n.time.to)-n.time.from);let o=e,u=100;if(this.playingRepresentationId!==this.downloadingRepresentationId){let p=this.getForwardBufferDuration(e),h=hs(i),m=hs(t),S=this.useSmartRepresentationSwitch&&this.tuning.dash.useNewRepresentationSwitch&&this.tuning.dash.useSmartRepresentationSwitch&&ei(h)&&ei(m)&&bB(h.quality,m.quality),b=this.useSmartRepresentationSwitch&&this.tuning.dash.useNewRepresentationSwitch&&this.tuning.dash.useDelayedRepresentationSwitch;if(S||b?o+=Math.min(p,this.tuning.dash.representationSwitchForwardBufferGap):n&&n.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&p>=n.time.to-e+u&&(o=n?n.time.to+u:-1/0),this.tuning.dash.useNewRepresentationSwitch){let T=(f=this.segments.entries().map(([y,I])=>{let w=I.find(L=>e>=L.time.from&&e<L.time.to);return{representationId:y,status:w==null?void 0:w.status}}).find(y=>y.status==="fed"))==null?void 0:f.representationId;if(!T)return;this.playingRepresentationId=T,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId))}}if(isFinite(this.bufferLimit)&&Ar(this.sourceBuffer.buffered)>=this.bufferLimit){let p=this.getForwardBufferDuration(e),h=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,p<h).catch(m=>{this.handleAsyncError(m,"pruneBuffer")});return}let c=[];if(!this.activeSegments.size&&(c=this.selectForwardBufferSegments(r,t.segmentReference.type,o),c.length)){let p="auto";if(this.tuning.dash.useFetchPriorityHints&&n)if((0,wo.default)(c,n))p="high";else{let h=(0,Bi.default)(c,0);h&&h.time.from-n.time.to>=this.forwardBufferTarget/2&&(p="low")}this.loadSegments(c,t,p).catch(h=>{this.handleAsyncError(h,"loadSegments")})}(!this.preloadOnly&&!this.allInitsLoaded&&n&&n.status==="fed"&&!c.length&&this.getForwardBufferDuration(e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let d=(0,Bi.default)(r,-1);!this.isLive&&d&&(this.fullyBuffered$.next(d.time.to-e-this.getForwardBufferDuration(e)<u),this.onLastSegment$.next(e-d.time.from>0))}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}searchGaps(e,t){this.gaps=[];let i=0,r=this.isLive?this.liveInitialAdditionalOffset:0;for(let s of e)Math.trunc(s.time.from-i)>0&&this.gaps.push({representation:t.id,from:i,to:s.time.from+r}),i=s.time.to;ei(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,Ao.default)(e==null?void 0: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!=null&&i.length)return{from:i[0].time.from,to:i[i.length-1].time.to}}updateLive(e){var i,r,s,n;let t=(i=(0,Ao.default)(e==null?void 0:e.streams[this.kind],o=>o.representations))!=null?i:[];if(![...this.segments.values()].every(o=>!o.length))for(let o of t){if(!o||!Ge(o.segmentReference))return;let u=o.segmentReference.segments.map(p=>({...p,status:"none",size:void 0})),l=100,c=(r=this.segments.get(o.id))!=null?r:[],d=(n=(s=(0,Bi.default)(c,-1))==null?void 0:s.time.to)!=null?n:0,f=u==null?void 0:u.findIndex(p=>d>=p.time.from+l&&d<=p.time.to+l);if(f===-1){this.liveUpdateSegmentIndex=0;let p=this.getActualLiveStartingSegments(o.segmentReference);this.segments.set(o.id,p)}else{let p=u.slice(f+1);this.segments.set(o.id,[...c,...p])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;$e(e);let t=this.segments.get(e);if(t!=null&&t.length){let i=t[t.length-1];this.updateLowLatencyLiveIfNeeded(i)}}calculateDurationFromSegments(){var t;if(!this.playingRepresentationId)return 0;let e=this.segments.get(this.playingRepresentationId);return(e?(t=(0,Bi.default)(e,-1))==null?void 0:t.time.to:0)||0}setSmartRepresentationSwitch(e){this.useSmartRepresentationSwitch=e}updateLowLatencyLiveIfNeeded(e){var i;let t=0;for(let r of this.representations.values()){let s=r.segmentReference;if(!Ge(s))return;let n=(i=this.segments.get(r.id))!=null?i:[],o=n.find(l=>Math.floor(l.time.from)===Math.floor(e.time.from));if(o&&!isFinite(o.time.to)&&(o.time.to=e.time.to,t=o.time.to-o.time.from),!!!n.find(l=>Math.floor(l.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let l=Math.round(e.time.to*s.timescale/1e3).toString(10),c=lt(s.segmentTemplateUrl,{segmentTime:l});n.push({status:"none",time:{from:e.time.to,to:1/0},url:c})}}this.currentLowLatencySegmentLength$.next(t)}findSegmentStartTime(e){var s,n,o;let t=(n=(s=this.switchingToRepresentationId)!=null?s:this.downloadingRepresentationId)!=null?n:this.playingRepresentationId;if(!t)return;let i=this.segments.get(t);if(!i)return;let r=i.find(u=>u.time.from<=e&&u.time.to>=e);return(o=r==null?void 0:r.time.from)!=null?o:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){var e;if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),(e=this.sourceBufferTaskQueue)==null||e.destroy(),this.gapDetectionIdleCallback&&yt&&yt(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&yt&&yt(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer)try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(t){if(!(t instanceof DOMException&&t.name==="NotFoundError"))throw t}this.sourceBuffer=null,this.downloadAbortController.abort(),this.switchAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,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:f,time:{from:p,to:h}},m)=>{let S=p<=i&&h>=i,b=p>i||S||m===0&&i===0,v=Math.min(this.forwardBufferTarget,this.bufferLimit),T=this.preloadOnly&&p<=i+v||r<v&&h-p>=v||h<=i+v;return(f==="none"||f==="partially_ejected"&&b&&T&&this.sourceBuffer&&N(this.mediaSource,this.sourceBuffer)&&!(xe(this.sourceBuffer.buffered,p)&&xe(this.sourceBuffer.buffered,h)))&&b&&T});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 f=s;f<n.length&&(o<=c||u<=d);f++){let p=n[f];if(o+=p.byte.to+1-p.byte.from,u+=p.time.to+1-p.time.from,p.status==="none"||p.status==="partially_ejected")l.push(p);else break}return l}async loadSegments(e,t,i="auto"){Ge(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 Zt(o,async function*(){let c=nd(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(),bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation});if(this.lastDataObtainedTimestampMs=xo(),!c)return;let d=new DataView(c),f=Tt(t.mime);if(!isFinite(r.segment.time.to)){let m=t.segmentReference.timescale;r.segment.time.to=f.getChunkEndTime(d,m)}u&&r.feedingBytes&&l?await Promise.all(l):await this.sourceBufferTaskQueue.append(d,o);let{serverDataReceivedTimestamp:p,serverDataPreparedTime:h}=f.getServerLatencyTimestamps(d);p&&h&&this.currentLiveSegmentServerLatency$.next(h-p),r.segment.status="downloaded",this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(c){this.abortActiveSegments([e]),It(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())Ge(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 Zt(n,async function*(){let u=nd(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),sd(window,"online").pipe(gB()).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,bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation}),this.lastDataObtainedTimestampMs=xo(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),It(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}prepareByteRangeFetchSegmentParams(e,t){if(Ge(t.segmentReference))throw new Error("Representation is not byte range type");let i=t.segmentReference.url,r={from:(0,Bi.default)(e,0).byte.from,to:(0,Bi.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=xo(),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:Mt.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!Ge(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=xo();let d=this.onSomeTemplateDataLoaded({dataView:l,loaded:c,signal:s,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(d)}catch(d){this.error$.next({id:"SegmentFeeding",category:Mt.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:d})}}:void 0;return{url:r,signal:s,onProgress:u,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)(0,wo.default)(e,t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:r,signal:s}){if(!this.activeSegments.size||!N(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=Tt(n.mime).parseFeedableSegmentChunk(l,this.isLive);c!=null&&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||!N(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,f=d-c+1,p=c<r,h=d<=r;if(!p)continue;let m=Tt(o.mime);if(l.status==="downloading"&&h){l.status="downloaded";let S=new DataView(e.buffer,e.byteOffset+c,f);await this.sourceBufferTaskQueue.append(S,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(f,r-c),u.loadedBytes>u.feedingBytes)){let S=new DataView(e.buffer,e.byteOffset+c+u.feedingBytes,u.loadedBytes-u.feedingBytes),b=u.loadedBytes===f?S:m.parseFeedableSegmentChunk(S);b!=null&&b.byteLength&&(l.status="partially_fed",u.feedingBytes+=b.byteLength,await this.sourceBufferTaskQueue.append(b,s)&&!s.aborted?(u.fedBytes+=b.byteLength,u.fedBytes===f&&this.onSegmentFullyAppended(u,t)):await n())}}}onSegmentFullyAppended(e,t){var i;if(!(he(this.sourceBuffer)||!N(this.mediaSource,this.sourceBuffer))){!this.isLive&&F.browser.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(xe(this.sourceBuffer.buffered,e.segment.time.from,100)&&xe(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:Mt.VIDEO_PIPELINE,message:"Browser stuck on empty result of adding segment to source buffer"})),this.tuning.dash.useNewRepresentationSwitch||(this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId))),e.segment.status="fed",ad(e.segment)&&(e.segment.size=e.fedBytes);for(let r of this.representations.values())if(r.id!==t)for(let s of(i=this.segments.get(r.id))!=null?i:[])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.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||(t=n),s===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let i=this.representations.get(e);i&&(this.initLoadIdleCallback=wr(()=>(0,aI.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?Zt(this.destroyAbortController.signal,async function*(){let o=nd(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,Tt(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 f=c;this.isLive&&Ge(e.segmentReference)&&(f=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,f),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:Mt.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||!N(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||he(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:f}=u[c],p=l[l.length-1];p.to>=d?p.to=Math.max(p.to,f):l.push(u[c])}return l},o=u=>{var c;if(s>=t)return r;r.push({...u.time}),r=n(r);let l=ad(u)?(c=u.size)!=null?c:0:u.byte.to-u.byte.from;s+=l};for(let u of this.segments.values())for(let l of u){let c=l.time.to<=e-this.tuning.dash.bufferPruningSafeZone,d=l.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(c||d)&&l.status==="fed"&&o(l)}for(let u=0;u<this.sourceBuffer.buffered.length;u++){let l=this.sourceBuffer.buffered.start(u)*1e3,c=this.sourceBuffer.buffered.end(u)*1e3,d=0;for(let f of this.segments.values())for(let p of f)(0,wo.default)(["none","partially_ejected"],p.status)&&Math.round(p.time.from)<=Math.round(l)&&Math.round(p.time.to)>=Math.round(c)&&d++;if(d===this.segments.size){let f={time:{from:l,to:c},url:"",status:"none"};o(f)}}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||!N(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||!N(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||!N(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||he(e)?0:Ee(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!(!this.sourceBuffer||!N(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||!N(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=wr(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:Mt.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if(he(this.sourceBuffer)||!N(this.mediaSource,this.sourceBuffer)||he(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:Mt.VIDEO_PIPELINE,thrown:e,message:"Something went wrong"})}};var ti=a=>{let e=new URL(a);return e.searchParams.set("quic","1"),e.toString()};var Ro=a=>{var s;let e=a.get("X-Delivery-Type"),t=a.get("X-Reused"),i=e===null?"http1":e!=null?e:void 0,r=t===null?void 0:(s={1:!0,0:!1}[t])!=null?s:void 0;return{type:i,reused:r}};import{abortable as ms,assertNever as sI,fromEvent as nI,merge as yB,now as bs,Subscription as TB,Subject as $r,ValueSubject as od,flattenObject as Mr,ErrorCategory as gs}from"@vkontakte/videoplayer-shared/es2018";var Po=a=>{let e=new URL(a);return e.searchParams.set("enable-subtitles","yes"),e.toString()};var Lo=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:s=!1}){this.manifestRequested=new $r;this.manifestReceived=new $r;this.firstBytesRequested=new $r;this.firstBytesReceived=new $r;this.lastConnectionType$=new od(void 0);this.lastConnectionReused$=new od(void 0);this.lastRequestFirstBytes$=new od(void 0);this.recoverableError$=new $r;this.error$=new $r;this.abortAllController=new Z;this.subscription=new TB;this.fetchManifest=ms(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=ti(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=Po(i)),this.manifestRequested.next();let r=yield this.doFetch(i,{signal:this.abortAllController.signal}).catch(ko);return r?(t.log("success",Mr({url:i,message:"Request successfully executed"})),t.end(),this.manifestReceived.next(),this.onHeadersReceived(r.headers),r.text()):(t.error("error",Mr({url:i,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=ms(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,bufferOptimisation:l=!1}={}){var _,K,J;let c=e,d=new Headers,f=this.tracer.createComponentTracer("Fetch");if(i)switch(t){case 0:{d.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let E=new URL(c,location.href);E.searchParams.append("bytes",`${i.from}-${i.to}`),c=E.toString();break}default:sI(t)}this.requestQuic&&(c=ti(c));let p=this.abortAllController.signal,h;if(n){let E=new Z;if(h=yB(nI(this.abortAllController.signal,"abort"),nI(n,"abort")).subscribe(()=>{try{E.abort()}catch(k){ko(k)}}),this.subscription.add(h),this.abortAllController.signal.aborted||n.aborted)try{E.abort()}catch(k){ko(k)}p=E.signal}let m=0,S=bs();f.log("startRequest",Mr({url:c,priority:s,rangeMethod:t,range:i,isLowLatency:u,requestStartedAt:S})),this.firstBytesRequested.next();let b=yield this.doFetch(c,{priority:s,headers:d,signal:p}),v=bs();if(!b)return f.error("error",{message:"No response in request"}),f.end(),h==null||h.unsubscribe(),null;if((_=this.throughputEstimator)==null||_.addRawRtt(v-S),!b.ok||!b.body){h==null||h.unsubscribe();let E=`Fetch error ${b.status}: ${b.statusText}`;return f.error("error",{message:E}),f.end(),Promise.reject(new Error(`Fetch error ${b.status}: ${b.statusText}`))}if(this.onHeadersReceived(b.headers),!r&&!o){h==null||h.unsubscribe();let E=bs(),k={requestStartedAt:S,requestEndedAt:E,duration:E-S};return f.log("endRequest",Mr(k)),f.end(),b.arrayBuffer()}let T=b.body;if(o){let E;[T,E]=b.body.tee(),(K=this.throughputEstimator)==null||K.trackStream(E,u)}let y=T.getReader(),I,w=parseInt((J=b.headers.get("content-length"))!=null?J:"",10);Number.isFinite(w)&&(I=w),!I&&i&&(I=i.to-i.from+1);let L=I?new Uint8Array(I):new Uint8Array(0),M=!1,R=E=>{h==null||h.unsubscribe(),M=!0,ko(E)},P=ms(p,async function*({done:E,value:k}){if(m===0&&(this.lastRequestFirstBytes$.next(bs()-S),this.firstBytesReceived.next()),p.aborted){h==null||h.unsubscribe();return}if(!E&&k){if(l&&I)L.set(k,m),m+=k.byteLength;else{let x=new Uint8Array(L.length+k.length);x.set(L),x.set(k,L.length),L=x,m+=k.byteLength}r==null||r(new DataView(L.buffer),m),yield y==null?void 0:y.read().then(P,R)}}.bind(this));yield y==null?void 0:y.read().then(P,R),h==null||h.unsubscribe();let V=bs(),D={failed:M,requestStartedAt:S,requestEndedAt:V,duration:V-S};return M?(f.error("endRequest",Mr(D)),f.end(),null):(f.log("endRequest",Mr(D)),f.end(),L.buffer)}.bind(this));this.fetchByteRangeRepresentation=ms(this.abortAllController.signal,async function*(e,t,i){var b;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 f=new DataView(d,r-n,s-n+1);if(!t.validateData(f))throw new Error("Invalid media file");let p=t.parseInit(f),h=(b=e.indexRange)!=null?b:t.getIndexRange(p);if(!h)throw new ReferenceError("No way to load representation index");let m;if(u)m=new DataView(d,h.from-n,h.to-h.from+1);else{let v=yield this.fetch(e.url,{range:h,priority:i,measureThroughput:!1});if(!v)return null;m=new DataView(v)}let S=t.parseSegments(m,p,h);return{init:p,dataView:new DataView(d),segments:S}}.bind(this));this.fetchTemplateRepresentation=ms(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}=Ro(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}async fetchRepresentation(e,t,i="auto"){var s,n;let{type:r}=e;switch(r){case"byteRange":return(s=await this.fetchByteRangeRepresentation(e,t,i))!=null?s:null;case"template":return(n=await this.fetchTemplateRepresentation(e,i))!=null?n:null;default:sI(r)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}async doFetch(e,t){let i=await Ze(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:gs.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:gs.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:gs.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:gs.FATAL});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${s})`,category:gs.FATAL})}}},ko=a=>{if(!It(a))throw a};var Dt=(a,e,t)=>t*e+(1-t)*a,ud=(a,e)=>a.reduce((t,i)=>t+i,0)/e,oI=(a,e,t,i)=>{let r=0,s=t,n=ud(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 IB,ValueSubject as uI}from"@vkontakte/videoplayer-shared/es2018";var ii=class{constructor(e){this.prevReported=void 0;this.pastMeasures=[];this.takenMeasures=0;this.measuresCursor=0;var i;this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new uI(e.initial),this.debounced$=new uI(e.initial);let t=(i=e.label)!=null?i:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new ke(`raw_${t}`),this.smoothedSeries$=new ke(`smoothed_${t}`),this.reportedSeries$=new ke(`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)&&(IB(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 $o=class extends ii{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=Dt(this.slow,e,this.params.emaAlphaSlow),this.fast=Dt(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var Mo=class extends ii{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=ud(this.pastMeasures,this.takenMeasures);this.emaSmoothed=Dt(this.emaSmoothed,e,this.params.emaAlpha);let i=oI(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=i?this.emaSmoothed:t}};var Do=class extends ii{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?Dt(this.smoothed,t,this.params.emaAlpha):t}};var Ct=class{static getSmoothedValue(e,t,i){return i.type==="TwoEma"?new $o({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new Mo({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 Do({initial:e,label:"liveEdgeDelay",...t})}};var Dr=(a,e)=>{a&&a.playbackRate!==e&&(a.playbackRate=e)};import{isNullable as EB,ValueSubject as xB}from"@vkontakte/videoplayer-shared/es2018";var Ss=class a{constructor(e,t){this.currentRepresentation$=new xB(null);this.maxRepresentations=4;this.representationsCursor=0;this.representations=[];this.currentSegment=null;this.getCurrentPosition=t.getCurrentPosition,this.processStreams(e)}updateLive(e){this.processStreams(e==null?void 0:e.streams.text)}seekLive(e){this.processStreams(e)}maintain(e=this.getCurrentPosition()){var t;if(!EB(e))for(let i of this.representations)for(let r of i){let s=r.segmentReference,n=s.segments.length,o=s.segments[0].time.from,u=s.segments[n-1].time.to;if(e<o||e>u)continue;let l=s.segments.find(c=>c.time.from<=e&&c.time.to>=e);!l||((t=this.currentSegment)==null?void 0:t.time.from)===l.time.from&&this.currentSegment.time.to===l.time.to||(this.currentSegment=l,this.currentRepresentation$.next({...r,label:"Live Text",language:"ru",isAuto:!0,url:new URL(l.url,s.baseUrl).toString()}))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e!=null?e:[]){let 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!=null&&e.some(t=>a.filterRepresentations(t.representations)))}static filterRepresentations(e){return e==null?void 0:e.filter(t=>t.kind==="text"&&"segmentReference"in t&&Ge(t.segmentReference))}};var Bo=O(ot(),1),ld=O(Ae(),1);import{assertNever as Vo}from"@vkontakte/videoplayer-shared/es2018";var Co=a=>{let{webmDecodingInfo:e}=F.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:Vo(a)}return[t,i]},lI=({webmCodec:a,androidPreferredFormat:e,iosPreferredFormat:t,preferMultiStream:i})=>{let r=[...i?["DASH_STREAMS"]:[],...Co(a),"DASH_SEP","DASH_ONDEMAND",...i?[]:["DASH_STREAMS"]],s=[...i?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...i?[]:["DASH_STREAMS"]];if(F.device.isAndroid)switch(e){case"mpeg":return["MPEG",...r,"HLS","HLS_ONDEMAND"];case"hls":return["HLS","HLS_ONDEMAND",...r,"MPEG"];case"dash":return[...r,"HLS","HLS_ONDEMAND","MPEG"];case"dash_any_mpeg":return[...s,"MPEG",...Co(a),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...Co(a),"MPEG",...s,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...Co(a),...s,"HLS","HLS_ONDEMAND"];default:Vo(e)}if(F.video.nativeHlsSupported)switch(t){case"hls":return[...r,"HLS","HLS_FMP4","HLS_ONDEMAND","MPEG"];case"hls_fmp4":return[...r,"HLS_FMP4","HLS","HLS_ONDEMAND","MPEG"];default:Vo(t)}return[...r,"HLS","HLS_ONDEMAND","MPEG"]},cI=({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=F.device.isMac&&F.browser.isSafari;if(F.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:Vo(a)}else F.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"]},cd=a=>a?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],_o=a=>{if(a.size===0)return;if(a.size===1){let t=a.values().next();return(0,Bo.default)(t.value.split("."),0)}for(let t of a){let i=(0,Bo.default)(t.split("."),0);if(i==="opus"||i==="vp09"||i==="av01")return i}let e=a.values().next();return(0,Bo.default)(e.value.split("."),0)},Oo=a=>{let e=a.map(i=>Cr(i)),{codecs:t}=F.video;return PB().filter(i=>{if((0,ld.default)(e,i))switch(i){case"av1":return t.av1;case"vp9":return t.vp9;case"avc1":return t.h264;case"hev1":return t.h265;default:return!1}else return!1})},Fo=a=>{let e=a.map(i=>Cr(i)),{codecs:t}=F.video;return kB().filter(i=>{if((0,ld.default)(e,i))switch(i){case"opus":return t.opus;case"mp4a":return t.aac;default:return!1}else return!1})},Cr=a=>a.split(".")[0].replace("0",""),PB=()=>["av1","vp9","hev1","avc1"],kB=()=>["opus","mp4a"];var BB=["timeupdate","progress","play","seeked","stalled","waiting"],VB=["timeupdate","progress","loadeddata","playing","seeked"];var qo=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.bufferManagers=[];this.subscription=new hI;this.representationSubscription=new hI;this.state$=new j("none");this.currentVideoRepresentation$=new ae(void 0);this.currentVideoRepresentationInit$=new ae(void 0);this.currentAudioRepresentation$=new ae(void 0);this.currentVideoSegmentLength$=new ae(0);this.currentAudioSegmentLength$=new ae(0);this.error$=new ri;this.manifestRequested=new ri;this.manifestReceived=new ri;this.firstBytesRequested=new ri;this.firstBytesReceived=new ri;this.lastConnectionType$=new ae(void 0);this.lastConnectionReused$=new ae(void 0);this.lastRequestFirstBytes$=new ae(void 0);this.currentLiveTextRepresentation$=new ae(null);this.isLive$=new ae(!1);this.isActiveLive$=new ae(!1);this.isLowLatency$=new ae(!1);this.liveDuration$=new ae(0);this.liveSeekableDuration$=new ae(0);this.liveAvailabilityStartTime$=new ae(0);this.liveStreamStatus$=new ae(void 0);this.bufferLength$=new ae(0);this.liveLatency$=new ae(void 0);this.liveLoadBufferLength$=new ae(0);this.livePositionFromPlayer$=new ae(0);this.currentStallDuration$=new ae(0);this.videoLastDataObtainedTimestamp$=new ae(0);this.fetcherRecoverableError$=new ri;this.fetcherError$=new ri;this.liveStreamEndTimestamp=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.forceEnded$=new ri;this.gapWatchdogActive=!1;this.destroyController=new Z;this.initManifest=pd(this.destroyController.signal,async function*(e,t,i){var r;this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=le(t,i,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),(r=this.manifest)!=null&&r.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:ct.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=pd(this.destroyController.signal,async function*(){var u,l;this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(c=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:ct.NETWORK,message:"Failed to load manifest",thrown:c})});if(!e)return null;let t=null;try{t=Eo(e!=null?e:"",this.manifestUrlString)}catch(c){let d=(u=To(e))!=null?u:{id:"ManifestParsing",category:ct.PARSER,message:"Failed to parse MPD manifest",thrown:c};this.error$.next(d)}if(!t)return null;let i=(c,d,f)=>{var p,h,m,S;return!!((h=(p=this.element)==null?void 0:p.canPlayType)!=null&&h.call(p,d)&&((S=(m=Qe())==null?void 0:m.isTypeSupported)!=null&&S.call(m,`${d}; codecs="${f}"`))||c==="text")};if(t.live){this.isLive$.next(!!t.live);let{availabilityStartTime:c,latestSegmentPublishTime:d,streamIsUnpublished:f,streamIsAlive:p}=t.live,h=((l=t.duration)!=null?l:0)/1e3;this.liveSeekableDuration$.next(-1*h),this.liveDuration$.next((d-c)/1e3),this.liveAvailabilityStartTime$.next(t.live.availabilityStartTime);let m="active";p||(m=f?"unpublished":"unexpectedly_down"),this.liveStreamStatus$.next(m)}let r={text:t.streams.text,video:[],audio:[]},s,n;for(let c of["video","audio"]){let f=t.streams[c].filter(({mime:h,codecs:m})=>i(c,h,m));r[c]=f;let p;if(this.tuning.dash.codecsPrioritizeEnabled){let h=f.map(({codecs:m})=>m);c==="audio"&&(n=Fo(h),p=n[0]),c==="video"&&(s=Oo(h),this.forceVideoCodec&&(0,mI.default)(s,this.forceVideoCodec)?p=this.forceVideoCodec:p=s[0]),p&&(r[c]=f.filter(({codecs:m})=>Cr(m)===p))}else{let h=new Set(f.map(({codecs:m})=>m));p=_o(h),p&&(r[c]=f.filter(({codecs:m})=>m.startsWith(p)))}if(c==="video"){let h=this.tuning.preferHDR,m=r.video.some(b=>b.hdr),S=r.video.some(b=>!b.hdr);F.display.isHDR&&h&&m?r.video=r.video.filter(b=>b.hdr):S&&(r.video=r.video.filter(b=>!b.hdr))}}let o={...t,streams:r};return this.tuning.dash.codecsPrioritizeEnabled&&(o.codecs={video:s,audio:n}),this.tracer.log("updateManifestEnd",ys(o)),o}.bind(this));this.initRepresentations=pd(this.destroyController.signal,async function*(e,t,i){var f;this.tracer.log("initRepresentationsStart",ys({initialVideo:e,initialAudio:t,sourceHls:i})),Br(this.manifest),Br(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let r=p=>{this.representationSubscription.add(Bt(p,"error").pipe(No(h=>{var m;return!!((m=this.element)!=null&&m.played.length)})).subscribe(h=>{this.error$.next({id:"VideoSource",category:ct.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:h})}))};this.source=Yn();let s=document.createElement("source");if(r(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),fr())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 fs("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],Ts(t)){let p=this.manifest.streams.audio.reduce((h,m)=>[...h,...m.representations],[]);this.audioBufferManager=new fs("audio",this.source,p,n),this.bufferManagers.push(this.audioBufferManager)}Ss.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new Ss(this.manifest.streams.text,n)),this.representationSubscription.add(this.fetcher.manifestRequested.subscribe(this.manifestRequested)),this.representationSubscription.add(this.fetcher.manifestReceived.subscribe(this.manifestReceived)),this.representationSubscription.add(this.fetcher.firstBytesRequested.subscribe(this.firstBytesRequested)),this.representationSubscription.add(this.fetcher.firstBytesReceived.subscribe(this.firstBytesReceived)),this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$));let u=()=>{var p;(p=this.stallWatchdogSubscription)==null||p.unsubscribe(),this.currentStallDuration$.next(0)};if(this.representationSubscription.add(Vi(...VB.map(p=>Bt(this.element,p))).pipe(_r(p=>this.element?Ee(this.element.buffered,this.element.currentTime*1e3):0),vs(),DB(p=>{p>this.tuning.dash.bufferEmptinessTolerance&&u()})).subscribe(this.bufferLength$)),this.representationSubscription.add(Vi(Bt(this.element,"ended"),this.forceEnded$).subscribe(()=>{u()})),this.isLive$.getValue()){this.subscription.add(this.liveDuration$.pipe(vs()).subscribe(h=>this.liveStreamEndTimestamp=fd())),this.subscription.add(Bt(this.element,"pause").subscribe(()=>{this.livePauseWatchdogSubscription=hd(1e3).subscribe(h=>{let m=zt(this.manifestUrlString,2);this.manifestUrlString=le(this.manifestUrlString,m+1e3,2),this.liveStreamStatus$.getValue()==="active"&&this.updateManifest()}),this.subscription.add(this.livePauseWatchdogSubscription)})).add(Bt(this.element,"play").subscribe(h=>{var m;return(m=this.livePauseWatchdogSubscription)==null?void 0:m.unsubscribe()})),this.representationSubscription.add(Vr({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(_r(({isActiveLive:h,isLowLatency:m})=>h&&m),vs()).subscribe(h=>{this.isManualDecreasePlaybackInLive()||Dr(this.element,1)})),this.representationSubscription.add(Vr({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(No(({bufferLength:h,isActiveLive:m,isLowLatency:S})=>m&&S&&!!h)).subscribe(({bufferLength:h})=>this.liveBuffer.next(h))),this.representationSubscription.add(this.videoBufferManager.currentLowLatencySegmentLength$.subscribe(h=>{if(!this.isActiveLive$.getValue()&&!this.isLowLatency$.getValue()&&!h)return;let m=this.liveSeekableDuration$.getValue()-h/1e3;this.liveSeekableDuration$.next(Math.max(m,-1*this.tuning.dashCmafLive.maxLiveDuration)),this.liveDuration$.next(this.liveDuration$.getValue()+h/1e3)})),this.representationSubscription.add(Vr({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe(No(({isLive:h})=>h),vs((h,m)=>m.bufferLength<h.bufferLength),_r(({rtt:h,bufferLength:m,segmentServerLatency:S})=>{let b=zt(this.manifestUrlString,2);return(h/2+m+S+b)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add(Vr({liveBuffer:this.liveBuffer.smoothed$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).subscribe(({liveBuffer:h,isActiveLive:m,isLowLatency:S})=>{if(!S||!m)return;let b=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,v=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,T=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,y=h-b;if(this.isManualDecreasePlaybackInLive())return;let I=1;Math.abs(y)>v&&(I=1+Math.sign(y)*T),Dr(this.element,I)})),this.representationSubscription.add(this.bufferLength$.subscribe(h=>{var S,b;let m=0;if(h){let v=((b=(S=this.element)==null?void 0:S.currentTime)!=null?b:0)*1e3;m=Math.min(...this.bufferManagers.map(y=>{var I,w;return(w=(I=y.getLiveSegmentsToLoadState(this.manifest))==null?void 0:I.to)!=null?w:v}))-v}this.liveLoadBufferLength$.getValue()!==m&&this.liveLoadBufferLength$.next(m)}));let p=0;this.representationSubscription.add(Vr({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(CB(1e3)).subscribe(async({liveLoadBufferLength:h,bufferLength:m})=>{if(!this.element||this.isUpdatingLive)return;let S=this.element.playbackRate,b=zt(this.manifestUrlString,2),v=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,T=Math.min(v,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*S),y=this.tuning.dashCmafLive.normalizedActualBufferOffset*S,I=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*S,w=isFinite(h)?h:m,L=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),M=v<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next(M);let R="none";if(L?R="active_low_latency":this.isLowLatency$.getValue()&&M?(this.bufferManagers.forEach(P=>P.proceedLowLatencyLive()),R="active_low_latency"):b!==0&&w<T?R="live_forward_buffering":w<T+I&&(R="live_with_target_offset"),isFinite(h)&&(p=h>p?h:p),R==="live_forward_buffering"||R==="live_with_target_offset"){let P=p-(T+y),V=this.normolizeLiveOffset(Math.trunc(b+P/S)),D=Math.abs(V-b),_=0;!h||D<=this.tuning.dashCmafLive.offsetCalculationError?_=b:V>0&&D>this.tuning.dashCmafLive.offsetCalculationError&&(_=V),this.manifestUrlString=le(this.manifestUrlString,_,2)}(R==="live_with_target_offset"||R==="live_forward_buffering")&&(p=0,await this.updateLive())},h=>{this.error$.next({id:"updateLive",category:ct.VIDEO_PIPELINE,thrown:h,message:"Failed to update live with subscription"})}))}let l=Vi(...this.bufferManagers.map(p=>p.fullyBuffered$)).pipe(_r(()=>this.bufferManagers.every(p=>p.fullyBuffered$.getValue()))),c=Vi(...this.bufferManagers.map(p=>p.onLastSegment$)).pipe(_r(()=>this.bufferManagers.some(p=>p.onLastSegment$.getValue()))),d=Vr({allBuffersFull:l,someBufferEnded:c}).pipe(vs(),_r(({allBuffersFull:p,someBufferEnded:h})=>p&&h),No(p=>p));if(this.representationSubscription.add(Vi(this.forceEnded$,d).subscribe(()=>{var p;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(h=>!h.updating))try{(p=this.source)==null||p.endOfStream()}catch(h){this.error$.next({id:"EndOfStream",category:ct.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:h})}})),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=>{var m;p&&(this.timeoutSourceOpenId=setTimeout(()=>{var S;if(((S=this.source)==null?void 0:S.readyState)==="open"){h();return}this.error$.next({id:"OpenOfStream",category:ct.VIDEO_PIPELINE,message:"Failed to open MediaSource",thrown:new Error("Timeout reject when wait sourceopen event"),traceAsLog:!0})},this.tuning.dash.sourceOpenTimeout)),(m=this.source)==null||m.addEventListener("sourceopen",()=>{this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),h()},{once:!0})})}if(!this.isLive$.getValue()){let p=[(f=this.manifest.duration)!=null?f:0,...(0,md.default)((0,md.default)([...this.manifest.streams.audio,...this.manifest.streams.video],h=>h.representations),h=>{let m=[];return h.duration&&m.push(h.duration),Ge(h.segmentReference)&&h.segmentReference.totalSegmentsDurationMs&&m.push(h.segmentReference.totalSegmentsDurationMs),m})];this.source.duration=Math.max(...p)/1e3}this.audioBufferManager&&Ts(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState("representations_ready"),this.tracer.log("initRepresentationsEnd")}.bind(this));this.tick=()=>{var t,i,r,s;if(!this.element||!this.videoBufferManager||((t=this.source)==null?void 0:t.readyState)!=="open")return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),(i=this.audioBufferManager)==null||i.maintain(e),(r=this.liveTextManager)==null||r.maintain(e),(this.videoBufferManager.gaps.length||(s=this.audioBufferManager)!=null&&s.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=hd(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),n=>{this.error$.next({id:"GapWatchdog",category:ct.WTF,message:"Error handling gaps",thrown:n})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name),this.forceVideoCodec=e.forceVideoCodec,this.fetcher=new Lo({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=Ct.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.bufferEstimator}),this.initTracerSubscription()}setSmartRepresentationSwitch(e){this.bufferManagers.forEach(t=>t.setSmartRepresentationSwitch(e))}async seekLive(e){var r,s,n;Br(this.element);let t=this.liveStreamStatus$.getValue()!=="active"?fd()-this.liveStreamEndTimestamp:0,i=this.normolizeLiveOffset(e+t);this.isActiveLive$.next(i===0),this.manifestUrlString=le(this.manifestUrlString,i,2),this.manifest=await this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,await((r=this.videoBufferManager)==null?void 0:r.seekLive(this.manifest.streams.video)),await((s=this.audioBufferManager)==null?void 0:s.seekLive(this.manifest.streams.audio)),(n=this.liveTextManager)==null||n.seekLive(this.manifest.streams.text))}initBuffer(){Br(this.element),this.state$.setState("running"),this.subscription.add(Vi(...BB.map(e=>Bt(this.element,e)),Bt(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:ct.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(Bt(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(Bt(this.element,"waiting").subscribe(()=>{var t;this.element&&this.element.readyState===2&&!this.element.seeking&&xe(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{var p,h,m,S,b,v,T,y,I,w,L;if(!this.element||((p=this.source)==null?void 0:p.readyState)!=="open")return;let i=this.currentStallDuration$.getValue();i+=50,this.currentStallDuration$.next(i);let r={timeInWaiting:i},s=fd(),n=100,o=(m=(h=this.videoBufferManager)==null?void 0:h.lastDataObtainedTimestamp)!=null?m:0;this.videoLastDataObtainedTimestamp$.next(o);let u=(b=(S=this.audioBufferManager)==null?void 0:S.lastDataObtainedTimestamp)!=null?b:0,l=(T=(v=this.videoBufferManager)==null?void 0:v.getForwardBufferDuration())!=null?T:0,c=(I=(y=this.audioBufferManager)==null?void 0:y.getForwardBufferDuration())!=null?I:0,d=l<n&&s-o>this.tuning.dash.crashOnStallTWithoutDataTimeout,f=this.audioBufferManager&&c<n&&s-u>this.tuning.dash.crashOnStallTWithoutDataTimeout;if((d||f)&&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 M=this.normolizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);this.seekLive(M).catch(R=>{this.error$.next({id:"stallIntervalCallback",category:ct.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:R})}),r.liveLastOffset=M}else{let M=this.element.currentTime*1e3;(w=this.videoBufferManager)==null||w.maintain(M),(L=this.audioBufferManager)==null||L.maintain(M),r.position=M}this.tracer.log("stallIntervalCallback",ys(r))};(t=this.stallWatchdogSubscription)==null||t.unsubscribe(),this.stallWatchdogSubscription=hd(50).subscribe(e,i=>{this.error$.next({id:"StallWatchdogCallback",category:ct.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==null?void 0:r.switchToWithPreviousAbort(t,i):r==null?void 0:r.switchTo(t,i):r==null?void 0:r.switchToOld(t,i)}async seek(e,t){var r,s,n,o,u;Br(this.element),Br(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((r=this.videoBufferManager.findSegmentStartTime(e))!=null?r:e,(n=(s=this.audioBufferManager)==null?void 0:s.findSegmentStartTime(e))!=null?n:e),this.warmUpMediaSourceIfNeeded(i),xe(this.element.buffered,i)||await Promise.all([this.videoBufferManager.abort(),(o=this.audioBufferManager)==null?void 0:o.abort()]),!(pI(this.element)||pI(this.videoBufferManager))&&(this.videoBufferManager.maintain(i),(u=this.audioBufferManager)==null||u.maintain(i),this.element.currentTime=i/1e3,this.tracer.log("seek",ys({requestedPosition:e,forcePrecise:t,position:i})))}warmUpMediaSourceIfNeeded(e=(t=>(t=this.element)==null?void 0:t.currentTime)()){var i;Ts(this.element)&&Ts(this.source)&&Ts(e)&&((i=this.source)==null?void 0:i.readyState)==="ended"&&this.element.duration*1e3-e>this.tuning.dash.seekBiasInTheEnd&&this.bufferManagers.forEach(r=>r.warmUpMediaSource())}get isStreamEnded(){var e;return((e=this.source)==null?void 0:e.readyState)==="ended"}stop(){var e,t,i;this.tracer.log("stop"),(e=this.element)==null||e.querySelectorAll("source").forEach(r=>{URL.revokeObjectURL(r.src),r.remove()}),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),(t=this.videoBufferManager)==null||t.destroy(),this.videoBufferManager=null,(i=this.audioBufferManager)==null||i.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getStreams(){var e;return(e=this.manifest)==null?void 0:e.streams}getCodecs(){var e;return(e=this.manifest)==null?void 0:e.codecs}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){var e;this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),((e=this.source)==null?void 0:e.readyState)==="open"&&Array.from(this.source.sourceBuffers).every(t=>!t.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}initTracerSubscription(){let e=MB(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(){var e;this.isUpdatingLive=!0,this.manifest=await this.updateManifest(),this.manifest&&(this.bufferManagers.forEach(t=>t.updateLive(this.manifest)),(e=this.liveTextManager)==null||e.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",ys(i)))}}calculateDurationFromSegments(){var e,t;return Math.max(((e=this.videoBufferManager)==null?void 0:e.calculateDurationFromSegments())||0,((t=this.audioBufferManager)==null?void 0:t.calculateDurationFromSegments())||0)}};var Uo=class{constructor(e,t){this.fov=e,this.orientation=t}};var jo=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!=null?e:this.rotationSpeed.x,this.rotationSpeed.y=t!=null?t:this.rotationSpeed.y,this.rotationSpeed.z=i!=null?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 bI=`attribute vec2 a_vertex;
125
125
  attribute vec2 a_texel;
126
126
 
127
127
  varying vec2 v_texel;
@@ -132,7 +132,7 @@ void main(void) {
132
132
  // save texel vector to pass to fragment shader
133
133
  v_texel = a_texel;
134
134
  }
135
- `;var bI=`#ifdef GL_ES
135
+ `;var gI=`#ifdef GL_ES
136
136
  precision highp float;
137
137
  precision highp int;
138
138
  #else
@@ -175,6 +175,6 @@ void main(void) {
175
175
  // sample using new coordinates
176
176
  gl_FragColor = texture2D(u_texture, tc);
177
177
  }
178
- `;var _r=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 Co(this.params.fov,this.params.orientation),this.cameraRotationManager=new Bo(this.camera,{rotationSpeed:this.params.rotationSpeed,maxYawAngle:this.params.maxYawAngle,rotationSpeedCorrection:this.params.rotationSpeedCorrection,degreeToPixelCorrection:this.params.degreeToPixelCorrection,speedFadeTime:this.params.speedFadeTime,speedFadeThreshold:this.params.speedFadeThreshold}),this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.textureMappingBuffer=this.createTextureMappingBuffer(),this.updateTextureMappingBuffer(),this.program=this.createProgram(),this.videoTexture=this.createTexture(),this.gl.useProgram(this.program),this.videoElementDataLoadedFn=this.onDataLoadedHandler.bind(this),this.renderFn=this.render.bind(this)}play(){this.active||(this.videoInitialized?this.doPlay():this.sourceVideoElement.readyState>=2?(this.videoInitialized=!0,this.doPlay()):this.sourceVideoElement.addEventListener("loadeddata",this.videoElementDataLoadedFn))}stop(){this.active=!1}startCameraManualRotation(e,t){this.cameraRotationManager.setRotationSpeed(e*this.params.rotationSpeed,t*this.params.rotationSpeed,0),this.cameraRotationManager.startRotation()}stopCameraManualRotation(e=!1){this.cameraRotationManager.stopRotation(e)}turnCamera(e,t){this.cameraRotationManager.turnCamera(e,t)}pointCameraTo(e,t){this.cameraRotationManager.pointCameraTo(e,t)}pixelToDegree(e){return{x:this.params.degreeToPixelCorrection*this.params.fov.x*-e.x/this.viewportWidth,y:this.params.degreeToPixelCorrection*this.params.fov.y*e.y/this.viewportHeight}}getCameraRotation(){return this.camera.orientation}holdCamera(){this.cameraRotationManager.stopRotation(!0)}releaseCamera(){this.cameraRotationManager.onCameraRelease()}destroy(){this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),this.stop(),this.canvas.remove()}setViewportSize(e,t){this.viewportWidth=e,this.viewportHeight=t,this.canvas.width=this.viewportWidth,this.canvas.height=this.viewportHeight,this.gl.viewport(0,0,this.canvas.width,this.canvas.height)}onDataLoadedHandler(){this.videoInitialized=!0,this.doPlay()}doPlay(){this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.active=!0,this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),requestAnimationFrame(this.renderFn)}render(e){this.cameraRotationManager.tick(e),this.updateTexture(),this.updateTextureMappingBuffer();let t=this.gl.getAttribLocation(this.program,"a_vertex"),i=this.gl.getAttribLocation(this.program,"a_texel"),r=this.gl.getUniformLocation(this.program,"u_texture"),s=this.gl.getUniformLocation(this.program,"u_focus");this.gl.enableVertexAttribArray(t),this.gl.enableVertexAttribArray(i),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.vertexBuffer),this.gl.vertexAttribPointer(t,2,this.gl.FLOAT,!1,0,0),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.vertexAttribPointer(i,2,this.gl.FLOAT,!1,0,0),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.uniform1i(r,0),this.gl.uniform2f(s,-this.camera.orientation.x,-this.camera.orientation.y),this.gl.drawArrays(this.gl.TRIANGLE_FAN,0,4),this.gl.bindTexture(this.gl.TEXTURE_2D,null),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),this.gl.disableVertexAttribArray(t),this.gl.disableVertexAttribArray(i),this.active&&requestAnimationFrame(this.renderFn)}createShader(e,t){let i=this.gl.createShader(t);if(!i)throw this.destroy(),new Error(`Could not create shader (${t})`);if(this.gl.shaderSource(i,e),this.gl.compileShader(i),!this.gl.getShaderParameter(i,this.gl.COMPILE_STATUS))throw this.destroy(),new Error("An error occurred while compiling the shader: "+this.gl.getShaderInfoLog(i));return i}createProgram(){let e=this.gl.createProgram();if(!e)throw this.destroy(),new Error("Could not create shader program");let t=this.createShader(mI,this.gl.VERTEX_SHADER),i=this.createShader(bI,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,f=t+r;return[s,n,o,u,l,c,d,f]}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 OB,now as Ts,once as FB,Subscription as NB,ValueSubject as cd,isNonNullable as qB,safeStorage as dd,filterChanged as UB}from"@vkontakte/videoplayer-shared/es2018";var Vo="stalls_manager_metrics",pd="stalls_manager_abr_params",gI="stalls_manager_default_tuning_abr_params",hd=class{constructor(){this.isSeeked$=new cd(!1);this.isBuffering$=new cd(!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 NB;this.severeStallOccurred$=new cd(!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(pd):{};return{...this.abrParams,...e}}set lastVideoTrackSelected(e){var t;((t=this.lastUniqueVideoTrackSelected)==null?void 0:t.id)!==e.id&&(this.lastUniqueVideoTrackSelected=e,this.lastUniqueVideoTrackSelectedTimestamp=Ts(),this.currentStallsCount=0)}destroy(){window.clearTimeout(this.qualityRestrictionTimer),this.subscription.unsubscribe(),this.currentStallDuration$.getValue()!==0&&this.updateStallData();let e=(Ts()-this.providerStartWatchingTimestamp-this.sumStallsDuration)/1e3,t=this.sumStallsDuration;this.addStallInfoToHistory(e,t),this.updateStoredAbrParams()}resetStoredAbrParamsIfNeeded(){let{bitrateFactorAtEmptyBuffer:e,bitrateFactorAtFullBuffer:t,containerSizeFactor:i}={...this.getStoredData(gI)},{bitrateFactorAtEmptyBuffer:r,bitrateFactorAtFullBuffer:s,containerSizeFactor:n}={...this.abrParams};this.tuning.enabled&&e===r&&t===s&&i===n||(this.removeStoredData(pd),this.setStoredData(gI,{bitrateFactorAtEmptyBuffer:r,bitrateFactorAtFullBuffer:s,containerSizeFactor:n}))}updateStoredAbrParams(){let e=[],t=this.getStoredData(Vo,"[]");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(Vo,[]),this.setStoredData(pd,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="{}"){var i;return JSON.parse((i=dd.get(e))!=null?i:t)}setStoredData(e,t){dd.set(e,JSON.stringify(t))}removeStoredData(e){dd.remove(e)}addStallInfoToHistory(e,t){if(e<this.tuning.minTvtToBeCounted||e>this.tuning.maxTvtToBeCounted||e*1e3<t)return;let i=this.getStoredData(Vo,"[]"),r=t/e,s=i.length?Dt(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(Vo,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(FB()).subscribe(t=>this.providerStartWatchingTimestamp=Ts())),this.subscription.add(this.currentStallDuration$.pipe(UB()).subscribe(t=>{let{stallDurationNoDataBeforeQualityDecrease:i,stallCountBeforeQualityDecrease:r,resetQualityRestrictionTimeout:s,ignoreStallsOnSeek:n}=this.tuning;if(OB(this.lastUniqueVideoTrackSelected)||n&&this.isSeeked$.getValue())return;let o=this.rtt$.getValue(),u=this.throughput$.getValue(),l=this.videoLastDataObtainedTimestamp$.getValue(),c=Ts(),d=r&&this.currentStallsCount>=r,f=i&&c-this.lastUniqueVideoTrackSelectedTimestamp>=i+o&&c-l>=i+o&&t>=i;(d||f)&&(this.severeStallOccurred$.next(!0),window.clearTimeout(this.qualityRestrictionTimer),this.maxQualityLimit=this.lastUniqueVideoTrackSelected.quality,qB(this.lastUniqueVideoTrackSelected.bitrate)&&u>this.lastUniqueVideoTrackSelected.bitrate&&(this.predictedThroughputWithoutData=this.lastUniqueVideoTrackSelected.bitrate)),!t&&Ts()-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}))}},_o=hd;import{combine as HB,map as jB,observeElementSize as QB,Subscription as WB,ValueSubject as fd,noop as GB}from"@vkontakte/videoplayer-shared/es2018";var Oo=class{constructor(){this.subscription=new WB;this.pipSize$=new fd(void 0);this.videoSize$=new fd(void 0);this.elementSize$=new fd(void 0);this.pictureInPictureWindowRemoveEventListener=GB}connect({observableVideo:e,video:t}){let i=r=>{let s=r.target;this.pipSize$.next({width:s.width,height:s.height})};this.subscription.add(QB(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(HB({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe(jB(({videoSize:r,inPip:s,pipSize:n})=>s?n:r)).subscribe(this.elementSize$))}getValue(){return this.elementSize$.getValue()}subscribe(e,t){return this.elementSize$.subscribe(e,t)}getObservable(){return this.elementSize$}destroy(){this.pictureInPictureWindowRemoveEventListener(),this.subscription.unsubscribe()}};var Bi=class{constructor(e){this.subscription=new e0;this.videoState=new H("stopped");this.observableVideo=null;this.droppedFramesManager=new Tr;this.stallsManager=new _o;this.elementSizeManager=new Oo;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new Xt;this.audioTrackSwitchHistory=new Xt;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==null?void 0: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"),L(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"),L(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="ready"&&L(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==null?void 0:i.to)==="playing"&&L(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&L(this.params.desiredState.playbackState,"paused");return;default:return YB(e)}}};this.init3DScene=e=>{var i,r,s;if(this.scene3D)return;this.scene3D=new _r(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:((i=e.projectionData)==null?void 0:i.pose.yaw)||0,y:((r=e.projectionData)==null?void 0:r.pose.pitch)||0,z:((s=e.projectionData)==null?void 0:s.pose.roll)||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});let t=this.elementSizeManager.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};this.textTracksManager=new Xe(e.source.url),this.params=e,this.video=De(e.container,e.tuning),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Te(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 Do({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode,tracer:this.tracer,forceVideoCodec:this.params.forceVideoCodec}),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params;ZB(this.observableVideo)&&(this.observableVideo=Ve(this.video),this.subscription.add(()=>{var n;return(n=this.observableVideo)==null?void 0:n.destroy()}));let i=this.constructor.name,r=n=>{e.error$.next({id:i,category:vI.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(md(l=>!!l.length),yI()).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(bd(l=>l.to.state!=="none"),Fo());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(md(SI),yI()),e.firstBytesEvent$),s(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),s(this.videoState.stateChangeEnded$.pipe(bd(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(bt(this.video,t.isLooped,r)),this.subscription.add(Be(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Ke(this.video,t.playbackRate,i.playbackRateState$,r)),this.elementSizeManager.connect({video:this.video,observableVideo:i}),s(Je(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),L(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),L(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.params.tuning.changePlaybackStateToPausedWhenEnded&&this.subscription.add(i.ended$.subscribe(()=>{this.videoState.setState("paused"),L(t.playbackState,"paused")})),this.subscription.add(this.player.manifestRequested.subscribe(this.params.output.manifestRequested$)).add(this.player.manifestReceived.subscribe(this.params.output.manifestReceived$)).add(this.player.firstBytesRequested.subscribe(this.params.output.firstBytesRequested$)).add(this.player.firstBytesReceived.subscribe(this.params.output.firstBytesReceived$)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:l})=>{if(l==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let c=this.player.getStreams(),d=this.player.getCodecs();if(KB(c,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let p=[];for(let h of c.audio){p.push(Kc(h));let m=[];for(let v of h.representations){let b=ZT(v);m.push(b),this.audioTracksMap.set(b,{stream:h,representation:v})}this.audioStreamsMap.set(h,m)}this.params.output.availableAudioStreams$.next(p)}let f=[];for(let p of c.video){f.push(Xc(p));let h=[];for(let m of p.representations){let v=JT({...m,streamId:p.id});v&&(h.push(v),this.videoTracksMap.set(v,{stream:p,representation:m}))}this.videoStreamsMap.set(p,h)}this.params.output.availableVideoStreams$.next(f);for(let p of c.text)for(let h of p.representations){let m=eI(p,h);this.textTracksMap.set(m,{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),d!=null&&d.video&&this.params.output.availableVideoCodecs$.next(d.video),d!=null&&d.audio&&this.params.output.availableAudioCodecs$.next(d.audio),this.audioTracksMap.size&&this.textTracksMap.size&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else l==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},r)),this.subscription.add(No(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$,JB(this.video,"progress")).pipe(md(()=>this.videoTracksMap.size>0)).subscribe(async()=>{let l=this.player.state$.getState(),c=this.player.state$.getTransition();if(!(0,TI.default)(["manifest_ready","running"],l)||c)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let d=this.selectVideoAudioRepresentations();if(!d)return;let[f,p]=d,h=[...this.videoTracksMap.keys()].find(v=>{var b;return((b=this.videoTracksMap.get(v))==null?void 0:b.representation.id)===f.id});SI(h)&&(this.stallsManager.lastVideoTrackSelected=h);let m=this.params.desiredState.autoVideoTrackLimits.getTransition();if(m&&this.params.output.autoVideoTrackLimits$.next(m.to),l==="manifest_ready")await this.player.initRepresentations(f.id,p==null?void 0:p.id,this.params.sourceHls);else if(await this.player.switchRepresentation("video",f.id),p){let v=!!t.audioStream.getTransition();await this.player.switchRepresentation("audio",p.id,v)}},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(Fo()).subscribe(l=>{let c=[...this.videoTracksMap.entries()].find(([,{representation:m}])=>m.id===l);if(!c){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[d,{stream:f}]=c,p=this.params.desiredState.videoStream.getTransition();p&&p.to&&p.to.id===f.id&&this.params.desiredState.videoStream.setState(p.to),e.currentVideoTrack$.next(d),e.currentVideoStream$.next(Xc(f));let h=this.player.calculateDurationFromSegments();h&&this.params.output.duration$.next(h/1e3)},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(Fo()).subscribe(l=>{let c=[...this.audioTracksMap.entries()].find(([,{representation:h}])=>h.id===l);if(!c){e.currentAudioStream$.next(void 0);return}let[d,{stream:f}]=c,p=this.params.desiredState.audioStream.getTransition();p&&p.to&&p.to.id===f.id&&this.params.desiredState.audioStream.setState(p.to),e.currentAudioStream$.next(Kc(f))},r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(l=>{var c,d;if(l!=null&&l.is3dVideo&&((c=this.params.tuning.spherical)!=null&&c.enabled))try{this.init3DScene(l),e.is3DVideo$.next(!0)}catch(f){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${f}`})}else this.destroy3DScene(),(d=this.params.tuning.spherical)!=null&&d.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(bd(({to:l})=>l==="ready"),Fo());this.subscription.add(No(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,gd(["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(No(o,this.player.state$.stateChangeEnded$,gd(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let u=No(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,gd(["init"])).pipe(XB(0));this.subscription.add(u.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){var P,V,D,_,K,J,I,R,x,w,B,ne,Ne;if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?La:ka,t=this.params.tuning.useNewAutoSelectVideoTrack?so:ao,i=this.params.tuning.useNewAutoSelectVideoTrack?St:ro,{desiredState:r,output:s}=this.params,n=r.autoVideoTrackSwitching.getState(),o=(P=r.videoTrack.getState())==null?void 0:P.id,l=[...this.videoTracksMap.keys()].find(({id:ie})=>ie===o),c=s.currentVideoTrack$.getValue(),d=((_=(D=r.videoStream.getState())!=null?D:l&&((V=this.videoTracksMap.get(l))==null?void 0:V.stream))!=null?_:this.videoStreamsMap.size===1)?this.videoStreamsMap.keys().next().value:void 0;if(!d)return;let f=[...this.videoStreamsMap.keys()].find(({id:ie})=>ie===d.id),p=f&&this.videoStreamsMap.get(f);if(!p)return;let h=be(this.video.buffered,this.video.currentTime*1e3),m;this.player.isActiveLive$.getValue()?m=this.player.isLowLatency$.getValue()?this.params.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.params.tuning.dashCmafLive.normalizedLiveMinBufferSize:this.player.isLive$.getValue()?m=this.params.tuning.dashCmafLive.normalizedTargetMinBufferSize:m=n?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;let v=(this.video.duration*1e3||1/0)-this.video.currentTime*1e3,b=Math.min(h/Math.min(m,v||1/0),1),S=(K=r.audioStream.getState())!=null?K:this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0,T=(J=[...this.audioStreamsMap.keys()].find(({id:ie})=>ie===(S==null?void 0:S.id)))!=null?J:this.audioStreamsMap.keys().next().value,y=0;if(T){if(l&&!n){let ie=e(l,p,(I=this.audioStreamsMap.get(T))!=null?I:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);y=Math.max(y,(R=ie==null?void 0:ie.bitrate)!=null?R:-1/0)}if(c){let ie=e(c,p,(x=this.audioStreamsMap.get(T))!=null?x:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);y=Math.max(y,(w=ie==null?void 0:ie.bitrate)!=null?w:-1/0)}}let E=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:y,forwardBufferHealth:b,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}),k=n?E!=null?E:l:l!=null?l:E,M=T&&t(k,p,(B=this.audioStreamsMap.get(T))!=null?B:[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.stallsManager.abrTuningParams,forwardBufferHealth:b,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),$=(ne=this.videoTracksMap.get(k))==null?void 0:ne.representation,A=M&&((Ne=this.audioTracksMap.get(M))==null?void 0:Ne.representation);if($&&A)return[$,A];if($&&!A&&this.audioTracksMap.size===0)return[$,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){_e(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),L(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:vI.DOM,thrown:e}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.stallsManager.destroy(),this.elementSizeManager.destroy(),this.destroy3DScene(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),this.params.output.currentVideoStream$.next(void 0),Ce(this.video),this.tracer.end()}};var Is=class extends Bi{subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();i(t.timeUpdate$,e.position$),i(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}};import{combine as vd,merge as II,filter as EI,filterChanged as xI,isNullable as Sd,map as wI,ValueSubject as yd,isNonNullable as t0}from"@vkontakte/videoplayer-shared/es2018";var Es=class extends Bi{constructor(e){super(e),this.textTracksManager.destroy()}subscribe(){super.subscribe();let e=!1,t=-1,{output:i,observableVideo:r,desiredState:s,connect:n}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canPlayLiveTailBuffer$.next(!0),n(r.timeUpdate$,i.liveBufferTime$),n(this.player.liveSeekableDuration$,i.duration$),n(this.player.liveLatency$,i.liveLatency$);let o=new yd(1);n(r.playbackRateState$,o),this.params.tuning.dashCmafLive.catchupLiveForMutedInactiveTab&&this.subscription.add(i.elementVisible$.pipe(xI()).subscribe(u=>{let l=i.position$.getValue(),c=i.volume$.getValue(),d=!c.volume||c.muted;!u&&!l&&d?e=!0:u&&e&&(this.seek(0),e=!1)})),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(s.isLowLatency.stateChangeEnded$.pipe(wI(u=>u.to)).subscribe(this.player.isLowLatency$)).add(vd({liveBufferTime:i.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(wI(({liveBufferTime:u,liveAvailabilityStartTime:l})=>u&&l?u+l:void 0)).subscribe(i.liveTime$)).add(this.player.liveStreamStatus$.pipe(EI(u=>t0(u))).subscribe(u=>i.isLiveEnded$.next(u!=="active"&&i.position$.getValue()===0))).add(vd({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:II(r.playbackRateState$,new yd(1))}).pipe(EI(({liveStreamStatus:u,liveDuration:l})=>u==="active"&&!!l)).subscribe(({liveDuration:u,playbackRate:l})=>{let c=i.liveBufferTime$.getValue(),d=i.position$.getValue(),{playbackCatchupSpeedup:f}=this.params.tuning.dashCmafLive.lowLatency;d||l<1-f||this.video.paused||Sd(c)||(t=u-c)})).add(vd({time:i.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:II(r.playbackRateState$,new yd(1))}).pipe(xI((u,l)=>this.player.liveStreamStatus$.getValue()==="active"?u.liveDuration===l.liveDuration:u.time===l.time)).subscribe(({time:u,liveDuration:l,playbackRate:c})=>{let d=i.position$.getValue(),{playbackCatchupSpeedup:f}=this.params.tuning.dashCmafLive.lowLatency;if(!d&&!this.video.paused&&c>=1-f||Sd(u)||Sd(l))return;let p=-1*(l-u-t);i.position$.next(Math.min(p,0))})).add(this.player.currentLiveTextRepresentation$.subscribe(u=>{if(u){let l=tI(u);this.params.output.availableTextTracks$.next([l])}}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,i=Math.trunc(t/1e3<=Math.abs(this.params.output.duration$.getValue())?t:0);this.player.seekLive(i).then(()=>{this.params.output.position$.next(e/1e3)})}};import{assertNever as P0,assertNonNullable as R0,debounce as k0,ErrorCategory as HI,filter as Vd,filterChanged as Xo,fromEvent as L0,isNonNullable as jI,isNullable as $0,map as _d,merge as Jo,observableFrom as Od,once as QI,Subscription as M0}from"@vkontakte/videoplayer-shared/es2018";var UI=O(Ae(),1),Cd=O(Oa(),1);import{abortable as Ld,assertNonNullable as qr,combine as Ur,ErrorCategory as dt,filter as zo,filterChanged as ks,flattenObject as Ls,fromEvent as Et,getTraceSubscriptionMethod as g0,interval as $d,isNonNullable as $s,isNullable as NI,map as Hr,merge as Ni,now as Md,Subject as ai,Subscription as Dd,tap as v0,throttle as qI,ValueSubject as se}from"@vkontakte/videoplayer-shared/es2018";var jo=O(Ae(),1),Fi=O(ot(),1),Qo=O(Oa(),1);var VI=O(Vn(),1);import{assertNever as i0,ErrorCategory as AI,Subject as PI}from"@vkontakte/videoplayer-shared/es2018";var r0=18,RI=!1;try{RI=F.browser.isSafari&&!!F.browser.safariVersion&&F.browser.safariVersion<=r0}catch(a){console.error(a)}var Td=class{constructor(e){this.bufferFull$=new PI;this.error$=new PI;this.queue=[];this.currentTask=null;this.destroyed=!1;this.abortRequested=!1;this.completeTask=()=>{var e;try{if(this.currentTask){let t=(e=this.currentTask.signal)==null?void 0:e.aborted;this.currentTask.callback(!t),this.currentTask=null}this.queue.length&&this.pull()}catch(t){this.error$.next({id:"BufferTaskQueueUnknown",category:AI.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:t})}};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)};RI&&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(){var r;if((this.buffer.updating||this.currentTask||this.destroyed)&&!this.abortRequested)return;let e=this.queue.shift();if(!e)return;if((r=e.signal)!=null&&r.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(s){s instanceof DOMException&&s.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):s instanceof DOMException&&s.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:AI.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:s}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){let{operation:t}=e;switch(t){case"append":this.buffer.appendBuffer(e.data);break;case"remove":this.buffer.remove(e.from/1e3,e.to/1e3);break;case"abort":this.buffer.abort();break;case"safariAbort":{this.buffer.abort(),this.buffer.appendBuffer(e.init);break}default:i0(t)}}},kI=Td;import{abortable as ri,assertNonNullable as Fe,ErrorCategory as _i,fromEvent as Ad,getExponentialDelay as Pd,isNonNullable as Or,isNullable as xe,now as Ho,once as u0,Subject as l0,Subscription as c0,ValueSubject as Oi}from"@vkontakte/videoplayer-shared/es2018";var Id=O(ot(),1);import{videoSizeToQuality as a0,throttleFn as s0}from"@vkontakte/videoplayer-shared/es2018";var LI=({id:a,width:e,height:t,bitrate:i,fps:r,quality:s,streamId:n})=>{var u;let o=(u=s?Kt(s):void 0)!=null?u:a0({width:e,height:t});return o&&{id:a,quality:o,bitrate:i,size:{width:e,height:t},fps:r,streamId:n}},$I=({id:a,bitrate:e})=>({id:a,bitrate:e}),MI=({language:a,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:a,label:e}),DI=({language:a,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:a,label:e}),Ed=({id:a,language:e,label:t,codecs:i,isDefault:r})=>({id:a,language:e,label:t,codec:(0,Id.default)(i.split("."),0),isDefault:r}),xd=({id:a,language:e,label:t,hdr:i,codecs:r})=>({id:a,language:e,hdr:i,label:t,codec:(0,Id.default)(r.split("."),0)}),wd=a=>"url"in a,Ge=a=>a.type==="template";var CI=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},Vi=(a,e)=>{for(let t of a)if(e(t))return t;return null},BI=a=>{let e=!1,t=s0(()=>{e=!0},a);return()=>{try{return t(),e}finally{e=!1}}};import{fromEvent as n0,Subscription as o0}from"@vkontakte/videoplayer-shared/es2018";var qo=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 Uo=class{constructor(e,t){this.lastUpdateTs=0;this.lastCallTs=0;this.prevRanges=[];this.subscription=new o0;this.mediaSource=e,this.sourceBuffer=t,this.subscription.add(n0(this.sourceBuffer,"updateend").subscribe(()=>this.updateend()))}updateend(){if(!N(this.mediaSource,this.sourceBuffer))return;let{prevRanges:e}=this,t=qo(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 xs=class{constructor(e,t,i,{fetcher:r,tuning:s,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new Oi(0);this.currentLowLatencySegmentLength$=new Oi(0);this.currentSegmentLength$=new Oi(0);this.onLastSegment$=new Oi(!1);this.fullyBuffered$=new Oi(!1);this.playingRepresentation$=new Oi(void 0);this.playingRepresentationInit$=new Oi(void 0);this.error$=new l0;this.gaps=[];this.subscription=new c0;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new Z;this.switchAbortController=new Z;this.destroyAbortController=new Z;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=ri(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);Fe(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new kI(this.sourceBuffer),this.sourceBufferBufferedDiff=new Uo(this.mediaSource,this.sourceBuffer),this.subscription.add(Ad(this.sourceBuffer,"updateend").subscribe(()=>{this.maintain()})),this.subscription.add(Ad(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:_i.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o||!N(this.mediaSource,this.sourceBuffer))return;let u=Math.min(this.bufferLimit,xr(this.sourceBuffer.buffered)*.8);this.bufferLimit=u;let l=be(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);Fe(i,"No init buffer for starting representation"),Fe(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=ri(this.destroyAbortController.signal,async function*(e,t=!1){if(!N(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);Fe(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if(xe(s)||xe(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),Fe(r,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!N(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();Or(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=ri(this.destroyAbortController.signal,async function*(e,t=!1){if(!N(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);Fe(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if(xe(s)||xe(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),Fe(r,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!N(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();Or(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=ri(this.destroyAbortController.signal,async function*(e){var u,l;let t=(u=(0,Qo.default)(e,c=>c.representations))!=null?u:[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let c of this.representations.keys()){let d=t.find(h=>h.id===c);d&&this.representations.set(c,d);let f=this.representations.get(c);if(!f||!Ge(f.segmentReference))return;let p=this.getActualLiveStartingSegments(f.segmentReference);this.segments.set(f.id,p)}let i=(l=this.switchingToRepresentationId)!=null?l:this.downloadingRepresentationId,r=this.representations.get(i);Fe(r);let s=this.segments.get(i);Fe(s,"No segments for starting representation");let n=this.initData.get(i);if(Fe(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));var c;this.fetcher=r,this.tuning=s,this.compatibilityMode=u,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=o,this.isLive=!!(l!=null&&l.live),this.baseUrls=(c=l==null?void 0:l.baseUrls)!=null?c:[],this.initData=new Map(i.map(d=>[d.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(i.map(d=>[d.id,d])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}switchToWithPreviousAbort(e,t=!1){!N(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new Z,ri(this.switchAbortController.signal,async function*(i,r=!1){this.switchingToRepresentationId=i;let s=this.representations.get(i);Fe(s,`No such representation ${i}`);let n=this.segments.get(i),o=this.initData.get(i);if(xe(o)||xe(n)?yield this.loadInit(s,"high",!1):o instanceof Promise&&(yield o),n=this.segments.get(i),Fe(n,"No segments for starting representation"),o=this.initData.get(i),!(!(o instanceof ArrayBuffer)||!this.sourceBuffer||!N(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();Or(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(){!xe(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 Z,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(xe(e)||xe(this.downloadingRepresentationId)||xe(this.playingRepresentationId)||xe(this.sourceBuffer)||!N(this.mediaSource,this.sourceBuffer)||Or(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if(Fe(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;let r=i.find(c=>e>=c.time.from&&e<c.time.to);Or(r)&&isFinite(r.time.from)&&isFinite(r.time.to)&&this.currentSegmentLength$.next((r==null?void 0:r.time.to)-r.time.from);let s=e,n=100;if(this.playingRepresentationId!==this.downloadingRepresentationId){let c=be(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)&&xr(this.sourceBuffer.buffered)>=this.bufferLimit){let c=be(this.sourceBuffer.buffered,e),d=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,c<d).catch(f=>{this.handleAsyncError(f,"pruneBuffer")});return}let u=null;if(!this.activeSegments.size&&(u=this.selectForwardBufferSegments(i,t.segmentReference.type,s),u!=null&&u.length)){let c="auto";if(this.tuning.dash.useFetchPriorityHints&&r)if((0,jo.default)(u,r))c="high";else{let d=(0,Fi.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!=null&&u.length)&&be(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let l=(0,Fi.default)(i,-1);!this.isLive&&l&&(this.fullyBuffered$.next(l.time.to-e-be(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;Or(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,Qo.default)(e==null?void 0: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!=null&&i.length)return{from:i[0].time.from,to:i[i.length-1].time.to}}updateLive(e){var i,r,s,n;let t=(i=(0,Qo.default)(e==null?void 0:e.streams[this.kind],o=>o.representations))!=null?i:[];if(![...this.segments.values()].every(o=>!o.length))for(let o of t){if(!o||!Ge(o.segmentReference))return;let u=o.segmentReference.segments.map(p=>({...p,status:"none",size:void 0})),l=100,c=(r=this.segments.get(o.id))!=null?r:[],d=(n=(s=(0,Fi.default)(c,-1))==null?void 0:s.time.to)!=null?n:0,f=u==null?void 0:u.findIndex(p=>d>=p.time.from+l&&d<=p.time.to+l);if(f===-1){this.liveUpdateSegmentIndex=0;let p=this.getActualLiveStartingSegments(o.segmentReference);this.segments.set(o.id,p)}else{let p=u.slice(f+1);this.segments.set(o.id,[...c,...p])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;Fe(e);let t=this.segments.get(e);if(t!=null&&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(!Ge(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=lt(r.segmentTemplateUrl,{segmentTime:u});s.push({status:"none",time:{from:e.time.to,to:1/0},url:l})}}this.currentLowLatencySegmentLength$.next(t)}findSegmentStartTime(e){var s,n,o;let t=(n=(s=this.switchingToRepresentationId)!=null?s:this.downloadingRepresentationId)!=null?n:this.playingRepresentationId;if(!t)return;let i=this.segments.get(t);if(!i)return;let r=i.find(u=>u.time.from<=e&&u.time.to>=e);return(o=r==null?void 0:r.time.from)!=null?o:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){var e,t;if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),(e=this.sourceBufferTaskQueue)==null||e.destroy(),(t=this.sourceBufferBufferedDiff)==null||t.destroy(),this.gapDetectionIdleCallback&&yt&&yt(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&yt&&yt(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer)try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(i){if(!(i instanceof DOMException&&i.name==="NotFoundError"))throw i}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:f,time:{from:p,to:h}},m)=>{let v=p<=i&&h>=i,b=p>i||v||m===0&&i===0,S=Math.min(this.forwardBufferTarget,this.bufferLimit),T=this.preloadOnly&&p<=i+S||r<S&&h-p>=S||h<=i+S;return(f==="none"||f==="partially_ejected"&&b&&T&&this.sourceBuffer&&N(this.mediaSource,this.sourceBuffer)&&!(Ie(this.sourceBuffer.buffered,p)&&Ie(this.sourceBuffer.buffered,h)))&&b&&T});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 f=s;f<n.length&&(o<=c||u<=d);f++){let p=n[f];if(o+=p.byte.to+1-p.byte.from,u+=p.time.to+1-p.time.from,p.status==="none"||p.status==="partially_ejected")l.push(p);else break}return l}async loadSegments(e,t,i="auto"){Ge(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 ri(o,async function*(){let c=Pd(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(),bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation});if(this.lastDataObtainedTimestampMs=Ho(),!c)return;let d=new DataView(c),f=Tt(t.mime);if(!isFinite(r.segment.time.to)){let m=t.segmentReference.timescale;r.segment.time.to=f.getChunkEndTime(d,m)}u&&r.feedingBytes&&l?await Promise.all(l):await this.sourceBufferTaskQueue.append(d,o);let{serverDataReceivedTimestamp:p,serverDataPreparedTime:h}=f.getServerLatencyTimestamps(d);p&&h&&this.currentLiveSegmentServerLatency$.next(h-p),r.segment.status="downloaded",this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(c){this.abortActiveSegments([e]),It(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())Ge(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 ri(n,async function*(){let u=Pd(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),Ad(window,"online").pipe(u0()).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,bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation}),this.lastDataObtainedTimestampMs=Ho(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),It(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}prepareByteRangeFetchSegmentParams(e,t){if(Ge(t.segmentReference))throw new Error("Representation is not byte range type");let i=t.segmentReference.url,r={from:(0,Fi.default)(e,0).byte.from,to:(0,Fi.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=Ho(),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:_i.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!Ge(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=Ho();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:_i.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,jo.default)(e,t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:r,signal:s}){if(!this.activeSegments.size||!N(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=Tt(n.mime).parseFeedableSegmentChunk(l,this.isLive);c!=null&&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||!N(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,f=d-c+1,p=c<r,h=d<=r;if(p){if(l.status==="downloading"&&h){l.status="downloaded";let m=new DataView(e.buffer,e.byteOffset+c,f);await this.sourceBufferTaskQueue.append(m,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(f,r-c),u.loadedBytes>u.feedingBytes)){let m=new DataView(e.buffer,e.byteOffset+c+u.feedingBytes,u.loadedBytes-u.feedingBytes),v=u.loadedBytes===f?m:Tt(o.mime).parseFeedableSegmentChunk(m);v!=null&&v.byteLength&&(l.status="partially_fed",u.feedingBytes+=v.byteLength,await this.sourceBufferTaskQueue.append(v,s)&&!s.aborted?(u.fedBytes+=v.byteLength,u.fedBytes===f&&this.onSegmentFullyAppended(u,t)):await n())}}}}onSegmentFullyAppended(e,t){if(!(xe(this.sourceBuffer)||!N(this.mediaSource,this.sourceBuffer))){!this.isLive&&F.browser.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(Ie(this.sourceBuffer.buffered,e.segment.time.from,100)&&Ie(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:_i.VIDEO_PIPELINE,message:"Browser stuck on empty result of adding segment to source buffer"})),this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status="fed",wd(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||(t=n),s===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let i=this.representations.get(e);i&&(this.initLoadIdleCallback=Er(()=>(0,VI.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?ri(this.destroyAbortController.signal,async function*(){let o=Pd(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,Tt(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 f=c;this.isLive&&Ge(e.segmentReference)&&(f=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,f),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:_i.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||!N(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||xe(e))return!1;this.checkEjectedSegments();let r=[],s=0,n=o=>{var l;if(s>=t)return;r.push({...o.time});let u=wd(o)?(l=o.size)!=null?l: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 f of d)(0,jo.default)(["none","partially_ejected"],f.status)&&Math.round(f.time.from)<=Math.round(u)&&Math.round(f.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=CI(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||!N(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||!N(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||!N(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||!N(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||xe(e)?0:be(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!this.sourceBuffer||!N(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||!N(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=Er(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:_i.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if(xe(this.sourceBuffer)||!N(this.mediaSource,this.sourceBuffer)||xe(this.playingRepresentationId)||this.sourceBufferBufferedDiff&&!this.sourceBufferBufferedDiff.wasUpdated())return;let e=qo(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],f=e[c+1];u||(u=d-t<=n&&f+t>=o),(n>=d&&n<f-t||o>d+t&&o<=f)&&(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:_i.VIDEO_PIPELINE,thrown:e,message:"Something went wrong"})}calculateDurationFromSegments(){var t;if(!this.playingRepresentationId)return 0;let e=this.segments.get(this.playingRepresentationId);return(e?(t=(0,Fi.default)(e,-1))==null?void 0:t.time.to:0)||0}};import{abortable as ws,assertNever as _I,fromEvent as OI,merge as d0,now as As,Subject as Fr,ValueSubject as Rd,flattenObject as Nr,ErrorCategory as Ps,SubscriptionRemovable as p0}from"@vkontakte/videoplayer-shared/es2018";var Go=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:s=!1}){this.manifestRequested=new Fr;this.manifestReceived=new Fr;this.firstBytesRequested=new Fr;this.firstBytesReceived=new Fr;this.lastConnectionType$=new Rd(void 0);this.lastConnectionReused$=new Rd(void 0);this.lastRequestFirstBytes$=new Rd(void 0);this.recoverableError$=new Fr;this.error$=new Fr;this.abortAllController=new Z;this.subscription=new p0;this.fetchManifest=ws(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=ei(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=yo(i)),this.manifestRequested.next();let r=yield this.doFetch(i,{signal:this.abortAllController.signal}).catch(Wo);return r?(t.log("success",Nr({url:i,message:"Request successfully executed"})),t.end(),this.manifestReceived.next(),this.onHeadersReceived(r.headers),r.text()):(t.error("error",Nr({url:i,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=ws(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,bufferOptimisation:l=!1}={}){var _,K,J;let c=e,d=new Headers,f=this.tracer.createComponentTracer("Fetch");if(i)switch(t){case 0:{d.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let I=new URL(c,location.href);I.searchParams.append("bytes",`${i.from}-${i.to}`),c=I.toString();break}default:_I(t)}this.requestQuic&&(c=ei(c));let p=this.abortAllController.signal,h;if(n){let I=new Z;if(h=d0(OI(this.abortAllController.signal,"abort"),OI(n,"abort")).subscribe(()=>{try{I.abort()}catch(R){Wo(R)}}),this.subscription.add(h),this.abortAllController.signal.aborted||n.aborted)try{I.abort()}catch(R){Wo(R)}p=I.signal}let m=0,v=As();f.log("startRequest",Nr({url:c,priority:s,rangeMethod:t,range:i,isLowLatency:u,requestStartedAt:v})),this.firstBytesRequested.next();let b=yield this.doFetch(c,{priority:s,headers:d,signal:p}),S=As();if(!b)return f.error("error",{message:"No response in request"}),f.end(),this.unsubscribeAbortSubscription(h),null;if((_=this.throughputEstimator)==null||_.addRawRtt(S-v),!b.ok||!b.body){this.unsubscribeAbortSubscription(h);let I=`Fetch error ${b.status}: ${b.statusText}`;return f.error("error",{message:I}),f.end(),Promise.reject(new Error(`Fetch error ${b.status}: ${b.statusText}`))}if(this.onHeadersReceived(b.headers),!r&&!o){this.unsubscribeAbortSubscription(h);let I=As(),R={requestStartedAt:v,requestEndedAt:I,duration:I-v};return f.log("endRequest",Nr(R)),f.end(),b.arrayBuffer()}let T=b.body;if(o){let I;[T,I]=b.body.tee(),(K=this.throughputEstimator)==null||K.trackStream(I,u)}let y=T.getReader(),E,k=parseInt((J=b.headers.get("content-length"))!=null?J:"",10);Number.isFinite(k)&&(E=k),!E&&i&&(E=i.to-i.from+1);let M=E?new Uint8Array(E):new Uint8Array(0),$=!1,A=I=>{this.unsubscribeAbortSubscription(h),$=!0,Wo(I)},P=ws(p,async function*({done:I,value:R}){if(m===0&&(this.lastRequestFirstBytes$.next(As()-v),this.firstBytesReceived.next()),p.aborted){this.unsubscribeAbortSubscription(h);return}if(!I&&R){if(l&&E)M.set(R,m),m+=R.byteLength;else{let x=new Uint8Array(M.length+R.length);x.set(M),x.set(R,M.length),M=x,m+=R.byteLength}r==null||r(new DataView(M.buffer),m),yield y==null?void 0:y.read().then(P,A)}}.bind(this));yield y==null?void 0:y.read().then(P,A),this.unsubscribeAbortSubscription(h);let V=As(),D={failed:$,requestStartedAt:v,requestEndedAt:V,duration:V-v};return $?(f.error("endRequest",Nr(D)),f.end(),null):(f.log("endRequest",Nr(D)),f.end(),M.buffer)}.bind(this));this.fetchByteRangeRepresentation=ws(this.abortAllController.signal,async function*(e,t,i){var b;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 f=new DataView(d,r-n,s-n+1);if(!t.validateData(f))throw new Error("Invalid media file");let p=t.parseInit(f),h=(b=e.indexRange)!=null?b:t.getIndexRange(p);if(!h)throw new ReferenceError("No way to load representation index");let m;if(u)m=new DataView(d,h.from-n,h.to-h.from+1);else{let S=yield this.fetch(e.url,{range:h,priority:i,measureThroughput:!1});if(!S)return null;m=new DataView(S)}let v=t.parseSegments(m,p,h);return{init:p,dataView:new DataView(d),segments:v}}.bind(this));this.fetchTemplateRepresentation=ws(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}=So(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}async fetchRepresentation(e,t,i="auto"){var s,n;let{type:r}=e;switch(r){case"byteRange":return(s=await this.fetchByteRangeRepresentation(e,t,i))!=null?s:null;case"template":return(n=await this.fetchTemplateRepresentation(e,i))!=null?n:null;default:_I(r)}}destroy(){this.abortAllController.abort(),this.tracer.end(),this.subscription.unsubscribe()}async doFetch(e,t){let i=await Ze(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:Ps.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:Ps.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:Ps.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:Ps.FATAL});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${s})`,category:Ps.FATAL})}}unsubscribeAbortSubscription(e){e&&(e.unsubscribe(),this.subscription.remove(e))}},Wo=a=>{if(!It(a))throw a};import{isNullable as h0,ValueSubject as f0}from"@vkontakte/videoplayer-shared/es2018";var Rs=class a{constructor(e,t){this.currentRepresentation$=new f0(null);this.maxRepresentations=4;this.representationsCursor=0;this.representations=[];this.currentSegment=null;this.getCurrentPosition=t.getCurrentPosition,this.processStreams(e)}updateLive(e){this.processStreams(e==null?void 0:e.streams.text)}seekLive(e){this.processStreams(e)}maintain(e=this.getCurrentPosition()){var t;if(!h0(e))for(let i of this.representations)for(let r of i){let s=r.segmentReference,n=s.segments.length,o=s.segments[0].time.from,u=s.segments[n-1].time.to;if(e<o||e>u)continue;let l=s.segments.find(c=>c.time.from<=e&&c.time.to>=e);!l||((t=this.currentSegment)==null?void 0:t.time.from)===l.time.from&&this.currentSegment.time.to===l.time.to||(this.currentSegment=l,this.currentRepresentation$.next({...r,label:"Live Text",language:"ru",isAuto:!0,url:new URL(l.url,s.baseUrl).toString()}))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e!=null?e:[]){let 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!=null&&e.some(t=>a.filterRepresentations(t.representations)))}static filterRepresentations(e){return e==null?void 0:e.filter(t=>t.kind==="text"&&"segmentReference"in t&&Ge(t.segmentReference))}};var S0=["progress","play","seeked","stalled","waiting"],y0=["timeupdate","progress","loadeddata","playing","seeked"];var Yo=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.bufferManagers=[];this.subscription=new Dd;this.representationSubscription=new Dd;this.state$=new H("none");this.currentVideoRepresentation$=new se(void 0);this.currentVideoRepresentationInit$=new se(void 0);this.currentAudioRepresentation$=new se(void 0);this.currentVideoSegmentLength$=new se(0);this.currentAudioSegmentLength$=new se(0);this.error$=new ai;this.manifestRequested=new ai;this.manifestReceived=new ai;this.firstBytesRequested=new ai;this.firstBytesReceived=new ai;this.lastConnectionType$=new se(void 0);this.lastConnectionReused$=new se(void 0);this.lastRequestFirstBytes$=new se(void 0);this.currentLiveTextRepresentation$=new se(null);this.isLive$=new se(!1);this.isActiveLive$=new se(!1);this.isLowLatency$=new se(!1);this.liveDuration$=new se(0);this.liveSeekableDuration$=new se(0);this.liveAvailabilityStartTime$=new se(0);this.liveStreamStatus$=new se(void 0);this.bufferLength$=new se(0);this.liveLatency$=new se(void 0);this.liveLoadBufferLength$=new se(0);this.livePositionFromPlayer$=new se(0);this.currentStallDuration$=new se(0);this.videoLastDataObtainedTimestamp$=new se(0);this.fetcherRecoverableError$=new ai;this.fetcherError$=new ai;this.liveStreamEndTimestamp=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.forceEnded$=new ai;this.gapWatchdogActive=!1;this.destroyController=new Z;this.initManifest=Ld(this.destroyController.signal,async function*(e,t,i){var r;this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=le(t,i,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),(r=this.manifest)!=null&&r.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:dt.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=Ld(this.destroyController.signal,async function*(){var u,l;this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(c=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:dt.NETWORK,message:"Failed to load manifest",thrown:c})});if(!e)return null;let t=null;try{t=mo(e!=null?e:"",this.manifestUrlString)}catch(c){let d=(u=ho(e))!=null?u:{id:"ManifestParsing",category:dt.PARSER,message:"Failed to parse MPD manifest",thrown:c};this.error$.next(d)}if(!t)return null;let i=(c,d,f)=>{var p,h,m,v;return!!((h=(p=this.element)==null?void 0:p.canPlayType)!=null&&h.call(p,d)&&((v=(m=Qe())==null?void 0:m.isTypeSupported)!=null&&v.call(m,`${d}; codecs="${f}"`))||c==="text")};if(t.live){this.isLive$.next(!!t.live);let{availabilityStartTime:c,latestSegmentPublishTime:d,streamIsUnpublished:f,streamIsAlive:p}=t.live,h=((l=t.duration)!=null?l:0)/1e3;this.liveSeekableDuration$.next(-1*h),this.liveDuration$.next((d-c)/1e3),this.liveAvailabilityStartTime$.next(t.live.availabilityStartTime);let m="active";p||(m=f?"unpublished":"unexpectedly_down"),this.liveStreamStatus$.next(m)}let r={text:t.streams.text,video:[],audio:[]},s,n;for(let c of["video","audio"]){let f=t.streams[c].filter(({mime:h,codecs:m})=>i(c,h,m));r[c]=f;let p;if(this.tuning.dash.codecsPrioritizeEnabled){let h=f.map(({codecs:m})=>m);c==="audio"&&(n=$o(h),p=n[0]),c==="video"&&(s=Lo(h),this.forceVideoCodec&&(0,UI.default)(s,this.forceVideoCodec)?p=this.forceVideoCodec:p=s[0]),p&&(r[c]=f.filter(({codecs:m})=>Dr(m)===p))}else{let h=new Set(f.map(({codecs:m})=>m));p=ko(h),p&&(r[c]=f.filter(({codecs:m})=>m.startsWith(p)))}if(c==="video"){let h=this.tuning.preferHDR,m=r.video.some(b=>b.hdr),v=r.video.some(b=>!b.hdr);F.display.isHDR&&h&&m?r.video=r.video.filter(b=>b.hdr):v&&(r.video=r.video.filter(b=>!b.hdr))}}let o={...t,streams:r};return this.tuning.dash.codecsPrioritizeEnabled&&(o.codecs={video:s,audio:n}),this.tracer.log("updateManifestEnd",Ls(o)),o}.bind(this));this.initRepresentations=Ld(this.destroyController.signal,async function*(e,t,i){var f;this.tracer.log("initRepresentationsStart",Ls({initialVideo:e,initialAudio:t,sourceHls:i})),qr(this.manifest),qr(this.element),this.representationSubscription.unsubscribe(),this.representationSubscription=new Dd,this.state$.startTransitionTo("representations_ready");let r=p=>{this.representationSubscription.add(Et(p,"error").pipe(zo(h=>{var m;return!!((m=this.element)!=null&&m.played.length)})).subscribe(h=>{this.error$.next({id:"VideoSource",category:dt.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:h})}))};this.source=qn();let s=document.createElement("source");if(r(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),pr())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 xs("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],$s(t)){let p=this.manifest.streams.audio.reduce((h,m)=>[...h,...m.representations],[]);this.audioBufferManager=new xs("audio",this.source,p,n),this.bufferManagers.push(this.audioBufferManager)}Rs.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new Rs(this.manifest.streams.text,n)),this.representationSubscription.add(this.fetcher.manifestRequested.subscribe(this.manifestRequested)),this.representationSubscription.add(this.fetcher.manifestReceived.subscribe(this.manifestReceived)),this.representationSubscription.add(this.fetcher.firstBytesRequested.subscribe(this.firstBytesRequested)),this.representationSubscription.add(this.fetcher.firstBytesReceived.subscribe(this.firstBytesReceived)),this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$));let u=()=>{var p;(p=this.stallWatchdogSubscription)==null||p.unsubscribe(),this.currentStallDuration$.next(0)};if(this.representationSubscription.add(Ni(...y0.map(p=>Et(this.element,p))).pipe(Hr(p=>this.element?be(this.element.buffered,this.element.currentTime*1e3):0),ks(),v0(p=>{p>this.tuning.dash.bufferEmptinessTolerance&&u()})).subscribe(this.bufferLength$)),this.representationSubscription.add(Ni(Et(this.element,"ended"),this.forceEnded$).subscribe(()=>{u()})),this.isLive$.getValue()){this.subscription.add(this.liveDuration$.pipe(ks()).subscribe(h=>this.liveStreamEndTimestamp=Md())),this.subscription.add(Et(this.element,"pause").subscribe(()=>{this.livePauseWatchdogSubscription=$d(1e3).subscribe(h=>{let m=zt(this.manifestUrlString,2);this.manifestUrlString=le(this.manifestUrlString,m+1e3,2),this.liveStreamStatus$.getValue()==="active"&&this.updateManifest()}),this.subscription.add(this.livePauseWatchdogSubscription)})).add(Et(this.element,"play").subscribe(h=>{var m;return(m=this.livePauseWatchdogSubscription)==null?void 0:m.unsubscribe()})),this.representationSubscription.add(Ur({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(Hr(({isActiveLive:h,isLowLatency:m})=>h&&m),ks()).subscribe(h=>{this.isManualDecreasePlaybackInLive()||Mr(this.element,1)})),this.representationSubscription.add(Ur({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(zo(({bufferLength:h,isActiveLive:m,isLowLatency:v})=>m&&v&&!!h)).subscribe(({bufferLength:h})=>this.liveBuffer.next(h))),this.representationSubscription.add(this.videoBufferManager.currentLowLatencySegmentLength$.subscribe(h=>{if(!this.isActiveLive$.getValue()&&!this.isLowLatency$.getValue()&&!h)return;let m=this.liveSeekableDuration$.getValue()-h/1e3;this.liveSeekableDuration$.next(Math.max(m,-1*this.tuning.dashCmafLive.maxLiveDuration)),this.liveDuration$.next(this.liveDuration$.getValue()+h/1e3)})),this.representationSubscription.add(Ur({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe(zo(({isLive:h})=>h),ks((h,m)=>m.bufferLength<h.bufferLength),Hr(({rtt:h,bufferLength:m,segmentServerLatency:v})=>{let b=zt(this.manifestUrlString,2);return(h/2+m+v+b)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add(Ur({liveBuffer:this.liveBuffer.smoothed$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).subscribe(({liveBuffer:h,isActiveLive:m,isLowLatency:v})=>{if(!v||!m)return;let b=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,S=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,T=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,y=h-b;if(this.isManualDecreasePlaybackInLive())return;let E=1;Math.abs(y)>S&&(E=1+Math.sign(y)*T),Mr(this.element,E)})),this.representationSubscription.add(this.bufferLength$.subscribe(h=>{var v,b;let m=0;if(h){let S=((b=(v=this.element)==null?void 0:v.currentTime)!=null?b:0)*1e3;m=Math.min(...this.bufferManagers.map(y=>{var E,k;return(k=(E=y.getLiveSegmentsToLoadState(this.manifest))==null?void 0:E.to)!=null?k:S}))-S}this.liveLoadBufferLength$.getValue()!==m&&this.liveLoadBufferLength$.next(m)}));let p=0;this.representationSubscription.add(Ur({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(qI(1e3)).subscribe(async({liveLoadBufferLength:h,bufferLength:m})=>{if(!this.element||this.isUpdatingLive)return;let v=this.element.playbackRate,b=zt(this.manifestUrlString,2),S=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,T=Math.min(S,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*v),y=this.tuning.dashCmafLive.normalizedActualBufferOffset*v,E=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*v,k=isFinite(h)?h:m,M=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),$=S<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next($);let A="none";if(M?A="active_low_latency":this.isLowLatency$.getValue()&&$?(this.bufferManagers.forEach(P=>P.proceedLowLatencyLive()),A="active_low_latency"):b!==0&&k<T?A="live_forward_buffering":k<T+E&&(A="live_with_target_offset"),isFinite(h)&&(p=h>p?h:p),A==="live_forward_buffering"||A==="live_with_target_offset"){let P=p-(T+y),V=this.normolizeLiveOffset(Math.trunc(b+P/v)),D=Math.abs(V-b),_=0;!h||D<=this.tuning.dashCmafLive.offsetCalculationError?_=b:V>0&&D>this.tuning.dashCmafLive.offsetCalculationError&&(_=V),this.manifestUrlString=le(this.manifestUrlString,_,2)}(A==="live_with_target_offset"||A==="live_forward_buffering")&&(p=0,await this.updateLive())},h=>{this.error$.next({id:"updateLive",category:dt.VIDEO_PIPELINE,thrown:h,message:"Failed to update live with subscription"})}))}let l=Ni(...this.bufferManagers.map(p=>p.fullyBuffered$)).pipe(Hr(()=>this.bufferManagers.every(p=>p.fullyBuffered$.getValue()))),c=Ni(...this.bufferManagers.map(p=>p.onLastSegment$)).pipe(Hr(()=>this.bufferManagers.some(p=>p.onLastSegment$.getValue()))),d=Ur({allBuffersFull:l,someBufferEnded:c}).pipe(ks(),Hr(({allBuffersFull:p,someBufferEnded:h})=>p&&h),zo(p=>p));if(this.representationSubscription.add(Ni(this.forceEnded$,d).subscribe(()=>{var p;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(h=>!h.updating))try{(p=this.source)==null||p.endOfStream()}catch(h){this.error$.next({id:"EndOfStream",category:dt.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:h})}})),this.representationSubscription.add(Ni(...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=>{var m;p&&(this.timeoutSourceOpenId=setTimeout(()=>{var v;if(((v=this.source)==null?void 0:v.readyState)==="open"){h();return}this.error$.next({id:"OpenOfStream",category:dt.VIDEO_PIPELINE,message:"Failed to open MediaSource",thrown:new Error("Timeout reject when wait sourceopen event"),traceAsLog:!0})},this.tuning.dash.sourceOpenTimeout)),(m=this.source)==null||m.addEventListener("sourceopen",()=>{this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),h()},{once:!0})})}if(!this.isLive$.getValue()){let p=[(f=this.manifest.duration)!=null?f:0,...(0,Cd.default)((0,Cd.default)([...this.manifest.streams.audio,...this.manifest.streams.video],h=>h.representations),h=>{let m=[];return h.duration&&m.push(h.duration),Ge(h.segmentReference)&&h.segmentReference.totalSegmentsDurationMs&&m.push(h.segmentReference.totalSegmentsDurationMs),m})];this.source.duration=Math.max(...p)/1e3}this.audioBufferManager&&$s(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState("representations_ready"),this.tracer.log("initRepresentationsEnd")}.bind(this));this.tick=()=>{var t,i,r,s;if(!this.element||!this.videoBufferManager||((t=this.source)==null?void 0:t.readyState)!=="open")return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),(i=this.audioBufferManager)==null||i.maintain(e),(r=this.liveTextManager)==null||r.maintain(e),(this.videoBufferManager.gaps.length||(s=this.audioBufferManager)!=null&&s.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=$d(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),n=>{this.error$.next({id:"GapWatchdog",category:dt.WTF,message:"Error handling gaps",thrown:n})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name),this.forceVideoCodec=e.forceVideoCodec,this.fetcher=new Go({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=Ct.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.bufferEstimator}),this.initTracerSubscription()}async seekLive(e){var r,s,n;qr(this.element);let t=this.liveStreamStatus$.getValue()!=="active"?Md()-this.liveStreamEndTimestamp:0,i=this.normolizeLiveOffset(e+t);this.isActiveLive$.next(i===0),this.manifestUrlString=le(this.manifestUrlString,i,2),this.manifest=await this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,await((r=this.videoBufferManager)==null?void 0:r.seekLive(this.manifest.streams.video)),await((s=this.audioBufferManager)==null?void 0:s.seekLive(this.manifest.streams.audio)),(n=this.liveTextManager)==null||n.seekLive(this.manifest.streams.text))}initBuffer(){qr(this.element),this.state$.setState("running");let e=Et(this.element,"timeupdate");this.tuning.dash.timeupdateEventTickThrottle&&(e=e.pipe(qI(this.tuning.dash.timeupdateEventTickThrottle))),this.subscription.add(Ni(...S0.map(t=>Et(this.element,t)),Et(window,"online"),e).subscribe(()=>this.tick(),t=>{this.error$.next({id:"DashVKPlayer",category:dt.WTF,message:"Internal logic error",thrown:t})})),this.subscription.add(Et(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(Et(this.element,"waiting").subscribe(()=>{var i;this.element&&this.element.readyState===HTMLMediaElement.HAVE_CURRENT_DATA&&!this.element.seeking&&Ie(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let t=()=>{var h,m,v,b,S,T,y,E,k,M,$;if(!this.element||((h=this.source)==null?void 0:h.readyState)!=="open")return;let r=this.currentStallDuration$.getValue();r+=50,this.currentStallDuration$.next(r);let s={timeInWaiting:r},n=Md(),o=100,u=(v=(m=this.videoBufferManager)==null?void 0:m.lastDataObtainedTimestamp)!=null?v:0;this.videoLastDataObtainedTimestamp$.next(u);let l=(S=(b=this.audioBufferManager)==null?void 0:b.lastDataObtainedTimestamp)!=null?S:0,c=(y=(T=this.videoBufferManager)==null?void 0:T.getForwardBufferDuration())!=null?y:0,d=(k=(E=this.audioBufferManager)==null?void 0:E.getForwardBufferDuration())!=null?k:0,f=c<o&&n-u>this.tuning.dash.crashOnStallTWithoutDataTimeout,p=this.audioBufferManager&&d<o&&n-l>this.tuning.dash.crashOnStallTWithoutDataTimeout;if((f||p)&&r>this.tuning.dash.crashOnStallTWithoutDataTimeout||r>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${r} ms`);if(this.isLive$.getValue()&&r%2e3===0){let A=this.normolizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);this.seekLive(A).catch(P=>{this.error$.next({id:"stallIntervalCallback",category:dt.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:P})}),s.liveLastOffset=A}else{let A=this.element.currentTime*1e3;(M=this.videoBufferManager)==null||M.maintain(A),($=this.audioBufferManager)==null||$.maintain(A),s.position=A}this.tracer.log("stallIntervalCallback",Ls(s))};(i=this.stallWatchdogSubscription)==null||i.unsubscribe(),this.stallWatchdogSubscription=$d(50).subscribe(t,r=>{this.error$.next({id:"StallWatchdogCallback",category:dt.NETWORK,message:"Can't restore DASH after stall.",thrown:r})}),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==null?void 0:r.switchToWithPreviousAbort(t,i):r==null?void 0:r.switchTo(t,i):r==null?void 0:r.switchToOld(t,i)}async seek(e,t){var r,s,n,o,u;qr(this.element),qr(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((r=this.videoBufferManager.findSegmentStartTime(e))!=null?r:e,(n=(s=this.audioBufferManager)==null?void 0:s.findSegmentStartTime(e))!=null?n:e),this.warmUpMediaSourceIfNeeded(i),Ie(this.element.buffered,i)||await Promise.all([this.videoBufferManager.abort(),(o=this.audioBufferManager)==null?void 0:o.abort()]),!(NI(this.element)||NI(this.videoBufferManager))&&(this.videoBufferManager.maintain(i),(u=this.audioBufferManager)==null||u.maintain(i),this.element.currentTime=i/1e3,this.tracer.log("seek",Ls({requestedPosition:e,forcePrecise:t,position:i})))}warmUpMediaSourceIfNeeded(e=(t=>(t=this.element)==null?void 0:t.currentTime)()){var i;$s(this.element)&&$s(this.source)&&$s(e)&&((i=this.source)==null?void 0:i.readyState)==="ended"&&this.element.duration*1e3-e>this.tuning.dash.seekBiasInTheEnd&&this.bufferManagers.forEach(r=>r.warmUpMediaSource())}get isStreamEnded(){var e;return((e=this.source)==null?void 0:e.readyState)==="ended"}stop(){var e,t,i;this.tracer.log("stop"),(e=this.element)==null||e.querySelectorAll("source").forEach(r=>{URL.revokeObjectURL(r.src),r.remove()}),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),(t=this.videoBufferManager)==null||t.destroy(),this.videoBufferManager=null,(i=this.audioBufferManager)==null||i.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getStreams(){var e;return(e=this.manifest)==null?void 0:e.streams}getCodecs(){var e;return(e=this.manifest)==null?void 0:e.codecs}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){var e;this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),((e=this.source)==null?void 0:e.readyState)==="open"&&Array.from(this.source.sourceBuffers).every(t=>!t.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}initTracerSubscription(){let e=g0(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(){var e;this.isUpdatingLive=!0,this.manifest=await this.updateManifest(),this.manifest&&(this.bufferManagers.forEach(t=>t.updateLive(this.manifest)),(e=this.liveTextManager)==null||e.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(){var e,t;return Math.max(((e=this.videoBufferManager)==null?void 0:e.calculateDurationFromSegments())||0,((t=this.audioBufferManager)==null?void 0:t.calculateDurationFromSegments())||0)}};import{combine as T0,map as I0,observeElementSize as E0,Subscription as x0,ValueSubject as Bd,noop as w0}from"@vkontakte/videoplayer-shared/es2018";var Ko=class{constructor(){this.subscription=new x0;this.pipSize$=new Bd(void 0);this.videoSize$=new Bd(void 0);this.elementSize$=new Bd(void 0);this.pictureInPictureWindowRemoveEventListener=w0}connect({observableVideo:e,video:t}){let i=r=>{let s=r.target;this.pipSize$.next({width:s.width,height:s.height})};this.subscription.add(E0(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(T0({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe(I0(({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 qi=class{constructor(e){this.subscription=new M0;this.videoState=new H("stopped");this.observableVideo=null;this.droppedFramesManager=new Tr;this.stallsManager=new _o;this.elementSizeManager=new Ko;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new Xt;this.audioTrackSwitchHistory=new Xt;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==null?void 0: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"),L(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"),L(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="ready"&&L(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==null?void 0:i.to)==="playing"&&L(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&L(this.params.desiredState.playbackState,"paused");return;default:return P0(e)}}};this.init3DScene=e=>{var i,r,s;if(this.scene3D)return;this.scene3D=new _r(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:((i=e.projectionData)==null?void 0:i.pose.yaw)||0,y:((r=e.projectionData)==null?void 0:r.pose.pitch)||0,z:((s=e.projectionData)==null?void 0:s.pose.roll)||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});let t=this.elementSizeManager.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};this.textTracksManager=new Xe(e.source.url),this.params=e,this.video=De(e.container,e.tuning),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Te(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 Yo({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode,tracer:this.tracer,forceVideoCodec:this.params.forceVideoCodec}),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params;$0(this.observableVideo)&&(this.observableVideo=Ve(this.video),this.subscription.add(()=>{var n;return(n=this.observableVideo)==null?void 0:n.destroy()}));let i=this.constructor.name,r=n=>{e.error$.next({id:i,category:HI.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(Vd(d=>!!d.length),QI()).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(_d(d=>d.to.state!=="none"),Xo());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(Vd(jI),QI()),e.firstBytesEvent$),s(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),s(this.videoState.stateChangeEnded$.pipe(_d(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(bt(this.video,t.isLooped,r)),this.subscription.add(Be(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Ke(this.video,t.playbackRate,i.playbackRateState$,r)),this.elementSizeManager.connect({video:this.video,observableVideo:i}),s(Je(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),L(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),L(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.params.tuning.changePlaybackStateToPausedWhenEnded&&this.subscription.add(i.ended$.subscribe(()=>{this.videoState.setState("paused"),L(t.playbackState,"paused")})),this.subscription.add(this.player.manifestRequested.subscribe(this.params.output.manifestRequested$)).add(this.player.manifestReceived.subscribe(this.params.output.manifestReceived$)).add(this.player.firstBytesRequested.subscribe(this.params.output.firstBytesRequested$)).add(this.player.firstBytesReceived.subscribe(this.params.output.firstBytesReceived$)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:d})=>{if(d==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let f=this.player.getStreams(),p=this.player.getCodecs();if(R0(f,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let m=[];for(let v of f.audio){m.push(Ed(v));let b=[];for(let S of v.representations){let T=$I(S);b.push(T),this.audioTracksMap.set(T,{stream:v,representation:S})}this.audioStreamsMap.set(v,b)}this.params.output.availableAudioStreams$.next(m)}let h=[];for(let m of f.video){h.push(xd(m));let v=[];for(let b of m.representations){let S=LI({...b,streamId:m.id});S&&(v.push(S),this.videoTracksMap.set(S,{stream:m,representation:b}))}this.videoStreamsMap.set(m,v)}this.params.output.availableVideoStreams$.next(h);for(let m of f.text)for(let v of m.representations){let b=MI(m,v);this.textTracksMap.set(b,{stream:m,representation:v})}this.params.output.availableVideoTracks$.next(Array.from(this.videoTracksMap.keys())),this.params.output.availableAudioTracks$.next(Array.from(this.audioTracksMap.keys())),this.params.output.isAudioAvailable$.next(!!this.audioTracksMap.size),p!=null&&p.video&&this.params.output.availableVideoCodecs$.next(p.video),p!=null&&p.audio&&this.params.output.availableAudioCodecs$.next(p.audio),this.audioTracksMap.size&&this.textTracksMap.size&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else d==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},r));let{vktvAbrThrottle:o}=this.params.tuning.dash,u=o&&BI(o)||null;this.subscription.add(Jo(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$,L0(this.video,"progress")).pipe(Vd(()=>this.videoTracksMap.size>0)).subscribe(async()=>{let d=this.player.state$.getState(),f=this.player.state$.getTransition();if(d!=="manifest_ready"&&d!=="running"||f||d==="running"&&u&&!u())return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState()),this.selectVideoAudioRepresentations();let{video:p,audio:h}=this.selectedRepresentations;if(!p)return;let m=Vi(this.videoTracksMap.keys(),b=>{var S;return((S=this.videoTracksMap.get(b))==null?void 0:S.representation.id)===p.id});jI(m)&&(this.stallsManager.lastVideoTrackSelected=m);let v=this.params.desiredState.autoVideoTrackLimits.getTransition();if(v&&this.params.output.autoVideoTrackLimits$.next(v.to),d==="manifest_ready")await this.player.initRepresentations(p.id,h==null?void 0:h.id,this.params.sourceHls);else if(await this.player.switchRepresentation("video",p.id),h){let b=!!t.audioStream.getTransition();await this.player.switchRepresentation("audio",h.id,b)}},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(Xo()).subscribe(d=>{let f=Vi(this.videoTracksMap.entries(),([,{representation:b}])=>b.id===d);if(!f){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[p,{stream:h}]=f,m=this.params.desiredState.videoStream.getTransition();m&&m.to&&m.to.id===h.id&&this.params.desiredState.videoStream.setState(m.to),e.currentVideoTrack$.next(p),e.currentVideoStream$.next(xd(h));let v=this.player.calculateDurationFromSegments();v&&this.params.output.duration$.next(v/1e3)},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(Xo()).subscribe(d=>{let f=Vi(this.audioTracksMap.entries(),([,{representation:v}])=>v.id===d);if(!f){e.currentAudioStream$.next(void 0);return}let[p,{stream:h}]=f,m=this.params.desiredState.audioStream.getTransition();m&&m.to&&m.to.id===h.id&&this.params.desiredState.audioStream.setState(m.to),e.currentAudioStream$.next(Ed(h))},r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(d=>{var f,p;if(d!=null&&d.is3dVideo&&((f=this.params.tuning.spherical)!=null&&f.enabled))try{this.init3DScene(d),e.is3DVideo$.next(!0)}catch(h){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${h}`})}else this.destroy3DScene(),(p=this.params.tuning.spherical)!=null&&p.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(_d(({to:d})=>d==="ready"),Xo());this.subscription.add(Jo(l,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,Od(["init"])).subscribe(()=>{let d=t.autoVideoTrackSwitching.getState(),p=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:d?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(p)})),this.subscription.add(Jo(l,this.player.state$.stateChangeEnded$,Od(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let c=Jo(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Od(["init"])).pipe(k0(0));this.subscription.add(c.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){var $,A,P,V,D,_,K,J,I,R,x,w;if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?La:ka,t=this.params.tuning.useNewAutoSelectVideoTrack?so:ao,i=this.params.tuning.useNewAutoSelectVideoTrack?St:ro,{desiredState:r,output:s}=this.params,n=r.autoVideoTrackSwitching.getState(),o=($=r.videoTrack.getState())==null?void 0:$.id,u=Vi(this.videoTracksMap.keys(),B=>B.id===o),l=s.currentVideoTrack$.getValue(),c=((V=(P=r.videoStream.getState())!=null?P:u&&((A=this.videoTracksMap.get(u))==null?void 0:A.stream))!=null?V:this.videoStreamsMap.size===1)?this.videoStreamsMap.keys().next().value:void 0;if(!c)return;let d=Vi(this.videoStreamsMap.keys(),B=>B.id===c.id),f=d&&this.videoStreamsMap.get(d);if(!f)return;let p=be(this.video.buffered,this.video.currentTime*1e3),h;this.player.isActiveLive$.getValue()?h=this.player.isLowLatency$.getValue()?this.params.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.params.tuning.dashCmafLive.normalizedLiveMinBufferSize:this.player.isLive$.getValue()?h=this.params.tuning.dashCmafLive.normalizedTargetMinBufferSize:h=n?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;let m=(this.video.duration*1e3||1/0)-this.video.currentTime*1e3,v=Math.min(p/Math.min(h,m||1/0),1),b=(D=r.audioStream.getState())!=null?D:this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0,S=(b==null?void 0:b.id)&&Vi(this.audioStreamsMap.keys(),B=>B.id===b.id)||this.audioStreamsMap.keys().next().value,T=0;if(S){if(u&&!n){let B=e(u,f,(_=this.audioStreamsMap.get(S))!=null?_:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);T=Math.max(T,(K=B==null?void 0:B.bitrate)!=null?K:-1/0)}if(l){let B=e(l,f,(J=this.audioStreamsMap.get(S))!=null?J:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);T=Math.max(T,(I=B==null?void 0:B.bitrate)!=null?I:-1/0)}}let y=u;(n||!y)&&(y=i(f,{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:T,forwardBufferHealth:v,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 E=S&&t(y,f,(R=this.audioStreamsMap.get(S))!=null?R:[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.stallsManager.abrTuningParams,forwardBufferHealth:v,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),k=(x=this.videoTracksMap.get(y))==null?void 0:x.representation,M=E&&((w=this.audioTracksMap.get(E))==null?void 0:w.representation);k&&M?(this.selectedRepresentations.video=k,this.selectedRepresentations.audio=M):k&&!M&&this.audioTracksMap.size===0&&(this.selectedRepresentations.video=k,this.selectedRepresentations.audio=null)}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){_e(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),L(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:HI.DOM,thrown:e}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.stallsManager.destroy(),this.elementSizeManager.destroy(),this.destroy3DScene(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),this.params.output.currentVideoStream$.next(void 0),Ce(this.video),this.tracer.end()}};var Ms=class extends qi{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 Fd,merge as WI,filter as GI,filterChanged as zI,isNullable as Nd,map as YI,ValueSubject as qd,isNonNullable as D0}from"@vkontakte/videoplayer-shared/es2018";var Ds=class extends qi{constructor(e){super(e),this.textTracksManager.destroy()}subscribe(){super.subscribe();let e=!1,t=-1,{output:i,observableVideo:r,desiredState:s,connect:n}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canPlayLiveTailBuffer$.next(!0),n(r.timeUpdate$,i.liveBufferTime$),n(this.player.liveSeekableDuration$,i.duration$),n(this.player.liveLatency$,i.liveLatency$);let o=new qd(1);n(r.playbackRateState$,o),this.params.tuning.dashCmafLive.catchupLiveForMutedInactiveTab&&this.subscription.add(i.elementVisible$.pipe(zI()).subscribe(u=>{let l=i.position$.getValue(),c=i.volume$.getValue(),d=!c.volume||c.muted;!u&&!l&&d?e=!0:u&&e&&(this.seek(0),e=!1)})),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(s.isLowLatency.stateChangeEnded$.pipe(YI(u=>u.to)).subscribe(this.player.isLowLatency$)).add(Fd({liveBufferTime:i.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(YI(({liveBufferTime:u,liveAvailabilityStartTime:l})=>u&&l?u+l:void 0)).subscribe(i.liveTime$)).add(this.player.liveStreamStatus$.pipe(GI(u=>D0(u))).subscribe(u=>i.isLiveEnded$.next(u!=="active"&&i.position$.getValue()===0))).add(Fd({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:WI(r.playbackRateState$,new qd(1))}).pipe(GI(({liveStreamStatus:u,liveDuration:l})=>u==="active"&&!!l)).subscribe(({liveDuration:u,playbackRate:l})=>{let c=i.liveBufferTime$.getValue(),d=i.position$.getValue(),{playbackCatchupSpeedup:f}=this.params.tuning.dashCmafLive.lowLatency;d||l<1-f||this.video.paused||Nd(c)||(t=u-c)})).add(Fd({time:i.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:WI(r.playbackRateState$,new qd(1))}).pipe(zI((u,l)=>this.player.liveStreamStatus$.getValue()==="active"?u.liveDuration===l.liveDuration:u.time===l.time)).subscribe(({time:u,liveDuration:l,playbackRate:c})=>{let d=i.position$.getValue(),{playbackCatchupSpeedup:f}=this.params.tuning.dashCmafLive.lowLatency;if(!d&&!this.video.paused&&c>=1-f||Nd(u)||Nd(l))return;let p=-1*(l-u-t);i.position$.next(Math.min(p,0))})).add(this.player.currentLiveTextRepresentation$.subscribe(u=>{if(u){let l=DI(u);this.params.output.availableTextTracks$.next([l])}}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,i=Math.trunc(t/1e3<=Math.abs(this.params.output.duration$.getValue())?t:0);this.player.seekLive(i).then(()=>{this.params.output.position$.next(e/1e3)})}};var KI="X-Playback-Duration",Ud=async a=>{var r;let e=await Ze(a),t=await e.text(),i=(r=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t))==null?void 0:r[1];return i?parseInt(i,10):e.headers.has(KI)?parseInt(e.headers.get(KI),10):void 0};import{assertNever as j0,combine as Q0,debounce as W0,ErrorCategory as tu,filter as G0,filterChanged as z0,isNonNullable as ZI,isNullable as iu,map as eE,merge as Y0,observableFrom as K0,Subscription as X0,ValueSubject as Qd,VideoQuality as J0}from"@vkontakte/videoplayer-shared/es2018";var jd=O(xl(),1);import{videoSizeToQuality as C0,getExponentialDelay as B0}from"@vkontakte/videoplayer-shared/es2018";var V0=a=>{let e=null;if(a.QUALITY&&(e=Kt(a.QUALITY)),!e&&a.RESOLUTION){let[t,i]=a.RESOLUTION.split("x").map(r=>parseInt(r,10));e=C0({width:t,height:i})}return e!=null?e:null},_0=(a,e)=>{var s,n;let t=a.split(`
179
- `),i=[],r=[];for(let o=0;o<t.length;o++){let u=t[o],l=u.match(/^#EXT-X-STREAM-INF:(.+)/),c=u.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!l&&!c)){if(l){let d=(0,jd.default)(l[1].split(",").map(S=>S.split("="))),f=(s=d.QUALITY)!=null?s:`stream-${d.BANDWIDTH}`,p=V0(d),h;d.BANDWIDTH&&(h=parseInt(d.BANDWIDTH,10)/1e3||void 0),!h&&d["AVERAGE-BANDWIDTH"]&&(h=parseInt(d["AVERAGE-BANDWIDTH"],10)/1e3||void 0);let m=d["FRAME-RATE"]?parseFloat(d["FRAME-RATE"]):void 0,v;if(d.RESOLUTION){let[S,T]=d.RESOLUTION.split("x").map(y=>parseInt(y,10));S&&T&&(v={width:S,height:T})}let b=new URL(t[++o],e).toString();p&&i.push({id:f,quality:p,url:b,bandwidth:h,size:v,fps:m})}if(c){let d=(0,jd.default)(c[1].split(",").map(m=>{let v=m.indexOf("=");return[m.substring(0,v),m.substring(v+1)]}).map(([m,v])=>[m,v.replace(/^"|"$/g,"")])),f=(n=d.URI)==null?void 0:n.replace(/playlist$/,"subtitles.vtt"),p=d.LANGUAGE,h=d.NAME;f&&p&&r.push({type:"internal",id:p,label:h,language:p,url:f,isAuto:!1})}}}if(!i.length)throw new Error("Empty manifest");return{qualityManifests:i,textTracks:r}},O0=a=>new Promise(e=>{setTimeout(()=>{e()},a)}),Hd=0,XI=async(a,e=a,t,i)=>{let s=await(await Ze(a,i)).text();Hd+=1;try{let{qualityManifests:n,textTracks:o}=_0(s,e);return{qualityManifests:n,textTracks:o}}catch(n){if(Hd<=t.manifestRetryMaxCount)return await O0(B0(Hd-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),XI(a,e,t)}return{qualityManifests:[],textTracks:[]}},Zo=XI;import{isNonNullable as F0,Subscription as N0,throttle as q0,ValueSubject as JI,Subject as U0,ErrorCategory as H0}from"@vkontakte/videoplayer-shared/es2018";var eu=class{constructor(e,t,i,r,s){this.subscription=new N0;this.abortControllers={destroy:new Z,nextManifest:null};this.prepareUrl=void 0;this.currentTextTrackData=null;this.availableTextTracks$=new JI(null);this.getCurrentTime$=new JI(null);this.error$=new U0;this.params={fetchManifestData:i,sourceUrl:r,downloadThreshold:s},this.subscription.add(e.pipe(q0(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 Ze(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(),f=new Date(i.programDateTime).valueOf();i.segmentStartTime=f-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(F0(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 Z;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(){var t;let e=(t=this.prepareUrl)!=null?t: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:H0.WTF,thrown:t,message:e})}};var Cs=class{constructor(e){this.subscription=new X0;this.videoState=new H("stopped");this.textTracksManager=null;this.liveTextManager=null;this.manifests$=new Qd([]);this.liveOffset=new Pi;this.manifestStartTime$=new Qd(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"),L(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==null?void 0: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"?L(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),L(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==null?void 0:r.to)==="playing"&&L(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==null?void 0:r.to)==="paused"&&(L(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return j0(t)}};var i;this.params=e,this.video=De(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:J0.INVARIANT,url:this.params.source.url};let t=(r,s)=>Zo(r,this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},s);this.params.tuning.useHlsLiveNewTextManager?this.liveTextManager=new eu(this.params.output.liveTime$,this.video,t,this.params.source.url,this.params.tuning.hlsLiveNewTextManagerDownloadThreshold):this.textTracksManager=new Xe(e.source.url),t(this.generateLiveUrl()).then(({qualityManifests:r,textTracks:s})=>{var n;r.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:tu.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),(n=this.liveTextManager)==null||n.processTextTracks(s,this.params.source.url),this.manifests$.next([this.masterManifest,...r])}).catch(r=>{this.params.output.error$.next({id:"ExtractHlsQualities",category:tu.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:r})}),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Te(this.params.source.url)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.maxSeekBackTime$=new Qd((i=e.source.maxSeekBackTime)!=null?i:1/0),this.subscribe()}selectManifest(){var u,l,c,d;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),r=t.getTransition(),s=(d=(c=(u=r==null?void 0:r.to)==null?void 0:u.id)!=null?c:(l=t.getState())==null?void 0:l.id)!=null?d:"master",n=this.manifests$.getValue();if(!n.length)return;let o=i?"master":s;return i&&!r&&t.startTransitionTo(this.masterManifest),n.find(f=>f.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsLiveProvider",category:tu.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},r=Ve(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(Be(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Ke(this.video,t.playbackRate,r.playbackRateState$,i)),s(Je(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"),L(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),L(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())==null?void 0:o.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(z0(),eE(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&&ZI(l.to)){let d=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let f=this.manifests$.getValue().find(p=>p.id===d);f&&(this.params.output.currentVideoTrack$.next(f),this.params.output.hostname$.next(Te(f.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(()=>{var u,l,c;let o=(c=(l=(u=this.video)==null?void 0:u.getStartDate)==null?void 0:l.call(u))==null?void 0:c.getTime();this.manifestStartTime$.next(o||void 0)},i)),this.subscription.add(Q0({startTime:this.manifestStartTime$.pipe(G0(ZI)),currentTime:r.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),i)),this.subscription.add(this.manifests$.pipe(eE(o=>o.map(({id:u,quality:l,size:c,bandwidth:d,fps:f})=>({id:u,quality:l,size:c,fps:f,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,i));let n=Y0(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,K0(["init"])).pipe(W0(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){var e,t;this.subscription.unsubscribe(),(e=this.textTracksManager)==null||e.destroy(),(t=this.liveTextManager)==null||t.destroy(),this.params.output.element$.next(void 0),Ce(this.video)}prepare(){var o,u,l;let e=this.selectManifest();if(iu(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:c,min:d}=(u=(o=t==null?void 0:t.to)!=null?o:i)!=null?u:{};for(let[f,p]of[[c,"mq"],[d,"lq"]]){let h=String(parseFloat(f||""));p&&f&&r.searchParams.set(p,h)}}let s=this.params.format==="HLS_LIVE_CMAF"?2:0,n=le(r.toString(),this.liveOffset.getTotalOffset(),s);(l=this.liveTextManager)==null||l.prepare(n),this.video.setAttribute("src",n),this.video.load(),Ud(n).then(c=>{var d;if(!iu(c))this.maxSeekBackTime$.next(c);else{let f=(d=this.params.source.maxSeekBackTime)!=null?d:this.maxSeekBackTime$.getValue();(iu(f)||!isFinite(f))&&Ze(n).then(p=>p.text()).then(p=>{var m;let h=(m=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(p))==null?void 0:m[1];if(h){let v=new URL(h,n).toString();Ud(v).then(b=>{iu(b)||this.maxSeekBackTime$.next(b)})}}).catch(()=>{})}})}playIfAllowed(){_e(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),L(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:tu.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=le(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 Z0,debounce as eV,ErrorCategory as Wd,fromEvent as Gd,isNonNullable as tV,isNullable as iV,map as tE,merge as iE,observableFrom as rE,Subscription as rV,ValueSubject as aV,VideoQuality as sV}from"@vkontakte/videoplayer-shared/es2018";var Bs=class{constructor(e){this.subscription=new rV;this.videoState=new H("stopped");this.manifests$=new aV([]);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"),L(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==null?void 0:r.to)!=="paused"&&l.state==="requested"&&this.seek(l.position),t){case"ready":i==="ready"?L(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),L(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==null?void 0:r.to)==="playing"&&L(this.params.desiredState.playbackState,"playing");return;case"paused":i==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&L(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return Z0(t)}};this.textTracksManager=new Xe(e.source.url),this.params=e,this.video=De(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:sV.INVARIANT,url:this.params.source.url},this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Te(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.manifestRequested$.next(),Zo(le(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:t,textTracks:i})=>{this.params.output.manifestReceived$.next(),this.manifests$.next([this.masterManifest,...t]),this.params.tuning.useNativeHLSTextTracks||this.params.desiredState.internalTextTracks.startTransitionTo(i)},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:Wd.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){var u,l,c,d;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),r=t.getTransition(),s=(d=(c=(u=r==null?void 0:r.to)==null?void 0:u.id)!=null?c:(l=t.getState())==null?void 0:l.id)!=null?d:"master",n=this.manifests$.getValue();if(!n.length)return;let o=i?"master":s;return i&&(!r||!r.from)&&t.startTransitionTo(this.masterManifest),n.find(f=>f.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsProvider",category:Wd.WTF,message:"HlsProvider internal logic error",thrown:o})},r=Ve(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(tE(o=>o.to)),this.params.output.playbackState$),this.subscription.add(bt(this.video,t.isLooped,i)),this.subscription.add(Be(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Ke(this.video,t.playbackRate,r.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),L(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),L(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())==null?void 0:o.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i).add(r.loadedMetadata$.subscribe(()=>{var p;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&&tV(l.to)){let h=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let m=this.manifests$.getValue().find(v=>v.id===h);m&&(this.params.output.currentVideoTrack$.next(m),this.params.output.hostname$.next(Te(m.url)))}let d=this.params.desiredState.playbackRate.getState(),f=(p=this.params.output.element$.getValue())==null?void 0:p.playbackRate;if(d!==f){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.params.tuning.changePlaybackStateToPausedWhenEnded&&this.subscription.add(r.ended$.subscribe(()=>{this.videoState.setState("paused"),L(t.playbackState,"paused")})),this.subscription.add(this.manifests$.pipe(tE(o=>o.map(({id:u,quality:l,size:c,bandwidth:d,fps:f})=>({id:u,quality:l,size:c,fps:f,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,i)),!F.device.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add(iE(Gd(o,"addtrack"),Gd(o,"removetrack"),Gd(o,"change"),rE(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},i))}let n=iE(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,rE(["init"])).pipe(eV(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),Ce(this.video)}prepare(){var s,n;let e=this.selectManifest();if(iV(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}=(n=(s=t==null?void 0:t.to)!=null?s:i)!=null?n:{};for(let[l,c]of[[o,"mq"],[u,"lq"]]){let d=String(parseFloat(l||""));c&&l&&r.searchParams.set(c,d)}}this.video.setAttribute("src",r.toString()),this.video.load()}playIfAllowed(){_e(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),L(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Wd.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};var nE=O(ir(),1),zd=O(fr(),1),oE=O(ot(),1);import{assertNever as nV,assertNonNullable as aE,debounce as oV,ErrorCategory as sE,isHigherOrEqual as uV,isLowerOrEqual as lV,isNonNullable as cV,merge as dV,observableFrom as pV,Subscription as hV,map as fV}from"@vkontakte/videoplayer-shared/es2018";var Vs=class{constructor(e){this.subscription=new hV;this.videoState=new H("stopped");this.trackUrls={};this.textTracksManager=new Xe;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"),L(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==null?void 0:i.to)!=="paused"&&o.state==="requested"&&this.seek(o.position),e){case"ready":t==="ready"?L(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),L(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==null?void 0:i.to)==="playing"&&L(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&L(this.params.desiredState.playbackState,"paused");return;default:return nV(e)}};this.params=e,this.video=De(e.container,e.tuning),this.params.output.element$.next(this.video),(0,nE.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,zd.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:sE.WTF,message:"MpegProvider internal logic error",thrown:o})},r=Ve(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(fV(o=>o.to)),this.params.output.playbackState$),this.subscription.add(bt(this.video,t.isLooped,i)),this.subscription.add(Be(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Ke(this.video,t.playbackRate,r.playbackRateState$,i)),s(Je(this.video),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),L(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),L(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{var u,l;((u=this.videoState.getTransition())==null?void 0:u.to)==="ready"&&this.videoState.setState("ready");let o=this.params.desiredState.videoTrack.getTransition();if(o&&cV(o.to)){this.params.desiredState.videoTrack.setState(o.to),this.params.output.currentVideoTrack$.next(this.trackUrls[o.to.id].track);let c=this.params.desiredState.playbackRate.getState(),d=(l=this.params.output.element$.getValue())==null?void 0:l.playbackRate;if(c!==d){let f=this.params.output.element$.getValue();f&&(this.params.desiredState.playbackRate.setState(c),f.playbackRate=c)}}this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.params.tuning.changePlaybackStateToPausedWhenEnded&&this.subscription.add(r.ended$.subscribe(()=>{this.videoState.setState("paused"),L(t.playbackState,"paused")})),this.textTracksManager.connect(this.video,t,e);let n=dV(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,pV(["init"])).pipe(oV(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.params.output.element$.next(void 0),Ce(this.video)}prepare(){var i;let e=(i=this.params.desiredState.videoTrack.getState())==null?void 0:i.id;aE(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];aE(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=ei(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(Te(t))}playIfAllowed(){_e(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),L(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:sE.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){var l,c;this.params.output.autoVideoTrackLimits$.next(e);let t=d=>{this.params.output.currentVideoTrack$.next(d),this.params.desiredState.videoTrack.startTransitionTo(d)},i=d=>{let f=St(n,{container:this.video.getBoundingClientRect(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:0,limits:d,abrLogger:this.params.dependencies.abrLogger});t(f)},r=(l=this.params.output.currentVideoTrack$.getValue())==null?void 0:l.quality,s=!!(e.max||e.min),n=(0,zd.default)(this.trackUrls).map(d=>d.track);if(!r||!s||br(e,n[0].quality,(c=(0,oE.default)(n,-1))==null?void 0:c.quality)){i();return}let o=e.max?lV(r,e.max):!0,u=e.min?uV(r,e.min):!0;o&&u||i(e)}};import{assertNever as lE,debounce as vV,merge as cE,observableFrom as SV,Subscription as yV,map as dE,ValueSubject as TV,ErrorCategory as Kd,VideoQuality as IV}from"@vkontakte/videoplayer-shared/es2018";import{ErrorCategory as mV}from"@vkontakte/videoplayer-shared/es2018";var uE=["stun:videostun.mycdn.me:80"],bV=1e3,gV=3,Yd=()=>null,ru=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=Yd;this.externalStopCallback=Yd;this.externalErrorCallback=Yd;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:uE}]};this.peerConnection=new RTCPeerConnection(e),this.peerConnection.ontrack=this.onPeerConnectionStream.bind(this),this.peerConnection.onicecandidate=this.onPeerConnectionIceCandidate.bind(this),this.peerConnection.oniceconnectionstatechange=this.onPeerConnectionIceConnectionStateChange.bind(this);let t=await this.createOffer();await this.peerConnection.setLocalDescription(t),this.send({type:this.signalingType,inviteType:"OFFER",streamKey:this.streamKey,sdp:t.sdp,callSupport:!1})}catch(e){this.handleRTCError(e)}}async handleAnswer(e){try{this.peerConnection&&await this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e}))}catch(t){this.handleRTCError(t)}}async handleCandidate(e){if(e)try{this.peerConnection&&await this.peerConnection.addIceCandidate(e)}catch(t){this.handleRTCError(t)}}handleUnpublished(){try{this.closeConnections(),this.externalStopCallback()}catch(e){this.handleRTCError(e)}}handleSystemError(e){this.options.errorChanel&&this.options.errorChanel.next({id:"webrtc-provider-error",category:mV.WTF,message:e.message})}async onPeerConnectionStream(e){let t=e.streams[0];this.stream&&this.stream.id===t.id||(this.stream=t,this.externalStartCallback(this.stream))}onPeerConnectionIceCandidate(e){e.candidate&&this.send({type:this.signalingType,inviteType:"CANDIDATE",candidate:e.candidate})}onPeerConnectionIceConnectionStateChange(){if(this.peerConnection){let e=this.peerConnection.iceConnectionState;["failed","closed"].indexOf(e)>-1&&(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():(this.closeConnections(),this.scheduleRetry()))}}async createOffer(){let e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");let t=await this.peerConnection.createOffer(e),i=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(i))throw new Error("No h264 codec support error");return t}handleRTCError(e){try{this.externalErrorCallback(e||new Error("RTC connection error"))}catch(t){this.handleSystemError(t)}}handleNetworkError(){try{this.externalErrorCallback(new Error("Network error"))}catch(e){this.handleSystemError(e)}}send(e){this.ws&&this.ws.send(JSON.stringify(e))}parseMessage(e){try{return JSON.parse(e)}catch(t){throw new Error("Can not parse socket message")}}closeConnections(){let e=this.ws;e&&(this.ws=null,e.close(1e3)),this.removePeerConnection()}removePeerConnection(){let e=this.peerConnection;e&&(this.peerConnection=null,e.close(),e.ontrack=null,e.onicecandidate=null,e.oniceconnectionstatechange=null,e=null)}scheduleRetry(){this.retryTimeout=setTimeout(this.connectWS.bind(this),bV)}normalizeOptions(e={}){let t={stunServerList:uE,maxRetryNumber:gV,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var _s=class{constructor(e){this.videoState=new H("stopped");this.maxSeekBackTime$=new TV(0);this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.pause(),this.video.srcObject=null,this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),L(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"),L(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==null?void 0:i.to)==="playing"&&L(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&L(this.params.desiredState.playbackState,"paused");return;default:return lE(e)}};this.subscription=new yV,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=De(e.container,e.tuning),this.liveStreamClient=new ru(this.params.source.url,{maxRetryNumber:this.params.tuning.webrtc.connectionRetryMaxNumber,errorChanel:this.params.output.error$}),this.liveStreamClient.onStart(this.onLiveStreamStart.bind(this)),this.liveStreamClient.onStop(this.onLiveStreamStop.bind(this)),this.liveStreamClient.onError(this.onLiveStreamError.bind(this)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.subscribe()}destroy(){this.subscription.unsubscribe(),this.liveStreamClient.disconnect(),this.params.output.element$.next(void 0),Ce(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,i=n=>{e.error$.next({id:"WebRTCLiveProvider",category:Kd.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};this.subscription.add(cE(this.videoState.stateChangeStarted$.pipe(dE(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe(dE(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})}));let r=Ve(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(Je(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(()=>{var n;((n=this.videoState.getTransition())==null?void 0:n.to)==="ready"&&this.videoState.setState("ready")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused")},i)).add(r.playing$.subscribe(()=>{this.videoState.setState("playing")},i)).add(r.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(Be(this.video,t.volume,r.volumeState$,i)).add(r.volumeState$.subscribe(e.volume$,i)).add(this.videoState.stateChangeEnded$.subscribe(n=>{switch(n.to){case"stopped":e.position$.next(0),e.duration$.next(0),t.playbackState.setState("stopped");break;case"ready":break;case"paused":t.playbackState.setState("paused");break;case"playing":t.playbackState.setState("playing");break;default:return lE(n.to)}},i)).add(cE(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,SV(["init"])).pipe(vV(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(Te(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.currentVideoTrack$.next({id:"webrtc",quality:IV.INVARIANT}),this.video.srcObject=e,L(this.params.desiredState.playbackState,"playing")}onLiveStreamStop(){this.videoState.startTransitionTo("stopped"),this.syncPlayback(),this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.params.output.endedEvent$.next()}onLiveStreamError(e){this.onLiveStreamStop(),this.params.output.error$.next({id:"WebRTC stream runtime error",category:Kd.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){_e(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),L(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Kd.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var jr=class{constructor(e){this.length=e.length,this.iterator=e[Symbol.iterator](),this.next()}next(){this.current=this.iterator.next(),this.index=this.index===void 0?0:this.index+1}getValue(){if(this.current.done)throw new Error("Iterable is completed");return this.current.value}isCompleted(){return!!this.current.done}isLast(){return this.index===this.length-1}};import{assertNever as Fs,assertNonNullable as si,ErrorCategory as au,filter as gE,isNonNullable as vE,isNullable as kV,map as LV,merge as $V,once as MV,Subject as ce,Subscription as SE,ValueSubject as q,flattenObject as Xd}from"@vkontakte/videoplayer-shared/es2018";import{Observable as EV,map as pE,Subscription as xV,Subject as wV}from"@vkontakte/videoplayer-shared/es2018";var hE=a=>new EV(e=>{let t=new xV,i=a.desiredPlaybackState$.stateChangeStarted$.pipe(pE(({from:l,to:c})=>`${l}-${c}`)),r=a.desiredPlaybackState$.stateChangeEnded$,s=a.providerChanged$.pipe(pE(({type:l})=>l!==void 0)),n=new wV,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 AV,Subscription as PV,combine as RV,filter as mE,once as bE}from"@vkontakte/videoplayer-shared/es2018";function fE(){return new(window.AudioContext||window.webkitAudioContext)}var Os=class Os{constructor(e,t,i,r){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=i;this.volumeMultiplier=r;this.destroyController=new Z;this.subscriptions=new PV;this.audioContext=null;this.gainNode=null;this.mediaElementSource=null;this.subscriptions.add(this.provider$.pipe(mE(s=>!!s.type),bE()).subscribe(({type:s})=>this.subscribe(s)))}subscribe(e){F.browser.isSafari&&e!=="MPEG"||this.subscriptions.add(RV({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe(mE(({playbackState:t,video:i,volume:{muted:r,volume:s}})=>t==="playing"&&!!i&&!r&&!!s),bE()).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=fE();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){var t;this.volumeMultiplierError$.next({id:Os.errorId,category:AV.VIDEO_PIPELINE,message:(t=e==null?void 0:e.message)!=null?t:`${Os.errorId} exception`,thrown:e})}};Os.errorId="VolumeMultiplierManager";var Qr=Os;var DV={chunkDuration:5e3,maxParallelRequests:5},Ns=class{constructor(e){this.current$=new q({type:void 0});this.providerError$=new ce;this.noAvailableProvidersError$=new ce;this.volumeMultiplierError$=new ce;this.providerOutput={position$:new q(0),duration$:new q(1/0),volume$:new q({muted:!1,volume:1}),availableVideoStreams$:new q([]),currentVideoStream$:new q(void 0),availableVideoTracks$:new q([]),currentVideoTrack$:new q(void 0),availableVideoCodecs$:new q([]),availableAudioStreams$:new q([]),currentAudioStream$:new q(void 0),availableAudioTracks$:new q([]),availableAudioCodecs$:new q([]),currentVideoSegmentLength$:new q(0),currentAudioSegmentLength$:new q(0),isAudioAvailable$:new q(!0),autoVideoTrackLimitingAvailable$:new q(!1),autoVideoTrackLimits$:new q(void 0),currentBuffer$:new q(void 0),isBuffering$:new q(!0),error$:new ce,fetcherError$:new ce,fetcherRecoverableError$:new ce,warning$:new ce,willSeekEvent$:new ce,soundProhibitedEvent$:new ce,seekedEvent$:new ce,loopedEvent$:new ce,endedEvent$:new ce,manifestRequested$:new ce,manifestReceived$:new ce,firstBytesRequested$:new ce,firstBytesReceived$:new ce,firstBytesEvent$:new ce,loadedMetadataEvent$:new ce,firstFrameEvent$:new ce,canplay$:new ce,isLive$:new q(void 0),isLiveEnded$:new q(null),canPlayLiveTailBuffer$:new q(!1),isLowLatency$:new q(!1),canChangePlaybackSpeed$:new q(!0),liveTime$:new q(void 0),liveBufferTime$:new q(void 0),liveLatency$:new q(void 0),severeStallOccurred$:new ce,availableTextTracks$:new q([]),currentTextTrack$:new q(void 0),hostname$:new q(void 0),httpConnectionType$:new q(void 0),httpConnectionReused$:new q(void 0),inPiP$:new q(!1),inFullscreen$:new q(!1),element$:new q(void 0),elementVisible$:new q(!0),availableSources$:new q(void 0),is3DVideo$:new q(!1),playbackState$:new q(""),getCurrentTime$:new q(null)};this.subscription=new SE;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=dc([...lI(this.params.tuning),...uI(this.params.tuning)]).filter(l=>vE(e.sources[l])),{forceFormat:i,formatsToAvoid:r}=this.params.tuning,s=[];i?s=[i]:r.length?s=[...t.filter(l=>!(0,Jd.default)(r,l)),...t.filter(l=>(0,Jd.default)(r,l))]:s=t,this.log({message:`Selected formats: ${s.join(" > ")}`}),this.tracer.log("Selected formats",Xd(s)),this.screenFormatsIterator=new jr(s);let n=[...ad(!0),...ad(!1)];this.chromecastFormatsIterator=new jr(n.filter(l=>vE(e.sources[l]))),this.providerOutput.availableSources$.next(e.sources);let{volumeMultiplier:o=1,tuning:{useVolumeMultiplier:u}}=this.params;u&&o!==1&&Qr.isSupported()&&(this.volumeMultiplierManager=new Qr(this.providerOutput,this.current$,this.volumeMultiplierError$,o))}init(){this.subscription.add(this.initProviderErrorHandling()).add(this.params.dependencies.chromecastInitializer.connection$.subscribe(()=>{this.reinitProvider()})).add(this.providerOutput.availableVideoCodecs$.subscribe(e=>{!this.videoCodecsIterator&&e.length>1&&(this.videoCodecsIterator=new jr(e))}))}destroy(){var e;this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe(),(e=this.volumeMultiplierManager)==null||e.destroy(),this.volumeMultiplierManager=null,this.tracer.end()}initProvider(){let e=this.chooseDestination(),t=this.chooseFormat(e);if(kV(t)){this.handleNoFormatsError(e);return}let i;try{i=this.createProvider(e,t)}catch(r){this.providerError$.next({id:"ProviderNotConstructed",category:au.WTF,message:"Failed to create provider",thrown:r})}i?this.current$.next({type:t,provider:i,destination:e}):this.current$.next({type:void 0})}reinitProvider(){this.tracer.log("reinitProvider"),this.destroyProvider(),this.initProvider()}switchToNextProvider(e){this.tracer.log("switchToNextProvider",{destination:e}),this.destroyProvider(),this.failoverIndex=void 0,this.skipFormat(e),this.initProvider()}switchToNextVideoCodec(){this.params.tuning.dash.codecsPrioritizeEnabled&&!this.videoCodecsIterator.isLast()&&(this.tracer.log("switchToNextVideoCodec"),this.destroyProvider(),this.videoCodecsIterator.next(),this.initProvider())}destroyProvider(){let e=this.current$.getValue().provider;if(!e)return;this.log({message:"destroyProvider"}),this.tracer.log("destroyProvider"),e.destroy();let t=this.providerOutput.position$.getValue()*1e3,i=this.params.desiredState.seekState.getState(),r=i.state!=="none";if(this.params.desiredState.seekState.setState({state:"requested",position:r?i.position:t,forcePrecise:r?i.forcePrecise:!1}),e.scene3D){let n=e.scene3D.getCameraRotation();this.params.desiredState.cameraOrientation.setState({x:n.x,y:n.y})}let s=this.providerOutput.isBuffering$;s.getValue()||s.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),this.tracer.log("createProvider",{destination:e,format:t}),e){case"SCREEN":return this.createScreenProvider(t);case"CHROMECAST":return this.createChromecastProvider(t);default:return Fs(e)}}createScreenProvider(e){var u,l;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 c=this.applyFailoverHost(t[e]),d=this.applyFailoverHost(t.HLS_ONDEMAND||t.HLS);return si(c),this.params.tuning.useNewDashProvider?new Ms({...o,source:c,sourceHls:d,forceVideoCodec:(u=this.videoCodecsIterator)==null?void 0:u.getValue()}):new Is({...o,source:c,sourceHls:d,forceVideoCodec:(l=this.videoCodecsIterator)==null?void 0:l.getValue()})}case"DASH_LIVE_CMAF":{let c=this.applyFailoverHost(t[e]);return si(c),this.params.tuning.useNewDashProvider?new Ds({...o,source:c}):new Es({...o,source:c})}case"HLS":case"HLS_ONDEMAND":case"HLS_FMP4":{let c=this.applyFailoverHost(t[e]);return si(c),new Bs({...o,source:c})}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let c=this.applyFailoverHost(t[e]);return si(c),new Cs({...o,source:c,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case"MPEG":{let c=this.applyFailoverHost(t[e]);return si(c),new Vs({...o,source:c})}case"DASH_LIVE":{let c=this.applyFailoverHost(t[e]);return si(c),new ty({...o,source:c,config:{...DV,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case"WEB_RTC_LIVE":{let c=this.applyFailoverHost(t[e]);return si(c),new _s({container:i,source:c,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 Fs(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 si(o),new xa({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 Fs(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return Fs(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 Fs(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,TE.default)((0,yE.default)(e).map(([r,s])=>[r,i(s)]))}initProviderErrorHandling(){let e=new SE,t=!1,i=0;return e.add($V(this.providerOutput.error$.pipe(gE(r=>!this.params.tuning.ignoreAudioRendererError||!r.message||!/AUDIO_RENDERER_ERROR/ig.test(r.message))),hE({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(LV(r=>({id:`ProviderHangup:${r}`,category:au.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(gE(({to:s})=>s==="playing"),MV()).subscribe(()=>t=!0);e.add(r)})),e.add(this.providerError$.subscribe(r=>{let s=this.current$.getValue().destination,n={error:r,currentDestination:s};if(s==="CHROMECAST")this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider("SCREEN"),()=>this.params.dependencies.chromecastInitializer.disconnect());else{let o=r.category===au.NETWORK,u=r.category===au.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=this.videoCodecsIterator&&!this.videoCodecsIterator.isLast()&&this.params.tuning.dash.codecsPrioritizeEnabled,f=l&&!u&&(o&&t||!c);n={...n,isNetworkError:o,isFatalError:u,haveFailoverHost:l,tryFailover:f,canReinitProvider:c},c?(i++,this.reinitProvider()):f?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):d?this.switchToNextVideoCodec():(i=0,this.switchToNextProvider(s!=null?s:"SCREEN"))}r.traceAsLog?this.tracer.log("providerInfo",Xd(n)):this.tracer.error("providerError",Xd(n))})),e}};import{fromEvent as su,once as CV,combine as BV,Subscription as IE,ValueSubject as Zd,map as VV,filter as _V,isNonNullable as nu,now as ze,safeStorage as ep}from"@vkontakte/videoplayer-shared/es2018";var OV=5e3,EE="one_video_throughput",xE="one_video_rtt",Vt=window.navigator.connection,wE=()=>{let a=Vt==null?void 0:Vt.downlink;if(nu(a)&&a!==10)return a*1e3},AE=()=>{let a=Vt==null?void 0:Vt.rtt;if(nu(a)&&a!==3e3)return a},PE=(a,e,t)=>{let i=t*8,r=i/a;return i/(r+e)},tp=class a{constructor(e){this.subscription=new IE;this.concurrentDownloads=new Set;var r,s;this.tuningConfig=e;let t=a.load(EE)||(e.useBrowserEstimation?wE():void 0)||OV,i=(s=(r=a.load(xE))!=null?r:e.useBrowserEstimation?AE():void 0)!=null?s:0;if(this.throughput$=new Zd(t),this.rtt$=new Zd(i),this.rttAdjustedThroughput$=new Zd(PE(t,i,e.rttPenaltyRequestSize)),this.throughput=Ct.getSmoothedValue(t,-1,e),this.rtt=Ct.getSmoothedValue(i,1,e),e.useBrowserEstimation){let n=()=>{let u=wE();u&&this.throughput.next(u);let l=AE();nu(l)&&this.rtt.next(l)};Vt&&"onchange"in Vt&&this.subscription.add(su(Vt,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{ep.set(EE,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{ep.set(xE,n.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(BV({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(VV(({throughput:n,rtt:o})=>PE(n,o,e.rttPenaltyRequestSize)),_V(n=>{let o=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(n-o)/o>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,i=ze(),r=new IE;switch(this.subscription.add(r),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:r.add(su(e,"progress").pipe(CV()).subscribe(s=>{t=s.loaded,i=ze()}));break;case 1:case 0:r.add(su(e,"loadstart").subscribe(()=>{t=0,i=ze()}));break}r.add(su(e,"loadend").subscribe(s=>{if(e.status===200){let n=s.loaded,o=ze(),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=ze(),n=0,o=ze(),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,ze()-s,1),this.concurrentDownloads.delete(e);else if(d){if(t){let f=ze();if(f-o>this.tuningConfig.lowLatency.continuesByteSequenceInterval||f-s>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let h=o-s;h&&this.addRawSpeed(n,h,1,t),n=d.byteLength,s=ze()}else n+=d.byteLength;o=ze()}else r+=d.byteLength,n+=d.byteLength,n>=this.tuningConfig.streamMinSampleSize&&ze()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,ze()-o,this.concurrentDownloads.size),n=0,o=ze());await(i==null?void 0:i.read().then(l,u))}};this.concurrentDownloads.add(e),i==null||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){var i;let t=ep.get(e);if(nu(t))return(i=parseInt(t,10))!=null?i:void 0}},RE=tp;import{fillWithDefault as FV,VideoQuality as ou}from"@vkontakte/videoplayer-shared/es2018";var kE={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:ou.Q_4320P,activeVideoAreaThreshold:.1,highQualityLimit:ou.Q_720P,trafficSavingLimit:ou.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:ou.Q_480P},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,seekBiasInTheEnd:2e3,maxSegmentDurationLeftToSelectNextSegment:3e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:3e3,crashOnStallTimeout:25e3,crashOnStallTWithoutDataTimeout:5e3,enableSubSegmentBufferFeeding:!0,bufferEmptinessTolerance:100,useFetchPriorityHints:!0,enableBaseUrlSupport:!0,maxSegmentRetryCount:5,sourceOpenTimeout:1e3,vktvAbrThrottle:0,timeupdateEventTickThrottle:300,fetcherBufferOptimisation:!0,codecsPrioritizeEnabled:!1},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,maxLiveDuration:7200,catchupLiveForMutedInactiveTab:!0,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:250,playbackCatchupSpeedup:.05,isActiveOnDefault:!1,bufferEstimator:{emaAlpha:.45,changeThreshold:.05,deviationDepth:20,deviationFactor:.5,extremumInterval:5}}},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1,lowLatencyActiveLiveDelay:3e3,activeLiveDelay:5e3,maxPausedTime:5e3},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,forceFormat:void 0,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:"07A4434E",useWebmBigRequest:!1,webmCodec:"vp9",androidPreferredFormat:"dash",iosPreferredFormat:"hls",preferCMAF:!1,preferWebRTC:!1,preferMultiStream:!1,preferHDR:!1,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,seekNearDurationBias:1,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useHlsJs:!1,useNativeHLSTextTracks:!1,useNewSwitchTo:!1,useNewDashProvider:!1,useNewAutoSelectVideoTrack:!1,useSafariEndlessRequestBugfix:!0,useRefactoredSearchGap:!1,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,manifestRetryInterval:300,manifestRetryMaxInterval:1e4,manifestRetryMaxCount:10,audioVideoSyncRate:20,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50},useVolumeMultiplier:!1,ignoreAudioRendererError:!1,useEnableSubtitlesParam:!1,useHlsLiveNewTextManager:!1,exposeInternalsToGlobal:!1,hlsLiveNewTextManagerDownloadThreshold:4e3,disableYandexPiP:!1,asyncResolveClientChecker:!1,autostartOnlyIfVisible:!1,changePlaybackStateToPausedWhenEnded:!1},LE=a=>{var e;return{...FV(a,kE),configName:[...(e=a.configName)!=null?e:[],...kE.configName]}};import{assertNonNullable as uu,combine as _t,ErrorCategory as lu,filter as U,filterChanged as Y,fromEvent as rp,isNonNullable as CE,isNullable as WV,Logger as GV,map as G,mapTo as BE,merge as ni,now as cu,once as j,Subject as W,Subscription as VE,tap as ap,ValueSubject as C,isHigher as zV,isInvariantQuality as _E,flattenObject as oi,throttle as sp,getTraceSubscriptionMethod as OE,TracerFactory as YV,InternalsExposure as KV}from"@vkontakte/videoplayer-shared/es2018";import{merge as NV,map as qV,filter as $E,isNonNullable as UV}from"@vkontakte/videoplayer-shared/es2018";var ip=({seekState:a,position$:e})=>NV(a.stateChangeEnded$.pipe(qV(({to:t})=>{var i;return t.state==="none"?void 0:((i=t.position)!=null?i:NaN)/1e3}),$E(UV)),e.pipe($E(()=>a.getState().state==="none")));import{assertNonNullable as HV}from"@vkontakte/videoplayer-shared/es2018";var ME=a=>{let e=typeof a.container=="string"?document.getElementById(a.container):a.container;return HV(e,`Wrong container or containerId {${a.container}}`),e};import{filter as jV,once as QV}from"@vkontakte/videoplayer-shared/es2018";var DE=(a,e,t,i)=>{a!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&(t==null?void 0:t.getValue().length)===0?t.pipe(jV(r=>r.length>0),QV()).subscribe(r=>{r.find(i)&&e.startTransitionTo(a)}):(a===void 0||t!=null&&t.getValue().find(i))&&e.startTransitionTo(a)};var du=class{constructor(e={configName:[]},t=YV.createRootTracer(!1)){this.subscription=new VE;this.logger=new GV;this.abrLogger=this.logger.createComponentLog("ABR");this.internalsExposure=null;this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new C(!1);this.hasLiveOffsetByPausedTimer=0;this.playerInitRequest=0;this.playerInited=new C(!1);this.wasSetStartedQuality=!1;this.desiredState={playbackState:new H("stopped"),seekState:new H({state:"none"}),volume:new H({volume:1,muted:!1}),videoTrack:new H(void 0),videoStream:new H(void 0),audioStream:new H(void 0),autoVideoTrackSwitching:new H(!0),autoVideoTrackLimits:new H({}),isLooped:new H(!1),isLowLatency:new H(!1),playbackRate:new H(1),externalTextTracks:new H([]),internalTextTracks:new H([]),currentTextTrack:new H(void 0),textTrackCuesSettings:new H({}),cameraOrientation:new H({x:0,y:0})};this.info={playbackState$:new C(void 0),position$:new C(0),duration$:new C(1/0),muted$:new C(!1),volume$:new C(1),availableVideoStreams$:new C([]),currentVideoStream$:new C(void 0),availableQualities$:new C([]),availableQualitiesFps$:new C({}),currentQuality$:new C(void 0),isAutoQualityEnabled$:new C(!0),autoQualityLimitingAvailable$:new C(!1),autoQualityLimits$:new C({}),predefinedQualityLimitType$:new C("unknown"),availableAudioStreams$:new C([]),currentAudioStream$:new C(void 0),availableAudioTracks$:new C([]),isAudioAvailable$:new C(!0),currentPlaybackRate$:new C(1),currentBuffer$:new C({start:0,end:0}),isBuffering$:new C(!0),isStalled$:new C(!1),isEnded$:new C(!1),isLooped$:new C(!1),isLive$:new C(void 0),isLiveEnded$:new C(null),canPlayLiveTailBuffer$:new C(!1),canChangePlaybackSpeed$:new C(void 0),atLiveEdge$:new C(void 0),atLiveDurationEdge$:new C(void 0),liveTime$:new C(void 0),liveBufferTime$:new C(void 0),liveLatency$:new C(void 0),currentFormat$:new C(void 0),availableTextTracks$:new C([]),currentTextTrack$:new C(void 0),throughputEstimation$:new C(void 0),rttEstimation$:new C(void 0),videoBitrate$:new C(void 0),hostname$:new C(void 0),httpConnectionType$:new C(void 0),httpConnectionReused$:new C(void 0),surface$:new C("none"),chromecastState$:new C("NOT_AVAILABLE"),chromecastDeviceName$:new C(void 0),intrinsicVideoSize$:new C(void 0),availableSources$:new C(void 0),is3DVideo$:new C(!1),currentVideoSegmentLength$:new C(0),currentAudioSegmentLength$:new C(0)};this.events={inited$:new W,ready$:new W,started$:new W,playing$:new W,paused$:new W,stopped$:new W,willReady$:new W,willStart$:new W,willResume$:new W,willPause$:new W,willStop$:new W,willDestruct$:new W,watchCoverageRecord$:new W,watchCoverageLive$:new W,managedError$:new W,fatalError$:new W,fetcherRecoverableError$:new W,ended$:new W,looped$:new W,seeked$:new W,willSeek$:new W,autoplaySoundProhibited$:new W,manifestRequested$:new W,manifestReceived$:new W,firstBytesRequested$:new W,firstBytesReceived$:new W,firstBytes$:new W,loadedMetadata$:new W,firstFrame$:new W,canplay$:new W,log$:new W,fetcherError$:new W,severeStallOccured$:new W};this.experimental={element$:new C(void 0),tuningConfigName$:new C([]),enableDebugTelemetry$:new C(!1),dumpTelemetry:PS,getCurrentTime$:new C(null)};if(this.initLogs(),this.tuning=LE(e),this.tracer=t,this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new un({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new RE(this.tuning.throughputEstimator),e.exposeInternalsToGlobal&&(this.internalsExposure=new KV("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(f=>JSON.stringify(f,(p,h)=>{let m=typeof h;return(0,FE.default)(["number","string","boolean"],m)?h:h===null?null:`<${m}>`})),c=`Player.${String(r)}`,d=`Exception calling ${c} (${l.join(", ")})`;throw this.events.fatalError$.next({id:c,category:lu.WTF,message:d,thrown:u}),u}}}})}initVideo(e){var s;this.config=e,(s=this.internalsExposure)==null||s.expose({config:e,logger:this.logger,tuning:this.tuning}),this.setMuted(this.tuning.isAudioDisabled);let t=()=>{var u,l,c;let{container:n,...o}=e;this.tracer.log("initVideo",oi(o)),this.domContainer=ME(e),this.chromecastInitializer.contentId=(u=e.meta)==null?void 0:u.videoId,this.providerContainer=new Ns({sources:e.sources,meta:(l=e.meta)!=null?l:{},failoverHosts:(c=e.failoverHosts)!=null?c:[],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?F.isInited$.pipe(U(n=>!!n),j()).subscribe(()=>{console.log("Core SDK async start"),i()}):i()};return this.isNotActiveTabCase()?(this.tracer.log("request play from hidden tab"),rp(document,"visibilitychange").pipe(j()).subscribe(r)):r(),this}destroy(){var e,t;this.tracer.log("destroy"),window.clearTimeout(this.hasLiveOffsetByPausedTimer),this.playerInitRequest&&window.cancelAnimationFrame(this.playerInitRequest),this.events.willDestruct$.next(),this.stop(),(e=this.providerContainer)==null||e.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe(),this.tracer.end(),(t=this.internalsExposure)==null||t.destroy()}prepare(){return this.subscription.add(this.playerInited.pipe(U(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(U(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(U(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(U(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(U(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(U(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(U(i=>!!i),j()).subscribe(()=>{var o;let i=this.desiredState.volume,r=i.getTransition(),s=(o=r==null?void 0:r.to.muted)!=null?o:this.info.muted$.getValue(),n=t!=null?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(U(i=>!!i),j()).subscribe(()=>{var o;let i=this.desiredState.volume,r=this.tuning.isAudioDisabled&&!t||e,s=i.getTransition(),n=(o=s==null?void 0:s.to.volume)!=null?o: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(U(t=>!!t),j()).subscribe(()=>{this.desiredState.videoStream.startTransitionTo(e)})),this}setAudioStream(e){return this.subscription.add(this.playerInited.pipe(U(t=>!!t),j()).subscribe(()=>{this.desiredState.audioStream.startTransitionTo(e)})),this}setQuality(e){return this.subscription.add(this.playerInited.pipe(U(t=>!!t),j()).subscribe(()=>{uu(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(U(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(U(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(U(t=>!!t),j()).subscribe(()=>{this.tracer.log("setAutoQualityLimits",oi(e)),this.desiredState.autoVideoTrackLimits.startTransitionTo(e)})),this}setPredefinedQualityLimits(e){return this.subscription.add(this.playerInited.pipe(U(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(U(t=>!!t),j()).subscribe(()=>{var i;uu(this.providerContainer);let t=(i=this.providerContainer)==null?void 0:i.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(U(t=>!!t),j()).subscribe(()=>{e.length&&this.tracer.log("setExternalTextTracks",oi(e)),this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>({type:"external",...t})))})),this}selectTextTrack(e){return this.subscription.add(this.playerInited.pipe(U(t=>!!t),j()).subscribe(()=>{var t;DE(e,this.desiredState.currentTextTrack,(t=this.providerContainer)==null?void 0:t.providerOutput.availableTextTracks$,i=>i.id===e),this.tracer.log("selectTextTrack",{textTrackId:e})})),this}setTextTrackCueSettings(e){return this.subscription.add(this.playerInited.pipe(U(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(U(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(U(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(U(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(U(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(U(e=>e),j()).subscribe(()=>{let e=this.getScene3D();e&&e.holdCamera()})),this}releaseCamera(){return this.subscription.add(this.playerInited.pipe(U(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(WV(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),i=t.state==="none"?void 0:t.position;return CE(i)?i/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}getScene3D(){var t,i;let e=(t=this.providerContainer)==null?void 0:t.current$.getValue();if((i=e==null?void 0:e.provider)!=null&&i.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(ni(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(xc(e,t,i))})),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(U(({from:e})=>e==="stopped"),j()).subscribe(()=>{this.initedAt=cu(),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",oi(n)),n.state==="requested"?this.desiredState.seekState.setState({...n,state:"applying"}):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:lu.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",oi(n)),n.state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe(G(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(G(n=>n.destination),Y()).subscribe(()=>this.isPlaybackStarted=!1)).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add(_t({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)=>_E(u)?1:_E(l)?-1:zV(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(Y()).subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.pipe(U(n=>CE(n))).subscribe(n=>{this.info.currentQuality$.next(n==null?void 0:n.quality),this.info.videoBitrate$.next(n==null?void 0:n.bitrate)})).add(e.providerOutput.currentVideoSegmentLength$.pipe(Y((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.pipe(Y((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe(Y()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(Y()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(Y()).subscribe(this.info.httpConnectionReused$)).add(e.providerOutput.currentTextTrack$.subscribe(this.info.currentTextTrack$)).add(e.providerOutput.availableTextTracks$.subscribe(this.info.availableTextTracks$)).add(e.providerOutput.autoVideoTrackLimitingAvailable$.subscribe(this.info.autoQualityLimitingAvailable$)).add(e.providerOutput.autoVideoTrackLimits$.subscribe(n=>{this.desiredState.autoVideoTrackLimits.setState(n!=null?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(ap(n=>n&&this.stop())).subscribe(this.info.isLiveEnded$)).add(e.providerOutput.canPlayLiveTailBuffer$.subscribe(this.info.canPlayLiveTailBuffer$)).add(e.providerOutput.canChangePlaybackSpeed$.subscribe(this.info.canChangePlaybackSpeed$)).add(e.providerOutput.liveTime$.subscribe(this.info.liveTime$)).add(e.providerOutput.liveBufferTime$.subscribe(this.info.liveBufferTime$)).add(e.providerOutput.liveLatency$.subscribe(this.info.liveLatency$)).add(_t({hasLiveOffsetByPaused:ni(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(G(n=>n.to),Y(),G(n=>n==="paused")),isLowLatency:e.providerOutput.isLowLatency$}).subscribe(({hasLiveOffsetByPaused:n,isLowLatency:o})=>{if(window.clearTimeout(this.hasLiveOffsetByPausedTimer),n){this.hasLiveOffsetByPausedTimer=window.setTimeout(()=>{this.hasLiveOffsetByPaused.next(!0)},this.getActiveLiveDelay(o));return}this.hasLiveOffsetByPaused.next(!1)})).add(_t({atLiveEdge:_t({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:ip({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}),Y(),ap(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(G(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add(_t({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),Y(),ap(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(G(n=>n.muted),Y()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(G(n=>n.volume),Y()).subscribe(this.info.volume$)).add(ip({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(ni(e.providerOutput.endedEvent$.pipe(BE(!0)),e.providerOutput.seekedEvent$.pipe(BE(!1))).pipe(Y()).subscribe(this.info.isEnded$)).add(e.providerOutput.endedEvent$.subscribe(this.events.ended$)).add(e.providerOutput.loopedEvent$.subscribe(this.events.looped$)).add(e.providerError$.subscribe(this.events.managedError$)).add(e.providerOutput.fetcherRecoverableError$.subscribe(this.events.fetcherRecoverableError$)).add(e.providerOutput.fetcherError$.subscribe(this.events.fatalError$)).add(e.volumeMultiplierError$.subscribe(this.events.managedError$)).add(e.noAvailableProvidersError$.pipe(G(n=>({id:n?`No${n}`:"NoProviders",category:lu.VIDEO_PIPELINE,message:n?`${n} was forced but failed or not available`:"No suitable providers or all providers failed"}))).subscribe(this.events.fatalError$)).add(e.providerOutput.element$.subscribe(this.experimental.element$)).add(e.providerOutput.getCurrentTime$.subscribe(this.experimental.getCurrentTime$)).add(e.providerOutput.manifestRequested$.pipe(j()).subscribe(this.events.manifestRequested$)).add(e.providerOutput.manifestReceived$.pipe(j()).subscribe(this.events.manifestReceived$)).add(e.providerOutput.firstBytesRequested$.pipe(j()).subscribe(this.events.firstBytesRequested$)).add(e.providerOutput.firstBytesReceived$.pipe(j()).subscribe(this.events.firstBytesReceived$)).add(e.providerOutput.firstBytesEvent$.pipe(j(),G(n=>n!=null?n:cu()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe(j(),G(()=>cu()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(j(),G(()=>cu()-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 C(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let i=new C(!0);this.subscription.add(e.current$.subscribe(()=>i.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(U(({to:n})=>n==="playing"),j()).subscribe(()=>i.next(!1)));let r=0,s=ni(e.providerOutput.isBuffering$,t,i).pipe(G(()=>{let n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||i.getValue();return n&&!o}),Y());this.subscription.add(s.subscribe(n=>{n?r=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(r),this.info.isStalled$.next(!1))})),this.subscription.add(ni(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{let n=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:n==null?void 0:n.videoWidth,height:n==null?void 0:n.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{var u,l;let o=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:(u=n==null?void 0:n.size)==null?void 0:u.width,height:(l=n==null?void 0:n.size)==null?void 0:l.height},{width:o==null?void 0:o.videoWidth,height:o==null?void 0:o.videoHeight})})).add(e.providerOutput.is3DVideo$.subscribe(this.info.is3DVideo$)),this.subscription.add(ni(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==null?void 0:e.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){let t=new VE;this.subscription.add(t),this.subscription.add(e.current$.pipe(Y((i,r)=>i.provider===r.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(U(i=>i.length>0),j()).subscribe(i=>{this.setStartingVideoTrack(i)}))}))}setStartingVideoTrack(e){var r;let t;this.wasSetStartedQuality=!0;let i=(r=this.explicitInitialQuality)!=null?r:this.info.currentQuality$.getValue();i&&(t=e.find(({quality:s})=>s===i),t||this.setAutoQuality(!0)),t||(t=St(e,{container:this.domContainer.getBoundingClientRect(),panelSize:this.config.panelSize,estimatedThroughput:this.throughputEstimator.throughput$.getValue(),tuning:this.tuning.autoTrackSelection,limits:this.desiredState.autoVideoTrackLimits.getState(),playbackRate:this.info.currentPlaybackRate$.getValue(),forwardBufferHealth:0,abrLogger:this.abrLogger})),this.desiredState.videoTrack.startTransitionTo(t),this.info.currentQuality$.next(t.quality),this.info.videoBitrate$.next(t.bitrate)}initLogs(){this.subscription.add(ni(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(){var t;let e=(t=this.providerContainer)==null?void 0:t.providerOutput;uu(this.providerContainer),uu(e),AS(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(i=>wS(i)),this.providerContainer.current$.subscribe(({type:i})=>Ra("provider",i)),e.duration$.subscribe(i=>Ra("duration",i)),e.availableVideoTracks$.pipe(U(i=>!!i.length),j()).subscribe(i=>Ra("tracks",i)),this.events.fatalError$.subscribe(new ke("fatalError")),this.events.managedError$.subscribe(new ke("managedError")),e.position$.subscribe(new ke("position")),e.currentVideoTrack$.pipe(G(i=>i==null?void 0:i.quality)).subscribe(new ke("quality")),this.info.currentBuffer$.subscribe(new ke("buffer")),e.isBuffering$.subscribe(new ke("isBuffering"))].forEach(i=>this.subscription.add(i)),Ra("codecs",F.video.supportedCodecs)}initTracerSubscription(){let e=OE(this.tracer.log.bind(this.tracer)),t=OE(this.tracer.error.bind(this.tracer));this.subscription.add(this.info.playbackState$.subscribe(e("playbackState"))).add(this.info.isLooped$.subscribe(e("isLooped"))).add(this.info.currentPlaybackRate$.pipe(Y()).subscribe(e("currentPlaybackRate"))).add(this.info.isAutoQualityEnabled$.subscribe(e("isAutoQualityEnabled"))).add(this.info.autoQualityLimits$.subscribe(e("autoQualityLimits"))).add(this.info.currentFormat$.subscribe(e("currentFormat"))).add(this.info.availableQualities$.subscribe(e("availableQualities"))).add(this.info.availableQualitiesFps$.subscribe(e("availableQualitiesFps"))).add(this.info.availableAudioTracks$.subscribe(e("availableAudioTracks"))).add(this.info.isAudioAvailable$.subscribe(e("isAudioAvailable"))).add(_t({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe(U(({currentQuality:i,videoBitrate:r})=>!!i&&!!r),Y((i,r)=>i.currentQuality===r.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe(U(i=>i>0),Y()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe(U(i=>i>0),Y()).subscribe(e("currentAudioSegmentLength"))).add(this.info.hostname$.subscribe(e("hostname"))).add(this.info.currentTextTrack$.subscribe(e("currentTextTrack"))).add(this.info.availableTextTracks$.subscribe(e("availableTextTracks"))).add(this.info.autoQualityLimitingAvailable$.subscribe(e("autoQualityLimitingAvailable"))).add(_t({currentBuffer:this.info.currentBuffer$.pipe(U(i=>i.end>0),Y((i,r)=>i.end===r.end&&i.start===r.start)),position:this.info.position$.pipe(Y())}).pipe(sp(1e3)).subscribe(e("currentBufferAndPosition"))).add(this.info.duration$.pipe(Y()).subscribe(e("duration"))).add(this.info.isBuffering$.subscribe(e("isBuffering"))).add(this.info.isLive$.pipe(Y()).subscribe(e("isLive"))).add(this.info.canChangePlaybackSpeed$.pipe(Y()).subscribe(e("canChangePlaybackSpeed"))).add(_t({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe(U(({liveTime:i,liveBufferTime:r})=>!!i&&!!r),sp(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe(Y(),U(i=>i===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe(Y(),U(i=>i===!0)).subscribe(e("atLiveDurationEdge"))).add(this.info.muted$.pipe(Y()).subscribe(e("muted"))).add(this.info.volume$.pipe(Y()).subscribe(e("volume"))).add(this.info.isEnded$.pipe(Y(),U(i=>i===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add(_t({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe(U(({throughputEstimation:i,rtt:r})=>!!i&&!!r),sp(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe(Y(),U(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==null||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:lu.DOM,message:String(r)})})};this.subscription.add(ni(rp(document,"visibilitychange"),rp(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{let r=document.visibilityState==="visible",s=this.desiredState.playbackState.getState()==="playing",n=!!e&&!(e!=null&&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",oi({quality:t,availableTracks:oi(e),track:oi(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&&!Ba()}};import{Subscription as S7,Observable as y7,Subject as T7,ValueSubject as I7,VideoQuality as E7}from"@vkontakte/videoplayer-shared/es2018";var x7=`@vkontakte/videoplayer-core@${Qp}`;export{en as ChromecastState,gu as HttpConnectionType,y7 as Observable,$e as PlaybackState,du as Player,tn as PredefinedQualityLimits,x7 as SDK_VERSION,T7 as Subject,S7 as Subscription,vu as Surface,Qp as VERSION,I7 as ValueSubject,At as VideoFormat,E7 as VideoQuality,U$ as areValidLiveRecordSources,F as clientChecker,Ea as isMobile};
178
+ `;var Or=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 Uo(this.params.fov,this.params.orientation),this.cameraRotationManager=new jo(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(bI,this.gl.VERTEX_SHADER),i=this.createShader(gI,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,f=t+r;return[s,n,o,u,l,c,d,f]}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 FB,now as Is,once as NB,Subscription as qB,ValueSubject as bd,isNonNullable as UB,safeStorage as gd,filterChanged as jB}from"@vkontakte/videoplayer-shared/es2018";var Ho="stalls_manager_metrics",Sd="stalls_manager_abr_params",SI="stalls_manager_default_tuning_abr_params",vd=class{constructor(){this.isSeeked$=new bd(!1);this.isBuffering$=new bd(!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 qB;this.severeStallOccurred$=new bd(!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(Sd):{};return{...this.abrParams,...e}}set lastVideoTrackSelected(e){var t;((t=this.lastUniqueVideoTrackSelected)==null?void 0:t.id)!==e.id&&(this.lastUniqueVideoTrackSelected=e,this.lastUniqueVideoTrackSelectedTimestamp=Is(),this.currentStallsCount=0)}destroy(){window.clearTimeout(this.qualityRestrictionTimer),this.subscription.unsubscribe(),this.currentStallDuration$.getValue()!==0&&this.updateStallData();let e=(Is()-this.providerStartWatchingTimestamp-this.sumStallsDuration)/1e3,t=this.sumStallsDuration;this.addStallInfoToHistory(e,t),this.updateStoredAbrParams()}resetStoredAbrParamsIfNeeded(){let{bitrateFactorAtEmptyBuffer:e,bitrateFactorAtFullBuffer:t,containerSizeFactor:i}={...this.getStoredData(SI)},{bitrateFactorAtEmptyBuffer:r,bitrateFactorAtFullBuffer:s,containerSizeFactor:n}={...this.abrParams};this.tuning.enabled&&e===r&&t===s&&i===n||(this.removeStoredData(Sd),this.setStoredData(SI,{bitrateFactorAtEmptyBuffer:r,bitrateFactorAtFullBuffer:s,containerSizeFactor:n}))}updateStoredAbrParams(){let e=[],t=this.getStoredData(Ho,"[]");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(Ho,[]),this.setStoredData(Sd,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="{}"){var i;return JSON.parse((i=gd.get(e))!=null?i:t)}setStoredData(e,t){gd.set(e,JSON.stringify(t))}removeStoredData(e){gd.remove(e)}addStallInfoToHistory(e,t){if(e<this.tuning.minTvtToBeCounted||e>this.tuning.maxTvtToBeCounted||e*1e3<t)return;let i=this.getStoredData(Ho,"[]"),r=t/e,s=i.length?Dt(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(Ho,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(NB()).subscribe(t=>this.providerStartWatchingTimestamp=Is())),this.subscription.add(this.currentStallDuration$.pipe(jB()).subscribe(t=>{let{stallDurationNoDataBeforeQualityDecrease:i,stallCountBeforeQualityDecrease:r,resetQualityRestrictionTimeout:s,ignoreStallsOnSeek:n}=this.tuning;if(FB(this.lastUniqueVideoTrackSelected)||n&&this.isSeeked$.getValue())return;let o=this.rtt$.getValue(),u=this.throughput$.getValue(),l=this.videoLastDataObtainedTimestamp$.getValue(),c=Is(),d=r&&this.currentStallsCount>=r,f=i&&c-this.lastUniqueVideoTrackSelectedTimestamp>=i+o&&c-l>=i+o&&t>=i;(d||f)&&(this.severeStallOccurred$.next(!0),window.clearTimeout(this.qualityRestrictionTimer),this.maxQualityLimit=this.lastUniqueVideoTrackSelected.quality,UB(this.lastUniqueVideoTrackSelected.bitrate)&&u>this.lastUniqueVideoTrackSelected.bitrate&&(this.predictedThroughputWithoutData=this.lastUniqueVideoTrackSelected.bitrate)),!t&&Is()-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}))}},Qo=vd;import{combine as HB,map as QB,observeElementSize as GB,Subscription as WB,ValueSubject as yd,noop as zB}from"@vkontakte/videoplayer-shared/es2018";var Go=class{constructor(){this.subscription=new WB;this.pipSize$=new yd(void 0);this.videoSize$=new yd(void 0);this.elementSize$=new yd(void 0);this.pictureInPictureWindowRemoveEventListener=zB}connect({observableVideo:e,video:t}){let i=r=>{let s=r.target;this.pipSize$.next({width:s.width,height:s.height})};this.subscription.add(GB(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(HB({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe(QB(({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 _i=class{constructor(e){this.subscription=new i0;this.videoState=new j("stopped");this.observableVideo=null;this.droppedFramesManager=new Er;this.stallsManager=new Qo;this.elementSizeManager=new Go;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new Xt;this.audioTrackSwitchHistory=new Xt;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==null?void 0: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"),$(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"),$(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="ready"&&$(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==null?void 0:i.to)==="playing"&&$(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&$(this.params.desiredState.playbackState,"paused");return;default:return KB(e)}}};this.init3DScene=e=>{var i,r,s;if(this.scene3D)return;this.scene3D=new Or(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:((i=e.projectionData)==null?void 0:i.pose.yaw)||0,y:((r=e.projectionData)==null?void 0:r.pose.pitch)||0,z:((s=e.projectionData)==null?void 0:s.pose.roll)||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});let t=this.elementSizeManager.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};this.textTracksManager=new Xe(e.source.url),this.params=e,this.video=Be(e.container,e.tuning),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Ie(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 qo({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode,tracer:this.tracer,forceVideoCodec:this.params.forceVideoCodec}),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params;t0(this.observableVideo)&&(this.observableVideo=Oe(this.video),this.subscription.add(()=>{var n;return(n=this.observableVideo)==null?void 0:n.destroy()}));let i=this.constructor.name,r=n=>{e.error$.next({id:i,category:vI.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(Td(l=>!!l.length),TI()).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(xs(l=>l.to.state!=="none"),Es());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(Td(yI),TI()),e.firstBytesEvent$),s(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),s(this.videoState.stateChangeEnded$.pipe(xs(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(bt(this.video,t.isLooped,r)),this.subscription.add(_e(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Ke(this.video,t.playbackRate,i.playbackRateState$,r)),this.elementSizeManager.connect({video:this.video,observableVideo:i}),s(Je(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),$(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),$(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.params.tuning.changePlaybackStateToPausedWhenEnded&&this.subscription.add(i.ended$.subscribe(()=>{this.videoState.setState("paused"),$(t.playbackState,"paused")})),this.subscription.add(this.player.manifestRequested.subscribe(this.params.output.manifestRequested$)).add(this.player.manifestReceived.subscribe(this.params.output.manifestReceived$)).add(this.player.firstBytesRequested.subscribe(this.params.output.firstBytesRequested$)).add(this.player.firstBytesReceived.subscribe(this.params.output.firstBytesReceived$)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:l})=>{if(l==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let c=this.player.getStreams(),d=this.player.getCodecs();if(XB(c,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let p=[];for(let h of c.audio){p.push(id(h));let m=[];for(let S of h.representations){let b=eI(S);m.push(b),this.audioTracksMap.set(b,{stream:h,representation:S})}this.audioStreamsMap.set(h,m)}this.params.output.availableAudioStreams$.next(p)}let f=[];for(let p of c.video){f.push(rd(p));let h=[];for(let m of p.representations){let S=hs({...m,streamId:p.id});S&&(h.push(S),this.videoTracksMap.set(S,{stream:p,representation:m}))}this.videoStreamsMap.set(p,h)}this.params.output.availableVideoStreams$.next(f);for(let p of c.text)for(let h of p.representations){let m=tI(p,h);this.textTracksMap.set(m,{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),d!=null&&d.video&&this.params.output.availableVideoCodecs$.next(d.video),d!=null&&d.audio&&this.params.output.availableAudioCodecs$.next(d.audio),this.audioTracksMap.size&&this.textTracksMap.size&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else l==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},r)),this.subscription.add(ws(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$,e0(this.video,"progress")).pipe(Td(()=>this.videoTracksMap.size>0)).subscribe(async()=>{let l=this.player.state$.getState(),c=this.player.state$.getTransition();if(!(0,II.default)(["manifest_ready","running"],l)||c)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let d=this.selectVideoAudioRepresentations();if(!d)return;let[f,p]=d,h=[...this.videoTracksMap.keys()].find(S=>{var b;return((b=this.videoTracksMap.get(S))==null?void 0:b.representation.id)===f.id});yI(h)&&(this.stallsManager.lastVideoTrackSelected=h);let m=this.params.desiredState.autoVideoTrackLimits.getTransition();if(m&&this.params.output.autoVideoTrackLimits$.next(m.to),l==="manifest_ready")await this.player.initRepresentations(f.id,p==null?void 0:p.id,this.params.sourceHls);else if(await this.player.switchRepresentation("video",f.id),p){let S=!!t.audioStream.getTransition();await this.player.switchRepresentation("audio",p.id,S)}},r)),this.subscription.add(JB({videoState:this.videoState.stateChangeEnded$,autoVideoTrackState:ws(Wo([t.autoVideoTrackSwitching.getState()]),t.autoVideoTrackSwitching.stateChangeEnded$.pipe(xs(l=>l.to)))}).pipe(xs(({videoState:l,autoVideoTrackState:c})=>l.to!=="stopped"&&c),Es()).subscribe(l=>this.player.setSmartRepresentationSwitch(l))),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(Es()).subscribe(l=>{let c=[...this.videoTracksMap.entries()].find(([,{representation:m}])=>m.id===l);if(!c){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[d,{stream:f}]=c,p=this.params.desiredState.videoStream.getTransition();p&&p.to&&p.to.id===f.id&&this.params.desiredState.videoStream.setState(p.to),e.currentVideoTrack$.next(d),e.currentVideoStream$.next(rd(f));let h=this.player.calculateDurationFromSegments();h&&this.params.output.duration$.next(h/1e3)},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(Es()).subscribe(l=>{let c=[...this.audioTracksMap.entries()].find(([,{representation:h}])=>h.id===l);if(!c){e.currentAudioStream$.next(void 0);return}let[d,{stream:f}]=c,p=this.params.desiredState.audioStream.getTransition();p&&p.to&&p.to.id===f.id&&this.params.desiredState.audioStream.setState(p.to),e.currentAudioStream$.next(id(f))},r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(l=>{var c,d;if(l!=null&&l.is3dVideo&&((c=this.params.tuning.spherical)!=null&&c.enabled))try{this.init3DScene(l),e.is3DVideo$.next(!0)}catch(f){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${f}`})}else this.destroy3DScene(),(d=this.params.tuning.spherical)!=null&&d.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(xs(({to:l})=>l==="ready"),Es());this.subscription.add(ws(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,Wo(["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(ws(o,this.player.state$.stateChangeEnded$,Wo(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let u=ws(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Wo(["init"])).pipe(ZB(0));this.subscription.add(u.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){var P,V,D,_,K,J,E,k,x,A,B,ne,Ne;if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?La:ka,t=this.params.tuning.useNewAutoSelectVideoTrack?fo:ho,i=this.params.tuning.useNewAutoSelectVideoTrack?vt:po,{desiredState:r,output:s}=this.params,n=r.autoVideoTrackSwitching.getState(),o=(P=r.videoTrack.getState())==null?void 0:P.id,l=[...this.videoTracksMap.keys()].find(({id:ie})=>ie===o),c=s.currentVideoTrack$.getValue(),d=((_=(D=r.videoStream.getState())!=null?D:l&&((V=this.videoTracksMap.get(l))==null?void 0:V.stream))!=null?_:this.videoStreamsMap.size===1)?this.videoStreamsMap.keys().next().value:void 0;if(!d)return;let f=[...this.videoStreamsMap.keys()].find(({id:ie})=>ie===d.id),p=f&&this.videoStreamsMap.get(f);if(!p)return;let h=Ee(this.video.buffered,this.video.currentTime*1e3),m;this.player.isActiveLive$.getValue()?m=this.player.isLowLatency$.getValue()?this.params.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.params.tuning.dashCmafLive.normalizedLiveMinBufferSize:this.player.isLive$.getValue()?m=this.params.tuning.dashCmafLive.normalizedTargetMinBufferSize:m=n?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;let S=(this.video.duration*1e3||1/0)-this.video.currentTime*1e3,b=Math.min(h/Math.min(m,S||1/0),1),v=(K=r.audioStream.getState())!=null?K:this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0,T=(J=[...this.audioStreamsMap.keys()].find(({id:ie})=>ie===(v==null?void 0:v.id)))!=null?J:this.audioStreamsMap.keys().next().value,y=0;if(T){if(l&&!n){let ie=e(l,p,(E=this.audioStreamsMap.get(T))!=null?E:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);y=Math.max(y,(k=ie==null?void 0:ie.bitrate)!=null?k:-1/0)}if(c){let ie=e(c,p,(x=this.audioStreamsMap.get(T))!=null?x:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);y=Math.max(y,(A=ie==null?void 0:ie.bitrate)!=null?A:-1/0)}}let I=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:y,forwardBufferHealth:b,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}),w=n?I!=null?I:l:l!=null?l:I,L=T&&t(w,p,(B=this.audioStreamsMap.get(T))!=null?B:[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.stallsManager.abrTuningParams,forwardBufferHealth:b,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),M=(ne=this.videoTracksMap.get(w))==null?void 0:ne.representation,R=L&&((Ne=this.audioTracksMap.get(L))==null?void 0:Ne.representation);if(M&&R)return[M,R];if(M&&!R&&this.audioTracksMap.size===0)return[M,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){Fe(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),$(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:vI.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),Ve(this.video),this.tracer.end()}};var As=class extends _i{subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();i(t.timeUpdate$,e.position$),i(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}};import{combine as Id,merge as EI,filter as xI,filterChanged as wI,isNullable as Ed,map as AI,ValueSubject as xd,isNonNullable as r0}from"@vkontakte/videoplayer-shared/es2018";var Rs=class extends _i{constructor(e){super(e),this.textTracksManager.destroy()}subscribe(){super.subscribe();let e=!1,t=-1,{output:i,observableVideo:r,desiredState:s,connect:n}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canPlayLiveTailBuffer$.next(!0),n(r.timeUpdate$,i.liveBufferTime$),n(this.player.liveSeekableDuration$,i.duration$),n(this.player.liveLatency$,i.liveLatency$);let o=new xd(1);n(r.playbackRateState$,o),this.params.tuning.dashCmafLive.catchupLiveForMutedInactiveTab&&this.subscription.add(i.elementVisible$.pipe(wI()).subscribe(u=>{let l=i.position$.getValue(),c=i.volume$.getValue(),d=!c.volume||c.muted;!u&&!l&&d?e=!0:u&&e&&(this.seek(0),e=!1)})),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(s.isLowLatency.stateChangeEnded$.pipe(AI(u=>u.to)).subscribe(this.player.isLowLatency$)).add(Id({liveBufferTime:i.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(AI(({liveBufferTime:u,liveAvailabilityStartTime:l})=>u&&l?u+l:void 0)).subscribe(i.liveTime$)).add(this.player.liveStreamStatus$.pipe(xI(u=>r0(u))).subscribe(u=>i.isLiveEnded$.next(u!=="active"&&i.position$.getValue()===0))).add(Id({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:EI(r.playbackRateState$,new xd(1))}).pipe(xI(({liveStreamStatus:u,liveDuration:l})=>u==="active"&&!!l)).subscribe(({liveDuration:u,playbackRate:l})=>{let c=i.liveBufferTime$.getValue(),d=i.position$.getValue(),{playbackCatchupSpeedup:f}=this.params.tuning.dashCmafLive.lowLatency;d||l<1-f||this.video.paused||Ed(c)||(t=u-c)})).add(Id({time:i.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:EI(r.playbackRateState$,new xd(1))}).pipe(wI((u,l)=>this.player.liveStreamStatus$.getValue()==="active"?u.liveDuration===l.liveDuration:u.time===l.time)).subscribe(({time:u,liveDuration:l,playbackRate:c})=>{let d=i.position$.getValue(),{playbackCatchupSpeedup:f}=this.params.tuning.dashCmafLive.lowLatency;if(!d&&!this.video.paused&&c>=1-f||Ed(u)||Ed(l))return;let p=-1*(l-u-t);i.position$.next(Math.min(p,0))})).add(this.player.currentLiveTextRepresentation$.subscribe(u=>{if(u){let l=iI(u);this.params.output.availableTextTracks$.next([l])}}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,i=Math.trunc(t/1e3<=Math.abs(this.params.output.duration$.getValue())?t:0);this.player.seekLive(i).then(()=>{this.params.output.position$.next(e/1e3)})}};import{assertNever as L0,assertNonNullable as $0,combine as M0,debounce as D0,ErrorCategory as jI,filter as Nd,filterChanged as _s,fromEvent as C0,isNonNullable as HI,isNullable as B0,map as Os,merge as Fs,observableFrom as au,once as QI,Subscription as V0}from"@vkontakte/videoplayer-shared/es2018";var UI=O(Ae(),1),Od=O(Oa(),1);import{abortable as Cd,assertNonNullable as qr,combine as Ur,ErrorCategory as dt,filter as tu,filterChanged as Cs,flattenObject as Bs,fromEvent as Et,getTraceSubscriptionMethod as y0,interval as Bd,isNonNullable as Vs,isNullable as NI,map as jr,merge as Ui,now as Vd,Subject as ni,Subscription as _d,tap as T0,throttle as qI,ValueSubject as se}from"@vkontakte/videoplayer-shared/es2018";var Xo=O(Ae(),1),qi=O(ot(),1),Jo=O(Oa(),1);var VI=O(Hn(),1);import{assertNever as a0,ErrorCategory as RI,Subject as PI}from"@vkontakte/videoplayer-shared/es2018";var s0=18,kI=!1;try{kI=F.browser.isSafari&&!!F.browser.safariVersion&&F.browser.safariVersion<=s0}catch(a){console.error(a)}var wd=class{constructor(e){this.bufferFull$=new PI;this.error$=new PI;this.queue=[];this.currentTask=null;this.destroyed=!1;this.abortRequested=!1;this.completeTask=()=>{var e;try{if(this.currentTask){let t=(e=this.currentTask.signal)==null?void 0:e.aborted;this.currentTask.callback(!t),this.currentTask=null}this.queue.length&&this.pull()}catch(t){this.error$.next({id:"BufferTaskQueueUnknown",category:RI.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:t})}};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)};kI&&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(){var r;if((this.buffer.updating||this.currentTask||this.destroyed)&&!this.abortRequested)return;let e=this.queue.shift();if(!e)return;if((r=e.signal)!=null&&r.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(s){s instanceof DOMException&&s.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):s instanceof DOMException&&s.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:RI.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:s}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){let{operation:t}=e;switch(t){case"append":this.buffer.appendBuffer(e.data);break;case"remove":this.buffer.remove(e.from/1e3,e.to/1e3);break;case"abort":this.buffer.abort();break;case"safariAbort":{this.buffer.abort(),this.buffer.appendBuffer(e.init);break}default:a0(t)}}},LI=wd;import{abortable as ai,assertNonNullable as Me,ErrorCategory as Fi,fromEvent as Ld,getExponentialDelay as $d,isHigher as c0,isNonNullable as si,isNullable as fe,now as Ko,once as d0,Subject as p0,Subscription as h0,ValueSubject as Ni}from"@vkontakte/videoplayer-shared/es2018";var Ad=O(ot(),1);import{videoSizeToQuality as n0,throttleFn as o0}from"@vkontakte/videoplayer-shared/es2018";var Ps=({id:a,width:e,height:t,bitrate:i,fps:r,quality:s,streamId:n})=>{var u;let o=(u=s?Kt(s):void 0)!=null?u:n0({width:e,height:t});return o&&{id:a,quality:o,bitrate:i,size:{width:e,height:t},fps:r,streamId:n}},$I=({id:a,bitrate:e})=>({id:a,bitrate:e}),MI=({language:a,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:a,label:e}),DI=({language:a,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:a,label:e}),Rd=({id:a,language:e,label:t,codecs:i,isDefault:r})=>({id:a,language:e,label:t,codec:(0,Ad.default)(i.split("."),0),isDefault:r}),Pd=({id:a,language:e,label:t,hdr:i,codecs:r})=>({id:a,language:e,hdr:i,label:t,codec:(0,Ad.default)(r.split("."),0)}),kd=a=>"url"in a,We=a=>a.type==="template";var CI=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},Oi=(a,e)=>{for(let t of a)if(e(t))return t;return null},BI=a=>{let e=!1,t=o0(()=>{e=!0},a);return()=>{try{return t(),e}finally{e=!1}}};import{fromEvent as u0,Subscription as l0}from"@vkontakte/videoplayer-shared/es2018";var zo=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 Yo=class{constructor(e,t){this.lastUpdateTs=0;this.lastCallTs=0;this.prevRanges=[];this.subscription=new l0;this.mediaSource=e,this.sourceBuffer=t,this.subscription.add(u0(this.sourceBuffer,"updateend").subscribe(()=>this.updateend()))}updateend(){if(!N(this.mediaSource,this.sourceBuffer))return;let{prevRanges:e}=this,t=zo(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 ks=class{constructor(e,t,i,{fetcher:r,tuning:s,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new Ni(0);this.currentLowLatencySegmentLength$=new Ni(0);this.currentSegmentLength$=new Ni(0);this.onLastSegment$=new Ni(!1);this.fullyBuffered$=new Ni(!1);this.playingRepresentation$=new Ni(void 0);this.playingRepresentationInit$=new Ni(void 0);this.error$=new p0;this.gaps=[];this.subscription=new h0;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new Z;this.switchAbortController=new Z;this.destroyAbortController=new Z;this.useSmartRepresentationSwitch=!1;this.bufferLimit=1/0;this.failedDownloads=0;this.baseUrls=[];this.baseUrlsIndex=0;this.isLive=!1;this.liveUpdateSegmentIndex=0;this.liveInitialAdditionalOffset=0;this.isSeekingLive=!1;this.index=0;this.lastDataObtainedTimestampMs=0;this.loadByteRangeSegmentsTimeoutId=0;this.sourceBufferBufferedDiff=null;this.startWith=ai(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);Me(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new LI(this.sourceBuffer),this.sourceBufferBufferedDiff=new Yo(this.mediaSource,this.sourceBuffer),this.subscription.add(Ld(this.sourceBuffer,"updateend").subscribe(()=>{this.maintain()})),this.subscription.add(Ld(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:Fi.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o||!N(this.mediaSource,this.sourceBuffer))return;let u=Math.min(this.bufferLimit,Ar(this.sourceBuffer.buffered)*.8);this.bufferLimit=u;let l=Ee(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);Me(i,"No init buffer for starting representation"),Me(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=ai(this.destroyAbortController.signal,async function*(e,t=!1){if(!N(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);Me(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if(fe(s)||fe(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),Me(r,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!N(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();si(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=ai(this.destroyAbortController.signal,async function*(e,t=!1){if(!N(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);Me(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if(fe(s)||fe(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),Me(r,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!N(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();si(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=ai(this.destroyAbortController.signal,async function*(e){var u,l;let t=(u=(0,Jo.default)(e,c=>c.representations))!=null?u:[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let c of this.representations.keys()){let d=t.find(h=>h.id===c);d&&this.representations.set(c,d);let f=this.representations.get(c);if(!f||!We(f.segmentReference))return;let p=this.getActualLiveStartingSegments(f.segmentReference);this.segments.set(f.id,p)}let i=(l=this.switchingToRepresentationId)!=null?l:this.downloadingRepresentationId,r=this.representations.get(i);Me(r);let s=this.segments.get(i);Me(s,"No segments for starting representation");let n=this.initData.get(i);if(Me(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));var c;this.fetcher=r,this.tuning=s,this.compatibilityMode=u,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=o,this.isLive=!!(l!=null&&l.live),this.baseUrls=(c=l==null?void 0:l.baseUrls)!=null?c:[],this.initData=new Map(i.map(d=>[d.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(i.map(d=>[d.id,d])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}switchToWithPreviousAbort(e,t=!1){!N(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new Z,ai(this.switchAbortController.signal,async function*(i,r=!1){this.switchingToRepresentationId=i;let s=this.representations.get(i);Me(s,`No such representation ${i}`);let n=this.segments.get(i),o=this.initData.get(i);if(fe(o)||fe(n)?yield this.loadInit(s,"high",!1):o instanceof Promise&&(yield o),n=this.segments.get(i),Me(n,"No segments for starting representation"),o=this.initData.get(i),!(!(o instanceof ArrayBuffer)||!this.sourceBuffer||!N(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();si(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(){!fe(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 Z,this.abortBuffer()}maintain(e=this.getCurrentPosition()){var f;if(fe(e)||fe(this.downloadingRepresentationId)||fe(this.playingRepresentationId)||fe(this.sourceBuffer)||!N(this.mediaSource,this.sourceBuffer)||si(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.representations.get(this.playingRepresentationId),r=this.segments.get(this.downloadingRepresentationId),s=this.segments.get(this.playingRepresentationId);if(Me(t,`No such representation ${this.downloadingRepresentationId}`),Me(i,`No such representation ${this.playingRepresentationId}`),fe(r)||fe(s))return;let n=r.find(p=>e>=p.time.from&&e<p.time.to);si(n)&&isFinite(n.time.from)&&isFinite(n.time.to)&&this.currentSegmentLength$.next((n==null?void 0:n.time.to)-n.time.from);let o=e,u=100;if(this.playingRepresentationId!==this.downloadingRepresentationId){let p=this.getForwardBufferDuration(e),h=Ps(i),m=Ps(t),S=this.useSmartRepresentationSwitch&&this.tuning.dash.useNewRepresentationSwitch&&this.tuning.dash.useSmartRepresentationSwitch&&si(h)&&si(m)&&c0(h.quality,m.quality),b=this.useSmartRepresentationSwitch&&this.tuning.dash.useNewRepresentationSwitch&&this.tuning.dash.useDelayedRepresentationSwitch;if(S||b?o+=Math.min(p,this.tuning.dash.representationSwitchForwardBufferGap):n&&n.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&p>=n.time.to-e+u&&(o=n?n.time.to+u:-1/0),this.tuning.dash.useNewRepresentationSwitch){let T=(f=this.segments.entries().map(([y,I])=>{let w=I.find(L=>e>=L.time.from&&e<L.time.to);return{representationId:y,status:w==null?void 0:w.status}}).find(y=>y.status==="fed"))==null?void 0:f.representationId;if(!T)return;this.playingRepresentationId=T,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId))}}if(isFinite(this.bufferLimit)&&Ar(this.sourceBuffer.buffered)>=this.bufferLimit){let p=Ee(this.sourceBuffer.buffered,e),h=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,p<h).catch(m=>{this.handleAsyncError(m,"pruneBuffer")});return}let c=null;if(!this.activeSegments.size&&(c=this.selectForwardBufferSegments(r,t.segmentReference.type,o),c!=null&&c.length)){let p="auto";if(this.tuning.dash.useFetchPriorityHints&&n)if((0,Xo.default)(c,n))p="high";else{let h=(0,qi.default)(c,0);h&&h.time.from-n.time.to>=this.forwardBufferTarget/2&&(p="low")}this.loadSegments(c,t,p).catch(h=>{this.handleAsyncError(h,"loadSegments")})}(!this.preloadOnly&&!this.allInitsLoaded&&n&&n.status==="fed"&&!(c!=null&&c.length)&&Ee(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let d=(0,qi.default)(r,-1);!this.isLive&&d&&(this.fullyBuffered$.next(d.time.to-e-Ee(this.sourceBuffer.buffered,e)<u),this.onLastSegment$.next(e-d.time.from>0))}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}searchGaps(e,t){this.gaps=[];let i=0,r=this.isLive?this.liveInitialAdditionalOffset:0;for(let s of e)Math.trunc(s.time.from-i)>0&&this.gaps.push({representation:t.id,from:i,to:s.time.from+r,persistent:!0}),i=s.time.to;si(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,Jo.default)(e==null?void 0: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!=null&&i.length)return{from:i[0].time.from,to:i[i.length-1].time.to}}updateLive(e){var i,r,s,n;let t=(i=(0,Jo.default)(e==null?void 0:e.streams[this.kind],o=>o.representations))!=null?i:[];if(![...this.segments.values()].every(o=>!o.length))for(let o of t){if(!o||!We(o.segmentReference))return;let u=o.segmentReference.segments.map(p=>({...p,status:"none",size:void 0})),l=100,c=(r=this.segments.get(o.id))!=null?r:[],d=(n=(s=(0,qi.default)(c,-1))==null?void 0:s.time.to)!=null?n:0,f=u==null?void 0:u.findIndex(p=>d>=p.time.from+l&&d<=p.time.to+l);if(f===-1){this.liveUpdateSegmentIndex=0;let p=this.getActualLiveStartingSegments(o.segmentReference);this.segments.set(o.id,p)}else{let p=u.slice(f+1);this.segments.set(o.id,[...c,...p])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;Me(e);let t=this.segments.get(e);if(t!=null&&t.length){let i=t[t.length-1];this.updateLowLatencyLiveIfNeeded(i)}}setSmartRepresentationSwitch(e){this.useSmartRepresentationSwitch=e}updateLowLatencyLiveIfNeeded(e){let t=0;for(let i of this.representations.values()){let r=i.segmentReference;if(!We(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=lt(r.segmentTemplateUrl,{segmentTime:u});s.push({status:"none",time:{from:e.time.to,to:1/0},url:l})}}this.currentLowLatencySegmentLength$.next(t)}findSegmentStartTime(e){var s,n,o;let t=(n=(s=this.switchingToRepresentationId)!=null?s:this.downloadingRepresentationId)!=null?n:this.playingRepresentationId;if(!t)return;let i=this.segments.get(t);if(!i)return;let r=i.find(u=>u.time.from<=e&&u.time.to>=e);return(o=r==null?void 0:r.time.from)!=null?o:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){var e,t;if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),(e=this.sourceBufferTaskQueue)==null||e.destroy(),(t=this.sourceBufferBufferedDiff)==null||t.destroy(),this.gapDetectionIdleCallback&&yt&&yt(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&yt&&yt(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer)try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(i){if(!(i instanceof DOMException&&i.name==="NotFoundError"))throw i}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:f,time:{from:p,to:h}},m)=>{let S=p<=i&&h>=i,b=p>i||S||m===0&&i===0,v=Math.min(this.forwardBufferTarget,this.bufferLimit),T=this.preloadOnly&&p<=i+v||r<v&&h-p>=v||h<=i+v;return(f==="none"||f==="partially_ejected"&&b&&T&&this.sourceBuffer&&N(this.mediaSource,this.sourceBuffer)&&!(xe(this.sourceBuffer.buffered,p)&&xe(this.sourceBuffer.buffered,h)))&&b&&T});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 f=s;f<n.length&&(o<=c||u<=d);f++){let p=n[f];if(o+=p.byte.to+1-p.byte.from,u+=p.time.to+1-p.time.from,p.status==="none"||p.status==="partially_ejected")l.push(p);else break}return l}async loadSegments(e,t,i="auto"){We(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 ai(o,async function*(){let c=$d(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(),bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation});if(this.lastDataObtainedTimestampMs=Ko(),!c)return;let d=new DataView(c),f=Tt(t.mime);if(!isFinite(r.segment.time.to)){let m=t.segmentReference.timescale;r.segment.time.to=f.getChunkEndTime(d,m)}u&&r.feedingBytes&&l?await Promise.all(l):await this.sourceBufferTaskQueue.append(d,o);let{serverDataReceivedTimestamp:p,serverDataPreparedTime:h}=f.getServerLatencyTimestamps(d);p&&h&&this.currentLiveSegmentServerLatency$.next(h-p),r.segment.status="downloaded",this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(c){this.abortActiveSegments([e]),It(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())We(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 ai(n,async function*(){let u=$d(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),Ld(window,"online").pipe(d0()).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,bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation}),this.lastDataObtainedTimestampMs=Ko(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),It(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}prepareByteRangeFetchSegmentParams(e,t){if(We(t.segmentReference))throw new Error("Representation is not byte range type");let i=t.segmentReference.url,r={from:(0,qi.default)(e,0).byte.from,to:(0,qi.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=Ko(),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:Fi.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!We(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=Ko();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:Fi.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,Xo.default)(e,t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:r,signal:s}){if(!this.activeSegments.size||!N(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=Tt(n.mime).parseFeedableSegmentChunk(l,this.isLive);c!=null&&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||!N(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,f=d-c+1,p=c<r,h=d<=r;if(p){if(l.status==="downloading"&&h){l.status="downloaded";let m=new DataView(e.buffer,e.byteOffset+c,f);await this.sourceBufferTaskQueue.append(m,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(f,r-c),u.loadedBytes>u.feedingBytes)){let m=new DataView(e.buffer,e.byteOffset+c+u.feedingBytes,u.loadedBytes-u.feedingBytes),S=u.loadedBytes===f?m:Tt(o.mime).parseFeedableSegmentChunk(m);S!=null&&S.byteLength&&(l.status="partially_fed",u.feedingBytes+=S.byteLength,await this.sourceBufferTaskQueue.append(S,s)&&!s.aborted?(u.fedBytes+=S.byteLength,u.fedBytes===f&&this.onSegmentFullyAppended(u,t)):await n())}}}}onSegmentFullyAppended(e,t){if(!(fe(this.sourceBuffer)||!N(this.mediaSource,this.sourceBuffer))){!this.isLive&&F.browser.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(xe(this.sourceBuffer.buffered,e.segment.time.from,100)&&xe(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:Fi.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",kd(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||(t=n),s===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let i=this.representations.get(e);i&&(this.initLoadIdleCallback=wr(()=>(0,VI.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?ai(this.destroyAbortController.signal,async function*(){let o=$d(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,Tt(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 f=c;this.isLive&&We(e.segmentReference)&&(f=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,f),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:Fi.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||!N(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||fe(e))return!1;this.checkEjectedSegments();let r=[],s=0,n=o=>{var l;if(s>=t)return;r.push({...o.time});let u=kd(o)?(l=o.size)!=null?l: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 f of d)(0,Xo.default)(["none","partially_ejected"],f.status)&&Math.round(f.time.from)<=Math.round(u)&&Math.round(f.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=CI(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||!N(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||!N(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||!N(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||!N(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||fe(e)?0:Ee(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!this.sourceBuffer||!N(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||!N(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=wr(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:Fi.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if(fe(this.sourceBuffer)||!N(this.mediaSource,this.sourceBuffer)||fe(this.playingRepresentationId)||this.sourceBufferBufferedDiff&&!this.sourceBufferBufferedDiff.wasUpdated())return;let e=zo(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],f=e[c+1];u||(u=d-t<=n&&f+t>=o),(n>=d&&n<f-t||o>d+t&&o<=f)&&(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:Fi.VIDEO_PIPELINE,thrown:e,message:"Something went wrong"})}calculateDurationFromSegments(){var t;if(!this.playingRepresentationId)return 0;let e=this.segments.get(this.playingRepresentationId);return(e?(t=(0,qi.default)(e,-1))==null?void 0:t.time.to:0)||0}};import{abortable as Ls,assertNever as _I,fromEvent as OI,merge as f0,now as $s,Subject as Fr,ValueSubject as Md,flattenObject as Nr,ErrorCategory as Ms,SubscriptionRemovable as m0}from"@vkontakte/videoplayer-shared/es2018";var eu=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:s=!1}){this.manifestRequested=new Fr;this.manifestReceived=new Fr;this.firstBytesRequested=new Fr;this.firstBytesReceived=new Fr;this.lastConnectionType$=new Md(void 0);this.lastConnectionReused$=new Md(void 0);this.lastRequestFirstBytes$=new Md(void 0);this.recoverableError$=new Fr;this.error$=new Fr;this.abortAllController=new Z;this.subscription=new m0;this.fetchManifest=Ls(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=ti(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=Po(i)),this.manifestRequested.next();let r=yield this.doFetch(i,{signal:this.abortAllController.signal}).catch(Zo);return r?(t.log("success",Nr({url:i,message:"Request successfully executed"})),t.end(),this.manifestReceived.next(),this.onHeadersReceived(r.headers),r.text()):(t.error("error",Nr({url:i,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=Ls(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,bufferOptimisation:l=!1}={}){var _,K,J;let c=e,d=new Headers,f=this.tracer.createComponentTracer("Fetch");if(i)switch(t){case 0:{d.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let E=new URL(c,location.href);E.searchParams.append("bytes",`${i.from}-${i.to}`),c=E.toString();break}default:_I(t)}this.requestQuic&&(c=ti(c));let p=this.abortAllController.signal,h;if(n){let E=new Z;if(h=f0(OI(this.abortAllController.signal,"abort"),OI(n,"abort")).subscribe(()=>{try{E.abort()}catch(k){Zo(k)}}),this.subscription.add(h),this.abortAllController.signal.aborted||n.aborted)try{E.abort()}catch(k){Zo(k)}p=E.signal}let m=0,S=$s();f.log("startRequest",Nr({url:c,priority:s,rangeMethod:t,range:i,isLowLatency:u,requestStartedAt:S})),this.firstBytesRequested.next();let b=yield this.doFetch(c,{priority:s,headers:d,signal:p}),v=$s();if(!b)return f.error("error",{message:"No response in request"}),f.end(),this.unsubscribeAbortSubscription(h),null;if((_=this.throughputEstimator)==null||_.addRawRtt(v-S),!b.ok||!b.body){this.unsubscribeAbortSubscription(h);let E=`Fetch error ${b.status}: ${b.statusText}`;return f.error("error",{message:E}),f.end(),Promise.reject(new Error(`Fetch error ${b.status}: ${b.statusText}`))}if(this.onHeadersReceived(b.headers),!r&&!o){this.unsubscribeAbortSubscription(h);let E=$s(),k={requestStartedAt:S,requestEndedAt:E,duration:E-S};return f.log("endRequest",Nr(k)),f.end(),b.arrayBuffer()}let T=b.body;if(o){let E;[T,E]=b.body.tee(),(K=this.throughputEstimator)==null||K.trackStream(E,u)}let y=T.getReader(),I,w=parseInt((J=b.headers.get("content-length"))!=null?J:"",10);Number.isFinite(w)&&(I=w),!I&&i&&(I=i.to-i.from+1);let L=I?new Uint8Array(I):new Uint8Array(0),M=!1,R=E=>{this.unsubscribeAbortSubscription(h),M=!0,Zo(E)},P=Ls(p,async function*({done:E,value:k}){if(m===0&&(this.lastRequestFirstBytes$.next($s()-S),this.firstBytesReceived.next()),p.aborted){this.unsubscribeAbortSubscription(h);return}if(!E&&k){if(l&&I)L.set(k,m),m+=k.byteLength;else{let x=new Uint8Array(L.length+k.length);x.set(L),x.set(k,L.length),L=x,m+=k.byteLength}r==null||r(new DataView(L.buffer),m),yield y==null?void 0:y.read().then(P,R)}}.bind(this));yield y==null?void 0:y.read().then(P,R),this.unsubscribeAbortSubscription(h);let V=$s(),D={failed:M,requestStartedAt:S,requestEndedAt:V,duration:V-S};return M?(f.error("endRequest",Nr(D)),f.end(),null):(f.log("endRequest",Nr(D)),f.end(),L.buffer)}.bind(this));this.fetchByteRangeRepresentation=Ls(this.abortAllController.signal,async function*(e,t,i){var b;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 f=new DataView(d,r-n,s-n+1);if(!t.validateData(f))throw new Error("Invalid media file");let p=t.parseInit(f),h=(b=e.indexRange)!=null?b:t.getIndexRange(p);if(!h)throw new ReferenceError("No way to load representation index");let m;if(u)m=new DataView(d,h.from-n,h.to-h.from+1);else{let v=yield this.fetch(e.url,{range:h,priority:i,measureThroughput:!1});if(!v)return null;m=new DataView(v)}let S=t.parseSegments(m,p,h);return{init:p,dataView:new DataView(d),segments:S}}.bind(this));this.fetchTemplateRepresentation=Ls(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}=Ro(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}async fetchRepresentation(e,t,i="auto"){var s,n;let{type:r}=e;switch(r){case"byteRange":return(s=await this.fetchByteRangeRepresentation(e,t,i))!=null?s:null;case"template":return(n=await this.fetchTemplateRepresentation(e,i))!=null?n:null;default:_I(r)}}destroy(){this.abortAllController.abort(),this.tracer.end(),this.subscription.unsubscribe()}async doFetch(e,t){let i=await Ze(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:Ms.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:Ms.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:Ms.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:Ms.FATAL});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${s})`,category:Ms.FATAL})}}unsubscribeAbortSubscription(e){e&&(e.unsubscribe(),this.subscription.remove(e))}},Zo=a=>{if(!It(a))throw a};import{isNullable as b0,ValueSubject as g0}from"@vkontakte/videoplayer-shared/es2018";var Ds=class a{constructor(e,t){this.currentRepresentation$=new g0(null);this.maxRepresentations=4;this.representationsCursor=0;this.representations=[];this.currentSegment=null;this.getCurrentPosition=t.getCurrentPosition,this.processStreams(e)}updateLive(e){this.processStreams(e==null?void 0:e.streams.text)}seekLive(e){this.processStreams(e)}maintain(e=this.getCurrentPosition()){var t;if(!b0(e))for(let i of this.representations)for(let r of i){let s=r.segmentReference,n=s.segments.length,o=s.segments[0].time.from,u=s.segments[n-1].time.to;if(e<o||e>u)continue;let l=s.segments.find(c=>c.time.from<=e&&c.time.to>=e);!l||((t=this.currentSegment)==null?void 0:t.time.from)===l.time.from&&this.currentSegment.time.to===l.time.to||(this.currentSegment=l,this.currentRepresentation$.next({...r,label:"Live Text",language:"ru",isAuto:!0,url:new URL(l.url,s.baseUrl).toString()}))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e!=null?e:[]){let 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!=null&&e.some(t=>a.filterRepresentations(t.representations)))}static filterRepresentations(e){return e==null?void 0:e.filter(t=>t.kind==="text"&&"segmentReference"in t&&We(t.segmentReference))}};var I0=["progress","play","seeked","stalled","waiting"],E0=["timeupdate","progress","loadeddata","playing","seeked"];var iu=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.bufferManagers=[];this.subscription=new _d;this.representationSubscription=new _d;this.state$=new j("none");this.currentVideoRepresentation$=new se(void 0);this.currentVideoRepresentationInit$=new se(void 0);this.currentAudioRepresentation$=new se(void 0);this.currentVideoSegmentLength$=new se(0);this.currentAudioSegmentLength$=new se(0);this.error$=new ni;this.manifestRequested=new ni;this.manifestReceived=new ni;this.firstBytesRequested=new ni;this.firstBytesReceived=new ni;this.lastConnectionType$=new se(void 0);this.lastConnectionReused$=new se(void 0);this.lastRequestFirstBytes$=new se(void 0);this.currentLiveTextRepresentation$=new se(null);this.isLive$=new se(!1);this.isActiveLive$=new se(!1);this.isLowLatency$=new se(!1);this.liveDuration$=new se(0);this.liveSeekableDuration$=new se(0);this.liveAvailabilityStartTime$=new se(0);this.liveStreamStatus$=new se(void 0);this.bufferLength$=new se(0);this.liveLatency$=new se(void 0);this.liveLoadBufferLength$=new se(0);this.livePositionFromPlayer$=new se(0);this.currentStallDuration$=new se(0);this.videoLastDataObtainedTimestamp$=new se(0);this.fetcherRecoverableError$=new ni;this.fetcherError$=new ni;this.liveStreamEndTimestamp=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.forceEnded$=new ni;this.gapWatchdogActive=!1;this.destroyController=new Z;this.initManifest=Cd(this.destroyController.signal,async function*(e,t,i){var r;this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=le(t,i,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),(r=this.manifest)!=null&&r.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:dt.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=Cd(this.destroyController.signal,async function*(){var u,l;this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(c=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:dt.NETWORK,message:"Failed to load manifest",thrown:c})});if(!e)return null;let t=null;try{t=Eo(e!=null?e:"",this.manifestUrlString)}catch(c){let d=(u=To(e))!=null?u:{id:"ManifestParsing",category:dt.PARSER,message:"Failed to parse MPD manifest",thrown:c};this.error$.next(d)}if(!t)return null;let i=(c,d,f)=>{var p,h,m,S;return!!((h=(p=this.element)==null?void 0:p.canPlayType)!=null&&h.call(p,d)&&((S=(m=Qe())==null?void 0:m.isTypeSupported)!=null&&S.call(m,`${d}; codecs="${f}"`))||c==="text")};if(t.live){this.isLive$.next(!!t.live);let{availabilityStartTime:c,latestSegmentPublishTime:d,streamIsUnpublished:f,streamIsAlive:p}=t.live,h=((l=t.duration)!=null?l:0)/1e3;this.liveSeekableDuration$.next(-1*h),this.liveDuration$.next((d-c)/1e3),this.liveAvailabilityStartTime$.next(t.live.availabilityStartTime);let m="active";p||(m=f?"unpublished":"unexpectedly_down"),this.liveStreamStatus$.next(m)}let r={text:t.streams.text,video:[],audio:[]},s,n;for(let c of["video","audio"]){let f=t.streams[c].filter(({mime:h,codecs:m})=>i(c,h,m));r[c]=f;let p;if(this.tuning.dash.codecsPrioritizeEnabled){let h=f.map(({codecs:m})=>m);c==="audio"&&(n=Fo(h),p=n[0]),c==="video"&&(s=Oo(h),this.forceVideoCodec&&(0,UI.default)(s,this.forceVideoCodec)?p=this.forceVideoCodec:p=s[0]),p&&(r[c]=f.filter(({codecs:m})=>Cr(m)===p))}else{let h=new Set(f.map(({codecs:m})=>m));p=_o(h),p&&(r[c]=f.filter(({codecs:m})=>m.startsWith(p)))}if(c==="video"){let h=this.tuning.preferHDR,m=r.video.some(b=>b.hdr),S=r.video.some(b=>!b.hdr);F.display.isHDR&&h&&m?r.video=r.video.filter(b=>b.hdr):S&&(r.video=r.video.filter(b=>!b.hdr))}}let o={...t,streams:r};return this.tuning.dash.codecsPrioritizeEnabled&&(o.codecs={video:s,audio:n}),this.tracer.log("updateManifestEnd",Bs(o)),o}.bind(this));this.initRepresentations=Cd(this.destroyController.signal,async function*(e,t,i){var f;this.tracer.log("initRepresentationsStart",Bs({initialVideo:e,initialAudio:t,sourceHls:i})),qr(this.manifest),qr(this.element),this.representationSubscription.unsubscribe(),this.representationSubscription=new _d,this.state$.startTransitionTo("representations_ready");let r=p=>{this.representationSubscription.add(Et(p,"error").pipe(tu(h=>{var m;return!!((m=this.element)!=null&&m.played.length)})).subscribe(h=>{this.error$.next({id:"VideoSource",category:dt.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:h})}))};this.source=Yn();let s=document.createElement("source");if(r(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),fr())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 ks("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],Vs(t)){let p=this.manifest.streams.audio.reduce((h,m)=>[...h,...m.representations],[]);this.audioBufferManager=new ks("audio",this.source,p,n),this.bufferManagers.push(this.audioBufferManager)}Ds.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new Ds(this.manifest.streams.text,n)),this.representationSubscription.add(this.fetcher.manifestRequested.subscribe(this.manifestRequested)),this.representationSubscription.add(this.fetcher.manifestReceived.subscribe(this.manifestReceived)),this.representationSubscription.add(this.fetcher.firstBytesRequested.subscribe(this.firstBytesRequested)),this.representationSubscription.add(this.fetcher.firstBytesReceived.subscribe(this.firstBytesReceived)),this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$));let u=()=>{var p;(p=this.stallWatchdogSubscription)==null||p.unsubscribe(),this.currentStallDuration$.next(0)};if(this.representationSubscription.add(Ui(...E0.map(p=>Et(this.element,p))).pipe(jr(p=>this.element?Ee(this.element.buffered,this.element.currentTime*1e3):0),Cs(),T0(p=>{p>this.tuning.dash.bufferEmptinessTolerance&&u()})).subscribe(this.bufferLength$)),this.representationSubscription.add(Ui(Et(this.element,"ended"),this.forceEnded$).subscribe(()=>{u()})),this.isLive$.getValue()){this.subscription.add(this.liveDuration$.pipe(Cs()).subscribe(h=>this.liveStreamEndTimestamp=Vd())),this.subscription.add(Et(this.element,"pause").subscribe(()=>{this.livePauseWatchdogSubscription=Bd(1e3).subscribe(h=>{let m=zt(this.manifestUrlString,2);this.manifestUrlString=le(this.manifestUrlString,m+1e3,2),this.liveStreamStatus$.getValue()==="active"&&this.updateManifest()}),this.subscription.add(this.livePauseWatchdogSubscription)})).add(Et(this.element,"play").subscribe(h=>{var m;return(m=this.livePauseWatchdogSubscription)==null?void 0:m.unsubscribe()})),this.representationSubscription.add(Ur({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(jr(({isActiveLive:h,isLowLatency:m})=>h&&m),Cs()).subscribe(h=>{this.isManualDecreasePlaybackInLive()||Dr(this.element,1)})),this.representationSubscription.add(Ur({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(tu(({bufferLength:h,isActiveLive:m,isLowLatency:S})=>m&&S&&!!h)).subscribe(({bufferLength:h})=>this.liveBuffer.next(h))),this.representationSubscription.add(this.videoBufferManager.currentLowLatencySegmentLength$.subscribe(h=>{if(!this.isActiveLive$.getValue()&&!this.isLowLatency$.getValue()&&!h)return;let m=this.liveSeekableDuration$.getValue()-h/1e3;this.liveSeekableDuration$.next(Math.max(m,-1*this.tuning.dashCmafLive.maxLiveDuration)),this.liveDuration$.next(this.liveDuration$.getValue()+h/1e3)})),this.representationSubscription.add(Ur({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe(tu(({isLive:h})=>h),Cs((h,m)=>m.bufferLength<h.bufferLength),jr(({rtt:h,bufferLength:m,segmentServerLatency:S})=>{let b=zt(this.manifestUrlString,2);return(h/2+m+S+b)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add(Ur({liveBuffer:this.liveBuffer.smoothed$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).subscribe(({liveBuffer:h,isActiveLive:m,isLowLatency:S})=>{if(!S||!m)return;let b=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,v=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,T=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,y=h-b;if(this.isManualDecreasePlaybackInLive())return;let I=1;Math.abs(y)>v&&(I=1+Math.sign(y)*T),Dr(this.element,I)})),this.representationSubscription.add(this.bufferLength$.subscribe(h=>{var S,b;let m=0;if(h){let v=((b=(S=this.element)==null?void 0:S.currentTime)!=null?b:0)*1e3;m=Math.min(...this.bufferManagers.map(y=>{var I,w;return(w=(I=y.getLiveSegmentsToLoadState(this.manifest))==null?void 0:I.to)!=null?w:v}))-v}this.liveLoadBufferLength$.getValue()!==m&&this.liveLoadBufferLength$.next(m)}));let p=0;this.representationSubscription.add(Ur({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(qI(1e3)).subscribe(async({liveLoadBufferLength:h,bufferLength:m})=>{if(!this.element||this.isUpdatingLive)return;let S=this.element.playbackRate,b=zt(this.manifestUrlString,2),v=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,T=Math.min(v,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*S),y=this.tuning.dashCmafLive.normalizedActualBufferOffset*S,I=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*S,w=isFinite(h)?h:m,L=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),M=v<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next(M);let R="none";if(L?R="active_low_latency":this.isLowLatency$.getValue()&&M?(this.bufferManagers.forEach(P=>P.proceedLowLatencyLive()),R="active_low_latency"):b!==0&&w<T?R="live_forward_buffering":w<T+I&&(R="live_with_target_offset"),isFinite(h)&&(p=h>p?h:p),R==="live_forward_buffering"||R==="live_with_target_offset"){let P=p-(T+y),V=this.normolizeLiveOffset(Math.trunc(b+P/S)),D=Math.abs(V-b),_=0;!h||D<=this.tuning.dashCmafLive.offsetCalculationError?_=b:V>0&&D>this.tuning.dashCmafLive.offsetCalculationError&&(_=V),this.manifestUrlString=le(this.manifestUrlString,_,2)}(R==="live_with_target_offset"||R==="live_forward_buffering")&&(p=0,await this.updateLive())},h=>{this.error$.next({id:"updateLive",category:dt.VIDEO_PIPELINE,thrown:h,message:"Failed to update live with subscription"})}))}let l=Ui(...this.bufferManagers.map(p=>p.fullyBuffered$)).pipe(jr(()=>this.bufferManagers.every(p=>p.fullyBuffered$.getValue()))),c=Ui(...this.bufferManagers.map(p=>p.onLastSegment$)).pipe(jr(()=>this.bufferManagers.some(p=>p.onLastSegment$.getValue()))),d=Ur({allBuffersFull:l,someBufferEnded:c}).pipe(Cs(),jr(({allBuffersFull:p,someBufferEnded:h})=>p&&h),tu(p=>p));if(this.representationSubscription.add(Ui(this.forceEnded$,d).subscribe(()=>{var p;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(h=>!h.updating))try{(p=this.source)==null||p.endOfStream()}catch(h){this.error$.next({id:"EndOfStream",category:dt.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:h})}})),this.representationSubscription.add(Ui(...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=>{var m;p&&(this.timeoutSourceOpenId=setTimeout(()=>{var S;if(((S=this.source)==null?void 0:S.readyState)==="open"){h();return}this.error$.next({id:"OpenOfStream",category:dt.VIDEO_PIPELINE,message:"Failed to open MediaSource",thrown:new Error("Timeout reject when wait sourceopen event"),traceAsLog:!0})},this.tuning.dash.sourceOpenTimeout)),(m=this.source)==null||m.addEventListener("sourceopen",()=>{this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),h()},{once:!0})})}if(!this.isLive$.getValue()){let p=[(f=this.manifest.duration)!=null?f:0,...(0,Od.default)((0,Od.default)([...this.manifest.streams.audio,...this.manifest.streams.video],h=>h.representations),h=>{let m=[];return h.duration&&m.push(h.duration),We(h.segmentReference)&&h.segmentReference.totalSegmentsDurationMs&&m.push(h.segmentReference.totalSegmentsDurationMs),m})];this.source.duration=Math.max(...p)/1e3}this.audioBufferManager&&Vs(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState("representations_ready"),this.tracer.log("initRepresentationsEnd")}.bind(this));this.tick=()=>{var t,i,r,s;if(!this.element||!this.videoBufferManager||((t=this.source)==null?void 0:t.readyState)!=="open")return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),(i=this.audioBufferManager)==null||i.maintain(e),(r=this.liveTextManager)==null||r.maintain(e),(this.videoBufferManager.gaps.length||(s=this.audioBufferManager)!=null&&s.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=Bd(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),n=>{this.error$.next({id:"GapWatchdog",category:dt.WTF,message:"Error handling gaps",thrown:n})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name),this.forceVideoCodec=e.forceVideoCodec,this.fetcher=new eu({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=Ct.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.bufferEstimator}),this.initTracerSubscription()}setSmartRepresentationSwitch(e){this.bufferManagers.forEach(t=>t.setSmartRepresentationSwitch(e))}async seekLive(e){var r,s,n;qr(this.element);let t=this.liveStreamStatus$.getValue()!=="active"?Vd()-this.liveStreamEndTimestamp:0,i=this.normolizeLiveOffset(e+t);this.isActiveLive$.next(i===0),this.manifestUrlString=le(this.manifestUrlString,i,2),this.manifest=await this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,await((r=this.videoBufferManager)==null?void 0:r.seekLive(this.manifest.streams.video)),await((s=this.audioBufferManager)==null?void 0:s.seekLive(this.manifest.streams.audio)),(n=this.liveTextManager)==null||n.seekLive(this.manifest.streams.text))}initBuffer(){qr(this.element),this.state$.setState("running");let e=Et(this.element,"timeupdate");this.tuning.dash.timeupdateEventTickThrottle&&(e=e.pipe(qI(this.tuning.dash.timeupdateEventTickThrottle))),this.subscription.add(Ui(...I0.map(t=>Et(this.element,t)),Et(window,"online"),e).subscribe(()=>this.tick(),t=>{this.error$.next({id:"DashVKPlayer",category:dt.WTF,message:"Internal logic error",thrown:t})})),this.subscription.add(Et(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(Et(this.element,"waiting").subscribe(()=>{var i;this.element&&this.element.readyState===HTMLMediaElement.HAVE_CURRENT_DATA&&!this.element.seeking&&xe(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let t=()=>{var h,m,S,b,v,T,y,I,w,L,M;if(!this.element||((h=this.source)==null?void 0:h.readyState)!=="open")return;let r=this.currentStallDuration$.getValue();r+=50,this.currentStallDuration$.next(r);let s={timeInWaiting:r},n=Vd(),o=100,u=(S=(m=this.videoBufferManager)==null?void 0:m.lastDataObtainedTimestamp)!=null?S:0;this.videoLastDataObtainedTimestamp$.next(u);let l=(v=(b=this.audioBufferManager)==null?void 0:b.lastDataObtainedTimestamp)!=null?v:0,c=(y=(T=this.videoBufferManager)==null?void 0:T.getForwardBufferDuration())!=null?y:0,d=(w=(I=this.audioBufferManager)==null?void 0:I.getForwardBufferDuration())!=null?w:0,f=c<o&&n-u>this.tuning.dash.crashOnStallTWithoutDataTimeout,p=this.audioBufferManager&&d<o&&n-l>this.tuning.dash.crashOnStallTWithoutDataTimeout;if((f||p)&&r>this.tuning.dash.crashOnStallTWithoutDataTimeout||r>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${r} ms`);if(this.isLive$.getValue()&&r%2e3===0){let R=this.normolizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);this.seekLive(R).catch(P=>{this.error$.next({id:"stallIntervalCallback",category:dt.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:P})}),s.liveLastOffset=R}else{let R=this.element.currentTime*1e3;(L=this.videoBufferManager)==null||L.maintain(R),(M=this.audioBufferManager)==null||M.maintain(R),s.position=R}this.tracer.log("stallIntervalCallback",Bs(s))};(i=this.stallWatchdogSubscription)==null||i.unsubscribe(),this.stallWatchdogSubscription=Bd(50).subscribe(t,r=>{this.error$.next({id:"StallWatchdogCallback",category:dt.NETWORK,message:"Can't restore DASH after stall.",thrown:r})}),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==null?void 0:r.switchToWithPreviousAbort(t,i):r==null?void 0:r.switchTo(t,i):r==null?void 0:r.switchToOld(t,i)}async seek(e,t){var r,s,n,o,u;qr(this.element),qr(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((r=this.videoBufferManager.findSegmentStartTime(e))!=null?r:e,(n=(s=this.audioBufferManager)==null?void 0:s.findSegmentStartTime(e))!=null?n:e),this.warmUpMediaSourceIfNeeded(i),xe(this.element.buffered,i)||await Promise.all([this.videoBufferManager.abort(),(o=this.audioBufferManager)==null?void 0:o.abort()]),!(NI(this.element)||NI(this.videoBufferManager))&&(this.videoBufferManager.maintain(i),(u=this.audioBufferManager)==null||u.maintain(i),this.element.currentTime=i/1e3,this.tracer.log("seek",Bs({requestedPosition:e,forcePrecise:t,position:i})))}warmUpMediaSourceIfNeeded(e=(t=>(t=this.element)==null?void 0:t.currentTime)()){var i;Vs(this.element)&&Vs(this.source)&&Vs(e)&&((i=this.source)==null?void 0:i.readyState)==="ended"&&this.element.duration*1e3-e>this.tuning.dash.seekBiasInTheEnd&&this.bufferManagers.forEach(r=>r.warmUpMediaSource())}get isStreamEnded(){var e;return((e=this.source)==null?void 0:e.readyState)==="ended"}stop(){var e,t,i;this.tracer.log("stop"),(e=this.element)==null||e.querySelectorAll("source").forEach(r=>{URL.revokeObjectURL(r.src),r.remove()}),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),(t=this.videoBufferManager)==null||t.destroy(),this.videoBufferManager=null,(i=this.audioBufferManager)==null||i.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getStreams(){var e;return(e=this.manifest)==null?void 0:e.streams}getCodecs(){var e;return(e=this.manifest)==null?void 0:e.codecs}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){var e;this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),((e=this.source)==null?void 0:e.readyState)==="open"&&Array.from(this.source.sourceBuffers).every(t=>!t.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}initTracerSubscription(){let e=y0(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(){var e;this.isUpdatingLive=!0,this.manifest=await this.updateManifest(),this.manifest&&(this.bufferManagers.forEach(t=>t.updateLive(this.manifest)),(e=this.liveTextManager)==null||e.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",Bs({isJumpGapAfterSeekLive:i,isActiveLowLatency:t,initialCurrentTime:r,jumpTo:u,resultCurrentTime:this.element.currentTime})))}}calculateDurationFromSegments(){var e,t;return Math.max(((e=this.videoBufferManager)==null?void 0:e.calculateDurationFromSegments())||0,((t=this.audioBufferManager)==null?void 0:t.calculateDurationFromSegments())||0)}};import{combine as x0,map as w0,observeElementSize as A0,Subscription as R0,ValueSubject as Fd,noop as P0}from"@vkontakte/videoplayer-shared/es2018";var ru=class{constructor(){this.subscription=new R0;this.pipSize$=new Fd(void 0);this.videoSize$=new Fd(void 0);this.elementSize$=new Fd(void 0);this.pictureInPictureWindowRemoveEventListener=P0}connect({observableVideo:e,video:t}){let i=r=>{let s=r.target;this.pipSize$.next({width:s.width,height:s.height})};this.subscription.add(A0(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(x0({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe(w0(({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 ji=class{constructor(e){this.subscription=new V0;this.videoState=new j("stopped");this.observableVideo=null;this.droppedFramesManager=new Er;this.stallsManager=new Qo;this.elementSizeManager=new ru;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new Xt;this.audioTrackSwitchHistory=new Xt;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==null?void 0: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"),$(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"),$(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="ready"&&$(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==null?void 0:i.to)==="playing"&&$(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&$(this.params.desiredState.playbackState,"paused");return;default:return L0(e)}}};this.init3DScene=e=>{var i,r,s;if(this.scene3D)return;this.scene3D=new Or(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:((i=e.projectionData)==null?void 0:i.pose.yaw)||0,y:((r=e.projectionData)==null?void 0:r.pose.pitch)||0,z:((s=e.projectionData)==null?void 0:s.pose.roll)||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});let t=this.elementSizeManager.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};this.textTracksManager=new Xe(e.source.url),this.params=e,this.video=Be(e.container,e.tuning),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Ie(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 iu({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode,tracer:this.tracer,forceVideoCodec:this.params.forceVideoCodec}),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params;B0(this.observableVideo)&&(this.observableVideo=Oe(this.video),this.subscription.add(()=>{var n;return(n=this.observableVideo)==null?void 0:n.destroy()}));let i=this.constructor.name,r=n=>{e.error$.next({id:i,category:jI.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(Nd(d=>!!d.length),QI()).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(Os(d=>d.to.state!=="none"),_s());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(Nd(HI),QI()),e.firstBytesEvent$),s(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),s(this.videoState.stateChangeEnded$.pipe(Os(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(bt(this.video,t.isLooped,r)),this.subscription.add(_e(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Ke(this.video,t.playbackRate,i.playbackRateState$,r)),this.elementSizeManager.connect({video:this.video,observableVideo:i}),s(Je(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),$(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),$(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.params.tuning.changePlaybackStateToPausedWhenEnded&&this.subscription.add(i.ended$.subscribe(()=>{this.videoState.setState("paused"),$(t.playbackState,"paused")})),this.subscription.add(this.player.manifestRequested.subscribe(this.params.output.manifestRequested$)).add(this.player.manifestReceived.subscribe(this.params.output.manifestReceived$)).add(this.player.firstBytesRequested.subscribe(this.params.output.firstBytesRequested$)).add(this.player.firstBytesReceived.subscribe(this.params.output.firstBytesReceived$)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:d})=>{if(d==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let f=this.player.getStreams(),p=this.player.getCodecs();if($0(f,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let m=[];for(let S of f.audio){m.push(Rd(S));let b=[];for(let v of S.representations){let T=$I(v);b.push(T),this.audioTracksMap.set(T,{stream:S,representation:v})}this.audioStreamsMap.set(S,b)}this.params.output.availableAudioStreams$.next(m)}let h=[];for(let m of f.video){h.push(Pd(m));let S=[];for(let b of m.representations){let v=Ps({...b,streamId:m.id});v&&(S.push(v),this.videoTracksMap.set(v,{stream:m,representation:b}))}this.videoStreamsMap.set(m,S)}this.params.output.availableVideoStreams$.next(h);for(let m of f.text)for(let S of m.representations){let b=MI(m,S);this.textTracksMap.set(b,{stream:m,representation:S})}this.params.output.availableVideoTracks$.next(Array.from(this.videoTracksMap.keys())),this.params.output.availableAudioTracks$.next(Array.from(this.audioTracksMap.keys())),this.params.output.isAudioAvailable$.next(!!this.audioTracksMap.size),p!=null&&p.video&&this.params.output.availableVideoCodecs$.next(p.video),p!=null&&p.audio&&this.params.output.availableAudioCodecs$.next(p.audio),this.audioTracksMap.size&&this.textTracksMap.size&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else d==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},r));let{vktvAbrThrottle:o}=this.params.tuning.dash,u=o&&BI(o)||null;this.subscription.add(Fs(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$,C0(this.video,"progress")).pipe(Nd(()=>this.videoTracksMap.size>0)).subscribe(async()=>{let d=this.player.state$.getState(),f=this.player.state$.getTransition();if(d!=="manifest_ready"&&d!=="running"||f||d==="running"&&u&&!u())return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState()),this.selectVideoAudioRepresentations();let{video:p,audio:h}=this.selectedRepresentations;if(!p)return;let m=Oi(this.videoTracksMap.keys(),b=>{var v;return((v=this.videoTracksMap.get(b))==null?void 0:v.representation.id)===p.id});HI(m)&&(this.stallsManager.lastVideoTrackSelected=m);let S=this.params.desiredState.autoVideoTrackLimits.getTransition();if(S&&this.params.output.autoVideoTrackLimits$.next(S.to),d==="manifest_ready")await this.player.initRepresentations(p.id,h==null?void 0:h.id,this.params.sourceHls);else if(await this.player.switchRepresentation("video",p.id),h){let b=!!t.audioStream.getTransition();await this.player.switchRepresentation("audio",h.id,b)}},r)),this.subscription.add(M0({videoState:this.videoState.stateChangeEnded$,autoVideoTrackState:Fs(au([t.autoVideoTrackSwitching.getState()]),t.autoVideoTrackSwitching.stateChangeEnded$.pipe(Os(d=>d.to)))}).pipe(Os(({videoState:d,autoVideoTrackState:f})=>d.to!=="stopped"&&f),_s()).subscribe(d=>this.player.setSmartRepresentationSwitch(d))),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:d})=>{this.scene3D&&d&&this.scene3D.pointCameraTo(d.x,d.y)})),this.subscription.add(this.elementSizeManager.subscribe(d=>{this.scene3D&&d&&this.scene3D.setViewportSize(d.width,d.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(_s()).subscribe(d=>{let f=Oi(this.videoTracksMap.entries(),([,{representation:b}])=>b.id===d);if(!f){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[p,{stream:h}]=f,m=this.params.desiredState.videoStream.getTransition();m&&m.to&&m.to.id===h.id&&this.params.desiredState.videoStream.setState(m.to),e.currentVideoTrack$.next(p),e.currentVideoStream$.next(Pd(h));let S=this.player.calculateDurationFromSegments();S&&this.params.output.duration$.next(S/1e3)},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(_s()).subscribe(d=>{let f=Oi(this.audioTracksMap.entries(),([,{representation:S}])=>S.id===d);if(!f){e.currentAudioStream$.next(void 0);return}let[p,{stream:h}]=f,m=this.params.desiredState.audioStream.getTransition();m&&m.to&&m.to.id===h.id&&this.params.desiredState.audioStream.setState(m.to),e.currentAudioStream$.next(Rd(h))},r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(d=>{var f,p;if(d!=null&&d.is3dVideo&&((f=this.params.tuning.spherical)!=null&&f.enabled))try{this.init3DScene(d),e.is3DVideo$.next(!0)}catch(h){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${h}`})}else this.destroy3DScene(),(p=this.params.tuning.spherical)!=null&&p.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(Os(({to:d})=>d==="ready"),_s());this.subscription.add(Fs(l,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,au(["init"])).subscribe(()=>{let d=t.autoVideoTrackSwitching.getState(),p=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:d?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(p)})),this.subscription.add(Fs(l,this.player.state$.stateChangeEnded$,au(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let c=Fs(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,au(["init"])).pipe(D0(0));this.subscription.add(c.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){var M,R,P,V,D,_,K,J,E,k,x,A;if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?La:ka,t=this.params.tuning.useNewAutoSelectVideoTrack?fo:ho,i=this.params.tuning.useNewAutoSelectVideoTrack?vt:po,{desiredState:r,output:s}=this.params,n=r.autoVideoTrackSwitching.getState(),o=(M=r.videoTrack.getState())==null?void 0:M.id,u=Oi(this.videoTracksMap.keys(),B=>B.id===o),l=s.currentVideoTrack$.getValue(),c=((V=(P=r.videoStream.getState())!=null?P:u&&((R=this.videoTracksMap.get(u))==null?void 0:R.stream))!=null?V:this.videoStreamsMap.size===1)?this.videoStreamsMap.keys().next().value:void 0;if(!c)return;let d=Oi(this.videoStreamsMap.keys(),B=>B.id===c.id),f=d&&this.videoStreamsMap.get(d);if(!f)return;let p=Ee(this.video.buffered,this.video.currentTime*1e3),h;this.player.isActiveLive$.getValue()?h=this.player.isLowLatency$.getValue()?this.params.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.params.tuning.dashCmafLive.normalizedLiveMinBufferSize:this.player.isLive$.getValue()?h=this.params.tuning.dashCmafLive.normalizedTargetMinBufferSize:h=n?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;let m=(this.video.duration*1e3||1/0)-this.video.currentTime*1e3,S=Math.min(p/Math.min(h,m||1/0),1),b=(D=r.audioStream.getState())!=null?D:this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0,v=(b==null?void 0:b.id)&&Oi(this.audioStreamsMap.keys(),B=>B.id===b.id)||this.audioStreamsMap.keys().next().value,T=0;if(v){if(u&&!n){let B=e(u,f,(_=this.audioStreamsMap.get(v))!=null?_:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);T=Math.max(T,(K=B==null?void 0:B.bitrate)!=null?K:-1/0)}if(l){let B=e(l,f,(J=this.audioStreamsMap.get(v))!=null?J:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);T=Math.max(T,(E=B==null?void 0:B.bitrate)!=null?E:-1/0)}}let y=u;(n||!y)&&(y=i(f,{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:T,forwardBufferHealth:S,current:l,visible:this.params.output.elementVisible$.getValue(),history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,stallsVideoMaxQualityLimit:this.stallsManager.videoMaxQualityLimit,stallsPredictedThroughput:this.stallsManager.predictedThroughput,abrLogger:this.params.dependencies.abrLogger}));let I=v&&t(y,f,(k=this.audioStreamsMap.get(v))!=null?k:[],{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}),w=(x=this.videoTracksMap.get(y))==null?void 0:x.representation,L=I&&((A=this.audioTracksMap.get(I))==null?void 0:A.representation);w&&L?(this.selectedRepresentations.video=w,this.selectedRepresentations.audio=L):w&&!L&&this.audioTracksMap.size===0&&(this.selectedRepresentations.video=w,this.selectedRepresentations.audio=null)}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){Fe(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),$(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:jI.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),Ve(this.video),this.tracer.end()}};var Ns=class extends ji{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 qd,merge as GI,filter as WI,filterChanged as zI,isNullable as Ud,map as YI,ValueSubject as jd,isNonNullable as _0}from"@vkontakte/videoplayer-shared/es2018";var qs=class extends ji{constructor(e){super(e),this.textTracksManager.destroy()}subscribe(){super.subscribe();let e=!1,t=-1,{output:i,observableVideo:r,desiredState:s,connect:n}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canPlayLiveTailBuffer$.next(!0),n(r.timeUpdate$,i.liveBufferTime$),n(this.player.liveSeekableDuration$,i.duration$),n(this.player.liveLatency$,i.liveLatency$);let o=new jd(1);n(r.playbackRateState$,o),this.params.tuning.dashCmafLive.catchupLiveForMutedInactiveTab&&this.subscription.add(i.elementVisible$.pipe(zI()).subscribe(u=>{let l=i.position$.getValue(),c=i.volume$.getValue(),d=!c.volume||c.muted;!u&&!l&&d?e=!0:u&&e&&(this.seek(0),e=!1)})),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(s.isLowLatency.stateChangeEnded$.pipe(YI(u=>u.to)).subscribe(this.player.isLowLatency$)).add(qd({liveBufferTime:i.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(YI(({liveBufferTime:u,liveAvailabilityStartTime:l})=>u&&l?u+l:void 0)).subscribe(i.liveTime$)).add(this.player.liveStreamStatus$.pipe(WI(u=>_0(u))).subscribe(u=>i.isLiveEnded$.next(u!=="active"&&i.position$.getValue()===0))).add(qd({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:GI(r.playbackRateState$,new jd(1))}).pipe(WI(({liveStreamStatus:u,liveDuration:l})=>u==="active"&&!!l)).subscribe(({liveDuration:u,playbackRate:l})=>{let c=i.liveBufferTime$.getValue(),d=i.position$.getValue(),{playbackCatchupSpeedup:f}=this.params.tuning.dashCmafLive.lowLatency;d||l<1-f||this.video.paused||Ud(c)||(t=u-c)})).add(qd({time:i.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:GI(r.playbackRateState$,new jd(1))}).pipe(zI((u,l)=>this.player.liveStreamStatus$.getValue()==="active"?u.liveDuration===l.liveDuration:u.time===l.time)).subscribe(({time:u,liveDuration:l,playbackRate:c})=>{let d=i.position$.getValue(),{playbackCatchupSpeedup:f}=this.params.tuning.dashCmafLive.lowLatency;if(!d&&!this.video.paused&&c>=1-f||Ud(u)||Ud(l))return;let p=-1*(l-u-t);i.position$.next(Math.min(p,0))})).add(this.player.currentLiveTextRepresentation$.subscribe(u=>{if(u){let l=DI(u);this.params.output.availableTextTracks$.next([l])}}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,i=Math.trunc(t/1e3<=Math.abs(this.params.output.duration$.getValue())?t:0);this.player.seekLive(i).then(()=>{this.params.output.position$.next(e/1e3)})}};var KI="X-Playback-Duration",Hd=async a=>{var r;let e=await Ze(a),t=await e.text(),i=(r=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t))==null?void 0:r[1];return i?parseInt(i,10):e.headers.has(KI)?parseInt(e.headers.get(KI),10):void 0};import{assertNever as z0,combine as Y0,debounce as K0,ErrorCategory as ou,filter as X0,filterChanged as J0,isNonNullable as ZI,isNullable as uu,map as eE,merge as Z0,observableFrom as eV,Subscription as tV,ValueSubject as Wd,VideoQuality as iV}from"@vkontakte/videoplayer-shared/es2018";var Gd=O(Ll(),1);import{videoSizeToQuality as O0,getExponentialDelay as F0}from"@vkontakte/videoplayer-shared/es2018";var N0=a=>{let e=null;if(a.QUALITY&&(e=Kt(a.QUALITY)),!e&&a.RESOLUTION){let[t,i]=a.RESOLUTION.split("x").map(r=>parseInt(r,10));e=O0({width:t,height:i})}return e!=null?e:null},q0=(a,e)=>{var s,n;let t=a.split(`
179
+ `),i=[],r=[];for(let o=0;o<t.length;o++){let u=t[o],l=u.match(/^#EXT-X-STREAM-INF:(.+)/),c=u.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!l&&!c)){if(l){let d=(0,Gd.default)(l[1].split(",").map(v=>v.split("="))),f=(s=d.QUALITY)!=null?s:`stream-${d.BANDWIDTH}`,p=N0(d),h;d.BANDWIDTH&&(h=parseInt(d.BANDWIDTH,10)/1e3||void 0),!h&&d["AVERAGE-BANDWIDTH"]&&(h=parseInt(d["AVERAGE-BANDWIDTH"],10)/1e3||void 0);let m=d["FRAME-RATE"]?parseFloat(d["FRAME-RATE"]):void 0,S;if(d.RESOLUTION){let[v,T]=d.RESOLUTION.split("x").map(y=>parseInt(y,10));v&&T&&(S={width:v,height:T})}let b=new URL(t[++o],e).toString();p&&i.push({id:f,quality:p,url:b,bandwidth:h,size:S,fps:m})}if(c){let d=(0,Gd.default)(c[1].split(",").map(m=>{let S=m.indexOf("=");return[m.substring(0,S),m.substring(S+1)]}).map(([m,S])=>[m,S.replace(/^"|"$/g,"")])),f=(n=d.URI)==null?void 0:n.replace(/playlist$/,"subtitles.vtt"),p=d.LANGUAGE,h=d.NAME;f&&p&&r.push({type:"internal",id:p,label:h,language:p,url:f,isAuto:!1})}}}if(!i.length)throw new Error("Empty manifest");return{qualityManifests:i,textTracks:r}},U0=a=>new Promise(e=>{setTimeout(()=>{e()},a)}),Qd=0,XI=async(a,e=a,t,i)=>{let s=await(await Ze(a,i)).text();Qd+=1;try{let{qualityManifests:n,textTracks:o}=q0(s,e);return{qualityManifests:n,textTracks:o}}catch(n){if(Qd<=t.manifestRetryMaxCount)return await U0(F0(Qd-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),XI(a,e,t)}return{qualityManifests:[],textTracks:[]}},su=XI;import{isNonNullable as j0,Subscription as H0,throttle as Q0,ValueSubject as JI,Subject as G0,ErrorCategory as W0}from"@vkontakte/videoplayer-shared/es2018";var nu=class{constructor(e,t,i,r,s){this.subscription=new H0;this.abortControllers={destroy:new Z,nextManifest:null};this.prepareUrl=void 0;this.currentTextTrackData=null;this.availableTextTracks$=new JI(null);this.getCurrentTime$=new JI(null);this.error$=new G0;this.params={fetchManifestData:i,sourceUrl:r,downloadThreshold:s},this.subscription.add(e.pipe(Q0(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 Ze(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(),f=new Date(i.programDateTime).valueOf();i.segmentStartTime=f-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(j0(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 Z;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(){var t;let e=(t=this.prepareUrl)!=null?t: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:W0.WTF,thrown:t,message:e})}};var Us=class{constructor(e){this.subscription=new tV;this.videoState=new j("stopped");this.textTracksManager=null;this.liveTextManager=null;this.manifests$=new Wd([]);this.liveOffset=new ki;this.manifestStartTime$=new Wd(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"),$(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==null?void 0: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"?$(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),$(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==null?void 0:r.to)==="playing"&&$(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==null?void 0:r.to)==="paused"&&($(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return z0(t)}};var i;this.params=e,this.video=Be(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:iV.INVARIANT,url:this.params.source.url};let t=(r,s)=>su(r,this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},s);this.params.tuning.useHlsLiveNewTextManager?this.liveTextManager=new nu(this.params.output.liveTime$,this.video,t,this.params.source.url,this.params.tuning.hlsLiveNewTextManagerDownloadThreshold):this.textTracksManager=new Xe(e.source.url),t(this.generateLiveUrl()).then(({qualityManifests:r,textTracks:s})=>{var n;r.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:ou.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),(n=this.liveTextManager)==null||n.processTextTracks(s,this.params.source.url),this.manifests$.next([this.masterManifest,...r])}).catch(r=>{this.params.output.error$.next({id:"ExtractHlsQualities",category:ou.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:r})}),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Ie(this.params.source.url)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.maxSeekBackTime$=new Wd((i=e.source.maxSeekBackTime)!=null?i:1/0),this.subscribe()}selectManifest(){var u,l,c,d;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),r=t.getTransition(),s=(d=(c=(u=r==null?void 0:r.to)==null?void 0:u.id)!=null?c:(l=t.getState())==null?void 0:l.id)!=null?d:"master",n=this.manifests$.getValue();if(!n.length)return;let o=i?"master":s;return i&&!r&&t.startTransitionTo(this.masterManifest),n.find(f=>f.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsLiveProvider",category:ou.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},r=Oe(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(_e(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Ke(this.video,t.playbackRate,r.playbackRateState$,i)),s(Je(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"),$(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),$(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())==null?void 0:o.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(J0(),eE(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&&ZI(l.to)){let d=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let f=this.manifests$.getValue().find(p=>p.id===d);f&&(this.params.output.currentVideoTrack$.next(f),this.params.output.hostname$.next(Ie(f.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(()=>{var u,l,c;let o=(c=(l=(u=this.video)==null?void 0:u.getStartDate)==null?void 0:l.call(u))==null?void 0:c.getTime();this.manifestStartTime$.next(o||void 0)},i)),this.subscription.add(Y0({startTime:this.manifestStartTime$.pipe(X0(ZI)),currentTime:r.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),i)),this.subscription.add(this.manifests$.pipe(eE(o=>o.map(({id:u,quality:l,size:c,bandwidth:d,fps:f})=>({id:u,quality:l,size:c,fps:f,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,i));let n=Z0(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,eV(["init"])).pipe(K0(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){var e,t;this.subscription.unsubscribe(),(e=this.textTracksManager)==null||e.destroy(),(t=this.liveTextManager)==null||t.destroy(),this.params.output.element$.next(void 0),Ve(this.video)}prepare(){var o,u,l;let e=this.selectManifest();if(uu(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:c,min:d}=(u=(o=t==null?void 0:t.to)!=null?o:i)!=null?u:{};for(let[f,p]of[[c,"mq"],[d,"lq"]]){let h=String(parseFloat(f||""));p&&f&&r.searchParams.set(p,h)}}let s=this.params.format==="HLS_LIVE_CMAF"?2:0,n=le(r.toString(),this.liveOffset.getTotalOffset(),s);(l=this.liveTextManager)==null||l.prepare(n),this.video.setAttribute("src",n),this.video.load(),Hd(n).then(c=>{var d;if(!uu(c))this.maxSeekBackTime$.next(c);else{let f=(d=this.params.source.maxSeekBackTime)!=null?d:this.maxSeekBackTime$.getValue();(uu(f)||!isFinite(f))&&Ze(n).then(p=>p.text()).then(p=>{var m;let h=(m=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(p))==null?void 0:m[1];if(h){let S=new URL(h,n).toString();Hd(S).then(b=>{uu(b)||this.maxSeekBackTime$.next(b)})}}).catch(()=>{})}})}playIfAllowed(){Fe(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),$(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:ou.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=le(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 rV,debounce as aV,ErrorCategory as zd,fromEvent as Yd,isNonNullable as sV,isNullable as nV,map as tE,merge as iE,observableFrom as rE,Subscription as oV,ValueSubject as uV,VideoQuality as lV}from"@vkontakte/videoplayer-shared/es2018";var js=class{constructor(e){this.subscription=new oV;this.videoState=new j("stopped");this.manifests$=new uV([]);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"),$(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==null?void 0:r.to)!=="paused"&&l.state==="requested"&&this.seek(l.position),t){case"ready":i==="ready"?$(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),$(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==null?void 0:r.to)==="playing"&&$(this.params.desiredState.playbackState,"playing");return;case"paused":i==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&$(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return rV(t)}};this.textTracksManager=new Xe(e.source.url),this.params=e,this.video=Be(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:lV.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(Ie(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.manifestRequested$.next(),su(le(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:t,textTracks:i})=>{this.params.output.manifestReceived$.next(),this.manifests$.next([this.masterManifest,...t]),this.params.tuning.useNativeHLSTextTracks||this.params.desiredState.internalTextTracks.startTransitionTo(i)},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:zd.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){var u,l,c,d;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),r=t.getTransition(),s=(d=(c=(u=r==null?void 0:r.to)==null?void 0:u.id)!=null?c:(l=t.getState())==null?void 0:l.id)!=null?d:"master",n=this.manifests$.getValue();if(!n.length)return;let o=i?"master":s;return i&&(!r||!r.from)&&t.startTransitionTo(this.masterManifest),n.find(f=>f.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsProvider",category:zd.WTF,message:"HlsProvider internal logic error",thrown:o})},r=Oe(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(tE(o=>o.to)),this.params.output.playbackState$),this.subscription.add(bt(this.video,t.isLooped,i)),this.subscription.add(_e(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Ke(this.video,t.playbackRate,r.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),$(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),$(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())==null?void 0:o.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i).add(r.loadedMetadata$.subscribe(()=>{var p;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&&sV(l.to)){let h=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let m=this.manifests$.getValue().find(S=>S.id===h);m&&(this.params.output.currentVideoTrack$.next(m),this.params.output.hostname$.next(Ie(m.url)))}let d=this.params.desiredState.playbackRate.getState(),f=(p=this.params.output.element$.getValue())==null?void 0:p.playbackRate;if(d!==f){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.params.tuning.changePlaybackStateToPausedWhenEnded&&this.subscription.add(r.ended$.subscribe(()=>{this.videoState.setState("paused"),$(t.playbackState,"paused")})),this.subscription.add(this.manifests$.pipe(tE(o=>o.map(({id:u,quality:l,size:c,bandwidth:d,fps:f})=>({id:u,quality:l,size:c,fps:f,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,i)),!F.device.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add(iE(Yd(o,"addtrack"),Yd(o,"removetrack"),Yd(o,"change"),rE(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},i))}let n=iE(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,rE(["init"])).pipe(aV(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),Ve(this.video)}prepare(){var s,n;let e=this.selectManifest();if(nV(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}=(n=(s=t==null?void 0:t.to)!=null?s:i)!=null?n:{};for(let[l,c]of[[o,"mq"],[u,"lq"]]){let d=String(parseFloat(l||""));c&&l&&r.searchParams.set(c,d)}}this.video.setAttribute("src",r.toString()),this.video.load()}playIfAllowed(){Fe(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),$(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:zd.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};var nE=O(ar(),1),Kd=O(br(),1),oE=O(ot(),1);import{assertNever as cV,assertNonNullable as aE,debounce as dV,ErrorCategory as sE,isHigherOrEqual as pV,isLowerOrEqual as hV,isNonNullable as fV,merge as mV,observableFrom as bV,Subscription as gV,map as SV}from"@vkontakte/videoplayer-shared/es2018";var Hs=class{constructor(e){this.subscription=new gV;this.videoState=new j("stopped");this.trackUrls={};this.textTracksManager=new Xe;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"),$(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==null?void 0:i.to)!=="paused"&&o.state==="requested"&&this.seek(o.position),e){case"ready":t==="ready"?$(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),$(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==null?void 0:i.to)==="playing"&&$(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&$(this.params.desiredState.playbackState,"paused");return;default:return cV(e)}};this.params=e,this.video=Be(e.container,e.tuning),this.params.output.element$.next(this.video),(0,nE.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,Kd.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:sE.WTF,message:"MpegProvider internal logic error",thrown:o})},r=Oe(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(SV(o=>o.to)),this.params.output.playbackState$),this.subscription.add(bt(this.video,t.isLooped,i)),this.subscription.add(_e(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Ke(this.video,t.playbackRate,r.playbackRateState$,i)),s(Je(this.video),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),$(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),$(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{var u,l;((u=this.videoState.getTransition())==null?void 0:u.to)==="ready"&&this.videoState.setState("ready");let o=this.params.desiredState.videoTrack.getTransition();if(o&&fV(o.to)){this.params.desiredState.videoTrack.setState(o.to),this.params.output.currentVideoTrack$.next(this.trackUrls[o.to.id].track);let c=this.params.desiredState.playbackRate.getState(),d=(l=this.params.output.element$.getValue())==null?void 0:l.playbackRate;if(c!==d){let f=this.params.output.element$.getValue();f&&(this.params.desiredState.playbackRate.setState(c),f.playbackRate=c)}}this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.params.tuning.changePlaybackStateToPausedWhenEnded&&this.subscription.add(r.ended$.subscribe(()=>{this.videoState.setState("paused"),$(t.playbackState,"paused")})),this.textTracksManager.connect(this.video,t,e);let n=mV(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,bV(["init"])).pipe(dV(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),Ve(this.video)}prepare(){var i;let e=(i=this.params.desiredState.videoTrack.getState())==null?void 0:i.id;aE(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];aE(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=ti(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(Ie(t))}playIfAllowed(){Fe(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),$(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:sE.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){var l,c;this.params.output.autoVideoTrackLimits$.next(e);let t=d=>{this.params.output.currentVideoTrack$.next(d),this.params.desiredState.videoTrack.startTransitionTo(d)},i=d=>{let f=vt(n,{container:this.video.getBoundingClientRect(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:0,limits:d,abrLogger:this.params.dependencies.abrLogger});t(f)},r=(l=this.params.output.currentVideoTrack$.getValue())==null?void 0:l.quality,s=!!(e.max||e.min),n=(0,Kd.default)(this.trackUrls).map(d=>d.track);if(!r||!s||Sr(e,n[0].quality,(c=(0,oE.default)(n,-1))==null?void 0:c.quality)){i();return}let o=e.max?hV(r,e.max):!0,u=e.min?pV(r,e.min):!0;o&&u||i(e)}};import{assertNever as lE,debounce as IV,merge as cE,observableFrom as EV,Subscription as xV,map as dE,ValueSubject as wV,ErrorCategory as Jd,VideoQuality as AV}from"@vkontakte/videoplayer-shared/es2018";import{ErrorCategory as vV}from"@vkontakte/videoplayer-shared/es2018";var uE=["stun:videostun.mycdn.me:80"],yV=1e3,TV=3,Xd=()=>null,lu=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=Xd;this.externalStopCallback=Xd;this.externalErrorCallback=Xd;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:uE}]};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:vV.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(t){throw new Error("Can not parse socket message")}}closeConnections(){let e=this.ws;e&&(this.ws=null,e.close(1e3)),this.removePeerConnection()}removePeerConnection(){let e=this.peerConnection;e&&(this.peerConnection=null,e.close(),e.ontrack=null,e.onicecandidate=null,e.oniceconnectionstatechange=null,e=null)}scheduleRetry(){this.retryTimeout=setTimeout(this.connectWS.bind(this),yV)}normalizeOptions(e={}){let t={stunServerList:uE,maxRetryNumber:TV,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var Qs=class{constructor(e){this.videoState=new j("stopped");this.maxSeekBackTime$=new wV(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"),$(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"),$(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==null?void 0:i.to)==="playing"&&$(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&$(this.params.desiredState.playbackState,"paused");return;default:return lE(e)}};this.subscription=new xV,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=Be(e.container,e.tuning),this.liveStreamClient=new lu(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),Ve(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,i=n=>{e.error$.next({id:"WebRTCLiveProvider",category:Jd.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};this.subscription.add(cE(this.videoState.stateChangeStarted$.pipe(dE(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe(dE(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})}));let r=Oe(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(Je(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(()=>{var n;((n=this.videoState.getTransition())==null?void 0:n.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(_e(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 lE(n.to)}},i)).add(cE(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,EV(["init"])).pipe(IV(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(Ie(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:AV.INVARIANT}),this.video.srcObject=e,$(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:Jd.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){Fe(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),$(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Jd.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var Hr=class{constructor(e){this.length=e.length,this.iterator=e[Symbol.iterator](),this.next()}next(){this.current=this.iterator.next(),this.index=this.index===void 0?0:this.index+1}getValue(){if(this.current.done)throw new Error("Iterable is completed");return this.current.value}isCompleted(){return!!this.current.done}isLast(){return this.index===this.length-1}};import{assertNever as Ws,assertNonNullable as oi,ErrorCategory as cu,filter as gE,isNonNullable as SE,isNullable as DV,map as CV,merge as BV,once as VV,Subject as ce,Subscription as vE,ValueSubject as q,flattenObject as Zd}from"@vkontakte/videoplayer-shared/es2018";import{Observable as RV,map as pE,Subscription as PV,Subject as kV}from"@vkontakte/videoplayer-shared/es2018";var hE=a=>new RV(e=>{let t=new PV,i=a.desiredPlaybackState$.stateChangeStarted$.pipe(pE(({from:l,to:c})=>`${l}-${c}`)),r=a.desiredPlaybackState$.stateChangeEnded$,s=a.providerChanged$.pipe(pE(({type:l})=>l!==void 0)),n=new kV,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 LV,Subscription as $V,combine as MV,filter as mE,once as bE}from"@vkontakte/videoplayer-shared/es2018";function fE(){return new(window.AudioContext||window.webkitAudioContext)}var Gs=class Gs{constructor(e,t,i,r){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=i;this.volumeMultiplier=r;this.destroyController=new Z;this.subscriptions=new $V;this.audioContext=null;this.gainNode=null;this.mediaElementSource=null;this.subscriptions.add(this.provider$.pipe(mE(s=>!!s.type),bE()).subscribe(({type:s})=>this.subscribe(s)))}subscribe(e){F.browser.isSafari&&e!=="MPEG"||this.subscriptions.add(MV({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe(mE(({playbackState:t,video:i,volume:{muted:r,volume:s}})=>t==="playing"&&!!i&&!r&&!!s),bE()).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=fE();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){var t;this.volumeMultiplierError$.next({id:Gs.errorId,category:LV.VIDEO_PIPELINE,message:(t=e==null?void 0:e.message)!=null?t:`${Gs.errorId} exception`,thrown:e})}};Gs.errorId="VolumeMultiplierManager";var Qr=Gs;var _V={chunkDuration:5e3,maxParallelRequests:5},zs=class{constructor(e){this.current$=new q({type:void 0});this.providerError$=new ce;this.noAvailableProvidersError$=new ce;this.volumeMultiplierError$=new ce;this.providerOutput={position$:new q(0),duration$:new q(1/0),volume$:new q({muted:!1,volume:1}),availableVideoStreams$:new q([]),currentVideoStream$:new q(void 0),availableVideoTracks$:new q([]),currentVideoTrack$:new q(void 0),availableVideoCodecs$:new q([]),availableAudioStreams$:new q([]),currentAudioStream$:new q(void 0),availableAudioTracks$:new q([]),availableAudioCodecs$:new q([]),currentVideoSegmentLength$:new q(0),currentAudioSegmentLength$:new q(0),isAudioAvailable$:new q(!0),autoVideoTrackLimitingAvailable$:new q(!1),autoVideoTrackLimits$:new q(void 0),currentBuffer$:new q(void 0),isBuffering$:new q(!0),error$:new ce,fetcherError$:new ce,fetcherRecoverableError$:new ce,warning$:new ce,willSeekEvent$:new ce,soundProhibitedEvent$:new ce,seekedEvent$:new ce,loopedEvent$:new ce,endedEvent$:new ce,manifestRequested$:new ce,manifestReceived$:new ce,firstBytesRequested$:new ce,firstBytesReceived$:new ce,firstBytesEvent$:new ce,loadedMetadataEvent$:new ce,firstFrameEvent$:new ce,canplay$:new ce,isLive$:new q(void 0),isLiveEnded$:new q(null),canPlayLiveTailBuffer$:new q(!1),isLowLatency$:new q(!1),canChangePlaybackSpeed$:new q(!0),liveTime$:new q(void 0),liveBufferTime$:new q(void 0),liveLatency$:new q(void 0),severeStallOccurred$:new ce,availableTextTracks$:new q([]),currentTextTrack$:new q(void 0),hostname$:new q(void 0),httpConnectionType$:new q(void 0),httpConnectionReused$:new q(void 0),inPiP$:new q(!1),inFullscreen$:new q(!1),element$:new q(void 0),elementVisible$:new q(!0),availableSources$:new q(void 0),is3DVideo$:new q(!1),playbackState$:new q(""),getCurrentTime$:new q(null)};this.subscription=new vE;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=gc([...cI(this.params.tuning),...lI(this.params.tuning)]).filter(l=>SE(e.sources[l])),{forceFormat:i,formatsToAvoid:r}=this.params.tuning,s=[];i?s=[i]:r.length?s=[...t.filter(l=>!(0,ep.default)(r,l)),...t.filter(l=>(0,ep.default)(r,l))]:s=t,this.log({message:`Selected formats: ${s.join(" > ")}`}),this.tracer.log("Selected formats",Zd(s)),this.screenFormatsIterator=new Hr(s);let n=[...cd(!0),...cd(!1)];this.chromecastFormatsIterator=new Hr(n.filter(l=>SE(e.sources[l]))),this.providerOutput.availableSources$.next(e.sources);let{volumeMultiplier:o=1,tuning:{useVolumeMultiplier:u}}=this.params;u&&o!==1&&Qr.isSupported()&&(this.volumeMultiplierManager=new Qr(this.providerOutput,this.current$,this.volumeMultiplierError$,o))}init(){this.subscription.add(this.initProviderErrorHandling()).add(this.params.dependencies.chromecastInitializer.connection$.subscribe(()=>{this.reinitProvider()})).add(this.providerOutput.availableVideoCodecs$.subscribe(e=>{!this.videoCodecsIterator&&e.length>1&&(this.videoCodecsIterator=new Hr(e))}))}destroy(){var e;this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe(),(e=this.volumeMultiplierManager)==null||e.destroy(),this.volumeMultiplierManager=null,this.tracer.end()}initProvider(){let e=this.chooseDestination(),t=this.chooseFormat(e);if(DV(t)){this.handleNoFormatsError(e);return}let i;try{i=this.createProvider(e,t)}catch(r){this.providerError$.next({id:"ProviderNotConstructed",category:cu.WTF,message:"Failed to create provider",thrown:r})}i?this.current$.next({type:t,provider:i,destination:e}):this.current$.next({type:void 0})}reinitProvider(){this.tracer.log("reinitProvider"),this.destroyProvider(),this.initProvider()}switchToNextProvider(e){this.tracer.log("switchToNextProvider",{destination:e}),this.destroyProvider(),this.failoverIndex=void 0,this.skipFormat(e),this.initProvider()}switchToNextVideoCodec(){this.params.tuning.dash.codecsPrioritizeEnabled&&!this.videoCodecsIterator.isLast()&&(this.tracer.log("switchToNextVideoCodec"),this.destroyProvider(),this.videoCodecsIterator.next(),this.initProvider())}destroyProvider(){let e=this.current$.getValue().provider;if(!e)return;this.log({message:"destroyProvider"}),this.tracer.log("destroyProvider"),e.destroy();let t=this.providerOutput.position$.getValue()*1e3,i=this.params.desiredState.seekState.getState(),r=i.state!=="none";if(this.params.desiredState.seekState.setState({state:"requested",position:r?i.position:t,forcePrecise:r?i.forcePrecise:!1}),e.scene3D){let n=e.scene3D.getCameraRotation();this.params.desiredState.cameraOrientation.setState({x:n.x,y:n.y})}let s=this.providerOutput.isBuffering$;s.getValue()||s.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),this.tracer.log("createProvider",{destination:e,format:t}),e){case"SCREEN":return this.createScreenProvider(t);case"CHROMECAST":return this.createChromecastProvider(t);default:return Ws(e)}}createScreenProvider(e){var u,l;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 c=this.applyFailoverHost(t[e]),d=this.applyFailoverHost(t.HLS_ONDEMAND||t.HLS);return oi(c),this.params.tuning.useNewDashProvider?new Ns({...o,source:c,sourceHls:d,forceVideoCodec:(u=this.videoCodecsIterator)==null?void 0:u.getValue()}):new As({...o,source:c,sourceHls:d,forceVideoCodec:(l=this.videoCodecsIterator)==null?void 0:l.getValue()})}case"DASH_LIVE_CMAF":{let c=this.applyFailoverHost(t[e]);return oi(c),this.params.tuning.useNewDashProvider?new qs({...o,source:c}):new Rs({...o,source:c})}case"HLS":case"HLS_ONDEMAND":case"HLS_FMP4":{let c=this.applyFailoverHost(t[e]);return oi(c),new js({...o,source:c})}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let c=this.applyFailoverHost(t[e]);return oi(c),new Us({...o,source:c,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case"MPEG":{let c=this.applyFailoverHost(t[e]);return oi(c),new Hs({...o,source:c})}case"DASH_LIVE":{let c=this.applyFailoverHost(t[e]);return oi(c),new ry({...o,source:c,config:{..._V,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case"WEB_RTC_LIVE":{let c=this.applyFailoverHost(t[e]);return oi(c),new Qs({container:i,source:c,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 Ws(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 oi(o),new xa({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 Ws(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return Ws(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 Ws(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,TE.default)((0,yE.default)(e).map(([r,s])=>[r,i(s)]))}initProviderErrorHandling(){let e=new vE,t=!1,i=0;return e.add(BV(this.providerOutput.error$.pipe(gE(r=>!this.params.tuning.ignoreAudioRendererError||!r.message||!/AUDIO_RENDERER_ERROR/ig.test(r.message))),hE({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(CV(r=>({id:`ProviderHangup:${r}`,category:cu.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(gE(({to:s})=>s==="playing"),VV()).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===cu.NETWORK,u=r.category===cu.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=this.videoCodecsIterator&&!this.videoCodecsIterator.isLast()&&this.params.tuning.dash.codecsPrioritizeEnabled,f=l&&!u&&(o&&t||!c);n={...n,isNetworkError:o,isFatalError:u,haveFailoverHost:l,tryFailover:f,canReinitProvider:c},c?(i++,this.reinitProvider()):f?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):d?this.switchToNextVideoCodec():(i=0,this.switchToNextProvider(s!=null?s:"SCREEN"))}r.traceAsLog?this.tracer.log("providerInfo",Zd(n)):this.tracer.error("providerError",Zd(n))})),e}};import{fromEvent as du,once as OV,combine as FV,Subscription as IE,ValueSubject as tp,map as NV,filter as qV,isNonNullable as pu,now as ze,safeStorage as ip}from"@vkontakte/videoplayer-shared/es2018";var UV=5e3,EE="one_video_throughput",xE="one_video_rtt",Vt=window.navigator.connection,wE=()=>{let a=Vt==null?void 0:Vt.downlink;if(pu(a)&&a!==10)return a*1e3},AE=()=>{let a=Vt==null?void 0:Vt.rtt;if(pu(a)&&a!==3e3)return a},RE=(a,e,t)=>{let i=t*8,r=i/a;return i/(r+e)},rp=class a{constructor(e){this.subscription=new IE;this.concurrentDownloads=new Set;var r,s;this.tuningConfig=e;let t=a.load(EE)||(e.useBrowserEstimation?wE():void 0)||UV,i=(s=(r=a.load(xE))!=null?r:e.useBrowserEstimation?AE():void 0)!=null?s:0;if(this.throughput$=new tp(t),this.rtt$=new tp(i),this.rttAdjustedThroughput$=new tp(RE(t,i,e.rttPenaltyRequestSize)),this.throughput=Ct.getSmoothedValue(t,-1,e),this.rtt=Ct.getSmoothedValue(i,1,e),e.useBrowserEstimation){let n=()=>{let u=wE();u&&this.throughput.next(u);let l=AE();pu(l)&&this.rtt.next(l)};Vt&&"onchange"in Vt&&this.subscription.add(du(Vt,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{ip.set(EE,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{ip.set(xE,n.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(FV({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(NV(({throughput:n,rtt:o})=>RE(n,o,e.rttPenaltyRequestSize)),qV(n=>{let o=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(n-o)/o>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,i=ze(),r=new IE;switch(this.subscription.add(r),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:r.add(du(e,"progress").pipe(OV()).subscribe(s=>{t=s.loaded,i=ze()}));break;case 1:case 0:r.add(du(e,"loadstart").subscribe(()=>{t=0,i=ze()}));break}r.add(du(e,"loadend").subscribe(s=>{if(e.status===200){let n=s.loaded,o=ze(),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=ze(),n=0,o=ze(),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,ze()-s,1),this.concurrentDownloads.delete(e);else if(d){if(t){let f=ze();if(f-o>this.tuningConfig.lowLatency.continuesByteSequenceInterval||f-s>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let h=o-s;h&&this.addRawSpeed(n,h,1,t),n=d.byteLength,s=ze()}else n+=d.byteLength;o=ze()}else r+=d.byteLength,n+=d.byteLength,n>=this.tuningConfig.streamMinSampleSize&&ze()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,ze()-o,this.concurrentDownloads.size),n=0,o=ze());await(i==null?void 0:i.read().then(l,u))}};this.concurrentDownloads.add(e),i==null||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){var i;let t=ip.get(e);if(pu(t))return(i=parseInt(t,10))!=null?i:void 0}},PE=rp;import{fillWithDefault as jV,VideoQuality as hu}from"@vkontakte/videoplayer-shared/es2018";var kE={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:hu.Q_4320P,activeVideoAreaThreshold:.1,highQualityLimit:hu.Q_720P,trafficSavingLimit:hu.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:hu.Q_480P},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,seekBiasInTheEnd:2e3,maxSegmentDurationLeftToSelectNextSegment:3e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:15e3,crashOnStallTimeout:25e3,crashOnStallTWithoutDataTimeout:5e3,enableSubSegmentBufferFeeding:!0,bufferEmptinessTolerance:100,useNewRepresentationSwitch:!1,useDelayedRepresentationSwitch:!1,useSmartRepresentationSwitch:!1,useFetchPriorityHints:!0,enableBaseUrlSupport:!0,maxSegmentRetryCount:5,sourceOpenTimeout:1e3,vktvAbrThrottle:0,timeupdateEventTickThrottle:300,fetcherBufferOptimisation:!0,codecsPrioritizeEnabled:!1},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,maxLiveDuration:7200,catchupLiveForMutedInactiveTab:!0,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:250,playbackCatchupSpeedup:.05,isActiveOnDefault:!1,bufferEstimator:{emaAlpha:.45,changeThreshold:.05,deviationDepth:20,deviationFactor:.5,extremumInterval:5}}},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1,lowLatencyActiveLiveDelay:3e3,activeLiveDelay:5e3,maxPausedTime:5e3},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,forceFormat:void 0,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:"07A4434E",useWebmBigRequest:!1,webmCodec:"vp9",androidPreferredFormat:"dash",iosPreferredFormat:"hls",preferCMAF:!1,preferWebRTC:!1,preferMultiStream:!1,preferHDR:!1,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,seekNearDurationBias:1,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useHlsJs:!1,useNativeHLSTextTracks:!1,useNewSwitchTo:!1,useNewDashProvider:!1,useNewAutoSelectVideoTrack:!1,useSafariEndlessRequestBugfix:!0,useRefactoredSearchGap:!1,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,manifestRetryInterval:300,manifestRetryMaxInterval:1e4,manifestRetryMaxCount:10,audioVideoSyncRate:20,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50},useVolumeMultiplier:!1,ignoreAudioRendererError:!1,useEnableSubtitlesParam:!1,useHlsLiveNewTextManager:!1,exposeInternalsToGlobal:!1,hlsLiveNewTextManagerDownloadThreshold:4e3,disableYandexPiP:!1,asyncResolveClientChecker:!1,autostartOnlyIfVisible:!1,changePlaybackStateToPausedWhenEnded:!1},LE=a=>{var e;return{...jV(a,kE),configName:[...(e=a.configName)!=null?e:[],...kE.configName]}};import{assertNonNullable as fu,combine as _t,ErrorCategory as mu,filter as U,filterChanged as Y,fromEvent as sp,isNonNullable as CE,isNullable as KV,Logger as XV,map as W,mapTo as BE,merge as ui,now as bu,once as H,Subject as G,Subscription as VE,tap as np,ValueSubject as C,isHigher as JV,isInvariantQuality as _E,flattenObject as li,throttle as op,getTraceSubscriptionMethod as OE,TracerFactory as ZV,InternalsExposure as e_}from"@vkontakte/videoplayer-shared/es2018";import{merge as HV,map as QV,filter as $E,isNonNullable as GV}from"@vkontakte/videoplayer-shared/es2018";var ap=({seekState:a,position$:e})=>HV(a.stateChangeEnded$.pipe(QV(({to:t})=>{var i;return t.state==="none"?void 0:((i=t.position)!=null?i:NaN)/1e3}),$E(GV)),e.pipe($E(()=>a.getState().state==="none")));import{assertNonNullable as WV}from"@vkontakte/videoplayer-shared/es2018";var ME=a=>{let e=typeof a.container=="string"?document.getElementById(a.container):a.container;return WV(e,`Wrong container or containerId {${a.container}}`),e};import{filter as zV,once as YV}from"@vkontakte/videoplayer-shared/es2018";var DE=(a,e,t,i)=>{a!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&(t==null?void 0:t.getValue().length)===0?t.pipe(zV(r=>r.length>0),YV()).subscribe(r=>{r.find(i)&&e.startTransitionTo(a)}):(a===void 0||t!=null&&t.getValue().find(i))&&e.startTransitionTo(a)};var gu=class{constructor(e={configName:[]},t=ZV.createRootTracer(!1)){this.subscription=new VE;this.logger=new XV;this.abrLogger=this.logger.createComponentLog("ABR");this.internalsExposure=null;this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new C(!1);this.hasLiveOffsetByPausedTimer=0;this.playerInitRequest=0;this.playerInited=new C(!1);this.wasSetStartedQuality=!1;this.desiredState={playbackState:new j("stopped"),seekState:new j({state:"none"}),volume:new j({volume:1,muted:!1}),videoTrack:new j(void 0),videoStream:new j(void 0),audioStream:new j(void 0),autoVideoTrackSwitching:new j(!0),autoVideoTrackLimits:new j({}),isLooped:new j(!1),isLowLatency:new j(!1),playbackRate:new j(1),externalTextTracks:new j([]),internalTextTracks:new j([]),currentTextTrack:new j(void 0),textTrackCuesSettings:new j({}),cameraOrientation:new j({x:0,y:0})};this.info={playbackState$:new C(void 0),position$:new C(0),duration$:new C(1/0),muted$:new C(!1),volume$:new C(1),availableVideoStreams$:new C([]),currentVideoStream$:new C(void 0),availableQualities$:new C([]),availableQualitiesFps$:new C({}),currentQuality$:new C(void 0),isAutoQualityEnabled$:new C(!0),autoQualityLimitingAvailable$:new C(!1),autoQualityLimits$:new C({}),predefinedQualityLimitType$:new C("unknown"),availableAudioStreams$:new C([]),currentAudioStream$:new C(void 0),availableAudioTracks$:new C([]),isAudioAvailable$:new C(!0),currentPlaybackRate$:new C(1),currentBuffer$:new C({start:0,end:0}),isBuffering$:new C(!0),isStalled$:new C(!1),isEnded$:new C(!1),isLooped$:new C(!1),isLive$:new C(void 0),isLiveEnded$:new C(null),canPlayLiveTailBuffer$:new C(!1),canChangePlaybackSpeed$:new C(void 0),atLiveEdge$:new C(void 0),atLiveDurationEdge$:new C(void 0),liveTime$:new C(void 0),liveBufferTime$:new C(void 0),liveLatency$:new C(void 0),currentFormat$:new C(void 0),availableTextTracks$:new C([]),currentTextTrack$:new C(void 0),throughputEstimation$:new C(void 0),rttEstimation$:new C(void 0),videoBitrate$:new C(void 0),hostname$:new C(void 0),httpConnectionType$:new C(void 0),httpConnectionReused$:new C(void 0),surface$:new C("none"),chromecastState$:new C("NOT_AVAILABLE"),chromecastDeviceName$:new C(void 0),intrinsicVideoSize$:new C(void 0),availableSources$:new C(void 0),is3DVideo$:new C(!1),currentVideoSegmentLength$:new C(0),currentAudioSegmentLength$:new C(0)};this.events={inited$:new G,ready$:new G,started$:new G,playing$:new G,paused$:new G,stopped$:new G,willReady$:new G,willStart$:new G,willResume$:new G,willPause$:new G,willStop$:new G,willDestruct$:new G,watchCoverageRecord$:new G,watchCoverageLive$:new G,managedError$:new G,fatalError$:new G,fetcherRecoverableError$:new G,ended$:new G,looped$:new G,seeked$:new G,willSeek$:new G,autoplaySoundProhibited$:new G,manifestRequested$:new G,manifestReceived$:new G,firstBytesRequested$:new G,firstBytesReceived$:new G,firstBytes$:new G,loadedMetadata$:new G,firstFrame$:new G,canplay$:new G,log$:new G,fetcherError$:new G,severeStallOccured$:new G};this.experimental={element$:new C(void 0),tuningConfigName$:new C([]),enableDebugTelemetry$:new C(!1),dumpTelemetry:kv,getCurrentTime$:new C(null)};if(this.initLogs(),this.tuning=LE(e),this.tracer=t,this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new bn({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new PE(this.tuning.throughputEstimator),e.exposeInternalsToGlobal&&(this.internalsExposure=new e_("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(f=>JSON.stringify(f,(p,h)=>{let m=typeof h;return(0,FE.default)(["number","string","boolean"],m)?h:h===null?null:`<${m}>`})),c=`Player.${String(r)}`,d=`Exception calling ${c} (${l.join(", ")})`;throw this.events.fatalError$.next({id:c,category:mu.WTF,message:d,thrown:u}),u}}}})}initVideo(e){var s;this.config=e,(s=this.internalsExposure)==null||s.expose({config:e,logger:this.logger,tuning:this.tuning}),this.setMuted(this.tuning.isAudioDisabled);let t=()=>{var u,l,c;let{container:n,...o}=e;this.tracer.log("initVideo",li(o)),this.domContainer=ME(e),this.chromecastInitializer.contentId=(u=e.meta)==null?void 0:u.videoId,this.providerContainer=new zs({sources:e.sources,meta:(l=e.meta)!=null?l:{},failoverHosts:(c=e.failoverHosts)!=null?c:[],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?F.isInited$.pipe(U(n=>!!n),H()).subscribe(()=>{console.log("Core SDK async start"),i()}):i()};return this.isNotActiveTabCase()?(this.tracer.log("request play from hidden tab"),sp(document,"visibilitychange").pipe(H()).subscribe(r)):r(),this}destroy(){var e,t;this.tracer.log("destroy"),window.clearTimeout(this.hasLiveOffsetByPausedTimer),this.playerInitRequest&&window.cancelAnimationFrame(this.playerInitRequest),this.events.willDestruct$.next(),this.stop(),(e=this.providerContainer)==null||e.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe(),this.tracer.end(),(t=this.internalsExposure)==null||t.destroy()}prepare(){return this.subscription.add(this.playerInited.pipe(U(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(U(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(U(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(U(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(U(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(U(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(U(i=>!!i),H()).subscribe(()=>{var o;let i=this.desiredState.volume,r=i.getTransition(),s=(o=r==null?void 0:r.to.muted)!=null?o:this.info.muted$.getValue(),n=t!=null?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(U(i=>!!i),H()).subscribe(()=>{var o;let i=this.desiredState.volume,r=this.tuning.isAudioDisabled&&!t||e,s=i.getTransition(),n=(o=s==null?void 0:s.to.volume)!=null?o: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(U(t=>!!t),H()).subscribe(()=>{this.desiredState.videoStream.startTransitionTo(e)})),this}setAudioStream(e){return this.subscription.add(this.playerInited.pipe(U(t=>!!t),H()).subscribe(()=>{this.desiredState.audioStream.startTransitionTo(e)})),this}setQuality(e){return this.subscription.add(this.playerInited.pipe(U(t=>!!t),H()).subscribe(()=>{fu(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(U(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(U(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(U(t=>!!t),H()).subscribe(()=>{this.tracer.log("setAutoQualityLimits",li(e)),this.desiredState.autoVideoTrackLimits.startTransitionTo(e)})),this}setPredefinedQualityLimits(e){return this.subscription.add(this.playerInited.pipe(U(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(U(t=>!!t),H()).subscribe(()=>{var i;fu(this.providerContainer);let t=(i=this.providerContainer)==null?void 0:i.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(U(t=>!!t),H()).subscribe(()=>{e.length&&this.tracer.log("setExternalTextTracks",li(e)),this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>({type:"external",...t})))})),this}selectTextTrack(e){return this.subscription.add(this.playerInited.pipe(U(t=>!!t),H()).subscribe(()=>{var t;DE(e,this.desiredState.currentTextTrack,(t=this.providerContainer)==null?void 0:t.providerOutput.availableTextTracks$,i=>i.id===e),this.tracer.log("selectTextTrack",{textTrackId:e})})),this}setTextTrackCueSettings(e){return this.subscription.add(this.playerInited.pipe(U(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(U(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(U(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(U(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(U(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(U(e=>e),H()).subscribe(()=>{let e=this.getScene3D();e&&e.holdCamera()})),this}releaseCamera(){return this.subscription.add(this.playerInited.pipe(U(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(KV(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),i=t.state==="none"?void 0:t.position;return CE(i)?i/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}getScene3D(){var t,i;let e=(t=this.providerContainer)==null?void 0:t.current$.getValue();if((i=e==null?void 0:e.provider)!=null&&i.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(ui(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(W(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(W(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(W(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(W(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(W(e=>e.to)).subscribe(e=>{this.info.autoQualityLimits$.next(e);let{highQualityLimit:t,trafficSavingLimit:i}=this.tuning.autoTrackSelection;this.info.predefinedQualityLimitType$.next(Lc(e,t,i))})),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(U(({from:e})=>e==="stopped"),H()).subscribe(()=>{this.initedAt=bu(),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",li(n)),n.state==="requested"?this.desiredState.seekState.setState({...n,state:"applying"}):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:mu.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",li(n)),n.state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe(W(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(W(n=>n.destination),Y()).subscribe(()=>this.isPlaybackStarted=!1)).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add(_t({availableVideoTracks:e.providerOutput.availableVideoTracks$,currentVideoStream:e.providerOutput.currentVideoStream$}).pipe(W(({availableVideoTracks:n,currentVideoStream:o})=>n.filter(u=>o?o.id===u.streamId:!0).map(({quality:u})=>u).sort((u,l)=>_E(u)?1:_E(l)?-1:JV(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(Y()).subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.pipe(U(n=>CE(n))).subscribe(n=>{this.info.currentQuality$.next(n==null?void 0:n.quality),this.info.videoBitrate$.next(n==null?void 0:n.bitrate)})).add(e.providerOutput.currentVideoSegmentLength$.pipe(Y((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.pipe(Y((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe(Y()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(Y()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(Y()).subscribe(this.info.httpConnectionReused$)).add(e.providerOutput.currentTextTrack$.subscribe(this.info.currentTextTrack$)).add(e.providerOutput.availableTextTracks$.subscribe(this.info.availableTextTracks$)).add(e.providerOutput.autoVideoTrackLimitingAvailable$.subscribe(this.info.autoQualityLimitingAvailable$)).add(e.providerOutput.autoVideoTrackLimits$.subscribe(n=>{this.desiredState.autoVideoTrackLimits.setState(n!=null?n:{})})).add(e.providerOutput.currentBuffer$.pipe(W(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(np(n=>n&&this.stop())).subscribe(this.info.isLiveEnded$)).add(e.providerOutput.canPlayLiveTailBuffer$.subscribe(this.info.canPlayLiveTailBuffer$)).add(e.providerOutput.canChangePlaybackSpeed$.subscribe(this.info.canChangePlaybackSpeed$)).add(e.providerOutput.liveTime$.subscribe(this.info.liveTime$)).add(e.providerOutput.liveBufferTime$.subscribe(this.info.liveBufferTime$)).add(e.providerOutput.liveLatency$.subscribe(this.info.liveLatency$)).add(_t({hasLiveOffsetByPaused:ui(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(W(n=>n.to),Y(),W(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(_t({atLiveEdge:_t({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:ap({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(W(({isLive:n,position:o,isLowLatency:u})=>{let l=this.getActiveLiveDelay(u);return n&&Math.abs(o)<l/1e3}),Y(),np(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(W(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add(_t({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(W(({isLive:n,position:o,duration:u})=>n&&(Math.abs(u)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),Y(),np(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(W(n=>n.muted),Y()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(W(n=>n.volume),Y()).subscribe(this.info.volume$)).add(ap({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(ui(e.providerOutput.endedEvent$.pipe(BE(!0)),e.providerOutput.seekedEvent$.pipe(BE(!1))).pipe(Y()).subscribe(this.info.isEnded$)).add(e.providerOutput.endedEvent$.subscribe(this.events.ended$)).add(e.providerOutput.loopedEvent$.subscribe(this.events.looped$)).add(e.providerError$.subscribe(this.events.managedError$)).add(e.providerOutput.fetcherRecoverableError$.subscribe(this.events.fetcherRecoverableError$)).add(e.providerOutput.fetcherError$.subscribe(this.events.fatalError$)).add(e.volumeMultiplierError$.subscribe(this.events.managedError$)).add(e.noAvailableProvidersError$.pipe(W(n=>({id:n?`No${n}`:"NoProviders",category:mu.VIDEO_PIPELINE,message:n?`${n} was forced but failed or not available`:"No suitable providers or all providers failed"}))).subscribe(this.events.fatalError$)).add(e.providerOutput.element$.subscribe(this.experimental.element$)).add(e.providerOutput.getCurrentTime$.subscribe(this.experimental.getCurrentTime$)).add(e.providerOutput.manifestRequested$.pipe(H()).subscribe(this.events.manifestRequested$)).add(e.providerOutput.manifestReceived$.pipe(H()).subscribe(this.events.manifestReceived$)).add(e.providerOutput.firstBytesRequested$.pipe(H()).subscribe(this.events.firstBytesRequested$)).add(e.providerOutput.firstBytesReceived$.pipe(H()).subscribe(this.events.firstBytesReceived$)).add(e.providerOutput.firstBytesEvent$.pipe(H(),W(n=>n!=null?n:bu()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe(H(),W(()=>bu()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(H(),W(()=>bu()-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 C(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let i=new C(!0);this.subscription.add(e.current$.subscribe(()=>i.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(U(({to:n})=>n==="playing"),H()).subscribe(()=>i.next(!1)));let r=0,s=ui(e.providerOutput.isBuffering$,t,i).pipe(W(()=>{let n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||i.getValue();return n&&!o}),Y());this.subscription.add(s.subscribe(n=>{n?r=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(r),this.info.isStalled$.next(!1))})),this.subscription.add(ui(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{let n=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:n==null?void 0:n.videoWidth,height:n==null?void 0:n.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{var u,l;let o=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:(u=n==null?void 0:n.size)==null?void 0:u.width,height:(l=n==null?void 0:n.size)==null?void 0:l.height},{width:o==null?void 0:o.videoWidth,height:o==null?void 0:o.videoHeight})})).add(e.providerOutput.is3DVideo$.subscribe(this.info.is3DVideo$)),this.subscription.add(ui(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(W(e=>e==null?void 0:e.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){let t=new VE;this.subscription.add(t),this.subscription.add(e.current$.pipe(Y((i,r)=>i.provider===r.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(U(i=>i.length>0),H()).subscribe(i=>{this.setStartingVideoTrack(i)}))}))}setStartingVideoTrack(e){var r;let t;this.wasSetStartedQuality=!0;let i=(r=this.explicitInitialQuality)!=null?r:this.info.currentQuality$.getValue();i&&(t=e.find(({quality:s})=>s===i),t||this.setAutoQuality(!0)),t||(t=vt(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(ui(this.desiredState.videoTrack.stateChangeStarted$.pipe(W(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(W(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(W(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(W(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(W(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(W(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(W(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(W(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(W(e=>({component:"desiredState",message:`[${e.entity} change] ${e.type}: ${JSON.stringify(e.transition)}`}))).subscribe(this.logger.log)),this.subscription.add(this.logger.log$.subscribe(this.events.log$))}initDebugTelemetry(){var t;let e=(t=this.providerContainer)==null?void 0:t.providerOutput;fu(this.providerContainer),fu(e),Pv(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(i=>Rv(i)),this.providerContainer.current$.subscribe(({type:i})=>Pa("provider",i)),e.duration$.subscribe(i=>Pa("duration",i)),e.availableVideoTracks$.pipe(U(i=>!!i.length),H()).subscribe(i=>Pa("tracks",i)),this.events.fatalError$.subscribe(new ke("fatalError")),this.events.managedError$.subscribe(new ke("managedError")),e.position$.subscribe(new ke("position")),e.currentVideoTrack$.pipe(W(i=>i==null?void 0:i.quality)).subscribe(new ke("quality")),this.info.currentBuffer$.subscribe(new ke("buffer")),e.isBuffering$.subscribe(new ke("isBuffering"))].forEach(i=>this.subscription.add(i)),Pa("codecs",F.video.supportedCodecs)}initTracerSubscription(){let e=OE(this.tracer.log.bind(this.tracer)),t=OE(this.tracer.error.bind(this.tracer));this.subscription.add(this.info.playbackState$.subscribe(e("playbackState"))).add(this.info.isLooped$.subscribe(e("isLooped"))).add(this.info.currentPlaybackRate$.pipe(Y()).subscribe(e("currentPlaybackRate"))).add(this.info.isAutoQualityEnabled$.subscribe(e("isAutoQualityEnabled"))).add(this.info.autoQualityLimits$.subscribe(e("autoQualityLimits"))).add(this.info.currentFormat$.subscribe(e("currentFormat"))).add(this.info.availableQualities$.subscribe(e("availableQualities"))).add(this.info.availableQualitiesFps$.subscribe(e("availableQualitiesFps"))).add(this.info.availableAudioTracks$.subscribe(e("availableAudioTracks"))).add(this.info.isAudioAvailable$.subscribe(e("isAudioAvailable"))).add(_t({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe(U(({currentQuality:i,videoBitrate:r})=>!!i&&!!r),Y((i,r)=>i.currentQuality===r.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe(U(i=>i>0),Y()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe(U(i=>i>0),Y()).subscribe(e("currentAudioSegmentLength"))).add(this.info.hostname$.subscribe(e("hostname"))).add(this.info.currentTextTrack$.subscribe(e("currentTextTrack"))).add(this.info.availableTextTracks$.subscribe(e("availableTextTracks"))).add(this.info.autoQualityLimitingAvailable$.subscribe(e("autoQualityLimitingAvailable"))).add(_t({currentBuffer:this.info.currentBuffer$.pipe(U(i=>i.end>0),Y((i,r)=>i.end===r.end&&i.start===r.start)),position:this.info.position$.pipe(Y())}).pipe(op(1e3)).subscribe(e("currentBufferAndPosition"))).add(this.info.duration$.pipe(Y()).subscribe(e("duration"))).add(this.info.isBuffering$.subscribe(e("isBuffering"))).add(this.info.isLive$.pipe(Y()).subscribe(e("isLive"))).add(this.info.canChangePlaybackSpeed$.pipe(Y()).subscribe(e("canChangePlaybackSpeed"))).add(_t({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe(U(({liveTime:i,liveBufferTime:r})=>!!i&&!!r),op(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe(Y(),U(i=>i===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe(Y(),U(i=>i===!0)).subscribe(e("atLiveDurationEdge"))).add(this.info.muted$.pipe(Y()).subscribe(e("muted"))).add(this.info.volume$.pipe(Y()).subscribe(e("volume"))).add(this.info.isEnded$.pipe(Y(),U(i=>i===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add(_t({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe(U(({throughputEstimation:i,rtt:r})=>!!i&&!!r),op(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe(Y(),U(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==null||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:mu.DOM,message:String(r)})})};this.subscription.add(ui(sp(document,"visibilitychange"),sp(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{let r=document.visibilityState==="visible",s=this.desiredState.playbackState.getState()==="playing",n=!!e&&!(e!=null&&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",li({quality:t,availableTracks:li(e),track:li(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&&!Ba()}};import{Subscription as wJ,Observable as AJ,Subject as RJ,ValueSubject as PJ,VideoQuality as kJ}from"@vkontakte/videoplayer-shared/es2018";var LJ=`@vkontakte/videoplayer-core@${Wp}`;export{ln as ChromecastState,Eu as HttpConnectionType,AJ as Observable,De as PlaybackState,gu as Player,cn as PredefinedQualityLimits,LJ as SDK_VERSION,RJ as Subject,wJ as Subscription,xu as Surface,Wp as VERSION,PJ as ValueSubject,At as VideoFormat,kJ as VideoQuality,U$ as areValidLiveRecordSources,F as clientChecker,Ea as isMobile};