@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/es2015.cjs.js +34 -34
- package/es2015.esm.js +34 -34
- package/es2018.cjs.js +31 -31
- package/es2018.esm.js +35 -35
- package/es2024.cjs.js +41 -41
- package/es2024.esm.js +46 -46
- package/esnext.cjs.js +41 -41
- package/esnext.esm.js +46 -46
- package/evergreen.esm.js +25 -25
- package/package.json +2 -2
- package/types/providers/DashProvider/lib/buffer.d.ts +2 -0
- package/types/providers/DashProvider/lib/player.d.ts +1 -0
- package/types/providers/DashProviderNew/lib/buffer.d.ts +2 -0
- package/types/providers/DashProviderNew/lib/player.d.ts +1 -0
- package/types/utils/tuningConfig.d.ts +3 -0
package/esnext.esm.js
CHANGED
|
@@ -1,127 +1,127 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @vkontakte/videoplayer-core v2.0.138-dev.
|
|
3
|
-
*
|
|
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 FI=Object.create;var Fd=Object.defineProperty;var NI=Object.getOwnPropertyDescriptor;var qI=Object.getOwnPropertyNames;var UI=Object.getPrototypeOf,HI=Object.prototype.hasOwnProperty;var m=(a,e)=>()=>(e||a((e={exports:{}}).exports,e),e.exports);var jI=(a,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of qI(e))!HI.call(a,r)&&r!==t&&Fd(a,r,{get:()=>e[r],enumerable:!(i=NI(e,r))||i.enumerable});return a};var C=(a,e,t)=>(t=a!=null?FI(UI(a)):{},jI(e||!a||!a.__esModule?Fd(t,"default",{value:a,enumerable:!0}):t,a));var re=m((Xo,qd)=>{"use strict";var Fr=function(a){return a&&a.Math===Math&&a};qd.exports=Fr(typeof globalThis=="object"&&globalThis)||Fr(typeof window=="object"&&window)||Fr(typeof self=="object"&&self)||Fr(typeof global=="object"&&global)||Fr(typeof Xo=="object"&&Xo)||function(){return this}()||Function("return this")()});var ce=m((W0,Ud)=>{"use strict";Ud.exports=function(a){try{return!!a()}catch{return!0}}});var Nr=m((G0,Hd)=>{"use strict";var QI=ce();Hd.exports=!QI(function(){var a=function(){}.bind();return typeof a!="function"||a.hasOwnProperty("prototype")})});var Jo=m((z0,Gd)=>{"use strict";var WI=Nr(),Wd=Function.prototype,jd=Wd.apply,Qd=Wd.call;Gd.exports=typeof Reflect=="object"&&Reflect.apply||(WI?Qd.bind(jd):function(){return Qd.apply(jd,arguments)})});var de=m((Y0,Kd)=>{"use strict";var zd=Nr(),Yd=Function.prototype,Zo=Yd.call,GI=zd&&Yd.bind.bind(Zo,Zo);Kd.exports=zd?GI:function(a){return function(){return Zo.apply(a,arguments)}}});var si=m((K0,Jd)=>{"use strict";var Xd=de(),zI=Xd({}.toString),YI=Xd("".slice);Jd.exports=function(a){return YI(zI(a),8,-1)}});var eu=m((X0,Zd)=>{"use strict";var KI=si(),XI=de();Zd.exports=function(a){if(KI(a)==="Function")return XI(a)}});var ae=m((J0,ep)=>{"use strict";var tu=typeof document=="object"&&document.all;ep.exports=typeof tu>"u"&&tu!==void 0?function(a){return typeof a=="function"||a===tu}:function(a){return typeof a=="function"}});var Fe=m((Z0,tp)=>{"use strict";var JI=ce();tp.exports=!JI(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var Ne=m((eV,ip)=>{"use strict";var ZI=Nr(),_s=Function.prototype.call;ip.exports=ZI?_s.bind(_s):function(){return _s.apply(_s,arguments)}});var iu=m(sp=>{"use strict";var rp={}.propertyIsEnumerable,ap=Object.getOwnPropertyDescriptor,eE=ap&&!rp.call({1:2},1);sp.f=eE?function(e){var t=ap(this,e);return!!t&&t.enumerable}:rp});var qr=m((iV,np)=>{"use strict";np.exports=function(a,e){return{enumerable:!(a&1),configurable:!(a&2),writable:!(a&4),value:e}}});var up=m((rV,op)=>{"use strict";var tE=de(),iE=ce(),rE=si(),ru=Object,aE=tE("".split);op.exports=iE(function(){return!ru("z").propertyIsEnumerable(0)})?function(a){return rE(a)==="String"?aE(a,""):ru(a)}:ru});var Ur=m((aV,lp)=>{"use strict";lp.exports=function(a){return a==null}});var Ft=m((sV,cp)=>{"use strict";var sE=Ur(),nE=TypeError;cp.exports=function(a){if(sE(a))throw new nE("Can't call method on "+a);return a}});var ni=m((nV,dp)=>{"use strict";var oE=up(),uE=Ft();dp.exports=function(a){return oE(uE(a))}});var Le=m((oV,pp)=>{"use strict";var lE=ae();pp.exports=function(a){return typeof a=="object"?a!==null:lE(a)}});var oi=m((uV,hp)=>{"use strict";hp.exports={}});var wt=m((lV,mp)=>{"use strict";var au=oi(),su=re(),cE=ae(),fp=function(a){return cE(a)?a:void 0};mp.exports=function(a,e){return arguments.length<2?fp(au[a])||fp(su[a]):au[a]&&au[a][e]||su[a]&&su[a][e]}});var Hr=m((cV,bp)=>{"use strict";var dE=de();bp.exports=dE({}.isPrototypeOf)});var ui=m((dV,vp)=>{"use strict";var pE=re(),gp=pE.navigator,Sp=gp&&gp.userAgent;vp.exports=Sp?String(Sp):""});var ou=m((pV,wp)=>{"use strict";var xp=re(),nu=ui(),yp=xp.process,Tp=xp.Deno,Ip=yp&&yp.versions||Tp&&Tp.version,Ep=Ip&&Ip.v8,et,Os;Ep&&(et=Ep.split("."),Os=et[0]>0&&et[0]<4?1:+(et[0]+et[1]));!Os&&nu&&(et=nu.match(/Edge\/(\d+)/),(!et||et[1]>=74)&&(et=nu.match(/Chrome\/(\d+)/),et&&(Os=+et[1])));wp.exports=Os});var uu=m((hV,Pp)=>{"use strict";var Ap=ou(),hE=ce(),fE=re(),mE=fE.String;Pp.exports=!!Object.getOwnPropertySymbols&&!hE(function(){var a=Symbol("symbol detection");return!mE(a)||!(Object(a)instanceof Symbol)||!Symbol.sham&&Ap&&Ap<41})});var lu=m((fV,kp)=>{"use strict";var bE=uu();kp.exports=bE&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var cu=m((mV,Rp)=>{"use strict";var gE=wt(),SE=ae(),vE=Hr(),yE=lu(),TE=Object;Rp.exports=yE?function(a){return typeof a=="symbol"}:function(a){var e=gE("Symbol");return SE(e)&&vE(e.prototype,TE(a))}});var jr=m((bV,Lp)=>{"use strict";var IE=String;Lp.exports=function(a){try{return IE(a)}catch{return"Object"}}});var ht=m((gV,$p)=>{"use strict";var EE=ae(),xE=jr(),wE=TypeError;$p.exports=function(a){if(EE(a))return a;throw new wE(xE(a)+" is not a function")}});var Qr=m((SV,Mp)=>{"use strict";var AE=ht(),PE=Ur();Mp.exports=function(a,e){var t=a[e];return PE(t)?void 0:AE(t)}});var Cp=m((vV,Dp)=>{"use strict";var du=Ne(),pu=ae(),hu=Le(),kE=TypeError;Dp.exports=function(a,e){var t,i;if(e==="string"&&pu(t=a.toString)&&!hu(i=du(t,a))||pu(t=a.valueOf)&&!hu(i=du(t,a))||e!=="string"&&pu(t=a.toString)&&!hu(i=du(t,a)))return i;throw new kE("Can't convert object to primitive value")}});var tt=m((yV,Bp)=>{"use strict";Bp.exports=!0});var Op=m((TV,_p)=>{"use strict";var Vp=re(),RE=Object.defineProperty;_p.exports=function(a,e){try{RE(Vp,a,{value:e,configurable:!0,writable:!0})}catch{Vp[a]=e}return e}});var Wr=m((IV,qp)=>{"use strict";var LE=tt(),$E=re(),ME=Op(),Fp="__core-js_shared__",Np=qp.exports=$E[Fp]||ME(Fp,{});(Np.versions||(Np.versions=[])).push({version:"3.43.0",mode:LE?"pure":"global",copyright:"\xA9 2014-2025 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.43.0/LICENSE",source:"https://github.com/zloirock/core-js"})});var fu=m((EV,Hp)=>{"use strict";var Up=Wr();Hp.exports=function(a,e){return Up[a]||(Up[a]=e||{})}});var Oi=m((xV,jp)=>{"use strict";var DE=Ft(),CE=Object;jp.exports=function(a){return CE(DE(a))}});var it=m((wV,Qp)=>{"use strict";var BE=de(),VE=Oi(),_E=BE({}.hasOwnProperty);Qp.exports=Object.hasOwn||function(e,t){return _E(VE(e),t)}});var mu=m((AV,Wp)=>{"use strict";var OE=de(),FE=0,NE=Math.random(),qE=OE(1.1.toString);Wp.exports=function(a){return"Symbol("+(a===void 0?"":a)+")_"+qE(++FE+NE,36)}});var be=m((PV,zp)=>{"use strict";var UE=re(),HE=fu(),Gp=it(),jE=mu(),QE=uu(),WE=lu(),Fi=UE.Symbol,bu=HE("wks"),GE=WE?Fi.for||Fi:Fi&&Fi.withoutSetter||jE;zp.exports=function(a){return Gp(bu,a)||(bu[a]=QE&&Gp(Fi,a)?Fi[a]:GE("Symbol."+a)),bu[a]}});var Jp=m((kV,Xp)=>{"use strict";var zE=Ne(),Yp=Le(),Kp=cu(),YE=Qr(),KE=Cp(),XE=be(),JE=TypeError,ZE=XE("toPrimitive");Xp.exports=function(a,e){if(!Yp(a)||Kp(a))return a;var t=YE(a,ZE),i;if(t){if(e===void 0&&(e="default"),i=zE(t,a,e),!Yp(i)||Kp(i))return i;throw new JE("Can't convert object to primitive value")}return e===void 0&&(e="number"),KE(a,e)}});var gu=m((RV,Zp)=>{"use strict";var ex=Jp(),tx=cu();Zp.exports=function(a){var e=ex(a,"string");return tx(e)?e:e+""}});var Fs=m((LV,th)=>{"use strict";var ix=re(),eh=Le(),Su=ix.document,rx=eh(Su)&&eh(Su.createElement);th.exports=function(a){return rx?Su.createElement(a):{}}});var vu=m(($V,ih)=>{"use strict";var ax=Fe(),sx=ce(),nx=Fs();ih.exports=!ax&&!sx(function(){return Object.defineProperty(nx("div"),"a",{get:function(){return 7}}).a!==7})});var sh=m(ah=>{"use strict";var ox=Fe(),ux=Ne(),lx=iu(),cx=qr(),dx=ni(),px=gu(),hx=it(),fx=vu(),rh=Object.getOwnPropertyDescriptor;ah.f=ox?rh:function(e,t){if(e=dx(e),t=px(t),fx)try{return rh(e,t)}catch{}if(hx(e,t))return cx(!ux(lx.f,e,t),e[t])}});var yu=m((DV,nh)=>{"use strict";var mx=ce(),bx=ae(),gx=/#|\.prototype\./,Gr=function(a,e){var t=vx[Sx(a)];return t===Tx?!0:t===yx?!1:bx(e)?mx(e):!!e},Sx=Gr.normalize=function(a){return String(a).replace(gx,".").toLowerCase()},vx=Gr.data={},yx=Gr.NATIVE="N",Tx=Gr.POLYFILL="P";nh.exports=Gr});var Ni=m((CV,uh)=>{"use strict";var oh=eu(),Ix=ht(),Ex=Nr(),xx=oh(oh.bind);uh.exports=function(a,e){return Ix(a),e===void 0?a:Ex?xx(a,e):function(){return a.apply(e,arguments)}}});var Tu=m((BV,lh)=>{"use strict";var wx=Fe(),Ax=ce();lh.exports=wx&&Ax(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var ft=m((VV,ch)=>{"use strict";var Px=Le(),kx=String,Rx=TypeError;ch.exports=function(a){if(Px(a))return a;throw new Rx(kx(a)+" is not an object")}});var li=m(ph=>{"use strict";var Lx=Fe(),$x=vu(),Mx=Tu(),Ns=ft(),dh=gu(),Dx=TypeError,Iu=Object.defineProperty,Cx=Object.getOwnPropertyDescriptor,Eu="enumerable",xu="configurable",wu="writable";ph.f=Lx?Mx?function(e,t,i){if(Ns(e),t=dh(t),Ns(i),typeof e=="function"&&t==="prototype"&&"value"in i&&wu in i&&!i[wu]){var r=Cx(e,t);r&&r[wu]&&(e[t]=i.value,i={configurable:xu in i?i[xu]:r[xu],enumerable:Eu in i?i[Eu]:r[Eu],writable:!1})}return Iu(e,t,i)}:Iu:function(e,t,i){if(Ns(e),t=dh(t),Ns(i),$x)try{return Iu(e,t,i)}catch{}if("get"in i||"set"in i)throw new Dx("Accessors not supported");return"value"in i&&(e[t]=i.value),e}});var qi=m((OV,hh)=>{"use strict";var Bx=Fe(),Vx=li(),_x=qr();hh.exports=Bx?function(a,e,t){return Vx.f(a,e,_x(1,t))}:function(a,e,t){return a[e]=t,a}});var oe=m((FV,mh)=>{"use strict";var zr=re(),Ox=Jo(),Fx=eu(),Nx=ae(),qx=sh().f,Ux=yu(),Ui=oi(),Hx=Ni(),Hi=qi(),fh=it();Wr();var jx=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 Ox(a,this,arguments)};return e.prototype=a.prototype,e};mh.exports=function(a,e){var t=a.target,i=a.global,r=a.stat,s=a.proto,n=i?zr:r?zr[t]:zr[t]&&zr[t].prototype,u=i?Ui:Ui[t]||Hi(Ui,t,{})[t],o=u.prototype,l,c,p,d,h,f,b,S,g;for(d in e)l=Ux(i?d:t+(r?".":"#")+d,a.forced),c=!l&&n&&fh(n,d),f=u[d],c&&(a.dontCallGetSet?(g=qx(n,d),b=g&&g.value):b=n[d]),h=c&&b?b:e[d],!(!l&&!s&&typeof f==typeof h)&&(a.bind&&c?S=Hx(h,zr):a.wrap&&c?S=jx(h):s&&Nx(h)?S=Fx(h):S=h,(a.sham||h&&h.sham||f&&f.sham)&&Hi(S,"sham",!0),Hi(u,d,S),s&&(p=t+"Prototype",fh(Ui,p)||Hi(Ui,p,{}),Hi(Ui[p],d,h),a.real&&o&&(l||!o[d])&&Hi(o,d,h)))}});var gh=m((NV,bh)=>{"use strict";var Qx=Math.ceil,Wx=Math.floor;bh.exports=Math.trunc||function(e){var t=+e;return(t>0?Wx:Qx)(t)}});var Yr=m((qV,Sh)=>{"use strict";var Gx=gh();Sh.exports=function(a){var e=+a;return e!==e||e===0?0:Gx(e)}});var yh=m((UV,vh)=>{"use strict";var zx=Yr(),Yx=Math.max,Kx=Math.min;vh.exports=function(a,e){var t=zx(a);return t<0?Yx(t+e,0):Kx(t,e)}});var Au=m((HV,Th)=>{"use strict";var Xx=Yr(),Jx=Math.min;Th.exports=function(a){var e=Xx(a);return e>0?Jx(e,9007199254740991):0}});var ji=m((jV,Ih)=>{"use strict";var Zx=Au();Ih.exports=function(a){return Zx(a.length)}});var Pu=m((QV,xh)=>{"use strict";var ew=ni(),tw=yh(),iw=ji(),Eh=function(a){return function(e,t,i){var r=ew(e),s=iw(r);if(s===0)return!a&&-1;var n=tw(i,s),u;if(a&&t!==t){for(;s>n;)if(u=r[n++],u!==u)return!0}else for(;s>n;n++)if((a||n in r)&&r[n]===t)return a||n||0;return!a&&-1}};xh.exports={includes:Eh(!0),indexOf:Eh(!1)}});var Kr=m((WV,wh)=>{"use strict";wh.exports=function(){}});var Ah=m(()=>{"use strict";var rw=oe(),aw=Pu().includes,sw=ce(),nw=Kr(),ow=sw(function(){return!Array(1).includes()});rw({target:"Array",proto:!0,forced:ow},{includes:function(e){return aw(this,e,arguments.length>1?arguments[1]:void 0)}});nw("includes")});var Nt=m((YV,Ph)=>{"use strict";var uw=wt();Ph.exports=uw});var Rh=m((KV,kh)=>{"use strict";Ah();var lw=Nt();kh.exports=lw("Array","includes")});var $h=m((XV,Lh)=>{"use strict";var cw=Rh();Lh.exports=cw});var Ee=m((JV,Mh)=>{"use strict";var dw=$h();Mh.exports=dw});var Hs=m((c_,Nh)=>{"use strict";var vw=fu(),yw=mu(),Fh=vw("keys");Nh.exports=function(a){return Fh[a]||(Fh[a]=yw(a))}});var Uh=m((d_,qh)=>{"use strict";var Tw=ce();qh.exports=!Tw(function(){function a(){}return a.prototype.constructor=null,Object.getPrototypeOf(new a)!==a.prototype})});var js=m((p_,jh)=>{"use strict";var Iw=it(),Ew=ae(),xw=Oi(),ww=Hs(),Aw=Uh(),Hh=ww("IE_PROTO"),Lu=Object,Pw=Lu.prototype;jh.exports=Aw?Lu.getPrototypeOf:function(a){var e=xw(a);if(Iw(e,Hh))return e[Hh];var t=e.constructor;return Ew(t)&&e instanceof t?t.prototype:e instanceof Lu?Pw:null}});var Qs=m((h_,Qh)=>{"use strict";Qh.exports={}});var zh=m((f_,Gh)=>{"use strict";var kw=de(),$u=it(),Rw=ni(),Lw=Pu().indexOf,$w=Qs(),Wh=kw([].push);Gh.exports=function(a,e){var t=Rw(a),i=0,r=[],s;for(s in t)!$u($w,s)&&$u(t,s)&&Wh(r,s);for(;e.length>i;)$u(t,s=e[i++])&&(~Lw(r,s)||Wh(r,s));return r}});var Mu=m((m_,Yh)=>{"use strict";Yh.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var Du=m((b_,Kh)=>{"use strict";var Mw=zh(),Dw=Mu();Kh.exports=Object.keys||function(e){return Mw(e,Dw)}});var Cu=m((g_,tf)=>{"use strict";var Jh=Fe(),Cw=ce(),Zh=de(),Bw=js(),Vw=Du(),_w=ni(),Ow=iu().f,ef=Zh(Ow),Fw=Zh([].push),Nw=Jh&&Cw(function(){var a=Object.create(null);return a[2]=2,!ef(a,2)}),Xh=function(a){return function(e){for(var t=_w(e),i=Vw(t),r=Nw&&Bw(t)===null,s=i.length,n=0,u=[],o;s>n;)o=i[n++],(!Jh||(r?o in t:ef(t,o)))&&Fw(u,a?[o,t[o]]:t[o]);return u}};tf.exports={entries:Xh(!0),values:Xh(!1)}});var rf=m(()=>{"use strict";var qw=oe(),Uw=Cu().entries;qw({target:"Object",stat:!0},{entries:function(e){return Uw(e)}})});var sf=m((y_,af)=>{"use strict";rf();var Hw=oi();af.exports=Hw.Object.entries});var of=m((T_,nf)=>{"use strict";var jw=sf();nf.exports=jw});var Qi=m((I_,uf)=>{"use strict";var Qw=of();uf.exports=Qw});var ci=m((E_,lf)=>{"use strict";lf.exports={}});var pf=m((x_,df)=>{"use strict";var Ww=re(),Gw=ae(),cf=Ww.WeakMap;df.exports=Gw(cf)&&/native code/.test(String(cf))});var Ou=m((w_,mf)=>{"use strict";var zw=pf(),ff=re(),Yw=Le(),Kw=qi(),Bu=it(),Vu=Wr(),Xw=Hs(),Jw=Qs(),hf="Object already initialized",_u=ff.TypeError,Zw=ff.WeakMap,Ws,Xr,Gs,eA=function(a){return Gs(a)?Xr(a):Ws(a,{})},tA=function(a){return function(e){var t;if(!Yw(e)||(t=Xr(e)).type!==a)throw new _u("Incompatible receiver, "+a+" required");return t}};zw||Vu.state?(rt=Vu.state||(Vu.state=new Zw),rt.get=rt.get,rt.has=rt.has,rt.set=rt.set,Ws=function(a,e){if(rt.has(a))throw new _u(hf);return e.facade=a,rt.set(a,e),e},Xr=function(a){return rt.get(a)||{}},Gs=function(a){return rt.has(a)}):(di=Xw("state"),Jw[di]=!0,Ws=function(a,e){if(Bu(a,di))throw new _u(hf);return e.facade=a,Kw(a,di,e),e},Xr=function(a){return Bu(a,di)?a[di]:{}},Gs=function(a){return Bu(a,di)});var rt,di;mf.exports={set:Ws,get:Xr,has:Gs,enforce:eA,getterFor:tA}});var qu=m((A_,gf)=>{"use strict";var Fu=Fe(),iA=it(),bf=Function.prototype,rA=Fu&&Object.getOwnPropertyDescriptor,Nu=iA(bf,"name"),aA=Nu&&function(){}.name==="something",sA=Nu&&(!Fu||Fu&&rA(bf,"name").configurable);gf.exports={EXISTS:Nu,PROPER:aA,CONFIGURABLE:sA}});var vf=m(Sf=>{"use strict";var nA=Fe(),oA=Tu(),uA=li(),lA=ft(),cA=ni(),dA=Du();Sf.f=nA&&!oA?Object.defineProperties:function(e,t){lA(e);for(var i=cA(t),r=dA(t),s=r.length,n=0,u;s>n;)uA.f(e,u=r[n++],i[u]);return e}});var Uu=m((k_,yf)=>{"use strict";var pA=wt();yf.exports=pA("document","documentElement")});var Wu=m((R_,Pf)=>{"use strict";var hA=ft(),fA=vf(),Tf=Mu(),mA=Qs(),bA=Uu(),gA=Fs(),SA=Hs(),If=">",Ef="<",ju="prototype",Qu="script",wf=SA("IE_PROTO"),Hu=function(){},Af=function(a){return Ef+Qu+If+a+Ef+"/"+Qu+If},xf=function(a){a.write(Af("")),a.close();var e=a.parentWindow.Object;return a=null,e},vA=function(){var a=gA("iframe"),e="java"+Qu+":",t;return a.style.display="none",bA.appendChild(a),a.src=String(e),t=a.contentWindow.document,t.open(),t.write(Af("document.F=Object")),t.close(),t.F},zs,Ys=function(){try{zs=new ActiveXObject("htmlfile")}catch{}Ys=typeof document<"u"?document.domain&&zs?xf(zs):vA():xf(zs);for(var a=Tf.length;a--;)delete Ys[ju][Tf[a]];return Ys()};mA[wf]=!0;Pf.exports=Object.create||function(e,t){var i;return e!==null?(Hu[ju]=hA(e),i=new Hu,Hu[ju]=null,i[wf]=e):i=Ys(),t===void 0?i:fA.f(i,t)}});var Wi=m((L_,kf)=>{"use strict";var yA=qi();kf.exports=function(a,e,t,i){return i&&i.enumerable?a[e]=t:yA(a,e,t),a}});var Ku=m(($_,$f)=>{"use strict";var TA=ce(),IA=ae(),EA=Le(),xA=Wu(),Rf=js(),wA=Wi(),AA=be(),PA=tt(),Yu=AA("iterator"),Lf=!1,At,Gu,zu;[].keys&&(zu=[].keys(),"next"in zu?(Gu=Rf(Rf(zu)),Gu!==Object.prototype&&(At=Gu)):Lf=!0);var kA=!EA(At)||TA(function(){var a={};return At[Yu].call(a)!==a});kA?At={}:PA&&(At=xA(At));IA(At[Yu])||wA(At,Yu,function(){return this});$f.exports={IteratorPrototype:At,BUGGY_SAFARI_ITERATORS:Lf}});var Ks=m((M_,Df)=>{"use strict";var RA=be(),LA=RA("toStringTag"),Mf={};Mf[LA]="z";Df.exports=String(Mf)==="[object z]"});var Jr=m((D_,Cf)=>{"use strict";var $A=Ks(),MA=ae(),Xs=si(),DA=be(),CA=DA("toStringTag"),BA=Object,VA=Xs(function(){return arguments}())==="Arguments",_A=function(a,e){try{return a[e]}catch{}};Cf.exports=$A?Xs:function(a){var e,t,i;return a===void 0?"Undefined":a===null?"Null":typeof(t=_A(e=BA(a),CA))=="string"?t:VA?Xs(e):(i=Xs(e))==="Object"&&MA(e.callee)?"Arguments":i}});var Vf=m((C_,Bf)=>{"use strict";var OA=Ks(),FA=Jr();Bf.exports=OA?{}.toString:function(){return"[object "+FA(this)+"]"}});var Zr=m((B_,Of)=>{"use strict";var NA=Ks(),qA=li().f,UA=qi(),HA=it(),jA=Vf(),QA=be(),_f=QA("toStringTag");Of.exports=function(a,e,t,i){var r=t?a:a&&a.prototype;r&&(HA(r,_f)||qA(r,_f,{configurable:!0,value:e}),i&&!NA&&UA(r,"toString",jA))}});var Nf=m((V_,Ff)=>{"use strict";var WA=Ku().IteratorPrototype,GA=Wu(),zA=qr(),YA=Zr(),KA=ci(),XA=function(){return this};Ff.exports=function(a,e,t,i){var r=e+" Iterator";return a.prototype=GA(WA,{next:zA(+!i,t)}),YA(a,r,!1,!0),KA[r]=XA,a}});var Uf=m((__,qf)=>{"use strict";var JA=de(),ZA=ht();qf.exports=function(a,e,t){try{return JA(ZA(Object.getOwnPropertyDescriptor(a,e)[t]))}catch{}}});var jf=m((O_,Hf)=>{"use strict";var eP=Le();Hf.exports=function(a){return eP(a)||a===null}});var Wf=m((F_,Qf)=>{"use strict";var tP=jf(),iP=String,rP=TypeError;Qf.exports=function(a){if(tP(a))return a;throw new rP("Can't set "+iP(a)+" as a prototype")}});var Xu=m((N_,Gf)=>{"use strict";var aP=Uf(),sP=Le(),nP=Ft(),oP=Wf();Gf.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var a=!1,e={},t;try{t=aP(Object.prototype,"__proto__","set"),t(e,[]),a=e instanceof Array}catch{}return function(r,s){return nP(r),oP(s),sP(r)&&(a?t(r,s):r.__proto__=s),r}}():void 0)});var am=m((q_,rm)=>{"use strict";var uP=oe(),lP=Ne(),Js=tt(),tm=qu(),cP=ae(),dP=Nf(),zf=js(),Yf=Xu(),pP=Zr(),hP=qi(),Ju=Wi(),fP=be(),Kf=ci(),im=Ku(),mP=tm.PROPER,bP=tm.CONFIGURABLE,Xf=im.IteratorPrototype,Zs=im.BUGGY_SAFARI_ITERATORS,ea=fP("iterator"),Jf="keys",ta="values",Zf="entries",em=function(){return this};rm.exports=function(a,e,t,i,r,s,n){dP(t,e,i);var u=function(g){if(g===r&&d)return d;if(!Zs&&g&&g in c)return c[g];switch(g){case Jf:return function(){return new t(this,g)};case ta:return function(){return new t(this,g)};case Zf:return function(){return new t(this,g)}}return function(){return new t(this)}},o=e+" Iterator",l=!1,c=a.prototype,p=c[ea]||c["@@iterator"]||r&&c[r],d=!Zs&&p||u(r),h=e==="Array"&&c.entries||p,f,b,S;if(h&&(f=zf(h.call(new a)),f!==Object.prototype&&f.next&&(!Js&&zf(f)!==Xf&&(Yf?Yf(f,Xf):cP(f[ea])||Ju(f,ea,em)),pP(f,o,!0,!0),Js&&(Kf[o]=em))),mP&&r===ta&&p&&p.name!==ta&&(!Js&&bP?hP(c,"name",ta):(l=!0,d=function(){return lP(p,this)})),r)if(b={values:u(ta),keys:s?d:u(Jf),entries:u(Zf)},n)for(S in b)(Zs||l||!(S in c))&&Ju(c,S,b[S]);else uP({target:e,proto:!0,forced:Zs||l},b);return(!Js||n)&&c[ea]!==d&&Ju(c,ea,d,{name:r}),Kf[e]=d,b}});var nm=m((U_,sm)=>{"use strict";sm.exports=function(a,e){return{value:a,done:e}}});var el=m((H_,dm)=>{"use strict";var gP=ni(),Zu=Kr(),om=ci(),lm=Ou(),SP=li().f,vP=am(),en=nm(),yP=tt(),TP=Fe(),cm="Array Iterator",IP=lm.set,EP=lm.getterFor(cm);dm.exports=vP(Array,"Array",function(a,e){IP(this,{type:cm,target:gP(a),index:0,kind:e})},function(){var a=EP(this),e=a.target,t=a.index++;if(!e||t>=e.length)return a.target=null,en(void 0,!0);switch(a.kind){case"keys":return en(t,!1);case"values":return en(e[t],!1)}return en([t,e[t]],!1)},"values");var um=om.Arguments=om.Array;Zu("keys");Zu("values");Zu("entries");if(!yP&&TP&&um.name!=="values")try{SP(um,"name",{value:"values"})}catch{}});var hm=m((j_,pm)=>{"use strict";var xP=be(),wP=ci(),AP=xP("iterator"),PP=Array.prototype;pm.exports=function(a){return a!==void 0&&(wP.Array===a||PP[AP]===a)}});var tl=m((Q_,mm)=>{"use strict";var kP=Jr(),fm=Qr(),RP=Ur(),LP=ci(),$P=be(),MP=$P("iterator");mm.exports=function(a){if(!RP(a))return fm(a,MP)||fm(a,"@@iterator")||LP[kP(a)]}});var gm=m((W_,bm)=>{"use strict";var DP=Ne(),CP=ht(),BP=ft(),VP=jr(),_P=tl(),OP=TypeError;bm.exports=function(a,e){var t=arguments.length<2?_P(a):e;if(CP(t))return BP(DP(t,a));throw new OP(VP(a)+" is not iterable")}});var ym=m((G_,vm)=>{"use strict";var FP=Ne(),Sm=ft(),NP=Qr();vm.exports=function(a,e,t){var i,r;Sm(a);try{if(i=NP(a,"return"),!i){if(e==="throw")throw t;return t}i=FP(i,a)}catch(s){r=!0,i=s}if(e==="throw")throw t;if(r)throw i;return Sm(i),t}});var rn=m((z_,xm)=>{"use strict";var qP=Ni(),UP=Ne(),HP=ft(),jP=jr(),QP=hm(),WP=ji(),Tm=Hr(),GP=gm(),zP=tl(),Im=ym(),YP=TypeError,tn=function(a,e){this.stopped=a,this.result=e},Em=tn.prototype;xm.exports=function(a,e,t){var i=t&&t.that,r=!!(t&&t.AS_ENTRIES),s=!!(t&&t.IS_RECORD),n=!!(t&&t.IS_ITERATOR),u=!!(t&&t.INTERRUPTED),o=qP(e,i),l,c,p,d,h,f,b,S=function(I){return l&&Im(l,"normal"),new tn(!0,I)},g=function(I){return r?(HP(I),u?o(I[0],I[1],S):o(I[0],I[1])):u?o(I,S):o(I)};if(s)l=a.iterator;else if(n)l=a;else{if(c=zP(a),!c)throw new YP(jP(a)+" is not iterable");if(QP(c)){for(p=0,d=WP(a);d>p;p++)if(h=g(a[p]),h&&Tm(Em,h))return h;return new tn(!1)}l=GP(a,c)}for(f=s?a.next:l.next;!(b=UP(f,l)).done;){try{h=g(b.value)}catch(I){Im(l,"throw",I)}if(typeof h=="object"&&h&&Tm(Em,h))return h}return new tn(!1)}});var Am=m((Y_,wm)=>{"use strict";var KP=Fe(),XP=li(),JP=qr();wm.exports=function(a,e,t){KP?XP.f(a,e,JP(0,t)):a[e]=t}});var Pm=m(()=>{"use strict";var ZP=oe(),ek=rn(),tk=Am();ZP({target:"Object",stat:!0},{fromEntries:function(e){var t={};return ek(e,function(i,r){tk(t,i,r)},{AS_ENTRIES:!0}),t}})});var Rm=m((J_,km)=>{"use strict";el();Pm();var ik=oi();km.exports=ik.Object.fromEntries});var $m=m((Z_,Lm)=>{"use strict";Lm.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 Dm=m(()=>{"use strict";el();var rk=$m(),ak=re(),sk=Zr(),Mm=ci();for(an in rk)sk(ak[an],an),Mm[an]=Mm.Array;var an});var Bm=m((iO,Cm)=>{"use strict";var nk=Rm();Dm();Cm.exports=nk});var il=m((rO,Vm)=>{"use strict";var ok=Bm();Vm.exports=ok});var _m=m(()=>{"use strict"});var rl=m((nO,Om)=>{"use strict";var ia=re(),uk=ui(),lk=si(),sn=function(a){return uk.slice(0,a.length)===a};Om.exports=function(){return sn("Bun/")?"BUN":sn("Cloudflare-Workers")?"CLOUDFLARE":sn("Deno/")?"DENO":sn("Node.js/")?"NODE":ia.Bun&&typeof Bun.version=="string"?"BUN":ia.Deno&&typeof Deno.version=="object"?"DENO":lk(ia.process)==="process"?"NODE":ia.window&&ia.document?"BROWSER":"REST"}()});var nn=m((oO,Fm)=>{"use strict";var ck=rl();Fm.exports=ck==="NODE"});var qm=m((uO,Nm)=>{"use strict";var dk=li();Nm.exports=function(a,e,t){return dk.f(a,e,t)}});var jm=m((lO,Hm)=>{"use strict";var pk=wt(),hk=qm(),fk=be(),mk=Fe(),Um=fk("species");Hm.exports=function(a){var e=pk(a);mk&&e&&!e[Um]&&hk(e,Um,{configurable:!0,get:function(){return this}})}});var Wm=m((cO,Qm)=>{"use strict";var bk=Hr(),gk=TypeError;Qm.exports=function(a,e){if(bk(e,a))return a;throw new gk("Incorrect invocation")}});var sl=m((dO,Gm)=>{"use strict";var Sk=de(),vk=ae(),al=Wr(),yk=Sk(Function.toString);vk(al.inspectSource)||(al.inspectSource=function(a){return yk(a)});Gm.exports=al.inspectSource});var ol=m((pO,Jm)=>{"use strict";var Tk=de(),Ik=ce(),zm=ae(),Ek=Jr(),xk=wt(),wk=sl(),Ym=function(){},Km=xk("Reflect","construct"),nl=/^\s*(?:class|function)\b/,Ak=Tk(nl.exec),Pk=!nl.test(Ym),ra=function(e){if(!zm(e))return!1;try{return Km(Ym,[],e),!0}catch{return!1}},Xm=function(e){if(!zm(e))return!1;switch(Ek(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return Pk||!!Ak(nl,wk(e))}catch{return!0}};Xm.sham=!0;Jm.exports=!Km||Ik(function(){var a;return ra(ra.call)||!ra(Object)||!ra(function(){a=!0})||a})?Xm:ra});var eb=m((hO,Zm)=>{"use strict";var kk=ol(),Rk=jr(),Lk=TypeError;Zm.exports=function(a){if(kk(a))return a;throw new Lk(Rk(a)+" is not a constructor")}});var ul=m((fO,ib)=>{"use strict";var tb=ft(),$k=eb(),Mk=Ur(),Dk=be(),Ck=Dk("species");ib.exports=function(a,e){var t=tb(a).constructor,i;return t===void 0||Mk(i=tb(t)[Ck])?e:$k(i)}});var ab=m((mO,rb)=>{"use strict";var Bk=de();rb.exports=Bk([].slice)});var nb=m((bO,sb)=>{"use strict";var Vk=TypeError;sb.exports=function(a,e){if(a<e)throw new Vk("Not enough arguments");return a}});var ll=m((gO,ob)=>{"use strict";var _k=ui();ob.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(_k)});var Sl=m((SO,bb)=>{"use strict";var qe=re(),Ok=Jo(),Fk=Ni(),ub=ae(),Nk=it(),mb=ce(),lb=Uu(),qk=ab(),cb=Fs(),Uk=nb(),Hk=ll(),jk=nn(),ml=qe.setImmediate,bl=qe.clearImmediate,Qk=qe.process,cl=qe.Dispatch,Wk=qe.Function,db=qe.MessageChannel,Gk=qe.String,dl=0,aa={},pb="onreadystatechange",sa,pi,pl,hl;mb(function(){sa=qe.location});var gl=function(a){if(Nk(aa,a)){var e=aa[a];delete aa[a],e()}},fl=function(a){return function(){gl(a)}},hb=function(a){gl(a.data)},fb=function(a){qe.postMessage(Gk(a),sa.protocol+"//"+sa.host)};(!ml||!bl)&&(ml=function(e){Uk(arguments.length,1);var t=ub(e)?e:Wk(e),i=qk(arguments,1);return aa[++dl]=function(){Ok(t,void 0,i)},pi(dl),dl},bl=function(e){delete aa[e]},jk?pi=function(a){Qk.nextTick(fl(a))}:cl&&cl.now?pi=function(a){cl.now(fl(a))}:db&&!Hk?(pl=new db,hl=pl.port2,pl.port1.onmessage=hb,pi=Fk(hl.postMessage,hl)):qe.addEventListener&&ub(qe.postMessage)&&!qe.importScripts&&sa&&sa.protocol!=="file:"&&!mb(fb)?(pi=fb,qe.addEventListener("message",hb,!1)):pb in cb("script")?pi=function(a){lb.appendChild(cb("script"))[pb]=function(){lb.removeChild(this),gl(a)}}:pi=function(a){setTimeout(fl(a),0)});bb.exports={set:ml,clear:bl}});var vb=m((vO,Sb)=>{"use strict";var gb=re(),zk=Fe(),Yk=Object.getOwnPropertyDescriptor;Sb.exports=function(a){if(!zk)return gb[a];var e=Yk(gb,a);return e&&e.value}});var vl=m((yO,Tb)=>{"use strict";var yb=function(){this.head=null,this.tail=null};yb.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}}};Tb.exports=yb});var Eb=m((TO,Ib)=>{"use strict";var Kk=ui();Ib.exports=/ipad|iphone|ipod/i.test(Kk)&&typeof Pebble<"u"});var wb=m((IO,xb)=>{"use strict";var Xk=ui();xb.exports=/web0s(?!.*chrome)/i.test(Xk)});var Mb=m((EO,$b)=>{"use strict";var zi=re(),Jk=vb(),Ab=Ni(),yl=Sl().set,Zk=vl(),eR=ll(),tR=Eb(),iR=wb(),Tl=nn(),Pb=zi.MutationObserver||zi.WebKitMutationObserver,kb=zi.document,Rb=zi.process,on=zi.Promise,xl=Jk("queueMicrotask"),Gi,Il,El,un,Lb;xl||(na=new Zk,oa=function(){var a,e;for(Tl&&(a=Rb.domain)&&a.exit();e=na.get();)try{e()}catch(t){throw na.head&&Gi(),t}a&&a.enter()},!eR&&!Tl&&!iR&&Pb&&kb?(Il=!0,El=kb.createTextNode(""),new Pb(oa).observe(El,{characterData:!0}),Gi=function(){El.data=Il=!Il}):!tR&&on&&on.resolve?(un=on.resolve(void 0),un.constructor=on,Lb=Ab(un.then,un),Gi=function(){Lb(oa)}):Tl?Gi=function(){Rb.nextTick(oa)}:(yl=Ab(yl,zi),Gi=function(){yl(oa)}),xl=function(a){na.head||Gi(),na.add(a)});var na,oa;$b.exports=xl});var Cb=m((xO,Db)=>{"use strict";Db.exports=function(a,e){try{arguments.length===1?console.error(a):console.error(a,e)}catch{}}});var ln=m((wO,Bb)=>{"use strict";Bb.exports=function(a){try{return{error:!1,value:a()}}catch(e){return{error:!0,value:e}}}});var hi=m((AO,Vb)=>{"use strict";var rR=re();Vb.exports=rR.Promise});var Yi=m((PO,Nb)=>{"use strict";var aR=re(),ua=hi(),sR=ae(),nR=yu(),oR=sl(),uR=be(),_b=rl(),lR=tt(),wl=ou(),Ob=ua&&ua.prototype,cR=uR("species"),Al=!1,Fb=sR(aR.PromiseRejectionEvent),dR=nR("Promise",function(){var a=oR(ua),e=a!==String(ua);if(!e&&wl===66||lR&&!(Ob.catch&&Ob.finally))return!0;if(!wl||wl<51||!/native code/.test(a)){var t=new ua(function(s){s(1)}),i=function(s){s(function(){},function(){})},r=t.constructor={};if(r[cR]=i,Al=t.then(function(){})instanceof i,!Al)return!0}return!e&&(_b==="BROWSER"||_b==="DENO")&&!Fb});Nb.exports={CONSTRUCTOR:dR,REJECTION_EVENT:Fb,SUBCLASSING:Al}});var Ki=m((kO,Ub)=>{"use strict";var qb=ht(),pR=TypeError,hR=function(a){var e,t;this.promise=new a(function(i,r){if(e!==void 0||t!==void 0)throw new pR("Bad Promise constructor");e=i,t=r}),this.resolve=qb(e),this.reject=qb(t)};Ub.exports.f=function(a){return new hR(a)}});var ug=m(()=>{"use strict";var fR=oe(),mR=tt(),hn=nn(),qt=re(),bR=oi(),er=Ne(),Hb=Wi(),jb=Xu(),gR=Zr(),SR=jm(),vR=ht(),pn=ae(),yR=Le(),TR=Wm(),IR=ul(),Yb=Sl().set,$l=Mb(),ER=Cb(),xR=ln(),wR=vl(),Kb=Ou(),fn=hi(),Ml=Yi(),Xb=Ki(),mn="Promise",Jb=Ml.CONSTRUCTOR,AR=Ml.REJECTION_EVENT,PR=Ml.SUBCLASSING,Pl=Kb.getterFor(mn),kR=Kb.set,Xi=fn&&fn.prototype,fi=fn,cn=Xi,Zb=qt.TypeError,kl=qt.document,Dl=qt.process,Rl=Xb.f,RR=Rl,LR=!!(kl&&kl.createEvent&&qt.dispatchEvent),eg="unhandledrejection",$R="rejectionhandled",Qb=0,tg=1,MR=2,Cl=1,ig=2,dn,Wb,rg,Gb,ag=function(a){var e;return yR(a)&&pn(e=a.then)?e:!1},sg=function(a,e){var t=e.value,i=e.state===tg,r=i?a.ok:a.fail,s=a.resolve,n=a.reject,u=a.domain,o,l,c;try{r?(i||(e.rejection===ig&&CR(e),e.rejection=Cl),r===!0?o=t:(u&&u.enter(),o=r(t),u&&(u.exit(),c=!0)),o===a.promise?n(new Zb("Promise-chain cycle")):(l=ag(o))?er(l,o,s,n):s(o)):n(t)}catch(p){u&&!c&&u.exit(),n(p)}},ng=function(a,e){a.notified||(a.notified=!0,$l(function(){for(var t=a.reactions,i;i=t.get();)sg(i,a);a.notified=!1,e&&!a.rejection&&DR(a)}))},og=function(a,e,t){var i,r;LR?(i=kl.createEvent("Event"),i.promise=e,i.reason=t,i.initEvent(a,!1,!0),qt.dispatchEvent(i)):i={promise:e,reason:t},!AR&&(r=qt["on"+a])?r(i):a===eg&&ER("Unhandled promise rejection",t)},DR=function(a){er(Yb,qt,function(){var e=a.facade,t=a.value,i=zb(a),r;if(i&&(r=xR(function(){hn?Dl.emit("unhandledRejection",t,e):og(eg,e,t)}),a.rejection=hn||zb(a)?ig:Cl,r.error))throw r.value})},zb=function(a){return a.rejection!==Cl&&!a.parent},CR=function(a){er(Yb,qt,function(){var e=a.facade;hn?Dl.emit("rejectionHandled",e):og($R,e,a.value)})},Ji=function(a,e,t){return function(i){a(e,i,t)}},Zi=function(a,e,t){a.done||(a.done=!0,t&&(a=t),a.value=e,a.state=MR,ng(a,!0))},Ll=function(a,e,t){if(!a.done){a.done=!0,t&&(a=t);try{if(a.facade===e)throw new Zb("Promise can't be resolved itself");var i=ag(e);i?$l(function(){var r={done:!1};try{er(i,e,Ji(Ll,r,a),Ji(Zi,r,a))}catch(s){Zi(r,s,a)}}):(a.value=e,a.state=tg,ng(a,!1))}catch(r){Zi({done:!1},r,a)}}};if(Jb&&(fi=function(e){TR(this,cn),vR(e),er(dn,this);var t=Pl(this);try{e(Ji(Ll,t),Ji(Zi,t))}catch(i){Zi(t,i)}},cn=fi.prototype,dn=function(e){kR(this,{type:mn,done:!1,notified:!1,parent:!1,reactions:new wR,rejection:!1,state:Qb,value:null})},dn.prototype=Hb(cn,"then",function(e,t){var i=Pl(this),r=Rl(IR(this,fi));return i.parent=!0,r.ok=pn(e)?e:!0,r.fail=pn(t)&&t,r.domain=hn?Dl.domain:void 0,i.state===Qb?i.reactions.add(r):$l(function(){sg(r,i)}),r.promise}),Wb=function(){var a=new dn,e=Pl(a);this.promise=a,this.resolve=Ji(Ll,e),this.reject=Ji(Zi,e)},Xb.f=Rl=function(a){return a===fi||a===rg?new Wb(a):RR(a)},!mR&&pn(fn)&&Xi!==Object.prototype)){Gb=Xi.then,PR||Hb(Xi,"then",function(e,t){var i=this;return new fi(function(r,s){er(Gb,i,r,s)}).then(e,t)},{unsafe:!0});try{delete Xi.constructor}catch{}jb&&jb(Xi,cn)}fR({global:!0,constructor:!0,wrap:!0,forced:Jb},{Promise:fi});rg=bR.Promise;gR(fi,mn,!1,!0);SR(mn)});var hg=m(($O,pg)=>{"use strict";var BR=be(),cg=BR("iterator"),dg=!1;try{lg=0,Bl={next:function(){return{done:!!lg++}},return:function(){dg=!0}},Bl[cg]=function(){return this},Array.from(Bl,function(){throw 2})}catch{}var lg,Bl;pg.exports=function(a,e){try{if(!e&&!dg)return!1}catch{return!1}var t=!1;try{var i={};i[cg]=function(){return{next:function(){return{done:t=!0}}}},a(i)}catch{}return t}});var Vl=m((MO,fg)=>{"use strict";var VR=hi(),_R=hg(),OR=Yi().CONSTRUCTOR;fg.exports=OR||!_R(function(a){VR.all(a).then(void 0,function(){})})});var mg=m(()=>{"use strict";var FR=oe(),NR=Ne(),qR=ht(),UR=Ki(),HR=ln(),jR=rn(),QR=Vl();FR({target:"Promise",stat:!0,forced:QR},{all:function(e){var t=this,i=UR.f(t),r=i.resolve,s=i.reject,n=HR(function(){var u=qR(t.resolve),o=[],l=0,c=1;jR(e,function(p){var d=l++,h=!1;c++,NR(u,t,p).then(function(f){h||(h=!0,o[d]=f,--c||r(o))},s)}),--c||r(o)});return n.error&&s(n.value),i.promise}})});var gg=m(()=>{"use strict";var WR=oe(),GR=tt(),zR=Yi().CONSTRUCTOR,Ol=hi(),YR=wt(),KR=ae(),XR=Wi(),bg=Ol&&Ol.prototype;WR({target:"Promise",proto:!0,forced:zR,real:!0},{catch:function(a){return this.then(void 0,a)}});!GR&&KR(Ol)&&(_l=YR("Promise").prototype.catch,bg.catch!==_l&&XR(bg,"catch",_l,{unsafe:!0}));var _l});var Sg=m(()=>{"use strict";var JR=oe(),ZR=Ne(),eL=ht(),tL=Ki(),iL=ln(),rL=rn(),aL=Vl();JR({target:"Promise",stat:!0,forced:aL},{race:function(e){var t=this,i=tL.f(t),r=i.reject,s=iL(function(){var n=eL(t.resolve);rL(e,function(u){ZR(n,t,u).then(i.resolve,r)})});return s.error&&r(s.value),i.promise}})});var vg=m(()=>{"use strict";var sL=oe(),nL=Ki(),oL=Yi().CONSTRUCTOR;sL({target:"Promise",stat:!0,forced:oL},{reject:function(e){var t=nL.f(this),i=t.reject;return i(e),t.promise}})});var Fl=m((qO,yg)=>{"use strict";var uL=ft(),lL=Le(),cL=Ki();yg.exports=function(a,e){if(uL(a),lL(e)&&e.constructor===a)return e;var t=cL.f(a),i=t.resolve;return i(e),t.promise}});var Eg=m(()=>{"use strict";var dL=oe(),pL=wt(),Tg=tt(),hL=hi(),Ig=Yi().CONSTRUCTOR,fL=Fl(),mL=pL("Promise"),bL=Tg&&!Ig;dL({target:"Promise",stat:!0,forced:Tg||Ig},{resolve:function(e){return fL(bL&&this===mL?hL:this,e)}})});var xg=m(()=>{"use strict";ug();mg();gg();Sg();vg();Eg()});var kg=m(()=>{"use strict";var gL=oe(),SL=tt(),bn=hi(),vL=ce(),Ag=wt(),Pg=ae(),yL=ul(),wg=Fl(),TL=Wi(),ql=bn&&bn.prototype,IL=!!bn&&vL(function(){ql.finally.call({then:function(){}},function(){})});gL({target:"Promise",proto:!0,real:!0,forced:IL},{finally:function(a){var e=yL(this,Ag("Promise")),t=Pg(a);return this.then(t?function(i){return wg(e,a()).then(function(){return i})}:a,t?function(i){return wg(e,a()).then(function(){throw i})}:a)}});!SL&&Pg(bn)&&(Nl=Ag("Promise").prototype.finally,ql.finally!==Nl&&TL(ql,"finally",Nl,{unsafe:!0}));var Nl});var Lg=m((zO,Rg)=>{"use strict";_m();xg();kg();var EL=Nt();Rg.exports=EL("Promise","finally")});var Mg=m((YO,$g)=>{"use strict";var xL=Lg();$g.exports=xL});var gn=m((KO,Dg)=>{"use strict";var wL=Mg();Dg.exports=wL});var Jg=m(()=>{"use strict";var WL=oe(),GL=Cu().values;WL({target:"Object",stat:!0},{values:function(e){return GL(e)}})});var eS=m((fN,Zg)=>{"use strict";Jg();var zL=oi();Zg.exports=zL.Object.values});var iS=m((mN,tS)=>{"use strict";var YL=eS();tS.exports=YL});var rr=m((bN,rS)=>{"use strict";var KL=iS();rS.exports=KL});var fS=m(()=>{"use strict";var p$=oe(),h$=Oi(),f$=ji(),m$=Yr(),b$=Kr();p$({target:"Array",proto:!0},{at:function(e){var t=h$(this),i=f$(t),r=m$(e),s=r>=0?r:i+r;return s<0||s>=i?void 0:t[s]}});b$("at")});var bS=m((WN,mS)=>{"use strict";fS();var g$=Nt();mS.exports=g$("Array","at")});var SS=m((GN,gS)=>{"use strict";var S$=bS();gS.exports=S$});var at=m((zN,vS)=>{"use strict";var v$=SS();vS.exports=v$});var pc=m((FU,ev)=>{"use strict";var Z$=si();ev.exports=Array.isArray||function(e){return Z$(e)==="Array"}});var iv=m((NU,tv)=>{"use strict";var eM=TypeError,tM=9007199254740991;tv.exports=function(a){if(a>tM)throw eM("Maximum allowed index exceeded");return a}});var sv=m((qU,av)=>{"use strict";var iM=pc(),rM=ji(),aM=iv(),sM=Ni(),rv=function(a,e,t,i,r,s,n,u){for(var o=r,l=0,c=n?sM(n,u):!1,p,d;l<i;)l in t&&(p=c?c(t[l],l,e):t[l],s>0&&iM(p)?(d=rM(p),o=rv(a,e,p,d,o,s-1)-1):(aM(o+1),a[o]=p),o++),l++;return o};av.exports=rv});var lv=m((UU,uv)=>{"use strict";var nv=pc(),nM=ol(),oM=Le(),uM=be(),lM=uM("species"),ov=Array;uv.exports=function(a){var e;return nv(a)&&(e=a.constructor,nM(e)&&(e===ov||nv(e.prototype))?e=void 0:oM(e)&&(e=e[lM],e===null&&(e=void 0))),e===void 0?ov:e}});var dv=m((HU,cv)=>{"use strict";var cM=lv();cv.exports=function(a,e){return new(cM(a))(e===0?0:e)}});var pv=m(()=>{"use strict";var dM=oe(),pM=sv(),hM=ht(),fM=Oi(),mM=ji(),bM=dv();dM({target:"Array",proto:!0},{flatMap:function(e){var t=fM(this),i=mM(t),r;return hM(e),r=bM(t,0),r.length=pM(r,t,t,i,0,1,e,arguments.length>1?arguments[1]:void 0),r}})});var hv=m(()=>{"use strict";var gM=Kr();gM("flatMap")});var mv=m((zU,fv)=>{"use strict";pv();hv();var SM=Nt();fv.exports=SM("Array","flatMap")});var gv=m((YU,bv)=>{"use strict";var vM=mv();bv.exports=vM});var xa=m((KU,Sv)=>{"use strict";var yM=gv();Sv.exports=yM});var wa=m((XU,vv)=>{"use strict";var TM=Jr(),IM=String;vv.exports=function(a){if(TM(a)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return IM(a)}});var hc=m((JU,yv)=>{"use strict";yv.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 Ev=m((ZU,Iv)=>{"use strict";var EM=de(),xM=Ft(),wM=wa(),mc=hc(),Tv=EM("".replace),AM=RegExp("^["+mc+"]+"),PM=RegExp("(^|[^"+mc+"])["+mc+"]+$"),fc=function(a){return function(e){var t=wM(xM(e));return a&1&&(t=Tv(t,AM,"")),a&2&&(t=Tv(t,PM,"$1")),t}};Iv.exports={start:fc(1),end:fc(2),trim:fc(3)}});var Pv=m((e1,Av)=>{"use strict";var kM=qu().PROPER,RM=ce(),xv=hc(),wv="\u200B\x85\u180E";Av.exports=function(a){return RM(function(){return!!xv[a]()||wv[a]()!==wv||kM&&xv[a].name!==a})}});var bc=m((t1,kv)=>{"use strict";var LM=Ev().start,$M=Pv();kv.exports=$M("trimStart")?function(){return LM(this)}:"".trimStart});var Lv=m(()=>{"use strict";var MM=oe(),Rv=bc();MM({target:"String",proto:!0,name:"trimStart",forced:"".trimLeft!==Rv},{trimLeft:Rv})});var Mv=m(()=>{"use strict";Lv();var DM=oe(),$v=bc();DM({target:"String",proto:!0,name:"trimStart",forced:"".trimStart!==$v},{trimStart:$v})});var Cv=m((n1,Dv)=>{"use strict";Mv();var CM=Nt();Dv.exports=CM("String","trimLeft")});var Vv=m((o1,Bv)=>{"use strict";var BM=Cv();Bv.exports=BM});var Ov=m((u1,_v)=>{"use strict";var VM=Vv();_v.exports=VM});var ey=m(()=>{"use strict"});var ty=m(()=>{"use strict"});var ry=m((zj,iy)=>{"use strict";var nD=Le(),oD=si(),uD=be(),lD=uD("match");iy.exports=function(a){var e;return nD(a)&&((e=a[lD])!==void 0?!!e:oD(a)==="RegExp")}});var ny=m((Yj,sy)=>{"use strict";var cD=re(),dD=ce(),ay=cD.RegExp,pD=!dD(function(){var a=!0;try{ay(".","d")}catch{a=!1}var e={},t="",i=a?"dgimsy":"gimsy",r=function(o,l){Object.defineProperty(e,o,{get:function(){return t+=l,!0}})},s={dotAll:"s",global:"g",ignoreCase:"i",multiline:"m",sticky:"y"};a&&(s.hasIndices="d");for(var n in s)r(n,s[n]);var u=Object.getOwnPropertyDescriptor(ay.prototype,"flags").get.call(e);return u!==i||t!==i});sy.exports={correct:pD}});var uy=m((Kj,oy)=>{"use strict";var hD=ft();oy.exports=function(){var a=hD(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 dy=m((Xj,cy)=>{"use strict";var fD=Ne(),mD=it(),bD=Hr(),ly=ny(),gD=uy(),SD=RegExp.prototype;cy.exports=ly.correct?function(a){return a.flags}:function(a){return!ly.correct&&bD(SD,a)&&!mD(a,"flags")?fD(gD,a):a.flags}});var hy=m((Jj,py)=>{"use strict";var Tc=de(),vD=Oi(),yD=Math.floor,vc=Tc("".charAt),TD=Tc("".replace),yc=Tc("".slice),ID=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,ED=/\$([$&'`]|\d{1,2})/g;py.exports=function(a,e,t,i,r,s){var n=t+a.length,u=i.length,o=ED;return r!==void 0&&(r=vD(r),o=ID),TD(s,o,function(l,c){var p;switch(vc(c,0)){case"$":return"$";case"&":return a;case"`":return yc(e,0,t);case"'":return yc(e,n);case"<":p=r[yc(c,1,-1)];break;default:var d=+c;if(d===0)return l;if(d>u){var h=yD(d/10);return h===0?l:h<=u?i[h-1]===void 0?vc(c,1):i[h-1]+vc(c,1):l}p=i[d-1]}return p===void 0?"":p})}});var by=m(()=>{"use strict";var xD=oe(),wD=Ne(),Ec=de(),fy=Ft(),AD=ae(),PD=Le(),kD=ry(),mr=wa(),RD=Qr(),LD=dy(),$D=hy(),MD=be(),DD=tt(),CD=MD("replace"),BD=TypeError,Ic=Ec("".indexOf),VD=Ec("".replace),my=Ec("".slice),_D=Math.max;xD({target:"String",proto:!0},{replaceAll:function(e,t){var i=fy(this),r,s,n,u,o,l,c,p,d,h,f=0,b="";if(PD(e)){if(r=kD(e),r&&(s=mr(fy(LD(e))),!~Ic(s,"g")))throw new BD("`.replaceAll` does not allow non-global regexes");if(n=RD(e,CD),n)return wD(n,e,i,t);if(DD&&r)return VD(mr(i),e,t)}for(u=mr(i),o=mr(e),l=AD(t),l||(t=mr(t)),c=o.length,p=_D(1,c),d=Ic(u,o);d!==-1;)h=l?mr(t(o,d,u)):$D(o,u,d,[],void 0,t),b+=my(u,f,d)+h,f=d+c,d=d+p>u.length?-1:Ic(u,o,d+p);return f<u.length&&(b+=my(u,f)),b}})});var Sy=m((tQ,gy)=>{"use strict";ey();ty();by();var OD=Nt();gy.exports=OD("String","replaceAll")});var yy=m((iQ,vy)=>{"use strict";var FD=Sy();vy.exports=FD});var Iy=m((rQ,Ty)=>{"use strict";var ND=yy();Ty.exports=ND});var xy=m((aQ,Ey)=>{"use strict";var qD=Yr(),UD=wa(),HD=Ft(),jD=RangeError;Ey.exports=function(e){var t=UD(HD(this)),i="",r=qD(e);if(r<0||r===1/0)throw new jD("Wrong number of repetitions");for(;r>0;(r>>>=1)&&(t+=t))r&1&&(i+=t);return i}});var Ry=m((sQ,ky)=>{"use strict";var Py=de(),QD=Au(),wy=wa(),WD=xy(),GD=Ft(),zD=Py(WD),YD=Py("".slice),KD=Math.ceil,Ay=function(a){return function(e,t,i){var r=wy(GD(e)),s=QD(t),n=r.length,u=i===void 0?" ":wy(i),o,l;return s<=n||u===""?r:(o=s-n,l=zD(u,KD(o/u.length)),l.length>o&&(l=YD(l,0,o)),a?r+l:l+r)}};ky.exports={start:Ay(!1),end:Ay(!0)}});var $y=m((nQ,Ly)=>{"use strict";var XD=ui();Ly.exports=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(XD)});var My=m(()=>{"use strict";var JD=oe(),ZD=Ry().start,eC=$y();JD({target:"String",proto:!0,forced:eC},{padStart:function(e){return ZD(this,e,arguments.length>1?arguments[1]:void 0)}})});var Cy=m((lQ,Dy)=>{"use strict";My();var tC=Nt();Dy.exports=tC("String","padStart")});var Vy=m((cQ,By)=>{"use strict";var iC=Cy();By.exports=iC});var Oy=m((dQ,_y)=>{"use strict";var rC=Vy();_y.exports=rC});var Nd="2.0.138-dev.2ccb74c0.0";var Re=(r=>(r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused",r))(Re||{}),xt=(y=>(y.MPEG="MPEG",y.DASH="DASH",y.DASH_SEP="DASH_SEP",y.DASH_SEP_VK="DASH_SEP",y.DASH_WEBM="DASH_WEBM",y.DASH_WEBM_AV1="DASH_WEBM_AV1",y.DASH_STREAMS="DASH_STREAMS",y.DASH_WEBM_VK="DASH_WEBM",y.DASH_ONDEMAND="DASH_ONDEMAND",y.DASH_ONDEMAND_VK="DASH_ONDEMAND",y.DASH_LIVE="DASH_LIVE",y.DASH_LIVE_CMAF="DASH_LIVE_CMAF",y.DASH_LIVE_WEBM="DASH_LIVE_WEBM",y.HLS="HLS",y.HLS_ONDEMAND="HLS_ONDEMAND",y.HLS_JS="HLS",y.HLS_FMP4="HLS_FMP4",y.HLS_LIVE="HLS_LIVE",y.HLS_LIVE_CMAF="HLS_LIVE_CMAF",y.WEB_RTC_LIVE="WEB_RTC_LIVE",y))(xt||{});var Bs=(r=>(r.NOT_AVAILABLE="NOT_AVAILABLE",r.AVAILABLE="AVAILABLE",r.CONNECTING="CONNECTING",r.CONNECTED="CONNECTED",r))(Bs||{}),Yo=(i=>(i.HTTP1="http1",i.HTTP2="http2",i.QUIC="quic",i))(Yo||{});var Ko=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(Ko||{}),Vs=(i=>(i.TRAFFIC_SAVING="traffic_saving",i.HIGH_QUALITY="high_quality",i.UNKNOWN="unknown",i))(Vs||{});var CI=C(Ee(),1);import{assertNever as Oh,assertNonNullable as pw,isNonNullable as qs,ValueSubject as ku,Subject as hw,Subscription as fw,merge as mw,observableFrom as bw,fromEvent as Ch,map as Bh,tap as Vh,filterChanged as gw,isNullable as Ru,ErrorCategory as _h}from"@vkontakte/videoplayer-shared";var Dh=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 Us=class{constructor(e){this.connection$=new ku(void 0);this.castState$=new ku("NOT_AVAILABLE");this.errorEvent$=new hw;this.realCastState$=new ku("NOT_AVAILABLE");this.subscription=new fw;this.isDestroyed=!1;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastInitializer");let t="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${t}`}),e.isDisabled||!t)return;let i=qs(window.chrome?.cast),r=!!window.__onGCastApiAvailable;i?this.initializeCastApi():(window.__onGCastApiAvailable=s=>{delete window.__onGCastApiAvailable,s&&!this.isDestroyed&&this.initializeCastApi()},r||Dh("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:_h.NETWORK,message:"Script loading failed!"})))}connect(){cast.framework.CastContext.getInstance()?.requestSession()}disconnect(){cast.framework.CastContext.getInstance()?.getCurrentSession()?.endSession(!0)}stopMedia(){return new Promise((e,t)=>{cast.framework.CastContext.getInstance()?.getCurrentSession()?.getMediaSession()?.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){qs(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();Ru(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();Ru(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(Ch(i,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(r=>{switch(r.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=i.getCurrentSession()?.getMediaSession()?.media?.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return Oh(r.sessionState)}})).add(mw(Ch(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(Vh(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),Bh(r=>r.castState)),bw([i.getCastState()])).pipe(gw(),Bh(Sw),Vh(r=>{this.log({message:`realCastState$: ${r}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{let s=r==="CONNECTED",n=qs(this.connection$.getValue());if(s&&!n){let u=i.getCurrentSession();pw(u);let o=u.getCastDevice(),l=u.getMediaSession()?.media?.contentId;(Ru(l)||l===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:u,castDevice:o}))}else!s&&n&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(r==="CONNECTED"?qs(this.connection$.getValue())?"CONNECTED":"AVAILABLE":r)}))}initializeCastApi(){let e,t,i;try{e=cast.framework.CastContext.getInstance(),t=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,i=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch{return}try{e.setOptions({receiverApplicationId:this.params.receiverApplicationId??t,autoJoinPolicy:i}),this.initListeners()}catch(r){this.errorEvent$.next({id:"ChromecastInitializer",category:_h.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:r})}}},Sw=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 Oh(a)}};var Ld=C(Ee(),1),mI=C(Qi(),1),bI=C(il(),1);var Yg=C(gn(),1);import{assertNever as Cg}from"@vkontakte/videoplayer-shared";var se=(a,e=0,t=0)=>{switch(t){case 0:return a.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case 1:{if(e===0)return a;let i=new URL(a);return i.searchParams.append("playback_shift",e.toFixed(0)),i.toString()}case 2:{let i=new URL(a);return!i.searchParams.get("offset_p")&&e===0?a:(i.searchParams.set("offset_p",e.toFixed(0)),i.toString())}default:Cg(t)}return a},Ut=(a,e)=>{switch(e){case 0:return NaN;case 1:{let t=new URL(a);return Number(t.searchParams.get("playback_shift"))}case 2:{let t=new URL(a);return Number(t.searchParams.get("offset_p")??0)}default:Cg(e)}};var P=(a,e,t=!1)=>{let i=a.getTransition();(t||!i||i.to===e)&&a.setState(e)};import{isNonNullable as AL,Subject as Sn,merge as Bg}from"@vkontakte/videoplayer-shared";var F=class{constructor(e){this.transitionStarted$=new Sn;this.transitionEnded$=new Sn;this.transitionUpdated$=new Sn;this.forceChanged$=new Sn;this.stateChangeStarted$=Bg(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=Bg(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||AL(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 Ug}from"@vkontakte/videoplayer-shared";var vn=class{constructor(){this._isMiuiBrowser=!1}get current(){return this._current}get isChrome(){return this.current==="Chrome"}get isFirefox(){return this.current==="Firefox"}get isSafari(){return this.current==="Safari"}get isOpera(){return this.current==="Opera"}get isEdge(){return this.current==="Edge"}get isYandex(){return this.current==="Yandex"}get isSamsungBrowser(){return this.current==="SamsungBrowser"}get currentVersion(){return this._current_version}get chromeVersion(){return this._chromeVersion}get firefoxVersion(){return this._firefoxVersion}get safariVersion(){return this._safariVersion}get operaVersion(){return this._operaVersion}get edgeVersion(){return this._edgeVersion}get yandexVersion(){return this._yandexVersion}get isMiuiBrowser(){return this._isMiuiBrowser}detect(){let{userAgent:e}=navigator;try{let t=/yabrowser/i.test(e)?"Yandex":void 0,i=/samsungbrowser/i.test(e)?"SamsungBrowser":void 0,r=/chrome|crios/i.test(e)?"Chrome":void 0,s=/chromium/i.test(e)?"Chromium":void 0,n=/firefox|fxios/i.test(e)?"Firefox":void 0,u=/webkit|safari|khtml/i.test(e)?"Safari":void 0,o=/opr\//i.test(e)?"Opera":void 0,l=/edg/i.test(e)?"Edge":void 0;this._isMiuiBrowser=/(XiaoMi)|(MiuiBrowser)/i.test(e),this._current=t||i||n||o||l||r||s||u||"Rest"}catch(t){console.error(t)}this.isChrome&&this.detectChromeVersion(),this.isFirefox&&this.detectFirefoxVersion(),this.isSafari&&this.detectSafariVersion(),this.isOpera&&this.detectOperaVersion(),this.isEdge&&this.detectEdgeVersion(),this.isYandex&&this.detectYandexVersion()}detectVersion(e){try{let{userAgent:t}=window.navigator,i=t.match(e);if(!i)return;let r=i[1],s=parseInt(r,10);if(!isNaN(s))return this._current_version=s,s}catch(t){console.error(t)}}detectChromeVersion(){this._chromeVersion=this.detectVersion(/Chrome\/(\d+\.\d+)/)}detectFirefoxVersion(){this._firefoxVersion=this.detectVersion(/Firefox\/(\d+\.\d+)/)}detectSafariVersion(){this._safariVersion=this.detectVersion(/Version\/(\d+)/)}detectOperaVersion(){this._operaVersion=this.detectVersion(/OPR\/(\d+\.\d+)/)}detectEdgeVersion(){this._edgeVersion=this.detectVersion(/Edg\/(\d+\.\d+)/)}detectYandexVersion(){this._yandexVersion=this.detectVersion(/YaBrowser\/(\d+\.\d+\.\d+)/)}};var Vg=C(Ee(),1);var la=()=>/Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test(navigator.appVersion??navigator.userAgent)||navigator?.userAgentData?.mobile;var yn=class{constructor(e){this._highEntropyValues={};this._displayChecker=e}get current(){return this._current}get isIOS(){let e=["iPhone","iPad","iPod"];return this._highEntropyValues.platform==="iOS"||(0,Vg.default)(e,this.current)}get isMac(){return this._highEntropyValues.platform==="macOS"||this.current==="Mac"}get isApple(){return this.isIOS||this.isMac}get isIphoneOrOldIpad(){if(!this.isApple||!this._displayChecker.isTouch)return!1;let e=this.current==="iPad"||this._displayChecker.width>700,t=this._iosVersion;return!e||e&&!!t&&t<16}get isAndroid(){return this._highEntropyValues.platform==="Android"||this.current==="Android"}get isMobile(){return this._highEntropyValues.mobile||this._isMobile}get iOSVersion(){return this._iosVersion}detect(){let{userAgent:e}=navigator;try{this._isMobile=la()}catch(t){console.error(t)}this.detectDevice(e),this.detectHighEntropyValues(),this.isIOS&&this.detectIOSVersion()}async detectHighEntropyValues(){let{userAgentData:e}=navigator;if(e?.getHighEntropyValues){let t=await e.getHighEntropyValues(["architecture","bitness","brands","mobile","platform","formFactor","model","platformVersion","wow64"]);this._highEntropyValues=t}}detectDevice(e){try{let t=/android/i.test(e)?"Android":void 0,i=/iphone/i.test(e)?"iPhone":void 0,r=/ipad/i.test(e)?"iPad":void 0,s=/ipod/i.test(e)?"iPod":void 0,n=/mac/i.test(e)?"Mac":void 0,u=/webOS|BlackBerry|IEMobile|Opera Mini/i.test(e)?"RestMobile":void 0;this._current=t||i||r||s||u||n||"Desktop"}catch(t){console.error(t)}}detectIOSVersion(){try{if(this._highEntropyValues.platformVersion){let s=this._highEntropyValues.platformVersion.split(".").slice(0,2).join("."),n=parseFloat(s);this._iosVersion=n;return}let{userAgent:e}=window.navigator,t=e.match(/OS (\d+(_\d+)?)/i);if(!t)return;let i=t[1].replace(/_/g,".");if(!i)return;let r=parseFloat(i);if(isNaN(r))return;this._iosVersion=r}catch(e){console.error(e)}}};var Tn=class{get isTouch(){return typeof this._maxTouchPoints=="number"?this._maxTouchPoints>1:"ontouchstart"in window}get maxTouchPoints(){return this._maxTouchPoints}get height(){return this._height}get width(){return this._width}get screenHeight(){return this._screenHeight}get screenWidth(){return this._screenWidth}get pixelRatio(){return this._pixelRatio}get isHDR(){return this._isHdr}get colorDepth(){return this._colorDepth}detect(){let{maxTouchPoints:e}=navigator;try{this._maxTouchPoints=e??0,this._isHdr=!!matchMedia("(dynamic-range: high)")?.matches,this._colorDepth=screen.colorDepth}catch(t){console.error(t)}try{this._pixelRatio=window.devicePixelRatio||1,this._height=screen.height,this._width=screen.width,this._height=screen.height,this._screenHeight=this._height*this._pixelRatio,this._screenWidth=this._width*this._pixelRatio}catch(t){console.error(t)}}};var Ue=()=>window.ManagedMediaSource||window.MediaSource,tr=()=>!!(window.ManagedMediaSource&&window.ManagedSourceBuffer?.prototype?.appendBuffer),_g=()=>!!(window.MediaSource&&window.SourceBuffer?.prototype?.appendBuffer),In=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;var PL=document.createElement("video"),kL='video/mp4; codecs="avc1.42000a,mp4a.40.2"',RL='video/mp4; codecs="hev1.1.6.L93.B0"',Og='video/webm; codecs="vp09.00.10.08"',Fg='video/webm; codecs="av01.0.00M.08"',LL='audio/mp4; codecs="mp4a.40.2"',$L='audio/webm; codecs="opus"',Ng,ML=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:Fg}}),window.navigator.mediaCapabilities.decodingInfo({...a,video:{...a.video,contentType:Og}})]);Ng={DASH_WEBM_AV1:e,DASH_WEBM:t}};ML().catch(a=>{console.log(PL),console.error(a)});var En=class{constructor(e,t){this._deviceChecker=e,this._browserChecker=t}get protocols(){return this._protocols}get containers(){return this._containers}get codecs(){return this._codecs}get webmDecodingInfo(){return Ng}get supportedCodecs(){return Object.keys(this._codecs).filter(e=>this._codecs[e])}get nativeHlsSupported(){return this._nativeHlsSupported}detect(){this._video=document.createElement("video");try{this._protocols={mms:tr(),mse:_g(),hls:!!(this._video.canPlayType?.("application/x-mpegurl")||this._video.canPlayType?.("vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},this._containers={mp4:!!this._video.canPlayType?.("video/mp4"),webm:!!this._video.canPlayType?.("video/webm"),cmaf:!0};let e=!!Ue()?.isTypeSupported?.(kL),t=!!Ue()?.isTypeSupported?.(RL),i=!!Ue()?.isTypeSupported?.(LL);this._codecs={h264:e,h265:t,vp9:!!Ue()?.isTypeSupported?.(Og),av1:!!Ue()?.isTypeSupported?.(Fg),aac:i,opus:!!Ue()?.isTypeSupported?.($L),mpeg:(e||t)&&i},this._nativeHlsSupported=this._protocols.hls&&this._containers.mp4}catch(e){console.error(e)}try{this.destroyVideoElement()}catch(e){console.error("Error destroying video element:",e)}}destroyVideoElement(){if(!this._video)return;if(this._video.pause(),this._video.currentTime=0,this._video.removeAttribute("src"),this._video.src="",this._video.load(),this._video.remove){this._video.remove(),this._video=null;return}this._video.parentNode&&this._video.parentNode.removeChild(this._video);let e=this._video.cloneNode(!1);this._video.parentNode?.replaceChild(e,this._video),this._video=null}};var qg="audio/mpeg",xn=class{supportMp3(){return this._codecs.mp3&&this._containers.mpeg}detect(){this._audio=document.createElement("audio");try{this._containers={mpeg:!!this._audio.canPlayType?.(qg)},this._codecs={mp3:!!Ue()?.isTypeSupported?.(qg)}}catch(e){console.error(e)}try{this.destroyAudioElement()}catch(e){console.error("Error destroying audio element:",e)}}destroyAudioElement(){if(!this._audio)return;if(this._audio.pause(),this._audio.currentTime=0,this._audio.removeAttribute("src"),this._audio.src="",this._audio.load(),this._audio.remove){this._audio.remove(),this._audio=null;return}this._audio.parentNode&&this._audio.parentNode.removeChild(this._audio);let e=this._audio.cloneNode(!1);this._audio.parentNode?.replaceChild(e,this._audio),this._audio=null}};import{ValueSubject as DL}from"@vkontakte/videoplayer-shared";var Ul=class{constructor(){this.isInited$=new DL(!1);this._displayChecker=new Tn,this._deviceChecker=new yn(this._displayChecker),this._browserChecker=new vn,this._videoChecker=new En(this._deviceChecker,this._browserChecker),this._audioChecker=new xn,this.detect()}get display(){return this._displayChecker}get device(){return this._deviceChecker}get browser(){return this._browserChecker}get video(){return this._videoChecker}get audio(){return this._audioChecker}async detect(){this._displayChecker.detect(),this._deviceChecker.detect(),this._browserChecker.detect(),this._videoChecker.detect(),this._audioChecker.detect(),this.isInited$.next(!0)}},B=new Ul;var Hl=a=>{let{containers:e,protocols:t,codecs:i,nativeHlsSupported:r}=B.video,s=(i.h264||i.h265)&&i.aac,n=t.mse||t.mms;return a.filter(u=>{switch(u){case"DASH_SEP":return n&&e.mp4&&s;case"DASH_WEBM":return n&&e.webm&&i.vp9&&i.opus;case"DASH_WEBM_AV1":return n&&e.webm&&i.av1&&i.opus;case"DASH_STREAMS":return n&&(e.mp4&&s||e.webm&&(i.vp9||i.av1)&&(i.opus||i.aac));case"DASH_LIVE":return n&&e.mp4&&s;case"DASH_LIVE_CMAF":return n&&e.mp4&&s&&e.cmaf;case"DASH_ONDEMAND":return n&&e.mp4&&s;case"HLS":case"HLS_ONDEMAND":case"HLS_FMP4":case"HLS_LIVE":case"HLS_LIVE_CMAF":return r;case"MPEG":return e.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return t.webrtc&&t.ws&&i.h264&&(e.mp4||e.webm);default:return Ug(u)}})},jl=a=>{switch(a){case"MPEG":case"DASH":case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":case"HLS":case"HLS_FMP4":case"HLS_ONDEMAND":return!1;case"DASH_LIVE":case"DASH_LIVE_CMAF":case"HLS_LIVE":case"HLS_LIVE_CMAF":case"DASH_LIVE_WEBM":case"WEB_RTC_LIVE":return!0;default:return Ug(a)}},CL=a=>{let t=Object.keys(a).filter(i=>!jl(i));return Hl(t).length>0};import{assertNever as ir,assertNonNullable as mi,debounce as Hg,ErrorCategory as jg,fromEvent as bi,isNonNullable as Qg,map as Wg,merge as Gg,observableFrom as BL,Subject as VL,Subscription as Ql,timeout as _L,getHighestQuality as OL}from"@vkontakte/videoplayer-shared";var FL=5,NL=5,qL=500,zg=7e3,ca=class{constructor(e){this.subscription=new Ql;this.loadMediaTimeoutSubscription=new Ql;this.videoState=new F("stopped");this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(s)};`}),i==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.stop());return}if(!t){if(r?.to!=="paused"&&s.state==="requested"&&e!=="stopped"){this.seek(s.position/1e3);return}switch(i){case"ready":{switch(e){case"playing":case"paused":case"ready":break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:ir(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:ir(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:ir(e)}break}default:ir(i)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(jl(e.format)),this.params.output.isAudioAvailable$.next(!0),this.handleRemoteVolumeChange({volume:this.params.connection.remotePlayer.volumeLevel,muted:this.params.connection.remotePlayer.isMuted});let t=this.params.connection.session.getMediaSession();t&&this.restoreSession(t),this.subscribe()}destroy(){this.log({message:"[destroy]"}),this.subscription.unsubscribe()}subscribe(){this.subscription.add(this.loadMediaTimeoutSubscription);let e=new Ql;this.subscription.add(e),this.subscription.add(Gg(this.videoState.stateChangeStarted$.pipe(Wg(r=>`stateChangeStarted$ ${JSON.stringify(r)}`)),this.videoState.stateChangeEnded$.pipe(Wg(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 VL;e.add(r.pipe(Hg(qL)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add(bi(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe(n=>{this.logRemoteEvent(n);let u=n.value;this.params.output.position$.next(u),(this.params.desiredState.seekState.getState().state==="applying"||Math.abs(u-s)>FL)&&r.next(u),s=u})),e.add(bi(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(bi(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(bi(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemotePause():this.handleRemotePlay()}),t(bi(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),r=>{this.logRemoteEvent(r);let{remotePlayer:s}=this.params.connection,n=r.value,u=this.params.output.isBuffering$.getValue(),o=n===chrome.cast.media.PlayerState.BUFFERING;switch(u!==o&&this.params.output.isBuffering$.next(o),n){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&s.duration-s.currentTime<NL&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),P(this.params.desiredState.playbackState,"stopped");break;case chrome.cast.media.PlayerState.PAUSED:{this.handleRemotePause();break}case chrome.cast.media.PlayerState.PLAYING:this.handleRemotePlay();break;case chrome.cast.media.PlayerState.BUFFERING:break;default:ir(n)}}),t(bi(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t(bi(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({muted:r.value})});let i=Gg(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,BL(["init"])).pipe(Hg(0));t(i,this.syncPlayback)}restoreSession(e){this.log({message:"restoreSession"});let{remotePlayer:t}=this.params.connection;if(e.playerState!==chrome.cast.media.PlayerState.IDLE){t.isPaused?(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),P(this.params.desiredState.playbackState,"playing"));let i=this.params.output.isLive$.getValue();this.params.output.duration$.next(i?0:t.duration),this.params.output.position$.next(i?0:t.currentTime),this.params.desiredState.seekState.setState({state:"none"})}}prepare(){let e=this.params.format;this.log({message:`[prepare] format: ${e}`});let t=this.createMediaInfo(e),i=this.createLoadRequest(t);this.loadMedia(i)}handleRemotePause(){let e=this.videoState.getState();(this.videoState.getTransition()?.to==="paused"||e==="playing")&&(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused"))}handleRemotePlay(){let e=this.videoState.getState();(this.videoState.getTransition()?.to==="playing"||e==="paused")&&(this.videoState.setState("playing"),P(this.params.desiredState.playbackState,"playing"))}handleRemoteReady(){this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.params.desiredState.playbackState.getTransition()?.to==="ready"&&P(this.params.desiredState.playbackState,"ready")}handleRemoteStop(){this.videoState.getState()!=="stopped"&&this.videoState.setState("stopped")}handleRemoteVolumeChange(e){let t=this.params.output.volume$.getValue(),i={volume:e.volume??t.volume,muted:e.muted??t.muted};(i.volume!==t.volume||i.muted!==i.muted)&&this.params.output.volume$.next(i)}seek(e){this.params.output.willSeekEvent$.next();let{remotePlayer:t,remotePlayerController:i}=this.params.connection;t.currentTime=e,i.seek()}stop(){let{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){let t=this.params.source,i,r,s;switch(e){case"MPEG":{let l=t[e];mi(l);let c=OL(Object.keys(l));mi(c);let p=l[c];mi(p),i=p,r="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_FMP4":case"HLS_ONDEMAND":{let l=t[e];mi(l),i=l.url,r="application/x-mpegurl",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":{let l=t[e];mi(l),i=l.url,r="application/dash+xml",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let l=t[e];mi(l),i=l.url,r="application/dash+xml",s=chrome.cast.media.StreamType.LIVE;break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let l=t[e];mi(l),i=se(l.url),r="application/x-mpegurl",s=chrome.cast.media.StreamType.LIVE;break}case"DASH_LIVE":case"WEB_RTC_LIVE":{let l="Unsupported format for Chromecast",c=new Error(l);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:jg.VIDEO_PIPELINE,message:l,thrown:c}),c}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return ir(e)}let n=new chrome.cast.media.MediaInfo(this.params.meta.videoId??i,r);n.contentUrl=i,n.streamType=s,n.metadata=new chrome.cast.media.GenericMediaMetadata;let{title:u,subtitle:o}=this.params.meta;return Qg(u)&&(n.metadata.title=u),Qg(o)&&(n.metadata.subtitle=o),n}createLoadRequest(e){let t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;let i=this.params.desiredState.seekState.getState();return i.state==="applying"||i.state==="requested"?t.currentTime=this.params.output.isLive$.getValue()?0:i.position/1e3:t.currentTime=0,t}loadMedia(e){let t=this.params.connection.session.loadMedia(e),i=new Promise((r,s)=>{this.loadMediaTimeoutSubscription.add(_L(zg).subscribe(()=>s(`timeout(${zg})`)))});(0,Yg.default)(Promise.race([t,i]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},r=>{let s=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${r}`;this.log({message:s}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:jg.VIDEO_PIPELINE,message:s,thrown:r})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var cc=C(Ee(),1);import{clearVideoElement as Xg}from"@vkontakte/videoplayer-shared";import{clearVideoElement as UL}from"@vkontakte/videoplayer-shared";var Kg=a=>{try{a.pause(),a.playbackRate=0,UL(a),a.remove()}catch(e){console.error(e)}};import{fromEvent as HL,Subscription as jL}from"@vkontakte/videoplayer-shared";var Wl=class{constructor(){this.attribute="data-pool-reused"}get(e){return e.hasAttribute(this.attribute)}set(e,t){e.toggleAttribute(this.attribute,t)}delete(e){e.removeAttribute(this.attribute)}},Gl=window.WeakMap?new WeakMap:new Wl,zl=window.WeakMap?new WeakMap:new Map,QL=(a,e=20)=>{let t=0;return HL(a,"ratechange").subscribe(i=>{t++,t>=e&&(a.currentTime=a.currentTime,t=0)})},$e=(a,{audioVideoSyncRate:e,disableYandexPiP:t})=>{let i=a.querySelector("video"),r=!!i;i?Xg(i):(i=document.createElement("video"),a.appendChild(i)),Gl.set(i,r);let s=new jL;return s.add(QL(i,e)),zl.set(i,s),i.setAttribute("crossorigin","anonymous"),i.setAttribute("playsinline","playsinline"),t&&i.setAttribute("x-yandex-pip","false"),i.controls=!1,i.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),i},Me=a=>{zl.get(a)?.unsubscribe(),zl.delete(a);let t=Gl.get(a);Gl.delete(a),t?Xg(a):Kg(a)};var Kl=C(rr(),1);import{assertNonNullable as pa,isNonNullable as bt,isNullable as ZL,fromEvent as ar,merge as aS,observableFrom as sS,filterChanged as nS,map as ha,Subject as oS,Subscription as e$,ValueSubject as t$,ErrorCategory as i$}from"@vkontakte/videoplayer-shared";import{isNonNullable as Yl,isNullable as XL,Subscription as JL}from"@vkontakte/videoplayer-shared";var wn=(a,e,t,{equal:i=(n,u)=>n===u,changed$:r,onError:s}={})=>{let n=a.getState(),u=e(),o=XL(r),l=new JL;return r&&l.add(r.subscribe(c=>{let p=a.getState();i(c,p)&&a.setState(c)},s)),i(u,n)||(t(n),o&&a.setState(n)),l.add(a.stateChangeStarted$.subscribe(c=>{t(c.to),o&&a.setState(c.to)},s)),l},mt=(a,e,t)=>wn(e,()=>a.loop,i=>{Yl(i)&&(a.loop=i)},{onError:t}),De=(a,e,t,i)=>wn(e,()=>({muted:a.muted,volume:a.volume}),r=>{Yl(r)&&(a.muted=r.muted,a.volume=r.volume)},{equal:(r,s)=>r===s||r?.muted===s?.muted&&r?.volume===s?.volume,changed$:t,onError:i}),ze=(a,e,t,i)=>wn(e,()=>a.playbackRate,r=>{Yl(r)&&(a.playbackRate=r)},{changed$:t,onError:i}),da=wn;var r$=a=>["__",a.language,a.label].join("|"),a$=(a,e)=>{if(a.id===e)return!0;let[t,i,r]=e.split("|");return a.language===i&&a.label===r},Xl=class a{constructor(e){this.available$=new oS;this.current$=new t$(void 0);this.error$=new oS;this.subscription=new e$;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:i$.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:s})};this.subscription.add(this.available$.subscribe(i.availableTextTracks$)),this.subscription.add(this.current$.subscribe(i.currentTextTrack$)),this.subscription.add(this.error$.subscribe(i.error$)),this.subscription.add(da(t.internalTextTracks,()=>(0,Kl.default)(this.internalTracks),s=>{bt(s)&&this.setInternal(s)},{equal:(s,n)=>bt(s)&&bt(n)&&s.length===n.length&&s.every(({id:u},o)=>u===n[o].id),changed$:this.available$.pipe(ha(s=>s.filter(({type:n})=>n==="internal"))),onError:r})),this.subscription.add(da(t.externalTextTracks,()=>(0,Kl.default)(this.externalTracks),s=>{bt(s)&&this.setExternal(s)},{equal:(s,n)=>bt(s)&&bt(n)&&s.length===n.length&&s.every(({id:u},o)=>u===n[o].id),changed$:this.available$.pipe(ha(s=>s.filter(({type:n})=>n==="external"))),onError:r})),this.subscription.add(da(t.currentTextTrack,()=>{if(this.video)return;let s=this.htmlTextTracksAsArray().find(({mode:n})=>n==="showing");return s&&this.htmlTextTrackToITextTrack(s).id},s=>this.select(s),{changed$:this.current$,onError:r})),this.subscription.add(da(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.activeCues)}))}subscribe(){pa(this.video);let{textTracks:e}=this.video;this.subscription.add(ar(e,"addtrack").subscribe(()=>{let i=this.current$.getValue();i&&this.select(i)})),this.subscription.add(aS(ar(e,"addtrack"),ar(e,"removetrack"),sS(["init"])).pipe(ha(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),nS((i,r)=>i.length===r.length&&i.every(({id:s},n)=>s===r[n].id))).subscribe(this.available$)),this.subscription.add(aS(ar(e,"change"),sS(["init"])).pipe(ha(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),ha(i=>i&&this.htmlTextTrackToITextTrack(i).id),nS()).subscribe(this.current$));let t=i=>this.applyCueSettings(i.target?.activeCues??null);this.subscription.add(ar(e,"addtrack").subscribe(i=>{i.track?.addEventListener("cuechange",t);let r=s=>{let n=s.target?.cues??null;n&&n.length&&(this.applyCueSettings(s.target?.cues??null),s.target?.removeEventListener("cuechange",r))};i.track?.addEventListener("cuechange",r)})),this.subscription.add(ar(e,"removetrack").subscribe(i=>{i.track?.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;let t=this.cueSettings.getState();for(let i of Array.from(e)){let r=i;bt(t.align)&&(r.align=t.align),bt(t.position)&&(r.position=t.position),bt(t.size)&&(r.size=t.size),bt(t.line)&&(r.line=t.line)}}htmlTextTracksAsArray(e=!1){pa(this.video);let t=[...this.video.textTracks];return e?t:t.filter(a.isHealthyTrack)}htmlTextTrackToITextTrack(e){let{language:t,label:i}=e,r=e.id?e.id:r$(e),s=this.externalTracks.has(r),n=(s?this.externalTracks.get(r)?.isAuto:this.internalTracks.get(r)?.isAuto)??r.includes("auto");return s?{id:r,type:"external",isAuto:n,language:t,label:i,url:this.externalTracks.get(r)?.url}:{id:r,type:"internal",isAuto:n,language:t,label:i,url:this.internalTracks.get(r)?.url}}static isHealthyTrack(e){return!(e.kind==="metadata"||e.groupId||e.id===""&&e.label===""&&e.language==="")}setExternal(e){this.internalTracks.size>0&&Array.from(this.internalTracks).forEach(([,t])=>this.detach(t)),e.filter(({id:t})=>!this.externalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.externalTracks).filter(([t])=>!e.find(i=>i.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){let t=[...this.externalTracks];e.filter(({id:i,language:r,isAuto:s})=>!this.internalTracks.has(i)&&!t.some(([,n])=>n.language===r&&n.isAuto===s)).forEach(i=>this.attach(i)),Array.from(this.internalTracks).filter(([i])=>!e.find(r=>r.id===i)).forEach(([,i])=>this.detach(i))}select(e){pa(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(ZL(e)||!a$(t,e))&&(t.mode="disabled")}destroy(){if(this.subscription.unsubscribe(),this.video)for(let e of Array.from(this.video.getElementsByTagName("track"))){let t=e.getAttribute("id");t&&this.externalTracks.has(t)&&this.video.removeChild(e)}this.externalTracks.clear()}attach(e){pa(this.video);let t=document.createElement("track");this.baseURL?t.setAttribute("src",new URL(e.url,this.baseURL).toString()):t.setAttribute("src",e.url),t.setAttribute("id",e.id),e.label&&t.setAttribute("label",e.label),e.language&&t.setAttribute("srclang",e.language),e.type==="external"?this.externalTracks.set(e.id,e):e.type==="internal"&&this.internalTracks.set(e.id,e),this.video.appendChild(t)}detach(e){pa(this.video);let t=Array.prototype.find.call(this.video.getElementsByTagName("track"),i=>i.getAttribute("id")===e.id);t&&this.video.removeChild(t),e.type==="external"?this.externalTracks.delete(e.id):e.type==="internal"&&this.internalTracks.delete(e.id)}},Ye=Xl;var gi=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 uS=a=>{let e=a;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e?.parentNode;return e??void 0},Jl=a=>{let e=uS(a);return!!(e&&e.fullscreenElement&&e.fullscreenElement===a)},lS=a=>{let e=uS(a);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===a)};import{fromEvent as xe,map as gt,merge as An,filterChanged as dS,isNonNullable as pS,Subject as n$,filter as Zl,mapTo as ec,combine as o$,once as u$,shareReplay as we,throttle as l$,ErrorCategory as c$,ValueSubject as hS,Subscription as d$}from"@vkontakte/videoplayer-shared";var s$=3,cS=(a,e,t=s$)=>{let i=0,r=0;for(let s=0;s<a.length;s++){let n=a.start(s),u=a.end(s);if(n<=e&&e<=u){if(i=n,r=u,!t)return{from:i,to:r};for(let o=s-1;o>=0;o--)a.end(o)+t>=i&&(i=a.start(o));for(let o=s+1;o<a.length;o++)a.start(o)-t<=r&&(r=a.end(o))}}return{from:i,to:r}};var Ce=a=>{let e=T=>xe(a,T).pipe(ec(void 0),we(1)),t=new d$,i=()=>t.unsubscribe(),r=An(xe(a,"progress"),xe(a,"timeupdate")).pipe(gt(()=>cS(a.buffered,a.currentTime)),we(1)),s=B.browser.isSafari?o$({play:e("play").pipe(u$()),playing:e("playing")}).pipe(ec(void 0),we(1)):e("playing"),n=xe(a,"volumechange").pipe(gt(()=>({muted:a.muted,volume:a.volume})),we(1)),u=xe(a,"ratechange").pipe(gt(()=>a.playbackRate),we(1)),o=xe(a,"error").pipe(Zl(()=>!!(a.error||a.played.length)),gt(()=>{let T=a.error;return{id:T?`MediaError#${T.code}`:"HtmlVideoError",category:c$.VIDEO_PIPELINE,message:T?T.message:"Error event from HTML video element",thrown:a.error??void 0}}),we(1)),l=xe(a,"timeupdate").pipe(gt(()=>a.currentTime),we(1)),c=["waiting","seeking","seeked","timeupdate"],p=new n$,d=.3,h;t.add(An(...c.map(T=>xe(a,T))).subscribe(T=>{let q=a.currentTime;a.loop&&pS(h)&&pS(q)&&h>=a.duration-d&&q<=d&&p.next(h),h=q}));let f=e("pause").pipe(Zl(()=>!a.error&&h!==a.duration),we(1)),b=xe(a,"enterpictureinpicture").pipe(we(1)),S=xe(a,"leavepictureinpicture").pipe(we(1)),g=new hS(lS(a));t.add(b.subscribe(()=>g.next(!0))),t.add(S.subscribe(()=>g.next(!1)));let I=new hS(Jl(a)),x=xe(a,"fullscreenchange").pipe(we(1));t.add(x.pipe(gt(()=>Jl(a))).subscribe(I));let y=.1,w=1e3,D=xe(a,"timeupdate").pipe(gt(T=>a.duration-a.currentTime<y),dS(),we(1)),L=An(D.pipe(Zl(T=>!a.loop&&T)),xe(a,"ended")).pipe(l$(w),ec(void 0),we(1)),R=An(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(T=>xe(a,T)),D.pipe(gt(T=>({type:T?"ended":"unknown"})))).pipe(gt(T=>B.browser.isFirefox&&T.type==="ended"?a.readyState<2:a.readyState<3),dS(),we(1));return{playing$:s,pause$:f,canplay$:e("canplay"),ended$:L,looped$:p,error$:o,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:l,durationChange$:xe(a,"durationchange").pipe(gt(()=>a.duration),we(1)),isBuffering$:R,currentBuffer$:r,volumeState$:n,playbackRateState$:u,inPiP$:g,inFullscreen$:I,enterPip$:b,leavePip$:S,destroy:i}};import{VideoQuality as Ht}from"@vkontakte/videoplayer-shared";var jt=a=>{switch(a){case"mobile":return Ht.Q_144P;case"lowest":return Ht.Q_240P;case"low":return Ht.Q_360P;case"sd":case"medium":return Ht.Q_480P;case"hd":case"high":return Ht.Q_720P;case"fullhd":case"full":return Ht.Q_1080P;case"quadhd":case"quad":return Ht.Q_1440P;case"ultrahd":case"ultra":return Ht.Q_2160P}};var Pe=C(at(),1),rc=C(Ee(),1),Si=C(Qi(),1);import{isNonNullable as K,isNullable as $n,now as RS,isHigher as Mn,isHigherOrEqual as nr,isInvariantQuality as Dn,isLowerOrEqual as or,videoSizeToQuality as LS,assertNotEmptyArray as Cn,assertNonNullable as $S}from"@vkontakte/videoplayer-shared";var tc=!1,kt={},yS=a=>{tc=a},TS=()=>{kt={}},IS=a=>{a(kt)},fa=(a,e)=>{tc&&(kt.meta=kt.meta??{},kt.meta[a]=e)},Ae=class{constructor(e){this.name=e}next(e){if(!tc)return;kt.series=kt.series??{};let t=kt.series[this.name]??[];t.push([Date.now(),e]),kt.series[this.name]=t}};import{isHigher as y$,isHigherOrEqual as eq,isLower as ES,isLowerOrEqual as tq,isNonNullable as Pn,isNullable as T$,videoHeightToQuality as kn}from"@vkontakte/videoplayer-shared";function ic(a,e,t){return!a.max&&a.min===e?"high_quality":!a.min&&a.max===t?"traffic_saving":"unknown"}function Rn(a,e,t){return!!a&&ic(a,e,t)==="high_quality"}function sr(a,e,t){return T$(a)||Pn(a.min)&&Pn(a.max)&&ES(a.max,a.min)||Pn(a.min)&&e&&y$(a.min,e)||Pn(a.max)&&t&&ES(a.max,t)}function xS({limits:a,highestAvailableHeight:e,lowestAvailableHeight:t}){return sr({max:a?.max?kn(a.max):void 0,min:a?.min?kn(a.min):void 0},e?kn(e):void 0,t?kn(t):void 0)}var MS=new Ae("best_bitrate"),Bn=(a,e,t)=>(e-t)*Math.pow(2,-10*a)+t;var ur=a=>(e,t)=>a*(Number(e.bitrate)-Number(t.bitrate)),Qt=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=RS()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},Vn='Assertion "ABR Tracks is empty array" failed',Ln=new WeakMap,wS=new WeakMap,AS=new WeakMap,ma=(a,e,t,i)=>{let r=[...e].sort(ur(1)),s=[...t].sort(ur(1)),n=s.filter(o=>K(o.bitrate)&&K(a.bitrate)?a.bitrate/o.bitrate>i:!0),u=(0,Pe.default)(s,Math.round(s.length*r.indexOf(a)/(r.length+1)))??(0,Pe.default)(s,-1);return u&&(0,rc.default)(n,u)?u:n.length?(0,Pe.default)(n,-1):(0,Pe.default)(s,0)},ba=(a,e,t,i)=>{let r=Ln.get(e);r||(r=[...e].sort(ur(1)),Ln.set(e,r));let s=Ln.get(t);s||(s=[...t].sort(ur(1)),Ln.set(t,s));let n=AS.get(a);n||(n=s.filter(o=>K(o.bitrate)&&K(a.bitrate)?a.bitrate/o.bitrate>i:!0),AS.set(a,n));let u=(0,Pe.default)(s,Math.round(s.length*r.indexOf(a)/(r.length+1)))??(0,Pe.default)(s,-1);return u&&(0,rc.default)(n,u)?u:n.length?(0,Pe.default)(n,-1):(0,Pe.default)(s,0)},PS=a=>"quality"in a,_n=(a,e,t,i)=>{let r=K(i?.last?.bitrate)&&K(t?.bitrate)&&i.last.bitrate<t.bitrate?a.trackCooldownIncreaseQuality:a.trackCooldownDecreaseQuality,s=t&&i&&i.history[t.id]&&RS()-i.history[t.id]<=r&&(!i.last||t.id!==i.last.id);if(t?.id&&i&&!s&&i.recordSelection(t),s&&i?.last){let n=i.last;i?.recordSwitch(n);let u=PS(n)?"video":"audio",o=PS(n)?n.quality:n.bitrate;return e({message:`
|
|
6
|
+
var FI=Object.create;var qd=Object.defineProperty;var NI=Object.getOwnPropertyDescriptor;var qI=Object.getOwnPropertyNames;var UI=Object.getPrototypeOf,jI=Object.prototype.hasOwnProperty;var m=(a,e)=>()=>(e||a((e={exports:{}}).exports,e),e.exports);var HI=(a,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of qI(e))!jI.call(a,r)&&r!==t&&qd(a,r,{get:()=>e[r],enumerable:!(i=NI(e,r))||i.enumerable});return a};var C=(a,e,t)=>(t=a!=null?FI(UI(a)):{},HI(e||!a||!a.__esModule?qd(t,"default",{value:a,enumerable:!0}):t,a));var re=m((ru,jd)=>{"use strict";var Fr=function(a){return a&&a.Math===Math&&a};jd.exports=Fr(typeof globalThis=="object"&&globalThis)||Fr(typeof window=="object"&&window)||Fr(typeof self=="object"&&self)||Fr(typeof global=="object"&&global)||Fr(typeof ru=="object"&&ru)||function(){return this}()||Function("return this")()});var pe=m((KV,Hd)=>{"use strict";Hd.exports=function(a){try{return!!a()}catch{return!0}}});var Nr=m((XV,Qd)=>{"use strict";var QI=pe();Qd.exports=!QI(function(){var a=function(){}.bind();return typeof a!="function"||a.hasOwnProperty("prototype")})});var au=m((JV,Yd)=>{"use strict";var GI=Nr(),zd=Function.prototype,Gd=zd.apply,Wd=zd.call;Yd.exports=typeof Reflect=="object"&&Reflect.apply||(GI?Wd.bind(Gd):function(){return Wd.apply(Gd,arguments)})});var he=m((ZV,Jd)=>{"use strict";var Kd=Nr(),Xd=Function.prototype,su=Xd.call,WI=Kd&&Xd.bind.bind(su,su);Jd.exports=Kd?WI:function(a){return function(){return su.apply(a,arguments)}}});var oi=m((e0,ep)=>{"use strict";var Zd=he(),zI=Zd({}.toString),YI=Zd("".slice);ep.exports=function(a){return YI(zI(a),8,-1)}});var nu=m((t0,tp)=>{"use strict";var KI=oi(),XI=he();tp.exports=function(a){if(KI(a)==="Function")return XI(a)}});var ae=m((i0,ip)=>{"use strict";var ou=typeof document=="object"&&document.all;ip.exports=typeof ou>"u"&&ou!==void 0?function(a){return typeof a=="function"||a===ou}:function(a){return typeof a=="function"}});var Fe=m((r0,rp)=>{"use strict";var JI=pe();rp.exports=!JI(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var Ne=m((a0,ap)=>{"use strict";var ZI=Nr(),Qs=Function.prototype.call;ap.exports=ZI?Qs.bind(Qs):function(){return Qs.apply(Qs,arguments)}});var uu=m(op=>{"use strict";var sp={}.propertyIsEnumerable,np=Object.getOwnPropertyDescriptor,eE=np&&!sp.call({1:2},1);op.f=eE?function(e){var t=np(this,e);return!!t&&t.enumerable}:sp});var qr=m((n0,up)=>{"use strict";up.exports=function(a,e){return{enumerable:!(a&1),configurable:!(a&2),writable:!(a&4),value:e}}});var cp=m((o0,lp)=>{"use strict";var tE=he(),iE=pe(),rE=oi(),lu=Object,aE=tE("".split);lp.exports=iE(function(){return!lu("z").propertyIsEnumerable(0)})?function(a){return rE(a)==="String"?aE(a,""):lu(a)}:lu});var Ur=m((u0,dp)=>{"use strict";dp.exports=function(a){return a==null}});var Ft=m((l0,pp)=>{"use strict";var sE=Ur(),nE=TypeError;pp.exports=function(a){if(sE(a))throw new nE("Can't call method on "+a);return a}});var ui=m((c0,hp)=>{"use strict";var oE=cp(),uE=Ft();hp.exports=function(a){return oE(uE(a))}});var Me=m((d0,fp)=>{"use strict";var lE=ae();fp.exports=function(a){return typeof a=="object"?a!==null:lE(a)}});var li=m((p0,mp)=>{"use strict";mp.exports={}});var wt=m((h0,gp)=>{"use strict";var cu=li(),du=re(),cE=ae(),bp=function(a){return cE(a)?a:void 0};gp.exports=function(a,e){return arguments.length<2?bp(cu[a])||bp(du[a]):cu[a]&&cu[a][e]||du[a]&&du[a][e]}});var jr=m((f0,Sp)=>{"use strict";var dE=he();Sp.exports=dE({}.isPrototypeOf)});var ci=m((m0,Tp)=>{"use strict";var pE=re(),vp=pE.navigator,yp=vp&&vp.userAgent;Tp.exports=yp?String(yp):""});var hu=m((b0,Pp)=>{"use strict";var Ap=re(),pu=ci(),Ip=Ap.process,Ep=Ap.Deno,xp=Ip&&Ip.versions||Ep&&Ep.version,wp=xp&&xp.v8,et,Gs;wp&&(et=wp.split("."),Gs=et[0]>0&&et[0]<4?1:+(et[0]+et[1]));!Gs&&pu&&(et=pu.match(/Edge\/(\d+)/),(!et||et[1]>=74)&&(et=pu.match(/Chrome\/(\d+)/),et&&(Gs=+et[1])));Pp.exports=Gs});var fu=m((g0,kp)=>{"use strict";var Rp=hu(),hE=pe(),fE=re(),mE=fE.String;kp.exports=!!Object.getOwnPropertySymbols&&!hE(function(){var a=Symbol("symbol detection");return!mE(a)||!(Object(a)instanceof Symbol)||!Symbol.sham&&Rp&&Rp<41})});var mu=m((S0,Lp)=>{"use strict";var bE=fu();Lp.exports=bE&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var bu=m((v0,$p)=>{"use strict";var gE=wt(),SE=ae(),vE=jr(),yE=mu(),TE=Object;$p.exports=yE?function(a){return typeof a=="symbol"}:function(a){var e=gE("Symbol");return SE(e)&&vE(e.prototype,TE(a))}});var Hr=m((y0,Mp)=>{"use strict";var IE=String;Mp.exports=function(a){try{return IE(a)}catch{return"Object"}}});var ht=m((T0,Dp)=>{"use strict";var EE=ae(),xE=Hr(),wE=TypeError;Dp.exports=function(a){if(EE(a))return a;throw new wE(xE(a)+" is not a function")}});var Qr=m((I0,Cp)=>{"use strict";var AE=ht(),PE=Ur();Cp.exports=function(a,e){var t=a[e];return PE(t)?void 0:AE(t)}});var Vp=m((E0,Bp)=>{"use strict";var gu=Ne(),Su=ae(),vu=Me(),RE=TypeError;Bp.exports=function(a,e){var t,i;if(e==="string"&&Su(t=a.toString)&&!vu(i=gu(t,a))||Su(t=a.valueOf)&&!vu(i=gu(t,a))||e!=="string"&&Su(t=a.toString)&&!vu(i=gu(t,a)))return i;throw new RE("Can't convert object to primitive value")}});var tt=m((x0,_p)=>{"use strict";_p.exports=!0});var Np=m((w0,Fp)=>{"use strict";var Op=re(),kE=Object.defineProperty;Fp.exports=function(a,e){try{kE(Op,a,{value:e,configurable:!0,writable:!0})}catch{Op[a]=e}return e}});var Gr=m((A0,jp)=>{"use strict";var LE=tt(),$E=re(),ME=Np(),qp="__core-js_shared__",Up=jp.exports=$E[qp]||ME(qp,{});(Up.versions||(Up.versions=[])).push({version:"3.43.0",mode:LE?"pure":"global",copyright:"\xA9 2014-2025 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.43.0/LICENSE",source:"https://github.com/zloirock/core-js"})});var yu=m((P0,Qp)=>{"use strict";var Hp=Gr();Qp.exports=function(a,e){return Hp[a]||(Hp[a]=e||{})}});var Ni=m((R0,Gp)=>{"use strict";var DE=Ft(),CE=Object;Gp.exports=function(a){return CE(DE(a))}});var it=m((k0,Wp)=>{"use strict";var BE=he(),VE=Ni(),_E=BE({}.hasOwnProperty);Wp.exports=Object.hasOwn||function(e,t){return _E(VE(e),t)}});var Tu=m((L0,zp)=>{"use strict";var OE=he(),FE=0,NE=Math.random(),qE=OE(1.1.toString);zp.exports=function(a){return"Symbol("+(a===void 0?"":a)+")_"+qE(++FE+NE,36)}});var ge=m(($0,Kp)=>{"use strict";var UE=re(),jE=yu(),Yp=it(),HE=Tu(),QE=fu(),GE=mu(),qi=UE.Symbol,Iu=jE("wks"),WE=GE?qi.for||qi:qi&&qi.withoutSetter||HE;Kp.exports=function(a){return Yp(Iu,a)||(Iu[a]=QE&&Yp(qi,a)?qi[a]:WE("Symbol."+a)),Iu[a]}});var eh=m((M0,Zp)=>{"use strict";var zE=Ne(),Xp=Me(),Jp=bu(),YE=Qr(),KE=Vp(),XE=ge(),JE=TypeError,ZE=XE("toPrimitive");Zp.exports=function(a,e){if(!Xp(a)||Jp(a))return a;var t=YE(a,ZE),i;if(t){if(e===void 0&&(e="default"),i=zE(t,a,e),!Xp(i)||Jp(i))return i;throw new JE("Can't convert object to primitive value")}return e===void 0&&(e="number"),KE(a,e)}});var Eu=m((D0,th)=>{"use strict";var ex=eh(),tx=bu();th.exports=function(a){var e=ex(a,"string");return tx(e)?e:e+""}});var Ws=m((C0,rh)=>{"use strict";var ix=re(),ih=Me(),xu=ix.document,rx=ih(xu)&&ih(xu.createElement);rh.exports=function(a){return rx?xu.createElement(a):{}}});var wu=m((B0,ah)=>{"use strict";var ax=Fe(),sx=pe(),nx=Ws();ah.exports=!ax&&!sx(function(){return Object.defineProperty(nx("div"),"a",{get:function(){return 7}}).a!==7})});var oh=m(nh=>{"use strict";var ox=Fe(),ux=Ne(),lx=uu(),cx=qr(),dx=ui(),px=Eu(),hx=it(),fx=wu(),sh=Object.getOwnPropertyDescriptor;nh.f=ox?sh:function(e,t){if(e=dx(e),t=px(t),fx)try{return sh(e,t)}catch{}if(hx(e,t))return cx(!ux(lx.f,e,t),e[t])}});var Au=m((_0,uh)=>{"use strict";var mx=pe(),bx=ae(),gx=/#|\.prototype\./,Wr=function(a,e){var t=vx[Sx(a)];return t===Tx?!0:t===yx?!1:bx(e)?mx(e):!!e},Sx=Wr.normalize=function(a){return String(a).replace(gx,".").toLowerCase()},vx=Wr.data={},yx=Wr.NATIVE="N",Tx=Wr.POLYFILL="P";uh.exports=Wr});var Ui=m((O0,ch)=>{"use strict";var lh=nu(),Ix=ht(),Ex=Nr(),xx=lh(lh.bind);ch.exports=function(a,e){return Ix(a),e===void 0?a:Ex?xx(a,e):function(){return a.apply(e,arguments)}}});var Pu=m((F0,dh)=>{"use strict";var wx=Fe(),Ax=pe();dh.exports=wx&&Ax(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var ft=m((N0,ph)=>{"use strict";var Px=Me(),Rx=String,kx=TypeError;ph.exports=function(a){if(Px(a))return a;throw new kx(Rx(a)+" is not an object")}});var di=m(fh=>{"use strict";var Lx=Fe(),$x=wu(),Mx=Pu(),zs=ft(),hh=Eu(),Dx=TypeError,Ru=Object.defineProperty,Cx=Object.getOwnPropertyDescriptor,ku="enumerable",Lu="configurable",$u="writable";fh.f=Lx?Mx?function(e,t,i){if(zs(e),t=hh(t),zs(i),typeof e=="function"&&t==="prototype"&&"value"in i&&$u in i&&!i[$u]){var r=Cx(e,t);r&&r[$u]&&(e[t]=i.value,i={configurable:Lu in i?i[Lu]:r[Lu],enumerable:ku in i?i[ku]:r[ku],writable:!1})}return Ru(e,t,i)}:Ru:function(e,t,i){if(zs(e),t=hh(t),zs(i),$x)try{return Ru(e,t,i)}catch{}if("get"in i||"set"in i)throw new Dx("Accessors not supported");return"value"in i&&(e[t]=i.value),e}});var ji=m((U0,mh)=>{"use strict";var Bx=Fe(),Vx=di(),_x=qr();mh.exports=Bx?function(a,e,t){return Vx.f(a,e,_x(1,t))}:function(a,e,t){return a[e]=t,a}});var oe=m((j0,gh)=>{"use strict";var zr=re(),Ox=au(),Fx=nu(),Nx=ae(),qx=oh().f,Ux=Au(),Hi=li(),jx=Ui(),Qi=ji(),bh=it();Gr();var Hx=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 Ox(a,this,arguments)};return e.prototype=a.prototype,e};gh.exports=function(a,e){var t=a.target,i=a.global,r=a.stat,s=a.proto,n=i?zr:r?zr[t]:zr[t]&&zr[t].prototype,u=i?Hi:Hi[t]||Qi(Hi,t,{})[t],o=u.prototype,l,d,h,c,p,f,b,S,g;for(c in e)l=Ux(i?c:t+(r?".":"#")+c,a.forced),d=!l&&n&&bh(n,c),f=u[c],d&&(a.dontCallGetSet?(g=qx(n,c),b=g&&g.value):b=n[c]),p=d&&b?b:e[c],!(!l&&!s&&typeof f==typeof p)&&(a.bind&&d?S=jx(p,zr):a.wrap&&d?S=Hx(p):s&&Nx(p)?S=Fx(p):S=p,(a.sham||p&&p.sham||f&&f.sham)&&Qi(S,"sham",!0),Qi(u,c,S),s&&(h=t+"Prototype",bh(Hi,h)||Qi(Hi,h,{}),Qi(Hi[h],c,p),a.real&&o&&(l||!o[c])&&Qi(o,c,p)))}});var vh=m((H0,Sh)=>{"use strict";var Qx=Math.ceil,Gx=Math.floor;Sh.exports=Math.trunc||function(e){var t=+e;return(t>0?Gx:Qx)(t)}});var Yr=m((Q0,yh)=>{"use strict";var Wx=vh();yh.exports=function(a){var e=+a;return e!==e||e===0?0:Wx(e)}});var Ih=m((G0,Th)=>{"use strict";var zx=Yr(),Yx=Math.max,Kx=Math.min;Th.exports=function(a,e){var t=zx(a);return t<0?Yx(t+e,0):Kx(t,e)}});var Mu=m((W0,Eh)=>{"use strict";var Xx=Yr(),Jx=Math.min;Eh.exports=function(a){var e=Xx(a);return e>0?Jx(e,9007199254740991):0}});var Gi=m((z0,xh)=>{"use strict";var Zx=Mu();xh.exports=function(a){return Zx(a.length)}});var Du=m((Y0,Ah)=>{"use strict";var ew=ui(),tw=Ih(),iw=Gi(),wh=function(a){return function(e,t,i){var r=ew(e),s=iw(r);if(s===0)return!a&&-1;var n=tw(i,s),u;if(a&&t!==t){for(;s>n;)if(u=r[n++],u!==u)return!0}else for(;s>n;n++)if((a||n in r)&&r[n]===t)return a||n||0;return!a&&-1}};Ah.exports={includes:wh(!0),indexOf:wh(!1)}});var Kr=m((K0,Ph)=>{"use strict";Ph.exports=function(){}});var Rh=m(()=>{"use strict";var rw=oe(),aw=Du().includes,sw=pe(),nw=Kr(),ow=sw(function(){return!Array(1).includes()});rw({target:"Array",proto:!0,forced:ow},{includes:function(e){return aw(this,e,arguments.length>1?arguments[1]:void 0)}});nw("includes")});var Nt=m((Z0,kh)=>{"use strict";var uw=wt();kh.exports=uw});var $h=m((e_,Lh)=>{"use strict";Rh();var lw=Nt();Lh.exports=lw("Array","includes")});var Dh=m((t_,Mh)=>{"use strict";var cw=$h();Mh.exports=cw});var Ee=m((i_,Ch)=>{"use strict";var dw=Dh();Ch.exports=dw});var Xs=m((f_,Uh)=>{"use strict";var vw=yu(),yw=Tu(),qh=vw("keys");Uh.exports=function(a){return qh[a]||(qh[a]=yw(a))}});var Hh=m((m_,jh)=>{"use strict";var Tw=pe();jh.exports=!Tw(function(){function a(){}return a.prototype.constructor=null,Object.getPrototypeOf(new a)!==a.prototype})});var Js=m((b_,Gh)=>{"use strict";var Iw=it(),Ew=ae(),xw=Ni(),ww=Xs(),Aw=Hh(),Qh=ww("IE_PROTO"),Vu=Object,Pw=Vu.prototype;Gh.exports=Aw?Vu.getPrototypeOf:function(a){var e=xw(a);if(Iw(e,Qh))return e[Qh];var t=e.constructor;return Ew(t)&&e instanceof t?t.prototype:e instanceof Vu?Pw:null}});var Zs=m((g_,Wh)=>{"use strict";Wh.exports={}});var Kh=m((S_,Yh)=>{"use strict";var Rw=he(),_u=it(),kw=ui(),Lw=Du().indexOf,$w=Zs(),zh=Rw([].push);Yh.exports=function(a,e){var t=kw(a),i=0,r=[],s;for(s in t)!_u($w,s)&&_u(t,s)&&zh(r,s);for(;e.length>i;)_u(t,s=e[i++])&&(~Lw(r,s)||zh(r,s));return r}});var Ou=m((v_,Xh)=>{"use strict";Xh.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var Fu=m((y_,Jh)=>{"use strict";var Mw=Kh(),Dw=Ou();Jh.exports=Object.keys||function(e){return Mw(e,Dw)}});var Nu=m((T_,af)=>{"use strict";var ef=Fe(),Cw=pe(),tf=he(),Bw=Js(),Vw=Fu(),_w=ui(),Ow=uu().f,rf=tf(Ow),Fw=tf([].push),Nw=ef&&Cw(function(){var a=Object.create(null);return a[2]=2,!rf(a,2)}),Zh=function(a){return function(e){for(var t=_w(e),i=Vw(t),r=Nw&&Bw(t)===null,s=i.length,n=0,u=[],o;s>n;)o=i[n++],(!ef||(r?o in t:rf(t,o)))&&Fw(u,a?[o,t[o]]:t[o]);return u}};af.exports={entries:Zh(!0),values:Zh(!1)}});var sf=m(()=>{"use strict";var qw=oe(),Uw=Nu().entries;qw({target:"Object",stat:!0},{entries:function(e){return Uw(e)}})});var of=m((x_,nf)=>{"use strict";sf();var jw=li();nf.exports=jw.Object.entries});var lf=m((w_,uf)=>{"use strict";var Hw=of();uf.exports=Hw});var Wi=m((A_,cf)=>{"use strict";var Qw=lf();cf.exports=Qw});var pi=m((P_,df)=>{"use strict";df.exports={}});var ff=m((R_,hf)=>{"use strict";var Gw=re(),Ww=ae(),pf=Gw.WeakMap;hf.exports=Ww(pf)&&/native code/.test(String(pf))});var Hu=m((k_,gf)=>{"use strict";var zw=ff(),bf=re(),Yw=Me(),Kw=ji(),qu=it(),Uu=Gr(),Xw=Xs(),Jw=Zs(),mf="Object already initialized",ju=bf.TypeError,Zw=bf.WeakMap,en,Xr,tn,eA=function(a){return tn(a)?Xr(a):en(a,{})},tA=function(a){return function(e){var t;if(!Yw(e)||(t=Xr(e)).type!==a)throw new ju("Incompatible receiver, "+a+" required");return t}};zw||Uu.state?(rt=Uu.state||(Uu.state=new Zw),rt.get=rt.get,rt.has=rt.has,rt.set=rt.set,en=function(a,e){if(rt.has(a))throw new ju(mf);return e.facade=a,rt.set(a,e),e},Xr=function(a){return rt.get(a)||{}},tn=function(a){return rt.has(a)}):(hi=Xw("state"),Jw[hi]=!0,en=function(a,e){if(qu(a,hi))throw new ju(mf);return e.facade=a,Kw(a,hi,e),e},Xr=function(a){return qu(a,hi)?a[hi]:{}},tn=function(a){return qu(a,hi)});var rt,hi;gf.exports={set:en,get:Xr,has:tn,enforce:eA,getterFor:tA}});var Wu=m((L_,vf)=>{"use strict";var Qu=Fe(),iA=it(),Sf=Function.prototype,rA=Qu&&Object.getOwnPropertyDescriptor,Gu=iA(Sf,"name"),aA=Gu&&function(){}.name==="something",sA=Gu&&(!Qu||Qu&&rA(Sf,"name").configurable);vf.exports={EXISTS:Gu,PROPER:aA,CONFIGURABLE:sA}});var Tf=m(yf=>{"use strict";var nA=Fe(),oA=Pu(),uA=di(),lA=ft(),cA=ui(),dA=Fu();yf.f=nA&&!oA?Object.defineProperties:function(e,t){lA(e);for(var i=cA(t),r=dA(t),s=r.length,n=0,u;s>n;)uA.f(e,u=r[n++],i[u]);return e}});var zu=m((M_,If)=>{"use strict";var pA=wt();If.exports=pA("document","documentElement")});var Ju=m((D_,kf)=>{"use strict";var hA=ft(),fA=Tf(),Ef=Ou(),mA=Zs(),bA=zu(),gA=Ws(),SA=Xs(),xf=">",wf="<",Ku="prototype",Xu="script",Pf=SA("IE_PROTO"),Yu=function(){},Rf=function(a){return wf+Xu+xf+a+wf+"/"+Xu+xf},Af=function(a){a.write(Rf("")),a.close();var e=a.parentWindow.Object;return a=null,e},vA=function(){var a=gA("iframe"),e="java"+Xu+":",t;return a.style.display="none",bA.appendChild(a),a.src=String(e),t=a.contentWindow.document,t.open(),t.write(Rf("document.F=Object")),t.close(),t.F},rn,an=function(){try{rn=new ActiveXObject("htmlfile")}catch{}an=typeof document<"u"?document.domain&&rn?Af(rn):vA():Af(rn);for(var a=Ef.length;a--;)delete an[Ku][Ef[a]];return an()};mA[Pf]=!0;kf.exports=Object.create||function(e,t){var i;return e!==null?(Yu[Ku]=hA(e),i=new Yu,Yu[Ku]=null,i[Pf]=e):i=an(),t===void 0?i:fA.f(i,t)}});var zi=m((C_,Lf)=>{"use strict";var yA=ji();Lf.exports=function(a,e,t,i){return i&&i.enumerable?a[e]=t:yA(a,e,t),a}});var il=m((B_,Df)=>{"use strict";var TA=pe(),IA=ae(),EA=Me(),xA=Ju(),$f=Js(),wA=zi(),AA=ge(),PA=tt(),tl=AA("iterator"),Mf=!1,At,Zu,el;[].keys&&(el=[].keys(),"next"in el?(Zu=$f($f(el)),Zu!==Object.prototype&&(At=Zu)):Mf=!0);var RA=!EA(At)||TA(function(){var a={};return At[tl].call(a)!==a});RA?At={}:PA&&(At=xA(At));IA(At[tl])||wA(At,tl,function(){return this});Df.exports={IteratorPrototype:At,BUGGY_SAFARI_ITERATORS:Mf}});var sn=m((V_,Bf)=>{"use strict";var kA=ge(),LA=kA("toStringTag"),Cf={};Cf[LA]="z";Bf.exports=String(Cf)==="[object z]"});var Jr=m((__,Vf)=>{"use strict";var $A=sn(),MA=ae(),nn=oi(),DA=ge(),CA=DA("toStringTag"),BA=Object,VA=nn(function(){return arguments}())==="Arguments",_A=function(a,e){try{return a[e]}catch{}};Vf.exports=$A?nn:function(a){var e,t,i;return a===void 0?"Undefined":a===null?"Null":typeof(t=_A(e=BA(a),CA))=="string"?t:VA?nn(e):(i=nn(e))==="Object"&&MA(e.callee)?"Arguments":i}});var Of=m((O_,_f)=>{"use strict";var OA=sn(),FA=Jr();_f.exports=OA?{}.toString:function(){return"[object "+FA(this)+"]"}});var Zr=m((F_,Nf)=>{"use strict";var NA=sn(),qA=di().f,UA=ji(),jA=it(),HA=Of(),QA=ge(),Ff=QA("toStringTag");Nf.exports=function(a,e,t,i){var r=t?a:a&&a.prototype;r&&(jA(r,Ff)||qA(r,Ff,{configurable:!0,value:e}),i&&!NA&&UA(r,"toString",HA))}});var Uf=m((N_,qf)=>{"use strict";var GA=il().IteratorPrototype,WA=Ju(),zA=qr(),YA=Zr(),KA=pi(),XA=function(){return this};qf.exports=function(a,e,t,i){var r=e+" Iterator";return a.prototype=WA(GA,{next:zA(+!i,t)}),YA(a,r,!1,!0),KA[r]=XA,a}});var Hf=m((q_,jf)=>{"use strict";var JA=he(),ZA=ht();jf.exports=function(a,e,t){try{return JA(ZA(Object.getOwnPropertyDescriptor(a,e)[t]))}catch{}}});var Gf=m((U_,Qf)=>{"use strict";var eP=Me();Qf.exports=function(a){return eP(a)||a===null}});var zf=m((j_,Wf)=>{"use strict";var tP=Gf(),iP=String,rP=TypeError;Wf.exports=function(a){if(tP(a))return a;throw new rP("Can't set "+iP(a)+" as a prototype")}});var rl=m((H_,Yf)=>{"use strict";var aP=Hf(),sP=Me(),nP=Ft(),oP=zf();Yf.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var a=!1,e={},t;try{t=aP(Object.prototype,"__proto__","set"),t(e,[]),a=e instanceof Array}catch{}return function(r,s){return nP(r),oP(s),sP(r)&&(a?t(r,s):r.__proto__=s),r}}():void 0)});var nm=m((Q_,sm)=>{"use strict";var uP=oe(),lP=Ne(),on=tt(),rm=Wu(),cP=ae(),dP=Uf(),Kf=Js(),Xf=rl(),pP=Zr(),hP=ji(),al=zi(),fP=ge(),Jf=pi(),am=il(),mP=rm.PROPER,bP=rm.CONFIGURABLE,Zf=am.IteratorPrototype,un=am.BUGGY_SAFARI_ITERATORS,ea=fP("iterator"),em="keys",ta="values",tm="entries",im=function(){return this};sm.exports=function(a,e,t,i,r,s,n){dP(t,e,i);var u=function(g){if(g===r&&c)return c;if(!un&&g&&g in d)return d[g];switch(g){case em:return function(){return new t(this,g)};case ta:return function(){return new t(this,g)};case tm:return function(){return new t(this,g)}}return function(){return new t(this)}},o=e+" Iterator",l=!1,d=a.prototype,h=d[ea]||d["@@iterator"]||r&&d[r],c=!un&&h||u(r),p=e==="Array"&&d.entries||h,f,b,S;if(p&&(f=Kf(p.call(new a)),f!==Object.prototype&&f.next&&(!on&&Kf(f)!==Zf&&(Xf?Xf(f,Zf):cP(f[ea])||al(f,ea,im)),pP(f,o,!0,!0),on&&(Jf[o]=im))),mP&&r===ta&&h&&h.name!==ta&&(!on&&bP?hP(d,"name",ta):(l=!0,c=function(){return lP(h,this)})),r)if(b={values:u(ta),keys:s?c:u(em),entries:u(tm)},n)for(S in b)(un||l||!(S in d))&&al(d,S,b[S]);else uP({target:e,proto:!0,forced:un||l},b);return(!on||n)&&d[ea]!==c&&al(d,ea,c,{name:r}),Jf[e]=c,b}});var um=m((G_,om)=>{"use strict";om.exports=function(a,e){return{value:a,done:e}}});var nl=m((W_,hm)=>{"use strict";var gP=ui(),sl=Kr(),lm=pi(),dm=Hu(),SP=di().f,vP=nm(),ln=um(),yP=tt(),TP=Fe(),pm="Array Iterator",IP=dm.set,EP=dm.getterFor(pm);hm.exports=vP(Array,"Array",function(a,e){IP(this,{type:pm,target:gP(a),index:0,kind:e})},function(){var a=EP(this),e=a.target,t=a.index++;if(!e||t>=e.length)return a.target=null,ln(void 0,!0);switch(a.kind){case"keys":return ln(t,!1);case"values":return ln(e[t],!1)}return ln([t,e[t]],!1)},"values");var cm=lm.Arguments=lm.Array;sl("keys");sl("values");sl("entries");if(!yP&&TP&&cm.name!=="values")try{SP(cm,"name",{value:"values"})}catch{}});var mm=m((z_,fm)=>{"use strict";var xP=ge(),wP=pi(),AP=xP("iterator"),PP=Array.prototype;fm.exports=function(a){return a!==void 0&&(wP.Array===a||PP[AP]===a)}});var ol=m((Y_,gm)=>{"use strict";var RP=Jr(),bm=Qr(),kP=Ur(),LP=pi(),$P=ge(),MP=$P("iterator");gm.exports=function(a){if(!kP(a))return bm(a,MP)||bm(a,"@@iterator")||LP[RP(a)]}});var vm=m((K_,Sm)=>{"use strict";var DP=Ne(),CP=ht(),BP=ft(),VP=Hr(),_P=ol(),OP=TypeError;Sm.exports=function(a,e){var t=arguments.length<2?_P(a):e;if(CP(t))return BP(DP(t,a));throw new OP(VP(a)+" is not iterable")}});var Im=m((X_,Tm)=>{"use strict";var FP=Ne(),ym=ft(),NP=Qr();Tm.exports=function(a,e,t){var i,r;ym(a);try{if(i=NP(a,"return"),!i){if(e==="throw")throw t;return t}i=FP(i,a)}catch(s){r=!0,i=s}if(e==="throw")throw t;if(r)throw i;return ym(i),t}});var dn=m((J_,Am)=>{"use strict";var qP=Ui(),UP=Ne(),jP=ft(),HP=Hr(),QP=mm(),GP=Gi(),Em=jr(),WP=vm(),zP=ol(),xm=Im(),YP=TypeError,cn=function(a,e){this.stopped=a,this.result=e},wm=cn.prototype;Am.exports=function(a,e,t){var i=t&&t.that,r=!!(t&&t.AS_ENTRIES),s=!!(t&&t.IS_RECORD),n=!!(t&&t.IS_ITERATOR),u=!!(t&&t.INTERRUPTED),o=qP(e,i),l,d,h,c,p,f,b,S=function(T){return l&&xm(l,"normal"),new cn(!0,T)},g=function(T){return r?(jP(T),u?o(T[0],T[1],S):o(T[0],T[1])):u?o(T,S):o(T)};if(s)l=a.iterator;else if(n)l=a;else{if(d=zP(a),!d)throw new YP(HP(a)+" is not iterable");if(QP(d)){for(h=0,c=GP(a);c>h;h++)if(p=g(a[h]),p&&Em(wm,p))return p;return new cn(!1)}l=WP(a,d)}for(f=s?a.next:l.next;!(b=UP(f,l)).done;){try{p=g(b.value)}catch(T){xm(l,"throw",T)}if(typeof p=="object"&&p&&Em(wm,p))return p}return new cn(!1)}});var Rm=m((Z_,Pm)=>{"use strict";var KP=Fe(),XP=di(),JP=qr();Pm.exports=function(a,e,t){KP?XP.f(a,e,JP(0,t)):a[e]=t}});var km=m(()=>{"use strict";var ZP=oe(),eR=dn(),tR=Rm();ZP({target:"Object",stat:!0},{fromEntries:function(e){var t={};return eR(e,function(i,r){tR(t,i,r)},{AS_ENTRIES:!0}),t}})});var $m=m((iO,Lm)=>{"use strict";nl();km();var iR=li();Lm.exports=iR.Object.fromEntries});var Dm=m((rO,Mm)=>{"use strict";Mm.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 Bm=m(()=>{"use strict";nl();var rR=Dm(),aR=re(),sR=Zr(),Cm=pi();for(pn in rR)sR(aR[pn],pn),Cm[pn]=Cm.Array;var pn});var _m=m((nO,Vm)=>{"use strict";var nR=$m();Bm();Vm.exports=nR});var ul=m((oO,Om)=>{"use strict";var oR=_m();Om.exports=oR});var Fm=m(()=>{"use strict"});var ll=m((cO,Nm)=>{"use strict";var ia=re(),uR=ci(),lR=oi(),hn=function(a){return uR.slice(0,a.length)===a};Nm.exports=function(){return hn("Bun/")?"BUN":hn("Cloudflare-Workers")?"CLOUDFLARE":hn("Deno/")?"DENO":hn("Node.js/")?"NODE":ia.Bun&&typeof Bun.version=="string"?"BUN":ia.Deno&&typeof Deno.version=="object"?"DENO":lR(ia.process)==="process"?"NODE":ia.window&&ia.document?"BROWSER":"REST"}()});var fn=m((dO,qm)=>{"use strict";var cR=ll();qm.exports=cR==="NODE"});var jm=m((pO,Um)=>{"use strict";var dR=di();Um.exports=function(a,e,t){return dR.f(a,e,t)}});var Gm=m((hO,Qm)=>{"use strict";var pR=wt(),hR=jm(),fR=ge(),mR=Fe(),Hm=fR("species");Qm.exports=function(a){var e=pR(a);mR&&e&&!e[Hm]&&hR(e,Hm,{configurable:!0,get:function(){return this}})}});var zm=m((fO,Wm)=>{"use strict";var bR=jr(),gR=TypeError;Wm.exports=function(a,e){if(bR(e,a))return a;throw new gR("Incorrect invocation")}});var dl=m((mO,Ym)=>{"use strict";var SR=he(),vR=ae(),cl=Gr(),yR=SR(Function.toString);vR(cl.inspectSource)||(cl.inspectSource=function(a){return yR(a)});Ym.exports=cl.inspectSource});var hl=m((bO,eb)=>{"use strict";var TR=he(),IR=pe(),Km=ae(),ER=Jr(),xR=wt(),wR=dl(),Xm=function(){},Jm=xR("Reflect","construct"),pl=/^\s*(?:class|function)\b/,AR=TR(pl.exec),PR=!pl.test(Xm),ra=function(e){if(!Km(e))return!1;try{return Jm(Xm,[],e),!0}catch{return!1}},Zm=function(e){if(!Km(e))return!1;switch(ER(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return PR||!!AR(pl,wR(e))}catch{return!0}};Zm.sham=!0;eb.exports=!Jm||IR(function(){var a;return ra(ra.call)||!ra(Object)||!ra(function(){a=!0})||a})?Zm:ra});var ib=m((gO,tb)=>{"use strict";var RR=hl(),kR=Hr(),LR=TypeError;tb.exports=function(a){if(RR(a))return a;throw new LR(kR(a)+" is not a constructor")}});var fl=m((SO,ab)=>{"use strict";var rb=ft(),$R=ib(),MR=Ur(),DR=ge(),CR=DR("species");ab.exports=function(a,e){var t=rb(a).constructor,i;return t===void 0||MR(i=rb(t)[CR])?e:$R(i)}});var nb=m((vO,sb)=>{"use strict";var BR=he();sb.exports=BR([].slice)});var ub=m((yO,ob)=>{"use strict";var VR=TypeError;ob.exports=function(a,e){if(a<e)throw new VR("Not enough arguments");return a}});var ml=m((TO,lb)=>{"use strict";var _R=ci();lb.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(_R)});var xl=m((IO,Sb)=>{"use strict";var qe=re(),OR=au(),FR=Ui(),cb=ae(),NR=it(),gb=pe(),db=zu(),qR=nb(),pb=Ws(),UR=ub(),jR=ml(),HR=fn(),Tl=qe.setImmediate,Il=qe.clearImmediate,QR=qe.process,bl=qe.Dispatch,GR=qe.Function,hb=qe.MessageChannel,WR=qe.String,gl=0,aa={},fb="onreadystatechange",sa,fi,Sl,vl;gb(function(){sa=qe.location});var El=function(a){if(NR(aa,a)){var e=aa[a];delete aa[a],e()}},yl=function(a){return function(){El(a)}},mb=function(a){El(a.data)},bb=function(a){qe.postMessage(WR(a),sa.protocol+"//"+sa.host)};(!Tl||!Il)&&(Tl=function(e){UR(arguments.length,1);var t=cb(e)?e:GR(e),i=qR(arguments,1);return aa[++gl]=function(){OR(t,void 0,i)},fi(gl),gl},Il=function(e){delete aa[e]},HR?fi=function(a){QR.nextTick(yl(a))}:bl&&bl.now?fi=function(a){bl.now(yl(a))}:hb&&!jR?(Sl=new hb,vl=Sl.port2,Sl.port1.onmessage=mb,fi=FR(vl.postMessage,vl)):qe.addEventListener&&cb(qe.postMessage)&&!qe.importScripts&&sa&&sa.protocol!=="file:"&&!gb(bb)?(fi=bb,qe.addEventListener("message",mb,!1)):fb in pb("script")?fi=function(a){db.appendChild(pb("script"))[fb]=function(){db.removeChild(this),El(a)}}:fi=function(a){setTimeout(yl(a),0)});Sb.exports={set:Tl,clear:Il}});var Tb=m((EO,yb)=>{"use strict";var vb=re(),zR=Fe(),YR=Object.getOwnPropertyDescriptor;yb.exports=function(a){if(!zR)return vb[a];var e=YR(vb,a);return e&&e.value}});var wl=m((xO,Eb)=>{"use strict";var Ib=function(){this.head=null,this.tail=null};Ib.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}}};Eb.exports=Ib});var wb=m((wO,xb)=>{"use strict";var KR=ci();xb.exports=/ipad|iphone|ipod/i.test(KR)&&typeof Pebble<"u"});var Pb=m((AO,Ab)=>{"use strict";var XR=ci();Ab.exports=/web0s(?!.*chrome)/i.test(XR)});var Cb=m((PO,Db)=>{"use strict";var Ki=re(),JR=Tb(),Rb=Ui(),Al=xl().set,ZR=wl(),ek=ml(),tk=wb(),ik=Pb(),Pl=fn(),kb=Ki.MutationObserver||Ki.WebKitMutationObserver,Lb=Ki.document,$b=Ki.process,mn=Ki.Promise,Ll=JR("queueMicrotask"),Yi,Rl,kl,bn,Mb;Ll||(na=new ZR,oa=function(){var a,e;for(Pl&&(a=$b.domain)&&a.exit();e=na.get();)try{e()}catch(t){throw na.head&&Yi(),t}a&&a.enter()},!ek&&!Pl&&!ik&&kb&&Lb?(Rl=!0,kl=Lb.createTextNode(""),new kb(oa).observe(kl,{characterData:!0}),Yi=function(){kl.data=Rl=!Rl}):!tk&&mn&&mn.resolve?(bn=mn.resolve(void 0),bn.constructor=mn,Mb=Rb(bn.then,bn),Yi=function(){Mb(oa)}):Pl?Yi=function(){$b.nextTick(oa)}:(Al=Rb(Al,Ki),Yi=function(){Al(oa)}),Ll=function(a){na.head||Yi(),na.add(a)});var na,oa;Db.exports=Ll});var Vb=m((RO,Bb)=>{"use strict";Bb.exports=function(a,e){try{arguments.length===1?console.error(a):console.error(a,e)}catch{}}});var gn=m((kO,_b)=>{"use strict";_b.exports=function(a){try{return{error:!1,value:a()}}catch(e){return{error:!0,value:e}}}});var mi=m((LO,Ob)=>{"use strict";var rk=re();Ob.exports=rk.Promise});var Xi=m(($O,Ub)=>{"use strict";var ak=re(),ua=mi(),sk=ae(),nk=Au(),ok=dl(),uk=ge(),Fb=ll(),lk=tt(),$l=hu(),Nb=ua&&ua.prototype,ck=uk("species"),Ml=!1,qb=sk(ak.PromiseRejectionEvent),dk=nk("Promise",function(){var a=ok(ua),e=a!==String(ua);if(!e&&$l===66||lk&&!(Nb.catch&&Nb.finally))return!0;if(!$l||$l<51||!/native code/.test(a)){var t=new ua(function(s){s(1)}),i=function(s){s(function(){},function(){})},r=t.constructor={};if(r[ck]=i,Ml=t.then(function(){})instanceof i,!Ml)return!0}return!e&&(Fb==="BROWSER"||Fb==="DENO")&&!qb});Ub.exports={CONSTRUCTOR:dk,REJECTION_EVENT:qb,SUBCLASSING:Ml}});var Ji=m((MO,Hb)=>{"use strict";var jb=ht(),pk=TypeError,hk=function(a){var e,t;this.promise=new a(function(i,r){if(e!==void 0||t!==void 0)throw new pk("Bad Promise constructor");e=i,t=r}),this.resolve=jb(e),this.reject=jb(t)};Hb.exports.f=function(a){return new hk(a)}});var cg=m(()=>{"use strict";var fk=oe(),mk=tt(),Tn=fn(),qt=re(),bk=li(),ir=Ne(),Qb=zi(),Gb=rl(),gk=Zr(),Sk=Gm(),vk=ht(),yn=ae(),yk=Me(),Tk=zm(),Ik=fl(),Xb=xl().set,_l=Cb(),Ek=Vb(),xk=gn(),wk=wl(),Jb=Hu(),In=mi(),Ol=Xi(),Zb=Ji(),En="Promise",eg=Ol.CONSTRUCTOR,Ak=Ol.REJECTION_EVENT,Pk=Ol.SUBCLASSING,Dl=Jb.getterFor(En),Rk=Jb.set,Zi=In&&In.prototype,bi=In,Sn=Zi,tg=qt.TypeError,Cl=qt.document,Fl=qt.process,Bl=Zb.f,kk=Bl,Lk=!!(Cl&&Cl.createEvent&&qt.dispatchEvent),ig="unhandledrejection",$k="rejectionhandled",Wb=0,rg=1,Mk=2,Nl=1,ag=2,vn,zb,sg,Yb,ng=function(a){var e;return yk(a)&&yn(e=a.then)?e:!1},og=function(a,e){var t=e.value,i=e.state===rg,r=i?a.ok:a.fail,s=a.resolve,n=a.reject,u=a.domain,o,l,d;try{r?(i||(e.rejection===ag&&Ck(e),e.rejection=Nl),r===!0?o=t:(u&&u.enter(),o=r(t),u&&(u.exit(),d=!0)),o===a.promise?n(new tg("Promise-chain cycle")):(l=ng(o))?ir(l,o,s,n):s(o)):n(t)}catch(h){u&&!d&&u.exit(),n(h)}},ug=function(a,e){a.notified||(a.notified=!0,_l(function(){for(var t=a.reactions,i;i=t.get();)og(i,a);a.notified=!1,e&&!a.rejection&&Dk(a)}))},lg=function(a,e,t){var i,r;Lk?(i=Cl.createEvent("Event"),i.promise=e,i.reason=t,i.initEvent(a,!1,!0),qt.dispatchEvent(i)):i={promise:e,reason:t},!Ak&&(r=qt["on"+a])?r(i):a===ig&&Ek("Unhandled promise rejection",t)},Dk=function(a){ir(Xb,qt,function(){var e=a.facade,t=a.value,i=Kb(a),r;if(i&&(r=xk(function(){Tn?Fl.emit("unhandledRejection",t,e):lg(ig,e,t)}),a.rejection=Tn||Kb(a)?ag:Nl,r.error))throw r.value})},Kb=function(a){return a.rejection!==Nl&&!a.parent},Ck=function(a){ir(Xb,qt,function(){var e=a.facade;Tn?Fl.emit("rejectionHandled",e):lg($k,e,a.value)})},er=function(a,e,t){return function(i){a(e,i,t)}},tr=function(a,e,t){a.done||(a.done=!0,t&&(a=t),a.value=e,a.state=Mk,ug(a,!0))},Vl=function(a,e,t){if(!a.done){a.done=!0,t&&(a=t);try{if(a.facade===e)throw new tg("Promise can't be resolved itself");var i=ng(e);i?_l(function(){var r={done:!1};try{ir(i,e,er(Vl,r,a),er(tr,r,a))}catch(s){tr(r,s,a)}}):(a.value=e,a.state=rg,ug(a,!1))}catch(r){tr({done:!1},r,a)}}};if(eg&&(bi=function(e){Tk(this,Sn),vk(e),ir(vn,this);var t=Dl(this);try{e(er(Vl,t),er(tr,t))}catch(i){tr(t,i)}},Sn=bi.prototype,vn=function(e){Rk(this,{type:En,done:!1,notified:!1,parent:!1,reactions:new wk,rejection:!1,state:Wb,value:null})},vn.prototype=Qb(Sn,"then",function(e,t){var i=Dl(this),r=Bl(Ik(this,bi));return i.parent=!0,r.ok=yn(e)?e:!0,r.fail=yn(t)&&t,r.domain=Tn?Fl.domain:void 0,i.state===Wb?i.reactions.add(r):_l(function(){og(r,i)}),r.promise}),zb=function(){var a=new vn,e=Dl(a);this.promise=a,this.resolve=er(Vl,e),this.reject=er(tr,e)},Zb.f=Bl=function(a){return a===bi||a===sg?new zb(a):kk(a)},!mk&&yn(In)&&Zi!==Object.prototype)){Yb=Zi.then,Pk||Qb(Zi,"then",function(e,t){var i=this;return new bi(function(r,s){ir(Yb,i,r,s)}).then(e,t)},{unsafe:!0});try{delete Zi.constructor}catch{}Gb&&Gb(Zi,Sn)}fk({global:!0,constructor:!0,wrap:!0,forced:eg},{Promise:bi});sg=bk.Promise;gk(bi,En,!1,!0);Sk(En)});var mg=m((BO,fg)=>{"use strict";var Bk=ge(),pg=Bk("iterator"),hg=!1;try{dg=0,ql={next:function(){return{done:!!dg++}},return:function(){hg=!0}},ql[pg]=function(){return this},Array.from(ql,function(){throw 2})}catch{}var dg,ql;fg.exports=function(a,e){try{if(!e&&!hg)return!1}catch{return!1}var t=!1;try{var i={};i[pg]=function(){return{next:function(){return{done:t=!0}}}},a(i)}catch{}return t}});var Ul=m((VO,bg)=>{"use strict";var Vk=mi(),_k=mg(),Ok=Xi().CONSTRUCTOR;bg.exports=Ok||!_k(function(a){Vk.all(a).then(void 0,function(){})})});var gg=m(()=>{"use strict";var Fk=oe(),Nk=Ne(),qk=ht(),Uk=Ji(),jk=gn(),Hk=dn(),Qk=Ul();Fk({target:"Promise",stat:!0,forced:Qk},{all:function(e){var t=this,i=Uk.f(t),r=i.resolve,s=i.reject,n=jk(function(){var u=qk(t.resolve),o=[],l=0,d=1;Hk(e,function(h){var c=l++,p=!1;d++,Nk(u,t,h).then(function(f){p||(p=!0,o[c]=f,--d||r(o))},s)}),--d||r(o)});return n.error&&s(n.value),i.promise}})});var vg=m(()=>{"use strict";var Gk=oe(),Wk=tt(),zk=Xi().CONSTRUCTOR,Hl=mi(),Yk=wt(),Kk=ae(),Xk=zi(),Sg=Hl&&Hl.prototype;Gk({target:"Promise",proto:!0,forced:zk,real:!0},{catch:function(a){return this.then(void 0,a)}});!Wk&&Kk(Hl)&&(jl=Yk("Promise").prototype.catch,Sg.catch!==jl&&Xk(Sg,"catch",jl,{unsafe:!0}));var jl});var yg=m(()=>{"use strict";var Jk=oe(),Zk=Ne(),eL=ht(),tL=Ji(),iL=gn(),rL=dn(),aL=Ul();Jk({target:"Promise",stat:!0,forced:aL},{race:function(e){var t=this,i=tL.f(t),r=i.reject,s=iL(function(){var n=eL(t.resolve);rL(e,function(u){Zk(n,t,u).then(i.resolve,r)})});return s.error&&r(s.value),i.promise}})});var Tg=m(()=>{"use strict";var sL=oe(),nL=Ji(),oL=Xi().CONSTRUCTOR;sL({target:"Promise",stat:!0,forced:oL},{reject:function(e){var t=nL.f(this),i=t.reject;return i(e),t.promise}})});var Ql=m((QO,Ig)=>{"use strict";var uL=ft(),lL=Me(),cL=Ji();Ig.exports=function(a,e){if(uL(a),lL(e)&&e.constructor===a)return e;var t=cL.f(a),i=t.resolve;return i(e),t.promise}});var wg=m(()=>{"use strict";var dL=oe(),pL=wt(),Eg=tt(),hL=mi(),xg=Xi().CONSTRUCTOR,fL=Ql(),mL=pL("Promise"),bL=Eg&&!xg;dL({target:"Promise",stat:!0,forced:Eg||xg},{resolve:function(e){return fL(bL&&this===mL?hL:this,e)}})});var Ag=m(()=>{"use strict";cg();gg();vg();yg();Tg();wg()});var Lg=m(()=>{"use strict";var gL=oe(),SL=tt(),xn=mi(),vL=pe(),Rg=wt(),kg=ae(),yL=fl(),Pg=Ql(),TL=zi(),Wl=xn&&xn.prototype,IL=!!xn&&vL(function(){Wl.finally.call({then:function(){}},function(){})});gL({target:"Promise",proto:!0,real:!0,forced:IL},{finally:function(a){var e=yL(this,Rg("Promise")),t=kg(a);return this.then(t?function(i){return Pg(e,a()).then(function(){return i})}:a,t?function(i){return Pg(e,a()).then(function(){throw i})}:a)}});!SL&&kg(xn)&&(Gl=Rg("Promise").prototype.finally,Wl.finally!==Gl&&TL(Wl,"finally",Gl,{unsafe:!0}));var Gl});var Mg=m((JO,$g)=>{"use strict";Fm();Ag();Lg();var EL=Nt();$g.exports=EL("Promise","finally")});var Cg=m((ZO,Dg)=>{"use strict";var xL=Mg();Dg.exports=xL});var wn=m((eF,Bg)=>{"use strict";var wL=Cg();Bg.exports=wL});var eS=m(()=>{"use strict";var GL=oe(),WL=Nu().values;GL({target:"Object",stat:!0},{values:function(e){return WL(e)}})});var iS=m((SN,tS)=>{"use strict";eS();var zL=li();tS.exports=zL.Object.values});var aS=m((vN,rS)=>{"use strict";var YL=iS();rS.exports=YL});var sr=m((yN,sS)=>{"use strict";var KL=aS();sS.exports=KL});var bS=m(()=>{"use strict";var p$=oe(),h$=Ni(),f$=Gi(),m$=Yr(),b$=Kr();p$({target:"Array",proto:!0},{at:function(e){var t=h$(this),i=f$(t),r=m$(e),s=r>=0?r:i+r;return s<0||s>=i?void 0:t[s]}});b$("at")});var SS=m((KN,gS)=>{"use strict";bS();var g$=Nt();gS.exports=g$("Array","at")});var yS=m((XN,vS)=>{"use strict";var S$=SS();vS.exports=S$});var at=m((JN,TS)=>{"use strict";var v$=yS();TS.exports=v$});var Sc=m((jU,iv)=>{"use strict";var Z$=oi();iv.exports=Array.isArray||function(e){return Z$(e)==="Array"}});var av=m((HU,rv)=>{"use strict";var eM=TypeError,tM=9007199254740991;rv.exports=function(a){if(a>tM)throw eM("Maximum allowed index exceeded");return a}});var ov=m((QU,nv)=>{"use strict";var iM=Sc(),rM=Gi(),aM=av(),sM=Ui(),sv=function(a,e,t,i,r,s,n,u){for(var o=r,l=0,d=n?sM(n,u):!1,h,c;l<i;)l in t&&(h=d?d(t[l],l,e):t[l],s>0&&iM(h)?(c=rM(h),o=sv(a,e,h,c,o,s-1)-1):(aM(o+1),a[o]=h),o++),l++;return o};nv.exports=sv});var dv=m((GU,cv)=>{"use strict";var uv=Sc(),nM=hl(),oM=Me(),uM=ge(),lM=uM("species"),lv=Array;cv.exports=function(a){var e;return uv(a)&&(e=a.constructor,nM(e)&&(e===lv||uv(e.prototype))?e=void 0:oM(e)&&(e=e[lM],e===null&&(e=void 0))),e===void 0?lv:e}});var hv=m((WU,pv)=>{"use strict";var cM=dv();pv.exports=function(a,e){return new(cM(a))(e===0?0:e)}});var fv=m(()=>{"use strict";var dM=oe(),pM=ov(),hM=ht(),fM=Ni(),mM=Gi(),bM=hv();dM({target:"Array",proto:!0},{flatMap:function(e){var t=fM(this),i=mM(t),r;return hM(e),r=bM(t,0),r.length=pM(r,t,t,i,0,1,e,arguments.length>1?arguments[1]:void 0),r}})});var mv=m(()=>{"use strict";var gM=Kr();gM("flatMap")});var gv=m((JU,bv)=>{"use strict";fv();mv();var SM=Nt();bv.exports=SM("Array","flatMap")});var vv=m((ZU,Sv)=>{"use strict";var vM=gv();Sv.exports=vM});var xa=m((e1,yv)=>{"use strict";var yM=vv();yv.exports=yM});var wa=m((t1,Tv)=>{"use strict";var TM=Jr(),IM=String;Tv.exports=function(a){if(TM(a)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return IM(a)}});var vc=m((i1,Iv)=>{"use strict";Iv.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 wv=m((r1,xv)=>{"use strict";var EM=he(),xM=Ft(),wM=wa(),Tc=vc(),Ev=EM("".replace),AM=RegExp("^["+Tc+"]+"),PM=RegExp("(^|[^"+Tc+"])["+Tc+"]+$"),yc=function(a){return function(e){var t=wM(xM(e));return a&1&&(t=Ev(t,AM,"")),a&2&&(t=Ev(t,PM,"$1")),t}};xv.exports={start:yc(1),end:yc(2),trim:yc(3)}});var kv=m((a1,Rv)=>{"use strict";var RM=Wu().PROPER,kM=pe(),Av=vc(),Pv="\u200B\x85\u180E";Rv.exports=function(a){return kM(function(){return!!Av[a]()||Pv[a]()!==Pv||RM&&Av[a].name!==a})}});var Ic=m((s1,Lv)=>{"use strict";var LM=wv().start,$M=kv();Lv.exports=$M("trimStart")?function(){return LM(this)}:"".trimStart});var Mv=m(()=>{"use strict";var MM=oe(),$v=Ic();MM({target:"String",proto:!0,name:"trimStart",forced:"".trimLeft!==$v},{trimLeft:$v})});var Cv=m(()=>{"use strict";Mv();var DM=oe(),Dv=Ic();DM({target:"String",proto:!0,name:"trimStart",forced:"".trimStart!==Dv},{trimStart:Dv})});var Vv=m((c1,Bv)=>{"use strict";Cv();var CM=Nt();Bv.exports=CM("String","trimLeft")});var Ov=m((d1,_v)=>{"use strict";var BM=Vv();_v.exports=BM});var Nv=m((p1,Fv)=>{"use strict";var VM=Ov();Fv.exports=VM});var iy=m(()=>{"use strict"});var ry=m(()=>{"use strict"});var sy=m((JH,ay)=>{"use strict";var nD=Me(),oD=oi(),uD=ge(),lD=uD("match");ay.exports=function(a){var e;return nD(a)&&((e=a[lD])!==void 0?!!e:oD(a)==="RegExp")}});var uy=m((ZH,oy)=>{"use strict";var cD=re(),dD=pe(),ny=cD.RegExp,pD=!dD(function(){var a=!0;try{ny(".","d")}catch{a=!1}var e={},t="",i=a?"dgimsy":"gimsy",r=function(o,l){Object.defineProperty(e,o,{get:function(){return t+=l,!0}})},s={dotAll:"s",global:"g",ignoreCase:"i",multiline:"m",sticky:"y"};a&&(s.hasIndices="d");for(var n in s)r(n,s[n]);var u=Object.getOwnPropertyDescriptor(ny.prototype,"flags").get.call(e);return u!==i||t!==i});oy.exports={correct:pD}});var cy=m((eQ,ly)=>{"use strict";var hD=ft();ly.exports=function(){var a=hD(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 hy=m((tQ,py)=>{"use strict";var fD=Ne(),mD=it(),bD=jr(),dy=uy(),gD=cy(),SD=RegExp.prototype;py.exports=dy.correct?function(a){return a.flags}:function(a){return!dy.correct&&bD(SD,a)&&!mD(a,"flags")?fD(gD,a):a.flags}});var my=m((iQ,fy)=>{"use strict";var Pc=he(),vD=Ni(),yD=Math.floor,wc=Pc("".charAt),TD=Pc("".replace),Ac=Pc("".slice),ID=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,ED=/\$([$&'`]|\d{1,2})/g;fy.exports=function(a,e,t,i,r,s){var n=t+a.length,u=i.length,o=ED;return r!==void 0&&(r=vD(r),o=ID),TD(s,o,function(l,d){var h;switch(wc(d,0)){case"$":return"$";case"&":return a;case"`":return Ac(e,0,t);case"'":return Ac(e,n);case"<":h=r[Ac(d,1,-1)];break;default:var c=+d;if(c===0)return l;if(c>u){var p=yD(c/10);return p===0?l:p<=u?i[p-1]===void 0?wc(d,1):i[p-1]+wc(d,1):l}h=i[c-1]}return h===void 0?"":h})}});var Sy=m(()=>{"use strict";var xD=oe(),wD=Ne(),kc=he(),by=Ft(),AD=ae(),PD=Me(),RD=sy(),gr=wa(),kD=Qr(),LD=hy(),$D=my(),MD=ge(),DD=tt(),CD=MD("replace"),BD=TypeError,Rc=kc("".indexOf),VD=kc("".replace),gy=kc("".slice),_D=Math.max;xD({target:"String",proto:!0},{replaceAll:function(e,t){var i=by(this),r,s,n,u,o,l,d,h,c,p,f=0,b="";if(PD(e)){if(r=RD(e),r&&(s=gr(by(LD(e))),!~Rc(s,"g")))throw new BD("`.replaceAll` does not allow non-global regexes");if(n=kD(e,CD),n)return wD(n,e,i,t);if(DD&&r)return VD(gr(i),e,t)}for(u=gr(i),o=gr(e),l=AD(t),l||(t=gr(t)),d=o.length,h=_D(1,d),c=Rc(u,o);c!==-1;)p=l?gr(t(o,c,u)):$D(o,u,c,[],void 0,t),b+=gy(u,f,c)+p,f=c+d,c=c+h>u.length?-1:Rc(u,o,c+h);return f<u.length&&(b+=gy(u,f)),b}})});var yy=m((sQ,vy)=>{"use strict";iy();ry();Sy();var OD=Nt();vy.exports=OD("String","replaceAll")});var Iy=m((nQ,Ty)=>{"use strict";var FD=yy();Ty.exports=FD});var xy=m((oQ,Ey)=>{"use strict";var ND=Iy();Ey.exports=ND});var Ay=m((uQ,wy)=>{"use strict";var qD=Yr(),UD=wa(),jD=Ft(),HD=RangeError;wy.exports=function(e){var t=UD(jD(this)),i="",r=qD(e);if(r<0||r===1/0)throw new HD("Wrong number of repetitions");for(;r>0;(r>>>=1)&&(t+=t))r&1&&(i+=t);return i}});var $y=m((lQ,Ly)=>{"use strict";var ky=he(),QD=Mu(),Py=wa(),GD=Ay(),WD=Ft(),zD=ky(GD),YD=ky("".slice),KD=Math.ceil,Ry=function(a){return function(e,t,i){var r=Py(WD(e)),s=QD(t),n=r.length,u=i===void 0?" ":Py(i),o,l;return s<=n||u===""?r:(o=s-n,l=zD(u,KD(o/u.length)),l.length>o&&(l=YD(l,0,o)),a?r+l:l+r)}};Ly.exports={start:Ry(!1),end:Ry(!0)}});var Dy=m((cQ,My)=>{"use strict";var XD=ci();My.exports=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(XD)});var Cy=m(()=>{"use strict";var JD=oe(),ZD=$y().start,eC=Dy();JD({target:"String",proto:!0,forced:eC},{padStart:function(e){return ZD(this,e,arguments.length>1?arguments[1]:void 0)}})});var Vy=m((hQ,By)=>{"use strict";Cy();var tC=Nt();By.exports=tC("String","padStart")});var Oy=m((fQ,_y)=>{"use strict";var iC=Vy();_y.exports=iC});var Ny=m((mQ,Fy)=>{"use strict";var rC=Oy();Fy.exports=rC});var Ud="2.0.138-dev.b9cfb5f8.0";var $e=(r=>(r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused",r))($e||{}),xt=(y=>(y.MPEG="MPEG",y.DASH="DASH",y.DASH_SEP="DASH_SEP",y.DASH_SEP_VK="DASH_SEP",y.DASH_WEBM="DASH_WEBM",y.DASH_WEBM_AV1="DASH_WEBM_AV1",y.DASH_STREAMS="DASH_STREAMS",y.DASH_WEBM_VK="DASH_WEBM",y.DASH_ONDEMAND="DASH_ONDEMAND",y.DASH_ONDEMAND_VK="DASH_ONDEMAND",y.DASH_LIVE="DASH_LIVE",y.DASH_LIVE_CMAF="DASH_LIVE_CMAF",y.DASH_LIVE_WEBM="DASH_LIVE_WEBM",y.HLS="HLS",y.HLS_ONDEMAND="HLS_ONDEMAND",y.HLS_JS="HLS",y.HLS_FMP4="HLS_FMP4",y.HLS_LIVE="HLS_LIVE",y.HLS_LIVE_CMAF="HLS_LIVE_CMAF",y.WEB_RTC_LIVE="WEB_RTC_LIVE",y))(xt||{});var js=(r=>(r.NOT_AVAILABLE="NOT_AVAILABLE",r.AVAILABLE="AVAILABLE",r.CONNECTING="CONNECTING",r.CONNECTED="CONNECTED",r))(js||{}),tu=(i=>(i.HTTP1="http1",i.HTTP2="http2",i.QUIC="quic",i))(tu||{});var iu=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(iu||{}),Hs=(i=>(i.TRAFFIC_SAVING="traffic_saving",i.HIGH_QUALITY="high_quality",i.UNKNOWN="unknown",i))(Hs||{});var CI=C(Ee(),1);import{assertNever as Nh,assertNonNullable as pw,isNonNullable as Ys,ValueSubject as Cu,Subject as hw,Subscription as fw,merge as mw,observableFrom as bw,fromEvent as Vh,map as _h,tap as Oh,filterChanged as gw,isNullable as Bu,ErrorCategory as Fh}from"@vkontakte/videoplayer-shared";var Bh=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 Ks=class{constructor(e){this.connection$=new Cu(void 0);this.castState$=new Cu("NOT_AVAILABLE");this.errorEvent$=new hw;this.realCastState$=new Cu("NOT_AVAILABLE");this.subscription=new fw;this.isDestroyed=!1;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastInitializer");let t="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${t}`}),e.isDisabled||!t)return;let i=Ys(window.chrome?.cast),r=!!window.__onGCastApiAvailable;i?this.initializeCastApi():(window.__onGCastApiAvailable=s=>{delete window.__onGCastApiAvailable,s&&!this.isDestroyed&&this.initializeCastApi()},r||Bh("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:Fh.NETWORK,message:"Script loading failed!"})))}connect(){cast.framework.CastContext.getInstance()?.requestSession()}disconnect(){cast.framework.CastContext.getInstance()?.getCurrentSession()?.endSession(!0)}stopMedia(){return new Promise((e,t)=>{cast.framework.CastContext.getInstance()?.getCurrentSession()?.getMediaSession()?.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){Ys(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();Bu(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();Bu(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(Vh(i,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(r=>{switch(r.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=i.getCurrentSession()?.getMediaSession()?.media?.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return Nh(r.sessionState)}})).add(mw(Vh(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(Oh(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),_h(r=>r.castState)),bw([i.getCastState()])).pipe(gw(),_h(Sw),Oh(r=>{this.log({message:`realCastState$: ${r}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{let s=r==="CONNECTED",n=Ys(this.connection$.getValue());if(s&&!n){let u=i.getCurrentSession();pw(u);let o=u.getCastDevice(),l=u.getMediaSession()?.media?.contentId;(Bu(l)||l===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:u,castDevice:o}))}else!s&&n&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(r==="CONNECTED"?Ys(this.connection$.getValue())?"CONNECTED":"AVAILABLE":r)}))}initializeCastApi(){let e,t,i;try{e=cast.framework.CastContext.getInstance(),t=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,i=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch{return}try{e.setOptions({receiverApplicationId:this.params.receiverApplicationId??t,autoJoinPolicy:i}),this.initListeners()}catch(r){this.errorEvent$.next({id:"ChromecastInitializer",category:Fh.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:r})}}},Sw=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 Nh(a)}};var Md=C(Ee(),1),mI=C(Wi(),1),bI=C(ul(),1);var Xg=C(wn(),1);import{assertNever as Vg}from"@vkontakte/videoplayer-shared";var se=(a,e=0,t=0)=>{switch(t){case 0:return a.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case 1:{if(e===0)return a;let i=new URL(a);return i.searchParams.append("playback_shift",e.toFixed(0)),i.toString()}case 2:{let i=new URL(a);return!i.searchParams.get("offset_p")&&e===0?a:(i.searchParams.set("offset_p",e.toFixed(0)),i.toString())}default:Vg(t)}return a},Ut=(a,e)=>{switch(e){case 0:return NaN;case 1:{let t=new URL(a);return Number(t.searchParams.get("playback_shift"))}case 2:{let t=new URL(a);return Number(t.searchParams.get("offset_p")??0)}default:Vg(e)}};var P=(a,e,t=!1)=>{let i=a.getTransition();(t||!i||i.to===e)&&a.setState(e)};import{isNonNullable as AL,Subject as An,merge as _g}from"@vkontakte/videoplayer-shared";var F=class{constructor(e){this.transitionStarted$=new An;this.transitionEnded$=new An;this.transitionUpdated$=new An;this.forceChanged$=new An;this.stateChangeStarted$=_g(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=_g(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||AL(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 Hg}from"@vkontakte/videoplayer-shared";var Pn=class{constructor(){this._isMiuiBrowser=!1}get current(){return this._current}get isChrome(){return this.current==="Chrome"}get isFirefox(){return this.current==="Firefox"}get isSafari(){return this.current==="Safari"}get isOpera(){return this.current==="Opera"}get isEdge(){return this.current==="Edge"}get isYandex(){return this.current==="Yandex"}get isSamsungBrowser(){return this.current==="SamsungBrowser"}get currentVersion(){return this._current_version}get chromeVersion(){return this._chromeVersion}get firefoxVersion(){return this._firefoxVersion}get safariVersion(){return this._safariVersion}get operaVersion(){return this._operaVersion}get edgeVersion(){return this._edgeVersion}get yandexVersion(){return this._yandexVersion}get isMiuiBrowser(){return this._isMiuiBrowser}detect(){let{userAgent:e}=navigator;try{let t=/yabrowser/i.test(e)?"Yandex":void 0,i=/samsungbrowser/i.test(e)?"SamsungBrowser":void 0,r=/chrome|crios/i.test(e)?"Chrome":void 0,s=/chromium/i.test(e)?"Chromium":void 0,n=/firefox|fxios/i.test(e)?"Firefox":void 0,u=/webkit|safari|khtml/i.test(e)?"Safari":void 0,o=/opr\//i.test(e)?"Opera":void 0,l=/edg/i.test(e)?"Edge":void 0;this._isMiuiBrowser=/(XiaoMi)|(MiuiBrowser)/i.test(e),this._current=t||i||n||o||l||r||s||u||"Rest"}catch(t){console.error(t)}this.isChrome&&this.detectChromeVersion(),this.isFirefox&&this.detectFirefoxVersion(),this.isSafari&&this.detectSafariVersion(),this.isOpera&&this.detectOperaVersion(),this.isEdge&&this.detectEdgeVersion(),this.isYandex&&this.detectYandexVersion()}detectVersion(e){try{let{userAgent:t}=window.navigator,i=t.match(e);if(!i)return;let r=i[1],s=parseInt(r,10);if(!isNaN(s))return this._current_version=s,s}catch(t){console.error(t)}}detectChromeVersion(){this._chromeVersion=this.detectVersion(/Chrome\/(\d+\.\d+)/)}detectFirefoxVersion(){this._firefoxVersion=this.detectVersion(/Firefox\/(\d+\.\d+)/)}detectSafariVersion(){this._safariVersion=this.detectVersion(/Version\/(\d+)/)}detectOperaVersion(){this._operaVersion=this.detectVersion(/OPR\/(\d+\.\d+)/)}detectEdgeVersion(){this._edgeVersion=this.detectVersion(/Edg\/(\d+\.\d+)/)}detectYandexVersion(){this._yandexVersion=this.detectVersion(/YaBrowser\/(\d+\.\d+\.\d+)/)}};var Og=C(Ee(),1);var la=()=>/Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test(navigator.appVersion??navigator.userAgent)||navigator?.userAgentData?.mobile;var Rn=class{constructor(e){this._highEntropyValues={};this._displayChecker=e}get current(){return this._current}get isIOS(){let e=["iPhone","iPad","iPod"];return this._highEntropyValues.platform==="iOS"||(0,Og.default)(e,this.current)}get isMac(){return this._highEntropyValues.platform==="macOS"||this.current==="Mac"}get isApple(){return this.isIOS||this.isMac}get isIphoneOrOldIpad(){if(!this.isApple||!this._displayChecker.isTouch)return!1;let e=this.current==="iPad"||this._displayChecker.width>700,t=this._iosVersion;return!e||e&&!!t&&t<16}get isAndroid(){return this._highEntropyValues.platform==="Android"||this.current==="Android"}get isMobile(){return this._highEntropyValues.mobile||this._isMobile}get iOSVersion(){return this._iosVersion}detect(){let{userAgent:e}=navigator;try{this._isMobile=la()}catch(t){console.error(t)}this.detectDevice(e),this.detectHighEntropyValues(),this.isIOS&&this.detectIOSVersion()}async detectHighEntropyValues(){let{userAgentData:e}=navigator;if(e?.getHighEntropyValues){let t=await e.getHighEntropyValues(["architecture","bitness","brands","mobile","platform","formFactor","model","platformVersion","wow64"]);this._highEntropyValues=t}}detectDevice(e){try{let t=/android/i.test(e)?"Android":void 0,i=/iphone/i.test(e)?"iPhone":void 0,r=/ipad/i.test(e)?"iPad":void 0,s=/ipod/i.test(e)?"iPod":void 0,n=/mac/i.test(e)?"Mac":void 0,u=/webOS|BlackBerry|IEMobile|Opera Mini/i.test(e)?"RestMobile":void 0;this._current=t||i||r||s||u||n||"Desktop"}catch(t){console.error(t)}}detectIOSVersion(){try{if(this._highEntropyValues.platformVersion){let s=this._highEntropyValues.platformVersion.split(".").slice(0,2).join("."),n=parseFloat(s);this._iosVersion=n;return}let{userAgent:e}=window.navigator,t=e.match(/OS (\d+(_\d+)?)/i);if(!t)return;let i=t[1].replace(/_/g,".");if(!i)return;let r=parseFloat(i);if(isNaN(r))return;this._iosVersion=r}catch(e){console.error(e)}}};var kn=class{get isTouch(){return typeof this._maxTouchPoints=="number"?this._maxTouchPoints>1:"ontouchstart"in window}get maxTouchPoints(){return this._maxTouchPoints}get height(){return this._height}get width(){return this._width}get screenHeight(){return this._screenHeight}get screenWidth(){return this._screenWidth}get pixelRatio(){return this._pixelRatio}get isHDR(){return this._isHdr}get colorDepth(){return this._colorDepth}detect(){let{maxTouchPoints:e}=navigator;try{this._maxTouchPoints=e??0,this._isHdr=!!matchMedia("(dynamic-range: high)")?.matches,this._colorDepth=screen.colorDepth}catch(t){console.error(t)}try{this._pixelRatio=window.devicePixelRatio||1,this._height=screen.height,this._width=screen.width,this._height=screen.height,this._screenHeight=this._height*this._pixelRatio,this._screenWidth=this._width*this._pixelRatio}catch(t){console.error(t)}}};var Ue=()=>window.ManagedMediaSource||window.MediaSource,rr=()=>!!(window.ManagedMediaSource&&window.ManagedSourceBuffer?.prototype?.appendBuffer),Fg=()=>!!(window.MediaSource&&window.SourceBuffer?.prototype?.appendBuffer),Ln=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;var PL=document.createElement("video"),RL='video/mp4; codecs="avc1.42000a,mp4a.40.2"',kL='video/mp4; codecs="hev1.1.6.L93.B0"',Ng='video/webm; codecs="vp09.00.10.08"',qg='video/webm; codecs="av01.0.00M.08"',LL='audio/mp4; codecs="mp4a.40.2"',$L='audio/webm; codecs="opus"',Ug,ML=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:qg}}),window.navigator.mediaCapabilities.decodingInfo({...a,video:{...a.video,contentType:Ng}})]);Ug={DASH_WEBM_AV1:e,DASH_WEBM:t}};ML().catch(a=>{console.log(PL),console.error(a)});var $n=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 Ug}get supportedCodecs(){return Object.keys(this._codecs).filter(e=>this._codecs[e])}get nativeHlsSupported(){return this._nativeHlsSupported}detect(){this._video=document.createElement("video");try{this._protocols={mms:rr(),mse:Fg(),hls:!!(this._video.canPlayType?.("application/x-mpegurl")||this._video.canPlayType?.("vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},this._containers={mp4:!!this._video.canPlayType?.("video/mp4"),webm:!!this._video.canPlayType?.("video/webm"),cmaf:!0};let e=!!Ue()?.isTypeSupported?.(RL),t=!!Ue()?.isTypeSupported?.(kL),i=!!Ue()?.isTypeSupported?.(LL);this._codecs={h264:e,h265:t,vp9:!!Ue()?.isTypeSupported?.(Ng),av1:!!Ue()?.isTypeSupported?.(qg),aac:i,opus:!!Ue()?.isTypeSupported?.($L),mpeg:(e||t)&&i},this._nativeHlsSupported=this._protocols.hls&&this._containers.mp4}catch(e){console.error(e)}try{this.destroyVideoElement()}catch(e){console.error("Error destroying video element:",e)}}destroyVideoElement(){if(!this._video)return;if(this._video.pause(),this._video.currentTime=0,this._video.removeAttribute("src"),this._video.src="",this._video.load(),this._video.remove){this._video.remove(),this._video=null;return}this._video.parentNode&&this._video.parentNode.removeChild(this._video);let e=this._video.cloneNode(!1);this._video.parentNode?.replaceChild(e,this._video),this._video=null}};var jg="audio/mpeg",Mn=class{supportMp3(){return this._codecs.mp3&&this._containers.mpeg}detect(){this._audio=document.createElement("audio");try{this._containers={mpeg:!!this._audio.canPlayType?.(jg)},this._codecs={mp3:!!Ue()?.isTypeSupported?.(jg)}}catch(e){console.error(e)}try{this.destroyAudioElement()}catch(e){console.error("Error destroying audio element:",e)}}destroyAudioElement(){if(!this._audio)return;if(this._audio.pause(),this._audio.currentTime=0,this._audio.removeAttribute("src"),this._audio.src="",this._audio.load(),this._audio.remove){this._audio.remove(),this._audio=null;return}this._audio.parentNode&&this._audio.parentNode.removeChild(this._audio);let e=this._audio.cloneNode(!1);this._audio.parentNode?.replaceChild(e,this._audio),this._audio=null}};import{ValueSubject as DL}from"@vkontakte/videoplayer-shared";var zl=class{constructor(){this.isInited$=new DL(!1);this._displayChecker=new kn,this._deviceChecker=new Rn(this._displayChecker),this._browserChecker=new Pn,this._videoChecker=new $n(this._deviceChecker,this._browserChecker),this._audioChecker=new Mn,this.detect()}get display(){return this._displayChecker}get device(){return this._deviceChecker}get browser(){return this._browserChecker}get video(){return this._videoChecker}get audio(){return this._audioChecker}async detect(){this._displayChecker.detect(),this._deviceChecker.detect(),this._browserChecker.detect(),this._videoChecker.detect(),this._audioChecker.detect(),this.isInited$.next(!0)}},B=new zl;var Yl=a=>{let{containers:e,protocols:t,codecs:i,nativeHlsSupported:r}=B.video,s=(i.h264||i.h265)&&i.aac,n=t.mse||t.mms;return a.filter(u=>{switch(u){case"DASH_SEP":return n&&e.mp4&&s;case"DASH_WEBM":return n&&e.webm&&i.vp9&&i.opus;case"DASH_WEBM_AV1":return n&&e.webm&&i.av1&&i.opus;case"DASH_STREAMS":return n&&(e.mp4&&s||e.webm&&(i.vp9||i.av1)&&(i.opus||i.aac));case"DASH_LIVE":return n&&e.mp4&&s;case"DASH_LIVE_CMAF":return n&&e.mp4&&s&&e.cmaf;case"DASH_ONDEMAND":return n&&e.mp4&&s;case"HLS":case"HLS_ONDEMAND":case"HLS_FMP4":case"HLS_LIVE":case"HLS_LIVE_CMAF":return r;case"MPEG":return e.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return t.webrtc&&t.ws&&i.h264&&(e.mp4||e.webm);default:return Hg(u)}})},Kl=a=>{switch(a){case"MPEG":case"DASH":case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":case"HLS":case"HLS_FMP4":case"HLS_ONDEMAND":return!1;case"DASH_LIVE":case"DASH_LIVE_CMAF":case"HLS_LIVE":case"HLS_LIVE_CMAF":case"DASH_LIVE_WEBM":case"WEB_RTC_LIVE":return!0;default:return Hg(a)}},CL=a=>{let t=Object.keys(a).filter(i=>!Kl(i));return Yl(t).length>0};import{assertNever as ar,assertNonNullable as gi,debounce as Qg,ErrorCategory as Gg,fromEvent as Si,isNonNullable as Wg,map as zg,merge as Yg,observableFrom as BL,Subject as VL,Subscription as Xl,timeout as _L,getHighestQuality as OL}from"@vkontakte/videoplayer-shared";var FL=5,NL=5,qL=500,Kg=7e3,ca=class{constructor(e){this.subscription=new Xl;this.loadMediaTimeoutSubscription=new Xl;this.videoState=new F("stopped");this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(s)};`}),i==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.stop());return}if(!t){if(r?.to!=="paused"&&s.state==="requested"&&e!=="stopped"){this.seek(s.position/1e3);return}switch(i){case"ready":{switch(e){case"playing":case"paused":case"ready":break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:ar(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:ar(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:ar(e)}break}default:ar(i)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(Kl(e.format)),this.params.output.isAudioAvailable$.next(!0),this.handleRemoteVolumeChange({volume:this.params.connection.remotePlayer.volumeLevel,muted:this.params.connection.remotePlayer.isMuted});let t=this.params.connection.session.getMediaSession();t&&this.restoreSession(t),this.subscribe()}destroy(){this.log({message:"[destroy]"}),this.subscription.unsubscribe()}subscribe(){this.subscription.add(this.loadMediaTimeoutSubscription);let e=new Xl;this.subscription.add(e),this.subscription.add(Yg(this.videoState.stateChangeStarted$.pipe(zg(r=>`stateChangeStarted$ ${JSON.stringify(r)}`)),this.videoState.stateChangeEnded$.pipe(zg(r=>`stateChangeEnded$ ${JSON.stringify(r)}`))).subscribe(r=>this.log({message:`[videoState] ${r}`})));let t=(r,s)=>this.subscription.add(r.subscribe(s));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{let r=new VL;e.add(r.pipe(Qg(qL)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add(Si(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe(n=>{this.logRemoteEvent(n);let u=n.value;this.params.output.position$.next(u),(this.params.desiredState.seekState.getState().state==="applying"||Math.abs(u-s)>FL)&&r.next(u),s=u})),e.add(Si(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(Si(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(Si(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemotePause():this.handleRemotePlay()}),t(Si(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),r=>{this.logRemoteEvent(r);let{remotePlayer:s}=this.params.connection,n=r.value,u=this.params.output.isBuffering$.getValue(),o=n===chrome.cast.media.PlayerState.BUFFERING;switch(u!==o&&this.params.output.isBuffering$.next(o),n){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&s.duration-s.currentTime<NL&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),P(this.params.desiredState.playbackState,"stopped");break;case chrome.cast.media.PlayerState.PAUSED:{this.handleRemotePause();break}case chrome.cast.media.PlayerState.PLAYING:this.handleRemotePlay();break;case chrome.cast.media.PlayerState.BUFFERING:break;default:ar(n)}}),t(Si(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t(Si(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({muted:r.value})});let i=Yg(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,BL(["init"])).pipe(Qg(0));t(i,this.syncPlayback)}restoreSession(e){this.log({message:"restoreSession"});let{remotePlayer:t}=this.params.connection;if(e.playerState!==chrome.cast.media.PlayerState.IDLE){t.isPaused?(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),P(this.params.desiredState.playbackState,"playing"));let i=this.params.output.isLive$.getValue();this.params.output.duration$.next(i?0:t.duration),this.params.output.position$.next(i?0:t.currentTime),this.params.desiredState.seekState.setState({state:"none"})}}prepare(){let e=this.params.format;this.log({message:`[prepare] format: ${e}`});let t=this.createMediaInfo(e),i=this.createLoadRequest(t);this.loadMedia(i)}handleRemotePause(){let e=this.videoState.getState();(this.videoState.getTransition()?.to==="paused"||e==="playing")&&(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused"))}handleRemotePlay(){let e=this.videoState.getState();(this.videoState.getTransition()?.to==="playing"||e==="paused")&&(this.videoState.setState("playing"),P(this.params.desiredState.playbackState,"playing"))}handleRemoteReady(){this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.params.desiredState.playbackState.getTransition()?.to==="ready"&&P(this.params.desiredState.playbackState,"ready")}handleRemoteStop(){this.videoState.getState()!=="stopped"&&this.videoState.setState("stopped")}handleRemoteVolumeChange(e){let t=this.params.output.volume$.getValue(),i={volume:e.volume??t.volume,muted:e.muted??t.muted};(i.volume!==t.volume||i.muted!==i.muted)&&this.params.output.volume$.next(i)}seek(e){this.params.output.willSeekEvent$.next();let{remotePlayer:t,remotePlayerController:i}=this.params.connection;t.currentTime=e,i.seek()}stop(){let{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){let t=this.params.source,i,r,s;switch(e){case"MPEG":{let l=t[e];gi(l);let d=OL(Object.keys(l));gi(d);let h=l[d];gi(h),i=h,r="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_FMP4":case"HLS_ONDEMAND":{let l=t[e];gi(l),i=l.url,r="application/x-mpegurl",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":{let l=t[e];gi(l),i=l.url,r="application/dash+xml",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let l=t[e];gi(l),i=l.url,r="application/dash+xml",s=chrome.cast.media.StreamType.LIVE;break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let l=t[e];gi(l),i=se(l.url),r="application/x-mpegurl",s=chrome.cast.media.StreamType.LIVE;break}case"DASH_LIVE":case"WEB_RTC_LIVE":{let l="Unsupported format for Chromecast",d=new Error(l);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:Gg.VIDEO_PIPELINE,message:l,thrown:d}),d}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return ar(e)}let n=new chrome.cast.media.MediaInfo(this.params.meta.videoId??i,r);n.contentUrl=i,n.streamType=s,n.metadata=new chrome.cast.media.GenericMediaMetadata;let{title:u,subtitle:o}=this.params.meta;return Wg(u)&&(n.metadata.title=u),Wg(o)&&(n.metadata.subtitle=o),n}createLoadRequest(e){let t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;let i=this.params.desiredState.seekState.getState();return i.state==="applying"||i.state==="requested"?t.currentTime=this.params.output.isLive$.getValue()?0:i.position/1e3:t.currentTime=0,t}loadMedia(e){let t=this.params.connection.session.loadMedia(e),i=new Promise((r,s)=>{this.loadMediaTimeoutSubscription.add(_L(Kg).subscribe(()=>s(`timeout(${Kg})`)))});(0,Xg.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:Gg.VIDEO_PIPELINE,message:s,thrown:r})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var bc=C(Ee(),1);import{clearVideoElement as Zg}from"@vkontakte/videoplayer-shared";import{clearVideoElement as UL}from"@vkontakte/videoplayer-shared";var Jg=a=>{try{a.pause(),a.playbackRate=0,UL(a),a.remove()}catch(e){console.error(e)}};import{fromEvent as jL,Subscription as HL}from"@vkontakte/videoplayer-shared";var Jl=class{constructor(){this.attribute="data-pool-reused"}get(e){return e.hasAttribute(this.attribute)}set(e,t){e.toggleAttribute(this.attribute,t)}delete(e){e.removeAttribute(this.attribute)}},Zl=window.WeakMap?new WeakMap:new Jl,ec=window.WeakMap?new WeakMap:new Map,QL=(a,e=20)=>{let t=0;return jL(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?Zg(i):(i=document.createElement("video"),a.appendChild(i)),Zl.set(i,r);let s=new HL;return s.add(QL(i,e)),ec.set(i,s),i.setAttribute("crossorigin","anonymous"),i.setAttribute("playsinline","playsinline"),t&&i.setAttribute("x-yandex-pip","false"),i.controls=!1,i.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),i},Ce=a=>{ec.get(a)?.unsubscribe(),ec.delete(a);let t=Zl.get(a);Zl.delete(a),t?Zg(a):Jg(a)};var ic=C(sr(),1);import{assertNonNullable as pa,isNonNullable as bt,isNullable as ZL,fromEvent as nr,merge as nS,observableFrom as oS,filterChanged as uS,map as ha,Subject as lS,Subscription as e$,ValueSubject as t$,ErrorCategory as i$}from"@vkontakte/videoplayer-shared";import{isNonNullable as tc,isNullable as XL,Subscription as JL}from"@vkontakte/videoplayer-shared";var Dn=(a,e,t,{equal:i=(n,u)=>n===u,changed$:r,onError:s}={})=>{let n=a.getState(),u=e(),o=XL(r),l=new JL;return r&&l.add(r.subscribe(d=>{let h=a.getState();i(d,h)&&a.setState(d)},s)),i(u,n)||(t(n),o&&a.setState(n)),l.add(a.stateChangeStarted$.subscribe(d=>{t(d.to),o&&a.setState(d.to)},s)),l},mt=(a,e,t)=>Dn(e,()=>a.loop,i=>{tc(i)&&(a.loop=i)},{onError:t}),Be=(a,e,t,i)=>Dn(e,()=>({muted:a.muted,volume:a.volume}),r=>{tc(r)&&(a.muted=r.muted,a.volume=r.volume)},{equal:(r,s)=>r===s||r?.muted===s?.muted&&r?.volume===s?.volume,changed$:t,onError:i}),ze=(a,e,t,i)=>Dn(e,()=>a.playbackRate,r=>{tc(r)&&(a.playbackRate=r)},{changed$:t,onError:i}),da=Dn;var r$=a=>["__",a.language,a.label].join("|"),a$=(a,e)=>{if(a.id===e)return!0;let[t,i,r]=e.split("|");return a.language===i&&a.label===r},rc=class a{constructor(e){this.available$=new lS;this.current$=new t$(void 0);this.error$=new lS;this.subscription=new e$;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:i$.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:s})};this.subscription.add(this.available$.subscribe(i.availableTextTracks$)),this.subscription.add(this.current$.subscribe(i.currentTextTrack$)),this.subscription.add(this.error$.subscribe(i.error$)),this.subscription.add(da(t.internalTextTracks,()=>(0,ic.default)(this.internalTracks),s=>{bt(s)&&this.setInternal(s)},{equal:(s,n)=>bt(s)&&bt(n)&&s.length===n.length&&s.every(({id:u},o)=>u===n[o].id),changed$:this.available$.pipe(ha(s=>s.filter(({type:n})=>n==="internal"))),onError:r})),this.subscription.add(da(t.externalTextTracks,()=>(0,ic.default)(this.externalTracks),s=>{bt(s)&&this.setExternal(s)},{equal:(s,n)=>bt(s)&&bt(n)&&s.length===n.length&&s.every(({id:u},o)=>u===n[o].id),changed$:this.available$.pipe(ha(s=>s.filter(({type:n})=>n==="external"))),onError:r})),this.subscription.add(da(t.currentTextTrack,()=>{if(this.video)return;let s=this.htmlTextTracksAsArray().find(({mode:n})=>n==="showing");return s&&this.htmlTextTrackToITextTrack(s).id},s=>this.select(s),{changed$:this.current$,onError:r})),this.subscription.add(da(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.activeCues)}))}subscribe(){pa(this.video);let{textTracks:e}=this.video;this.subscription.add(nr(e,"addtrack").subscribe(()=>{let i=this.current$.getValue();i&&this.select(i)})),this.subscription.add(nS(nr(e,"addtrack"),nr(e,"removetrack"),oS(["init"])).pipe(ha(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),uS((i,r)=>i.length===r.length&&i.every(({id:s},n)=>s===r[n].id))).subscribe(this.available$)),this.subscription.add(nS(nr(e,"change"),oS(["init"])).pipe(ha(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),ha(i=>i&&this.htmlTextTrackToITextTrack(i).id),uS()).subscribe(this.current$));let t=i=>this.applyCueSettings(i.target?.activeCues??null);this.subscription.add(nr(e,"addtrack").subscribe(i=>{i.track?.addEventListener("cuechange",t);let r=s=>{let n=s.target?.cues??null;n&&n.length&&(this.applyCueSettings(s.target?.cues??null),s.target?.removeEventListener("cuechange",r))};i.track?.addEventListener("cuechange",r)})),this.subscription.add(nr(e,"removetrack").subscribe(i=>{i.track?.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;let t=this.cueSettings.getState();for(let i of Array.from(e)){let r=i;bt(t.align)&&(r.align=t.align),bt(t.position)&&(r.position=t.position),bt(t.size)&&(r.size=t.size),bt(t.line)&&(r.line=t.line)}}htmlTextTracksAsArray(e=!1){pa(this.video);let t=[...this.video.textTracks];return e?t:t.filter(a.isHealthyTrack)}htmlTextTrackToITextTrack(e){let{language:t,label:i}=e,r=e.id?e.id:r$(e),s=this.externalTracks.has(r),n=(s?this.externalTracks.get(r)?.isAuto:this.internalTracks.get(r)?.isAuto)??r.includes("auto");return s?{id:r,type:"external",isAuto:n,language:t,label:i,url:this.externalTracks.get(r)?.url}:{id:r,type:"internal",isAuto:n,language:t,label:i,url:this.internalTracks.get(r)?.url}}static isHealthyTrack(e){return!(e.kind==="metadata"||e.groupId||e.id===""&&e.label===""&&e.language==="")}setExternal(e){this.internalTracks.size>0&&Array.from(this.internalTracks).forEach(([,t])=>this.detach(t)),e.filter(({id:t})=>!this.externalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.externalTracks).filter(([t])=>!e.find(i=>i.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){let t=[...this.externalTracks];e.filter(({id:i,language:r,isAuto:s})=>!this.internalTracks.has(i)&&!t.some(([,n])=>n.language===r&&n.isAuto===s)).forEach(i=>this.attach(i)),Array.from(this.internalTracks).filter(([i])=>!e.find(r=>r.id===i)).forEach(([,i])=>this.detach(i))}select(e){pa(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(ZL(e)||!a$(t,e))&&(t.mode="disabled")}destroy(){if(this.subscription.unsubscribe(),this.video)for(let e of Array.from(this.video.getElementsByTagName("track"))){let t=e.getAttribute("id");t&&this.externalTracks.has(t)&&this.video.removeChild(e)}this.externalTracks.clear()}attach(e){pa(this.video);let t=document.createElement("track");this.baseURL?t.setAttribute("src",new URL(e.url,this.baseURL).toString()):t.setAttribute("src",e.url),t.setAttribute("id",e.id),e.label&&t.setAttribute("label",e.label),e.language&&t.setAttribute("srclang",e.language),e.type==="external"?this.externalTracks.set(e.id,e):e.type==="internal"&&this.internalTracks.set(e.id,e),this.video.appendChild(t)}detach(e){pa(this.video);let t=Array.prototype.find.call(this.video.getElementsByTagName("track"),i=>i.getAttribute("id")===e.id);t&&this.video.removeChild(t),e.type==="external"?this.externalTracks.delete(e.id):e.type==="internal"&&this.internalTracks.delete(e.id)}},Ye=rc;var vi=class{constructor(){this.pausedTime=0;this.streamOffset=0;this.pauseTimestamp=0}getTotalPausedTime(){return this.pausedTime+this.getCurrentPausedTime()}getCurrentPausedTime(){return this.pauseTimestamp>0?Date.now()-this.pauseTimestamp:0}getStreamOffset(){return this.streamOffset}getTotalOffset(){return this.getTotalPausedTime()+this.streamOffset}pause(){this.pauseTimestamp===0&&(this.pauseTimestamp=Date.now())}resume(){this.pauseTimestamp>0&&(this.pausedTime+=this.getCurrentPausedTime(),this.pauseTimestamp=0)}resetTo(e,t=!1){this.streamOffset=e,this.pauseTimestamp=0,this.pausedTime=0,t&&this.pause()}};var cS=a=>{let e=a;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e?.parentNode;return e??void 0},ac=a=>{let e=cS(a);return!!(e&&e.fullscreenElement&&e.fullscreenElement===a)},dS=a=>{let e=cS(a);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===a)};import{fromEvent as xe,map as gt,merge as Cn,filterChanged as hS,isNonNullable as fS,Subject as n$,filter as sc,mapTo as nc,combine as o$,once as u$,shareReplay as we,throttle as l$,ErrorCategory as c$,ValueSubject as mS,Subscription as d$}from"@vkontakte/videoplayer-shared";var s$=3,pS=(a,e,t=s$)=>{let i=0,r=0;for(let s=0;s<a.length;s++){let n=a.start(s),u=a.end(s);if(n<=e&&e<=u){if(i=n,r=u,!t)return{from:i,to:r};for(let o=s-1;o>=0;o--)a.end(o)+t>=i&&(i=a.start(o));for(let o=s+1;o<a.length;o++)a.start(o)-t<=r&&(r=a.end(o))}}return{from:i,to:r}};var Ve=a=>{let e=I=>xe(a,I).pipe(nc(void 0),we(1)),t=new d$,i=()=>t.unsubscribe(),r=Cn(xe(a,"progress"),xe(a,"timeupdate")).pipe(gt(()=>pS(a.buffered,a.currentTime)),we(1)),s=B.browser.isSafari?o$({play:e("play").pipe(u$()),playing:e("playing")}).pipe(nc(void 0),we(1)):e("playing"),n=xe(a,"volumechange").pipe(gt(()=>({muted:a.muted,volume:a.volume})),we(1)),u=xe(a,"ratechange").pipe(gt(()=>a.playbackRate),we(1)),o=xe(a,"error").pipe(sc(()=>!!(a.error||a.played.length)),gt(()=>{let I=a.error;return{id:I?`MediaError#${I.code}`:"HtmlVideoError",category:c$.VIDEO_PIPELINE,message:I?I.message:"Error event from HTML video element",thrown:a.error??void 0}}),we(1)),l=xe(a,"timeupdate").pipe(gt(()=>a.currentTime),we(1)),d=["waiting","seeking","seeked","timeupdate"],h=new n$,c=.3,p;t.add(Cn(...d.map(I=>xe(a,I))).subscribe(I=>{let q=a.currentTime;a.loop&&fS(p)&&fS(q)&&p>=a.duration-c&&q<=c&&h.next(p),p=q}));let f=e("pause").pipe(sc(()=>!a.error&&p!==a.duration),we(1)),b=xe(a,"enterpictureinpicture").pipe(we(1)),S=xe(a,"leavepictureinpicture").pipe(we(1)),g=new mS(dS(a));t.add(b.subscribe(()=>g.next(!0))),t.add(S.subscribe(()=>g.next(!1)));let T=new mS(ac(a)),E=xe(a,"fullscreenchange").pipe(we(1));t.add(E.pipe(gt(()=>ac(a))).subscribe(T));let y=.1,w=1e3,k=xe(a,"timeupdate").pipe(gt(I=>a.duration-a.currentTime<y),hS(),we(1)),$=Cn(k.pipe(sc(I=>!a.loop&&I)),xe(a,"ended")).pipe(l$(w),nc(void 0),we(1)),L=Cn(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(I=>xe(a,I)),k.pipe(gt(I=>({type:I?"ended":"unknown"})))).pipe(gt(I=>B.browser.isFirefox&&I.type==="ended"?a.readyState<2:a.readyState<3),hS(),we(1));return{playing$:s,pause$:f,canplay$:e("canplay"),ended$:$,looped$:h,error$:o,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:l,durationChange$:xe(a,"durationchange").pipe(gt(()=>a.duration),we(1)),isBuffering$:L,currentBuffer$:r,volumeState$:n,playbackRateState$:u,inPiP$:g,inFullscreen$:T,enterPip$:b,leavePip$:S,destroy:i}};import{VideoQuality as jt}from"@vkontakte/videoplayer-shared";var Ht=a=>{switch(a){case"mobile":return jt.Q_144P;case"lowest":return jt.Q_240P;case"low":return jt.Q_360P;case"sd":case"medium":return jt.Q_480P;case"hd":case"high":return jt.Q_720P;case"fullhd":case"full":return jt.Q_1080P;case"quadhd":case"quad":return jt.Q_1440P;case"ultrahd":case"ultra":return jt.Q_2160P}};var Pe=C(at(),1),lc=C(Ee(),1),yi=C(Wi(),1);import{isNonNullable as K,isNullable as Fn,now as $S,isHigher as Nn,isHigherOrEqual as ur,isInvariantQuality as qn,isLowerOrEqual as lr,videoSizeToQuality as MS,assertNotEmptyArray as Un,assertNonNullable as DS}from"@vkontakte/videoplayer-shared";var oc=!1,Rt={},IS=a=>{oc=a},ES=()=>{Rt={}},xS=a=>{a(Rt)},fa=(a,e)=>{oc&&(Rt.meta=Rt.meta??{},Rt.meta[a]=e)},Ae=class{constructor(e){this.name=e}next(e){if(!oc)return;Rt.series=Rt.series??{};let t=Rt.series[this.name]??[];t.push([Date.now(),e]),Rt.series[this.name]=t}};import{isHigher as y$,isHigherOrEqual as aq,isLower as wS,isLowerOrEqual as sq,isNonNullable as Bn,isNullable as T$,videoHeightToQuality as Vn}from"@vkontakte/videoplayer-shared";function uc(a,e,t){return!a.max&&a.min===e?"high_quality":!a.min&&a.max===t?"traffic_saving":"unknown"}function _n(a,e,t){return!!a&&uc(a,e,t)==="high_quality"}function or(a,e,t){return T$(a)||Bn(a.min)&&Bn(a.max)&&wS(a.max,a.min)||Bn(a.min)&&e&&y$(a.min,e)||Bn(a.max)&&t&&wS(a.max,t)}function AS({limits:a,highestAvailableHeight:e,lowestAvailableHeight:t}){return or({max:a?.max?Vn(a.max):void 0,min:a?.min?Vn(a.min):void 0},e?Vn(e):void 0,t?Vn(t):void 0)}var CS=new Ae("best_bitrate"),jn=(a,e,t)=>(e-t)*Math.pow(2,-10*a)+t;var cr=a=>(e,t)=>a*(Number(e.bitrate)-Number(t.bitrate)),Qt=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=$S()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},Hn='Assertion "ABR Tracks is empty array" failed',On=new WeakMap,PS=new WeakMap,RS=new WeakMap,ma=(a,e,t,i)=>{let r=[...e].sort(cr(1)),s=[...t].sort(cr(1)),n=s.filter(o=>K(o.bitrate)&&K(a.bitrate)?a.bitrate/o.bitrate>i:!0),u=(0,Pe.default)(s,Math.round(s.length*r.indexOf(a)/(r.length+1)))??(0,Pe.default)(s,-1);return u&&(0,lc.default)(n,u)?u:n.length?(0,Pe.default)(n,-1):(0,Pe.default)(s,0)},ba=(a,e,t,i)=>{let r=On.get(e);r||(r=[...e].sort(cr(1)),On.set(e,r));let s=On.get(t);s||(s=[...t].sort(cr(1)),On.set(t,s));let n=RS.get(a);n||(n=s.filter(o=>K(o.bitrate)&&K(a.bitrate)?a.bitrate/o.bitrate>i:!0),RS.set(a,n));let u=(0,Pe.default)(s,Math.round(s.length*r.indexOf(a)/(r.length+1)))??(0,Pe.default)(s,-1);return u&&(0,lc.default)(n,u)?u:n.length?(0,Pe.default)(n,-1):(0,Pe.default)(s,0)},kS=a=>"quality"in a,Qn=(a,e,t,i)=>{let r=K(i?.last?.bitrate)&&K(t?.bitrate)&&i.last.bitrate<t.bitrate?a.trackCooldownIncreaseQuality:a.trackCooldownDecreaseQuality,s=t&&i&&i.history[t.id]&&$S()-i.history[t.id]<=r&&(!i.last||t.id!==i.last.id);if(t?.id&&i&&!s&&i.recordSelection(t),s&&i?.last){let n=i.last;i?.recordSwitch(n);let u=kS(n)?"video":"audio",o=kS(n)?n.quality:n.bitrate;return e({message:`
|
|
8
8
|
[last ${u} selected] ${o}
|
|
9
|
-
`}),n}return i?.recordSwitch(t),t},I$=(a,e)=>Math.log(e)/Math.log(a),
|
|
9
|
+
`}),n}return i?.recordSwitch(t),t},I$=(a,e)=>Math.log(e)/Math.log(a),BS=({tuning:a,container:e,limits:t,panelSize:i})=>{let r=a.containerSizeFactor;if(i)return{containerSizeLimit:i,containerSizeFactor:r};if(a.usePixelRatio&&B.display.pixelRatio){let s=B.display.pixelRatio;if(a.pixelRatioMultiplier)r*=a.pixelRatioMultiplier*(s-1)+1;else{let n=a.pixelRatioLogBase,[u=0,o=0,l=0]=a.pixelRatioLogCoefficients,d=I$(n,u*s+o)+l;Number.isFinite(d)&&(r*=d)}}return _n(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}},LS=new WeakMap,St=(a,{container:e,estimatedThroughput:t,tuning:i,limits:r,reserve:s=0,forwardBufferHealth:n,playbackRate:u,current:o,history:l,visible:d,droppedVideoMaxQualityLimit:h,stallsVideoMaxQualityLimit:c,stallsPredictedThroughput:p,abrLogger:f,panelSize:b})=>{Un(a,Hn);let{containerSizeFactor:S,containerSizeLimit:g}=BS({container:e,tuning:i,limits:r,panelSize:b}),T=i.considerPlaybackRate&&K(u)?u:1,E=LS.get(a);E||(E=a.filter(v=>!qn(v.quality)).sort((v,x)=>Nn(v.quality,x.quality)?-1:1),LS.set(a,E));let y=(0,Pe.default)(E,-1)?.quality,w=(0,Pe.default)(E,0)?.quality,k=or(r,w,y),$=T*jn(n??.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),A={},L=null;for(let v of E){let x=!0;if(g)if(v.size)x=v.size.width<=g.width&&v.size.height<=g.height;else{let H=g&&MS(g);x=H?lr(v.quality,H):!0}if(!x){A[v.quality]="FitsContainer";continue}let z=p||t,D=K(z)&&isFinite(z)&&K(v.bitrate)?z-s>=v.bitrate*$:!0,j=_n(r,i.highQualityLimit,i.trafficSavingLimit)&&r?.min===v.quality;if(!D&&!j){A[v.quality]="FitsThroughput";continue}if(i.lazyQualitySwitch&&K(i.minBufferToSwitchUp)&&o&&!qn(o.quality)&&(n??0)<i.minBufferToSwitchUp&&Nn(v.quality,o.quality)){A[v.quality]="Buffer";continue}if(!!h&&ur(v.quality,h)&&!j){A[v.quality]="DroppedFramesLimit";continue}if(!!c&&ur(v.quality,c)&&!j){A[v.quality]="StallsLimit";continue}let me=k||(Fn(r?.max)||lr(v.quality,r.max))&&(Fn(r?.min)||ur(v.quality,r.min)),be=K(d)&&!d?lr(v.quality,i.backgroundVideoQualityLimit):!0;if(!me||!be){A[v.quality]="FitsQualityLimits";continue}L||(L=v)}L&&L.bitrate&&CS.next(L.bitrate);let I=L??(0,Pe.default)(E,-1)??a[0],q=l?.last,M=Qn(i,f,I,l);return K(l)&&M.quality!==q?.quality&&f({message:`
|
|
10
10
|
[VIDEO TRACKS ABR]
|
|
11
11
|
[available video tracks]
|
|
12
12
|
${a.map(v=>`{ id: ${v.id}, quality: ${v.quality}, bitrate: ${v.bitrate}, size: ${v.size?.width}:${v.size?.height} }`).join(`
|
|
13
13
|
`)}
|
|
14
14
|
|
|
15
15
|
[tuning]
|
|
16
|
-
${(0,
|
|
16
|
+
${(0,yi.default)(i??{}).map(([v,x])=>`${v}: ${x}`).join(`
|
|
17
17
|
`)}
|
|
18
18
|
|
|
19
19
|
[limit params]
|
|
20
20
|
containerSizeFactor: ${S},
|
|
21
21
|
containerSizeLimit: ${g?.width??0} x ${g?.height??0},
|
|
22
22
|
estimatedThroughput: ${t},
|
|
23
|
-
stallsPredictedThroughput: ${
|
|
23
|
+
stallsPredictedThroughput: ${p},
|
|
24
24
|
reserve: ${s},
|
|
25
25
|
playbackRate: ${u},
|
|
26
|
-
playbackRateFactor: ${
|
|
26
|
+
playbackRateFactor: ${T},
|
|
27
27
|
forwardBufferHealth: ${n},
|
|
28
|
-
bitrateFactor: ${
|
|
28
|
+
bitrateFactor: ${$},
|
|
29
29
|
minBufferToSwitchUp: ${i.minBufferToSwitchUp},
|
|
30
|
-
droppedVideoMaxQualityLimit: ${
|
|
31
|
-
stallsVideoMaxQualityLimit: ${
|
|
32
|
-
limitsAreInvalid: ${
|
|
30
|
+
droppedVideoMaxQualityLimit: ${h},
|
|
31
|
+
stallsVideoMaxQualityLimit: ${c},
|
|
32
|
+
limitsAreInvalid: ${k},
|
|
33
33
|
maxQualityLimit: ${r?.max},
|
|
34
34
|
minQualityLimit: ${r?.min},
|
|
35
35
|
|
|
36
36
|
[limited video tracks]
|
|
37
|
-
${(0,
|
|
37
|
+
${(0,yi.default)(A).map(([v,x])=>`${v}: ${x}`).join(`
|
|
38
38
|
`)||"All tracks are available"}
|
|
39
39
|
|
|
40
|
-
[best video track] ${
|
|
41
|
-
[selected video track] ${
|
|
42
|
-
`})
|
|
40
|
+
[best video track] ${L?.quality}
|
|
41
|
+
[selected video track] ${M?.quality}
|
|
42
|
+
`}),M},Gn=(a,{container:e,estimatedThroughput:t,tuning:i,limits:r,reserve:s=0,forwardBufferHealth:n,playbackRate:u,current:o,history:l,visible:d,droppedVideoMaxQualityLimit:h,stallsVideoMaxQualityLimit:c,stallsPredictedThroughput:p,abrLogger:f,panelSize:b})=>{Un(a,Hn);let{containerSizeFactor:S,containerSizeLimit:g}=BS({container:e,tuning:i,limits:r,panelSize:b}),T=i.considerPlaybackRate&&K(u)?u:1,E=a.filter(x=>!qn(x.quality)).sort((x,z)=>Nn(x.quality,z.quality)?-1:1),y=(0,Pe.default)(E,-1)?.quality,w=(0,Pe.default)(E,0)?.quality,k=or(r,w,y),$=T*jn(n??.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),A={},I=E.filter(x=>{let z=!0;if(g)if(x.size)z=x.size.width<=g.width&&x.size.height<=g.height;else{let U=g&&MS(g);z=U?lr(x.quality,U):!0}if(!z)return A[x.quality]="FitsContainer",!1;let D=p||t,j=K(D)&&isFinite(D)&&K(x.bitrate)?D-s>=x.bitrate*$:!0,J=_n(r,i.highQualityLimit,i.trafficSavingLimit)&&r?.min===x.quality;if(!j&&!J)return A[x.quality]="FitsThroughput",!1;if(i.lazyQualitySwitch&&K(i.minBufferToSwitchUp)&&o&&!qn(o.quality)&&(n??0)<i.minBufferToSwitchUp&&Nn(x.quality,o.quality))return A[x.quality]="Buffer",!1;if(!!h&&ur(x.quality,h)&&!J)return A[x.quality]="DroppedFramesLimit",!1;if(!!c&&ur(x.quality,c)&&!J)return A[x.quality]="StallsLimit",!1;let be=k||(Fn(r?.max)||lr(x.quality,r.max))&&(Fn(r?.min)||ur(x.quality,r.min)),H=K(d)&&!d?lr(x.quality,i.backgroundVideoQualityLimit):!0;return!be||!H?(A[x.quality]="FitsQualityLimits",!1):!0})[0];I&&I.bitrate&&CS.next(I.bitrate);let q=I??(0,Pe.default)(E,-1)??a[0],M=l?.last,v=Qn(i,f,q,l);return K(l)&&v.quality!==M?.quality&&f({message:`
|
|
43
43
|
[VIDEO TRACKS ABR]
|
|
44
44
|
[available video tracks]
|
|
45
|
-
${a.map(
|
|
45
|
+
${a.map(x=>`{ id: ${x.id}, quality: ${x.quality}, bitrate: ${x.bitrate}, size: ${x.size?.width}:${x.size?.height} }`).join(`
|
|
46
46
|
`)}
|
|
47
47
|
|
|
48
48
|
[tuning]
|
|
49
|
-
${(0,
|
|
49
|
+
${(0,yi.default)(i??{}).map(([x,z])=>`${x}: ${z}`).join(`
|
|
50
50
|
`)}
|
|
51
51
|
|
|
52
52
|
[limit params]
|
|
53
53
|
containerSizeFactor: ${S},
|
|
54
54
|
containerSizeLimit: ${g?.width??0} x ${g?.height??0},
|
|
55
55
|
estimatedThroughput: ${t},
|
|
56
|
-
stallsPredictedThroughput: ${
|
|
56
|
+
stallsPredictedThroughput: ${p},
|
|
57
57
|
reserve: ${s},
|
|
58
58
|
playbackRate: ${u},
|
|
59
|
-
playbackRateFactor: ${
|
|
59
|
+
playbackRateFactor: ${T},
|
|
60
60
|
forwardBufferHealth: ${n},
|
|
61
|
-
bitrateFactor: ${
|
|
61
|
+
bitrateFactor: ${$},
|
|
62
62
|
minBufferToSwitchUp: ${i.minBufferToSwitchUp},
|
|
63
|
-
droppedVideoMaxQualityLimit: ${
|
|
64
|
-
stallsVideoMaxQualityLimit: ${
|
|
65
|
-
limitsAreInvalid: ${
|
|
63
|
+
droppedVideoMaxQualityLimit: ${h},
|
|
64
|
+
stallsVideoMaxQualityLimit: ${c},
|
|
65
|
+
limitsAreInvalid: ${k},
|
|
66
66
|
maxQualityLimit: ${r?.max},
|
|
67
67
|
minQualityLimit: ${r?.min},
|
|
68
68
|
|
|
69
69
|
[limited video tracks]
|
|
70
|
-
${(0,
|
|
70
|
+
${(0,yi.default)(A).map(([x,z])=>`${x}: ${z}`).join(`
|
|
71
71
|
`)||"All tracks are available"}
|
|
72
72
|
|
|
73
|
-
[best video track] ${
|
|
73
|
+
[best video track] ${I?.quality}
|
|
74
74
|
[selected video track] ${v?.quality}
|
|
75
|
-
`}),v},
|
|
75
|
+
`}),v},Wn=(a,e,t,{estimatedThroughput:i,tuning:r,playbackRate:s,forwardBufferHealth:n,history:u,abrLogger:o,stallsPredictedThroughput:l})=>{Un(t,Hn);let d=r.considerPlaybackRate&&K(s)?s:1,h=[...t].sort(cr(-1)),c=a.bitrate;DS(c);let p=d*jn(n??.5,r.bitrateAudioFactorAtEmptyBuffer,r.bitrateAudioFactorAtFullBuffer),f,b=ma(a,e,t,r.minVideoAudioRatio),S=l||i;K(S)&&isFinite(S)&&(f=h.find(E=>K(E.bitrate)&&K(b?.bitrate)?S-c>=E.bitrate*p&&E.bitrate>=b.bitrate:!1)),f||(f=b);let g=u?.last,T=f&&Qn(r,o,f,u);return K(u)&&T?.bitrate!==g?.bitrate&&o({message:`
|
|
76
76
|
[AUDIO TRACKS ABR]
|
|
77
77
|
[available audio tracks]
|
|
78
|
-
${t.map(
|
|
78
|
+
${t.map(E=>`{ id: ${E.id}, bitrate: ${E.bitrate} }`).join(`
|
|
79
79
|
`)}
|
|
80
80
|
|
|
81
81
|
[tuning]
|
|
82
|
-
${(0,
|
|
82
|
+
${(0,yi.default)(r??{}).map(([E,y])=>`${E}: ${y}`).join(`
|
|
83
83
|
`)}
|
|
84
84
|
|
|
85
85
|
[limit params]
|
|
86
86
|
estimatedThroughput: ${i},
|
|
87
87
|
stallsPredictedThroughput: ${l},
|
|
88
|
-
reserve: ${
|
|
88
|
+
reserve: ${c},
|
|
89
89
|
playbackRate: ${s},
|
|
90
|
-
playbackRateFactor: ${
|
|
90
|
+
playbackRateFactor: ${d},
|
|
91
91
|
forwardBufferHealth: ${n},
|
|
92
|
-
bitrateFactor: ${
|
|
92
|
+
bitrateFactor: ${p},
|
|
93
93
|
minBufferToSwitchUp: ${r.minBufferToSwitchUp},
|
|
94
94
|
|
|
95
|
-
[selected audio track] ${
|
|
96
|
-
`}),
|
|
95
|
+
[selected audio track] ${T?.id}
|
|
96
|
+
`}),T},zn=(a,e,t,{estimatedThroughput:i,tuning:r,playbackRate:s,forwardBufferHealth:n,history:u,abrLogger:o,stallsPredictedThroughput:l})=>{Un(t,Hn);let d=r.considerPlaybackRate&&K(s)?s:1,h=PS.get(t);h||(h=[...t].sort(cr(-1)),PS.set(t,h));let c=a.bitrate;DS(c);let p=d*jn(n??.5,r.bitrateAudioFactorAtEmptyBuffer,r.bitrateAudioFactorAtFullBuffer),f,b=ba(a,e,t,r.minVideoAudioRatio),S=l||i;K(S)&&isFinite(S)&&(f=h.find(E=>K(E.bitrate)&&K(b?.bitrate)?S-c>=E.bitrate*p&&E.bitrate>=b.bitrate:!1)),f||(f=b);let g=u?.last,T=f&&Qn(r,o,f,u);return K(u)&&T?.bitrate!==g?.bitrate&&o({message:`
|
|
97
97
|
[AUDIO TRACKS ABR]
|
|
98
98
|
[available audio tracks]
|
|
99
|
-
${t.map(
|
|
99
|
+
${t.map(E=>`{ id: ${E.id}, bitrate: ${E.bitrate} }`).join(`
|
|
100
100
|
`)}
|
|
101
101
|
|
|
102
102
|
[tuning]
|
|
103
|
-
${(0,
|
|
103
|
+
${(0,yi.default)(r??{}).map(([E,y])=>`${E}: ${y}`).join(`
|
|
104
104
|
`)}
|
|
105
105
|
|
|
106
106
|
[limit params]
|
|
107
107
|
estimatedThroughput: ${i},
|
|
108
108
|
stallsPredictedThroughput: ${l},
|
|
109
|
-
reserve: ${
|
|
109
|
+
reserve: ${c},
|
|
110
110
|
playbackRate: ${s},
|
|
111
|
-
playbackRateFactor: ${
|
|
111
|
+
playbackRateFactor: ${d},
|
|
112
112
|
forwardBufferHealth: ${n},
|
|
113
|
-
bitrateFactor: ${
|
|
113
|
+
bitrateFactor: ${p},
|
|
114
114
|
minBufferToSwitchUp: ${r.minBufferToSwitchUp},
|
|
115
115
|
|
|
116
|
-
[selected audio track] ${
|
|
117
|
-
`}),I};var ge=a=>new URL(a).hostname;import{assertNever as jS,assertNonNullable as QS,combine as H$,debounce as j$,ErrorCategory as WS,filter as GS,filterChanged as Q$,isNonNullable as uc,map as jn,merge as zS,observableFrom as W$,once as G$,Subscription as z$,ValueSubject as lc,videoQualityToHeight as YS,videoSizeToQuality as Y$}from"@vkontakte/videoplayer-shared";var NS=C(at(),1);var BS=C(Ee(),1),CS=a=>{if(a instanceof DOMException&&(0,BS.default)(["Failed to load because no supported source was found.","The element has no supported sources."],a.message))throw a;return!(a instanceof DOMException&&(a.code===20||a.name==="AbortError"))},Be=async(a,e)=>{let t=a.muted;try{await a.play()}catch(i){if(!CS(i))return!1;if(e&&e(),t)return console.warn(i),!1;a.muted=!0;try{await a.play()}catch(r){return CS(r)&&(a.muted=!1,console.warn(r)),!1}}return!0};import{isNonNullable as Un,isNullable as w$,assertNonNullable as va}from"@vkontakte/videoplayer-shared";var _S=C(rr(),1);import{isNonNullable as VS,assertNonNullable as qn,now as E$}from"@vkontakte/videoplayer-shared";function pe(){return E$()}function ac(a){return pe()-a}function sc(a){let e=a.split("/"),t=e.slice(0,e.length-1).join("/"),i=/^([a-z]+:)?\/\//i,r=n=>i.test(n);return{resolve:(n,u,o=!1)=>{r(n)||(n.startsWith("/")||(n="/"+n),n=t+n);let l=n.indexOf("?")>-1?"&":"?";return o&&(n+=l+"lowLat=1",l="&"),u&&(n+=l+"_rnd="+Math.floor(999999999*Math.random())),n}}}function OS(a,e,t){let i=(...r)=>{t.apply(null,r),a.removeEventListener(e,i)};a.addEventListener(e,i)}function lr(a,e,t,i){let r=window.XMLHttpRequest,s,n,u,o=!1,l=0,c,p,d=!1,h="arraybuffer",f=7e3,b=2e3,S=()=>{if(o)return;qn(c);let $=ac(c),v;if($<b){v=b-$,setTimeout(S,v);return}b*=2,b>f&&(b=f),n&&n.abort(),n=new r,D()},g=$=>(s=$,q),I=$=>(p=$,q),x=()=>(h="json",q),y=()=>{if(!o){if(--l>=0){S(),i&&i();return}o=!0,p&&p(),t&&t()}},w=$=>(d=$,q),D=()=>{c=pe(),n=new r,n.open("get",a);let $=0,v,E=0,z=()=>(qn(c),Math.max(c,Math.max(v||0,E||0)));if(s&&n.addEventListener("progress",M=>{let H=pe();s.updateChunk&&M.loaded>$&&(s.updateChunk(z(),M.loaded-$),$=M.loaded,v=H)}),u&&(n.timeout=u,n.addEventListener("timeout",()=>y())),n.addEventListener("load",()=>{if(o)return;qn(n);let M=n.status;if(M>=200&&M<300){let{response:H,responseType:J}=n,ie=H?.byteLength;if(typeof ie=="number"&&s){let ue=ie-$;ue&&s.updateChunk&&s.updateChunk(z(),ue)}J==="json"&&(!H||!(0,_S.default)(H).length)?y():(p&&p(),e(H))}else y()}),n.addEventListener("error",()=>{y()}),d){let M=()=>{qn(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(E=pe(),n.removeEventListener("readystatechange",M))};n.addEventListener("readystatechange",M)}return n.responseType=h,n.send(),q},q={withBitrateReporting:g,withParallel:w,withJSONResponse:x,withRetryCount:$=>(l=$,q),withRetryInterval:($,v)=>(VS($)&&(b=$),VS(v)&&(f=v),q),withTimeout:$=>(u=$,q),withFinally:I,send:D,abort:()=>{n&&(n.abort(),n=void 0),o=!0,p&&p()}};return q}var ga=class{constructor(e){this.intervals=[];this.currentRate=0;this.logger=e}_updateRate(e){let t=.2;this.currentRate&&(e<this.currentRate*.1?t=.8:e<this.currentRate*.5?t=.5:e<this.currentRate*.7&&(t=.3)),e=Math.max(1,Math.min(e,100*1024*1024)),this.currentRate=this.currentRate?this.currentRate*(1-t)+e*t:e}_createInterval(e,t,i){return{start:e,end:t,bytes:i}}_doMergeIntervals(e,t){e.start=Math.min(t.start,e.start),e.end=Math.max(t.end,e.end),e.bytes+=t.bytes}_mergeIntervals(e,t){return e.start<=t.end&&t.start<=e.end?(this._doMergeIntervals(e,t),!0):!1}_flushIntervals(){if(!this.intervals.length)return!1;let e=this.intervals[0].start,t=this.intervals[this.intervals.length-1].end-500;if(t-e>2e3){let i=0,r=0;for(;this.intervals.length>0;){let s=this.intervals[0];if(s.end<=t)i+=s.end-s.start,r+=s.bytes,this.intervals.splice(0,1);else{if(s.start>=t)break;{let n=t-s.start,u=s.end-s.start;i+=n;let o=s.bytes*n/u;r+=o,s.start=t,s.bytes-=o}}}if(r>0&&i>0){let s=r*8/(i/1e3);return this._updateRate(s),this.logger(`rate updated, new=${Math.round(s/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(r)}/${Math.round(i)} interval=${Math.round(t-e)}`),!0}}return!1}_joinIntervals(){let e;do{e=!1;for(let t=0;t<this.intervals.length-1;++t)this._mergeIntervals(this.intervals[t],this.intervals[t+1])&&(this.intervals.splice(t+1,1),e=!0)}while(e)}addInterval(e,t,i){return this.intervals.push(this._createInterval(e,t,i)),this._joinIntervals(),this.intervals.length>100&&(this.logger(`too many intervals (${this.intervals.length}); will merge`,{type:"warn"}),this._doMergeIntervals(this.intervals[1],this.intervals[0]),this.intervals.splice(0,1)),this._flushIntervals()}getBitRate(){return this.currentRate}};var FS=C(rr(),1);var Sa=class{constructor(e,t,i,r,s){this.pendingQueue=[];this.activeRequests={};this.completeRequests={};this.averageSegmentDuration=2e3;this.lastPrefetchStart=0;this.throttleTimeout=null;this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=i,this.MAX_PARALLEL_REQUESTS=r,this.logger=s}limitCompleteCount(){let e;for(;(e=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){let t=e[Math.floor(Math.random()*e.length)];this.logger(`Dropping completed request for url ${t}`,{type:"warn"}),delete this.completeRequests[t]}}_sendRequest(e,t){let i=pe(),r=o=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=o,e._errorCB?e._errorCB(o):(this.limitCompleteCount(),this.completeRequests[t]=e)},s=o=>{e._complete=1,e._responseData=o,e._downloadTime=pe()-i,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(o,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},n=()=>{e._finallyCB&&e._finallyCB()},u=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=lr(t,s,()=>r("error"),u),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally(n),this.activeRequests[t]=e,e._request.send(),this.lastPrefetchStart=pe()}_getParallelRequestCount(){return Math.min(this.MAX_PARALLEL_REQUESTS,this.averageSegmentDuration<3e3?3:2)}_getPrefetchDelay(){return Math.max(100,Math.min(5e3,this.averageSegmentDuration/3))}_canSendPending(){let e=this._getParallelRequestCount(),t=pe();if(Object.keys(this.activeRequests).length>=e)return!1;let i=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),i>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),i),!1):!0}_sendPending(){for(;this._canSendPending();){let e=this.pendingQueue.pop();if(e){if(this.activeRequests[e]||this.completeRequests[e])continue;this.logger(`Submitting pending request url=${e}`),this._sendRequest({},e)}else return}}_removeFromActive(e){delete this.completeRequests[e],delete this.activeRequests[e]}abortAll(){(0,FS.default)(this.activeRequests).forEach(e=>{e&&e._request&&e._request.abort()}),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,i,r){let s={};return s.send=()=>{let n=this.activeRequests[e]||this.completeRequests[e];if(n)n._cb=t,n._errorCB=i,n._retryCB=r,n._finallyCB=s._finallyCB,n._error||n._complete?(this._removeFromActive(e),setTimeout(()=>{n._complete?(this.logger(`Requested url already prefetched, url=${e}`),t(n._responseData,n._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${e}`),i(n._errorMsg)),s._finallyCB&&s._finallyCB()},0)):this.logger(`Attached to active request, url=${e}`);else{let u=this.pendingQueue.indexOf(e);u!==-1&&this.pendingQueue.splice(u,1),this.logger(`Request not prefetched, starting new request, url=${e}${u===-1?"":"; removed pending"}`),this._sendRequest(s,e)}},s._cb=t,s._errorCB=i,s._retryCB=r,s.abort=function(){s.request&&s.request.abort()},s.withFinally=n=>(s._finallyCB=n,s),s}prefetch(e){this.activeRequests[e]||this.completeRequests[e]?this.logger(`Request already active for url=${e}`):(this.logger(`Added to pending queue; url=${e}`),this.pendingQueue.unshift(e),this._sendPending())}optimizeForSegDuration(e){this.averageSegmentDuration=e}};import{Subject as A$}from"@vkontakte/videoplayer-shared";var Hn=1e4,nc=3;var P$=6e4,k$=10,R$=1,L$=500,ya=class{constructor(e){this.paused=!1;this.autoQuality=!0;this.autoQualityLimits=void 0;this.buffering=!0;this.destroyed=!1;this.videoPlayStarted=!1;this.lowLatency=!1;this.bitrate=0;this.manifest=[];this.sourceBuffer=0;this.bufferStates=[];this.sourceJitter=-1;this.waitingForFirstBufferAfterSrcChange=!1;this.params=e,this.soundProhibitedEvent$=new A$,this.chunkRateEstimator=new ga(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=sc(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setAutoQualityLimits(e){this.autoQualityLimits=e}switchByName(e){let t;for(let i=0;i<this.manifest.length;++i)if(t=this.manifest[i],t.name===e){this._switchToQuality(t);return}}catchUp(){if(this.rep&&this.rep.stop(),this.currentManifestEntry){let e=this.params.playbackState.getState();this.paused=e==="paused",this._initPlayerWith(this.currentManifestEntry),this._notifyBuffering(!0)}}stop(){this.params.videoElement.pause(),this.rep&&(this.rep.stop(),this.rep=null)}pause(){this.paused=!0,this.params.videoElement.pause(),this.videoPlayStarted=!1,this._notifyBuffering(!1)}play(){this.paused=!1;let e=this.lowLatency&&this._getBufferSizeSec()>this.sourceJitter+5;this.rep&&!e?(this.bufferStates=[],this.videoPlayStarted=!1,this.shouldPlay()?this._playVideoElement():this._notifyBuffering(!0)):this.catchUp()}startPlay(e,t){this.autoQuality=t,this._initPlayerWith(e)}destroy(){this.destroyed=!0,this.rep&&(this.rep.stop(),this.rep=null),this.manifestRequest&&this.manifestRequest.abort(),this.manifestRefetchTimer&&(clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=void 0)}reinit(e){this.manifestUrl=e,this.urlResolver=sc(e),this.catchUp()}_handleNetworkError(){this.params.logger("Fatal network error"),this.params.playerCallback({name:"error",type:"network"})}_retryCallback(){this.params.playerCallback({name:"retry"})}_getBufferSizeSec(){let e=this.params.videoElement,t=0,i=e.buffered.length;return i!==0&&(t=e.buffered.end(i-1)-Math.max(e.currentTime,e.buffered.start(0))),t}_notifyBuffering(e){this.destroyed||(this.params.logger(`buffering: ${e}`),this.params.playerCallback({name:"buffering",isBuffering:e}),this.buffering=e)}_initVideo(){let{videoElement:e,logger:t}=this.params;e.addEventListener("error",()=>{!!e.error&&!this.destroyed&&(t(`Video element error: ${e.error?.code}, details: ${e.error?.message}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{let i=this._getBufferSizeSec();!this.paused&&i<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(i+.1)*1e3)):this.buffering&&this.videoPlayStarted&&this._notifyBuffering(!1)}),e.addEventListener("playing",()=>{t("playing")}),e.addEventListener("stalled",()=>this._fixupStall()),e.addEventListener("waiting",()=>this._fixupStall())}_fixupStall(){let{logger:e,videoElement:t}=this.params,i=t.buffered.length,r;i!==0&&!this.waitingForFirstBufferAfterSrcChange&&(r=t.buffered.start(i-1),t.currentTime<r&&(e("Fixup stall"),t.currentTime=r))}_selectQuality(e){let{videoElement:t}=this.params,i,r,s,n=t&&1.62*(B.display.pixelRatio||1)*t.offsetHeight||520;for(let u=0;u<this.manifest.length;++u){s=this.manifest[u];let{max:o,min:l}=this.autoQualityLimits||{};!xS({limits:this.autoQualityLimits,highestAvailableHeight:this.manifest[0].video.height,lowestAvailableHeight:(0,NS.default)(this.manifest,-1).video.height})&&(o&&s.video.height>o||l&&s.video.height<l)||(s.bitrate<e&&n>Math.min(s.video.height,s.video.width)?(!r||s.bitrate>r.bitrate)&&(r=s):(!i||i.bitrate>s.bitrate)&&(i=s))}return r||i}shouldPlay(){if(this.paused)return!1;let t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||Un(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){let{logger:i,videoElement:r,playerCallback:s}=this.params;this.mediaSource=new window.MediaSource,i("setting video src"),r.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.videoPlayStarted=!1,r.addEventListener("canplay",()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});let n=()=>{OS(r,"progress",()=>{r.buffered.length?(r.currentTime=r.buffered.start(0),this.waitingForFirstBufferAfterSrcChange=!1,s({name:"playing"})):n()})};this.waitingForFirstBufferAfterSrcChange=!0,n()}_initPlayerWith(e){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new Sa(nc,Hn,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){let{logger:t,videoElement:i,playerCallback:r}=this.params,s=!1,n=null,u=null,o=null,l=null,c=!1,p=()=>{let y=s&&(!c||c===this.rep);return y||t("Not running!"),y},d=(y,w,D)=>{o&&o.abort(),o=lr(this.urlResolver.resolve(y,!1),w,D,()=>this._retryCallback()).withTimeout(Hn).withBitrateReporting(this.bitrateSwitcher).withRetryCount(nc).withFinally(()=>{o=null}).send()},h=(y,w,D)=>{va(this.filesFetcher),u?.abort(),u=this.filesFetcher.requestData(this.urlResolver.resolve(y,!1),w,D,()=>this._retryCallback()).withFinally(()=>{u=null}).send()},f=y=>{let w=i.playbackRate;i.playbackRate!==y&&(t(`Playback rate switch: ${w}=>${y}`),i.playbackRate=y)},b=y=>{this.lowLatency=y,t(`lowLatency changed to ${y}`),S()},S=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)f(1);else{let y=this._getBufferSizeSec();if(this.bufferStates.length<5){f(1);return}let D=pe()-1e4,L=0;for(let R=0;R<this.bufferStates.length;R++){let T=this.bufferStates[R];y=Math.min(y,T.buf),T.ts<D&&L++}this.bufferStates.splice(0,L),t(`update playback rate; minBuffer=${y} drop=${L} jitter=${this.sourceJitter}`);let A=y-R$;this.sourceJitter>=0?A-=this.sourceJitter/2:this.sourceJitter-=1,A>3?f(1.15):A>1?f(1.1):A>.3?f(1.05):f(1)}},g=y=>{let w,D=()=>w&&w.start?w.start.length:0,L=M=>w.start[M]/1e3,A=M=>w.dur[M]/1e3,R=M=>w.fragIndex+M,T=(M,H)=>({chunkIdx:R(M),startTS:L(M),dur:A(M),discontinuity:H}),q=()=>{let M=0;if(w&&w.dur){let H=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,J=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,ie=H;this.sourceJitter>1&&(ie+=this.sourceJitter-1);let ue=w.dur.length-1;for(;ue>=0&&(ie-=w.dur[ue],!(ie<=0));--ue);M=Math.min(ue,w.dur.length-1-J),M=Math.max(M,0)}return T(M,!0)},$=M=>{let H=D();if(!(H<=0)){if(Un(M)){for(let J=0;J<H;J++)if(L(J)>M)return T(J)}return q()}},v=M=>{let H=D(),J=M?M.chunkIdx+1:0,ie=J-w.fragIndex;if(!(H<=0)){if(!M||ie<0||ie-H>k$)return t(`Resync: offset=${ie} bChunks=${H} chunk=`+JSON.stringify(M)),q();if(!(ie>=H))return T(J-w.fragIndex,!1)}},E=(M,H,J)=>{l&&l.abort(),l=lr(this.urlResolver.resolve(M,!0,this.lowLatency),H,J,()=>this._retryCallback()).withTimeout(Hn).withRetryCount(nc).withFinally(()=>{l=null}).withJSONResponse().send()};return{seek:(M,H)=>{E(y,J=>{if(!p())return;w=J;let ie=!!w.lowLatency;ie!==this.lowLatency&&b(ie);let ue=0;for(let fe=0;fe<w.dur.length;++fe)ue+=w.dur[fe];ue>0&&(va(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(ue/w.dur.length)),r({name:"index",zeroTime:w.zeroTime,shiftDuration:w.shiftDuration}),this.sourceJitter=w.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,w.jitter/1e3)):1,M($(H))},()=>this._handleNetworkError())},nextChunk:v}},I=()=>{s=!1,u&&u.abort(),o&&o.abort(),l&&l.abort(),va(this.filesFetcher),this.filesFetcher.abortAll()};return c={start:y=>{let{videoElement:w,logger:D}=this.params,L=g(e.jidxUrl),A,R,T,q,$=0,v,E,z,M=()=>{v&&(clearTimeout(v),v=void 0);let U=Math.max(L$,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),ke=$+U,Te=pe(),le=Math.min(1e4,ke-Te);$=Te;let We=()=>{l||p()&&L.seek(()=>{p()&&($=pe(),H(),M())})};le>0?v=window.setTimeout(()=>{this.paused?M():We()},le):We()},H=()=>{let U;for(;U=L.nextChunk(q);)q=U,me(U);let ke=L.nextChunk(T);if(ke){if(T&&ke.discontinuity){D("Detected discontinuity; restarting playback"),this.paused?M():(I(),this._initPlayerWith(e));return}fe(ke)}else M()},J=(U,ke)=>{if(!p()||!this.sourceBuffer)return;let Te,le,We,Bt=lt=>{window.setTimeout(()=>{p()&&J(U,ke)},lt)};if(this.sourceBuffer.updating)D("Source buffer is updating; delaying appendBuffer"),Bt(100);else{let lt=pe(),Oe=w.currentTime;!this.paused&&w.buffered.length>1&&E===Oe&<-z>500&&(D("Stall suspected; trying to fix"),this._fixupStall()),E!==Oe&&(E=Oe,z=lt);let Vt=this._getBufferSizeSec();if(Vt>30)D(`Buffered ${Vt} seconds; delaying appendBuffer`),Bt(2e3);else try{this.sourceBuffer.appendBuffer(U),this.videoPlayStarted?(this.bufferStates.push({ts:lt,buf:Vt}),S(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),ke&&ke()}catch(ct){if(ct.name==="QuotaExceededError")D("QuotaExceededError; delaying appendBuffer"),We=this.sourceBuffer.buffered.length,We!==0&&(Te=this.sourceBuffer.buffered.start(0),le=Oe,le-Te>4&&this.sourceBuffer.remove(Te,le-3)),Bt(1e3);else throw ct}}},ie=()=>{R&&A&&(D([`Appending chunk, sz=${R.byteLength}:`,JSON.stringify(T)]),J(R,function(){R=null,H()}))},ue=U=>e.fragUrlTemplate.replace("%%id%%",U.chunkIdx),fe=U=>{p()&&h(ue(U),(ke,Te)=>{if(p()){if(Te/=1e3,R=ke,T=U,n=U.startTS,Te){let le=Math.min(10,U.dur/Te);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*le:le}ie()}},()=>this._handleNetworkError())},me=U=>{p()&&(va(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(ue(U),!1)))},j=U=>{p()&&(e.cachedHeader=U,J(U,()=>{A=!0,ie()}))};s=!0,L.seek(U=>{if(p()){if($=pe(),!U){M();return}q=U,!w$(y)||U.startTS>y?fe(U):(T=U,H())}},y),e.cachedHeader?j(e.cachedHeader):d(e.headerUrl,j,()=>this._handleNetworkError())},stop:I,getTimestampSec:()=>n},c}_switchToQuality(e){let{logger:t,playerCallback:i}=this.params,r;e.bitrate!==this.bitrate&&(this.rep&&(r=this.rep.getTimestampSec(),Un(r)&&(r+=.1),this.rep.stop()),this.currentManifestEntry=e,this.rep=this._representation(e),t(`switch to quality: codecs=${e.codecs}; headerUrl=${e.headerUrl}; bitrate=${e.bitrate}`),this.bitrate=e.bitrate,va(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(r),i({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return Un(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,i=p=>{if(!this.autoQuality)return;let d,h,f;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&p<this.bitrate&&(h=this._getBufferSizeSec(),f=p/this.bitrate,h>10&&f>.8||h>15&&f>.5||h>20&&f>.3)){e(`Not switching: buffer=${Math.floor(h)}; bitrate=${this.bitrate}; newRate=${Math.floor(p)}`);return}d=this._selectQuality(p),d?this._switchToQuality(d):e(`Could not find quality by bitrate ${p}`)},s={updateChunk:(d,h)=>{let f=pe();if(this.chunkRateEstimator.addInterval(d,f,h)){let S=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:h,duration:f-d,speed:S}),!0}},get:()=>{let d=this.chunkRateEstimator.getBitRate();return d?d*.85:0}},n=-1/0,u,o=!0,l=()=>{let p=s.get();if(p&&u&&this.autoQuality){if(o&&p>u&&ac(n)<3e4)return;i(p)}o=this.autoQuality};return{updateChunk:(p,d)=>{let h=s.updateChunk(p,d);return h&&l(),h},notifySwitch:p=>{let d=pe();p<u&&(n=d),u=p}}}_fetchManifest(e,t,i){this.manifestRequest=lr(this.urlResolver.resolve(e,!0),t,i,()=>this._retryCallback()).withJSONResponse().withTimeout(Hn).withRetryCount(this.params.config.manifestRetryMaxCount).withRetryInterval(this.params.config.manifestRetryInterval,this.params.config.manifestRetryMaxInterval).send().withFinally(()=>{this.manifestRequest=void 0})}_playVideoElement(){let{videoElement:e}=this.params;Be(e,()=>{this.soundProhibitedEvent$.next()}).then(t=>{t||(this.params.liveOffset.pause(),this.params.videoState.setState("paused"))})}_handleManifestUpdate(e){let{logger:t,playerCallback:i,videoElement:r}=this.params,s=n=>{let u=[];return n?.length?(n.forEach((o,l)=>{o.video&&r.canPlayType(o.codecs).replace(/no/,"")&&window.MediaSource?.isTypeSupported?.(o.codecs)&&(o.index=l,u.push(o))}),u.sort(function(o,l){return o.video&&l.video?l.video.height-o.video.height:l.bitrate-o.bitrate}),u):(i({name:"error",type:"empty_manifest"}),[])};this.manifest=s(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),i({name:"manifest",manifest:this.manifest})}_refetchManifest(e){this.destroyed||(this.manifestRefetchTimer&&clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=window.setTimeout(()=>{this._fetchManifest(e,t=>{this.destroyed||(this._handleManifestUpdate(t),this._refetchManifest(e))},()=>this._refetchManifest(e))},P$))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};var HS=C(Qi(),1);import{debounce as $$,filter as qS,fromEvent as M$,interval as D$,isHigher as C$,isInvariantQuality as B$,isLower as V$,merge as _$,Subject as US,Subscription as O$}from"@vkontakte/videoplayer-shared";var oc=class{constructor(){this.onDroopedVideoFramesLimit$=new US;this.subscription=new O$;this.playing=!1;this.tracks=[];this.forceChecker$=new US;this.isForceCheckCounter=0;this.prevTotalVideoFrames=0;this.prevDroppedVideoFrames=0;this.limitCounts={};this.handleChangeVideoQuality=()=>{let e=this.tracks.find(({size:t})=>t?.height===this.video.videoHeight&&t?.width===this.video.videoWidth);e&&!B$(e.quality)&&this.onChangeQuality(e.quality)};this.checkDroppedFrames=()=>{let{totalVideoFrames:e,droppedVideoFrames:t}=this.video.getVideoPlaybackQuality(),i=e-this.prevTotalVideoFrames,r=t-this.prevDroppedVideoFrames,s=1-(i-r)/i;!isNaN(s)&&s>0&&this.log({message:`[dropped]. current dropped percent: ${s}, limit: ${this.droppedFramesChecker.percentLimit}`}),!isNaN(s)&&s>=this.droppedFramesChecker.percentLimit&&C$(this.currentQuality,this.droppedFramesChecker.minQualityBanLimit)&&(this.limitCounts[this.currentQuality]=(this.limitCounts[this.currentQuality]??0)+1,this.maxQualityLimit=this.getMaxQualityLimit(this.currentQuality),this.currentTimer&&window.clearTimeout(this.currentTimer),this.currentTimer=window.setTimeout(()=>this.maxQualityLimit=this.getMaxQualityLimit(),this.droppedFramesChecker.qualityUpWaitingTime),this.onDroopedVideoFramesLimitTrigger()),this.savePrevFrameCounts(e,t)}}connect(e){this.log=e.logger.createComponentLog("DroppedFramesManager"),this.video=e.video,this.isAuto=e.isAuto,this.tracks=e.tracks,this.droppedFramesChecker=e.droppedFramesChecker,this.subscription.add(e.playing$.subscribe(()=>this.playing=!0)),this.subscription.add(e.pause$.subscribe(()=>this.playing=!1)),this.isEnabled&&this.subscribe()}destroy(){this.currentTimer&&window.clearTimeout(this.currentTimer),this.subscription.unsubscribe()}get droppedVideoMaxQualityLimit(){return this.maxQualityLimit}subscribe(){this.subscription.add(M$(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=D$(this.droppedFramesChecker.checkTime).pipe(qS(()=>this.playing),qS(()=>{let r=!!this.isForceCheckCounter;return r&&(this.isForceCheckCounter-=1),!r})),t=this.forceChecker$.pipe($$(this.droppedFramesChecker.checkTime)),i=_$(e,t);this.subscription.add(i.subscribe(this.checkDroppedFrames))}onChangeQuality(e){this.currentQuality=e;let{totalVideoFrames:t,droppedVideoFrames:i}=this.video.getVideoPlaybackQuality();this.savePrevFrameCounts(t,i),this.isForceCheckCounter=this.droppedFramesChecker.tickCountAfterQualityChange,this.forceChecker$.next()}onDroopedVideoFramesLimitTrigger(){this.isAuto.getState()&&(this.log({message:`[onDroopedVideoFramesLimit]. maxQualityLimit: ${this.maxQualityLimit}`}),this.onDroopedVideoFramesLimit$.next())}getMaxQualityLimit(e){let t=(0,HS.default)(this.limitCounts).filter(([,i])=>i>=this.droppedFramesChecker.countLimit).sort(([i],[r])=>V$(i,r)?-1:1)?.[0]?.[0];return e??t}get isEnabled(){return this.droppedFramesChecker.enabled&&this.isDroppedFramesCheckerSupport}get isDroppedFramesCheckerSupport(){return!!this.video&&typeof this.video.getVideoPlaybackQuality=="function"}savePrevFrameCounts(e,t){this.prevTotalVideoFrames=e,this.prevDroppedVideoFrames=t}},cr=oc;import{map as F$,Observable as N$}from"@vkontakte/videoplayer-shared";import{fromEvent as q$}from"@vkontakte/videoplayer-shared";var Ta=()=>!!window.documentPictureInPicture?.window||!!document.pictureInPictureElement;var U$=(a,e)=>new N$(t=>{if(!window.IntersectionObserver)return;let i={root:null},r=new IntersectionObserver((n,u)=>{n.forEach(o=>t.next(o.isIntersecting||Ta()))},{...i,...e});r.observe(a);let s=q$(document,"visibilitychange").pipe(F$(n=>!document.hidden||Ta())).subscribe(n=>t.next(n));return()=>{r.unobserve(a),s.unsubscribe()}}),Ke=U$;var K$=["paused","playing","ready"],X$=["paused","playing","ready"],Ia=class{constructor(e){this.subscription=new z$;this.videoState=new F("stopped");this.representations$=new lc([]);this.droppedFramesManager=new cr;this.maxSeekBackTime$=new lc(1/0);this.zeroTime$=new lc(void 0);this.liveOffset=new gi;this._dashCb=e=>{switch(e.name){case"buffering":{let t=e.isBuffering;this.params.output.isBuffering$.next(t);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${e.type}`,category:WS.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{let t=e.manifest,i=[];for(let r of t){let s=r.name??r.index.toString(10),n=jt(r.name)??Y$(r.video),u=r.bitrate/1e3,o={...r.video};if(!n)continue;let l={id:s,quality:n,bitrate:u,size:o};i.push({track:l,representation:r})}this.representations$.next(i),this.params.output.availableVideoTracks$.next(i.map(({track:r})=>r)),this.videoState.getTransition()?.to==="manifest_ready"&&this.videoState.setState("manifest_ready");break}case"qualitySwitch":{let t=e.quality,i=this.representations$.getValue().find(({representation:r})=>r===t)?.track;this.params.output.hostname$.next(new URL(t.headerUrl,this.params.source.url).hostname),uc(i)&&this.params.output.currentVideoTrack$.next(i);break}case"bandwidth":{let{size:t,duration:i}=e;this.params.dependencies.throughputEstimator.addRawSpeed(t,i);break}case"index":{this.maxSeekBackTime$.next(e.shiftDuration||0),this.zeroTime$.next(e.zeroTime);break}}};this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; seekState: ${JSON.stringify(s)};`}),i==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState("stopped"));return}if(t)return;let n=this.params.desiredState.videoTrack.getTransition(),u=this.params.desiredState.autoVideoTrackSwitching.getTransition();if((0,cc.default)(X$,e)&&(n||u)){this.prepare();return}if(r?.to!=="paused"&&s.state==="requested"&&(0,cc.default)(K$,e)){this.seek(s.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(se(this.params.source.url));return;case"manifest_ready":this.videoState.startTransitionTo("ready"),this.prepare();break;case"ready":if(i==="paused")this.videoState.setState("paused");else if(i==="playing"){this.videoState.startTransitionTo("playing");let o=r?.from;o&&o==="ready"&&this.dash.catchUp(),this.dash.play()}return;case"playing":i==="paused"&&(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.dash.pause());return;case"paused":if(i==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.dash.play(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let o=this.liveOffset.getTotalOffset();o>=this.maxSeekBackTime$.getValue()&&(o=0,this.liveOffset.resetTo(o)),this.liveOffset.resume(),this.params.output.position$.next(-o/1e3),this.dash.reinit(se(this.params.source.url,o))}return;default:return jS(e)}};this.textTracksManager=new Ye(e.source.url),this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=r=>{e.output.error$.next({id:"DashLiveProvider",category:WS.WTF,message:"DashLiveProvider internal logic error",thrown:r})};this.subscription.add(zS(this.videoState.stateChangeStarted$.pipe(jn(r=>({transition:r,type:"start"}))),this.videoState.stateChangeEnded$.pipe(jn(r=>({transition:r,type:"end"})))).subscribe(({transition:r,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(r)}`})})),this.video=$e(e.container,e.tuning),this.params.output.element$.next(this.video),this.dash=this.createLiveDashPlayer(),this.subscription.add(this.dash.soundProhibitedEvent$.subscribe(this.params.output.soundProhibitedEvent$)),this.params.output.duration$.next(1/0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(ge(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);let i=Ce(this.video);this.subscription.add(()=>i.destroy()),this.subscription.add(this.representations$.pipe(jn(r=>r.map(({track:s})=>s)),GS(r=>!!r.length),G$()).subscribe(r=>this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks:r}))),this.subscription.add(i.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready")},t)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused")},t)).add(i.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.videoState.setState("playing")},t)).add(i.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(Q$(),jn(r=>-r/1e3)).subscribe(this.params.output.duration$)).add(H$({zeroTime:this.zeroTime$.pipe(GS(uc)),position:i.timeUpdate$}).subscribe(({zeroTime:r,position:s})=>this.params.output.liveTime$.next(r+s*1e3),t)).add(mt(this.video,this.params.desiredState.isLooped,t)).add(De(this.video,this.params.desiredState.volume,i.volumeState$,t)).add(i.volumeState$.subscribe(this.params.output.volume$,t)).add(ze(this.video,this.params.desiredState.playbackRate,i.playbackRateState$,t)).add(i.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(i.loadedMetadata$.subscribe(this.params.output.loadedMetadataEvent$)).add(i.playing$.subscribe(this.params.output.firstFrameEvent$)).add(i.canplay$.subscribe(this.params.output.canplay$)).add(i.inPiP$.subscribe(this.params.output.inPiP$)).add(i.inFullscreen$.subscribe(this.params.output.inFullscreen$)).add(Ke(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:r,min:s}})=>{this.dash.setAutoQualityLimits({max:r&&YS(r),min:s&&YS(s)}),this.params.output.autoVideoTrackLimits$.next({max:r,min:s})})).add(this.videoState.stateChangeEnded$.subscribe(r=>{switch(r.to){case"stopped":this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState("stopped");break;case"manifest_ready":case"ready":this.params.desiredState.playbackState.getTransition()?.to==="ready"&&this.params.desiredState.playbackState.setState("ready");break;case"paused":this.params.desiredState.playbackState.setState("paused");break;case"playing":this.params.desiredState.playbackState.setState("playing");break;default:return jS(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$,W$(["init"])).pipe(j$(0)).subscribe(this.syncPlayback,t))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.droppedFramesManager.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),Me(this.video)}createLiveDashPlayer(){let e=new ya({videoElement:this.video,videoState:this.videoState,playbackState:this.params.desiredState.playbackState,liveOffset:this.liveOffset,config:{maxParallelRequests:this.params.config.maxParallelRequests,minBuffer:this.params.tuning.live.minBuffer,minBufferSegments:this.params.tuning.live.minBufferSegments,lowLatencyMinBuffer:this.params.tuning.live.lowLatencyMinBuffer,lowLatencyMinBufferSegments:this.params.tuning.live.lowLatencyMinBufferSegments,isLiveCatchUpMode:this.params.tuning.live.isLiveCatchUpMode,manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},playerCallback:this._dashCb,logger:t=>{this.params.dependencies.logger.log({message:String(t),component:"LiveDashPlayer"})}});return e.pause(),e}prepare(){let e=this.representations$.getValue(),t=this.params.desiredState.videoTrack.getTransition()?.to??this.params.desiredState.videoTrack.getState(),i=this.params.desiredState.autoVideoTrackSwitching.getTransition()?.to??this.params.desiredState.autoVideoTrackSwitching.getState(),r=!i&&uc(t)?t:St(e.map(({track:l})=>l),{container:this.video.getBoundingClientRect(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),s=r?.id,n=this.params.desiredState.videoTrack.getTransition(),u=this.params.desiredState.videoTrack.getState()?.id,o=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(r&&(n||s!==u)&&this.setVideoTrack(r),o&&this.setAutoQuality(i),n||o||s!==u){let l=e.find(({track:c})=>c.id===s)?.representation;QS(l,"Representations missing"),this.dash.startPlay(l,i)}}setVideoTrack(e){let t=this.representations$.getValue().find(({track:i})=>i.id===e.id)?.representation;QS(t,`No such representation ${e.id}`),this.dash.switchByName(t.name),this.params.desiredState.videoTrack.setState(e)}setAutoQuality(e){this.dash.setAutoQualityEnabled(e),this.params.desiredState.autoVideoTrackSwitching.setState(e)}seek(e){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),i=this.videoState.getState(),r=t==="paused"&&i==="paused",s=-e,n=s<=this.maxSeekBackTime$.getValue()?s:0;this.params.output.position$.next(e/1e3),this.dash.reinit(se(this.params.source.url,n)),r&&this.dash.pause(),this.liveOffset.resetTo(n,r)}};var KS=Ia;var bT=C(Ee(),1);var he=(a,e)=>{let t=0;for(let i=0;i<a.length;i++){let r=a.start(i)*1e3,s=a.end(i)*1e3;r<=e&&e<=s&&(t=s)}return Math.max(t-e,0)};import{assertNever as qC,assertNonNullable as UC,debounce as HC,ErrorCategory as hT,filter as Gc,filterChanged as yo,fromEvent as jC,isNonNullable as fT,isNullable as QC,map as zc,merge as To,observableFrom as Yc,once as mT,Subscription as WC}from"@vkontakte/videoplayer-shared";var{NativeAbortSignal:wU,NativeAbortController:AU}=function(a){return{NativeAbortSignal:a.AbortSignal,NativeAbortController:a.AbortController}}(typeof self<"u"?self:global);function XS(a){let e;try{e=new Event("abort")}catch{typeof document<"u"?document.createEvent?(e=document.createEvent("Event"),e.initEvent("abort",!1,!1)):(e=document.createEventObject(),e.type="abort"):e={type:"abort",bubbles:!1,cancelable:!1}}return e.reason=a,e}function JS(a){if(a===void 0)if(typeof document>"u")a=new Error("This operation was aborted"),a.name="AbortError";else try{a=new DOMException("signal is aborted without reason"),Object.defineProperty(a,"name",{value:"AbortError"})}catch{a=new Error("This operation was aborted"),a.name="AbortError"}return a}var Qn=class{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,i){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:i})}removeEventListener(e,t){if(!(e in this.listeners))return;let i=this.listeners[e];for(let r=0,s=i.length;r<s;r++)if(i[r].callback===t){i.splice(r,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;let i=this.listeners[e.type].slice();for(let r=0,s=i.length;r<s;r++){let n=i[r];try{n.callback.call(this,e)}catch(u){Promise.resolve().then(()=>{throw u})}n.options&&n.options.once&&this.removeEventListener(e.type,n.callback)}return!e.defaultPrevented}},dr=class extends Qn{constructor(){super(),this.listeners||Qn.call(this),Object.defineProperty(this,"aborted",{value:!1,writable:!0,configurable:!0}),Object.defineProperty(this,"onabort",{value:null,writable:!0,configurable:!0}),Object.defineProperty(this,"reason",{value:void 0,writable:!0,configurable:!0})}toString(){return"[object AbortSignal]"}dispatchEvent(e){e.type==="abort"&&(this.aborted=!0,typeof this.onabort=="function"&&this.onabort.call(this,e)),super.dispatchEvent(e)}throwIfAborted(){let{aborted:e,reason:t="Aborted"}=this;if(e)throw t}static timeout(e){let t=new vi;return setTimeout(()=>t.abort(new DOMException(`This signal is timeout in ${e}ms`,"TimeoutError")),e),t.signal}static any(e){let t=new vi;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}},vi=class{constructor(){Object.defineProperty(this,"signal",{value:new dr,writable:!0,configurable:!0})}abort(e){let t=JS(e),i=XS(t);this.signal.reason=t,this.signal.dispatchEvent(i)}toString(){return"[object AbortController]"}};typeof Symbol<"u"&&Symbol.toStringTag&&(vi.prototype[Symbol.toStringTag]="AbortController",dr.prototype[Symbol.toStringTag]="AbortSignal");function Wn(a){return a.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof a.Request=="function"&&!a.Request.prototype.hasOwnProperty("signal")||!a.AbortController}function dc(a){typeof a=="function"&&(a={fetch:a});let{fetch:e,Request:t=e.Request,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r=!1}=a;if(!Wn({fetch:e,Request:t,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r}))return{fetch:e,Request:s};let s=t;(s&&!s.prototype.hasOwnProperty("signal")||r)&&(s=function(l,c){let p;c&&c.signal&&(p=c.signal,delete c.signal);let d=new t(l,c);return p&&Object.defineProperty(d,"signal",{writable:!1,enumerable:!1,configurable:!0,value:p}),d},s.prototype=t.prototype);let n=e;return{fetch:(o,l)=>{let c=s&&s.prototype.isPrototypeOf(o)?o.signal:l?l.signal:void 0;if(c){let p;try{p=new DOMException("Aborted","AbortError")}catch{p=new Error("Aborted"),p.name="AbortError"}if(c.aborted)return Promise.reject(p);let d=new Promise((h,f)=>{c.addEventListener("abort",()=>f(p),{once:!0})});return l&&l.signal&&delete l.signal,Promise.race([d,n(o,l)])}return n(o,l)},Request:s}}var J$=()=>"fetch"in window,Ea=J$()&&Wn({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),ZS=Ea?dc({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,Xe=Ea?ZS.fetch:window.fetch,VU=Ea?ZS.Request:window.Request,X=Ea?vi:window.AbortController,_U=Ea?dr:window.AbortSignal;var lT=C(Ee(),1),qc=C(xa(),1);var Fv=C(Ov(),1);import{ErrorCategory as Aa}from"@vkontakte/videoplayer-shared";var Gn=a=>{if(!a)return{id:"EmptyResponse",category:Aa.PARSER,message:"Empty response"};if(a.length<=2&&a.match(/^\d+$/))return{id:`UVError#${a}`,category:Aa.NETWORK,message:`UV Error ${a}`};let e=(0,Fv.default)(a).substring(0,100).toLowerCase();if(e.startsWith("<!doctype")||e.startsWith("<html>")||e.startsWith("<body>")||e.startsWith("<head>"))return{id:"UnexpectedHTML",category:Aa.NETWORK,message:"Received unexpected HTML, possibly a ISP block"};if(e.startsWith("<?xml"))return new DOMParser().parseFromString(a,"text/xml").querySelector("parsererror")?{id:"InvalidXML",category:Aa.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:Aa.PARSER,message:"Response is valid XML, but parser failed"}};var Se=(a,e,t=0)=>{for(let i=0;i<a.length;i++)if(a.start(i)*1e3-t<=e&&a.end(i)*1e3+t>e)return!0;return!1};import{abortable as Oc,assertNonNullable as Er,combine as xr,ErrorCategory as ot,filter as ho,filterChanged as as,flattenObject as ss,fromEvent as Dt,getTraceSubscriptionMethod as EC,interval as Fc,isNonNullable as ns,isNullable as nT,map as wr,merge as xi,now as Nc,Subject as Kt,Subscription as oT,tap as xC,throttle as wC,ValueSubject as ee}from"@vkontakte/videoplayer-shared";var Xn=C(Ee(),1),Ei=C(at(),1),Jn=C(xa(),1);var _M=(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)},OM=a=>window.clearTimeout(a),Nv=a=>typeof a=="function"&&a?.toString().endsWith("{ [native code] }"),qv=!Nv(window.requestIdleCallback)||!Nv(window.cancelIdleCallback),pr=qv?_M:window.requestIdleCallback,vt=qv?OM:window.cancelIdleCallback;var Jy=C(gn(),1);import{assertNever as FM,ErrorCategory as Uv,Subject as Hv}from"@vkontakte/videoplayer-shared";var NM=18,jv=!1;try{jv=B.browser.isSafari&&!!B.browser.safariVersion&&B.browser.safariVersion<=NM}catch(a){console.error(a)}var gc=class{constructor(e){this.bufferFull$=new Hv;this.error$=new Hv;this.queue=[];this.currentTask=null;this.destroyed=!1;this.abortRequested=!1;this.completeTask=()=>{try{if(this.currentTask){let e=this.currentTask.signal?.aborted;this.currentTask.callback(!e),this.currentTask=null}this.queue.length&&this.pull()}catch(e){this.error$.next({id:"BufferTaskQueueUnknown",category:Uv.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:e})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(i=>{let r={operation:"append",data:e,signal:t,callback:i};this.queue.push(r),this.pull()})}async remove(e,t,i){return i&&i.aborted?!1:new Promise(r=>{let s={operation:"remove",from:e,to:t,signal:i,callback:r};this.queue.unshift(s),this.pull()})}async abort(e){return new Promise(t=>{let i,r=s=>{this.abortRequested=!1,t(s)};jv&&e?i={operation:"safariAbort",init:e,callback:r}:i={operation:"abort",callback:r};for(let{callback:s}of this.queue)s(!1);this.abortRequested=!0,i&&(this.queue=[i]),this.pull()})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){if((this.buffer.updating||this.currentTask||this.destroyed)&&!this.abortRequested)return;let e=this.queue.shift();if(!e)return;if(e.signal?.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(r){r instanceof DOMException&&r.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):r instanceof DOMException&&r.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:Uv.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:r}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){let{operation:t}=e;switch(t){case"append":this.buffer.appendBuffer(e.data);break;case"remove":this.buffer.remove(e.from/1e3,e.to/1e3);break;case"abort":this.buffer.abort();break;case"safariAbort":{this.buffer.abort(),this.buffer.appendBuffer(e.init);break}default:FM(t)}}},Qv=gc;var hr=a=>{let e=0;for(let t=0;t<a.length;t++)e+=a.end(t)-a.start(t);return e*1e3};import{abortable as Gt,assertNonNullable as Ve,ErrorCategory as Lt,fromEvent as $c,getExponentialDelay as Mc,isNonNullable as Sr,isNullable as ve,now as Kn,once as uC,Subject as lC,Subscription as cC,ValueSubject as Ii}from"@vkontakte/videoplayer-shared";var Wv=C(at(),1);var zn=a=>a.valid,Q=class{constructor(e,t){this.cursor=0;this.source=e,this.boxParser=t,this.children=[];let i=this.readUint32();this.type=this.readString(4),i===1&&(this.cursor+=8);let r=e.byteOffset+this.cursor,s;i===0?(this.size=void 0,this.valid=!1,s=void 0):i===1?(this.size=void 0,this.valid=!1,s=void 0):i>e.byteLength?(this.size=i,this.valid=!1,s=Math.min(i-this.cursor,e.byteLength-this.cursor)):(this.size=i,this.valid=!0,s=i-this.cursor),this.content=new DataView(e.buffer,r,s)}get id(){return this.type}scanForBoxes(e){return this.boxParser.parse(e)}readString(e,t="ascii"){let r=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,r}readUint8(){let e=this.source.getUint8(this.cursor);return this.cursor+=1,e}readUint16(){let e=this.source.getUint16(this.cursor);return this.cursor+=2,e}readUint32(){let e=this.source.getUint32(this.cursor);return this.cursor+=4,e}readUint64(){let e=this.source.getBigInt64(this.cursor);return this.cursor+=8,e}};var fr=class extends Q{};import{assertNever as qM}from"@vkontakte/videoplayer-shared";var Pa=class extends Q{constructor(e,t){if(super(e,t),!this.valid)return;let i=this.readString(16),r=new DataView(this.content.buffer,this.content.byteOffset+16,this.content.byteLength-16);this.userData=this.parseData(i,r)}parseData(e,t){switch(e){case"ondemandlivejson":{let i=new TextDecoder("ascii").decode(t),r=JSON.parse(i);return{received:r["t-in"],prepared:r["t-out"]}}default:qM(e)}}};var ka=class extends Q{constructor(e,t){if(super(e,t),!this.valid)return;this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let i=new DataView(this.content.buffer,this.content.byteOffset+8,this.content.byteLength-8);for(let r=0;r<i.byteLength;r+=4){let s=this.readString(4);this.compatibleBrands.push(s)}}};var Ra=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Z=class extends Q{constructor(e,t){if(super(e,t),!this.valid)return;let i=this.readUint32();this.version=i>>>24,this.flags=i&16777215,this.content=new DataView(this.content.buffer,this.content.byteOffset+4,this.content.byteLength-4)}};var La=class extends Z{constructor(e,t){super(e,t),this.valid&&(this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.timescale=this.readUint32(),this.duration=this.readUint32(),this.rate=this.readUint32(),this.volume=this.readUint16())}};var $a=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ma=class extends Q{constructor(e,t){super(e,t),this.data=this.content}};var yi=class extends Z{get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e,t){if(super(e,t),!!this.valid){this.segments=[],this.referenceId=this.readUint32(),this.timescale=this.readUint32(),this.earliestPresentationTime32=this.readUint32(),this.firstOffset32=this.readUint32(),this.earliestPresentationTime64=0,this.firstOffset64=0,this.referenceCount=this.readUint32()&65535;for(let i=0;i<this.referenceCount;i++){let r=this.readUint32(),s=r>>>31,n=r<<1>>>1,u=this.readUint32();r=this.readUint32();let o=r>>>28,l=r<<3>>>3;this.segments.push({referenceType:s,referencedSize:n,subsegmentDuration:u,SAPType:o,SAPDeltaTime:l})}}}};var Da=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ca=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ba=class extends Z{constructor(e,t){if(super(e,t),!this.valid)return;switch(this.readUint8()){case 0:this.stereoMode=0;break;case 1:this.stereoMode=1;break;case 2:this.stereoMode=2;break;case 3:this.stereoMode=3;break;case 4:this.stereoMode=4;break}this.cursor+=1}};var Va=class extends Z{constructor(e,t){super(e,t),this.valid&&(this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32())}};var _a=class extends Z{constructor(e,t){super(e,t),this.valid&&(this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32())}};var Oa=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Fa=class extends Z{constructor(e,t){super(e,t),this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.trackId=this.readUint32(),this.cursor+=4,this.duration=this.readUint32(),this.cursor+=8,this.layer=this.readUint16(),this.alternateGroup=this.readUint16(),this.cursor+=2,this.cursor+=2,this.matrix=[[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()]],this.width=this.readUint32(),this.height=this.readUint32()}};var Na=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var qa=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ua=class extends Z{constructor(e,t){super(e,t),this.valid&&(this.sequenceNumber=this.readUint32())}};var Ha=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ja=class extends Z{constructor(e,t){super(e,t),this.trackId=this.readUint32(),this.flags&1&&(this.baseDataOffset=this.readUint64()),this.flags&2&&(this.sampleDescriptionIndex=this.readUint32()),this.flags&8&&(this.defaultSampleDuration=this.readUint32()),this.flags&16&&(this.defaultSampleSize=this.readUint32()),this.flags&32&&(this.defaultSampleFlags=this.readUint32())}};var Qa=class extends Z{constructor(t,i){super(t,i);this.baseMediaDecodeTime32=0;this.baseMediaDecodeTime64=BigInt(0);this.version===1?this.baseMediaDecodeTime64=this.readUint64():this.baseMediaDecodeTime32=this.readUint32()}get baseMediaDecodeTime(){return this.version===1?this.baseMediaDecodeTime64:this.baseMediaDecodeTime32}};var Wa=class extends Z{constructor(t,i){super(t,i);this.sampleDuration=[];this.sampleSize=[];this.sampleFlags=[];this.sampleCompositionTimeOffset=[];this.optionalFields=0;this.sampleCount=this.readUint32(),this.flags&1&&(this.dataOffset=this.readUint32()),this.flags&4&&(this.firstSampleFlags=this.readUint32());for(let r=0;r<this.sampleCount;r++)this.flags&256&&this.sampleDuration.push(this.readUint32()),this.flags&512&&this.sampleSize.push(this.readUint32()),this.flags&1024&&this.sampleFlags.push(this.readUint32()),this.flags&2048&&this.sampleCompositionTimeOffset.push(this.readUint32())}};var Ga=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var za=class extends Z{constructor(e,t){super(e,t),this.valid&&(this.entryCount=this.readUint32(),this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+4,this.content.byteLength-4)))}};var Ya=class extends Q{constructor(e,t){super(e,t),this.valid&&(this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+78,this.content.byteLength-78)))}};var HM={ftyp:ka,moov:Ra,mvhd:La,moof:$a,mdat:Ma,sidx:yi,trak:Da,mdia:Oa,mfhd:Ua,tkhd:Fa,traf:Ha,tfhd:ja,tfdt:Qa,trun:Wa,minf:Na,sv3d:Ca,st3d:Ba,prhd:Va,proj:qa,equi:_a,uuid:Pa,stbl:Ga,stsd:za,avc1:Ya,unknown:fr},Rt=class a{constructor(e={}){this.options={offset:0,...e}}parse(e){let t=[],i=this.options.offset;for(;i<e.byteLength;){let s=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+i+4,4)),n;try{n=this.createBox(s,new DataView(e.buffer,e.byteOffset+i,e.byteLength-i))}catch(u){if(!(u instanceof RangeError))throw u}if(!n||!zn(n))break;t.push(n),i+=n.size}return t}createBox(e,t){let i=HM[e];return i?new i(t,new a):new fr(t,new a)}};var Wt=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{zn(t)&&(this.index[t.type]??=[],this.index[t.type].push(t),t.children.length>0&&this.indexBoxLevel(t.children))})}find(e){return this.index[e]&&this.index[e][0]?this.index[e][0]:null}findAll(e){return this.index[e]||[]}};var QM=new TextDecoder("ascii"),WM=a=>QM.decode(new DataView(a.buffer,a.byteOffset+4,4))==="ftyp",GM=a=>{let e=new yi(a,new Rt),t=e.earliestPresentationTime/e.timescale*1e3,i=a.byteOffset+a.byteLength+e.firstOffset;return e.segments.map(s=>{if(s.referenceType!==0)throw new Error("Unsupported multilevel sidx");let n=s.subsegmentDuration/e.timescale*1e3,u={status:"none",time:{from:t,to:t+n},byte:{from:i,to:i+s.referencedSize-1}};return t+=n,i+=s.referencedSize,u})},zM=(a,e)=>{let i=new Rt().parse(a),r=new Wt(i),s=r.findAll("moof"),n=e?r.findAll("uuid"):r.findAll("mdat");if(!(n.length&&s.length))return null;let u=s[0],o=n[n.length-1],l=u.source.byteOffset,p=o.source.byteOffset-u.source.byteOffset+o.size;return new DataView(a.buffer,l,p)},YM=a=>{let t=new Rt().parse(a),i=new Wt(t),r={},s=i.findAll("uuid"),n=(0,Wv.default)(s,-1);return n?{serverDataReceivedTimestamp:n.userData.received,serverDataPreparedTime:n.userData.received}:r},KM=a=>{let t=new Rt().parse(a);return new Wt(t).find("sidx")?.timescale},XM=(a,e)=>{let i=new Rt().parse(a),s=new Wt(i).findAll("traf"),n=s[s.length-1].children.find(p=>p.type==="tfhd"),u=s[s.length-1].children.find(p=>p.type==="tfdt"),o=s[s.length-1].children.find(p=>p.type==="trun"),l=0;return o.sampleDuration.length?l=o.sampleDuration.reduce((p,d)=>p+d,0):l=n.defaultSampleDuration*o.sampleCount,(Number(u.baseMediaDecodeTime)+l)/e*1e3},JM=a=>{let e={is3dVideo:!1,stereoMode:0,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}},i=new Rt().parse(a),r=new Wt(i);if(r.find("sv3d")){e.is3dVideo=!0;let n=r.find("st3d");n&&(e.stereoMode=n.stereoMode);let u=r.find("prhd");u&&(e.projectionData.pose.yaw=u.poseYawDegrees,e.projectionData.pose.pitch=u.posePitchDegrees,e.projectionData.pose.roll=u.poseRollDegrees);let o=r.find("equi");o&&(e.projectionData.bounds.top=o.projectionBoundsTop,e.projectionData.bounds.right=o.projectionBoundsRight,e.projectionData.bounds.bottom=o.projectionBoundsBottom,e.projectionData.bounds.left=o.projectionBoundsLeft)}return e},Gv={validateData:WM,parseInit:JM,getIndexRange:()=>{},parseSegments:GM,parseFeedableSegmentChunk:zM,getChunkEndTime:XM,getServerLatencyTimestamps:YM,getTimescaleFromIndex:KM};var Ja=C(Ee(),1);import{assertNonNullable as Sc,isNonNullable as Xv,isNullable as eD}from"@vkontakte/videoplayer-shared";import{assertNever as ZM}from"@vkontakte/videoplayer-shared";var zv={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"}},Yv=a=>{let e=a.getUint8(0),t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);let i=Xa(a,t),r=i in zv,s=r?zv[i].type:"binary",n=a.getUint8(t),u=0;n&128?u=1:n&64?u=2:n&32?u=3:n&16?u=4:n&8?u=5:n&4?u=6:n&2?u=7:n&1&&(u=8);let o=new DataView(a.buffer,a.byteOffset+t+1,u-1),l=n&255>>u,c=Xa(o),p=l*2**((u-1)*8)+c,d=t+u,h;return d+p>a.byteLength?h=new DataView(a.buffer,a.byteOffset+d):h=new DataView(a.buffer,a.byteOffset+d,p),{tag:r?i:"0x"+i.toString(16).toUpperCase(),type:s,tagHeaderSize:d,tagSize:d+p,value:h,valueSize:p}},Xa=(a,e=a.byteLength)=>{switch(e){case 1:return a.getUint8(0);case 2:return a.getUint16(0);case 3:return a.getUint8(0)*2**16+a.getUint16(1);case 4:return a.getUint32(0);case 5:return a.getUint8(0)*2**32+a.getUint32(1);case 6:return a.getUint16(0)*2**32+a.getUint32(2);case 7:{let t=a.getUint8(0)*281474976710656+a.getUint16(1)*4294967296+a.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},st=(a,e)=>{switch(e){case"int":return a.getInt8(0);case"uint":return Xa(a);case"float":return a.byteLength===4?a.getFloat32(0):a.getFloat64(0);case"string":return new TextDecoder("ascii").decode(a);case"utf8":return new TextDecoder("utf-8").decode(a);case"date":return new Date(Date.UTC(2001,0)+a.getInt8(0)).getTime();case"master":return a;case"binary":return a;default:ZM(e)}},Ti=(a,e)=>{let t=0;for(;t<a.byteLength;){let i=new DataView(a.buffer,a.byteOffset+t),r=Yv(i);if(!e(r))return;r.type==="master"&&Ti(r.value,e),t=r.value.byteOffset-a.byteOffset+r.valueSize}},Kv=a=>{if(a.getUint32(0)!==440786851)return!1;let e,t,i,r=Yv(a);return Ti(r.value,({tag:s,type:n,value:u})=>(s===17143?e=st(u,n):s===17026?t=st(u,n):s===17029&&(i=st(u,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)};var Jv=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],tD=[231,22612,22743,167,171,163,160,175],iD=a=>{let e,t,i,r,s=!1,n=!1,u=!1,o,l,c=!1,p=0;return Ti(a,({tag:d,type:h,value:f,valueSize:b})=>{if(d===21419){let S=st(f,h);l=Xa(S)}else d!==21420&&(l=void 0);return d===408125543?(e=f.byteOffset,t=f.byteOffset+b):d===357149030?s=!0:d===290298740?n=!0:d===2807729?i=st(f,h):d===17545?r=st(f,h):d===21420&&l===475249515?o=st(f,h):d===374648427?Ti(f,({tag:S,type:g,value:I})=>S===30321?(c=st(I,g)===1,!1):!0):s&&n&&(0,Ja.default)(Jv,d)&&(u=!0),!u}),Sc(e,"Failed to parse webm Segment start"),Sc(t,"Failed to parse webm Segment end"),Sc(r,"Failed to parse webm Segment duration"),i=i??1e6,{segmentStart:Math.round(e/1e9*i*1e3),segmentEnd:Math.round(t/1e9*i*1e3),timeScale:i,segmentDuration:Math.round(r/1e9*i*1e3),cuesSeekPosition:o,is3dVideo:c,stereoMode:p,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},rD=a=>{if(eD(a.cuesSeekPosition))return;let e=a.segmentStart+a.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},aD=(a,e)=>{let t=!1,i=!1,r=u=>Xv(u.time)&&Xv(u.position),s=[],n;return Ti(a,({tag:u,type:o,value:l})=>{switch(u){case 475249515:t=!0;break;case 187:n&&r(n)&&s.push(n),n={};break;case 179:n&&(n.time=st(l,o));break;case 183:break;case 241:n&&(n.position=st(l,o));break;default:t&&(0,Ja.default)(Jv,u)&&(i=!0)}return!(t&&i)}),n&&r(n)&&s.push(n),s.map((u,o)=>{let{time:l,position:c}=u,p=s[o+1];return{status:"none",time:{from:l,to:p?p.time:e.segmentDuration},byte:{from:e.segmentStart+c,to:p?e.segmentStart+p.position-1:e.segmentEnd-1}}})},sD=a=>{let e=0,t=!1;try{Ti(a,i=>i.tag===524531317?i.tagSize<=a.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):(0,Ja.default)(tD,i.tag)?(e+i.tagSize<=a.byteLength&&(e+=i.tagSize,t||=(0,Ja.default)([163,160,175],i.tag)),!0):!1)}catch{}return e>0&&e<=a.byteLength&&t?new DataView(a.buffer,a.byteOffset,e):null},Zv={validateData:Kv,parseInit:iD,getIndexRange:rD,parseSegments:aD,parseFeedableSegmentChunk:sD};var yt=a=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(a);if(e){let[,t,i]=e;if(t==="audio"||t==="video")switch(i){case"webm":return Zv;case"mp4":return Gv}}throw new ReferenceError(`Unsupported mime type ${a}`)};var Tt=a=>a instanceof DOMException&&(a.name==="AbortError"||a.code===20);var wc=C(Iy(),1),jy=C(Qi(),1),Qy=C(Oy(),1),Wy=C(at(),1),Ac=C(rr(),1);var Fy=C(Ee(),1),xc=a=>{let e=a.split("."),[t,...i]=e;if(!t)return!1;switch(t){case"av01":{let[r,s,n]=i;return!!(n&&parseInt(n,10)>8)}case"vp09":{let[r,s,n]=i;return!!(r&&parseInt(r,10)>=2&&n&&parseInt(n,10)>8)}case"avc1":{let r=i[0];if(!r||r.length!==6)return!1;let[s,n]=r.toUpperCase(),u=s+n;return(0,Fy.default)(["6E","7A","F4"],u)}}return!1};import{isNonNullable as sC,isNullable as Uy}from"@vkontakte/videoplayer-shared";var Ny=a=>{if(a.includes("/")){let e=a.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(a)};var qy=a=>{try{let e=aC(),t=a.match(e),{groups:i}=t??{};if(i){let r={};if(i.extensions){let u=i.extensions.toLowerCase().match(/(?:[0-9a-wy-z](?:-[a-z0-9]{2,8})+)/g);Array.from(u||[]).forEach(o=>{r[o[0]]=o.slice(2)})}let s=i.variants?.split(/-/).filter(u=>u!==""),n={extlang:i.extlang,langtag:i.langtag,language:i.language,privateuse:i.privateuse||i.privateuse2,region:i.region,script:i.script,extensions:r,variants:s};return Object.keys(n).forEach(u=>{let o=n[u];(typeof o>"u"||o==="")&&delete n[u]}),n}return null}catch{return null}};function aC(){let a="(?<extlang>(?:[a-z]{3}(?:-[a-z]{3}){0,2}))",e="x(?:-[a-z0-9]{1,8})+",c=`^(?:(?<langtag>${`
|
|
116
|
+
[selected audio track] ${T?.id}
|
|
117
|
+
`}),T};var Se=a=>new URL(a).hostname;import{assertNever as GS,assertNonNullable as WS,combine as j$,debounce as H$,ErrorCategory as zS,filter as YS,filterChanged as Q$,isNonNullable as fc,map as Jn,merge as KS,observableFrom as G$,once as W$,Subscription as z$,ValueSubject as mc,videoQualityToHeight as XS,videoSizeToQuality as Y$}from"@vkontakte/videoplayer-shared";var US=C(at(),1);var _S=C(Ee(),1),VS=a=>{if(a instanceof DOMException&&(0,_S.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(!VS(i))return!1;if(e&&e(),t)return console.warn(i),!1;a.muted=!0;try{await a.play()}catch(r){return VS(r)&&(a.muted=!1,console.warn(r)),!1}}return!0};import{isNonNullable as Kn,isNullable as w$,assertNonNullable as va}from"@vkontakte/videoplayer-shared";var FS=C(sr(),1);import{isNonNullable as OS,assertNonNullable as Yn,now as E$}from"@vkontakte/videoplayer-shared";function fe(){return E$()}function cc(a){return fe()-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,u,o=!1)=>{r(n)||(n.startsWith("/")||(n="/"+n),n=t+n);let l=n.indexOf("?")>-1?"&":"?";return o&&(n+=l+"lowLat=1",l="&"),u&&(n+=l+"_rnd="+Math.floor(999999999*Math.random())),n}}}function NS(a,e,t){let i=(...r)=>{t.apply(null,r),a.removeEventListener(e,i)};a.addEventListener(e,i)}function dr(a,e,t,i){let r=window.XMLHttpRequest,s,n,u,o=!1,l=0,d,h,c=!1,p="arraybuffer",f=7e3,b=2e3,S=()=>{if(o)return;Yn(d);let M=cc(d),v;if(M<b){v=b-M,setTimeout(S,v);return}b*=2,b>f&&(b=f),n&&n.abort(),n=new r,k()},g=M=>(s=M,q),T=M=>(h=M,q),E=()=>(p="json",q),y=()=>{if(!o){if(--l>=0){S(),i&&i();return}o=!0,h&&h(),t&&t()}},w=M=>(c=M,q),k=()=>{d=fe(),n=new r,n.open("get",a);let M=0,v,x=0,z=()=>(Yn(d),Math.max(d,Math.max(v||0,x||0)));if(s&&n.addEventListener("progress",D=>{let j=fe();s.updateChunk&&D.loaded>M&&(s.updateChunk(z(),D.loaded-M),M=D.loaded,v=j)}),u&&(n.timeout=u,n.addEventListener("timeout",()=>y())),n.addEventListener("load",()=>{if(o)return;Yn(n);let D=n.status;if(D>=200&&D<300){let{response:j,responseType:J}=n,ie=j?.byteLength;if(typeof ie=="number"&&s){let ue=ie-M;ue&&s.updateChunk&&s.updateChunk(z(),ue)}J==="json"&&(!j||!(0,FS.default)(j).length)?y():(h&&h(),e(j))}else y()}),n.addEventListener("error",()=>{y()}),c){let D=()=>{Yn(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(x=fe(),n.removeEventListener("readystatechange",D))};n.addEventListener("readystatechange",D)}return n.responseType=p,n.send(),q},q={withBitrateReporting:g,withParallel:w,withJSONResponse:E,withRetryCount:M=>(l=M,q),withRetryInterval:(M,v)=>(OS(M)&&(b=M),OS(v)&&(f=v),q),withTimeout:M=>(u=M,q),withFinally:T,send:k,abort:()=>{n&&(n.abort(),n=void 0),o=!0,h&&h()}};return q}var ga=class{constructor(e){this.intervals=[];this.currentRate=0;this.logger=e}_updateRate(e){let t=.2;this.currentRate&&(e<this.currentRate*.1?t=.8:e<this.currentRate*.5?t=.5:e<this.currentRate*.7&&(t=.3)),e=Math.max(1,Math.min(e,100*1024*1024)),this.currentRate=this.currentRate?this.currentRate*(1-t)+e*t:e}_createInterval(e,t,i){return{start:e,end:t,bytes:i}}_doMergeIntervals(e,t){e.start=Math.min(t.start,e.start),e.end=Math.max(t.end,e.end),e.bytes+=t.bytes}_mergeIntervals(e,t){return e.start<=t.end&&t.start<=e.end?(this._doMergeIntervals(e,t),!0):!1}_flushIntervals(){if(!this.intervals.length)return!1;let e=this.intervals[0].start,t=this.intervals[this.intervals.length-1].end-500;if(t-e>2e3){let i=0,r=0;for(;this.intervals.length>0;){let s=this.intervals[0];if(s.end<=t)i+=s.end-s.start,r+=s.bytes,this.intervals.splice(0,1);else{if(s.start>=t)break;{let n=t-s.start,u=s.end-s.start;i+=n;let o=s.bytes*n/u;r+=o,s.start=t,s.bytes-=o}}}if(r>0&&i>0){let s=r*8/(i/1e3);return this._updateRate(s),this.logger(`rate updated, new=${Math.round(s/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(r)}/${Math.round(i)} interval=${Math.round(t-e)}`),!0}}return!1}_joinIntervals(){let e;do{e=!1;for(let t=0;t<this.intervals.length-1;++t)this._mergeIntervals(this.intervals[t],this.intervals[t+1])&&(this.intervals.splice(t+1,1),e=!0)}while(e)}addInterval(e,t,i){return this.intervals.push(this._createInterval(e,t,i)),this._joinIntervals(),this.intervals.length>100&&(this.logger(`too many intervals (${this.intervals.length}); will merge`,{type:"warn"}),this._doMergeIntervals(this.intervals[1],this.intervals[0]),this.intervals.splice(0,1)),this._flushIntervals()}getBitRate(){return this.currentRate}};var qS=C(sr(),1);var Sa=class{constructor(e,t,i,r,s){this.pendingQueue=[];this.activeRequests={};this.completeRequests={};this.averageSegmentDuration=2e3;this.lastPrefetchStart=0;this.throttleTimeout=null;this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=i,this.MAX_PARALLEL_REQUESTS=r,this.logger=s}limitCompleteCount(){let e;for(;(e=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){let t=e[Math.floor(Math.random()*e.length)];this.logger(`Dropping completed request for url ${t}`,{type:"warn"}),delete this.completeRequests[t]}}_sendRequest(e,t){let i=fe(),r=o=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=o,e._errorCB?e._errorCB(o):(this.limitCompleteCount(),this.completeRequests[t]=e)},s=o=>{e._complete=1,e._responseData=o,e._downloadTime=fe()-i,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(o,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},n=()=>{e._finallyCB&&e._finallyCB()},u=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=dr(t,s,()=>r("error"),u),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally(n),this.activeRequests[t]=e,e._request.send(),this.lastPrefetchStart=fe()}_getParallelRequestCount(){return Math.min(this.MAX_PARALLEL_REQUESTS,this.averageSegmentDuration<3e3?3:2)}_getPrefetchDelay(){return Math.max(100,Math.min(5e3,this.averageSegmentDuration/3))}_canSendPending(){let e=this._getParallelRequestCount(),t=fe();if(Object.keys(this.activeRequests).length>=e)return!1;let i=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),i>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),i),!1):!0}_sendPending(){for(;this._canSendPending();){let e=this.pendingQueue.pop();if(e){if(this.activeRequests[e]||this.completeRequests[e])continue;this.logger(`Submitting pending request url=${e}`),this._sendRequest({},e)}else return}}_removeFromActive(e){delete this.completeRequests[e],delete this.activeRequests[e]}abortAll(){(0,qS.default)(this.activeRequests).forEach(e=>{e&&e._request&&e._request.abort()}),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,i,r){let s={};return s.send=()=>{let n=this.activeRequests[e]||this.completeRequests[e];if(n)n._cb=t,n._errorCB=i,n._retryCB=r,n._finallyCB=s._finallyCB,n._error||n._complete?(this._removeFromActive(e),setTimeout(()=>{n._complete?(this.logger(`Requested url already prefetched, url=${e}`),t(n._responseData,n._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${e}`),i(n._errorMsg)),s._finallyCB&&s._finallyCB()},0)):this.logger(`Attached to active request, url=${e}`);else{let u=this.pendingQueue.indexOf(e);u!==-1&&this.pendingQueue.splice(u,1),this.logger(`Request not prefetched, starting new request, url=${e}${u===-1?"":"; removed pending"}`),this._sendRequest(s,e)}},s._cb=t,s._errorCB=i,s._retryCB=r,s.abort=function(){s.request&&s.request.abort()},s.withFinally=n=>(s._finallyCB=n,s),s}prefetch(e){this.activeRequests[e]||this.completeRequests[e]?this.logger(`Request already active for url=${e}`):(this.logger(`Added to pending queue; url=${e}`),this.pendingQueue.unshift(e),this._sendPending())}optimizeForSegDuration(e){this.averageSegmentDuration=e}};import{Subject as A$}from"@vkontakte/videoplayer-shared";var Xn=1e4,pc=3;var P$=6e4,R$=10,k$=1,L$=500,ya=class{constructor(e){this.paused=!1;this.autoQuality=!0;this.autoQualityLimits=void 0;this.buffering=!0;this.destroyed=!1;this.videoPlayStarted=!1;this.lowLatency=!1;this.bitrate=0;this.manifest=[];this.sourceBuffer=0;this.bufferStates=[];this.sourceJitter=-1;this.waitingForFirstBufferAfterSrcChange=!1;this.params=e,this.soundProhibitedEvent$=new A$,this.chunkRateEstimator=new ga(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",()=>{!!e.error&&!this.destroyed&&(t(`Video element error: ${e.error?.code}, details: ${e.error?.message}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{let i=this._getBufferSizeSec();!this.paused&&i<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(i+.1)*1e3)):this.buffering&&this.videoPlayStarted&&this._notifyBuffering(!1)}),e.addEventListener("playing",()=>{t("playing")}),e.addEventListener("stalled",()=>this._fixupStall()),e.addEventListener("waiting",()=>this._fixupStall())}_fixupStall(){let{logger:e,videoElement:t}=this.params,i=t.buffered.length,r;i!==0&&!this.waitingForFirstBufferAfterSrcChange&&(r=t.buffered.start(i-1),t.currentTime<r&&(e("Fixup stall"),t.currentTime=r))}_selectQuality(e){let{videoElement:t}=this.params,i,r,s,n=t&&1.62*(B.display.pixelRatio||1)*t.offsetHeight||520;for(let u=0;u<this.manifest.length;++u){s=this.manifest[u];let{max:o,min:l}=this.autoQualityLimits||{};!AS({limits:this.autoQualityLimits,highestAvailableHeight:this.manifest[0].video.height,lowestAvailableHeight:(0,US.default)(this.manifest,-1).video.height})&&(o&&s.video.height>o||l&&s.video.height<l)||(s.bitrate<e&&n>Math.min(s.video.height,s.video.width)?(!r||s.bitrate>r.bitrate)&&(r=s):(!i||i.bitrate>s.bitrate)&&(i=s))}return r||i}shouldPlay(){if(this.paused)return!1;let t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||Kn(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){let{logger:i,videoElement:r,playerCallback:s}=this.params;this.mediaSource=new window.MediaSource,i("setting video src"),r.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.videoPlayStarted=!1,r.addEventListener("canplay",()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});let n=()=>{NS(r,"progress",()=>{r.buffered.length?(r.currentTime=r.buffered.start(0),this.waitingForFirstBufferAfterSrcChange=!1,s({name:"playing"})):n()})};this.waitingForFirstBufferAfterSrcChange=!0,n()}_initPlayerWith(e){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new Sa(pc,Xn,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){let{logger:t,videoElement:i,playerCallback:r}=this.params,s=!1,n=null,u=null,o=null,l=null,d=!1,h=()=>{let y=s&&(!d||d===this.rep);return y||t("Not running!"),y},c=(y,w,k)=>{o&&o.abort(),o=dr(this.urlResolver.resolve(y,!1),w,k,()=>this._retryCallback()).withTimeout(Xn).withBitrateReporting(this.bitrateSwitcher).withRetryCount(pc).withFinally(()=>{o=null}).send()},p=(y,w,k)=>{va(this.filesFetcher),u?.abort(),u=this.filesFetcher.requestData(this.urlResolver.resolve(y,!1),w,k,()=>this._retryCallback()).withFinally(()=>{u=null}).send()},f=y=>{let w=i.playbackRate;i.playbackRate!==y&&(t(`Playback rate switch: ${w}=>${y}`),i.playbackRate=y)},b=y=>{this.lowLatency=y,t(`lowLatency changed to ${y}`),S()},S=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)f(1);else{let y=this._getBufferSizeSec();if(this.bufferStates.length<5){f(1);return}let k=fe()-1e4,$=0;for(let L=0;L<this.bufferStates.length;L++){let I=this.bufferStates[L];y=Math.min(y,I.buf),I.ts<k&&$++}this.bufferStates.splice(0,$),t(`update playback rate; minBuffer=${y} drop=${$} jitter=${this.sourceJitter}`);let A=y-k$;this.sourceJitter>=0?A-=this.sourceJitter/2:this.sourceJitter-=1,A>3?f(1.15):A>1?f(1.1):A>.3?f(1.05):f(1)}},g=y=>{let w,k=()=>w&&w.start?w.start.length:0,$=D=>w.start[D]/1e3,A=D=>w.dur[D]/1e3,L=D=>w.fragIndex+D,I=(D,j)=>({chunkIdx:L(D),startTS:$(D),dur:A(D),discontinuity:j}),q=()=>{let D=0;if(w&&w.dur){let j=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,J=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,ie=j;this.sourceJitter>1&&(ie+=this.sourceJitter-1);let ue=w.dur.length-1;for(;ue>=0&&(ie-=w.dur[ue],!(ie<=0));--ue);D=Math.min(ue,w.dur.length-1-J),D=Math.max(D,0)}return I(D,!0)},M=D=>{let j=k();if(!(j<=0)){if(Kn(D)){for(let J=0;J<j;J++)if($(J)>D)return I(J)}return q()}},v=D=>{let j=k(),J=D?D.chunkIdx+1:0,ie=J-w.fragIndex;if(!(j<=0)){if(!D||ie<0||ie-j>R$)return t(`Resync: offset=${ie} bChunks=${j} chunk=`+JSON.stringify(D)),q();if(!(ie>=j))return I(J-w.fragIndex,!1)}},x=(D,j,J)=>{l&&l.abort(),l=dr(this.urlResolver.resolve(D,!0,this.lowLatency),j,J,()=>this._retryCallback()).withTimeout(Xn).withRetryCount(pc).withFinally(()=>{l=null}).withJSONResponse().send()};return{seek:(D,j)=>{x(y,J=>{if(!h())return;w=J;let ie=!!w.lowLatency;ie!==this.lowLatency&&b(ie);let ue=0;for(let me=0;me<w.dur.length;++me)ue+=w.dur[me];ue>0&&(va(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(ue/w.dur.length)),r({name:"index",zeroTime:w.zeroTime,shiftDuration:w.shiftDuration}),this.sourceJitter=w.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,w.jitter/1e3)):1,D(M(j))},()=>this._handleNetworkError())},nextChunk:v}},T=()=>{s=!1,u&&u.abort(),o&&o.abort(),l&&l.abort(),va(this.filesFetcher),this.filesFetcher.abortAll()};return d={start:y=>{let{videoElement:w,logger:k}=this.params,$=g(e.jidxUrl),A,L,I,q,M=0,v,x,z,D=()=>{v&&(clearTimeout(v),v=void 0);let U=Math.max(L$,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),Le=M+U,Te=fe(),de=Math.min(1e4,Le-Te);M=Te;let Ge=()=>{l||h()&&$.seek(()=>{h()&&(M=fe(),j(),D())})};de>0?v=window.setTimeout(()=>{this.paused?D():Ge()},de):Ge()},j=()=>{let U;for(;U=$.nextChunk(q);)q=U,be(U);let Le=$.nextChunk(I);if(Le){if(I&&Le.discontinuity){k("Detected discontinuity; restarting playback"),this.paused?D():(T(),this._initPlayerWith(e));return}me(Le)}else D()},J=(U,Le)=>{if(!h()||!this.sourceBuffer)return;let Te,de,Ge,Bt=lt=>{window.setTimeout(()=>{h()&&J(U,Le)},lt)};if(this.sourceBuffer.updating)k("Source buffer is updating; delaying appendBuffer"),Bt(100);else{let lt=fe(),Oe=w.currentTime;!this.paused&&w.buffered.length>1&&x===Oe&<-z>500&&(k("Stall suspected; trying to fix"),this._fixupStall()),x!==Oe&&(x=Oe,z=lt);let Vt=this._getBufferSizeSec();if(Vt>30)k(`Buffered ${Vt} seconds; delaying appendBuffer`),Bt(2e3);else try{this.sourceBuffer.appendBuffer(U),this.videoPlayStarted?(this.bufferStates.push({ts:lt,buf:Vt}),S(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),Le&&Le()}catch(ct){if(ct.name==="QuotaExceededError")k("QuotaExceededError; delaying appendBuffer"),Ge=this.sourceBuffer.buffered.length,Ge!==0&&(Te=this.sourceBuffer.buffered.start(0),de=Oe,de-Te>4&&this.sourceBuffer.remove(Te,de-3)),Bt(1e3);else throw ct}}},ie=()=>{L&&A&&(k([`Appending chunk, sz=${L.byteLength}:`,JSON.stringify(I)]),J(L,function(){L=null,j()}))},ue=U=>e.fragUrlTemplate.replace("%%id%%",U.chunkIdx),me=U=>{h()&&p(ue(U),(Le,Te)=>{if(h()){if(Te/=1e3,L=Le,I=U,n=U.startTS,Te){let de=Math.min(10,U.dur/Te);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*de:de}ie()}},()=>this._handleNetworkError())},be=U=>{h()&&(va(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(ue(U),!1)))},H=U=>{h()&&(e.cachedHeader=U,J(U,()=>{A=!0,ie()}))};s=!0,$.seek(U=>{if(h()){if(M=fe(),!U){D();return}q=U,!w$(y)||U.startTS>y?me(U):(I=U,j())}},y),e.cachedHeader?H(e.cachedHeader):c(e.headerUrl,H,()=>this._handleNetworkError())},stop:T,getTimestampSec:()=>n},d}_switchToQuality(e){let{logger:t,playerCallback:i}=this.params,r;e.bitrate!==this.bitrate&&(this.rep&&(r=this.rep.getTimestampSec(),Kn(r)&&(r+=.1),this.rep.stop()),this.currentManifestEntry=e,this.rep=this._representation(e),t(`switch to quality: codecs=${e.codecs}; headerUrl=${e.headerUrl}; bitrate=${e.bitrate}`),this.bitrate=e.bitrate,va(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(r),i({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return Kn(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,i=h=>{if(!this.autoQuality)return;let c,p,f;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&h<this.bitrate&&(p=this._getBufferSizeSec(),f=h/this.bitrate,p>10&&f>.8||p>15&&f>.5||p>20&&f>.3)){e(`Not switching: buffer=${Math.floor(p)}; bitrate=${this.bitrate}; newRate=${Math.floor(h)}`);return}c=this._selectQuality(h),c?this._switchToQuality(c):e(`Could not find quality by bitrate ${h}`)},s={updateChunk:(c,p)=>{let f=fe();if(this.chunkRateEstimator.addInterval(c,f,p)){let S=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:p,duration:f-c,speed:S}),!0}},get:()=>{let c=this.chunkRateEstimator.getBitRate();return c?c*.85:0}},n=-1/0,u,o=!0,l=()=>{let h=s.get();if(h&&u&&this.autoQuality){if(o&&h>u&&cc(n)<3e4)return;i(h)}o=this.autoQuality};return{updateChunk:(h,c)=>{let p=s.updateChunk(h,c);return p&&l(),p},notifySwitch:h=>{let c=fe();h<u&&(n=c),u=h}}}_fetchManifest(e,t,i){this.manifestRequest=dr(this.urlResolver.resolve(e,!0),t,i,()=>this._retryCallback()).withJSONResponse().withTimeout(Xn).withRetryCount(this.params.config.manifestRetryMaxCount).withRetryInterval(this.params.config.manifestRetryInterval,this.params.config.manifestRetryMaxInterval).send().withFinally(()=>{this.manifestRequest=void 0})}_playVideoElement(){let{videoElement:e}=this.params;_e(e,()=>{this.soundProhibitedEvent$.next()}).then(t=>{t||(this.params.liveOffset.pause(),this.params.videoState.setState("paused"))})}_handleManifestUpdate(e){let{logger:t,playerCallback:i,videoElement:r}=this.params,s=n=>{let u=[];return n?.length?(n.forEach((o,l)=>{o.video&&r.canPlayType(o.codecs).replace(/no/,"")&&window.MediaSource?.isTypeSupported?.(o.codecs)&&(o.index=l,u.push(o))}),u.sort(function(o,l){return o.video&&l.video?l.video.height-o.video.height:l.bitrate-o.bitrate}),u):(i({name:"error",type:"empty_manifest"}),[])};this.manifest=s(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),i({name:"manifest",manifest:this.manifest})}_refetchManifest(e){this.destroyed||(this.manifestRefetchTimer&&clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=window.setTimeout(()=>{this._fetchManifest(e,t=>{this.destroyed||(this._handleManifestUpdate(t),this._refetchManifest(e))},()=>this._refetchManifest(e))},P$))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};var QS=C(Wi(),1);import{debounce as $$,filter as jS,fromEvent as M$,interval as D$,isHigher as C$,isInvariantQuality as B$,isLower as V$,merge as _$,Subject as HS,Subscription as O$}from"@vkontakte/videoplayer-shared";var hc=class{constructor(){this.onDroopedVideoFramesLimit$=new HS;this.subscription=new O$;this.playing=!1;this.tracks=[];this.forceChecker$=new HS;this.isForceCheckCounter=0;this.prevTotalVideoFrames=0;this.prevDroppedVideoFrames=0;this.limitCounts={};this.handleChangeVideoQuality=()=>{let e=this.tracks.find(({size:t})=>t?.height===this.video.videoHeight&&t?.width===this.video.videoWidth);e&&!B$(e.quality)&&this.onChangeQuality(e.quality)};this.checkDroppedFrames=()=>{let{totalVideoFrames:e,droppedVideoFrames:t}=this.video.getVideoPlaybackQuality(),i=e-this.prevTotalVideoFrames,r=t-this.prevDroppedVideoFrames,s=1-(i-r)/i;!isNaN(s)&&s>0&&this.log({message:`[dropped]. current dropped percent: ${s}, limit: ${this.droppedFramesChecker.percentLimit}`}),!isNaN(s)&&s>=this.droppedFramesChecker.percentLimit&&C$(this.currentQuality,this.droppedFramesChecker.minQualityBanLimit)&&(this.limitCounts[this.currentQuality]=(this.limitCounts[this.currentQuality]??0)+1,this.maxQualityLimit=this.getMaxQualityLimit(this.currentQuality),this.currentTimer&&window.clearTimeout(this.currentTimer),this.currentTimer=window.setTimeout(()=>this.maxQualityLimit=this.getMaxQualityLimit(),this.droppedFramesChecker.qualityUpWaitingTime),this.onDroopedVideoFramesLimitTrigger()),this.savePrevFrameCounts(e,t)}}connect(e){this.log=e.logger.createComponentLog("DroppedFramesManager"),this.video=e.video,this.isAuto=e.isAuto,this.tracks=e.tracks,this.droppedFramesChecker=e.droppedFramesChecker,this.subscription.add(e.playing$.subscribe(()=>this.playing=!0)),this.subscription.add(e.pause$.subscribe(()=>this.playing=!1)),this.isEnabled&&this.subscribe()}destroy(){this.currentTimer&&window.clearTimeout(this.currentTimer),this.subscription.unsubscribe()}get droppedVideoMaxQualityLimit(){return this.maxQualityLimit}subscribe(){this.subscription.add(M$(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=D$(this.droppedFramesChecker.checkTime).pipe(jS(()=>this.playing),jS(()=>{let r=!!this.isForceCheckCounter;return r&&(this.isForceCheckCounter-=1),!r})),t=this.forceChecker$.pipe($$(this.droppedFramesChecker.checkTime)),i=_$(e,t);this.subscription.add(i.subscribe(this.checkDroppedFrames))}onChangeQuality(e){this.currentQuality=e;let{totalVideoFrames:t,droppedVideoFrames:i}=this.video.getVideoPlaybackQuality();this.savePrevFrameCounts(t,i),this.isForceCheckCounter=this.droppedFramesChecker.tickCountAfterQualityChange,this.forceChecker$.next()}onDroopedVideoFramesLimitTrigger(){this.isAuto.getState()&&(this.log({message:`[onDroopedVideoFramesLimit]. maxQualityLimit: ${this.maxQualityLimit}`}),this.onDroopedVideoFramesLimit$.next())}getMaxQualityLimit(e){let t=(0,QS.default)(this.limitCounts).filter(([,i])=>i>=this.droppedFramesChecker.countLimit).sort(([i],[r])=>V$(i,r)?-1:1)?.[0]?.[0];return e??t}get isEnabled(){return this.droppedFramesChecker.enabled&&this.isDroppedFramesCheckerSupport}get isDroppedFramesCheckerSupport(){return!!this.video&&typeof this.video.getVideoPlaybackQuality=="function"}savePrevFrameCounts(e,t){this.prevTotalVideoFrames=e,this.prevDroppedVideoFrames=t}},pr=hc;import{map as F$,Observable as N$}from"@vkontakte/videoplayer-shared";import{fromEvent as q$}from"@vkontakte/videoplayer-shared";var Ta=()=>!!window.documentPictureInPicture?.window||!!document.pictureInPictureElement;var U$=(a,e)=>new N$(t=>{if(!window.IntersectionObserver)return;let i={root:null},r=new IntersectionObserver((n,u)=>{n.forEach(o=>t.next(o.isIntersecting||Ta()))},{...i,...e});r.observe(a);let s=q$(document,"visibilitychange").pipe(F$(n=>!document.hidden||Ta())).subscribe(n=>t.next(n));return()=>{r.unobserve(a),s.unsubscribe()}}),Ke=U$;var K$=["paused","playing","ready"],X$=["paused","playing","ready"],Ia=class{constructor(e){this.subscription=new z$;this.videoState=new F("stopped");this.representations$=new mc([]);this.droppedFramesManager=new pr;this.maxSeekBackTime$=new mc(1/0);this.zeroTime$=new mc(void 0);this.liveOffset=new vi;this._dashCb=e=>{switch(e.name){case"buffering":{let t=e.isBuffering;this.params.output.isBuffering$.next(t);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${e.type}`,category:zS.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{let t=e.manifest,i=[];for(let r of t){let s=r.name??r.index.toString(10),n=Ht(r.name)??Y$(r.video),u=r.bitrate/1e3,o={...r.video};if(!n)continue;let l={id:s,quality:n,bitrate:u,size:o};i.push({track:l,representation:r})}this.representations$.next(i),this.params.output.availableVideoTracks$.next(i.map(({track:r})=>r)),this.videoState.getTransition()?.to==="manifest_ready"&&this.videoState.setState("manifest_ready");break}case"qualitySwitch":{let t=e.quality,i=this.representations$.getValue().find(({representation:r})=>r===t)?.track;this.params.output.hostname$.next(new URL(t.headerUrl,this.params.source.url).hostname),fc(i)&&this.params.output.currentVideoTrack$.next(i);break}case"bandwidth":{let{size:t,duration:i}=e;this.params.dependencies.throughputEstimator.addRawSpeed(t,i);break}case"index":{this.maxSeekBackTime$.next(e.shiftDuration||0),this.zeroTime$.next(e.zeroTime);break}}};this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; seekState: ${JSON.stringify(s)};`}),i==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState("stopped"));return}if(t)return;let n=this.params.desiredState.videoTrack.getTransition(),u=this.params.desiredState.autoVideoTrackSwitching.getTransition();if((0,bc.default)(X$,e)&&(n||u)){this.prepare();return}if(r?.to!=="paused"&&s.state==="requested"&&(0,bc.default)(K$,e)){this.seek(s.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(se(this.params.source.url));return;case"manifest_ready":this.videoState.startTransitionTo("ready"),this.prepare();break;case"ready":if(i==="paused")this.videoState.setState("paused");else if(i==="playing"){this.videoState.startTransitionTo("playing");let o=r?.from;o&&o==="ready"&&this.dash.catchUp(),this.dash.play()}return;case"playing":i==="paused"&&(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.dash.pause());return;case"paused":if(i==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.dash.play(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let o=this.liveOffset.getTotalOffset();o>=this.maxSeekBackTime$.getValue()&&(o=0,this.liveOffset.resetTo(o)),this.liveOffset.resume(),this.params.output.position$.next(-o/1e3),this.dash.reinit(se(this.params.source.url,o))}return;default:return GS(e)}};this.textTracksManager=new Ye(e.source.url),this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=r=>{e.output.error$.next({id:"DashLiveProvider",category:zS.WTF,message:"DashLiveProvider internal logic error",thrown:r})};this.subscription.add(KS(this.videoState.stateChangeStarted$.pipe(Jn(r=>({transition:r,type:"start"}))),this.videoState.stateChangeEnded$.pipe(Jn(r=>({transition:r,type:"end"})))).subscribe(({transition:r,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(r)}`})})),this.video=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(Se(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);let i=Ve(this.video);this.subscription.add(()=>i.destroy()),this.subscription.add(this.representations$.pipe(Jn(r=>r.map(({track:s})=>s)),YS(r=>!!r.length),W$()).subscribe(r=>this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks:r}))),this.subscription.add(i.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready")},t)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused")},t)).add(i.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.videoState.setState("playing")},t)).add(i.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(Q$(),Jn(r=>-r/1e3)).subscribe(this.params.output.duration$)).add(j$({zeroTime:this.zeroTime$.pipe(YS(fc)),position:i.timeUpdate$}).subscribe(({zeroTime:r,position:s})=>this.params.output.liveTime$.next(r+s*1e3),t)).add(mt(this.video,this.params.desiredState.isLooped,t)).add(Be(this.video,this.params.desiredState.volume,i.volumeState$,t)).add(i.volumeState$.subscribe(this.params.output.volume$,t)).add(ze(this.video,this.params.desiredState.playbackRate,i.playbackRateState$,t)).add(i.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(i.loadedMetadata$.subscribe(this.params.output.loadedMetadataEvent$)).add(i.playing$.subscribe(this.params.output.firstFrameEvent$)).add(i.canplay$.subscribe(this.params.output.canplay$)).add(i.inPiP$.subscribe(this.params.output.inPiP$)).add(i.inFullscreen$.subscribe(this.params.output.inFullscreen$)).add(Ke(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:r,min:s}})=>{this.dash.setAutoQualityLimits({max:r&&XS(r),min:s&&XS(s)}),this.params.output.autoVideoTrackLimits$.next({max:r,min:s})})).add(this.videoState.stateChangeEnded$.subscribe(r=>{switch(r.to){case"stopped":this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState("stopped");break;case"manifest_ready":case"ready":this.params.desiredState.playbackState.getTransition()?.to==="ready"&&this.params.desiredState.playbackState.setState("ready");break;case"paused":this.params.desiredState.playbackState.setState("paused");break;case"playing":this.params.desiredState.playbackState.setState("playing");break;default:return GS(r.to)}},t)).add(KS(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,G$(["init"])).pipe(H$(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 ya({videoElement:this.video,videoState:this.videoState,playbackState:this.params.desiredState.playbackState,liveOffset:this.liveOffset,config:{maxParallelRequests:this.params.config.maxParallelRequests,minBuffer:this.params.tuning.live.minBuffer,minBufferSegments:this.params.tuning.live.minBufferSegments,lowLatencyMinBuffer:this.params.tuning.live.lowLatencyMinBuffer,lowLatencyMinBufferSegments:this.params.tuning.live.lowLatencyMinBufferSegments,isLiveCatchUpMode:this.params.tuning.live.isLiveCatchUpMode,manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},playerCallback:this._dashCb,logger:t=>{this.params.dependencies.logger.log({message:String(t),component:"LiveDashPlayer"})}});return e.pause(),e}prepare(){let e=this.representations$.getValue(),t=this.params.desiredState.videoTrack.getTransition()?.to??this.params.desiredState.videoTrack.getState(),i=this.params.desiredState.autoVideoTrackSwitching.getTransition()?.to??this.params.desiredState.autoVideoTrackSwitching.getState(),r=!i&&fc(t)?t:St(e.map(({track:l})=>l),{container:this.video.getBoundingClientRect(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),s=r?.id,n=this.params.desiredState.videoTrack.getTransition(),u=this.params.desiredState.videoTrack.getState()?.id,o=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(r&&(n||s!==u)&&this.setVideoTrack(r),o&&this.setAutoQuality(i),n||o||s!==u){let l=e.find(({track:d})=>d.id===s)?.representation;WS(l,"Representations missing"),this.dash.startPlay(l,i)}}setVideoTrack(e){let t=this.representations$.getValue().find(({track:i})=>i.id===e.id)?.representation;WS(t,`No such representation ${e.id}`),this.dash.switchByName(t.name),this.params.desiredState.videoTrack.setState(e)}setAutoQuality(e){this.dash.setAutoQualityEnabled(e),this.params.desiredState.autoVideoTrackSwitching.setState(e)}seek(e){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),i=this.videoState.getState(),r=t==="paused"&&i==="paused",s=-e,n=s<=this.maxSeekBackTime$.getValue()?s:0;this.params.output.position$.next(e/1e3),this.dash.reinit(se(this.params.source.url,n)),r&&this.dash.pause(),this.liveOffset.resetTo(n,r)}};var JS=Ia;var gT=C(Ee(),1);var ve=(a,e)=>{let t=0;for(let i=0;i<a.length;i++){let r=a.start(i)*1e3,s=a.end(i)*1e3;r<=e&&e<=s&&(t=s)}return Math.max(t-e,0)};import{assertNever as UC,assertNonNullable as jC,combine as HC,debounce as QC,ErrorCategory as fT,filter as Zc,filterChanged as ls,fromEvent as GC,isNonNullable as mT,isNullable as WC,map as cs,merge as ds,observableFrom as Ro,once as bT,Subscription as zC}from"@vkontakte/videoplayer-shared";var{NativeAbortSignal:kU,NativeAbortController:LU}=function(a){return{NativeAbortSignal:a.AbortSignal,NativeAbortController:a.AbortController}}(typeof self<"u"?self:global);function ZS(a){let e;try{e=new Event("abort")}catch{typeof document<"u"?document.createEvent?(e=document.createEvent("Event"),e.initEvent("abort",!1,!1)):(e=document.createEventObject(),e.type="abort"):e={type:"abort",bubbles:!1,cancelable:!1}}return e.reason=a,e}function ev(a){if(a===void 0)if(typeof document>"u")a=new Error("This operation was aborted"),a.name="AbortError";else try{a=new DOMException("signal is aborted without reason"),Object.defineProperty(a,"name",{value:"AbortError"})}catch{a=new Error("This operation was aborted"),a.name="AbortError"}return a}var Zn=class{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,i){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:i})}removeEventListener(e,t){if(!(e in this.listeners))return;let i=this.listeners[e];for(let r=0,s=i.length;r<s;r++)if(i[r].callback===t){i.splice(r,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;let i=this.listeners[e.type].slice();for(let r=0,s=i.length;r<s;r++){let n=i[r];try{n.callback.call(this,e)}catch(u){Promise.resolve().then(()=>{throw u})}n.options&&n.options.once&&this.removeEventListener(e.type,n.callback)}return!e.defaultPrevented}},hr=class extends Zn{constructor(){super(),this.listeners||Zn.call(this),Object.defineProperty(this,"aborted",{value:!1,writable:!0,configurable:!0}),Object.defineProperty(this,"onabort",{value:null,writable:!0,configurable:!0}),Object.defineProperty(this,"reason",{value:void 0,writable:!0,configurable:!0})}toString(){return"[object AbortSignal]"}dispatchEvent(e){e.type==="abort"&&(this.aborted=!0,typeof this.onabort=="function"&&this.onabort.call(this,e)),super.dispatchEvent(e)}throwIfAborted(){let{aborted:e,reason:t="Aborted"}=this;if(e)throw t}static timeout(e){let t=new Ti;return setTimeout(()=>t.abort(new DOMException(`This signal is timeout in ${e}ms`,"TimeoutError")),e),t.signal}static any(e){let t=new Ti;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}},Ti=class{constructor(){Object.defineProperty(this,"signal",{value:new hr,writable:!0,configurable:!0})}abort(e){let t=ev(e),i=ZS(t);this.signal.reason=t,this.signal.dispatchEvent(i)}toString(){return"[object AbortController]"}};typeof Symbol<"u"&&Symbol.toStringTag&&(Ti.prototype[Symbol.toStringTag]="AbortController",hr.prototype[Symbol.toStringTag]="AbortSignal");function eo(a){return a.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof a.Request=="function"&&!a.Request.prototype.hasOwnProperty("signal")||!a.AbortController}function gc(a){typeof a=="function"&&(a={fetch:a});let{fetch:e,Request:t=e.Request,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r=!1}=a;if(!eo({fetch:e,Request:t,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r}))return{fetch:e,Request:s};let s=t;(s&&!s.prototype.hasOwnProperty("signal")||r)&&(s=function(l,d){let h;d&&d.signal&&(h=d.signal,delete d.signal);let c=new t(l,d);return h&&Object.defineProperty(c,"signal",{writable:!1,enumerable:!1,configurable:!0,value:h}),c},s.prototype=t.prototype);let n=e;return{fetch:(o,l)=>{let d=s&&s.prototype.isPrototypeOf(o)?o.signal:l?l.signal:void 0;if(d){let h;try{h=new DOMException("Aborted","AbortError")}catch{h=new Error("Aborted"),h.name="AbortError"}if(d.aborted)return Promise.reject(h);let c=new Promise((p,f)=>{d.addEventListener("abort",()=>f(h),{once:!0})});return l&&l.signal&&delete l.signal,Promise.race([c,n(o,l)])}return n(o,l)},Request:s}}var J$=()=>"fetch"in window,Ea=J$()&&eo({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),tv=Ea?gc({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,Xe=Ea?tv.fetch:window.fetch,NU=Ea?tv.Request:window.Request,X=Ea?Ti:window.AbortController,qU=Ea?hr:window.AbortSignal;var cT=C(Ee(),1),Wc=C(xa(),1);var qv=C(Nv(),1);import{ErrorCategory as Aa}from"@vkontakte/videoplayer-shared";var to=a=>{if(!a)return{id:"EmptyResponse",category:Aa.PARSER,message:"Empty response"};if(a.length<=2&&a.match(/^\d+$/))return{id:`UVError#${a}`,category:Aa.NETWORK,message:`UV Error ${a}`};let e=(0,qv.default)(a).substring(0,100).toLowerCase();if(e.startsWith("<!doctype")||e.startsWith("<html>")||e.startsWith("<body>")||e.startsWith("<head>"))return{id:"UnexpectedHTML",category:Aa.NETWORK,message:"Received unexpected HTML, possibly a ISP block"};if(e.startsWith("<?xml"))return new DOMParser().parseFromString(a,"text/xml").querySelector("parsererror")?{id:"InvalidXML",category:Aa.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:Aa.PARSER,message:"Response is valid XML, but parser failed"}};var ye=(a,e,t=0)=>{for(let i=0;i<a.length;i++)if(a.start(i)*1e3-t<=e&&a.end(i)*1e3+t>e)return!0;return!1};import{abortable as Hc,assertNonNullable as xr,combine as wr,ErrorCategory as ot,filter as To,filterChanged as ss,flattenObject as ns,fromEvent as Dt,getTraceSubscriptionMethod as xC,interval as Qc,isNonNullable as os,isNullable as oT,map as Ar,merge as Ai,now as Gc,Subject as Xt,Subscription as uT,tap as wC,throttle as AC,ValueSubject as ee}from"@vkontakte/videoplayer-shared";var so=C(Ee(),1),wi=C(at(),1),no=C(xa(),1);var _M=(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)},OM=a=>window.clearTimeout(a),Uv=a=>typeof a=="function"&&a?.toString().endsWith("{ [native code] }"),jv=!Uv(window.requestIdleCallback)||!Uv(window.cancelIdleCallback),fr=jv?_M:window.requestIdleCallback,vt=jv?OM:window.cancelIdleCallback;var Zy=C(wn(),1);import{assertNever as FM,ErrorCategory as Hv,Subject as Qv}from"@vkontakte/videoplayer-shared";var NM=18,Gv=!1;try{Gv=B.browser.isSafari&&!!B.browser.safariVersion&&B.browser.safariVersion<=NM}catch(a){console.error(a)}var Ec=class{constructor(e){this.bufferFull$=new Qv;this.error$=new Qv;this.queue=[];this.currentTask=null;this.destroyed=!1;this.abortRequested=!1;this.completeTask=()=>{try{if(this.currentTask){let e=this.currentTask.signal?.aborted;this.currentTask.callback(!e),this.currentTask=null}this.queue.length&&this.pull()}catch(e){this.error$.next({id:"BufferTaskQueueUnknown",category:Hv.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:e})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(i=>{let r={operation:"append",data:e,signal:t,callback:i};this.queue.push(r),this.pull()})}async remove(e,t,i){return i&&i.aborted?!1:new Promise(r=>{let s={operation:"remove",from:e,to:t,signal:i,callback:r};this.queue.unshift(s),this.pull()})}async abort(e){return new Promise(t=>{let i,r=s=>{this.abortRequested=!1,t(s)};Gv&&e?i={operation:"safariAbort",init:e,callback:r}:i={operation:"abort",callback:r};for(let{callback:s}of this.queue)s(!1);this.abortRequested=!0,i&&(this.queue=[i]),this.pull()})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){if((this.buffer.updating||this.currentTask||this.destroyed)&&!this.abortRequested)return;let e=this.queue.shift();if(!e)return;if(e.signal?.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(r){r instanceof DOMException&&r.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):r instanceof DOMException&&r.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:Hv.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:r}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){let{operation:t}=e;switch(t){case"append":this.buffer.appendBuffer(e.data);break;case"remove":this.buffer.remove(e.from/1e3,e.to/1e3);break;case"abort":this.buffer.abort();break;case"safariAbort":{this.buffer.abort(),this.buffer.appendBuffer(e.init);break}default:FM(t)}}},Wv=Ec;var mr=a=>{let e=0;for(let t=0;t<a.length;t++)e+=a.end(t)-a.start(t);return e*1e3};import{abortable as Wt,assertNonNullable as Re,ErrorCategory as Lt,fromEvent as _c,getExponentialDelay as Oc,isHigher as uC,isNonNullable as zt,isNullable as le,now as ao,once as lC,Subject as cC,Subscription as dC,ValueSubject as xi}from"@vkontakte/videoplayer-shared";var zv=C(at(),1);var io=a=>a.valid,Q=class{constructor(e,t){this.cursor=0;this.source=e,this.boxParser=t,this.children=[];let i=this.readUint32();this.type=this.readString(4),i===1&&(this.cursor+=8);let r=e.byteOffset+this.cursor,s;i===0?(this.size=void 0,this.valid=!1,s=void 0):i===1?(this.size=void 0,this.valid=!1,s=void 0):i>e.byteLength?(this.size=i,this.valid=!1,s=Math.min(i-this.cursor,e.byteLength-this.cursor)):(this.size=i,this.valid=!0,s=i-this.cursor),this.content=new DataView(e.buffer,r,s)}get id(){return this.type}scanForBoxes(e){return this.boxParser.parse(e)}readString(e,t="ascii"){let r=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,r}readUint8(){let e=this.source.getUint8(this.cursor);return this.cursor+=1,e}readUint16(){let e=this.source.getUint16(this.cursor);return this.cursor+=2,e}readUint32(){let e=this.source.getUint32(this.cursor);return this.cursor+=4,e}readUint64(){let e=this.source.getBigInt64(this.cursor);return this.cursor+=8,e}};var br=class extends Q{};import{assertNever as qM}from"@vkontakte/videoplayer-shared";var Pa=class extends Q{constructor(e,t){if(super(e,t),!this.valid)return;let i=this.readString(16),r=new DataView(this.content.buffer,this.content.byteOffset+16,this.content.byteLength-16);this.userData=this.parseData(i,r)}parseData(e,t){switch(e){case"ondemandlivejson":{let i=new TextDecoder("ascii").decode(t),r=JSON.parse(i);return{received:r["t-in"],prepared:r["t-out"]}}default:qM(e)}}};var Ra=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 ka=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Z=class extends Q{constructor(e,t){if(super(e,t),!this.valid)return;let i=this.readUint32();this.version=i>>>24,this.flags=i&16777215,this.content=new DataView(this.content.buffer,this.content.byteOffset+4,this.content.byteLength-4)}};var La=class extends Z{constructor(e,t){super(e,t),this.valid&&(this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.timescale=this.readUint32(),this.duration=this.readUint32(),this.rate=this.readUint32(),this.volume=this.readUint16())}};var $a=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ma=class extends Q{constructor(e,t){super(e,t),this.data=this.content}};var Ii=class extends Z{get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e,t){if(super(e,t),!!this.valid){this.segments=[],this.referenceId=this.readUint32(),this.timescale=this.readUint32(),this.earliestPresentationTime32=this.readUint32(),this.firstOffset32=this.readUint32(),this.earliestPresentationTime64=0,this.firstOffset64=0,this.referenceCount=this.readUint32()&65535;for(let i=0;i<this.referenceCount;i++){let r=this.readUint32(),s=r>>>31,n=r<<1>>>1,u=this.readUint32();r=this.readUint32();let o=r>>>28,l=r<<3>>>3;this.segments.push({referenceType:s,referencedSize:n,subsegmentDuration:u,SAPType:o,SAPDeltaTime:l})}}}};var Da=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ca=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ba=class extends Z{constructor(e,t){if(super(e,t),!this.valid)return;switch(this.readUint8()){case 0:this.stereoMode=0;break;case 1:this.stereoMode=1;break;case 2:this.stereoMode=2;break;case 3:this.stereoMode=3;break;case 4:this.stereoMode=4;break}this.cursor+=1}};var Va=class extends Z{constructor(e,t){super(e,t),this.valid&&(this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32())}};var _a=class extends Z{constructor(e,t){super(e,t),this.valid&&(this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32())}};var Oa=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Fa=class extends Z{constructor(e,t){super(e,t),this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.trackId=this.readUint32(),this.cursor+=4,this.duration=this.readUint32(),this.cursor+=8,this.layer=this.readUint16(),this.alternateGroup=this.readUint16(),this.cursor+=2,this.cursor+=2,this.matrix=[[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()]],this.width=this.readUint32(),this.height=this.readUint32()}};var Na=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var qa=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ua=class extends Z{constructor(e,t){super(e,t),this.valid&&(this.sequenceNumber=this.readUint32())}};var ja=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ha=class extends Z{constructor(e,t){super(e,t),this.trackId=this.readUint32(),this.flags&1&&(this.baseDataOffset=this.readUint64()),this.flags&2&&(this.sampleDescriptionIndex=this.readUint32()),this.flags&8&&(this.defaultSampleDuration=this.readUint32()),this.flags&16&&(this.defaultSampleSize=this.readUint32()),this.flags&32&&(this.defaultSampleFlags=this.readUint32())}};var Qa=class extends Z{constructor(t,i){super(t,i);this.baseMediaDecodeTime32=0;this.baseMediaDecodeTime64=BigInt(0);this.version===1?this.baseMediaDecodeTime64=this.readUint64():this.baseMediaDecodeTime32=this.readUint32()}get baseMediaDecodeTime(){return this.version===1?this.baseMediaDecodeTime64:this.baseMediaDecodeTime32}};var Ga=class extends Z{constructor(t,i){super(t,i);this.sampleDuration=[];this.sampleSize=[];this.sampleFlags=[];this.sampleCompositionTimeOffset=[];this.optionalFields=0;this.sampleCount=this.readUint32(),this.flags&1&&(this.dataOffset=this.readUint32()),this.flags&4&&(this.firstSampleFlags=this.readUint32());for(let r=0;r<this.sampleCount;r++)this.flags&256&&this.sampleDuration.push(this.readUint32()),this.flags&512&&this.sampleSize.push(this.readUint32()),this.flags&1024&&this.sampleFlags.push(this.readUint32()),this.flags&2048&&this.sampleCompositionTimeOffset.push(this.readUint32())}};var Wa=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var za=class extends Z{constructor(e,t){super(e,t),this.valid&&(this.entryCount=this.readUint32(),this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+4,this.content.byteLength-4)))}};var Ya=class extends Q{constructor(e,t){super(e,t),this.valid&&(this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+78,this.content.byteLength-78)))}};var jM={ftyp:Ra,moov:ka,mvhd:La,moof:$a,mdat:Ma,sidx:Ii,trak:Da,mdia:Oa,mfhd:Ua,tkhd:Fa,traf:ja,tfhd:Ha,tfdt:Qa,trun:Ga,minf:Na,sv3d:Ca,st3d:Ba,prhd:Va,proj:qa,equi:_a,uuid:Pa,stbl:Wa,stsd:za,avc1:Ya,unknown:br},kt=class a{constructor(e={}){this.options={offset:0,...e}}parse(e){let t=[],i=this.options.offset;for(;i<e.byteLength;){let s=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+i+4,4)),n;try{n=this.createBox(s,new DataView(e.buffer,e.byteOffset+i,e.byteLength-i))}catch(u){if(!(u instanceof RangeError))throw u}if(!n||!io(n))break;t.push(n),i+=n.size}return t}createBox(e,t){let i=jM[e];return i?new i(t,new a):new br(t,new a)}};var Gt=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{io(t)&&(this.index[t.type]??=[],this.index[t.type].push(t),t.children.length>0&&this.indexBoxLevel(t.children))})}find(e){return this.index[e]&&this.index[e][0]?this.index[e][0]:null}findAll(e){return this.index[e]||[]}};var QM=new TextDecoder("ascii"),GM=a=>QM.decode(new DataView(a.buffer,a.byteOffset+4,4))==="ftyp",WM=a=>{let e=new Ii(a,new kt),t=e.earliestPresentationTime/e.timescale*1e3,i=a.byteOffset+a.byteLength+e.firstOffset;return e.segments.map(s=>{if(s.referenceType!==0)throw new Error("Unsupported multilevel sidx");let n=s.subsegmentDuration/e.timescale*1e3,u={status:"none",time:{from:t,to:t+n},byte:{from:i,to:i+s.referencedSize-1}};return t+=n,i+=s.referencedSize,u})},zM=(a,e)=>{let i=new kt().parse(a),r=new Gt(i),s=r.findAll("moof"),n=e?r.findAll("uuid"):r.findAll("mdat");if(!(n.length&&s.length))return null;let u=s[0],o=n[n.length-1],l=u.source.byteOffset,h=o.source.byteOffset-u.source.byteOffset+o.size;return new DataView(a.buffer,l,h)},YM=a=>{let t=new kt().parse(a),i=new Gt(t),r={},s=i.findAll("uuid"),n=(0,zv.default)(s,-1);return n?{serverDataReceivedTimestamp:n.userData.received,serverDataPreparedTime:n.userData.received}:r},KM=a=>{let t=new kt().parse(a);return new Gt(t).find("sidx")?.timescale},XM=(a,e)=>{let i=new kt().parse(a),s=new Gt(i).findAll("traf"),n=s[s.length-1].children.find(h=>h.type==="tfhd"),u=s[s.length-1].children.find(h=>h.type==="tfdt"),o=s[s.length-1].children.find(h=>h.type==="trun"),l=0;return o.sampleDuration.length?l=o.sampleDuration.reduce((h,c)=>h+c,0):l=n.defaultSampleDuration*o.sampleCount,(Number(u.baseMediaDecodeTime)+l)/e*1e3},JM=a=>{let e={is3dVideo:!1,stereoMode:0,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}},i=new kt().parse(a),r=new Gt(i);if(r.find("sv3d")){e.is3dVideo=!0;let n=r.find("st3d");n&&(e.stereoMode=n.stereoMode);let u=r.find("prhd");u&&(e.projectionData.pose.yaw=u.poseYawDegrees,e.projectionData.pose.pitch=u.posePitchDegrees,e.projectionData.pose.roll=u.poseRollDegrees);let o=r.find("equi");o&&(e.projectionData.bounds.top=o.projectionBoundsTop,e.projectionData.bounds.right=o.projectionBoundsRight,e.projectionData.bounds.bottom=o.projectionBoundsBottom,e.projectionData.bounds.left=o.projectionBoundsLeft)}return e},Yv={validateData:GM,parseInit:JM,getIndexRange:()=>{},parseSegments:WM,parseFeedableSegmentChunk:zM,getChunkEndTime:XM,getServerLatencyTimestamps:YM,getTimescaleFromIndex:KM};var Ja=C(Ee(),1);import{assertNonNullable as xc,isNonNullable as Zv,isNullable as eD}from"@vkontakte/videoplayer-shared";import{assertNever as ZM}from"@vkontakte/videoplayer-shared";var Kv={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"}},Xv=a=>{let e=a.getUint8(0),t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);let i=Xa(a,t),r=i in Kv,s=r?Kv[i].type:"binary",n=a.getUint8(t),u=0;n&128?u=1:n&64?u=2:n&32?u=3:n&16?u=4:n&8?u=5:n&4?u=6:n&2?u=7:n&1&&(u=8);let o=new DataView(a.buffer,a.byteOffset+t+1,u-1),l=n&255>>u,d=Xa(o),h=l*2**((u-1)*8)+d,c=t+u,p;return c+h>a.byteLength?p=new DataView(a.buffer,a.byteOffset+c):p=new DataView(a.buffer,a.byteOffset+c,h),{tag:r?i:"0x"+i.toString(16).toUpperCase(),type:s,tagHeaderSize:c,tagSize:c+h,value:p,valueSize:h}},Xa=(a,e=a.byteLength)=>{switch(e){case 1:return a.getUint8(0);case 2:return a.getUint16(0);case 3:return a.getUint8(0)*2**16+a.getUint16(1);case 4:return a.getUint32(0);case 5:return a.getUint8(0)*2**32+a.getUint32(1);case 6:return a.getUint16(0)*2**32+a.getUint32(2);case 7:{let t=a.getUint8(0)*281474976710656+a.getUint16(1)*4294967296+a.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},st=(a,e)=>{switch(e){case"int":return a.getInt8(0);case"uint":return Xa(a);case"float":return a.byteLength===4?a.getFloat32(0):a.getFloat64(0);case"string":return new TextDecoder("ascii").decode(a);case"utf8":return new TextDecoder("utf-8").decode(a);case"date":return new Date(Date.UTC(2001,0)+a.getInt8(0)).getTime();case"master":return a;case"binary":return a;default:ZM(e)}},Ei=(a,e)=>{let t=0;for(;t<a.byteLength;){let i=new DataView(a.buffer,a.byteOffset+t),r=Xv(i);if(!e(r))return;r.type==="master"&&Ei(r.value,e),t=r.value.byteOffset-a.byteOffset+r.valueSize}},Jv=a=>{if(a.getUint32(0)!==440786851)return!1;let e,t,i,r=Xv(a);return Ei(r.value,({tag:s,type:n,value:u})=>(s===17143?e=st(u,n):s===17026?t=st(u,n):s===17029&&(i=st(u,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)};var ey=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],tD=[231,22612,22743,167,171,163,160,175],iD=a=>{let e,t,i,r,s=!1,n=!1,u=!1,o,l,d=!1,h=0;return Ei(a,({tag:c,type:p,value:f,valueSize:b})=>{if(c===21419){let S=st(f,p);l=Xa(S)}else c!==21420&&(l=void 0);return c===408125543?(e=f.byteOffset,t=f.byteOffset+b):c===357149030?s=!0:c===290298740?n=!0:c===2807729?i=st(f,p):c===17545?r=st(f,p):c===21420&&l===475249515?o=st(f,p):c===374648427?Ei(f,({tag:S,type:g,value:T})=>S===30321?(d=st(T,g)===1,!1):!0):s&&n&&(0,Ja.default)(ey,c)&&(u=!0),!u}),xc(e,"Failed to parse webm Segment start"),xc(t,"Failed to parse webm Segment end"),xc(r,"Failed to parse webm Segment duration"),i=i??1e6,{segmentStart:Math.round(e/1e9*i*1e3),segmentEnd:Math.round(t/1e9*i*1e3),timeScale:i,segmentDuration:Math.round(r/1e9*i*1e3),cuesSeekPosition:o,is3dVideo:d,stereoMode:h,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},rD=a=>{if(eD(a.cuesSeekPosition))return;let e=a.segmentStart+a.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},aD=(a,e)=>{let t=!1,i=!1,r=u=>Zv(u.time)&&Zv(u.position),s=[],n;return Ei(a,({tag:u,type:o,value:l})=>{switch(u){case 475249515:t=!0;break;case 187:n&&r(n)&&s.push(n),n={};break;case 179:n&&(n.time=st(l,o));break;case 183:break;case 241:n&&(n.position=st(l,o));break;default:t&&(0,Ja.default)(ey,u)&&(i=!0)}return!(t&&i)}),n&&r(n)&&s.push(n),s.map((u,o)=>{let{time:l,position:d}=u,h=s[o+1];return{status:"none",time:{from:l,to:h?h.time:e.segmentDuration},byte:{from:e.segmentStart+d,to:h?e.segmentStart+h.position-1:e.segmentEnd-1}}})},sD=a=>{let e=0,t=!1;try{Ei(a,i=>i.tag===524531317?i.tagSize<=a.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):(0,Ja.default)(tD,i.tag)?(e+i.tagSize<=a.byteLength&&(e+=i.tagSize,t||=(0,Ja.default)([163,160,175],i.tag)),!0):!1)}catch{}return e>0&&e<=a.byteLength&&t?new DataView(a.buffer,a.byteOffset,e):null},ty={validateData:Jv,parseInit:iD,getIndexRange:rD,parseSegments:aD,parseFeedableSegmentChunk:sD};var yt=a=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(a);if(e){let[,t,i]=e;if(t==="audio"||t==="video")switch(i){case"webm":return ty;case"mp4":return Yv}}throw new ReferenceError(`Unsupported mime type ${a}`)};var Tt=a=>a instanceof DOMException&&(a.name==="AbortError"||a.code===20);var $c=C(xy(),1),Gy=C(Wi(),1),Wy=C(Ny(),1),zy=C(at(),1),Mc=C(sr(),1);var qy=C(Ee(),1),Lc=a=>{let e=a.split("."),[t,...i]=e;if(!t)return!1;switch(t){case"av01":{let[r,s,n]=i;return!!(n&&parseInt(n,10)>8)}case"vp09":{let[r,s,n]=i;return!!(r&&parseInt(r,10)>=2&&n&&parseInt(n,10)>8)}case"avc1":{let r=i[0];if(!r||r.length!==6)return!1;let[s,n]=r.toUpperCase(),u=s+n;return(0,qy.default)(["6E","7A","F4"],u)}}return!1};import{isNonNullable as sC,isNullable as Hy}from"@vkontakte/videoplayer-shared";var Uy=a=>{if(a.includes("/")){let e=a.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(a)};var jy=a=>{try{let e=aC(),t=a.match(e),{groups:i}=t??{};if(i){let r={};if(i.extensions){let u=i.extensions.toLowerCase().match(/(?:[0-9a-wy-z](?:-[a-z0-9]{2,8})+)/g);Array.from(u||[]).forEach(o=>{r[o[0]]=o.slice(2)})}let s=i.variants?.split(/-/).filter(u=>u!==""),n={extlang:i.extlang,langtag:i.langtag,language:i.language,privateuse:i.privateuse||i.privateuse2,region:i.region,script:i.script,extensions:r,variants:s};return Object.keys(n).forEach(u=>{let o=n[u];(typeof o>"u"||o==="")&&delete n[u]}),n}return null}catch{return null}};function aC(){let a="(?<extlang>(?:[a-z]{3}(?:-[a-z]{3}){0,2}))",e="x(?:-[a-z0-9]{1,8})+",d=`^(?:(?<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 Hy=a=>{if(!a?.startsWith("P"))return;let e=(n,u)=>{let o=n?parseFloat(n.replace(",",".")):NaN;return(isNaN(o)?0:o)*u},i=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(a),r=i?.[1]==="-"?-1:1,s={days:e(i?.[5],r),hours:e(i?.[6],r),minutes:e(i?.[7],r),seconds:e(i?.[8],r)};return s.days*24*60*60*1e3+s.hours*60*60*1e3+s.minutes*60*1e3+s.seconds*1e3},nt=(a,e)=>{let t=a;t=(0,wc.default)(t,"$$","$");let i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[r,s]of(0,jy.default)(i)){let n=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=(0,wc.default)(t,n,(u,o)=>Uy(s)?u:Uy(o)?s:(0,Qy.default)(s,parseInt(o,10),"0"))}return t},Yn=(a,e)=>{let i=new DOMParser().parseFromString(a,"application/xml"),r={video:[],audio:[],text:[]},s=i.children[0],n=Array.from(s.querySelectorAll("MPD > BaseURL").values()).map(R=>R.textContent?.trim()??""),u=(0,Wy.default)(n,0)??"",o=s.getAttribute("type")==="dynamic",l=s.getAttribute("availabilityStartTime"),c=s.getAttribute("publishTime"),p=s.getElementsByTagName("vk:Attrs")[0],d=p?.getElementsByTagName("vk:XLatestSegmentPublishTime")[0].textContent,h=p?.getElementsByTagName("vk:XStreamIsLive")[0].textContent,f=p?.getElementsByTagName("vk:XStreamIsUnpublished")[0].textContent,b=p?.getElementsByTagName("vk:XPlaybackDuration")[0].textContent,S;o&&(S={availabilityStartTime:l?new Date(l).getTime():0,publishTime:c?new Date(c).getTime():0,latestSegmentPublishTime:d?new Date(d).getTime():0,streamIsAlive:h==="yes",streamIsUnpublished:f==="yes"});let g,I=s.getAttribute("mediaPresentationDuration"),x=[...s.getElementsByTagName("Period")],y=x.reduce((R,T)=>({...R,[T.id]:T.children}),{}),w=x.reduce((R,T)=>({...R,[T.id]:T.getAttribute("duration")}),{});I?g=Hy(I):(0,Ac.default)(w).filter(R=>R).length&&!o?g=(0,Ac.default)(w).reduce((R,T)=>R+(Hy(T)??0),0):b&&(g=parseInt(b,10));let D=0,L=s.getAttribute("profiles")?.split(",")??[];for(let R of x.map(T=>T.id))for(let T of y[R]){let q=T.getAttribute("id")??"id"+(D++).toString(10),$=T.getAttribute("mimeType")??"",v=T.getAttribute("codecs")??"",E=T.getAttribute("contentType")??$?.split("/")[0],z=T.getAttribute("profiles")?.split(",")??[],M=qy(T.getAttribute("lang")??"")??{},H=T.querySelector("Label")?.textContent?.trim()??void 0,J=T.querySelectorAll("Representation"),ie=T.querySelector("SegmentTemplate"),ue=T.querySelector("Role")?.getAttribute("value")??void 0,fe=E,me={id:q,language:M.language,isDefault:ue==="main",label:H,codecs:v,hdr:fe==="video"&&xc(v),mime:$,representations:[]};for(let j of J){let U=j.getAttribute("lang")??void 0,ke=H??T.getAttribute("label")??j.getAttribute("label")??void 0,Te=j.querySelector("BaseURL")?.textContent?.trim()??"",le=new URL(Te||u,e).toString(),We=j.getAttribute("mimeType")??$,Bt=j.getAttribute("codecs")??v??"",lt;if(E==="text"){let Oe=j.getAttribute("id")||"",Vt=M.privateuse?.includes("x-auto")||Oe.includes("_auto"),ct=j.querySelector("SegmentTemplate");if(ct){let Br={representationId:j.getAttribute("id")??void 0,bandwidth:j.getAttribute("bandwidth")??void 0},Ps=parseInt(j.getAttribute("bandwidth")??"",10)/1e3,ks=parseInt(ct.getAttribute("startNumber")??"",10)??1,Mi=parseInt(ct.getAttribute("timescale")??"",10),Go=ct.querySelectorAll("SegmentTimeline S")??[],Di=ct.getAttribute("media");if(!Di)continue;let Rs=[],Ls=0,$s="",Ci=0,Vr=ks,Ie=0;for(let Je of Go){let ii=parseInt(Je.getAttribute("d")??"",10),Ge=parseInt(Je.getAttribute("r")??"",10)||0,_t=parseInt(Je.getAttribute("t")??"",10);Ie=Number.isFinite(_t)?_t:Ie;let ri=ii/Mi*1e3,Bi=Ie/Mi*1e3;for(let dt=0;dt<Ge+1;dt++){let Ot=nt(Di,{...Br,segmentNumber:Vr.toString(10),segmentTime:(Ie+dt*ii).toString(10)}),Vi=(Bi??0)+dt*ri,Or=Vi+ri;Vr++,Rs.push({time:{from:Vi,to:Or},url:Ot})}Ie+=(Ge+1)*ii,Ls+=(Ge+1)*ri}Ci=Ie/Mi*1e3,$s=nt(Di,{...Br,segmentNumber:Vr.toString(10),segmentTime:Ie.toString(10)});let _r={time:{from:Ci,to:1/0},url:$s},Et={type:"template",baseUrl:le,segmentTemplateUrl:Di,initUrl:"",totalSegmentsDurationMs:Ls,segments:Rs,nextSegmentBeyondManifest:_r,timescale:Mi};lt={id:Oe,kind:"text",segmentReference:Et,profiles:[],duration:g,bitrate:Ps,mime:"",codecs:"",width:0,height:0,isAuto:Vt}}else lt={id:Oe,isAuto:Vt,kind:"text",url:le}}else{let Oe=j.getAttribute("contentType")??We?.split("/")[0]??E,Vt=T.getAttribute("profiles")?.split(",")??[],ct=parseInt(j.getAttribute("width")??"",10),Br=parseInt(j.getAttribute("height")??"",10),Ps=parseInt(j.getAttribute("bandwidth")??"",10)/1e3,ks=j.getAttribute("frameRate")??"",Mi=j.getAttribute("quality")??void 0,Go=ks?Ny(ks):void 0,Di=j.getAttribute("id")??"id"+(D++).toString(10),Rs=Oe==="video"?`${Br}p`:Oe==="audio"?`${Ps}Kbps`:Bt,Ls=`${Di}@${Rs}`,$s=[...L,...z,...Vt],Ci,Vr=j.querySelector("SegmentBase"),Ie=j.querySelector("SegmentTemplate")??ie;if(Vr){let Et=j.querySelector("SegmentBase Initialization")?.getAttribute("range")??"",[Je,ii]=Et.split("-").map(Ot=>parseInt(Ot,10)),Ge={from:Je,to:ii},_t=j.querySelector("SegmentBase")?.getAttribute("indexRange"),[ri,Bi]=_t?_t.split("-").map(Ot=>parseInt(Ot,10)):[],dt=_t?{from:ri,to:Bi}:void 0;Ci={type:"byteRange",url:le,initRange:Ge,indexRange:dt}}else if(Ie){let Et={representationId:j.getAttribute("id")??void 0,bandwidth:j.getAttribute("bandwidth")??void 0},Je=parseInt(Ie.getAttribute("timescale")??"",10),ii=Ie.getAttribute("initialization")??"",Ge=Ie.getAttribute("media"),_t=parseInt(Ie.getAttribute("startNumber")??"",10)??1,ri=nt(ii,Et);if(!Ge)throw new ReferenceError("No media attribute in SegmentTemplate");let Bi=Ie.querySelectorAll("SegmentTimeline S")??[],dt=[],Ot=0,Vi="",Or=0;if(Bi.length){let Ms=_t,Ze=0;for(let _i of Bi){let pt=parseInt(_i.getAttribute("d")??"",10),ai=parseInt(_i.getAttribute("r")??"",10)||0,Ds=parseInt(_i.getAttribute("t")??"",10);Ze=Number.isFinite(Ds)?Ds:Ze;let zo=pt/Je*1e3,VI=Ze/Je*1e3;for(let Cs=0;Cs<ai+1;Cs++){let _I=nt(Ge,{...Et,segmentNumber:Ms.toString(10),segmentTime:(Ze+Cs*pt).toString(10)}),Od=(VI??0)+Cs*zo,OI=Od+zo;Ms++,dt.push({time:{from:Od,to:OI},url:_I})}Ze+=(ai+1)*pt,Ot+=(ai+1)*zo}Or=Ze/Je*1e3,Vi=nt(Ge,{...Et,segmentNumber:Ms.toString(10),segmentTime:Ze.toString(10)})}else if(sC(g)){let Ze=parseInt(Ie.getAttribute("duration")??"",10)/Je*1e3,_i=Math.ceil(g/Ze),pt=0;for(let ai=1;ai<_i;ai++){let Ds=nt(Ge,{...Et,segmentNumber:ai.toString(10),segmentTime:pt.toString(10)});dt.push({time:{from:pt,to:pt+Ze},url:Ds}),pt+=Ze}Or=pt,Vi=nt(Ge,{...Et,segmentNumber:_i.toString(10),segmentTime:pt.toString(10)})}let BI={time:{from:Or,to:1/0},url:Vi};Ci={type:"template",baseUrl:le,segmentTemplateUrl:Ge,initUrl:ri,totalSegmentsDurationMs:Ot,segments:dt,nextSegmentBeyondManifest:BI,timescale:Je}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!Oe||!We)continue;let _r={video:"video",audio:"audio",text:"text"}[Oe];if(!_r)continue;fe||=_r,lt={id:Ls,kind:_r,segmentReference:Ci,profiles:$s,duration:g,bitrate:Ps,mime:We,codecs:Bt,width:ct,height:Br,fps:Go,quality:Mi}}me.language||=U,me.label||=ke,me.mime||=We,me.codecs||=Bt,me.hdr||=fe==="video"&&xc(Bt),me.representations.push(lt)}if(fe){let j=r[fe].find(U=>U.id===me.id);if(j&&me.representations.every(U=>U.segmentReference.type==="template"))for(let U of j.representations){let Te=me.representations.find(We=>We.id===U.id)?.segmentReference,le=U.segmentReference;le.segments.push(...Te.segments),le.nextSegmentBeyondManifest=Te.nextSegmentBeyondManifest}else r[fe].push(me)}}return{duration:g,streams:r,baseUrls:n,live:S}};var Pc=C(at(),1);import{videoSizeToQuality as nC}from"@vkontakte/videoplayer-shared";var Gy=({id:a,width:e,height:t,bitrate:i,fps:r,quality:s,streamId:n})=>{let u=(s?jt(s):void 0)??nC({width:e,height:t});return u&&{id:a,quality:u,bitrate:i,size:{width:e,height:t},fps:r,streamId:n}},zy=({id:a,bitrate:e})=>({id:a,bitrate:e}),Yy=({language:a,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:a,label:e}),Ky=({language:a,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:a,label:e}),kc=({id:a,language:e,label:t,codecs:i,isDefault:r})=>({id:a,language:e,label:t,codec:(0,Pc.default)(i.split("."),0),isDefault:r}),Rc=({id:a,language:e,label:t,hdr:i,codecs:r})=>({id:a,language:e,hdr:i,label:t,codec:(0,Pc.default)(r.split("."),0)}),Lc=a=>"url"in a,He=a=>a.type==="template";import{isNonNullable as Xy}from"@vkontakte/videoplayer-shared";var V=(a,e)=>Xy(a)&&Xy(e)&&a.readyState==="open"&&oC(a,e);function oC(a,e){for(let t=0;t<a.activeSourceBuffers.length;++t)if(a.activeSourceBuffers[t]===e)return!0;return!1}var Za=class{constructor(e,t,i,{fetcher:r,tuning:s,getCurrentPosition:n,isActiveLowLatency:u,compatibilityMode:o=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new Ii(0);this.currentLowLatencySegmentLength$=new Ii(0);this.currentSegmentLength$=new Ii(0);this.onLastSegment$=new Ii(!1);this.fullyBuffered$=new Ii(!1);this.playingRepresentation$=new Ii(void 0);this.playingRepresentationInit$=new Ii(void 0);this.error$=new lC;this.gaps=[];this.subscription=new cC;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new X;this.switchAbortController=new X;this.destroyAbortController=new X;this.bufferLimit=1/0;this.failedDownloads=0;this.baseUrls=[];this.baseUrlsIndex=0;this.isLive=!1;this.liveUpdateSegmentIndex=0;this.liveInitialAdditionalOffset=0;this.isSeekingLive=!1;this.index=0;this.lastDataObtainedTimestampMs=0;this.loadByteRangeSegmentsTimeoutId=0;this.startWith=Gt(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);Ve(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new Qv(this.sourceBuffer),this.subscription.add($c(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let u,o=this.mediaSource.readyState;o!=="open"&&(u={id:`SegmentEjection_source_${o}`,category:Lt.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),u??={id:"SegmentEjection",category:Lt.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n},this.error$.next(u)})),this.subscription.add($c(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:Lt.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let u=this.getCurrentPosition();if(!this.sourceBuffer||!u||!V(this.mediaSource,this.sourceBuffer))return;let o=Math.min(this.bufferLimit,hr(this.sourceBuffer.buffered)*.8);this.bufferLimit=o;let l=this.getForwardBufferDuration(u),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(u,n*2,l<c).catch(p=>{this.handleAsyncError(p,"pruneBuffer")})})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(n=>this.error$.next(n))),yield this.loadInit(t,"high",!0);let i=this.initData.get(t.id),r=this.segments.get(t.id),s=this.parsedInitData.get(t.id);Ve(i,"No init buffer for starting representation"),Ve(r,"No segments for starting representation"),i instanceof ArrayBuffer&&(this.searchGaps(r,t),yield this.sourceBufferTaskQueue.append(i,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(s))}.bind(this));this.switchTo=Gt(this.destroyAbortController.signal,async function*(e,t=!1){if(!V(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);Ve(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if(ve(s)||ve(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),Ve(r,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!V(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer();else{let n=this.getCurrentPosition();Sr(n)&&!this.isLive&&(this.bufferLimit=1/0,await this.pruneBuffer(n,1/0,!0)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}this.maintain()}}.bind(this));this.switchToOld=Gt(this.destroyAbortController.signal,async function*(e,t=!1){if(!V(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);Ve(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if(ve(s)||ve(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),Ve(r,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!V(this.mediaSource,this.sourceBuffer)))if(yield this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer(),this.maintain();else{let n=this.getCurrentPosition();Sr(n)&&(this.isLive||(this.bufferLimit=1/0,await this.pruneBuffer(n,1/0,!0)),this.maintain(n)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}}.bind(this));this.seekLive=Gt(this.destroyAbortController.signal,async function*(e){let t=(0,Jn.default)(e,o=>o.representations)??[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let o of this.representations.keys()){let l=t.find(d=>d.id===o);l&&this.representations.set(o,l);let c=this.representations.get(o);if(!c||!He(c.segmentReference))return;let p=this.getActualLiveStartingSegments(c.segmentReference);this.segments.set(c.id,p)}let i=this.switchingToRepresentationId??this.downloadingRepresentationId,r=this.representations.get(i);Ve(r);let s=this.segments.get(i);Ve(s,"No segments for starting representation");let n=this.initData.get(i);if(Ve(n,"No init buffer for starting representation"),!(n instanceof ArrayBuffer))return;let u=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,yield this.abort(),u&&(yield this.sourceBufferTaskQueue.remove(u.from*1e3,u.to*1e3,this.destroyAbortController.signal)),this.searchGaps(s,r),yield this.sourceBufferTaskQueue.append(n,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this));this.fetcher=r,this.tuning=s,this.compatibilityMode=o,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=u,this.isLive=!!l?.live,this.baseUrls=l?.baseUrls??[],this.initData=new Map(i.map(c=>[c.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(i.map(c=>[c.id,c])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}switchToWithPreviousAbort(e,t=!1){!V(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new X,Gt(this.switchAbortController.signal,async function*(i,r=!1){this.switchingToRepresentationId=i;let s=this.representations.get(i);Ve(s,`No such representation ${i}`);let n=this.segments.get(i),u=this.initData.get(i);if(ve(u)||ve(n)?yield this.loadInit(s,"high",!1):u instanceof Promise&&(yield u),n=this.segments.get(i),Ve(n,"No segments for starting representation"),u=this.initData.get(i),!(!(u instanceof ArrayBuffer)||!this.sourceBuffer||!V(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(u,this.downloadAbortController.signal),r)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=i,yield this.dropBuffer();else{let o=this.getCurrentPosition();Sr(o)&&!this.isLive&&(this.bufferLimit=this.forwardBufferTarget,yield this.pruneBuffer(o,1/0,!0)),this.downloadingRepresentationId=i,this.switchingToRepresentationId=void 0}this.maintain()}}.bind(this))(e,t))}warmUpMediaSource(){!ve(this.sourceBuffer)&&!this.sourceBuffer.updating&&(this.sourceBuffer.mode="segments")}async abort(){for(let e of this.activeSegments)this.abortSegment(e.segment);return this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new X,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(ve(e)||ve(this.downloadingRepresentationId)||ve(this.playingRepresentationId)||ve(this.sourceBuffer)||!V(this.mediaSource,this.sourceBuffer)||Sr(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if(Ve(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;let r=i.find(c=>e>=c.time.from&&e<c.time.to);Sr(r)&&isFinite(r.time.from)&&isFinite(r.time.to)&&this.currentSegmentLength$.next(r?.time.to-r.time.from);let s=e,n=100;if(this.playingRepresentationId!==this.downloadingRepresentationId){let c=this.getForwardBufferDuration(e),p=r?r.time.to+n:-1/0;r&&r.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&c>=r.time.to-e+n&&(s=p)}if(isFinite(this.bufferLimit)&&hr(this.sourceBuffer.buffered)>=this.bufferLimit){let c=this.getForwardBufferDuration(e),p=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,c<p).catch(d=>{this.handleAsyncError(d,"pruneBuffer")});return}let o=[];if(!this.activeSegments.size&&(o=this.selectForwardBufferSegments(i,t.segmentReference.type,s),o.length)){let c="auto";if(this.tuning.dash.useFetchPriorityHints&&r)if((0,Xn.default)(o,r))c="high";else{let p=(0,Ei.default)(o,0);p&&p.time.from-r.time.to>=this.forwardBufferTarget/2&&(c="low")}this.loadSegments(o,t,c).catch(p=>{this.handleAsyncError(p,"loadSegments")})}(!this.preloadOnly&&!this.allInitsLoaded&&r&&r.status==="fed"&&!o.length&&this.getForwardBufferDuration(e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let l=(0,Ei.default)(i,-1);!this.isLive&&l&&(this.fullyBuffered$.next(l.time.to-e-this.getForwardBufferDuration(e)<n),this.onLastSegment$.next(e-l.time.from>0))}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}searchGaps(e,t){this.gaps=[];let i=0,r=this.isLive?this.liveInitialAdditionalOffset:0;for(let s of e)Math.trunc(s.time.from-i)>0&&this.gaps.push({representation:t.id,from:i,to:s.time.from+r}),i=s.time.to;Sr(t.duration)&&t.duration-i>0&&!this.isLive&&this.gaps.push({representation:t.id,from:i,to:t.duration})}getActualLiveStartingSegments(e){let t=e.segments,i=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,r=[],s=0,n=t.length-1;do r.unshift(t[n]),s+=t[n].time.to-t[n].time.from,n--;while(s<i&&n>=0);return this.liveInitialAdditionalOffset=s-i,this.isActiveLowLatency()?[r[0]]:r}getLiveSegmentsToLoadState(e){let t=(0,Jn.default)(e?.streams[this.kind],r=>r.representations).find(r=>r.id===this.downloadingRepresentationId);if(!t)return;let i=this.segments.get(t.id);if(i?.length)return{from:i[0].time.from,to:i[i.length-1].time.to}}updateLive(e){let t=(0,Jn.default)(e?.streams[this.kind],i=>i.representations)??[];if(![...this.segments.values()].every(i=>!i.length))for(let i of t){if(!i||!He(i.segmentReference))return;let r=i.segmentReference.segments.map(l=>({...l,status:"none",size:void 0})),s=100,n=this.segments.get(i.id)??[],u=(0,Ei.default)(n,-1)?.time.to??0,o=r?.findIndex(l=>u>=l.time.from+s&&u<=l.time.to+s);if(o===-1){this.liveUpdateSegmentIndex=0;let l=this.getActualLiveStartingSegments(i.segmentReference);this.segments.set(i.id,l)}else{let l=r.slice(o+1);this.segments.set(i.id,[...n,...l])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;Ve(e);let t=this.segments.get(e);if(t?.length){let i=t[t.length-1];this.updateLowLatencyLiveIfNeeded(i)}}calculateDurationFromSegments(){if(!this.playingRepresentationId)return 0;let e=this.segments.get(this.playingRepresentationId);return(e?(0,Ei.default)(e,-1)?.time.to:0)||0}updateLowLatencyLiveIfNeeded(e){let t=0;for(let i of this.representations.values()){let r=i.segmentReference;if(!He(r))return;let s=this.segments.get(i.id)??[],n=s.find(o=>Math.floor(o.time.from)===Math.floor(e.time.from));if(n&&!isFinite(n.time.to)&&(n.time.to=e.time.to,t=n.time.to-n.time.from),!!!s.find(o=>Math.floor(o.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let o=Math.round(e.time.to*r.timescale/1e3).toString(10),l=nt(r.segmentTemplateUrl,{segmentTime:o});s.push({status:"none",time:{from:e.time.to,to:1/0},url:l})}}this.currentLowLatencySegmentLength$.next(t)}findSegmentStartTime(e){let t=this.switchingToRepresentationId??this.downloadingRepresentationId??this.playingRepresentationId;if(!t)return;let i=this.segments.get(t);return i?i.find(s=>s.time.from<=e&&s.time.to>=e)?.time.from??void 0:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),this.sourceBufferTaskQueue?.destroy(),this.gapDetectionIdleCallback&&vt&&vt(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&vt&&vt(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer)try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(e){if(!(e instanceof DOMException&&e.name==="NotFoundError"))throw e}this.sourceBuffer=null,this.downloadAbortController.abort(),this.switchAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,i){return this.isLive?this.selectForwardBufferSegmentsLive(e,i):this.selectForwardBufferSegmentsRecord(e,t,i)}selectForwardBufferSegmentsLive(e,t){let i=e.findIndex(r=>t>=r.time.from&&t<r.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=i),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,i){let r=this.getForwardBufferDuration(i),s=e.findIndex(({status:d,time:{from:h,to:f}},b)=>{let S=h<=i&&f>=i,g=h>i||S||b===0&&i===0,I=Math.min(this.forwardBufferTarget,this.bufferLimit),x=this.preloadOnly&&h<=i+I||r<I&&f-h>=I||f<=i+I;return(d==="none"||d==="partially_ejected"&&g&&x&&this.sourceBuffer&&V(this.mediaSource,this.sourceBuffer)&&!(Se(this.sourceBuffer.buffered,h)&&Se(this.sourceBuffer.buffered,f)))&&g&&x});if(s===-1)return[];if(t!=="byteRange")return e.slice(s,s+1);let n=e,u=0,o=0,l=[],c=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,p=this.preloadOnly?this.forwardBufferTarget:0;for(let d=s;d<n.length&&(u<=c||o<=p);d++){let h=n[d];if(u+=h.byte.to+1-h.byte.from,o+=h.time.to+1-h.time.from,h.status==="none"||h.status==="partially_ejected")l.push(h);else break}return l}async loadSegments(e,t,i="auto"){He(t.segmentReference)?await this.loadTemplateSegment(e[0],t,i):await this.loadByteRangeSegments(e,t,i)}async loadTemplateSegment(e,t,i="auto"){e.status="downloading";let r={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(r);let{range:s,url:n,signal:u,onProgress:o,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&u&&(await Gt(u,async function*(){let c=Mc(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(p=>setTimeout(p,c))}.bind(this))(),u.aborted&&this.abortActiveSegments([e]));try{let c=await this.fetcher.fetch(n,{range:s,signal:u,onProgress:o,priority:i,isLowLatency:this.isActiveLowLatency(),bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation});if(this.lastDataObtainedTimestampMs=Kn(),!c)return;let p=new DataView(c),d=yt(t.mime);if(!isFinite(r.segment.time.to)){let b=t.segmentReference.timescale;r.segment.time.to=d.getChunkEndTime(p,b)}o&&r.feedingBytes&&l?await Promise.all(l):await this.sourceBufferTaskQueue.append(p,u);let{serverDataReceivedTimestamp:h,serverDataPreparedTime:f}=d.getServerLatencyTimestamps(p);h&&f&&this.currentLiveSegmentServerLatency$.next(f-h),r.segment.status="downloaded",this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(c){this.abortActiveSegments([e]),Tt(c)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}updateRepresentationsBaseUrlIfNeeded(){if(!this.tuning.dash.enableBaseUrlSupport||!this.baseUrls.length||this.failedDownloads<=this.tuning.dash.maxSegmentRetryCount)return;this.baseUrlsIndex=(this.baseUrlsIndex+1)%this.baseUrls.length;let e=this.baseUrls[this.baseUrlsIndex];for(let t of this.representations.values())He(t.segmentReference)?t.segmentReference.baseUrl=e:t.segmentReference.url=e}async loadByteRangeSegments(e,t,i="auto"){if(!e.length)return;for(let o of e)o.status="downloading",this.activeSegments.add({segment:o,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:r,url:s,signal:n,onProgress:u}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(await Gt(n,async function*(){let o=Mc(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,o),$c(window,"online").pipe(uC()).subscribe(()=>{l(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(s,{range:r,onProgress:u,signal:n,priority:i,bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation}),this.lastDataObtainedTimestampMs=Kn(),this.failedDownloads=0}catch(o){this.abortActiveSegments(e),Tt(o)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}prepareByteRangeFetchSegmentParams(e,t){if(He(t.segmentReference))throw new Error("Representation is not byte range type");let i=t.segmentReference.url,r={from:(0,Ei.default)(e,0).byte.from,to:(0,Ei.default)(e,-1).byte.to},{signal:s}=this.downloadAbortController;return{url:i,range:r,signal:s,onProgress:async(u,o)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=Kn(),await this.onSomeByteRangesDataLoaded({dataView:u,loaded:o,signal:s,onSegmentAppendFailed:()=>this.abort(),globalFrom:r?r.from:0,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:Lt.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!He(t.segmentReference))throw new Error("Representation is not template type");let i=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&i.searchParams.set("low-latency","yes");let r=i.toString(),{signal:s}=this.downloadAbortController,n=[],o=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(l,c)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=Kn();let p=this.onSomeTemplateDataLoaded({dataView:l,loaded:c,signal:s,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(p)}catch(p){this.error$.next({id:"SegmentFeeding",category:Lt.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:p})}}:void 0;return{url:r,signal:s,onProgress:o,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)(0,Xn.default)(e,t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:r,signal:s}){if(!this.activeSegments.size||!V(this.mediaSource,this.sourceBuffer))return;let n=this.representations.get(t);if(n)for(let u of this.activeSegments){let{segment:o}=u;if(u.representationId===t){if(s.aborted){r();continue}if(u.loadedBytes=i,u.loadedBytes>u.feedingBytes){let l=new DataView(e.buffer,e.byteOffset+u.feedingBytes,u.loadedBytes-u.feedingBytes),c=yt(n.mime).parseFeedableSegmentChunk(l,this.isLive);c?.byteLength&&(o.status="partially_fed",u.feedingBytes+=c.byteLength,await this.sourceBufferTaskQueue.append(c),u.fedBytes+=c.byteLength)}}}}async onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:s,onSegmentAppendFailed:n}){if(!this.activeSegments.size||!V(this.mediaSource,this.sourceBuffer))return;let u=this.representations.get(t);if(u)for(let o of this.activeSegments){let{segment:l}=o;if(o.representationId!==t)continue;if(s.aborted){await n();continue}let c=l.byte.from-i,p=l.byte.to-i,d=p-c+1,h=c<r,f=p<=r;if(!h)continue;let b=yt(u.mime);if(l.status==="downloading"&&f){l.status="downloaded";let S=new DataView(e.buffer,e.byteOffset+c,d);await this.sourceBufferTaskQueue.append(S,s)&&!s.aborted?this.onSegmentFullyAppended(o,t):await n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(l.status==="downloading"||l.status==="partially_fed")&&(o.loadedBytes=Math.min(d,r-c),o.loadedBytes>o.feedingBytes)){let S=new DataView(e.buffer,e.byteOffset+c+o.feedingBytes,o.loadedBytes-o.feedingBytes),g=o.loadedBytes===d?S:b.parseFeedableSegmentChunk(S);g?.byteLength&&(l.status="partially_fed",o.feedingBytes+=g.byteLength,await this.sourceBufferTaskQueue.append(g,s)&&!s.aborted?(o.fedBytes+=g.byteLength,o.fedBytes===d&&this.onSegmentFullyAppended(o,t)):await n())}}}onSegmentFullyAppended(e,t){if(!(ve(this.sourceBuffer)||!V(this.mediaSource,this.sourceBuffer))){!this.isLive&&B.browser.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(Se(this.sourceBuffer.buffered,e.segment.time.from,100)&&Se(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:Lt.VIDEO_PIPELINE,message:"Browser stuck on empty result of adding segment to source buffer"})),this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status="fed",Lc(e.segment)&&(e.segment.size=e.fedBytes);for(let i of this.representations.values())if(i.id!==t)for(let r of this.segments.get(i.id)??[])r.status==="fed"&&Math.round(r.time.from)===Math.round(e.segment.time.from)&&Math.round(r.time.to)===Math.round(e.segment.time.to)&&(r.status="none");this.updateLowLatencyLiveIfNeeded(e.segment),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment])}}abortSegment(e){e.status==="partially_fed"?e.status="partially_ejected":e.status!=="partially_ejected"&&(e.status="none");for(let t of this.activeSegments.values())if(t.segment===e){this.activeSegments.delete(t);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(let[r,s]of this.initData.entries()){let n=s instanceof Promise;t||=n,s===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let i=this.representations.get(e);i&&(this.initLoadIdleCallback=pr(()=>(0,Jy.default)(this.loadInit(i,"low",!1),()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",i=!1){let r=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!i&&this.failedDownloads>0?Gt(this.destroyAbortController.signal,async function*(){let u=Mc(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(o=>setTimeout(o,u))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,yt(e.mime),r)).then(async u=>{if(!u)return;let{init:o,dataView:l,segments:c}=u,p=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,p);let d=c;this.isLive&&He(e.segmentReference)&&(d=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,d),o&&this.parsedInitData.set(e.id,o)}).then(()=>this.failedDownloads=0,u=>{this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:Lt.WTF,message:"loadInit threw",thrown:u})});return this.initData.set(e.id,n),n}async dropBuffer(){for(let e of this.segments.values())for(let t of e)t.status="none";await this.pruneBuffer(0,1/0,!0)}async pruneBuffer(e,t,i=!1){if(!this.sourceBuffer||!V(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||ve(e))return!1;let r=[],s=0,n=o=>{o.sort((c,p)=>c.from-p.from);let l=[o[0]];for(let c=1;c<o.length;c++){let{from:p,to:d}=o[c],h=l[l.length-1];h.to>=p?h.to=Math.max(h.to,d):l.push(o[c])}return l},u=o=>{if(s>=t)return r;r.push({...o.time}),r=n(r);let l=Lc(o)?o.size??0:o.byte.to-o.byte.from;s+=l};for(let o of this.segments.values())for(let l of o){let c=l.time.to<=e-this.tuning.dash.bufferPruningSafeZone,p=l.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(c||p)&&l.status==="fed"&&u(l)}for(let o=0;o<this.sourceBuffer.buffered.length;o++){let l=this.sourceBuffer.buffered.start(o)*1e3,c=this.sourceBuffer.buffered.end(o)*1e3,p=0;for(let d of this.segments.values())for(let h of d)(0,Xn.default)(["none","partially_ejected"],h.status)&&Math.round(h.time.from)<=Math.round(l)&&Math.round(h.time.to)>=Math.round(c)&&p++;if(p===this.segments.size){let d={time:{from:l,to:c},url:"",status:"none"};u(d)}}if(r.length&&i){let o=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let l of this.segments.values())for(let c of l)c.time.from>=e+o&&c.status==="fed"&&u(c)}return r.length?(await Promise.all(r.map(l=>this.sourceBufferTaskQueue.remove(l.from,l.to)))).reduce((l,c)=>l||c,!1):!1}async abortBuffer(){if(!this.sourceBuffer||!V(this.mediaSource,this.sourceBuffer))return!1;let e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;return this.sourceBufferTaskQueue.abort(t)}getDebugBufferState(){if(!(!this.sourceBuffer||!V(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}getForwardBufferDuration(e=this.getCurrentPosition()){return!this.sourceBuffer||!V(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||ve(e)?0:he(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!(!this.sourceBuffer||!V(this.mediaSource,this.sourceBuffer))){if(this.tuning.useRefactoredSearchGap)for(let i=0;i<this.sourceBuffer.buffered.length;i++)this.gaps=this.gaps.filter(r=>this.sourceBuffer&&(Math.round(r.from)<Math.round(this.sourceBuffer.buffered.start(i)*1e3)||Math.round(r.to)>Math.round(this.sourceBuffer.buffered.end(i)*1e3)));for(let i of t){let r={representation:e,from:i.time.from,to:i.time.to};for(let s=0;s<this.sourceBuffer.buffered.length;s++){let n=this.sourceBuffer.buffered.start(s)*1e3,u=this.sourceBuffer.buffered.end(s)*1e3;if(!(u<=i.time.from||n>=i.time.to)){if(n<=i.time.from&&u>=i.time.to){r=void 0;break}u>i.time.from&&u<i.time.to&&(r.from=u),n<i.time.to&&n>i.time.from&&(r.to=n)}}r&&r.to-r.from>1&&!this.gaps.some(s=>r&&s.from===r.from&&s.to===r.to)&&this.gaps.push(r)}}}detectGapsWhenIdle(e,t){if(!(this.gapDetectionIdleCallback||!this.sourceBuffer||!V(this.mediaSource,this.sourceBuffer))){if(!this.tuning.useRefactoredSearchGap)for(let i=0;i<this.sourceBuffer.buffered.length;i++)this.gaps=this.gaps.filter(r=>this.sourceBuffer&&(Math.round(r.from)<Math.round(this.sourceBuffer.buffered.start(i)*1e3)||Math.round(r.to)>Math.round(this.sourceBuffer.buffered.end(i)*1e3)));this.gapDetectionIdleCallback=pr(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:Lt.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if(ve(this.sourceBuffer)||!V(this.mediaSource,this.sourceBuffer)||ve(this.playingRepresentationId))return;let e=[];for(let i=0;i<this.sourceBuffer.buffered.length;i++){let r=Math.floor(this.sourceBuffer.buffered.start(i)*1e3),s=Math.ceil(this.sourceBuffer.buffered.end(i)*1e3);e.push({from:r,to:s})}let t=100;for(let i of this.segments.values())for(let r of i){let{status:s}=r;if(s!=="fed"&&s!=="partially_ejected")continue;let n=Math.floor(r.time.from),u=Math.ceil(r.time.to),o=e.some(c=>c.from-t<=n&&c.to+t>=u),l=e.filter(c=>n>=c.from&&n<c.to-t||u>c.from+t&&u<=c.to);o||(l.length===1?r.status="partially_ejected":this.gaps.some(c=>c.from===r.time.from||c.to===r.time.to)?r.status="partially_ejected":r.status="none")}}handleAsyncError(e,t){this.error$.next({id:t,category:Lt.VIDEO_PIPELINE,thrown:e,message:"Something went wrong"})}};var zt=a=>{let e=new URL(a);return e.searchParams.set("quic","1"),e.toString()};var Zn=a=>{let e=a.get("X-Delivery-Type"),t=a.get("X-Reused"),i=e===null?"http1":e??void 0,r=t===null?void 0:{1:!0,0:!1}[t]??void 0;return{type:i,reused:r}};import{abortable as es,assertNever as Zy,fromEvent as eT,merge as dC,now as ts,Subscription as pC,Subject as vr,ValueSubject as Dc,flattenObject as yr,ErrorCategory as is}from"@vkontakte/videoplayer-shared";var eo=a=>{let e=new URL(a);return e.searchParams.set("enable-subtitles","yes"),e.toString()};var io=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:s=!1}){this.manifestRequested=new vr;this.manifestReceived=new vr;this.firstBytesRequested=new vr;this.firstBytesReceived=new vr;this.lastConnectionType$=new Dc(void 0);this.lastConnectionReused$=new Dc(void 0);this.lastRequestFirstBytes$=new Dc(void 0);this.recoverableError$=new vr;this.error$=new vr;this.abortAllController=new X;this.subscription=new pC;this.fetchManifest=es(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=zt(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=eo(i)),this.manifestRequested.next();let r=yield this.doFetch(i,{signal:this.abortAllController.signal}).catch(to);return r?(t.log("success",yr({url:i,message:"Request successfully executed"})),t.end(),this.manifestReceived.next(),this.onHeadersReceived(r.headers),r.text()):(t.error("error",yr({url:i,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=es(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:i,onProgress:r,priority:s="auto",signal:n,measureThroughput:u=!0,isLowLatency:o=!1,bufferOptimisation:l=!1}={}){let c=e,p=new Headers,d=this.tracer.createComponentTracer("Fetch");if(i)switch(t){case 0:{p.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let v=new URL(c,location.href);v.searchParams.append("bytes",`${i.from}-${i.to}`),c=v.toString();break}default:Zy(t)}this.requestQuic&&(c=zt(c));let h=this.abortAllController.signal,f;if(n){let v=new X;if(f=dC(eT(this.abortAllController.signal,"abort"),eT(n,"abort")).subscribe(()=>{try{v.abort()}catch(E){to(E)}}),this.subscription.add(f),this.abortAllController.signal.aborted||n.aborted)try{v.abort()}catch(E){to(E)}h=v.signal}let b=0,S=ts();d.log("startRequest",yr({url:c,priority:s,rangeMethod:t,range:i,isLowLatency:o,requestStartedAt:S})),this.firstBytesRequested.next();let g=yield this.doFetch(c,{priority:s,headers:p,signal:h}),I=ts();if(!g)return d.error("error",{message:"No response in request"}),d.end(),f?.unsubscribe(),null;if(this.throughputEstimator?.addRawRtt(I-S),!g.ok||!g.body){f?.unsubscribe();let v=`Fetch error ${g.status}: ${g.statusText}`;return d.error("error",{message:v}),d.end(),Promise.reject(new Error(`Fetch error ${g.status}: ${g.statusText}`))}if(this.onHeadersReceived(g.headers),!r&&!u){f?.unsubscribe();let v=ts(),E={requestStartedAt:S,requestEndedAt:v,duration:v-S};return d.log("endRequest",yr(E)),d.end(),g.arrayBuffer()}let x=g.body;if(u){let v;[x,v]=g.body.tee(),this.throughputEstimator?.trackStream(v,o)}let y=x.getReader(),w,D=parseInt(g.headers.get("content-length")??"",10);Number.isFinite(D)&&(w=D),!w&&i&&(w=i.to-i.from+1);let L=w?new Uint8Array(w):new Uint8Array(0),A=!1,R=v=>{f?.unsubscribe(),A=!0,to(v)},T=es(h,async function*({done:v,value:E}){if(b===0&&(this.lastRequestFirstBytes$.next(ts()-S),this.firstBytesReceived.next()),h.aborted){f?.unsubscribe();return}if(!v&&E){if(l&&w)L.set(E,b),b+=E.byteLength;else{let z=new Uint8Array(L.length+E.length);z.set(L),z.set(E,L.length),L=z,b+=E.byteLength}r?.(new DataView(L.buffer),b),yield y?.read().then(T,R)}}.bind(this));yield y?.read().then(T,R),f?.unsubscribe();let q=ts(),$={failed:A,requestStartedAt:S,requestEndedAt:q,duration:q-S};return A?(d.error("endRequest",yr($)),d.end(),null):(d.log("endRequest",yr($)),d.end(),L.buffer)}.bind(this));this.fetchByteRangeRepresentation=es(this.abortAllController.signal,async function*(e,t,i){if(e.type!=="byteRange")return null;let{from:r,to:s}=e.initRange,n=r,u=s,o=!1,l,c;e.indexRange&&(l=e.indexRange.from,c=e.indexRange.to,o=s+1===l,o&&(n=Math.min(l,r),u=Math.max(c,s))),n=Math.min(n,0);let p=yield this.fetch(e.url,{range:{from:n,to:u},priority:i,measureThroughput:!1});if(!p)return null;let d=new DataView(p,r-n,s-n+1);if(!t.validateData(d))throw new Error("Invalid media file");let h=t.parseInit(d),f=e.indexRange??t.getIndexRange(h);if(!f)throw new ReferenceError("No way to load representation index");let b;if(o)b=new DataView(p,f.from-n,f.to-f.from+1);else{let g=yield this.fetch(e.url,{range:f,priority:i,measureThroughput:!1});if(!g)return null;b=new DataView(g)}let S=t.parseSegments(b,h,f);return{init:h,dataView:new DataView(p),segments:S}}.bind(this));this.fetchTemplateRepresentation=es(this.abortAllController.signal,async function*(e,t){if(e.type!=="template")return null;let i=new URL(e.initUrl,e.baseUrl).toString(),r=yield this.fetch(i,{priority:t,measureThroughput:!1});return r?{init:null,segments:e.segments.map(n=>({...n,status:"none",size:void 0})),dataView:new DataView(r)}:null}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=r,this.tracer=i.createComponentTracer("Fetcher"),this.useEnableSubtitlesParam=s}onHeadersReceived(e){let{type:t,reused:i}=Zn(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}async fetchRepresentation(e,t,i="auto"){let{type:r}=e;switch(r){case"byteRange":return await this.fetchByteRangeRepresentation(e,t,i)??null;case"template":return await this.fetchTemplateRepresentation(e,i)??null;default:Zy(r)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}async doFetch(e,t){let i=await Xe(e,t);if(i.ok)return i;let r=await i.text(),s=parseInt(r);if(!isNaN(s))switch(s){case 1:this.recoverableError$.next({id:"VideoDataLinkExpiredError",message:"Video data links have expired",category:is.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:is.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:is.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:is.FATAL});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${s})`,category:is.FATAL})}}},to=a=>{if(!Tt(a))throw a};var $t=(a,e,t)=>t*e+(1-t)*a,Cc=(a,e)=>a.reduce((t,i)=>t+i,0)/e,tT=(a,e,t,i)=>{let r=0,s=t,n=Cc(a,e),u=e<i?e:i;for(let o=0;o<u;o++)a[s]>n?r++:r--,s=(a.length+s-1)%a.length;return Math.abs(r)===u};import{isNullable as hC,ValueSubject as iT}from"@vkontakte/videoplayer-shared";var Yt=class{constructor(e){this.prevReported=void 0;this.pastMeasures=[];this.takenMeasures=0;this.measuresCursor=0;this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new iT(e.initial),this.debounced$=new iT(e.initial);let t=e.label??"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new Ae(`raw_${t}`),this.smoothedSeries$=new Ae(`smoothed_${t}`),this.reportedSeries$=new Ae(`reported_${t}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,i=0;for(let u=0;u<this.pastMeasures.length;u++)this.pastMeasures[u]!==void 0&&(t+=(this.pastMeasures[u]-this.smoothed)**2,i++);this.takenMeasures=i,t/=i;let r=Math.sqrt(t),s=this.smoothed+this.params.deviationFactor*r,n=this.smoothed-this.params.deviationFactor*r;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(e),this.updateSmoothedValue(e),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),!(this.smoothed>s||this.smoothed<n)&&(hC(this.prevReported)||Math.abs(this.smoothed-this.prevReported)/this.prevReported>=this.params.changeThreshold)&&(this.prevReported=this.smoothed,this.debounced$.next(this.smoothed),this.reportedSeries$.next(this.smoothed))}};var ro=class extends Yt{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=$t(this.slow,e,this.params.emaAlphaSlow),this.fast=$t(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var ao=class extends Yt{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=Cc(this.pastMeasures,this.takenMeasures);this.emaSmoothed=$t(this.emaSmoothed,e,this.params.emaAlpha);let i=tT(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=i?this.emaSmoothed:t}};var so=class extends Yt{constructor(t){super(t);this.furtherValues=[];this.currentTopExtremumValue=0;this.extremumInterval=t.extremumInterval}next(t){this.currentTopExtremumValue<=t?(this.currentTopExtremumValue=t,this.furtherValues=[]):this.furtherValues.length===this.extremumInterval?(super.next(this.currentTopExtremumValue),this.currentTopExtremumValue=t,this.furtherValues=[]):this.furtherValues.push(t)}updateSmoothedValue(t){this.smoothed=this.smoothed?$t(this.smoothed,t,this.params.emaAlpha):t}};var Mt=class{static getSmoothedValue(e,t,i){return i.type==="TwoEma"?new ro({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new ao({initial:e,emaAlpha:i.emaAlpha,basisTrendChangeCount:i.basisTrendChangeCount,changeThreshold:i.changeThreshold,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"})}static getLiveBufferSmoothedValue(e,t){return new so({initial:e,label:"liveEdgeDelay",...t})}};var Tr=(a,e)=>{a&&a.playbackRate!==e&&(a.playbackRate=e)};import{isNullable as fC,ValueSubject as mC}from"@vkontakte/videoplayer-shared";var rs=class a{constructor(e,t){this.currentRepresentation$=new mC(null);this.maxRepresentations=4;this.representationsCursor=0;this.representations=[];this.currentSegment=null;this.getCurrentPosition=t.getCurrentPosition,this.processStreams(e)}updateLive(e){this.processStreams(e?.streams.text)}seekLive(e){this.processStreams(e)}maintain(e=this.getCurrentPosition()){if(!fC(e))for(let t of this.representations)for(let i of t){let r=i.segmentReference,s=r.segments.length,n=r.segments[0].time.from,u=r.segments[s-1].time.to;if(e<n||e>u)continue;let o=r.segments.find(l=>l.time.from<=e&&l.time.to>=e);!o||this.currentSegment?.time.from===o.time.from&&this.currentSegment.time.to===o.time.to||(this.currentSegment=o,this.currentRepresentation$.next({...i,label:"Live Text",language:"ru",isAuto:!0,url:new URL(o.url,r.baseUrl).toString()}))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e??[]){let i=a.filterRepresentations(t.representations);if(i){this.representations[this.representationsCursor]=i,this.representationsCursor=(this.representationsCursor+1)%this.maxRepresentations;break}}}static isSupported(e){return!!e?.some(t=>a.filterRepresentations(t.representations))}static filterRepresentations(e){return e?.filter(t=>t.kind==="text"&&"segmentReference"in t&&He(t.segmentReference))}};var oo=C(at(),1),Bc=C(Ee(),1);import{assertNever as uo}from"@vkontakte/videoplayer-shared";var no=a=>{let{webmDecodingInfo:e}=B.video,t="DASH_WEBM",i="DASH_WEBM_AV1";switch(a){case"vp9":return[t,i];case"av1":return[i,t];case"none":return[];case"smooth":return e?e[i].smooth?[i,t]:e[t].smooth?[t,i]:[i,t]:[t,i];case"power_efficient":return e?e[i].powerEfficient?[i,t]:e[t].powerEfficient?[t,i]:[i,t]:[t,i];default:uo(a)}return[t,i]},rT=({webmCodec:a,androidPreferredFormat:e,iosPreferredFormat:t,preferMultiStream:i})=>{let r=[...i?["DASH_STREAMS"]:[],...no(a),"DASH_SEP","DASH_ONDEMAND",...i?[]:["DASH_STREAMS"]],s=[...i?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...i?[]:["DASH_STREAMS"]];if(B.device.isAndroid)switch(e){case"mpeg":return["MPEG",...r,"HLS","HLS_ONDEMAND"];case"hls":return["HLS","HLS_ONDEMAND",...r,"MPEG"];case"dash":return[...r,"HLS","HLS_ONDEMAND","MPEG"];case"dash_any_mpeg":return[...s,"MPEG",...no(a),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...no(a),"MPEG",...s,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...no(a),...s,"HLS","HLS_ONDEMAND"];default:uo(e)}if(B.video.nativeHlsSupported)switch(t){case"hls":return[...r,"HLS","HLS_FMP4","HLS_ONDEMAND","MPEG"];case"hls_fmp4":return[...r,"HLS_FMP4","HLS","HLS_ONDEMAND","MPEG"];default:uo(t)}return[...r,"HLS","HLS_ONDEMAND","MPEG"]},aT=({androidPreferredFormat:a,preferCMAF:e,preferWebRTC:t})=>{let i=e?["DASH_LIVE_CMAF","DASH_LIVE"]:["DASH_LIVE","DASH_LIVE_CMAF"],r=e?["HLS_LIVE_CMAF","HLS_LIVE"]:["HLS_LIVE","HLS_LIVE_CMAF"],s=[...i,...r],n=[...r,...i],u,o=B.device.isMac&&B.browser.isSafari;if(B.device.isAndroid)switch(a){case"dash":case"dash_any_mpeg":case"dash_any_webm":case"dash_sep":{u=s;break}case"hls":case"mpeg":{u=n;break}default:uo(a)}else B.video.nativeHlsSupported&&!o?u=n:o?u=e?["DASH_LIVE_CMAF","HLS_LIVE_CMAF","HLS_LIVE","DASH_LIVE"]:["HLS_LIVE","DASH_LIVE","DASH_LIVE_CMAF","HLS_LIVE_CMAF"]:u=s;return t?["WEB_RTC_LIVE",...u]:[...u,"WEB_RTC_LIVE"]},Vc=a=>a?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],lo=a=>{if(a.size===0)return;if(a.size===1){let t=a.values().next();return(0,oo.default)(t.value.split("."),0)}for(let t of a){let i=(0,oo.default)(t.split("."),0);if(i==="opus"||i==="vp09"||i==="av01")return i}let e=a.values().next();return(0,oo.default)(e.value.split("."),0)},co=a=>{let e=a.map(i=>Ir(i)),{codecs:t}=B.video;return vC().filter(i=>{if((0,Bc.default)(e,i))switch(i){case"av1":return t.av1;case"vp9":return t.vp9;case"avc1":return t.h264;case"hev1":return t.h265;default:return!1}else return!1})},po=a=>{let e=a.map(i=>Ir(i)),{codecs:t}=B.video;return yC().filter(i=>{if((0,Bc.default)(e,i))switch(i){case"opus":return t.opus;case"mp4a":return t.aac;default:return!1}else return!1})},Ir=a=>a.split(".")[0].replace("0",""),vC=()=>["av1","vp9","hev1","avc1"],yC=()=>["opus","mp4a"];var AC=["timeupdate","progress","play","seeked","stalled","waiting"],PC=["timeupdate","progress","loadeddata","playing","seeked"];var fo=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.bufferManagers=[];this.subscription=new oT;this.representationSubscription=new oT;this.state$=new F("none");this.currentVideoRepresentation$=new ee(void 0);this.currentVideoRepresentationInit$=new ee(void 0);this.currentAudioRepresentation$=new ee(void 0);this.currentVideoSegmentLength$=new ee(0);this.currentAudioSegmentLength$=new ee(0);this.error$=new Kt;this.manifestRequested=new Kt;this.manifestReceived=new Kt;this.firstBytesRequested=new Kt;this.firstBytesReceived=new Kt;this.lastConnectionType$=new ee(void 0);this.lastConnectionReused$=new ee(void 0);this.lastRequestFirstBytes$=new ee(void 0);this.currentLiveTextRepresentation$=new ee(null);this.isLive$=new ee(!1);this.isActiveLive$=new ee(!1);this.isLowLatency$=new ee(!1);this.liveDuration$=new ee(0);this.liveSeekableDuration$=new ee(0);this.liveAvailabilityStartTime$=new ee(0);this.liveStreamStatus$=new ee(void 0);this.bufferLength$=new ee(0);this.liveLatency$=new ee(void 0);this.liveLoadBufferLength$=new ee(0);this.livePositionFromPlayer$=new ee(0);this.currentStallDuration$=new ee(0);this.videoLastDataObtainedTimestamp$=new ee(0);this.fetcherRecoverableError$=new Kt;this.fetcherError$=new Kt;this.liveStreamEndTimestamp=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.forceEnded$=new Kt;this.gapWatchdogActive=!1;this.destroyController=new X;this.initManifest=Oc(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=se(t,i,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),this.manifest?.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:ot.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=Oc(this.destroyController.signal,async function*(){this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(o=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:ot.NETWORK,message:"Failed to load manifest",thrown:o})});if(!e)return null;let t=null;try{t=Yn(e??"",this.manifestUrlString)}catch(o){let l=Gn(e)??{id:"ManifestParsing",category:ot.PARSER,message:"Failed to parse MPD manifest",thrown:o};this.error$.next(l)}if(!t)return null;let i=(o,l,c)=>!!(this.element?.canPlayType?.(l)&&Ue()?.isTypeSupported?.(`${l}; codecs="${c}"`)||o==="text");if(t.live){this.isLive$.next(!!t.live);let{availabilityStartTime:o,latestSegmentPublishTime:l,streamIsUnpublished:c,streamIsAlive:p}=t.live,d=(t.duration??0)/1e3;this.liveSeekableDuration$.next(-1*d),this.liveDuration$.next((l-o)/1e3),this.liveAvailabilityStartTime$.next(t.live.availabilityStartTime);let h="active";p||(h=c?"unpublished":"unexpectedly_down"),this.liveStreamStatus$.next(h)}let r={text:t.streams.text,video:[],audio:[]},s,n;for(let o of["video","audio"]){let c=t.streams[o].filter(({mime:d,codecs:h})=>i(o,d,h));r[o]=c;let p;if(this.tuning.dash.codecsPrioritizeEnabled){let d=c.map(({codecs:h})=>h);o==="audio"&&(n=po(d),p=n[0]),o==="video"&&(s=co(d),this.forceVideoCodec&&(0,lT.default)(s,this.forceVideoCodec)?p=this.forceVideoCodec:p=s[0]),p&&(r[o]=c.filter(({codecs:h})=>Ir(h)===p))}else{let d=new Set(c.map(({codecs:h})=>h));p=lo(d),p&&(r[o]=c.filter(({codecs:h})=>h.startsWith(p)))}if(o==="video"){let d=this.tuning.preferHDR,h=r.video.some(b=>b.hdr),f=r.video.some(b=>!b.hdr);B.display.isHDR&&d&&h?r.video=r.video.filter(b=>b.hdr):f&&(r.video=r.video.filter(b=>!b.hdr))}}let u={...t,streams:r};return this.tuning.dash.codecsPrioritizeEnabled&&(u.codecs={video:s,audio:n}),this.tracer.log("updateManifestEnd",ss(u)),u}.bind(this));this.initRepresentations=Oc(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initRepresentationsStart",ss({initialVideo:e,initialAudio:t,sourceHls:i})),Er(this.manifest),Er(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let r=d=>{this.representationSubscription.add(Dt(d,"error").pipe(ho(h=>!!this.element?.played.length)).subscribe(h=>{this.error$.next({id:"VideoSource",category:ot.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:h})}))};this.source=In();let s=document.createElement("source");if(r(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),tr())if(i){let d=document.createElement("source");r(d),d.type="application/x-mpegurl",d.src=i.url,this.element.appendChild(d)}else this.element.disableRemotePlayback=!0;this.isActiveLive$.next(this.isLive$.getValue());let n={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),manifest:this.manifest},u=this.manifest.streams.video.reduce((d,h)=>[...d,...h.representations],[]);if(this.videoBufferManager=new Za("video",this.source,u,n),this.bufferManagers=[this.videoBufferManager],ns(t)){let d=this.manifest.streams.audio.reduce((h,f)=>[...h,...f.representations],[]);this.audioBufferManager=new Za("audio",this.source,d,n),this.bufferManagers.push(this.audioBufferManager)}rs.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new rs(this.manifest.streams.text,n)),this.representationSubscription.add(this.fetcher.manifestRequested.subscribe(this.manifestRequested)),this.representationSubscription.add(this.fetcher.manifestReceived.subscribe(this.manifestReceived)),this.representationSubscription.add(this.fetcher.firstBytesRequested.subscribe(this.firstBytesRequested)),this.representationSubscription.add(this.fetcher.firstBytesReceived.subscribe(this.firstBytesReceived)),this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$));let o=()=>{this.stallWatchdogSubscription?.unsubscribe(),this.currentStallDuration$.next(0)};if(this.representationSubscription.add(xi(...PC.map(d=>Dt(this.element,d))).pipe(wr(d=>this.element?he(this.element.buffered,this.element.currentTime*1e3):0),as(),xC(d=>{d>this.tuning.dash.bufferEmptinessTolerance&&o()})).subscribe(this.bufferLength$)),this.representationSubscription.add(xi(Dt(this.element,"ended"),this.forceEnded$).subscribe(()=>{o()})),this.isLive$.getValue()){this.subscription.add(this.liveDuration$.pipe(as()).subscribe(h=>this.liveStreamEndTimestamp=Nc())),this.subscription.add(Dt(this.element,"pause").subscribe(()=>{this.livePauseWatchdogSubscription=Fc(1e3).subscribe(h=>{let f=Ut(this.manifestUrlString,2);this.manifestUrlString=se(this.manifestUrlString,f+1e3,2),this.liveStreamStatus$.getValue()==="active"&&this.updateManifest()}),this.subscription.add(this.livePauseWatchdogSubscription)})).add(Dt(this.element,"play").subscribe(h=>this.livePauseWatchdogSubscription?.unsubscribe())),this.representationSubscription.add(xr({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(wr(({isActiveLive:h,isLowLatency:f})=>h&&f),as()).subscribe(h=>{this.isManualDecreasePlaybackInLive()||Tr(this.element,1)})),this.representationSubscription.add(xr({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(ho(({bufferLength:h,isActiveLive:f,isLowLatency:b})=>f&&b&&!!h)).subscribe(({bufferLength:h})=>this.liveBuffer.next(h))),this.representationSubscription.add(this.videoBufferManager.currentLowLatencySegmentLength$.subscribe(h=>{if(!this.isActiveLive$.getValue()&&!this.isLowLatency$.getValue()&&!h)return;let f=this.liveSeekableDuration$.getValue()-h/1e3;this.liveSeekableDuration$.next(Math.max(f,-1*this.tuning.dashCmafLive.maxLiveDuration)),this.liveDuration$.next(this.liveDuration$.getValue()+h/1e3)})),this.representationSubscription.add(xr({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe(ho(({isLive:h})=>h),as((h,f)=>f.bufferLength<h.bufferLength),wr(({rtt:h,bufferLength:f,segmentServerLatency:b})=>{let S=Ut(this.manifestUrlString,2);return(h/2+f+b+S)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add(xr({liveBuffer:this.liveBuffer.smoothed$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).subscribe(({liveBuffer:h,isActiveLive:f,isLowLatency:b})=>{if(!b||!f)return;let S=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,g=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,I=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,x=h-S;if(this.isManualDecreasePlaybackInLive())return;let y=1;Math.abs(x)>g&&(y=1+Math.sign(x)*I),Tr(this.element,y)})),this.representationSubscription.add(this.bufferLength$.subscribe(h=>{let f=0;if(h){let b=(this.element?.currentTime??0)*1e3;f=Math.min(...this.bufferManagers.map(g=>g.getLiveSegmentsToLoadState(this.manifest)?.to??b))-b}this.liveLoadBufferLength$.getValue()!==f&&this.liveLoadBufferLength$.next(f)}));let d=0;this.representationSubscription.add(xr({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(wC(1e3)).subscribe(async({liveLoadBufferLength:h,bufferLength:f})=>{if(!this.element||this.isUpdatingLive)return;let b=this.element.playbackRate,S=Ut(this.manifestUrlString,2),g=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,I=Math.min(g,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*b),x=this.tuning.dashCmafLive.normalizedActualBufferOffset*b,y=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*b,w=isFinite(h)?h:f,D=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),L=g<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next(L);let A="none";if(D?A="active_low_latency":this.isLowLatency$.getValue()&&L?(this.bufferManagers.forEach(R=>R.proceedLowLatencyLive()),A="active_low_latency"):S!==0&&w<I?A="live_forward_buffering":w<I+y&&(A="live_with_target_offset"),isFinite(h)&&(d=h>d?h:d),A==="live_forward_buffering"||A==="live_with_target_offset"){let R=d-(I+x),T=this.normolizeLiveOffset(Math.trunc(S+R/b)),q=Math.abs(T-S),$=0;!h||q<=this.tuning.dashCmafLive.offsetCalculationError?$=S:T>0&&q>this.tuning.dashCmafLive.offsetCalculationError&&($=T),this.manifestUrlString=se(this.manifestUrlString,$,2)}(A==="live_with_target_offset"||A==="live_forward_buffering")&&(d=0,await this.updateLive())},h=>{this.error$.next({id:"updateLive",category:ot.VIDEO_PIPELINE,thrown:h,message:"Failed to update live with subscription"})}))}let l=xi(...this.bufferManagers.map(d=>d.fullyBuffered$)).pipe(wr(()=>this.bufferManagers.every(d=>d.fullyBuffered$.getValue()))),c=xi(...this.bufferManagers.map(d=>d.onLastSegment$)).pipe(wr(()=>this.bufferManagers.some(d=>d.onLastSegment$.getValue()))),p=xr({allBuffersFull:l,someBufferEnded:c}).pipe(as(),wr(({allBuffersFull:d,someBufferEnded:h})=>d&&h),ho(d=>d));if(this.representationSubscription.add(xi(this.forceEnded$,p).subscribe(()=>{if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(d=>!d.updating))try{this.source?.endOfStream()}catch(d){this.error$.next({id:"EndOfStream",category:ot.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:d})}})),this.representationSubscription.add(xi(...this.bufferManagers.map(d=>d.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.representationSubscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&(this.representationSubscription.add(this.audioBufferManager.playingRepresentation$.subscribe(this.currentAudioRepresentation$)),this.representationSubscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$))),this.liveTextManager&&this.representationSubscription.add(this.liveTextManager.currentRepresentation$.subscribe(this.currentLiveTextRepresentation$)),this.source.readyState!=="open"){let d=this.tuning.dash.sourceOpenTimeout>=0;yield new Promise(h=>{d&&(this.timeoutSourceOpenId=setTimeout(()=>{if(this.source?.readyState==="open"){h();return}this.error$.next({id:"OpenOfStream",category:ot.VIDEO_PIPELINE,message:"Failed to open MediaSource",thrown:new Error("Timeout reject when wait sourceopen event"),traceAsLog:!0})},this.tuning.dash.sourceOpenTimeout)),this.source?.addEventListener("sourceopen",()=>{this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),h()},{once:!0})})}if(!this.isLive$.getValue()){let d=[this.manifest.duration??0,...(0,qc.default)((0,qc.default)([...this.manifest.streams.audio,...this.manifest.streams.video],h=>h.representations),h=>{let f=[];return h.duration&&f.push(h.duration),He(h.segmentReference)&&h.segmentReference.totalSegmentsDurationMs&&f.push(h.segmentReference.totalSegmentsDurationMs),f})];this.source.duration=Math.max(...d)/1e3}this.audioBufferManager&&ns(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState("representations_ready"),this.tracer.log("initRepresentationsEnd")}.bind(this));this.tick=()=>{if(!this.element||!this.videoBufferManager||this.source?.readyState!=="open")return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),this.audioBufferManager?.maintain(e),this.liveTextManager?.maintain(e),(this.videoBufferManager.gaps.length||this.audioBufferManager?.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=Fc(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),t=>{this.error$.next({id:"GapWatchdog",category:ot.WTF,message:"Error handling gaps",thrown:t})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name),this.forceVideoCodec=e.forceVideoCodec,this.fetcher=new io({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer,useEnableSubtitlesParam:e.tuning.useEnableSubtitlesParam}),this.subscription.add(this.fetcher.recoverableError$.subscribe(this.fetcherRecoverableError$)),this.subscription.add(this.fetcher.error$.subscribe(this.fetcherError$)),this.liveBuffer=Mt.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.bufferEstimator}),this.initTracerSubscription()}async seekLive(e){Er(this.element);let t=this.liveStreamStatus$.getValue()!=="active"?Nc()-this.liveStreamEndTimestamp:0,i=this.normolizeLiveOffset(e+t);this.isActiveLive$.next(i===0),this.manifestUrlString=se(this.manifestUrlString,i,2),this.manifest=await this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,await this.videoBufferManager?.seekLive(this.manifest.streams.video),await this.audioBufferManager?.seekLive(this.manifest.streams.audio),this.liveTextManager?.seekLive(this.manifest.streams.text))}initBuffer(){Er(this.element),this.state$.setState("running"),this.subscription.add(xi(...AC.map(e=>Dt(this.element,e)),Dt(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:ot.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(Dt(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(Dt(this.element,"waiting").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&Se(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{if(!this.element||this.source?.readyState!=="open")return;let t=this.currentStallDuration$.getValue();t+=50,this.currentStallDuration$.next(t);let i={timeInWaiting:t},r=Nc(),s=100,n=this.videoBufferManager?.lastDataObtainedTimestamp??0;this.videoLastDataObtainedTimestamp$.next(n);let u=this.audioBufferManager?.lastDataObtainedTimestamp??0,o=this.videoBufferManager?.getForwardBufferDuration()??0,l=this.audioBufferManager?.getForwardBufferDuration()??0,c=o<s&&r-n>this.tuning.dash.crashOnStallTWithoutDataTimeout,p=this.audioBufferManager&&l<s&&r-u>this.tuning.dash.crashOnStallTWithoutDataTimeout;if((c||p)&&t>this.tuning.dash.crashOnStallTWithoutDataTimeout||t>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${t} ms`);if(this.isLive$.getValue()&&t%2e3===0){let d=this.normolizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);this.seekLive(d).catch(h=>{this.error$.next({id:"stallIntervalCallback",category:ot.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:h})}),i.liveLastOffset=d}else{let d=this.element.currentTime*1e3;this.videoBufferManager?.maintain(d),this.audioBufferManager?.maintain(d),i.position=d}this.tracer.log("stallIntervalCallback",ss(i))};this.stallWatchdogSubscription?.unsubscribe(),this.stallWatchdogSubscription=Fc(50).subscribe(e,t=>{this.error$.next({id:"StallWatchdogCallback",category:ot.NETWORK,message:"Can't restore DASH after stall.",thrown:t})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t,i=!1){let r={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return this.tuning.useNewSwitchTo?this.currentStallDuration$.getValue()>0?r?.switchToWithPreviousAbort(t,i):r?.switchTo(t,i):r?.switchToOld(t,i)}async seek(e,t){Er(this.element),Er(this.videoBufferManager);let i;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?i=e:i=Math.max(this.videoBufferManager.findSegmentStartTime(e)??e,this.audioBufferManager?.findSegmentStartTime(e)??e),this.warmUpMediaSourceIfNeeded(i),Se(this.element.buffered,i)||await Promise.all([this.videoBufferManager.abort(),this.audioBufferManager?.abort()]),!(nT(this.element)||nT(this.videoBufferManager))&&(this.videoBufferManager.maintain(i),this.audioBufferManager?.maintain(i),this.element.currentTime=i/1e3,this.tracer.log("seek",ss({requestedPosition:e,forcePrecise:t,position:i})))}warmUpMediaSourceIfNeeded(e=this.element?.currentTime){ns(this.element)&&ns(this.source)&&ns(e)&&this.source?.readyState==="ended"&&this.element.duration*1e3-e>this.tuning.dash.seekBiasInTheEnd&&this.bufferManagers.forEach(t=>t.warmUpMediaSource())}get isStreamEnded(){return this.source?.readyState==="ended"}stop(){this.tracer.log("stop"),this.element?.querySelectorAll("source").forEach(e=>{URL.revokeObjectURL(e.src),e.remove()}),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),this.videoBufferManager?.destroy(),this.videoBufferManager=null,this.audioBufferManager?.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getStreams(){return this.manifest?.streams}getCodecs(){return this.manifest?.codecs}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),this.source?.readyState==="open"&&Array.from(this.source.sourceBuffers).every(e=>!e.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}initTracerSubscription(){let e=EC(this.tracer.error.bind(this.tracer));this.subscription.add(this.error$.subscribe(e("error")))}isManualDecreasePlaybackInLive(){if(!this.element||!this.isLive$.getValue())return!1;let e=1-this.element.playbackRate;return Number(e.toFixed(2))>Number(this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup.toFixed(2))}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}async updateLive(){this.isUpdatingLive=!0,this.manifest=await this.updateManifest(),this.manifest&&(this.bufferManagers.forEach(e=>e.updateLive(this.manifest)),this.liveTextManager?.updateLive(this.manifest)),this.isUpdatingLive=!1}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.getDebugBufferState();if(!e)return;let t=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),i={isJumpGapAfterSeekLive:this.isJumpGapAfterSeekLive,isActiveLowLatency:t,initialCurrentTime:this.element.currentTime};this.isJumpGapAfterSeekLive&&!t&&this.element.currentTime>e.to&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let r=this.element.currentTime*1e3,s=[],n=this.element.readyState===1?this.tuning.endGapTolerance:0;for(let u of this.bufferManagers)for(let o of u.gaps)u.playingRepresentation$.getValue()===o.representation&&o.from-n<=r&&o.to+n>r&&(this.element.duration*1e3-o.to<this.tuning.endGapTolerance?s.push(1/0):s.push(o.to));if(s.length){let u=Math.max(...s)+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,u===1/0?this.forceEnded$.next():(this.element.currentTime=u/1e3,i={...i,gapEnds:s,jumpTo:u,resultCurrentTime:this.element.currentTime},this.tracer.log("jumpGap",ss(i)))}}calculateDurationFromSegments(){return Math.max(this.videoBufferManager?.calculateDurationFromSegments()||0,this.audioBufferManager?.calculateDurationFromSegments()||0)}};var mo=class{constructor(e,t){this.fov=e,this.orientation=t}};var bo=class{constructor(e,t){this.rotating=!1;this.fading=!1;this.lastTickTS=0;this.lastCameraTurnTS=0;this.fadeStartSpeed=null;this.fadeTime=0;this.camera=e,this.options=t,this.rotationSpeed={x:0,y:0,z:0},this.fadeCorrection=1/(this.options.speedFadeTime/1e3)**2}turnCamera(e=0,t=0,i=0){this.pointCameraTo(this.camera.orientation.x+e,this.camera.orientation.y+t,this.camera.orientation.z+i)}pointCameraTo(e=0,t=0,i=0){t=this.limitCameraRotationY(t);let r=e-this.camera.orientation.x,s=t-this.camera.orientation.y,n=i-this.camera.orientation.z;this.camera.orientation.x=e,this.camera.orientation.y=t,this.camera.orientation.z=i,this.lastCameraTurn={x:r,y:s,z:n},this.lastCameraTurnTS=Date.now()}setRotationSpeed(e,t,i){this.rotationSpeed.x=e??this.rotationSpeed.x,this.rotationSpeed.y=t??this.rotationSpeed.y,this.rotationSpeed.z=i??this.rotationSpeed.z}startRotation(){this.rotating=!0}stopRotation(e=!1){e?(this.setRotationSpeed(0,0,0),this.fadeStartSpeed=null):this.startFading(this.rotationSpeed.x,this.rotationSpeed.y,this.rotationSpeed.z),this.rotating=!1}onCameraRelease(){if(this.lastCameraTurn&&this.lastCameraTurnTS){let e=Date.now()-this.lastCameraTurnTS;if(e<this.options.speedFadeThreshold){let t=(1-e/this.options.speedFadeThreshold)*this.options.rotationSpeedCorrection;this.startFading(this.lastCameraTurn.x*t,this.lastCameraTurn.y*t,this.lastCameraTurn.z*t)}}}startFading(e,t,i){this.setRotationSpeed(e,t,i),this.fadeStartSpeed={...this.rotationSpeed},this.fading=!0}stopFading(){this.fadeStartSpeed=null,this.fading=!0,this.fadeTime=0}limitCameraRotationY(e){return Math.max(-this.options.maxYawAngle,Math.min(e,this.options.maxYawAngle))}tick(e){if(!this.lastTickTS){this.lastTickTS=e,this.lastCameraTurnTS=Date.now();return}let t=e-this.lastTickTS,i=t/1e3;if(this.rotating)this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*i,this.rotationSpeed.y*this.options.rotationSpeedCorrection*i,this.rotationSpeed.z*this.options.rotationSpeedCorrection*i);else if(this.fading&&this.fadeStartSpeed){let r=-this.fadeCorrection*(this.fadeTime/1e3)**2+1;this.setRotationSpeed(this.fadeStartSpeed.x*r,this.fadeStartSpeed.y*r,this.fadeStartSpeed.z*r),r>0?this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*i,this.rotationSpeed.y*this.options.rotationSpeedCorrection*i,this.rotationSpeed.z*this.options.rotationSpeedCorrection*i):(this.stopRotation(!0),this.stopFading()),this.fadeTime=Math.min(this.fadeTime+t,this.options.speedFadeTime)}this.lastTickTS=e}};var cT=`attribute vec2 a_vertex;
|
|
124
|
+
`})|(?<privateuse2>${e}))$`.replace(/[\s\t\n]/g,"");return new RegExp(d,"i")}var Qy=a=>{if(!a?.startsWith("P"))return;let e=(n,u)=>{let o=n?parseFloat(n.replace(",",".")):NaN;return(isNaN(o)?0:o)*u},i=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(a),r=i?.[1]==="-"?-1:1,s={days:e(i?.[5],r),hours:e(i?.[6],r),minutes:e(i?.[7],r),seconds:e(i?.[8],r)};return s.days*24*60*60*1e3+s.hours*60*60*1e3+s.minutes*60*1e3+s.seconds*1e3},nt=(a,e)=>{let t=a;t=(0,$c.default)(t,"$$","$");let i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[r,s]of(0,Gy.default)(i)){let n=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=(0,$c.default)(t,n,(u,o)=>Hy(s)?u:Hy(o)?s:(0,Wy.default)(s,parseInt(o,10),"0"))}return t},ro=(a,e)=>{let i=new DOMParser().parseFromString(a,"application/xml"),r={video:[],audio:[],text:[]},s=i.children[0],n=Array.from(s.querySelectorAll("MPD > BaseURL").values()).map(L=>L.textContent?.trim()??""),u=(0,zy.default)(n,0)??"",o=s.getAttribute("type")==="dynamic",l=s.getAttribute("availabilityStartTime"),d=s.getAttribute("publishTime"),h=s.getElementsByTagName("vk:Attrs")[0],c=h?.getElementsByTagName("vk:XLatestSegmentPublishTime")[0].textContent,p=h?.getElementsByTagName("vk:XStreamIsLive")[0].textContent,f=h?.getElementsByTagName("vk:XStreamIsUnpublished")[0].textContent,b=h?.getElementsByTagName("vk:XPlaybackDuration")[0].textContent,S;o&&(S={availabilityStartTime:l?new Date(l).getTime():0,publishTime:d?new Date(d).getTime():0,latestSegmentPublishTime:c?new Date(c).getTime():0,streamIsAlive:p==="yes",streamIsUnpublished:f==="yes"});let g,T=s.getAttribute("mediaPresentationDuration"),E=[...s.getElementsByTagName("Period")],y=E.reduce((L,I)=>({...L,[I.id]:I.children}),{}),w=E.reduce((L,I)=>({...L,[I.id]:I.getAttribute("duration")}),{});T?g=Qy(T):(0,Mc.default)(w).filter(L=>L).length&&!o?g=(0,Mc.default)(w).reduce((L,I)=>L+(Qy(I)??0),0):b&&(g=parseInt(b,10));let k=0,$=s.getAttribute("profiles")?.split(",")??[];for(let L of E.map(I=>I.id))for(let I of y[L]){let q=I.getAttribute("id")??"id"+(k++).toString(10),M=I.getAttribute("mimeType")??"",v=I.getAttribute("codecs")??"",x=I.getAttribute("contentType")??M?.split("/")[0],z=I.getAttribute("profiles")?.split(",")??[],D=jy(I.getAttribute("lang")??"")??{},j=I.querySelector("Label")?.textContent?.trim()??void 0,J=I.querySelectorAll("Representation"),ie=I.querySelector("SegmentTemplate"),ue=I.querySelector("Role")?.getAttribute("value")??void 0,me=x,be={id:q,language:D.language,isDefault:ue==="main",label:j,codecs:v,hdr:me==="video"&&Lc(v),mime:M,representations:[]};for(let H of J){let U=H.getAttribute("lang")??void 0,Le=j??I.getAttribute("label")??H.getAttribute("label")??void 0,Te=H.querySelector("BaseURL")?.textContent?.trim()??"",de=new URL(Te||u,e).toString(),Ge=H.getAttribute("mimeType")??M,Bt=H.getAttribute("codecs")??v??"",lt;if(x==="text"){let Oe=H.getAttribute("id")||"",Vt=D.privateuse?.includes("x-auto")||Oe.includes("_auto"),ct=H.querySelector("SegmentTemplate");if(ct){let Br={representationId:H.getAttribute("id")??void 0,bandwidth:H.getAttribute("bandwidth")??void 0},Bs=parseInt(H.getAttribute("bandwidth")??"",10)/1e3,Vs=parseInt(ct.getAttribute("startNumber")??"",10)??1,Ci=parseInt(ct.getAttribute("timescale")??"",10),Zo=ct.querySelectorAll("SegmentTimeline S")??[],Bi=ct.getAttribute("media");if(!Bi)continue;let _s=[],Os=0,Fs="",Vi=0,Vr=Vs,Ie=0;for(let Je of Zo){let ai=parseInt(Je.getAttribute("d")??"",10),We=parseInt(Je.getAttribute("r")??"",10)||0,_t=parseInt(Je.getAttribute("t")??"",10);Ie=Number.isFinite(_t)?_t:Ie;let si=ai/Ci*1e3,_i=Ie/Ci*1e3;for(let dt=0;dt<We+1;dt++){let Ot=nt(Bi,{...Br,segmentNumber:Vr.toString(10),segmentTime:(Ie+dt*ai).toString(10)}),Oi=(_i??0)+dt*si,Or=Oi+si;Vr++,_s.push({time:{from:Oi,to:Or},url:Ot})}Ie+=(We+1)*ai,Os+=(We+1)*si}Vi=Ie/Ci*1e3,Fs=nt(Bi,{...Br,segmentNumber:Vr.toString(10),segmentTime:Ie.toString(10)});let _r={time:{from:Vi,to:1/0},url:Fs},Et={type:"template",baseUrl:de,segmentTemplateUrl:Bi,initUrl:"",totalSegmentsDurationMs:Os,segments:_s,nextSegmentBeyondManifest:_r,timescale:Ci};lt={id:Oe,kind:"text",segmentReference:Et,profiles:[],duration:g,bitrate:Bs,mime:"",codecs:"",width:0,height:0,isAuto:Vt}}else lt={id:Oe,isAuto:Vt,kind:"text",url:de}}else{let Oe=H.getAttribute("contentType")??Ge?.split("/")[0]??x,Vt=I.getAttribute("profiles")?.split(",")??[],ct=parseInt(H.getAttribute("width")??"",10),Br=parseInt(H.getAttribute("height")??"",10),Bs=parseInt(H.getAttribute("bandwidth")??"",10)/1e3,Vs=H.getAttribute("frameRate")??"",Ci=H.getAttribute("quality")??void 0,Zo=Vs?Uy(Vs):void 0,Bi=H.getAttribute("id")??"id"+(k++).toString(10),_s=Oe==="video"?`${Br}p`:Oe==="audio"?`${Bs}Kbps`:Bt,Os=`${Bi}@${_s}`,Fs=[...$,...z,...Vt],Vi,Vr=H.querySelector("SegmentBase"),Ie=H.querySelector("SegmentTemplate")??ie;if(Vr){let Et=H.querySelector("SegmentBase Initialization")?.getAttribute("range")??"",[Je,ai]=Et.split("-").map(Ot=>parseInt(Ot,10)),We={from:Je,to:ai},_t=H.querySelector("SegmentBase")?.getAttribute("indexRange"),[si,_i]=_t?_t.split("-").map(Ot=>parseInt(Ot,10)):[],dt=_t?{from:si,to:_i}:void 0;Vi={type:"byteRange",url:de,initRange:We,indexRange:dt}}else if(Ie){let Et={representationId:H.getAttribute("id")??void 0,bandwidth:H.getAttribute("bandwidth")??void 0},Je=parseInt(Ie.getAttribute("timescale")??"",10),ai=Ie.getAttribute("initialization")??"",We=Ie.getAttribute("media"),_t=parseInt(Ie.getAttribute("startNumber")??"",10)??1,si=nt(ai,Et);if(!We)throw new ReferenceError("No media attribute in SegmentTemplate");let _i=Ie.querySelectorAll("SegmentTimeline S")??[],dt=[],Ot=0,Oi="",Or=0;if(_i.length){let Ns=_t,Ze=0;for(let Fi of _i){let pt=parseInt(Fi.getAttribute("d")??"",10),ni=parseInt(Fi.getAttribute("r")??"",10)||0,qs=parseInt(Fi.getAttribute("t")??"",10);Ze=Number.isFinite(qs)?qs:Ze;let eu=pt/Je*1e3,VI=Ze/Je*1e3;for(let Us=0;Us<ni+1;Us++){let _I=nt(We,{...Et,segmentNumber:Ns.toString(10),segmentTime:(Ze+Us*pt).toString(10)}),Nd=(VI??0)+Us*eu,OI=Nd+eu;Ns++,dt.push({time:{from:Nd,to:OI},url:_I})}Ze+=(ni+1)*pt,Ot+=(ni+1)*eu}Or=Ze/Je*1e3,Oi=nt(We,{...Et,segmentNumber:Ns.toString(10),segmentTime:Ze.toString(10)})}else if(sC(g)){let Ze=parseInt(Ie.getAttribute("duration")??"",10)/Je*1e3,Fi=Math.ceil(g/Ze),pt=0;for(let ni=1;ni<Fi;ni++){let qs=nt(We,{...Et,segmentNumber:ni.toString(10),segmentTime:pt.toString(10)});dt.push({time:{from:pt,to:pt+Ze},url:qs}),pt+=Ze}Or=pt,Oi=nt(We,{...Et,segmentNumber:Fi.toString(10),segmentTime:pt.toString(10)})}let BI={time:{from:Or,to:1/0},url:Oi};Vi={type:"template",baseUrl:de,segmentTemplateUrl:We,initUrl:si,totalSegmentsDurationMs:Ot,segments:dt,nextSegmentBeyondManifest:BI,timescale:Je}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!Oe||!Ge)continue;let _r={video:"video",audio:"audio",text:"text"}[Oe];if(!_r)continue;me||=_r,lt={id:Os,kind:_r,segmentReference:Vi,profiles:Fs,duration:g,bitrate:Bs,mime:Ge,codecs:Bt,width:ct,height:Br,fps:Zo,quality:Ci}}be.language||=U,be.label||=Le,be.mime||=Ge,be.codecs||=Bt,be.hdr||=me==="video"&&Lc(Bt),be.representations.push(lt)}if(me){let H=r[me].find(U=>U.id===be.id);if(H&&be.representations.every(U=>U.segmentReference.type==="template"))for(let U of H.representations){let Te=be.representations.find(Ge=>Ge.id===U.id)?.segmentReference,de=U.segmentReference;de.segments.push(...Te.segments),de.nextSegmentBeyondManifest=Te.nextSegmentBeyondManifest}else r[me].push(be)}}return{duration:g,streams:r,baseUrls:n,live:S}};var Dc=C(at(),1);import{videoSizeToQuality as nC}from"@vkontakte/videoplayer-shared";var Za=({id:a,width:e,height:t,bitrate:i,fps:r,quality:s,streamId:n})=>{let u=(s?Ht(s):void 0)??nC({width:e,height:t});return u&&{id:a,quality:u,bitrate:i,size:{width:e,height:t},fps:r,streamId:n}},Yy=({id:a,bitrate:e})=>({id:a,bitrate:e}),Ky=({language:a,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:a,label:e}),Xy=({language:a,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:a,label:e}),Cc=({id:a,language:e,label:t,codecs:i,isDefault:r})=>({id:a,language:e,label:t,codec:(0,Dc.default)(i.split("."),0),isDefault:r}),Bc=({id:a,language:e,label:t,hdr:i,codecs:r})=>({id:a,language:e,hdr:i,label:t,codec:(0,Dc.default)(r.split("."),0)}),Vc=a=>"url"in a,je=a=>a.type==="template";import{isNonNullable as Jy}from"@vkontakte/videoplayer-shared";var V=(a,e)=>Jy(a)&&Jy(e)&&a.readyState==="open"&&oC(a,e);function oC(a,e){for(let t=0;t<a.activeSourceBuffers.length;++t)if(a.activeSourceBuffers[t]===e)return!0;return!1}var es=class{constructor(e,t,i,{fetcher:r,tuning:s,getCurrentPosition:n,isActiveLowLatency:u,compatibilityMode:o=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new xi(0);this.currentLowLatencySegmentLength$=new xi(0);this.currentSegmentLength$=new xi(0);this.onLastSegment$=new xi(!1);this.fullyBuffered$=new xi(!1);this.playingRepresentation$=new xi(void 0);this.playingRepresentationInit$=new xi(void 0);this.error$=new cC;this.gaps=[];this.subscription=new dC;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new X;this.switchAbortController=new X;this.destroyAbortController=new X;this.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=Wt(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);Re(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new Wv(this.sourceBuffer),this.subscription.add(_c(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let u,o=this.mediaSource.readyState;o!=="open"&&(u={id:`SegmentEjection_source_${o}`,category:Lt.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),u??={id:"SegmentEjection",category:Lt.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n},this.error$.next(u)})),this.subscription.add(_c(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:Lt.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let u=this.getCurrentPosition();if(!this.sourceBuffer||!u||!V(this.mediaSource,this.sourceBuffer))return;let o=Math.min(this.bufferLimit,mr(this.sourceBuffer.buffered)*.8);this.bufferLimit=o;let l=this.getForwardBufferDuration(u),d=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(u,n*2,l<d).catch(h=>{this.handleAsyncError(h,"pruneBuffer")})})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(n=>this.error$.next(n))),yield this.loadInit(t,"high",!0);let i=this.initData.get(t.id),r=this.segments.get(t.id),s=this.parsedInitData.get(t.id);Re(i,"No init buffer for starting representation"),Re(r,"No segments for starting representation"),i instanceof ArrayBuffer&&(this.searchGaps(r,t),yield this.sourceBufferTaskQueue.append(i,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(s))}.bind(this));this.switchTo=Wt(this.destroyAbortController.signal,async function*(e,t=!1){if(!V(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);Re(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if(le(s)||le(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),Re(r,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!V(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer();else{let n=this.getCurrentPosition();zt(n)&&!this.isLive&&(this.bufferLimit=1/0,await this.pruneBuffer(n,1/0,!0)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}this.maintain()}}.bind(this));this.switchToOld=Wt(this.destroyAbortController.signal,async function*(e,t=!1){if(!V(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);Re(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if(le(s)||le(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),Re(r,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!V(this.mediaSource,this.sourceBuffer)))if(yield this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer(),this.maintain();else{let n=this.getCurrentPosition();zt(n)&&(this.isLive||(this.bufferLimit=1/0,await this.pruneBuffer(n,1/0,!0)),this.maintain(n)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}}.bind(this));this.seekLive=Wt(this.destroyAbortController.signal,async function*(e){let t=(0,no.default)(e,o=>o.representations)??[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let o of this.representations.keys()){let l=t.find(c=>c.id===o);l&&this.representations.set(o,l);let d=this.representations.get(o);if(!d||!je(d.segmentReference))return;let h=this.getActualLiveStartingSegments(d.segmentReference);this.segments.set(d.id,h)}let i=this.switchingToRepresentationId??this.downloadingRepresentationId,r=this.representations.get(i);Re(r);let s=this.segments.get(i);Re(s,"No segments for starting representation");let n=this.initData.get(i);if(Re(n,"No init buffer for starting representation"),!(n instanceof ArrayBuffer))return;let u=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,yield this.abort(),u&&(yield this.sourceBufferTaskQueue.remove(u.from*1e3,u.to*1e3,this.destroyAbortController.signal)),this.searchGaps(s,r),yield this.sourceBufferTaskQueue.append(n,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this));this.fetcher=r,this.tuning=s,this.compatibilityMode=o,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=u,this.isLive=!!l?.live,this.baseUrls=l?.baseUrls??[],this.initData=new Map(i.map(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){!V(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new X,Wt(this.switchAbortController.signal,async function*(i,r=!1){this.switchingToRepresentationId=i;let s=this.representations.get(i);Re(s,`No such representation ${i}`);let n=this.segments.get(i),u=this.initData.get(i);if(le(u)||le(n)?yield this.loadInit(s,"high",!1):u instanceof Promise&&(yield u),n=this.segments.get(i),Re(n,"No segments for starting representation"),u=this.initData.get(i),!(!(u instanceof ArrayBuffer)||!this.sourceBuffer||!V(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(u,this.downloadAbortController.signal),r)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=i,yield this.dropBuffer();else{let o=this.getCurrentPosition();zt(o)&&!this.isLive&&(this.bufferLimit=this.forwardBufferTarget,yield this.pruneBuffer(o,1/0,!0)),this.downloadingRepresentationId=i,this.switchingToRepresentationId=void 0}this.maintain()}}.bind(this))(e,t))}warmUpMediaSource(){!le(this.sourceBuffer)&&!this.sourceBuffer.updating&&(this.sourceBuffer.mode="segments")}async abort(){for(let e of this.activeSegments)this.abortSegment(e.segment);return this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new X,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(le(e)||le(this.downloadingRepresentationId)||le(this.playingRepresentationId)||le(this.sourceBuffer)||!V(this.mediaSource,this.sourceBuffer)||zt(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.representations.get(this.playingRepresentationId),r=this.segments.get(this.downloadingRepresentationId),s=this.segments.get(this.playingRepresentationId);if(Re(t,`No such representation ${this.downloadingRepresentationId}`),Re(i,`No such representation ${this.playingRepresentationId}`),le(r)||le(s))return;let n=r.find(c=>e>=c.time.from&&e<c.time.to);zt(n)&&isFinite(n.time.from)&&isFinite(n.time.to)&&this.currentSegmentLength$.next(n?.time.to-n.time.from);let u=e,o=100;if(this.playingRepresentationId!==this.downloadingRepresentationId){let c=this.getForwardBufferDuration(e),p=Za(i),f=Za(t),b=this.useSmartRepresentationSwitch&&this.tuning.dash.useNewRepresentationSwitch&&this.tuning.dash.useSmartRepresentationSwitch&&zt(p)&&zt(f)&&uC(p.quality,f.quality),S=this.useSmartRepresentationSwitch&&this.tuning.dash.useNewRepresentationSwitch&&this.tuning.dash.useDelayedRepresentationSwitch;if(b||S?u+=Math.min(c,this.tuning.dash.representationSwitchForwardBufferGap):n&&n.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&c>=n.time.to-e+o&&(u=n?n.time.to+o:-1/0),this.tuning.dash.useNewRepresentationSwitch){let T=this.segments.entries().map(([E,y])=>{let w=y.find(k=>e>=k.time.from&&e<k.time.to);return{representationId:E,status:w?.status}}).find(E=>E.status==="fed")?.representationId;if(!T)return;this.playingRepresentationId=T,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId))}}if(isFinite(this.bufferLimit)&&mr(this.sourceBuffer.buffered)>=this.bufferLimit){let c=this.getForwardBufferDuration(e),p=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,c<p).catch(f=>{this.handleAsyncError(f,"pruneBuffer")});return}let d=[];if(!this.activeSegments.size&&(d=this.selectForwardBufferSegments(r,t.segmentReference.type,u),d.length)){let c="auto";if(this.tuning.dash.useFetchPriorityHints&&n)if((0,so.default)(d,n))c="high";else{let p=(0,wi.default)(d,0);p&&p.time.from-n.time.to>=this.forwardBufferTarget/2&&(c="low")}this.loadSegments(d,t,c).catch(p=>{this.handleAsyncError(p,"loadSegments")})}(!this.preloadOnly&&!this.allInitsLoaded&&n&&n.status==="fed"&&!d.length&&this.getForwardBufferDuration(e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let h=(0,wi.default)(r,-1);!this.isLive&&h&&(this.fullyBuffered$.next(h.time.to-e-this.getForwardBufferDuration(e)<o),this.onLastSegment$.next(e-h.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;zt(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,no.default)(e?.streams[this.kind],r=>r.representations).find(r=>r.id===this.downloadingRepresentationId);if(!t)return;let i=this.segments.get(t.id);if(i?.length)return{from:i[0].time.from,to:i[i.length-1].time.to}}updateLive(e){let t=(0,no.default)(e?.streams[this.kind],i=>i.representations)??[];if(![...this.segments.values()].every(i=>!i.length))for(let i of t){if(!i||!je(i.segmentReference))return;let r=i.segmentReference.segments.map(l=>({...l,status:"none",size:void 0})),s=100,n=this.segments.get(i.id)??[],u=(0,wi.default)(n,-1)?.time.to??0,o=r?.findIndex(l=>u>=l.time.from+s&&u<=l.time.to+s);if(o===-1){this.liveUpdateSegmentIndex=0;let l=this.getActualLiveStartingSegments(i.segmentReference);this.segments.set(i.id,l)}else{let l=r.slice(o+1);this.segments.set(i.id,[...n,...l])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;Re(e);let t=this.segments.get(e);if(t?.length){let i=t[t.length-1];this.updateLowLatencyLiveIfNeeded(i)}}calculateDurationFromSegments(){if(!this.playingRepresentationId)return 0;let e=this.segments.get(this.playingRepresentationId);return(e?(0,wi.default)(e,-1)?.time.to:0)||0}setSmartRepresentationSwitch(e){this.useSmartRepresentationSwitch=e}updateLowLatencyLiveIfNeeded(e){let t=0;for(let i of this.representations.values()){let r=i.segmentReference;if(!je(r))return;let s=this.segments.get(i.id)??[],n=s.find(o=>Math.floor(o.time.from)===Math.floor(e.time.from));if(n&&!isFinite(n.time.to)&&(n.time.to=e.time.to,t=n.time.to-n.time.from),!!!s.find(o=>Math.floor(o.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let o=Math.round(e.time.to*r.timescale/1e3).toString(10),l=nt(r.segmentTemplateUrl,{segmentTime:o});s.push({status:"none",time:{from:e.time.to,to:1/0},url:l})}}this.currentLowLatencySegmentLength$.next(t)}findSegmentStartTime(e){let t=this.switchingToRepresentationId??this.downloadingRepresentationId??this.playingRepresentationId;if(!t)return;let i=this.segments.get(t);return i?i.find(s=>s.time.from<=e&&s.time.to>=e)?.time.from??void 0:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),this.sourceBufferTaskQueue?.destroy(),this.gapDetectionIdleCallback&&vt&&vt(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&vt&&vt(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer)try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(e){if(!(e instanceof DOMException&&e.name==="NotFoundError"))throw e}this.sourceBuffer=null,this.downloadAbortController.abort(),this.switchAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,i){return this.isLive?this.selectForwardBufferSegmentsLive(e,i):this.selectForwardBufferSegmentsRecord(e,t,i)}selectForwardBufferSegmentsLive(e,t){let i=e.findIndex(r=>t>=r.time.from&&t<r.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=i),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,i){let r=this.getForwardBufferDuration(i),s=e.findIndex(({status:c,time:{from:p,to:f}},b)=>{let S=p<=i&&f>=i,g=p>i||S||b===0&&i===0,T=Math.min(this.forwardBufferTarget,this.bufferLimit),E=this.preloadOnly&&p<=i+T||r<T&&f-p>=T||f<=i+T;return(c==="none"||c==="partially_ejected"&&g&&E&&this.sourceBuffer&&V(this.mediaSource,this.sourceBuffer)&&!(ye(this.sourceBuffer.buffered,p)&&ye(this.sourceBuffer.buffered,f)))&&g&&E});if(s===-1)return[];if(t!=="byteRange")return e.slice(s,s+1);let n=e,u=0,o=0,l=[],d=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,h=this.preloadOnly?this.forwardBufferTarget:0;for(let c=s;c<n.length&&(u<=d||o<=h);c++){let p=n[c];if(u+=p.byte.to+1-p.byte.from,o+=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"){je(t.segmentReference)?await this.loadTemplateSegment(e[0],t,i):await this.loadByteRangeSegments(e,t,i)}async loadTemplateSegment(e,t,i="auto"){e.status="downloading";let r={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(r);let{range:s,url:n,signal:u,onProgress:o,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&u&&(await Wt(u,async function*(){let d=Oc(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(h=>setTimeout(h,d))}.bind(this))(),u.aborted&&this.abortActiveSegments([e]));try{let d=await this.fetcher.fetch(n,{range:s,signal:u,onProgress:o,priority:i,isLowLatency:this.isActiveLowLatency(),bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation});if(this.lastDataObtainedTimestampMs=ao(),!d)return;let h=new DataView(d),c=yt(t.mime);if(!isFinite(r.segment.time.to)){let b=t.segmentReference.timescale;r.segment.time.to=c.getChunkEndTime(h,b)}o&&r.feedingBytes&&l?await Promise.all(l):await this.sourceBufferTaskQueue.append(h,u);let{serverDataReceivedTimestamp:p,serverDataPreparedTime:f}=c.getServerLatencyTimestamps(h);p&&f&&this.currentLiveSegmentServerLatency$.next(f-p),r.segment.status="downloaded",this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(d){this.abortActiveSegments([e]),Tt(d)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}updateRepresentationsBaseUrlIfNeeded(){if(!this.tuning.dash.enableBaseUrlSupport||!this.baseUrls.length||this.failedDownloads<=this.tuning.dash.maxSegmentRetryCount)return;this.baseUrlsIndex=(this.baseUrlsIndex+1)%this.baseUrls.length;let e=this.baseUrls[this.baseUrlsIndex];for(let t of this.representations.values())je(t.segmentReference)?t.segmentReference.baseUrl=e:t.segmentReference.url=e}async loadByteRangeSegments(e,t,i="auto"){if(!e.length)return;for(let o of e)o.status="downloading",this.activeSegments.add({segment:o,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:r,url:s,signal:n,onProgress:u}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(await Wt(n,async function*(){let o=Oc(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,o),_c(window,"online").pipe(lC()).subscribe(()=>{l(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(s,{range:r,onProgress:u,signal:n,priority:i,bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation}),this.lastDataObtainedTimestampMs=ao(),this.failedDownloads=0}catch(o){this.abortActiveSegments(e),Tt(o)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}prepareByteRangeFetchSegmentParams(e,t){if(je(t.segmentReference))throw new Error("Representation is not byte range type");let i=t.segmentReference.url,r={from:(0,wi.default)(e,0).byte.from,to:(0,wi.default)(e,-1).byte.to},{signal:s}=this.downloadAbortController;return{url:i,range:r,signal:s,onProgress:async(u,o)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=ao(),await this.onSomeByteRangesDataLoaded({dataView:u,loaded:o,signal:s,onSegmentAppendFailed:()=>this.abort(),globalFrom:r?r.from:0,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:Lt.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!je(t.segmentReference))throw new Error("Representation is not template type");let i=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&i.searchParams.set("low-latency","yes");let r=i.toString(),{signal:s}=this.downloadAbortController,n=[],o=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(l,d)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=ao();let h=this.onSomeTemplateDataLoaded({dataView:l,loaded:d,signal:s,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(h)}catch(h){this.error$.next({id:"SegmentFeeding",category:Lt.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:h})}}:void 0;return{url:r,signal:s,onProgress:o,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)(0,so.default)(e,t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:r,signal:s}){if(!this.activeSegments.size||!V(this.mediaSource,this.sourceBuffer))return;let n=this.representations.get(t);if(n)for(let u of this.activeSegments){let{segment:o}=u;if(u.representationId===t){if(s.aborted){r();continue}if(u.loadedBytes=i,u.loadedBytes>u.feedingBytes){let l=new DataView(e.buffer,e.byteOffset+u.feedingBytes,u.loadedBytes-u.feedingBytes),d=yt(n.mime).parseFeedableSegmentChunk(l,this.isLive);d?.byteLength&&(o.status="partially_fed",u.feedingBytes+=d.byteLength,await this.sourceBufferTaskQueue.append(d),u.fedBytes+=d.byteLength)}}}}async onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:s,onSegmentAppendFailed:n}){if(!this.activeSegments.size||!V(this.mediaSource,this.sourceBuffer))return;let u=this.representations.get(t);if(u)for(let o of this.activeSegments){let{segment:l}=o;if(o.representationId!==t)continue;if(s.aborted){await n();continue}let d=l.byte.from-i,h=l.byte.to-i,c=h-d+1,p=d<r,f=h<=r;if(!p)continue;let b=yt(u.mime);if(l.status==="downloading"&&f){l.status="downloaded";let S=new DataView(e.buffer,e.byteOffset+d,c);await this.sourceBufferTaskQueue.append(S,s)&&!s.aborted?this.onSegmentFullyAppended(o,t):await n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(l.status==="downloading"||l.status==="partially_fed")&&(o.loadedBytes=Math.min(c,r-d),o.loadedBytes>o.feedingBytes)){let S=new DataView(e.buffer,e.byteOffset+d+o.feedingBytes,o.loadedBytes-o.feedingBytes),g=o.loadedBytes===c?S:b.parseFeedableSegmentChunk(S);g?.byteLength&&(l.status="partially_fed",o.feedingBytes+=g.byteLength,await this.sourceBufferTaskQueue.append(g,s)&&!s.aborted?(o.fedBytes+=g.byteLength,o.fedBytes===c&&this.onSegmentFullyAppended(o,t)):await n())}}}onSegmentFullyAppended(e,t){if(!(le(this.sourceBuffer)||!V(this.mediaSource,this.sourceBuffer))){!this.isLive&&B.browser.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(ye(this.sourceBuffer.buffered,e.segment.time.from,100)&&ye(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:Lt.VIDEO_PIPELINE,message:"Browser stuck on empty result of adding segment to source buffer"})),this.tuning.dash.useNewRepresentationSwitch||(this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId))),e.segment.status="fed",Vc(e.segment)&&(e.segment.size=e.fedBytes);for(let i of this.representations.values())if(i.id!==t)for(let r of this.segments.get(i.id)??[])r.status==="fed"&&Math.round(r.time.from)===Math.round(e.segment.time.from)&&Math.round(r.time.to)===Math.round(e.segment.time.to)&&(r.status="none");this.updateLowLatencyLiveIfNeeded(e.segment),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment])}}abortSegment(e){e.status==="partially_fed"?e.status="partially_ejected":e.status!=="partially_ejected"&&(e.status="none");for(let t of this.activeSegments.values())if(t.segment===e){this.activeSegments.delete(t);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(let[r,s]of this.initData.entries()){let n=s instanceof Promise;t||=n,s===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let i=this.representations.get(e);i&&(this.initLoadIdleCallback=fr(()=>(0,Zy.default)(this.loadInit(i,"low",!1),()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",i=!1){let r=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!i&&this.failedDownloads>0?Wt(this.destroyAbortController.signal,async function*(){let u=Oc(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(o=>setTimeout(o,u))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,yt(e.mime),r)).then(async u=>{if(!u)return;let{init:o,dataView:l,segments:d}=u,h=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,h);let c=d;this.isLive&&je(e.segmentReference)&&(c=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,c),o&&this.parsedInitData.set(e.id,o)}).then(()=>this.failedDownloads=0,u=>{this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:Lt.WTF,message:"loadInit threw",thrown:u})});return this.initData.set(e.id,n),n}async dropBuffer(){for(let e of this.segments.values())for(let t of e)t.status="none";await this.pruneBuffer(0,1/0,!0)}async pruneBuffer(e,t,i=!1){if(!this.sourceBuffer||!V(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||le(e))return!1;let r=[],s=0,n=o=>{o.sort((d,h)=>d.from-h.from);let l=[o[0]];for(let d=1;d<o.length;d++){let{from:h,to:c}=o[d],p=l[l.length-1];p.to>=h?p.to=Math.max(p.to,c):l.push(o[d])}return l},u=o=>{if(s>=t)return r;r.push({...o.time}),r=n(r);let l=Vc(o)?o.size??0:o.byte.to-o.byte.from;s+=l};for(let o of this.segments.values())for(let l of o){let d=l.time.to<=e-this.tuning.dash.bufferPruningSafeZone,h=l.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(d||h)&&l.status==="fed"&&u(l)}for(let o=0;o<this.sourceBuffer.buffered.length;o++){let l=this.sourceBuffer.buffered.start(o)*1e3,d=this.sourceBuffer.buffered.end(o)*1e3,h=0;for(let c of this.segments.values())for(let p of c)(0,so.default)(["none","partially_ejected"],p.status)&&Math.round(p.time.from)<=Math.round(l)&&Math.round(p.time.to)>=Math.round(d)&&h++;if(h===this.segments.size){let c={time:{from:l,to:d},url:"",status:"none"};u(c)}}if(r.length&&i){let o=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let l of this.segments.values())for(let d of l)d.time.from>=e+o&&d.status==="fed"&&u(d)}return r.length?(await Promise.all(r.map(l=>this.sourceBufferTaskQueue.remove(l.from,l.to)))).reduce((l,d)=>l||d,!1):!1}async abortBuffer(){if(!this.sourceBuffer||!V(this.mediaSource,this.sourceBuffer))return!1;let e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;return this.sourceBufferTaskQueue.abort(t)}getDebugBufferState(){if(!(!this.sourceBuffer||!V(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}getForwardBufferDuration(e=this.getCurrentPosition()){return!this.sourceBuffer||!V(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||le(e)?0:ve(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!(!this.sourceBuffer||!V(this.mediaSource,this.sourceBuffer))){if(this.tuning.useRefactoredSearchGap)for(let i=0;i<this.sourceBuffer.buffered.length;i++)this.gaps=this.gaps.filter(r=>this.sourceBuffer&&(Math.round(r.from)<Math.round(this.sourceBuffer.buffered.start(i)*1e3)||Math.round(r.to)>Math.round(this.sourceBuffer.buffered.end(i)*1e3)));for(let i of t){let r={representation:e,from:i.time.from,to:i.time.to};for(let s=0;s<this.sourceBuffer.buffered.length;s++){let n=this.sourceBuffer.buffered.start(s)*1e3,u=this.sourceBuffer.buffered.end(s)*1e3;if(!(u<=i.time.from||n>=i.time.to)){if(n<=i.time.from&&u>=i.time.to){r=void 0;break}u>i.time.from&&u<i.time.to&&(r.from=u),n<i.time.to&&n>i.time.from&&(r.to=n)}}r&&r.to-r.from>1&&!this.gaps.some(s=>r&&s.from===r.from&&s.to===r.to)&&this.gaps.push(r)}}}detectGapsWhenIdle(e,t){if(!(this.gapDetectionIdleCallback||!this.sourceBuffer||!V(this.mediaSource,this.sourceBuffer))){if(!this.tuning.useRefactoredSearchGap)for(let i=0;i<this.sourceBuffer.buffered.length;i++)this.gaps=this.gaps.filter(r=>this.sourceBuffer&&(Math.round(r.from)<Math.round(this.sourceBuffer.buffered.start(i)*1e3)||Math.round(r.to)>Math.round(this.sourceBuffer.buffered.end(i)*1e3)));this.gapDetectionIdleCallback=fr(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:Lt.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if(le(this.sourceBuffer)||!V(this.mediaSource,this.sourceBuffer)||le(this.playingRepresentationId))return;let e=[];for(let i=0;i<this.sourceBuffer.buffered.length;i++){let r=Math.floor(this.sourceBuffer.buffered.start(i)*1e3),s=Math.ceil(this.sourceBuffer.buffered.end(i)*1e3);e.push({from:r,to:s})}let t=100;for(let i of this.segments.values())for(let r of i){let{status:s}=r;if(s!=="fed"&&s!=="partially_ejected")continue;let n=Math.floor(r.time.from),u=Math.ceil(r.time.to),o=e.some(d=>d.from-t<=n&&d.to+t>=u),l=e.filter(d=>n>=d.from&&n<d.to-t||u>d.from+t&&u<=d.to);o||(l.length===1?r.status="partially_ejected":this.gaps.some(d=>d.from===r.time.from||d.to===r.time.to)?r.status="partially_ejected":r.status="none")}}handleAsyncError(e,t){this.error$.next({id:t,category:Lt.VIDEO_PIPELINE,thrown:e,message:"Something went wrong"})}};var Yt=a=>{let e=new URL(a);return e.searchParams.set("quic","1"),e.toString()};var oo=a=>{let e=a.get("X-Delivery-Type"),t=a.get("X-Reused"),i=e===null?"http1":e??void 0,r=t===null?void 0:{1:!0,0:!1}[t]??void 0;return{type:i,reused:r}};import{abortable as ts,assertNever as eT,fromEvent as tT,merge as pC,now as is,Subscription as hC,Subject as yr,ValueSubject as Fc,flattenObject as Tr,ErrorCategory as rs}from"@vkontakte/videoplayer-shared";var uo=a=>{let e=new URL(a);return e.searchParams.set("enable-subtitles","yes"),e.toString()};var co=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:s=!1}){this.manifestRequested=new yr;this.manifestReceived=new yr;this.firstBytesRequested=new yr;this.firstBytesReceived=new yr;this.lastConnectionType$=new Fc(void 0);this.lastConnectionReused$=new Fc(void 0);this.lastRequestFirstBytes$=new Fc(void 0);this.recoverableError$=new yr;this.error$=new yr;this.abortAllController=new X;this.subscription=new hC;this.fetchManifest=ts(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=Yt(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=uo(i)),this.manifestRequested.next();let r=yield this.doFetch(i,{signal:this.abortAllController.signal}).catch(lo);return r?(t.log("success",Tr({url:i,message:"Request successfully executed"})),t.end(),this.manifestReceived.next(),this.onHeadersReceived(r.headers),r.text()):(t.error("error",Tr({url:i,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=ts(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:i,onProgress:r,priority:s="auto",signal:n,measureThroughput:u=!0,isLowLatency:o=!1,bufferOptimisation:l=!1}={}){let d=e,h=new Headers,c=this.tracer.createComponentTracer("Fetch");if(i)switch(t){case 0:{h.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let v=new URL(d,location.href);v.searchParams.append("bytes",`${i.from}-${i.to}`),d=v.toString();break}default:eT(t)}this.requestQuic&&(d=Yt(d));let p=this.abortAllController.signal,f;if(n){let v=new X;if(f=pC(tT(this.abortAllController.signal,"abort"),tT(n,"abort")).subscribe(()=>{try{v.abort()}catch(x){lo(x)}}),this.subscription.add(f),this.abortAllController.signal.aborted||n.aborted)try{v.abort()}catch(x){lo(x)}p=v.signal}let b=0,S=is();c.log("startRequest",Tr({url:d,priority:s,rangeMethod:t,range:i,isLowLatency:o,requestStartedAt:S})),this.firstBytesRequested.next();let g=yield this.doFetch(d,{priority:s,headers:h,signal:p}),T=is();if(!g)return c.error("error",{message:"No response in request"}),c.end(),f?.unsubscribe(),null;if(this.throughputEstimator?.addRawRtt(T-S),!g.ok||!g.body){f?.unsubscribe();let v=`Fetch error ${g.status}: ${g.statusText}`;return c.error("error",{message:v}),c.end(),Promise.reject(new Error(`Fetch error ${g.status}: ${g.statusText}`))}if(this.onHeadersReceived(g.headers),!r&&!u){f?.unsubscribe();let v=is(),x={requestStartedAt:S,requestEndedAt:v,duration:v-S};return c.log("endRequest",Tr(x)),c.end(),g.arrayBuffer()}let E=g.body;if(u){let v;[E,v]=g.body.tee(),this.throughputEstimator?.trackStream(v,o)}let y=E.getReader(),w,k=parseInt(g.headers.get("content-length")??"",10);Number.isFinite(k)&&(w=k),!w&&i&&(w=i.to-i.from+1);let $=w?new Uint8Array(w):new Uint8Array(0),A=!1,L=v=>{f?.unsubscribe(),A=!0,lo(v)},I=ts(p,async function*({done:v,value:x}){if(b===0&&(this.lastRequestFirstBytes$.next(is()-S),this.firstBytesReceived.next()),p.aborted){f?.unsubscribe();return}if(!v&&x){if(l&&w)$.set(x,b),b+=x.byteLength;else{let z=new Uint8Array($.length+x.length);z.set($),z.set(x,$.length),$=z,b+=x.byteLength}r?.(new DataView($.buffer),b),yield y?.read().then(I,L)}}.bind(this));yield y?.read().then(I,L),f?.unsubscribe();let q=is(),M={failed:A,requestStartedAt:S,requestEndedAt:q,duration:q-S};return A?(c.error("endRequest",Tr(M)),c.end(),null):(c.log("endRequest",Tr(M)),c.end(),$.buffer)}.bind(this));this.fetchByteRangeRepresentation=ts(this.abortAllController.signal,async function*(e,t,i){if(e.type!=="byteRange")return null;let{from:r,to:s}=e.initRange,n=r,u=s,o=!1,l,d;e.indexRange&&(l=e.indexRange.from,d=e.indexRange.to,o=s+1===l,o&&(n=Math.min(l,r),u=Math.max(d,s))),n=Math.min(n,0);let h=yield this.fetch(e.url,{range:{from:n,to:u},priority:i,measureThroughput:!1});if(!h)return null;let c=new DataView(h,r-n,s-n+1);if(!t.validateData(c))throw new Error("Invalid media file");let p=t.parseInit(c),f=e.indexRange??t.getIndexRange(p);if(!f)throw new ReferenceError("No way to load representation index");let b;if(o)b=new DataView(h,f.from-n,f.to-f.from+1);else{let g=yield this.fetch(e.url,{range:f,priority:i,measureThroughput:!1});if(!g)return null;b=new DataView(g)}let S=t.parseSegments(b,p,f);return{init:p,dataView:new DataView(h),segments:S}}.bind(this));this.fetchTemplateRepresentation=ts(this.abortAllController.signal,async function*(e,t){if(e.type!=="template")return null;let i=new URL(e.initUrl,e.baseUrl).toString(),r=yield this.fetch(i,{priority:t,measureThroughput:!1});return r?{init:null,segments:e.segments.map(n=>({...n,status:"none",size:void 0})),dataView:new DataView(r)}:null}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=r,this.tracer=i.createComponentTracer("Fetcher"),this.useEnableSubtitlesParam=s}onHeadersReceived(e){let{type:t,reused:i}=oo(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}async fetchRepresentation(e,t,i="auto"){let{type:r}=e;switch(r){case"byteRange":return await this.fetchByteRangeRepresentation(e,t,i)??null;case"template":return await this.fetchTemplateRepresentation(e,i)??null;default:eT(r)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}async doFetch(e,t){let i=await Xe(e,t);if(i.ok)return i;let r=await i.text(),s=parseInt(r);if(!isNaN(s))switch(s){case 1:this.recoverableError$.next({id:"VideoDataLinkExpiredError",message:"Video data links have expired",category:rs.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:rs.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:rs.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:rs.FATAL});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${s})`,category:rs.FATAL})}}},lo=a=>{if(!Tt(a))throw a};var $t=(a,e,t)=>t*e+(1-t)*a,Nc=(a,e)=>a.reduce((t,i)=>t+i,0)/e,iT=(a,e,t,i)=>{let r=0,s=t,n=Nc(a,e),u=e<i?e:i;for(let o=0;o<u;o++)a[s]>n?r++:r--,s=(a.length+s-1)%a.length;return Math.abs(r)===u};import{isNullable as fC,ValueSubject as rT}from"@vkontakte/videoplayer-shared";var Kt=class{constructor(e){this.prevReported=void 0;this.pastMeasures=[];this.takenMeasures=0;this.measuresCursor=0;this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new rT(e.initial),this.debounced$=new rT(e.initial);let t=e.label??"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new Ae(`raw_${t}`),this.smoothedSeries$=new Ae(`smoothed_${t}`),this.reportedSeries$=new Ae(`reported_${t}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,i=0;for(let u=0;u<this.pastMeasures.length;u++)this.pastMeasures[u]!==void 0&&(t+=(this.pastMeasures[u]-this.smoothed)**2,i++);this.takenMeasures=i,t/=i;let r=Math.sqrt(t),s=this.smoothed+this.params.deviationFactor*r,n=this.smoothed-this.params.deviationFactor*r;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(e),this.updateSmoothedValue(e),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),!(this.smoothed>s||this.smoothed<n)&&(fC(this.prevReported)||Math.abs(this.smoothed-this.prevReported)/this.prevReported>=this.params.changeThreshold)&&(this.prevReported=this.smoothed,this.debounced$.next(this.smoothed),this.reportedSeries$.next(this.smoothed))}};var po=class extends Kt{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=$t(this.slow,e,this.params.emaAlphaSlow),this.fast=$t(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var ho=class extends Kt{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=Nc(this.pastMeasures,this.takenMeasures);this.emaSmoothed=$t(this.emaSmoothed,e,this.params.emaAlpha);let i=iT(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=i?this.emaSmoothed:t}};var fo=class extends Kt{constructor(t){super(t);this.furtherValues=[];this.currentTopExtremumValue=0;this.extremumInterval=t.extremumInterval}next(t){this.currentTopExtremumValue<=t?(this.currentTopExtremumValue=t,this.furtherValues=[]):this.furtherValues.length===this.extremumInterval?(super.next(this.currentTopExtremumValue),this.currentTopExtremumValue=t,this.furtherValues=[]):this.furtherValues.push(t)}updateSmoothedValue(t){this.smoothed=this.smoothed?$t(this.smoothed,t,this.params.emaAlpha):t}};var Mt=class{static getSmoothedValue(e,t,i){return i.type==="TwoEma"?new po({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new ho({initial:e,emaAlpha:i.emaAlpha,basisTrendChangeCount:i.basisTrendChangeCount,changeThreshold:i.changeThreshold,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"})}static getLiveBufferSmoothedValue(e,t){return new fo({initial:e,label:"liveEdgeDelay",...t})}};var Ir=(a,e)=>{a&&a.playbackRate!==e&&(a.playbackRate=e)};import{isNullable as mC,ValueSubject as bC}from"@vkontakte/videoplayer-shared";var as=class a{constructor(e,t){this.currentRepresentation$=new bC(null);this.maxRepresentations=4;this.representationsCursor=0;this.representations=[];this.currentSegment=null;this.getCurrentPosition=t.getCurrentPosition,this.processStreams(e)}updateLive(e){this.processStreams(e?.streams.text)}seekLive(e){this.processStreams(e)}maintain(e=this.getCurrentPosition()){if(!mC(e))for(let t of this.representations)for(let i of t){let r=i.segmentReference,s=r.segments.length,n=r.segments[0].time.from,u=r.segments[s-1].time.to;if(e<n||e>u)continue;let o=r.segments.find(l=>l.time.from<=e&&l.time.to>=e);!o||this.currentSegment?.time.from===o.time.from&&this.currentSegment.time.to===o.time.to||(this.currentSegment=o,this.currentRepresentation$.next({...i,label:"Live Text",language:"ru",isAuto:!0,url:new URL(o.url,r.baseUrl).toString()}))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e??[]){let i=a.filterRepresentations(t.representations);if(i){this.representations[this.representationsCursor]=i,this.representationsCursor=(this.representationsCursor+1)%this.maxRepresentations;break}}}static isSupported(e){return!!e?.some(t=>a.filterRepresentations(t.representations))}static filterRepresentations(e){return e?.filter(t=>t.kind==="text"&&"segmentReference"in t&&je(t.segmentReference))}};var bo=C(at(),1),qc=C(Ee(),1);import{assertNever as go}from"@vkontakte/videoplayer-shared";var mo=a=>{let{webmDecodingInfo:e}=B.video,t="DASH_WEBM",i="DASH_WEBM_AV1";switch(a){case"vp9":return[t,i];case"av1":return[i,t];case"none":return[];case"smooth":return e?e[i].smooth?[i,t]:e[t].smooth?[t,i]:[i,t]:[t,i];case"power_efficient":return e?e[i].powerEfficient?[i,t]:e[t].powerEfficient?[t,i]:[i,t]:[t,i];default:go(a)}return[t,i]},aT=({webmCodec:a,androidPreferredFormat:e,iosPreferredFormat:t,preferMultiStream:i})=>{let r=[...i?["DASH_STREAMS"]:[],...mo(a),"DASH_SEP","DASH_ONDEMAND",...i?[]:["DASH_STREAMS"]],s=[...i?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...i?[]:["DASH_STREAMS"]];if(B.device.isAndroid)switch(e){case"mpeg":return["MPEG",...r,"HLS","HLS_ONDEMAND"];case"hls":return["HLS","HLS_ONDEMAND",...r,"MPEG"];case"dash":return[...r,"HLS","HLS_ONDEMAND","MPEG"];case"dash_any_mpeg":return[...s,"MPEG",...mo(a),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...mo(a),"MPEG",...s,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...mo(a),...s,"HLS","HLS_ONDEMAND"];default:go(e)}if(B.video.nativeHlsSupported)switch(t){case"hls":return[...r,"HLS","HLS_FMP4","HLS_ONDEMAND","MPEG"];case"hls_fmp4":return[...r,"HLS_FMP4","HLS","HLS_ONDEMAND","MPEG"];default:go(t)}return[...r,"HLS","HLS_ONDEMAND","MPEG"]},sT=({androidPreferredFormat:a,preferCMAF:e,preferWebRTC:t})=>{let i=e?["DASH_LIVE_CMAF","DASH_LIVE"]:["DASH_LIVE","DASH_LIVE_CMAF"],r=e?["HLS_LIVE_CMAF","HLS_LIVE"]:["HLS_LIVE","HLS_LIVE_CMAF"],s=[...i,...r],n=[...r,...i],u,o=B.device.isMac&&B.browser.isSafari;if(B.device.isAndroid)switch(a){case"dash":case"dash_any_mpeg":case"dash_any_webm":case"dash_sep":{u=s;break}case"hls":case"mpeg":{u=n;break}default:go(a)}else B.video.nativeHlsSupported&&!o?u=n:o?u=e?["DASH_LIVE_CMAF","HLS_LIVE_CMAF","HLS_LIVE","DASH_LIVE"]:["HLS_LIVE","DASH_LIVE","DASH_LIVE_CMAF","HLS_LIVE_CMAF"]:u=s;return t?["WEB_RTC_LIVE",...u]:[...u,"WEB_RTC_LIVE"]},Uc=a=>a?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],So=a=>{if(a.size===0)return;if(a.size===1){let t=a.values().next();return(0,bo.default)(t.value.split("."),0)}for(let t of a){let i=(0,bo.default)(t.split("."),0);if(i==="opus"||i==="vp09"||i==="av01")return i}let e=a.values().next();return(0,bo.default)(e.value.split("."),0)},vo=a=>{let e=a.map(i=>Er(i)),{codecs:t}=B.video;return yC().filter(i=>{if((0,qc.default)(e,i))switch(i){case"av1":return t.av1;case"vp9":return t.vp9;case"avc1":return t.h264;case"hev1":return t.h265;default:return!1}else return!1})},yo=a=>{let e=a.map(i=>Er(i)),{codecs:t}=B.video;return TC().filter(i=>{if((0,qc.default)(e,i))switch(i){case"opus":return t.opus;case"mp4a":return t.aac;default:return!1}else return!1})},Er=a=>a.split(".")[0].replace("0",""),yC=()=>["av1","vp9","hev1","avc1"],TC=()=>["opus","mp4a"];var PC=["timeupdate","progress","play","seeked","stalled","waiting"],RC=["timeupdate","progress","loadeddata","playing","seeked"];var Io=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.bufferManagers=[];this.subscription=new uT;this.representationSubscription=new uT;this.state$=new F("none");this.currentVideoRepresentation$=new ee(void 0);this.currentVideoRepresentationInit$=new ee(void 0);this.currentAudioRepresentation$=new ee(void 0);this.currentVideoSegmentLength$=new ee(0);this.currentAudioSegmentLength$=new ee(0);this.error$=new Xt;this.manifestRequested=new Xt;this.manifestReceived=new Xt;this.firstBytesRequested=new Xt;this.firstBytesReceived=new Xt;this.lastConnectionType$=new ee(void 0);this.lastConnectionReused$=new ee(void 0);this.lastRequestFirstBytes$=new ee(void 0);this.currentLiveTextRepresentation$=new ee(null);this.isLive$=new ee(!1);this.isActiveLive$=new ee(!1);this.isLowLatency$=new ee(!1);this.liveDuration$=new ee(0);this.liveSeekableDuration$=new ee(0);this.liveAvailabilityStartTime$=new ee(0);this.liveStreamStatus$=new ee(void 0);this.bufferLength$=new ee(0);this.liveLatency$=new ee(void 0);this.liveLoadBufferLength$=new ee(0);this.livePositionFromPlayer$=new ee(0);this.currentStallDuration$=new ee(0);this.videoLastDataObtainedTimestamp$=new ee(0);this.fetcherRecoverableError$=new Xt;this.fetcherError$=new Xt;this.liveStreamEndTimestamp=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.forceEnded$=new Xt;this.gapWatchdogActive=!1;this.destroyController=new X;this.initManifest=Hc(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=se(t,i,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),this.manifest?.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:ot.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=Hc(this.destroyController.signal,async function*(){this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(o=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:ot.NETWORK,message:"Failed to load manifest",thrown:o})});if(!e)return null;let t=null;try{t=ro(e??"",this.manifestUrlString)}catch(o){let l=to(e)??{id:"ManifestParsing",category:ot.PARSER,message:"Failed to parse MPD manifest",thrown:o};this.error$.next(l)}if(!t)return null;let i=(o,l,d)=>!!(this.element?.canPlayType?.(l)&&Ue()?.isTypeSupported?.(`${l}; codecs="${d}"`)||o==="text");if(t.live){this.isLive$.next(!!t.live);let{availabilityStartTime:o,latestSegmentPublishTime:l,streamIsUnpublished:d,streamIsAlive:h}=t.live,c=(t.duration??0)/1e3;this.liveSeekableDuration$.next(-1*c),this.liveDuration$.next((l-o)/1e3),this.liveAvailabilityStartTime$.next(t.live.availabilityStartTime);let p="active";h||(p=d?"unpublished":"unexpectedly_down"),this.liveStreamStatus$.next(p)}let r={text:t.streams.text,video:[],audio:[]},s,n;for(let o of["video","audio"]){let d=t.streams[o].filter(({mime:c,codecs:p})=>i(o,c,p));r[o]=d;let h;if(this.tuning.dash.codecsPrioritizeEnabled){let c=d.map(({codecs:p})=>p);o==="audio"&&(n=yo(c),h=n[0]),o==="video"&&(s=vo(c),this.forceVideoCodec&&(0,cT.default)(s,this.forceVideoCodec)?h=this.forceVideoCodec:h=s[0]),h&&(r[o]=d.filter(({codecs:p})=>Er(p)===h))}else{let c=new Set(d.map(({codecs:p})=>p));h=So(c),h&&(r[o]=d.filter(({codecs:p})=>p.startsWith(h)))}if(o==="video"){let c=this.tuning.preferHDR,p=r.video.some(b=>b.hdr),f=r.video.some(b=>!b.hdr);B.display.isHDR&&c&&p?r.video=r.video.filter(b=>b.hdr):f&&(r.video=r.video.filter(b=>!b.hdr))}}let u={...t,streams:r};return this.tuning.dash.codecsPrioritizeEnabled&&(u.codecs={video:s,audio:n}),this.tracer.log("updateManifestEnd",ns(u)),u}.bind(this));this.initRepresentations=Hc(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initRepresentationsStart",ns({initialVideo:e,initialAudio:t,sourceHls:i})),xr(this.manifest),xr(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let r=c=>{this.representationSubscription.add(Dt(c,"error").pipe(To(p=>!!this.element?.played.length)).subscribe(p=>{this.error$.next({id:"VideoSource",category:ot.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:p})}))};this.source=Ln();let s=document.createElement("source");if(r(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),rr())if(i){let c=document.createElement("source");r(c),c.type="application/x-mpegurl",c.src=i.url,this.element.appendChild(c)}else this.element.disableRemotePlayback=!0;this.isActiveLive$.next(this.isLive$.getValue());let n={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),manifest:this.manifest},u=this.manifest.streams.video.reduce((c,p)=>[...c,...p.representations],[]);if(this.videoBufferManager=new es("video",this.source,u,n),this.bufferManagers=[this.videoBufferManager],os(t)){let c=this.manifest.streams.audio.reduce((p,f)=>[...p,...f.representations],[]);this.audioBufferManager=new es("audio",this.source,c,n),this.bufferManagers.push(this.audioBufferManager)}as.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new as(this.manifest.streams.text,n)),this.representationSubscription.add(this.fetcher.manifestRequested.subscribe(this.manifestRequested)),this.representationSubscription.add(this.fetcher.manifestReceived.subscribe(this.manifestReceived)),this.representationSubscription.add(this.fetcher.firstBytesRequested.subscribe(this.firstBytesRequested)),this.representationSubscription.add(this.fetcher.firstBytesReceived.subscribe(this.firstBytesReceived)),this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$));let o=()=>{this.stallWatchdogSubscription?.unsubscribe(),this.currentStallDuration$.next(0)};if(this.representationSubscription.add(Ai(...RC.map(c=>Dt(this.element,c))).pipe(Ar(c=>this.element?ve(this.element.buffered,this.element.currentTime*1e3):0),ss(),wC(c=>{c>this.tuning.dash.bufferEmptinessTolerance&&o()})).subscribe(this.bufferLength$)),this.representationSubscription.add(Ai(Dt(this.element,"ended"),this.forceEnded$).subscribe(()=>{o()})),this.isLive$.getValue()){this.subscription.add(this.liveDuration$.pipe(ss()).subscribe(p=>this.liveStreamEndTimestamp=Gc())),this.subscription.add(Dt(this.element,"pause").subscribe(()=>{this.livePauseWatchdogSubscription=Qc(1e3).subscribe(p=>{let f=Ut(this.manifestUrlString,2);this.manifestUrlString=se(this.manifestUrlString,f+1e3,2),this.liveStreamStatus$.getValue()==="active"&&this.updateManifest()}),this.subscription.add(this.livePauseWatchdogSubscription)})).add(Dt(this.element,"play").subscribe(p=>this.livePauseWatchdogSubscription?.unsubscribe())),this.representationSubscription.add(wr({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(Ar(({isActiveLive:p,isLowLatency:f})=>p&&f),ss()).subscribe(p=>{this.isManualDecreasePlaybackInLive()||Ir(this.element,1)})),this.representationSubscription.add(wr({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(To(({bufferLength:p,isActiveLive:f,isLowLatency:b})=>f&&b&&!!p)).subscribe(({bufferLength:p})=>this.liveBuffer.next(p))),this.representationSubscription.add(this.videoBufferManager.currentLowLatencySegmentLength$.subscribe(p=>{if(!this.isActiveLive$.getValue()&&!this.isLowLatency$.getValue()&&!p)return;let f=this.liveSeekableDuration$.getValue()-p/1e3;this.liveSeekableDuration$.next(Math.max(f,-1*this.tuning.dashCmafLive.maxLiveDuration)),this.liveDuration$.next(this.liveDuration$.getValue()+p/1e3)})),this.representationSubscription.add(wr({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe(To(({isLive:p})=>p),ss((p,f)=>f.bufferLength<p.bufferLength),Ar(({rtt:p,bufferLength:f,segmentServerLatency:b})=>{let S=Ut(this.manifestUrlString,2);return(p/2+f+b+S)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add(wr({liveBuffer:this.liveBuffer.smoothed$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).subscribe(({liveBuffer:p,isActiveLive:f,isLowLatency:b})=>{if(!b||!f)return;let S=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,g=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,T=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,E=p-S;if(this.isManualDecreasePlaybackInLive())return;let y=1;Math.abs(E)>g&&(y=1+Math.sign(E)*T),Ir(this.element,y)})),this.representationSubscription.add(this.bufferLength$.subscribe(p=>{let f=0;if(p){let b=(this.element?.currentTime??0)*1e3;f=Math.min(...this.bufferManagers.map(g=>g.getLiveSegmentsToLoadState(this.manifest)?.to??b))-b}this.liveLoadBufferLength$.getValue()!==f&&this.liveLoadBufferLength$.next(f)}));let c=0;this.representationSubscription.add(wr({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(AC(1e3)).subscribe(async({liveLoadBufferLength:p,bufferLength:f})=>{if(!this.element||this.isUpdatingLive)return;let b=this.element.playbackRate,S=Ut(this.manifestUrlString,2),g=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,T=Math.min(g,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*b),E=this.tuning.dashCmafLive.normalizedActualBufferOffset*b,y=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*b,w=isFinite(p)?p:f,k=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),$=g<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next($);let A="none";if(k?A="active_low_latency":this.isLowLatency$.getValue()&&$?(this.bufferManagers.forEach(L=>L.proceedLowLatencyLive()),A="active_low_latency"):S!==0&&w<T?A="live_forward_buffering":w<T+y&&(A="live_with_target_offset"),isFinite(p)&&(c=p>c?p:c),A==="live_forward_buffering"||A==="live_with_target_offset"){let L=c-(T+E),I=this.normolizeLiveOffset(Math.trunc(S+L/b)),q=Math.abs(I-S),M=0;!p||q<=this.tuning.dashCmafLive.offsetCalculationError?M=S:I>0&&q>this.tuning.dashCmafLive.offsetCalculationError&&(M=I),this.manifestUrlString=se(this.manifestUrlString,M,2)}(A==="live_with_target_offset"||A==="live_forward_buffering")&&(c=0,await this.updateLive())},p=>{this.error$.next({id:"updateLive",category:ot.VIDEO_PIPELINE,thrown:p,message:"Failed to update live with subscription"})}))}let l=Ai(...this.bufferManagers.map(c=>c.fullyBuffered$)).pipe(Ar(()=>this.bufferManagers.every(c=>c.fullyBuffered$.getValue()))),d=Ai(...this.bufferManagers.map(c=>c.onLastSegment$)).pipe(Ar(()=>this.bufferManagers.some(c=>c.onLastSegment$.getValue()))),h=wr({allBuffersFull:l,someBufferEnded:d}).pipe(ss(),Ar(({allBuffersFull:c,someBufferEnded:p})=>c&&p),To(c=>c));if(this.representationSubscription.add(Ai(this.forceEnded$,h).subscribe(()=>{if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(c=>!c.updating))try{this.source?.endOfStream()}catch(c){this.error$.next({id:"EndOfStream",category:ot.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:c})}})),this.representationSubscription.add(Ai(...this.bufferManagers.map(c=>c.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.representationSubscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&(this.representationSubscription.add(this.audioBufferManager.playingRepresentation$.subscribe(this.currentAudioRepresentation$)),this.representationSubscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$))),this.liveTextManager&&this.representationSubscription.add(this.liveTextManager.currentRepresentation$.subscribe(this.currentLiveTextRepresentation$)),this.source.readyState!=="open"){let c=this.tuning.dash.sourceOpenTimeout>=0;yield new Promise(p=>{c&&(this.timeoutSourceOpenId=setTimeout(()=>{if(this.source?.readyState==="open"){p();return}this.error$.next({id:"OpenOfStream",category:ot.VIDEO_PIPELINE,message:"Failed to open MediaSource",thrown:new Error("Timeout reject when wait sourceopen event"),traceAsLog:!0})},this.tuning.dash.sourceOpenTimeout)),this.source?.addEventListener("sourceopen",()=>{this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),p()},{once:!0})})}if(!this.isLive$.getValue()){let c=[this.manifest.duration??0,...(0,Wc.default)((0,Wc.default)([...this.manifest.streams.audio,...this.manifest.streams.video],p=>p.representations),p=>{let f=[];return p.duration&&f.push(p.duration),je(p.segmentReference)&&p.segmentReference.totalSegmentsDurationMs&&f.push(p.segmentReference.totalSegmentsDurationMs),f})];this.source.duration=Math.max(...c)/1e3}this.audioBufferManager&&os(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState("representations_ready"),this.tracer.log("initRepresentationsEnd")}.bind(this));this.tick=()=>{if(!this.element||!this.videoBufferManager||this.source?.readyState!=="open")return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),this.audioBufferManager?.maintain(e),this.liveTextManager?.maintain(e),(this.videoBufferManager.gaps.length||this.audioBufferManager?.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=Qc(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),t=>{this.error$.next({id:"GapWatchdog",category:ot.WTF,message:"Error handling gaps",thrown:t})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name),this.forceVideoCodec=e.forceVideoCodec,this.fetcher=new co({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer,useEnableSubtitlesParam:e.tuning.useEnableSubtitlesParam}),this.subscription.add(this.fetcher.recoverableError$.subscribe(this.fetcherRecoverableError$)),this.subscription.add(this.fetcher.error$.subscribe(this.fetcherError$)),this.liveBuffer=Mt.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.bufferEstimator}),this.initTracerSubscription()}setSmartRepresentationSwitch(e){this.bufferManagers.forEach(t=>t.setSmartRepresentationSwitch(e))}async seekLive(e){xr(this.element);let t=this.liveStreamStatus$.getValue()!=="active"?Gc()-this.liveStreamEndTimestamp:0,i=this.normolizeLiveOffset(e+t);this.isActiveLive$.next(i===0),this.manifestUrlString=se(this.manifestUrlString,i,2),this.manifest=await this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,await this.videoBufferManager?.seekLive(this.manifest.streams.video),await this.audioBufferManager?.seekLive(this.manifest.streams.audio),this.liveTextManager?.seekLive(this.manifest.streams.text))}initBuffer(){xr(this.element),this.state$.setState("running"),this.subscription.add(Ai(...PC.map(e=>Dt(this.element,e)),Dt(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:ot.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(Dt(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(Dt(this.element,"waiting").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&ye(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{if(!this.element||this.source?.readyState!=="open")return;let t=this.currentStallDuration$.getValue();t+=50,this.currentStallDuration$.next(t);let i={timeInWaiting:t},r=Gc(),s=100,n=this.videoBufferManager?.lastDataObtainedTimestamp??0;this.videoLastDataObtainedTimestamp$.next(n);let u=this.audioBufferManager?.lastDataObtainedTimestamp??0,o=this.videoBufferManager?.getForwardBufferDuration()??0,l=this.audioBufferManager?.getForwardBufferDuration()??0,d=o<s&&r-n>this.tuning.dash.crashOnStallTWithoutDataTimeout,h=this.audioBufferManager&&l<s&&r-u>this.tuning.dash.crashOnStallTWithoutDataTimeout;if((d||h)&&t>this.tuning.dash.crashOnStallTWithoutDataTimeout||t>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${t} ms`);if(this.isLive$.getValue()&&t%2e3===0){let c=this.normolizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);this.seekLive(c).catch(p=>{this.error$.next({id:"stallIntervalCallback",category:ot.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:p})}),i.liveLastOffset=c}else{let c=this.element.currentTime*1e3;this.videoBufferManager?.maintain(c),this.audioBufferManager?.maintain(c),i.position=c}this.tracer.log("stallIntervalCallback",ns(i))};this.stallWatchdogSubscription?.unsubscribe(),this.stallWatchdogSubscription=Qc(50).subscribe(e,t=>{this.error$.next({id:"StallWatchdogCallback",category:ot.NETWORK,message:"Can't restore DASH after stall.",thrown:t})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t,i=!1){let r={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return this.tuning.useNewSwitchTo?this.currentStallDuration$.getValue()>0?r?.switchToWithPreviousAbort(t,i):r?.switchTo(t,i):r?.switchToOld(t,i)}async seek(e,t){xr(this.element),xr(this.videoBufferManager);let i;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?i=e:i=Math.max(this.videoBufferManager.findSegmentStartTime(e)??e,this.audioBufferManager?.findSegmentStartTime(e)??e),this.warmUpMediaSourceIfNeeded(i),ye(this.element.buffered,i)||await Promise.all([this.videoBufferManager.abort(),this.audioBufferManager?.abort()]),!(oT(this.element)||oT(this.videoBufferManager))&&(this.videoBufferManager.maintain(i),this.audioBufferManager?.maintain(i),this.element.currentTime=i/1e3,this.tracer.log("seek",ns({requestedPosition:e,forcePrecise:t,position:i})))}warmUpMediaSourceIfNeeded(e=this.element?.currentTime){os(this.element)&&os(this.source)&&os(e)&&this.source?.readyState==="ended"&&this.element.duration*1e3-e>this.tuning.dash.seekBiasInTheEnd&&this.bufferManagers.forEach(t=>t.warmUpMediaSource())}get isStreamEnded(){return this.source?.readyState==="ended"}stop(){this.tracer.log("stop"),this.element?.querySelectorAll("source").forEach(e=>{URL.revokeObjectURL(e.src),e.remove()}),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),this.videoBufferManager?.destroy(),this.videoBufferManager=null,this.audioBufferManager?.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getStreams(){return this.manifest?.streams}getCodecs(){return this.manifest?.codecs}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),this.source?.readyState==="open"&&Array.from(this.source.sourceBuffers).every(e=>!e.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}initTracerSubscription(){let e=xC(this.tracer.error.bind(this.tracer));this.subscription.add(this.error$.subscribe(e("error")))}isManualDecreasePlaybackInLive(){if(!this.element||!this.isLive$.getValue())return!1;let e=1-this.element.playbackRate;return Number(e.toFixed(2))>Number(this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup.toFixed(2))}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}async updateLive(){this.isUpdatingLive=!0,this.manifest=await this.updateManifest(),this.manifest&&(this.bufferManagers.forEach(e=>e.updateLive(this.manifest)),this.liveTextManager?.updateLive(this.manifest)),this.isUpdatingLive=!1}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.getDebugBufferState();if(!e)return;let t=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),i={isJumpGapAfterSeekLive:this.isJumpGapAfterSeekLive,isActiveLowLatency:t,initialCurrentTime:this.element.currentTime};this.isJumpGapAfterSeekLive&&!t&&this.element.currentTime>e.to&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let r=this.element.currentTime*1e3,s=[],n=this.element.readyState===1?this.tuning.endGapTolerance:0;for(let u of this.bufferManagers)for(let o of u.gaps)u.playingRepresentation$.getValue()===o.representation&&o.from-n<=r&&o.to+n>r&&(this.element.duration*1e3-o.to<this.tuning.endGapTolerance?s.push(1/0):s.push(o.to));if(s.length){let u=Math.max(...s)+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,u===1/0?this.forceEnded$.next():(this.element.currentTime=u/1e3,i={...i,gapEnds:s,jumpTo:u,resultCurrentTime:this.element.currentTime},this.tracer.log("jumpGap",ns(i)))}}calculateDurationFromSegments(){return Math.max(this.videoBufferManager?.calculateDurationFromSegments()||0,this.audioBufferManager?.calculateDurationFromSegments()||0)}};var Eo=class{constructor(e,t){this.fov=e,this.orientation=t}};var xo=class{constructor(e,t){this.rotating=!1;this.fading=!1;this.lastTickTS=0;this.lastCameraTurnTS=0;this.fadeStartSpeed=null;this.fadeTime=0;this.camera=e,this.options=t,this.rotationSpeed={x:0,y:0,z:0},this.fadeCorrection=1/(this.options.speedFadeTime/1e3)**2}turnCamera(e=0,t=0,i=0){this.pointCameraTo(this.camera.orientation.x+e,this.camera.orientation.y+t,this.camera.orientation.z+i)}pointCameraTo(e=0,t=0,i=0){t=this.limitCameraRotationY(t);let r=e-this.camera.orientation.x,s=t-this.camera.orientation.y,n=i-this.camera.orientation.z;this.camera.orientation.x=e,this.camera.orientation.y=t,this.camera.orientation.z=i,this.lastCameraTurn={x:r,y:s,z:n},this.lastCameraTurnTS=Date.now()}setRotationSpeed(e,t,i){this.rotationSpeed.x=e??this.rotationSpeed.x,this.rotationSpeed.y=t??this.rotationSpeed.y,this.rotationSpeed.z=i??this.rotationSpeed.z}startRotation(){this.rotating=!0}stopRotation(e=!1){e?(this.setRotationSpeed(0,0,0),this.fadeStartSpeed=null):this.startFading(this.rotationSpeed.x,this.rotationSpeed.y,this.rotationSpeed.z),this.rotating=!1}onCameraRelease(){if(this.lastCameraTurn&&this.lastCameraTurnTS){let e=Date.now()-this.lastCameraTurnTS;if(e<this.options.speedFadeThreshold){let t=(1-e/this.options.speedFadeThreshold)*this.options.rotationSpeedCorrection;this.startFading(this.lastCameraTurn.x*t,this.lastCameraTurn.y*t,this.lastCameraTurn.z*t)}}}startFading(e,t,i){this.setRotationSpeed(e,t,i),this.fadeStartSpeed={...this.rotationSpeed},this.fading=!0}stopFading(){this.fadeStartSpeed=null,this.fading=!0,this.fadeTime=0}limitCameraRotationY(e){return Math.max(-this.options.maxYawAngle,Math.min(e,this.options.maxYawAngle))}tick(e){if(!this.lastTickTS){this.lastTickTS=e,this.lastCameraTurnTS=Date.now();return}let t=e-this.lastTickTS,i=t/1e3;if(this.rotating)this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*i,this.rotationSpeed.y*this.options.rotationSpeedCorrection*i,this.rotationSpeed.z*this.options.rotationSpeedCorrection*i);else if(this.fading&&this.fadeStartSpeed){let r=-this.fadeCorrection*(this.fadeTime/1e3)**2+1;this.setRotationSpeed(this.fadeStartSpeed.x*r,this.fadeStartSpeed.y*r,this.fadeStartSpeed.z*r),r>0?this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*i,this.rotationSpeed.y*this.options.rotationSpeedCorrection*i,this.rotationSpeed.z*this.options.rotationSpeedCorrection*i):(this.stopRotation(!0),this.stopFading()),this.fadeTime=Math.min(this.fadeTime+t,this.options.speedFadeTime)}this.lastTickTS=e}};var dT=`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
|
|
135
|
+
`;var pT=`#ifdef GL_ES
|
|
136
136
|
precision highp float;
|
|
137
137
|
precision highp int;
|
|
138
138
|
#else
|
|
@@ -175,6 +175,6 @@ void main(void) {
|
|
|
175
175
|
// sample using new coordinates
|
|
176
176
|
gl_FragColor = texture2D(u_texture, tc);
|
|
177
177
|
}
|
|
178
|
-
`;var Ar=class{constructor(e,t,i){this.videoInitialized=!1;this.active=!1;this.container=e,this.sourceVideoElement=t,this.params=i,this.canvas=this.createCanvas();let r=this.canvas.getContext("webgl");if(!r)throw new Error("Could not initialize WebGL context");this.gl=r,this.container.appendChild(this.canvas),this.camera=new mo(this.params.fov,this.params.orientation),this.cameraRotationManager=new bo(this.camera,{rotationSpeed:this.params.rotationSpeed,maxYawAngle:this.params.maxYawAngle,rotationSpeedCorrection:this.params.rotationSpeedCorrection,degreeToPixelCorrection:this.params.degreeToPixelCorrection,speedFadeTime:this.params.speedFadeTime,speedFadeThreshold:this.params.speedFadeThreshold}),this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.textureMappingBuffer=this.createTextureMappingBuffer(),this.updateTextureMappingBuffer(),this.program=this.createProgram(),this.videoTexture=this.createTexture(),this.gl.useProgram(this.program),this.videoElementDataLoadedFn=this.onDataLoadedHandler.bind(this),this.renderFn=this.render.bind(this)}play(){this.active||(this.videoInitialized?this.doPlay():this.sourceVideoElement.readyState>=2?(this.videoInitialized=!0,this.doPlay()):this.sourceVideoElement.addEventListener("loadeddata",this.videoElementDataLoadedFn))}stop(){this.active=!1}startCameraManualRotation(e,t){this.cameraRotationManager.setRotationSpeed(e*this.params.rotationSpeed,t*this.params.rotationSpeed,0),this.cameraRotationManager.startRotation()}stopCameraManualRotation(e=!1){this.cameraRotationManager.stopRotation(e)}turnCamera(e,t){this.cameraRotationManager.turnCamera(e,t)}pointCameraTo(e,t){this.cameraRotationManager.pointCameraTo(e,t)}pixelToDegree(e){return{x:this.params.degreeToPixelCorrection*this.params.fov.x*-e.x/this.viewportWidth,y:this.params.degreeToPixelCorrection*this.params.fov.y*e.y/this.viewportHeight}}getCameraRotation(){return this.camera.orientation}holdCamera(){this.cameraRotationManager.stopRotation(!0)}releaseCamera(){this.cameraRotationManager.onCameraRelease()}destroy(){this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),this.stop(),this.canvas.remove()}setViewportSize(e,t){this.viewportWidth=e,this.viewportHeight=t,this.canvas.width=this.viewportWidth,this.canvas.height=this.viewportHeight,this.gl.viewport(0,0,this.canvas.width,this.canvas.height)}onDataLoadedHandler(){this.videoInitialized=!0,this.doPlay()}doPlay(){this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.active=!0,this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),requestAnimationFrame(this.renderFn)}render(e){this.cameraRotationManager.tick(e),this.updateTexture(),this.updateTextureMappingBuffer();let t=this.gl.getAttribLocation(this.program,"a_vertex"),i=this.gl.getAttribLocation(this.program,"a_texel"),r=this.gl.getUniformLocation(this.program,"u_texture"),s=this.gl.getUniformLocation(this.program,"u_focus");this.gl.enableVertexAttribArray(t),this.gl.enableVertexAttribArray(i),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.vertexBuffer),this.gl.vertexAttribPointer(t,2,this.gl.FLOAT,!1,0,0),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.vertexAttribPointer(i,2,this.gl.FLOAT,!1,0,0),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.uniform1i(r,0),this.gl.uniform2f(s,-this.camera.orientation.x,-this.camera.orientation.y),this.gl.drawArrays(this.gl.TRIANGLE_FAN,0,4),this.gl.bindTexture(this.gl.TEXTURE_2D,null),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),this.gl.disableVertexAttribArray(t),this.gl.disableVertexAttribArray(i),this.active&&requestAnimationFrame(this.renderFn)}createShader(e,t){let i=this.gl.createShader(t);if(!i)throw this.destroy(),new Error(`Could not create shader (${t})`);if(this.gl.shaderSource(i,e),this.gl.compileShader(i),!this.gl.getShaderParameter(i,this.gl.COMPILE_STATUS))throw this.destroy(),new Error("An error occurred while compiling the shader: "+this.gl.getShaderInfoLog(i));return i}createProgram(){let e=this.gl.createProgram();if(!e)throw this.destroy(),new Error("Could not create shader program");let t=this.createShader(cT,this.gl.VERTEX_SHADER),i=this.createShader(dT,this.gl.FRAGMENT_SHADER);if(this.gl.attachShader(e,t),this.gl.attachShader(e,i),this.gl.linkProgram(e),!this.gl.getProgramParameter(e,this.gl.LINK_STATUS))throw this.destroy(),new Error("Could not link shader program.");return e}createTexture(){let e=this.gl.createTexture();if(!e)throw this.destroy(),new Error("Could not create texture");return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.bindTexture(this.gl.TEXTURE_2D,null),e}updateTexture(){this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,!0),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.sourceVideoElement),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}createVertexBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create vertex buffer");let t=1,i=1,r=this.frameHeight/(this.frameWidth/this.viewportWidth);return r>this.viewportHeight?t=this.viewportHeight/r:i=r/this.viewportHeight,this.gl.bindBuffer(this.gl.ARRAY_BUFFER,e),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-t,-i,t,-i,t,i,-t,i]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),e}createTextureMappingBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create texture mapping buffer");return e}calculateTexturePosition(){let e=.5-this.camera.orientation.x/360,t=.5-this.camera.orientation.y/180,i=this.camera.fov.x/360/2,r=this.camera.fov.y/180/2,s=e-i,n=t-r,u=e+i,o=t-r,l=e+i,c=t+r,p=e-i,d=t+r;return[s,n,u,o,l,c,p,d]}updateTextureMappingBuffer(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([...this.calculateTexturePosition()]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}updateFrameSize(){this.frameWidth=this.sourceVideoElement.videoWidth,this.frameHeight=this.sourceVideoElement.videoHeight}createCanvas(){let e=document.createElement("canvas");return e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e}};import{isNullable as LC,now as os,once as $C,Subscription as MC,ValueSubject as Uc,isNonNullable as DC,safeStorage as Hc,filterChanged as CC}from"@vkontakte/videoplayer-shared";var go="stalls_manager_metrics",jc="stalls_manager_abr_params",pT="stalls_manager_default_tuning_abr_params",Qc=class{constructor(){this.isSeeked$=new Uc(!1);this.isBuffering$=new Uc(!1);this.maxQualityLimit=void 0;this.currentStallsCount=0;this.sumStallsDuration=0;this.lastStallDuration=0;this.providerStartWatchingTimestamp=0;this.lastUniqueVideoTrackSelectedTimestamp=0;this.predictedThroughputWithoutData=0;this.subscription=new MC;this.severeStallOccurred$=new Uc(!1)}init(e){this.currentStallDuration$=e.currentStallDuration$,this.videoLastDataObtainedTimestamp$=e.videoLastDataObtainedTimestamp$,this.throughput$=e.throughput$,this.rtt$=e.rtt$,this.tuning=e.tuning,this.abrParams=e.abrParams,this.resetStoredAbrParamsIfNeeded(),this.subscribe(e)}get videoMaxQualityLimit(){return this.maxQualityLimit}get predictedThroughput(){return this.predictedThroughputWithoutData}get abrTuningParams(){let e=this.tuning.enabled?this.getStoredData(jc):{};return{...this.abrParams,...e}}set lastVideoTrackSelected(e){this.lastUniqueVideoTrackSelected?.id!==e.id&&(this.lastUniqueVideoTrackSelected=e,this.lastUniqueVideoTrackSelectedTimestamp=os(),this.currentStallsCount=0)}destroy(){window.clearTimeout(this.qualityRestrictionTimer),this.subscription.unsubscribe(),this.currentStallDuration$.getValue()!==0&&this.updateStallData();let e=(os()-this.providerStartWatchingTimestamp-this.sumStallsDuration)/1e3,t=this.sumStallsDuration;this.addStallInfoToHistory(e,t),this.updateStoredAbrParams()}resetStoredAbrParamsIfNeeded(){let{bitrateFactorAtEmptyBuffer:e,bitrateFactorAtFullBuffer:t,containerSizeFactor:i}={...this.getStoredData(pT)},{bitrateFactorAtEmptyBuffer:r,bitrateFactorAtFullBuffer:s,containerSizeFactor:n}={...this.abrParams};this.tuning.enabled&&e===r&&t===s&&i===n||(this.removeStoredData(jc),this.setStoredData(pT,{bitrateFactorAtEmptyBuffer:r,bitrateFactorAtFullBuffer:s,containerSizeFactor:n}))}updateStoredAbrParams(){let e=[],t=this.getStoredData(go,"[]");if(!this.tuning.enabled||t.length<this.tuning.stallsMetricsHistoryLength)return;let i=t.reduce((s,n)=>s+n.tvt,0);if(this.tuning.useTotalStallsDurationPerTvt){let n=t.reduce((u,o)=>u+o.stallsDuration,0)/i;e.push(this.calculateOptimalAbrParams(n,i))}if(this.tuning.useAverageStallsDurationPerTvt){let s=t.reduce((n,u)=>n+u.stallsDurationPerTvt,0)/t.length;e.push(this.calculateOptimalAbrParams(s,i))}this.tuning.useEmaStallsDurationPerTvt&&e.push(this.calculateOptimalAbrParams(t[t.length-1].stallsDurationPerTvtSmoothed,i));let r={bitrateFactorAtEmptyBuffer:Math.max(...e.map(s=>s.bitrateFactorAtEmptyBuffer)),bitrateFactorAtFullBuffer:Math.max(...e.map(s=>s.bitrateFactorAtFullBuffer)),containerSizeFactor:Math.min(...e.map(s=>s.containerSizeFactor))};this.setStoredData(go,[]),this.setStoredData(jc,r)}calculateOptimalAbrParams(e,t){let{targetStallsDurationPerTvt:i,deviationStallsDurationPerTvt:r,criticalStallsDurationPerTvt:s,abrAdjustingSpeed:n,significantTvt:u,stallsMetricsHistoryLength:o}=this.tuning,l=n*Math.min(t/(u*o),1),c=this.abrTuningParams;return e<i-r?c={bitrateFactorAtEmptyBuffer:Math.max(c.bitrateFactorAtEmptyBuffer-l,this.abrParams.minBitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.max(c.bitrateFactorAtFullBuffer-l,this.abrParams.minBitrateFactorAtFullBuffer),containerSizeFactor:Math.min(c.containerSizeFactor+l,this.abrParams.maxContainerSizeFactor)}:e>i+r&&(c={bitrateFactorAtEmptyBuffer:Math.min(c.bitrateFactorAtEmptyBuffer+l,this.abrParams.maxBitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.min(c.bitrateFactorAtFullBuffer+l,this.abrParams.maxBitrateFactorAtFullBuffer),containerSizeFactor:Math.max(c.containerSizeFactor-l,this.abrParams.minContainerSizeFactor)}),e>s&&(c={bitrateFactorAtEmptyBuffer:Math.max(c.bitrateFactorAtEmptyBuffer,this.abrParams.bitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.max(c.bitrateFactorAtFullBuffer,this.abrParams.bitrateFactorAtFullBuffer),containerSizeFactor:Math.min(c.containerSizeFactor,this.abrParams.containerSizeFactor)}),c}getStoredData(e,t="{}"){return JSON.parse(Hc.get(e)??t)}setStoredData(e,t){Hc.set(e,JSON.stringify(t))}removeStoredData(e){Hc.remove(e)}addStallInfoToHistory(e,t){if(e<this.tuning.minTvtToBeCounted||e>this.tuning.maxTvtToBeCounted||e*1e3<t)return;let i=this.getStoredData(go,"[]"),r=t/e,s=i.length?$t(i[i.length-1].stallsDurationPerTvtSmoothed,t/e,this.tuning.emaAlpha):r,n={tvt:e,stallsDuration:t,stallsDurationPerTvt:r,stallsDurationPerTvtSmoothed:s};i.push(n),i.length>this.tuning.stallsMetricsHistoryLength&&i.shift(),this.setStoredData(go,i)}updateStallData(){this.providerStartWatchingTimestamp&&!this.isSeeked$.getValue()&&(this.sumStallsDuration+=Math.min(this.lastStallDuration,this.tuning.maxPossibleStallDuration),this.currentStallsCount++)}subscribe(e){this.subscription.add(e.isSeeked$.subscribe(this.isSeeked$)),this.subscription.add(e.isBuffering$.subscribe(this.isBuffering$)),this.subscription.add(e.looped$.subscribe(t=>this.currentStallsCount=0)),this.subscription.add(e.playing$.pipe($C()).subscribe(t=>this.providerStartWatchingTimestamp=os())),this.subscription.add(this.currentStallDuration$.pipe(CC()).subscribe(t=>{let{stallDurationNoDataBeforeQualityDecrease:i,stallCountBeforeQualityDecrease:r,resetQualityRestrictionTimeout:s,ignoreStallsOnSeek:n}=this.tuning;if(LC(this.lastUniqueVideoTrackSelected)||n&&this.isSeeked$.getValue())return;let u=this.rtt$.getValue(),o=this.throughput$.getValue(),l=this.videoLastDataObtainedTimestamp$.getValue(),c=os(),p=r&&this.currentStallsCount>=r,d=i&&c-this.lastUniqueVideoTrackSelectedTimestamp>=i+u&&c-l>=i+u&&t>=i;(p||d)&&(this.severeStallOccurred$.next(!0),window.clearTimeout(this.qualityRestrictionTimer),this.maxQualityLimit=this.lastUniqueVideoTrackSelected.quality,DC(this.lastUniqueVideoTrackSelected.bitrate)&&o>this.lastUniqueVideoTrackSelected.bitrate&&(this.predictedThroughputWithoutData=this.lastUniqueVideoTrackSelected.bitrate)),!t&&os()-this.providerStartWatchingTimestamp>this.lastStallDuration&&(this.updateStallData(),this.severeStallOccurred$.next(!1),window.clearTimeout(this.qualityRestrictionTimer),this.qualityRestrictionTimer=window.setTimeout(()=>{this.maxQualityLimit=void 0,this.predictedThroughputWithoutData=0},s)),this.lastStallDuration=t}))}},So=Qc;import{combine as BC,map as VC,observeElementSize as _C,Subscription as OC,ValueSubject as Wc,noop as FC}from"@vkontakte/videoplayer-shared";var vo=class{constructor(){this.subscription=new OC;this.pipSize$=new Wc(void 0);this.videoSize$=new Wc(void 0);this.elementSize$=new Wc(void 0);this.pictureInPictureWindowRemoveEventListener=FC}connect({observableVideo:e,video:t}){let i=r=>{let s=r.target;this.pipSize$.next({width:s.width,height:s.height})};this.subscription.add(_C(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(BC({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe(VC(({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 wi=class{constructor(e){this.subscription=new WC;this.videoState=new F("stopped");this.observableVideo=null;this.droppedFramesManager=new cr;this.stallsManager=new So;this.elementSizeManager=new vo;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new Qt;this.audioTrackSwitchHistory=new Qt;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(r.state==="requested"&&i?.to!=="paused"&&e!=="stopped"&&t!=="stopped"&&this.seek(r.position,r.forcePrecise),t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.player.stop(),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),P(this.params.desiredState.playbackState,"stopped",!0));return}switch(e){case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();return;case"ready":t==="paused"?(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="ready"&&P(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):t==="playing"&&this.video.paused?this.playIfAllowed():i?.to==="playing"&&P(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&P(this.params.desiredState.playbackState,"paused");return;default:return qC(e)}}};this.init3DScene=e=>{if(this.scene3D)return;this.scene3D=new Ar(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:e.projectionData?.pose.yaw||0,y:e.projectionData?.pose.pitch||0,z:e.projectionData?.pose.roll||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});let t=this.elementSizeManager.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};this.textTracksManager=new Ye(e.source.url),this.params=e,this.video=$e(e.container,e.tuning),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(ge(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.player=new fo({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode,tracer:this.tracer,forceVideoCodec:this.params.forceVideoCodec}),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params;QC(this.observableVideo)&&(this.observableVideo=Ce(this.video),this.subscription.add(()=>this.observableVideo?.destroy()));let i=this.constructor.name,r=n=>{e.error$.next({id:i,category:hT.WTF,message:`${i} internal logic error`,thrown:n})},s=(n,u)=>this.subscription.add(n.subscribe(u,r));return{output:e,desiredState:t,observableVideo:this.observableVideo,genericErrorListener:r,connect:s}}subscribe(){let{output:e,desiredState:t,observableVideo:i,genericErrorListener:r,connect:s}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe(Gc(l=>!!l.length),mT()).subscribe(l=>{this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks:l})}));let n=this.params.desiredState.seekState.stateChangeEnded$.pipe(zc(l=>l.to.state!=="none"),yo());this.stallsManager.init({isSeeked$:n,currentStallDuration$:this.player.currentStallDuration$,videoLastDataObtainedTimestamp$:this.player.videoLastDataObtainedTimestamp$,throughput$:this.params.dependencies.throughputEstimator.throughput$,rtt$:this.params.dependencies.throughputEstimator.rtt$,tuning:this.params.tuning.stallsManager,abrParams:this.params.tuning.autoTrackSelection,isBuffering$:i.isBuffering$,looped$:i.looped$,playing$:i.playing$}),s(i.ended$,e.endedEvent$),s(i.looped$,e.loopedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(i.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),s(i.loadedMetadata$,e.loadedMetadataEvent$),s(this.player.error$,e.error$),s(this.player.fetcherRecoverableError$,e.fetcherRecoverableError$),s(this.player.fetcherError$,e.fetcherError$),s(this.player.lastConnectionType$,e.httpConnectionType$),s(this.player.lastConnectionReused$,e.httpConnectionReused$),s(this.player.isLive$,e.isLive$),s(this.player.lastRequestFirstBytes$.pipe(Gc(fT),mT()),e.firstBytesEvent$),s(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),s(this.videoState.stateChangeEnded$.pipe(zc(l=>l.to)),this.params.output.playbackState$),this.subscription.add(i.looped$.subscribe(()=>this.player.warmUpMediaSourceIfNeeded(),r)),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(mt(this.video,t.isLooped,r)),this.subscription.add(De(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(ze(this.video,t.playbackRate,i.playbackRateState$,r)),this.elementSizeManager.connect({video:this.video,observableVideo:i}),s(Ke(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),P(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),P(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.params.tuning.changePlaybackStateToPausedWhenEnded&&this.subscription.add(i.ended$.subscribe(()=>{this.videoState.setState("paused"),P(t.playbackState,"paused")})),this.subscription.add(this.player.manifestRequested.subscribe(this.params.output.manifestRequested$)).add(this.player.manifestReceived.subscribe(this.params.output.manifestReceived$)).add(this.player.firstBytesRequested.subscribe(this.params.output.firstBytesRequested$)).add(this.player.firstBytesReceived.subscribe(this.params.output.firstBytesReceived$)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:l})=>{if(l==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let c=this.player.getStreams(),p=this.player.getCodecs();if(UC(c,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let h=[];for(let f of c.audio){h.push(kc(f));let b=[];for(let S of f.representations){let g=zy(S);b.push(g),this.audioTracksMap.set(g,{stream:f,representation:S})}this.audioStreamsMap.set(f,b)}this.params.output.availableAudioStreams$.next(h)}let d=[];for(let h of c.video){d.push(Rc(h));let f=[];for(let b of h.representations){let S=Gy({...b,streamId:h.id});S&&(f.push(S),this.videoTracksMap.set(S,{stream:h,representation:b}))}this.videoStreamsMap.set(h,f)}this.params.output.availableVideoStreams$.next(d);for(let h of c.text)for(let f of h.representations){let b=Yy(h,f);this.textTracksMap.set(b,{stream:h,representation:f})}this.params.output.availableVideoTracks$.next(Array.from(this.videoTracksMap.keys())),this.params.output.availableAudioTracks$.next(Array.from(this.audioTracksMap.keys())),this.params.output.isAudioAvailable$.next(!!this.audioTracksMap.size),p?.video&&this.params.output.availableVideoCodecs$.next(p.video),p?.audio&&this.params.output.availableAudioCodecs$.next(p.audio),this.audioTracksMap.size&&this.textTracksMap.size&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else l==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},r)),this.subscription.add(To(this.player.currentStallDuration$,this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,this.elementSizeManager.getObservable(),this.params.output.elementVisible$,this.droppedFramesManager.onDroopedVideoFramesLimit$,jC(this.video,"progress")).pipe(Gc(()=>this.videoTracksMap.size>0)).subscribe(async()=>{let l=this.player.state$.getState(),c=this.player.state$.getTransition();if(!(0,bT.default)(["manifest_ready","running"],l)||c)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let p=this.selectVideoAudioRepresentations();if(!p)return;let[d,h]=p,f=[...this.videoTracksMap.keys()].find(S=>this.videoTracksMap.get(S)?.representation.id===d.id);fT(f)&&(this.stallsManager.lastVideoTrackSelected=f);let b=this.params.desiredState.autoVideoTrackLimits.getTransition();if(b&&this.params.output.autoVideoTrackLimits$.next(b.to),l==="manifest_ready")await this.player.initRepresentations(d.id,h?.id,this.params.sourceHls);else if(await this.player.switchRepresentation("video",d.id),h){let S=!!t.audioStream.getTransition();await this.player.switchRepresentation("audio",h.id,S)}},r)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:l})=>{this.scene3D&&l&&this.scene3D.pointCameraTo(l.x,l.y)})),this.subscription.add(this.elementSizeManager.subscribe(l=>{this.scene3D&&l&&this.scene3D.setViewportSize(l.width,l.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(yo()).subscribe(l=>{let c=[...this.videoTracksMap.entries()].find(([,{representation:b}])=>b.id===l);if(!c){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[p,{stream:d}]=c,h=this.params.desiredState.videoStream.getTransition();h&&h.to&&h.to.id===d.id&&this.params.desiredState.videoStream.setState(h.to),e.currentVideoTrack$.next(p),e.currentVideoStream$.next(Rc(d));let f=this.player.calculateDurationFromSegments();f&&this.params.output.duration$.next(f/1e3)},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(yo()).subscribe(l=>{let c=[...this.audioTracksMap.entries()].find(([,{representation:f}])=>f.id===l);if(!c){e.currentAudioStream$.next(void 0);return}let[p,{stream:d}]=c,h=this.params.desiredState.audioStream.getTransition();h&&h.to&&h.to.id===d.id&&this.params.desiredState.audioStream.setState(h.to),e.currentAudioStream$.next(kc(d))},r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(l=>{if(l?.is3dVideo&&this.params.tuning.spherical?.enabled)try{this.init3DScene(l),e.is3DVideo$.next(!0)}catch(c){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${c}`})}else this.destroy3DScene(),this.params.tuning.spherical?.enabled&&e.is3DVideo$.next(!1)},r)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,r)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,r)),this.textTracksManager.connect(this.video,t,e);let u=t.playbackState.stateChangeStarted$.pipe(zc(({to:l})=>l==="ready"),yo());this.subscription.add(To(u,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,Yc(["init"])).subscribe(()=>{let l=t.autoVideoTrackSwitching.getState(),p=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:l?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(p)})),this.subscription.add(To(u,this.player.state$.stateChangeEnded$,Yc(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let o=To(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Yc(["init"])).pipe(HC(0));this.subscription.add(o.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?ba:ma,t=this.params.tuning.useNewAutoSelectVideoTrack?Nn:Fn,i=this.params.tuning.useNewAutoSelectVideoTrack?St:On,{desiredState:r,output:s}=this.params,n=r.autoVideoTrackSwitching.getState(),u=r.videoTrack.getState()?.id,l=[...this.videoTracksMap.keys()].find(({id:T})=>T===u),c=s.currentVideoTrack$.getValue(),p=r.videoStream.getState()??(l&&this.videoTracksMap.get(l)?.stream)??this.videoStreamsMap.size===1?this.videoStreamsMap.keys().next().value:void 0;if(!p)return;let d=[...this.videoStreamsMap.keys()].find(({id:T})=>T===p.id),h=d&&this.videoStreamsMap.get(d);if(!h)return;let f=he(this.video.buffered,this.video.currentTime*1e3),b;this.player.isActiveLive$.getValue()?b=this.player.isLowLatency$.getValue()?this.params.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.params.tuning.dashCmafLive.normalizedLiveMinBufferSize:this.player.isLive$.getValue()?b=this.params.tuning.dashCmafLive.normalizedTargetMinBufferSize:b=n?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;let S=(this.video.duration*1e3||1/0)-this.video.currentTime*1e3,g=Math.min(f/Math.min(b,S||1/0),1),I=r.audioStream.getState()??(this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0),x=[...this.audioStreamsMap.keys()].find(({id:T})=>T===I?.id)??this.audioStreamsMap.keys().next().value,y=0;if(x){if(l&&!n){let T=e(l,h,this.audioStreamsMap.get(x)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);y=Math.max(y,T?.bitrate??-1/0)}if(c){let T=e(c,h,this.audioStreamsMap.get(x)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);y=Math.max(y,T?.bitrate??-1/0)}}let w=i(h,{container:this.elementSizeManager.getValue(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.stallsManager.abrTuningParams,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:y,forwardBufferHealth:g,current:c,visible:this.params.output.elementVisible$.getValue(),history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,stallsVideoMaxQualityLimit:this.stallsManager.videoMaxQualityLimit,stallsPredictedThroughput:this.stallsManager.predictedThroughput,abrLogger:this.params.dependencies.abrLogger}),D=n?w??l:l??w,L=x&&t(D,h,this.audioStreamsMap.get(x)??[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.stallsManager.abrTuningParams,forwardBufferHealth:g,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),A=this.videoTracksMap.get(D)?.representation,R=L&&this.audioTracksMap.get(L)?.representation;if(A&&R)return[A,R];if(A&&!R&&this.audioTracksMap.size===0)return[A,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){Be(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:hT.DOM,thrown:e}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.stallsManager.destroy(),this.elementSizeManager.destroy(),this.destroy3DScene(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),this.params.output.currentVideoStream$.next(void 0),Me(this.video),this.tracer.end()}};var us=class extends wi{subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();i(t.timeUpdate$,e.position$),i(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}};import{combine as Kc,merge as gT,filter as ST,filterChanged as vT,isNullable as Xc,map as yT,ValueSubject as Jc,isNonNullable as GC}from"@vkontakte/videoplayer-shared";var ls=class extends wi{constructor(e){super(e),this.textTracksManager.destroy()}subscribe(){super.subscribe();let e=!1,t=-1,{output:i,observableVideo:r,desiredState:s,connect:n}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canPlayLiveTailBuffer$.next(!0),n(r.timeUpdate$,i.liveBufferTime$),n(this.player.liveSeekableDuration$,i.duration$),n(this.player.liveLatency$,i.liveLatency$);let u=new Jc(1);n(r.playbackRateState$,u),this.params.tuning.dashCmafLive.catchupLiveForMutedInactiveTab&&this.subscription.add(i.elementVisible$.pipe(vT()).subscribe(o=>{let l=i.position$.getValue(),c=i.volume$.getValue(),p=!c.volume||c.muted;!o&&!l&&p?e=!0:o&&e&&(this.seek(0),e=!1)})),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(s.isLowLatency.stateChangeEnded$.pipe(yT(o=>o.to)).subscribe(this.player.isLowLatency$)).add(Kc({liveBufferTime:i.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(yT(({liveBufferTime:o,liveAvailabilityStartTime:l})=>o&&l?o+l:void 0)).subscribe(i.liveTime$)).add(this.player.liveStreamStatus$.pipe(ST(o=>GC(o))).subscribe(o=>i.isLiveEnded$.next(o!=="active"&&i.position$.getValue()===0))).add(Kc({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:gT(r.playbackRateState$,new Jc(1))}).pipe(ST(({liveStreamStatus:o,liveDuration:l})=>o==="active"&&!!l)).subscribe(({liveDuration:o,playbackRate:l})=>{let c=i.liveBufferTime$.getValue(),p=i.position$.getValue(),{playbackCatchupSpeedup:d}=this.params.tuning.dashCmafLive.lowLatency;p||l<1-d||this.video.paused||Xc(c)||(t=o-c)})).add(Kc({time:i.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:gT(r.playbackRateState$,new Jc(1))}).pipe(vT((o,l)=>this.player.liveStreamStatus$.getValue()==="active"?o.liveDuration===l.liveDuration:o.time===l.time)).subscribe(({time:o,liveDuration:l,playbackRate:c})=>{let p=i.position$.getValue(),{playbackCatchupSpeedup:d}=this.params.tuning.dashCmafLive.lowLatency;if(!p&&!this.video.paused&&c>=1-d||Xc(o)||Xc(l))return;let h=-1*(l-o-t);i.position$.next(Math.min(h,0))})).add(this.player.currentLiveTextRepresentation$.subscribe(o=>{if(o){let l=Ky(o);this.params.output.availableTextTracks$.next([l])}}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,i=Math.trunc(t/1e3<=Math.abs(this.params.output.duration$.getValue())?t:0);this.player.seekLive(i).then(()=>{this.params.output.position$.next(e/1e3)})}};import{assertNever as vB,assertNonNullable as yB,debounce as TB,ErrorCategory as OT,filter as fd,filterChanged as Mo,fromEvent as IB,isNonNullable as FT,isNullable as EB,map as md,merge as Do,observableFrom as bd,once as NT,Subscription as xB}from"@vkontakte/videoplayer-shared";var _T=C(Ee(),1),pd=C(xa(),1);import{abortable as ud,assertNonNullable as Lr,combine as $r,ErrorCategory as ut,filter as Ro,filterChanged as ms,flattenObject as bs,fromEvent as It,getTraceSubscriptionMethod as lB,interval as ld,isNonNullable as gs,isNullable as BT,map as Mr,merge as Li,now as cd,Subject as Jt,Subscription as dd,tap as cB,throttle as VT,ValueSubject as te}from"@vkontakte/videoplayer-shared";var wo=C(Ee(),1),Ri=C(at(),1),Ao=C(xa(),1);var $T=C(gn(),1);import{assertNever as zC,ErrorCategory as TT,Subject as IT}from"@vkontakte/videoplayer-shared";var YC=18,ET=!1;try{ET=B.browser.isSafari&&!!B.browser.safariVersion&&B.browser.safariVersion<=YC}catch(a){console.error(a)}var Zc=class{constructor(e){this.bufferFull$=new IT;this.error$=new IT;this.queue=[];this.currentTask=null;this.destroyed=!1;this.abortRequested=!1;this.completeTask=()=>{try{if(this.currentTask){let e=this.currentTask.signal?.aborted;this.currentTask.callback(!e),this.currentTask=null}this.queue.length&&this.pull()}catch(e){this.error$.next({id:"BufferTaskQueueUnknown",category:TT.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:e})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(i=>{let r={operation:"append",data:e,signal:t,callback:i};this.queue.push(r),this.pull()})}async remove(e,t,i){return i&&i.aborted?!1:new Promise(r=>{let s={operation:"remove",from:e,to:t,signal:i,callback:r};this.queue.unshift(s),this.pull()})}async abort(e){return new Promise(t=>{let i,r=s=>{this.abortRequested=!1,t(s)};ET&&e?i={operation:"safariAbort",init:e,callback:r}:i={operation:"abort",callback:r};for(let{callback:s}of this.queue)s(!1);this.abortRequested=!0,i&&(this.queue=[i]),this.pull()})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){if((this.buffer.updating||this.currentTask||this.destroyed)&&!this.abortRequested)return;let e=this.queue.shift();if(!e)return;if(e.signal?.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(r){r instanceof DOMException&&r.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):r instanceof DOMException&&r.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:TT.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:r}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){let{operation:t}=e;switch(t){case"append":this.buffer.appendBuffer(e.data);break;case"remove":this.buffer.remove(e.from/1e3,e.to/1e3);break;case"abort":this.buffer.abort();break;case"safariAbort":{this.buffer.abort(),this.buffer.appendBuffer(e.init);break}default:zC(t)}}},xT=Zc;import{abortable as Xt,assertNonNullable as _e,ErrorCategory as Pi,fromEvent as ad,getExponentialDelay as sd,isNonNullable as Pr,isNullable as ye,now as xo,once as eB,Subject as tB,Subscription as iB,ValueSubject as ki}from"@vkontakte/videoplayer-shared";var ed=C(at(),1);import{videoSizeToQuality as KC,throttleFn as XC}from"@vkontakte/videoplayer-shared";var wT=({id:a,width:e,height:t,bitrate:i,fps:r,quality:s,streamId:n})=>{let u=(s?jt(s):void 0)??KC({width:e,height:t});return u&&{id:a,quality:u,bitrate:i,size:{width:e,height:t},fps:r,streamId:n}},AT=({id:a,bitrate:e})=>({id:a,bitrate:e}),PT=({language:a,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:a,label:e}),kT=({language:a,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:a,label:e}),td=({id:a,language:e,label:t,codecs:i,isDefault:r})=>({id:a,language:e,label:t,codec:(0,ed.default)(i.split("."),0),isDefault:r}),id=({id:a,language:e,label:t,hdr:i,codecs:r})=>({id:a,language:e,hdr:i,label:t,codec:(0,ed.default)(r.split("."),0)}),rd=a=>"url"in a,je=a=>a.type==="template";var RT=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},Ai=(a,e)=>{for(let t of a)if(e(t))return t;return null},LT=a=>{let e=!1,t=XC(()=>{e=!0},a);return()=>{try{return t(),e}finally{e=!1}}};import{fromEvent as JC,Subscription as ZC}from"@vkontakte/videoplayer-shared";var Io=a=>{let e=[];for(let t=0;t<a.length;t++){let i=Math.floor(a.start(t)*1e3),r=Math.ceil(a.end(t)*1e3);e.push(i,r)}return e};var Eo=class{constructor(e,t){this.lastUpdateTs=0;this.lastCallTs=0;this.prevRanges=[];this.subscription=new ZC;this.mediaSource=e,this.sourceBuffer=t,this.subscription.add(JC(this.sourceBuffer,"updateend").subscribe(()=>this.updateend()))}updateend(){if(!V(this.mediaSource,this.sourceBuffer))return;let{prevRanges:e}=this,t=Io(this.sourceBuffer.buffered);this.prevRanges=t,this.isRangesRemoved(e,t)&&(this.lastUpdateTs=Date.now())}isRangesRemoved(e,t){if(e.length!==t.length)return!0;for(let i=0;i<e.length;i+=2){let r=e[i],s=e[i+1],n=t[i],u=t[i+1];if(n>r||u<s)return!0}return!1}wasUpdated(){let{lastCallTs:e,lastUpdateTs:t}=this;return this.lastCallTs=Date.now(),e<=t}destroy(){this.subscription.unsubscribe()}};var cs=class{constructor(e,t,i,{fetcher:r,tuning:s,getCurrentPosition:n,isActiveLowLatency:u,compatibilityMode:o=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new ki(0);this.currentLowLatencySegmentLength$=new ki(0);this.currentSegmentLength$=new ki(0);this.onLastSegment$=new ki(!1);this.fullyBuffered$=new ki(!1);this.playingRepresentation$=new ki(void 0);this.playingRepresentationInit$=new ki(void 0);this.error$=new tB;this.gaps=[];this.subscription=new iB;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new X;this.switchAbortController=new X;this.destroyAbortController=new X;this.bufferLimit=1/0;this.failedDownloads=0;this.baseUrls=[];this.baseUrlsIndex=0;this.isLive=!1;this.liveUpdateSegmentIndex=0;this.liveInitialAdditionalOffset=0;this.isSeekingLive=!1;this.index=0;this.lastDataObtainedTimestampMs=0;this.loadByteRangeSegmentsTimeoutId=0;this.sourceBufferBufferedDiff=null;this.startWith=Xt(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);_e(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new xT(this.sourceBuffer),this.sourceBufferBufferedDiff=new Eo(this.mediaSource,this.sourceBuffer),this.subscription.add(ad(this.sourceBuffer,"updateend").subscribe(()=>{this.maintain()})),this.subscription.add(ad(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:Pi.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let u=this.getCurrentPosition();if(!this.sourceBuffer||!u||!V(this.mediaSource,this.sourceBuffer))return;let o=Math.min(this.bufferLimit,hr(this.sourceBuffer.buffered)*.8);this.bufferLimit=o;let l=he(this.sourceBuffer.buffered,u),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(u,n*2,l<c).catch(p=>{this.handleAsyncError(p,"pruneBuffer")})})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(n=>this.error$.next(n))),yield this.loadInit(t,"high",!0);let i=this.initData.get(t.id),r=this.segments.get(t.id),s=this.parsedInitData.get(t.id);_e(i,"No init buffer for starting representation"),_e(r,"No segments for starting representation"),i instanceof ArrayBuffer&&(this.searchGaps(r,t),yield this.sourceBufferTaskQueue.append(i,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(s))}.bind(this));this.switchTo=Xt(this.destroyAbortController.signal,async function*(e,t=!1){if(!V(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);_e(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if(ye(s)||ye(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),_e(r,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!V(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer();else{let n=this.getCurrentPosition();Pr(n)&&!this.isLive&&(this.bufferLimit=1/0,await this.pruneBuffer(n,1/0,!0)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}this.maintain()}}.bind(this));this.switchToOld=Xt(this.destroyAbortController.signal,async function*(e,t=!1){if(!V(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);_e(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if(ye(s)||ye(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),_e(r,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!V(this.mediaSource,this.sourceBuffer)))if(yield this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer(),this.maintain();else{let n=this.getCurrentPosition();Pr(n)&&(this.isLive||(this.bufferLimit=1/0,await this.pruneBuffer(n,1/0,!0)),this.maintain(n)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}}.bind(this));this.seekLive=Xt(this.destroyAbortController.signal,async function*(e){let t=(0,Ao.default)(e,o=>o.representations)??[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let o of this.representations.keys()){let l=t.find(d=>d.id===o);l&&this.representations.set(o,l);let c=this.representations.get(o);if(!c||!je(c.segmentReference))return;let p=this.getActualLiveStartingSegments(c.segmentReference);this.segments.set(c.id,p)}let i=this.switchingToRepresentationId??this.downloadingRepresentationId,r=this.representations.get(i);_e(r);let s=this.segments.get(i);_e(s,"No segments for starting representation");let n=this.initData.get(i);if(_e(n,"No init buffer for starting representation"),!(n instanceof ArrayBuffer))return;let u=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,yield this.abort(),u&&(yield this.sourceBufferTaskQueue.remove(u.from*1e3,u.to*1e3,this.destroyAbortController.signal)),this.searchGaps(s,r),yield this.sourceBufferTaskQueue.append(n,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this));this.fetcher=r,this.tuning=s,this.compatibilityMode=o,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=u,this.isLive=!!l?.live,this.baseUrls=l?.baseUrls??[],this.initData=new Map(i.map(c=>[c.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(i.map(c=>[c.id,c])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}switchToWithPreviousAbort(e,t=!1){!V(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new X,Xt(this.switchAbortController.signal,async function*(i,r=!1){this.switchingToRepresentationId=i;let s=this.representations.get(i);_e(s,`No such representation ${i}`);let n=this.segments.get(i),u=this.initData.get(i);if(ye(u)||ye(n)?yield this.loadInit(s,"high",!1):u instanceof Promise&&(yield u),n=this.segments.get(i),_e(n,"No segments for starting representation"),u=this.initData.get(i),!(!(u instanceof ArrayBuffer)||!this.sourceBuffer||!V(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(u,this.downloadAbortController.signal),r)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=i,yield this.dropBuffer();else{let o=this.getCurrentPosition();Pr(o)&&!this.isLive&&(this.bufferLimit=this.forwardBufferTarget,yield this.pruneBuffer(o,1/0,!0)),this.downloadingRepresentationId=i,this.switchingToRepresentationId=void 0}this.maintain()}}.bind(this))(e,t))}warmUpMediaSource(){!ye(this.sourceBuffer)&&!this.sourceBuffer.updating&&(this.sourceBuffer.mode="segments")}async abort(){for(let e of this.activeSegments)this.abortSegment(e.segment);return this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new X,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(ye(e)||ye(this.downloadingRepresentationId)||ye(this.playingRepresentationId)||ye(this.sourceBuffer)||!V(this.mediaSource,this.sourceBuffer)||Pr(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if(_e(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;let r=i.find(c=>e>=c.time.from&&e<c.time.to);Pr(r)&&isFinite(r.time.from)&&isFinite(r.time.to)&&this.currentSegmentLength$.next(r?.time.to-r.time.from);let s=e,n=100;if(this.playingRepresentationId!==this.downloadingRepresentationId){let c=he(this.sourceBuffer.buffered,e),p=r?r.time.to+n:-1/0;r&&r.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&c>=r.time.to-e+n&&(s=p)}if(isFinite(this.bufferLimit)&&hr(this.sourceBuffer.buffered)>=this.bufferLimit){let c=he(this.sourceBuffer.buffered,e),p=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,c<p).catch(d=>{this.handleAsyncError(d,"pruneBuffer")});return}let o=null;if(!this.activeSegments.size&&(o=this.selectForwardBufferSegments(i,t.segmentReference.type,s),o?.length)){let c="auto";if(this.tuning.dash.useFetchPriorityHints&&r)if((0,wo.default)(o,r))c="high";else{let p=(0,Ri.default)(o,0);p&&p.time.from-r.time.to>=this.forwardBufferTarget/2&&(c="low")}this.loadSegments(o,t,c).catch(p=>{this.handleAsyncError(p,"loadSegments")})}(!this.preloadOnly&&!this.allInitsLoaded&&r&&r.status==="fed"&&!o?.length&&he(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let l=(0,Ri.default)(i,-1);!this.isLive&&l&&(this.fullyBuffered$.next(l.time.to-e-he(this.sourceBuffer.buffered,e)<n),this.onLastSegment$.next(e-l.time.from>0))}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}searchGaps(e,t){this.gaps=[];let i=0,r=this.isLive?this.liveInitialAdditionalOffset:0;for(let s of e)Math.trunc(s.time.from-i)>0&&this.gaps.push({representation:t.id,from:i,to:s.time.from+r,persistent:!0}),i=s.time.to;Pr(t.duration)&&t.duration-i>0&&!this.isLive&&this.gaps.push({representation:t.id,from:i,to:t.duration,persistent:!0})}getActualLiveStartingSegments(e){let t=e.segments,i=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,r=[],s=0,n=t.length-1;do r.unshift(t[n]),s+=t[n].time.to-t[n].time.from,n--;while(s<i&&n>=0);return this.liveInitialAdditionalOffset=s-i,this.isActiveLowLatency()?[r[0]]:r}getLiveSegmentsToLoadState(e){let t=(0,Ao.default)(e?.streams[this.kind],r=>r.representations).find(r=>r.id===this.downloadingRepresentationId);if(!t)return;let i=this.segments.get(t.id);if(i?.length)return{from:i[0].time.from,to:i[i.length-1].time.to}}updateLive(e){let t=(0,Ao.default)(e?.streams[this.kind],i=>i.representations)??[];if(![...this.segments.values()].every(i=>!i.length))for(let i of t){if(!i||!je(i.segmentReference))return;let r=i.segmentReference.segments.map(l=>({...l,status:"none",size:void 0})),s=100,n=this.segments.get(i.id)??[],u=(0,Ri.default)(n,-1)?.time.to??0,o=r?.findIndex(l=>u>=l.time.from+s&&u<=l.time.to+s);if(o===-1){this.liveUpdateSegmentIndex=0;let l=this.getActualLiveStartingSegments(i.segmentReference);this.segments.set(i.id,l)}else{let l=r.slice(o+1);this.segments.set(i.id,[...n,...l])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;_e(e);let t=this.segments.get(e);if(t?.length){let i=t[t.length-1];this.updateLowLatencyLiveIfNeeded(i)}}updateLowLatencyLiveIfNeeded(e){let t=0;for(let i of this.representations.values()){let r=i.segmentReference;if(!je(r))return;let s=this.segments.get(i.id);if(!s)continue;let n=s.find(o=>Math.floor(o.time.from)===Math.floor(e.time.from));if(n&&!isFinite(n.time.to)&&(n.time.to=e.time.to,t=n.time.to-n.time.from),!!!s.find(o=>Math.floor(o.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let o=Math.round(e.time.to*r.timescale/1e3).toString(10),l=nt(r.segmentTemplateUrl,{segmentTime:o});s.push({status:"none",time:{from:e.time.to,to:1/0},url:l})}}this.currentLowLatencySegmentLength$.next(t)}findSegmentStartTime(e){let t=this.switchingToRepresentationId??this.downloadingRepresentationId??this.playingRepresentationId;if(!t)return;let i=this.segments.get(t);return i?i.find(s=>s.time.from<=e&&s.time.to>=e)?.time.from??void 0:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),this.sourceBufferTaskQueue?.destroy(),this.sourceBufferBufferedDiff?.destroy(),this.gapDetectionIdleCallback&&vt&&vt(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&vt&&vt(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer)try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(e){if(!(e instanceof DOMException&&e.name==="NotFoundError"))throw e}this.sourceBuffer=null,this.downloadAbortController.abort(),this.switchAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,i){return this.checkEjectedSegments(),this.isLive?this.selectForwardBufferSegmentsLive(e,i):this.selectForwardBufferSegmentsRecord(e,t,i)}selectForwardBufferSegmentsLive(e,t){if(this.playingRepresentationId!==this.downloadingRepresentationId){let i=e.findIndex(r=>t>=r.time.from&&t<r.time.to);this.liveUpdateSegmentIndex=i}return this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):null}selectForwardBufferSegmentsRecord(e,t,i){let r=this.getForwardBufferDuration(i),s=e.findIndex(({status:d,time:{from:h,to:f}},b)=>{let S=h<=i&&f>=i,g=h>i||S||b===0&&i===0,I=Math.min(this.forwardBufferTarget,this.bufferLimit),x=this.preloadOnly&&h<=i+I||r<I&&f-h>=I||f<=i+I;return(d==="none"||d==="partially_ejected"&&g&&x&&this.sourceBuffer&&V(this.mediaSource,this.sourceBuffer)&&!(Se(this.sourceBuffer.buffered,h)&&Se(this.sourceBuffer.buffered,f)))&&g&&x});if(s===-1)return null;if(t!=="byteRange")return e.slice(s,s+1);let n=e,u=0,o=0,l=[],c=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,p=this.preloadOnly?this.forwardBufferTarget:0;for(let d=s;d<n.length&&(u<=c||o<=p);d++){let h=n[d];if(u+=h.byte.to+1-h.byte.from,o+=h.time.to+1-h.time.from,h.status==="none"||h.status==="partially_ejected")l.push(h);else break}return l}async loadSegments(e,t,i="auto"){je(t.segmentReference)?await this.loadTemplateSegment(e[0],t,i):await this.loadByteRangeSegments(e,t,i)}async loadTemplateSegment(e,t,i="auto"){e.status="downloading";let r={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(r);let{range:s,url:n,signal:u,onProgress:o,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&u&&(await Xt(u,async function*(){let c=sd(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(p=>setTimeout(p,c))}.bind(this))(),u.aborted&&this.abortActiveSegments([e]));try{let c=await this.fetcher.fetch(n,{range:s,signal:u,onProgress:o,priority:i,isLowLatency:this.isActiveLowLatency(),bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation});if(this.lastDataObtainedTimestampMs=xo(),!c)return;let p=new DataView(c),d=yt(t.mime);if(!isFinite(r.segment.time.to)){let b=t.segmentReference.timescale;r.segment.time.to=d.getChunkEndTime(p,b)}o&&r.feedingBytes&&l?await Promise.all(l):await this.sourceBufferTaskQueue.append(p,u);let{serverDataReceivedTimestamp:h,serverDataPreparedTime:f}=d.getServerLatencyTimestamps(p);h&&f&&this.currentLiveSegmentServerLatency$.next(f-h),r.segment.status="downloaded",this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(c){this.abortActiveSegments([e]),Tt(c)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}updateRepresentationsBaseUrlIfNeeded(){if(!this.tuning.dash.enableBaseUrlSupport||!this.baseUrls.length||this.failedDownloads<=this.tuning.dash.maxSegmentRetryCount)return;this.baseUrlsIndex=(this.baseUrlsIndex+1)%this.baseUrls.length;let e=this.baseUrls[this.baseUrlsIndex];for(let t of this.representations.values())je(t.segmentReference)?t.segmentReference.baseUrl=e:t.segmentReference.url=e}async loadByteRangeSegments(e,t,i="auto"){if(!e.length)return;for(let o of e)o.status="downloading",this.activeSegments.add({segment:o,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:r,url:s,signal:n,onProgress:u}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(await Xt(n,async function*(){let o=sd(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,o),ad(window,"online").pipe(eB()).subscribe(()=>{l(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(s,{range:r,onProgress:u,signal:n,priority:i,bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation}),this.lastDataObtainedTimestampMs=xo(),this.failedDownloads=0}catch(o){this.abortActiveSegments(e),Tt(o)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}prepareByteRangeFetchSegmentParams(e,t){if(je(t.segmentReference))throw new Error("Representation is not byte range type");let i=t.segmentReference.url,r={from:(0,Ri.default)(e,0).byte.from,to:(0,Ri.default)(e,-1).byte.to},{signal:s}=this.downloadAbortController;return{url:i,range:r,signal:s,onProgress:async(u,o)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=xo(),await this.onSomeByteRangesDataLoaded({dataView:u,loaded:o,signal:s,onSegmentAppendFailed:()=>this.abort(),globalFrom:r?r.from:0,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:Pi.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!je(t.segmentReference))throw new Error("Representation is not template type");let i=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&i.searchParams.set("low-latency","yes");let r=i.toString(),{signal:s}=this.downloadAbortController,n=[],o=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(l,c)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=xo();let p=this.onSomeTemplateDataLoaded({dataView:l,loaded:c,signal:s,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(p)}catch(p){this.error$.next({id:"SegmentFeeding",category:Pi.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:p})}}:void 0;return{url:r,signal:s,onProgress:o,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)(0,wo.default)(e,t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:r,signal:s}){if(!this.activeSegments.size||!V(this.mediaSource,this.sourceBuffer))return;let n=this.representations.get(t);if(n)for(let u of this.activeSegments){let{segment:o}=u;if(u.representationId===t){if(s.aborted){r();continue}if(u.loadedBytes=i,u.loadedBytes>u.feedingBytes){let l=new DataView(e.buffer,e.byteOffset+u.feedingBytes,u.loadedBytes-u.feedingBytes),c=yt(n.mime).parseFeedableSegmentChunk(l,this.isLive);c?.byteLength&&(o.status="partially_fed",u.feedingBytes+=c.byteLength,await this.sourceBufferTaskQueue.append(c),u.fedBytes+=c.byteLength)}}}}async onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:s,onSegmentAppendFailed:n}){if(!this.activeSegments.size||!V(this.mediaSource,this.sourceBuffer))return;let u=this.representations.get(t);if(u)for(let o of this.activeSegments){if(o.representationId!==t)continue;if(s.aborted){await n();continue}let{segment:l}=o,c=l.byte.from-i,p=l.byte.to-i,d=p-c+1,h=c<r,f=p<=r;if(h){if(l.status==="downloading"&&f){l.status="downloaded";let b=new DataView(e.buffer,e.byteOffset+c,d);await this.sourceBufferTaskQueue.append(b,s)&&!s.aborted?this.onSegmentFullyAppended(o,t):await n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(l.status==="downloading"||l.status==="partially_fed")&&(o.loadedBytes=Math.min(d,r-c),o.loadedBytes>o.feedingBytes)){let b=new DataView(e.buffer,e.byteOffset+c+o.feedingBytes,o.loadedBytes-o.feedingBytes),S=o.loadedBytes===d?b:yt(u.mime).parseFeedableSegmentChunk(b);S?.byteLength&&(l.status="partially_fed",o.feedingBytes+=S.byteLength,await this.sourceBufferTaskQueue.append(S,s)&&!s.aborted?(o.fedBytes+=S.byteLength,o.fedBytes===d&&this.onSegmentFullyAppended(o,t)):await n())}}}}onSegmentFullyAppended(e,t){if(!(ye(this.sourceBuffer)||!V(this.mediaSource,this.sourceBuffer))){!this.isLive&&B.browser.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(Se(this.sourceBuffer.buffered,e.segment.time.from,100)&&Se(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:Pi.VIDEO_PIPELINE,message:"Browser stuck on empty result of adding segment to source buffer"})),this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status="fed",rd(e.segment)&&(e.segment.size=e.fedBytes);for(let i of this.representations.values()){if(i.id===t)continue;let r=this.segments.get(i.id);if(r)for(let s of r)s.status==="fed"&&Math.round(s.time.from)===Math.round(e.segment.time.from)&&Math.round(s.time.to)===Math.round(e.segment.time.to)&&(s.status="none")}this.isActiveLowLatency()&&this.updateLowLatencyLiveIfNeeded(e.segment),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,e.segment)}}abortSegment(e){e.status==="partially_fed"?e.status="partially_ejected":e.status!=="partially_ejected"&&(e.status="none");for(let t of this.activeSegments.values())if(t.segment===e){this.activeSegments.delete(t);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(let[r,s]of this.initData.entries()){let n=s instanceof Promise;t||=n,s===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let i=this.representations.get(e);i&&(this.initLoadIdleCallback=pr(()=>(0,$T.default)(this.loadInit(i,"low",!1),()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",i=!1){let r=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!i&&this.failedDownloads>0?Xt(this.destroyAbortController.signal,async function*(){let u=sd(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(o=>setTimeout(o,u))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,yt(e.mime),r)).then(u=>{if(!u)return;let{init:o,dataView:l,segments:c}=u,p=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,p);let d=c;this.isLive&&je(e.segmentReference)&&(d=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,d),o&&this.parsedInitData.set(e.id,o)}).then(()=>this.failedDownloads=0,u=>{this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:Pi.WTF,message:"loadInit threw",thrown:u})});return this.initData.set(e.id,n),n}async dropBuffer(){for(let e of this.segments.values())for(let t of e)t.status="none";await this.pruneBuffer(0,1/0,!0)}async pruneBuffer(e,t,i=!1){if(!this.sourceBuffer||!V(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||ye(e))return!1;this.checkEjectedSegments();let r=[],s=0,n=u=>{if(s>=t)return;r.push({...u.time});let o=rd(u)?u.size??0:u.byte.to-u.byte.from;s+=o};for(let u of this.segments.values())for(let o of u){let l=o.time.to<=e-this.tuning.dash.bufferPruningSafeZone,c=o.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(l||c)&&o.status==="fed"&&n(o)}for(let u=0;u<this.sourceBuffer.buffered.length;u++){let o=this.sourceBuffer.buffered.start(u)*1e3,l=this.sourceBuffer.buffered.end(u)*1e3,c=0;for(let p of this.segments.values())for(let d of p)(0,wo.default)(["none","partially_ejected"],d.status)&&Math.round(d.time.from)<=Math.round(o)&&Math.round(d.time.to)>=Math.round(l)&&c++;if(c===this.segments.size){let p={time:{from:o,to:l},url:"",status:"none"};n(p)}}if(r.length&&i){let u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let o of this.segments.values())for(let l of o)l.time.from>=e+u&&l.status==="fed"&&n(l)}return r.length?(r=RT(r),(await Promise.all(r.map(o=>this.sourceBufferTaskQueue.remove(o.from,o.to)))).reduce((o,l)=>o||l,!1)):!1}async abortBuffer(){if(!this.sourceBuffer||!V(this.mediaSource,this.sourceBuffer))return!1;let e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;return this.sourceBufferTaskQueue.abort(t)}getDebugBufferState(){if(!(!this.sourceBuffer||!V(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}getBufferedTo(){return!this.sourceBuffer||!V(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length?null:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}getForwardBufferDuration(e=this.getCurrentPosition()){return!this.sourceBuffer||!V(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||ye(e)?0:he(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!this.sourceBuffer||!V(this.mediaSource,this.sourceBuffer))return;let{buffered:i}=this.sourceBuffer;this.tuning.useRefactoredSearchGap&&(this.gaps=this.gaps.filter(s=>{if(s.persistent)return!0;let n=Math.round(s.from),u=Math.round(s.to);for(let o=0;o<i.length;o++)if(n>=Math.round(i.start(o)*1e3)&&u<=Math.round(i.end(o)*1e3))return!1;return!0}));let r={representation:e,from:t.time.from,to:t.time.to,persistent:!1};for(let s=0;s<i.length;s++){let n=i.start(s)*1e3,u=i.end(s)*1e3;if(!(u<=t.time.from||n>=t.time.to)){if(n<=t.time.from&&u>=t.time.to){r=void 0;break}u>t.time.from&&u<t.time.to&&(r.from=u),n<t.time.to&&n>t.time.from&&(r.to=n)}}r&&r.to-r.from>1&&!this.gaps.some(s=>r&&s.from===r.from&&s.to===r.to)&&this.gaps.push(r)}detectGapsWhenIdle(e,t){if(!(this.gapDetectionIdleCallback||!this.sourceBuffer||!V(this.mediaSource,this.sourceBuffer))){if(!this.tuning.useRefactoredSearchGap)for(let i=0;i<this.sourceBuffer.buffered.length;i++)this.gaps=this.gaps.filter(r=>r.persistent||this.sourceBuffer&&(Math.round(r.from)<Math.round(this.sourceBuffer.buffered.start(i)*1e3)||Math.round(r.to)>Math.round(this.sourceBuffer.buffered.end(i)*1e3)));this.gapDetectionIdleCallback=pr(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:Pi.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if(ye(this.sourceBuffer)||!V(this.mediaSource,this.sourceBuffer)||ye(this.playingRepresentationId)||this.sourceBufferBufferedDiff&&!this.sourceBufferBufferedDiff.wasUpdated())return;let e=Io(this.sourceBuffer.buffered),t=100;for(let i of this.segments.values())for(let r of i){let{status:s}=r;if(s!=="fed"&&s!=="partially_ejected")continue;let n=Math.floor(r.time.from),u=Math.ceil(r.time.to),o=!1,l=0;for(let c=0;c<e.length;c+=2){let p=e[c],d=e[c+1];o||(o=p-t<=n&&d+t>=u),(n>=p&&n<d-t||u>p+t&&u<=d)&&(l+=1)}o||(l===1?r.status="partially_ejected":this.gaps.some(c=>c.from===r.time.from||c.to===r.time.to)?r.status="partially_ejected":r.status="none")}}handleAsyncError(e,t){this.error$.next({id:t,category:Pi.VIDEO_PIPELINE,thrown:e,message:"Something went wrong"})}calculateDurationFromSegments(){if(!this.playingRepresentationId)return 0;let e=this.segments.get(this.playingRepresentationId);return(e?(0,Ri.default)(e,-1)?.time.to:0)||0}};import{abortable as ds,assertNever as MT,fromEvent as DT,merge as rB,now as ps,Subject as kr,ValueSubject as nd,flattenObject as Rr,ErrorCategory as hs,SubscriptionRemovable as aB}from"@vkontakte/videoplayer-shared";var ko=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:s=!1}){this.manifestRequested=new kr;this.manifestReceived=new kr;this.firstBytesRequested=new kr;this.firstBytesReceived=new kr;this.lastConnectionType$=new nd(void 0);this.lastConnectionReused$=new nd(void 0);this.lastRequestFirstBytes$=new nd(void 0);this.recoverableError$=new kr;this.error$=new kr;this.abortAllController=new X;this.subscription=new aB;this.fetchManifest=ds(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=zt(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=eo(i)),this.manifestRequested.next();let r=yield this.doFetch(i,{signal:this.abortAllController.signal}).catch(Po);return r?(t.log("success",Rr({url:i,message:"Request successfully executed"})),t.end(),this.manifestReceived.next(),this.onHeadersReceived(r.headers),r.text()):(t.error("error",Rr({url:i,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=ds(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:i,onProgress:r,priority:s="auto",signal:n,measureThroughput:u=!0,isLowLatency:o=!1,bufferOptimisation:l=!1}={}){let c=e,p=new Headers,d=this.tracer.createComponentTracer("Fetch");if(i)switch(t){case 0:{p.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let v=new URL(c,location.href);v.searchParams.append("bytes",`${i.from}-${i.to}`),c=v.toString();break}default:MT(t)}this.requestQuic&&(c=zt(c));let h=this.abortAllController.signal,f;if(n){let v=new X;if(f=rB(DT(this.abortAllController.signal,"abort"),DT(n,"abort")).subscribe(()=>{try{v.abort()}catch(E){Po(E)}}),this.subscription.add(f),this.abortAllController.signal.aborted||n.aborted)try{v.abort()}catch(E){Po(E)}h=v.signal}let b=0,S=ps();d.log("startRequest",Rr({url:c,priority:s,rangeMethod:t,range:i,isLowLatency:o,requestStartedAt:S})),this.firstBytesRequested.next();let g=yield this.doFetch(c,{priority:s,headers:p,signal:h}),I=ps();if(!g)return d.error("error",{message:"No response in request"}),d.end(),this.unsubscribeAbortSubscription(f),null;if(this.throughputEstimator?.addRawRtt(I-S),!g.ok||!g.body){this.unsubscribeAbortSubscription(f);let v=`Fetch error ${g.status}: ${g.statusText}`;return d.error("error",{message:v}),d.end(),Promise.reject(new Error(`Fetch error ${g.status}: ${g.statusText}`))}if(this.onHeadersReceived(g.headers),!r&&!u){this.unsubscribeAbortSubscription(f);let v=ps(),E={requestStartedAt:S,requestEndedAt:v,duration:v-S};return d.log("endRequest",Rr(E)),d.end(),g.arrayBuffer()}let x=g.body;if(u){let v;[x,v]=g.body.tee(),this.throughputEstimator?.trackStream(v,o)}let y=x.getReader(),w,D=parseInt(g.headers.get("content-length")??"",10);Number.isFinite(D)&&(w=D),!w&&i&&(w=i.to-i.from+1);let L=w?new Uint8Array(w):new Uint8Array(0),A=!1,R=v=>{this.unsubscribeAbortSubscription(f),A=!0,Po(v)},T=ds(h,async function*({done:v,value:E}){if(b===0&&(this.lastRequestFirstBytes$.next(ps()-S),this.firstBytesReceived.next()),h.aborted){this.unsubscribeAbortSubscription(f);return}if(!v&&E){if(l&&w)L.set(E,b),b+=E.byteLength;else{let z=new Uint8Array(L.length+E.length);z.set(L),z.set(E,L.length),L=z,b+=E.byteLength}r?.(new DataView(L.buffer),b),yield y?.read().then(T,R)}}.bind(this));yield y?.read().then(T,R),this.unsubscribeAbortSubscription(f);let q=ps(),$={failed:A,requestStartedAt:S,requestEndedAt:q,duration:q-S};return A?(d.error("endRequest",Rr($)),d.end(),null):(d.log("endRequest",Rr($)),d.end(),L.buffer)}.bind(this));this.fetchByteRangeRepresentation=ds(this.abortAllController.signal,async function*(e,t,i){if(e.type!=="byteRange")return null;let{from:r,to:s}=e.initRange,n=r,u=s,o=!1,l,c;e.indexRange&&(l=e.indexRange.from,c=e.indexRange.to,o=s+1===l,o&&(n=Math.min(l,r),u=Math.max(c,s))),n=Math.min(n,0);let p=yield this.fetch(e.url,{range:{from:n,to:u},priority:i,measureThroughput:!1});if(!p)return null;let d=new DataView(p,r-n,s-n+1);if(!t.validateData(d))throw new Error("Invalid media file");let h=t.parseInit(d),f=e.indexRange??t.getIndexRange(h);if(!f)throw new ReferenceError("No way to load representation index");let b;if(o)b=new DataView(p,f.from-n,f.to-f.from+1);else{let g=yield this.fetch(e.url,{range:f,priority:i,measureThroughput:!1});if(!g)return null;b=new DataView(g)}let S=t.parseSegments(b,h,f);return{init:h,dataView:new DataView(p),segments:S}}.bind(this));this.fetchTemplateRepresentation=ds(this.abortAllController.signal,async function*(e,t){if(e.type!=="template")return null;let i=new URL(e.initUrl,e.baseUrl).toString(),r=yield this.fetch(i,{priority:t,measureThroughput:!1});return r?{init:null,segments:e.segments.map(n=>({...n,status:"none",size:void 0})),dataView:new DataView(r)}:null}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=r,this.tracer=i.createComponentTracer("Fetcher"),this.useEnableSubtitlesParam=s}onHeadersReceived(e){let{type:t,reused:i}=Zn(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}async fetchRepresentation(e,t,i="auto"){let{type:r}=e;switch(r){case"byteRange":return await this.fetchByteRangeRepresentation(e,t,i)??null;case"template":return await this.fetchTemplateRepresentation(e,i)??null;default:MT(r)}}destroy(){this.abortAllController.abort(),this.tracer.end(),this.subscription.unsubscribe()}async doFetch(e,t){let i=await Xe(e,t);if(i.ok)return i;let r=await i.text(),s=parseInt(r);if(!isNaN(s))switch(s){case 1:this.recoverableError$.next({id:"VideoDataLinkExpiredError",message:"Video data links have expired",category:hs.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:hs.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:hs.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:hs.FATAL});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${s})`,category:hs.FATAL})}}unsubscribeAbortSubscription(e){e&&(e.unsubscribe(),this.subscription.remove(e))}},Po=a=>{if(!Tt(a))throw a};import{isNullable as sB,ValueSubject as nB}from"@vkontakte/videoplayer-shared";var fs=class a{constructor(e,t){this.currentRepresentation$=new nB(null);this.maxRepresentations=4;this.representationsCursor=0;this.representations=[];this.currentSegment=null;this.getCurrentPosition=t.getCurrentPosition,this.processStreams(e)}updateLive(e){this.processStreams(e?.streams.text)}seekLive(e){this.processStreams(e)}maintain(e=this.getCurrentPosition()){if(!sB(e))for(let t of this.representations)for(let i of t){let r=i.segmentReference,s=r.segments.length,n=r.segments[0].time.from,u=r.segments[s-1].time.to;if(e<n||e>u)continue;let o=r.segments.find(l=>l.time.from<=e&&l.time.to>=e);!o||this.currentSegment?.time.from===o.time.from&&this.currentSegment.time.to===o.time.to||(this.currentSegment=o,this.currentRepresentation$.next({...i,label:"Live Text",language:"ru",isAuto:!0,url:new URL(o.url,r.baseUrl).toString()}))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e??[]){let i=a.filterRepresentations(t.representations);if(i){this.representations[this.representationsCursor]=i,this.representationsCursor=(this.representationsCursor+1)%this.maxRepresentations;break}}}static isSupported(e){return!!e?.some(t=>a.filterRepresentations(t.representations))}static filterRepresentations(e){return e?.filter(t=>t.kind==="text"&&"segmentReference"in t&&je(t.segmentReference))}};var dB=["progress","play","seeked","stalled","waiting"],pB=["timeupdate","progress","loadeddata","playing","seeked"];var Lo=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.bufferManagers=[];this.subscription=new dd;this.representationSubscription=new dd;this.state$=new F("none");this.currentVideoRepresentation$=new te(void 0);this.currentVideoRepresentationInit$=new te(void 0);this.currentAudioRepresentation$=new te(void 0);this.currentVideoSegmentLength$=new te(0);this.currentAudioSegmentLength$=new te(0);this.error$=new Jt;this.manifestRequested=new Jt;this.manifestReceived=new Jt;this.firstBytesRequested=new Jt;this.firstBytesReceived=new Jt;this.lastConnectionType$=new te(void 0);this.lastConnectionReused$=new te(void 0);this.lastRequestFirstBytes$=new te(void 0);this.currentLiveTextRepresentation$=new te(null);this.isLive$=new te(!1);this.isActiveLive$=new te(!1);this.isLowLatency$=new te(!1);this.liveDuration$=new te(0);this.liveSeekableDuration$=new te(0);this.liveAvailabilityStartTime$=new te(0);this.liveStreamStatus$=new te(void 0);this.bufferLength$=new te(0);this.liveLatency$=new te(void 0);this.liveLoadBufferLength$=new te(0);this.livePositionFromPlayer$=new te(0);this.currentStallDuration$=new te(0);this.videoLastDataObtainedTimestamp$=new te(0);this.fetcherRecoverableError$=new Jt;this.fetcherError$=new Jt;this.liveStreamEndTimestamp=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.forceEnded$=new Jt;this.gapWatchdogActive=!1;this.destroyController=new X;this.initManifest=ud(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=se(t,i,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),this.manifest?.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:ut.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=ud(this.destroyController.signal,async function*(){this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(o=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:ut.NETWORK,message:"Failed to load manifest",thrown:o})});if(!e)return null;let t=null;try{t=Yn(e??"",this.manifestUrlString)}catch(o){let l=Gn(e)??{id:"ManifestParsing",category:ut.PARSER,message:"Failed to parse MPD manifest",thrown:o};this.error$.next(l)}if(!t)return null;let i=(o,l,c)=>!!(this.element?.canPlayType?.(l)&&Ue()?.isTypeSupported?.(`${l}; codecs="${c}"`)||o==="text");if(t.live){this.isLive$.next(!!t.live);let{availabilityStartTime:o,latestSegmentPublishTime:l,streamIsUnpublished:c,streamIsAlive:p}=t.live,d=(t.duration??0)/1e3;this.liveSeekableDuration$.next(-1*d),this.liveDuration$.next((l-o)/1e3),this.liveAvailabilityStartTime$.next(t.live.availabilityStartTime);let h="active";p||(h=c?"unpublished":"unexpectedly_down"),this.liveStreamStatus$.next(h)}let r={text:t.streams.text,video:[],audio:[]},s,n;for(let o of["video","audio"]){let c=t.streams[o].filter(({mime:d,codecs:h})=>i(o,d,h));r[o]=c;let p;if(this.tuning.dash.codecsPrioritizeEnabled){let d=c.map(({codecs:h})=>h);o==="audio"&&(n=po(d),p=n[0]),o==="video"&&(s=co(d),this.forceVideoCodec&&(0,_T.default)(s,this.forceVideoCodec)?p=this.forceVideoCodec:p=s[0]),p&&(r[o]=c.filter(({codecs:h})=>Ir(h)===p))}else{let d=new Set(c.map(({codecs:h})=>h));p=lo(d),p&&(r[o]=c.filter(({codecs:h})=>h.startsWith(p)))}if(o==="video"){let d=this.tuning.preferHDR,h=r.video.some(b=>b.hdr),f=r.video.some(b=>!b.hdr);B.display.isHDR&&d&&h?r.video=r.video.filter(b=>b.hdr):f&&(r.video=r.video.filter(b=>!b.hdr))}}let u={...t,streams:r};return this.tuning.dash.codecsPrioritizeEnabled&&(u.codecs={video:s,audio:n}),this.tracer.log("updateManifestEnd",bs(u)),u}.bind(this));this.initRepresentations=ud(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initRepresentationsStart",bs({initialVideo:e,initialAudio:t,sourceHls:i})),Lr(this.manifest),Lr(this.element),this.representationSubscription.unsubscribe(),this.representationSubscription=new dd,this.state$.startTransitionTo("representations_ready");let r=d=>{this.representationSubscription.add(It(d,"error").pipe(Ro(h=>!!this.element?.played.length)).subscribe(h=>{this.error$.next({id:"VideoSource",category:ut.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:h})}))};this.source=In();let s=document.createElement("source");if(r(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),tr())if(i){let d=document.createElement("source");r(d),d.type="application/x-mpegurl",d.src=i.url,this.element.appendChild(d)}else this.element.disableRemotePlayback=!0;this.isActiveLive$.next(this.isLive$.getValue());let n={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),manifest:this.manifest},u=this.manifest.streams.video.reduce((d,h)=>[...d,...h.representations],[]);if(this.videoBufferManager=new cs("video",this.source,u,n),this.bufferManagers=[this.videoBufferManager],gs(t)){let d=this.manifest.streams.audio.reduce((h,f)=>[...h,...f.representations],[]);this.audioBufferManager=new cs("audio",this.source,d,n),this.bufferManagers.push(this.audioBufferManager)}fs.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new fs(this.manifest.streams.text,n)),this.representationSubscription.add(this.fetcher.manifestRequested.subscribe(this.manifestRequested)),this.representationSubscription.add(this.fetcher.manifestReceived.subscribe(this.manifestReceived)),this.representationSubscription.add(this.fetcher.firstBytesRequested.subscribe(this.firstBytesRequested)),this.representationSubscription.add(this.fetcher.firstBytesReceived.subscribe(this.firstBytesReceived)),this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$));let o=()=>{this.stallWatchdogSubscription?.unsubscribe(),this.currentStallDuration$.next(0)};if(this.representationSubscription.add(Li(...pB.map(d=>It(this.element,d))).pipe(Mr(d=>this.element?he(this.element.buffered,this.element.currentTime*1e3):0),ms(),cB(d=>{d>this.tuning.dash.bufferEmptinessTolerance&&o()})).subscribe(this.bufferLength$)),this.representationSubscription.add(Li(It(this.element,"ended"),this.forceEnded$).subscribe(()=>{o()})),this.isLive$.getValue()){this.subscription.add(this.liveDuration$.pipe(ms()).subscribe(h=>this.liveStreamEndTimestamp=cd())),this.subscription.add(It(this.element,"pause").subscribe(()=>{this.livePauseWatchdogSubscription=ld(1e3).subscribe(h=>{let f=Ut(this.manifestUrlString,2);this.manifestUrlString=se(this.manifestUrlString,f+1e3,2),this.liveStreamStatus$.getValue()==="active"&&this.updateManifest()}),this.subscription.add(this.livePauseWatchdogSubscription)})).add(It(this.element,"play").subscribe(h=>this.livePauseWatchdogSubscription?.unsubscribe())),this.representationSubscription.add($r({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(Mr(({isActiveLive:h,isLowLatency:f})=>h&&f),ms()).subscribe(h=>{this.isManualDecreasePlaybackInLive()||Tr(this.element,1)})),this.representationSubscription.add($r({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(Ro(({bufferLength:h,isActiveLive:f,isLowLatency:b})=>f&&b&&!!h)).subscribe(({bufferLength:h})=>this.liveBuffer.next(h))),this.representationSubscription.add(this.videoBufferManager.currentLowLatencySegmentLength$.subscribe(h=>{if(!this.isActiveLive$.getValue()&&!this.isLowLatency$.getValue()&&!h)return;let f=this.liveSeekableDuration$.getValue()-h/1e3;this.liveSeekableDuration$.next(Math.max(f,-1*this.tuning.dashCmafLive.maxLiveDuration)),this.liveDuration$.next(this.liveDuration$.getValue()+h/1e3)})),this.representationSubscription.add($r({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe(Ro(({isLive:h})=>h),ms((h,f)=>f.bufferLength<h.bufferLength),Mr(({rtt:h,bufferLength:f,segmentServerLatency:b})=>{let S=Ut(this.manifestUrlString,2);return(h/2+f+b+S)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add($r({liveBuffer:this.liveBuffer.smoothed$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).subscribe(({liveBuffer:h,isActiveLive:f,isLowLatency:b})=>{if(!b||!f)return;let S=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,g=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,I=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,x=h-S;if(this.isManualDecreasePlaybackInLive())return;let y=1;Math.abs(x)>g&&(y=1+Math.sign(x)*I),Tr(this.element,y)})),this.representationSubscription.add(this.bufferLength$.subscribe(h=>{let f=0;if(h){let b=(this.element?.currentTime??0)*1e3;f=Math.min(...this.bufferManagers.map(g=>g.getLiveSegmentsToLoadState(this.manifest)?.to??b))-b}this.liveLoadBufferLength$.getValue()!==f&&this.liveLoadBufferLength$.next(f)}));let d=0;this.representationSubscription.add($r({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(VT(1e3)).subscribe(async({liveLoadBufferLength:h,bufferLength:f})=>{if(!this.element||this.isUpdatingLive)return;let b=this.element.playbackRate,S=Ut(this.manifestUrlString,2),g=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,I=Math.min(g,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*b),x=this.tuning.dashCmafLive.normalizedActualBufferOffset*b,y=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*b,w=isFinite(h)?h:f,D=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),L=g<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next(L);let A="none";if(D?A="active_low_latency":this.isLowLatency$.getValue()&&L?(this.bufferManagers.forEach(R=>R.proceedLowLatencyLive()),A="active_low_latency"):S!==0&&w<I?A="live_forward_buffering":w<I+y&&(A="live_with_target_offset"),isFinite(h)&&(d=h>d?h:d),A==="live_forward_buffering"||A==="live_with_target_offset"){let R=d-(I+x),T=this.normolizeLiveOffset(Math.trunc(S+R/b)),q=Math.abs(T-S),$=0;!h||q<=this.tuning.dashCmafLive.offsetCalculationError?$=S:T>0&&q>this.tuning.dashCmafLive.offsetCalculationError&&($=T),this.manifestUrlString=se(this.manifestUrlString,$,2)}(A==="live_with_target_offset"||A==="live_forward_buffering")&&(d=0,await this.updateLive())},h=>{this.error$.next({id:"updateLive",category:ut.VIDEO_PIPELINE,thrown:h,message:"Failed to update live with subscription"})}))}let l=Li(...this.bufferManagers.map(d=>d.fullyBuffered$)).pipe(Mr(()=>this.bufferManagers.every(d=>d.fullyBuffered$.getValue()))),c=Li(...this.bufferManagers.map(d=>d.onLastSegment$)).pipe(Mr(()=>this.bufferManagers.some(d=>d.onLastSegment$.getValue()))),p=$r({allBuffersFull:l,someBufferEnded:c}).pipe(ms(),Mr(({allBuffersFull:d,someBufferEnded:h})=>d&&h),Ro(d=>d));if(this.representationSubscription.add(Li(this.forceEnded$,p).subscribe(()=>{if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(d=>!d.updating))try{this.source?.endOfStream()}catch(d){this.error$.next({id:"EndOfStream",category:ut.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:d})}})),this.representationSubscription.add(Li(...this.bufferManagers.map(d=>d.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.representationSubscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&(this.representationSubscription.add(this.audioBufferManager.playingRepresentation$.subscribe(this.currentAudioRepresentation$)),this.representationSubscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$))),this.liveTextManager&&this.representationSubscription.add(this.liveTextManager.currentRepresentation$.subscribe(this.currentLiveTextRepresentation$)),this.source.readyState!=="open"){let d=this.tuning.dash.sourceOpenTimeout>=0;yield new Promise(h=>{d&&(this.timeoutSourceOpenId=setTimeout(()=>{if(this.source?.readyState==="open"){h();return}this.error$.next({id:"OpenOfStream",category:ut.VIDEO_PIPELINE,message:"Failed to open MediaSource",thrown:new Error("Timeout reject when wait sourceopen event"),traceAsLog:!0})},this.tuning.dash.sourceOpenTimeout)),this.source?.addEventListener("sourceopen",()=>{this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),h()},{once:!0})})}if(!this.isLive$.getValue()){let d=[this.manifest.duration??0,...(0,pd.default)((0,pd.default)([...this.manifest.streams.audio,...this.manifest.streams.video],h=>h.representations),h=>{let f=[];return h.duration&&f.push(h.duration),je(h.segmentReference)&&h.segmentReference.totalSegmentsDurationMs&&f.push(h.segmentReference.totalSegmentsDurationMs),f})];this.source.duration=Math.max(...d)/1e3}this.audioBufferManager&&gs(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState("representations_ready"),this.tracer.log("initRepresentationsEnd")}.bind(this));this.tick=()=>{if(!this.element||!this.videoBufferManager||this.source?.readyState!=="open")return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),this.audioBufferManager?.maintain(e),this.liveTextManager?.maintain(e),(this.videoBufferManager.gaps.length||this.audioBufferManager?.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=ld(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),t=>{this.error$.next({id:"GapWatchdog",category:ut.WTF,message:"Error handling gaps",thrown:t})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name),this.forceVideoCodec=e.forceVideoCodec,this.fetcher=new ko({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer,useEnableSubtitlesParam:e.tuning.useEnableSubtitlesParam}),this.subscription.add(this.fetcher.recoverableError$.subscribe(this.fetcherRecoverableError$)),this.subscription.add(this.fetcher.error$.subscribe(this.fetcherError$)),this.liveBuffer=Mt.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.bufferEstimator}),this.initTracerSubscription()}async seekLive(e){Lr(this.element);let t=this.liveStreamStatus$.getValue()!=="active"?cd()-this.liveStreamEndTimestamp:0,i=this.normolizeLiveOffset(e+t);this.isActiveLive$.next(i===0),this.manifestUrlString=se(this.manifestUrlString,i,2),this.manifest=await this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,await this.videoBufferManager?.seekLive(this.manifest.streams.video),await this.audioBufferManager?.seekLive(this.manifest.streams.audio),this.liveTextManager?.seekLive(this.manifest.streams.text))}initBuffer(){Lr(this.element),this.state$.setState("running");let e=It(this.element,"timeupdate");this.tuning.dash.timeupdateEventTickThrottle&&(e=e.pipe(VT(this.tuning.dash.timeupdateEventTickThrottle))),this.subscription.add(Li(...dB.map(t=>It(this.element,t)),It(window,"online"),e).subscribe(()=>this.tick(),t=>{this.error$.next({id:"DashVKPlayer",category:ut.WTF,message:"Internal logic error",thrown:t})})),this.subscription.add(It(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===HTMLMediaElement.HAVE_CURRENT_DATA&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(It(this.element,"waiting").subscribe(()=>{this.element&&this.element.readyState===HTMLMediaElement.HAVE_CURRENT_DATA&&!this.element.seeking&&Se(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let t=()=>{if(!this.element||this.source?.readyState!=="open")return;let i=this.currentStallDuration$.getValue();i+=50,this.currentStallDuration$.next(i);let r={timeInWaiting:i},s=cd(),n=100,u=this.videoBufferManager?.lastDataObtainedTimestamp??0;this.videoLastDataObtainedTimestamp$.next(u);let o=this.audioBufferManager?.lastDataObtainedTimestamp??0,l=this.videoBufferManager?.getForwardBufferDuration()??0,c=this.audioBufferManager?.getForwardBufferDuration()??0,p=l<n&&s-u>this.tuning.dash.crashOnStallTWithoutDataTimeout,d=this.audioBufferManager&&c<n&&s-o>this.tuning.dash.crashOnStallTWithoutDataTimeout;if((p||d)&&i>this.tuning.dash.crashOnStallTWithoutDataTimeout||i>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${i} ms`);if(this.isLive$.getValue()&&i%2e3===0){let h=this.normolizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);this.seekLive(h).catch(f=>{this.error$.next({id:"stallIntervalCallback",category:ut.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:f})}),r.liveLastOffset=h}else{let h=this.element.currentTime*1e3;this.videoBufferManager?.maintain(h),this.audioBufferManager?.maintain(h),r.position=h}this.tracer.log("stallIntervalCallback",bs(r))};this.stallWatchdogSubscription?.unsubscribe(),this.stallWatchdogSubscription=ld(50).subscribe(t,i=>{this.error$.next({id:"StallWatchdogCallback",category:ut.NETWORK,message:"Can't restore DASH after stall.",thrown:i})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t,i=!1){let r={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return this.tuning.useNewSwitchTo?this.currentStallDuration$.getValue()>0?r?.switchToWithPreviousAbort(t,i):r?.switchTo(t,i):r?.switchToOld(t,i)}async seek(e,t){Lr(this.element),Lr(this.videoBufferManager);let i;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?i=e:i=Math.max(this.videoBufferManager.findSegmentStartTime(e)??e,this.audioBufferManager?.findSegmentStartTime(e)??e),this.warmUpMediaSourceIfNeeded(i),Se(this.element.buffered,i)||await Promise.all([this.videoBufferManager.abort(),this.audioBufferManager?.abort()]),!(BT(this.element)||BT(this.videoBufferManager))&&(this.videoBufferManager.maintain(i),this.audioBufferManager?.maintain(i),this.element.currentTime=i/1e3,this.tracer.log("seek",bs({requestedPosition:e,forcePrecise:t,position:i})))}warmUpMediaSourceIfNeeded(e=this.element?.currentTime){gs(this.element)&&gs(this.source)&&gs(e)&&this.source?.readyState==="ended"&&this.element.duration*1e3-e>this.tuning.dash.seekBiasInTheEnd&&this.bufferManagers.forEach(t=>t.warmUpMediaSource())}get isStreamEnded(){return this.source?.readyState==="ended"}stop(){this.tracer.log("stop"),this.element?.querySelectorAll("source").forEach(e=>{URL.revokeObjectURL(e.src),e.remove()}),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),this.videoBufferManager?.destroy(),this.videoBufferManager=null,this.audioBufferManager?.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getStreams(){return this.manifest?.streams}getCodecs(){return this.manifest?.codecs}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),this.source?.readyState==="open"&&Array.from(this.source.sourceBuffers).every(e=>!e.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}initTracerSubscription(){let e=lB(this.tracer.error.bind(this.tracer));this.subscription.add(this.error$.subscribe(e("error")))}isManualDecreasePlaybackInLive(){return!this.element||!this.isLive$.getValue()?!1:1-this.element.playbackRate>this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}async updateLive(){this.isUpdatingLive=!0,this.manifest=await this.updateManifest(),this.manifest&&(this.bufferManagers.forEach(e=>e.updateLive(this.manifest)),this.liveTextManager?.updateLive(this.manifest)),this.isUpdatingLive=!1}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.getBufferedTo();if(e===null)return;let t=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),i=this.isJumpGapAfterSeekLive,r=this.element.currentTime;this.isJumpGapAfterSeekLive&&!t&&this.element.currentTime>e&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let s=this.element.currentTime*1e3,n=null,u=this.element.readyState===HTMLMediaElement.HAVE_METADATA?this.tuning.endGapTolerance:0;for(let o of this.bufferManagers)for(let l of o.gaps)(l.persistent||o.playingRepresentation$.getValue()===l.representation)&&l.from-u<=s&&l.to+u>s&&(this.element.duration*1e3-l.to<this.tuning.endGapTolerance?n=1/0:(n===null||l.to>n)&&(n=l.to));if(n!==null){let o=n+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,o===1/0?this.forceEnded$.next():(this.element.currentTime=o/1e3,this.tracer.log("jumpGap",bs({isJumpGapAfterSeekLive:i,isActiveLowLatency:t,initialCurrentTime:r,jumpTo:o,resultCurrentTime:this.element.currentTime})))}}calculateDurationFromSegments(){return Math.max(this.videoBufferManager?.calculateDurationFromSegments()||0,this.audioBufferManager?.calculateDurationFromSegments()||0)}};import{combine as hB,map as fB,observeElementSize as mB,Subscription as bB,ValueSubject as hd,noop as gB}from"@vkontakte/videoplayer-shared";var $o=class{constructor(){this.subscription=new bB;this.pipSize$=new hd(void 0);this.videoSize$=new hd(void 0);this.elementSize$=new hd(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(mB(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(fB(({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 xB;this.videoState=new F("stopped");this.observableVideo=null;this.droppedFramesManager=new cr;this.stallsManager=new So;this.elementSizeManager=new $o;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new Qt;this.audioTrackSwitchHistory=new Qt;this.selectedRepresentations={audio:null,video:null};this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(r.state==="requested"&&i?.to!=="paused"&&e!=="stopped"&&t!=="stopped"&&this.seek(r.position,r.forcePrecise),t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.player.stop(),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),P(this.params.desiredState.playbackState,"stopped",!0));return}switch(e){case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();return;case"ready":t==="paused"?(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="ready"&&P(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):t==="playing"&&this.video.paused?this.playIfAllowed():i?.to==="playing"&&P(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&P(this.params.desiredState.playbackState,"paused");return;default:return vB(e)}}};this.init3DScene=e=>{if(this.scene3D)return;this.scene3D=new Ar(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:e.projectionData?.pose.yaw||0,y:e.projectionData?.pose.pitch||0,z:e.projectionData?.pose.roll||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});let t=this.elementSizeManager.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};this.textTracksManager=new Ye(e.source.url),this.params=e,this.video=$e(e.container,e.tuning),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(ge(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.player=new Lo({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode,tracer:this.tracer,forceVideoCodec:this.params.forceVideoCodec}),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params;EB(this.observableVideo)&&(this.observableVideo=Ce(this.video),this.subscription.add(()=>this.observableVideo?.destroy()));let i=this.constructor.name,r=n=>{e.error$.next({id:i,category:OT.WTF,message:`${i} internal logic error`,thrown:n})},s=(n,u)=>this.subscription.add(n.subscribe(u,r));return{output:e,desiredState:t,observableVideo:this.observableVideo,genericErrorListener:r,connect:s}}subscribe(){let{output:e,desiredState:t,observableVideo:i,genericErrorListener:r,connect:s}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe(fd(p=>!!p.length),NT()).subscribe(p=>{this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks:p})}));let n=this.params.desiredState.seekState.stateChangeEnded$.pipe(md(p=>p.to.state!=="none"),Mo());this.stallsManager.init({isSeeked$:n,currentStallDuration$:this.player.currentStallDuration$,videoLastDataObtainedTimestamp$:this.player.videoLastDataObtainedTimestamp$,throughput$:this.params.dependencies.throughputEstimator.throughput$,rtt$:this.params.dependencies.throughputEstimator.rtt$,tuning:this.params.tuning.stallsManager,abrParams:this.params.tuning.autoTrackSelection,isBuffering$:i.isBuffering$,looped$:i.looped$,playing$:i.playing$}),s(i.ended$,e.endedEvent$),s(i.looped$,e.loopedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(i.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),s(i.loadedMetadata$,e.loadedMetadataEvent$),s(this.player.error$,e.error$),s(this.player.fetcherRecoverableError$,e.fetcherRecoverableError$),s(this.player.fetcherError$,e.fetcherError$),s(this.player.lastConnectionType$,e.httpConnectionType$),s(this.player.lastConnectionReused$,e.httpConnectionReused$),s(this.player.isLive$,e.isLive$),s(this.player.lastRequestFirstBytes$.pipe(fd(FT),NT()),e.firstBytesEvent$),s(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),s(this.videoState.stateChangeEnded$.pipe(md(p=>p.to)),this.params.output.playbackState$),this.subscription.add(i.looped$.subscribe(()=>this.player.warmUpMediaSourceIfNeeded(),r)),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(mt(this.video,t.isLooped,r)),this.subscription.add(De(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(ze(this.video,t.playbackRate,i.playbackRateState$,r)),this.elementSizeManager.connect({video:this.video,observableVideo:i}),s(Ke(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),P(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),P(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.params.tuning.changePlaybackStateToPausedWhenEnded&&this.subscription.add(i.ended$.subscribe(()=>{this.videoState.setState("paused"),P(t.playbackState,"paused")})),this.subscription.add(this.player.manifestRequested.subscribe(this.params.output.manifestRequested$)).add(this.player.manifestReceived.subscribe(this.params.output.manifestReceived$)).add(this.player.firstBytesRequested.subscribe(this.params.output.firstBytesRequested$)).add(this.player.firstBytesReceived.subscribe(this.params.output.firstBytesReceived$)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:p})=>{if(p==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let d=this.player.getStreams(),h=this.player.getCodecs();if(yB(d,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let b=[];for(let S of d.audio){b.push(td(S));let g=[];for(let I of S.representations){let x=AT(I);g.push(x),this.audioTracksMap.set(x,{stream:S,representation:I})}this.audioStreamsMap.set(S,g)}this.params.output.availableAudioStreams$.next(b)}let f=[];for(let b of d.video){f.push(id(b));let S=[];for(let g of b.representations){let I=wT({...g,streamId:b.id});I&&(S.push(I),this.videoTracksMap.set(I,{stream:b,representation:g}))}this.videoStreamsMap.set(b,S)}this.params.output.availableVideoStreams$.next(f);for(let b of d.text)for(let S of b.representations){let g=PT(b,S);this.textTracksMap.set(g,{stream:b,representation:S})}this.params.output.availableVideoTracks$.next(Array.from(this.videoTracksMap.keys())),this.params.output.availableAudioTracks$.next(Array.from(this.audioTracksMap.keys())),this.params.output.isAudioAvailable$.next(!!this.audioTracksMap.size),h?.video&&this.params.output.availableVideoCodecs$.next(h.video),h?.audio&&this.params.output.availableAudioCodecs$.next(h.audio),this.audioTracksMap.size&&this.textTracksMap.size&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else p==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},r));let{vktvAbrThrottle:u}=this.params.tuning.dash,o=u&<(u)||null;this.subscription.add(Do(this.player.currentStallDuration$,this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,this.elementSizeManager.getObservable(),this.params.output.elementVisible$,this.droppedFramesManager.onDroopedVideoFramesLimit$,IB(this.video,"progress")).pipe(fd(()=>this.videoTracksMap.size>0)).subscribe(async()=>{let p=this.player.state$.getState(),d=this.player.state$.getTransition();if(p!=="manifest_ready"&&p!=="running"||d||p==="running"&&o&&!o())return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState()),this.selectVideoAudioRepresentations();let{video:h,audio:f}=this.selectedRepresentations;if(!h)return;let b=Ai(this.videoTracksMap.keys(),g=>this.videoTracksMap.get(g)?.representation.id===h.id);FT(b)&&(this.stallsManager.lastVideoTrackSelected=b);let S=this.params.desiredState.autoVideoTrackLimits.getTransition();if(S&&this.params.output.autoVideoTrackLimits$.next(S.to),p==="manifest_ready")await this.player.initRepresentations(h.id,f?.id,this.params.sourceHls);else if(await this.player.switchRepresentation("video",h.id),f){let g=!!t.audioStream.getTransition();await this.player.switchRepresentation("audio",f.id,g)}},r)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:p})=>{this.scene3D&&p&&this.scene3D.pointCameraTo(p.x,p.y)})),this.subscription.add(this.elementSizeManager.subscribe(p=>{this.scene3D&&p&&this.scene3D.setViewportSize(p.width,p.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(Mo()).subscribe(p=>{let d=Ai(this.videoTracksMap.entries(),([,{representation:g}])=>g.id===p);if(!d){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[h,{stream:f}]=d,b=this.params.desiredState.videoStream.getTransition();b&&b.to&&b.to.id===f.id&&this.params.desiredState.videoStream.setState(b.to),e.currentVideoTrack$.next(h),e.currentVideoStream$.next(id(f));let S=this.player.calculateDurationFromSegments();S&&this.params.output.duration$.next(S/1e3)},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(Mo()).subscribe(p=>{let d=Ai(this.audioTracksMap.entries(),([,{representation:S}])=>S.id===p);if(!d){e.currentAudioStream$.next(void 0);return}let[h,{stream:f}]=d,b=this.params.desiredState.audioStream.getTransition();b&&b.to&&b.to.id===f.id&&this.params.desiredState.audioStream.setState(b.to),e.currentAudioStream$.next(td(f))},r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(p=>{if(p?.is3dVideo&&this.params.tuning.spherical?.enabled)try{this.init3DScene(p),e.is3DVideo$.next(!0)}catch(d){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${d}`})}else this.destroy3DScene(),this.params.tuning.spherical?.enabled&&e.is3DVideo$.next(!1)},r)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,r)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,r)),this.textTracksManager.connect(this.video,t,e);let l=t.playbackState.stateChangeStarted$.pipe(md(({to:p})=>p==="ready"),Mo());this.subscription.add(Do(l,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,bd(["init"])).subscribe(()=>{let p=t.autoVideoTrackSwitching.getState(),h=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:p?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(h)})),this.subscription.add(Do(l,this.player.state$.stateChangeEnded$,bd(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let c=Do(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,bd(["init"])).pipe(TB(0));this.subscription.add(c.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?ba:ma,t=this.params.tuning.useNewAutoSelectVideoTrack?Nn:Fn,i=this.params.tuning.useNewAutoSelectVideoTrack?St:On,{desiredState:r,output:s}=this.params,n=r.autoVideoTrackSwitching.getState(),u=r.videoTrack.getState()?.id,o=Ai(this.videoTracksMap.keys(),A=>A.id===u),l=s.currentVideoTrack$.getValue(),c=r.videoStream.getState()??(o&&this.videoTracksMap.get(o)?.stream)??this.videoStreamsMap.size===1?this.videoStreamsMap.keys().next().value:void 0;if(!c)return;let p=Ai(this.videoStreamsMap.keys(),A=>A.id===c.id),d=p&&this.videoStreamsMap.get(p);if(!d)return;let h=he(this.video.buffered,this.video.currentTime*1e3),f;this.player.isActiveLive$.getValue()?f=this.player.isLowLatency$.getValue()?this.params.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.params.tuning.dashCmafLive.normalizedLiveMinBufferSize:this.player.isLive$.getValue()?f=this.params.tuning.dashCmafLive.normalizedTargetMinBufferSize:f=n?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;let b=(this.video.duration*1e3||1/0)-this.video.currentTime*1e3,S=Math.min(h/Math.min(f,b||1/0),1),g=r.audioStream.getState()??(this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0),I=g?.id&&Ai(this.audioStreamsMap.keys(),A=>A.id===g.id)||this.audioStreamsMap.keys().next().value,x=0;if(I){if(o&&!n){let A=e(o,d,this.audioStreamsMap.get(I)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);x=Math.max(x,A?.bitrate??-1/0)}if(l){let A=e(l,d,this.audioStreamsMap.get(I)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);x=Math.max(x,A?.bitrate??-1/0)}}let y=o;(n||!y)&&(y=i(d,{container:this.elementSizeManager.getValue(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.stallsManager.abrTuningParams,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:x,forwardBufferHealth:S,current:l,visible:this.params.output.elementVisible$.getValue(),history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,stallsVideoMaxQualityLimit:this.stallsManager.videoMaxQualityLimit,stallsPredictedThroughput:this.stallsManager.predictedThroughput,abrLogger:this.params.dependencies.abrLogger}));let w=I&&t(y,d,this.audioStreamsMap.get(I)??[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.stallsManager.abrTuningParams,forwardBufferHealth:S,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),D=this.videoTracksMap.get(y)?.representation,L=w&&this.audioTracksMap.get(w)?.representation;D&&L?(this.selectedRepresentations.video=D,this.selectedRepresentations.audio=L):D&&!L&&this.audioTracksMap.size===0&&(this.selectedRepresentations.video=D,this.selectedRepresentations.audio=null)}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){Be(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:OT.DOM,thrown:e}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.stallsManager.destroy(),this.elementSizeManager.destroy(),this.destroy3DScene(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),this.params.output.currentVideoStream$.next(void 0),Me(this.video),this.tracer.end()}};var Ss=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 gd,merge as qT,filter as UT,filterChanged as HT,isNullable as Sd,map as jT,ValueSubject as vd,isNonNullable as wB}from"@vkontakte/videoplayer-shared";var vs=class extends $i{constructor(e){super(e),this.textTracksManager.destroy()}subscribe(){super.subscribe();let e=!1,t=-1,{output:i,observableVideo:r,desiredState:s,connect:n}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canPlayLiveTailBuffer$.next(!0),n(r.timeUpdate$,i.liveBufferTime$),n(this.player.liveSeekableDuration$,i.duration$),n(this.player.liveLatency$,i.liveLatency$);let u=new vd(1);n(r.playbackRateState$,u),this.params.tuning.dashCmafLive.catchupLiveForMutedInactiveTab&&this.subscription.add(i.elementVisible$.pipe(HT()).subscribe(o=>{let l=i.position$.getValue(),c=i.volume$.getValue(),p=!c.volume||c.muted;!o&&!l&&p?e=!0:o&&e&&(this.seek(0),e=!1)})),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(s.isLowLatency.stateChangeEnded$.pipe(jT(o=>o.to)).subscribe(this.player.isLowLatency$)).add(gd({liveBufferTime:i.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(jT(({liveBufferTime:o,liveAvailabilityStartTime:l})=>o&&l?o+l:void 0)).subscribe(i.liveTime$)).add(this.player.liveStreamStatus$.pipe(UT(o=>wB(o))).subscribe(o=>i.isLiveEnded$.next(o!=="active"&&i.position$.getValue()===0))).add(gd({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:qT(r.playbackRateState$,new vd(1))}).pipe(UT(({liveStreamStatus:o,liveDuration:l})=>o==="active"&&!!l)).subscribe(({liveDuration:o,playbackRate:l})=>{let c=i.liveBufferTime$.getValue(),p=i.position$.getValue(),{playbackCatchupSpeedup:d}=this.params.tuning.dashCmafLive.lowLatency;p||l<1-d||this.video.paused||Sd(c)||(t=o-c)})).add(gd({time:i.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:qT(r.playbackRateState$,new vd(1))}).pipe(HT((o,l)=>this.player.liveStreamStatus$.getValue()==="active"?o.liveDuration===l.liveDuration:o.time===l.time)).subscribe(({time:o,liveDuration:l,playbackRate:c})=>{let p=i.position$.getValue(),{playbackCatchupSpeedup:d}=this.params.tuning.dashCmafLive.lowLatency;if(!p&&!this.video.paused&&c>=1-d||Sd(o)||Sd(l))return;let h=-1*(l-o-t);i.position$.next(Math.min(h,0))})).add(this.player.currentLiveTextRepresentation$.subscribe(o=>{if(o){let l=kT(o);this.params.output.availableTextTracks$.next([l])}}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,i=Math.trunc(t/1e3<=Math.abs(this.params.output.duration$.getValue())?t:0);this.player.seekLive(i).then(()=>{this.params.output.position$.next(e/1e3)})}};var QT="X-Playback-Duration",yd=async a=>{let e=await Xe(a),t=await e.text(),i=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t)?.[1];return i?parseInt(i,10):e.headers.has(QT)?parseInt(e.headers.get(QT),10):void 0};import{assertNever as VB,combine as _B,debounce as OB,ErrorCategory as Vo,filter as FB,filterChanged as NB,isNonNullable as zT,isNullable as _o,map as YT,merge as qB,observableFrom as UB,Subscription as HB,ValueSubject as Ed,VideoQuality as jB}from"@vkontakte/videoplayer-shared";var Id=C(il(),1);import{videoSizeToQuality as AB,getExponentialDelay as PB}from"@vkontakte/videoplayer-shared";var kB=a=>{let e=null;if(a.QUALITY&&(e=jt(a.QUALITY)),!e&&a.RESOLUTION){let[t,i]=a.RESOLUTION.split("x").map(r=>parseInt(r,10));e=AB({width:t,height:i})}return e??null},RB=(a,e)=>{let t=a.split(`
|
|
179
|
-
`),i=[],r=[];for(let s=0;s<t.length;s++){let n=t[s],u=n.match(/^#EXT-X-STREAM-INF:(.+)/),o=n.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!u&&!o)){if(u){let l=(0,
|
|
180
|
-
`),s=0;for(let n=0;n<r.length;++n){let u=r[n];switch(!0){case u.startsWith("#EXTINF:"):{let o=r[++n],l=new URL(o,t).toString(),c=Number(this.extractPlaylistRowValue("#EXTINF:",u))*1e3;if(i.segments.push({time:{from:s,to:s+c},url:l}),s=s+c,!i.segmentStartTime){let p=new Date(i.vkStartTime).valueOf(),d=new Date(i.programDateTime).valueOf();i.segmentStartTime=d-p}break}case u.startsWith("#EXT-X-TARGETDURATION:"):i.targetDuration=Number(this.extractPlaylistRowValue("#EXT-X-TARGETDURATION:",u));break;case u.startsWith("#EXT-X-MEDIA-SEQUENCE:"):i.mediaSequence=Number(this.extractPlaylistRowValue("#EXT-X-MEDIA-SEQUENCE:",u));break;case u.startsWith("#EXT-X-VK-PLAYBACK-DURATION:"):i.vkPlaybackDuration=Number(this.extractPlaylistRowValue("#EXT-X-VK-PLAYBACK-DURATION:",u));break;case u.startsWith("#EXT-X-PROGRAM-DATE-TIME:"):{let o=this.extractPlaylistRowValue("#EXT-X-PROGRAM-DATE-TIME:",u);i.programDateTime=o;let l=new Date(o);l.setMilliseconds(0),s=l.valueOf();break}case u.startsWith("#EXT-X-VK-START-TIME:"):i.vkStartTime=this.extractPlaylistRowValue("#EXT-X-VK-START-TIME:",u);break}}return i}extractPlaylistRowValue(e,t){switch(e){case"#EXTINF:":return t.substring(e.length,t.length-1);default:return t.substring(e.length)}}processLiveTime(e){if($B(e)&&this.currentTextTrackData){let{segments:t}=this.currentTextTrackData.playlist,{from:i}=t[0].time,{to:r}=t[t.length-1].time;if(e<i||e>r)return;r-e<this.params.downloadThreshold&&this.fetchNextManifestData();for(let n of t)if(n.time.from<=e&&n.time.to>=e){this.availableTextTracks$.next([{...this.currentTextTrackData.textTrack,url:n.url,isAuto:!0}]);break}}}async fetchNextManifestData(){try{if(this.abortControllers.nextManifest)return;this.abortControllers.nextManifest=new X;let{textTracks:e}=await this.fetchManifestData(),t=await this.parseTextTracks(e,this.params.sourceUrl);this.currentTextTrackData&&t&&(this.currentTextTrackData.playlist.segments=t.playlist.segments)}catch(e){this.error("fetchNextManifestData",e)}finally{this.abortControllers.nextManifest=null}}async fetchManifestData(){let e=this.prepareUrl??this.params.sourceUrl;return await this.params.fetchManifestData(e,{signal:this.abortControllers.destroy.signal})}error(e,t){this.error$.next({id:"[LiveTextManager][HLS_LIVE_CMAF]",category:BB.WTF,thrown:t,message:e})}};var ys=class{constructor(e){this.subscription=new HB;this.videoState=new F("stopped");this.textTracksManager=null;this.liveTextManager=null;this.manifests$=new Ed([]);this.liveOffset=new gi;this.manifestStartTime$=new Ed(void 0);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),u=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),P(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||n||u){let c=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(c),this.prepare(),u&&this.params.output.autoVideoTrackLimits$.next(u.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if(r?.to!=="paused"&&l.state==="requested"){this.videoState.startTransitionTo("ready"),this.seek(l.position&&l.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(t){case"ready":i==="ready"?P(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),P(this.params.desiredState.playbackState,"paused")):i==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":i==="paused"?(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.video.paused?this.videoState.setState("paused"):this.video.pause()):r?.to==="playing"&&P(this.params.desiredState.playbackState,"playing");return;case"paused":if(i==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let c=this.liveOffset.getTotalOffset();c>=this.maxSeekBackTime$.getValue()&&(c=0,this.liveOffset.resetTo(c)),this.liveOffset.resume(),this.params.output.position$.next(-c/1e3),this.prepare()}else r?.to==="paused"&&(P(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return VB(t)}};this.params=e,this.video=$e(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:jB.INVARIANT,url:this.params.source.url};let t=(i,r)=>Co(i,this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},r);this.params.tuning.useHlsLiveNewTextManager?this.liveTextManager=new Bo(this.params.output.liveTime$,this.video,t,this.params.source.url,this.params.tuning.hlsLiveNewTextManagerDownloadThreshold):this.textTracksManager=new Ye(e.source.url),t(this.generateLiveUrl()).then(({qualityManifests:i,textTracks:r})=>{i.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:Vo.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),this.liveTextManager?.processTextTracks(r,this.params.source.url),this.manifests$.next([this.masterManifest,...i])}).catch(i=>{this.params.output.error$.next({id:"ExtractHlsQualities",category:Vo.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:i})}),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(ge(this.params.source.url)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.maxSeekBackTime$=new Ed(e.source.maxSeekBackTime??1/0),this.subscribe()}selectManifest(){let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),r=t.getTransition(),s=r?.to?.id??t.getState()?.id??"master",n=this.manifests$.getValue();if(!n.length)return;let u=i?"master":s;return i&&!r&&t.startTransitionTo(this.masterManifest),n.find(o=>o.id===u)}subscribe(){let{output:e,desiredState:t}=this.params,i=u=>{e.error$.next({id:"HlsLiveProvider",category:Vo.WTF,message:"HlsLiveProvider internal logic error",thrown:u})},r=Ce(this.video);this.subscription.add(()=>r.destroy());let s=(u,o)=>this.subscription.add(u.subscribe(o,i));s(r.ended$,e.endedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentBuffer$),s(r.loadedMetadata$,e.firstBytesEvent$),s(r.loadedMetadata$,e.loadedMetadataEvent$),s(r.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(De(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(ze(this.video,t.playbackRate,r.playbackRateState$,i)),s(Ke(this.video),e.elementVisible$),this.liveTextManager?(s(this.liveTextManager.getCurrentTime$,this.params.output.getCurrentTime$),s(this.liveTextManager.error$,this.params.output.error$)):this.textTracksManager&&this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),P(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),P(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.liveTextManager&&this.subscription.add(this.liveTextManager.availableTextTracks$.subscribe(u=>{u&&this.params.output.availableTextTracks$.next(u)})),this.subscription.add(this.maxSeekBackTime$.pipe(NB(),YT(u=>-u/1e3)).subscribe(this.params.output.duration$,i)),this.subscription.add(r.loadedMetadata$.subscribe(()=>{let u=this.params.desiredState.seekState.getState(),o=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&zT(l.to)){let p=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let d=this.manifests$.getValue().find(h=>h.id===p);d&&(this.params.output.currentVideoTrack$.next(d),this.params.output.hostname$.next(ge(d.url)))}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),o&&o.from==="changing_manifest"&&this.videoState.setState(o.to),u&&u.state==="requested"&&this.seek(u.position)},i)),this.subscription.add(r.loadedData$.subscribe(()=>{let u=this.video?.getStartDate?.()?.getTime();this.manifestStartTime$.next(u||void 0)},i)),this.subscription.add(_B({startTime:this.manifestStartTime$.pipe(FB(zT)),currentTime:r.timeUpdate$}).subscribe(({startTime:u,currentTime:o})=>this.params.output.liveTime$.next(u+o*1e3),i)),this.subscription.add(this.manifests$.pipe(YT(u=>u.map(({id:o,quality:l,size:c,bandwidth:p,fps:d})=>({id:o,quality:l,size:c,fps:d,bitrate:p})))).subscribe(this.params.output.availableVideoTracks$,i));let n=qB(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,UB(["init"])).pipe(OB(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager?.destroy(),this.liveTextManager?.destroy(),this.params.output.element$.next(void 0),Me(this.video)}prepare(){let e=this.selectManifest();if(_o(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),r=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){let{max:u,min:o}=t?.to??i??{};for(let[l,c]of[[u,"mq"],[o,"lq"]]){let p=String(parseFloat(l||""));c&&l&&r.searchParams.set(c,p)}}let s=this.params.format==="HLS_LIVE_CMAF"?2:0,n=se(r.toString(),this.liveOffset.getTotalOffset(),s);this.liveTextManager?.prepare(n),this.video.setAttribute("src",n),this.video.load(),yd(n).then(u=>{if(!_o(u))this.maxSeekBackTime$.next(u);else{let o=this.params.source.maxSeekBackTime??this.maxSeekBackTime$.getValue();(_o(o)||!isFinite(o))&&Xe(n).then(l=>l.text()).then(l=>{let c=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(l)?.[1];if(c){let p=new URL(c,n).toString();yd(p).then(d=>{_o(d)||this.maxSeekBackTime$.next(d)})}}).catch(()=>{})}})}playIfAllowed(){Be(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),P(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Vo.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,i=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(i),this.params.output.position$.next(-i/1e3),this.params.output.seekedEvent$.next()}generateLiveUrl(){let e=se(this.params.source.url);if(this.params.tuning.useHlsLiveNewTextManager){let t=new URL(e);t.searchParams.set("enable-subtitles","yes"),e=t.toString()}return e}};import{assertNever as QB,debounce as WB,ErrorCategory as xd,fromEvent as wd,isNonNullable as GB,isNullable as zB,map as KT,merge as XT,observableFrom as JT,Subscription as YB,ValueSubject as KB,VideoQuality as XB}from"@vkontakte/videoplayer-shared";var Ts=class{constructor(e){this.subscription=new YB;this.videoState=new F("stopped");this.manifests$=new KB([]);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),u=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),P(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||n||u){let c=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(c);let{currentTime:p}=this.video;this.prepare(),u&&this.params.output.autoVideoTrackLimits$.next(u.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:p*1e3,forcePrecise:!0});return}switch(r?.to!=="paused"&&l.state==="requested"&&this.seek(l.position),t){case"ready":i==="ready"?P(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused")):i==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":i==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):r?.to==="playing"&&P(this.params.desiredState.playbackState,"playing");return;case"paused":i==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):r?.to==="paused"&&P(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return QB(t)}};this.textTracksManager=new Ye(e.source.url),this.params=e,this.video=$e(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:XB.INVARIANT,url:this.params.source.url},this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(ge(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.manifestRequested$.next(),Co(se(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:t,textTracks:i})=>{this.params.output.manifestReceived$.next(),this.manifests$.next([this.masterManifest,...t]),this.params.tuning.useNativeHLSTextTracks||this.params.desiredState.internalTextTracks.startTransitionTo(i)},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:xd.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),r=t.getTransition(),s=r?.to?.id??t.getState()?.id??"master",n=this.manifests$.getValue();if(!n.length)return;let u=i?"master":s;return i&&(!r||!r.from)&&t.startTransitionTo(this.masterManifest),n.find(o=>o.id===u)}subscribe(){let{output:e,desiredState:t}=this.params,i=u=>{e.error$.next({id:"HlsProvider",category:xd.WTF,message:"HlsProvider internal logic error",thrown:u})},r=Ce(this.video);this.subscription.add(()=>r.destroy());let s=(u,o)=>this.subscription.add(u.subscribe(o));if(s(r.timeUpdate$,e.position$),s(r.durationChange$,e.duration$),s(r.ended$,e.endedEvent$),s(r.looped$,e.loopedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentBuffer$),s(r.loadedMetadata$,e.firstBytesEvent$),s(r.loadedMetadata$,e.loadedMetadataEvent$),s(r.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.seeked$,e.seekedEvent$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe(KT(u=>u.to)),this.params.output.playbackState$),this.subscription.add(mt(this.video,t.isLooped,i)),this.subscription.add(De(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(ze(this.video,t.playbackRate,r.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),P(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),P(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i).add(r.loadedMetadata$.subscribe(()=>{let u=this.params.desiredState.seekState.getState(),o=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&GB(l.to)){let h=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let f=this.manifests$.getValue().find(b=>b.id===h);f&&(this.params.output.currentVideoTrack$.next(f),this.params.output.hostname$.next(ge(f.url)))}let p=this.params.desiredState.playbackRate.getState(),d=this.params.output.element$.getValue()?.playbackRate;if(p!==d){let h=this.params.output.element$.getValue();h&&(this.params.desiredState.playbackRate.setState(p),h.playbackRate=p)}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),o&&o.from==="changing_manifest"&&this.videoState.setState(o.to),u.state==="requested"&&this.seek(u.position)},i))),this.params.tuning.changePlaybackStateToPausedWhenEnded&&this.subscription.add(r.ended$.subscribe(()=>{this.videoState.setState("paused"),P(t.playbackState,"paused")})),this.subscription.add(this.manifests$.pipe(KT(u=>u.map(({id:o,quality:l,size:c,bandwidth:p,fps:d})=>({id:o,quality:l,size:c,fps:d,bitrate:p})))).subscribe(this.params.output.availableVideoTracks$,i)),!B.device.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:u}=this.video;this.subscription.add(XT(wd(u,"addtrack"),wd(u,"removetrack"),wd(u,"change"),JT(["init"])).subscribe(()=>{for(let o=0;o<u.length;o++)u[o].mode="hidden"},i))}let n=XT(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,JT(["init"])).pipe(WB(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),Me(this.video)}prepare(){let e=this.selectManifest();if(zB(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),r=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){let{max:s,min:n}=t?.to??i??{};for(let[u,o]of[[s,"mq"],[n,"lq"]]){let l=String(parseFloat(u||""));o&&u&&r.searchParams.set(o,l)}}this.video.setAttribute("src",r.toString()),this.video.load()}playIfAllowed(){Be(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:xd.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};var tI=C(Qi(),1),Ad=C(rr(),1),iI=C(at(),1);import{assertNever as JB,assertNonNullable as ZT,debounce as ZB,ErrorCategory as eI,isHigherOrEqual as e0,isLowerOrEqual as t0,isNonNullable as i0,merge as r0,observableFrom as a0,Subscription as s0,map as n0}from"@vkontakte/videoplayer-shared";var Is=class{constructor(e){this.subscription=new s0;this.videoState=new F("stopped");this.trackUrls={};this.textTracksManager=new Ye;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),P(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let s=this.params.desiredState.autoVideoTrackLimits.getTransition(),n=this.params.desiredState.videoTrack.getTransition(),u=this.params.desiredState.seekState.getState();if(s&&e!=="ready"&&!n){this.handleQualityLimitTransition(s.to);return}if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(n){let{currentTime:o}=this.video;this.prepare(),u.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:o*1e3,forcePrecise:!0});return}switch(i?.to!=="paused"&&u.state==="requested"&&this.seek(u.position),e){case"ready":t==="ready"?P(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):i?.to==="playing"&&P(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&P(this.params.desiredState.playbackState,"paused");return;default:return JB(e)}};this.params=e,this.video=$e(e.container,e.tuning),this.params.output.element$.next(this.video),(0,tI.default)(this.params.source).reverse().forEach(([t,i],r)=>{let s=r.toString(10);this.trackUrls[s]={track:{quality:t,id:s},url:i}}),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next((0,Ad.default)(this.trackUrls).map(({track:t})=>t)),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.desiredState.autoVideoTrackSwitching.setState(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.subscribe()}subscribe(){let{output:e,desiredState:t}=this.params,i=u=>{e.error$.next({id:"MpegProvider",category:eI.WTF,message:"MpegProvider internal logic error",thrown:u})},r=Ce(this.video);this.subscription.add(()=>r.destroy());let s=(u,o)=>this.subscription.add(u.subscribe(o,i));s(r.timeUpdate$,e.position$),s(r.durationChange$,e.duration$),s(r.ended$,e.endedEvent$),s(r.looped$,e.loopedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentBuffer$),s(r.loadedMetadata$,e.firstBytesEvent$),s(r.loadedMetadata$,e.loadedMetadataEvent$),s(r.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.seeked$,e.seekedEvent$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe(n0(u=>u.to)),this.params.output.playbackState$),this.subscription.add(mt(this.video,t.isLooped,i)),this.subscription.add(De(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(ze(this.video,t.playbackRate,r.playbackRateState$,i)),s(Ke(this.video),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),P(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),P(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready");let u=this.params.desiredState.videoTrack.getTransition();if(u&&i0(u.to)){this.params.desiredState.videoTrack.setState(u.to),this.params.output.currentVideoTrack$.next(this.trackUrls[u.to.id].track);let o=this.params.desiredState.playbackRate.getState(),l=this.params.output.element$.getValue()?.playbackRate;if(o!==l){let c=this.params.output.element$.getValue();c&&(this.params.desiredState.playbackRate.setState(o),c.playbackRate=o)}}this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.params.tuning.changePlaybackStateToPausedWhenEnded&&this.subscription.add(r.ended$.subscribe(()=>{this.videoState.setState("paused"),P(t.playbackState,"paused")})),this.textTracksManager.connect(this.video,t,e);let n=r0(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,a0(["init"])).pipe(ZB(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.params.output.element$.next(void 0),Me(this.video)}prepare(){let e=this.params.desiredState.videoTrack.getState()?.id;ZT(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];ZT(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=zt(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(ge(t))}playIfAllowed(){Be(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:eI.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){this.params.output.autoVideoTrackLimits$.next(e);let t=l=>{this.params.output.currentVideoTrack$.next(l),this.params.desiredState.videoTrack.startTransitionTo(l)},i=l=>{let c=St(n,{container:this.video.getBoundingClientRect(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:0,limits:l,abrLogger:this.params.dependencies.abrLogger});t(c)},r=this.params.output.currentVideoTrack$.getValue()?.quality,s=!!(e.max||e.min),n=(0,Ad.default)(this.trackUrls).map(l=>l.track);if(!r||!s||sr(e,n[0].quality,(0,iI.default)(n,-1)?.quality)){i();return}let u=e.max?t0(r,e.max):!0,o=e.min?e0(r,e.min):!0;u&&o||i(e)}};import{assertNever as aI,debounce as c0,merge as sI,observableFrom as d0,Subscription as p0,map as nI,ValueSubject as h0,ErrorCategory as kd,VideoQuality as f0}from"@vkontakte/videoplayer-shared";import{ErrorCategory as o0}from"@vkontakte/videoplayer-shared";var rI=["stun:videostun.mycdn.me:80"],u0=1e3,l0=3,Pd=()=>null,Oo=class{constructor(e,t){this.ws=null;this.peerConnection=null;this.serverUrl="";this.streamKey="";this.stream=null;this.signalingType="JOIN";this.retryCount=0;this.externalStartCallback=Pd;this.externalStopCallback=Pd;this.externalErrorCallback=Pd;this.options=this.normalizeOptions(t);let i=e.split("/");this.serverUrl=i.slice(0,i.length-1).join("/"),this.streamKey=i[i.length-1]}onStart(e){try{this.externalStartCallback=e}catch(t){this.handleSystemError(t)}}onStop(e){try{this.externalStopCallback=e}catch(t){this.handleSystemError(t)}}onError(e){try{this.externalErrorCallback=e}catch(t){this.handleSystemError(t)}}connect(){this.connectWS()}disconnect(){try{this.externalStopCallback(),this.closeConnections()}catch(e){this.handleSystemError(e)}}connectWS(){this.ws||(this.ws=new WebSocket(this.serverUrl),this.ws.onopen=this.onSocketOpen.bind(this),this.ws.onmessage=this.onSocketMessage.bind(this),this.ws.onclose=this.onSocketClose.bind(this),this.ws.onerror=this.onSocketError.bind(this))}onSocketOpen(){this.handleLogin()}onSocketClose(e){try{if(!this.ws)return;this.ws=null,e.code>1e3?(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():this.scheduleRetry()):this.externalStopCallback()}catch(t){this.handleRTCError(t)}}onSocketError(e){try{this.externalErrorCallback(new Error(e.toString()))}catch(t){this.handleRTCError(t)}}onSocketMessage(e){try{let t=this.parseMessage(e.data);switch(t.type){case"JOIN":case"CALL_JOIN":this.handleJoinMessage(t);break;case"UPDATE":this.handleUpdateMessage(t);break;case"STATUS":this.handleStatusMessage(t);break}}catch(t){this.handleRTCError(t)}}handleJoinMessage(e){switch(e.inviteType){case"ANSWER":this.handleAnswer(e.sdp);break;case"CANDIDATE":this.handleCandidate(e.candidate);break}}handleStatusMessage(e){switch(e.status){case"UNPUBLISHED":this.handleUnpublished();break}}async handleUpdateMessage(e){try{let t=await this.createOffer();this.peerConnection&&await this.peerConnection.setLocalDescription(t),this.handleAnswer(e.sdp)}catch(t){this.handleRTCError(t)}}async handleLogin(){try{let e={iceServers:[{urls:rI}]};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:o0.WTF,message:e.message})}async onPeerConnectionStream(e){let t=e.streams[0];this.stream&&this.stream.id===t.id||(this.stream=t,this.externalStartCallback(this.stream))}onPeerConnectionIceCandidate(e){e.candidate&&this.send({type:this.signalingType,inviteType:"CANDIDATE",candidate:e.candidate})}onPeerConnectionIceConnectionStateChange(){if(this.peerConnection){let e=this.peerConnection.iceConnectionState;["failed","closed"].indexOf(e)>-1&&(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():(this.closeConnections(),this.scheduleRetry()))}}async createOffer(){let e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");let t=await this.peerConnection.createOffer(e),i=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(i))throw new Error("No h264 codec support error");return t}handleRTCError(e){try{this.externalErrorCallback(e||new Error("RTC connection error"))}catch(t){this.handleSystemError(t)}}handleNetworkError(){try{this.externalErrorCallback(new Error("Network error"))}catch(e){this.handleSystemError(e)}}send(e){this.ws&&this.ws.send(JSON.stringify(e))}parseMessage(e){try{return JSON.parse(e)}catch{throw new Error("Can not parse socket message")}}closeConnections(){let e=this.ws;e&&(this.ws=null,e.close(1e3)),this.removePeerConnection()}removePeerConnection(){let e=this.peerConnection;e&&(this.peerConnection=null,e.close(),e.ontrack=null,e.onicecandidate=null,e.oniceconnectionstatechange=null,e=null)}scheduleRetry(){this.retryTimeout=setTimeout(this.connectWS.bind(this),u0)}normalizeOptions(e={}){let t={stunServerList:rI,maxRetryNumber:l0,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var Es=class{constructor(e){this.videoState=new F("stopped");this.maxSeekBackTime$=new h0(0);this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.pause(),this.video.srcObject=null,this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),P(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let s=this.params.desiredState.videoTrack.getTransition();if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s){this.prepare();return}switch(e){case"ready":t==="paused"?(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):i?.to==="playing"&&P(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&P(this.params.desiredState.playbackState,"paused");return;default:return aI(e)}};this.subscription=new p0,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=$e(e.container,e.tuning),this.liveStreamClient=new Oo(this.params.source.url,{maxRetryNumber:this.params.tuning.webrtc.connectionRetryMaxNumber,errorChanel:this.params.output.error$}),this.liveStreamClient.onStart(this.onLiveStreamStart.bind(this)),this.liveStreamClient.onStop(this.onLiveStreamStop.bind(this)),this.liveStreamClient.onError(this.onLiveStreamError.bind(this)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.subscribe()}destroy(){this.subscription.unsubscribe(),this.liveStreamClient.disconnect(),this.params.output.element$.next(void 0),Me(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,i=n=>{e.error$.next({id:"WebRTCLiveProvider",category:kd.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};this.subscription.add(sI(this.videoState.stateChangeStarted$.pipe(nI(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe(nI(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:u})=>{this.log({message:`[videoState change] ${u}: ${JSON.stringify(n)}`})}));let r=Ce(this.video);this.subscription.add(()=>r.destroy());let s=(n,u)=>this.subscription.add(n.subscribe(u,i));s(r.timeUpdate$,e.liveTime$),s(r.ended$,e.endedEvent$),s(r.looped$,e.loopedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentBuffer$),s(Ke(this.video),this.params.output.elementVisible$),this.subscription.add(r.durationChange$.subscribe(n=>{e.duration$.next(n===1/0?0:n)})).add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused")},i)).add(r.playing$.subscribe(()=>{this.videoState.setState("playing")},i)).add(r.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(De(this.video,t.volume,r.volumeState$,i)).add(r.volumeState$.subscribe(e.volume$,i)).add(this.videoState.stateChangeEnded$.subscribe(n=>{switch(n.to){case"stopped":e.position$.next(0),e.duration$.next(0),t.playbackState.setState("stopped");break;case"ready":break;case"paused":t.playbackState.setState("paused");break;case"playing":t.playbackState.setState("playing");break;default:return aI(n.to)}},i)).add(sI(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,d0(["init"])).pipe(c0(0)).subscribe(this.syncPlayback.bind(this),i)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),i))}onLiveStreamStart(e){this.params.output.element$.next(this.video),this.params.output.duration$.next(0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(ge(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.currentVideoTrack$.next({id:"webrtc",quality:f0.INVARIANT}),this.video.srcObject=e,P(this.params.desiredState.playbackState,"playing")}onLiveStreamStop(){this.videoState.startTransitionTo("stopped"),this.syncPlayback(),this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.params.output.endedEvent$.next()}onLiveStreamError(e){this.onLiveStreamStop(),this.params.output.error$.next({id:"WebRTC stream runtime error",category:kd.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){Be(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:kd.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var Dr=class{constructor(e){this.length=e.length,this.iterator=e[Symbol.iterator](),this.next()}next(){this.current=this.iterator.next(),this.index=this.index===void 0?0:this.index+1}getValue(){if(this.current.done)throw new Error("Iterable is completed");return this.current.value}isCompleted(){return!!this.current.done}isLast(){return this.index===this.length-1}};import{assertNever as xs,assertNonNullable as Zt,ErrorCategory as Fo,filter as pI,isNonNullable as hI,isNullable as T0,map as I0,merge as E0,once as x0,Subject as ne,Subscription as fI,ValueSubject as _,flattenObject as Rd}from"@vkontakte/videoplayer-shared";import{Observable as m0,map as oI,Subscription as b0,Subject as g0}from"@vkontakte/videoplayer-shared";var uI=a=>new m0(e=>{let t=new b0,i=a.desiredPlaybackState$.stateChangeStarted$.pipe(oI(({from:l,to:c})=>`${l}-${c}`)),r=a.desiredPlaybackState$.stateChangeEnded$,s=a.providerChanged$.pipe(oI(({type:l})=>l!==void 0)),n=new g0,u=0,o="unknown";return t.add(i.subscribe(l=>{u&&window.clearTimeout(u),o=l,u=window.setTimeout(()=>n.next(l),a.maxTransitionInterval)})),t.add(r.subscribe(()=>{window.clearTimeout(u),o="unknown",u=0})),t.add(s.subscribe(l=>{u&&(window.clearTimeout(u),u=0,l&&(u=window.setTimeout(()=>n.next(o),a.maxTransitionInterval)))})),t.add(n.subscribe(e)),()=>{window.clearTimeout(u),t.unsubscribe()}});import{ErrorCategory as S0,Subscription as v0,combine as y0,filter as cI,once as dI}from"@vkontakte/videoplayer-shared";function lI(){return new(window.AudioContext||window.webkitAudioContext)}var Cr=class a{constructor(e,t,i,r){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=i;this.volumeMultiplier=r;this.destroyController=new X;this.subscriptions=new v0;this.audioContext=null;this.gainNode=null;this.mediaElementSource=null;this.subscriptions.add(this.provider$.pipe(cI(s=>!!s.type),dI()).subscribe(({type:s})=>this.subscribe(s)))}static{this.errorId="VolumeMultiplierManager"}subscribe(e){B.browser.isSafari&&e!=="MPEG"||this.subscriptions.add(y0({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe(cI(({playbackState:t,video:i,volume:{muted:r,volume:s}})=>t==="playing"&&!!i&&!r&&!!s),dI()).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=lI();this.audioContext=i;let r=i.createGain();if(this.gainNode=r,r.gain.value=t,r.connect(i.destination),i.state==="suspended"&&(await i.resume(),this.destroyController.signal.aborted))return!1;let s=i.createMediaElementSource(e);return this.mediaElementSource=s,s.connect(r),!0}cleanup(){this.mediaElementSource&&(this.mediaElementSource.disconnect(),this.mediaElementSource=null),this.gainNode&&(this.gainNode.disconnect(),this.gainNode=null),this.audioContext&&(this.audioContext.state!=="closed"&&this.audioContext.close(),this.audioContext=null)}destroy(){this.destroyController.abort(),this.subscriptions.unsubscribe(),this.cleanup()}handleError(e){this.volumeMultiplierError$.next({id:a.errorId,category:S0.VIDEO_PIPELINE,message:e?.message??`${a.errorId} exception`,thrown:e})}};var w0={chunkDuration:5e3,maxParallelRequests:5},ws=class{constructor(e){this.current$=new _({type:void 0});this.providerError$=new ne;this.noAvailableProvidersError$=new ne;this.volumeMultiplierError$=new ne;this.providerOutput={position$:new _(0),duration$:new _(1/0),volume$:new _({muted:!1,volume:1}),availableVideoStreams$:new _([]),currentVideoStream$:new _(void 0),availableVideoTracks$:new _([]),currentVideoTrack$:new _(void 0),availableVideoCodecs$:new _([]),availableAudioStreams$:new _([]),currentAudioStream$:new _(void 0),availableAudioTracks$:new _([]),availableAudioCodecs$:new _([]),currentVideoSegmentLength$:new _(0),currentAudioSegmentLength$:new _(0),isAudioAvailable$:new _(!0),autoVideoTrackLimitingAvailable$:new _(!1),autoVideoTrackLimits$:new _(void 0),currentBuffer$:new _(void 0),isBuffering$:new _(!0),error$:new ne,fetcherError$:new ne,fetcherRecoverableError$:new ne,warning$:new ne,willSeekEvent$:new ne,soundProhibitedEvent$:new ne,seekedEvent$:new ne,loopedEvent$:new ne,endedEvent$:new ne,manifestRequested$:new ne,manifestReceived$:new ne,firstBytesRequested$:new ne,firstBytesReceived$:new ne,firstBytesEvent$:new ne,loadedMetadataEvent$:new ne,firstFrameEvent$:new ne,canplay$:new ne,isLive$:new _(void 0),isLiveEnded$:new _(null),canPlayLiveTailBuffer$:new _(!1),isLowLatency$:new _(!1),canChangePlaybackSpeed$:new _(!0),liveTime$:new _(void 0),liveBufferTime$:new _(void 0),liveLatency$:new _(void 0),severeStallOccurred$:new ne,availableTextTracks$:new _([]),currentTextTrack$:new _(void 0),hostname$:new _(void 0),httpConnectionType$:new _(void 0),httpConnectionReused$:new _(void 0),inPiP$:new _(!1),inFullscreen$:new _(!1),element$:new _(void 0),elementVisible$:new _(!0),availableSources$:new _(void 0),is3DVideo$:new _(!1),playbackState$:new _(""),getCurrentTime$:new _(null)};this.subscription=new fI;this.volumeMultiplierManager=null;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer"),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name);let t=Hl([...aT(this.params.tuning),...rT(this.params.tuning)]).filter(l=>hI(e.sources[l])),{forceFormat:i,formatsToAvoid:r}=this.params.tuning,s=[];i?s=[i]:r.length?s=[...t.filter(l=>!(0,Ld.default)(r,l)),...t.filter(l=>(0,Ld.default)(r,l))]:s=t,this.log({message:`Selected formats: ${s.join(" > ")}`}),this.tracer.log("Selected formats",Rd(s)),this.screenFormatsIterator=new Dr(s);let n=[...Vc(!0),...Vc(!1)];this.chromecastFormatsIterator=new Dr(n.filter(l=>hI(e.sources[l]))),this.providerOutput.availableSources$.next(e.sources);let{volumeMultiplier:u=1,tuning:{useVolumeMultiplier:o}}=this.params;o&&u!==1&&Cr.isSupported()&&(this.volumeMultiplierManager=new Cr(this.providerOutput,this.current$,this.volumeMultiplierError$,u))}init(){this.subscription.add(this.initProviderErrorHandling()).add(this.params.dependencies.chromecastInitializer.connection$.subscribe(()=>{this.reinitProvider()})).add(this.providerOutput.availableVideoCodecs$.subscribe(e=>{!this.videoCodecsIterator&&e.length>1&&(this.videoCodecsIterator=new Dr(e))}))}destroy(){this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe(),this.volumeMultiplierManager?.destroy(),this.volumeMultiplierManager=null,this.tracer.end()}initProvider(){let e=this.chooseDestination(),t=this.chooseFormat(e);if(T0(t)){this.handleNoFormatsError(e);return}let i;try{i=this.createProvider(e,t)}catch(r){this.providerError$.next({id:"ProviderNotConstructed",category:Fo.WTF,message:"Failed to create provider",thrown:r})}i?this.current$.next({type:t,provider:i,destination:e}):this.current$.next({type:void 0})}reinitProvider(){this.tracer.log("reinitProvider"),this.destroyProvider(),this.initProvider()}switchToNextProvider(e){this.tracer.log("switchToNextProvider",{destination:e}),this.destroyProvider(),this.failoverIndex=void 0,this.skipFormat(e),this.initProvider()}switchToNextVideoCodec(){this.params.tuning.dash.codecsPrioritizeEnabled&&!this.videoCodecsIterator.isLast()&&(this.tracer.log("switchToNextVideoCodec"),this.destroyProvider(),this.videoCodecsIterator.next(),this.initProvider())}destroyProvider(){let e=this.current$.getValue().provider;if(!e)return;this.log({message:"destroyProvider"}),this.tracer.log("destroyProvider"),e.destroy();let t=this.providerOutput.position$.getValue()*1e3,i=this.params.desiredState.seekState.getState(),r=i.state!=="none";if(this.params.desiredState.seekState.setState({state:"requested",position:r?i.position:t,forcePrecise:r?i.forcePrecise:!1}),e.scene3D){let n=e.scene3D.getCameraRotation();this.params.desiredState.cameraOrientation.setState({x:n.x,y:n.y})}let s=this.providerOutput.isBuffering$;s.getValue()||s.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),this.tracer.log("createProvider",{destination:e,format:t}),e){case"SCREEN":return this.createScreenProvider(t);case"CHROMECAST":return this.createChromecastProvider(t);default:return xs(e)}}createScreenProvider(e){let{sources:t,container:i,desiredState:r,panelSize:s}=this.params,n=this.providerOutput,u={container:i,source:null,desiredState:r,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning,panelSize:s};switch(e){case"DASH_SEP":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_ONDEMAND":case"DASH_STREAMS":{let o=this.applyFailoverHost(t[e]),l=this.applyFailoverHost(t.HLS_ONDEMAND||t.HLS);return Zt(o),this.params.tuning.useNewDashProvider?new Ss({...u,source:o,sourceHls:l,forceVideoCodec:this.videoCodecsIterator?.getValue()}):new us({...u,source:o,sourceHls:l,forceVideoCodec:this.videoCodecsIterator?.getValue()})}case"DASH_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return Zt(o),this.params.tuning.useNewDashProvider?new vs({...u,source:o}):new ls({...u,source:o})}case"HLS":case"HLS_ONDEMAND":case"HLS_FMP4":{let o=this.applyFailoverHost(t[e]);return Zt(o),new Ts({...u,source:o})}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return Zt(o),new ys({...u,source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case"MPEG":{let o=this.applyFailoverHost(t[e]);return Zt(o),new Is({...u,source:o})}case"DASH_LIVE":{let o=this.applyFailoverHost(t[e]);return Zt(o),new KS({...u,source:o,config:{...w0,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case"WEB_RTC_LIVE":{let o=this.applyFailoverHost(t[e]);return Zt(o),new Es({container:i,source:o,desiredState:r,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return xs(e)}}createChromecastProvider(e){let{sources:t,container:i,desiredState:r,meta:s}=this.params,n=this.providerOutput,u=this.params.dependencies.chromecastInitializer.connection$.getValue();return Zt(u),new ca({connection:u,meta:s,container:i,source:t,format:e,desiredState:r,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?"CHROMECAST":"SCREEN"}chooseFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case"CHROMECAST":return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return xs(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return xs(e)}}handleNoFormatsError(e){switch(e){case"SCREEN":this.noAvailableProvidersError$.next(this.params.tuning.forceFormat),this.current$.next({type:void 0});return;case"CHROMECAST":this.params.dependencies.chromecastInitializer.disconnect();return;default:return xs(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;let t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;let i=r=>{let s=new URL(r);return s.host=t,s.toString()};if(e===void 0)return e;if("type"in e){if(e.type==="raw")return e;if(e.type==="url")return{...e,url:i(e.url)}}return(0,bI.default)((0,mI.default)(e).map(([r,s])=>[r,i(s)]))}initProviderErrorHandling(){let e=new fI,t=!1,i=0;return e.add(E0(this.providerOutput.error$.pipe(pI(r=>!this.params.tuning.ignoreAudioRendererError||!r.message||!/AUDIO_RENDERER_ERROR/ig.test(r.message))),uI({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(I0(r=>({id:`ProviderHangup:${r}`,category:Fo.WTF,message:`A ${r} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.providerOutput.fetcherError$.subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;let r=this.params.desiredState.playbackState.transitionEnded$.pipe(pI(({to:s})=>s==="playing"),x0()).subscribe(()=>t=!0);e.add(r)})),e.add(this.providerError$.subscribe(r=>{let s=this.current$.getValue().destination,n={error:r,currentDestination:s};if(s==="CHROMECAST")this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider("SCREEN"),()=>this.params.dependencies.chromecastInitializer.disconnect());else{let u=r.category===Fo.NETWORK,o=r.category===Fo.FATAL,l=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),c=i<this.params.tuning.providerErrorLimit&&!o,p=this.videoCodecsIterator&&!this.videoCodecsIterator.isLast()&&this.params.tuning.dash.codecsPrioritizeEnabled,d=l&&!o&&(u&&t||!c);n={...n,isNetworkError:u,isFatalError:o,haveFailoverHost:l,tryFailover:d,canReinitProvider:c},c?(i++,this.reinitProvider()):d?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):p?this.switchToNextVideoCodec():(i=0,this.switchToNextProvider(s??"SCREEN"))}r.traceAsLog?this.tracer.log("providerInfo",Rd(n)):this.tracer.error("providerError",Rd(n))})),e}};import{fromEvent as No,once as A0,combine as P0,Subscription as gI,ValueSubject as $d,map as k0,filter as R0,isNonNullable as qo,now as Qe,safeStorage as Md}from"@vkontakte/videoplayer-shared";var L0=5e3,SI="one_video_throughput",vI="one_video_rtt",As=window.navigator.connection,yI=()=>{let a=As?.downlink;if(qo(a)&&a!==10)return a*1e3},TI=()=>{let a=As?.rtt;if(qo(a)&&a!==3e3)return a},II=(a,e,t)=>{let i=t*8,r=i/a;return i/(r+e)},Dd=class a{constructor(e){this.subscription=new gI;this.concurrentDownloads=new Set;this.tuningConfig=e;let t=a.load(SI)||(e.useBrowserEstimation?yI():void 0)||L0,i=a.load(vI)??(e.useBrowserEstimation?TI():void 0)??0;if(this.throughput$=new $d(t),this.rtt$=new $d(i),this.rttAdjustedThroughput$=new $d(II(t,i,e.rttPenaltyRequestSize)),this.throughput=Mt.getSmoothedValue(t,-1,e),this.rtt=Mt.getSmoothedValue(i,1,e),e.useBrowserEstimation){let r=()=>{let n=yI();n&&this.throughput.next(n);let u=TI();qo(u)&&this.rtt.next(u)};As&&"onchange"in As&&this.subscription.add(No(As,"change").subscribe(r)),r()}this.subscription.add(this.throughput.smoothed$.subscribe(r=>{Md.set(SI,r.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(r=>{Md.set(vI,r.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(P0({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(k0(({throughput:r,rtt:s})=>II(r,s,e.rttPenaltyRequestSize)),R0(r=>{let s=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(r-s)/s>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,i=Qe(),r=new gI;switch(this.subscription.add(r),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:r.add(No(e,"progress").pipe(A0()).subscribe(s=>{t=s.loaded,i=Qe()}));break;case 1:case 0:r.add(No(e,"loadstart").subscribe(()=>{t=0,i=Qe()}));break}r.add(No(e,"loadend").subscribe(s=>{if(e.status===200){let n=s.loaded,u=Qe(),o=n-t,l=u-i;this.addRawSpeed(o,l,1)}this.concurrentDownloads.delete(e),r.unsubscribe()}))}trackStream(e,t=!1){let i=e.getReader();if(!i){e.cancel("Could not get reader");return}let r=0,s=Qe(),n=0,u=Qe(),o=c=>{this.concurrentDownloads.delete(e),i.releaseLock(),e.cancel(`Throughput Estimator error: ${c}`).catch(()=>{})},l=async({done:c,value:p})=>{if(c)!t&&this.addRawSpeed(r,Qe()-s,1),this.concurrentDownloads.delete(e);else if(p){if(t){let d=Qe();if(d-u>this.tuningConfig.lowLatency.continuesByteSequenceInterval||d-s>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let f=u-s;f&&this.addRawSpeed(n,f,1,t),n=p.byteLength,s=Qe()}else n+=p.byteLength;u=Qe()}else r+=p.byteLength,n+=p.byteLength,n>=this.tuningConfig.streamMinSampleSize&&Qe()-u>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,Qe()-u,this.concurrentDownloads.size),n=0,u=Qe());await i?.read().then(l,o)}};this.concurrentDownloads.add(e),i?.read().then(l,o)}addRawSpeed(e,t,i=1,r=!1){if(a.sanityCheck(e,t,r)){let s=e*8/t;this.throughput.next(s*i)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,i=!1){let r=e*8/t;return!(!r||!isFinite(r)||r>1e6||r<30||i&&e<1e4||!i&&e<10*1024||!i&&t<=20)}static load(e){let t=Md.get(e);if(qo(t))return parseInt(t,10)??void 0}},EI=Dd;import{fillWithDefault as $0,VideoQuality as Uo}from"@vkontakte/videoplayer-shared";var xI={configName:["core"],throughputEstimator:{type:"EmaAndMa",emaAlphaSlow:.2,emaAlphaFast:.7,emaAlpha:.45,basisTrendChangeCount:10,changeThreshold:.05,useBrowserEstimation:!0,rttPenaltyRequestSize:1*1024*1024,streamMinSampleSize:10*1024,streamMinSampleTime:300,deviationDepth:20,deviationFactor:.5,lowLatency:{continuesByteSequenceInterval:50,maxLastEvaluationTimeout:300}},autoTrackSelection:{maxBitrateFactorAtEmptyBuffer:4,bitrateFactorAtEmptyBuffer:2.8,minBitrateFactorAtEmptyBuffer:1.5,bitrateAudioFactorAtEmptyBuffer:10,maxBitrateFactorAtFullBuffer:3,bitrateFactorAtFullBuffer:2,minBitrateFactorAtFullBuffer:1,bitrateAudioFactorAtFullBuffer:7,minVideoAudioRatio:5,minAvailableThroughputAudioRatio:5,usePixelRatio:!0,pixelRatioMultiplier:void 0,pixelRatioLogBase:3,pixelRatioLogCoefficients:[1,0,1],limitByContainer:!0,maxContainerSizeFactor:2,containerSizeFactor:1.3,minContainerSizeFactor:1,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldownIncreaseQuality:15e3,trackCooldownDecreaseQuality:3e3,backgroundVideoQualityLimit:Uo.Q_4320P,activeVideoAreaThreshold:.1,highQualityLimit:Uo.Q_720P,trafficSavingLimit:Uo.Q_480P},stallsManager:{enabled:!1,stallDurationNoDataBeforeQualityDecrease:500,stallDurationToBeCount:100,stallCountBeforeQualityDecrease:3,resetQualityRestrictionTimeout:1e4,ignoreStallsOnSeek:!0,stallsMetricsHistoryLength:5,maxPossibleStallDuration:3e4,minTvtToBeCounted:5,maxTvtToBeCounted:10800,significantTvt:600,targetStallsDurationPerTvt:1,deviationStallsDurationPerTvt:.5,criticalStallsDurationPerTvt:6,abrAdjustingSpeed:.1,emaAlpha:.6,useTotalStallsDurationPerTvt:!0,useAverageStallsDurationPerTvt:!0,useEmaStallsDurationPerTvt:!0},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:Uo.Q_480P},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,seekBiasInTheEnd:2e3,maxSegmentDurationLeftToSelectNextSegment:3e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:3e3,crashOnStallTimeout:25e3,crashOnStallTWithoutDataTimeout:5e3,enableSubSegmentBufferFeeding:!0,bufferEmptinessTolerance:100,useFetchPriorityHints:!0,enableBaseUrlSupport:!0,maxSegmentRetryCount:5,sourceOpenTimeout:1e3,vktvAbrThrottle:0,timeupdateEventTickThrottle:300,fetcherBufferOptimisation:!0,codecsPrioritizeEnabled:!1},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,maxLiveDuration:7200,catchupLiveForMutedInactiveTab:!0,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:250,playbackCatchupSpeedup:.05,isActiveOnDefault:!1,bufferEstimator:{emaAlpha:.45,changeThreshold:.05,deviationDepth:20,deviationFactor:.5,extremumInterval:5}}},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1,lowLatencyActiveLiveDelay:3e3,activeLiveDelay:5e3,maxPausedTime:5e3},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,forceFormat:void 0,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:"07A4434E",useWebmBigRequest:!1,webmCodec:"vp9",androidPreferredFormat:"dash",iosPreferredFormat:"hls",preferCMAF:!1,preferWebRTC:!1,preferMultiStream:!1,preferHDR:!1,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,seekNearDurationBias:1,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useHlsJs:!1,useNativeHLSTextTracks:!1,useNewSwitchTo:!1,useNewDashProvider:!1,useNewAutoSelectVideoTrack:!1,useSafariEndlessRequestBugfix:!0,useRefactoredSearchGap:!1,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,manifestRetryInterval:300,manifestRetryMaxInterval:1e4,manifestRetryMaxCount:10,audioVideoSyncRate:20,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50},useVolumeMultiplier:!1,ignoreAudioRendererError:!1,useEnableSubtitlesParam:!1,useHlsLiveNewTextManager:!1,exposeInternalsToGlobal:!1,hlsLiveNewTextManagerDownloadThreshold:4e3,disableYandexPiP:!1,asyncResolveClientChecker:!1,autostartOnlyIfVisible:!1,changePlaybackStateToPausedWhenEnded:!1},wI=a=>({...$0(a,xI),configName:[...a.configName??[],...xI.configName]});import{assertNonNullable as Ho,combine as Ct,ErrorCategory as jo,filter as O,filterChanged as Y,fromEvent as Bd,isNonNullable as RI,isNullable as O0,Logger as F0,map as G,mapTo as LI,merge as ei,now as Qo,once as N,Subject as W,Subscription as $I,tap as Vd,ValueSubject as k,isHigher as N0,isInvariantQuality as MI,flattenObject as ti,throttle as _d,getTraceSubscriptionMethod as DI,TracerFactory as q0,InternalsExposure as U0}from"@vkontakte/videoplayer-shared";import{merge as M0,map as D0,filter as AI,isNonNullable as C0}from"@vkontakte/videoplayer-shared";var Cd=({seekState:a,position$:e})=>M0(a.stateChangeEnded$.pipe(D0(({to:t})=>t.state==="none"?void 0:(t.position??NaN)/1e3),AI(C0)),e.pipe(AI(()=>a.getState().state==="none")));import{assertNonNullable as B0}from"@vkontakte/videoplayer-shared";var PI=a=>{let e=typeof a.container=="string"?document.getElementById(a.container):a.container;return B0(e,`Wrong container or containerId {${a.container}}`),e};import{filter as V0,once as _0}from"@vkontakte/videoplayer-shared";var kI=(a,e,t,i)=>{a!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&t?.getValue().length===0?t.pipe(V0(r=>r.length>0),_0()).subscribe(r=>{r.find(i)&&e.startTransitionTo(a)}):(a===void 0||t?.getValue().find(i))&&e.startTransitionTo(a)};var Wo=class{constructor(e={configName:[]},t=q0.createRootTracer(!1)){this.subscription=new $I;this.logger=new F0;this.abrLogger=this.logger.createComponentLog("ABR");this.internalsExposure=null;this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new k(!1);this.hasLiveOffsetByPausedTimer=0;this.playerInitRequest=0;this.playerInited=new k(!1);this.wasSetStartedQuality=!1;this.desiredState={playbackState:new F("stopped"),seekState:new F({state:"none"}),volume:new F({volume:1,muted:!1}),videoTrack:new F(void 0),videoStream:new F(void 0),audioStream:new F(void 0),autoVideoTrackSwitching:new F(!0),autoVideoTrackLimits:new F({}),isLooped:new F(!1),isLowLatency:new F(!1),playbackRate:new F(1),externalTextTracks:new F([]),internalTextTracks:new F([]),currentTextTrack:new F(void 0),textTrackCuesSettings:new F({}),cameraOrientation:new F({x:0,y:0})};this.info={playbackState$:new k(void 0),position$:new k(0),duration$:new k(1/0),muted$:new k(!1),volume$:new k(1),availableVideoStreams$:new k([]),currentVideoStream$:new k(void 0),availableQualities$:new k([]),availableQualitiesFps$:new k({}),currentQuality$:new k(void 0),isAutoQualityEnabled$:new k(!0),autoQualityLimitingAvailable$:new k(!1),autoQualityLimits$:new k({}),predefinedQualityLimitType$:new k("unknown"),availableAudioStreams$:new k([]),currentAudioStream$:new k(void 0),availableAudioTracks$:new k([]),isAudioAvailable$:new k(!0),currentPlaybackRate$:new k(1),currentBuffer$:new k({start:0,end:0}),isBuffering$:new k(!0),isStalled$:new k(!1),isEnded$:new k(!1),isLooped$:new k(!1),isLive$:new k(void 0),isLiveEnded$:new k(null),canPlayLiveTailBuffer$:new k(!1),canChangePlaybackSpeed$:new k(void 0),atLiveEdge$:new k(void 0),atLiveDurationEdge$:new k(void 0),liveTime$:new k(void 0),liveBufferTime$:new k(void 0),liveLatency$:new k(void 0),currentFormat$:new k(void 0),availableTextTracks$:new k([]),currentTextTrack$:new k(void 0),throughputEstimation$:new k(void 0),rttEstimation$:new k(void 0),videoBitrate$:new k(void 0),hostname$:new k(void 0),httpConnectionType$:new k(void 0),httpConnectionReused$:new k(void 0),surface$:new k("none"),chromecastState$:new k("NOT_AVAILABLE"),chromecastDeviceName$:new k(void 0),intrinsicVideoSize$:new k(void 0),availableSources$:new k(void 0),is3DVideo$:new k(!1),currentVideoSegmentLength$:new k(0),currentAudioSegmentLength$:new k(0)};this.events={inited$:new W,ready$:new W,started$:new W,playing$:new W,paused$:new W,stopped$:new W,willReady$:new W,willStart$:new W,willResume$:new W,willPause$:new W,willStop$:new W,willDestruct$:new W,watchCoverageRecord$:new W,watchCoverageLive$:new W,managedError$:new W,fatalError$:new W,fetcherRecoverableError$:new W,ended$:new W,looped$:new W,seeked$:new W,willSeek$:new W,autoplaySoundProhibited$:new W,manifestRequested$:new W,manifestReceived$:new W,firstBytesRequested$:new W,firstBytesReceived$:new W,firstBytes$:new W,loadedMetadata$:new W,firstFrame$:new W,canplay$:new W,log$:new W,fetcherError$:new W,severeStallOccured$:new W};this.experimental={element$:new k(void 0),tuningConfigName$:new k([]),enableDebugTelemetry$:new k(!1),dumpTelemetry:IS,getCurrentTime$:new k(null)};if(this.initLogs(),this.tuning=wI(e),this.tracer=t,this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new Us({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new EI(this.tuning.throughputEstimator),e.exposeInternalsToGlobal&&(this.internalsExposure=new U0("CORE"),this.internalsExposure.expose({player:this})),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(i,r,s)=>{let n=Reflect.get(i,r,s);return typeof n!="function"?n:(...u)=>{try{return n.apply(i,u)}catch(o){let l=u.map(d=>JSON.stringify(d,(h,f)=>{let b=typeof f;return(0,CI.default)(["number","string","boolean"],b)?f:f===null?null:`<${b}>`})),c=`Player.${String(r)}`,p=`Exception calling ${c} (${l.join(", ")})`;throw this.events.fatalError$.next({id:c,category:jo.WTF,message:p,thrown:o}),o}}}})}initVideo(e){this.config=e,this.internalsExposure?.expose({config:e,logger:this.logger,tuning:this.tuning}),this.setMuted(this.tuning.isAudioDisabled);let t=()=>{let{container:s,...n}=e;this.tracer.log("initVideo",ti(n)),this.domContainer=PI(e),this.chromecastInitializer.contentId=e.meta?.videoId,this.providerContainer=new ws({sources:e.sources,meta:e.meta??{},failoverHosts:e.failoverHosts??[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,tracer:this.tracer,logger:this.logger,abrLogger:this.abrLogger},tuning:this.tuning,volumeMultiplier:e.volumeMultiplier,panelSize:e.panelSize}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.initTracerSubscription(),this.providerContainer.init(),this.setLiveLowLatency(this.tuning.dashCmafLive.lowLatency.isActiveOnDefault),this.initDebugTelemetry(),this.initWakeLock(),this.playerInited.next(!0)},i=()=>{this.tuning.autostartOnlyIfVisible&&window.requestAnimationFrame?this.playerInitRequest=window.requestAnimationFrame(()=>t()):t()},r=()=>{this.tuning.asyncResolveClientChecker?B.isInited$.pipe(O(s=>!!s),N()).subscribe(()=>{console.log("Core SDK async start"),i()}):i()};return this.isNotActiveTabCase()?(this.tracer.log("request play from hidden tab"),Bd(document,"visibilitychange").pipe(N()).subscribe(r)):r(),this}destroy(){this.tracer.log("destroy"),window.clearTimeout(this.hasLiveOffsetByPausedTimer),this.playerInitRequest&&window.cancelAnimationFrame(this.playerInitRequest),this.events.willDestruct$.next(),this.stop(),this.providerContainer?.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe(),this.tracer.end(),this.internalsExposure?.destroy()}prepare(){return this.subscription.add(this.playerInited.pipe(O(e=>!!e),N()).subscribe(()=>{let e=this.desiredState.playbackState;this.tracer.log("prepare",{currentPlayBackState:e.getState()}),e.getState()==="stopped"&&e.startTransitionTo("ready")})),this}play(){return this.subscription.add(this.playerInited.pipe(O(e=>!!e),N()).subscribe(()=>{let e=this.desiredState.playbackState;this.tracer.log("play",{currentPlayBackState:e.getState()}),e.getState()!=="playing"&&e.startTransitionTo("playing")})),this}pause(){return this.subscription.add(this.playerInited.pipe(O(e=>!!e),N()).subscribe(()=>{let e=this.desiredState.playbackState;this.tracer.log("pause",{currentPlayBackState:e.getState()}),e.getState()!=="paused"&&e.startTransitionTo("paused")})),this}stop(){return this.subscription.add(this.playerInited.pipe(O(e=>!!e),N()).subscribe(()=>{let e=this.desiredState.playbackState;this.tracer.log("stop",{currentPlayBackState:e.getState()}),e.getState()!=="stopped"&&e.startTransitionTo("stopped")})),this}seekTime(e,t=!0){return this.subscription.add(this.playerInited.pipe(O(i=>!!i),N()).subscribe(()=>{let i=this.info.duration$.getValue(),r=this.info.isLive$.getValue(),s=e;e>=i&&!r&&(s=i-this.tuning.seekNearDurationBias),this.tracer.log("seekTime",{duration:i,isLive:r,time:e,calculatedTime:s,forcePrecise:t}),Number.isFinite(s)&&(this.events.willSeek$.next({from:this.getExactTime(),to:s}),this.desiredState.seekState.setState({state:"requested",position:s*1e3,forcePrecise:t}))})),this}seekPercent(e){return this.subscription.add(this.playerInited.pipe(O(t=>!!t),N()).subscribe(()=>{let t=this.info.duration$.getValue();this.tracer.log("seekPercent",{percent:e,duration:t}),isFinite(t)&&this.seekTime(Math.abs(t)*e,!1)})),this}setVolume(e,t){return this.subscription.add(this.playerInited.pipe(O(i=>!!i),N()).subscribe(()=>{let i=this.desiredState.volume,s=i.getTransition()?.to.muted??this.info.muted$.getValue(),n=t??(this.tuning.isAudioDisabled||s);this.tracer.log("setVolume",{volume:e,isAudioDisabled:this.tuning.isAudioDisabled,chromecastState:this.chromecastInitializer.castState$.getValue(),muted:n}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setVolume(e):i.startTransitionTo({volume:e,muted:n})})),this}setMuted(e,t=!1){return this.subscription.add(this.playerInited.pipe(O(i=>!!i),N()).subscribe(()=>{let i=this.desiredState.volume,r=this.tuning.isAudioDisabled&&!t||e,n=i.getTransition()?.to.volume??this.info.volume$.getValue();this.tracer.log("setMuted",{isMuted:e,nextMuted:r,volume:n,isAudioDisabled:this.tuning.isAudioDisabled,chromecastState:this.chromecastInitializer.castState$.getValue()}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setMuted(r):i.startTransitionTo({volume:n,muted:r})})),this}setVideoStream(e){return this.subscription.add(this.playerInited.pipe(O(t=>!!t),N()).subscribe(()=>{this.desiredState.videoStream.startTransitionTo(e)})),this}setAudioStream(e){return this.subscription.add(this.playerInited.pipe(O(t=>!!t),N()).subscribe(()=>{this.desiredState.audioStream.startTransitionTo(e)})),this}setQuality(e){return this.subscription.add(this.playerInited.pipe(O(t=>!!t),N()).subscribe(()=>{Ho(this.providerContainer);let t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();this.tracer.log("setQuality",{isDelayed:t.length===0,quality:e}),this.desiredState.videoTrack.getState()===void 0&&this.desiredState.videoTrack.getPrevState()===void 0&&t.length===0?this.wasSetStartedQuality?this.providerContainer.providerOutput.availableVideoTracks$.pipe(O(i=>i.length>0),N()).subscribe(i=>{this.setVideoTrackIdByQuality(i,e)}):this.explicitInitialQuality=e:t.length>0&&this.setVideoTrackIdByQuality(t,e)})),this}setAutoQuality(e){return this.subscription.add(this.playerInited.pipe(O(t=>!!t),N()).subscribe(()=>{this.tracer.log("setAutoQuality",{enable:e}),this.desiredState.autoVideoTrackSwitching.startTransitionTo(e)})),this}setAutoQualityLimits(e){return this.subscription.add(this.playerInited.pipe(O(t=>!!t),N()).subscribe(()=>{this.tracer.log("setAutoQualityLimits",ti(e)),this.desiredState.autoVideoTrackLimits.startTransitionTo(e)})),this}setPredefinedQualityLimits(e){return this.subscription.add(this.playerInited.pipe(O(t=>!!t),N()).subscribe(()=>{if(this.info.predefinedQualityLimitType$.getValue()===e)return this;let{highQualityLimit:t,trafficSavingLimit:i}=this.tuning.autoTrackSelection,r;switch(e){case"high_quality":r={min:t,max:void 0};break;case"traffic_saving":r={max:i,min:void 0};break;default:r={max:void 0,min:void 0}}this.setAutoQualityLimits(r)})),this}setPlaybackRate(e){return this.subscription.add(this.playerInited.pipe(O(t=>!!t),N()).subscribe(()=>{Ho(this.providerContainer);let t=this.providerContainer?.providerOutput.element$.getValue();this.tracer.log("setPlaybackRate",{playbackRate:e,isVideoElementAvailable:!!t}),t&&(this.desiredState.playbackRate.setState(e),t.playbackRate=e)})),this}setExternalTextTracks(e){return this.subscription.add(this.playerInited.pipe(O(t=>!!t),N()).subscribe(()=>{e.length&&this.tracer.log("setExternalTextTracks",ti(e)),this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>({type:"external",...t})))})),this}selectTextTrack(e){return this.subscription.add(this.playerInited.pipe(O(t=>!!t),N()).subscribe(()=>{kI(e,this.desiredState.currentTextTrack,this.providerContainer?.providerOutput.availableTextTracks$,t=>t.id===e),this.tracer.log("selectTextTrack",{textTrackId:e})})),this}setTextTrackCueSettings(e){return this.subscription.add(this.playerInited.pipe(O(t=>!!t),N()).subscribe(()=>{this.tracer.log("setTextTrackCueSettings",{...e}),this.desiredState.textTrackCuesSettings.startTransitionTo(e)})),this}setLiveLowLatency(e){let t=this.info.isLive$.getValue(),i=this.desiredState.isLowLatency.getState();return!t||i===e?this:(this.tracer.log("live switch to low latency "+e),this.desiredState.isLowLatency.setState(e),this.seekTime(0))}setLooped(e){return this.subscription.add(this.playerInited.pipe(O(t=>!!t),N()).subscribe(()=>{this.tracer.log("setLooped",{isLooped:e}),this.desiredState.isLooped.startTransitionTo(e)})),this}toggleChromecast(){this.tracer.log("toggleChromecast"),this.chromecastInitializer.toggleConnection()}startCameraManualRotation(e,t){return this.subscription.add(this.playerInited.pipe(O(i=>!!i),N()).subscribe(()=>{let i=this.getScene3D();this.tracer.log("startCameraManualRotation",{isScene3DAvailable:!!i,mx:e,my:t}),i&&i.startCameraManualRotation(e,t)})),this}stopCameraManualRotation(e=!1){return this.subscription.add(this.playerInited.pipe(O(t=>!!t),N()).subscribe(()=>{let t=this.getScene3D();this.tracer.log("stopCameraManualRotation",{isScene3DAvailable:!!t,immediate:e}),t&&t.stopCameraManualRotation(e)})),this}moveCameraFocusPX(e,t){return this.subscription.add(this.playerInited.pipe(O(i=>!!i),N()).subscribe(()=>{let i=this.getScene3D();if(this.tracer.log("moveCameraFocusPX",{isScene3DAvailable:!!i,dxpx:e,dypx:t}),i){let r=i.getCameraRotation(),s=i.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:r.x+s.x,y:r.y+s.y})}})),this}holdCamera(){return this.subscription.add(this.playerInited.pipe(O(e=>e),N()).subscribe(()=>{let e=this.getScene3D();e&&e.holdCamera()})),this}releaseCamera(){return this.subscription.add(this.playerInited.pipe(O(e=>!!e),N()).subscribe(()=>{let e=this.getScene3D();e&&e.releaseCamera()})),this}getExactTime(){if(!this.providerContainer)return 0;let e=this.providerContainer.providerOutput.element$.getValue();if(O0(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),i=t.state==="none"?void 0:t.position;return RI(i)?i/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}getScene3D(){let e=this.providerContainer?.current$.getValue();if(e?.provider?.scene3D)return e.provider.scene3D}setIntrinsicVideoSize(...e){let t={width:e.reduce((i,{width:r})=>i||r||0,0),height:e.reduce((i,{height:r})=>i||r||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add(ei(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(G(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(G(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(G(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(G(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(G(e=>e.to)).subscribe(e=>{this.info.autoQualityLimits$.next(e);let{highQualityLimit:t,trafficSavingLimit:i}=this.tuning.autoTrackSelection;this.info.predefinedQualityLimitType$.next(ic(e,t,i))})),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(O(({from:e})=>e==="stopped"),N()).subscribe(()=>{this.initedAt=Qo(),this.events.inited$.next()})).add(this.desiredState.playbackState.stateChangeEnded$.subscribe(e=>{switch(e.to){case"ready":this.events.ready$.next();break;case"playing":this.isPlaybackStarted||this.events.started$.next(),this.isPlaybackStarted=!0,this.events.playing$.next();break;case"paused":this.events.paused$.next();break;case"stopped":this.events.stopped$.next()}})).add(this.desiredState.playbackState.stateChangeStarted$.subscribe(e=>{switch(e.to){case"ready":this.events.willReady$.next();break;case"paused":this.events.willPause$.next();break;case"playing":this.isPlaybackStarted?this.events.willResume$.next():this.events.willStart$.next();break;case"stopped":this.events.willStop$.next();break;default:}}))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();this.tracer.log("willSeekEvent",ti(n)),n.state==="requested"?this.desiredState.seekState.setState({...n,state:"applying"}):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:jo.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.soundProhibitedEvent$.pipe(N()).subscribe(this.events.autoplaySoundProhibited$)).add(e.providerOutput.severeStallOccurred$.subscribe(this.events.severeStallOccured$)).add(e.providerOutput.seekedEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();this.tracer.log("seekedEvent",ti(n)),n.state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe(G(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(G(n=>n.destination),Y()).subscribe(()=>this.isPlaybackStarted=!1)).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add(Ct({availableVideoTracks:e.providerOutput.availableVideoTracks$,currentVideoStream:e.providerOutput.currentVideoStream$}).pipe(G(({availableVideoTracks:n,currentVideoStream:u})=>n.filter(o=>u?u.id===o.streamId:!0).map(({quality:o})=>o).sort((o,l)=>MI(o)?1:MI(l)?-1:N0(l,o)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(n=>{let u={};for(let o of n)o.fps&&(u[o.quality]=o.fps);this.info.availableQualitiesFps$.next(u)})).add(e.providerOutput.availableAudioStreams$.subscribe(this.info.availableAudioStreams$)).add(e.providerOutput.currentVideoStream$.subscribe(this.info.currentVideoStream$)).add(e.providerOutput.currentAudioStream$.subscribe(this.info.currentAudioStream$)).add(e.providerOutput.availableAudioTracks$.subscribe(this.info.availableAudioTracks$)).add(e.providerOutput.isAudioAvailable$.pipe(Y()).subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.pipe(O(n=>RI(n))).subscribe(n=>{this.info.currentQuality$.next(n?.quality),this.info.videoBitrate$.next(n?.bitrate)})).add(e.providerOutput.currentVideoSegmentLength$.pipe(Y((n,u)=>Math.round(n)===Math.round(u))).subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.pipe(Y((n,u)=>Math.round(n)===Math.round(u))).subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe(Y()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(Y()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(Y()).subscribe(this.info.httpConnectionReused$)).add(e.providerOutput.currentTextTrack$.subscribe(this.info.currentTextTrack$)).add(e.providerOutput.availableTextTracks$.subscribe(this.info.availableTextTracks$)).add(e.providerOutput.autoVideoTrackLimitingAvailable$.subscribe(this.info.autoQualityLimitingAvailable$)).add(e.providerOutput.autoVideoTrackLimits$.subscribe(n=>{this.desiredState.autoVideoTrackLimits.setState(n??{})})).add(e.providerOutput.currentBuffer$.pipe(G(n=>n?{start:n.from,end:n.to}:{start:0,end:0})).subscribe(this.info.currentBuffer$)).add(e.providerOutput.duration$.subscribe(this.info.duration$)).add(e.providerOutput.isBuffering$.subscribe(this.info.isBuffering$)).add(e.providerOutput.isLive$.subscribe(this.info.isLive$)).add(e.providerOutput.isLiveEnded$.pipe(Vd(n=>n&&this.stop())).subscribe(this.info.isLiveEnded$)).add(e.providerOutput.canPlayLiveTailBuffer$.subscribe(this.info.canPlayLiveTailBuffer$)).add(e.providerOutput.canChangePlaybackSpeed$.subscribe(this.info.canChangePlaybackSpeed$)).add(e.providerOutput.liveTime$.subscribe(this.info.liveTime$)).add(e.providerOutput.liveBufferTime$.subscribe(this.info.liveBufferTime$)).add(e.providerOutput.liveLatency$.subscribe(this.info.liveLatency$)).add(Ct({hasLiveOffsetByPaused:ei(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(G(n=>n.to),Y(),G(n=>n==="paused")),isLowLatency:e.providerOutput.isLowLatency$}).subscribe(({hasLiveOffsetByPaused:n,isLowLatency:u})=>{if(window.clearTimeout(this.hasLiveOffsetByPausedTimer),n){this.hasLiveOffsetByPausedTimer=window.setTimeout(()=>{this.hasLiveOffsetByPaused.next(!0)},this.getActiveLiveDelay(u));return}this.hasLiveOffsetByPaused.next(!1)})).add(Ct({atLiveEdge:Ct({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:Cd({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(G(({isLive:n,position:u,isLowLatency:o})=>{let l=this.getActiveLiveDelay(o);return n&&Math.abs(u)<l/1e3}),Y(),Vd(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(G(({atLiveEdge:n,hasPausedTimeoutCase:u})=>n&&!u)).subscribe(this.info.atLiveEdge$)).add(Ct({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(G(({isLive:n,position:u,duration:o})=>n&&(Math.abs(o)-Math.abs(u))*1e3<this.tuning.live.activeLiveDelay),Y(),Vd(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(G(n=>n.muted),Y()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(G(n=>n.volume),Y()).subscribe(this.info.volume$)).add(Cd({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(ei(e.providerOutput.endedEvent$.pipe(LI(!0)),e.providerOutput.seekedEvent$.pipe(LI(!1))).pipe(Y()).subscribe(this.info.isEnded$)).add(e.providerOutput.endedEvent$.subscribe(this.events.ended$)).add(e.providerOutput.loopedEvent$.subscribe(this.events.looped$)).add(e.providerError$.subscribe(this.events.managedError$)).add(e.providerOutput.fetcherRecoverableError$.subscribe(this.events.fetcherRecoverableError$)).add(e.providerOutput.fetcherError$.subscribe(this.events.fatalError$)).add(e.volumeMultiplierError$.subscribe(this.events.managedError$)).add(e.noAvailableProvidersError$.pipe(G(n=>({id:n?`No${n}`:"NoProviders",category:jo.VIDEO_PIPELINE,message:n?`${n} was forced but failed or not available`:"No suitable providers or all providers failed"}))).subscribe(this.events.fatalError$)).add(e.providerOutput.element$.subscribe(this.experimental.element$)).add(e.providerOutput.getCurrentTime$.subscribe(this.experimental.getCurrentTime$)).add(e.providerOutput.manifestRequested$.pipe(N()).subscribe(this.events.manifestRequested$)).add(e.providerOutput.manifestReceived$.pipe(N()).subscribe(this.events.manifestReceived$)).add(e.providerOutput.firstBytesRequested$.pipe(N()).subscribe(this.events.firstBytesRequested$)).add(e.providerOutput.firstBytesReceived$.pipe(N()).subscribe(this.events.firstBytesReceived$)).add(e.providerOutput.firstBytesEvent$.pipe(N(),G(n=>n??Qo()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe(N(),G(()=>Qo()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(N(),G(()=>Qo()-this.initedAt)).subscribe(this.events.canplay$)).add(this.throughputEstimator.throughput$.subscribe(this.info.throughputEstimation$)).add(this.throughputEstimator.rtt$.subscribe(this.info.rttEstimation$)).add(e.providerOutput.availableSources$.subscribe(this.info.availableSources$));let t=new k(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let i=new k(!0);this.subscription.add(e.current$.subscribe(()=>i.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(O(({to:n})=>n==="playing"),N()).subscribe(()=>i.next(!1)));let r=0,s=ei(e.providerOutput.isBuffering$,t,i).pipe(G(()=>{let n=e.providerOutput.isBuffering$.getValue(),u=t.getValue()||i.getValue();return n&&!u}),Y());this.subscription.add(s.subscribe(n=>{n?r=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(r),this.info.isStalled$.next(!1))})),this.subscription.add(ei(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{let n=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:n?.videoWidth,height:n?.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{let u=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:n?.size?.width,height:n?.size?.height},{width:u?.videoWidth,height:u?.videoHeight})})).add(e.providerOutput.is3DVideo$.subscribe(this.info.is3DVideo$)),this.subscription.add(ei(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,e.providerOutput.elementVisible$,this.chromecastInitializer.castState$).subscribe(()=>{let n=e.providerOutput.inPiP$.getValue(),u=e.providerOutput.inFullscreen$.getValue(),o=e.providerOutput.element$.getValue(),l=e.providerOutput.elementVisible$.getValue(),c=this.chromecastInitializer.castState$.getValue(),p;c==="CONNECTED"?p="second_screen":o?l?n?p="pip":u?p="fullscreen":p="inline":p="invisible":p="none",this.info.surface$.getValue()!==p&&this.info.surface$.next(p)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(G(e=>e?.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){let t=new $I;this.subscription.add(t),this.subscription.add(e.current$.pipe(Y((i,r)=>i.provider===r.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(O(i=>i.length>0),N()).subscribe(i=>{this.setStartingVideoTrack(i)}))}))}setStartingVideoTrack(e){let t;this.wasSetStartedQuality=!0;let i=this.explicitInitialQuality??this.info.currentQuality$.getValue();i&&(t=e.find(({quality:r})=>r===i),t||this.setAutoQuality(!0)),t||(t=St(e,{container:this.domContainer.getBoundingClientRect(),panelSize:this.config.panelSize,estimatedThroughput:this.throughputEstimator.throughput$.getValue(),tuning:this.tuning.autoTrackSelection,limits:this.desiredState.autoVideoTrackLimits.getState(),playbackRate:this.info.currentPlaybackRate$.getValue(),forwardBufferHealth:0,abrLogger:this.abrLogger})),this.desiredState.videoTrack.startTransitionTo(t),this.info.currentQuality$.next(t.quality),this.info.videoBitrate$.next(t.bitrate)}initLogs(){this.subscription.add(ei(this.desiredState.videoTrack.stateChangeStarted$.pipe(G(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(G(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(G(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(G(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(G(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(G(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(G(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(G(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(G(e=>({component:"desiredState",message:`[${e.entity} change] ${e.type}: ${JSON.stringify(e.transition)}`}))).subscribe(this.logger.log)),this.subscription.add(this.logger.log$.subscribe(this.events.log$))}initDebugTelemetry(){let e=this.providerContainer?.providerOutput;Ho(this.providerContainer),Ho(e),TS(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(t=>yS(t)),this.providerContainer.current$.subscribe(({type:t})=>fa("provider",t)),e.duration$.subscribe(t=>fa("duration",t)),e.availableVideoTracks$.pipe(O(t=>!!t.length),N()).subscribe(t=>fa("tracks",t)),this.events.fatalError$.subscribe(new Ae("fatalError")),this.events.managedError$.subscribe(new Ae("managedError")),e.position$.subscribe(new Ae("position")),e.currentVideoTrack$.pipe(G(t=>t?.quality)).subscribe(new Ae("quality")),this.info.currentBuffer$.subscribe(new Ae("buffer")),e.isBuffering$.subscribe(new Ae("isBuffering"))].forEach(t=>this.subscription.add(t)),fa("codecs",B.video.supportedCodecs)}initTracerSubscription(){let e=DI(this.tracer.log.bind(this.tracer)),t=DI(this.tracer.error.bind(this.tracer));this.subscription.add(this.info.playbackState$.subscribe(e("playbackState"))).add(this.info.isLooped$.subscribe(e("isLooped"))).add(this.info.currentPlaybackRate$.pipe(Y()).subscribe(e("currentPlaybackRate"))).add(this.info.isAutoQualityEnabled$.subscribe(e("isAutoQualityEnabled"))).add(this.info.autoQualityLimits$.subscribe(e("autoQualityLimits"))).add(this.info.currentFormat$.subscribe(e("currentFormat"))).add(this.info.availableQualities$.subscribe(e("availableQualities"))).add(this.info.availableQualitiesFps$.subscribe(e("availableQualitiesFps"))).add(this.info.availableAudioTracks$.subscribe(e("availableAudioTracks"))).add(this.info.isAudioAvailable$.subscribe(e("isAudioAvailable"))).add(Ct({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe(O(({currentQuality:i,videoBitrate:r})=>!!i&&!!r),Y((i,r)=>i.currentQuality===r.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe(O(i=>i>0),Y()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe(O(i=>i>0),Y()).subscribe(e("currentAudioSegmentLength"))).add(this.info.hostname$.subscribe(e("hostname"))).add(this.info.currentTextTrack$.subscribe(e("currentTextTrack"))).add(this.info.availableTextTracks$.subscribe(e("availableTextTracks"))).add(this.info.autoQualityLimitingAvailable$.subscribe(e("autoQualityLimitingAvailable"))).add(Ct({currentBuffer:this.info.currentBuffer$.pipe(O(i=>i.end>0),Y((i,r)=>i.end===r.end&&i.start===r.start)),position:this.info.position$.pipe(Y())}).pipe(_d(1e3)).subscribe(e("currentBufferAndPosition"))).add(this.info.duration$.pipe(Y()).subscribe(e("duration"))).add(this.info.isBuffering$.subscribe(e("isBuffering"))).add(this.info.isLive$.pipe(Y()).subscribe(e("isLive"))).add(this.info.canChangePlaybackSpeed$.pipe(Y()).subscribe(e("canChangePlaybackSpeed"))).add(Ct({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe(O(({liveTime:i,liveBufferTime:r})=>!!i&&!!r),_d(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe(Y(),O(i=>i===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe(Y(),O(i=>i===!0)).subscribe(e("atLiveDurationEdge"))).add(this.info.muted$.pipe(Y()).subscribe(e("muted"))).add(this.info.volume$.pipe(Y()).subscribe(e("volume"))).add(this.info.isEnded$.pipe(Y(),O(i=>i===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add(Ct({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe(O(({throughputEstimation:i,rtt:r})=>!!i&&!!r),_d(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe(Y(),O(i=>i===!0)).subscribe(e("is3DVideo"))).add(this.info.surface$.subscribe(e("surface"))).add(this.events.ended$.subscribe(e("ended"))).add(this.events.looped$.subscribe(e("looped"))).add(this.events.managedError$.subscribe(t("managedError"))).add(this.events.fatalError$.subscribe(t("fatalError"))).add(this.events.firstBytes$.subscribe(e("firstBytes"))).add(this.events.firstFrame$.subscribe(e("firstFrame"))).add(this.events.canplay$.subscribe(e("canplay")))}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e,t=()=>{e?.release(),e=void 0},i=async()=>{t(),e=await window.navigator.wakeLock.request("screen").catch(r=>{r instanceof DOMException&&r.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:jo.DOM,message:String(r)})})};this.subscription.add(ei(Bd(document,"visibilitychange"),Bd(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{let r=document.visibilityState==="visible",s=this.desiredState.playbackState.getState()==="playing",n=!!e&&!e?.released;r&&s?n||i():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){let i=e.find(r=>r.quality===t);this.tracer.log("setVideoTrackIdByQuality",ti({quality:t,availableTracks:ti(e),track:ti(i),isAutoQuality:!i})),i?this.desiredState.videoTrack.startTransitionTo(i):this.setAutoQuality(!0)}getActiveLiveDelay(e=!1){return e?this.tuning.live.lowLatencyActiveLiveDelay:this.tuning.live.activeLiveDelay}isNotActiveTabCase(){return document.hidden&&this.tuning.autoplayOnlyInActiveTab&&!Ta()}};import{Subscription as dX,Observable as pX,Subject as hX,ValueSubject as fX,VideoQuality as mX}from"@vkontakte/videoplayer-shared";var bX=`@vkontakte/videoplayer-core@${Nd}`;export{Bs as ChromecastState,Yo as HttpConnectionType,pX as Observable,Re as PlaybackState,Wo as Player,Vs as PredefinedQualityLimits,bX as SDK_VERSION,hX as Subject,dX as Subscription,Ko as Surface,Nd as VERSION,fX as ValueSubject,xt as VideoFormat,mX as VideoQuality,CL as areValidLiveRecordSources,B as clientChecker,la as isMobile};
|
|
178
|
+
`;var Pr=class{constructor(e,t,i){this.videoInitialized=!1;this.active=!1;this.container=e,this.sourceVideoElement=t,this.params=i,this.canvas=this.createCanvas();let r=this.canvas.getContext("webgl");if(!r)throw new Error("Could not initialize WebGL context");this.gl=r,this.container.appendChild(this.canvas),this.camera=new Eo(this.params.fov,this.params.orientation),this.cameraRotationManager=new xo(this.camera,{rotationSpeed:this.params.rotationSpeed,maxYawAngle:this.params.maxYawAngle,rotationSpeedCorrection:this.params.rotationSpeedCorrection,degreeToPixelCorrection:this.params.degreeToPixelCorrection,speedFadeTime:this.params.speedFadeTime,speedFadeThreshold:this.params.speedFadeThreshold}),this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.textureMappingBuffer=this.createTextureMappingBuffer(),this.updateTextureMappingBuffer(),this.program=this.createProgram(),this.videoTexture=this.createTexture(),this.gl.useProgram(this.program),this.videoElementDataLoadedFn=this.onDataLoadedHandler.bind(this),this.renderFn=this.render.bind(this)}play(){this.active||(this.videoInitialized?this.doPlay():this.sourceVideoElement.readyState>=2?(this.videoInitialized=!0,this.doPlay()):this.sourceVideoElement.addEventListener("loadeddata",this.videoElementDataLoadedFn))}stop(){this.active=!1}startCameraManualRotation(e,t){this.cameraRotationManager.setRotationSpeed(e*this.params.rotationSpeed,t*this.params.rotationSpeed,0),this.cameraRotationManager.startRotation()}stopCameraManualRotation(e=!1){this.cameraRotationManager.stopRotation(e)}turnCamera(e,t){this.cameraRotationManager.turnCamera(e,t)}pointCameraTo(e,t){this.cameraRotationManager.pointCameraTo(e,t)}pixelToDegree(e){return{x:this.params.degreeToPixelCorrection*this.params.fov.x*-e.x/this.viewportWidth,y:this.params.degreeToPixelCorrection*this.params.fov.y*e.y/this.viewportHeight}}getCameraRotation(){return this.camera.orientation}holdCamera(){this.cameraRotationManager.stopRotation(!0)}releaseCamera(){this.cameraRotationManager.onCameraRelease()}destroy(){this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),this.stop(),this.canvas.remove()}setViewportSize(e,t){this.viewportWidth=e,this.viewportHeight=t,this.canvas.width=this.viewportWidth,this.canvas.height=this.viewportHeight,this.gl.viewport(0,0,this.canvas.width,this.canvas.height)}onDataLoadedHandler(){this.videoInitialized=!0,this.doPlay()}doPlay(){this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.active=!0,this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),requestAnimationFrame(this.renderFn)}render(e){this.cameraRotationManager.tick(e),this.updateTexture(),this.updateTextureMappingBuffer();let t=this.gl.getAttribLocation(this.program,"a_vertex"),i=this.gl.getAttribLocation(this.program,"a_texel"),r=this.gl.getUniformLocation(this.program,"u_texture"),s=this.gl.getUniformLocation(this.program,"u_focus");this.gl.enableVertexAttribArray(t),this.gl.enableVertexAttribArray(i),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.vertexBuffer),this.gl.vertexAttribPointer(t,2,this.gl.FLOAT,!1,0,0),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.vertexAttribPointer(i,2,this.gl.FLOAT,!1,0,0),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.uniform1i(r,0),this.gl.uniform2f(s,-this.camera.orientation.x,-this.camera.orientation.y),this.gl.drawArrays(this.gl.TRIANGLE_FAN,0,4),this.gl.bindTexture(this.gl.TEXTURE_2D,null),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),this.gl.disableVertexAttribArray(t),this.gl.disableVertexAttribArray(i),this.active&&requestAnimationFrame(this.renderFn)}createShader(e,t){let i=this.gl.createShader(t);if(!i)throw this.destroy(),new Error(`Could not create shader (${t})`);if(this.gl.shaderSource(i,e),this.gl.compileShader(i),!this.gl.getShaderParameter(i,this.gl.COMPILE_STATUS))throw this.destroy(),new Error("An error occurred while compiling the shader: "+this.gl.getShaderInfoLog(i));return i}createProgram(){let e=this.gl.createProgram();if(!e)throw this.destroy(),new Error("Could not create shader program");let t=this.createShader(dT,this.gl.VERTEX_SHADER),i=this.createShader(pT,this.gl.FRAGMENT_SHADER);if(this.gl.attachShader(e,t),this.gl.attachShader(e,i),this.gl.linkProgram(e),!this.gl.getProgramParameter(e,this.gl.LINK_STATUS))throw this.destroy(),new Error("Could not link shader program.");return e}createTexture(){let e=this.gl.createTexture();if(!e)throw this.destroy(),new Error("Could not create texture");return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.bindTexture(this.gl.TEXTURE_2D,null),e}updateTexture(){this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,!0),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.sourceVideoElement),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}createVertexBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create vertex buffer");let t=1,i=1,r=this.frameHeight/(this.frameWidth/this.viewportWidth);return r>this.viewportHeight?t=this.viewportHeight/r:i=r/this.viewportHeight,this.gl.bindBuffer(this.gl.ARRAY_BUFFER,e),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-t,-i,t,-i,t,i,-t,i]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),e}createTextureMappingBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create texture mapping buffer");return e}calculateTexturePosition(){let e=.5-this.camera.orientation.x/360,t=.5-this.camera.orientation.y/180,i=this.camera.fov.x/360/2,r=this.camera.fov.y/180/2,s=e-i,n=t-r,u=e+i,o=t-r,l=e+i,d=t+r,h=e-i,c=t+r;return[s,n,u,o,l,d,h,c]}updateTextureMappingBuffer(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([...this.calculateTexturePosition()]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}updateFrameSize(){this.frameWidth=this.sourceVideoElement.videoWidth,this.frameHeight=this.sourceVideoElement.videoHeight}createCanvas(){let e=document.createElement("canvas");return e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e}};import{isNullable as $C,now as us,once as MC,Subscription as DC,ValueSubject as zc,isNonNullable as CC,safeStorage as Yc,filterChanged as BC}from"@vkontakte/videoplayer-shared";var wo="stalls_manager_metrics",Kc="stalls_manager_abr_params",hT="stalls_manager_default_tuning_abr_params",Xc=class{constructor(){this.isSeeked$=new zc(!1);this.isBuffering$=new zc(!1);this.maxQualityLimit=void 0;this.currentStallsCount=0;this.sumStallsDuration=0;this.lastStallDuration=0;this.providerStartWatchingTimestamp=0;this.lastUniqueVideoTrackSelectedTimestamp=0;this.predictedThroughputWithoutData=0;this.subscription=new DC;this.severeStallOccurred$=new zc(!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(Kc):{};return{...this.abrParams,...e}}set lastVideoTrackSelected(e){this.lastUniqueVideoTrackSelected?.id!==e.id&&(this.lastUniqueVideoTrackSelected=e,this.lastUniqueVideoTrackSelectedTimestamp=us(),this.currentStallsCount=0)}destroy(){window.clearTimeout(this.qualityRestrictionTimer),this.subscription.unsubscribe(),this.currentStallDuration$.getValue()!==0&&this.updateStallData();let e=(us()-this.providerStartWatchingTimestamp-this.sumStallsDuration)/1e3,t=this.sumStallsDuration;this.addStallInfoToHistory(e,t),this.updateStoredAbrParams()}resetStoredAbrParamsIfNeeded(){let{bitrateFactorAtEmptyBuffer:e,bitrateFactorAtFullBuffer:t,containerSizeFactor:i}={...this.getStoredData(hT)},{bitrateFactorAtEmptyBuffer:r,bitrateFactorAtFullBuffer:s,containerSizeFactor:n}={...this.abrParams};this.tuning.enabled&&e===r&&t===s&&i===n||(this.removeStoredData(Kc),this.setStoredData(hT,{bitrateFactorAtEmptyBuffer:r,bitrateFactorAtFullBuffer:s,containerSizeFactor:n}))}updateStoredAbrParams(){let e=[],t=this.getStoredData(wo,"[]");if(!this.tuning.enabled||t.length<this.tuning.stallsMetricsHistoryLength)return;let i=t.reduce((s,n)=>s+n.tvt,0);if(this.tuning.useTotalStallsDurationPerTvt){let n=t.reduce((u,o)=>u+o.stallsDuration,0)/i;e.push(this.calculateOptimalAbrParams(n,i))}if(this.tuning.useAverageStallsDurationPerTvt){let s=t.reduce((n,u)=>n+u.stallsDurationPerTvt,0)/t.length;e.push(this.calculateOptimalAbrParams(s,i))}this.tuning.useEmaStallsDurationPerTvt&&e.push(this.calculateOptimalAbrParams(t[t.length-1].stallsDurationPerTvtSmoothed,i));let r={bitrateFactorAtEmptyBuffer:Math.max(...e.map(s=>s.bitrateFactorAtEmptyBuffer)),bitrateFactorAtFullBuffer:Math.max(...e.map(s=>s.bitrateFactorAtFullBuffer)),containerSizeFactor:Math.min(...e.map(s=>s.containerSizeFactor))};this.setStoredData(wo,[]),this.setStoredData(Kc,r)}calculateOptimalAbrParams(e,t){let{targetStallsDurationPerTvt:i,deviationStallsDurationPerTvt:r,criticalStallsDurationPerTvt:s,abrAdjustingSpeed:n,significantTvt:u,stallsMetricsHistoryLength:o}=this.tuning,l=n*Math.min(t/(u*o),1),d=this.abrTuningParams;return e<i-r?d={bitrateFactorAtEmptyBuffer:Math.max(d.bitrateFactorAtEmptyBuffer-l,this.abrParams.minBitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.max(d.bitrateFactorAtFullBuffer-l,this.abrParams.minBitrateFactorAtFullBuffer),containerSizeFactor:Math.min(d.containerSizeFactor+l,this.abrParams.maxContainerSizeFactor)}:e>i+r&&(d={bitrateFactorAtEmptyBuffer:Math.min(d.bitrateFactorAtEmptyBuffer+l,this.abrParams.maxBitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.min(d.bitrateFactorAtFullBuffer+l,this.abrParams.maxBitrateFactorAtFullBuffer),containerSizeFactor:Math.max(d.containerSizeFactor-l,this.abrParams.minContainerSizeFactor)}),e>s&&(d={bitrateFactorAtEmptyBuffer:Math.max(d.bitrateFactorAtEmptyBuffer,this.abrParams.bitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.max(d.bitrateFactorAtFullBuffer,this.abrParams.bitrateFactorAtFullBuffer),containerSizeFactor:Math.min(d.containerSizeFactor,this.abrParams.containerSizeFactor)}),d}getStoredData(e,t="{}"){return JSON.parse(Yc.get(e)??t)}setStoredData(e,t){Yc.set(e,JSON.stringify(t))}removeStoredData(e){Yc.remove(e)}addStallInfoToHistory(e,t){if(e<this.tuning.minTvtToBeCounted||e>this.tuning.maxTvtToBeCounted||e*1e3<t)return;let i=this.getStoredData(wo,"[]"),r=t/e,s=i.length?$t(i[i.length-1].stallsDurationPerTvtSmoothed,t/e,this.tuning.emaAlpha):r,n={tvt:e,stallsDuration:t,stallsDurationPerTvt:r,stallsDurationPerTvtSmoothed:s};i.push(n),i.length>this.tuning.stallsMetricsHistoryLength&&i.shift(),this.setStoredData(wo,i)}updateStallData(){this.providerStartWatchingTimestamp&&!this.isSeeked$.getValue()&&(this.sumStallsDuration+=Math.min(this.lastStallDuration,this.tuning.maxPossibleStallDuration),this.currentStallsCount++)}subscribe(e){this.subscription.add(e.isSeeked$.subscribe(this.isSeeked$)),this.subscription.add(e.isBuffering$.subscribe(this.isBuffering$)),this.subscription.add(e.looped$.subscribe(t=>this.currentStallsCount=0)),this.subscription.add(e.playing$.pipe(MC()).subscribe(t=>this.providerStartWatchingTimestamp=us())),this.subscription.add(this.currentStallDuration$.pipe(BC()).subscribe(t=>{let{stallDurationNoDataBeforeQualityDecrease:i,stallCountBeforeQualityDecrease:r,resetQualityRestrictionTimeout:s,ignoreStallsOnSeek:n}=this.tuning;if($C(this.lastUniqueVideoTrackSelected)||n&&this.isSeeked$.getValue())return;let u=this.rtt$.getValue(),o=this.throughput$.getValue(),l=this.videoLastDataObtainedTimestamp$.getValue(),d=us(),h=r&&this.currentStallsCount>=r,c=i&&d-this.lastUniqueVideoTrackSelectedTimestamp>=i+u&&d-l>=i+u&&t>=i;(h||c)&&(this.severeStallOccurred$.next(!0),window.clearTimeout(this.qualityRestrictionTimer),this.maxQualityLimit=this.lastUniqueVideoTrackSelected.quality,CC(this.lastUniqueVideoTrackSelected.bitrate)&&o>this.lastUniqueVideoTrackSelected.bitrate&&(this.predictedThroughputWithoutData=this.lastUniqueVideoTrackSelected.bitrate)),!t&&us()-this.providerStartWatchingTimestamp>this.lastStallDuration&&(this.updateStallData(),this.severeStallOccurred$.next(!1),window.clearTimeout(this.qualityRestrictionTimer),this.qualityRestrictionTimer=window.setTimeout(()=>{this.maxQualityLimit=void 0,this.predictedThroughputWithoutData=0},s)),this.lastStallDuration=t}))}},Ao=Xc;import{combine as VC,map as _C,observeElementSize as OC,Subscription as FC,ValueSubject as Jc,noop as NC}from"@vkontakte/videoplayer-shared";var Po=class{constructor(){this.subscription=new FC;this.pipSize$=new Jc(void 0);this.videoSize$=new Jc(void 0);this.elementSize$=new Jc(void 0);this.pictureInPictureWindowRemoveEventListener=NC}connect({observableVideo:e,video:t}){let i=r=>{let s=r.target;this.pipSize$.next({width:s.width,height:s.height})};this.subscription.add(OC(t).subscribe(this.videoSize$)).add(e.enterPip$.subscribe(({pictureInPictureWindow:r})=>{this.pipSize$.next({width:r.width,height:r.height}),r.addEventListener("resize",i),this.pictureInPictureWindowRemoveEventListener=()=>{r.removeEventListener("resize",i)}})).add(e.leavePip$.subscribe(()=>{this.pictureInPictureWindowRemoveEventListener()})).add(VC({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe(_C(({videoSize:r,inPip:s,pipSize:n})=>s?n:r)).subscribe(this.elementSize$))}getValue(){return this.elementSize$.getValue()}subscribe(e,t){return this.elementSize$.subscribe(e,t)}getObservable(){return this.elementSize$}destroy(){this.pictureInPictureWindowRemoveEventListener(),this.subscription.unsubscribe()}};var Pi=class{constructor(e){this.subscription=new zC;this.videoState=new F("stopped");this.observableVideo=null;this.droppedFramesManager=new pr;this.stallsManager=new Ao;this.elementSizeManager=new Po;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new Qt;this.audioTrackSwitchHistory=new Qt;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(r.state==="requested"&&i?.to!=="paused"&&e!=="stopped"&&t!=="stopped"&&this.seek(r.position,r.forcePrecise),t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.player.stop(),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),P(this.params.desiredState.playbackState,"stopped",!0));return}switch(e){case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();return;case"ready":t==="paused"?(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="ready"&&P(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):t==="playing"&&this.video.paused?this.playIfAllowed():i?.to==="playing"&&P(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&P(this.params.desiredState.playbackState,"paused");return;default:return UC(e)}}};this.init3DScene=e=>{if(this.scene3D)return;this.scene3D=new Pr(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:e.projectionData?.pose.yaw||0,y:e.projectionData?.pose.pitch||0,z:e.projectionData?.pose.roll||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});let t=this.elementSizeManager.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};this.textTracksManager=new Ye(e.source.url),this.params=e,this.video=De(e.container,e.tuning),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Se(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.player=new Io({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode,tracer:this.tracer,forceVideoCodec:this.params.forceVideoCodec}),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params;WC(this.observableVideo)&&(this.observableVideo=Ve(this.video),this.subscription.add(()=>this.observableVideo?.destroy()));let i=this.constructor.name,r=n=>{e.error$.next({id:i,category:fT.WTF,message:`${i} internal logic error`,thrown:n})},s=(n,u)=>this.subscription.add(n.subscribe(u,r));return{output:e,desiredState:t,observableVideo:this.observableVideo,genericErrorListener:r,connect:s}}subscribe(){let{output:e,desiredState:t,observableVideo:i,genericErrorListener:r,connect:s}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe(Zc(l=>!!l.length),bT()).subscribe(l=>{this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks:l})}));let n=this.params.desiredState.seekState.stateChangeEnded$.pipe(cs(l=>l.to.state!=="none"),ls());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(Zc(mT),bT()),e.firstBytesEvent$),s(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),s(this.videoState.stateChangeEnded$.pipe(cs(l=>l.to)),this.params.output.playbackState$),this.subscription.add(i.looped$.subscribe(()=>this.player.warmUpMediaSourceIfNeeded(),r)),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(mt(this.video,t.isLooped,r)),this.subscription.add(Be(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(ze(this.video,t.playbackRate,i.playbackRateState$,r)),this.elementSizeManager.connect({video:this.video,observableVideo:i}),s(Ke(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),P(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),P(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.params.tuning.changePlaybackStateToPausedWhenEnded&&this.subscription.add(i.ended$.subscribe(()=>{this.videoState.setState("paused"),P(t.playbackState,"paused")})),this.subscription.add(this.player.manifestRequested.subscribe(this.params.output.manifestRequested$)).add(this.player.manifestReceived.subscribe(this.params.output.manifestReceived$)).add(this.player.firstBytesRequested.subscribe(this.params.output.firstBytesRequested$)).add(this.player.firstBytesReceived.subscribe(this.params.output.firstBytesReceived$)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:l})=>{if(l==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let d=this.player.getStreams(),h=this.player.getCodecs();if(jC(d,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let p=[];for(let f of d.audio){p.push(Cc(f));let b=[];for(let S of f.representations){let g=Yy(S);b.push(g),this.audioTracksMap.set(g,{stream:f,representation:S})}this.audioStreamsMap.set(f,b)}this.params.output.availableAudioStreams$.next(p)}let c=[];for(let p of d.video){c.push(Bc(p));let f=[];for(let b of p.representations){let S=Za({...b,streamId:p.id});S&&(f.push(S),this.videoTracksMap.set(S,{stream:p,representation:b}))}this.videoStreamsMap.set(p,f)}this.params.output.availableVideoStreams$.next(c);for(let p of d.text)for(let f of p.representations){let b=Ky(p,f);this.textTracksMap.set(b,{stream:p,representation:f})}this.params.output.availableVideoTracks$.next(Array.from(this.videoTracksMap.keys())),this.params.output.availableAudioTracks$.next(Array.from(this.audioTracksMap.keys())),this.params.output.isAudioAvailable$.next(!!this.audioTracksMap.size),h?.video&&this.params.output.availableVideoCodecs$.next(h.video),h?.audio&&this.params.output.availableAudioCodecs$.next(h.audio),this.audioTracksMap.size&&this.textTracksMap.size&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else l==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},r)),this.subscription.add(ds(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$,GC(this.video,"progress")).pipe(Zc(()=>this.videoTracksMap.size>0)).subscribe(async()=>{let l=this.player.state$.getState(),d=this.player.state$.getTransition();if(!(0,gT.default)(["manifest_ready","running"],l)||d)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let h=this.selectVideoAudioRepresentations();if(!h)return;let[c,p]=h,f=[...this.videoTracksMap.keys()].find(S=>this.videoTracksMap.get(S)?.representation.id===c.id);mT(f)&&(this.stallsManager.lastVideoTrackSelected=f);let b=this.params.desiredState.autoVideoTrackLimits.getTransition();if(b&&this.params.output.autoVideoTrackLimits$.next(b.to),l==="manifest_ready")await this.player.initRepresentations(c.id,p?.id,this.params.sourceHls);else if(await this.player.switchRepresentation("video",c.id),p){let S=!!t.audioStream.getTransition();await this.player.switchRepresentation("audio",p.id,S)}},r)),this.subscription.add(HC({videoState:this.videoState.stateChangeEnded$,autoVideoTrackState:ds(Ro([t.autoVideoTrackSwitching.getState()]),t.autoVideoTrackSwitching.stateChangeEnded$.pipe(cs(l=>l.to)))}).pipe(cs(({videoState:l,autoVideoTrackState:d})=>l.to!=="stopped"&&d),ls()).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(ls()).subscribe(l=>{let d=[...this.videoTracksMap.entries()].find(([,{representation:b}])=>b.id===l);if(!d){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[h,{stream:c}]=d,p=this.params.desiredState.videoStream.getTransition();p&&p.to&&p.to.id===c.id&&this.params.desiredState.videoStream.setState(p.to),e.currentVideoTrack$.next(h),e.currentVideoStream$.next(Bc(c));let f=this.player.calculateDurationFromSegments();f&&this.params.output.duration$.next(f/1e3)},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(ls()).subscribe(l=>{let d=[...this.audioTracksMap.entries()].find(([,{representation:f}])=>f.id===l);if(!d){e.currentAudioStream$.next(void 0);return}let[h,{stream:c}]=d,p=this.params.desiredState.audioStream.getTransition();p&&p.to&&p.to.id===c.id&&this.params.desiredState.audioStream.setState(p.to),e.currentAudioStream$.next(Cc(c))},r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(l=>{if(l?.is3dVideo&&this.params.tuning.spherical?.enabled)try{this.init3DScene(l),e.is3DVideo$.next(!0)}catch(d){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${d}`})}else this.destroy3DScene(),this.params.tuning.spherical?.enabled&&e.is3DVideo$.next(!1)},r)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,r)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,r)),this.textTracksManager.connect(this.video,t,e);let u=t.playbackState.stateChangeStarted$.pipe(cs(({to:l})=>l==="ready"),ls());this.subscription.add(ds(u,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,Ro(["init"])).subscribe(()=>{let l=t.autoVideoTrackSwitching.getState(),h=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:l?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(h)})),this.subscription.add(ds(u,this.player.state$.stateChangeEnded$,Ro(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let o=ds(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Ro(["init"])).pipe(QC(0));this.subscription.add(o.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?ba:ma,t=this.params.tuning.useNewAutoSelectVideoTrack?zn:Wn,i=this.params.tuning.useNewAutoSelectVideoTrack?St:Gn,{desiredState:r,output:s}=this.params,n=r.autoVideoTrackSwitching.getState(),u=r.videoTrack.getState()?.id,l=[...this.videoTracksMap.keys()].find(({id:I})=>I===u),d=s.currentVideoTrack$.getValue(),h=r.videoStream.getState()??(l&&this.videoTracksMap.get(l)?.stream)??this.videoStreamsMap.size===1?this.videoStreamsMap.keys().next().value:void 0;if(!h)return;let c=[...this.videoStreamsMap.keys()].find(({id:I})=>I===h.id),p=c&&this.videoStreamsMap.get(c);if(!p)return;let f=ve(this.video.buffered,this.video.currentTime*1e3),b;this.player.isActiveLive$.getValue()?b=this.player.isLowLatency$.getValue()?this.params.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.params.tuning.dashCmafLive.normalizedLiveMinBufferSize:this.player.isLive$.getValue()?b=this.params.tuning.dashCmafLive.normalizedTargetMinBufferSize:b=n?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;let S=(this.video.duration*1e3||1/0)-this.video.currentTime*1e3,g=Math.min(f/Math.min(b,S||1/0),1),T=r.audioStream.getState()??(this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0),E=[...this.audioStreamsMap.keys()].find(({id:I})=>I===T?.id)??this.audioStreamsMap.keys().next().value,y=0;if(E){if(l&&!n){let I=e(l,p,this.audioStreamsMap.get(E)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);y=Math.max(y,I?.bitrate??-1/0)}if(d){let I=e(d,p,this.audioStreamsMap.get(E)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);y=Math.max(y,I?.bitrate??-1/0)}}let w=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:g,current:d,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?w??l:l??w,$=E&&t(k,p,this.audioStreamsMap.get(E)??[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.stallsManager.abrTuningParams,forwardBufferHealth:g,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),A=this.videoTracksMap.get(k)?.representation,L=$&&this.audioTracksMap.get($)?.representation;if(A&&L)return[A,L];if(A&&!L&&this.audioTracksMap.size===0)return[A,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){_e(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:fT.DOM,thrown:e}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.stallsManager.destroy(),this.elementSizeManager.destroy(),this.destroy3DScene(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),this.params.output.currentVideoStream$.next(void 0),Ce(this.video),this.tracer.end()}};var ps=class extends Pi{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 ed,merge as ST,filter as vT,filterChanged as yT,isNullable as td,map as TT,ValueSubject as id,isNonNullable as YC}from"@vkontakte/videoplayer-shared";var hs=class extends Pi{constructor(e){super(e),this.textTracksManager.destroy()}subscribe(){super.subscribe();let e=!1,t=-1,{output:i,observableVideo:r,desiredState:s,connect:n}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canPlayLiveTailBuffer$.next(!0),n(r.timeUpdate$,i.liveBufferTime$),n(this.player.liveSeekableDuration$,i.duration$),n(this.player.liveLatency$,i.liveLatency$);let u=new id(1);n(r.playbackRateState$,u),this.params.tuning.dashCmafLive.catchupLiveForMutedInactiveTab&&this.subscription.add(i.elementVisible$.pipe(yT()).subscribe(o=>{let l=i.position$.getValue(),d=i.volume$.getValue(),h=!d.volume||d.muted;!o&&!l&&h?e=!0:o&&e&&(this.seek(0),e=!1)})),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(s.isLowLatency.stateChangeEnded$.pipe(TT(o=>o.to)).subscribe(this.player.isLowLatency$)).add(ed({liveBufferTime:i.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(TT(({liveBufferTime:o,liveAvailabilityStartTime:l})=>o&&l?o+l:void 0)).subscribe(i.liveTime$)).add(this.player.liveStreamStatus$.pipe(vT(o=>YC(o))).subscribe(o=>i.isLiveEnded$.next(o!=="active"&&i.position$.getValue()===0))).add(ed({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:ST(r.playbackRateState$,new id(1))}).pipe(vT(({liveStreamStatus:o,liveDuration:l})=>o==="active"&&!!l)).subscribe(({liveDuration:o,playbackRate:l})=>{let d=i.liveBufferTime$.getValue(),h=i.position$.getValue(),{playbackCatchupSpeedup:c}=this.params.tuning.dashCmafLive.lowLatency;h||l<1-c||this.video.paused||td(d)||(t=o-d)})).add(ed({time:i.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:ST(r.playbackRateState$,new id(1))}).pipe(yT((o,l)=>this.player.liveStreamStatus$.getValue()==="active"?o.liveDuration===l.liveDuration:o.time===l.time)).subscribe(({time:o,liveDuration:l,playbackRate:d})=>{let h=i.position$.getValue(),{playbackCatchupSpeedup:c}=this.params.tuning.dashCmafLive.lowLatency;if(!h&&!this.video.paused&&d>=1-c||td(o)||td(l))return;let p=-1*(l-o-t);i.position$.next(Math.min(p,0))})).add(this.player.currentLiveTextRepresentation$.subscribe(o=>{if(o){let l=Xy(o);this.params.output.availableTextTracks$.next([l])}}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,i=Math.trunc(t/1e3<=Math.abs(this.params.output.duration$.getValue())?t:0);this.player.seekLive(i).then(()=>{this.params.output.position$.next(e/1e3)})}};import{assertNever as IB,assertNonNullable as EB,combine as xB,debounce as wB,ErrorCategory as OT,filter as Sd,filterChanged as Es,fromEvent as AB,isNonNullable as FT,isNullable as PB,map as xs,merge as ws,observableFrom as Fo,once as NT,Subscription as RB}from"@vkontakte/videoplayer-shared";var _T=C(Ee(),1),bd=C(xa(),1);import{abortable as pd,assertNonNullable as Lr,combine as $r,ErrorCategory as ut,filter as Vo,filterChanged as ys,flattenObject as Ts,fromEvent as It,getTraceSubscriptionMethod as pB,interval as hd,isNonNullable as Is,isNullable as BT,map as Mr,merge as Mi,now as fd,Subject as ei,Subscription as md,tap as hB,throttle as VT,ValueSubject as te}from"@vkontakte/videoplayer-shared";var Mo=C(Ee(),1),$i=C(at(),1),Do=C(xa(),1);var $T=C(wn(),1);import{assertNever as KC,ErrorCategory as IT,Subject as ET}from"@vkontakte/videoplayer-shared";var XC=18,xT=!1;try{xT=B.browser.isSafari&&!!B.browser.safariVersion&&B.browser.safariVersion<=XC}catch(a){console.error(a)}var rd=class{constructor(e){this.bufferFull$=new ET;this.error$=new ET;this.queue=[];this.currentTask=null;this.destroyed=!1;this.abortRequested=!1;this.completeTask=()=>{try{if(this.currentTask){let e=this.currentTask.signal?.aborted;this.currentTask.callback(!e),this.currentTask=null}this.queue.length&&this.pull()}catch(e){this.error$.next({id:"BufferTaskQueueUnknown",category:IT.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:e})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(i=>{let r={operation:"append",data:e,signal:t,callback:i};this.queue.push(r),this.pull()})}async remove(e,t,i){return i&&i.aborted?!1:new Promise(r=>{let s={operation:"remove",from:e,to:t,signal:i,callback:r};this.queue.unshift(s),this.pull()})}async abort(e){return new Promise(t=>{let i,r=s=>{this.abortRequested=!1,t(s)};xT&&e?i={operation:"safariAbort",init:e,callback:r}:i={operation:"abort",callback:r};for(let{callback:s}of this.queue)s(!1);this.abortRequested=!0,i&&(this.queue=[i]),this.pull()})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){if((this.buffer.updating||this.currentTask||this.destroyed)&&!this.abortRequested)return;let e=this.queue.shift();if(!e)return;if(e.signal?.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(r){r instanceof DOMException&&r.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):r instanceof DOMException&&r.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:IT.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:r}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){let{operation:t}=e;switch(t){case"append":this.buffer.appendBuffer(e.data);break;case"remove":this.buffer.remove(e.from/1e3,e.to/1e3);break;case"abort":this.buffer.abort();break;case"safariAbort":{this.buffer.abort(),this.buffer.appendBuffer(e.init);break}default:KC(t)}}},wT=rd;import{abortable as Jt,assertNonNullable as ke,ErrorCategory as ki,fromEvent as ud,getExponentialDelay as ld,isHigher as iB,isNonNullable as Zt,isNullable as ce,now as $o,once as rB,Subject as aB,Subscription as sB,ValueSubject as Li}from"@vkontakte/videoplayer-shared";var ad=C(at(),1);import{videoSizeToQuality as JC,throttleFn as ZC}from"@vkontakte/videoplayer-shared";var fs=({id:a,width:e,height:t,bitrate:i,fps:r,quality:s,streamId:n})=>{let u=(s?Ht(s):void 0)??JC({width:e,height:t});return u&&{id:a,quality:u,bitrate:i,size:{width:e,height:t},fps:r,streamId:n}},AT=({id:a,bitrate:e})=>({id:a,bitrate:e}),PT=({language:a,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:a,label:e}),RT=({language:a,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:a,label:e}),sd=({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}),nd=({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)}),od=a=>"url"in a,He=a=>a.type==="template";var kT=a=>{a.sort((t,i)=>t.from-i.from);let e=[a[0]];for(let t=1;t<a.length;t++){let{from:i,to:r}=a[t],s=e[e.length-1];s.to>=i?s.to=Math.max(s.to,r):e.push(a[t])}return e},Ri=(a,e)=>{for(let t of a)if(e(t))return t;return null},LT=a=>{let e=!1,t=ZC(()=>{e=!0},a);return()=>{try{return t(),e}finally{e=!1}}};import{fromEvent as eB,Subscription as tB}from"@vkontakte/videoplayer-shared";var ko=a=>{let e=[];for(let t=0;t<a.length;t++){let i=Math.floor(a.start(t)*1e3),r=Math.ceil(a.end(t)*1e3);e.push(i,r)}return e};var Lo=class{constructor(e,t){this.lastUpdateTs=0;this.lastCallTs=0;this.prevRanges=[];this.subscription=new tB;this.mediaSource=e,this.sourceBuffer=t,this.subscription.add(eB(this.sourceBuffer,"updateend").subscribe(()=>this.updateend()))}updateend(){if(!V(this.mediaSource,this.sourceBuffer))return;let{prevRanges:e}=this,t=ko(this.sourceBuffer.buffered);this.prevRanges=t,this.isRangesRemoved(e,t)&&(this.lastUpdateTs=Date.now())}isRangesRemoved(e,t){if(e.length!==t.length)return!0;for(let i=0;i<e.length;i+=2){let r=e[i],s=e[i+1],n=t[i],u=t[i+1];if(n>r||u<s)return!0}return!1}wasUpdated(){let{lastCallTs:e,lastUpdateTs:t}=this;return this.lastCallTs=Date.now(),e<=t}destroy(){this.subscription.unsubscribe()}};var ms=class{constructor(e,t,i,{fetcher:r,tuning:s,getCurrentPosition:n,isActiveLowLatency:u,compatibilityMode:o=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new Li(0);this.currentLowLatencySegmentLength$=new Li(0);this.currentSegmentLength$=new Li(0);this.onLastSegment$=new Li(!1);this.fullyBuffered$=new Li(!1);this.playingRepresentation$=new Li(void 0);this.playingRepresentationInit$=new Li(void 0);this.error$=new aB;this.gaps=[];this.subscription=new sB;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new X;this.switchAbortController=new X;this.destroyAbortController=new X;this.useSmartRepresentationSwitch=!1;this.bufferLimit=1/0;this.failedDownloads=0;this.baseUrls=[];this.baseUrlsIndex=0;this.isLive=!1;this.liveUpdateSegmentIndex=0;this.liveInitialAdditionalOffset=0;this.isSeekingLive=!1;this.index=0;this.lastDataObtainedTimestampMs=0;this.loadByteRangeSegmentsTimeoutId=0;this.sourceBufferBufferedDiff=null;this.startWith=Jt(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);ke(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new wT(this.sourceBuffer),this.sourceBufferBufferedDiff=new Lo(this.mediaSource,this.sourceBuffer),this.subscription.add(ud(this.sourceBuffer,"updateend").subscribe(()=>{this.maintain()})),this.subscription.add(ud(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:ki.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let u=this.getCurrentPosition();if(!this.sourceBuffer||!u||!V(this.mediaSource,this.sourceBuffer))return;let o=Math.min(this.bufferLimit,mr(this.sourceBuffer.buffered)*.8);this.bufferLimit=o;let l=ve(this.sourceBuffer.buffered,u),d=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(u,n*2,l<d).catch(h=>{this.handleAsyncError(h,"pruneBuffer")})})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(n=>this.error$.next(n))),yield this.loadInit(t,"high",!0);let i=this.initData.get(t.id),r=this.segments.get(t.id),s=this.parsedInitData.get(t.id);ke(i,"No init buffer for starting representation"),ke(r,"No segments for starting representation"),i instanceof ArrayBuffer&&(this.searchGaps(r,t),yield this.sourceBufferTaskQueue.append(i,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(s))}.bind(this));this.switchTo=Jt(this.destroyAbortController.signal,async function*(e,t=!1){if(!V(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);ke(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if(ce(s)||ce(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),ke(r,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!V(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer();else{let n=this.getCurrentPosition();Zt(n)&&!this.isLive&&(this.bufferLimit=1/0,await this.pruneBuffer(n,1/0,!0)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}this.maintain()}}.bind(this));this.switchToOld=Jt(this.destroyAbortController.signal,async function*(e,t=!1){if(!V(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);ke(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if(ce(s)||ce(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),ke(r,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!V(this.mediaSource,this.sourceBuffer)))if(yield this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer(),this.maintain();else{let n=this.getCurrentPosition();Zt(n)&&(this.isLive||(this.bufferLimit=1/0,await this.pruneBuffer(n,1/0,!0)),this.maintain(n)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}}.bind(this));this.seekLive=Jt(this.destroyAbortController.signal,async function*(e){let t=(0,Do.default)(e,o=>o.representations)??[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let o of this.representations.keys()){let l=t.find(c=>c.id===o);l&&this.representations.set(o,l);let d=this.representations.get(o);if(!d||!He(d.segmentReference))return;let h=this.getActualLiveStartingSegments(d.segmentReference);this.segments.set(d.id,h)}let i=this.switchingToRepresentationId??this.downloadingRepresentationId,r=this.representations.get(i);ke(r);let s=this.segments.get(i);ke(s,"No segments for starting representation");let n=this.initData.get(i);if(ke(n,"No init buffer for starting representation"),!(n instanceof ArrayBuffer))return;let u=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,yield this.abort(),u&&(yield this.sourceBufferTaskQueue.remove(u.from*1e3,u.to*1e3,this.destroyAbortController.signal)),this.searchGaps(s,r),yield this.sourceBufferTaskQueue.append(n,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this));this.fetcher=r,this.tuning=s,this.compatibilityMode=o,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=u,this.isLive=!!l?.live,this.baseUrls=l?.baseUrls??[],this.initData=new Map(i.map(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){!V(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new X,Jt(this.switchAbortController.signal,async function*(i,r=!1){this.switchingToRepresentationId=i;let s=this.representations.get(i);ke(s,`No such representation ${i}`);let n=this.segments.get(i),u=this.initData.get(i);if(ce(u)||ce(n)?yield this.loadInit(s,"high",!1):u instanceof Promise&&(yield u),n=this.segments.get(i),ke(n,"No segments for starting representation"),u=this.initData.get(i),!(!(u instanceof ArrayBuffer)||!this.sourceBuffer||!V(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(u,this.downloadAbortController.signal),r)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=i,yield this.dropBuffer();else{let o=this.getCurrentPosition();Zt(o)&&!this.isLive&&(this.bufferLimit=this.forwardBufferTarget,yield this.pruneBuffer(o,1/0,!0)),this.downloadingRepresentationId=i,this.switchingToRepresentationId=void 0}this.maintain()}}.bind(this))(e,t))}warmUpMediaSource(){!ce(this.sourceBuffer)&&!this.sourceBuffer.updating&&(this.sourceBuffer.mode="segments")}async abort(){for(let e of this.activeSegments)this.abortSegment(e.segment);return this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new X,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(ce(e)||ce(this.downloadingRepresentationId)||ce(this.playingRepresentationId)||ce(this.sourceBuffer)||!V(this.mediaSource,this.sourceBuffer)||Zt(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.representations.get(this.playingRepresentationId),r=this.segments.get(this.downloadingRepresentationId),s=this.segments.get(this.playingRepresentationId);if(ke(t,`No such representation ${this.downloadingRepresentationId}`),ke(i,`No such representation ${this.playingRepresentationId}`),ce(r)||ce(s))return;let n=r.find(c=>e>=c.time.from&&e<c.time.to);Zt(n)&&isFinite(n.time.from)&&isFinite(n.time.to)&&this.currentSegmentLength$.next(n?.time.to-n.time.from);let u=e,o=100;if(this.playingRepresentationId!==this.downloadingRepresentationId){let c=this.getForwardBufferDuration(e),p=fs(i),f=fs(t),b=this.useSmartRepresentationSwitch&&this.tuning.dash.useNewRepresentationSwitch&&this.tuning.dash.useSmartRepresentationSwitch&&Zt(p)&&Zt(f)&&iB(p.quality,f.quality),S=this.useSmartRepresentationSwitch&&this.tuning.dash.useNewRepresentationSwitch&&this.tuning.dash.useDelayedRepresentationSwitch;if(b||S?u+=Math.min(c,this.tuning.dash.representationSwitchForwardBufferGap):n&&n.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&c>=n.time.to-e+o&&(u=n?n.time.to+o:-1/0),this.tuning.dash.useNewRepresentationSwitch){let T=this.segments.entries().map(([E,y])=>{let w=y.find(k=>e>=k.time.from&&e<k.time.to);return{representationId:E,status:w?.status}}).find(E=>E.status==="fed")?.representationId;if(!T)return;this.playingRepresentationId=T,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId))}}if(isFinite(this.bufferLimit)&&mr(this.sourceBuffer.buffered)>=this.bufferLimit){let c=ve(this.sourceBuffer.buffered,e),p=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,c<p).catch(f=>{this.handleAsyncError(f,"pruneBuffer")});return}let d=null;if(!this.activeSegments.size&&(d=this.selectForwardBufferSegments(r,t.segmentReference.type,u),d?.length)){let c="auto";if(this.tuning.dash.useFetchPriorityHints&&n)if((0,Mo.default)(d,n))c="high";else{let p=(0,$i.default)(d,0);p&&p.time.from-n.time.to>=this.forwardBufferTarget/2&&(c="low")}this.loadSegments(d,t,c).catch(p=>{this.handleAsyncError(p,"loadSegments")})}(!this.preloadOnly&&!this.allInitsLoaded&&n&&n.status==="fed"&&!d?.length&&ve(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let h=(0,$i.default)(r,-1);!this.isLive&&h&&(this.fullyBuffered$.next(h.time.to-e-ve(this.sourceBuffer.buffered,e)<o),this.onLastSegment$.next(e-h.time.from>0))}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}searchGaps(e,t){this.gaps=[];let i=0,r=this.isLive?this.liveInitialAdditionalOffset:0;for(let s of e)Math.trunc(s.time.from-i)>0&&this.gaps.push({representation:t.id,from:i,to:s.time.from+r,persistent:!0}),i=s.time.to;Zt(t.duration)&&t.duration-i>0&&!this.isLive&&this.gaps.push({representation:t.id,from:i,to:t.duration,persistent:!0})}getActualLiveStartingSegments(e){let t=e.segments,i=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,r=[],s=0,n=t.length-1;do r.unshift(t[n]),s+=t[n].time.to-t[n].time.from,n--;while(s<i&&n>=0);return this.liveInitialAdditionalOffset=s-i,this.isActiveLowLatency()?[r[0]]:r}getLiveSegmentsToLoadState(e){let t=(0,Do.default)(e?.streams[this.kind],r=>r.representations).find(r=>r.id===this.downloadingRepresentationId);if(!t)return;let i=this.segments.get(t.id);if(i?.length)return{from:i[0].time.from,to:i[i.length-1].time.to}}updateLive(e){let t=(0,Do.default)(e?.streams[this.kind],i=>i.representations)??[];if(![...this.segments.values()].every(i=>!i.length))for(let i of t){if(!i||!He(i.segmentReference))return;let r=i.segmentReference.segments.map(l=>({...l,status:"none",size:void 0})),s=100,n=this.segments.get(i.id)??[],u=(0,$i.default)(n,-1)?.time.to??0,o=r?.findIndex(l=>u>=l.time.from+s&&u<=l.time.to+s);if(o===-1){this.liveUpdateSegmentIndex=0;let l=this.getActualLiveStartingSegments(i.segmentReference);this.segments.set(i.id,l)}else{let l=r.slice(o+1);this.segments.set(i.id,[...n,...l])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;ke(e);let t=this.segments.get(e);if(t?.length){let i=t[t.length-1];this.updateLowLatencyLiveIfNeeded(i)}}setSmartRepresentationSwitch(e){this.useSmartRepresentationSwitch=e}updateLowLatencyLiveIfNeeded(e){let t=0;for(let i of this.representations.values()){let r=i.segmentReference;if(!He(r))return;let s=this.segments.get(i.id);if(!s)continue;let n=s.find(o=>Math.floor(o.time.from)===Math.floor(e.time.from));if(n&&!isFinite(n.time.to)&&(n.time.to=e.time.to,t=n.time.to-n.time.from),!!!s.find(o=>Math.floor(o.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let o=Math.round(e.time.to*r.timescale/1e3).toString(10),l=nt(r.segmentTemplateUrl,{segmentTime:o});s.push({status:"none",time:{from:e.time.to,to:1/0},url:l})}}this.currentLowLatencySegmentLength$.next(t)}findSegmentStartTime(e){let t=this.switchingToRepresentationId??this.downloadingRepresentationId??this.playingRepresentationId;if(!t)return;let i=this.segments.get(t);return i?i.find(s=>s.time.from<=e&&s.time.to>=e)?.time.from??void 0:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),this.sourceBufferTaskQueue?.destroy(),this.sourceBufferBufferedDiff?.destroy(),this.gapDetectionIdleCallback&&vt&&vt(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&vt&&vt(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer)try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(e){if(!(e instanceof DOMException&&e.name==="NotFoundError"))throw e}this.sourceBuffer=null,this.downloadAbortController.abort(),this.switchAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,i){return this.checkEjectedSegments(),this.isLive?this.selectForwardBufferSegmentsLive(e,i):this.selectForwardBufferSegmentsRecord(e,t,i)}selectForwardBufferSegmentsLive(e,t){if(this.playingRepresentationId!==this.downloadingRepresentationId){let i=e.findIndex(r=>t>=r.time.from&&t<r.time.to);this.liveUpdateSegmentIndex=i}return this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):null}selectForwardBufferSegmentsRecord(e,t,i){let r=this.getForwardBufferDuration(i),s=e.findIndex(({status:c,time:{from:p,to:f}},b)=>{let S=p<=i&&f>=i,g=p>i||S||b===0&&i===0,T=Math.min(this.forwardBufferTarget,this.bufferLimit),E=this.preloadOnly&&p<=i+T||r<T&&f-p>=T||f<=i+T;return(c==="none"||c==="partially_ejected"&&g&&E&&this.sourceBuffer&&V(this.mediaSource,this.sourceBuffer)&&!(ye(this.sourceBuffer.buffered,p)&&ye(this.sourceBuffer.buffered,f)))&&g&&E});if(s===-1)return null;if(t!=="byteRange")return e.slice(s,s+1);let n=e,u=0,o=0,l=[],d=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,h=this.preloadOnly?this.forwardBufferTarget:0;for(let c=s;c<n.length&&(u<=d||o<=h);c++){let p=n[c];if(u+=p.byte.to+1-p.byte.from,o+=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"){He(t.segmentReference)?await this.loadTemplateSegment(e[0],t,i):await this.loadByteRangeSegments(e,t,i)}async loadTemplateSegment(e,t,i="auto"){e.status="downloading";let r={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(r);let{range:s,url:n,signal:u,onProgress:o,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&u&&(await Jt(u,async function*(){let d=ld(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(h=>setTimeout(h,d))}.bind(this))(),u.aborted&&this.abortActiveSegments([e]));try{let d=await this.fetcher.fetch(n,{range:s,signal:u,onProgress:o,priority:i,isLowLatency:this.isActiveLowLatency(),bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation});if(this.lastDataObtainedTimestampMs=$o(),!d)return;let h=new DataView(d),c=yt(t.mime);if(!isFinite(r.segment.time.to)){let b=t.segmentReference.timescale;r.segment.time.to=c.getChunkEndTime(h,b)}o&&r.feedingBytes&&l?await Promise.all(l):await this.sourceBufferTaskQueue.append(h,u);let{serverDataReceivedTimestamp:p,serverDataPreparedTime:f}=c.getServerLatencyTimestamps(h);p&&f&&this.currentLiveSegmentServerLatency$.next(f-p),r.segment.status="downloaded",this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(d){this.abortActiveSegments([e]),Tt(d)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}updateRepresentationsBaseUrlIfNeeded(){if(!this.tuning.dash.enableBaseUrlSupport||!this.baseUrls.length||this.failedDownloads<=this.tuning.dash.maxSegmentRetryCount)return;this.baseUrlsIndex=(this.baseUrlsIndex+1)%this.baseUrls.length;let e=this.baseUrls[this.baseUrlsIndex];for(let t of this.representations.values())He(t.segmentReference)?t.segmentReference.baseUrl=e:t.segmentReference.url=e}async loadByteRangeSegments(e,t,i="auto"){if(!e.length)return;for(let o of e)o.status="downloading",this.activeSegments.add({segment:o,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:r,url:s,signal:n,onProgress:u}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(await Jt(n,async function*(){let o=ld(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,o),ud(window,"online").pipe(rB()).subscribe(()=>{l(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(s,{range:r,onProgress:u,signal:n,priority:i,bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation}),this.lastDataObtainedTimestampMs=$o(),this.failedDownloads=0}catch(o){this.abortActiveSegments(e),Tt(o)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}prepareByteRangeFetchSegmentParams(e,t){if(He(t.segmentReference))throw new Error("Representation is not byte range type");let i=t.segmentReference.url,r={from:(0,$i.default)(e,0).byte.from,to:(0,$i.default)(e,-1).byte.to},{signal:s}=this.downloadAbortController;return{url:i,range:r,signal:s,onProgress:async(u,o)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=$o(),await this.onSomeByteRangesDataLoaded({dataView:u,loaded:o,signal:s,onSegmentAppendFailed:()=>this.abort(),globalFrom:r?r.from:0,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:ki.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!He(t.segmentReference))throw new Error("Representation is not template type");let i=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&i.searchParams.set("low-latency","yes");let r=i.toString(),{signal:s}=this.downloadAbortController,n=[],o=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(l,d)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=$o();let h=this.onSomeTemplateDataLoaded({dataView:l,loaded:d,signal:s,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(h)}catch(h){this.error$.next({id:"SegmentFeeding",category:ki.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:h})}}:void 0;return{url:r,signal:s,onProgress:o,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)(0,Mo.default)(e,t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:r,signal:s}){if(!this.activeSegments.size||!V(this.mediaSource,this.sourceBuffer))return;let n=this.representations.get(t);if(n)for(let u of this.activeSegments){let{segment:o}=u;if(u.representationId===t){if(s.aborted){r();continue}if(u.loadedBytes=i,u.loadedBytes>u.feedingBytes){let l=new DataView(e.buffer,e.byteOffset+u.feedingBytes,u.loadedBytes-u.feedingBytes),d=yt(n.mime).parseFeedableSegmentChunk(l,this.isLive);d?.byteLength&&(o.status="partially_fed",u.feedingBytes+=d.byteLength,await this.sourceBufferTaskQueue.append(d),u.fedBytes+=d.byteLength)}}}}async onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:s,onSegmentAppendFailed:n}){if(!this.activeSegments.size||!V(this.mediaSource,this.sourceBuffer))return;let u=this.representations.get(t);if(u)for(let o of this.activeSegments){if(o.representationId!==t)continue;if(s.aborted){await n();continue}let{segment:l}=o,d=l.byte.from-i,h=l.byte.to-i,c=h-d+1,p=d<r,f=h<=r;if(p){if(l.status==="downloading"&&f){l.status="downloaded";let b=new DataView(e.buffer,e.byteOffset+d,c);await this.sourceBufferTaskQueue.append(b,s)&&!s.aborted?this.onSegmentFullyAppended(o,t):await n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(l.status==="downloading"||l.status==="partially_fed")&&(o.loadedBytes=Math.min(c,r-d),o.loadedBytes>o.feedingBytes)){let b=new DataView(e.buffer,e.byteOffset+d+o.feedingBytes,o.loadedBytes-o.feedingBytes),S=o.loadedBytes===c?b:yt(u.mime).parseFeedableSegmentChunk(b);S?.byteLength&&(l.status="partially_fed",o.feedingBytes+=S.byteLength,await this.sourceBufferTaskQueue.append(S,s)&&!s.aborted?(o.fedBytes+=S.byteLength,o.fedBytes===c&&this.onSegmentFullyAppended(o,t)):await n())}}}}onSegmentFullyAppended(e,t){if(!(ce(this.sourceBuffer)||!V(this.mediaSource,this.sourceBuffer))){!this.isLive&&B.browser.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(ye(this.sourceBuffer.buffered,e.segment.time.from,100)&&ye(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:ki.VIDEO_PIPELINE,message:"Browser stuck on empty result of adding segment to source buffer"})),this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status="fed",od(e.segment)&&(e.segment.size=e.fedBytes);for(let i of this.representations.values()){if(i.id===t)continue;let r=this.segments.get(i.id);if(r)for(let s of r)s.status==="fed"&&Math.round(s.time.from)===Math.round(e.segment.time.from)&&Math.round(s.time.to)===Math.round(e.segment.time.to)&&(s.status="none")}this.isActiveLowLatency()&&this.updateLowLatencyLiveIfNeeded(e.segment),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,e.segment)}}abortSegment(e){e.status==="partially_fed"?e.status="partially_ejected":e.status!=="partially_ejected"&&(e.status="none");for(let t of this.activeSegments.values())if(t.segment===e){this.activeSegments.delete(t);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(let[r,s]of this.initData.entries()){let n=s instanceof Promise;t||=n,s===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let i=this.representations.get(e);i&&(this.initLoadIdleCallback=fr(()=>(0,$T.default)(this.loadInit(i,"low",!1),()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",i=!1){let r=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!i&&this.failedDownloads>0?Jt(this.destroyAbortController.signal,async function*(){let u=ld(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(o=>setTimeout(o,u))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,yt(e.mime),r)).then(u=>{if(!u)return;let{init:o,dataView:l,segments:d}=u,h=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,h);let c=d;this.isLive&&He(e.segmentReference)&&(c=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,c),o&&this.parsedInitData.set(e.id,o)}).then(()=>this.failedDownloads=0,u=>{this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:ki.WTF,message:"loadInit threw",thrown:u})});return this.initData.set(e.id,n),n}async dropBuffer(){for(let e of this.segments.values())for(let t of e)t.status="none";await this.pruneBuffer(0,1/0,!0)}async pruneBuffer(e,t,i=!1){if(!this.sourceBuffer||!V(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||ce(e))return!1;this.checkEjectedSegments();let r=[],s=0,n=u=>{if(s>=t)return;r.push({...u.time});let o=od(u)?u.size??0:u.byte.to-u.byte.from;s+=o};for(let u of this.segments.values())for(let o of u){let l=o.time.to<=e-this.tuning.dash.bufferPruningSafeZone,d=o.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(l||d)&&o.status==="fed"&&n(o)}for(let u=0;u<this.sourceBuffer.buffered.length;u++){let o=this.sourceBuffer.buffered.start(u)*1e3,l=this.sourceBuffer.buffered.end(u)*1e3,d=0;for(let h of this.segments.values())for(let c of h)(0,Mo.default)(["none","partially_ejected"],c.status)&&Math.round(c.time.from)<=Math.round(o)&&Math.round(c.time.to)>=Math.round(l)&&d++;if(d===this.segments.size){let h={time:{from:o,to:l},url:"",status:"none"};n(h)}}if(r.length&&i){let u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let o of this.segments.values())for(let l of o)l.time.from>=e+u&&l.status==="fed"&&n(l)}return r.length?(r=kT(r),(await Promise.all(r.map(o=>this.sourceBufferTaskQueue.remove(o.from,o.to)))).reduce((o,l)=>o||l,!1)):!1}async abortBuffer(){if(!this.sourceBuffer||!V(this.mediaSource,this.sourceBuffer))return!1;let e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;return this.sourceBufferTaskQueue.abort(t)}getDebugBufferState(){if(!(!this.sourceBuffer||!V(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}getBufferedTo(){return!this.sourceBuffer||!V(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length?null:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}getForwardBufferDuration(e=this.getCurrentPosition()){return!this.sourceBuffer||!V(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||ce(e)?0:ve(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!this.sourceBuffer||!V(this.mediaSource,this.sourceBuffer))return;let{buffered:i}=this.sourceBuffer;this.tuning.useRefactoredSearchGap&&(this.gaps=this.gaps.filter(s=>{if(s.persistent)return!0;let n=Math.round(s.from),u=Math.round(s.to);for(let o=0;o<i.length;o++)if(n>=Math.round(i.start(o)*1e3)&&u<=Math.round(i.end(o)*1e3))return!1;return!0}));let r={representation:e,from:t.time.from,to:t.time.to,persistent:!1};for(let s=0;s<i.length;s++){let n=i.start(s)*1e3,u=i.end(s)*1e3;if(!(u<=t.time.from||n>=t.time.to)){if(n<=t.time.from&&u>=t.time.to){r=void 0;break}u>t.time.from&&u<t.time.to&&(r.from=u),n<t.time.to&&n>t.time.from&&(r.to=n)}}r&&r.to-r.from>1&&!this.gaps.some(s=>r&&s.from===r.from&&s.to===r.to)&&this.gaps.push(r)}detectGapsWhenIdle(e,t){if(!(this.gapDetectionIdleCallback||!this.sourceBuffer||!V(this.mediaSource,this.sourceBuffer))){if(!this.tuning.useRefactoredSearchGap)for(let i=0;i<this.sourceBuffer.buffered.length;i++)this.gaps=this.gaps.filter(r=>r.persistent||this.sourceBuffer&&(Math.round(r.from)<Math.round(this.sourceBuffer.buffered.start(i)*1e3)||Math.round(r.to)>Math.round(this.sourceBuffer.buffered.end(i)*1e3)));this.gapDetectionIdleCallback=fr(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:ki.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if(ce(this.sourceBuffer)||!V(this.mediaSource,this.sourceBuffer)||ce(this.playingRepresentationId)||this.sourceBufferBufferedDiff&&!this.sourceBufferBufferedDiff.wasUpdated())return;let e=ko(this.sourceBuffer.buffered),t=100;for(let i of this.segments.values())for(let r of i){let{status:s}=r;if(s!=="fed"&&s!=="partially_ejected")continue;let n=Math.floor(r.time.from),u=Math.ceil(r.time.to),o=!1,l=0;for(let d=0;d<e.length;d+=2){let h=e[d],c=e[d+1];o||(o=h-t<=n&&c+t>=u),(n>=h&&n<c-t||u>h+t&&u<=c)&&(l+=1)}o||(l===1?r.status="partially_ejected":this.gaps.some(d=>d.from===r.time.from||d.to===r.time.to)?r.status="partially_ejected":r.status="none")}}handleAsyncError(e,t){this.error$.next({id:t,category:ki.VIDEO_PIPELINE,thrown:e,message:"Something went wrong"})}calculateDurationFromSegments(){if(!this.playingRepresentationId)return 0;let e=this.segments.get(this.playingRepresentationId);return(e?(0,$i.default)(e,-1)?.time.to:0)||0}};import{abortable as bs,assertNever as MT,fromEvent as DT,merge as nB,now as gs,Subject as Rr,ValueSubject as cd,flattenObject as kr,ErrorCategory as Ss,SubscriptionRemovable as oB}from"@vkontakte/videoplayer-shared";var Bo=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:s=!1}){this.manifestRequested=new Rr;this.manifestReceived=new Rr;this.firstBytesRequested=new Rr;this.firstBytesReceived=new Rr;this.lastConnectionType$=new cd(void 0);this.lastConnectionReused$=new cd(void 0);this.lastRequestFirstBytes$=new cd(void 0);this.recoverableError$=new Rr;this.error$=new Rr;this.abortAllController=new X;this.subscription=new oB;this.fetchManifest=bs(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=Yt(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=uo(i)),this.manifestRequested.next();let r=yield this.doFetch(i,{signal:this.abortAllController.signal}).catch(Co);return r?(t.log("success",kr({url:i,message:"Request successfully executed"})),t.end(),this.manifestReceived.next(),this.onHeadersReceived(r.headers),r.text()):(t.error("error",kr({url:i,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=bs(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:i,onProgress:r,priority:s="auto",signal:n,measureThroughput:u=!0,isLowLatency:o=!1,bufferOptimisation:l=!1}={}){let d=e,h=new Headers,c=this.tracer.createComponentTracer("Fetch");if(i)switch(t){case 0:{h.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let v=new URL(d,location.href);v.searchParams.append("bytes",`${i.from}-${i.to}`),d=v.toString();break}default:MT(t)}this.requestQuic&&(d=Yt(d));let p=this.abortAllController.signal,f;if(n){let v=new X;if(f=nB(DT(this.abortAllController.signal,"abort"),DT(n,"abort")).subscribe(()=>{try{v.abort()}catch(x){Co(x)}}),this.subscription.add(f),this.abortAllController.signal.aborted||n.aborted)try{v.abort()}catch(x){Co(x)}p=v.signal}let b=0,S=gs();c.log("startRequest",kr({url:d,priority:s,rangeMethod:t,range:i,isLowLatency:o,requestStartedAt:S})),this.firstBytesRequested.next();let g=yield this.doFetch(d,{priority:s,headers:h,signal:p}),T=gs();if(!g)return c.error("error",{message:"No response in request"}),c.end(),this.unsubscribeAbortSubscription(f),null;if(this.throughputEstimator?.addRawRtt(T-S),!g.ok||!g.body){this.unsubscribeAbortSubscription(f);let v=`Fetch error ${g.status}: ${g.statusText}`;return c.error("error",{message:v}),c.end(),Promise.reject(new Error(`Fetch error ${g.status}: ${g.statusText}`))}if(this.onHeadersReceived(g.headers),!r&&!u){this.unsubscribeAbortSubscription(f);let v=gs(),x={requestStartedAt:S,requestEndedAt:v,duration:v-S};return c.log("endRequest",kr(x)),c.end(),g.arrayBuffer()}let E=g.body;if(u){let v;[E,v]=g.body.tee(),this.throughputEstimator?.trackStream(v,o)}let y=E.getReader(),w,k=parseInt(g.headers.get("content-length")??"",10);Number.isFinite(k)&&(w=k),!w&&i&&(w=i.to-i.from+1);let $=w?new Uint8Array(w):new Uint8Array(0),A=!1,L=v=>{this.unsubscribeAbortSubscription(f),A=!0,Co(v)},I=bs(p,async function*({done:v,value:x}){if(b===0&&(this.lastRequestFirstBytes$.next(gs()-S),this.firstBytesReceived.next()),p.aborted){this.unsubscribeAbortSubscription(f);return}if(!v&&x){if(l&&w)$.set(x,b),b+=x.byteLength;else{let z=new Uint8Array($.length+x.length);z.set($),z.set(x,$.length),$=z,b+=x.byteLength}r?.(new DataView($.buffer),b),yield y?.read().then(I,L)}}.bind(this));yield y?.read().then(I,L),this.unsubscribeAbortSubscription(f);let q=gs(),M={failed:A,requestStartedAt:S,requestEndedAt:q,duration:q-S};return A?(c.error("endRequest",kr(M)),c.end(),null):(c.log("endRequest",kr(M)),c.end(),$.buffer)}.bind(this));this.fetchByteRangeRepresentation=bs(this.abortAllController.signal,async function*(e,t,i){if(e.type!=="byteRange")return null;let{from:r,to:s}=e.initRange,n=r,u=s,o=!1,l,d;e.indexRange&&(l=e.indexRange.from,d=e.indexRange.to,o=s+1===l,o&&(n=Math.min(l,r),u=Math.max(d,s))),n=Math.min(n,0);let h=yield this.fetch(e.url,{range:{from:n,to:u},priority:i,measureThroughput:!1});if(!h)return null;let c=new DataView(h,r-n,s-n+1);if(!t.validateData(c))throw new Error("Invalid media file");let p=t.parseInit(c),f=e.indexRange??t.getIndexRange(p);if(!f)throw new ReferenceError("No way to load representation index");let b;if(o)b=new DataView(h,f.from-n,f.to-f.from+1);else{let g=yield this.fetch(e.url,{range:f,priority:i,measureThroughput:!1});if(!g)return null;b=new DataView(g)}let S=t.parseSegments(b,p,f);return{init:p,dataView:new DataView(h),segments:S}}.bind(this));this.fetchTemplateRepresentation=bs(this.abortAllController.signal,async function*(e,t){if(e.type!=="template")return null;let i=new URL(e.initUrl,e.baseUrl).toString(),r=yield this.fetch(i,{priority:t,measureThroughput:!1});return r?{init:null,segments:e.segments.map(n=>({...n,status:"none",size:void 0})),dataView:new DataView(r)}:null}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=r,this.tracer=i.createComponentTracer("Fetcher"),this.useEnableSubtitlesParam=s}onHeadersReceived(e){let{type:t,reused:i}=oo(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}async fetchRepresentation(e,t,i="auto"){let{type:r}=e;switch(r){case"byteRange":return await this.fetchByteRangeRepresentation(e,t,i)??null;case"template":return await this.fetchTemplateRepresentation(e,i)??null;default:MT(r)}}destroy(){this.abortAllController.abort(),this.tracer.end(),this.subscription.unsubscribe()}async doFetch(e,t){let i=await Xe(e,t);if(i.ok)return i;let r=await i.text(),s=parseInt(r);if(!isNaN(s))switch(s){case 1:this.recoverableError$.next({id:"VideoDataLinkExpiredError",message:"Video data links have expired",category:Ss.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:Ss.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:Ss.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:Ss.FATAL});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${s})`,category:Ss.FATAL})}}unsubscribeAbortSubscription(e){e&&(e.unsubscribe(),this.subscription.remove(e))}},Co=a=>{if(!Tt(a))throw a};import{isNullable as uB,ValueSubject as lB}from"@vkontakte/videoplayer-shared";var vs=class a{constructor(e,t){this.currentRepresentation$=new lB(null);this.maxRepresentations=4;this.representationsCursor=0;this.representations=[];this.currentSegment=null;this.getCurrentPosition=t.getCurrentPosition,this.processStreams(e)}updateLive(e){this.processStreams(e?.streams.text)}seekLive(e){this.processStreams(e)}maintain(e=this.getCurrentPosition()){if(!uB(e))for(let t of this.representations)for(let i of t){let r=i.segmentReference,s=r.segments.length,n=r.segments[0].time.from,u=r.segments[s-1].time.to;if(e<n||e>u)continue;let o=r.segments.find(l=>l.time.from<=e&&l.time.to>=e);!o||this.currentSegment?.time.from===o.time.from&&this.currentSegment.time.to===o.time.to||(this.currentSegment=o,this.currentRepresentation$.next({...i,label:"Live Text",language:"ru",isAuto:!0,url:new URL(o.url,r.baseUrl).toString()}))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e??[]){let i=a.filterRepresentations(t.representations);if(i){this.representations[this.representationsCursor]=i,this.representationsCursor=(this.representationsCursor+1)%this.maxRepresentations;break}}}static isSupported(e){return!!e?.some(t=>a.filterRepresentations(t.representations))}static filterRepresentations(e){return e?.filter(t=>t.kind==="text"&&"segmentReference"in t&&He(t.segmentReference))}};var fB=["progress","play","seeked","stalled","waiting"],mB=["timeupdate","progress","loadeddata","playing","seeked"];var _o=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.bufferManagers=[];this.subscription=new md;this.representationSubscription=new md;this.state$=new F("none");this.currentVideoRepresentation$=new te(void 0);this.currentVideoRepresentationInit$=new te(void 0);this.currentAudioRepresentation$=new te(void 0);this.currentVideoSegmentLength$=new te(0);this.currentAudioSegmentLength$=new te(0);this.error$=new ei;this.manifestRequested=new ei;this.manifestReceived=new ei;this.firstBytesRequested=new ei;this.firstBytesReceived=new ei;this.lastConnectionType$=new te(void 0);this.lastConnectionReused$=new te(void 0);this.lastRequestFirstBytes$=new te(void 0);this.currentLiveTextRepresentation$=new te(null);this.isLive$=new te(!1);this.isActiveLive$=new te(!1);this.isLowLatency$=new te(!1);this.liveDuration$=new te(0);this.liveSeekableDuration$=new te(0);this.liveAvailabilityStartTime$=new te(0);this.liveStreamStatus$=new te(void 0);this.bufferLength$=new te(0);this.liveLatency$=new te(void 0);this.liveLoadBufferLength$=new te(0);this.livePositionFromPlayer$=new te(0);this.currentStallDuration$=new te(0);this.videoLastDataObtainedTimestamp$=new te(0);this.fetcherRecoverableError$=new ei;this.fetcherError$=new ei;this.liveStreamEndTimestamp=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.forceEnded$=new ei;this.gapWatchdogActive=!1;this.destroyController=new X;this.initManifest=pd(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=se(t,i,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),this.manifest?.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:ut.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=pd(this.destroyController.signal,async function*(){this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(o=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:ut.NETWORK,message:"Failed to load manifest",thrown:o})});if(!e)return null;let t=null;try{t=ro(e??"",this.manifestUrlString)}catch(o){let l=to(e)??{id:"ManifestParsing",category:ut.PARSER,message:"Failed to parse MPD manifest",thrown:o};this.error$.next(l)}if(!t)return null;let i=(o,l,d)=>!!(this.element?.canPlayType?.(l)&&Ue()?.isTypeSupported?.(`${l}; codecs="${d}"`)||o==="text");if(t.live){this.isLive$.next(!!t.live);let{availabilityStartTime:o,latestSegmentPublishTime:l,streamIsUnpublished:d,streamIsAlive:h}=t.live,c=(t.duration??0)/1e3;this.liveSeekableDuration$.next(-1*c),this.liveDuration$.next((l-o)/1e3),this.liveAvailabilityStartTime$.next(t.live.availabilityStartTime);let p="active";h||(p=d?"unpublished":"unexpectedly_down"),this.liveStreamStatus$.next(p)}let r={text:t.streams.text,video:[],audio:[]},s,n;for(let o of["video","audio"]){let d=t.streams[o].filter(({mime:c,codecs:p})=>i(o,c,p));r[o]=d;let h;if(this.tuning.dash.codecsPrioritizeEnabled){let c=d.map(({codecs:p})=>p);o==="audio"&&(n=yo(c),h=n[0]),o==="video"&&(s=vo(c),this.forceVideoCodec&&(0,_T.default)(s,this.forceVideoCodec)?h=this.forceVideoCodec:h=s[0]),h&&(r[o]=d.filter(({codecs:p})=>Er(p)===h))}else{let c=new Set(d.map(({codecs:p})=>p));h=So(c),h&&(r[o]=d.filter(({codecs:p})=>p.startsWith(h)))}if(o==="video"){let c=this.tuning.preferHDR,p=r.video.some(b=>b.hdr),f=r.video.some(b=>!b.hdr);B.display.isHDR&&c&&p?r.video=r.video.filter(b=>b.hdr):f&&(r.video=r.video.filter(b=>!b.hdr))}}let u={...t,streams:r};return this.tuning.dash.codecsPrioritizeEnabled&&(u.codecs={video:s,audio:n}),this.tracer.log("updateManifestEnd",Ts(u)),u}.bind(this));this.initRepresentations=pd(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initRepresentationsStart",Ts({initialVideo:e,initialAudio:t,sourceHls:i})),Lr(this.manifest),Lr(this.element),this.representationSubscription.unsubscribe(),this.representationSubscription=new md,this.state$.startTransitionTo("representations_ready");let r=c=>{this.representationSubscription.add(It(c,"error").pipe(Vo(p=>!!this.element?.played.length)).subscribe(p=>{this.error$.next({id:"VideoSource",category:ut.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:p})}))};this.source=Ln();let s=document.createElement("source");if(r(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),rr())if(i){let c=document.createElement("source");r(c),c.type="application/x-mpegurl",c.src=i.url,this.element.appendChild(c)}else this.element.disableRemotePlayback=!0;this.isActiveLive$.next(this.isLive$.getValue());let n={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),manifest:this.manifest},u=this.manifest.streams.video.reduce((c,p)=>[...c,...p.representations],[]);if(this.videoBufferManager=new ms("video",this.source,u,n),this.bufferManagers=[this.videoBufferManager],Is(t)){let c=this.manifest.streams.audio.reduce((p,f)=>[...p,...f.representations],[]);this.audioBufferManager=new ms("audio",this.source,c,n),this.bufferManagers.push(this.audioBufferManager)}vs.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new vs(this.manifest.streams.text,n)),this.representationSubscription.add(this.fetcher.manifestRequested.subscribe(this.manifestRequested)),this.representationSubscription.add(this.fetcher.manifestReceived.subscribe(this.manifestReceived)),this.representationSubscription.add(this.fetcher.firstBytesRequested.subscribe(this.firstBytesRequested)),this.representationSubscription.add(this.fetcher.firstBytesReceived.subscribe(this.firstBytesReceived)),this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$));let o=()=>{this.stallWatchdogSubscription?.unsubscribe(),this.currentStallDuration$.next(0)};if(this.representationSubscription.add(Mi(...mB.map(c=>It(this.element,c))).pipe(Mr(c=>this.element?ve(this.element.buffered,this.element.currentTime*1e3):0),ys(),hB(c=>{c>this.tuning.dash.bufferEmptinessTolerance&&o()})).subscribe(this.bufferLength$)),this.representationSubscription.add(Mi(It(this.element,"ended"),this.forceEnded$).subscribe(()=>{o()})),this.isLive$.getValue()){this.subscription.add(this.liveDuration$.pipe(ys()).subscribe(p=>this.liveStreamEndTimestamp=fd())),this.subscription.add(It(this.element,"pause").subscribe(()=>{this.livePauseWatchdogSubscription=hd(1e3).subscribe(p=>{let f=Ut(this.manifestUrlString,2);this.manifestUrlString=se(this.manifestUrlString,f+1e3,2),this.liveStreamStatus$.getValue()==="active"&&this.updateManifest()}),this.subscription.add(this.livePauseWatchdogSubscription)})).add(It(this.element,"play").subscribe(p=>this.livePauseWatchdogSubscription?.unsubscribe())),this.representationSubscription.add($r({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(Mr(({isActiveLive:p,isLowLatency:f})=>p&&f),ys()).subscribe(p=>{this.isManualDecreasePlaybackInLive()||Ir(this.element,1)})),this.representationSubscription.add($r({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(Vo(({bufferLength:p,isActiveLive:f,isLowLatency:b})=>f&&b&&!!p)).subscribe(({bufferLength:p})=>this.liveBuffer.next(p))),this.representationSubscription.add(this.videoBufferManager.currentLowLatencySegmentLength$.subscribe(p=>{if(!this.isActiveLive$.getValue()&&!this.isLowLatency$.getValue()&&!p)return;let f=this.liveSeekableDuration$.getValue()-p/1e3;this.liveSeekableDuration$.next(Math.max(f,-1*this.tuning.dashCmafLive.maxLiveDuration)),this.liveDuration$.next(this.liveDuration$.getValue()+p/1e3)})),this.representationSubscription.add($r({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe(Vo(({isLive:p})=>p),ys((p,f)=>f.bufferLength<p.bufferLength),Mr(({rtt:p,bufferLength:f,segmentServerLatency:b})=>{let S=Ut(this.manifestUrlString,2);return(p/2+f+b+S)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add($r({liveBuffer:this.liveBuffer.smoothed$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).subscribe(({liveBuffer:p,isActiveLive:f,isLowLatency:b})=>{if(!b||!f)return;let S=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,g=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,T=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,E=p-S;if(this.isManualDecreasePlaybackInLive())return;let y=1;Math.abs(E)>g&&(y=1+Math.sign(E)*T),Ir(this.element,y)})),this.representationSubscription.add(this.bufferLength$.subscribe(p=>{let f=0;if(p){let b=(this.element?.currentTime??0)*1e3;f=Math.min(...this.bufferManagers.map(g=>g.getLiveSegmentsToLoadState(this.manifest)?.to??b))-b}this.liveLoadBufferLength$.getValue()!==f&&this.liveLoadBufferLength$.next(f)}));let c=0;this.representationSubscription.add($r({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(VT(1e3)).subscribe(async({liveLoadBufferLength:p,bufferLength:f})=>{if(!this.element||this.isUpdatingLive)return;let b=this.element.playbackRate,S=Ut(this.manifestUrlString,2),g=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,T=Math.min(g,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*b),E=this.tuning.dashCmafLive.normalizedActualBufferOffset*b,y=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*b,w=isFinite(p)?p:f,k=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),$=g<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next($);let A="none";if(k?A="active_low_latency":this.isLowLatency$.getValue()&&$?(this.bufferManagers.forEach(L=>L.proceedLowLatencyLive()),A="active_low_latency"):S!==0&&w<T?A="live_forward_buffering":w<T+y&&(A="live_with_target_offset"),isFinite(p)&&(c=p>c?p:c),A==="live_forward_buffering"||A==="live_with_target_offset"){let L=c-(T+E),I=this.normolizeLiveOffset(Math.trunc(S+L/b)),q=Math.abs(I-S),M=0;!p||q<=this.tuning.dashCmafLive.offsetCalculationError?M=S:I>0&&q>this.tuning.dashCmafLive.offsetCalculationError&&(M=I),this.manifestUrlString=se(this.manifestUrlString,M,2)}(A==="live_with_target_offset"||A==="live_forward_buffering")&&(c=0,await this.updateLive())},p=>{this.error$.next({id:"updateLive",category:ut.VIDEO_PIPELINE,thrown:p,message:"Failed to update live with subscription"})}))}let l=Mi(...this.bufferManagers.map(c=>c.fullyBuffered$)).pipe(Mr(()=>this.bufferManagers.every(c=>c.fullyBuffered$.getValue()))),d=Mi(...this.bufferManagers.map(c=>c.onLastSegment$)).pipe(Mr(()=>this.bufferManagers.some(c=>c.onLastSegment$.getValue()))),h=$r({allBuffersFull:l,someBufferEnded:d}).pipe(ys(),Mr(({allBuffersFull:c,someBufferEnded:p})=>c&&p),Vo(c=>c));if(this.representationSubscription.add(Mi(this.forceEnded$,h).subscribe(()=>{if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(c=>!c.updating))try{this.source?.endOfStream()}catch(c){this.error$.next({id:"EndOfStream",category:ut.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:c})}})),this.representationSubscription.add(Mi(...this.bufferManagers.map(c=>c.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.representationSubscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&(this.representationSubscription.add(this.audioBufferManager.playingRepresentation$.subscribe(this.currentAudioRepresentation$)),this.representationSubscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$))),this.liveTextManager&&this.representationSubscription.add(this.liveTextManager.currentRepresentation$.subscribe(this.currentLiveTextRepresentation$)),this.source.readyState!=="open"){let c=this.tuning.dash.sourceOpenTimeout>=0;yield new Promise(p=>{c&&(this.timeoutSourceOpenId=setTimeout(()=>{if(this.source?.readyState==="open"){p();return}this.error$.next({id:"OpenOfStream",category:ut.VIDEO_PIPELINE,message:"Failed to open MediaSource",thrown:new Error("Timeout reject when wait sourceopen event"),traceAsLog:!0})},this.tuning.dash.sourceOpenTimeout)),this.source?.addEventListener("sourceopen",()=>{this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),p()},{once:!0})})}if(!this.isLive$.getValue()){let c=[this.manifest.duration??0,...(0,bd.default)((0,bd.default)([...this.manifest.streams.audio,...this.manifest.streams.video],p=>p.representations),p=>{let f=[];return p.duration&&f.push(p.duration),He(p.segmentReference)&&p.segmentReference.totalSegmentsDurationMs&&f.push(p.segmentReference.totalSegmentsDurationMs),f})];this.source.duration=Math.max(...c)/1e3}this.audioBufferManager&&Is(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState("representations_ready"),this.tracer.log("initRepresentationsEnd")}.bind(this));this.tick=()=>{if(!this.element||!this.videoBufferManager||this.source?.readyState!=="open")return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),this.audioBufferManager?.maintain(e),this.liveTextManager?.maintain(e),(this.videoBufferManager.gaps.length||this.audioBufferManager?.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=hd(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),t=>{this.error$.next({id:"GapWatchdog",category:ut.WTF,message:"Error handling gaps",thrown:t})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name),this.forceVideoCodec=e.forceVideoCodec,this.fetcher=new Bo({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer,useEnableSubtitlesParam:e.tuning.useEnableSubtitlesParam}),this.subscription.add(this.fetcher.recoverableError$.subscribe(this.fetcherRecoverableError$)),this.subscription.add(this.fetcher.error$.subscribe(this.fetcherError$)),this.liveBuffer=Mt.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.bufferEstimator}),this.initTracerSubscription()}setSmartRepresentationSwitch(e){this.bufferManagers.forEach(t=>t.setSmartRepresentationSwitch(e))}async seekLive(e){Lr(this.element);let t=this.liveStreamStatus$.getValue()!=="active"?fd()-this.liveStreamEndTimestamp:0,i=this.normolizeLiveOffset(e+t);this.isActiveLive$.next(i===0),this.manifestUrlString=se(this.manifestUrlString,i,2),this.manifest=await this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,await this.videoBufferManager?.seekLive(this.manifest.streams.video),await this.audioBufferManager?.seekLive(this.manifest.streams.audio),this.liveTextManager?.seekLive(this.manifest.streams.text))}initBuffer(){Lr(this.element),this.state$.setState("running");let e=It(this.element,"timeupdate");this.tuning.dash.timeupdateEventTickThrottle&&(e=e.pipe(VT(this.tuning.dash.timeupdateEventTickThrottle))),this.subscription.add(Mi(...fB.map(t=>It(this.element,t)),It(window,"online"),e).subscribe(()=>this.tick(),t=>{this.error$.next({id:"DashVKPlayer",category:ut.WTF,message:"Internal logic error",thrown:t})})),this.subscription.add(It(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===HTMLMediaElement.HAVE_CURRENT_DATA&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(It(this.element,"waiting").subscribe(()=>{this.element&&this.element.readyState===HTMLMediaElement.HAVE_CURRENT_DATA&&!this.element.seeking&&ye(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let t=()=>{if(!this.element||this.source?.readyState!=="open")return;let i=this.currentStallDuration$.getValue();i+=50,this.currentStallDuration$.next(i);let r={timeInWaiting:i},s=fd(),n=100,u=this.videoBufferManager?.lastDataObtainedTimestamp??0;this.videoLastDataObtainedTimestamp$.next(u);let o=this.audioBufferManager?.lastDataObtainedTimestamp??0,l=this.videoBufferManager?.getForwardBufferDuration()??0,d=this.audioBufferManager?.getForwardBufferDuration()??0,h=l<n&&s-u>this.tuning.dash.crashOnStallTWithoutDataTimeout,c=this.audioBufferManager&&d<n&&s-o>this.tuning.dash.crashOnStallTWithoutDataTimeout;if((h||c)&&i>this.tuning.dash.crashOnStallTWithoutDataTimeout||i>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${i} ms`);if(this.isLive$.getValue()&&i%2e3===0){let p=this.normolizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);this.seekLive(p).catch(f=>{this.error$.next({id:"stallIntervalCallback",category:ut.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:f})}),r.liveLastOffset=p}else{let p=this.element.currentTime*1e3;this.videoBufferManager?.maintain(p),this.audioBufferManager?.maintain(p),r.position=p}this.tracer.log("stallIntervalCallback",Ts(r))};this.stallWatchdogSubscription?.unsubscribe(),this.stallWatchdogSubscription=hd(50).subscribe(t,i=>{this.error$.next({id:"StallWatchdogCallback",category:ut.NETWORK,message:"Can't restore DASH after stall.",thrown:i})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t,i=!1){let r={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return this.tuning.useNewSwitchTo?this.currentStallDuration$.getValue()>0?r?.switchToWithPreviousAbort(t,i):r?.switchTo(t,i):r?.switchToOld(t,i)}async seek(e,t){Lr(this.element),Lr(this.videoBufferManager);let i;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?i=e:i=Math.max(this.videoBufferManager.findSegmentStartTime(e)??e,this.audioBufferManager?.findSegmentStartTime(e)??e),this.warmUpMediaSourceIfNeeded(i),ye(this.element.buffered,i)||await Promise.all([this.videoBufferManager.abort(),this.audioBufferManager?.abort()]),!(BT(this.element)||BT(this.videoBufferManager))&&(this.videoBufferManager.maintain(i),this.audioBufferManager?.maintain(i),this.element.currentTime=i/1e3,this.tracer.log("seek",Ts({requestedPosition:e,forcePrecise:t,position:i})))}warmUpMediaSourceIfNeeded(e=this.element?.currentTime){Is(this.element)&&Is(this.source)&&Is(e)&&this.source?.readyState==="ended"&&this.element.duration*1e3-e>this.tuning.dash.seekBiasInTheEnd&&this.bufferManagers.forEach(t=>t.warmUpMediaSource())}get isStreamEnded(){return this.source?.readyState==="ended"}stop(){this.tracer.log("stop"),this.element?.querySelectorAll("source").forEach(e=>{URL.revokeObjectURL(e.src),e.remove()}),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),this.videoBufferManager?.destroy(),this.videoBufferManager=null,this.audioBufferManager?.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getStreams(){return this.manifest?.streams}getCodecs(){return this.manifest?.codecs}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),this.source?.readyState==="open"&&Array.from(this.source.sourceBuffers).every(e=>!e.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}initTracerSubscription(){let e=pB(this.tracer.error.bind(this.tracer));this.subscription.add(this.error$.subscribe(e("error")))}isManualDecreasePlaybackInLive(){return!this.element||!this.isLive$.getValue()?!1:1-this.element.playbackRate>this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}async updateLive(){this.isUpdatingLive=!0,this.manifest=await this.updateManifest(),this.manifest&&(this.bufferManagers.forEach(e=>e.updateLive(this.manifest)),this.liveTextManager?.updateLive(this.manifest)),this.isUpdatingLive=!1}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.getBufferedTo();if(e===null)return;let t=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),i=this.isJumpGapAfterSeekLive,r=this.element.currentTime;this.isJumpGapAfterSeekLive&&!t&&this.element.currentTime>e&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let s=this.element.currentTime*1e3,n=null,u=this.element.readyState===HTMLMediaElement.HAVE_METADATA?this.tuning.endGapTolerance:0;for(let o of this.bufferManagers)for(let l of o.gaps)(l.persistent||o.playingRepresentation$.getValue()===l.representation)&&l.from-u<=s&&l.to+u>s&&(this.element.duration*1e3-l.to<this.tuning.endGapTolerance?n=1/0:(n===null||l.to>n)&&(n=l.to));if(n!==null){let o=n+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,o===1/0?this.forceEnded$.next():(this.element.currentTime=o/1e3,this.tracer.log("jumpGap",Ts({isJumpGapAfterSeekLive:i,isActiveLowLatency:t,initialCurrentTime:r,jumpTo:o,resultCurrentTime:this.element.currentTime})))}}calculateDurationFromSegments(){return Math.max(this.videoBufferManager?.calculateDurationFromSegments()||0,this.audioBufferManager?.calculateDurationFromSegments()||0)}};import{combine as bB,map as gB,observeElementSize as SB,Subscription as vB,ValueSubject as gd,noop as yB}from"@vkontakte/videoplayer-shared";var Oo=class{constructor(){this.subscription=new vB;this.pipSize$=new gd(void 0);this.videoSize$=new gd(void 0);this.elementSize$=new gd(void 0);this.pictureInPictureWindowRemoveEventListener=yB}connect({observableVideo:e,video:t}){let i=r=>{let s=r.target;this.pipSize$.next({width:s.width,height:s.height})};this.subscription.add(SB(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(bB({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe(gB(({videoSize:r,inPip:s,pipSize:n})=>s?n:r)).subscribe(this.elementSize$))}getValue(){return this.elementSize$.getValue()}subscribe(e,t){return this.elementSize$.subscribe(e,t)}getObservable(){return this.elementSize$}destroy(){this.pictureInPictureWindowRemoveEventListener(),this.subscription.unsubscribe()}};var Di=class{constructor(e){this.subscription=new RB;this.videoState=new F("stopped");this.observableVideo=null;this.droppedFramesManager=new pr;this.stallsManager=new Ao;this.elementSizeManager=new Oo;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new Qt;this.audioTrackSwitchHistory=new Qt;this.selectedRepresentations={audio:null,video:null};this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(r.state==="requested"&&i?.to!=="paused"&&e!=="stopped"&&t!=="stopped"&&this.seek(r.position,r.forcePrecise),t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.player.stop(),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),P(this.params.desiredState.playbackState,"stopped",!0));return}switch(e){case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();return;case"ready":t==="paused"?(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="ready"&&P(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):t==="playing"&&this.video.paused?this.playIfAllowed():i?.to==="playing"&&P(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&P(this.params.desiredState.playbackState,"paused");return;default:return IB(e)}}};this.init3DScene=e=>{if(this.scene3D)return;this.scene3D=new Pr(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:e.projectionData?.pose.yaw||0,y:e.projectionData?.pose.pitch||0,z:e.projectionData?.pose.roll||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});let t=this.elementSizeManager.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};this.textTracksManager=new Ye(e.source.url),this.params=e,this.video=De(e.container,e.tuning),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Se(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.player=new _o({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode,tracer:this.tracer,forceVideoCodec:this.params.forceVideoCodec}),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params;PB(this.observableVideo)&&(this.observableVideo=Ve(this.video),this.subscription.add(()=>this.observableVideo?.destroy()));let i=this.constructor.name,r=n=>{e.error$.next({id:i,category:OT.WTF,message:`${i} internal logic error`,thrown:n})},s=(n,u)=>this.subscription.add(n.subscribe(u,r));return{output:e,desiredState:t,observableVideo:this.observableVideo,genericErrorListener:r,connect:s}}subscribe(){let{output:e,desiredState:t,observableVideo:i,genericErrorListener:r,connect:s}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe(Sd(h=>!!h.length),NT()).subscribe(h=>{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:h})}));let n=this.params.desiredState.seekState.stateChangeEnded$.pipe(xs(h=>h.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(Sd(FT),NT()),e.firstBytesEvent$),s(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),s(this.videoState.stateChangeEnded$.pipe(xs(h=>h.to)),this.params.output.playbackState$),this.subscription.add(i.looped$.subscribe(()=>this.player.warmUpMediaSourceIfNeeded(),r)),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(mt(this.video,t.isLooped,r)),this.subscription.add(Be(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(ze(this.video,t.playbackRate,i.playbackRateState$,r)),this.elementSizeManager.connect({video:this.video,observableVideo:i}),s(Ke(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),P(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),P(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.params.tuning.changePlaybackStateToPausedWhenEnded&&this.subscription.add(i.ended$.subscribe(()=>{this.videoState.setState("paused"),P(t.playbackState,"paused")})),this.subscription.add(this.player.manifestRequested.subscribe(this.params.output.manifestRequested$)).add(this.player.manifestReceived.subscribe(this.params.output.manifestReceived$)).add(this.player.firstBytesRequested.subscribe(this.params.output.firstBytesRequested$)).add(this.player.firstBytesReceived.subscribe(this.params.output.firstBytesReceived$)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:h})=>{if(h==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let c=this.player.getStreams(),p=this.player.getCodecs();if(EB(c,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let b=[];for(let S of c.audio){b.push(sd(S));let g=[];for(let T of S.representations){let E=AT(T);g.push(E),this.audioTracksMap.set(E,{stream:S,representation:T})}this.audioStreamsMap.set(S,g)}this.params.output.availableAudioStreams$.next(b)}let f=[];for(let b of c.video){f.push(nd(b));let S=[];for(let g of b.representations){let T=fs({...g,streamId:b.id});T&&(S.push(T),this.videoTracksMap.set(T,{stream:b,representation:g}))}this.videoStreamsMap.set(b,S)}this.params.output.availableVideoStreams$.next(f);for(let b of c.text)for(let S of b.representations){let g=PT(b,S);this.textTracksMap.set(g,{stream:b,representation:S})}this.params.output.availableVideoTracks$.next(Array.from(this.videoTracksMap.keys())),this.params.output.availableAudioTracks$.next(Array.from(this.audioTracksMap.keys())),this.params.output.isAudioAvailable$.next(!!this.audioTracksMap.size),p?.video&&this.params.output.availableVideoCodecs$.next(p.video),p?.audio&&this.params.output.availableAudioCodecs$.next(p.audio),this.audioTracksMap.size&&this.textTracksMap.size&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else h==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},r));let{vktvAbrThrottle:u}=this.params.tuning.dash,o=u&<(u)||null;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$,AB(this.video,"progress")).pipe(Sd(()=>this.videoTracksMap.size>0)).subscribe(async()=>{let h=this.player.state$.getState(),c=this.player.state$.getTransition();if(h!=="manifest_ready"&&h!=="running"||c||h==="running"&&o&&!o())return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState()),this.selectVideoAudioRepresentations();let{video:p,audio:f}=this.selectedRepresentations;if(!p)return;let b=Ri(this.videoTracksMap.keys(),g=>this.videoTracksMap.get(g)?.representation.id===p.id);FT(b)&&(this.stallsManager.lastVideoTrackSelected=b);let S=this.params.desiredState.autoVideoTrackLimits.getTransition();if(S&&this.params.output.autoVideoTrackLimits$.next(S.to),h==="manifest_ready")await this.player.initRepresentations(p.id,f?.id,this.params.sourceHls);else if(await this.player.switchRepresentation("video",p.id),f){let g=!!t.audioStream.getTransition();await this.player.switchRepresentation("audio",f.id,g)}},r)),this.subscription.add(xB({videoState:this.videoState.stateChangeEnded$,autoVideoTrackState:ws(Fo([t.autoVideoTrackSwitching.getState()]),t.autoVideoTrackSwitching.stateChangeEnded$.pipe(xs(h=>h.to)))}).pipe(xs(({videoState:h,autoVideoTrackState:c})=>h.to!=="stopped"&&c),Es()).subscribe(h=>this.player.setSmartRepresentationSwitch(h))),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:h})=>{this.scene3D&&h&&this.scene3D.pointCameraTo(h.x,h.y)})),this.subscription.add(this.elementSizeManager.subscribe(h=>{this.scene3D&&h&&this.scene3D.setViewportSize(h.width,h.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(Es()).subscribe(h=>{let c=Ri(this.videoTracksMap.entries(),([,{representation:g}])=>g.id===h);if(!c){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[p,{stream:f}]=c,b=this.params.desiredState.videoStream.getTransition();b&&b.to&&b.to.id===f.id&&this.params.desiredState.videoStream.setState(b.to),e.currentVideoTrack$.next(p),e.currentVideoStream$.next(nd(f));let S=this.player.calculateDurationFromSegments();S&&this.params.output.duration$.next(S/1e3)},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(Es()).subscribe(h=>{let c=Ri(this.audioTracksMap.entries(),([,{representation:S}])=>S.id===h);if(!c){e.currentAudioStream$.next(void 0);return}let[p,{stream:f}]=c,b=this.params.desiredState.audioStream.getTransition();b&&b.to&&b.to.id===f.id&&this.params.desiredState.audioStream.setState(b.to),e.currentAudioStream$.next(sd(f))},r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(h=>{if(h?.is3dVideo&&this.params.tuning.spherical?.enabled)try{this.init3DScene(h),e.is3DVideo$.next(!0)}catch(c){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${c}`})}else this.destroy3DScene(),this.params.tuning.spherical?.enabled&&e.is3DVideo$.next(!1)},r)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,r)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,r)),this.textTracksManager.connect(this.video,t,e);let l=t.playbackState.stateChangeStarted$.pipe(xs(({to:h})=>h==="ready"),Es());this.subscription.add(ws(l,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,Fo(["init"])).subscribe(()=>{let h=t.autoVideoTrackSwitching.getState(),p=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:h?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(p)})),this.subscription.add(ws(l,this.player.state$.stateChangeEnded$,Fo(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let d=ws(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Fo(["init"])).pipe(wB(0));this.subscription.add(d.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?ba:ma,t=this.params.tuning.useNewAutoSelectVideoTrack?zn:Wn,i=this.params.tuning.useNewAutoSelectVideoTrack?St:Gn,{desiredState:r,output:s}=this.params,n=r.autoVideoTrackSwitching.getState(),u=r.videoTrack.getState()?.id,o=Ri(this.videoTracksMap.keys(),A=>A.id===u),l=s.currentVideoTrack$.getValue(),d=r.videoStream.getState()??(o&&this.videoTracksMap.get(o)?.stream)??this.videoStreamsMap.size===1?this.videoStreamsMap.keys().next().value:void 0;if(!d)return;let h=Ri(this.videoStreamsMap.keys(),A=>A.id===d.id),c=h&&this.videoStreamsMap.get(h);if(!c)return;let p=ve(this.video.buffered,this.video.currentTime*1e3),f;this.player.isActiveLive$.getValue()?f=this.player.isLowLatency$.getValue()?this.params.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.params.tuning.dashCmafLive.normalizedLiveMinBufferSize:this.player.isLive$.getValue()?f=this.params.tuning.dashCmafLive.normalizedTargetMinBufferSize:f=n?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;let b=(this.video.duration*1e3||1/0)-this.video.currentTime*1e3,S=Math.min(p/Math.min(f,b||1/0),1),g=r.audioStream.getState()??(this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0),T=g?.id&&Ri(this.audioStreamsMap.keys(),A=>A.id===g.id)||this.audioStreamsMap.keys().next().value,E=0;if(T){if(o&&!n){let A=e(o,c,this.audioStreamsMap.get(T)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);E=Math.max(E,A?.bitrate??-1/0)}if(l){let A=e(l,c,this.audioStreamsMap.get(T)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);E=Math.max(E,A?.bitrate??-1/0)}}let y=o;(n||!y)&&(y=i(c,{container:this.elementSizeManager.getValue(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.stallsManager.abrTuningParams,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:E,forwardBufferHealth:S,current:l,visible:this.params.output.elementVisible$.getValue(),history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,stallsVideoMaxQualityLimit:this.stallsManager.videoMaxQualityLimit,stallsPredictedThroughput:this.stallsManager.predictedThroughput,abrLogger:this.params.dependencies.abrLogger}));let w=T&&t(y,c,this.audioStreamsMap.get(T)??[],{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}),k=this.videoTracksMap.get(y)?.representation,$=w&&this.audioTracksMap.get(w)?.representation;k&&$?(this.selectedRepresentations.video=k,this.selectedRepresentations.audio=$):k&&!$&&this.audioTracksMap.size===0&&(this.selectedRepresentations.video=k,this.selectedRepresentations.audio=null)}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){_e(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:OT.DOM,thrown:e}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.stallsManager.destroy(),this.elementSizeManager.destroy(),this.destroy3DScene(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),this.params.output.currentVideoStream$.next(void 0),Ce(this.video),this.tracer.end()}};var As=class extends Di{subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();i(t.timeUpdate$,e.position$),i(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}};import{combine as vd,merge as qT,filter as UT,filterChanged as jT,isNullable as yd,map as HT,ValueSubject as Td,isNonNullable as kB}from"@vkontakte/videoplayer-shared";var Ps=class extends Di{constructor(e){super(e),this.textTracksManager.destroy()}subscribe(){super.subscribe();let e=!1,t=-1,{output:i,observableVideo:r,desiredState:s,connect:n}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canPlayLiveTailBuffer$.next(!0),n(r.timeUpdate$,i.liveBufferTime$),n(this.player.liveSeekableDuration$,i.duration$),n(this.player.liveLatency$,i.liveLatency$);let u=new Td(1);n(r.playbackRateState$,u),this.params.tuning.dashCmafLive.catchupLiveForMutedInactiveTab&&this.subscription.add(i.elementVisible$.pipe(jT()).subscribe(o=>{let l=i.position$.getValue(),d=i.volume$.getValue(),h=!d.volume||d.muted;!o&&!l&&h?e=!0:o&&e&&(this.seek(0),e=!1)})),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(s.isLowLatency.stateChangeEnded$.pipe(HT(o=>o.to)).subscribe(this.player.isLowLatency$)).add(vd({liveBufferTime:i.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(HT(({liveBufferTime:o,liveAvailabilityStartTime:l})=>o&&l?o+l:void 0)).subscribe(i.liveTime$)).add(this.player.liveStreamStatus$.pipe(UT(o=>kB(o))).subscribe(o=>i.isLiveEnded$.next(o!=="active"&&i.position$.getValue()===0))).add(vd({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:qT(r.playbackRateState$,new Td(1))}).pipe(UT(({liveStreamStatus:o,liveDuration:l})=>o==="active"&&!!l)).subscribe(({liveDuration:o,playbackRate:l})=>{let d=i.liveBufferTime$.getValue(),h=i.position$.getValue(),{playbackCatchupSpeedup:c}=this.params.tuning.dashCmafLive.lowLatency;h||l<1-c||this.video.paused||yd(d)||(t=o-d)})).add(vd({time:i.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:qT(r.playbackRateState$,new Td(1))}).pipe(jT((o,l)=>this.player.liveStreamStatus$.getValue()==="active"?o.liveDuration===l.liveDuration:o.time===l.time)).subscribe(({time:o,liveDuration:l,playbackRate:d})=>{let h=i.position$.getValue(),{playbackCatchupSpeedup:c}=this.params.tuning.dashCmafLive.lowLatency;if(!h&&!this.video.paused&&d>=1-c||yd(o)||yd(l))return;let p=-1*(l-o-t);i.position$.next(Math.min(p,0))})).add(this.player.currentLiveTextRepresentation$.subscribe(o=>{if(o){let l=RT(o);this.params.output.availableTextTracks$.next([l])}}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,i=Math.trunc(t/1e3<=Math.abs(this.params.output.duration$.getValue())?t:0);this.player.seekLive(i).then(()=>{this.params.output.position$.next(e/1e3)})}};var QT="X-Playback-Duration",Id=async a=>{let e=await Xe(a),t=await e.text(),i=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t)?.[1];return i?parseInt(i,10):e.headers.has(QT)?parseInt(e.headers.get(QT),10):void 0};import{assertNever as NB,combine as qB,debounce as UB,ErrorCategory as Uo,filter as jB,filterChanged as HB,isNonNullable as zT,isNullable as jo,map as YT,merge as QB,observableFrom as GB,Subscription as WB,ValueSubject as wd,VideoQuality as zB}from"@vkontakte/videoplayer-shared";var xd=C(ul(),1);import{videoSizeToQuality as LB,getExponentialDelay as $B}from"@vkontakte/videoplayer-shared";var MB=a=>{let e=null;if(a.QUALITY&&(e=Ht(a.QUALITY)),!e&&a.RESOLUTION){let[t,i]=a.RESOLUTION.split("x").map(r=>parseInt(r,10));e=LB({width:t,height:i})}return e??null},DB=(a,e)=>{let t=a.split(`
|
|
179
|
+
`),i=[],r=[];for(let s=0;s<t.length;s++){let n=t[s],u=n.match(/^#EXT-X-STREAM-INF:(.+)/),o=n.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!u&&!o)){if(u){let l=(0,xd.default)(u[1].split(",").map(S=>S.split("="))),d=l.QUALITY??`stream-${l.BANDWIDTH}`,h=MB(l),c;l.BANDWIDTH&&(c=parseInt(l.BANDWIDTH,10)/1e3||void 0),!c&&l["AVERAGE-BANDWIDTH"]&&(c=parseInt(l["AVERAGE-BANDWIDTH"],10)/1e3||void 0);let p=l["FRAME-RATE"]?parseFloat(l["FRAME-RATE"]):void 0,f;if(l.RESOLUTION){let[S,g]=l.RESOLUTION.split("x").map(T=>parseInt(T,10));S&&g&&(f={width:S,height:g})}let b=new URL(t[++s],e).toString();h&&i.push({id:d,quality:h,url:b,bandwidth:c,size:f,fps:p})}if(o){let l=(0,xd.default)(o[1].split(",").map(p=>{let f=p.indexOf("=");return[p.substring(0,f),p.substring(f+1)]}).map(([p,f])=>[p,f.replace(/^"|"$/g,"")])),d=l.URI?.replace(/playlist$/,"subtitles.vtt"),h=l.LANGUAGE,c=l.NAME;d&&h&&r.push({type:"internal",id:h,label:c,language:h,url:d,isAuto:!1})}}}if(!i.length)throw new Error("Empty manifest");return{qualityManifests:i,textTracks:r}},CB=a=>new Promise(e=>{setTimeout(()=>{e()},a)}),Ed=0,GT=async(a,e=a,t,i)=>{let s=await(await Xe(a,i)).text();Ed+=1;try{let{qualityManifests:n,textTracks:u}=DB(s,e);return{qualityManifests:n,textTracks:u}}catch{if(Ed<=t.manifestRetryMaxCount)return await CB($B(Ed-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),GT(a,e,t)}return{qualityManifests:[],textTracks:[]}},No=GT;import{isNonNullable as BB,Subscription as VB,throttle as _B,ValueSubject as WT,Subject as OB,ErrorCategory as FB}from"@vkontakte/videoplayer-shared";var qo=class{constructor(e,t,i,r,s){this.subscription=new VB;this.abortControllers={destroy:new X,nextManifest:null};this.prepareUrl=void 0;this.currentTextTrackData=null;this.availableTextTracks$=new WT(null);this.getCurrentTime$=new WT(null);this.error$=new OB;this.params={fetchManifestData:i,sourceUrl:r,downloadThreshold:s},this.subscription.add(e.pipe(_B(1e3)).subscribe(n=>{this.processLiveTime(n)})),this.getCurrentTime$.next(()=>this.currentTextTrackData?this.currentTextTrackData.playlist.segmentStartTime/1e3+t.currentTime:0)}destroy(){this.subscription.unsubscribe(),this.abortControllers.destroy.abort()}async prepare(e){try{let t=new URL(e);t.searchParams.set("enable-subtitles","yes"),this.prepareUrl=t.toString();let{textTracks:i}=await this.fetchManifestData();await this.processTextTracks(i,this.params.sourceUrl)}catch(t){this.error("prepare",t)}}async processTextTracks(e,t){try{let i=await this.parseTextTracks(e,t);i&&(this.currentTextTrackData=i)}catch(i){this.error("processTextTracks",i)}}async parseTextTracks(e,t){for(let i of e){let r=new URL(i.url,t).toString(),n=await(await Xe(r,{signal:this.abortControllers.destroy.signal})).text(),u=this.parsePlaylist(n,r);return{textTrack:i,playlist:u}}}parsePlaylist(e,t){let i={mediaSequence:0,programDateTime:"",segments:[],targetDuration:0,vkPlaybackDuration:0,segmentStartTime:0,vkStartTime:""},r=e.split(`
|
|
180
|
+
`),s=0;for(let n=0;n<r.length;++n){let u=r[n];switch(!0){case u.startsWith("#EXTINF:"):{let o=r[++n],l=new URL(o,t).toString(),d=Number(this.extractPlaylistRowValue("#EXTINF:",u))*1e3;if(i.segments.push({time:{from:s,to:s+d},url:l}),s=s+d,!i.segmentStartTime){let h=new Date(i.vkStartTime).valueOf(),c=new Date(i.programDateTime).valueOf();i.segmentStartTime=c-h}break}case u.startsWith("#EXT-X-TARGETDURATION:"):i.targetDuration=Number(this.extractPlaylistRowValue("#EXT-X-TARGETDURATION:",u));break;case u.startsWith("#EXT-X-MEDIA-SEQUENCE:"):i.mediaSequence=Number(this.extractPlaylistRowValue("#EXT-X-MEDIA-SEQUENCE:",u));break;case u.startsWith("#EXT-X-VK-PLAYBACK-DURATION:"):i.vkPlaybackDuration=Number(this.extractPlaylistRowValue("#EXT-X-VK-PLAYBACK-DURATION:",u));break;case u.startsWith("#EXT-X-PROGRAM-DATE-TIME:"):{let o=this.extractPlaylistRowValue("#EXT-X-PROGRAM-DATE-TIME:",u);i.programDateTime=o;let l=new Date(o);l.setMilliseconds(0),s=l.valueOf();break}case u.startsWith("#EXT-X-VK-START-TIME:"):i.vkStartTime=this.extractPlaylistRowValue("#EXT-X-VK-START-TIME:",u);break}}return i}extractPlaylistRowValue(e,t){switch(e){case"#EXTINF:":return t.substring(e.length,t.length-1);default:return t.substring(e.length)}}processLiveTime(e){if(BB(e)&&this.currentTextTrackData){let{segments:t}=this.currentTextTrackData.playlist,{from:i}=t[0].time,{to:r}=t[t.length-1].time;if(e<i||e>r)return;r-e<this.params.downloadThreshold&&this.fetchNextManifestData();for(let n of t)if(n.time.from<=e&&n.time.to>=e){this.availableTextTracks$.next([{...this.currentTextTrackData.textTrack,url:n.url,isAuto:!0}]);break}}}async fetchNextManifestData(){try{if(this.abortControllers.nextManifest)return;this.abortControllers.nextManifest=new X;let{textTracks:e}=await this.fetchManifestData(),t=await this.parseTextTracks(e,this.params.sourceUrl);this.currentTextTrackData&&t&&(this.currentTextTrackData.playlist.segments=t.playlist.segments)}catch(e){this.error("fetchNextManifestData",e)}finally{this.abortControllers.nextManifest=null}}async fetchManifestData(){let e=this.prepareUrl??this.params.sourceUrl;return await this.params.fetchManifestData(e,{signal:this.abortControllers.destroy.signal})}error(e,t){this.error$.next({id:"[LiveTextManager][HLS_LIVE_CMAF]",category:FB.WTF,thrown:t,message:e})}};var Rs=class{constructor(e){this.subscription=new WB;this.videoState=new F("stopped");this.textTracksManager=null;this.liveTextManager=null;this.manifests$=new wd([]);this.liveOffset=new vi;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(),u=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),P(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||n||u){let d=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(d),this.prepare(),u&&this.params.output.autoVideoTrackLimits$.next(u.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if(r?.to!=="paused"&&l.state==="requested"){this.videoState.startTransitionTo("ready"),this.seek(l.position&&l.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(t){case"ready":i==="ready"?P(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),P(this.params.desiredState.playbackState,"paused")):i==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":i==="paused"?(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.video.paused?this.videoState.setState("paused"):this.video.pause()):r?.to==="playing"&&P(this.params.desiredState.playbackState,"playing");return;case"paused":if(i==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let d=this.liveOffset.getTotalOffset();d>=this.maxSeekBackTime$.getValue()&&(d=0,this.liveOffset.resetTo(d)),this.liveOffset.resume(),this.params.output.position$.next(-d/1e3),this.prepare()}else r?.to==="paused"&&(P(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return NB(t)}};this.params=e,this.video=De(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:zB.INVARIANT,url:this.params.source.url};let t=(i,r)=>No(i,this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},r);this.params.tuning.useHlsLiveNewTextManager?this.liveTextManager=new qo(this.params.output.liveTime$,this.video,t,this.params.source.url,this.params.tuning.hlsLiveNewTextManagerDownloadThreshold):this.textTracksManager=new Ye(e.source.url),t(this.generateLiveUrl()).then(({qualityManifests:i,textTracks:r})=>{i.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:Uo.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),this.liveTextManager?.processTextTracks(r,this.params.source.url),this.manifests$.next([this.masterManifest,...i])}).catch(i=>{this.params.output.error$.next({id:"ExtractHlsQualities",category:Uo.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:i})}),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Se(this.params.source.url)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.maxSeekBackTime$=new wd(e.source.maxSeekBackTime??1/0),this.subscribe()}selectManifest(){let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),r=t.getTransition(),s=r?.to?.id??t.getState()?.id??"master",n=this.manifests$.getValue();if(!n.length)return;let u=i?"master":s;return i&&!r&&t.startTransitionTo(this.masterManifest),n.find(o=>o.id===u)}subscribe(){let{output:e,desiredState:t}=this.params,i=u=>{e.error$.next({id:"HlsLiveProvider",category:Uo.WTF,message:"HlsLiveProvider internal logic error",thrown:u})},r=Ve(this.video);this.subscription.add(()=>r.destroy());let s=(u,o)=>this.subscription.add(u.subscribe(o,i));s(r.ended$,e.endedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentBuffer$),s(r.loadedMetadata$,e.firstBytesEvent$),s(r.loadedMetadata$,e.loadedMetadataEvent$),s(r.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(Be(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(ze(this.video,t.playbackRate,r.playbackRateState$,i)),s(Ke(this.video),e.elementVisible$),this.liveTextManager?(s(this.liveTextManager.getCurrentTime$,this.params.output.getCurrentTime$),s(this.liveTextManager.error$,this.params.output.error$)):this.textTracksManager&&this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),P(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),P(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.liveTextManager&&this.subscription.add(this.liveTextManager.availableTextTracks$.subscribe(u=>{u&&this.params.output.availableTextTracks$.next(u)})),this.subscription.add(this.maxSeekBackTime$.pipe(HB(),YT(u=>-u/1e3)).subscribe(this.params.output.duration$,i)),this.subscription.add(r.loadedMetadata$.subscribe(()=>{let u=this.params.desiredState.seekState.getState(),o=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&zT(l.to)){let h=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let c=this.manifests$.getValue().find(p=>p.id===h);c&&(this.params.output.currentVideoTrack$.next(c),this.params.output.hostname$.next(Se(c.url)))}d&&this.params.desiredState.autoVideoTrackSwitching.setState(d.to),o&&o.from==="changing_manifest"&&this.videoState.setState(o.to),u&&u.state==="requested"&&this.seek(u.position)},i)),this.subscription.add(r.loadedData$.subscribe(()=>{let u=this.video?.getStartDate?.()?.getTime();this.manifestStartTime$.next(u||void 0)},i)),this.subscription.add(qB({startTime:this.manifestStartTime$.pipe(jB(zT)),currentTime:r.timeUpdate$}).subscribe(({startTime:u,currentTime:o})=>this.params.output.liveTime$.next(u+o*1e3),i)),this.subscription.add(this.manifests$.pipe(YT(u=>u.map(({id:o,quality:l,size:d,bandwidth:h,fps:c})=>({id:o,quality:l,size:d,fps:c,bitrate:h})))).subscribe(this.params.output.availableVideoTracks$,i));let n=QB(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,GB(["init"])).pipe(UB(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager?.destroy(),this.liveTextManager?.destroy(),this.params.output.element$.next(void 0),Ce(this.video)}prepare(){let e=this.selectManifest();if(jo(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),r=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){let{max:u,min:o}=t?.to??i??{};for(let[l,d]of[[u,"mq"],[o,"lq"]]){let h=String(parseFloat(l||""));d&&l&&r.searchParams.set(d,h)}}let s=this.params.format==="HLS_LIVE_CMAF"?2:0,n=se(r.toString(),this.liveOffset.getTotalOffset(),s);this.liveTextManager?.prepare(n),this.video.setAttribute("src",n),this.video.load(),Id(n).then(u=>{if(!jo(u))this.maxSeekBackTime$.next(u);else{let o=this.params.source.maxSeekBackTime??this.maxSeekBackTime$.getValue();(jo(o)||!isFinite(o))&&Xe(n).then(l=>l.text()).then(l=>{let d=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(l)?.[1];if(d){let h=new URL(d,n).toString();Id(h).then(c=>{jo(c)||this.maxSeekBackTime$.next(c)})}}).catch(()=>{})}})}playIfAllowed(){_e(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),P(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Uo.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,i=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(i),this.params.output.position$.next(-i/1e3),this.params.output.seekedEvent$.next()}generateLiveUrl(){let e=se(this.params.source.url);if(this.params.tuning.useHlsLiveNewTextManager){let t=new URL(e);t.searchParams.set("enable-subtitles","yes"),e=t.toString()}return e}};import{assertNever as YB,debounce as KB,ErrorCategory as Ad,fromEvent as Pd,isNonNullable as XB,isNullable as JB,map as KT,merge as XT,observableFrom as JT,Subscription as ZB,ValueSubject as eV,VideoQuality as tV}from"@vkontakte/videoplayer-shared";var ks=class{constructor(e){this.subscription=new ZB;this.videoState=new F("stopped");this.manifests$=new eV([]);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),u=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),P(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||n||u){let d=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(d);let{currentTime:h}=this.video;this.prepare(),u&&this.params.output.autoVideoTrackLimits$.next(u.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:h*1e3,forcePrecise:!0});return}switch(r?.to!=="paused"&&l.state==="requested"&&this.seek(l.position),t){case"ready":i==="ready"?P(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused")):i==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":i==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):r?.to==="playing"&&P(this.params.desiredState.playbackState,"playing");return;case"paused":i==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):r?.to==="paused"&&P(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return YB(t)}};this.textTracksManager=new Ye(e.source.url),this.params=e,this.video=De(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:tV.INVARIANT,url:this.params.source.url},this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Se(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.manifestRequested$.next(),No(se(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:t,textTracks:i})=>{this.params.output.manifestReceived$.next(),this.manifests$.next([this.masterManifest,...t]),this.params.tuning.useNativeHLSTextTracks||this.params.desiredState.internalTextTracks.startTransitionTo(i)},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:Ad.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),r=t.getTransition(),s=r?.to?.id??t.getState()?.id??"master",n=this.manifests$.getValue();if(!n.length)return;let u=i?"master":s;return i&&(!r||!r.from)&&t.startTransitionTo(this.masterManifest),n.find(o=>o.id===u)}subscribe(){let{output:e,desiredState:t}=this.params,i=u=>{e.error$.next({id:"HlsProvider",category:Ad.WTF,message:"HlsProvider internal logic error",thrown:u})},r=Ve(this.video);this.subscription.add(()=>r.destroy());let s=(u,o)=>this.subscription.add(u.subscribe(o));if(s(r.timeUpdate$,e.position$),s(r.durationChange$,e.duration$),s(r.ended$,e.endedEvent$),s(r.looped$,e.loopedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentBuffer$),s(r.loadedMetadata$,e.firstBytesEvent$),s(r.loadedMetadata$,e.loadedMetadataEvent$),s(r.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.seeked$,e.seekedEvent$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe(KT(u=>u.to)),this.params.output.playbackState$),this.subscription.add(mt(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(ze(this.video,t.playbackRate,r.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),P(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),P(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i).add(r.loadedMetadata$.subscribe(()=>{let u=this.params.desiredState.seekState.getState(),o=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&XB(l.to)){let p=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let f=this.manifests$.getValue().find(b=>b.id===p);f&&(this.params.output.currentVideoTrack$.next(f),this.params.output.hostname$.next(Se(f.url)))}let h=this.params.desiredState.playbackRate.getState(),c=this.params.output.element$.getValue()?.playbackRate;if(h!==c){let p=this.params.output.element$.getValue();p&&(this.params.desiredState.playbackRate.setState(h),p.playbackRate=h)}d&&this.params.desiredState.autoVideoTrackSwitching.setState(d.to),o&&o.from==="changing_manifest"&&this.videoState.setState(o.to),u.state==="requested"&&this.seek(u.position)},i))),this.params.tuning.changePlaybackStateToPausedWhenEnded&&this.subscription.add(r.ended$.subscribe(()=>{this.videoState.setState("paused"),P(t.playbackState,"paused")})),this.subscription.add(this.manifests$.pipe(KT(u=>u.map(({id:o,quality:l,size:d,bandwidth:h,fps:c})=>({id:o,quality:l,size:d,fps:c,bitrate:h})))).subscribe(this.params.output.availableVideoTracks$,i)),!B.device.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:u}=this.video;this.subscription.add(XT(Pd(u,"addtrack"),Pd(u,"removetrack"),Pd(u,"change"),JT(["init"])).subscribe(()=>{for(let o=0;o<u.length;o++)u[o].mode="hidden"},i))}let n=XT(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,JT(["init"])).pipe(KB(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),Ce(this.video)}prepare(){let e=this.selectManifest();if(JB(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),r=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){let{max:s,min:n}=t?.to??i??{};for(let[u,o]of[[s,"mq"],[n,"lq"]]){let l=String(parseFloat(u||""));o&&u&&r.searchParams.set(o,l)}}this.video.setAttribute("src",r.toString()),this.video.load()}playIfAllowed(){_e(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Ad.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};var tI=C(Wi(),1),Rd=C(sr(),1),iI=C(at(),1);import{assertNever as iV,assertNonNullable as ZT,debounce as rV,ErrorCategory as eI,isHigherOrEqual as aV,isLowerOrEqual as sV,isNonNullable as nV,merge as oV,observableFrom as uV,Subscription as lV,map as cV}from"@vkontakte/videoplayer-shared";var Ls=class{constructor(e){this.subscription=new lV;this.videoState=new F("stopped");this.trackUrls={};this.textTracksManager=new Ye;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),P(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let s=this.params.desiredState.autoVideoTrackLimits.getTransition(),n=this.params.desiredState.videoTrack.getTransition(),u=this.params.desiredState.seekState.getState();if(s&&e!=="ready"&&!n){this.handleQualityLimitTransition(s.to);return}if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(n){let{currentTime:o}=this.video;this.prepare(),u.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:o*1e3,forcePrecise:!0});return}switch(i?.to!=="paused"&&u.state==="requested"&&this.seek(u.position),e){case"ready":t==="ready"?P(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):i?.to==="playing"&&P(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&P(this.params.desiredState.playbackState,"paused");return;default:return iV(e)}};this.params=e,this.video=De(e.container,e.tuning),this.params.output.element$.next(this.video),(0,tI.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,Rd.default)(this.trackUrls).map(({track:t})=>t)),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.desiredState.autoVideoTrackSwitching.setState(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.subscribe()}subscribe(){let{output:e,desiredState:t}=this.params,i=u=>{e.error$.next({id:"MpegProvider",category:eI.WTF,message:"MpegProvider internal logic error",thrown:u})},r=Ve(this.video);this.subscription.add(()=>r.destroy());let s=(u,o)=>this.subscription.add(u.subscribe(o,i));s(r.timeUpdate$,e.position$),s(r.durationChange$,e.duration$),s(r.ended$,e.endedEvent$),s(r.looped$,e.loopedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentBuffer$),s(r.loadedMetadata$,e.firstBytesEvent$),s(r.loadedMetadata$,e.loadedMetadataEvent$),s(r.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.seeked$,e.seekedEvent$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe(cV(u=>u.to)),this.params.output.playbackState$),this.subscription.add(mt(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(ze(this.video,t.playbackRate,r.playbackRateState$,i)),s(Ke(this.video),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),P(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),P(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready");let u=this.params.desiredState.videoTrack.getTransition();if(u&&nV(u.to)){this.params.desiredState.videoTrack.setState(u.to),this.params.output.currentVideoTrack$.next(this.trackUrls[u.to.id].track);let o=this.params.desiredState.playbackRate.getState(),l=this.params.output.element$.getValue()?.playbackRate;if(o!==l){let d=this.params.output.element$.getValue();d&&(this.params.desiredState.playbackRate.setState(o),d.playbackRate=o)}}this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.params.tuning.changePlaybackStateToPausedWhenEnded&&this.subscription.add(r.ended$.subscribe(()=>{this.videoState.setState("paused"),P(t.playbackState,"paused")})),this.textTracksManager.connect(this.video,t,e);let n=oV(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,uV(["init"])).pipe(rV(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.params.output.element$.next(void 0),Ce(this.video)}prepare(){let e=this.params.desiredState.videoTrack.getState()?.id;ZT(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];ZT(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=Yt(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(Se(t))}playIfAllowed(){_e(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:eI.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){this.params.output.autoVideoTrackLimits$.next(e);let t=l=>{this.params.output.currentVideoTrack$.next(l),this.params.desiredState.videoTrack.startTransitionTo(l)},i=l=>{let d=St(n,{container:this.video.getBoundingClientRect(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:0,limits:l,abrLogger:this.params.dependencies.abrLogger});t(d)},r=this.params.output.currentVideoTrack$.getValue()?.quality,s=!!(e.max||e.min),n=(0,Rd.default)(this.trackUrls).map(l=>l.track);if(!r||!s||or(e,n[0].quality,(0,iI.default)(n,-1)?.quality)){i();return}let u=e.max?sV(r,e.max):!0,o=e.min?aV(r,e.min):!0;u&&o||i(e)}};import{assertNever as aI,debounce as fV,merge as sI,observableFrom as mV,Subscription as bV,map as nI,ValueSubject as gV,ErrorCategory as Ld,VideoQuality as SV}from"@vkontakte/videoplayer-shared";import{ErrorCategory as dV}from"@vkontakte/videoplayer-shared";var rI=["stun:videostun.mycdn.me:80"],pV=1e3,hV=3,kd=()=>null,Ho=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=kd;this.externalStopCallback=kd;this.externalErrorCallback=kd;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:rI}]};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:dV.WTF,message:e.message})}async onPeerConnectionStream(e){let t=e.streams[0];this.stream&&this.stream.id===t.id||(this.stream=t,this.externalStartCallback(this.stream))}onPeerConnectionIceCandidate(e){e.candidate&&this.send({type:this.signalingType,inviteType:"CANDIDATE",candidate:e.candidate})}onPeerConnectionIceConnectionStateChange(){if(this.peerConnection){let e=this.peerConnection.iceConnectionState;["failed","closed"].indexOf(e)>-1&&(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():(this.closeConnections(),this.scheduleRetry()))}}async createOffer(){let e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");let t=await this.peerConnection.createOffer(e),i=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(i))throw new Error("No h264 codec support error");return t}handleRTCError(e){try{this.externalErrorCallback(e||new Error("RTC connection error"))}catch(t){this.handleSystemError(t)}}handleNetworkError(){try{this.externalErrorCallback(new Error("Network error"))}catch(e){this.handleSystemError(e)}}send(e){this.ws&&this.ws.send(JSON.stringify(e))}parseMessage(e){try{return JSON.parse(e)}catch{throw new Error("Can not parse socket message")}}closeConnections(){let e=this.ws;e&&(this.ws=null,e.close(1e3)),this.removePeerConnection()}removePeerConnection(){let e=this.peerConnection;e&&(this.peerConnection=null,e.close(),e.ontrack=null,e.onicecandidate=null,e.oniceconnectionstatechange=null,e=null)}scheduleRetry(){this.retryTimeout=setTimeout(this.connectWS.bind(this),pV)}normalizeOptions(e={}){let t={stunServerList:rI,maxRetryNumber:hV,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 F("stopped");this.maxSeekBackTime$=new gV(0);this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.pause(),this.video.srcObject=null,this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),P(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let s=this.params.desiredState.videoTrack.getTransition();if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s){this.prepare();return}switch(e){case"ready":t==="paused"?(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):i?.to==="playing"&&P(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&P(this.params.desiredState.playbackState,"paused");return;default:return aI(e)}};this.subscription=new bV,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=De(e.container,e.tuning),this.liveStreamClient=new Ho(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:Ld.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};this.subscription.add(sI(this.videoState.stateChangeStarted$.pipe(nI(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe(nI(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:u})=>{this.log({message:`[videoState change] ${u}: ${JSON.stringify(n)}`})}));let r=Ve(this.video);this.subscription.add(()=>r.destroy());let s=(n,u)=>this.subscription.add(n.subscribe(u,i));s(r.timeUpdate$,e.liveTime$),s(r.ended$,e.endedEvent$),s(r.looped$,e.loopedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentBuffer$),s(Ke(this.video),this.params.output.elementVisible$),this.subscription.add(r.durationChange$.subscribe(n=>{e.duration$.next(n===1/0?0:n)})).add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused")},i)).add(r.playing$.subscribe(()=>{this.videoState.setState("playing")},i)).add(r.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(Be(this.video,t.volume,r.volumeState$,i)).add(r.volumeState$.subscribe(e.volume$,i)).add(this.videoState.stateChangeEnded$.subscribe(n=>{switch(n.to){case"stopped":e.position$.next(0),e.duration$.next(0),t.playbackState.setState("stopped");break;case"ready":break;case"paused":t.playbackState.setState("paused");break;case"playing":t.playbackState.setState("playing");break;default:return aI(n.to)}},i)).add(sI(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,mV(["init"])).pipe(fV(0)).subscribe(this.syncPlayback.bind(this),i)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),i))}onLiveStreamStart(e){this.params.output.element$.next(this.video),this.params.output.duration$.next(0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(Se(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.currentVideoTrack$.next({id:"webrtc",quality:SV.INVARIANT}),this.video.srcObject=e,P(this.params.desiredState.playbackState,"playing")}onLiveStreamStop(){this.videoState.startTransitionTo("stopped"),this.syncPlayback(),this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.params.output.endedEvent$.next()}onLiveStreamError(e){this.onLiveStreamStop(),this.params.output.error$.next({id:"WebRTC stream runtime error",category:Ld.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){_e(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Ld.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var Dr=class{constructor(e){this.length=e.length,this.iterator=e[Symbol.iterator](),this.next()}next(){this.current=this.iterator.next(),this.index=this.index===void 0?0:this.index+1}getValue(){if(this.current.done)throw new Error("Iterable is completed");return this.current.value}isCompleted(){return!!this.current.done}isLast(){return this.index===this.length-1}};import{assertNever as Ms,assertNonNullable as ti,ErrorCategory as Qo,filter as pI,isNonNullable as hI,isNullable as wV,map as AV,merge as PV,once as RV,Subject as ne,Subscription as fI,ValueSubject as _,flattenObject as $d}from"@vkontakte/videoplayer-shared";import{Observable as vV,map as oI,Subscription as yV,Subject as TV}from"@vkontakte/videoplayer-shared";var uI=a=>new vV(e=>{let t=new yV,i=a.desiredPlaybackState$.stateChangeStarted$.pipe(oI(({from:l,to:d})=>`${l}-${d}`)),r=a.desiredPlaybackState$.stateChangeEnded$,s=a.providerChanged$.pipe(oI(({type:l})=>l!==void 0)),n=new TV,u=0,o="unknown";return t.add(i.subscribe(l=>{u&&window.clearTimeout(u),o=l,u=window.setTimeout(()=>n.next(l),a.maxTransitionInterval)})),t.add(r.subscribe(()=>{window.clearTimeout(u),o="unknown",u=0})),t.add(s.subscribe(l=>{u&&(window.clearTimeout(u),u=0,l&&(u=window.setTimeout(()=>n.next(o),a.maxTransitionInterval)))})),t.add(n.subscribe(e)),()=>{window.clearTimeout(u),t.unsubscribe()}});import{ErrorCategory as IV,Subscription as EV,combine as xV,filter as cI,once as dI}from"@vkontakte/videoplayer-shared";function lI(){return new(window.AudioContext||window.webkitAudioContext)}var Cr=class a{constructor(e,t,i,r){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=i;this.volumeMultiplier=r;this.destroyController=new X;this.subscriptions=new EV;this.audioContext=null;this.gainNode=null;this.mediaElementSource=null;this.subscriptions.add(this.provider$.pipe(cI(s=>!!s.type),dI()).subscribe(({type:s})=>this.subscribe(s)))}static{this.errorId="VolumeMultiplierManager"}subscribe(e){B.browser.isSafari&&e!=="MPEG"||this.subscriptions.add(xV({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe(cI(({playbackState:t,video:i,volume:{muted:r,volume:s}})=>t==="playing"&&!!i&&!r&&!!s),dI()).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=lI();this.audioContext=i;let r=i.createGain();if(this.gainNode=r,r.gain.value=t,r.connect(i.destination),i.state==="suspended"&&(await i.resume(),this.destroyController.signal.aborted))return!1;let s=i.createMediaElementSource(e);return this.mediaElementSource=s,s.connect(r),!0}cleanup(){this.mediaElementSource&&(this.mediaElementSource.disconnect(),this.mediaElementSource=null),this.gainNode&&(this.gainNode.disconnect(),this.gainNode=null),this.audioContext&&(this.audioContext.state!=="closed"&&this.audioContext.close(),this.audioContext=null)}destroy(){this.destroyController.abort(),this.subscriptions.unsubscribe(),this.cleanup()}handleError(e){this.volumeMultiplierError$.next({id:a.errorId,category:IV.VIDEO_PIPELINE,message:e?.message??`${a.errorId} exception`,thrown:e})}};var kV={chunkDuration:5e3,maxParallelRequests:5},Ds=class{constructor(e){this.current$=new _({type:void 0});this.providerError$=new ne;this.noAvailableProvidersError$=new ne;this.volumeMultiplierError$=new ne;this.providerOutput={position$:new _(0),duration$:new _(1/0),volume$:new _({muted:!1,volume:1}),availableVideoStreams$:new _([]),currentVideoStream$:new _(void 0),availableVideoTracks$:new _([]),currentVideoTrack$:new _(void 0),availableVideoCodecs$:new _([]),availableAudioStreams$:new _([]),currentAudioStream$:new _(void 0),availableAudioTracks$:new _([]),availableAudioCodecs$:new _([]),currentVideoSegmentLength$:new _(0),currentAudioSegmentLength$:new _(0),isAudioAvailable$:new _(!0),autoVideoTrackLimitingAvailable$:new _(!1),autoVideoTrackLimits$:new _(void 0),currentBuffer$:new _(void 0),isBuffering$:new _(!0),error$:new ne,fetcherError$:new ne,fetcherRecoverableError$:new ne,warning$:new ne,willSeekEvent$:new ne,soundProhibitedEvent$:new ne,seekedEvent$:new ne,loopedEvent$:new ne,endedEvent$:new ne,manifestRequested$:new ne,manifestReceived$:new ne,firstBytesRequested$:new ne,firstBytesReceived$:new ne,firstBytesEvent$:new ne,loadedMetadataEvent$:new ne,firstFrameEvent$:new ne,canplay$:new ne,isLive$:new _(void 0),isLiveEnded$:new _(null),canPlayLiveTailBuffer$:new _(!1),isLowLatency$:new _(!1),canChangePlaybackSpeed$:new _(!0),liveTime$:new _(void 0),liveBufferTime$:new _(void 0),liveLatency$:new _(void 0),severeStallOccurred$:new ne,availableTextTracks$:new _([]),currentTextTrack$:new _(void 0),hostname$:new _(void 0),httpConnectionType$:new _(void 0),httpConnectionReused$:new _(void 0),inPiP$:new _(!1),inFullscreen$:new _(!1),element$:new _(void 0),elementVisible$:new _(!0),availableSources$:new _(void 0),is3DVideo$:new _(!1),playbackState$:new _(""),getCurrentTime$:new _(null)};this.subscription=new fI;this.volumeMultiplierManager=null;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer"),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name);let t=Yl([...sT(this.params.tuning),...aT(this.params.tuning)]).filter(l=>hI(e.sources[l])),{forceFormat:i,formatsToAvoid:r}=this.params.tuning,s=[];i?s=[i]:r.length?s=[...t.filter(l=>!(0,Md.default)(r,l)),...t.filter(l=>(0,Md.default)(r,l))]:s=t,this.log({message:`Selected formats: ${s.join(" > ")}`}),this.tracer.log("Selected formats",$d(s)),this.screenFormatsIterator=new Dr(s);let n=[...Uc(!0),...Uc(!1)];this.chromecastFormatsIterator=new Dr(n.filter(l=>hI(e.sources[l]))),this.providerOutput.availableSources$.next(e.sources);let{volumeMultiplier:u=1,tuning:{useVolumeMultiplier:o}}=this.params;o&&u!==1&&Cr.isSupported()&&(this.volumeMultiplierManager=new Cr(this.providerOutput,this.current$,this.volumeMultiplierError$,u))}init(){this.subscription.add(this.initProviderErrorHandling()).add(this.params.dependencies.chromecastInitializer.connection$.subscribe(()=>{this.reinitProvider()})).add(this.providerOutput.availableVideoCodecs$.subscribe(e=>{!this.videoCodecsIterator&&e.length>1&&(this.videoCodecsIterator=new Dr(e))}))}destroy(){this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe(),this.volumeMultiplierManager?.destroy(),this.volumeMultiplierManager=null,this.tracer.end()}initProvider(){let e=this.chooseDestination(),t=this.chooseFormat(e);if(wV(t)){this.handleNoFormatsError(e);return}let i;try{i=this.createProvider(e,t)}catch(r){this.providerError$.next({id:"ProviderNotConstructed",category:Qo.WTF,message:"Failed to create provider",thrown:r})}i?this.current$.next({type:t,provider:i,destination:e}):this.current$.next({type:void 0})}reinitProvider(){this.tracer.log("reinitProvider"),this.destroyProvider(),this.initProvider()}switchToNextProvider(e){this.tracer.log("switchToNextProvider",{destination:e}),this.destroyProvider(),this.failoverIndex=void 0,this.skipFormat(e),this.initProvider()}switchToNextVideoCodec(){this.params.tuning.dash.codecsPrioritizeEnabled&&!this.videoCodecsIterator.isLast()&&(this.tracer.log("switchToNextVideoCodec"),this.destroyProvider(),this.videoCodecsIterator.next(),this.initProvider())}destroyProvider(){let e=this.current$.getValue().provider;if(!e)return;this.log({message:"destroyProvider"}),this.tracer.log("destroyProvider"),e.destroy();let t=this.providerOutput.position$.getValue()*1e3,i=this.params.desiredState.seekState.getState(),r=i.state!=="none";if(this.params.desiredState.seekState.setState({state:"requested",position:r?i.position:t,forcePrecise:r?i.forcePrecise:!1}),e.scene3D){let n=e.scene3D.getCameraRotation();this.params.desiredState.cameraOrientation.setState({x:n.x,y:n.y})}let s=this.providerOutput.isBuffering$;s.getValue()||s.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),this.tracer.log("createProvider",{destination:e,format:t}),e){case"SCREEN":return this.createScreenProvider(t);case"CHROMECAST":return this.createChromecastProvider(t);default:return Ms(e)}}createScreenProvider(e){let{sources:t,container:i,desiredState:r,panelSize:s}=this.params,n=this.providerOutput,u={container:i,source:null,desiredState:r,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning,panelSize:s};switch(e){case"DASH_SEP":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_ONDEMAND":case"DASH_STREAMS":{let o=this.applyFailoverHost(t[e]),l=this.applyFailoverHost(t.HLS_ONDEMAND||t.HLS);return ti(o),this.params.tuning.useNewDashProvider?new As({...u,source:o,sourceHls:l,forceVideoCodec:this.videoCodecsIterator?.getValue()}):new ps({...u,source:o,sourceHls:l,forceVideoCodec:this.videoCodecsIterator?.getValue()})}case"DASH_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return ti(o),this.params.tuning.useNewDashProvider?new Ps({...u,source:o}):new hs({...u,source:o})}case"HLS":case"HLS_ONDEMAND":case"HLS_FMP4":{let o=this.applyFailoverHost(t[e]);return ti(o),new ks({...u,source:o})}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return ti(o),new Rs({...u,source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case"MPEG":{let o=this.applyFailoverHost(t[e]);return ti(o),new Ls({...u,source:o})}case"DASH_LIVE":{let o=this.applyFailoverHost(t[e]);return ti(o),new JS({...u,source:o,config:{...kV,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case"WEB_RTC_LIVE":{let o=this.applyFailoverHost(t[e]);return ti(o),new $s({container:i,source:o,desiredState:r,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return Ms(e)}}createChromecastProvider(e){let{sources:t,container:i,desiredState:r,meta:s}=this.params,n=this.providerOutput,u=this.params.dependencies.chromecastInitializer.connection$.getValue();return ti(u),new ca({connection:u,meta:s,container:i,source:t,format:e,desiredState:r,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?"CHROMECAST":"SCREEN"}chooseFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case"CHROMECAST":return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return Ms(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return Ms(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 Ms(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,bI.default)((0,mI.default)(e).map(([r,s])=>[r,i(s)]))}initProviderErrorHandling(){let e=new fI,t=!1,i=0;return e.add(PV(this.providerOutput.error$.pipe(pI(r=>!this.params.tuning.ignoreAudioRendererError||!r.message||!/AUDIO_RENDERER_ERROR/ig.test(r.message))),uI({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(AV(r=>({id:`ProviderHangup:${r}`,category:Qo.WTF,message:`A ${r} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.providerOutput.fetcherError$.subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;let r=this.params.desiredState.playbackState.transitionEnded$.pipe(pI(({to:s})=>s==="playing"),RV()).subscribe(()=>t=!0);e.add(r)})),e.add(this.providerError$.subscribe(r=>{let s=this.current$.getValue().destination,n={error:r,currentDestination:s};if(s==="CHROMECAST")this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider("SCREEN"),()=>this.params.dependencies.chromecastInitializer.disconnect());else{let u=r.category===Qo.NETWORK,o=r.category===Qo.FATAL,l=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),d=i<this.params.tuning.providerErrorLimit&&!o,h=this.videoCodecsIterator&&!this.videoCodecsIterator.isLast()&&this.params.tuning.dash.codecsPrioritizeEnabled,c=l&&!o&&(u&&t||!d);n={...n,isNetworkError:u,isFatalError:o,haveFailoverHost:l,tryFailover:c,canReinitProvider:d},d?(i++,this.reinitProvider()):c?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):h?this.switchToNextVideoCodec():(i=0,this.switchToNextProvider(s??"SCREEN"))}r.traceAsLog?this.tracer.log("providerInfo",$d(n)):this.tracer.error("providerError",$d(n))})),e}};import{fromEvent as Go,once as LV,combine as $V,Subscription as gI,ValueSubject as Dd,map as MV,filter as DV,isNonNullable as Wo,now as Qe,safeStorage as Cd}from"@vkontakte/videoplayer-shared";var CV=5e3,SI="one_video_throughput",vI="one_video_rtt",Cs=window.navigator.connection,yI=()=>{let a=Cs?.downlink;if(Wo(a)&&a!==10)return a*1e3},TI=()=>{let a=Cs?.rtt;if(Wo(a)&&a!==3e3)return a},II=(a,e,t)=>{let i=t*8,r=i/a;return i/(r+e)},Bd=class a{constructor(e){this.subscription=new gI;this.concurrentDownloads=new Set;this.tuningConfig=e;let t=a.load(SI)||(e.useBrowserEstimation?yI():void 0)||CV,i=a.load(vI)??(e.useBrowserEstimation?TI():void 0)??0;if(this.throughput$=new Dd(t),this.rtt$=new Dd(i),this.rttAdjustedThroughput$=new Dd(II(t,i,e.rttPenaltyRequestSize)),this.throughput=Mt.getSmoothedValue(t,-1,e),this.rtt=Mt.getSmoothedValue(i,1,e),e.useBrowserEstimation){let r=()=>{let n=yI();n&&this.throughput.next(n);let u=TI();Wo(u)&&this.rtt.next(u)};Cs&&"onchange"in Cs&&this.subscription.add(Go(Cs,"change").subscribe(r)),r()}this.subscription.add(this.throughput.smoothed$.subscribe(r=>{Cd.set(SI,r.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(r=>{Cd.set(vI,r.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add($V({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(MV(({throughput:r,rtt:s})=>II(r,s,e.rttPenaltyRequestSize)),DV(r=>{let s=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(r-s)/s>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,i=Qe(),r=new gI;switch(this.subscription.add(r),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:r.add(Go(e,"progress").pipe(LV()).subscribe(s=>{t=s.loaded,i=Qe()}));break;case 1:case 0:r.add(Go(e,"loadstart").subscribe(()=>{t=0,i=Qe()}));break}r.add(Go(e,"loadend").subscribe(s=>{if(e.status===200){let n=s.loaded,u=Qe(),o=n-t,l=u-i;this.addRawSpeed(o,l,1)}this.concurrentDownloads.delete(e),r.unsubscribe()}))}trackStream(e,t=!1){let i=e.getReader();if(!i){e.cancel("Could not get reader");return}let r=0,s=Qe(),n=0,u=Qe(),o=d=>{this.concurrentDownloads.delete(e),i.releaseLock(),e.cancel(`Throughput Estimator error: ${d}`).catch(()=>{})},l=async({done:d,value:h})=>{if(d)!t&&this.addRawSpeed(r,Qe()-s,1),this.concurrentDownloads.delete(e);else if(h){if(t){let c=Qe();if(c-u>this.tuningConfig.lowLatency.continuesByteSequenceInterval||c-s>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let f=u-s;f&&this.addRawSpeed(n,f,1,t),n=h.byteLength,s=Qe()}else n+=h.byteLength;u=Qe()}else r+=h.byteLength,n+=h.byteLength,n>=this.tuningConfig.streamMinSampleSize&&Qe()-u>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,Qe()-u,this.concurrentDownloads.size),n=0,u=Qe());await i?.read().then(l,o)}};this.concurrentDownloads.add(e),i?.read().then(l,o)}addRawSpeed(e,t,i=1,r=!1){if(a.sanityCheck(e,t,r)){let s=e*8/t;this.throughput.next(s*i)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,i=!1){let r=e*8/t;return!(!r||!isFinite(r)||r>1e6||r<30||i&&e<1e4||!i&&e<10*1024||!i&&t<=20)}static load(e){let t=Cd.get(e);if(Wo(t))return parseInt(t,10)??void 0}},EI=Bd;import{fillWithDefault as BV,VideoQuality as zo}from"@vkontakte/videoplayer-shared";var xI={configName:["core"],throughputEstimator:{type:"EmaAndMa",emaAlphaSlow:.2,emaAlphaFast:.7,emaAlpha:.45,basisTrendChangeCount:10,changeThreshold:.05,useBrowserEstimation:!0,rttPenaltyRequestSize:1*1024*1024,streamMinSampleSize:10*1024,streamMinSampleTime:300,deviationDepth:20,deviationFactor:.5,lowLatency:{continuesByteSequenceInterval:50,maxLastEvaluationTimeout:300}},autoTrackSelection:{maxBitrateFactorAtEmptyBuffer:4,bitrateFactorAtEmptyBuffer:2.8,minBitrateFactorAtEmptyBuffer:1.5,bitrateAudioFactorAtEmptyBuffer:10,maxBitrateFactorAtFullBuffer:3,bitrateFactorAtFullBuffer:2,minBitrateFactorAtFullBuffer:1,bitrateAudioFactorAtFullBuffer:7,minVideoAudioRatio:5,minAvailableThroughputAudioRatio:5,usePixelRatio:!0,pixelRatioMultiplier:void 0,pixelRatioLogBase:3,pixelRatioLogCoefficients:[1,0,1],limitByContainer:!0,maxContainerSizeFactor:2,containerSizeFactor:1.3,minContainerSizeFactor:1,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldownIncreaseQuality:15e3,trackCooldownDecreaseQuality:3e3,backgroundVideoQualityLimit:zo.Q_4320P,activeVideoAreaThreshold:.1,highQualityLimit:zo.Q_720P,trafficSavingLimit:zo.Q_480P},stallsManager:{enabled:!1,stallDurationNoDataBeforeQualityDecrease:500,stallDurationToBeCount:100,stallCountBeforeQualityDecrease:3,resetQualityRestrictionTimeout:1e4,ignoreStallsOnSeek:!0,stallsMetricsHistoryLength:5,maxPossibleStallDuration:3e4,minTvtToBeCounted:5,maxTvtToBeCounted:10800,significantTvt:600,targetStallsDurationPerTvt:1,deviationStallsDurationPerTvt:.5,criticalStallsDurationPerTvt:6,abrAdjustingSpeed:.1,emaAlpha:.6,useTotalStallsDurationPerTvt:!0,useAverageStallsDurationPerTvt:!0,useEmaStallsDurationPerTvt:!0},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:zo.Q_480P},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,seekBiasInTheEnd:2e3,maxSegmentDurationLeftToSelectNextSegment:3e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:15e3,crashOnStallTimeout:25e3,crashOnStallTWithoutDataTimeout:5e3,enableSubSegmentBufferFeeding:!0,bufferEmptinessTolerance:100,useNewRepresentationSwitch:!1,useDelayedRepresentationSwitch:!1,useSmartRepresentationSwitch:!1,useFetchPriorityHints:!0,enableBaseUrlSupport:!0,maxSegmentRetryCount:5,sourceOpenTimeout:1e3,vktvAbrThrottle:0,timeupdateEventTickThrottle:300,fetcherBufferOptimisation:!0,codecsPrioritizeEnabled:!1},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},wI=a=>({...BV(a,xI),configName:[...a.configName??[],...xI.configName]});import{assertNonNullable as Yo,combine as Ct,ErrorCategory as Ko,filter as O,filterChanged as Y,fromEvent as _d,isNonNullable as kI,isNullable as UV,Logger as jV,map as W,mapTo as LI,merge as ii,now as Xo,once as N,Subject as G,Subscription as $I,tap as Od,ValueSubject as R,isHigher as HV,isInvariantQuality as MI,flattenObject as ri,throttle as Fd,getTraceSubscriptionMethod as DI,TracerFactory as QV,InternalsExposure as GV}from"@vkontakte/videoplayer-shared";import{merge as VV,map as _V,filter as AI,isNonNullable as OV}from"@vkontakte/videoplayer-shared";var Vd=({seekState:a,position$:e})=>VV(a.stateChangeEnded$.pipe(_V(({to:t})=>t.state==="none"?void 0:(t.position??NaN)/1e3),AI(OV)),e.pipe(AI(()=>a.getState().state==="none")));import{assertNonNullable as FV}from"@vkontakte/videoplayer-shared";var PI=a=>{let e=typeof a.container=="string"?document.getElementById(a.container):a.container;return FV(e,`Wrong container or containerId {${a.container}}`),e};import{filter as NV,once as qV}from"@vkontakte/videoplayer-shared";var RI=(a,e,t,i)=>{a!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&t?.getValue().length===0?t.pipe(NV(r=>r.length>0),qV()).subscribe(r=>{r.find(i)&&e.startTransitionTo(a)}):(a===void 0||t?.getValue().find(i))&&e.startTransitionTo(a)};var Jo=class{constructor(e={configName:[]},t=QV.createRootTracer(!1)){this.subscription=new $I;this.logger=new jV;this.abrLogger=this.logger.createComponentLog("ABR");this.internalsExposure=null;this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new R(!1);this.hasLiveOffsetByPausedTimer=0;this.playerInitRequest=0;this.playerInited=new R(!1);this.wasSetStartedQuality=!1;this.desiredState={playbackState:new F("stopped"),seekState:new F({state:"none"}),volume:new F({volume:1,muted:!1}),videoTrack:new F(void 0),videoStream:new F(void 0),audioStream:new F(void 0),autoVideoTrackSwitching:new F(!0),autoVideoTrackLimits:new F({}),isLooped:new F(!1),isLowLatency:new F(!1),playbackRate:new F(1),externalTextTracks:new F([]),internalTextTracks:new F([]),currentTextTrack:new F(void 0),textTrackCuesSettings:new F({}),cameraOrientation:new F({x:0,y:0})};this.info={playbackState$:new R(void 0),position$:new R(0),duration$:new R(1/0),muted$:new R(!1),volume$:new R(1),availableVideoStreams$:new R([]),currentVideoStream$:new R(void 0),availableQualities$:new R([]),availableQualitiesFps$:new R({}),currentQuality$:new R(void 0),isAutoQualityEnabled$:new R(!0),autoQualityLimitingAvailable$:new R(!1),autoQualityLimits$:new R({}),predefinedQualityLimitType$:new R("unknown"),availableAudioStreams$:new R([]),currentAudioStream$:new R(void 0),availableAudioTracks$:new R([]),isAudioAvailable$:new R(!0),currentPlaybackRate$:new R(1),currentBuffer$:new R({start:0,end:0}),isBuffering$:new R(!0),isStalled$:new R(!1),isEnded$:new R(!1),isLooped$:new R(!1),isLive$:new R(void 0),isLiveEnded$:new R(null),canPlayLiveTailBuffer$:new R(!1),canChangePlaybackSpeed$:new R(void 0),atLiveEdge$:new R(void 0),atLiveDurationEdge$:new R(void 0),liveTime$:new R(void 0),liveBufferTime$:new R(void 0),liveLatency$:new R(void 0),currentFormat$:new R(void 0),availableTextTracks$:new R([]),currentTextTrack$:new R(void 0),throughputEstimation$:new R(void 0),rttEstimation$:new R(void 0),videoBitrate$:new R(void 0),hostname$:new R(void 0),httpConnectionType$:new R(void 0),httpConnectionReused$:new R(void 0),surface$:new R("none"),chromecastState$:new R("NOT_AVAILABLE"),chromecastDeviceName$:new R(void 0),intrinsicVideoSize$:new R(void 0),availableSources$:new R(void 0),is3DVideo$:new R(!1),currentVideoSegmentLength$:new R(0),currentAudioSegmentLength$:new R(0)};this.events={inited$:new 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 R(void 0),tuningConfigName$:new R([]),enableDebugTelemetry$:new R(!1),dumpTelemetry:xS,getCurrentTime$:new R(null)};if(this.initLogs(),this.tuning=wI(e),this.tracer=t,this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new Ks({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new EI(this.tuning.throughputEstimator),e.exposeInternalsToGlobal&&(this.internalsExposure=new GV("CORE"),this.internalsExposure.expose({player:this})),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(i,r,s)=>{let n=Reflect.get(i,r,s);return typeof n!="function"?n:(...u)=>{try{return n.apply(i,u)}catch(o){let l=u.map(c=>JSON.stringify(c,(p,f)=>{let b=typeof f;return(0,CI.default)(["number","string","boolean"],b)?f:f===null?null:`<${b}>`})),d=`Player.${String(r)}`,h=`Exception calling ${d} (${l.join(", ")})`;throw this.events.fatalError$.next({id:d,category:Ko.WTF,message:h,thrown:o}),o}}}})}initVideo(e){this.config=e,this.internalsExposure?.expose({config:e,logger:this.logger,tuning:this.tuning}),this.setMuted(this.tuning.isAudioDisabled);let t=()=>{let{container:s,...n}=e;this.tracer.log("initVideo",ri(n)),this.domContainer=PI(e),this.chromecastInitializer.contentId=e.meta?.videoId,this.providerContainer=new Ds({sources:e.sources,meta:e.meta??{},failoverHosts:e.failoverHosts??[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,tracer:this.tracer,logger:this.logger,abrLogger:this.abrLogger},tuning:this.tuning,volumeMultiplier:e.volumeMultiplier,panelSize:e.panelSize}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.initTracerSubscription(),this.providerContainer.init(),this.setLiveLowLatency(this.tuning.dashCmafLive.lowLatency.isActiveOnDefault),this.initDebugTelemetry(),this.initWakeLock(),this.playerInited.next(!0)},i=()=>{this.tuning.autostartOnlyIfVisible&&window.requestAnimationFrame?this.playerInitRequest=window.requestAnimationFrame(()=>t()):t()},r=()=>{this.tuning.asyncResolveClientChecker?B.isInited$.pipe(O(s=>!!s),N()).subscribe(()=>{console.log("Core SDK async start"),i()}):i()};return this.isNotActiveTabCase()?(this.tracer.log("request play from hidden tab"),_d(document,"visibilitychange").pipe(N()).subscribe(r)):r(),this}destroy(){this.tracer.log("destroy"),window.clearTimeout(this.hasLiveOffsetByPausedTimer),this.playerInitRequest&&window.cancelAnimationFrame(this.playerInitRequest),this.events.willDestruct$.next(),this.stop(),this.providerContainer?.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe(),this.tracer.end(),this.internalsExposure?.destroy()}prepare(){return this.subscription.add(this.playerInited.pipe(O(e=>!!e),N()).subscribe(()=>{let e=this.desiredState.playbackState;this.tracer.log("prepare",{currentPlayBackState:e.getState()}),e.getState()==="stopped"&&e.startTransitionTo("ready")})),this}play(){return this.subscription.add(this.playerInited.pipe(O(e=>!!e),N()).subscribe(()=>{let e=this.desiredState.playbackState;this.tracer.log("play",{currentPlayBackState:e.getState()}),e.getState()!=="playing"&&e.startTransitionTo("playing")})),this}pause(){return this.subscription.add(this.playerInited.pipe(O(e=>!!e),N()).subscribe(()=>{let e=this.desiredState.playbackState;this.tracer.log("pause",{currentPlayBackState:e.getState()}),e.getState()!=="paused"&&e.startTransitionTo("paused")})),this}stop(){return this.subscription.add(this.playerInited.pipe(O(e=>!!e),N()).subscribe(()=>{let e=this.desiredState.playbackState;this.tracer.log("stop",{currentPlayBackState:e.getState()}),e.getState()!=="stopped"&&e.startTransitionTo("stopped")})),this}seekTime(e,t=!0){return this.subscription.add(this.playerInited.pipe(O(i=>!!i),N()).subscribe(()=>{let i=this.info.duration$.getValue(),r=this.info.isLive$.getValue(),s=e;e>=i&&!r&&(s=i-this.tuning.seekNearDurationBias),this.tracer.log("seekTime",{duration:i,isLive:r,time:e,calculatedTime:s,forcePrecise:t}),Number.isFinite(s)&&(this.events.willSeek$.next({from:this.getExactTime(),to:s}),this.desiredState.seekState.setState({state:"requested",position:s*1e3,forcePrecise:t}))})),this}seekPercent(e){return this.subscription.add(this.playerInited.pipe(O(t=>!!t),N()).subscribe(()=>{let t=this.info.duration$.getValue();this.tracer.log("seekPercent",{percent:e,duration:t}),isFinite(t)&&this.seekTime(Math.abs(t)*e,!1)})),this}setVolume(e,t){return this.subscription.add(this.playerInited.pipe(O(i=>!!i),N()).subscribe(()=>{let i=this.desiredState.volume,s=i.getTransition()?.to.muted??this.info.muted$.getValue(),n=t??(this.tuning.isAudioDisabled||s);this.tracer.log("setVolume",{volume:e,isAudioDisabled:this.tuning.isAudioDisabled,chromecastState:this.chromecastInitializer.castState$.getValue(),muted:n}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setVolume(e):i.startTransitionTo({volume:e,muted:n})})),this}setMuted(e,t=!1){return this.subscription.add(this.playerInited.pipe(O(i=>!!i),N()).subscribe(()=>{let i=this.desiredState.volume,r=this.tuning.isAudioDisabled&&!t||e,n=i.getTransition()?.to.volume??this.info.volume$.getValue();this.tracer.log("setMuted",{isMuted:e,nextMuted:r,volume:n,isAudioDisabled:this.tuning.isAudioDisabled,chromecastState:this.chromecastInitializer.castState$.getValue()}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setMuted(r):i.startTransitionTo({volume:n,muted:r})})),this}setVideoStream(e){return this.subscription.add(this.playerInited.pipe(O(t=>!!t),N()).subscribe(()=>{this.desiredState.videoStream.startTransitionTo(e)})),this}setAudioStream(e){return this.subscription.add(this.playerInited.pipe(O(t=>!!t),N()).subscribe(()=>{this.desiredState.audioStream.startTransitionTo(e)})),this}setQuality(e){return this.subscription.add(this.playerInited.pipe(O(t=>!!t),N()).subscribe(()=>{Yo(this.providerContainer);let t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();this.tracer.log("setQuality",{isDelayed:t.length===0,quality:e}),this.desiredState.videoTrack.getState()===void 0&&this.desiredState.videoTrack.getPrevState()===void 0&&t.length===0?this.wasSetStartedQuality?this.providerContainer.providerOutput.availableVideoTracks$.pipe(O(i=>i.length>0),N()).subscribe(i=>{this.setVideoTrackIdByQuality(i,e)}):this.explicitInitialQuality=e:t.length>0&&this.setVideoTrackIdByQuality(t,e)})),this}setAutoQuality(e){return this.subscription.add(this.playerInited.pipe(O(t=>!!t),N()).subscribe(()=>{this.tracer.log("setAutoQuality",{enable:e}),this.desiredState.autoVideoTrackSwitching.startTransitionTo(e)})),this}setAutoQualityLimits(e){return this.subscription.add(this.playerInited.pipe(O(t=>!!t),N()).subscribe(()=>{this.tracer.log("setAutoQualityLimits",ri(e)),this.desiredState.autoVideoTrackLimits.startTransitionTo(e)})),this}setPredefinedQualityLimits(e){return this.subscription.add(this.playerInited.pipe(O(t=>!!t),N()).subscribe(()=>{if(this.info.predefinedQualityLimitType$.getValue()===e)return this;let{highQualityLimit:t,trafficSavingLimit:i}=this.tuning.autoTrackSelection,r;switch(e){case"high_quality":r={min:t,max:void 0};break;case"traffic_saving":r={max:i,min:void 0};break;default:r={max:void 0,min:void 0}}this.setAutoQualityLimits(r)})),this}setPlaybackRate(e){return this.subscription.add(this.playerInited.pipe(O(t=>!!t),N()).subscribe(()=>{Yo(this.providerContainer);let t=this.providerContainer?.providerOutput.element$.getValue();this.tracer.log("setPlaybackRate",{playbackRate:e,isVideoElementAvailable:!!t}),t&&(this.desiredState.playbackRate.setState(e),t.playbackRate=e)})),this}setExternalTextTracks(e){return this.subscription.add(this.playerInited.pipe(O(t=>!!t),N()).subscribe(()=>{e.length&&this.tracer.log("setExternalTextTracks",ri(e)),this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>({type:"external",...t})))})),this}selectTextTrack(e){return this.subscription.add(this.playerInited.pipe(O(t=>!!t),N()).subscribe(()=>{RI(e,this.desiredState.currentTextTrack,this.providerContainer?.providerOutput.availableTextTracks$,t=>t.id===e),this.tracer.log("selectTextTrack",{textTrackId:e})})),this}setTextTrackCueSettings(e){return this.subscription.add(this.playerInited.pipe(O(t=>!!t),N()).subscribe(()=>{this.tracer.log("setTextTrackCueSettings",{...e}),this.desiredState.textTrackCuesSettings.startTransitionTo(e)})),this}setLiveLowLatency(e){let t=this.info.isLive$.getValue(),i=this.desiredState.isLowLatency.getState();return!t||i===e?this:(this.tracer.log("live switch to low latency "+e),this.desiredState.isLowLatency.setState(e),this.seekTime(0))}setLooped(e){return this.subscription.add(this.playerInited.pipe(O(t=>!!t),N()).subscribe(()=>{this.tracer.log("setLooped",{isLooped:e}),this.desiredState.isLooped.startTransitionTo(e)})),this}toggleChromecast(){this.tracer.log("toggleChromecast"),this.chromecastInitializer.toggleConnection()}startCameraManualRotation(e,t){return this.subscription.add(this.playerInited.pipe(O(i=>!!i),N()).subscribe(()=>{let i=this.getScene3D();this.tracer.log("startCameraManualRotation",{isScene3DAvailable:!!i,mx:e,my:t}),i&&i.startCameraManualRotation(e,t)})),this}stopCameraManualRotation(e=!1){return this.subscription.add(this.playerInited.pipe(O(t=>!!t),N()).subscribe(()=>{let t=this.getScene3D();this.tracer.log("stopCameraManualRotation",{isScene3DAvailable:!!t,immediate:e}),t&&t.stopCameraManualRotation(e)})),this}moveCameraFocusPX(e,t){return this.subscription.add(this.playerInited.pipe(O(i=>!!i),N()).subscribe(()=>{let i=this.getScene3D();if(this.tracer.log("moveCameraFocusPX",{isScene3DAvailable:!!i,dxpx:e,dypx:t}),i){let r=i.getCameraRotation(),s=i.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:r.x+s.x,y:r.y+s.y})}})),this}holdCamera(){return this.subscription.add(this.playerInited.pipe(O(e=>e),N()).subscribe(()=>{let e=this.getScene3D();e&&e.holdCamera()})),this}releaseCamera(){return this.subscription.add(this.playerInited.pipe(O(e=>!!e),N()).subscribe(()=>{let e=this.getScene3D();e&&e.releaseCamera()})),this}getExactTime(){if(!this.providerContainer)return 0;let e=this.providerContainer.providerOutput.element$.getValue();if(UV(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),i=t.state==="none"?void 0:t.position;return kI(i)?i/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}getScene3D(){let e=this.providerContainer?.current$.getValue();if(e?.provider?.scene3D)return e.provider.scene3D}setIntrinsicVideoSize(...e){let t={width:e.reduce((i,{width:r})=>i||r||0,0),height:e.reduce((i,{height:r})=>i||r||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add(ii(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(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(uc(e,t,i))})),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(O(({from:e})=>e==="stopped"),N()).subscribe(()=>{this.initedAt=Xo(),this.events.inited$.next()})).add(this.desiredState.playbackState.stateChangeEnded$.subscribe(e=>{switch(e.to){case"ready":this.events.ready$.next();break;case"playing":this.isPlaybackStarted||this.events.started$.next(),this.isPlaybackStarted=!0,this.events.playing$.next();break;case"paused":this.events.paused$.next();break;case"stopped":this.events.stopped$.next()}})).add(this.desiredState.playbackState.stateChangeStarted$.subscribe(e=>{switch(e.to){case"ready":this.events.willReady$.next();break;case"paused":this.events.willPause$.next();break;case"playing":this.isPlaybackStarted?this.events.willResume$.next():this.events.willStart$.next();break;case"stopped":this.events.willStop$.next();break;default:}}))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();this.tracer.log("willSeekEvent",ri(n)),n.state==="requested"?this.desiredState.seekState.setState({...n,state:"applying"}):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:Ko.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.soundProhibitedEvent$.pipe(N()).subscribe(this.events.autoplaySoundProhibited$)).add(e.providerOutput.severeStallOccurred$.subscribe(this.events.severeStallOccured$)).add(e.providerOutput.seekedEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();this.tracer.log("seekedEvent",ri(n)),n.state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe(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(Ct({availableVideoTracks:e.providerOutput.availableVideoTracks$,currentVideoStream:e.providerOutput.currentVideoStream$}).pipe(W(({availableVideoTracks:n,currentVideoStream:u})=>n.filter(o=>u?u.id===o.streamId:!0).map(({quality:o})=>o).sort((o,l)=>MI(o)?1:MI(l)?-1:HV(l,o)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(n=>{let u={};for(let o of n)o.fps&&(u[o.quality]=o.fps);this.info.availableQualitiesFps$.next(u)})).add(e.providerOutput.availableAudioStreams$.subscribe(this.info.availableAudioStreams$)).add(e.providerOutput.currentVideoStream$.subscribe(this.info.currentVideoStream$)).add(e.providerOutput.currentAudioStream$.subscribe(this.info.currentAudioStream$)).add(e.providerOutput.availableAudioTracks$.subscribe(this.info.availableAudioTracks$)).add(e.providerOutput.isAudioAvailable$.pipe(Y()).subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.pipe(O(n=>kI(n))).subscribe(n=>{this.info.currentQuality$.next(n?.quality),this.info.videoBitrate$.next(n?.bitrate)})).add(e.providerOutput.currentVideoSegmentLength$.pipe(Y((n,u)=>Math.round(n)===Math.round(u))).subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.pipe(Y((n,u)=>Math.round(n)===Math.round(u))).subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe(Y()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(Y()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(Y()).subscribe(this.info.httpConnectionReused$)).add(e.providerOutput.currentTextTrack$.subscribe(this.info.currentTextTrack$)).add(e.providerOutput.availableTextTracks$.subscribe(this.info.availableTextTracks$)).add(e.providerOutput.autoVideoTrackLimitingAvailable$.subscribe(this.info.autoQualityLimitingAvailable$)).add(e.providerOutput.autoVideoTrackLimits$.subscribe(n=>{this.desiredState.autoVideoTrackLimits.setState(n??{})})).add(e.providerOutput.currentBuffer$.pipe(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(Od(n=>n&&this.stop())).subscribe(this.info.isLiveEnded$)).add(e.providerOutput.canPlayLiveTailBuffer$.subscribe(this.info.canPlayLiveTailBuffer$)).add(e.providerOutput.canChangePlaybackSpeed$.subscribe(this.info.canChangePlaybackSpeed$)).add(e.providerOutput.liveTime$.subscribe(this.info.liveTime$)).add(e.providerOutput.liveBufferTime$.subscribe(this.info.liveBufferTime$)).add(e.providerOutput.liveLatency$.subscribe(this.info.liveLatency$)).add(Ct({hasLiveOffsetByPaused:ii(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(W(n=>n.to),Y(),W(n=>n==="paused")),isLowLatency:e.providerOutput.isLowLatency$}).subscribe(({hasLiveOffsetByPaused:n,isLowLatency:u})=>{if(window.clearTimeout(this.hasLiveOffsetByPausedTimer),n){this.hasLiveOffsetByPausedTimer=window.setTimeout(()=>{this.hasLiveOffsetByPaused.next(!0)},this.getActiveLiveDelay(u));return}this.hasLiveOffsetByPaused.next(!1)})).add(Ct({atLiveEdge:Ct({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:Vd({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(W(({isLive:n,position:u,isLowLatency:o})=>{let l=this.getActiveLiveDelay(o);return n&&Math.abs(u)<l/1e3}),Y(),Od(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(W(({atLiveEdge:n,hasPausedTimeoutCase:u})=>n&&!u)).subscribe(this.info.atLiveEdge$)).add(Ct({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(W(({isLive:n,position:u,duration:o})=>n&&(Math.abs(o)-Math.abs(u))*1e3<this.tuning.live.activeLiveDelay),Y(),Od(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(W(n=>n.muted),Y()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(W(n=>n.volume),Y()).subscribe(this.info.volume$)).add(Vd({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(ii(e.providerOutput.endedEvent$.pipe(LI(!0)),e.providerOutput.seekedEvent$.pipe(LI(!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:Ko.VIDEO_PIPELINE,message:n?`${n} was forced but failed or not available`:"No suitable providers or all providers failed"}))).subscribe(this.events.fatalError$)).add(e.providerOutput.element$.subscribe(this.experimental.element$)).add(e.providerOutput.getCurrentTime$.subscribe(this.experimental.getCurrentTime$)).add(e.providerOutput.manifestRequested$.pipe(N()).subscribe(this.events.manifestRequested$)).add(e.providerOutput.manifestReceived$.pipe(N()).subscribe(this.events.manifestReceived$)).add(e.providerOutput.firstBytesRequested$.pipe(N()).subscribe(this.events.firstBytesRequested$)).add(e.providerOutput.firstBytesReceived$.pipe(N()).subscribe(this.events.firstBytesReceived$)).add(e.providerOutput.firstBytesEvent$.pipe(N(),W(n=>n??Xo()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe(N(),W(()=>Xo()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(N(),W(()=>Xo()-this.initedAt)).subscribe(this.events.canplay$)).add(this.throughputEstimator.throughput$.subscribe(this.info.throughputEstimation$)).add(this.throughputEstimator.rtt$.subscribe(this.info.rttEstimation$)).add(e.providerOutput.availableSources$.subscribe(this.info.availableSources$));let t=new R(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let i=new R(!0);this.subscription.add(e.current$.subscribe(()=>i.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(O(({to:n})=>n==="playing"),N()).subscribe(()=>i.next(!1)));let r=0,s=ii(e.providerOutput.isBuffering$,t,i).pipe(W(()=>{let n=e.providerOutput.isBuffering$.getValue(),u=t.getValue()||i.getValue();return n&&!u}),Y());this.subscription.add(s.subscribe(n=>{n?r=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(r),this.info.isStalled$.next(!1))})),this.subscription.add(ii(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{let n=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:n?.videoWidth,height:n?.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{let u=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:n?.size?.width,height:n?.size?.height},{width:u?.videoWidth,height:u?.videoHeight})})).add(e.providerOutput.is3DVideo$.subscribe(this.info.is3DVideo$)),this.subscription.add(ii(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,e.providerOutput.elementVisible$,this.chromecastInitializer.castState$).subscribe(()=>{let n=e.providerOutput.inPiP$.getValue(),u=e.providerOutput.inFullscreen$.getValue(),o=e.providerOutput.element$.getValue(),l=e.providerOutput.elementVisible$.getValue(),d=this.chromecastInitializer.castState$.getValue(),h;d==="CONNECTED"?h="second_screen":o?l?n?h="pip":u?h="fullscreen":h="inline":h="invisible":h="none",this.info.surface$.getValue()!==h&&this.info.surface$.next(h)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(W(e=>e?.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){let t=new $I;this.subscription.add(t),this.subscription.add(e.current$.pipe(Y((i,r)=>i.provider===r.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(O(i=>i.length>0),N()).subscribe(i=>{this.setStartingVideoTrack(i)}))}))}setStartingVideoTrack(e){let t;this.wasSetStartedQuality=!0;let i=this.explicitInitialQuality??this.info.currentQuality$.getValue();i&&(t=e.find(({quality:r})=>r===i),t||this.setAutoQuality(!0)),t||(t=St(e,{container:this.domContainer.getBoundingClientRect(),panelSize:this.config.panelSize,estimatedThroughput:this.throughputEstimator.throughput$.getValue(),tuning:this.tuning.autoTrackSelection,limits:this.desiredState.autoVideoTrackLimits.getState(),playbackRate:this.info.currentPlaybackRate$.getValue(),forwardBufferHealth:0,abrLogger:this.abrLogger})),this.desiredState.videoTrack.startTransitionTo(t),this.info.currentQuality$.next(t.quality),this.info.videoBitrate$.next(t.bitrate)}initLogs(){this.subscription.add(ii(this.desiredState.videoTrack.stateChangeStarted$.pipe(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(){let e=this.providerContainer?.providerOutput;Yo(this.providerContainer),Yo(e),ES(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(t=>IS(t)),this.providerContainer.current$.subscribe(({type:t})=>fa("provider",t)),e.duration$.subscribe(t=>fa("duration",t)),e.availableVideoTracks$.pipe(O(t=>!!t.length),N()).subscribe(t=>fa("tracks",t)),this.events.fatalError$.subscribe(new Ae("fatalError")),this.events.managedError$.subscribe(new Ae("managedError")),e.position$.subscribe(new Ae("position")),e.currentVideoTrack$.pipe(W(t=>t?.quality)).subscribe(new Ae("quality")),this.info.currentBuffer$.subscribe(new Ae("buffer")),e.isBuffering$.subscribe(new Ae("isBuffering"))].forEach(t=>this.subscription.add(t)),fa("codecs",B.video.supportedCodecs)}initTracerSubscription(){let e=DI(this.tracer.log.bind(this.tracer)),t=DI(this.tracer.error.bind(this.tracer));this.subscription.add(this.info.playbackState$.subscribe(e("playbackState"))).add(this.info.isLooped$.subscribe(e("isLooped"))).add(this.info.currentPlaybackRate$.pipe(Y()).subscribe(e("currentPlaybackRate"))).add(this.info.isAutoQualityEnabled$.subscribe(e("isAutoQualityEnabled"))).add(this.info.autoQualityLimits$.subscribe(e("autoQualityLimits"))).add(this.info.currentFormat$.subscribe(e("currentFormat"))).add(this.info.availableQualities$.subscribe(e("availableQualities"))).add(this.info.availableQualitiesFps$.subscribe(e("availableQualitiesFps"))).add(this.info.availableAudioTracks$.subscribe(e("availableAudioTracks"))).add(this.info.isAudioAvailable$.subscribe(e("isAudioAvailable"))).add(Ct({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe(O(({currentQuality:i,videoBitrate:r})=>!!i&&!!r),Y((i,r)=>i.currentQuality===r.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe(O(i=>i>0),Y()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe(O(i=>i>0),Y()).subscribe(e("currentAudioSegmentLength"))).add(this.info.hostname$.subscribe(e("hostname"))).add(this.info.currentTextTrack$.subscribe(e("currentTextTrack"))).add(this.info.availableTextTracks$.subscribe(e("availableTextTracks"))).add(this.info.autoQualityLimitingAvailable$.subscribe(e("autoQualityLimitingAvailable"))).add(Ct({currentBuffer:this.info.currentBuffer$.pipe(O(i=>i.end>0),Y((i,r)=>i.end===r.end&&i.start===r.start)),position:this.info.position$.pipe(Y())}).pipe(Fd(1e3)).subscribe(e("currentBufferAndPosition"))).add(this.info.duration$.pipe(Y()).subscribe(e("duration"))).add(this.info.isBuffering$.subscribe(e("isBuffering"))).add(this.info.isLive$.pipe(Y()).subscribe(e("isLive"))).add(this.info.canChangePlaybackSpeed$.pipe(Y()).subscribe(e("canChangePlaybackSpeed"))).add(Ct({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe(O(({liveTime:i,liveBufferTime:r})=>!!i&&!!r),Fd(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe(Y(),O(i=>i===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe(Y(),O(i=>i===!0)).subscribe(e("atLiveDurationEdge"))).add(this.info.muted$.pipe(Y()).subscribe(e("muted"))).add(this.info.volume$.pipe(Y()).subscribe(e("volume"))).add(this.info.isEnded$.pipe(Y(),O(i=>i===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add(Ct({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe(O(({throughputEstimation:i,rtt:r})=>!!i&&!!r),Fd(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe(Y(),O(i=>i===!0)).subscribe(e("is3DVideo"))).add(this.info.surface$.subscribe(e("surface"))).add(this.events.ended$.subscribe(e("ended"))).add(this.events.looped$.subscribe(e("looped"))).add(this.events.managedError$.subscribe(t("managedError"))).add(this.events.fatalError$.subscribe(t("fatalError"))).add(this.events.firstBytes$.subscribe(e("firstBytes"))).add(this.events.firstFrame$.subscribe(e("firstFrame"))).add(this.events.canplay$.subscribe(e("canplay")))}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e,t=()=>{e?.release(),e=void 0},i=async()=>{t(),e=await window.navigator.wakeLock.request("screen").catch(r=>{r instanceof DOMException&&r.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:Ko.DOM,message:String(r)})})};this.subscription.add(ii(_d(document,"visibilitychange"),_d(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{let r=document.visibilityState==="visible",s=this.desiredState.playbackState.getState()==="playing",n=!!e&&!e?.released;r&&s?n||i():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){let i=e.find(r=>r.quality===t);this.tracer.log("setVideoTrackIdByQuality",ri({quality:t,availableTracks:ri(e),track:ri(i),isAutoQuality:!i})),i?this.desiredState.videoTrack.startTransitionTo(i):this.setAutoQuality(!0)}getActiveLiveDelay(e=!1){return e?this.tuning.live.lowLatencyActiveLiveDelay:this.tuning.live.activeLiveDelay}isNotActiveTabCase(){return document.hidden&&this.tuning.autoplayOnlyInActiveTab&&!Ta()}};import{Subscription as gX,Observable as SX,Subject as vX,ValueSubject as yX,VideoQuality as TX}from"@vkontakte/videoplayer-shared";var IX=`@vkontakte/videoplayer-core@${Ud}`;export{js as ChromecastState,tu as HttpConnectionType,SX as Observable,$e as PlaybackState,Jo as Player,Hs as PredefinedQualityLimits,IX as SDK_VERSION,vX as Subject,gX as Subscription,iu as Surface,Ud as VERSION,yX as ValueSubject,xt as VideoFormat,TX as VideoQuality,CL as areValidLiveRecordSources,B as clientChecker,la as isMobile};
|